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>
42 usec_t now(clockid_t clock_id) {
45 assert_se(clock_gettime(clock_id, &ts) == 0);
47 return timespec_load(&ts);
50 usec_t timespec_load(const struct timespec *ts) {
54 (usec_t) ts->tv_sec * USEC_PER_SEC +
55 (usec_t) ts->tv_nsec / NSEC_PER_USEC;
58 struct timespec *timespec_store(struct timespec *ts, usec_t u) {
61 ts->tv_sec = (time_t) (u / USEC_PER_SEC);
62 ts->tv_nsec = (long int) ((u % USEC_PER_SEC) * NSEC_PER_USEC);
67 usec_t timeval_load(const struct timeval *tv) {
71 (usec_t) tv->tv_sec * USEC_PER_SEC +
75 struct timeval *timeval_store(struct timeval *tv, usec_t u) {
78 tv->tv_sec = (time_t) (u / USEC_PER_SEC);
79 tv->tv_usec = (suseconds_t) (u % USEC_PER_SEC);
84 bool endswith(const char *s, const char *postfix) {
96 return memcmp(s + sl - pl, postfix, pl) == 0;
99 bool startswith(const char *s, const char *prefix) {
111 return memcmp(s, prefix, pl) == 0;
114 bool first_word(const char *s, const char *word) {
126 if (memcmp(s, word, wl) != 0)
129 return (s[wl] == 0 ||
130 strchr(WHITESPACE, s[wl]));
133 int close_nointr(int fd) {
139 if ((r = close(fd)) >= 0)
147 void close_nointr_nofail(int fd) {
149 /* like close_nointr() but cannot fail, and guarantees errno
152 assert_se(close_nointr(fd) == 0);
155 int parse_boolean(const char *v) {
158 if (streq(v, "1") || v[0] == 'y' || v[0] == 'Y' || v[0] == 't' || v[0] == 'T' || !strcasecmp(v, "on"))
160 else if (streq(v, "0") || v[0] == 'n' || v[0] == 'N' || v[0] == 'f' || v[0] == 'F' || !strcasecmp(v, "off"))
166 int safe_atou(const char *s, unsigned *ret_u) {
174 l = strtoul(s, &x, 0);
176 if (!x || *x || errno)
177 return errno ? -errno : -EINVAL;
179 if ((unsigned long) (unsigned) l != l)
182 *ret_u = (unsigned) l;
186 int safe_atoi(const char *s, int *ret_i) {
194 l = strtol(s, &x, 0);
196 if (!x || *x || errno)
197 return errno ? -errno : -EINVAL;
199 if ((long) (int) l != l)
206 int safe_atolu(const char *s, long unsigned *ret_lu) {
214 l = strtoul(s, &x, 0);
216 if (!x || *x || errno)
217 return errno ? -errno : -EINVAL;
223 int safe_atoli(const char *s, long int *ret_li) {
231 l = strtol(s, &x, 0);
233 if (!x || *x || errno)
234 return errno ? -errno : -EINVAL;
240 int safe_atollu(const char *s, long long unsigned *ret_llu) {
242 unsigned long long l;
248 l = strtoull(s, &x, 0);
250 if (!x || *x || errno)
251 return errno ? -errno : -EINVAL;
257 int safe_atolli(const char *s, long long int *ret_lli) {
265 l = strtoll(s, &x, 0);
267 if (!x || *x || errno)
268 return errno ? -errno : -EINVAL;
274 /* Split a string into words. */
275 char *split_spaces(const char *c, size_t *l, char **state) {
278 current = *state ? *state : (char*) c;
280 if (!*current || *c == 0)
283 current += strspn(current, WHITESPACE);
284 *l = strcspn(current, WHITESPACE);
287 return (char*) current;
290 /* Split a path into filenames. */
291 char *split_slash(const char *c, size_t *l, char **state) {
294 current = *state ? *state : (char*) c;
296 if (!*current || *c == 0)
299 current += strspn(current, "/");
300 *l = strcspn(current, "/");
303 return (char*) current;
306 /* Split a string into words, but consider strings enclosed in '' and
307 * "" as words even if they include spaces. */
308 char *split_quoted(const char *c, size_t *l, char **state) {
311 current = *state ? *state : (char*) c;
313 if (!*current || *c == 0)
316 current += strspn(current, WHITESPACE);
318 if (*current == '\'') {
320 *l = strcspn(current, "'");
325 } else if (*current == '\"') {
327 *l = strcspn(current, "\"");
333 *l = strcspn(current, WHITESPACE);
337 /* FIXME: Cannot deal with strings that have spaces AND ticks
340 return (char*) current;
343 int get_parent_of_pid(pid_t pid, pid_t *_ppid) {
346 char fn[132], line[256], *p;
347 long long unsigned ppid;
352 assert_se(snprintf(fn, sizeof(fn)-1, "/proc/%llu/stat", (unsigned long long) pid) < (int) (sizeof(fn)-1));
353 fn[sizeof(fn)-1] = 0;
355 if (!(f = fopen(fn, "r")))
358 if (!(fgets(line, sizeof(line), f))) {
366 /* Let's skip the pid and comm fields. The latter is enclosed
367 * in () but does not escape any () in its value, so let's
368 * skip over it manually */
370 if (!(p = strrchr(line, ')')))
381 if ((long long unsigned) (pid_t) ppid != ppid)
384 *_ppid = (pid_t) ppid;
389 int write_one_line_file(const char *fn, const char *line) {
396 if (!(f = fopen(fn, "we")))
399 if (fputs(line, f) < 0) {
410 int read_one_line_file(const char *fn, char **line) {
418 if (!(f = fopen(fn, "re")))
421 if (!(fgets(t, sizeof(t), f))) {
426 if (!(c = strdup(t))) {
439 char *strappend(const char *s, const char *suffix) {
449 if (!(r = new(char, a+b+1)))
453 memcpy(r+a, suffix, b);
459 int readlink_malloc(const char *p, char **r) {
469 if (!(c = new(char, l)))
472 if ((n = readlink(p, c, l-1)) < 0) {
478 if ((size_t) n < l-1) {
489 char *file_name_from_path(const char *p) {
494 if ((r = strrchr(p, '/')))
500 bool path_is_absolute(const char *p) {
506 bool is_path(const char *p) {
508 return !!strchr(p, '/');
511 char *path_make_absolute(const char *p, const char *prefix) {
516 if (path_is_absolute(p) || !prefix)
519 if (asprintf(&r, "%s/%s", prefix, p) < 0)
525 int reset_all_signal_handlers(void) {
528 for (sig = 1; sig < _NSIG; sig++) {
531 if (sig == SIGKILL || sig == SIGSTOP)
535 sa.sa_handler = SIG_DFL;
536 sa.sa_flags = SA_RESTART;
538 /* On Linux the first two RT signals are reserved by
539 * glibc, and sigaction() will return EINVAL for them. */
540 if ((sigaction(sig, &sa, NULL) < 0))
548 char *strstrip(char *s) {
551 /* Drops trailing whitespace. Modifies the string in
552 * place. Returns pointer to first non-space character */
554 s += strspn(s, WHITESPACE);
557 if (!strchr(WHITESPACE, *e))
569 char *file_in_same_dir(const char *path, const char *filename) {
576 /* This removes the last component of path and appends
577 * filename, unless the latter is absolute anyway or the
580 if (path_is_absolute(filename))
581 return strdup(filename);
583 if (!(e = strrchr(path, '/')))
584 return strdup(filename);
586 k = strlen(filename);
587 if (!(r = new(char, e-path+1+k+1)))
590 memcpy(r, path, e-path+1);
591 memcpy(r+(e-path)+1, filename, k+1);
596 int mkdir_parents(const char *path, mode_t mode) {
601 /* Creates every parent directory in the path except the last
604 p = path + strspn(path, "/");
609 e = p + strcspn(p, "/");
610 p = e + strspn(e, "/");
612 /* Is this the last component? If so, then we're
617 if (!(t = strndup(path, e - path)))
624 if (r < 0 && errno != EEXIST)
629 char hexchar(int x) {
630 static const char table[16] = "0123456789abcdef";
632 return table[x & 15];
635 int unhexchar(char c) {
637 if (c >= '0' && c <= '9')
640 if (c >= 'a' && c <= 'f')
643 if (c >= 'A' && c <= 'F')
649 char octchar(int x) {
650 return '0' + (x & 7);
653 int unoctchar(char c) {
655 if (c >= '0' && c <= '7')
661 char *cescape(const char *s) {
667 /* Does C style string escaping. */
669 if (!(r = new(char, strlen(s)*4 + 1)))
672 for (f = s, t = r; *f; f++)
718 /* For special chars we prefer octal over
719 * hexadecimal encoding, simply because glib's
720 * g_strescape() does the same */
721 if ((*f < ' ') || (*f >= 127)) {
723 *(t++) = octchar((unsigned char) *f >> 6);
724 *(t++) = octchar((unsigned char) *f >> 3);
725 *(t++) = octchar((unsigned char) *f);
736 char *cunescape(const char *s) {
742 /* Undoes C style string escaping */
744 if (!(r = new(char, strlen(s)+1)))
747 for (f = s, t = r; *f; f++) {
790 /* hexadecimal encoding */
793 if ((a = unhexchar(f[1])) < 0 ||
794 (b = unhexchar(f[2])) < 0) {
795 /* Invalid escape code, let's take it literal then */
799 *(t++) = (char) ((a << 4) | b);
817 if ((a = unoctchar(f[0])) < 0 ||
818 (b = unoctchar(f[1])) < 0 ||
819 (c = unoctchar(f[2])) < 0) {
820 /* Invalid escape code, let's take it literal then */
824 *(t++) = (char) ((a << 6) | (b << 3) | c);
832 /* premature end of string.*/
837 /* Invalid escape code, let's take it literal then */
850 char *xescape(const char *s, const char *bad) {
854 /* Escapes all chars in bad, in addition to \ and all special
855 * chars, in \xFF style escaping. May be reversed with
858 if (!(r = new(char, strlen(s)*4+1)))
861 for (f = s, t = r; *f; f++) {
863 if (*f < ' ' || *f >= 127 ||
864 *f == '\\' || strchr(bad, *f)) {
867 *(t++) = hexchar(*f >> 4);
868 *(t++) = hexchar(*f);
878 char *bus_path_escape(const char *s) {
884 /* Escapes all chars that D-Bus' object path cannot deal
885 * with. Can be reverse with bus_path_unescape() */
887 if (!(r = new(char, strlen(s)*3+1)))
890 for (f = s, t = r; *f; f++) {
892 if (!(*f >= 'A' && *f <= 'Z') &&
893 !(*f >= 'a' && *f <= 'z') &&
894 !(*f >= '0' && *f <= '9')) {
896 *(t++) = hexchar(*f >> 4);
897 *(t++) = hexchar(*f);
907 char *bus_path_unescape(const char *s) {
913 if (!(r = new(char, strlen(s)+1)))
916 for (f = s, t = r; *f; f++) {
921 if ((a = unhexchar(f[1])) < 0 ||
922 (b = unhexchar(f[2])) < 0) {
923 /* Invalid escape code, let's take it literal then */
926 *(t++) = (char) ((a << 4) | b);
938 char *path_kill_slashes(char *path) {
942 /* Removes redundant inner and trailing slashes. Modifies the
943 * passed string in-place.
945 * ///foo///bar/ becomes /foo/bar
948 for (f = path, t = path; *f; f++) {
963 /* Special rule, if we are talking of the root directory, a
964 trailing slash is good */
966 if (t == path && slash)
973 bool path_startswith(const char *path, const char *prefix) {
977 if ((path[0] == '/') != (prefix[0] == '/'))
983 path += strspn(path, "/");
984 prefix += strspn(prefix, "/");
992 a = strcspn(path, "/");
993 b = strcspn(prefix, "/");
998 if (memcmp(path, prefix, a) != 0)
1006 char *ascii_strlower(char *path) {
1011 for (p = path; *p; p++)
1012 if (*p >= 'A' && *p <= 'Z')
1013 *p = *p - 'A' + 'a';
1018 static const char *const ioprio_class_table[] = {
1019 [IOPRIO_CLASS_NONE] = "none",
1020 [IOPRIO_CLASS_RT] = "realtime",
1021 [IOPRIO_CLASS_BE] = "best-effort",
1022 [IOPRIO_CLASS_IDLE] = "idle"
1025 DEFINE_STRING_TABLE_LOOKUP(ioprio_class, int);
1027 static const char *const sigchld_code_table[] = {
1028 [CLD_EXITED] = "exited",
1029 [CLD_KILLED] = "killed",
1030 [CLD_DUMPED] = "dumped",
1031 [CLD_TRAPPED] = "trapped",
1032 [CLD_STOPPED] = "stopped",
1033 [CLD_CONTINUED] = "continued",
1036 DEFINE_STRING_TABLE_LOOKUP(sigchld_code, int);
1038 static const char *const log_facility_table[LOG_NFACILITIES] = {
1039 [LOG_FAC(LOG_KERN)] = "kern",
1040 [LOG_FAC(LOG_USER)] = "user",
1041 [LOG_FAC(LOG_MAIL)] = "mail",
1042 [LOG_FAC(LOG_DAEMON)] = "daemon",
1043 [LOG_FAC(LOG_AUTH)] = "auth",
1044 [LOG_FAC(LOG_SYSLOG)] = "syslog",
1045 [LOG_FAC(LOG_LPR)] = "lpr",
1046 [LOG_FAC(LOG_NEWS)] = "news",
1047 [LOG_FAC(LOG_UUCP)] = "uucp",
1048 [LOG_FAC(LOG_CRON)] = "cron",
1049 [LOG_FAC(LOG_AUTHPRIV)] = "authpriv",
1050 [LOG_FAC(LOG_FTP)] = "ftp",
1051 [LOG_FAC(LOG_LOCAL0)] = "local0",
1052 [LOG_FAC(LOG_LOCAL1)] = "local1",
1053 [LOG_FAC(LOG_LOCAL2)] = "local2",
1054 [LOG_FAC(LOG_LOCAL3)] = "local3",
1055 [LOG_FAC(LOG_LOCAL4)] = "local4",
1056 [LOG_FAC(LOG_LOCAL5)] = "local5",
1057 [LOG_FAC(LOG_LOCAL6)] = "local6",
1058 [LOG_FAC(LOG_LOCAL7)] = "local7"
1061 DEFINE_STRING_TABLE_LOOKUP(log_facility, int);
1063 static const char *const log_level_table[] = {
1064 [LOG_EMERG] = "emerg",
1065 [LOG_ALERT] = "alert",
1066 [LOG_CRIT] = "crit",
1068 [LOG_WARNING] = "warning",
1069 [LOG_NOTICE] = "notice",
1070 [LOG_INFO] = "info",
1071 [LOG_DEBUG] = "debug"
1074 DEFINE_STRING_TABLE_LOOKUP(log_level, int);
1076 static const char* const sched_policy_table[] = {
1077 [SCHED_OTHER] = "other",
1078 [SCHED_BATCH] = "batch",
1079 [SCHED_IDLE] = "idle",
1080 [SCHED_FIFO] = "fifo",
1084 DEFINE_STRING_TABLE_LOOKUP(sched_policy, int);
1086 static const char* const rlimit_table[] = {
1087 [RLIMIT_CPU] = "LimitCPU",
1088 [RLIMIT_FSIZE] = "LimitFSIZE",
1089 [RLIMIT_DATA] = "LimitDATA",
1090 [RLIMIT_STACK] = "LimitSTACK",
1091 [RLIMIT_CORE] = "LimitCORE",
1092 [RLIMIT_RSS] = "LimitRSS",
1093 [RLIMIT_NOFILE] = "LimitNOFILE",
1094 [RLIMIT_AS] = "LimitAS",
1095 [RLIMIT_NPROC] = "LimitNPROC",
1096 [RLIMIT_MEMLOCK] = "LimitMEMLOCK",
1097 [RLIMIT_LOCKS] = "LimitLOCKS",
1098 [RLIMIT_SIGPENDING] = "LimitSIGPENDING",
1099 [RLIMIT_MSGQUEUE] = "LimitMSGQUEUE",
1100 [RLIMIT_NICE] = "LimitNICE",
1101 [RLIMIT_RTPRIO] = "LimitRTPRIO",
1102 [RLIMIT_RTTIME] = "LimitRTTIME"
1105 DEFINE_STRING_TABLE_LOOKUP(rlimit, int);