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
;
182 * Make a full resolution of the given path even if it doesn't exist.
183 * This function uses the utils_partial_realpath function to resolve
184 * symlinks and relatives paths at the start of the string, and
185 * implements functionnalities to resolve the './' and '../' strings
186 * in the middle of a path. This function is only necessary because
187 * realpath(3) does not accept to resolve unexistent paths.
188 * The returned string was allocated in the function, it is thus of
189 * the responsibility of the caller to free this memory.
192 char *utils_expand_path(const char *path
)
194 char *next
, *previous
, *slash
, *start_path
, *absolute_path
= NULL
;
196 int is_dot
, is_dotdot
;
203 /* Allocate memory for the absolute_path */
204 absolute_path
= zmalloc(PATH_MAX
);
205 if (absolute_path
== NULL
) {
206 PERROR("zmalloc expand path");
211 * If the path is not already absolute nor explicitly relative,
212 * consider we're in the current directory
214 if (*path
!= '/' && strncmp(path
, "./", 2) != 0 &&
215 strncmp(path
, "../", 3) != 0) {
216 snprintf(absolute_path
, PATH_MAX
, "./%s", path
);
217 /* Else, we just copy the path */
219 strncpy(absolute_path
, path
, PATH_MAX
);
222 /* Resolve partially our path */
223 absolute_path
= utils_partial_realpath(absolute_path
,
224 absolute_path
, PATH_MAX
);
226 /* As long as we find '/./' in the working_path string */
227 while ((next
= strstr(absolute_path
, "/./"))) {
229 /* We prepare the start_path not containing it */
230 start_path
= strndup(absolute_path
, next
- absolute_path
);
235 /* And we concatenate it with the part after this string */
236 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 2);
241 /* As long as we find '/../' in the working_path string */
242 while ((next
= strstr(absolute_path
, "/../"))) {
243 /* We find the last level of directory */
244 previous
= absolute_path
;
245 while ((slash
= strpbrk(previous
, "/")) && slash
!= next
) {
246 previous
= slash
+ 1;
249 /* Then we prepare the start_path not containing it */
250 start_path
= strndup(absolute_path
, previous
- absolute_path
);
256 /* And we concatenate it with the part after the '/../' */
257 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 4);
259 /* We can free the memory used for the start path*/
262 /* Then we verify for symlinks using partial_realpath */
263 absolute_path
= utils_partial_realpath(absolute_path
,
264 absolute_path
, PATH_MAX
);
267 /* Identify the last token */
268 last_token
= strrchr(absolute_path
, '/');
270 /* Verify that this token is not a relative path */
271 is_dotdot
= (strcmp(last_token
, "/..") == 0);
272 is_dot
= (strcmp(last_token
, "/.") == 0);
274 /* If it is, take action */
275 if (is_dot
|| is_dotdot
) {
276 /* For both, remove this token */
279 /* If it was a reference to parent directory, go back one more time */
281 last_token
= strrchr(absolute_path
, '/');
283 /* If there was only one level left, we keep the first '/' */
284 if (last_token
== absolute_path
) {
292 return absolute_path
;
300 * Create a pipe in dst.
303 int utils_create_pipe(int *dst
)
313 PERROR("create pipe");
320 * Create pipe and set CLOEXEC flag to both fd.
322 * Make sure the pipe opened by this function are closed at some point. Use
323 * utils_close_pipe().
326 int utils_create_pipe_cloexec(int *dst
)
334 ret
= utils_create_pipe(dst
);
339 for (i
= 0; i
< 2; i
++) {
340 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
342 PERROR("fcntl pipe cloexec");
352 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
354 * Make sure the pipe opened by this function are closed at some point. Use
355 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
356 * support OSes other than Linux 2.6.23+.
359 int utils_create_pipe_cloexec_nonblock(int *dst
)
367 ret
= utils_create_pipe(dst
);
372 for (i
= 0; i
< 2; i
++) {
373 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
375 PERROR("fcntl pipe cloexec");
379 * Note: we override any flag that could have been
380 * previously set on the fd.
382 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
384 PERROR("fcntl pipe nonblock");
394 * Close both read and write side of the pipe.
397 void utils_close_pipe(int *src
)
405 for (i
= 0; i
< 2; i
++) {
413 PERROR("close pipe");
419 * Create a new string using two strings range.
422 char *utils_strdupdelim(const char *begin
, const char *end
)
426 str
= zmalloc(end
- begin
+ 1);
428 PERROR("zmalloc strdupdelim");
432 memcpy(str
, begin
, end
- begin
);
433 str
[end
- begin
] = '\0';
440 * Set CLOEXEC flag to the give file descriptor.
443 int utils_set_fd_cloexec(int fd
)
452 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
454 PERROR("fcntl cloexec");
463 * Create pid file to the given path and filename.
466 int utils_create_pid_file(pid_t pid
, const char *filepath
)
473 fp
= fopen(filepath
, "w");
475 PERROR("open pid file %s", filepath
);
480 ret
= fprintf(fp
, "%d\n", pid
);
482 PERROR("fprintf pid file");
486 DBG("Pid %d written in file %s", pid
, filepath
);
492 * Create lock file to the given path and filename.
493 * Returns the associated file descriptor, -1 on error.
496 int utils_create_lock_file(const char *filepath
)
503 fd
= open(filepath
, O_CREAT
,
504 O_WRONLY
| S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
506 PERROR("open lock file %s", filepath
);
512 * Attempt to lock the file. If this fails, there is
513 * already a process using the same lock file running
514 * and we should exit.
516 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
518 WARN("Could not get lock file %s, another instance is running.",
530 * Create directory using the given path and mode.
532 * On success, return 0 else a negative error code.
535 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
539 if (uid
< 0 || gid
< 0) {
540 ret
= mkdir(path
, mode
);
542 ret
= run_as_mkdir(path
, mode
, uid
, gid
);
545 if (errno
!= EEXIST
) {
546 PERROR("mkdir %s, uid %d, gid %d", path
? path
: "NULL",
557 * Internal version of mkdir_recursive. Runs as the current user.
558 * Don't call directly; use utils_mkdir_recursive().
560 * This function is ominously marked as "unsafe" since it should only
561 * be called by a caller that has transitioned to the uid and gid under which
562 * the directory creation should occur.
565 int _utils_mkdir_recursive_unsafe(const char *path
, mode_t mode
)
567 char *p
, tmp
[PATH_MAX
];
573 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
575 PERROR("snprintf mkdir");
580 if (tmp
[len
- 1] == '/') {
584 for (p
= tmp
+ 1; *p
; p
++) {
587 if (tmp
[strlen(tmp
) - 1] == '.' &&
588 tmp
[strlen(tmp
) - 2] == '.' &&
589 tmp
[strlen(tmp
) - 3] == '/') {
590 ERR("Using '/../' is not permitted in the trace path (%s)",
595 ret
= mkdir(tmp
, mode
);
597 if (errno
!= EEXIST
) {
598 PERROR("mkdir recursive");
607 ret
= mkdir(tmp
, mode
);
609 if (errno
!= EEXIST
) {
610 PERROR("mkdir recursive last element");
622 * Recursively create directory using the given path and mode, under the
623 * provided uid and gid.
625 * On success, return 0 else a negative error code.
628 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
632 if (uid
< 0 || gid
< 0) {
633 /* Run as current user. */
634 ret
= _utils_mkdir_recursive_unsafe(path
, mode
);
636 ret
= run_as_mkdir_recursive(path
, mode
, uid
, gid
);
639 PERROR("mkdir %s, uid %d, gid %d", path
? path
: "NULL",
647 * path is the output parameter. It needs to be PATH_MAX len.
649 * Return 0 on success or else a negative value.
651 static int utils_stream_file_name(char *path
,
652 const char *path_name
, const char *file_name
,
653 uint64_t size
, uint64_t count
,
657 char full_path
[PATH_MAX
];
658 char *path_name_suffix
= NULL
;
661 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
662 path_name
, file_name
);
664 PERROR("snprintf create output file");
668 /* Setup extra string if suffix or/and a count is needed. */
669 if (size
> 0 && suffix
) {
670 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
671 } else if (size
> 0) {
672 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
674 ret
= asprintf(&extra
, "%s", suffix
);
677 PERROR("Allocating extra string to name");
682 * If we split the trace in multiple files, we have to add the count at
683 * the end of the tracefile name.
686 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
688 PERROR("Allocating path name with extra string");
689 goto error_free_suffix
;
691 strncpy(path
, path_name_suffix
, PATH_MAX
- 1);
692 path
[PATH_MAX
- 1] = '\0';
694 strncpy(path
, full_path
, PATH_MAX
- 1);
696 path
[PATH_MAX
- 1] = '\0';
699 free(path_name_suffix
);
707 * Create the stream file on disk.
709 * Return 0 on success or else a negative value.
712 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
713 uint64_t count
, int uid
, int gid
, char *suffix
)
715 int ret
, flags
, mode
;
718 ret
= utils_stream_file_name(path
, path_name
, file_name
,
719 size
, count
, suffix
);
724 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
725 /* Open with 660 mode */
726 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
728 if (uid
< 0 || gid
< 0) {
729 ret
= open(path
, flags
, mode
);
731 ret
= run_as_open(path
, flags
, mode
, uid
, gid
);
734 PERROR("open stream path %s", path
);
741 * Unlink the stream tracefile from disk.
743 * Return 0 on success or else a negative value.
746 int utils_unlink_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
747 uint64_t count
, int uid
, int gid
, char *suffix
)
752 ret
= utils_stream_file_name(path
, path_name
, file_name
,
753 size
, count
, suffix
);
757 if (uid
< 0 || gid
< 0) {
760 ret
= run_as_unlink(path
, uid
, gid
);
766 DBG("utils_unlink_stream_file %s returns %d", path
, ret
);
771 * Change the output tracefile according to the given size and count The
772 * new_count pointer is set during this operation.
774 * From the consumer, the stream lock MUST be held before calling this function
775 * because we are modifying the stream status.
777 * Return 0 on success or else a negative value.
780 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
781 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
791 PERROR("Closing tracefile");
797 * In tracefile rotation, for the relay daemon we need
798 * to unlink the old file if present, because it may
799 * still be open in reading by the live thread, and we
800 * need to ensure that we do not overwrite the content
801 * between get_index and get_packet. Since we have no
802 * way to verify integrity of the data content compared
803 * to the associated index, we need to ensure the reader
804 * has exclusive access to the file content, and that
805 * the open of the data file is performed in get_index.
806 * Unlinking the old file rather than overwriting it
809 *new_count
= (*new_count
+ 1) % count
;
810 ret
= utils_unlink_stream_file(path_name
, file_name
,
811 size
, *new_count
, uid
, gid
, 0);
812 if (ret
< 0 && errno
!= ENOENT
) {
819 ret
= utils_create_stream_file(path_name
, file_name
, size
, *new_count
,
835 * Parse a string that represents a size in human readable format. It
836 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
838 * The suffix multiply the integer by:
843 * @param str The string to parse.
844 * @param size Pointer to a uint64_t that will be filled with the
847 * @return 0 on success, -1 on failure.
850 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
859 DBG("utils_parse_size_suffix: received a NULL string.");
864 /* strtoull will accept a negative number, but we don't want to. */
865 if (strchr(str
, '-') != NULL
) {
866 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
871 /* str_end will point to the \0 */
872 str_end
= str
+ strlen(str
);
874 base_size
= strtoull(str
, &num_end
, 0);
876 PERROR("utils_parse_size_suffix strtoull");
881 if (num_end
== str
) {
882 /* strtoull parsed nothing, not good. */
883 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
888 /* Check if a prefix is present. */
906 DBG("utils_parse_size_suffix: invalid suffix.");
911 /* Check for garbage after the valid input. */
912 if (num_end
!= str_end
) {
913 DBG("utils_parse_size_suffix: Garbage after size string.");
918 *size
= base_size
<< shift
;
920 /* Check for overflow */
921 if ((*size
>> shift
) != base_size
) {
922 DBG("utils_parse_size_suffix: oops, overflow detected.");
933 * fls: returns the position of the most significant bit.
934 * Returns 0 if no bit is set, else returns the position of the most
935 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
937 #if defined(__i386) || defined(__x86_64)
938 static inline unsigned int fls_u32(uint32_t x
)
946 : "=r" (r
) : "rm" (x
));
953 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
960 if (!(x
& 0xFFFF0000U
)) {
964 if (!(x
& 0xFF000000U
)) {
968 if (!(x
& 0xF0000000U
)) {
972 if (!(x
& 0xC0000000U
)) {
976 if (!(x
& 0x80000000U
)) {
985 * Return the minimum order for which x <= (1UL << order).
986 * Return -1 if x is 0.
989 int utils_get_count_order_u32(uint32_t x
)
995 return fls_u32(x
- 1);
999 * Obtain the value of LTTNG_HOME environment variable, if exists.
1000 * Otherwise returns the value of HOME.
1003 char *utils_get_home_dir(void)
1008 val
= getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
1012 val
= getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
1017 /* Fallback on the password file entry. */
1018 pwd
= getpwuid(getuid());
1024 DBG3("Home directory is '%s'", val
);
1031 * Get user's home directory. Dynamically allocated, must be freed
1035 char *utils_get_user_home_dir(uid_t uid
)
1038 struct passwd
*result
;
1039 char *home_dir
= NULL
;
1044 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1049 buf
= zmalloc(buflen
);
1054 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
1055 if (ret
|| !result
) {
1056 if (ret
== ERANGE
) {
1064 home_dir
= strdup(pwd
.pw_dir
);
1071 * Obtain the value of LTTNG_KMOD_PROBES environment variable, if exists.
1072 * Otherwise returns NULL.
1075 char *utils_get_kmod_probes_list(void)
1077 return getenv(DEFAULT_LTTNG_KMOD_PROBES
);
1081 * Obtain the value of LTTNG_EXTRA_KMOD_PROBES environment variable, if
1082 * exists. Otherwise returns NULL.
1085 char *utils_get_extra_kmod_probes_list(void)
1087 return getenv(DEFAULT_LTTNG_EXTRA_KMOD_PROBES
);
1091 * With the given format, fill dst with the time of len maximum siz.
1093 * Return amount of bytes set in the buffer or else 0 on error.
1096 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
1100 struct tm
*timeinfo
;
1105 /* Get date and time for session path */
1107 timeinfo
= localtime(&rawtime
);
1108 ret
= strftime(dst
, len
, format
, timeinfo
);
1110 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
1118 * Return the group ID matching name, else 0 if it cannot be found.
1121 gid_t
utils_get_group_id(const char *name
)
1125 grp
= getgrnam(name
);
1127 static volatile int warn_once
;
1130 WARN("No tracing group detected");
1139 * Return a newly allocated option string. This string is to be used as the
1140 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1141 * of elements in the long_options array. Returns NULL if the string's
1145 char *utils_generate_optstring(const struct option
*long_options
,
1149 size_t string_len
= opt_count
, str_pos
= 0;
1153 * Compute the necessary string length. One letter per option, two when an
1154 * argument is necessary, and a trailing NULL.
1156 for (i
= 0; i
< opt_count
; i
++) {
1157 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1160 optstring
= zmalloc(string_len
);
1165 for (i
= 0; i
< opt_count
; i
++) {
1166 if (!long_options
[i
].name
) {
1167 /* Got to the trailing NULL element */
1171 optstring
[str_pos
++] = (char)long_options
[i
].val
;
1172 if (long_options
[i
].has_arg
) {
1173 optstring
[str_pos
++] = ':';