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