]>
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>
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 *strappend(const char *s
, const char *suffix
) {
451 if (!(r
= new(char, a
+b
+1)))
455 memcpy(r
+a
, suffix
, b
);
461 int readlink_malloc(const char *p
, char **r
) {
471 if (!(c
= new(char, l
)))
474 if ((n
= readlink(p
, c
, l
-1)) < 0) {
480 if ((size_t) n
< l
-1) {
491 char *file_name_from_path(const char *p
) {
496 if ((r
= strrchr(p
, '/')))
502 bool path_is_absolute(const char *p
) {
508 bool is_path(const char *p
) {
510 return !!strchr(p
, '/');
513 char *path_make_absolute(const char *p
, const char *prefix
) {
518 /* Makes every item in the list an absolute path by prepending
519 * the prefix, if specified and necessary */
521 if (path_is_absolute(p
) || !prefix
)
524 if (asprintf(&r
, "%s/%s", prefix
, p
) < 0)
530 char *path_make_absolute_cwd(const char *p
) {
535 /* Similar to path_make_absolute(), but prefixes with the
536 * current working directory. */
538 if (path_is_absolute(p
))
541 if (!(cwd
= get_current_dir_name()))
544 r
= path_make_absolute(p
, cwd
);
550 char **strv_path_make_absolute_cwd(char **l
) {
553 /* Goes through every item in the string list and makes it
554 * absolute. This works in place and won't rollback any
555 * changes on failure. */
560 if (!(t
= path_make_absolute_cwd(*s
)))
570 int reset_all_signal_handlers(void) {
573 for (sig
= 1; sig
< _NSIG
; sig
++) {
576 if (sig
== SIGKILL
|| sig
== SIGSTOP
)
580 sa
.sa_handler
= SIG_DFL
;
581 sa
.sa_flags
= SA_RESTART
;
583 /* On Linux the first two RT signals are reserved by
584 * glibc, and sigaction() will return EINVAL for them. */
585 if ((sigaction(sig
, &sa
, NULL
) < 0))
593 char *strstrip(char *s
) {
596 /* Drops trailing whitespace. Modifies the string in
597 * place. Returns pointer to first non-space character */
599 s
+= strspn(s
, WHITESPACE
);
602 if (!strchr(WHITESPACE
, *e
))
614 char *file_in_same_dir(const char *path
, const char *filename
) {
621 /* This removes the last component of path and appends
622 * filename, unless the latter is absolute anyway or the
625 if (path_is_absolute(filename
))
626 return strdup(filename
);
628 if (!(e
= strrchr(path
, '/')))
629 return strdup(filename
);
631 k
= strlen(filename
);
632 if (!(r
= new(char, e
-path
+1+k
+1)))
635 memcpy(r
, path
, e
-path
+1);
636 memcpy(r
+(e
-path
)+1, filename
, k
+1);
641 int mkdir_parents(const char *path
, mode_t mode
) {
646 /* Creates every parent directory in the path except the last
649 p
= path
+ strspn(path
, "/");
654 e
= p
+ strcspn(p
, "/");
655 p
= e
+ strspn(e
, "/");
657 /* Is this the last component? If so, then we're
662 if (!(t
= strndup(path
, e
- path
)))
669 if (r
< 0 && errno
!= EEXIST
)
674 char hexchar(int x
) {
675 static const char table
[16] = "0123456789abcdef";
677 return table
[x
& 15];
680 int unhexchar(char c
) {
682 if (c
>= '0' && c
<= '9')
685 if (c
>= 'a' && c
<= 'f')
688 if (c
>= 'A' && c
<= 'F')
694 char octchar(int x
) {
695 return '0' + (x
& 7);
698 int unoctchar(char c
) {
700 if (c
>= '0' && c
<= '7')
706 char decchar(int x
) {
707 return '0' + (x
% 10);
710 int undecchar(char c
) {
712 if (c
>= '0' && c
<= '9')
718 char *cescape(const char *s
) {
724 /* Does C style string escaping. */
726 if (!(r
= new(char, strlen(s
)*4 + 1)))
729 for (f
= s
, t
= r
; *f
; f
++)
775 /* For special chars we prefer octal over
776 * hexadecimal encoding, simply because glib's
777 * g_strescape() does the same */
778 if ((*f
< ' ') || (*f
>= 127)) {
780 *(t
++) = octchar((unsigned char) *f
>> 6);
781 *(t
++) = octchar((unsigned char) *f
>> 3);
782 *(t
++) = octchar((unsigned char) *f
);
793 char *cunescape(const char *s
) {
799 /* Undoes C style string escaping */
801 if (!(r
= new(char, strlen(s
)+1)))
804 for (f
= s
, t
= r
; *f
; f
++) {
847 /* hexadecimal encoding */
850 if ((a
= unhexchar(f
[1])) < 0 ||
851 (b
= unhexchar(f
[2])) < 0) {
852 /* Invalid escape code, let's take it literal then */
856 *(t
++) = (char) ((a
<< 4) | b
);
874 if ((a
= unoctchar(f
[0])) < 0 ||
875 (b
= unoctchar(f
[1])) < 0 ||
876 (c
= unoctchar(f
[2])) < 0) {
877 /* Invalid escape code, let's take it literal then */
881 *(t
++) = (char) ((a
<< 6) | (b
<< 3) | c
);
889 /* premature end of string.*/
894 /* Invalid escape code, let's take it literal then */
907 char *xescape(const char *s
, const char *bad
) {
911 /* Escapes all chars in bad, in addition to \ and all special
912 * chars, in \xFF style escaping. May be reversed with
915 if (!(r
= new(char, strlen(s
)*4+1)))
918 for (f
= s
, t
= r
; *f
; f
++) {
920 if ((*f
< ' ') || (*f
>= 127) ||
921 (*f
== '\\') || strchr(bad
, *f
)) {
924 *(t
++) = hexchar(*f
>> 4);
925 *(t
++) = hexchar(*f
);
935 char *bus_path_escape(const char *s
) {
941 /* Escapes all chars that D-Bus' object path cannot deal
942 * with. Can be reverse with bus_path_unescape() */
944 if (!(r
= new(char, strlen(s
)*3+1)))
947 for (f
= s
, t
= r
; *f
; f
++) {
949 if (!(*f
>= 'A' && *f
<= 'Z') &&
950 !(*f
>= 'a' && *f
<= 'z') &&
951 !(*f
>= '0' && *f
<= '9')) {
953 *(t
++) = hexchar(*f
>> 4);
954 *(t
++) = hexchar(*f
);
964 char *bus_path_unescape(const char *s
) {
970 if (!(r
= new(char, strlen(s
)+1)))
973 for (f
= s
, t
= r
; *f
; f
++) {
978 if ((a
= unhexchar(f
[1])) < 0 ||
979 (b
= unhexchar(f
[2])) < 0) {
980 /* Invalid escape code, let's take it literal then */
983 *(t
++) = (char) ((a
<< 4) | b
);
995 char *path_kill_slashes(char *path
) {
999 /* Removes redundant inner and trailing slashes. Modifies the
1000 * passed string in-place.
1002 * ///foo///bar/ becomes /foo/bar
1005 for (f
= path
, t
= path
; *f
; f
++) {
1020 /* Special rule, if we are talking of the root directory, a
1021 trailing slash is good */
1023 if (t
== path
&& slash
)
1030 bool path_startswith(const char *path
, const char *prefix
) {
1034 if ((path
[0] == '/') != (prefix
[0] == '/'))
1040 path
+= strspn(path
, "/");
1041 prefix
+= strspn(prefix
, "/");
1049 a
= strcspn(path
, "/");
1050 b
= strcspn(prefix
, "/");
1055 if (memcmp(path
, prefix
, a
) != 0)
1063 char *ascii_strlower(char *t
) {
1068 for (p
= t
; *p
; p
++)
1069 if (*p
>= 'A' && *p
<= 'Z')
1070 *p
= *p
- 'A' + 'a';
1075 bool ignore_file(const char *filename
) {
1079 filename
[0] == '.' ||
1080 endswith(filename
, "~") ||
1081 endswith(filename
, ".rpmnew") ||
1082 endswith(filename
, ".rpmsave") ||
1083 endswith(filename
, ".rpmorig") ||
1084 endswith(filename
, ".dpkg-old") ||
1085 endswith(filename
, ".dpkg-new") ||
1086 endswith(filename
, ".swp");
1089 int fd_nonblock(int fd
, bool nonblock
) {
1094 if ((flags
= fcntl(fd
, F_GETFL
, 0)) < 0)
1098 flags
|= O_NONBLOCK
;
1100 flags
&= ~O_NONBLOCK
;
1102 if (fcntl(fd
, F_SETFL
, flags
) < 0)
1108 int fd_cloexec(int fd
, bool cloexec
) {
1113 if ((flags
= fcntl(fd
, F_GETFD
, 0)) < 0)
1117 flags
|= FD_CLOEXEC
;
1119 flags
&= ~FD_CLOEXEC
;
1121 if (fcntl(fd
, F_SETFD
, flags
) < 0)
1127 int close_all_fds(const int except
[], unsigned n_except
) {
1132 if (!(d
= opendir("/proc/self/fd")))
1135 while ((de
= readdir(d
))) {
1138 if (de
->d_name
[0] == '.')
1141 if ((r
= safe_atoi(de
->d_name
, &fd
)) < 0)
1155 for (i
= 0; i
< n_except
; i
++)
1156 if (except
[i
] == fd
) {
1165 if ((r
= close_nointr(fd
)) < 0) {
1166 /* Valgrind has its own FD and doesn't want to have it closed */
1179 static const char *const ioprio_class_table
[] = {
1180 [IOPRIO_CLASS_NONE
] = "none",
1181 [IOPRIO_CLASS_RT
] = "realtime",
1182 [IOPRIO_CLASS_BE
] = "best-effort",
1183 [IOPRIO_CLASS_IDLE
] = "idle"
1186 DEFINE_STRING_TABLE_LOOKUP(ioprio_class
, int);
1188 static const char *const sigchld_code_table
[] = {
1189 [CLD_EXITED
] = "exited",
1190 [CLD_KILLED
] = "killed",
1191 [CLD_DUMPED
] = "dumped",
1192 [CLD_TRAPPED
] = "trapped",
1193 [CLD_STOPPED
] = "stopped",
1194 [CLD_CONTINUED
] = "continued",
1197 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
1199 static const char *const log_facility_table
[LOG_NFACILITIES
] = {
1200 [LOG_FAC(LOG_KERN
)] = "kern",
1201 [LOG_FAC(LOG_USER
)] = "user",
1202 [LOG_FAC(LOG_MAIL
)] = "mail",
1203 [LOG_FAC(LOG_DAEMON
)] = "daemon",
1204 [LOG_FAC(LOG_AUTH
)] = "auth",
1205 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
1206 [LOG_FAC(LOG_LPR
)] = "lpr",
1207 [LOG_FAC(LOG_NEWS
)] = "news",
1208 [LOG_FAC(LOG_UUCP
)] = "uucp",
1209 [LOG_FAC(LOG_CRON
)] = "cron",
1210 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
1211 [LOG_FAC(LOG_FTP
)] = "ftp",
1212 [LOG_FAC(LOG_LOCAL0
)] = "local0",
1213 [LOG_FAC(LOG_LOCAL1
)] = "local1",
1214 [LOG_FAC(LOG_LOCAL2
)] = "local2",
1215 [LOG_FAC(LOG_LOCAL3
)] = "local3",
1216 [LOG_FAC(LOG_LOCAL4
)] = "local4",
1217 [LOG_FAC(LOG_LOCAL5
)] = "local5",
1218 [LOG_FAC(LOG_LOCAL6
)] = "local6",
1219 [LOG_FAC(LOG_LOCAL7
)] = "local7"
1222 DEFINE_STRING_TABLE_LOOKUP(log_facility
, int);
1224 static const char *const log_level_table
[] = {
1225 [LOG_EMERG
] = "emerg",
1226 [LOG_ALERT
] = "alert",
1227 [LOG_CRIT
] = "crit",
1229 [LOG_WARNING
] = "warning",
1230 [LOG_NOTICE
] = "notice",
1231 [LOG_INFO
] = "info",
1232 [LOG_DEBUG
] = "debug"
1235 DEFINE_STRING_TABLE_LOOKUP(log_level
, int);
1237 static const char* const sched_policy_table
[] = {
1238 [SCHED_OTHER
] = "other",
1239 [SCHED_BATCH
] = "batch",
1240 [SCHED_IDLE
] = "idle",
1241 [SCHED_FIFO
] = "fifo",
1245 DEFINE_STRING_TABLE_LOOKUP(sched_policy
, int);
1247 static const char* const rlimit_table
[] = {
1248 [RLIMIT_CPU
] = "LimitCPU",
1249 [RLIMIT_FSIZE
] = "LimitFSIZE",
1250 [RLIMIT_DATA
] = "LimitDATA",
1251 [RLIMIT_STACK
] = "LimitSTACK",
1252 [RLIMIT_CORE
] = "LimitCORE",
1253 [RLIMIT_RSS
] = "LimitRSS",
1254 [RLIMIT_NOFILE
] = "LimitNOFILE",
1255 [RLIMIT_AS
] = "LimitAS",
1256 [RLIMIT_NPROC
] = "LimitNPROC",
1257 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
1258 [RLIMIT_LOCKS
] = "LimitLOCKS",
1259 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
1260 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
1261 [RLIMIT_NICE
] = "LimitNICE",
1262 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
1263 [RLIMIT_RTTIME
] = "LimitRTTIME"
1266 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);