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