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