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