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>
35 #include <common/common.h>
36 #include <common/runas.h>
42 * Return a partial realpath(3) of the path even if the full path does not
43 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
44 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
45 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
46 * point directory does not exist.
47 * In case resolved_path is NULL, the string returned was allocated in the
48 * function and thus need to be freed by the caller. The size argument allows
49 * to specify the size of the resolved_path argument if given, or the size to
53 char *utils_partial_realpath(const char *path
, char *resolved_path
, size_t size
)
55 char *cut_path
= NULL
, *try_path
= NULL
, *try_path_prev
= NULL
;
56 const char *next
, *prev
, *end
;
64 * Identify the end of the path, we don't want to treat the
65 * last char if it is a '/', we will just keep it on the side
66 * to be added at the end, and return a value coherent with
67 * the path given as argument
69 end
= path
+ strlen(path
);
70 if (*(end
-1) == '/') {
74 /* Initiate the values of the pointers before looping */
77 /* Only to ensure try_path is not NULL to enter the while */
78 try_path
= (char *)next
;
80 /* Resolve the canonical path of the first part of the path */
81 while (try_path
!= NULL
&& next
!= end
) {
83 * If there is not any '/' left, we want to try with
86 next
= strpbrk(next
+ 1, "/");
91 /* Cut the part we will be trying to resolve */
92 cut_path
= strndup(path
, next
- path
);
93 if (cut_path
== NULL
) {
98 /* Try to resolve this part */
99 try_path
= realpath((char *)cut_path
, NULL
);
100 if (try_path
== NULL
) {
102 * There was an error, we just want to be assured it
103 * is linked to an unexistent directory, if it's another
104 * reason, we spawn an error
108 /* Ignore the error */
111 PERROR("realpath (partial_realpath)");
116 /* Save the place we are before trying the next step */
118 try_path_prev
= try_path
;
122 /* Free the allocated memory */
127 /* Allocate memory for the resolved path if necessary */
128 if (resolved_path
== NULL
) {
129 resolved_path
= zmalloc(size
);
130 if (resolved_path
== NULL
) {
131 PERROR("zmalloc resolved path");
137 * If we were able to solve at least partially the path, we can concatenate
138 * what worked and what didn't work
140 if (try_path_prev
!= NULL
) {
141 /* If we risk to concatenate two '/', we remove one of them */
142 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
143 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
147 * Duplicate the memory used by prev in case resolved_path and
148 * path are pointers for the same memory space
150 cut_path
= strdup(prev
);
151 if (cut_path
== NULL
) {
156 /* Concatenate the strings */
157 snprintf(resolved_path
, size
, "%s%s", try_path_prev
, cut_path
);
159 /* Free the allocated memory */
163 * Else, we just copy the path in our resolved_path to
167 strncpy(resolved_path
, path
, size
);
170 /* Then we return the 'partially' resolved path */
171 return resolved_path
;
180 * Make a full resolution of the given path even if it doesn't exist.
181 * This function uses the utils_partial_realpath function to resolve
182 * symlinks and relatives paths at the start of the string, and
183 * implements functionnalities to resolve the './' and '../' strings
184 * in the middle of a path. This function is only necessary because
185 * realpath(3) does not accept to resolve unexistent paths.
186 * The returned string was allocated in the function, it is thus of
187 * the responsibility of the caller to free this memory.
190 char *utils_expand_path(const char *path
)
192 char *next
, *previous
, *slash
, *start_path
, *absolute_path
= NULL
;
194 int is_dot
, is_dotdot
;
201 /* Allocate memory for the absolute_path */
202 absolute_path
= zmalloc(PATH_MAX
);
203 if (absolute_path
== NULL
) {
204 PERROR("zmalloc expand path");
209 * If the path is not already absolute nor explicitly relative,
210 * consider we're in the current directory
212 if (*path
!= '/' && strncmp(path
, "./", 2) != 0 &&
213 strncmp(path
, "../", 3) != 0) {
214 snprintf(absolute_path
, PATH_MAX
, "./%s", path
);
215 /* Else, we just copy the path */
217 strncpy(absolute_path
, path
, PATH_MAX
);
220 /* Resolve partially our path */
221 absolute_path
= utils_partial_realpath(absolute_path
,
222 absolute_path
, PATH_MAX
);
224 /* As long as we find '/./' in the working_path string */
225 while ((next
= strstr(absolute_path
, "/./"))) {
227 /* We prepare the start_path not containing it */
228 start_path
= strndup(absolute_path
, next
- absolute_path
);
233 /* And we concatenate it with the part after this string */
234 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 2);
239 /* As long as we find '/../' in the working_path string */
240 while ((next
= strstr(absolute_path
, "/../"))) {
241 /* We find the last level of directory */
242 previous
= absolute_path
;
243 while ((slash
= strpbrk(previous
, "/")) && slash
!= next
) {
244 previous
= slash
+ 1;
247 /* Then we prepare the start_path not containing it */
248 start_path
= strndup(absolute_path
, previous
- absolute_path
);
254 /* And we concatenate it with the part after the '/../' */
255 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 4);
257 /* We can free the memory used for the start path*/
260 /* Then we verify for symlinks using partial_realpath */
261 absolute_path
= utils_partial_realpath(absolute_path
,
262 absolute_path
, PATH_MAX
);
265 /* Identify the last token */
266 last_token
= strrchr(absolute_path
, '/');
268 /* Verify that this token is not a relative path */
269 is_dotdot
= (strcmp(last_token
, "/..") == 0);
270 is_dot
= (strcmp(last_token
, "/.") == 0);
272 /* If it is, take action */
273 if (is_dot
|| is_dotdot
) {
274 /* For both, remove this token */
277 /* If it was a reference to parent directory, go back one more time */
279 last_token
= strrchr(absolute_path
, '/');
281 /* If there was only one level left, we keep the first '/' */
282 if (last_token
== absolute_path
) {
290 return absolute_path
;
298 * Create a pipe in dst.
301 int utils_create_pipe(int *dst
)
311 PERROR("create pipe");
318 * Create pipe and set CLOEXEC flag to both fd.
320 * Make sure the pipe opened by this function are closed at some point. Use
321 * utils_close_pipe().
324 int utils_create_pipe_cloexec(int *dst
)
332 ret
= utils_create_pipe(dst
);
337 for (i
= 0; i
< 2; i
++) {
338 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
340 PERROR("fcntl pipe cloexec");
350 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
352 * Make sure the pipe opened by this function are closed at some point. Use
353 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
354 * support OSes other than Linux 2.6.23+.
357 int utils_create_pipe_cloexec_nonblock(int *dst
)
365 ret
= utils_create_pipe(dst
);
370 for (i
= 0; i
< 2; i
++) {
371 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
373 PERROR("fcntl pipe cloexec");
377 * Note: we override any flag that could have been
378 * previously set on the fd.
380 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
382 PERROR("fcntl pipe nonblock");
392 * Close both read and write side of the pipe.
395 void utils_close_pipe(int *src
)
403 for (i
= 0; i
< 2; i
++) {
411 PERROR("close pipe");
417 * Create a new string using two strings range.
420 char *utils_strdupdelim(const char *begin
, const char *end
)
424 str
= zmalloc(end
- begin
+ 1);
426 PERROR("zmalloc strdupdelim");
430 memcpy(str
, begin
, end
- begin
);
431 str
[end
- begin
] = '\0';
438 * Set CLOEXEC flag to the give file descriptor.
441 int utils_set_fd_cloexec(int fd
)
450 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
452 PERROR("fcntl cloexec");
461 * Create pid file to the given path and filename.
464 int utils_create_pid_file(pid_t pid
, const char *filepath
)
471 fp
= fopen(filepath
, "w");
473 PERROR("open pid file %s", filepath
);
478 ret
= fprintf(fp
, "%d\n", pid
);
480 PERROR("fprintf pid file");
484 DBG("Pid %d written in file %s", pid
, filepath
);
490 * Create lock file to the given path and filename.
491 * Returns the associated file descriptor, -1 on error.
494 int utils_create_lock_file(const char *filepath
)
501 fd
= open(filepath
, O_CREAT
,
502 O_WRONLY
| S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
504 PERROR("open lock file %s", filepath
);
510 * Attempt to lock the file. If this fails, there is
511 * already a process using the same lock file running
512 * and we should exit.
514 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
516 WARN("Could not get lock file %s, another instance is running.",
528 * Create directory using the given path and mode.
530 * On success, return 0 else a negative error code.
533 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
537 if (uid
< 0 || gid
< 0) {
538 ret
= mkdir(path
, mode
);
540 ret
= run_as_mkdir(path
, mode
, uid
, gid
);
543 if (errno
!= EEXIST
) {
544 PERROR("mkdir %s, uid %d, gid %d", path
? path
: "NULL",
555 * Internal version of mkdir_recursive. Runs as the current user.
556 * Don't call directly; use utils_mkdir_recursive().
558 * This function is ominously marked as "unsafe" since it should only
559 * be called by a caller that has transitioned to the uid and gid under which
560 * the directory creation should occur.
563 int _utils_mkdir_recursive_unsafe(const char *path
, mode_t mode
)
565 char *p
, tmp
[PATH_MAX
];
571 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
573 PERROR("snprintf mkdir");
578 if (tmp
[len
- 1] == '/') {
582 for (p
= tmp
+ 1; *p
; p
++) {
585 if (tmp
[strlen(tmp
) - 1] == '.' &&
586 tmp
[strlen(tmp
) - 2] == '.' &&
587 tmp
[strlen(tmp
) - 3] == '/') {
588 ERR("Using '/../' is not permitted in the trace path (%s)",
593 ret
= mkdir(tmp
, mode
);
595 if (errno
!= EEXIST
) {
596 PERROR("mkdir recursive");
605 ret
= mkdir(tmp
, mode
);
607 if (errno
!= EEXIST
) {
608 PERROR("mkdir recursive last element");
620 * Recursively create directory using the given path and mode, under the
621 * provided uid and gid.
623 * On success, return 0 else a negative error code.
626 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
630 if (uid
< 0 || gid
< 0) {
631 /* Run as current user. */
632 ret
= _utils_mkdir_recursive_unsafe(path
, mode
);
634 ret
= run_as_mkdir_recursive(path
, mode
, uid
, gid
);
637 PERROR("mkdir %s, uid %d, gid %d", path
? path
: "NULL",
645 * path is the output parameter. It needs to be PATH_MAX len.
647 * Return 0 on success or else a negative value.
649 static int utils_stream_file_name(char *path
,
650 const char *path_name
, const char *file_name
,
651 uint64_t size
, uint64_t count
,
655 char full_path
[PATH_MAX
];
656 char *path_name_suffix
= NULL
;
659 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
660 path_name
, file_name
);
662 PERROR("snprintf create output file");
666 /* Setup extra string if suffix or/and a count is needed. */
667 if (size
> 0 && suffix
) {
668 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
669 } else if (size
> 0) {
670 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
672 ret
= asprintf(&extra
, "%s", suffix
);
675 PERROR("Allocating extra string to name");
680 * If we split the trace in multiple files, we have to add the count at
681 * the end of the tracefile name.
684 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
686 PERROR("Allocating path name with extra string");
687 goto error_free_suffix
;
689 strncpy(path
, path_name_suffix
, PATH_MAX
- 1);
690 path
[PATH_MAX
- 1] = '\0';
692 strncpy(path
, full_path
, PATH_MAX
- 1);
694 path
[PATH_MAX
- 1] = '\0';
697 free(path_name_suffix
);
705 * Create the stream file on disk.
707 * Return 0 on success or else a negative value.
710 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
711 uint64_t count
, int uid
, int gid
, char *suffix
)
713 int ret
, flags
, mode
;
716 ret
= utils_stream_file_name(path
, path_name
, file_name
,
717 size
, count
, suffix
);
722 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
723 /* Open with 660 mode */
724 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
726 if (uid
< 0 || gid
< 0) {
727 ret
= open(path
, flags
, mode
);
729 ret
= run_as_open(path
, flags
, mode
, uid
, gid
);
732 PERROR("open stream path %s", path
);
739 * Unlink the stream tracefile from disk.
741 * Return 0 on success or else a negative value.
744 int utils_unlink_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
745 uint64_t count
, int uid
, int gid
, char *suffix
)
750 ret
= utils_stream_file_name(path
, path_name
, file_name
,
751 size
, count
, suffix
);
755 if (uid
< 0 || gid
< 0) {
758 ret
= run_as_unlink(path
, uid
, gid
);
764 DBG("utils_unlink_stream_file %s returns %d", path
, ret
);
769 * Change the output tracefile according to the given size and count The
770 * new_count pointer is set during this operation.
772 * From the consumer, the stream lock MUST be held before calling this function
773 * because we are modifying the stream status.
775 * Return 0 on success or else a negative value.
778 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
779 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
789 PERROR("Closing tracefile");
795 * In tracefile rotation, for the relay daemon we need
796 * to unlink the old file if present, because it may
797 * still be open in reading by the live thread, and we
798 * need to ensure that we do not overwrite the content
799 * between get_index and get_packet. Since we have no
800 * way to verify integrity of the data content compared
801 * to the associated index, we need to ensure the reader
802 * has exclusive access to the file content, and that
803 * the open of the data file is performed in get_index.
804 * Unlinking the old file rather than overwriting it
807 *new_count
= (*new_count
+ 1) % count
;
808 ret
= utils_unlink_stream_file(path_name
, file_name
,
809 size
, *new_count
, uid
, gid
, 0);
810 if (ret
< 0 && errno
!= ENOENT
) {
817 ret
= utils_create_stream_file(path_name
, file_name
, size
, *new_count
,
833 * Parse a string that represents a size in human readable format. It
834 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
836 * The suffix multiply the integer by:
841 * @param str The string to parse.
842 * @param size Pointer to a uint64_t that will be filled with the
845 * @return 0 on success, -1 on failure.
848 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
857 DBG("utils_parse_size_suffix: received a NULL string.");
862 /* strtoull will accept a negative number, but we don't want to. */
863 if (strchr(str
, '-') != NULL
) {
864 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
869 /* str_end will point to the \0 */
870 str_end
= str
+ strlen(str
);
872 base_size
= strtoull(str
, &num_end
, 0);
874 PERROR("utils_parse_size_suffix strtoull");
879 if (num_end
== str
) {
880 /* strtoull parsed nothing, not good. */
881 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
886 /* Check if a prefix is present. */
904 DBG("utils_parse_size_suffix: invalid suffix.");
909 /* Check for garbage after the valid input. */
910 if (num_end
!= str_end
) {
911 DBG("utils_parse_size_suffix: Garbage after size string.");
916 *size
= base_size
<< shift
;
918 /* Check for overflow */
919 if ((*size
>> shift
) != base_size
) {
920 DBG("utils_parse_size_suffix: oops, overflow detected.");
931 * fls: returns the position of the most significant bit.
932 * Returns 0 if no bit is set, else returns the position of the most
933 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
935 #if defined(__i386) || defined(__x86_64)
936 static inline unsigned int fls_u32(uint32_t x
)
944 : "=r" (r
) : "rm" (x
));
951 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
958 if (!(x
& 0xFFFF0000U
)) {
962 if (!(x
& 0xFF000000U
)) {
966 if (!(x
& 0xF0000000U
)) {
970 if (!(x
& 0xC0000000U
)) {
974 if (!(x
& 0x80000000U
)) {
983 * Return the minimum order for which x <= (1UL << order).
984 * Return -1 if x is 0.
987 int utils_get_count_order_u32(uint32_t x
)
993 return fls_u32(x
- 1);
997 * Obtain the value of LTTNG_HOME environment variable, if exists.
998 * Otherwise returns the value of HOME.
1001 char *utils_get_home_dir(void)
1006 val
= getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
1010 val
= getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
1015 /* Fallback on the password file entry. */
1016 pwd
= getpwuid(getuid());
1022 DBG3("Home directory is '%s'", val
);
1029 * Get user's home directory. Dynamically allocated, must be freed
1033 char *utils_get_user_home_dir(uid_t uid
)
1036 struct passwd
*result
;
1037 char *home_dir
= NULL
;
1042 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1047 buf
= zmalloc(buflen
);
1052 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
1053 if (ret
|| !result
) {
1054 if (ret
== ERANGE
) {
1062 home_dir
= strdup(pwd
.pw_dir
);
1069 * Obtain the value of LTTNG_KMOD_PROBES environment variable, if exists.
1070 * Otherwise returns NULL.
1073 char *utils_get_kmod_probes_list(void)
1075 return getenv(DEFAULT_LTTNG_KMOD_PROBES
);
1079 * Obtain the value of LTTNG_EXTRA_KMOD_PROBES environment variable, if
1080 * exists. Otherwise returns NULL.
1083 char *utils_get_extra_kmod_probes_list(void)
1085 return getenv(DEFAULT_LTTNG_EXTRA_KMOD_PROBES
);
1089 * With the given format, fill dst with the time of len maximum siz.
1091 * Return amount of bytes set in the buffer or else 0 on error.
1094 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
1098 struct tm
*timeinfo
;
1103 /* Get date and time for session path */
1105 timeinfo
= localtime(&rawtime
);
1106 ret
= strftime(dst
, len
, format
, timeinfo
);
1108 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
1116 * Return the group ID matching name, else 0 if it cannot be found.
1119 gid_t
utils_get_group_id(const char *name
)
1123 grp
= getgrnam(name
);
1125 static volatile int warn_once
;
1128 WARN("No tracing group detected");
1137 * Return a newly allocated option string. This string is to be used as the
1138 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1139 * of elements in the long_options array. Returns NULL if the string's
1143 char *utils_generate_optstring(const struct option
*long_options
,
1147 size_t string_len
= opt_count
, str_pos
= 0;
1151 * Compute the necessary string length. One letter per option, two when an
1152 * argument is necessary, and a trailing NULL.
1154 for (i
= 0; i
< opt_count
; i
++) {
1155 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1158 optstring
= zmalloc(string_len
);
1163 for (i
= 0; i
< opt_count
; i
++) {
1164 if (!long_options
[i
].name
) {
1165 /* Got to the trailing NULL element */
1169 optstring
[str_pos
++] = (char)long_options
[i
].val
;
1170 if (long_options
[i
].has_arg
) {
1171 optstring
[str_pos
++] = ':';