]>
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 bool streq_ptr(const char *a
, const char *b
) {
47 /* Like streq(), but tries to make sense of NULL pointers */
58 usec_t
now(clockid_t clock_id
) {
61 assert_se(clock_gettime(clock_id
, &ts
) == 0);
63 return timespec_load(&ts
);
66 usec_t
timespec_load(const struct timespec
*ts
) {
70 (usec_t
) ts
->tv_sec
* USEC_PER_SEC
+
71 (usec_t
) ts
->tv_nsec
/ NSEC_PER_USEC
;
74 struct timespec
*timespec_store(struct timespec
*ts
, usec_t u
) {
77 ts
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
78 ts
->tv_nsec
= (long int) ((u
% USEC_PER_SEC
) * NSEC_PER_USEC
);
83 usec_t
timeval_load(const struct timeval
*tv
) {
87 (usec_t
) tv
->tv_sec
* USEC_PER_SEC
+
91 struct timeval
*timeval_store(struct timeval
*tv
, usec_t u
) {
94 tv
->tv_sec
= (time_t) (u
/ USEC_PER_SEC
);
95 tv
->tv_usec
= (suseconds_t
) (u
% USEC_PER_SEC
);
100 bool endswith(const char *s
, const char *postfix
) {
107 pl
= strlen(postfix
);
112 return memcmp(s
+ sl
- pl
, postfix
, pl
) == 0;
115 bool startswith(const char *s
, const char *prefix
) {
127 return memcmp(s
, prefix
, pl
) == 0;
130 bool first_word(const char *s
, const char *word
) {
142 if (memcmp(s
, word
, wl
) != 0)
145 return (s
[wl
] == 0 ||
146 strchr(WHITESPACE
, s
[wl
]));
149 int close_nointr(int fd
) {
155 if ((r
= close(fd
)) >= 0)
163 void close_nointr_nofail(int fd
) {
165 /* like close_nointr() but cannot fail, and guarantees errno
168 assert_se(close_nointr(fd
) == 0);
171 int parse_boolean(const char *v
) {
174 if (streq(v
, "1") || v
[0] == 'y' || v
[0] == 'Y' || v
[0] == 't' || v
[0] == 'T' || !strcasecmp(v
, "on"))
176 else if (streq(v
, "0") || v
[0] == 'n' || v
[0] == 'N' || v
[0] == 'f' || v
[0] == 'F' || !strcasecmp(v
, "off"))
182 int safe_atou(const char *s
, unsigned *ret_u
) {
190 l
= strtoul(s
, &x
, 0);
192 if (!x
|| *x
|| errno
)
193 return errno
? -errno
: -EINVAL
;
195 if ((unsigned long) (unsigned) l
!= l
)
198 *ret_u
= (unsigned) l
;
202 int safe_atoi(const char *s
, int *ret_i
) {
210 l
= strtol(s
, &x
, 0);
212 if (!x
|| *x
|| errno
)
213 return errno
? -errno
: -EINVAL
;
215 if ((long) (int) l
!= l
)
222 int safe_atolu(const char *s
, long unsigned *ret_lu
) {
230 l
= strtoul(s
, &x
, 0);
232 if (!x
|| *x
|| errno
)
233 return errno
? -errno
: -EINVAL
;
239 int safe_atoli(const char *s
, long int *ret_li
) {
247 l
= strtol(s
, &x
, 0);
249 if (!x
|| *x
|| errno
)
250 return errno
? -errno
: -EINVAL
;
256 int safe_atollu(const char *s
, long long unsigned *ret_llu
) {
258 unsigned long long l
;
264 l
= strtoull(s
, &x
, 0);
266 if (!x
|| *x
|| errno
)
267 return errno
? -errno
: -EINVAL
;
273 int safe_atolli(const char *s
, long long int *ret_lli
) {
281 l
= strtoll(s
, &x
, 0);
283 if (!x
|| *x
|| errno
)
284 return errno
? -errno
: -EINVAL
;
290 /* Split a string into words. */
291 char *split(const char *c
, size_t *l
, const char *separator
, char **state
) {
294 current
= *state
? *state
: (char*) c
;
296 if (!*current
|| *c
== 0)
299 current
+= strspn(current
, separator
);
300 *l
= strcspn(current
, separator
);
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 char **split_path_and_make_absolute(const char *p
) {
347 if (!(l
= strv_split(p
, ":")))
350 if (!strv_path_make_absolute_cwd(l
)) {
358 int get_parent_of_pid(pid_t pid
, pid_t
*_ppid
) {
361 char fn
[132], line
[256], *p
;
362 long long unsigned ppid
;
367 assert_se(snprintf(fn
, sizeof(fn
)-1, "/proc/%llu/stat", (unsigned long long) pid
) < (int) (sizeof(fn
)-1));
368 fn
[sizeof(fn
)-1] = 0;
370 if (!(f
= fopen(fn
, "r")))
373 if (!(fgets(line
, sizeof(line
), f
))) {
381 /* Let's skip the pid and comm fields. The latter is enclosed
382 * in () but does not escape any () in its value, so let's
383 * skip over it manually */
385 if (!(p
= strrchr(line
, ')')))
396 if ((long long unsigned) (pid_t
) ppid
!= ppid
)
399 *_ppid
= (pid_t
) ppid
;
404 int write_one_line_file(const char *fn
, const char *line
) {
411 if (!(f
= fopen(fn
, "we")))
414 if (fputs(line
, f
) < 0) {
425 int read_one_line_file(const char *fn
, char **line
) {
433 if (!(f
= fopen(fn
, "re")))
436 if (!(fgets(t
, sizeof(t
), f
))) {
441 if (!(c
= strdup(t
))) {
454 char *truncate_nl(char *s
) {
457 s
[strcspn(s
, NEWLINE
)] = 0;
461 int get_process_name(pid_t pid
, char **name
) {
468 if (asprintf(&p
, "/proc/%llu/comm", (unsigned long long) pid
) < 0)
471 r
= read_one_line_file(p
, name
);
481 char *strappend(const char *s
, const char *suffix
) {
491 if (!(r
= new(char, a
+b
+1)))
495 memcpy(r
+a
, suffix
, b
);
501 int readlink_malloc(const char *p
, char **r
) {
511 if (!(c
= new(char, l
)))
514 if ((n
= readlink(p
, c
, l
-1)) < 0) {
520 if ((size_t) n
< l
-1) {
531 char *file_name_from_path(const char *p
) {
536 if ((r
= strrchr(p
, '/')))
542 bool path_is_absolute(const char *p
) {
548 bool is_path(const char *p
) {
550 return !!strchr(p
, '/');
553 char *path_make_absolute(const char *p
, const char *prefix
) {
558 /* Makes every item in the list an absolute path by prepending
559 * the prefix, if specified and necessary */
561 if (path_is_absolute(p
) || !prefix
)
564 if (asprintf(&r
, "%s/%s", prefix
, p
) < 0)
570 char *path_make_absolute_cwd(const char *p
) {
575 /* Similar to path_make_absolute(), but prefixes with the
576 * current working directory. */
578 if (path_is_absolute(p
))
581 if (!(cwd
= get_current_dir_name()))
584 r
= path_make_absolute(p
, cwd
);
590 char **strv_path_make_absolute_cwd(char **l
) {
593 /* Goes through every item in the string list and makes it
594 * absolute. This works in place and won't rollback any
595 * changes on failure. */
600 if (!(t
= path_make_absolute_cwd(*s
)))
610 int reset_all_signal_handlers(void) {
613 for (sig
= 1; sig
< _NSIG
; sig
++) {
616 if (sig
== SIGKILL
|| sig
== SIGSTOP
)
620 sa
.sa_handler
= SIG_DFL
;
621 sa
.sa_flags
= SA_RESTART
;
623 /* On Linux the first two RT signals are reserved by
624 * glibc, and sigaction() will return EINVAL for them. */
625 if ((sigaction(sig
, &sa
, NULL
) < 0))
633 char *strstrip(char *s
) {
636 /* Drops trailing whitespace. Modifies the string in
637 * place. Returns pointer to first non-space character */
639 s
+= strspn(s
, WHITESPACE
);
642 if (!strchr(WHITESPACE
, *e
))
654 char *delete_chars(char *s
, const char *bad
) {
657 /* Drops all whitespace, regardless where in the string */
659 for (f
= s
, t
= s
; *f
; f
++) {
671 char *file_in_same_dir(const char *path
, const char *filename
) {
678 /* This removes the last component of path and appends
679 * filename, unless the latter is absolute anyway or the
682 if (path_is_absolute(filename
))
683 return strdup(filename
);
685 if (!(e
= strrchr(path
, '/')))
686 return strdup(filename
);
688 k
= strlen(filename
);
689 if (!(r
= new(char, e
-path
+1+k
+1)))
692 memcpy(r
, path
, e
-path
+1);
693 memcpy(r
+(e
-path
)+1, filename
, k
+1);
698 int mkdir_parents(const char *path
, mode_t mode
) {
703 /* Creates every parent directory in the path except the last
706 p
= path
+ strspn(path
, "/");
711 e
= p
+ strcspn(p
, "/");
712 p
= e
+ strspn(e
, "/");
714 /* Is this the last component? If so, then we're
719 if (!(t
= strndup(path
, e
- path
)))
726 if (r
< 0 && errno
!= EEXIST
)
731 int mkdir_p(const char *path
, mode_t mode
) {
736 if ((r
= mkdir_parents(path
, mode
)) < 0)
739 if (mkdir(path
, mode
) < 0)
745 char hexchar(int x
) {
746 static const char table
[16] = "0123456789abcdef";
748 return table
[x
& 15];
751 int unhexchar(char c
) {
753 if (c
>= '0' && c
<= '9')
756 if (c
>= 'a' && c
<= 'f')
759 if (c
>= 'A' && c
<= 'F')
765 char octchar(int x
) {
766 return '0' + (x
& 7);
769 int unoctchar(char c
) {
771 if (c
>= '0' && c
<= '7')
777 char decchar(int x
) {
778 return '0' + (x
% 10);
781 int undecchar(char c
) {
783 if (c
>= '0' && c
<= '9')
789 char *cescape(const char *s
) {
795 /* Does C style string escaping. */
797 if (!(r
= new(char, strlen(s
)*4 + 1)))
800 for (f
= s
, t
= r
; *f
; f
++)
846 /* For special chars we prefer octal over
847 * hexadecimal encoding, simply because glib's
848 * g_strescape() does the same */
849 if ((*f
< ' ') || (*f
>= 127)) {
851 *(t
++) = octchar((unsigned char) *f
>> 6);
852 *(t
++) = octchar((unsigned char) *f
>> 3);
853 *(t
++) = octchar((unsigned char) *f
);
864 char *cunescape(const char *s
) {
870 /* Undoes C style string escaping */
872 if (!(r
= new(char, strlen(s
)+1)))
875 for (f
= s
, t
= r
; *f
; f
++) {
918 /* hexadecimal encoding */
921 if ((a
= unhexchar(f
[1])) < 0 ||
922 (b
= unhexchar(f
[2])) < 0) {
923 /* Invalid escape code, let's take it literal then */
927 *(t
++) = (char) ((a
<< 4) | b
);
945 if ((a
= unoctchar(f
[0])) < 0 ||
946 (b
= unoctchar(f
[1])) < 0 ||
947 (c
= unoctchar(f
[2])) < 0) {
948 /* Invalid escape code, let's take it literal then */
952 *(t
++) = (char) ((a
<< 6) | (b
<< 3) | c
);
960 /* premature end of string.*/
965 /* Invalid escape code, let's take it literal then */
978 char *xescape(const char *s
, const char *bad
) {
982 /* Escapes all chars in bad, in addition to \ and all special
983 * chars, in \xFF style escaping. May be reversed with
986 if (!(r
= new(char, strlen(s
)*4+1)))
989 for (f
= s
, t
= r
; *f
; f
++) {
991 if ((*f
< ' ') || (*f
>= 127) ||
992 (*f
== '\\') || strchr(bad
, *f
)) {
995 *(t
++) = hexchar(*f
>> 4);
996 *(t
++) = hexchar(*f
);
1006 char *bus_path_escape(const char *s
) {
1012 /* Escapes all chars that D-Bus' object path cannot deal
1013 * with. Can be reverse with bus_path_unescape() */
1015 if (!(r
= new(char, strlen(s
)*3+1)))
1018 for (f
= s
, t
= r
; *f
; f
++) {
1020 if (!(*f
>= 'A' && *f
<= 'Z') &&
1021 !(*f
>= 'a' && *f
<= 'z') &&
1022 !(*f
>= '0' && *f
<= '9')) {
1024 *(t
++) = hexchar(*f
>> 4);
1025 *(t
++) = hexchar(*f
);
1035 char *bus_path_unescape(const char *s
) {
1041 if (!(r
= new(char, strlen(s
)+1)))
1044 for (f
= s
, t
= r
; *f
; f
++) {
1049 if ((a
= unhexchar(f
[1])) < 0 ||
1050 (b
= unhexchar(f
[2])) < 0) {
1051 /* Invalid escape code, let's take it literal then */
1054 *(t
++) = (char) ((a
<< 4) | b
);
1066 char *path_kill_slashes(char *path
) {
1070 /* Removes redundant inner and trailing slashes. Modifies the
1071 * passed string in-place.
1073 * ///foo///bar/ becomes /foo/bar
1076 for (f
= path
, t
= path
; *f
; f
++) {
1091 /* Special rule, if we are talking of the root directory, a
1092 trailing slash is good */
1094 if (t
== path
&& slash
)
1101 bool path_startswith(const char *path
, const char *prefix
) {
1105 if ((path
[0] == '/') != (prefix
[0] == '/'))
1111 path
+= strspn(path
, "/");
1112 prefix
+= strspn(prefix
, "/");
1120 a
= strcspn(path
, "/");
1121 b
= strcspn(prefix
, "/");
1126 if (memcmp(path
, prefix
, a
) != 0)
1134 char *ascii_strlower(char *t
) {
1139 for (p
= t
; *p
; p
++)
1140 if (*p
>= 'A' && *p
<= 'Z')
1141 *p
= *p
- 'A' + 'a';
1146 bool ignore_file(const char *filename
) {
1150 filename
[0] == '.' ||
1151 endswith(filename
, "~") ||
1152 endswith(filename
, ".rpmnew") ||
1153 endswith(filename
, ".rpmsave") ||
1154 endswith(filename
, ".rpmorig") ||
1155 endswith(filename
, ".dpkg-old") ||
1156 endswith(filename
, ".dpkg-new") ||
1157 endswith(filename
, ".swp");
1160 int fd_nonblock(int fd
, bool nonblock
) {
1165 if ((flags
= fcntl(fd
, F_GETFL
, 0)) < 0)
1169 flags
|= O_NONBLOCK
;
1171 flags
&= ~O_NONBLOCK
;
1173 if (fcntl(fd
, F_SETFL
, flags
) < 0)
1179 int fd_cloexec(int fd
, bool cloexec
) {
1184 if ((flags
= fcntl(fd
, F_GETFD
, 0)) < 0)
1188 flags
|= FD_CLOEXEC
;
1190 flags
&= ~FD_CLOEXEC
;
1192 if (fcntl(fd
, F_SETFD
, flags
) < 0)
1198 int close_all_fds(const int except
[], unsigned n_except
) {
1203 if (!(d
= opendir("/proc/self/fd")))
1206 while ((de
= readdir(d
))) {
1209 if (de
->d_name
[0] == '.')
1212 if ((r
= safe_atoi(de
->d_name
, &fd
)) < 0)
1226 for (i
= 0; i
< n_except
; i
++)
1227 if (except
[i
] == fd
) {
1236 if ((r
= close_nointr(fd
)) < 0) {
1237 /* Valgrind has its own FD and doesn't want to have it closed */
1250 bool chars_intersect(const char *a
, const char *b
) {
1253 /* Returns true if any of the chars in a are in b. */
1254 for (p
= a
; *p
; p
++)
1261 char *format_timestamp(char *buf
, size_t l
, usec_t t
) {
1271 sec
= (time_t) t
/ USEC_PER_SEC
;
1273 if (strftime(buf
, l
, "%a, %d %b %Y %H:%M:%S %z", localtime_r(&sec
, &tm
)) <= 0)
1279 static const char *const ioprio_class_table
[] = {
1280 [IOPRIO_CLASS_NONE
] = "none",
1281 [IOPRIO_CLASS_RT
] = "realtime",
1282 [IOPRIO_CLASS_BE
] = "best-effort",
1283 [IOPRIO_CLASS_IDLE
] = "idle"
1286 DEFINE_STRING_TABLE_LOOKUP(ioprio_class
, int);
1288 static const char *const sigchld_code_table
[] = {
1289 [CLD_EXITED
] = "exited",
1290 [CLD_KILLED
] = "killed",
1291 [CLD_DUMPED
] = "dumped",
1292 [CLD_TRAPPED
] = "trapped",
1293 [CLD_STOPPED
] = "stopped",
1294 [CLD_CONTINUED
] = "continued",
1297 DEFINE_STRING_TABLE_LOOKUP(sigchld_code
, int);
1299 static const char *const log_facility_table
[LOG_NFACILITIES
] = {
1300 [LOG_FAC(LOG_KERN
)] = "kern",
1301 [LOG_FAC(LOG_USER
)] = "user",
1302 [LOG_FAC(LOG_MAIL
)] = "mail",
1303 [LOG_FAC(LOG_DAEMON
)] = "daemon",
1304 [LOG_FAC(LOG_AUTH
)] = "auth",
1305 [LOG_FAC(LOG_SYSLOG
)] = "syslog",
1306 [LOG_FAC(LOG_LPR
)] = "lpr",
1307 [LOG_FAC(LOG_NEWS
)] = "news",
1308 [LOG_FAC(LOG_UUCP
)] = "uucp",
1309 [LOG_FAC(LOG_CRON
)] = "cron",
1310 [LOG_FAC(LOG_AUTHPRIV
)] = "authpriv",
1311 [LOG_FAC(LOG_FTP
)] = "ftp",
1312 [LOG_FAC(LOG_LOCAL0
)] = "local0",
1313 [LOG_FAC(LOG_LOCAL1
)] = "local1",
1314 [LOG_FAC(LOG_LOCAL2
)] = "local2",
1315 [LOG_FAC(LOG_LOCAL3
)] = "local3",
1316 [LOG_FAC(LOG_LOCAL4
)] = "local4",
1317 [LOG_FAC(LOG_LOCAL5
)] = "local5",
1318 [LOG_FAC(LOG_LOCAL6
)] = "local6",
1319 [LOG_FAC(LOG_LOCAL7
)] = "local7"
1322 DEFINE_STRING_TABLE_LOOKUP(log_facility
, int);
1324 static const char *const log_level_table
[] = {
1325 [LOG_EMERG
] = "emerg",
1326 [LOG_ALERT
] = "alert",
1327 [LOG_CRIT
] = "crit",
1329 [LOG_WARNING
] = "warning",
1330 [LOG_NOTICE
] = "notice",
1331 [LOG_INFO
] = "info",
1332 [LOG_DEBUG
] = "debug"
1335 DEFINE_STRING_TABLE_LOOKUP(log_level
, int);
1337 static const char* const sched_policy_table
[] = {
1338 [SCHED_OTHER
] = "other",
1339 [SCHED_BATCH
] = "batch",
1340 [SCHED_IDLE
] = "idle",
1341 [SCHED_FIFO
] = "fifo",
1345 DEFINE_STRING_TABLE_LOOKUP(sched_policy
, int);
1347 static const char* const rlimit_table
[] = {
1348 [RLIMIT_CPU
] = "LimitCPU",
1349 [RLIMIT_FSIZE
] = "LimitFSIZE",
1350 [RLIMIT_DATA
] = "LimitDATA",
1351 [RLIMIT_STACK
] = "LimitSTACK",
1352 [RLIMIT_CORE
] = "LimitCORE",
1353 [RLIMIT_RSS
] = "LimitRSS",
1354 [RLIMIT_NOFILE
] = "LimitNOFILE",
1355 [RLIMIT_AS
] = "LimitAS",
1356 [RLIMIT_NPROC
] = "LimitNPROC",
1357 [RLIMIT_MEMLOCK
] = "LimitMEMLOCK",
1358 [RLIMIT_LOCKS
] = "LimitLOCKS",
1359 [RLIMIT_SIGPENDING
] = "LimitSIGPENDING",
1360 [RLIMIT_MSGQUEUE
] = "LimitMSGQUEUE",
1361 [RLIMIT_NICE
] = "LimitNICE",
1362 [RLIMIT_RTPRIO
] = "LimitRTPRIO",
1363 [RLIMIT_RTTIME
] = "LimitRTTIME"
1366 DEFINE_STRING_TABLE_LOOKUP(rlimit
, int);