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
= NULL
;
116 char *next
, *cut_path
= NULL
, *expanded_path
= NULL
;
123 /* Allocate memory for the expanded path */
124 expanded_path
= zmalloc(PATH_MAX
);
125 if (expanded_path
== NULL
) {
126 PERROR("zmalloc expand path");
130 /* If given path is already absolute */
132 strncpy(expanded_path
, path
, PATH_MAX
);
133 /* Else, we have some work to do */
135 /* Pointer to the last char of the path */
136 const char *last_char
= path
+ strlen(path
) - 1;
140 /* Split part that will be resolved by realpath (relative path from
141 * current directory using ./ or ../ only) and part that could not
144 while ((next
= strpbrk(end_path
, "/")) && (next
!= last_char
)) {
146 if (strncmp(end_path
, "./", 2) != 0 &&
147 strncmp(end_path
, "../", 3) != 0) {
152 /* If this is the end of the string, and we still can resolve it */
153 if (strncmp(end_path
, "..\0", 3) == 0 ||
154 strncmp(end_path
, ".\0", 2) == 0) {
155 end_path
+= strlen(end_path
);
158 /* If the end part is the whole path, we are in the current dir */
159 if (end_path
== path
) {
160 cut_path
= strdup(".");
161 /* Else, cut the resolvable part from original path */
163 cut_path
= strndup(path
, end_path
- path
);
166 /* Resolve the canonical path of the first part of the path */
167 expanded_path
= realpath((char *)cut_path
, expanded_path
);
168 if (expanded_path
== NULL
) {
171 ERR("%s: No such file or directory", cut_path
);
174 PERROR("realpath utils expand path");
180 /* Add end part to expanded path if not empty */
181 if (*end_path
!= 0) {
182 strncat(expanded_path
, "/", PATH_MAX
- strlen(expanded_path
) - 1);
183 strncat(expanded_path
, end_path
,
184 PATH_MAX
- strlen(expanded_path
) - 1);
188 /* Resolve the internal './' and '../' strings */
189 next
= utils_resolve_relative(expanded_path
);
205 * Create a pipe in dst.
208 int utils_create_pipe(int *dst
)
218 PERROR("create pipe");
225 * Create pipe and set CLOEXEC flag to both fd.
227 * Make sure the pipe opened by this function are closed at some point. Use
228 * utils_close_pipe().
231 int utils_create_pipe_cloexec(int *dst
)
239 ret
= utils_create_pipe(dst
);
244 for (i
= 0; i
< 2; i
++) {
245 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
247 PERROR("fcntl pipe cloexec");
257 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
259 * Make sure the pipe opened by this function are closed at some point. Use
260 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
261 * support OSes other than Linux 2.6.23+.
264 int utils_create_pipe_cloexec_nonblock(int *dst
)
272 ret
= utils_create_pipe(dst
);
277 for (i
= 0; i
< 2; i
++) {
278 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
280 PERROR("fcntl pipe cloexec");
284 * Note: we override any flag that could have been
285 * previously set on the fd.
287 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
289 PERROR("fcntl pipe nonblock");
299 * Close both read and write side of the pipe.
302 void utils_close_pipe(int *src
)
310 for (i
= 0; i
< 2; i
++) {
318 PERROR("close pipe");
324 * Create a new string using two strings range.
327 char *utils_strdupdelim(const char *begin
, const char *end
)
331 str
= zmalloc(end
- begin
+ 1);
333 PERROR("zmalloc strdupdelim");
337 memcpy(str
, begin
, end
- begin
);
338 str
[end
- begin
] = '\0';
345 * Set CLOEXEC flag to the give file descriptor.
348 int utils_set_fd_cloexec(int fd
)
357 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
359 PERROR("fcntl cloexec");
368 * Create pid file to the given path and filename.
371 int utils_create_pid_file(pid_t pid
, const char *filepath
)
378 fp
= fopen(filepath
, "w");
380 PERROR("open pid file %s", filepath
);
385 ret
= fprintf(fp
, "%d\n", pid
);
387 PERROR("fprintf pid file");
391 DBG("Pid %d written in file %s", pid
, filepath
);
397 * Recursively create directory using the given path and mode.
399 * On success, return 0 else a negative error code.
402 int utils_mkdir_recursive(const char *path
, mode_t mode
)
404 char *p
, tmp
[PATH_MAX
];
410 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
412 PERROR("snprintf mkdir");
417 if (tmp
[len
- 1] == '/') {
421 for (p
= tmp
+ 1; *p
; p
++) {
424 if (tmp
[strlen(tmp
) - 1] == '.' &&
425 tmp
[strlen(tmp
) - 2] == '.' &&
426 tmp
[strlen(tmp
) - 3] == '/') {
427 ERR("Using '/../' is not permitted in the trace path (%s)",
432 ret
= mkdir(tmp
, mode
);
434 if (errno
!= EEXIST
) {
435 PERROR("mkdir recursive");
444 ret
= mkdir(tmp
, mode
);
446 if (errno
!= EEXIST
) {
447 PERROR("mkdir recursive last piece");
459 * Create the stream tracefile on disk.
461 * Return 0 on success or else a negative value.
464 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
465 uint64_t count
, int uid
, int gid
, char *suffix
)
467 int ret
, out_fd
, flags
, mode
;
468 char full_path
[PATH_MAX
], *path_name_suffix
= NULL
, *path
;
474 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
475 path_name
, file_name
);
477 PERROR("snprintf create output file");
481 /* Setup extra string if suffix or/and a count is needed. */
482 if (size
> 0 && suffix
) {
483 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
484 } else if (size
> 0) {
485 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
487 ret
= asprintf(&extra
, "%s", suffix
);
490 PERROR("Allocating extra string to name");
495 * If we split the trace in multiple files, we have to add the count at the
496 * end of the tracefile name
499 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
501 PERROR("Allocating path name with extra string");
502 goto error_free_suffix
;
504 path
= path_name_suffix
;
509 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
510 /* Open with 660 mode */
511 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
513 if (uid
< 0 || gid
< 0) {
514 out_fd
= open(path
, flags
, mode
);
516 out_fd
= run_as_open(path
, flags
, mode
, uid
, gid
);
519 PERROR("open stream path %s", path
);
525 free(path_name_suffix
);
533 * Change the output tracefile according to the given size and count The
534 * new_count pointer is set during this operation.
536 * From the consumer, the stream lock MUST be held before calling this function
537 * because we are modifying the stream status.
539 * Return 0 on success or else a negative value.
542 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
543 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
553 PERROR("Closing tracefile");
558 *new_count
= (*new_count
+ 1) % count
;
563 ret
= utils_create_stream_file(path_name
, file_name
, size
, *new_count
,
578 * Prints the error message corresponding to a regex error code.
580 * @param errcode The error code.
581 * @param regex The regex object that produced the error code.
583 static void regex_print_error(int errcode
, regex_t
*regex
)
585 /* Get length of error message and allocate accordingly */
589 assert(regex
!= NULL
);
591 length
= regerror(errcode
, regex
, NULL
, 0);
593 ERR("regerror returned a length of 0");
597 buffer
= zmalloc(length
);
599 ERR("regex_print_error: zmalloc failed");
603 /* Get and print error message */
604 regerror(errcode
, regex
, buffer
, length
);
605 ERR("regex error: %s\n", buffer
);
611 * Parse a string that represents a size in human readable format. It
612 * supports decimal integers suffixed by 'k', 'M' or 'G'.
614 * The suffix multiply the integer by:
619 * @param str The string to parse.
620 * @param size Pointer to a size_t that will be filled with the
623 * @return 0 on success, -1 on failure.
626 int utils_parse_size_suffix(char *str
, uint64_t *size
)
630 const int nmatch
= 3;
631 regmatch_t suffix_match
, matches
[nmatch
];
632 unsigned long long base_size
;
640 ret
= regcomp(®ex
, "^\\(0x\\)\\{0,1\\}[0-9][0-9]*\\([kKMG]\\{0,1\\}\\)$", 0);
642 regex_print_error(ret
, ®ex
);
648 ret
= regexec(®ex
, str
, nmatch
, matches
, 0);
654 /* There is a match ! */
656 base_size
= strtoull(str
, NULL
, 0);
663 /* Check if there is a suffix */
664 suffix_match
= matches
[2];
665 if (suffix_match
.rm_eo
- suffix_match
.rm_so
== 1) {
666 switch (*(str
+ suffix_match
.rm_so
)) {
678 ERR("parse_human_size: invalid suffix");
684 *size
= base_size
<< shift
;
686 /* Check for overflow */
687 if ((*size
>> shift
) != base_size
) {
688 ERR("parse_size_suffix: oops, overflow detected.");
702 * fls: returns the position of the most significant bit.
703 * Returns 0 if no bit is set, else returns the position of the most
704 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
706 #if defined(__i386) || defined(__x86_64)
707 static inline unsigned int fls_u32(uint32_t x
)
715 : "=r" (r
) : "rm" (x
));
722 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
729 if (!(x
& 0xFFFF0000U
)) {
733 if (!(x
& 0xFF000000U
)) {
737 if (!(x
& 0xF0000000U
)) {
741 if (!(x
& 0xC0000000U
)) {
745 if (!(x
& 0x80000000U
)) {
754 * Return the minimum order for which x <= (1UL << order).
755 * Return -1 if x is 0.
758 int utils_get_count_order_u32(uint32_t x
)
764 return fls_u32(x
- 1);
768 * Obtain the value of LTTNG_HOME environment variable, if exists.
769 * Otherwise returns the value of HOME.
772 char *utils_get_home_dir(void)
775 val
= getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
779 return getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
783 * With the given format, fill dst with the time of len maximum siz.
785 * Return amount of bytes set in the buffer or else 0 on error.
788 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
797 /* Get date and time for session path */
799 timeinfo
= localtime(&rawtime
);
800 ret
= strftime(dst
, len
, format
, timeinfo
);
802 ERR("Unable to strftime with format %s at dst %p of len %lu", format
,
810 * Return the group ID matching name, else 0 if it cannot be found.
813 gid_t
utils_get_group_id(const char *name
)
817 grp
= getgrnam(name
);
819 static volatile int warn_once
;
822 WARN("No tracing group detected");