chiark / gitweb /
namespace: rework namespace support
[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_with_prefix(const char *s, size_t length, const char *prefix) {
1566         char *r, *t;
1567         const char *f;
1568         size_t pl;
1569
1570         assert(s);
1571
1572         /* Undoes C style string escaping, and optionally prefixes it. */
1573
1574         pl = prefix ? strlen(prefix) : 0;
1575
1576         r = new(char, pl+length+1);
1577         if (!r)
1578                 return r;
1579
1580         if (prefix)
1581                 memcpy(r, prefix, pl);
1582
1583         for (f = s, t = r + pl; f < s + length; f++) {
1584
1585                 if (*f != '\\') {
1586                         *(t++) = *f;
1587                         continue;
1588                 }
1589
1590                 f++;
1591
1592                 switch (*f) {
1593
1594                 case 'a':
1595                         *(t++) = '\a';
1596                         break;
1597                 case 'b':
1598                         *(t++) = '\b';
1599                         break;
1600                 case 'f':
1601                         *(t++) = '\f';
1602                         break;
1603                 case 'n':
1604                         *(t++) = '\n';
1605                         break;
1606                 case 'r':
1607                         *(t++) = '\r';
1608                         break;
1609                 case 't':
1610                         *(t++) = '\t';
1611                         break;
1612                 case 'v':
1613                         *(t++) = '\v';
1614                         break;
1615                 case '\\':
1616                         *(t++) = '\\';
1617                         break;
1618                 case '"':
1619                         *(t++) = '"';
1620                         break;
1621                 case '\'':
1622                         *(t++) = '\'';
1623                         break;
1624
1625                 case 's':
1626                         /* This is an extension of the XDG syntax files */
1627                         *(t++) = ' ';
1628                         break;
1629
1630                 case 'x': {
1631                         /* hexadecimal encoding */
1632                         int a, b;
1633
1634                         a = unhexchar(f[1]);
1635                         b = unhexchar(f[2]);
1636
1637                         if (a < 0 || b < 0) {
1638                                 /* Invalid escape code, let's take it literal then */
1639                                 *(t++) = '\\';
1640                                 *(t++) = 'x';
1641                         } else {
1642                                 *(t++) = (char) ((a << 4) | b);
1643                                 f += 2;
1644                         }
1645
1646                         break;
1647                 }
1648
1649                 case '0':
1650                 case '1':
1651                 case '2':
1652                 case '3':
1653                 case '4':
1654                 case '5':
1655                 case '6':
1656                 case '7': {
1657                         /* octal encoding */
1658                         int a, b, c;
1659
1660                         a = unoctchar(f[0]);
1661                         b = unoctchar(f[1]);
1662                         c = unoctchar(f[2]);
1663
1664                         if (a < 0 || b < 0 || c < 0) {
1665                                 /* Invalid escape code, let's take it literal then */
1666                                 *(t++) = '\\';
1667                                 *(t++) = f[0];
1668                         } else {
1669                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1670                                 f += 2;
1671                         }
1672
1673                         break;
1674                 }
1675
1676                 case 0:
1677                         /* premature end of string.*/
1678                         *(t++) = '\\';
1679                         goto finish;
1680
1681                 default:
1682                         /* Invalid escape code, let's take it literal then */
1683                         *(t++) = '\\';
1684                         *(t++) = *f;
1685                         break;
1686                 }
1687         }
1688
1689 finish:
1690         *t = 0;
1691         return r;
1692 }
1693
1694 char *cunescape_length(const char *s, size_t length) {
1695         return cunescape_length_with_prefix(s, length, NULL);
1696 }
1697
1698 char *cunescape(const char *s) {
1699         assert(s);
1700
1701         return cunescape_length(s, strlen(s));
1702 }
1703
1704 char *xescape(const char *s, const char *bad) {
1705         char *r, *t;
1706         const char *f;
1707
1708         /* Escapes all chars in bad, in addition to \ and all special
1709          * chars, in \xFF style escaping. May be reversed with
1710          * cunescape. */
1711
1712         if (!(r = new(char, strlen(s)*4+1)))
1713                 return NULL;
1714
1715         for (f = s, t = r; *f; f++) {
1716
1717                 if ((*f < ' ') || (*f >= 127) ||
1718                     (*f == '\\') || strchr(bad, *f)) {
1719                         *(t++) = '\\';
1720                         *(t++) = 'x';
1721                         *(t++) = hexchar(*f >> 4);
1722                         *(t++) = hexchar(*f);
1723                 } else
1724                         *(t++) = *f;
1725         }
1726
1727         *t = 0;
1728
1729         return r;
1730 }
1731
1732 char *bus_path_escape(const char *s) {
1733         char *r, *t;
1734         const char *f;
1735
1736         assert(s);
1737
1738         /* Escapes all chars that D-Bus' object path cannot deal
1739          * with. Can be reverse with bus_path_unescape() */
1740
1741         if (!(r = new(char, strlen(s)*3+1)))
1742                 return NULL;
1743
1744         for (f = s, t = r; *f; f++) {
1745
1746                 if (!(*f >= 'A' && *f <= 'Z') &&
1747                     !(*f >= 'a' && *f <= 'z') &&
1748                     !(*f >= '0' && *f <= '9')) {
1749                         *(t++) = '_';
1750                         *(t++) = hexchar(*f >> 4);
1751                         *(t++) = hexchar(*f);
1752                 } else
1753                         *(t++) = *f;
1754         }
1755
1756         *t = 0;
1757
1758         return r;
1759 }
1760
1761 char *bus_path_unescape(const char *f) {
1762         char *r, *t;
1763
1764         assert(f);
1765
1766         if (!(r = strdup(f)))
1767                 return NULL;
1768
1769         for (t = r; *f; f++) {
1770
1771                 if (*f == '_') {
1772                         int a, b;
1773
1774                         if ((a = unhexchar(f[1])) < 0 ||
1775                             (b = unhexchar(f[2])) < 0) {
1776                                 /* Invalid escape code, let's take it literal then */
1777                                 *(t++) = '_';
1778                         } else {
1779                                 *(t++) = (char) ((a << 4) | b);
1780                                 f += 2;
1781                         }
1782                 } else
1783                         *(t++) = *f;
1784         }
1785
1786         *t = 0;
1787
1788         return r;
1789 }
1790
1791 char *ascii_strlower(char *t) {
1792         char *p;
1793
1794         assert(t);
1795
1796         for (p = t; *p; p++)
1797                 if (*p >= 'A' && *p <= 'Z')
1798                         *p = *p - 'A' + 'a';
1799
1800         return t;
1801 }
1802
1803 bool ignore_file(const char *filename) {
1804         assert(filename);
1805
1806         return
1807                 filename[0] == '.' ||
1808                 streq(filename, "lost+found") ||
1809                 streq(filename, "aquota.user") ||
1810                 streq(filename, "aquota.group") ||
1811                 endswith(filename, "~") ||
1812                 endswith(filename, ".rpmnew") ||
1813                 endswith(filename, ".rpmsave") ||
1814                 endswith(filename, ".rpmorig") ||
1815                 endswith(filename, ".dpkg-old") ||
1816                 endswith(filename, ".dpkg-new") ||
1817                 endswith(filename, ".swp");
1818 }
1819
1820 int fd_nonblock(int fd, bool nonblock) {
1821         int flags;
1822
1823         assert(fd >= 0);
1824
1825         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1826                 return -errno;
1827
1828         if (nonblock)
1829                 flags |= O_NONBLOCK;
1830         else
1831                 flags &= ~O_NONBLOCK;
1832
1833         if (fcntl(fd, F_SETFL, flags) < 0)
1834                 return -errno;
1835
1836         return 0;
1837 }
1838
1839 int fd_cloexec(int fd, bool cloexec) {
1840         int flags;
1841
1842         assert(fd >= 0);
1843
1844         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1845                 return -errno;
1846
1847         if (cloexec)
1848                 flags |= FD_CLOEXEC;
1849         else
1850                 flags &= ~FD_CLOEXEC;
1851
1852         if (fcntl(fd, F_SETFD, flags) < 0)
1853                 return -errno;
1854
1855         return 0;
1856 }
1857
1858 static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1859         unsigned i;
1860
1861         assert(n_fdset == 0 || fdset);
1862
1863         for (i = 0; i < n_fdset; i++)
1864                 if (fdset[i] == fd)
1865                         return true;
1866
1867         return false;
1868 }
1869
1870 int close_all_fds(const int except[], unsigned n_except) {
1871         DIR *d;
1872         struct dirent *de;
1873         int r = 0;
1874
1875         assert(n_except == 0 || except);
1876
1877         d = opendir("/proc/self/fd");
1878         if (!d) {
1879                 int fd;
1880                 struct rlimit rl;
1881
1882                 /* When /proc isn't available (for example in chroots)
1883                  * the fallback is brute forcing through the fd
1884                  * table */
1885
1886                 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1887                 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1888
1889                         if (fd_in_set(fd, except, n_except))
1890                                 continue;
1891
1892                         if (close_nointr(fd) < 0)
1893                                 if (errno != EBADF && r == 0)
1894                                         r = -errno;
1895                 }
1896
1897                 return r;
1898         }
1899
1900         while ((de = readdir(d))) {
1901                 int fd = -1;
1902
1903                 if (ignore_file(de->d_name))
1904                         continue;
1905
1906                 if (safe_atoi(de->d_name, &fd) < 0)
1907                         /* Let's better ignore this, just in case */
1908                         continue;
1909
1910                 if (fd < 3)
1911                         continue;
1912
1913                 if (fd == dirfd(d))
1914                         continue;
1915
1916                 if (fd_in_set(fd, except, n_except))
1917                         continue;
1918
1919                 if (close_nointr(fd) < 0) {
1920                         /* Valgrind has its own FD and doesn't want to have it closed */
1921                         if (errno != EBADF && r == 0)
1922                                 r = -errno;
1923                 }
1924         }
1925
1926         closedir(d);
1927         return r;
1928 }
1929
1930 bool chars_intersect(const char *a, const char *b) {
1931         const char *p;
1932
1933         /* Returns true if any of the chars in a are in b. */
1934         for (p = a; *p; p++)
1935                 if (strchr(b, *p))
1936                         return true;
1937
1938         return false;
1939 }
1940
1941 char *format_timestamp(char *buf, size_t l, usec_t t) {
1942         struct tm tm;
1943         time_t sec;
1944
1945         assert(buf);
1946         assert(l > 0);
1947
1948         if (t <= 0)
1949                 return NULL;
1950
1951         sec = (time_t) (t / USEC_PER_SEC);
1952
1953         if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1954                 return NULL;
1955
1956         return buf;
1957 }
1958
1959 char *format_timestamp_pretty(char *buf, size_t l, usec_t t) {
1960         usec_t n, d;
1961
1962         n = now(CLOCK_REALTIME);
1963
1964         if (t <= 0 || t > n || t + USEC_PER_DAY*7 <= t)
1965                 return NULL;
1966
1967         d = n - t;
1968
1969         if (d >= USEC_PER_YEAR)
1970                 snprintf(buf, l, "%llu years and %llu months ago",
1971                          (unsigned long long) (d / USEC_PER_YEAR),
1972                          (unsigned long long) ((d % USEC_PER_YEAR) / USEC_PER_MONTH));
1973         else if (d >= USEC_PER_MONTH)
1974                 snprintf(buf, l, "%llu months and %llu days ago",
1975                          (unsigned long long) (d / USEC_PER_MONTH),
1976                          (unsigned long long) ((d % USEC_PER_MONTH) / USEC_PER_DAY));
1977         else if (d >= USEC_PER_WEEK)
1978                 snprintf(buf, l, "%llu weeks and %llu days ago",
1979                          (unsigned long long) (d / USEC_PER_WEEK),
1980                          (unsigned long long) ((d % USEC_PER_WEEK) / USEC_PER_DAY));
1981         else if (d >= 2*USEC_PER_DAY)
1982                 snprintf(buf, l, "%llu days ago", (unsigned long long) (d / USEC_PER_DAY));
1983         else if (d >= 25*USEC_PER_HOUR)
1984                 snprintf(buf, l, "1 day and %lluh ago",
1985                          (unsigned long long) ((d - USEC_PER_DAY) / USEC_PER_HOUR));
1986         else if (d >= 6*USEC_PER_HOUR)
1987                 snprintf(buf, l, "%lluh ago",
1988                          (unsigned long long) (d / USEC_PER_HOUR));
1989         else if (d >= USEC_PER_HOUR)
1990                 snprintf(buf, l, "%lluh %llumin ago",
1991                          (unsigned long long) (d / USEC_PER_HOUR),
1992                          (unsigned long long) ((d % USEC_PER_HOUR) / USEC_PER_MINUTE));
1993         else if (d >= 5*USEC_PER_MINUTE)
1994                 snprintf(buf, l, "%llumin ago",
1995                          (unsigned long long) (d / USEC_PER_MINUTE));
1996         else if (d >= USEC_PER_MINUTE)
1997                 snprintf(buf, l, "%llumin %llus ago",
1998                          (unsigned long long) (d / USEC_PER_MINUTE),
1999                          (unsigned long long) ((d % USEC_PER_MINUTE) / USEC_PER_SEC));
2000         else if (d >= USEC_PER_SEC)
2001                 snprintf(buf, l, "%llus ago",
2002                          (unsigned long long) (d / USEC_PER_SEC));
2003         else if (d >= USEC_PER_MSEC)
2004                 snprintf(buf, l, "%llums ago",
2005                          (unsigned long long) (d / USEC_PER_MSEC));
2006         else if (d > 0)
2007                 snprintf(buf, l, "%lluus ago",
2008                          (unsigned long long) d);
2009         else
2010                 snprintf(buf, l, "now");
2011
2012         buf[l-1] = 0;
2013         return buf;
2014 }
2015
2016 char *format_timespan(char *buf, size_t l, usec_t t) {
2017         static const struct {
2018                 const char *suffix;
2019                 usec_t usec;
2020         } table[] = {
2021                 { "w", USEC_PER_WEEK },
2022                 { "d", USEC_PER_DAY },
2023                 { "h", USEC_PER_HOUR },
2024                 { "min", USEC_PER_MINUTE },
2025                 { "s", USEC_PER_SEC },
2026                 { "ms", USEC_PER_MSEC },
2027                 { "us", 1 },
2028         };
2029
2030         unsigned i;
2031         char *p = buf;
2032
2033         assert(buf);
2034         assert(l > 0);
2035
2036         if (t == (usec_t) -1)
2037                 return NULL;
2038
2039         if (t == 0) {
2040                 snprintf(p, l, "0");
2041                 p[l-1] = 0;
2042                 return p;
2043         }
2044
2045         /* The result of this function can be parsed with parse_usec */
2046
2047         for (i = 0; i < ELEMENTSOF(table); i++) {
2048                 int k;
2049                 size_t n;
2050
2051                 if (t < table[i].usec)
2052                         continue;
2053
2054                 if (l <= 1)
2055                         break;
2056
2057                 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
2058                 n = MIN((size_t) k, l);
2059
2060                 l -= n;
2061                 p += n;
2062
2063                 t %= table[i].usec;
2064         }
2065
2066         *p = 0;
2067
2068         return buf;
2069 }
2070
2071 bool fstype_is_network(const char *fstype) {
2072         static const char * const table[] = {
2073                 "cifs",
2074                 "smbfs",
2075                 "ncpfs",
2076                 "nfs",
2077                 "nfs4",
2078                 "gfs",
2079                 "gfs2"
2080         };
2081
2082         unsigned i;
2083
2084         for (i = 0; i < ELEMENTSOF(table); i++)
2085                 if (streq(table[i], fstype))
2086                         return true;
2087
2088         return false;
2089 }
2090
2091 int chvt(int vt) {
2092         int fd, r = 0;
2093
2094         if ((fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
2095                 return -errno;
2096
2097         if (vt < 0) {
2098                 int tiocl[2] = {
2099                         TIOCL_GETKMSGREDIRECT,
2100                         0
2101                 };
2102
2103                 if (ioctl(fd, TIOCLINUX, tiocl) < 0) {
2104                         r = -errno;
2105                         goto fail;
2106                 }
2107
2108                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2109         }
2110
2111         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2112                 r = -errno;
2113
2114 fail:
2115         close_nointr_nofail(fd);
2116         return r;
2117 }
2118
2119 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
2120         struct termios old_termios, new_termios;
2121         char c;
2122         char line[LINE_MAX];
2123
2124         assert(f);
2125         assert(ret);
2126
2127         if (tcgetattr(fileno(f), &old_termios) >= 0) {
2128                 new_termios = old_termios;
2129
2130                 new_termios.c_lflag &= ~ICANON;
2131                 new_termios.c_cc[VMIN] = 1;
2132                 new_termios.c_cc[VTIME] = 0;
2133
2134                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2135                         size_t k;
2136
2137                         if (t != (usec_t) -1) {
2138                                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
2139                                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2140                                         return -ETIMEDOUT;
2141                                 }
2142                         }
2143
2144                         k = fread(&c, 1, 1, f);
2145
2146                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2147
2148                         if (k <= 0)
2149                                 return -EIO;
2150
2151                         if (need_nl)
2152                                 *need_nl = c != '\n';
2153
2154                         *ret = c;
2155                         return 0;
2156                 }
2157         }
2158
2159         if (t != (usec_t) -1)
2160                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
2161                         return -ETIMEDOUT;
2162
2163         if (!fgets(line, sizeof(line), f))
2164                 return -EIO;
2165
2166         truncate_nl(line);
2167
2168         if (strlen(line) != 1)
2169                 return -EBADMSG;
2170
2171         if (need_nl)
2172                 *need_nl = false;
2173
2174         *ret = line[0];
2175         return 0;
2176 }
2177
2178 int ask(char *ret, const char *replies, const char *text, ...) {
2179         bool on_tty;
2180
2181         assert(ret);
2182         assert(replies);
2183         assert(text);
2184
2185         on_tty = isatty(STDOUT_FILENO);
2186
2187         for (;;) {
2188                 va_list ap;
2189                 char c;
2190                 int r;
2191                 bool need_nl = true;
2192
2193                 if (on_tty)
2194                         fputs(ANSI_HIGHLIGHT_ON, stdout);
2195
2196                 va_start(ap, text);
2197                 vprintf(text, ap);
2198                 va_end(ap);
2199
2200                 if (on_tty)
2201                         fputs(ANSI_HIGHLIGHT_OFF, stdout);
2202
2203                 fflush(stdout);
2204
2205                 r = read_one_char(stdin, &c, (usec_t) -1, &need_nl);
2206                 if (r < 0) {
2207
2208                         if (r == -EBADMSG) {
2209                                 puts("Bad input, please try again.");
2210                                 continue;
2211                         }
2212
2213                         putchar('\n');
2214                         return r;
2215                 }
2216
2217                 if (need_nl)
2218                         putchar('\n');
2219
2220                 if (strchr(replies, c)) {
2221                         *ret = c;
2222                         return 0;
2223                 }
2224
2225                 puts("Read unexpected character, please try again.");
2226         }
2227 }
2228
2229 int reset_terminal_fd(int fd, bool switch_to_text) {
2230         struct termios termios;
2231         int r = 0;
2232
2233         /* Set terminal to some sane defaults */
2234
2235         assert(fd >= 0);
2236
2237         /* We leave locked terminal attributes untouched, so that
2238          * Plymouth may set whatever it wants to set, and we don't
2239          * interfere with that. */
2240
2241         /* Disable exclusive mode, just in case */
2242         ioctl(fd, TIOCNXCL);
2243
2244         /* Switch to text mode */
2245         if (switch_to_text)
2246                 ioctl(fd, KDSETMODE, KD_TEXT);
2247
2248         /* Enable console unicode mode */
2249         ioctl(fd, KDSKBMODE, K_UNICODE);
2250
2251         if (tcgetattr(fd, &termios) < 0) {
2252                 r = -errno;
2253                 goto finish;
2254         }
2255
2256         /* We only reset the stuff that matters to the software. How
2257          * hardware is set up we don't touch assuming that somebody
2258          * else will do that for us */
2259
2260         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2261         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2262         termios.c_oflag |= ONLCR;
2263         termios.c_cflag |= CREAD;
2264         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2265
2266         termios.c_cc[VINTR]    =   03;  /* ^C */
2267         termios.c_cc[VQUIT]    =  034;  /* ^\ */
2268         termios.c_cc[VERASE]   = 0177;
2269         termios.c_cc[VKILL]    =  025;  /* ^X */
2270         termios.c_cc[VEOF]     =   04;  /* ^D */
2271         termios.c_cc[VSTART]   =  021;  /* ^Q */
2272         termios.c_cc[VSTOP]    =  023;  /* ^S */
2273         termios.c_cc[VSUSP]    =  032;  /* ^Z */
2274         termios.c_cc[VLNEXT]   =  026;  /* ^V */
2275         termios.c_cc[VWERASE]  =  027;  /* ^W */
2276         termios.c_cc[VREPRINT] =  022;  /* ^R */
2277         termios.c_cc[VEOL]     =    0;
2278         termios.c_cc[VEOL2]    =    0;
2279
2280         termios.c_cc[VTIME]  = 0;
2281         termios.c_cc[VMIN]   = 1;
2282
2283         if (tcsetattr(fd, TCSANOW, &termios) < 0)
2284                 r = -errno;
2285
2286 finish:
2287         /* Just in case, flush all crap out */
2288         tcflush(fd, TCIOFLUSH);
2289
2290         return r;
2291 }
2292
2293 int reset_terminal(const char *name) {
2294         int fd, r;
2295
2296         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2297         if (fd < 0)
2298                 return fd;
2299
2300         r = reset_terminal_fd(fd, true);
2301         close_nointr_nofail(fd);
2302
2303         return r;
2304 }
2305
2306 int open_terminal(const char *name, int mode) {
2307         int fd, r;
2308         unsigned c = 0;
2309
2310         /*
2311          * If a TTY is in the process of being closed opening it might
2312          * cause EIO. This is horribly awful, but unlikely to be
2313          * changed in the kernel. Hence we work around this problem by
2314          * retrying a couple of times.
2315          *
2316          * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2317          */
2318
2319         for (;;) {
2320                 fd = open(name, mode);
2321                 if (fd >= 0)
2322                         break;
2323
2324                 if (errno != EIO)
2325                         return -errno;
2326
2327                 /* Max 1s in total */
2328                 if (c >= 20)
2329                         return -errno;
2330
2331                 usleep(50 * USEC_PER_MSEC);
2332                 c++;
2333         }
2334
2335         if (fd < 0)
2336                 return -errno;
2337
2338         r = isatty(fd);
2339         if (r < 0) {
2340                 close_nointr_nofail(fd);
2341                 return -errno;
2342         }
2343
2344         if (!r) {
2345                 close_nointr_nofail(fd);
2346                 return -ENOTTY;
2347         }
2348
2349         return fd;
2350 }
2351
2352 int flush_fd(int fd) {
2353         struct pollfd pollfd;
2354
2355         zero(pollfd);
2356         pollfd.fd = fd;
2357         pollfd.events = POLLIN;
2358
2359         for (;;) {
2360                 char buf[LINE_MAX];
2361                 ssize_t l;
2362                 int r;
2363
2364                 if ((r = poll(&pollfd, 1, 0)) < 0) {
2365
2366                         if (errno == EINTR)
2367                                 continue;
2368
2369                         return -errno;
2370                 }
2371
2372                 if (r == 0)
2373                         return 0;
2374
2375                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2376
2377                         if (errno == EINTR)
2378                                 continue;
2379
2380                         if (errno == EAGAIN)
2381                                 return 0;
2382
2383                         return -errno;
2384                 }
2385
2386                 if (l <= 0)
2387                         return 0;
2388         }
2389 }
2390
2391 int acquire_terminal(
2392                 const char *name,
2393                 bool fail,
2394                 bool force,
2395                 bool ignore_tiocstty_eperm,
2396                 usec_t timeout) {
2397
2398         int fd = -1, notify = -1, r = 0, wd = -1;
2399         usec_t ts = 0;
2400         struct sigaction sa_old, sa_new;
2401
2402         assert(name);
2403
2404         /* We use inotify to be notified when the tty is closed. We
2405          * create the watch before checking if we can actually acquire
2406          * it, so that we don't lose any event.
2407          *
2408          * Note: strictly speaking this actually watches for the
2409          * device being closed, it does *not* really watch whether a
2410          * tty loses its controlling process. However, unless some
2411          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2412          * its tty otherwise this will not become a problem. As long
2413          * as the administrator makes sure not configure any service
2414          * on the same tty as an untrusted user this should not be a
2415          * problem. (Which he probably should not do anyway.) */
2416
2417         if (timeout != (usec_t) -1)
2418                 ts = now(CLOCK_MONOTONIC);
2419
2420         if (!fail && !force) {
2421                 notify = inotify_init1(IN_CLOEXEC | (timeout != (usec_t) -1 ? IN_NONBLOCK : 0));
2422                 if (notify < 0) {
2423                         r = -errno;
2424                         goto fail;
2425                 }
2426
2427                 wd = inotify_add_watch(notify, name, IN_CLOSE);
2428                 if (wd < 0) {
2429                         r = -errno;
2430                         goto fail;
2431                 }
2432         }
2433
2434         for (;;) {
2435                 if (notify >= 0) {
2436                         r = flush_fd(notify);
2437                         if (r < 0)
2438                                 goto fail;
2439                 }
2440
2441                 /* We pass here O_NOCTTY only so that we can check the return
2442                  * value TIOCSCTTY and have a reliable way to figure out if we
2443                  * successfully became the controlling process of the tty */
2444                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
2445                 if (fd < 0)
2446                         return fd;
2447
2448                 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2449                  * if we already own the tty. */
2450                 zero(sa_new);
2451                 sa_new.sa_handler = SIG_IGN;
2452                 sa_new.sa_flags = SA_RESTART;
2453                 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2454
2455                 /* First, try to get the tty */
2456                 if (ioctl(fd, TIOCSCTTY, force) < 0)
2457                         r = -errno;
2458
2459                 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2460
2461                 /* Sometimes it makes sense to ignore TIOCSCTTY
2462                  * returning EPERM, i.e. when very likely we already
2463                  * are have this controlling terminal. */
2464                 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
2465                         r = 0;
2466
2467                 if (r < 0 && (force || fail || r != -EPERM)) {
2468                         goto fail;
2469                 }
2470
2471                 if (r >= 0)
2472                         break;
2473
2474                 assert(!fail);
2475                 assert(!force);
2476                 assert(notify >= 0);
2477
2478                 for (;;) {
2479                         uint8_t inotify_buffer[sizeof(struct inotify_event) + FILENAME_MAX];
2480                         ssize_t l;
2481                         struct inotify_event *e;
2482
2483                         if (timeout != (usec_t) -1) {
2484                                 usec_t n;
2485
2486                                 n = now(CLOCK_MONOTONIC);
2487                                 if (ts + timeout < n) {
2488                                         r = -ETIMEDOUT;
2489                                         goto fail;
2490                                 }
2491
2492                                 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
2493                                 if (r < 0)
2494                                         goto fail;
2495
2496                                 if (r == 0) {
2497                                         r = -ETIMEDOUT;
2498                                         goto fail;
2499                                 }
2500                         }
2501
2502                         l = read(notify, inotify_buffer, sizeof(inotify_buffer));
2503                         if (l < 0) {
2504
2505                                 if (errno == EINTR || errno == EAGAIN)
2506                                         continue;
2507
2508                                 r = -errno;
2509                                 goto fail;
2510                         }
2511
2512                         e = (struct inotify_event*) inotify_buffer;
2513
2514                         while (l > 0) {
2515                                 size_t step;
2516
2517                                 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
2518                                         r = -EIO;
2519                                         goto fail;
2520                                 }
2521
2522                                 step = sizeof(struct inotify_event) + e->len;
2523                                 assert(step <= (size_t) l);
2524
2525                                 e = (struct inotify_event*) ((uint8_t*) e + step);
2526                                 l -= step;
2527                         }
2528
2529                         break;
2530                 }
2531
2532                 /* We close the tty fd here since if the old session
2533                  * ended our handle will be dead. It's important that
2534                  * we do this after sleeping, so that we don't enter
2535                  * an endless loop. */
2536                 close_nointr_nofail(fd);
2537         }
2538
2539         if (notify >= 0)
2540                 close_nointr_nofail(notify);
2541
2542         r = reset_terminal_fd(fd, true);
2543         if (r < 0)
2544                 log_warning("Failed to reset terminal: %s", strerror(-r));
2545
2546         return fd;
2547
2548 fail:
2549         if (fd >= 0)
2550                 close_nointr_nofail(fd);
2551
2552         if (notify >= 0)
2553                 close_nointr_nofail(notify);
2554
2555         return r;
2556 }
2557
2558 int release_terminal(void) {
2559         int r = 0, fd;
2560         struct sigaction sa_old, sa_new;
2561
2562         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC)) < 0)
2563                 return -errno;
2564
2565         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2566          * by our own TIOCNOTTY */
2567
2568         zero(sa_new);
2569         sa_new.sa_handler = SIG_IGN;
2570         sa_new.sa_flags = SA_RESTART;
2571         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2572
2573         if (ioctl(fd, TIOCNOTTY) < 0)
2574                 r = -errno;
2575
2576         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2577
2578         close_nointr_nofail(fd);
2579         return r;
2580 }
2581
2582 int sigaction_many(const struct sigaction *sa, ...) {
2583         va_list ap;
2584         int r = 0, sig;
2585
2586         va_start(ap, sa);
2587         while ((sig = va_arg(ap, int)) > 0)
2588                 if (sigaction(sig, sa, NULL) < 0)
2589                         r = -errno;
2590         va_end(ap);
2591
2592         return r;
2593 }
2594
2595 int ignore_signals(int sig, ...) {
2596         struct sigaction sa;
2597         va_list ap;
2598         int r = 0;
2599
2600         zero(sa);
2601         sa.sa_handler = SIG_IGN;
2602         sa.sa_flags = SA_RESTART;
2603
2604         if (sigaction(sig, &sa, NULL) < 0)
2605                 r = -errno;
2606
2607         va_start(ap, sig);
2608         while ((sig = va_arg(ap, int)) > 0)
2609                 if (sigaction(sig, &sa, NULL) < 0)
2610                         r = -errno;
2611         va_end(ap);
2612
2613         return r;
2614 }
2615
2616 int default_signals(int sig, ...) {
2617         struct sigaction sa;
2618         va_list ap;
2619         int r = 0;
2620
2621         zero(sa);
2622         sa.sa_handler = SIG_DFL;
2623         sa.sa_flags = SA_RESTART;
2624
2625         if (sigaction(sig, &sa, NULL) < 0)
2626                 r = -errno;
2627
2628         va_start(ap, sig);
2629         while ((sig = va_arg(ap, int)) > 0)
2630                 if (sigaction(sig, &sa, NULL) < 0)
2631                         r = -errno;
2632         va_end(ap);
2633
2634         return r;
2635 }
2636
2637 int close_pipe(int p[]) {
2638         int a = 0, b = 0;
2639
2640         assert(p);
2641
2642         if (p[0] >= 0) {
2643                 a = close_nointr(p[0]);
2644                 p[0] = -1;
2645         }
2646
2647         if (p[1] >= 0) {
2648                 b = close_nointr(p[1]);
2649                 p[1] = -1;
2650         }
2651
2652         return a < 0 ? a : b;
2653 }
2654
2655 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2656         uint8_t *p;
2657         ssize_t n = 0;
2658
2659         assert(fd >= 0);
2660         assert(buf);
2661
2662         p = buf;
2663
2664         while (nbytes > 0) {
2665                 ssize_t k;
2666
2667                 if ((k = read(fd, p, nbytes)) <= 0) {
2668
2669                         if (k < 0 && errno == EINTR)
2670                                 continue;
2671
2672                         if (k < 0 && errno == EAGAIN && do_poll) {
2673                                 struct pollfd pollfd;
2674
2675                                 zero(pollfd);
2676                                 pollfd.fd = fd;
2677                                 pollfd.events = POLLIN;
2678
2679                                 if (poll(&pollfd, 1, -1) < 0) {
2680                                         if (errno == EINTR)
2681                                                 continue;
2682
2683                                         return n > 0 ? n : -errno;
2684                                 }
2685
2686                                 if (pollfd.revents != POLLIN)
2687                                         return n > 0 ? n : -EIO;
2688
2689                                 continue;
2690                         }
2691
2692                         return n > 0 ? n : (k < 0 ? -errno : 0);
2693                 }
2694
2695                 p += k;
2696                 nbytes -= k;
2697                 n += k;
2698         }
2699
2700         return n;
2701 }
2702
2703 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2704         const uint8_t *p;
2705         ssize_t n = 0;
2706
2707         assert(fd >= 0);
2708         assert(buf);
2709
2710         p = buf;
2711
2712         while (nbytes > 0) {
2713                 ssize_t k;
2714
2715                 k = write(fd, p, nbytes);
2716                 if (k <= 0) {
2717
2718                         if (k < 0 && errno == EINTR)
2719                                 continue;
2720
2721                         if (k < 0 && errno == EAGAIN && do_poll) {
2722                                 struct pollfd pollfd;
2723
2724                                 zero(pollfd);
2725                                 pollfd.fd = fd;
2726                                 pollfd.events = POLLOUT;
2727
2728                                 if (poll(&pollfd, 1, -1) < 0) {
2729                                         if (errno == EINTR)
2730                                                 continue;
2731
2732                                         return n > 0 ? n : -errno;
2733                                 }
2734
2735                                 if (pollfd.revents != POLLOUT)
2736                                         return n > 0 ? n : -EIO;
2737
2738                                 continue;
2739                         }
2740
2741                         return n > 0 ? n : (k < 0 ? -errno : 0);
2742                 }
2743
2744                 p += k;
2745                 nbytes -= k;
2746                 n += k;
2747         }
2748
2749         return n;
2750 }
2751
2752 int parse_usec(const char *t, usec_t *usec) {
2753         static const struct {
2754                 const char *suffix;
2755                 usec_t usec;
2756         } table[] = {
2757                 { "sec", USEC_PER_SEC },
2758                 { "s", USEC_PER_SEC },
2759                 { "min", USEC_PER_MINUTE },
2760                 { "hr", USEC_PER_HOUR },
2761                 { "h", USEC_PER_HOUR },
2762                 { "d", USEC_PER_DAY },
2763                 { "w", USEC_PER_WEEK },
2764                 { "msec", USEC_PER_MSEC },
2765                 { "ms", USEC_PER_MSEC },
2766                 { "m", USEC_PER_MINUTE },
2767                 { "usec", 1ULL },
2768                 { "us", 1ULL },
2769                 { "", USEC_PER_SEC }, /* default is sec */
2770         };
2771
2772         const char *p;
2773         usec_t r = 0;
2774
2775         assert(t);
2776         assert(usec);
2777
2778         p = t;
2779         do {
2780                 long long l;
2781                 char *e;
2782                 unsigned i;
2783
2784                 errno = 0;
2785                 l = strtoll(p, &e, 10);
2786
2787                 if (errno != 0)
2788                         return -errno;
2789
2790                 if (l < 0)
2791                         return -ERANGE;
2792
2793                 if (e == p)
2794                         return -EINVAL;
2795
2796                 e += strspn(e, WHITESPACE);
2797
2798                 for (i = 0; i < ELEMENTSOF(table); i++)
2799                         if (startswith(e, table[i].suffix)) {
2800                                 r += (usec_t) l * table[i].usec;
2801                                 p = e + strlen(table[i].suffix);
2802                                 break;
2803                         }
2804
2805                 if (i >= ELEMENTSOF(table))
2806                         return -EINVAL;
2807
2808         } while (*p != 0);
2809
2810         *usec = r;
2811
2812         return 0;
2813 }
2814
2815 int parse_nsec(const char *t, nsec_t *nsec) {
2816         static const struct {
2817                 const char *suffix;
2818                 nsec_t nsec;
2819         } table[] = {
2820                 { "sec", NSEC_PER_SEC },
2821                 { "s", NSEC_PER_SEC },
2822                 { "min", NSEC_PER_MINUTE },
2823                 { "hr", NSEC_PER_HOUR },
2824                 { "h", NSEC_PER_HOUR },
2825                 { "d", NSEC_PER_DAY },
2826                 { "w", NSEC_PER_WEEK },
2827                 { "msec", NSEC_PER_MSEC },
2828                 { "ms", NSEC_PER_MSEC },
2829                 { "m", NSEC_PER_MINUTE },
2830                 { "usec", NSEC_PER_USEC },
2831                 { "us", NSEC_PER_USEC },
2832                 { "nsec", 1ULL },
2833                 { "ns", 1ULL },
2834                 { "", 1ULL }, /* default is nsec */
2835         };
2836
2837         const char *p;
2838         nsec_t r = 0;
2839
2840         assert(t);
2841         assert(nsec);
2842
2843         p = t;
2844         do {
2845                 long long l;
2846                 char *e;
2847                 unsigned i;
2848
2849                 errno = 0;
2850                 l = strtoll(p, &e, 10);
2851
2852                 if (errno != 0)
2853                         return -errno;
2854
2855                 if (l < 0)
2856                         return -ERANGE;
2857
2858                 if (e == p)
2859                         return -EINVAL;
2860
2861                 e += strspn(e, WHITESPACE);
2862
2863                 for (i = 0; i < ELEMENTSOF(table); i++)
2864                         if (startswith(e, table[i].suffix)) {
2865                                 r += (nsec_t) l * table[i].nsec;
2866                                 p = e + strlen(table[i].suffix);
2867                                 break;
2868                         }
2869
2870                 if (i >= ELEMENTSOF(table))
2871                         return -EINVAL;
2872
2873         } while (*p != 0);
2874
2875         *nsec = r;
2876
2877         return 0;
2878 }
2879
2880 int parse_bytes(const char *t, off_t *bytes) {
2881         static const struct {
2882                 const char *suffix;
2883                 off_t factor;
2884         } table[] = {
2885                 { "B", 1 },
2886                 { "K", 1024ULL },
2887                 { "M", 1024ULL*1024ULL },
2888                 { "G", 1024ULL*1024ULL*1024ULL },
2889                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2890                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2891                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2892                 { "", 1 },
2893         };
2894
2895         const char *p;
2896         off_t r = 0;
2897
2898         assert(t);
2899         assert(bytes);
2900
2901         p = t;
2902         do {
2903                 long long l;
2904                 char *e;
2905                 unsigned i;
2906
2907                 errno = 0;
2908                 l = strtoll(p, &e, 10);
2909
2910                 if (errno != 0)
2911                         return -errno;
2912
2913                 if (l < 0)
2914                         return -ERANGE;
2915
2916                 if (e == p)
2917                         return -EINVAL;
2918
2919                 e += strspn(e, WHITESPACE);
2920
2921                 for (i = 0; i < ELEMENTSOF(table); i++)
2922                         if (startswith(e, table[i].suffix)) {
2923                                 r += (off_t) l * table[i].factor;
2924                                 p = e + strlen(table[i].suffix);
2925                                 break;
2926                         }
2927
2928                 if (i >= ELEMENTSOF(table))
2929                         return -EINVAL;
2930
2931         } while (*p != 0);
2932
2933         *bytes = r;
2934
2935         return 0;
2936 }
2937
2938 int make_stdio(int fd) {
2939         int r, s, t;
2940
2941         assert(fd >= 0);
2942
2943         r = dup2(fd, STDIN_FILENO);
2944         s = dup2(fd, STDOUT_FILENO);
2945         t = dup2(fd, STDERR_FILENO);
2946
2947         if (fd >= 3)
2948                 close_nointr_nofail(fd);
2949
2950         if (r < 0 || s < 0 || t < 0)
2951                 return -errno;
2952
2953         fd_cloexec(STDIN_FILENO, false);
2954         fd_cloexec(STDOUT_FILENO, false);
2955         fd_cloexec(STDERR_FILENO, false);
2956
2957         return 0;
2958 }
2959
2960 int make_null_stdio(void) {
2961         int null_fd;
2962
2963         null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2964         if (null_fd < 0)
2965                 return -errno;
2966
2967         return make_stdio(null_fd);
2968 }
2969
2970 bool is_device_path(const char *path) {
2971
2972         /* Returns true on paths that refer to a device, either in
2973          * sysfs or in /dev */
2974
2975         return
2976                 path_startswith(path, "/dev/") ||
2977                 path_startswith(path, "/sys/");
2978 }
2979
2980 int dir_is_empty(const char *path) {
2981         DIR *d;
2982         int r;
2983         struct dirent buf, *de;
2984
2985         if (!(d = opendir(path)))
2986                 return -errno;
2987
2988         for (;;) {
2989                 if ((r = readdir_r(d, &buf, &de)) > 0) {
2990                         r = -r;
2991                         break;
2992                 }
2993
2994                 if (!de) {
2995                         r = 1;
2996                         break;
2997                 }
2998
2999                 if (!ignore_file(de->d_name)) {
3000                         r = 0;
3001                         break;
3002                 }
3003         }
3004
3005         closedir(d);
3006         return r;
3007 }
3008
3009 unsigned long long random_ull(void) {
3010         int fd;
3011         uint64_t ull;
3012         ssize_t r;
3013
3014         fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
3015         if (fd < 0)
3016                 goto fallback;
3017
3018         r = loop_read(fd, &ull, sizeof(ull), true);
3019         close_nointr_nofail(fd);
3020
3021         if (r != sizeof(ull))
3022                 goto fallback;
3023
3024         return ull;
3025
3026 fallback:
3027         return random() * RAND_MAX + random();
3028 }
3029
3030 void rename_process(const char name[8]) {
3031         assert(name);
3032
3033         /* This is a like a poor man's setproctitle(). It changes the
3034          * comm field, argv[0], and also the glibc's internally used
3035          * name of the process. For the first one a limit of 16 chars
3036          * applies, to the second one usually one of 10 (i.e. length
3037          * of "/sbin/init"), to the third one one of 7 (i.e. length of
3038          * "systemd"). If you pass a longer string it will be
3039          * truncated */
3040
3041         prctl(PR_SET_NAME, name);
3042
3043         if (program_invocation_name)
3044                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3045
3046         if (saved_argc > 0) {
3047                 int i;
3048
3049                 if (saved_argv[0])
3050                         strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3051
3052                 for (i = 1; i < saved_argc; i++) {
3053                         if (!saved_argv[i])
3054                                 break;
3055
3056                         memset(saved_argv[i], 0, strlen(saved_argv[i]));
3057                 }
3058         }
3059 }
3060
3061 void sigset_add_many(sigset_t *ss, ...) {
3062         va_list ap;
3063         int sig;
3064
3065         assert(ss);
3066
3067         va_start(ap, ss);
3068         while ((sig = va_arg(ap, int)) > 0)
3069                 assert_se(sigaddset(ss, sig) == 0);
3070         va_end(ap);
3071 }
3072
3073 char* gethostname_malloc(void) {
3074         struct utsname u;
3075
3076         assert_se(uname(&u) >= 0);
3077
3078         if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
3079                 return strdup(u.nodename);
3080
3081         return strdup(u.sysname);
3082 }
3083
3084 bool hostname_is_set(void) {
3085         struct utsname u;
3086
3087         assert_se(uname(&u) >= 0);
3088
3089         return !isempty(u.nodename) && !streq(u.nodename, "(none)");
3090 }
3091
3092
3093 static char *lookup_uid(uid_t uid) {
3094         long bufsize;
3095         char *buf, *name;
3096         struct passwd pwbuf, *pw = NULL;
3097
3098         /* Shortcut things to avoid NSS lookups */
3099         if (uid == 0)
3100                 return strdup("root");
3101
3102         bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
3103         if (bufsize <= 0)
3104                 bufsize = 4096;
3105
3106         buf = malloc(bufsize);
3107         if (!buf)
3108                 return NULL;
3109
3110         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3111                 name = strdup(pw->pw_name);
3112                 free(buf);
3113                 return name;
3114         }
3115
3116         free(buf);
3117
3118         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3119                 return NULL;
3120
3121         return name;
3122 }
3123
3124 char* getlogname_malloc(void) {
3125         uid_t uid;
3126         struct stat st;
3127
3128         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3129                 uid = st.st_uid;
3130         else
3131                 uid = getuid();
3132
3133         return lookup_uid(uid);
3134 }
3135
3136 char *getusername_malloc(void) {
3137         const char *e;
3138
3139         e = getenv("USER");
3140         if (e)
3141                 return strdup(e);
3142
3143         return lookup_uid(getuid());
3144 }
3145
3146 int getttyname_malloc(int fd, char **r) {
3147         char path[PATH_MAX], *c;
3148         int k;
3149
3150         assert(r);
3151
3152         if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3153                 return -k;
3154
3155         char_array_0(path);
3156
3157         if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3158                 return -ENOMEM;
3159
3160         *r = c;
3161         return 0;
3162 }
3163
3164 int getttyname_harder(int fd, char **r) {
3165         int k;
3166         char *s;
3167
3168         if ((k = getttyname_malloc(fd, &s)) < 0)
3169                 return k;
3170
3171         if (streq(s, "tty")) {
3172                 free(s);
3173                 return get_ctty(0, NULL, r);
3174         }
3175
3176         *r = s;
3177         return 0;
3178 }
3179
3180 int get_ctty_devnr(pid_t pid, dev_t *d) {
3181         int k;
3182         char line[LINE_MAX], *p, *fn;
3183         unsigned long ttynr;
3184         FILE *f;
3185
3186         if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3187                 return -ENOMEM;
3188
3189         f = fopen(fn, "re");
3190         free(fn);
3191         if (!f)
3192                 return -errno;
3193
3194         if (!fgets(line, sizeof(line), f)) {
3195                 k = feof(f) ? -EIO : -errno;
3196                 fclose(f);
3197                 return k;
3198         }
3199
3200         fclose(f);
3201
3202         p = strrchr(line, ')');
3203         if (!p)
3204                 return -EIO;
3205
3206         p++;
3207
3208         if (sscanf(p, " "
3209                    "%*c "  /* state */
3210                    "%*d "  /* ppid */
3211                    "%*d "  /* pgrp */
3212                    "%*d "  /* session */
3213                    "%lu ", /* ttynr */
3214                    &ttynr) != 1)
3215                 return -EIO;
3216
3217         *d = (dev_t) ttynr;
3218         return 0;
3219 }
3220
3221 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3222         int k;
3223         char fn[PATH_MAX], *s, *b, *p;
3224         dev_t devnr;
3225
3226         assert(r);
3227
3228         k = get_ctty_devnr(pid, &devnr);
3229         if (k < 0)
3230                 return k;
3231
3232         snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3233         char_array_0(fn);
3234
3235         if ((k = readlink_malloc(fn, &s)) < 0) {
3236
3237                 if (k != -ENOENT)
3238                         return k;
3239
3240                 /* This is an ugly hack */
3241                 if (major(devnr) == 136) {
3242                         if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3243                                 return -ENOMEM;
3244
3245                         *r = b;
3246                         if (_devnr)
3247                                 *_devnr = devnr;
3248
3249                         return 0;
3250                 }
3251
3252                 /* Probably something like the ptys which have no
3253                  * symlink in /dev/char. Let's return something
3254                  * vaguely useful. */
3255
3256                 if (!(b = strdup(fn + 5)))
3257                         return -ENOMEM;
3258
3259                 *r = b;
3260                 if (_devnr)
3261                         *_devnr = devnr;
3262
3263                 return 0;
3264         }
3265
3266         if (startswith(s, "/dev/"))
3267                 p = s + 5;
3268         else if (startswith(s, "../"))
3269                 p = s + 3;
3270         else
3271                 p = s;
3272
3273         b = strdup(p);
3274         free(s);
3275
3276         if (!b)
3277                 return -ENOMEM;
3278
3279         *r = b;
3280         if (_devnr)
3281                 *_devnr = devnr;
3282
3283         return 0;
3284 }
3285
3286 int rm_rf_children_dangerous(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3287         DIR *d;
3288         int ret = 0;
3289
3290         assert(fd >= 0);
3291
3292         /* This returns the first error we run into, but nevertheless
3293          * tries to go on. This closes the passed fd. */
3294
3295         d = fdopendir(fd);
3296         if (!d) {
3297                 close_nointr_nofail(fd);
3298
3299                 return errno == ENOENT ? 0 : -errno;
3300         }
3301
3302         for (;;) {
3303                 struct dirent buf, *de;
3304                 bool is_dir, keep_around;
3305                 struct stat st;
3306                 int r;
3307
3308                 r = readdir_r(d, &buf, &de);
3309                 if (r != 0 && ret == 0) {
3310                         ret = -r;
3311                         break;
3312                 }
3313
3314                 if (!de)
3315                         break;
3316
3317                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3318                         continue;
3319
3320                 if (de->d_type == DT_UNKNOWN ||
3321                     honour_sticky ||
3322                     (de->d_type == DT_DIR && root_dev)) {
3323                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3324                                 if (ret == 0 && errno != ENOENT)
3325                                         ret = -errno;
3326                                 continue;
3327                         }
3328
3329                         is_dir = S_ISDIR(st.st_mode);
3330                         keep_around =
3331                                 honour_sticky &&
3332                                 (st.st_uid == 0 || st.st_uid == getuid()) &&
3333                                 (st.st_mode & S_ISVTX);
3334                 } else {
3335                         is_dir = de->d_type == DT_DIR;
3336                         keep_around = false;
3337                 }
3338
3339                 if (is_dir) {
3340                         int subdir_fd;
3341
3342                         /* if root_dev is set, remove subdirectories only, if device is same as dir */
3343                         if (root_dev && st.st_dev != root_dev->st_dev)
3344                                 continue;
3345
3346                         subdir_fd = openat(fd, de->d_name,
3347                                            O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3348                         if (subdir_fd < 0) {
3349                                 if (ret == 0 && errno != ENOENT)
3350                                         ret = -errno;
3351                                 continue;
3352                         }
3353
3354                         r = rm_rf_children(subdir_fd, only_dirs, honour_sticky, root_dev);
3355                         if (r < 0 && ret == 0)
3356                                 ret = r;
3357
3358                         if (!keep_around)
3359                                 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3360                                         if (ret == 0 && errno != ENOENT)
3361                                                 ret = -errno;
3362                                 }
3363
3364                 } else if (!only_dirs && !keep_around) {
3365
3366                         if (unlinkat(fd, de->d_name, 0) < 0) {
3367                                 if (ret == 0 && errno != ENOENT)
3368                                         ret = -errno;
3369                         }
3370                 }
3371         }
3372
3373         closedir(d);
3374
3375         return ret;
3376 }
3377
3378 int rm_rf_children(int fd, bool only_dirs, bool honour_sticky, struct stat *root_dev) {
3379         struct statfs s;
3380
3381         assert(fd >= 0);
3382
3383         if (fstatfs(fd, &s) < 0) {
3384                 close_nointr_nofail(fd);
3385                 return -errno;
3386         }
3387
3388         /* We refuse to clean disk file systems with this call. This
3389          * is extra paranoia just to be sure we never ever remove
3390          * non-state data */
3391
3392         if (s.f_type != TMPFS_MAGIC &&
3393             s.f_type != RAMFS_MAGIC) {
3394                 log_error("Attempted to remove disk file system, and we can't allow that.");
3395                 close_nointr_nofail(fd);
3396                 return -EPERM;
3397         }
3398
3399         return rm_rf_children_dangerous(fd, only_dirs, honour_sticky, root_dev);
3400 }
3401
3402 static int rm_rf_internal(const char *path, bool only_dirs, bool delete_root, bool honour_sticky, bool dangerous) {
3403         int fd, r;
3404         struct statfs s;
3405
3406         assert(path);
3407
3408         /* We refuse to clean the root file system with this
3409          * call. This is extra paranoia to never cause a really
3410          * seriously broken system. */
3411         if (path_equal(path, "/")) {
3412                 log_error("Attempted to remove entire root file system, and we can't allow that.");
3413                 return -EPERM;
3414         }
3415
3416         fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|O_NOFOLLOW|O_NOATIME);
3417         if (fd < 0) {
3418
3419                 if (errno != ENOTDIR)
3420                         return -errno;
3421
3422                 if (!dangerous) {
3423                         if (statfs(path, &s) < 0)
3424                                 return -errno;
3425
3426                         if (s.f_type != TMPFS_MAGIC &&
3427                             s.f_type != RAMFS_MAGIC) {
3428                                 log_error("Attempted to remove disk file system, and we can't allow that.");
3429                                 return -EPERM;
3430                         }
3431                 }
3432
3433                 if (delete_root && !only_dirs)
3434                         if (unlink(path) < 0 && errno != ENOENT)
3435                                 return -errno;
3436
3437                 return 0;
3438         }
3439
3440         if (!dangerous) {
3441                 if (fstatfs(fd, &s) < 0) {
3442                         close_nointr_nofail(fd);
3443                         return -errno;
3444                 }
3445
3446                 if (s.f_type != TMPFS_MAGIC &&
3447                     s.f_type != RAMFS_MAGIC) {
3448                         log_error("Attempted to remove disk file system, and we can't allow that.");
3449                         close_nointr_nofail(fd);
3450                         return -EPERM;
3451                 }
3452         }
3453
3454         r = rm_rf_children_dangerous(fd, only_dirs, honour_sticky, NULL);
3455         if (delete_root) {
3456
3457                 if (honour_sticky && file_is_priv_sticky(path) > 0)
3458                         return r;
3459
3460                 if (rmdir(path) < 0 && errno != ENOENT) {
3461                         if (r == 0)
3462                                 r = -errno;
3463                 }
3464         }
3465
3466         return r;
3467 }
3468
3469 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3470         return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, false);
3471 }
3472
3473 int rm_rf_dangerous(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3474         return rm_rf_internal(path, only_dirs, delete_root, honour_sticky, true);
3475 }
3476
3477 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3478         assert(path);
3479
3480         /* Under the assumption that we are running privileged we
3481          * first change the access mode and only then hand out
3482          * ownership to avoid a window where access is too open. */
3483
3484         if (mode != (mode_t) -1)
3485                 if (chmod(path, mode) < 0)
3486                         return -errno;
3487
3488         if (uid != (uid_t) -1 || gid != (gid_t) -1)
3489                 if (chown(path, uid, gid) < 0)
3490                         return -errno;
3491
3492         return 0;
3493 }
3494
3495 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3496         assert(fd >= 0);
3497
3498         /* Under the assumption that we are running privileged we
3499          * first change the access mode and only then hand out
3500          * ownership to avoid a window where access is too open. */
3501
3502         if (fchmod(fd, mode) < 0)
3503                 return -errno;
3504
3505         if (fchown(fd, uid, gid) < 0)
3506                 return -errno;
3507
3508         return 0;
3509 }
3510
3511 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3512         cpu_set_t *r;
3513         unsigned n = 1024;
3514
3515         /* Allocates the cpuset in the right size */
3516
3517         for (;;) {
3518                 if (!(r = CPU_ALLOC(n)))
3519                         return NULL;
3520
3521                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3522                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3523
3524                         if (ncpus)
3525                                 *ncpus = n;
3526
3527                         return r;
3528                 }
3529
3530                 CPU_FREE(r);
3531
3532                 if (errno != EINVAL)
3533                         return NULL;
3534
3535                 n *= 2;
3536         }
3537 }
3538
3539 void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3540         char *s = NULL;
3541         static const char status_indent[] = "         "; /* "[" STATUS "] " */
3542         int fd = -1;
3543         struct iovec iovec[5];
3544         int n = 0;
3545
3546         assert(format);
3547
3548         /* This is independent of logging, as status messages are
3549          * optional and go exclusively to the console. */
3550
3551         if (vasprintf(&s, format, ap) < 0)
3552                 goto finish;
3553
3554         fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3555         if (fd < 0)
3556                 goto finish;
3557
3558         if (ellipse) {
3559                 char *e;
3560                 size_t emax, sl;
3561                 int c;
3562
3563                 c = fd_columns(fd);
3564                 if (c <= 0)
3565                         c = 80;
3566
3567                 sl = status ? strlen(status_indent) : 0;
3568
3569                 emax = c - sl - 1;
3570                 if (emax < 3)
3571                         emax = 3;
3572
3573                 e = ellipsize(s, emax, 75);
3574                 if (e) {
3575                         free(s);
3576                         s = e;
3577                 }
3578         }
3579
3580         zero(iovec);
3581
3582         if (status) {
3583                 if (!isempty(status)) {
3584                         IOVEC_SET_STRING(iovec[n++], "[");
3585                         IOVEC_SET_STRING(iovec[n++], status);
3586                         IOVEC_SET_STRING(iovec[n++], "] ");
3587                 } else
3588                         IOVEC_SET_STRING(iovec[n++], status_indent);
3589         }
3590
3591         IOVEC_SET_STRING(iovec[n++], s);
3592         IOVEC_SET_STRING(iovec[n++], "\n");
3593
3594         writev(fd, iovec, n);
3595
3596 finish:
3597         free(s);
3598
3599         if (fd >= 0)
3600                 close_nointr_nofail(fd);
3601 }
3602
3603 void status_printf(const char *status, bool ellipse, const char *format, ...) {
3604         va_list ap;
3605
3606         assert(format);
3607
3608         va_start(ap, format);
3609         status_vprintf(status, ellipse, format, ap);
3610         va_end(ap);
3611 }
3612
3613 void status_welcome(void) {
3614         char *pretty_name = NULL, *ansi_color = NULL;
3615         const char *const_pretty = NULL, *const_color = NULL;
3616         int r;
3617
3618         if ((r = parse_env_file("/etc/os-release", NEWLINE,
3619                                 "PRETTY_NAME", &pretty_name,
3620                                 "ANSI_COLOR", &ansi_color,
3621                                 NULL)) < 0) {
3622
3623                 if (r != -ENOENT)
3624                         log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3625         }
3626
3627         if (!pretty_name && !const_pretty)
3628                 const_pretty = "Linux";
3629
3630         if (!ansi_color && !const_color)
3631                 const_color = "1";
3632
3633         status_printf(NULL,
3634                       false,
3635                       "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3636                       const_color ? const_color : ansi_color,
3637                       const_pretty ? const_pretty : pretty_name);
3638
3639         free(ansi_color);
3640         free(pretty_name);
3641 }
3642
3643 char *replace_env(const char *format, char **env) {
3644         enum {
3645                 WORD,
3646                 CURLY,
3647                 VARIABLE
3648         } state = WORD;
3649
3650         const char *e, *word = format;
3651         char *r = NULL, *k;
3652
3653         assert(format);
3654
3655         for (e = format; *e; e ++) {
3656
3657                 switch (state) {
3658
3659                 case WORD:
3660                         if (*e == '$')
3661                                 state = CURLY;
3662                         break;
3663
3664                 case CURLY:
3665                         if (*e == '{') {
3666                                 if (!(k = strnappend(r, word, e-word-1)))
3667                                         goto fail;
3668
3669                                 free(r);
3670                                 r = k;
3671
3672                                 word = e-1;
3673                                 state = VARIABLE;
3674
3675                         } else if (*e == '$') {
3676                                 if (!(k = strnappend(r, word, e-word)))
3677                                         goto fail;
3678
3679                                 free(r);
3680                                 r = k;
3681
3682                                 word = e+1;
3683                                 state = WORD;
3684                         } else
3685                                 state = WORD;
3686                         break;
3687
3688                 case VARIABLE:
3689                         if (*e == '}') {
3690                                 const char *t;
3691
3692                                 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3693                                         t = "";
3694
3695                                 if (!(k = strappend(r, t)))
3696                                         goto fail;
3697
3698                                 free(r);
3699                                 r = k;
3700
3701                                 word = e+1;
3702                                 state = WORD;
3703                         }
3704                         break;
3705                 }
3706         }
3707
3708         if (!(k = strnappend(r, word, e-word)))
3709                 goto fail;
3710
3711         free(r);
3712         return k;
3713
3714 fail:
3715         free(r);
3716         return NULL;
3717 }
3718
3719 char **replace_env_argv(char **argv, char **env) {
3720         char **r, **i;
3721         unsigned k = 0, l = 0;
3722
3723         l = strv_length(argv);
3724
3725         if (!(r = new(char*, l+1)))
3726                 return NULL;
3727
3728         STRV_FOREACH(i, argv) {
3729
3730                 /* If $FOO appears as single word, replace it by the split up variable */
3731                 if ((*i)[0] == '$' && (*i)[1] != '{') {
3732                         char *e;
3733                         char **w, **m;
3734                         unsigned q;
3735
3736                         if ((e = strv_env_get(env, *i+1))) {
3737
3738                                 if (!(m = strv_split_quoted(e))) {
3739                                         r[k] = NULL;
3740                                         strv_free(r);
3741                                         return NULL;
3742                                 }
3743                         } else
3744                                 m = NULL;
3745
3746                         q = strv_length(m);
3747                         l = l + q - 1;
3748
3749                         if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3750                                 r[k] = NULL;
3751                                 strv_free(r);
3752                                 strv_free(m);
3753                                 return NULL;
3754                         }
3755
3756                         r = w;
3757                         if (m) {
3758                                 memcpy(r + k, m, q * sizeof(char*));
3759                                 free(m);
3760                         }
3761
3762                         k += q;
3763                         continue;
3764                 }
3765
3766                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3767                 if (!(r[k++] = replace_env(*i, env))) {
3768                         strv_free(r);
3769                         return NULL;
3770                 }
3771         }
3772
3773         r[k] = NULL;
3774         return r;
3775 }
3776
3777 int fd_columns(int fd) {
3778         struct winsize ws;
3779         zero(ws);
3780
3781         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3782                 return -errno;
3783
3784         if (ws.ws_col <= 0)
3785                 return -EIO;
3786
3787         return ws.ws_col;
3788 }
3789
3790 static unsigned columns_cached(bool cached) {
3791         static __thread int parsed_columns = 0, env_columns = -1;
3792         const char *e;
3793
3794         if (_likely_(parsed_columns > 0 && cached))
3795                 return parsed_columns;
3796
3797         if (_unlikely_(env_columns == -1)) {
3798                 e = getenv("COLUMNS");
3799                 if (e)
3800                         env_columns = atoi(e);
3801                 else
3802                         env_columns = 0;
3803         }
3804
3805         if (env_columns > 0) {
3806                 parsed_columns = env_columns;
3807                 return parsed_columns;
3808         }
3809
3810         if (parsed_columns <= 0 || !cached)
3811                 parsed_columns = fd_columns(STDOUT_FILENO);
3812
3813         if (parsed_columns <= 0)
3814                 parsed_columns = 80;
3815
3816         return parsed_columns;
3817 }
3818
3819 unsigned columns(void) {
3820         return columns_cached(true);
3821 }
3822
3823 unsigned columns_uncached(void) {
3824         return columns_cached(false);
3825 }
3826
3827 int fd_lines(int fd) {
3828         struct winsize ws;
3829         zero(ws);
3830
3831         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3832                 return -errno;
3833
3834         if (ws.ws_row <= 0)
3835                 return -EIO;
3836
3837         return ws.ws_row;
3838 }
3839
3840 unsigned lines(void) {
3841         static __thread int parsed_lines = 0;
3842         const char *e;
3843
3844         if (_likely_(parsed_lines > 0))
3845                 return parsed_lines;
3846
3847         e = getenv("LINES");
3848         if (e)
3849                 parsed_lines = atoi(e);
3850
3851         if (parsed_lines <= 0)
3852                 parsed_lines = fd_lines(STDOUT_FILENO);
3853
3854         if (parsed_lines <= 0)
3855                 parsed_lines = 25;
3856
3857         return parsed_lines;
3858 }
3859
3860 int running_in_chroot(void) {
3861         struct stat a, b;
3862
3863         zero(a);
3864         zero(b);
3865
3866         /* Only works as root */
3867
3868         if (stat("/proc/1/root", &a) < 0)
3869                 return -errno;
3870
3871         if (stat("/", &b) < 0)
3872                 return -errno;
3873
3874         return
3875                 a.st_dev != b.st_dev ||
3876                 a.st_ino != b.st_ino;
3877 }
3878
3879 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3880         size_t x;
3881         char *r;
3882
3883         assert(s);
3884         assert(percent <= 100);
3885         assert(new_length >= 3);
3886
3887         if (old_length <= 3 || old_length <= new_length)
3888                 return strndup(s, old_length);
3889
3890         r = new0(char, new_length+1);
3891         if (!r)
3892                 return r;
3893
3894         x = (new_length * percent) / 100;
3895
3896         if (x > new_length - 3)
3897                 x = new_length - 3;
3898
3899         memcpy(r, s, x);
3900         r[x] = '.';
3901         r[x+1] = '.';
3902         r[x+2] = '.';
3903         memcpy(r + x + 3,
3904                s + old_length - (new_length - x - 3),
3905                new_length - x - 3);
3906
3907         return r;
3908 }
3909
3910 char *ellipsize(const char *s, size_t length, unsigned percent) {
3911         return ellipsize_mem(s, strlen(s), length, percent);
3912 }
3913
3914 int touch(const char *path) {
3915         int fd;
3916
3917         assert(path);
3918
3919         if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
3920                 return -errno;
3921
3922         close_nointr_nofail(fd);
3923         return 0;
3924 }
3925
3926 char *unquote(const char *s, const char* quotes) {
3927         size_t l;
3928         assert(s);
3929
3930         l = strlen(s);
3931         if (l < 2)
3932                 return strdup(s);
3933
3934         if (strchr(quotes, s[0]) && s[l-1] == s[0])
3935                 return strndup(s+1, l-2);
3936
3937         return strdup(s);
3938 }
3939
3940 char *normalize_env_assignment(const char *s) {
3941         char *name, *value, *p, *r;
3942
3943         p = strchr(s, '=');
3944
3945         if (!p) {
3946                 if (!(r = strdup(s)))
3947                         return NULL;
3948
3949                 return strstrip(r);
3950         }
3951
3952         if (!(name = strndup(s, p - s)))
3953                 return NULL;
3954
3955         if (!(p = strdup(p+1))) {
3956                 free(name);
3957                 return NULL;
3958         }
3959
3960         value = unquote(strstrip(p), QUOTES);
3961         free(p);
3962
3963         if (!value) {
3964                 free(name);
3965                 return NULL;
3966         }
3967
3968         if (asprintf(&r, "%s=%s", name, value) < 0)
3969                 r = NULL;
3970
3971         free(value);
3972         free(name);
3973
3974         return r;
3975 }
3976
3977 int wait_for_terminate(pid_t pid, siginfo_t *status) {
3978         siginfo_t dummy;
3979
3980         assert(pid >= 1);
3981
3982         if (!status)
3983                 status = &dummy;
3984
3985         for (;;) {
3986                 zero(*status);
3987
3988                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
3989
3990                         if (errno == EINTR)
3991                                 continue;
3992
3993                         return -errno;
3994                 }
3995
3996                 return 0;
3997         }
3998 }
3999
4000 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4001         int r;
4002         siginfo_t status;
4003
4004         assert(name);
4005         assert(pid > 1);
4006
4007         if ((r = wait_for_terminate(pid, &status)) < 0) {
4008                 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4009                 return r;
4010         }
4011
4012         if (status.si_code == CLD_EXITED) {
4013                 if (status.si_status != 0) {
4014                         log_warning("%s failed with error code %i.", name, status.si_status);
4015                         return status.si_status;
4016                 }
4017
4018                 log_debug("%s succeeded.", name);
4019                 return 0;
4020
4021         } else if (status.si_code == CLD_KILLED ||
4022                    status.si_code == CLD_DUMPED) {
4023
4024                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4025                 return -EPROTO;
4026         }
4027
4028         log_warning("%s failed due to unknown reason.", name);
4029         return -EPROTO;
4030
4031 }
4032
4033 _noreturn_ void freeze(void) {
4034
4035         /* Make sure nobody waits for us on a socket anymore */
4036         close_all_fds(NULL, 0);
4037
4038         sync();
4039
4040         for (;;)
4041                 pause();
4042 }
4043
4044 bool null_or_empty(struct stat *st) {
4045         assert(st);
4046
4047         if (S_ISREG(st->st_mode) && st->st_size <= 0)
4048                 return true;
4049
4050         if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4051                 return true;
4052
4053         return false;
4054 }
4055
4056 int null_or_empty_path(const char *fn) {
4057         struct stat st;
4058
4059         assert(fn);
4060
4061         if (stat(fn, &st) < 0)
4062                 return -errno;
4063
4064         return null_or_empty(&st);
4065 }
4066
4067 DIR *xopendirat(int fd, const char *name, int flags) {
4068         int nfd;
4069         DIR *d;
4070
4071         if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4072                 return NULL;
4073
4074         if (!(d = fdopendir(nfd))) {
4075                 close_nointr_nofail(nfd);
4076                 return NULL;
4077         }
4078
4079         return d;
4080 }
4081
4082 int signal_from_string_try_harder(const char *s) {
4083         int signo;
4084         assert(s);
4085
4086         if ((signo = signal_from_string(s)) <= 0)
4087                 if (startswith(s, "SIG"))
4088                         return signal_from_string(s+3);
4089
4090         return signo;
4091 }
4092
4093 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4094
4095         assert(f);
4096         assert(name);
4097         assert(t);
4098
4099         if (!dual_timestamp_is_set(t))
4100                 return;
4101
4102         fprintf(f, "%s=%llu %llu\n",
4103                 name,
4104                 (unsigned long long) t->realtime,
4105                 (unsigned long long) t->monotonic);
4106 }
4107
4108 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4109         unsigned long long a, b;
4110
4111         assert(value);
4112         assert(t);
4113
4114         if (sscanf(value, "%lli %llu", &a, &b) != 2)
4115                 log_debug("Failed to parse finish timestamp value %s", value);
4116         else {
4117                 t->realtime = a;
4118                 t->monotonic = b;
4119         }
4120 }
4121
4122 char *fstab_node_to_udev_node(const char *p) {
4123         char *dn, *t, *u;
4124         int r;
4125
4126         /* FIXME: to follow udev's logic 100% we need to leave valid
4127          * UTF8 chars unescaped */
4128
4129         if (startswith(p, "LABEL=")) {
4130
4131                 if (!(u = unquote(p+6, "\"\'")))
4132                         return NULL;
4133
4134                 t = xescape(u, "/ ");
4135                 free(u);
4136
4137                 if (!t)
4138                         return NULL;
4139
4140                 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4141                 free(t);
4142
4143                 if (r < 0)
4144                         return NULL;
4145
4146                 return dn;
4147         }
4148
4149         if (startswith(p, "UUID=")) {
4150
4151                 if (!(u = unquote(p+5, "\"\'")))
4152                         return NULL;
4153
4154                 t = xescape(u, "/ ");
4155                 free(u);
4156
4157                 if (!t)
4158                         return NULL;
4159
4160                 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4161                 free(t);
4162
4163                 if (r < 0)
4164                         return NULL;
4165
4166                 return dn;
4167         }
4168
4169         return strdup(p);
4170 }
4171
4172 bool tty_is_vc(const char *tty) {
4173         assert(tty);
4174
4175         if (startswith(tty, "/dev/"))
4176                 tty += 5;
4177
4178         return vtnr_from_tty(tty) >= 0;
4179 }
4180
4181 bool tty_is_console(const char *tty) {
4182         assert(tty);
4183
4184         if (startswith(tty, "/dev/"))
4185                 tty += 5;
4186
4187         return streq(tty, "console");
4188 }
4189
4190 int vtnr_from_tty(const char *tty) {
4191         int i, r;
4192
4193         assert(tty);
4194
4195         if (startswith(tty, "/dev/"))
4196                 tty += 5;
4197
4198         if (!startswith(tty, "tty") )
4199                 return -EINVAL;
4200
4201         if (tty[3] < '0' || tty[3] > '9')
4202                 return -EINVAL;
4203
4204         r = safe_atoi(tty+3, &i);
4205         if (r < 0)
4206                 return r;
4207
4208         if (i < 0 || i > 63)
4209                 return -EINVAL;
4210
4211         return i;
4212 }
4213
4214 bool tty_is_vc_resolve(const char *tty) {
4215         char *active = NULL;
4216         bool b;
4217
4218         assert(tty);
4219
4220         if (startswith(tty, "/dev/"))
4221                 tty += 5;
4222
4223         /* Resolve where /dev/console is pointing to, if /sys is
4224          * actually ours (i.e. not read-only-mounted which is a sign
4225          * for container setups) */
4226         if (streq(tty, "console") && path_is_read_only_fs("/sys") <= 0)
4227                 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4228                         /* If multiple log outputs are configured the
4229                          * last one is what /dev/console points to */
4230                         tty = strrchr(active, ' ');
4231                         if (tty)
4232                                 tty++;
4233                         else
4234                                 tty = active;
4235                 }
4236
4237         b = tty_is_vc(tty);
4238         free(active);
4239
4240         return b;
4241 }
4242
4243 const char *default_term_for_tty(const char *tty) {
4244         assert(tty);
4245
4246         return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt102";
4247 }
4248
4249 bool dirent_is_file(const struct dirent *de) {
4250         assert(de);
4251
4252         if (ignore_file(de->d_name))
4253                 return false;
4254
4255         if (de->d_type != DT_REG &&
4256             de->d_type != DT_LNK &&
4257             de->d_type != DT_UNKNOWN)
4258                 return false;
4259
4260         return true;
4261 }
4262
4263 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4264         assert(de);
4265
4266         if (!dirent_is_file(de))
4267                 return false;
4268
4269         return endswith(de->d_name, suffix);
4270 }
4271
4272 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4273         DIR *_d = NULL;
4274         struct dirent *de;
4275         Hashmap *pids = NULL;
4276
4277         assert(directory);
4278
4279         /* Executes all binaries in a directory in parallel and waits
4280          * until all they all finished. */
4281
4282         if (!d) {
4283                 if (!(_d = opendir(directory))) {
4284
4285                         if (errno == ENOENT)
4286                                 return;
4287
4288                         log_error("Failed to enumerate directory %s: %m", directory);
4289                         return;
4290                 }
4291
4292                 d = _d;
4293         }
4294
4295         if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4296                 log_error("Failed to allocate set.");
4297                 goto finish;
4298         }
4299
4300         while ((de = readdir(d))) {
4301                 char *path;
4302                 pid_t pid;
4303                 int k;
4304
4305                 if (!dirent_is_file(de))
4306                         continue;
4307
4308                 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4309                         log_oom();
4310                         continue;
4311                 }
4312
4313                 if ((pid = fork()) < 0) {
4314                         log_error("Failed to fork: %m");
4315                         free(path);
4316                         continue;
4317                 }
4318
4319                 if (pid == 0) {
4320                         char *_argv[2];
4321                         /* Child */
4322
4323                         if (!argv) {
4324                                 _argv[0] = path;
4325                                 _argv[1] = NULL;
4326                                 argv = _argv;
4327                         } else
4328                                 argv[0] = path;
4329
4330                         execv(path, argv);
4331
4332                         log_error("Failed to execute %s: %m", path);
4333                         _exit(EXIT_FAILURE);
4334                 }
4335
4336                 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4337
4338                 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4339                         log_error("Failed to add PID to set: %s", strerror(-k));
4340                         free(path);
4341                 }
4342         }
4343
4344         while (!hashmap_isempty(pids)) {
4345                 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4346                 siginfo_t si;
4347                 char *path;
4348
4349                 zero(si);
4350                 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4351
4352                         if (errno == EINTR)
4353                                 continue;
4354
4355                         log_error("waitid() failed: %m");
4356                         goto finish;
4357                 }
4358
4359                 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4360                         if (!is_clean_exit(si.si_code, si.si_status)) {
4361                                 if (si.si_code == CLD_EXITED)
4362                                         log_error("%s exited with exit status %i.", path, si.si_status);
4363                                 else
4364                                         log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4365                         } else
4366                                 log_debug("%s exited successfully.", path);
4367
4368                         free(path);
4369                 }
4370         }
4371
4372 finish:
4373         if (_d)
4374                 closedir(_d);
4375
4376         if (pids)
4377                 hashmap_free_free(pids);
4378 }
4379
4380 int kill_and_sigcont(pid_t pid, int sig) {
4381         int r;
4382
4383         r = kill(pid, sig) < 0 ? -errno : 0;
4384
4385         if (r >= 0)
4386                 kill(pid, SIGCONT);
4387
4388         return r;
4389 }
4390
4391 bool nulstr_contains(const char*nulstr, const char *needle) {
4392         const char *i;
4393
4394         if (!nulstr)
4395                 return false;
4396
4397         NULSTR_FOREACH(i, nulstr)
4398                 if (streq(i, needle))
4399                         return true;
4400
4401         return false;
4402 }
4403
4404 bool plymouth_running(void) {
4405         return access("/run/plymouth/pid", F_OK) >= 0;
4406 }
4407
4408 void parse_syslog_priority(char **p, int *priority) {
4409         int a = 0, b = 0, c = 0;
4410         int k;
4411
4412         assert(p);
4413         assert(*p);
4414         assert(priority);
4415
4416         if ((*p)[0] != '<')
4417                 return;
4418
4419         if (!strchr(*p, '>'))
4420                 return;
4421
4422         if ((*p)[2] == '>') {
4423                 c = undecchar((*p)[1]);
4424                 k = 3;
4425         } else if ((*p)[3] == '>') {
4426                 b = undecchar((*p)[1]);
4427                 c = undecchar((*p)[2]);
4428                 k = 4;
4429         } else if ((*p)[4] == '>') {
4430                 a = undecchar((*p)[1]);
4431                 b = undecchar((*p)[2]);
4432                 c = undecchar((*p)[3]);
4433                 k = 5;
4434         } else
4435                 return;
4436
4437         if (a < 0 || b < 0 || c < 0)
4438                 return;
4439
4440         *priority = a*100+b*10+c;
4441         *p += k;
4442 }
4443
4444 void skip_syslog_pid(char **buf) {
4445         char *p;
4446
4447         assert(buf);
4448         assert(*buf);
4449
4450         p = *buf;
4451
4452         if (*p != '[')
4453                 return;
4454
4455         p++;
4456         p += strspn(p, "0123456789");
4457
4458         if (*p != ']')
4459                 return;
4460
4461         p++;
4462
4463         *buf = p;
4464 }
4465
4466 void skip_syslog_date(char **buf) {
4467         enum {
4468                 LETTER,
4469                 SPACE,
4470                 NUMBER,
4471                 SPACE_OR_NUMBER,
4472                 COLON
4473         } sequence[] = {
4474                 LETTER, LETTER, LETTER,
4475                 SPACE,
4476                 SPACE_OR_NUMBER, NUMBER,
4477                 SPACE,
4478                 SPACE_OR_NUMBER, NUMBER,
4479                 COLON,
4480                 SPACE_OR_NUMBER, NUMBER,
4481                 COLON,
4482                 SPACE_OR_NUMBER, NUMBER,
4483                 SPACE
4484         };
4485
4486         char *p;
4487         unsigned i;
4488
4489         assert(buf);
4490         assert(*buf);
4491
4492         p = *buf;
4493
4494         for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
4495
4496                 if (!*p)
4497                         return;
4498
4499                 switch (sequence[i]) {
4500
4501                 case SPACE:
4502                         if (*p != ' ')
4503                                 return;
4504                         break;
4505
4506                 case SPACE_OR_NUMBER:
4507                         if (*p == ' ')
4508                                 break;
4509
4510                         /* fall through */
4511
4512                 case NUMBER:
4513                         if (*p < '0' || *p > '9')
4514                                 return;
4515
4516                         break;
4517
4518                 case LETTER:
4519                         if (!(*p >= 'A' && *p <= 'Z') &&
4520                             !(*p >= 'a' && *p <= 'z'))
4521                                 return;
4522
4523                         break;
4524
4525                 case COLON:
4526                         if (*p != ':')
4527                                 return;
4528                         break;
4529
4530                 }
4531         }
4532
4533         *buf = p;
4534 }
4535
4536 char* strshorten(char *s, size_t l) {
4537         assert(s);
4538
4539         if (l < strlen(s))
4540                 s[l] = 0;
4541
4542         return s;
4543 }
4544
4545 static bool hostname_valid_char(char c) {
4546         return
4547                 (c >= 'a' && c <= 'z') ||
4548                 (c >= 'A' && c <= 'Z') ||
4549                 (c >= '0' && c <= '9') ||
4550                 c == '-' ||
4551                 c == '_' ||
4552                 c == '.';
4553 }
4554
4555 bool hostname_is_valid(const char *s) {
4556         const char *p;
4557
4558         if (isempty(s))
4559                 return false;
4560
4561         for (p = s; *p; p++)
4562                 if (!hostname_valid_char(*p))
4563                         return false;
4564
4565         if (p-s > HOST_NAME_MAX)
4566                 return false;
4567
4568         return true;
4569 }
4570
4571 char* hostname_cleanup(char *s) {
4572         char *p, *d;
4573
4574         for (p = s, d = s; *p; p++)
4575                 if ((*p >= 'a' && *p <= 'z') ||
4576                     (*p >= 'A' && *p <= 'Z') ||
4577                     (*p >= '0' && *p <= '9') ||
4578                     *p == '-' ||
4579                     *p == '_' ||
4580                     *p == '.')
4581                         *(d++) = *p;
4582
4583         *d = 0;
4584
4585         strshorten(s, HOST_NAME_MAX);
4586         return s;
4587 }
4588
4589 int pipe_eof(int fd) {
4590         struct pollfd pollfd;
4591         int r;
4592
4593         zero(pollfd);
4594         pollfd.fd = fd;
4595         pollfd.events = POLLIN|POLLHUP;
4596
4597         r = poll(&pollfd, 1, 0);
4598         if (r < 0)
4599                 return -errno;
4600
4601         if (r == 0)
4602                 return 0;
4603
4604         return pollfd.revents & POLLHUP;
4605 }
4606
4607 int fd_wait_for_event(int fd, int event, usec_t t) {
4608         struct pollfd pollfd;
4609         int r;
4610
4611         zero(pollfd);
4612         pollfd.fd = fd;
4613         pollfd.events = event;
4614
4615         r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4616         if (r < 0)
4617                 return -errno;
4618
4619         if (r == 0)
4620                 return 0;
4621
4622         return pollfd.revents;
4623 }
4624
4625 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4626         FILE *f;
4627         char *t;
4628         const char *fn;
4629         size_t k;
4630         int fd;
4631
4632         assert(path);
4633         assert(_f);
4634         assert(_temp_path);
4635
4636         t = new(char, strlen(path) + 1 + 6 + 1);
4637         if (!t)
4638                 return -ENOMEM;
4639
4640         fn = path_get_file_name(path);
4641         k = fn-path;
4642         memcpy(t, path, k);
4643         t[k] = '.';
4644         stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4645
4646         fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4647         if (fd < 0) {
4648                 free(t);
4649                 return -errno;
4650         }
4651
4652         f = fdopen(fd, "we");
4653         if (!f) {
4654                 unlink(t);
4655                 free(t);
4656                 return -errno;
4657         }
4658
4659         *_f = f;
4660         *_temp_path = t;
4661
4662         return 0;
4663 }
4664
4665 int terminal_vhangup_fd(int fd) {
4666         assert(fd >= 0);
4667
4668         if (ioctl(fd, TIOCVHANGUP) < 0)
4669                 return -errno;
4670
4671         return 0;
4672 }
4673
4674 int terminal_vhangup(const char *name) {
4675         int fd, r;
4676
4677         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4678         if (fd < 0)
4679                 return fd;
4680
4681         r = terminal_vhangup_fd(fd);
4682         close_nointr_nofail(fd);
4683
4684         return r;
4685 }
4686
4687 int vt_disallocate(const char *name) {
4688         int fd, r;
4689         unsigned u;
4690
4691         /* Deallocate the VT if possible. If not possible
4692          * (i.e. because it is the active one), at least clear it
4693          * entirely (including the scrollback buffer) */
4694
4695         if (!startswith(name, "/dev/"))
4696                 return -EINVAL;
4697
4698         if (!tty_is_vc(name)) {
4699                 /* So this is not a VT. I guess we cannot deallocate
4700                  * it then. But let's at least clear the screen */
4701
4702                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4703                 if (fd < 0)
4704                         return fd;
4705
4706                 loop_write(fd,
4707                            "\033[r"    /* clear scrolling region */
4708                            "\033[H"    /* move home */
4709                            "\033[2J",  /* clear screen */
4710                            10, false);
4711                 close_nointr_nofail(fd);
4712
4713                 return 0;
4714         }
4715
4716         if (!startswith(name, "/dev/tty"))
4717                 return -EINVAL;
4718
4719         r = safe_atou(name+8, &u);
4720         if (r < 0)
4721                 return r;
4722
4723         if (u <= 0)
4724                 return -EINVAL;
4725
4726         /* Try to deallocate */
4727         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
4728         if (fd < 0)
4729                 return fd;
4730
4731         r = ioctl(fd, VT_DISALLOCATE, u);
4732         close_nointr_nofail(fd);
4733
4734         if (r >= 0)
4735                 return 0;
4736
4737         if (errno != EBUSY)
4738                 return -errno;
4739
4740         /* Couldn't deallocate, so let's clear it fully with
4741          * scrollback */
4742         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4743         if (fd < 0)
4744                 return fd;
4745
4746         loop_write(fd,
4747                    "\033[r"   /* clear scrolling region */
4748                    "\033[H"   /* move home */
4749                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4750                    10, false);
4751         close_nointr_nofail(fd);
4752
4753         return 0;
4754 }
4755
4756 int copy_file(const char *from, const char *to) {
4757         int r, fdf, fdt;
4758
4759         assert(from);
4760         assert(to);
4761
4762         fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
4763         if (fdf < 0)
4764                 return -errno;
4765
4766         fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
4767         if (fdt < 0) {
4768                 close_nointr_nofail(fdf);
4769                 return -errno;
4770         }
4771
4772         for (;;) {
4773                 char buf[PIPE_BUF];
4774                 ssize_t n, k;
4775
4776                 n = read(fdf, buf, sizeof(buf));
4777                 if (n < 0) {
4778                         r = -errno;
4779
4780                         close_nointr_nofail(fdf);
4781                         close_nointr(fdt);
4782                         unlink(to);
4783
4784                         return r;
4785                 }
4786
4787                 if (n == 0)
4788                         break;
4789
4790                 errno = 0;
4791                 k = loop_write(fdt, buf, n, false);
4792                 if (n != k) {
4793                         r = k < 0 ? k : (errno ? -errno : -EIO);
4794
4795                         close_nointr_nofail(fdf);
4796                         close_nointr(fdt);
4797
4798                         unlink(to);
4799                         return r;
4800                 }
4801         }
4802
4803         close_nointr_nofail(fdf);
4804         r = close_nointr(fdt);
4805
4806         if (r < 0) {
4807                 unlink(to);
4808                 return r;
4809         }
4810
4811         return 0;
4812 }
4813
4814 int symlink_or_copy(const char *from, const char *to) {
4815         char *pf = NULL, *pt = NULL;
4816         struct stat a, b;
4817         int r;
4818
4819         assert(from);
4820         assert(to);
4821
4822         if (path_get_parent(from, &pf) < 0 ||
4823             path_get_parent(to, &pt) < 0) {
4824                 r = -ENOMEM;
4825                 goto finish;
4826         }
4827
4828         if (stat(pf, &a) < 0 ||
4829             stat(pt, &b) < 0) {
4830                 r = -errno;
4831                 goto finish;
4832         }
4833
4834         if (a.st_dev != b.st_dev) {
4835                 free(pf);
4836                 free(pt);
4837
4838                 return copy_file(from, to);
4839         }
4840
4841         if (symlink(from, to) < 0) {
4842                 r = -errno;
4843                 goto finish;
4844         }
4845
4846         r = 0;
4847
4848 finish:
4849         free(pf);
4850         free(pt);
4851
4852         return r;
4853 }
4854
4855 int symlink_or_copy_atomic(const char *from, const char *to) {
4856         char *t, *x;
4857         const char *fn;
4858         size_t k;
4859         unsigned long long ull;
4860         unsigned i;
4861         int r;
4862
4863         assert(from);
4864         assert(to);
4865
4866         t = new(char, strlen(to) + 1 + 16 + 1);
4867         if (!t)
4868                 return -ENOMEM;
4869
4870         fn = path_get_file_name(to);
4871         k = fn-to;
4872         memcpy(t, to, k);
4873         t[k] = '.';
4874         x = stpcpy(t+k+1, fn);
4875
4876         ull = random_ull();
4877         for (i = 0; i < 16; i++) {
4878                 *(x++) = hexchar(ull & 0xF);
4879                 ull >>= 4;
4880         }
4881
4882         *x = 0;
4883
4884         r = symlink_or_copy(from, t);
4885         if (r < 0) {
4886                 unlink(t);
4887                 free(t);
4888                 return r;
4889         }
4890
4891         if (rename(t, to) < 0) {
4892                 r = -errno;
4893                 unlink(t);
4894                 free(t);
4895                 return r;
4896         }
4897
4898         free(t);
4899         return r;
4900 }
4901
4902 bool display_is_local(const char *display) {
4903         assert(display);
4904
4905         return
4906                 display[0] == ':' &&
4907                 display[1] >= '0' &&
4908                 display[1] <= '9';
4909 }
4910
4911 int socket_from_display(const char *display, char **path) {
4912         size_t k;
4913         char *f, *c;
4914
4915         assert(display);
4916         assert(path);
4917
4918         if (!display_is_local(display))
4919                 return -EINVAL;
4920
4921         k = strspn(display+1, "0123456789");
4922
4923         f = new(char, sizeof("/tmp/.X11-unix/X") + k);
4924         if (!f)
4925                 return -ENOMEM;
4926
4927         c = stpcpy(f, "/tmp/.X11-unix/X");
4928         memcpy(c, display+1, k);
4929         c[k] = 0;
4930
4931         *path = f;
4932
4933         return 0;
4934 }
4935
4936 int get_user_creds(
4937                 const char **username,
4938                 uid_t *uid, gid_t *gid,
4939                 const char **home,
4940                 const char **shell) {
4941
4942         struct passwd *p;
4943         uid_t u;
4944
4945         assert(username);
4946         assert(*username);
4947
4948         /* We enforce some special rules for uid=0: in order to avoid
4949          * NSS lookups for root we hardcode its data. */
4950
4951         if (streq(*username, "root") || streq(*username, "0")) {
4952                 *username = "root";
4953
4954                 if (uid)
4955                         *uid = 0;
4956
4957                 if (gid)
4958                         *gid = 0;
4959
4960                 if (home)
4961                         *home = "/root";
4962
4963                 if (shell)
4964                         *shell = "/bin/sh";
4965
4966                 return 0;
4967         }
4968
4969         if (parse_uid(*username, &u) >= 0) {
4970                 errno = 0;
4971                 p = getpwuid(u);
4972
4973                 /* If there are multiple users with the same id, make
4974                  * sure to leave $USER to the configured value instead
4975                  * of the first occurrence in the database. However if
4976                  * the uid was configured by a numeric uid, then let's
4977                  * pick the real username from /etc/passwd. */
4978                 if (p)
4979                         *username = p->pw_name;
4980         } else {
4981                 errno = 0;
4982                 p = getpwnam(*username);
4983         }
4984
4985         if (!p)
4986                 return errno != 0 ? -errno : -ESRCH;
4987
4988         if (uid)
4989                 *uid = p->pw_uid;
4990
4991         if (gid)
4992                 *gid = p->pw_gid;
4993
4994         if (home)
4995                 *home = p->pw_dir;
4996
4997         if (shell)
4998                 *shell = p->pw_shell;
4999
5000         return 0;
5001 }
5002
5003 int get_group_creds(const char **groupname, gid_t *gid) {
5004         struct group *g;
5005         gid_t id;
5006
5007         assert(groupname);
5008
5009         /* We enforce some special rules for gid=0: in order to avoid
5010          * NSS lookups for root we hardcode its data. */
5011
5012         if (streq(*groupname, "root") || streq(*groupname, "0")) {
5013                 *groupname = "root";
5014
5015                 if (gid)
5016                         *gid = 0;
5017
5018                 return 0;
5019         }
5020
5021         if (parse_gid(*groupname, &id) >= 0) {
5022                 errno = 0;
5023                 g = getgrgid(id);
5024
5025                 if (g)
5026                         *groupname = g->gr_name;
5027         } else {
5028                 errno = 0;
5029                 g = getgrnam(*groupname);
5030         }
5031
5032         if (!g)
5033                 return errno != 0 ? -errno : -ESRCH;
5034
5035         if (gid)
5036                 *gid = g->gr_gid;
5037
5038         return 0;
5039 }
5040
5041 int in_group(const char *name) {
5042         gid_t gid, *gids;
5043         int ngroups_max, r, i;
5044
5045         r = get_group_creds(&name, &gid);
5046         if (r < 0)
5047                 return r;
5048
5049         if (getgid() == gid)
5050                 return 1;
5051
5052         if (getegid() == gid)
5053                 return 1;
5054
5055         ngroups_max = sysconf(_SC_NGROUPS_MAX);
5056         assert(ngroups_max > 0);
5057
5058         gids = alloca(sizeof(gid_t) * ngroups_max);
5059
5060         r = getgroups(ngroups_max, gids);
5061         if (r < 0)
5062                 return -errno;
5063
5064         for (i = 0; i < r; i++)
5065                 if (gids[i] == gid)
5066                         return 1;
5067
5068         return 0;
5069 }
5070
5071 int glob_exists(const char *path) {
5072         glob_t g;
5073         int r, k;
5074
5075         assert(path);
5076
5077         zero(g);
5078         errno = 0;
5079         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5080
5081         if (k == GLOB_NOMATCH)
5082                 r = 0;
5083         else if (k == GLOB_NOSPACE)
5084                 r = -ENOMEM;
5085         else if (k == 0)
5086                 r = !strv_isempty(g.gl_pathv);
5087         else
5088                 r = errno ? -errno : -EIO;
5089
5090         globfree(&g);
5091
5092         return r;
5093 }
5094
5095 int dirent_ensure_type(DIR *d, struct dirent *de) {
5096         struct stat st;
5097
5098         assert(d);
5099         assert(de);
5100
5101         if (de->d_type != DT_UNKNOWN)
5102                 return 0;
5103
5104         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5105                 return -errno;
5106
5107         de->d_type =
5108                 S_ISREG(st.st_mode)  ? DT_REG  :
5109                 S_ISDIR(st.st_mode)  ? DT_DIR  :
5110                 S_ISLNK(st.st_mode)  ? DT_LNK  :
5111                 S_ISFIFO(st.st_mode) ? DT_FIFO :
5112                 S_ISSOCK(st.st_mode) ? DT_SOCK :
5113                 S_ISCHR(st.st_mode)  ? DT_CHR  :
5114                 S_ISBLK(st.st_mode)  ? DT_BLK  :
5115                                        DT_UNKNOWN;
5116
5117         return 0;
5118 }
5119
5120 int in_search_path(const char *path, char **search) {
5121         char **i, *parent;
5122         int r;
5123
5124         r = path_get_parent(path, &parent);
5125         if (r < 0)
5126                 return r;
5127
5128         r = 0;
5129
5130         STRV_FOREACH(i, search) {
5131                 if (path_equal(parent, *i)) {
5132                         r = 1;
5133                         break;
5134                 }
5135         }
5136
5137         free(parent);
5138
5139         return r;
5140 }
5141
5142 int get_files_in_directory(const char *path, char ***list) {
5143         DIR *d;
5144         int r = 0;
5145         unsigned n = 0;
5146         char **l = NULL;
5147
5148         assert(path);
5149
5150         /* Returns all files in a directory in *list, and the number
5151          * of files as return value. If list is NULL returns only the
5152          * number */
5153
5154         d = opendir(path);
5155         if (!d)
5156                 return -errno;
5157
5158         for (;;) {
5159                 struct dirent buffer, *de;
5160                 int k;
5161
5162                 k = readdir_r(d, &buffer, &de);
5163                 if (k != 0) {
5164                         r = -k;
5165                         goto finish;
5166                 }
5167
5168                 if (!de)
5169                         break;
5170
5171                 dirent_ensure_type(d, de);
5172
5173                 if (!dirent_is_file(de))
5174                         continue;
5175
5176                 if (list) {
5177                         if ((unsigned) r >= n) {
5178                                 char **t;
5179
5180                                 n = MAX(16, 2*r);
5181                                 t = realloc(l, sizeof(char*) * n);
5182                                 if (!t) {
5183                                         r = -ENOMEM;
5184                                         goto finish;
5185                                 }
5186
5187                                 l = t;
5188                         }
5189
5190                         assert((unsigned) r < n);
5191
5192                         l[r] = strdup(de->d_name);
5193                         if (!l[r]) {
5194                                 r = -ENOMEM;
5195                                 goto finish;
5196                         }
5197
5198                         l[++r] = NULL;
5199                 } else
5200                         r++;
5201         }
5202
5203 finish:
5204         if (d)
5205                 closedir(d);
5206
5207         if (r >= 0) {
5208                 if (list)
5209                         *list = l;
5210         } else
5211                 strv_free(l);
5212
5213         return r;
5214 }
5215
5216 char *strjoin(const char *x, ...) {
5217         va_list ap;
5218         size_t l;
5219         char *r, *p;
5220
5221         va_start(ap, x);
5222
5223         if (x) {
5224                 l = strlen(x);
5225
5226                 for (;;) {
5227                         const char *t;
5228
5229                         t = va_arg(ap, const char *);
5230                         if (!t)
5231                                 break;
5232
5233                         l += strlen(t);
5234                 }
5235         } else
5236                 l = 0;
5237
5238         va_end(ap);
5239
5240         r = new(char, l+1);
5241         if (!r)
5242                 return NULL;
5243
5244         if (x) {
5245                 p = stpcpy(r, x);
5246
5247                 va_start(ap, x);
5248
5249                 for (;;) {
5250                         const char *t;
5251
5252                         t = va_arg(ap, const char *);
5253                         if (!t)
5254                                 break;
5255
5256                         p = stpcpy(p, t);
5257                 }
5258
5259                 va_end(ap);
5260         } else
5261                 r[0] = 0;
5262
5263         return r;
5264 }
5265
5266 bool is_main_thread(void) {
5267         static __thread int cached = 0;
5268
5269         if (_unlikely_(cached == 0))
5270                 cached = getpid() == gettid() ? 1 : -1;
5271
5272         return cached > 0;
5273 }
5274
5275 int block_get_whole_disk(dev_t d, dev_t *ret) {
5276         char *p, *s;
5277         int r;
5278         unsigned n, m;
5279
5280         assert(ret);
5281
5282         /* If it has a queue this is good enough for us */
5283         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5284                 return -ENOMEM;
5285
5286         r = access(p, F_OK);
5287         free(p);
5288
5289         if (r >= 0) {
5290                 *ret = d;
5291                 return 0;
5292         }
5293
5294         /* If it is a partition find the originating device */
5295         if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5296                 return -ENOMEM;
5297
5298         r = access(p, F_OK);
5299         free(p);
5300
5301         if (r < 0)
5302                 return -ENOENT;
5303
5304         /* Get parent dev_t */
5305         if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5306                 return -ENOMEM;
5307
5308         r = read_one_line_file(p, &s);
5309         free(p);
5310
5311         if (r < 0)
5312                 return r;
5313
5314         r = sscanf(s, "%u:%u", &m, &n);
5315         free(s);
5316
5317         if (r != 2)
5318                 return -EINVAL;
5319
5320         /* Only return this if it is really good enough for us. */
5321         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5322                 return -ENOMEM;
5323
5324         r = access(p, F_OK);
5325         free(p);
5326
5327         if (r >= 0) {
5328                 *ret = makedev(m, n);
5329                 return 0;
5330         }
5331
5332         return -ENOENT;
5333 }
5334
5335 int file_is_priv_sticky(const char *p) {
5336         struct stat st;
5337
5338         assert(p);
5339
5340         if (lstat(p, &st) < 0)
5341                 return -errno;
5342
5343         return
5344                 (st.st_uid == 0 || st.st_uid == getuid()) &&
5345                 (st.st_mode & S_ISVTX);
5346 }
5347
5348 static const char *const ioprio_class_table[] = {
5349         [IOPRIO_CLASS_NONE] = "none",
5350         [IOPRIO_CLASS_RT] = "realtime",
5351         [IOPRIO_CLASS_BE] = "best-effort",
5352         [IOPRIO_CLASS_IDLE] = "idle"
5353 };
5354
5355 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5356
5357 static const char *const sigchld_code_table[] = {
5358         [CLD_EXITED] = "exited",
5359         [CLD_KILLED] = "killed",
5360         [CLD_DUMPED] = "dumped",
5361         [CLD_TRAPPED] = "trapped",
5362         [CLD_STOPPED] = "stopped",
5363         [CLD_CONTINUED] = "continued",
5364 };
5365
5366 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
5367
5368 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
5369         [LOG_FAC(LOG_KERN)] = "kern",
5370         [LOG_FAC(LOG_USER)] = "user",
5371         [LOG_FAC(LOG_MAIL)] = "mail",
5372         [LOG_FAC(LOG_DAEMON)] = "daemon",
5373         [LOG_FAC(LOG_AUTH)] = "auth",
5374         [LOG_FAC(LOG_SYSLOG)] = "syslog",
5375         [LOG_FAC(LOG_LPR)] = "lpr",
5376         [LOG_FAC(LOG_NEWS)] = "news",
5377         [LOG_FAC(LOG_UUCP)] = "uucp",
5378         [LOG_FAC(LOG_CRON)] = "cron",
5379         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
5380         [LOG_FAC(LOG_FTP)] = "ftp",
5381         [LOG_FAC(LOG_LOCAL0)] = "local0",
5382         [LOG_FAC(LOG_LOCAL1)] = "local1",
5383         [LOG_FAC(LOG_LOCAL2)] = "local2",
5384         [LOG_FAC(LOG_LOCAL3)] = "local3",
5385         [LOG_FAC(LOG_LOCAL4)] = "local4",
5386         [LOG_FAC(LOG_LOCAL5)] = "local5",
5387         [LOG_FAC(LOG_LOCAL6)] = "local6",
5388         [LOG_FAC(LOG_LOCAL7)] = "local7"
5389 };
5390
5391 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
5392
5393 static const char *const log_level_table[] = {
5394         [LOG_EMERG] = "emerg",
5395         [LOG_ALERT] = "alert",
5396         [LOG_CRIT] = "crit",
5397         [LOG_ERR] = "err",
5398         [LOG_WARNING] = "warning",
5399         [LOG_NOTICE] = "notice",
5400         [LOG_INFO] = "info",
5401         [LOG_DEBUG] = "debug"
5402 };
5403
5404 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
5405
5406 static const char* const sched_policy_table[] = {
5407         [SCHED_OTHER] = "other",
5408         [SCHED_BATCH] = "batch",
5409         [SCHED_IDLE] = "idle",
5410         [SCHED_FIFO] = "fifo",
5411         [SCHED_RR] = "rr"
5412 };
5413
5414 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
5415
5416 static const char* const rlimit_table[] = {
5417         [RLIMIT_CPU] = "LimitCPU",
5418         [RLIMIT_FSIZE] = "LimitFSIZE",
5419         [RLIMIT_DATA] = "LimitDATA",
5420         [RLIMIT_STACK] = "LimitSTACK",
5421         [RLIMIT_CORE] = "LimitCORE",
5422         [RLIMIT_RSS] = "LimitRSS",
5423         [RLIMIT_NOFILE] = "LimitNOFILE",
5424         [RLIMIT_AS] = "LimitAS",
5425         [RLIMIT_NPROC] = "LimitNPROC",
5426         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
5427         [RLIMIT_LOCKS] = "LimitLOCKS",
5428         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
5429         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
5430         [RLIMIT_NICE] = "LimitNICE",
5431         [RLIMIT_RTPRIO] = "LimitRTPRIO",
5432         [RLIMIT_RTTIME] = "LimitRTTIME"
5433 };
5434
5435 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
5436
5437 static const char* const ip_tos_table[] = {
5438         [IPTOS_LOWDELAY] = "low-delay",
5439         [IPTOS_THROUGHPUT] = "throughput",
5440         [IPTOS_RELIABILITY] = "reliability",
5441         [IPTOS_LOWCOST] = "low-cost",
5442 };
5443
5444 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
5445
5446 static const char *const __signal_table[] = {
5447         [SIGHUP] = "HUP",
5448         [SIGINT] = "INT",
5449         [SIGQUIT] = "QUIT",
5450         [SIGILL] = "ILL",
5451         [SIGTRAP] = "TRAP",
5452         [SIGABRT] = "ABRT",
5453         [SIGBUS] = "BUS",
5454         [SIGFPE] = "FPE",
5455         [SIGKILL] = "KILL",
5456         [SIGUSR1] = "USR1",
5457         [SIGSEGV] = "SEGV",
5458         [SIGUSR2] = "USR2",
5459         [SIGPIPE] = "PIPE",
5460         [SIGALRM] = "ALRM",
5461         [SIGTERM] = "TERM",
5462 #ifdef SIGSTKFLT
5463         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
5464 #endif
5465         [SIGCHLD] = "CHLD",
5466         [SIGCONT] = "CONT",
5467         [SIGSTOP] = "STOP",
5468         [SIGTSTP] = "TSTP",
5469         [SIGTTIN] = "TTIN",
5470         [SIGTTOU] = "TTOU",
5471         [SIGURG] = "URG",
5472         [SIGXCPU] = "XCPU",
5473         [SIGXFSZ] = "XFSZ",
5474         [SIGVTALRM] = "VTALRM",
5475         [SIGPROF] = "PROF",
5476         [SIGWINCH] = "WINCH",
5477         [SIGIO] = "IO",
5478         [SIGPWR] = "PWR",
5479         [SIGSYS] = "SYS"
5480 };
5481
5482 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
5483
5484 const char *signal_to_string(int signo) {
5485         static __thread char buf[12];
5486         const char *name;
5487
5488         name = __signal_to_string(signo);
5489         if (name)
5490                 return name;
5491
5492         if (signo >= SIGRTMIN && signo <= SIGRTMAX)
5493                 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
5494         else
5495                 snprintf(buf, sizeof(buf) - 1, "%d", signo);
5496         char_array_0(buf);
5497         return buf;
5498 }
5499
5500 int signal_from_string(const char *s) {
5501         int signo;
5502         int offset = 0;
5503         unsigned u;
5504
5505         signo =__signal_from_string(s);
5506         if (signo > 0)
5507                 return signo;
5508
5509         if (startswith(s, "RTMIN+")) {
5510                 s += 6;
5511                 offset = SIGRTMIN;
5512         }
5513         if (safe_atou(s, &u) >= 0) {
5514                 signo = (int) u + offset;
5515                 if (signo > 0 && signo < _NSIG)
5516                         return signo;
5517         }
5518         return -1;
5519 }
5520
5521 bool kexec_loaded(void) {
5522        bool loaded = false;
5523        char *s;
5524
5525        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
5526                if (s[0] == '1')
5527                        loaded = true;
5528                free(s);
5529        }
5530        return loaded;
5531 }
5532
5533 int strdup_or_null(const char *a, char **b) {
5534         char *c;
5535
5536         assert(b);
5537
5538         if (!a) {
5539                 *b = NULL;
5540                 return 0;
5541         }
5542
5543         c = strdup(a);
5544         if (!c)
5545                 return -ENOMEM;
5546
5547         *b = c;
5548         return 0;
5549 }
5550
5551 int prot_from_flags(int flags) {
5552
5553         switch (flags & O_ACCMODE) {
5554
5555         case O_RDONLY:
5556                 return PROT_READ;
5557
5558         case O_WRONLY:
5559                 return PROT_WRITE;
5560
5561         case O_RDWR:
5562                 return PROT_READ|PROT_WRITE;
5563
5564         default:
5565                 return -EINVAL;
5566         }
5567 }
5568
5569 char *format_bytes(char *buf, size_t l, off_t t) {
5570         unsigned i;
5571
5572         static const struct {
5573                 const char *suffix;
5574                 off_t factor;
5575         } table[] = {
5576                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5577                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5578                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5579                 { "G", 1024ULL*1024ULL*1024ULL },
5580                 { "M", 1024ULL*1024ULL },
5581                 { "K", 1024ULL },
5582         };
5583
5584         for (i = 0; i < ELEMENTSOF(table); i++) {
5585
5586                 if (t >= table[i].factor) {
5587                         snprintf(buf, l,
5588                                  "%llu.%llu%s",
5589                                  (unsigned long long) (t / table[i].factor),
5590                                  (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
5591                                  table[i].suffix);
5592
5593                         goto finish;
5594                 }
5595         }
5596
5597         snprintf(buf, l, "%lluB", (unsigned long long) t);
5598
5599 finish:
5600         buf[l-1] = 0;
5601         return buf;
5602
5603 }
5604
5605 void* memdup(const void *p, size_t l) {
5606         void *r;
5607
5608         assert(p);
5609
5610         r = malloc(l);
5611         if (!r)
5612                 return NULL;
5613
5614         memcpy(r, p, l);
5615         return r;
5616 }
5617
5618 int fd_inc_sndbuf(int fd, size_t n) {
5619         int r, value;
5620         socklen_t l = sizeof(value);
5621
5622         r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
5623         if (r >= 0 &&
5624             l == sizeof(value) &&
5625             (size_t) value >= n*2)
5626                 return 0;
5627
5628         value = (int) n;
5629         r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
5630         if (r < 0)
5631                 return -errno;
5632
5633         return 1;
5634 }
5635
5636 int fd_inc_rcvbuf(int fd, size_t n) {
5637         int r, value;
5638         socklen_t l = sizeof(value);
5639
5640         r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
5641         if (r >= 0 &&
5642             l == sizeof(value) &&
5643             (size_t) value >= n*2)
5644                 return 0;
5645
5646         value = (int) n;
5647         r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
5648         if (r < 0)
5649                 return -errno;
5650
5651         return 1;
5652 }
5653
5654 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
5655         pid_t parent_pid, agent_pid;
5656         int fd;
5657         bool stdout_is_tty, stderr_is_tty;
5658         unsigned n, i;
5659         va_list ap;
5660         char **l;
5661
5662         assert(pid);
5663         assert(path);
5664
5665         parent_pid = getpid();
5666
5667         /* Spawns a temporary TTY agent, making sure it goes away when
5668          * we go away */
5669
5670         agent_pid = fork();
5671         if (agent_pid < 0)
5672                 return -errno;
5673
5674         if (agent_pid != 0) {
5675                 *pid = agent_pid;
5676                 return 0;
5677         }
5678
5679         /* In the child:
5680          *
5681          * Make sure the agent goes away when the parent dies */
5682         if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
5683                 _exit(EXIT_FAILURE);
5684
5685         /* Check whether our parent died before we were able
5686          * to set the death signal */
5687         if (getppid() != parent_pid)
5688                 _exit(EXIT_SUCCESS);
5689
5690         /* Don't leak fds to the agent */
5691         close_all_fds(except, n_except);
5692
5693         stdout_is_tty = isatty(STDOUT_FILENO);
5694         stderr_is_tty = isatty(STDERR_FILENO);
5695
5696         if (!stdout_is_tty || !stderr_is_tty) {
5697                 /* Detach from stdout/stderr. and reopen
5698                  * /dev/tty for them. This is important to
5699                  * ensure that when systemctl is started via
5700                  * popen() or a similar call that expects to
5701                  * read EOF we actually do generate EOF and
5702                  * not delay this indefinitely by because we
5703                  * keep an unused copy of stdin around. */
5704                 fd = open("/dev/tty", O_WRONLY);
5705                 if (fd < 0) {
5706                         log_error("Failed to open /dev/tty: %m");
5707                         _exit(EXIT_FAILURE);
5708                 }
5709
5710                 if (!stdout_is_tty)
5711                         dup2(fd, STDOUT_FILENO);
5712
5713                 if (!stderr_is_tty)
5714                         dup2(fd, STDERR_FILENO);
5715
5716                 if (fd > 2)
5717                         close(fd);
5718         }
5719
5720         /* Count arguments */
5721         va_start(ap, path);
5722         for (n = 0; va_arg(ap, char*); n++)
5723                 ;
5724         va_end(ap);
5725
5726         /* Allocate strv */
5727         l = alloca(sizeof(char *) * (n + 1));
5728
5729         /* Fill in arguments */
5730         va_start(ap, path);
5731         for (i = 0; i <= n; i++)
5732                 l[i] = va_arg(ap, char*);
5733         va_end(ap);
5734
5735         execv(path, l);
5736         _exit(EXIT_FAILURE);
5737 }
5738
5739 int setrlimit_closest(int resource, const struct rlimit *rlim) {
5740         struct rlimit highest, fixed;
5741
5742         assert(rlim);
5743
5744         if (setrlimit(resource, rlim) >= 0)
5745                 return 0;
5746
5747         if (errno != EPERM)
5748                 return -errno;
5749
5750         /* So we failed to set the desired setrlimit, then let's try
5751          * to get as close as we can */
5752         assert_se(getrlimit(resource, &highest) == 0);
5753
5754         fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
5755         fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
5756
5757         if (setrlimit(resource, &fixed) < 0)
5758                 return -errno;
5759
5760         return 0;
5761 }
5762
5763 int getenv_for_pid(pid_t pid, const char *field, char **_value) {
5764         char path[sizeof("/proc/")-1+10+sizeof("/environ")], *value = NULL;
5765         int r;
5766         FILE *f;
5767         bool done = false;
5768         size_t l;
5769
5770         assert(field);
5771         assert(_value);
5772
5773         if (pid == 0)
5774                 pid = getpid();
5775
5776         snprintf(path, sizeof(path), "/proc/%lu/environ", (unsigned long) pid);
5777         char_array_0(path);
5778
5779         f = fopen(path, "re");
5780         if (!f)
5781                 return -errno;
5782
5783         l = strlen(field);
5784         r = 0;
5785
5786         do {
5787                 char line[LINE_MAX];
5788                 unsigned i;
5789
5790                 for (i = 0; i < sizeof(line)-1; i++) {
5791                         int c;
5792
5793                         c = getc(f);
5794                         if (_unlikely_(c == EOF)) {
5795                                 done = true;
5796                                 break;
5797                         } else if (c == 0)
5798                                 break;
5799
5800                         line[i] = c;
5801                 }
5802                 line[i] = 0;
5803
5804                 if (memcmp(line, field, l) == 0 && line[l] == '=') {
5805                         value = strdup(line + l + 1);
5806                         if (!value) {
5807                                 r = -ENOMEM;
5808                                 break;
5809                         }
5810
5811                         r = 1;
5812                         break;
5813                 }
5814
5815         } while (!done);
5816
5817         fclose(f);
5818
5819         if (r >= 0)
5820                 *_value = value;
5821
5822         return r;
5823 }
5824
5825 int can_sleep(const char *type) {
5826         char *p, *w, *state;
5827         size_t l, k;
5828         bool found = false;
5829         int r;
5830
5831         assert(type);
5832
5833         r = read_one_line_file("/sys/power/state", &p);
5834         if (r < 0)
5835                 return r == -ENOENT ? 0 : r;
5836
5837         k = strlen(type);
5838
5839         FOREACH_WORD_SEPARATOR(w, l, p, WHITESPACE, state) {
5840                 if (l == k && strncmp(w, type, l) == 0) {
5841                         found = true;
5842                         break;
5843                 }
5844         }
5845
5846         free(p);
5847         return found;
5848 }
5849
5850 bool is_valid_documentation_url(const char *url) {
5851         assert(url);
5852
5853         if (startswith(url, "http://") && url[7])
5854                 return true;
5855
5856         if (startswith(url, "https://") && url[8])
5857                 return true;
5858
5859         if (startswith(url, "file:") && url[5])
5860                 return true;
5861
5862         if (startswith(url, "info:") && url[5])
5863                 return true;
5864
5865         if (startswith(url, "man:") && url[4])
5866                 return true;
5867
5868         return false;
5869 }
5870
5871 bool in_initrd(void) {
5872         static int saved = -1;
5873         struct statfs s;
5874
5875         if (saved >= 0)
5876                 return saved;
5877
5878         /* We make two checks here:
5879          *
5880          * 1. the flag file /etc/initrd-release must exist
5881          * 2. the root file system must be a memory file system
5882          *
5883          * The second check is extra paranoia, since misdetecting an
5884          * initrd can have bad bad consequences due the initrd
5885          * emptying when transititioning to the main systemd.
5886          */
5887
5888         saved = access("/etc/initrd-release", F_OK) >= 0 &&
5889                 statfs("/", &s) >= 0 &&
5890                 (s.f_type == TMPFS_MAGIC || s.f_type == RAMFS_MAGIC);
5891
5892         return saved;
5893 }
5894
5895 void warn_melody(void) {
5896         int fd;
5897
5898         fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
5899         if (fd < 0)
5900                 return;
5901
5902         /* Yeah, this is synchronous. Kinda sucks. Bute well... */
5903
5904         ioctl(fd, KIOCSOUND, (int)(1193180/440));
5905         usleep(125*USEC_PER_MSEC);
5906
5907         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5908         usleep(125*USEC_PER_MSEC);
5909
5910         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5911         usleep(125*USEC_PER_MSEC);
5912
5913         ioctl(fd, KIOCSOUND, 0);
5914         close_nointr_nofail(fd);
5915 }
5916
5917 int make_console_stdio(void) {
5918         int fd, r;
5919
5920         /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5921
5922         fd = acquire_terminal("/dev/console", false, true, true, (usec_t) -1);
5923         if (fd < 0) {
5924                 log_error("Failed to acquire terminal: %s", strerror(-fd));
5925                 return fd;
5926         }
5927
5928         r = make_stdio(fd);
5929         if (r < 0) {
5930                 log_error("Failed to duplicate terminal fd: %s", strerror(-r));
5931                 return r;
5932         }
5933
5934         return 0;
5935 }
5936
5937 int get_home_dir(char **_h) {
5938         char *h;
5939         const char *e;
5940         uid_t u;
5941         struct passwd *p;
5942
5943         assert(_h);
5944
5945         /* Take the user specified one */
5946         e = getenv("HOME");
5947         if (e) {
5948                 h = strdup(e);
5949                 if (!h)
5950                         return -ENOMEM;
5951
5952                 *_h = h;
5953                 return 0;
5954         }
5955
5956         /* Hardcode home directory for root to avoid NSS */
5957         u = getuid();
5958         if (u == 0) {
5959                 h = strdup("/root");
5960                 if (!h)
5961                         return -ENOMEM;
5962
5963                 *_h = h;
5964                 return 0;
5965         }
5966
5967         /* Check the database... */
5968         errno = 0;
5969         p = getpwuid(u);
5970         if (!p)
5971                 return errno ? -errno : -ENOENT;
5972
5973         if (!path_is_absolute(p->pw_dir))
5974                 return -EINVAL;
5975
5976         h = strdup(p->pw_dir);
5977         if (!h)
5978                 return -ENOMEM;
5979
5980         *_h = h;
5981         return 0;
5982 }
5983
5984 int get_shell(char **_sh) {
5985         char *sh;
5986         const char *e;
5987         uid_t u;
5988         struct passwd *p;
5989
5990         assert(_sh);
5991
5992         /* Take the user specified one */
5993         e = getenv("SHELL");
5994         if (e) {
5995                 sh = strdup(e);
5996                 if (!sh)
5997                         return -ENOMEM;
5998
5999                 *_sh = sh;
6000                 return 0;
6001         }
6002
6003         /* Hardcode home directory for root to avoid NSS */
6004         u = getuid();
6005         if (u == 0) {
6006                 sh = strdup("/bin/sh");
6007                 if (!sh)
6008                         return -ENOMEM;
6009
6010                 *_sh = sh;
6011                 return 0;
6012         }
6013
6014         /* Check the database... */
6015         errno = 0;
6016         p = getpwuid(u);
6017         if (!p)
6018                 return errno ? -errno : -ESRCH;
6019
6020         if (!path_is_absolute(p->pw_shell))
6021                 return -EINVAL;
6022
6023         sh = strdup(p->pw_shell);
6024         if (!sh)
6025                 return -ENOMEM;
6026
6027         *_sh = sh;
6028         return 0;
6029 }