2 * Copyright (C) 2012 - David Goulet <dgoulet@efficios.com>
3 * Copyright (C) 2013 - Raphaël Beamonte <raphael.beamonte@gmail.com>
4 * Copyright (C) 2013 - Jérémie Galarneau <jeremie.galarneau@efficios.com>
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License, version 2 only, as
8 * published by the Free Software Foundation.
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 * You should have received a copy of the GNU General Public License along with
16 * this program; if not, write to the Free Software Foundation, Inc., 51
17 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
28 #include <sys/types.h>
34 #include <common/common.h>
35 #include <common/runas.h>
41 * Return a partial realpath(3) of the path even if the full path does not
42 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
43 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
44 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
45 * point directory does not exist.
46 * In case resolved_path is NULL, the string returned was allocated in the
47 * function and thus need to be freed by the caller. The size argument allows
48 * to specify the size of the resolved_path argument if given, or the size to
52 char *utils_partial_realpath(const char *path
, char *resolved_path
, size_t size
)
54 char *cut_path
, *try_path
= NULL
, *try_path_prev
= NULL
;
55 const char *next
, *prev
, *end
;
63 * Identify the end of the path, we don't want to treat the
64 * last char if it is a '/', we will just keep it on the side
65 * to be added at the end, and return a value coherent with
66 * the path given as argument
68 end
= path
+ strlen(path
);
69 if (*(end
-1) == '/') {
73 /* Initiate the values of the pointers before looping */
76 /* Only to ensure try_path is not NULL to enter the while */
77 try_path
= (char *)next
;
79 /* Resolve the canonical path of the first part of the path */
80 while (try_path
!= NULL
&& next
!= end
) {
82 * If there is not any '/' left, we want to try with
85 next
= strpbrk(next
+ 1, "/");
90 /* Cut the part we will be trying to resolve */
91 cut_path
= strndup(path
, next
- path
);
93 /* Try to resolve this part */
94 try_path
= realpath((char *)cut_path
, NULL
);
95 if (try_path
== NULL
) {
97 * There was an error, we just want to be assured it
98 * is linked to an unexistent directory, if it's another
99 * reason, we spawn an error
103 /* Ignore the error */
106 PERROR("realpath (partial_realpath)");
111 /* Save the place we are before trying the next step */
113 try_path_prev
= try_path
;
117 /* Free the allocated memory */
121 /* Allocate memory for the resolved path if necessary */
122 if (resolved_path
== NULL
) {
123 resolved_path
= zmalloc(size
);
124 if (resolved_path
== NULL
) {
125 PERROR("zmalloc resolved path");
131 * If we were able to solve at least partially the path, we can concatenate
132 * what worked and what didn't work
134 if (try_path_prev
!= NULL
) {
135 /* If we risk to concatenate two '/', we remove one of them */
136 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
137 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
141 * Duplicate the memory used by prev in case resolved_path and
142 * path are pointers for the same memory space
144 cut_path
= strdup(prev
);
146 /* Concatenate the strings */
147 snprintf(resolved_path
, size
, "%s%s", try_path_prev
, cut_path
);
149 /* Free the allocated memory */
153 * Else, we just copy the path in our resolved_path to
157 strncpy(resolved_path
, path
, size
);
160 /* Then we return the 'partially' resolved path */
161 return resolved_path
;
169 * Make a full resolution of the given path even if it doesn't exist.
170 * This function uses the utils_partial_realpath function to resolve
171 * symlinks and relatives paths at the start of the string, and
172 * implements functionnalities to resolve the './' and '../' strings
173 * in the middle of a path. This function is only necessary because
174 * realpath(3) does not accept to resolve unexistent paths.
175 * The returned string was allocated in the function, it is thus of
176 * the responsibility of the caller to free this memory.
179 char *utils_expand_path(const char *path
)
181 char *next
, *previous
, *slash
, *start_path
, *absolute_path
= NULL
;
183 int is_dot
, is_dotdot
;
190 /* Allocate memory for the absolute_path */
191 absolute_path
= zmalloc(PATH_MAX
);
192 if (absolute_path
== NULL
) {
193 PERROR("zmalloc expand path");
198 * If the path is not already absolute nor explicitly relative,
199 * consider we're in the current directory
201 if (*path
!= '/' && strncmp(path
, "./", 2) != 0 &&
202 strncmp(path
, "../", 3) != 0) {
203 snprintf(absolute_path
, PATH_MAX
, "./%s", path
);
204 /* Else, we just copy the path */
206 strncpy(absolute_path
, path
, PATH_MAX
);
209 /* Resolve partially our path */
210 absolute_path
= utils_partial_realpath(absolute_path
,
211 absolute_path
, PATH_MAX
);
213 /* As long as we find '/./' in the working_path string */
214 while ((next
= strstr(absolute_path
, "/./"))) {
216 /* We prepare the start_path not containing it */
217 start_path
= strndup(absolute_path
, next
- absolute_path
);
219 /* And we concatenate it with the part after this string */
220 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 2);
225 /* As long as we find '/../' in the working_path string */
226 while ((next
= strstr(absolute_path
, "/../"))) {
227 /* We find the last level of directory */
228 previous
= absolute_path
;
229 while ((slash
= strpbrk(previous
, "/")) && slash
!= next
) {
230 previous
= slash
+ 1;
233 /* Then we prepare the start_path not containing it */
234 start_path
= strndup(absolute_path
, previous
- absolute_path
);
236 /* And we concatenate it with the part after the '/../' */
237 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 4);
239 /* We can free the memory used for the start path*/
242 /* Then we verify for symlinks using partial_realpath */
243 absolute_path
= utils_partial_realpath(absolute_path
,
244 absolute_path
, PATH_MAX
);
247 /* Identify the last token */
248 last_token
= strrchr(absolute_path
, '/');
250 /* Verify that this token is not a relative path */
251 is_dotdot
= (strcmp(last_token
, "/..") == 0);
252 is_dot
= (strcmp(last_token
, "/.") == 0);
254 /* If it is, take action */
255 if (is_dot
|| is_dotdot
) {
256 /* For both, remove this token */
259 /* If it was a reference to parent directory, go back one more time */
261 last_token
= strrchr(absolute_path
, '/');
263 /* If there was only one level left, we keep the first '/' */
264 if (last_token
== absolute_path
) {
272 return absolute_path
;
280 * Create a pipe in dst.
283 int utils_create_pipe(int *dst
)
293 PERROR("create pipe");
300 * Create pipe and set CLOEXEC flag to both fd.
302 * Make sure the pipe opened by this function are closed at some point. Use
303 * utils_close_pipe().
306 int utils_create_pipe_cloexec(int *dst
)
314 ret
= utils_create_pipe(dst
);
319 for (i
= 0; i
< 2; i
++) {
320 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
322 PERROR("fcntl pipe cloexec");
332 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
334 * Make sure the pipe opened by this function are closed at some point. Use
335 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
336 * support OSes other than Linux 2.6.23+.
339 int utils_create_pipe_cloexec_nonblock(int *dst
)
347 ret
= utils_create_pipe(dst
);
352 for (i
= 0; i
< 2; i
++) {
353 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
355 PERROR("fcntl pipe cloexec");
359 * Note: we override any flag that could have been
360 * previously set on the fd.
362 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
364 PERROR("fcntl pipe nonblock");
374 * Close both read and write side of the pipe.
377 void utils_close_pipe(int *src
)
385 for (i
= 0; i
< 2; i
++) {
393 PERROR("close pipe");
399 * Create a new string using two strings range.
402 char *utils_strdupdelim(const char *begin
, const char *end
)
406 str
= zmalloc(end
- begin
+ 1);
408 PERROR("zmalloc strdupdelim");
412 memcpy(str
, begin
, end
- begin
);
413 str
[end
- begin
] = '\0';
420 * Set CLOEXEC flag to the give file descriptor.
423 int utils_set_fd_cloexec(int fd
)
432 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
434 PERROR("fcntl cloexec");
443 * Create pid file to the given path and filename.
446 int utils_create_pid_file(pid_t pid
, const char *filepath
)
453 fp
= fopen(filepath
, "w");
455 PERROR("open pid file %s", filepath
);
460 ret
= fprintf(fp
, "%d\n", pid
);
462 PERROR("fprintf pid file");
466 DBG("Pid %d written in file %s", pid
, filepath
);
472 * Recursively create directory using the given path and mode.
474 * On success, return 0 else a negative error code.
477 int utils_mkdir_recursive(const char *path
, mode_t mode
)
479 char *p
, tmp
[PATH_MAX
];
485 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
487 PERROR("snprintf mkdir");
492 if (tmp
[len
- 1] == '/') {
496 for (p
= tmp
+ 1; *p
; p
++) {
499 if (tmp
[strlen(tmp
) - 1] == '.' &&
500 tmp
[strlen(tmp
) - 2] == '.' &&
501 tmp
[strlen(tmp
) - 3] == '/') {
502 ERR("Using '/../' is not permitted in the trace path (%s)",
507 ret
= mkdir(tmp
, mode
);
509 if (errno
!= EEXIST
) {
510 PERROR("mkdir recursive");
519 ret
= mkdir(tmp
, mode
);
521 if (errno
!= EEXIST
) {
522 PERROR("mkdir recursive last piece");
534 * Create the stream tracefile on disk.
536 * Return 0 on success or else a negative value.
539 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
540 uint64_t count
, int uid
, int gid
, char *suffix
)
542 int ret
, out_fd
, flags
, mode
;
543 char full_path
[PATH_MAX
], *path_name_suffix
= NULL
, *path
;
549 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
550 path_name
, file_name
);
552 PERROR("snprintf create output file");
556 /* Setup extra string if suffix or/and a count is needed. */
557 if (size
> 0 && suffix
) {
558 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
559 } else if (size
> 0) {
560 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
562 ret
= asprintf(&extra
, "%s", suffix
);
565 PERROR("Allocating extra string to name");
570 * If we split the trace in multiple files, we have to add the count at the
571 * end of the tracefile name
574 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
576 PERROR("Allocating path name with extra string");
577 goto error_free_suffix
;
579 path
= path_name_suffix
;
584 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
585 /* Open with 660 mode */
586 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
588 if (uid
< 0 || gid
< 0) {
589 out_fd
= open(path
, flags
, mode
);
591 out_fd
= run_as_open(path
, flags
, mode
, uid
, gid
);
594 PERROR("open stream path %s", path
);
600 free(path_name_suffix
);
608 * Change the output tracefile according to the given size and count The
609 * new_count pointer is set during this operation.
611 * From the consumer, the stream lock MUST be held before calling this function
612 * because we are modifying the stream status.
614 * Return 0 on success or else a negative value.
617 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
618 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
628 PERROR("Closing tracefile");
633 *new_count
= (*new_count
+ 1) % count
;
638 ret
= utils_create_stream_file(path_name
, file_name
, size
, *new_count
,
653 * Prints the error message corresponding to a regex error code.
655 * @param errcode The error code.
656 * @param regex The regex object that produced the error code.
658 static void regex_print_error(int errcode
, regex_t
*regex
)
660 /* Get length of error message and allocate accordingly */
664 assert(regex
!= NULL
);
666 length
= regerror(errcode
, regex
, NULL
, 0);
668 ERR("regerror returned a length of 0");
672 buffer
= zmalloc(length
);
674 ERR("regex_print_error: zmalloc failed");
678 /* Get and print error message */
679 regerror(errcode
, regex
, buffer
, length
);
680 ERR("regex error: %s\n", buffer
);
686 * Parse a string that represents a size in human readable format. It
687 * supports decimal integers suffixed by 'k', 'M' or 'G'.
689 * The suffix multiply the integer by:
694 * @param str The string to parse.
695 * @param size Pointer to a size_t that will be filled with the
698 * @return 0 on success, -1 on failure.
701 int utils_parse_size_suffix(char *str
, uint64_t *size
)
705 const int nmatch
= 3;
706 regmatch_t suffix_match
, matches
[nmatch
];
707 unsigned long long base_size
;
715 ret
= regcomp(®ex
, "^\\(0x\\)\\{0,1\\}[0-9][0-9]*\\([kKMG]\\{0,1\\}\\)$", 0);
717 regex_print_error(ret
, ®ex
);
723 ret
= regexec(®ex
, str
, nmatch
, matches
, 0);
729 /* There is a match ! */
731 base_size
= strtoull(str
, NULL
, 0);
738 /* Check if there is a suffix */
739 suffix_match
= matches
[2];
740 if (suffix_match
.rm_eo
- suffix_match
.rm_so
== 1) {
741 switch (*(str
+ suffix_match
.rm_so
)) {
753 ERR("parse_human_size: invalid suffix");
759 *size
= base_size
<< shift
;
761 /* Check for overflow */
762 if ((*size
>> shift
) != base_size
) {
763 ERR("parse_size_suffix: oops, overflow detected.");
777 * fls: returns the position of the most significant bit.
778 * Returns 0 if no bit is set, else returns the position of the most
779 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
781 #if defined(__i386) || defined(__x86_64)
782 static inline unsigned int fls_u32(uint32_t x
)
790 : "=r" (r
) : "rm" (x
));
797 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
804 if (!(x
& 0xFFFF0000U
)) {
808 if (!(x
& 0xFF000000U
)) {
812 if (!(x
& 0xF0000000U
)) {
816 if (!(x
& 0xC0000000U
)) {
820 if (!(x
& 0x80000000U
)) {
829 * Return the minimum order for which x <= (1UL << order).
830 * Return -1 if x is 0.
833 int utils_get_count_order_u32(uint32_t x
)
839 return fls_u32(x
- 1);
843 * Obtain the value of LTTNG_HOME environment variable, if exists.
844 * Otherwise returns the value of HOME.
847 char *utils_get_home_dir(void)
850 val
= getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
854 return getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
858 * With the given format, fill dst with the time of len maximum siz.
860 * Return amount of bytes set in the buffer or else 0 on error.
863 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
872 /* Get date and time for session path */
874 timeinfo
= localtime(&rawtime
);
875 ret
= strftime(dst
, len
, format
, timeinfo
);
877 ERR("Unable to strftime with format %s at dst %p of len %lu", format
,
885 * Return the group ID matching name, else 0 if it cannot be found.
888 gid_t
utils_get_group_id(const char *name
)
892 grp
= getgrnam(name
);
894 static volatile int warn_once
;
897 WARN("No tracing group detected");
906 * Return a newly allocated option string. This string is to be used as the
907 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
908 * of elements in the long_options array. Returns NULL if the string's
912 char *utils_generate_optstring(const struct option
*long_options
,
916 size_t string_len
= opt_count
, str_pos
= 0;
920 * Compute the necessary string length. One letter per option, two when an
921 * argument is necessary, and a trailing NULL.
923 for (i
= 0; i
< opt_count
; i
++) {
924 string_len
+= long_options
[i
].has_arg
? 1 : 0;
927 optstring
= zmalloc(string_len
);
932 for (i
= 0; i
< opt_count
; i
++) {
933 if (!long_options
[i
].name
) {
934 /* Got to the trailing NULL element */
938 optstring
[str_pos
++] = (char)long_options
[i
].val
;
939 if (long_options
[i
].has_arg
) {
940 optstring
[str_pos
++] = ':';