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
, *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 */
126 /* Allocate memory for the resolved path if necessary */
127 if (resolved_path
== NULL
) {
128 resolved_path
= zmalloc(size
);
129 if (resolved_path
== NULL
) {
130 PERROR("zmalloc resolved path");
136 * If we were able to solve at least partially the path, we can concatenate
137 * what worked and what didn't work
139 if (try_path_prev
!= NULL
) {
140 /* If we risk to concatenate two '/', we remove one of them */
141 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
142 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
146 * Duplicate the memory used by prev in case resolved_path and
147 * path are pointers for the same memory space
149 cut_path
= strdup(prev
);
150 if (cut_path
== NULL
) {
155 /* Concatenate the strings */
156 snprintf(resolved_path
, size
, "%s%s", try_path_prev
, cut_path
);
158 /* Free the allocated memory */
162 * Else, we just copy the path in our resolved_path to
166 strncpy(resolved_path
, path
, size
);
169 /* Then we return the 'partially' resolved path */
170 return resolved_path
;
178 * Make a full resolution of the given path even if it doesn't exist.
179 * This function uses the utils_partial_realpath function to resolve
180 * symlinks and relatives paths at the start of the string, and
181 * implements functionnalities to resolve the './' and '../' strings
182 * in the middle of a path. This function is only necessary because
183 * realpath(3) does not accept to resolve unexistent paths.
184 * The returned string was allocated in the function, it is thus of
185 * the responsibility of the caller to free this memory.
188 char *utils_expand_path(const char *path
)
190 char *next
, *previous
, *slash
, *start_path
, *absolute_path
= NULL
;
192 int is_dot
, is_dotdot
;
199 /* Allocate memory for the absolute_path */
200 absolute_path
= zmalloc(PATH_MAX
);
201 if (absolute_path
== NULL
) {
202 PERROR("zmalloc expand path");
207 * If the path is not already absolute nor explicitly relative,
208 * consider we're in the current directory
210 if (*path
!= '/' && strncmp(path
, "./", 2) != 0 &&
211 strncmp(path
, "../", 3) != 0) {
212 snprintf(absolute_path
, PATH_MAX
, "./%s", path
);
213 /* Else, we just copy the path */
215 strncpy(absolute_path
, path
, PATH_MAX
);
218 /* Resolve partially our path */
219 absolute_path
= utils_partial_realpath(absolute_path
,
220 absolute_path
, PATH_MAX
);
222 /* As long as we find '/./' in the working_path string */
223 while ((next
= strstr(absolute_path
, "/./"))) {
225 /* We prepare the start_path not containing it */
226 start_path
= strndup(absolute_path
, next
- absolute_path
);
231 /* And we concatenate it with the part after this string */
232 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 2);
237 /* As long as we find '/../' in the working_path string */
238 while ((next
= strstr(absolute_path
, "/../"))) {
239 /* We find the last level of directory */
240 previous
= absolute_path
;
241 while ((slash
= strpbrk(previous
, "/")) && slash
!= next
) {
242 previous
= slash
+ 1;
245 /* Then we prepare the start_path not containing it */
246 start_path
= strndup(absolute_path
, previous
- absolute_path
);
252 /* And we concatenate it with the part after the '/../' */
253 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 4);
255 /* We can free the memory used for the start path*/
258 /* Then we verify for symlinks using partial_realpath */
259 absolute_path
= utils_partial_realpath(absolute_path
,
260 absolute_path
, PATH_MAX
);
263 /* Identify the last token */
264 last_token
= strrchr(absolute_path
, '/');
266 /* Verify that this token is not a relative path */
267 is_dotdot
= (strcmp(last_token
, "/..") == 0);
268 is_dot
= (strcmp(last_token
, "/.") == 0);
270 /* If it is, take action */
271 if (is_dot
|| is_dotdot
) {
272 /* For both, remove this token */
275 /* If it was a reference to parent directory, go back one more time */
277 last_token
= strrchr(absolute_path
, '/');
279 /* If there was only one level left, we keep the first '/' */
280 if (last_token
== absolute_path
) {
288 return absolute_path
;
296 * Create a pipe in dst.
299 int utils_create_pipe(int *dst
)
309 PERROR("create pipe");
316 * Create pipe and set CLOEXEC flag to both fd.
318 * Make sure the pipe opened by this function are closed at some point. Use
319 * utils_close_pipe().
322 int utils_create_pipe_cloexec(int *dst
)
330 ret
= utils_create_pipe(dst
);
335 for (i
= 0; i
< 2; i
++) {
336 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
338 PERROR("fcntl pipe cloexec");
348 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
350 * Make sure the pipe opened by this function are closed at some point. Use
351 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
352 * support OSes other than Linux 2.6.23+.
355 int utils_create_pipe_cloexec_nonblock(int *dst
)
363 ret
= utils_create_pipe(dst
);
368 for (i
= 0; i
< 2; i
++) {
369 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
371 PERROR("fcntl pipe cloexec");
375 * Note: we override any flag that could have been
376 * previously set on the fd.
378 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
380 PERROR("fcntl pipe nonblock");
390 * Close both read and write side of the pipe.
393 void utils_close_pipe(int *src
)
401 for (i
= 0; i
< 2; i
++) {
409 PERROR("close pipe");
415 * Create a new string using two strings range.
418 char *utils_strdupdelim(const char *begin
, const char *end
)
422 str
= zmalloc(end
- begin
+ 1);
424 PERROR("zmalloc strdupdelim");
428 memcpy(str
, begin
, end
- begin
);
429 str
[end
- begin
] = '\0';
436 * Set CLOEXEC flag to the give file descriptor.
439 int utils_set_fd_cloexec(int fd
)
448 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
450 PERROR("fcntl cloexec");
459 * Create pid file to the given path and filename.
462 int utils_create_pid_file(pid_t pid
, const char *filepath
)
469 fp
= fopen(filepath
, "w");
471 PERROR("open pid file %s", filepath
);
476 ret
= fprintf(fp
, "%d\n", pid
);
478 PERROR("fprintf pid file");
482 DBG("Pid %d written in file %s", pid
, filepath
);
488 * Create lock file to the given path and filename.
489 * Returns the associated file descriptor, -1 on error.
492 int utils_create_lock_file(const char *filepath
)
499 fd
= open(filepath
, O_CREAT
,
500 O_WRONLY
| S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
502 PERROR("open lock file %s", filepath
);
508 * Attempt to lock the file. If this fails, there is
509 * already a process using the same lock file running
510 * and we should exit.
512 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
514 WARN("Could not get lock file %s, another instance is running.",
526 * Recursively create directory using the given path and mode.
528 * On success, return 0 else a negative error code.
531 int utils_mkdir_recursive(const char *path
, mode_t mode
)
533 char *p
, tmp
[PATH_MAX
];
539 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
541 PERROR("snprintf mkdir");
546 if (tmp
[len
- 1] == '/') {
550 for (p
= tmp
+ 1; *p
; p
++) {
553 if (tmp
[strlen(tmp
) - 1] == '.' &&
554 tmp
[strlen(tmp
) - 2] == '.' &&
555 tmp
[strlen(tmp
) - 3] == '/') {
556 ERR("Using '/../' is not permitted in the trace path (%s)",
561 ret
= mkdir(tmp
, mode
);
563 if (errno
!= EEXIST
) {
564 PERROR("mkdir recursive");
573 ret
= mkdir(tmp
, mode
);
575 if (errno
!= EEXIST
) {
576 PERROR("mkdir recursive last piece");
588 * Create the stream tracefile on disk.
590 * Return 0 on success or else a negative value.
593 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
594 uint64_t count
, int uid
, int gid
, char *suffix
)
596 int ret
, out_fd
, flags
, mode
;
597 char full_path
[PATH_MAX
], *path_name_suffix
= NULL
, *path
;
603 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
604 path_name
, file_name
);
606 PERROR("snprintf create output file");
610 /* Setup extra string if suffix or/and a count is needed. */
611 if (size
> 0 && suffix
) {
612 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
613 } else if (size
> 0) {
614 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
616 ret
= asprintf(&extra
, "%s", suffix
);
619 PERROR("Allocating extra string to name");
624 * If we split the trace in multiple files, we have to add the count at the
625 * end of the tracefile name
628 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
630 PERROR("Allocating path name with extra string");
631 goto error_free_suffix
;
633 path
= path_name_suffix
;
638 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
639 /* Open with 660 mode */
640 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
642 if (uid
< 0 || gid
< 0) {
643 out_fd
= open(path
, flags
, mode
);
645 out_fd
= run_as_open(path
, flags
, mode
, uid
, gid
);
648 PERROR("open stream path %s", path
);
654 free(path_name_suffix
);
662 * Change the output tracefile according to the given size and count The
663 * new_count pointer is set during this operation.
665 * From the consumer, the stream lock MUST be held before calling this function
666 * because we are modifying the stream status.
668 * Return 0 on success or else a negative value.
671 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
672 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
682 PERROR("Closing tracefile");
687 *new_count
= (*new_count
+ 1) % count
;
692 ret
= utils_create_stream_file(path_name
, file_name
, size
, *new_count
,
708 * Parse a string that represents a size in human readable format. It
709 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
711 * The suffix multiply the integer by:
716 * @param str The string to parse.
717 * @param size Pointer to a uint64_t that will be filled with the
720 * @return 0 on success, -1 on failure.
723 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
732 DBG("utils_parse_size_suffix: received a NULL string.");
737 /* strtoull will accept a negative number, but we don't want to. */
738 if (strchr(str
, '-') != NULL
) {
739 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
744 /* str_end will point to the \0 */
745 str_end
= str
+ strlen(str
);
747 base_size
= strtoull(str
, &num_end
, 0);
749 PERROR("utils_parse_size_suffix strtoull");
754 if (num_end
== str
) {
755 /* strtoull parsed nothing, not good. */
756 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
761 /* Check if a prefix is present. */
779 DBG("utils_parse_size_suffix: invalid suffix.");
784 /* Check for garbage after the valid input. */
785 if (num_end
!= str_end
) {
786 DBG("utils_parse_size_suffix: Garbage after size string.");
791 *size
= base_size
<< shift
;
793 /* Check for overflow */
794 if ((*size
>> shift
) != base_size
) {
795 DBG("utils_parse_size_suffix: oops, overflow detected.");
806 * fls: returns the position of the most significant bit.
807 * Returns 0 if no bit is set, else returns the position of the most
808 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
810 #if defined(__i386) || defined(__x86_64)
811 static inline unsigned int fls_u32(uint32_t x
)
819 : "=r" (r
) : "rm" (x
));
826 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
833 if (!(x
& 0xFFFF0000U
)) {
837 if (!(x
& 0xFF000000U
)) {
841 if (!(x
& 0xF0000000U
)) {
845 if (!(x
& 0xC0000000U
)) {
849 if (!(x
& 0x80000000U
)) {
858 * Return the minimum order for which x <= (1UL << order).
859 * Return -1 if x is 0.
862 int utils_get_count_order_u32(uint32_t x
)
868 return fls_u32(x
- 1);
872 * Obtain the value of LTTNG_HOME environment variable, if exists.
873 * Otherwise returns the value of HOME.
876 char *utils_get_home_dir(void)
881 val
= getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
885 val
= getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
890 /* Fallback on the password file entry. */
891 pwd
= getpwuid(getuid());
897 DBG3("Home directory is '%s'", val
);
904 * Get user's home directory. Dynamically allocated, must be freed
908 char *utils_get_user_home_dir(uid_t uid
)
911 struct passwd
*result
;
912 char *home_dir
= NULL
;
917 buflen
= sysconf(_SC_GETPW_R_SIZE_MAX
);
922 buf
= zmalloc(buflen
);
927 ret
= getpwuid_r(uid
, &pwd
, buf
, buflen
, &result
);
928 if (ret
|| !result
) {
937 home_dir
= strdup(pwd
.pw_dir
);
944 * Obtain the value of LTTNG_KMOD_PROBES environment variable, if exists.
945 * Otherwise returns NULL.
948 char *utils_get_kmod_probes_list(void)
950 return getenv(DEFAULT_LTTNG_KMOD_PROBES
);
954 * Obtain the value of LTTNG_EXTRA_KMOD_PROBES environment variable, if
955 * exists. Otherwise returns NULL.
958 char *utils_get_extra_kmod_probes_list(void)
960 return getenv(DEFAULT_LTTNG_EXTRA_KMOD_PROBES
);
964 * With the given format, fill dst with the time of len maximum siz.
966 * Return amount of bytes set in the buffer or else 0 on error.
969 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
978 /* Get date and time for session path */
980 timeinfo
= localtime(&rawtime
);
981 ret
= strftime(dst
, len
, format
, timeinfo
);
983 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
991 * Return the group ID matching name, else 0 if it cannot be found.
994 gid_t
utils_get_group_id(const char *name
)
998 grp
= getgrnam(name
);
1000 static volatile int warn_once
;
1003 WARN("No tracing group detected");
1012 * Return a newly allocated option string. This string is to be used as the
1013 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1014 * of elements in the long_options array. Returns NULL if the string's
1018 char *utils_generate_optstring(const struct option
*long_options
,
1022 size_t string_len
= opt_count
, str_pos
= 0;
1026 * Compute the necessary string length. One letter per option, two when an
1027 * argument is necessary, and a trailing NULL.
1029 for (i
= 0; i
< opt_count
; i
++) {
1030 string_len
+= long_options
[i
].has_arg
? 1 : 0;
1033 optstring
= zmalloc(string_len
);
1038 for (i
= 0; i
< opt_count
; i
++) {
1039 if (!long_options
[i
].name
) {
1040 /* Got to the trailing NULL element */
1044 optstring
[str_pos
++] = (char)long_options
[i
].val
;
1045 if (long_options
[i
].has_arg
) {
1046 optstring
[str_pos
++] = ':';