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");
439 * Create a new string using two strings range.
442 char *utils_strdupdelim(const char *begin
, const char *end
)
446 str
= zmalloc(end
- begin
+ 1);
448 PERROR("zmalloc strdupdelim");
452 memcpy(str
, begin
, end
- begin
);
453 str
[end
- begin
] = '\0';
460 * Set CLOEXEC flag to the give file descriptor.
463 int utils_set_fd_cloexec(int fd
)
472 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
474 PERROR("fcntl cloexec");
483 * Create pid file to the given path and filename.
486 int utils_create_pid_file(pid_t pid
, const char *filepath
)
493 fp
= fopen(filepath
, "w");
495 PERROR("open pid file %s", filepath
);
500 ret
= fprintf(fp
, "%d\n", (int) pid
);
502 PERROR("fprintf pid file");
509 DBG("Pid %d written in file %s", (int) pid
, filepath
);
516 * Create lock file to the given path and filename.
517 * Returns the associated file descriptor, -1 on error.
520 int utils_create_lock_file(const char *filepath
)
528 memset(&lock
, 0, sizeof(lock
));
529 fd
= open(filepath
, O_CREAT
| O_WRONLY
, S_IRUSR
| S_IWUSR
|
532 PERROR("open lock file %s", filepath
);
538 * Attempt to lock the file. If this fails, there is
539 * already a process using the same lock file running
540 * and we should exit.
542 lock
.l_whence
= SEEK_SET
;
543 lock
.l_type
= F_WRLCK
;
545 ret
= fcntl(fd
, F_SETLK
, &lock
);
547 PERROR("fcntl lock file");
548 ERR("Could not get lock file %s, another instance is running.",
551 PERROR("close lock file");
562 * On some filesystems (e.g. nfs), mkdir will validate access rights before
563 * checking for the existence of the path element. This means that on a setup
564 * where "/home/" is a mounted NFS share, and running as an unpriviledged user,
565 * recursively creating a path of the form "/home/my_user/trace/" will fail with
566 * EACCES on mkdir("/home", ...).
568 * Performing a stat(...) on the path to check for existence allows us to
569 * work around this behaviour.
572 int mkdir_check_exists(const char *path
, mode_t mode
)
577 ret
= stat(path
, &st
);
579 if (S_ISDIR(st
.st_mode
)) {
580 /* Directory exists, skip. */
583 /* Exists, but is not a directory. */
591 * Let mkdir handle other errors as the caller expects mkdir
594 ret
= mkdir(path
, mode
);
600 * Create directory using the given path and mode.
602 * On success, return 0 else a negative error code.
605 int utils_mkdir(const char *path
, mode_t mode
, int uid
, int gid
)
609 if (uid
< 0 || gid
< 0) {
610 ret
= mkdir_check_exists(path
, mode
);
612 ret
= run_as_mkdir(path
, mode
, uid
, gid
);
615 if (errno
!= EEXIST
) {
616 PERROR("mkdir %s, uid %d, gid %d", path
? path
: "NULL",
627 * Internal version of mkdir_recursive. Runs as the current user.
628 * Don't call directly; use utils_mkdir_recursive().
630 * This function is ominously marked as "unsafe" since it should only
631 * be called by a caller that has transitioned to the uid and gid under which
632 * the directory creation should occur.
635 int _utils_mkdir_recursive_unsafe(const char *path
, mode_t mode
)
637 char *p
, tmp
[PATH_MAX
];
643 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
645 PERROR("snprintf mkdir");
650 if (tmp
[len
- 1] == '/') {
654 for (p
= tmp
+ 1; *p
; p
++) {
657 if (tmp
[strlen(tmp
) - 1] == '.' &&
658 tmp
[strlen(tmp
) - 2] == '.' &&
659 tmp
[strlen(tmp
) - 3] == '/') {
660 ERR("Using '/../' is not permitted in the trace path (%s)",
665 ret
= mkdir_check_exists(tmp
, mode
);
667 if (errno
!= EACCES
) {
668 PERROR("mkdir recursive");
677 ret
= mkdir_check_exists(tmp
, mode
);
679 PERROR("mkdir recursive last element");
688 * Recursively create directory using the given path and mode, under the
689 * provided uid and gid.
691 * On success, return 0 else a negative error code.
694 int utils_mkdir_recursive(const char *path
, mode_t mode
, int uid
, int gid
)
698 if (uid
< 0 || gid
< 0) {
699 /* Run as current user. */
700 ret
= _utils_mkdir_recursive_unsafe(path
, mode
);
702 ret
= run_as_mkdir_recursive(path
, mode
, uid
, gid
);
705 PERROR("mkdir %s, uid %d, gid %d", path
? path
: "NULL",
713 * path is the output parameter. It needs to be PATH_MAX len.
715 * Return 0 on success or else a negative value.
717 static int utils_stream_file_name(char *path
,
718 const char *path_name
, const char *file_name
,
719 uint64_t size
, uint64_t count
,
723 char full_path
[PATH_MAX
];
724 char *path_name_suffix
= NULL
;
727 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
728 path_name
, file_name
);
730 PERROR("snprintf create output file");
734 /* Setup extra string if suffix or/and a count is needed. */
735 if (size
> 0 && suffix
) {
736 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
737 } else if (size
> 0) {
738 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
740 ret
= asprintf(&extra
, "%s", suffix
);
743 PERROR("Allocating extra string to name");
748 * If we split the trace in multiple files, we have to add the count at
749 * the end of the tracefile name.
752 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
754 PERROR("Allocating path name with extra string");
755 goto error_free_suffix
;
757 strncpy(path
, path_name_suffix
, PATH_MAX
- 1);
758 path
[PATH_MAX
- 1] = '\0';
760 strncpy(path
, full_path
, PATH_MAX
- 1);
762 path
[PATH_MAX
- 1] = '\0';
765 free(path_name_suffix
);
773 * Create the stream file on disk.
775 * Return 0 on success or else a negative value.
778 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
779 uint64_t count
, int uid
, int gid
, char *suffix
)
781 int ret
, flags
, mode
;
784 ret
= utils_stream_file_name(path
, path_name
, file_name
,
785 size
, count
, suffix
);
790 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
791 /* Open with 660 mode */
792 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
794 if (uid
< 0 || gid
< 0) {
795 ret
= open(path
, flags
, mode
);
797 ret
= run_as_open(path
, flags
, mode
, uid
, gid
);
800 PERROR("open stream path %s", path
);
807 * Unlink the stream tracefile from disk.
809 * Return 0 on success or else a negative value.
812 int utils_unlink_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
813 uint64_t count
, int uid
, int gid
, char *suffix
)
818 ret
= utils_stream_file_name(path
, path_name
, file_name
,
819 size
, count
, suffix
);
823 if (uid
< 0 || gid
< 0) {
826 ret
= run_as_unlink(path
, uid
, gid
);
832 DBG("utils_unlink_stream_file %s returns %d", path
, ret
);
837 * Change the output tracefile according to the given size and count The
838 * new_count pointer is set during this operation.
840 * From the consumer, the stream lock MUST be held before calling this function
841 * because we are modifying the stream status.
843 * Return 0 on success or else a negative value.
846 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
847 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
856 PERROR("Closing tracefile");
863 * In tracefile rotation, for the relay daemon we need
864 * to unlink the old file if present, because it may
865 * still be open in reading by the live thread, and we
866 * need to ensure that we do not overwrite the content
867 * between get_index and get_packet. Since we have no
868 * way to verify integrity of the data content compared
869 * to the associated index, we need to ensure the reader
870 * has exclusive access to the file content, and that
871 * the open of the data file is performed in get_index.
872 * Unlinking the old file rather than overwriting it
876 *new_count
= (*new_count
+ 1) % count
;
878 ret
= utils_unlink_stream_file(path_name
, file_name
, size
,
879 new_count
? *new_count
: 0, uid
, gid
, 0);
880 if (ret
< 0 && errno
!= ENOENT
) {
889 ret
= utils_create_stream_file(path_name
, file_name
, size
,
890 new_count
? *new_count
: 0, uid
, gid
, 0);
905 * Parse a string that represents a size in human readable format. It
906 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
908 * The suffix multiply the integer by:
913 * @param str The string to parse.
914 * @param size Pointer to a uint64_t that will be filled with the
917 * @return 0 on success, -1 on failure.
920 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
929 DBG("utils_parse_size_suffix: received a NULL string.");
934 /* strtoull will accept a negative number, but we don't want to. */
935 if (strchr(str
, '-') != NULL
) {
936 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
941 /* str_end will point to the \0 */
942 str_end
= str
+ strlen(str
);
944 base_size
= strtoull(str
, &num_end
, 0);
946 PERROR("utils_parse_size_suffix strtoull");
951 if (num_end
== str
) {
952 /* strtoull parsed nothing, not good. */
953 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
958 /* Check if a prefix is present. */
976 DBG("utils_parse_size_suffix: invalid suffix.");
981 /* Check for garbage after the valid input. */
982 if (num_end
!= str_end
) {
983 DBG("utils_parse_size_suffix: Garbage after size string.");
988 *size
= base_size
<< shift
;
990 /* Check for overflow */
991 if ((*size
>> shift
) != base_size
) {
992 DBG("utils_parse_size_suffix: oops, overflow detected.");
1003 * fls: returns the position of the most significant bit.
1004 * Returns 0 if no bit is set, else returns the position of the most
1005 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
1007 #if defined(__i386) || defined(__x86_64)
1008 static inline unsigned int fls_u32(uint32_t x
)
1012 asm("bsrl %1,%0\n\t"
1016 : "=r" (r
) : "rm" (x
));
1022 #if defined(__x86_64)
1024 unsigned int fls_u64(uint64_t x
)
1028 asm("bsrq %1,%0\n\t"
1032 : "=r" (r
) : "rm" (x
));
1039 static __attribute__((unused
))
1040 unsigned int fls_u64(uint64_t x
)
1042 unsigned int r
= 64;
1047 if (!(x
& 0xFFFFFFFF00000000ULL
)) {
1051 if (!(x
& 0xFFFF000000000000ULL
)) {
1055 if (!(x
& 0xFF00000000000000ULL
)) {
1059 if (!(x
& 0xF000000000000000ULL
)) {
1063 if (!(x
& 0xC000000000000000ULL
)) {
1067 if (!(x
& 0x8000000000000000ULL
)) {
1076 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
1078 unsigned int r
= 32;
1083 if (!(x
& 0xFFFF0000U
)) {
1087 if (!(x
& 0xFF000000U
)) {
1091 if (!(x
& 0xF0000000U
)) {
1095 if (!(x
& 0xC0000000U
)) {
1099 if (!(x
& 0x80000000U
)) {
1108 * Return the minimum order for which x <= (1UL << order).
1109 * Return -1 if x is 0.
1112 int utils_get_count_order_u32(uint32_t x
)
1118 return fls_u32(x
- 1);
1122 * Return the minimum order for which x <= (1UL << order).
1123 * Return -1 if x is 0.
1126 int utils_get_count_order_u64(uint64_t x
)
1132 return fls_u64(x
- 1);
1136 * Obtain the value of LTTNG_HOME environment variable, if exists.
1137 * Otherwise returns the value of HOME.
1140 char *utils_get_home_dir(void)
1145 val
= lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
1149 val
= lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
1154 /* Fallback on the password file entry. */
1155 pwd
= getpwuid(getuid());
1161 DBG3("Home directory is '%s'", val
);
1168 * Get user's home directory. Dynamically allocated, must be freed
1172 char *utils_get_user_home_dir(uid_t uid
)
1175 struct passwd
*result
;
1176 char *home_dir
= NULL
;
1181 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1186 buf
= zmalloc(buflen
);
1191 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
1192 if (ret
|| !result
) {
1193 if (ret
== ERANGE
) {
1201 home_dir
= strdup(pwd
.pw_dir
);
1208 * With the given format, fill dst with the time of len maximum siz.
1210 * Return amount of bytes set in the buffer or else 0 on error.
1213 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
1217 struct tm
*timeinfo
;
1222 /* Get date and time for session path */
1224 timeinfo
= localtime(&rawtime
);
1225 ret
= strftime(dst
, len
, format
, timeinfo
);
1227 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
1235 * Return 0 on success and set *gid to the group_ID matching the passed name.
1236 * Else -1 if it cannot be found or an error occurred.
1239 int utils_get_group_id(const char *name
, bool warn
, gid_t
*gid
)
1241 static volatile int warn_once
;
1246 struct group
*result
;
1247 struct lttng_dynamic_buffer buffer
;
1249 /* Get the system limit, if it exists. */
1250 sys_len
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1251 if (sys_len
== -1) {
1254 len
= (size_t) sys_len
;
1257 lttng_dynamic_buffer_init(&buffer
);
1258 ret
= lttng_dynamic_buffer_set_size(&buffer
, len
);
1260 ERR("Failed to allocate group info buffer");
1265 while ((ret
= getgrnam_r(name
, &grp
, buffer
.data
, buffer
.size
, &result
)) == ERANGE
) {
1266 const size_t new_len
= 2 * buffer
.size
;
1268 /* Buffer is not big enough, increase its size. */
1269 if (new_len
< buffer
.size
) {
1270 ERR("Group info buffer size overflow");
1275 ret
= lttng_dynamic_buffer_set_size(&buffer
, new_len
);
1277 ERR("Failed to grow group info buffer to %zu bytes",
1284 PERROR("Failed to get group file entry for group name \"%s\"",
1290 /* Group not found. */
1296 *gid
= result
->gr_gid
;
1300 if (ret
&& warn
&& !warn_once
) {
1301 WARN("No tracing group detected");
1304 lttng_dynamic_buffer_reset(&buffer
);
1309 * Return a newly allocated option string. This string is to be used as the
1310 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1311 * of elements in the long_options array. Returns NULL if the string's
1315 char *utils_generate_optstring(const struct option
*long_options
,
1319 size_t string_len
= opt_count
, str_pos
= 0;
1323 * Compute the necessary string length. One letter per option, two when an
1324 * argument is necessary, and a trailing NULL.
1326 for (i
= 0; i
< opt_count
; i
++) {
1327 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1330 optstring
= zmalloc(string_len
);
1335 for (i
= 0; i
< opt_count
; i
++) {
1336 if (!long_options
[i
].name
) {
1337 /* Got to the trailing NULL element */
1341 if (long_options
[i
].val
!= '\0') {
1342 optstring
[str_pos
++] = (char) long_options
[i
].val
;
1343 if (long_options
[i
].has_arg
) {
1344 optstring
[str_pos
++] = ':';
1354 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
1355 * any file. Try to rmdir any empty directory within the hierarchy.
1358 int utils_recursive_rmdir(const char *path
)
1362 int dir_fd
, ret
= 0, closeret
, is_empty
= 1;
1363 struct dirent
*entry
;
1365 /* Open directory */
1366 dir
= opendir(path
);
1368 PERROR("Cannot open '%s' path", path
);
1371 dir_fd
= lttng_dirfd(dir
);
1373 PERROR("lttng_dirfd");
1377 path_len
= strlen(path
);
1378 while ((entry
= readdir(dir
))) {
1381 char filename
[PATH_MAX
];
1383 if (!strcmp(entry
->d_name
, ".")
1384 || !strcmp(entry
->d_name
, "..")) {
1388 name_len
= strlen(entry
->d_name
);
1389 if (path_len
+ name_len
+ 2 > sizeof(filename
)) {
1390 ERR("Failed to remove file: path name too long (%s/%s)",
1391 path
, entry
->d_name
);
1394 if (snprintf(filename
, sizeof(filename
), "%s/%s",
1395 path
, entry
->d_name
) < 0) {
1396 ERR("Failed to format path.");
1400 if (stat(filename
, &st
)) {
1405 if (S_ISDIR(st
.st_mode
)) {
1406 char subpath
[PATH_MAX
];
1408 strncpy(subpath
, path
, PATH_MAX
);
1409 subpath
[PATH_MAX
- 1] = '\0';
1410 strncat(subpath
, "/",
1411 PATH_MAX
- strlen(subpath
) - 1);
1412 strncat(subpath
, entry
->d_name
,
1413 PATH_MAX
- strlen(subpath
) - 1);
1414 if (utils_recursive_rmdir(subpath
)) {
1417 } else if (S_ISREG(st
.st_mode
)) {
1425 closeret
= closedir(dir
);
1430 DBG3("Attempting rmdir %s", path
);
1437 int utils_truncate_stream_file(int fd
, off_t length
)
1442 ret
= ftruncate(fd
, length
);
1444 PERROR("ftruncate");
1447 lseek_ret
= lseek(fd
, length
, SEEK_SET
);
1448 if (lseek_ret
< 0) {
1457 static const char *get_man_bin_path(void)
1459 char *env_man_path
= lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV
);
1462 return env_man_path
;
1465 return DEFAULT_MAN_BIN_PATH
;
1469 int utils_show_help(int section
, const char *page_name
,
1470 const char *help_msg
)
1472 char section_string
[8];
1473 const char *man_bin_path
= get_man_bin_path();
1477 printf("%s", help_msg
);
1481 /* Section integer -> section string */
1482 ret
= sprintf(section_string
, "%d", section
);
1483 assert(ret
> 0 && ret
< 8);
1486 * Execute man pager.
1488 * We provide -M to man here because LTTng-tools can
1489 * be installed outside /usr, in which case its man pages are
1490 * not located in the default /usr/share/man directory.
1492 ret
= execlp(man_bin_path
, "man", "-M", MANPATH
,
1493 section_string
, page_name
, NULL
);
1500 int timespec_to_ms(struct timespec ts
, unsigned long *ms
)
1502 unsigned long res
, remain_ms
;
1504 if (ts
.tv_sec
> ULONG_MAX
/ MSEC_PER_SEC
) {
1506 return -1; /* multiplication overflow */
1508 res
= ts
.tv_sec
* MSEC_PER_SEC
;
1509 remain_ms
= ULONG_MAX
- res
;
1510 if (ts
.tv_nsec
/ NSEC_PER_MSEC
> remain_ms
) {
1512 return -1; /* addition overflow */
1514 res
+= ts
.tv_nsec
/ NSEC_PER_MSEC
;
1520 struct timespec
timespec_abs_diff(struct timespec t1
, struct timespec t2
)
1522 uint64_t ts1
= (uint64_t) t1
.tv_sec
* (uint64_t) NSEC_PER_SEC
+
1523 (uint64_t) t1
.tv_nsec
;
1524 uint64_t ts2
= (uint64_t) t2
.tv_sec
* (uint64_t) NSEC_PER_SEC
+
1525 (uint64_t) t2
.tv_nsec
;
1526 uint64_t diff
= max(ts1
, ts2
) - min(ts1
, ts2
);
1527 struct timespec res
;
1529 res
.tv_sec
= diff
/ (uint64_t) NSEC_PER_SEC
;
1530 res
.tv_nsec
= diff
% (uint64_t) NSEC_PER_SEC
;