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