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