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>
45 usec_t now(clockid_t clock_id) {
48 assert_se(clock_gettime(clock_id, &ts) == 0);
50 return timespec_load(&ts);
53 usec_t timespec_load(const struct timespec *ts) {
57 (usec_t) ts->tv_sec * USEC_PER_SEC +
58 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
61 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
64 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
65 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
70 usec_t timeval_load(const struct timeval *tv) {
74 (usec_t) tv->tv_sec * USEC_PER_SEC +
78 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
81 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
82 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
87 bool endswith(const char *s, const char *postfix) {
99 return memcmp(s + sl - pl, postfix, pl) == 0;
102 bool startswith(const char *s, const char *prefix) {
114 return memcmp(s, prefix, pl) == 0;
117 bool first_word(const char *s, const char *word) {
129 if (memcmp(s, word, wl) != 0)
132 return (s[wl] == 0 ||
133 strchr(WHITESPACE, s[wl]));
136 int close_nointr(int fd) {
142 if ((r = close(fd)) >= 0)
150 void close_nointr_nofail(int fd) {
152 /* like close_nointr() but cannot fail, and guarantees errno
155 assert_se(close_nointr(fd) == 0);
158 int parse_boolean(const char *v) {
161 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
163 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
169 int safe_atou(const char *s, unsigned *ret_u) {
177 l = strtoul(s, &x, 0);
179 if (!x || *x || errno)
180 return errno ? -errno : -EINVAL;
182 if ((unsigned long) (unsigned) l != l)
185 *ret_u = (unsigned) l;
189 int safe_atoi(const char *s, int *ret_i) {
197 l = strtol(s, &x, 0);
199 if (!x || *x || errno)
200 return errno ? -errno : -EINVAL;
202 if ((long) (int) l != l)
209 int safe_atolu(const char *s, long unsigned *ret_lu) {
217 l = strtoul(s, &x, 0);
219 if (!x || *x || errno)
220 return errno ? -errno : -EINVAL;
226 int safe_atoli(const char *s, long int *ret_li) {
234 l = strtol(s, &x, 0);
236 if (!x || *x || errno)
237 return errno ? -errno : -EINVAL;
243 int safe_atollu(const char *s, long long unsigned *ret_llu) {
245 unsigned long long l;
251 l = strtoull(s, &x, 0);
253 if (!x || *x || errno)
254 return errno ? -errno : -EINVAL;
260 int safe_atolli(const char *s, long long int *ret_lli) {
268 l = strtoll(s, &x, 0);
270 if (!x || *x || errno)
271 return errno ? -errno : -EINVAL;
277 /* Split a string into words. */
278 char *split(const char *c, size_t *l, const char *separator, char **state) {
281 current = *state ? *state : (char*) c;
283 if (!*current || *c == 0)
286 current += strspn(current, separator);
287 *l = strcspn(current, separator);
290 return (char*) current;
293 /* Split a string into words, but consider strings enclosed in '' and
294 * "" as words even if they include spaces. */
295 char *split_quoted(const char *c, size_t *l, char **state) {
298 current = *state ? *state : (char*) c;
300 if (!*current || *c == 0)
303 current += strspn(current, WHITESPACE);
305 if (*current == '\'') {
307 *l = strcspn(current, "'");
312 } else if (*current == '\"') {
314 *l = strcspn(current, "\"");
320 *l = strcspn(current, WHITESPACE);
324 /* FIXME: Cannot deal with strings that have spaces AND ticks
327 return (char*) current;
330 char **split_path_and_make_absolute(const char *p) {
334 if (!(l = strv_split(p, ":")))
337 if (!strv_path_make_absolute_cwd(l)) {
345 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
348 char fn[132], line[256], *p;
349 long long unsigned ppid;
354 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%llu/stat", (unsigned long long) pid) < (int) (sizeof(fn)-1));
355 fn[sizeof(fn)-1] = 0;
357 if (!(f = fopen(fn, "r")))
360 if (!(fgets(line, sizeof(line), f))) {
368 /* Let's skip the pid and comm fields. The latter is enclosed
369 * in () but does not escape any () in its value, so let's
370 * skip over it manually */
372 if (!(p = strrchr(line, ')')))
383 if ((long long unsigned) (pid_t) ppid != ppid)
386 *_ppid = (pid_t) ppid;
391 int write_one_line_file(const char *fn, const char *line) {
398 if (!(f = fopen(fn, "we")))
401 if (fputs(line, f) < 0) {
412 int read_one_line_file(const char *fn, char **line) {
420 if (!(f = fopen(fn, "re")))
423 if (!(fgets(t, sizeof(t), f))) {
428 if (!(c = strdup(t))) {
441 char *truncate_nl(char *s) {
444 s[strcspn(s, NEWLINE)] = 0;
448 int get_process_name(pid_t pid, char **name) {
455 if (asprintf(&p, "/proc/%llu/comm", (unsigned long long) pid) < 0)
458 r = read_one_line_file(p, name);
468 char *strappend(const char *s, const char *suffix) {
478 if (!(r = new(char, a+b+1)))
482 memcpy(r+a, suffix, b);
488 int readlink_malloc(const char *p, char **r) {
498 if (!(c = new(char, l)))
501 if ((n = readlink(p, c, l-1)) < 0) {
507 if ((size_t) n < l-1) {
518 char *file_name_from_path(const char *p) {
523 if ((r = strrchr(p, '/')))
529 bool path_is_absolute(const char *p) {
535 bool is_path(const char *p) {
537 return !!strchr(p, '/');
540 char *path_make_absolute(const char *p, const char *prefix) {
545 /* Makes every item in the list an absolute path by prepending
546 * the prefix, if specified and necessary */
548 if (path_is_absolute(p) || !prefix)
551 if (asprintf(&r, "%s/%s", prefix, p) < 0)
557 char *path_make_absolute_cwd(const char *p) {
562 /* Similar to path_make_absolute(), but prefixes with the
563 * current working directory. */
565 if (path_is_absolute(p))
568 if (!(cwd = get_current_dir_name()))
571 r = path_make_absolute(p, cwd);
577 char **strv_path_make_absolute_cwd(char **l) {
580 /* Goes through every item in the string list and makes it
581 * absolute. This works in place and won't rollback any
582 * changes on failure. */
587 if (!(t = path_make_absolute_cwd(*s)))
597 int reset_all_signal_handlers(void) {
600 for (sig = 1; sig < _NSIG; sig++) {
603 if (sig == SIGKILL || sig == SIGSTOP)
607 sa.sa_handler = SIG_DFL;
608 sa.sa_flags = SA_RESTART;
610 /* On Linux the first two RT signals are reserved by
611 * glibc, and sigaction() will return EINVAL for them. */
612 if ((sigaction(sig, &sa, NULL) < 0))
620 char *strstrip(char *s) {
623 /* Drops trailing whitespace. Modifies the string in
624 * place. Returns pointer to first non-space character */
626 s += strspn(s, WHITESPACE);
629 if (!strchr(WHITESPACE, *e))
641 char *delete_chars(char *s, const char *bad) {
644 /* Drops all whitespace, regardless where in the string */
646 for (f = s, t = s; *f; f++) {
658 char *file_in_same_dir(const char *path, const char *filename) {
665 /* This removes the last component of path and appends
666 * filename, unless the latter is absolute anyway or the
669 if (path_is_absolute(filename))
670 return strdup(filename);
672 if (!(e = strrchr(path, '/')))
673 return strdup(filename);
675 k = strlen(filename);
676 if (!(r = new(char, e-path+1+k+1)))
679 memcpy(r, path, e-path+1);
680 memcpy(r+(e-path)+1, filename, k+1);
685 int mkdir_parents(const char *path, mode_t mode) {
690 /* Creates every parent directory in the path except the last
693 p = path + strspn(path, "/");
698 e = p + strcspn(p, "/");
699 p = e + strspn(e, "/");
701 /* Is this the last component? If so, then we're
706 if (!(t = strndup(path, e - path)))
713 if (r < 0 && errno != EEXIST)
718 char hexchar(int x) {
719 static const char table[16] = "0123456789abcdef";
721 return table[x & 15];
724 int unhexchar(char c) {
726 if (c >= '0' && c <= '9')
729 if (c >= 'a' && c <= 'f')
732 if (c >= 'A' && c <= 'F')
738 char octchar(int x) {
739 return '0' + (x & 7);
742 int unoctchar(char c) {
744 if (c >= '0' && c <= '7')
750 char decchar(int x) {
751 return '0' + (x % 10);
754 int undecchar(char c) {
756 if (c >= '0' && c <= '9')
762 char *cescape(const char *s) {
768 /* Does C style string escaping. */
770 if (!(r = new(char, strlen(s)*4 + 1)))
773 for (f = s, t = r; *f; f++)
819 /* For special chars we prefer octal over
820 * hexadecimal encoding, simply because glib's
821 * g_strescape() does the same */
822 if ((*f < ' ') || (*f >= 127)) {
824 *(t++) = octchar((unsigned char) *f >> 6);
825 *(t++) = octchar((unsigned char) *f >> 3);
826 *(t++) = octchar((unsigned char) *f);
837 char *cunescape(const char *s) {
843 /* Undoes C style string escaping */
845 if (!(r = new(char, strlen(s)+1)))
848 for (f = s, t = r; *f; f++) {
891 /* hexadecimal encoding */
894 if ((a = unhexchar(f[1])) < 0 ||
895 (b = unhexchar(f[2])) < 0) {
896 /* Invalid escape code, let's take it literal then */
900 *(t++) = (char) ((a << 4) | b);
918 if ((a = unoctchar(f[0])) < 0 ||
919 (b = unoctchar(f[1])) < 0 ||
920 (c = unoctchar(f[2])) < 0) {
921 /* Invalid escape code, let's take it literal then */
925 *(t++) = (char) ((a << 6) | (b << 3) | c);
933 /* premature end of string.*/
938 /* Invalid escape code, let's take it literal then */
951 char *xescape(const char *s, const char *bad) {
955 /* Escapes all chars in bad, in addition to \ and all special
956 * chars, in \xFF style escaping. May be reversed with
959 if (!(r = new(char, strlen(s)*4+1)))
962 for (f = s, t = r; *f; f++) {
964 if ((*f < ' ') || (*f >= 127) ||
965 (*f == '\\') || strchr(bad, *f)) {
968 *(t++) = hexchar(*f >> 4);
969 *(t++) = hexchar(*f);
979 char *bus_path_escape(const char *s) {
985 /* Escapes all chars that D-Bus' object path cannot deal
986 * with. Can be reverse with bus_path_unescape() */
988 if (!(r = new(char, strlen(s)*3+1)))
991 for (f = s, t = r; *f; f++) {
993 if (!(*f >= 'A' && *f <= 'Z') &&
994 !(*f >= 'a' && *f <= 'z') &&
995 !(*f >= '0' && *f <= '9')) {
997 *(t++) = hexchar(*f >> 4);
998 *(t++) = hexchar(*f);
1008 char *bus_path_unescape(const char *s) {
1014 if (!(r = new(char, strlen(s)+1)))
1017 for (f = s, t = r; *f; f++) {
1022 if ((a = unhexchar(f[1])) < 0 ||
1023 (b = unhexchar(f[2])) < 0) {
1024 /* Invalid escape code, let's take it literal then */
1027 *(t++) = (char) ((a << 4) | b);
1039 char *path_kill_slashes(char *path) {
1043 /* Removes redundant inner and trailing slashes. Modifies the
1044 * passed string in-place.
1046 * ///foo///bar/ becomes /foo/bar
1049 for (f = path, t = path; *f; f++) {
1064 /* Special rule, if we are talking of the root directory, a
1065 trailing slash is good */
1067 if (t == path && slash)
1074 bool path_startswith(const char *path, const char *prefix) {
1078 if ((path[0] == '/') != (prefix[0] == '/'))
1084 path += strspn(path, "/");
1085 prefix += strspn(prefix, "/");
1093 a = strcspn(path, "/");
1094 b = strcspn(prefix, "/");
1099 if (memcmp(path, prefix, a) != 0)
1107 char *ascii_strlower(char *t) {
1112 for (p = t; *p; p++)
1113 if (*p >= 'A' && *p <= 'Z')
1114 *p = *p - 'A' + 'a';
1119 bool ignore_file(const char *filename) {
1123 filename[0] == '.' ||
1124 endswith(filename, "~") ||
1125 endswith(filename, ".rpmnew") ||
1126 endswith(filename, ".rpmsave") ||
1127 endswith(filename, ".rpmorig") ||
1128 endswith(filename, ".dpkg-old") ||
1129 endswith(filename, ".dpkg-new") ||
1130 endswith(filename, ".swp");
1133 int fd_nonblock(int fd, bool nonblock) {
1138 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1142 flags |= O_NONBLOCK;
1144 flags &= ~O_NONBLOCK;
1146 if (fcntl(fd, F_SETFL, flags) < 0)
1152 int fd_cloexec(int fd, bool cloexec) {
1157 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1161 flags |= FD_CLOEXEC;
1163 flags &= ~FD_CLOEXEC;
1165 if (fcntl(fd, F_SETFD, flags) < 0)
1171 int close_all_fds(const int except[], unsigned n_except) {
1176 if (!(d = opendir("/proc/self/fd")))
1179 while ((de = readdir(d))) {
1182 if (de->d_name[0] == '.')
1185 if ((r = safe_atoi(de->d_name, &fd)) < 0)
1199 for (i = 0; i < n_except; i++)
1200 if (except[i] == fd) {
1209 if ((r = close_nointr(fd)) < 0) {
1210 /* Valgrind has its own FD and doesn't want to have it closed */
1223 bool chars_intersect(const char *a, const char *b) {
1226 /* Returns true if any of the chars in a are in b. */
1227 for (p = a; *p; p++)
1234 static const char *const ioprio_class_table[] = {
1235 [IOPRIO_CLASS_NONE] = "none",
1236 [IOPRIO_CLASS_RT] = "realtime",
1237 [IOPRIO_CLASS_BE] = "best-effort",
1238 [IOPRIO_CLASS_IDLE] = "idle"
1241 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
1243 static const char *const sigchld_code_table[] = {
1244 [CLD_EXITED] = "exited",
1245 [CLD_KILLED] = "killed",
1246 [CLD_DUMPED] = "dumped",
1247 [CLD_TRAPPED] = "trapped",
1248 [CLD_STOPPED] = "stopped",
1249 [CLD_CONTINUED] = "continued",
1252 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
1254 static const char *const log_facility_table[LOG_NFACILITIES] = {
1255 [LOG_FAC(LOG_KERN)] = "kern",
1256 [LOG_FAC(LOG_USER)] = "user",
1257 [LOG_FAC(LOG_MAIL)] = "mail",
1258 [LOG_FAC(LOG_DAEMON)] = "daemon",
1259 [LOG_FAC(LOG_AUTH)] = "auth",
1260 [LOG_FAC(LOG_SYSLOG)] = "syslog",
1261 [LOG_FAC(LOG_LPR)] = "lpr",
1262 [LOG_FAC(LOG_NEWS)] = "news",
1263 [LOG_FAC(LOG_UUCP)] = "uucp",
1264 [LOG_FAC(LOG_CRON)] = "cron",
1265 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
1266 [LOG_FAC(LOG_FTP)] = "ftp",
1267 [LOG_FAC(LOG_LOCAL0)] = "local0",
1268 [LOG_FAC(LOG_LOCAL1)] = "local1",
1269 [LOG_FAC(LOG_LOCAL2)] = "local2",
1270 [LOG_FAC(LOG_LOCAL3)] = "local3",
1271 [LOG_FAC(LOG_LOCAL4)] = "local4",
1272 [LOG_FAC(LOG_LOCAL5)] = "local5",
1273 [LOG_FAC(LOG_LOCAL6)] = "local6",
1274 [LOG_FAC(LOG_LOCAL7)] = "local7"
1277 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
1279 static const char *const log_level_table[] = {
1280 [LOG_EMERG] = "emerg",
1281 [LOG_ALERT] = "alert",
1282 [LOG_CRIT] = "crit",
1284 [LOG_WARNING] = "warning",
1285 [LOG_NOTICE] = "notice",
1286 [LOG_INFO] = "info",
1287 [LOG_DEBUG] = "debug"
1290 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
1292 static const char* const sched_policy_table[] = {
1293 [SCHED_OTHER] = "other",
1294 [SCHED_BATCH] = "batch",
1295 [SCHED_IDLE] = "idle",
1296 [SCHED_FIFO] = "fifo",
1300 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
1302 static const char* const rlimit_table[] = {
1303 [RLIMIT_CPU] = "LimitCPU",
1304 [RLIMIT_FSIZE] = "LimitFSIZE",
1305 [RLIMIT_DATA] = "LimitDATA",
1306 [RLIMIT_STACK] = "LimitSTACK",
1307 [RLIMIT_CORE] = "LimitCORE",
1308 [RLIMIT_RSS] = "LimitRSS",
1309 [RLIMIT_NOFILE] = "LimitNOFILE",
1310 [RLIMIT_AS] = "LimitAS",
1311 [RLIMIT_NPROC] = "LimitNPROC",
1312 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
1313 [RLIMIT_LOCKS] = "LimitLOCKS",
1314 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
1315 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
1316 [RLIMIT_NICE] = "LimitNICE",
1317 [RLIMIT_RTPRIO] = "LimitRTPRIO",
1318 [RLIMIT_RTTIME] = "LimitRTTIME"
1321 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);