]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/util.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
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.
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.
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/>.
31 #include <sys/resource.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
37 #include <sys/ioctl.h>
39 #include <linux/tiocl.h>
42 #include <sys/inotify.h>
46 #include <sys/prctl.h>
47 #include <sys/utsname.h>
57 bool streq_ptr(const char *a
, const char *b
) {
59 /* Like streq(), but tries to make sense of NULL pointers */
70 usec_t
now(clockid_t clock_id
) {
73 assert_se(clock_gettime(clock_id
, &ts
) == 0);
75 return timespec_load(&ts
);
78 timestamp
* timestamp_get(timestamp
*ts
) {
81 ts
->realtime
= now(CLOCK_REALTIME
);
82 ts
->monotonic
= now(CLOCK_MONOTONIC
);
87 usec_t
timespec_load(const struct timespec
*ts
) {
91 (usec_t
) ts
->tv_sec
* USEC_PER_SEC
+
92 (usec_t
) ts
->tv_nsec
/ NSEC_PER_USEC
;
95 struct timespec
*timespec_store(struct timespec
*ts
, usec_t u
) {
98 ts
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
99 ts
->tv_nsec
= (long int) ((u
% USEC_PER_SEC
) * NSEC_PER_USEC
);
104 usec_t
timeval_load(const struct timeval
*tv
) {
108 (usec_t
) tv
->tv_sec
* USEC_PER_SEC
+
109 (usec_t
) tv
->tv_usec
;
112 struct timeval
*timeval_store(struct timeval
*tv
, usec_t u
) {
115 tv
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
116 tv
->tv_usec
= (suseconds_t
) (u
% USEC_PER_SEC
);
121 bool endswith(const char *s
, const char *postfix
) {
128 pl
= strlen(postfix
);
136 return memcmp(s
+ sl
- pl
, postfix
, pl
) == 0;
139 bool startswith(const char *s
, const char *prefix
) {
154 return memcmp(s
, prefix
, pl
) == 0;
157 bool startswith_no_case(const char *s
, const char *prefix
) {
173 for(i
= 0; i
< pl
; ++i
) {
174 if (tolower(s
[i
]) != tolower(prefix
[i
]))
181 bool first_word(const char *s
, const char *word
) {
196 if (memcmp(s
, word
, wl
) != 0)
200 strchr(WHITESPACE
, s
[wl
]);
203 int close_nointr(int fd
) {
209 if ((r
= close(fd
)) >= 0)
217 void close_nointr_nofail(int fd
) {
218 int saved_errno
= errno
;
220 /* like close_nointr() but cannot fail, and guarantees errno
223 assert_se(close_nointr(fd
) == 0);
228 void close_many(const int fds
[], unsigned n_fd
) {
231 for (i
= 0; i
< n_fd
; i
++)
232 close_nointr_nofail(fds
[i
]);
235 int parse_boolean(const char *v
) {
238 if (streq(v
, "1") || v
[0] == 'y' || v
[0] == 'Y' || v
[0] == 't' || v
[0] == 'T' || !strcasecmp(v
, "on"))
240 else if (streq(v
, "0") || v
[0] == 'n' || v
[0] == 'N' || v
[0] == 'f' || v
[0] == 'F' || !strcasecmp(v
, "off"))
246 int parse_pid(const char *s
, pid_t
* ret_pid
) {
254 if ((r
= safe_atolu(s
, &ul
)) < 0)
259 if ((unsigned long) pid
!= ul
)
269 int safe_atou(const char *s
, unsigned *ret_u
) {
277 l
= strtoul(s
, &x
, 0);
279 if (!x
|| *x
|| errno
)
280 return errno
? -errno
: -EINVAL
;
282 if ((unsigned long) (unsigned) l
!= l
)
285 *ret_u
= (unsigned) l
;
289 int safe_atoi(const char *s
, int *ret_i
) {
297 l
= strtol(s
, &x
, 0);
299 if (!x
|| *x
|| errno
)
300 return errno
? -errno
: -EINVAL
;
302 if ((long) (int) l
!= l
)
309 int safe_atolu(const char *s
, long unsigned *ret_lu
) {
317 l
= strtoul(s
, &x
, 0);
319 if (!x
|| *x
|| errno
)
320 return errno
? -errno
: -EINVAL
;
326 int safe_atoli(const char *s
, long int *ret_li
) {
334 l
= strtol(s
, &x
, 0);
336 if (!x
|| *x
|| errno
)
337 return errno
? -errno
: -EINVAL
;
343 int safe_atollu(const char *s
, long long unsigned *ret_llu
) {
345 unsigned long long l
;
351 l
= strtoull(s
, &x
, 0);
353 if (!x
|| *x
|| errno
)
354 return errno
? -errno
: -EINVAL
;
360 int safe_atolli(const char *s
, long long int *ret_lli
) {
368 l
= strtoll(s
, &x
, 0);
370 if (!x
|| *x
|| errno
)
371 return errno
? -errno
: -EINVAL
;
377 /* Split a string into words. */
378 char *split(const char *c
, size_t *l
, const char *separator
, char **state
) {
381 current
= *state
? *state
: (char*) c
;
383 if (!*current
|| *c
== 0)
386 current
+= strspn(current
, separator
);
387 *l
= strcspn(current
, separator
);
390 return (char*) current
;
393 /* Split a string into words, but consider strings enclosed in '' and
394 * "" as words even if they include spaces. */
395 char *split_quoted(const char *c
, size_t *l
, char **state
) {
398 current
= *state
? *state
: (char*) c
;
400 if (!*current
|| *c
== 0)
403 current
+= strspn(current
, WHITESPACE
);
405 if (*current
== '\'') {
407 *l
= strcspn(current
, "'");
412 } else if (*current
== '\"') {
414 *l
= strcspn(current
, "\"");
420 *l
= strcspn(current
, WHITESPACE
);
424 /* FIXME: Cannot deal with strings that have spaces AND ticks
427 return (char*) current
;
430 char **split_path_and_make_absolute(const char *p
) {
434 if (!(l
= strv_split(p
, ":")))
437 if (!strv_path_make_absolute_cwd(l
)) {
445 int get_parent_of_pid(pid_t pid
, pid_t
*_ppid
) {
448 char fn
[132], line
[256], *p
;
449 long long unsigned ppid
;
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;
457 if (!(f
= fopen(fn
, "r")))
460 if (!(fgets(line
, sizeof(line
), f
))) {
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 */
472 if (!(p
= strrchr(line
, ')')))
483 if ((long long unsigned) (pid_t
) ppid
!= ppid
)
486 *_ppid
= (pid_t
) ppid
;
491 int write_one_line_file(const char *fn
, const char *line
) {
498 if (!(f
= fopen(fn
, "we")))
501 if (fputs(line
, f
) < 0) {
512 int read_one_line_file(const char *fn
, char **line
) {
520 if (!(f
= fopen(fn
, "re")))
523 if (!(fgets(t
, sizeof(t
), f
))) {
528 if (!(c
= strdup(t
))) {
541 char *truncate_nl(char *s
) {
544 s
[strcspn(s
, NEWLINE
)] = 0;
548 int get_process_name(pid_t pid
, char **name
) {
555 if (asprintf(&p
, "/proc/%llu/comm", (unsigned long long) pid
) < 0)
558 r
= read_one_line_file(p
, name
);
568 char *strappend(const char *s
, const char *suffix
) {
578 if (!(r
= new(char, a
+b
+1)))
582 memcpy(r
+a
, suffix
, b
);
588 int readlink_malloc(const char *p
, char **r
) {
598 if (!(c
= new(char, l
)))
601 if ((n
= readlink(p
, c
, l
-1)) < 0) {
607 if ((size_t) n
< l
-1) {
618 int readlink_and_make_absolute(const char *p
, char **r
) {
625 if ((j
= readlink_malloc(p
, &target
)) < 0)
628 k
= file_in_same_dir(p
, target
);
638 char *file_name_from_path(const char *p
) {
643 if ((r
= strrchr(p
, '/')))
649 bool path_is_absolute(const char *p
) {
655 bool is_path(const char *p
) {
657 return !!strchr(p
, '/');
660 char *path_make_absolute(const char *p
, const char *prefix
) {
665 /* Makes every item in the list an absolute path by prepending
666 * the prefix, if specified and necessary */
668 if (path_is_absolute(p
) || !prefix
)
671 if (asprintf(&r
, "%s/%s", prefix
, p
) < 0)
677 char *path_make_absolute_cwd(const char *p
) {
682 /* Similar to path_make_absolute(), but prefixes with the
683 * current working directory. */
685 if (path_is_absolute(p
))
688 if (!(cwd
= get_current_dir_name()))
691 r
= path_make_absolute(p
, cwd
);
697 char **strv_path_make_absolute_cwd(char **l
) {
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. */
707 if (!(t
= path_make_absolute_cwd(*s
)))
717 char **strv_path_canonicalize(char **l
) {
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. */
732 t
= path_make_absolute_cwd(*s
);
741 u
= canonicalize_file_name(t
);
745 if (errno
== ENOMEM
|| !errno
)
762 int reset_all_signal_handlers(void) {
765 for (sig
= 1; sig
< _NSIG
; sig
++) {
768 if (sig
== SIGKILL
|| sig
== SIGSTOP
)
772 sa
.sa_handler
= SIG_DFL
;
773 sa
.sa_flags
= SA_RESTART
;
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))
785 char *strstrip(char *s
) {
788 /* Drops trailing whitespace. Modifies the string in
789 * place. Returns pointer to first non-space character */
791 s
+= strspn(s
, WHITESPACE
);
794 if (!strchr(WHITESPACE
, *e
))
805 char *delete_chars(char *s
, const char *bad
) {
808 /* Drops all whitespace, regardless where in the string */
810 for (f
= s
, t
= s
; *f
; f
++) {
822 char *file_in_same_dir(const char *path
, const char *filename
) {
829 /* This removes the last component of path and appends
830 * filename, unless the latter is absolute anyway or the
833 if (path_is_absolute(filename
))
834 return strdup(filename
);
836 if (!(e
= strrchr(path
, '/')))
837 return strdup(filename
);
839 k
= strlen(filename
);
840 if (!(r
= new(char, e
-path
+1+k
+1)))
843 memcpy(r
, path
, e
-path
+1);
844 memcpy(r
+(e
-path
)+1, filename
, k
+1);
849 int mkdir_parents(const char *path
, mode_t mode
) {
854 /* Creates every parent directory in the path except the last
857 p
= path
+ strspn(path
, "/");
862 e
= p
+ strcspn(p
, "/");
863 p
= e
+ strspn(e
, "/");
865 /* Is this the last component? If so, then we're
870 if (!(t
= strndup(path
, e
- path
)))
877 if (r
< 0 && errno
!= EEXIST
)
882 int mkdir_p(const char *path
, mode_t mode
) {
887 if ((r
= mkdir_parents(path
, mode
)) < 0)
890 if (mkdir(path
, mode
) < 0)
896 int rmdir_parents(const char *path
, const char *stop
) {
905 /* Skip trailing slashes */
906 while (l
> 0 && path
[l
-1] == '/')
912 /* Skip last component */
913 while (l
> 0 && path
[l
-1] != '/')
916 /* Skip trailing slashes */
917 while (l
> 0 && path
[l
-1] == '/')
923 if (!(t
= strndup(path
, l
)))
926 if (path_startswith(stop
, t
)) {
943 char hexchar(int x
) {
944 static const char table
[16] = "0123456789abcdef";
946 return table
[x
& 15];
949 int unhexchar(char c
) {
951 if (c
>= '0' && c
<= '9')
954 if (c
>= 'a' && c
<= 'f')
957 if (c
>= 'A' && c
<= 'F')
963 char octchar(int x
) {
964 return '0' + (x
& 7);
967 int unoctchar(char c
) {
969 if (c
>= '0' && c
<= '7')
975 char decchar(int x
) {
976 return '0' + (x
% 10);
979 int undecchar(char c
) {
981 if (c
>= '0' && c
<= '9')
987 char *cescape(const char *s
) {
993 /* Does C style string escaping. */
995 if (!(r
= new(char, strlen(s
)*4 + 1)))
998 for (f
= s
, t
= r
; *f
; f
++)
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)) {
1049 *(t
++) = octchar((unsigned char) *f
>> 6);
1050 *(t
++) = octchar((unsigned char) *f
>> 3);
1051 *(t
++) = octchar((unsigned char) *f
);
1062 char *cunescape(const char *s
) {
1068 /* Undoes C style string escaping */
1070 if (!(r
= new(char, strlen(s
)+1)))
1073 for (f
= s
, t
= r
; *f
; f
++) {
1116 /* hexadecimal encoding */
1119 if ((a
= unhexchar(f
[1])) < 0 ||
1120 (b
= unhexchar(f
[2])) < 0) {
1121 /* Invalid escape code, let's take it literal then */
1125 *(t
++) = (char) ((a
<< 4) | b
);
1140 /* octal encoding */
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 */
1150 *(t
++) = (char) ((a
<< 6) | (b
<< 3) | c
);
1158 /* premature end of string.*/
1163 /* Invalid escape code, let's take it literal then */
1176 char *xescape(const char *s
, const char *bad
) {
1180 /* Escapes all chars in bad, in addition to \ and all special
1181 * chars, in \xFF style escaping. May be reversed with
1184 if (!(r
= new(char, strlen(s
)*4+1)))
1187 for (f
= s
, t
= r
; *f
; f
++) {
1189 if ((*f
< ' ') || (*f
>= 127) ||
1190 (*f
== '\\') || strchr(bad
, *f
)) {
1193 *(t
++) = hexchar(*f
>> 4);
1194 *(t
++) = hexchar(*f
);
1204 char *bus_path_escape(const char *s
) {
1210 /* Escapes all chars that D-Bus' object path cannot deal
1211 * with. Can be reverse with bus_path_unescape() */
1213 if (!(r
= new(char, strlen(s
)*3+1)))
1216 for (f
= s
, t
= r
; *f
; f
++) {
1218 if (!(*f
>= 'A' && *f
<= 'Z') &&
1219 !(*f
>= 'a' && *f
<= 'z') &&
1220 !(*f
>= '0' && *f
<= '9')) {
1222 *(t
++) = hexchar(*f
>> 4);
1223 *(t
++) = hexchar(*f
);
1233 char *bus_path_unescape(const char *f
) {
1238 if (!(r
= strdup(f
)))
1241 for (t
= r
; *f
; f
++) {
1246 if ((a
= unhexchar(f
[1])) < 0 ||
1247 (b
= unhexchar(f
[2])) < 0) {
1248 /* Invalid escape code, let's take it literal then */
1251 *(t
++) = (char) ((a
<< 4) | b
);
1263 char *path_kill_slashes(char *path
) {
1267 /* Removes redundant inner and trailing slashes. Modifies the
1268 * passed string in-place.
1270 * ///foo///bar/ becomes /foo/bar
1273 for (f
= path
, t
= path
; *f
; f
++) {
1288 /* Special rule, if we are talking of the root directory, a
1289 trailing slash is good */
1291 if (t
== path
&& slash
)
1298 bool path_startswith(const char *path
, const char *prefix
) {
1302 if ((path
[0] == '/') != (prefix
[0] == '/'))
1308 path
+= strspn(path
, "/");
1309 prefix
+= strspn(prefix
, "/");
1317 a
= strcspn(path
, "/");
1318 b
= strcspn(prefix
, "/");
1323 if (memcmp(path
, prefix
, a
) != 0)
1331 bool path_equal(const char *a
, const char *b
) {
1335 if ((a
[0] == '/') != (b
[0] == '/'))
1341 a
+= strspn(a
, "/");
1342 b
+= strspn(b
, "/");
1344 if (*a
== 0 && *b
== 0)
1347 if (*a
== 0 || *b
== 0)
1350 j
= strcspn(a
, "/");
1351 k
= strcspn(b
, "/");
1356 if (memcmp(a
, b
, j
) != 0)
1364 char *ascii_strlower(char *t
) {
1369 for (p
= t
; *p
; p
++)
1370 if (*p
>= 'A' && *p
<= 'Z')
1371 *p
= *p
- 'A' + 'a';
1376 bool ignore_file(const char *filename
) {
1380 filename
[0] == '.' ||
1381 streq(filename
, "lost+found") ||
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");
1391 int fd_nonblock(int fd
, bool nonblock
) {
1396 if ((flags
= fcntl(fd
, F_GETFL
, 0)) < 0)
1400 flags
|= O_NONBLOCK
;
1402 flags
&= ~O_NONBLOCK
;
1404 if (fcntl(fd
, F_SETFL
, flags
) < 0)
1410 int fd_cloexec(int fd
, bool cloexec
) {
1415 if ((flags
= fcntl(fd
, F_GETFD
, 0)) < 0)
1419 flags
|= FD_CLOEXEC
;
1421 flags
&= ~FD_CLOEXEC
;
1423 if (fcntl(fd
, F_SETFD
, flags
) < 0)
1429 int close_all_fds(const int except
[], unsigned n_except
) {
1434 if (!(d
= opendir("/proc/self/fd")))
1437 while ((de
= readdir(d
))) {
1440 if (ignore_file(de
->d_name
))
1443 if ((r
= safe_atoi(de
->d_name
, &fd
)) < 0)
1457 for (i
= 0; i
< n_except
; i
++)
1458 if (except
[i
] == fd
) {
1467 if ((r
= close_nointr(fd
)) < 0) {
1468 /* Valgrind has its own FD and doesn't want to have it closed */
1481 bool chars_intersect(const char *a
, const char *b
) {
1484 /* Returns true if any of the chars in a are in b. */
1485 for (p
= a
; *p
; p
++)
1492 char *format_timestamp(char *buf
, size_t l
, usec_t t
) {
1502 sec
= (time_t) t
/ USEC_PER_SEC
;
1504 if (strftime(buf
, l
, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec
, &tm
)) <= 0)
1510 char *format_timespan(char *buf
, size_t l
, usec_t t
) {
1511 static const struct {
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
},
1530 if (t
== (usec_t
) -1)
1533 /* The result of this function can be parsed with parse_usec */
1535 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
1539 if (t
< table
[i
].usec
)
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
);
1559 bool fstype_is_network(const char *fstype
) {
1560 static const char * const table
[] = {
1572 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
1573 if (streq(table
[i
], fstype
))
1582 if ((fd
= open("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
)) < 0)
1587 TIOCL_GETKMSGREDIRECT
,
1591 if (ioctl(fd
, TIOCLINUX
, tiocl
) < 0)
1594 vt
= tiocl
[0] <= 0 ? 1 : tiocl
[0];
1597 if (ioctl(fd
, VT_ACTIVATE
, vt
) < 0)
1600 close_nointr_nofail(r
);
1604 int read_one_char(FILE *f
, char *ret
, bool *need_nl
) {
1605 struct termios old_termios
, new_termios
;
1612 if (tcgetattr(fileno(f
), &old_termios
) >= 0) {
1613 new_termios
= old_termios
;
1615 new_termios
.c_lflag
&= ~ICANON
;
1616 new_termios
.c_cc
[VMIN
] = 1;
1617 new_termios
.c_cc
[VTIME
] = 0;
1619 if (tcsetattr(fileno(f
), TCSADRAIN
, &new_termios
) >= 0) {
1622 k
= fread(&c
, 1, 1, f
);
1624 tcsetattr(fileno(f
), TCSADRAIN
, &old_termios
);
1630 *need_nl
= c
!= '\n';
1637 if (!(fgets(line
, sizeof(line
), f
)))
1642 if (strlen(line
) != 1)
1652 int ask(char *ret
, const char *replies
, const char *text
, ...) {
1661 bool need_nl
= true;
1663 fputs("\x1B[1m", stdout
);
1669 fputs("\x1B[0m", stdout
);
1673 if ((r
= read_one_char(stdin
, &c
, &need_nl
)) < 0) {
1675 if (r
== -EBADMSG
) {
1676 puts("Bad input, please try again.");
1687 if (strchr(replies
, c
)) {
1692 puts("Read unexpected character, please try again.");
1696 int reset_terminal(int fd
) {
1697 struct termios termios
;
1702 /* Set terminal to some sane defaults */
1704 if (tcgetattr(fd
, &termios
) < 0) {
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 */
1713 termios
.c_iflag
&= ~(IGNBRK
| BRKINT
| ISTRIP
| INLCR
| IGNCR
| IUCLC
);
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
;
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 */
1730 termios
.c_cc
[VEOL
] = 0;
1731 termios
.c_cc
[VEOL2
] = 0;
1733 termios
.c_cc
[VTIME
] = 0;
1734 termios
.c_cc
[VMIN
] = 1;
1736 if (tcsetattr(fd
, TCSANOW
, &termios
) < 0)
1740 /* Just in case, flush all crap out */
1741 tcflush(fd
, TCIOFLUSH
);
1746 int open_terminal(const char *name
, int mode
) {
1749 if ((fd
= open(name
, mode
)) < 0)
1752 if ((r
= isatty(fd
)) < 0) {
1753 close_nointr_nofail(fd
);
1758 close_nointr_nofail(fd
);
1765 int flush_fd(int fd
) {
1766 struct pollfd pollfd
;
1770 pollfd
.events
= POLLIN
;
1777 if ((r
= poll(&pollfd
, 1, 0)) < 0) {
1788 if ((l
= read(fd
, buf
, sizeof(buf
))) < 0) {
1793 if (errno
== EAGAIN
)
1804 int acquire_terminal(const char *name
, bool fail
, bool force
, bool ignore_tiocstty_eperm
) {
1805 int fd
= -1, notify
= -1, r
, wd
= -1;
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.
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.) */
1822 if (!fail
&& !force
) {
1823 if ((notify
= inotify_init1(IN_CLOEXEC
)) < 0) {
1828 if ((wd
= inotify_add_watch(notify
, name
, IN_CLOSE
)) < 0) {
1836 if ((r
= flush_fd(notify
)) < 0)
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)
1845 /* First, try to get the tty */
1846 r
= ioctl(fd
, TIOCSCTTY
, force
);
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
)
1854 if (r
< 0 && (force
|| fail
|| errno
!= EPERM
)) {
1864 assert(notify
>= 0);
1867 struct inotify_event e
;
1870 if ((l
= read(notify
, &e
, sizeof(e
))) != sizeof(e
)) {
1884 if (e
.wd
!= wd
|| !(e
.mask
& IN_CLOSE
)) {
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
);
1900 close_nointr_nofail(notify
);
1902 if ((r
= reset_terminal(fd
)) < 0)
1903 log_warning("Failed to reset terminal: %s", strerror(-r
));
1909 close_nointr_nofail(fd
);
1912 close_nointr_nofail(notify
);
1917 int release_terminal(void) {
1919 struct sigaction sa_old
, sa_new
;
1921 if ((fd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_NDELAY
)) < 0)
1924 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
1925 * by our own TIOCNOTTY */
1928 sa_new
.sa_handler
= SIG_IGN
;
1929 sa_new
.sa_flags
= SA_RESTART
;
1930 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
1932 if (ioctl(fd
, TIOCNOTTY
) < 0)
1935 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
1937 close_nointr_nofail(fd
);
1941 int sigaction_many(const struct sigaction
*sa
, ...) {
1946 while ((sig
= va_arg(ap
, int)) > 0)
1947 if (sigaction(sig
, sa
, NULL
) < 0)
1954 int ignore_signals(int sig
, ...) {
1955 struct sigaction sa
;
1960 sa
.sa_handler
= SIG_IGN
;
1961 sa
.sa_flags
= SA_RESTART
;
1963 if (sigaction(sig
, &sa
, NULL
) < 0)
1967 while ((sig
= va_arg(ap
, int)) > 0)
1968 if (sigaction(sig
, &sa
, NULL
) < 0)
1975 int default_signals(int sig
, ...) {
1976 struct sigaction sa
;
1981 sa
.sa_handler
= SIG_DFL
;
1982 sa
.sa_flags
= SA_RESTART
;
1984 if (sigaction(sig
, &sa
, NULL
) < 0)
1988 while ((sig
= va_arg(ap
, int)) > 0)
1989 if (sigaction(sig
, &sa
, NULL
) < 0)
1996 int close_pipe(int p
[]) {
2002 a
= close_nointr(p
[0]);
2007 b
= close_nointr(p
[1]);
2011 return a
< 0 ? a
: b
;
2014 ssize_t
loop_read(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2023 while (nbytes
> 0) {
2026 if ((k
= read(fd
, p
, nbytes
)) <= 0) {
2028 if (k
< 0 && errno
== EINTR
)
2031 if (k
< 0 && errno
== EAGAIN
&& do_poll
) {
2032 struct pollfd pollfd
;
2036 pollfd
.events
= POLLIN
;
2038 if (poll(&pollfd
, 1, -1) < 0) {
2042 return n
> 0 ? n
: -errno
;
2045 if (pollfd
.revents
!= POLLIN
)
2046 return n
> 0 ? n
: -EIO
;
2051 return n
> 0 ? n
: (k
< 0 ? -errno
: 0);
2062 ssize_t
loop_write(int fd
, const void *buf
, size_t nbytes
, bool do_poll
) {
2071 while (nbytes
> 0) {
2074 if ((k
= write(fd
, p
, nbytes
)) <= 0) {
2076 if (k
< 0 && errno
== EINTR
)
2079 if (k
< 0 && errno
== EAGAIN
&& do_poll
) {
2080 struct pollfd pollfd
;
2084 pollfd
.events
= POLLOUT
;
2086 if (poll(&pollfd
, 1, -1) < 0) {
2090 return n
> 0 ? n
: -errno
;
2093 if (pollfd
.revents
!= POLLOUT
)
2094 return n
> 0 ? n
: -EIO
;
2099 return n
> 0 ? n
: (k
< 0 ? -errno
: 0);
2110 int path_is_mount_point(const char *t
) {
2114 if (lstat(t
, &a
) < 0) {
2116 if (errno
== ENOENT
)
2122 if (!(copy
= strdup(t
)))
2125 if (lstat(dirname(copy
), &b
) < 0) {
2132 return a
.st_dev
!= b
.st_dev
;
2135 int parse_usec(const char *t
, usec_t
*usec
) {
2136 static const struct {
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
},
2152 { "", USEC_PER_SEC
},
2168 l
= strtoll(p
, &e
, 10);
2179 e
+= strspn(e
, WHITESPACE
);
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
);
2188 if (i
>= ELEMENTSOF(table
))
2198 int make_stdio(int fd
) {
2203 r
= dup2(fd
, STDIN_FILENO
);
2204 s
= dup2(fd
, STDOUT_FILENO
);
2205 t
= dup2(fd
, STDERR_FILENO
);
2208 close_nointr_nofail(fd
);
2210 if (r
< 0 || s
< 0 || t
< 0)
2216 bool is_clean_exit(int code
, int status
) {
2218 if (code
== CLD_EXITED
)
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
)
2227 status
== SIGTERM
||
2233 bool is_device_path(const char *path
) {
2235 /* Returns true on paths that refer to a device, either in
2236 * sysfs or in /dev */
2239 path_startswith(path
, "/dev/") ||
2240 path_startswith(path
, "/sys/");
2243 int dir_is_empty(const char *path
) {
2246 struct dirent buf
, *de
;
2248 if (!(d
= opendir(path
)))
2252 if ((r
= readdir_r(d
, &buf
, &de
)) > 0) {
2262 if (!ignore_file(de
->d_name
)) {
2272 unsigned long long random_ull(void) {
2277 if ((fd
= open("/dev/urandom", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
)) < 0)
2280 r
= loop_read(fd
, &ull
, sizeof(ull
), true);
2281 close_nointr_nofail(fd
);
2283 if (r
!= sizeof(ull
))
2289 return random() * RAND_MAX
+ random();
2292 void rename_process(const char name
[8]) {
2295 prctl(PR_SET_NAME
, name
);
2297 /* This is a like a poor man's setproctitle(). The string
2298 * passed should fit in 7 chars (i.e. the length of
2301 if (program_invocation_name
)
2302 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
2305 void sigset_add_many(sigset_t
*ss
, ...) {
2312 while ((sig
= va_arg(ap
, int)) > 0)
2313 assert_se(sigaddset(ss
, sig
) == 0);
2317 char* gethostname_malloc(void) {
2320 assert_se(uname(&u
) >= 0);
2323 return strdup(u
.nodename
);
2325 return strdup(u
.sysname
);
2328 char* getlogname_malloc(void) {
2332 struct passwd pwbuf
, *pw
= NULL
;
2335 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
2340 /* Shortcut things to avoid NSS lookups */
2342 return strdup("root");
2344 if ((bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
)) <= 0)
2347 if (!(buf
= malloc(bufsize
)))
2350 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
) {
2351 name
= strdup(pw
->pw_name
);
2358 if (asprintf(&name
, "%lu", (unsigned long) uid
) < 0)
2364 char *getttyname_malloc(void) {
2365 char path
[PATH_MAX
], *p
;
2367 if (ttyname_r(STDIN_FILENO
, path
, sizeof(path
)) < 0)
2368 return strdup("unknown");
2373 if (startswith(path
, "/dev/"))
2379 static 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"
2386 DEFINE_STRING_TABLE_LOOKUP(ioprio_class
, int);
2388 static 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",
2397 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
2399 static 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"
2422 DEFINE_STRING_TABLE_LOOKUP(log_facility
, int);
2424 static const char *const log_level_table
[] = {
2425 [LOG_EMERG
] = "emerg",
2426 [LOG_ALERT
] = "alert",
2427 [LOG_CRIT
] = "crit",
2429 [LOG_WARNING
] = "warning",
2430 [LOG_NOTICE
] = "notice",
2431 [LOG_INFO
] = "info",
2432 [LOG_DEBUG
] = "debug"
2435 DEFINE_STRING_TABLE_LOOKUP(log_level
, int);
2437 static const char* const sched_policy_table
[] = {
2438 [SCHED_OTHER
] = "other",
2439 [SCHED_BATCH
] = "batch",
2440 [SCHED_IDLE
] = "idle",
2441 [SCHED_FIFO
] = "fifo",
2445 DEFINE_STRING_TABLE_LOOKUP(sched_policy
, int);
2447 static 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"
2466 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);