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