chiark / gitweb /
863371c0dcd0bcbbd4f5f16884fc3caa4fba9dda
[elogind.git] / src / shared / 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 Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 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   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <string.h>
23 #include <unistd.h>
24 #include <errno.h>
25 #include <stdlib.h>
26 #include <signal.h>
27 #include <libintl.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 <poll.h>
43 #include <ctype.h>
44 #include <sys/prctl.h>
45 #include <sys/utsname.h>
46 #include <pwd.h>
47 #include <netinet/ip.h>
48 #include <linux/kd.h>
49 #include <sys/wait.h>
50 #include <sys/time.h>
51 #include <glob.h>
52 #include <grp.h>
53 #include <sys/mman.h>
54 #include <sys/vfs.h>
55 #include <sys/mount.h>
56 #include <linux/magic.h>
57 #include <limits.h>
58 #include <langinfo.h>
59 #include <locale.h>
60 #include <sys/personality.h>
61 #include <sys/xattr.h>
62 #include <sys/statvfs.h>
63 #include <sys/file.h>
64 #include <linux/fs.h>
65
66 /* When we include libgen.h because we need dirname() we immediately
67  * undefine basename() since libgen.h defines it as a macro to the XDG
68  * version which is really broken. */
69 #include <libgen.h>
70 #undef basename
71
72 #ifdef HAVE_SYS_AUXV_H
73 #include <sys/auxv.h>
74 #endif
75
76 #include "config.h"
77 #include "macro.h"
78 #include "util.h"
79 #include "ioprio.h"
80 #include "missing.h"
81 #include "log.h"
82 #include "strv.h"
83 #include "mkdir.h"
84 #include "path-util.h"
85 #include "exit-status.h"
86 #include "hashmap.h"
87 #include "env-util.h"
88 #include "fileio.h"
89 #include "device-nodes.h"
90 #include "utf8.h"
91 #include "gunicode.h"
92 #include "virt.h"
93 #include "def.h"
94 #include "sparse-endian.h"
95 #include "formats-util.h"
96 #include "process-util.h"
97
98 /* Put this test here for a lack of better place */
99 assert_cc(EAGAIN == EWOULDBLOCK);
100
101 int saved_argc = 0;
102 char **saved_argv = NULL;
103
104 static volatile unsigned cached_columns = 0;
105 static volatile unsigned cached_lines = 0;
106
107 size_t page_size(void) {
108         static thread_local size_t pgsz = 0;
109         long r;
110
111         if (_likely_(pgsz > 0))
112                 return pgsz;
113
114         r = sysconf(_SC_PAGESIZE);
115         assert(r > 0);
116
117         pgsz = (size_t) r;
118         return pgsz;
119 }
120
121 bool streq_ptr(const char *a, const char *b) {
122
123         /* Like streq(), but tries to make sense of NULL pointers */
124
125         if (a && b)
126                 return streq(a, b);
127
128         if (!a && !b)
129                 return true;
130
131         return false;
132 }
133
134 char* endswith(const char *s, const char *postfix) {
135         size_t sl, pl;
136
137         assert(s);
138         assert(postfix);
139
140         sl = strlen(s);
141         pl = strlen(postfix);
142
143         if (pl == 0)
144                 return (char*) s + sl;
145
146         if (sl < pl)
147                 return NULL;
148
149         if (memcmp(s + sl - pl, postfix, pl) != 0)
150                 return NULL;
151
152         return (char*) s + sl - pl;
153 }
154
155 char* first_word(const char *s, const char *word) {
156         size_t sl, wl;
157         const char *p;
158
159         assert(s);
160         assert(word);
161
162         /* Checks if the string starts with the specified word, either
163          * followed by NUL or by whitespace. Returns a pointer to the
164          * NUL or the first character after the whitespace. */
165
166         sl = strlen(s);
167         wl = strlen(word);
168
169         if (sl < wl)
170                 return NULL;
171
172         if (wl == 0)
173                 return (char*) s;
174
175         if (memcmp(s, word, wl) != 0)
176                 return NULL;
177
178         p = s + wl;
179         if (*p == 0)
180                 return (char*) p;
181
182         if (!strchr(WHITESPACE, *p))
183                 return NULL;
184
185         p += strspn(p, WHITESPACE);
186         return (char*) p;
187 }
188
189 size_t cescape_char(char c, char *buf) {
190         char * buf_old = buf;
191
192         switch (c) {
193
194                 case '\a':
195                         *(buf++) = '\\';
196                         *(buf++) = 'a';
197                         break;
198                 case '\b':
199                         *(buf++) = '\\';
200                         *(buf++) = 'b';
201                         break;
202                 case '\f':
203                         *(buf++) = '\\';
204                         *(buf++) = 'f';
205                         break;
206                 case '\n':
207                         *(buf++) = '\\';
208                         *(buf++) = 'n';
209                         break;
210                 case '\r':
211                         *(buf++) = '\\';
212                         *(buf++) = 'r';
213                         break;
214                 case '\t':
215                         *(buf++) = '\\';
216                         *(buf++) = 't';
217                         break;
218                 case '\v':
219                         *(buf++) = '\\';
220                         *(buf++) = 'v';
221                         break;
222                 case '\\':
223                         *(buf++) = '\\';
224                         *(buf++) = '\\';
225                         break;
226                 case '"':
227                         *(buf++) = '\\';
228                         *(buf++) = '"';
229                         break;
230                 case '\'':
231                         *(buf++) = '\\';
232                         *(buf++) = '\'';
233                         break;
234
235                 default:
236                         /* For special chars we prefer octal over
237                          * hexadecimal encoding, simply because glib's
238                          * g_strescape() does the same */
239                         if ((c < ' ') || (c >= 127)) {
240                                 *(buf++) = '\\';
241                                 *(buf++) = octchar((unsigned char) c >> 6);
242                                 *(buf++) = octchar((unsigned char) c >> 3);
243                                 *(buf++) = octchar((unsigned char) c);
244                         } else
245                                 *(buf++) = c;
246                         break;
247         }
248
249         return buf - buf_old;
250 }
251
252 int close_nointr(int fd) {
253         assert(fd >= 0);
254
255         if (close(fd) >= 0)
256                 return 0;
257
258         /*
259          * Just ignore EINTR; a retry loop is the wrong thing to do on
260          * Linux.
261          *
262          * http://lkml.indiana.edu/hypermail/linux/kernel/0509.1/0877.html
263          * https://bugzilla.gnome.org/show_bug.cgi?id=682819
264          * http://utcc.utoronto.ca/~cks/space/blog/unix/CloseEINTR
265          * https://sites.google.com/site/michaelsafyan/software-engineering/checkforeintrwheninvokingclosethinkagain
266          */
267         if (errno == EINTR)
268                 return 0;
269
270         return -errno;
271 }
272
273 int safe_close(int fd) {
274
275         /*
276          * Like close_nointr() but cannot fail. Guarantees errno is
277          * unchanged. Is a NOP with negative fds passed, and returns
278          * -1, so that it can be used in this syntax:
279          *
280          * fd = safe_close(fd);
281          */
282
283         if (fd >= 0) {
284                 PROTECT_ERRNO;
285
286                 /* The kernel might return pretty much any error code
287                  * via close(), but the fd will be closed anyway. The
288                  * only condition we want to check for here is whether
289                  * the fd was invalid at all... */
290
291                 assert_se(close_nointr(fd) != -EBADF);
292         }
293
294         return -1;
295 }
296
297 void close_many(const int fds[], unsigned n_fd) {
298         unsigned i;
299
300         assert(fds || n_fd <= 0);
301
302         for (i = 0; i < n_fd; i++)
303                 safe_close(fds[i]);
304 }
305
306 int unlink_noerrno(const char *path) {
307         PROTECT_ERRNO;
308         int r;
309
310         r = unlink(path);
311         if (r < 0)
312                 return -errno;
313
314         return 0;
315 }
316
317 int parse_boolean(const char *v) {
318         assert(v);
319
320         if (streq(v, "1") || strcaseeq(v, "yes") || strcaseeq(v, "y") || strcaseeq(v, "true") || strcaseeq(v, "t") || strcaseeq(v, "on"))
321                 return 1;
322         else if (streq(v, "0") || strcaseeq(v, "no") || strcaseeq(v, "n") || strcaseeq(v, "false") || strcaseeq(v, "f") || strcaseeq(v, "off"))
323                 return 0;
324
325         return -EINVAL;
326 }
327
328 int parse_pid(const char *s, pid_t* ret_pid) {
329         unsigned long ul = 0;
330         pid_t pid;
331         int r;
332
333         assert(s);
334         assert(ret_pid);
335
336         r = safe_atolu(s, &ul);
337         if (r < 0)
338                 return r;
339
340         pid = (pid_t) ul;
341
342         if ((unsigned long) pid != ul)
343                 return -ERANGE;
344
345         if (pid <= 0)
346                 return -ERANGE;
347
348         *ret_pid = pid;
349         return 0;
350 }
351
352 int parse_uid(const char *s, uid_t* ret_uid) {
353         unsigned long ul = 0;
354         uid_t uid;
355         int r;
356
357         assert(s);
358         assert(ret_uid);
359
360         r = safe_atolu(s, &ul);
361         if (r < 0)
362                 return r;
363
364         uid = (uid_t) ul;
365
366         if ((unsigned long) uid != ul)
367                 return -ERANGE;
368
369         /* Some libc APIs use UID_INVALID as special placeholder */
370         if (uid == (uid_t) 0xFFFFFFFF)
371                 return -ENXIO;
372
373         /* A long time ago UIDs where 16bit, hence explicitly avoid the 16bit -1 too */
374         if (uid == (uid_t) 0xFFFF)
375                 return -ENXIO;
376
377         *ret_uid = uid;
378         return 0;
379 }
380
381 int safe_atou(const char *s, unsigned *ret_u) {
382         char *x = NULL;
383         unsigned long l;
384
385         assert(s);
386         assert(ret_u);
387
388         errno = 0;
389         l = strtoul(s, &x, 0);
390
391         if (!x || x == s || *x || errno)
392                 return errno > 0 ? -errno : -EINVAL;
393
394         if ((unsigned long) (unsigned) l != l)
395                 return -ERANGE;
396
397         *ret_u = (unsigned) l;
398         return 0;
399 }
400
401 int safe_atoi(const char *s, int *ret_i) {
402         char *x = NULL;
403         long l;
404
405         assert(s);
406         assert(ret_i);
407
408         errno = 0;
409         l = strtol(s, &x, 0);
410
411         if (!x || x == s || *x || errno)
412                 return errno > 0 ? -errno : -EINVAL;
413
414         if ((long) (int) l != l)
415                 return -ERANGE;
416
417         *ret_i = (int) l;
418         return 0;
419 }
420
421 int safe_atou8(const char *s, uint8_t *ret) {
422         char *x = NULL;
423         unsigned long l;
424
425         assert(s);
426         assert(ret);
427
428         errno = 0;
429         l = strtoul(s, &x, 0);
430
431         if (!x || x == s || *x || errno)
432                 return errno > 0 ? -errno : -EINVAL;
433
434         if ((unsigned long) (uint8_t) l != l)
435                 return -ERANGE;
436
437         *ret = (uint8_t) l;
438         return 0;
439 }
440
441 int safe_atou16(const char *s, uint16_t *ret) {
442         char *x = NULL;
443         unsigned long l;
444
445         assert(s);
446         assert(ret);
447
448         errno = 0;
449         l = strtoul(s, &x, 0);
450
451         if (!x || x == s || *x || errno)
452                 return errno > 0 ? -errno : -EINVAL;
453
454         if ((unsigned long) (uint16_t) l != l)
455                 return -ERANGE;
456
457         *ret = (uint16_t) l;
458         return 0;
459 }
460
461 int safe_atoi16(const char *s, int16_t *ret) {
462         char *x = NULL;
463         long l;
464
465         assert(s);
466         assert(ret);
467
468         errno = 0;
469         l = strtol(s, &x, 0);
470
471         if (!x || x == s || *x || errno)
472                 return errno > 0 ? -errno : -EINVAL;
473
474         if ((long) (int16_t) l != l)
475                 return -ERANGE;
476
477         *ret = (int16_t) l;
478         return 0;
479 }
480
481 int safe_atollu(const char *s, long long unsigned *ret_llu) {
482         char *x = NULL;
483         unsigned long long l;
484
485         assert(s);
486         assert(ret_llu);
487
488         errno = 0;
489         l = strtoull(s, &x, 0);
490
491         if (!x || x == s || *x || errno)
492                 return errno ? -errno : -EINVAL;
493
494         *ret_llu = l;
495         return 0;
496 }
497
498 int safe_atolli(const char *s, long long int *ret_lli) {
499         char *x = NULL;
500         long long l;
501
502         assert(s);
503         assert(ret_lli);
504
505         errno = 0;
506         l = strtoll(s, &x, 0);
507
508         if (!x || x == s || *x || errno)
509                 return errno ? -errno : -EINVAL;
510
511         *ret_lli = l;
512         return 0;
513 }
514
515 int safe_atod(const char *s, double *ret_d) {
516         char *x = NULL;
517         double d = 0;
518         locale_t loc;
519
520         assert(s);
521         assert(ret_d);
522
523         loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t) 0);
524         if (loc == (locale_t) 0)
525                 return -errno;
526
527         errno = 0;
528         d = strtod_l(s, &x, loc);
529
530         if (!x || x == s || *x || errno) {
531                 freelocale(loc);
532                 return errno ? -errno : -EINVAL;
533         }
534
535         freelocale(loc);
536         *ret_d = (double) d;
537         return 0;
538 }
539
540 static size_t strcspn_escaped(const char *s, const char *reject) {
541         bool escaped = false;
542         int n;
543
544         for (n=0; s[n]; n++) {
545                 if (escaped)
546                         escaped = false;
547                 else if (s[n] == '\\')
548                         escaped = true;
549                 else if (strchr(reject, s[n]))
550                         break;
551         }
552
553         /* if s ends in \, return index of previous char */
554         return n - escaped;
555 }
556
557 /* Split a string into words. */
558 const char* split(const char **state, size_t *l, const char *separator, bool quoted) {
559         const char *current;
560
561         current = *state;
562
563         if (!*current) {
564                 assert(**state == '\0');
565                 return NULL;
566         }
567
568         current += strspn(current, separator);
569         if (!*current) {
570                 *state = current;
571                 return NULL;
572         }
573
574         if (quoted && strchr("\'\"", *current)) {
575                 char quotechars[2] = {*current, '\0'};
576
577                 *l = strcspn_escaped(current + 1, quotechars);
578                 if (current[*l + 1] == '\0' ||
579                     (current[*l + 2] && !strchr(separator, current[*l + 2]))) {
580                         /* right quote missing or garbage at the end */
581                         *state = current;
582                         return NULL;
583                 }
584                 assert(current[*l + 1] == quotechars[0]);
585                 *state = current++ + *l + 2;
586         } else if (quoted) {
587                 *l = strcspn_escaped(current, separator);
588                 if (current[*l] && !strchr(separator, current[*l])) {
589                         /* unfinished escape */
590                         *state = current;
591                         return NULL;
592                 }
593                 *state = current + *l;
594         } else {
595                 *l = strcspn(current, separator);
596                 *state = current + *l;
597         }
598
599         return current;
600 }
601
602 int fchmod_umask(int fd, mode_t m) {
603         mode_t u;
604         int r;
605
606         u = umask(0777);
607         r = fchmod(fd, m & (~u)) < 0 ? -errno : 0;
608         umask(u);
609
610         return r;
611 }
612
613 char *truncate_nl(char *s) {
614         assert(s);
615
616         s[strcspn(s, NEWLINE)] = 0;
617         return s;
618 }
619
620 char *strnappend(const char *s, const char *suffix, size_t b) {
621         size_t a;
622         char *r;
623
624         if (!s && !suffix)
625                 return strdup("");
626
627         if (!s)
628                 return strndup(suffix, b);
629
630         if (!suffix)
631                 return strdup(s);
632
633         assert(s);
634         assert(suffix);
635
636         a = strlen(s);
637         if (b > ((size_t) -1) - a)
638                 return NULL;
639
640         r = new(char, a+b+1);
641         if (!r)
642                 return NULL;
643
644         memcpy(r, s, a);
645         memcpy(r+a, suffix, b);
646         r[a+b] = 0;
647
648         return r;
649 }
650
651 char *strappend(const char *s, const char *suffix) {
652         return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
653 }
654
655 int readlinkat_malloc(int fd, const char *p, char **ret) {
656         size_t l = 100;
657         int r;
658
659         assert(p);
660         assert(ret);
661
662         for (;;) {
663                 char *c;
664                 ssize_t n;
665
666                 c = new(char, l);
667                 if (!c)
668                         return -ENOMEM;
669
670                 n = readlinkat(fd, p, c, l-1);
671                 if (n < 0) {
672                         r = -errno;
673                         free(c);
674                         return r;
675                 }
676
677                 if ((size_t) n < l-1) {
678                         c[n] = 0;
679                         *ret = c;
680                         return 0;
681                 }
682
683                 free(c);
684                 l *= 2;
685         }
686 }
687
688 int readlink_malloc(const char *p, char **ret) {
689         return readlinkat_malloc(AT_FDCWD, p, ret);
690 }
691
692 int readlink_value(const char *p, char **ret) {
693         _cleanup_free_ char *link = NULL;
694         char *value;
695         int r;
696
697         r = readlink_malloc(p, &link);
698         if (r < 0)
699                 return r;
700
701         value = basename(link);
702         if (!value)
703                 return -ENOENT;
704
705         value = strdup(value);
706         if (!value)
707                 return -ENOMEM;
708
709         *ret = value;
710
711         return 0;
712 }
713
714 int readlink_and_make_absolute(const char *p, char **r) {
715         _cleanup_free_ char *target = NULL;
716         char *k;
717         int j;
718
719         assert(p);
720         assert(r);
721
722         j = readlink_malloc(p, &target);
723         if (j < 0)
724                 return j;
725
726         k = file_in_same_dir(p, target);
727         if (!k)
728                 return -ENOMEM;
729
730         *r = k;
731         return 0;
732 }
733
734 int readlink_and_canonicalize(const char *p, char **r) {
735         char *t, *s;
736         int j;
737
738         assert(p);
739         assert(r);
740
741         j = readlink_and_make_absolute(p, &t);
742         if (j < 0)
743                 return j;
744
745         s = canonicalize_file_name(t);
746         if (s) {
747                 free(t);
748                 *r = s;
749         } else
750                 *r = t;
751
752         path_kill_slashes(*r);
753
754         return 0;
755 }
756
757 int reset_all_signal_handlers(void) {
758         int sig, r = 0;
759
760         for (sig = 1; sig < _NSIG; sig++) {
761                 struct sigaction sa = {
762                         .sa_handler = SIG_DFL,
763                         .sa_flags = SA_RESTART,
764                 };
765
766                 /* These two cannot be caught... */
767                 if (sig == SIGKILL || sig == SIGSTOP)
768                         continue;
769
770                 /* On Linux the first two RT signals are reserved by
771                  * glibc, and sigaction() will return EINVAL for them. */
772                 if ((sigaction(sig, &sa, NULL) < 0))
773                         if (errno != EINVAL && r == 0)
774                                 r = -errno;
775         }
776
777         return r;
778 }
779
780 int reset_signal_mask(void) {
781         sigset_t ss;
782
783         if (sigemptyset(&ss) < 0)
784                 return -errno;
785
786         if (sigprocmask(SIG_SETMASK, &ss, NULL) < 0)
787                 return -errno;
788
789         return 0;
790 }
791
792 char *strstrip(char *s) {
793         char *e;
794
795         /* Drops trailing whitespace. Modifies the string in
796          * place. Returns pointer to first non-space character */
797
798         s += strspn(s, WHITESPACE);
799
800         for (e = strchr(s, 0); e > s; e --)
801                 if (!strchr(WHITESPACE, e[-1]))
802                         break;
803
804         *e = 0;
805
806         return s;
807 }
808
809 char *delete_chars(char *s, const char *bad) {
810         char *f, *t;
811
812         /* Drops all whitespace, regardless where in the string */
813
814         for (f = s, t = s; *f; f++) {
815                 if (strchr(bad, *f))
816                         continue;
817
818                 *(t++) = *f;
819         }
820
821         *t = 0;
822
823         return s;
824 }
825
826 char *file_in_same_dir(const char *path, const char *filename) {
827         char *e, *ret;
828         size_t k;
829
830         assert(path);
831         assert(filename);
832
833         /* This removes the last component of path and appends
834          * filename, unless the latter is absolute anyway or the
835          * former isn't */
836
837         if (path_is_absolute(filename))
838                 return strdup(filename);
839
840         e = strrchr(path, '/');
841         if (!e)
842                 return strdup(filename);
843
844         k = strlen(filename);
845         ret = new(char, (e + 1 - path) + k + 1);
846         if (!ret)
847                 return NULL;
848
849         memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
850         return ret;
851 }
852
853 int rmdir_parents(const char *path, const char *stop) {
854         size_t l;
855         int r = 0;
856
857         assert(path);
858         assert(stop);
859
860         l = strlen(path);
861
862         /* Skip trailing slashes */
863         while (l > 0 && path[l-1] == '/')
864                 l--;
865
866         while (l > 0) {
867                 char *t;
868
869                 /* Skip last component */
870                 while (l > 0 && path[l-1] != '/')
871                         l--;
872
873                 /* Skip trailing slashes */
874                 while (l > 0 && path[l-1] == '/')
875                         l--;
876
877                 if (l <= 0)
878                         break;
879
880                 if (!(t = strndup(path, l)))
881                         return -ENOMEM;
882
883                 if (path_startswith(stop, t)) {
884                         free(t);
885                         return 0;
886                 }
887
888                 r = rmdir(t);
889                 free(t);
890
891                 if (r < 0)
892                         if (errno != ENOENT)
893                                 return -errno;
894         }
895
896         return 0;
897 }
898
899 char hexchar(int x) {
900         static const char table[16] = "0123456789abcdef";
901
902         return table[x & 15];
903 }
904
905 int unhexchar(char c) {
906
907         if (c >= '0' && c <= '9')
908                 return c - '0';
909
910         if (c >= 'a' && c <= 'f')
911                 return c - 'a' + 10;
912
913         if (c >= 'A' && c <= 'F')
914                 return c - 'A' + 10;
915
916         return -EINVAL;
917 }
918
919 char *hexmem(const void *p, size_t l) {
920         char *r, *z;
921         const uint8_t *x;
922
923         z = r = malloc(l * 2 + 1);
924         if (!r)
925                 return NULL;
926
927         for (x = p; x < (const uint8_t*) p + l; x++) {
928                 *(z++) = hexchar(*x >> 4);
929                 *(z++) = hexchar(*x & 15);
930         }
931
932         *z = 0;
933         return r;
934 }
935
936 void *unhexmem(const char *p, size_t l) {
937         uint8_t *r, *z;
938         const char *x;
939
940         assert(p);
941
942         z = r = malloc((l + 1) / 2 + 1);
943         if (!r)
944                 return NULL;
945
946         for (x = p; x < p + l; x += 2) {
947                 int a, b;
948
949                 a = unhexchar(x[0]);
950                 if (x+1 < p + l)
951                         b = unhexchar(x[1]);
952                 else
953                         b = 0;
954
955                 *(z++) = (uint8_t) a << 4 | (uint8_t) b;
956         }
957
958         *z = 0;
959         return r;
960 }
961
962 char octchar(int x) {
963         return '0' + (x & 7);
964 }
965
966 int unoctchar(char c) {
967
968         if (c >= '0' && c <= '7')
969                 return c - '0';
970
971         return -EINVAL;
972 }
973
974 char decchar(int x) {
975         return '0' + (x % 10);
976 }
977
978 int undecchar(char c) {
979
980         if (c >= '0' && c <= '9')
981                 return c - '0';
982
983         return -EINVAL;
984 }
985
986 char *cescape(const char *s) {
987         char *r, *t;
988         const char *f;
989
990         assert(s);
991
992         /* Does C style string escaping. May be reversed with
993          * cunescape(). */
994
995         r = new(char, strlen(s)*4 + 1);
996         if (!r)
997                 return NULL;
998
999         for (f = s, t = r; *f; f++)
1000                 t += cescape_char(*f, t);
1001
1002         *t = 0;
1003
1004         return r;
1005 }
1006
1007 static int cunescape_one(const char *p, size_t length, char *ret, uint32_t *ret_unicode) {
1008         int r = 1;
1009
1010         assert(p);
1011         assert(*p);
1012         assert(ret);
1013
1014         /* Unescapes C style. Returns the unescaped character in ret,
1015          * unless we encountered a \u sequence in which case the full
1016          * unicode character is returned in ret_unicode, instead. */
1017
1018         if (length != (size_t) -1 && length < 1)
1019                 return -EINVAL;
1020
1021         switch (p[0]) {
1022
1023         case 'a':
1024                 *ret = '\a';
1025                 break;
1026         case 'b':
1027                 *ret = '\b';
1028                 break;
1029         case 'f':
1030                 *ret = '\f';
1031                 break;
1032         case 'n':
1033                 *ret = '\n';
1034                 break;
1035         case 'r':
1036                 *ret = '\r';
1037                 break;
1038         case 't':
1039                 *ret = '\t';
1040                 break;
1041         case 'v':
1042                 *ret = '\v';
1043                 break;
1044         case '\\':
1045                 *ret = '\\';
1046                 break;
1047         case '"':
1048                 *ret = '"';
1049                 break;
1050         case '\'':
1051                 *ret = '\'';
1052                 break;
1053
1054         case 's':
1055                 /* This is an extension of the XDG syntax files */
1056                 *ret = ' ';
1057                 break;
1058
1059         case 'x': {
1060                 /* hexadecimal encoding */
1061                 int a, b;
1062
1063                 if (length != (size_t) -1 && length < 3)
1064                         return -EINVAL;
1065
1066                 a = unhexchar(p[1]);
1067                 if (a < 0)
1068                         return -EINVAL;
1069
1070                 b = unhexchar(p[2]);
1071                 if (b < 0)
1072                         return -EINVAL;
1073
1074                 /* Don't allow NUL bytes */
1075                 if (a == 0 && b == 0)
1076                         return -EINVAL;
1077
1078                 *ret = (char) ((a << 4U) | b);
1079                 r = 3;
1080                 break;
1081         }
1082
1083         case 'u': {
1084                 /* C++11 style 16bit unicode */
1085
1086                 int a[4];
1087                 unsigned i;
1088                 uint32_t c;
1089
1090                 if (length != (size_t) -1 && length < 5)
1091                         return -EINVAL;
1092
1093                 for (i = 0; i < 4; i++) {
1094                         a[i] = unhexchar(p[1 + i]);
1095                         if (a[i] < 0)
1096                                 return a[i];
1097                 }
1098
1099                 c = ((uint32_t) a[0] << 12U) | ((uint32_t) a[1] << 8U) | ((uint32_t) a[2] << 4U) | (uint32_t) a[3];
1100
1101                 /* Don't allow 0 chars */
1102                 if (c == 0)
1103                         return -EINVAL;
1104
1105                 if (c < 128)
1106                         *ret = c;
1107                 else {
1108                         if (!ret_unicode)
1109                                 return -EINVAL;
1110
1111                         *ret = 0;
1112                         *ret_unicode = c;
1113                 }
1114
1115                 r = 5;
1116                 break;
1117         }
1118
1119         case 'U': {
1120                 /* C++11 style 32bit unicode */
1121
1122                 int a[8];
1123                 unsigned i;
1124                 uint32_t c;
1125
1126                 if (length != (size_t) -1 && length < 9)
1127                         return -EINVAL;
1128
1129                 for (i = 0; i < 8; i++) {
1130                         a[i] = unhexchar(p[1 + i]);
1131                         if (a[i] < 0)
1132                                 return a[i];
1133                 }
1134
1135                 c = ((uint32_t) a[0] << 28U) | ((uint32_t) a[1] << 24U) | ((uint32_t) a[2] << 20U) | ((uint32_t) a[3] << 16U) |
1136                     ((uint32_t) a[4] << 12U) | ((uint32_t) a[5] <<  8U) | ((uint32_t) a[6] <<  4U) |  (uint32_t) a[7];
1137
1138                 /* Don't allow 0 chars */
1139                 if (c == 0)
1140                         return -EINVAL;
1141
1142                 /* Don't allow invalid code points */
1143                 if (!unichar_is_valid(c))
1144                         return -EINVAL;
1145
1146                 if (c < 128)
1147                         *ret = c;
1148                 else {
1149                         if (!ret_unicode)
1150                                 return -EINVAL;
1151
1152                         *ret = 0;
1153                         *ret_unicode = c;
1154                 }
1155
1156                 r = 9;
1157                 break;
1158         }
1159
1160         case '0':
1161         case '1':
1162         case '2':
1163         case '3':
1164         case '4':
1165         case '5':
1166         case '6':
1167         case '7': {
1168                 /* octal encoding */
1169                 int a, b, c;
1170                 uint32_t m;
1171
1172                 if (length != (size_t) -1 && length < 4)
1173                         return -EINVAL;
1174
1175                 a = unoctchar(p[0]);
1176                 if (a < 0)
1177                         return -EINVAL;
1178
1179                 b = unoctchar(p[1]);
1180                 if (b < 0)
1181                         return -EINVAL;
1182
1183                 c = unoctchar(p[2]);
1184                 if (c < 0)
1185                         return -EINVAL;
1186
1187                 /* don't allow NUL bytes */
1188                 if (a == 0 && b == 0 && c == 0)
1189                         return -EINVAL;
1190
1191                 /* Don't allow bytes above 255 */
1192                 m = ((uint32_t) a << 6U) | ((uint32_t) b << 3U) | (uint32_t) c;
1193                 if (m > 255)
1194                         return -EINVAL;
1195
1196                 *ret = m;
1197                 r = 3;
1198                 break;
1199         }
1200
1201         default:
1202                 return -EINVAL;
1203         }
1204
1205         return r;
1206 }
1207
1208 int cunescape_length_with_prefix(const char *s, size_t length, const char *prefix, UnescapeFlags flags, char **ret) {
1209         char *r, *t;
1210         const char *f;
1211         size_t pl;
1212
1213         assert(s);
1214         assert(ret);
1215
1216         /* Undoes C style string escaping, and optionally prefixes it. */
1217
1218         pl = prefix ? strlen(prefix) : 0;
1219
1220         r = new(char, pl+length+1);
1221         if (!r)
1222                 return -ENOMEM;
1223
1224         if (prefix)
1225                 memcpy(r, prefix, pl);
1226
1227         for (f = s, t = r + pl; f < s + length; f++) {
1228                 size_t remaining;
1229                 uint32_t u;
1230                 char c;
1231                 int k;
1232
1233                 remaining = s + length - f;
1234                 assert(remaining > 0);
1235
1236                 if (*f != '\\') {
1237                         /* A literal literal, copy verbatim */
1238                         *(t++) = *f;
1239                         continue;
1240                 }
1241
1242                 if (remaining == 1) {
1243                         if (flags & UNESCAPE_RELAX) {
1244                                 /* A trailing backslash, copy verbatim */
1245                                 *(t++) = *f;
1246                                 continue;
1247                         }
1248
1249                         free(r);
1250                         return -EINVAL;
1251                 }
1252
1253                 k = cunescape_one(f + 1, remaining - 1, &c, &u);
1254                 if (k < 0) {
1255                         if (flags & UNESCAPE_RELAX) {
1256                                 /* Invalid escape code, let's take it literal then */
1257                                 *(t++) = '\\';
1258                                 continue;
1259                         }
1260
1261                         free(r);
1262                         return k;
1263                 }
1264
1265                 if (c != 0)
1266                         /* Non-Unicode? Let's encode this directly */
1267                         *(t++) = c;
1268                 else
1269                         /* Unicode? Then let's encode this in UTF-8 */
1270                         t += utf8_encode_unichar(t, u);
1271
1272                 f += k;
1273         }
1274
1275         *t = 0;
1276
1277         *ret = r;
1278         return t - r;
1279 }
1280
1281 int cunescape_length(const char *s, size_t length, UnescapeFlags flags, char **ret) {
1282         return cunescape_length_with_prefix(s, length, NULL, flags, ret);
1283 }
1284
1285 int cunescape(const char *s, UnescapeFlags flags, char **ret) {
1286         return cunescape_length(s, strlen(s), flags, ret);
1287 }
1288
1289 char *xescape(const char *s, const char *bad) {
1290         char *r, *t;
1291         const char *f;
1292
1293         /* Escapes all chars in bad, in addition to \ and all special
1294          * chars, in \xFF style escaping. May be reversed with
1295          * cunescape(). */
1296
1297         r = new(char, strlen(s) * 4 + 1);
1298         if (!r)
1299                 return NULL;
1300
1301         for (f = s, t = r; *f; f++) {
1302
1303                 if ((*f < ' ') || (*f >= 127) ||
1304                     (*f == '\\') || strchr(bad, *f)) {
1305                         *(t++) = '\\';
1306                         *(t++) = 'x';
1307                         *(t++) = hexchar(*f >> 4);
1308                         *(t++) = hexchar(*f);
1309                 } else
1310                         *(t++) = *f;
1311         }
1312
1313         *t = 0;
1314
1315         return r;
1316 }
1317
1318 char *ascii_strlower(char *t) {
1319         char *p;
1320
1321         assert(t);
1322
1323         for (p = t; *p; p++)
1324                 if (*p >= 'A' && *p <= 'Z')
1325                         *p = *p - 'A' + 'a';
1326
1327         return t;
1328 }
1329
1330 _pure_ static bool hidden_file_allow_backup(const char *filename) {
1331         assert(filename);
1332
1333         return
1334                 filename[0] == '.' ||
1335                 streq(filename, "lost+found") ||
1336                 streq(filename, "aquota.user") ||
1337                 streq(filename, "aquota.group") ||
1338                 endswith(filename, ".rpmnew") ||
1339                 endswith(filename, ".rpmsave") ||
1340                 endswith(filename, ".rpmorig") ||
1341                 endswith(filename, ".dpkg-old") ||
1342                 endswith(filename, ".dpkg-new") ||
1343                 endswith(filename, ".dpkg-tmp") ||
1344                 endswith(filename, ".dpkg-dist") ||
1345                 endswith(filename, ".dpkg-bak") ||
1346                 endswith(filename, ".dpkg-backup") ||
1347                 endswith(filename, ".dpkg-remove") ||
1348                 endswith(filename, ".swp");
1349 }
1350
1351 bool hidden_file(const char *filename) {
1352         assert(filename);
1353
1354         if (endswith(filename, "~"))
1355                 return true;
1356
1357         return hidden_file_allow_backup(filename);
1358 }
1359
1360 int fd_nonblock(int fd, bool nonblock) {
1361         int flags, nflags;
1362
1363         assert(fd >= 0);
1364
1365         flags = fcntl(fd, F_GETFL, 0);
1366         if (flags < 0)
1367                 return -errno;
1368
1369         if (nonblock)
1370                 nflags = flags | O_NONBLOCK;
1371         else
1372                 nflags = flags & ~O_NONBLOCK;
1373
1374         if (nflags == flags)
1375                 return 0;
1376
1377         if (fcntl(fd, F_SETFL, nflags) < 0)
1378                 return -errno;
1379
1380         return 0;
1381 }
1382
1383 int fd_cloexec(int fd, bool cloexec) {
1384         int flags, nflags;
1385
1386         assert(fd >= 0);
1387
1388         flags = fcntl(fd, F_GETFD, 0);
1389         if (flags < 0)
1390                 return -errno;
1391
1392         if (cloexec)
1393                 nflags = flags | FD_CLOEXEC;
1394         else
1395                 nflags = flags & ~FD_CLOEXEC;
1396
1397         if (nflags == flags)
1398                 return 0;
1399
1400         if (fcntl(fd, F_SETFD, nflags) < 0)
1401                 return -errno;
1402
1403         return 0;
1404 }
1405
1406 _pure_ static bool fd_in_set(int fd, const int fdset[], unsigned n_fdset) {
1407         unsigned i;
1408
1409         assert(n_fdset == 0 || fdset);
1410
1411         for (i = 0; i < n_fdset; i++)
1412                 if (fdset[i] == fd)
1413                         return true;
1414
1415         return false;
1416 }
1417
1418 int close_all_fds(const int except[], unsigned n_except) {
1419         _cleanup_closedir_ DIR *d = NULL;
1420         struct dirent *de;
1421         int r = 0;
1422
1423         assert(n_except == 0 || except);
1424
1425         d = opendir("/proc/self/fd");
1426         if (!d) {
1427                 int fd;
1428                 struct rlimit rl;
1429
1430                 /* When /proc isn't available (for example in chroots)
1431                  * the fallback is brute forcing through the fd
1432                  * table */
1433
1434                 assert_se(getrlimit(RLIMIT_NOFILE, &rl) >= 0);
1435                 for (fd = 3; fd < (int) rl.rlim_max; fd ++) {
1436
1437                         if (fd_in_set(fd, except, n_except))
1438                                 continue;
1439
1440                         if (close_nointr(fd) < 0)
1441                                 if (errno != EBADF && r == 0)
1442                                         r = -errno;
1443                 }
1444
1445                 return r;
1446         }
1447
1448         while ((de = readdir(d))) {
1449                 int fd = -1;
1450
1451                 if (hidden_file(de->d_name))
1452                         continue;
1453
1454                 if (safe_atoi(de->d_name, &fd) < 0)
1455                         /* Let's better ignore this, just in case */
1456                         continue;
1457
1458                 if (fd < 3)
1459                         continue;
1460
1461                 if (fd == dirfd(d))
1462                         continue;
1463
1464                 if (fd_in_set(fd, except, n_except))
1465                         continue;
1466
1467                 if (close_nointr(fd) < 0) {
1468                         /* Valgrind has its own FD and doesn't want to have it closed */
1469                         if (errno != EBADF && r == 0)
1470                                 r = -errno;
1471                 }
1472         }
1473
1474         return r;
1475 }
1476
1477 bool chars_intersect(const char *a, const char *b) {
1478         const char *p;
1479
1480         /* Returns true if any of the chars in a are in b. */
1481         for (p = a; *p; p++)
1482                 if (strchr(b, *p))
1483                         return true;
1484
1485         return false;
1486 }
1487
1488 bool fstype_is_network(const char *fstype) {
1489         static const char table[] =
1490                 "afs\0"
1491                 "cifs\0"
1492                 "smbfs\0"
1493                 "sshfs\0"
1494                 "ncpfs\0"
1495                 "ncp\0"
1496                 "nfs\0"
1497                 "nfs4\0"
1498                 "gfs\0"
1499                 "gfs2\0"
1500                 "glusterfs\0";
1501
1502         const char *x;
1503
1504         x = startswith(fstype, "fuse.");
1505         if (x)
1506                 fstype = x;
1507
1508         return nulstr_contains(table, fstype);
1509 }
1510
1511 int chvt(int vt) {
1512         _cleanup_close_ int fd;
1513
1514         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
1515         if (fd < 0)
1516                 return -errno;
1517
1518         if (vt < 0) {
1519                 int tiocl[2] = {
1520                         TIOCL_GETKMSGREDIRECT,
1521                         0
1522                 };
1523
1524                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1525                         return -errno;
1526
1527                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1528         }
1529
1530         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1531                 return -errno;
1532
1533         return 0;
1534 }
1535
1536 int read_one_char(FILE *f, char *ret, usec_t t, bool *need_nl) {
1537         struct termios old_termios, new_termios;
1538         char c, line[LINE_MAX];
1539
1540         assert(f);
1541         assert(ret);
1542
1543         if (tcgetattr(fileno(f), &old_termios) >= 0) {
1544                 new_termios = old_termios;
1545
1546                 new_termios.c_lflag &= ~ICANON;
1547                 new_termios.c_cc[VMIN] = 1;
1548                 new_termios.c_cc[VTIME] = 0;
1549
1550                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1551                         size_t k;
1552
1553                         if (t != USEC_INFINITY) {
1554                                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0) {
1555                                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1556                                         return -ETIMEDOUT;
1557                                 }
1558                         }
1559
1560                         k = fread(&c, 1, 1, f);
1561
1562                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1563
1564                         if (k <= 0)
1565                                 return -EIO;
1566
1567                         if (need_nl)
1568                                 *need_nl = c != '\n';
1569
1570                         *ret = c;
1571                         return 0;
1572                 }
1573         }
1574
1575         if (t != USEC_INFINITY) {
1576                 if (fd_wait_for_event(fileno(f), POLLIN, t) <= 0)
1577                         return -ETIMEDOUT;
1578         }
1579
1580         errno = 0;
1581         if (!fgets(line, sizeof(line), f))
1582                 return errno ? -errno : -EIO;
1583
1584         truncate_nl(line);
1585
1586         if (strlen(line) != 1)
1587                 return -EBADMSG;
1588
1589         if (need_nl)
1590                 *need_nl = false;
1591
1592         *ret = line[0];
1593         return 0;
1594 }
1595
1596 int ask_char(char *ret, const char *replies, const char *text, ...) {
1597         int r;
1598
1599         assert(ret);
1600         assert(replies);
1601         assert(text);
1602
1603         for (;;) {
1604                 va_list ap;
1605                 char c;
1606                 bool need_nl = true;
1607
1608                 if (on_tty())
1609                         fputs(ANSI_HIGHLIGHT_ON, stdout);
1610
1611                 va_start(ap, text);
1612                 vprintf(text, ap);
1613                 va_end(ap);
1614
1615                 if (on_tty())
1616                         fputs(ANSI_HIGHLIGHT_OFF, stdout);
1617
1618                 fflush(stdout);
1619
1620                 r = read_one_char(stdin, &c, USEC_INFINITY, &need_nl);
1621                 if (r < 0) {
1622
1623                         if (r == -EBADMSG) {
1624                                 puts("Bad input, please try again.");
1625                                 continue;
1626                         }
1627
1628                         putchar('\n');
1629                         return r;
1630                 }
1631
1632                 if (need_nl)
1633                         putchar('\n');
1634
1635                 if (strchr(replies, c)) {
1636                         *ret = c;
1637                         return 0;
1638                 }
1639
1640                 puts("Read unexpected character, please try again.");
1641         }
1642 }
1643
1644 int ask_string(char **ret, const char *text, ...) {
1645         assert(ret);
1646         assert(text);
1647
1648         for (;;) {
1649                 char line[LINE_MAX];
1650                 va_list ap;
1651
1652                 if (on_tty())
1653                         fputs(ANSI_HIGHLIGHT_ON, stdout);
1654
1655                 va_start(ap, text);
1656                 vprintf(text, ap);
1657                 va_end(ap);
1658
1659                 if (on_tty())
1660                         fputs(ANSI_HIGHLIGHT_OFF, stdout);
1661
1662                 fflush(stdout);
1663
1664                 errno = 0;
1665                 if (!fgets(line, sizeof(line), stdin))
1666                         return errno ? -errno : -EIO;
1667
1668                 if (!endswith(line, "\n"))
1669                         putchar('\n');
1670                 else {
1671                         char *s;
1672
1673                         if (isempty(line))
1674                                 continue;
1675
1676                         truncate_nl(line);
1677                         s = strdup(line);
1678                         if (!s)
1679                                 return -ENOMEM;
1680
1681                         *ret = s;
1682                         return 0;
1683                 }
1684         }
1685 }
1686
1687 int reset_terminal_fd(int fd, bool switch_to_text) {
1688         struct termios termios;
1689         int r = 0;
1690
1691         /* Set terminal to some sane defaults */
1692
1693         assert(fd >= 0);
1694
1695         /* We leave locked terminal attributes untouched, so that
1696          * Plymouth may set whatever it wants to set, and we don't
1697          * interfere with that. */
1698
1699         /* Disable exclusive mode, just in case */
1700         ioctl(fd, TIOCNXCL);
1701
1702         /* Switch to text mode */
1703         if (switch_to_text)
1704                 ioctl(fd, KDSETMODE, KD_TEXT);
1705
1706         /* Enable console unicode mode */
1707         ioctl(fd, KDSKBMODE, K_UNICODE);
1708
1709         if (tcgetattr(fd, &termios) < 0) {
1710                 r = -errno;
1711                 goto finish;
1712         }
1713
1714         /* We only reset the stuff that matters to the software. How
1715          * hardware is set up we don't touch assuming that somebody
1716          * else will do that for us */
1717
1718         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1719         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1720         termios.c_oflag |= ONLCR;
1721         termios.c_cflag |= CREAD;
1722         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1723
1724         termios.c_cc[VINTR]    =   03;  /* ^C */
1725         termios.c_cc[VQUIT]    =  034;  /* ^\ */
1726         termios.c_cc[VERASE]   = 0177;
1727         termios.c_cc[VKILL]    =  025;  /* ^X */
1728         termios.c_cc[VEOF]     =   04;  /* ^D */
1729         termios.c_cc[VSTART]   =  021;  /* ^Q */
1730         termios.c_cc[VSTOP]    =  023;  /* ^S */
1731         termios.c_cc[VSUSP]    =  032;  /* ^Z */
1732         termios.c_cc[VLNEXT]   =  026;  /* ^V */
1733         termios.c_cc[VWERASE]  =  027;  /* ^W */
1734         termios.c_cc[VREPRINT] =  022;  /* ^R */
1735         termios.c_cc[VEOL]     =    0;
1736         termios.c_cc[VEOL2]    =    0;
1737
1738         termios.c_cc[VTIME]  = 0;
1739         termios.c_cc[VMIN]   = 1;
1740
1741         if (tcsetattr(fd, TCSANOW, &termios) < 0)
1742                 r = -errno;
1743
1744 finish:
1745         /* Just in case, flush all crap out */
1746         tcflush(fd, TCIOFLUSH);
1747
1748         return r;
1749 }
1750
1751 int reset_terminal(const char *name) {
1752         _cleanup_close_ int fd = -1;
1753
1754         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1755         if (fd < 0)
1756                 return fd;
1757
1758         return reset_terminal_fd(fd, true);
1759 }
1760
1761 int open_terminal(const char *name, int mode) {
1762         int fd, r;
1763         unsigned c = 0;
1764
1765         /*
1766          * If a TTY is in the process of being closed opening it might
1767          * cause EIO. This is horribly awful, but unlikely to be
1768          * changed in the kernel. Hence we work around this problem by
1769          * retrying a couple of times.
1770          *
1771          * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
1772          */
1773
1774         assert(!(mode & O_CREAT));
1775
1776         for (;;) {
1777                 fd = open(name, mode, 0);
1778                 if (fd >= 0)
1779                         break;
1780
1781                 if (errno != EIO)
1782                         return -errno;
1783
1784                 /* Max 1s in total */
1785                 if (c >= 20)
1786                         return -errno;
1787
1788                 usleep(50 * USEC_PER_MSEC);
1789                 c++;
1790         }
1791
1792         r = isatty(fd);
1793         if (r < 0) {
1794                 safe_close(fd);
1795                 return -errno;
1796         }
1797
1798         if (!r) {
1799                 safe_close(fd);
1800                 return -ENOTTY;
1801         }
1802
1803         return fd;
1804 }
1805
1806 int flush_fd(int fd) {
1807         struct pollfd pollfd = {
1808                 .fd = fd,
1809                 .events = POLLIN,
1810         };
1811
1812         for (;;) {
1813                 char buf[LINE_MAX];
1814                 ssize_t l;
1815                 int r;
1816
1817                 r = poll(&pollfd, 1, 0);
1818                 if (r < 0) {
1819                         if (errno == EINTR)
1820                                 continue;
1821
1822                         return -errno;
1823
1824                 } else if (r == 0)
1825                         return 0;
1826
1827                 l = read(fd, buf, sizeof(buf));
1828                 if (l < 0) {
1829
1830                         if (errno == EINTR)
1831                                 continue;
1832
1833                         if (errno == EAGAIN)
1834                                 return 0;
1835
1836                         return -errno;
1837                 } else if (l == 0)
1838                         return 0;
1839         }
1840 }
1841
1842 int acquire_terminal(
1843                 const char *name,
1844                 bool fail,
1845                 bool force,
1846                 bool ignore_tiocstty_eperm,
1847                 usec_t timeout) {
1848
1849         int fd = -1, notify = -1, r = 0, wd = -1;
1850         usec_t ts = 0;
1851
1852         assert(name);
1853
1854         /* We use inotify to be notified when the tty is closed. We
1855          * create the watch before checking if we can actually acquire
1856          * it, so that we don't lose any event.
1857          *
1858          * Note: strictly speaking this actually watches for the
1859          * device being closed, it does *not* really watch whether a
1860          * tty loses its controlling process. However, unless some
1861          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1862          * its tty otherwise this will not become a problem. As long
1863          * as the administrator makes sure not configure any service
1864          * on the same tty as an untrusted user this should not be a
1865          * problem. (Which he probably should not do anyway.) */
1866
1867         if (timeout != USEC_INFINITY)
1868                 ts = now(CLOCK_MONOTONIC);
1869
1870         if (!fail && !force) {
1871                 notify = inotify_init1(IN_CLOEXEC | (timeout != USEC_INFINITY ? IN_NONBLOCK : 0));
1872                 if (notify < 0) {
1873                         r = -errno;
1874                         goto fail;
1875                 }
1876
1877                 wd = inotify_add_watch(notify, name, IN_CLOSE);
1878                 if (wd < 0) {
1879                         r = -errno;
1880                         goto fail;
1881                 }
1882         }
1883
1884         for (;;) {
1885                 struct sigaction sa_old, sa_new = {
1886                         .sa_handler = SIG_IGN,
1887                         .sa_flags = SA_RESTART,
1888                 };
1889
1890                 if (notify >= 0) {
1891                         r = flush_fd(notify);
1892                         if (r < 0)
1893                                 goto fail;
1894                 }
1895
1896                 /* We pass here O_NOCTTY only so that we can check the return
1897                  * value TIOCSCTTY and have a reliable way to figure out if we
1898                  * successfully became the controlling process of the tty */
1899                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
1900                 if (fd < 0)
1901                         return fd;
1902
1903                 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1904                  * if we already own the tty. */
1905                 assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1906
1907                 /* First, try to get the tty */
1908                 if (ioctl(fd, TIOCSCTTY, force) < 0)
1909                         r = -errno;
1910
1911                 assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1912
1913                 /* Sometimes it makes sense to ignore TIOCSCTTY
1914                  * returning EPERM, i.e. when very likely we already
1915                  * are have this controlling terminal. */
1916                 if (r < 0 && r == -EPERM && ignore_tiocstty_eperm)
1917                         r = 0;
1918
1919                 if (r < 0 && (force || fail || r != -EPERM)) {
1920                         goto fail;
1921                 }
1922
1923                 if (r >= 0)
1924                         break;
1925
1926                 assert(!fail);
1927                 assert(!force);
1928                 assert(notify >= 0);
1929
1930                 for (;;) {
1931                         union inotify_event_buffer buffer;
1932                         struct inotify_event *e;
1933                         ssize_t l;
1934
1935                         if (timeout != USEC_INFINITY) {
1936                                 usec_t n;
1937
1938                                 n = now(CLOCK_MONOTONIC);
1939                                 if (ts + timeout < n) {
1940                                         r = -ETIMEDOUT;
1941                                         goto fail;
1942                                 }
1943
1944                                 r = fd_wait_for_event(fd, POLLIN, ts + timeout - n);
1945                                 if (r < 0)
1946                                         goto fail;
1947
1948                                 if (r == 0) {
1949                                         r = -ETIMEDOUT;
1950                                         goto fail;
1951                                 }
1952                         }
1953
1954                         l = read(notify, &buffer, sizeof(buffer));
1955                         if (l < 0) {
1956                                 if (errno == EINTR || errno == EAGAIN)
1957                                         continue;
1958
1959                                 r = -errno;
1960                                 goto fail;
1961                         }
1962
1963                         FOREACH_INOTIFY_EVENT(e, buffer, l) {
1964                                 if (e->wd != wd || !(e->mask & IN_CLOSE)) {
1965                                         r = -EIO;
1966                                         goto fail;
1967                                 }
1968                         }
1969
1970                         break;
1971                 }
1972
1973                 /* We close the tty fd here since if the old session
1974                  * ended our handle will be dead. It's important that
1975                  * we do this after sleeping, so that we don't enter
1976                  * an endless loop. */
1977                 fd = safe_close(fd);
1978         }
1979
1980         safe_close(notify);
1981
1982         r = reset_terminal_fd(fd, true);
1983         if (r < 0)
1984                 log_warning_errno(r, "Failed to reset terminal: %m");
1985
1986         return fd;
1987
1988 fail:
1989         safe_close(fd);
1990         safe_close(notify);
1991
1992         return r;
1993 }
1994
1995 int release_terminal(void) {
1996         static const struct sigaction sa_new = {
1997                 .sa_handler = SIG_IGN,
1998                 .sa_flags = SA_RESTART,
1999         };
2000
2001         _cleanup_close_ int fd = -1;
2002         struct sigaction sa_old;
2003         int r = 0;
2004
2005         fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY|O_CLOEXEC);
2006         if (fd < 0)
2007                 return -errno;
2008
2009         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2010          * by our own TIOCNOTTY */
2011         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2012
2013         if (ioctl(fd, TIOCNOTTY) < 0)
2014                 r = -errno;
2015
2016         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2017
2018         return r;
2019 }
2020
2021 int sigaction_many(const struct sigaction *sa, ...) {
2022         va_list ap;
2023         int r = 0, sig;
2024
2025         va_start(ap, sa);
2026         while ((sig = va_arg(ap, int)) > 0)
2027                 if (sigaction(sig, sa, NULL) < 0)
2028                         r = -errno;
2029         va_end(ap);
2030
2031         return r;
2032 }
2033
2034 int ignore_signals(int sig, ...) {
2035         struct sigaction sa = {
2036                 .sa_handler = SIG_IGN,
2037                 .sa_flags = SA_RESTART,
2038         };
2039         va_list ap;
2040         int r = 0;
2041
2042         if (sigaction(sig, &sa, NULL) < 0)
2043                 r = -errno;
2044
2045         va_start(ap, sig);
2046         while ((sig = va_arg(ap, int)) > 0)
2047                 if (sigaction(sig, &sa, NULL) < 0)
2048                         r = -errno;
2049         va_end(ap);
2050
2051         return r;
2052 }
2053
2054 int default_signals(int sig, ...) {
2055         struct sigaction sa = {
2056                 .sa_handler = SIG_DFL,
2057                 .sa_flags = SA_RESTART,
2058         };
2059         va_list ap;
2060         int r = 0;
2061
2062         if (sigaction(sig, &sa, NULL) < 0)
2063                 r = -errno;
2064
2065         va_start(ap, sig);
2066         while ((sig = va_arg(ap, int)) > 0)
2067                 if (sigaction(sig, &sa, NULL) < 0)
2068                         r = -errno;
2069         va_end(ap);
2070
2071         return r;
2072 }
2073
2074 void safe_close_pair(int p[]) {
2075         assert(p);
2076
2077         if (p[0] == p[1]) {
2078                 /* Special case pairs which use the same fd in both
2079                  * directions... */
2080                 p[0] = p[1] = safe_close(p[0]);
2081                 return;
2082         }
2083
2084         p[0] = safe_close(p[0]);
2085         p[1] = safe_close(p[1]);
2086 }
2087
2088 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2089         uint8_t *p = buf;
2090         ssize_t n = 0;
2091
2092         assert(fd >= 0);
2093         assert(buf);
2094
2095         while (nbytes > 0) {
2096                 ssize_t k;
2097
2098                 k = read(fd, p, nbytes);
2099                 if (k < 0) {
2100                         if (errno == EINTR)
2101                                 continue;
2102
2103                         if (errno == EAGAIN && do_poll) {
2104
2105                                 /* We knowingly ignore any return value here,
2106                                  * and expect that any error/EOF is reported
2107                                  * via read() */
2108
2109                                 fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
2110                                 continue;
2111                         }
2112
2113                         return n > 0 ? n : -errno;
2114                 }
2115
2116                 if (k == 0)
2117                         return n;
2118
2119                 p += k;
2120                 nbytes -= k;
2121                 n += k;
2122         }
2123
2124         return n;
2125 }
2126
2127 int loop_read_exact(int fd, void *buf, size_t nbytes, bool do_poll) {
2128         ssize_t n;
2129
2130         n = loop_read(fd, buf, nbytes, do_poll);
2131         if (n < 0)
2132                 return n;
2133         if ((size_t) n != nbytes)
2134                 return -EIO;
2135         return 0;
2136 }
2137
2138 int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2139         const uint8_t *p = buf;
2140
2141         assert(fd >= 0);
2142         assert(buf);
2143
2144         errno = 0;
2145
2146         while (nbytes > 0) {
2147                 ssize_t k;
2148
2149                 k = write(fd, p, nbytes);
2150                 if (k < 0) {
2151                         if (errno == EINTR)
2152                                 continue;
2153
2154                         if (errno == EAGAIN && do_poll) {
2155                                 /* We knowingly ignore any return value here,
2156                                  * and expect that any error/EOF is reported
2157                                  * via write() */
2158
2159                                 fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
2160                                 continue;
2161                         }
2162
2163                         return -errno;
2164                 }
2165
2166                 if (k == 0) /* Can't really happen */
2167                         return -EIO;
2168
2169                 p += k;
2170                 nbytes -= k;
2171         }
2172
2173         return 0;
2174 }
2175
2176 int parse_size(const char *t, off_t base, off_t *size) {
2177
2178         /* Soo, sometimes we want to parse IEC binary suffxies, and
2179          * sometimes SI decimal suffixes. This function can parse
2180          * both. Which one is the right way depends on the
2181          * context. Wikipedia suggests that SI is customary for
2182          * hardrware metrics and network speeds, while IEC is
2183          * customary for most data sizes used by software and volatile
2184          * (RAM) memory. Hence be careful which one you pick!
2185          *
2186          * In either case we use just K, M, G as suffix, and not Ki,
2187          * Mi, Gi or so (as IEC would suggest). That's because that's
2188          * frickin' ugly. But this means you really need to make sure
2189          * to document which base you are parsing when you use this
2190          * call. */
2191
2192         struct table {
2193                 const char *suffix;
2194                 unsigned long long factor;
2195         };
2196
2197         static const struct table iec[] = {
2198                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2199                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2200                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2201                 { "G", 1024ULL*1024ULL*1024ULL },
2202                 { "M", 1024ULL*1024ULL },
2203                 { "K", 1024ULL },
2204                 { "B", 1 },
2205                 { "", 1 },
2206         };
2207
2208         static const struct table si[] = {
2209                 { "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2210                 { "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
2211                 { "T", 1000ULL*1000ULL*1000ULL*1000ULL },
2212                 { "G", 1000ULL*1000ULL*1000ULL },
2213                 { "M", 1000ULL*1000ULL },
2214                 { "K", 1000ULL },
2215                 { "B", 1 },
2216                 { "", 1 },
2217         };
2218
2219         const struct table *table;
2220         const char *p;
2221         unsigned long long r = 0;
2222         unsigned n_entries, start_pos = 0;
2223
2224         assert(t);
2225         assert(base == 1000 || base == 1024);
2226         assert(size);
2227
2228         if (base == 1000) {
2229                 table = si;
2230                 n_entries = ELEMENTSOF(si);
2231         } else {
2232                 table = iec;
2233                 n_entries = ELEMENTSOF(iec);
2234         }
2235
2236         p = t;
2237         do {
2238                 long long l;
2239                 unsigned long long l2;
2240                 double frac = 0;
2241                 char *e;
2242                 unsigned i;
2243
2244                 errno = 0;
2245                 l = strtoll(p, &e, 10);
2246
2247                 if (errno > 0)
2248                         return -errno;
2249
2250                 if (l < 0)
2251                         return -ERANGE;
2252
2253                 if (e == p)
2254                         return -EINVAL;
2255
2256                 if (*e == '.') {
2257                         e++;
2258                         if (*e >= '0' && *e <= '9') {
2259                                 char *e2;
2260
2261                                 /* strotoull itself would accept space/+/- */
2262                                 l2 = strtoull(e, &e2, 10);
2263
2264                                 if (errno == ERANGE)
2265                                         return -errno;
2266
2267                                 /* Ignore failure. E.g. 10.M is valid */
2268                                 frac = l2;
2269                                 for (; e < e2; e++)
2270                                         frac /= 10;
2271                         }
2272                 }
2273
2274                 e += strspn(e, WHITESPACE);
2275
2276                 for (i = start_pos; i < n_entries; i++)
2277                         if (startswith(e, table[i].suffix)) {
2278                                 unsigned long long tmp;
2279                                 if ((unsigned long long) l + (frac > 0) > ULLONG_MAX / table[i].factor)
2280                                         return -ERANGE;
2281                                 tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
2282                                 if (tmp > ULLONG_MAX - r)
2283                                         return -ERANGE;
2284
2285                                 r += tmp;
2286                                 if ((unsigned long long) (off_t) r != r)
2287                                         return -ERANGE;
2288
2289                                 p = e + strlen(table[i].suffix);
2290
2291                                 start_pos = i + 1;
2292                                 break;
2293                         }
2294
2295                 if (i >= n_entries)
2296                         return -EINVAL;
2297
2298         } while (*p);
2299
2300         *size = r;
2301
2302         return 0;
2303 }
2304
2305 int make_stdio(int fd) {
2306         int r, s, t;
2307
2308         assert(fd >= 0);
2309
2310         r = dup2(fd, STDIN_FILENO);
2311         s = dup2(fd, STDOUT_FILENO);
2312         t = dup2(fd, STDERR_FILENO);
2313
2314         if (fd >= 3)
2315                 safe_close(fd);
2316
2317         if (r < 0 || s < 0 || t < 0)
2318                 return -errno;
2319
2320         /* Explicitly unset O_CLOEXEC, since if fd was < 3, then
2321          * dup2() was a NOP and the bit hence possibly set. */
2322         fd_cloexec(STDIN_FILENO, false);
2323         fd_cloexec(STDOUT_FILENO, false);
2324         fd_cloexec(STDERR_FILENO, false);
2325
2326         return 0;
2327 }
2328
2329 int make_null_stdio(void) {
2330         int null_fd;
2331
2332         null_fd = open("/dev/null", O_RDWR|O_NOCTTY);
2333         if (null_fd < 0)
2334                 return -errno;
2335
2336         return make_stdio(null_fd);
2337 }
2338
2339 bool is_device_path(const char *path) {
2340
2341         /* Returns true on paths that refer to a device, either in
2342          * sysfs or in /dev */
2343
2344         return
2345                 path_startswith(path, "/dev/") ||
2346                 path_startswith(path, "/sys/");
2347 }
2348
2349 int dir_is_empty(const char *path) {
2350         _cleanup_closedir_ DIR *d;
2351
2352         d = opendir(path);
2353         if (!d)
2354                 return -errno;
2355
2356         for (;;) {
2357                 struct dirent *de;
2358
2359                 errno = 0;
2360                 de = readdir(d);
2361                 if (!de && errno != 0)
2362                         return -errno;
2363
2364                 if (!de)
2365                         return 1;
2366
2367                 if (!hidden_file(de->d_name))
2368                         return 0;
2369         }
2370 }
2371
2372 char* dirname_malloc(const char *path) {
2373         char *d, *dir, *dir2;
2374
2375         d = strdup(path);
2376         if (!d)
2377                 return NULL;
2378         dir = dirname(d);
2379         assert(dir);
2380
2381         if (dir != d) {
2382                 dir2 = strdup(dir);
2383                 free(d);
2384                 return dir2;
2385         }
2386
2387         return dir;
2388 }
2389
2390 int dev_urandom(void *p, size_t n) {
2391         static int have_syscall = -1;
2392
2393         _cleanup_close_ int fd = -1;
2394         int r;
2395
2396         /* Gathers some randomness from the kernel. This call will
2397          * never block, and will always return some data from the
2398          * kernel, regardless if the random pool is fully initialized
2399          * or not. It thus makes no guarantee for the quality of the
2400          * returned entropy, but is good enough for or usual usecases
2401          * of seeding the hash functions for hashtable */
2402
2403         /* Use the getrandom() syscall unless we know we don't have
2404          * it, or when the requested size is too large for it. */
2405         if (have_syscall != 0 || (size_t) (int) n != n) {
2406                 r = getrandom(p, n, GRND_NONBLOCK);
2407                 if (r == (int) n) {
2408                         have_syscall = true;
2409                         return 0;
2410                 }
2411
2412                 if (r < 0) {
2413                         if (errno == ENOSYS)
2414                                 /* we lack the syscall, continue with
2415                                  * reading from /dev/urandom */
2416                                 have_syscall = false;
2417                         else if (errno == EAGAIN)
2418                                 /* not enough entropy for now. Let's
2419                                  * remember to use the syscall the
2420                                  * next time, again, but also read
2421                                  * from /dev/urandom for now, which
2422                                  * doesn't care about the current
2423                                  * amount of entropy.  */
2424                                 have_syscall = true;
2425                         else
2426                                 return -errno;
2427                 } else
2428                         /* too short read? */
2429                         return -ENODATA;
2430         }
2431
2432         fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
2433         if (fd < 0)
2434                 return errno == ENOENT ? -ENOSYS : -errno;
2435
2436         return loop_read_exact(fd, p, n, true);
2437 }
2438
2439 void initialize_srand(void) {
2440         static bool srand_called = false;
2441         unsigned x;
2442 #ifdef HAVE_SYS_AUXV_H
2443         void *auxv;
2444 #endif
2445
2446         if (srand_called)
2447                 return;
2448
2449         x = 0;
2450
2451 #ifdef HAVE_SYS_AUXV_H
2452         /* The kernel provides us with a bit of entropy in auxv, so
2453          * let's try to make use of that to seed the pseudo-random
2454          * generator. It's better than nothing... */
2455
2456         auxv = (void*) getauxval(AT_RANDOM);
2457         if (auxv)
2458                 x ^= *(unsigned*) auxv;
2459 #endif
2460
2461         x ^= (unsigned) now(CLOCK_REALTIME);
2462         x ^= (unsigned) gettid();
2463
2464         srand(x);
2465         srand_called = true;
2466 }
2467
2468 void random_bytes(void *p, size_t n) {
2469         uint8_t *q;
2470         int r;
2471
2472         r = dev_urandom(p, n);
2473         if (r >= 0)
2474                 return;
2475
2476         /* If some idiot made /dev/urandom unavailable to us, he'll
2477          * get a PRNG instead. */
2478
2479         initialize_srand();
2480
2481         for (q = p; q < (uint8_t*) p + n; q ++)
2482                 *q = rand();
2483 }
2484
2485 void rename_process(const char name[8]) {
2486         assert(name);
2487
2488         /* This is a like a poor man's setproctitle(). It changes the
2489          * comm field, argv[0], and also the glibc's internally used
2490          * name of the process. For the first one a limit of 16 chars
2491          * applies, to the second one usually one of 10 (i.e. length
2492          * of "/sbin/init"), to the third one one of 7 (i.e. length of
2493          * "systemd"). If you pass a longer string it will be
2494          * truncated */
2495
2496         prctl(PR_SET_NAME, name);
2497
2498         if (program_invocation_name)
2499                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2500
2501         if (saved_argc > 0) {
2502                 int i;
2503
2504                 if (saved_argv[0])
2505                         strncpy(saved_argv[0], name, strlen(saved_argv[0]));
2506
2507                 for (i = 1; i < saved_argc; i++) {
2508                         if (!saved_argv[i])
2509                                 break;
2510
2511                         memzero(saved_argv[i], strlen(saved_argv[i]));
2512                 }
2513         }
2514 }
2515
2516 void sigset_add_many(sigset_t *ss, ...) {
2517         va_list ap;
2518         int sig;
2519
2520         assert(ss);
2521
2522         va_start(ap, ss);
2523         while ((sig = va_arg(ap, int)) > 0)
2524                 assert_se(sigaddset(ss, sig) == 0);
2525         va_end(ap);
2526 }
2527
2528 int sigprocmask_many(int how, ...) {
2529         va_list ap;
2530         sigset_t ss;
2531         int sig;
2532
2533         assert_se(sigemptyset(&ss) == 0);
2534
2535         va_start(ap, how);
2536         while ((sig = va_arg(ap, int)) > 0)
2537                 assert_se(sigaddset(&ss, sig) == 0);
2538         va_end(ap);
2539
2540         if (sigprocmask(how, &ss, NULL) < 0)
2541                 return -errno;
2542
2543         return 0;
2544 }
2545
2546 char* gethostname_malloc(void) {
2547         struct utsname u;
2548
2549         assert_se(uname(&u) >= 0);
2550
2551         if (!isempty(u.nodename) && !streq(u.nodename, "(none)"))
2552                 return strdup(u.nodename);
2553
2554         return strdup(u.sysname);
2555 }
2556
2557 bool hostname_is_set(void) {
2558         struct utsname u;
2559
2560         assert_se(uname(&u) >= 0);
2561
2562         return !isempty(u.nodename) && !streq(u.nodename, "(none)");
2563 }
2564
2565 char *lookup_uid(uid_t uid) {
2566         long bufsize;
2567         char *name;
2568         _cleanup_free_ char *buf = NULL;
2569         struct passwd pwbuf, *pw = NULL;
2570
2571         /* Shortcut things to avoid NSS lookups */
2572         if (uid == 0)
2573                 return strdup("root");
2574
2575         bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
2576         if (bufsize <= 0)
2577                 bufsize = 4096;
2578
2579         buf = malloc(bufsize);
2580         if (!buf)
2581                 return NULL;
2582
2583         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw)
2584                 return strdup(pw->pw_name);
2585
2586         if (asprintf(&name, UID_FMT, uid) < 0)
2587                 return NULL;
2588
2589         return name;
2590 }
2591
2592 char* getlogname_malloc(void) {
2593         uid_t uid;
2594         struct stat st;
2595
2596         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2597                 uid = st.st_uid;
2598         else
2599                 uid = getuid();
2600
2601         return lookup_uid(uid);
2602 }
2603
2604 char *getusername_malloc(void) {
2605         const char *e;
2606
2607         e = getenv("USER");
2608         if (e)
2609                 return strdup(e);
2610
2611         return lookup_uid(getuid());
2612 }
2613
2614 int getttyname_malloc(int fd, char **ret) {
2615         size_t l = 100;
2616         int r;
2617
2618         assert(fd >= 0);
2619         assert(ret);
2620
2621         for (;;) {
2622                 char path[l];
2623
2624                 r = ttyname_r(fd, path, sizeof(path));
2625                 if (r == 0) {
2626                         const char *p;
2627                         char *c;
2628
2629                         p = startswith(path, "/dev/");
2630                         c = strdup(p ?: path);
2631                         if (!c)
2632                                 return -ENOMEM;
2633
2634                         *ret = c;
2635                         return 0;
2636                 }
2637
2638                 if (r != ERANGE)
2639                         return -r;
2640
2641                 l *= 2;
2642         }
2643
2644         return 0;
2645 }
2646
2647 int getttyname_harder(int fd, char **r) {
2648         int k;
2649         char *s = NULL;
2650
2651         k = getttyname_malloc(fd, &s);
2652         if (k < 0)
2653                 return k;
2654
2655         if (streq(s, "tty")) {
2656                 free(s);
2657                 return get_ctty(0, NULL, r);
2658         }
2659
2660         *r = s;
2661         return 0;
2662 }
2663
2664 int get_ctty_devnr(pid_t pid, dev_t *d) {
2665         int r;
2666         _cleanup_free_ char *line = NULL;
2667         const char *p;
2668         unsigned long ttynr;
2669
2670         assert(pid >= 0);
2671
2672         p = procfs_file_alloca(pid, "stat");
2673         r = read_one_line_file(p, &line);
2674         if (r < 0)
2675                 return r;
2676
2677         p = strrchr(line, ')');
2678         if (!p)
2679                 return -EIO;
2680
2681         p++;
2682
2683         if (sscanf(p, " "
2684                    "%*c "  /* state */
2685                    "%*d "  /* ppid */
2686                    "%*d "  /* pgrp */
2687                    "%*d "  /* session */
2688                    "%lu ", /* ttynr */
2689                    &ttynr) != 1)
2690                 return -EIO;
2691
2692         if (major(ttynr) == 0 && minor(ttynr) == 0)
2693                 return -ENOENT;
2694
2695         if (d)
2696                 *d = (dev_t) ttynr;
2697
2698         return 0;
2699 }
2700
2701 int get_ctty(pid_t pid, dev_t *_devnr, char **r) {
2702         char fn[sizeof("/dev/char/")-1 + 2*DECIMAL_STR_MAX(unsigned) + 1 + 1], *b = NULL;
2703         _cleanup_free_ char *s = NULL;
2704         const char *p;
2705         dev_t devnr;
2706         int k;
2707
2708         assert(r);
2709
2710         k = get_ctty_devnr(pid, &devnr);
2711         if (k < 0)
2712                 return k;
2713
2714         sprintf(fn, "/dev/char/%u:%u", major(devnr), minor(devnr));
2715
2716         k = readlink_malloc(fn, &s);
2717         if (k < 0) {
2718
2719                 if (k != -ENOENT)
2720                         return k;
2721
2722                 /* This is an ugly hack */
2723                 if (major(devnr) == 136) {
2724                         if (asprintf(&b, "pts/%u", minor(devnr)) < 0)
2725                                 return -ENOMEM;
2726                 } else {
2727                         /* Probably something like the ptys which have no
2728                          * symlink in /dev/char. Let's return something
2729                          * vaguely useful. */
2730
2731                         b = strdup(fn + 5);
2732                         if (!b)
2733                                 return -ENOMEM;
2734                 }
2735         } else {
2736                 if (startswith(s, "/dev/"))
2737                         p = s + 5;
2738                 else if (startswith(s, "../"))
2739                         p = s + 3;
2740                 else
2741                         p = s;
2742
2743                 b = strdup(p);
2744                 if (!b)
2745                         return -ENOMEM;
2746         }
2747
2748         *r = b;
2749         if (_devnr)
2750                 *_devnr = devnr;
2751
2752         return 0;
2753 }
2754
2755 bool is_temporary_fs(const struct statfs *s) {
2756         assert(s);
2757
2758         return F_TYPE_EQUAL(s->f_type, TMPFS_MAGIC) ||
2759                F_TYPE_EQUAL(s->f_type, RAMFS_MAGIC);
2760 }
2761
2762 int fd_is_temporary_fs(int fd) {
2763         struct statfs s;
2764
2765         if (fstatfs(fd, &s) < 0)
2766                 return -errno;
2767
2768         return is_temporary_fs(&s);
2769 }
2770
2771 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2772         assert(path);
2773
2774         /* Under the assumption that we are running privileged we
2775          * first change the access mode and only then hand out
2776          * ownership to avoid a window where access is too open. */
2777
2778         if (mode != MODE_INVALID)
2779                 if (chmod(path, mode) < 0)
2780                         return -errno;
2781
2782         if (uid != UID_INVALID || gid != GID_INVALID)
2783                 if (chown(path, uid, gid) < 0)
2784                         return -errno;
2785
2786         return 0;
2787 }
2788
2789 int fchmod_and_fchown(int fd, mode_t mode, uid_t uid, gid_t gid) {
2790         assert(fd >= 0);
2791
2792         /* Under the assumption that we are running privileged we
2793          * first change the access mode and only then hand out
2794          * ownership to avoid a window where access is too open. */
2795
2796         if (mode != MODE_INVALID)
2797                 if (fchmod(fd, mode) < 0)
2798                         return -errno;
2799
2800         if (uid != UID_INVALID || gid != GID_INVALID)
2801                 if (fchown(fd, uid, gid) < 0)
2802                         return -errno;
2803
2804         return 0;
2805 }
2806
2807 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2808         cpu_set_t *r;
2809         unsigned n = 1024;
2810
2811         /* Allocates the cpuset in the right size */
2812
2813         for (;;) {
2814                 if (!(r = CPU_ALLOC(n)))
2815                         return NULL;
2816
2817                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2818                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2819
2820                         if (ncpus)
2821                                 *ncpus = n;
2822
2823                         return r;
2824                 }
2825
2826                 CPU_FREE(r);
2827
2828                 if (errno != EINVAL)
2829                         return NULL;
2830
2831                 n *= 2;
2832         }
2833 }
2834
2835 int status_vprintf(const char *status, bool ellipse, bool ephemeral, const char *format, va_list ap) {
2836         static const char status_indent[] = "         "; /* "[" STATUS "] " */
2837         _cleanup_free_ char *s = NULL;
2838         _cleanup_close_ int fd = -1;
2839         struct iovec iovec[6] = {};
2840         int n = 0;
2841         static bool prev_ephemeral;
2842
2843         assert(format);
2844
2845         /* This is independent of logging, as status messages are
2846          * optional and go exclusively to the console. */
2847
2848         if (vasprintf(&s, format, ap) < 0)
2849                 return log_oom();
2850
2851         fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
2852         if (fd < 0)
2853                 return fd;
2854
2855         if (ellipse) {
2856                 char *e;
2857                 size_t emax, sl;
2858                 int c;
2859
2860                 c = fd_columns(fd);
2861                 if (c <= 0)
2862                         c = 80;
2863
2864                 sl = status ? sizeof(status_indent)-1 : 0;
2865
2866                 emax = c - sl - 1;
2867                 if (emax < 3)
2868                         emax = 3;
2869
2870                 e = ellipsize(s, emax, 50);
2871                 if (e) {
2872                         free(s);
2873                         s = e;
2874                 }
2875         }
2876
2877         if (prev_ephemeral)
2878                 IOVEC_SET_STRING(iovec[n++], "\r" ANSI_ERASE_TO_END_OF_LINE);
2879         prev_ephemeral = ephemeral;
2880
2881         if (status) {
2882                 if (!isempty(status)) {
2883                         IOVEC_SET_STRING(iovec[n++], "[");
2884                         IOVEC_SET_STRING(iovec[n++], status);
2885                         IOVEC_SET_STRING(iovec[n++], "] ");
2886                 } else
2887                         IOVEC_SET_STRING(iovec[n++], status_indent);
2888         }
2889
2890         IOVEC_SET_STRING(iovec[n++], s);
2891         if (!ephemeral)
2892                 IOVEC_SET_STRING(iovec[n++], "\n");
2893
2894         if (writev(fd, iovec, n) < 0)
2895                 return -errno;
2896
2897         return 0;
2898 }
2899
2900 int status_printf(const char *status, bool ellipse, bool ephemeral, const char *format, ...) {
2901         va_list ap;
2902         int r;
2903
2904         assert(format);
2905
2906         va_start(ap, format);
2907         r = status_vprintf(status, ellipse, ephemeral, format, ap);
2908         va_end(ap);
2909
2910         return r;
2911 }
2912
2913 char *replace_env(const char *format, char **env) {
2914         enum {
2915                 WORD,
2916                 CURLY,
2917                 VARIABLE
2918         } state = WORD;
2919
2920         const char *e, *word = format;
2921         char *r = NULL, *k;
2922
2923         assert(format);
2924
2925         for (e = format; *e; e ++) {
2926
2927                 switch (state) {
2928
2929                 case WORD:
2930                         if (*e == '$')
2931                                 state = CURLY;
2932                         break;
2933
2934                 case CURLY:
2935                         if (*e == '{') {
2936                                 k = strnappend(r, word, e-word-1);
2937                                 if (!k)
2938                                         goto fail;
2939
2940                                 free(r);
2941                                 r = k;
2942
2943                                 word = e-1;
2944                                 state = VARIABLE;
2945
2946                         } else if (*e == '$') {
2947                                 k = strnappend(r, word, e-word);
2948                                 if (!k)
2949                                         goto fail;
2950
2951                                 free(r);
2952                                 r = k;
2953
2954                                 word = e+1;
2955                                 state = WORD;
2956                         } else
2957                                 state = WORD;
2958                         break;
2959
2960                 case VARIABLE:
2961                         if (*e == '}') {
2962                                 const char *t;
2963
2964                                 t = strempty(strv_env_get_n(env, word+2, e-word-2));
2965
2966                                 k = strappend(r, t);
2967                                 if (!k)
2968                                         goto fail;
2969
2970                                 free(r);
2971                                 r = k;
2972
2973                                 word = e+1;
2974                                 state = WORD;
2975                         }
2976                         break;
2977                 }
2978         }
2979
2980         k = strnappend(r, word, e-word);
2981         if (!k)
2982                 goto fail;
2983
2984         free(r);
2985         return k;
2986
2987 fail:
2988         free(r);
2989         return NULL;
2990 }
2991
2992 char **replace_env_argv(char **argv, char **env) {
2993         char **ret, **i;
2994         unsigned k = 0, l = 0;
2995
2996         l = strv_length(argv);
2997
2998         ret = new(char*, l+1);
2999         if (!ret)
3000                 return NULL;
3001
3002         STRV_FOREACH(i, argv) {
3003
3004                 /* If $FOO appears as single word, replace it by the split up variable */
3005                 if ((*i)[0] == '$' && (*i)[1] != '{') {
3006                         char *e;
3007                         char **w, **m = NULL;
3008                         unsigned q;
3009
3010                         e = strv_env_get(env, *i+1);
3011                         if (e) {
3012                                 int r;
3013
3014                                 r = strv_split_quoted(&m, e, UNQUOTE_RELAX);
3015                                 if (r < 0) {
3016                                         ret[k] = NULL;
3017                                         strv_free(ret);
3018                                         return NULL;
3019                                 }
3020                         } else
3021                                 m = NULL;
3022
3023                         q = strv_length(m);
3024                         l = l + q - 1;
3025
3026                         w = realloc(ret, sizeof(char*) * (l+1));
3027                         if (!w) {
3028                                 ret[k] = NULL;
3029                                 strv_free(ret);
3030                                 strv_free(m);
3031                                 return NULL;
3032                         }
3033
3034                         ret = w;
3035                         if (m) {
3036                                 memcpy(ret + k, m, q * sizeof(char*));
3037                                 free(m);
3038                         }
3039
3040                         k += q;
3041                         continue;
3042                 }
3043
3044                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3045                 ret[k] = replace_env(*i, env);
3046                 if (!ret[k]) {
3047                         strv_free(ret);
3048                         return NULL;
3049                 }
3050                 k++;
3051         }
3052
3053         ret[k] = NULL;
3054         return ret;
3055 }
3056
3057 int fd_columns(int fd) {
3058         struct winsize ws = {};
3059
3060         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3061                 return -errno;
3062
3063         if (ws.ws_col <= 0)
3064                 return -EIO;
3065
3066         return ws.ws_col;
3067 }
3068
3069 unsigned columns(void) {
3070         const char *e;
3071         int c;
3072
3073         if (_likely_(cached_columns > 0))
3074                 return cached_columns;
3075
3076         c = 0;
3077         e = getenv("COLUMNS");
3078         if (e)
3079                 (void) safe_atoi(e, &c);
3080
3081         if (c <= 0)
3082                 c = fd_columns(STDOUT_FILENO);
3083
3084         if (c <= 0)
3085                 c = 80;
3086
3087         cached_columns = c;
3088         return cached_columns;
3089 }
3090
3091 int fd_lines(int fd) {
3092         struct winsize ws = {};
3093
3094         if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
3095                 return -errno;
3096
3097         if (ws.ws_row <= 0)
3098                 return -EIO;
3099
3100         return ws.ws_row;
3101 }
3102
3103 unsigned lines(void) {
3104         const char *e;
3105         int l;
3106
3107         if (_likely_(cached_lines > 0))
3108                 return cached_lines;
3109
3110         l = 0;
3111         e = getenv("LINES");
3112         if (e)
3113                 (void) safe_atoi(e, &l);
3114
3115         if (l <= 0)
3116                 l = fd_lines(STDOUT_FILENO);
3117
3118         if (l <= 0)
3119                 l = 24;
3120
3121         cached_lines = l;
3122         return cached_lines;
3123 }
3124
3125 /* intended to be used as a SIGWINCH sighandler */
3126 void columns_lines_cache_reset(int signum) {
3127         cached_columns = 0;
3128         cached_lines = 0;
3129 }
3130
3131 bool on_tty(void) {
3132         static int cached_on_tty = -1;
3133
3134         if (_unlikely_(cached_on_tty < 0))
3135                 cached_on_tty = isatty(STDOUT_FILENO) > 0;
3136
3137         return cached_on_tty;
3138 }
3139
3140 int files_same(const char *filea, const char *fileb) {
3141         struct stat a, b;
3142
3143         if (stat(filea, &a) < 0)
3144                 return -errno;
3145
3146         if (stat(fileb, &b) < 0)
3147                 return -errno;
3148
3149         return a.st_dev == b.st_dev &&
3150                a.st_ino == b.st_ino;
3151 }
3152
3153 int running_in_chroot(void) {
3154         int ret;
3155
3156         ret = files_same("/proc/1/root", "/");
3157         if (ret < 0)
3158                 return ret;
3159
3160         return ret == 0;
3161 }
3162
3163 static char *ascii_ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3164         size_t x;
3165         char *r;
3166
3167         assert(s);
3168         assert(percent <= 100);
3169         assert(new_length >= 3);
3170
3171         if (old_length <= 3 || old_length <= new_length)
3172                 return strndup(s, old_length);
3173
3174         r = new0(char, new_length+1);
3175         if (!r)
3176                 return NULL;
3177
3178         x = (new_length * percent) / 100;
3179
3180         if (x > new_length - 3)
3181                 x = new_length - 3;
3182
3183         memcpy(r, s, x);
3184         r[x] = '.';
3185         r[x+1] = '.';
3186         r[x+2] = '.';
3187         memcpy(r + x + 3,
3188                s + old_length - (new_length - x - 3),
3189                new_length - x - 3);
3190
3191         return r;
3192 }
3193
3194 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
3195         size_t x;
3196         char *e;
3197         const char *i, *j;
3198         unsigned k, len, len2;
3199
3200         assert(s);
3201         assert(percent <= 100);
3202         assert(new_length >= 3);
3203
3204         /* if no multibyte characters use ascii_ellipsize_mem for speed */
3205         if (ascii_is_valid(s))
3206                 return ascii_ellipsize_mem(s, old_length, new_length, percent);
3207
3208         if (old_length <= 3 || old_length <= new_length)
3209                 return strndup(s, old_length);
3210
3211         x = (new_length * percent) / 100;
3212
3213         if (x > new_length - 3)
3214                 x = new_length - 3;
3215
3216         k = 0;
3217         for (i = s; k < x && i < s + old_length; i = utf8_next_char(i)) {
3218                 int c;
3219
3220                 c = utf8_encoded_to_unichar(i);
3221                 if (c < 0)
3222                         return NULL;
3223                 k += unichar_iswide(c) ? 2 : 1;
3224         }
3225
3226         if (k > x) /* last character was wide and went over quota */
3227                 x ++;
3228
3229         for (j = s + old_length; k < new_length && j > i; ) {
3230                 int c;
3231
3232                 j = utf8_prev_char(j);
3233                 c = utf8_encoded_to_unichar(j);
3234                 if (c < 0)
3235                         return NULL;
3236                 k += unichar_iswide(c) ? 2 : 1;
3237         }
3238         assert(i <= j);
3239
3240         /* we don't actually need to ellipsize */
3241         if (i == j)
3242                 return memdup(s, old_length + 1);
3243
3244         /* make space for ellipsis */
3245         j = utf8_next_char(j);
3246
3247         len = i - s;
3248         len2 = s + old_length - j;
3249         e = new(char, len + 3 + len2 + 1);
3250         if (!e)
3251                 return NULL;
3252
3253         /*
3254         printf("old_length=%zu new_length=%zu x=%zu len=%u len2=%u k=%u\n",
3255                old_length, new_length, x, len, len2, k);
3256         */
3257
3258         memcpy(e, s, len);
3259         e[len]   = 0xe2; /* tri-dot ellipsis: … */
3260         e[len + 1] = 0x80;
3261         e[len + 2] = 0xa6;
3262
3263         memcpy(e + len + 3, j, len2 + 1);
3264
3265         return e;
3266 }
3267
3268 char *ellipsize(const char *s, size_t length, unsigned percent) {
3269         return ellipsize_mem(s, strlen(s), length, percent);
3270 }
3271
3272 int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode) {
3273         _cleanup_close_ int fd;
3274         int r;
3275
3276         assert(path);
3277
3278         if (parents)
3279                 mkdir_parents(path, 0755);
3280
3281         fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, mode > 0 ? mode : 0644);
3282         if (fd < 0)
3283                 return -errno;
3284
3285         if (mode > 0) {
3286                 r = fchmod(fd, mode);
3287                 if (r < 0)
3288                         return -errno;
3289         }
3290
3291         if (uid != UID_INVALID || gid != GID_INVALID) {
3292                 r = fchown(fd, uid, gid);
3293                 if (r < 0)
3294                         return -errno;
3295         }
3296
3297         if (stamp != USEC_INFINITY) {
3298                 struct timespec ts[2];
3299
3300                 timespec_store(&ts[0], stamp);
3301                 ts[1] = ts[0];
3302                 r = futimens(fd, ts);
3303         } else
3304                 r = futimens(fd, NULL);
3305         if (r < 0)
3306                 return -errno;
3307
3308         return 0;
3309 }
3310
3311 int touch(const char *path) {
3312         return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, 0);
3313 }
3314
3315 static char *unquote(const char *s, const char* quotes) {
3316         size_t l;
3317         assert(s);
3318
3319         /* This is rather stupid, simply removes the heading and
3320          * trailing quotes if there is one. Doesn't care about
3321          * escaping or anything.
3322          *
3323          * DON'T USE THIS FOR NEW CODE ANYMORE!*/
3324
3325         l = strlen(s);
3326         if (l < 2)
3327                 return strdup(s);
3328
3329         if (strchr(quotes, s[0]) && s[l-1] == s[0])
3330                 return strndup(s+1, l-2);
3331
3332         return strdup(s);
3333 }
3334
3335 noreturn void freeze(void) {
3336
3337         /* Make sure nobody waits for us on a socket anymore */
3338         close_all_fds(NULL, 0);
3339
3340         sync();
3341
3342         for (;;)
3343                 pause();
3344 }
3345
3346 bool null_or_empty(struct stat *st) {
3347         assert(st);
3348
3349         if (S_ISREG(st->st_mode) && st->st_size <= 0)
3350                 return true;
3351
3352         if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
3353                 return true;
3354
3355         return false;
3356 }
3357
3358 int null_or_empty_path(const char *fn) {
3359         struct stat st;
3360
3361         assert(fn);
3362
3363         if (stat(fn, &st) < 0)
3364                 return -errno;
3365
3366         return null_or_empty(&st);
3367 }
3368
3369 int null_or_empty_fd(int fd) {
3370         struct stat st;
3371
3372         assert(fd >= 0);
3373
3374         if (fstat(fd, &st) < 0)
3375                 return -errno;
3376
3377         return null_or_empty(&st);
3378 }
3379
3380 DIR *xopendirat(int fd, const char *name, int flags) {
3381         int nfd;
3382         DIR *d;
3383
3384         assert(!(flags & O_CREAT));
3385
3386         nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
3387         if (nfd < 0)
3388                 return NULL;
3389
3390         d = fdopendir(nfd);
3391         if (!d) {
3392                 safe_close(nfd);
3393                 return NULL;
3394         }
3395
3396         return d;
3397 }
3398
3399 int signal_from_string_try_harder(const char *s) {
3400         int signo;
3401         assert(s);
3402
3403         signo = signal_from_string(s);
3404         if (signo <= 0)
3405                 if (startswith(s, "SIG"))
3406                         return signal_from_string(s+3);
3407
3408         return signo;
3409 }
3410
3411 static char *tag_to_udev_node(const char *tagvalue, const char *by) {
3412         _cleanup_free_ char *t = NULL, *u = NULL;
3413         size_t enc_len;
3414
3415         u = unquote(tagvalue, QUOTES);
3416         if (!u)
3417                 return NULL;
3418
3419         enc_len = strlen(u) * 4 + 1;
3420         t = new(char, enc_len);
3421         if (!t)
3422                 return NULL;
3423
3424         if (encode_devnode_name(u, t, enc_len) < 0)
3425                 return NULL;
3426
3427         return strjoin("/dev/disk/by-", by, "/", t, NULL);
3428 }
3429
3430 char *fstab_node_to_udev_node(const char *p) {
3431         assert(p);
3432
3433         if (startswith(p, "LABEL="))
3434                 return tag_to_udev_node(p+6, "label");
3435
3436         if (startswith(p, "UUID="))
3437                 return tag_to_udev_node(p+5, "uuid");
3438
3439         if (startswith(p, "PARTUUID="))
3440                 return tag_to_udev_node(p+9, "partuuid");
3441
3442         if (startswith(p, "PARTLABEL="))
3443                 return tag_to_udev_node(p+10, "partlabel");
3444
3445         return strdup(p);
3446 }
3447
3448 bool tty_is_vc(const char *tty) {
3449         assert(tty);
3450
3451         return vtnr_from_tty(tty) >= 0;
3452 }
3453
3454 bool tty_is_console(const char *tty) {
3455         assert(tty);
3456
3457         if (startswith(tty, "/dev/"))
3458                 tty += 5;
3459
3460         return streq(tty, "console");
3461 }
3462
3463 int vtnr_from_tty(const char *tty) {
3464         int i, r;
3465
3466         assert(tty);
3467
3468         if (startswith(tty, "/dev/"))
3469                 tty += 5;
3470
3471         if (!startswith(tty, "tty") )
3472                 return -EINVAL;
3473
3474         if (tty[3] < '0' || tty[3] > '9')
3475                 return -EINVAL;
3476
3477         r = safe_atoi(tty+3, &i);
3478         if (r < 0)
3479                 return r;
3480
3481         if (i < 0 || i > 63)
3482                 return -EINVAL;
3483
3484         return i;
3485 }
3486
3487 char *resolve_dev_console(char **active) {
3488         char *tty;
3489
3490         /* Resolve where /dev/console is pointing to, if /sys is actually ours
3491          * (i.e. not read-only-mounted which is a sign for container setups) */
3492
3493         if (path_is_read_only_fs("/sys") > 0)
3494                 return NULL;
3495
3496         if (read_one_line_file("/sys/class/tty/console/active", active) < 0)
3497                 return NULL;
3498
3499         /* If multiple log outputs are configured the last one is what
3500          * /dev/console points to */
3501         tty = strrchr(*active, ' ');
3502         if (tty)
3503                 tty++;
3504         else
3505                 tty = *active;
3506
3507         if (streq(tty, "tty0")) {
3508                 char *tmp;
3509
3510                 /* Get the active VC (e.g. tty1) */
3511                 if (read_one_line_file("/sys/class/tty/tty0/active", &tmp) >= 0) {
3512                         free(*active);
3513                         tty = *active = tmp;
3514                 }
3515         }
3516
3517         return tty;
3518 }
3519
3520 bool tty_is_vc_resolve(const char *tty) {
3521         _cleanup_free_ char *active = NULL;
3522
3523         assert(tty);
3524
3525         if (startswith(tty, "/dev/"))
3526                 tty += 5;
3527
3528         if (streq(tty, "console")) {
3529                 tty = resolve_dev_console(&active);
3530                 if (!tty)
3531                         return false;
3532         }
3533
3534         return tty_is_vc(tty);
3535 }
3536
3537 const char *default_term_for_tty(const char *tty) {
3538         assert(tty);
3539
3540         return tty_is_vc_resolve(tty) ? "TERM=linux" : "TERM=vt220";
3541 }
3542
3543 bool dirent_is_file(const struct dirent *de) {
3544         assert(de);
3545
3546         if (hidden_file(de->d_name))
3547                 return false;
3548
3549         if (de->d_type != DT_REG &&
3550             de->d_type != DT_LNK &&
3551             de->d_type != DT_UNKNOWN)
3552                 return false;
3553
3554         return true;
3555 }
3556
3557 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
3558         assert(de);
3559
3560         if (de->d_type != DT_REG &&
3561             de->d_type != DT_LNK &&
3562             de->d_type != DT_UNKNOWN)
3563                 return false;
3564
3565         if (hidden_file_allow_backup(de->d_name))
3566                 return false;
3567
3568         return endswith(de->d_name, suffix);
3569 }
3570
3571 static int do_execute(char **directories, usec_t timeout, char *argv[]) {
3572         _cleanup_hashmap_free_free_ Hashmap *pids = NULL;
3573         _cleanup_set_free_free_ Set *seen = NULL;
3574         char **directory;
3575
3576         /* We fork this all off from a child process so that we can
3577          * somewhat cleanly make use of SIGALRM to set a time limit */
3578
3579         reset_all_signal_handlers();
3580         reset_signal_mask();
3581
3582         assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
3583
3584         pids = hashmap_new(NULL);
3585         if (!pids)
3586                 return log_oom();
3587
3588         seen = set_new(&string_hash_ops);
3589         if (!seen)
3590                 return log_oom();
3591
3592         STRV_FOREACH(directory, directories) {
3593                 _cleanup_closedir_ DIR *d;
3594                 struct dirent *de;
3595
3596                 d = opendir(*directory);
3597                 if (!d) {
3598                         if (errno == ENOENT)
3599                                 continue;
3600
3601                         return log_error_errno(errno, "Failed to open directory %s: %m", *directory);
3602                 }
3603
3604                 FOREACH_DIRENT(de, d, break) {
3605                         _cleanup_free_ char *path = NULL;
3606                         pid_t pid;
3607                         int r;
3608
3609                         if (!dirent_is_file(de))
3610                                 continue;
3611
3612                         if (set_contains(seen, de->d_name)) {
3613                                 log_debug("%1$s/%2$s skipped (%2$s was already seen).", *directory, de->d_name);
3614                                 continue;
3615                         }
3616
3617                         r = set_put_strdup(seen, de->d_name);
3618                         if (r < 0)
3619                                 return log_oom();
3620
3621                         path = strjoin(*directory, "/", de->d_name, NULL);
3622                         if (!path)
3623                                 return log_oom();
3624
3625                         if (null_or_empty_path(path)) {
3626                                 log_debug("%s is empty (a mask).", path);
3627                                 continue;
3628                         }
3629
3630                         pid = fork();
3631                         if (pid < 0) {
3632                                 log_error_errno(errno, "Failed to fork: %m");
3633                                 continue;
3634                         } else if (pid == 0) {
3635                                 char *_argv[2];
3636
3637                                 assert_se(prctl(PR_SET_PDEATHSIG, SIGTERM) == 0);
3638
3639                                 if (!argv) {
3640                                         _argv[0] = path;
3641                                         _argv[1] = NULL;
3642                                         argv = _argv;
3643                                 } else
3644                                         argv[0] = path;
3645
3646                                 execv(path, argv);
3647                                 return log_error_errno(errno, "Failed to execute %s: %m", path);
3648                         }
3649
3650                         log_debug("Spawned %s as " PID_FMT ".", path, pid);
3651
3652                         r = hashmap_put(pids, UINT_TO_PTR(pid), path);
3653                         if (r < 0)
3654                                 return log_oom();
3655                         path = NULL;
3656                 }
3657         }
3658
3659         /* Abort execution of this process after the timout. We simply
3660          * rely on SIGALRM as default action terminating the process,
3661          * and turn on alarm(). */
3662
3663         if (timeout != USEC_INFINITY)
3664                 alarm((timeout + USEC_PER_SEC - 1) / USEC_PER_SEC);
3665
3666         while (!hashmap_isempty(pids)) {
3667                 _cleanup_free_ char *path = NULL;
3668                 pid_t pid;
3669
3670                 pid = PTR_TO_UINT(hashmap_first_key(pids));
3671                 assert(pid > 0);
3672
3673                 path = hashmap_remove(pids, UINT_TO_PTR(pid));
3674                 assert(path);
3675
3676                 wait_for_terminate_and_warn(path, pid, true);
3677         }
3678
3679         return 0;
3680 }
3681
3682 void execute_directories(const char* const* directories, usec_t timeout, char *argv[]) {
3683         pid_t executor_pid;
3684         int r;
3685         char *name;
3686         char **dirs = (char**) directories;
3687
3688         assert(!strv_isempty(dirs));
3689
3690         name = basename(dirs[0]);
3691         assert(!isempty(name));
3692
3693         /* Executes all binaries in the directories in parallel and waits
3694          * for them to finish. Optionally a timeout is applied. If a file
3695          * with the same name exists in more than one directory, the
3696          * earliest one wins. */
3697
3698         executor_pid = fork();
3699         if (executor_pid < 0) {
3700                 log_error_errno(errno, "Failed to fork: %m");
3701                 return;
3702
3703         } else if (executor_pid == 0) {
3704                 r = do_execute(dirs, timeout, argv);
3705                 _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
3706         }
3707
3708         wait_for_terminate_and_warn(name, executor_pid, true);
3709 }
3710
3711 bool nulstr_contains(const char*nulstr, const char *needle) {
3712         const char *i;
3713
3714         if (!nulstr)
3715                 return false;
3716
3717         NULSTR_FOREACH(i, nulstr)
3718                 if (streq(i, needle))
3719                         return true;
3720
3721         return false;
3722 }
3723
3724 bool plymouth_running(void) {
3725         return access("/run/plymouth/pid", F_OK) >= 0;
3726 }
3727
3728 char* strshorten(char *s, size_t l) {
3729         assert(s);
3730
3731         if (l < strlen(s))
3732                 s[l] = 0;
3733
3734         return s;
3735 }
3736
3737 static bool hostname_valid_char(char c) {
3738         return
3739                 (c >= 'a' && c <= 'z') ||
3740                 (c >= 'A' && c <= 'Z') ||
3741                 (c >= '0' && c <= '9') ||
3742                 c == '-' ||
3743                 c == '_' ||
3744                 c == '.';
3745 }
3746
3747 bool hostname_is_valid(const char *s) {
3748         const char *p;
3749         bool dot;
3750
3751         if (isempty(s))
3752                 return false;
3753
3754         /* Doesn't accept empty hostnames, hostnames with trailing or
3755          * leading dots, and hostnames with multiple dots in a
3756          * sequence. Also ensures that the length stays below
3757          * HOST_NAME_MAX. */
3758
3759         for (p = s, dot = true; *p; p++) {
3760                 if (*p == '.') {
3761                         if (dot)
3762                                 return false;
3763
3764                         dot = true;
3765                 } else {
3766                         if (!hostname_valid_char(*p))
3767                                 return false;
3768
3769                         dot = false;
3770                 }
3771         }
3772
3773         if (dot)
3774                 return false;
3775
3776         if (p-s > HOST_NAME_MAX)
3777                 return false;
3778
3779         return true;
3780 }
3781
3782 char* hostname_cleanup(char *s, bool lowercase) {
3783         char *p, *d;
3784         bool dot;
3785
3786         for (p = s, d = s, dot = true; *p; p++) {
3787                 if (*p == '.') {
3788                         if (dot)
3789                                 continue;
3790
3791                         *(d++) = '.';
3792                         dot = true;
3793                 } else if (hostname_valid_char(*p)) {
3794                         *(d++) = lowercase ? tolower(*p) : *p;
3795                         dot = false;
3796                 }
3797
3798         }
3799
3800         if (dot && d > s)
3801                 d[-1] = 0;
3802         else
3803                 *d = 0;
3804
3805         strshorten(s, HOST_NAME_MAX);
3806
3807         return s;
3808 }
3809
3810 bool machine_name_is_valid(const char *s) {
3811
3812         if (!hostname_is_valid(s))
3813                 return false;
3814
3815         /* Machine names should be useful hostnames, but also be
3816          * useful in unit names, hence we enforce a stricter length
3817          * limitation. */
3818
3819         if (strlen(s) > 64)
3820                 return false;
3821
3822         return true;
3823 }
3824
3825 int pipe_eof(int fd) {
3826         struct pollfd pollfd = {
3827                 .fd = fd,
3828                 .events = POLLIN|POLLHUP,
3829         };
3830
3831         int r;
3832
3833         r = poll(&pollfd, 1, 0);
3834         if (r < 0)
3835                 return -errno;
3836
3837         if (r == 0)
3838                 return 0;
3839
3840         return pollfd.revents & POLLHUP;
3841 }
3842
3843 int fd_wait_for_event(int fd, int event, usec_t t) {
3844
3845         struct pollfd pollfd = {
3846                 .fd = fd,
3847                 .events = event,
3848         };
3849
3850         struct timespec ts;
3851         int r;
3852
3853         r = ppoll(&pollfd, 1, t == USEC_INFINITY ? NULL : timespec_store(&ts, t), NULL);
3854         if (r < 0)
3855                 return -errno;
3856
3857         if (r == 0)
3858                 return 0;
3859
3860         return pollfd.revents;
3861 }
3862
3863 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
3864         FILE *f;
3865         char *t;
3866         int r, fd;
3867
3868         assert(path);
3869         assert(_f);
3870         assert(_temp_path);
3871
3872         r = tempfn_xxxxxx(path, &t);
3873         if (r < 0)
3874                 return r;
3875
3876         fd = mkostemp_safe(t, O_WRONLY|O_CLOEXEC);
3877         if (fd < 0) {
3878                 free(t);
3879                 return -errno;
3880         }
3881
3882         f = fdopen(fd, "we");
3883         if (!f) {
3884                 unlink(t);
3885                 free(t);
3886                 return -errno;
3887         }
3888
3889         *_f = f;
3890         *_temp_path = t;
3891
3892         return 0;
3893 }
3894
3895 int terminal_vhangup_fd(int fd) {
3896         assert(fd >= 0);
3897
3898         if (ioctl(fd, TIOCVHANGUP) < 0)
3899                 return -errno;
3900
3901         return 0;
3902 }
3903
3904 int terminal_vhangup(const char *name) {
3905         _cleanup_close_ int fd;
3906
3907         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3908         if (fd < 0)
3909                 return fd;
3910
3911         return terminal_vhangup_fd(fd);
3912 }
3913
3914 int vt_disallocate(const char *name) {
3915         int fd, r;
3916         unsigned u;
3917
3918         /* Deallocate the VT if possible. If not possible
3919          * (i.e. because it is the active one), at least clear it
3920          * entirely (including the scrollback buffer) */
3921
3922         if (!startswith(name, "/dev/"))
3923                 return -EINVAL;
3924
3925         if (!tty_is_vc(name)) {
3926                 /* So this is not a VT. I guess we cannot deallocate
3927                  * it then. But let's at least clear the screen */
3928
3929                 fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3930                 if (fd < 0)
3931                         return fd;
3932
3933                 loop_write(fd,
3934                            "\033[r"    /* clear scrolling region */
3935                            "\033[H"    /* move home */
3936                            "\033[2J",  /* clear screen */
3937                            10, false);
3938                 safe_close(fd);
3939
3940                 return 0;
3941         }
3942
3943         if (!startswith(name, "/dev/tty"))
3944                 return -EINVAL;
3945
3946         r = safe_atou(name+8, &u);
3947         if (r < 0)
3948                 return r;
3949
3950         if (u <= 0)
3951                 return -EINVAL;
3952
3953         /* Try to deallocate */
3954         fd = open_terminal("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC);
3955         if (fd < 0)
3956                 return fd;
3957
3958         r = ioctl(fd, VT_DISALLOCATE, u);
3959         safe_close(fd);
3960
3961         if (r >= 0)
3962                 return 0;
3963
3964         if (errno != EBUSY)
3965                 return -errno;
3966
3967         /* Couldn't deallocate, so let's clear it fully with
3968          * scrollback */
3969         fd = open_terminal(name, O_RDWR|O_NOCTTY|O_CLOEXEC);
3970         if (fd < 0)
3971                 return fd;
3972
3973         loop_write(fd,
3974                    "\033[r"   /* clear scrolling region */
3975                    "\033[H"   /* move home */
3976                    "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
3977                    10, false);
3978         safe_close(fd);
3979
3980         return 0;
3981 }
3982
3983 int symlink_atomic(const char *from, const char *to) {
3984         _cleanup_free_ char *t = NULL;
3985         int r;
3986
3987         assert(from);
3988         assert(to);
3989
3990         r = tempfn_random(to, &t);
3991         if (r < 0)
3992                 return r;
3993
3994         if (symlink(from, t) < 0)
3995                 return -errno;
3996
3997         if (rename(t, to) < 0) {
3998                 unlink_noerrno(t);
3999                 return -errno;
4000         }
4001
4002         return 0;
4003 }
4004
4005 int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
4006         _cleanup_free_ char *t = NULL;
4007         int r;
4008
4009         assert(path);
4010
4011         r = tempfn_random(path, &t);
4012         if (r < 0)
4013                 return r;
4014
4015         if (mknod(t, mode, dev) < 0)
4016                 return -errno;
4017
4018         if (rename(t, path) < 0) {
4019                 unlink_noerrno(t);
4020                 return -errno;
4021         }
4022
4023         return 0;
4024 }
4025
4026 int mkfifo_atomic(const char *path, mode_t mode) {
4027         _cleanup_free_ char *t = NULL;
4028         int r;
4029
4030         assert(path);
4031
4032         r = tempfn_random(path, &t);
4033         if (r < 0)
4034                 return r;
4035
4036         if (mkfifo(t, mode) < 0)
4037                 return -errno;
4038
4039         if (rename(t, path) < 0) {
4040                 unlink_noerrno(t);
4041                 return -errno;
4042         }
4043
4044         return 0;
4045 }
4046
4047 bool display_is_local(const char *display) {
4048         assert(display);
4049
4050         return
4051                 display[0] == ':' &&
4052                 display[1] >= '0' &&
4053                 display[1] <= '9';
4054 }
4055
4056 int socket_from_display(const char *display, char **path) {
4057         size_t k;
4058         char *f, *c;
4059
4060         assert(display);
4061         assert(path);
4062
4063         if (!display_is_local(display))
4064                 return -EINVAL;
4065
4066         k = strspn(display+1, "0123456789");
4067
4068         f = new(char, strlen("/tmp/.X11-unix/X") + k + 1);
4069         if (!f)
4070                 return -ENOMEM;
4071
4072         c = stpcpy(f, "/tmp/.X11-unix/X");
4073         memcpy(c, display+1, k);
4074         c[k] = 0;
4075
4076         *path = f;
4077
4078         return 0;
4079 }
4080
4081 int get_user_creds(
4082                 const char **username,
4083                 uid_t *uid, gid_t *gid,
4084                 const char **home,
4085                 const char **shell) {
4086
4087         struct passwd *p;
4088         uid_t u;
4089
4090         assert(username);
4091         assert(*username);
4092
4093         /* We enforce some special rules for uid=0: in order to avoid
4094          * NSS lookups for root we hardcode its data. */
4095
4096         if (streq(*username, "root") || streq(*username, "0")) {
4097                 *username = "root";
4098
4099                 if (uid)
4100                         *uid = 0;
4101
4102                 if (gid)
4103                         *gid = 0;
4104
4105                 if (home)
4106                         *home = "/root";
4107
4108                 if (shell)
4109                         *shell = "/bin/sh";
4110
4111                 return 0;
4112         }
4113
4114         if (parse_uid(*username, &u) >= 0) {
4115                 errno = 0;
4116                 p = getpwuid(u);
4117
4118                 /* If there are multiple users with the same id, make
4119                  * sure to leave $USER to the configured value instead
4120                  * of the first occurrence in the database. However if
4121                  * the uid was configured by a numeric uid, then let's
4122                  * pick the real username from /etc/passwd. */
4123                 if (p)
4124                         *username = p->pw_name;
4125         } else {
4126                 errno = 0;
4127                 p = getpwnam(*username);
4128         }
4129
4130         if (!p)
4131                 return errno > 0 ? -errno : -ESRCH;
4132
4133         if (uid)
4134                 *uid = p->pw_uid;
4135
4136         if (gid)
4137                 *gid = p->pw_gid;
4138
4139         if (home)
4140                 *home = p->pw_dir;
4141
4142         if (shell)
4143                 *shell = p->pw_shell;
4144
4145         return 0;
4146 }
4147
4148 char* uid_to_name(uid_t uid) {
4149         struct passwd *p;
4150         char *r;
4151
4152         if (uid == 0)
4153                 return strdup("root");
4154
4155         p = getpwuid(uid);
4156         if (p)
4157                 return strdup(p->pw_name);
4158
4159         if (asprintf(&r, UID_FMT, uid) < 0)
4160                 return NULL;
4161
4162         return r;
4163 }
4164
4165 char* gid_to_name(gid_t gid) {
4166         struct group *p;
4167         char *r;
4168
4169         if (gid == 0)
4170                 return strdup("root");
4171
4172         p = getgrgid(gid);
4173         if (p)
4174                 return strdup(p->gr_name);
4175
4176         if (asprintf(&r, GID_FMT, gid) < 0)
4177                 return NULL;
4178
4179         return r;
4180 }
4181
4182 int get_group_creds(const char **groupname, gid_t *gid) {
4183         struct group *g;
4184         gid_t id;
4185
4186         assert(groupname);
4187
4188         /* We enforce some special rules for gid=0: in order to avoid
4189          * NSS lookups for root we hardcode its data. */
4190
4191         if (streq(*groupname, "root") || streq(*groupname, "0")) {
4192                 *groupname = "root";
4193
4194                 if (gid)
4195                         *gid = 0;
4196
4197                 return 0;
4198         }
4199
4200         if (parse_gid(*groupname, &id) >= 0) {
4201                 errno = 0;
4202                 g = getgrgid(id);
4203
4204                 if (g)
4205                         *groupname = g->gr_name;
4206         } else {
4207                 errno = 0;
4208                 g = getgrnam(*groupname);
4209         }
4210
4211         if (!g)
4212                 return errno > 0 ? -errno : -ESRCH;
4213
4214         if (gid)
4215                 *gid = g->gr_gid;
4216
4217         return 0;
4218 }
4219
4220 int in_gid(gid_t gid) {
4221         gid_t *gids;
4222         int ngroups_max, r, i;
4223
4224         if (getgid() == gid)
4225                 return 1;
4226
4227         if (getegid() == gid)
4228                 return 1;
4229
4230         ngroups_max = sysconf(_SC_NGROUPS_MAX);
4231         assert(ngroups_max > 0);
4232
4233         gids = alloca(sizeof(gid_t) * ngroups_max);
4234
4235         r = getgroups(ngroups_max, gids);
4236         if (r < 0)
4237                 return -errno;
4238
4239         for (i = 0; i < r; i++)
4240                 if (gids[i] == gid)
4241                         return 1;
4242
4243         return 0;
4244 }
4245
4246 int in_group(const char *name) {
4247         int r;
4248         gid_t gid;
4249
4250         r = get_group_creds(&name, &gid);
4251         if (r < 0)
4252                 return r;
4253
4254         return in_gid(gid);
4255 }
4256
4257 int glob_exists(const char *path) {
4258         _cleanup_globfree_ glob_t g = {};
4259         int k;
4260
4261         assert(path);
4262
4263         errno = 0;
4264         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4265
4266         if (k == GLOB_NOMATCH)
4267                 return 0;
4268         else if (k == GLOB_NOSPACE)
4269                 return -ENOMEM;
4270         else if (k == 0)
4271                 return !strv_isempty(g.gl_pathv);
4272         else
4273                 return errno ? -errno : -EIO;
4274 }
4275
4276 int glob_extend(char ***strv, const char *path) {
4277         _cleanup_globfree_ glob_t g = {};
4278         int k;
4279         char **p;
4280
4281         errno = 0;
4282         k = glob(path, GLOB_NOSORT|GLOB_BRACE, NULL, &g);
4283
4284         if (k == GLOB_NOMATCH)
4285                 return -ENOENT;
4286         else if (k == GLOB_NOSPACE)
4287                 return -ENOMEM;
4288         else if (k != 0 || strv_isempty(g.gl_pathv))
4289                 return errno ? -errno : -EIO;
4290
4291         STRV_FOREACH(p, g.gl_pathv) {
4292                 k = strv_extend(strv, *p);
4293                 if (k < 0)
4294                         break;
4295         }
4296
4297         return k;
4298 }
4299
4300 int dirent_ensure_type(DIR *d, struct dirent *de) {
4301         struct stat st;
4302
4303         assert(d);
4304         assert(de);
4305
4306         if (de->d_type != DT_UNKNOWN)
4307                 return 0;
4308
4309         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
4310                 return -errno;
4311
4312         de->d_type =
4313                 S_ISREG(st.st_mode)  ? DT_REG  :
4314                 S_ISDIR(st.st_mode)  ? DT_DIR  :
4315                 S_ISLNK(st.st_mode)  ? DT_LNK  :
4316                 S_ISFIFO(st.st_mode) ? DT_FIFO :
4317                 S_ISSOCK(st.st_mode) ? DT_SOCK :
4318                 S_ISCHR(st.st_mode)  ? DT_CHR  :
4319                 S_ISBLK(st.st_mode)  ? DT_BLK  :
4320                                        DT_UNKNOWN;
4321
4322         return 0;
4323 }
4324
4325 int get_files_in_directory(const char *path, char ***list) {
4326         _cleanup_closedir_ DIR *d = NULL;
4327         size_t bufsize = 0, n = 0;
4328         _cleanup_strv_free_ char **l = NULL;
4329
4330         assert(path);
4331
4332         /* Returns all files in a directory in *list, and the number
4333          * of files as return value. If list is NULL returns only the
4334          * number. */
4335
4336         d = opendir(path);
4337         if (!d)
4338                 return -errno;
4339
4340         for (;;) {
4341                 struct dirent *de;
4342
4343                 errno = 0;
4344                 de = readdir(d);
4345                 if (!de && errno != 0)
4346                         return -errno;
4347                 if (!de)
4348                         break;
4349
4350                 dirent_ensure_type(d, de);
4351
4352                 if (!dirent_is_file(de))
4353                         continue;
4354
4355                 if (list) {
4356                         /* one extra slot is needed for the terminating NULL */
4357                         if (!GREEDY_REALLOC(l, bufsize, n + 2))
4358                                 return -ENOMEM;
4359
4360                         l[n] = strdup(de->d_name);
4361                         if (!l[n])
4362                                 return -ENOMEM;
4363
4364                         l[++n] = NULL;
4365                 } else
4366                         n++;
4367         }
4368
4369         if (list) {
4370                 *list = l;
4371                 l = NULL; /* avoid freeing */
4372         }
4373
4374         return n;
4375 }
4376
4377 char *strjoin(const char *x, ...) {
4378         va_list ap;
4379         size_t l;
4380         char *r, *p;
4381
4382         va_start(ap, x);
4383
4384         if (x) {
4385                 l = strlen(x);
4386
4387                 for (;;) {
4388                         const char *t;
4389                         size_t n;
4390
4391                         t = va_arg(ap, const char *);
4392                         if (!t)
4393                                 break;
4394
4395                         n = strlen(t);
4396                         if (n > ((size_t) -1) - l) {
4397                                 va_end(ap);
4398                                 return NULL;
4399                         }
4400
4401                         l += n;
4402                 }
4403         } else
4404                 l = 0;
4405
4406         va_end(ap);
4407
4408         r = new(char, l+1);
4409         if (!r)
4410                 return NULL;
4411
4412         if (x) {
4413                 p = stpcpy(r, x);
4414
4415                 va_start(ap, x);
4416
4417                 for (;;) {
4418                         const char *t;
4419
4420                         t = va_arg(ap, const char *);
4421                         if (!t)
4422                                 break;
4423
4424                         p = stpcpy(p, t);
4425                 }
4426
4427                 va_end(ap);
4428         } else
4429                 r[0] = 0;
4430
4431         return r;
4432 }
4433
4434 bool is_main_thread(void) {
4435         static thread_local int cached = 0;
4436
4437         if (_unlikely_(cached == 0))
4438                 cached = getpid() == gettid() ? 1 : -1;
4439
4440         return cached > 0;
4441 }
4442
4443 int block_get_whole_disk(dev_t d, dev_t *ret) {
4444         char *p, *s;
4445         int r;
4446         unsigned n, m;
4447
4448         assert(ret);
4449
4450         /* If it has a queue this is good enough for us */
4451         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", major(d), minor(d)) < 0)
4452                 return -ENOMEM;
4453
4454         r = access(p, F_OK);
4455         free(p);
4456
4457         if (r >= 0) {
4458                 *ret = d;
4459                 return 0;
4460         }
4461
4462         /* If it is a partition find the originating device */
4463         if (asprintf(&p, "/sys/dev/block/%u:%u/partition", major(d), minor(d)) < 0)
4464                 return -ENOMEM;
4465
4466         r = access(p, F_OK);
4467         free(p);
4468
4469         if (r < 0)
4470                 return -ENOENT;
4471
4472         /* Get parent dev_t */
4473         if (asprintf(&p, "/sys/dev/block/%u:%u/../dev", major(d), minor(d)) < 0)
4474                 return -ENOMEM;
4475
4476         r = read_one_line_file(p, &s);
4477         free(p);
4478
4479         if (r < 0)
4480                 return r;
4481
4482         r = sscanf(s, "%u:%u", &m, &n);
4483         free(s);
4484
4485         if (r != 2)
4486                 return -EINVAL;
4487
4488         /* Only return this if it is really good enough for us. */
4489         if (asprintf(&p, "/sys/dev/block/%u:%u/queue", m, n) < 0)
4490                 return -ENOMEM;
4491
4492         r = access(p, F_OK);
4493         free(p);
4494
4495         if (r >= 0) {
4496                 *ret = makedev(m, n);
4497                 return 0;
4498         }
4499
4500         return -ENOENT;
4501 }
4502
4503 static const char *const ioprio_class_table[] = {
4504         [IOPRIO_CLASS_NONE] = "none",
4505         [IOPRIO_CLASS_RT] = "realtime",
4506         [IOPRIO_CLASS_BE] = "best-effort",
4507         [IOPRIO_CLASS_IDLE] = "idle"
4508 };
4509
4510 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, INT_MAX);
4511
4512 static const char *const sigchld_code_table[] = {
4513         [CLD_EXITED] = "exited",
4514         [CLD_KILLED] = "killed",
4515         [CLD_DUMPED] = "dumped",
4516         [CLD_TRAPPED] = "trapped",
4517         [CLD_STOPPED] = "stopped",
4518         [CLD_CONTINUED] = "continued",
4519 };
4520
4521 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
4522
4523 static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = {
4524         [LOG_FAC(LOG_KERN)] = "kern",
4525         [LOG_FAC(LOG_USER)] = "user",
4526         [LOG_FAC(LOG_MAIL)] = "mail",
4527         [LOG_FAC(LOG_DAEMON)] = "daemon",
4528         [LOG_FAC(LOG_AUTH)] = "auth",
4529         [LOG_FAC(LOG_SYSLOG)] = "syslog",
4530         [LOG_FAC(LOG_LPR)] = "lpr",
4531         [LOG_FAC(LOG_NEWS)] = "news",
4532         [LOG_FAC(LOG_UUCP)] = "uucp",
4533         [LOG_FAC(LOG_CRON)] = "cron",
4534         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
4535         [LOG_FAC(LOG_FTP)] = "ftp",
4536         [LOG_FAC(LOG_LOCAL0)] = "local0",
4537         [LOG_FAC(LOG_LOCAL1)] = "local1",
4538         [LOG_FAC(LOG_LOCAL2)] = "local2",
4539         [LOG_FAC(LOG_LOCAL3)] = "local3",
4540         [LOG_FAC(LOG_LOCAL4)] = "local4",
4541         [LOG_FAC(LOG_LOCAL5)] = "local5",
4542         [LOG_FAC(LOG_LOCAL6)] = "local6",
4543         [LOG_FAC(LOG_LOCAL7)] = "local7"
4544 };
4545
4546 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0));
4547
4548 static const char *const log_level_table[] = {
4549         [LOG_EMERG] = "emerg",
4550         [LOG_ALERT] = "alert",
4551         [LOG_CRIT] = "crit",
4552         [LOG_ERR] = "err",
4553         [LOG_WARNING] = "warning",
4554         [LOG_NOTICE] = "notice",
4555         [LOG_INFO] = "info",
4556         [LOG_DEBUG] = "debug"
4557 };
4558
4559 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG);
4560
4561 static const char* const sched_policy_table[] = {
4562         [SCHED_OTHER] = "other",
4563         [SCHED_BATCH] = "batch",
4564         [SCHED_IDLE] = "idle",
4565         [SCHED_FIFO] = "fifo",
4566         [SCHED_RR] = "rr"
4567 };
4568
4569 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(sched_policy, int, INT_MAX);
4570
4571 static const char* const rlimit_table[_RLIMIT_MAX] = {
4572         [RLIMIT_CPU] = "LimitCPU",
4573         [RLIMIT_FSIZE] = "LimitFSIZE",
4574         [RLIMIT_DATA] = "LimitDATA",
4575         [RLIMIT_STACK] = "LimitSTACK",
4576         [RLIMIT_CORE] = "LimitCORE",
4577         [RLIMIT_RSS] = "LimitRSS",
4578         [RLIMIT_NOFILE] = "LimitNOFILE",
4579         [RLIMIT_AS] = "LimitAS",
4580         [RLIMIT_NPROC] = "LimitNPROC",
4581         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
4582         [RLIMIT_LOCKS] = "LimitLOCKS",
4583         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
4584         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
4585         [RLIMIT_NICE] = "LimitNICE",
4586         [RLIMIT_RTPRIO] = "LimitRTPRIO",
4587         [RLIMIT_RTTIME] = "LimitRTTIME"
4588 };
4589
4590 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
4591
4592 static const char* const ip_tos_table[] = {
4593         [IPTOS_LOWDELAY] = "low-delay",
4594         [IPTOS_THROUGHPUT] = "throughput",
4595         [IPTOS_RELIABILITY] = "reliability",
4596         [IPTOS_LOWCOST] = "low-cost",
4597 };
4598
4599 DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ip_tos, int, 0xff);
4600
4601 static const char *const __signal_table[] = {
4602         [SIGHUP] = "HUP",
4603         [SIGINT] = "INT",
4604         [SIGQUIT] = "QUIT",
4605         [SIGILL] = "ILL",
4606         [SIGTRAP] = "TRAP",
4607         [SIGABRT] = "ABRT",
4608         [SIGBUS] = "BUS",
4609         [SIGFPE] = "FPE",
4610         [SIGKILL] = "KILL",
4611         [SIGUSR1] = "USR1",
4612         [SIGSEGV] = "SEGV",
4613         [SIGUSR2] = "USR2",
4614         [SIGPIPE] = "PIPE",
4615         [SIGALRM] = "ALRM",
4616         [SIGTERM] = "TERM",
4617 #ifdef SIGSTKFLT
4618         [SIGSTKFLT] = "STKFLT",  /* Linux on SPARC doesn't know SIGSTKFLT */
4619 #endif
4620         [SIGCHLD] = "CHLD",
4621         [SIGCONT] = "CONT",
4622         [SIGSTOP] = "STOP",
4623         [SIGTSTP] = "TSTP",
4624         [SIGTTIN] = "TTIN",
4625         [SIGTTOU] = "TTOU",
4626         [SIGURG] = "URG",
4627         [SIGXCPU] = "XCPU",
4628         [SIGXFSZ] = "XFSZ",
4629         [SIGVTALRM] = "VTALRM",
4630         [SIGPROF] = "PROF",
4631         [SIGWINCH] = "WINCH",
4632         [SIGIO] = "IO",
4633         [SIGPWR] = "PWR",
4634         [SIGSYS] = "SYS"
4635 };
4636
4637 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal, int);
4638
4639 const char *signal_to_string(int signo) {
4640         static thread_local char buf[sizeof("RTMIN+")-1 + DECIMAL_STR_MAX(int) + 1];
4641         const char *name;
4642
4643         name = __signal_to_string(signo);
4644         if (name)
4645                 return name;
4646
4647         if (signo >= SIGRTMIN && signo <= SIGRTMAX)
4648                 snprintf(buf, sizeof(buf), "RTMIN+%d", signo - SIGRTMIN);
4649         else
4650                 snprintf(buf, sizeof(buf), "%d", signo);
4651
4652         return buf;
4653 }
4654
4655 int signal_from_string(const char *s) {
4656         int signo;
4657         int offset = 0;
4658         unsigned u;
4659
4660         signo = __signal_from_string(s);
4661         if (signo > 0)
4662                 return signo;
4663
4664         if (startswith(s, "RTMIN+")) {
4665                 s += 6;
4666                 offset = SIGRTMIN;
4667         }
4668         if (safe_atou(s, &u) >= 0) {
4669                 signo = (int) u + offset;
4670                 if (signo > 0 && signo < _NSIG)
4671                         return signo;
4672         }
4673         return -EINVAL;
4674 }
4675
4676 bool kexec_loaded(void) {
4677        bool loaded = false;
4678        char *s;
4679
4680        if (read_one_line_file("/sys/kernel/kexec_loaded", &s) >= 0) {
4681                if (s[0] == '1')
4682                        loaded = true;
4683                free(s);
4684        }
4685        return loaded;
4686 }
4687
4688 int prot_from_flags(int flags) {
4689
4690         switch (flags & O_ACCMODE) {
4691
4692         case O_RDONLY:
4693                 return PROT_READ;
4694
4695         case O_WRONLY:
4696                 return PROT_WRITE;
4697
4698         case O_RDWR:
4699                 return PROT_READ|PROT_WRITE;
4700
4701         default:
4702                 return -EINVAL;
4703         }
4704 }
4705
4706 char *format_bytes(char *buf, size_t l, off_t t) {
4707         unsigned i;
4708
4709         static const struct {
4710                 const char *suffix;
4711                 off_t factor;
4712         } table[] = {
4713                 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4714                 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
4715                 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
4716                 { "G", 1024ULL*1024ULL*1024ULL },
4717                 { "M", 1024ULL*1024ULL },
4718                 { "K", 1024ULL },
4719         };
4720
4721         if (t == (off_t) -1)
4722                 return NULL;
4723
4724         for (i = 0; i < ELEMENTSOF(table); i++) {
4725
4726                 if (t >= table[i].factor) {
4727                         snprintf(buf, l,
4728                                  "%llu.%llu%s",
4729                                  (unsigned long long) (t / table[i].factor),
4730                                  (unsigned long long) (((t*10ULL) / table[i].factor) % 10ULL),
4731                                  table[i].suffix);
4732
4733                         goto finish;
4734                 }
4735         }
4736
4737         snprintf(buf, l, "%lluB", (unsigned long long) t);
4738
4739 finish:
4740         buf[l-1] = 0;
4741         return buf;
4742
4743 }
4744
4745 void* memdup(const void *p, size_t l) {
4746         void *r;
4747
4748         assert(p);
4749
4750         r = malloc(l);
4751         if (!r)
4752                 return NULL;
4753
4754         memcpy(r, p, l);
4755         return r;
4756 }
4757
4758 int fd_inc_sndbuf(int fd, size_t n) {
4759         int r, value;
4760         socklen_t l = sizeof(value);
4761
4762         r = getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, &l);
4763         if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
4764                 return 0;
4765
4766         /* If we have the privileges we will ignore the kernel limit. */
4767
4768         value = (int) n;
4769         if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
4770                 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
4771                         return -errno;
4772
4773         return 1;
4774 }
4775
4776 int fd_inc_rcvbuf(int fd, size_t n) {
4777         int r, value;
4778         socklen_t l = sizeof(value);
4779
4780         r = getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, &l);
4781         if (r >= 0 && l == sizeof(value) && (size_t) value >= n*2)
4782                 return 0;
4783
4784         /* If we have the privileges we will ignore the kernel limit. */
4785
4786         value = (int) n;
4787         if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
4788                 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
4789                         return -errno;
4790         return 1;
4791 }
4792
4793 int fork_agent(pid_t *pid, const int except[], unsigned n_except, const char *path, ...) {
4794         bool stdout_is_tty, stderr_is_tty;
4795         pid_t parent_pid, agent_pid;
4796         sigset_t ss, saved_ss;
4797         unsigned n, i;
4798         va_list ap;
4799         char **l;
4800
4801         assert(pid);
4802         assert(path);
4803
4804         /* Spawns a temporary TTY agent, making sure it goes away when
4805          * we go away */
4806
4807         parent_pid = getpid();
4808
4809         /* First we temporarily block all signals, so that the new
4810          * child has them blocked initially. This way, we can be sure
4811          * that SIGTERMs are not lost we might send to the agent. */
4812         assert_se(sigfillset(&ss) >= 0);
4813         assert_se(sigprocmask(SIG_SETMASK, &ss, &saved_ss) >= 0);
4814
4815         agent_pid = fork();
4816         if (agent_pid < 0) {
4817                 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
4818                 return -errno;
4819         }
4820
4821         if (agent_pid != 0) {
4822                 assert_se(sigprocmask(SIG_SETMASK, &saved_ss, NULL) >= 0);
4823                 *pid = agent_pid;
4824                 return 0;
4825         }
4826
4827         /* In the child:
4828          *
4829          * Make sure the agent goes away when the parent dies */
4830         if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
4831                 _exit(EXIT_FAILURE);
4832
4833         /* Make sure we actually can kill the agent, if we need to, in
4834          * case somebody invoked us from a shell script that trapped
4835          * SIGTERM or so... */
4836         reset_all_signal_handlers();
4837         reset_signal_mask();
4838
4839         /* Check whether our parent died before we were able
4840          * to set the death signal and unblock the signals */
4841         if (getppid() != parent_pid)
4842                 _exit(EXIT_SUCCESS);
4843
4844         /* Don't leak fds to the agent */
4845         close_all_fds(except, n_except);
4846
4847         stdout_is_tty = isatty(STDOUT_FILENO);
4848         stderr_is_tty = isatty(STDERR_FILENO);
4849
4850         if (!stdout_is_tty || !stderr_is_tty) {
4851                 int fd;
4852
4853                 /* Detach from stdout/stderr. and reopen
4854                  * /dev/tty for them. This is important to
4855                  * ensure that when systemctl is started via
4856                  * popen() or a similar call that expects to
4857                  * read EOF we actually do generate EOF and
4858                  * not delay this indefinitely by because we
4859                  * keep an unused copy of stdin around. */
4860                 fd = open("/dev/tty", O_WRONLY);
4861                 if (fd < 0) {
4862                         log_error_errno(errno, "Failed to open /dev/tty: %m");
4863                         _exit(EXIT_FAILURE);
4864                 }
4865
4866                 if (!stdout_is_tty)
4867                         dup2(fd, STDOUT_FILENO);
4868
4869                 if (!stderr_is_tty)
4870                         dup2(fd, STDERR_FILENO);
4871
4872                 if (fd > 2)
4873                         close(fd);
4874         }
4875
4876         /* Count arguments */
4877         va_start(ap, path);
4878         for (n = 0; va_arg(ap, char*); n++)
4879                 ;
4880         va_end(ap);
4881
4882         /* Allocate strv */
4883         l = alloca(sizeof(char *) * (n + 1));
4884
4885         /* Fill in arguments */
4886         va_start(ap, path);
4887         for (i = 0; i <= n; i++)
4888                 l[i] = va_arg(ap, char*);
4889         va_end(ap);
4890
4891         execv(path, l);
4892         _exit(EXIT_FAILURE);
4893 }
4894
4895 int setrlimit_closest(int resource, const struct rlimit *rlim) {
4896         struct rlimit highest, fixed;
4897
4898         assert(rlim);
4899
4900         if (setrlimit(resource, rlim) >= 0)
4901                 return 0;
4902
4903         if (errno != EPERM)
4904                 return -errno;
4905
4906         /* So we failed to set the desired setrlimit, then let's try
4907          * to get as close as we can */
4908         assert_se(getrlimit(resource, &highest) == 0);
4909
4910         fixed.rlim_cur = MIN(rlim->rlim_cur, highest.rlim_max);
4911         fixed.rlim_max = MIN(rlim->rlim_max, highest.rlim_max);
4912
4913         if (setrlimit(resource, &fixed) < 0)
4914                 return -errno;
4915
4916         return 0;
4917 }
4918
4919 bool http_etag_is_valid(const char *etag) {
4920         if (isempty(etag))
4921                 return false;
4922
4923         if (!endswith(etag, "\""))
4924                 return false;
4925
4926         if (!startswith(etag, "\"") && !startswith(etag, "W/\""))
4927                 return false;
4928
4929         return true;
4930 }
4931
4932 bool http_url_is_valid(const char *url) {
4933         const char *p;
4934
4935         if (isempty(url))
4936                 return false;
4937
4938         p = startswith(url, "http://");
4939         if (!p)
4940                 p = startswith(url, "https://");
4941         if (!p)
4942                 return false;
4943
4944         if (isempty(p))
4945                 return false;
4946
4947         return ascii_is_valid(p);
4948 }
4949
4950 bool documentation_url_is_valid(const char *url) {
4951         const char *p;
4952
4953         if (isempty(url))
4954                 return false;
4955
4956         if (http_url_is_valid(url))
4957                 return true;
4958
4959         p = startswith(url, "file:/");
4960         if (!p)
4961                 p = startswith(url, "info:");
4962         if (!p)
4963                 p = startswith(url, "man:");
4964
4965         if (isempty(p))
4966                 return false;
4967
4968         return ascii_is_valid(p);
4969 }
4970
4971 bool in_initrd(void) {
4972         static int saved = -1;
4973         struct statfs s;
4974
4975         if (saved >= 0)
4976                 return saved;
4977
4978         /* We make two checks here:
4979          *
4980          * 1. the flag file /etc/initrd-release must exist
4981          * 2. the root file system must be a memory file system
4982          *
4983          * The second check is extra paranoia, since misdetecting an
4984          * initrd can have bad bad consequences due the initrd
4985          * emptying when transititioning to the main systemd.
4986          */
4987
4988         saved = access("/etc/initrd-release", F_OK) >= 0 &&
4989                 statfs("/", &s) >= 0 &&
4990                 is_temporary_fs(&s);
4991
4992         return saved;
4993 }
4994
4995 void warn_melody(void) {
4996         _cleanup_close_ int fd = -1;
4997
4998         fd = open("/dev/console", O_WRONLY|O_CLOEXEC|O_NOCTTY);
4999         if (fd < 0)
5000                 return;
5001
5002         /* Yeah, this is synchronous. Kinda sucks. But well... */
5003
5004         ioctl(fd, KIOCSOUND, (int)(1193180/440));
5005         usleep(125*USEC_PER_MSEC);
5006
5007         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5008         usleep(125*USEC_PER_MSEC);
5009
5010         ioctl(fd, KIOCSOUND, (int)(1193180/220));
5011         usleep(125*USEC_PER_MSEC);
5012
5013         ioctl(fd, KIOCSOUND, 0);
5014 }
5015
5016 int make_console_stdio(void) {
5017         int fd, r;
5018
5019         /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5020
5021         fd = acquire_terminal("/dev/console", false, true, true, USEC_INFINITY);
5022         if (fd < 0)
5023                 return log_error_errno(fd, "Failed to acquire terminal: %m");
5024
5025         r = make_stdio(fd);
5026         if (r < 0)
5027                 return log_error_errno(r, "Failed to duplicate terminal fd: %m");
5028
5029         return 0;
5030 }
5031
5032 int get_home_dir(char **_h) {
5033         struct passwd *p;
5034         const char *e;
5035         char *h;
5036         uid_t u;
5037
5038         assert(_h);
5039
5040         /* Take the user specified one */
5041         e = secure_getenv("HOME");
5042         if (e && path_is_absolute(e)) {
5043                 h = strdup(e);
5044                 if (!h)
5045                         return -ENOMEM;
5046
5047                 *_h = h;
5048                 return 0;
5049         }
5050
5051         /* Hardcode home directory for root to avoid NSS */
5052         u = getuid();
5053         if (u == 0) {
5054                 h = strdup("/root");
5055                 if (!h)
5056                         return -ENOMEM;
5057
5058                 *_h = h;
5059                 return 0;
5060         }
5061
5062         /* Check the database... */
5063         errno = 0;
5064         p = getpwuid(u);
5065         if (!p)
5066                 return errno > 0 ? -errno : -ESRCH;
5067
5068         if (!path_is_absolute(p->pw_dir))
5069                 return -EINVAL;
5070
5071         h = strdup(p->pw_dir);
5072         if (!h)
5073                 return -ENOMEM;
5074
5075         *_h = h;
5076         return 0;
5077 }
5078
5079 int get_shell(char **_s) {
5080         struct passwd *p;
5081         const char *e;
5082         char *s;
5083         uid_t u;
5084
5085         assert(_s);
5086
5087         /* Take the user specified one */
5088         e = getenv("SHELL");
5089         if (e) {
5090                 s = strdup(e);
5091                 if (!s)
5092                         return -ENOMEM;
5093
5094                 *_s = s;
5095                 return 0;
5096         }
5097
5098         /* Hardcode home directory for root to avoid NSS */
5099         u = getuid();
5100         if (u == 0) {
5101                 s = strdup("/bin/sh");
5102                 if (!s)
5103                         return -ENOMEM;
5104
5105                 *_s = s;
5106                 return 0;
5107         }
5108
5109         /* Check the database... */
5110         errno = 0;
5111         p = getpwuid(u);
5112         if (!p)
5113                 return errno > 0 ? -errno : -ESRCH;
5114
5115         if (!path_is_absolute(p->pw_shell))
5116                 return -EINVAL;
5117
5118         s = strdup(p->pw_shell);
5119         if (!s)
5120                 return -ENOMEM;
5121
5122         *_s = s;
5123         return 0;
5124 }
5125
5126 bool filename_is_valid(const char *p) {
5127
5128         if (isempty(p))
5129                 return false;
5130
5131         if (strchr(p, '/'))
5132                 return false;
5133
5134         if (streq(p, "."))
5135                 return false;
5136
5137         if (streq(p, ".."))
5138                 return false;
5139
5140         if (strlen(p) > FILENAME_MAX)
5141                 return false;
5142
5143         return true;
5144 }
5145
5146 bool string_is_safe(const char *p) {
5147         const char *t;
5148
5149         if (!p)
5150                 return false;
5151
5152         for (t = p; *t; t++) {
5153                 if (*t > 0 && *t < ' ')
5154                         return false;
5155
5156                 if (strchr("\\\"\'\0x7f", *t))
5157                         return false;
5158         }
5159
5160         return true;
5161 }
5162
5163 /**
5164  * Check if a string contains control characters. If 'ok' is non-NULL
5165  * it may be a string containing additional CCs to be considered OK.
5166  */
5167 bool string_has_cc(const char *p, const char *ok) {
5168         const char *t;
5169
5170         assert(p);
5171
5172         for (t = p; *t; t++) {
5173                 if (ok && strchr(ok, *t))
5174                         continue;
5175
5176                 if (*t > 0 && *t < ' ')
5177                         return true;
5178
5179                 if (*t == 127)
5180                         return true;
5181         }
5182
5183         return false;
5184 }
5185
5186 bool path_is_safe(const char *p) {
5187
5188         if (isempty(p))
5189                 return false;
5190
5191         if (streq(p, "..") || startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
5192                 return false;
5193
5194         if (strlen(p) > PATH_MAX)
5195                 return false;
5196
5197         /* The following two checks are not really dangerous, but hey, they still are confusing */
5198         if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
5199                 return false;
5200
5201         if (strstr(p, "//"))
5202                 return false;
5203
5204         return true;
5205 }
5206
5207 /* hey glibc, APIs with callbacks without a user pointer are so useless */
5208 void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
5209                  int (*compar) (const void *, const void *, void *), void *arg) {
5210         size_t l, u, idx;
5211         const void *p;
5212         int comparison;
5213
5214         l = 0;
5215         u = nmemb;
5216         while (l < u) {
5217                 idx = (l + u) / 2;
5218                 p = (void *)(((const char *) base) + (idx * size));
5219                 comparison = compar(key, p, arg);
5220                 if (comparison < 0)
5221                         u = idx;
5222                 else if (comparison > 0)
5223                         l = idx + 1;
5224                 else
5225                         return (void *)p;
5226         }
5227         return NULL;
5228 }
5229
5230 void init_gettext(void) {
5231         setlocale(LC_ALL, "");
5232         textdomain(GETTEXT_PACKAGE);
5233 }
5234
5235 bool is_locale_utf8(void) {
5236         const char *set;
5237         static int cached_answer = -1;
5238
5239         if (cached_answer >= 0)
5240                 goto out;
5241
5242         if (!setlocale(LC_ALL, "")) {
5243                 cached_answer = true;
5244                 goto out;
5245         }
5246
5247         set = nl_langinfo(CODESET);
5248         if (!set) {
5249                 cached_answer = true;
5250                 goto out;
5251         }
5252
5253         if (streq(set, "UTF-8")) {
5254                 cached_answer = true;
5255                 goto out;
5256         }
5257
5258         /* For LC_CTYPE=="C" return true, because CTYPE is effectly
5259          * unset and everything can do to UTF-8 nowadays. */
5260         set = setlocale(LC_CTYPE, NULL);
5261         if (!set) {
5262                 cached_answer = true;
5263                 goto out;
5264         }
5265
5266         /* Check result, but ignore the result if C was set
5267          * explicitly. */
5268         cached_answer =
5269                 streq(set, "C") &&
5270                 !getenv("LC_ALL") &&
5271                 !getenv("LC_CTYPE") &&
5272                 !getenv("LANG");
5273
5274 out:
5275         return (bool) cached_answer;
5276 }
5277
5278 const char *draw_special_char(DrawSpecialChar ch) {
5279         static const char *draw_table[2][_DRAW_SPECIAL_CHAR_MAX] = {
5280
5281                 /* UTF-8 */ {
5282                         [DRAW_TREE_VERTICAL]      = "\342\224\202 ",            /* │  */
5283                         [DRAW_TREE_BRANCH]        = "\342\224\234\342\224\200", /* ├─ */
5284                         [DRAW_TREE_RIGHT]         = "\342\224\224\342\224\200", /* └─ */
5285                         [DRAW_TREE_SPACE]         = "  ",                       /*    */
5286                         [DRAW_TRIANGULAR_BULLET]  = "\342\200\243",             /* ‣ */
5287                         [DRAW_BLACK_CIRCLE]       = "\342\227\217",             /* ● */
5288                         [DRAW_ARROW]              = "\342\206\222",             /* → */
5289                         [DRAW_DASH]               = "\342\200\223",             /* – */
5290                 },
5291
5292                 /* ASCII fallback */ {
5293                         [DRAW_TREE_VERTICAL]      = "| ",
5294                         [DRAW_TREE_BRANCH]        = "|-",
5295                         [DRAW_TREE_RIGHT]         = "`-",
5296                         [DRAW_TREE_SPACE]         = "  ",
5297                         [DRAW_TRIANGULAR_BULLET]  = ">",
5298                         [DRAW_BLACK_CIRCLE]       = "*",
5299                         [DRAW_ARROW]              = "->",
5300                         [DRAW_DASH]               = "-",
5301                 }
5302         };
5303
5304         return draw_table[!is_locale_utf8()][ch];
5305 }
5306
5307 char *strreplace(const char *text, const char *old_string, const char *new_string) {
5308         const char *f;
5309         char *t, *r;
5310         size_t l, old_len, new_len;
5311
5312         assert(text);
5313         assert(old_string);
5314         assert(new_string);
5315
5316         old_len = strlen(old_string);
5317         new_len = strlen(new_string);
5318
5319         l = strlen(text);
5320         r = new(char, l+1);
5321         if (!r)
5322                 return NULL;
5323
5324         f = text;
5325         t = r;
5326         while (*f) {
5327                 char *a;
5328                 size_t d, nl;
5329
5330                 if (!startswith(f, old_string)) {
5331                         *(t++) = *(f++);
5332                         continue;
5333                 }
5334
5335                 d = t - r;
5336                 nl = l - old_len + new_len;
5337                 a = realloc(r, nl + 1);
5338                 if (!a)
5339                         goto oom;
5340
5341                 l = nl;
5342                 r = a;
5343                 t = r + d;
5344
5345                 t = stpcpy(t, new_string);
5346                 f += old_len;
5347         }
5348
5349         *t = 0;
5350         return r;
5351
5352 oom:
5353         free(r);
5354         return NULL;
5355 }
5356
5357 char *strip_tab_ansi(char **ibuf, size_t *_isz) {
5358         const char *i, *begin = NULL;
5359         enum {
5360                 STATE_OTHER,
5361                 STATE_ESCAPE,
5362                 STATE_BRACKET
5363         } state = STATE_OTHER;
5364         char *obuf = NULL;
5365         size_t osz = 0, isz;
5366         FILE *f;
5367
5368         assert(ibuf);
5369         assert(*ibuf);
5370
5371         /* Strips ANSI color and replaces TABs by 8 spaces */
5372
5373         isz = _isz ? *_isz : strlen(*ibuf);
5374
5375         f = open_memstream(&obuf, &osz);
5376         if (!f)
5377                 return NULL;
5378
5379         for (i = *ibuf; i < *ibuf + isz + 1; i++) {
5380
5381                 switch (state) {
5382
5383                 case STATE_OTHER:
5384                         if (i >= *ibuf + isz) /* EOT */
5385                                 break;
5386                         else if (*i == '\x1B')
5387                                 state = STATE_ESCAPE;
5388                         else if (*i == '\t')
5389                                 fputs("        ", f);
5390                         else
5391                                 fputc(*i, f);
5392                         break;
5393
5394                 case STATE_ESCAPE:
5395                         if (i >= *ibuf + isz) { /* EOT */
5396                                 fputc('\x1B', f);
5397                                 break;
5398                         } else if (*i == '[') {
5399                                 state = STATE_BRACKET;
5400                                 begin = i + 1;
5401                         } else {
5402                                 fputc('\x1B', f);
5403                                 fputc(*i, f);
5404                                 state = STATE_OTHER;
5405                         }
5406
5407                         break;
5408
5409                 case STATE_BRACKET:
5410
5411                         if (i >= *ibuf + isz || /* EOT */
5412                             (!(*i >= '0' && *i <= '9') && *i != ';' && *i != 'm')) {
5413                                 fputc('\x1B', f);
5414                                 fputc('[', f);
5415                                 state = STATE_OTHER;
5416                                 i = begin-1;
5417                         } else if (*i == 'm')
5418                                 state = STATE_OTHER;
5419                         break;
5420                 }
5421         }
5422
5423         if (ferror(f)) {
5424                 fclose(f);
5425                 free(obuf);
5426                 return NULL;
5427         }
5428
5429         fclose(f);
5430
5431         free(*ibuf);
5432         *ibuf = obuf;
5433
5434         if (_isz)
5435                 *_isz = osz;
5436
5437         return obuf;
5438 }
5439
5440 int on_ac_power(void) {
5441         bool found_offline = false, found_online = false;
5442         _cleanup_closedir_ DIR *d = NULL;
5443
5444         d = opendir("/sys/class/power_supply");
5445         if (!d)
5446                 return errno == ENOENT ? true : -errno;
5447
5448         for (;;) {
5449                 struct dirent *de;
5450                 _cleanup_close_ int fd = -1, device = -1;
5451                 char contents[6];
5452                 ssize_t n;
5453
5454                 errno = 0;
5455                 de = readdir(d);
5456                 if (!de && errno != 0)
5457                         return -errno;
5458
5459                 if (!de)
5460                         break;
5461
5462                 if (hidden_file(de->d_name))
5463                         continue;
5464
5465                 device = openat(dirfd(d), de->d_name, O_DIRECTORY|O_RDONLY|O_CLOEXEC|O_NOCTTY);
5466                 if (device < 0) {
5467                         if (errno == ENOENT || errno == ENOTDIR)
5468                                 continue;
5469
5470                         return -errno;
5471                 }
5472
5473                 fd = openat(device, "type", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5474                 if (fd < 0) {
5475                         if (errno == ENOENT)
5476                                 continue;
5477
5478                         return -errno;
5479                 }
5480
5481                 n = read(fd, contents, sizeof(contents));
5482                 if (n < 0)
5483                         return -errno;
5484
5485                 if (n != 6 || memcmp(contents, "Mains\n", 6))
5486                         continue;
5487
5488                 safe_close(fd);
5489                 fd = openat(device, "online", O_RDONLY|O_CLOEXEC|O_NOCTTY);
5490                 if (fd < 0) {
5491                         if (errno == ENOENT)
5492                                 continue;
5493
5494                         return -errno;
5495                 }
5496
5497                 n = read(fd, contents, sizeof(contents));
5498                 if (n < 0)
5499                         return -errno;
5500
5501                 if (n != 2 || contents[1] != '\n')
5502                         return -EIO;
5503
5504                 if (contents[0] == '1') {
5505                         found_online = true;
5506                         break;
5507                 } else if (contents[0] == '0')
5508                         found_offline = true;
5509                 else
5510                         return -EIO;
5511         }
5512
5513         return found_online || !found_offline;
5514 }
5515
5516 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
5517         char **i;
5518
5519         assert(path);
5520         assert(mode);
5521         assert(_f);
5522
5523         if (!path_strv_resolve_uniq(search, root))
5524                 return -ENOMEM;
5525
5526         STRV_FOREACH(i, search) {
5527                 _cleanup_free_ char *p = NULL;
5528                 FILE *f;
5529
5530                 if (root)
5531                         p = strjoin(root, *i, "/", path, NULL);
5532                 else
5533                         p = strjoin(*i, "/", path, NULL);
5534                 if (!p)
5535                         return -ENOMEM;
5536
5537                 f = fopen(p, mode);
5538                 if (f) {
5539                         *_f = f;
5540                         return 0;
5541                 }
5542
5543                 if (errno != ENOENT)
5544                         return -errno;
5545         }
5546
5547         return -ENOENT;
5548 }
5549
5550 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
5551         _cleanup_strv_free_ char **copy = NULL;
5552
5553         assert(path);
5554         assert(mode);
5555         assert(_f);
5556
5557         if (path_is_absolute(path)) {
5558                 FILE *f;
5559
5560                 f = fopen(path, mode);
5561                 if (f) {
5562                         *_f = f;
5563                         return 0;
5564                 }
5565
5566                 return -errno;
5567         }
5568
5569         copy = strv_copy((char**) search);
5570         if (!copy)
5571                 return -ENOMEM;
5572
5573         return search_and_fopen_internal(path, mode, root, copy, _f);
5574 }
5575
5576 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
5577         _cleanup_strv_free_ char **s = NULL;
5578
5579         if (path_is_absolute(path)) {
5580                 FILE *f;
5581
5582                 f = fopen(path, mode);
5583                 if (f) {
5584                         *_f = f;
5585                         return 0;
5586                 }
5587
5588                 return -errno;
5589         }
5590
5591         s = strv_split_nulstr(search);
5592         if (!s)
5593                 return -ENOMEM;
5594
5595         return search_and_fopen_internal(path, mode, root, s, _f);
5596 }
5597
5598 char *strextend(char **x, ...) {
5599         va_list ap;
5600         size_t f, l;
5601         char *r, *p;
5602
5603         assert(x);
5604
5605         l = f = *x ? strlen(*x) : 0;
5606
5607         va_start(ap, x);
5608         for (;;) {
5609                 const char *t;
5610                 size_t n;
5611
5612                 t = va_arg(ap, const char *);
5613                 if (!t)
5614                         break;
5615
5616                 n = strlen(t);
5617                 if (n > ((size_t) -1) - l) {
5618                         va_end(ap);
5619                         return NULL;
5620                 }
5621
5622                 l += n;
5623         }
5624         va_end(ap);
5625
5626         r = realloc(*x, l+1);
5627         if (!r)
5628                 return NULL;
5629
5630         p = r + f;
5631
5632         va_start(ap, x);
5633         for (;;) {
5634                 const char *t;
5635
5636                 t = va_arg(ap, const char *);
5637                 if (!t)
5638                         break;
5639
5640                 p = stpcpy(p, t);
5641         }
5642         va_end(ap);
5643
5644         *p = 0;
5645         *x = r;
5646
5647         return r + l;
5648 }
5649
5650 char *strrep(const char *s, unsigned n) {
5651         size_t l;
5652         char *r, *p;
5653         unsigned i;
5654
5655         assert(s);
5656
5657         l = strlen(s);
5658         p = r = malloc(l * n + 1);
5659         if (!r)
5660                 return NULL;
5661
5662         for (i = 0; i < n; i++)
5663                 p = stpcpy(p, s);
5664
5665         *p = 0;
5666         return r;
5667 }
5668
5669 void* greedy_realloc(void **p, size_t *allocated, size_t need, size_t size) {
5670         size_t a, newalloc;
5671         void *q;
5672
5673         assert(p);
5674         assert(allocated);
5675
5676         if (*allocated >= need)
5677                 return *p;
5678
5679         newalloc = MAX(need * 2, 64u / size);
5680         a = newalloc * size;
5681
5682         /* check for overflows */
5683         if (a < size * need)
5684                 return NULL;
5685
5686         q = realloc(*p, a);
5687         if (!q)
5688                 return NULL;
5689
5690         *p = q;
5691         *allocated = newalloc;
5692         return q;
5693 }
5694
5695 void* greedy_realloc0(void **p, size_t *allocated, size_t need, size_t size) {
5696         size_t prev;
5697         uint8_t *q;
5698
5699         assert(p);
5700         assert(allocated);
5701
5702         prev = *allocated;
5703
5704         q = greedy_realloc(p, allocated, need, size);
5705         if (!q)
5706                 return NULL;
5707
5708         if (*allocated > prev)
5709                 memzero(q + prev * size, (*allocated - prev) * size);
5710
5711         return q;
5712 }
5713
5714 bool id128_is_valid(const char *s) {
5715         size_t i, l;
5716
5717         l = strlen(s);
5718         if (l == 32) {
5719
5720                 /* Simple formatted 128bit hex string */
5721
5722                 for (i = 0; i < l; i++) {
5723                         char c = s[i];
5724
5725                         if (!(c >= '0' && c <= '9') &&
5726                             !(c >= 'a' && c <= 'z') &&
5727                             !(c >= 'A' && c <= 'Z'))
5728                                 return false;
5729                 }
5730
5731         } else if (l == 36) {
5732
5733                 /* Formatted UUID */
5734
5735                 for (i = 0; i < l; i++) {
5736                         char c = s[i];
5737
5738                         if ((i == 8 || i == 13 || i == 18 || i == 23)) {
5739                                 if (c != '-')
5740                                         return false;
5741                         } else {
5742                                 if (!(c >= '0' && c <= '9') &&
5743                                     !(c >= 'a' && c <= 'z') &&
5744                                     !(c >= 'A' && c <= 'Z'))
5745                                         return false;
5746                         }
5747                 }
5748
5749         } else
5750                 return false;
5751
5752         return true;
5753 }
5754
5755 int split_pair(const char *s, const char *sep, char **l, char **r) {
5756         char *x, *a, *b;
5757
5758         assert(s);
5759         assert(sep);
5760         assert(l);
5761         assert(r);
5762
5763         if (isempty(sep))
5764                 return -EINVAL;
5765
5766         x = strstr(s, sep);
5767         if (!x)
5768                 return -EINVAL;
5769
5770         a = strndup(s, x - s);
5771         if (!a)
5772                 return -ENOMEM;
5773
5774         b = strdup(x + strlen(sep));
5775         if (!b) {
5776                 free(a);
5777                 return -ENOMEM;
5778         }
5779
5780         *l = a;
5781         *r = b;
5782
5783         return 0;
5784 }
5785
5786 int shall_restore_state(void) {
5787         _cleanup_free_ char *value = NULL;
5788         int r;
5789
5790         r = get_proc_cmdline_key("systemd.restore_state=", &value);
5791         if (r < 0)
5792                 return r;
5793         if (r == 0)
5794                 return true;
5795
5796         return parse_boolean(value) != 0;
5797 }
5798
5799 int proc_cmdline(char **ret) {
5800         assert(ret);
5801
5802         if (detect_container(NULL) > 0)
5803                 return get_process_cmdline(1, 0, false, ret);
5804         else
5805                 return read_one_line_file("/proc/cmdline", ret);
5806 }
5807
5808 int parse_proc_cmdline(int (*parse_item)(const char *key, const char *value)) {
5809         _cleanup_free_ char *line = NULL;
5810         const char *p;
5811         int r;
5812
5813         assert(parse_item);
5814
5815         r = proc_cmdline(&line);
5816         if (r < 0)
5817                 return r;
5818
5819         p = line;
5820         for (;;) {
5821                 _cleanup_free_ char *word = NULL;
5822                 char *value = NULL;
5823
5824                 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
5825                 if (r < 0)
5826                         return r;
5827                 if (r == 0)
5828                         break;
5829
5830                 /* Filter out arguments that are intended only for the
5831                  * initrd */
5832                 if (!in_initrd() && startswith(word, "rd."))
5833                         continue;
5834
5835                 value = strchr(word, '=');
5836                 if (value)
5837                         *(value++) = 0;
5838
5839                 r = parse_item(word, value);
5840                 if (r < 0)
5841                         return r;
5842         }
5843
5844         return 0;
5845 }
5846
5847 int get_proc_cmdline_key(const char *key, char **value) {
5848         _cleanup_free_ char *line = NULL, *ret = NULL;
5849         bool found = false;
5850         const char *p;
5851         int r;
5852
5853         assert(key);
5854
5855         r = proc_cmdline(&line);
5856         if (r < 0)
5857                 return r;
5858
5859         p = line;
5860         for (;;) {
5861                 _cleanup_free_ char *word = NULL;
5862                 const char *e;
5863
5864                 r = unquote_first_word(&p, &word, UNQUOTE_RELAX);
5865                 if (r < 0)
5866                         return r;
5867                 if (r == 0)
5868                         break;
5869
5870                 /* Filter out arguments that are intended only for the
5871                  * initrd */
5872                 if (!in_initrd() && startswith(word, "rd."))
5873                         continue;
5874
5875                 if (value) {
5876                         e = startswith(word, key);
5877                         if (!e)
5878                                 continue;
5879
5880                         r = free_and_strdup(&ret, e);
5881                         if (r < 0)
5882                                 return r;
5883
5884                         found = true;
5885                 } else {
5886                         if (streq(word, key))
5887                                 found = true;
5888                 }
5889         }
5890
5891         if (value) {
5892                 *value = ret;
5893                 ret = NULL;
5894         }
5895
5896         return found;
5897
5898 }
5899
5900 int container_get_leader(const char *machine, pid_t *pid) {
5901         _cleanup_free_ char *s = NULL, *class = NULL;
5902         const char *p;
5903         pid_t leader;
5904         int r;
5905
5906         assert(machine);
5907         assert(pid);
5908
5909         p = strjoina("/run/systemd/machines/", machine);
5910         r = parse_env_file(p, NEWLINE, "LEADER", &s, "CLASS", &class, NULL);
5911         if (r == -ENOENT)
5912                 return -EHOSTDOWN;
5913         if (r < 0)
5914                 return r;
5915         if (!s)
5916                 return -EIO;
5917
5918         if (!streq_ptr(class, "container"))
5919                 return -EIO;
5920
5921         r = parse_pid(s, &leader);
5922         if (r < 0)
5923                 return r;
5924         if (leader <= 1)
5925                 return -EIO;
5926
5927         *pid = leader;
5928         return 0;
5929 }
5930
5931 int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *root_fd) {
5932         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, netnsfd = -1;
5933         int rfd = -1;
5934
5935         assert(pid >= 0);
5936
5937         if (mntns_fd) {
5938                 const char *mntns;
5939
5940                 mntns = procfs_file_alloca(pid, "ns/mnt");
5941                 mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
5942                 if (mntnsfd < 0)
5943                         return -errno;
5944         }
5945
5946         if (pidns_fd) {
5947                 const char *pidns;
5948
5949                 pidns = procfs_file_alloca(pid, "ns/pid");
5950                 pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
5951                 if (pidnsfd < 0)
5952                         return -errno;
5953         }
5954
5955         if (netns_fd) {
5956                 const char *netns;
5957
5958                 netns = procfs_file_alloca(pid, "ns/net");
5959                 netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
5960                 if (netnsfd < 0)
5961                         return -errno;
5962         }
5963
5964         if (root_fd) {
5965                 const char *root;
5966
5967                 root = procfs_file_alloca(pid, "root");
5968                 rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
5969                 if (rfd < 0)
5970                         return -errno;
5971         }
5972
5973         if (pidns_fd)
5974                 *pidns_fd = pidnsfd;
5975
5976         if (mntns_fd)
5977                 *mntns_fd = mntnsfd;
5978
5979         if (netns_fd)
5980                 *netns_fd = netnsfd;
5981
5982         if (root_fd)
5983                 *root_fd = rfd;
5984
5985         pidnsfd = mntnsfd = netnsfd = -1;
5986
5987         return 0;
5988 }
5989
5990 int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int root_fd) {
5991
5992         if (pidns_fd >= 0)
5993                 if (setns(pidns_fd, CLONE_NEWPID) < 0)
5994                         return -errno;
5995
5996         if (mntns_fd >= 0)
5997                 if (setns(mntns_fd, CLONE_NEWNS) < 0)
5998                         return -errno;
5999
6000         if (netns_fd >= 0)
6001                 if (setns(netns_fd, CLONE_NEWNET) < 0)
6002                         return -errno;
6003
6004         if (root_fd >= 0) {
6005                 if (fchdir(root_fd) < 0)
6006                         return -errno;
6007
6008                 if (chroot(".") < 0)
6009                         return -errno;
6010         }
6011
6012         if (setresgid(0, 0, 0) < 0)
6013                 return -errno;
6014
6015         if (setgroups(0, NULL) < 0)
6016                 return -errno;
6017
6018         if (setresuid(0, 0, 0) < 0)
6019                 return -errno;
6020
6021         return 0;
6022 }
6023
6024 int getpeercred(int fd, struct ucred *ucred) {
6025         socklen_t n = sizeof(struct ucred);
6026         struct ucred u;
6027         int r;
6028
6029         assert(fd >= 0);
6030         assert(ucred);
6031
6032         r = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &u, &n);
6033         if (r < 0)
6034                 return -errno;
6035
6036         if (n != sizeof(struct ucred))
6037                 return -EIO;
6038
6039         /* Check if the data is actually useful and not suppressed due
6040          * to namespacing issues */
6041         if (u.pid <= 0)
6042                 return -ENODATA;
6043         if (u.uid == UID_INVALID)
6044                 return -ENODATA;
6045         if (u.gid == GID_INVALID)
6046                 return -ENODATA;
6047
6048         *ucred = u;
6049         return 0;
6050 }
6051
6052 int getpeersec(int fd, char **ret) {
6053         socklen_t n = 64;
6054         char *s;
6055         int r;
6056
6057         assert(fd >= 0);
6058         assert(ret);
6059
6060         s = new0(char, n);
6061         if (!s)
6062                 return -ENOMEM;
6063
6064         r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6065         if (r < 0) {
6066                 free(s);
6067
6068                 if (errno != ERANGE)
6069                         return -errno;
6070
6071                 s = new0(char, n);
6072                 if (!s)
6073                         return -ENOMEM;
6074
6075                 r = getsockopt(fd, SOL_SOCKET, SO_PEERSEC, s, &n);
6076                 if (r < 0) {
6077                         free(s);
6078                         return -errno;
6079                 }
6080         }
6081
6082         if (isempty(s)) {
6083                 free(s);
6084                 return -EOPNOTSUPP;
6085         }
6086
6087         *ret = s;
6088         return 0;
6089 }
6090
6091 /* This is much like like mkostemp() but is subject to umask(). */
6092 int mkostemp_safe(char *pattern, int flags) {
6093         _cleanup_umask_ mode_t u;
6094         int fd;
6095
6096         assert(pattern);
6097
6098         u = umask(077);
6099
6100         fd = mkostemp(pattern, flags);
6101         if (fd < 0)
6102                 return -errno;
6103
6104         return fd;
6105 }
6106
6107 int open_tmpfile(const char *path, int flags) {
6108         char *p;
6109         int fd;
6110
6111         assert(path);
6112
6113 #ifdef O_TMPFILE
6114         /* Try O_TMPFILE first, if it is supported */
6115         fd = open(path, flags|O_TMPFILE, S_IRUSR|S_IWUSR);
6116         if (fd >= 0)
6117                 return fd;
6118 #endif
6119
6120         /* Fall back to unguessable name + unlinking */
6121         p = strjoina(path, "/systemd-tmp-XXXXXX");
6122
6123         fd = mkostemp_safe(p, flags);
6124         if (fd < 0)
6125                 return fd;
6126
6127         unlink(p);
6128         return fd;
6129 }
6130
6131 int fd_warn_permissions(const char *path, int fd) {
6132         struct stat st;
6133
6134         if (fstat(fd, &st) < 0)
6135                 return -errno;
6136
6137         if (st.st_mode & 0111)
6138                 log_warning("Configuration file %s is marked executable. Please remove executable permission bits. Proceeding anyway.", path);
6139
6140         if (st.st_mode & 0002)
6141                 log_warning("Configuration file %s is marked world-writable. Please remove world writability permission bits. Proceeding anyway.", path);
6142
6143         if (getpid() == 1 && (st.st_mode & 0044) != 0044)
6144                 log_warning("Configuration file %s is marked world-inaccessible. This has no effect as configuration data is accessible via APIs without restrictions. Proceeding anyway.", path);
6145
6146         return 0;
6147 }
6148
6149 unsigned long personality_from_string(const char *p) {
6150
6151         /* Parse a personality specifier. We introduce our own
6152          * identifiers that indicate specific ABIs, rather than just
6153          * hints regarding the register size, since we want to keep
6154          * things open for multiple locally supported ABIs for the
6155          * same register size. We try to reuse the ABI identifiers
6156          * used by libseccomp. */
6157
6158 #if defined(__x86_64__)
6159
6160         if (streq(p, "x86"))
6161                 return PER_LINUX32;
6162
6163         if (streq(p, "x86-64"))
6164                 return PER_LINUX;
6165
6166 #elif defined(__i386__)
6167
6168         if (streq(p, "x86"))
6169                 return PER_LINUX;
6170 #endif
6171
6172         /* personality(7) documents that 0xffffffffUL is used for
6173          * querying the current personality, hence let's use that here
6174          * as error indicator. */
6175         return 0xffffffffUL;
6176 }
6177
6178 const char* personality_to_string(unsigned long p) {
6179
6180 #if defined(__x86_64__)
6181
6182         if (p == PER_LINUX32)
6183                 return "x86";
6184
6185         if (p == PER_LINUX)
6186                 return "x86-64";
6187
6188 #elif defined(__i386__)
6189
6190         if (p == PER_LINUX)
6191                 return "x86";
6192 #endif
6193
6194         return NULL;
6195 }
6196
6197 uint64_t physical_memory(void) {
6198         long mem;
6199
6200         /* We return this as uint64_t in case we are running as 32bit
6201          * process on a 64bit kernel with huge amounts of memory */
6202
6203         mem = sysconf(_SC_PHYS_PAGES);
6204         assert(mem > 0);
6205
6206         return (uint64_t) mem * (uint64_t) page_size();
6207 }
6208
6209 void hexdump(FILE *f, const void *p, size_t s) {
6210         const uint8_t *b = p;
6211         unsigned n = 0;
6212
6213         assert(s == 0 || b);
6214
6215         while (s > 0) {
6216                 size_t i;
6217
6218                 fprintf(f, "%04x  ", n);
6219
6220                 for (i = 0; i < 16; i++) {
6221
6222                         if (i >= s)
6223                                 fputs("   ", f);
6224                         else
6225                                 fprintf(f, "%02x ", b[i]);
6226
6227                         if (i == 7)
6228                                 fputc(' ', f);
6229                 }
6230
6231                 fputc(' ', f);
6232
6233                 for (i = 0; i < 16; i++) {
6234
6235                         if (i >= s)
6236                                 fputc(' ', f);
6237                         else
6238                                 fputc(isprint(b[i]) ? (char) b[i] : '.', f);
6239                 }
6240
6241                 fputc('\n', f);
6242
6243                 if (s < 16)
6244                         break;
6245
6246                 n += 16;
6247                 b += 16;
6248                 s -= 16;
6249         }
6250 }
6251
6252 int update_reboot_param_file(const char *param) {
6253         int r = 0;
6254
6255         if (param) {
6256
6257                 r = write_string_file(REBOOT_PARAM_FILE, param);
6258                 if (r < 0)
6259                         log_error("Failed to write reboot param to "
6260                                   REBOOT_PARAM_FILE": %s", strerror(-r));
6261         } else
6262                 unlink(REBOOT_PARAM_FILE);
6263
6264         return r;
6265 }
6266
6267 int umount_recursive(const char *prefix, int flags) {
6268         bool again;
6269         int n = 0, r;
6270
6271         /* Try to umount everything recursively below a
6272          * directory. Also, take care of stacked mounts, and keep
6273          * unmounting them until they are gone. */
6274
6275         do {
6276                 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6277
6278                 again = false;
6279                 r = 0;
6280
6281                 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6282                 if (!proc_self_mountinfo)
6283                         return -errno;
6284
6285                 for (;;) {
6286                         _cleanup_free_ char *path = NULL, *p = NULL;
6287                         int k;
6288
6289                         k = fscanf(proc_self_mountinfo,
6290                                    "%*s "       /* (1) mount id */
6291                                    "%*s "       /* (2) parent id */
6292                                    "%*s "       /* (3) major:minor */
6293                                    "%*s "       /* (4) root */
6294                                    "%ms "       /* (5) mount point */
6295                                    "%*s"        /* (6) mount options */
6296                                    "%*[^-]"     /* (7) optional fields */
6297                                    "- "         /* (8) separator */
6298                                    "%*s "       /* (9) file system type */
6299                                    "%*s"        /* (10) mount source */
6300                                    "%*s"        /* (11) mount options 2 */
6301                                    "%*[^\n]",   /* some rubbish at the end */
6302                                    &path);
6303                         if (k != 1) {
6304                                 if (k == EOF)
6305                                         break;
6306
6307                                 continue;
6308                         }
6309
6310                         r = cunescape(path, UNESCAPE_RELAX, &p);
6311                         if (r < 0)
6312                                 return r;
6313
6314                         if (!path_startswith(p, prefix))
6315                                 continue;
6316
6317                         if (umount2(p, flags) < 0) {
6318                                 r = -errno;
6319                                 continue;
6320                         }
6321
6322                         again = true;
6323                         n++;
6324
6325                         break;
6326                 }
6327
6328         } while (again);
6329
6330         return r ? r : n;
6331 }
6332
6333 static int get_mount_flags(const char *path, unsigned long *flags) {
6334         struct statvfs buf;
6335
6336         if (statvfs(path, &buf) < 0)
6337                 return -errno;
6338         *flags = buf.f_flag;
6339         return 0;
6340 }
6341
6342 int bind_remount_recursive(const char *prefix, bool ro) {
6343         _cleanup_set_free_free_ Set *done = NULL;
6344         _cleanup_free_ char *cleaned = NULL;
6345         int r;
6346
6347         /* Recursively remount a directory (and all its submounts)
6348          * read-only or read-write. If the directory is already
6349          * mounted, we reuse the mount and simply mark it
6350          * MS_BIND|MS_RDONLY (or remove the MS_RDONLY for read-write
6351          * operation). If it isn't we first make it one. Afterwards we
6352          * apply MS_BIND|MS_RDONLY (or remove MS_RDONLY) to all
6353          * submounts we can access, too. When mounts are stacked on
6354          * the same mount point we only care for each individual
6355          * "top-level" mount on each point, as we cannot
6356          * influence/access the underlying mounts anyway. We do not
6357          * have any effect on future submounts that might get
6358          * propagated, they migt be writable. This includes future
6359          * submounts that have been triggered via autofs. */
6360
6361         cleaned = strdup(prefix);
6362         if (!cleaned)
6363                 return -ENOMEM;
6364
6365         path_kill_slashes(cleaned);
6366
6367         done = set_new(&string_hash_ops);
6368         if (!done)
6369                 return -ENOMEM;
6370
6371         for (;;) {
6372                 _cleanup_fclose_ FILE *proc_self_mountinfo = NULL;
6373                 _cleanup_set_free_free_ Set *todo = NULL;
6374                 bool top_autofs = false;
6375                 char *x;
6376                 unsigned long orig_flags;
6377
6378                 todo = set_new(&string_hash_ops);
6379                 if (!todo)
6380                         return -ENOMEM;
6381
6382                 proc_self_mountinfo = fopen("/proc/self/mountinfo", "re");
6383                 if (!proc_self_mountinfo)
6384                         return -errno;
6385
6386                 for (;;) {
6387                         _cleanup_free_ char *path = NULL, *p = NULL, *type = NULL;
6388                         int k;
6389
6390                         k = fscanf(proc_self_mountinfo,
6391                                    "%*s "       /* (1) mount id */
6392                                    "%*s "       /* (2) parent id */
6393                                    "%*s "       /* (3) major:minor */
6394                                    "%*s "       /* (4) root */
6395                                    "%ms "       /* (5) mount point */
6396                                    "%*s"        /* (6) mount options (superblock) */
6397                                    "%*[^-]"     /* (7) optional fields */
6398                                    "- "         /* (8) separator */
6399                                    "%ms "       /* (9) file system type */
6400                                    "%*s"        /* (10) mount source */
6401                                    "%*s"        /* (11) mount options (bind mount) */
6402                                    "%*[^\n]",   /* some rubbish at the end */
6403                                    &path,
6404                                    &type);
6405                         if (k != 2) {
6406                                 if (k == EOF)
6407                                         break;
6408
6409                                 continue;
6410                         }
6411
6412                         r = cunescape(path, UNESCAPE_RELAX, &p);
6413                         if (r < 0)
6414                                 return r;
6415
6416                         /* Let's ignore autofs mounts.  If they aren't
6417                          * triggered yet, we want to avoid triggering
6418                          * them, as we don't make any guarantees for
6419                          * future submounts anyway.  If they are
6420                          * already triggered, then we will find
6421                          * another entry for this. */
6422                         if (streq(type, "autofs")) {
6423                                 top_autofs = top_autofs || path_equal(cleaned, p);
6424                                 continue;
6425                         }
6426
6427                         if (path_startswith(p, cleaned) &&
6428                             !set_contains(done, p)) {
6429
6430                                 r = set_consume(todo, p);
6431                                 p = NULL;
6432
6433                                 if (r == -EEXIST)
6434                                         continue;
6435                                 if (r < 0)
6436                                         return r;
6437                         }
6438                 }
6439
6440                 /* If we have no submounts to process anymore and if
6441                  * the root is either already done, or an autofs, we
6442                  * are done */
6443                 if (set_isempty(todo) &&
6444                     (top_autofs || set_contains(done, cleaned)))
6445                         return 0;
6446
6447                 if (!set_contains(done, cleaned) &&
6448                     !set_contains(todo, cleaned)) {
6449                         /* The prefix directory itself is not yet a
6450                          * mount, make it one. */
6451                         if (mount(cleaned, cleaned, NULL, MS_BIND|MS_REC, NULL) < 0)
6452                                 return -errno;
6453
6454                         orig_flags = 0;
6455                         (void) get_mount_flags(cleaned, &orig_flags);
6456                         orig_flags &= ~MS_RDONLY;
6457
6458                         if (mount(NULL, prefix, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0)
6459                                 return -errno;
6460
6461                         x = strdup(cleaned);
6462                         if (!x)
6463                                 return -ENOMEM;
6464
6465                         r = set_consume(done, x);
6466                         if (r < 0)
6467                                 return r;
6468                 }
6469
6470                 while ((x = set_steal_first(todo))) {
6471
6472                         r = set_consume(done, x);
6473                         if (r == -EEXIST)
6474                                 continue;
6475                         if (r < 0)
6476                                 return r;
6477
6478                         /* Try to reuse the original flag set, but
6479                          * don't care for errors, in case of
6480                          * obstructed mounts */
6481                         orig_flags = 0;
6482                         (void) get_mount_flags(x, &orig_flags);
6483                         orig_flags &= ~MS_RDONLY;
6484
6485                         if (mount(NULL, x, NULL, orig_flags|MS_BIND|MS_REMOUNT|(ro ? MS_RDONLY : 0), NULL) < 0) {
6486
6487                                 /* Deal with mount points that are
6488                                  * obstructed by a later mount */
6489
6490                                 if (errno != ENOENT)
6491                                         return -errno;
6492                         }
6493
6494                 }
6495         }
6496 }
6497
6498 int fflush_and_check(FILE *f) {
6499         assert(f);
6500
6501         errno = 0;
6502         fflush(f);
6503
6504         if (ferror(f))
6505                 return errno ? -errno : -EIO;
6506
6507         return 0;
6508 }
6509
6510 int tempfn_xxxxxx(const char *p, char **ret) {
6511         const char *fn;
6512         char *t;
6513
6514         assert(p);
6515         assert(ret);
6516
6517         /*
6518          * Turns this:
6519          *         /foo/bar/waldo
6520          *
6521          * Into this:
6522          *         /foo/bar/.#waldoXXXXXX
6523          */
6524
6525         fn = basename(p);
6526         if (!filename_is_valid(fn))
6527                 return -EINVAL;
6528
6529         t = new(char, strlen(p) + 2 + 6 + 1);
6530         if (!t)
6531                 return -ENOMEM;
6532
6533         strcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), "XXXXXX");
6534
6535         *ret = path_kill_slashes(t);
6536         return 0;
6537 }
6538
6539 int tempfn_random(const char *p, char **ret) {
6540         const char *fn;
6541         char *t, *x;
6542         uint64_t u;
6543         unsigned i;
6544
6545         assert(p);
6546         assert(ret);
6547
6548         /*
6549          * Turns this:
6550          *         /foo/bar/waldo
6551          *
6552          * Into this:
6553          *         /foo/bar/.#waldobaa2a261115984a9
6554          */
6555
6556         fn = basename(p);
6557         if (!filename_is_valid(fn))
6558                 return -EINVAL;
6559
6560         t = new(char, strlen(p) + 2 + 16 + 1);
6561         if (!t)
6562                 return -ENOMEM;
6563
6564         x = stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn);
6565
6566         u = random_u64();
6567         for (i = 0; i < 16; i++) {
6568                 *(x++) = hexchar(u & 0xF);
6569                 u >>= 4;
6570         }
6571
6572         *x = 0;
6573
6574         *ret = path_kill_slashes(t);
6575         return 0;
6576 }
6577
6578 int tempfn_random_child(const char *p, char **ret) {
6579         char *t, *x;
6580         uint64_t u;
6581         unsigned i;
6582
6583         assert(p);
6584         assert(ret);
6585
6586         /* Turns this:
6587          *         /foo/bar/waldo
6588          * Into this:
6589          *         /foo/bar/waldo/.#3c2b6219aa75d7d0
6590          */
6591
6592         t = new(char, strlen(p) + 3 + 16 + 1);
6593         if (!t)
6594                 return -ENOMEM;
6595
6596         x = stpcpy(stpcpy(t, p), "/.#");
6597
6598         u = random_u64();
6599         for (i = 0; i < 16; i++) {
6600                 *(x++) = hexchar(u & 0xF);
6601                 u >>= 4;
6602         }
6603
6604         *x = 0;
6605
6606         *ret = path_kill_slashes(t);
6607         return 0;
6608 }
6609
6610 /* make sure the hostname is not "localhost" */
6611 bool is_localhost(const char *hostname) {
6612         assert(hostname);
6613
6614         /* This tries to identify local host and domain names
6615          * described in RFC6761 plus the redhatism of .localdomain */
6616
6617         return streq(hostname, "localhost") ||
6618                streq(hostname, "localhost.") ||
6619                streq(hostname, "localdomain.") ||
6620                streq(hostname, "localdomain") ||
6621                endswith(hostname, ".localhost") ||
6622                endswith(hostname, ".localhost.") ||
6623                endswith(hostname, ".localdomain") ||
6624                endswith(hostname, ".localdomain.");
6625 }
6626
6627 int take_password_lock(const char *root) {
6628
6629         struct flock flock = {
6630                 .l_type = F_WRLCK,
6631                 .l_whence = SEEK_SET,
6632                 .l_start = 0,
6633                 .l_len = 0,
6634         };
6635
6636         const char *path;
6637         int fd, r;
6638
6639         /* This is roughly the same as lckpwdf(), but not as awful. We
6640          * don't want to use alarm() and signals, hence we implement
6641          * our own trivial version of this.
6642          *
6643          * Note that shadow-utils also takes per-database locks in
6644          * addition to lckpwdf(). However, we don't given that they
6645          * are redundant as they they invoke lckpwdf() first and keep
6646          * it during everything they do. The per-database locks are
6647          * awfully racy, and thus we just won't do them. */
6648
6649         if (root)
6650                 path = strjoina(root, "/etc/.pwd.lock");
6651         else
6652                 path = "/etc/.pwd.lock";
6653
6654         fd = open(path, O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW, 0600);
6655         if (fd < 0)
6656                 return -errno;
6657
6658         r = fcntl(fd, F_SETLKW, &flock);
6659         if (r < 0) {
6660                 safe_close(fd);
6661                 return -errno;
6662         }
6663
6664         return fd;
6665 }
6666
6667 int is_symlink(const char *path) {
6668         struct stat info;
6669
6670         if (lstat(path, &info) < 0)
6671                 return -errno;
6672
6673         return !!S_ISLNK(info.st_mode);
6674 }
6675
6676 int is_dir(const char* path, bool follow) {
6677         struct stat st;
6678         int r;
6679
6680         if (follow)
6681                 r = stat(path, &st);
6682         else
6683                 r = lstat(path, &st);
6684         if (r < 0)
6685                 return -errno;
6686
6687         return !!S_ISDIR(st.st_mode);
6688 }
6689
6690 int unquote_first_word(const char **p, char **ret, UnquoteFlags flags) {
6691         _cleanup_free_ char *s = NULL;
6692         size_t allocated = 0, sz = 0;
6693         int r;
6694
6695         enum {
6696                 START,
6697                 VALUE,
6698                 VALUE_ESCAPE,
6699                 SINGLE_QUOTE,
6700                 SINGLE_QUOTE_ESCAPE,
6701                 DOUBLE_QUOTE,
6702                 DOUBLE_QUOTE_ESCAPE,
6703                 SPACE,
6704         } state = START;
6705
6706         assert(p);
6707         assert(*p);
6708         assert(ret);
6709
6710         /* Parses the first word of a string, and returns it in
6711          * *ret. Removes all quotes in the process. When parsing fails
6712          * (because of an uneven number of quotes or similar), leaves
6713          * the pointer *p at the first invalid character. */
6714
6715         for (;;) {
6716                 char c = **p;
6717
6718                 switch (state) {
6719
6720                 case START:
6721                         if (c == 0)
6722                                 goto finish;
6723                         else if (strchr(WHITESPACE, c))
6724                                 break;
6725
6726                         state = VALUE;
6727                         /* fallthrough */
6728
6729                 case VALUE:
6730                         if (c == 0)
6731                                 goto finish;
6732                         else if (c == '\'')
6733                                 state = SINGLE_QUOTE;
6734                         else if (c == '\\')
6735                                 state = VALUE_ESCAPE;
6736                         else if (c == '\"')
6737                                 state = DOUBLE_QUOTE;
6738                         else if (strchr(WHITESPACE, c))
6739                                 state = SPACE;
6740                         else {
6741                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
6742                                         return -ENOMEM;
6743
6744                                 s[sz++] = c;
6745                         }
6746
6747                         break;
6748
6749                 case VALUE_ESCAPE:
6750                         if (c == 0) {
6751                                 if (flags & UNQUOTE_RELAX)
6752                                         goto finish;
6753                                 return -EINVAL;
6754                         }
6755
6756                         if (!GREEDY_REALLOC(s, allocated, sz+7))
6757                                 return -ENOMEM;
6758
6759                         if (flags & UNQUOTE_CUNESCAPE) {
6760                                 uint32_t u;
6761
6762                                 r = cunescape_one(*p, (size_t) -1, &c, &u);
6763                                 if (r < 0)
6764                                         return -EINVAL;
6765
6766                                 (*p) += r - 1;
6767
6768                                 if (c != 0)
6769                                         s[sz++] = c; /* normal explicit char */
6770                                 else
6771                                         sz += utf8_encode_unichar(s + sz, u); /* unicode chars we'll encode as utf8 */
6772                         } else
6773                                 s[sz++] = c;
6774
6775                         state = VALUE;
6776                         break;
6777
6778                 case SINGLE_QUOTE:
6779                         if (c == 0) {
6780                                 if (flags & UNQUOTE_RELAX)
6781                                         goto finish;
6782                                 return -EINVAL;
6783                         } else if (c == '\'')
6784                                 state = VALUE;
6785                         else if (c == '\\')
6786                                 state = SINGLE_QUOTE_ESCAPE;
6787                         else {
6788                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
6789                                         return -ENOMEM;
6790
6791                                 s[sz++] = c;
6792                         }
6793
6794                         break;
6795
6796                 case SINGLE_QUOTE_ESCAPE:
6797                         if (c == 0) {
6798                                 if (flags & UNQUOTE_RELAX)
6799                                         goto finish;
6800                                 return -EINVAL;
6801                         }
6802
6803                         if (!GREEDY_REALLOC(s, allocated, sz+7))
6804                                 return -ENOMEM;
6805
6806                         if (flags & UNQUOTE_CUNESCAPE) {
6807                                 uint32_t u;
6808
6809                                 r = cunescape_one(*p, (size_t) -1, &c, &u);
6810                                 if (r < 0)
6811                                         return -EINVAL;
6812
6813                                 (*p) += r - 1;
6814
6815                                 if (c != 0)
6816                                         s[sz++] = c;
6817                                 else
6818                                         sz += utf8_encode_unichar(s + sz, u);
6819                         } else
6820                                 s[sz++] = c;
6821
6822                         state = SINGLE_QUOTE;
6823                         break;
6824
6825                 case DOUBLE_QUOTE:
6826                         if (c == 0)
6827                                 return -EINVAL;
6828                         else if (c == '\"')
6829                                 state = VALUE;
6830                         else if (c == '\\')
6831                                 state = DOUBLE_QUOTE_ESCAPE;
6832                         else {
6833                                 if (!GREEDY_REALLOC(s, allocated, sz+2))
6834                                         return -ENOMEM;
6835
6836                                 s[sz++] = c;
6837                         }
6838
6839                         break;
6840
6841                 case DOUBLE_QUOTE_ESCAPE:
6842                         if (c == 0) {
6843                                 if (flags & UNQUOTE_RELAX)
6844                                         goto finish;
6845                                 return -EINVAL;
6846                         }
6847
6848                         if (!GREEDY_REALLOC(s, allocated, sz+7))
6849                                 return -ENOMEM;
6850
6851                         if (flags & UNQUOTE_CUNESCAPE) {
6852                                 uint32_t u;
6853
6854                                 r = cunescape_one(*p, (size_t) -1, &c, &u);
6855                                 if (r < 0)
6856                                         return -EINVAL;
6857
6858                                 (*p) += r - 1;
6859
6860                                 if (c != 0)
6861                                         s[sz++] = c;
6862                                 else
6863                                         sz += utf8_encode_unichar(s + sz, u);
6864                         } else
6865                                 s[sz++] = c;
6866
6867                         state = DOUBLE_QUOTE;
6868                         break;
6869
6870                 case SPACE:
6871                         if (c == 0)
6872                                 goto finish;
6873                         if (!strchr(WHITESPACE, c))
6874                                 goto finish;
6875
6876                         break;
6877                 }
6878
6879                 (*p) ++;
6880         }
6881
6882 finish:
6883         if (!s) {
6884                 *ret = NULL;
6885                 return 0;
6886         }
6887
6888         s[sz] = 0;
6889         *ret = s;
6890         s = NULL;
6891
6892         return 1;
6893 }
6894
6895 int unquote_many_words(const char **p, UnquoteFlags flags, ...) {
6896         va_list ap;
6897         char **l;
6898         int n = 0, i, c, r;
6899
6900         /* Parses a number of words from a string, stripping any
6901          * quotes if necessary. */
6902
6903         assert(p);
6904
6905         /* Count how many words are expected */
6906         va_start(ap, flags);
6907         for (;;) {
6908                 if (!va_arg(ap, char **))
6909                         break;
6910                 n++;
6911         }
6912         va_end(ap);
6913
6914         if (n <= 0)
6915                 return 0;
6916
6917         /* Read all words into a temporary array */
6918         l = newa0(char*, n);
6919         for (c = 0; c < n; c++) {
6920
6921                 r = unquote_first_word(p, &l[c], flags);
6922                 if (r < 0) {
6923                         int j;
6924
6925                         for (j = 0; j < c; j++)
6926                                 free(l[j]);
6927
6928                         return r;
6929                 }
6930
6931                 if (r == 0)
6932                         break;
6933         }
6934
6935         /* If we managed to parse all words, return them in the passed
6936          * in parameters */
6937         va_start(ap, flags);
6938         for (i = 0; i < n; i++) {
6939                 char **v;
6940
6941                 v = va_arg(ap, char **);
6942                 assert(v);
6943
6944                 *v = l[i];
6945         }
6946         va_end(ap);
6947
6948         return c;
6949 }
6950
6951 int free_and_strdup(char **p, const char *s) {
6952         char *t;
6953
6954         assert(p);
6955
6956         /* Replaces a string pointer with an strdup()ed new string,
6957          * possibly freeing the old one. */
6958
6959         if (s) {
6960                 t = strdup(s);
6961                 if (!t)
6962                         return -ENOMEM;
6963         } else
6964                 t = NULL;
6965
6966         free(*p);
6967         *p = t;
6968
6969         return 0;
6970 }
6971
6972 int sethostname_idempotent(const char *s) {
6973         int r;
6974         char buf[HOST_NAME_MAX + 1] = {};
6975
6976         assert(s);
6977
6978         r = gethostname(buf, sizeof(buf));
6979         if (r < 0)
6980                 return -errno;
6981
6982         if (streq(buf, s))
6983                 return 0;
6984
6985         r = sethostname(s, strlen(s));
6986         if (r < 0)
6987                 return -errno;
6988
6989         return 1;
6990 }
6991
6992 int ptsname_malloc(int fd, char **ret) {
6993         size_t l = 100;
6994
6995         assert(fd >= 0);
6996         assert(ret);
6997
6998         for (;;) {
6999                 char *c;
7000
7001                 c = new(char, l);
7002                 if (!c)
7003                         return -ENOMEM;
7004
7005                 if (ptsname_r(fd, c, l) == 0) {
7006                         *ret = c;
7007                         return 0;
7008                 }
7009                 if (errno != ERANGE) {
7010                         free(c);
7011                         return -errno;
7012                 }
7013
7014                 free(c);
7015                 l *= 2;
7016         }
7017 }
7018
7019 int openpt_in_namespace(pid_t pid, int flags) {
7020         _cleanup_close_ int pidnsfd = -1, mntnsfd = -1, rootfd = -1;
7021         _cleanup_close_pair_ int pair[2] = { -1, -1 };
7022         union {
7023                 struct cmsghdr cmsghdr;
7024                 uint8_t buf[CMSG_SPACE(sizeof(int))];
7025         } control = {};
7026         struct msghdr mh = {
7027                 .msg_control = &control,
7028                 .msg_controllen = sizeof(control),
7029         };
7030         struct cmsghdr *cmsg;
7031         siginfo_t si;
7032         pid_t child;
7033         int r;
7034
7035         assert(pid > 0);
7036
7037         r = namespace_open(pid, &pidnsfd, &mntnsfd, NULL, &rootfd);
7038         if (r < 0)
7039                 return r;
7040
7041         if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pair) < 0)
7042                 return -errno;
7043
7044         child = fork();
7045         if (child < 0)
7046                 return -errno;
7047
7048         if (child == 0) {
7049                 int master;
7050
7051                 pair[0] = safe_close(pair[0]);
7052
7053                 r = namespace_enter(pidnsfd, mntnsfd, -1, rootfd);
7054                 if (r < 0)
7055                         _exit(EXIT_FAILURE);
7056
7057                 master = posix_openpt(flags);
7058                 if (master < 0)
7059                         _exit(EXIT_FAILURE);
7060
7061                 cmsg = CMSG_FIRSTHDR(&mh);
7062                 cmsg->cmsg_level = SOL_SOCKET;
7063                 cmsg->cmsg_type = SCM_RIGHTS;
7064                 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
7065                 memcpy(CMSG_DATA(cmsg), &master, sizeof(int));
7066
7067                 mh.msg_controllen = cmsg->cmsg_len;
7068
7069                 if (sendmsg(pair[1], &mh, MSG_NOSIGNAL) < 0)
7070                         _exit(EXIT_FAILURE);
7071
7072                 _exit(EXIT_SUCCESS);
7073         }
7074
7075         pair[1] = safe_close(pair[1]);
7076
7077         r = wait_for_terminate(child, &si);
7078         if (r < 0)
7079                 return r;
7080         if (si.si_code != CLD_EXITED || si.si_status != EXIT_SUCCESS)
7081                 return -EIO;
7082
7083         if (recvmsg(pair[0], &mh, MSG_NOSIGNAL|MSG_CMSG_CLOEXEC) < 0)
7084                 return -errno;
7085
7086         for (cmsg = CMSG_FIRSTHDR(&mh); cmsg; cmsg = CMSG_NXTHDR(&mh, cmsg))
7087                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
7088                         int *fds;
7089                         unsigned n_fds;
7090
7091                         fds = (int*) CMSG_DATA(cmsg);
7092                         n_fds = (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int);
7093
7094                         if (n_fds != 1) {
7095                                 close_many(fds, n_fds);
7096                                 return -EIO;
7097                         }
7098
7099                         return fds[0];
7100                 }
7101
7102         return -EIO;
7103 }
7104
7105 ssize_t fgetxattrat_fake(int dirfd, const char *filename, const char *attribute, void *value, size_t size, int flags) {
7106         _cleanup_close_ int fd = -1;
7107         ssize_t l;
7108
7109         /* The kernel doesn't have a fgetxattrat() command, hence let's emulate one */
7110
7111         fd = openat(dirfd, filename, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOATIME|(flags & AT_SYMLINK_NOFOLLOW ? O_NOFOLLOW : 0));
7112         if (fd < 0)
7113                 return -errno;
7114
7115         l = fgetxattr(fd, attribute, value, size);
7116         if (l < 0)
7117                 return -errno;
7118
7119         return l;
7120 }
7121
7122 static int parse_crtime(le64_t le, usec_t *usec) {
7123         uint64_t u;
7124
7125         assert(usec);
7126
7127         u = le64toh(le);
7128         if (u == 0 || u == (uint64_t) -1)
7129                 return -EIO;
7130
7131         *usec = (usec_t) u;
7132         return 0;
7133 }
7134
7135 int fd_getcrtime(int fd, usec_t *usec) {
7136         le64_t le;
7137         ssize_t n;
7138
7139         assert(fd >= 0);
7140         assert(usec);
7141
7142         /* Until Linux gets a real concept of birthtime/creation time,
7143          * let's fake one with xattrs */
7144
7145         n = fgetxattr(fd, "user.crtime_usec", &le, sizeof(le));
7146         if (n < 0)
7147                 return -errno;
7148         if (n != sizeof(le))
7149                 return -EIO;
7150
7151         return parse_crtime(le, usec);
7152 }
7153
7154 int fd_getcrtime_at(int dirfd, const char *name, usec_t *usec, int flags) {
7155         le64_t le;
7156         ssize_t n;
7157
7158         n = fgetxattrat_fake(dirfd, name, "user.crtime_usec", &le, sizeof(le), flags);
7159         if (n < 0)
7160                 return -errno;
7161         if (n != sizeof(le))
7162                 return -EIO;
7163
7164         return parse_crtime(le, usec);
7165 }
7166
7167 int path_getcrtime(const char *p, usec_t *usec) {
7168         le64_t le;
7169         ssize_t n;
7170
7171         assert(p);
7172         assert(usec);
7173
7174         n = getxattr(p, "user.crtime_usec", &le, sizeof(le));
7175         if (n < 0)
7176                 return -errno;
7177         if (n != sizeof(le))
7178                 return -EIO;
7179
7180         return parse_crtime(le, usec);
7181 }
7182
7183 int fd_setcrtime(int fd, usec_t usec) {
7184         le64_t le;
7185
7186         assert(fd >= 0);
7187
7188         if (usec <= 0)
7189                 usec = now(CLOCK_REALTIME);
7190
7191         le = htole64((uint64_t) usec);
7192         if (fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0) < 0)
7193                 return -errno;
7194
7195         return 0;
7196 }
7197
7198 int chattr_fd(int fd, unsigned value, unsigned mask) {
7199         unsigned old_attr, new_attr;
7200
7201         assert(fd >= 0);
7202
7203         if (mask == 0)
7204                 return 0;
7205
7206         if (ioctl(fd, FS_IOC_GETFLAGS, &old_attr) < 0)
7207                 return -errno;
7208
7209         new_attr = (old_attr & ~mask) | (value & mask);
7210         if (new_attr == old_attr)
7211                 return 0;
7212
7213         if (ioctl(fd, FS_IOC_SETFLAGS, &new_attr) < 0)
7214                 return -errno;
7215
7216         return 1;
7217 }
7218
7219 int chattr_path(const char *p, unsigned value, unsigned mask) {
7220         _cleanup_close_ int fd = -1;
7221
7222         assert(p);
7223
7224         if (mask == 0)
7225                 return 0;
7226
7227         fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
7228         if (fd < 0)
7229                 return -errno;
7230
7231         return chattr_fd(fd, value, mask);
7232 }
7233
7234 int read_attr_fd(int fd, unsigned *ret) {
7235         assert(fd >= 0);
7236
7237         if (ioctl(fd, FS_IOC_GETFLAGS, ret) < 0)
7238                 return -errno;
7239
7240         return 0;
7241 }
7242
7243 int read_attr_path(const char *p, unsigned *ret) {
7244         _cleanup_close_ int fd = -1;
7245
7246         assert(p);
7247         assert(ret);
7248
7249         fd = open(p, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NOFOLLOW);
7250         if (fd < 0)
7251                 return -errno;
7252
7253         return read_attr_fd(fd, ret);
7254 }
7255
7256 int make_lock_file(const char *p, int operation, LockFile *ret) {
7257         _cleanup_close_ int fd = -1;
7258         _cleanup_free_ char *t = NULL;
7259         int r;
7260
7261         /*
7262          * We use UNPOSIX locks if they are available. They have nice
7263          * semantics, and are mostly compatible with NFS. However,
7264          * they are only available on new kernels. When we detect we
7265          * are running on an older kernel, then we fall back to good
7266          * old BSD locks. They also have nice semantics, but are
7267          * slightly problematic on NFS, where they are upgraded to
7268          * POSIX locks, even though locally they are orthogonal to
7269          * POSIX locks.
7270          */
7271
7272         t = strdup(p);
7273         if (!t)
7274                 return -ENOMEM;
7275
7276         for (;;) {
7277                 struct flock fl = {
7278                         .l_type = (operation & ~LOCK_NB) == LOCK_EX ? F_WRLCK : F_RDLCK,
7279                         .l_whence = SEEK_SET,
7280                 };
7281                 struct stat st;
7282
7283                 fd = open(p, O_CREAT|O_RDWR|O_NOFOLLOW|O_CLOEXEC|O_NOCTTY, 0600);
7284                 if (fd < 0)
7285                         return -errno;
7286
7287                 r = fcntl(fd, (operation & LOCK_NB) ? F_OFD_SETLK : F_OFD_SETLKW, &fl);
7288                 if (r < 0) {
7289
7290                         /* If the kernel is too old, use good old BSD locks */
7291                         if (errno == EINVAL)
7292                                 r = flock(fd, operation);
7293
7294                         if (r < 0)
7295                                 return errno == EAGAIN ? -EBUSY : -errno;
7296                 }
7297
7298                 /* If we acquired the lock, let's check if the file
7299                  * still exists in the file system. If not, then the
7300                  * previous exclusive owner removed it and then closed
7301                  * it. In such a case our acquired lock is worthless,
7302                  * hence try again. */
7303
7304                 r = fstat(fd, &st);
7305                 if (r < 0)
7306                         return -errno;
7307                 if (st.st_nlink > 0)
7308                         break;
7309
7310                 fd = safe_close(fd);
7311         }
7312
7313         ret->path = t;
7314         ret->fd = fd;
7315         ret->operation = operation;
7316
7317         fd = -1;
7318         t = NULL;
7319
7320         return r;
7321 }
7322
7323 int make_lock_file_for(const char *p, int operation, LockFile *ret) {
7324         const char *fn;
7325         char *t;
7326
7327         assert(p);
7328         assert(ret);
7329
7330         fn = basename(p);
7331         if (!filename_is_valid(fn))
7332                 return -EINVAL;
7333
7334         t = newa(char, strlen(p) + 2 + 4 + 1);
7335         stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), fn), ".lck");
7336
7337         return make_lock_file(t, operation, ret);
7338 }
7339
7340 void release_lock_file(LockFile *f) {
7341         int r;
7342
7343         if (!f)
7344                 return;
7345
7346         if (f->path) {
7347
7348                 /* If we are the exclusive owner we can safely delete
7349                  * the lock file itself. If we are not the exclusive
7350                  * owner, we can try becoming it. */
7351
7352                 if (f->fd >= 0 &&
7353                     (f->operation & ~LOCK_NB) == LOCK_SH) {
7354                         static const struct flock fl = {
7355                                 .l_type = F_WRLCK,
7356                                 .l_whence = SEEK_SET,
7357                         };
7358
7359                         r = fcntl(f->fd, F_OFD_SETLK, &fl);
7360                         if (r < 0 && errno == EINVAL)
7361                                 r = flock(f->fd, LOCK_EX|LOCK_NB);
7362
7363                         if (r >= 0)
7364                                 f->operation = LOCK_EX|LOCK_NB;
7365                 }
7366
7367                 if ((f->operation & ~LOCK_NB) == LOCK_EX)
7368                         unlink_noerrno(f->path);
7369
7370                 free(f->path);
7371                 f->path = NULL;
7372         }
7373
7374         f->fd = safe_close(f->fd);
7375         f->operation = 0;
7376 }
7377
7378 static size_t nul_length(const uint8_t *p, size_t sz) {
7379         size_t n = 0;
7380
7381         while (sz > 0) {
7382                 if (*p != 0)
7383                         break;
7384
7385                 n++;
7386                 p++;
7387                 sz--;
7388         }
7389
7390         return n;
7391 }
7392
7393 ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
7394         const uint8_t *q, *w, *e;
7395         ssize_t l;
7396
7397         q = w = p;
7398         e = q + sz;
7399         while (q < e) {
7400                 size_t n;
7401
7402                 n = nul_length(q, e - q);
7403
7404                 /* If there are more than the specified run length of
7405                  * NUL bytes, or if this is the beginning or the end
7406                  * of the buffer, then seek instead of write */
7407                 if ((n > run_length) ||
7408                     (n > 0 && q == p) ||
7409                     (n > 0 && q + n >= e)) {
7410                         if (q > w) {
7411                                 l = write(fd, w, q - w);
7412                                 if (l < 0)
7413                                         return -errno;
7414                                 if (l != q -w)
7415                                         return -EIO;
7416                         }
7417
7418                         if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
7419                                 return -errno;
7420
7421                         q += n;
7422                         w = q;
7423                 } else if (n > 0)
7424                         q += n;
7425                 else
7426                         q ++;
7427         }
7428
7429         if (q > w) {
7430                 l = write(fd, w, q - w);
7431                 if (l < 0)
7432                         return -errno;
7433                 if (l != q - w)
7434                         return -EIO;
7435         }
7436
7437         return q - (const uint8_t*) p;
7438 }
7439
7440 void sigkill_wait(pid_t *pid) {
7441         if (!pid)
7442                 return;
7443         if (*pid <= 1)
7444                 return;
7445
7446         if (kill(*pid, SIGKILL) > 0)
7447                 (void) wait_for_terminate(*pid, NULL);
7448 }
7449
7450 int syslog_parse_priority(const char **p, int *priority, bool with_facility) {
7451         int a = 0, b = 0, c = 0;
7452         int k;
7453
7454         assert(p);
7455         assert(*p);
7456         assert(priority);
7457
7458         if ((*p)[0] != '<')
7459                 return 0;
7460
7461         if (!strchr(*p, '>'))
7462                 return 0;
7463
7464         if ((*p)[2] == '>') {
7465                 c = undecchar((*p)[1]);
7466                 k = 3;
7467         } else if ((*p)[3] == '>') {
7468                 b = undecchar((*p)[1]);
7469                 c = undecchar((*p)[2]);
7470                 k = 4;
7471         } else if ((*p)[4] == '>') {
7472                 a = undecchar((*p)[1]);
7473                 b = undecchar((*p)[2]);
7474                 c = undecchar((*p)[3]);
7475                 k = 5;
7476         } else
7477                 return 0;
7478
7479         if (a < 0 || b < 0 || c < 0 ||
7480             (!with_facility && (a || b || c > 7)))
7481                 return 0;
7482
7483         if (with_facility)
7484                 *priority = a*100 + b*10 + c;
7485         else
7486                 *priority = (*priority & LOG_FACMASK) | c;
7487
7488         *p += k;
7489         return 1;
7490 }
7491
7492 ssize_t string_table_lookup(const char * const *table, size_t len, const char *key) {
7493         size_t i;
7494
7495         if (!key)
7496                 return -1;
7497
7498         for (i = 0; i < len; ++i)
7499                 if (streq_ptr(table[i], key))
7500                         return (ssize_t)i;
7501
7502         return -1;
7503 }
7504
7505 void cmsg_close_all(struct msghdr *mh) {
7506         struct cmsghdr *cmsg;
7507
7508         assert(mh);
7509
7510         for (cmsg = CMSG_FIRSTHDR(mh); cmsg; cmsg = CMSG_NXTHDR(mh, cmsg))
7511                 if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS)
7512                         close_many((int*) CMSG_DATA(cmsg), (cmsg->cmsg_len - CMSG_LEN(0)) / sizeof(int));
7513 }
7514
7515 int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath) {
7516         struct stat buf;
7517         int ret;
7518
7519         ret = renameat2(olddirfd, oldpath, newdirfd, newpath, RENAME_NOREPLACE);
7520         if (ret >= 0)
7521                 return 0;
7522
7523         /* Even though renameat2() exists since Linux 3.15, btrfs added
7524          * support for it later. If it is not implemented, fallback to another
7525          * method. */
7526         if (errno != EINVAL)
7527                 return -errno;
7528
7529         /* The link()/unlink() fallback does not work on directories. But
7530          * renameat() without RENAME_NOREPLACE gives the same semantics on
7531          * directories, except when newpath is an *empty* directory. This is
7532          * good enough. */
7533         ret = fstatat(olddirfd, oldpath, &buf, AT_SYMLINK_NOFOLLOW);
7534         if (ret >= 0 && S_ISDIR(buf.st_mode)) {
7535                 ret = renameat(olddirfd, oldpath, newdirfd, newpath);
7536                 return ret >= 0 ? 0 : -errno;
7537         }
7538
7539         /* If it is not a directory, use the link()/unlink() fallback. */
7540         ret = linkat(olddirfd, oldpath, newdirfd, newpath, 0);
7541         if (ret < 0)
7542                 return -errno;
7543
7544         ret = unlinkat(olddirfd, oldpath, 0);
7545         if (ret < 0) {
7546                 /* backup errno before the following unlinkat() alters it */
7547                 ret = errno;
7548                 (void) unlinkat(newdirfd, newpath, 0);
7549                 errno = ret;
7550                 return -errno;
7551         }
7552
7553         return 0;
7554 }
7555
7556 char *shell_maybe_quote(const char *s) {
7557         const char *p;
7558         char *r, *t;
7559
7560         assert(s);
7561
7562         /* Encloses a string in double quotes if necessary to make it
7563          * OK as shell string. */
7564
7565         for (p = s; *p; p++)
7566                 if (*p <= ' ' ||
7567                     *p >= 127 ||
7568                     strchr(SHELL_NEED_QUOTES, *p))
7569                         break;
7570
7571         if (!*p)
7572                 return strdup(s);
7573
7574         r = new(char, 1+strlen(s)*2+1+1);
7575         if (!r)
7576                 return NULL;
7577
7578         t = r;
7579         *(t++) = '"';
7580         t = mempcpy(t, s, p - s);
7581
7582         for (; *p; p++) {
7583
7584                 if (strchr(SHELL_NEED_ESCAPE, *p))
7585                         *(t++) = '\\';
7586
7587                 *(t++) = *p;
7588         }
7589
7590         *(t++)= '"';
7591         *t = 0;
7592
7593         return r;
7594 }
7595
7596 int parse_mode(const char *s, mode_t *ret) {
7597         char *x;
7598         long l;
7599
7600         assert(s);
7601         assert(ret);
7602
7603         errno = 0;
7604         l = strtol(s, &x, 8);
7605         if (errno != 0)
7606                 return -errno;
7607
7608         if (!x || x == s || *x)
7609                 return -EINVAL;
7610         if (l < 0 || l  > 07777)
7611                 return -ERANGE;
7612
7613         *ret = (mode_t) l;
7614         return 0;
7615 }