]>
git.ipfire.org Git - people/ms/systemd.git/blob - util.c
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>
43 usec_t
now(clockid_t clock_id
) {
46 assert_se(clock_gettime(clock_id
, &ts
) == 0);
48 return timespec_load(&ts
);
51 usec_t
timespec_load(const struct timespec
*ts
) {
55 (usec_t
) ts
->tv_sec
* USEC_PER_SEC
+
56 (usec_t
) ts
->tv_nsec
/ NSEC_PER_USEC
;
59 struct timespec
*timespec_store(struct timespec
*ts
, usec_t u
) {
62 ts
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
63 ts
->tv_nsec
= (long int) ((u
% USEC_PER_SEC
) * NSEC_PER_USEC
);
68 usec_t
timeval_load(const struct timeval
*tv
) {
72 (usec_t
) tv
->tv_sec
* USEC_PER_SEC
+
76 struct timeval
*timeval_store(struct timeval
*tv
, usec_t u
) {
79 tv
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
80 tv
->tv_usec
= (suseconds_t
) (u
% USEC_PER_SEC
);
85 bool endswith(const char *s
, const char *postfix
) {
97 return memcmp(s
+ sl
- pl
, postfix
, pl
) == 0;
100 bool startswith(const char *s
, const char *prefix
) {
112 return memcmp(s
, prefix
, pl
) == 0;
115 bool first_word(const char *s
, const char *word
) {
127 if (memcmp(s
, word
, wl
) != 0)
130 return (s
[wl
] == 0 ||
131 strchr(WHITESPACE
, s
[wl
]));
134 int close_nointr(int fd
) {
140 if ((r
= close(fd
)) >= 0)
148 void close_nointr_nofail(int fd
) {
150 /* like close_nointr() but cannot fail, and guarantees errno
153 assert_se(close_nointr(fd
) == 0);
156 int parse_boolean(const char *v
) {
159 if (streq(v
, "1") || v
[0] == 'y' || v
[0] == 'Y' || v
[0] == 't' || v
[0] == 'T' || !strcasecmp(v
, "on"))
161 else if (streq(v
, "0") || v
[0] == 'n' || v
[0] == 'N' || v
[0] == 'f' || v
[0] == 'F' || !strcasecmp(v
, "off"))
167 int safe_atou(const char *s
, unsigned *ret_u
) {
175 l
= strtoul(s
, &x
, 0);
177 if (!x
|| *x
|| errno
)
178 return errno
? -errno
: -EINVAL
;
180 if ((unsigned long) (unsigned) l
!= l
)
183 *ret_u
= (unsigned) l
;
187 int safe_atoi(const char *s
, int *ret_i
) {
195 l
= strtol(s
, &x
, 0);
197 if (!x
|| *x
|| errno
)
198 return errno
? -errno
: -EINVAL
;
200 if ((long) (int) l
!= l
)
207 int safe_atolu(const char *s
, long unsigned *ret_lu
) {
215 l
= strtoul(s
, &x
, 0);
217 if (!x
|| *x
|| errno
)
218 return errno
? -errno
: -EINVAL
;
224 int safe_atoli(const char *s
, long int *ret_li
) {
232 l
= strtol(s
, &x
, 0);
234 if (!x
|| *x
|| errno
)
235 return errno
? -errno
: -EINVAL
;
241 int safe_atollu(const char *s
, long long unsigned *ret_llu
) {
243 unsigned long long l
;
249 l
= strtoull(s
, &x
, 0);
251 if (!x
|| *x
|| errno
)
252 return errno
? -errno
: -EINVAL
;
258 int safe_atolli(const char *s
, long long int *ret_lli
) {
266 l
= strtoll(s
, &x
, 0);
268 if (!x
|| *x
|| errno
)
269 return errno
? -errno
: -EINVAL
;
275 /* Split a string into words. */
276 char *split(const char *c
, size_t *l
, const char *separator
, char **state
) {
279 current
= *state
? *state
: (char*) c
;
281 if (!*current
|| *c
== 0)
284 current
+= strspn(current
, separator
);
285 *l
= strcspn(current
, separator
);
288 return (char*) current
;
291 /* Split a string into words, but consider strings enclosed in '' and
292 * "" as words even if they include spaces. */
293 char *split_quoted(const char *c
, size_t *l
, char **state
) {
296 current
= *state
? *state
: (char*) c
;
298 if (!*current
|| *c
== 0)
301 current
+= strspn(current
, WHITESPACE
);
303 if (*current
== '\'') {
305 *l
= strcspn(current
, "'");
310 } else if (*current
== '\"') {
312 *l
= strcspn(current
, "\"");
318 *l
= strcspn(current
, WHITESPACE
);
322 /* FIXME: Cannot deal with strings that have spaces AND ticks
325 return (char*) current
;
328 char **split_path_and_make_absolute(const char *p
) {
332 if (!(l
= strv_split(p
, ":")))
335 if (!strv_path_make_absolute_cwd(l
)) {
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 /* Makes every item in the list an absolute path by prepending
517 * the prefix, if specified and necessary */
519 if (path_is_absolute(p
) || !prefix
)
522 if (asprintf(&r
, "%s/%s", prefix
, p
) < 0)
528 char *path_make_absolute_cwd(const char *p
) {
533 /* Similar to path_make_absolute(), but prefixes with the
534 * current working directory. */
536 if (path_is_absolute(p
))
539 if (!(cwd
= get_current_dir_name()))
542 r
= path_make_absolute(p
, cwd
);
548 char **strv_path_make_absolute_cwd(char **l
) {
551 /* Goes through every item in the string list and makes it
552 * absolute. This works in place and won't rollback any
553 * changes on failure. */
558 if (!(t
= path_make_absolute_cwd(*s
)))
568 int reset_all_signal_handlers(void) {
571 for (sig
= 1; sig
< _NSIG
; sig
++) {
574 if (sig
== SIGKILL
|| sig
== SIGSTOP
)
578 sa
.sa_handler
= SIG_DFL
;
579 sa
.sa_flags
= SA_RESTART
;
581 /* On Linux the first two RT signals are reserved by
582 * glibc, and sigaction() will return EINVAL for them. */
583 if ((sigaction(sig
, &sa
, NULL
) < 0))
591 char *strstrip(char *s
) {
594 /* Drops trailing whitespace. Modifies the string in
595 * place. Returns pointer to first non-space character */
597 s
+= strspn(s
, WHITESPACE
);
600 if (!strchr(WHITESPACE
, *e
))
612 char *file_in_same_dir(const char *path
, const char *filename
) {
619 /* This removes the last component of path and appends
620 * filename, unless the latter is absolute anyway or the
623 if (path_is_absolute(filename
))
624 return strdup(filename
);
626 if (!(e
= strrchr(path
, '/')))
627 return strdup(filename
);
629 k
= strlen(filename
);
630 if (!(r
= new(char, e
-path
+1+k
+1)))
633 memcpy(r
, path
, e
-path
+1);
634 memcpy(r
+(e
-path
)+1, filename
, k
+1);
639 int mkdir_parents(const char *path
, mode_t mode
) {
644 /* Creates every parent directory in the path except the last
647 p
= path
+ strspn(path
, "/");
652 e
= p
+ strcspn(p
, "/");
653 p
= e
+ strspn(e
, "/");
655 /* Is this the last component? If so, then we're
660 if (!(t
= strndup(path
, e
- path
)))
667 if (r
< 0 && errno
!= EEXIST
)
672 char hexchar(int x
) {
673 static const char table
[16] = "0123456789abcdef";
675 return table
[x
& 15];
678 int unhexchar(char c
) {
680 if (c
>= '0' && c
<= '9')
683 if (c
>= 'a' && c
<= 'f')
686 if (c
>= 'A' && c
<= 'F')
692 char octchar(int x
) {
693 return '0' + (x
& 7);
696 int unoctchar(char c
) {
698 if (c
>= '0' && c
<= '7')
704 char *cescape(const char *s
) {
710 /* Does C style string escaping. */
712 if (!(r
= new(char, strlen(s
)*4 + 1)))
715 for (f
= s
, t
= r
; *f
; f
++)
761 /* For special chars we prefer octal over
762 * hexadecimal encoding, simply because glib's
763 * g_strescape() does the same */
764 if ((*f
< ' ') || (*f
>= 127)) {
766 *(t
++) = octchar((unsigned char) *f
>> 6);
767 *(t
++) = octchar((unsigned char) *f
>> 3);
768 *(t
++) = octchar((unsigned char) *f
);
779 char *cunescape(const char *s
) {
785 /* Undoes C style string escaping */
787 if (!(r
= new(char, strlen(s
)+1)))
790 for (f
= s
, t
= r
; *f
; f
++) {
833 /* hexadecimal encoding */
836 if ((a
= unhexchar(f
[1])) < 0 ||
837 (b
= unhexchar(f
[2])) < 0) {
838 /* Invalid escape code, let's take it literal then */
842 *(t
++) = (char) ((a
<< 4) | b
);
860 if ((a
= unoctchar(f
[0])) < 0 ||
861 (b
= unoctchar(f
[1])) < 0 ||
862 (c
= unoctchar(f
[2])) < 0) {
863 /* Invalid escape code, let's take it literal then */
867 *(t
++) = (char) ((a
<< 6) | (b
<< 3) | c
);
875 /* premature end of string.*/
880 /* Invalid escape code, let's take it literal then */
893 char *xescape(const char *s
, const char *bad
) {
897 /* Escapes all chars in bad, in addition to \ and all special
898 * chars, in \xFF style escaping. May be reversed with
901 if (!(r
= new(char, strlen(s
)*4+1)))
904 for (f
= s
, t
= r
; *f
; f
++) {
906 if (*f
< ' ' || *f
>= 127 ||
907 *f
== '\\' || strchr(bad
, *f
)) {
910 *(t
++) = hexchar(*f
>> 4);
911 *(t
++) = hexchar(*f
);
921 char *bus_path_escape(const char *s
) {
927 /* Escapes all chars that D-Bus' object path cannot deal
928 * with. Can be reverse with bus_path_unescape() */
930 if (!(r
= new(char, strlen(s
)*3+1)))
933 for (f
= s
, t
= r
; *f
; f
++) {
935 if (!(*f
>= 'A' && *f
<= 'Z') &&
936 !(*f
>= 'a' && *f
<= 'z') &&
937 !(*f
>= '0' && *f
<= '9')) {
939 *(t
++) = hexchar(*f
>> 4);
940 *(t
++) = hexchar(*f
);
950 char *bus_path_unescape(const char *s
) {
956 if (!(r
= new(char, strlen(s
)+1)))
959 for (f
= s
, t
= r
; *f
; f
++) {
964 if ((a
= unhexchar(f
[1])) < 0 ||
965 (b
= unhexchar(f
[2])) < 0) {
966 /* Invalid escape code, let's take it literal then */
969 *(t
++) = (char) ((a
<< 4) | b
);
981 char *path_kill_slashes(char *path
) {
985 /* Removes redundant inner and trailing slashes. Modifies the
986 * passed string in-place.
988 * ///foo///bar/ becomes /foo/bar
991 for (f
= path
, t
= path
; *f
; f
++) {
1006 /* Special rule, if we are talking of the root directory, a
1007 trailing slash is good */
1009 if (t
== path
&& slash
)
1016 bool path_startswith(const char *path
, const char *prefix
) {
1020 if ((path
[0] == '/') != (prefix
[0] == '/'))
1026 path
+= strspn(path
, "/");
1027 prefix
+= strspn(prefix
, "/");
1035 a
= strcspn(path
, "/");
1036 b
= strcspn(prefix
, "/");
1041 if (memcmp(path
, prefix
, a
) != 0)
1049 char *ascii_strlower(char *path
) {
1054 for (p
= path
; *p
; p
++)
1055 if (*p
>= 'A' && *p
<= 'Z')
1056 *p
= *p
- 'A' + 'a';
1061 bool ignore_file(const char *filename
) {
1065 filename
[0] == '.' ||
1066 endswith(filename
, "~") ||
1067 endswith(filename
, ".rpmnew") ||
1068 endswith(filename
, ".rpmsave") ||
1069 endswith(filename
, ".rpmorig") ||
1070 endswith(filename
, ".dpkg-old") ||
1071 endswith(filename
, ".dpkg-new") ||
1072 endswith(filename
, ".swp");
1075 static const char *const ioprio_class_table
[] = {
1076 [IOPRIO_CLASS_NONE
] = "none",
1077 [IOPRIO_CLASS_RT
] = "realtime",
1078 [IOPRIO_CLASS_BE
] = "best-effort",
1079 [IOPRIO_CLASS_IDLE
] = "idle"
1082 DEFINE_STRING_TABLE_LOOKUP(ioprio_class
, int);
1084 static const char *const sigchld_code_table
[] = {
1085 [CLD_EXITED
] = "exited",
1086 [CLD_KILLED
] = "killed",
1087 [CLD_DUMPED
] = "dumped",
1088 [CLD_TRAPPED
] = "trapped",
1089 [CLD_STOPPED
] = "stopped",
1090 [CLD_CONTINUED
] = "continued",
1093 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
1095 static const char *const log_facility_table
[LOG_NFACILITIES
] = {
1096 [LOG_FAC(LOG_KERN
)] = "kern",
1097 [LOG_FAC(LOG_USER
)] = "user",
1098 [LOG_FAC(LOG_MAIL
)] = "mail",
1099 [LOG_FAC(LOG_DAEMON
)] = "daemon",
1100 [LOG_FAC(LOG_AUTH
)] = "auth",
1101 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
1102 [LOG_FAC(LOG_LPR
)] = "lpr",
1103 [LOG_FAC(LOG_NEWS
)] = "news",
1104 [LOG_FAC(LOG_UUCP
)] = "uucp",
1105 [LOG_FAC(LOG_CRON
)] = "cron",
1106 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
1107 [LOG_FAC(LOG_FTP
)] = "ftp",
1108 [LOG_FAC(LOG_LOCAL0
)] = "local0",
1109 [LOG_FAC(LOG_LOCAL1
)] = "local1",
1110 [LOG_FAC(LOG_LOCAL2
)] = "local2",
1111 [LOG_FAC(LOG_LOCAL3
)] = "local3",
1112 [LOG_FAC(LOG_LOCAL4
)] = "local4",
1113 [LOG_FAC(LOG_LOCAL5
)] = "local5",
1114 [LOG_FAC(LOG_LOCAL6
)] = "local6",
1115 [LOG_FAC(LOG_LOCAL7
)] = "local7"
1118 DEFINE_STRING_TABLE_LOOKUP(log_facility
, int);
1120 static const char *const log_level_table
[] = {
1121 [LOG_EMERG
] = "emerg",
1122 [LOG_ALERT
] = "alert",
1123 [LOG_CRIT
] = "crit",
1125 [LOG_WARNING
] = "warning",
1126 [LOG_NOTICE
] = "notice",
1127 [LOG_INFO
] = "info",
1128 [LOG_DEBUG
] = "debug"
1131 DEFINE_STRING_TABLE_LOOKUP(log_level
, int);
1133 static const char* const sched_policy_table
[] = {
1134 [SCHED_OTHER
] = "other",
1135 [SCHED_BATCH
] = "batch",
1136 [SCHED_IDLE
] = "idle",
1137 [SCHED_FIFO
] = "fifo",
1141 DEFINE_STRING_TABLE_LOOKUP(sched_policy
, int);
1143 static const char* const rlimit_table
[] = {
1144 [RLIMIT_CPU
] = "LimitCPU",
1145 [RLIMIT_FSIZE
] = "LimitFSIZE",
1146 [RLIMIT_DATA
] = "LimitDATA",
1147 [RLIMIT_STACK
] = "LimitSTACK",
1148 [RLIMIT_CORE
] = "LimitCORE",
1149 [RLIMIT_RSS
] = "LimitRSS",
1150 [RLIMIT_NOFILE
] = "LimitNOFILE",
1151 [RLIMIT_AS
] = "LimitAS",
1152 [RLIMIT_NPROC
] = "LimitNPROC",
1153 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
1154 [RLIMIT_LOCKS
] = "LimitLOCKS",
1155 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
1156 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
1157 [RLIMIT_NICE
] = "LimitNICE",
1158 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
1159 [RLIMIT_RTTIME
] = "LimitRTTIME"
1162 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);