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