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