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