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>
36 #include <common/common.h>
37 #include <common/runas.h>
38 #include <common/compat/getenv.h>
39 #include <common/compat/string.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
= NULL
, *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
= lttng_strndup(path
, next
- path
);
96 if (cut_path
== NULL
) {
97 PERROR("lttng_strndup");
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 */
130 /* Allocate memory for the resolved path if necessary */
131 if (resolved_path
== NULL
) {
132 resolved_path
= zmalloc(size
);
133 if (resolved_path
== NULL
) {
134 PERROR("zmalloc resolved path");
140 * If we were able to solve at least partially the path, we can concatenate
141 * what worked and what didn't work
143 if (try_path_prev
!= NULL
) {
144 /* If we risk to concatenate two '/', we remove one of them */
145 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
146 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
150 * Duplicate the memory used by prev in case resolved_path and
151 * path are pointers for the same memory space
153 cut_path
= strdup(prev
);
154 if (cut_path
== NULL
) {
159 /* Concatenate the strings */
160 snprintf(resolved_path
, size
, "%s%s", try_path_prev
, cut_path
);
162 /* Free the allocated memory */
166 try_path_prev
= NULL
;
168 * Else, we just copy the path in our resolved_path to
172 strncpy(resolved_path
, path
, size
);
175 /* Then we return the 'partially' resolved path */
176 return resolved_path
;
185 * Make a full resolution of the given path even if it doesn't exist.
186 * This function uses the utils_partial_realpath function to resolve
187 * symlinks and relatives paths at the start of the string, and
188 * implements functionnalities to resolve the './' and '../' strings
189 * in the middle of a path. This function is only necessary because
190 * realpath(3) does not accept to resolve unexistent paths.
191 * The returned string was allocated in the function, it is thus of
192 * the responsibility of the caller to free this memory.
195 char *utils_expand_path(const char *path
)
197 char *next
, *previous
, *slash
, *start_path
, *absolute_path
= NULL
;
199 int is_dot
, is_dotdot
;
206 /* Allocate memory for the absolute_path */
207 absolute_path
= zmalloc(PATH_MAX
);
208 if (absolute_path
== NULL
) {
209 PERROR("zmalloc expand path");
214 * If the path is not already absolute nor explicitly relative,
215 * consider we're in the current directory
217 if (*path
!= '/' && strncmp(path
, "./", 2) != 0 &&
218 strncmp(path
, "../", 3) != 0) {
219 snprintf(absolute_path
, PATH_MAX
, "./%s", path
);
220 /* Else, we just copy the path */
222 strncpy(absolute_path
, path
, PATH_MAX
);
225 /* Resolve partially our path */
226 absolute_path
= utils_partial_realpath(absolute_path
,
227 absolute_path
, PATH_MAX
);
229 /* As long as we find '/./' in the working_path string */
230 while ((next
= strstr(absolute_path
, "/./"))) {
232 /* We prepare the start_path not containing it */
233 start_path
= lttng_strndup(absolute_path
, next
- absolute_path
);
235 PERROR("lttng_strndup");
238 /* And we concatenate it with the part after this string */
239 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 2);
244 /* As long as we find '/../' in the working_path string */
245 while ((next
= strstr(absolute_path
, "/../"))) {
246 /* We find the last level of directory */
247 previous
= absolute_path
;
248 while ((slash
= strpbrk(previous
, "/")) && slash
!= next
) {
249 previous
= slash
+ 1;
252 /* Then we prepare the start_path not containing it */
253 start_path
= lttng_strndup(absolute_path
, previous
- absolute_path
);
255 PERROR("lttng_strndup");
259 /* And we concatenate it with the part after the '/../' */
260 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 4);
262 /* We can free the memory used for the start path*/
265 /* Then we verify for symlinks using partial_realpath */
266 absolute_path
= utils_partial_realpath(absolute_path
,
267 absolute_path
, PATH_MAX
);
270 /* Identify the last token */
271 last_token
= strrchr(absolute_path
, '/');
273 /* Verify that this token is not a relative path */
274 is_dotdot
= (strcmp(last_token
, "/..") == 0);
275 is_dot
= (strcmp(last_token
, "/.") == 0);
277 /* If it is, take action */
278 if (is_dot
|| is_dotdot
) {
279 /* For both, remove this token */
282 /* If it was a reference to parent directory, go back one more time */
284 last_token
= strrchr(absolute_path
, '/');
286 /* If there was only one level left, we keep the first '/' */
287 if (last_token
== absolute_path
) {
295 return absolute_path
;
303 * Create a pipe in dst.
306 int utils_create_pipe(int *dst
)
316 PERROR("create pipe");
323 * Create pipe and set CLOEXEC flag to both fd.
325 * Make sure the pipe opened by this function are closed at some point. Use
326 * utils_close_pipe().
329 int utils_create_pipe_cloexec(int *dst
)
337 ret
= utils_create_pipe(dst
);
342 for (i
= 0; i
< 2; i
++) {
343 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
345 PERROR("fcntl pipe cloexec");
355 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
357 * Make sure the pipe opened by this function are closed at some point. Use
358 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
359 * support OSes other than Linux 2.6.23+.
362 int utils_create_pipe_cloexec_nonblock(int *dst
)
370 ret
= utils_create_pipe(dst
);
375 for (i
= 0; i
< 2; i
++) {
376 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
378 PERROR("fcntl pipe cloexec");
382 * Note: we override any flag that could have been
383 * previously set on the fd.
385 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
387 PERROR("fcntl pipe nonblock");
397 * Close both read and write side of the pipe.
400 void utils_close_pipe(int *src
)
408 for (i
= 0; i
< 2; i
++) {
416 PERROR("close pipe");
422 * Create a new string using two strings range.
425 char *utils_strdupdelim(const char *begin
, const char *end
)
429 str
= zmalloc(end
- begin
+ 1);
431 PERROR("zmalloc strdupdelim");
435 memcpy(str
, begin
, end
- begin
);
436 str
[end
- begin
] = '\0';
443 * Set CLOEXEC flag to the give file descriptor.
446 int utils_set_fd_cloexec(int fd
)
455 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
457 PERROR("fcntl cloexec");
466 * Create pid file to the given path and filename.
469 int utils_create_pid_file(pid_t pid
, const char *filepath
)
476 fp
= fopen(filepath
, "w");
478 PERROR("open pid file %s", filepath
);
483 ret
= fprintf(fp
, "%d\n", pid
);
485 PERROR("fprintf pid file");
492 DBG("Pid %d written in file %s", pid
, filepath
);
499 * Create lock file to the given path and filename.
500 * Returns the associated file descriptor, -1 on error.
503 int utils_create_lock_file(const char *filepath
)
511 memset(&lock
, 0, sizeof(lock
));
512 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
515 PERROR("open lock file %s", filepath
);
521 * Attempt to lock the file. If this fails, there is
522 * already a process using the same lock file running
523 * and we should exit.
525 lock
.l_whence
= SEEK_SET
;
526 lock
.l_type
= F_WRLCK
;
528 ret
= fcntl(fd
, F_SETLK
, &lock
);
530 PERROR("fcntl lock file");
531 ERR("Could not get lock file %s, another instance is running.",
534 PERROR("close lock file");
545 * Create directory using the given path and mode.
547 * On success, return 0 else a negative error code.
550 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
554 if (uid
< 0 || gid
< 0) {
555 ret
= mkdir(path
, mode
);
557 ret
= run_as_mkdir(path
, mode
, uid
, gid
);
560 if (errno
!= EEXIST
) {
561 PERROR("mkdir %s, uid %d, gid %d", path
? path
: "NULL",
572 * Internal version of mkdir_recursive. Runs as the current user.
573 * Don't call directly; use utils_mkdir_recursive().
575 * This function is ominously marked as "unsafe" since it should only
576 * be called by a caller that has transitioned to the uid and gid under which
577 * the directory creation should occur.
580 int _utils_mkdir_recursive_unsafe(const char *path
, mode_t mode
)
582 char *p
, tmp
[PATH_MAX
];
588 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
590 PERROR("snprintf mkdir");
595 if (tmp
[len
- 1] == '/') {
599 for (p
= tmp
+ 1; *p
; p
++) {
602 if (tmp
[strlen(tmp
) - 1] == '.' &&
603 tmp
[strlen(tmp
) - 2] == '.' &&
604 tmp
[strlen(tmp
) - 3] == '/') {
605 ERR("Using '/../' is not permitted in the trace path (%s)",
610 ret
= mkdir(tmp
, mode
);
612 if (errno
!= EEXIST
) {
613 PERROR("mkdir recursive");
622 ret
= mkdir(tmp
, mode
);
624 if (errno
!= EEXIST
) {
625 PERROR("mkdir recursive last element");
637 * Recursively create directory using the given path and mode, under the
638 * provided uid and gid.
640 * On success, return 0 else a negative error code.
643 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
647 if (uid
< 0 || gid
< 0) {
648 /* Run as current user. */
649 ret
= _utils_mkdir_recursive_unsafe(path
, mode
);
651 ret
= run_as_mkdir_recursive(path
, mode
, uid
, gid
);
654 PERROR("mkdir %s, uid %d, gid %d", path
? path
: "NULL",
662 * path is the output parameter. It needs to be PATH_MAX len.
664 * Return 0 on success or else a negative value.
666 static int utils_stream_file_name(char *path
,
667 const char *path_name
, const char *file_name
,
668 uint64_t size
, uint64_t count
,
672 char full_path
[PATH_MAX
];
673 char *path_name_suffix
= NULL
;
676 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
677 path_name
, file_name
);
679 PERROR("snprintf create output file");
683 /* Setup extra string if suffix or/and a count is needed. */
684 if (size
> 0 && suffix
) {
685 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
686 } else if (size
> 0) {
687 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
689 ret
= asprintf(&extra
, "%s", suffix
);
692 PERROR("Allocating extra string to name");
697 * If we split the trace in multiple files, we have to add the count at
698 * the end of the tracefile name.
701 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
703 PERROR("Allocating path name with extra string");
704 goto error_free_suffix
;
706 strncpy(path
, path_name_suffix
, PATH_MAX
- 1);
707 path
[PATH_MAX
- 1] = '\0';
709 strncpy(path
, full_path
, PATH_MAX
- 1);
711 path
[PATH_MAX
- 1] = '\0';
714 free(path_name_suffix
);
722 * Create the stream file on disk.
724 * Return 0 on success or else a negative value.
727 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
728 uint64_t count
, int uid
, int gid
, char *suffix
)
730 int ret
, flags
, mode
;
733 ret
= utils_stream_file_name(path
, path_name
, file_name
,
734 size
, count
, suffix
);
739 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
740 /* Open with 660 mode */
741 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
743 if (uid
< 0 || gid
< 0) {
744 ret
= open(path
, flags
, mode
);
746 ret
= run_as_open(path
, flags
, mode
, uid
, gid
);
749 PERROR("open stream path %s", path
);
756 * Unlink the stream tracefile from disk.
758 * Return 0 on success or else a negative value.
761 int utils_unlink_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
762 uint64_t count
, int uid
, int gid
, char *suffix
)
767 ret
= utils_stream_file_name(path
, path_name
, file_name
,
768 size
, count
, suffix
);
772 if (uid
< 0 || gid
< 0) {
775 ret
= run_as_unlink(path
, uid
, gid
);
781 DBG("utils_unlink_stream_file %s returns %d", path
, ret
);
786 * Change the output tracefile according to the given size and count The
787 * new_count pointer is set during this operation.
789 * From the consumer, the stream lock MUST be held before calling this function
790 * because we are modifying the stream status.
792 * Return 0 on success or else a negative value.
795 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
796 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
806 PERROR("Closing tracefile");
812 * In tracefile rotation, for the relay daemon we need
813 * to unlink the old file if present, because it may
814 * still be open in reading by the live thread, and we
815 * need to ensure that we do not overwrite the content
816 * between get_index and get_packet. Since we have no
817 * way to verify integrity of the data content compared
818 * to the associated index, we need to ensure the reader
819 * has exclusive access to the file content, and that
820 * the open of the data file is performed in get_index.
821 * Unlinking the old file rather than overwriting it
824 *new_count
= (*new_count
+ 1) % count
;
825 ret
= utils_unlink_stream_file(path_name
, file_name
,
826 size
, *new_count
, uid
, gid
, 0);
827 if (ret
< 0 && errno
!= ENOENT
) {
834 ret
= utils_create_stream_file(path_name
, file_name
, size
, *new_count
,
850 * Parse a string that represents a size in human readable format. It
851 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
853 * The suffix multiply the integer by:
858 * @param str The string to parse.
859 * @param size Pointer to a uint64_t that will be filled with the
862 * @return 0 on success, -1 on failure.
865 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
874 DBG("utils_parse_size_suffix: received a NULL string.");
879 /* strtoull will accept a negative number, but we don't want to. */
880 if (strchr(str
, '-') != NULL
) {
881 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
886 /* str_end will point to the \0 */
887 str_end
= str
+ strlen(str
);
889 base_size
= strtoull(str
, &num_end
, 0);
891 PERROR("utils_parse_size_suffix strtoull");
896 if (num_end
== str
) {
897 /* strtoull parsed nothing, not good. */
898 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
903 /* Check if a prefix is present. */
921 DBG("utils_parse_size_suffix: invalid suffix.");
926 /* Check for garbage after the valid input. */
927 if (num_end
!= str_end
) {
928 DBG("utils_parse_size_suffix: Garbage after size string.");
933 *size
= base_size
<< shift
;
935 /* Check for overflow */
936 if ((*size
>> shift
) != base_size
) {
937 DBG("utils_parse_size_suffix: oops, overflow detected.");
948 * fls: returns the position of the most significant bit.
949 * Returns 0 if no bit is set, else returns the position of the most
950 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
952 #if defined(__i386) || defined(__x86_64)
953 static inline unsigned int fls_u32(uint32_t x
)
961 : "=r" (r
) : "rm" (x
));
968 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
975 if (!(x
& 0xFFFF0000U
)) {
979 if (!(x
& 0xFF000000U
)) {
983 if (!(x
& 0xF0000000U
)) {
987 if (!(x
& 0xC0000000U
)) {
991 if (!(x
& 0x80000000U
)) {
1000 * Return the minimum order for which x <= (1UL << order).
1001 * Return -1 if x is 0.
1004 int utils_get_count_order_u32(uint32_t x
)
1010 return fls_u32(x
- 1);
1014 * Obtain the value of LTTNG_HOME environment variable, if exists.
1015 * Otherwise returns the value of HOME.
1018 char *utils_get_home_dir(void)
1023 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
1027 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
1032 /* Fallback on the password file entry. */
1033 pwd
= getpwuid(getuid());
1039 DBG3("Home directory is '%s'", val
);
1046 * Get user's home directory. Dynamically allocated, must be freed
1050 char *utils_get_user_home_dir(uid_t uid
)
1053 struct passwd
*result
;
1054 char *home_dir
= NULL
;
1059 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1064 buf
= zmalloc(buflen
);
1069 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
1070 if (ret
|| !result
) {
1071 if (ret
== ERANGE
) {
1079 home_dir
= strdup(pwd
.pw_dir
);
1086 * Obtain the value of LTTNG_KMOD_PROBES environment variable, if exists.
1087 * Otherwise returns NULL.
1090 char *utils_get_kmod_probes_list(void)
1092 return lttng_secure_getenv(DEFAULT_LTTNG_KMOD_PROBES
);
1096 * Obtain the value of LTTNG_EXTRA_KMOD_PROBES environment variable, if
1097 * exists. Otherwise returns NULL.
1100 char *utils_get_extra_kmod_probes_list(void)
1102 return lttng_secure_getenv(DEFAULT_LTTNG_EXTRA_KMOD_PROBES
);
1106 * With the given format, fill dst with the time of len maximum siz.
1108 * Return amount of bytes set in the buffer or else 0 on error.
1111 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
1115 struct tm
*timeinfo
;
1120 /* Get date and time for session path */
1122 timeinfo
= localtime(&rawtime
);
1123 ret
= strftime(dst
, len
, format
, timeinfo
);
1125 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
1133 * Return the group ID matching name, else 0 if it cannot be found.
1136 gid_t
utils_get_group_id(const char *name
)
1140 grp
= getgrnam(name
);
1142 static volatile int warn_once
;
1145 WARN("No tracing group detected");
1154 * Return a newly allocated option string. This string is to be used as the
1155 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1156 * of elements in the long_options array. Returns NULL if the string's
1160 char *utils_generate_optstring(const struct option
*long_options
,
1164 size_t string_len
= opt_count
, str_pos
= 0;
1168 * Compute the necessary string length. One letter per option, two when an
1169 * argument is necessary, and a trailing NULL.
1171 for (i
= 0; i
< opt_count
; i
++) {
1172 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1175 optstring
= zmalloc(string_len
);
1180 for (i
= 0; i
< opt_count
; i
++) {
1181 if (!long_options
[i
].name
) {
1182 /* Got to the trailing NULL element */
1186 if (long_options
[i
].val
!= '\0') {
1187 optstring
[str_pos
++] = (char) long_options
[i
].val
;
1188 if (long_options
[i
].has_arg
) {
1189 optstring
[str_pos
++] = ':';
1199 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1200 * any file. Try to rmdir any empty directory within the hierarchy.
1203 int utils_recursive_rmdir(const char *path
)
1207 int dir_fd
, ret
= 0, closeret
, is_empty
= 1;
1208 struct dirent
*entry
;
1210 /* Open directory */
1211 dir
= opendir(path
);
1213 PERROR("Cannot open '%s' path", path
);
1216 dir_fd
= dirfd(dir
);
1222 path_len
= strlen(path
);
1223 while ((entry
= readdir(dir
))) {
1224 if (!strcmp(entry
->d_name
, ".")
1225 || !strcmp(entry
->d_name
, ".."))
1230 char filename
[PATH_MAX
];
1232 name_len
= strlen(entry
->d_name
);
1233 if (path_len
+ name_len
+ 2 > sizeof(filename
)) {
1234 ERR("Failed to remove file: path name too long (%s/%s)",
1235 path
, entry
->d_name
);
1238 if (snprintf(filename
, sizeof(filename
), "%s/%s",
1239 path
, entry
->d_name
) < 0) {
1240 ERR("Failed to format path.");
1244 if (stat(filename
, &st
)) {
1249 if (S_ISDIR(st
.st_mode
)) {
1250 char subpath
[PATH_MAX
];
1252 strncpy(subpath
, path
, PATH_MAX
);
1253 subpath
[PATH_MAX
- 1] = '\0';
1254 strncat(subpath
, "/",
1255 PATH_MAX
- strlen(subpath
) - 1);
1256 strncat(subpath
, entry
->d_name
,
1257 PATH_MAX
- strlen(subpath
) - 1);
1258 if (utils_recursive_rmdir(subpath
)) {
1261 } else if (S_ISREG(st
.st_mode
)) {
1269 closeret
= closedir(dir
);
1274 DBG3("Attempting rmdir %s", path
);