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