]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/util.c
7f5fa05dca4d1beb15da5b82db6a6792198dec9b
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>
49 #include <netinet/ip.h>
58 bool streq_ptr(const char *a
, const char *b
) {
60 /* Like streq(), but tries to make sense of NULL pointers */
71 usec_t
now(clockid_t clock_id
) {
74 assert_se(clock_gettime(clock_id
, &ts
) == 0);
76 return timespec_load(&ts
);
79 dual_timestamp
* dual_timestamp_get(dual_timestamp
*ts
) {
82 ts
->realtime
= now(CLOCK_REALTIME
);
83 ts
->monotonic
= now(CLOCK_MONOTONIC
);
88 usec_t
timespec_load(const struct timespec
*ts
) {
92 (usec_t
) ts
->tv_sec
* USEC_PER_SEC
+
93 (usec_t
) ts
->tv_nsec
/ NSEC_PER_USEC
;
96 struct timespec
*timespec_store(struct timespec
*ts
, usec_t u
) {
99 ts
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
100 ts
->tv_nsec
= (long int) ((u
% USEC_PER_SEC
) * NSEC_PER_USEC
);
105 usec_t
timeval_load(const struct timeval
*tv
) {
109 (usec_t
) tv
->tv_sec
* USEC_PER_SEC
+
110 (usec_t
) tv
->tv_usec
;
113 struct timeval
*timeval_store(struct timeval
*tv
, usec_t u
) {
116 tv
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
117 tv
->tv_usec
= (suseconds_t
) (u
% USEC_PER_SEC
);
122 bool endswith(const char *s
, const char *postfix
) {
129 pl
= strlen(postfix
);
137 return memcmp(s
+ sl
- pl
, postfix
, pl
) == 0;
140 bool startswith(const char *s
, const char *prefix
) {
155 return memcmp(s
, prefix
, pl
) == 0;
158 bool startswith_no_case(const char *s
, const char *prefix
) {
174 for(i
= 0; i
< pl
; ++i
) {
175 if (tolower(s
[i
]) != tolower(prefix
[i
]))
182 bool first_word(const char *s
, const char *word
) {
197 if (memcmp(s
, word
, wl
) != 0)
201 strchr(WHITESPACE
, s
[wl
]);
204 int close_nointr(int fd
) {
210 if ((r
= close(fd
)) >= 0)
218 void close_nointr_nofail(int fd
) {
219 int saved_errno
= errno
;
221 /* like close_nointr() but cannot fail, and guarantees errno
224 assert_se(close_nointr(fd
) == 0);
229 void close_many(const int fds
[], unsigned n_fd
) {
232 for (i
= 0; i
< n_fd
; i
++)
233 close_nointr_nofail(fds
[i
]);
236 int parse_boolean(const char *v
) {
239 if (streq(v
, "1") || v
[0] == 'y' || v
[0] == 'Y' || v
[0] == 't' || v
[0] == 'T' || !strcasecmp(v
, "on"))
241 else if (streq(v
, "0") || v
[0] == 'n' || v
[0] == 'N' || v
[0] == 'f' || v
[0] == 'F' || !strcasecmp(v
, "off"))
247 int parse_pid(const char *s
, pid_t
* ret_pid
) {
255 if ((r
= safe_atolu(s
, &ul
)) < 0)
260 if ((unsigned long) pid
!= ul
)
270 int safe_atou(const char *s
, unsigned *ret_u
) {
278 l
= strtoul(s
, &x
, 0);
280 if (!x
|| *x
|| errno
)
281 return errno
? -errno
: -EINVAL
;
283 if ((unsigned long) (unsigned) l
!= l
)
286 *ret_u
= (unsigned) l
;
290 int safe_atoi(const char *s
, int *ret_i
) {
298 l
= strtol(s
, &x
, 0);
300 if (!x
|| *x
|| errno
)
301 return errno
? -errno
: -EINVAL
;
303 if ((long) (int) l
!= l
)
310 int safe_atollu(const char *s
, long long unsigned *ret_llu
) {
312 unsigned long long l
;
318 l
= strtoull(s
, &x
, 0);
320 if (!x
|| *x
|| errno
)
321 return errno
? -errno
: -EINVAL
;
327 int safe_atolli(const char *s
, long long int *ret_lli
) {
335 l
= strtoll(s
, &x
, 0);
337 if (!x
|| *x
|| errno
)
338 return errno
? -errno
: -EINVAL
;
344 /* Split a string into words. */
345 char *split(const char *c
, size_t *l
, const char *separator
, char **state
) {
348 current
= *state
? *state
: (char*) c
;
350 if (!*current
|| *c
== 0)
353 current
+= strspn(current
, separator
);
354 *l
= strcspn(current
, separator
);
357 return (char*) current
;
360 /* Split a string into words, but consider strings enclosed in '' and
361 * "" as words even if they include spaces. */
362 char *split_quoted(const char *c
, size_t *l
, char **state
) {
364 bool escaped
= false;
366 current
= *state
? *state
: (char*) c
;
368 if (!*current
|| *c
== 0)
371 current
+= strspn(current
, WHITESPACE
);
373 if (*current
== '\'') {
376 for (e
= current
; *e
; e
++) {
386 *state
= *e
== 0 ? e
: e
+1;
387 } else if (*current
== '\"') {
390 for (e
= current
; *e
; e
++) {
400 *state
= *e
== 0 ? e
: e
+1;
402 for (e
= current
; *e
; e
++) {
407 else if (strchr(WHITESPACE
, *e
))
414 return (char*) current
;
417 char **split_path_and_make_absolute(const char *p
) {
421 if (!(l
= strv_split(p
, ":")))
424 if (!strv_path_make_absolute_cwd(l
)) {
432 int get_parent_of_pid(pid_t pid
, pid_t
*_ppid
) {
435 char fn
[132], line
[256], *p
;
441 assert_se(snprintf(fn
, sizeof(fn
)-1, "/proc/%lu/stat", (unsigned long) pid
) < (int) (sizeof(fn
)-1));
442 fn
[sizeof(fn
)-1] = 0;
444 if (!(f
= fopen(fn
, "r")))
447 if (!(fgets(line
, sizeof(line
), f
))) {
455 /* Let's skip the pid and comm fields. The latter is enclosed
456 * in () but does not escape any () in its value, so let's
457 * skip over it manually */
459 if (!(p
= strrchr(line
, ')')))
470 if ((long unsigned) (pid_t
) ppid
!= ppid
)
473 *_ppid
= (pid_t
) ppid
;
478 int write_one_line_file(const char *fn
, const char *line
) {
485 if (!(f
= fopen(fn
, "we")))
488 if (fputs(line
, f
) < 0) {
499 int read_one_line_file(const char *fn
, char **line
) {
507 if (!(f
= fopen(fn
, "re")))
510 if (!(fgets(t
, sizeof(t
), f
))) {
515 if (!(c
= strdup(t
))) {
528 char *truncate_nl(char *s
) {
531 s
[strcspn(s
, NEWLINE
)] = 0;
535 int get_process_name(pid_t pid
, char **name
) {
542 if (asprintf(&p
, "/proc/%lu/comm", (unsigned long) pid
) < 0)
545 r
= read_one_line_file(p
, name
);
555 int get_process_cmdline(pid_t pid
, size_t max_length
, char **line
) {
563 assert(max_length
> 0);
566 if (asprintf(&p
, "/proc/%lu/cmdline", (unsigned long) pid
) < 0)
575 if (!(r
= new(char, max_length
))) {
582 while ((c
= getc(f
)) != EOF
) {
604 size_t n
= MIN(left
-1, 3U);
613 return get_process_name(pid
, line
);
619 char *strnappend(const char *s
, const char *suffix
, size_t b
) {
627 return strndup(suffix
, b
);
637 if (!(r
= new(char, a
+b
+1)))
641 memcpy(r
+a
, suffix
, b
);
647 char *strappend(const char *s
, const char *suffix
) {
648 return strnappend(s
, suffix
, suffix
? strlen(suffix
) : 0);
651 int readlink_malloc(const char *p
, char **r
) {
661 if (!(c
= new(char, l
)))
664 if ((n
= readlink(p
, c
, l
-1)) < 0) {
670 if ((size_t) n
< l
-1) {
681 int readlink_and_make_absolute(const char *p
, char **r
) {
688 if ((j
= readlink_malloc(p
, &target
)) < 0)
691 k
= file_in_same_dir(p
, target
);
701 char *file_name_from_path(const char *p
) {
706 if ((r
= strrchr(p
, '/')))
712 bool path_is_absolute(const char *p
) {
718 bool is_path(const char *p
) {
720 return !!strchr(p
, '/');
723 char *path_make_absolute(const char *p
, const char *prefix
) {
728 /* Makes every item in the list an absolute path by prepending
729 * the prefix, if specified and necessary */
731 if (path_is_absolute(p
) || !prefix
)
734 if (asprintf(&r
, "%s/%s", prefix
, p
) < 0)
740 char *path_make_absolute_cwd(const char *p
) {
745 /* Similar to path_make_absolute(), but prefixes with the
746 * current working directory. */
748 if (path_is_absolute(p
))
751 if (!(cwd
= get_current_dir_name()))
754 r
= path_make_absolute(p
, cwd
);
760 char **strv_path_make_absolute_cwd(char **l
) {
763 /* Goes through every item in the string list and makes it
764 * absolute. This works in place and won't rollback any
765 * changes on failure. */
770 if (!(t
= path_make_absolute_cwd(*s
)))
780 char **strv_path_canonicalize(char **l
) {
788 /* Goes through every item in the string list and canonicalize
789 * the path. This works in place and won't rollback any
790 * changes on failure. */
795 t
= path_make_absolute_cwd(*s
);
804 u
= canonicalize_file_name(t
);
808 if (errno
== ENOMEM
|| !errno
)
825 int reset_all_signal_handlers(void) {
828 for (sig
= 1; sig
< _NSIG
; sig
++) {
831 if (sig
== SIGKILL
|| sig
== SIGSTOP
)
835 sa
.sa_handler
= SIG_DFL
;
836 sa
.sa_flags
= SA_RESTART
;
838 /* On Linux the first two RT signals are reserved by
839 * glibc, and sigaction() will return EINVAL for them. */
840 if ((sigaction(sig
, &sa
, NULL
) < 0))
848 char *strstrip(char *s
) {
851 /* Drops trailing whitespace. Modifies the string in
852 * place. Returns pointer to first non-space character */
854 s
+= strspn(s
, WHITESPACE
);
857 if (!strchr(WHITESPACE
, *e
))
868 char *delete_chars(char *s
, const char *bad
) {
871 /* Drops all whitespace, regardless where in the string */
873 for (f
= s
, t
= s
; *f
; f
++) {
885 char *file_in_same_dir(const char *path
, const char *filename
) {
892 /* This removes the last component of path and appends
893 * filename, unless the latter is absolute anyway or the
896 if (path_is_absolute(filename
))
897 return strdup(filename
);
899 if (!(e
= strrchr(path
, '/')))
900 return strdup(filename
);
902 k
= strlen(filename
);
903 if (!(r
= new(char, e
-path
+1+k
+1)))
906 memcpy(r
, path
, e
-path
+1);
907 memcpy(r
+(e
-path
)+1, filename
, k
+1);
912 int safe_mkdir(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
915 if (mkdir(path
, mode
) >= 0)
916 if (chmod_and_chown(path
, mode
, uid
, gid
) < 0)
919 if (lstat(path
, &st
) < 0)
922 if ((st
.st_mode
& 0777) != mode
||
925 !S_ISDIR(st
.st_mode
)) {
934 int mkdir_parents(const char *path
, mode_t mode
) {
939 /* Creates every parent directory in the path except the last
942 p
= path
+ strspn(path
, "/");
947 e
= p
+ strcspn(p
, "/");
948 p
= e
+ strspn(e
, "/");
950 /* Is this the last component? If so, then we're
955 if (!(t
= strndup(path
, e
- path
)))
962 if (r
< 0 && errno
!= EEXIST
)
967 int mkdir_p(const char *path
, mode_t mode
) {
972 if ((r
= mkdir_parents(path
, mode
)) < 0)
975 if (mkdir(path
, mode
) < 0)
981 int rmdir_parents(const char *path
, const char *stop
) {
990 /* Skip trailing slashes */
991 while (l
> 0 && path
[l
-1] == '/')
997 /* Skip last component */
998 while (l
> 0 && path
[l
-1] != '/')
1001 /* Skip trailing slashes */
1002 while (l
> 0 && path
[l
-1] == '/')
1008 if (!(t
= strndup(path
, l
)))
1011 if (path_startswith(stop
, t
)) {
1020 if (errno
!= ENOENT
)
1028 char hexchar(int x
) {
1029 static const char table
[16] = "0123456789abcdef";
1031 return table
[x
& 15];
1034 int unhexchar(char c
) {
1036 if (c
>= '0' && c
<= '9')
1039 if (c
>= 'a' && c
<= 'f')
1040 return c
- 'a' + 10;
1042 if (c
>= 'A' && c
<= 'F')
1043 return c
- 'A' + 10;
1048 char octchar(int x
) {
1049 return '0' + (x
& 7);
1052 int unoctchar(char c
) {
1054 if (c
>= '0' && c
<= '7')
1060 char decchar(int x
) {
1061 return '0' + (x
% 10);
1064 int undecchar(char c
) {
1066 if (c
>= '0' && c
<= '9')
1072 char *cescape(const char *s
) {
1078 /* Does C style string escaping. */
1080 if (!(r
= new(char, strlen(s
)*4 + 1)))
1083 for (f
= s
, t
= r
; *f
; f
++)
1129 /* For special chars we prefer octal over
1130 * hexadecimal encoding, simply because glib's
1131 * g_strescape() does the same */
1132 if ((*f
< ' ') || (*f
>= 127)) {
1134 *(t
++) = octchar((unsigned char) *f
>> 6);
1135 *(t
++) = octchar((unsigned char) *f
>> 3);
1136 *(t
++) = octchar((unsigned char) *f
);
1147 char *cunescape_length(const char *s
, size_t length
) {
1153 /* Undoes C style string escaping */
1155 if (!(r
= new(char, length
+1)))
1158 for (f
= s
, t
= r
; f
< s
+ length
; f
++) {
1201 /* This is an extension of the XDG syntax files */
1206 /* hexadecimal encoding */
1209 if ((a
= unhexchar(f
[1])) < 0 ||
1210 (b
= unhexchar(f
[2])) < 0) {
1211 /* Invalid escape code, let's take it literal then */
1215 *(t
++) = (char) ((a
<< 4) | b
);
1230 /* octal encoding */
1233 if ((a
= unoctchar(f
[0])) < 0 ||
1234 (b
= unoctchar(f
[1])) < 0 ||
1235 (c
= unoctchar(f
[2])) < 0) {
1236 /* Invalid escape code, let's take it literal then */
1240 *(t
++) = (char) ((a
<< 6) | (b
<< 3) | c
);
1248 /* premature end of string.*/
1253 /* Invalid escape code, let's take it literal then */
1265 char *cunescape(const char *s
) {
1266 return cunescape_length(s
, strlen(s
));
1269 char *xescape(const char *s
, const char *bad
) {
1273 /* Escapes all chars in bad, in addition to \ and all special
1274 * chars, in \xFF style escaping. May be reversed with
1277 if (!(r
= new(char, strlen(s
)*4+1)))
1280 for (f
= s
, t
= r
; *f
; f
++) {
1282 if ((*f
< ' ') || (*f
>= 127) ||
1283 (*f
== '\\') || strchr(bad
, *f
)) {
1286 *(t
++) = hexchar(*f
>> 4);
1287 *(t
++) = hexchar(*f
);
1297 char *bus_path_escape(const char *s
) {
1303 /* Escapes all chars that D-Bus' object path cannot deal
1304 * with. Can be reverse with bus_path_unescape() */
1306 if (!(r
= new(char, strlen(s
)*3+1)))
1309 for (f
= s
, t
= r
; *f
; f
++) {
1311 if (!(*f
>= 'A' && *f
<= 'Z') &&
1312 !(*f
>= 'a' && *f
<= 'z') &&
1313 !(*f
>= '0' && *f
<= '9')) {
1315 *(t
++) = hexchar(*f
>> 4);
1316 *(t
++) = hexchar(*f
);
1326 char *bus_path_unescape(const char *f
) {
1331 if (!(r
= strdup(f
)))
1334 for (t
= r
; *f
; f
++) {
1339 if ((a
= unhexchar(f
[1])) < 0 ||
1340 (b
= unhexchar(f
[2])) < 0) {
1341 /* Invalid escape code, let's take it literal then */
1344 *(t
++) = (char) ((a
<< 4) | b
);
1356 char *path_kill_slashes(char *path
) {
1360 /* Removes redundant inner and trailing slashes. Modifies the
1361 * passed string in-place.
1363 * ///foo///bar/ becomes /foo/bar
1366 for (f
= path
, t
= path
; *f
; f
++) {
1381 /* Special rule, if we are talking of the root directory, a
1382 trailing slash is good */
1384 if (t
== path
&& slash
)
1391 bool path_startswith(const char *path
, const char *prefix
) {
1395 if ((path
[0] == '/') != (prefix
[0] == '/'))
1401 path
+= strspn(path
, "/");
1402 prefix
+= strspn(prefix
, "/");
1410 a
= strcspn(path
, "/");
1411 b
= strcspn(prefix
, "/");
1416 if (memcmp(path
, prefix
, a
) != 0)
1424 bool path_equal(const char *a
, const char *b
) {
1428 if ((a
[0] == '/') != (b
[0] == '/'))
1434 a
+= strspn(a
, "/");
1435 b
+= strspn(b
, "/");
1437 if (*a
== 0 && *b
== 0)
1440 if (*a
== 0 || *b
== 0)
1443 j
= strcspn(a
, "/");
1444 k
= strcspn(b
, "/");
1449 if (memcmp(a
, b
, j
) != 0)
1457 char *ascii_strlower(char *t
) {
1462 for (p
= t
; *p
; p
++)
1463 if (*p
>= 'A' && *p
<= 'Z')
1464 *p
= *p
- 'A' + 'a';
1469 bool ignore_file(const char *filename
) {
1473 filename
[0] == '.' ||
1474 streq(filename
, "lost+found") ||
1475 endswith(filename
, "~") ||
1476 endswith(filename
, ".rpmnew") ||
1477 endswith(filename
, ".rpmsave") ||
1478 endswith(filename
, ".rpmorig") ||
1479 endswith(filename
, ".dpkg-old") ||
1480 endswith(filename
, ".dpkg-new") ||
1481 endswith(filename
, ".swp");
1484 int fd_nonblock(int fd
, bool nonblock
) {
1489 if ((flags
= fcntl(fd
, F_GETFL
, 0)) < 0)
1493 flags
|= O_NONBLOCK
;
1495 flags
&= ~O_NONBLOCK
;
1497 if (fcntl(fd
, F_SETFL
, flags
) < 0)
1503 int fd_cloexec(int fd
, bool cloexec
) {
1508 if ((flags
= fcntl(fd
, F_GETFD
, 0)) < 0)
1512 flags
|= FD_CLOEXEC
;
1514 flags
&= ~FD_CLOEXEC
;
1516 if (fcntl(fd
, F_SETFD
, flags
) < 0)
1522 int close_all_fds(const int except
[], unsigned n_except
) {
1527 if (!(d
= opendir("/proc/self/fd")))
1530 while ((de
= readdir(d
))) {
1533 if (ignore_file(de
->d_name
))
1536 if ((r
= safe_atoi(de
->d_name
, &fd
)) < 0)
1550 for (i
= 0; i
< n_except
; i
++)
1551 if (except
[i
] == fd
) {
1560 if ((r
= close_nointr(fd
)) < 0) {
1561 /* Valgrind has its own FD and doesn't want to have it closed */
1574 bool chars_intersect(const char *a
, const char *b
) {
1577 /* Returns true if any of the chars in a are in b. */
1578 for (p
= a
; *p
; p
++)
1585 char *format_timestamp(char *buf
, size_t l
, usec_t t
) {
1595 sec
= (time_t) (t
/ USEC_PER_SEC
);
1597 if (strftime(buf
, l
, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec
, &tm
)) <= 0)
1603 char *format_timespan(char *buf
, size_t l
, usec_t t
) {
1604 static const struct {
1608 { "w", USEC_PER_WEEK
},
1609 { "d", USEC_PER_DAY
},
1610 { "h", USEC_PER_HOUR
},
1611 { "min", USEC_PER_MINUTE
},
1612 { "s", USEC_PER_SEC
},
1613 { "ms", USEC_PER_MSEC
},
1623 if (t
== (usec_t
) -1)
1626 /* The result of this function can be parsed with parse_usec */
1628 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
1632 if (t
< table
[i
].usec
)
1638 k
= snprintf(p
, l
, "%s%llu%s", p
> buf
? " " : "", (unsigned long long) (t
/ table
[i
].usec
), table
[i
].suffix
);
1639 n
= MIN((size_t) k
, l
);
1652 bool fstype_is_network(const char *fstype
) {
1653 static const char * const table
[] = {
1665 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
1666 if (streq(table
[i
], fstype
))
1675 if ((fd
= open("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
)) < 0)
1680 TIOCL_GETKMSGREDIRECT
,
1684 if (ioctl(fd
, TIOCLINUX
, tiocl
) < 0)
1687 vt
= tiocl
[0] <= 0 ? 1 : tiocl
[0];
1690 if (ioctl(fd
, VT_ACTIVATE
, vt
) < 0)
1693 close_nointr_nofail(r
);
1697 int read_one_char(FILE *f
, char *ret
, bool *need_nl
) {
1698 struct termios old_termios
, new_termios
;
1705 if (tcgetattr(fileno(f
), &old_termios
) >= 0) {
1706 new_termios
= old_termios
;
1708 new_termios
.c_lflag
&= ~ICANON
;
1709 new_termios
.c_cc
[VMIN
] = 1;
1710 new_termios
.c_cc
[VTIME
] = 0;
1712 if (tcsetattr(fileno(f
), TCSADRAIN
, &new_termios
) >= 0) {
1715 k
= fread(&c
, 1, 1, f
);
1717 tcsetattr(fileno(f
), TCSADRAIN
, &old_termios
);
1723 *need_nl
= c
!= '\n';
1730 if (!(fgets(line
, sizeof(line
), f
)))
1735 if (strlen(line
) != 1)
1745 int ask(char *ret
, const char *replies
, const char *text
, ...) {
1754 bool need_nl
= true;
1756 fputs("\x1B[1m", stdout
);
1762 fputs("\x1B[0m", stdout
);
1766 if ((r
= read_one_char(stdin
, &c
, &need_nl
)) < 0) {
1768 if (r
== -EBADMSG
) {
1769 puts("Bad input, please try again.");
1780 if (strchr(replies
, c
)) {
1785 puts("Read unexpected character, please try again.");
1789 int reset_terminal(int fd
) {
1790 struct termios termios
;
1795 /* Set terminal to some sane defaults */
1797 if (tcgetattr(fd
, &termios
) < 0) {
1802 /* We only reset the stuff that matters to the software. How
1803 * hardware is set up we don't touch assuming that somebody
1804 * else will do that for us */
1806 termios
.c_iflag
&= ~(IGNBRK
| BRKINT
| ISTRIP
| INLCR
| IGNCR
| IUCLC
);
1807 termios
.c_iflag
|= ICRNL
| IMAXBEL
| IUTF8
;
1808 termios
.c_oflag
|= ONLCR
;
1809 termios
.c_cflag
|= CREAD
;
1810 termios
.c_lflag
= ISIG
| ICANON
| IEXTEN
| ECHO
| ECHOE
| ECHOK
| ECHOCTL
| ECHOPRT
| ECHOKE
;
1812 termios
.c_cc
[VINTR
] = 03; /* ^C */
1813 termios
.c_cc
[VQUIT
] = 034; /* ^\ */
1814 termios
.c_cc
[VERASE
] = 0177;
1815 termios
.c_cc
[VKILL
] = 025; /* ^X */
1816 termios
.c_cc
[VEOF
] = 04; /* ^D */
1817 termios
.c_cc
[VSTART
] = 021; /* ^Q */
1818 termios
.c_cc
[VSTOP
] = 023; /* ^S */
1819 termios
.c_cc
[VSUSP
] = 032; /* ^Z */
1820 termios
.c_cc
[VLNEXT
] = 026; /* ^V */
1821 termios
.c_cc
[VWERASE
] = 027; /* ^W */
1822 termios
.c_cc
[VREPRINT
] = 022; /* ^R */
1823 termios
.c_cc
[VEOL
] = 0;
1824 termios
.c_cc
[VEOL2
] = 0;
1826 termios
.c_cc
[VTIME
] = 0;
1827 termios
.c_cc
[VMIN
] = 1;
1829 if (tcsetattr(fd
, TCSANOW
, &termios
) < 0)
1833 /* Just in case, flush all crap out */
1834 tcflush(fd
, TCIOFLUSH
);
1839 int open_terminal(const char *name
, int mode
) {
1842 if ((fd
= open(name
, mode
)) < 0)
1845 if ((r
= isatty(fd
)) < 0) {
1846 close_nointr_nofail(fd
);
1851 close_nointr_nofail(fd
);
1858 int flush_fd(int fd
) {
1859 struct pollfd pollfd
;
1863 pollfd
.events
= POLLIN
;
1870 if ((r
= poll(&pollfd
, 1, 0)) < 0) {
1881 if ((l
= read(fd
, buf
, sizeof(buf
))) < 0) {
1886 if (errno
== EAGAIN
)
1897 int acquire_terminal(const char *name
, bool fail
, bool force
, bool ignore_tiocstty_eperm
) {
1898 int fd
= -1, notify
= -1, r
, wd
= -1;
1902 /* We use inotify to be notified when the tty is closed. We
1903 * create the watch before checking if we can actually acquire
1904 * it, so that we don't lose any event.
1906 * Note: strictly speaking this actually watches for the
1907 * device being closed, it does *not* really watch whether a
1908 * tty loses its controlling process. However, unless some
1909 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
1910 * its tty otherwise this will not become a problem. As long
1911 * as the administrator makes sure not configure any service
1912 * on the same tty as an untrusted user this should not be a
1913 * problem. (Which he probably should not do anyway.) */
1915 if (!fail
&& !force
) {
1916 if ((notify
= inotify_init1(IN_CLOEXEC
)) < 0) {
1921 if ((wd
= inotify_add_watch(notify
, name
, IN_CLOSE
)) < 0) {
1929 if ((r
= flush_fd(notify
)) < 0)
1932 /* We pass here O_NOCTTY only so that we can check the return
1933 * value TIOCSCTTY and have a reliable way to figure out if we
1934 * successfully became the controlling process of the tty */
1935 if ((fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
)) < 0)
1938 /* First, try to get the tty */
1939 r
= ioctl(fd
, TIOCSCTTY
, force
);
1941 /* Sometimes it makes sense to ignore TIOCSCTTY
1942 * returning EPERM, i.e. when very likely we already
1943 * are have this controlling terminal. */
1944 if (r
< 0 && errno
== EPERM
&& ignore_tiocstty_eperm
)
1947 if (r
< 0 && (force
|| fail
|| errno
!= EPERM
)) {
1957 assert(notify
>= 0);
1960 struct inotify_event e
;
1963 if ((l
= read(notify
, &e
, sizeof(e
))) != sizeof(e
)) {
1977 if (e
.wd
!= wd
|| !(e
.mask
& IN_CLOSE
)) {
1985 /* We close the tty fd here since if the old session
1986 * ended our handle will be dead. It's important that
1987 * we do this after sleeping, so that we don't enter
1988 * an endless loop. */
1989 close_nointr_nofail(fd
);
1993 close_nointr_nofail(notify
);
1995 if ((r
= reset_terminal(fd
)) < 0)
1996 log_warning("Failed to reset terminal: %s", strerror(-r
));
2002 close_nointr_nofail(fd
);
2005 close_nointr_nofail(notify
);
2010 int release_terminal(void) {
2012 struct sigaction sa_old
, sa_new
;
2014 if ((fd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_NDELAY
)) < 0)
2017 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2018 * by our own TIOCNOTTY */
2021 sa_new
.sa_handler
= SIG_IGN
;
2022 sa_new
.sa_flags
= SA_RESTART
;
2023 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
2025 if (ioctl(fd
, TIOCNOTTY
) < 0)
2028 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
2030 close_nointr_nofail(fd
);
2034 int sigaction_many(const struct sigaction
*sa
, ...) {
2039 while ((sig
= va_arg(ap
, int)) > 0)
2040 if (sigaction(sig
, sa
, NULL
) < 0)
2047 int ignore_signals(int sig
, ...) {
2048 struct sigaction sa
;
2053 sa
.sa_handler
= SIG_IGN
;
2054 sa
.sa_flags
= SA_RESTART
;
2056 if (sigaction(sig
, &sa
, NULL
) < 0)
2060 while ((sig
= va_arg(ap
, int)) > 0)
2061 if (sigaction(sig
, &sa
, NULL
) < 0)
2068 int default_signals(int sig
, ...) {
2069 struct sigaction sa
;
2074 sa
.sa_handler
= SIG_DFL
;
2075 sa
.sa_flags
= SA_RESTART
;
2077 if (sigaction(sig
, &sa
, NULL
) < 0)
2081 while ((sig
= va_arg(ap
, int)) > 0)
2082 if (sigaction(sig
, &sa
, NULL
) < 0)
2089 int close_pipe(int p
[]) {
2095 a
= close_nointr(p
[0]);
2100 b
= close_nointr(p
[1]);
2104 return a
< 0 ? a
: b
;
2107 ssize_t
loop_read(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2116 while (nbytes
> 0) {
2119 if ((k
= read(fd
, p
, nbytes
)) <= 0) {
2121 if (k
< 0 && errno
== EINTR
)
2124 if (k
< 0 && errno
== EAGAIN
&& do_poll
) {
2125 struct pollfd pollfd
;
2129 pollfd
.events
= POLLIN
;
2131 if (poll(&pollfd
, 1, -1) < 0) {
2135 return n
> 0 ? n
: -errno
;
2138 if (pollfd
.revents
!= POLLIN
)
2139 return n
> 0 ? n
: -EIO
;
2144 return n
> 0 ? n
: (k
< 0 ? -errno
: 0);
2155 ssize_t
loop_write(int fd
, const void *buf
, size_t nbytes
, bool do_poll
) {
2164 while (nbytes
> 0) {
2167 if ((k
= write(fd
, p
, nbytes
)) <= 0) {
2169 if (k
< 0 && errno
== EINTR
)
2172 if (k
< 0 && errno
== EAGAIN
&& do_poll
) {
2173 struct pollfd pollfd
;
2177 pollfd
.events
= POLLOUT
;
2179 if (poll(&pollfd
, 1, -1) < 0) {
2183 return n
> 0 ? n
: -errno
;
2186 if (pollfd
.revents
!= POLLOUT
)
2187 return n
> 0 ? n
: -EIO
;
2192 return n
> 0 ? n
: (k
< 0 ? -errno
: 0);
2203 int path_is_mount_point(const char *t
) {
2207 if (lstat(t
, &a
) < 0) {
2209 if (errno
== ENOENT
)
2215 if (!(copy
= strdup(t
)))
2218 if (lstat(dirname(copy
), &b
) < 0) {
2225 return a
.st_dev
!= b
.st_dev
;
2228 int parse_usec(const char *t
, usec_t
*usec
) {
2229 static const struct {
2233 { "sec", USEC_PER_SEC
},
2234 { "s", USEC_PER_SEC
},
2235 { "min", USEC_PER_MINUTE
},
2236 { "hr", USEC_PER_HOUR
},
2237 { "h", USEC_PER_HOUR
},
2238 { "d", USEC_PER_DAY
},
2239 { "w", USEC_PER_WEEK
},
2240 { "msec", USEC_PER_MSEC
},
2241 { "ms", USEC_PER_MSEC
},
2242 { "m", USEC_PER_MINUTE
},
2245 { "", USEC_PER_SEC
},
2261 l
= strtoll(p
, &e
, 10);
2272 e
+= strspn(e
, WHITESPACE
);
2274 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
2275 if (startswith(e
, table
[i
].suffix
)) {
2276 r
+= (usec_t
) l
* table
[i
].usec
;
2277 p
= e
+ strlen(table
[i
].suffix
);
2281 if (i
>= ELEMENTSOF(table
))
2291 int make_stdio(int fd
) {
2296 r
= dup2(fd
, STDIN_FILENO
);
2297 s
= dup2(fd
, STDOUT_FILENO
);
2298 t
= dup2(fd
, STDERR_FILENO
);
2301 close_nointr_nofail(fd
);
2303 if (r
< 0 || s
< 0 || t
< 0)
2309 bool is_clean_exit(int code
, int status
) {
2311 if (code
== CLD_EXITED
)
2314 /* If a daemon does not implement handlers for some of the
2315 * signals that's not considered an unclean shutdown */
2316 if (code
== CLD_KILLED
)
2320 status
== SIGTERM
||
2326 bool is_device_path(const char *path
) {
2328 /* Returns true on paths that refer to a device, either in
2329 * sysfs or in /dev */
2332 path_startswith(path
, "/dev/") ||
2333 path_startswith(path
, "/sys/");
2336 int dir_is_empty(const char *path
) {
2339 struct dirent buf
, *de
;
2341 if (!(d
= opendir(path
)))
2345 if ((r
= readdir_r(d
, &buf
, &de
)) > 0) {
2355 if (!ignore_file(de
->d_name
)) {
2365 unsigned long long random_ull(void) {
2370 if ((fd
= open("/dev/urandom", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
)) < 0)
2373 r
= loop_read(fd
, &ull
, sizeof(ull
), true);
2374 close_nointr_nofail(fd
);
2376 if (r
!= sizeof(ull
))
2382 return random() * RAND_MAX
+ random();
2385 void rename_process(const char name
[8]) {
2388 prctl(PR_SET_NAME
, name
);
2390 /* This is a like a poor man's setproctitle(). The string
2391 * passed should fit in 7 chars (i.e. the length of
2394 if (program_invocation_name
)
2395 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
2398 void sigset_add_many(sigset_t
*ss
, ...) {
2405 while ((sig
= va_arg(ap
, int)) > 0)
2406 assert_se(sigaddset(ss
, sig
) == 0);
2410 char* gethostname_malloc(void) {
2413 assert_se(uname(&u
) >= 0);
2416 return strdup(u
.nodename
);
2418 return strdup(u
.sysname
);
2421 int getmachineid_malloc(char **b
) {
2426 if ((r
= read_one_line_file("/var/lib/dbus/machine-id", b
)) < 0)
2433 char* getlogname_malloc(void) {
2437 struct passwd pwbuf
, *pw
= NULL
;
2440 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
2445 /* Shortcut things to avoid NSS lookups */
2447 return strdup("root");
2449 if ((bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
)) <= 0)
2452 if (!(buf
= malloc(bufsize
)))
2455 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
) {
2456 name
= strdup(pw
->pw_name
);
2463 if (asprintf(&name
, "%lu", (unsigned long) uid
) < 0)
2469 int getttyname_malloc(char **r
) {
2470 char path
[PATH_MAX
], *p
, *c
;
2474 if (ttyname_r(STDIN_FILENO
, path
, sizeof(path
)) < 0)
2480 if (startswith(path
, "/dev/"))
2483 if (!(c
= strdup(p
)))
2490 static int rm_rf_children(int fd
, bool only_dirs
) {
2496 /* This returns the first error we run into, but nevertheless
2499 if (!(d
= fdopendir(fd
))) {
2500 close_nointr_nofail(fd
);
2505 struct dirent buf
, *de
;
2509 if ((r
= readdir_r(d
, &buf
, &de
)) != 0) {
2518 if (streq(de
->d_name
, ".") || streq(de
->d_name
, ".."))
2521 if (de
->d_type
== DT_UNKNOWN
) {
2524 if (fstatat(fd
, de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0) {
2530 is_dir
= S_ISDIR(st
.st_mode
);
2532 is_dir
= de
->d_type
== DT_DIR
;
2537 if ((subdir_fd
= openat(fd
, de
->d_name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
)) < 0) {
2543 if ((r
= rm_rf_children(subdir_fd
, only_dirs
)) < 0) {
2548 if (unlinkat(fd
, de
->d_name
, AT_REMOVEDIR
) < 0) {
2552 } else if (!only_dirs
) {
2554 if (unlinkat(fd
, de
->d_name
, 0) < 0) {
2566 int rm_rf(const char *path
, bool only_dirs
, bool delete_root
) {
2572 if ((fd
= open(path
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
)) < 0) {
2574 if (errno
!= ENOTDIR
)
2577 if (delete_root
&& !only_dirs
)
2578 if (unlink(path
) < 0)
2584 r
= rm_rf_children(fd
, only_dirs
);
2587 if (rmdir(path
) < 0) {
2595 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
2598 /* Under the assumption that we are running privileged we
2599 * first change the access mode and only then hand out
2600 * ownership to avoid a window where access is too open. */
2602 if (chmod(path
, mode
) < 0)
2605 if (chown(path
, uid
, gid
) < 0)
2611 cpu_set_t
* cpu_set_malloc(unsigned *ncpus
) {
2615 /* Allocates the cpuset in the right size */
2618 if (!(r
= CPU_ALLOC(n
)))
2621 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n
), r
) >= 0) {
2622 CPU_ZERO_S(CPU_ALLOC_SIZE(n
), r
);
2632 if (errno
!= EINVAL
)
2639 void status_vprintf(const char *format
, va_list ap
) {
2645 /* This independent of logging, as status messages are
2646 * optional and go exclusively to the console. */
2648 if (vasprintf(&s
, format
, ap
) < 0)
2651 if ((fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
)) < 0)
2654 write(fd
, s
, strlen(s
));
2660 close_nointr_nofail(fd
);
2663 void status_printf(const char *format
, ...) {
2668 va_start(ap
, format
);
2669 status_vprintf(format
, ap
);
2673 void status_welcome(void) {
2675 #if defined(TARGET_FEDORA)
2678 if (read_one_line_file("/etc/system-release", &r
) < 0)
2683 /* This tries to mimic the color magic the old Red Hat sysinit
2686 if (startswith(r
, "Red Hat"))
2687 status_printf("Welcome to \x1B[0;31m%s\x1B[0m!\n", r
); /* Red for RHEL */
2688 else if (startswith(r
, "Fedora"))
2689 status_printf("Welcome to \x1B[0;34m%s\x1B[0m!\n", r
); /* Blue for Fedora */
2691 status_printf("Welcome to %s!\n", r
);
2695 #elif defined(TARGET_SUSE)
2698 if (read_one_line_file("/etc/SuSE-release", &r
) < 0)
2703 status_printf("Welcome to \x1B[0;32m%s\x1B[0m!\n", r
); /* Green for SUSE */
2706 #warning "You probably should add a welcome text logic here."
2710 char *replace_env(const char *format
, char **env
) {
2717 const char *e
, *word
= format
;
2722 for (e
= format
; *e
; e
++) {
2733 if (!(k
= strnappend(r
, word
, e
-word
-1)))
2742 } else if (*e
== '$') {
2743 if (!(k
= strnappend(r
, word
, e
-word
)))
2759 if ((t
= strv_env_get_with_length(env
, word
+2, e
-word
-2))) {
2760 if (!(k
= strappend(r
, t
)))
2775 if (!(k
= strnappend(r
, word
, e
-word
)))
2786 char **replace_env_argv(char **argv
, char **env
) {
2790 if (!(r
= new(char*, strv_length(argv
)+1)))
2793 STRV_FOREACH(i
, argv
) {
2794 if (!(r
[k
++] = replace_env(*i
, env
))) {
2805 static __thread
int parsed_columns
= 0;
2808 if (parsed_columns
> 0)
2809 return parsed_columns
;
2811 if ((e
= getenv("COLUMNS")))
2812 parsed_columns
= atoi(e
);
2814 if (parsed_columns
<= 0) {
2818 if (ioctl(STDIN_FILENO
, TIOCGWINSZ
, &ws
) >= 0)
2819 parsed_columns
= ws
.ws_col
;
2822 if (parsed_columns
<= 0)
2823 parsed_columns
= 80;
2825 return parsed_columns
;
2828 int running_in_chroot(void) {
2834 /* Only works as root */
2836 if (stat("/proc/1/root", &a
) < 0)
2839 if (stat("/", &b
) < 0)
2843 a
.st_dev
!= b
.st_dev
||
2844 a
.st_ino
!= b
.st_ino
;
2847 static const char *const ioprio_class_table
[] = {
2848 [IOPRIO_CLASS_NONE
] = "none",
2849 [IOPRIO_CLASS_RT
] = "realtime",
2850 [IOPRIO_CLASS_BE
] = "best-effort",
2851 [IOPRIO_CLASS_IDLE
] = "idle"
2854 DEFINE_STRING_TABLE_LOOKUP(ioprio_class
, int);
2856 static const char *const sigchld_code_table
[] = {
2857 [CLD_EXITED
] = "exited",
2858 [CLD_KILLED
] = "killed",
2859 [CLD_DUMPED
] = "dumped",
2860 [CLD_TRAPPED
] = "trapped",
2861 [CLD_STOPPED
] = "stopped",
2862 [CLD_CONTINUED
] = "continued",
2865 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
2867 static const char *const log_facility_table
[LOG_NFACILITIES
] = {
2868 [LOG_FAC(LOG_KERN
)] = "kern",
2869 [LOG_FAC(LOG_USER
)] = "user",
2870 [LOG_FAC(LOG_MAIL
)] = "mail",
2871 [LOG_FAC(LOG_DAEMON
)] = "daemon",
2872 [LOG_FAC(LOG_AUTH
)] = "auth",
2873 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
2874 [LOG_FAC(LOG_LPR
)] = "lpr",
2875 [LOG_FAC(LOG_NEWS
)] = "news",
2876 [LOG_FAC(LOG_UUCP
)] = "uucp",
2877 [LOG_FAC(LOG_CRON
)] = "cron",
2878 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
2879 [LOG_FAC(LOG_FTP
)] = "ftp",
2880 [LOG_FAC(LOG_LOCAL0
)] = "local0",
2881 [LOG_FAC(LOG_LOCAL1
)] = "local1",
2882 [LOG_FAC(LOG_LOCAL2
)] = "local2",
2883 [LOG_FAC(LOG_LOCAL3
)] = "local3",
2884 [LOG_FAC(LOG_LOCAL4
)] = "local4",
2885 [LOG_FAC(LOG_LOCAL5
)] = "local5",
2886 [LOG_FAC(LOG_LOCAL6
)] = "local6",
2887 [LOG_FAC(LOG_LOCAL7
)] = "local7"
2890 DEFINE_STRING_TABLE_LOOKUP(log_facility
, int);
2892 static const char *const log_level_table
[] = {
2893 [LOG_EMERG
] = "emerg",
2894 [LOG_ALERT
] = "alert",
2895 [LOG_CRIT
] = "crit",
2897 [LOG_WARNING
] = "warning",
2898 [LOG_NOTICE
] = "notice",
2899 [LOG_INFO
] = "info",
2900 [LOG_DEBUG
] = "debug"
2903 DEFINE_STRING_TABLE_LOOKUP(log_level
, int);
2905 static const char* const sched_policy_table
[] = {
2906 [SCHED_OTHER
] = "other",
2907 [SCHED_BATCH
] = "batch",
2908 [SCHED_IDLE
] = "idle",
2909 [SCHED_FIFO
] = "fifo",
2913 DEFINE_STRING_TABLE_LOOKUP(sched_policy
, int);
2915 static const char* const rlimit_table
[] = {
2916 [RLIMIT_CPU
] = "LimitCPU",
2917 [RLIMIT_FSIZE
] = "LimitFSIZE",
2918 [RLIMIT_DATA
] = "LimitDATA",
2919 [RLIMIT_STACK
] = "LimitSTACK",
2920 [RLIMIT_CORE
] = "LimitCORE",
2921 [RLIMIT_RSS
] = "LimitRSS",
2922 [RLIMIT_NOFILE
] = "LimitNOFILE",
2923 [RLIMIT_AS
] = "LimitAS",
2924 [RLIMIT_NPROC
] = "LimitNPROC",
2925 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
2926 [RLIMIT_LOCKS
] = "LimitLOCKS",
2927 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
2928 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
2929 [RLIMIT_NICE
] = "LimitNICE",
2930 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
2931 [RLIMIT_RTTIME
] = "LimitRTTIME"
2934 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
2936 static const char* const ip_tos_table
[] = {
2937 [IPTOS_LOWDELAY
] = "low-delay",
2938 [IPTOS_THROUGHPUT
] = "throughput",
2939 [IPTOS_RELIABILITY
] = "reliability",
2940 [IPTOS_LOWCOST
] = "low-cost",
2943 DEFINE_STRING_TABLE_LOOKUP(ip_tos
, int);