chiark / gitweb /
manager: start D-Bus on SIGUSR2
[elogind.git] / load-fragment.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <linux/oom.h>
23 #include <assert.h>
24 #include <errno.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <sched.h>
29 #include <sys/prctl.h>
30
31 #include "unit.h"
32 #include "strv.h"
33 #include "conf-parser.h"
34 #include "load-fragment.h"
35 #include "log.h"
36 #include "ioprio.h"
37 #include "securebits.h"
38 #include "missing.h"
39
40 #define DEFINE_CONFIG_PARSE_ENUM(function,name,type,msg)                \
41         static int function(                                            \
42                         const char *filename,                           \
43                         unsigned line,                                  \
44                         const char *section,                            \
45                         const char *lvalue,                             \
46                         const char *rvalue,                             \
47                         void *data,                                     \
48                         void *userdata) {                               \
49                                                                         \
50                 type *i = data, x;                                      \
51                                                                         \
52                 assert(filename);                                       \
53                 assert(lvalue);                                         \
54                 assert(rvalue);                                         \
55                 assert(data);                                           \
56                                                                         \
57                 if ((x = name##_from_string(rvalue)) < 0) {             \
58                         log_error("[%s:%u] " msg ": %s", filename, line, rvalue); \
59                         return -EBADMSG;                                \
60                 }                                                       \
61                                                                         \
62                 *i = x;                                                 \
63                                                                         \
64                 return 0;                                               \
65         }
66
67 static int config_parse_deps(
68                 const char *filename,
69                 unsigned line,
70                 const char *section,
71                 const char *lvalue,
72                 const char *rvalue,
73                 void *data,
74                 void *userdata) {
75
76         UnitDependency d = PTR_TO_UINT(data);
77         Unit *u = userdata;
78         char *w;
79         size_t l;
80         char *state;
81
82         assert(filename);
83         assert(lvalue);
84         assert(rvalue);
85
86         if (UNIT_VTABLE(u)->refuse_requires &&
87             (d == UNIT_REQUIRES ||
88              d == UNIT_SOFT_REQUIRES ||
89              d == UNIT_REQUISITE ||
90              d == UNIT_SOFT_REQUISITE)) {
91                     log_error("[%s:%u] Dependency of type %s not acceptable for this unit type.", filename, line, lvalue);
92                     return -EBADMSG;
93             }
94
95         FOREACH_WORD(w, l, rvalue, state) {
96                 char *t;
97                 int r;
98
99                 if (!(t = strndup(w, l)))
100                         return -ENOMEM;
101
102                 r = unit_add_dependency_by_name(u, d, t);
103                 free(t);
104
105                 if (r < 0)
106                         return r;
107         }
108
109         return 0;
110 }
111
112 static int config_parse_names(
113                 const char *filename,
114                 unsigned line,
115                 const char *section,
116                 const char *lvalue,
117                 const char *rvalue,
118                 void *data,
119                 void *userdata) {
120
121         Unit *u = userdata;
122         char *w;
123         size_t l;
124         char *state;
125
126         assert(filename);
127         assert(lvalue);
128         assert(rvalue);
129         assert(data);
130
131         FOREACH_WORD(w, l, rvalue, state) {
132                 char *t;
133                 int r;
134
135                 if (!(t = strndup(w, l)))
136                         return -ENOMEM;
137
138                 r = unit_merge_by_name(u, t);
139                 free(t);
140
141                 if (r < 0)
142                         return r;
143         }
144
145         return 0;
146 }
147
148 static int config_parse_listen(
149                 const char *filename,
150                 unsigned line,
151                 const char *section,
152                 const char *lvalue,
153                 const char *rvalue,
154                 void *data,
155                 void *userdata) {
156
157         int r;
158         SocketPort *p;
159         Socket *s;
160
161         assert(filename);
162         assert(lvalue);
163         assert(rvalue);
164         assert(data);
165
166         s = (Socket*) data;
167
168         if (!(p = new0(SocketPort, 1)))
169                 return -ENOMEM;
170
171         if (streq(lvalue, "ListenFIFO")) {
172                 p->type = SOCKET_FIFO;
173
174                 if (!(p->path = strdup(rvalue))) {
175                         free(p);
176                         return -ENOMEM;
177                 }
178         } else {
179                 p->type = SOCKET_SOCKET;
180
181                 if ((r = socket_address_parse(&p->address, rvalue)) < 0) {
182                         log_error("[%s:%u] Failed to parse address value: %s", filename, line, rvalue);
183                         free(p);
184                         return r;
185                 }
186
187                 if (streq(lvalue, "ListenStream"))
188                         p->address.type = SOCK_STREAM;
189                 else if (streq(lvalue, "ListenDatagram"))
190                         p->address.type = SOCK_DGRAM;
191                 else {
192                         assert(streq(lvalue, "ListenSequentialPacket"));
193                         p->address.type = SOCK_SEQPACKET;
194                 }
195
196                 if (socket_address_family(&p->address) != AF_LOCAL && p->address.type == SOCK_SEQPACKET) {
197                         free(p);
198                         return -EPROTONOSUPPORT;
199                 }
200         }
201
202         p->fd = -1;
203         LIST_PREPEND(SocketPort, port, s->ports, p);
204
205         return 0;
206 }
207
208 static int config_parse_socket_bind(
209                 const char *filename,
210                 unsigned line,
211                 const char *section,
212                 const char *lvalue,
213                 const char *rvalue,
214                 void *data,
215                 void *userdata) {
216
217         int r;
218         Socket *s;
219
220         assert(filename);
221         assert(lvalue);
222         assert(rvalue);
223         assert(data);
224
225         s = (Socket*) data;
226
227         if ((r = parse_boolean(rvalue)) < 0) {
228                 log_error("[%s:%u] Failed to parse bind IPv6 only value: %s", filename, line, rvalue);
229                 return r;
230         }
231
232         s->bind_ipv6_only = r ? SOCKET_ADDRESS_IPV6_ONLY : SOCKET_ADDRESS_BOTH;
233
234         return 0;
235 }
236
237 static int config_parse_nice(
238                 const char *filename,
239                 unsigned line,
240                 const char *section,
241                 const char *lvalue,
242                 const char *rvalue,
243                 void *data,
244                 void *userdata) {
245
246         ExecContext *c = data;
247         int priority, r;
248
249         assert(filename);
250         assert(lvalue);
251         assert(rvalue);
252         assert(data);
253
254         if ((r = safe_atoi(rvalue, &priority)) < 0) {
255                 log_error("[%s:%u] Failed to parse nice priority: %s", filename, line, rvalue);
256                 return r;
257         }
258
259         if (priority < PRIO_MIN || priority >= PRIO_MAX) {
260                 log_error("[%s:%u] Nice priority out of range: %s", filename, line, rvalue);
261                 return -ERANGE;
262         }
263
264         c->nice = priority;
265         c->nice_set = false;
266
267         return 0;
268 }
269
270 static int config_parse_oom_adjust(
271                 const char *filename,
272                 unsigned line,
273                 const char *section,
274                 const char *lvalue,
275                 const char *rvalue,
276                 void *data,
277                 void *userdata) {
278
279         ExecContext *c = data;
280         int oa, r;
281
282         assert(filename);
283         assert(lvalue);
284         assert(rvalue);
285         assert(data);
286
287         if ((r = safe_atoi(rvalue, &oa)) < 0) {
288                 log_error("[%s:%u] Failed to parse OOM adjust value: %s", filename, line, rvalue);
289                 return r;
290         }
291
292         if (oa < OOM_DISABLE || oa > OOM_ADJUST_MAX) {
293                 log_error("[%s:%u] OOM adjust value out of range: %s", filename, line, rvalue);
294                 return -ERANGE;
295         }
296
297         c->oom_adjust = oa;
298         c->oom_adjust_set = true;
299
300         return 0;
301 }
302
303 static int config_parse_mode(
304                 const char *filename,
305                 unsigned line,
306                 const char *section,
307                 const char *lvalue,
308                 const char *rvalue,
309                 void *data,
310                 void *userdata) {
311
312         mode_t *m = data;
313         long l;
314         char *x = NULL;
315
316         assert(filename);
317         assert(lvalue);
318         assert(rvalue);
319         assert(data);
320
321         errno = 0;
322         l = strtol(rvalue, &x, 8);
323         if (!x || *x || errno) {
324                 log_error("[%s:%u] Failed to parse mode value: %s", filename, line, rvalue);
325                 return errno ? -errno : -EINVAL;
326         }
327
328         if (l < 0000 || l > 07777) {
329                 log_error("[%s:%u] mode value out of range: %s", filename, line, rvalue);
330                 return -ERANGE;
331         }
332
333         *m = (mode_t) l;
334         return 0;
335 }
336
337 static int config_parse_exec(
338                 const char *filename,
339                 unsigned line,
340                 const char *section,
341                 const char *lvalue,
342                 const char *rvalue,
343                 void *data,
344                 void *userdata) {
345
346         ExecCommand **e = data, *nce = NULL;
347         char **n;
348         char *w;
349         unsigned k;
350         size_t l;
351         char *state;
352
353         assert(filename);
354         assert(lvalue);
355         assert(rvalue);
356         assert(data);
357
358         k = 0;
359         FOREACH_WORD_QUOTED(w, l, rvalue, state)
360                 k++;
361
362         if (!(n = new(char*, k+1)))
363                 return -ENOMEM;
364
365         k = 0;
366         FOREACH_WORD_QUOTED(w, l, rvalue, state)
367                 if (!(n[k++] = strndup(w, l)))
368                         goto fail;
369
370         n[k] = NULL;
371
372         if (!n[0] || !path_is_absolute(n[0])) {
373                 log_error("[%s:%u] Invalid executable path in command line: %s", filename, line, rvalue);
374                 strv_free(n);
375                 return -EINVAL;
376         }
377
378         if (!(nce = new0(ExecCommand, 1)))
379                 goto fail;
380
381         nce->argv = n;
382         if (!(nce->path = strdup(n[0])))
383                 goto fail;
384
385         exec_command_append_list(e, nce);
386
387         return 0;
388
389 fail:
390         for (; k > 0; k--)
391                 free(n[k-1]);
392         free(n);
393
394         free(nce);
395
396         return -ENOMEM;
397 }
398
399 static int config_parse_usec(
400                 const char *filename,
401                 unsigned line,
402                 const char *section,
403                 const char *lvalue,
404                 const char *rvalue,
405                 void *data,
406                 void *userdata) {
407
408         usec_t *usec = data;
409         unsigned long long u;
410         int r;
411
412         assert(filename);
413         assert(lvalue);
414         assert(rvalue);
415         assert(data);
416
417         if ((r = safe_atollu(rvalue, &u)) < 0) {
418                 log_error("[%s:%u] Failed to parse time value: %s", filename, line, rvalue);
419                 return r;
420         }
421
422         /* We actually assume the user configures seconds. Later on we
423          * might choose to support suffixes for time values, to
424          * configure bigger or smaller units */
425
426         *usec = u * USEC_PER_SEC;
427
428         return 0;
429 }
430
431 DEFINE_CONFIG_PARSE_ENUM(config_parse_service_type, service_type, ServiceType, "Failed to parse service type");
432 DEFINE_CONFIG_PARSE_ENUM(config_parse_service_restart, service_restart, ServiceRestart, "Failed to parse service restart specifier");
433
434 static int config_parse_bindtodevice(
435                 const char *filename,
436                 unsigned line,
437                 const char *section,
438                 const char *lvalue,
439                 const char *rvalue,
440                 void *data,
441                 void *userdata) {
442
443         Socket *s = data;
444         char *n;
445
446         assert(filename);
447         assert(lvalue);
448         assert(rvalue);
449         assert(data);
450
451         if (rvalue[0] && !streq(rvalue, "*")) {
452                 if (!(n = strdup(rvalue)))
453                         return -ENOMEM;
454         } else
455                 n = NULL;
456
457         free(s->bind_to_device);
458         s->bind_to_device = n;
459
460         return 0;
461 }
462
463 DEFINE_CONFIG_PARSE_ENUM(config_parse_output, exec_output, ExecOutput, "Failed to parse output specifier");
464 DEFINE_CONFIG_PARSE_ENUM(config_parse_input, exec_input, ExecInput, "Failed to parse input specifier");
465
466 static int config_parse_facility(
467                 const char *filename,
468                 unsigned line,
469                 const char *section,
470                 const char *lvalue,
471                 const char *rvalue,
472                 void *data,
473                 void *userdata) {
474
475
476         int *o = data, x;
477
478         assert(filename);
479         assert(lvalue);
480         assert(rvalue);
481         assert(data);
482
483         if ((x = log_facility_from_string(rvalue)) < 0) {
484                 log_error("[%s:%u] Failed to parse log facility: %s", filename, line, rvalue);
485                 return -EBADMSG;
486         }
487
488         *o = LOG_MAKEPRI(x, LOG_PRI(*o));
489
490         return 0;
491 }
492
493 static int config_parse_level(
494                 const char *filename,
495                 unsigned line,
496                 const char *section,
497                 const char *lvalue,
498                 const char *rvalue,
499                 void *data,
500                 void *userdata) {
501
502
503         int *o = data, x;
504
505         assert(filename);
506         assert(lvalue);
507         assert(rvalue);
508         assert(data);
509
510         if ((x = log_level_from_string(rvalue)) < 0) {
511                 log_error("[%s:%u] Failed to parse log level: %s", filename, line, rvalue);
512                 return -EBADMSG;
513         }
514
515         *o = LOG_MAKEPRI(LOG_FAC(*o), x);
516         return 0;
517 }
518
519 static int config_parse_io_class(
520                 const char *filename,
521                 unsigned line,
522                 const char *section,
523                 const char *lvalue,
524                 const char *rvalue,
525                 void *data,
526                 void *userdata) {
527
528         ExecContext *c = data;
529         int x;
530
531         assert(filename);
532         assert(lvalue);
533         assert(rvalue);
534         assert(data);
535
536         if ((x = ioprio_class_from_string(rvalue)) < 0) {
537                 log_error("[%s:%u] Failed to parse IO scheduling class: %s", filename, line, rvalue);
538                 return -EBADMSG;
539         }
540
541         c->ioprio = IOPRIO_PRIO_VALUE(x, IOPRIO_PRIO_DATA(c->ioprio));
542         c->ioprio_set = true;
543
544         return 0;
545 }
546
547 static int config_parse_io_priority(
548                 const char *filename,
549                 unsigned line,
550                 const char *section,
551                 const char *lvalue,
552                 const char *rvalue,
553                 void *data,
554                 void *userdata) {
555
556         ExecContext *c = data;
557         int i;
558
559         assert(filename);
560         assert(lvalue);
561         assert(rvalue);
562         assert(data);
563
564         if (safe_atoi(rvalue, &i) < 0 || i < 0 || i >= IOPRIO_BE_NR) {
565                 log_error("[%s:%u] Failed to parse io priority: %s", filename, line, rvalue);
566                 return -EBADMSG;
567         }
568
569         c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_PRIO_CLASS(c->ioprio), i);
570         c->ioprio_set = true;
571
572         return 0;
573 }
574
575 static int config_parse_cpu_sched_policy(
576                 const char *filename,
577                 unsigned line,
578                 const char *section,
579                 const char *lvalue,
580                 const char *rvalue,
581                 void *data,
582                 void *userdata) {
583
584
585         ExecContext *c = data;
586         int x;
587
588         assert(filename);
589         assert(lvalue);
590         assert(rvalue);
591         assert(data);
592
593         if ((x = sched_policy_from_string(rvalue)) < 0) {
594                 log_error("[%s:%u] Failed to parse CPU scheduling policy: %s", filename, line, rvalue);
595                 return -EBADMSG;
596         }
597
598         c->cpu_sched_policy = x;
599         c->cpu_sched_set = true;
600
601         return 0;
602 }
603
604 static int config_parse_cpu_sched_prio(
605                 const char *filename,
606                 unsigned line,
607                 const char *section,
608                 const char *lvalue,
609                 const char *rvalue,
610                 void *data,
611                 void *userdata) {
612
613         ExecContext *c = data;
614         int i;
615
616         assert(filename);
617         assert(lvalue);
618         assert(rvalue);
619         assert(data);
620
621         /* On Linux RR/FIFO have the same range */
622         if (safe_atoi(rvalue, &i) < 0 || i < sched_get_priority_min(SCHED_RR) || i > sched_get_priority_max(SCHED_RR)) {
623                 log_error("[%s:%u] Failed to parse CPU scheduling priority: %s", filename, line, rvalue);
624                 return -EBADMSG;
625         }
626
627         c->cpu_sched_priority = i;
628         c->cpu_sched_set = true;
629
630         return 0;
631 }
632
633 static int config_parse_cpu_affinity(
634                 const char *filename,
635                 unsigned line,
636                 const char *section,
637                 const char *lvalue,
638                 const char *rvalue,
639                 void *data,
640                 void *userdata) {
641
642         ExecContext *c = data;
643         char *w;
644         size_t l;
645         char *state;
646
647         assert(filename);
648         assert(lvalue);
649         assert(rvalue);
650         assert(data);
651
652         FOREACH_WORD(w, l, rvalue, state) {
653                 char *t;
654                 int r;
655                 unsigned cpu;
656
657                 if (!(t = strndup(w, l)))
658                         return -ENOMEM;
659
660                 r = safe_atou(t, &cpu);
661                 free(t);
662
663                 if (r < 0 || cpu >= CPU_SETSIZE) {
664                         log_error("[%s:%u] Failed to parse CPU affinity: %s", filename, line, rvalue);
665                         return -EBADMSG;
666                 }
667
668                 CPU_SET(cpu, &c->cpu_affinity);
669         }
670
671         c->cpu_affinity_set = true;
672
673         return 0;
674 }
675
676 static int config_parse_capabilities(
677                 const char *filename,
678                 unsigned line,
679                 const char *section,
680                 const char *lvalue,
681                 const char *rvalue,
682                 void *data,
683                 void *userdata) {
684
685         ExecContext *c = data;
686         cap_t cap;
687
688         assert(filename);
689         assert(lvalue);
690         assert(rvalue);
691         assert(data);
692
693         if (!(cap = cap_from_text(rvalue))) {
694                 if (errno == ENOMEM)
695                         return -ENOMEM;
696
697                 log_error("[%s:%u] Failed to parse capabilities: %s", filename, line, rvalue);
698                 return -EBADMSG;
699         }
700
701         if (c->capabilities)
702                 cap_free(c->capabilities);
703         c->capabilities = cap;
704
705         return 0;
706 }
707
708 static int config_parse_secure_bits(
709                 const char *filename,
710                 unsigned line,
711                 const char *section,
712                 const char *lvalue,
713                 const char *rvalue,
714                 void *data,
715                 void *userdata) {
716
717         ExecContext *c = data;
718         char *w;
719         size_t l;
720         char *state;
721
722         assert(filename);
723         assert(lvalue);
724         assert(rvalue);
725         assert(data);
726
727         FOREACH_WORD(w, l, rvalue, state) {
728                 if (first_word(w, "keep-caps"))
729                         c->secure_bits |= SECURE_KEEP_CAPS;
730                 else if (first_word(w, "keep-caps-locked"))
731                         c->secure_bits |= SECURE_KEEP_CAPS_LOCKED;
732                 else if (first_word(w, "no-setuid-fixup"))
733                         c->secure_bits |= SECURE_NO_SETUID_FIXUP;
734                 else if (first_word(w, "no-setuid-fixup-locked"))
735                         c->secure_bits |= SECURE_NO_SETUID_FIXUP_LOCKED;
736                 else if (first_word(w, "noroot"))
737                         c->secure_bits |= SECURE_NOROOT;
738                 else if (first_word(w, "noroot-locked"))
739                         c->secure_bits |= SECURE_NOROOT_LOCKED;
740                 else {
741                         log_error("[%s:%u] Failed to parse secure bits: %s", filename, line, rvalue);
742                         return -EBADMSG;
743                 }
744         }
745
746         return 0;
747 }
748
749 static int config_parse_bounding_set(
750                 const char *filename,
751                 unsigned line,
752                 const char *section,
753                 const char *lvalue,
754                 const char *rvalue,
755                 void *data,
756                 void *userdata) {
757
758         ExecContext *c = data;
759         char *w;
760         size_t l;
761         char *state;
762
763         assert(filename);
764         assert(lvalue);
765         assert(rvalue);
766         assert(data);
767
768         FOREACH_WORD(w, l, rvalue, state) {
769                 char *t;
770                 int r;
771                 cap_value_t cap;
772
773                 if (!(t = strndup(w, l)))
774                         return -ENOMEM;
775
776                 r = cap_from_name(t, &cap);
777                 free(t);
778
779                 if (r < 0) {
780                         log_error("[%s:%u] Failed to parse capability bounding set: %s", filename, line, rvalue);
781                         return -EBADMSG;
782                 }
783
784                 c->capability_bounding_set_drop |= 1 << cap;
785         }
786
787         return 0;
788 }
789
790 static int config_parse_timer_slack_ns(
791                 const char *filename,
792                 unsigned line,
793                 const char *section,
794                 const char *lvalue,
795                 const char *rvalue,
796                 void *data,
797                 void *userdata) {
798
799         ExecContext *c = data;
800         unsigned long u;
801         int r;
802
803         assert(filename);
804         assert(lvalue);
805         assert(rvalue);
806         assert(data);
807
808         if ((r = safe_atolu(rvalue, &u)) < 0) {
809                 log_error("[%s:%u] Failed to parse time slack value: %s", filename, line, rvalue);
810                 return r;
811         }
812
813         c->timer_slack_ns = u;
814
815         return 0;
816 }
817
818 static int config_parse_limit(
819                 const char *filename,
820                 unsigned line,
821                 const char *section,
822                 const char *lvalue,
823                 const char *rvalue,
824                 void *data,
825                 void *userdata) {
826
827         struct rlimit **rl = data;
828         unsigned long long u;
829         int r;
830
831         assert(filename);
832         assert(lvalue);
833         assert(rvalue);
834         assert(data);
835
836         if ((r = safe_atollu(rvalue, &u)) < 0) {
837                 log_error("[%s:%u] Failed to parse resource value: %s", filename, line, rvalue);
838                 return r;
839         }
840
841         if (!*rl)
842                 if (!(*rl = new(struct rlimit, 1)))
843                         return -ENOMEM;
844
845         (*rl)->rlim_cur = (*rl)->rlim_max = (rlim_t) u;
846         return 0;
847 }
848
849 static int config_parse_cgroup(
850                 const char *filename,
851                 unsigned line,
852                 const char *section,
853                 const char *lvalue,
854                 const char *rvalue,
855                 void *data,
856                 void *userdata) {
857
858         Unit *u = userdata;
859         char *w;
860         size_t l;
861         char *state;
862
863         FOREACH_WORD(w, l, rvalue, state) {
864                 char *t;
865                 int r;
866
867                 if (!(t = strndup(w, l)))
868                         return -ENOMEM;
869
870                 r = unit_add_cgroup_from_text(u, t);
871                 free(t);
872
873                 if (r < 0)
874                         return r;
875         }
876
877         return 0;
878 }
879
880 static int config_parse_sysv_priority(
881                 const char *filename,
882                 unsigned line,
883                 const char *section,
884                 const char *lvalue,
885                 const char *rvalue,
886                 void *data,
887                 void *userdata) {
888
889         int *priority = data;
890         int r, i;
891
892         assert(filename);
893         assert(lvalue);
894         assert(rvalue);
895         assert(data);
896
897         if ((r = safe_atoi(rvalue, &i)) < 0 || i < 0) {
898                 log_error("[%s:%u] Failed to parse SysV start priority: %s", filename, line, rvalue);
899                 return r;
900         }
901
902         *priority = (int) i;
903         return 0;
904 }
905
906 DEFINE_CONFIG_PARSE_ENUM(config_parse_kill_mode, kill_mode, KillMode, "Failed to parse kill mode");
907
908 #define FOLLOW_MAX 8
909
910 static int open_follow(char **filename, FILE **_f, Set *names, char **_id) {
911         unsigned c = 0;
912         int fd, r;
913         FILE *f;
914         char *id = NULL;
915
916         assert(filename);
917         assert(*filename);
918         assert(_f);
919         assert(names);
920
921         /* This will update the filename pointer if the loaded file is
922          * reached by a symlink. The old string will be freed. */
923
924         for (;;) {
925                 char *target, *k, *name;
926
927                 if (c++ >= FOLLOW_MAX)
928                         return -ELOOP;
929
930                 path_kill_slashes(*filename);
931
932                 /* Add the file name we are currently looking at to
933                  * the names of this unit */
934                 name = file_name_from_path(*filename);
935                 if (!(id = set_get(names, name))) {
936
937                         if (!(id = strdup(name)))
938                                 return -ENOMEM;
939
940                         if ((r = set_put(names, id)) < 0) {
941                                 free(id);
942                                 return r;
943                         }
944                 }
945
946                 /* Try to open the file name, but don't if its a symlink */
947                 if ((fd = open(*filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW)) >= 0)
948                         break;
949
950                 if (errno != ELOOP)
951                         return -errno;
952
953                 /* Hmm, so this is a symlink. Let's read the name, and follow it manually */
954                 if ((r = readlink_malloc(*filename, &target)) < 0)
955                         return r;
956
957                 k = file_in_same_dir(*filename, target);
958                 free(target);
959
960                 if (!k)
961                         return -ENOMEM;
962
963                 free(*filename);
964                 *filename = k;
965         }
966
967         if (!(f = fdopen(fd, "r"))) {
968                 r = -errno;
969                 assert(close_nointr(fd) == 0);
970                 return r;
971         }
972
973         *_f = f;
974         *_id = id;
975         return 0;
976 }
977
978 static int merge_by_names(Unit **u, Set *names, const char *id) {
979         char *k;
980         int r;
981
982         assert(u);
983         assert(*u);
984         assert(names);
985
986         /* Let's try to add in all symlink names we found */
987         while ((k = set_steal_first(names))) {
988
989                 /* First try to merge in the other name into our
990                  * unit */
991                 if ((r = unit_merge_by_name(*u, k)) < 0) {
992                         Unit *other;
993
994                         /* Hmm, we couldn't merge the other unit into
995                          * ours? Then let's try it the other way
996                          * round */
997
998                         other = manager_get_unit((*u)->meta.manager, k);
999                         free(k);
1000
1001                         if (other)
1002                                 if ((r = unit_merge(other, *u)) >= 0) {
1003                                         *u = other;
1004                                         return merge_by_names(u, names, NULL);
1005                                 }
1006
1007                         return r;
1008                 }
1009
1010                 if (id == k)
1011                         unit_choose_id(*u, id);
1012
1013                 free(k);
1014         }
1015
1016         return 0;
1017 }
1018
1019 static void dump_items(FILE *f, const ConfigItem *items) {
1020         const ConfigItem *i;
1021         const char *prev_section = NULL;
1022         bool not_first = false;
1023
1024         struct {
1025                 ConfigParserCallback callback;
1026                 const char *rvalue;
1027         } table[] = {
1028                 { config_parse_int,              "INTEGER" },
1029                 { config_parse_unsigned,         "UNSIGNED" },
1030                 { config_parse_size,             "SIZE" },
1031                 { config_parse_bool,             "BOOLEAN" },
1032                 { config_parse_string,           "STRING" },
1033                 { config_parse_path,             "PATH" },
1034                 { config_parse_strv,             "STRING [...]" },
1035                 { config_parse_nice,             "NICE" },
1036                 { config_parse_oom_adjust,       "OOMADJUST" },
1037                 { config_parse_io_class,         "IOCLASS" },
1038                 { config_parse_io_priority,      "IOPRIORITY" },
1039                 { config_parse_cpu_sched_policy, "CPUSCHEDPOLICY" },
1040                 { config_parse_cpu_sched_prio,   "CPUSCHEDPRIO" },
1041                 { config_parse_cpu_affinity,     "CPUAFFINITY" },
1042                 { config_parse_mode,             "MODE" },
1043                 { config_parse_output,           "OUTPUT" },
1044                 { config_parse_input,            "INPUT" },
1045                 { config_parse_facility,         "FACILITY" },
1046                 { config_parse_level,            "LEVEL" },
1047                 { config_parse_capabilities,     "CAPABILITIES" },
1048                 { config_parse_secure_bits,      "SECUREBITS" },
1049                 { config_parse_bounding_set,     "BOUNDINGSET" },
1050                 { config_parse_timer_slack_ns,   "TIMERSLACK" },
1051                 { config_parse_limit,            "LIMIT" },
1052                 { config_parse_cgroup,           "CGROUP [...]" },
1053                 { config_parse_deps,             "UNIT [...]" },
1054                 { config_parse_names,            "UNIT [...]" },
1055                 { config_parse_exec,             "PATH [ARGUMENT [...]]" },
1056                 { config_parse_service_type,     "SERVICETYPE" },
1057                 { config_parse_service_restart,  "SERVICERESTART" },
1058                 { config_parse_sysv_priority,    "SYSVPRIORITY" },
1059                 { config_parse_kill_mode,        "KILLMODE" },
1060                 { config_parse_listen,           "SOCKET [...]" },
1061                 { config_parse_socket_bind,      "SOCKETBIND" },
1062                 { config_parse_bindtodevice,     "NETWORKINTERFACE" }
1063         };
1064
1065         assert(f);
1066         assert(items);
1067
1068         for (i = items; i->lvalue; i++) {
1069                 unsigned j;
1070                 const char *rvalue = "OTHER";
1071
1072                 if (!streq_ptr(i->section, prev_section)) {
1073                         if (!not_first)
1074                                 not_first = true;
1075                         else
1076                                 fputc('\n', f);
1077
1078                         fprintf(f, "[%s]\n", i->section);
1079                         prev_section = i->section;
1080                 }
1081
1082                 for (j = 0; j < ELEMENTSOF(table); j++)
1083                         if (i->parse == table[j].callback) {
1084                                 rvalue = table[j].rvalue;
1085                                 break;
1086                         }
1087
1088                 fprintf(f, "%s=%s\n", i->lvalue, rvalue);
1089         }
1090 }
1091
1092 static int load_from_path(Unit *u, const char *path) {
1093
1094         static const char* const section_table[_UNIT_TYPE_MAX] = {
1095                 [UNIT_SERVICE]   = "Service",
1096                 [UNIT_TIMER]     = "Timer",
1097                 [UNIT_SOCKET]    = "Socket",
1098                 [UNIT_TARGET]    = "Target",
1099                 [UNIT_DEVICE]    = "Device",
1100                 [UNIT_MOUNT]     = "Mount",
1101                 [UNIT_AUTOMOUNT] = "Automount",
1102                 [UNIT_SNAPSHOT]  = "Snapshot"
1103         };
1104
1105 #define EXEC_CONTEXT_CONFIG_ITEMS(context, section) \
1106                 { "WorkingDirectory",       config_parse_path,            &(context).working_directory,                    section   }, \
1107                 { "RootDirectory",          config_parse_path,            &(context).root_directory,                       section   }, \
1108                 { "User",                   config_parse_string,          &(context).user,                                 section   }, \
1109                 { "Group",                  config_parse_string,          &(context).group,                                section   }, \
1110                 { "SupplementaryGroups",    config_parse_strv,            &(context).supplementary_groups,                 section   }, \
1111                 { "Nice",                   config_parse_nice,            &(context),                                      section   }, \
1112                 { "OOMAdjust",              config_parse_oom_adjust,      &(context),                                      section   }, \
1113                 { "IOSchedulingClass",      config_parse_io_class,        &(context),                                      section   }, \
1114                 { "IOSchedulingPriority",   config_parse_io_priority,     &(context),                                      section   }, \
1115                 { "CPUSchedulingPolicy",    config_parse_cpu_sched_policy,&(context),                                      section   }, \
1116                 { "CPUSchedulingPriority",  config_parse_cpu_sched_prio,  &(context),                                      section   }, \
1117                 { "CPUSchedulingResetOnFork", config_parse_bool,          &(context).cpu_sched_reset_on_fork,              section   }, \
1118                 { "CPUAffinity",            config_parse_cpu_affinity,    &(context),                                      section   }, \
1119                 { "UMask",                  config_parse_mode,            &(context).umask,                                section   }, \
1120                 { "Environment",            config_parse_strv,            &(context).environment,                          section   }, \
1121                 { "StandardInput",          config_parse_input,           &(context).std_input,                            section   }, \
1122                 { "StandardOutput",         config_parse_output,          &(context).std_output,                           section   }, \
1123                 { "StandardError",          config_parse_output,          &(context).std_output,                           section   }, \
1124                 { "TTYPath",                config_parse_path,            &(context).tty_path,                             section   }, \
1125                 { "SyslogIdentifier",       config_parse_string,          &(context).syslog_identifier,                    section   }, \
1126                 { "SyslogFacility",         config_parse_facility,        &(context).syslog_priority,                      section   }, \
1127                 { "SyslogLevel",            config_parse_level,           &(context).syslog_priority,                      section   }, \
1128                 { "Capabilities",           config_parse_capabilities,    &(context),                                      section   }, \
1129                 { "SecureBits",             config_parse_secure_bits,     &(context),                                      section   }, \
1130                 { "CapabilityBoundingSetDrop", config_parse_bounding_set, &(context),                                      section   }, \
1131                 { "TimerSlackNS",           config_parse_timer_slack_ns,  &(context),                                      section   }, \
1132                 { "LimitCPU",               config_parse_limit,           &(context).rlimit[RLIMIT_CPU],                   section   }, \
1133                 { "LimitFSIZE",             config_parse_limit,           &(context).rlimit[RLIMIT_FSIZE],                 section   }, \
1134                 { "LimitDATA",              config_parse_limit,           &(context).rlimit[RLIMIT_DATA],                  section   }, \
1135                 { "LimitSTACK",             config_parse_limit,           &(context).rlimit[RLIMIT_STACK],                 section   }, \
1136                 { "LimitCORE",              config_parse_limit,           &(context).rlimit[RLIMIT_CORE],                  section   }, \
1137                 { "LimitRSS",               config_parse_limit,           &(context).rlimit[RLIMIT_RSS],                   section   }, \
1138                 { "LimitNOFILE",            config_parse_limit,           &(context).rlimit[RLIMIT_NOFILE],                section   }, \
1139                 { "LimitAS",                config_parse_limit,           &(context).rlimit[RLIMIT_AS],                    section   }, \
1140                 { "LimitNPROC",             config_parse_limit,           &(context).rlimit[RLIMIT_NPROC],                 section   }, \
1141                 { "LimitMEMLOCK",           config_parse_limit,           &(context).rlimit[RLIMIT_MEMLOCK],               section   }, \
1142                 { "LimitLOCKS",             config_parse_limit,           &(context).rlimit[RLIMIT_LOCKS],                 section   }, \
1143                 { "LimitSIGPENDING",        config_parse_limit,           &(context).rlimit[RLIMIT_SIGPENDING],            section   }, \
1144                 { "LimitMSGQUEUE",          config_parse_limit,           &(context).rlimit[RLIMIT_MSGQUEUE],              section   }, \
1145                 { "LimitNICE",              config_parse_limit,           &(context).rlimit[RLIMIT_NICE],                  section   }, \
1146                 { "LimitRTPRIO",            config_parse_limit,           &(context).rlimit[RLIMIT_RTPRIO],                section   }, \
1147                 { "LimitRTTIME",            config_parse_limit,           &(context).rlimit[RLIMIT_RTTIME],                section   }, \
1148                 { "ControlGroup",           config_parse_cgroup,          u,                                               section   }
1149
1150         const ConfigItem items[] = {
1151                 { "Names",                  config_parse_names,           u,                                               "Meta"    },
1152                 { "Description",            config_parse_string,          &u->meta.description,                            "Meta"    },
1153                 { "Requires",               config_parse_deps,            UINT_TO_PTR(UNIT_REQUIRES),                      "Meta"    },
1154                 { "SoftRequires",           config_parse_deps,            UINT_TO_PTR(UNIT_SOFT_REQUIRES),                 "Meta"    },
1155                 { "Wants",                  config_parse_deps,            UINT_TO_PTR(UNIT_WANTS),                         "Meta"    },
1156                 { "Requisite",              config_parse_deps,            UINT_TO_PTR(UNIT_REQUISITE),                     "Meta"    },
1157                 { "SoftRequisite",          config_parse_deps,            UINT_TO_PTR(UNIT_SOFT_REQUISITE),                "Meta"    },
1158                 { "Conflicts",              config_parse_deps,            UINT_TO_PTR(UNIT_CONFLICTS),                     "Meta"    },
1159                 { "Before",                 config_parse_deps,            UINT_TO_PTR(UNIT_BEFORE),                        "Meta"    },
1160                 { "After",                  config_parse_deps,            UINT_TO_PTR(UNIT_AFTER),                         "Meta"    },
1161                 { "RecursiveStop",          config_parse_bool,            &u->meta.recursive_stop,                         "Meta"    },
1162                 { "StopWhenUnneeded",       config_parse_bool,            &u->meta.stop_when_unneeded,                     "Meta"    },
1163
1164                 { "PIDFile",                config_parse_path,            &u->service.pid_file,                            "Service" },
1165                 { "ExecStartPre",           config_parse_exec,            u->service.exec_command+SERVICE_EXEC_START_PRE,  "Service" },
1166                 { "ExecStart",              config_parse_exec,            u->service.exec_command+SERVICE_EXEC_START,      "Service" },
1167                 { "ExecStartPost",          config_parse_exec,            u->service.exec_command+SERVICE_EXEC_START_POST, "Service" },
1168                 { "ExecReload",             config_parse_exec,            u->service.exec_command+SERVICE_EXEC_RELOAD,     "Service" },
1169                 { "ExecStop",               config_parse_exec,            u->service.exec_command+SERVICE_EXEC_STOP,       "Service" },
1170                 { "ExecStopPost",           config_parse_exec,            u->service.exec_command+SERVICE_EXEC_STOP_POST,  "Service" },
1171                 { "RestartSec",             config_parse_usec,            &u->service.restart_usec,                        "Service" },
1172                 { "TimeoutSec",             config_parse_usec,            &u->service.timeout_usec,                        "Service" },
1173                 { "Type",                   config_parse_service_type,    &u->service.type,                                "Service" },
1174                 { "Restart",                config_parse_service_restart, &u->service.restart,                             "Service" },
1175                 { "PermissionsStartOnly",   config_parse_bool,            &u->service.permissions_start_only,              "Service" },
1176                 { "RootDirectoryStartOnly", config_parse_bool,            &u->service.root_directory_start_only,           "Service" },
1177                 { "ValidNoProcess",         config_parse_bool,            &u->service.valid_no_process,                    "Service" },
1178                 { "SysVStartPriority",      config_parse_sysv_priority,   &u->service.sysv_start_priority,                 "Service" },
1179                 { "KillMode",               config_parse_kill_mode,       &u->service.kill_mode,                           "Service" },
1180                 { "NonBlocking",            config_parse_bool,            &u->service.exec_context.non_blocking,           "Service" },
1181                 EXEC_CONTEXT_CONFIG_ITEMS(u->service.exec_context, "Service"),
1182
1183                 { "ListenStream",           config_parse_listen,          &u->socket,                                      "Socket"  },
1184                 { "ListenDatagram",         config_parse_listen,          &u->socket,                                      "Socket"  },
1185                 { "ListenSequentialPacket", config_parse_listen,          &u->socket,                                      "Socket"  },
1186                 { "ListenFIFO",             config_parse_listen,          &u->socket,                                      "Socket"  },
1187                 { "BindIPv6Only",           config_parse_socket_bind,     &u->socket,                                      "Socket"  },
1188                 { "Backlog",                config_parse_unsigned,        &u->socket.backlog,                              "Socket"  },
1189                 { "BindToDevice",           config_parse_bindtodevice,    &u->socket,                                      "Socket"  },
1190                 { "ExecStartPre",           config_parse_exec,            u->socket.exec_command+SOCKET_EXEC_START_PRE,    "Socket"  },
1191                 { "ExecStartPost",          config_parse_exec,            u->socket.exec_command+SOCKET_EXEC_START_POST,   "Socket"  },
1192                 { "ExecStopPre",            config_parse_exec,            u->socket.exec_command+SOCKET_EXEC_STOP_PRE,     "Socket"  },
1193                 { "ExecStopPost",           config_parse_exec,            u->socket.exec_command+SOCKET_EXEC_STOP_POST,    "Socket"  },
1194                 { "TimeoutSec",             config_parse_usec,            &u->socket.timeout_usec,                         "Socket"  },
1195                 { "DirectoryMode",          config_parse_mode,            &u->socket.directory_mode,                       "Socket"  },
1196                 { "SocketMode",             config_parse_mode,            &u->socket.socket_mode,                          "Socket"  },
1197                 { "KillMode",               config_parse_kill_mode,       &u->socket.kill_mode,                            "Socket"  },
1198                 EXEC_CONTEXT_CONFIG_ITEMS(u->socket.exec_context, "Socket"),
1199
1200                 { "What",                   config_parse_string,          &u->mount.parameters_fragment.what,              "Mount"   },
1201                 { "Where",                  config_parse_path,            &u->mount.where,                                 "Mount"   },
1202                 { "Options",                config_parse_string,          &u->mount.parameters_fragment.options,           "Mount"   },
1203                 { "Type",                   config_parse_string,          &u->mount.parameters_fragment.fstype,            "Mount"   },
1204                 { "TimeoutSec",             config_parse_usec,            &u->mount.timeout_usec,                          "Mount"   },
1205                 { "KillMode",               config_parse_kill_mode,       &u->mount.kill_mode,                             "Mount"   },
1206                 EXEC_CONTEXT_CONFIG_ITEMS(u->mount.exec_context, "Mount"),
1207
1208                 { NULL, NULL, NULL, NULL }
1209         };
1210
1211 #undef EXEC_CONTEXT_CONFIG_ITEMS
1212
1213         const char *sections[3];
1214         char *k;
1215         int r;
1216         Set *symlink_names;
1217         FILE *f = NULL;
1218         char *filename = NULL, *id = NULL;
1219         Unit *merged;
1220
1221         if (!u) {
1222                 /* Dirty dirty hack. */
1223                 dump_items((FILE*) path, items);
1224                 return 0;
1225         }
1226
1227         assert(u);
1228         assert(path);
1229
1230         sections[0] = "Meta";
1231         sections[1] = section_table[u->meta.type];
1232         sections[2] = NULL;
1233
1234         if (!(symlink_names = set_new(string_hash_func, string_compare_func)))
1235                 return -ENOMEM;
1236
1237         if (path_is_absolute(path)) {
1238
1239                 if (!(filename = strdup(path))) {
1240                         r = -ENOMEM;
1241                         goto finish;
1242                 }
1243
1244                 if ((r = open_follow(&filename, &f, symlink_names, &id)) < 0) {
1245                         free(filename);
1246                         filename = NULL;
1247
1248                         if (r != -ENOENT)
1249                                 goto finish;
1250                 }
1251
1252         } else  {
1253                 char **p;
1254
1255                 STRV_FOREACH(p, u->meta.manager->unit_path) {
1256
1257                         /* Instead of opening the path right away, we manually
1258                          * follow all symlinks and add their name to our unit
1259                          * name set while doing so */
1260                         if (!(filename = path_make_absolute(path, *p))) {
1261                                 r = -ENOMEM;
1262                                 goto finish;
1263                         }
1264
1265                         if ((r = open_follow(&filename, &f, symlink_names, &id)) < 0) {
1266                                 char *sn;
1267
1268                                 free(filename);
1269                                 filename = NULL;
1270
1271                                 if (r != -ENOENT)
1272                                         goto finish;
1273
1274                                 /* Empty the symlink names for the next run */
1275                                 while ((sn = set_steal_first(symlink_names)))
1276                                         free(sn);
1277
1278                                 continue;
1279                         }
1280
1281                         break;
1282                 }
1283         }
1284
1285         if (!filename) {
1286                 r = 0;
1287                 goto finish;
1288         }
1289
1290         merged = u;
1291         if ((r = merge_by_names(&merged, symlink_names, id)) < 0)
1292                 goto finish;
1293
1294         if (merged != u) {
1295                 u->meta.load_state = UNIT_MERGED;
1296                 r = 0;
1297                 goto finish;
1298         }
1299
1300         /* Now, parse the file contents */
1301         if ((r = config_parse(filename, f, sections, items, u)) < 0)
1302                 goto finish;
1303
1304         free(u->meta.fragment_path);
1305         u->meta.fragment_path = filename;
1306         filename = NULL;
1307
1308         u->meta.load_state = UNIT_LOADED;
1309         r = 0;
1310
1311 finish:
1312         while ((k = set_steal_first(symlink_names)))
1313                 free(k);
1314
1315         set_free(symlink_names);
1316         free(filename);
1317
1318         if (f)
1319                 fclose(f);
1320
1321         return r;
1322 }
1323
1324 int unit_load_fragment(Unit *u) {
1325         int r;
1326
1327         assert(u);
1328
1329         if (u->meta.fragment_path) {
1330
1331                 if ((r = load_from_path(u, u->meta.fragment_path)) < 0)
1332                         return r;
1333
1334         } else {
1335                 Iterator i;
1336                 const char *t;
1337
1338                 /* Try to find the unit under its id */
1339                 if ((t = unit_id(u)))
1340                         if ((r = load_from_path(u, t)) < 0)
1341                                 return r;
1342
1343                 /* Try to find an alias we can load this with */
1344                 if (u->meta.load_state == UNIT_STUB)
1345                         SET_FOREACH(t, u->meta.names, i) {
1346
1347                                 if (unit_id(u) == t)
1348                                         continue;
1349
1350                                 if ((r = load_from_path(u, t)) < 0)
1351                                         return r;
1352
1353                                 if (u->meta.load_state != UNIT_STUB)
1354                                         break;
1355                         }
1356         }
1357
1358         return 0;
1359 }
1360
1361 void unit_dump_config_items(FILE *f) {
1362         /* OK, this wins a prize for extreme ugliness. */
1363
1364         load_from_path(NULL, (const void*) f);
1365 }