chiark / gitweb /
always use /etc/os-release and ignore all distro-specific files
[elogind.git] / src / util.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
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 <assert.h>
23 #include <string.h>
24 #include <unistd.h>
25 #include <errno.h>
26 #include <stdlib.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <syslog.h>
30 #include <sched.h>
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <fcntl.h>
36 #include <dirent.h>
37 #include <sys/ioctl.h>
38 #include <linux/vt.h>
39 #include <linux/tiocl.h>
40 #include <termios.h>
41 #include <stdarg.h>
42 #include <sys/inotify.h>
43 #include <sys/poll.h>
44 #include <libgen.h>
45 #include <ctype.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
48 #include <pwd.h>
49 #include <netinet/ip.h>
50 #include <linux/kd.h>
51 #include <dlfcn.h>
52 #include <sys/wait.h>
53 #include <sys/capability.h>
54 #include <sys/time.h>
55 #include <linux/rtc.h>
56 #include <glob.h>
57 #include <grp.h>
58 #include <sys/mman.h>
59
60 #include "macro.h"
61 #include "util.h"
62 #include "ioprio.h"
63 #include "missing.h"
64 #include "log.h"
65 #include "strv.h"
66 #include "label.h"
67 #include "exit-status.h"
68 #include "hashmap.h"
69
70 int saved_argc = 0;
71 char **saved_argv = NULL;
72
73 size_t page_size(void) {
74         static __thread size_t pgsz = 0;
75         long r;
76
77         if (_likely_(pgsz > 0))
78                 return pgsz;
79
80         assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
81
82         pgsz = (size_t) r;
83
84         return pgsz;
85 }
86
87 bool streq_ptr(const char *a, const char *b) {
88
89         /* Like streq(), but tries to make sense of NULL pointers */
90
91         if (a && b)
92                 return streq(a, b);
93
94         if (!a && !b)
95                 return true;
96
97         return false;
98 }
99
100 usec_t now(clockid_t clock_id) {
101         struct timespec ts;
102
103         assert_se(clock_gettime(clock_id, &ts) == 0);
104
105         return timespec_load(&ts);
106 }
107
108 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
109         assert(ts);
110
111         ts->realtime = now(CLOCK_REALTIME);
112         ts->monotonic = now(CLOCK_MONOTONIC);
113
114         return ts;
115 }
116
117 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
118         int64_t delta;
119         assert(ts);
120
121         ts->realtime = u;
122
123         if (u == 0)
124                 ts->monotonic = 0;
125         else {
126                 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
127
128                 ts->monotonic = now(CLOCK_MONOTONIC);
129
130                 if ((int64_t) ts->monotonic > delta)
131                         ts->monotonic -= delta;
132                 else
133                         ts->monotonic = 0;
134         }
135
136         return ts;
137 }
138
139 usec_t timespec_load(const struct timespec *ts) {
140         assert(ts);
141
142         return
143                 (usec_t) ts->tv_sec * USEC_PER_SEC +
144                 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
145 }
146
147 struct timespec *timespec_store(struct timespec *ts, usec_t u)  {
148         assert(ts);
149
150         ts->tv_sec = (time_t) (u / USEC_PER_SEC);
151         ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
152
153         return ts;
154 }
155
156 usec_t timeval_load(const struct timeval *tv) {
157         assert(tv);
158
159         return
160                 (usec_t) tv->tv_sec * USEC_PER_SEC +
161                 (usec_t) tv->tv_usec;
162 }
163
164 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
165         assert(tv);
166
167         tv->tv_sec = (time_t) (u / USEC_PER_SEC);
168         tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
169
170         return tv;
171 }
172
173 bool endswith(const char *s, const char *postfix) {
174         size_t sl, pl;
175
176         assert(s);
177         assert(postfix);
178
179         sl = strlen(s);
180         pl = strlen(postfix);
181
182         if (pl == 0)
183                 return true;
184
185         if (sl < pl)
186                 return false;
187
188         return memcmp(s + sl - pl, postfix, pl) == 0;
189 }
190
191 bool startswith(const char *s, const char *prefix) {
192         size_t sl, pl;
193
194         assert(s);
195         assert(prefix);
196
197         sl = strlen(s);
198         pl = strlen(prefix);
199
200         if (pl == 0)
201                 return true;
202
203         if (sl < pl)
204                 return false;
205
206         return memcmp(s, prefix, pl) == 0;
207 }
208
209 bool startswith_no_case(const char *s, const char *prefix) {
210         size_t sl, pl;
211         unsigned i;
212
213         assert(s);
214         assert(prefix);
215
216         sl = strlen(s);
217         pl = strlen(prefix);
218
219         if (pl == 0)
220                 return true;
221
222         if (sl < pl)
223                 return false;
224
225         for(i = 0; i < pl; ++i) {
226                 if (tolower(s[i]) != tolower(prefix[i]))
227                         return false;
228         }
229
230         return true;
231 }
232
233 bool first_word(const char *s, const char *word) {
234         size_t sl, wl;
235
236         assert(s);
237         assert(word);
238
239         sl = strlen(s);
240         wl = strlen(word);
241
242         if (sl < wl)
243                 return false;
244
245         if (wl == 0)
246                 return true;
247
248         if (memcmp(s, word, wl) != 0)
249                 return false;
250
251         return s[wl] == 0 ||
252                 strchr(WHITESPACE, s[wl]);
253 }
254
255 int close_nointr(int fd) {
256         assert(fd >= 0);
257
258         for (;;) {
259                 int r;
260
261                 r = close(fd);
262                 if (r >= 0)
263                         return r;
264
265                 if (errno != EINTR)
266                         return -errno;
267         }
268 }
269
270 void close_nointr_nofail(int fd) {
271         int saved_errno = errno;
272
273         /* like close_nointr() but cannot fail, and guarantees errno
274          * is unchanged */
275
276         assert_se(close_nointr(fd) == 0);
277
278         errno = saved_errno;
279 }
280
281 void close_many(const int fds[], unsigned n_fd) {
282         unsigned i;
283
284         for (i = 0; i < n_fd; i++)
285                 close_nointr_nofail(fds[i]);
286 }
287
288 int parse_boolean(const char *v) {
289         assert(v);
290
291         if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
292                 return 1;
293         else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
294                 return 0;
295
296         return -EINVAL;
297 }
298
299 int parse_pid(const char *s, pid_t* ret_pid) {
300         unsigned long ul = 0;
301         pid_t pid;
302         int r;
303
304         assert(s);
305         assert(ret_pid);
306
307         if ((r = safe_atolu(s, &ul)) < 0)
308                 return r;
309
310         pid = (pid_t) ul;
311
312         if ((unsigned long) pid != ul)
313                 return -ERANGE;
314
315         if (pid <= 0)
316                 return -ERANGE;
317
318         *ret_pid = pid;
319         return 0;
320 }
321
322 int parse_uid(const char *s, uid_t* ret_uid) {
323         unsigned long ul = 0;
324         uid_t uid;
325         int r;
326
327         assert(s);
328         assert(ret_uid);
329
330         if ((r = safe_atolu(s, &ul)) < 0)
331                 return r;
332
333         uid = (uid_t) ul;
334
335         if ((unsigned long) uid != ul)
336                 return -ERANGE;
337
338         *ret_uid = uid;
339         return 0;
340 }
341
342 int safe_atou(const char *s, unsigned *ret_u) {
343         char *x = NULL;
344         unsigned long l;
345
346         assert(s);
347         assert(ret_u);
348
349         errno = 0;
350         l = strtoul(s, &x, 0);
351
352         if (!x || *x || errno)
353                 return errno ? -errno : -EINVAL;
354
355         if ((unsigned long) (unsigned) l != l)
356                 return -ERANGE;
357
358         *ret_u = (unsigned) l;
359         return 0;
360 }
361
362 int safe_atoi(const char *s, int *ret_i) {
363         char *x = NULL;
364         long l;
365
366         assert(s);
367         assert(ret_i);
368
369         errno = 0;
370         l = strtol(s, &x, 0);
371
372         if (!x || *x || errno)
373                 return errno ? -errno : -EINVAL;
374
375         if ((long) (int) l != l)
376                 return -ERANGE;
377
378         *ret_i = (int) l;
379         return 0;
380 }
381
382 int safe_atollu(const char *s, long long unsigned *ret_llu) {
383         char *x = NULL;
384         unsigned long long l;
385
386         assert(s);
387         assert(ret_llu);
388
389         errno = 0;
390         l = strtoull(s, &x, 0);
391
392         if (!x || *x || errno)
393                 return errno ? -errno : -EINVAL;
394
395         *ret_llu = l;
396         return 0;
397 }
398
399 int safe_atolli(const char *s, long long int *ret_lli) {
400         char *x = NULL;
401         long long l;
402
403         assert(s);
404         assert(ret_lli);
405
406         errno = 0;
407         l = strtoll(s, &x, 0);
408
409         if (!x || *x || errno)
410                 return errno ? -errno : -EINVAL;
411
412         *ret_lli = l;
413         return 0;
414 }
415
416 /* Split a string into words. */
417 char *split(const char *c, size_t *l, const char *separator, char **state) {
418         char *current;
419
420         current = *state ? *state : (char*) c;
421
422         if (!*current || *c == 0)
423                 return NULL;
424
425         current += strspn(current, separator);
426         *l = strcspn(current, separator);
427         *state = current+*l;
428
429         return (char*) current;
430 }
431
432 /* Split a string into words, but consider strings enclosed in '' and
433  * "" as words even if they include spaces. */
434 char *split_quoted(const char *c, size_t *l, char **state) {
435         char *current, *e;
436         bool escaped = false;
437
438         current = *state ? *state : (char*) c;
439
440         if (!*current || *c == 0)
441                 return NULL;
442
443         current += strspn(current, WHITESPACE);
444
445         if (*current == '\'') {
446                 current ++;
447
448                 for (e = current; *e; e++) {
449                         if (escaped)
450                                 escaped = false;
451                         else if (*e == '\\')
452                                 escaped = true;
453                         else if (*e == '\'')
454                                 break;
455                 }
456
457                 *l = e-current;
458                 *state = *e == 0 ? e : e+1;
459         } else if (*current == '\"') {
460                 current ++;
461
462                 for (e = current; *e; e++) {
463                         if (escaped)
464                                 escaped = false;
465                         else if (*e == '\\')
466                                 escaped = true;
467                         else if (*e == '\"')
468                                 break;
469                 }
470
471                 *l = e-current;
472                 *state = *e == 0 ? e : e+1;
473         } else {
474                 for (e = current; *e; e++) {
475                         if (escaped)
476                                 escaped = false;
477                         else if (*e == '\\')
478                                 escaped = true;
479                         else if (strchr(WHITESPACE, *e))
480                                 break;
481                 }
482                 *l = e-current;
483                 *state = e;
484         }
485
486         return (char*) current;
487 }
488
489 char **split_path_and_make_absolute(const char *p) {
490         char **l;
491         assert(p);
492
493         if (!(l = strv_split(p, ":")))
494                 return NULL;
495
496         if (!strv_path_make_absolute_cwd(l)) {
497                 strv_free(l);
498                 return NULL;
499         }
500
501         return l;
502 }
503
504 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
505         int r;
506         FILE *f;
507         char fn[PATH_MAX], line[LINE_MAX], *p;
508         long unsigned ppid;
509
510         assert(pid > 0);
511         assert(_ppid);
512
513         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
514         char_array_0(fn);
515
516         if (!(f = fopen(fn, "re")))
517                 return -errno;
518
519         if (!(fgets(line, sizeof(line), f))) {
520                 r = feof(f) ? -EIO : -errno;
521                 fclose(f);
522                 return r;
523         }
524
525         fclose(f);
526
527         /* Let's skip the pid and comm fields. The latter is enclosed
528          * in () but does not escape any () in its value, so let's
529          * skip over it manually */
530
531         if (!(p = strrchr(line, ')')))
532                 return -EIO;
533
534         p++;
535
536         if (sscanf(p, " "
537                    "%*c "  /* state */
538                    "%lu ", /* ppid */
539                    &ppid) != 1)
540                 return -EIO;
541
542         if ((long unsigned) (pid_t) ppid != ppid)
543                 return -ERANGE;
544
545         *_ppid = (pid_t) ppid;
546
547         return 0;
548 }
549
550 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
551         int r;
552         FILE *f;
553         char fn[PATH_MAX], line[LINE_MAX], *p;
554
555         assert(pid > 0);
556         assert(st);
557
558         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
559         char_array_0(fn);
560
561         if (!(f = fopen(fn, "re")))
562                 return -errno;
563
564         if (!(fgets(line, sizeof(line), f))) {
565                 r = feof(f) ? -EIO : -errno;
566                 fclose(f);
567                 return r;
568         }
569
570         fclose(f);
571
572         /* Let's skip the pid and comm fields. The latter is enclosed
573          * in () but does not escape any () in its value, so let's
574          * skip over it manually */
575
576         if (!(p = strrchr(line, ')')))
577                 return -EIO;
578
579         p++;
580
581         if (sscanf(p, " "
582                    "%*c "  /* state */
583                    "%*d "  /* ppid */
584                    "%*d "  /* pgrp */
585                    "%*d "  /* session */
586                    "%*d "  /* tty_nr */
587                    "%*d "  /* tpgid */
588                    "%*u "  /* flags */
589                    "%*u "  /* minflt */
590                    "%*u "  /* cminflt */
591                    "%*u "  /* majflt */
592                    "%*u "  /* cmajflt */
593                    "%*u "  /* utime */
594                    "%*u "  /* stime */
595                    "%*d "  /* cutime */
596                    "%*d "  /* cstime */
597                    "%*d "  /* priority */
598                    "%*d "  /* nice */
599                    "%*d "  /* num_threads */
600                    "%*d "  /* itrealvalue */
601                    "%llu "  /* starttime */,
602                    st) != 1)
603                 return -EIO;
604
605         return 0;
606 }
607
608 int write_one_line_file(const char *fn, const char *line) {
609         FILE *f;
610         int r;
611
612         assert(fn);
613         assert(line);
614
615         if (!(f = fopen(fn, "we")))
616                 return -errno;
617
618         errno = 0;
619         if (fputs(line, f) < 0) {
620                 r = -errno;
621                 goto finish;
622         }
623
624         if (!endswith(line, "\n"))
625                 fputc('\n', f);
626
627         fflush(f);
628
629         if (ferror(f)) {
630                 if (errno != 0)
631                         r = -errno;
632                 else
633                         r = -EIO;
634         } else
635                 r = 0;
636
637 finish:
638         fclose(f);
639         return r;
640 }
641
642 int fchmod_umask(int fd, mode_t m) {
643         mode_t u;
644         int r;
645
646         u = umask(0777);
647         r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
648         umask(u);
649
650         return r;
651 }
652
653 int write_one_line_file_atomic(const char *fn, const char *line) {
654         FILE *f;
655         int r;
656         char *p;
657
658         assert(fn);
659         assert(line);
660
661         r = fopen_temporary(fn, &f, &p);
662         if (r < 0)
663                 return r;
664
665         fchmod_umask(fileno(f), 0644);
666
667         errno = 0;
668         if (fputs(line, f) < 0) {
669                 r = -errno;
670                 goto finish;
671         }
672
673         if (!endswith(line, "\n"))
674                 fputc('\n', f);
675
676         fflush(f);
677
678         if (ferror(f)) {
679                 if (errno != 0)
680                         r = -errno;
681                 else
682                         r = -EIO;
683         } else {
684                 if (rename(p, fn) < 0)
685                         r = -errno;
686                 else
687                         r = 0;
688         }
689
690 finish:
691         if (r < 0)
692                 unlink(p);
693
694         fclose(f);
695         free(p);
696
697         return r;
698 }
699
700 int read_one_line_file(const char *fn, char **line) {
701         FILE *f;
702         int r;
703         char t[LINE_MAX], *c;
704
705         assert(fn);
706         assert(line);
707
708         f = fopen(fn, "re");
709         if (!f)
710                 return -errno;
711
712         if (!fgets(t, sizeof(t), f)) {
713
714                 if (ferror(f)) {
715                         r = -errno;
716                         goto finish;
717                 }
718
719                 t[0] = 0;
720         }
721
722         c = strdup(t);
723         if (!c) {
724                 r = -ENOMEM;
725                 goto finish;
726         }
727
728         truncate_nl(c);
729
730         *line = c;
731         r = 0;
732
733 finish:
734         fclose(f);
735         return r;
736 }
737
738 int read_full_file(const char *fn, char **contents, size_t *size) {
739         FILE *f;
740         int r;
741         size_t n, l;
742         char *buf = NULL;
743         struct stat st;
744
745         if (!(f = fopen(fn, "re")))
746                 return -errno;
747
748         if (fstat(fileno(f), &st) < 0) {
749                 r = -errno;
750                 goto finish;
751         }
752
753         /* Safety check */
754         if (st.st_size > 4*1024*1024) {
755                 r = -E2BIG;
756                 goto finish;
757         }
758
759         n = st.st_size > 0 ? st.st_size : LINE_MAX;
760         l = 0;
761
762         for (;;) {
763                 char *t;
764                 size_t k;
765
766                 if (!(t = realloc(buf, n+1))) {
767                         r = -ENOMEM;
768                         goto finish;
769                 }
770
771                 buf = t;
772                 k = fread(buf + l, 1, n - l, f);
773
774                 if (k <= 0) {
775                         if (ferror(f)) {
776                                 r = -errno;
777                                 goto finish;
778                         }
779
780                         break;
781                 }
782
783                 l += k;
784                 n *= 2;
785
786                 /* Safety check */
787                 if (n > 4*1024*1024) {
788                         r = -E2BIG;
789                         goto finish;
790                 }
791         }
792
793         buf[l] = 0;
794         *contents = buf;
795         buf = NULL;
796
797         if (size)
798                 *size = l;
799
800         r = 0;
801
802 finish:
803         fclose(f);
804         free(buf);
805
806         return r;
807 }
808
809 int parse_env_file(
810                 const char *fname,
811                 const char *separator, ...) {
812
813         int r = 0;
814         char *contents = NULL, *p;
815
816         assert(fname);
817         assert(separator);
818
819         if ((r = read_full_file(fname, &contents, NULL)) < 0)
820                 return r;
821
822         p = contents;
823         for (;;) {
824                 const char *key = NULL;
825
826                 p += strspn(p, separator);
827                 p += strspn(p, WHITESPACE);
828
829                 if (!*p)
830                         break;
831
832                 if (!strchr(COMMENTS, *p)) {
833                         va_list ap;
834                         char **value;
835
836                         va_start(ap, separator);
837                         while ((key = va_arg(ap, char *))) {
838                                 size_t n;
839                                 char *v;
840
841                                 value = va_arg(ap, char **);
842
843                                 n = strlen(key);
844                                 if (strncmp(p, key, n) != 0 ||
845                                     p[n] != '=')
846                                         continue;
847
848                                 p += n + 1;
849                                 n = strcspn(p, separator);
850
851                                 if (n >= 2 &&
852                                     strchr(QUOTES, p[0]) &&
853                                     p[n-1] == p[0])
854                                         v = strndup(p+1, n-2);
855                                 else
856                                         v = strndup(p, n);
857
858                                 if (!v) {
859                                         r = -ENOMEM;
860                                         va_end(ap);
861                                         goto fail;
862                                 }
863
864                                 if (v[0] == '\0') {
865                                         /* return empty value strings as NULL */
866                                         free(v);
867                                         v = NULL;
868                                 }
869
870                                 free(*value);
871                                 *value = v;
872
873                                 p += n;
874
875                                 r ++;
876                                 break;
877                         }
878                         va_end(ap);
879                 }
880
881                 if (!key)
882                         p += strcspn(p, separator);
883         }
884
885 fail:
886         free(contents);
887         return r;
888 }
889
890 int load_env_file(
891                 const char *fname,
892                 char ***rl) {
893
894         FILE *f;
895         char **m = 0;
896         int r;
897
898         assert(fname);
899         assert(rl);
900
901         if (!(f = fopen(fname, "re")))
902                 return -errno;
903
904         while (!feof(f)) {
905                 char l[LINE_MAX], *p, *u;
906                 char **t;
907
908                 if (!fgets(l, sizeof(l), f)) {
909                         if (feof(f))
910                                 break;
911
912                         r = -errno;
913                         goto finish;
914                 }
915
916                 p = strstrip(l);
917
918                 if (!*p)
919                         continue;
920
921                 if (strchr(COMMENTS, *p))
922                         continue;
923
924                 if (!(u = normalize_env_assignment(p))) {
925                         log_error("Out of memory");
926                         r = -ENOMEM;
927                         goto finish;
928                 }
929
930                 t = strv_append(m, u);
931                 free(u);
932
933                 if (!t) {
934                         log_error("Out of memory");
935                         r = -ENOMEM;
936                         goto finish;
937                 }
938
939                 strv_free(m);
940                 m = t;
941         }
942
943         r = 0;
944
945         *rl = m;
946         m = NULL;
947
948 finish:
949         if (f)
950                 fclose(f);
951
952         strv_free(m);
953
954         return r;
955 }
956
957 int write_env_file(const char *fname, char **l) {
958         char **i, *p;
959         FILE *f;
960         int r;
961
962         r = fopen_temporary(fname, &f, &p);
963         if (r < 0)
964                 return r;
965
966         fchmod_umask(fileno(f), 0644);
967
968         errno = 0;
969         STRV_FOREACH(i, l) {
970                 fputs(*i, f);
971                 fputc('\n', f);
972         }
973
974         fflush(f);
975
976         if (ferror(f)) {
977                 if (errno != 0)
978                         r = -errno;
979                 else
980                         r = -EIO;
981         } else {
982                 if (rename(p, fname) < 0)
983                         r = -errno;
984                 else
985                         r = 0;
986         }
987
988         if (r < 0)
989                 unlink(p);
990
991         fclose(f);
992         free(p);
993
994         return r;
995 }
996
997 char *truncate_nl(char *s) {
998         assert(s);
999
1000         s[strcspn(s, NEWLINE)] = 0;
1001         return s;
1002 }
1003
1004 int get_process_comm(pid_t pid, char **name) {
1005         int r;
1006
1007         assert(name);
1008
1009         if (pid == 0)
1010                 r = read_one_line_file("/proc/self/comm", name);
1011         else {
1012                 char *p;
1013                 if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
1014                         return -ENOMEM;
1015
1016                 r = read_one_line_file(p, name);
1017                 free(p);
1018         }
1019
1020         return r;
1021 }
1022
1023 int get_process_cmdline(pid_t pid, size_t max_length, bool comm_fallback, char **line) {
1024         char *r, *k;
1025         int c;
1026         bool space = false;
1027         size_t left;
1028         FILE *f;
1029
1030         assert(max_length > 0);
1031         assert(line);
1032
1033         if (pid == 0)
1034                 f = fopen("/proc/self/cmdline", "re");
1035         else {
1036                 char *p;
1037                 if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1038                         return -ENOMEM;
1039
1040                 f = fopen(p, "re");
1041                 free(p);
1042         }
1043
1044         if (!f)
1045                 return -errno;
1046
1047         r = new(char, max_length);
1048         if (!r) {
1049                 fclose(f);
1050                 return -ENOMEM;
1051         }
1052
1053         k = r;
1054         left = max_length;
1055         while ((c = getc(f)) != EOF) {
1056
1057                 if (isprint(c)) {
1058                         if (space) {
1059                                 if (left <= 4)
1060                                         break;
1061
1062                                 *(k++) = ' ';
1063                                 left--;
1064                                 space = false;
1065                         }
1066
1067                         if (left <= 4)
1068                                 break;
1069
1070                         *(k++) = (char) c;
1071                         left--;
1072                 }  else
1073                         space = true;
1074         }
1075
1076         if (left <= 4) {
1077                 size_t n = MIN(left-1, 3U);
1078                 memcpy(k, "...", n);
1079                 k[n] = 0;
1080         } else
1081                 *k = 0;
1082
1083         fclose(f);
1084
1085         /* Kernel threads have no argv[] */
1086         if (r[0] == 0) {
1087                 char *t;
1088                 int h;
1089
1090                 free(r);
1091
1092                 if (!comm_fallback)
1093                         return -ENOENT;
1094
1095                 h = get_process_comm(pid, &t);
1096                 if (h < 0)
1097                         return h;
1098
1099                 r = join("[", t, "]", NULL);
1100                 free(t);
1101
1102                 if (!r)
1103                         return -ENOMEM;
1104         }
1105
1106         *line = r;
1107         return 0;
1108 }
1109
1110 int is_kernel_thread(pid_t pid) {
1111         char *p;
1112         size_t count;
1113         char c;
1114         bool eof;
1115         FILE *f;
1116
1117         if (pid == 0)
1118                 return 0;
1119
1120         if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
1121                 return -ENOMEM;
1122
1123         f = fopen(p, "re");
1124         free(p);
1125
1126         if (!f)
1127                 return -errno;
1128
1129         count = fread(&c, 1, 1, f);
1130         eof = feof(f);
1131         fclose(f);
1132
1133         /* Kernel threads have an empty cmdline */
1134
1135         if (count <= 0)
1136                 return eof ? 1 : -errno;
1137
1138         return 0;
1139 }
1140
1141 int get_process_exe(pid_t pid, char **name) {
1142         int r;
1143
1144         assert(name);
1145
1146         if (pid == 0)
1147                 r = readlink_malloc("/proc/self/exe", name);
1148         else {
1149                 char *p;
1150                 if (asprintf(&p, "/proc/%lu/exe", (unsigned long) pid) < 0)
1151                         return -ENOMEM;
1152
1153                 r = readlink_malloc(p, name);
1154                 free(p);
1155         }
1156
1157         return r;
1158 }
1159
1160 int get_process_uid(pid_t pid, uid_t *uid) {
1161         char *p;
1162         FILE *f;
1163         int r;
1164
1165         assert(uid);
1166
1167         if (pid == 0)
1168                 return getuid();
1169
1170         if (asprintf(&p, "/proc/%lu/status", (unsigned long) pid) < 0)
1171                 return -ENOMEM;
1172
1173         f = fopen(p, "re");
1174         free(p);
1175
1176         if (!f)
1177                 return -errno;
1178
1179         while (!feof(f)) {
1180                 char line[LINE_MAX], *l;
1181
1182                 if (!fgets(line, sizeof(line), f)) {
1183                         if (feof(f))
1184                                 break;
1185
1186                         r = -errno;
1187                         goto finish;
1188                 }
1189
1190                 l = strstrip(line);
1191
1192                 if (startswith(l, "Uid:")) {
1193                         l += 4;
1194                         l += strspn(l, WHITESPACE);
1195
1196                         l[strcspn(l, WHITESPACE)] = 0;
1197
1198                         r = parse_uid(l, uid);
1199                         goto finish;
1200                 }
1201         }
1202
1203         r = -EIO;
1204
1205 finish:
1206         fclose(f);
1207
1208         return r;
1209 }
1210
1211 char *strnappend(const char *s, const char *suffix, size_t b) {
1212         size_t a;
1213         char *r;
1214
1215         if (!s && !suffix)
1216                 return strdup("");
1217
1218         if (!s)
1219                 return strndup(suffix, b);
1220
1221         if (!suffix)
1222                 return strdup(s);
1223
1224         assert(s);
1225         assert(suffix);
1226
1227         a = strlen(s);
1228
1229         if (!(r = new(char, a+b+1)))
1230                 return NULL;
1231
1232         memcpy(r, s, a);
1233         memcpy(r+a, suffix, b);
1234         r[a+b] = 0;
1235
1236         return r;
1237 }
1238
1239 char *strappend(const char *s, const char *suffix) {
1240         return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
1241 }
1242
1243 int readlink_malloc(const char *p, char **r) {
1244         size_t l = 100;
1245
1246         assert(p);
1247         assert(r);
1248
1249         for (;;) {
1250                 char *c;
1251                 ssize_t n;
1252
1253                 if (!(c = new(char, l)))
1254                         return -ENOMEM;
1255
1256                 if ((n = readlink(p, c, l-1)) < 0) {
1257                         int ret = -errno;
1258                         free(c);
1259                         return ret;
1260                 }
1261
1262                 if ((size_t) n < l-1) {
1263                         c[n] = 0;
1264                         *r = c;
1265                         return 0;
1266                 }
1267
1268                 free(c);
1269                 l *= 2;
1270         }
1271 }
1272
1273 int readlink_and_make_absolute(const char *p, char **r) {
1274         char *target, *k;
1275         int j;
1276
1277         assert(p);
1278         assert(r);
1279
1280         if ((j = readlink_malloc(p, &target)) < 0)
1281                 return j;
1282
1283         k = file_in_same_dir(p, target);
1284         free(target);
1285
1286         if (!k)
1287                 return -ENOMEM;
1288
1289         *r = k;
1290         return 0;
1291 }
1292
1293 int readlink_and_canonicalize(const char *p, char **r) {
1294         char *t, *s;
1295         int j;
1296
1297         assert(p);
1298         assert(r);
1299
1300         j = readlink_and_make_absolute(p, &t);
1301         if (j < 0)
1302                 return j;
1303
1304         s = canonicalize_file_name(t);
1305         if (s) {
1306                 free(t);
1307                 *r = s;
1308         } else
1309                 *r = t;
1310
1311         path_kill_slashes(*r);
1312
1313         return 0;
1314 }
1315
1316 int parent_of_path(const char *path, char **_r) {
1317         const char *e, *a = NULL, *b = NULL, *p;
1318         char *r;
1319         bool slash = false;
1320
1321         assert(path);
1322         assert(_r);
1323
1324         if (!*path)
1325                 return -EINVAL;
1326
1327         for (e = path; *e; e++) {
1328
1329                 if (!slash && *e == '/') {
1330                         a = b;
1331                         b = e;
1332                         slash = true;
1333                 } else if (slash && *e != '/')
1334                         slash = false;
1335         }
1336
1337         if (*(e-1) == '/')
1338                 p = a;
1339         else
1340                 p = b;
1341
1342         if (!p)
1343                 return -EINVAL;
1344
1345         if (p == path)
1346                 r = strdup("/");
1347         else
1348                 r = strndup(path, p-path);
1349
1350         if (!r)
1351                 return -ENOMEM;
1352
1353         *_r = r;
1354         return 0;
1355 }
1356
1357
1358 char *file_name_from_path(const char *p) {
1359         char *r;
1360
1361         assert(p);
1362
1363         if ((r = strrchr(p, '/')))
1364                 return r + 1;
1365
1366         return (char*) p;
1367 }
1368
1369 bool path_is_absolute(const char *p) {
1370         assert(p);
1371
1372         return p[0] == '/';
1373 }
1374
1375 bool is_path(const char *p) {
1376
1377         return !!strchr(p, '/');
1378 }
1379
1380 char *path_make_absolute(const char *p, const char *prefix) {
1381         assert(p);
1382
1383         /* Makes every item in the list an absolute path by prepending
1384          * the prefix, if specified and necessary */
1385
1386         if (path_is_absolute(p) || !prefix)
1387                 return strdup(p);
1388
1389         return join(prefix, "/", p, NULL);
1390 }
1391
1392 char *path_make_absolute_cwd(const char *p) {
1393         char *cwd, *r;
1394
1395         assert(p);
1396
1397         /* Similar to path_make_absolute(), but prefixes with the
1398          * current working directory. */
1399
1400         if (path_is_absolute(p))
1401                 return strdup(p);
1402
1403         if (!(cwd = get_current_dir_name()))
1404                 return NULL;
1405
1406         r = path_make_absolute(p, cwd);
1407         free(cwd);
1408
1409         return r;
1410 }
1411
1412 char **strv_path_make_absolute_cwd(char **l) {
1413         char **s;
1414
1415         /* Goes through every item in the string list and makes it
1416          * absolute. This works in place and won't rollback any
1417          * changes on failure. */
1418
1419         STRV_FOREACH(s, l) {
1420                 char *t;
1421
1422                 if (!(t = path_make_absolute_cwd(*s)))
1423                         return NULL;
1424
1425                 free(*s);
1426                 *s = t;
1427         }
1428
1429         return l;
1430 }
1431
1432 char **strv_path_canonicalize(char **l) {
1433         char **s;
1434         unsigned k = 0;
1435         bool enomem = false;
1436
1437         if (strv_isempty(l))
1438                 return l;
1439
1440         /* Goes through every item in the string list and canonicalize
1441          * the path. This works in place and won't rollback any
1442          * changes on failure. */
1443
1444         STRV_FOREACH(s, l) {
1445                 char *t, *u;
1446
1447                 t = path_make_absolute_cwd(*s);
1448                 free(*s);
1449
1450                 if (!t) {
1451                         enomem = true;
1452                         continue;
1453                 }
1454
1455                 errno = 0;
1456                 u = canonicalize_file_name(t);
1457                 free(t);
1458
1459                 if (!u) {
1460                         if (errno == ENOMEM || !errno)
1461                                 enomem = true;
1462
1463                         continue;
1464                 }
1465
1466                 l[k++] = u;
1467         }
1468
1469         l[k] = NULL;
1470
1471         if (enomem)
1472                 return NULL;
1473
1474         return l;
1475 }
1476
1477 char **strv_path_remove_empty(char **l) {
1478         char **f, **t;
1479
1480         if (!l)
1481                 return NULL;
1482
1483         for (f = t = l; *f; f++) {
1484
1485                 if (dir_is_empty(*f) > 0) {
1486                         free(*f);
1487                         continue;
1488                 }
1489
1490                 *(t++) = *f;
1491         }
1492
1493         *t = NULL;
1494         return l;
1495 }
1496
1497 int reset_all_signal_handlers(void) {
1498         int sig;
1499
1500         for (sig = 1; sig < _NSIG; sig++) {
1501                 struct sigaction sa;
1502
1503                 if (sig == SIGKILL || sig == SIGSTOP)
1504                         continue;
1505
1506                 zero(sa);
1507                 sa.sa_handler = SIG_DFL;
1508                 sa.sa_flags = SA_RESTART;
1509
1510                 /* On Linux the first two RT signals are reserved by
1511                  * glibc, and sigaction() will return EINVAL for them. */
1512                 if ((sigaction(sig, &sa, NULL) < 0))
1513                         if (errno != EINVAL)
1514                                 return -errno;
1515         }
1516
1517         return 0;
1518 }
1519
1520 char *strstrip(char *s) {
1521         char *e;
1522
1523         /* Drops trailing whitespace. Modifies the string in
1524          * place. Returns pointer to first non-space character */
1525
1526         s += strspn(s, WHITESPACE);
1527
1528         for (e = strchr(s, 0); e > s; e --)
1529                 if (!strchr(WHITESPACE, e[-1]))
1530                         break;
1531
1532         *e = 0;
1533
1534         return s;
1535 }
1536
1537 char *delete_chars(char *s, const char *bad) {
1538         char *f, *t;
1539
1540         /* Drops all whitespace, regardless where in the string */
1541
1542         for (f = s, t = s; *f; f++) {
1543                 if (strchr(bad, *f))
1544                         continue;
1545
1546                 *(t++) = *f;
1547         }
1548
1549         *t = 0;
1550
1551         return s;
1552 }
1553
1554 bool in_charset(const char *s, const char* charset) {
1555         const char *i;
1556
1557         assert(s);
1558         assert(charset);
1559
1560         for (i = s; *i; i++)
1561                 if (!strchr(charset, *i))
1562                         return false;
1563
1564         return true;
1565 }
1566
1567 char *file_in_same_dir(const char *path, const char *filename) {
1568         char *e, *r;
1569         size_t k;
1570
1571         assert(path);
1572         assert(filename);
1573
1574         /* This removes the last component of path and appends
1575          * filename, unless the latter is absolute anyway or the
1576          * former isn't */
1577
1578         if (path_is_absolute(filename))
1579                 return strdup(filename);
1580
1581         if (!(e = strrchr(path, '/')))
1582                 return strdup(filename);
1583
1584         k = strlen(filename);
1585         if (!(r = new(char, e-path+1+k+1)))
1586                 return NULL;
1587
1588         memcpy(r, path, e-path+1);
1589         memcpy(r+(e-path)+1, filename, k+1);
1590
1591         return r;
1592 }
1593
1594 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1595         struct stat st;
1596
1597         if (label_mkdir(path, mode) >= 0)
1598                 if (chmod_and_chown(path, mode, uid, gid) < 0)
1599                         return -errno;
1600
1601         if (lstat(path, &st) < 0)
1602                 return -errno;
1603
1604         if ((st.st_mode & 0777) != mode ||
1605             st.st_uid != uid ||
1606             st.st_gid != gid ||
1607             !S_ISDIR(st.st_mode)) {
1608                 errno = EEXIST;
1609                 return -errno;
1610         }
1611
1612         return 0;
1613 }
1614
1615
1616 int mkdir_parents(const char *path, mode_t mode) {
1617         const char *p, *e;
1618
1619         assert(path);
1620
1621         /* Creates every parent directory in the path except the last
1622          * component. */
1623
1624         p = path + strspn(path, "/");
1625         for (;;) {
1626                 int r;
1627                 char *t;
1628
1629                 e = p + strcspn(p, "/");
1630                 p = e + strspn(e, "/");
1631
1632                 /* Is this the last component? If so, then we're
1633                  * done */
1634                 if (*p == 0)
1635                         return 0;
1636
1637                 if (!(t = strndup(path, e - path)))
1638                         return -ENOMEM;
1639
1640                 r = label_mkdir(t, mode);
1641                 free(t);
1642
1643                 if (r < 0 && errno != EEXIST)
1644                         return -errno;
1645         }
1646 }
1647
1648 int mkdir_p(const char *path, mode_t mode) {
1649         int r;
1650
1651         /* Like mkdir -p */
1652
1653         if ((r = mkdir_parents(path, mode)) < 0)
1654                 return r;
1655
1656         if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1657                 return -errno;
1658
1659         return 0;
1660 }
1661
1662 int rmdir_parents(const char *path, const char *stop) {
1663         size_t l;
1664         int r = 0;
1665
1666         assert(path);
1667         assert(stop);
1668
1669         l = strlen(path);
1670
1671         /* Skip trailing slashes */
1672         while (l > 0 && path[l-1] == '/')
1673                 l--;
1674
1675         while (l > 0) {
1676                 char *t;
1677
1678                 /* Skip last component */
1679                 while (l > 0 && path[l-1] != '/')
1680                         l--;
1681
1682                 /* Skip trailing slashes */
1683                 while (l > 0 && path[l-1] == '/')
1684                         l--;
1685
1686                 if (l <= 0)
1687                         break;
1688
1689                 if (!(t = strndup(path, l)))
1690                         return -ENOMEM;
1691
1692                 if (path_startswith(stop, t)) {
1693                         free(t);
1694                         return 0;
1695                 }
1696
1697                 r = rmdir(t);
1698                 free(t);
1699
1700                 if (r < 0)
1701                         if (errno != ENOENT)
1702                                 return -errno;
1703         }
1704
1705         return 0;
1706 }
1707
1708
1709 char hexchar(int x) {
1710         static const char table[16] = "0123456789abcdef";
1711
1712         return table[x & 15];
1713 }
1714
1715 int unhexchar(char c) {
1716
1717         if (c >= '0' && c <= '9')
1718                 return c - '0';
1719
1720         if (c >= 'a' && c <= 'f')
1721                 return c - 'a' + 10;
1722
1723         if (c >= 'A' && c <= 'F')
1724                 return c - 'A' + 10;
1725
1726         return -1;
1727 }
1728
1729 char octchar(int x) {
1730         return '0' + (x & 7);
1731 }
1732
1733 int unoctchar(char c) {
1734
1735         if (c >= '0' && c <= '7')
1736                 return c - '0';
1737
1738         return -1;
1739 }
1740
1741 char decchar(int x) {
1742         return '0' + (x % 10);
1743 }
1744
1745 int undecchar(char c) {
1746
1747         if (c >= '0' && c <= '9')
1748                 return c - '0';
1749
1750         return -1;
1751 }
1752
1753 char *cescape(const char *s) {
1754         char *r, *t;
1755         const char *f;
1756
1757         assert(s);
1758
1759         /* Does C style string escaping. */
1760
1761         if (!(r = new(char, strlen(s)*4 + 1)))
1762                 return NULL;
1763
1764         for (f = s, t = r; *f; f++)
1765
1766                 switch (*f) {
1767
1768                 case '\a':
1769                         *(t++) = '\\';
1770                         *(t++) = 'a';
1771                         break;
1772                 case '\b':
1773                         *(t++) = '\\';
1774                         *(t++) = 'b';
1775                         break;
1776                 case '\f':
1777                         *(t++) = '\\';
1778                         *(t++) = 'f';
1779                         break;
1780                 case '\n':
1781                         *(t++) = '\\';
1782                         *(t++) = 'n';
1783                         break;
1784                 case '\r':
1785                         *(t++) = '\\';
1786                         *(t++) = 'r';
1787                         break;
1788                 case '\t':
1789                         *(t++) = '\\';
1790                         *(t++) = 't';
1791                         break;
1792                 case '\v':
1793                         *(t++) = '\\';
1794                         *(t++) = 'v';
1795                         break;
1796                 case '\\':
1797                         *(t++) = '\\';
1798                         *(t++) = '\\';
1799                         break;
1800                 case '"':
1801                         *(t++) = '\\';
1802                         *(t++) = '"';
1803                         break;
1804                 case '\'':
1805                         *(t++) = '\\';
1806                         *(t++) = '\'';
1807                         break;
1808
1809                 default:
1810                         /* For special chars we prefer octal over
1811                          * hexadecimal encoding, simply because glib's
1812                          * g_strescape() does the same */
1813                         if ((*f < ' ') || (*f >= 127)) {
1814                                 *(t++) = '\\';
1815                                 *(t++) = octchar((unsigned char) *f >> 6);
1816                                 *(t++) = octchar((unsigned char) *f >> 3);
1817                                 *(t++) = octchar((unsigned char) *f);
1818                         } else
1819                                 *(t++) = *f;
1820                         break;
1821                 }
1822
1823         *t = 0;
1824
1825         return r;
1826 }
1827
1828 char *cunescape_length(const char *s, size_t length) {
1829         char *r, *t;
1830         const char *f;
1831
1832         assert(s);
1833
1834         /* Undoes C style string escaping */
1835
1836         if (!(r = new(char, length+1)))
1837                 return r;
1838
1839         for (f = s, t = r; f < s + length; f++) {
1840
1841                 if (*f != '\\') {
1842                         *(t++) = *f;
1843                         continue;
1844                 }
1845
1846                 f++;
1847
1848                 switch (*f) {
1849
1850                 case 'a':
1851                         *(t++) = '\a';
1852                         break;
1853                 case 'b':
1854                         *(t++) = '\b';
1855                         break;
1856                 case 'f':
1857                         *(t++) = '\f';
1858                         break;
1859                 case 'n':
1860                         *(t++) = '\n';
1861                         break;
1862                 case 'r':
1863                         *(t++) = '\r';
1864                         break;
1865                 case 't':
1866                         *(t++) = '\t';
1867                         break;
1868                 case 'v':
1869                         *(t++) = '\v';
1870                         break;
1871                 case '\\':
1872                         *(t++) = '\\';
1873                         break;
1874                 case '"':
1875                         *(t++) = '"';
1876                         break;
1877                 case '\'':
1878                         *(t++) = '\'';
1879                         break;
1880
1881                 case 's':
1882                         /* This is an extension of the XDG syntax files */
1883                         *(t++) = ' ';
1884                         break;
1885
1886                 case 'x': {
1887                         /* hexadecimal encoding */
1888                         int a, b;
1889
1890                         if ((a = unhexchar(f[1])) < 0 ||
1891                             (b = unhexchar(f[2])) < 0) {
1892                                 /* Invalid escape code, let's take it literal then */
1893                                 *(t++) = '\\';
1894                                 *(t++) = 'x';
1895                         } else {
1896                                 *(t++) = (char) ((a << 4) | b);
1897                                 f += 2;
1898                         }
1899
1900                         break;
1901                 }
1902
1903                 case '0':
1904                 case '1':
1905                 case '2':
1906                 case '3':
1907                 case '4':
1908                 case '5':
1909                 case '6':
1910                 case '7': {
1911                         /* octal encoding */
1912                         int a, b, c;
1913
1914                         if ((a = unoctchar(f[0])) < 0 ||
1915                             (b = unoctchar(f[1])) < 0 ||
1916                             (c = unoctchar(f[2])) < 0) {
1917                                 /* Invalid escape code, let's take it literal then */
1918                                 *(t++) = '\\';
1919                                 *(t++) = f[0];
1920                         } else {
1921                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1922                                 f += 2;
1923                         }
1924
1925                         break;
1926                 }
1927
1928                 case 0:
1929                         /* premature end of string.*/
1930                         *(t++) = '\\';
1931                         goto finish;
1932
1933                 default:
1934                         /* Invalid escape code, let's take it literal then */
1935                         *(t++) = '\\';
1936                         *(t++) = *f;
1937                         break;
1938                 }
1939         }
1940
1941 finish:
1942         *t = 0;
1943         return r;
1944 }
1945
1946 char *cunescape(const char *s) {
1947         return cunescape_length(s, strlen(s));
1948 }
1949
1950 char *xescape(const char *s, const char *bad) {
1951         char *r, *t;
1952         const char *f;
1953
1954         /* Escapes all chars in bad, in addition to \ and all special
1955          * chars, in \xFF style escaping. May be reversed with
1956          * cunescape. */
1957
1958         if (!(r = new(char, strlen(s)*4+1)))
1959                 return NULL;
1960
1961         for (f = s, t = r; *f; f++) {
1962
1963                 if ((*f < ' ') || (*f >= 127) ||
1964                     (*f == '\\') || strchr(bad, *f)) {
1965                         *(t++) = '\\';
1966                         *(t++) = 'x';
1967                         *(t++) = hexchar(*f >> 4);
1968                         *(t++) = hexchar(*f);
1969                 } else
1970                         *(t++) = *f;
1971         }
1972
1973         *t = 0;
1974
1975         return r;
1976 }
1977
1978 char *bus_path_escape(const char *s) {
1979         char *r, *t;
1980         const char *f;
1981
1982         assert(s);
1983
1984         /* Escapes all chars that D-Bus' object path cannot deal
1985          * with. Can be reverse with bus_path_unescape() */
1986
1987         if (!(r = new(char, strlen(s)*3+1)))
1988                 return NULL;
1989
1990         for (f = s, t = r; *f; f++) {
1991
1992                 if (!(*f >= 'A' && *f <= 'Z') &&
1993                     !(*f >= 'a' && *f <= 'z') &&
1994                     !(*f >= '0' && *f <= '9')) {
1995                         *(t++) = '_';
1996                         *(t++) = hexchar(*f >> 4);
1997                         *(t++) = hexchar(*f);
1998                 } else
1999                         *(t++) = *f;
2000         }
2001
2002         *t = 0;
2003
2004         return r;
2005 }
2006
2007 char *bus_path_unescape(const char *f) {
2008         char *r, *t;
2009
2010         assert(f);
2011
2012         if (!(r = strdup(f)))
2013                 return NULL;
2014
2015         for (t = r; *f; f++) {
2016
2017                 if (*f == '_') {
2018                         int a, b;
2019
2020                         if ((a = unhexchar(f[1])) < 0 ||
2021                             (b = unhexchar(f[2])) < 0) {
2022                                 /* Invalid escape code, let's take it literal then */
2023                                 *(t++) = '_';
2024                         } else {
2025                                 *(t++) = (char) ((a << 4) | b);
2026                                 f += 2;
2027                         }
2028                 } else
2029                         *(t++) = *f;
2030         }
2031
2032         *t = 0;
2033
2034         return r;
2035 }
2036
2037 char *path_kill_slashes(char *path) {
2038         char *f, *t;
2039         bool slash = false;
2040
2041         /* Removes redundant inner and trailing slashes. Modifies the
2042          * passed string in-place.
2043          *
2044          * ///foo///bar/ becomes /foo/bar
2045          */
2046
2047         for (f = path, t = path; *f; f++) {
2048
2049                 if (*f == '/') {
2050                         slash = true;
2051                         continue;
2052                 }
2053
2054                 if (slash) {
2055                         slash = false;
2056                         *(t++) = '/';
2057                 }
2058
2059                 *(t++) = *f;
2060         }
2061
2062         /* Special rule, if we are talking of the root directory, a
2063         trailing slash is good */
2064
2065         if (t == path && slash)
2066                 *(t++) = '/';
2067
2068         *t = 0;
2069         return path;
2070 }
2071
2072 bool path_startswith(const char *path, const char *prefix) {
2073         assert(path);
2074         assert(prefix);
2075
2076         if ((path[0] == '/') != (prefix[0] == '/'))
2077                 return false;
2078
2079         for (;;) {
2080                 size_t a, b;
2081
2082                 path += strspn(path, "/");
2083                 prefix += strspn(prefix, "/");
2084
2085                 if (*prefix == 0)
2086                         return true;
2087
2088                 if (*path == 0)
2089                         return false;
2090
2091                 a = strcspn(path, "/");
2092                 b = strcspn(prefix, "/");
2093
2094                 if (a != b)
2095                         return false;
2096
2097                 if (memcmp(path, prefix, a) != 0)
2098                         return false;
2099
2100                 path += a;
2101                 prefix += b;
2102         }
2103 }
2104
2105 bool path_equal(const char *a, const char *b) {
2106         assert(a);
2107         assert(b);
2108
2109         if ((a[0] == '/') != (b[0] == '/'))
2110                 return false;
2111
2112         for (;;) {
2113                 size_t j, k;
2114
2115                 a += strspn(a, "/");
2116                 b += strspn(b, "/");
2117
2118                 if (*a == 0 && *b == 0)
2119                         return true;
2120
2121                 if (*a == 0 || *b == 0)
2122                         return false;
2123
2124                 j = strcspn(a, "/");
2125                 k = strcspn(b, "/");
2126
2127                 if (j != k)
2128                         return false;
2129
2130                 if (memcmp(a, b, j) != 0)
2131                         return false;
2132
2133                 a += j;
2134                 b += k;
2135         }
2136 }
2137
2138 char *ascii_strlower(char *t) {
2139         char *p;
2140
2141         assert(t);
2142
2143         for (p = t; *p; p++)
2144                 if (*p >= 'A' && *p <= 'Z')
2145                         *p = *p - 'A' + 'a';
2146
2147         return t;
2148 }
2149
2150 bool ignore_file(const char *filename) {
2151         assert(filename);
2152
2153         return
2154                 filename[0] == '.' ||
2155                 streq(filename, "lost+found") ||
2156                 streq(filename, "aquota.user") ||
2157                 streq(filename, "aquota.group") ||
2158                 endswith(filename, "~") ||
2159                 endswith(filename, ".rpmnew") ||
2160                 endswith(filename, ".rpmsave") ||
2161                 endswith(filename, ".rpmorig") ||
2162                 endswith(filename, ".dpkg-old") ||
2163                 endswith(filename, ".dpkg-new") ||
2164                 endswith(filename, ".swp");
2165 }
2166
2167 int fd_nonblock(int fd, bool nonblock) {
2168         int flags;
2169
2170         assert(fd >= 0);
2171
2172         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
2173                 return -errno;
2174
2175         if (nonblock)
2176                 flags |= O_NONBLOCK;
2177         else
2178                 flags &= ~O_NONBLOCK;
2179
2180         if (fcntl(fd, F_SETFL, flags) < 0)
2181                 return -errno;
2182
2183         return 0;
2184 }
2185
2186 int fd_cloexec(int fd, bool cloexec) {
2187         int flags;
2188
2189         assert(fd >= 0);
2190
2191         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
2192                 return -errno;
2193
2194         if (cloexec)
2195                 flags |= FD_CLOEXEC;
2196         else
2197                 flags &= ~FD_CLOEXEC;
2198
2199         if (fcntl(fd, F_SETFD, flags) < 0)
2200                 return -errno;
2201
2202         return 0;
2203 }
2204
2205 int close_all_fds(const int except[], unsigned n_except) {
2206         DIR *d;
2207         struct dirent *de;
2208         int r = 0;
2209
2210         if (!(d = opendir("/proc/self/fd")))
2211                 return -errno;
2212
2213         while ((de = readdir(d))) {
2214                 int fd = -1;
2215
2216                 if (ignore_file(de->d_name))
2217                         continue;
2218
2219                 if (safe_atoi(de->d_name, &fd) < 0)
2220                         /* Let's better ignore this, just in case */
2221                         continue;
2222
2223                 if (fd < 3)
2224                         continue;
2225
2226                 if (fd == dirfd(d))
2227                         continue;
2228
2229                 if (except) {
2230                         bool found;
2231                         unsigned i;
2232
2233                         found = false;
2234                         for (i = 0; i < n_except; i++)
2235                                 if (except[i] == fd) {
2236                                         found = true;
2237                                         break;
2238                                 }
2239
2240                         if (found)
2241                                 continue;
2242                 }
2243
2244                 if (close_nointr(fd) < 0) {
2245                         /* Valgrind has its own FD and doesn't want to have it closed */
2246                         if (errno != EBADF && r == 0)
2247                                 r = -errno;
2248                 }
2249         }
2250
2251         closedir(d);
2252         return r;
2253 }
2254
2255 bool chars_intersect(const char *a, const char *b) {
2256         const char *p;
2257
2258         /* Returns true if any of the chars in a are in b. */
2259         for (p = a; *p; p++)
2260                 if (strchr(b, *p))
2261                         return true;
2262
2263         return false;
2264 }
2265
2266 char *format_timestamp(char *buf, size_t l, usec_t t) {
2267         struct tm tm;
2268         time_t sec;
2269
2270         assert(buf);
2271         assert(l > 0);
2272
2273         if (t <= 0)
2274                 return NULL;
2275
2276         sec = (time_t) (t / USEC_PER_SEC);
2277
2278         if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
2279                 return NULL;
2280
2281         return buf;
2282 }
2283
2284 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
2285         usec_t n, d;
2286
2287         n = now(CLOCK_REALTIME);
2288
2289         if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
2290                 return NULL;
2291
2292         d = n - t;
2293
2294         if (d >= USEC_PER_YEAR)
2295                 snprintf(buf, l, "%llu years and %llu months ago",
2296                          (unsigned long long) (d / USEC_PER_YEAR),
2297                          (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
2298         else if (d >= USEC_PER_MONTH)
2299                 snprintf(buf, l, "%llu months and %llu days ago",
2300                          (unsigned long long) (d / USEC_PER_MONTH),
2301                          (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
2302         else if (d >= USEC_PER_WEEK)
2303                 snprintf(buf, l, "%llu weeks and %llu days ago",
2304                          (unsigned long long) (d / USEC_PER_WEEK),
2305                          (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
2306         else if (d >= 2*USEC_PER_DAY)
2307                 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
2308         else if (d >= 25*USEC_PER_HOUR)
2309                 snprintf(buf, l, "1 day and %lluh ago",
2310                          (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
2311         else if (d >= 6*USEC_PER_HOUR)
2312                 snprintf(buf, l, "%lluh ago",
2313                          (unsigned long long) (d / USEC_PER_HOUR));
2314         else if (d >= USEC_PER_HOUR)
2315                 snprintf(buf, l, "%lluh %llumin ago",
2316                          (unsigned long long) (d / USEC_PER_HOUR),
2317                          (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
2318         else if (d >= 5*USEC_PER_MINUTE)
2319                 snprintf(buf, l, "%llumin ago",
2320                          (unsigned long long) (d / USEC_PER_MINUTE));
2321         else if (d >= USEC_PER_MINUTE)
2322                 snprintf(buf, l, "%llumin %llus ago",
2323                          (unsigned long long) (d / USEC_PER_MINUTE),
2324                          (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2325         else if (d >= USEC_PER_SEC)
2326                 snprintf(buf, l, "%llus ago",
2327                          (unsigned long long) (d / USEC_PER_SEC));
2328         else if (d >= USEC_PER_MSEC)
2329                 snprintf(buf, l, "%llums ago",
2330                          (unsigned long long) (d / USEC_PER_MSEC));
2331         else if (d > 0)
2332                 snprintf(buf, l, "%lluus ago",
2333                          (unsigned long long) d);
2334         else
2335                 snprintf(buf, l, "now");
2336
2337         buf[l-1] = 0;
2338         return buf;
2339 }
2340
2341 char *format_timespan(char *buf, size_t l, usec_t t) {
2342         static const struct {
2343                 const char *suffix;
2344                 usec_t usec;
2345         } table[] = {
2346                 { "w", USEC_PER_WEEK },
2347                 { "d", USEC_PER_DAY },
2348                 { "h", USEC_PER_HOUR },
2349                 { "min", USEC_PER_MINUTE },
2350                 { "s", USEC_PER_SEC },
2351                 { "ms", USEC_PER_MSEC },
2352                 { "us", 1 },
2353         };
2354
2355         unsigned i;
2356         char *p = buf;
2357
2358         assert(buf);
2359         assert(l > 0);
2360
2361         if (t == (usec_t) -1)
2362                 return NULL;
2363
2364         if (t == 0) {
2365                 snprintf(p, l, "0");
2366                 p[l-1] = 0;
2367                 return p;
2368         }
2369
2370         /* The result of this function can be parsed with parse_usec */
2371
2372         for (i = 0; i < ELEMENTSOF(table); i++) {
2373                 int k;
2374                 size_t n;
2375
2376                 if (t < table[i].usec)
2377                         continue;
2378
2379                 if (l <= 1)
2380                         break;
2381
2382                 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2383                 n = MIN((size_t) k, l);
2384
2385                 l -= n;
2386                 p += n;
2387
2388                 t %= table[i].usec;
2389         }
2390
2391         *p = 0;
2392
2393         return buf;
2394 }
2395
2396 bool fstype_is_network(const char *fstype) {
2397         static const char * const table[] = {
2398                 "cifs",
2399                 "smbfs",
2400                 "ncpfs",
2401                 "nfs",
2402                 "nfs4",
2403                 "gfs",
2404                 "gfs2"
2405         };
2406
2407         unsigned i;
2408
2409         for (i = 0; i < ELEMENTSOF(table); i++)
2410                 if (streq(table[i], fstype))
2411                         return true;
2412
2413         return false;
2414 }
2415
2416 int chvt(int vt) {
2417         int fd, r = 0;
2418
2419         if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2420                 return -errno;
2421
2422         if (vt < 0) {
2423                 int tiocl[2] = {
2424                         TIOCL_GETKMSGREDIRECT,
2425                         0
2426                 };
2427
2428                 if (ioctl(fd, TIOCLINUX, tiocl) < 0) {
2429                         r = -errno;
2430                         goto fail;
2431                 }
2432
2433                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2434         }
2435
2436         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2437                 r = -errno;
2438
2439 fail:
2440         close_nointr_nofail(fd);
2441         return r;
2442 }
2443
2444 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2445         struct termios old_termios, new_termios;
2446         char c;
2447         char line[LINE_MAX];
2448
2449         assert(f);
2450         assert(ret);
2451
2452         if (tcgetattr(fileno(f), &old_termios) >= 0) {
2453                 new_termios = old_termios;
2454
2455                 new_termios.c_lflag &= ~ICANON;
2456                 new_termios.c_cc[VMIN] = 1;
2457                 new_termios.c_cc[VTIME] = 0;
2458
2459                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2460                         size_t k;
2461
2462                         if (t != (usec_t) -1) {
2463                                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2464                                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2465                                         return -ETIMEDOUT;
2466                                 }
2467                         }
2468
2469                         k = fread(&c, 1, 1, f);
2470
2471                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2472
2473                         if (k <= 0)
2474                                 return -EIO;
2475
2476                         if (need_nl)
2477                                 *need_nl = c != '\n';
2478
2479                         *ret = c;
2480                         return 0;
2481                 }
2482         }
2483
2484         if (t != (usec_t) -1)
2485                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2486                         return -ETIMEDOUT;
2487
2488         if (!fgets(line, sizeof(line), f))
2489                 return -EIO;
2490
2491         truncate_nl(line);
2492
2493         if (strlen(line) != 1)
2494                 return -EBADMSG;
2495
2496         if (need_nl)
2497                 *need_nl = false;
2498
2499         *ret = line[0];
2500         return 0;
2501 }
2502
2503 int ask(char *ret, const char *replies, const char *text, ...) {
2504         bool on_tty;
2505
2506         assert(ret);
2507         assert(replies);
2508         assert(text);
2509
2510         on_tty = isatty(STDOUT_FILENO);
2511
2512         for (;;) {
2513                 va_list ap;
2514                 char c;
2515                 int r;
2516                 bool need_nl = true;
2517
2518                 if (on_tty)
2519                         fputs(ANSI_HIGHLIGHT_ON, stdout);
2520
2521                 va_start(ap, text);
2522                 vprintf(text, ap);
2523                 va_end(ap);
2524
2525                 if (on_tty)
2526                         fputs(ANSI_HIGHLIGHT_OFF, stdout);
2527
2528                 fflush(stdout);
2529
2530                 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2531                 if (r < 0) {
2532
2533                         if (r == -EBADMSG) {
2534                                 puts("Bad input, please try again.");
2535                                 continue;
2536                         }
2537
2538                         putchar('\n');
2539                         return r;
2540                 }
2541
2542                 if (need_nl)
2543                         putchar('\n');
2544
2545                 if (strchr(replies, c)) {
2546                         *ret = c;
2547                         return 0;
2548                 }
2549
2550                 puts("Read unexpected character, please try again.");
2551         }
2552 }
2553
2554 int reset_terminal_fd(int fd, bool switch_to_text) {
2555         struct termios termios;
2556         int r = 0;
2557
2558         /* Set terminal to some sane defaults */
2559
2560         assert(fd >= 0);
2561
2562         /* We leave locked terminal attributes untouched, so that
2563          * Plymouth may set whatever it wants to set, and we don't
2564          * interfere with that. */
2565
2566         /* Disable exclusive mode, just in case */
2567         ioctl(fd, TIOCNXCL);
2568
2569         /* Switch to text mode */
2570         if (switch_to_text)
2571                 ioctl(fd, KDSETMODE, KD_TEXT);
2572
2573         /* Enable console unicode mode */
2574         ioctl(fd, KDSKBMODE, K_UNICODE);
2575
2576         if (tcgetattr(fd, &termios) < 0) {
2577                 r = -errno;
2578                 goto finish;
2579         }
2580
2581         /* We only reset the stuff that matters to the software. How
2582          * hardware is set up we don't touch assuming that somebody
2583          * else will do that for us */
2584
2585         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2586         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2587         termios.c_oflag |= ONLCR;
2588         termios.c_cflag |= CREAD;
2589         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2590
2591         termios.c_cc[VINTR]    =   03;  /* ^C */
2592         termios.c_cc[VQUIT]    =  034;  /* ^\ */
2593         termios.c_cc[VERASE]   = 0177;
2594         termios.c_cc[VKILL]    =  025;  /* ^X */
2595         termios.c_cc[VEOF]     =   04;  /* ^D */
2596         termios.c_cc[VSTART]   =  021;  /* ^Q */
2597         termios.c_cc[VSTOP]    =  023;  /* ^S */
2598         termios.c_cc[VSUSP]    =  032;  /* ^Z */
2599         termios.c_cc[VLNEXT]   =  026;  /* ^V */
2600         termios.c_cc[VWERASE]  =  027;  /* ^W */
2601         termios.c_cc[VREPRINT] =  022;  /* ^R */
2602         termios.c_cc[VEOL]     =    0;
2603         termios.c_cc[VEOL2]    =    0;
2604
2605         termios.c_cc[VTIME]  = 0;
2606         termios.c_cc[VMIN]   = 1;
2607
2608         if (tcsetattr(fd, TCSANOW, &termios) < 0)
2609                 r = -errno;
2610
2611 finish:
2612         /* Just in case, flush all crap out */
2613         tcflush(fd, TCIOFLUSH);
2614
2615         return r;
2616 }
2617
2618 int reset_terminal(const char *name) {
2619         int fd, r;
2620
2621         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2622         if (fd < 0)
2623                 return fd;
2624
2625         r = reset_terminal_fd(fd, true);
2626         close_nointr_nofail(fd);
2627
2628         return r;
2629 }
2630
2631 int open_terminal(const char *name, int mode) {
2632         int fd, r;
2633         unsigned c = 0;
2634
2635         /*
2636          * If a TTY is in the process of being closed opening it might
2637          * cause EIO. This is horribly awful, but unlikely to be
2638          * changed in the kernel. Hence we work around this problem by
2639          * retrying a couple of times.
2640          *
2641          * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2642          */
2643
2644         for (;;) {
2645                 if ((fd = open(name, mode)) >= 0)
2646                         break;
2647
2648                 if (errno != EIO)
2649                         return -errno;
2650
2651                 if (c >= 20)
2652                         return -errno;
2653
2654                 usleep(50 * USEC_PER_MSEC);
2655                 c++;
2656         }
2657
2658         if (fd < 0)
2659                 return -errno;
2660
2661         if ((r = isatty(fd)) < 0) {
2662                 close_nointr_nofail(fd);
2663                 return -errno;
2664         }
2665
2666         if (!r) {
2667                 close_nointr_nofail(fd);
2668                 return -ENOTTY;
2669         }
2670
2671         return fd;
2672 }
2673
2674 int flush_fd(int fd) {
2675         struct pollfd pollfd;
2676
2677         zero(pollfd);
2678         pollfd.fd = fd;
2679         pollfd.events = POLLIN;
2680
2681         for (;;) {
2682                 char buf[LINE_MAX];
2683                 ssize_t l;
2684                 int r;
2685
2686                 if ((r = poll(&pollfd, 1, 0)) < 0) {
2687
2688                         if (errno == EINTR)
2689                                 continue;
2690
2691                         return -errno;
2692                 }
2693
2694                 if (r == 0)
2695                         return 0;
2696
2697                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2698
2699                         if (errno == EINTR)
2700                                 continue;
2701
2702                         if (errno == EAGAIN)
2703                                 return 0;
2704
2705                         return -errno;
2706                 }
2707
2708                 if (l <= 0)
2709                         return 0;
2710         }
2711 }
2712
2713 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2714         int fd = -1, notify = -1, r, wd = -1;
2715
2716         assert(name);
2717
2718         /* We use inotify to be notified when the tty is closed. We
2719          * create the watch before checking if we can actually acquire
2720          * it, so that we don't lose any event.
2721          *
2722          * Note: strictly speaking this actually watches for the
2723          * device being closed, it does *not* really watch whether a
2724          * tty loses its controlling process. However, unless some
2725          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2726          * its tty otherwise this will not become a problem. As long
2727          * as the administrator makes sure not configure any service
2728          * on the same tty as an untrusted user this should not be a
2729          * problem. (Which he probably should not do anyway.) */
2730
2731         if (!fail && !force) {
2732                 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2733                         r = -errno;
2734                         goto fail;
2735                 }
2736
2737                 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2738                         r = -errno;
2739                         goto fail;
2740                 }
2741         }
2742
2743         for (;;) {
2744                 if (notify >= 0)
2745                         if ((r = flush_fd(notify)) < 0)
2746                                 goto fail;
2747
2748                 /* We pass here O_NOCTTY only so that we can check the return
2749                  * value TIOCSCTTY and have a reliable way to figure out if we
2750                  * successfully became the controlling process of the tty */
2751                 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2752                         return fd;
2753
2754                 /* First, try to get the tty */
2755                 r = ioctl(fd, TIOCSCTTY, force);
2756
2757                 /* Sometimes it makes sense to ignore TIOCSCTTY
2758                  * returning EPERM, i.e. when very likely we already
2759                  * are have this controlling terminal. */
2760                 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2761                         r = 0;
2762
2763                 if (r < 0 && (force || fail || errno != EPERM)) {
2764                         r = -errno;
2765                         goto fail;
2766                 }
2767
2768                 if (r >= 0)
2769                         break;
2770
2771                 assert(!fail);
2772                 assert(!force);
2773                 assert(notify >= 0);
2774
2775                 for (;;) {
2776                         uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2777                         ssize_t l;
2778                         struct inotify_event *e;
2779
2780                         if ((l = read(notify, inotify_buffer, sizeof(inotify_buffer))) < 0) {
2781
2782                                 if (errno == EINTR)
2783                                         continue;
2784
2785                                 r = -errno;
2786                                 goto fail;
2787                         }
2788
2789                         e = (struct inotify_event*) inotify_buffer;
2790
2791                         while (l > 0) {
2792                                 size_t step;
2793
2794                                 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2795                                         r = -EIO;
2796                                         goto fail;
2797                                 }
2798
2799                                 step = sizeof(struct inotify_event) + e->len;
2800                                 assert(step <= (size_t) l);
2801
2802                                 e = (struct inotify_event*) ((uint8_t*) e + step);
2803                                 l -= step;
2804                         }
2805
2806                         break;
2807                 }
2808
2809                 /* We close the tty fd here since if the old session
2810                  * ended our handle will be dead. It's important that
2811                  * we do this after sleeping, so that we don't enter
2812                  * an endless loop. */
2813                 close_nointr_nofail(fd);
2814         }
2815
2816         if (notify >= 0)
2817                 close_nointr_nofail(notify);
2818
2819         r = reset_terminal_fd(fd, true);
2820         if (r < 0)
2821                 log_warning("Failed to reset terminal: %s", strerror(-r));
2822
2823         return fd;
2824
2825 fail:
2826         if (fd >= 0)
2827                 close_nointr_nofail(fd);
2828
2829         if (notify >= 0)
2830                 close_nointr_nofail(notify);
2831
2832         return r;
2833 }
2834
2835 int release_terminal(void) {
2836         int r = 0, fd;
2837         struct sigaction sa_old, sa_new;
2838
2839         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2840                 return -errno;
2841
2842         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2843          * by our own TIOCNOTTY */
2844
2845         zero(sa_new);
2846         sa_new.sa_handler = SIG_IGN;
2847         sa_new.sa_flags = SA_RESTART;
2848         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2849
2850         if (ioctl(fd, TIOCNOTTY) < 0)
2851                 r = -errno;
2852
2853         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2854
2855         close_nointr_nofail(fd);
2856         return r;
2857 }
2858
2859 int sigaction_many(const struct sigaction *sa, ...) {
2860         va_list ap;
2861         int r = 0, sig;
2862
2863         va_start(ap, sa);
2864         while ((sig = va_arg(ap, int)) > 0)
2865                 if (sigaction(sig, sa, NULL) < 0)
2866                         r = -errno;
2867         va_end(ap);
2868
2869         return r;
2870 }
2871
2872 int ignore_signals(int sig, ...) {
2873         struct sigaction sa;
2874         va_list ap;
2875         int r = 0;
2876
2877         zero(sa);
2878         sa.sa_handler = SIG_IGN;
2879         sa.sa_flags = SA_RESTART;
2880
2881         if (sigaction(sig, &sa, NULL) < 0)
2882                 r = -errno;
2883
2884         va_start(ap, sig);
2885         while ((sig = va_arg(ap, int)) > 0)
2886                 if (sigaction(sig, &sa, NULL) < 0)
2887                         r = -errno;
2888         va_end(ap);
2889
2890         return r;
2891 }
2892
2893 int default_signals(int sig, ...) {
2894         struct sigaction sa;
2895         va_list ap;
2896         int r = 0;
2897
2898         zero(sa);
2899         sa.sa_handler = SIG_DFL;
2900         sa.sa_flags = SA_RESTART;
2901
2902         if (sigaction(sig, &sa, NULL) < 0)
2903                 r = -errno;
2904
2905         va_start(ap, sig);
2906         while ((sig = va_arg(ap, int)) > 0)
2907                 if (sigaction(sig, &sa, NULL) < 0)
2908                         r = -errno;
2909         va_end(ap);
2910
2911         return r;
2912 }
2913
2914 int close_pipe(int p[]) {
2915         int a = 0, b = 0;
2916
2917         assert(p);
2918
2919         if (p[0] >= 0) {
2920                 a = close_nointr(p[0]);
2921                 p[0] = -1;
2922         }
2923
2924         if (p[1] >= 0) {
2925                 b = close_nointr(p[1]);
2926                 p[1] = -1;
2927         }
2928
2929         return a < 0 ? a : b;
2930 }
2931
2932 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2933         uint8_t *p;
2934         ssize_t n = 0;
2935
2936         assert(fd >= 0);
2937         assert(buf);
2938
2939         p = buf;
2940
2941         while (nbytes > 0) {
2942                 ssize_t k;
2943
2944                 if ((k = read(fd, p, nbytes)) <= 0) {
2945
2946                         if (k < 0 && errno == EINTR)
2947                                 continue;
2948
2949                         if (k < 0 && errno == EAGAIN && do_poll) {
2950                                 struct pollfd pollfd;
2951
2952                                 zero(pollfd);
2953                                 pollfd.fd = fd;
2954                                 pollfd.events = POLLIN;
2955
2956                                 if (poll(&pollfd, 1, -1) < 0) {
2957                                         if (errno == EINTR)
2958                                                 continue;
2959
2960                                         return n > 0 ? n : -errno;
2961                                 }
2962
2963                                 if (pollfd.revents != POLLIN)
2964                                         return n > 0 ? n : -EIO;
2965
2966                                 continue;
2967                         }
2968
2969                         return n > 0 ? n : (k < 0 ? -errno : 0);
2970                 }
2971
2972                 p += k;
2973                 nbytes -= k;
2974                 n += k;
2975         }
2976
2977         return n;
2978 }
2979
2980 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2981         const uint8_t *p;
2982         ssize_t n = 0;
2983
2984         assert(fd >= 0);
2985         assert(buf);
2986
2987         p = buf;
2988
2989         while (nbytes > 0) {
2990                 ssize_t k;
2991
2992                 k = write(fd, p, nbytes);
2993                 if (k <= 0) {
2994
2995                         if (k < 0 && errno == EINTR)
2996                                 continue;
2997
2998                         if (k < 0 && errno == EAGAIN && do_poll) {
2999                                 struct pollfd pollfd;
3000
3001                                 zero(pollfd);
3002                                 pollfd.fd = fd;
3003                                 pollfd.events = POLLOUT;
3004
3005                                 if (poll(&pollfd, 1, -1) < 0) {
3006                                         if (errno == EINTR)
3007                                                 continue;
3008
3009                                         return n > 0 ? n : -errno;
3010                                 }
3011
3012                                 if (pollfd.revents != POLLOUT)
3013                                         return n > 0 ? n : -EIO;
3014
3015                                 continue;
3016                         }
3017
3018                         return n > 0 ? n : (k < 0 ? -errno : 0);
3019                 }
3020
3021                 p += k;
3022                 nbytes -= k;
3023                 n += k;
3024         }
3025
3026         return n;
3027 }
3028
3029 int path_is_mount_point(const char *t, bool allow_symlink) {
3030         struct stat a, b;
3031         char *parent;
3032         int r;
3033
3034         if (allow_symlink)
3035                 r = stat(t, &a);
3036         else
3037                 r = lstat(t, &a);
3038
3039         if (r < 0) {
3040                 if (errno == ENOENT)
3041                         return 0;
3042
3043                 return -errno;
3044         }
3045
3046         r = parent_of_path(t, &parent);
3047         if (r < 0)
3048                 return r;
3049
3050         r = lstat(parent, &b);
3051         free(parent);
3052
3053         if (r < 0)
3054                 return -errno;
3055
3056         return a.st_dev != b.st_dev;
3057 }
3058
3059 int parse_usec(const char *t, usec_t *usec) {
3060         static const struct {
3061                 const char *suffix;
3062                 usec_t usec;
3063         } table[] = {
3064                 { "sec", USEC_PER_SEC },
3065                 { "s", USEC_PER_SEC },
3066                 { "min", USEC_PER_MINUTE },
3067                 { "hr", USEC_PER_HOUR },
3068                 { "h", USEC_PER_HOUR },
3069                 { "d", USEC_PER_DAY },
3070                 { "w", USEC_PER_WEEK },
3071                 { "msec", USEC_PER_MSEC },
3072                 { "ms", USEC_PER_MSEC },
3073                 { "m", USEC_PER_MINUTE },
3074                 { "usec", 1ULL },
3075                 { "us", 1ULL },
3076                 { "", USEC_PER_SEC },
3077         };
3078
3079         const char *p;
3080         usec_t r = 0;
3081
3082         assert(t);
3083         assert(usec);
3084
3085         p = t;
3086         do {
3087                 long long l;
3088                 char *e;
3089                 unsigned i;
3090
3091                 errno = 0;
3092                 l = strtoll(p, &e, 10);
3093
3094                 if (errno != 0)
3095                         return -errno;
3096
3097                 if (l < 0)
3098                         return -ERANGE;
3099
3100                 if (e == p)
3101                         return -EINVAL;
3102
3103                 e += strspn(e, WHITESPACE);
3104
3105                 for (i = 0; i < ELEMENTSOF(table); i++)
3106                         if (startswith(e, table[i].suffix)) {
3107                                 r += (usec_t) l * table[i].usec;
3108                                 p = e + strlen(table[i].suffix);
3109                                 break;
3110                         }
3111
3112                 if (i >= ELEMENTSOF(table))
3113                         return -EINVAL;
3114
3115         } while (*p != 0);
3116
3117         *usec = r;
3118
3119         return 0;
3120 }
3121
3122 int parse_bytes(const char *t, off_t *bytes) {
3123         static const struct {
3124                 const char *suffix;
3125                 off_t factor;
3126         } table[] = {
3127                 { "B", 1 },
3128                 { "K", 1024ULL },
3129                 { "M", 1024ULL*1024ULL },
3130                 { "G", 1024ULL*1024ULL*1024ULL },
3131                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3132                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3133                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
3134                 { "", 1 },
3135         };
3136
3137         const char *p;
3138         off_t r = 0;
3139
3140         assert(t);
3141         assert(bytes);
3142
3143         p = t;
3144         do {
3145                 long long l;
3146                 char *e;
3147                 unsigned i;
3148
3149                 errno = 0;
3150                 l = strtoll(p, &e, 10);
3151
3152                 if (errno != 0)
3153                         return -errno;
3154
3155                 if (l < 0)
3156                         return -ERANGE;
3157
3158                 if (e == p)
3159                         return -EINVAL;
3160
3161                 e += strspn(e, WHITESPACE);
3162
3163                 for (i = 0; i < ELEMENTSOF(table); i++)
3164                         if (startswith(e, table[i].suffix)) {
3165                                 r += (off_t) l * table[i].factor;
3166                                 p = e + strlen(table[i].suffix);
3167                                 break;
3168                         }
3169
3170                 if (i >= ELEMENTSOF(table))
3171                         return -EINVAL;
3172
3173         } while (*p != 0);
3174
3175         *bytes = r;
3176
3177         return 0;
3178 }
3179
3180 int make_stdio(int fd) {
3181         int r, s, t;
3182
3183         assert(fd >= 0);
3184
3185         r = dup2(fd, STDIN_FILENO);
3186         s = dup2(fd, STDOUT_FILENO);
3187         t = dup2(fd, STDERR_FILENO);
3188
3189         if (fd >= 3)
3190                 close_nointr_nofail(fd);
3191
3192         if (r < 0 || s < 0 || t < 0)
3193                 return -errno;
3194
3195         fd_cloexec(STDIN_FILENO, false);
3196         fd_cloexec(STDOUT_FILENO, false);
3197         fd_cloexec(STDERR_FILENO, false);
3198
3199         return 0;
3200 }
3201
3202 int make_null_stdio(void) {
3203         int null_fd;
3204
3205         if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3206                 return -errno;
3207
3208         return make_stdio(null_fd);
3209 }
3210
3211 bool is_device_path(const char *path) {
3212
3213         /* Returns true on paths that refer to a device, either in
3214          * sysfs or in /dev */
3215
3216         return
3217                 path_startswith(path, "/dev/") ||
3218                 path_startswith(path, "/sys/");
3219 }
3220
3221 int dir_is_empty(const char *path) {
3222         DIR *d;
3223         int r;
3224         struct dirent buf, *de;
3225
3226         if (!(d = opendir(path)))
3227                 return -errno;
3228
3229         for (;;) {
3230                 if ((r = readdir_r(d, &buf, &de)) > 0) {
3231                         r = -r;
3232                         break;
3233                 }
3234
3235                 if (!de) {
3236                         r = 1;
3237                         break;
3238                 }
3239
3240                 if (!ignore_file(de->d_name)) {
3241                         r = 0;
3242                         break;
3243                 }
3244         }
3245
3246         closedir(d);
3247         return r;
3248 }
3249
3250 unsigned long long random_ull(void) {
3251         int fd;
3252         uint64_t ull;
3253         ssize_t r;
3254
3255         if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3256                 goto fallback;
3257
3258         r = loop_read(fd, &ull, sizeof(ull), true);
3259         close_nointr_nofail(fd);
3260
3261         if (r != sizeof(ull))
3262                 goto fallback;
3263
3264         return ull;
3265
3266 fallback:
3267         return random() * RAND_MAX + random();
3268 }
3269
3270 void rename_process(const char name[8]) {
3271         assert(name);
3272
3273         /* This is a like a poor man's setproctitle(). It changes the
3274          * comm field, argv[0], and also the glibc's internally used
3275          * name of the process. For the first one a limit of 16 chars
3276          * applies, to the second one usually one of 10 (i.e. length
3277          * of "/sbin/init"), to the third one one of 7 (i.e. length of
3278          * "systemd"). If you pass a longer string it will be
3279          * truncated */
3280
3281         prctl(PR_SET_NAME, name);
3282
3283         if (program_invocation_name)
3284                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3285
3286         if (saved_argc > 0) {
3287                 int i;
3288
3289                 if (saved_argv[0])
3290                         strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3291
3292                 for (i = 1; i < saved_argc; i++) {
3293                         if (!saved_argv[i])
3294                                 break;
3295
3296                         memset(saved_argv[i], 0, strlen(saved_argv[i]));
3297                 }
3298         }
3299 }
3300
3301 void sigset_add_many(sigset_t *ss, ...) {
3302         va_list ap;
3303         int sig;
3304
3305         assert(ss);
3306
3307         va_start(ap, ss);
3308         while ((sig = va_arg(ap, int)) > 0)
3309                 assert_se(sigaddset(ss, sig) == 0);
3310         va_end(ap);
3311 }
3312
3313 char* gethostname_malloc(void) {
3314         struct utsname u;
3315
3316         assert_se(uname(&u) >= 0);
3317
3318         if (u.nodename[0])
3319                 return strdup(u.nodename);
3320
3321         return strdup(u.sysname);
3322 }
3323
3324 char* getlogname_malloc(void) {
3325         uid_t uid;
3326         long bufsize;
3327         char *buf, *name;
3328         struct passwd pwbuf, *pw = NULL;
3329         struct stat st;
3330
3331         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3332                 uid = st.st_uid;
3333         else
3334                 uid = getuid();
3335
3336         /* Shortcut things to avoid NSS lookups */
3337         if (uid == 0)
3338                 return strdup("root");
3339
3340         if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3341                 bufsize = 4096;
3342
3343         if (!(buf = malloc(bufsize)))
3344                 return NULL;
3345
3346         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3347                 name = strdup(pw->pw_name);
3348                 free(buf);
3349                 return name;
3350         }
3351
3352         free(buf);
3353
3354         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3355                 return NULL;
3356
3357         return name;
3358 }
3359
3360 int getttyname_malloc(int fd, char **r) {
3361         char path[PATH_MAX], *c;
3362         int k;
3363
3364         assert(r);
3365
3366         if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3367                 return -k;
3368
3369         char_array_0(path);
3370
3371         if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3372                 return -ENOMEM;
3373
3374         *r = c;
3375         return 0;
3376 }
3377
3378 int getttyname_harder(int fd, char **r) {
3379         int k;
3380         char *s;
3381
3382         if ((k = getttyname_malloc(fd, &s)) < 0)
3383                 return k;
3384
3385         if (streq(s, "tty")) {
3386                 free(s);
3387                 return get_ctty(0, NULL, r);
3388         }
3389
3390         *r = s;
3391         return 0;
3392 }
3393
3394 int get_ctty_devnr(pid_t pid, dev_t *d) {
3395         int k;
3396         char line[LINE_MAX], *p, *fn;
3397         unsigned long ttynr;
3398         FILE *f;
3399
3400         if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3401                 return -ENOMEM;
3402
3403         f = fopen(fn, "re");
3404         free(fn);
3405         if (!f)
3406                 return -errno;
3407
3408         if (!fgets(line, sizeof(line), f)) {
3409                 k = feof(f) ? -EIO : -errno;
3410                 fclose(f);
3411                 return k;
3412         }
3413
3414         fclose(f);
3415
3416         p = strrchr(line, ')');
3417         if (!p)
3418                 return -EIO;
3419
3420         p++;
3421
3422         if (sscanf(p, " "
3423                    "%*c "  /* state */
3424                    "%*d "  /* ppid */
3425                    "%*d "  /* pgrp */
3426                    "%*d "  /* session */
3427                    "%lu ", /* ttynr */
3428                    &ttynr) != 1)
3429                 return -EIO;
3430
3431         *d = (dev_t) ttynr;
3432         return 0;
3433 }
3434
3435 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3436         int k;
3437         char fn[PATH_MAX], *s, *b, *p;
3438         dev_t devnr;
3439
3440         assert(r);
3441
3442         k = get_ctty_devnr(pid, &devnr);
3443         if (k < 0)
3444                 return k;
3445
3446         snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3447         char_array_0(fn);
3448
3449         if ((k = readlink_malloc(fn, &s)) < 0) {
3450
3451                 if (k != -ENOENT)
3452                         return k;
3453
3454                 /* This is an ugly hack */
3455                 if (major(devnr) == 136) {
3456                         if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3457                                 return -ENOMEM;
3458
3459                         *r = b;
3460                         if (_devnr)
3461                                 *_devnr = devnr;
3462
3463                         return 0;
3464                 }
3465
3466                 /* Probably something like the ptys which have no
3467                  * symlink in /dev/char. Let's return something
3468                  * vaguely useful. */
3469
3470                 if (!(b = strdup(fn + 5)))
3471                         return -ENOMEM;
3472
3473                 *r = b;
3474                 if (_devnr)
3475                         *_devnr = devnr;
3476
3477                 return 0;
3478         }
3479
3480         if (startswith(s, "/dev/"))
3481                 p = s + 5;
3482         else if (startswith(s, "../"))
3483                 p = s + 3;
3484         else
3485                 p = s;
3486
3487         b = strdup(p);
3488         free(s);
3489
3490         if (!b)
3491                 return -ENOMEM;
3492
3493         *r = b;
3494         if (_devnr)
3495                 *_devnr = devnr;
3496
3497         return 0;
3498 }
3499
3500 static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) {
3501         DIR *d;
3502         int ret = 0;
3503
3504         assert(fd >= 0);
3505
3506         /* This returns the first error we run into, but nevertheless
3507          * tries to go on */
3508
3509         if (!(d = fdopendir(fd))) {
3510                 close_nointr_nofail(fd);
3511
3512                 return errno == ENOENT ? 0 : -errno;
3513         }
3514
3515         for (;;) {
3516                 struct dirent buf, *de;
3517                 bool is_dir, keep_around = false;
3518                 int r;
3519
3520                 if ((r = readdir_r(d, &buf, &de)) != 0) {
3521                         if (ret == 0)
3522                                 ret = -r;
3523                         break;
3524                 }
3525
3526                 if (!de)
3527                         break;
3528
3529                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3530                         continue;
3531
3532                 if (de->d_type == DT_UNKNOWN) {
3533                         struct stat st;
3534
3535                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3536                                 if (ret == 0 && errno != ENOENT)
3537                                         ret = -errno;
3538                                 continue;
3539                         }
3540
3541                         if (honour_sticky)
3542                                 keep_around =
3543                                         (st.st_uid == 0 || st.st_uid == getuid()) &&
3544                                         (st.st_mode & S_ISVTX);
3545
3546                         is_dir = S_ISDIR(st.st_mode);
3547
3548                 } else {
3549                         if (honour_sticky) {
3550                                 struct stat st;
3551
3552                                 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3553                                         if (ret == 0 && errno != ENOENT)
3554                                                 ret = -errno;
3555                                         continue;
3556                                 }
3557
3558                                 keep_around =
3559                                         (st.st_uid == 0 || st.st_uid == getuid()) &&
3560                                         (st.st_mode & S_ISVTX);
3561                         }
3562
3563                         is_dir = de->d_type == DT_DIR;
3564                 }
3565
3566                 if (is_dir) {
3567                         int subdir_fd;
3568
3569                         if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3570                                 if (ret == 0 && errno != ENOENT)
3571                                         ret = -errno;
3572                                 continue;
3573                         }
3574
3575                         if ((r = rm_rf_children(subdir_fd, only_dirs, honour_sticky)) < 0) {
3576                                 if (ret == 0)
3577                                         ret = r;
3578                         }
3579
3580                         if (!keep_around)
3581                                 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3582                                         if (ret == 0 && errno != ENOENT)
3583                                                 ret = -errno;
3584                                 }
3585
3586                 } else if (!only_dirs && !keep_around) {
3587
3588                         if (unlinkat(fd, de->d_name, 0) < 0) {
3589                                 if (ret == 0 && errno != ENOENT)
3590                                         ret = -errno;
3591                         }
3592                 }
3593         }
3594
3595         closedir(d);
3596
3597         return ret;
3598 }
3599
3600 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3601         int fd;
3602         int r;
3603
3604         assert(path);
3605
3606         if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3607
3608                 if (errno != ENOTDIR)
3609                         return -errno;
3610
3611                 if (delete_root && !only_dirs)
3612                         if (unlink(path) < 0)
3613                                 return -errno;
3614
3615                 return 0;
3616         }
3617
3618         r = rm_rf_children(fd, only_dirs, honour_sticky);
3619
3620         if (delete_root) {
3621
3622                 if (honour_sticky && file_is_priv_sticky(path) > 0)
3623                         return r;
3624
3625                 if (rmdir(path) < 0 && errno != ENOENT) {
3626                         if (r == 0)
3627                                 r = -errno;
3628                 }
3629         }
3630
3631         return r;
3632 }
3633
3634 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3635         assert(path);
3636
3637         /* Under the assumption that we are running privileged we
3638          * first change the access mode and only then hand out
3639          * ownership to avoid a window where access is too open. */
3640
3641         if (mode != (mode_t) -1)
3642                 if (chmod(path, mode) < 0)
3643                         return -errno;
3644
3645         if (uid != (uid_t) -1 || gid != (gid_t) -1)
3646                 if (chown(path, uid, gid) < 0)
3647                         return -errno;
3648
3649         return 0;
3650 }
3651
3652 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3653         assert(fd >= 0);
3654
3655         /* Under the assumption that we are running privileged we
3656          * first change the access mode and only then hand out
3657          * ownership to avoid a window where access is too open. */
3658
3659         if (fchmod(fd, mode) < 0)
3660                 return -errno;
3661
3662         if (fchown(fd, uid, gid) < 0)
3663                 return -errno;
3664
3665         return 0;
3666 }
3667
3668 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3669         cpu_set_t *r;
3670         unsigned n = 1024;
3671
3672         /* Allocates the cpuset in the right size */
3673
3674         for (;;) {
3675                 if (!(r = CPU_ALLOC(n)))
3676                         return NULL;
3677
3678                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3679                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3680
3681                         if (ncpus)
3682                                 *ncpus = n;
3683
3684                         return r;
3685                 }
3686
3687                 CPU_FREE(r);
3688
3689                 if (errno != EINVAL)
3690                         return NULL;
3691
3692                 n *= 2;
3693         }
3694 }
3695
3696 void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3697         char *s = NULL, *spaces = NULL, *e;
3698         int fd = -1, c;
3699         size_t emax, sl, left;
3700         struct iovec iovec[5];
3701         int n = 0;
3702
3703         assert(format);
3704
3705         /* This independent of logging, as status messages are
3706          * optional and go exclusively to the console. */
3707
3708         if (vasprintf(&s, format, ap) < 0)
3709                 goto finish;
3710
3711         fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3712         if (fd < 0)
3713                 goto finish;
3714
3715         if (ellipse) {
3716                 c = fd_columns(fd);
3717                 if (c <= 0)
3718                         c = 80;
3719
3720                 if (status) {
3721                         sl = 2 + 6 + 1; /* " [" status "]" */
3722                         emax = (size_t) c > sl ? c - sl - 1 : 0;
3723                 } else
3724                         emax = c - 1;
3725
3726                 e = ellipsize(s, emax, 75);
3727                 if (e) {
3728                         free(s);
3729                         s = e;
3730                 }
3731         }
3732
3733         zero(iovec);
3734         IOVEC_SET_STRING(iovec[n++], s);
3735
3736         if (ellipse) {
3737                 sl = strlen(s);
3738                 left = emax > sl ? emax - sl : 0;
3739                 if (left > 0) {
3740                         spaces = malloc(left);
3741                         if (spaces) {
3742                                 memset(spaces, ' ', left);
3743                                 iovec[n].iov_base = spaces;
3744                                 iovec[n].iov_len = left;
3745                                 n++;
3746                         }
3747                 }
3748         }
3749
3750         if (status) {
3751                 IOVEC_SET_STRING(iovec[n++], " [");
3752                 IOVEC_SET_STRING(iovec[n++], status);
3753                 IOVEC_SET_STRING(iovec[n++], "]\n");
3754         } else
3755                 IOVEC_SET_STRING(iovec[n++], "\n");
3756
3757         writev(fd, iovec, n);
3758
3759 finish:
3760         free(s);
3761         free(spaces);
3762
3763         if (fd >= 0)
3764                 close_nointr_nofail(fd);
3765 }
3766
3767 void status_printf(const char *status, bool ellipse, const char *format, ...) {
3768         va_list ap;
3769
3770         assert(format);
3771
3772         va_start(ap, format);
3773         status_vprintf(status, ellipse, format, ap);
3774         va_end(ap);
3775 }
3776
3777 void status_welcome(void) {
3778         char *pretty_name = NULL, *ansi_color = NULL;
3779         const char *const_pretty = NULL, *const_color = NULL;
3780         int r;
3781
3782         if ((r = parse_env_file("/etc/os-release", NEWLINE,
3783                                 "PRETTY_NAME", &pretty_name,
3784                                 "ANSI_COLOR", &ansi_color,
3785                                 NULL)) < 0) {
3786
3787                 if (r != -ENOENT)
3788                         log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3789         }
3790
3791         if (!pretty_name && !const_pretty)
3792                 const_pretty = "Linux";
3793
3794         if (!ansi_color && !const_color)
3795                 const_color = "1";
3796
3797         status_printf(NULL,
3798                       false,
3799                       "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3800                       const_color ? const_color : ansi_color,
3801                       const_pretty ? const_pretty : pretty_name);
3802
3803         free(ansi_color);
3804         free(pretty_name);
3805 }
3806
3807 char *replace_env(const char *format, char **env) {
3808         enum {
3809                 WORD,
3810                 CURLY,
3811                 VARIABLE
3812         } state = WORD;
3813
3814         const char *e, *word = format;
3815         char *r = NULL, *k;
3816
3817         assert(format);
3818
3819         for (e = format; *e; e ++) {
3820
3821                 switch (state) {
3822
3823                 case WORD:
3824                         if (*e == '$')
3825                                 state = CURLY;
3826                         break;
3827
3828                 case CURLY:
3829                         if (*e == '{') {
3830                                 if (!(k = strnappend(r, word, e-word-1)))
3831                                         goto fail;
3832
3833                                 free(r);
3834                                 r = k;
3835
3836                                 word = e-1;
3837                                 state = VARIABLE;
3838
3839                         } else if (*e == '$') {
3840                                 if (!(k = strnappend(r, word, e-word)))
3841                                         goto fail;
3842
3843                                 free(r);
3844                                 r = k;
3845
3846                                 word = e+1;
3847                                 state = WORD;
3848                         } else
3849                                 state = WORD;
3850                         break;
3851
3852                 case VARIABLE:
3853                         if (*e == '}') {
3854                                 const char *t;
3855
3856                                 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3857                                         t = "";
3858
3859                                 if (!(k = strappend(r, t)))
3860                                         goto fail;
3861
3862                                 free(r);
3863                                 r = k;
3864
3865                                 word = e+1;
3866                                 state = WORD;
3867                         }
3868                         break;
3869                 }
3870         }
3871
3872         if (!(k = strnappend(r, word, e-word)))
3873                 goto fail;
3874
3875         free(r);
3876         return k;
3877
3878 fail:
3879         free(r);
3880         return NULL;
3881 }
3882
3883 char **replace_env_argv(char **argv, char **env) {
3884         char **r, **i;
3885         unsigned k = 0, l = 0;
3886
3887         l = strv_length(argv);
3888
3889         if (!(r = new(char*, l+1)))
3890                 return NULL;
3891
3892         STRV_FOREACH(i, argv) {
3893
3894                 /* If $FOO appears as single word, replace it by the split up variable */
3895                 if ((*i)[0] == '$' && (*i)[1] != '{') {
3896                         char *e;
3897                         char **w, **m;
3898                         unsigned q;
3899
3900                         if ((e = strv_env_get(env, *i+1))) {
3901
3902                                 if (!(m = strv_split_quoted(e))) {
3903                                         r[k] = NULL;
3904                                         strv_free(r);
3905                                         return NULL;
3906                                 }
3907                         } else
3908                                 m = NULL;
3909
3910                         q = strv_length(m);
3911                         l = l + q - 1;
3912
3913                         if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3914                                 r[k] = NULL;
3915                                 strv_free(r);
3916                                 strv_free(m);
3917                                 return NULL;
3918                         }
3919
3920                         r = w;
3921                         if (m) {
3922                                 memcpy(r + k, m, q * sizeof(char*));
3923                                 free(m);
3924                         }
3925
3926                         k += q;
3927                         continue;
3928                 }
3929
3930                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3931                 if (!(r[k++] = replace_env(*i, env))) {
3932                         strv_free(r);
3933                         return NULL;
3934                 }
3935         }
3936
3937         r[k] = NULL;
3938         return r;
3939 }
3940
3941 int fd_columns(int fd) {
3942         struct winsize ws;
3943         zero(ws);
3944
3945         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3946                 return -errno;
3947
3948         if (ws.ws_col <= 0)
3949                 return -EIO;
3950
3951         return ws.ws_col;
3952 }
3953
3954 unsigned columns(void) {
3955         static __thread int parsed_columns = 0;
3956         const char *e;
3957
3958         if (_likely_(parsed_columns > 0))
3959                 return parsed_columns;
3960
3961         e = getenv("COLUMNS");
3962         if (e)
3963                 parsed_columns = atoi(e);
3964
3965         if (parsed_columns <= 0)
3966                 parsed_columns = fd_columns(STDOUT_FILENO);
3967
3968         if (parsed_columns <= 0)
3969                 parsed_columns = 80;
3970
3971         return parsed_columns;
3972 }
3973
3974 int fd_lines(int fd) {
3975         struct winsize ws;
3976         zero(ws);
3977
3978         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3979                 return -errno;
3980
3981         if (ws.ws_row <= 0)
3982                 return -EIO;
3983
3984         return ws.ws_row;
3985 }
3986
3987 unsigned lines(void) {
3988         static __thread int parsed_lines = 0;
3989         const char *e;
3990
3991         if (_likely_(parsed_lines > 0))
3992                 return parsed_lines;
3993
3994         e = getenv("LINES");
3995         if (e)
3996                 parsed_lines = atoi(e);
3997
3998         if (parsed_lines <= 0)
3999                 parsed_lines = fd_lines(STDOUT_FILENO);
4000
4001         if (parsed_lines <= 0)
4002                 parsed_lines = 25;
4003
4004         return parsed_lines;
4005 }
4006
4007 int running_in_chroot(void) {
4008         struct stat a, b;
4009
4010         zero(a);
4011         zero(b);
4012
4013         /* Only works as root */
4014
4015         if (stat("/proc/1/root", &a) < 0)
4016                 return -errno;
4017
4018         if (stat("/", &b) < 0)
4019                 return -errno;
4020
4021         return
4022                 a.st_dev != b.st_dev ||
4023                 a.st_ino != b.st_ino;
4024 }
4025
4026 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
4027         size_t x;
4028         char *r;
4029
4030         assert(s);
4031         assert(percent <= 100);
4032         assert(new_length >= 3);
4033
4034         if (old_length <= 3 || old_length <= new_length)
4035                 return strndup(s, old_length);
4036
4037         r = new0(char, new_length+1);
4038         if (!r)
4039                 return r;
4040
4041         x = (new_length * percent) / 100;
4042
4043         if (x > new_length - 3)
4044                 x = new_length - 3;
4045
4046         memcpy(r, s, x);
4047         r[x] = '.';
4048         r[x+1] = '.';
4049         r[x+2] = '.';
4050         memcpy(r + x + 3,
4051                s + old_length - (new_length - x - 3),
4052                new_length - x - 3);
4053
4054         return r;
4055 }
4056
4057 char *ellipsize(const char *s, size_t length, unsigned percent) {
4058         return ellipsize_mem(s, strlen(s), length, percent);
4059 }
4060
4061 int touch(const char *path) {
4062         int fd;
4063
4064         assert(path);
4065
4066         if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
4067                 return -errno;
4068
4069         close_nointr_nofail(fd);
4070         return 0;
4071 }
4072
4073 char *unquote(const char *s, const char* quotes) {
4074         size_t l;
4075         assert(s);
4076
4077         l = strlen(s);
4078         if (l < 2)
4079                 return strdup(s);
4080
4081         if (strchr(quotes, s[0]) && s[l-1] == s[0])
4082                 return strndup(s+1, l-2);
4083
4084         return strdup(s);
4085 }
4086
4087 char *normalize_env_assignment(const char *s) {
4088         char *name, *value, *p, *r;
4089
4090         p = strchr(s, '=');
4091
4092         if (!p) {
4093                 if (!(r = strdup(s)))
4094                         return NULL;
4095
4096                 return strstrip(r);
4097         }
4098
4099         if (!(name = strndup(s, p - s)))
4100                 return NULL;
4101
4102         if (!(p = strdup(p+1))) {
4103                 free(name);
4104                 return NULL;
4105         }
4106
4107         value = unquote(strstrip(p), QUOTES);
4108         free(p);
4109
4110         if (!value) {
4111                 free(name);
4112                 return NULL;
4113         }
4114
4115         if (asprintf(&r, "%s=%s", name, value) < 0)
4116                 r = NULL;
4117
4118         free(value);
4119         free(name);
4120
4121         return r;
4122 }
4123
4124 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4125         siginfo_t dummy;
4126
4127         assert(pid >= 1);
4128
4129         if (!status)
4130                 status = &dummy;
4131
4132         for (;;) {
4133                 zero(*status);
4134
4135                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4136
4137                         if (errno == EINTR)
4138                                 continue;
4139
4140                         return -errno;
4141                 }
4142
4143                 return 0;
4144         }
4145 }
4146
4147 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4148         int r;
4149         siginfo_t status;
4150
4151         assert(name);
4152         assert(pid > 1);
4153
4154         if ((r = wait_for_terminate(pid, &status)) < 0) {
4155                 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4156                 return r;
4157         }
4158
4159         if (status.si_code == CLD_EXITED) {
4160                 if (status.si_status != 0) {
4161                         log_warning("%s failed with error code %i.", name, status.si_status);
4162                         return status.si_status;
4163                 }
4164
4165                 log_debug("%s succeeded.", name);
4166                 return 0;
4167
4168         } else if (status.si_code == CLD_KILLED ||
4169                    status.si_code == CLD_DUMPED) {
4170
4171                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4172                 return -EPROTO;
4173         }
4174
4175         log_warning("%s failed due to unknown reason.", name);
4176         return -EPROTO;
4177
4178 }
4179
4180 void freeze(void) {
4181
4182         /* Make sure nobody waits for us on a socket anymore */
4183         close_all_fds(NULL, 0);
4184
4185         sync();
4186
4187         for (;;)
4188                 pause();
4189 }
4190
4191 bool null_or_empty(struct stat *st) {
4192         assert(st);
4193
4194         if (S_ISREG(st->st_mode) && st->st_size <= 0)
4195                 return true;
4196
4197         if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4198                 return true;
4199
4200         return false;
4201 }
4202
4203 int null_or_empty_path(const char *fn) {
4204         struct stat st;
4205
4206         assert(fn);
4207
4208         if (stat(fn, &st) < 0)
4209                 return -errno;
4210
4211         return null_or_empty(&st);
4212 }
4213
4214 DIR *xopendirat(int fd, const char *name, int flags) {
4215         int nfd;
4216         DIR *d;
4217
4218         if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4219                 return NULL;
4220
4221         if (!(d = fdopendir(nfd))) {
4222                 close_nointr_nofail(nfd);
4223                 return NULL;
4224         }
4225
4226         return d;
4227 }
4228
4229 int signal_from_string_try_harder(const char *s) {
4230         int signo;
4231         assert(s);
4232
4233         if ((signo = signal_from_string(s)) <= 0)
4234                 if (startswith(s, "SIG"))
4235                         return signal_from_string(s+3);
4236
4237         return signo;
4238 }
4239
4240 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4241
4242         assert(f);
4243         assert(name);
4244         assert(t);
4245
4246         if (!dual_timestamp_is_set(t))
4247                 return;
4248
4249         fprintf(f, "%s=%llu %llu\n",
4250                 name,
4251                 (unsigned long long) t->realtime,
4252                 (unsigned long long) t->monotonic);
4253 }
4254
4255 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4256         unsigned long long a, b;
4257
4258         assert(value);
4259         assert(t);
4260
4261         if (sscanf(value, "%lli %llu", &a, &b) != 2)
4262                 log_debug("Failed to parse finish timestamp value %s", value);
4263         else {
4264                 t->realtime = a;
4265                 t->monotonic = b;
4266         }
4267 }
4268
4269 char *fstab_node_to_udev_node(const char *p) {
4270         char *dn, *t, *u;
4271         int r;
4272
4273         /* FIXME: to follow udev's logic 100% we need to leave valid
4274          * UTF8 chars unescaped */
4275
4276         if (startswith(p, "LABEL=")) {
4277
4278                 if (!(u = unquote(p+6, "\"\'")))
4279                         return NULL;
4280
4281                 t = xescape(u, "/ ");
4282                 free(u);
4283
4284                 if (!t)
4285                         return NULL;
4286
4287                 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4288                 free(t);
4289
4290                 if (r < 0)
4291                         return NULL;
4292
4293                 return dn;
4294         }
4295
4296         if (startswith(p, "UUID=")) {
4297
4298                 if (!(u = unquote(p+5, "\"\'")))
4299                         return NULL;
4300
4301                 t = xescape(u, "/ ");
4302                 free(u);
4303
4304                 if (!t)
4305                         return NULL;
4306
4307                 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4308                 free(t);
4309
4310                 if (r < 0)
4311                         return NULL;
4312
4313                 return dn;
4314         }
4315
4316         return strdup(p);
4317 }
4318
4319 void filter_environ(const char *prefix) {
4320         int i, j;
4321         assert(prefix);
4322
4323         if (!environ)
4324                 return;
4325
4326         for (i = 0, j = 0; environ[i]; i++) {
4327
4328                 if (startswith(environ[i], prefix))
4329                         continue;
4330
4331                 environ[j++] = environ[i];
4332         }
4333
4334         environ[j] = NULL;
4335 }
4336
4337 bool tty_is_vc(const char *tty) {
4338         assert(tty);
4339
4340         if (startswith(tty, "/dev/"))
4341                 tty += 5;
4342
4343         return vtnr_from_tty(tty) >= 0;
4344 }
4345
4346 int vtnr_from_tty(const char *tty) {
4347         int i, r;
4348
4349         assert(tty);
4350
4351         if (startswith(tty, "/dev/"))
4352                 tty += 5;
4353
4354         if (!startswith(tty, "tty") )
4355                 return -EINVAL;
4356
4357         if (tty[3] < '0' || tty[3] > '9')
4358                 return -EINVAL;
4359
4360         r = safe_atoi(tty+3, &i);
4361         if (r < 0)
4362                 return r;
4363
4364         if (i < 0 || i > 63)
4365                 return -EINVAL;
4366
4367         return i;
4368 }
4369
4370 bool tty_is_vc_resolve(const char *tty) {
4371         char *active = NULL;
4372         bool b;
4373
4374         assert(tty);
4375
4376         if (startswith(tty, "/dev/"))
4377                 tty += 5;
4378
4379         /* Resolve where /dev/console is pointing to */
4380         if (streq(tty, "console"))
4381                 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4382                         /* If multiple log outputs are configured the
4383                          * last one is what /dev/console points to */
4384                         tty = strrchr(active, ' ');
4385                         if (tty)
4386                                 tty++;
4387                         else
4388                                 tty = active;
4389                 }
4390
4391         b = tty_is_vc(tty);
4392         free(active);
4393
4394         return b;
4395 }
4396
4397 const char *default_term_for_tty(const char *tty) {
4398         assert(tty);
4399
4400         return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt100";
4401 }
4402
4403 bool dirent_is_file(const struct dirent *de) {
4404         assert(de);
4405
4406         if (ignore_file(de->d_name))
4407                 return false;
4408
4409         if (de->d_type != DT_REG &&
4410             de->d_type != DT_LNK &&
4411             de->d_type != DT_UNKNOWN)
4412                 return false;
4413
4414         return true;
4415 }
4416
4417 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4418         assert(de);
4419
4420         if (!dirent_is_file(de))
4421                 return false;
4422
4423         return endswith(de->d_name, suffix);
4424 }
4425
4426 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4427         DIR *_d = NULL;
4428         struct dirent *de;
4429         Hashmap *pids = NULL;
4430
4431         assert(directory);
4432
4433         /* Executes all binaries in a directory in parallel and waits
4434          * until all they all finished. */
4435
4436         if (!d) {
4437                 if (!(_d = opendir(directory))) {
4438
4439                         if (errno == ENOENT)
4440                                 return;
4441
4442                         log_error("Failed to enumerate directory %s: %m", directory);
4443                         return;
4444                 }
4445
4446                 d = _d;
4447         }
4448
4449         if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4450                 log_error("Failed to allocate set.");
4451                 goto finish;
4452         }
4453
4454         while ((de = readdir(d))) {
4455                 char *path;
4456                 pid_t pid;
4457                 int k;
4458
4459                 if (!dirent_is_file(de))
4460                         continue;
4461
4462                 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4463                         log_error("Out of memory");
4464                         continue;
4465                 }
4466
4467                 if ((pid = fork()) < 0) {
4468                         log_error("Failed to fork: %m");
4469                         free(path);
4470                         continue;
4471                 }
4472
4473                 if (pid == 0) {
4474                         char *_argv[2];
4475                         /* Child */
4476
4477                         if (!argv) {
4478                                 _argv[0] = path;
4479                                 _argv[1] = NULL;
4480                                 argv = _argv;
4481                         } else
4482                                 if (!argv[0])
4483                                         argv[0] = path;
4484
4485                         execv(path, argv);
4486
4487                         log_error("Failed to execute %s: %m", path);
4488                         _exit(EXIT_FAILURE);
4489                 }
4490
4491                 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4492
4493                 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4494                         log_error("Failed to add PID to set: %s", strerror(-k));
4495                         free(path);
4496                 }
4497         }
4498
4499         while (!hashmap_isempty(pids)) {
4500                 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4501                 siginfo_t si;
4502                 char *path;
4503
4504                 zero(si);
4505                 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4506
4507                         if (errno == EINTR)
4508                                 continue;
4509
4510                         log_error("waitid() failed: %m");
4511                         goto finish;
4512                 }
4513
4514                 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4515                         if (!is_clean_exit(si.si_code, si.si_status)) {
4516                                 if (si.si_code == CLD_EXITED)
4517                                         log_error("%s exited with exit status %i.", path, si.si_status);
4518                                 else
4519                                         log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4520                         } else
4521                                 log_debug("%s exited successfully.", path);
4522
4523                         free(path);
4524                 }
4525         }
4526
4527 finish:
4528         if (_d)
4529                 closedir(_d);
4530
4531         if (pids)
4532                 hashmap_free_free(pids);
4533 }
4534
4535 int kill_and_sigcont(pid_t pid, int sig) {
4536         int r;
4537
4538         r = kill(pid, sig) < 0 ? -errno : 0;
4539
4540         if (r >= 0)
4541                 kill(pid, SIGCONT);
4542
4543         return r;
4544 }
4545
4546 bool nulstr_contains(const char*nulstr, const char *needle) {
4547         const char *i;
4548
4549         if (!nulstr)
4550                 return false;
4551
4552         NULSTR_FOREACH(i, nulstr)
4553                 if (streq(i, needle))
4554                         return true;
4555
4556         return false;
4557 }
4558
4559 bool plymouth_running(void) {
4560         return access("/run/plymouth/pid", F_OK) >= 0;
4561 }
4562
4563 void parse_syslog_priority(char **p, int *priority) {
4564         int a = 0, b = 0, c = 0;
4565         int k;
4566
4567         assert(p);
4568         assert(*p);
4569         assert(priority);
4570
4571         if ((*p)[0] != '<')
4572                 return;
4573
4574         if (!strchr(*p, '>'))
4575                 return;
4576
4577         if ((*p)[2] == '>') {
4578                 c = undecchar((*p)[1]);
4579                 k = 3;
4580         } else if ((*p)[3] == '>') {
4581                 b = undecchar((*p)[1]);
4582                 c = undecchar((*p)[2]);
4583                 k = 4;
4584         } else if ((*p)[4] == '>') {
4585                 a = undecchar((*p)[1]);
4586                 b = undecchar((*p)[2]);
4587                 c = undecchar((*p)[3]);
4588                 k = 5;
4589         } else
4590                 return;
4591
4592         if (a < 0 || b < 0 || c < 0)
4593                 return;
4594
4595         *priority = a*100+b*10+c;
4596         *p += k;
4597 }
4598
4599 void skip_syslog_pid(char **buf) {
4600         char *p;
4601
4602         assert(buf);
4603         assert(*buf);
4604
4605         p = *buf;
4606
4607         if (*p != '[')
4608                 return;
4609
4610         p++;
4611         p += strspn(p, "0123456789");
4612
4613         if (*p != ']')
4614                 return;
4615
4616         p++;
4617
4618         *buf = p;
4619 }
4620
4621 void skip_syslog_date(char **buf) {
4622         enum {
4623                 LETTER,
4624                 SPACE,
4625                 NUMBER,
4626                 SPACE_OR_NUMBER,
4627                 COLON
4628         } sequence[] = {
4629                 LETTER, LETTER, LETTER,
4630                 SPACE,
4631                 SPACE_OR_NUMBER, NUMBER,
4632                 SPACE,
4633                 SPACE_OR_NUMBER, NUMBER,
4634                 COLON,
4635                 SPACE_OR_NUMBER, NUMBER,
4636                 COLON,
4637                 SPACE_OR_NUMBER, NUMBER,
4638                 SPACE
4639         };
4640
4641         char *p;
4642         unsigned i;
4643
4644         assert(buf);
4645         assert(*buf);
4646
4647         p = *buf;
4648
4649         for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
4650
4651                 if (!*p)
4652                         return;
4653
4654                 switch (sequence[i]) {
4655
4656                 case SPACE:
4657                         if (*p != ' ')
4658                                 return;
4659                         break;
4660
4661                 case SPACE_OR_NUMBER:
4662                         if (*p == ' ')
4663                                 break;
4664
4665                         /* fall through */
4666
4667                 case NUMBER:
4668                         if (*p < '0' || *p > '9')
4669                                 return;
4670
4671                         break;
4672
4673                 case LETTER:
4674                         if (!(*p >= 'A' && *p <= 'Z') &&
4675                             !(*p >= 'a' && *p <= 'z'))
4676                                 return;
4677
4678                         break;
4679
4680                 case COLON:
4681                         if (*p != ':')
4682                                 return;
4683                         break;
4684
4685                 }
4686         }
4687
4688         *buf = p;
4689 }
4690
4691 int have_effective_cap(int value) {
4692         cap_t cap;
4693         cap_flag_value_t fv;
4694         int r;
4695
4696         if (!(cap = cap_get_proc()))
4697                 return -errno;
4698
4699         if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4700                 r = -errno;
4701         else
4702                 r = fv == CAP_SET;
4703
4704         cap_free(cap);
4705         return r;
4706 }
4707
4708 char* strshorten(char *s, size_t l) {
4709         assert(s);
4710
4711         if (l < strlen(s))
4712                 s[l] = 0;
4713
4714         return s;
4715 }
4716
4717 static bool hostname_valid_char(char c) {
4718         return
4719                 (c >= 'a' && c <= 'z') ||
4720                 (c >= 'A' && c <= 'Z') ||
4721                 (c >= '0' && c <= '9') ||
4722                 c == '-' ||
4723                 c == '_' ||
4724                 c == '.';
4725 }
4726
4727 bool hostname_is_valid(const char *s) {
4728         const char *p;
4729
4730         if (isempty(s))
4731                 return false;
4732
4733         for (p = s; *p; p++)
4734                 if (!hostname_valid_char(*p))
4735                         return false;
4736
4737         if (p-s > HOST_NAME_MAX)
4738                 return false;
4739
4740         return true;
4741 }
4742
4743 char* hostname_cleanup(char *s) {
4744         char *p, *d;
4745
4746         for (p = s, d = s; *p; p++)
4747                 if ((*p >= 'a' && *p <= 'z') ||
4748                     (*p >= 'A' && *p <= 'Z') ||
4749                     (*p >= '0' && *p <= '9') ||
4750                     *p == '-' ||
4751                     *p == '_' ||
4752                     *p == '.')
4753                         *(d++) = *p;
4754
4755         *d = 0;
4756
4757         strshorten(s, HOST_NAME_MAX);
4758         return s;
4759 }
4760
4761 int pipe_eof(int fd) {
4762         struct pollfd pollfd;
4763         int r;
4764
4765         zero(pollfd);
4766         pollfd.fd = fd;
4767         pollfd.events = POLLIN|POLLHUP;
4768
4769         r = poll(&pollfd, 1, 0);
4770         if (r < 0)
4771                 return -errno;
4772
4773         if (r == 0)
4774                 return 0;
4775
4776         return pollfd.revents & POLLHUP;
4777 }
4778
4779 int fd_wait_for_event(int fd, int event, usec_t t) {
4780         struct pollfd pollfd;
4781         int r;
4782
4783         zero(pollfd);
4784         pollfd.fd = fd;
4785         pollfd.events = event;
4786
4787         r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4788         if (r < 0)
4789                 return -errno;
4790
4791         if (r == 0)
4792                 return 0;
4793
4794         return pollfd.revents;
4795 }
4796
4797 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4798         FILE *f;
4799         char *t;
4800         const char *fn;
4801         size_t k;
4802         int fd;
4803
4804         assert(path);
4805         assert(_f);
4806         assert(_temp_path);
4807
4808         t = new(char, strlen(path) + 1 + 6 + 1);
4809         if (!t)
4810                 return -ENOMEM;
4811
4812         fn = file_name_from_path(path);
4813         k = fn-path;
4814         memcpy(t, path, k);
4815         t[k] = '.';
4816         stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4817
4818         fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4819         if (fd < 0) {
4820                 free(t);
4821                 return -errno;
4822         }
4823
4824         f = fdopen(fd, "we");
4825         if (!f) {
4826                 unlink(t);
4827                 free(t);
4828                 return -errno;
4829         }
4830
4831         *_f = f;
4832         *_temp_path = t;
4833
4834         return 0;
4835 }
4836
4837 int terminal_vhangup_fd(int fd) {
4838         assert(fd >= 0);
4839
4840         if (ioctl(fd, TIOCVHANGUP) < 0)
4841                 return -errno;
4842
4843         return 0;
4844 }
4845
4846 int terminal_vhangup(const char *name) {
4847         int fd, r;
4848
4849         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4850         if (fd < 0)
4851                 return fd;
4852
4853         r = terminal_vhangup_fd(fd);
4854         close_nointr_nofail(fd);
4855
4856         return r;
4857 }
4858
4859 int vt_disallocate(const char *name) {
4860         int fd, r;
4861         unsigned u;
4862
4863         /* Deallocate the VT if possible. If not possible
4864          * (i.e. because it is the active one), at least clear it
4865          * entirely (including the scrollback buffer) */
4866
4867         if (!startswith(name, "/dev/"))
4868                 return -EINVAL;
4869
4870         if (!tty_is_vc(name)) {
4871                 /* So this is not a VT. I guess we cannot deallocate
4872                  * it then. But let's at least clear the screen */
4873
4874                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4875                 if (fd < 0)
4876                         return fd;
4877
4878                 loop_write(fd,
4879                            "\033[r"    /* clear scrolling region */
4880                            "\033[H"    /* move home */
4881                            "\033[2J",  /* clear screen */
4882                            10, false);
4883                 close_nointr_nofail(fd);
4884
4885                 return 0;
4886         }
4887
4888         if (!startswith(name, "/dev/tty"))
4889                 return -EINVAL;
4890
4891         r = safe_atou(name+8, &u);
4892         if (r < 0)
4893                 return r;
4894
4895         if (u <= 0)
4896                 return -EINVAL;
4897
4898         /* Try to deallocate */
4899         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4900         if (fd < 0)
4901                 return fd;
4902
4903         r = ioctl(fd, VT_DISALLOCATE, u);
4904         close_nointr_nofail(fd);
4905
4906         if (r >= 0)
4907                 return 0;
4908
4909         if (errno != EBUSY)
4910                 return -errno;
4911
4912         /* Couldn't deallocate, so let's clear it fully with
4913          * scrollback */
4914         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4915         if (fd < 0)
4916                 return fd;
4917
4918         loop_write(fd,
4919                    "\033[r"   /* clear scrolling region */
4920                    "\033[H"   /* move home */
4921                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4922                    10, false);
4923         close_nointr_nofail(fd);
4924
4925         return 0;
4926 }
4927
4928 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4929         DIR *dir;
4930         struct dirent buffer, *de;
4931         int r = 0;
4932
4933         dir = opendir(path);
4934         if (!dir) {
4935                 if (errno == ENOENT)
4936                         return 0;
4937                 return -errno;
4938         }
4939
4940         for (;;) {
4941                 int k;
4942                 char *p, *f;
4943
4944                 k = readdir_r(dir, &buffer, &de);
4945                 if (k != 0) {
4946                         r = -k;
4947                         goto finish;
4948                 }
4949
4950                 if (!de)
4951                         break;
4952
4953                 if (!dirent_is_file_with_suffix(de, suffix))
4954                         continue;
4955
4956                 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4957                         r = -ENOMEM;
4958                         goto finish;
4959                 }
4960
4961                 f = canonicalize_file_name(p);
4962                 if (!f) {
4963                         log_error("Failed to canonicalize file name '%s': %m", p);
4964                         free(p);
4965                         continue;
4966                 }
4967                 free(p);
4968
4969                 log_debug("found: %s\n", f);
4970                 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
4971                         free(f);
4972         }
4973
4974 finish:
4975         closedir(dir);
4976         return r;
4977 }
4978
4979 static int base_cmp(const void *a, const void *b) {
4980         const char *s1, *s2;
4981
4982         s1 = *(char * const *)a;
4983         s2 = *(char * const *)b;
4984         return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4985 }
4986
4987 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4988         Hashmap *fh = NULL;
4989         char **dirs = NULL;
4990         char **files = NULL;
4991         char **p;
4992         va_list ap;
4993         int r = 0;
4994
4995         va_start(ap, dir);
4996         dirs = strv_new_ap(dir, ap);
4997         va_end(ap);
4998         if (!dirs) {
4999                 r = -ENOMEM;
5000                 goto finish;
5001         }
5002         if (!strv_path_canonicalize(dirs)) {
5003                 r = -ENOMEM;
5004                 goto finish;
5005         }
5006         if (!strv_uniq(dirs)) {
5007                 r = -ENOMEM;
5008                 goto finish;
5009         }
5010
5011         fh = hashmap_new(string_hash_func, string_compare_func);
5012         if (!fh) {
5013                 r = -ENOMEM;
5014                 goto finish;
5015         }
5016
5017         STRV_FOREACH(p, dirs) {
5018                 if (files_add(fh, *p, suffix) < 0) {
5019                         log_error("Failed to search for files.");
5020                         r = -EINVAL;
5021                         goto finish;
5022                 }
5023         }
5024
5025         files = hashmap_get_strv(fh);
5026         if (files == NULL) {
5027                 log_error("Failed to compose list of files.");
5028                 r = -ENOMEM;
5029                 goto finish;
5030         }
5031
5032         qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
5033
5034 finish:
5035         strv_free(dirs);
5036         hashmap_free(fh);
5037         *strv = files;
5038         return r;
5039 }
5040
5041 int hwclock_is_localtime(void) {
5042         FILE *f;
5043         bool local = false;
5044
5045         /*
5046          * The third line of adjtime is "UTC" or "LOCAL" or nothing.
5047          *   # /etc/adjtime
5048          *   0.0 0 0
5049          *   0
5050          *   UTC
5051          */
5052         f = fopen("/etc/adjtime", "re");
5053         if (f) {
5054                 char line[LINE_MAX];
5055                 bool b;
5056
5057                 b = fgets(line, sizeof(line), f) &&
5058                         fgets(line, sizeof(line), f) &&
5059                         fgets(line, sizeof(line), f);
5060
5061                 fclose(f);
5062
5063                 if (!b)
5064                         return -EIO;
5065
5066
5067                 truncate_nl(line);
5068                 local = streq(line, "LOCAL");
5069
5070         } else if (errno != -ENOENT)
5071                 return -errno;
5072
5073         return local;
5074 }
5075
5076 int hwclock_apply_localtime_delta(int *min) {
5077         const struct timeval *tv_null = NULL;
5078         struct timespec ts;
5079         struct tm *tm;
5080         int minuteswest;
5081         struct timezone tz;
5082
5083         assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
5084         assert_se(tm = localtime(&ts.tv_sec));
5085         minuteswest = tm->tm_gmtoff / 60;
5086
5087         tz.tz_minuteswest = -minuteswest;
5088         tz.tz_dsttime = 0; /* DST_NONE*/
5089
5090         /*
5091          * If the hardware clock does not run in UTC, but in local time:
5092          * The very first time we set the kernel's timezone, it will warp
5093          * the clock so that it runs in UTC instead of local time.
5094          */
5095         if (settimeofday(tv_null, &tz) < 0)
5096                 return -errno;
5097         if (min)
5098                 *min = minuteswest;
5099         return 0;
5100 }
5101
5102 int hwclock_reset_localtime_delta(void) {
5103         const struct timeval *tv_null = NULL;
5104         struct timezone tz;
5105
5106         tz.tz_minuteswest = 0;
5107         tz.tz_dsttime = 0; /* DST_NONE*/
5108
5109         if (settimeofday(tv_null, &tz) < 0)
5110                 return -errno;
5111
5112         return 0;
5113 }
5114
5115 int rtc_open(int flags) {
5116         int fd;
5117         DIR *d;
5118
5119         /* First, we try to make use of the /dev/rtc symlink. If that
5120          * doesn't exist, we open the first RTC which has hctosys=1
5121          * set. If we don't find any we just take the first RTC that
5122          * exists at all. */
5123
5124         fd = open("/dev/rtc", flags);
5125         if (fd >= 0)
5126                 return fd;
5127
5128         d = opendir("/sys/class/rtc");
5129         if (!d)
5130                 goto fallback;
5131
5132         for (;;) {
5133                 char *p, *v;
5134                 struct dirent buf, *de;
5135                 int r;
5136
5137                 r = readdir_r(d, &buf, &de);
5138                 if (r != 0)
5139                         goto fallback;
5140
5141                 if (!de)
5142                         goto fallback;
5143
5144                 if (ignore_file(de->d_name))
5145                         continue;
5146
5147                 p = join("/sys/class/rtc/", de->d_name, "/hctosys", NULL);
5148                 if (!p) {
5149                         closedir(d);
5150                         return -ENOMEM;
5151                 }
5152
5153                 r = read_one_line_file(p, &v);
5154                 free(p);
5155
5156                 if (r < 0)
5157                         continue;
5158
5159                 r = parse_boolean(v);
5160                 free(v);
5161
5162                 if (r <= 0)
5163                         continue;
5164
5165                 p = strappend("/dev/", de->d_name);
5166                 fd = open(p, flags);
5167                 free(p);
5168
5169                 if (fd >= 0) {
5170                         closedir(d);
5171                         return fd;
5172                 }
5173         }
5174
5175 fallback:
5176         if (d)
5177                 closedir(d);
5178
5179         fd = open("/dev/rtc0", flags);
5180         if (fd < 0)
5181                 return -errno;
5182
5183         return fd;
5184 }
5185
5186 int hwclock_get_time(struct tm *tm) {
5187         int fd;
5188         int err = 0;
5189
5190         assert(tm);
5191
5192         fd = rtc_open(O_RDONLY|O_CLOEXEC);
5193         if (fd < 0)
5194                 return -errno;
5195
5196         /* This leaves the timezone fields of struct tm
5197          * uninitialized! */
5198         if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5199                 err = -errno;
5200
5201         /* We don't now daylight saving, so we reset this in order not
5202          * to confused mktime(). */
5203         tm->tm_isdst = -1;
5204
5205         close_nointr_nofail(fd);
5206
5207         return err;
5208 }
5209
5210 int hwclock_set_time(const struct tm *tm) {
5211         int fd;
5212         int err = 0;
5213
5214         assert(tm);
5215
5216         fd = rtc_open(O_RDONLY|O_CLOEXEC);
5217         if (fd < 0)
5218                 return -errno;
5219
5220         if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5221                 err = -errno;
5222
5223         close_nointr_nofail(fd);
5224
5225         return err;
5226 }
5227
5228 int copy_file(const char *from, const char *to) {
5229         int r, fdf, fdt;
5230
5231         assert(from);
5232         assert(to);
5233
5234         fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5235         if (fdf < 0)
5236                 return -errno;
5237
5238         fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5239         if (fdt < 0) {
5240                 close_nointr_nofail(fdf);
5241                 return -errno;
5242         }
5243
5244         for (;;) {
5245                 char buf[PIPE_BUF];
5246                 ssize_t n, k;
5247
5248                 n = read(fdf, buf, sizeof(buf));
5249                 if (n < 0) {
5250                         r = -errno;
5251
5252                         close_nointr_nofail(fdf);
5253                         close_nointr(fdt);
5254                         unlink(to);
5255
5256                         return r;
5257                 }
5258
5259                 if (n == 0)
5260                         break;
5261
5262                 errno = 0;
5263                 k = loop_write(fdt, buf, n, false);
5264                 if (n != k) {
5265                         r = k < 0 ? k : (errno ? -errno : -EIO);
5266
5267                         close_nointr_nofail(fdf);
5268                         close_nointr(fdt);
5269
5270                         unlink(to);
5271                         return r;
5272                 }
5273         }
5274
5275         close_nointr_nofail(fdf);
5276         r = close_nointr(fdt);
5277
5278         if (r < 0) {
5279                 unlink(to);
5280                 return r;
5281         }
5282
5283         return 0;
5284 }
5285
5286 int symlink_or_copy(const char *from, const char *to) {
5287         char *pf = NULL, *pt = NULL;
5288         struct stat a, b;
5289         int r;
5290
5291         assert(from);
5292         assert(to);
5293
5294         if (parent_of_path(from, &pf) < 0 ||
5295             parent_of_path(to, &pt) < 0) {
5296                 r = -ENOMEM;
5297                 goto finish;
5298         }
5299
5300         if (stat(pf, &a) < 0 ||
5301             stat(pt, &b) < 0) {
5302                 r = -errno;
5303                 goto finish;
5304         }
5305
5306         if (a.st_dev != b.st_dev) {
5307                 free(pf);
5308                 free(pt);
5309
5310                 return copy_file(from, to);
5311         }
5312
5313         if (symlink(from, to) < 0) {
5314                 r = -errno;
5315                 goto finish;
5316         }
5317
5318         r = 0;
5319
5320 finish:
5321         free(pf);
5322         free(pt);
5323
5324         return r;
5325 }
5326
5327 int symlink_or_copy_atomic(const char *from, const char *to) {
5328         char *t, *x;
5329         const char *fn;
5330         size_t k;
5331         unsigned long long ull;
5332         unsigned i;
5333         int r;
5334
5335         assert(from);
5336         assert(to);
5337
5338         t = new(char, strlen(to) + 1 + 16 + 1);
5339         if (!t)
5340                 return -ENOMEM;
5341
5342         fn = file_name_from_path(to);
5343         k = fn-to;
5344         memcpy(t, to, k);
5345         t[k] = '.';
5346         x = stpcpy(t+k+1, fn);
5347
5348         ull = random_ull();
5349         for (i = 0; i < 16; i++) {
5350                 *(x++) = hexchar(ull & 0xF);
5351                 ull >>= 4;
5352         }
5353
5354         *x = 0;
5355
5356         r = symlink_or_copy(from, t);
5357         if (r < 0) {
5358                 unlink(t);
5359                 free(t);
5360                 return r;
5361         }
5362
5363         if (rename(t, to) < 0) {
5364                 r = -errno;
5365                 unlink(t);
5366                 free(t);
5367                 return r;
5368         }
5369
5370         free(t);
5371         return r;
5372 }
5373
5374 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5375         char *s;
5376         uint32_t u;
5377         int r;
5378
5379         assert(id);
5380
5381         if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5382                 return -ENOENT;
5383
5384         if (pid == 0)
5385                 r = read_one_line_file("/proc/self/sessionid", &s);
5386         else {
5387                 char *p;
5388
5389                 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5390                         return -ENOMEM;
5391
5392                 r = read_one_line_file(p, &s);
5393                 free(p);
5394         }
5395
5396         if (r < 0)
5397                 return r;
5398
5399         r = safe_atou32(s, &u);
5400         free(s);
5401
5402         if (r < 0)
5403                 return r;
5404
5405         if (u == (uint32_t) -1 || u <= 0)
5406                 return -ENOENT;
5407
5408         *id = u;
5409         return 0;
5410 }
5411
5412 int audit_loginuid_from_pid(pid_t pid, uid_t *uid) {
5413         char *s;
5414         uid_t u;
5415         int r;
5416
5417         assert(uid);
5418
5419         /* Only use audit login uid if we are executed with sufficient
5420          * capabilities so that pam_loginuid could do its job. If we
5421          * are lacking the CAP_AUDIT_CONTROL capabality we most likely
5422          * are being run in a container and /proc/self/loginuid is
5423          * useless since it probably contains a uid of the host
5424          * system. */
5425
5426         if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5427                 return -ENOENT;
5428
5429         if (pid == 0)
5430                 r = read_one_line_file("/proc/self/loginuid", &s);
5431         else {
5432                 char *p;
5433
5434                 if (asprintf(&p, "/proc/%lu/loginuid", (unsigned long) pid) < 0)
5435                         return -ENOMEM;
5436
5437                 r = read_one_line_file(p, &s);
5438                 free(p);
5439         }
5440
5441         if (r < 0)
5442                 return r;
5443
5444         r = parse_uid(s, &u);
5445         free(s);
5446
5447         if (r < 0)
5448                 return r;
5449
5450         if (u == (uid_t) -1)
5451                 return -ENOENT;
5452
5453         *uid = (uid_t) u;
5454         return 0;
5455 }
5456
5457 bool display_is_local(const char *display) {
5458         assert(display);
5459
5460         return
5461                 display[0] == ':' &&
5462                 display[1] >= '0' &&
5463                 display[1] <= '9';
5464 }
5465
5466 int socket_from_display(const char *display, char **path) {
5467         size_t k;
5468         char *f, *c;
5469
5470         assert(display);
5471         assert(path);
5472
5473         if (!display_is_local(display))
5474                 return -EINVAL;
5475
5476         k = strspn(display+1, "0123456789");
5477
5478         f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5479         if (!f)
5480                 return -ENOMEM;
5481
5482         c = stpcpy(f, "/tmp/.X11-unix/X");
5483         memcpy(c, display+1, k);
5484         c[k] = 0;
5485
5486         *path = f;
5487
5488         return 0;
5489 }
5490
5491 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5492         struct passwd *p;
5493         uid_t u;
5494
5495         assert(username);
5496         assert(*username);
5497
5498         /* We enforce some special rules for uid=0: in order to avoid
5499          * NSS lookups for root we hardcode its data. */
5500
5501         if (streq(*username, "root") || streq(*username, "0")) {
5502                 *username = "root";
5503
5504                 if (uid)
5505                         *uid = 0;
5506
5507                 if (gid)
5508                         *gid = 0;
5509
5510                 if (home)
5511                         *home = "/root";
5512                 return 0;
5513         }
5514
5515         if (parse_uid(*username, &u) >= 0) {
5516                 errno = 0;
5517                 p = getpwuid(u);
5518
5519                 /* If there are multiple users with the same id, make
5520                  * sure to leave $USER to the configured value instead
5521                  * of the first occurrence in the database. However if
5522                  * the uid was configured by a numeric uid, then let's
5523                  * pick the real username from /etc/passwd. */
5524                 if (p)
5525                         *username = p->pw_name;
5526         } else {
5527                 errno = 0;
5528                 p = getpwnam(*username);
5529         }
5530
5531         if (!p)
5532                 return errno != 0 ? -errno : -ESRCH;
5533
5534         if (uid)
5535                 *uid = p->pw_uid;
5536
5537         if (gid)
5538                 *gid = p->pw_gid;
5539
5540         if (home)
5541                 *home = p->pw_dir;
5542
5543         return 0;
5544 }
5545
5546 int get_group_creds(const char **groupname, gid_t *gid) {
5547         struct group *g;
5548         gid_t id;
5549
5550         assert(groupname);
5551
5552         /* We enforce some special rules for gid=0: in order to avoid
5553          * NSS lookups for root we hardcode its data. */
5554
5555         if (streq(*groupname, "root") || streq(*groupname, "0")) {
5556                 *groupname = "root";
5557
5558                 if (gid)
5559                         *gid = 0;
5560
5561                 return 0;
5562         }
5563
5564         if (parse_gid(*groupname, &id) >= 0) {
5565                 errno = 0;
5566                 g = getgrgid(id);
5567
5568                 if (g)
5569                         *groupname = g->gr_name;
5570         } else {
5571                 errno = 0;
5572                 g = getgrnam(*groupname);
5573         }
5574
5575         if (!g)
5576                 return errno != 0 ? -errno : -ESRCH;
5577
5578         if (gid)
5579                 *gid = g->gr_gid;
5580
5581         return 0;
5582 }
5583
5584 int glob_exists(const char *path) {
5585         glob_t g;
5586         int r, k;
5587
5588         assert(path);
5589
5590         zero(g);
5591         errno = 0;
5592         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5593
5594         if (k == GLOB_NOMATCH)
5595                 r = 0;
5596         else if (k == GLOB_NOSPACE)
5597                 r = -ENOMEM;
5598         else if (k == 0)
5599                 r = !strv_isempty(g.gl_pathv);
5600         else
5601                 r = errno ? -errno : -EIO;
5602
5603         globfree(&g);
5604
5605         return r;
5606 }
5607
5608 int dirent_ensure_type(DIR *d, struct dirent *de) {
5609         struct stat st;
5610
5611         assert(d);
5612         assert(de);
5613
5614         if (de->d_type != DT_UNKNOWN)
5615                 return 0;
5616
5617         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5618                 return -errno;
5619
5620         de->d_type =
5621                 S_ISREG(st.st_mode)  ? DT_REG  :
5622                 S_ISDIR(st.st_mode)  ? DT_DIR  :
5623                 S_ISLNK(st.st_mode)  ? DT_LNK  :
5624                 S_ISFIFO(st.st_mode) ? DT_FIFO :
5625                 S_ISSOCK(st.st_mode) ? DT_SOCK :
5626                 S_ISCHR(st.st_mode)  ? DT_CHR  :
5627                 S_ISBLK(st.st_mode)  ? DT_BLK  :
5628                                        DT_UNKNOWN;
5629
5630         return 0;
5631 }
5632
5633 int in_search_path(const char *path, char **search) {
5634         char **i, *parent;
5635         int r;
5636
5637         r = parent_of_path(path, &parent);
5638         if (r < 0)
5639                 return r;
5640
5641         r = 0;
5642
5643         STRV_FOREACH(i, search) {
5644                 if (path_equal(parent, *i)) {
5645                         r = 1;
5646                         break;
5647                 }
5648         }
5649
5650         free(parent);
5651
5652         return r;
5653 }
5654
5655 int get_files_in_directory(const char *path, char ***list) {
5656         DIR *d;
5657         int r = 0;
5658         unsigned n = 0;
5659         char **l = NULL;
5660
5661         assert(path);
5662
5663         /* Returns all files in a directory in *list, and the number
5664          * of files as return value. If list is NULL returns only the
5665          * number */
5666
5667         d = opendir(path);
5668         if (!d)
5669                 return -errno;
5670
5671         for (;;) {
5672                 struct dirent buffer, *de;
5673                 int k;
5674
5675                 k = readdir_r(d, &buffer, &de);
5676                 if (k != 0) {
5677                         r = -k;
5678                         goto finish;
5679                 }
5680
5681                 if (!de)
5682                         break;
5683
5684                 dirent_ensure_type(d, de);
5685
5686                 if (!dirent_is_file(de))
5687                         continue;
5688
5689                 if (list) {
5690                         if ((unsigned) r >= n) {
5691                                 char **t;
5692
5693                                 n = MAX(16, 2*r);
5694                                 t = realloc(l, sizeof(char*) * n);
5695                                 if (!t) {
5696                                         r = -ENOMEM;
5697                                         goto finish;
5698                                 }
5699
5700                                 l = t;
5701                         }
5702
5703                         assert((unsigned) r < n);
5704
5705                         l[r] = strdup(de->d_name);
5706                         if (!l[r]) {
5707                                 r = -ENOMEM;
5708                                 goto finish;
5709                         }
5710
5711                         l[++r] = NULL;
5712                 } else
5713                         r++;
5714         }
5715
5716 finish:
5717         if (d)
5718                 closedir(d);
5719
5720         if (r >= 0) {
5721                 if (list)
5722                         *list = l;
5723         } else
5724                 strv_free(l);
5725
5726         return r;
5727 }
5728
5729 char *join(const char *x, ...) {
5730         va_list ap;
5731         size_t l;
5732         char *r, *p;
5733
5734         va_start(ap, x);
5735
5736         if (x) {
5737                 l = strlen(x);
5738
5739                 for (;;) {
5740                         const char *t;
5741
5742                         t = va_arg(ap, const char *);
5743                         if (!t)
5744                                 break;
5745
5746                         l += strlen(t);
5747                 }
5748         } else
5749                 l = 0;
5750
5751         va_end(ap);
5752
5753         r = new(char, l+1);
5754         if (!r)
5755                 return NULL;
5756
5757         if (x) {
5758                 p = stpcpy(r, x);
5759
5760                 va_start(ap, x);
5761
5762                 for (;;) {
5763                         const char *t;
5764
5765                         t = va_arg(ap, const char *);
5766                         if (!t)
5767                                 break;
5768
5769                         p = stpcpy(p, t);
5770                 }
5771
5772                 va_end(ap);
5773         } else
5774                 r[0] = 0;
5775
5776         return r;
5777 }
5778
5779 bool is_main_thread(void) {
5780         static __thread int cached = 0;
5781
5782         if (_unlikely_(cached == 0))
5783                 cached = getpid() == gettid() ? 1 : -1;
5784
5785         return cached > 0;
5786 }
5787
5788 int block_get_whole_disk(dev_t d, dev_t *ret) {
5789         char *p, *s;
5790         int r;
5791         unsigned n, m;
5792
5793         assert(ret);
5794
5795         /* If it has a queue this is good enough for us */
5796         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5797                 return -ENOMEM;
5798
5799         r = access(p, F_OK);
5800         free(p);
5801
5802         if (r >= 0) {
5803                 *ret = d;
5804                 return 0;
5805         }
5806
5807         /* If it is a partition find the originating device */
5808         if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5809                 return -ENOMEM;
5810
5811         r = access(p, F_OK);
5812         free(p);
5813
5814         if (r < 0)
5815                 return -ENOENT;
5816
5817         /* Get parent dev_t */
5818         if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5819                 return -ENOMEM;
5820
5821         r = read_one_line_file(p, &s);
5822         free(p);
5823
5824         if (r < 0)
5825                 return r;
5826
5827         r = sscanf(s, "%u:%u", &m, &n);
5828         free(s);
5829
5830         if (r != 2)
5831                 return -EINVAL;
5832
5833         /* Only return this if it is really good enough for us. */
5834         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5835                 return -ENOMEM;
5836
5837         r = access(p, F_OK);
5838         free(p);
5839
5840         if (r >= 0) {
5841                 *ret = makedev(m, n);
5842                 return 0;
5843         }
5844
5845         return -ENOENT;
5846 }
5847
5848 int file_is_priv_sticky(const char *p) {
5849         struct stat st;
5850
5851         assert(p);
5852
5853         if (lstat(p, &st) < 0)
5854                 return -errno;
5855
5856         return
5857                 (st.st_uid == 0 || st.st_uid == getuid()) &&
5858                 (st.st_mode & S_ISVTX);
5859 }
5860
5861 static const char *const ioprio_class_table[] = {
5862         [IOPRIO_CLASS_NONE] = "none",
5863         [IOPRIO_CLASS_RT] = "realtime",
5864         [IOPRIO_CLASS_BE] = "best-effort",
5865         [IOPRIO_CLASS_IDLE] = "idle"
5866 };
5867
5868 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5869
5870 static const char *const sigchld_code_table[] = {
5871         [CLD_EXITED] = "exited",
5872         [CLD_KILLED] = "killed",
5873         [CLD_DUMPED] = "dumped",
5874         [CLD_TRAPPED] = "trapped",
5875         [CLD_STOPPED] = "stopped",
5876         [CLD_CONTINUED] = "continued",
5877 };
5878
5879 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5880
5881 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5882         [LOG_FAC(LOG_KERN)] = "kern",
5883         [LOG_FAC(LOG_USER)] = "user",
5884         [LOG_FAC(LOG_MAIL)] = "mail",
5885         [LOG_FAC(LOG_DAEMON)] = "daemon",
5886         [LOG_FAC(LOG_AUTH)] = "auth",
5887         [LOG_FAC(LOG_SYSLOG)] = "syslog",
5888         [LOG_FAC(LOG_LPR)] = "lpr",
5889         [LOG_FAC(LOG_NEWS)] = "news",
5890         [LOG_FAC(LOG_UUCP)] = "uucp",
5891         [LOG_FAC(LOG_CRON)] = "cron",
5892         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5893         [LOG_FAC(LOG_FTP)] = "ftp",
5894         [LOG_FAC(LOG_LOCAL0)] = "local0",
5895         [LOG_FAC(LOG_LOCAL1)] = "local1",
5896         [LOG_FAC(LOG_LOCAL2)] = "local2",
5897         [LOG_FAC(LOG_LOCAL3)] = "local3",
5898         [LOG_FAC(LOG_LOCAL4)] = "local4",
5899         [LOG_FAC(LOG_LOCAL5)] = "local5",
5900         [LOG_FAC(LOG_LOCAL6)] = "local6",
5901         [LOG_FAC(LOG_LOCAL7)] = "local7"
5902 };
5903
5904 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5905
5906 static const char *const log_level_table[] = {
5907         [LOG_EMERG] = "emerg",
5908         [LOG_ALERT] = "alert",
5909         [LOG_CRIT] = "crit",
5910         [LOG_ERR] = "err",
5911         [LOG_WARNING] = "warning",
5912         [LOG_NOTICE] = "notice",
5913         [LOG_INFO] = "info",
5914         [LOG_DEBUG] = "debug"
5915 };
5916
5917 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5918
5919 static const char* const sched_policy_table[] = {
5920         [SCHED_OTHER] = "other",
5921         [SCHED_BATCH] = "batch",
5922         [SCHED_IDLE] = "idle",
5923         [SCHED_FIFO] = "fifo",
5924         [SCHED_RR] = "rr"
5925 };
5926
5927 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5928
5929 static const char* const rlimit_table[] = {
5930         [RLIMIT_CPU] = "LimitCPU",
5931         [RLIMIT_FSIZE] = "LimitFSIZE",
5932         [RLIMIT_DATA] = "LimitDATA",
5933         [RLIMIT_STACK] = "LimitSTACK",
5934         [RLIMIT_CORE] = "LimitCORE",
5935         [RLIMIT_RSS] = "LimitRSS",
5936         [RLIMIT_NOFILE] = "LimitNOFILE",
5937         [RLIMIT_AS] = "LimitAS",
5938         [RLIMIT_NPROC] = "LimitNPROC",
5939         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5940         [RLIMIT_LOCKS] = "LimitLOCKS",
5941         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5942         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5943         [RLIMIT_NICE] = "LimitNICE",
5944         [RLIMIT_RTPRIO] = "LimitRTPRIO",
5945         [RLIMIT_RTTIME] = "LimitRTTIME"
5946 };
5947
5948 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5949
5950 static const char* const ip_tos_table[] = {
5951         [IPTOS_LOWDELAY] = "low-delay",
5952         [IPTOS_THROUGHPUT] = "throughput",
5953         [IPTOS_RELIABILITY] = "reliability",
5954         [IPTOS_LOWCOST] = "low-cost",
5955 };
5956
5957 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5958
5959 static const char *const __signal_table[] = {
5960         [SIGHUP] = "HUP",
5961         [SIGINT] = "INT",
5962         [SIGQUIT] = "QUIT",
5963         [SIGILL] = "ILL",
5964         [SIGTRAP] = "TRAP",
5965         [SIGABRT] = "ABRT",
5966         [SIGBUS] = "BUS",
5967         [SIGFPE] = "FPE",
5968         [SIGKILL] = "KILL",
5969         [SIGUSR1] = "USR1",
5970         [SIGSEGV] = "SEGV",
5971         [SIGUSR2] = "USR2",
5972         [SIGPIPE] = "PIPE",
5973         [SIGALRM] = "ALRM",
5974         [SIGTERM] = "TERM",
5975 #ifdef SIGSTKFLT
5976         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
5977 #endif
5978         [SIGCHLD] = "CHLD",
5979         [SIGCONT] = "CONT",
5980         [SIGSTOP] = "STOP",
5981         [SIGTSTP] = "TSTP",
5982         [SIGTTIN] = "TTIN",
5983         [SIGTTOU] = "TTOU",
5984         [SIGURG] = "URG",
5985         [SIGXCPU] = "XCPU",
5986         [SIGXFSZ] = "XFSZ",
5987         [SIGVTALRM] = "VTALRM",
5988         [SIGPROF] = "PROF",
5989         [SIGWINCH] = "WINCH",
5990         [SIGIO] = "IO",
5991         [SIGPWR] = "PWR",
5992         [SIGSYS] = "SYS"
5993 };
5994
5995 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5996
5997 const char *signal_to_string(int signo) {
5998         static __thread char buf[12];
5999         const char *name;
6000
6001         name = __signal_to_string(signo);
6002         if (name)
6003                 return name;
6004
6005         if (signo >= SIGRTMIN && signo <= SIGRTMAX)
6006                 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
6007         else
6008                 snprintf(buf, sizeof(buf) - 1, "%d", signo);
6009         char_array_0(buf);
6010         return buf;
6011 }
6012
6013 int signal_from_string(const char *s) {
6014         int signo;
6015         int offset = 0;
6016         unsigned u;
6017
6018         signo =__signal_from_string(s);
6019         if (signo > 0)
6020                 return signo;
6021
6022         if (startswith(s, "RTMIN+")) {
6023                 s += 6;
6024                 offset = SIGRTMIN;
6025         }
6026         if (safe_atou(s, &u) >= 0) {
6027                 signo = (int) u + offset;
6028                 if (signo > 0 && signo < _NSIG)
6029                         return signo;
6030         }
6031         return -1;
6032 }
6033
6034 bool kexec_loaded(void) {
6035        bool loaded = false;
6036        char *s;
6037
6038        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
6039                if (s[0] == '1')
6040                        loaded = true;
6041                free(s);
6042        }
6043        return loaded;
6044 }
6045
6046 int strdup_or_null(const char *a, char **b) {
6047         char *c;
6048
6049         assert(b);
6050
6051         if (!a) {
6052                 *b = NULL;
6053                 return 0;
6054         }
6055
6056         c = strdup(a);
6057         if (!c)
6058                 return -ENOMEM;
6059
6060         *b = c;
6061         return 0;
6062 }
6063
6064 int prot_from_flags(int flags) {
6065
6066         switch (flags & O_ACCMODE) {
6067
6068         case O_RDONLY:
6069                 return PROT_READ;
6070
6071         case O_WRONLY:
6072                 return PROT_WRITE;
6073
6074         case O_RDWR:
6075                 return PROT_READ|PROT_WRITE;
6076
6077         default:
6078                 return -EINVAL;
6079         }
6080 }
6081
6082 unsigned long cap_last_cap(void) {
6083         static __thread unsigned long saved;
6084         static __thread bool valid = false;
6085         unsigned long p;
6086
6087         if (valid)
6088                 return saved;
6089
6090         p = (unsigned long) CAP_LAST_CAP;
6091
6092         if (prctl(PR_CAPBSET_READ, p) < 0) {
6093
6094                 /* Hmm, look downwards, until we find one that
6095                  * works */
6096                 for (p--; p > 0; p --)
6097                         if (prctl(PR_CAPBSET_READ, p) >= 0)
6098                                 break;
6099
6100         } else {
6101
6102                 /* Hmm, look upwards, until we find one that doesn't
6103                  * work */
6104                 for (;; p++)
6105                         if (prctl(PR_CAPBSET_READ, p+1) < 0)
6106                                 break;
6107         }
6108
6109         saved = p;
6110         valid = true;
6111
6112         return p;
6113 }
6114
6115 char *format_bytes(char *buf, size_t l, off_t t) {
6116         unsigned i;
6117
6118         static const struct {
6119                 const char *suffix;
6120                 off_t factor;
6121         } table[] = {
6122                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6123                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6124                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
6125                 { "G", 1024ULL*1024ULL*1024ULL },
6126                 { "M", 1024ULL*1024ULL },
6127                 { "K", 1024ULL },
6128         };
6129
6130         for (i = 0; i < ELEMENTSOF(table); i++) {
6131
6132                 if (t >= table[i].factor) {
6133                         snprintf(buf, l,
6134                                  "%llu.%llu%s",
6135                                  (unsigned long long) (t / table[i].factor),
6136                                  (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
6137                                  table[i].suffix);
6138
6139                         goto finish;
6140                 }
6141         }
6142
6143         snprintf(buf, l, "%lluB", (unsigned long long) t);
6144
6145 finish:
6146         buf[l-1] = 0;
6147         return buf;
6148
6149 }
6150
6151 void* memdup(const void *p, size_t l) {
6152         void *r;
6153
6154         assert(p);
6155
6156         r = malloc(l);
6157         if (!r)
6158                 return NULL;
6159
6160         memcpy(r, p, l);
6161         return r;
6162 }
6163
6164 int fd_inc_sndbuf(int fd, size_t n) {
6165         int r, value;
6166         socklen_t l = sizeof(value);
6167
6168         r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
6169         if (r >= 0 &&
6170             l == sizeof(value) &&
6171             (size_t) value >= n*2)
6172                 return 0;
6173
6174         value = (int) n;
6175         r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
6176         if (r < 0)
6177                 return -errno;
6178
6179         return 1;
6180 }
6181
6182 int fd_inc_rcvbuf(int fd, size_t n) {
6183         int r, value;
6184         socklen_t l = sizeof(value);
6185
6186         r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
6187         if (r >= 0 &&
6188             l == sizeof(value) &&
6189             (size_t) value >= n*2)
6190                 return 0;
6191
6192         value = (int) n;
6193         r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
6194         if (r < 0)
6195                 return -errno;
6196
6197         return 1;
6198 }