chiark / gitweb /
util: when replacing env vars replace unset envvars by nothing
[elogind.git] / src / util.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
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
52 #include "macro.h"
53 #include "util.h"
54 #include "ioprio.h"
55 #include "missing.h"
56 #include "log.h"
57 #include "strv.h"
58
59 #ifdef HAVE_SELINUX
60 #include <selinux/selinux.h>
61 #include <selinux/label.h>
62
63 static struct selabel_handle *label_hnd = NULL;
64
65 static inline bool use_selinux(void) {
66         static int use_selinux_ind = -1;
67
68         if (use_selinux_ind < 0)
69                 use_selinux_ind = is_selinux_enabled() > 0;
70
71         return use_selinux_ind;
72 }
73
74 static int label_get_file_label_from_path(
75                 const char *label,
76                 const char *path,
77                 const char *class,
78                 security_context_t *fcon) {
79
80         security_context_t dir_con = NULL;
81         security_class_t sclass;
82         int r = 0;
83
84         r = getfilecon(path, &dir_con);
85         if (r >= 0) {
86                 r = -1;
87                 errno = EINVAL;
88
89                 if ((sclass = string_to_security_class(class)) != 0)
90                         r = security_compute_create((security_context_t) label, dir_con, sclass, fcon);
91         }
92         if (r < 0)
93                 r = -errno;
94
95         freecon(dir_con);
96         return r;
97 }
98
99 #endif
100
101 int label_init(void) {
102         int r = 0;
103
104 #ifdef HAVE_SELINUX
105
106         if (!use_selinux())
107                 return 0;
108
109         label_hnd = selabel_open(SELABEL_CTX_FILE, NULL, 0);
110         if (!label_hnd) {
111                 log_full(security_getenforce() == 1 ? LOG_ERR : LOG_DEBUG,
112                          "Failed to initialize SELinux context: %m");
113                 r = (security_getenforce() == 1) ? -errno : 0;
114         }
115 #endif
116
117         return r;
118 }
119
120 int label_fix(const char *path) {
121         int r = 0;
122
123 #ifdef HAVE_SELINUX
124         struct stat st;
125         security_context_t fcon;
126
127         if (!use_selinux() || !label_hnd)
128                 return 0;
129
130         r = lstat(path, &st);
131         if (r == 0) {
132                 r = selabel_lookup_raw(label_hnd, &fcon, path, st.st_mode);
133
134                 if (r == 0) {
135                         r = setfilecon(path, fcon);
136                         freecon(fcon);
137                 }
138         }
139         if (r < 0) {
140                 log_full(security_getenforce() == 1 ? LOG_ERR : LOG_DEBUG,
141                          "Unable to fix label of %s: %m", path);
142                 r = (security_getenforce() == 1) ? -errno : 0;
143         }
144 #endif
145
146         return r;
147 }
148
149 void label_finish(void) {
150
151 #ifdef HAVE_SELINUX
152         if (use_selinux() && label_hnd)
153                 selabel_close(label_hnd);
154 #endif
155 }
156
157 int label_get_socket_label_from_exe(const char *exe, char **label) {
158
159         int r = 0;
160
161 #ifdef HAVE_SELINUX
162         security_context_t mycon = NULL, fcon = NULL;
163         security_class_t sclass;
164
165         if (!use_selinux()) {
166                 *label = NULL;
167                 return 0;
168         }
169
170         r = getcon(&mycon);
171         if (r < 0)
172                 goto fail;
173
174         r = getfilecon(exe, &fcon);
175         if (r < 0)
176                 goto fail;
177
178         sclass = string_to_security_class("process");
179         r = security_compute_create(mycon, fcon, sclass, (security_context_t *) label);
180         if (r == 0)
181                 log_debug("SELinux Socket context for %s will be set to %s", exe, *label);
182
183 fail:
184         if (r < 0 && security_getenforce() == 1)
185                 r = -errno;
186
187         freecon(mycon);
188         freecon(fcon);
189 #endif
190
191         return r;
192 }
193
194 int label_fifofile_set(const char *label, const char *path) {
195         int r = 0;
196
197 #ifdef HAVE_SELINUX
198         security_context_t filecon = NULL;
199
200         if (!use_selinux() || !label)
201                 return 0;
202
203         if (((r = label_get_file_label_from_path(label, path, "fifo_file", &filecon)) == 0)) {
204                 if ((r = setfscreatecon(filecon)) < 0) {
205                         log_error("Failed to set SELinux file context (%s) on %s: %m", label, path);
206                         r = -errno;
207                 }
208
209                 freecon(filecon);
210         }
211
212         if (r < 0 && security_getenforce() == 0)
213                 r = 0;
214 #endif
215
216         return r;
217 }
218
219 int label_socket_set(const char *label) {
220
221 #ifdef HAVE_SELINUX
222         if (!use_selinux())
223                 return 0;
224
225         if (setsockcreatecon((security_context_t) label) < 0) {
226                 log_full(security_getenforce() == 1 ? LOG_ERR : LOG_DEBUG,
227                          "Failed to set SELinux context (%s) on socket: %m", label);
228
229                 if (security_getenforce() == 1)
230                         return -errno;
231         }
232 #endif
233
234         return 0;
235 }
236
237 void label_file_clear(void) {
238
239 #ifdef HAVE_SELINUX
240         if (!use_selinux())
241                 return;
242
243         setfscreatecon(NULL);
244 #endif
245 }
246
247 void label_socket_clear(void) {
248
249 #ifdef HAVE_SELINUX
250         if (!use_selinux())
251                 return;
252
253         setsockcreatecon(NULL);
254 #endif
255 }
256
257 void label_free(const char *label) {
258
259 #ifdef HAVE_SELINUX
260         if (!use_selinux())
261                 return;
262
263         freecon((security_context_t) label);
264 #endif
265 }
266
267 static int label_mkdir(
268         const char *path,
269         mode_t mode) {
270
271 #ifdef HAVE_SELINUX
272         int r;
273         security_context_t fcon = NULL;
274
275         if (use_selinux() && label_hnd) {
276                 if (path[0] == '/') {
277                         r = selabel_lookup_raw(label_hnd, &fcon, path, mode);
278                 }
279                 else {
280                         char *cwd = NULL;
281                         char *newpath = NULL;
282                         cwd = getcwd(NULL,0);
283                         if ((! cwd) || (asprintf(&newpath, "%s/%s",cwd,path) < 0)) {
284                                 free(cwd);
285                                 return -errno;
286                         }
287                         r = selabel_lookup_raw(label_hnd, &fcon, newpath, mode);
288                         free(cwd);
289                         free(newpath);
290                 }
291
292                 if (r == 0)
293                         r = setfscreatecon(fcon);
294
295                 if ((r < 0) && (errno != ENOENT)) {
296                         log_error("Failed to set security context %s for %s", fcon, path);
297
298                         if (security_getenforce() == 1)
299                                 goto finish;
300                 }
301         }
302         r = mkdir(path, mode);
303
304 finish:
305         if (use_selinux() && label_hnd) {
306                 setfscreatecon(NULL);
307                 freecon(fcon);
308         }
309
310         return r;
311 #else
312         return mkdir(path, mode);
313 #endif
314 }
315
316 bool streq_ptr(const char *a, const char *b) {
317
318         /* Like streq(), but tries to make sense of NULL pointers */
319
320         if (a && b)
321                 return streq(a, b);
322
323         if (!a && !b)
324                 return true;
325
326         return false;
327 }
328
329 usec_t now(clockid_t clock_id) {
330         struct timespec ts;
331
332         assert_se(clock_gettime(clock_id, &ts) == 0);
333
334         return timespec_load(&ts);
335 }
336
337 dual_timestamp* dual_timestamp_get(dual_timestamp *ts) {
338         assert(ts);
339
340         ts->realtime = now(CLOCK_REALTIME);
341         ts->monotonic = now(CLOCK_MONOTONIC);
342
343         return ts;
344 }
345
346 usec_t timespec_load(const struct timespec *ts) {
347         assert(ts);
348
349         return
350                 (usec_t) ts->tv_sec * USEC_PER_SEC +
351                 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
352 }
353
354 struct timespec *timespec_store(struct timespec *ts, usec_t u)  {
355         assert(ts);
356
357         ts->tv_sec = (time_t) (u / USEC_PER_SEC);
358         ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
359
360         return ts;
361 }
362
363 usec_t timeval_load(const struct timeval *tv) {
364         assert(tv);
365
366         return
367                 (usec_t) tv->tv_sec * USEC_PER_SEC +
368                 (usec_t) tv->tv_usec;
369 }
370
371 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
372         assert(tv);
373
374         tv->tv_sec = (time_t) (u / USEC_PER_SEC);
375         tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
376
377         return tv;
378 }
379
380 bool endswith(const char *s, const char *postfix) {
381         size_t sl, pl;
382
383         assert(s);
384         assert(postfix);
385
386         sl = strlen(s);
387         pl = strlen(postfix);
388
389         if (pl == 0)
390                 return true;
391
392         if (sl < pl)
393                 return false;
394
395         return memcmp(s + sl - pl, postfix, pl) == 0;
396 }
397
398 bool startswith(const char *s, const char *prefix) {
399         size_t sl, pl;
400
401         assert(s);
402         assert(prefix);
403
404         sl = strlen(s);
405         pl = strlen(prefix);
406
407         if (pl == 0)
408                 return true;
409
410         if (sl < pl)
411                 return false;
412
413         return memcmp(s, prefix, pl) == 0;
414 }
415
416 bool startswith_no_case(const char *s, const char *prefix) {
417         size_t sl, pl;
418         unsigned i;
419
420         assert(s);
421         assert(prefix);
422
423         sl = strlen(s);
424         pl = strlen(prefix);
425
426         if (pl == 0)
427                 return true;
428
429         if (sl < pl)
430                 return false;
431
432         for(i = 0; i < pl; ++i) {
433                 if (tolower(s[i]) != tolower(prefix[i]))
434                         return false;
435         }
436
437         return true;
438 }
439
440 bool first_word(const char *s, const char *word) {
441         size_t sl, wl;
442
443         assert(s);
444         assert(word);
445
446         sl = strlen(s);
447         wl = strlen(word);
448
449         if (sl < wl)
450                 return false;
451
452         if (wl == 0)
453                 return true;
454
455         if (memcmp(s, word, wl) != 0)
456                 return false;
457
458         return s[wl] == 0 ||
459                 strchr(WHITESPACE, s[wl]);
460 }
461
462 int close_nointr(int fd) {
463         assert(fd >= 0);
464
465         for (;;) {
466                 int r;
467
468                 if ((r = close(fd)) >= 0)
469                         return r;
470
471                 if (errno != EINTR)
472                         return r;
473         }
474 }
475
476 void close_nointr_nofail(int fd) {
477         int saved_errno = errno;
478
479         /* like close_nointr() but cannot fail, and guarantees errno
480          * is unchanged */
481
482         assert_se(close_nointr(fd) == 0);
483
484         errno = saved_errno;
485 }
486
487 void close_many(const int fds[], unsigned n_fd) {
488         unsigned i;
489
490         for (i = 0; i < n_fd; i++)
491                 close_nointr_nofail(fds[i]);
492 }
493
494 int parse_boolean(const char *v) {
495         assert(v);
496
497         if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
498                 return 1;
499         else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
500                 return 0;
501
502         return -EINVAL;
503 }
504
505 int parse_pid(const char *s, pid_t* ret_pid) {
506         unsigned long ul;
507         pid_t pid;
508         int r;
509
510         assert(s);
511         assert(ret_pid);
512
513         if ((r = safe_atolu(s, &ul)) < 0)
514                 return r;
515
516         pid = (pid_t) ul;
517
518         if ((unsigned long) pid != ul)
519                 return -ERANGE;
520
521         if (pid <= 0)
522                 return -ERANGE;
523
524         *ret_pid = pid;
525         return 0;
526 }
527
528 int safe_atou(const char *s, unsigned *ret_u) {
529         char *x = NULL;
530         unsigned long l;
531
532         assert(s);
533         assert(ret_u);
534
535         errno = 0;
536         l = strtoul(s, &x, 0);
537
538         if (!x || *x || errno)
539                 return errno ? -errno : -EINVAL;
540
541         if ((unsigned long) (unsigned) l != l)
542                 return -ERANGE;
543
544         *ret_u = (unsigned) l;
545         return 0;
546 }
547
548 int safe_atoi(const char *s, int *ret_i) {
549         char *x = NULL;
550         long l;
551
552         assert(s);
553         assert(ret_i);
554
555         errno = 0;
556         l = strtol(s, &x, 0);
557
558         if (!x || *x || errno)
559                 return errno ? -errno : -EINVAL;
560
561         if ((long) (int) l != l)
562                 return -ERANGE;
563
564         *ret_i = (int) l;
565         return 0;
566 }
567
568 int safe_atollu(const char *s, long long unsigned *ret_llu) {
569         char *x = NULL;
570         unsigned long long l;
571
572         assert(s);
573         assert(ret_llu);
574
575         errno = 0;
576         l = strtoull(s, &x, 0);
577
578         if (!x || *x || errno)
579                 return errno ? -errno : -EINVAL;
580
581         *ret_llu = l;
582         return 0;
583 }
584
585 int safe_atolli(const char *s, long long int *ret_lli) {
586         char *x = NULL;
587         long long l;
588
589         assert(s);
590         assert(ret_lli);
591
592         errno = 0;
593         l = strtoll(s, &x, 0);
594
595         if (!x || *x || errno)
596                 return errno ? -errno : -EINVAL;
597
598         *ret_lli = l;
599         return 0;
600 }
601
602 /* Split a string into words. */
603 char *split(const char *c, size_t *l, const char *separator, char **state) {
604         char *current;
605
606         current = *state ? *state : (char*) c;
607
608         if (!*current || *c == 0)
609                 return NULL;
610
611         current += strspn(current, separator);
612         *l = strcspn(current, separator);
613         *state = current+*l;
614
615         return (char*) current;
616 }
617
618 /* Split a string into words, but consider strings enclosed in '' and
619  * "" as words even if they include spaces. */
620 char *split_quoted(const char *c, size_t *l, char **state) {
621         char *current, *e;
622         bool escaped = false;
623
624         current = *state ? *state : (char*) c;
625
626         if (!*current || *c == 0)
627                 return NULL;
628
629         current += strspn(current, WHITESPACE);
630
631         if (*current == '\'') {
632                 current ++;
633
634                 for (e = current; *e; e++) {
635                         if (escaped)
636                                 escaped = false;
637                         else if (*e == '\\')
638                                 escaped = true;
639                         else if (*e == '\'')
640                                 break;
641                 }
642
643                 *l = e-current;
644                 *state = *e == 0 ? e : e+1;
645         } else if (*current == '\"') {
646                 current ++;
647
648                 for (e = current; *e; e++) {
649                         if (escaped)
650                                 escaped = false;
651                         else if (*e == '\\')
652                                 escaped = true;
653                         else if (*e == '\"')
654                                 break;
655                 }
656
657                 *l = e-current;
658                 *state = *e == 0 ? e : e+1;
659         } else {
660                 for (e = current; *e; e++) {
661                         if (escaped)
662                                 escaped = false;
663                         else if (*e == '\\')
664                                 escaped = true;
665                         else if (strchr(WHITESPACE, *e))
666                                 break;
667                 }
668                 *l = e-current;
669                 *state = e;
670         }
671
672         return (char*) current;
673 }
674
675 char **split_path_and_make_absolute(const char *p) {
676         char **l;
677         assert(p);
678
679         if (!(l = strv_split(p, ":")))
680                 return NULL;
681
682         if (!strv_path_make_absolute_cwd(l)) {
683                 strv_free(l);
684                 return NULL;
685         }
686
687         return l;
688 }
689
690 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
691         int r;
692         FILE *f;
693         char fn[132], line[256], *p;
694         long unsigned ppid;
695
696         assert(pid >= 0);
697         assert(_ppid);
698
699         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%lu/stat", (unsigned long) pid) < (int) (sizeof(fn)-1));
700         fn[sizeof(fn)-1] = 0;
701
702         if (!(f = fopen(fn, "r")))
703                 return -errno;
704
705         if (!(fgets(line, sizeof(line), f))) {
706                 r = -errno;
707                 fclose(f);
708                 return r;
709         }
710
711         fclose(f);
712
713         /* Let's skip the pid and comm fields. The latter is enclosed
714          * in () but does not escape any () in its value, so let's
715          * skip over it manually */
716
717         if (!(p = strrchr(line, ')')))
718                 return -EIO;
719
720         p++;
721
722         if (sscanf(p, " "
723                    "%*c "  /* state */
724                    "%lu ", /* ppid */
725                    &ppid) != 1)
726                 return -EIO;
727
728         if ((long unsigned) (pid_t) ppid != ppid)
729                 return -ERANGE;
730
731         *_ppid = (pid_t) ppid;
732
733         return 0;
734 }
735
736 int write_one_line_file(const char *fn, const char *line) {
737         FILE *f;
738         int r;
739
740         assert(fn);
741         assert(line);
742
743         if (!(f = fopen(fn, "we")))
744                 return -errno;
745
746         if (fputs(line, f) < 0) {
747                 r = -errno;
748                 goto finish;
749         }
750
751         r = 0;
752 finish:
753         fclose(f);
754         return r;
755 }
756
757 int read_one_line_file(const char *fn, char **line) {
758         FILE *f;
759         int r;
760         char t[2048], *c;
761
762         assert(fn);
763         assert(line);
764
765         if (!(f = fopen(fn, "re")))
766                 return -errno;
767
768         if (!(fgets(t, sizeof(t), f))) {
769                 r = -errno;
770                 goto finish;
771         }
772
773         if (!(c = strdup(t))) {
774                 r = -ENOMEM;
775                 goto finish;
776         }
777
778         *line = c;
779         r = 0;
780
781 finish:
782         fclose(f);
783         return r;
784 }
785
786 char *truncate_nl(char *s) {
787         assert(s);
788
789         s[strcspn(s, NEWLINE)] = 0;
790         return s;
791 }
792
793 int get_process_name(pid_t pid, char **name) {
794         char *p;
795         int r;
796
797         assert(pid >= 1);
798         assert(name);
799
800         if (asprintf(&p, "/proc/%lu/comm", (unsigned long) pid) < 0)
801                 return -ENOMEM;
802
803         r = read_one_line_file(p, name);
804         free(p);
805
806         if (r < 0)
807                 return r;
808
809         truncate_nl(*name);
810         return 0;
811 }
812
813 int get_process_cmdline(pid_t pid, size_t max_length, char **line) {
814         char *p, *r, *k;
815         int c;
816         bool space = false;
817         size_t left;
818         FILE *f;
819
820         assert(pid >= 1);
821         assert(max_length > 0);
822         assert(line);
823
824         if (asprintf(&p, "/proc/%lu/cmdline", (unsigned long) pid) < 0)
825                 return -ENOMEM;
826
827         f = fopen(p, "r");
828         free(p);
829
830         if (!f)
831                 return -errno;
832
833         if (!(r = new(char, max_length))) {
834                 fclose(f);
835                 return -ENOMEM;
836         }
837
838         k = r;
839         left = max_length;
840         while ((c = getc(f)) != EOF) {
841
842                 if (isprint(c)) {
843                         if (space) {
844                                 if (left <= 4)
845                                         break;
846
847                                 *(k++) = ' ';
848                                 left--;
849                                 space = false;
850                         }
851
852                         if (left <= 4)
853                                 break;
854
855                         *(k++) = (char) c;
856                         left--;
857                 }  else
858                         space = true;
859         }
860
861         if (left <= 4) {
862                 size_t n = MIN(left-1, 3U);
863                 memcpy(k, "...", n);
864                 k[n] = 0;
865         } else
866                 *k = 0;
867
868         fclose(f);
869
870         /* Kernel threads have no argv[] */
871         if (r[0] == 0) {
872                 char *t;
873                 int h;
874
875                 free(r);
876
877                 if ((h = get_process_name(pid, &t)) < 0)
878                         return h;
879
880                 h = asprintf(&r, "[%s]", t);
881                 free(t);
882
883                 if (h < 0)
884                         return -ENOMEM;
885         }
886
887         *line = r;
888         return 0;
889 }
890
891 char *strnappend(const char *s, const char *suffix, size_t b) {
892         size_t a;
893         char *r;
894
895         if (!s && !suffix)
896                 return strdup("");
897
898         if (!s)
899                 return strndup(suffix, b);
900
901         if (!suffix)
902                 return strdup(s);
903
904         assert(s);
905         assert(suffix);
906
907         a = strlen(s);
908
909         if (!(r = new(char, a+b+1)))
910                 return NULL;
911
912         memcpy(r, s, a);
913         memcpy(r+a, suffix, b);
914         r[a+b] = 0;
915
916         return r;
917 }
918
919 char *strappend(const char *s, const char *suffix) {
920         return strnappend(s, suffix, suffix ? strlen(suffix) : 0);
921 }
922
923 int readlink_malloc(const char *p, char **r) {
924         size_t l = 100;
925
926         assert(p);
927         assert(r);
928
929         for (;;) {
930                 char *c;
931                 ssize_t n;
932
933                 if (!(c = new(char, l)))
934                         return -ENOMEM;
935
936                 if ((n = readlink(p, c, l-1)) < 0) {
937                         int ret = -errno;
938                         free(c);
939                         return ret;
940                 }
941
942                 if ((size_t) n < l-1) {
943                         c[n] = 0;
944                         *r = c;
945                         return 0;
946                 }
947
948                 free(c);
949                 l *= 2;
950         }
951 }
952
953 int readlink_and_make_absolute(const char *p, char **r) {
954         char *target, *k;
955         int j;
956
957         assert(p);
958         assert(r);
959
960         if ((j = readlink_malloc(p, &target)) < 0)
961                 return j;
962
963         k = file_in_same_dir(p, target);
964         free(target);
965
966         if (!k)
967                 return -ENOMEM;
968
969         *r = k;
970         return 0;
971 }
972
973 int parent_of_path(const char *path, char **_r) {
974         const char *e, *a = NULL, *b = NULL, *p;
975         char *r;
976         bool slash = false;
977
978         assert(path);
979         assert(_r);
980
981         if (!*path)
982                 return -EINVAL;
983
984         for (e = path; *e; e++) {
985
986                 if (!slash && *e == '/') {
987                         a = b;
988                         b = e;
989                         slash = true;
990                 } else if (slash && *e != '/')
991                         slash = false;
992         }
993
994         if (*(e-1) == '/')
995                 p = a;
996         else
997                 p = b;
998
999         if (!p)
1000                 return -EINVAL;
1001
1002         if (p == path)
1003                 r = strdup("/");
1004         else
1005                 r = strndup(path, p-path);
1006
1007         if (!r)
1008                 return -ENOMEM;
1009
1010         *_r = r;
1011         return 0;
1012 }
1013
1014
1015 char *file_name_from_path(const char *p) {
1016         char *r;
1017
1018         assert(p);
1019
1020         if ((r = strrchr(p, '/')))
1021                 return r + 1;
1022
1023         return (char*) p;
1024 }
1025
1026 bool path_is_absolute(const char *p) {
1027         assert(p);
1028
1029         return p[0] == '/';
1030 }
1031
1032 bool is_path(const char *p) {
1033
1034         return !!strchr(p, '/');
1035 }
1036
1037 char *path_make_absolute(const char *p, const char *prefix) {
1038         char *r;
1039
1040         assert(p);
1041
1042         /* Makes every item in the list an absolute path by prepending
1043          * the prefix, if specified and necessary */
1044
1045         if (path_is_absolute(p) || !prefix)
1046                 return strdup(p);
1047
1048         if (asprintf(&r, "%s/%s", prefix, p) < 0)
1049                 return NULL;
1050
1051         return r;
1052 }
1053
1054 char *path_make_absolute_cwd(const char *p) {
1055         char *cwd, *r;
1056
1057         assert(p);
1058
1059         /* Similar to path_make_absolute(), but prefixes with the
1060          * current working directory. */
1061
1062         if (path_is_absolute(p))
1063                 return strdup(p);
1064
1065         if (!(cwd = get_current_dir_name()))
1066                 return NULL;
1067
1068         r = path_make_absolute(p, cwd);
1069         free(cwd);
1070
1071         return r;
1072 }
1073
1074 char **strv_path_make_absolute_cwd(char **l) {
1075         char **s;
1076
1077         /* Goes through every item in the string list and makes it
1078          * absolute. This works in place and won't rollback any
1079          * changes on failure. */
1080
1081         STRV_FOREACH(s, l) {
1082                 char *t;
1083
1084                 if (!(t = path_make_absolute_cwd(*s)))
1085                         return NULL;
1086
1087                 free(*s);
1088                 *s = t;
1089         }
1090
1091         return l;
1092 }
1093
1094 char **strv_path_canonicalize(char **l) {
1095         char **s;
1096         unsigned k = 0;
1097         bool enomem = false;
1098
1099         if (strv_isempty(l))
1100                 return l;
1101
1102         /* Goes through every item in the string list and canonicalize
1103          * the path. This works in place and won't rollback any
1104          * changes on failure. */
1105
1106         STRV_FOREACH(s, l) {
1107                 char *t, *u;
1108
1109                 t = path_make_absolute_cwd(*s);
1110                 free(*s);
1111
1112                 if (!t) {
1113                         enomem = true;
1114                         continue;
1115                 }
1116
1117                 errno = 0;
1118                 u = canonicalize_file_name(t);
1119                 free(t);
1120
1121                 if (!u) {
1122                         if (errno == ENOMEM || !errno)
1123                                 enomem = true;
1124
1125                         continue;
1126                 }
1127
1128                 l[k++] = u;
1129         }
1130
1131         l[k] = NULL;
1132
1133         if (enomem)
1134                 return NULL;
1135
1136         return l;
1137 }
1138
1139 int reset_all_signal_handlers(void) {
1140         int sig;
1141
1142         for (sig = 1; sig < _NSIG; sig++) {
1143                 struct sigaction sa;
1144
1145                 if (sig == SIGKILL || sig == SIGSTOP)
1146                         continue;
1147
1148                 zero(sa);
1149                 sa.sa_handler = SIG_DFL;
1150                 sa.sa_flags = SA_RESTART;
1151
1152                 /* On Linux the first two RT signals are reserved by
1153                  * glibc, and sigaction() will return EINVAL for them. */
1154                 if ((sigaction(sig, &sa, NULL) < 0))
1155                         if (errno != EINVAL)
1156                                 return -errno;
1157         }
1158
1159         return 0;
1160 }
1161
1162 char *strstrip(char *s) {
1163         char *e, *l = NULL;
1164
1165         /* Drops trailing whitespace. Modifies the string in
1166          * place. Returns pointer to first non-space character */
1167
1168         s += strspn(s, WHITESPACE);
1169
1170         for (e = s; *e; e++)
1171                 if (!strchr(WHITESPACE, *e))
1172                         l = e;
1173
1174         if (l)
1175                 *(l+1) = 0;
1176         else
1177                 *s = 0;
1178
1179         return s;
1180 }
1181
1182 char *delete_chars(char *s, const char *bad) {
1183         char *f, *t;
1184
1185         /* Drops all whitespace, regardless where in the string */
1186
1187         for (f = s, t = s; *f; f++) {
1188                 if (strchr(bad, *f))
1189                         continue;
1190
1191                 *(t++) = *f;
1192         }
1193
1194         *t = 0;
1195
1196         return s;
1197 }
1198
1199 char *file_in_same_dir(const char *path, const char *filename) {
1200         char *e, *r;
1201         size_t k;
1202
1203         assert(path);
1204         assert(filename);
1205
1206         /* This removes the last component of path and appends
1207          * filename, unless the latter is absolute anyway or the
1208          * former isn't */
1209
1210         if (path_is_absolute(filename))
1211                 return strdup(filename);
1212
1213         if (!(e = strrchr(path, '/')))
1214                 return strdup(filename);
1215
1216         k = strlen(filename);
1217         if (!(r = new(char, e-path+1+k+1)))
1218                 return NULL;
1219
1220         memcpy(r, path, e-path+1);
1221         memcpy(r+(e-path)+1, filename, k+1);
1222
1223         return r;
1224 }
1225
1226 int safe_mkdir(const char *path, mode_t mode, uid_t uid, gid_t gid) {
1227         struct stat st;
1228
1229         if (label_mkdir(path, mode) >= 0)
1230                 if (chmod_and_chown(path, mode, uid, gid) < 0)
1231                         return -errno;
1232
1233         if (lstat(path, &st) < 0)
1234                 return -errno;
1235
1236         if ((st.st_mode & 0777) != mode ||
1237             st.st_uid != uid ||
1238             st.st_gid != gid ||
1239             !S_ISDIR(st.st_mode)) {
1240                 errno = EEXIST;
1241                 return -errno;
1242         }
1243
1244         return 0;
1245 }
1246
1247
1248 int mkdir_parents(const char *path, mode_t mode) {
1249         const char *p, *e;
1250
1251         assert(path);
1252
1253         /* Creates every parent directory in the path except the last
1254          * component. */
1255
1256         p = path + strspn(path, "/");
1257         for (;;) {
1258                 int r;
1259                 char *t;
1260
1261                 e = p + strcspn(p, "/");
1262                 p = e + strspn(e, "/");
1263
1264                 /* Is this the last component? If so, then we're
1265                  * done */
1266                 if (*p == 0)
1267                         return 0;
1268
1269                 if (!(t = strndup(path, e - path)))
1270                         return -ENOMEM;
1271
1272                 r = label_mkdir(t, mode);
1273                 free(t);
1274
1275                 if (r < 0 && errno != EEXIST)
1276                         return -errno;
1277         }
1278 }
1279
1280 int mkdir_p(const char *path, mode_t mode) {
1281         int r;
1282
1283         /* Like mkdir -p */
1284
1285         if ((r = mkdir_parents(path, mode)) < 0)
1286                 return r;
1287
1288         if (label_mkdir(path, mode) < 0 && errno != EEXIST)
1289                 return -errno;
1290
1291         return 0;
1292 }
1293
1294 int rmdir_parents(const char *path, const char *stop) {
1295         size_t l;
1296         int r = 0;
1297
1298         assert(path);
1299         assert(stop);
1300
1301         l = strlen(path);
1302
1303         /* Skip trailing slashes */
1304         while (l > 0 && path[l-1] == '/')
1305                 l--;
1306
1307         while (l > 0) {
1308                 char *t;
1309
1310                 /* Skip last component */
1311                 while (l > 0 && path[l-1] != '/')
1312                         l--;
1313
1314                 /* Skip trailing slashes */
1315                 while (l > 0 && path[l-1] == '/')
1316                         l--;
1317
1318                 if (l <= 0)
1319                         break;
1320
1321                 if (!(t = strndup(path, l)))
1322                         return -ENOMEM;
1323
1324                 if (path_startswith(stop, t)) {
1325                         free(t);
1326                         return 0;
1327                 }
1328
1329                 r = rmdir(t);
1330                 free(t);
1331
1332                 if (r < 0)
1333                         if (errno != ENOENT)
1334                                 return -errno;
1335         }
1336
1337         return 0;
1338 }
1339
1340
1341 char hexchar(int x) {
1342         static const char table[16] = "0123456789abcdef";
1343
1344         return table[x & 15];
1345 }
1346
1347 int unhexchar(char c) {
1348
1349         if (c >= '0' && c <= '9')
1350                 return c - '0';
1351
1352         if (c >= 'a' && c <= 'f')
1353                 return c - 'a' + 10;
1354
1355         if (c >= 'A' && c <= 'F')
1356                 return c - 'A' + 10;
1357
1358         return -1;
1359 }
1360
1361 char octchar(int x) {
1362         return '0' + (x & 7);
1363 }
1364
1365 int unoctchar(char c) {
1366
1367         if (c >= '0' && c <= '7')
1368                 return c - '0';
1369
1370         return -1;
1371 }
1372
1373 char decchar(int x) {
1374         return '0' + (x % 10);
1375 }
1376
1377 int undecchar(char c) {
1378
1379         if (c >= '0' && c <= '9')
1380                 return c - '0';
1381
1382         return -1;
1383 }
1384
1385 char *cescape(const char *s) {
1386         char *r, *t;
1387         const char *f;
1388
1389         assert(s);
1390
1391         /* Does C style string escaping. */
1392
1393         if (!(r = new(char, strlen(s)*4 + 1)))
1394                 return NULL;
1395
1396         for (f = s, t = r; *f; f++)
1397
1398                 switch (*f) {
1399
1400                 case '\a':
1401                         *(t++) = '\\';
1402                         *(t++) = 'a';
1403                         break;
1404                 case '\b':
1405                         *(t++) = '\\';
1406                         *(t++) = 'b';
1407                         break;
1408                 case '\f':
1409                         *(t++) = '\\';
1410                         *(t++) = 'f';
1411                         break;
1412                 case '\n':
1413                         *(t++) = '\\';
1414                         *(t++) = 'n';
1415                         break;
1416                 case '\r':
1417                         *(t++) = '\\';
1418                         *(t++) = 'r';
1419                         break;
1420                 case '\t':
1421                         *(t++) = '\\';
1422                         *(t++) = 't';
1423                         break;
1424                 case '\v':
1425                         *(t++) = '\\';
1426                         *(t++) = 'v';
1427                         break;
1428                 case '\\':
1429                         *(t++) = '\\';
1430                         *(t++) = '\\';
1431                         break;
1432                 case '"':
1433                         *(t++) = '\\';
1434                         *(t++) = '"';
1435                         break;
1436                 case '\'':
1437                         *(t++) = '\\';
1438                         *(t++) = '\'';
1439                         break;
1440
1441                 default:
1442                         /* For special chars we prefer octal over
1443                          * hexadecimal encoding, simply because glib's
1444                          * g_strescape() does the same */
1445                         if ((*f < ' ') || (*f >= 127)) {
1446                                 *(t++) = '\\';
1447                                 *(t++) = octchar((unsigned char) *f >> 6);
1448                                 *(t++) = octchar((unsigned char) *f >> 3);
1449                                 *(t++) = octchar((unsigned char) *f);
1450                         } else
1451                                 *(t++) = *f;
1452                         break;
1453                 }
1454
1455         *t = 0;
1456
1457         return r;
1458 }
1459
1460 char *cunescape_length(const char *s, size_t length) {
1461         char *r, *t;
1462         const char *f;
1463
1464         assert(s);
1465
1466         /* Undoes C style string escaping */
1467
1468         if (!(r = new(char, length+1)))
1469                 return r;
1470
1471         for (f = s, t = r; f < s + length; f++) {
1472
1473                 if (*f != '\\') {
1474                         *(t++) = *f;
1475                         continue;
1476                 }
1477
1478                 f++;
1479
1480                 switch (*f) {
1481
1482                 case 'a':
1483                         *(t++) = '\a';
1484                         break;
1485                 case 'b':
1486                         *(t++) = '\b';
1487                         break;
1488                 case 'f':
1489                         *(t++) = '\f';
1490                         break;
1491                 case 'n':
1492                         *(t++) = '\n';
1493                         break;
1494                 case 'r':
1495                         *(t++) = '\r';
1496                         break;
1497                 case 't':
1498                         *(t++) = '\t';
1499                         break;
1500                 case 'v':
1501                         *(t++) = '\v';
1502                         break;
1503                 case '\\':
1504                         *(t++) = '\\';
1505                         break;
1506                 case '"':
1507                         *(t++) = '"';
1508                         break;
1509                 case '\'':
1510                         *(t++) = '\'';
1511                         break;
1512
1513                 case 's':
1514                         /* This is an extension of the XDG syntax files */
1515                         *(t++) = ' ';
1516                         break;
1517
1518                 case 'x': {
1519                         /* hexadecimal encoding */
1520                         int a, b;
1521
1522                         if ((a = unhexchar(f[1])) < 0 ||
1523                             (b = unhexchar(f[2])) < 0) {
1524                                 /* Invalid escape code, let's take it literal then */
1525                                 *(t++) = '\\';
1526                                 *(t++) = 'x';
1527                         } else {
1528                                 *(t++) = (char) ((a << 4) | b);
1529                                 f += 2;
1530                         }
1531
1532                         break;
1533                 }
1534
1535                 case '0':
1536                 case '1':
1537                 case '2':
1538                 case '3':
1539                 case '4':
1540                 case '5':
1541                 case '6':
1542                 case '7': {
1543                         /* octal encoding */
1544                         int a, b, c;
1545
1546                         if ((a = unoctchar(f[0])) < 0 ||
1547                             (b = unoctchar(f[1])) < 0 ||
1548                             (c = unoctchar(f[2])) < 0) {
1549                                 /* Invalid escape code, let's take it literal then */
1550                                 *(t++) = '\\';
1551                                 *(t++) = f[0];
1552                         } else {
1553                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1554                                 f += 2;
1555                         }
1556
1557                         break;
1558                 }
1559
1560                 case 0:
1561                         /* premature end of string.*/
1562                         *(t++) = '\\';
1563                         goto finish;
1564
1565                 default:
1566                         /* Invalid escape code, let's take it literal then */
1567                         *(t++) = '\\';
1568                         *(t++) = *f;
1569                         break;
1570                 }
1571         }
1572
1573 finish:
1574         *t = 0;
1575         return r;
1576 }
1577
1578 char *cunescape(const char *s) {
1579         return cunescape_length(s, strlen(s));
1580 }
1581
1582 char *xescape(const char *s, const char *bad) {
1583         char *r, *t;
1584         const char *f;
1585
1586         /* Escapes all chars in bad, in addition to \ and all special
1587          * chars, in \xFF style escaping. May be reversed with
1588          * cunescape. */
1589
1590         if (!(r = new(char, strlen(s)*4+1)))
1591                 return NULL;
1592
1593         for (f = s, t = r; *f; f++) {
1594
1595                 if ((*f < ' ') || (*f >= 127) ||
1596                     (*f == '\\') || strchr(bad, *f)) {
1597                         *(t++) = '\\';
1598                         *(t++) = 'x';
1599                         *(t++) = hexchar(*f >> 4);
1600                         *(t++) = hexchar(*f);
1601                 } else
1602                         *(t++) = *f;
1603         }
1604
1605         *t = 0;
1606
1607         return r;
1608 }
1609
1610 char *bus_path_escape(const char *s) {
1611         char *r, *t;
1612         const char *f;
1613
1614         assert(s);
1615
1616         /* Escapes all chars that D-Bus' object path cannot deal
1617          * with. Can be reverse with bus_path_unescape() */
1618
1619         if (!(r = new(char, strlen(s)*3+1)))
1620                 return NULL;
1621
1622         for (f = s, t = r; *f; f++) {
1623
1624                 if (!(*f >= 'A' && *f <= 'Z') &&
1625                     !(*f >= 'a' && *f <= 'z') &&
1626                     !(*f >= '0' && *f <= '9')) {
1627                         *(t++) = '_';
1628                         *(t++) = hexchar(*f >> 4);
1629                         *(t++) = hexchar(*f);
1630                 } else
1631                         *(t++) = *f;
1632         }
1633
1634         *t = 0;
1635
1636         return r;
1637 }
1638
1639 char *bus_path_unescape(const char *f) {
1640         char *r, *t;
1641
1642         assert(f);
1643
1644         if (!(r = strdup(f)))
1645                 return NULL;
1646
1647         for (t = r; *f; f++) {
1648
1649                 if (*f == '_') {
1650                         int a, b;
1651
1652                         if ((a = unhexchar(f[1])) < 0 ||
1653                             (b = unhexchar(f[2])) < 0) {
1654                                 /* Invalid escape code, let's take it literal then */
1655                                 *(t++) = '_';
1656                         } else {
1657                                 *(t++) = (char) ((a << 4) | b);
1658                                 f += 2;
1659                         }
1660                 } else
1661                         *(t++) = *f;
1662         }
1663
1664         *t = 0;
1665
1666         return r;
1667 }
1668
1669 char *path_kill_slashes(char *path) {
1670         char *f, *t;
1671         bool slash = false;
1672
1673         /* Removes redundant inner and trailing slashes. Modifies the
1674          * passed string in-place.
1675          *
1676          * ///foo///bar/ becomes /foo/bar
1677          */
1678
1679         for (f = path, t = path; *f; f++) {
1680
1681                 if (*f == '/') {
1682                         slash = true;
1683                         continue;
1684                 }
1685
1686                 if (slash) {
1687                         slash = false;
1688                         *(t++) = '/';
1689                 }
1690
1691                 *(t++) = *f;
1692         }
1693
1694         /* Special rule, if we are talking of the root directory, a
1695         trailing slash is good */
1696
1697         if (t == path && slash)
1698                 *(t++) = '/';
1699
1700         *t = 0;
1701         return path;
1702 }
1703
1704 bool path_startswith(const char *path, const char *prefix) {
1705         assert(path);
1706         assert(prefix);
1707
1708         if ((path[0] == '/') != (prefix[0] == '/'))
1709                 return false;
1710
1711         for (;;) {
1712                 size_t a, b;
1713
1714                 path += strspn(path, "/");
1715                 prefix += strspn(prefix, "/");
1716
1717                 if (*prefix == 0)
1718                         return true;
1719
1720                 if (*path == 0)
1721                         return false;
1722
1723                 a = strcspn(path, "/");
1724                 b = strcspn(prefix, "/");
1725
1726                 if (a != b)
1727                         return false;
1728
1729                 if (memcmp(path, prefix, a) != 0)
1730                         return false;
1731
1732                 path += a;
1733                 prefix += b;
1734         }
1735 }
1736
1737 bool path_equal(const char *a, const char *b) {
1738         assert(a);
1739         assert(b);
1740
1741         if ((a[0] == '/') != (b[0] == '/'))
1742                 return false;
1743
1744         for (;;) {
1745                 size_t j, k;
1746
1747                 a += strspn(a, "/");
1748                 b += strspn(b, "/");
1749
1750                 if (*a == 0 && *b == 0)
1751                         return true;
1752
1753                 if (*a == 0 || *b == 0)
1754                         return false;
1755
1756                 j = strcspn(a, "/");
1757                 k = strcspn(b, "/");
1758
1759                 if (j != k)
1760                         return false;
1761
1762                 if (memcmp(a, b, j) != 0)
1763                         return false;
1764
1765                 a += j;
1766                 b += k;
1767         }
1768 }
1769
1770 char *ascii_strlower(char *t) {
1771         char *p;
1772
1773         assert(t);
1774
1775         for (p = t; *p; p++)
1776                 if (*p >= 'A' && *p <= 'Z')
1777                         *p = *p - 'A' + 'a';
1778
1779         return t;
1780 }
1781
1782 bool ignore_file(const char *filename) {
1783         assert(filename);
1784
1785         return
1786                 filename[0] == '.' ||
1787                 streq(filename, "lost+found") ||
1788                 endswith(filename, "~") ||
1789                 endswith(filename, ".rpmnew") ||
1790                 endswith(filename, ".rpmsave") ||
1791                 endswith(filename, ".rpmorig") ||
1792                 endswith(filename, ".dpkg-old") ||
1793                 endswith(filename, ".dpkg-new") ||
1794                 endswith(filename, ".swp");
1795 }
1796
1797 int fd_nonblock(int fd, bool nonblock) {
1798         int flags;
1799
1800         assert(fd >= 0);
1801
1802         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1803                 return -errno;
1804
1805         if (nonblock)
1806                 flags |= O_NONBLOCK;
1807         else
1808                 flags &= ~O_NONBLOCK;
1809
1810         if (fcntl(fd, F_SETFL, flags) < 0)
1811                 return -errno;
1812
1813         return 0;
1814 }
1815
1816 int fd_cloexec(int fd, bool cloexec) {
1817         int flags;
1818
1819         assert(fd >= 0);
1820
1821         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1822                 return -errno;
1823
1824         if (cloexec)
1825                 flags |= FD_CLOEXEC;
1826         else
1827                 flags &= ~FD_CLOEXEC;
1828
1829         if (fcntl(fd, F_SETFD, flags) < 0)
1830                 return -errno;
1831
1832         return 0;
1833 }
1834
1835 int close_all_fds(const int except[], unsigned n_except) {
1836         DIR *d;
1837         struct dirent *de;
1838         int r = 0;
1839
1840         if (!(d = opendir("/proc/self/fd")))
1841                 return -errno;
1842
1843         while ((de = readdir(d))) {
1844                 int fd = -1;
1845
1846                 if (ignore_file(de->d_name))
1847                         continue;
1848
1849                 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1850                         goto finish;
1851
1852                 if (fd < 3)
1853                         continue;
1854
1855                 if (fd == dirfd(d))
1856                         continue;
1857
1858                 if (except) {
1859                         bool found;
1860                         unsigned i;
1861
1862                         found = false;
1863                         for (i = 0; i < n_except; i++)
1864                                 if (except[i] == fd) {
1865                                         found = true;
1866                                         break;
1867                                 }
1868
1869                         if (found)
1870                                 continue;
1871                 }
1872
1873                 if ((r = close_nointr(fd)) < 0) {
1874                         /* Valgrind has its own FD and doesn't want to have it closed */
1875                         if (errno != EBADF)
1876                                 goto finish;
1877                 }
1878         }
1879
1880         r = 0;
1881
1882 finish:
1883         closedir(d);
1884         return r;
1885 }
1886
1887 bool chars_intersect(const char *a, const char *b) {
1888         const char *p;
1889
1890         /* Returns true if any of the chars in a are in b. */
1891         for (p = a; *p; p++)
1892                 if (strchr(b, *p))
1893                         return true;
1894
1895         return false;
1896 }
1897
1898 char *format_timestamp(char *buf, size_t l, usec_t t) {
1899         struct tm tm;
1900         time_t sec;
1901
1902         assert(buf);
1903         assert(l > 0);
1904
1905         if (t <= 0)
1906                 return NULL;
1907
1908         sec = (time_t) (t / USEC_PER_SEC);
1909
1910         if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1911                 return NULL;
1912
1913         return buf;
1914 }
1915
1916 char *format_timespan(char *buf, size_t l, usec_t t) {
1917         static const struct {
1918                 const char *suffix;
1919                 usec_t usec;
1920         } table[] = {
1921                 { "w", USEC_PER_WEEK },
1922                 { "d", USEC_PER_DAY },
1923                 { "h", USEC_PER_HOUR },
1924                 { "min", USEC_PER_MINUTE },
1925                 { "s", USEC_PER_SEC },
1926                 { "ms", USEC_PER_MSEC },
1927                 { "us", 1 },
1928         };
1929
1930         unsigned i;
1931         char *p = buf;
1932
1933         assert(buf);
1934         assert(l > 0);
1935
1936         if (t == (usec_t) -1)
1937                 return NULL;
1938
1939         if (t == 0) {
1940                 snprintf(p, l, "0");
1941                 p[l-1] = 0;
1942                 return p;
1943         }
1944
1945         /* The result of this function can be parsed with parse_usec */
1946
1947         for (i = 0; i < ELEMENTSOF(table); i++) {
1948                 int k;
1949                 size_t n;
1950
1951                 if (t < table[i].usec)
1952                         continue;
1953
1954                 if (l <= 1)
1955                         break;
1956
1957                 k = snprintf(p, l, "%s%llu%s", p > buf ? " " : "", (unsigned long long) (t / table[i].usec), table[i].suffix);
1958                 n = MIN((size_t) k, l);
1959
1960                 l -= n;
1961                 p += n;
1962
1963                 t %= table[i].usec;
1964         }
1965
1966         *p = 0;
1967
1968         return buf;
1969 }
1970
1971 bool fstype_is_network(const char *fstype) {
1972         static const char * const table[] = {
1973                 "cifs",
1974                 "smbfs",
1975                 "ncpfs",
1976                 "nfs",
1977                 "nfs4",
1978                 "gfs",
1979                 "gfs2"
1980         };
1981
1982         unsigned i;
1983
1984         for (i = 0; i < ELEMENTSOF(table); i++)
1985                 if (streq(table[i], fstype))
1986                         return true;
1987
1988         return false;
1989 }
1990
1991 int chvt(int vt) {
1992         int fd, r = 0;
1993
1994         if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1995                 return -errno;
1996
1997         if (vt < 0) {
1998                 int tiocl[2] = {
1999                         TIOCL_GETKMSGREDIRECT,
2000                         0
2001                 };
2002
2003                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
2004                         return -errno;
2005
2006                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
2007         }
2008
2009         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
2010                 r = -errno;
2011
2012         close_nointr_nofail(r);
2013         return r;
2014 }
2015
2016 int read_one_char(FILE *f, char *ret, bool *need_nl) {
2017         struct termios old_termios, new_termios;
2018         char c;
2019         char line[1024];
2020
2021         assert(f);
2022         assert(ret);
2023
2024         if (tcgetattr(fileno(f), &old_termios) >= 0) {
2025                 new_termios = old_termios;
2026
2027                 new_termios.c_lflag &= ~ICANON;
2028                 new_termios.c_cc[VMIN] = 1;
2029                 new_termios.c_cc[VTIME] = 0;
2030
2031                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
2032                         size_t k;
2033
2034                         k = fread(&c, 1, 1, f);
2035
2036                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
2037
2038                         if (k <= 0)
2039                                 return -EIO;
2040
2041                         if (need_nl)
2042                                 *need_nl = c != '\n';
2043
2044                         *ret = c;
2045                         return 0;
2046                 }
2047         }
2048
2049         if (!(fgets(line, sizeof(line), f)))
2050                 return -EIO;
2051
2052         truncate_nl(line);
2053
2054         if (strlen(line) != 1)
2055                 return -EBADMSG;
2056
2057         if (need_nl)
2058                 *need_nl = false;
2059
2060         *ret = line[0];
2061         return 0;
2062 }
2063
2064 int ask(char *ret, const char *replies, const char *text, ...) {
2065         assert(ret);
2066         assert(replies);
2067         assert(text);
2068
2069         for (;;) {
2070                 va_list ap;
2071                 char c;
2072                 int r;
2073                 bool need_nl = true;
2074
2075                 fputs("\x1B[1m", stdout);
2076
2077                 va_start(ap, text);
2078                 vprintf(text, ap);
2079                 va_end(ap);
2080
2081                 fputs("\x1B[0m", stdout);
2082
2083                 fflush(stdout);
2084
2085                 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
2086
2087                         if (r == -EBADMSG) {
2088                                 puts("Bad input, please try again.");
2089                                 continue;
2090                         }
2091
2092                         putchar('\n');
2093                         return r;
2094                 }
2095
2096                 if (need_nl)
2097                         putchar('\n');
2098
2099                 if (strchr(replies, c)) {
2100                         *ret = c;
2101                         return 0;
2102                 }
2103
2104                 puts("Read unexpected character, please try again.");
2105         }
2106 }
2107
2108 int reset_terminal(int fd) {
2109         struct termios termios;
2110         int r = 0;
2111         long arg;
2112
2113         /* Set terminal to some sane defaults */
2114
2115         assert(fd >= 0);
2116
2117         /* First, unlock termios */
2118         zero(termios);
2119         ioctl(fd, TIOCSLCKTRMIOS, &termios);
2120
2121         /* Disable exclusive mode, just in case */
2122         ioctl(fd, TIOCNXCL);
2123
2124         /* Enable console unicode mode */
2125         arg = K_UNICODE;
2126         ioctl(fd, KDSKBMODE, &arg);
2127
2128         if (tcgetattr(fd, &termios) < 0) {
2129                 r = -errno;
2130                 goto finish;
2131         }
2132
2133         /* We only reset the stuff that matters to the software. How
2134          * hardware is set up we don't touch assuming that somebody
2135          * else will do that for us */
2136
2137         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
2138         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
2139         termios.c_oflag |= ONLCR;
2140         termios.c_cflag |= CREAD;
2141         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
2142
2143         termios.c_cc[VINTR]    =   03;  /* ^C */
2144         termios.c_cc[VQUIT]    =  034;  /* ^\ */
2145         termios.c_cc[VERASE]   = 0177;
2146         termios.c_cc[VKILL]    =  025;  /* ^X */
2147         termios.c_cc[VEOF]     =   04;  /* ^D */
2148         termios.c_cc[VSTART]   =  021;  /* ^Q */
2149         termios.c_cc[VSTOP]    =  023;  /* ^S */
2150         termios.c_cc[VSUSP]    =  032;  /* ^Z */
2151         termios.c_cc[VLNEXT]   =  026;  /* ^V */
2152         termios.c_cc[VWERASE]  =  027;  /* ^W */
2153         termios.c_cc[VREPRINT] =  022;  /* ^R */
2154         termios.c_cc[VEOL]     =    0;
2155         termios.c_cc[VEOL2]    =    0;
2156
2157         termios.c_cc[VTIME]  = 0;
2158         termios.c_cc[VMIN]   = 1;
2159
2160         if (tcsetattr(fd, TCSANOW, &termios) < 0)
2161                 r = -errno;
2162
2163 finish:
2164         /* Just in case, flush all crap out */
2165         tcflush(fd, TCIOFLUSH);
2166
2167         return r;
2168 }
2169
2170 int open_terminal(const char *name, int mode) {
2171         int fd, r;
2172
2173         if ((fd = open(name, mode)) < 0)
2174                 return -errno;
2175
2176         if ((r = isatty(fd)) < 0) {
2177                 close_nointr_nofail(fd);
2178                 return -errno;
2179         }
2180
2181         if (!r) {
2182                 close_nointr_nofail(fd);
2183                 return -ENOTTY;
2184         }
2185
2186         return fd;
2187 }
2188
2189 int flush_fd(int fd) {
2190         struct pollfd pollfd;
2191
2192         zero(pollfd);
2193         pollfd.fd = fd;
2194         pollfd.events = POLLIN;
2195
2196         for (;;) {
2197                 char buf[1024];
2198                 ssize_t l;
2199                 int r;
2200
2201                 if ((r = poll(&pollfd, 1, 0)) < 0) {
2202
2203                         if (errno == EINTR)
2204                                 continue;
2205
2206                         return -errno;
2207                 }
2208
2209                 if (r == 0)
2210                         return 0;
2211
2212                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
2213
2214                         if (errno == EINTR)
2215                                 continue;
2216
2217                         if (errno == EAGAIN)
2218                                 return 0;
2219
2220                         return -errno;
2221                 }
2222
2223                 if (l <= 0)
2224                         return 0;
2225         }
2226 }
2227
2228 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
2229         int fd = -1, notify = -1, r, wd = -1;
2230
2231         assert(name);
2232
2233         /* We use inotify to be notified when the tty is closed. We
2234          * create the watch before checking if we can actually acquire
2235          * it, so that we don't lose any event.
2236          *
2237          * Note: strictly speaking this actually watches for the
2238          * device being closed, it does *not* really watch whether a
2239          * tty loses its controlling process. However, unless some
2240          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2241          * its tty otherwise this will not become a problem. As long
2242          * as the administrator makes sure not configure any service
2243          * on the same tty as an untrusted user this should not be a
2244          * problem. (Which he probably should not do anyway.) */
2245
2246         if (!fail && !force) {
2247                 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
2248                         r = -errno;
2249                         goto fail;
2250                 }
2251
2252                 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
2253                         r = -errno;
2254                         goto fail;
2255                 }
2256         }
2257
2258         for (;;) {
2259                 if (notify >= 0)
2260                         if ((r = flush_fd(notify)) < 0)
2261                                 goto fail;
2262
2263                 /* We pass here O_NOCTTY only so that we can check the return
2264                  * value TIOCSCTTY and have a reliable way to figure out if we
2265                  * successfully became the controlling process of the tty */
2266                 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
2267                         return -errno;
2268
2269                 /* First, try to get the tty */
2270                 r = ioctl(fd, TIOCSCTTY, force);
2271
2272                 /* Sometimes it makes sense to ignore TIOCSCTTY
2273                  * returning EPERM, i.e. when very likely we already
2274                  * are have this controlling terminal. */
2275                 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
2276                         r = 0;
2277
2278                 if (r < 0 && (force || fail || errno != EPERM)) {
2279                         r = -errno;
2280                         goto fail;
2281                 }
2282
2283                 if (r >= 0)
2284                         break;
2285
2286                 assert(!fail);
2287                 assert(!force);
2288                 assert(notify >= 0);
2289
2290                 for (;;) {
2291                         struct inotify_event e;
2292                         ssize_t l;
2293
2294                         if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
2295
2296                                 if (l < 0) {
2297
2298                                         if (errno == EINTR)
2299                                                 continue;
2300
2301                                         r = -errno;
2302                                 } else
2303                                         r = -EIO;
2304
2305                                 goto fail;
2306                         }
2307
2308                         if (e.wd != wd || !(e.mask & IN_CLOSE)) {
2309                                 r = -EIO;
2310                                 goto fail;
2311                         }
2312
2313                         break;
2314                 }
2315
2316                 /* We close the tty fd here since if the old session
2317                  * ended our handle will be dead. It's important that
2318                  * we do this after sleeping, so that we don't enter
2319                  * an endless loop. */
2320                 close_nointr_nofail(fd);
2321         }
2322
2323         if (notify >= 0)
2324                 close_nointr_nofail(notify);
2325
2326         if ((r = reset_terminal(fd)) < 0)
2327                 log_warning("Failed to reset terminal: %s", strerror(-r));
2328
2329         return fd;
2330
2331 fail:
2332         if (fd >= 0)
2333                 close_nointr_nofail(fd);
2334
2335         if (notify >= 0)
2336                 close_nointr_nofail(notify);
2337
2338         return r;
2339 }
2340
2341 int release_terminal(void) {
2342         int r = 0, fd;
2343         struct sigaction sa_old, sa_new;
2344
2345         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
2346                 return -errno;
2347
2348         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2349          * by our own TIOCNOTTY */
2350
2351         zero(sa_new);
2352         sa_new.sa_handler = SIG_IGN;
2353         sa_new.sa_flags = SA_RESTART;
2354         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
2355
2356         if (ioctl(fd, TIOCNOTTY) < 0)
2357                 r = -errno;
2358
2359         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
2360
2361         close_nointr_nofail(fd);
2362         return r;
2363 }
2364
2365 int sigaction_many(const struct sigaction *sa, ...) {
2366         va_list ap;
2367         int r = 0, sig;
2368
2369         va_start(ap, sa);
2370         while ((sig = va_arg(ap, int)) > 0)
2371                 if (sigaction(sig, sa, NULL) < 0)
2372                         r = -errno;
2373         va_end(ap);
2374
2375         return r;
2376 }
2377
2378 int ignore_signals(int sig, ...) {
2379         struct sigaction sa;
2380         va_list ap;
2381         int r = 0;
2382
2383         zero(sa);
2384         sa.sa_handler = SIG_IGN;
2385         sa.sa_flags = SA_RESTART;
2386
2387         if (sigaction(sig, &sa, NULL) < 0)
2388                 r = -errno;
2389
2390         va_start(ap, sig);
2391         while ((sig = va_arg(ap, int)) > 0)
2392                 if (sigaction(sig, &sa, NULL) < 0)
2393                         r = -errno;
2394         va_end(ap);
2395
2396         return r;
2397 }
2398
2399 int default_signals(int sig, ...) {
2400         struct sigaction sa;
2401         va_list ap;
2402         int r = 0;
2403
2404         zero(sa);
2405         sa.sa_handler = SIG_DFL;
2406         sa.sa_flags = SA_RESTART;
2407
2408         if (sigaction(sig, &sa, NULL) < 0)
2409                 r = -errno;
2410
2411         va_start(ap, sig);
2412         while ((sig = va_arg(ap, int)) > 0)
2413                 if (sigaction(sig, &sa, NULL) < 0)
2414                         r = -errno;
2415         va_end(ap);
2416
2417         return r;
2418 }
2419
2420 int close_pipe(int p[]) {
2421         int a = 0, b = 0;
2422
2423         assert(p);
2424
2425         if (p[0] >= 0) {
2426                 a = close_nointr(p[0]);
2427                 p[0] = -1;
2428         }
2429
2430         if (p[1] >= 0) {
2431                 b = close_nointr(p[1]);
2432                 p[1] = -1;
2433         }
2434
2435         return a < 0 ? a : b;
2436 }
2437
2438 ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
2439         uint8_t *p;
2440         ssize_t n = 0;
2441
2442         assert(fd >= 0);
2443         assert(buf);
2444
2445         p = buf;
2446
2447         while (nbytes > 0) {
2448                 ssize_t k;
2449
2450                 if ((k = read(fd, p, nbytes)) <= 0) {
2451
2452                         if (k < 0 && errno == EINTR)
2453                                 continue;
2454
2455                         if (k < 0 && errno == EAGAIN && do_poll) {
2456                                 struct pollfd pollfd;
2457
2458                                 zero(pollfd);
2459                                 pollfd.fd = fd;
2460                                 pollfd.events = POLLIN;
2461
2462                                 if (poll(&pollfd, 1, -1) < 0) {
2463                                         if (errno == EINTR)
2464                                                 continue;
2465
2466                                         return n > 0 ? n : -errno;
2467                                 }
2468
2469                                 if (pollfd.revents != POLLIN)
2470                                         return n > 0 ? n : -EIO;
2471
2472                                 continue;
2473                         }
2474
2475                         return n > 0 ? n : (k < 0 ? -errno : 0);
2476                 }
2477
2478                 p += k;
2479                 nbytes -= k;
2480                 n += k;
2481         }
2482
2483         return n;
2484 }
2485
2486 ssize_t loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
2487         const uint8_t *p;
2488         ssize_t n = 0;
2489
2490         assert(fd >= 0);
2491         assert(buf);
2492
2493         p = buf;
2494
2495         while (nbytes > 0) {
2496                 ssize_t k;
2497
2498                 if ((k = write(fd, p, nbytes)) <= 0) {
2499
2500                         if (k < 0 && errno == EINTR)
2501                                 continue;
2502
2503                         if (k < 0 && errno == EAGAIN && do_poll) {
2504                                 struct pollfd pollfd;
2505
2506                                 zero(pollfd);
2507                                 pollfd.fd = fd;
2508                                 pollfd.events = POLLOUT;
2509
2510                                 if (poll(&pollfd, 1, -1) < 0) {
2511                                         if (errno == EINTR)
2512                                                 continue;
2513
2514                                         return n > 0 ? n : -errno;
2515                                 }
2516
2517                                 if (pollfd.revents != POLLOUT)
2518                                         return n > 0 ? n : -EIO;
2519
2520                                 continue;
2521                         }
2522
2523                         return n > 0 ? n : (k < 0 ? -errno : 0);
2524                 }
2525
2526                 p += k;
2527                 nbytes -= k;
2528                 n += k;
2529         }
2530
2531         return n;
2532 }
2533
2534 int path_is_mount_point(const char *t) {
2535         struct stat a, b;
2536         char *parent;
2537         int r;
2538
2539         if (lstat(t, &a) < 0) {
2540                 if (errno == ENOENT)
2541                         return 0;
2542
2543                 return -errno;
2544         }
2545
2546         if ((r = parent_of_path(t, &parent)) < 0)
2547                 return r;
2548
2549         r = lstat(parent, &b);
2550         free(parent);
2551
2552         if (r < 0)
2553                 return -errno;
2554
2555         return a.st_dev != b.st_dev;
2556 }
2557
2558 int parse_usec(const char *t, usec_t *usec) {
2559         static const struct {
2560                 const char *suffix;
2561                 usec_t usec;
2562         } table[] = {
2563                 { "sec", USEC_PER_SEC },
2564                 { "s", USEC_PER_SEC },
2565                 { "min", USEC_PER_MINUTE },
2566                 { "hr", USEC_PER_HOUR },
2567                 { "h", USEC_PER_HOUR },
2568                 { "d", USEC_PER_DAY },
2569                 { "w", USEC_PER_WEEK },
2570                 { "msec", USEC_PER_MSEC },
2571                 { "ms", USEC_PER_MSEC },
2572                 { "m", USEC_PER_MINUTE },
2573                 { "usec", 1ULL },
2574                 { "us", 1ULL },
2575                 { "", USEC_PER_SEC },
2576         };
2577
2578         const char *p;
2579         usec_t r = 0;
2580
2581         assert(t);
2582         assert(usec);
2583
2584         p = t;
2585         do {
2586                 long long l;
2587                 char *e;
2588                 unsigned i;
2589
2590                 errno = 0;
2591                 l = strtoll(p, &e, 10);
2592
2593                 if (errno != 0)
2594                         return -errno;
2595
2596                 if (l < 0)
2597                         return -ERANGE;
2598
2599                 if (e == p)
2600                         return -EINVAL;
2601
2602                 e += strspn(e, WHITESPACE);
2603
2604                 for (i = 0; i < ELEMENTSOF(table); i++)
2605                         if (startswith(e, table[i].suffix)) {
2606                                 r += (usec_t) l * table[i].usec;
2607                                 p = e + strlen(table[i].suffix);
2608                                 break;
2609                         }
2610
2611                 if (i >= ELEMENTSOF(table))
2612                         return -EINVAL;
2613
2614         } while (*p != 0);
2615
2616         *usec = r;
2617
2618         return 0;
2619 }
2620
2621 int make_stdio(int fd) {
2622         int r, s, t;
2623
2624         assert(fd >= 0);
2625
2626         r = dup2(fd, STDIN_FILENO);
2627         s = dup2(fd, STDOUT_FILENO);
2628         t = dup2(fd, STDERR_FILENO);
2629
2630         if (fd >= 3)
2631                 close_nointr_nofail(fd);
2632
2633         if (r < 0 || s < 0 || t < 0)
2634                 return -errno;
2635
2636         return 0;
2637 }
2638
2639 bool is_clean_exit(int code, int status) {
2640
2641         if (code == CLD_EXITED)
2642                 return status == 0;
2643
2644         /* If a daemon does not implement handlers for some of the
2645          * signals that's not considered an unclean shutdown */
2646         if (code == CLD_KILLED)
2647                 return
2648                         status == SIGHUP ||
2649                         status == SIGINT ||
2650                         status == SIGTERM ||
2651                         status == SIGPIPE;
2652
2653         return false;
2654 }
2655
2656 bool is_device_path(const char *path) {
2657
2658         /* Returns true on paths that refer to a device, either in
2659          * sysfs or in /dev */
2660
2661         return
2662                 path_startswith(path, "/dev/") ||
2663                 path_startswith(path, "/sys/");
2664 }
2665
2666 int dir_is_empty(const char *path) {
2667         DIR *d;
2668         int r;
2669         struct dirent buf, *de;
2670
2671         if (!(d = opendir(path)))
2672                 return -errno;
2673
2674         for (;;) {
2675                 if ((r = readdir_r(d, &buf, &de)) > 0) {
2676                         r = -r;
2677                         break;
2678                 }
2679
2680                 if (!de) {
2681                         r = 1;
2682                         break;
2683                 }
2684
2685                 if (!ignore_file(de->d_name)) {
2686                         r = 0;
2687                         break;
2688                 }
2689         }
2690
2691         closedir(d);
2692         return r;
2693 }
2694
2695 unsigned long long random_ull(void) {
2696         int fd;
2697         uint64_t ull;
2698         ssize_t r;
2699
2700         if ((fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY)) < 0)
2701                 goto fallback;
2702
2703         r = loop_read(fd, &ull, sizeof(ull), true);
2704         close_nointr_nofail(fd);
2705
2706         if (r != sizeof(ull))
2707                 goto fallback;
2708
2709         return ull;
2710
2711 fallback:
2712         return random() * RAND_MAX + random();
2713 }
2714
2715 void rename_process(const char name[8]) {
2716         assert(name);
2717
2718         prctl(PR_SET_NAME, name);
2719
2720         /* This is a like a poor man's setproctitle(). The string
2721          * passed should fit in 7 chars (i.e. the length of
2722          * "systemd") */
2723
2724         if (program_invocation_name)
2725                 strncpy(program_invocation_name, name, strlen(program_invocation_name));
2726 }
2727
2728 void sigset_add_many(sigset_t *ss, ...) {
2729         va_list ap;
2730         int sig;
2731
2732         assert(ss);
2733
2734         va_start(ap, ss);
2735         while ((sig = va_arg(ap, int)) > 0)
2736                 assert_se(sigaddset(ss, sig) == 0);
2737         va_end(ap);
2738 }
2739
2740 char* gethostname_malloc(void) {
2741         struct utsname u;
2742
2743         assert_se(uname(&u) >= 0);
2744
2745         if (u.nodename[0])
2746                 return strdup(u.nodename);
2747
2748         return strdup(u.sysname);
2749 }
2750
2751 int getmachineid_malloc(char **b) {
2752         int r;
2753
2754         assert(b);
2755
2756         if ((r = read_one_line_file("/var/lib/dbus/machine-id", b)) < 0)
2757                 return r;
2758
2759         strstrip(*b);
2760         return 0;
2761 }
2762
2763 char* getlogname_malloc(void) {
2764         uid_t uid;
2765         long bufsize;
2766         char *buf, *name;
2767         struct passwd pwbuf, *pw = NULL;
2768         struct stat st;
2769
2770         if (isatty(STDIN_FILENO) && fstat(STDIN_FILENO, &st) >= 0)
2771                 uid = st.st_uid;
2772         else
2773                 uid = getuid();
2774
2775         /* Shortcut things to avoid NSS lookups */
2776         if (uid == 0)
2777                 return strdup("root");
2778
2779         if ((bufsize = sysconf(_SC_GETPW_R_SIZE_MAX)) <= 0)
2780                 bufsize = 4096;
2781
2782         if (!(buf = malloc(bufsize)))
2783                 return NULL;
2784
2785         if (getpwuid_r(uid, &pwbuf, buf, bufsize, &pw) == 0 && pw) {
2786                 name = strdup(pw->pw_name);
2787                 free(buf);
2788                 return name;
2789         }
2790
2791         free(buf);
2792
2793         if (asprintf(&name, "%lu", (unsigned long) uid) < 0)
2794                 return NULL;
2795
2796         return name;
2797 }
2798
2799 int getttyname_malloc(char **r) {
2800         char path[PATH_MAX], *p, *c;
2801
2802         assert(r);
2803
2804         if (ttyname_r(STDIN_FILENO, path, sizeof(path)) < 0)
2805                 return -errno;
2806
2807         char_array_0(path);
2808
2809         p = path;
2810         if (startswith(path, "/dev/"))
2811                 p += 5;
2812
2813         if (!(c = strdup(p)))
2814                 return -ENOMEM;
2815
2816         *r = c;
2817         return 0;
2818 }
2819
2820 static int rm_rf_children(int fd, bool only_dirs) {
2821         DIR *d;
2822         int ret = 0;
2823
2824         assert(fd >= 0);
2825
2826         /* This returns the first error we run into, but nevertheless
2827          * tries to go on */
2828
2829         if (!(d = fdopendir(fd))) {
2830                 close_nointr_nofail(fd);
2831
2832                 return errno == ENOENT ? 0 : -errno;
2833         }
2834
2835         for (;;) {
2836                 struct dirent buf, *de;
2837                 bool is_dir;
2838                 int r;
2839
2840                 if ((r = readdir_r(d, &buf, &de)) != 0) {
2841                         if (ret == 0)
2842                                 ret = -r;
2843                         break;
2844                 }
2845
2846                 if (!de)
2847                         break;
2848
2849                 if (streq(de->d_name, ".") || streq(de->d_name, ".."))
2850                         continue;
2851
2852                 if (de->d_type == DT_UNKNOWN) {
2853                         struct stat st;
2854
2855                         if (fstatat(fd, de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0) {
2856                                 if (ret == 0 && errno != ENOENT)
2857                                         ret = -errno;
2858                                 continue;
2859                         }
2860
2861                         is_dir = S_ISDIR(st.st_mode);
2862                 } else
2863                         is_dir = de->d_type == DT_DIR;
2864
2865                 if (is_dir) {
2866                         int subdir_fd;
2867
2868                         if ((subdir_fd = openat(fd, de->d_name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2869                                 if (ret == 0 && errno != ENOENT)
2870                                         ret = -errno;
2871                                 continue;
2872                         }
2873
2874                         if ((r = rm_rf_children(subdir_fd, only_dirs)) < 0) {
2875                                 if (ret == 0)
2876                                         ret = r;
2877                         }
2878
2879                         if (unlinkat(fd, de->d_name, AT_REMOVEDIR) < 0) {
2880                                 if (ret == 0 && errno != ENOENT)
2881                                         ret = -errno;
2882                         }
2883                 } else  if (!only_dirs) {
2884
2885                         if (unlinkat(fd, de->d_name, 0) < 0) {
2886                                 if (ret == 0 && errno != ENOENT)
2887                                         ret = -errno;
2888                         }
2889                 }
2890         }
2891
2892         closedir(d);
2893
2894         return ret;
2895 }
2896
2897 int rm_rf(const char *path, bool only_dirs, bool delete_root) {
2898         int fd;
2899         int r;
2900
2901         assert(path);
2902
2903         if ((fd = open(path, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC)) < 0) {
2904
2905                 if (errno != ENOTDIR)
2906                         return -errno;
2907
2908                 if (delete_root && !only_dirs)
2909                         if (unlink(path) < 0)
2910                                 return -errno;
2911
2912                 return 0;
2913         }
2914
2915         r = rm_rf_children(fd, only_dirs);
2916
2917         if (delete_root)
2918                 if (rmdir(path) < 0) {
2919                         if (r == 0)
2920                                 r = -errno;
2921                 }
2922
2923         return r;
2924 }
2925
2926 int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
2927         assert(path);
2928
2929         /* Under the assumption that we are running privileged we
2930          * first change the access mode and only then hand out
2931          * ownership to avoid a window where access is too open. */
2932
2933         if (chmod(path, mode) < 0)
2934                 return -errno;
2935
2936         if (chown(path, uid, gid) < 0)
2937                 return -errno;
2938
2939         return 0;
2940 }
2941
2942 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
2943         cpu_set_t *r;
2944         unsigned n = 1024;
2945
2946         /* Allocates the cpuset in the right size */
2947
2948         for (;;) {
2949                 if (!(r = CPU_ALLOC(n)))
2950                         return NULL;
2951
2952                 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), r) >= 0) {
2953                         CPU_ZERO_S(CPU_ALLOC_SIZE(n), r);
2954
2955                         if (ncpus)
2956                                 *ncpus = n;
2957
2958                         return r;
2959                 }
2960
2961                 CPU_FREE(r);
2962
2963                 if (errno != EINVAL)
2964                         return NULL;
2965
2966                 n *= 2;
2967         }
2968 }
2969
2970 void status_vprintf(const char *format, va_list ap) {
2971         char *s = NULL;
2972         int fd = -1;
2973
2974         assert(format);
2975
2976         /* This independent of logging, as status messages are
2977          * optional and go exclusively to the console. */
2978
2979         if (vasprintf(&s, format, ap) < 0)
2980                 goto finish;
2981
2982         if ((fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC)) < 0)
2983                 goto finish;
2984
2985         write(fd, s, strlen(s));
2986
2987 finish:
2988         free(s);
2989
2990         if (fd >= 0)
2991                 close_nointr_nofail(fd);
2992 }
2993
2994 void status_printf(const char *format, ...) {
2995         va_list ap;
2996
2997         assert(format);
2998
2999         va_start(ap, format);
3000         status_vprintf(format, ap);
3001         va_end(ap);
3002 }
3003
3004 void status_welcome(void) {
3005
3006 #if defined(TARGET_FEDORA)
3007         char *r;
3008
3009         if (read_one_line_file("/etc/system-release", &r) < 0)
3010                 return;
3011
3012         truncate_nl(r);
3013
3014         /* This tries to mimic the color magic the old Red Hat sysinit
3015          * script did. */
3016
3017         if (startswith(r, "Red Hat"))
3018                 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r); /* Red for RHEL */
3019         else if (startswith(r, "Fedora"))
3020                 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r); /* Blue for Fedora */
3021         else
3022                 status_printf("Welcome to %s!\n", r);
3023
3024         free(r);
3025
3026 #elif defined(TARGET_SUSE)
3027         char *r;
3028
3029         if (read_one_line_file("/etc/SuSE-release", &r) < 0)
3030                 return;
3031
3032         truncate_nl(r);
3033
3034         status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r); /* Green for SUSE */
3035         free(r);
3036 #else
3037 #warning "You probably should add a welcome text logic here."
3038 #endif
3039 }
3040
3041 char *replace_env(const char *format, char **env) {
3042         enum {
3043                 WORD,
3044                 CURLY,
3045                 VARIABLE
3046         } state = WORD;
3047
3048         const char *e, *word = format;
3049         char *r = NULL, *k;
3050
3051         assert(format);
3052
3053         for (e = format; *e; e ++) {
3054
3055                 switch (state) {
3056
3057                 case WORD:
3058                         if (*e == '$')
3059                                 state = CURLY;
3060                         break;
3061
3062                 case CURLY:
3063                         if (*e == '{') {
3064                                 if (!(k = strnappend(r, word, e-word-1)))
3065                                         goto fail;
3066
3067                                 free(r);
3068                                 r = k;
3069
3070                                 word = e-1;
3071                                 state = VARIABLE;
3072
3073                         } else if (*e == '$') {
3074                                 if (!(k = strnappend(r, word, e-word)))
3075                                         goto fail;
3076
3077                                 free(r);
3078                                 r = k;
3079
3080                                 word = e+1;
3081                                 state = WORD;
3082                         } else
3083                                 state = WORD;
3084                         break;
3085
3086                 case VARIABLE:
3087                         if (*e == '}') {
3088                                 const char *t;
3089
3090                                 if (!(t = strv_env_get_with_length(env, word+2, e-word-2)))
3091                                         t = "";
3092
3093                                 if (!(k = strappend(r, t)))
3094                                         goto fail;
3095
3096                                 free(r);
3097                                 r = k;
3098
3099                                 word = e+1;
3100                                 state = WORD;
3101                         }
3102                         break;
3103                 }
3104         }
3105
3106         if (!(k = strnappend(r, word, e-word)))
3107                 goto fail;
3108
3109         free(r);
3110         return k;
3111
3112 fail:
3113         free(r);
3114         return NULL;
3115 }
3116
3117 char **replace_env_argv(char **argv, char **env) {
3118         char **r, **i;
3119         unsigned k = 0, l = 0;
3120
3121         l = strv_length(argv);
3122
3123         if (!(r = new(char*, l+1)))
3124                 return NULL;
3125
3126         STRV_FOREACH(i, argv) {
3127
3128                 /* If $FOO appears as single word, replace it by the split up variable */
3129                 if ((*i)[0] == '$' && (*i)[1] != '{') {
3130                         char *e;
3131                         char **w, **m;
3132                         unsigned q;
3133
3134                         if ((e = strv_env_get(env, *i+1))) {
3135
3136                                 if (!(m = strv_split_quoted(e))) {
3137                                         r[k] = NULL;
3138                                         strv_free(r);
3139                                         return NULL;
3140                                 }
3141                         } else
3142                                 m = NULL;
3143
3144                         q = strv_length(m);
3145                         l = l + q - 1;
3146
3147                         if (!(w = realloc(r, sizeof(char*) * (l+1)))) {
3148                                 r[k] = NULL;
3149                                 strv_free(r);
3150                                 strv_free(m);
3151                                 return NULL;
3152                         }
3153
3154                         r = w;
3155                         if (m) {
3156                                 memcpy(r + k, m, q * sizeof(char*));
3157                                 free(m);
3158                         }
3159
3160                         k += q;
3161                         continue;
3162                 }
3163
3164                 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3165                 if (!(r[k++] = replace_env(*i, env))) {
3166                         strv_free(r);
3167                         return NULL;
3168                 }
3169         }
3170
3171         r[k] = NULL;
3172         return r;
3173 }
3174
3175 int columns(void) {
3176         static __thread int parsed_columns = 0;
3177         const char *e;
3178
3179         if (parsed_columns > 0)
3180                 return parsed_columns;
3181
3182         if ((e = getenv("COLUMNS")))
3183                 parsed_columns = atoi(e);
3184
3185         if (parsed_columns <= 0) {
3186                 struct winsize ws;
3187                 zero(ws);
3188
3189                 if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) >= 0)
3190                         parsed_columns = ws.ws_col;
3191         }
3192
3193         if (parsed_columns <= 0)
3194                 parsed_columns = 80;
3195
3196         return parsed_columns;
3197 }
3198
3199 int running_in_chroot(void) {
3200         struct stat a, b;
3201
3202         zero(a);
3203         zero(b);
3204
3205         /* Only works as root */
3206
3207         if (stat("/proc/1/root", &a) < 0)
3208                 return -errno;
3209
3210         if (stat("/", &b) < 0)
3211                 return -errno;
3212
3213         return
3214                 a.st_dev != b.st_dev ||
3215                 a.st_ino != b.st_ino;
3216 }
3217
3218 char *ellipsize(const char *s, unsigned length, unsigned percent) {
3219         size_t l, x;
3220         char *r;
3221
3222         assert(s);
3223         assert(percent <= 100);
3224         assert(length >= 3);
3225
3226         l = strlen(s);
3227
3228         if (l <= 3 || l <= length)
3229                 return strdup(s);
3230
3231         if (!(r = new0(char, length+1)))
3232                 return r;
3233
3234         x = (length * percent) / 100;
3235
3236         if (x > length - 3)
3237                 x = length - 3;
3238
3239         memcpy(r, s, x);
3240         r[x] = '.';
3241         r[x+1] = '.';
3242         r[x+2] = '.';
3243         memcpy(r + x + 3,
3244                s + l - (length - x - 3),
3245                length - x - 3);
3246
3247         return r;
3248 }
3249
3250 static const char *const ioprio_class_table[] = {
3251         [IOPRIO_CLASS_NONE] = "none",
3252         [IOPRIO_CLASS_RT] = "realtime",
3253         [IOPRIO_CLASS_BE] = "best-effort",
3254         [IOPRIO_CLASS_IDLE] = "idle"
3255 };
3256
3257 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
3258
3259 static const char *const sigchld_code_table[] = {
3260         [CLD_EXITED] = "exited",
3261         [CLD_KILLED] = "killed",
3262         [CLD_DUMPED] = "dumped",
3263         [CLD_TRAPPED] = "trapped",
3264         [CLD_STOPPED] = "stopped",
3265         [CLD_CONTINUED] = "continued",
3266 };
3267
3268 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
3269
3270 static const char *const log_facility_table[LOG_NFACILITIES] = {
3271         [LOG_FAC(LOG_KERN)] = "kern",
3272         [LOG_FAC(LOG_USER)] = "user",
3273         [LOG_FAC(LOG_MAIL)] = "mail",
3274         [LOG_FAC(LOG_DAEMON)] = "daemon",
3275         [LOG_FAC(LOG_AUTH)] = "auth",
3276         [LOG_FAC(LOG_SYSLOG)] = "syslog",
3277         [LOG_FAC(LOG_LPR)] = "lpr",
3278         [LOG_FAC(LOG_NEWS)] = "news",
3279         [LOG_FAC(LOG_UUCP)] = "uucp",
3280         [LOG_FAC(LOG_CRON)] = "cron",
3281         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
3282         [LOG_FAC(LOG_FTP)] = "ftp",
3283         [LOG_FAC(LOG_LOCAL0)] = "local0",
3284         [LOG_FAC(LOG_LOCAL1)] = "local1",
3285         [LOG_FAC(LOG_LOCAL2)] = "local2",
3286         [LOG_FAC(LOG_LOCAL3)] = "local3",
3287         [LOG_FAC(LOG_LOCAL4)] = "local4",
3288         [LOG_FAC(LOG_LOCAL5)] = "local5",
3289         [LOG_FAC(LOG_LOCAL6)] = "local6",
3290         [LOG_FAC(LOG_LOCAL7)] = "local7"
3291 };
3292
3293 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
3294
3295 static const char *const log_level_table[] = {
3296         [LOG_EMERG] = "emerg",
3297         [LOG_ALERT] = "alert",
3298         [LOG_CRIT] = "crit",
3299         [LOG_ERR] = "err",
3300         [LOG_WARNING] = "warning",
3301         [LOG_NOTICE] = "notice",
3302         [LOG_INFO] = "info",
3303         [LOG_DEBUG] = "debug"
3304 };
3305
3306 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
3307
3308 static const char* const sched_policy_table[] = {
3309         [SCHED_OTHER] = "other",
3310         [SCHED_BATCH] = "batch",
3311         [SCHED_IDLE] = "idle",
3312         [SCHED_FIFO] = "fifo",
3313         [SCHED_RR] = "rr"
3314 };
3315
3316 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
3317
3318 static const char* const rlimit_table[] = {
3319         [RLIMIT_CPU] = "LimitCPU",
3320         [RLIMIT_FSIZE] = "LimitFSIZE",
3321         [RLIMIT_DATA] = "LimitDATA",
3322         [RLIMIT_STACK] = "LimitSTACK",
3323         [RLIMIT_CORE] = "LimitCORE",
3324         [RLIMIT_RSS] = "LimitRSS",
3325         [RLIMIT_NOFILE] = "LimitNOFILE",
3326         [RLIMIT_AS] = "LimitAS",
3327         [RLIMIT_NPROC] = "LimitNPROC",
3328         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
3329         [RLIMIT_LOCKS] = "LimitLOCKS",
3330         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
3331         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
3332         [RLIMIT_NICE] = "LimitNICE",
3333         [RLIMIT_RTPRIO] = "LimitRTPRIO",
3334         [RLIMIT_RTTIME] = "LimitRTTIME"
3335 };
3336
3337 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);
3338
3339 static const char* const ip_tos_table[] = {
3340         [IPTOS_LOWDELAY] = "low-delay",
3341         [IPTOS_THROUGHPUT] = "throughput",
3342         [IPTOS_RELIABILITY] = "reliability",
3343         [IPTOS_LOWCOST] = "low-cost",
3344 };
3345
3346 DEFINE_STRING_TABLE_LOOKUP(ip_tos, int);
3347
3348 static const char *const signal_table[] = {
3349         [SIGHUP] = "HUP",
3350         [SIGINT] = "INT",
3351         [SIGQUIT] = "QUIT",
3352         [SIGILL] = "ILL",
3353         [SIGTRAP] = "TRAP",
3354         [SIGABRT] = "ABRT",
3355         [SIGBUS] = "BUS",
3356         [SIGFPE] = "FPE",
3357         [SIGKILL] = "KILL",
3358         [SIGUSR1] = "USR1",
3359         [SIGSEGV] = "SEGV",
3360         [SIGUSR2] = "USR2",
3361         [SIGPIPE] = "PIPE",
3362         [SIGALRM] = "ALRM",
3363         [SIGTERM] = "TERM",
3364         [SIGSTKFLT] = "STKFLT",
3365         [SIGCHLD] = "CHLD",
3366         [SIGCONT] = "CONT",
3367         [SIGSTOP] = "STOP",
3368         [SIGTSTP] = "TSTP",
3369         [SIGTTIN] = "TTIN",
3370         [SIGTTOU] = "TTOU",
3371         [SIGURG] = "URG",
3372         [SIGXCPU] = "XCPU",
3373         [SIGXFSZ] = "XFSZ",
3374         [SIGVTALRM] = "VTALRM",
3375         [SIGPROF] = "PROF",
3376         [SIGWINCH] = "WINCH",
3377         [SIGIO] = "IO",
3378         [SIGPWR] = "PWR",
3379         [SIGSYS] = "SYS"
3380 };
3381
3382 DEFINE_STRING_TABLE_LOOKUP(signal, int);