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