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>
44 usec_t now(clockid_t clock_id) {
47 assert_se(clock_gettime(clock_id, &ts) == 0);
49 return timespec_load(&ts);
52 usec_t timespec_load(const struct timespec *ts) {
56 (usec_t) ts->tv_sec * USEC_PER_SEC +
57 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
60 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
63 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
64 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
69 usec_t timeval_load(const struct timeval *tv) {
73 (usec_t) tv->tv_sec * USEC_PER_SEC +
77 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
80 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
81 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
86 bool endswith(const char *s, const char *postfix) {
98 return memcmp(s + sl - pl, postfix, pl) == 0;
101 bool startswith(const char *s, const char *prefix) {
113 return memcmp(s, prefix, pl) == 0;
116 bool first_word(const char *s, const char *word) {
128 if (memcmp(s, word, wl) != 0)
131 return (s[wl] == 0 ||
132 strchr(WHITESPACE, s[wl]));
135 int close_nointr(int fd) {
141 if ((r = close(fd)) >= 0)
149 void close_nointr_nofail(int fd) {
151 /* like close_nointr() but cannot fail, and guarantees errno
154 assert_se(close_nointr(fd) == 0);
157 int parse_boolean(const char *v) {
160 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
162 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
168 int safe_atou(const char *s, unsigned *ret_u) {
176 l = strtoul(s, &x, 0);
178 if (!x || *x || errno)
179 return errno ? -errno : -EINVAL;
181 if ((unsigned long) (unsigned) l != l)
184 *ret_u = (unsigned) l;
188 int safe_atoi(const char *s, int *ret_i) {
196 l = strtol(s, &x, 0);
198 if (!x || *x || errno)
199 return errno ? -errno : -EINVAL;
201 if ((long) (int) l != l)
208 int safe_atolu(const char *s, long unsigned *ret_lu) {
216 l = strtoul(s, &x, 0);
218 if (!x || *x || errno)
219 return errno ? -errno : -EINVAL;
225 int safe_atoli(const char *s, long int *ret_li) {
233 l = strtol(s, &x, 0);
235 if (!x || *x || errno)
236 return errno ? -errno : -EINVAL;
242 int safe_atollu(const char *s, long long unsigned *ret_llu) {
244 unsigned long long l;
250 l = strtoull(s, &x, 0);
252 if (!x || *x || errno)
253 return errno ? -errno : -EINVAL;
259 int safe_atolli(const char *s, long long int *ret_lli) {
267 l = strtoll(s, &x, 0);
269 if (!x || *x || errno)
270 return errno ? -errno : -EINVAL;
276 /* Split a string into words. */
277 char *split(const char *c, size_t *l, const char *separator, char **state) {
280 current = *state ? *state : (char*) c;
282 if (!*current || *c == 0)
285 current += strspn(current, separator);
286 *l = strcspn(current, separator);
289 return (char*) current;
292 /* Split a string into words, but consider strings enclosed in '' and
293 * "" as words even if they include spaces. */
294 char *split_quoted(const char *c, size_t *l, char **state) {
297 current = *state ? *state : (char*) c;
299 if (!*current || *c == 0)
302 current += strspn(current, WHITESPACE);
304 if (*current == '\'') {
306 *l = strcspn(current, "'");
311 } else if (*current == '\"') {
313 *l = strcspn(current, "\"");
319 *l = strcspn(current, WHITESPACE);
323 /* FIXME: Cannot deal with strings that have spaces AND ticks
326 return (char*) current;
329 char **split_path_and_make_absolute(const char *p) {
333 if (!(l = strv_split(p, ":")))
336 if (!strv_path_make_absolute_cwd(l)) {
344 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
347 char fn[132], line[256], *p;
348 long long unsigned ppid;
353 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%llu/stat", (unsigned long long) pid) < (int) (sizeof(fn)-1));
354 fn[sizeof(fn)-1] = 0;
356 if (!(f = fopen(fn, "r")))
359 if (!(fgets(line, sizeof(line), f))) {
367 /* Let's skip the pid and comm fields. The latter is enclosed
368 * in () but does not escape any () in its value, so let's
369 * skip over it manually */
371 if (!(p = strrchr(line, ')')))
382 if ((long long unsigned) (pid_t) ppid != ppid)
385 *_ppid = (pid_t) ppid;
390 int write_one_line_file(const char *fn, const char *line) {
397 if (!(f = fopen(fn, "we")))
400 if (fputs(line, f) < 0) {
411 int read_one_line_file(const char *fn, char **line) {
419 if (!(f = fopen(fn, "re")))
422 if (!(fgets(t, sizeof(t), f))) {
427 if (!(c = strdup(t))) {
440 char *strappend(const char *s, const char *suffix) {
450 if (!(r = new(char, a+b+1)))
454 memcpy(r+a, suffix, b);
460 int readlink_malloc(const char *p, char **r) {
470 if (!(c = new(char, l)))
473 if ((n = readlink(p, c, l-1)) < 0) {
479 if ((size_t) n < l-1) {
490 char *file_name_from_path(const char *p) {
495 if ((r = strrchr(p, '/')))
501 bool path_is_absolute(const char *p) {
507 bool is_path(const char *p) {
509 return !!strchr(p, '/');
512 char *path_make_absolute(const char *p, const char *prefix) {
517 /* Makes every item in the list an absolute path by prepending
518 * the prefix, if specified and necessary */
520 if (path_is_absolute(p) || !prefix)
523 if (asprintf(&r, "%s/%s", prefix, p) < 0)
529 char *path_make_absolute_cwd(const char *p) {
534 /* Similar to path_make_absolute(), but prefixes with the
535 * current working directory. */
537 if (path_is_absolute(p))
540 if (!(cwd = get_current_dir_name()))
543 r = path_make_absolute(p, cwd);
549 char **strv_path_make_absolute_cwd(char **l) {
552 /* Goes through every item in the string list and makes it
553 * absolute. This works in place and won't rollback any
554 * changes on failure. */
559 if (!(t = path_make_absolute_cwd(*s)))
569 int reset_all_signal_handlers(void) {
572 for (sig = 1; sig < _NSIG; sig++) {
575 if (sig == SIGKILL || sig == SIGSTOP)
579 sa.sa_handler = SIG_DFL;
580 sa.sa_flags = SA_RESTART;
582 /* On Linux the first two RT signals are reserved by
583 * glibc, and sigaction() will return EINVAL for them. */
584 if ((sigaction(sig, &sa, NULL) < 0))
592 char *strstrip(char *s) {
595 /* Drops trailing whitespace. Modifies the string in
596 * place. Returns pointer to first non-space character */
598 s += strspn(s, WHITESPACE);
601 if (!strchr(WHITESPACE, *e))
613 char *file_in_same_dir(const char *path, const char *filename) {
620 /* This removes the last component of path and appends
621 * filename, unless the latter is absolute anyway or the
624 if (path_is_absolute(filename))
625 return strdup(filename);
627 if (!(e = strrchr(path, '/')))
628 return strdup(filename);
630 k = strlen(filename);
631 if (!(r = new(char, e-path+1+k+1)))
634 memcpy(r, path, e-path+1);
635 memcpy(r+(e-path)+1, filename, k+1);
640 int mkdir_parents(const char *path, mode_t mode) {
645 /* Creates every parent directory in the path except the last
648 p = path + strspn(path, "/");
653 e = p + strcspn(p, "/");
654 p = e + strspn(e, "/");
656 /* Is this the last component? If so, then we're
661 if (!(t = strndup(path, e - path)))
668 if (r < 0 && errno != EEXIST)
673 char hexchar(int x) {
674 static const char table[16] = "0123456789abcdef";
676 return table[x & 15];
679 int unhexchar(char c) {
681 if (c >= '0' && c <= '9')
684 if (c >= 'a' && c <= 'f')
687 if (c >= 'A' && c <= 'F')
693 char octchar(int x) {
694 return '0' + (x & 7);
697 int unoctchar(char c) {
699 if (c >= '0' && c <= '7')
705 char decchar(int x) {
706 return '0' + (x % 10);
709 int undecchar(char c) {
711 if (c >= '0' && c <= '9')
717 char *cescape(const char *s) {
723 /* Does C style string escaping. */
725 if (!(r = new(char, strlen(s)*4 + 1)))
728 for (f = s, t = r; *f; f++)
774 /* For special chars we prefer octal over
775 * hexadecimal encoding, simply because glib's
776 * g_strescape() does the same */
777 if ((*f < ' ') || (*f >= 127)) {
779 *(t++) = octchar((unsigned char) *f >> 6);
780 *(t++) = octchar((unsigned char) *f >> 3);
781 *(t++) = octchar((unsigned char) *f);
792 char *cunescape(const char *s) {
798 /* Undoes C style string escaping */
800 if (!(r = new(char, strlen(s)+1)))
803 for (f = s, t = r; *f; f++) {
846 /* hexadecimal encoding */
849 if ((a = unhexchar(f[1])) < 0 ||
850 (b = unhexchar(f[2])) < 0) {
851 /* Invalid escape code, let's take it literal then */
855 *(t++) = (char) ((a << 4) | b);
873 if ((a = unoctchar(f[0])) < 0 ||
874 (b = unoctchar(f[1])) < 0 ||
875 (c = unoctchar(f[2])) < 0) {
876 /* Invalid escape code, let's take it literal then */
880 *(t++) = (char) ((a << 6) | (b << 3) | c);
888 /* premature end of string.*/
893 /* Invalid escape code, let's take it literal then */
906 char *xescape(const char *s, const char *bad) {
910 /* Escapes all chars in bad, in addition to \ and all special
911 * chars, in \xFF style escaping. May be reversed with
914 if (!(r = new(char, strlen(s)*4+1)))
917 for (f = s, t = r; *f; f++) {
919 if ((*f < ' ') || (*f >= 127) ||
920 (*f == '\\') || strchr(bad, *f)) {
923 *(t++) = hexchar(*f >> 4);
924 *(t++) = hexchar(*f);
934 char *bus_path_escape(const char *s) {
940 /* Escapes all chars that D-Bus' object path cannot deal
941 * with. Can be reverse with bus_path_unescape() */
943 if (!(r = new(char, strlen(s)*3+1)))
946 for (f = s, t = r; *f; f++) {
948 if (!(*f >= 'A' && *f <= 'Z') &&
949 !(*f >= 'a' && *f <= 'z') &&
950 !(*f >= '0' && *f <= '9')) {
952 *(t++) = hexchar(*f >> 4);
953 *(t++) = hexchar(*f);
963 char *bus_path_unescape(const char *s) {
969 if (!(r = new(char, strlen(s)+1)))
972 for (f = s, t = r; *f; f++) {
977 if ((a = unhexchar(f[1])) < 0 ||
978 (b = unhexchar(f[2])) < 0) {
979 /* Invalid escape code, let's take it literal then */
982 *(t++) = (char) ((a << 4) | b);
994 char *path_kill_slashes(char *path) {
998 /* Removes redundant inner and trailing slashes. Modifies the
999 * passed string in-place.
1001 * ///foo///bar/ becomes /foo/bar
1004 for (f = path, t = path; *f; f++) {
1019 /* Special rule, if we are talking of the root directory, a
1020 trailing slash is good */
1022 if (t == path && slash)
1029 bool path_startswith(const char *path, const char *prefix) {
1033 if ((path[0] == '/') != (prefix[0] == '/'))
1039 path += strspn(path, "/");
1040 prefix += strspn(prefix, "/");
1048 a = strcspn(path, "/");
1049 b = strcspn(prefix, "/");
1054 if (memcmp(path, prefix, a) != 0)
1062 char *ascii_strlower(char *t) {
1067 for (p = t; *p; p++)
1068 if (*p >= 'A' && *p <= 'Z')
1069 *p = *p - 'A' + 'a';
1074 bool ignore_file(const char *filename) {
1078 filename[0] == '.' ||
1079 endswith(filename, "~") ||
1080 endswith(filename, ".rpmnew") ||
1081 endswith(filename, ".rpmsave") ||
1082 endswith(filename, ".rpmorig") ||
1083 endswith(filename, ".dpkg-old") ||
1084 endswith(filename, ".dpkg-new") ||
1085 endswith(filename, ".swp");
1088 int fd_nonblock(int fd, bool nonblock) {
1093 if ((flags = fcntl(fd, F_GETFL, 0)) < 0)
1097 flags |= O_NONBLOCK;
1099 flags &= ~O_NONBLOCK;
1101 if (fcntl(fd, F_SETFL, flags) < 0)
1107 int fd_cloexec(int fd, bool cloexec) {
1112 if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
1116 flags |= FD_CLOEXEC;
1118 flags &= ~FD_CLOEXEC;
1120 if (fcntl(fd, F_SETFD, flags) < 0)
1126 static const char *const ioprio_class_table[] = {
1127 [IOPRIO_CLASS_NONE] = "none",
1128 [IOPRIO_CLASS_RT] = "realtime",
1129 [IOPRIO_CLASS_BE] = "best-effort",
1130 [IOPRIO_CLASS_IDLE] = "idle"
1133 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
1135 static const char *const sigchld_code_table[] = {
1136 [CLD_EXITED] = "exited",
1137 [CLD_KILLED] = "killed",
1138 [CLD_DUMPED] = "dumped",
1139 [CLD_TRAPPED] = "trapped",
1140 [CLD_STOPPED] = "stopped",
1141 [CLD_CONTINUED] = "continued",
1144 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
1146 static const char *const log_facility_table[LOG_NFACILITIES] = {
1147 [LOG_FAC(LOG_KERN)] = "kern",
1148 [LOG_FAC(LOG_USER)] = "user",
1149 [LOG_FAC(LOG_MAIL)] = "mail",
1150 [LOG_FAC(LOG_DAEMON)] = "daemon",
1151 [LOG_FAC(LOG_AUTH)] = "auth",
1152 [LOG_FAC(LOG_SYSLOG)] = "syslog",
1153 [LOG_FAC(LOG_LPR)] = "lpr",
1154 [LOG_FAC(LOG_NEWS)] = "news",
1155 [LOG_FAC(LOG_UUCP)] = "uucp",
1156 [LOG_FAC(LOG_CRON)] = "cron",
1157 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
1158 [LOG_FAC(LOG_FTP)] = "ftp",
1159 [LOG_FAC(LOG_LOCAL0)] = "local0",
1160 [LOG_FAC(LOG_LOCAL1)] = "local1",
1161 [LOG_FAC(LOG_LOCAL2)] = "local2",
1162 [LOG_FAC(LOG_LOCAL3)] = "local3",
1163 [LOG_FAC(LOG_LOCAL4)] = "local4",
1164 [LOG_FAC(LOG_LOCAL5)] = "local5",
1165 [LOG_FAC(LOG_LOCAL6)] = "local6",
1166 [LOG_FAC(LOG_LOCAL7)] = "local7"
1169 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
1171 static const char *const log_level_table[] = {
1172 [LOG_EMERG] = "emerg",
1173 [LOG_ALERT] = "alert",
1174 [LOG_CRIT] = "crit",
1176 [LOG_WARNING] = "warning",
1177 [LOG_NOTICE] = "notice",
1178 [LOG_INFO] = "info",
1179 [LOG_DEBUG] = "debug"
1182 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
1184 static const char* const sched_policy_table[] = {
1185 [SCHED_OTHER] = "other",
1186 [SCHED_BATCH] = "batch",
1187 [SCHED_IDLE] = "idle",
1188 [SCHED_FIFO] = "fifo",
1192 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
1194 static const char* const rlimit_table[] = {
1195 [RLIMIT_CPU] = "LimitCPU",
1196 [RLIMIT_FSIZE] = "LimitFSIZE",
1197 [RLIMIT_DATA] = "LimitDATA",
1198 [RLIMIT_STACK] = "LimitSTACK",
1199 [RLIMIT_CORE] = "LimitCORE",
1200 [RLIMIT_RSS] = "LimitRSS",
1201 [RLIMIT_NOFILE] = "LimitNOFILE",
1202 [RLIMIT_AS] = "LimitAS",
1203 [RLIMIT_NPROC] = "LimitNPROC",
1204 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
1205 [RLIMIT_LOCKS] = "LimitLOCKS",
1206 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
1207 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
1208 [RLIMIT_NICE] = "LimitNICE",
1209 [RLIMIT_RTPRIO] = "LimitRTPRIO",
1210 [RLIMIT_RTTIME] = "LimitRTTIME"
1213 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);