chiark / gitweb /
85a8e37d4b559aca10af667fbd6f101c577e99b4
[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
47 #include "macro.h"
48 #include "util.h"
49 #include "ioprio.h"
50 #include "missing.h"
51 #include "log.h"
52 #include "strv.h"
53
54 bool streq_ptr(const char *a, const char *b) {
55
56         /* Like streq(), but tries to make sense of NULL pointers */
57
58         if (a && b)
59                 return streq(a, b);
60
61         if (!a && !b)
62                 return true;
63
64         return false;
65 }
66
67 usec_t now(clockid_t clock_id) {
68         struct timespec ts;
69
70         assert_se(clock_gettime(clock_id, &ts) == 0);
71
72         return timespec_load(&ts);
73 }
74
75 usec_t timespec_load(const struct timespec *ts) {
76         assert(ts);
77
78         return
79                 (usec_t) ts->tv_sec * USEC_PER_SEC +
80                 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
81 }
82
83 struct timespec *timespec_store(struct timespec *ts, usec_t u)  {
84         assert(ts);
85
86         ts->tv_sec = (time_t) (u / USEC_PER_SEC);
87         ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
88
89         return ts;
90 }
91
92 usec_t timeval_load(const struct timeval *tv) {
93         assert(tv);
94
95         return
96                 (usec_t) tv->tv_sec * USEC_PER_SEC +
97                 (usec_t) tv->tv_usec;
98 }
99
100 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
101         assert(tv);
102
103         tv->tv_sec = (time_t) (u / USEC_PER_SEC);
104         tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
105
106         return tv;
107 }
108
109 bool endswith(const char *s, const char *postfix) {
110         size_t sl, pl;
111
112         assert(s);
113         assert(postfix);
114
115         sl = strlen(s);
116         pl = strlen(postfix);
117
118         if (pl == 0)
119                 return true;
120
121         if (sl < pl)
122                 return false;
123
124         return memcmp(s + sl - pl, postfix, pl) == 0;
125 }
126
127 bool startswith(const char *s, const char *prefix) {
128         size_t sl, pl;
129
130         assert(s);
131         assert(prefix);
132
133         sl = strlen(s);
134         pl = strlen(prefix);
135
136         if (pl == 0)
137                 return true;
138
139         if (sl < pl)
140                 return false;
141
142         return memcmp(s, prefix, pl) == 0;
143 }
144
145 bool startswith_no_case(const char *s, const char *prefix) {
146         size_t sl, pl;
147         unsigned i;
148
149         assert(s);
150         assert(prefix);
151
152         sl = strlen(s);
153         pl = strlen(prefix);
154
155         if (pl == 0)
156                 return true;
157
158         if (sl < pl)
159                 return false;
160
161         for(i = 0; i < pl; ++i) {
162                 if (tolower(s[i]) != tolower(prefix[i]))
163                         return false;
164         }
165
166         return true;
167 }
168
169 bool first_word(const char *s, const char *word) {
170         size_t sl, wl;
171
172         assert(s);
173         assert(word);
174
175         sl = strlen(s);
176         wl = strlen(word);
177
178         if (sl < wl)
179                 return false;
180
181         if (wl == 0)
182                 return true;
183
184         if (memcmp(s, word, wl) != 0)
185                 return false;
186
187         return s[wl] == 0 ||
188                 strchr(WHITESPACE, s[wl]);
189 }
190
191 int close_nointr(int fd) {
192         assert(fd >= 0);
193
194         for (;;) {
195                 int r;
196
197                 if ((r = close(fd)) >= 0)
198                         return r;
199
200                 if (errno != EINTR)
201                         return r;
202         }
203 }
204
205 void close_nointr_nofail(int fd) {
206         int saved_errno = errno;
207
208         /* like close_nointr() but cannot fail, and guarantees errno
209          * is unchanged */
210
211         assert_se(close_nointr(fd) == 0);
212
213         errno = saved_errno;
214 }
215
216 int parse_boolean(const char *v) {
217         assert(v);
218
219         if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
220                 return 1;
221         else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
222                 return 0;
223
224         return -EINVAL;
225 }
226
227 int safe_atou(const char *s, unsigned *ret_u) {
228         char *x = NULL;
229         unsigned long l;
230
231         assert(s);
232         assert(ret_u);
233
234         errno = 0;
235         l = strtoul(s, &x, 0);
236
237         if (!x || *x || errno)
238                 return errno ? -errno : -EINVAL;
239
240         if ((unsigned long) (unsigned) l != l)
241                 return -ERANGE;
242
243         *ret_u = (unsigned) l;
244         return 0;
245 }
246
247 int safe_atoi(const char *s, int *ret_i) {
248         char *x = NULL;
249         long l;
250
251         assert(s);
252         assert(ret_i);
253
254         errno = 0;
255         l = strtol(s, &x, 0);
256
257         if (!x || *x || errno)
258                 return errno ? -errno : -EINVAL;
259
260         if ((long) (int) l != l)
261                 return -ERANGE;
262
263         *ret_i = (int) l;
264         return 0;
265 }
266
267 int safe_atolu(const char *s, long unsigned *ret_lu) {
268         char *x = NULL;
269         unsigned long l;
270
271         assert(s);
272         assert(ret_lu);
273
274         errno = 0;
275         l = strtoul(s, &x, 0);
276
277         if (!x || *x || errno)
278                 return errno ? -errno : -EINVAL;
279
280         *ret_lu = l;
281         return 0;
282 }
283
284 int safe_atoli(const char *s, long int *ret_li) {
285         char *x = NULL;
286         long l;
287
288         assert(s);
289         assert(ret_li);
290
291         errno = 0;
292         l = strtol(s, &x, 0);
293
294         if (!x || *x || errno)
295                 return errno ? -errno : -EINVAL;
296
297         *ret_li = l;
298         return 0;
299 }
300
301 int safe_atollu(const char *s, long long unsigned *ret_llu) {
302         char *x = NULL;
303         unsigned long long l;
304
305         assert(s);
306         assert(ret_llu);
307
308         errno = 0;
309         l = strtoull(s, &x, 0);
310
311         if (!x || *x || errno)
312                 return errno ? -errno : -EINVAL;
313
314         *ret_llu = l;
315         return 0;
316 }
317
318 int safe_atolli(const char *s, long long int *ret_lli) {
319         char *x = NULL;
320         long long l;
321
322         assert(s);
323         assert(ret_lli);
324
325         errno = 0;
326         l = strtoll(s, &x, 0);
327
328         if (!x || *x || errno)
329                 return errno ? -errno : -EINVAL;
330
331         *ret_lli = l;
332         return 0;
333 }
334
335 /* Split a string into words. */
336 char *split(const char *c, size_t *l, const char *separator, char **state) {
337         char *current;
338
339         current = *state ? *state : (char*) c;
340
341         if (!*current || *c == 0)
342                 return NULL;
343
344         current += strspn(current, separator);
345         *l = strcspn(current, separator);
346         *state = current+*l;
347
348         return (char*) current;
349 }
350
351 /* Split a string into words, but consider strings enclosed in '' and
352  * "" as words even if they include spaces. */
353 char *split_quoted(const char *c, size_t *l, char **state) {
354         char *current;
355
356         current = *state ? *state : (char*) c;
357
358         if (!*current || *c == 0)
359                 return NULL;
360
361         current += strspn(current, WHITESPACE);
362
363         if (*current == '\'') {
364                 current ++;
365                 *l = strcspn(current, "'");
366                 *state = current+*l;
367
368                 if (**state == '\'')
369                         (*state)++;
370         } else if (*current == '\"') {
371                 current ++;
372                 *l = strcspn(current, "\"");
373                 *state = current+*l;
374
375                 if (**state == '\"')
376                         (*state)++;
377         } else {
378                 *l = strcspn(current, WHITESPACE);
379                 *state = current+*l;
380         }
381
382         /* FIXME: Cannot deal with strings that have spaces AND ticks
383          * in them */
384
385         return (char*) current;
386 }
387
388 char **split_path_and_make_absolute(const char *p) {
389         char **l;
390         assert(p);
391
392         if (!(l = strv_split(p, ":")))
393                 return NULL;
394
395         if (!strv_path_make_absolute_cwd(l)) {
396                 strv_free(l);
397                 return NULL;
398         }
399
400         return l;
401 }
402
403 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
404         int r;
405         FILE *f;
406         char fn[132], line[256], *p;
407         long long unsigned ppid;
408
409         assert(pid >= 0);
410         assert(_ppid);
411
412         assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%llu/stat", (unsigned long long) pid) < (int) (sizeof(fn)-1));
413         fn[sizeof(fn)-1] = 0;
414
415         if (!(f = fopen(fn, "r")))
416                 return -errno;
417
418         if (!(fgets(line, sizeof(line), f))) {
419                 r = -errno;
420                 fclose(f);
421                 return r;
422         }
423
424         fclose(f);
425
426         /* Let's skip the pid and comm fields. The latter is enclosed
427          * in () but does not escape any () in its value, so let's
428          * skip over it manually */
429
430         if (!(p = strrchr(line, ')')))
431                 return -EIO;
432
433         p++;
434
435         if (sscanf(p, " "
436                    "%*c "  /* state */
437                    "%llu ", /* ppid */
438                    &ppid) != 1)
439                 return -EIO;
440
441         if ((long long unsigned) (pid_t) ppid != ppid)
442                 return -ERANGE;
443
444         *_ppid = (pid_t) ppid;
445
446         return 0;
447 }
448
449 int write_one_line_file(const char *fn, const char *line) {
450         FILE *f;
451         int r;
452
453         assert(fn);
454         assert(line);
455
456         if (!(f = fopen(fn, "we")))
457                 return -errno;
458
459         if (fputs(line, f) < 0) {
460                 r = -errno;
461                 goto finish;
462         }
463
464         r = 0;
465 finish:
466         fclose(f);
467         return r;
468 }
469
470 int read_one_line_file(const char *fn, char **line) {
471         FILE *f;
472         int r;
473         char t[2048], *c;
474
475         assert(fn);
476         assert(line);
477
478         if (!(f = fopen(fn, "re")))
479                 return -errno;
480
481         if (!(fgets(t, sizeof(t), f))) {
482                 r = -errno;
483                 goto finish;
484         }
485
486         if (!(c = strdup(t))) {
487                 r = -ENOMEM;
488                 goto finish;
489         }
490
491         *line = c;
492         r = 0;
493
494 finish:
495         fclose(f);
496         return r;
497 }
498
499 char *truncate_nl(char *s) {
500         assert(s);
501
502         s[strcspn(s, NEWLINE)] = 0;
503         return s;
504 }
505
506 int get_process_name(pid_t pid, char **name) {
507         char *p;
508         int r;
509
510         assert(pid >= 1);
511         assert(name);
512
513         if (asprintf(&p, "/proc/%llu/comm", (unsigned long long) pid) < 0)
514                 return -ENOMEM;
515
516         r = read_one_line_file(p, name);
517         free(p);
518
519         if (r < 0)
520                 return r;
521
522         truncate_nl(*name);
523         return 0;
524 }
525
526 char *strappend(const char *s, const char *suffix) {
527         size_t a, b;
528         char *r;
529
530         assert(s);
531         assert(suffix);
532
533         a = strlen(s);
534         b = strlen(suffix);
535
536         if (!(r = new(char, a+b+1)))
537                 return NULL;
538
539         memcpy(r, s, a);
540         memcpy(r+a, suffix, b);
541         r[a+b] = 0;
542
543         return r;
544 }
545
546 int readlink_malloc(const char *p, char **r) {
547         size_t l = 100;
548
549         assert(p);
550         assert(r);
551
552         for (;;) {
553                 char *c;
554                 ssize_t n;
555
556                 if (!(c = new(char, l)))
557                         return -ENOMEM;
558
559                 if ((n = readlink(p, c, l-1)) < 0) {
560                         int ret = -errno;
561                         free(c);
562                         return ret;
563                 }
564
565                 if ((size_t) n < l-1) {
566                         c[n] = 0;
567                         *r = c;
568                         return 0;
569                 }
570
571                 free(c);
572                 l *= 2;
573         }
574 }
575
576 char *file_name_from_path(const char *p) {
577         char *r;
578
579         assert(p);
580
581         if ((r = strrchr(p, '/')))
582                 return r + 1;
583
584         return (char*) p;
585 }
586
587 bool path_is_absolute(const char *p) {
588         assert(p);
589
590         return p[0] == '/';
591 }
592
593 bool is_path(const char *p) {
594
595         return !!strchr(p, '/');
596 }
597
598 char *path_make_absolute(const char *p, const char *prefix) {
599         char *r;
600
601         assert(p);
602
603         /* Makes every item in the list an absolute path by prepending
604          * the prefix, if specified and necessary */
605
606         if (path_is_absolute(p) || !prefix)
607                 return strdup(p);
608
609         if (asprintf(&r, "%s/%s", prefix, p) < 0)
610                 return NULL;
611
612         return r;
613 }
614
615 char *path_make_absolute_cwd(const char *p) {
616         char *cwd, *r;
617
618         assert(p);
619
620         /* Similar to path_make_absolute(), but prefixes with the
621          * current working directory. */
622
623         if (path_is_absolute(p))
624                 return strdup(p);
625
626         if (!(cwd = get_current_dir_name()))
627                 return NULL;
628
629         r = path_make_absolute(p, cwd);
630         free(cwd);
631
632         return r;
633 }
634
635 char **strv_path_make_absolute_cwd(char **l) {
636         char **s;
637
638         /* Goes through every item in the string list and makes it
639          * absolute. This works in place and won't rollback any
640          * changes on failure. */
641
642         STRV_FOREACH(s, l) {
643                 char *t;
644
645                 if (!(t = path_make_absolute_cwd(*s)))
646                         return NULL;
647
648                 free(*s);
649                 *s = t;
650         }
651
652         return l;
653 }
654
655 char **strv_path_canonicalize(char **l) {
656         char **s;
657         unsigned k = 0;
658         bool enomem = false;
659
660         if (strv_isempty(l))
661                 return l;
662
663         /* Goes through every item in the string list and canonicalize
664          * the path. This works in place and won't rollback any
665          * changes on failure. */
666
667         STRV_FOREACH(s, l) {
668                 char *t, *u;
669
670                 t = path_make_absolute_cwd(*s);
671                 free(*s);
672
673                 if (!t) {
674                         enomem = true;
675                         continue;
676                 }
677
678                 errno = 0;
679                 u = canonicalize_file_name(t);
680                 free(t);
681
682                 if (!u) {
683                         if (errno == ENOMEM || !errno)
684                                 enomem = true;
685
686                         continue;
687                 }
688
689                 l[k++] = u;
690         }
691
692         l[k] = NULL;
693
694         if (enomem)
695                 return NULL;
696
697         return l;
698 }
699
700 int reset_all_signal_handlers(void) {
701         int sig;
702
703         for (sig = 1; sig < _NSIG; sig++) {
704                 struct sigaction sa;
705
706                 if (sig == SIGKILL || sig == SIGSTOP)
707                         continue;
708
709                 zero(sa);
710                 sa.sa_handler = SIG_DFL;
711                 sa.sa_flags = SA_RESTART;
712
713                 /* On Linux the first two RT signals are reserved by
714                  * glibc, and sigaction() will return EINVAL for them. */
715                 if ((sigaction(sig, &sa, NULL) < 0))
716                         if (errno != EINVAL)
717                                 return -errno;
718         }
719
720         return 0;
721 }
722
723 char *strstrip(char *s) {
724         char *e, *l = NULL;
725
726         /* Drops trailing whitespace. Modifies the string in
727          * place. Returns pointer to first non-space character */
728
729         s += strspn(s, WHITESPACE);
730
731         for (e = s; *e; e++)
732                 if (!strchr(WHITESPACE, *e))
733                         l = e;
734
735         if (l)
736                 *(l+1) = 0;
737         else
738                 *s = 0;
739
740         return s;
741 }
742
743 char *delete_chars(char *s, const char *bad) {
744         char *f, *t;
745
746         /* Drops all whitespace, regardless where in the string */
747
748         for (f = s, t = s; *f; f++) {
749                 if (strchr(bad, *f))
750                         continue;
751
752                 *(t++) = *f;
753         }
754
755         *t = 0;
756
757         return s;
758 }
759
760 char *file_in_same_dir(const char *path, const char *filename) {
761         char *e, *r;
762         size_t k;
763
764         assert(path);
765         assert(filename);
766
767         /* This removes the last component of path and appends
768          * filename, unless the latter is absolute anyway or the
769          * former isn't */
770
771         if (path_is_absolute(filename))
772                 return strdup(filename);
773
774         if (!(e = strrchr(path, '/')))
775                 return strdup(filename);
776
777         k = strlen(filename);
778         if (!(r = new(char, e-path+1+k+1)))
779                 return NULL;
780
781         memcpy(r, path, e-path+1);
782         memcpy(r+(e-path)+1, filename, k+1);
783
784         return r;
785 }
786
787 int mkdir_parents(const char *path, mode_t mode) {
788         const char *p, *e;
789
790         assert(path);
791
792         /* Creates every parent directory in the path except the last
793          * component. */
794
795         p = path + strspn(path, "/");
796         for (;;) {
797                 int r;
798                 char *t;
799
800                 e = p + strcspn(p, "/");
801                 p = e + strspn(e, "/");
802
803                 /* Is this the last component? If so, then we're
804                  * done */
805                 if (*p == 0)
806                         return 0;
807
808                 if (!(t = strndup(path, e - path)))
809                         return -ENOMEM;
810
811                 r = mkdir(t, mode);
812
813                 free(t);
814
815                 if (r < 0 && errno != EEXIST)
816                         return -errno;
817         }
818 }
819
820 int mkdir_p(const char *path, mode_t mode) {
821         int r;
822
823         /* Like mkdir -p */
824
825         if ((r = mkdir_parents(path, mode)) < 0)
826                 return r;
827
828         if (mkdir(path, mode) < 0)
829                 return -errno;
830
831         return 0;
832 }
833
834 char hexchar(int x) {
835         static const char table[16] = "0123456789abcdef";
836
837         return table[x & 15];
838 }
839
840 int unhexchar(char c) {
841
842         if (c >= '0' && c <= '9')
843                 return c - '0';
844
845         if (c >= 'a' && c <= 'f')
846                 return c - 'a' + 10;
847
848         if (c >= 'A' && c <= 'F')
849                 return c - 'A' + 10;
850
851         return -1;
852 }
853
854 char octchar(int x) {
855         return '0' + (x & 7);
856 }
857
858 int unoctchar(char c) {
859
860         if (c >= '0' && c <= '7')
861                 return c - '0';
862
863         return -1;
864 }
865
866 char decchar(int x) {
867         return '0' + (x % 10);
868 }
869
870 int undecchar(char c) {
871
872         if (c >= '0' && c <= '9')
873                 return c - '0';
874
875         return -1;
876 }
877
878 char *cescape(const char *s) {
879         char *r, *t;
880         const char *f;
881
882         assert(s);
883
884         /* Does C style string escaping. */
885
886         if (!(r = new(char, strlen(s)*4 + 1)))
887                 return NULL;
888
889         for (f = s, t = r; *f; f++)
890
891                 switch (*f) {
892
893                 case '\a':
894                         *(t++) = '\\';
895                         *(t++) = 'a';
896                         break;
897                 case '\b':
898                         *(t++) = '\\';
899                         *(t++) = 'b';
900                         break;
901                 case '\f':
902                         *(t++) = '\\';
903                         *(t++) = 'f';
904                         break;
905                 case '\n':
906                         *(t++) = '\\';
907                         *(t++) = 'n';
908                         break;
909                 case '\r':
910                         *(t++) = '\\';
911                         *(t++) = 'r';
912                         break;
913                 case '\t':
914                         *(t++) = '\\';
915                         *(t++) = 't';
916                         break;
917                 case '\v':
918                         *(t++) = '\\';
919                         *(t++) = 'v';
920                         break;
921                 case '\\':
922                         *(t++) = '\\';
923                         *(t++) = '\\';
924                         break;
925                 case '"':
926                         *(t++) = '\\';
927                         *(t++) = '"';
928                         break;
929                 case '\'':
930                         *(t++) = '\\';
931                         *(t++) = '\'';
932                         break;
933
934                 default:
935                         /* For special chars we prefer octal over
936                          * hexadecimal encoding, simply because glib's
937                          * g_strescape() does the same */
938                         if ((*f < ' ') || (*f >= 127)) {
939                                 *(t++) = '\\';
940                                 *(t++) = octchar((unsigned char) *f >> 6);
941                                 *(t++) = octchar((unsigned char) *f >> 3);
942                                 *(t++) = octchar((unsigned char) *f);
943                         } else
944                                 *(t++) = *f;
945                         break;
946                 }
947
948         *t = 0;
949
950         return r;
951 }
952
953 char *cunescape(const char *s) {
954         char *r, *t;
955         const char *f;
956
957         assert(s);
958
959         /* Undoes C style string escaping */
960
961         if (!(r = new(char, strlen(s)+1)))
962                 return r;
963
964         for (f = s, t = r; *f; f++) {
965
966                 if (*f != '\\') {
967                         *(t++) = *f;
968                         continue;
969                 }
970
971                 f++;
972
973                 switch (*f) {
974
975                 case 'a':
976                         *(t++) = '\a';
977                         break;
978                 case 'b':
979                         *(t++) = '\b';
980                         break;
981                 case 'f':
982                         *(t++) = '\f';
983                         break;
984                 case 'n':
985                         *(t++) = '\n';
986                         break;
987                 case 'r':
988                         *(t++) = '\r';
989                         break;
990                 case 't':
991                         *(t++) = '\t';
992                         break;
993                 case 'v':
994                         *(t++) = '\v';
995                         break;
996                 case '\\':
997                         *(t++) = '\\';
998                         break;
999                 case '"':
1000                         *(t++) = '"';
1001                         break;
1002                 case '\'':
1003                         *(t++) = '\'';
1004                         break;
1005
1006                 case 'x': {
1007                         /* hexadecimal encoding */
1008                         int a, b;
1009
1010                         if ((a = unhexchar(f[1])) < 0 ||
1011                             (b = unhexchar(f[2])) < 0) {
1012                                 /* Invalid escape code, let's take it literal then */
1013                                 *(t++) = '\\';
1014                                 *(t++) = 'x';
1015                         } else {
1016                                 *(t++) = (char) ((a << 4) | b);
1017                                 f += 2;
1018                         }
1019
1020                         break;
1021                 }
1022
1023                 case '0':
1024                 case '1':
1025                 case '2':
1026                 case '3':
1027                 case '4':
1028                 case '5':
1029                 case '6':
1030                 case '7': {
1031                         /* octal encoding */
1032                         int a, b, c;
1033
1034                         if ((a = unoctchar(f[0])) < 0 ||
1035                             (b = unoctchar(f[1])) < 0 ||
1036                             (c = unoctchar(f[2])) < 0) {
1037                                 /* Invalid escape code, let's take it literal then */
1038                                 *(t++) = '\\';
1039                                 *(t++) = f[0];
1040                         } else {
1041                                 *(t++) = (char) ((a << 6) | (b << 3) | c);
1042                                 f += 2;
1043                         }
1044
1045                         break;
1046                 }
1047
1048                 case 0:
1049                         /* premature end of string.*/
1050                         *(t++) = '\\';
1051                         goto finish;
1052
1053                 default:
1054                         /* Invalid escape code, let's take it literal then */
1055                         *(t++) = '\\';
1056                         *(t++) = 'f';
1057                         break;
1058                 }
1059         }
1060
1061 finish:
1062         *t = 0;
1063         return r;
1064 }
1065
1066
1067 char *xescape(const char *s, const char *bad) {
1068         char *r, *t;
1069         const char *f;
1070
1071         /* Escapes all chars in bad, in addition to \ and all special
1072          * chars, in \xFF style escaping. May be reversed with
1073          * cunescape. */
1074
1075         if (!(r = new(char, strlen(s)*4+1)))
1076                 return NULL;
1077
1078         for (f = s, t = r; *f; f++) {
1079
1080                 if ((*f < ' ') || (*f >= 127) ||
1081                     (*f == '\\') || strchr(bad, *f)) {
1082                         *(t++) = '\\';
1083                         *(t++) = 'x';
1084                         *(t++) = hexchar(*f >> 4);
1085                         *(t++) = hexchar(*f);
1086                 } else
1087                         *(t++) = *f;
1088         }
1089
1090         *t = 0;
1091
1092         return r;
1093 }
1094
1095 char *bus_path_escape(const char *s) {
1096         char *r, *t;
1097         const char *f;
1098
1099         assert(s);
1100
1101         /* Escapes all chars that D-Bus' object path cannot deal
1102          * with. Can be reverse with bus_path_unescape() */
1103
1104         if (!(r = new(char, strlen(s)*3+1)))
1105                 return NULL;
1106
1107         for (f = s, t = r; *f; f++) {
1108
1109                 if (!(*f >= 'A' && *f <= 'Z') &&
1110                     !(*f >= 'a' && *f <= 'z') &&
1111                     !(*f >= '0' && *f <= '9')) {
1112                         *(t++) = '_';
1113                         *(t++) = hexchar(*f >> 4);
1114                         *(t++) = hexchar(*f);
1115                 } else
1116                         *(t++) = *f;
1117         }
1118
1119         *t = 0;
1120
1121         return r;
1122 }
1123
1124 char *bus_path_unescape(const char *f) {
1125         char *r, *t;
1126
1127         assert(f);
1128
1129         if (!(r = strdup(f)))
1130                 return NULL;
1131
1132         for (t = r; *f; f++) {
1133
1134                 if (*f == '_') {
1135                         int a, b;
1136
1137                         if ((a = unhexchar(f[1])) < 0 ||
1138                             (b = unhexchar(f[2])) < 0) {
1139                                 /* Invalid escape code, let's take it literal then */
1140                                 *(t++) = '_';
1141                         } else {
1142                                 *(t++) = (char) ((a << 4) | b);
1143                                 f += 2;
1144                         }
1145                 } else
1146                         *(t++) = *f;
1147         }
1148
1149         *t = 0;
1150
1151         return r;
1152 }
1153
1154 char *path_kill_slashes(char *path) {
1155         char *f, *t;
1156         bool slash = false;
1157
1158         /* Removes redundant inner and trailing slashes. Modifies the
1159          * passed string in-place.
1160          *
1161          * ///foo///bar/ becomes /foo/bar
1162          */
1163
1164         for (f = path, t = path; *f; f++) {
1165
1166                 if (*f == '/') {
1167                         slash = true;
1168                         continue;
1169                 }
1170
1171                 if (slash) {
1172                         slash = false;
1173                         *(t++) = '/';
1174                 }
1175
1176                 *(t++) = *f;
1177         }
1178
1179         /* Special rule, if we are talking of the root directory, a
1180         trailing slash is good */
1181
1182         if (t == path && slash)
1183                 *(t++) = '/';
1184
1185         *t = 0;
1186         return path;
1187 }
1188
1189 bool path_startswith(const char *path, const char *prefix) {
1190         assert(path);
1191         assert(prefix);
1192
1193         if ((path[0] == '/') != (prefix[0] == '/'))
1194                 return false;
1195
1196         for (;;) {
1197                 size_t a, b;
1198
1199                 path += strspn(path, "/");
1200                 prefix += strspn(prefix, "/");
1201
1202                 if (*prefix == 0)
1203                         return true;
1204
1205                 if (*path == 0)
1206                         return false;
1207
1208                 a = strcspn(path, "/");
1209                 b = strcspn(prefix, "/");
1210
1211                 if (a != b)
1212                         return false;
1213
1214                 if (memcmp(path, prefix, a) != 0)
1215                         return false;
1216
1217                 path += a;
1218                 prefix += b;
1219         }
1220 }
1221
1222 bool path_equal(const char *a, const char *b) {
1223         assert(a);
1224         assert(b);
1225
1226         if ((a[0] == '/') != (b[0] == '/'))
1227                 return false;
1228
1229         for (;;) {
1230                 size_t j, k;
1231
1232                 a += strspn(a, "/");
1233                 b += strspn(b, "/");
1234
1235                 if (*a == 0 && *b == 0)
1236                         return true;
1237
1238                 if (*a == 0 || *b == 0)
1239                         return false;
1240
1241                 j = strcspn(a, "/");
1242                 k = strcspn(b, "/");
1243
1244                 if (j != k)
1245                         return false;
1246
1247                 if (memcmp(a, b, j) != 0)
1248                         return false;
1249
1250                 a += j;
1251                 b += k;
1252         }
1253 }
1254
1255 char *ascii_strlower(char *t) {
1256         char *p;
1257
1258         assert(t);
1259
1260         for (p = t; *p; p++)
1261                 if (*p >= 'A' && *p <= 'Z')
1262                         *p = *p - 'A' + 'a';
1263
1264         return t;
1265 }
1266
1267 bool ignore_file(const char *filename) {
1268         assert(filename);
1269
1270         return
1271                 filename[0] == '.' ||
1272                 streq(filename, "lost+found") ||
1273                 endswith(filename, "~") ||
1274                 endswith(filename, ".rpmnew") ||
1275                 endswith(filename, ".rpmsave") ||
1276                 endswith(filename, ".rpmorig") ||
1277                 endswith(filename, ".dpkg-old") ||
1278                 endswith(filename, ".dpkg-new") ||
1279                 endswith(filename, ".swp");
1280 }
1281
1282 int fd_nonblock(int fd, bool nonblock) {
1283         int flags;
1284
1285         assert(fd >= 0);
1286
1287         if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1288                 return -errno;
1289
1290         if (nonblock)
1291                 flags |= O_NONBLOCK;
1292         else
1293                 flags &= ~O_NONBLOCK;
1294
1295         if (fcntl(fd, F_SETFL, flags) < 0)
1296                 return -errno;
1297
1298         return 0;
1299 }
1300
1301 int fd_cloexec(int fd, bool cloexec) {
1302         int flags;
1303
1304         assert(fd >= 0);
1305
1306         if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1307                 return -errno;
1308
1309         if (cloexec)
1310                 flags |= FD_CLOEXEC;
1311         else
1312                 flags &= ~FD_CLOEXEC;
1313
1314         if (fcntl(fd, F_SETFD, flags) < 0)
1315                 return -errno;
1316
1317         return 0;
1318 }
1319
1320 int close_all_fds(const int except[], unsigned n_except) {
1321         DIR *d;
1322         struct dirent *de;
1323         int r = 0;
1324
1325         if (!(d = opendir("/proc/self/fd")))
1326                 return -errno;
1327
1328         while ((de = readdir(d))) {
1329                 int fd = -1;
1330
1331                 if (ignore_file(de->d_name))
1332                         continue;
1333
1334                 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1335                         goto finish;
1336
1337                 if (fd < 3)
1338                         continue;
1339
1340                 if (fd == dirfd(d))
1341                         continue;
1342
1343                 if (except) {
1344                         bool found;
1345                         unsigned i;
1346
1347                         found = false;
1348                         for (i = 0; i < n_except; i++)
1349                                 if (except[i] == fd) {
1350                                         found = true;
1351                                         break;
1352                                 }
1353
1354                         if (found)
1355                                 continue;
1356                 }
1357
1358                 if ((r = close_nointr(fd)) < 0) {
1359                         /* Valgrind has its own FD and doesn't want to have it closed */
1360                         if (errno != EBADF)
1361                                 goto finish;
1362                 }
1363         }
1364
1365         r = 0;
1366
1367 finish:
1368         closedir(d);
1369         return r;
1370 }
1371
1372 bool chars_intersect(const char *a, const char *b) {
1373         const char *p;
1374
1375         /* Returns true if any of the chars in a are in b. */
1376         for (p = a; *p; p++)
1377                 if (strchr(b, *p))
1378                         return true;
1379
1380         return false;
1381 }
1382
1383 char *format_timestamp(char *buf, size_t l, usec_t t) {
1384         struct tm tm;
1385         time_t sec;
1386
1387         assert(buf);
1388         assert(l > 0);
1389
1390         if (t <= 0)
1391                 return NULL;
1392
1393         sec = (time_t) t / USEC_PER_SEC;
1394
1395         if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1396                 return NULL;
1397
1398         return buf;
1399 }
1400
1401 bool fstype_is_network(const char *fstype) {
1402         static const char * const table[] = {
1403                 "cifs",
1404                 "smbfs",
1405                 "ncpfs",
1406                 "nfs",
1407                 "nfs4",
1408                 "gfs",
1409                 "gfs2"
1410         };
1411
1412         unsigned i;
1413
1414         for (i = 0; i < ELEMENTSOF(table); i++)
1415                 if (streq(table[i], fstype))
1416                         return true;
1417
1418         return false;
1419 }
1420
1421 int chvt(int vt) {
1422         int fd, r = 0;
1423
1424         if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1425                 return -errno;
1426
1427         if (vt < 0) {
1428                 int tiocl[2] = {
1429                         TIOCL_GETKMSGREDIRECT,
1430                         0
1431                 };
1432
1433                 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1434                         return -errno;
1435
1436                 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1437         }
1438
1439         if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1440                 r = -errno;
1441
1442         close_nointr_nofail(r);
1443         return r;
1444 }
1445
1446 int read_one_char(FILE *f, char *ret, bool *need_nl) {
1447         struct termios old_termios, new_termios;
1448         char c;
1449         char line[1024];
1450
1451         assert(f);
1452         assert(ret);
1453
1454         if (tcgetattr(fileno(f), &old_termios) >= 0) {
1455                 new_termios = old_termios;
1456
1457                 new_termios.c_lflag &= ~ICANON;
1458                 new_termios.c_cc[VMIN] = 1;
1459                 new_termios.c_cc[VTIME] = 0;
1460
1461                 if (tcsetattr(fileno(f), TCSADRAIN, &new_termios) >= 0) {
1462                         size_t k;
1463
1464                         k = fread(&c, 1, 1, f);
1465
1466                         tcsetattr(fileno(f), TCSADRAIN, &old_termios);
1467
1468                         if (k <= 0)
1469                                 return -EIO;
1470
1471                         if (need_nl)
1472                                 *need_nl = c != '\n';
1473
1474                         *ret = c;
1475                         return 0;
1476                 }
1477         }
1478
1479         if (!(fgets(line, sizeof(line), f)))
1480                 return -EIO;
1481
1482         truncate_nl(line);
1483
1484         if (strlen(line) != 1)
1485                 return -EBADMSG;
1486
1487         if (need_nl)
1488                 *need_nl = false;
1489
1490         *ret = line[0];
1491         return 0;
1492 }
1493
1494 int ask(char *ret, const char *replies, const char *text, ...) {
1495         assert(ret);
1496         assert(replies);
1497         assert(text);
1498
1499         for (;;) {
1500                 va_list ap;
1501                 char c;
1502                 int r;
1503                 bool need_nl = true;
1504
1505                 fputs("\x1B[1m", stdout);
1506
1507                 va_start(ap, text);
1508                 vprintf(text, ap);
1509                 va_end(ap);
1510
1511                 fputs("\x1B[0m", stdout);
1512
1513                 fflush(stdout);
1514
1515                 if ((r = read_one_char(stdin, &c, &need_nl)) < 0) {
1516
1517                         if (r == -EBADMSG) {
1518                                 puts("Bad input, please try again.");
1519                                 continue;
1520                         }
1521
1522                         putchar('\n');
1523                         return r;
1524                 }
1525
1526                 if (need_nl)
1527                         putchar('\n');
1528
1529                 if (strchr(replies, c)) {
1530                         *ret = c;
1531                         return 0;
1532                 }
1533
1534                 puts("Read unexpected character, please try again.");
1535         }
1536 }
1537
1538 int reset_terminal(int fd) {
1539         struct termios termios;
1540         int r = 0;
1541
1542         assert(fd >= 0);
1543
1544         /* Set terminal to some sane defaults */
1545
1546         if (tcgetattr(fd, &termios) < 0) {
1547                 r = -errno;
1548                 goto finish;
1549         }
1550
1551         /* We only reset the stuff that matters to the software. How
1552          * hardware is set up we don't touch assuming that somebody
1553          * else will do that for us */
1554
1555         termios.c_iflag &= ~(IGNBRK | BRKINT | ISTRIP | INLCR | IGNCR | IUCLC);
1556         termios.c_iflag |= ICRNL | IMAXBEL | IUTF8;
1557         termios.c_oflag |= ONLCR;
1558         termios.c_cflag |= CREAD;
1559         termios.c_lflag = ISIG | ICANON | IEXTEN | ECHO | ECHOE | ECHOK | ECHOCTL | ECHOPRT | ECHOKE;
1560
1561         termios.c_cc[VINTR]    =   03;  /* ^C */
1562         termios.c_cc[VQUIT]    =  034;  /* ^\ */
1563         termios.c_cc[VERASE]   = 0177;
1564         termios.c_cc[VKILL]    =  025;  /* ^X */
1565         termios.c_cc[VEOF]     =   04;  /* ^D */
1566         termios.c_cc[VSTART]   =  021;  /* ^Q */
1567         termios.c_cc[VSTOP]    =  023;  /* ^S */
1568         termios.c_cc[VSUSP]    =  032;  /* ^Z */
1569         termios.c_cc[VLNEXT]   =  026;  /* ^V */
1570         termios.c_cc[VWERASE]  =  027;  /* ^W */
1571         termios.c_cc[VREPRINT] =  022;  /* ^R */
1572         termios.c_cc[VEOL]     =    0;
1573         termios.c_cc[VEOL2]    =    0;
1574
1575         termios.c_cc[VTIME]  = 0;
1576         termios.c_cc[VMIN]   = 1;
1577
1578         if (tcsetattr(fd, TCSANOW, &termios) < 0)
1579                 r = -errno;
1580
1581 finish:
1582         /* Just in case, flush all crap out */
1583         tcflush(fd, TCIOFLUSH);
1584
1585         return r;
1586 }
1587
1588 int open_terminal(const char *name, int mode) {
1589         int fd, r;
1590
1591         if ((fd = open(name, mode)) < 0)
1592                 return -errno;
1593
1594         if ((r = isatty(fd)) < 0) {
1595                 close_nointr_nofail(fd);
1596                 return -errno;
1597         }
1598
1599         if (!r) {
1600                 close_nointr_nofail(fd);
1601                 return -ENOTTY;
1602         }
1603
1604         return fd;
1605 }
1606
1607 int flush_fd(int fd) {
1608         struct pollfd pollfd;
1609
1610         zero(pollfd);
1611         pollfd.fd = fd;
1612         pollfd.events = POLLIN;
1613
1614         for (;;) {
1615                 char buf[1024];
1616                 ssize_t l;
1617                 int r;
1618
1619                 if ((r = poll(&pollfd, 1, 0)) < 0) {
1620
1621                         if (errno == EINTR)
1622                                 continue;
1623
1624                         return -errno;
1625                 }
1626
1627                 if (r == 0)
1628                         return 0;
1629
1630                 if ((l = read(fd, buf, sizeof(buf))) < 0) {
1631
1632                         if (errno == EINTR)
1633                                 continue;
1634
1635                         if (errno == EAGAIN)
1636                                 return 0;
1637
1638                         return -errno;
1639                 }
1640
1641                 if (l <= 0)
1642                         return 0;
1643         }
1644 }
1645
1646 int acquire_terminal(const char *name, bool fail, bool force, bool ignore_tiocstty_eperm) {
1647         int fd = -1, notify = -1, r, wd = -1;
1648
1649         assert(name);
1650
1651         /* We use inotify to be notified when the tty is closed. We
1652          * create the watch before checking if we can actually acquire
1653          * it, so that we don't lose any event.
1654          *
1655          * Note: strictly speaking this actually watches for the
1656          * device being closed, it does *not* really watch whether a
1657          * tty loses its controlling process. However, unless some
1658          * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1659          * its tty otherwise this will not become a problem. As long
1660          * as the administrator makes sure not configure any service
1661          * on the same tty as an untrusted user this should not be a
1662          * problem. (Which he probably should not do anyway.) */
1663
1664         if (!fail && !force) {
1665                 if ((notify = inotify_init1(IN_CLOEXEC)) < 0) {
1666                         r = -errno;
1667                         goto fail;
1668                 }
1669
1670                 if ((wd = inotify_add_watch(notify, name, IN_CLOSE)) < 0) {
1671                         r = -errno;
1672                         goto fail;
1673                 }
1674         }
1675
1676         for (;;) {
1677                 if (notify >= 0)
1678                         if ((r = flush_fd(notify)) < 0)
1679                                 goto fail;
1680
1681                 /* We pass here O_NOCTTY only so that we can check the return
1682                  * value TIOCSCTTY and have a reliable way to figure out if we
1683                  * successfully became the controlling process of the tty */
1684                 if ((fd = open_terminal(name, O_RDWR|O_NOCTTY)) < 0)
1685                         return -errno;
1686
1687                 /* First, try to get the tty */
1688                 r = ioctl(fd, TIOCSCTTY, force);
1689
1690                 /* Sometimes it makes sense to ignore TIOCSCTTY
1691                  * returning EPERM, i.e. when very likely we already
1692                  * are have this controlling terminal. */
1693                 if (r < 0 && errno == EPERM && ignore_tiocstty_eperm)
1694                         r = 0;
1695
1696                 if (r < 0 && (force || fail || errno != EPERM)) {
1697                         r = -errno;
1698                         goto fail;
1699                 }
1700
1701                 if (r >= 0)
1702                         break;
1703
1704                 assert(!fail);
1705                 assert(!force);
1706                 assert(notify >= 0);
1707
1708                 for (;;) {
1709                         struct inotify_event e;
1710                         ssize_t l;
1711
1712                         if ((l = read(notify, &e, sizeof(e))) != sizeof(e)) {
1713
1714                                 if (l < 0) {
1715
1716                                         if (errno == EINTR)
1717                                                 continue;
1718
1719                                         r = -errno;
1720                                 } else
1721                                         r = -EIO;
1722
1723                                 goto fail;
1724                         }
1725
1726                         if (e.wd != wd || !(e.mask & IN_CLOSE)) {
1727                                 r = -errno;
1728                                 goto fail;
1729                         }
1730
1731                         break;
1732                 }
1733
1734                 /* We close the tty fd here since if the old session
1735                  * ended our handle will be dead. It's important that
1736                  * we do this after sleeping, so that we don't enter
1737                  * an endless loop. */
1738                 close_nointr_nofail(fd);
1739         }
1740
1741         if (notify >= 0)
1742                 close_nointr_nofail(notify);
1743
1744         if ((r = reset_terminal(fd)) < 0)
1745                 log_warning("Failed to reset terminal: %s", strerror(-r));
1746
1747         return fd;
1748
1749 fail:
1750         if (fd >= 0)
1751                 close_nointr_nofail(fd);
1752
1753         if (notify >= 0)
1754                 close_nointr_nofail(notify);
1755
1756         return r;
1757 }
1758
1759 int release_terminal(void) {
1760         int r = 0, fd;
1761         struct sigaction sa_old, sa_new;
1762
1763         if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
1764                 return -errno;
1765
1766         /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1767          * by our own TIOCNOTTY */
1768
1769         zero(sa_new);
1770         sa_new.sa_handler = SIG_IGN;
1771         sa_new.sa_flags = SA_RESTART;
1772         assert_se(sigaction(SIGHUP, &sa_new, &sa_old) == 0);
1773
1774         if (ioctl(fd, TIOCNOTTY) < 0)
1775                 r = -errno;
1776
1777         assert_se(sigaction(SIGHUP, &sa_old, NULL) == 0);
1778
1779         close_nointr_nofail(fd);
1780         return r;
1781 }
1782
1783 int sigaction_many(const struct sigaction *sa, ...) {
1784         va_list ap;
1785         int r = 0, sig;
1786
1787         va_start(ap, sa);
1788         while ((sig = va_arg(ap, int)) > 0)
1789                 if (sigaction(sig, sa, NULL) < 0)
1790                         r = -errno;
1791         va_end(ap);
1792
1793         return r;
1794 }
1795
1796 int ignore_signals(int sig, ...) {
1797         struct sigaction sa;
1798         va_list ap;
1799         int r = 0;
1800
1801         zero(sa);
1802         sa.sa_handler = SIG_IGN;
1803         sa.sa_flags = SA_RESTART;
1804
1805         if (sigaction(sig, &sa, NULL) < 0)
1806                 r = -errno;
1807
1808         va_start(ap, sig);
1809         while ((sig = va_arg(ap, int)) > 0)
1810                 if (sigaction(sig, &sa, NULL) < 0)
1811                         r = -errno;
1812         va_end(ap);
1813
1814         return r;
1815 }
1816
1817 int default_signals(int sig, ...) {
1818         struct sigaction sa;
1819         va_list ap;
1820         int r = 0;
1821
1822         zero(sa);
1823         sa.sa_handler = SIG_DFL;
1824         sa.sa_flags = SA_RESTART;
1825
1826         if (sigaction(sig, &sa, NULL) < 0)
1827                 r = -errno;
1828
1829         va_start(ap, sig);
1830         while ((sig = va_arg(ap, int)) > 0)
1831                 if (sigaction(sig, &sa, NULL) < 0)
1832                         r = -errno;
1833         va_end(ap);
1834
1835         return r;
1836 }
1837
1838 int close_pipe(int p[]) {
1839         int a = 0, b = 0;
1840
1841         assert(p);
1842
1843         if (p[0] >= 0) {
1844                 a = close_nointr(p[0]);
1845                 p[0] = -1;
1846         }
1847
1848         if (p[1] >= 0) {
1849                 b = close_nointr(p[1]);
1850                 p[1] = -1;
1851         }
1852
1853         return a < 0 ? a : b;
1854 }
1855
1856 ssize_t loop_read(int fd, void *buf, size_t nbytes) {
1857         uint8_t *p;
1858         ssize_t n = 0;
1859
1860         assert(fd >= 0);
1861         assert(buf);
1862
1863         p = buf;
1864
1865         while (nbytes > 0) {
1866                 ssize_t k;
1867
1868                 if ((k = read(fd, p, nbytes)) <= 0) {
1869
1870                         if (errno == EINTR)
1871                                 continue;
1872
1873                         if (errno == EAGAIN) {
1874                                 struct pollfd pollfd;
1875
1876                                 zero(pollfd);
1877                                 pollfd.fd = fd;
1878                                 pollfd.events = POLLIN;
1879
1880                                 if (poll(&pollfd, 1, -1) < 0) {
1881                                         if (errno == EINTR)
1882                                                 continue;
1883
1884                                         return n > 0 ? n : -errno;
1885                                 }
1886
1887                                 if (pollfd.revents != POLLIN)
1888                                         return n > 0 ? n : -EIO;
1889
1890                                 continue;
1891                         }
1892
1893                         return n > 0 ? n : (k < 0 ? -errno : 0);
1894                 }
1895
1896                 p += k;
1897                 nbytes -= k;
1898                 n += k;
1899         }
1900
1901         return n;
1902 }
1903
1904 int path_is_mount_point(const char *t) {
1905         struct stat a, b;
1906         char *copy;
1907
1908         if (lstat(t, &a) < 0) {
1909
1910                 if (errno == ENOENT)
1911                         return 0;
1912
1913                 return -errno;
1914         }
1915
1916         if (!(copy = strdup(t)))
1917                 return -ENOMEM;
1918
1919         if (lstat(dirname(copy), &b) < 0) {
1920                 free(copy);
1921                 return -errno;
1922         }
1923
1924         free(copy);
1925
1926         return a.st_dev != b.st_dev;
1927 }
1928
1929 int parse_usec(const char *t, usec_t *usec) {
1930         static const struct {
1931                 const char *suffix;
1932                 usec_t usec;
1933         } table[] = {
1934                 { "sec", USEC_PER_SEC },
1935                 { "s", USEC_PER_SEC },
1936                 { "min", USEC_PER_MINUTE },
1937                 { "hr", USEC_PER_HOUR },
1938                 { "h", USEC_PER_HOUR },
1939                 { "d", USEC_PER_DAY },
1940                 { "w", USEC_PER_WEEK },
1941                 { "msec", USEC_PER_MSEC },
1942                 { "ms", USEC_PER_MSEC },
1943                 { "m", USEC_PER_MINUTE },
1944                 { "usec", 1ULL },
1945                 { "us", 1ULL },
1946                 { "", USEC_PER_SEC },
1947         };
1948
1949         const char *p;
1950         usec_t r = 0;
1951
1952         assert(t);
1953         assert(usec);
1954
1955         p = t;
1956         do {
1957                 long long l;
1958                 char *e;
1959                 unsigned i;
1960
1961                 errno = 0;
1962                 l = strtoll(p, &e, 10);
1963
1964                 if (errno != 0)
1965                         return -errno;
1966
1967                 if (l < 0)
1968                         return -ERANGE;
1969
1970                 if (e == p)
1971                         return -EINVAL;
1972
1973                 e += strspn(e, WHITESPACE);
1974
1975                 for (i = 0; i < ELEMENTSOF(table); i++)
1976                         if (startswith(e, table[i].suffix)) {
1977                                 r += (usec_t) l * table[i].usec;
1978                                 p = e + strlen(table[i].suffix);
1979                                 break;
1980                         }
1981
1982                 if (i >= ELEMENTSOF(table))
1983                         return -EINVAL;
1984
1985         } while (*p != 0);
1986
1987         *usec = r;
1988
1989         return 0;
1990 }
1991
1992 int make_stdio(int fd) {
1993         int r, s, t;
1994
1995         assert(fd >= 0);
1996
1997         r = dup2(fd, STDIN_FILENO);
1998         s = dup2(fd, STDOUT_FILENO);
1999         t = dup2(fd, STDERR_FILENO);
2000
2001         if (fd >= 3)
2002                 close_nointr_nofail(fd);
2003
2004         if (r < 0 || s < 0 || t < 0)
2005                 return -errno;
2006
2007         return 0;
2008 }
2009
2010 bool is_clean_exit(int code, int status) {
2011
2012         if (code == CLD_EXITED)
2013                 return status == 0;
2014
2015         /* If a daemon does not implement handlers for some of the
2016          * signals that's not considered an unclean shutdown */
2017         if (code == CLD_KILLED)
2018                 return
2019                         status == SIGHUP ||
2020                         status == SIGINT ||
2021                         status == SIGTERM ||
2022                         status == SIGPIPE;
2023
2024         return false;
2025 }
2026
2027 bool is_device_path(const char *path) {
2028
2029         /* Returns true on paths that refer to a device, either in
2030          * sysfs or in /dev */
2031
2032         return
2033                 path_startswith(path, "/dev/") ||
2034                 path_startswith(path, "/sys/");
2035 }
2036
2037 static const char *const ioprio_class_table[] = {
2038         [IOPRIO_CLASS_NONE] = "none",
2039         [IOPRIO_CLASS_RT] = "realtime",
2040         [IOPRIO_CLASS_BE] = "best-effort",
2041         [IOPRIO_CLASS_IDLE] = "idle"
2042 };
2043
2044 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
2045
2046 static const char *const sigchld_code_table[] = {
2047         [CLD_EXITED] = "exited",
2048         [CLD_KILLED] = "killed",
2049         [CLD_DUMPED] = "dumped",
2050         [CLD_TRAPPED] = "trapped",
2051         [CLD_STOPPED] = "stopped",
2052         [CLD_CONTINUED] = "continued",
2053 };
2054
2055 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
2056
2057 static const char *const log_facility_table[LOG_NFACILITIES] = {
2058         [LOG_FAC(LOG_KERN)] = "kern",
2059         [LOG_FAC(LOG_USER)] = "user",
2060         [LOG_FAC(LOG_MAIL)] = "mail",
2061         [LOG_FAC(LOG_DAEMON)] = "daemon",
2062         [LOG_FAC(LOG_AUTH)] = "auth",
2063         [LOG_FAC(LOG_SYSLOG)] = "syslog",
2064         [LOG_FAC(LOG_LPR)] = "lpr",
2065         [LOG_FAC(LOG_NEWS)] = "news",
2066         [LOG_FAC(LOG_UUCP)] = "uucp",
2067         [LOG_FAC(LOG_CRON)] = "cron",
2068         [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
2069         [LOG_FAC(LOG_FTP)] = "ftp",
2070         [LOG_FAC(LOG_LOCAL0)] = "local0",
2071         [LOG_FAC(LOG_LOCAL1)] = "local1",
2072         [LOG_FAC(LOG_LOCAL2)] = "local2",
2073         [LOG_FAC(LOG_LOCAL3)] = "local3",
2074         [LOG_FAC(LOG_LOCAL4)] = "local4",
2075         [LOG_FAC(LOG_LOCAL5)] = "local5",
2076         [LOG_FAC(LOG_LOCAL6)] = "local6",
2077         [LOG_FAC(LOG_LOCAL7)] = "local7"
2078 };
2079
2080 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
2081
2082 static const char *const log_level_table[] = {
2083         [LOG_EMERG] = "emerg",
2084         [LOG_ALERT] = "alert",
2085         [LOG_CRIT] = "crit",
2086         [LOG_ERR] = "err",
2087         [LOG_WARNING] = "warning",
2088         [LOG_NOTICE] = "notice",
2089         [LOG_INFO] = "info",
2090         [LOG_DEBUG] = "debug"
2091 };
2092
2093 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
2094
2095 static const char* const sched_policy_table[] = {
2096         [SCHED_OTHER] = "other",
2097         [SCHED_BATCH] = "batch",
2098         [SCHED_IDLE] = "idle",
2099         [SCHED_FIFO] = "fifo",
2100         [SCHED_RR] = "rr"
2101 };
2102
2103 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
2104
2105 static const char* const rlimit_table[] = {
2106         [RLIMIT_CPU] = "LimitCPU",
2107         [RLIMIT_FSIZE] = "LimitFSIZE",
2108         [RLIMIT_DATA] = "LimitDATA",
2109         [RLIMIT_STACK] = "LimitSTACK",
2110         [RLIMIT_CORE] = "LimitCORE",
2111         [RLIMIT_RSS] = "LimitRSS",
2112         [RLIMIT_NOFILE] = "LimitNOFILE",
2113         [RLIMIT_AS] = "LimitAS",
2114         [RLIMIT_NPROC] = "LimitNPROC",
2115         [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
2116         [RLIMIT_LOCKS] = "LimitLOCKS",
2117         [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
2118         [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
2119         [RLIMIT_NICE] = "LimitNICE",
2120         [RLIMIT_RTPRIO] = "LimitRTPRIO",
2121         [RLIMIT_RTTIME] = "LimitRTTIME"
2122 };
2123
2124 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);