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 * Return a partial realpath(3) of the path even if the full path does not
40 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
41 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
42 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
43 * point directory does not exist.
44 * In case resolved_path is NULL, the string returned was allocated in the
45 * function and thus need to be freed by the caller. The size argument allows
46 * to specify the size of the resolved_path argument if given, or the size to
50 char *utils_partial_realpath(const char *path
, char *resolved_path
, size_t size
)
52 char *cut_path
, *try_path
= NULL
, *try_path_prev
= NULL
;
53 const char *next
, *prev
, *end
;
61 * Identify the end of the path, we don't want to treat the
62 * last char if it is a '/', we will just keep it on the side
63 * to be added at the end, and return a value coherent with
64 * the path given as argument
66 end
= path
+ strlen(path
);
67 if (*(end
-1) == '/') {
71 /* Initiate the values of the pointers before looping */
74 /* Only to ensure try_path is not NULL to enter the while */
75 try_path
= (char *)next
;
77 /* Resolve the canonical path of the first part of the path */
78 while (try_path
!= NULL
&& next
!= end
) {
80 * If there is not any '/' left, we want to try with
83 next
= strpbrk(next
+ 1, "/");
88 /* Cut the part we will be trying to resolve */
89 cut_path
= strndup(path
, next
- path
);
91 /* Try to resolve this part */
92 try_path
= realpath((char *)cut_path
, NULL
);
93 if (try_path
== NULL
) {
95 * There was an error, we just want to be assured it
96 * is linked to an unexistent directory, if it's another
97 * reason, we spawn an error
101 /* Ignore the error */
104 PERROR("realpath (partial_realpath)");
109 /* Save the place we are before trying the next step */
111 try_path_prev
= try_path
;
115 /* Free the allocated memory */
119 /* Allocate memory for the resolved path if necessary */
120 if (resolved_path
== NULL
) {
121 resolved_path
= zmalloc(size
);
122 if (resolved_path
== NULL
) {
123 PERROR("zmalloc resolved path");
129 * If we were able to solve at least partially the path, we can concatenate
130 * what worked and what didn't work
132 if (try_path_prev
!= NULL
) {
133 /* If we risk to concatenate two '/', we remove one of them */
134 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
135 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
139 * Duplicate the memory used by prev in case resolved_path and
140 * path are pointers for the same memory space
142 cut_path
= strdup(prev
);
144 /* Concatenate the strings */
145 snprintf(resolved_path
, size
, "%s%s", try_path_prev
, cut_path
);
147 /* Free the allocated memory */
151 * Else, we just copy the path in our resolved_path to
155 strncpy(resolved_path
, path
, size
);
158 /* Then we return the 'partially' resolved path */
159 return resolved_path
;
167 * Resolve the './' and '../' strings in the middle of a path using
168 * our very own way to do it, so that it works even if the directory
172 char *utils_resolve_relative(const char *path
)
174 char *next
, *previous
, *slash
, *start_path
, *absolute_path
= NULL
;
181 /* Allocate memory for the absolute path */
182 absolute_path
= zmalloc(PATH_MAX
);
183 if (absolute_path
== NULL
) {
184 PERROR("zmalloc expand path");
188 /* Copy the path in the absolute path */
189 strncpy(absolute_path
, path
, PATH_MAX
);
191 /* As long as we find '/./' in the path string */
192 while ((next
= strstr(absolute_path
, "/./"))) {
194 /* We prepare the start_path not containing it */
195 start_path
= strndup(absolute_path
, next
- absolute_path
);
197 /* And we concatenate it with the part after this string */
198 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 2);
203 /* As long as we find '/../' in the path string */
204 while ((next
= strstr(absolute_path
, "/../"))) {
205 /* If the path starts with '/../', there's a problem */
206 if (next
== absolute_path
) {
207 ERR("%s: Path cannot be resolved", path
);
211 /* We find the last level of directory */
212 previous
= absolute_path
;
213 while ((slash
= strpbrk(previous
+ 1, "/")) && slash
!= next
) {
217 /* Then we prepare the start_path not containing it */
218 start_path
= strndup(absolute_path
, previous
- absolute_path
);
220 /* And we concatenate it with the part after the '/../' */
221 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 3);
226 return absolute_path
;
235 * Return the realpath(3) of the path even if the last directory token does not
236 * exist. For example, with /tmp/test1/test2, if test2/ does not exist but the
237 * /tmp/test1 does, the real path is returned. In normal time, realpath(3)
238 * fails if the end point directory does not exist.
241 char *utils_expand_path(const char *path
)
243 const char *end_path
= NULL
;
244 char *next
, *cut_path
= NULL
, *expanded_path
= NULL
;
251 /* Allocate memory for the expanded path */
252 expanded_path
= zmalloc(PATH_MAX
);
253 if (expanded_path
== NULL
) {
254 PERROR("zmalloc expand path");
258 /* If given path is already absolute */
260 strncpy(expanded_path
, path
, PATH_MAX
);
261 /* Else, we have some work to do */
263 /* Pointer to the last char of the path */
264 const char *last_char
= path
+ strlen(path
) - 1;
268 /* Split part that will be resolved by realpath (relative path from
269 * current directory using ./ or ../ only) and part that could not
272 while ((next
= strpbrk(end_path
, "/")) && (next
!= last_char
)) {
274 if (strncmp(end_path
, "./", 2) != 0 &&
275 strncmp(end_path
, "../", 3) != 0) {
280 /* If this is the end of the string, and we still can resolve it */
281 if (strncmp(end_path
, "..\0", 3) == 0 ||
282 strncmp(end_path
, ".\0", 2) == 0) {
283 end_path
+= strlen(end_path
);
286 /* If the end part is the whole path, we are in the current dir */
287 if (end_path
== path
) {
288 cut_path
= strdup(".");
289 /* Else, cut the resolvable part from original path */
291 cut_path
= strndup(path
, end_path
- path
);
294 /* Resolve the canonical path of the first part of the path */
295 expanded_path
= realpath((char *)cut_path
, expanded_path
);
296 if (expanded_path
== NULL
) {
299 ERR("%s: No such file or directory", cut_path
);
302 PERROR("realpath utils expand path");
308 /* Add end part to expanded path if not empty */
309 if (*end_path
!= 0) {
310 strncat(expanded_path
, "/", PATH_MAX
- strlen(expanded_path
) - 1);
311 strncat(expanded_path
, end_path
,
312 PATH_MAX
- strlen(expanded_path
) - 1);
316 /* Resolve the internal './' and '../' strings */
317 next
= utils_resolve_relative(expanded_path
);
333 * Create a pipe in dst.
336 int utils_create_pipe(int *dst
)
346 PERROR("create pipe");
353 * Create pipe and set CLOEXEC flag to both fd.
355 * Make sure the pipe opened by this function are closed at some point. Use
356 * utils_close_pipe().
359 int utils_create_pipe_cloexec(int *dst
)
367 ret
= utils_create_pipe(dst
);
372 for (i
= 0; i
< 2; i
++) {
373 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
375 PERROR("fcntl pipe cloexec");
385 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
387 * Make sure the pipe opened by this function are closed at some point. Use
388 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
389 * support OSes other than Linux 2.6.23+.
392 int utils_create_pipe_cloexec_nonblock(int *dst
)
400 ret
= utils_create_pipe(dst
);
405 for (i
= 0; i
< 2; i
++) {
406 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
408 PERROR("fcntl pipe cloexec");
412 * Note: we override any flag that could have been
413 * previously set on the fd.
415 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
417 PERROR("fcntl pipe nonblock");
427 * Close both read and write side of the pipe.
430 void utils_close_pipe(int *src
)
438 for (i
= 0; i
< 2; i
++) {
446 PERROR("close pipe");
452 * Create a new string using two strings range.
455 char *utils_strdupdelim(const char *begin
, const char *end
)
459 str
= zmalloc(end
- begin
+ 1);
461 PERROR("zmalloc strdupdelim");
465 memcpy(str
, begin
, end
- begin
);
466 str
[end
- begin
] = '\0';
473 * Set CLOEXEC flag to the give file descriptor.
476 int utils_set_fd_cloexec(int fd
)
485 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
487 PERROR("fcntl cloexec");
496 * Create pid file to the given path and filename.
499 int utils_create_pid_file(pid_t pid
, const char *filepath
)
506 fp
= fopen(filepath
, "w");
508 PERROR("open pid file %s", filepath
);
513 ret
= fprintf(fp
, "%d\n", pid
);
515 PERROR("fprintf pid file");
519 DBG("Pid %d written in file %s", pid
, filepath
);
525 * Recursively create directory using the given path and mode.
527 * On success, return 0 else a negative error code.
530 int utils_mkdir_recursive(const char *path
, mode_t mode
)
532 char *p
, tmp
[PATH_MAX
];
538 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
540 PERROR("snprintf mkdir");
545 if (tmp
[len
- 1] == '/') {
549 for (p
= tmp
+ 1; *p
; p
++) {
552 if (tmp
[strlen(tmp
) - 1] == '.' &&
553 tmp
[strlen(tmp
) - 2] == '.' &&
554 tmp
[strlen(tmp
) - 3] == '/') {
555 ERR("Using '/../' is not permitted in the trace path (%s)",
560 ret
= mkdir(tmp
, mode
);
562 if (errno
!= EEXIST
) {
563 PERROR("mkdir recursive");
572 ret
= mkdir(tmp
, mode
);
574 if (errno
!= EEXIST
) {
575 PERROR("mkdir recursive last piece");
587 * Create the stream tracefile on disk.
589 * Return 0 on success or else a negative value.
592 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
593 uint64_t count
, int uid
, int gid
, char *suffix
)
595 int ret
, out_fd
, flags
, mode
;
596 char full_path
[PATH_MAX
], *path_name_suffix
= NULL
, *path
;
602 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
603 path_name
, file_name
);
605 PERROR("snprintf create output file");
609 /* Setup extra string if suffix or/and a count is needed. */
610 if (size
> 0 && suffix
) {
611 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
612 } else if (size
> 0) {
613 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
615 ret
= asprintf(&extra
, "%s", suffix
);
618 PERROR("Allocating extra string to name");
623 * If we split the trace in multiple files, we have to add the count at the
624 * end of the tracefile name
627 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
629 PERROR("Allocating path name with extra string");
630 goto error_free_suffix
;
632 path
= path_name_suffix
;
637 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
638 /* Open with 660 mode */
639 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
641 if (uid
< 0 || gid
< 0) {
642 out_fd
= open(path
, flags
, mode
);
644 out_fd
= run_as_open(path
, flags
, mode
, uid
, gid
);
647 PERROR("open stream path %s", path
);
653 free(path_name_suffix
);
661 * Change the output tracefile according to the given size and count The
662 * new_count pointer is set during this operation.
664 * From the consumer, the stream lock MUST be held before calling this function
665 * because we are modifying the stream status.
667 * Return 0 on success or else a negative value.
670 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
671 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
681 PERROR("Closing tracefile");
686 *new_count
= (*new_count
+ 1) % count
;
691 ret
= utils_create_stream_file(path_name
, file_name
, size
, *new_count
,
706 * Prints the error message corresponding to a regex error code.
708 * @param errcode The error code.
709 * @param regex The regex object that produced the error code.
711 static void regex_print_error(int errcode
, regex_t
*regex
)
713 /* Get length of error message and allocate accordingly */
717 assert(regex
!= NULL
);
719 length
= regerror(errcode
, regex
, NULL
, 0);
721 ERR("regerror returned a length of 0");
725 buffer
= zmalloc(length
);
727 ERR("regex_print_error: zmalloc failed");
731 /* Get and print error message */
732 regerror(errcode
, regex
, buffer
, length
);
733 ERR("regex error: %s\n", buffer
);
739 * Parse a string that represents a size in human readable format. It
740 * supports decimal integers suffixed by 'k', 'M' or 'G'.
742 * The suffix multiply the integer by:
747 * @param str The string to parse.
748 * @param size Pointer to a size_t that will be filled with the
751 * @return 0 on success, -1 on failure.
754 int utils_parse_size_suffix(char *str
, uint64_t *size
)
758 const int nmatch
= 3;
759 regmatch_t suffix_match
, matches
[nmatch
];
760 unsigned long long base_size
;
768 ret
= regcomp(®ex
, "^\\(0x\\)\\{0,1\\}[0-9][0-9]*\\([kKMG]\\{0,1\\}\\)$", 0);
770 regex_print_error(ret
, ®ex
);
776 ret
= regexec(®ex
, str
, nmatch
, matches
, 0);
782 /* There is a match ! */
784 base_size
= strtoull(str
, NULL
, 0);
791 /* Check if there is a suffix */
792 suffix_match
= matches
[2];
793 if (suffix_match
.rm_eo
- suffix_match
.rm_so
== 1) {
794 switch (*(str
+ suffix_match
.rm_so
)) {
806 ERR("parse_human_size: invalid suffix");
812 *size
= base_size
<< shift
;
814 /* Check for overflow */
815 if ((*size
>> shift
) != base_size
) {
816 ERR("parse_size_suffix: oops, overflow detected.");
830 * fls: returns the position of the most significant bit.
831 * Returns 0 if no bit is set, else returns the position of the most
832 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
834 #if defined(__i386) || defined(__x86_64)
835 static inline unsigned int fls_u32(uint32_t x
)
843 : "=r" (r
) : "rm" (x
));
850 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
857 if (!(x
& 0xFFFF0000U
)) {
861 if (!(x
& 0xFF000000U
)) {
865 if (!(x
& 0xF0000000U
)) {
869 if (!(x
& 0xC0000000U
)) {
873 if (!(x
& 0x80000000U
)) {
882 * Return the minimum order for which x <= (1UL << order).
883 * Return -1 if x is 0.
886 int utils_get_count_order_u32(uint32_t x
)
892 return fls_u32(x
- 1);
896 * Obtain the value of LTTNG_HOME environment variable, if exists.
897 * Otherwise returns the value of HOME.
900 char *utils_get_home_dir(void)
903 val
= getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
907 return getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
911 * With the given format, fill dst with the time of len maximum siz.
913 * Return amount of bytes set in the buffer or else 0 on error.
916 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
925 /* Get date and time for session path */
927 timeinfo
= localtime(&rawtime
);
928 ret
= strftime(dst
, len
, format
, timeinfo
);
930 ERR("Unable to strftime with format %s at dst %p of len %lu", format
,
938 * Return the group ID matching name, else 0 if it cannot be found.
941 gid_t
utils_get_group_id(const char *name
)
945 grp
= getgrnam(name
);
947 static volatile int warn_once
;
950 WARN("No tracing group detected");