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