2 * Copyright (C) 2012 - David Goulet <dgoulet@efficios.com>
3 * Copyright (C) 2013 - Raphaƫl Beamonte <raphael.beamonte@gmail.com>
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License, version 2 only, as
7 * published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 * You should have received a copy of the GNU General Public License along with
15 * this program; if not, write to the Free Software Foundation, Inc., 51
16 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 #include <sys/types.h>
34 #include <common/common.h>
35 #include <common/runas.h>
41 * Return a partial realpath(3) of the path even if the full path does not
42 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
43 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
44 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
45 * point directory does not exist.
46 * In case resolved_path is NULL, the string returned was allocated in the
47 * function and thus need to be freed by the caller. The size argument allows
48 * to specify the size of the resolved_path argument if given, or the size to
52 char *utils_partial_realpath(const char *path
, char *resolved_path
, size_t size
)
54 char *cut_path
, *try_path
= NULL
, *try_path_prev
= NULL
;
55 const char *next
, *prev
, *end
;
63 * Identify the end of the path, we don't want to treat the
64 * last char if it is a '/', we will just keep it on the side
65 * to be added at the end, and return a value coherent with
66 * the path given as argument
68 end
= path
+ strlen(path
);
69 if (*(end
-1) == '/') {
73 /* Initiate the values of the pointers before looping */
76 /* Only to ensure try_path is not NULL to enter the while */
77 try_path
= (char *)next
;
79 /* Resolve the canonical path of the first part of the path */
80 while (try_path
!= NULL
&& next
!= end
) {
82 * If there is not any '/' left, we want to try with
85 next
= strpbrk(next
+ 1, "/");
90 /* Cut the part we will be trying to resolve */
91 cut_path
= strndup(path
, next
- path
);
92 if (cut_path
== NULL
) {
97 /* Try to resolve this part */
98 try_path
= realpath((char *)cut_path
, NULL
);
99 if (try_path
== NULL
) {
101 * There was an error, we just want to be assured it
102 * is linked to an unexistent directory, if it's another
103 * reason, we spawn an error
107 /* Ignore the error */
110 PERROR("realpath (partial_realpath)");
115 /* Save the place we are before trying the next step */
117 try_path_prev
= try_path
;
121 /* Free the allocated memory */
125 /* Allocate memory for the resolved path if necessary */
126 if (resolved_path
== NULL
) {
127 resolved_path
= zmalloc(size
);
128 if (resolved_path
== NULL
) {
129 PERROR("zmalloc resolved path");
135 * If we were able to solve at least partially the path, we can concatenate
136 * what worked and what didn't work
138 if (try_path_prev
!= NULL
) {
139 /* If we risk to concatenate two '/', we remove one of them */
140 if (try_path_prev
[strlen(try_path_prev
) - 1] == '/' && prev
[0] == '/') {
141 try_path_prev
[strlen(try_path_prev
) - 1] = '\0';
145 * Duplicate the memory used by prev in case resolved_path and
146 * path are pointers for the same memory space
148 cut_path
= strdup(prev
);
149 if (cut_path
== NULL
) {
154 /* Concatenate the strings */
155 snprintf(resolved_path
, size
, "%s%s", try_path_prev
, cut_path
);
157 /* Free the allocated memory */
161 * Else, we just copy the path in our resolved_path to
165 strncpy(resolved_path
, path
, size
);
168 /* Then we return the 'partially' resolved path */
169 return resolved_path
;
177 * Make a full resolution of the given path even if it doesn't exist.
178 * This function uses the utils_partial_realpath function to resolve
179 * symlinks and relatives paths at the start of the string, and
180 * implements functionnalities to resolve the './' and '../' strings
181 * in the middle of a path. This function is only necessary because
182 * realpath(3) does not accept to resolve unexistent paths.
183 * The returned string was allocated in the function, it is thus of
184 * the responsibility of the caller to free this memory.
187 char *utils_expand_path(const char *path
)
189 char *next
, *previous
, *slash
, *start_path
, *absolute_path
= NULL
;
191 int is_dot
, is_dotdot
;
198 /* Allocate memory for the absolute_path */
199 absolute_path
= zmalloc(PATH_MAX
);
200 if (absolute_path
== NULL
) {
201 PERROR("zmalloc expand path");
206 * If the path is not already absolute nor explicitly relative,
207 * consider we're in the current directory
209 if (*path
!= '/' && strncmp(path
, "./", 2) != 0 &&
210 strncmp(path
, "../", 3) != 0) {
211 snprintf(absolute_path
, PATH_MAX
, "./%s", path
);
212 /* Else, we just copy the path */
214 strncpy(absolute_path
, path
, PATH_MAX
);
217 /* Resolve partially our path */
218 absolute_path
= utils_partial_realpath(absolute_path
,
219 absolute_path
, PATH_MAX
);
221 /* As long as we find '/./' in the working_path string */
222 while ((next
= strstr(absolute_path
, "/./"))) {
224 /* We prepare the start_path not containing it */
225 start_path
= strndup(absolute_path
, next
- absolute_path
);
230 /* And we concatenate it with the part after this string */
231 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 2);
236 /* As long as we find '/../' in the working_path string */
237 while ((next
= strstr(absolute_path
, "/../"))) {
238 /* We find the last level of directory */
239 previous
= absolute_path
;
240 while ((slash
= strpbrk(previous
, "/")) && slash
!= next
) {
241 previous
= slash
+ 1;
244 /* Then we prepare the start_path not containing it */
245 start_path
= strndup(absolute_path
, previous
- absolute_path
);
251 /* And we concatenate it with the part after the '/../' */
252 snprintf(absolute_path
, PATH_MAX
, "%s%s", start_path
, next
+ 4);
254 /* We can free the memory used for the start path*/
257 /* Then we verify for symlinks using partial_realpath */
258 absolute_path
= utils_partial_realpath(absolute_path
,
259 absolute_path
, PATH_MAX
);
262 /* Identify the last token */
263 last_token
= strrchr(absolute_path
, '/');
265 /* Verify that this token is not a relative path */
266 is_dotdot
= (strcmp(last_token
, "/..") == 0);
267 is_dot
= (strcmp(last_token
, "/.") == 0);
269 /* If it is, take action */
270 if (is_dot
|| is_dotdot
) {
271 /* For both, remove this token */
274 /* If it was a reference to parent directory, go back one more time */
276 last_token
= strrchr(absolute_path
, '/');
278 /* If there was only one level left, we keep the first '/' */
279 if (last_token
== absolute_path
) {
287 return absolute_path
;
295 * Create a pipe in dst.
298 int utils_create_pipe(int *dst
)
308 PERROR("create pipe");
315 * Create pipe and set CLOEXEC flag to both fd.
317 * Make sure the pipe opened by this function are closed at some point. Use
318 * utils_close_pipe().
321 int utils_create_pipe_cloexec(int *dst
)
329 ret
= utils_create_pipe(dst
);
334 for (i
= 0; i
< 2; i
++) {
335 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
337 PERROR("fcntl pipe cloexec");
347 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
349 * Make sure the pipe opened by this function are closed at some point. Use
350 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
351 * support OSes other than Linux 2.6.23+.
354 int utils_create_pipe_cloexec_nonblock(int *dst
)
362 ret
= utils_create_pipe(dst
);
367 for (i
= 0; i
< 2; i
++) {
368 ret
= fcntl(dst
[i
], F_SETFD
, FD_CLOEXEC
);
370 PERROR("fcntl pipe cloexec");
374 * Note: we override any flag that could have been
375 * previously set on the fd.
377 ret
= fcntl(dst
[i
], F_SETFL
, O_NONBLOCK
);
379 PERROR("fcntl pipe nonblock");
389 * Close both read and write side of the pipe.
392 void utils_close_pipe(int *src
)
400 for (i
= 0; i
< 2; i
++) {
408 PERROR("close pipe");
414 * Create a new string using two strings range.
417 char *utils_strdupdelim(const char *begin
, const char *end
)
421 str
= zmalloc(end
- begin
+ 1);
423 PERROR("zmalloc strdupdelim");
427 memcpy(str
, begin
, end
- begin
);
428 str
[end
- begin
] = '\0';
435 * Set CLOEXEC flag to the give file descriptor.
438 int utils_set_fd_cloexec(int fd
)
447 ret
= fcntl(fd
, F_SETFD
, FD_CLOEXEC
);
449 PERROR("fcntl cloexec");
458 * Create pid file to the given path and filename.
461 int utils_create_pid_file(pid_t pid
, const char *filepath
)
468 fp
= fopen(filepath
, "w");
470 PERROR("open pid file %s", filepath
);
475 ret
= fprintf(fp
, "%d\n", pid
);
477 PERROR("fprintf pid file");
481 DBG("Pid %d written in file %s", pid
, filepath
);
487 * Create lock file to the given path and filename.
488 * Returns the associated file descriptor, -1 on error.
491 int utils_create_lock_file(const char *filepath
)
498 fd
= open(filepath
, O_CREAT
,
499 O_WRONLY
| S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
);
501 PERROR("open lock file %s", filepath
);
507 * Attempt to lock the file. If this fails, there is
508 * already a process using the same lock file running
509 * and we should exit.
511 ret
= flock(fd
, LOCK_EX
| LOCK_NB
);
513 WARN("Could not get lock file %s, another instance is running.",
525 * Recursively create directory using the given path and mode.
527 * On success, return 0 else a negative error code.
530 int utils_mkdir_recursive(const char *path
, mode_t mode
)
532 char *p
, tmp
[PATH_MAX
];
538 ret
= snprintf(tmp
, sizeof(tmp
), "%s", path
);
540 PERROR("snprintf mkdir");
545 if (tmp
[len
- 1] == '/') {
549 for (p
= tmp
+ 1; *p
; p
++) {
552 if (tmp
[strlen(tmp
) - 1] == '.' &&
553 tmp
[strlen(tmp
) - 2] == '.' &&
554 tmp
[strlen(tmp
) - 3] == '/') {
555 ERR("Using '/../' is not permitted in the trace path (%s)",
560 ret
= mkdir(tmp
, mode
);
562 if (errno
!= EEXIST
) {
563 PERROR("mkdir recursive");
572 ret
= mkdir(tmp
, mode
);
574 if (errno
!= EEXIST
) {
575 PERROR("mkdir recursive last piece");
587 * Create the stream tracefile on disk.
589 * Return 0 on success or else a negative value.
592 int utils_create_stream_file(const char *path_name
, char *file_name
, uint64_t size
,
593 uint64_t count
, int uid
, int gid
, char *suffix
)
595 int ret
, out_fd
, flags
, mode
;
596 char full_path
[PATH_MAX
], *path_name_suffix
= NULL
, *path
;
602 ret
= snprintf(full_path
, sizeof(full_path
), "%s/%s",
603 path_name
, file_name
);
605 PERROR("snprintf create output file");
609 /* Setup extra string if suffix or/and a count is needed. */
610 if (size
> 0 && suffix
) {
611 ret
= asprintf(&extra
, "_%" PRIu64
"%s", count
, suffix
);
612 } else if (size
> 0) {
613 ret
= asprintf(&extra
, "_%" PRIu64
, count
);
615 ret
= asprintf(&extra
, "%s", suffix
);
618 PERROR("Allocating extra string to name");
623 * If we split the trace in multiple files, we have to add the count at the
624 * end of the tracefile name
627 ret
= asprintf(&path_name_suffix
, "%s%s", full_path
, extra
);
629 PERROR("Allocating path name with extra string");
630 goto error_free_suffix
;
632 path
= path_name_suffix
;
637 flags
= O_WRONLY
| O_CREAT
| O_TRUNC
;
638 /* Open with 660 mode */
639 mode
= S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
;
641 if (uid
< 0 || gid
< 0) {
642 out_fd
= open(path
, flags
, mode
);
644 out_fd
= run_as_open(path
, flags
, mode
, uid
, gid
);
647 PERROR("open stream path %s", path
);
653 free(path_name_suffix
);
661 * Change the output tracefile according to the given size and count The
662 * new_count pointer is set during this operation.
664 * From the consumer, the stream lock MUST be held before calling this function
665 * because we are modifying the stream status.
667 * Return 0 on success or else a negative value.
670 int utils_rotate_stream_file(char *path_name
, char *file_name
, uint64_t size
,
671 uint64_t count
, int uid
, int gid
, int out_fd
, uint64_t *new_count
,
681 PERROR("Closing tracefile");
686 *new_count
= (*new_count
+ 1) % count
;
691 ret
= utils_create_stream_file(path_name
, file_name
, size
, *new_count
,
707 * Parse a string that represents a size in human readable format. It
708 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
710 * The suffix multiply the integer by:
715 * @param str The string to parse.
716 * @param size Pointer to a uint64_t that will be filled with the
719 * @return 0 on success, -1 on failure.
722 int utils_parse_size_suffix(const char * const str
, uint64_t * const size
)
731 DBG("utils_parse_size_suffix: received a NULL string.");
736 /* strtoull will accept a negative number, but we don't want to. */
737 if (strchr(str
, '-') != NULL
) {
738 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
743 /* str_end will point to the \0 */
744 str_end
= str
+ strlen(str
);
746 base_size
= strtoull(str
, &num_end
, 0);
748 PERROR("utils_parse_size_suffix strtoull");
753 if (num_end
== str
) {
754 /* strtoull parsed nothing, not good. */
755 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
760 /* Check if a prefix is present. */
778 DBG("utils_parse_size_suffix: invalid suffix.");
783 /* Check for garbage after the valid input. */
784 if (num_end
!= str_end
) {
785 DBG("utils_parse_size_suffix: Garbage after size string.");
790 *size
= base_size
<< shift
;
792 /* Check for overflow */
793 if ((*size
>> shift
) != base_size
) {
794 DBG("utils_parse_size_suffix: oops, overflow detected.");
805 * fls: returns the position of the most significant bit.
806 * Returns 0 if no bit is set, else returns the position of the most
807 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
809 #if defined(__i386) || defined(__x86_64)
810 static inline unsigned int fls_u32(uint32_t x
)
818 : "=r" (r
) : "rm" (x
));
825 static __attribute__((unused
)) unsigned int fls_u32(uint32_t x
)
832 if (!(x
& 0xFFFF0000U
)) {
836 if (!(x
& 0xFF000000U
)) {
840 if (!(x
& 0xF0000000U
)) {
844 if (!(x
& 0xC0000000U
)) {
848 if (!(x
& 0x80000000U
)) {
857 * Return the minimum order for which x <= (1UL << order).
858 * Return -1 if x is 0.
861 int utils_get_count_order_u32(uint32_t x
)
867 return fls_u32(x
- 1);
871 * Obtain the value of LTTNG_HOME environment variable, if exists.
872 * Otherwise returns the value of HOME.
875 char *utils_get_home_dir(void)
880 val
= getenv(DEFAULT_LTTNG_HOME_ENV_VAR
);
884 val
= getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR
);
889 /* Fallback on the password file entry. */
890 pwd
= getpwuid(getuid());
896 DBG3("Home directory is '%s'", val
);
903 * With the given format, fill dst with the time of len maximum siz.
905 * Return amount of bytes set in the buffer or else 0 on error.
908 size_t utils_get_current_time_str(const char *format
, char *dst
, size_t len
)
917 /* Get date and time for session path */
919 timeinfo
= localtime(&rawtime
);
920 ret
= strftime(dst
, len
, format
, timeinfo
);
922 ERR("Unable to strftime with format %s at dst %p of len %zu", format
,
930 * Return the group ID matching name, else 0 if it cannot be found.
933 gid_t
utils_get_group_id(const char *name
)
937 grp
= getgrnam(name
);
939 static volatile int warn_once
;
942 WARN("No tracing group detected");