2 * Copyright (C) 2012 - David Goulet <dgoulet@efficios.com>
3 * Copyright (C) 2013 - Raphaƫl Beamonte <raphael.beamonte@gmail.com>
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License, version 2 only, as
7 * published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 * You should have received a copy of the GNU General Public License along with
15 * this program; if not, write to the Free Software Foundation, Inc., 51
16 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 #include <sys/types.h>
33 #include <common/common.h>
34 #include <common/runas.h>
40 * Return a partial realpath(3) of the path even if the full path does not
41 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
42 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
43 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
44 * point directory does not exist.
45 * In case resolved_path is NULL, the string returned was allocated in the
46 * function and thus need to be freed by the caller. The size argument allows
47 * to specify the size of the resolved_path argument if given, or the size to
51 char *utils_partial_realpath(const char *path
, char *resolved_path
, size_t size
)
53 char *cut_path
, *try_path
= NULL
, *try_path_prev
= NULL
;
54 const char *next
, *prev
, *end
;
62 * Identify the end of the path, we don't want to treat the
63 * last char if it is a '/', we will just keep it on the side
64 * to be added at the end, and return a value coherent with
65 * the path given as argument
67 end
= path
+ strlen(path
);
68 if (*(end
-1) == '/') {
72 /* Initiate the values of the pointers before looping */
75 /* Only to ensure try_path is not NULL to enter the while */
76 try_path
= (char *)next
;
78 /* Resolve the canonical path of the first part of the path */
79 while (try_path
!= NULL
&& next
!= end
) {
81 * If there is not any '/' left, we want to try with
84 next
= strpbrk(next
+ 1, "/");
89 /* Cut the part we will be trying to resolve */
90 cut_path
= strndup(path
, next
- path
);
92 /* Try to resolve this part */
93 try_path
= realpath((char *)cut_path
, NULL
);
94 if (try_path
== NULL
) {
96 * There was an error, we just want to be assured it
97 * is linked to an unexistent directory, if it's another
98 * reason, we spawn an error
102 /* Ignore the error */
105 PERROR("realpath (partial_realpath)");
110 /* Save the place we are before trying the next step */
112 try_path_prev
= try_path
;
116 /* Free the allocated memory */
120 /* Allocate memory for the resolved path if necessary */
121 if (resolved_path
== NULL
) {
122 resolved_path
= zmalloc(size
);
123 if (resolved_path
== NULL
) {
124 PERROR("zmalloc resolved path");
130 * If we were able to solve at least partially the path, we can concatenate
131 * what worked and what didn't work
133 if (try_path_prev
!= NULL
) {
134 /* If we risk to concatenate two '/', we remove one of them */
135 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
136 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
140 * Duplicate the memory used by prev in case resolved_path and
141 * path are pointers for the same memory space
143 cut_path
= strdup(prev
);
145 /* Concatenate the strings */
146 snprintf(resolved_path
, size
, "%s%s", try_path_prev
, cut_path
);
148 /* Free the allocated memory */
152 * Else, we just copy the path in our resolved_path to
156 strncpy(resolved_path
, path
, size
);
159 /* Then we return the 'partially' resolved path */
160 return resolved_path
;
168 * Make a full resolution of the given path even if it doesn't exist.
169 * This function uses the utils_partial_realpath function to resolve
170 * symlinks and relatives paths at the start of the string, and
171 * implements functionnalities to resolve the './' and '../' strings
172 * in the middle of a path. This function is only necessary because
173 * realpath(3) does not accept to resolve unexistent paths.
174 * The returned string was allocated in the function, it is thus of
175 * the responsibility of the caller to free this memory.
178 char *utils_expand_path(const char *path
)
180 char *next
, *previous
, *slash
, *start_path
, *absolute_path
= NULL
;
187 /* Allocate memory for the absolute_path */
188 absolute_path
= zmalloc(PATH_MAX
);
189 if (absolute_path
== NULL
) {
190 PERROR("zmalloc expand path");
195 * If the path is not already absolute nor explicitly relative,
196 * consider we're in the current directory
198 if (*path
!= '/' && strncmp(path
, "./", 2) != 0 &&
199 strncmp(path
, "../", 3) != 0) {
200 snprintf(absolute_path
, PATH_MAX
, "./%s", path
);
201 /* Else, we just copy the path */
203 strncpy(absolute_path
, path
, PATH_MAX
);
206 /* Resolve partially our path */
207 absolute_path
= utils_partial_realpath(absolute_path
,
208 absolute_path
, PATH_MAX
);
210 /* As long as we find '/./' in the working_path string */
211 while ((next
= strstr(absolute_path
, "/./"))) {
213 /* We prepare the start_path not containing it */
214 start_path
= strndup(absolute_path
, next
- absolute_path
);
216 /* And we concatenate it with the part after this string */
217 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 2);
222 /* As long as we find '/../' in the working_path string */
223 while ((next
= strstr(absolute_path
, "/../"))) {
224 /* We find the last level of directory */
225 previous
= absolute_path
;
226 while ((slash
= strpbrk(previous
, "/")) && slash
!= next
) {
227 previous
= slash
+ 1;
230 /* Then we prepare the start_path not containing it */
231 start_path
= strndup(absolute_path
, previous
- absolute_path
);
233 /* And we concatenate it with the part after the '/../' */
234 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 4);
236 /* We can free the memory used for the start path*/
239 /* Then we verify for symlinks using partial_realpath */
240 absolute_path
= utils_partial_realpath(absolute_path
,
241 absolute_path
, PATH_MAX
);
244 return absolute_path
;
252 * Create a pipe in dst.
255 int utils_create_pipe(int *dst
)
265 PERROR("create pipe");
272 * Create pipe and set CLOEXEC flag to both fd.
274 * Make sure the pipe opened by this function are closed at some point. Use
275 * utils_close_pipe().
278 int utils_create_pipe_cloexec(int *dst
)
286 ret
= utils_create_pipe(dst
);
291 for (i
= 0; i
< 2; i
++) {
292 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
294 PERROR("fcntl pipe cloexec");
304 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
306 * Make sure the pipe opened by this function are closed at some point. Use
307 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
308 * support OSes other than Linux 2.6.23+.
311 int utils_create_pipe_cloexec_nonblock(int *dst
)
319 ret
= utils_create_pipe(dst
);
324 for (i
= 0; i
< 2; i
++) {
325 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
327 PERROR("fcntl pipe cloexec");
331 * Note: we override any flag that could have been
332 * previously set on the fd.
334 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
336 PERROR("fcntl pipe nonblock");
346 * Close both read and write side of the pipe.
349 void utils_close_pipe(int *src
)
357 for (i
= 0; i
< 2; i
++) {
365 PERROR("close pipe");
371 * Create a new string using two strings range.
374 char *utils_strdupdelim(const char *begin
, const char *end
)
378 str
= zmalloc(end
- begin
+ 1);
380 PERROR("zmalloc strdupdelim");
384 memcpy(str
, begin
, end
- begin
);
385 str
[end
- begin
] = '\0';
392 * Set CLOEXEC flag to the give file descriptor.
395 int utils_set_fd_cloexec(int fd
)
404 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
406 PERROR("fcntl cloexec");
415 * Create pid file to the given path and filename.
418 int utils_create_pid_file(pid_t pid
, const char *filepath
)
425 fp
= fopen(filepath
, "w");
427 PERROR("open pid file %s", filepath
);
432 ret
= fprintf(fp
, "%d\n", pid
);
434 PERROR("fprintf pid file");
438 DBG("Pid %d written in file %s", pid
, filepath
);
444 * Recursively create directory using the given path and mode.
446 * On success, return 0 else a negative error code.
449 int utils_mkdir_recursive(const char *path
, mode_t mode
)
451 char *p
, tmp
[PATH_MAX
];
457 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
459 PERROR("snprintf mkdir");
464 if (tmp
[len
- 1] == '/') {
468 for (p
= tmp
+ 1; *p
; p
++) {
471 if (tmp
[strlen(tmp
) - 1] == '.' &&
472 tmp
[strlen(tmp
) - 2] == '.' &&
473 tmp
[strlen(tmp
) - 3] == '/') {
474 ERR("Using '/../' is not permitted in the trace path (%s)",
479 ret
= mkdir(tmp
, mode
);
481 if (errno
!= EEXIST
) {
482 PERROR("mkdir recursive");
491 ret
= mkdir(tmp
, mode
);
493 if (errno
!= EEXIST
) {
494 PERROR("mkdir recursive last piece");
506 * Create the stream tracefile on disk.
508 * Return 0 on success or else a negative value.
511 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
512 uint64_t count
, int uid
, int gid
, char *suffix
)
514 int ret
, out_fd
, flags
, mode
;
515 char full_path
[PATH_MAX
], *path_name_suffix
= NULL
, *path
;
521 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
522 path_name
, file_name
);
524 PERROR("snprintf create output file");
528 /* Setup extra string if suffix or/and a count is needed. */
529 if (size
> 0 && suffix
) {
530 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
531 } else if (size
> 0) {
532 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
534 ret
= asprintf(&extra
, "%s", suffix
);
537 PERROR("Allocating extra string to name");
542 * If we split the trace in multiple files, we have to add the count at the
543 * end of the tracefile name
546 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
548 PERROR("Allocating path name with extra string");
549 goto error_free_suffix
;
551 path
= path_name_suffix
;
556 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
557 /* Open with 660 mode */
558 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
560 if (uid
< 0 || gid
< 0) {
561 out_fd
= open(path
, flags
, mode
);
563 out_fd
= run_as_open(path
, flags
, mode
, uid
, gid
);
566 PERROR("open stream path %s", path
);
572 free(path_name_suffix
);
580 * Change the output tracefile according to the given size and count The
581 * new_count pointer is set during this operation.
583 * From the consumer, the stream lock MUST be held before calling this function
584 * because we are modifying the stream status.
586 * Return 0 on success or else a negative value.
589 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
590 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
600 PERROR("Closing tracefile");
605 *new_count
= (*new_count
+ 1) % count
;
610 ret
= utils_create_stream_file(path_name
, file_name
, size
, *new_count
,
625 * Prints the error message corresponding to a regex error code.
627 * @param errcode The error code.
628 * @param regex The regex object that produced the error code.
630 static void regex_print_error(int errcode
, regex_t
*regex
)
632 /* Get length of error message and allocate accordingly */
636 assert(regex
!= NULL
);
638 length
= regerror(errcode
, regex
, NULL
, 0);
640 ERR("regerror returned a length of 0");
644 buffer
= zmalloc(length
);
646 ERR("regex_print_error: zmalloc failed");
650 /* Get and print error message */
651 regerror(errcode
, regex
, buffer
, length
);
652 ERR("regex error: %s\n", buffer
);
658 * Parse a string that represents a size in human readable format. It
659 * supports decimal integers suffixed by 'k', 'M' or 'G'.
661 * The suffix multiply the integer by:
666 * @param str The string to parse.
667 * @param size Pointer to a size_t that will be filled with the
670 * @return 0 on success, -1 on failure.
673 int utils_parse_size_suffix(char *str
, uint64_t *size
)
677 const int nmatch
= 3;
678 regmatch_t suffix_match
, matches
[nmatch
];
679 unsigned long long base_size
;
687 ret
= regcomp(®ex
, "^\\(0x\\)\\{0,1\\}[0-9][0-9]*\\([kKMG]\\{0,1\\}\\)$", 0);
689 regex_print_error(ret
, ®ex
);
695 ret
= regexec(®ex
, str
, nmatch
, matches
, 0);
701 /* There is a match ! */
703 base_size
= strtoull(str
, NULL
, 0);
710 /* Check if there is a suffix */
711 suffix_match
= matches
[2];
712 if (suffix_match
.rm_eo
- suffix_match
.rm_so
== 1) {
713 switch (*(str
+ suffix_match
.rm_so
)) {
725 ERR("parse_human_size: invalid suffix");
731 *size
= base_size
<< shift
;
733 /* Check for overflow */
734 if ((*size
>> shift
) != base_size
) {
735 ERR("parse_size_suffix: oops, overflow detected.");
749 * fls: returns the position of the most significant bit.
750 * Returns 0 if no bit is set, else returns the position of the most
751 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
753 #if defined(__i386) || defined(__x86_64)
754 static inline unsigned int fls_u32(uint32_t x
)
762 : "=r" (r
) : "rm" (x
));
769 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
776 if (!(x
& 0xFFFF0000U
)) {
780 if (!(x
& 0xFF000000U
)) {
784 if (!(x
& 0xF0000000U
)) {
788 if (!(x
& 0xC0000000U
)) {
792 if (!(x
& 0x80000000U
)) {
801 * Return the minimum order for which x <= (1UL << order).
802 * Return -1 if x is 0.
805 int utils_get_count_order_u32(uint32_t x
)
811 return fls_u32(x
- 1);
815 * Obtain the value of LTTNG_HOME environment variable, if exists.
816 * Otherwise returns the value of HOME.
819 char *utils_get_home_dir(void)
822 val
= getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
826 return getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
830 * With the given format, fill dst with the time of len maximum siz.
832 * Return amount of bytes set in the buffer or else 0 on error.
835 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
844 /* Get date and time for session path */
846 timeinfo
= localtime(&rawtime
);
847 ret
= strftime(dst
, len
, format
, timeinfo
);
849 ERR("Unable to strftime with format %s at dst %p of len %lu", format
,
857 * Return the group ID matching name, else 0 if it cannot be found.
860 gid_t
utils_get_group_id(const char *name
)
864 grp
= getgrnam(name
);
866 static volatile int warn_once
;
869 WARN("No tracing group detected");