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