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>
48 bool streq_ptr(const char *a, const char *b) {
50 /* Like streq(), but tries to make sense of NULL pointers */
61 usec_t now(clockid_t clock_id) {
64 assert_se(clock_gettime(clock_id, &ts) == 0);
66 return timespec_load(&ts);
69 usec_t timespec_load(const struct timespec *ts) {
73 (usec_t) ts->tv_sec * USEC_PER_SEC +
74 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
77 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
80 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
81 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
86 usec_t timeval_load(const struct timeval *tv) {
90 (usec_t) tv->tv_sec * USEC_PER_SEC +
94 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
97 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
98 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
103 bool endswith(const char *s, const char *postfix) {
110 pl = strlen(postfix);
115 return memcmp(s + sl - pl, postfix, pl) == 0;
118 bool startswith(const char *s, const char *prefix) {
130 return memcmp(s, prefix, pl) == 0;
133 bool first_word(const char *s, const char *word) {
145 if (memcmp(s, word, wl) != 0)
148 return (s[wl] == 0 ||
149 strchr(WHITESPACE, s[wl]));
152 int close_nointr(int fd) {
158 if ((r = close(fd)) >= 0)
166 void close_nointr_nofail(int fd) {
168 /* like close_nointr() but cannot fail, and guarantees errno
171 assert_se(close_nointr(fd) == 0);
174 int parse_boolean(const char *v) {
177 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
179 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
185 int safe_atou(const char *s, unsigned *ret_u) {
193 l = strtoul(s, &x, 0);
195 if (!x || *x || errno)
196 return errno ? -errno : -EINVAL;
198 if ((unsigned long) (unsigned) l != l)
201 *ret_u = (unsigned) l;
205 int safe_atoi(const char *s, int *ret_i) {
213 l = strtol(s, &x, 0);
215 if (!x || *x || errno)
216 return errno ? -errno : -EINVAL;
218 if ((long) (int) l != l)
225 int safe_atolu(const char *s, long unsigned *ret_lu) {
233 l = strtoul(s, &x, 0);
235 if (!x || *x || errno)
236 return errno ? -errno : -EINVAL;
242 int safe_atoli(const char *s, long int *ret_li) {
250 l = strtol(s, &x, 0);
252 if (!x || *x || errno)
253 return errno ? -errno : -EINVAL;
259 int safe_atollu(const char *s, long long unsigned *ret_llu) {
261 unsigned long long l;
267 l = strtoull(s, &x, 0);
269 if (!x || *x || errno)
270 return errno ? -errno : -EINVAL;
276 int safe_atolli(const char *s, long long int *ret_lli) {
284 l = strtoll(s, &x, 0);
286 if (!x || *x || errno)
287 return errno ? -errno : -EINVAL;
293 /* Split a string into words. */
294 char *split(const char *c, size_t *l, const char *separator, char **state) {
297 current = *state ? *state : (char*) c;
299 if (!*current || *c == 0)
302 current += strspn(current, separator);
303 *l = strcspn(current, separator);
306 return (char*) current;
309 /* Split a string into words, but consider strings enclosed in '' and
310 * "" as words even if they include spaces. */
311 char *split_quoted(const char *c, size_t *l, char **state) {
314 current = *state ? *state : (char*) c;
316 if (!*current || *c == 0)
319 current += strspn(current, WHITESPACE);
321 if (*current == '\'') {
323 *l = strcspn(current, "'");
328 } else if (*current == '\"') {
330 *l = strcspn(current, "\"");
336 *l = strcspn(current, WHITESPACE);
340 /* FIXME: Cannot deal with strings that have spaces AND ticks
343 return (char*) current;
346 char **split_path_and_make_absolute(const char *p) {
350 if (!(l = strv_split(p, ":")))
353 if (!strv_path_make_absolute_cwd(l)) {
361 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
364 char fn[132], line[256], *p;
365 long long unsigned ppid;
370 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%llu/stat", (unsigned long long) pid) < (int) (sizeof(fn)-1));
371 fn[sizeof(fn)-1] = 0;
373 if (!(f = fopen(fn, "r")))
376 if (!(fgets(line, sizeof(line), f))) {
384 /* Let's skip the pid and comm fields. The latter is enclosed
385 * in () but does not escape any () in its value, so let's
386 * skip over it manually */
388 if (!(p = strrchr(line, ')')))
399 if ((long long unsigned) (pid_t) ppid != ppid)
402 *_ppid = (pid_t) ppid;
407 int write_one_line_file(const char *fn, const char *line) {
414 if (!(f = fopen(fn, "we")))
417 if (fputs(line, f) < 0) {
428 int read_one_line_file(const char *fn, char **line) {
436 if (!(f = fopen(fn, "re")))
439 if (!(fgets(t, sizeof(t), f))) {
444 if (!(c = strdup(t))) {
457 char *truncate_nl(char *s) {
460 s[strcspn(s, NEWLINE)] = 0;
464 int get_process_name(pid_t pid, char **name) {
471 if (asprintf(&p, "/proc/%llu/comm", (unsigned long long) pid) < 0)
474 r = read_one_line_file(p, name);
484 char *strappend(const char *s, const char *suffix) {
494 if (!(r = new(char, a+b+1)))
498 memcpy(r+a, suffix, b);
504 int readlink_malloc(const char *p, char **r) {
514 if (!(c = new(char, l)))
517 if ((n = readlink(p, c, l-1)) < 0) {
523 if ((size_t) n < l-1) {
534 char *file_name_from_path(const char *p) {
539 if ((r = strrchr(p, '/')))
545 bool path_is_absolute(const char *p) {
551 bool is_path(const char *p) {
553 return !!strchr(p, '/');
556 char *path_make_absolute(const char *p, const char *prefix) {
561 /* Makes every item in the list an absolute path by prepending
562 * the prefix, if specified and necessary */
564 if (path_is_absolute(p) || !prefix)
567 if (asprintf(&r, "%s/%s", prefix, p) < 0)
573 char *path_make_absolute_cwd(const char *p) {
578 /* Similar to path_make_absolute(), but prefixes with the
579 * current working directory. */
581 if (path_is_absolute(p))
584 if (!(cwd = get_current_dir_name()))
587 r = path_make_absolute(p, cwd);
593 char **strv_path_make_absolute_cwd(char **l) {
596 /* Goes through every item in the string list and makes it
597 * absolute. This works in place and won't rollback any
598 * changes on failure. */
603 if (!(t = path_make_absolute_cwd(*s)))
613 int reset_all_signal_handlers(void) {
616 for (sig = 1; sig < _NSIG; sig++) {
619 if (sig == SIGKILL || sig == SIGSTOP)
623 sa.sa_handler = SIG_DFL;
624 sa.sa_flags = SA_RESTART;
626 /* On Linux the first two RT signals are reserved by
627 * glibc, and sigaction() will return EINVAL for them. */
628 if ((sigaction(sig, &sa, NULL) < 0))
636 char *strstrip(char *s) {
639 /* Drops trailing whitespace. Modifies the string in
640 * place. Returns pointer to first non-space character */
642 s += strspn(s, WHITESPACE);
645 if (!strchr(WHITESPACE, *e))
657 char *delete_chars(char *s, const char *bad) {
660 /* Drops all whitespace, regardless where in the string */
662 for (f = s, t = s; *f; f++) {
674 char *file_in_same_dir(const char *path, const char *filename) {
681 /* This removes the last component of path and appends
682 * filename, unless the latter is absolute anyway or the
685 if (path_is_absolute(filename))
686 return strdup(filename);
688 if (!(e = strrchr(path, '/')))
689 return strdup(filename);
691 k = strlen(filename);
692 if (!(r = new(char, e-path+1+k+1)))
695 memcpy(r, path, e-path+1);
696 memcpy(r+(e-path)+1, filename, k+1);
701 int mkdir_parents(const char *path, mode_t mode) {
706 /* Creates every parent directory in the path except the last
709 p = path + strspn(path, "/");
714 e = p + strcspn(p, "/");
715 p = e + strspn(e, "/");
717 /* Is this the last component? If so, then we're
722 if (!(t = strndup(path, e - path)))
729 if (r < 0 && errno != EEXIST)
734 int mkdir_p(const char *path, mode_t mode) {
739 if ((r = mkdir_parents(path, mode)) < 0)
742 if (mkdir(path, mode) < 0)
748 char hexchar(int x) {
749 static const char table[16] = "0123456789abcdef";
751 return table[x & 15];
754 int unhexchar(char c) {
756 if (c >= '0' && c <= '9')
759 if (c >= 'a' && c <= 'f')
762 if (c >= 'A' && c <= 'F')
768 char octchar(int x) {
769 return '0' + (x & 7);
772 int unoctchar(char c) {
774 if (c >= '0' && c <= '7')
780 char decchar(int x) {
781 return '0' + (x % 10);
784 int undecchar(char c) {
786 if (c >= '0' && c <= '9')
792 char *cescape(const char *s) {
798 /* Does C style string escaping. */
800 if (!(r = new(char, strlen(s)*4 + 1)))
803 for (f = s, t = r; *f; f++)
849 /* For special chars we prefer octal over
850 * hexadecimal encoding, simply because glib's
851 * g_strescape() does the same */
852 if ((*f < ' ') || (*f >= 127)) {
854 *(t++) = octchar((unsigned char) *f >> 6);
855 *(t++) = octchar((unsigned char) *f >> 3);
856 *(t++) = octchar((unsigned char) *f);
867 char *cunescape(const char *s) {
873 /* Undoes C style string escaping */
875 if (!(r = new(char, strlen(s)+1)))
878 for (f = s, t = r; *f; f++) {
921 /* hexadecimal encoding */
924 if ((a = unhexchar(f[1])) < 0 ||
925 (b = unhexchar(f[2])) < 0) {
926 /* Invalid escape code, let's take it literal then */
930 *(t++) = (char) ((a << 4) | b);
948 if ((a = unoctchar(f[0])) < 0 ||
949 (b = unoctchar(f[1])) < 0 ||
950 (c = unoctchar(f[2])) < 0) {
951 /* Invalid escape code, let's take it literal then */
955 *(t++) = (char) ((a << 6) | (b << 3) | c);
963 /* premature end of string.*/
968 /* Invalid escape code, let's take it literal then */
981 char *xescape(const char *s, const char *bad) {
985 /* Escapes all chars in bad, in addition to \ and all special
986 * chars, in \xFF style escaping. May be reversed with
989 if (!(r = new(char, strlen(s)*4+1)))
992 for (f = s, t = r; *f; f++) {
994 if ((*f < ' ') || (*f >= 127) ||
995 (*f == '\\') || strchr(bad, *f)) {
998 *(t++) = hexchar(*f >> 4);
999 *(t++) = hexchar(*f);
1009 char *bus_path_escape(const char *s) {
1015 /* Escapes all chars that D-Bus' object path cannot deal
1016 * with. Can be reverse with bus_path_unescape() */
1018 if (!(r = new(char, strlen(s)*3+1)))
1021 for (f = s, t = r; *f; f++) {
1023 if (!(*f >= 'A' && *f <= 'Z') &&
1024 !(*f >= 'a' && *f <= 'z') &&
1025 !(*f >= '0' && *f <= '9')) {
1027 *(t++) = hexchar(*f >> 4);
1028 *(t++) = hexchar(*f);
1038 char *bus_path_unescape(const char *s) {
1044 if (!(r = new(char, strlen(s)+1)))
1047 for (f = s, t = r; *f; f++) {
1052 if ((a = unhexchar(f[1])) < 0 ||
1053 (b = unhexchar(f[2])) < 0) {
1054 /* Invalid escape code, let's take it literal then */
1057 *(t++) = (char) ((a << 4) | b);
1069 char *path_kill_slashes(char *path) {
1073 /* Removes redundant inner and trailing slashes. Modifies the
1074 * passed string in-place.
1076 * ///foo///bar/ becomes /foo/bar
1079 for (f = path, t = path; *f; f++) {
1094 /* Special rule, if we are talking of the root directory, a
1095 trailing slash is good */
1097 if (t == path && slash)
1104 bool path_startswith(const char *path, const char *prefix) {
1108 if ((path[0] == '/') != (prefix[0] == '/'))
1114 path += strspn(path, "/");
1115 prefix += strspn(prefix, "/");
1123 a = strcspn(path, "/");
1124 b = strcspn(prefix, "/");
1129 if (memcmp(path, prefix, a) != 0)
1137 char *ascii_strlower(char *t) {
1142 for (p = t; *p; p++)
1143 if (*p >= 'A' && *p <= 'Z')
1144 *p = *p - 'A' + 'a';
1149 bool ignore_file(const char *filename) {
1153 filename[0] == '.' ||
1154 endswith(filename, "~") ||
1155 endswith(filename, ".rpmnew") ||
1156 endswith(filename, ".rpmsave") ||
1157 endswith(filename, ".rpmorig") ||
1158 endswith(filename, ".dpkg-old") ||
1159 endswith(filename, ".dpkg-new") ||
1160 endswith(filename, ".swp");
1163 int fd_nonblock(int fd, bool nonblock) {
1168 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1172 flags |= O_NONBLOCK;
1174 flags &= ~O_NONBLOCK;
1176 if (fcntl(fd, F_SETFL, flags) < 0)
1182 int fd_cloexec(int fd, bool cloexec) {
1187 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1191 flags |= FD_CLOEXEC;
1193 flags &= ~FD_CLOEXEC;
1195 if (fcntl(fd, F_SETFD, flags) < 0)
1201 int close_all_fds(const int except[], unsigned n_except) {
1206 if (!(d = opendir("/proc/self/fd")))
1209 while ((de = readdir(d))) {
1212 if (de->d_name[0] == '.')
1215 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1229 for (i = 0; i < n_except; i++)
1230 if (except[i] == fd) {
1239 if ((r = close_nointr(fd)) < 0) {
1240 /* Valgrind has its own FD and doesn't want to have it closed */
1253 bool chars_intersect(const char *a, const char *b) {
1256 /* Returns true if any of the chars in a are in b. */
1257 for (p = a; *p; p++)
1264 char *format_timestamp(char *buf, size_t l, usec_t t) {
1274 sec = (time_t) t / USEC_PER_SEC;
1276 if (strftime(buf, l, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec, &tm)) <= 0)
1282 bool fstype_is_network(const char *fstype) {
1283 static const char * const table[] = {
1293 for (i = 0; i < ELEMENTSOF(table); i++)
1294 if (streq(table[i], fstype))
1303 if ((fd = open("/dev/tty0", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0)
1308 TIOCL_GETKMSGREDIRECT,
1312 if (ioctl(fd, TIOCLINUX, tiocl) < 0)
1315 vt = tiocl[0] <= 0 ? 1 : tiocl[0];
1318 if (ioctl(fd, VT_ACTIVATE, vt) < 0)
1325 static const char *const ioprio_class_table[] = {
1326 [IOPRIO_CLASS_NONE] = "none",
1327 [IOPRIO_CLASS_RT] = "realtime",
1328 [IOPRIO_CLASS_BE] = "best-effort",
1329 [IOPRIO_CLASS_IDLE] = "idle"
1332 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
1334 static const char *const sigchld_code_table[] = {
1335 [CLD_EXITED] = "exited",
1336 [CLD_KILLED] = "killed",
1337 [CLD_DUMPED] = "dumped",
1338 [CLD_TRAPPED] = "trapped",
1339 [CLD_STOPPED] = "stopped",
1340 [CLD_CONTINUED] = "continued",
1343 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
1345 static const char *const log_facility_table[LOG_NFACILITIES] = {
1346 [LOG_FAC(LOG_KERN)] = "kern",
1347 [LOG_FAC(LOG_USER)] = "user",
1348 [LOG_FAC(LOG_MAIL)] = "mail",
1349 [LOG_FAC(LOG_DAEMON)] = "daemon",
1350 [LOG_FAC(LOG_AUTH)] = "auth",
1351 [LOG_FAC(LOG_SYSLOG)] = "syslog",
1352 [LOG_FAC(LOG_LPR)] = "lpr",
1353 [LOG_FAC(LOG_NEWS)] = "news",
1354 [LOG_FAC(LOG_UUCP)] = "uucp",
1355 [LOG_FAC(LOG_CRON)] = "cron",
1356 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
1357 [LOG_FAC(LOG_FTP)] = "ftp",
1358 [LOG_FAC(LOG_LOCAL0)] = "local0",
1359 [LOG_FAC(LOG_LOCAL1)] = "local1",
1360 [LOG_FAC(LOG_LOCAL2)] = "local2",
1361 [LOG_FAC(LOG_LOCAL3)] = "local3",
1362 [LOG_FAC(LOG_LOCAL4)] = "local4",
1363 [LOG_FAC(LOG_LOCAL5)] = "local5",
1364 [LOG_FAC(LOG_LOCAL6)] = "local6",
1365 [LOG_FAC(LOG_LOCAL7)] = "local7"
1368 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
1370 static const char *const log_level_table[] = {
1371 [LOG_EMERG] = "emerg",
1372 [LOG_ALERT] = "alert",
1373 [LOG_CRIT] = "crit",
1375 [LOG_WARNING] = "warning",
1376 [LOG_NOTICE] = "notice",
1377 [LOG_INFO] = "info",
1378 [LOG_DEBUG] = "debug"
1381 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
1383 static const char* const sched_policy_table[] = {
1384 [SCHED_OTHER] = "other",
1385 [SCHED_BATCH] = "batch",
1386 [SCHED_IDLE] = "idle",
1387 [SCHED_FIFO] = "fifo",
1391 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
1393 static const char* const rlimit_table[] = {
1394 [RLIMIT_CPU] = "LimitCPU",
1395 [RLIMIT_FSIZE] = "LimitFSIZE",
1396 [RLIMIT_DATA] = "LimitDATA",
1397 [RLIMIT_STACK] = "LimitSTACK",
1398 [RLIMIT_CORE] = "LimitCORE",
1399 [RLIMIT_RSS] = "LimitRSS",
1400 [RLIMIT_NOFILE] = "LimitNOFILE",
1401 [RLIMIT_AS] = "LimitAS",
1402 [RLIMIT_NPROC] = "LimitNPROC",
1403 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
1404 [RLIMIT_LOCKS] = "LimitLOCKS",
1405 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
1406 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
1407 [RLIMIT_NICE] = "LimitNICE",
1408 [RLIMIT_RTPRIO] = "LimitRTPRIO",
1409 [RLIMIT_RTTIME] = "LimitRTTIME"
1412 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);