chiark / gitweb /
exec: include path name of binary we are about to execute when renaming forked off...
[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         /* This is a like a poor man's setproctitle(). It changes the
3267          * comm field, argv[0], and also the glibc's internally used
3268          * name of the process. For the first one a limit of 16 chars
3269          * applies, to the second one usually one of 10 (i.e. length
3270          * of "/sbin/init"), to the third one one of 7 (i.e. length of
3271          * "systemd"). If you pass a longer string it will be
3272          * truncated */
3273
3274         prctl(PR_SET_NAME, name);
3275
3276         if (program_invocation_name)
3277                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
3278
3279         if (saved_argc > 0) {
3280                 int i;
3281
3282                 if (saved_argv[0])
3283                         strncpy(saved_argv[0], name, strlen(saved_argv[0]));
3284
3285                 for (i = 1; i < saved_argc; i++) {
3286                         if (!saved_argv[i])
3287                                 break;
3288
3289                         memset(saved_argv[i], 0, strlen(saved_argv[i]));
3290                 }
3291         }
3292 }
3293
3294 void sigset_add_many(sigset_t *ss, ...) {
3295         va_list ap;
3296         int sig;
3297
3298         assert(ss);
3299
3300         va_start(ap, ss);
3301         while ((sig = va_arg(ap, int)) > 0)
3302                 assert_se(sigaddset(ss, sig) == 0);
3303         va_end(ap);
3304 }
3305
3306 char* gethostname_malloc(void) {
3307         struct utsname u;
3308
3309         assert_se(uname(&u) >= 0);
3310
3311         if (u.nodename[0])
3312                 return strdup(u.nodename);
3313
3314         return strdup(u.sysname);
3315 }
3316
3317 char* getlogname_malloc(void) {
3318         uid_t uid;
3319         long bufsize;
3320         char *buf, *name;
3321         struct passwd pwbuf, *pw = NULL;
3322         struct stat st;
3323
3324         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
3325                 uid = st.st_uid;
3326         else
3327                 uid = getuid();
3328
3329         /* Shortcut things to avoid NSS lookups */
3330         if (uid == 0)
3331                 return strdup("root");
3332
3333         if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
3334                 bufsize = 4096;
3335
3336         if (!(buf = malloc(bufsize)))
3337                 return NULL;
3338
3339         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
3340                 name = strdup(pw->pw_name);
3341                 free(buf);
3342                 return name;
3343         }
3344
3345         free(buf);
3346
3347         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
3348                 return NULL;
3349
3350         return name;
3351 }
3352
3353 int getttyname_malloc(int fd, char **r) {
3354         char path[PATH_MAX], *c;
3355         int k;
3356
3357         assert(r);
3358
3359         if ((k = ttyname_r(fd, path, sizeof(path))) != 0)
3360                 return -k;
3361
3362         char_array_0(path);
3363
3364         if (!(c = strdup(startswith(path, "/dev/") ? path + 5 : path)))
3365                 return -ENOMEM;
3366
3367         *r = c;
3368         return 0;
3369 }
3370
3371 int getttyname_harder(int fd, char **r) {
3372         int k;
3373         char *s;
3374
3375         if ((k = getttyname_malloc(fd, &s)) < 0)
3376                 return k;
3377
3378         if (streq(s, "tty")) {
3379                 free(s);
3380                 return get_ctty(0, NULL, r);
3381         }
3382
3383         *r = s;
3384         return 0;
3385 }
3386
3387 int get_ctty_devnr(pid_t pid, dev_t *d) {
3388         int k;
3389         char line[LINE_MAX], *p, *fn;
3390         unsigned long ttynr;
3391         FILE *f;
3392
3393         if (asprintf(&fn, "/proc/%lu/stat", (unsigned long) (pid <= 0 ? getpid() : pid)) < 0)
3394                 return -ENOMEM;
3395
3396         f = fopen(fn, "re");
3397         free(fn);
3398         if (!f)
3399                 return -errno;
3400
3401         if (!fgets(line, sizeof(line), f)) {
3402                 k = feof(f) ? -EIO : -errno;
3403                 fclose(f);
3404                 return k;
3405         }
3406
3407         fclose(f);
3408
3409         p = strrchr(line, ')');
3410         if (!p)
3411                 return -EIO;
3412
3413         p++;
3414
3415         if (sscanf(p, " "
3416                    "%*c "  /* state */
3417                    "%*d "  /* ppid */
3418                    "%*d "  /* pgrp */
3419                    "%*d "  /* session */
3420                    "%lu ", /* ttynr */
3421                    &ttynr) != 1)
3422                 return -EIO;
3423
3424         *d = (dev_t) ttynr;
3425         return 0;
3426 }
3427
3428 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
3429         int k;
3430         char fn[PATH_MAX], *s, *b, *p;
3431         dev_t devnr;
3432
3433         assert(r);
3434
3435         k = get_ctty_devnr(pid, &devnr);
3436         if (k < 0)
3437                 return k;
3438
3439         snprintf(fn, sizeof(fn), "/dev/char/%u:%u", major(devnr), minor(devnr));
3440         char_array_0(fn);
3441
3442         if ((k = readlink_malloc(fn, &s)) < 0) {
3443
3444                 if (k != -ENOENT)
3445                         return k;
3446
3447                 /* This is an ugly hack */
3448                 if (major(devnr) == 136) {
3449                         if (asprintf(&b, "pts/%lu", (unsigned long) minor(devnr)) < 0)
3450                                 return -ENOMEM;
3451
3452                         *r = b;
3453                         if (_devnr)
3454                                 *_devnr = devnr;
3455
3456                         return 0;
3457                 }
3458
3459                 /* Probably something like the ptys which have no
3460                  * symlink in /dev/char. Let's return something
3461                  * vaguely useful. */
3462
3463                 if (!(b = strdup(fn + 5)))
3464                         return -ENOMEM;
3465
3466                 *r = b;
3467                 if (_devnr)
3468                         *_devnr = devnr;
3469
3470                 return 0;
3471         }
3472
3473         if (startswith(s, "/dev/"))
3474                 p = s + 5;
3475         else if (startswith(s, "../"))
3476                 p = s + 3;
3477         else
3478                 p = s;
3479
3480         b = strdup(p);
3481         free(s);
3482
3483         if (!b)
3484                 return -ENOMEM;
3485
3486         *r = b;
3487         if (_devnr)
3488                 *_devnr = devnr;
3489
3490         return 0;
3491 }
3492
3493 static int rm_rf_children(int fd, bool only_dirs, bool honour_sticky) {
3494         DIR *d;
3495         int ret = 0;
3496
3497         assert(fd >= 0);
3498
3499         /* This returns the first error we run into, but nevertheless
3500          * tries to go on */
3501
3502         if (!(d = fdopendir(fd))) {
3503                 close_nointr_nofail(fd);
3504
3505                 return errno == ENOENT ? 0 : -errno;
3506         }
3507
3508         for (;;) {
3509                 struct dirent buf, *de;
3510                 bool is_dir, keep_around = false;
3511                 int r;
3512
3513                 if ((r = readdir_r(d, &buf, &de)) != 0) {
3514                         if (ret == 0)
3515                                 ret = -r;
3516                         break;
3517                 }
3518
3519                 if (!de)
3520                         break;
3521
3522                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
3523                         continue;
3524
3525                 if (de->d_type == DT_UNKNOWN) {
3526                         struct stat st;
3527
3528                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3529                                 if (ret == 0 && errno != ENOENT)
3530                                         ret = -errno;
3531                                 continue;
3532                         }
3533
3534                         if (honour_sticky)
3535                                 keep_around =
3536                                         (st.st_uid == 0 || st.st_uid == getuid()) &&
3537                                         (st.st_mode & S_ISVTX);
3538
3539                         is_dir = S_ISDIR(st.st_mode);
3540
3541                 } else {
3542                         if (honour_sticky) {
3543                                 struct stat st;
3544
3545                                 if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
3546                                         if (ret == 0 && errno != ENOENT)
3547                                                 ret = -errno;
3548                                         continue;
3549                                 }
3550
3551                                 keep_around =
3552                                         (st.st_uid == 0 || st.st_uid == getuid()) &&
3553                                         (st.st_mode & S_ISVTX);
3554                         }
3555
3556                         is_dir = de->d_type == DT_DIR;
3557                 }
3558
3559                 if (is_dir) {
3560                         int subdir_fd;
3561
3562                         if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3563                                 if (ret == 0 && errno != ENOENT)
3564                                         ret = -errno;
3565                                 continue;
3566                         }
3567
3568                         if ((r = rm_rf_children(subdir_fd, only_dirs, honour_sticky)) < 0) {
3569                                 if (ret == 0)
3570                                         ret = r;
3571                         }
3572
3573                         if (!keep_around)
3574                                 if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
3575                                         if (ret == 0 && errno != ENOENT)
3576                                                 ret = -errno;
3577                                 }
3578
3579                 } else if (!only_dirs && !keep_around) {
3580
3581                         if (unlinkat(fd, de->d_name, 0) < 0) {
3582                                 if (ret == 0 && errno != ENOENT)
3583                                         ret = -errno;
3584                         }
3585                 }
3586         }
3587
3588         closedir(d);
3589
3590         return ret;
3591 }
3592
3593 int rm_rf(const char *path, bool only_dirs, bool delete_root, bool honour_sticky) {
3594         int fd;
3595         int r;
3596
3597         assert(path);
3598
3599         if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
3600
3601                 if (errno != ENOTDIR)
3602                         return -errno;
3603
3604                 if (delete_root && !only_dirs)
3605                         if (unlink(path) < 0)
3606                                 return -errno;
3607
3608                 return 0;
3609         }
3610
3611         r = rm_rf_children(fd, only_dirs, honour_sticky);
3612
3613         if (delete_root) {
3614
3615                 if (honour_sticky && file_is_priv_sticky(path) > 0)
3616                         return r;
3617
3618                 if (rmdir(path) < 0 && errno != ENOENT) {
3619                         if (r == 0)
3620                                 r = -errno;
3621                 }
3622         }
3623
3624         return r;
3625 }
3626
3627 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
3628         assert(path);
3629
3630         /* Under the assumption that we are running privileged we
3631          * first change the access mode and only then hand out
3632          * ownership to avoid a window where access is too open. */
3633
3634         if (mode != (mode_t) -1)
3635                 if (chmod(path, mode) < 0)
3636                         return -errno;
3637
3638         if (uid != (uid_t) -1 || gid != (gid_t) -1)
3639                 if (chown(path, uid, gid) < 0)
3640                         return -errno;
3641
3642         return 0;
3643 }
3644
3645 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
3646         assert(fd >= 0);
3647
3648         /* Under the assumption that we are running privileged we
3649          * first change the access mode and only then hand out
3650          * ownership to avoid a window where access is too open. */
3651
3652         if (fchmod(fd, mode) < 0)
3653                 return -errno;
3654
3655         if (fchown(fd, uid, gid) < 0)
3656                 return -errno;
3657
3658         return 0;
3659 }
3660
3661 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
3662         cpu_set_t *r;
3663         unsigned n = 1024;
3664
3665         /* Allocates the cpuset in the right size */
3666
3667         for (;;) {
3668                 if (!(r = CPU_ALLOC(n)))
3669                         return NULL;
3670
3671                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
3672                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
3673
3674                         if (ncpus)
3675                                 *ncpus = n;
3676
3677                         return r;
3678                 }
3679
3680                 CPU_FREE(r);
3681
3682                 if (errno != EINVAL)
3683                         return NULL;
3684
3685                 n *= 2;
3686         }
3687 }
3688
3689 void status_vprintf(const char *status, bool ellipse, const char *format, va_list ap) {
3690         char *s = NULL, *spaces = NULL, *e;
3691         int fd = -1, c;
3692         size_t emax, sl, left;
3693         struct iovec iovec[5];
3694         int n = 0;
3695
3696         assert(format);
3697
3698         /* This independent of logging, as status messages are
3699          * optional and go exclusively to the console. */
3700
3701         if (vasprintf(&s, format, ap) < 0)
3702                 goto finish;
3703
3704         fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3705         if (fd < 0)
3706                 goto finish;
3707
3708         if (ellipse) {
3709                 c = fd_columns(fd);
3710                 if (c <= 0)
3711                         c = 80;
3712
3713                 if (status) {
3714                         sl = 2 + 6 + 1; /* " [" status "]" */
3715                         emax = (size_t) c > sl ? c - sl - 1 : 0;
3716                 } else
3717                         emax = c - 1;
3718
3719                 e = ellipsize(s, emax, 75);
3720                 if (e) {
3721                         free(s);
3722                         s = e;
3723                 }
3724         }
3725
3726         zero(iovec);
3727         IOVEC_SET_STRING(iovec[n++], s);
3728
3729         if (ellipse) {
3730                 sl = strlen(s);
3731                 left = emax > sl ? emax - sl : 0;
3732                 if (left > 0) {
3733                         spaces = malloc(left);
3734                         if (spaces) {
3735                                 memset(spaces, ' ', left);
3736                                 iovec[n].iov_base = spaces;
3737                                 iovec[n].iov_len = left;
3738                                 n++;
3739                         }
3740                 }
3741         }
3742
3743         if (status) {
3744                 IOVEC_SET_STRING(iovec[n++], " [");
3745                 IOVEC_SET_STRING(iovec[n++], status);
3746                 IOVEC_SET_STRING(iovec[n++], "]\n");
3747         } else
3748                 IOVEC_SET_STRING(iovec[n++], "\n");
3749
3750         writev(fd, iovec, n);
3751
3752 finish:
3753         free(s);
3754         free(spaces);
3755
3756         if (fd >= 0)
3757                 close_nointr_nofail(fd);
3758 }
3759
3760 void status_printf(const char *status, bool ellipse, const char *format, ...) {
3761         va_list ap;
3762
3763         assert(format);
3764
3765         va_start(ap, format);
3766         status_vprintf(status, ellipse, format, ap);
3767         va_end(ap);
3768 }
3769
3770 void status_welcome(void) {
3771         char *pretty_name = NULL, *ansi_color = NULL;
3772         const char *const_pretty = NULL, *const_color = NULL;
3773         int r;
3774
3775         if ((r = parse_env_file("/etc/os-release", NEWLINE,
3776                                 "PRETTY_NAME", &pretty_name,
3777                                 "ANSI_COLOR", &ansi_color,
3778                                 NULL)) < 0) {
3779
3780                 if (r != -ENOENT)
3781                         log_warning("Failed to read /etc/os-release: %s", strerror(-r));
3782         }
3783
3784 #if defined(TARGET_FEDORA)
3785         if (!pretty_name) {
3786                 if ((r = read_one_line_file("/etc/system-release", &pretty_name)) < 0) {
3787
3788                         if (r != -ENOENT)
3789                                 log_warning("Failed to read /etc/system-release: %s", strerror(-r));
3790                 }
3791         }
3792
3793         if (!ansi_color && pretty_name) {
3794
3795                 /* This tries to mimic the color magic the old Red Hat sysinit
3796                  * script did. */
3797
3798                 if (startswith(pretty_name, "Red Hat"))
3799                         const_color = "0;31"; /* Red for RHEL */
3800                 else if (startswith(pretty_name, "Fedora"))
3801                         const_color = "0;34"; /* Blue for Fedora */
3802         }
3803
3804 #elif defined(TARGET_SUSE)
3805
3806         if (!pretty_name) {
3807                 if ((r = read_one_line_file("/etc/SuSE-release", &pretty_name)) < 0) {
3808
3809                         if (r != -ENOENT)
3810                                 log_warning("Failed to read /etc/SuSE-release: %s", strerror(-r));
3811                 }
3812         }
3813
3814         if (!ansi_color)
3815                 const_color = "0;32"; /* Green for openSUSE */
3816
3817 #elif defined(TARGET_GENTOO)
3818
3819         if (!pretty_name) {
3820                 if ((r = read_one_line_file("/etc/gentoo-release", &pretty_name)) < 0) {
3821
3822                         if (r != -ENOENT)
3823                                 log_warning("Failed to read /etc/gentoo-release: %s", strerror(-r));
3824                 }
3825         }
3826
3827         if (!ansi_color)
3828                 const_color = "1;34"; /* Light Blue for Gentoo */
3829
3830 #elif defined(TARGET_ALTLINUX)
3831
3832         if (!pretty_name) {
3833                 if ((r = read_one_line_file("/etc/altlinux-release", &pretty_name)) < 0) {
3834
3835                         if (r != -ENOENT)
3836                                 log_warning("Failed to read /etc/altlinux-release: %s", strerror(-r));
3837                 }
3838         }
3839
3840         if (!ansi_color)
3841                 const_color = "0;36"; /* Cyan for ALTLinux */
3842
3843
3844 #elif defined(TARGET_DEBIAN)
3845
3846         if (!pretty_name) {
3847                 char *version;
3848
3849                 if ((r = read_one_line_file("/etc/debian_version", &version)) < 0) {
3850
3851                         if (r != -ENOENT)
3852                                 log_warning("Failed to read /etc/debian_version: %s", strerror(-r));
3853                 } else {
3854                         pretty_name = strappend("Debian ", version);
3855                         free(version);
3856
3857                         if (!pretty_name)
3858                                 log_warning("Failed to allocate Debian version string.");
3859                 }
3860         }
3861
3862         if (!ansi_color)
3863                 const_color = "1;31"; /* Light Red for Debian */
3864
3865 #elif defined(TARGET_UBUNTU)
3866
3867         if ((r = parse_env_file("/etc/lsb-release", NEWLINE,
3868                                 "DISTRIB_DESCRIPTION", &pretty_name,
3869                                 NULL)) < 0) {
3870
3871                 if (r != -ENOENT)
3872                         log_warning("Failed to read /etc/lsb-release: %s", strerror(-r));
3873         }
3874
3875         if (!ansi_color)
3876                 const_color = "0;33"; /* Orange/Brown for Ubuntu */
3877
3878 #elif defined(TARGET_MANDRIVA)
3879
3880         if (!pretty_name) {
3881                 char *s, *p;
3882
3883                 if ((r = read_one_line_file("/etc/mandriva-release", &s) < 0)) {
3884                         if (r != -ENOENT)
3885                                 log_warning("Failed to read /etc/mandriva-release: %s", strerror(-r));
3886                 } else {
3887                         p = strstr(s, " release ");
3888                         if (p) {
3889                                 *p = '\0';
3890                                 p += 9;
3891                                 p[strcspn(p, " ")] = '\0';
3892
3893                                 /* This corresponds to standard rc.sysinit */
3894                                 if (asprintf(&pretty_name, "%s\x1B[0;39m %s", s, p) > 0)
3895                                         const_color = "1;36";
3896                                 else
3897                                         log_warning("Failed to allocate Mandriva version string.");
3898                         } else
3899                                 log_warning("Failed to parse /etc/mandriva-release");
3900                         free(s);
3901                 }
3902         }
3903 #elif defined(TARGET_MEEGO)
3904
3905         if (!pretty_name) {
3906                 if ((r = read_one_line_file("/etc/meego-release", &pretty_name)) < 0) {
3907
3908                         if (r != -ENOENT)
3909                                 log_warning("Failed to read /etc/meego-release: %s", strerror(-r));
3910                 }
3911         }
3912
3913        if (!ansi_color)
3914                const_color = "1;35"; /* Bright Magenta for MeeGo */
3915 #endif
3916
3917         if (!pretty_name && !const_pretty)
3918                 const_pretty = "Linux";
3919
3920         if (!ansi_color && !const_color)
3921                 const_color = "1";
3922
3923         status_printf(NULL,
3924                       false,
3925                       "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3926                       const_color ? const_color : ansi_color,
3927                       const_pretty ? const_pretty : pretty_name);
3928
3929         free(ansi_color);
3930         free(pretty_name);
3931 }
3932
3933 char *replace_env(const char *format, char **env) {
3934         enum {
3935                 WORD,
3936                 CURLY,
3937                 VARIABLE
3938         } state = WORD;
3939
3940         const char *e, *word = format;
3941         char *r = NULL, *k;
3942
3943         assert(format);
3944
3945         for (e = format; *e; e ++) {
3946
3947                 switch (state) {
3948
3949                 case WORD:
3950                         if (*e == '$')
3951                                 state = CURLY;
3952                         break;
3953
3954                 case CURLY:
3955                         if (*e == '{') {
3956                                 if (!(k = strnappend(r, word, e-word-1)))
3957                                         goto fail;
3958
3959                                 free(r);
3960                                 r = k;
3961
3962                                 word = e-1;
3963                                 state = VARIABLE;
3964
3965                         } else if (*e == '$') {
3966                                 if (!(k = strnappend(r, word, e-word)))
3967                                         goto fail;
3968
3969                                 free(r);
3970                                 r = k;
3971
3972                                 word = e+1;
3973                                 state = WORD;
3974                         } else
3975                                 state = WORD;
3976                         break;
3977
3978                 case VARIABLE:
3979                         if (*e == '}') {
3980                                 const char *t;
3981
3982                                 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3983                                         t = "";
3984
3985                                 if (!(k = strappend(r, t)))
3986                                         goto fail;
3987
3988                                 free(r);
3989                                 r = k;
3990
3991                                 word = e+1;
3992                                 state = WORD;
3993                         }
3994                         break;
3995                 }
3996         }
3997
3998         if (!(k = strnappend(r, word, e-word)))
3999                 goto fail;
4000
4001         free(r);
4002         return k;
4003
4004 fail:
4005         free(r);
4006         return NULL;
4007 }
4008
4009 char **replace_env_argv(char **argv, char **env) {
4010         char **r, **i;
4011         unsigned k = 0, l = 0;
4012
4013         l = strv_length(argv);
4014
4015         if (!(r = new(char*, l+1)))
4016                 return NULL;
4017
4018         STRV_FOREACH(i, argv) {
4019
4020                 /* If $FOO appears as single word, replace it by the split up variable */
4021                 if ((*i)[0] == '$' && (*i)[1] != '{') {
4022                         char *e;
4023                         char **w, **m;
4024                         unsigned q;
4025
4026                         if ((e = strv_env_get(env, *i+1))) {
4027
4028                                 if (!(m = strv_split_quoted(e))) {
4029                                         r[k] = NULL;
4030                                         strv_free(r);
4031                                         return NULL;
4032                                 }
4033                         } else
4034                                 m = NULL;
4035
4036                         q = strv_length(m);
4037                         l = l + q - 1;
4038
4039                         if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
4040                                 r[k] = NULL;
4041                                 strv_free(r);
4042                                 strv_free(m);
4043                                 return NULL;
4044                         }
4045
4046                         r = w;
4047                         if (m) {
4048                                 memcpy(r + k, m, q * sizeof(char*));
4049                                 free(m);
4050                         }
4051
4052                         k += q;
4053                         continue;
4054                 }
4055
4056                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
4057                 if (!(r[k++] = replace_env(*i, env))) {
4058                         strv_free(r);
4059                         return NULL;
4060                 }
4061         }
4062
4063         r[k] = NULL;
4064         return r;
4065 }
4066
4067 int fd_columns(int fd) {
4068         struct winsize ws;
4069         zero(ws);
4070
4071         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
4072                 return -errno;
4073
4074         if (ws.ws_col <= 0)
4075                 return -EIO;
4076
4077         return ws.ws_col;
4078 }
4079
4080 unsigned columns(void) {
4081         static __thread int parsed_columns = 0;
4082         const char *e;
4083
4084         if (_likely_(parsed_columns > 0))
4085                 return parsed_columns;
4086
4087         e = getenv("COLUMNS");
4088         if (e)
4089                 parsed_columns = atoi(e);
4090
4091         if (parsed_columns <= 0)
4092                 parsed_columns = fd_columns(STDOUT_FILENO);
4093
4094         if (parsed_columns <= 0)
4095                 parsed_columns = 80;
4096
4097         return parsed_columns;
4098 }
4099
4100 int fd_lines(int fd) {
4101         struct winsize ws;
4102         zero(ws);
4103
4104         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
4105                 return -errno;
4106
4107         if (ws.ws_row <= 0)
4108                 return -EIO;
4109
4110         return ws.ws_row;
4111 }
4112
4113 unsigned lines(void) {
4114         static __thread int parsed_lines = 0;
4115         const char *e;
4116
4117         if (_likely_(parsed_lines > 0))
4118                 return parsed_lines;
4119
4120         e = getenv("LINES");
4121         if (e)
4122                 parsed_lines = atoi(e);
4123
4124         if (parsed_lines <= 0)
4125                 parsed_lines = fd_lines(STDOUT_FILENO);
4126
4127         if (parsed_lines <= 0)
4128                 parsed_lines = 25;
4129
4130         return parsed_lines;
4131 }
4132
4133 int running_in_chroot(void) {
4134         struct stat a, b;
4135
4136         zero(a);
4137         zero(b);
4138
4139         /* Only works as root */
4140
4141         if (stat("/proc/1/root", &a) < 0)
4142                 return -errno;
4143
4144         if (stat("/", &b) < 0)
4145                 return -errno;
4146
4147         return
4148                 a.st_dev != b.st_dev ||
4149                 a.st_ino != b.st_ino;
4150 }
4151
4152 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
4153         size_t x;
4154         char *r;
4155
4156         assert(s);
4157         assert(percent <= 100);
4158         assert(new_length >= 3);
4159
4160         if (old_length <= 3 || old_length <= new_length)
4161                 return strndup(s, old_length);
4162
4163         r = new0(char, new_length+1);
4164         if (!r)
4165                 return r;
4166
4167         x = (new_length * percent) / 100;
4168
4169         if (x > new_length - 3)
4170                 x = new_length - 3;
4171
4172         memcpy(r, s, x);
4173         r[x] = '.';
4174         r[x+1] = '.';
4175         r[x+2] = '.';
4176         memcpy(r + x + 3,
4177                s + old_length - (new_length - x - 3),
4178                new_length - x - 3);
4179
4180         return r;
4181 }
4182
4183 char *ellipsize(const char *s, size_t length, unsigned percent) {
4184         return ellipsize_mem(s, strlen(s), length, percent);
4185 }
4186
4187 int touch(const char *path) {
4188         int fd;
4189
4190         assert(path);
4191
4192         if ((fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0644)) < 0)
4193                 return -errno;
4194
4195         close_nointr_nofail(fd);
4196         return 0;
4197 }
4198
4199 char *unquote(const char *s, const char* quotes) {
4200         size_t l;
4201         assert(s);
4202
4203         l = strlen(s);
4204         if (l < 2)
4205                 return strdup(s);
4206
4207         if (strchr(quotes, s[0]) && s[l-1] == s[0])
4208                 return strndup(s+1, l-2);
4209
4210         return strdup(s);
4211 }
4212
4213 char *normalize_env_assignment(const char *s) {
4214         char *name, *value, *p, *r;
4215
4216         p = strchr(s, '=');
4217
4218         if (!p) {
4219                 if (!(r = strdup(s)))
4220                         return NULL;
4221
4222                 return strstrip(r);
4223         }
4224
4225         if (!(name = strndup(s, p - s)))
4226                 return NULL;
4227
4228         if (!(p = strdup(p+1))) {
4229                 free(name);
4230                 return NULL;
4231         }
4232
4233         value = unquote(strstrip(p), QUOTES);
4234         free(p);
4235
4236         if (!value) {
4237                 free(name);
4238                 return NULL;
4239         }
4240
4241         if (asprintf(&r, "%s=%s", name, value) < 0)
4242                 r = NULL;
4243
4244         free(value);
4245         free(name);
4246
4247         return r;
4248 }
4249
4250 int wait_for_terminate(pid_t pid, siginfo_t *status) {
4251         siginfo_t dummy;
4252
4253         assert(pid >= 1);
4254
4255         if (!status)
4256                 status = &dummy;
4257
4258         for (;;) {
4259                 zero(*status);
4260
4261                 if (waitid(P_PID, pid, status, WEXITED) < 0) {
4262
4263                         if (errno == EINTR)
4264                                 continue;
4265
4266                         return -errno;
4267                 }
4268
4269                 return 0;
4270         }
4271 }
4272
4273 int wait_for_terminate_and_warn(const char *name, pid_t pid) {
4274         int r;
4275         siginfo_t status;
4276
4277         assert(name);
4278         assert(pid > 1);
4279
4280         if ((r = wait_for_terminate(pid, &status)) < 0) {
4281                 log_warning("Failed to wait for %s: %s", name, strerror(-r));
4282                 return r;
4283         }
4284
4285         if (status.si_code == CLD_EXITED) {
4286                 if (status.si_status != 0) {
4287                         log_warning("%s failed with error code %i.", name, status.si_status);
4288                         return status.si_status;
4289                 }
4290
4291                 log_debug("%s succeeded.", name);
4292                 return 0;
4293
4294         } else if (status.si_code == CLD_KILLED ||
4295                    status.si_code == CLD_DUMPED) {
4296
4297                 log_warning("%s terminated by signal %s.", name, signal_to_string(status.si_status));
4298                 return -EPROTO;
4299         }
4300
4301         log_warning("%s failed due to unknown reason.", name);
4302         return -EPROTO;
4303
4304 }
4305
4306 void freeze(void) {
4307
4308         /* Make sure nobody waits for us on a socket anymore */
4309         close_all_fds(NULL, 0);
4310
4311         sync();
4312
4313         for (;;)
4314                 pause();
4315 }
4316
4317 bool null_or_empty(struct stat *st) {
4318         assert(st);
4319
4320         if (S_ISREG(st->st_mode) && st->st_size <= 0)
4321                 return true;
4322
4323         if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
4324                 return true;
4325
4326         return false;
4327 }
4328
4329 int null_or_empty_path(const char *fn) {
4330         struct stat st;
4331
4332         assert(fn);
4333
4334         if (stat(fn, &st) < 0)
4335                 return -errno;
4336
4337         return null_or_empty(&st);
4338 }
4339
4340 DIR *xopendirat(int fd, const char *name, int flags) {
4341         int nfd;
4342         DIR *d;
4343
4344         if ((nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags)) < 0)
4345                 return NULL;
4346
4347         if (!(d = fdopendir(nfd))) {
4348                 close_nointr_nofail(nfd);
4349                 return NULL;
4350         }
4351
4352         return d;
4353 }
4354
4355 int signal_from_string_try_harder(const char *s) {
4356         int signo;
4357         assert(s);
4358
4359         if ((signo = signal_from_string(s)) <= 0)
4360                 if (startswith(s, "SIG"))
4361                         return signal_from_string(s+3);
4362
4363         return signo;
4364 }
4365
4366 void dual_timestamp_serialize(FILE *f, const char *name, dual_timestamp *t) {
4367
4368         assert(f);
4369         assert(name);
4370         assert(t);
4371
4372         if (!dual_timestamp_is_set(t))
4373                 return;
4374
4375         fprintf(f, "%s=%llu %llu\n",
4376                 name,
4377                 (unsigned long long) t->realtime,
4378                 (unsigned long long) t->monotonic);
4379 }
4380
4381 void dual_timestamp_deserialize(const char *value, dual_timestamp *t) {
4382         unsigned long long a, b;
4383
4384         assert(value);
4385         assert(t);
4386
4387         if (sscanf(value, "%lli %llu", &a, &b) != 2)
4388                 log_debug("Failed to parse finish timestamp value %s", value);
4389         else {
4390                 t->realtime = a;
4391                 t->monotonic = b;
4392         }
4393 }
4394
4395 char *fstab_node_to_udev_node(const char *p) {
4396         char *dn, *t, *u;
4397         int r;
4398
4399         /* FIXME: to follow udev's logic 100% we need to leave valid
4400          * UTF8 chars unescaped */
4401
4402         if (startswith(p, "LABEL=")) {
4403
4404                 if (!(u = unquote(p+6, "\"\'")))
4405                         return NULL;
4406
4407                 t = xescape(u, "/ ");
4408                 free(u);
4409
4410                 if (!t)
4411                         return NULL;
4412
4413                 r = asprintf(&dn, "/dev/disk/by-label/%s", t);
4414                 free(t);
4415
4416                 if (r < 0)
4417                         return NULL;
4418
4419                 return dn;
4420         }
4421
4422         if (startswith(p, "UUID=")) {
4423
4424                 if (!(u = unquote(p+5, "\"\'")))
4425                         return NULL;
4426
4427                 t = xescape(u, "/ ");
4428                 free(u);
4429
4430                 if (!t)
4431                         return NULL;
4432
4433                 r = asprintf(&dn, "/dev/disk/by-uuid/%s", t);
4434                 free(t);
4435
4436                 if (r < 0)
4437                         return NULL;
4438
4439                 return dn;
4440         }
4441
4442         return strdup(p);
4443 }
4444
4445 void filter_environ(const char *prefix) {
4446         int i, j;
4447         assert(prefix);
4448
4449         if (!environ)
4450                 return;
4451
4452         for (i = 0, j = 0; environ[i]; i++) {
4453
4454                 if (startswith(environ[i], prefix))
4455                         continue;
4456
4457                 environ[j++] = environ[i];
4458         }
4459
4460         environ[j] = NULL;
4461 }
4462
4463 bool tty_is_vc(const char *tty) {
4464         assert(tty);
4465
4466         if (startswith(tty, "/dev/"))
4467                 tty += 5;
4468
4469         return vtnr_from_tty(tty) >= 0;
4470 }
4471
4472 int vtnr_from_tty(const char *tty) {
4473         int i, r;
4474
4475         assert(tty);
4476
4477         if (startswith(tty, "/dev/"))
4478                 tty += 5;
4479
4480         if (!startswith(tty, "tty") )
4481                 return -EINVAL;
4482
4483         if (tty[3] < '0' || tty[3] > '9')
4484                 return -EINVAL;
4485
4486         r = safe_atoi(tty+3, &i);
4487         if (r < 0)
4488                 return r;
4489
4490         if (i < 0 || i > 63)
4491                 return -EINVAL;
4492
4493         return i;
4494 }
4495
4496 bool tty_is_vc_resolve(const char *tty) {
4497         char *active = NULL;
4498         bool b;
4499
4500         assert(tty);
4501
4502         if (startswith(tty, "/dev/"))
4503                 tty += 5;
4504
4505         /* Resolve where /dev/console is pointing to */
4506         if (streq(tty, "console"))
4507                 if (read_one_line_file("/sys/class/tty/console/active", &active) >= 0) {
4508                         /* If multiple log outputs are configured the
4509                          * last one is what /dev/console points to */
4510                         tty = strrchr(active, ' ');
4511                         if (tty)
4512                                 tty++;
4513                         else
4514                                 tty = active;
4515                 }
4516
4517         b = tty_is_vc(tty);
4518         free(active);
4519
4520         return b;
4521 }
4522
4523 const char *default_term_for_tty(const char *tty) {
4524         assert(tty);
4525
4526         return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt100";
4527 }
4528
4529 bool dirent_is_file(const struct dirent *de) {
4530         assert(de);
4531
4532         if (ignore_file(de->d_name))
4533                 return false;
4534
4535         if (de->d_type != DT_REG &&
4536             de->d_type != DT_LNK &&
4537             de->d_type != DT_UNKNOWN)
4538                 return false;
4539
4540         return true;
4541 }
4542
4543 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
4544         assert(de);
4545
4546         if (!dirent_is_file(de))
4547                 return false;
4548
4549         return endswith(de->d_name, suffix);
4550 }
4551
4552 void execute_directory(const char *directory, DIR *d, char *argv[]) {
4553         DIR *_d = NULL;
4554         struct dirent *de;
4555         Hashmap *pids = NULL;
4556
4557         assert(directory);
4558
4559         /* Executes all binaries in a directory in parallel and waits
4560          * until all they all finished. */
4561
4562         if (!d) {
4563                 if (!(_d = opendir(directory))) {
4564
4565                         if (errno == ENOENT)
4566                                 return;
4567
4568                         log_error("Failed to enumerate directory %s: %m", directory);
4569                         return;
4570                 }
4571
4572                 d = _d;
4573         }
4574
4575         if (!(pids = hashmap_new(trivial_hash_func, trivial_compare_func))) {
4576                 log_error("Failed to allocate set.");
4577                 goto finish;
4578         }
4579
4580         while ((de = readdir(d))) {
4581                 char *path;
4582                 pid_t pid;
4583                 int k;
4584
4585                 if (!dirent_is_file(de))
4586                         continue;
4587
4588                 if (asprintf(&path, "%s/%s", directory, de->d_name) < 0) {
4589                         log_error("Out of memory");
4590                         continue;
4591                 }
4592
4593                 if ((pid = fork()) < 0) {
4594                         log_error("Failed to fork: %m");
4595                         free(path);
4596                         continue;
4597                 }
4598
4599                 if (pid == 0) {
4600                         char *_argv[2];
4601                         /* Child */
4602
4603                         if (!argv) {
4604                                 _argv[0] = path;
4605                                 _argv[1] = NULL;
4606                                 argv = _argv;
4607                         } else
4608                                 if (!argv[0])
4609                                         argv[0] = path;
4610
4611                         execv(path, argv);
4612
4613                         log_error("Failed to execute %s: %m", path);
4614                         _exit(EXIT_FAILURE);
4615                 }
4616
4617                 log_debug("Spawned %s as %lu", path, (unsigned long) pid);
4618
4619                 if ((k = hashmap_put(pids, UINT_TO_PTR(pid), path)) < 0) {
4620                         log_error("Failed to add PID to set: %s", strerror(-k));
4621                         free(path);
4622                 }
4623         }
4624
4625         while (!hashmap_isempty(pids)) {
4626                 siginfo_t si;
4627                 char *path;
4628
4629                 zero(si);
4630                 if (waitid(P_ALL, 0, &si, WEXITED) < 0) {
4631
4632                         if (errno == EINTR)
4633                                 continue;
4634
4635                         log_error("waitid() failed: %m");
4636                         goto finish;
4637                 }
4638
4639                 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4640                         if (!is_clean_exit(si.si_code, si.si_status)) {
4641                                 if (si.si_code == CLD_EXITED)
4642                                         log_error("%s exited with exit status %i.", path, si.si_status);
4643                                 else
4644                                         log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4645                         } else
4646                                 log_debug("%s exited successfully.", path);
4647
4648                         free(path);
4649                 }
4650         }
4651
4652 finish:
4653         if (_d)
4654                 closedir(_d);
4655
4656         if (pids)
4657                 hashmap_free_free(pids);
4658 }
4659
4660 int kill_and_sigcont(pid_t pid, int sig) {
4661         int r;
4662
4663         r = kill(pid, sig) < 0 ? -errno : 0;
4664
4665         if (r >= 0)
4666                 kill(pid, SIGCONT);
4667
4668         return r;
4669 }
4670
4671 bool nulstr_contains(const char*nulstr, const char *needle) {
4672         const char *i;
4673
4674         if (!nulstr)
4675                 return false;
4676
4677         NULSTR_FOREACH(i, nulstr)
4678                 if (streq(i, needle))
4679                         return true;
4680
4681         return false;
4682 }
4683
4684 bool plymouth_running(void) {
4685         return access("/run/plymouth/pid", F_OK) >= 0;
4686 }
4687
4688 void parse_syslog_priority(char **p, int *priority) {
4689         int a = 0, b = 0, c = 0;
4690         int k;
4691
4692         assert(p);
4693         assert(*p);
4694         assert(priority);
4695
4696         if ((*p)[0] != '<')
4697                 return;
4698
4699         if (!strchr(*p, '>'))
4700                 return;
4701
4702         if ((*p)[2] == '>') {
4703                 c = undecchar((*p)[1]);
4704                 k = 3;
4705         } else if ((*p)[3] == '>') {
4706                 b = undecchar((*p)[1]);
4707                 c = undecchar((*p)[2]);
4708                 k = 4;
4709         } else if ((*p)[4] == '>') {
4710                 a = undecchar((*p)[1]);
4711                 b = undecchar((*p)[2]);
4712                 c = undecchar((*p)[3]);
4713                 k = 5;
4714         } else
4715                 return;
4716
4717         if (a < 0 || b < 0 || c < 0)
4718                 return;
4719
4720         *priority = a*100+b*10+c;
4721         *p += k;
4722 }
4723
4724 void skip_syslog_pid(char **buf) {
4725         char *p;
4726
4727         assert(buf);
4728         assert(*buf);
4729
4730         p = *buf;
4731
4732         if (*p != '[')
4733                 return;
4734
4735         p++;
4736         p += strspn(p, "0123456789");
4737
4738         if (*p != ']')
4739                 return;
4740
4741         p++;
4742
4743         *buf = p;
4744 }
4745
4746 void skip_syslog_date(char **buf) {
4747         enum {
4748                 LETTER,
4749                 SPACE,
4750                 NUMBER,
4751                 SPACE_OR_NUMBER,
4752                 COLON
4753         } sequence[] = {
4754                 LETTER, LETTER, LETTER,
4755                 SPACE,
4756                 SPACE_OR_NUMBER, NUMBER,
4757                 SPACE,
4758                 SPACE_OR_NUMBER, NUMBER,
4759                 COLON,
4760                 SPACE_OR_NUMBER, NUMBER,
4761                 COLON,
4762                 SPACE_OR_NUMBER, NUMBER,
4763                 SPACE
4764         };
4765
4766         char *p;
4767         unsigned i;
4768
4769         assert(buf);
4770         assert(*buf);
4771
4772         p = *buf;
4773
4774         for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
4775
4776                 if (!*p)
4777                         return;
4778
4779                 switch (sequence[i]) {
4780
4781                 case SPACE:
4782                         if (*p != ' ')
4783                                 return;
4784                         break;
4785
4786                 case SPACE_OR_NUMBER:
4787                         if (*p == ' ')
4788                                 break;
4789
4790                         /* fall through */
4791
4792                 case NUMBER:
4793                         if (*p < '0' || *p > '9')
4794                                 return;
4795
4796                         break;
4797
4798                 case LETTER:
4799                         if (!(*p >= 'A' && *p <= 'Z') &&
4800                             !(*p >= 'a' && *p <= 'z'))
4801                                 return;
4802
4803                         break;
4804
4805                 case COLON:
4806                         if (*p != ':')
4807                                 return;
4808                         break;
4809
4810                 }
4811         }
4812
4813         *buf = p;
4814 }
4815
4816 int have_effective_cap(int value) {
4817         cap_t cap;
4818         cap_flag_value_t fv;
4819         int r;
4820
4821         if (!(cap = cap_get_proc()))
4822                 return -errno;
4823
4824         if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4825                 r = -errno;
4826         else
4827                 r = fv == CAP_SET;
4828
4829         cap_free(cap);
4830         return r;
4831 }
4832
4833 char* strshorten(char *s, size_t l) {
4834         assert(s);
4835
4836         if (l < strlen(s))
4837                 s[l] = 0;
4838
4839         return s;
4840 }
4841
4842 static bool hostname_valid_char(char c) {
4843         return
4844                 (c >= 'a' && c <= 'z') ||
4845                 (c >= 'A' && c <= 'Z') ||
4846                 (c >= '0' && c <= '9') ||
4847                 c == '-' ||
4848                 c == '_' ||
4849                 c == '.';
4850 }
4851
4852 bool hostname_is_valid(const char *s) {
4853         const char *p;
4854
4855         if (isempty(s))
4856                 return false;
4857
4858         for (p = s; *p; p++)
4859                 if (!hostname_valid_char(*p))
4860                         return false;
4861
4862         if (p-s > HOST_NAME_MAX)
4863                 return false;
4864
4865         return true;
4866 }
4867
4868 char* hostname_cleanup(char *s) {
4869         char *p, *d;
4870
4871         for (p = s, d = s; *p; p++)
4872                 if ((*p >= 'a' && *p <= 'z') ||
4873                     (*p >= 'A' && *p <= 'Z') ||
4874                     (*p >= '0' && *p <= '9') ||
4875                     *p == '-' ||
4876                     *p == '_' ||
4877                     *p == '.')
4878                         *(d++) = *p;
4879
4880         *d = 0;
4881
4882         strshorten(s, HOST_NAME_MAX);
4883         return s;
4884 }
4885
4886 int pipe_eof(int fd) {
4887         struct pollfd pollfd;
4888         int r;
4889
4890         zero(pollfd);
4891         pollfd.fd = fd;
4892         pollfd.events = POLLIN|POLLHUP;
4893
4894         r = poll(&pollfd, 1, 0);
4895         if (r < 0)
4896                 return -errno;
4897
4898         if (r == 0)
4899                 return 0;
4900
4901         return pollfd.revents & POLLHUP;
4902 }
4903
4904 int fd_wait_for_event(int fd, int event, usec_t t) {
4905         struct pollfd pollfd;
4906         int r;
4907
4908         zero(pollfd);
4909         pollfd.fd = fd;
4910         pollfd.events = event;
4911
4912         r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4913         if (r < 0)
4914                 return -errno;
4915
4916         if (r == 0)
4917                 return 0;
4918
4919         return pollfd.revents;
4920 }
4921
4922 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4923         FILE *f;
4924         char *t;
4925         const char *fn;
4926         size_t k;
4927         int fd;
4928
4929         assert(path);
4930         assert(_f);
4931         assert(_temp_path);
4932
4933         t = new(char, strlen(path) + 1 + 6 + 1);
4934         if (!t)
4935                 return -ENOMEM;
4936
4937         fn = file_name_from_path(path);
4938         k = fn-path;
4939         memcpy(t, path, k);
4940         t[k] = '.';
4941         stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4942
4943         fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4944         if (fd < 0) {
4945                 free(t);
4946                 return -errno;
4947         }
4948
4949         f = fdopen(fd, "we");
4950         if (!f) {
4951                 unlink(t);
4952                 free(t);
4953                 return -errno;
4954         }
4955
4956         *_f = f;
4957         *_temp_path = t;
4958
4959         return 0;
4960 }
4961
4962 int terminal_vhangup_fd(int fd) {
4963         assert(fd >= 0);
4964
4965         if (ioctl(fd, TIOCVHANGUP) < 0)
4966                 return -errno;
4967
4968         return 0;
4969 }
4970
4971 int terminal_vhangup(const char *name) {
4972         int fd, r;
4973
4974         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4975         if (fd < 0)
4976                 return fd;
4977
4978         r = terminal_vhangup_fd(fd);
4979         close_nointr_nofail(fd);
4980
4981         return r;
4982 }
4983
4984 int vt_disallocate(const char *name) {
4985         int fd, r;
4986         unsigned u;
4987
4988         /* Deallocate the VT if possible. If not possible
4989          * (i.e. because it is the active one), at least clear it
4990          * entirely (including the scrollback buffer) */
4991
4992         if (!startswith(name, "/dev/"))
4993                 return -EINVAL;
4994
4995         if (!tty_is_vc(name)) {
4996                 /* So this is not a VT. I guess we cannot deallocate
4997                  * it then. But let's at least clear the screen */
4998
4999                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
5000                 if (fd < 0)
5001                         return fd;
5002
5003                 loop_write(fd,
5004                            "\033[r"    /* clear scrolling region */
5005                            "\033[H"    /* move home */
5006                            "\033[2J",  /* clear screen */
5007                            10, false);
5008                 close_nointr_nofail(fd);
5009
5010                 return 0;
5011         }
5012
5013         if (!startswith(name, "/dev/tty"))
5014                 return -EINVAL;
5015
5016         r = safe_atou(name+8, &u);
5017         if (r < 0)
5018                 return r;
5019
5020         if (u <= 0)
5021                 return -EINVAL;
5022
5023         /* Try to deallocate */
5024         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
5025         if (fd < 0)
5026                 return fd;
5027
5028         r = ioctl(fd, VT_DISALLOCATE, u);
5029         close_nointr_nofail(fd);
5030
5031         if (r >= 0)
5032                 return 0;
5033
5034         if (errno != EBUSY)
5035                 return -errno;
5036
5037         /* Couldn't deallocate, so let's clear it fully with
5038          * scrollback */
5039         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
5040         if (fd < 0)
5041                 return fd;
5042
5043         loop_write(fd,
5044                    "\033[r"   /* clear scrolling region */
5045                    "\033[H"   /* move home */
5046                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
5047                    10, false);
5048         close_nointr_nofail(fd);
5049
5050         return 0;
5051 }
5052
5053 static int files_add(Hashmap *h, const char *path, const char *suffix) {
5054         DIR *dir;
5055         struct dirent buffer, *de;
5056         int r = 0;
5057
5058         dir = opendir(path);
5059         if (!dir) {
5060                 if (errno == ENOENT)
5061                         return 0;
5062                 return -errno;
5063         }
5064
5065         for (;;) {
5066                 int k;
5067                 char *p, *f;
5068
5069                 k = readdir_r(dir, &buffer, &de);
5070                 if (k != 0) {
5071                         r = -k;
5072                         goto finish;
5073                 }
5074
5075                 if (!de)
5076                         break;
5077
5078                 if (!dirent_is_file_with_suffix(de, suffix))
5079                         continue;
5080
5081                 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
5082                         r = -ENOMEM;
5083                         goto finish;
5084                 }
5085
5086                 f = canonicalize_file_name(p);
5087                 if (!f) {
5088                         log_error("Failed to canonicalize file name '%s': %m", p);
5089                         free(p);
5090                         continue;
5091                 }
5092                 free(p);
5093
5094                 log_debug("found: %s\n", f);
5095                 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
5096                         free(f);
5097         }
5098
5099 finish:
5100         closedir(dir);
5101         return r;
5102 }
5103
5104 static int base_cmp(const void *a, const void *b) {
5105         const char *s1, *s2;
5106
5107         s1 = *(char * const *)a;
5108         s2 = *(char * const *)b;
5109         return strcmp(file_name_from_path(s1), file_name_from_path(s2));
5110 }
5111
5112 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
5113         Hashmap *fh = NULL;
5114         char **dirs = NULL;
5115         char **files = NULL;
5116         char **p;
5117         va_list ap;
5118         int r = 0;
5119
5120         va_start(ap, dir);
5121         dirs = strv_new_ap(dir, ap);
5122         va_end(ap);
5123         if (!dirs) {
5124                 r = -ENOMEM;
5125                 goto finish;
5126         }
5127         if (!strv_path_canonicalize(dirs)) {
5128                 r = -ENOMEM;
5129                 goto finish;
5130         }
5131         if (!strv_uniq(dirs)) {
5132                 r = -ENOMEM;
5133                 goto finish;
5134         }
5135
5136         fh = hashmap_new(string_hash_func, string_compare_func);
5137         if (!fh) {
5138                 r = -ENOMEM;
5139                 goto finish;
5140         }
5141
5142         STRV_FOREACH(p, dirs) {
5143                 if (files_add(fh, *p, suffix) < 0) {
5144                         log_error("Failed to search for files.");
5145                         r = -EINVAL;
5146                         goto finish;
5147                 }
5148         }
5149
5150         files = hashmap_get_strv(fh);
5151         if (files == NULL) {
5152                 log_error("Failed to compose list of files.");
5153                 r = -ENOMEM;
5154                 goto finish;
5155         }
5156
5157         qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
5158
5159 finish:
5160         strv_free(dirs);
5161         hashmap_free(fh);
5162         *strv = files;
5163         return r;
5164 }
5165
5166 int hwclock_is_localtime(void) {
5167         FILE *f;
5168         bool local = false;
5169
5170         /*
5171          * The third line of adjtime is "UTC" or "LOCAL" or nothing.
5172          *   # /etc/adjtime
5173          *   0.0 0 0
5174          *   0
5175          *   UTC
5176          */
5177         f = fopen("/etc/adjtime", "re");
5178         if (f) {
5179                 char line[LINE_MAX];
5180                 bool b;
5181
5182                 b = fgets(line, sizeof(line), f) &&
5183                         fgets(line, sizeof(line), f) &&
5184                         fgets(line, sizeof(line), f);
5185
5186                 fclose(f);
5187
5188                 if (!b)
5189                         return -EIO;
5190
5191
5192                 truncate_nl(line);
5193                 local = streq(line, "LOCAL");
5194
5195         } else if (errno != -ENOENT)
5196                 return -errno;
5197
5198         return local;
5199 }
5200
5201 int hwclock_apply_localtime_delta(int *min) {
5202         const struct timeval *tv_null = NULL;
5203         struct timespec ts;
5204         struct tm *tm;
5205         int minuteswest;
5206         struct timezone tz;
5207
5208         assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
5209         assert_se(tm = localtime(&ts.tv_sec));
5210         minuteswest = tm->tm_gmtoff / 60;
5211
5212         tz.tz_minuteswest = -minuteswest;
5213         tz.tz_dsttime = 0; /* DST_NONE*/
5214
5215         /*
5216          * If the hardware clock does not run in UTC, but in local time:
5217          * The very first time we set the kernel's timezone, it will warp
5218          * the clock so that it runs in UTC instead of local time.
5219          */
5220         if (settimeofday(tv_null, &tz) < 0)
5221                 return -errno;
5222         if (min)
5223                 *min = minuteswest;
5224         return 0;
5225 }
5226
5227 int hwclock_reset_localtime_delta(void) {
5228         const struct timeval *tv_null = NULL;
5229         struct timezone tz;
5230
5231         tz.tz_minuteswest = 0;
5232         tz.tz_dsttime = 0; /* DST_NONE*/
5233
5234         if (settimeofday(tv_null, &tz) < 0)
5235                 return -errno;
5236
5237         return 0;
5238 }
5239
5240 int rtc_open(int flags) {
5241         int fd;
5242         DIR *d;
5243
5244         /* First, we try to make use of the /dev/rtc symlink. If that
5245          * doesn't exist, we open the first RTC which has hctosys=1
5246          * set. If we don't find any we just take the first RTC that
5247          * exists at all. */
5248
5249         fd = open("/dev/rtc", flags);
5250         if (fd >= 0)
5251                 return fd;
5252
5253         d = opendir("/sys/class/rtc");
5254         if (!d)
5255                 goto fallback;
5256
5257         for (;;) {
5258                 char *p, *v;
5259                 struct dirent buf, *de;
5260                 int r;
5261
5262                 r = readdir_r(d, &buf, &de);
5263                 if (r != 0)
5264                         goto fallback;
5265
5266                 if (!de)
5267                         goto fallback;
5268
5269                 if (ignore_file(de->d_name))
5270                         continue;
5271
5272                 p = join("/sys/class/rtc/", de->d_name, "/hctosys", NULL);
5273                 if (!p) {
5274                         closedir(d);
5275                         return -ENOMEM;
5276                 }
5277
5278                 r = read_one_line_file(p, &v);
5279                 free(p);
5280
5281                 if (r < 0)
5282                         continue;
5283
5284                 r = parse_boolean(v);
5285                 free(v);
5286
5287                 if (r <= 0)
5288                         continue;
5289
5290                 p = strappend("/dev/", de->d_name);
5291                 fd = open(p, flags);
5292                 free(p);
5293
5294                 if (fd >= 0) {
5295                         closedir(d);
5296                         return fd;
5297                 }
5298         }
5299
5300 fallback:
5301         if (d)
5302                 closedir(d);
5303
5304         fd = open("/dev/rtc0", flags);
5305         if (fd < 0)
5306                 return -errno;
5307
5308         return fd;
5309 }
5310
5311 int hwclock_get_time(struct tm *tm) {
5312         int fd;
5313         int err = 0;
5314
5315         assert(tm);
5316
5317         fd = rtc_open(O_RDONLY|O_CLOEXEC);
5318         if (fd < 0)
5319                 return -errno;
5320
5321         /* This leaves the timezone fields of struct tm
5322          * uninitialized! */
5323         if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5324                 err = -errno;
5325
5326         /* We don't now daylight saving, so we reset this in order not
5327          * to confused mktime(). */
5328         tm->tm_isdst = -1;
5329
5330         close_nointr_nofail(fd);
5331
5332         return err;
5333 }
5334
5335 int hwclock_set_time(const struct tm *tm) {
5336         int fd;
5337         int err = 0;
5338
5339         assert(tm);
5340
5341         fd = rtc_open(O_RDONLY|O_CLOEXEC);
5342         if (fd < 0)
5343                 return -errno;
5344
5345         if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5346                 err = -errno;
5347
5348         close_nointr_nofail(fd);
5349
5350         return err;
5351 }
5352
5353 int copy_file(const char *from, const char *to) {
5354         int r, fdf, fdt;
5355
5356         assert(from);
5357         assert(to);
5358
5359         fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5360         if (fdf < 0)
5361                 return -errno;
5362
5363         fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5364         if (fdt < 0) {
5365                 close_nointr_nofail(fdf);
5366                 return -errno;
5367         }
5368
5369         for (;;) {
5370                 char buf[PIPE_BUF];
5371                 ssize_t n, k;
5372
5373                 n = read(fdf, buf, sizeof(buf));
5374                 if (n < 0) {
5375                         r = -errno;
5376
5377                         close_nointr_nofail(fdf);
5378                         close_nointr(fdt);
5379                         unlink(to);
5380
5381                         return r;
5382                 }
5383
5384                 if (n == 0)
5385                         break;
5386
5387                 errno = 0;
5388                 k = loop_write(fdt, buf, n, false);
5389                 if (n != k) {
5390                         r = k < 0 ? k : (errno ? -errno : -EIO);
5391
5392                         close_nointr_nofail(fdf);
5393                         close_nointr(fdt);
5394
5395                         unlink(to);
5396                         return r;
5397                 }
5398         }
5399
5400         close_nointr_nofail(fdf);
5401         r = close_nointr(fdt);
5402
5403         if (r < 0) {
5404                 unlink(to);
5405                 return r;
5406         }
5407
5408         return 0;
5409 }
5410
5411 int symlink_or_copy(const char *from, const char *to) {
5412         char *pf = NULL, *pt = NULL;
5413         struct stat a, b;
5414         int r;
5415
5416         assert(from);
5417         assert(to);
5418
5419         if (parent_of_path(from, &pf) < 0 ||
5420             parent_of_path(to, &pt) < 0) {
5421                 r = -ENOMEM;
5422                 goto finish;
5423         }
5424
5425         if (stat(pf, &a) < 0 ||
5426             stat(pt, &b) < 0) {
5427                 r = -errno;
5428                 goto finish;
5429         }
5430
5431         if (a.st_dev != b.st_dev) {
5432                 free(pf);
5433                 free(pt);
5434
5435                 return copy_file(from, to);
5436         }
5437
5438         if (symlink(from, to) < 0) {
5439                 r = -errno;
5440                 goto finish;
5441         }
5442
5443         r = 0;
5444
5445 finish:
5446         free(pf);
5447         free(pt);
5448
5449         return r;
5450 }
5451
5452 int symlink_or_copy_atomic(const char *from, const char *to) {
5453         char *t, *x;
5454         const char *fn;
5455         size_t k;
5456         unsigned long long ull;
5457         unsigned i;
5458         int r;
5459
5460         assert(from);
5461         assert(to);
5462
5463         t = new(char, strlen(to) + 1 + 16 + 1);
5464         if (!t)
5465                 return -ENOMEM;
5466
5467         fn = file_name_from_path(to);
5468         k = fn-to;
5469         memcpy(t, to, k);
5470         t[k] = '.';
5471         x = stpcpy(t+k+1, fn);
5472
5473         ull = random_ull();
5474         for (i = 0; i < 16; i++) {
5475                 *(x++) = hexchar(ull & 0xF);
5476                 ull >>= 4;
5477         }
5478
5479         *x = 0;
5480
5481         r = symlink_or_copy(from, t);
5482         if (r < 0) {
5483                 unlink(t);
5484                 free(t);
5485                 return r;
5486         }
5487
5488         if (rename(t, to) < 0) {
5489                 r = -errno;
5490                 unlink(t);
5491                 free(t);
5492                 return r;
5493         }
5494
5495         free(t);
5496         return r;
5497 }
5498
5499 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5500         char *s;
5501         uint32_t u;
5502         int r;
5503
5504         assert(id);
5505
5506         if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5507                 return -ENOENT;
5508
5509         if (pid == 0)
5510                 r = read_one_line_file("/proc/self/sessionid", &s);
5511         else {
5512                 char *p;
5513
5514                 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5515                         return -ENOMEM;
5516
5517                 r = read_one_line_file(p, &s);
5518                 free(p);
5519         }
5520
5521         if (r < 0)
5522                 return r;
5523
5524         r = safe_atou32(s, &u);
5525         free(s);
5526
5527         if (r < 0)
5528                 return r;
5529
5530         if (u == (uint32_t) -1 || u <= 0)
5531                 return -ENOENT;
5532
5533         *id = u;
5534         return 0;
5535 }
5536
5537 int audit_loginuid_from_pid(pid_t pid, uid_t *uid) {
5538         char *s;
5539         uid_t u;
5540         int r;
5541
5542         assert(uid);
5543
5544         /* Only use audit login uid if we are executed with sufficient
5545          * capabilities so that pam_loginuid could do its job. If we
5546          * are lacking the CAP_AUDIT_CONTROL capabality we most likely
5547          * are being run in a container and /proc/self/loginuid is
5548          * useless since it probably contains a uid of the host
5549          * system. */
5550
5551         if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5552                 return -ENOENT;
5553
5554         if (pid == 0)
5555                 r = read_one_line_file("/proc/self/loginuid", &s);
5556         else {
5557                 char *p;
5558
5559                 if (asprintf(&p, "/proc/%lu/loginuid", (unsigned long) pid) < 0)
5560                         return -ENOMEM;
5561
5562                 r = read_one_line_file(p, &s);
5563                 free(p);
5564         }
5565
5566         if (r < 0)
5567                 return r;
5568
5569         r = parse_uid(s, &u);
5570         free(s);
5571
5572         if (r < 0)
5573                 return r;
5574
5575         if (u == (uid_t) -1)
5576                 return -ENOENT;
5577
5578         *uid = (uid_t) u;
5579         return 0;
5580 }
5581
5582 bool display_is_local(const char *display) {
5583         assert(display);
5584
5585         return
5586                 display[0] == ':' &&
5587                 display[1] >= '0' &&
5588                 display[1] <= '9';
5589 }
5590
5591 int socket_from_display(const char *display, char **path) {
5592         size_t k;
5593         char *f, *c;
5594
5595         assert(display);
5596         assert(path);
5597
5598         if (!display_is_local(display))
5599                 return -EINVAL;
5600
5601         k = strspn(display+1, "0123456789");
5602
5603         f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5604         if (!f)
5605                 return -ENOMEM;
5606
5607         c = stpcpy(f, "/tmp/.X11-unix/X");
5608         memcpy(c, display+1, k);
5609         c[k] = 0;
5610
5611         *path = f;
5612
5613         return 0;
5614 }
5615
5616 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5617         struct passwd *p;
5618         uid_t u;
5619
5620         assert(username);
5621         assert(*username);
5622
5623         /* We enforce some special rules for uid=0: in order to avoid
5624          * NSS lookups for root we hardcode its data. */
5625
5626         if (streq(*username, "root") || streq(*username, "0")) {
5627                 *username = "root";
5628
5629                 if (uid)
5630                         *uid = 0;
5631
5632                 if (gid)
5633                         *gid = 0;
5634
5635                 if (home)
5636                         *home = "/root";
5637                 return 0;
5638         }
5639
5640         if (parse_uid(*username, &u) >= 0) {
5641                 errno = 0;
5642                 p = getpwuid(u);
5643
5644                 /* If there are multiple users with the same id, make
5645                  * sure to leave $USER to the configured value instead
5646                  * of the first occurrence in the database. However if
5647                  * the uid was configured by a numeric uid, then let's
5648                  * pick the real username from /etc/passwd. */
5649                 if (p)
5650                         *username = p->pw_name;
5651         } else {
5652                 errno = 0;
5653                 p = getpwnam(*username);
5654         }
5655
5656         if (!p)
5657                 return errno != 0 ? -errno : -ESRCH;
5658
5659         if (uid)
5660                 *uid = p->pw_uid;
5661
5662         if (gid)
5663                 *gid = p->pw_gid;
5664
5665         if (home)
5666                 *home = p->pw_dir;
5667
5668         return 0;
5669 }
5670
5671 int get_group_creds(const char **groupname, gid_t *gid) {
5672         struct group *g;
5673         gid_t id;
5674
5675         assert(groupname);
5676
5677         /* We enforce some special rules for gid=0: in order to avoid
5678          * NSS lookups for root we hardcode its data. */
5679
5680         if (streq(*groupname, "root") || streq(*groupname, "0")) {
5681                 *groupname = "root";
5682
5683                 if (gid)
5684                         *gid = 0;
5685
5686                 return 0;
5687         }
5688
5689         if (parse_gid(*groupname, &id) >= 0) {
5690                 errno = 0;
5691                 g = getgrgid(id);
5692
5693                 if (g)
5694                         *groupname = g->gr_name;
5695         } else {
5696                 errno = 0;
5697                 g = getgrnam(*groupname);
5698         }
5699
5700         if (!g)
5701                 return errno != 0 ? -errno : -ESRCH;
5702
5703         if (gid)
5704                 *gid = g->gr_gid;
5705
5706         return 0;
5707 }
5708
5709 int glob_exists(const char *path) {
5710         glob_t g;
5711         int r, k;
5712
5713         assert(path);
5714
5715         zero(g);
5716         errno = 0;
5717         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5718
5719         if (k == GLOB_NOMATCH)
5720                 r = 0;
5721         else if (k == GLOB_NOSPACE)
5722                 r = -ENOMEM;
5723         else if (k == 0)
5724                 r = !strv_isempty(g.gl_pathv);
5725         else
5726                 r = errno ? -errno : -EIO;
5727
5728         globfree(&g);
5729
5730         return r;
5731 }
5732
5733 int dirent_ensure_type(DIR *d, struct dirent *de) {
5734         struct stat st;
5735
5736         assert(d);
5737         assert(de);
5738
5739         if (de->d_type != DT_UNKNOWN)
5740                 return 0;
5741
5742         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5743                 return -errno;
5744
5745         de->d_type =
5746                 S_ISREG(st.st_mode)  ? DT_REG  :
5747                 S_ISDIR(st.st_mode)  ? DT_DIR  :
5748                 S_ISLNK(st.st_mode)  ? DT_LNK  :
5749                 S_ISFIFO(st.st_mode) ? DT_FIFO :
5750                 S_ISSOCK(st.st_mode) ? DT_SOCK :
5751                 S_ISCHR(st.st_mode)  ? DT_CHR  :
5752                 S_ISBLK(st.st_mode)  ? DT_BLK  :
5753                                        DT_UNKNOWN;
5754
5755         return 0;
5756 }
5757
5758 int in_search_path(const char *path, char **search) {
5759         char **i, *parent;
5760         int r;
5761
5762         r = parent_of_path(path, &parent);
5763         if (r < 0)
5764                 return r;
5765
5766         r = 0;
5767
5768         STRV_FOREACH(i, search) {
5769                 if (path_equal(parent, *i)) {
5770                         r = 1;
5771                         break;
5772                 }
5773         }
5774
5775         free(parent);
5776
5777         return r;
5778 }
5779
5780 int get_files_in_directory(const char *path, char ***list) {
5781         DIR *d;
5782         int r = 0;
5783         unsigned n = 0;
5784         char **l = NULL;
5785
5786         assert(path);
5787
5788         /* Returns all files in a directory in *list, and the number
5789          * of files as return value. If list is NULL returns only the
5790          * number */
5791
5792         d = opendir(path);
5793         if (!d)
5794                 return -errno;
5795
5796         for (;;) {
5797                 struct dirent buffer, *de;
5798                 int k;
5799
5800                 k = readdir_r(d, &buffer, &de);
5801                 if (k != 0) {
5802                         r = -k;
5803                         goto finish;
5804                 }
5805
5806                 if (!de)
5807                         break;
5808
5809                 dirent_ensure_type(d, de);
5810
5811                 if (!dirent_is_file(de))
5812                         continue;
5813
5814                 if (list) {
5815                         if ((unsigned) r >= n) {
5816                                 char **t;
5817
5818                                 n = MAX(16, 2*r);
5819                                 t = realloc(l, sizeof(char*) * n);
5820                                 if (!t) {
5821                                         r = -ENOMEM;
5822                                         goto finish;
5823                                 }
5824
5825                                 l = t;
5826                         }
5827
5828                         assert((unsigned) r < n);
5829
5830                         l[r] = strdup(de->d_name);
5831                         if (!l[r]) {
5832                                 r = -ENOMEM;
5833                                 goto finish;
5834                         }
5835
5836                         l[++r] = NULL;
5837                 } else
5838                         r++;
5839         }
5840
5841 finish:
5842         if (d)
5843                 closedir(d);
5844
5845         if (r >= 0) {
5846                 if (list)
5847                         *list = l;
5848         } else
5849                 strv_free(l);
5850
5851         return r;
5852 }
5853
5854 char *join(const char *x, ...) {
5855         va_list ap;
5856         size_t l;
5857         char *r, *p;
5858
5859         va_start(ap, x);
5860
5861         if (x) {
5862                 l = strlen(x);
5863
5864                 for (;;) {
5865                         const char *t;
5866
5867                         t = va_arg(ap, const char *);
5868                         if (!t)
5869                                 break;
5870
5871                         l += strlen(t);
5872                 }
5873         } else
5874                 l = 0;
5875
5876         va_end(ap);
5877
5878         r = new(char, l+1);
5879         if (!r)
5880                 return NULL;
5881
5882         if (x) {
5883                 p = stpcpy(r, x);
5884
5885                 va_start(ap, x);
5886
5887                 for (;;) {
5888                         const char *t;
5889
5890                         t = va_arg(ap, const char *);
5891                         if (!t)
5892                                 break;
5893
5894                         p = stpcpy(p, t);
5895                 }
5896
5897                 va_end(ap);
5898         } else
5899                 r[0] = 0;
5900
5901         return r;
5902 }
5903
5904 bool is_main_thread(void) {
5905         static __thread int cached = 0;
5906
5907         if (_unlikely_(cached == 0))
5908                 cached = getpid() == gettid() ? 1 : -1;
5909
5910         return cached > 0;
5911 }
5912
5913 int block_get_whole_disk(dev_t d, dev_t *ret) {
5914         char *p, *s;
5915         int r;
5916         unsigned n, m;
5917
5918         assert(ret);
5919
5920         /* If it has a queue this is good enough for us */
5921         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5922                 return -ENOMEM;
5923
5924         r = access(p, F_OK);
5925         free(p);
5926
5927         if (r >= 0) {
5928                 *ret = d;
5929                 return 0;
5930         }
5931
5932         /* If it is a partition find the originating device */
5933         if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5934                 return -ENOMEM;
5935
5936         r = access(p, F_OK);
5937         free(p);
5938
5939         if (r < 0)
5940                 return -ENOENT;
5941
5942         /* Get parent dev_t */
5943         if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5944                 return -ENOMEM;
5945
5946         r = read_one_line_file(p, &s);
5947         free(p);
5948
5949         if (r < 0)
5950                 return r;
5951
5952         r = sscanf(s, "%u:%u", &m, &n);
5953         free(s);
5954
5955         if (r != 2)
5956                 return -EINVAL;
5957
5958         /* Only return this if it is really good enough for us. */
5959         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5960                 return -ENOMEM;
5961
5962         r = access(p, F_OK);
5963         free(p);
5964
5965         if (r >= 0) {
5966                 *ret = makedev(m, n);
5967                 return 0;
5968         }
5969
5970         return -ENOENT;
5971 }
5972
5973 int file_is_priv_sticky(const char *p) {
5974         struct stat st;
5975
5976         assert(p);
5977
5978         if (lstat(p, &st) < 0)
5979                 return -errno;
5980
5981         return
5982                 (st.st_uid == 0 || st.st_uid == getuid()) &&
5983                 (st.st_mode & S_ISVTX);
5984 }
5985
5986 static const char *const ioprio_class_table[] = {
5987         [IOPRIO_CLASS_NONE] = "none",
5988         [IOPRIO_CLASS_RT] = "realtime",
5989         [IOPRIO_CLASS_BE] = "best-effort",
5990         [IOPRIO_CLASS_IDLE] = "idle"
5991 };
5992
5993 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5994
5995 static const char *const sigchld_code_table[] = {
5996         [CLD_EXITED] = "exited",
5997         [CLD_KILLED] = "killed",
5998         [CLD_DUMPED] = "dumped",
5999         [CLD_TRAPPED] = "trapped",
6000         [CLD_STOPPED] = "stopped",
6001         [CLD_CONTINUED] = "continued",
6002 };
6003
6004 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
6005
6006 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
6007         [LOG_FAC(LOG_KERN)] = "kern",
6008         [LOG_FAC(LOG_USER)] = "user",
6009         [LOG_FAC(LOG_MAIL)] = "mail",
6010         [LOG_FAC(LOG_DAEMON)] = "daemon",
6011         [LOG_FAC(LOG_AUTH)] = "auth",
6012         [LOG_FAC(LOG_SYSLOG)] = "syslog",
6013         [LOG_FAC(LOG_LPR)] = "lpr",
6014         [LOG_FAC(LOG_NEWS)] = "news",
6015         [LOG_FAC(LOG_UUCP)] = "uucp",
6016         [LOG_FAC(LOG_CRON)] = "cron",
6017         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
6018         [LOG_FAC(LOG_FTP)] = "ftp",
6019         [LOG_FAC(LOG_LOCAL0)] = "local0",
6020         [LOG_FAC(LOG_LOCAL1)] = "local1",
6021         [LOG_FAC(LOG_LOCAL2)] = "local2",
6022         [LOG_FAC(LOG_LOCAL3)] = "local3",
6023         [LOG_FAC(LOG_LOCAL4)] = "local4",
6024         [LOG_FAC(LOG_LOCAL5)] = "local5",
6025         [LOG_FAC(LOG_LOCAL6)] = "local6",
6026         [LOG_FAC(LOG_LOCAL7)] = "local7"
6027 };
6028
6029 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
6030
6031 static const char *const log_level_table[] = {
6032         [LOG_EMERG] = "emerg",
6033         [LOG_ALERT] = "alert",
6034         [LOG_CRIT] = "crit",
6035         [LOG_ERR] = "err",
6036         [LOG_WARNING] = "warning",
6037         [LOG_NOTICE] = "notice",
6038         [LOG_INFO] = "info",
6039         [LOG_DEBUG] = "debug"
6040 };
6041
6042 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
6043
6044 static const char* const sched_policy_table[] = {
6045         [SCHED_OTHER] = "other",
6046         [SCHED_BATCH] = "batch",
6047         [SCHED_IDLE] = "idle",
6048         [SCHED_FIFO] = "fifo",
6049         [SCHED_RR] = "rr"
6050 };
6051
6052 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
6053
6054 static const char* const rlimit_table[] = {
6055         [RLIMIT_CPU] = "LimitCPU",
6056         [RLIMIT_FSIZE] = "LimitFSIZE",
6057         [RLIMIT_DATA] = "LimitDATA",
6058         [RLIMIT_STACK] = "LimitSTACK",
6059         [RLIMIT_CORE] = "LimitCORE",
6060         [RLIMIT_RSS] = "LimitRSS",
6061         [RLIMIT_NOFILE] = "LimitNOFILE",
6062         [RLIMIT_AS] = "LimitAS",
6063         [RLIMIT_NPROC] = "LimitNPROC",
6064         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
6065         [RLIMIT_LOCKS] = "LimitLOCKS",
6066         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
6067         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
6068         [RLIMIT_NICE] = "LimitNICE",
6069         [RLIMIT_RTPRIO] = "LimitRTPRIO",
6070         [RLIMIT_RTTIME] = "LimitRTTIME"
6071 };
6072
6073 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
6074
6075 static const char* const ip_tos_table[] = {
6076         [IPTOS_LOWDELAY] = "low-delay",
6077         [IPTOS_THROUGHPUT] = "throughput",
6078         [IPTOS_RELIABILITY] = "reliability",
6079         [IPTOS_LOWCOST] = "low-cost",
6080 };
6081
6082 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
6083
6084 static const char *const __signal_table[] = {
6085         [SIGHUP] = "HUP",
6086         [SIGINT] = "INT",
6087         [SIGQUIT] = "QUIT",
6088         [SIGILL] = "ILL",
6089         [SIGTRAP] = "TRAP",
6090         [SIGABRT] = "ABRT",
6091         [SIGBUS] = "BUS",
6092         [SIGFPE] = "FPE",
6093         [SIGKILL] = "KILL",
6094         [SIGUSR1] = "USR1",
6095         [SIGSEGV] = "SEGV",
6096         [SIGUSR2] = "USR2",
6097         [SIGPIPE] = "PIPE",
6098         [SIGALRM] = "ALRM",
6099         [SIGTERM] = "TERM",
6100 #ifdef SIGSTKFLT
6101         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
6102 #endif
6103         [SIGCHLD] = "CHLD",
6104         [SIGCONT] = "CONT",
6105         [SIGSTOP] = "STOP",
6106         [SIGTSTP] = "TSTP",
6107         [SIGTTIN] = "TTIN",
6108         [SIGTTOU] = "TTOU",
6109         [SIGURG] = "URG",
6110         [SIGXCPU] = "XCPU",
6111         [SIGXFSZ] = "XFSZ",
6112         [SIGVTALRM] = "VTALRM",
6113         [SIGPROF] = "PROF",
6114         [SIGWINCH] = "WINCH",
6115         [SIGIO] = "IO",
6116         [SIGPWR] = "PWR",
6117         [SIGSYS] = "SYS"
6118 };
6119
6120 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
6121
6122 const char *signal_to_string(int signo) {
6123         static __thread char buf[12];
6124         const char *name;
6125
6126         name = __signal_to_string(signo);
6127         if (name)
6128                 return name;
6129
6130         if (signo >= SIGRTMIN && signo <= SIGRTMAX)
6131                 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
6132         else
6133                 snprintf(buf, sizeof(buf) - 1, "%d", signo);
6134         char_array_0(buf);
6135         return buf;
6136 }
6137
6138 int signal_from_string(const char *s) {
6139         int signo;
6140         int offset = 0;
6141         unsigned u;
6142
6143         signo =__signal_from_string(s);
6144         if (signo > 0)
6145                 return signo;
6146
6147         if (startswith(s, "RTMIN+")) {
6148                 s += 6;
6149                 offset = SIGRTMIN;
6150         }
6151         if (safe_atou(s, &u) >= 0) {
6152                 signo = (int) u + offset;
6153                 if (signo > 0 && signo < _NSIG)
6154                         return signo;
6155         }
6156         return -1;
6157 }
6158
6159 bool kexec_loaded(void) {
6160        bool loaded = false;
6161        char *s;
6162
6163        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
6164                if (s[0] == '1')
6165                        loaded = true;
6166                free(s);
6167        }
6168        return loaded;
6169 }
6170
6171 int strdup_or_null(const char *a, char **b) {
6172         char *c;
6173
6174         assert(b);
6175
6176         if (!a) {
6177                 *b = NULL;
6178                 return 0;
6179         }
6180
6181         c = strdup(a);
6182         if (!c)
6183                 return -ENOMEM;
6184
6185         *b = c;
6186         return 0;
6187 }
6188
6189 int prot_from_flags(int flags) {
6190
6191         switch (flags & O_ACCMODE) {
6192
6193         case O_RDONLY:
6194                 return PROT_READ;
6195
6196         case O_WRONLY:
6197                 return PROT_WRITE;
6198
6199         case O_RDWR:
6200                 return PROT_READ|PROT_WRITE;
6201
6202         default:
6203                 return -EINVAL;
6204         }
6205 }
6206
6207 unsigned long cap_last_cap(void) {
6208         static __thread unsigned long saved;
6209         static __thread bool valid = false;
6210         unsigned long p;
6211
6212         if (valid)
6213                 return saved;
6214
6215         p = (unsigned long) CAP_LAST_CAP;
6216
6217         if (prctl(PR_CAPBSET_READ, p) < 0) {
6218
6219                 /* Hmm, look downwards, until we find one that
6220                  * works */
6221                 for (p--; p > 0; p --)
6222                         if (prctl(PR_CAPBSET_READ, p) >= 0)
6223                                 break;
6224
6225         } else {
6226
6227                 /* Hmm, look upwards, until we find one that doesn't
6228                  * work */
6229                 for (;; p++)
6230                         if (prctl(PR_CAPBSET_READ, p+1) < 0)
6231                                 break;
6232         }
6233
6234         saved = p;
6235         valid = true;
6236
6237         return p;
6238 }
6239
6240 char *format_bytes(char *buf, size_t l, off_t t) {
6241         unsigned i;
6242
6243         static const struct {
6244                 const char *suffix;
6245                 off_t factor;
6246         } table[] = {
6247                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6248                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6249                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
6250                 { "G", 1024ULL*1024ULL*1024ULL },
6251                 { "M", 1024ULL*1024ULL },
6252                 { "K", 1024ULL },
6253         };
6254
6255         for (i = 0; i < ELEMENTSOF(table); i++) {
6256
6257                 if (t >= table[i].factor) {
6258                         snprintf(buf, l,
6259                                  "%llu.%llu%s",
6260                                  (unsigned long long) (t / table[i].factor),
6261                                  (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
6262                                  table[i].suffix);
6263
6264                         goto finish;
6265                 }
6266         }
6267
6268         snprintf(buf, l, "%lluB", (unsigned long long) t);
6269
6270 finish:
6271         buf[l-1] = 0;
6272         return buf;
6273
6274 }
6275
6276 void* memdup(const void *p, size_t l) {
6277         void *r;
6278
6279         assert(p);
6280
6281         r = malloc(l);
6282         if (!r)
6283                 return NULL;
6284
6285         memcpy(r, p, l);
6286         return r;
6287 }
6288
6289 int fd_inc_sndbuf(int fd, size_t n) {
6290         int r, value;
6291         socklen_t l = sizeof(value);
6292
6293         r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
6294         if (r >= 0 &&
6295             l == sizeof(value) &&
6296             (size_t) value >= n*2)
6297                 return 0;
6298
6299         value = (int) n;
6300         r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
6301         if (r < 0)
6302                 return -errno;
6303
6304         return 1;
6305 }
6306
6307 int fd_inc_rcvbuf(int fd, size_t n) {
6308         int r, value;
6309         socklen_t l = sizeof(value);
6310
6311         r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
6312         if (r >= 0 &&
6313             l == sizeof(value) &&
6314             (size_t) value >= n*2)
6315                 return 0;
6316
6317         value = (int) n;
6318         r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
6319         if (r < 0)
6320                 return -errno;
6321
6322         return 1;
6323 }