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>
35 #include <common/common.h>
36 #include <common/runas.h>
37 #include <common/compat/getenv.h>
38 #include <common/compat/string.h>
39 #include <common/compat/dirent.h>
40 #include <lttng/constant.h>
46 * Return a partial realpath(3) of the path even if the full path does not
47 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
48 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
49 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
50 * point directory does not exist.
51 * In case resolved_path is NULL, the string returned was allocated in the
52 * function and thus need to be freed by the caller. The size argument allows
53 * to specify the size of the resolved_path argument if given, or the size to
57 char *utils_partial_realpath(const char *path
, char *resolved_path
, size_t size
)
59 char *cut_path
= NULL
, *try_path
= NULL
, *try_path_prev
= NULL
;
60 const char *next
, *prev
, *end
;
68 * Identify the end of the path, we don't want to treat the
69 * last char if it is a '/', we will just keep it on the side
70 * to be added at the end, and return a value coherent with
71 * the path given as argument
73 end
= path
+ strlen(path
);
74 if (*(end
-1) == '/') {
78 /* Initiate the values of the pointers before looping */
81 /* Only to ensure try_path is not NULL to enter the while */
82 try_path
= (char *)next
;
84 /* Resolve the canonical path of the first part of the path */
85 while (try_path
!= NULL
&& next
!= end
) {
86 char *try_path_buf
= NULL
;
89 * If there is not any '/' left, we want to try with
92 next
= strpbrk(next
+ 1, "/");
97 /* Cut the part we will be trying to resolve */
98 cut_path
= lttng_strndup(path
, next
- path
);
99 if (cut_path
== NULL
) {
100 PERROR("lttng_strndup");
104 try_path_buf
= zmalloc(LTTNG_PATH_MAX
);
110 /* Try to resolve this part */
111 try_path
= realpath((char *) cut_path
, try_path_buf
);
112 if (try_path
== NULL
) {
115 * There was an error, we just want to be assured it
116 * is linked to an unexistent directory, if it's another
117 * reason, we spawn an error
121 /* Ignore the error */
124 PERROR("realpath (partial_realpath)");
129 /* Save the place we are before trying the next step */
132 try_path_prev
= try_path
;
136 /* Free the allocated memory */
141 /* Allocate memory for the resolved path if necessary */
142 if (resolved_path
== NULL
) {
143 resolved_path
= zmalloc(size
);
144 if (resolved_path
== NULL
) {
145 PERROR("zmalloc resolved path");
151 * If we were able to solve at least partially the path, we can concatenate
152 * what worked and what didn't work
154 if (try_path_prev
!= NULL
) {
155 /* If we risk to concatenate two '/', we remove one of them */
156 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
157 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
161 * Duplicate the memory used by prev in case resolved_path and
162 * path are pointers for the same memory space
164 cut_path
= strdup(prev
);
165 if (cut_path
== NULL
) {
170 /* Concatenate the strings */
171 snprintf(resolved_path
, size
, "%s%s", try_path_prev
, cut_path
);
173 /* Free the allocated memory */
177 try_path_prev
= NULL
;
179 * Else, we just copy the path in our resolved_path to
183 strncpy(resolved_path
, path
, size
);
186 /* Then we return the 'partially' resolved path */
187 return resolved_path
;
193 if (try_path_prev
!= try_path
) {
200 * Make a full resolution of the given path even if it doesn't exist.
201 * This function uses the utils_partial_realpath function to resolve
202 * symlinks and relatives paths at the start of the string, and
203 * implements functionnalities to resolve the './' and '../' strings
204 * in the middle of a path. This function is only necessary because
205 * realpath(3) does not accept to resolve unexistent paths.
206 * The returned string was allocated in the function, it is thus of
207 * the responsibility of the caller to free this memory.
210 char *utils_expand_path(const char *path
)
212 char *next
, *previous
, *slash
, *start_path
, *absolute_path
= NULL
;
214 int is_dot
, is_dotdot
;
221 /* Allocate memory for the absolute_path */
222 absolute_path
= zmalloc(PATH_MAX
);
223 if (absolute_path
== NULL
) {
224 PERROR("zmalloc expand path");
229 * If the path is not already absolute nor explicitly relative,
230 * consider we're in the current directory
232 if (*path
!= '/' && strncmp(path
, "./", 2) != 0 &&
233 strncmp(path
, "../", 3) != 0) {
234 snprintf(absolute_path
, PATH_MAX
, "./%s", path
);
235 /* Else, we just copy the path */
237 strncpy(absolute_path
, path
, PATH_MAX
);
240 /* Resolve partially our path */
241 absolute_path
= utils_partial_realpath(absolute_path
,
242 absolute_path
, PATH_MAX
);
244 /* As long as we find '/./' in the working_path string */
245 while ((next
= strstr(absolute_path
, "/./"))) {
247 /* We prepare the start_path not containing it */
248 start_path
= lttng_strndup(absolute_path
, next
- absolute_path
);
250 PERROR("lttng_strndup");
253 /* And we concatenate it with the part after this string */
254 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 2);
259 /* As long as we find '/../' in the working_path string */
260 while ((next
= strstr(absolute_path
, "/../"))) {
261 /* We find the last level of directory */
262 previous
= absolute_path
;
263 while ((slash
= strpbrk(previous
, "/")) && slash
!= next
) {
264 previous
= slash
+ 1;
267 /* Then we prepare the start_path not containing it */
268 start_path
= lttng_strndup(absolute_path
, previous
- absolute_path
);
270 PERROR("lttng_strndup");
274 /* And we concatenate it with the part after the '/../' */
275 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 4);
277 /* We can free the memory used for the start path*/
280 /* Then we verify for symlinks using partial_realpath */
281 absolute_path
= utils_partial_realpath(absolute_path
,
282 absolute_path
, PATH_MAX
);
285 /* Identify the last token */
286 last_token
= strrchr(absolute_path
, '/');
288 /* Verify that this token is not a relative path */
289 is_dotdot
= (strcmp(last_token
, "/..") == 0);
290 is_dot
= (strcmp(last_token
, "/.") == 0);
292 /* If it is, take action */
293 if (is_dot
|| is_dotdot
) {
294 /* For both, remove this token */
297 /* If it was a reference to parent directory, go back one more time */
299 last_token
= strrchr(absolute_path
, '/');
301 /* If there was only one level left, we keep the first '/' */
302 if (last_token
== absolute_path
) {
310 return absolute_path
;
318 * Create a pipe in dst.
321 int utils_create_pipe(int *dst
)
331 PERROR("create pipe");
338 * Create pipe and set CLOEXEC flag to both fd.
340 * Make sure the pipe opened by this function are closed at some point. Use
341 * utils_close_pipe().
344 int utils_create_pipe_cloexec(int *dst
)
352 ret
= utils_create_pipe(dst
);
357 for (i
= 0; i
< 2; i
++) {
358 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
360 PERROR("fcntl pipe cloexec");
370 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
372 * Make sure the pipe opened by this function are closed at some point. Use
373 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
374 * support OSes other than Linux 2.6.23+.
377 int utils_create_pipe_cloexec_nonblock(int *dst
)
385 ret
= utils_create_pipe(dst
);
390 for (i
= 0; i
< 2; i
++) {
391 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
393 PERROR("fcntl pipe cloexec");
397 * Note: we override any flag that could have been
398 * previously set on the fd.
400 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
402 PERROR("fcntl pipe nonblock");
412 * Close both read and write side of the pipe.
415 void utils_close_pipe(int *src
)
423 for (i
= 0; i
< 2; i
++) {
431 PERROR("close pipe");
437 * Create a new string using two strings range.
440 char *utils_strdupdelim(const char *begin
, const char *end
)
444 str
= zmalloc(end
- begin
+ 1);
446 PERROR("zmalloc strdupdelim");
450 memcpy(str
, begin
, end
- begin
);
451 str
[end
- begin
] = '\0';
458 * Set CLOEXEC flag to the give file descriptor.
461 int utils_set_fd_cloexec(int fd
)
470 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
472 PERROR("fcntl cloexec");
481 * Create pid file to the given path and filename.
484 int utils_create_pid_file(pid_t pid
, const char *filepath
)
491 fp
= fopen(filepath
, "w");
493 PERROR("open pid file %s", filepath
);
498 ret
= fprintf(fp
, "%d\n", (int) pid
);
500 PERROR("fprintf pid file");
507 DBG("Pid %d written in file %s", (int) pid
, filepath
);
514 * Create lock file to the given path and filename.
515 * Returns the associated file descriptor, -1 on error.
518 int utils_create_lock_file(const char *filepath
)
526 memset(&lock
, 0, sizeof(lock
));
527 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
530 PERROR("open lock file %s", filepath
);
536 * Attempt to lock the file. If this fails, there is
537 * already a process using the same lock file running
538 * and we should exit.
540 lock
.l_whence
= SEEK_SET
;
541 lock
.l_type
= F_WRLCK
;
543 ret
= fcntl(fd
, F_SETLK
, &lock
);
545 PERROR("fcntl lock file");
546 ERR("Could not get lock file %s, another instance is running.",
549 PERROR("close lock file");
560 * On some filesystems (e.g. nfs), mkdir will validate access rights before
561 * checking for the existence of the path element. This means that on a setup
562 * where "/home/" is a mounted NFS share, and running as an unpriviledged user,
563 * recursively creating a path of the form "/home/my_user/trace/" will fail with
564 * EACCES on mkdir("/home", ...).
566 * Performing a stat(...) on the path to check for existence allows us to
567 * work around this behaviour.
570 int mkdir_check_exists(const char *path
, mode_t mode
)
575 ret
= stat(path
, &st
);
577 if (S_ISDIR(st
.st_mode
)) {
578 /* Directory exists, skip. */
581 /* Exists, but is not a directory. */
589 * Let mkdir handle other errors as the caller expects mkdir
592 ret
= mkdir(path
, mode
);
598 * Create directory using the given path and mode.
600 * On success, return 0 else a negative error code.
603 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
607 if (uid
< 0 || gid
< 0) {
608 ret
= mkdir_check_exists(path
, mode
);
610 ret
= run_as_mkdir(path
, mode
, uid
, gid
);
613 if (errno
!= EEXIST
) {
614 PERROR("mkdir %s, uid %d, gid %d", path
? path
: "NULL",
625 * Internal version of mkdir_recursive. Runs as the current user.
626 * Don't call directly; use utils_mkdir_recursive().
628 * This function is ominously marked as "unsafe" since it should only
629 * be called by a caller that has transitioned to the uid and gid under which
630 * the directory creation should occur.
633 int _utils_mkdir_recursive_unsafe(const char *path
, mode_t mode
)
635 char *p
, tmp
[PATH_MAX
];
641 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
643 PERROR("snprintf mkdir");
648 if (tmp
[len
- 1] == '/') {
652 for (p
= tmp
+ 1; *p
; p
++) {
655 if (tmp
[strlen(tmp
) - 1] == '.' &&
656 tmp
[strlen(tmp
) - 2] == '.' &&
657 tmp
[strlen(tmp
) - 3] == '/') {
658 ERR("Using '/../' is not permitted in the trace path (%s)",
663 ret
= mkdir_check_exists(tmp
, mode
);
665 if (errno
!= EACCES
) {
666 PERROR("mkdir recursive");
675 ret
= mkdir_check_exists(tmp
, mode
);
677 PERROR("mkdir recursive last element");
686 * Recursively create directory using the given path and mode, under the
687 * provided uid and gid.
689 * On success, return 0 else a negative error code.
692 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
696 if (uid
< 0 || gid
< 0) {
697 /* Run as current user. */
698 ret
= _utils_mkdir_recursive_unsafe(path
, mode
);
700 ret
= run_as_mkdir_recursive(path
, mode
, uid
, gid
);
703 PERROR("mkdir %s, uid %d, gid %d", path
? path
: "NULL",
711 * path is the output parameter. It needs to be PATH_MAX len.
713 * Return 0 on success or else a negative value.
715 static int utils_stream_file_name(char *path
,
716 const char *path_name
, const char *file_name
,
717 uint64_t size
, uint64_t count
,
721 char full_path
[PATH_MAX
];
722 char *path_name_suffix
= NULL
;
725 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
726 path_name
, file_name
);
728 PERROR("snprintf create output file");
732 /* Setup extra string if suffix or/and a count is needed. */
733 if (size
> 0 && suffix
) {
734 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
735 } else if (size
> 0) {
736 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
738 ret
= asprintf(&extra
, "%s", suffix
);
741 PERROR("Allocating extra string to name");
746 * If we split the trace in multiple files, we have to add the count at
747 * the end of the tracefile name.
750 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
752 PERROR("Allocating path name with extra string");
753 goto error_free_suffix
;
755 strncpy(path
, path_name_suffix
, PATH_MAX
- 1);
756 path
[PATH_MAX
- 1] = '\0';
758 ret
= lttng_strncpy(path
, full_path
, PATH_MAX
);
760 ERR("Failed to copy stream file name");
761 goto error_free_suffix
;
764 path
[PATH_MAX
- 1] = '\0';
767 free(path_name_suffix
);
775 * Create the stream file on disk.
777 * Return 0 on success or else a negative value.
780 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
781 uint64_t count
, int uid
, int gid
, char *suffix
)
783 int ret
, flags
, mode
;
786 ret
= utils_stream_file_name(path
, path_name
, file_name
,
787 size
, count
, suffix
);
793 * With the session rotation feature on the relay, we might need to seek
794 * and truncate a tracefile, so we need read and write access.
796 flags
= O_RDWR
| O_CREAT
| O_TRUNC
;
797 /* Open with 660 mode */
798 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
800 if (uid
< 0 || gid
< 0) {
801 ret
= open(path
, flags
, mode
);
803 ret
= run_as_open(path
, flags
, mode
, uid
, gid
);
806 PERROR("open stream path %s", path
);
813 * Unlink the stream tracefile from disk.
815 * Return 0 on success or else a negative value.
818 int utils_unlink_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
819 uint64_t count
, int uid
, int gid
, char *suffix
)
824 ret
= utils_stream_file_name(path
, path_name
, file_name
,
825 size
, count
, suffix
);
829 if (uid
< 0 || gid
< 0) {
832 ret
= run_as_unlink(path
, uid
, gid
);
838 DBG("utils_unlink_stream_file %s returns %d", path
, ret
);
843 * Change the output tracefile according to the given size and count The
844 * new_count pointer is set during this operation.
846 * From the consumer, the stream lock MUST be held before calling this function
847 * because we are modifying the stream status.
849 * Return 0 on success or else a negative value.
852 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
853 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
862 PERROR("Closing tracefile");
869 * In tracefile rotation, for the relay daemon we need
870 * to unlink the old file if present, because it may
871 * still be open in reading by the live thread, and we
872 * need to ensure that we do not overwrite the content
873 * between get_index and get_packet. Since we have no
874 * way to verify integrity of the data content compared
875 * to the associated index, we need to ensure the reader
876 * has exclusive access to the file content, and that
877 * the open of the data file is performed in get_index.
878 * Unlinking the old file rather than overwriting it
882 *new_count
= (*new_count
+ 1) % count
;
884 ret
= utils_unlink_stream_file(path_name
, file_name
, size
,
885 new_count
? *new_count
: 0, uid
, gid
, 0);
886 if (ret
< 0 && errno
!= ENOENT
) {
895 ret
= utils_create_stream_file(path_name
, file_name
, size
,
896 new_count
? *new_count
: 0, uid
, gid
, 0);
911 * Parse a string that represents a size in human readable format. It
912 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
914 * The suffix multiply the integer by:
919 * @param str The string to parse.
920 * @param size Pointer to a uint64_t that will be filled with the
923 * @return 0 on success, -1 on failure.
926 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
935 DBG("utils_parse_size_suffix: received a NULL string.");
940 /* strtoull will accept a negative number, but we don't want to. */
941 if (strchr(str
, '-') != NULL
) {
942 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
947 /* str_end will point to the \0 */
948 str_end
= str
+ strlen(str
);
950 base_size
= strtoull(str
, &num_end
, 0);
952 PERROR("utils_parse_size_suffix strtoull");
957 if (num_end
== str
) {
958 /* strtoull parsed nothing, not good. */
959 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
964 /* Check if a prefix is present. */
982 DBG("utils_parse_size_suffix: invalid suffix.");
987 /* Check for garbage after the valid input. */
988 if (num_end
!= str_end
) {
989 DBG("utils_parse_size_suffix: Garbage after size string.");
994 *size
= base_size
<< shift
;
996 /* Check for overflow */
997 if ((*size
>> shift
) != base_size
) {
998 DBG("utils_parse_size_suffix: oops, overflow detected.");
1009 * Parse a string that represents a time in human readable format. It
1010 * supports decimal integers suffixed by 's', 'u', 'm', 'us', and 'ms'.
1012 * The suffix multiply the integer by:
1017 * Note that unit-less numbers are assumed to be microseconds.
1019 * @param str The string to parse, assumed to be NULL-terminated.
1020 * @param time_us Pointer to a uint64_t that will be filled with the
1021 * resulting time in microseconds.
1023 * @return 0 on success, -1 on failure.
1026 int utils_parse_time_suffix(char const * const str
, uint64_t * const time_us
)
1030 long multiplier
= 1;
1031 const char *str_end
;
1035 DBG("utils_parse_time_suffix: received a NULL string.");
1040 /* strtoull will accept a negative number, but we don't want to. */
1041 if (strchr(str
, '-') != NULL
) {
1042 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
1047 /* str_end will point to the \0 */
1048 str_end
= str
+ strlen(str
);
1050 base_time
= strtoull(str
, &num_end
, 10);
1052 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str
);
1057 if (num_end
== str
) {
1058 /* strtoull parsed nothing, not good. */
1059 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
1064 /* Check if a prefix is present. */
1068 /* Skip another letter in the 'us' case. */
1069 num_end
+= (*(num_end
+ 1) == 's') ? 2 : 1;
1073 /* Skip another letter in the 'ms' case. */
1074 num_end
+= (*(num_end
+ 1) == 's') ? 2 : 1;
1077 multiplier
= 1000000;
1083 DBG("utils_parse_time_suffix: invalid suffix.");
1088 /* Check for garbage after the valid input. */
1089 if (num_end
!= str_end
) {
1090 DBG("utils_parse_time_suffix: Garbage after time string.");
1095 *time_us
= base_time
* multiplier
;
1097 /* Check for overflow */
1098 if ((*time_us
/ multiplier
) != base_time
) {
1099 DBG("utils_parse_time_suffix: oops, overflow detected.");
1110 * fls: returns the position of the most significant bit.
1111 * Returns 0 if no bit is set, else returns the position of the most
1112 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
1114 #if defined(__i386) || defined(__x86_64)
1115 static inline unsigned int fls_u32(uint32_t x
)
1119 asm("bsrl %1,%0\n\t"
1123 : "=r" (r
) : "rm" (x
));
1129 #if defined(__x86_64)
1131 unsigned int fls_u64(uint64_t x
)
1135 asm("bsrq %1,%0\n\t"
1139 : "=r" (r
) : "rm" (x
));
1146 static __attribute__((unused
))
1147 unsigned int fls_u64(uint64_t x
)
1149 unsigned int r
= 64;
1154 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
1158 if (!(x
& 0xFFFF000000000000ULL
)) {
1162 if (!(x
& 0xFF00000000000000ULL
)) {
1166 if (!(x
& 0xF000000000000000ULL
)) {
1170 if (!(x
& 0xC000000000000000ULL
)) {
1174 if (!(x
& 0x8000000000000000ULL
)) {
1183 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
1185 unsigned int r
= 32;
1190 if (!(x
& 0xFFFF0000U
)) {
1194 if (!(x
& 0xFF000000U
)) {
1198 if (!(x
& 0xF0000000U
)) {
1202 if (!(x
& 0xC0000000U
)) {
1206 if (!(x
& 0x80000000U
)) {
1215 * Return the minimum order for which x <= (1UL << order).
1216 * Return -1 if x is 0.
1219 int utils_get_count_order_u32(uint32_t x
)
1225 return fls_u32(x
- 1);
1229 * Return the minimum order for which x <= (1UL << order).
1230 * Return -1 if x is 0.
1233 int utils_get_count_order_u64(uint64_t x
)
1239 return fls_u64(x
- 1);
1243 * Obtain the value of LTTNG_HOME environment variable, if exists.
1244 * Otherwise returns the value of HOME.
1247 char *utils_get_home_dir(void)
1252 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
1256 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
1261 /* Fallback on the password file entry. */
1262 pwd
= getpwuid(getuid());
1268 DBG3("Home directory is '%s'", val
);
1275 * Get user's home directory. Dynamically allocated, must be freed
1279 char *utils_get_user_home_dir(uid_t uid
)
1282 struct passwd
*result
;
1283 char *home_dir
= NULL
;
1288 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1293 buf
= zmalloc(buflen
);
1298 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
1299 if (ret
|| !result
) {
1300 if (ret
== ERANGE
) {
1308 home_dir
= strdup(pwd
.pw_dir
);
1315 * With the given format, fill dst with the time of len maximum siz.
1317 * Return amount of bytes set in the buffer or else 0 on error.
1320 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
1324 struct tm
*timeinfo
;
1329 /* Get date and time for session path */
1331 timeinfo
= localtime(&rawtime
);
1332 ret
= strftime(dst
, len
, format
, timeinfo
);
1334 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
1342 * Return the group ID matching name, else 0 if it cannot be found.
1345 gid_t
utils_get_group_id(const char *name
)
1349 grp
= getgrnam(name
);
1351 static volatile int warn_once
;
1354 WARN("No tracing group detected");
1363 * Return a newly allocated option string. This string is to be used as the
1364 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1365 * of elements in the long_options array. Returns NULL if the string's
1369 char *utils_generate_optstring(const struct option
*long_options
,
1373 size_t string_len
= opt_count
, str_pos
= 0;
1377 * Compute the necessary string length. One letter per option, two when an
1378 * argument is necessary, and a trailing NULL.
1380 for (i
= 0; i
< opt_count
; i
++) {
1381 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1384 optstring
= zmalloc(string_len
);
1389 for (i
= 0; i
< opt_count
; i
++) {
1390 if (!long_options
[i
].name
) {
1391 /* Got to the trailing NULL element */
1395 if (long_options
[i
].val
!= '\0') {
1396 optstring
[str_pos
++] = (char) long_options
[i
].val
;
1397 if (long_options
[i
].has_arg
) {
1398 optstring
[str_pos
++] = ':';
1408 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1409 * any file. Try to rmdir any empty directory within the hierarchy.
1412 int utils_recursive_rmdir(const char *path
)
1416 int dir_fd
, ret
= 0, closeret
, is_empty
= 1;
1417 struct dirent
*entry
;
1419 /* Open directory */
1420 dir
= opendir(path
);
1422 PERROR("Cannot open '%s' path", path
);
1425 dir_fd
= lttng_dirfd(dir
);
1427 PERROR("lttng_dirfd");
1431 path_len
= strlen(path
);
1432 while ((entry
= readdir(dir
))) {
1435 char filename
[PATH_MAX
];
1437 if (!strcmp(entry
->d_name
, ".")
1438 || !strcmp(entry
->d_name
, "..")) {
1442 name_len
= strlen(entry
->d_name
);
1443 if (path_len
+ name_len
+ 2 > sizeof(filename
)) {
1444 ERR("Failed to remove file: path name too long (%s/%s)",
1445 path
, entry
->d_name
);
1448 if (snprintf(filename
, sizeof(filename
), "%s/%s",
1449 path
, entry
->d_name
) < 0) {
1450 ERR("Failed to format path.");
1454 if (stat(filename
, &st
)) {
1459 if (S_ISDIR(st
.st_mode
)) {
1460 char subpath
[PATH_MAX
];
1462 strncpy(subpath
, path
, PATH_MAX
);
1463 subpath
[PATH_MAX
- 1] = '\0';
1464 strncat(subpath
, "/",
1465 PATH_MAX
- strlen(subpath
) - 1);
1466 strncat(subpath
, entry
->d_name
,
1467 PATH_MAX
- strlen(subpath
) - 1);
1468 if (utils_recursive_rmdir(subpath
)) {
1471 } else if (S_ISREG(st
.st_mode
)) {
1479 closeret
= closedir(dir
);
1484 DBG3("Attempting rmdir %s", path
);
1491 int utils_truncate_stream_file(int fd
, off_t length
)
1496 ret
= ftruncate(fd
, length
);
1498 PERROR("ftruncate");
1501 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1502 if (lseek_ret
< 0) {
1511 static const char *get_man_bin_path(void)
1513 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1516 return env_man_path
;
1519 return DEFAULT_MAN_BIN_PATH
;
1523 int utils_show_help(int section
, const char *page_name
,
1524 const char *help_msg
)
1526 char section_string
[8];
1527 const char *man_bin_path
= get_man_bin_path();
1531 printf("%s", help_msg
);
1535 /* Section integer -> section string */
1536 ret
= sprintf(section_string
, "%d", section
);
1537 assert(ret
> 0 && ret
< 8);
1540 * Execute man pager.
1542 * We provide -M to man here because LTTng-tools can
1543 * be installed outside /usr, in which case its man pages are
1544 * not located in the default /usr/share/man directory.
1546 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1547 section_string
, page_name
, NULL
);