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