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