chiark / gitweb /
README: correct license claims
[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         long arg;
2457
2458         /* Set terminal to some sane defaults */
2459
2460         assert(fd >= 0);
2461
2462         /* We leave locked terminal attributes untouched, so that
2463          * Plymouth may set whatever it wants to set, and we don't
2464          * interfere with that. */
2465
2466         /* Disable exclusive mode, just in case */
2467         ioctl(fd, TIOCNXCL);
2468
2469         /* Enable console unicode mode */
2470         arg = K_UNICODE;
2471         ioctl(fd, KDSKBMODE, &arg);
2472
2473         if (tcgetattr(fd, &termios) < 0) {
2474                 r = -errno;
2475                 goto finish;
2476         }
2477
2478         /* We only reset the stuff that matters to the software. How
2479          * hardware is set up we don't touch assuming that somebody
2480          * else will do that for us */
2481
2482         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2483         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2484         termios.c_oflag |= ONLCR;
2485         termios.c_cflag |= CREAD;
2486         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2487
2488         termios.c_cc[VINTR]    =   03;  /* ^C */
2489         termios.c_cc[VQUIT]    =  034;  /* ^\ */
2490         termios.c_cc[VERASE]   = 0177;
2491         termios.c_cc[VKILL]    =  025;  /* ^X */
2492         termios.c_cc[VEOF]     =   04;  /* ^D */
2493         termios.c_cc[VSTART]   =  021;  /* ^Q */
2494         termios.c_cc[VSTOP]    =  023;  /* ^S */
2495         termios.c_cc[VSUSP]    =  032;  /* ^Z */
2496         termios.c_cc[VLNEXT]   =  026;  /* ^V */
2497         termios.c_cc[VWERASE]  =  027;  /* ^W */
2498         termios.c_cc[VREPRINT] =  022;  /* ^R */
2499         termios.c_cc[VEOL]     =    0;
2500         termios.c_cc[VEOL2]    =    0;
2501
2502         termios.c_cc[VTIME]  = 0;
2503         termios.c_cc[VMIN]   = 1;
2504
2505         if (tcsetattr(fd, TCSANOW, &termios) < 0)
2506                 r = -errno;
2507
2508 finish:
2509         /* Just in case, flush all crap out */
2510         tcflush(fd, TCIOFLUSH);
2511
2512         return r;
2513 }
2514
2515 int reset_terminal(const char *name) {
2516         int fd, r;
2517
2518         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2519         if (fd < 0)
2520                 return fd;
2521
2522         r = reset_terminal_fd(fd);
2523         close_nointr_nofail(fd);
2524
2525         return r;
2526 }
2527
2528 int open_terminal(const char *name, int mode) {
2529         int fd, r;
2530         unsigned c = 0;
2531
2532         /*
2533          * If a TTY is in the process of being closed opening it might
2534          * cause EIO. This is horribly awful, but unlikely to be
2535          * changed in the kernel. Hence we work around this problem by
2536          * retrying a couple of times.
2537          *
2538          * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2539          */
2540
2541         for (;;) {
2542                 if ((fd = open(name, mode)) >= 0)
2543                         break;
2544
2545                 if (errno != EIO)
2546                         return -errno;
2547
2548                 if (c >= 20)
2549                         return -errno;
2550
2551                 usleep(50 * USEC_PER_MSEC);
2552                 c++;
2553         }
2554
2555         if (fd < 0)
2556                 return -errno;
2557
2558         if ((r = isatty(fd)) < 0) {
2559                 close_nointr_nofail(fd);
2560                 return -errno;
2561         }
2562
2563         if (!r) {
2564                 close_nointr_nofail(fd);
2565                 return -ENOTTY;
2566         }
2567
2568         return fd;
2569 }
2570
2571 int flush_fd(int fd) {
2572         struct pollfd pollfd;
2573
2574         zero(pollfd);
2575         pollfd.fd = fd;
2576         pollfd.events = POLLIN;
2577
2578         for (;;) {
2579                 char buf[LINE_MAX];
2580                 ssize_t l;
2581                 int r;
2582
2583                 if ((r = poll(&pollfd, 1, 0)) < 0) {
2584
2585                         if (errno == EINTR)
2586                                 continue;
2587
2588                         return -errno;
2589                 }
2590
2591                 if (r == 0)
2592                         return 0;
2593
2594                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2595
2596                         if (errno == EINTR)
2597                                 continue;
2598
2599                         if (errno == EAGAIN)
2600                                 return 0;
2601
2602                         return -errno;
2603                 }
2604
2605                 if (l <= 0)
2606                         return 0;
2607         }
2608 }
2609
2610 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2611         int fd = -1, notify = -1, r, wd = -1;
2612
2613         assert(name);
2614
2615         /* We use inotify to be notified when the tty is closed. We
2616          * create the watch before checking if we can actually acquire
2617          * it, so that we don't lose any event.
2618          *
2619          * Note: strictly speaking this actually watches for the
2620          * device being closed, it does *not* really watch whether a
2621          * tty loses its controlling process. However, unless some
2622          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2623          * its tty otherwise this will not become a problem. As long
2624          * as the administrator makes sure not configure any service
2625          * on the same tty as an untrusted user this should not be a
2626          * problem. (Which he probably should not do anyway.) */
2627
2628         if (!fail && !force) {
2629                 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2630                         r = -errno;
2631                         goto fail;
2632                 }
2633
2634                 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2635                         r = -errno;
2636                         goto fail;
2637                 }
2638         }
2639
2640         for (;;) {
2641                 if (notify >= 0)
2642                         if ((r = flush_fd(notify)) < 0)
2643                                 goto fail;
2644
2645                 /* We pass here O_NOCTTY only so that we can check the return
2646                  * value TIOCSCTTY and have a reliable way to figure out if we
2647                  * successfully became the controlling process of the tty */
2648                 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2649                         return fd;
2650
2651                 /* First, try to get the tty */
2652                 r = ioctl(fd, TIOCSCTTY, force);
2653
2654                 /* Sometimes it makes sense to ignore TIOCSCTTY
2655                  * returning EPERM, i.e. when very likely we already
2656                  * are have this controlling terminal. */
2657                 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2658                         r = 0;
2659
2660                 if (r < 0 && (force || fail || errno != EPERM)) {
2661                         r = -errno;
2662                         goto fail;
2663                 }
2664
2665                 if (r >= 0)
2666                         break;
2667
2668                 assert(!fail);
2669                 assert(!force);
2670                 assert(notify >= 0);
2671
2672                 for (;;) {
2673                         uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2674                         ssize_t l;
2675                         struct inotify_event *e;
2676
2677                         if ((l = read(notify, inotify_buffer, sizeof(inotify_buffer))) < 0) {
2678
2679                                 if (errno == EINTR)
2680                                         continue;
2681
2682                                 r = -errno;
2683                                 goto fail;
2684                         }
2685
2686                         e = (struct inotify_event*) inotify_buffer;
2687
2688                         while (l > 0) {
2689                                 size_t step;
2690
2691                                 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2692                                         r = -EIO;
2693                                         goto fail;
2694                                 }
2695
2696                                 step = sizeof(struct inotify_event) + e->len;
2697                                 assert(step <= (size_t) l);
2698
2699                                 e = (struct inotify_event*) ((uint8_t*) e + step);
2700                                 l -= step;
2701                         }
2702
2703                         break;
2704                 }
2705
2706                 /* We close the tty fd here since if the old session
2707                  * ended our handle will be dead. It's important that
2708                  * we do this after sleeping, so that we don't enter
2709                  * an endless loop. */
2710                 close_nointr_nofail(fd);
2711         }
2712
2713         if (notify >= 0)
2714                 close_nointr_nofail(notify);
2715
2716         if ((r = reset_terminal_fd(fd)) < 0)
2717                 log_warning("Failed to reset terminal: %s", strerror(-r));
2718
2719         return fd;
2720
2721 fail:
2722         if (fd >= 0)
2723                 close_nointr_nofail(fd);
2724
2725         if (notify >= 0)
2726                 close_nointr_nofail(notify);
2727
2728         return r;
2729 }
2730
2731 int release_terminal(void) {
2732         int r = 0, fd;
2733         struct sigaction sa_old, sa_new;
2734
2735         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2736                 return -errno;
2737
2738         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2739          * by our own TIOCNOTTY */
2740
2741         zero(sa_new);
2742         sa_new.sa_handler = SIG_IGN;
2743         sa_new.sa_flags = SA_RESTART;
2744         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2745
2746         if (ioctl(fd, TIOCNOTTY) < 0)
2747                 r = -errno;
2748
2749         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2750
2751         close_nointr_nofail(fd);
2752         return r;
2753 }
2754
2755 int sigaction_many(const struct sigaction *sa, ...) {
2756         va_list ap;
2757         int r = 0, sig;
2758
2759         va_start(ap, sa);
2760         while ((sig = va_arg(ap, int)) > 0)
2761                 if (sigaction(sig, sa, NULL) < 0)
2762                         r = -errno;
2763         va_end(ap);
2764
2765         return r;
2766 }
2767
2768 int ignore_signals(int sig, ...) {
2769         struct sigaction sa;
2770         va_list ap;
2771         int r = 0;
2772
2773         zero(sa);
2774         sa.sa_handler = SIG_IGN;
2775         sa.sa_flags = SA_RESTART;
2776
2777         if (sigaction(sig, &sa, NULL) < 0)
2778                 r = -errno;
2779
2780         va_start(ap, sig);
2781         while ((sig = va_arg(ap, int)) > 0)
2782                 if (sigaction(sig, &sa, NULL) < 0)
2783                         r = -errno;
2784         va_end(ap);
2785
2786         return r;
2787 }
2788
2789 int default_signals(int sig, ...) {
2790         struct sigaction sa;
2791         va_list ap;
2792         int r = 0;
2793
2794         zero(sa);
2795         sa.sa_handler = SIG_DFL;
2796         sa.sa_flags = SA_RESTART;
2797
2798         if (sigaction(sig, &sa, NULL) < 0)
2799                 r = -errno;
2800
2801         va_start(ap, sig);
2802         while ((sig = va_arg(ap, int)) > 0)
2803                 if (sigaction(sig, &sa, NULL) < 0)
2804                         r = -errno;
2805         va_end(ap);
2806
2807         return r;
2808 }
2809
2810 int close_pipe(int p[]) {
2811         int a = 0, b = 0;
2812
2813         assert(p);
2814
2815         if (p[0] >= 0) {
2816                 a = close_nointr(p[0]);
2817                 p[0] = -1;
2818         }
2819
2820         if (p[1] >= 0) {
2821                 b = close_nointr(p[1]);
2822                 p[1] = -1;
2823         }
2824
2825         return a < 0 ? a : b;
2826 }
2827
2828 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2829         uint8_t *p;
2830         ssize_t n = 0;
2831
2832         assert(fd >= 0);
2833         assert(buf);
2834
2835         p = buf;
2836
2837         while (nbytes > 0) {
2838                 ssize_t k;
2839
2840                 if ((k = read(fd, p, nbytes)) <= 0) {
2841
2842                         if (k < 0 && errno == EINTR)
2843                                 continue;
2844
2845                         if (k < 0 && errno == EAGAIN && do_poll) {
2846                                 struct pollfd pollfd;
2847
2848                                 zero(pollfd);
2849                                 pollfd.fd = fd;
2850                                 pollfd.events = POLLIN;
2851
2852                                 if (poll(&pollfd, 1, -1) < 0) {
2853                                         if (errno == EINTR)
2854                                                 continue;
2855
2856                                         return n > 0 ? n : -errno;
2857                                 }
2858
2859                                 if (pollfd.revents != POLLIN)
2860                                         return n > 0 ? n : -EIO;
2861
2862                                 continue;
2863                         }
2864
2865                         return n > 0 ? n : (k < 0 ? -errno : 0);
2866                 }
2867
2868                 p += k;
2869                 nbytes -= k;
2870                 n += k;
2871         }
2872
2873         return n;
2874 }
2875
2876 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2877         const uint8_t *p;
2878         ssize_t n = 0;
2879
2880         assert(fd >= 0);
2881         assert(buf);
2882
2883         p = buf;
2884
2885         while (nbytes > 0) {
2886                 ssize_t k;
2887
2888                 k = write(fd, p, nbytes);
2889                 if (k <= 0) {
2890
2891                         if (k < 0 && errno == EINTR)
2892                                 continue;
2893
2894                         if (k < 0 && errno == EAGAIN && do_poll) {
2895                                 struct pollfd pollfd;
2896
2897                                 zero(pollfd);
2898                                 pollfd.fd = fd;
2899                                 pollfd.events = POLLOUT;
2900
2901                                 if (poll(&pollfd, 1, -1) < 0) {
2902                                         if (errno == EINTR)
2903                                                 continue;
2904
2905                                         return n > 0 ? n : -errno;
2906                                 }
2907
2908                                 if (pollfd.revents != POLLOUT)
2909                                         return n > 0 ? n : -EIO;
2910
2911                                 continue;
2912                         }
2913
2914                         return n > 0 ? n : (k < 0 ? -errno : 0);
2915                 }
2916
2917                 p += k;
2918                 nbytes -= k;
2919                 n += k;
2920         }
2921
2922         return n;
2923 }
2924
2925 int path_is_mount_point(const char *t, bool allow_symlink) {
2926         struct stat a, b;
2927         char *parent;
2928         int r;
2929
2930         if (allow_symlink)
2931                 r = stat(t, &a);
2932         else
2933                 r = lstat(t, &a);
2934
2935         if (r < 0) {
2936                 if (errno == ENOENT)
2937                         return 0;
2938
2939                 return -errno;
2940         }
2941
2942         r = parent_of_path(t, &parent);
2943         if (r < 0)
2944                 return r;
2945
2946         r = lstat(parent, &b);
2947         free(parent);
2948
2949         if (r < 0)
2950                 return -errno;
2951
2952         return a.st_dev != b.st_dev;
2953 }
2954
2955 int parse_usec(const char *t, usec_t *usec) {
2956         static const struct {
2957                 const char *suffix;
2958                 usec_t usec;
2959         } table[] = {
2960                 { "sec", USEC_PER_SEC },
2961                 { "s", USEC_PER_SEC },
2962                 { "min", USEC_PER_MINUTE },
2963                 { "hr", USEC_PER_HOUR },
2964                 { "h", USEC_PER_HOUR },
2965                 { "d", USEC_PER_DAY },
2966                 { "w", USEC_PER_WEEK },
2967                 { "msec", USEC_PER_MSEC },
2968                 { "ms", USEC_PER_MSEC },
2969                 { "m", USEC_PER_MINUTE },
2970                 { "usec", 1ULL },
2971                 { "us", 1ULL },
2972                 { "", USEC_PER_SEC },
2973         };
2974
2975         const char *p;
2976         usec_t r = 0;
2977
2978         assert(t);
2979         assert(usec);
2980
2981         p = t;
2982         do {
2983                 long long l;
2984                 char *e;
2985                 unsigned i;
2986
2987                 errno = 0;
2988                 l = strtoll(p, &e, 10);
2989
2990                 if (errno != 0)
2991                         return -errno;
2992
2993                 if (l < 0)
2994                         return -ERANGE;
2995
2996                 if (e == p)
2997                         return -EINVAL;
2998
2999                 e += strspn(e, WHITESPACE);
3000
3001                 for (i = 0; i < ELEMENTSOF(table); i++)
3002                         if (startswith(e, table[i].suffix)) {
3003                                 r += (usec_t) l * table[i].usec;
3004                                 p = e + strlen(table[i].suffix);
3005                                 break;
3006                         }
3007
3008                 if (i >= ELEMENTSOF(table))
3009                         return -EINVAL;
3010
3011         } while (*p != 0);
3012
3013         *usec = r;
3014
3015         return 0;
3016 }
3017
3018 int parse_bytes(const char *t, off_t *bytes) {
3019         static const struct {
3020                 const char *suffix;
3021                 off_t factor;
3022         } table[] = {
3023                 { "B", 1 },
3024                 { "K", 1024ULL },
3025                 { "M", 1024ULL*1024ULL },
3026                 { "G", 1024ULL*1024ULL*1024ULL },
3027                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
3028                 { "", 1 },
3029         };
3030
3031         const char *p;
3032         off_t r = 0;
3033
3034         assert(t);
3035         assert(bytes);
3036
3037         p = t;
3038         do {
3039                 long long l;
3040                 char *e;
3041                 unsigned i;
3042
3043                 errno = 0;
3044                 l = strtoll(p, &e, 10);
3045
3046                 if (errno != 0)
3047                         return -errno;
3048
3049                 if (l < 0)
3050                         return -ERANGE;
3051
3052                 if (e == p)
3053                         return -EINVAL;
3054
3055                 e += strspn(e, WHITESPACE);
3056
3057                 for (i = 0; i < ELEMENTSOF(table); i++)
3058                         if (startswith(e, table[i].suffix)) {
3059                                 r += (off_t) l * table[i].factor;
3060                                 p = e + strlen(table[i].suffix);
3061                                 break;
3062                         }
3063
3064                 if (i >= ELEMENTSOF(table))
3065                         return -EINVAL;
3066
3067         } while (*p != 0);
3068
3069         *bytes = r;
3070
3071         return 0;
3072 }
3073
3074 int make_stdio(int fd) {
3075         int r, s, t;
3076
3077         assert(fd >= 0);
3078
3079         r = dup2(fd, STDIN_FILENO);
3080         s = dup2(fd, STDOUT_FILENO);
3081         t = dup2(fd, STDERR_FILENO);
3082
3083         if (fd >= 3)
3084                 close_nointr_nofail(fd);
3085
3086         if (r < 0 || s < 0 || t < 0)
3087                 return -errno;
3088
3089         fd_cloexec(STDIN_FILENO, false);
3090         fd_cloexec(STDOUT_FILENO, false);
3091         fd_cloexec(STDERR_FILENO, false);
3092
3093         return 0;
3094 }
3095
3096 int make_null_stdio(void) {
3097         int null_fd;
3098
3099         if ((null_fd = open("/dev/null", O_RDWR|O_NOCTTY)) < 0)
3100                 return -errno;
3101
3102         return make_stdio(null_fd);
3103 }
3104
3105 bool is_device_path(const char *path) {
3106
3107         /* Returns true on paths that refer to a device, either in
3108          * sysfs or in /dev */
3109
3110         return
3111                 path_startswith(path, "/dev/") ||
3112                 path_startswith(path, "/sys/");
3113 }
3114
3115 int dir_is_empty(const char *path) {
3116         DIR *d;
3117         int r;
3118         struct dirent buf, *de;
3119
3120         if (!(d = opendir(path)))
3121                 return -errno;
3122
3123         for (;;) {
3124                 if ((r = readdir_r(d, &buf, &de)) > 0) {
3125                         r = -r;
3126                         break;
3127                 }
3128
3129                 if (!de) {
3130                         r = 1;
3131                         break;
3132                 }
3133
3134                 if (!ignore_file(de->d_name)) {
3135                         r = 0;
3136                         break;
3137                 }
3138         }
3139
3140         closedir(d);
3141         return r;
3142 }
3143
3144 unsigned long long random_ull(void) {
3145         int fd;
3146         uint64_t ull;
3147         ssize_t r;
3148
3149         if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3150                 goto fallback;
3151
3152         r = loop_read(fd, &ull, sizeof(ull), true);
3153         close_nointr_nofail(fd);
3154
3155         if (r != sizeof(ull))
3156                 goto fallback;
3157
3158         return ull;
3159
3160 fallback:
3161         return random() * RAND_MAX + random();
3162 }
3163
3164 void rename_process(const char name[8]) {
3165         assert(name);
3166
3167         prctl(PR_SET_NAME, name);
3168
3169         /* This is a like a poor man's setproctitle(). The string
3170          * passed should fit in 7 chars (i.e. the length of
3171          * "systemd") */
3172
3173         if (program_invocation_name)
3174                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3175
3176         if (saved_argc > 0) {
3177                 int i;
3178
3179                 if (saved_argv[0])
3180                         strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3181
3182                 for (i = 1; i < saved_argc; i++) {
3183                         if (!saved_argv[i])
3184                                 break;
3185
3186                         memset(saved_argv[i], 0, strlen(saved_argv[i]));
3187                 }
3188         }
3189 }
3190
3191 void sigset_add_many(sigset_t *ss, ...) {
3192         va_list ap;
3193         int sig;
3194
3195         assert(ss);
3196
3197         va_start(ap, ss);
3198         while ((sig = va_arg(ap, int)) > 0)
3199                 assert_se(sigaddset(ss, sig) == 0);
3200         va_end(ap);
3201 }
3202
3203 char* gethostname_malloc(void) {
3204         struct utsname u;
3205
3206         assert_se(uname(&u) >= 0);
3207
3208         if (u.nodename[0])
3209                 return strdup(u.nodename);
3210
3211         return strdup(u.sysname);
3212 }
3213
3214 char* getlogname_malloc(void) {
3215         uid_t uid;
3216         long bufsize;
3217         char *buf, *name;
3218         struct passwd pwbuf, *pw = NULL;
3219         struct stat st;
3220
3221         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3222                 uid = st.st_uid;
3223         else
3224                 uid = getuid();
3225
3226         /* Shortcut things to avoid NSS lookups */
3227         if (uid == 0)
3228                 return strdup("root");
3229
3230         if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3231                 bufsize = 4096;
3232
3233         if (!(buf = malloc(bufsize)))
3234                 return NULL;
3235
3236         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3237                 name = strdup(pw->pw_name);
3238                 free(buf);
3239                 return name;
3240         }
3241
3242         free(buf);
3243
3244         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3245                 return NULL;
3246
3247         return name;
3248 }
3249
3250 int getttyname_malloc(int fd, char **r) {
3251         char path[PATH_MAX], *c;
3252         int k;
3253
3254         assert(r);
3255
3256         if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3257                 return -k;
3258
3259         char_array_0(path);
3260
3261         if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3262                 return -ENOMEM;
3263
3264         *r = c;
3265         return 0;
3266 }
3267
3268 int getttyname_harder(int fd, char **r) {
3269         int k;
3270         char *s;
3271
3272         if ((k = getttyname_malloc(fd, &s)) < 0)
3273                 return k;
3274
3275         if (streq(s, "tty")) {
3276                 free(s);
3277                 return get_ctty(0, NULL, r);
3278         }
3279
3280         *r = s;
3281         return 0;
3282 }
3283
3284 int get_ctty_devnr(pid_t pid, dev_t *d) {
3285         int k;
3286         char line[LINE_MAX], *p, *fn;
3287         unsigned long ttynr;
3288         FILE *f;
3289
3290         if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3291                 return -ENOMEM;
3292
3293         f = fopen(fn, "re");
3294         free(fn);
3295         if (!f)
3296                 return -errno;
3297
3298         if (!fgets(line, sizeof(line), f)) {
3299                 k = feof(f) ? -EIO : -errno;
3300                 fclose(f);
3301                 return k;
3302         }
3303
3304         fclose(f);
3305
3306         p = strrchr(line, ')');
3307         if (!p)
3308                 return -EIO;
3309
3310         p++;
3311
3312         if (sscanf(p, " "
3313                    "%*c "  /* state */
3314                    "%*d "  /* ppid */
3315                    "%*d "  /* pgrp */
3316                    "%*d "  /* session */
3317                    "%lu ", /* ttynr */
3318                    &ttynr) != 1)
3319                 return -EIO;
3320
3321         *d = (dev_t) ttynr;
3322         return 0;
3323 }
3324
3325 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3326         int k;
3327         char fn[PATH_MAX], *s, *b, *p;
3328         dev_t devnr;
3329
3330         assert(r);
3331
3332         k = get_ctty_devnr(pid, &devnr);
3333         if (k < 0)
3334                 return k;
3335
3336         snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3337         char_array_0(fn);
3338
3339         if ((k = readlink_malloc(fn, &s)) < 0) {
3340
3341                 if (k != -ENOENT)
3342                         return k;
3343
3344                 /* This is an ugly hack */
3345                 if (major(devnr) == 136) {
3346                         if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3347                                 return -ENOMEM;
3348
3349                         *r = b;
3350                         if (_devnr)
3351                                 *_devnr = devnr;
3352
3353                         return 0;
3354                 }
3355
3356                 /* Probably something like the ptys which have no
3357                  * symlink in /dev/char. Let's return something
3358                  * vaguely useful. */
3359
3360                 if (!(b = strdup(fn + 5)))
3361                         return -ENOMEM;
3362
3363                 *r = b;
3364                 if (_devnr)
3365                         *_devnr = devnr;
3366
3367                 return 0;
3368         }
3369
3370         if (startswith(s, "/dev/"))
3371                 p = s + 5;
3372         else if (startswith(s, "../"))
3373                 p = s + 3;
3374         else
3375                 p = s;
3376
3377         b = strdup(p);
3378         free(s);
3379
3380         if (!b)
3381                 return -ENOMEM;
3382
3383         *r = b;
3384         if (_devnr)
3385                 *_devnr = devnr;
3386
3387         return 0;
3388 }
3389
3390 static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) {
3391         DIR *d;
3392         int ret = 0;
3393
3394         assert(fd >= 0);
3395
3396         /* This returns the first error we run into, but nevertheless
3397          * tries to go on */
3398
3399         if (!(d = fdopendir(fd))) {
3400                 close_nointr_nofail(fd);
3401
3402                 return errno == ENOENT ? 0 : -errno;
3403         }
3404
3405         for (;;) {
3406                 struct dirent buf, *de;
3407                 bool is_dir, keep_around = false;
3408                 int r;
3409
3410                 if ((r = readdir_r(d, &buf, &de)) != 0) {
3411                         if (ret == 0)
3412                                 ret = -r;
3413                         break;
3414                 }
3415
3416                 if (!de)
3417                         break;
3418
3419                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3420                         continue;
3421
3422                 if (de->d_type == DT_UNKNOWN) {
3423                         struct stat st;
3424
3425                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3426                                 if (ret == 0 && errno != ENOENT)
3427                                         ret = -errno;
3428                                 continue;
3429                         }
3430
3431                         if (honour_sticky)
3432                                 keep_around = st.st_uid == 0 && (st.st_mode & S_ISVTX);
3433
3434                         is_dir = S_ISDIR(st.st_mode);
3435
3436                 } else {
3437                         if (honour_sticky) {
3438                                 struct stat st;
3439
3440                                 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3441                                         if (ret == 0 && errno != ENOENT)
3442                                                 ret = -errno;
3443                                         continue;
3444                                 }
3445
3446                                 keep_around = st.st_uid == 0 && (st.st_mode & S_ISVTX);
3447                         }
3448
3449                         is_dir = de->d_type == DT_DIR;
3450                 }
3451
3452                 if (is_dir) {
3453                         int subdir_fd;
3454
3455                         if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3456                                 if (ret == 0 && errno != ENOENT)
3457                                         ret = -errno;
3458                                 continue;
3459                         }
3460
3461                         if ((r = rm_rf_children(subdir_fd, only_dirs, honour_sticky)) < 0) {
3462                                 if (ret == 0)
3463                                         ret = r;
3464                         }
3465
3466                         if (!keep_around)
3467                                 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3468                                         if (ret == 0 && errno != ENOENT)
3469                                                 ret = -errno;
3470                                 }
3471
3472                 } else if (!only_dirs && !keep_around) {
3473
3474                         if (unlinkat(fd, de->d_name, 0) < 0) {
3475                                 if (ret == 0 && errno != ENOENT)
3476                                         ret = -errno;
3477                         }
3478                 }
3479         }
3480
3481         closedir(d);
3482
3483         return ret;
3484 }
3485
3486 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3487         int fd;
3488         int r;
3489
3490         assert(path);
3491
3492         if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3493
3494                 if (errno != ENOTDIR)
3495                         return -errno;
3496
3497                 if (delete_root && !only_dirs)
3498                         if (unlink(path) < 0)
3499                                 return -errno;
3500
3501                 return 0;
3502         }
3503
3504         r = rm_rf_children(fd, only_dirs, honour_sticky);
3505
3506         if (delete_root) {
3507
3508                 if (honour_sticky && file_is_sticky(path) > 0)
3509                         return r;
3510
3511                 if (rmdir(path) < 0 && errno != ENOENT) {
3512                         if (r == 0)
3513                                 r = -errno;
3514                 }
3515         }
3516
3517         return r;
3518 }
3519
3520 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3521         assert(path);
3522
3523         /* Under the assumption that we are running privileged we
3524          * first change the access mode and only then hand out
3525          * ownership to avoid a window where access is too open. */
3526
3527         if (chmod(path, mode) < 0)
3528                 return -errno;
3529
3530         if (chown(path, uid, gid) < 0)
3531                 return -errno;
3532
3533         return 0;
3534 }
3535
3536 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3537         assert(fd >= 0);
3538
3539         /* Under the assumption that we are running privileged we
3540          * first change the access mode and only then hand out
3541          * ownership to avoid a window where access is too open. */
3542
3543         if (fchmod(fd, mode) < 0)
3544                 return -errno;
3545
3546         if (fchown(fd, uid, gid) < 0)
3547                 return -errno;
3548
3549         return 0;
3550 }
3551
3552 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3553         cpu_set_t *r;
3554         unsigned n = 1024;
3555
3556         /* Allocates the cpuset in the right size */
3557
3558         for (;;) {
3559                 if (!(r = CPU_ALLOC(n)))
3560                         return NULL;
3561
3562                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3563                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3564
3565                         if (ncpus)
3566                                 *ncpus = n;
3567
3568                         return r;
3569                 }
3570
3571                 CPU_FREE(r);
3572
3573                 if (errno != EINVAL)
3574                         return NULL;
3575
3576                 n *= 2;
3577         }
3578 }
3579
3580 void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3581         char *s = NULL, *spaces = NULL, *e;
3582         int fd = -1, c;
3583         size_t emax, sl, left;
3584         struct iovec iovec[5];
3585         int n = 0;
3586
3587         assert(format);
3588
3589         /* This independent of logging, as status messages are
3590          * optional and go exclusively to the console. */
3591
3592         if (vasprintf(&s, format, ap) < 0)
3593                 goto finish;
3594
3595         fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3596         if (fd < 0)
3597                 goto finish;
3598
3599         if (ellipse) {
3600                 c = fd_columns(fd);
3601                 if (c <= 0)
3602                         c = 80;
3603
3604                 if (status) {
3605                         sl = 2 + 6 + 1; /* " [" status "]" */
3606                         emax = (size_t) c > sl ? c - sl - 1 : 0;
3607                 } else
3608                         emax = c - 1;
3609
3610                 e = ellipsize(s, emax, 75);
3611                 if (e) {
3612                         free(s);
3613                         s = e;
3614                 }
3615         }
3616
3617         zero(iovec);
3618         IOVEC_SET_STRING(iovec[n++], s);
3619
3620         if (ellipse) {
3621                 sl = strlen(s);
3622                 left = emax > sl ? emax - sl : 0;
3623                 if (left > 0) {
3624                         spaces = malloc(left);
3625                         if (spaces) {
3626                                 memset(spaces, ' ', left);
3627                                 iovec[n].iov_base = spaces;
3628                                 iovec[n].iov_len = left;
3629                                 n++;
3630                         }
3631                 }
3632         }
3633
3634         if (status) {
3635                 IOVEC_SET_STRING(iovec[n++], " [");
3636                 IOVEC_SET_STRING(iovec[n++], status);
3637                 IOVEC_SET_STRING(iovec[n++], "]\n");
3638         } else
3639                 IOVEC_SET_STRING(iovec[n++], "\n");
3640
3641         writev(fd, iovec, n);
3642
3643 finish:
3644         free(s);
3645         free(spaces);
3646
3647         if (fd >= 0)
3648                 close_nointr_nofail(fd);
3649 }
3650
3651 void status_printf(const char *status, bool ellipse, const char *format, ...) {
3652         va_list ap;
3653
3654         assert(format);
3655
3656         va_start(ap, format);
3657         status_vprintf(status, ellipse, format, ap);
3658         va_end(ap);
3659 }
3660
3661 void status_welcome(void) {
3662         char *pretty_name = NULL, *ansi_color = NULL;
3663         const char *const_pretty = NULL, *const_color = NULL;
3664         int r;
3665
3666         if ((r = parse_env_file("/etc/os-release", NEWLINE,
3667                                 "PRETTY_NAME", &pretty_name,
3668                                 "ANSI_COLOR", &ansi_color,
3669                                 NULL)) < 0) {
3670
3671                 if (r != -ENOENT)
3672                         log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3673         }
3674
3675 #if defined(TARGET_FEDORA)
3676         if (!pretty_name) {
3677                 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3678
3679                         if (r != -ENOENT)
3680                                 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3681                 }
3682         }
3683
3684         if (!ansi_color && pretty_name) {
3685
3686                 /* This tries to mimic the color magic the old Red Hat sysinit
3687                  * script did. */
3688
3689                 if (startswith(pretty_name, "Red Hat"))
3690                         const_color = "0;31"; /* Red for RHEL */
3691                 else if (startswith(pretty_name, "Fedora"))
3692                         const_color = "0;34"; /* Blue for Fedora */
3693         }
3694
3695 #elif defined(TARGET_SUSE)
3696
3697         if (!pretty_name) {
3698                 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3699
3700                         if (r != -ENOENT)
3701                                 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3702                 }
3703         }
3704
3705         if (!ansi_color)
3706                 const_color = "0;32"; /* Green for openSUSE */
3707
3708 #elif defined(TARGET_GENTOO)
3709
3710         if (!pretty_name) {
3711                 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3712
3713                         if (r != -ENOENT)
3714                                 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3715                 }
3716         }
3717
3718         if (!ansi_color)
3719                 const_color = "1;34"; /* Light Blue for Gentoo */
3720
3721 #elif defined(TARGET_ALTLINUX)
3722
3723         if (!pretty_name) {
3724                 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3725
3726                         if (r != -ENOENT)
3727                                 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3728                 }
3729         }
3730
3731         if (!ansi_color)
3732                 const_color = "0;36"; /* Cyan for ALTLinux */
3733
3734
3735 #elif defined(TARGET_DEBIAN)
3736
3737         if (!pretty_name) {
3738                 char *version;
3739
3740                 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3741
3742                         if (r != -ENOENT)
3743                                 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3744                 } else {
3745                         pretty_name = strappend("Debian ", version);
3746                         free(version);
3747
3748                         if (!pretty_name)
3749                                 log_warning("Failed to allocate Debian version string.");
3750                 }
3751         }
3752
3753         if (!ansi_color)
3754                 const_color = "1;31"; /* Light Red for Debian */
3755
3756 #elif defined(TARGET_UBUNTU)
3757
3758         if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3759                                 "DISTRIB_DESCRIPTION", &pretty_name,
3760                                 NULL)) < 0) {
3761
3762                 if (r != -ENOENT)
3763                         log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3764         }
3765
3766         if (!ansi_color)
3767                 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3768
3769 #elif defined(TARGET_MANDRIVA)
3770
3771         if (!pretty_name) {
3772                 char *s, *p;
3773
3774                 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3775                         if (r != -ENOENT)
3776                                 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3777                 } else {
3778                         p = strstr(s, " release ");
3779                         if (p) {
3780                                 *p = '\0';
3781                                 p += 9;
3782                                 p[strcspn(p, " ")] = '\0';
3783
3784                                 /* This corresponds to standard rc.sysinit */
3785                                 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3786                                         const_color = "1;36";
3787                                 else
3788                                         log_warning("Failed to allocate Mandriva version string.");
3789                         } else
3790                                 log_warning("Failed to parse /etc/mandriva-release");
3791                         free(s);
3792                 }
3793         }
3794 #elif defined(TARGET_MEEGO)
3795
3796         if (!pretty_name) {
3797                 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3798
3799                         if (r != -ENOENT)
3800                                 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3801                 }
3802         }
3803
3804        if (!ansi_color)
3805                const_color = "1;35"; /* Bright Magenta for MeeGo */
3806 #endif
3807
3808         if (!pretty_name && !const_pretty)
3809                 const_pretty = "Linux";
3810
3811         if (!ansi_color && !const_color)
3812                 const_color = "1";
3813
3814         status_printf(NULL,
3815                       false,
3816                       "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3817                       const_color ? const_color : ansi_color,
3818                       const_pretty ? const_pretty : pretty_name);
3819
3820         free(ansi_color);
3821         free(pretty_name);
3822 }
3823
3824 char *replace_env(const char *format, char **env) {
3825         enum {
3826                 WORD,
3827                 CURLY,
3828                 VARIABLE
3829         } state = WORD;
3830
3831         const char *e, *word = format;
3832         char *r = NULL, *k;
3833
3834         assert(format);
3835
3836         for (e = format; *e; e ++) {
3837
3838                 switch (state) {
3839
3840                 case WORD:
3841                         if (*e == '$')
3842                                 state = CURLY;
3843                         break;
3844
3845                 case CURLY:
3846                         if (*e == '{') {
3847                                 if (!(k = strnappend(r, word, e-word-1)))
3848                                         goto fail;
3849
3850                                 free(r);
3851                                 r = k;
3852
3853                                 word = e-1;
3854                                 state = VARIABLE;
3855
3856                         } else if (*e == '$') {
3857                                 if (!(k = strnappend(r, word, e-word)))
3858                                         goto fail;
3859
3860                                 free(r);
3861                                 r = k;
3862
3863                                 word = e+1;
3864                                 state = WORD;
3865                         } else
3866                                 state = WORD;
3867                         break;
3868
3869                 case VARIABLE:
3870                         if (*e == '}') {
3871                                 const char *t;
3872
3873                                 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3874                                         t = "";
3875
3876                                 if (!(k = strappend(r, t)))
3877                                         goto fail;
3878
3879                                 free(r);
3880                                 r = k;
3881
3882                                 word = e+1;
3883                                 state = WORD;
3884                         }
3885                         break;
3886                 }
3887         }
3888
3889         if (!(k = strnappend(r, word, e-word)))
3890                 goto fail;
3891
3892         free(r);
3893         return k;
3894
3895 fail:
3896         free(r);
3897         return NULL;
3898 }
3899
3900 char **replace_env_argv(char **argv, char **env) {
3901         char **r, **i;
3902         unsigned k = 0, l = 0;
3903
3904         l = strv_length(argv);
3905
3906         if (!(r = new(char*, l+1)))
3907                 return NULL;
3908
3909         STRV_FOREACH(i, argv) {
3910
3911                 /* If $FOO appears as single word, replace it by the split up variable */
3912                 if ((*i)[0] == '$' && (*i)[1] != '{') {
3913                         char *e;
3914                         char **w, **m;
3915                         unsigned q;
3916
3917                         if ((e = strv_env_get(env, *i+1))) {
3918
3919                                 if (!(m = strv_split_quoted(e))) {
3920                                         r[k] = NULL;
3921                                         strv_free(r);
3922                                         return NULL;
3923                                 }
3924                         } else
3925                                 m = NULL;
3926
3927                         q = strv_length(m);
3928                         l = l + q - 1;
3929
3930                         if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3931                                 r[k] = NULL;
3932                                 strv_free(r);
3933                                 strv_free(m);
3934                                 return NULL;
3935                         }
3936
3937                         r = w;
3938                         if (m) {
3939                                 memcpy(r + k, m, q * sizeof(char*));
3940                                 free(m);
3941                         }
3942
3943                         k += q;
3944                         continue;
3945                 }
3946
3947                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3948                 if (!(r[k++] = replace_env(*i, env))) {
3949                         strv_free(r);
3950                         return NULL;
3951                 }
3952         }
3953
3954         r[k] = NULL;
3955         return r;
3956 }
3957
3958 int fd_columns(int fd) {
3959         struct winsize ws;
3960         zero(ws);
3961
3962         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3963                 return -errno;
3964
3965         if (ws.ws_col <= 0)
3966                 return -EIO;
3967
3968         return ws.ws_col;
3969 }
3970
3971 unsigned columns(void) {
3972         static __thread int parsed_columns = 0;
3973         const char *e;
3974
3975         if (_likely_(parsed_columns > 0))
3976                 return parsed_columns;
3977
3978         e = getenv("COLUMNS");
3979         if (e)
3980                 parsed_columns = atoi(e);
3981
3982         if (parsed_columns <= 0)
3983                 parsed_columns = fd_columns(STDOUT_FILENO);
3984
3985         if (parsed_columns <= 0)
3986                 parsed_columns = 80;
3987
3988         return parsed_columns;
3989 }
3990
3991 int running_in_chroot(void) {
3992         struct stat a, b;
3993
3994         zero(a);
3995         zero(b);
3996
3997         /* Only works as root */
3998
3999         if (stat("/proc/1/root", &a) < 0)
4000                 return -errno;
4001
4002         if (stat("/", &b) < 0)
4003                 return -errno;
4004
4005         return
4006                 a.st_dev != b.st_dev ||
4007                 a.st_ino != b.st_ino;
4008 }
4009
4010 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
4011         size_t x;
4012         char *r;
4013
4014         assert(s);
4015         assert(percent <= 100);
4016         assert(new_length >= 3);
4017
4018         if (old_length <= 3 || old_length <= new_length)
4019                 return strndup(s, old_length);
4020
4021         r = new0(char, new_length+1);
4022         if (!r)
4023                 return r;
4024
4025         x = (new_length * percent) / 100;
4026
4027         if (x > new_length - 3)
4028                 x = new_length - 3;
4029
4030         memcpy(r, s, x);
4031         r[x] = '.';
4032         r[x+1] = '.';
4033         r[x+2] = '.';
4034         memcpy(r + x + 3,
4035                s + old_length - (new_length - x - 3),
4036                new_length - x - 3);
4037
4038         return r;
4039 }
4040
4041 char *ellipsize(const char *s, size_t length, unsigned percent) {
4042         return ellipsize_mem(s, strlen(s), length, percent);
4043 }
4044
4045 int touch(const char *path) {
4046         int fd;
4047
4048         assert(path);
4049
4050         if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
4051                 return -errno;
4052
4053         close_nointr_nofail(fd);
4054         return 0;
4055 }
4056
4057 char *unquote(const char *s, const char* quotes) {
4058         size_t l;
4059         assert(s);
4060
4061         if ((l = strlen(s)) < 2)
4062                 return strdup(s);
4063
4064         if (strchr(quotes, s[0]) && s[l-1] == s[0])
4065                 return strndup(s+1, l-2);
4066
4067         return strdup(s);
4068 }
4069
4070 char *normalize_env_assignment(const char *s) {
4071         char *name, *value, *p, *r;
4072
4073         p = strchr(s, '=');
4074
4075         if (!p) {
4076                 if (!(r = strdup(s)))
4077                         return NULL;
4078
4079                 return strstrip(r);
4080         }
4081
4082         if (!(name = strndup(s, p - s)))
4083                 return NULL;
4084
4085         if (!(p = strdup(p+1))) {
4086                 free(name);
4087                 return NULL;
4088         }
4089
4090         value = unquote(strstrip(p), QUOTES);
4091         free(p);
4092
4093         if (!value) {
4094                 free(name);
4095                 return NULL;
4096         }
4097
4098         if (asprintf(&r, "%s=%s", name, value) < 0)
4099                 r = NULL;
4100
4101         free(value);
4102         free(name);
4103
4104         return r;
4105 }
4106
4107 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4108         siginfo_t dummy;
4109
4110         assert(pid >= 1);
4111
4112         if (!status)
4113                 status = &dummy;
4114
4115         for (;;) {
4116                 zero(*status);
4117
4118                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4119
4120                         if (errno == EINTR)
4121                                 continue;
4122
4123                         return -errno;
4124                 }
4125
4126                 return 0;
4127         }
4128 }
4129
4130 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4131         int r;
4132         siginfo_t status;
4133
4134         assert(name);
4135         assert(pid > 1);
4136
4137         if ((r = wait_for_terminate(pid, &status)) < 0) {
4138                 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4139                 return r;
4140         }
4141
4142         if (status.si_code == CLD_EXITED) {
4143                 if (status.si_status != 0) {
4144                         log_warning("%s failed with error code %i.", name, status.si_status);
4145                         return status.si_status;
4146                 }
4147
4148                 log_debug("%s succeeded.", name);
4149                 return 0;
4150
4151         } else if (status.si_code == CLD_KILLED ||
4152                    status.si_code == CLD_DUMPED) {
4153
4154                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4155                 return -EPROTO;
4156         }
4157
4158         log_warning("%s failed due to unknown reason.", name);
4159         return -EPROTO;
4160
4161 }
4162
4163 void freeze(void) {
4164
4165         /* Make sure nobody waits for us on a socket anymore */
4166         close_all_fds(NULL, 0);
4167
4168         sync();
4169
4170         for (;;)
4171                 pause();
4172 }
4173
4174 bool null_or_empty(struct stat *st) {
4175         assert(st);
4176
4177         if (S_ISREG(st->st_mode) && st->st_size <= 0)
4178                 return true;
4179
4180         if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4181                 return true;
4182
4183         return false;
4184 }
4185
4186 int null_or_empty_path(const char *fn) {
4187         struct stat st;
4188
4189         assert(fn);
4190
4191         if (stat(fn, &st) < 0)
4192                 return -errno;
4193
4194         return null_or_empty(&st);
4195 }
4196
4197 DIR *xopendirat(int fd, const char *name, int flags) {
4198         int nfd;
4199         DIR *d;
4200
4201         if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4202                 return NULL;
4203
4204         if (!(d = fdopendir(nfd))) {
4205                 close_nointr_nofail(nfd);
4206                 return NULL;
4207         }
4208
4209         return d;
4210 }
4211
4212 int signal_from_string_try_harder(const char *s) {
4213         int signo;
4214         assert(s);
4215
4216         if ((signo = signal_from_string(s)) <= 0)
4217                 if (startswith(s, "SIG"))
4218                         return signal_from_string(s+3);
4219
4220         return signo;
4221 }
4222
4223 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4224
4225         assert(f);
4226         assert(name);
4227         assert(t);
4228
4229         if (!dual_timestamp_is_set(t))
4230                 return;
4231
4232         fprintf(f, "%s=%llu %llu\n",
4233                 name,
4234                 (unsigned long long) t->realtime,
4235                 (unsigned long long) t->monotonic);
4236 }
4237
4238 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4239         unsigned long long a, b;
4240
4241         assert(value);
4242         assert(t);
4243
4244         if (sscanf(value, "%lli %llu", &a, &b) != 2)
4245                 log_debug("Failed to parse finish timestamp value %s", value);
4246         else {
4247                 t->realtime = a;
4248                 t->monotonic = b;
4249         }
4250 }
4251
4252 char *fstab_node_to_udev_node(const char *p) {
4253         char *dn, *t, *u;
4254         int r;
4255
4256         /* FIXME: to follow udev's logic 100% we need to leave valid
4257          * UTF8 chars unescaped */
4258
4259         if (startswith(p, "LABEL=")) {
4260
4261                 if (!(u = unquote(p+6, "\"\'")))
4262                         return NULL;
4263
4264                 t = xescape(u, "/ ");
4265                 free(u);
4266
4267                 if (!t)
4268                         return NULL;
4269
4270                 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4271                 free(t);
4272
4273                 if (r < 0)
4274                         return NULL;
4275
4276                 return dn;
4277         }
4278
4279         if (startswith(p, "UUID=")) {
4280
4281                 if (!(u = unquote(p+5, "\"\'")))
4282                         return NULL;
4283
4284                 t = xescape(u, "/ ");
4285                 free(u);
4286
4287                 if (!t)
4288                         return NULL;
4289
4290                 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4291                 free(t);
4292
4293                 if (r < 0)
4294                         return NULL;
4295
4296                 return dn;
4297         }
4298
4299         return strdup(p);
4300 }
4301
4302 void filter_environ(const char *prefix) {
4303         int i, j;
4304         assert(prefix);
4305
4306         if (!environ)
4307                 return;
4308
4309         for (i = 0, j = 0; environ[i]; i++) {
4310
4311                 if (startswith(environ[i], prefix))
4312                         continue;
4313
4314                 environ[j++] = environ[i];
4315         }
4316
4317         environ[j] = NULL;
4318 }
4319
4320 bool tty_is_vc(const char *tty) {
4321         assert(tty);
4322
4323         if (startswith(tty, "/dev/"))
4324                 tty += 5;
4325
4326         return vtnr_from_tty(tty) >= 0;
4327 }
4328
4329 int vtnr_from_tty(const char *tty) {
4330         int i, r;
4331
4332         assert(tty);
4333
4334         if (startswith(tty, "/dev/"))
4335                 tty += 5;
4336
4337         if (!startswith(tty, "tty") )
4338                 return -EINVAL;
4339
4340         if (tty[3] < '0' || tty[3] > '9')
4341                 return -EINVAL;
4342
4343         r = safe_atoi(tty+3, &i);
4344         if (r < 0)
4345                 return r;
4346
4347         if (i < 0 || i > 63)
4348                 return -EINVAL;
4349
4350         return i;
4351 }
4352
4353 const char *default_term_for_tty(const char *tty) {
4354         char *active = NULL;
4355         const char *term;
4356
4357         assert(tty);
4358
4359         if (startswith(tty, "/dev/"))
4360                 tty += 5;
4361
4362         /* Resolve where /dev/console is pointing when determining
4363          * TERM */
4364         if (streq(tty, "console"))
4365                 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4366                         /* If multiple log outputs are configured the
4367                          * last one is what /dev/console points to */
4368                         if ((tty = strrchr(active, ' ')))
4369                                 tty++;
4370                         else
4371                                 tty = active;
4372                 }
4373
4374         term = tty_is_vc(tty) ? "TERM=linux" : "TERM=vt100";
4375         free(active);
4376
4377         return term;
4378 }
4379
4380 bool dirent_is_file(const struct dirent *de) {
4381         assert(de);
4382
4383         if (ignore_file(de->d_name))
4384                 return false;
4385
4386         if (de->d_type != DT_REG &&
4387             de->d_type != DT_LNK &&
4388             de->d_type != DT_UNKNOWN)
4389                 return false;
4390
4391         return true;
4392 }
4393
4394 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4395         assert(de);
4396
4397         if (!dirent_is_file(de))
4398                 return false;
4399
4400         return endswith(de->d_name, suffix);
4401 }
4402
4403 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4404         DIR *_d = NULL;
4405         struct dirent *de;
4406         Hashmap *pids = NULL;
4407
4408         assert(directory);
4409
4410         /* Executes all binaries in a directory in parallel and waits
4411          * until all they all finished. */
4412
4413         if (!d) {
4414                 if (!(_d = opendir(directory))) {
4415
4416                         if (errno == ENOENT)
4417                                 return;
4418
4419                         log_error("Failed to enumerate directory %s: %m", directory);
4420                         return;
4421                 }
4422
4423                 d = _d;
4424         }
4425
4426         if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4427                 log_error("Failed to allocate set.");
4428                 goto finish;
4429         }
4430
4431         while ((de = readdir(d))) {
4432                 char *path;
4433                 pid_t pid;
4434                 int k;
4435
4436                 if (!dirent_is_file(de))
4437                         continue;
4438
4439                 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4440                         log_error("Out of memory");
4441                         continue;
4442                 }
4443
4444                 if ((pid = fork()) < 0) {
4445                         log_error("Failed to fork: %m");
4446                         free(path);
4447                         continue;
4448                 }
4449
4450                 if (pid == 0) {
4451                         char *_argv[2];
4452                         /* Child */
4453
4454                         if (!argv) {
4455                                 _argv[0] = path;
4456                                 _argv[1] = NULL;
4457                                 argv = _argv;
4458                         } else
4459                                 if (!argv[0])
4460                                         argv[0] = path;
4461
4462                         execv(path, argv);
4463
4464                         log_error("Failed to execute %s: %m", path);
4465                         _exit(EXIT_FAILURE);
4466                 }
4467
4468                 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4469
4470                 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4471                         log_error("Failed to add PID to set: %s", strerror(-k));
4472                         free(path);
4473                 }
4474         }
4475
4476         while (!hashmap_isempty(pids)) {
4477                 siginfo_t si;
4478                 char *path;
4479
4480                 zero(si);
4481                 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4482
4483                         if (errno == EINTR)
4484                                 continue;
4485
4486                         log_error("waitid() failed: %m");
4487                         goto finish;
4488                 }
4489
4490                 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4491                         if (!is_clean_exit(si.si_code, si.si_status)) {
4492                                 if (si.si_code == CLD_EXITED)
4493                                         log_error("%s exited with exit status %i.", path, si.si_status);
4494                                 else
4495                                         log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4496                         } else
4497                                 log_debug("%s exited successfully.", path);
4498
4499                         free(path);
4500                 }
4501         }
4502
4503 finish:
4504         if (_d)
4505                 closedir(_d);
4506
4507         if (pids)
4508                 hashmap_free_free(pids);
4509 }
4510
4511 int kill_and_sigcont(pid_t pid, int sig) {
4512         int r;
4513
4514         r = kill(pid, sig) < 0 ? -errno : 0;
4515
4516         if (r >= 0)
4517                 kill(pid, SIGCONT);
4518
4519         return r;
4520 }
4521
4522 bool nulstr_contains(const char*nulstr, const char *needle) {
4523         const char *i;
4524
4525         if (!nulstr)
4526                 return false;
4527
4528         NULSTR_FOREACH(i, nulstr)
4529                 if (streq(i, needle))
4530                         return true;
4531
4532         return false;
4533 }
4534
4535 bool plymouth_running(void) {
4536         return access("/run/plymouth/pid", F_OK) >= 0;
4537 }
4538
4539 void parse_syslog_priority(char **p, int *priority) {
4540         int a = 0, b = 0, c = 0;
4541         int k;
4542
4543         assert(p);
4544         assert(*p);
4545         assert(priority);
4546
4547         if ((*p)[0] != '<')
4548                 return;
4549
4550         if (!strchr(*p, '>'))
4551                 return;
4552
4553         if ((*p)[2] == '>') {
4554                 c = undecchar((*p)[1]);
4555                 k = 3;
4556         } else if ((*p)[3] == '>') {
4557                 b = undecchar((*p)[1]);
4558                 c = undecchar((*p)[2]);
4559                 k = 4;
4560         } else if ((*p)[4] == '>') {
4561                 a = undecchar((*p)[1]);
4562                 b = undecchar((*p)[2]);
4563                 c = undecchar((*p)[3]);
4564                 k = 5;
4565         } else
4566                 return;
4567
4568         if (a < 0 || b < 0 || c < 0)
4569                 return;
4570
4571         *priority = a*100+b*10+c;
4572         *p += k;
4573 }
4574
4575 void skip_syslog_pid(char **buf) {
4576         char *p;
4577
4578         assert(buf);
4579         assert(*buf);
4580
4581         p = *buf;
4582
4583         if (*p != '[')
4584                 return;
4585
4586         p++;
4587         p += strspn(p, "0123456789");
4588
4589         if (*p != ']')
4590                 return;
4591
4592         p++;
4593
4594         *buf = p;
4595 }
4596
4597 void skip_syslog_date(char **buf) {
4598         enum {
4599                 LETTER,
4600                 SPACE,
4601                 NUMBER,
4602                 SPACE_OR_NUMBER,
4603                 COLON
4604         } sequence[] = {
4605                 LETTER, LETTER, LETTER,
4606                 SPACE,
4607                 SPACE_OR_NUMBER, NUMBER,
4608                 SPACE,
4609                 SPACE_OR_NUMBER, NUMBER,
4610                 COLON,
4611                 SPACE_OR_NUMBER, NUMBER,
4612                 COLON,
4613                 SPACE_OR_NUMBER, NUMBER,
4614                 SPACE
4615         };
4616
4617         char *p;
4618         unsigned i;
4619
4620         assert(buf);
4621         assert(*buf);
4622
4623         p = *buf;
4624
4625         for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
4626
4627                 if (!*p)
4628                         return;
4629
4630                 switch (sequence[i]) {
4631
4632                 case SPACE:
4633                         if (*p != ' ')
4634                                 return;
4635                         break;
4636
4637                 case SPACE_OR_NUMBER:
4638                         if (*p == ' ')
4639                                 break;
4640
4641                         /* fall through */
4642
4643                 case NUMBER:
4644                         if (*p < '0' || *p > '9')
4645                                 return;
4646
4647                         break;
4648
4649                 case LETTER:
4650                         if (!(*p >= 'A' && *p <= 'Z') &&
4651                             !(*p >= 'a' && *p <= 'z'))
4652                                 return;
4653
4654                         break;
4655
4656                 case COLON:
4657                         if (*p != ':')
4658                                 return;
4659                         break;
4660
4661                 }
4662         }
4663
4664         *buf = p;
4665 }
4666
4667 int have_effective_cap(int value) {
4668         cap_t cap;
4669         cap_flag_value_t fv;
4670         int r;
4671
4672         if (!(cap = cap_get_proc()))
4673                 return -errno;
4674
4675         if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4676                 r = -errno;
4677         else
4678                 r = fv == CAP_SET;
4679
4680         cap_free(cap);
4681         return r;
4682 }
4683
4684 char* strshorten(char *s, size_t l) {
4685         assert(s);
4686
4687         if (l < strlen(s))
4688                 s[l] = 0;
4689
4690         return s;
4691 }
4692
4693 static bool hostname_valid_char(char c) {
4694         return
4695                 (c >= 'a' && c <= 'z') ||
4696                 (c >= 'A' && c <= 'Z') ||
4697                 (c >= '0' && c <= '9') ||
4698                 c == '-' ||
4699                 c == '_' ||
4700                 c == '.';
4701 }
4702
4703 bool hostname_is_valid(const char *s) {
4704         const char *p;
4705
4706         if (isempty(s))
4707                 return false;
4708
4709         for (p = s; *p; p++)
4710                 if (!hostname_valid_char(*p))
4711                         return false;
4712
4713         if (p-s > HOST_NAME_MAX)
4714                 return false;
4715
4716         return true;
4717 }
4718
4719 char* hostname_cleanup(char *s) {
4720         char *p, *d;
4721
4722         for (p = s, d = s; *p; p++)
4723                 if ((*p >= 'a' && *p <= 'z') ||
4724                     (*p >= 'A' && *p <= 'Z') ||
4725                     (*p >= '0' && *p <= '9') ||
4726                     *p == '-' ||
4727                     *p == '_' ||
4728                     *p == '.')
4729                         *(d++) = *p;
4730
4731         *d = 0;
4732
4733         strshorten(s, HOST_NAME_MAX);
4734         return s;
4735 }
4736
4737 int pipe_eof(int fd) {
4738         struct pollfd pollfd;
4739         int r;
4740
4741         zero(pollfd);
4742         pollfd.fd = fd;
4743         pollfd.events = POLLIN|POLLHUP;
4744
4745         r = poll(&pollfd, 1, 0);
4746         if (r < 0)
4747                 return -errno;
4748
4749         if (r == 0)
4750                 return 0;
4751
4752         return pollfd.revents & POLLHUP;
4753 }
4754
4755 int fd_wait_for_event(int fd, int event) {
4756         struct pollfd pollfd;
4757         int r;
4758
4759         zero(pollfd);
4760         pollfd.fd = fd;
4761         pollfd.events = event;
4762
4763         r = poll(&pollfd, 1, -1);
4764         if (r < 0)
4765                 return -errno;
4766
4767         if (r == 0)
4768                 return 0;
4769
4770         return pollfd.revents;
4771 }
4772
4773 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4774         FILE *f;
4775         char *t;
4776         const char *fn;
4777         size_t k;
4778         int fd;
4779
4780         assert(path);
4781         assert(_f);
4782         assert(_temp_path);
4783
4784         t = new(char, strlen(path) + 1 + 6 + 1);
4785         if (!t)
4786                 return -ENOMEM;
4787
4788         fn = file_name_from_path(path);
4789         k = fn-path;
4790         memcpy(t, path, k);
4791         t[k] = '.';
4792         stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4793
4794         fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4795         if (fd < 0) {
4796                 free(t);
4797                 return -errno;
4798         }
4799
4800         f = fdopen(fd, "we");
4801         if (!f) {
4802                 unlink(t);
4803                 free(t);
4804                 return -errno;
4805         }
4806
4807         *_f = f;
4808         *_temp_path = t;
4809
4810         return 0;
4811 }
4812
4813 int terminal_vhangup_fd(int fd) {
4814         assert(fd >= 0);
4815
4816         if (ioctl(fd, TIOCVHANGUP) < 0)
4817                 return -errno;
4818
4819         return 0;
4820 }
4821
4822 int terminal_vhangup(const char *name) {
4823         int fd, r;
4824
4825         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4826         if (fd < 0)
4827                 return fd;
4828
4829         r = terminal_vhangup_fd(fd);
4830         close_nointr_nofail(fd);
4831
4832         return r;
4833 }
4834
4835 int vt_disallocate(const char *name) {
4836         int fd, r;
4837         unsigned u;
4838
4839         /* Deallocate the VT if possible. If not possible
4840          * (i.e. because it is the active one), at least clear it
4841          * entirely (including the scrollback buffer) */
4842
4843         if (!startswith(name, "/dev/"))
4844                 return -EINVAL;
4845
4846         if (!tty_is_vc(name)) {
4847                 /* So this is not a VT. I guess we cannot deallocate
4848                  * it then. But let's at least clear the screen */
4849
4850                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4851                 if (fd < 0)
4852                         return fd;
4853
4854                 loop_write(fd,
4855                            "\033[r"    /* clear scrolling region */
4856                            "\033[H"    /* move home */
4857                            "\033[2J",  /* clear screen */
4858                            10, false);
4859                 close_nointr_nofail(fd);
4860
4861                 return 0;
4862         }
4863
4864         if (!startswith(name, "/dev/tty"))
4865                 return -EINVAL;
4866
4867         r = safe_atou(name+8, &u);
4868         if (r < 0)
4869                 return r;
4870
4871         if (u <= 0)
4872                 return -EINVAL;
4873
4874         /* Try to deallocate */
4875         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4876         if (fd < 0)
4877                 return fd;
4878
4879         r = ioctl(fd, VT_DISALLOCATE, u);
4880         close_nointr_nofail(fd);
4881
4882         if (r >= 0)
4883                 return 0;
4884
4885         if (errno != EBUSY)
4886                 return -errno;
4887
4888         /* Couldn't deallocate, so let's clear it fully with
4889          * scrollback */
4890         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4891         if (fd < 0)
4892                 return fd;
4893
4894         loop_write(fd,
4895                    "\033[r"   /* clear scrolling region */
4896                    "\033[H"   /* move home */
4897                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4898                    10, false);
4899         close_nointr_nofail(fd);
4900
4901         return 0;
4902 }
4903
4904 static int files_add(Hashmap *h, const char *path, const char *suffix) {
4905         DIR *dir;
4906         struct dirent buffer, *de;
4907         int r = 0;
4908
4909         dir = opendir(path);
4910         if (!dir) {
4911                 if (errno == ENOENT)
4912                         return 0;
4913                 return -errno;
4914         }
4915
4916         for (;;) {
4917                 int k;
4918                 char *p, *f;
4919
4920                 k = readdir_r(dir, &buffer, &de);
4921                 if (k != 0) {
4922                         r = -k;
4923                         goto finish;
4924                 }
4925
4926                 if (!de)
4927                         break;
4928
4929                 if (!dirent_is_file_with_suffix(de, suffix))
4930                         continue;
4931
4932                 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
4933                         r = -ENOMEM;
4934                         goto finish;
4935                 }
4936
4937                 f = canonicalize_file_name(p);
4938                 if (!f) {
4939                         log_error("Failed to canonicalize file name '%s': %m", p);
4940                         free(p);
4941                         continue;
4942                 }
4943                 free(p);
4944
4945                 log_debug("found: %s\n", f);
4946                 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
4947                         free(f);
4948         }
4949
4950 finish:
4951         closedir(dir);
4952         return r;
4953 }
4954
4955 static int base_cmp(const void *a, const void *b) {
4956         const char *s1, *s2;
4957
4958         s1 = *(char * const *)a;
4959         s2 = *(char * const *)b;
4960         return strcmp(file_name_from_path(s1), file_name_from_path(s2));
4961 }
4962
4963 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
4964         Hashmap *fh = NULL;
4965         char **dirs = NULL;
4966         char **files = NULL;
4967         char **p;
4968         va_list ap;
4969         int r = 0;
4970
4971         va_start(ap, dir);
4972         dirs = strv_new_ap(dir, ap);
4973         va_end(ap);
4974         if (!dirs) {
4975                 r = -ENOMEM;
4976                 goto finish;
4977         }
4978         if (!strv_path_canonicalize(dirs)) {
4979                 r = -ENOMEM;
4980                 goto finish;
4981         }
4982         if (!strv_uniq(dirs)) {
4983                 r = -ENOMEM;
4984                 goto finish;
4985         }
4986
4987         fh = hashmap_new(string_hash_func, string_compare_func);
4988         if (!fh) {
4989                 r = -ENOMEM;
4990                 goto finish;
4991         }
4992
4993         STRV_FOREACH(p, dirs) {
4994                 if (files_add(fh, *p, suffix) < 0) {
4995                         log_error("Failed to search for files.");
4996                         r = -EINVAL;
4997                         goto finish;
4998                 }
4999         }
5000
5001         files = hashmap_get_strv(fh);
5002         if (files == NULL) {
5003                 log_error("Failed to compose list of files.");
5004                 r = -ENOMEM;
5005                 goto finish;
5006         }
5007
5008         qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
5009
5010 finish:
5011         strv_free(dirs);
5012         hashmap_free(fh);
5013         *strv = files;
5014         return r;
5015 }
5016
5017 int hwclock_is_localtime(void) {
5018         FILE *f;
5019         bool local = false;
5020
5021         /*
5022          * The third line of adjtime is "UTC" or "LOCAL" or nothing.
5023          *   # /etc/adjtime
5024          *   0.0 0 0
5025          *   0
5026          *   UTC
5027          */
5028         f = fopen("/etc/adjtime", "re");
5029         if (f) {
5030                 char line[LINE_MAX];
5031                 bool b;
5032
5033                 b = fgets(line, sizeof(line), f) &&
5034                         fgets(line, sizeof(line), f) &&
5035                         fgets(line, sizeof(line), f);
5036
5037                 fclose(f);
5038
5039                 if (!b)
5040                         return -EIO;
5041
5042
5043                 truncate_nl(line);
5044                 local = streq(line, "LOCAL");
5045
5046         } else if (errno != -ENOENT)
5047                 return -errno;
5048
5049         return local;
5050 }
5051
5052 int hwclock_apply_localtime_delta(int *min) {
5053         const struct timeval *tv_null = NULL;
5054         struct timespec ts;
5055         struct tm *tm;
5056         int minuteswest;
5057         struct timezone tz;
5058
5059         assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
5060         assert_se(tm = localtime(&ts.tv_sec));
5061         minuteswest = tm->tm_gmtoff / 60;
5062
5063         tz.tz_minuteswest = -minuteswest;
5064         tz.tz_dsttime = 0; /* DST_NONE*/
5065
5066         /*
5067          * If the hardware clock does not run in UTC, but in local time:
5068          * The very first time we set the kernel's timezone, it will warp
5069          * the clock so that it runs in UTC instead of local time.
5070          */
5071         if (settimeofday(tv_null, &tz) < 0)
5072                 return -errno;
5073         if (min)
5074                 *min = minuteswest;
5075         return 0;
5076 }
5077
5078 int hwclock_reset_localtime_delta(void) {
5079         const struct timeval *tv_null = NULL;
5080         struct timezone tz;
5081
5082         tz.tz_minuteswest = 0;
5083         tz.tz_dsttime = 0; /* DST_NONE*/
5084
5085         if (settimeofday(tv_null, &tz) < 0)
5086                 return -errno;
5087
5088         return 0;
5089 }
5090
5091 int hwclock_get_time(struct tm *tm) {
5092         int fd;
5093         int err = 0;
5094
5095         assert(tm);
5096
5097         fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
5098         if (fd < 0)
5099                 return -errno;
5100
5101         /* This leaves the timezone fields of struct tm
5102          * uninitialized! */
5103         if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5104                 err = -errno;
5105
5106         /* We don't now daylight saving, so we reset this in order not
5107          * to confused mktime(). */
5108         tm->tm_isdst = -1;
5109
5110         close_nointr_nofail(fd);
5111
5112         return err;
5113 }
5114
5115 int hwclock_set_time(const struct tm *tm) {
5116         int fd;
5117         int err = 0;
5118
5119         assert(tm);
5120
5121         fd = open("/dev/rtc0", O_RDONLY|O_CLOEXEC);
5122         if (fd < 0)
5123                 return -errno;
5124
5125         if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5126                 err = -errno;
5127
5128         close_nointr_nofail(fd);
5129
5130         return err;
5131 }
5132
5133 int copy_file(const char *from, const char *to) {
5134         int r, fdf, fdt;
5135
5136         assert(from);
5137         assert(to);
5138
5139         fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5140         if (fdf < 0)
5141                 return -errno;
5142
5143         fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5144         if (fdt < 0) {
5145                 close_nointr_nofail(fdf);
5146                 return -errno;
5147         }
5148
5149         for (;;) {
5150                 char buf[PIPE_BUF];
5151                 ssize_t n, k;
5152
5153                 n = read(fdf, buf, sizeof(buf));
5154                 if (n < 0) {
5155                         r = -errno;
5156
5157                         close_nointr_nofail(fdf);
5158                         close_nointr(fdt);
5159                         unlink(to);
5160
5161                         return r;
5162                 }
5163
5164                 if (n == 0)
5165                         break;
5166
5167                 errno = 0;
5168                 k = loop_write(fdt, buf, n, false);
5169                 if (n != k) {
5170                         r = k < 0 ? k : (errno ? -errno : -EIO);
5171
5172                         close_nointr_nofail(fdf);
5173                         close_nointr(fdt);
5174
5175                         unlink(to);
5176                         return r;
5177                 }
5178         }
5179
5180         close_nointr_nofail(fdf);
5181         r = close_nointr(fdt);
5182
5183         if (r < 0) {
5184                 unlink(to);
5185                 return r;
5186         }
5187
5188         return 0;
5189 }
5190
5191 int symlink_or_copy(const char *from, const char *to) {
5192         char *pf = NULL, *pt = NULL;
5193         struct stat a, b;
5194         int r;
5195
5196         assert(from);
5197         assert(to);
5198
5199         if (parent_of_path(from, &pf) < 0 ||
5200             parent_of_path(to, &pt) < 0) {
5201                 r = -ENOMEM;
5202                 goto finish;
5203         }
5204
5205         if (stat(pf, &a) < 0 ||
5206             stat(pt, &b) < 0) {
5207                 r = -errno;
5208                 goto finish;
5209         }
5210
5211         if (a.st_dev != b.st_dev) {
5212                 free(pf);
5213                 free(pt);
5214
5215                 return copy_file(from, to);
5216         }
5217
5218         if (symlink(from, to) < 0) {
5219                 r = -errno;
5220                 goto finish;
5221         }
5222
5223         r = 0;
5224
5225 finish:
5226         free(pf);
5227         free(pt);
5228
5229         return r;
5230 }
5231
5232 int symlink_or_copy_atomic(const char *from, const char *to) {
5233         char *t, *x;
5234         const char *fn;
5235         size_t k;
5236         unsigned long long ull;
5237         unsigned i;
5238         int r;
5239
5240         assert(from);
5241         assert(to);
5242
5243         t = new(char, strlen(to) + 1 + 16 + 1);
5244         if (!t)
5245                 return -ENOMEM;
5246
5247         fn = file_name_from_path(to);
5248         k = fn-to;
5249         memcpy(t, to, k);
5250         t[k] = '.';
5251         x = stpcpy(t+k+1, fn);
5252
5253         ull = random_ull();
5254         for (i = 0; i < 16; i++) {
5255                 *(x++) = hexchar(ull & 0xF);
5256                 ull >>= 4;
5257         }
5258
5259         *x = 0;
5260
5261         r = symlink_or_copy(from, t);
5262         if (r < 0) {
5263                 unlink(t);
5264                 free(t);
5265                 return r;
5266         }
5267
5268         if (rename(t, to) < 0) {
5269                 r = -errno;
5270                 unlink(t);
5271                 free(t);
5272                 return r;
5273         }
5274
5275         free(t);
5276         return r;
5277 }
5278
5279 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5280         char *s;
5281         uint32_t u;
5282         int r;
5283
5284         assert(id);
5285
5286         if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5287                 return -ENOENT;
5288
5289         if (pid == 0)
5290                 r = read_one_line_file("/proc/self/sessionid", &s);
5291         else {
5292                 char *p;
5293
5294                 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5295                         return -ENOMEM;
5296
5297                 r = read_one_line_file(p, &s);
5298                 free(p);
5299         }
5300
5301         if (r < 0)
5302                 return r;
5303
5304         r = safe_atou32(s, &u);
5305         free(s);
5306
5307         if (r < 0)
5308                 return r;
5309
5310         if (u == (uint32_t) -1 || u <= 0)
5311                 return -ENOENT;
5312
5313         *id = u;
5314         return 0;
5315 }
5316
5317 int audit_loginuid_from_pid(pid_t pid, uid_t *uid) {
5318         char *s;
5319         uid_t u;
5320         int r;
5321
5322         assert(uid);
5323
5324         /* Only use audit login uid if we are executed with sufficient
5325          * capabilities so that pam_loginuid could do its job. If we
5326          * are lacking the CAP_AUDIT_CONTROL capabality we most likely
5327          * are being run in a container and /proc/self/loginuid is
5328          * useless since it probably contains a uid of the host
5329          * system. */
5330
5331         if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5332                 return -ENOENT;
5333
5334         if (pid == 0)
5335                 r = read_one_line_file("/proc/self/loginuid", &s);
5336         else {
5337                 char *p;
5338
5339                 if (asprintf(&p, "/proc/%lu/loginuid", (unsigned long) pid) < 0)
5340                         return -ENOMEM;
5341
5342                 r = read_one_line_file(p, &s);
5343                 free(p);
5344         }
5345
5346         if (r < 0)
5347                 return r;
5348
5349         r = parse_uid(s, &u);
5350         free(s);
5351
5352         if (r < 0)
5353                 return r;
5354
5355         if (u == (uid_t) -1)
5356                 return -ENOENT;
5357
5358         *uid = (uid_t) u;
5359         return 0;
5360 }
5361
5362 bool display_is_local(const char *display) {
5363         assert(display);
5364
5365         return
5366                 display[0] == ':' &&
5367                 display[1] >= '0' &&
5368                 display[1] <= '9';
5369 }
5370
5371 int socket_from_display(const char *display, char **path) {
5372         size_t k;
5373         char *f, *c;
5374
5375         assert(display);
5376         assert(path);
5377
5378         if (!display_is_local(display))
5379                 return -EINVAL;
5380
5381         k = strspn(display+1, "0123456789");
5382
5383         f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5384         if (!f)
5385                 return -ENOMEM;
5386
5387         c = stpcpy(f, "/tmp/.X11-unix/X");
5388         memcpy(c, display+1, k);
5389         c[k] = 0;
5390
5391         *path = f;
5392
5393         return 0;
5394 }
5395
5396 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5397         struct passwd *p;
5398         uid_t u;
5399
5400         assert(username);
5401         assert(*username);
5402
5403         /* We enforce some special rules for uid=0: in order to avoid
5404          * NSS lookups for root we hardcode its data. */
5405
5406         if (streq(*username, "root") || streq(*username, "0")) {
5407                 *username = "root";
5408
5409                 if (uid)
5410                         *uid = 0;
5411
5412                 if (gid)
5413                         *gid = 0;
5414
5415                 if (home)
5416                         *home = "/root";
5417                 return 0;
5418         }
5419
5420         if (parse_uid(*username, &u) >= 0) {
5421                 errno = 0;
5422                 p = getpwuid(u);
5423
5424                 /* If there are multiple users with the same id, make
5425                  * sure to leave $USER to the configured value instead
5426                  * of the first occurrence in the database. However if
5427                  * the uid was configured by a numeric uid, then let's
5428                  * pick the real username from /etc/passwd. */
5429                 if (p)
5430                         *username = p->pw_name;
5431         } else {
5432                 errno = 0;
5433                 p = getpwnam(*username);
5434         }
5435
5436         if (!p)
5437                 return errno != 0 ? -errno : -ESRCH;
5438
5439         if (uid)
5440                 *uid = p->pw_uid;
5441
5442         if (gid)
5443                 *gid = p->pw_gid;
5444
5445         if (home)
5446                 *home = p->pw_dir;
5447
5448         return 0;
5449 }
5450
5451 int get_group_creds(const char **groupname, gid_t *gid) {
5452         struct group *g;
5453         gid_t id;
5454
5455         assert(groupname);
5456
5457         /* We enforce some special rules for gid=0: in order to avoid
5458          * NSS lookups for root we hardcode its data. */
5459
5460         if (streq(*groupname, "root") || streq(*groupname, "0")) {
5461                 *groupname = "root";
5462
5463                 if (gid)
5464                         *gid = 0;
5465
5466                 return 0;
5467         }
5468
5469         if (parse_gid(*groupname, &id) >= 0) {
5470                 errno = 0;
5471                 g = getgrgid(id);
5472
5473                 if (g)
5474                         *groupname = g->gr_name;
5475         } else {
5476                 errno = 0;
5477                 g = getgrnam(*groupname);
5478         }
5479
5480         if (!g)
5481                 return errno != 0 ? -errno : -ESRCH;
5482
5483         if (gid)
5484                 *gid = g->gr_gid;
5485
5486         return 0;
5487 }
5488
5489 int glob_exists(const char *path) {
5490         glob_t g;
5491         int r, k;
5492
5493         assert(path);
5494
5495         zero(g);
5496         errno = 0;
5497         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5498
5499         if (k == GLOB_NOMATCH)
5500                 r = 0;
5501         else if (k == GLOB_NOSPACE)
5502                 r = -ENOMEM;
5503         else if (k == 0)
5504                 r = !strv_isempty(g.gl_pathv);
5505         else
5506                 r = errno ? -errno : -EIO;
5507
5508         globfree(&g);
5509
5510         return r;
5511 }
5512
5513 int dirent_ensure_type(DIR *d, struct dirent *de) {
5514         struct stat st;
5515
5516         assert(d);
5517         assert(de);
5518
5519         if (de->d_type != DT_UNKNOWN)
5520                 return 0;
5521
5522         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5523                 return -errno;
5524
5525         de->d_type =
5526                 S_ISREG(st.st_mode)  ? DT_REG  :
5527                 S_ISDIR(st.st_mode)  ? DT_DIR  :
5528                 S_ISLNK(st.st_mode)  ? DT_LNK  :
5529                 S_ISFIFO(st.st_mode) ? DT_FIFO :
5530                 S_ISSOCK(st.st_mode) ? DT_SOCK :
5531                 S_ISCHR(st.st_mode)  ? DT_CHR  :
5532                 S_ISBLK(st.st_mode)  ? DT_BLK  :
5533                                        DT_UNKNOWN;
5534
5535         return 0;
5536 }
5537
5538 int in_search_path(const char *path, char **search) {
5539         char **i, *parent;
5540         int r;
5541
5542         r = parent_of_path(path, &parent);
5543         if (r < 0)
5544                 return r;
5545
5546         r = 0;
5547
5548         STRV_FOREACH(i, search) {
5549                 if (path_equal(parent, *i)) {
5550                         r = 1;
5551                         break;
5552                 }
5553         }
5554
5555         free(parent);
5556
5557         return r;
5558 }
5559
5560 int get_files_in_directory(const char *path, char ***list) {
5561         DIR *d;
5562         int r = 0;
5563         unsigned n = 0;
5564         char **l = NULL;
5565
5566         assert(path);
5567
5568         /* Returns all files in a directory in *list, and the number
5569          * of files as return value. If list is NULL returns only the
5570          * number */
5571
5572         d = opendir(path);
5573         if (!d)
5574                 return -errno;
5575
5576         for (;;) {
5577                 struct dirent buffer, *de;
5578                 int k;
5579
5580                 k = readdir_r(d, &buffer, &de);
5581                 if (k != 0) {
5582                         r = -k;
5583                         goto finish;
5584                 }
5585
5586                 if (!de)
5587                         break;
5588
5589                 dirent_ensure_type(d, de);
5590
5591                 if (!dirent_is_file(de))
5592                         continue;
5593
5594                 if (list) {
5595                         if ((unsigned) r >= n) {
5596                                 char **t;
5597
5598                                 n = MAX(16, 2*r);
5599                                 t = realloc(l, sizeof(char*) * n);
5600                                 if (!t) {
5601                                         r = -ENOMEM;
5602                                         goto finish;
5603                                 }
5604
5605                                 l = t;
5606                         }
5607
5608                         assert((unsigned) r < n);
5609
5610                         l[r] = strdup(de->d_name);
5611                         if (!l[r]) {
5612                                 r = -ENOMEM;
5613                                 goto finish;
5614                         }
5615
5616                         l[++r] = NULL;
5617                 } else
5618                         r++;
5619         }
5620
5621 finish:
5622         if (d)
5623                 closedir(d);
5624
5625         if (r >= 0) {
5626                 if (list)
5627                         *list = l;
5628         } else
5629                 strv_free(l);
5630
5631         return r;
5632 }
5633
5634 char *join(const char *x, ...) {
5635         va_list ap;
5636         size_t l;
5637         char *r, *p;
5638
5639         va_start(ap, x);
5640
5641         if (x) {
5642                 l = strlen(x);
5643
5644                 for (;;) {
5645                         const char *t;
5646
5647                         t = va_arg(ap, const char *);
5648                         if (!t)
5649                                 break;
5650
5651                         l += strlen(t);
5652                 }
5653         } else
5654                 l = 0;
5655
5656         va_end(ap);
5657
5658         r = new(char, l+1);
5659         if (!r)
5660                 return NULL;
5661
5662         if (x) {
5663                 p = stpcpy(r, x);
5664
5665                 va_start(ap, x);
5666
5667                 for (;;) {
5668                         const char *t;
5669
5670                         t = va_arg(ap, const char *);
5671                         if (!t)
5672                                 break;
5673
5674                         p = stpcpy(p, t);
5675                 }
5676
5677                 va_end(ap);
5678         } else
5679                 r[0] = 0;
5680
5681         return r;
5682 }
5683
5684 bool is_main_thread(void) {
5685         static __thread int cached = 0;
5686
5687         if (_unlikely_(cached == 0))
5688                 cached = getpid() == gettid() ? 1 : -1;
5689
5690         return cached > 0;
5691 }
5692
5693 int block_get_whole_disk(dev_t d, dev_t *ret) {
5694         char *p, *s;
5695         int r;
5696         unsigned n, m;
5697
5698         assert(ret);
5699
5700         /* If it has a queue this is good enough for us */
5701         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5702                 return -ENOMEM;
5703
5704         r = access(p, F_OK);
5705         free(p);
5706
5707         if (r >= 0) {
5708                 *ret = d;
5709                 return 0;
5710         }
5711
5712         /* If it is a partition find the originating device */
5713         if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5714                 return -ENOMEM;
5715
5716         r = access(p, F_OK);
5717         free(p);
5718
5719         if (r < 0)
5720                 return -ENOENT;
5721
5722         /* Get parent dev_t */
5723         if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5724                 return -ENOMEM;
5725
5726         r = read_one_line_file(p, &s);
5727         free(p);
5728
5729         if (r < 0)
5730                 return r;
5731
5732         r = sscanf(s, "%u:%u", &m, &n);
5733         free(s);
5734
5735         if (r != 2)
5736                 return -EINVAL;
5737
5738         /* Only return this if it is really good enough for us. */
5739         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5740                 return -ENOMEM;
5741
5742         r = access(p, F_OK);
5743         free(p);
5744
5745         if (r >= 0) {
5746                 *ret = makedev(m, n);
5747                 return 0;
5748         }
5749
5750         return -ENOENT;
5751 }
5752
5753 int file_is_sticky(const char *p) {
5754         struct stat st;
5755
5756         assert(p);
5757
5758         if (lstat(p, &st) < 0)
5759                 return -errno;
5760
5761         return
5762                 st.st_uid == 0 &&
5763                 (st.st_mode & S_ISVTX);
5764 }
5765
5766 static const char *const ioprio_class_table[] = {
5767         [IOPRIO_CLASS_NONE] = "none",
5768         [IOPRIO_CLASS_RT] = "realtime",
5769         [IOPRIO_CLASS_BE] = "best-effort",
5770         [IOPRIO_CLASS_IDLE] = "idle"
5771 };
5772
5773 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5774
5775 static const char *const sigchld_code_table[] = {
5776         [CLD_EXITED] = "exited",
5777         [CLD_KILLED] = "killed",
5778         [CLD_DUMPED] = "dumped",
5779         [CLD_TRAPPED] = "trapped",
5780         [CLD_STOPPED] = "stopped",
5781         [CLD_CONTINUED] = "continued",
5782 };
5783
5784 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5785
5786 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5787         [LOG_FAC(LOG_KERN)] = "kern",
5788         [LOG_FAC(LOG_USER)] = "user",
5789         [LOG_FAC(LOG_MAIL)] = "mail",
5790         [LOG_FAC(LOG_DAEMON)] = "daemon",
5791         [LOG_FAC(LOG_AUTH)] = "auth",
5792         [LOG_FAC(LOG_SYSLOG)] = "syslog",
5793         [LOG_FAC(LOG_LPR)] = "lpr",
5794         [LOG_FAC(LOG_NEWS)] = "news",
5795         [LOG_FAC(LOG_UUCP)] = "uucp",
5796         [LOG_FAC(LOG_CRON)] = "cron",
5797         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5798         [LOG_FAC(LOG_FTP)] = "ftp",
5799         [LOG_FAC(LOG_LOCAL0)] = "local0",
5800         [LOG_FAC(LOG_LOCAL1)] = "local1",
5801         [LOG_FAC(LOG_LOCAL2)] = "local2",
5802         [LOG_FAC(LOG_LOCAL3)] = "local3",
5803         [LOG_FAC(LOG_LOCAL4)] = "local4",
5804         [LOG_FAC(LOG_LOCAL5)] = "local5",
5805         [LOG_FAC(LOG_LOCAL6)] = "local6",
5806         [LOG_FAC(LOG_LOCAL7)] = "local7"
5807 };
5808
5809 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5810
5811 static const char *const log_level_table[] = {
5812         [LOG_EMERG] = "emerg",
5813         [LOG_ALERT] = "alert",
5814         [LOG_CRIT] = "crit",
5815         [LOG_ERR] = "err",
5816         [LOG_WARNING] = "warning",
5817         [LOG_NOTICE] = "notice",
5818         [LOG_INFO] = "info",
5819         [LOG_DEBUG] = "debug"
5820 };
5821
5822 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5823
5824 static const char* const sched_policy_table[] = {
5825         [SCHED_OTHER] = "other",
5826         [SCHED_BATCH] = "batch",
5827         [SCHED_IDLE] = "idle",
5828         [SCHED_FIFO] = "fifo",
5829         [SCHED_RR] = "rr"
5830 };
5831
5832 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5833
5834 static const char* const rlimit_table[] = {
5835         [RLIMIT_CPU] = "LimitCPU",
5836         [RLIMIT_FSIZE] = "LimitFSIZE",
5837         [RLIMIT_DATA] = "LimitDATA",
5838         [RLIMIT_STACK] = "LimitSTACK",
5839         [RLIMIT_CORE] = "LimitCORE",
5840         [RLIMIT_RSS] = "LimitRSS",
5841         [RLIMIT_NOFILE] = "LimitNOFILE",
5842         [RLIMIT_AS] = "LimitAS",
5843         [RLIMIT_NPROC] = "LimitNPROC",
5844         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5845         [RLIMIT_LOCKS] = "LimitLOCKS",
5846         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5847         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5848         [RLIMIT_NICE] = "LimitNICE",
5849         [RLIMIT_RTPRIO] = "LimitRTPRIO",
5850         [RLIMIT_RTTIME] = "LimitRTTIME"
5851 };
5852
5853 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5854
5855 static const char* const ip_tos_table[] = {
5856         [IPTOS_LOWDELAY] = "low-delay",
5857         [IPTOS_THROUGHPUT] = "throughput",
5858         [IPTOS_RELIABILITY] = "reliability",
5859         [IPTOS_LOWCOST] = "low-cost",
5860 };
5861
5862 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5863
5864 static const char *const __signal_table[] = {
5865         [SIGHUP] = "HUP",
5866         [SIGINT] = "INT",
5867         [SIGQUIT] = "QUIT",
5868         [SIGILL] = "ILL",
5869         [SIGTRAP] = "TRAP",
5870         [SIGABRT] = "ABRT",
5871         [SIGBUS] = "BUS",
5872         [SIGFPE] = "FPE",
5873         [SIGKILL] = "KILL",
5874         [SIGUSR1] = "USR1",
5875         [SIGSEGV] = "SEGV",
5876         [SIGUSR2] = "USR2",
5877         [SIGPIPE] = "PIPE",
5878         [SIGALRM] = "ALRM",
5879         [SIGTERM] = "TERM",
5880 #ifdef SIGSTKFLT
5881         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
5882 #endif
5883         [SIGCHLD] = "CHLD",
5884         [SIGCONT] = "CONT",
5885         [SIGSTOP] = "STOP",
5886         [SIGTSTP] = "TSTP",
5887         [SIGTTIN] = "TTIN",
5888         [SIGTTOU] = "TTOU",
5889         [SIGURG] = "URG",
5890         [SIGXCPU] = "XCPU",
5891         [SIGXFSZ] = "XFSZ",
5892         [SIGVTALRM] = "VTALRM",
5893         [SIGPROF] = "PROF",
5894         [SIGWINCH] = "WINCH",
5895         [SIGIO] = "IO",
5896         [SIGPWR] = "PWR",
5897         [SIGSYS] = "SYS"
5898 };
5899
5900 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5901
5902 const char *signal_to_string(int signo) {
5903         static __thread char buf[12];
5904         const char *name;
5905
5906         name = __signal_to_string(signo);
5907         if (name)
5908                 return name;
5909
5910         if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5911                 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5912         else
5913                 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5914         char_array_0(buf);
5915         return buf;
5916 }
5917
5918 int signal_from_string(const char *s) {
5919         int signo;
5920         int offset = 0;
5921         unsigned u;
5922
5923         signo =__signal_from_string(s);
5924         if (signo > 0)
5925                 return signo;
5926
5927         if (startswith(s, "RTMIN+")) {
5928                 s += 6;
5929                 offset = SIGRTMIN;
5930         }
5931         if (safe_atou(s, &u) >= 0) {
5932                 signo = (int) u + offset;
5933                 if (signo > 0 && signo < _NSIG)
5934                         return signo;
5935         }
5936         return -1;
5937 }
5938
5939 bool kexec_loaded(void) {
5940        bool loaded = false;
5941        char *s;
5942
5943        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5944                if (s[0] == '1')
5945                        loaded = true;
5946                free(s);
5947        }
5948        return loaded;
5949 }
5950
5951 int strdup_or_null(const char *a, char **b) {
5952         char *c;
5953
5954         assert(b);
5955
5956         if (!a) {
5957                 *b = NULL;
5958                 return 0;
5959         }
5960
5961         c = strdup(a);
5962         if (!c)
5963                 return -ENOMEM;
5964
5965         *b = c;
5966         return 0;
5967 }
5968
5969 int prot_from_flags(int flags) {
5970
5971         switch (flags & O_ACCMODE) {
5972
5973         case O_RDONLY:
5974                 return PROT_READ;
5975
5976         case O_WRONLY:
5977                 return PROT_WRITE;
5978
5979         case O_RDWR:
5980                 return PROT_READ|PROT_WRITE;
5981
5982         default:
5983                 return -EINVAL;
5984         }
5985 }
5986
5987 unsigned long cap_last_cap(void) {
5988         static __thread unsigned long saved;
5989         static __thread bool valid = false;
5990         unsigned long p;
5991
5992         if (valid)
5993                 return saved;
5994
5995         p = (unsigned long) CAP_LAST_CAP;
5996
5997         if (prctl(PR_CAPBSET_READ, p) < 0) {
5998
5999                 /* Hmm, look downwards, until we find one that
6000                  * works */
6001                 for (p--; p > 0; p --)
6002                         if (prctl(PR_CAPBSET_READ, p) >= 0)
6003                                 break;
6004
6005         } else {
6006
6007                 /* Hmm, look upwards, until we find one that doesn't
6008                  * work */
6009                 for (;; p++)
6010                         if (prctl(PR_CAPBSET_READ, p+1) < 0)
6011                                 break;
6012         }
6013
6014         saved = p;
6015         valid = true;
6016
6017         return p;
6018 }
6019
6020 char *format_bytes(char *buf, size_t l, off_t t) {
6021         unsigned i;
6022
6023         static const struct {
6024                 const char *suffix;
6025                 off_t factor;
6026         } table[] = {
6027                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
6028                 { "G", 1024ULL*1024ULL*1024ULL },
6029                 { "M", 1024ULL*1024ULL },
6030                 { "K", 1024ULL },
6031         };
6032
6033         for (i = 0; i < ELEMENTSOF(table); i++) {
6034
6035                 if (t >= table[i].factor) {
6036                         snprintf(buf, l,
6037                                  "%llu.%llu%s",
6038                                  (unsigned long long) (t / table[i].factor),
6039                                  (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
6040                                  table[i].suffix);
6041
6042                         goto finish;
6043                 }
6044         }
6045
6046         snprintf(buf, l, "%lluB", (unsigned long long) t);
6047
6048 finish:
6049         buf[l-1] = 0;
6050         return buf;
6051
6052 }