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