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>
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
;
181 int is_dot
, is_dotdot
;
188 /* Allocate memory for the absolute_path */
189 absolute_path
= zmalloc(PATH_MAX
);
190 if (absolute_path
== NULL
) {
191 PERROR("zmalloc expand path");
196 * If the path is not already absolute nor explicitly relative,
197 * consider we're in the current directory
199 if (*path
!= '/' && strncmp(path
, "./", 2) != 0 &&
200 strncmp(path
, "../", 3) != 0) {
201 snprintf(absolute_path
, PATH_MAX
, "./%s", path
);
202 /* Else, we just copy the path */
204 strncpy(absolute_path
, path
, PATH_MAX
);
207 /* Resolve partially our path */
208 absolute_path
= utils_partial_realpath(absolute_path
,
209 absolute_path
, PATH_MAX
);
211 /* As long as we find '/./' in the working_path string */
212 while ((next
= strstr(absolute_path
, "/./"))) {
214 /* We prepare the start_path not containing it */
215 start_path
= strndup(absolute_path
, next
- absolute_path
);
217 /* And we concatenate it with the part after this string */
218 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 2);
223 /* As long as we find '/../' in the working_path string */
224 while ((next
= strstr(absolute_path
, "/../"))) {
225 /* We find the last level of directory */
226 previous
= absolute_path
;
227 while ((slash
= strpbrk(previous
, "/")) && slash
!= next
) {
228 previous
= slash
+ 1;
231 /* Then we prepare the start_path not containing it */
232 start_path
= strndup(absolute_path
, previous
- absolute_path
);
234 /* And we concatenate it with the part after the '/../' */
235 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 4);
237 /* We can free the memory used for the start path*/
240 /* Then we verify for symlinks using partial_realpath */
241 absolute_path
= utils_partial_realpath(absolute_path
,
242 absolute_path
, PATH_MAX
);
245 /* Identify the last token */
246 last_token
= strrchr(absolute_path
, '/');
248 /* Verify that this token is not a relative path */
249 is_dotdot
= (strcmp(last_token
, "/..") == 0);
250 is_dot
= (strcmp(last_token
, "/.") == 0);
252 /* If it is, take action */
253 if (is_dot
|| is_dotdot
) {
254 /* For both, remove this token */
257 /* If it was a reference to parent directory, go back one more time */
259 last_token
= strrchr(absolute_path
, '/');
261 /* If there was only one level left, we keep the first '/' */
262 if (last_token
== absolute_path
) {
270 return absolute_path
;
278 * Create a pipe in dst.
281 int utils_create_pipe(int *dst
)
291 PERROR("create pipe");
298 * Create pipe and set CLOEXEC flag to both fd.
300 * Make sure the pipe opened by this function are closed at some point. Use
301 * utils_close_pipe().
304 int utils_create_pipe_cloexec(int *dst
)
312 ret
= utils_create_pipe(dst
);
317 for (i
= 0; i
< 2; i
++) {
318 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
320 PERROR("fcntl pipe cloexec");
330 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
332 * Make sure the pipe opened by this function are closed at some point. Use
333 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
334 * support OSes other than Linux 2.6.23+.
337 int utils_create_pipe_cloexec_nonblock(int *dst
)
345 ret
= utils_create_pipe(dst
);
350 for (i
= 0; i
< 2; i
++) {
351 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
353 PERROR("fcntl pipe cloexec");
357 * Note: we override any flag that could have been
358 * previously set on the fd.
360 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
362 PERROR("fcntl pipe nonblock");
372 * Close both read and write side of the pipe.
375 void utils_close_pipe(int *src
)
383 for (i
= 0; i
< 2; i
++) {
391 PERROR("close pipe");
397 * Create a new string using two strings range.
400 char *utils_strdupdelim(const char *begin
, const char *end
)
404 str
= zmalloc(end
- begin
+ 1);
406 PERROR("zmalloc strdupdelim");
410 memcpy(str
, begin
, end
- begin
);
411 str
[end
- begin
] = '\0';
418 * Set CLOEXEC flag to the give file descriptor.
421 int utils_set_fd_cloexec(int fd
)
430 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
432 PERROR("fcntl cloexec");
441 * Create pid file to the given path and filename.
444 int utils_create_pid_file(pid_t pid
, const char *filepath
)
451 fp
= fopen(filepath
, "w");
453 PERROR("open pid file %s", filepath
);
458 ret
= fprintf(fp
, "%d\n", pid
);
460 PERROR("fprintf pid file");
464 DBG("Pid %d written in file %s", pid
, filepath
);
470 * Recursively create directory using the given path and mode.
472 * On success, return 0 else a negative error code.
475 int utils_mkdir_recursive(const char *path
, mode_t mode
)
477 char *p
, tmp
[PATH_MAX
];
483 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
485 PERROR("snprintf mkdir");
490 if (tmp
[len
- 1] == '/') {
494 for (p
= tmp
+ 1; *p
; p
++) {
497 if (tmp
[strlen(tmp
) - 1] == '.' &&
498 tmp
[strlen(tmp
) - 2] == '.' &&
499 tmp
[strlen(tmp
) - 3] == '/') {
500 ERR("Using '/../' is not permitted in the trace path (%s)",
505 ret
= mkdir(tmp
, mode
);
507 if (errno
!= EEXIST
) {
508 PERROR("mkdir recursive");
517 ret
= mkdir(tmp
, mode
);
519 if (errno
!= EEXIST
) {
520 PERROR("mkdir recursive last piece");
532 * Create the stream tracefile on disk.
534 * Return 0 on success or else a negative value.
537 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
538 uint64_t count
, int uid
, int gid
, char *suffix
)
540 int ret
, out_fd
, flags
, mode
;
541 char full_path
[PATH_MAX
], *path_name_suffix
= NULL
, *path
;
547 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
548 path_name
, file_name
);
550 PERROR("snprintf create output file");
554 /* Setup extra string if suffix or/and a count is needed. */
555 if (size
> 0 && suffix
) {
556 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
557 } else if (size
> 0) {
558 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
560 ret
= asprintf(&extra
, "%s", suffix
);
563 PERROR("Allocating extra string to name");
568 * If we split the trace in multiple files, we have to add the count at the
569 * end of the tracefile name
572 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
574 PERROR("Allocating path name with extra string");
575 goto error_free_suffix
;
577 path
= path_name_suffix
;
582 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
583 /* Open with 660 mode */
584 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
586 if (uid
< 0 || gid
< 0) {
587 out_fd
= open(path
, flags
, mode
);
589 out_fd
= run_as_open(path
, flags
, mode
, uid
, gid
);
592 PERROR("open stream path %s", path
);
598 free(path_name_suffix
);
606 * Change the output tracefile according to the given size and count The
607 * new_count pointer is set during this operation.
609 * From the consumer, the stream lock MUST be held before calling this function
610 * because we are modifying the stream status.
612 * Return 0 on success or else a negative value.
615 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
616 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
626 PERROR("Closing tracefile");
631 *new_count
= (*new_count
+ 1) % count
;
636 ret
= utils_create_stream_file(path_name
, file_name
, size
, *new_count
,
652 * Parse a string that represents a size in human readable format. It
653 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
655 * The suffix multiply the integer by:
660 * @param str The string to parse.
661 * @param size Pointer to a uint64_t that will be filled with the
664 * @return 0 on success, -1 on failure.
667 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
676 DBG("utils_parse_size_suffix: received a NULL string.");
681 /* strtoull will accept a negative number, but we don't want to. */
682 if (strchr(str
, '-') != NULL
) {
683 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
688 /* str_end will point to the \0 */
689 str_end
= str
+ strlen(str
);
691 base_size
= strtoull(str
, &num_end
, 0);
693 PERROR("utils_parse_size_suffix strtoull");
698 if (num_end
== str
) {
699 /* strtoull parsed nothing, not good. */
700 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
705 /* Check if a prefix is present. */
723 DBG("utils_parse_size_suffix: invalid suffix.");
728 /* Check for garbage after the valid input. */
729 if (num_end
!= str_end
) {
730 DBG("utils_parse_size_suffix: Garbage after size string.");
735 *size
= base_size
<< shift
;
737 /* Check for overflow */
738 if ((*size
>> shift
) != base_size
) {
739 DBG("utils_parse_size_suffix: oops, overflow detected.");
750 * fls: returns the position of the most significant bit.
751 * Returns 0 if no bit is set, else returns the position of the most
752 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
754 #if defined(__i386) || defined(__x86_64)
755 static inline unsigned int fls_u32(uint32_t x
)
763 : "=r" (r
) : "rm" (x
));
770 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
777 if (!(x
& 0xFFFF0000U
)) {
781 if (!(x
& 0xFF000000U
)) {
785 if (!(x
& 0xF0000000U
)) {
789 if (!(x
& 0xC0000000U
)) {
793 if (!(x
& 0x80000000U
)) {
802 * Return the minimum order for which x <= (1UL << order).
803 * Return -1 if x is 0.
806 int utils_get_count_order_u32(uint32_t x
)
812 return fls_u32(x
- 1);
816 * Obtain the value of LTTNG_HOME environment variable, if exists.
817 * Otherwise returns the value of HOME.
820 char *utils_get_home_dir(void)
823 val
= getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
827 return getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
831 * With the given format, fill dst with the time of len maximum siz.
833 * Return amount of bytes set in the buffer or else 0 on error.
836 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
845 /* Get date and time for session path */
847 timeinfo
= localtime(&rawtime
);
848 ret
= strftime(dst
, len
, format
, timeinfo
);
850 ERR("Unable to strftime with format %s at dst %p of len %lu", format
,
858 * Return the group ID matching name, else 0 if it cannot be found.
861 gid_t
utils_get_group_id(const char *name
)
865 grp
= getgrnam(name
);
867 static volatile int warn_once
;
870 WARN("No tracing group detected");