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