]>
git.ipfire.org Git - thirdparty/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 *delete_chars(char *s
, const char *bad
) {
617 /* Drops all whitespace, regardless where in the string */
619 for (f
= s
, t
= s
; *f
; f
++) {
631 char *file_in_same_dir(const char *path
, const char *filename
) {
638 /* This removes the last component of path and appends
639 * filename, unless the latter is absolute anyway or the
642 if (path_is_absolute(filename
))
643 return strdup(filename
);
645 if (!(e
= strrchr(path
, '/')))
646 return strdup(filename
);
648 k
= strlen(filename
);
649 if (!(r
= new(char, e
-path
+1+k
+1)))
652 memcpy(r
, path
, e
-path
+1);
653 memcpy(r
+(e
-path
)+1, filename
, k
+1);
658 int mkdir_parents(const char *path
, mode_t mode
) {
663 /* Creates every parent directory in the path except the last
666 p
= path
+ strspn(path
, "/");
671 e
= p
+ strcspn(p
, "/");
672 p
= e
+ strspn(e
, "/");
674 /* Is this the last component? If so, then we're
679 if (!(t
= strndup(path
, e
- path
)))
686 if (r
< 0 && errno
!= EEXIST
)
691 char hexchar(int x
) {
692 static const char table
[16] = "0123456789abcdef";
694 return table
[x
& 15];
697 int unhexchar(char c
) {
699 if (c
>= '0' && c
<= '9')
702 if (c
>= 'a' && c
<= 'f')
705 if (c
>= 'A' && c
<= 'F')
711 char octchar(int x
) {
712 return '0' + (x
& 7);
715 int unoctchar(char c
) {
717 if (c
>= '0' && c
<= '7')
723 char decchar(int x
) {
724 return '0' + (x
% 10);
727 int undecchar(char c
) {
729 if (c
>= '0' && c
<= '9')
735 char *cescape(const char *s
) {
741 /* Does C style string escaping. */
743 if (!(r
= new(char, strlen(s
)*4 + 1)))
746 for (f
= s
, t
= r
; *f
; f
++)
792 /* For special chars we prefer octal over
793 * hexadecimal encoding, simply because glib's
794 * g_strescape() does the same */
795 if ((*f
< ' ') || (*f
>= 127)) {
797 *(t
++) = octchar((unsigned char) *f
>> 6);
798 *(t
++) = octchar((unsigned char) *f
>> 3);
799 *(t
++) = octchar((unsigned char) *f
);
810 char *cunescape(const char *s
) {
816 /* Undoes C style string escaping */
818 if (!(r
= new(char, strlen(s
)+1)))
821 for (f
= s
, t
= r
; *f
; f
++) {
864 /* hexadecimal encoding */
867 if ((a
= unhexchar(f
[1])) < 0 ||
868 (b
= unhexchar(f
[2])) < 0) {
869 /* Invalid escape code, let's take it literal then */
873 *(t
++) = (char) ((a
<< 4) | b
);
891 if ((a
= unoctchar(f
[0])) < 0 ||
892 (b
= unoctchar(f
[1])) < 0 ||
893 (c
= unoctchar(f
[2])) < 0) {
894 /* Invalid escape code, let's take it literal then */
898 *(t
++) = (char) ((a
<< 6) | (b
<< 3) | c
);
906 /* premature end of string.*/
911 /* Invalid escape code, let's take it literal then */
924 char *xescape(const char *s
, const char *bad
) {
928 /* Escapes all chars in bad, in addition to \ and all special
929 * chars, in \xFF style escaping. May be reversed with
932 if (!(r
= new(char, strlen(s
)*4+1)))
935 for (f
= s
, t
= r
; *f
; f
++) {
937 if ((*f
< ' ') || (*f
>= 127) ||
938 (*f
== '\\') || strchr(bad
, *f
)) {
941 *(t
++) = hexchar(*f
>> 4);
942 *(t
++) = hexchar(*f
);
952 char *bus_path_escape(const char *s
) {
958 /* Escapes all chars that D-Bus' object path cannot deal
959 * with. Can be reverse with bus_path_unescape() */
961 if (!(r
= new(char, strlen(s
)*3+1)))
964 for (f
= s
, t
= r
; *f
; f
++) {
966 if (!(*f
>= 'A' && *f
<= 'Z') &&
967 !(*f
>= 'a' && *f
<= 'z') &&
968 !(*f
>= '0' && *f
<= '9')) {
970 *(t
++) = hexchar(*f
>> 4);
971 *(t
++) = hexchar(*f
);
981 char *bus_path_unescape(const char *s
) {
987 if (!(r
= new(char, strlen(s
)+1)))
990 for (f
= s
, t
= r
; *f
; f
++) {
995 if ((a
= unhexchar(f
[1])) < 0 ||
996 (b
= unhexchar(f
[2])) < 0) {
997 /* Invalid escape code, let's take it literal then */
1000 *(t
++) = (char) ((a
<< 4) | b
);
1012 char *path_kill_slashes(char *path
) {
1016 /* Removes redundant inner and trailing slashes. Modifies the
1017 * passed string in-place.
1019 * ///foo///bar/ becomes /foo/bar
1022 for (f
= path
, t
= path
; *f
; f
++) {
1037 /* Special rule, if we are talking of the root directory, a
1038 trailing slash is good */
1040 if (t
== path
&& slash
)
1047 bool path_startswith(const char *path
, const char *prefix
) {
1051 if ((path
[0] == '/') != (prefix
[0] == '/'))
1057 path
+= strspn(path
, "/");
1058 prefix
+= strspn(prefix
, "/");
1066 a
= strcspn(path
, "/");
1067 b
= strcspn(prefix
, "/");
1072 if (memcmp(path
, prefix
, a
) != 0)
1080 char *ascii_strlower(char *t
) {
1085 for (p
= t
; *p
; p
++)
1086 if (*p
>= 'A' && *p
<= 'Z')
1087 *p
= *p
- 'A' + 'a';
1092 bool ignore_file(const char *filename
) {
1096 filename
[0] == '.' ||
1097 endswith(filename
, "~") ||
1098 endswith(filename
, ".rpmnew") ||
1099 endswith(filename
, ".rpmsave") ||
1100 endswith(filename
, ".rpmorig") ||
1101 endswith(filename
, ".dpkg-old") ||
1102 endswith(filename
, ".dpkg-new") ||
1103 endswith(filename
, ".swp");
1106 int fd_nonblock(int fd
, bool nonblock
) {
1111 if ((flags
= fcntl(fd
, F_GETFL
, 0)) < 0)
1115 flags
|= O_NONBLOCK
;
1117 flags
&= ~O_NONBLOCK
;
1119 if (fcntl(fd
, F_SETFL
, flags
) < 0)
1125 int fd_cloexec(int fd
, bool cloexec
) {
1130 if ((flags
= fcntl(fd
, F_GETFD
, 0)) < 0)
1134 flags
|= FD_CLOEXEC
;
1136 flags
&= ~FD_CLOEXEC
;
1138 if (fcntl(fd
, F_SETFD
, flags
) < 0)
1144 int close_all_fds(const int except
[], unsigned n_except
) {
1149 if (!(d
= opendir("/proc/self/fd")))
1152 while ((de
= readdir(d
))) {
1155 if (de
->d_name
[0] == '.')
1158 if ((r
= safe_atoi(de
->d_name
, &fd
)) < 0)
1172 for (i
= 0; i
< n_except
; i
++)
1173 if (except
[i
] == fd
) {
1182 if ((r
= close_nointr(fd
)) < 0) {
1183 /* Valgrind has its own FD and doesn't want to have it closed */
1196 bool chars_intersect(const char *a
, const char *b
) {
1199 /* Returns true if any of the chars in a are in b. */
1200 for (p
= a
; *p
; p
++)
1207 static const char *const ioprio_class_table
[] = {
1208 [IOPRIO_CLASS_NONE
] = "none",
1209 [IOPRIO_CLASS_RT
] = "realtime",
1210 [IOPRIO_CLASS_BE
] = "best-effort",
1211 [IOPRIO_CLASS_IDLE
] = "idle"
1214 DEFINE_STRING_TABLE_LOOKUP(ioprio_class
, int);
1216 static const char *const sigchld_code_table
[] = {
1217 [CLD_EXITED
] = "exited",
1218 [CLD_KILLED
] = "killed",
1219 [CLD_DUMPED
] = "dumped",
1220 [CLD_TRAPPED
] = "trapped",
1221 [CLD_STOPPED
] = "stopped",
1222 [CLD_CONTINUED
] = "continued",
1225 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
1227 static const char *const log_facility_table
[LOG_NFACILITIES
] = {
1228 [LOG_FAC(LOG_KERN
)] = "kern",
1229 [LOG_FAC(LOG_USER
)] = "user",
1230 [LOG_FAC(LOG_MAIL
)] = "mail",
1231 [LOG_FAC(LOG_DAEMON
)] = "daemon",
1232 [LOG_FAC(LOG_AUTH
)] = "auth",
1233 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
1234 [LOG_FAC(LOG_LPR
)] = "lpr",
1235 [LOG_FAC(LOG_NEWS
)] = "news",
1236 [LOG_FAC(LOG_UUCP
)] = "uucp",
1237 [LOG_FAC(LOG_CRON
)] = "cron",
1238 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
1239 [LOG_FAC(LOG_FTP
)] = "ftp",
1240 [LOG_FAC(LOG_LOCAL0
)] = "local0",
1241 [LOG_FAC(LOG_LOCAL1
)] = "local1",
1242 [LOG_FAC(LOG_LOCAL2
)] = "local2",
1243 [LOG_FAC(LOG_LOCAL3
)] = "local3",
1244 [LOG_FAC(LOG_LOCAL4
)] = "local4",
1245 [LOG_FAC(LOG_LOCAL5
)] = "local5",
1246 [LOG_FAC(LOG_LOCAL6
)] = "local6",
1247 [LOG_FAC(LOG_LOCAL7
)] = "local7"
1250 DEFINE_STRING_TABLE_LOOKUP(log_facility
, int);
1252 static const char *const log_level_table
[] = {
1253 [LOG_EMERG
] = "emerg",
1254 [LOG_ALERT
] = "alert",
1255 [LOG_CRIT
] = "crit",
1257 [LOG_WARNING
] = "warning",
1258 [LOG_NOTICE
] = "notice",
1259 [LOG_INFO
] = "info",
1260 [LOG_DEBUG
] = "debug"
1263 DEFINE_STRING_TABLE_LOOKUP(log_level
, int);
1265 static const char* const sched_policy_table
[] = {
1266 [SCHED_OTHER
] = "other",
1267 [SCHED_BATCH
] = "batch",
1268 [SCHED_IDLE
] = "idle",
1269 [SCHED_FIFO
] = "fifo",
1273 DEFINE_STRING_TABLE_LOOKUP(sched_policy
, int);
1275 static const char* const rlimit_table
[] = {
1276 [RLIMIT_CPU
] = "LimitCPU",
1277 [RLIMIT_FSIZE
] = "LimitFSIZE",
1278 [RLIMIT_DATA
] = "LimitDATA",
1279 [RLIMIT_STACK
] = "LimitSTACK",
1280 [RLIMIT_CORE
] = "LimitCORE",
1281 [RLIMIT_RSS
] = "LimitRSS",
1282 [RLIMIT_NOFILE
] = "LimitNOFILE",
1283 [RLIMIT_AS
] = "LimitAS",
1284 [RLIMIT_NPROC
] = "LimitNPROC",
1285 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
1286 [RLIMIT_LOCKS
] = "LimitLOCKS",
1287 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
1288 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
1289 [RLIMIT_NICE
] = "LimitNICE",
1290 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
1291 [RLIMIT_RTTIME
] = "LimitRTTIME"
1294 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);