2 * Copyright (C) 2012 - David Goulet <dgoulet@efficios.com>
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License, version 2 only, as
6 * published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful, but WITHOUT
9 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
13 * You should have received a copy of the GNU General Public License along with
14 * this program; if not, write to the Free Software Foundation, Inc., 51
15 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 #include <sys/types.h>
32 #include <common/common.h>
33 #include <common/runas.h>
39 * Resolve the './' and '../' strings in the middle of a path using
40 * our very own way to do it, so that it works even if the directory
44 char *utils_resolve_relative(const char *path
)
46 char *next
, *previous
, *slash
, *start_path
, *absolute_path
= NULL
;
53 /* Allocate memory for the absolute path */
54 absolute_path
= zmalloc(PATH_MAX
);
55 if (absolute_path
== NULL
) {
56 PERROR("zmalloc expand path");
60 /* Copy the path in the absolute path */
61 strncpy(absolute_path
, path
, PATH_MAX
);
63 /* As long as we find '/./' in the path string */
64 while ((next
= strstr(absolute_path
, "/./"))) {
66 /* We prepare the start_path not containing it */
67 start_path
= strndup(absolute_path
, next
- absolute_path
);
69 /* And we concatenate it with the part after this string */
70 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 2);
75 /* As long as we find '/../' in the path string */
76 while ((next
= strstr(absolute_path
, "/../"))) {
77 /* If the path starts with '/../', there's a problem */
78 if (next
== absolute_path
) {
79 ERR("%s: Path cannot be resolved", path
);
83 /* We find the last level of directory */
84 previous
= absolute_path
;
85 while ((slash
= strpbrk(previous
+ 1, "/")) && slash
!= next
) {
89 /* Then we prepare the start_path not containing it */
90 start_path
= strndup(absolute_path
, previous
- absolute_path
);
92 /* And we concatenate it with the part after the '/../' */
93 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 3);
107 * Return the realpath(3) of the path even if the last directory token does not
108 * exist. For example, with /tmp/test1/test2, if test2/ does not exist but the
109 * /tmp/test1 does, the real path is returned. In normal time, realpath(3)
110 * fails if the end point directory does not exist.
113 char *utils_expand_path(const char *path
)
115 const char *end_path
= path
;
116 char *next
, *cut_path
= NULL
, *expanded_path
= NULL
;
123 /* Find last token delimited by '/' */
124 while ((next
= strpbrk(end_path
+ 1, "/"))) {
128 /* Cut last token from original path */
129 cut_path
= strndup(path
, end_path
- path
);
131 expanded_path
= zmalloc(PATH_MAX
);
132 if (expanded_path
== NULL
) {
133 PERROR("zmalloc expand path");
137 expanded_path
= realpath((char *)cut_path
, expanded_path
);
138 if (expanded_path
== NULL
) {
141 ERR("%s: No such file or directory", cut_path
);
144 PERROR("realpath utils expand path");
150 /* Add end part to expanded path */
151 strncat(expanded_path
, end_path
, PATH_MAX
- strlen(expanded_path
) - 1);
154 return expanded_path
;
163 * Create a pipe in dst.
166 int utils_create_pipe(int *dst
)
176 PERROR("create pipe");
183 * Create pipe and set CLOEXEC flag to both fd.
185 * Make sure the pipe opened by this function are closed at some point. Use
186 * utils_close_pipe().
189 int utils_create_pipe_cloexec(int *dst
)
197 ret
= utils_create_pipe(dst
);
202 for (i
= 0; i
< 2; i
++) {
203 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
205 PERROR("fcntl pipe cloexec");
215 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
217 * Make sure the pipe opened by this function are closed at some point. Use
218 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
219 * support OSes other than Linux 2.6.23+.
222 int utils_create_pipe_cloexec_nonblock(int *dst
)
230 ret
= utils_create_pipe(dst
);
235 for (i
= 0; i
< 2; i
++) {
236 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
238 PERROR("fcntl pipe cloexec");
242 * Note: we override any flag that could have been
243 * previously set on the fd.
245 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
247 PERROR("fcntl pipe nonblock");
257 * Close both read and write side of the pipe.
260 void utils_close_pipe(int *src
)
268 for (i
= 0; i
< 2; i
++) {
276 PERROR("close pipe");
282 * Create a new string using two strings range.
285 char *utils_strdupdelim(const char *begin
, const char *end
)
289 str
= zmalloc(end
- begin
+ 1);
291 PERROR("zmalloc strdupdelim");
295 memcpy(str
, begin
, end
- begin
);
296 str
[end
- begin
] = '\0';
303 * Set CLOEXEC flag to the give file descriptor.
306 int utils_set_fd_cloexec(int fd
)
315 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
317 PERROR("fcntl cloexec");
326 * Create pid file to the given path and filename.
329 int utils_create_pid_file(pid_t pid
, const char *filepath
)
336 fp
= fopen(filepath
, "w");
338 PERROR("open pid file %s", filepath
);
343 ret
= fprintf(fp
, "%d\n", pid
);
345 PERROR("fprintf pid file");
349 DBG("Pid %d written in file %s", pid
, filepath
);
355 * Recursively create directory using the given path and mode.
357 * On success, return 0 else a negative error code.
360 int utils_mkdir_recursive(const char *path
, mode_t mode
)
362 char *p
, tmp
[PATH_MAX
];
368 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
370 PERROR("snprintf mkdir");
375 if (tmp
[len
- 1] == '/') {
379 for (p
= tmp
+ 1; *p
; p
++) {
382 if (tmp
[strlen(tmp
) - 1] == '.' &&
383 tmp
[strlen(tmp
) - 2] == '.' &&
384 tmp
[strlen(tmp
) - 3] == '/') {
385 ERR("Using '/../' is not permitted in the trace path (%s)",
390 ret
= mkdir(tmp
, mode
);
392 if (errno
!= EEXIST
) {
393 PERROR("mkdir recursive");
402 ret
= mkdir(tmp
, mode
);
404 if (errno
!= EEXIST
) {
405 PERROR("mkdir recursive last piece");
417 * Create the stream tracefile on disk.
419 * Return 0 on success or else a negative value.
422 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
423 uint64_t count
, int uid
, int gid
, char *suffix
)
425 int ret
, out_fd
, flags
, mode
;
426 char full_path
[PATH_MAX
], *path_name_suffix
= NULL
, *path
;
432 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
433 path_name
, file_name
);
435 PERROR("snprintf create output file");
439 /* Setup extra string if suffix or/and a count is needed. */
440 if (size
> 0 && suffix
) {
441 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
442 } else if (size
> 0) {
443 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
445 ret
= asprintf(&extra
, "%s", suffix
);
448 PERROR("Allocating extra string to name");
453 * If we split the trace in multiple files, we have to add the count at the
454 * end of the tracefile name
457 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
459 PERROR("Allocating path name with extra string");
460 goto error_free_suffix
;
462 path
= path_name_suffix
;
467 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
468 /* Open with 660 mode */
469 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
471 if (uid
< 0 || gid
< 0) {
472 out_fd
= open(path
, flags
, mode
);
474 out_fd
= run_as_open(path
, flags
, mode
, uid
, gid
);
477 PERROR("open stream path %s", path
);
483 free(path_name_suffix
);
491 * Change the output tracefile according to the given size and count The
492 * new_count pointer is set during this operation.
494 * From the consumer, the stream lock MUST be held before calling this function
495 * because we are modifying the stream status.
497 * Return 0 on success or else a negative value.
500 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
501 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
511 PERROR("Closing tracefile");
516 *new_count
= (*new_count
+ 1) % count
;
521 ret
= utils_create_stream_file(path_name
, file_name
, size
, *new_count
,
536 * Prints the error message corresponding to a regex error code.
538 * @param errcode The error code.
539 * @param regex The regex object that produced the error code.
541 static void regex_print_error(int errcode
, regex_t
*regex
)
543 /* Get length of error message and allocate accordingly */
547 assert(regex
!= NULL
);
549 length
= regerror(errcode
, regex
, NULL
, 0);
551 ERR("regerror returned a length of 0");
555 buffer
= zmalloc(length
);
557 ERR("regex_print_error: zmalloc failed");
561 /* Get and print error message */
562 regerror(errcode
, regex
, buffer
, length
);
563 ERR("regex error: %s\n", buffer
);
569 * Parse a string that represents a size in human readable format. It
570 * supports decimal integers suffixed by 'k', 'M' or 'G'.
572 * The suffix multiply the integer by:
577 * @param str The string to parse.
578 * @param size Pointer to a size_t that will be filled with the
581 * @return 0 on success, -1 on failure.
584 int utils_parse_size_suffix(char *str
, uint64_t *size
)
588 const int nmatch
= 3;
589 regmatch_t suffix_match
, matches
[nmatch
];
590 unsigned long long base_size
;
598 ret
= regcomp(®ex
, "^\\(0x\\)\\{0,1\\}[0-9][0-9]*\\([kKMG]\\{0,1\\}\\)$", 0);
600 regex_print_error(ret
, ®ex
);
606 ret
= regexec(®ex
, str
, nmatch
, matches
, 0);
612 /* There is a match ! */
614 base_size
= strtoull(str
, NULL
, 0);
621 /* Check if there is a suffix */
622 suffix_match
= matches
[2];
623 if (suffix_match
.rm_eo
- suffix_match
.rm_so
== 1) {
624 switch (*(str
+ suffix_match
.rm_so
)) {
636 ERR("parse_human_size: invalid suffix");
642 *size
= base_size
<< shift
;
644 /* Check for overflow */
645 if ((*size
>> shift
) != base_size
) {
646 ERR("parse_size_suffix: oops, overflow detected.");
660 * fls: returns the position of the most significant bit.
661 * Returns 0 if no bit is set, else returns the position of the most
662 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
664 #if defined(__i386) || defined(__x86_64)
665 static inline unsigned int fls_u32(uint32_t x
)
673 : "=r" (r
) : "rm" (x
));
680 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
687 if (!(x
& 0xFFFF0000U
)) {
691 if (!(x
& 0xFF000000U
)) {
695 if (!(x
& 0xF0000000U
)) {
699 if (!(x
& 0xC0000000U
)) {
703 if (!(x
& 0x80000000U
)) {
712 * Return the minimum order for which x <= (1UL << order).
713 * Return -1 if x is 0.
716 int utils_get_count_order_u32(uint32_t x
)
722 return fls_u32(x
- 1);
726 * Obtain the value of LTTNG_HOME environment variable, if exists.
727 * Otherwise returns the value of HOME.
730 char *utils_get_home_dir(void)
733 val
= getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
737 return getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
741 * With the given format, fill dst with the time of len maximum siz.
743 * Return amount of bytes set in the buffer or else 0 on error.
746 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
755 /* Get date and time for session path */
757 timeinfo
= localtime(&rawtime
);
758 ret
= strftime(dst
, len
, format
, timeinfo
);
760 ERR("Unable to strftime with format %s at dst %p of len %lu", format
,
768 * Return the group ID matching name, else 0 if it cannot be found.
771 gid_t
utils_get_group_id(const char *name
)
775 grp
= getgrnam(name
);
777 static volatile int warn_once
;
780 WARN("No tracing group detected");