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