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 <common/dynamic-buffer.h>
41 #include <lttng/constant.h>
48 * Return a partial realpath(3) of the path even if the full path does not
49 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
50 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
51 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
52 * point directory does not exist.
53 * In case resolved_path is NULL, the string returned was allocated in the
54 * function and thus need to be freed by the caller. The size argument allows
55 * to specify the size of the resolved_path argument if given, or the size to
59 char *utils_partial_realpath(const char *path
, char *resolved_path
, size_t size
)
61 char *cut_path
= NULL
, *try_path
= NULL
, *try_path_prev
= NULL
;
62 const char *next
, *prev
, *end
;
70 * Identify the end of the path, we don't want to treat the
71 * last char if it is a '/', we will just keep it on the side
72 * to be added at the end, and return a value coherent with
73 * the path given as argument
75 end
= path
+ strlen(path
);
76 if (*(end
-1) == '/') {
80 /* Initiate the values of the pointers before looping */
83 /* Only to ensure try_path is not NULL to enter the while */
84 try_path
= (char *)next
;
86 /* Resolve the canonical path of the first part of the path */
87 while (try_path
!= NULL
&& next
!= end
) {
88 char *try_path_buf
= NULL
;
91 * If there is not any '/' left, we want to try with
94 next
= strpbrk(next
+ 1, "/");
99 /* Cut the part we will be trying to resolve */
100 cut_path
= lttng_strndup(path
, next
- path
);
101 if (cut_path
== NULL
) {
102 PERROR("lttng_strndup");
106 try_path_buf
= zmalloc(LTTNG_PATH_MAX
);
112 /* Try to resolve this part */
113 try_path
= realpath((char *) cut_path
, try_path_buf
);
114 if (try_path
== NULL
) {
117 * There was an error, we just want to be assured it
118 * is linked to an unexistent directory, if it's another
119 * reason, we spawn an error
123 /* Ignore the error */
126 PERROR("realpath (partial_realpath)");
131 /* Save the place we are before trying the next step */
134 try_path_prev
= try_path
;
138 /* Free the allocated memory */
143 /* Allocate memory for the resolved path if necessary */
144 if (resolved_path
== NULL
) {
145 resolved_path
= zmalloc(size
);
146 if (resolved_path
== NULL
) {
147 PERROR("zmalloc resolved path");
153 * If we were able to solve at least partially the path, we can concatenate
154 * what worked and what didn't work
156 if (try_path_prev
!= NULL
) {
157 /* If we risk to concatenate two '/', we remove one of them */
158 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
159 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
163 * Duplicate the memory used by prev in case resolved_path and
164 * path are pointers for the same memory space
166 cut_path
= strdup(prev
);
167 if (cut_path
== NULL
) {
172 /* Concatenate the strings */
173 snprintf(resolved_path
, size
, "%s%s", try_path_prev
, cut_path
);
175 /* Free the allocated memory */
179 try_path_prev
= NULL
;
181 * Else, we just copy the path in our resolved_path to
185 strncpy(resolved_path
, path
, size
);
188 /* Then we return the 'partially' resolved path */
189 return resolved_path
;
195 if (try_path_prev
!= try_path
) {
202 * Make a full resolution of the given path even if it doesn't exist.
203 * This function uses the utils_partial_realpath function to resolve
204 * symlinks and relatives paths at the start of the string, and
205 * implements functionnalities to resolve the './' and '../' strings
206 * in the middle of a path. This function is only necessary because
207 * realpath(3) does not accept to resolve unexistent paths.
208 * The returned string was allocated in the function, it is thus of
209 * the responsibility of the caller to free this memory.
212 char *utils_expand_path(const char *path
)
214 char *next
, *previous
, *slash
, *start_path
, *absolute_path
= NULL
;
216 int is_dot
, is_dotdot
;
223 /* Allocate memory for the absolute_path */
224 absolute_path
= zmalloc(PATH_MAX
);
225 if (absolute_path
== NULL
) {
226 PERROR("zmalloc expand path");
231 * If the path is not already absolute nor explicitly relative,
232 * consider we're in the current directory
234 if (*path
!= '/' && strncmp(path
, "./", 2) != 0 &&
235 strncmp(path
, "../", 3) != 0) {
236 snprintf(absolute_path
, PATH_MAX
, "./%s", path
);
237 /* Else, we just copy the path */
239 strncpy(absolute_path
, path
, PATH_MAX
);
242 /* Resolve partially our path */
243 absolute_path
= utils_partial_realpath(absolute_path
,
244 absolute_path
, PATH_MAX
);
246 /* As long as we find '/./' in the working_path string */
247 while ((next
= strstr(absolute_path
, "/./"))) {
249 /* We prepare the start_path not containing it */
250 start_path
= lttng_strndup(absolute_path
, next
- absolute_path
);
252 PERROR("lttng_strndup");
255 /* And we concatenate it with the part after this string */
256 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 2);
261 /* As long as we find '/../' in the working_path string */
262 while ((next
= strstr(absolute_path
, "/../"))) {
263 /* We find the last level of directory */
264 previous
= absolute_path
;
265 while ((slash
= strpbrk(previous
, "/")) && slash
!= next
) {
266 previous
= slash
+ 1;
269 /* Then we prepare the start_path not containing it */
270 start_path
= lttng_strndup(absolute_path
, previous
- absolute_path
);
272 PERROR("lttng_strndup");
276 /* And we concatenate it with the part after the '/../' */
277 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 4);
279 /* We can free the memory used for the start path*/
282 /* Then we verify for symlinks using partial_realpath */
283 absolute_path
= utils_partial_realpath(absolute_path
,
284 absolute_path
, PATH_MAX
);
287 /* Identify the last token */
288 last_token
= strrchr(absolute_path
, '/');
290 /* Verify that this token is not a relative path */
291 is_dotdot
= (strcmp(last_token
, "/..") == 0);
292 is_dot
= (strcmp(last_token
, "/.") == 0);
294 /* If it is, take action */
295 if (is_dot
|| is_dotdot
) {
296 /* For both, remove this token */
299 /* If it was a reference to parent directory, go back one more time */
301 last_token
= strrchr(absolute_path
, '/');
303 /* If there was only one level left, we keep the first '/' */
304 if (last_token
== absolute_path
) {
312 return absolute_path
;
320 * Create a pipe in dst.
323 int utils_create_pipe(int *dst
)
333 PERROR("create pipe");
340 * Create pipe and set CLOEXEC flag to both fd.
342 * Make sure the pipe opened by this function are closed at some point. Use
343 * utils_close_pipe().
346 int utils_create_pipe_cloexec(int *dst
)
354 ret
= utils_create_pipe(dst
);
359 for (i
= 0; i
< 2; i
++) {
360 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
362 PERROR("fcntl pipe cloexec");
372 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
374 * Make sure the pipe opened by this function are closed at some point. Use
375 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
376 * support OSes other than Linux 2.6.23+.
379 int utils_create_pipe_cloexec_nonblock(int *dst
)
387 ret
= utils_create_pipe(dst
);
392 for (i
= 0; i
< 2; i
++) {
393 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
395 PERROR("fcntl pipe cloexec");
399 * Note: we override any flag that could have been
400 * previously set on the fd.
402 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
404 PERROR("fcntl pipe nonblock");
414 * Close both read and write side of the pipe.
417 void utils_close_pipe(int *src
)
425 for (i
= 0; i
< 2; i
++) {
433 PERROR("close pipe");
440 * Create a new string using two strings range.
443 char *utils_strdupdelim(const char *begin
, const char *end
)
447 str
= zmalloc(end
- begin
+ 1);
449 PERROR("zmalloc strdupdelim");
453 memcpy(str
, begin
, end
- begin
);
454 str
[end
- begin
] = '\0';
461 * Set CLOEXEC flag to the give file descriptor.
464 int utils_set_fd_cloexec(int fd
)
473 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
475 PERROR("fcntl cloexec");
484 * Create pid file to the given path and filename.
487 int utils_create_pid_file(pid_t pid
, const char *filepath
)
494 fp
= fopen(filepath
, "w");
496 PERROR("open pid file %s", filepath
);
501 ret
= fprintf(fp
, "%d\n", (int) pid
);
503 PERROR("fprintf pid file");
510 DBG("Pid %d written in file %s", (int) pid
, filepath
);
517 * Create lock file to the given path and filename.
518 * Returns the associated file descriptor, -1 on error.
521 int utils_create_lock_file(const char *filepath
)
529 memset(&lock
, 0, sizeof(lock
));
530 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
533 PERROR("open lock file %s", filepath
);
539 * Attempt to lock the file. If this fails, there is
540 * already a process using the same lock file running
541 * and we should exit.
543 lock
.l_whence
= SEEK_SET
;
544 lock
.l_type
= F_WRLCK
;
546 ret
= fcntl(fd
, F_SETLK
, &lock
);
548 PERROR("fcntl lock file");
549 ERR("Could not get lock file %s, another instance is running.",
552 PERROR("close lock file");
563 * On some filesystems (e.g. nfs), mkdir will validate access rights before
564 * checking for the existence of the path element. This means that on a setup
565 * where "/home/" is a mounted NFS share, and running as an unpriviledged user,
566 * recursively creating a path of the form "/home/my_user/trace/" will fail with
567 * EACCES on mkdir("/home", ...).
569 * Performing a stat(...) on the path to check for existence allows us to
570 * work around this behaviour.
573 int mkdir_check_exists(const char *path
, mode_t mode
)
578 ret
= stat(path
, &st
);
580 if (S_ISDIR(st
.st_mode
)) {
581 /* Directory exists, skip. */
584 /* Exists, but is not a directory. */
592 * Let mkdir handle other errors as the caller expects mkdir
595 ret
= mkdir(path
, mode
);
601 * Create directory using the given path and mode.
603 * On success, return 0 else a negative error code.
606 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
610 if (uid
< 0 || gid
< 0) {
611 ret
= mkdir_check_exists(path
, mode
);
613 ret
= run_as_mkdir(path
, mode
, uid
, gid
);
616 if (errno
!= EEXIST
) {
617 PERROR("mkdir %s, uid %d, gid %d", path
? path
: "NULL",
628 * Internal version of mkdir_recursive. Runs as the current user.
629 * Don't call directly; use utils_mkdir_recursive().
631 * This function is ominously marked as "unsafe" since it should only
632 * be called by a caller that has transitioned to the uid and gid under which
633 * the directory creation should occur.
636 int _utils_mkdir_recursive_unsafe(const char *path
, mode_t mode
)
638 char *p
, tmp
[PATH_MAX
];
644 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
646 PERROR("snprintf mkdir");
651 if (tmp
[len
- 1] == '/') {
655 for (p
= tmp
+ 1; *p
; p
++) {
658 if (tmp
[strlen(tmp
) - 1] == '.' &&
659 tmp
[strlen(tmp
) - 2] == '.' &&
660 tmp
[strlen(tmp
) - 3] == '/') {
661 ERR("Using '/../' is not permitted in the trace path (%s)",
666 ret
= mkdir_check_exists(tmp
, mode
);
668 if (errno
!= EACCES
) {
669 PERROR("mkdir recursive");
678 ret
= mkdir_check_exists(tmp
, mode
);
680 PERROR("mkdir recursive last element");
689 * Recursively create directory using the given path and mode, under the
690 * provided uid and gid.
692 * On success, return 0 else a negative error code.
695 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
699 if (uid
< 0 || gid
< 0) {
700 /* Run as current user. */
701 ret
= _utils_mkdir_recursive_unsafe(path
, mode
);
703 ret
= run_as_mkdir_recursive(path
, mode
, uid
, gid
);
706 PERROR("mkdir %s, uid %d, gid %d", path
? path
: "NULL",
714 * path is the output parameter. It needs to be PATH_MAX len.
716 * Return 0 on success or else a negative value.
718 static int utils_stream_file_name(char *path
,
719 const char *path_name
, const char *file_name
,
720 uint64_t size
, uint64_t count
,
724 char full_path
[PATH_MAX
];
725 char *path_name_suffix
= NULL
;
728 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
729 path_name
, file_name
);
731 PERROR("snprintf create output file");
735 /* Setup extra string if suffix or/and a count is needed. */
736 if (size
> 0 && suffix
) {
737 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
738 } else if (size
> 0) {
739 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
741 ret
= asprintf(&extra
, "%s", suffix
);
744 PERROR("Allocating extra string to name");
749 * If we split the trace in multiple files, we have to add the count at
750 * the end of the tracefile name.
753 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
755 PERROR("Allocating path name with extra string");
756 goto error_free_suffix
;
758 strncpy(path
, path_name_suffix
, PATH_MAX
- 1);
759 path
[PATH_MAX
- 1] = '\0';
761 strncpy(path
, full_path
, PATH_MAX
- 1);
763 path
[PATH_MAX
- 1] = '\0';
766 free(path_name_suffix
);
774 * Create the stream file on disk.
776 * Return 0 on success or else a negative value.
779 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
780 uint64_t count
, int uid
, int gid
, char *suffix
)
782 int ret
, flags
, mode
;
785 ret
= utils_stream_file_name(path
, path_name
, file_name
,
786 size
, count
, suffix
);
791 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
792 /* Open with 660 mode */
793 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
795 if (uid
< 0 || gid
< 0) {
796 ret
= open(path
, flags
, mode
);
798 ret
= run_as_open(path
, flags
, mode
, uid
, gid
);
801 PERROR("open stream path %s", path
);
808 * Unlink the stream tracefile from disk.
810 * Return 0 on success or else a negative value.
813 int utils_unlink_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
814 uint64_t count
, int uid
, int gid
, char *suffix
)
819 ret
= utils_stream_file_name(path
, path_name
, file_name
,
820 size
, count
, suffix
);
824 if (uid
< 0 || gid
< 0) {
827 ret
= run_as_unlink(path
, uid
, gid
);
833 DBG("utils_unlink_stream_file %s returns %d", path
, ret
);
838 * Change the output tracefile according to the given size and count The
839 * new_count pointer is set during this operation.
841 * From the consumer, the stream lock MUST be held before calling this function
842 * because we are modifying the stream status.
844 * Return 0 on success or else a negative value.
847 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
848 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
857 PERROR("Closing tracefile");
864 * In tracefile rotation, for the relay daemon we need
865 * to unlink the old file if present, because it may
866 * still be open in reading by the live thread, and we
867 * need to ensure that we do not overwrite the content
868 * between get_index and get_packet. Since we have no
869 * way to verify integrity of the data content compared
870 * to the associated index, we need to ensure the reader
871 * has exclusive access to the file content, and that
872 * the open of the data file is performed in get_index.
873 * Unlinking the old file rather than overwriting it
877 *new_count
= (*new_count
+ 1) % count
;
879 ret
= utils_unlink_stream_file(path_name
, file_name
, size
,
880 new_count
? *new_count
: 0, uid
, gid
, 0);
881 if (ret
< 0 && errno
!= ENOENT
) {
890 ret
= utils_create_stream_file(path_name
, file_name
, size
,
891 new_count
? *new_count
: 0, uid
, gid
, 0);
906 * Parse a string that represents a size in human readable format. It
907 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
909 * The suffix multiply the integer by:
914 * @param str The string to parse.
915 * @param size Pointer to a uint64_t that will be filled with the
918 * @return 0 on success, -1 on failure.
921 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
930 DBG("utils_parse_size_suffix: received a NULL string.");
935 /* strtoull will accept a negative number, but we don't want to. */
936 if (strchr(str
, '-') != NULL
) {
937 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
942 /* str_end will point to the \0 */
943 str_end
= str
+ strlen(str
);
945 base_size
= strtoull(str
, &num_end
, 0);
947 PERROR("utils_parse_size_suffix strtoull");
952 if (num_end
== str
) {
953 /* strtoull parsed nothing, not good. */
954 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
959 /* Check if a prefix is present. */
977 DBG("utils_parse_size_suffix: invalid suffix.");
982 /* Check for garbage after the valid input. */
983 if (num_end
!= str_end
) {
984 DBG("utils_parse_size_suffix: Garbage after size string.");
989 *size
= base_size
<< shift
;
991 /* Check for overflow */
992 if ((*size
>> shift
) != base_size
) {
993 DBG("utils_parse_size_suffix: oops, overflow detected.");
1004 * fls: returns the position of the most significant bit.
1005 * Returns 0 if no bit is set, else returns the position of the most
1006 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
1008 #if defined(__i386) || defined(__x86_64)
1009 static inline unsigned int fls_u32(uint32_t x
)
1013 asm("bsrl %1,%0\n\t"
1017 : "=r" (r
) : "rm" (x
));
1023 #if defined(__x86_64)
1025 unsigned int fls_u64(uint64_t x
)
1029 asm("bsrq %1,%0\n\t"
1033 : "=r" (r
) : "rm" (x
));
1040 static __attribute__((unused
))
1041 unsigned int fls_u64(uint64_t x
)
1043 unsigned int r
= 64;
1048 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
1052 if (!(x
& 0xFFFF000000000000ULL
)) {
1056 if (!(x
& 0xFF00000000000000ULL
)) {
1060 if (!(x
& 0xF000000000000000ULL
)) {
1064 if (!(x
& 0xC000000000000000ULL
)) {
1068 if (!(x
& 0x8000000000000000ULL
)) {
1077 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
1079 unsigned int r
= 32;
1084 if (!(x
& 0xFFFF0000U
)) {
1088 if (!(x
& 0xFF000000U
)) {
1092 if (!(x
& 0xF0000000U
)) {
1096 if (!(x
& 0xC0000000U
)) {
1100 if (!(x
& 0x80000000U
)) {
1109 * Return the minimum order for which x <= (1UL << order).
1110 * Return -1 if x is 0.
1113 int utils_get_count_order_u32(uint32_t x
)
1119 return fls_u32(x
- 1);
1123 * Return the minimum order for which x <= (1UL << order).
1124 * Return -1 if x is 0.
1127 int utils_get_count_order_u64(uint64_t x
)
1133 return fls_u64(x
- 1);
1137 * Obtain the value of LTTNG_HOME environment variable, if exists.
1138 * Otherwise returns the value of HOME.
1141 char *utils_get_home_dir(void)
1146 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
1150 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
1155 /* Fallback on the password file entry. */
1156 pwd
= getpwuid(getuid());
1162 DBG3("Home directory is '%s'", val
);
1169 * Get user's home directory. Dynamically allocated, must be freed
1173 char *utils_get_user_home_dir(uid_t uid
)
1176 struct passwd
*result
;
1177 char *home_dir
= NULL
;
1182 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1187 buf
= zmalloc(buflen
);
1192 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
1193 if (ret
|| !result
) {
1194 if (ret
== ERANGE
) {
1202 home_dir
= strdup(pwd
.pw_dir
);
1209 * With the given format, fill dst with the time of len maximum siz.
1211 * Return amount of bytes set in the buffer or else 0 on error.
1214 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
1218 struct tm
*timeinfo
;
1223 /* Get date and time for session path */
1225 timeinfo
= localtime(&rawtime
);
1226 ret
= strftime(dst
, len
, format
, timeinfo
);
1228 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
1236 * Return 0 on success and set *gid to the group_ID matching the passed name.
1237 * Else -1 if it cannot be found or an error occurred.
1240 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
1242 static volatile int warn_once
;
1247 struct group
*result
;
1248 struct lttng_dynamic_buffer buffer
;
1250 /* Get the system limit, if it exists. */
1251 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1252 if (sys_len
== -1) {
1255 len
= (size_t) sys_len
;
1258 lttng_dynamic_buffer_init(&buffer
);
1259 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
1261 ERR("Failed to allocate group info buffer");
1266 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
1267 const size_t new_len
= 2 * buffer
.size
;
1269 /* Buffer is not big enough, increase its size. */
1270 if (new_len
< buffer
.size
) {
1271 ERR("Group info buffer size overflow");
1276 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
1278 ERR("Failed to grow group info buffer to %zu bytes",
1285 PERROR("Failed to get group file entry for group name \"%s\"",
1291 /* Group not found. */
1297 *gid
= result
->gr_gid
;
1301 if (ret
&& warn
&& !warn_once
) {
1302 WARN("No tracing group detected");
1305 lttng_dynamic_buffer_reset(&buffer
);
1310 * Return a newly allocated option string. This string is to be used as the
1311 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1312 * of elements in the long_options array. Returns NULL if the string's
1316 char *utils_generate_optstring(const struct option
*long_options
,
1320 size_t string_len
= opt_count
, str_pos
= 0;
1324 * Compute the necessary string length. One letter per option, two when an
1325 * argument is necessary, and a trailing NULL.
1327 for (i
= 0; i
< opt_count
; i
++) {
1328 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1331 optstring
= zmalloc(string_len
);
1336 for (i
= 0; i
< opt_count
; i
++) {
1337 if (!long_options
[i
].name
) {
1338 /* Got to the trailing NULL element */
1342 if (long_options
[i
].val
!= '\0') {
1343 optstring
[str_pos
++] = (char) long_options
[i
].val
;
1344 if (long_options
[i
].has_arg
) {
1345 optstring
[str_pos
++] = ':';
1355 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1356 * any file. Try to rmdir any empty directory within the hierarchy.
1359 int utils_recursive_rmdir(const char *path
)
1363 int dir_fd
, ret
= 0, closeret
, is_empty
= 1;
1364 struct dirent
*entry
;
1366 /* Open directory */
1367 dir
= opendir(path
);
1369 PERROR("Cannot open '%s' path", path
);
1372 dir_fd
= lttng_dirfd(dir
);
1374 PERROR("lttng_dirfd");
1378 path_len
= strlen(path
);
1379 while ((entry
= readdir(dir
))) {
1382 char filename
[PATH_MAX
];
1384 if (!strcmp(entry
->d_name
, ".")
1385 || !strcmp(entry
->d_name
, "..")) {
1389 name_len
= strlen(entry
->d_name
);
1390 if (path_len
+ name_len
+ 2 > sizeof(filename
)) {
1391 ERR("Failed to remove file: path name too long (%s/%s)",
1392 path
, entry
->d_name
);
1395 if (snprintf(filename
, sizeof(filename
), "%s/%s",
1396 path
, entry
->d_name
) < 0) {
1397 ERR("Failed to format path.");
1401 if (stat(filename
, &st
)) {
1406 if (S_ISDIR(st
.st_mode
)) {
1407 char subpath
[PATH_MAX
];
1409 strncpy(subpath
, path
, PATH_MAX
);
1410 subpath
[PATH_MAX
- 1] = '\0';
1411 strncat(subpath
, "/",
1412 PATH_MAX
- strlen(subpath
) - 1);
1413 strncat(subpath
, entry
->d_name
,
1414 PATH_MAX
- strlen(subpath
) - 1);
1415 if (utils_recursive_rmdir(subpath
)) {
1418 } else if (S_ISREG(st
.st_mode
)) {
1426 closeret
= closedir(dir
);
1431 DBG3("Attempting rmdir %s", path
);
1438 int utils_truncate_stream_file(int fd
, off_t length
)
1443 ret
= ftruncate(fd
, length
);
1445 PERROR("ftruncate");
1448 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1449 if (lseek_ret
< 0) {
1458 static const char *get_man_bin_path(void)
1460 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1463 return env_man_path
;
1466 return DEFAULT_MAN_BIN_PATH
;
1470 int utils_show_help(int section
, const char *page_name
,
1471 const char *help_msg
)
1473 char section_string
[8];
1474 const char *man_bin_path
= get_man_bin_path();
1478 printf("%s", help_msg
);
1482 /* Section integer -> section string */
1483 ret
= sprintf(section_string
, "%d", section
);
1484 assert(ret
> 0 && ret
< 8);
1487 * Execute man pager.
1489 * We provide -M to man here because LTTng-tools can
1490 * be installed outside /usr, in which case its man pages are
1491 * not located in the default /usr/share/man directory.
1493 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1494 section_string
, page_name
, NULL
);
1501 int timespec_to_ms(struct timespec ts
, unsigned long *ms
)
1503 unsigned long res
, remain_ms
;
1505 if (ts
.tv_sec
> ULONG_MAX
/ MSEC_PER_SEC
) {
1507 return -1; /* multiplication overflow */
1509 res
= ts
.tv_sec
* MSEC_PER_SEC
;
1510 remain_ms
= ULONG_MAX
- res
;
1511 if (ts
.tv_nsec
/ NSEC_PER_MSEC
> remain_ms
) {
1513 return -1; /* addition overflow */
1515 res
+= ts
.tv_nsec
/ NSEC_PER_MSEC
;
1521 struct timespec
timespec_abs_diff(struct timespec t1
, struct timespec t2
)
1523 uint64_t ts1
= (uint64_t) t1
.tv_sec
* (uint64_t) NSEC_PER_SEC
+
1524 (uint64_t) t1
.tv_nsec
;
1525 uint64_t ts2
= (uint64_t) t2
.tv_sec
* (uint64_t) NSEC_PER_SEC
+
1526 (uint64_t) t2
.tv_nsec
;
1527 uint64_t diff
= max(ts1
, ts2
) - min(ts1
, ts2
);
1528 struct timespec res
;
1530 res
.tv_sec
= diff
/ (uint64_t) NSEC_PER_SEC
;
1531 res
.tv_nsec
= diff
% (uint64_t) NSEC_PER_SEC
;