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