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.
29 #include <sys/types.h>
37 #include <common/common.h>
38 #include <common/runas.h>
39 #include <common/compat/getenv.h>
45 * Return a partial realpath(3) of the path even if the full path does not
46 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
47 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
48 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
49 * point directory does not exist.
50 * In case resolved_path is NULL, the string returned was allocated in the
51 * function and thus need to be freed by the caller. The size argument allows
52 * to specify the size of the resolved_path argument if given, or the size to
56 char *utils_partial_realpath(const char *path
, char *resolved_path
, size_t size
)
58 char *cut_path
, *try_path
= NULL
, *try_path_prev
= NULL
;
59 const char *next
, *prev
, *end
;
67 * Identify the end of the path, we don't want to treat the
68 * last char if it is a '/', we will just keep it on the side
69 * to be added at the end, and return a value coherent with
70 * the path given as argument
72 end
= path
+ strlen(path
);
73 if (*(end
-1) == '/') {
77 /* Initiate the values of the pointers before looping */
80 /* Only to ensure try_path is not NULL to enter the while */
81 try_path
= (char *)next
;
83 /* Resolve the canonical path of the first part of the path */
84 while (try_path
!= NULL
&& next
!= end
) {
86 * If there is not any '/' left, we want to try with
89 next
= strpbrk(next
+ 1, "/");
94 /* Cut the part we will be trying to resolve */
95 cut_path
= strndup(path
, next
- path
);
96 if (cut_path
== NULL
) {
101 /* Try to resolve this part */
102 try_path
= realpath((char *)cut_path
, NULL
);
103 if (try_path
== NULL
) {
105 * There was an error, we just want to be assured it
106 * is linked to an unexistent directory, if it's another
107 * reason, we spawn an error
111 /* Ignore the error */
114 PERROR("realpath (partial_realpath)");
119 /* Save the place we are before trying the next step */
121 try_path_prev
= try_path
;
125 /* Free the allocated memory */
129 /* Allocate memory for the resolved path if necessary */
130 if (resolved_path
== NULL
) {
131 resolved_path
= zmalloc(size
);
132 if (resolved_path
== NULL
) {
133 PERROR("zmalloc resolved path");
139 * If we were able to solve at least partially the path, we can concatenate
140 * what worked and what didn't work
142 if (try_path_prev
!= NULL
) {
143 /* If we risk to concatenate two '/', we remove one of them */
144 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
145 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
149 * Duplicate the memory used by prev in case resolved_path and
150 * path are pointers for the same memory space
152 cut_path
= strdup(prev
);
153 if (cut_path
== NULL
) {
158 /* Concatenate the strings */
159 snprintf(resolved_path
, size
, "%s%s", try_path_prev
, cut_path
);
161 /* Free the allocated memory */
165 * Else, we just copy the path in our resolved_path to
169 strncpy(resolved_path
, path
, size
);
172 /* Then we return the 'partially' resolved path */
173 return resolved_path
;
181 * Make a full resolution of the given path even if it doesn't exist.
182 * This function uses the utils_partial_realpath function to resolve
183 * symlinks and relatives paths at the start of the string, and
184 * implements functionnalities to resolve the './' and '../' strings
185 * in the middle of a path. This function is only necessary because
186 * realpath(3) does not accept to resolve unexistent paths.
187 * The returned string was allocated in the function, it is thus of
188 * the responsibility of the caller to free this memory.
191 char *utils_expand_path(const char *path
)
193 char *next
, *previous
, *slash
, *start_path
, *absolute_path
= NULL
;
195 int is_dot
, is_dotdot
;
202 /* Allocate memory for the absolute_path */
203 absolute_path
= zmalloc(PATH_MAX
);
204 if (absolute_path
== NULL
) {
205 PERROR("zmalloc expand path");
210 * If the path is not already absolute nor explicitly relative,
211 * consider we're in the current directory
213 if (*path
!= '/' && strncmp(path
, "./", 2) != 0 &&
214 strncmp(path
, "../", 3) != 0) {
215 snprintf(absolute_path
, PATH_MAX
, "./%s", path
);
216 /* Else, we just copy the path */
218 strncpy(absolute_path
, path
, PATH_MAX
);
221 /* Resolve partially our path */
222 absolute_path
= utils_partial_realpath(absolute_path
,
223 absolute_path
, PATH_MAX
);
225 /* As long as we find '/./' in the working_path string */
226 while ((next
= strstr(absolute_path
, "/./"))) {
228 /* We prepare the start_path not containing it */
229 start_path
= strndup(absolute_path
, next
- absolute_path
);
234 /* And we concatenate it with the part after this string */
235 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 2);
240 /* As long as we find '/../' in the working_path string */
241 while ((next
= strstr(absolute_path
, "/../"))) {
242 /* We find the last level of directory */
243 previous
= absolute_path
;
244 while ((slash
= strpbrk(previous
, "/")) && slash
!= next
) {
245 previous
= slash
+ 1;
248 /* Then we prepare the start_path not containing it */
249 start_path
= strndup(absolute_path
, previous
- absolute_path
);
255 /* And we concatenate it with the part after the '/../' */
256 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 4);
258 /* We can free the memory used for the start path*/
261 /* Then we verify for symlinks using partial_realpath */
262 absolute_path
= utils_partial_realpath(absolute_path
,
263 absolute_path
, PATH_MAX
);
266 /* Identify the last token */
267 last_token
= strrchr(absolute_path
, '/');
269 /* Verify that this token is not a relative path */
270 is_dotdot
= (strcmp(last_token
, "/..") == 0);
271 is_dot
= (strcmp(last_token
, "/.") == 0);
273 /* If it is, take action */
274 if (is_dot
|| is_dotdot
) {
275 /* For both, remove this token */
278 /* If it was a reference to parent directory, go back one more time */
280 last_token
= strrchr(absolute_path
, '/');
282 /* If there was only one level left, we keep the first '/' */
283 if (last_token
== absolute_path
) {
291 return absolute_path
;
299 * Create a pipe in dst.
302 int utils_create_pipe(int *dst
)
312 PERROR("create pipe");
319 * Create pipe and set CLOEXEC flag to both fd.
321 * Make sure the pipe opened by this function are closed at some point. Use
322 * utils_close_pipe().
325 int utils_create_pipe_cloexec(int *dst
)
333 ret
= utils_create_pipe(dst
);
338 for (i
= 0; i
< 2; i
++) {
339 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
341 PERROR("fcntl pipe cloexec");
351 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
353 * Make sure the pipe opened by this function are closed at some point. Use
354 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
355 * support OSes other than Linux 2.6.23+.
358 int utils_create_pipe_cloexec_nonblock(int *dst
)
366 ret
= utils_create_pipe(dst
);
371 for (i
= 0; i
< 2; i
++) {
372 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
374 PERROR("fcntl pipe cloexec");
378 * Note: we override any flag that could have been
379 * previously set on the fd.
381 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
383 PERROR("fcntl pipe nonblock");
393 * Close both read and write side of the pipe.
396 void utils_close_pipe(int *src
)
404 for (i
= 0; i
< 2; i
++) {
412 PERROR("close pipe");
418 * Create a new string using two strings range.
421 char *utils_strdupdelim(const char *begin
, const char *end
)
425 str
= zmalloc(end
- begin
+ 1);
427 PERROR("zmalloc strdupdelim");
431 memcpy(str
, begin
, end
- begin
);
432 str
[end
- begin
] = '\0';
439 * Set CLOEXEC flag to the give file descriptor.
442 int utils_set_fd_cloexec(int fd
)
451 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
453 PERROR("fcntl cloexec");
462 * Create pid file to the given path and filename.
465 int utils_create_pid_file(pid_t pid
, const char *filepath
)
472 fp
= fopen(filepath
, "w");
474 PERROR("open pid file %s", filepath
);
479 ret
= fprintf(fp
, "%d\n", pid
);
481 PERROR("fprintf pid file");
488 DBG("Pid %d written in file %s", pid
, filepath
);
495 * Create lock file to the given path and filename.
496 * Returns the associated file descriptor, -1 on error.
499 int utils_create_lock_file(const char *filepath
)
506 fd
= open(filepath
, O_CREAT
,
507 O_WRONLY
| S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
509 PERROR("open lock file %s", filepath
);
515 * Attempt to lock the file. If this fails, there is
516 * already a process using the same lock file running
517 * and we should exit.
519 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
521 ERR("Could not get lock file %s, another instance is running.",
524 PERROR("close lock file");
535 * Recursively create directory using the given path and mode.
537 * On success, return 0 else a negative error code.
540 int utils_mkdir_recursive(const char *path
, mode_t mode
)
542 char *p
, tmp
[PATH_MAX
];
548 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
550 PERROR("snprintf mkdir");
555 if (tmp
[len
- 1] == '/') {
559 for (p
= tmp
+ 1; *p
; p
++) {
562 if (tmp
[strlen(tmp
) - 1] == '.' &&
563 tmp
[strlen(tmp
) - 2] == '.' &&
564 tmp
[strlen(tmp
) - 3] == '/') {
565 ERR("Using '/../' is not permitted in the trace path (%s)",
570 ret
= mkdir(tmp
, mode
);
572 if (errno
!= EEXIST
) {
573 PERROR("mkdir recursive");
582 ret
= mkdir(tmp
, mode
);
584 if (errno
!= EEXIST
) {
585 PERROR("mkdir recursive last piece");
597 * Create the stream tracefile on disk.
599 * Return 0 on success or else a negative value.
602 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
603 uint64_t count
, int uid
, int gid
, char *suffix
)
605 int ret
, out_fd
, flags
, mode
;
606 char full_path
[PATH_MAX
], *path_name_suffix
= NULL
, *path
;
612 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
613 path_name
, file_name
);
615 PERROR("snprintf create output file");
619 /* Setup extra string if suffix or/and a count is needed. */
620 if (size
> 0 && suffix
) {
621 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
622 } else if (size
> 0) {
623 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
625 ret
= asprintf(&extra
, "%s", suffix
);
628 PERROR("Allocating extra string to name");
633 * If we split the trace in multiple files, we have to add the count at the
634 * end of the tracefile name
637 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
639 PERROR("Allocating path name with extra string");
640 goto error_free_suffix
;
642 path
= path_name_suffix
;
647 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
648 /* Open with 660 mode */
649 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
651 if (uid
< 0 || gid
< 0) {
652 out_fd
= open(path
, flags
, mode
);
654 out_fd
= run_as_open(path
, flags
, mode
, uid
, gid
);
657 PERROR("open stream path %s", path
);
663 free(path_name_suffix
);
671 * Change the output tracefile according to the given size and count The
672 * new_count pointer is set during this operation.
674 * From the consumer, the stream lock MUST be held before calling this function
675 * because we are modifying the stream status.
677 * Return 0 on success or else a negative value.
680 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
681 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
691 PERROR("Closing tracefile");
696 *new_count
= (*new_count
+ 1) % count
;
701 ret
= utils_create_stream_file(path_name
, file_name
, size
, *new_count
,
717 * Parse a string that represents a size in human readable format. It
718 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
720 * The suffix multiply the integer by:
725 * @param str The string to parse.
726 * @param size Pointer to a uint64_t that will be filled with the
729 * @return 0 on success, -1 on failure.
732 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
741 DBG("utils_parse_size_suffix: received a NULL string.");
746 /* strtoull will accept a negative number, but we don't want to. */
747 if (strchr(str
, '-') != NULL
) {
748 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
753 /* str_end will point to the \0 */
754 str_end
= str
+ strlen(str
);
756 base_size
= strtoull(str
, &num_end
, 0);
758 PERROR("utils_parse_size_suffix strtoull");
763 if (num_end
== str
) {
764 /* strtoull parsed nothing, not good. */
765 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
770 /* Check if a prefix is present. */
788 DBG("utils_parse_size_suffix: invalid suffix.");
793 /* Check for garbage after the valid input. */
794 if (num_end
!= str_end
) {
795 DBG("utils_parse_size_suffix: Garbage after size string.");
800 *size
= base_size
<< shift
;
802 /* Check for overflow */
803 if ((*size
>> shift
) != base_size
) {
804 DBG("utils_parse_size_suffix: oops, overflow detected.");
815 * fls: returns the position of the most significant bit.
816 * Returns 0 if no bit is set, else returns the position of the most
817 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
819 #if defined(__i386) || defined(__x86_64)
820 static inline unsigned int fls_u32(uint32_t x
)
828 : "=r" (r
) : "rm" (x
));
835 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
842 if (!(x
& 0xFFFF0000U
)) {
846 if (!(x
& 0xFF000000U
)) {
850 if (!(x
& 0xF0000000U
)) {
854 if (!(x
& 0xC0000000U
)) {
858 if (!(x
& 0x80000000U
)) {
867 * Return the minimum order for which x <= (1UL << order).
868 * Return -1 if x is 0.
871 int utils_get_count_order_u32(uint32_t x
)
877 return fls_u32(x
- 1);
881 * Obtain the value of LTTNG_HOME environment variable, if exists.
882 * Otherwise returns the value of HOME.
885 char *utils_get_home_dir(void)
890 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
894 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
899 /* Fallback on the password file entry. */
900 pwd
= getpwuid(getuid());
906 DBG3("Home directory is '%s'", val
);
913 * Get user's home directory. Dynamically allocated, must be freed
917 char *utils_get_user_home_dir(uid_t uid
)
920 struct passwd
*result
;
921 char *home_dir
= NULL
;
926 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
931 buf
= zmalloc(buflen
);
936 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
937 if (ret
|| !result
) {
946 home_dir
= strdup(pwd
.pw_dir
);
953 * Obtain the value of LTTNG_KMOD_PROBES environment variable, if exists.
954 * Otherwise returns NULL.
957 char *utils_get_kmod_probes_list(void)
959 return lttng_secure_getenv(DEFAULT_LTTNG_KMOD_PROBES
);
963 * Obtain the value of LTTNG_EXTRA_KMOD_PROBES environment variable, if
964 * exists. Otherwise returns NULL.
967 char *utils_get_extra_kmod_probes_list(void)
969 return lttng_secure_getenv(DEFAULT_LTTNG_EXTRA_KMOD_PROBES
);
973 * With the given format, fill dst with the time of len maximum siz.
975 * Return amount of bytes set in the buffer or else 0 on error.
978 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
987 /* Get date and time for session path */
989 timeinfo
= localtime(&rawtime
);
990 ret
= strftime(dst
, len
, format
, timeinfo
);
992 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
1000 * Return the group ID matching name, else 0 if it cannot be found.
1003 gid_t
utils_get_group_id(const char *name
)
1007 grp
= getgrnam(name
);
1009 static volatile int warn_once
;
1012 WARN("No tracing group detected");
1021 * Return a newly allocated option string. This string is to be used as the
1022 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1023 * of elements in the long_options array. Returns NULL if the string's
1027 char *utils_generate_optstring(const struct option
*long_options
,
1031 size_t string_len
= opt_count
, str_pos
= 0;
1035 * Compute the necessary string length. One letter per option, two when an
1036 * argument is necessary, and a trailing NULL.
1038 for (i
= 0; i
< opt_count
; i
++) {
1039 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1042 optstring
= zmalloc(string_len
);
1047 for (i
= 0; i
< opt_count
; i
++) {
1048 if (!long_options
[i
].name
) {
1049 /* Got to the trailing NULL element */
1053 optstring
[str_pos
++] = (char)long_options
[i
].val
;
1054 if (long_options
[i
].has_arg
) {
1055 optstring
[str_pos
++] = ':';
1064 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1065 * any file. Try to rmdir any empty directory within the hierarchy.
1068 int utils_recursive_rmdir(const char *path
)
1071 int dir_fd
, ret
= 0, closeret
, is_empty
= 1;
1072 struct dirent
*entry
;
1074 /* Open directory */
1075 dir
= opendir(path
);
1077 PERROR("Cannot open '%s' path", path
);
1080 dir_fd
= dirfd(dir
);
1086 while ((entry
= readdir(dir
))) {
1087 if (!strcmp(entry
->d_name
, ".")
1088 || !strcmp(entry
->d_name
, ".."))
1090 switch (entry
->d_type
) {
1093 char subpath
[PATH_MAX
];
1095 strncpy(subpath
, path
, PATH_MAX
);
1096 subpath
[PATH_MAX
- 1] = '\0';
1097 strncat(subpath
, "/",
1098 PATH_MAX
- strlen(subpath
) - 1);
1099 strncat(subpath
, entry
->d_name
,
1100 PATH_MAX
- strlen(subpath
) - 1);
1101 if (utils_recursive_rmdir(subpath
)) {
1115 closeret
= closedir(dir
);
1120 DBG3("Attempting rmdir %s", path
);