chiark / gitweb /
systemctl: append .service to unit names lacking suffix
[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 #include <sys/vfs.h>
58 #include <linux/magic.h>
59
60 #include "macro.h"
61 #include "util.h"
62 #include "ioprio.h"
63 #include "missing.h"
64 #include "log.h"
65 #include "strv.h"
66 #include "label.h"
67 #include "path-util.h"
68 #include "exit-status.h"
69 #include "hashmap.h"
70
71 int saved_argc = 0;
72 char **saved_argv = NULL;
73
74 size_t page_size(void) {
75         static __thread size_t pgsz = 0;
76         long r;
77
78         if (_likely_(pgsz > 0))
79                 return pgsz;
80
81         assert_se((r = sysconf(_SC_PAGESIZE)) > 0);
82
83         pgsz = (size_t) r;
84
85         return pgsz;
86 }
87
88 bool streq_ptr(const char *a, const char *b) {
89
90         /* Like streq(), but tries to make sense of NULL pointers */
91
92         if (a && b)
93                 return streq(a, b);
94
95         if (!a && !b)
96                 return true;
97
98         return false;
99 }
100
101 usec_t now(clockid_t clock_id) {
102         struct timespec ts;
103
104         assert_se(clock_gettime(clock_id, &ts) == 0);
105
106         return timespec_load(&ts);
107 }
108
109 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
110         assert(ts);
111
112         ts->realtime = now(CLOCK_REALTIME);
113         ts->monotonic = now(CLOCK_MONOTONIC);
114
115         return ts;
116 }
117
118 dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u) {
119         int64_t delta;
120         assert(ts);
121
122         ts->realtime = u;
123
124         if (u == 0)
125                 ts->monotonic = 0;
126         else {
127                 delta = (int64_t) now(CLOCK_REALTIME) - (int64_t) u;
128
129                 ts->monotonic = now(CLOCK_MONOTONIC);
130
131                 if ((int64_t) ts->monotonic > delta)
132                         ts->monotonic -= delta;
133                 else
134                         ts->monotonic = 0;
135         }
136
137         return ts;
138 }
139
140 usec_t timespec_load(const struct timespec *ts) {
141         assert(ts);
142
143         return
144                 (usec_t) ts->tv_sec * USEC_PER_SEC +
145                 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
146 }
147
148 struct timespec *timespec_store(struct timespec *ts, usec_t u)  {
149         assert(ts);
150
151         ts->tv_sec = (time_t) (u / USEC_PER_SEC);
152         ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
153
154         return ts;
155 }
156
157 usec_t timeval_load(const struct timeval *tv) {
158         assert(tv);
159
160         return
161                 (usec_t) tv->tv_sec * USEC_PER_SEC +
162                 (usec_t) tv->tv_usec;
163 }
164
165 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
166         assert(tv);
167
168         tv->tv_sec = (time_t) (u / USEC_PER_SEC);
169         tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
170
171         return tv;
172 }
173
174 bool endswith(const char *s, const char *postfix) {
175         size_t sl, pl;
176
177         assert(s);
178         assert(postfix);
179
180         sl = strlen(s);
181         pl = strlen(postfix);
182
183         if (pl == 0)
184                 return true;
185
186         if (sl < pl)
187                 return false;
188
189         return memcmp(s + sl - pl, postfix, pl) == 0;
190 }
191
192 bool startswith(const char *s, const char *prefix) {
193         size_t sl, pl;
194
195         assert(s);
196         assert(prefix);
197
198         sl = strlen(s);
199         pl = strlen(prefix);
200
201         if (pl == 0)
202                 return true;
203
204         if (sl < pl)
205                 return false;
206
207         return memcmp(s, prefix, pl) == 0;
208 }
209
210 bool startswith_no_case(const char *s, const char *prefix) {
211         size_t sl, pl;
212         unsigned i;
213
214         assert(s);
215         assert(prefix);
216
217         sl = strlen(s);
218         pl = strlen(prefix);
219
220         if (pl == 0)
221                 return true;
222
223         if (sl < pl)
224                 return false;
225
226         for(i = 0; i < pl; ++i) {
227                 if (tolower(s[i]) != tolower(prefix[i]))
228                         return false;
229         }
230
231         return true;
232 }
233
234 bool first_word(const char *s, const char *word) {
235         size_t sl, wl;
236
237         assert(s);
238         assert(word);
239
240         sl = strlen(s);
241         wl = strlen(word);
242
243         if (sl < wl)
244                 return false;
245
246         if (wl == 0)
247                 return true;
248
249         if (memcmp(s, word, wl) != 0)
250                 return false;
251
252         return s[wl] == 0 ||
253                 strchr(WHITESPACE, s[wl]);
254 }
255
256 int close_nointr(int fd) {
257         assert(fd >= 0);
258
259         for (;;) {
260                 int r;
261
262                 r = close(fd);
263                 if (r >= 0)
264                         return r;
265
266                 if (errno != EINTR)
267                         return -errno;
268         }
269 }
270
271 void close_nointr_nofail(int fd) {
272         int saved_errno = errno;
273
274         /* like close_nointr() but cannot fail, and guarantees errno
275          * is unchanged */
276
277         assert_se(close_nointr(fd) == 0);
278
279         errno = saved_errno;
280 }
281
282 void close_many(const int fds[], unsigned n_fd) {
283         unsigned i;
284
285         for (i = 0; i < n_fd; i++)
286                 close_nointr_nofail(fds[i]);
287 }
288
289 int parse_boolean(const char *v) {
290         assert(v);
291
292         if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
293                 return 1;
294         else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
295                 return 0;
296
297         return -EINVAL;
298 }
299
300 int parse_pid(const char *s, pid_t* ret_pid) {
301         unsigned long ul = 0;
302         pid_t pid;
303         int r;
304
305         assert(s);
306         assert(ret_pid);
307
308         if ((r = safe_atolu(s, &ul)) < 0)
309                 return r;
310
311         pid = (pid_t) ul;
312
313         if ((unsigned long) pid != ul)
314                 return -ERANGE;
315
316         if (pid <= 0)
317                 return -ERANGE;
318
319         *ret_pid = pid;
320         return 0;
321 }
322
323 int parse_uid(const char *s, uid_t* ret_uid) {
324         unsigned long ul = 0;
325         uid_t uid;
326         int r;
327
328         assert(s);
329         assert(ret_uid);
330
331         if ((r = safe_atolu(s, &ul)) < 0)
332                 return r;
333
334         uid = (uid_t) ul;
335
336         if ((unsigned long) uid != ul)
337                 return -ERANGE;
338
339         *ret_uid = uid;
340         return 0;
341 }
342
343 int safe_atou(const char *s, unsigned *ret_u) {
344         char *x = NULL;
345         unsigned long l;
346
347         assert(s);
348         assert(ret_u);
349
350         errno = 0;
351         l = strtoul(s, &x, 0);
352
353         if (!x || *x || errno)
354                 return errno ? -errno : -EINVAL;
355
356         if ((unsigned long) (unsigned) l != l)
357                 return -ERANGE;
358
359         *ret_u = (unsigned) l;
360         return 0;
361 }
362
363 int safe_atoi(const char *s, int *ret_i) {
364         char *x = NULL;
365         long l;
366
367         assert(s);
368         assert(ret_i);
369
370         errno = 0;
371         l = strtol(s, &x, 0);
372
373         if (!x || *x || errno)
374                 return errno ? -errno : -EINVAL;
375
376         if ((long) (int) l != l)
377                 return -ERANGE;
378
379         *ret_i = (int) l;
380         return 0;
381 }
382
383 int safe_atollu(const char *s, long long unsigned *ret_llu) {
384         char *x = NULL;
385         unsigned long long l;
386
387         assert(s);
388         assert(ret_llu);
389
390         errno = 0;
391         l = strtoull(s, &x, 0);
392
393         if (!x || *x || errno)
394                 return errno ? -errno : -EINVAL;
395
396         *ret_llu = l;
397         return 0;
398 }
399
400 int safe_atolli(const char *s, long long int *ret_lli) {
401         char *x = NULL;
402         long long l;
403
404         assert(s);
405         assert(ret_lli);
406
407         errno = 0;
408         l = strtoll(s, &x, 0);
409
410         if (!x || *x || errno)
411                 return errno ? -errno : -EINVAL;
412
413         *ret_lli = l;
414         return 0;
415 }
416
417 /* Split a string into words. */
418 char *split(const char *c, size_t *l, const char *separator, char **state) {
419         char *current;
420
421         current = *state ? *state : (char*) c;
422
423         if (!*current || *c == 0)
424                 return NULL;
425
426         current += strspn(current, separator);
427         *l = strcspn(current, separator);
428         *state = current+*l;
429
430         return (char*) current;
431 }
432
433 /* Split a string into words, but consider strings enclosed in '' and
434  * "" as words even if they include spaces. */
435 char *split_quoted(const char *c, size_t *l, char **state) {
436         char *current, *e;
437         bool escaped = false;
438
439         current = *state ? *state : (char*) c;
440
441         if (!*current || *c == 0)
442                 return NULL;
443
444         current += strspn(current, WHITESPACE);
445
446         if (*current == '\'') {
447                 current ++;
448
449                 for (e = current; *e; e++) {
450                         if (escaped)
451                                 escaped = false;
452                         else if (*e == '\\')
453                                 escaped = true;
454                         else if (*e == '\'')
455                                 break;
456                 }
457
458                 *l = e-current;
459                 *state = *e == 0 ? e : e+1;
460         } else if (*current == '\"') {
461                 current ++;
462
463                 for (e = current; *e; e++) {
464                         if (escaped)
465                                 escaped = false;
466                         else if (*e == '\\')
467                                 escaped = true;
468                         else if (*e == '\"')
469                                 break;
470                 }
471
472                 *l = e-current;
473                 *state = *e == 0 ? e : e+1;
474         } else {
475                 for (e = current; *e; e++) {
476                         if (escaped)
477                                 escaped = false;
478                         else if (*e == '\\')
479                                 escaped = true;
480                         else if (strchr(WHITESPACE, *e))
481                                 break;
482                 }
483                 *l = e-current;
484                 *state = e;
485         }
486
487         return (char*) current;
488 }
489
490 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
491         int r;
492         FILE *f;
493         char fn[PATH_MAX], line[LINE_MAX], *p;
494         long unsigned ppid;
495
496         assert(pid > 0);
497         assert(_ppid);
498
499         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
500         char_array_0(fn);
501
502         if (!(f = fopen(fn, "re")))
503                 return -errno;
504
505         if (!(fgets(line, sizeof(line), f))) {
506                 r = feof(f) ? -EIO : -errno;
507                 fclose(f);
508                 return r;
509         }
510
511         fclose(f);
512
513         /* Let's skip the pid and comm fields. The latter is enclosed
514          * in () but does not escape any () in its value, so let's
515          * skip over it manually */
516
517         if (!(p = strrchr(line, ')')))
518                 return -EIO;
519
520         p++;
521
522         if (sscanf(p, " "
523                    "%*c "  /* state */
524                    "%lu ", /* ppid */
525                    &ppid) != 1)
526                 return -EIO;
527
528         if ((long unsigned) (pid_t) ppid != ppid)
529                 return -ERANGE;
530
531         *_ppid = (pid_t) ppid;
532
533         return 0;
534 }
535
536 int get_starttime_of_pid(pid_t pid, unsigned long long *st) {
537         int r;
538         FILE *f;
539         char fn[PATH_MAX], line[LINE_MAX], *p;
540
541         assert(pid > 0);
542         assert(st);
543
544         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
545         char_array_0(fn);
546
547         if (!(f = fopen(fn, "re")))
548                 return -errno;
549
550         if (!(fgets(line, sizeof(line), f))) {
551                 r = feof(f) ? -EIO : -errno;
552                 fclose(f);
553                 return r;
554         }
555
556         fclose(f);
557
558         /* Let's skip the pid and comm fields. The latter is enclosed
559          * in () but does not escape any () in its value, so let's
560          * skip over it manually */
561
562         if (!(p = strrchr(line, ')')))
563                 return -EIO;
564
565         p++;
566
567         if (sscanf(p, " "
568                    "%*c "  /* state */
569                    "%*d "  /* ppid */
570                    "%*d "  /* pgrp */
571                    "%*d "  /* session */
572                    "%*d "  /* tty_nr */
573                    "%*d "  /* tpgid */
574                    "%*u "  /* flags */
575                    "%*u "  /* minflt */
576                    "%*u "  /* cminflt */
577                    "%*u "  /* majflt */
578                    "%*u "  /* cmajflt */
579                    "%*u "  /* utime */
580                    "%*u "  /* stime */
581                    "%*d "  /* cutime */
582                    "%*d "  /* cstime */
583                    "%*d "  /* priority */
584                    "%*d "  /* nice */
585                    "%*d "  /* num_threads */
586                    "%*d "  /* itrealvalue */
587                    "%llu "  /* starttime */,
588                    st) != 1)
589                 return -EIO;
590
591         return 0;
592 }
593
594 int write_one_line_file(const char *fn, const char *line) {
595         FILE *f;
596         int r;
597
598         assert(fn);
599         assert(line);
600
601         f = fopen(fn, "we");
602         if (!f)
603                 return -errno;
604
605         errno = 0;
606         if (fputs(line, f) < 0) {
607                 r = -errno;
608                 goto finish;
609         }
610
611         if (!endswith(line, "\n"))
612                 fputc('\n', f);
613
614         fflush(f);
615
616         if (ferror(f)) {
617                 if (errno != 0)
618                         r = -errno;
619                 else
620                         r = -EIO;
621         } else
622                 r = 0;
623
624 finish:
625         fclose(f);
626         return r;
627 }
628
629 int fchmod_umask(int fd, mode_t m) {
630         mode_t u;
631         int r;
632
633         u = umask(0777);
634         r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
635         umask(u);
636
637         return r;
638 }
639
640 int write_one_line_file_atomic(const char *fn, const char *line) {
641         FILE *f;
642         int r;
643         char *p;
644
645         assert(fn);
646         assert(line);
647
648         r = fopen_temporary(fn, &f, &p);
649         if (r < 0)
650                 return r;
651
652         fchmod_umask(fileno(f), 0644);
653
654         errno = 0;
655         if (fputs(line, f) < 0) {
656                 r = -errno;
657                 goto finish;
658         }
659
660         if (!endswith(line, "\n"))
661                 fputc('\n', f);
662
663         fflush(f);
664
665         if (ferror(f)) {
666                 if (errno != 0)
667                         r = -errno;
668                 else
669                         r = -EIO;
670         } else {
671                 if (rename(p, fn) < 0)
672                         r = -errno;
673                 else
674                         r = 0;
675         }
676
677 finish:
678         if (r < 0)
679                 unlink(p);
680
681         fclose(f);
682         free(p);
683
684         return r;
685 }
686
687 int read_one_line_file(const char *fn, char **line) {
688         FILE *f;
689         int r;
690         char t[LINE_MAX], *c;
691
692         assert(fn);
693         assert(line);
694
695         f = fopen(fn, "re");
696         if (!f)
697                 return -errno;
698
699         if (!fgets(t, sizeof(t), f)) {
700
701                 if (ferror(f)) {
702                         r = -errno;
703                         goto finish;
704                 }
705
706                 t[0] = 0;
707         }
708
709         c = strdup(t);
710         if (!c) {
711                 r = -ENOMEM;
712                 goto finish;
713         }
714
715         truncate_nl(c);
716
717         *line = c;
718         r = 0;
719
720 finish:
721         fclose(f);
722         return r;
723 }
724
725 int read_full_file(const char *fn, char **contents, size_t *size) {
726         FILE *f;
727         int r;
728         size_t n, l;
729         char *buf = NULL;
730         struct stat st;
731
732         if (!(f = fopen(fn, "re")))
733                 return -errno;
734
735         if (fstat(fileno(f), &st) < 0) {
736                 r = -errno;
737                 goto finish;
738         }
739
740         /* Safety check */
741         if (st.st_size > 4*1024*1024) {
742                 r = -E2BIG;
743                 goto finish;
744         }
745
746         n = st.st_size > 0 ? st.st_size : LINE_MAX;
747         l = 0;
748
749         for (;;) {
750                 char *t;
751                 size_t k;
752
753                 if (!(t = realloc(buf, n+1))) {
754                         r = -ENOMEM;
755                         goto finish;
756                 }
757
758                 buf = t;
759                 k = fread(buf + l, 1, n - l, f);
760
761                 if (k <= 0) {
762                         if (ferror(f)) {
763                                 r = -errno;
764                                 goto finish;
765                         }
766
767                         break;
768                 }
769
770                 l += k;
771                 n *= 2;
772
773                 /* Safety check */
774                 if (n > 4*1024*1024) {
775                         r = -E2BIG;
776                         goto finish;
777                 }
778         }
779
780         buf[l] = 0;
781         *contents = buf;
782         buf = NULL;
783
784         if (size)
785                 *size = l;
786
787         r = 0;
788
789 finish:
790         fclose(f);
791         free(buf);
792
793         return r;
794 }
795
796 int parse_env_file(
797                 const char *fname,
798                 const char *separator, ...) {
799
800         int r = 0;
801         char *contents = NULL, *p;
802
803         assert(fname);
804         assert(separator);
805
806         if ((r = read_full_file(fname, &contents, NULL)) < 0)
807                 return r;
808
809         p = contents;
810         for (;;) {
811                 const char *key = NULL;
812
813                 p += strspn(p, separator);
814                 p += strspn(p, WHITESPACE);
815
816                 if (!*p)
817                         break;
818
819                 if (!strchr(COMMENTS, *p)) {
820                         va_list ap;
821                         char **value;
822
823                         va_start(ap, separator);
824                         while ((key = va_arg(ap, char *))) {
825                                 size_t n;
826                                 char *v;
827
828                                 value = va_arg(ap, char **);
829
830                                 n = strlen(key);
831                                 if (strncmp(p, key, n) != 0 ||
832                                     p[n] != '=')
833                                         continue;
834
835                                 p += n + 1;
836                                 n = strcspn(p, separator);
837
838                                 if (n >= 2 &&
839                                     strchr(QUOTES, p[0]) &&
840                                     p[n-1] == p[0])
841                                         v = strndup(p+1, n-2);
842                                 else
843                                         v = strndup(p, n);
844
845                                 if (!v) {
846                                         r = -ENOMEM;
847                                         va_end(ap);
848                                         goto fail;
849                                 }
850
851                                 if (v[0] == '\0') {
852                                         /* return empty value strings as NULL */
853                                         free(v);
854                                         v = NULL;
855                                 }
856
857                                 free(*value);
858                                 *value = v;
859
860                                 p += n;
861
862                                 r ++;
863                                 break;
864                         }
865                         va_end(ap);
866                 }
867
868                 if (!key)
869                         p += strcspn(p, separator);
870         }
871
872 fail:
873         free(contents);
874         return r;
875 }
876
877 int load_env_file(
878                 const char *fname,
879                 char ***rl) {
880
881         FILE *f;
882         char **m = NULL;
883         int r;
884
885         assert(fname);
886         assert(rl);
887
888         if (!(f = fopen(fname, "re")))
889                 return -errno;
890
891         while (!feof(f)) {
892                 char l[LINE_MAX], *p, *u;
893                 char **t;
894
895                 if (!fgets(l, sizeof(l), f)) {
896                         if (feof(f))
897                                 break;
898
899                         r = -errno;
900                         goto finish;
901                 }
902
903                 p = strstrip(l);
904
905                 if (!*p)
906                         continue;
907
908                 if (strchr(COMMENTS, *p))
909                         continue;
910
911                 if (!(u = normalize_env_assignment(p))) {
912                         r = log_oom();
913                         goto finish;
914                 }
915
916                 t = strv_append(m, u);
917                 free(u);
918
919                 if (!t) {
920                         r = log_oom();
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 = strjoin("[", 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 = 0, wd = -1;
2387         usec_t ts = 0;
2388         struct sigaction sa_old, sa_new;
2389
2390         assert(name);
2391
2392         /* We use inotify to be notified when the tty is closed. We
2393          * create the watch before checking if we can actually acquire
2394          * it, so that we don't lose any event.
2395          *
2396          * Note: strictly speaking this actually watches for the
2397          * device being closed, it does *not* really watch whether a
2398          * tty loses its controlling process. However, unless some
2399          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2400          * its tty otherwise this will not become a problem. As long
2401          * as the administrator makes sure not configure any service
2402          * on the same tty as an untrusted user this should not be a
2403          * problem. (Which he probably should not do anyway.) */
2404
2405         if (timeout != (usec_t) -1)
2406                 ts = now(CLOCK_MONOTONIC);
2407
2408         if (!fail && !force) {
2409                 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2410                 if (notify < 0) {
2411                         r = -errno;
2412                         goto fail;
2413                 }
2414
2415                 wd = inotify_add_watch(notify, name, IN_CLOSE);
2416                 if (wd < 0) {
2417                         r = -errno;
2418                         goto fail;
2419                 }
2420         }
2421
2422         for (;;) {
2423                 if (notify >= 0) {
2424                         r = flush_fd(notify);
2425                         if (r < 0)
2426                                 goto fail;
2427                 }
2428
2429                 /* We pass here O_NOCTTY only so that we can check the return
2430                  * value TIOCSCTTY and have a reliable way to figure out if we
2431                  * successfully became the controlling process of the tty */
2432                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2433                 if (fd < 0)
2434                         return fd;
2435
2436                 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2437                  * if we already own the tty. */
2438                 zero(sa_new);
2439                 sa_new.sa_handler = SIG_IGN;
2440                 sa_new.sa_flags = SA_RESTART;
2441                 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2442
2443                 /* First, try to get the tty */
2444                 if (ioctl(fd, TIOCSCTTY, force) < 0)
2445                         r = -errno;
2446
2447                 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2448
2449                 /* Sometimes it makes sense to ignore TIOCSCTTY
2450                  * returning EPERM, i.e. when very likely we already
2451                  * are have this controlling terminal. */
2452                 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2453                         r = 0;
2454
2455                 if (r < 0 && (force || fail || r != -EPERM)) {
2456                         goto fail;
2457                 }
2458
2459                 if (r >= 0)
2460                         break;
2461
2462                 assert(!fail);
2463                 assert(!force);
2464                 assert(notify >= 0);
2465
2466                 for (;;) {
2467                         uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2468                         ssize_t l;
2469                         struct inotify_event *e;
2470
2471                         if (timeout != (usec_t) -1) {
2472                                 usec_t n;
2473
2474                                 n = now(CLOCK_MONOTONIC);
2475                                 if (ts + timeout < n) {
2476                                         r = -ETIMEDOUT;
2477                                         goto fail;
2478                                 }
2479
2480                                 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2481                                 if (r < 0)
2482                                         goto fail;
2483
2484                                 if (r == 0) {
2485                                         r = -ETIMEDOUT;
2486                                         goto fail;
2487                                 }
2488                         }
2489
2490                         l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2491                         if (l < 0) {
2492
2493                                 if (errno == EINTR || errno == EAGAIN)
2494                                         continue;
2495
2496                                 r = -errno;
2497                                 goto fail;
2498                         }
2499
2500                         e = (struct inotify_event*) inotify_buffer;
2501
2502                         while (l > 0) {
2503                                 size_t step;
2504
2505                                 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2506                                         r = -EIO;
2507                                         goto fail;
2508                                 }
2509
2510                                 step = sizeof(struct inotify_event) + e->len;
2511                                 assert(step <= (size_t) l);
2512
2513                                 e = (struct inotify_event*) ((uint8_t*) e + step);
2514                                 l -= step;
2515                         }
2516
2517                         break;
2518                 }
2519
2520                 /* We close the tty fd here since if the old session
2521                  * ended our handle will be dead. It's important that
2522                  * we do this after sleeping, so that we don't enter
2523                  * an endless loop. */
2524                 close_nointr_nofail(fd);
2525         }
2526
2527         if (notify >= 0)
2528                 close_nointr_nofail(notify);
2529
2530         r = reset_terminal_fd(fd, true);
2531         if (r < 0)
2532                 log_warning("Failed to reset terminal: %s", strerror(-r));
2533
2534         return fd;
2535
2536 fail:
2537         if (fd >= 0)
2538                 close_nointr_nofail(fd);
2539
2540         if (notify >= 0)
2541                 close_nointr_nofail(notify);
2542
2543         return r;
2544 }
2545
2546 int release_terminal(void) {
2547         int r = 0, fd;
2548         struct sigaction sa_old, sa_new;
2549
2550         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2551                 return -errno;
2552
2553         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2554          * by our own TIOCNOTTY */
2555
2556         zero(sa_new);
2557         sa_new.sa_handler = SIG_IGN;
2558         sa_new.sa_flags = SA_RESTART;
2559         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2560
2561         if (ioctl(fd, TIOCNOTTY) < 0)
2562                 r = -errno;
2563
2564         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2565
2566         close_nointr_nofail(fd);
2567         return r;
2568 }
2569
2570 int sigaction_many(const struct sigaction *sa, ...) {
2571         va_list ap;
2572         int r = 0, sig;
2573
2574         va_start(ap, sa);
2575         while ((sig = va_arg(ap, int)) > 0)
2576                 if (sigaction(sig, sa, NULL) < 0)
2577                         r = -errno;
2578         va_end(ap);
2579
2580         return r;
2581 }
2582
2583 int ignore_signals(int sig, ...) {
2584         struct sigaction sa;
2585         va_list ap;
2586         int r = 0;
2587
2588         zero(sa);
2589         sa.sa_handler = SIG_IGN;
2590         sa.sa_flags = SA_RESTART;
2591
2592         if (sigaction(sig, &sa, NULL) < 0)
2593                 r = -errno;
2594
2595         va_start(ap, sig);
2596         while ((sig = va_arg(ap, int)) > 0)
2597                 if (sigaction(sig, &sa, NULL) < 0)
2598                         r = -errno;
2599         va_end(ap);
2600
2601         return r;
2602 }
2603
2604 int default_signals(int sig, ...) {
2605         struct sigaction sa;
2606         va_list ap;
2607         int r = 0;
2608
2609         zero(sa);
2610         sa.sa_handler = SIG_DFL;
2611         sa.sa_flags = SA_RESTART;
2612
2613         if (sigaction(sig, &sa, NULL) < 0)
2614                 r = -errno;
2615
2616         va_start(ap, sig);
2617         while ((sig = va_arg(ap, int)) > 0)
2618                 if (sigaction(sig, &sa, NULL) < 0)
2619                         r = -errno;
2620         va_end(ap);
2621
2622         return r;
2623 }
2624
2625 int close_pipe(int p[]) {
2626         int a = 0, b = 0;
2627
2628         assert(p);
2629
2630         if (p[0] >= 0) {
2631                 a = close_nointr(p[0]);
2632                 p[0] = -1;
2633         }
2634
2635         if (p[1] >= 0) {
2636                 b = close_nointr(p[1]);
2637                 p[1] = -1;
2638         }
2639
2640         return a < 0 ? a : b;
2641 }
2642
2643 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2644         uint8_t *p;
2645         ssize_t n = 0;
2646
2647         assert(fd >= 0);
2648         assert(buf);
2649
2650         p = buf;
2651
2652         while (nbytes > 0) {
2653                 ssize_t k;
2654
2655                 if ((k = read(fd, p, nbytes)) <= 0) {
2656
2657                         if (k < 0 && errno == EINTR)
2658                                 continue;
2659
2660                         if (k < 0 && errno == EAGAIN && do_poll) {
2661                                 struct pollfd pollfd;
2662
2663                                 zero(pollfd);
2664                                 pollfd.fd = fd;
2665                                 pollfd.events = POLLIN;
2666
2667                                 if (poll(&pollfd, 1, -1) < 0) {
2668                                         if (errno == EINTR)
2669                                                 continue;
2670
2671                                         return n > 0 ? n : -errno;
2672                                 }
2673
2674                                 if (pollfd.revents != POLLIN)
2675                                         return n > 0 ? n : -EIO;
2676
2677                                 continue;
2678                         }
2679
2680                         return n > 0 ? n : (k < 0 ? -errno : 0);
2681                 }
2682
2683                 p += k;
2684                 nbytes -= k;
2685                 n += k;
2686         }
2687
2688         return n;
2689 }
2690
2691 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2692         const uint8_t *p;
2693         ssize_t n = 0;
2694
2695         assert(fd >= 0);
2696         assert(buf);
2697
2698         p = buf;
2699
2700         while (nbytes > 0) {
2701                 ssize_t k;
2702
2703                 k = write(fd, p, nbytes);
2704                 if (k <= 0) {
2705
2706                         if (k < 0 && errno == EINTR)
2707                                 continue;
2708
2709                         if (k < 0 && errno == EAGAIN && do_poll) {
2710                                 struct pollfd pollfd;
2711
2712                                 zero(pollfd);
2713                                 pollfd.fd = fd;
2714                                 pollfd.events = POLLOUT;
2715
2716                                 if (poll(&pollfd, 1, -1) < 0) {
2717                                         if (errno == EINTR)
2718                                                 continue;
2719
2720                                         return n > 0 ? n : -errno;
2721                                 }
2722
2723                                 if (pollfd.revents != POLLOUT)
2724                                         return n > 0 ? n : -EIO;
2725
2726                                 continue;
2727                         }
2728
2729                         return n > 0 ? n : (k < 0 ? -errno : 0);
2730                 }
2731
2732                 p += k;
2733                 nbytes -= k;
2734                 n += k;
2735         }
2736
2737         return n;
2738 }
2739
2740 int parse_usec(const char *t, usec_t *usec) {
2741         static const struct {
2742                 const char *suffix;
2743                 usec_t usec;
2744         } table[] = {
2745                 { "sec", USEC_PER_SEC },
2746                 { "s", USEC_PER_SEC },
2747                 { "min", USEC_PER_MINUTE },
2748                 { "hr", USEC_PER_HOUR },
2749                 { "h", USEC_PER_HOUR },
2750                 { "d", USEC_PER_DAY },
2751                 { "w", USEC_PER_WEEK },
2752                 { "msec", USEC_PER_MSEC },
2753                 { "ms", USEC_PER_MSEC },
2754                 { "m", USEC_PER_MINUTE },
2755                 { "usec", 1ULL },
2756                 { "us", 1ULL },
2757                 { "", USEC_PER_SEC }, /* default is sec */
2758         };
2759
2760         const char *p;
2761         usec_t r = 0;
2762
2763         assert(t);
2764         assert(usec);
2765
2766         p = t;
2767         do {
2768                 long long l;
2769                 char *e;
2770                 unsigned i;
2771
2772                 errno = 0;
2773                 l = strtoll(p, &e, 10);
2774
2775                 if (errno != 0)
2776                         return -errno;
2777
2778                 if (l < 0)
2779                         return -ERANGE;
2780
2781                 if (e == p)
2782                         return -EINVAL;
2783
2784                 e += strspn(e, WHITESPACE);
2785
2786                 for (i = 0; i < ELEMENTSOF(table); i++)
2787                         if (startswith(e, table[i].suffix)) {
2788                                 r += (usec_t) l * table[i].usec;
2789                                 p = e + strlen(table[i].suffix);
2790                                 break;
2791                         }
2792
2793                 if (i >= ELEMENTSOF(table))
2794                         return -EINVAL;
2795
2796         } while (*p != 0);
2797
2798         *usec = r;
2799
2800         return 0;
2801 }
2802
2803 int parse_nsec(const char *t, nsec_t *nsec) {
2804         static const struct {
2805                 const char *suffix;
2806                 nsec_t nsec;
2807         } table[] = {
2808                 { "sec", NSEC_PER_SEC },
2809                 { "s", NSEC_PER_SEC },
2810                 { "min", NSEC_PER_MINUTE },
2811                 { "hr", NSEC_PER_HOUR },
2812                 { "h", NSEC_PER_HOUR },
2813                 { "d", NSEC_PER_DAY },
2814                 { "w", NSEC_PER_WEEK },
2815                 { "msec", NSEC_PER_MSEC },
2816                 { "ms", NSEC_PER_MSEC },
2817                 { "m", NSEC_PER_MINUTE },
2818                 { "usec", NSEC_PER_USEC },
2819                 { "us", NSEC_PER_USEC },
2820                 { "nsec", 1ULL },
2821                 { "ns", 1ULL },
2822                 { "", 1ULL }, /* default is nsec */
2823         };
2824
2825         const char *p;
2826         nsec_t r = 0;
2827
2828         assert(t);
2829         assert(nsec);
2830
2831         p = t;
2832         do {
2833                 long long l;
2834                 char *e;
2835                 unsigned i;
2836
2837                 errno = 0;
2838                 l = strtoll(p, &e, 10);
2839
2840                 if (errno != 0)
2841                         return -errno;
2842
2843                 if (l < 0)
2844                         return -ERANGE;
2845
2846                 if (e == p)
2847                         return -EINVAL;
2848
2849                 e += strspn(e, WHITESPACE);
2850
2851                 for (i = 0; i < ELEMENTSOF(table); i++)
2852                         if (startswith(e, table[i].suffix)) {
2853                                 r += (nsec_t) l * table[i].nsec;
2854                                 p = e + strlen(table[i].suffix);
2855                                 break;
2856                         }
2857
2858                 if (i >= ELEMENTSOF(table))
2859                         return -EINVAL;
2860
2861         } while (*p != 0);
2862
2863         *nsec = r;
2864
2865         return 0;
2866 }
2867
2868 int parse_bytes(const char *t, off_t *bytes) {
2869         static const struct {
2870                 const char *suffix;
2871                 off_t factor;
2872         } table[] = {
2873                 { "B", 1 },
2874                 { "K", 1024ULL },
2875                 { "M", 1024ULL*1024ULL },
2876                 { "G", 1024ULL*1024ULL*1024ULL },
2877                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2878                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2879                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2880                 { "", 1 },
2881         };
2882
2883         const char *p;
2884         off_t r = 0;
2885
2886         assert(t);
2887         assert(bytes);
2888
2889         p = t;
2890         do {
2891                 long long l;
2892                 char *e;
2893                 unsigned i;
2894
2895                 errno = 0;
2896                 l = strtoll(p, &e, 10);
2897
2898                 if (errno != 0)
2899                         return -errno;
2900
2901                 if (l < 0)
2902                         return -ERANGE;
2903
2904                 if (e == p)
2905                         return -EINVAL;
2906
2907                 e += strspn(e, WHITESPACE);
2908
2909                 for (i = 0; i < ELEMENTSOF(table); i++)
2910                         if (startswith(e, table[i].suffix)) {
2911                                 r += (off_t) l * table[i].factor;
2912                                 p = e + strlen(table[i].suffix);
2913                                 break;
2914                         }
2915
2916                 if (i >= ELEMENTSOF(table))
2917                         return -EINVAL;
2918
2919         } while (*p != 0);
2920
2921         *bytes = r;
2922
2923         return 0;
2924 }
2925
2926 int make_stdio(int fd) {
2927         int r, s, t;
2928
2929         assert(fd >= 0);
2930
2931         r = dup2(fd, STDIN_FILENO);
2932         s = dup2(fd, STDOUT_FILENO);
2933         t = dup2(fd, STDERR_FILENO);
2934
2935         if (fd >= 3)
2936                 close_nointr_nofail(fd);
2937
2938         if (r < 0 || s < 0 || t < 0)
2939                 return -errno;
2940
2941         fd_cloexec(STDIN_FILENO, false);
2942         fd_cloexec(STDOUT_FILENO, false);
2943         fd_cloexec(STDERR_FILENO, false);
2944
2945         return 0;
2946 }
2947
2948 int make_null_stdio(void) {
2949         int null_fd;
2950
2951         null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2952         if (null_fd < 0)
2953                 return -errno;
2954
2955         return make_stdio(null_fd);
2956 }
2957
2958 bool is_device_path(const char *path) {
2959
2960         /* Returns true on paths that refer to a device, either in
2961          * sysfs or in /dev */
2962
2963         return
2964                 path_startswith(path, "/dev/") ||
2965                 path_startswith(path, "/sys/");
2966 }
2967
2968 int dir_is_empty(const char *path) {
2969         DIR *d;
2970         int r;
2971         struct dirent buf, *de;
2972
2973         if (!(d = opendir(path)))
2974                 return -errno;
2975
2976         for (;;) {
2977                 if ((r = readdir_r(d, &buf, &de)) > 0) {
2978                         r = -r;
2979                         break;
2980                 }
2981
2982                 if (!de) {
2983                         r = 1;
2984                         break;
2985                 }
2986
2987                 if (!ignore_file(de->d_name)) {
2988                         r = 0;
2989                         break;
2990                 }
2991         }
2992
2993         closedir(d);
2994         return r;
2995 }
2996
2997 unsigned long long random_ull(void) {
2998         int fd;
2999         uint64_t ull;
3000         ssize_t r;
3001
3002         if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
3003                 goto fallback;
3004
3005         r = loop_read(fd, &ull, sizeof(ull), true);
3006         close_nointr_nofail(fd);
3007
3008         if (r != sizeof(ull))
3009                 goto fallback;
3010
3011         return ull;
3012
3013 fallback:
3014         return random() * RAND_MAX + random();
3015 }
3016
3017 void rename_process(const char name[8]) {
3018         assert(name);
3019
3020         /* This is a like a poor man's setproctitle(). It changes the
3021          * comm field, argv[0], and also the glibc's internally used
3022          * name of the process. For the first one a limit of 16 chars
3023          * applies, to the second one usually one of 10 (i.e. length
3024          * of "/sbin/init"), to the third one one of 7 (i.e. length of
3025          * "systemd"). If you pass a longer string it will be
3026          * truncated */
3027
3028         prctl(PR_SET_NAME, name);
3029
3030         if (program_invocation_name)
3031                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3032
3033         if (saved_argc > 0) {
3034                 int i;
3035
3036                 if (saved_argv[0])
3037                         strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3038
3039                 for (i = 1; i < saved_argc; i++) {
3040                         if (!saved_argv[i])
3041                                 break;
3042
3043                         memset(saved_argv[i], 0, strlen(saved_argv[i]));
3044                 }
3045         }
3046 }
3047
3048 void sigset_add_many(sigset_t *ss, ...) {
3049         va_list ap;
3050         int sig;
3051
3052         assert(ss);
3053
3054         va_start(ap, ss);
3055         while ((sig = va_arg(ap, int)) > 0)
3056                 assert_se(sigaddset(ss, sig) == 0);
3057         va_end(ap);
3058 }
3059
3060 char* gethostname_malloc(void) {
3061         struct utsname u;
3062
3063         assert_se(uname(&u) >= 0);
3064
3065         if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3066                 return strdup(u.nodename);
3067
3068         return strdup(u.sysname);
3069 }
3070
3071 bool hostname_is_set(void) {
3072         struct utsname u;
3073
3074         assert_se(uname(&u) >= 0);
3075
3076         return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3077 }
3078
3079
3080 static char *lookup_uid(uid_t uid) {
3081         long bufsize;
3082         char *buf, *name;
3083         struct passwd pwbuf, *pw = NULL;
3084
3085         /* Shortcut things to avoid NSS lookups */
3086         if (uid == 0)
3087                 return strdup("root");
3088
3089         bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3090         if (bufsize <= 0)
3091                 bufsize = 4096;
3092
3093         buf = malloc(bufsize);
3094         if (!buf)
3095                 return NULL;
3096
3097         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3098                 name = strdup(pw->pw_name);
3099                 free(buf);
3100                 return name;
3101         }
3102
3103         free(buf);
3104
3105         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3106                 return NULL;
3107
3108         return name;
3109 }
3110
3111 char* getlogname_malloc(void) {
3112         uid_t uid;
3113         struct stat st;
3114
3115         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3116                 uid = st.st_uid;
3117         else
3118                 uid = getuid();
3119
3120         return lookup_uid(uid);
3121 }
3122
3123 char *getusername_malloc(void) {
3124         const char *e;
3125
3126         e = getenv("USER");
3127         if (e)
3128                 return strdup(e);
3129
3130         return lookup_uid(getuid());
3131 }
3132
3133 int getttyname_malloc(int fd, char **r) {
3134         char path[PATH_MAX], *c;
3135         int k;
3136
3137         assert(r);
3138
3139         if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3140                 return -k;
3141
3142         char_array_0(path);
3143
3144         if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3145                 return -ENOMEM;
3146
3147         *r = c;
3148         return 0;
3149 }
3150
3151 int getttyname_harder(int fd, char **r) {
3152         int k;
3153         char *s;
3154
3155         if ((k = getttyname_malloc(fd, &s)) < 0)
3156                 return k;
3157
3158         if (streq(s, "tty")) {
3159                 free(s);
3160                 return get_ctty(0, NULL, r);
3161         }
3162
3163         *r = s;
3164         return 0;
3165 }
3166
3167 int get_ctty_devnr(pid_t pid, dev_t *d) {
3168         int k;
3169         char line[LINE_MAX], *p, *fn;
3170         unsigned long ttynr;
3171         FILE *f;
3172
3173         if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3174                 return -ENOMEM;
3175
3176         f = fopen(fn, "re");
3177         free(fn);
3178         if (!f)
3179                 return -errno;
3180
3181         if (!fgets(line, sizeof(line), f)) {
3182                 k = feof(f) ? -EIO : -errno;
3183                 fclose(f);
3184                 return k;
3185         }
3186
3187         fclose(f);
3188
3189         p = strrchr(line, ')');
3190         if (!p)
3191                 return -EIO;
3192
3193         p++;
3194
3195         if (sscanf(p, " "
3196                    "%*c "  /* state */
3197                    "%*d "  /* ppid */
3198                    "%*d "  /* pgrp */
3199                    "%*d "  /* session */
3200                    "%lu ", /* ttynr */
3201                    &ttynr) != 1)
3202                 return -EIO;
3203
3204         *d = (dev_t) ttynr;
3205         return 0;
3206 }
3207
3208 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3209         int k;
3210         char fn[PATH_MAX], *s, *b, *p;
3211         dev_t devnr;
3212
3213         assert(r);
3214
3215         k = get_ctty_devnr(pid, &devnr);
3216         if (k < 0)
3217                 return k;
3218
3219         snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3220         char_array_0(fn);
3221
3222         if ((k = readlink_malloc(fn, &s)) < 0) {
3223
3224                 if (k != -ENOENT)
3225                         return k;
3226
3227                 /* This is an ugly hack */
3228                 if (major(devnr) == 136) {
3229                         if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3230                                 return -ENOMEM;
3231
3232                         *r = b;
3233                         if (_devnr)
3234                                 *_devnr = devnr;
3235
3236                         return 0;
3237                 }
3238
3239                 /* Probably something like the ptys which have no
3240                  * symlink in /dev/char. Let's return something
3241                  * vaguely useful. */
3242
3243                 if (!(b = strdup(fn + 5)))
3244                         return -ENOMEM;
3245
3246                 *r = b;
3247                 if (_devnr)
3248                         *_devnr = devnr;
3249
3250                 return 0;
3251         }
3252
3253         if (startswith(s, "/dev/"))
3254                 p = s + 5;
3255         else if (startswith(s, "../"))
3256                 p = s + 3;
3257         else
3258                 p = s;
3259
3260         b = strdup(p);
3261         free(s);
3262
3263         if (!b)
3264                 return -ENOMEM;
3265
3266         *r = b;
3267         if (_devnr)
3268                 *_devnr = devnr;
3269
3270         return 0;
3271 }
3272
3273 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3274         DIR *d;
3275         int ret = 0;
3276
3277         assert(fd >= 0);
3278
3279         /* This returns the first error we run into, but nevertheless
3280          * tries to go on. This closes the passed fd. */
3281
3282         d = fdopendir(fd);
3283         if (!d) {
3284                 close_nointr_nofail(fd);
3285
3286                 return errno == ENOENT ? 0 : -errno;
3287         }
3288
3289         for (;;) {
3290                 struct dirent buf, *de;
3291                 bool is_dir, keep_around;
3292                 struct stat st;
3293                 int r;
3294
3295                 r = readdir_r(d, &buf, &de);
3296                 if (r != 0 && ret == 0) {
3297                         ret = -r;
3298                         break;
3299                 }
3300
3301                 if (!de)
3302                         break;
3303
3304                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3305                         continue;
3306
3307                 if (de->d_type == DT_UNKNOWN ||
3308                     honour_sticky ||
3309                     (de->d_type == DT_DIR && root_dev)) {
3310                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3311                                 if (ret == 0 && errno != ENOENT)
3312                                         ret = -errno;
3313                                 continue;
3314                         }
3315
3316                         is_dir = S_ISDIR(st.st_mode);
3317                         keep_around =
3318                                 honour_sticky &&
3319                                 (st.st_uid == 0 || st.st_uid == getuid()) &&
3320                                 (st.st_mode & S_ISVTX);
3321                 } else {
3322                         is_dir = de->d_type == DT_DIR;
3323                         keep_around = false;
3324                 }
3325
3326                 if (is_dir) {
3327                         int subdir_fd;
3328
3329                         /* if root_dev is set, remove subdirectories only, if device is same as dir */
3330                         if (root_dev && st.st_dev != root_dev->st_dev)
3331                                 continue;
3332
3333                         subdir_fd = openat(fd, de->d_name,
3334                                            O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3335                         if (subdir_fd < 0) {
3336                                 if (ret == 0 && errno != ENOENT)
3337                                         ret = -errno;
3338                                 continue;
3339                         }
3340
3341                         r = rm_rf_children(subdir_fd, only_dirs, honour_sticky, root_dev);
3342                         if (r < 0 && ret == 0)
3343                                 ret = r;
3344
3345                         if (!keep_around)
3346                                 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3347                                         if (ret == 0 && errno != ENOENT)
3348                                                 ret = -errno;
3349                                 }
3350
3351                 } else if (!only_dirs && !keep_around) {
3352
3353                         if (unlinkat(fd, de->d_name, 0) < 0) {
3354                                 if (ret == 0 && errno != ENOENT)
3355                                         ret = -errno;
3356                         }
3357                 }
3358         }
3359
3360         closedir(d);
3361
3362         return ret;
3363 }
3364
3365 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3366         struct statfs s;
3367
3368         assert(fd >= 0);
3369
3370         if (fstatfs(fd, &s) < 0) {
3371                 close_nointr_nofail(fd);
3372                 return -errno;
3373         }
3374
3375         /* We refuse to clean disk file systems with this call. This
3376          * is extra paranoia just to be sure we never ever remove
3377          * non-state data */
3378
3379         if (s.f_type != TMPFS_MAGIC &&
3380             s.f_type != RAMFS_MAGIC) {
3381                 log_error("Attempted to remove disk file system, and we can't allow that.");
3382                 close_nointr_nofail(fd);
3383                 return -EPERM;
3384         }
3385
3386         return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3387 }
3388
3389 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3390         int fd, r;
3391         struct statfs s;
3392
3393         assert(path);
3394
3395         /* We refuse to clean the root file system with this
3396          * call. This is extra paranoia to never cause a really
3397          * seriously broken system. */
3398         if (path_equal(path, "/")) {
3399                 log_error("Attempted to remove entire root file system, and we can't allow that.");
3400                 return -EPERM;
3401         }
3402
3403         fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3404         if (fd < 0) {
3405
3406                 if (errno != ENOTDIR)
3407                         return -errno;
3408
3409                 if (!dangerous) {
3410                         if (statfs(path, &s) < 0)
3411                                 return -errno;
3412
3413                         if (s.f_type != TMPFS_MAGIC &&
3414                             s.f_type != RAMFS_MAGIC) {
3415                                 log_error("Attempted to remove disk file system, and we can't allow that.");
3416                                 return -EPERM;
3417                         }
3418                 }
3419
3420                 if (delete_root && !only_dirs)
3421                         if (unlink(path) < 0 && errno != ENOENT)
3422                                 return -errno;
3423
3424                 return 0;
3425         }
3426
3427         if (!dangerous) {
3428                 if (fstatfs(fd, &s) < 0) {
3429                         close_nointr_nofail(fd);
3430                         return -errno;
3431                 }
3432
3433                 if (s.f_type != TMPFS_MAGIC &&
3434                     s.f_type != RAMFS_MAGIC) {
3435                         log_error("Attempted to remove disk file system, and we can't allow that.");
3436                         close_nointr_nofail(fd);
3437                         return -EPERM;
3438                 }
3439         }
3440
3441         r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3442         if (delete_root) {
3443
3444                 if (honour_sticky && file_is_priv_sticky(path) > 0)
3445                         return r;
3446
3447                 if (rmdir(path) < 0 && errno != ENOENT) {
3448                         if (r == 0)
3449                                 r = -errno;
3450                 }
3451         }
3452
3453         return r;
3454 }
3455
3456 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3457         return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3458 }
3459
3460 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3461         return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3462 }
3463
3464 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3465         assert(path);
3466
3467         /* Under the assumption that we are running privileged we
3468          * first change the access mode and only then hand out
3469          * ownership to avoid a window where access is too open. */
3470
3471         if (mode != (mode_t) -1)
3472                 if (chmod(path, mode) < 0)
3473                         return -errno;
3474
3475         if (uid != (uid_t) -1 || gid != (gid_t) -1)
3476                 if (chown(path, uid, gid) < 0)
3477                         return -errno;
3478
3479         return 0;
3480 }
3481
3482 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3483         assert(fd >= 0);
3484
3485         /* Under the assumption that we are running privileged we
3486          * first change the access mode and only then hand out
3487          * ownership to avoid a window where access is too open. */
3488
3489         if (fchmod(fd, mode) < 0)
3490                 return -errno;
3491
3492         if (fchown(fd, uid, gid) < 0)
3493                 return -errno;
3494
3495         return 0;
3496 }
3497
3498 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3499         cpu_set_t *r;
3500         unsigned n = 1024;
3501
3502         /* Allocates the cpuset in the right size */
3503
3504         for (;;) {
3505                 if (!(r = CPU_ALLOC(n)))
3506                         return NULL;
3507
3508                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3509                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3510
3511                         if (ncpus)
3512                                 *ncpus = n;
3513
3514                         return r;
3515                 }
3516
3517                 CPU_FREE(r);
3518
3519                 if (errno != EINVAL)
3520                         return NULL;
3521
3522                 n *= 2;
3523         }
3524 }
3525
3526 void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3527         char *s = NULL;
3528         static const char status_indent[] = "         "; /* "[" STATUS "] " */
3529         int fd = -1;
3530         struct iovec iovec[5];
3531         int n = 0;
3532
3533         assert(format);
3534
3535         /* This is independent of logging, as status messages are
3536          * optional and go exclusively to the console. */
3537
3538         if (vasprintf(&s, format, ap) < 0)
3539                 goto finish;
3540
3541         fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3542         if (fd < 0)
3543                 goto finish;
3544
3545         if (ellipse) {
3546                 char *e;
3547                 size_t emax, sl;
3548                 int c;
3549
3550                 c = fd_columns(fd);
3551                 if (c <= 0)
3552                         c = 80;
3553
3554                 sl = status ? strlen(status_indent) : 0;
3555
3556                 emax = c - sl - 1;
3557                 if (emax < 3)
3558                         emax = 3;
3559
3560                 e = ellipsize(s, emax, 75);
3561                 if (e) {
3562                         free(s);
3563                         s = e;
3564                 }
3565         }
3566
3567         zero(iovec);
3568
3569         if (status) {
3570                 if (!isempty(status)) {
3571                         IOVEC_SET_STRING(iovec[n++], "[");
3572                         IOVEC_SET_STRING(iovec[n++], status);
3573                         IOVEC_SET_STRING(iovec[n++], "] ");
3574                 } else
3575                         IOVEC_SET_STRING(iovec[n++], status_indent);
3576         }
3577
3578         IOVEC_SET_STRING(iovec[n++], s);
3579         IOVEC_SET_STRING(iovec[n++], "\n");
3580
3581         writev(fd, iovec, n);
3582
3583 finish:
3584         free(s);
3585
3586         if (fd >= 0)
3587                 close_nointr_nofail(fd);
3588 }
3589
3590 void status_printf(const char *status, bool ellipse, const char *format, ...) {
3591         va_list ap;
3592
3593         assert(format);
3594
3595         va_start(ap, format);
3596         status_vprintf(status, ellipse, format, ap);
3597         va_end(ap);
3598 }
3599
3600 void status_welcome(void) {
3601         char *pretty_name = NULL, *ansi_color = NULL;
3602         const char *const_pretty = NULL, *const_color = NULL;
3603         int r;
3604
3605         if ((r = parse_env_file("/etc/os-release", NEWLINE,
3606                                 "PRETTY_NAME", &pretty_name,
3607                                 "ANSI_COLOR", &ansi_color,
3608                                 NULL)) < 0) {
3609
3610                 if (r != -ENOENT)
3611                         log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3612         }
3613
3614         if (!pretty_name && !const_pretty)
3615                 const_pretty = "Linux";
3616
3617         if (!ansi_color && !const_color)
3618                 const_color = "1";
3619
3620         status_printf(NULL,
3621                       false,
3622                       "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3623                       const_color ? const_color : ansi_color,
3624                       const_pretty ? const_pretty : pretty_name);
3625
3626         free(ansi_color);
3627         free(pretty_name);
3628 }
3629
3630 char *replace_env(const char *format, char **env) {
3631         enum {
3632                 WORD,
3633                 CURLY,
3634                 VARIABLE
3635         } state = WORD;
3636
3637         const char *e, *word = format;
3638         char *r = NULL, *k;
3639
3640         assert(format);
3641
3642         for (e = format; *e; e ++) {
3643
3644                 switch (state) {
3645
3646                 case WORD:
3647                         if (*e == '$')
3648                                 state = CURLY;
3649                         break;
3650
3651                 case CURLY:
3652                         if (*e == '{') {
3653                                 if (!(k = strnappend(r, word, e-word-1)))
3654                                         goto fail;
3655
3656                                 free(r);
3657                                 r = k;
3658
3659                                 word = e-1;
3660                                 state = VARIABLE;
3661
3662                         } else if (*e == '$') {
3663                                 if (!(k = strnappend(r, word, e-word)))
3664                                         goto fail;
3665
3666                                 free(r);
3667                                 r = k;
3668
3669                                 word = e+1;
3670                                 state = WORD;
3671                         } else
3672                                 state = WORD;
3673                         break;
3674
3675                 case VARIABLE:
3676                         if (*e == '}') {
3677                                 const char *t;
3678
3679                                 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3680                                         t = "";
3681
3682                                 if (!(k = strappend(r, t)))
3683                                         goto fail;
3684
3685                                 free(r);
3686                                 r = k;
3687
3688                                 word = e+1;
3689                                 state = WORD;
3690                         }
3691                         break;
3692                 }
3693         }
3694
3695         if (!(k = strnappend(r, word, e-word)))
3696                 goto fail;
3697
3698         free(r);
3699         return k;
3700
3701 fail:
3702         free(r);
3703         return NULL;
3704 }
3705
3706 char **replace_env_argv(char **argv, char **env) {
3707         char **r, **i;
3708         unsigned k = 0, l = 0;
3709
3710         l = strv_length(argv);
3711
3712         if (!(r = new(char*, l+1)))
3713                 return NULL;
3714
3715         STRV_FOREACH(i, argv) {
3716
3717                 /* If $FOO appears as single word, replace it by the split up variable */
3718                 if ((*i)[0] == '$' && (*i)[1] != '{') {
3719                         char *e;
3720                         char **w, **m;
3721                         unsigned q;
3722
3723                         if ((e = strv_env_get(env, *i+1))) {
3724
3725                                 if (!(m = strv_split_quoted(e))) {
3726                                         r[k] = NULL;
3727                                         strv_free(r);
3728                                         return NULL;
3729                                 }
3730                         } else
3731                                 m = NULL;
3732
3733                         q = strv_length(m);
3734                         l = l + q - 1;
3735
3736                         if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3737                                 r[k] = NULL;
3738                                 strv_free(r);
3739                                 strv_free(m);
3740                                 return NULL;
3741                         }
3742
3743                         r = w;
3744                         if (m) {
3745                                 memcpy(r + k, m, q * sizeof(char*));
3746                                 free(m);
3747                         }
3748
3749                         k += q;
3750                         continue;
3751                 }
3752
3753                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3754                 if (!(r[k++] = replace_env(*i, env))) {
3755                         strv_free(r);
3756                         return NULL;
3757                 }
3758         }
3759
3760         r[k] = NULL;
3761         return r;
3762 }
3763
3764 int fd_columns(int fd) {
3765         struct winsize ws;
3766         zero(ws);
3767
3768         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3769                 return -errno;
3770
3771         if (ws.ws_col <= 0)
3772                 return -EIO;
3773
3774         return ws.ws_col;
3775 }
3776
3777 static unsigned columns_cached(bool cached) {
3778         static __thread int parsed_columns = 0, env_columns = -1;
3779         const char *e;
3780
3781         if (_likely_(parsed_columns > 0 && cached))
3782                 return parsed_columns;
3783
3784         if (_unlikely_(env_columns == -1)) {
3785                 e = getenv("COLUMNS");
3786                 if (e)
3787                         env_columns = atoi(e);
3788                 else
3789                         env_columns = 0;
3790         }
3791
3792         if (env_columns > 0) {
3793                 parsed_columns = env_columns;
3794                 return parsed_columns;
3795         }
3796
3797         if (parsed_columns <= 0 || !cached)
3798                 parsed_columns = fd_columns(STDOUT_FILENO);
3799
3800         if (parsed_columns <= 0)
3801                 parsed_columns = 80;
3802
3803         return parsed_columns;
3804 }
3805
3806 unsigned columns(void) {
3807         return columns_cached(true);
3808 }
3809
3810 unsigned columns_uncached(void) {
3811         return columns_cached(false);
3812 }
3813
3814 int fd_lines(int fd) {
3815         struct winsize ws;
3816         zero(ws);
3817
3818         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3819                 return -errno;
3820
3821         if (ws.ws_row <= 0)
3822                 return -EIO;
3823
3824         return ws.ws_row;
3825 }
3826
3827 unsigned lines(void) {
3828         static __thread int parsed_lines = 0;
3829         const char *e;
3830
3831         if (_likely_(parsed_lines > 0))
3832                 return parsed_lines;
3833
3834         e = getenv("LINES");
3835         if (e)
3836                 parsed_lines = atoi(e);
3837
3838         if (parsed_lines <= 0)
3839                 parsed_lines = fd_lines(STDOUT_FILENO);
3840
3841         if (parsed_lines <= 0)
3842                 parsed_lines = 25;
3843
3844         return parsed_lines;
3845 }
3846
3847 int running_in_chroot(void) {
3848         struct stat a, b;
3849
3850         zero(a);
3851         zero(b);
3852
3853         /* Only works as root */
3854
3855         if (stat("/proc/1/root", &a) < 0)
3856                 return -errno;
3857
3858         if (stat("/", &b) < 0)
3859                 return -errno;
3860
3861         return
3862                 a.st_dev != b.st_dev ||
3863                 a.st_ino != b.st_ino;
3864 }
3865
3866 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3867         size_t x;
3868         char *r;
3869
3870         assert(s);
3871         assert(percent <= 100);
3872         assert(new_length >= 3);
3873
3874         if (old_length <= 3 || old_length <= new_length)
3875                 return strndup(s, old_length);
3876
3877         r = new0(char, new_length+1);
3878         if (!r)
3879                 return r;
3880
3881         x = (new_length * percent) / 100;
3882
3883         if (x > new_length - 3)
3884                 x = new_length - 3;
3885
3886         memcpy(r, s, x);
3887         r[x] = '.';
3888         r[x+1] = '.';
3889         r[x+2] = '.';
3890         memcpy(r + x + 3,
3891                s + old_length - (new_length - x - 3),
3892                new_length - x - 3);
3893
3894         return r;
3895 }
3896
3897 char *ellipsize(const char *s, size_t length, unsigned percent) {
3898         return ellipsize_mem(s, strlen(s), length, percent);
3899 }
3900
3901 int touch(const char *path) {
3902         int fd;
3903
3904         assert(path);
3905
3906         if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3907                 return -errno;
3908
3909         close_nointr_nofail(fd);
3910         return 0;
3911 }
3912
3913 char *unquote(const char *s, const char* quotes) {
3914         size_t l;
3915         assert(s);
3916
3917         l = strlen(s);
3918         if (l < 2)
3919                 return strdup(s);
3920
3921         if (strchr(quotes, s[0]) && s[l-1] == s[0])
3922                 return strndup(s+1, l-2);
3923
3924         return strdup(s);
3925 }
3926
3927 char *normalize_env_assignment(const char *s) {
3928         char *name, *value, *p, *r;
3929
3930         p = strchr(s, '=');
3931
3932         if (!p) {
3933                 if (!(r = strdup(s)))
3934                         return NULL;
3935
3936                 return strstrip(r);
3937         }
3938
3939         if (!(name = strndup(s, p - s)))
3940                 return NULL;
3941
3942         if (!(p = strdup(p+1))) {
3943                 free(name);
3944                 return NULL;
3945         }
3946
3947         value = unquote(strstrip(p), QUOTES);
3948         free(p);
3949
3950         if (!value) {
3951                 free(name);
3952                 return NULL;
3953         }
3954
3955         if (asprintf(&r, "%s=%s", name, value) < 0)
3956                 r = NULL;
3957
3958         free(value);
3959         free(name);
3960
3961         return r;
3962 }
3963
3964 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3965         siginfo_t dummy;
3966
3967         assert(pid >= 1);
3968
3969         if (!status)
3970                 status = &dummy;
3971
3972         for (;;) {
3973                 zero(*status);
3974
3975                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3976
3977                         if (errno == EINTR)
3978                                 continue;
3979
3980                         return -errno;
3981                 }
3982
3983                 return 0;
3984         }
3985 }
3986
3987 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
3988         int r;
3989         siginfo_t status;
3990
3991         assert(name);
3992         assert(pid > 1);
3993
3994         if ((r = wait_for_terminate(pid, &status)) < 0) {
3995                 log_warning("Failed to wait for %s: %s", name, strerror(-r));
3996                 return r;
3997         }
3998
3999         if (status.si_code == CLD_EXITED) {
4000                 if (status.si_status != 0) {
4001                         log_warning("%s failed with error code %i.", name, status.si_status);
4002                         return status.si_status;
4003                 }
4004
4005                 log_debug("%s succeeded.", name);
4006                 return 0;
4007
4008         } else if (status.si_code == CLD_KILLED ||
4009                    status.si_code == CLD_DUMPED) {
4010
4011                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4012                 return -EPROTO;
4013         }
4014
4015         log_warning("%s failed due to unknown reason.", name);
4016         return -EPROTO;
4017
4018 }
4019
4020 _noreturn_ void freeze(void) {
4021
4022         /* Make sure nobody waits for us on a socket anymore */
4023         close_all_fds(NULL, 0);
4024
4025         sync();
4026
4027         for (;;)
4028                 pause();
4029 }
4030
4031 bool null_or_empty(struct stat *st) {
4032         assert(st);
4033
4034         if (S_ISREG(st->st_mode) && st->st_size <= 0)
4035                 return true;
4036
4037         if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4038                 return true;
4039
4040         return false;
4041 }
4042
4043 int null_or_empty_path(const char *fn) {
4044         struct stat st;
4045
4046         assert(fn);
4047
4048         if (stat(fn, &st) < 0)
4049                 return -errno;
4050
4051         return null_or_empty(&st);
4052 }
4053
4054 DIR *xopendirat(int fd, const char *name, int flags) {
4055         int nfd;
4056         DIR *d;
4057
4058         if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4059                 return NULL;
4060
4061         if (!(d = fdopendir(nfd))) {
4062                 close_nointr_nofail(nfd);
4063                 return NULL;
4064         }
4065
4066         return d;
4067 }
4068
4069 int signal_from_string_try_harder(const char *s) {
4070         int signo;
4071         assert(s);
4072
4073         if ((signo = signal_from_string(s)) <= 0)
4074                 if (startswith(s, "SIG"))
4075                         return signal_from_string(s+3);
4076
4077         return signo;
4078 }
4079
4080 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4081
4082         assert(f);
4083         assert(name);
4084         assert(t);
4085
4086         if (!dual_timestamp_is_set(t))
4087                 return;
4088
4089         fprintf(f, "%s=%llu %llu\n",
4090                 name,
4091                 (unsigned long long) t->realtime,
4092                 (unsigned long long) t->monotonic);
4093 }
4094
4095 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4096         unsigned long long a, b;
4097
4098         assert(value);
4099         assert(t);
4100
4101         if (sscanf(value, "%lli %llu", &a, &b) != 2)
4102                 log_debug("Failed to parse finish timestamp value %s", value);
4103         else {
4104                 t->realtime = a;
4105                 t->monotonic = b;
4106         }
4107 }
4108
4109 char *fstab_node_to_udev_node(const char *p) {
4110         char *dn, *t, *u;
4111         int r;
4112
4113         /* FIXME: to follow udev's logic 100% we need to leave valid
4114          * UTF8 chars unescaped */
4115
4116         if (startswith(p, "LABEL=")) {
4117
4118                 if (!(u = unquote(p+6, "\"\'")))
4119                         return NULL;
4120
4121                 t = xescape(u, "/ ");
4122                 free(u);
4123
4124                 if (!t)
4125                         return NULL;
4126
4127                 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4128                 free(t);
4129
4130                 if (r < 0)
4131                         return NULL;
4132
4133                 return dn;
4134         }
4135
4136         if (startswith(p, "UUID=")) {
4137
4138                 if (!(u = unquote(p+5, "\"\'")))
4139                         return NULL;
4140
4141                 t = xescape(u, "/ ");
4142                 free(u);
4143
4144                 if (!t)
4145                         return NULL;
4146
4147                 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4148                 free(t);
4149
4150                 if (r < 0)
4151                         return NULL;
4152
4153                 return dn;
4154         }
4155
4156         return strdup(p);
4157 }
4158
4159 bool tty_is_vc(const char *tty) {
4160         assert(tty);
4161
4162         if (startswith(tty, "/dev/"))
4163                 tty += 5;
4164
4165         return vtnr_from_tty(tty) >= 0;
4166 }
4167
4168 bool tty_is_console(const char *tty) {
4169         assert(tty);
4170
4171         if (startswith(tty, "/dev/"))
4172                 tty += 5;
4173
4174         return streq(tty, "console");
4175 }
4176
4177 int vtnr_from_tty(const char *tty) {
4178         int i, r;
4179
4180         assert(tty);
4181
4182         if (startswith(tty, "/dev/"))
4183                 tty += 5;
4184
4185         if (!startswith(tty, "tty") )
4186                 return -EINVAL;
4187
4188         if (tty[3] < '0' || tty[3] > '9')
4189                 return -EINVAL;
4190
4191         r = safe_atoi(tty+3, &i);
4192         if (r < 0)
4193                 return r;
4194
4195         if (i < 0 || i > 63)
4196                 return -EINVAL;
4197
4198         return i;
4199 }
4200
4201 bool tty_is_vc_resolve(const char *tty) {
4202         char *active = NULL;
4203         bool b;
4204
4205         assert(tty);
4206
4207         if (startswith(tty, "/dev/"))
4208                 tty += 5;
4209
4210         /* Resolve where /dev/console is pointing to, if /sys is
4211          * actually ours (i.e. not read-only-mounted which is a sign
4212          * for container setups) */
4213         if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4214                 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4215                         /* If multiple log outputs are configured the
4216                          * last one is what /dev/console points to */
4217                         tty = strrchr(active, ' ');
4218                         if (tty)
4219                                 tty++;
4220                         else
4221                                 tty = active;
4222                 }
4223
4224         b = tty_is_vc(tty);
4225         free(active);
4226
4227         return b;
4228 }
4229
4230 const char *default_term_for_tty(const char *tty) {
4231         assert(tty);
4232
4233         return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4234 }
4235
4236 bool dirent_is_file(const struct dirent *de) {
4237         assert(de);
4238
4239         if (ignore_file(de->d_name))
4240                 return false;
4241
4242         if (de->d_type != DT_REG &&
4243             de->d_type != DT_LNK &&
4244             de->d_type != DT_UNKNOWN)
4245                 return false;
4246
4247         return true;
4248 }
4249
4250 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4251         assert(de);
4252
4253         if (!dirent_is_file(de))
4254                 return false;
4255
4256         return endswith(de->d_name, suffix);
4257 }
4258
4259 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4260         DIR *_d = NULL;
4261         struct dirent *de;
4262         Hashmap *pids = NULL;
4263
4264         assert(directory);
4265
4266         /* Executes all binaries in a directory in parallel and waits
4267          * until all they all finished. */
4268
4269         if (!d) {
4270                 if (!(_d = opendir(directory))) {
4271
4272                         if (errno == ENOENT)
4273                                 return;
4274
4275                         log_error("Failed to enumerate directory %s: %m", directory);
4276                         return;
4277                 }
4278
4279                 d = _d;
4280         }
4281
4282         if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4283                 log_error("Failed to allocate set.");
4284                 goto finish;
4285         }
4286
4287         while ((de = readdir(d))) {
4288                 char *path;
4289                 pid_t pid;
4290                 int k;
4291
4292                 if (!dirent_is_file(de))
4293                         continue;
4294
4295                 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4296                         log_oom();
4297                         continue;
4298                 }
4299
4300                 if ((pid = fork()) < 0) {
4301                         log_error("Failed to fork: %m");
4302                         free(path);
4303                         continue;
4304                 }
4305
4306                 if (pid == 0) {
4307                         char *_argv[2];
4308                         /* Child */
4309
4310                         if (!argv) {
4311                                 _argv[0] = path;
4312                                 _argv[1] = NULL;
4313                                 argv = _argv;
4314                         } else
4315                                 argv[0] = path;
4316
4317                         execv(path, argv);
4318
4319                         log_error("Failed to execute %s: %m", path);
4320                         _exit(EXIT_FAILURE);
4321                 }
4322
4323                 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4324
4325                 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4326                         log_error("Failed to add PID to set: %s", strerror(-k));
4327                         free(path);
4328                 }
4329         }
4330
4331         while (!hashmap_isempty(pids)) {
4332                 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4333                 siginfo_t si;
4334                 char *path;
4335
4336                 zero(si);
4337                 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4338
4339                         if (errno == EINTR)
4340                                 continue;
4341
4342                         log_error("waitid() failed: %m");
4343                         goto finish;
4344                 }
4345
4346                 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4347                         if (!is_clean_exit(si.si_code, si.si_status)) {
4348                                 if (si.si_code == CLD_EXITED)
4349                                         log_error("%s exited with exit status %i.", path, si.si_status);
4350                                 else
4351                                         log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4352                         } else
4353                                 log_debug("%s exited successfully.", path);
4354
4355                         free(path);
4356                 }
4357         }
4358
4359 finish:
4360         if (_d)
4361                 closedir(_d);
4362
4363         if (pids)
4364                 hashmap_free_free(pids);
4365 }
4366
4367 int kill_and_sigcont(pid_t pid, int sig) {
4368         int r;
4369
4370         r = kill(pid, sig) < 0 ? -errno : 0;
4371
4372         if (r >= 0)
4373                 kill(pid, SIGCONT);
4374
4375         return r;
4376 }
4377
4378 bool nulstr_contains(const char*nulstr, const char *needle) {
4379         const char *i;
4380
4381         if (!nulstr)
4382                 return false;
4383
4384         NULSTR_FOREACH(i, nulstr)
4385                 if (streq(i, needle))
4386                         return true;
4387
4388         return false;
4389 }
4390
4391 bool plymouth_running(void) {
4392         return access("/run/plymouth/pid", F_OK) >= 0;
4393 }
4394
4395 void parse_syslog_priority(char **p, int *priority) {
4396         int a = 0, b = 0, c = 0;
4397         int k;
4398
4399         assert(p);
4400         assert(*p);
4401         assert(priority);
4402
4403         if ((*p)[0] != '<')
4404                 return;
4405
4406         if (!strchr(*p, '>'))
4407                 return;
4408
4409         if ((*p)[2] == '>') {
4410                 c = undecchar((*p)[1]);
4411                 k = 3;
4412         } else if ((*p)[3] == '>') {
4413                 b = undecchar((*p)[1]);
4414                 c = undecchar((*p)[2]);
4415                 k = 4;
4416         } else if ((*p)[4] == '>') {
4417                 a = undecchar((*p)[1]);
4418                 b = undecchar((*p)[2]);
4419                 c = undecchar((*p)[3]);
4420                 k = 5;
4421         } else
4422                 return;
4423
4424         if (a < 0 || b < 0 || c < 0)
4425                 return;
4426
4427         *priority = a*100+b*10+c;
4428         *p += k;
4429 }
4430
4431 void skip_syslog_pid(char **buf) {
4432         char *p;
4433
4434         assert(buf);
4435         assert(*buf);
4436
4437         p = *buf;
4438
4439         if (*p != '[')
4440                 return;
4441
4442         p++;
4443         p += strspn(p, "0123456789");
4444
4445         if (*p != ']')
4446                 return;
4447
4448         p++;
4449
4450         *buf = p;
4451 }
4452
4453 void skip_syslog_date(char **buf) {
4454         enum {
4455                 LETTER,
4456                 SPACE,
4457                 NUMBER,
4458                 SPACE_OR_NUMBER,
4459                 COLON
4460         } sequence[] = {
4461                 LETTER, LETTER, LETTER,
4462                 SPACE,
4463                 SPACE_OR_NUMBER, NUMBER,
4464                 SPACE,
4465                 SPACE_OR_NUMBER, NUMBER,
4466                 COLON,
4467                 SPACE_OR_NUMBER, NUMBER,
4468                 COLON,
4469                 SPACE_OR_NUMBER, NUMBER,
4470                 SPACE
4471         };
4472
4473         char *p;
4474         unsigned i;
4475
4476         assert(buf);
4477         assert(*buf);
4478
4479         p = *buf;
4480
4481         for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
4482
4483                 if (!*p)
4484                         return;
4485
4486                 switch (sequence[i]) {
4487
4488                 case SPACE:
4489                         if (*p != ' ')
4490                                 return;
4491                         break;
4492
4493                 case SPACE_OR_NUMBER:
4494                         if (*p == ' ')
4495                                 break;
4496
4497                         /* fall through */
4498
4499                 case NUMBER:
4500                         if (*p < '0' || *p > '9')
4501                                 return;
4502
4503                         break;
4504
4505                 case LETTER:
4506                         if (!(*p >= 'A' && *p <= 'Z') &&
4507                             !(*p >= 'a' && *p <= 'z'))
4508                                 return;
4509
4510                         break;
4511
4512                 case COLON:
4513                         if (*p != ':')
4514                                 return;
4515                         break;
4516
4517                 }
4518         }
4519
4520         *buf = p;
4521 }
4522
4523 char* strshorten(char *s, size_t l) {
4524         assert(s);
4525
4526         if (l < strlen(s))
4527                 s[l] = 0;
4528
4529         return s;
4530 }
4531
4532 static bool hostname_valid_char(char c) {
4533         return
4534                 (c >= 'a' && c <= 'z') ||
4535                 (c >= 'A' && c <= 'Z') ||
4536                 (c >= '0' && c <= '9') ||
4537                 c == '-' ||
4538                 c == '_' ||
4539                 c == '.';
4540 }
4541
4542 bool hostname_is_valid(const char *s) {
4543         const char *p;
4544
4545         if (isempty(s))
4546                 return false;
4547
4548         for (p = s; *p; p++)
4549                 if (!hostname_valid_char(*p))
4550                         return false;
4551
4552         if (p-s > HOST_NAME_MAX)
4553                 return false;
4554
4555         return true;
4556 }
4557
4558 char* hostname_cleanup(char *s) {
4559         char *p, *d;
4560
4561         for (p = s, d = s; *p; p++)
4562                 if ((*p >= 'a' && *p <= 'z') ||
4563                     (*p >= 'A' && *p <= 'Z') ||
4564                     (*p >= '0' && *p <= '9') ||
4565                     *p == '-' ||
4566                     *p == '_' ||
4567                     *p == '.')
4568                         *(d++) = *p;
4569
4570         *d = 0;
4571
4572         strshorten(s, HOST_NAME_MAX);
4573         return s;
4574 }
4575
4576 int pipe_eof(int fd) {
4577         struct pollfd pollfd;
4578         int r;
4579
4580         zero(pollfd);
4581         pollfd.fd = fd;
4582         pollfd.events = POLLIN|POLLHUP;
4583
4584         r = poll(&pollfd, 1, 0);
4585         if (r < 0)
4586                 return -errno;
4587
4588         if (r == 0)
4589                 return 0;
4590
4591         return pollfd.revents & POLLHUP;
4592 }
4593
4594 int fd_wait_for_event(int fd, int event, usec_t t) {
4595         struct pollfd pollfd;
4596         int r;
4597
4598         zero(pollfd);
4599         pollfd.fd = fd;
4600         pollfd.events = event;
4601
4602         r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4603         if (r < 0)
4604                 return -errno;
4605
4606         if (r == 0)
4607                 return 0;
4608
4609         return pollfd.revents;
4610 }
4611
4612 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4613         FILE *f;
4614         char *t;
4615         const char *fn;
4616         size_t k;
4617         int fd;
4618
4619         assert(path);
4620         assert(_f);
4621         assert(_temp_path);
4622
4623         t = new(char, strlen(path) + 1 + 6 + 1);
4624         if (!t)
4625                 return -ENOMEM;
4626
4627         fn = path_get_file_name(path);
4628         k = fn-path;
4629         memcpy(t, path, k);
4630         t[k] = '.';
4631         stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4632
4633         fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4634         if (fd < 0) {
4635                 free(t);
4636                 return -errno;
4637         }
4638
4639         f = fdopen(fd, "we");
4640         if (!f) {
4641                 unlink(t);
4642                 free(t);
4643                 return -errno;
4644         }
4645
4646         *_f = f;
4647         *_temp_path = t;
4648
4649         return 0;
4650 }
4651
4652 int terminal_vhangup_fd(int fd) {
4653         assert(fd >= 0);
4654
4655         if (ioctl(fd, TIOCVHANGUP) < 0)
4656                 return -errno;
4657
4658         return 0;
4659 }
4660
4661 int terminal_vhangup(const char *name) {
4662         int fd, r;
4663
4664         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4665         if (fd < 0)
4666                 return fd;
4667
4668         r = terminal_vhangup_fd(fd);
4669         close_nointr_nofail(fd);
4670
4671         return r;
4672 }
4673
4674 int vt_disallocate(const char *name) {
4675         int fd, r;
4676         unsigned u;
4677
4678         /* Deallocate the VT if possible. If not possible
4679          * (i.e. because it is the active one), at least clear it
4680          * entirely (including the scrollback buffer) */
4681
4682         if (!startswith(name, "/dev/"))
4683                 return -EINVAL;
4684
4685         if (!tty_is_vc(name)) {
4686                 /* So this is not a VT. I guess we cannot deallocate
4687                  * it then. But let's at least clear the screen */
4688
4689                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4690                 if (fd < 0)
4691                         return fd;
4692
4693                 loop_write(fd,
4694                            "\033[r"    /* clear scrolling region */
4695                            "\033[H"    /* move home */
4696                            "\033[2J",  /* clear screen */
4697                            10, false);
4698                 close_nointr_nofail(fd);
4699
4700                 return 0;
4701         }
4702
4703         if (!startswith(name, "/dev/tty"))
4704                 return -EINVAL;
4705
4706         r = safe_atou(name+8, &u);
4707         if (r < 0)
4708                 return r;
4709
4710         if (u <= 0)
4711                 return -EINVAL;
4712
4713         /* Try to deallocate */
4714         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4715         if (fd < 0)
4716                 return fd;
4717
4718         r = ioctl(fd, VT_DISALLOCATE, u);
4719         close_nointr_nofail(fd);
4720
4721         if (r >= 0)
4722                 return 0;
4723
4724         if (errno != EBUSY)
4725                 return -errno;
4726
4727         /* Couldn't deallocate, so let's clear it fully with
4728          * scrollback */
4729         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4730         if (fd < 0)
4731                 return fd;
4732
4733         loop_write(fd,
4734                    "\033[r"   /* clear scrolling region */
4735                    "\033[H"   /* move home */
4736                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4737                    10, false);
4738         close_nointr_nofail(fd);
4739
4740         return 0;
4741 }
4742
4743 int copy_file(const char *from, const char *to) {
4744         int r, fdf, fdt;
4745
4746         assert(from);
4747         assert(to);
4748
4749         fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4750         if (fdf < 0)
4751                 return -errno;
4752
4753         fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4754         if (fdt < 0) {
4755                 close_nointr_nofail(fdf);
4756                 return -errno;
4757         }
4758
4759         for (;;) {
4760                 char buf[PIPE_BUF];
4761                 ssize_t n, k;
4762
4763                 n = read(fdf, buf, sizeof(buf));
4764                 if (n < 0) {
4765                         r = -errno;
4766
4767                         close_nointr_nofail(fdf);
4768                         close_nointr(fdt);
4769                         unlink(to);
4770
4771                         return r;
4772                 }
4773
4774                 if (n == 0)
4775                         break;
4776
4777                 errno = 0;
4778                 k = loop_write(fdt, buf, n, false);
4779                 if (n != k) {
4780                         r = k < 0 ? k : (errno ? -errno : -EIO);
4781
4782                         close_nointr_nofail(fdf);
4783                         close_nointr(fdt);
4784
4785                         unlink(to);
4786                         return r;
4787                 }
4788         }
4789
4790         close_nointr_nofail(fdf);
4791         r = close_nointr(fdt);
4792
4793         if (r < 0) {
4794                 unlink(to);
4795                 return r;
4796         }
4797
4798         return 0;
4799 }
4800
4801 int symlink_or_copy(const char *from, const char *to) {
4802         char *pf = NULL, *pt = NULL;
4803         struct stat a, b;
4804         int r;
4805
4806         assert(from);
4807         assert(to);
4808
4809         if (path_get_parent(from, &pf) < 0 ||
4810             path_get_parent(to, &pt) < 0) {
4811                 r = -ENOMEM;
4812                 goto finish;
4813         }
4814
4815         if (stat(pf, &a) < 0 ||
4816             stat(pt, &b) < 0) {
4817                 r = -errno;
4818                 goto finish;
4819         }
4820
4821         if (a.st_dev != b.st_dev) {
4822                 free(pf);
4823                 free(pt);
4824
4825                 return copy_file(from, to);
4826         }
4827
4828         if (symlink(from, to) < 0) {
4829                 r = -errno;
4830                 goto finish;
4831         }
4832
4833         r = 0;
4834
4835 finish:
4836         free(pf);
4837         free(pt);
4838
4839         return r;
4840 }
4841
4842 int symlink_or_copy_atomic(const char *from, const char *to) {
4843         char *t, *x;
4844         const char *fn;
4845         size_t k;
4846         unsigned long long ull;
4847         unsigned i;
4848         int r;
4849
4850         assert(from);
4851         assert(to);
4852
4853         t = new(char, strlen(to) + 1 + 16 + 1);
4854         if (!t)
4855                 return -ENOMEM;
4856
4857         fn = path_get_file_name(to);
4858         k = fn-to;
4859         memcpy(t, to, k);
4860         t[k] = '.';
4861         x = stpcpy(t+k+1, fn);
4862
4863         ull = random_ull();
4864         for (i = 0; i < 16; i++) {
4865                 *(x++) = hexchar(ull & 0xF);
4866                 ull >>= 4;
4867         }
4868
4869         *x = 0;
4870
4871         r = symlink_or_copy(from, t);
4872         if (r < 0) {
4873                 unlink(t);
4874                 free(t);
4875                 return r;
4876         }
4877
4878         if (rename(t, to) < 0) {
4879                 r = -errno;
4880                 unlink(t);
4881                 free(t);
4882                 return r;
4883         }
4884
4885         free(t);
4886         return r;
4887 }
4888
4889 bool display_is_local(const char *display) {
4890         assert(display);
4891
4892         return
4893                 display[0] == ':' &&
4894                 display[1] >= '0' &&
4895                 display[1] <= '9';
4896 }
4897
4898 int socket_from_display(const char *display, char **path) {
4899         size_t k;
4900         char *f, *c;
4901
4902         assert(display);
4903         assert(path);
4904
4905         if (!display_is_local(display))
4906                 return -EINVAL;
4907
4908         k = strspn(display+1, "0123456789");
4909
4910         f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4911         if (!f)
4912                 return -ENOMEM;
4913
4914         c = stpcpy(f, "/tmp/.X11-unix/X");
4915         memcpy(c, display+1, k);
4916         c[k] = 0;
4917
4918         *path = f;
4919
4920         return 0;
4921 }
4922
4923 int get_user_creds(
4924                 const char **username,
4925                 uid_t *uid, gid_t *gid,
4926                 const char **home,
4927                 const char **shell) {
4928
4929         struct passwd *p;
4930         uid_t u;
4931
4932         assert(username);
4933         assert(*username);
4934
4935         /* We enforce some special rules for uid=0: in order to avoid
4936          * NSS lookups for root we hardcode its data. */
4937
4938         if (streq(*username, "root") || streq(*username, "0")) {
4939                 *username = "root";
4940
4941                 if (uid)
4942                         *uid = 0;
4943
4944                 if (gid)
4945                         *gid = 0;
4946
4947                 if (home)
4948                         *home = "/root";
4949
4950                 if (shell)
4951                         *shell = "/bin/sh";
4952
4953                 return 0;
4954         }
4955
4956         if (parse_uid(*username, &u) >= 0) {
4957                 errno = 0;
4958                 p = getpwuid(u);
4959
4960                 /* If there are multiple users with the same id, make
4961                  * sure to leave $USER to the configured value instead
4962                  * of the first occurrence in the database. However if
4963                  * the uid was configured by a numeric uid, then let's
4964                  * pick the real username from /etc/passwd. */
4965                 if (p)
4966                         *username = p->pw_name;
4967         } else {
4968                 errno = 0;
4969                 p = getpwnam(*username);
4970         }
4971
4972         if (!p)
4973                 return errno != 0 ? -errno : -ESRCH;
4974
4975         if (uid)
4976                 *uid = p->pw_uid;
4977
4978         if (gid)
4979                 *gid = p->pw_gid;
4980
4981         if (home)
4982                 *home = p->pw_dir;
4983
4984         if (shell)
4985                 *shell = p->pw_shell;
4986
4987         return 0;
4988 }
4989
4990 int get_group_creds(const char **groupname, gid_t *gid) {
4991         struct group *g;
4992         gid_t id;
4993
4994         assert(groupname);
4995
4996         /* We enforce some special rules for gid=0: in order to avoid
4997          * NSS lookups for root we hardcode its data. */
4998
4999         if (streq(*groupname, "root") || streq(*groupname, "0")) {
5000                 *groupname = "root";
5001
5002                 if (gid)
5003                         *gid = 0;
5004
5005                 return 0;
5006         }
5007
5008         if (parse_gid(*groupname, &id) >= 0) {
5009                 errno = 0;
5010                 g = getgrgid(id);
5011
5012                 if (g)
5013                         *groupname = g->gr_name;
5014         } else {
5015                 errno = 0;
5016                 g = getgrnam(*groupname);
5017         }
5018
5019         if (!g)
5020                 return errno != 0 ? -errno : -ESRCH;
5021
5022         if (gid)
5023                 *gid = g->gr_gid;
5024
5025         return 0;
5026 }
5027
5028 int in_group(const char *name) {
5029         gid_t gid, *gids;
5030         int ngroups_max, r, i;
5031
5032         r = get_group_creds(&name, &gid);
5033         if (r < 0)
5034                 return r;
5035
5036         if (getgid() == gid)
5037                 return 1;
5038
5039         if (getegid() == gid)
5040                 return 1;
5041
5042         ngroups_max = sysconf(_SC_NGROUPS_MAX);
5043         assert(ngroups_max > 0);
5044
5045         gids = alloca(sizeof(gid_t) * ngroups_max);
5046
5047         r = getgroups(ngroups_max, gids);
5048         if (r < 0)
5049                 return -errno;
5050
5051         for (i = 0; i < r; i++)
5052                 if (gids[i] == gid)
5053                         return 1;
5054
5055         return 0;
5056 }
5057
5058 int glob_exists(const char *path) {
5059         glob_t g;
5060         int r, k;
5061
5062         assert(path);
5063
5064         zero(g);
5065         errno = 0;
5066         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5067
5068         if (k == GLOB_NOMATCH)
5069                 r = 0;
5070         else if (k == GLOB_NOSPACE)
5071                 r = -ENOMEM;
5072         else if (k == 0)
5073                 r = !strv_isempty(g.gl_pathv);
5074         else
5075                 r = errno ? -errno : -EIO;
5076
5077         globfree(&g);
5078
5079         return r;
5080 }
5081
5082 int dirent_ensure_type(DIR *d, struct dirent *de) {
5083         struct stat st;
5084
5085         assert(d);
5086         assert(de);
5087
5088         if (de->d_type != DT_UNKNOWN)
5089                 return 0;
5090
5091         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5092                 return -errno;
5093
5094         de->d_type =
5095                 S_ISREG(st.st_mode)  ? DT_REG  :
5096                 S_ISDIR(st.st_mode)  ? DT_DIR  :
5097                 S_ISLNK(st.st_mode)  ? DT_LNK  :
5098                 S_ISFIFO(st.st_mode) ? DT_FIFO :
5099                 S_ISSOCK(st.st_mode) ? DT_SOCK :
5100                 S_ISCHR(st.st_mode)  ? DT_CHR  :
5101                 S_ISBLK(st.st_mode)  ? DT_BLK  :
5102                                        DT_UNKNOWN;
5103
5104         return 0;
5105 }
5106
5107 int in_search_path(const char *path, char **search) {
5108         char **i, *parent;
5109         int r;
5110
5111         r = path_get_parent(path, &parent);
5112         if (r < 0)
5113                 return r;
5114
5115         r = 0;
5116
5117         STRV_FOREACH(i, search) {
5118                 if (path_equal(parent, *i)) {
5119                         r = 1;
5120                         break;
5121                 }
5122         }
5123
5124         free(parent);
5125
5126         return r;
5127 }
5128
5129 int get_files_in_directory(const char *path, char ***list) {
5130         DIR *d;
5131         int r = 0;
5132         unsigned n = 0;
5133         char **l = NULL;
5134
5135         assert(path);
5136
5137         /* Returns all files in a directory in *list, and the number
5138          * of files as return value. If list is NULL returns only the
5139          * number */
5140
5141         d = opendir(path);
5142         if (!d)
5143                 return -errno;
5144
5145         for (;;) {
5146                 struct dirent buffer, *de;
5147                 int k;
5148
5149                 k = readdir_r(d, &buffer, &de);
5150                 if (k != 0) {
5151                         r = -k;
5152                         goto finish;
5153                 }
5154
5155                 if (!de)
5156                         break;
5157
5158                 dirent_ensure_type(d, de);
5159
5160                 if (!dirent_is_file(de))
5161                         continue;
5162
5163                 if (list) {
5164                         if ((unsigned) r >= n) {
5165                                 char **t;
5166
5167                                 n = MAX(16, 2*r);
5168                                 t = realloc(l, sizeof(char*) * n);
5169                                 if (!t) {
5170                                         r = -ENOMEM;
5171                                         goto finish;
5172                                 }
5173
5174                                 l = t;
5175                         }
5176
5177                         assert((unsigned) r < n);
5178
5179                         l[r] = strdup(de->d_name);
5180                         if (!l[r]) {
5181                                 r = -ENOMEM;
5182                                 goto finish;
5183                         }
5184
5185                         l[++r] = NULL;
5186                 } else
5187                         r++;
5188         }
5189
5190 finish:
5191         if (d)
5192                 closedir(d);
5193
5194         if (r >= 0) {
5195                 if (list)
5196                         *list = l;
5197         } else
5198                 strv_free(l);
5199
5200         return r;
5201 }
5202
5203 char *strjoin(const char *x, ...) {
5204         va_list ap;
5205         size_t l;
5206         char *r, *p;
5207
5208         va_start(ap, x);
5209
5210         if (x) {
5211                 l = strlen(x);
5212
5213                 for (;;) {
5214                         const char *t;
5215
5216                         t = va_arg(ap, const char *);
5217                         if (!t)
5218                                 break;
5219
5220                         l += strlen(t);
5221                 }
5222         } else
5223                 l = 0;
5224
5225         va_end(ap);
5226
5227         r = new(char, l+1);
5228         if (!r)
5229                 return NULL;
5230
5231         if (x) {
5232                 p = stpcpy(r, x);
5233
5234                 va_start(ap, x);
5235
5236                 for (;;) {
5237                         const char *t;
5238
5239                         t = va_arg(ap, const char *);
5240                         if (!t)
5241                                 break;
5242
5243                         p = stpcpy(p, t);
5244                 }
5245
5246                 va_end(ap);
5247         } else
5248                 r[0] = 0;
5249
5250         return r;
5251 }
5252
5253 bool is_main_thread(void) {
5254         static __thread int cached = 0;
5255
5256         if (_unlikely_(cached == 0))
5257                 cached = getpid() == gettid() ? 1 : -1;
5258
5259         return cached > 0;
5260 }
5261
5262 int block_get_whole_disk(dev_t d, dev_t *ret) {
5263         char *p, *s;
5264         int r;
5265         unsigned n, m;
5266
5267         assert(ret);
5268
5269         /* If it has a queue this is good enough for us */
5270         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5271                 return -ENOMEM;
5272
5273         r = access(p, F_OK);
5274         free(p);
5275
5276         if (r >= 0) {
5277                 *ret = d;
5278                 return 0;
5279         }
5280
5281         /* If it is a partition find the originating device */
5282         if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5283                 return -ENOMEM;
5284
5285         r = access(p, F_OK);
5286         free(p);
5287
5288         if (r < 0)
5289                 return -ENOENT;
5290
5291         /* Get parent dev_t */
5292         if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5293                 return -ENOMEM;
5294
5295         r = read_one_line_file(p, &s);
5296         free(p);
5297
5298         if (r < 0)
5299                 return r;
5300
5301         r = sscanf(s, "%u:%u", &m, &n);
5302         free(s);
5303
5304         if (r != 2)
5305                 return -EINVAL;
5306
5307         /* Only return this if it is really good enough for us. */
5308         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5309                 return -ENOMEM;
5310
5311         r = access(p, F_OK);
5312         free(p);
5313
5314         if (r >= 0) {
5315                 *ret = makedev(m, n);
5316                 return 0;
5317         }
5318
5319         return -ENOENT;
5320 }
5321
5322 int file_is_priv_sticky(const char *p) {
5323         struct stat st;
5324
5325         assert(p);
5326
5327         if (lstat(p, &st) < 0)
5328                 return -errno;
5329
5330         return
5331                 (st.st_uid == 0 || st.st_uid == getuid()) &&
5332                 (st.st_mode & S_ISVTX);
5333 }
5334
5335 static const char *const ioprio_class_table[] = {
5336         [IOPRIO_CLASS_NONE] = "none",
5337         [IOPRIO_CLASS_RT] = "realtime",
5338         [IOPRIO_CLASS_BE] = "best-effort",
5339         [IOPRIO_CLASS_IDLE] = "idle"
5340 };
5341
5342 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5343
5344 static const char *const sigchld_code_table[] = {
5345         [CLD_EXITED] = "exited",
5346         [CLD_KILLED] = "killed",
5347         [CLD_DUMPED] = "dumped",
5348         [CLD_TRAPPED] = "trapped",
5349         [CLD_STOPPED] = "stopped",
5350         [CLD_CONTINUED] = "continued",
5351 };
5352
5353 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5354
5355 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5356         [LOG_FAC(LOG_KERN)] = "kern",
5357         [LOG_FAC(LOG_USER)] = "user",
5358         [LOG_FAC(LOG_MAIL)] = "mail",
5359         [LOG_FAC(LOG_DAEMON)] = "daemon",
5360         [LOG_FAC(LOG_AUTH)] = "auth",
5361         [LOG_FAC(LOG_SYSLOG)] = "syslog",
5362         [LOG_FAC(LOG_LPR)] = "lpr",
5363         [LOG_FAC(LOG_NEWS)] = "news",
5364         [LOG_FAC(LOG_UUCP)] = "uucp",
5365         [LOG_FAC(LOG_CRON)] = "cron",
5366         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5367         [LOG_FAC(LOG_FTP)] = "ftp",
5368         [LOG_FAC(LOG_LOCAL0)] = "local0",
5369         [LOG_FAC(LOG_LOCAL1)] = "local1",
5370         [LOG_FAC(LOG_LOCAL2)] = "local2",
5371         [LOG_FAC(LOG_LOCAL3)] = "local3",
5372         [LOG_FAC(LOG_LOCAL4)] = "local4",
5373         [LOG_FAC(LOG_LOCAL5)] = "local5",
5374         [LOG_FAC(LOG_LOCAL6)] = "local6",
5375         [LOG_FAC(LOG_LOCAL7)] = "local7"
5376 };
5377
5378 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5379
5380 static const char *const log_level_table[] = {
5381         [LOG_EMERG] = "emerg",
5382         [LOG_ALERT] = "alert",
5383         [LOG_CRIT] = "crit",
5384         [LOG_ERR] = "err",
5385         [LOG_WARNING] = "warning",
5386         [LOG_NOTICE] = "notice",
5387         [LOG_INFO] = "info",
5388         [LOG_DEBUG] = "debug"
5389 };
5390
5391 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5392
5393 static const char* const sched_policy_table[] = {
5394         [SCHED_OTHER] = "other",
5395         [SCHED_BATCH] = "batch",
5396         [SCHED_IDLE] = "idle",
5397         [SCHED_FIFO] = "fifo",
5398         [SCHED_RR] = "rr"
5399 };
5400
5401 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5402
5403 static const char* const rlimit_table[] = {
5404         [RLIMIT_CPU] = "LimitCPU",
5405         [RLIMIT_FSIZE] = "LimitFSIZE",
5406         [RLIMIT_DATA] = "LimitDATA",
5407         [RLIMIT_STACK] = "LimitSTACK",
5408         [RLIMIT_CORE] = "LimitCORE",
5409         [RLIMIT_RSS] = "LimitRSS",
5410         [RLIMIT_NOFILE] = "LimitNOFILE",
5411         [RLIMIT_AS] = "LimitAS",
5412         [RLIMIT_NPROC] = "LimitNPROC",
5413         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5414         [RLIMIT_LOCKS] = "LimitLOCKS",
5415         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5416         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5417         [RLIMIT_NICE] = "LimitNICE",
5418         [RLIMIT_RTPRIO] = "LimitRTPRIO",
5419         [RLIMIT_RTTIME] = "LimitRTTIME"
5420 };
5421
5422 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5423
5424 static const char* const ip_tos_table[] = {
5425         [IPTOS_LOWDELAY] = "low-delay",
5426         [IPTOS_THROUGHPUT] = "throughput",
5427         [IPTOS_RELIABILITY] = "reliability",
5428         [IPTOS_LOWCOST] = "low-cost",
5429 };
5430
5431 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5432
5433 static const char *const __signal_table[] = {
5434         [SIGHUP] = "HUP",
5435         [SIGINT] = "INT",
5436         [SIGQUIT] = "QUIT",
5437         [SIGILL] = "ILL",
5438         [SIGTRAP] = "TRAP",
5439         [SIGABRT] = "ABRT",
5440         [SIGBUS] = "BUS",
5441         [SIGFPE] = "FPE",
5442         [SIGKILL] = "KILL",
5443         [SIGUSR1] = "USR1",
5444         [SIGSEGV] = "SEGV",
5445         [SIGUSR2] = "USR2",
5446         [SIGPIPE] = "PIPE",
5447         [SIGALRM] = "ALRM",
5448         [SIGTERM] = "TERM",
5449 #ifdef SIGSTKFLT
5450         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
5451 #endif
5452         [SIGCHLD] = "CHLD",
5453         [SIGCONT] = "CONT",
5454         [SIGSTOP] = "STOP",
5455         [SIGTSTP] = "TSTP",
5456         [SIGTTIN] = "TTIN",
5457         [SIGTTOU] = "TTOU",
5458         [SIGURG] = "URG",
5459         [SIGXCPU] = "XCPU",
5460         [SIGXFSZ] = "XFSZ",
5461         [SIGVTALRM] = "VTALRM",
5462         [SIGPROF] = "PROF",
5463         [SIGWINCH] = "WINCH",
5464         [SIGIO] = "IO",
5465         [SIGPWR] = "PWR",
5466         [SIGSYS] = "SYS"
5467 };
5468
5469 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5470
5471 const char *signal_to_string(int signo) {
5472         static __thread char buf[12];
5473         const char *name;
5474
5475         name = __signal_to_string(signo);
5476         if (name)
5477                 return name;
5478
5479         if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5480                 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5481         else
5482                 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5483         char_array_0(buf);
5484         return buf;
5485 }
5486
5487 int signal_from_string(const char *s) {
5488         int signo;
5489         int offset = 0;
5490         unsigned u;
5491
5492         signo =__signal_from_string(s);
5493         if (signo > 0)
5494                 return signo;
5495
5496         if (startswith(s, "RTMIN+")) {
5497                 s += 6;
5498                 offset = SIGRTMIN;
5499         }
5500         if (safe_atou(s, &u) >= 0) {
5501                 signo = (int) u + offset;
5502                 if (signo > 0 && signo < _NSIG)
5503                         return signo;
5504         }
5505         return -1;
5506 }
5507
5508 bool kexec_loaded(void) {
5509        bool loaded = false;
5510        char *s;
5511
5512        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5513                if (s[0] == '1')
5514                        loaded = true;
5515                free(s);
5516        }
5517        return loaded;
5518 }
5519
5520 int strdup_or_null(const char *a, char **b) {
5521         char *c;
5522
5523         assert(b);
5524
5525         if (!a) {
5526                 *b = NULL;
5527                 return 0;
5528         }
5529
5530         c = strdup(a);
5531         if (!c)
5532                 return -ENOMEM;
5533
5534         *b = c;
5535         return 0;
5536 }
5537
5538 int prot_from_flags(int flags) {
5539
5540         switch (flags & O_ACCMODE) {
5541
5542         case O_RDONLY:
5543                 return PROT_READ;
5544
5545         case O_WRONLY:
5546                 return PROT_WRITE;
5547
5548         case O_RDWR:
5549                 return PROT_READ|PROT_WRITE;
5550
5551         default:
5552                 return -EINVAL;
5553         }
5554 }
5555
5556 char *format_bytes(char *buf, size_t l, off_t t) {
5557         unsigned i;
5558
5559         static const struct {
5560                 const char *suffix;
5561                 off_t factor;
5562         } table[] = {
5563                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5564                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5565                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5566                 { "G", 1024ULL*1024ULL*1024ULL },
5567                 { "M", 1024ULL*1024ULL },
5568                 { "K", 1024ULL },
5569         };
5570
5571         for (i = 0; i < ELEMENTSOF(table); i++) {
5572
5573                 if (t >= table[i].factor) {
5574                         snprintf(buf, l,
5575                                  "%llu.%llu%s",
5576                                  (unsigned long long) (t / table[i].factor),
5577                                  (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5578                                  table[i].suffix);
5579
5580                         goto finish;
5581                 }
5582         }
5583
5584         snprintf(buf, l, "%lluB", (unsigned long long) t);
5585
5586 finish:
5587         buf[l-1] = 0;
5588         return buf;
5589
5590 }
5591
5592 void* memdup(const void *p, size_t l) {
5593         void *r;
5594
5595         assert(p);
5596
5597         r = malloc(l);
5598         if (!r)
5599                 return NULL;
5600
5601         memcpy(r, p, l);
5602         return r;
5603 }
5604
5605 int fd_inc_sndbuf(int fd, size_t n) {
5606         int r, value;
5607         socklen_t l = sizeof(value);
5608
5609         r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5610         if (r >= 0 &&
5611             l == sizeof(value) &&
5612             (size_t) value >= n*2)
5613                 return 0;
5614
5615         value = (int) n;
5616         r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5617         if (r < 0)
5618                 return -errno;
5619
5620         return 1;
5621 }
5622
5623 int fd_inc_rcvbuf(int fd, size_t n) {
5624         int r, value;
5625         socklen_t l = sizeof(value);
5626
5627         r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5628         if (r >= 0 &&
5629             l == sizeof(value) &&
5630             (size_t) value >= n*2)
5631                 return 0;
5632
5633         value = (int) n;
5634         r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5635         if (r < 0)
5636                 return -errno;
5637
5638         return 1;
5639 }
5640
5641 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5642         pid_t parent_pid, agent_pid;
5643         int fd;
5644         bool stdout_is_tty, stderr_is_tty;
5645         unsigned n, i;
5646         va_list ap;
5647         char **l;
5648
5649         assert(pid);
5650         assert(path);
5651
5652         parent_pid = getpid();
5653
5654         /* Spawns a temporary TTY agent, making sure it goes away when
5655          * we go away */
5656
5657         agent_pid = fork();
5658         if (agent_pid < 0)
5659                 return -errno;
5660
5661         if (agent_pid != 0) {
5662                 *pid = agent_pid;
5663                 return 0;
5664         }
5665
5666         /* In the child:
5667          *
5668          * Make sure the agent goes away when the parent dies */
5669         if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5670                 _exit(EXIT_FAILURE);
5671
5672         /* Check whether our parent died before we were able
5673          * to set the death signal */
5674         if (getppid() != parent_pid)
5675                 _exit(EXIT_SUCCESS);
5676
5677         /* Don't leak fds to the agent */
5678         close_all_fds(except, n_except);
5679
5680         stdout_is_tty = isatty(STDOUT_FILENO);
5681         stderr_is_tty = isatty(STDERR_FILENO);
5682
5683         if (!stdout_is_tty || !stderr_is_tty) {
5684                 /* Detach from stdout/stderr. and reopen
5685                  * /dev/tty for them. This is important to
5686                  * ensure that when systemctl is started via
5687                  * popen() or a similar call that expects to
5688                  * read EOF we actually do generate EOF and
5689                  * not delay this indefinitely by because we
5690                  * keep an unused copy of stdin around. */
5691                 fd = open("/dev/tty", O_WRONLY);
5692                 if (fd < 0) {
5693                         log_error("Failed to open /dev/tty: %m");
5694                         _exit(EXIT_FAILURE);
5695                 }
5696
5697                 if (!stdout_is_tty)
5698                         dup2(fd, STDOUT_FILENO);
5699
5700                 if (!stderr_is_tty)
5701                         dup2(fd, STDERR_FILENO);
5702
5703                 if (fd > 2)
5704                         close(fd);
5705         }
5706
5707         /* Count arguments */
5708         va_start(ap, path);
5709         for (n = 0; va_arg(ap, char*); n++)
5710                 ;
5711         va_end(ap);
5712
5713         /* Allocate strv */
5714         l = alloca(sizeof(char *) * (n + 1));
5715
5716         /* Fill in arguments */
5717         va_start(ap, path);
5718         for (i = 0; i <= n; i++)
5719                 l[i] = va_arg(ap, char*);
5720         va_end(ap);
5721
5722         execv(path, l);
5723         _exit(EXIT_FAILURE);
5724 }
5725
5726 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5727         struct rlimit highest, fixed;
5728
5729         assert(rlim);
5730
5731         if (setrlimit(resource, rlim) >= 0)
5732                 return 0;
5733
5734         if (errno != EPERM)
5735                 return -errno;
5736
5737         /* So we failed to set the desired setrlimit, then let's try
5738          * to get as close as we can */
5739         assert_se(getrlimit(resource, &highest) == 0);
5740
5741         fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5742         fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5743
5744         if (setrlimit(resource, &fixed) < 0)
5745                 return -errno;
5746
5747         return 0;
5748 }
5749
5750 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5751         char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5752         int r;
5753         FILE *f;
5754         bool done = false;
5755         size_t l;
5756
5757         assert(field);
5758         assert(_value);
5759
5760         if (pid == 0)
5761                 pid = getpid();
5762
5763         snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5764         char_array_0(path);
5765
5766         f = fopen(path, "re");
5767         if (!f)
5768                 return -errno;
5769
5770         l = strlen(field);
5771         r = 0;
5772
5773         do {
5774                 char line[LINE_MAX];
5775                 unsigned i;
5776
5777                 for (i = 0; i < sizeof(line)-1; i++) {
5778                         int c;
5779
5780                         c = getc(f);
5781                         if (_unlikely_(c == EOF)) {
5782                                 done = true;
5783                                 break;
5784                         } else if (c == 0)
5785                                 break;
5786
5787                         line[i] = c;
5788                 }
5789                 line[i] = 0;
5790
5791                 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5792                         value = strdup(line + l + 1);
5793                         if (!value) {
5794                                 r = -ENOMEM;
5795                                 break;
5796                         }
5797
5798                         r = 1;
5799                         break;
5800                 }
5801
5802         } while (!done);
5803
5804         fclose(f);
5805
5806         if (r >= 0)
5807                 *_value = value;
5808
5809         return r;
5810 }
5811
5812 int can_sleep(const char *type) {
5813         char *p, *w, *state;
5814         size_t l, k;
5815         bool found = false;
5816         int r;
5817
5818         assert(type);
5819
5820         r = read_one_line_file("/sys/power/state", &p);
5821         if (r < 0)
5822                 return r == -ENOENT ? 0 : r;
5823
5824         k = strlen(type);
5825
5826         FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5827                 if (l == k && strncmp(w, type, l) == 0) {
5828                         found = true;
5829                         break;
5830                 }
5831         }
5832
5833         free(p);
5834         return found;
5835 }
5836
5837 bool is_valid_documentation_url(const char *url) {
5838         assert(url);
5839
5840         if (startswith(url, "http://") && url[7])
5841                 return true;
5842
5843         if (startswith(url, "https://") && url[8])
5844                 return true;
5845
5846         if (startswith(url, "file:") && url[5])
5847                 return true;
5848
5849         if (startswith(url, "info:") && url[5])
5850                 return true;
5851
5852         if (startswith(url, "man:") && url[4])
5853                 return true;
5854
5855         return false;
5856 }
5857
5858 bool in_initrd(void) {
5859         static int saved = -1;
5860         struct statfs s;
5861
5862         if (saved >= 0)
5863                 return saved;
5864
5865         /* We make two checks here:
5866          *
5867          * 1. the flag file /etc/initrd-release must exist
5868          * 2. the root file system must be a memory file system
5869          *
5870          * The second check is extra paranoia, since misdetecting an
5871          * initrd can have bad bad consequences due the initrd
5872          * emptying when transititioning to the main systemd.
5873          */
5874
5875         saved = access("/etc/initrd-release", F_OK) >= 0 &&
5876                 statfs("/", &s) >= 0 &&
5877                 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5878
5879         return saved;
5880 }
5881
5882 void warn_melody(void) {
5883         int fd;
5884
5885         fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5886         if (fd < 0)
5887                 return;
5888
5889         /* Yeah, this is synchronous. Kinda sucks. Bute well... */
5890
5891         ioctl(fd, KIOCSOUND, (int)(1193180/440));
5892         usleep(125*USEC_PER_MSEC);
5893
5894         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5895         usleep(125*USEC_PER_MSEC);
5896
5897         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5898         usleep(125*USEC_PER_MSEC);
5899
5900         ioctl(fd, KIOCSOUND, 0);
5901         close_nointr_nofail(fd);
5902 }
5903
5904 int make_console_stdio(void) {
5905         int fd, r;
5906
5907         /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5908
5909         fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5910         if (fd < 0) {
5911                 log_error("Failed to acquire terminal: %s", strerror(-fd));
5912                 return fd;
5913         }
5914
5915         r = make_stdio(fd);
5916         if (r < 0) {
5917                 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5918                 return r;
5919         }
5920
5921         return 0;
5922 }
5923
5924 int get_home_dir(char **_h) {
5925         char *h;
5926         const char *e;
5927         uid_t u;
5928         struct passwd *p;
5929
5930         assert(_h);
5931
5932         /* Take the user specified one */
5933         e = getenv("HOME");
5934         if (e) {
5935                 h = strdup(e);
5936                 if (!h)
5937                         return -ENOMEM;
5938
5939                 *_h = h;
5940                 return 0;
5941         }
5942
5943         /* Hardcode home directory for root to avoid NSS */
5944         u = getuid();
5945         if (u == 0) {
5946                 h = strdup("/root");
5947                 if (!h)
5948                         return -ENOMEM;
5949
5950                 *_h = h;
5951                 return 0;
5952         }
5953
5954         /* Check the database... */
5955         errno = 0;
5956         p = getpwuid(u);
5957         if (!p)
5958                 return errno ? -errno : -ENOENT;
5959
5960         if (!path_is_absolute(p->pw_dir))
5961                 return -EINVAL;
5962
5963         h = strdup(p->pw_dir);
5964         if (!h)
5965                 return -ENOMEM;
5966
5967         *_h = h;
5968         return 0;
5969 }
5970
5971 int get_shell(char **_sh) {
5972         char *sh;
5973         const char *e;
5974         uid_t u;
5975         struct passwd *p;
5976
5977         assert(_sh);
5978
5979         /* Take the user specified one */
5980         e = getenv("SHELL");
5981         if (e) {
5982                 sh = strdup(e);
5983                 if (!sh)
5984                         return -ENOMEM;
5985
5986                 *_sh = sh;
5987                 return 0;
5988         }
5989
5990         /* Hardcode home directory for root to avoid NSS */
5991         u = getuid();
5992         if (u == 0) {
5993                 sh = strdup("/bin/sh");
5994                 if (!sh)
5995                         return -ENOMEM;
5996
5997                 *_sh = sh;
5998                 return 0;
5999         }
6000
6001         /* Check the database... */
6002         errno = 0;
6003         p = getpwuid(u);
6004         if (!p)
6005                 return errno ? -errno : -ESRCH;
6006
6007         if (!path_is_absolute(p->pw_shell))
6008                 return -EINVAL;
6009
6010         sh = strdup(p->pw_shell);
6011         if (!sh)
6012                 return -ENOMEM;
6013
6014         *_sh = sh;
6015         return 0;
6016 }