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 * Make a full resolution of the given path even if it doesn't exist.
168 * This function uses the utils_partial_realpath function to resolve
169 * symlinks and relatives paths at the start of the string, and
170 * implements functionnalities to resolve the './' and '../' strings
171 * in the middle of a path. This function is only necessary because
172 * realpath(3) does not accept to resolve unexistent paths.
173 * The returned string was allocated in the function, it is thus of
174 * the responsibility of the caller to free this memory.
177 char *utils_expand_path(const char *path
)
179 char *next
, *previous
, *slash
, *start_path
, *absolute_path
= NULL
;
186 /* Allocate memory for the absolute_path */
187 absolute_path
= zmalloc(PATH_MAX
);
188 if (absolute_path
== NULL
) {
189 PERROR("zmalloc expand path");
194 * If the path is not already absolute nor explicitly relative,
195 * consider we're in the current directory
197 if (*path
!= '/' && strncmp(path
, "./", 2) != 0 &&
198 strncmp(path
, "../", 3) != 0) {
199 snprintf(absolute_path
, PATH_MAX
, "./%s", path
);
200 /* Else, we just copy the path */
202 strncpy(absolute_path
, path
, PATH_MAX
);
205 /* Resolve partially our path */
206 absolute_path
= utils_partial_realpath(absolute_path
,
207 absolute_path
, PATH_MAX
);
209 /* As long as we find '/./' in the working_path string */
210 while ((next
= strstr(absolute_path
, "/./"))) {
212 /* We prepare the start_path not containing it */
213 start_path
= strndup(absolute_path
, next
- absolute_path
);
215 /* And we concatenate it with the part after this string */
216 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 2);
221 /* As long as we find '/../' in the working_path string */
222 while ((next
= strstr(absolute_path
, "/../"))) {
223 /* We find the last level of directory */
224 previous
= absolute_path
;
225 while ((slash
= strpbrk(previous
, "/")) && slash
!= next
) {
226 previous
= slash
+ 1;
229 /* Then we prepare the start_path not containing it */
230 start_path
= strndup(absolute_path
, previous
- absolute_path
);
232 /* And we concatenate it with the part after the '/../' */
233 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 4);
235 /* We can free the memory used for the start path*/
238 /* Then we verify for symlinks using partial_realpath */
239 absolute_path
= utils_partial_realpath(absolute_path
,
240 absolute_path
, PATH_MAX
);
243 return absolute_path
;
251 * Create a pipe in dst.
254 int utils_create_pipe(int *dst
)
264 PERROR("create pipe");
271 * Create pipe and set CLOEXEC flag to both fd.
273 * Make sure the pipe opened by this function are closed at some point. Use
274 * utils_close_pipe().
277 int utils_create_pipe_cloexec(int *dst
)
285 ret
= utils_create_pipe(dst
);
290 for (i
= 0; i
< 2; i
++) {
291 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
293 PERROR("fcntl pipe cloexec");
303 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
305 * Make sure the pipe opened by this function are closed at some point. Use
306 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
307 * support OSes other than Linux 2.6.23+.
310 int utils_create_pipe_cloexec_nonblock(int *dst
)
318 ret
= utils_create_pipe(dst
);
323 for (i
= 0; i
< 2; i
++) {
324 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
326 PERROR("fcntl pipe cloexec");
330 * Note: we override any flag that could have been
331 * previously set on the fd.
333 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
335 PERROR("fcntl pipe nonblock");
345 * Close both read and write side of the pipe.
348 void utils_close_pipe(int *src
)
356 for (i
= 0; i
< 2; i
++) {
364 PERROR("close pipe");
370 * Create a new string using two strings range.
373 char *utils_strdupdelim(const char *begin
, const char *end
)
377 str
= zmalloc(end
- begin
+ 1);
379 PERROR("zmalloc strdupdelim");
383 memcpy(str
, begin
, end
- begin
);
384 str
[end
- begin
] = '\0';
391 * Set CLOEXEC flag to the give file descriptor.
394 int utils_set_fd_cloexec(int fd
)
403 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
405 PERROR("fcntl cloexec");
414 * Create pid file to the given path and filename.
417 int utils_create_pid_file(pid_t pid
, const char *filepath
)
424 fp
= fopen(filepath
, "w");
426 PERROR("open pid file %s", filepath
);
431 ret
= fprintf(fp
, "%d\n", pid
);
433 PERROR("fprintf pid file");
437 DBG("Pid %d written in file %s", pid
, filepath
);
443 * Recursively create directory using the given path and mode.
445 * On success, return 0 else a negative error code.
448 int utils_mkdir_recursive(const char *path
, mode_t mode
)
450 char *p
, tmp
[PATH_MAX
];
456 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
458 PERROR("snprintf mkdir");
463 if (tmp
[len
- 1] == '/') {
467 for (p
= tmp
+ 1; *p
; p
++) {
470 if (tmp
[strlen(tmp
) - 1] == '.' &&
471 tmp
[strlen(tmp
) - 2] == '.' &&
472 tmp
[strlen(tmp
) - 3] == '/') {
473 ERR("Using '/../' is not permitted in the trace path (%s)",
478 ret
= mkdir(tmp
, mode
);
480 if (errno
!= EEXIST
) {
481 PERROR("mkdir recursive");
490 ret
= mkdir(tmp
, mode
);
492 if (errno
!= EEXIST
) {
493 PERROR("mkdir recursive last piece");
505 * Create the stream tracefile on disk.
507 * Return 0 on success or else a negative value.
510 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
511 uint64_t count
, int uid
, int gid
, char *suffix
)
513 int ret
, out_fd
, flags
, mode
;
514 char full_path
[PATH_MAX
], *path_name_suffix
= NULL
, *path
;
520 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
521 path_name
, file_name
);
523 PERROR("snprintf create output file");
527 /* Setup extra string if suffix or/and a count is needed. */
528 if (size
> 0 && suffix
) {
529 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
530 } else if (size
> 0) {
531 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
533 ret
= asprintf(&extra
, "%s", suffix
);
536 PERROR("Allocating extra string to name");
541 * If we split the trace in multiple files, we have to add the count at the
542 * end of the tracefile name
545 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
547 PERROR("Allocating path name with extra string");
548 goto error_free_suffix
;
550 path
= path_name_suffix
;
555 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
556 /* Open with 660 mode */
557 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
559 if (uid
< 0 || gid
< 0) {
560 out_fd
= open(path
, flags
, mode
);
562 out_fd
= run_as_open(path
, flags
, mode
, uid
, gid
);
565 PERROR("open stream path %s", path
);
571 free(path_name_suffix
);
579 * Change the output tracefile according to the given size and count The
580 * new_count pointer is set during this operation.
582 * From the consumer, the stream lock MUST be held before calling this function
583 * because we are modifying the stream status.
585 * Return 0 on success or else a negative value.
588 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
589 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
599 PERROR("Closing tracefile");
604 *new_count
= (*new_count
+ 1) % count
;
609 ret
= utils_create_stream_file(path_name
, file_name
, size
, *new_count
,
624 * Prints the error message corresponding to a regex error code.
626 * @param errcode The error code.
627 * @param regex The regex object that produced the error code.
629 static void regex_print_error(int errcode
, regex_t
*regex
)
631 /* Get length of error message and allocate accordingly */
635 assert(regex
!= NULL
);
637 length
= regerror(errcode
, regex
, NULL
, 0);
639 ERR("regerror returned a length of 0");
643 buffer
= zmalloc(length
);
645 ERR("regex_print_error: zmalloc failed");
649 /* Get and print error message */
650 regerror(errcode
, regex
, buffer
, length
);
651 ERR("regex error: %s\n", buffer
);
657 * Parse a string that represents a size in human readable format. It
658 * supports decimal integers suffixed by 'k', 'M' or 'G'.
660 * The suffix multiply the integer by:
665 * @param str The string to parse.
666 * @param size Pointer to a size_t that will be filled with the
669 * @return 0 on success, -1 on failure.
672 int utils_parse_size_suffix(char *str
, uint64_t *size
)
676 const int nmatch
= 3;
677 regmatch_t suffix_match
, matches
[nmatch
];
678 unsigned long long base_size
;
686 ret
= regcomp(®ex
, "^\\(0x\\)\\{0,1\\}[0-9][0-9]*\\([kKMG]\\{0,1\\}\\)$", 0);
688 regex_print_error(ret
, ®ex
);
694 ret
= regexec(®ex
, str
, nmatch
, matches
, 0);
700 /* There is a match ! */
702 base_size
= strtoull(str
, NULL
, 0);
709 /* Check if there is a suffix */
710 suffix_match
= matches
[2];
711 if (suffix_match
.rm_eo
- suffix_match
.rm_so
== 1) {
712 switch (*(str
+ suffix_match
.rm_so
)) {
724 ERR("parse_human_size: invalid suffix");
730 *size
= base_size
<< shift
;
732 /* Check for overflow */
733 if ((*size
>> shift
) != base_size
) {
734 ERR("parse_size_suffix: oops, overflow detected.");
748 * fls: returns the position of the most significant bit.
749 * Returns 0 if no bit is set, else returns the position of the most
750 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
752 #if defined(__i386) || defined(__x86_64)
753 static inline unsigned int fls_u32(uint32_t x
)
761 : "=r" (r
) : "rm" (x
));
768 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
775 if (!(x
& 0xFFFF0000U
)) {
779 if (!(x
& 0xFF000000U
)) {
783 if (!(x
& 0xF0000000U
)) {
787 if (!(x
& 0xC0000000U
)) {
791 if (!(x
& 0x80000000U
)) {
800 * Return the minimum order for which x <= (1UL << order).
801 * Return -1 if x is 0.
804 int utils_get_count_order_u32(uint32_t x
)
810 return fls_u32(x
- 1);
814 * Obtain the value of LTTNG_HOME environment variable, if exists.
815 * Otherwise returns the value of HOME.
818 char *utils_get_home_dir(void)
821 val
= getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
825 return getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
829 * With the given format, fill dst with the time of len maximum siz.
831 * Return amount of bytes set in the buffer or else 0 on error.
834 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
843 /* Get date and time for session path */
845 timeinfo
= localtime(&rawtime
);
846 ret
= strftime(dst
, len
, format
, timeinfo
);
848 ERR("Unable to strftime with format %s at dst %p of len %lu", format
,
856 * Return the group ID matching name, else 0 if it cannot be found.
859 gid_t
utils_get_group_id(const char *name
)
863 grp
= getgrnam(name
);
865 static volatile int warn_once
;
868 WARN("No tracing group detected");