chiark / gitweb /
service: add StartLimitInterval/StartLimitBurst/StartLimitAction
[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                 pid_t pid = PTR_TO_UINT(hashmap_first_key(pids));
4627                 siginfo_t si;
4628                 char *path;
4629
4630                 zero(si);
4631                 if (waitid(P_PID, pid, &si, WEXITED) < 0) {
4632
4633                         if (errno == EINTR)
4634                                 continue;
4635
4636                         log_error("waitid() failed: %m");
4637                         goto finish;
4638                 }
4639
4640                 if ((path = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)))) {
4641                         if (!is_clean_exit(si.si_code, si.si_status)) {
4642                                 if (si.si_code == CLD_EXITED)
4643                                         log_error("%s exited with exit status %i.", path, si.si_status);
4644                                 else
4645                                         log_error("%s terminated by signal %s.", path, signal_to_string(si.si_status));
4646                         } else
4647                                 log_debug("%s exited successfully.", path);
4648
4649                         free(path);
4650                 }
4651         }
4652
4653 finish:
4654         if (_d)
4655                 closedir(_d);
4656
4657         if (pids)
4658                 hashmap_free_free(pids);
4659 }
4660
4661 int kill_and_sigcont(pid_t pid, int sig) {
4662         int r;
4663
4664         r = kill(pid, sig) < 0 ? -errno : 0;
4665
4666         if (r >= 0)
4667                 kill(pid, SIGCONT);
4668
4669         return r;
4670 }
4671
4672 bool nulstr_contains(const char*nulstr, const char *needle) {
4673         const char *i;
4674
4675         if (!nulstr)
4676                 return false;
4677
4678         NULSTR_FOREACH(i, nulstr)
4679                 if (streq(i, needle))
4680                         return true;
4681
4682         return false;
4683 }
4684
4685 bool plymouth_running(void) {
4686         return access("/run/plymouth/pid", F_OK) >= 0;
4687 }
4688
4689 void parse_syslog_priority(char **p, int *priority) {
4690         int a = 0, b = 0, c = 0;
4691         int k;
4692
4693         assert(p);
4694         assert(*p);
4695         assert(priority);
4696
4697         if ((*p)[0] != '<')
4698                 return;
4699
4700         if (!strchr(*p, '>'))
4701                 return;
4702
4703         if ((*p)[2] == '>') {
4704                 c = undecchar((*p)[1]);
4705                 k = 3;
4706         } else if ((*p)[3] == '>') {
4707                 b = undecchar((*p)[1]);
4708                 c = undecchar((*p)[2]);
4709                 k = 4;
4710         } else if ((*p)[4] == '>') {
4711                 a = undecchar((*p)[1]);
4712                 b = undecchar((*p)[2]);
4713                 c = undecchar((*p)[3]);
4714                 k = 5;
4715         } else
4716                 return;
4717
4718         if (a < 0 || b < 0 || c < 0)
4719                 return;
4720
4721         *priority = a*100+b*10+c;
4722         *p += k;
4723 }
4724
4725 void skip_syslog_pid(char **buf) {
4726         char *p;
4727
4728         assert(buf);
4729         assert(*buf);
4730
4731         p = *buf;
4732
4733         if (*p != '[')
4734                 return;
4735
4736         p++;
4737         p += strspn(p, "0123456789");
4738
4739         if (*p != ']')
4740                 return;
4741
4742         p++;
4743
4744         *buf = p;
4745 }
4746
4747 void skip_syslog_date(char **buf) {
4748         enum {
4749                 LETTER,
4750                 SPACE,
4751                 NUMBER,
4752                 SPACE_OR_NUMBER,
4753                 COLON
4754         } sequence[] = {
4755                 LETTER, LETTER, LETTER,
4756                 SPACE,
4757                 SPACE_OR_NUMBER, NUMBER,
4758                 SPACE,
4759                 SPACE_OR_NUMBER, NUMBER,
4760                 COLON,
4761                 SPACE_OR_NUMBER, NUMBER,
4762                 COLON,
4763                 SPACE_OR_NUMBER, NUMBER,
4764                 SPACE
4765         };
4766
4767         char *p;
4768         unsigned i;
4769
4770         assert(buf);
4771         assert(*buf);
4772
4773         p = *buf;
4774
4775         for (i = 0; i < ELEMENTSOF(sequence); i++, p++) {
4776
4777                 if (!*p)
4778                         return;
4779
4780                 switch (sequence[i]) {
4781
4782                 case SPACE:
4783                         if (*p != ' ')
4784                                 return;
4785                         break;
4786
4787                 case SPACE_OR_NUMBER:
4788                         if (*p == ' ')
4789                                 break;
4790
4791                         /* fall through */
4792
4793                 case NUMBER:
4794                         if (*p < '0' || *p > '9')
4795                                 return;
4796
4797                         break;
4798
4799                 case LETTER:
4800                         if (!(*p >= 'A' && *p <= 'Z') &&
4801                             !(*p >= 'a' && *p <= 'z'))
4802                                 return;
4803
4804                         break;
4805
4806                 case COLON:
4807                         if (*p != ':')
4808                                 return;
4809                         break;
4810
4811                 }
4812         }
4813
4814         *buf = p;
4815 }
4816
4817 int have_effective_cap(int value) {
4818         cap_t cap;
4819         cap_flag_value_t fv;
4820         int r;
4821
4822         if (!(cap = cap_get_proc()))
4823                 return -errno;
4824
4825         if (cap_get_flag(cap, value, CAP_EFFECTIVE, &fv) < 0)
4826                 r = -errno;
4827         else
4828                 r = fv == CAP_SET;
4829
4830         cap_free(cap);
4831         return r;
4832 }
4833
4834 char* strshorten(char *s, size_t l) {
4835         assert(s);
4836
4837         if (l < strlen(s))
4838                 s[l] = 0;
4839
4840         return s;
4841 }
4842
4843 static bool hostname_valid_char(char c) {
4844         return
4845                 (c >= 'a' && c <= 'z') ||
4846                 (c >= 'A' && c <= 'Z') ||
4847                 (c >= '0' && c <= '9') ||
4848                 c == '-' ||
4849                 c == '_' ||
4850                 c == '.';
4851 }
4852
4853 bool hostname_is_valid(const char *s) {
4854         const char *p;
4855
4856         if (isempty(s))
4857                 return false;
4858
4859         for (p = s; *p; p++)
4860                 if (!hostname_valid_char(*p))
4861                         return false;
4862
4863         if (p-s > HOST_NAME_MAX)
4864                 return false;
4865
4866         return true;
4867 }
4868
4869 char* hostname_cleanup(char *s) {
4870         char *p, *d;
4871
4872         for (p = s, d = s; *p; p++)
4873                 if ((*p >= 'a' && *p <= 'z') ||
4874                     (*p >= 'A' && *p <= 'Z') ||
4875                     (*p >= '0' && *p <= '9') ||
4876                     *p == '-' ||
4877                     *p == '_' ||
4878                     *p == '.')
4879                         *(d++) = *p;
4880
4881         *d = 0;
4882
4883         strshorten(s, HOST_NAME_MAX);
4884         return s;
4885 }
4886
4887 int pipe_eof(int fd) {
4888         struct pollfd pollfd;
4889         int r;
4890
4891         zero(pollfd);
4892         pollfd.fd = fd;
4893         pollfd.events = POLLIN|POLLHUP;
4894
4895         r = poll(&pollfd, 1, 0);
4896         if (r < 0)
4897                 return -errno;
4898
4899         if (r == 0)
4900                 return 0;
4901
4902         return pollfd.revents & POLLHUP;
4903 }
4904
4905 int fd_wait_for_event(int fd, int event, usec_t t) {
4906         struct pollfd pollfd;
4907         int r;
4908
4909         zero(pollfd);
4910         pollfd.fd = fd;
4911         pollfd.events = event;
4912
4913         r = poll(&pollfd, 1, t == (usec_t) -1 ? -1 : (int) (t / USEC_PER_MSEC));
4914         if (r < 0)
4915                 return -errno;
4916
4917         if (r == 0)
4918                 return 0;
4919
4920         return pollfd.revents;
4921 }
4922
4923 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
4924         FILE *f;
4925         char *t;
4926         const char *fn;
4927         size_t k;
4928         int fd;
4929
4930         assert(path);
4931         assert(_f);
4932         assert(_temp_path);
4933
4934         t = new(char, strlen(path) + 1 + 6 + 1);
4935         if (!t)
4936                 return -ENOMEM;
4937
4938         fn = file_name_from_path(path);
4939         k = fn-path;
4940         memcpy(t, path, k);
4941         t[k] = '.';
4942         stpcpy(stpcpy(t+k+1, fn), "XXXXXX");
4943
4944         fd = mkostemp(t, O_WRONLY|O_CLOEXEC);
4945         if (fd < 0) {
4946                 free(t);
4947                 return -errno;
4948         }
4949
4950         f = fdopen(fd, "we");
4951         if (!f) {
4952                 unlink(t);
4953                 free(t);
4954                 return -errno;
4955         }
4956
4957         *_f = f;
4958         *_temp_path = t;
4959
4960         return 0;
4961 }
4962
4963 int terminal_vhangup_fd(int fd) {
4964         assert(fd >= 0);
4965
4966         if (ioctl(fd, TIOCVHANGUP) < 0)
4967                 return -errno;
4968
4969         return 0;
4970 }
4971
4972 int terminal_vhangup(const char *name) {
4973         int fd, r;
4974
4975         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
4976         if (fd < 0)
4977                 return fd;
4978
4979         r = terminal_vhangup_fd(fd);
4980         close_nointr_nofail(fd);
4981
4982         return r;
4983 }
4984
4985 int vt_disallocate(const char *name) {
4986         int fd, r;
4987         unsigned u;
4988
4989         /* Deallocate the VT if possible. If not possible
4990          * (i.e. because it is the active one), at least clear it
4991          * entirely (including the scrollback buffer) */
4992
4993         if (!startswith(name, "/dev/"))
4994                 return -EINVAL;
4995
4996         if (!tty_is_vc(name)) {
4997                 /* So this is not a VT. I guess we cannot deallocate
4998                  * it then. But let's at least clear the screen */
4999
5000                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
5001                 if (fd < 0)
5002                         return fd;
5003
5004                 loop_write(fd,
5005                            "\033[r"    /* clear scrolling region */
5006                            "\033[H"    /* move home */
5007                            "\033[2J",  /* clear screen */
5008                            10, false);
5009                 close_nointr_nofail(fd);
5010
5011                 return 0;
5012         }
5013
5014         if (!startswith(name, "/dev/tty"))
5015                 return -EINVAL;
5016
5017         r = safe_atou(name+8, &u);
5018         if (r < 0)
5019                 return r;
5020
5021         if (u <= 0)
5022                 return -EINVAL;
5023
5024         /* Try to deallocate */
5025         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
5026         if (fd < 0)
5027                 return fd;
5028
5029         r = ioctl(fd, VT_DISALLOCATE, u);
5030         close_nointr_nofail(fd);
5031
5032         if (r >= 0)
5033                 return 0;
5034
5035         if (errno != EBUSY)
5036                 return -errno;
5037
5038         /* Couldn't deallocate, so let's clear it fully with
5039          * scrollback */
5040         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
5041         if (fd < 0)
5042                 return fd;
5043
5044         loop_write(fd,
5045                    "\033[r"   /* clear scrolling region */
5046                    "\033[H"   /* move home */
5047                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
5048                    10, false);
5049         close_nointr_nofail(fd);
5050
5051         return 0;
5052 }
5053
5054 static int files_add(Hashmap *h, const char *path, const char *suffix) {
5055         DIR *dir;
5056         struct dirent buffer, *de;
5057         int r = 0;
5058
5059         dir = opendir(path);
5060         if (!dir) {
5061                 if (errno == ENOENT)
5062                         return 0;
5063                 return -errno;
5064         }
5065
5066         for (;;) {
5067                 int k;
5068                 char *p, *f;
5069
5070                 k = readdir_r(dir, &buffer, &de);
5071                 if (k != 0) {
5072                         r = -k;
5073                         goto finish;
5074                 }
5075
5076                 if (!de)
5077                         break;
5078
5079                 if (!dirent_is_file_with_suffix(de, suffix))
5080                         continue;
5081
5082                 if (asprintf(&p, "%s/%s", path, de->d_name) < 0) {
5083                         r = -ENOMEM;
5084                         goto finish;
5085                 }
5086
5087                 f = canonicalize_file_name(p);
5088                 if (!f) {
5089                         log_error("Failed to canonicalize file name '%s': %m", p);
5090                         free(p);
5091                         continue;
5092                 }
5093                 free(p);
5094
5095                 log_debug("found: %s\n", f);
5096                 if (hashmap_put(h, file_name_from_path(f), f) <= 0)
5097                         free(f);
5098         }
5099
5100 finish:
5101         closedir(dir);
5102         return r;
5103 }
5104
5105 static int base_cmp(const void *a, const void *b) {
5106         const char *s1, *s2;
5107
5108         s1 = *(char * const *)a;
5109         s2 = *(char * const *)b;
5110         return strcmp(file_name_from_path(s1), file_name_from_path(s2));
5111 }
5112
5113 int conf_files_list(char ***strv, const char *suffix, const char *dir, ...) {
5114         Hashmap *fh = NULL;
5115         char **dirs = NULL;
5116         char **files = NULL;
5117         char **p;
5118         va_list ap;
5119         int r = 0;
5120
5121         va_start(ap, dir);
5122         dirs = strv_new_ap(dir, ap);
5123         va_end(ap);
5124         if (!dirs) {
5125                 r = -ENOMEM;
5126                 goto finish;
5127         }
5128         if (!strv_path_canonicalize(dirs)) {
5129                 r = -ENOMEM;
5130                 goto finish;
5131         }
5132         if (!strv_uniq(dirs)) {
5133                 r = -ENOMEM;
5134                 goto finish;
5135         }
5136
5137         fh = hashmap_new(string_hash_func, string_compare_func);
5138         if (!fh) {
5139                 r = -ENOMEM;
5140                 goto finish;
5141         }
5142
5143         STRV_FOREACH(p, dirs) {
5144                 if (files_add(fh, *p, suffix) < 0) {
5145                         log_error("Failed to search for files.");
5146                         r = -EINVAL;
5147                         goto finish;
5148                 }
5149         }
5150
5151         files = hashmap_get_strv(fh);
5152         if (files == NULL) {
5153                 log_error("Failed to compose list of files.");
5154                 r = -ENOMEM;
5155                 goto finish;
5156         }
5157
5158         qsort(files, hashmap_size(fh), sizeof(char *), base_cmp);
5159
5160 finish:
5161         strv_free(dirs);
5162         hashmap_free(fh);
5163         *strv = files;
5164         return r;
5165 }
5166
5167 int hwclock_is_localtime(void) {
5168         FILE *f;
5169         bool local = false;
5170
5171         /*
5172          * The third line of adjtime is "UTC" or "LOCAL" or nothing.
5173          *   # /etc/adjtime
5174          *   0.0 0 0
5175          *   0
5176          *   UTC
5177          */
5178         f = fopen("/etc/adjtime", "re");
5179         if (f) {
5180                 char line[LINE_MAX];
5181                 bool b;
5182
5183                 b = fgets(line, sizeof(line), f) &&
5184                         fgets(line, sizeof(line), f) &&
5185                         fgets(line, sizeof(line), f);
5186
5187                 fclose(f);
5188
5189                 if (!b)
5190                         return -EIO;
5191
5192
5193                 truncate_nl(line);
5194                 local = streq(line, "LOCAL");
5195
5196         } else if (errno != -ENOENT)
5197                 return -errno;
5198
5199         return local;
5200 }
5201
5202 int hwclock_apply_localtime_delta(int *min) {
5203         const struct timeval *tv_null = NULL;
5204         struct timespec ts;
5205         struct tm *tm;
5206         int minuteswest;
5207         struct timezone tz;
5208
5209         assert_se(clock_gettime(CLOCK_REALTIME, &ts) == 0);
5210         assert_se(tm = localtime(&ts.tv_sec));
5211         minuteswest = tm->tm_gmtoff / 60;
5212
5213         tz.tz_minuteswest = -minuteswest;
5214         tz.tz_dsttime = 0; /* DST_NONE*/
5215
5216         /*
5217          * If the hardware clock does not run in UTC, but in local time:
5218          * The very first time we set the kernel's timezone, it will warp
5219          * the clock so that it runs in UTC instead of local time.
5220          */
5221         if (settimeofday(tv_null, &tz) < 0)
5222                 return -errno;
5223         if (min)
5224                 *min = minuteswest;
5225         return 0;
5226 }
5227
5228 int hwclock_reset_localtime_delta(void) {
5229         const struct timeval *tv_null = NULL;
5230         struct timezone tz;
5231
5232         tz.tz_minuteswest = 0;
5233         tz.tz_dsttime = 0; /* DST_NONE*/
5234
5235         if (settimeofday(tv_null, &tz) < 0)
5236                 return -errno;
5237
5238         return 0;
5239 }
5240
5241 int rtc_open(int flags) {
5242         int fd;
5243         DIR *d;
5244
5245         /* First, we try to make use of the /dev/rtc symlink. If that
5246          * doesn't exist, we open the first RTC which has hctosys=1
5247          * set. If we don't find any we just take the first RTC that
5248          * exists at all. */
5249
5250         fd = open("/dev/rtc", flags);
5251         if (fd >= 0)
5252                 return fd;
5253
5254         d = opendir("/sys/class/rtc");
5255         if (!d)
5256                 goto fallback;
5257
5258         for (;;) {
5259                 char *p, *v;
5260                 struct dirent buf, *de;
5261                 int r;
5262
5263                 r = readdir_r(d, &buf, &de);
5264                 if (r != 0)
5265                         goto fallback;
5266
5267                 if (!de)
5268                         goto fallback;
5269
5270                 if (ignore_file(de->d_name))
5271                         continue;
5272
5273                 p = join("/sys/class/rtc/", de->d_name, "/hctosys", NULL);
5274                 if (!p) {
5275                         closedir(d);
5276                         return -ENOMEM;
5277                 }
5278
5279                 r = read_one_line_file(p, &v);
5280                 free(p);
5281
5282                 if (r < 0)
5283                         continue;
5284
5285                 r = parse_boolean(v);
5286                 free(v);
5287
5288                 if (r <= 0)
5289                         continue;
5290
5291                 p = strappend("/dev/", de->d_name);
5292                 fd = open(p, flags);
5293                 free(p);
5294
5295                 if (fd >= 0) {
5296                         closedir(d);
5297                         return fd;
5298                 }
5299         }
5300
5301 fallback:
5302         if (d)
5303                 closedir(d);
5304
5305         fd = open("/dev/rtc0", flags);
5306         if (fd < 0)
5307                 return -errno;
5308
5309         return fd;
5310 }
5311
5312 int hwclock_get_time(struct tm *tm) {
5313         int fd;
5314         int err = 0;
5315
5316         assert(tm);
5317
5318         fd = rtc_open(O_RDONLY|O_CLOEXEC);
5319         if (fd < 0)
5320                 return -errno;
5321
5322         /* This leaves the timezone fields of struct tm
5323          * uninitialized! */
5324         if (ioctl(fd, RTC_RD_TIME, tm) < 0)
5325                 err = -errno;
5326
5327         /* We don't now daylight saving, so we reset this in order not
5328          * to confused mktime(). */
5329         tm->tm_isdst = -1;
5330
5331         close_nointr_nofail(fd);
5332
5333         return err;
5334 }
5335
5336 int hwclock_set_time(const struct tm *tm) {
5337         int fd;
5338         int err = 0;
5339
5340         assert(tm);
5341
5342         fd = rtc_open(O_RDONLY|O_CLOEXEC);
5343         if (fd < 0)
5344                 return -errno;
5345
5346         if (ioctl(fd, RTC_SET_TIME, tm) < 0)
5347                 err = -errno;
5348
5349         close_nointr_nofail(fd);
5350
5351         return err;
5352 }
5353
5354 int copy_file(const char *from, const char *to) {
5355         int r, fdf, fdt;
5356
5357         assert(from);
5358         assert(to);
5359
5360         fdf = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
5361         if (fdf < 0)
5362                 return -errno;
5363
5364         fdt = open(to, O_WRONLY|O_CREAT|O_EXCL|O_CLOEXEC|O_NOCTTY, 0644);
5365         if (fdt < 0) {
5366                 close_nointr_nofail(fdf);
5367                 return -errno;
5368         }
5369
5370         for (;;) {
5371                 char buf[PIPE_BUF];
5372                 ssize_t n, k;
5373
5374                 n = read(fdf, buf, sizeof(buf));
5375                 if (n < 0) {
5376                         r = -errno;
5377
5378                         close_nointr_nofail(fdf);
5379                         close_nointr(fdt);
5380                         unlink(to);
5381
5382                         return r;
5383                 }
5384
5385                 if (n == 0)
5386                         break;
5387
5388                 errno = 0;
5389                 k = loop_write(fdt, buf, n, false);
5390                 if (n != k) {
5391                         r = k < 0 ? k : (errno ? -errno : -EIO);
5392
5393                         close_nointr_nofail(fdf);
5394                         close_nointr(fdt);
5395
5396                         unlink(to);
5397                         return r;
5398                 }
5399         }
5400
5401         close_nointr_nofail(fdf);
5402         r = close_nointr(fdt);
5403
5404         if (r < 0) {
5405                 unlink(to);
5406                 return r;
5407         }
5408
5409         return 0;
5410 }
5411
5412 int symlink_or_copy(const char *from, const char *to) {
5413         char *pf = NULL, *pt = NULL;
5414         struct stat a, b;
5415         int r;
5416
5417         assert(from);
5418         assert(to);
5419
5420         if (parent_of_path(from, &pf) < 0 ||
5421             parent_of_path(to, &pt) < 0) {
5422                 r = -ENOMEM;
5423                 goto finish;
5424         }
5425
5426         if (stat(pf, &a) < 0 ||
5427             stat(pt, &b) < 0) {
5428                 r = -errno;
5429                 goto finish;
5430         }
5431
5432         if (a.st_dev != b.st_dev) {
5433                 free(pf);
5434                 free(pt);
5435
5436                 return copy_file(from, to);
5437         }
5438
5439         if (symlink(from, to) < 0) {
5440                 r = -errno;
5441                 goto finish;
5442         }
5443
5444         r = 0;
5445
5446 finish:
5447         free(pf);
5448         free(pt);
5449
5450         return r;
5451 }
5452
5453 int symlink_or_copy_atomic(const char *from, const char *to) {
5454         char *t, *x;
5455         const char *fn;
5456         size_t k;
5457         unsigned long long ull;
5458         unsigned i;
5459         int r;
5460
5461         assert(from);
5462         assert(to);
5463
5464         t = new(char, strlen(to) + 1 + 16 + 1);
5465         if (!t)
5466                 return -ENOMEM;
5467
5468         fn = file_name_from_path(to);
5469         k = fn-to;
5470         memcpy(t, to, k);
5471         t[k] = '.';
5472         x = stpcpy(t+k+1, fn);
5473
5474         ull = random_ull();
5475         for (i = 0; i < 16; i++) {
5476                 *(x++) = hexchar(ull & 0xF);
5477                 ull >>= 4;
5478         }
5479
5480         *x = 0;
5481
5482         r = symlink_or_copy(from, t);
5483         if (r < 0) {
5484                 unlink(t);
5485                 free(t);
5486                 return r;
5487         }
5488
5489         if (rename(t, to) < 0) {
5490                 r = -errno;
5491                 unlink(t);
5492                 free(t);
5493                 return r;
5494         }
5495
5496         free(t);
5497         return r;
5498 }
5499
5500 int audit_session_from_pid(pid_t pid, uint32_t *id) {
5501         char *s;
5502         uint32_t u;
5503         int r;
5504
5505         assert(id);
5506
5507         if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5508                 return -ENOENT;
5509
5510         if (pid == 0)
5511                 r = read_one_line_file("/proc/self/sessionid", &s);
5512         else {
5513                 char *p;
5514
5515                 if (asprintf(&p, "/proc/%lu/sessionid", (unsigned long) pid) < 0)
5516                         return -ENOMEM;
5517
5518                 r = read_one_line_file(p, &s);
5519                 free(p);
5520         }
5521
5522         if (r < 0)
5523                 return r;
5524
5525         r = safe_atou32(s, &u);
5526         free(s);
5527
5528         if (r < 0)
5529                 return r;
5530
5531         if (u == (uint32_t) -1 || u <= 0)
5532                 return -ENOENT;
5533
5534         *id = u;
5535         return 0;
5536 }
5537
5538 int audit_loginuid_from_pid(pid_t pid, uid_t *uid) {
5539         char *s;
5540         uid_t u;
5541         int r;
5542
5543         assert(uid);
5544
5545         /* Only use audit login uid if we are executed with sufficient
5546          * capabilities so that pam_loginuid could do its job. If we
5547          * are lacking the CAP_AUDIT_CONTROL capabality we most likely
5548          * are being run in a container and /proc/self/loginuid is
5549          * useless since it probably contains a uid of the host
5550          * system. */
5551
5552         if (have_effective_cap(CAP_AUDIT_CONTROL) <= 0)
5553                 return -ENOENT;
5554
5555         if (pid == 0)
5556                 r = read_one_line_file("/proc/self/loginuid", &s);
5557         else {
5558                 char *p;
5559
5560                 if (asprintf(&p, "/proc/%lu/loginuid", (unsigned long) pid) < 0)
5561                         return -ENOMEM;
5562
5563                 r = read_one_line_file(p, &s);
5564                 free(p);
5565         }
5566
5567         if (r < 0)
5568                 return r;
5569
5570         r = parse_uid(s, &u);
5571         free(s);
5572
5573         if (r < 0)
5574                 return r;
5575
5576         if (u == (uid_t) -1)
5577                 return -ENOENT;
5578
5579         *uid = (uid_t) u;
5580         return 0;
5581 }
5582
5583 bool display_is_local(const char *display) {
5584         assert(display);
5585
5586         return
5587                 display[0] == ':' &&
5588                 display[1] >= '0' &&
5589                 display[1] <= '9';
5590 }
5591
5592 int socket_from_display(const char *display, char **path) {
5593         size_t k;
5594         char *f, *c;
5595
5596         assert(display);
5597         assert(path);
5598
5599         if (!display_is_local(display))
5600                 return -EINVAL;
5601
5602         k = strspn(display+1, "0123456789");
5603
5604         f = new(char, sizeof("/tmp/.X11-unix/X") + k);
5605         if (!f)
5606                 return -ENOMEM;
5607
5608         c = stpcpy(f, "/tmp/.X11-unix/X");
5609         memcpy(c, display+1, k);
5610         c[k] = 0;
5611
5612         *path = f;
5613
5614         return 0;
5615 }
5616
5617 int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
5618         struct passwd *p;
5619         uid_t u;
5620
5621         assert(username);
5622         assert(*username);
5623
5624         /* We enforce some special rules for uid=0: in order to avoid
5625          * NSS lookups for root we hardcode its data. */
5626
5627         if (streq(*username, "root") || streq(*username, "0")) {
5628                 *username = "root";
5629
5630                 if (uid)
5631                         *uid = 0;
5632
5633                 if (gid)
5634                         *gid = 0;
5635
5636                 if (home)
5637                         *home = "/root";
5638                 return 0;
5639         }
5640
5641         if (parse_uid(*username, &u) >= 0) {
5642                 errno = 0;
5643                 p = getpwuid(u);
5644
5645                 /* If there are multiple users with the same id, make
5646                  * sure to leave $USER to the configured value instead
5647                  * of the first occurrence in the database. However if
5648                  * the uid was configured by a numeric uid, then let's
5649                  * pick the real username from /etc/passwd. */
5650                 if (p)
5651                         *username = p->pw_name;
5652         } else {
5653                 errno = 0;
5654                 p = getpwnam(*username);
5655         }
5656
5657         if (!p)
5658                 return errno != 0 ? -errno : -ESRCH;
5659
5660         if (uid)
5661                 *uid = p->pw_uid;
5662
5663         if (gid)
5664                 *gid = p->pw_gid;
5665
5666         if (home)
5667                 *home = p->pw_dir;
5668
5669         return 0;
5670 }
5671
5672 int get_group_creds(const char **groupname, gid_t *gid) {
5673         struct group *g;
5674         gid_t id;
5675
5676         assert(groupname);
5677
5678         /* We enforce some special rules for gid=0: in order to avoid
5679          * NSS lookups for root we hardcode its data. */
5680
5681         if (streq(*groupname, "root") || streq(*groupname, "0")) {
5682                 *groupname = "root";
5683
5684                 if (gid)
5685                         *gid = 0;
5686
5687                 return 0;
5688         }
5689
5690         if (parse_gid(*groupname, &id) >= 0) {
5691                 errno = 0;
5692                 g = getgrgid(id);
5693
5694                 if (g)
5695                         *groupname = g->gr_name;
5696         } else {
5697                 errno = 0;
5698                 g = getgrnam(*groupname);
5699         }
5700
5701         if (!g)
5702                 return errno != 0 ? -errno : -ESRCH;
5703
5704         if (gid)
5705                 *gid = g->gr_gid;
5706
5707         return 0;
5708 }
5709
5710 int glob_exists(const char *path) {
5711         glob_t g;
5712         int r, k;
5713
5714         assert(path);
5715
5716         zero(g);
5717         errno = 0;
5718         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
5719
5720         if (k == GLOB_NOMATCH)
5721                 r = 0;
5722         else if (k == GLOB_NOSPACE)
5723                 r = -ENOMEM;
5724         else if (k == 0)
5725                 r = !strv_isempty(g.gl_pathv);
5726         else
5727                 r = errno ? -errno : -EIO;
5728
5729         globfree(&g);
5730
5731         return r;
5732 }
5733
5734 int dirent_ensure_type(DIR *d, struct dirent *de) {
5735         struct stat st;
5736
5737         assert(d);
5738         assert(de);
5739
5740         if (de->d_type != DT_UNKNOWN)
5741                 return 0;
5742
5743         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
5744                 return -errno;
5745
5746         de->d_type =
5747                 S_ISREG(st.st_mode)  ? DT_REG  :
5748                 S_ISDIR(st.st_mode)  ? DT_DIR  :
5749                 S_ISLNK(st.st_mode)  ? DT_LNK  :
5750                 S_ISFIFO(st.st_mode) ? DT_FIFO :
5751                 S_ISSOCK(st.st_mode) ? DT_SOCK :
5752                 S_ISCHR(st.st_mode)  ? DT_CHR  :
5753                 S_ISBLK(st.st_mode)  ? DT_BLK  :
5754                                        DT_UNKNOWN;
5755
5756         return 0;
5757 }
5758
5759 int in_search_path(const char *path, char **search) {
5760         char **i, *parent;
5761         int r;
5762
5763         r = parent_of_path(path, &parent);
5764         if (r < 0)
5765                 return r;
5766
5767         r = 0;
5768
5769         STRV_FOREACH(i, search) {
5770                 if (path_equal(parent, *i)) {
5771                         r = 1;
5772                         break;
5773                 }
5774         }
5775
5776         free(parent);
5777
5778         return r;
5779 }
5780
5781 int get_files_in_directory(const char *path, char ***list) {
5782         DIR *d;
5783         int r = 0;
5784         unsigned n = 0;
5785         char **l = NULL;
5786
5787         assert(path);
5788
5789         /* Returns all files in a directory in *list, and the number
5790          * of files as return value. If list is NULL returns only the
5791          * number */
5792
5793         d = opendir(path);
5794         if (!d)
5795                 return -errno;
5796
5797         for (;;) {
5798                 struct dirent buffer, *de;
5799                 int k;
5800
5801                 k = readdir_r(d, &buffer, &de);
5802                 if (k != 0) {
5803                         r = -k;
5804                         goto finish;
5805                 }
5806
5807                 if (!de)
5808                         break;
5809
5810                 dirent_ensure_type(d, de);
5811
5812                 if (!dirent_is_file(de))
5813                         continue;
5814
5815                 if (list) {
5816                         if ((unsigned) r >= n) {
5817                                 char **t;
5818
5819                                 n = MAX(16, 2*r);
5820                                 t = realloc(l, sizeof(char*) * n);
5821                                 if (!t) {
5822                                         r = -ENOMEM;
5823                                         goto finish;
5824                                 }
5825
5826                                 l = t;
5827                         }
5828
5829                         assert((unsigned) r < n);
5830
5831                         l[r] = strdup(de->d_name);
5832                         if (!l[r]) {
5833                                 r = -ENOMEM;
5834                                 goto finish;
5835                         }
5836
5837                         l[++r] = NULL;
5838                 } else
5839                         r++;
5840         }
5841
5842 finish:
5843         if (d)
5844                 closedir(d);
5845
5846         if (r >= 0) {
5847                 if (list)
5848                         *list = l;
5849         } else
5850                 strv_free(l);
5851
5852         return r;
5853 }
5854
5855 char *join(const char *x, ...) {
5856         va_list ap;
5857         size_t l;
5858         char *r, *p;
5859
5860         va_start(ap, x);
5861
5862         if (x) {
5863                 l = strlen(x);
5864
5865                 for (;;) {
5866                         const char *t;
5867
5868                         t = va_arg(ap, const char *);
5869                         if (!t)
5870                                 break;
5871
5872                         l += strlen(t);
5873                 }
5874         } else
5875                 l = 0;
5876
5877         va_end(ap);
5878
5879         r = new(char, l+1);
5880         if (!r)
5881                 return NULL;
5882
5883         if (x) {
5884                 p = stpcpy(r, x);
5885
5886                 va_start(ap, x);
5887
5888                 for (;;) {
5889                         const char *t;
5890
5891                         t = va_arg(ap, const char *);
5892                         if (!t)
5893                                 break;
5894
5895                         p = stpcpy(p, t);
5896                 }
5897
5898                 va_end(ap);
5899         } else
5900                 r[0] = 0;
5901
5902         return r;
5903 }
5904
5905 bool is_main_thread(void) {
5906         static __thread int cached = 0;
5907
5908         if (_unlikely_(cached == 0))
5909                 cached = getpid() == gettid() ? 1 : -1;
5910
5911         return cached > 0;
5912 }
5913
5914 int block_get_whole_disk(dev_t d, dev_t *ret) {
5915         char *p, *s;
5916         int r;
5917         unsigned n, m;
5918
5919         assert(ret);
5920
5921         /* If it has a queue this is good enough for us */
5922         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
5923                 return -ENOMEM;
5924
5925         r = access(p, F_OK);
5926         free(p);
5927
5928         if (r >= 0) {
5929                 *ret = d;
5930                 return 0;
5931         }
5932
5933         /* If it is a partition find the originating device */
5934         if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
5935                 return -ENOMEM;
5936
5937         r = access(p, F_OK);
5938         free(p);
5939
5940         if (r < 0)
5941                 return -ENOENT;
5942
5943         /* Get parent dev_t */
5944         if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
5945                 return -ENOMEM;
5946
5947         r = read_one_line_file(p, &s);
5948         free(p);
5949
5950         if (r < 0)
5951                 return r;
5952
5953         r = sscanf(s, "%u:%u", &m, &n);
5954         free(s);
5955
5956         if (r != 2)
5957                 return -EINVAL;
5958
5959         /* Only return this if it is really good enough for us. */
5960         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
5961                 return -ENOMEM;
5962
5963         r = access(p, F_OK);
5964         free(p);
5965
5966         if (r >= 0) {
5967                 *ret = makedev(m, n);
5968                 return 0;
5969         }
5970
5971         return -ENOENT;
5972 }
5973
5974 int file_is_priv_sticky(const char *p) {
5975         struct stat st;
5976
5977         assert(p);
5978
5979         if (lstat(p, &st) < 0)
5980                 return -errno;
5981
5982         return
5983                 (st.st_uid == 0 || st.st_uid == getuid()) &&
5984                 (st.st_mode & S_ISVTX);
5985 }
5986
5987 static const char *const ioprio_class_table[] = {
5988         [IOPRIO_CLASS_NONE] = "none",
5989         [IOPRIO_CLASS_RT] = "realtime",
5990         [IOPRIO_CLASS_BE] = "best-effort",
5991         [IOPRIO_CLASS_IDLE] = "idle"
5992 };
5993
5994 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
5995
5996 static const char *const sigchld_code_table[] = {
5997         [CLD_EXITED] = "exited",
5998         [CLD_KILLED] = "killed",
5999         [CLD_DUMPED] = "dumped",
6000         [CLD_TRAPPED] = "trapped",
6001         [CLD_STOPPED] = "stopped",
6002         [CLD_CONTINUED] = "continued",
6003 };
6004
6005 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
6006
6007 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
6008         [LOG_FAC(LOG_KERN)] = "kern",
6009         [LOG_FAC(LOG_USER)] = "user",
6010         [LOG_FAC(LOG_MAIL)] = "mail",
6011         [LOG_FAC(LOG_DAEMON)] = "daemon",
6012         [LOG_FAC(LOG_AUTH)] = "auth",
6013         [LOG_FAC(LOG_SYSLOG)] = "syslog",
6014         [LOG_FAC(LOG_LPR)] = "lpr",
6015         [LOG_FAC(LOG_NEWS)] = "news",
6016         [LOG_FAC(LOG_UUCP)] = "uucp",
6017         [LOG_FAC(LOG_CRON)] = "cron",
6018         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
6019         [LOG_FAC(LOG_FTP)] = "ftp",
6020         [LOG_FAC(LOG_LOCAL0)] = "local0",
6021         [LOG_FAC(LOG_LOCAL1)] = "local1",
6022         [LOG_FAC(LOG_LOCAL2)] = "local2",
6023         [LOG_FAC(LOG_LOCAL3)] = "local3",
6024         [LOG_FAC(LOG_LOCAL4)] = "local4",
6025         [LOG_FAC(LOG_LOCAL5)] = "local5",
6026         [LOG_FAC(LOG_LOCAL6)] = "local6",
6027         [LOG_FAC(LOG_LOCAL7)] = "local7"
6028 };
6029
6030 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted, int);
6031
6032 static const char *const log_level_table[] = {
6033         [LOG_EMERG] = "emerg",
6034         [LOG_ALERT] = "alert",
6035         [LOG_CRIT] = "crit",
6036         [LOG_ERR] = "err",
6037         [LOG_WARNING] = "warning",
6038         [LOG_NOTICE] = "notice",
6039         [LOG_INFO] = "info",
6040         [LOG_DEBUG] = "debug"
6041 };
6042
6043 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
6044
6045 static const char* const sched_policy_table[] = {
6046         [SCHED_OTHER] = "other",
6047         [SCHED_BATCH] = "batch",
6048         [SCHED_IDLE] = "idle",
6049         [SCHED_FIFO] = "fifo",
6050         [SCHED_RR] = "rr"
6051 };
6052
6053 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
6054
6055 static const char* const rlimit_table[] = {
6056         [RLIMIT_CPU] = "LimitCPU",
6057         [RLIMIT_FSIZE] = "LimitFSIZE",
6058         [RLIMIT_DATA] = "LimitDATA",
6059         [RLIMIT_STACK] = "LimitSTACK",
6060         [RLIMIT_CORE] = "LimitCORE",
6061         [RLIMIT_RSS] = "LimitRSS",
6062         [RLIMIT_NOFILE] = "LimitNOFILE",
6063         [RLIMIT_AS] = "LimitAS",
6064         [RLIMIT_NPROC] = "LimitNPROC",
6065         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
6066         [RLIMIT_LOCKS] = "LimitLOCKS",
6067         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
6068         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
6069         [RLIMIT_NICE] = "LimitNICE",
6070         [RLIMIT_RTPRIO] = "LimitRTPRIO",
6071         [RLIMIT_RTTIME] = "LimitRTTIME"
6072 };
6073
6074 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
6075
6076 static const char* const ip_tos_table[] = {
6077         [IPTOS_LOWDELAY] = "low-delay",
6078         [IPTOS_THROUGHPUT] = "throughput",
6079         [IPTOS_RELIABILITY] = "reliability",
6080         [IPTOS_LOWCOST] = "low-cost",
6081 };
6082
6083 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
6084
6085 static const char *const __signal_table[] = {
6086         [SIGHUP] = "HUP",
6087         [SIGINT] = "INT",
6088         [SIGQUIT] = "QUIT",
6089         [SIGILL] = "ILL",
6090         [SIGTRAP] = "TRAP",
6091         [SIGABRT] = "ABRT",
6092         [SIGBUS] = "BUS",
6093         [SIGFPE] = "FPE",
6094         [SIGKILL] = "KILL",
6095         [SIGUSR1] = "USR1",
6096         [SIGSEGV] = "SEGV",
6097         [SIGUSR2] = "USR2",
6098         [SIGPIPE] = "PIPE",
6099         [SIGALRM] = "ALRM",
6100         [SIGTERM] = "TERM",
6101 #ifdef SIGSTKFLT
6102         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
6103 #endif
6104         [SIGCHLD] = "CHLD",
6105         [SIGCONT] = "CONT",
6106         [SIGSTOP] = "STOP",
6107         [SIGTSTP] = "TSTP",
6108         [SIGTTIN] = "TTIN",
6109         [SIGTTOU] = "TTOU",
6110         [SIGURG] = "URG",
6111         [SIGXCPU] = "XCPU",
6112         [SIGXFSZ] = "XFSZ",
6113         [SIGVTALRM] = "VTALRM",
6114         [SIGPROF] = "PROF",
6115         [SIGWINCH] = "WINCH",
6116         [SIGIO] = "IO",
6117         [SIGPWR] = "PWR",
6118         [SIGSYS] = "SYS"
6119 };
6120
6121 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
6122
6123 const char *signal_to_string(int signo) {
6124         static __thread char buf[12];
6125         const char *name;
6126
6127         name = __signal_to_string(signo);
6128         if (name)
6129                 return name;
6130
6131         if (signo >= SIGRTMIN && signo <= SIGRTMAX)
6132                 snprintf(buf, sizeof(buf) - 1, "RTMIN+%d", signo - SIGRTMIN);
6133         else
6134                 snprintf(buf, sizeof(buf) - 1, "%d", signo);
6135         char_array_0(buf);
6136         return buf;
6137 }
6138
6139 int signal_from_string(const char *s) {
6140         int signo;
6141         int offset = 0;
6142         unsigned u;
6143
6144         signo =__signal_from_string(s);
6145         if (signo > 0)
6146                 return signo;
6147
6148         if (startswith(s, "RTMIN+")) {
6149                 s += 6;
6150                 offset = SIGRTMIN;
6151         }
6152         if (safe_atou(s, &u) >= 0) {
6153                 signo = (int) u + offset;
6154                 if (signo > 0 && signo < _NSIG)
6155                         return signo;
6156         }
6157         return -1;
6158 }
6159
6160 bool kexec_loaded(void) {
6161        bool loaded = false;
6162        char *s;
6163
6164        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
6165                if (s[0] == '1')
6166                        loaded = true;
6167                free(s);
6168        }
6169        return loaded;
6170 }
6171
6172 int strdup_or_null(const char *a, char **b) {
6173         char *c;
6174
6175         assert(b);
6176
6177         if (!a) {
6178                 *b = NULL;
6179                 return 0;
6180         }
6181
6182         c = strdup(a);
6183         if (!c)
6184                 return -ENOMEM;
6185
6186         *b = c;
6187         return 0;
6188 }
6189
6190 int prot_from_flags(int flags) {
6191
6192         switch (flags & O_ACCMODE) {
6193
6194         case O_RDONLY:
6195                 return PROT_READ;
6196
6197         case O_WRONLY:
6198                 return PROT_WRITE;
6199
6200         case O_RDWR:
6201                 return PROT_READ|PROT_WRITE;
6202
6203         default:
6204                 return -EINVAL;
6205         }
6206 }
6207
6208 unsigned long cap_last_cap(void) {
6209         static __thread unsigned long saved;
6210         static __thread bool valid = false;
6211         unsigned long p;
6212
6213         if (valid)
6214                 return saved;
6215
6216         p = (unsigned long) CAP_LAST_CAP;
6217
6218         if (prctl(PR_CAPBSET_READ, p) < 0) {
6219
6220                 /* Hmm, look downwards, until we find one that
6221                  * works */
6222                 for (p--; p > 0; p --)
6223                         if (prctl(PR_CAPBSET_READ, p) >= 0)
6224                                 break;
6225
6226         } else {
6227
6228                 /* Hmm, look upwards, until we find one that doesn't
6229                  * work */
6230                 for (;; p++)
6231                         if (prctl(PR_CAPBSET_READ, p+1) < 0)
6232                                 break;
6233         }
6234
6235         saved = p;
6236         valid = true;
6237
6238         return p;
6239 }
6240
6241 char *format_bytes(char *buf, size_t l, off_t t) {
6242         unsigned i;
6243
6244         static const struct {
6245                 const char *suffix;
6246                 off_t factor;
6247         } table[] = {
6248                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6249                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
6250                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
6251                 { "G", 1024ULL*1024ULL*1024ULL },
6252                 { "M", 1024ULL*1024ULL },
6253                 { "K", 1024ULL },
6254         };
6255
6256         for (i = 0; i < ELEMENTSOF(table); i++) {
6257
6258                 if (t >= table[i].factor) {
6259                         snprintf(buf, l,
6260                                  "%llu.%llu%s",
6261                                  (unsigned long long) (t / table[i].factor),
6262                                  (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
6263                                  table[i].suffix);
6264
6265                         goto finish;
6266                 }
6267         }
6268
6269         snprintf(buf, l, "%lluB", (unsigned long long) t);
6270
6271 finish:
6272         buf[l-1] = 0;
6273         return buf;
6274
6275 }
6276
6277 void* memdup(const void *p, size_t l) {
6278         void *r;
6279
6280         assert(p);
6281
6282         r = malloc(l);
6283         if (!r)
6284                 return NULL;
6285
6286         memcpy(r, p, l);
6287         return r;
6288 }
6289
6290 int fd_inc_sndbuf(int fd, size_t n) {
6291         int r, value;
6292         socklen_t l = sizeof(value);
6293
6294         r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
6295         if (r >= 0 &&
6296             l == sizeof(value) &&
6297             (size_t) value >= n*2)
6298                 return 0;
6299
6300         value = (int) n;
6301         r = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value));
6302         if (r < 0)
6303                 return -errno;
6304
6305         return 1;
6306 }
6307
6308 int fd_inc_rcvbuf(int fd, size_t n) {
6309         int r, value;
6310         socklen_t l = sizeof(value);
6311
6312         r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
6313         if (r >= 0 &&
6314             l == sizeof(value) &&
6315             (size_t) value >= n*2)
6316                 return 0;
6317
6318         value = (int) n;
6319         r = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value));
6320         if (r < 0)
6321                 return -errno;
6322
6323         return 1;
6324 }