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.
27 #include <sys/types.h>
34 #include <common/common.h>
35 #include <common/runas.h>
36 #include <common/compat/getenv.h>
37 #include <common/compat/string.h>
38 #include <common/compat/dirent.h>
44 * Return a partial realpath(3) of the path even if the full path does not
45 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
46 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
47 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
48 * point directory does not exist.
49 * In case resolved_path is NULL, the string returned was allocated in the
50 * function and thus need to be freed by the caller. The size argument allows
51 * to specify the size of the resolved_path argument if given, or the size to
55 char *utils_partial_realpath(const char *path
, char *resolved_path
, size_t size
)
57 char *cut_path
= NULL
, *try_path
= NULL
, *try_path_prev
= NULL
;
58 const char *next
, *prev
, *end
;
66 * Identify the end of the path, we don't want to treat the
67 * last char if it is a '/', we will just keep it on the side
68 * to be added at the end, and return a value coherent with
69 * the path given as argument
71 end
= path
+ strlen(path
);
72 if (*(end
-1) == '/') {
76 /* Initiate the values of the pointers before looping */
79 /* Only to ensure try_path is not NULL to enter the while */
80 try_path
= (char *)next
;
82 /* Resolve the canonical path of the first part of the path */
83 while (try_path
!= NULL
&& next
!= end
) {
85 * If there is not any '/' left, we want to try with
88 next
= strpbrk(next
+ 1, "/");
93 /* Cut the part we will be trying to resolve */
94 cut_path
= lttng_strndup(path
, next
- path
);
95 if (cut_path
== NULL
) {
96 PERROR("lttng_strndup");
100 /* Try to resolve this part */
101 try_path
= realpath((char *)cut_path
, NULL
);
102 if (try_path
== NULL
) {
104 * There was an error, we just want to be assured it
105 * is linked to an unexistent directory, if it's another
106 * reason, we spawn an error
110 /* Ignore the error */
113 PERROR("realpath (partial_realpath)");
118 /* Save the place we are before trying the next step */
120 try_path_prev
= try_path
;
124 /* 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 try_path_prev
= NULL
;
167 * Else, we just copy the path in our resolved_path to
171 strncpy(resolved_path
, path
, size
);
174 /* Then we return the 'partially' resolved path */
175 return resolved_path
;
184 * Make a full resolution of the given path even if it doesn't exist.
185 * This function uses the utils_partial_realpath function to resolve
186 * symlinks and relatives paths at the start of the string, and
187 * implements functionnalities to resolve the './' and '../' strings
188 * in the middle of a path. This function is only necessary because
189 * realpath(3) does not accept to resolve unexistent paths.
190 * The returned string was allocated in the function, it is thus of
191 * the responsibility of the caller to free this memory.
194 char *utils_expand_path(const char *path
)
196 char *next
, *previous
, *slash
, *start_path
, *absolute_path
= NULL
;
198 int is_dot
, is_dotdot
;
205 /* Allocate memory for the absolute_path */
206 absolute_path
= zmalloc(PATH_MAX
);
207 if (absolute_path
== NULL
) {
208 PERROR("zmalloc expand path");
213 * If the path is not already absolute nor explicitly relative,
214 * consider we're in the current directory
216 if (*path
!= '/' && strncmp(path
, "./", 2) != 0 &&
217 strncmp(path
, "../", 3) != 0) {
218 snprintf(absolute_path
, PATH_MAX
, "./%s", path
);
219 /* Else, we just copy the path */
221 strncpy(absolute_path
, path
, PATH_MAX
);
224 /* Resolve partially our path */
225 absolute_path
= utils_partial_realpath(absolute_path
,
226 absolute_path
, PATH_MAX
);
228 /* As long as we find '/./' in the working_path string */
229 while ((next
= strstr(absolute_path
, "/./"))) {
231 /* We prepare the start_path not containing it */
232 start_path
= lttng_strndup(absolute_path
, next
- absolute_path
);
234 PERROR("lttng_strndup");
237 /* And we concatenate it with the part after this string */
238 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 2);
243 /* As long as we find '/../' in the working_path string */
244 while ((next
= strstr(absolute_path
, "/../"))) {
245 /* We find the last level of directory */
246 previous
= absolute_path
;
247 while ((slash
= strpbrk(previous
, "/")) && slash
!= next
) {
248 previous
= slash
+ 1;
251 /* Then we prepare the start_path not containing it */
252 start_path
= lttng_strndup(absolute_path
, previous
- absolute_path
);
254 PERROR("lttng_strndup");
258 /* And we concatenate it with the part after the '/../' */
259 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 4);
261 /* We can free the memory used for the start path*/
264 /* Then we verify for symlinks using partial_realpath */
265 absolute_path
= utils_partial_realpath(absolute_path
,
266 absolute_path
, PATH_MAX
);
269 /* Identify the last token */
270 last_token
= strrchr(absolute_path
, '/');
272 /* Verify that this token is not a relative path */
273 is_dotdot
= (strcmp(last_token
, "/..") == 0);
274 is_dot
= (strcmp(last_token
, "/.") == 0);
276 /* If it is, take action */
277 if (is_dot
|| is_dotdot
) {
278 /* For both, remove this token */
281 /* If it was a reference to parent directory, go back one more time */
283 last_token
= strrchr(absolute_path
, '/');
285 /* If there was only one level left, we keep the first '/' */
286 if (last_token
== absolute_path
) {
294 return absolute_path
;
302 * Create a pipe in dst.
305 int utils_create_pipe(int *dst
)
315 PERROR("create pipe");
322 * Create pipe and set CLOEXEC flag to both fd.
324 * Make sure the pipe opened by this function are closed at some point. Use
325 * utils_close_pipe().
328 int utils_create_pipe_cloexec(int *dst
)
336 ret
= utils_create_pipe(dst
);
341 for (i
= 0; i
< 2; i
++) {
342 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
344 PERROR("fcntl pipe cloexec");
354 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
356 * Make sure the pipe opened by this function are closed at some point. Use
357 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
358 * support OSes other than Linux 2.6.23+.
361 int utils_create_pipe_cloexec_nonblock(int *dst
)
369 ret
= utils_create_pipe(dst
);
374 for (i
= 0; i
< 2; i
++) {
375 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
377 PERROR("fcntl pipe cloexec");
381 * Note: we override any flag that could have been
382 * previously set on the fd.
384 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
386 PERROR("fcntl pipe nonblock");
396 * Close both read and write side of the pipe.
399 void utils_close_pipe(int *src
)
407 for (i
= 0; i
< 2; i
++) {
415 PERROR("close pipe");
421 * Create a new string using two strings range.
424 char *utils_strdupdelim(const char *begin
, const char *end
)
428 str
= zmalloc(end
- begin
+ 1);
430 PERROR("zmalloc strdupdelim");
434 memcpy(str
, begin
, end
- begin
);
435 str
[end
- begin
] = '\0';
442 * Set CLOEXEC flag to the give file descriptor.
445 int utils_set_fd_cloexec(int fd
)
454 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
456 PERROR("fcntl cloexec");
465 * Create pid file to the given path and filename.
468 int utils_create_pid_file(pid_t pid
, const char *filepath
)
475 fp
= fopen(filepath
, "w");
477 PERROR("open pid file %s", filepath
);
482 ret
= fprintf(fp
, "%d\n", pid
);
484 PERROR("fprintf pid file");
491 DBG("Pid %d written in file %s", pid
, filepath
);
498 * Create lock file to the given path and filename.
499 * Returns the associated file descriptor, -1 on error.
502 int utils_create_lock_file(const char *filepath
)
510 memset(&lock
, 0, sizeof(lock
));
511 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
514 PERROR("open lock file %s", filepath
);
520 * Attempt to lock the file. If this fails, there is
521 * already a process using the same lock file running
522 * and we should exit.
524 lock
.l_whence
= SEEK_SET
;
525 lock
.l_type
= F_WRLCK
;
527 ret
= fcntl(fd
, F_SETLK
, &lock
);
529 PERROR("fcntl lock file");
530 ERR("Could not get lock file %s, another instance is running.",
533 PERROR("close lock file");
544 * Create directory using the given path and mode.
546 * On success, return 0 else a negative error code.
549 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
553 if (uid
< 0 || gid
< 0) {
554 ret
= mkdir(path
, mode
);
556 ret
= run_as_mkdir(path
, mode
, uid
, gid
);
559 if (errno
!= EEXIST
) {
560 PERROR("mkdir %s, uid %d, gid %d", path
? path
: "NULL",
571 * Internal version of mkdir_recursive. Runs as the current user.
572 * Don't call directly; use utils_mkdir_recursive().
574 * This function is ominously marked as "unsafe" since it should only
575 * be called by a caller that has transitioned to the uid and gid under which
576 * the directory creation should occur.
579 int _utils_mkdir_recursive_unsafe(const char *path
, mode_t mode
)
581 char *p
, tmp
[PATH_MAX
];
587 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
589 PERROR("snprintf mkdir");
594 if (tmp
[len
- 1] == '/') {
598 for (p
= tmp
+ 1; *p
; p
++) {
601 if (tmp
[strlen(tmp
) - 1] == '.' &&
602 tmp
[strlen(tmp
) - 2] == '.' &&
603 tmp
[strlen(tmp
) - 3] == '/') {
604 ERR("Using '/../' is not permitted in the trace path (%s)",
609 ret
= mkdir(tmp
, mode
);
611 if (errno
!= EEXIST
) {
612 PERROR("mkdir recursive");
621 ret
= mkdir(tmp
, mode
);
623 if (errno
!= EEXIST
) {
624 PERROR("mkdir recursive last element");
636 * Recursively create directory using the given path and mode, under the
637 * provided uid and gid.
639 * On success, return 0 else a negative error code.
642 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
646 if (uid
< 0 || gid
< 0) {
647 /* Run as current user. */
648 ret
= _utils_mkdir_recursive_unsafe(path
, mode
);
650 ret
= run_as_mkdir_recursive(path
, mode
, uid
, gid
);
653 PERROR("mkdir %s, uid %d, gid %d", path
? path
: "NULL",
661 * path is the output parameter. It needs to be PATH_MAX len.
663 * Return 0 on success or else a negative value.
665 static int utils_stream_file_name(char *path
,
666 const char *path_name
, const char *file_name
,
667 uint64_t size
, uint64_t count
,
671 char full_path
[PATH_MAX
];
672 char *path_name_suffix
= NULL
;
675 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
676 path_name
, file_name
);
678 PERROR("snprintf create output file");
682 /* Setup extra string if suffix or/and a count is needed. */
683 if (size
> 0 && suffix
) {
684 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
685 } else if (size
> 0) {
686 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
688 ret
= asprintf(&extra
, "%s", suffix
);
691 PERROR("Allocating extra string to name");
696 * If we split the trace in multiple files, we have to add the count at
697 * the end of the tracefile name.
700 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
702 PERROR("Allocating path name with extra string");
703 goto error_free_suffix
;
705 strncpy(path
, path_name_suffix
, PATH_MAX
- 1);
706 path
[PATH_MAX
- 1] = '\0';
708 strncpy(path
, full_path
, PATH_MAX
- 1);
710 path
[PATH_MAX
- 1] = '\0';
713 free(path_name_suffix
);
721 * Create the stream file on disk.
723 * Return 0 on success or else a negative value.
726 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
727 uint64_t count
, int uid
, int gid
, char *suffix
)
729 int ret
, flags
, mode
;
732 ret
= utils_stream_file_name(path
, path_name
, file_name
,
733 size
, count
, suffix
);
738 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
739 /* Open with 660 mode */
740 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
742 if (uid
< 0 || gid
< 0) {
743 ret
= open(path
, flags
, mode
);
745 ret
= run_as_open(path
, flags
, mode
, uid
, gid
);
748 PERROR("open stream path %s", path
);
755 * Unlink the stream tracefile from disk.
757 * Return 0 on success or else a negative value.
760 int utils_unlink_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
761 uint64_t count
, int uid
, int gid
, char *suffix
)
766 ret
= utils_stream_file_name(path
, path_name
, file_name
,
767 size
, count
, suffix
);
771 if (uid
< 0 || gid
< 0) {
774 ret
= run_as_unlink(path
, uid
, gid
);
780 DBG("utils_unlink_stream_file %s returns %d", path
, ret
);
785 * Change the output tracefile according to the given size and count The
786 * new_count pointer is set during this operation.
788 * From the consumer, the stream lock MUST be held before calling this function
789 * because we are modifying the stream status.
791 * Return 0 on success or else a negative value.
794 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
795 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
805 PERROR("Closing tracefile");
811 * In tracefile rotation, for the relay daemon we need
812 * to unlink the old file if present, because it may
813 * still be open in reading by the live thread, and we
814 * need to ensure that we do not overwrite the content
815 * between get_index and get_packet. Since we have no
816 * way to verify integrity of the data content compared
817 * to the associated index, we need to ensure the reader
818 * has exclusive access to the file content, and that
819 * the open of the data file is performed in get_index.
820 * Unlinking the old file rather than overwriting it
823 *new_count
= (*new_count
+ 1) % count
;
824 ret
= utils_unlink_stream_file(path_name
, file_name
,
825 size
, *new_count
, uid
, gid
, 0);
826 if (ret
< 0 && errno
!= ENOENT
) {
833 ret
= utils_create_stream_file(path_name
, file_name
, size
, *new_count
,
849 * Parse a string that represents a size in human readable format. It
850 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
852 * The suffix multiply the integer by:
857 * @param str The string to parse.
858 * @param size Pointer to a uint64_t that will be filled with the
861 * @return 0 on success, -1 on failure.
864 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
873 DBG("utils_parse_size_suffix: received a NULL string.");
878 /* strtoull will accept a negative number, but we don't want to. */
879 if (strchr(str
, '-') != NULL
) {
880 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
885 /* str_end will point to the \0 */
886 str_end
= str
+ strlen(str
);
888 base_size
= strtoull(str
, &num_end
, 0);
890 PERROR("utils_parse_size_suffix strtoull");
895 if (num_end
== str
) {
896 /* strtoull parsed nothing, not good. */
897 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
902 /* Check if a prefix is present. */
920 DBG("utils_parse_size_suffix: invalid suffix.");
925 /* Check for garbage after the valid input. */
926 if (num_end
!= str_end
) {
927 DBG("utils_parse_size_suffix: Garbage after size string.");
932 *size
= base_size
<< shift
;
934 /* Check for overflow */
935 if ((*size
>> shift
) != base_size
) {
936 DBG("utils_parse_size_suffix: oops, overflow detected.");
947 * fls: returns the position of the most significant bit.
948 * Returns 0 if no bit is set, else returns the position of the most
949 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
951 #if defined(__i386) || defined(__x86_64)
952 static inline unsigned int fls_u32(uint32_t x
)
960 : "=r" (r
) : "rm" (x
));
967 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
974 if (!(x
& 0xFFFF0000U
)) {
978 if (!(x
& 0xFF000000U
)) {
982 if (!(x
& 0xF0000000U
)) {
986 if (!(x
& 0xC0000000U
)) {
990 if (!(x
& 0x80000000U
)) {
999 * Return the minimum order for which x <= (1UL << order).
1000 * Return -1 if x is 0.
1003 int utils_get_count_order_u32(uint32_t x
)
1009 return fls_u32(x
- 1);
1013 * Obtain the value of LTTNG_HOME environment variable, if exists.
1014 * Otherwise returns the value of HOME.
1017 char *utils_get_home_dir(void)
1022 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
1026 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
1031 /* Fallback on the password file entry. */
1032 pwd
= getpwuid(getuid());
1038 DBG3("Home directory is '%s'", val
);
1045 * Get user's home directory. Dynamically allocated, must be freed
1049 char *utils_get_user_home_dir(uid_t uid
)
1052 struct passwd
*result
;
1053 char *home_dir
= NULL
;
1058 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1063 buf
= zmalloc(buflen
);
1068 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
1069 if (ret
|| !result
) {
1070 if (ret
== ERANGE
) {
1078 home_dir
= strdup(pwd
.pw_dir
);
1085 * Obtain the value of LTTNG_KMOD_PROBES environment variable, if exists.
1086 * Otherwise returns NULL.
1089 char *utils_get_kmod_probes_list(void)
1091 return lttng_secure_getenv(DEFAULT_LTTNG_KMOD_PROBES
);
1095 * Obtain the value of LTTNG_EXTRA_KMOD_PROBES environment variable, if
1096 * exists. Otherwise returns NULL.
1099 char *utils_get_extra_kmod_probes_list(void)
1101 return lttng_secure_getenv(DEFAULT_LTTNG_EXTRA_KMOD_PROBES
);
1105 * With the given format, fill dst with the time of len maximum siz.
1107 * Return amount of bytes set in the buffer or else 0 on error.
1110 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
1114 struct tm
*timeinfo
;
1119 /* Get date and time for session path */
1121 timeinfo
= localtime(&rawtime
);
1122 ret
= strftime(dst
, len
, format
, timeinfo
);
1124 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
1132 * Return the group ID matching name, else 0 if it cannot be found.
1135 gid_t
utils_get_group_id(const char *name
)
1139 grp
= getgrnam(name
);
1141 static volatile int warn_once
;
1144 WARN("No tracing group detected");
1153 * Return a newly allocated option string. This string is to be used as the
1154 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1155 * of elements in the long_options array. Returns NULL if the string's
1159 char *utils_generate_optstring(const struct option
*long_options
,
1163 size_t string_len
= opt_count
, str_pos
= 0;
1167 * Compute the necessary string length. One letter per option, two when an
1168 * argument is necessary, and a trailing NULL.
1170 for (i
= 0; i
< opt_count
; i
++) {
1171 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1174 optstring
= zmalloc(string_len
);
1179 for (i
= 0; i
< opt_count
; i
++) {
1180 if (!long_options
[i
].name
) {
1181 /* Got to the trailing NULL element */
1185 if (long_options
[i
].val
!= '\0') {
1186 optstring
[str_pos
++] = (char) long_options
[i
].val
;
1187 if (long_options
[i
].has_arg
) {
1188 optstring
[str_pos
++] = ':';
1198 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1199 * any file. Try to rmdir any empty directory within the hierarchy.
1202 int utils_recursive_rmdir(const char *path
)
1206 int dir_fd
, ret
= 0, closeret
, is_empty
= 1;
1207 struct dirent
*entry
;
1209 /* Open directory */
1210 dir
= opendir(path
);
1212 PERROR("Cannot open '%s' path", path
);
1215 dir_fd
= lttng_dirfd(dir
);
1217 PERROR("lttng_dirfd");
1221 path_len
= strlen(path
);
1222 while ((entry
= readdir(dir
))) {
1223 if (!strcmp(entry
->d_name
, ".")
1224 || !strcmp(entry
->d_name
, ".."))
1229 char filename
[PATH_MAX
];
1231 name_len
= strlen(entry
->d_name
);
1232 if (path_len
+ name_len
+ 2 > sizeof(filename
)) {
1233 ERR("Failed to remove file: path name too long (%s/%s)",
1234 path
, entry
->d_name
);
1237 if (snprintf(filename
, sizeof(filename
), "%s/%s",
1238 path
, entry
->d_name
) < 0) {
1239 ERR("Failed to format path.");
1243 if (stat(filename
, &st
)) {
1248 if (S_ISDIR(st
.st_mode
)) {
1249 char subpath
[PATH_MAX
];
1251 strncpy(subpath
, path
, PATH_MAX
);
1252 subpath
[PATH_MAX
- 1] = '\0';
1253 strncat(subpath
, "/",
1254 PATH_MAX
- strlen(subpath
) - 1);
1255 strncat(subpath
, entry
->d_name
,
1256 PATH_MAX
- strlen(subpath
) - 1);
1257 if (utils_recursive_rmdir(subpath
)) {
1260 } else if (S_ISREG(st
.st_mode
)) {
1268 closeret
= closedir(dir
);
1273 DBG3("Attempting rmdir %s", path
);