1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
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 Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser 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 #include <linux/magic.h>
67 #include "path-util.h"
68 #include "exit-status.h"
72 char **saved_argv
= NULL
;
74 size_t page_size(void) {
75 static __thread
size_t pgsz
= 0;
78 if (_likely_(pgsz
> 0))
81 assert_se((r
= sysconf(_SC_PAGESIZE
)) > 0);
88 bool streq_ptr(const char *a
, const char *b
) {
90 /* Like streq(), but tries to make sense of NULL pointers */
101 usec_t
now(clockid_t clock_id
) {
104 assert_se(clock_gettime(clock_id
, &ts
) == 0);
106 return timespec_load(&ts
);
109 dual_timestamp
* dual_timestamp_get(dual_timestamp
*ts
) {
112 ts
->realtime
= now(CLOCK_REALTIME
);
113 ts
->monotonic
= now(CLOCK_MONOTONIC
);
118 dual_timestamp
* dual_timestamp_from_realtime(dual_timestamp
*ts
, usec_t u
) {
127 delta
= (int64_t) now(CLOCK_REALTIME
) - (int64_t) u
;
129 ts
->monotonic
= now(CLOCK_MONOTONIC
);
131 if ((int64_t) ts
->monotonic
> delta
)
132 ts
->monotonic
-= delta
;
140 usec_t
timespec_load(const struct timespec
*ts
) {
144 (usec_t
) ts
->tv_sec
* USEC_PER_SEC
+
145 (usec_t
) ts
->tv_nsec
/ NSEC_PER_USEC
;
148 struct timespec
*timespec_store(struct timespec
*ts
, usec_t u
) {
151 ts
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
152 ts
->tv_nsec
= (long int) ((u
% USEC_PER_SEC
) * NSEC_PER_USEC
);
157 usec_t
timeval_load(const struct timeval
*tv
) {
161 (usec_t
) tv
->tv_sec
* USEC_PER_SEC
+
162 (usec_t
) tv
->tv_usec
;
165 struct timeval
*timeval_store(struct timeval
*tv
, usec_t u
) {
168 tv
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
169 tv
->tv_usec
= (suseconds_t
) (u
% USEC_PER_SEC
);
174 bool endswith(const char *s
, const char *postfix
) {
181 pl
= strlen(postfix
);
189 return memcmp(s
+ sl
- pl
, postfix
, pl
) == 0;
192 bool startswith(const char *s
, const char *prefix
) {
207 return memcmp(s
, prefix
, pl
) == 0;
210 bool startswith_no_case(const char *s
, const char *prefix
) {
226 for(i
= 0; i
< pl
; ++i
) {
227 if (tolower(s
[i
]) != tolower(prefix
[i
]))
234 bool first_word(const char *s
, const char *word
) {
249 if (memcmp(s
, word
, wl
) != 0)
253 strchr(WHITESPACE
, s
[wl
]);
256 int close_nointr(int fd
) {
271 void close_nointr_nofail(int fd
) {
272 int saved_errno
= errno
;
274 /* like close_nointr() but cannot fail, and guarantees errno
277 assert_se(close_nointr(fd
) == 0);
282 void close_many(const int fds
[], unsigned n_fd
) {
285 for (i
= 0; i
< n_fd
; i
++)
286 close_nointr_nofail(fds
[i
]);
289 int parse_boolean(const char *v
) {
292 if (streq(v
, "1") || v
[0] == 'y' || v
[0] == 'Y' || v
[0] == 't' || v
[0] == 'T' || !strcasecmp(v
, "on"))
294 else if (streq(v
, "0") || v
[0] == 'n' || v
[0] == 'N' || v
[0] == 'f' || v
[0] == 'F' || !strcasecmp(v
, "off"))
300 int parse_pid(const char *s
, pid_t
* ret_pid
) {
301 unsigned long ul
= 0;
308 if ((r
= safe_atolu(s
, &ul
)) < 0)
313 if ((unsigned long) pid
!= ul
)
323 int parse_uid(const char *s
, uid_t
* ret_uid
) {
324 unsigned long ul
= 0;
331 if ((r
= safe_atolu(s
, &ul
)) < 0)
336 if ((unsigned long) uid
!= ul
)
343 int safe_atou(const char *s
, unsigned *ret_u
) {
351 l
= strtoul(s
, &x
, 0);
353 if (!x
|| *x
|| errno
)
354 return errno
? -errno
: -EINVAL
;
356 if ((unsigned long) (unsigned) l
!= l
)
359 *ret_u
= (unsigned) l
;
363 int safe_atoi(const char *s
, int *ret_i
) {
371 l
= strtol(s
, &x
, 0);
373 if (!x
|| *x
|| errno
)
374 return errno
? -errno
: -EINVAL
;
376 if ((long) (int) l
!= l
)
383 int safe_atollu(const char *s
, long long unsigned *ret_llu
) {
385 unsigned long long l
;
391 l
= strtoull(s
, &x
, 0);
393 if (!x
|| *x
|| errno
)
394 return errno
? -errno
: -EINVAL
;
400 int safe_atolli(const char *s
, long long int *ret_lli
) {
408 l
= strtoll(s
, &x
, 0);
410 if (!x
|| *x
|| errno
)
411 return errno
? -errno
: -EINVAL
;
417 /* Split a string into words. */
418 char *split(const char *c
, size_t *l
, const char *separator
, char **state
) {
421 current
= *state
? *state
: (char*) c
;
423 if (!*current
|| *c
== 0)
426 current
+= strspn(current
, separator
);
427 *l
= strcspn(current
, separator
);
430 return (char*) current
;
433 /* Split a string into words, but consider strings enclosed in '' and
434 * "" as words even if they include spaces. */
435 char *split_quoted(const char *c
, size_t *l
, char **state
) {
437 bool escaped
= false;
439 current
= *state
? *state
: (char*) c
;
441 if (!*current
|| *c
== 0)
444 current
+= strspn(current
, WHITESPACE
);
446 if (*current
== '\'') {
449 for (e
= current
; *e
; e
++) {
459 *state
= *e
== 0 ? e
: e
+1;
460 } else if (*current
== '\"') {
463 for (e
= current
; *e
; e
++) {
473 *state
= *e
== 0 ? e
: e
+1;
475 for (e
= current
; *e
; e
++) {
480 else if (strchr(WHITESPACE
, *e
))
487 return (char*) current
;
490 int get_parent_of_pid(pid_t pid
, pid_t
*_ppid
) {
493 char fn
[PATH_MAX
], line
[LINE_MAX
], *p
;
499 assert_se(snprintf(fn
, sizeof(fn
)-1, "/proc/%lu/stat", (unsigned long) pid
) < (int) (sizeof(fn
)-1));
502 if (!(f
= fopen(fn
, "re")))
505 if (!(fgets(line
, sizeof(line
), f
))) {
506 r
= feof(f
) ? -EIO
: -errno
;
513 /* Let's skip the pid and comm fields. The latter is enclosed
514 * in () but does not escape any () in its value, so let's
515 * skip over it manually */
517 if (!(p
= strrchr(line
, ')')))
528 if ((long unsigned) (pid_t
) ppid
!= ppid
)
531 *_ppid
= (pid_t
) ppid
;
536 int get_starttime_of_pid(pid_t pid
, unsigned long long *st
) {
539 char fn
[PATH_MAX
], line
[LINE_MAX
], *p
;
544 assert_se(snprintf(fn
, sizeof(fn
)-1, "/proc/%lu/stat", (unsigned long) pid
) < (int) (sizeof(fn
)-1));
547 if (!(f
= fopen(fn
, "re")))
550 if (!(fgets(line
, sizeof(line
), f
))) {
551 r
= feof(f
) ? -EIO
: -errno
;
558 /* Let's skip the pid and comm fields. The latter is enclosed
559 * in () but does not escape any () in its value, so let's
560 * skip over it manually */
562 if (!(p
= strrchr(line
, ')')))
583 "%*d " /* priority */
585 "%*d " /* num_threads */
586 "%*d " /* itrealvalue */
587 "%llu " /* starttime */,
594 int write_one_line_file(const char *fn
, const char *line
) {
606 if (fputs(line
, f
) < 0) {
611 if (!endswith(line
, "\n"))
629 int fchmod_umask(int fd
, mode_t m
) {
634 r
= fchmod(fd
, m
& (~u
)) < 0 ? -errno
: 0;
640 int write_one_line_file_atomic(const char *fn
, const char *line
) {
648 r
= fopen_temporary(fn
, &f
, &p
);
652 fchmod_umask(fileno(f
), 0644);
655 if (fputs(line
, f
) < 0) {
660 if (!endswith(line
, "\n"))
671 if (rename(p
, fn
) < 0)
687 int read_one_line_file(const char *fn
, char **line
) {
690 char t
[LINE_MAX
], *c
;
699 if (!fgets(t
, sizeof(t
), f
)) {
725 int read_full_file(const char *fn
, char **contents
, size_t *size
) {
732 if (!(f
= fopen(fn
, "re")))
735 if (fstat(fileno(f
), &st
) < 0) {
741 if (st
.st_size
> 4*1024*1024) {
746 n
= st
.st_size
> 0 ? st
.st_size
: LINE_MAX
;
753 if (!(t
= realloc(buf
, n
+1))) {
759 k
= fread(buf
+ l
, 1, n
- l
, f
);
774 if (n
> 4*1024*1024) {
798 const char *separator
, ...) {
801 char *contents
= NULL
, *p
;
806 if ((r
= read_full_file(fname
, &contents
, NULL
)) < 0)
811 const char *key
= NULL
;
813 p
+= strspn(p
, separator
);
814 p
+= strspn(p
, WHITESPACE
);
819 if (!strchr(COMMENTS
, *p
)) {
823 va_start(ap
, separator
);
824 while ((key
= va_arg(ap
, char *))) {
828 value
= va_arg(ap
, char **);
831 if (strncmp(p
, key
, n
) != 0 ||
836 n
= strcspn(p
, separator
);
839 strchr(QUOTES
, p
[0]) &&
841 v
= strndup(p
+1, n
-2);
852 /* return empty value strings as NULL */
869 p
+= strcspn(p
, separator
);
888 if (!(f
= fopen(fname
, "re")))
892 char l
[LINE_MAX
], *p
, *u
;
895 if (!fgets(l
, sizeof(l
), f
)) {
908 if (strchr(COMMENTS
, *p
))
911 if (!(u
= normalize_env_assignment(p
))) {
912 log_error("Out of memory.");
917 t
= strv_append(m
, u
);
921 log_error("Out of memory.");
944 int write_env_file(const char *fname
, char **l
) {
949 r
= fopen_temporary(fname
, &f
, &p
);
953 fchmod_umask(fileno(f
), 0644);
969 if (rename(p
, fname
) < 0)
984 char *truncate_nl(char *s
) {
987 s
[strcspn(s
, NEWLINE
)] = 0;
991 int get_process_comm(pid_t pid
, char **name
) {
997 r
= read_one_line_file("/proc/self/comm", name
);
1000 if (asprintf(&p
, "/proc/%lu/comm", (unsigned long) pid
) < 0)
1003 r
= read_one_line_file(p
, name
);
1010 int get_process_cmdline(pid_t pid
, size_t max_length
, bool comm_fallback
, char **line
) {
1017 assert(max_length
> 0);
1021 f
= fopen("/proc/self/cmdline", "re");
1024 if (asprintf(&p
, "/proc/%lu/cmdline", (unsigned long) pid
) < 0)
1034 r
= new(char, max_length
);
1042 while ((c
= getc(f
)) != EOF
) {
1064 size_t n
= MIN(left
-1, 3U);
1065 memcpy(k
, "...", n
);
1072 /* Kernel threads have no argv[] */
1082 h
= get_process_comm(pid
, &t
);
1086 r
= strjoin("[", t
, "]", NULL
);
1097 int is_kernel_thread(pid_t pid
) {
1107 if (asprintf(&p
, "/proc/%lu/cmdline", (unsigned long) pid
) < 0)
1116 count
= fread(&c
, 1, 1, f
);
1120 /* Kernel threads have an empty cmdline */
1123 return eof
? 1 : -errno
;
1128 int get_process_exe(pid_t pid
, char **name
) {
1134 r
= readlink_malloc("/proc/self/exe", name
);
1137 if (asprintf(&p
, "/proc/%lu/exe", (unsigned long) pid
) < 0)
1140 r
= readlink_malloc(p
, name
);
1147 int get_process_uid(pid_t pid
, uid_t
*uid
) {
1157 if (asprintf(&p
, "/proc/%lu/status", (unsigned long) pid
) < 0)
1167 char line
[LINE_MAX
], *l
;
1169 if (!fgets(line
, sizeof(line
), f
)) {
1179 if (startswith(l
, "Uid:")) {
1181 l
+= strspn(l
, WHITESPACE
);
1183 l
[strcspn(l
, WHITESPACE
)] = 0;
1185 r
= parse_uid(l
, uid
);
1198 char *strnappend(const char *s
, const char *suffix
, size_t b
) {
1206 return strndup(suffix
, b
);
1216 if (!(r
= new(char, a
+b
+1)))
1220 memcpy(r
+a
, suffix
, b
);
1226 char *strappend(const char *s
, const char *suffix
) {
1227 return strnappend(s
, suffix
, suffix
? strlen(suffix
) : 0);
1230 int readlink_malloc(const char *p
, char **r
) {
1240 if (!(c
= new(char, l
)))
1243 if ((n
= readlink(p
, c
, l
-1)) < 0) {
1249 if ((size_t) n
< l
-1) {
1260 int readlink_and_make_absolute(const char *p
, char **r
) {
1267 if ((j
= readlink_malloc(p
, &target
)) < 0)
1270 k
= file_in_same_dir(p
, target
);
1280 int readlink_and_canonicalize(const char *p
, char **r
) {
1287 j
= readlink_and_make_absolute(p
, &t
);
1291 s
= canonicalize_file_name(t
);
1298 path_kill_slashes(*r
);
1303 int reset_all_signal_handlers(void) {
1306 for (sig
= 1; sig
< _NSIG
; sig
++) {
1307 struct sigaction sa
;
1309 if (sig
== SIGKILL
|| sig
== SIGSTOP
)
1313 sa
.sa_handler
= SIG_DFL
;
1314 sa
.sa_flags
= SA_RESTART
;
1316 /* On Linux the first two RT signals are reserved by
1317 * glibc, and sigaction() will return EINVAL for them. */
1318 if ((sigaction(sig
, &sa
, NULL
) < 0))
1319 if (errno
!= EINVAL
)
1326 char *strstrip(char *s
) {
1329 /* Drops trailing whitespace. Modifies the string in
1330 * place. Returns pointer to first non-space character */
1332 s
+= strspn(s
, WHITESPACE
);
1334 for (e
= strchr(s
, 0); e
> s
; e
--)
1335 if (!strchr(WHITESPACE
, e
[-1]))
1343 char *delete_chars(char *s
, const char *bad
) {
1346 /* Drops all whitespace, regardless where in the string */
1348 for (f
= s
, t
= s
; *f
; f
++) {
1349 if (strchr(bad
, *f
))
1360 bool in_charset(const char *s
, const char* charset
) {
1366 for (i
= s
; *i
; i
++)
1367 if (!strchr(charset
, *i
))
1373 char *file_in_same_dir(const char *path
, const char *filename
) {
1380 /* This removes the last component of path and appends
1381 * filename, unless the latter is absolute anyway or the
1384 if (path_is_absolute(filename
))
1385 return strdup(filename
);
1387 if (!(e
= strrchr(path
, '/')))
1388 return strdup(filename
);
1390 k
= strlen(filename
);
1391 if (!(r
= new(char, e
-path
+1+k
+1)))
1394 memcpy(r
, path
, e
-path
+1);
1395 memcpy(r
+(e
-path
)+1, filename
, k
+1);
1400 int rmdir_parents(const char *path
, const char *stop
) {
1409 /* Skip trailing slashes */
1410 while (l
> 0 && path
[l
-1] == '/')
1416 /* Skip last component */
1417 while (l
> 0 && path
[l
-1] != '/')
1420 /* Skip trailing slashes */
1421 while (l
> 0 && path
[l
-1] == '/')
1427 if (!(t
= strndup(path
, l
)))
1430 if (path_startswith(stop
, t
)) {
1439 if (errno
!= ENOENT
)
1447 char hexchar(int x
) {
1448 static const char table
[16] = "0123456789abcdef";
1450 return table
[x
& 15];
1453 int unhexchar(char c
) {
1455 if (c
>= '0' && c
<= '9')
1458 if (c
>= 'a' && c
<= 'f')
1459 return c
- 'a' + 10;
1461 if (c
>= 'A' && c
<= 'F')
1462 return c
- 'A' + 10;
1467 char octchar(int x
) {
1468 return '0' + (x
& 7);
1471 int unoctchar(char c
) {
1473 if (c
>= '0' && c
<= '7')
1479 char decchar(int x
) {
1480 return '0' + (x
% 10);
1483 int undecchar(char c
) {
1485 if (c
>= '0' && c
<= '9')
1491 char *cescape(const char *s
) {
1497 /* Does C style string escaping. */
1499 r
= new(char, strlen(s
)*4 + 1);
1503 for (f
= s
, t
= r
; *f
; f
++)
1549 /* For special chars we prefer octal over
1550 * hexadecimal encoding, simply because glib's
1551 * g_strescape() does the same */
1552 if ((*f
< ' ') || (*f
>= 127)) {
1554 *(t
++) = octchar((unsigned char) *f
>> 6);
1555 *(t
++) = octchar((unsigned char) *f
>> 3);
1556 *(t
++) = octchar((unsigned char) *f
);
1567 char *cunescape_length(const char *s
, size_t length
) {
1573 /* Undoes C style string escaping */
1575 r
= new(char, length
+1);
1579 for (f
= s
, t
= r
; f
< s
+ length
; f
++) {
1622 /* This is an extension of the XDG syntax files */
1627 /* hexadecimal encoding */
1630 a
= unhexchar(f
[1]);
1631 b
= unhexchar(f
[2]);
1633 if (a
< 0 || b
< 0) {
1634 /* Invalid escape code, let's take it literal then */
1638 *(t
++) = (char) ((a
<< 4) | b
);
1653 /* octal encoding */
1656 a
= unoctchar(f
[0]);
1657 b
= unoctchar(f
[1]);
1658 c
= unoctchar(f
[2]);
1660 if (a
< 0 || b
< 0 || c
< 0) {
1661 /* Invalid escape code, let's take it literal then */
1665 *(t
++) = (char) ((a
<< 6) | (b
<< 3) | c
);
1673 /* premature end of string.*/
1678 /* Invalid escape code, let's take it literal then */
1690 char *cunescape(const char *s
) {
1691 return cunescape_length(s
, strlen(s
));
1694 char *xescape(const char *s
, const char *bad
) {
1698 /* Escapes all chars in bad, in addition to \ and all special
1699 * chars, in \xFF style escaping. May be reversed with
1702 if (!(r
= new(char, strlen(s
)*4+1)))
1705 for (f
= s
, t
= r
; *f
; f
++) {
1707 if ((*f
< ' ') || (*f
>= 127) ||
1708 (*f
== '\\') || strchr(bad
, *f
)) {
1711 *(t
++) = hexchar(*f
>> 4);
1712 *(t
++) = hexchar(*f
);
1722 char *bus_path_escape(const char *s
) {
1728 /* Escapes all chars that D-Bus' object path cannot deal
1729 * with. Can be reverse with bus_path_unescape() */
1731 if (!(r
= new(char, strlen(s
)*3+1)))
1734 for (f
= s
, t
= r
; *f
; f
++) {
1736 if (!(*f
>= 'A' && *f
<= 'Z') &&
1737 !(*f
>= 'a' && *f
<= 'z') &&
1738 !(*f
>= '0' && *f
<= '9')) {
1740 *(t
++) = hexchar(*f
>> 4);
1741 *(t
++) = hexchar(*f
);
1751 char *bus_path_unescape(const char *f
) {
1756 if (!(r
= strdup(f
)))
1759 for (t
= r
; *f
; f
++) {
1764 if ((a
= unhexchar(f
[1])) < 0 ||
1765 (b
= unhexchar(f
[2])) < 0) {
1766 /* Invalid escape code, let's take it literal then */
1769 *(t
++) = (char) ((a
<< 4) | b
);
1781 char *ascii_strlower(char *t
) {
1786 for (p
= t
; *p
; p
++)
1787 if (*p
>= 'A' && *p
<= 'Z')
1788 *p
= *p
- 'A' + 'a';
1793 bool ignore_file(const char *filename
) {
1797 filename
[0] == '.' ||
1798 streq(filename
, "lost+found") ||
1799 streq(filename
, "aquota.user") ||
1800 streq(filename
, "aquota.group") ||
1801 endswith(filename
, "~") ||
1802 endswith(filename
, ".rpmnew") ||
1803 endswith(filename
, ".rpmsave") ||
1804 endswith(filename
, ".rpmorig") ||
1805 endswith(filename
, ".dpkg-old") ||
1806 endswith(filename
, ".dpkg-new") ||
1807 endswith(filename
, ".swp");
1810 int fd_nonblock(int fd
, bool nonblock
) {
1815 if ((flags
= fcntl(fd
, F_GETFL
, 0)) < 0)
1819 flags
|= O_NONBLOCK
;
1821 flags
&= ~O_NONBLOCK
;
1823 if (fcntl(fd
, F_SETFL
, flags
) < 0)
1829 int fd_cloexec(int fd
, bool cloexec
) {
1834 if ((flags
= fcntl(fd
, F_GETFD
, 0)) < 0)
1838 flags
|= FD_CLOEXEC
;
1840 flags
&= ~FD_CLOEXEC
;
1842 if (fcntl(fd
, F_SETFD
, flags
) < 0)
1848 static bool fd_in_set(int fd
, const int fdset
[], unsigned n_fdset
) {
1851 assert(n_fdset
== 0 || fdset
);
1853 for (i
= 0; i
< n_fdset
; i
++)
1860 int close_all_fds(const int except
[], unsigned n_except
) {
1865 assert(n_except
== 0 || except
);
1867 d
= opendir("/proc/self/fd");
1872 /* When /proc isn't available (for example in chroots)
1873 * the fallback is brute forcing through the fd
1876 assert_se(getrlimit(RLIMIT_NOFILE
, &rl
) >= 0);
1877 for (fd
= 3; fd
< (int) rl
.rlim_max
; fd
++) {
1879 if (fd_in_set(fd
, except
, n_except
))
1882 if (close_nointr(fd
) < 0)
1883 if (errno
!= EBADF
&& r
== 0)
1890 while ((de
= readdir(d
))) {
1893 if (ignore_file(de
->d_name
))
1896 if (safe_atoi(de
->d_name
, &fd
) < 0)
1897 /* Let's better ignore this, just in case */
1906 if (fd_in_set(fd
, except
, n_except
))
1909 if (close_nointr(fd
) < 0) {
1910 /* Valgrind has its own FD and doesn't want to have it closed */
1911 if (errno
!= EBADF
&& r
== 0)
1920 bool chars_intersect(const char *a
, const char *b
) {
1923 /* Returns true if any of the chars in a are in b. */
1924 for (p
= a
; *p
; p
++)
1931 char *format_timestamp(char *buf
, size_t l
, usec_t t
) {
1941 sec
= (time_t) (t
/ USEC_PER_SEC
);
1943 if (strftime(buf
, l
, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec
, &tm
)) <= 0)
1949 char *format_timestamp_pretty(char *buf
, size_t l
, usec_t t
) {
1952 n
= now(CLOCK_REALTIME
);
1954 if (t
<= 0 || t
> n
|| t
+ USEC_PER_DAY
*7 <= t
)
1959 if (d
>= USEC_PER_YEAR
)
1960 snprintf(buf
, l
, "%llu years and %llu months ago",
1961 (unsigned long long) (d
/ USEC_PER_YEAR
),
1962 (unsigned long long) ((d
% USEC_PER_YEAR
) / USEC_PER_MONTH
));
1963 else if (d
>= USEC_PER_MONTH
)
1964 snprintf(buf
, l
, "%llu months and %llu days ago",
1965 (unsigned long long) (d
/ USEC_PER_MONTH
),
1966 (unsigned long long) ((d
% USEC_PER_MONTH
) / USEC_PER_DAY
));
1967 else if (d
>= USEC_PER_WEEK
)
1968 snprintf(buf
, l
, "%llu weeks and %llu days ago",
1969 (unsigned long long) (d
/ USEC_PER_WEEK
),
1970 (unsigned long long) ((d
% USEC_PER_WEEK
) / USEC_PER_DAY
));
1971 else if (d
>= 2*USEC_PER_DAY
)
1972 snprintf(buf
, l
, "%llu days ago", (unsigned long long) (d
/ USEC_PER_DAY
));
1973 else if (d
>= 25*USEC_PER_HOUR
)
1974 snprintf(buf
, l
, "1 day and %lluh ago",
1975 (unsigned long long) ((d
- USEC_PER_DAY
) / USEC_PER_HOUR
));
1976 else if (d
>= 6*USEC_PER_HOUR
)
1977 snprintf(buf
, l
, "%lluh ago",
1978 (unsigned long long) (d
/ USEC_PER_HOUR
));
1979 else if (d
>= USEC_PER_HOUR
)
1980 snprintf(buf
, l
, "%lluh %llumin ago",
1981 (unsigned long long) (d
/ USEC_PER_HOUR
),
1982 (unsigned long long) ((d
% USEC_PER_HOUR
) / USEC_PER_MINUTE
));
1983 else if (d
>= 5*USEC_PER_MINUTE
)
1984 snprintf(buf
, l
, "%llumin ago",
1985 (unsigned long long) (d
/ USEC_PER_MINUTE
));
1986 else if (d
>= USEC_PER_MINUTE
)
1987 snprintf(buf
, l
, "%llumin %llus ago",
1988 (unsigned long long) (d
/ USEC_PER_MINUTE
),
1989 (unsigned long long) ((d
% USEC_PER_MINUTE
) / USEC_PER_SEC
));
1990 else if (d
>= USEC_PER_SEC
)
1991 snprintf(buf
, l
, "%llus ago",
1992 (unsigned long long) (d
/ USEC_PER_SEC
));
1993 else if (d
>= USEC_PER_MSEC
)
1994 snprintf(buf
, l
, "%llums ago",
1995 (unsigned long long) (d
/ USEC_PER_MSEC
));
1997 snprintf(buf
, l
, "%lluus ago",
1998 (unsigned long long) d
);
2000 snprintf(buf
, l
, "now");
2006 char *format_timespan(char *buf
, size_t l
, usec_t t
) {
2007 static const struct {
2011 { "w", USEC_PER_WEEK
},
2012 { "d", USEC_PER_DAY
},
2013 { "h", USEC_PER_HOUR
},
2014 { "min", USEC_PER_MINUTE
},
2015 { "s", USEC_PER_SEC
},
2016 { "ms", USEC_PER_MSEC
},
2026 if (t
== (usec_t
) -1)
2030 snprintf(p
, l
, "0");
2035 /* The result of this function can be parsed with parse_usec */
2037 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
2041 if (t
< table
[i
].usec
)
2047 k
= snprintf(p
, l
, "%s%llu%s", p
> buf
? " " : "", (unsigned long long) (t
/ table
[i
].usec
), table
[i
].suffix
);
2048 n
= MIN((size_t) k
, l
);
2061 bool fstype_is_network(const char *fstype
) {
2062 static const char * const table
[] = {
2074 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
2075 if (streq(table
[i
], fstype
))
2084 if ((fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
)) < 0)
2089 TIOCL_GETKMSGREDIRECT
,
2093 if (ioctl(fd
, TIOCLINUX
, tiocl
) < 0) {
2098 vt
= tiocl
[0] <= 0 ? 1 : tiocl
[0];
2101 if (ioctl(fd
, VT_ACTIVATE
, vt
) < 0)
2105 close_nointr_nofail(fd
);
2109 int read_one_char(FILE *f
, char *ret
, usec_t t
, bool *need_nl
) {
2110 struct termios old_termios
, new_termios
;
2112 char line
[LINE_MAX
];
2117 if (tcgetattr(fileno(f
), &old_termios
) >= 0) {
2118 new_termios
= old_termios
;
2120 new_termios
.c_lflag
&= ~ICANON
;
2121 new_termios
.c_cc
[VMIN
] = 1;
2122 new_termios
.c_cc
[VTIME
] = 0;
2124 if (tcsetattr(fileno(f
), TCSADRAIN
, &new_termios
) >= 0) {
2127 if (t
!= (usec_t
) -1) {
2128 if (fd_wait_for_event(fileno(f
), POLLIN
, t
) <= 0) {
2129 tcsetattr(fileno(f
), TCSADRAIN
, &old_termios
);
2134 k
= fread(&c
, 1, 1, f
);
2136 tcsetattr(fileno(f
), TCSADRAIN
, &old_termios
);
2142 *need_nl
= c
!= '\n';
2149 if (t
!= (usec_t
) -1)
2150 if (fd_wait_for_event(fileno(f
), POLLIN
, t
) <= 0)
2153 if (!fgets(line
, sizeof(line
), f
))
2158 if (strlen(line
) != 1)
2168 int ask(char *ret
, const char *replies
, const char *text
, ...) {
2175 on_tty
= isatty(STDOUT_FILENO
);
2181 bool need_nl
= true;
2184 fputs(ANSI_HIGHLIGHT_ON
, stdout
);
2191 fputs(ANSI_HIGHLIGHT_OFF
, stdout
);
2195 r
= read_one_char(stdin
, &c
, (usec_t
) -1, &need_nl
);
2198 if (r
== -EBADMSG
) {
2199 puts("Bad input, please try again.");
2210 if (strchr(replies
, c
)) {
2215 puts("Read unexpected character, please try again.");
2219 int reset_terminal_fd(int fd
, bool switch_to_text
) {
2220 struct termios termios
;
2223 /* Set terminal to some sane defaults */
2227 /* We leave locked terminal attributes untouched, so that
2228 * Plymouth may set whatever it wants to set, and we don't
2229 * interfere with that. */
2231 /* Disable exclusive mode, just in case */
2232 ioctl(fd
, TIOCNXCL
);
2234 /* Switch to text mode */
2236 ioctl(fd
, KDSETMODE
, KD_TEXT
);
2238 /* Enable console unicode mode */
2239 ioctl(fd
, KDSKBMODE
, K_UNICODE
);
2241 if (tcgetattr(fd
, &termios
) < 0) {
2246 /* We only reset the stuff that matters to the software. How
2247 * hardware is set up we don't touch assuming that somebody
2248 * else will do that for us */
2250 termios
.c_iflag
&= ~(IGNBRK
| BRKINT
| ISTRIP
| INLCR
| IGNCR
| IUCLC
);
2251 termios
.c_iflag
|= ICRNL
| IMAXBEL
| IUTF8
;
2252 termios
.c_oflag
|= ONLCR
;
2253 termios
.c_cflag
|= CREAD
;
2254 termios
.c_lflag
= ISIG
| ICANON
| IEXTEN
| ECHO
| ECHOE
| ECHOK
| ECHOCTL
| ECHOPRT
| ECHOKE
;
2256 termios
.c_cc
[VINTR
] = 03; /* ^C */
2257 termios
.c_cc
[VQUIT
] = 034; /* ^\ */
2258 termios
.c_cc
[VERASE
] = 0177;
2259 termios
.c_cc
[VKILL
] = 025; /* ^X */
2260 termios
.c_cc
[VEOF
] = 04; /* ^D */
2261 termios
.c_cc
[VSTART
] = 021; /* ^Q */
2262 termios
.c_cc
[VSTOP
] = 023; /* ^S */
2263 termios
.c_cc
[VSUSP
] = 032; /* ^Z */
2264 termios
.c_cc
[VLNEXT
] = 026; /* ^V */
2265 termios
.c_cc
[VWERASE
] = 027; /* ^W */
2266 termios
.c_cc
[VREPRINT
] = 022; /* ^R */
2267 termios
.c_cc
[VEOL
] = 0;
2268 termios
.c_cc
[VEOL2
] = 0;
2270 termios
.c_cc
[VTIME
] = 0;
2271 termios
.c_cc
[VMIN
] = 1;
2273 if (tcsetattr(fd
, TCSANOW
, &termios
) < 0)
2277 /* Just in case, flush all crap out */
2278 tcflush(fd
, TCIOFLUSH
);
2283 int reset_terminal(const char *name
) {
2286 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
2290 r
= reset_terminal_fd(fd
, true);
2291 close_nointr_nofail(fd
);
2296 int open_terminal(const char *name
, int mode
) {
2301 * If a TTY is in the process of being closed opening it might
2302 * cause EIO. This is horribly awful, but unlikely to be
2303 * changed in the kernel. Hence we work around this problem by
2304 * retrying a couple of times.
2306 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/554172/comments/245
2310 fd
= open(name
, mode
);
2317 /* Max 1s in total */
2321 usleep(50 * USEC_PER_MSEC
);
2330 close_nointr_nofail(fd
);
2335 close_nointr_nofail(fd
);
2342 int flush_fd(int fd
) {
2343 struct pollfd pollfd
;
2347 pollfd
.events
= POLLIN
;
2354 if ((r
= poll(&pollfd
, 1, 0)) < 0) {
2365 if ((l
= read(fd
, buf
, sizeof(buf
))) < 0) {
2370 if (errno
== EAGAIN
)
2381 int acquire_terminal(
2385 bool ignore_tiocstty_eperm
,
2388 int fd
= -1, notify
= -1, r
= 0, wd
= -1;
2390 struct sigaction sa_old
, sa_new
;
2394 /* We use inotify to be notified when the tty is closed. We
2395 * create the watch before checking if we can actually acquire
2396 * it, so that we don't lose any event.
2398 * Note: strictly speaking this actually watches for the
2399 * device being closed, it does *not* really watch whether a
2400 * tty loses its controlling process. However, unless some
2401 * rogue process uses TIOCNOTTY on /dev/tty *after* closing
2402 * its tty otherwise this will not become a problem. As long
2403 * as the administrator makes sure not configure any service
2404 * on the same tty as an untrusted user this should not be a
2405 * problem. (Which he probably should not do anyway.) */
2407 if (timeout
!= (usec_t
) -1)
2408 ts
= now(CLOCK_MONOTONIC
);
2410 if (!fail
&& !force
) {
2411 notify
= inotify_init1(IN_CLOEXEC
| (timeout
!= (usec_t
) -1 ? IN_NONBLOCK
: 0));
2417 wd
= inotify_add_watch(notify
, name
, IN_CLOSE
);
2426 r
= flush_fd(notify
);
2431 /* We pass here O_NOCTTY only so that we can check the return
2432 * value TIOCSCTTY and have a reliable way to figure out if we
2433 * successfully became the controlling process of the tty */
2434 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
2438 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2439 * if we already own the tty. */
2441 sa_new
.sa_handler
= SIG_IGN
;
2442 sa_new
.sa_flags
= SA_RESTART
;
2443 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
2445 /* First, try to get the tty */
2446 if (ioctl(fd
, TIOCSCTTY
, force
) < 0)
2449 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
2451 /* Sometimes it makes sense to ignore TIOCSCTTY
2452 * returning EPERM, i.e. when very likely we already
2453 * are have this controlling terminal. */
2454 if (r
< 0 && r
== -EPERM
&& ignore_tiocstty_eperm
)
2457 if (r
< 0 && (force
|| fail
|| r
!= -EPERM
)) {
2466 assert(notify
>= 0);
2469 uint8_t inotify_buffer
[sizeof(struct inotify_event
) + FILENAME_MAX
];
2471 struct inotify_event
*e
;
2473 if (timeout
!= (usec_t
) -1) {
2476 n
= now(CLOCK_MONOTONIC
);
2477 if (ts
+ timeout
< n
) {
2482 r
= fd_wait_for_event(fd
, POLLIN
, ts
+ timeout
- n
);
2492 l
= read(notify
, inotify_buffer
, sizeof(inotify_buffer
));
2495 if (errno
== EINTR
|| errno
== EAGAIN
)
2502 e
= (struct inotify_event
*) inotify_buffer
;
2507 if (e
->wd
!= wd
|| !(e
->mask
& IN_CLOSE
)) {
2512 step
= sizeof(struct inotify_event
) + e
->len
;
2513 assert(step
<= (size_t) l
);
2515 e
= (struct inotify_event
*) ((uint8_t*) e
+ step
);
2522 /* We close the tty fd here since if the old session
2523 * ended our handle will be dead. It's important that
2524 * we do this after sleeping, so that we don't enter
2525 * an endless loop. */
2526 close_nointr_nofail(fd
);
2530 close_nointr_nofail(notify
);
2532 r
= reset_terminal_fd(fd
, true);
2534 log_warning("Failed to reset terminal: %s", strerror(-r
));
2540 close_nointr_nofail(fd
);
2543 close_nointr_nofail(notify
);
2548 int release_terminal(void) {
2550 struct sigaction sa_old
, sa_new
;
2552 if ((fd
= open("/dev/tty", O_RDWR
|O_NOCTTY
|O_NDELAY
|O_CLOEXEC
)) < 0)
2555 /* Temporarily ignore SIGHUP, so that we don't get SIGHUP'ed
2556 * by our own TIOCNOTTY */
2559 sa_new
.sa_handler
= SIG_IGN
;
2560 sa_new
.sa_flags
= SA_RESTART
;
2561 assert_se(sigaction(SIGHUP
, &sa_new
, &sa_old
) == 0);
2563 if (ioctl(fd
, TIOCNOTTY
) < 0)
2566 assert_se(sigaction(SIGHUP
, &sa_old
, NULL
) == 0);
2568 close_nointr_nofail(fd
);
2572 int sigaction_many(const struct sigaction
*sa
, ...) {
2577 while ((sig
= va_arg(ap
, int)) > 0)
2578 if (sigaction(sig
, sa
, NULL
) < 0)
2585 int ignore_signals(int sig
, ...) {
2586 struct sigaction sa
;
2591 sa
.sa_handler
= SIG_IGN
;
2592 sa
.sa_flags
= SA_RESTART
;
2594 if (sigaction(sig
, &sa
, NULL
) < 0)
2598 while ((sig
= va_arg(ap
, int)) > 0)
2599 if (sigaction(sig
, &sa
, NULL
) < 0)
2606 int default_signals(int sig
, ...) {
2607 struct sigaction sa
;
2612 sa
.sa_handler
= SIG_DFL
;
2613 sa
.sa_flags
= SA_RESTART
;
2615 if (sigaction(sig
, &sa
, NULL
) < 0)
2619 while ((sig
= va_arg(ap
, int)) > 0)
2620 if (sigaction(sig
, &sa
, NULL
) < 0)
2627 int close_pipe(int p
[]) {
2633 a
= close_nointr(p
[0]);
2638 b
= close_nointr(p
[1]);
2642 return a
< 0 ? a
: b
;
2645 ssize_t
loop_read(int fd
, void *buf
, size_t nbytes
, bool do_poll
) {
2654 while (nbytes
> 0) {
2657 if ((k
= read(fd
, p
, nbytes
)) <= 0) {
2659 if (k
< 0 && errno
== EINTR
)
2662 if (k
< 0 && errno
== EAGAIN
&& do_poll
) {
2663 struct pollfd pollfd
;
2667 pollfd
.events
= POLLIN
;
2669 if (poll(&pollfd
, 1, -1) < 0) {
2673 return n
> 0 ? n
: -errno
;
2676 if (pollfd
.revents
!= POLLIN
)
2677 return n
> 0 ? n
: -EIO
;
2682 return n
> 0 ? n
: (k
< 0 ? -errno
: 0);
2693 ssize_t
loop_write(int fd
, const void *buf
, size_t nbytes
, bool do_poll
) {
2702 while (nbytes
> 0) {
2705 k
= write(fd
, p
, nbytes
);
2708 if (k
< 0 && errno
== EINTR
)
2711 if (k
< 0 && errno
== EAGAIN
&& do_poll
) {
2712 struct pollfd pollfd
;
2716 pollfd
.events
= POLLOUT
;
2718 if (poll(&pollfd
, 1, -1) < 0) {
2722 return n
> 0 ? n
: -errno
;
2725 if (pollfd
.revents
!= POLLOUT
)
2726 return n
> 0 ? n
: -EIO
;
2731 return n
> 0 ? n
: (k
< 0 ? -errno
: 0);
2742 int parse_usec(const char *t
, usec_t
*usec
) {
2743 static const struct {
2747 { "sec", USEC_PER_SEC
},
2748 { "s", USEC_PER_SEC
},
2749 { "min", USEC_PER_MINUTE
},
2750 { "hr", USEC_PER_HOUR
},
2751 { "h", USEC_PER_HOUR
},
2752 { "d", USEC_PER_DAY
},
2753 { "w", USEC_PER_WEEK
},
2754 { "msec", USEC_PER_MSEC
},
2755 { "ms", USEC_PER_MSEC
},
2756 { "m", USEC_PER_MINUTE
},
2759 { "", USEC_PER_SEC
}, /* default is sec */
2775 l
= strtoll(p
, &e
, 10);
2786 e
+= strspn(e
, WHITESPACE
);
2788 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
2789 if (startswith(e
, table
[i
].suffix
)) {
2790 r
+= (usec_t
) l
* table
[i
].usec
;
2791 p
= e
+ strlen(table
[i
].suffix
);
2795 if (i
>= ELEMENTSOF(table
))
2805 int parse_nsec(const char *t
, nsec_t
*nsec
) {
2806 static const struct {
2810 { "sec", NSEC_PER_SEC
},
2811 { "s", NSEC_PER_SEC
},
2812 { "min", NSEC_PER_MINUTE
},
2813 { "hr", NSEC_PER_HOUR
},
2814 { "h", NSEC_PER_HOUR
},
2815 { "d", NSEC_PER_DAY
},
2816 { "w", NSEC_PER_WEEK
},
2817 { "msec", NSEC_PER_MSEC
},
2818 { "ms", NSEC_PER_MSEC
},
2819 { "m", NSEC_PER_MINUTE
},
2820 { "usec", NSEC_PER_USEC
},
2821 { "us", NSEC_PER_USEC
},
2824 { "", 1ULL }, /* default is nsec */
2840 l
= strtoll(p
, &e
, 10);
2851 e
+= strspn(e
, WHITESPACE
);
2853 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
2854 if (startswith(e
, table
[i
].suffix
)) {
2855 r
+= (nsec_t
) l
* table
[i
].nsec
;
2856 p
= e
+ strlen(table
[i
].suffix
);
2860 if (i
>= ELEMENTSOF(table
))
2870 int parse_bytes(const char *t
, off_t
*bytes
) {
2871 static const struct {
2877 { "M", 1024ULL*1024ULL },
2878 { "G", 1024ULL*1024ULL*1024ULL },
2879 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
2880 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2881 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
2898 l
= strtoll(p
, &e
, 10);
2909 e
+= strspn(e
, WHITESPACE
);
2911 for (i
= 0; i
< ELEMENTSOF(table
); i
++)
2912 if (startswith(e
, table
[i
].suffix
)) {
2913 r
+= (off_t
) l
* table
[i
].factor
;
2914 p
= e
+ strlen(table
[i
].suffix
);
2918 if (i
>= ELEMENTSOF(table
))
2928 int make_stdio(int fd
) {
2933 r
= dup2(fd
, STDIN_FILENO
);
2934 s
= dup2(fd
, STDOUT_FILENO
);
2935 t
= dup2(fd
, STDERR_FILENO
);
2938 close_nointr_nofail(fd
);
2940 if (r
< 0 || s
< 0 || t
< 0)
2943 fd_cloexec(STDIN_FILENO
, false);
2944 fd_cloexec(STDOUT_FILENO
, false);
2945 fd_cloexec(STDERR_FILENO
, false);
2950 int make_null_stdio(void) {
2953 null_fd
= open("/dev/null", O_RDWR
|O_NOCTTY
);
2957 return make_stdio(null_fd
);
2960 bool is_device_path(const char *path
) {
2962 /* Returns true on paths that refer to a device, either in
2963 * sysfs or in /dev */
2966 path_startswith(path
, "/dev/") ||
2967 path_startswith(path
, "/sys/");
2970 int dir_is_empty(const char *path
) {
2973 struct dirent buf
, *de
;
2975 if (!(d
= opendir(path
)))
2979 if ((r
= readdir_r(d
, &buf
, &de
)) > 0) {
2989 if (!ignore_file(de
->d_name
)) {
2999 unsigned long long random_ull(void) {
3004 if ((fd
= open("/dev/urandom", O_RDONLY
|O_CLOEXEC
|O_NOCTTY
)) < 0)
3007 r
= loop_read(fd
, &ull
, sizeof(ull
), true);
3008 close_nointr_nofail(fd
);
3010 if (r
!= sizeof(ull
))
3016 return random() * RAND_MAX
+ random();
3019 void rename_process(const char name
[8]) {
3022 /* This is a like a poor man's setproctitle(). It changes the
3023 * comm field, argv[0], and also the glibc's internally used
3024 * name of the process. For the first one a limit of 16 chars
3025 * applies, to the second one usually one of 10 (i.e. length
3026 * of "/sbin/init"), to the third one one of 7 (i.e. length of
3027 * "systemd"). If you pass a longer string it will be
3030 prctl(PR_SET_NAME
, name
);
3032 if (program_invocation_name
)
3033 strncpy(program_invocation_name
, name
, strlen(program_invocation_name
));
3035 if (saved_argc
> 0) {
3039 strncpy(saved_argv
[0], name
, strlen(saved_argv
[0]));
3041 for (i
= 1; i
< saved_argc
; i
++) {
3045 memset(saved_argv
[i
], 0, strlen(saved_argv
[i
]));
3050 void sigset_add_many(sigset_t
*ss
, ...) {
3057 while ((sig
= va_arg(ap
, int)) > 0)
3058 assert_se(sigaddset(ss
, sig
) == 0);
3062 char* gethostname_malloc(void) {
3065 assert_se(uname(&u
) >= 0);
3067 if (!isempty(u
.nodename
) && !streq(u
.nodename
, "(none)"))
3068 return strdup(u
.nodename
);
3070 return strdup(u
.sysname
);
3073 bool hostname_is_set(void) {
3076 assert_se(uname(&u
) >= 0);
3078 return !isempty(u
.nodename
) && !streq(u
.nodename
, "(none)");
3082 static char *lookup_uid(uid_t uid
) {
3085 struct passwd pwbuf
, *pw
= NULL
;
3087 /* Shortcut things to avoid NSS lookups */
3089 return strdup("root");
3091 bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
3095 buf
= malloc(bufsize
);
3099 if (getpwuid_r(uid
, &pwbuf
, buf
, bufsize
, &pw
) == 0 && pw
) {
3100 name
= strdup(pw
->pw_name
);
3107 if (asprintf(&name
, "%lu", (unsigned long) uid
) < 0)
3113 char* getlogname_malloc(void) {
3117 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
3122 return lookup_uid(uid
);
3125 char *getusername_malloc(void) {
3132 return lookup_uid(getuid());
3135 int getttyname_malloc(int fd
, char **r
) {
3136 char path
[PATH_MAX
], *c
;
3141 if ((k
= ttyname_r(fd
, path
, sizeof(path
))) != 0)
3146 if (!(c
= strdup(startswith(path
, "/dev/") ? path
+ 5 : path
)))
3153 int getttyname_harder(int fd
, char **r
) {
3157 if ((k
= getttyname_malloc(fd
, &s
)) < 0)
3160 if (streq(s
, "tty")) {
3162 return get_ctty(0, NULL
, r
);
3169 int get_ctty_devnr(pid_t pid
, dev_t
*d
) {
3171 char line
[LINE_MAX
], *p
, *fn
;
3172 unsigned long ttynr
;
3175 if (asprintf(&fn
, "/proc/%lu/stat", (unsigned long) (pid
<= 0 ? getpid() : pid
)) < 0)
3178 f
= fopen(fn
, "re");
3183 if (!fgets(line
, sizeof(line
), f
)) {
3184 k
= feof(f
) ? -EIO
: -errno
;
3191 p
= strrchr(line
, ')');
3201 "%*d " /* session */
3210 int get_ctty(pid_t pid
, dev_t
*_devnr
, char **r
) {
3212 char fn
[PATH_MAX
], *s
, *b
, *p
;
3217 k
= get_ctty_devnr(pid
, &devnr
);
3221 snprintf(fn
, sizeof(fn
), "/dev/char/%u:%u", major(devnr
), minor(devnr
));
3224 if ((k
= readlink_malloc(fn
, &s
)) < 0) {
3229 /* This is an ugly hack */
3230 if (major(devnr
) == 136) {
3231 if (asprintf(&b
, "pts/%lu", (unsigned long) minor(devnr
)) < 0)
3241 /* Probably something like the ptys which have no
3242 * symlink in /dev/char. Let's return something
3243 * vaguely useful. */
3245 if (!(b
= strdup(fn
+ 5)))
3255 if (startswith(s
, "/dev/"))
3257 else if (startswith(s
, "../"))
3275 int rm_rf_children_dangerous(int fd
, bool only_dirs
, bool honour_sticky
, struct stat
*root_dev
) {
3281 /* This returns the first error we run into, but nevertheless
3282 * tries to go on. This closes the passed fd. */
3286 close_nointr_nofail(fd
);
3288 return errno
== ENOENT
? 0 : -errno
;
3292 struct dirent buf
, *de
;
3293 bool is_dir
, keep_around
;
3297 r
= readdir_r(d
, &buf
, &de
);
3298 if (r
!= 0 && ret
== 0) {
3306 if (streq(de
->d_name
, ".") || streq(de
->d_name
, ".."))
3309 if (de
->d_type
== DT_UNKNOWN
||
3311 (de
->d_type
== DT_DIR
&& root_dev
)) {
3312 if (fstatat(fd
, de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0) {
3313 if (ret
== 0 && errno
!= ENOENT
)
3318 is_dir
= S_ISDIR(st
.st_mode
);
3321 (st
.st_uid
== 0 || st
.st_uid
== getuid()) &&
3322 (st
.st_mode
& S_ISVTX
);
3324 is_dir
= de
->d_type
== DT_DIR
;
3325 keep_around
= false;
3331 /* if root_dev is set, remove subdirectories only, if device is same as dir */
3332 if (root_dev
&& st
.st_dev
!= root_dev
->st_dev
)
3335 subdir_fd
= openat(fd
, de
->d_name
,
3336 O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|O_NOFOLLOW
|O_NOATIME
);
3337 if (subdir_fd
< 0) {
3338 if (ret
== 0 && errno
!= ENOENT
)
3343 r
= rm_rf_children(subdir_fd
, only_dirs
, honour_sticky
, root_dev
);
3344 if (r
< 0 && ret
== 0)
3348 if (unlinkat(fd
, de
->d_name
, AT_REMOVEDIR
) < 0) {
3349 if (ret
== 0 && errno
!= ENOENT
)
3353 } else if (!only_dirs
&& !keep_around
) {
3355 if (unlinkat(fd
, de
->d_name
, 0) < 0) {
3356 if (ret
== 0 && errno
!= ENOENT
)
3367 int rm_rf_children(int fd
, bool only_dirs
, bool honour_sticky
, struct stat
*root_dev
) {
3372 if (fstatfs(fd
, &s
) < 0) {
3373 close_nointr_nofail(fd
);
3377 /* We refuse to clean disk file systems with this call. This
3378 * is extra paranoia just to be sure we never ever remove
3381 if (s
.f_type
!= TMPFS_MAGIC
&&
3382 s
.f_type
!= RAMFS_MAGIC
) {
3383 log_error("Attempted to remove disk file system, and we can't allow that.");
3384 close_nointr_nofail(fd
);
3388 return rm_rf_children_dangerous(fd
, only_dirs
, honour_sticky
, root_dev
);
3391 static int rm_rf_internal(const char *path
, bool only_dirs
, bool delete_root
, bool honour_sticky
, bool dangerous
) {
3397 /* We refuse to clean the root file system with this
3398 * call. This is extra paranoia to never cause a really
3399 * seriously broken system. */
3400 if (path_equal(path
, "/")) {
3401 log_error("Attempted to remove entire root file system, and we can't allow that.");
3405 fd
= open(path
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|O_NOFOLLOW
|O_NOATIME
);
3408 if (errno
!= ENOTDIR
)
3412 if (statfs(path
, &s
) < 0)
3415 if (s
.f_type
!= TMPFS_MAGIC
&&
3416 s
.f_type
!= RAMFS_MAGIC
) {
3417 log_error("Attempted to remove disk file system, and we can't allow that.");
3422 if (delete_root
&& !only_dirs
)
3423 if (unlink(path
) < 0 && errno
!= ENOENT
)
3430 if (fstatfs(fd
, &s
) < 0) {
3431 close_nointr_nofail(fd
);
3435 if (s
.f_type
!= TMPFS_MAGIC
&&
3436 s
.f_type
!= RAMFS_MAGIC
) {
3437 log_error("Attempted to remove disk file system, and we can't allow that.");
3438 close_nointr_nofail(fd
);
3443 r
= rm_rf_children_dangerous(fd
, only_dirs
, honour_sticky
, NULL
);
3446 if (honour_sticky
&& file_is_priv_sticky(path
) > 0)
3449 if (rmdir(path
) < 0 && errno
!= ENOENT
) {
3458 int rm_rf(const char *path
, bool only_dirs
, bool delete_root
, bool honour_sticky
) {
3459 return rm_rf_internal(path
, only_dirs
, delete_root
, honour_sticky
, false);
3462 int rm_rf_dangerous(const char *path
, bool only_dirs
, bool delete_root
, bool honour_sticky
) {
3463 return rm_rf_internal(path
, only_dirs
, delete_root
, honour_sticky
, true);
3466 int chmod_and_chown(const char *path
, mode_t mode
, uid_t uid
, gid_t gid
) {
3469 /* Under the assumption that we are running privileged we
3470 * first change the access mode and only then hand out
3471 * ownership to avoid a window where access is too open. */
3473 if (mode
!= (mode_t
) -1)
3474 if (chmod(path
, mode
) < 0)
3477 if (uid
!= (uid_t
) -1 || gid
!= (gid_t
) -1)
3478 if (chown(path
, uid
, gid
) < 0)
3484 int fchmod_and_fchown(int fd
, mode_t mode
, uid_t uid
, gid_t gid
) {
3487 /* Under the assumption that we are running privileged we
3488 * first change the access mode and only then hand out
3489 * ownership to avoid a window where access is too open. */
3491 if (fchmod(fd
, mode
) < 0)
3494 if (fchown(fd
, uid
, gid
) < 0)
3500 cpu_set_t
* cpu_set_malloc(unsigned *ncpus
) {
3504 /* Allocates the cpuset in the right size */
3507 if (!(r
= CPU_ALLOC(n
)))
3510 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n
), r
) >= 0) {
3511 CPU_ZERO_S(CPU_ALLOC_SIZE(n
), r
);
3521 if (errno
!= EINVAL
)
3528 void status_vprintf(const char *status
, bool ellipse
, const char *format
, va_list ap
) {
3530 static const char status_indent
[] = " "; /* "[" STATUS "] " */
3532 struct iovec iovec
[5];
3537 /* This is independent of logging, as status messages are
3538 * optional and go exclusively to the console. */
3540 if (vasprintf(&s
, format
, ap
) < 0)
3543 fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
3556 sl
= status
? strlen(status_indent
) : 0;
3562 e
= ellipsize(s
, emax
, 75);
3572 if (!isempty(status
)) {
3573 IOVEC_SET_STRING(iovec
[n
++], "[");
3574 IOVEC_SET_STRING(iovec
[n
++], status
);
3575 IOVEC_SET_STRING(iovec
[n
++], "] ");
3577 IOVEC_SET_STRING(iovec
[n
++], status_indent
);
3580 IOVEC_SET_STRING(iovec
[n
++], s
);
3581 IOVEC_SET_STRING(iovec
[n
++], "\n");
3583 writev(fd
, iovec
, n
);
3589 close_nointr_nofail(fd
);
3592 void status_printf(const char *status
, bool ellipse
, const char *format
, ...) {
3597 va_start(ap
, format
);
3598 status_vprintf(status
, ellipse
, format
, ap
);
3602 void status_welcome(void) {
3603 char *pretty_name
= NULL
, *ansi_color
= NULL
;
3604 const char *const_pretty
= NULL
, *const_color
= NULL
;
3607 if ((r
= parse_env_file("/etc/os-release", NEWLINE
,
3608 "PRETTY_NAME", &pretty_name
,
3609 "ANSI_COLOR", &ansi_color
,
3613 log_warning("Failed to read /etc/os-release: %s", strerror(-r
));
3616 if (!pretty_name
&& !const_pretty
)
3617 const_pretty
= "Linux";
3619 if (!ansi_color
&& !const_color
)
3624 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
3625 const_color
? const_color
: ansi_color
,
3626 const_pretty
? const_pretty
: pretty_name
);
3632 char *replace_env(const char *format
, char **env
) {
3639 const char *e
, *word
= format
;
3644 for (e
= format
; *e
; e
++) {
3655 if (!(k
= strnappend(r
, word
, e
-word
-1)))
3664 } else if (*e
== '$') {
3665 if (!(k
= strnappend(r
, word
, e
-word
)))
3681 if (!(t
= strv_env_get_with_length(env
, word
+2, e
-word
-2)))
3684 if (!(k
= strappend(r
, t
)))
3697 if (!(k
= strnappend(r
, word
, e
-word
)))
3708 char **replace_env_argv(char **argv
, char **env
) {
3710 unsigned k
= 0, l
= 0;
3712 l
= strv_length(argv
);
3714 if (!(r
= new(char*, l
+1)))
3717 STRV_FOREACH(i
, argv
) {
3719 /* If $FOO appears as single word, replace it by the split up variable */
3720 if ((*i
)[0] == '$' && (*i
)[1] != '{') {
3725 if ((e
= strv_env_get(env
, *i
+1))) {
3727 if (!(m
= strv_split_quoted(e
))) {
3738 if (!(w
= realloc(r
, sizeof(char*) * (l
+1)))) {
3747 memcpy(r
+ k
, m
, q
* sizeof(char*));
3755 /* If ${FOO} appears as part of a word, replace it by the variable as-is */
3756 if (!(r
[k
++] = replace_env(*i
, env
))) {
3766 int fd_columns(int fd
) {
3770 if (ioctl(fd
, TIOCGWINSZ
, &ws
) < 0)
3779 unsigned columns(void) {
3780 static __thread
int parsed_columns
= 0;
3783 if (_likely_(parsed_columns
> 0))
3784 return parsed_columns
;
3786 e
= getenv("COLUMNS");
3788 parsed_columns
= atoi(e
);
3790 if (parsed_columns
<= 0)
3791 parsed_columns
= fd_columns(STDOUT_FILENO
);
3793 if (parsed_columns
<= 0)
3794 parsed_columns
= 80;
3796 return parsed_columns
;
3799 int fd_lines(int fd
) {
3803 if (ioctl(fd
, TIOCGWINSZ
, &ws
) < 0)
3812 unsigned lines(void) {
3813 static __thread
int parsed_lines
= 0;
3816 if (_likely_(parsed_lines
> 0))
3817 return parsed_lines
;
3819 e
= getenv("LINES");
3821 parsed_lines
= atoi(e
);
3823 if (parsed_lines
<= 0)
3824 parsed_lines
= fd_lines(STDOUT_FILENO
);
3826 if (parsed_lines
<= 0)
3829 return parsed_lines
;
3832 int running_in_chroot(void) {
3838 /* Only works as root */
3840 if (stat("/proc/1/root", &a
) < 0)
3843 if (stat("/", &b
) < 0)
3847 a
.st_dev
!= b
.st_dev
||
3848 a
.st_ino
!= b
.st_ino
;
3851 char *ellipsize_mem(const char *s
, size_t old_length
, size_t new_length
, unsigned percent
) {
3856 assert(percent
<= 100);
3857 assert(new_length
>= 3);
3859 if (old_length
<= 3 || old_length
<= new_length
)
3860 return strndup(s
, old_length
);
3862 r
= new0(char, new_length
+1);
3866 x
= (new_length
* percent
) / 100;
3868 if (x
> new_length
- 3)
3876 s
+ old_length
- (new_length
- x
- 3),
3877 new_length
- x
- 3);
3882 char *ellipsize(const char *s
, size_t length
, unsigned percent
) {
3883 return ellipsize_mem(s
, strlen(s
), length
, percent
);
3886 int touch(const char *path
) {
3891 if ((fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
, 0644)) < 0)
3894 close_nointr_nofail(fd
);
3898 char *unquote(const char *s
, const char* quotes
) {
3906 if (strchr(quotes
, s
[0]) && s
[l
-1] == s
[0])
3907 return strndup(s
+1, l
-2);
3912 char *normalize_env_assignment(const char *s
) {
3913 char *name
, *value
, *p
, *r
;
3918 if (!(r
= strdup(s
)))
3924 if (!(name
= strndup(s
, p
- s
)))
3927 if (!(p
= strdup(p
+1))) {
3932 value
= unquote(strstrip(p
), QUOTES
);
3940 if (asprintf(&r
, "%s=%s", name
, value
) < 0)
3949 int wait_for_terminate(pid_t pid
, siginfo_t
*status
) {
3960 if (waitid(P_PID
, pid
, status
, WEXITED
) < 0) {
3972 int wait_for_terminate_and_warn(const char *name
, pid_t pid
) {
3979 if ((r
= wait_for_terminate(pid
, &status
)) < 0) {
3980 log_warning("Failed to wait for %s: %s", name
, strerror(-r
));
3984 if (status
.si_code
== CLD_EXITED
) {
3985 if (status
.si_status
!= 0) {
3986 log_warning("%s failed with error code %i.", name
, status
.si_status
);
3987 return status
.si_status
;
3990 log_debug("%s succeeded.", name
);
3993 } else if (status
.si_code
== CLD_KILLED
||
3994 status
.si_code
== CLD_DUMPED
) {
3996 log_warning("%s terminated by signal %s.", name
, signal_to_string(status
.si_status
));
4000 log_warning("%s failed due to unknown reason.", name
);
4005 _noreturn_
void freeze(void) {
4007 /* Make sure nobody waits for us on a socket anymore */
4008 close_all_fds(NULL
, 0);
4016 bool null_or_empty(struct stat
*st
) {
4019 if (S_ISREG(st
->st_mode
) && st
->st_size
<= 0)
4022 if (S_ISCHR(st
->st_mode
) || S_ISBLK(st
->st_mode
))
4028 int null_or_empty_path(const char *fn
) {
4033 if (stat(fn
, &st
) < 0)
4036 return null_or_empty(&st
);
4039 DIR *xopendirat(int fd
, const char *name
, int flags
) {
4043 if ((nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
)) < 0)
4046 if (!(d
= fdopendir(nfd
))) {
4047 close_nointr_nofail(nfd
);
4054 int signal_from_string_try_harder(const char *s
) {
4058 if ((signo
= signal_from_string(s
)) <= 0)
4059 if (startswith(s
, "SIG"))
4060 return signal_from_string(s
+3);
4065 void dual_timestamp_serialize(FILE *f
, const char *name
, dual_timestamp
*t
) {
4071 if (!dual_timestamp_is_set(t
))
4074 fprintf(f
, "%s=%llu %llu\n",
4076 (unsigned long long) t
->realtime
,
4077 (unsigned long long) t
->monotonic
);
4080 void dual_timestamp_deserialize(const char *value
, dual_timestamp
*t
) {
4081 unsigned long long a
, b
;
4086 if (sscanf(value
, "%lli %llu", &a
, &b
) != 2)
4087 log_debug("Failed to parse finish timestamp value %s", value
);
4094 char *fstab_node_to_udev_node(const char *p
) {
4098 /* FIXME: to follow udev's logic 100% we need to leave valid
4099 * UTF8 chars unescaped */
4101 if (startswith(p
, "LABEL=")) {
4103 if (!(u
= unquote(p
+6, "\"\'")))
4106 t
= xescape(u
, "/ ");
4112 r
= asprintf(&dn
, "/dev/disk/by-label/%s", t
);
4121 if (startswith(p
, "UUID=")) {
4123 if (!(u
= unquote(p
+5, "\"\'")))
4126 t
= xescape(u
, "/ ");
4132 r
= asprintf(&dn
, "/dev/disk/by-uuid/%s", t
);
4144 bool tty_is_vc(const char *tty
) {
4147 if (startswith(tty
, "/dev/"))
4150 return vtnr_from_tty(tty
) >= 0;
4153 bool tty_is_console(const char *tty
) {
4156 if (startswith(tty
, "/dev/"))
4159 return streq(tty
, "console");
4162 int vtnr_from_tty(const char *tty
) {
4167 if (startswith(tty
, "/dev/"))
4170 if (!startswith(tty
, "tty") )
4173 if (tty
[3] < '0' || tty
[3] > '9')
4176 r
= safe_atoi(tty
+3, &i
);
4180 if (i
< 0 || i
> 63)
4186 bool tty_is_vc_resolve(const char *tty
) {
4187 char *active
= NULL
;
4192 if (startswith(tty
, "/dev/"))
4195 /* Resolve where /dev/console is pointing to, if /sys is
4196 * actually ours (i.e. not read-only-mounted which is a sign
4197 * for container setups) */
4198 if (streq(tty
, "console") && path_is_read_only_fs("/sys") <= 0)
4199 if (read_one_line_file("/sys/class/tty/console/active", &active
) >= 0) {
4200 /* If multiple log outputs are configured the
4201 * last one is what /dev/console points to */
4202 tty
= strrchr(active
, ' ');
4215 const char *default_term_for_tty(const char *tty
) {
4218 return tty_is_vc_resolve(tty
) ? "TERM=linux" : "TERM=vt102";
4221 bool dirent_is_file(const struct dirent
*de
) {
4224 if (ignore_file(de
->d_name
))
4227 if (de
->d_type
!= DT_REG
&&
4228 de
->d_type
!= DT_LNK
&&
4229 de
->d_type
!= DT_UNKNOWN
)
4235 bool dirent_is_file_with_suffix(const struct dirent
*de
, const char *suffix
) {
4238 if (!dirent_is_file(de
))
4241 return endswith(de
->d_name
, suffix
);
4244 void execute_directory(const char *directory
, DIR *d
, char *argv
[]) {
4247 Hashmap
*pids
= NULL
;
4251 /* Executes all binaries in a directory in parallel and waits
4252 * until all they all finished. */
4255 if (!(_d
= opendir(directory
))) {
4257 if (errno
== ENOENT
)
4260 log_error("Failed to enumerate directory %s: %m", directory
);
4267 if (!(pids
= hashmap_new(trivial_hash_func
, trivial_compare_func
))) {
4268 log_error("Failed to allocate set.");
4272 while ((de
= readdir(d
))) {
4277 if (!dirent_is_file(de
))
4280 if (asprintf(&path
, "%s/%s", directory
, de
->d_name
) < 0) {
4281 log_error("Out of memory.");
4285 if ((pid
= fork()) < 0) {
4286 log_error("Failed to fork: %m");
4304 log_error("Failed to execute %s: %m", path
);
4305 _exit(EXIT_FAILURE
);
4308 log_debug("Spawned %s as %lu", path
, (unsigned long) pid
);
4310 if ((k
= hashmap_put(pids
, UINT_TO_PTR(pid
), path
)) < 0) {
4311 log_error("Failed to add PID to set: %s", strerror(-k
));
4316 while (!hashmap_isempty(pids
)) {
4317 pid_t pid
= PTR_TO_UINT(hashmap_first_key(pids
));
4322 if (waitid(P_PID
, pid
, &si
, WEXITED
) < 0) {
4327 log_error("waitid() failed: %m");
4331 if ((path
= hashmap_remove(pids
, UINT_TO_PTR(si
.si_pid
)))) {
4332 if (!is_clean_exit(si
.si_code
, si
.si_status
)) {
4333 if (si
.si_code
== CLD_EXITED
)
4334 log_error("%s exited with exit status %i.", path
, si
.si_status
);
4336 log_error("%s terminated by signal %s.", path
, signal_to_string(si
.si_status
));
4338 log_debug("%s exited successfully.", path
);
4349 hashmap_free_free(pids
);
4352 int kill_and_sigcont(pid_t pid
, int sig
) {
4355 r
= kill(pid
, sig
) < 0 ? -errno
: 0;
4363 bool nulstr_contains(const char*nulstr
, const char *needle
) {
4369 NULSTR_FOREACH(i
, nulstr
)
4370 if (streq(i
, needle
))
4376 bool plymouth_running(void) {
4377 return access("/run/plymouth/pid", F_OK
) >= 0;
4380 void parse_syslog_priority(char **p
, int *priority
) {
4381 int a
= 0, b
= 0, c
= 0;
4391 if (!strchr(*p
, '>'))
4394 if ((*p
)[2] == '>') {
4395 c
= undecchar((*p
)[1]);
4397 } else if ((*p
)[3] == '>') {
4398 b
= undecchar((*p
)[1]);
4399 c
= undecchar((*p
)[2]);
4401 } else if ((*p
)[4] == '>') {
4402 a
= undecchar((*p
)[1]);
4403 b
= undecchar((*p
)[2]);
4404 c
= undecchar((*p
)[3]);
4409 if (a
< 0 || b
< 0 || c
< 0)
4412 *priority
= a
*100+b
*10+c
;
4416 void skip_syslog_pid(char **buf
) {
4428 p
+= strspn(p
, "0123456789");
4438 void skip_syslog_date(char **buf
) {
4446 LETTER
, LETTER
, LETTER
,
4448 SPACE_OR_NUMBER
, NUMBER
,
4450 SPACE_OR_NUMBER
, NUMBER
,
4452 SPACE_OR_NUMBER
, NUMBER
,
4454 SPACE_OR_NUMBER
, NUMBER
,
4466 for (i
= 0; i
< ELEMENTSOF(sequence
); i
++, p
++) {
4471 switch (sequence
[i
]) {
4478 case SPACE_OR_NUMBER
:
4485 if (*p
< '0' || *p
> '9')
4491 if (!(*p
>= 'A' && *p
<= 'Z') &&
4492 !(*p
>= 'a' && *p
<= 'z'))
4508 char* strshorten(char *s
, size_t l
) {
4517 static bool hostname_valid_char(char c
) {
4519 (c
>= 'a' && c
<= 'z') ||
4520 (c
>= 'A' && c
<= 'Z') ||
4521 (c
>= '0' && c
<= '9') ||
4527 bool hostname_is_valid(const char *s
) {
4533 for (p
= s
; *p
; p
++)
4534 if (!hostname_valid_char(*p
))
4537 if (p
-s
> HOST_NAME_MAX
)
4543 char* hostname_cleanup(char *s
) {
4546 for (p
= s
, d
= s
; *p
; p
++)
4547 if ((*p
>= 'a' && *p
<= 'z') ||
4548 (*p
>= 'A' && *p
<= 'Z') ||
4549 (*p
>= '0' && *p
<= '9') ||
4557 strshorten(s
, HOST_NAME_MAX
);
4561 int pipe_eof(int fd
) {
4562 struct pollfd pollfd
;
4567 pollfd
.events
= POLLIN
|POLLHUP
;
4569 r
= poll(&pollfd
, 1, 0);
4576 return pollfd
.revents
& POLLHUP
;
4579 int fd_wait_for_event(int fd
, int event
, usec_t t
) {
4580 struct pollfd pollfd
;
4585 pollfd
.events
= event
;
4587 r
= poll(&pollfd
, 1, t
== (usec_t
) -1 ? -1 : (int) (t
/ USEC_PER_MSEC
));
4594 return pollfd
.revents
;
4597 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
4608 t
= new(char, strlen(path
) + 1 + 6 + 1);
4612 fn
= path_get_file_name(path
);
4616 stpcpy(stpcpy(t
+k
+1, fn
), "XXXXXX");
4618 fd
= mkostemp(t
, O_WRONLY
|O_CLOEXEC
);
4624 f
= fdopen(fd
, "we");
4637 int terminal_vhangup_fd(int fd
) {
4640 if (ioctl(fd
, TIOCVHANGUP
) < 0)
4646 int terminal_vhangup(const char *name
) {
4649 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
4653 r
= terminal_vhangup_fd(fd
);
4654 close_nointr_nofail(fd
);
4659 int vt_disallocate(const char *name
) {
4663 /* Deallocate the VT if possible. If not possible
4664 * (i.e. because it is the active one), at least clear it
4665 * entirely (including the scrollback buffer) */
4667 if (!startswith(name
, "/dev/"))
4670 if (!tty_is_vc(name
)) {
4671 /* So this is not a VT. I guess we cannot deallocate
4672 * it then. But let's at least clear the screen */
4674 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
4679 "\033[r" /* clear scrolling region */
4680 "\033[H" /* move home */
4681 "\033[2J", /* clear screen */
4683 close_nointr_nofail(fd
);
4688 if (!startswith(name
, "/dev/tty"))
4691 r
= safe_atou(name
+8, &u
);
4698 /* Try to deallocate */
4699 fd
= open_terminal("/dev/tty0", O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
4703 r
= ioctl(fd
, VT_DISALLOCATE
, u
);
4704 close_nointr_nofail(fd
);
4712 /* Couldn't deallocate, so let's clear it fully with
4714 fd
= open_terminal(name
, O_RDWR
|O_NOCTTY
|O_CLOEXEC
);
4719 "\033[r" /* clear scrolling region */
4720 "\033[H" /* move home */
4721 "\033[3J", /* clear screen including scrollback, requires Linux 2.6.40 */
4723 close_nointr_nofail(fd
);
4728 int copy_file(const char *from
, const char *to
) {
4734 fdf
= open(from
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
);
4738 fdt
= open(to
, O_WRONLY
|O_CREAT
|O_EXCL
|O_CLOEXEC
|O_NOCTTY
, 0644);
4740 close_nointr_nofail(fdf
);
4748 n
= read(fdf
, buf
, sizeof(buf
));
4752 close_nointr_nofail(fdf
);
4763 k
= loop_write(fdt
, buf
, n
, false);
4765 r
= k
< 0 ? k
: (errno
? -errno
: -EIO
);
4767 close_nointr_nofail(fdf
);
4775 close_nointr_nofail(fdf
);
4776 r
= close_nointr(fdt
);
4786 int symlink_or_copy(const char *from
, const char *to
) {
4787 char *pf
= NULL
, *pt
= NULL
;
4794 if (path_get_parent(from
, &pf
) < 0 ||
4795 path_get_parent(to
, &pt
) < 0) {
4800 if (stat(pf
, &a
) < 0 ||
4806 if (a
.st_dev
!= b
.st_dev
) {
4810 return copy_file(from
, to
);
4813 if (symlink(from
, to
) < 0) {
4827 int symlink_or_copy_atomic(const char *from
, const char *to
) {
4831 unsigned long long ull
;
4838 t
= new(char, strlen(to
) + 1 + 16 + 1);
4842 fn
= path_get_file_name(to
);
4846 x
= stpcpy(t
+k
+1, fn
);
4849 for (i
= 0; i
< 16; i
++) {
4850 *(x
++) = hexchar(ull
& 0xF);
4856 r
= symlink_or_copy(from
, t
);
4863 if (rename(t
, to
) < 0) {
4874 bool display_is_local(const char *display
) {
4878 display
[0] == ':' &&
4879 display
[1] >= '0' &&
4883 int socket_from_display(const char *display
, char **path
) {
4890 if (!display_is_local(display
))
4893 k
= strspn(display
+1, "0123456789");
4895 f
= new(char, sizeof("/tmp/.X11-unix/X") + k
);
4899 c
= stpcpy(f
, "/tmp/.X11-unix/X");
4900 memcpy(c
, display
+1, k
);
4909 const char **username
,
4910 uid_t
*uid
, gid_t
*gid
,
4912 const char **shell
) {
4920 /* We enforce some special rules for uid=0: in order to avoid
4921 * NSS lookups for root we hardcode its data. */
4923 if (streq(*username
, "root") || streq(*username
, "0")) {
4941 if (parse_uid(*username
, &u
) >= 0) {
4945 /* If there are multiple users with the same id, make
4946 * sure to leave $USER to the configured value instead
4947 * of the first occurrence in the database. However if
4948 * the uid was configured by a numeric uid, then let's
4949 * pick the real username from /etc/passwd. */
4951 *username
= p
->pw_name
;
4954 p
= getpwnam(*username
);
4958 return errno
!= 0 ? -errno
: -ESRCH
;
4970 *shell
= p
->pw_shell
;
4975 int get_group_creds(const char **groupname
, gid_t
*gid
) {
4981 /* We enforce some special rules for gid=0: in order to avoid
4982 * NSS lookups for root we hardcode its data. */
4984 if (streq(*groupname
, "root") || streq(*groupname
, "0")) {
4985 *groupname
= "root";
4993 if (parse_gid(*groupname
, &id
) >= 0) {
4998 *groupname
= g
->gr_name
;
5001 g
= getgrnam(*groupname
);
5005 return errno
!= 0 ? -errno
: -ESRCH
;
5013 int in_group(const char *name
) {
5015 int ngroups_max
, r
, i
;
5017 r
= get_group_creds(&name
, &gid
);
5021 if (getgid() == gid
)
5024 if (getegid() == gid
)
5027 ngroups_max
= sysconf(_SC_NGROUPS_MAX
);
5028 assert(ngroups_max
> 0);
5030 gids
= alloca(sizeof(gid_t
) * ngroups_max
);
5032 r
= getgroups(ngroups_max
, gids
);
5036 for (i
= 0; i
< r
; i
++)
5043 int glob_exists(const char *path
) {
5051 k
= glob(path
, GLOB_NOSORT
|GLOB_BRACE
, NULL
, &g
);
5053 if (k
== GLOB_NOMATCH
)
5055 else if (k
== GLOB_NOSPACE
)
5058 r
= !strv_isempty(g
.gl_pathv
);
5060 r
= errno
? -errno
: -EIO
;
5067 int dirent_ensure_type(DIR *d
, struct dirent
*de
) {
5073 if (de
->d_type
!= DT_UNKNOWN
)
5076 if (fstatat(dirfd(d
), de
->d_name
, &st
, AT_SYMLINK_NOFOLLOW
) < 0)
5080 S_ISREG(st
.st_mode
) ? DT_REG
:
5081 S_ISDIR(st
.st_mode
) ? DT_DIR
:
5082 S_ISLNK(st
.st_mode
) ? DT_LNK
:
5083 S_ISFIFO(st
.st_mode
) ? DT_FIFO
:
5084 S_ISSOCK(st
.st_mode
) ? DT_SOCK
:
5085 S_ISCHR(st
.st_mode
) ? DT_CHR
:
5086 S_ISBLK(st
.st_mode
) ? DT_BLK
:
5092 int in_search_path(const char *path
, char **search
) {
5096 r
= path_get_parent(path
, &parent
);
5102 STRV_FOREACH(i
, search
) {
5103 if (path_equal(parent
, *i
)) {
5114 int get_files_in_directory(const char *path
, char ***list
) {
5122 /* Returns all files in a directory in *list, and the number
5123 * of files as return value. If list is NULL returns only the
5131 struct dirent buffer
, *de
;
5134 k
= readdir_r(d
, &buffer
, &de
);
5143 dirent_ensure_type(d
, de
);
5145 if (!dirent_is_file(de
))
5149 if ((unsigned) r
>= n
) {
5153 t
= realloc(l
, sizeof(char*) * n
);
5162 assert((unsigned) r
< n
);
5164 l
[r
] = strdup(de
->d_name
);
5188 char *strjoin(const char *x
, ...) {
5201 t
= va_arg(ap
, const char *);
5224 t
= va_arg(ap
, const char *);
5238 bool is_main_thread(void) {
5239 static __thread
int cached
= 0;
5241 if (_unlikely_(cached
== 0))
5242 cached
= getpid() == gettid() ? 1 : -1;
5247 int block_get_whole_disk(dev_t d
, dev_t
*ret
) {
5254 /* If it has a queue this is good enough for us */
5255 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", major(d
), minor(d
)) < 0)
5258 r
= access(p
, F_OK
);
5266 /* If it is a partition find the originating device */
5267 if (asprintf(&p
, "/sys/dev/block/%u:%u/partition", major(d
), minor(d
)) < 0)
5270 r
= access(p
, F_OK
);
5276 /* Get parent dev_t */
5277 if (asprintf(&p
, "/sys/dev/block/%u:%u/../dev", major(d
), minor(d
)) < 0)
5280 r
= read_one_line_file(p
, &s
);
5286 r
= sscanf(s
, "%u:%u", &m
, &n
);
5292 /* Only return this if it is really good enough for us. */
5293 if (asprintf(&p
, "/sys/dev/block/%u:%u/queue", m
, n
) < 0)
5296 r
= access(p
, F_OK
);
5300 *ret
= makedev(m
, n
);
5307 int file_is_priv_sticky(const char *p
) {
5312 if (lstat(p
, &st
) < 0)
5316 (st
.st_uid
== 0 || st
.st_uid
== getuid()) &&
5317 (st
.st_mode
& S_ISVTX
);
5320 static const char *const ioprio_class_table
[] = {
5321 [IOPRIO_CLASS_NONE
] = "none",
5322 [IOPRIO_CLASS_RT
] = "realtime",
5323 [IOPRIO_CLASS_BE
] = "best-effort",
5324 [IOPRIO_CLASS_IDLE
] = "idle"
5327 DEFINE_STRING_TABLE_LOOKUP(ioprio_class
, int);
5329 static const char *const sigchld_code_table
[] = {
5330 [CLD_EXITED
] = "exited",
5331 [CLD_KILLED
] = "killed",
5332 [CLD_DUMPED
] = "dumped",
5333 [CLD_TRAPPED
] = "trapped",
5334 [CLD_STOPPED
] = "stopped",
5335 [CLD_CONTINUED
] = "continued",
5338 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
5340 static const char *const log_facility_unshifted_table
[LOG_NFACILITIES
] = {
5341 [LOG_FAC(LOG_KERN
)] = "kern",
5342 [LOG_FAC(LOG_USER
)] = "user",
5343 [LOG_FAC(LOG_MAIL
)] = "mail",
5344 [LOG_FAC(LOG_DAEMON
)] = "daemon",
5345 [LOG_FAC(LOG_AUTH
)] = "auth",
5346 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
5347 [LOG_FAC(LOG_LPR
)] = "lpr",
5348 [LOG_FAC(LOG_NEWS
)] = "news",
5349 [LOG_FAC(LOG_UUCP
)] = "uucp",
5350 [LOG_FAC(LOG_CRON
)] = "cron",
5351 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
5352 [LOG_FAC(LOG_FTP
)] = "ftp",
5353 [LOG_FAC(LOG_LOCAL0
)] = "local0",
5354 [LOG_FAC(LOG_LOCAL1
)] = "local1",
5355 [LOG_FAC(LOG_LOCAL2
)] = "local2",
5356 [LOG_FAC(LOG_LOCAL3
)] = "local3",
5357 [LOG_FAC(LOG_LOCAL4
)] = "local4",
5358 [LOG_FAC(LOG_LOCAL5
)] = "local5",
5359 [LOG_FAC(LOG_LOCAL6
)] = "local6",
5360 [LOG_FAC(LOG_LOCAL7
)] = "local7"
5363 DEFINE_STRING_TABLE_LOOKUP(log_facility_unshifted
, int);
5365 static const char *const log_level_table
[] = {
5366 [LOG_EMERG
] = "emerg",
5367 [LOG_ALERT
] = "alert",
5368 [LOG_CRIT
] = "crit",
5370 [LOG_WARNING
] = "warning",
5371 [LOG_NOTICE
] = "notice",
5372 [LOG_INFO
] = "info",
5373 [LOG_DEBUG
] = "debug"
5376 DEFINE_STRING_TABLE_LOOKUP(log_level
, int);
5378 static const char* const sched_policy_table
[] = {
5379 [SCHED_OTHER
] = "other",
5380 [SCHED_BATCH
] = "batch",
5381 [SCHED_IDLE
] = "idle",
5382 [SCHED_FIFO
] = "fifo",
5386 DEFINE_STRING_TABLE_LOOKUP(sched_policy
, int);
5388 static const char* const rlimit_table
[] = {
5389 [RLIMIT_CPU
] = "LimitCPU",
5390 [RLIMIT_FSIZE
] = "LimitFSIZE",
5391 [RLIMIT_DATA
] = "LimitDATA",
5392 [RLIMIT_STACK
] = "LimitSTACK",
5393 [RLIMIT_CORE
] = "LimitCORE",
5394 [RLIMIT_RSS
] = "LimitRSS",
5395 [RLIMIT_NOFILE
] = "LimitNOFILE",
5396 [RLIMIT_AS
] = "LimitAS",
5397 [RLIMIT_NPROC
] = "LimitNPROC",
5398 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
5399 [RLIMIT_LOCKS
] = "LimitLOCKS",
5400 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
5401 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
5402 [RLIMIT_NICE
] = "LimitNICE",
5403 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
5404 [RLIMIT_RTTIME
] = "LimitRTTIME"
5407 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);
5409 static const char* const ip_tos_table
[] = {
5410 [IPTOS_LOWDELAY
] = "low-delay",
5411 [IPTOS_THROUGHPUT
] = "throughput",
5412 [IPTOS_RELIABILITY
] = "reliability",
5413 [IPTOS_LOWCOST
] = "low-cost",
5416 DEFINE_STRING_TABLE_LOOKUP(ip_tos
, int);
5418 static const char *const __signal_table
[] = {
5435 [SIGSTKFLT
] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
5446 [SIGVTALRM
] = "VTALRM",
5448 [SIGWINCH
] = "WINCH",
5454 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(__signal
, int);
5456 const char *signal_to_string(int signo
) {
5457 static __thread
char buf
[12];
5460 name
= __signal_to_string(signo
);
5464 if (signo
>= SIGRTMIN
&& signo
<= SIGRTMAX
)
5465 snprintf(buf
, sizeof(buf
) - 1, "RTMIN+%d", signo
- SIGRTMIN
);
5467 snprintf(buf
, sizeof(buf
) - 1, "%d", signo
);
5472 int signal_from_string(const char *s
) {
5477 signo
=__signal_from_string(s
);
5481 if (startswith(s
, "RTMIN+")) {
5485 if (safe_atou(s
, &u
) >= 0) {
5486 signo
= (int) u
+ offset
;
5487 if (signo
> 0 && signo
< _NSIG
)
5493 bool kexec_loaded(void) {
5494 bool loaded
= false;
5497 if (read_one_line_file("/sys/kernel/kexec_loaded", &s
) >= 0) {
5505 int strdup_or_null(const char *a
, char **b
) {
5523 int prot_from_flags(int flags
) {
5525 switch (flags
& O_ACCMODE
) {
5534 return PROT_READ
|PROT_WRITE
;
5541 char *format_bytes(char *buf
, size_t l
, off_t t
) {
5544 static const struct {
5548 { "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5549 { "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
5550 { "T", 1024ULL*1024ULL*1024ULL*1024ULL },
5551 { "G", 1024ULL*1024ULL*1024ULL },
5552 { "M", 1024ULL*1024ULL },
5556 for (i
= 0; i
< ELEMENTSOF(table
); i
++) {
5558 if (t
>= table
[i
].factor
) {
5561 (unsigned long long) (t
/ table
[i
].factor
),
5562 (unsigned long long) (((t
*10ULL) / table
[i
].factor
) % 10ULL),
5569 snprintf(buf
, l
, "%lluB", (unsigned long long) t
);
5577 void* memdup(const void *p
, size_t l
) {
5590 int fd_inc_sndbuf(int fd
, size_t n
) {
5592 socklen_t l
= sizeof(value
);
5594 r
= getsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, &l
);
5596 l
== sizeof(value
) &&
5597 (size_t) value
>= n
*2)
5601 r
= setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
));
5608 int fd_inc_rcvbuf(int fd
, size_t n
) {
5610 socklen_t l
= sizeof(value
);
5612 r
= getsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, &l
);
5614 l
== sizeof(value
) &&
5615 (size_t) value
>= n
*2)
5619 r
= setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
));
5626 int fork_agent(pid_t
*pid
, const int except
[], unsigned n_except
, const char *path
, ...) {
5627 pid_t parent_pid
, agent_pid
;
5629 bool stdout_is_tty
, stderr_is_tty
;
5637 parent_pid
= getpid();
5639 /* Spawns a temporary TTY agent, making sure it goes away when
5646 if (agent_pid
!= 0) {
5653 * Make sure the agent goes away when the parent dies */
5654 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
5655 _exit(EXIT_FAILURE
);
5657 /* Check whether our parent died before we were able
5658 * to set the death signal */
5659 if (getppid() != parent_pid
)
5660 _exit(EXIT_SUCCESS
);
5662 /* Don't leak fds to the agent */
5663 close_all_fds(except
, n_except
);
5665 stdout_is_tty
= isatty(STDOUT_FILENO
);
5666 stderr_is_tty
= isatty(STDERR_FILENO
);
5668 if (!stdout_is_tty
|| !stderr_is_tty
) {
5669 /* Detach from stdout/stderr. and reopen
5670 * /dev/tty for them. This is important to
5671 * ensure that when systemctl is started via
5672 * popen() or a similar call that expects to
5673 * read EOF we actually do generate EOF and
5674 * not delay this indefinitely by because we
5675 * keep an unused copy of stdin around. */
5676 fd
= open("/dev/tty", O_WRONLY
);
5678 log_error("Failed to open /dev/tty: %m");
5679 _exit(EXIT_FAILURE
);
5683 dup2(fd
, STDOUT_FILENO
);
5686 dup2(fd
, STDERR_FILENO
);
5692 /* Count arguments */
5694 for (n
= 0; va_arg(ap
, char*); n
++)
5699 l
= alloca(sizeof(char *) * (n
+ 1));
5701 /* Fill in arguments */
5703 for (i
= 0; i
<= n
; i
++)
5704 l
[i
] = va_arg(ap
, char*);
5708 _exit(EXIT_FAILURE
);
5711 int setrlimit_closest(int resource
, const struct rlimit
*rlim
) {
5712 struct rlimit highest
, fixed
;
5716 if (setrlimit(resource
, rlim
) >= 0)
5722 /* So we failed to set the desired setrlimit, then let's try
5723 * to get as close as we can */
5724 assert_se(getrlimit(resource
, &highest
) == 0);
5726 fixed
.rlim_cur
= MIN(rlim
->rlim_cur
, highest
.rlim_max
);
5727 fixed
.rlim_max
= MIN(rlim
->rlim_max
, highest
.rlim_max
);
5729 if (setrlimit(resource
, &fixed
) < 0)
5735 int getenv_for_pid(pid_t pid
, const char *field
, char **_value
) {
5736 char path
[sizeof("/proc/")-1+10+sizeof("/environ")], *value
= NULL
;
5748 snprintf(path
, sizeof(path
), "/proc/%lu/environ", (unsigned long) pid
);
5751 f
= fopen(path
, "re");
5759 char line
[LINE_MAX
];
5762 for (i
= 0; i
< sizeof(line
)-1; i
++) {
5766 if (_unlikely_(c
== EOF
)) {
5776 if (memcmp(line
, field
, l
) == 0 && line
[l
] == '=') {
5777 value
= strdup(line
+ l
+ 1);
5797 int can_sleep(const char *type
) {
5798 char *p
, *w
, *state
;
5805 r
= read_one_line_file("/sys/power/state", &p
);
5807 return r
== -ENOENT
? 0 : r
;
5811 FOREACH_WORD_SEPARATOR(w
, l
, p
, WHITESPACE
, state
) {
5812 if (l
== k
&& strncmp(w
, type
, l
) == 0) {
5822 bool is_valid_documentation_url(const char *url
) {
5825 if (startswith(url
, "http://") && url
[7])
5828 if (startswith(url
, "https://") && url
[8])
5831 if (startswith(url
, "file:") && url
[5])
5834 if (startswith(url
, "info:") && url
[5])
5837 if (startswith(url
, "man:") && url
[4])
5843 bool in_initrd(void) {
5844 static int saved
= -1;
5850 /* We make two checks here:
5852 * 1. the flag file /etc/initrd-release must exist
5853 * 2. the root file system must be a memory file system
5855 * The second check is extra paranoia, since misdetecting an
5856 * initrd can have bad bad consequences due the initrd
5857 * emptying when transititioning to the main systemd.
5860 saved
= access("/etc/initrd-release", F_OK
) >= 0 &&
5861 statfs("/", &s
) >= 0 &&
5862 (s
.f_type
== TMPFS_MAGIC
|| s
.f_type
== RAMFS_MAGIC
);
5867 void warn_melody(void) {
5870 fd
= open("/dev/console", O_WRONLY
|O_CLOEXEC
|O_NOCTTY
);
5874 /* Yeah, this is synchronous. Kinda sucks. Bute well... */
5876 ioctl(fd
, KIOCSOUND
, (int)(1193180/440));
5877 usleep(125*USEC_PER_MSEC
);
5879 ioctl(fd
, KIOCSOUND
, (int)(1193180/220));
5880 usleep(125*USEC_PER_MSEC
);
5882 ioctl(fd
, KIOCSOUND
, (int)(1193180/220));
5883 usleep(125*USEC_PER_MSEC
);
5885 ioctl(fd
, KIOCSOUND
, 0);
5886 close_nointr_nofail(fd
);
5889 int make_console_stdio(void) {
5892 /* Make /dev/console the controlling terminal and stdin/stdout/stderr */
5894 fd
= acquire_terminal("/dev/console", false, true, true, (usec_t
) -1);
5896 log_error("Failed to acquire terminal: %s", strerror(-fd
));
5902 log_error("Failed to duplicate terminal fd: %s", strerror(-r
));
5909 int get_home_dir(char **_h
) {
5917 /* Take the user specified one */
5928 /* Hardcode home directory for root to avoid NSS */
5931 h
= strdup("/root");
5939 /* Check the database... */
5943 return errno
? -errno
: -ENOENT
;
5945 if (!path_is_absolute(p
->pw_dir
))
5948 h
= strdup(p
->pw_dir
);
5956 int get_shell(char **_sh
) {
5964 /* Take the user specified one */
5965 e
= getenv("SHELL");
5975 /* Hardcode home directory for root to avoid NSS */
5978 sh
= strdup("/bin/sh");
5986 /* Check the database... */
5990 return errno
? -errno
: -ESRCH
;
5992 if (!path_is_absolute(p
->pw_shell
))
5995 sh
= strdup(p
->pw_shell
);