Move time utils to their own time.c file
[lttng-tools.git] / src / common / utils.c
CommitLineData
81b86775
DG
1/*
2 * Copyright (C) 2012 - David Goulet <dgoulet@efficios.com>
66495845 3 * Copyright (C) 2013 - Raphaël Beamonte <raphael.beamonte@gmail.com>
8db0dc00 4 * Copyright (C) 2013 - Jérémie Galarneau <jeremie.galarneau@efficios.com>
81b86775
DG
5 *
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.
9 *
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
13 * more details.
14 *
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.
18 */
19
6c1c0768 20#define _LGPL_SOURCE
35f90c40 21#include <assert.h>
81b86775
DG
22#include <ctype.h>
23#include <fcntl.h>
24#include <limits.h>
25#include <stdlib.h>
2d851108 26#include <sys/stat.h>
0c7bcad5 27#include <sys/types.h>
2d851108 28#include <unistd.h>
fe4477ee 29#include <inttypes.h>
6c71277b 30#include <grp.h>
fb198a11 31#include <pwd.h>
c9cb3e7d 32#include <sys/file.h>
a98e236e 33#include <unistd.h>
81b86775
DG
34
35#include <common/common.h>
fe4477ee 36#include <common/runas.h>
e8fa9fb0 37#include <common/compat/getenv.h>
f5436bfc 38#include <common/compat/string.h>
5a2451c9 39#include <common/compat/dirent.h>
d7c23421 40#include <lttng/constant.h>
81b86775
DG
41
42#include "utils.h"
feb0f3e5 43#include "defaults.h"
2daf6502 44#include "time.h"
81b86775 45
5154230f
RB
46/*
47 * Return a partial realpath(3) of the path even if the full path does not
48 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
49 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
50 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
51 * point directory does not exist.
52 * In case resolved_path is NULL, the string returned was allocated in the
53 * function and thus need to be freed by the caller. The size argument allows
54 * to specify the size of the resolved_path argument if given, or the size to
55 * allocate.
56 */
57LTTNG_HIDDEN
58char *utils_partial_realpath(const char *path, char *resolved_path, size_t size)
59{
9482daac 60 char *cut_path = NULL, *try_path = NULL, *try_path_prev = NULL;
5154230f
RB
61 const char *next, *prev, *end;
62
63 /* Safety net */
64 if (path == NULL) {
65 goto error;
66 }
67
68 /*
69 * Identify the end of the path, we don't want to treat the
70 * last char if it is a '/', we will just keep it on the side
71 * to be added at the end, and return a value coherent with
72 * the path given as argument
73 */
74 end = path + strlen(path);
75 if (*(end-1) == '/') {
76 end--;
77 }
78
79 /* Initiate the values of the pointers before looping */
80 next = path;
81 prev = next;
82 /* Only to ensure try_path is not NULL to enter the while */
83 try_path = (char *)next;
84
85 /* Resolve the canonical path of the first part of the path */
86 while (try_path != NULL && next != end) {
d7c23421
JG
87 char *try_path_buf = NULL;
88
5154230f
RB
89 /*
90 * If there is not any '/' left, we want to try with
91 * the full path
92 */
93 next = strpbrk(next + 1, "/");
94 if (next == NULL) {
95 next = end;
96 }
97
98 /* Cut the part we will be trying to resolve */
f5436bfc 99 cut_path = lttng_strndup(path, next - path);
d9dbcf5e 100 if (cut_path == NULL) {
f5436bfc 101 PERROR("lttng_strndup");
d9dbcf5e
MD
102 goto error;
103 }
5154230f 104
d7c23421
JG
105 try_path_buf = zmalloc(LTTNG_PATH_MAX);
106 if (!try_path_buf) {
107 PERROR("zmalloc");
108 goto error;
109 }
110
5154230f 111 /* Try to resolve this part */
f3472d9a 112 try_path = realpath((char *) cut_path, try_path_buf);
5154230f 113 if (try_path == NULL) {
d7c23421 114 free(try_path_buf);
5154230f
RB
115 /*
116 * There was an error, we just want to be assured it
117 * is linked to an unexistent directory, if it's another
118 * reason, we spawn an error
119 */
120 switch (errno) {
121 case ENOENT:
122 /* Ignore the error */
123 break;
124 default:
125 PERROR("realpath (partial_realpath)");
126 goto error;
127 break;
128 }
129 } else {
130 /* Save the place we are before trying the next step */
d7c23421 131 try_path_buf = NULL;
5154230f
RB
132 free(try_path_prev);
133 try_path_prev = try_path;
134 prev = next;
135 }
136
137 /* Free the allocated memory */
138 free(cut_path);
c14cc491 139 cut_path = NULL;
494a8e99 140 }
5154230f
RB
141
142 /* Allocate memory for the resolved path if necessary */
143 if (resolved_path == NULL) {
144 resolved_path = zmalloc(size);
145 if (resolved_path == NULL) {
146 PERROR("zmalloc resolved path");
147 goto error;
148 }
149 }
150
151 /*
152 * If we were able to solve at least partially the path, we can concatenate
153 * what worked and what didn't work
154 */
155 if (try_path_prev != NULL) {
156 /* If we risk to concatenate two '/', we remove one of them */
157 if (try_path_prev[strlen(try_path_prev) - 1] == '/' && prev[0] == '/') {
158 try_path_prev[strlen(try_path_prev) - 1] = '\0';
159 }
160
161 /*
162 * Duplicate the memory used by prev in case resolved_path and
163 * path are pointers for the same memory space
164 */
165 cut_path = strdup(prev);
d9dbcf5e
MD
166 if (cut_path == NULL) {
167 PERROR("strdup");
168 goto error;
169 }
5154230f
RB
170
171 /* Concatenate the strings */
172 snprintf(resolved_path, size, "%s%s", try_path_prev, cut_path);
173
174 /* Free the allocated memory */
175 free(cut_path);
176 free(try_path_prev);
494a8e99
JG
177 cut_path = NULL;
178 try_path_prev = NULL;
5154230f
RB
179 /*
180 * Else, we just copy the path in our resolved_path to
181 * return it as is
182 */
183 } else {
184 strncpy(resolved_path, path, size);
185 }
186
187 /* Then we return the 'partially' resolved path */
188 return resolved_path;
189
190error:
191 free(resolved_path);
9482daac 192 free(cut_path);
b86d5f3f 193 free(try_path);
32bd4678
MJ
194 if (try_path_prev != try_path) {
195 free(try_path_prev);
196 }
5154230f
RB
197 return NULL;
198}
199
4b223a67 200static
6740483e 201int expand_double_slashes_dot_and_dotdot(char *path)
4b223a67
FD
202{
203 size_t expanded_path_len, path_len;
204 const char *curr_char, *path_last_char, *next_slash, *prev_slash;
205
206 path_len = strlen(path);
207 path_last_char = &path[path_len];
208
209 if (path_len == 0) {
4b223a67
FD
210 goto error;
211 }
212
213 expanded_path_len = 0;
214
215 /* We iterate over the provided path to expand the "//", "../" and "./" */
216 for (curr_char = path; curr_char <= path_last_char; curr_char = next_slash + 1) {
217 /* Find the next forward slash. */
218 size_t curr_token_len;
219
220 if (curr_char == path_last_char) {
221 expanded_path_len++;
222 break;
223 }
224
225 next_slash = memchr(curr_char, '/', path_last_char - curr_char);
226 if (next_slash == NULL) {
227 /* Reached the end of the provided path. */
228 next_slash = path_last_char;
229 }
230
231 /* Compute how long is the previous token. */
232 curr_token_len = next_slash - curr_char;
233 switch(curr_token_len) {
234 case 0:
235 /*
236 * The pointer has not move meaning that curr_char is
237 * pointing to a slash. It that case there is no token
238 * to copy, so continue the iteration to find the next
239 * token
240 */
241 continue;
242 case 1:
243 /*
244 * The pointer moved 1 character. Check if that
245 * character is a dot ('.'), if it is: omit it, else
246 * copy the token to the normalized path.
247 */
248 if (curr_char[0] == '.') {
249 continue;
250 }
251 break;
252 case 2:
253 /*
254 * The pointer moved 2 characters. Check if these
255 * characters are double dots ('..'). If that is the
256 * case, we need to remove the last token of the
257 * normalized path.
258 */
259 if (curr_char[0] == '.' && curr_char[1] == '.') {
260 /*
261 * Find the previous path component by
262 * using the memrchr function to find the
263 * previous forward slash and substract that
264 * len to the resulting path.
265 */
266 prev_slash = lttng_memrchr(path, '/', expanded_path_len);
267 /*
268 * If prev_slash is NULL, we reached the
269 * beginning of the path. We can't go back any
270 * further.
271 */
272 if (prev_slash != NULL) {
273 expanded_path_len = prev_slash - path;
274 }
275 continue;
276 }
277 break;
278 default:
279 break;
280 }
281
282 /*
283 * Copy the current token which is neither a '.' nor a '..'.
284 */
285 path[expanded_path_len++] = '/';
286 memcpy(&path[expanded_path_len], curr_char, curr_token_len);
287 expanded_path_len += curr_token_len;
288 }
289
290 if (expanded_path_len == 0) {
291 path[expanded_path_len++] = '/';
292 }
293
294 path[expanded_path_len] = '\0';
6740483e 295 return 0;
4b223a67 296error:
6740483e 297 return -1;
4b223a67
FD
298}
299
81b86775 300/*
3d229795
RB
301 * Make a full resolution of the given path even if it doesn't exist.
302 * This function uses the utils_partial_realpath function to resolve
303 * symlinks and relatives paths at the start of the string, and
304 * implements functionnalities to resolve the './' and '../' strings
305 * in the middle of a path. This function is only necessary because
306 * realpath(3) does not accept to resolve unexistent paths.
307 * The returned string was allocated in the function, it is thus of
308 * the responsibility of the caller to free this memory.
81b86775 309 */
90e535ef 310LTTNG_HIDDEN
4b223a67 311char *_utils_expand_path(const char *path, bool keep_symlink)
81b86775 312{
857f0d94 313 int ret;
4b223a67 314 char *absolute_path = NULL;
5de083f4 315 char *last_token;
6740483e 316 bool is_dot, is_dotdot;
81b86775
DG
317
318 /* Safety net */
319 if (path == NULL) {
320 goto error;
321 }
322
3d229795 323 /* Allocate memory for the absolute_path */
857f0d94 324 absolute_path = zmalloc(LTTNG_PATH_MAX);
3d229795 325 if (absolute_path == NULL) {
81b86775
DG
326 PERROR("zmalloc expand path");
327 goto error;
328 }
329
4b223a67 330 if (path[0] == '/') {
857f0d94
JG
331 ret = lttng_strncpy(absolute_path, path, LTTNG_PATH_MAX);
332 if (ret) {
333 ERR("Path exceeds maximal size of %i bytes", LTTNG_PATH_MAX);
334 goto error;
335 }
4b223a67
FD
336 } else {
337 /*
338 * This is a relative path. We need to get the present working
339 * directory and start the path walk from there.
340 */
857f0d94 341 char current_working_dir[LTTNG_PATH_MAX];
4b223a67 342 char *cwd_ret;
857f0d94 343
4b223a67
FD
344 cwd_ret = getcwd(current_working_dir, sizeof(current_working_dir));
345 if (!cwd_ret) {
d9dbcf5e
MD
346 goto error;
347 }
4b223a67
FD
348 /*
349 * Get the number of character in the CWD and allocate an array
350 * to can hold it and the path provided by the caller.
351 */
857f0d94
JG
352 ret = snprintf(absolute_path, LTTNG_PATH_MAX, "%s/%s",
353 current_working_dir, path);
354 if (ret >= LTTNG_PATH_MAX) {
355 ERR("Concatenating current working directory %s and path %s exceeds maximal size of %i bytes",
356 current_working_dir, path, LTTNG_PATH_MAX);
357 goto error;
358 }
3d229795 359 }
116f95d9 360
4b223a67
FD
361 if (keep_symlink) {
362 /* Resolve partially our path */
3d229795 363 absolute_path = utils_partial_realpath(absolute_path,
857f0d94 364 absolute_path, LTTNG_PATH_MAX);
116f95d9 365 }
81b86775 366
6740483e
JG
367 ret = expand_double_slashes_dot_and_dotdot(absolute_path);
368 if (ret) {
4b223a67
FD
369 goto error;
370 }
371
5de083f4
RB
372 /* Identify the last token */
373 last_token = strrchr(absolute_path, '/');
374
375 /* Verify that this token is not a relative path */
376 is_dotdot = (strcmp(last_token, "/..") == 0);
377 is_dot = (strcmp(last_token, "/.") == 0);
378
379 /* If it is, take action */
380 if (is_dot || is_dotdot) {
381 /* For both, remove this token */
382 *last_token = '\0';
383
384 /* If it was a reference to parent directory, go back one more time */
385 if (is_dotdot) {
386 last_token = strrchr(absolute_path, '/');
387
388 /* If there was only one level left, we keep the first '/' */
389 if (last_token == absolute_path) {
390 last_token++;
391 }
392
393 *last_token = '\0';
394 }
395 }
396
3d229795 397 return absolute_path;
81b86775
DG
398
399error:
3d229795 400 free(absolute_path);
81b86775
DG
401 return NULL;
402}
4b223a67
FD
403LTTNG_HIDDEN
404char *utils_expand_path(const char *path)
405{
406 return _utils_expand_path(path, true);
407}
81b86775 408
4b223a67
FD
409LTTNG_HIDDEN
410char *utils_expand_path_keep_symlink(const char *path)
411{
412 return _utils_expand_path(path, false);
413}
81b86775
DG
414/*
415 * Create a pipe in dst.
416 */
90e535ef 417LTTNG_HIDDEN
81b86775
DG
418int utils_create_pipe(int *dst)
419{
420 int ret;
421
422 if (dst == NULL) {
423 return -1;
424 }
425
426 ret = pipe(dst);
427 if (ret < 0) {
428 PERROR("create pipe");
429 }
430
431 return ret;
432}
433
434/*
435 * Create pipe and set CLOEXEC flag to both fd.
436 *
437 * Make sure the pipe opened by this function are closed at some point. Use
438 * utils_close_pipe().
439 */
90e535ef 440LTTNG_HIDDEN
81b86775
DG
441int utils_create_pipe_cloexec(int *dst)
442{
443 int ret, i;
444
445 if (dst == NULL) {
446 return -1;
447 }
448
449 ret = utils_create_pipe(dst);
450 if (ret < 0) {
451 goto error;
452 }
453
454 for (i = 0; i < 2; i++) {
455 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
456 if (ret < 0) {
457 PERROR("fcntl pipe cloexec");
458 goto error;
459 }
460 }
461
462error:
463 return ret;
464}
465
094f381c
MD
466/*
467 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
468 *
469 * Make sure the pipe opened by this function are closed at some point. Use
470 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
471 * support OSes other than Linux 2.6.23+.
472 */
473LTTNG_HIDDEN
474int utils_create_pipe_cloexec_nonblock(int *dst)
475{
476 int ret, i;
477
478 if (dst == NULL) {
479 return -1;
480 }
481
482 ret = utils_create_pipe(dst);
483 if (ret < 0) {
484 goto error;
485 }
486
487 for (i = 0; i < 2; i++) {
488 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
489 if (ret < 0) {
490 PERROR("fcntl pipe cloexec");
491 goto error;
492 }
493 /*
494 * Note: we override any flag that could have been
495 * previously set on the fd.
496 */
497 ret = fcntl(dst[i], F_SETFL, O_NONBLOCK);
498 if (ret < 0) {
499 PERROR("fcntl pipe nonblock");
500 goto error;
501 }
502 }
503
504error:
505 return ret;
506}
507
81b86775
DG
508/*
509 * Close both read and write side of the pipe.
510 */
90e535ef 511LTTNG_HIDDEN
81b86775
DG
512void utils_close_pipe(int *src)
513{
514 int i, ret;
515
516 if (src == NULL) {
517 return;
518 }
519
520 for (i = 0; i < 2; i++) {
521 /* Safety check */
522 if (src[i] < 0) {
523 continue;
524 }
525
526 ret = close(src[i]);
527 if (ret) {
528 PERROR("close pipe");
529 }
530 }
531}
a4b92340
DG
532
533/*
534 * Create a new string using two strings range.
535 */
90e535ef 536LTTNG_HIDDEN
a4b92340
DG
537char *utils_strdupdelim(const char *begin, const char *end)
538{
539 char *str;
540
541 str = zmalloc(end - begin + 1);
542 if (str == NULL) {
543 PERROR("zmalloc strdupdelim");
544 goto error;
545 }
546
547 memcpy(str, begin, end - begin);
548 str[end - begin] = '\0';
549
550error:
551 return str;
552}
b662582b
DG
553
554/*
555 * Set CLOEXEC flag to the give file descriptor.
556 */
90e535ef 557LTTNG_HIDDEN
b662582b
DG
558int utils_set_fd_cloexec(int fd)
559{
560 int ret;
561
562 if (fd < 0) {
563 ret = -EINVAL;
564 goto end;
565 }
566
567 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
568 if (ret < 0) {
569 PERROR("fcntl cloexec");
570 ret = -errno;
571 }
572
573end:
574 return ret;
575}
35f90c40
DG
576
577/*
578 * Create pid file to the given path and filename.
579 */
90e535ef 580LTTNG_HIDDEN
35f90c40
DG
581int utils_create_pid_file(pid_t pid, const char *filepath)
582{
583 int ret;
584 FILE *fp;
585
586 assert(filepath);
587
588 fp = fopen(filepath, "w");
589 if (fp == NULL) {
590 PERROR("open pid file %s", filepath);
591 ret = -1;
592 goto error;
593 }
594
d1f721c5 595 ret = fprintf(fp, "%d\n", (int) pid);
35f90c40
DG
596 if (ret < 0) {
597 PERROR("fprintf pid file");
e205d79b 598 goto error;
35f90c40
DG
599 }
600
e205d79b
MD
601 if (fclose(fp)) {
602 PERROR("fclose");
603 }
d1f721c5 604 DBG("Pid %d written in file %s", (int) pid, filepath);
e205d79b 605 ret = 0;
35f90c40
DG
606error:
607 return ret;
608}
2d851108 609
c9cb3e7d
JG
610/*
611 * Create lock file to the given path and filename.
612 * Returns the associated file descriptor, -1 on error.
613 */
614LTTNG_HIDDEN
615int utils_create_lock_file(const char *filepath)
616{
617 int ret;
618 int fd;
77e7fddf 619 struct flock lock;
c9cb3e7d
JG
620
621 assert(filepath);
622
77e7fddf
MJ
623 memset(&lock, 0, sizeof(lock));
624 fd = open(filepath, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR |
625 S_IRGRP | S_IWGRP);
c9cb3e7d
JG
626 if (fd < 0) {
627 PERROR("open lock file %s", filepath);
e6576ba2 628 fd = -1;
c9cb3e7d
JG
629 goto error;
630 }
631
632 /*
633 * Attempt to lock the file. If this fails, there is
634 * already a process using the same lock file running
635 * and we should exit.
636 */
77e7fddf
MJ
637 lock.l_whence = SEEK_SET;
638 lock.l_type = F_WRLCK;
639
640 ret = fcntl(fd, F_SETLK, &lock);
641 if (ret == -1) {
642 PERROR("fcntl lock file");
208ff148 643 ERR("Could not get lock file %s, another instance is running.",
c9cb3e7d 644 filepath);
ffb0b851
JG
645 if (close(fd)) {
646 PERROR("close lock file");
647 }
c9cb3e7d
JG
648 fd = ret;
649 goto error;
650 }
651
652error:
653 return fd;
654}
655
a98e236e
JG
656/*
657 * On some filesystems (e.g. nfs), mkdir will validate access rights before
658 * checking for the existence of the path element. This means that on a setup
659 * where "/home/" is a mounted NFS share, and running as an unpriviledged user,
660 * recursively creating a path of the form "/home/my_user/trace/" will fail with
661 * EACCES on mkdir("/home", ...).
662 *
663 * Performing a stat(...) on the path to check for existence allows us to
664 * work around this behaviour.
665 */
666static
667int mkdir_check_exists(const char *path, mode_t mode)
668{
669 int ret = 0;
670 struct stat st;
671
672 ret = stat(path, &st);
673 if (ret == 0) {
674 if (S_ISDIR(st.st_mode)) {
675 /* Directory exists, skip. */
676 goto end;
677 } else {
678 /* Exists, but is not a directory. */
679 errno = ENOTDIR;
680 ret = -1;
681 goto end;
682 }
683 }
684
685 /*
686 * Let mkdir handle other errors as the caller expects mkdir
687 * semantics.
688 */
689 ret = mkdir(path, mode);
690end:
691 return ret;
692}
693
2d851108 694/*
d77dded2 695 * Create directory using the given path and mode.
2d851108
DG
696 *
697 * On success, return 0 else a negative error code.
698 */
90e535ef 699LTTNG_HIDDEN
d77dded2
JG
700int utils_mkdir(const char *path, mode_t mode, int uid, int gid)
701{
702 int ret;
703
704 if (uid < 0 || gid < 0) {
a98e236e 705 ret = mkdir_check_exists(path, mode);
d77dded2
JG
706 } else {
707 ret = run_as_mkdir(path, mode, uid, gid);
708 }
709 if (ret < 0) {
710 if (errno != EEXIST) {
711 PERROR("mkdir %s, uid %d, gid %d", path ? path : "NULL",
712 uid, gid);
713 } else {
714 ret = 0;
715 }
716 }
717
718 return ret;
719}
720
721/*
722 * Internal version of mkdir_recursive. Runs as the current user.
723 * Don't call directly; use utils_mkdir_recursive().
724 *
725 * This function is ominously marked as "unsafe" since it should only
726 * be called by a caller that has transitioned to the uid and gid under which
727 * the directory creation should occur.
728 */
729LTTNG_HIDDEN
730int _utils_mkdir_recursive_unsafe(const char *path, mode_t mode)
2d851108
DG
731{
732 char *p, tmp[PATH_MAX];
2d851108
DG
733 size_t len;
734 int ret;
735
736 assert(path);
737
738 ret = snprintf(tmp, sizeof(tmp), "%s", path);
739 if (ret < 0) {
740 PERROR("snprintf mkdir");
741 goto error;
742 }
743
744 len = ret;
745 if (tmp[len - 1] == '/') {
746 tmp[len - 1] = 0;
747 }
748
749 for (p = tmp + 1; *p; p++) {
750 if (*p == '/') {
751 *p = 0;
752 if (tmp[strlen(tmp) - 1] == '.' &&
753 tmp[strlen(tmp) - 2] == '.' &&
754 tmp[strlen(tmp) - 3] == '/') {
755 ERR("Using '/../' is not permitted in the trace path (%s)",
756 tmp);
757 ret = -1;
758 goto error;
759 }
a98e236e 760 ret = mkdir_check_exists(tmp, mode);
2d851108 761 if (ret < 0) {
a98e236e 762 if (errno != EACCES) {
0c7bcad5
MD
763 PERROR("mkdir recursive");
764 ret = -errno;
765 goto error;
2d851108
DG
766 }
767 }
768 *p = '/';
769 }
770 }
771
a98e236e 772 ret = mkdir_check_exists(tmp, mode);
2d851108 773 if (ret < 0) {
a98e236e
JG
774 PERROR("mkdir recursive last element");
775 ret = -errno;
2d851108
DG
776 }
777
778error:
779 return ret;
780}
fe4477ee 781
d77dded2
JG
782/*
783 * Recursively create directory using the given path and mode, under the
784 * provided uid and gid.
785 *
786 * On success, return 0 else a negative error code.
787 */
788LTTNG_HIDDEN
789int utils_mkdir_recursive(const char *path, mode_t mode, int uid, int gid)
790{
791 int ret;
792
793 if (uid < 0 || gid < 0) {
794 /* Run as current user. */
795 ret = _utils_mkdir_recursive_unsafe(path, mode);
796 } else {
797 ret = run_as_mkdir_recursive(path, mode, uid, gid);
798 }
799 if (ret < 0) {
800 PERROR("mkdir %s, uid %d, gid %d", path ? path : "NULL",
801 uid, gid);
802 }
803
804 return ret;
805}
806
fe4477ee 807/*
d77dded2 808 * path is the output parameter. It needs to be PATH_MAX len.
fe4477ee
JD
809 *
810 * Return 0 on success or else a negative value.
811 */
7591bab1
MD
812static int utils_stream_file_name(char *path,
813 const char *path_name, const char *file_name,
814 uint64_t size, uint64_t count,
815 const char *suffix)
fe4477ee 816{
7591bab1
MD
817 int ret;
818 char full_path[PATH_MAX];
819 char *path_name_suffix = NULL;
309167d2 820 char *extra = NULL;
fe4477ee 821
fe4477ee
JD
822 ret = snprintf(full_path, sizeof(full_path), "%s/%s",
823 path_name, file_name);
824 if (ret < 0) {
825 PERROR("snprintf create output file");
826 goto error;
827 }
828
309167d2
JD
829 /* Setup extra string if suffix or/and a count is needed. */
830 if (size > 0 && suffix) {
831 ret = asprintf(&extra, "_%" PRIu64 "%s", count, suffix);
832 } else if (size > 0) {
833 ret = asprintf(&extra, "_%" PRIu64, count);
834 } else if (suffix) {
835 ret = asprintf(&extra, "%s", suffix);
836 }
837 if (ret < 0) {
838 PERROR("Allocating extra string to name");
839 goto error;
840 }
841
fe4477ee 842 /*
7591bab1
MD
843 * If we split the trace in multiple files, we have to add the count at
844 * the end of the tracefile name.
fe4477ee 845 */
309167d2
JD
846 if (extra) {
847 ret = asprintf(&path_name_suffix, "%s%s", full_path, extra);
fe4477ee 848 if (ret < 0) {
309167d2
JD
849 PERROR("Allocating path name with extra string");
850 goto error_free_suffix;
fe4477ee 851 }
7591bab1
MD
852 strncpy(path, path_name_suffix, PATH_MAX - 1);
853 path[PATH_MAX - 1] = '\0';
fe4477ee 854 } else {
072ede59
JG
855 ret = lttng_strncpy(path, full_path, PATH_MAX);
856 if (ret) {
857 ERR("Failed to copy stream file name");
858 goto error_free_suffix;
859 }
7591bab1
MD
860 }
861 path[PATH_MAX - 1] = '\0';
862 ret = 0;
863
864 free(path_name_suffix);
865error_free_suffix:
866 free(extra);
867error:
868 return ret;
869}
870
871/*
872 * Create the stream file on disk.
873 *
874 * Return 0 on success or else a negative value.
875 */
876LTTNG_HIDDEN
877int utils_create_stream_file(const char *path_name, char *file_name, uint64_t size,
878 uint64_t count, int uid, int gid, char *suffix)
879{
880 int ret, flags, mode;
881 char path[PATH_MAX];
882
883 ret = utils_stream_file_name(path, path_name, file_name,
884 size, count, suffix);
885 if (ret < 0) {
886 goto error;
fe4477ee
JD
887 }
888
d3ecc550
JD
889 /*
890 * With the session rotation feature on the relay, we might need to seek
891 * and truncate a tracefile, so we need read and write access.
892 */
893 flags = O_RDWR | O_CREAT | O_TRUNC;
0f907de1 894 /* Open with 660 mode */
be96a7d1
DG
895 mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
896
897 if (uid < 0 || gid < 0) {
7591bab1 898 ret = open(path, flags, mode);
be96a7d1 899 } else {
7591bab1 900 ret = run_as_open(path, flags, mode, uid, gid);
be96a7d1 901 }
7591bab1 902 if (ret < 0) {
fe4477ee 903 PERROR("open stream path %s", path);
fe4477ee 904 }
7591bab1
MD
905error:
906 return ret;
907}
fe4477ee 908
7591bab1
MD
909/*
910 * Unlink the stream tracefile from disk.
911 *
912 * Return 0 on success or else a negative value.
913 */
914LTTNG_HIDDEN
915int utils_unlink_stream_file(const char *path_name, char *file_name, uint64_t size,
916 uint64_t count, int uid, int gid, char *suffix)
917{
918 int ret;
919 char path[PATH_MAX];
920
921 ret = utils_stream_file_name(path, path_name, file_name,
922 size, count, suffix);
923 if (ret < 0) {
924 goto error;
925 }
926 if (uid < 0 || gid < 0) {
927 ret = unlink(path);
928 } else {
929 ret = run_as_unlink(path, uid, gid);
7591bab1
MD
930 }
931 if (ret < 0) {
932 goto error;
933 }
fe4477ee 934error:
7591bab1 935 DBG("utils_unlink_stream_file %s returns %d", path, ret);
fe4477ee
JD
936 return ret;
937}
938
939/*
940 * Change the output tracefile according to the given size and count The
941 * new_count pointer is set during this operation.
942 *
943 * From the consumer, the stream lock MUST be held before calling this function
944 * because we are modifying the stream status.
945 *
946 * Return 0 on success or else a negative value.
947 */
bc182241 948LTTNG_HIDDEN
fe4477ee 949int utils_rotate_stream_file(char *path_name, char *file_name, uint64_t size,
309167d2
JD
950 uint64_t count, int uid, int gid, int out_fd, uint64_t *new_count,
951 int *stream_fd)
fe4477ee
JD
952{
953 int ret;
954
309167d2
JD
955 assert(stream_fd);
956
fe4477ee
JD
957 ret = close(out_fd);
958 if (ret < 0) {
959 PERROR("Closing tracefile");
960 goto error;
961 }
b5b0c181 962 *stream_fd = -1;
fe4477ee
JD
963
964 if (count > 0) {
7591bab1
MD
965 /*
966 * In tracefile rotation, for the relay daemon we need
967 * to unlink the old file if present, because it may
968 * still be open in reading by the live thread, and we
969 * need to ensure that we do not overwrite the content
970 * between get_index and get_packet. Since we have no
971 * way to verify integrity of the data content compared
972 * to the associated index, we need to ensure the reader
973 * has exclusive access to the file content, and that
974 * the open of the data file is performed in get_index.
975 * Unlinking the old file rather than overwriting it
976 * achieves this.
977 */
93ec662e
JD
978 if (new_count) {
979 *new_count = (*new_count + 1) % count;
980 }
981 ret = utils_unlink_stream_file(path_name, file_name, size,
982 new_count ? *new_count : 0, uid, gid, 0);
7591bab1
MD
983 if (ret < 0 && errno != ENOENT) {
984 goto error;
985 }
fe4477ee 986 } else {
93ec662e
JD
987 if (new_count) {
988 (*new_count)++;
989 }
fe4477ee
JD
990 }
991
93ec662e
JD
992 ret = utils_create_stream_file(path_name, file_name, size,
993 new_count ? *new_count : 0, uid, gid, 0);
309167d2
JD
994 if (ret < 0) {
995 goto error;
996 }
997 *stream_fd = ret;
998
999 /* Success. */
1000 ret = 0;
1001
fe4477ee
JD
1002error:
1003 return ret;
1004}
70d0b120 1005
70d0b120
SM
1006
1007/**
1008 * Parse a string that represents a size in human readable format. It
5983a922 1009 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
70d0b120
SM
1010 *
1011 * The suffix multiply the integer by:
1012 * 'k': 1024
1013 * 'M': 1024^2
1014 * 'G': 1024^3
1015 *
1016 * @param str The string to parse.
5983a922 1017 * @param size Pointer to a uint64_t that will be filled with the
cfa9a5a2 1018 * resulting size.
70d0b120
SM
1019 *
1020 * @return 0 on success, -1 on failure.
1021 */
00a52467 1022LTTNG_HIDDEN
5983a922 1023int utils_parse_size_suffix(const char * const str, uint64_t * const size)
70d0b120 1024{
70d0b120 1025 int ret;
5983a922 1026 uint64_t base_size;
70d0b120 1027 long shift = 0;
5983a922
SM
1028 const char *str_end;
1029 char *num_end;
70d0b120
SM
1030
1031 if (!str) {
5983a922 1032 DBG("utils_parse_size_suffix: received a NULL string.");
70d0b120
SM
1033 ret = -1;
1034 goto end;
1035 }
1036
5983a922
SM
1037 /* strtoull will accept a negative number, but we don't want to. */
1038 if (strchr(str, '-') != NULL) {
1039 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
70d0b120 1040 ret = -1;
5983a922 1041 goto end;
70d0b120
SM
1042 }
1043
5983a922
SM
1044 /* str_end will point to the \0 */
1045 str_end = str + strlen(str);
70d0b120 1046 errno = 0;
5983a922 1047 base_size = strtoull(str, &num_end, 0);
70d0b120 1048 if (errno != 0) {
5983a922 1049 PERROR("utils_parse_size_suffix strtoull");
70d0b120 1050 ret = -1;
5983a922
SM
1051 goto end;
1052 }
1053
1054 if (num_end == str) {
1055 /* strtoull parsed nothing, not good. */
1056 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
1057 ret = -1;
1058 goto end;
1059 }
1060
1061 /* Check if a prefix is present. */
1062 switch (*num_end) {
1063 case 'G':
1064 shift = GIBI_LOG2;
1065 num_end++;
1066 break;
1067 case 'M': /* */
1068 shift = MEBI_LOG2;
1069 num_end++;
1070 break;
1071 case 'K':
1072 case 'k':
1073 shift = KIBI_LOG2;
1074 num_end++;
1075 break;
1076 case '\0':
1077 break;
1078 default:
1079 DBG("utils_parse_size_suffix: invalid suffix.");
1080 ret = -1;
1081 goto end;
1082 }
1083
1084 /* Check for garbage after the valid input. */
1085 if (num_end != str_end) {
1086 DBG("utils_parse_size_suffix: Garbage after size string.");
1087 ret = -1;
1088 goto end;
70d0b120
SM
1089 }
1090
1091 *size = base_size << shift;
1092
1093 /* Check for overflow */
1094 if ((*size >> shift) != base_size) {
5983a922 1095 DBG("utils_parse_size_suffix: oops, overflow detected.");
70d0b120 1096 ret = -1;
5983a922 1097 goto end;
70d0b120
SM
1098 }
1099
1100 ret = 0;
70d0b120
SM
1101end:
1102 return ret;
1103}
cfa9a5a2 1104
7010c033
SM
1105/**
1106 * Parse a string that represents a time in human readable format. It
1107 * supports decimal integers suffixed by 's', 'u', 'm', 'us', and 'ms'.
1108 *
1109 * The suffix multiply the integer by:
1110 * 'u'/'us': 1
1111 * 'm'/'ms': 1000
1112 * 's': 1000000
1113 *
1114 * Note that unit-less numbers are assumed to be microseconds.
1115 *
1116 * @param str The string to parse, assumed to be NULL-terminated.
1117 * @param time_us Pointer to a uint64_t that will be filled with the
1118 * resulting time in microseconds.
1119 *
1120 * @return 0 on success, -1 on failure.
1121 */
1122LTTNG_HIDDEN
1123int utils_parse_time_suffix(char const * const str, uint64_t * const time_us)
1124{
1125 int ret;
1126 uint64_t base_time;
1127 long multiplier = 1;
1128 const char *str_end;
1129 char *num_end;
1130
1131 if (!str) {
1132 DBG("utils_parse_time_suffix: received a NULL string.");
1133 ret = -1;
1134 goto end;
1135 }
1136
1137 /* strtoull will accept a negative number, but we don't want to. */
1138 if (strchr(str, '-') != NULL) {
1139 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
1140 ret = -1;
1141 goto end;
1142 }
1143
1144 /* str_end will point to the \0 */
1145 str_end = str + strlen(str);
1146 errno = 0;
1147 base_time = strtoull(str, &num_end, 10);
1148 if (errno != 0) {
1149 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str);
1150 ret = -1;
1151 goto end;
1152 }
1153
1154 if (num_end == str) {
1155 /* strtoull parsed nothing, not good. */
1156 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
1157 ret = -1;
1158 goto end;
1159 }
1160
1161 /* Check if a prefix is present. */
1162 switch (*num_end) {
1163 case 'u':
1164 multiplier = 1;
1165 /* Skip another letter in the 'us' case. */
1166 num_end += (*(num_end + 1) == 's') ? 2 : 1;
1167 break;
1168 case 'm':
1169 multiplier = 1000;
1170 /* Skip another letter in the 'ms' case. */
1171 num_end += (*(num_end + 1) == 's') ? 2 : 1;
1172 break;
1173 case 's':
1174 multiplier = 1000000;
1175 num_end++;
1176 break;
1177 case '\0':
1178 break;
1179 default:
1180 DBG("utils_parse_time_suffix: invalid suffix.");
1181 ret = -1;
1182 goto end;
1183 }
1184
1185 /* Check for garbage after the valid input. */
1186 if (num_end != str_end) {
1187 DBG("utils_parse_time_suffix: Garbage after time string.");
1188 ret = -1;
1189 goto end;
1190 }
1191
1192 *time_us = base_time * multiplier;
1193
1194 /* Check for overflow */
1195 if ((*time_us / multiplier) != base_time) {
1196 DBG("utils_parse_time_suffix: oops, overflow detected.");
1197 ret = -1;
1198 goto end;
1199 }
1200
1201 ret = 0;
1202end:
1203 return ret;
1204}
1205
cfa9a5a2
DG
1206/*
1207 * fls: returns the position of the most significant bit.
1208 * Returns 0 if no bit is set, else returns the position of the most
1209 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
1210 */
1211#if defined(__i386) || defined(__x86_64)
1212static inline unsigned int fls_u32(uint32_t x)
1213{
1214 int r;
1215
1216 asm("bsrl %1,%0\n\t"
1217 "jnz 1f\n\t"
1218 "movl $-1,%0\n\t"
1219 "1:\n\t"
1220 : "=r" (r) : "rm" (x));
1221 return r + 1;
1222}
1223#define HAS_FLS_U32
1224#endif
1225
db5be0a3
JG
1226#if defined(__x86_64)
1227static inline
1228unsigned int fls_u64(uint64_t x)
1229{
1230 long r;
1231
1232 asm("bsrq %1,%0\n\t"
1233 "jnz 1f\n\t"
1234 "movq $-1,%0\n\t"
1235 "1:\n\t"
1236 : "=r" (r) : "rm" (x));
1237 return r + 1;
1238}
1239#define HAS_FLS_U64
1240#endif
1241
1242#ifndef HAS_FLS_U64
1243static __attribute__((unused))
1244unsigned int fls_u64(uint64_t x)
1245{
1246 unsigned int r = 64;
1247
1248 if (!x)
1249 return 0;
1250
1251 if (!(x & 0xFFFFFFFF00000000ULL)) {
1252 x <<= 32;
1253 r -= 32;
1254 }
1255 if (!(x & 0xFFFF000000000000ULL)) {
1256 x <<= 16;
1257 r -= 16;
1258 }
1259 if (!(x & 0xFF00000000000000ULL)) {
1260 x <<= 8;
1261 r -= 8;
1262 }
1263 if (!(x & 0xF000000000000000ULL)) {
1264 x <<= 4;
1265 r -= 4;
1266 }
1267 if (!(x & 0xC000000000000000ULL)) {
1268 x <<= 2;
1269 r -= 2;
1270 }
1271 if (!(x & 0x8000000000000000ULL)) {
1272 x <<= 1;
1273 r -= 1;
1274 }
1275 return r;
1276}
1277#endif
1278
cfa9a5a2
DG
1279#ifndef HAS_FLS_U32
1280static __attribute__((unused)) unsigned int fls_u32(uint32_t x)
1281{
1282 unsigned int r = 32;
1283
1284 if (!x) {
1285 return 0;
1286 }
1287 if (!(x & 0xFFFF0000U)) {
1288 x <<= 16;
1289 r -= 16;
1290 }
1291 if (!(x & 0xFF000000U)) {
1292 x <<= 8;
1293 r -= 8;
1294 }
1295 if (!(x & 0xF0000000U)) {
1296 x <<= 4;
1297 r -= 4;
1298 }
1299 if (!(x & 0xC0000000U)) {
1300 x <<= 2;
1301 r -= 2;
1302 }
1303 if (!(x & 0x80000000U)) {
1304 x <<= 1;
1305 r -= 1;
1306 }
1307 return r;
1308}
1309#endif
1310
1311/*
1312 * Return the minimum order for which x <= (1UL << order).
1313 * Return -1 if x is 0.
1314 */
1315LTTNG_HIDDEN
1316int utils_get_count_order_u32(uint32_t x)
1317{
1318 if (!x) {
1319 return -1;
1320 }
1321
1322 return fls_u32(x - 1);
1323}
feb0f3e5 1324
db5be0a3
JG
1325/*
1326 * Return the minimum order for which x <= (1UL << order).
1327 * Return -1 if x is 0.
1328 */
1329LTTNG_HIDDEN
1330int utils_get_count_order_u64(uint64_t x)
1331{
1332 if (!x) {
1333 return -1;
1334 }
1335
1336 return fls_u64(x - 1);
1337}
1338
feb0f3e5
AM
1339/**
1340 * Obtain the value of LTTNG_HOME environment variable, if exists.
1341 * Otherwise returns the value of HOME.
1342 */
00a52467 1343LTTNG_HIDDEN
feb0f3e5
AM
1344char *utils_get_home_dir(void)
1345{
1346 char *val = NULL;
04135dbd
DG
1347 struct passwd *pwd;
1348
e8fa9fb0 1349 val = lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR);
feb0f3e5 1350 if (val != NULL) {
04135dbd
DG
1351 goto end;
1352 }
e8fa9fb0 1353 val = lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR);
04135dbd
DG
1354 if (val != NULL) {
1355 goto end;
feb0f3e5 1356 }
04135dbd
DG
1357
1358 /* Fallback on the password file entry. */
1359 pwd = getpwuid(getuid());
1360 if (!pwd) {
1361 goto end;
1362 }
1363 val = pwd->pw_dir;
1364
1365 DBG3("Home directory is '%s'", val);
1366
1367end:
1368 return val;
feb0f3e5 1369}
26fe5938 1370
fb198a11
JG
1371/**
1372 * Get user's home directory. Dynamically allocated, must be freed
1373 * by the caller.
1374 */
1375LTTNG_HIDDEN
1376char *utils_get_user_home_dir(uid_t uid)
1377{
1378 struct passwd pwd;
1379 struct passwd *result;
1380 char *home_dir = NULL;
1381 char *buf = NULL;
1382 long buflen;
1383 int ret;
1384
1385 buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
1386 if (buflen == -1) {
1387 goto end;
1388 }
1389retry:
1390 buf = zmalloc(buflen);
1391 if (!buf) {
1392 goto end;
1393 }
1394
1395 ret = getpwuid_r(uid, &pwd, buf, buflen, &result);
1396 if (ret || !result) {
1397 if (ret == ERANGE) {
1398 free(buf);
1399 buflen *= 2;
1400 goto retry;
1401 }
1402 goto end;
1403 }
1404
1405 home_dir = strdup(pwd.pw_dir);
1406end:
1407 free(buf);
1408 return home_dir;
1409}
1410
26fe5938
DG
1411/*
1412 * With the given format, fill dst with the time of len maximum siz.
1413 *
1414 * Return amount of bytes set in the buffer or else 0 on error.
1415 */
1416LTTNG_HIDDEN
1417size_t utils_get_current_time_str(const char *format, char *dst, size_t len)
1418{
1419 size_t ret;
1420 time_t rawtime;
1421 struct tm *timeinfo;
1422
1423 assert(format);
1424 assert(dst);
1425
1426 /* Get date and time for session path */
1427 time(&rawtime);
1428 timeinfo = localtime(&rawtime);
1429 ret = strftime(dst, len, format, timeinfo);
1430 if (ret == 0) {
68e6efdd 1431 ERR("Unable to strftime with format %s at dst %p of len %zu", format,
26fe5938
DG
1432 dst, len);
1433 }
1434
1435 return ret;
1436}
6c71277b
MD
1437
1438/*
1439 * Return the group ID matching name, else 0 if it cannot be found.
1440 */
1441LTTNG_HIDDEN
1442gid_t utils_get_group_id(const char *name)
1443{
1444 struct group *grp;
1445
1446 grp = getgrnam(name);
1447 if (!grp) {
1448 static volatile int warn_once;
1449
1450 if (!warn_once) {
1451 WARN("No tracing group detected");
1452 warn_once = 1;
1453 }
1454 return 0;
1455 }
1456 return grp->gr_gid;
1457}
8db0dc00
JG
1458
1459/*
1460 * Return a newly allocated option string. This string is to be used as the
1461 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1462 * of elements in the long_options array. Returns NULL if the string's
1463 * allocation fails.
1464 */
1465LTTNG_HIDDEN
1466char *utils_generate_optstring(const struct option *long_options,
1467 size_t opt_count)
1468{
1469 int i;
1470 size_t string_len = opt_count, str_pos = 0;
1471 char *optstring;
1472
1473 /*
1474 * Compute the necessary string length. One letter per option, two when an
1475 * argument is necessary, and a trailing NULL.
1476 */
1477 for (i = 0; i < opt_count; i++) {
1478 string_len += long_options[i].has_arg ? 1 : 0;
1479 }
1480
1481 optstring = zmalloc(string_len);
1482 if (!optstring) {
1483 goto end;
1484 }
1485
1486 for (i = 0; i < opt_count; i++) {
1487 if (!long_options[i].name) {
1488 /* Got to the trailing NULL element */
1489 break;
1490 }
1491
a596dcb9
JG
1492 if (long_options[i].val != '\0') {
1493 optstring[str_pos++] = (char) long_options[i].val;
1494 if (long_options[i].has_arg) {
1495 optstring[str_pos++] = ':';
1496 }
8db0dc00
JG
1497 }
1498 }
1499
1500end:
1501 return optstring;
1502}
3d071855
MD
1503
1504/*
1505 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
9529ec1b 1506 * any file. Try to rmdir any empty directory within the hierarchy.
3d071855
MD
1507 */
1508LTTNG_HIDDEN
1509int utils_recursive_rmdir(const char *path)
1510{
1511 DIR *dir;
7a946beb 1512 size_t path_len;
9529ec1b 1513 int dir_fd, ret = 0, closeret, is_empty = 1;
3d071855
MD
1514 struct dirent *entry;
1515
1516 /* Open directory */
1517 dir = opendir(path);
1518 if (!dir) {
1519 PERROR("Cannot open '%s' path", path);
1520 return -1;
1521 }
5a2451c9 1522 dir_fd = lttng_dirfd(dir);
3d071855 1523 if (dir_fd < 0) {
5a2451c9 1524 PERROR("lttng_dirfd");
3d071855
MD
1525 return -1;
1526 }
1527
7a946beb 1528 path_len = strlen(path);
3d071855 1529 while ((entry = readdir(dir))) {
7a946beb
MJ
1530 struct stat st;
1531 size_t name_len;
1532 char filename[PATH_MAX];
1533
3763af87
JG
1534 if (!strcmp(entry->d_name, ".")
1535 || !strcmp(entry->d_name, "..")) {
1536 continue;
1537 }
1538
7a946beb
MJ
1539 name_len = strlen(entry->d_name);
1540 if (path_len + name_len + 2 > sizeof(filename)) {
1541 ERR("Failed to remove file: path name too long (%s/%s)",
1542 path, entry->d_name);
1543 continue;
1544 }
1545 if (snprintf(filename, sizeof(filename), "%s/%s",
1546 path, entry->d_name) < 0) {
1547 ERR("Failed to format path.");
1548 continue;
1549 }
1550
1551 if (stat(filename, &st)) {
1552 PERROR("stat");
1553 continue;
1554 }
1555
1556 if (S_ISDIR(st.st_mode)) {
3d071855
MD
1557 char subpath[PATH_MAX];
1558
1559 strncpy(subpath, path, PATH_MAX);
1560 subpath[PATH_MAX - 1] = '\0';
1561 strncat(subpath, "/",
1562 PATH_MAX - strlen(subpath) - 1);
1563 strncat(subpath, entry->d_name,
1564 PATH_MAX - strlen(subpath) - 1);
9529ec1b
MD
1565 if (utils_recursive_rmdir(subpath)) {
1566 is_empty = 0;
3d071855 1567 }
7a946beb 1568 } else if (S_ISREG(st.st_mode)) {
9529ec1b 1569 is_empty = 0;
7a946beb 1570 } else {
3d071855
MD
1571 ret = -EINVAL;
1572 goto end;
1573 }
1574 }
1575end:
1576 closeret = closedir(dir);
1577 if (closeret) {
1578 PERROR("closedir");
1579 }
9529ec1b 1580 if (is_empty) {
3d071855
MD
1581 DBG3("Attempting rmdir %s", path);
1582 ret = rmdir(path);
1583 }
1584 return ret;
1585}
93ec662e
JD
1586
1587LTTNG_HIDDEN
1588int utils_truncate_stream_file(int fd, off_t length)
1589{
1590 int ret;
a5df8828 1591 off_t lseek_ret;
93ec662e
JD
1592
1593 ret = ftruncate(fd, length);
1594 if (ret < 0) {
1595 PERROR("ftruncate");
1596 goto end;
1597 }
a5df8828
GL
1598 lseek_ret = lseek(fd, length, SEEK_SET);
1599 if (lseek_ret < 0) {
93ec662e 1600 PERROR("lseek");
a5df8828 1601 ret = -1;
93ec662e
JD
1602 goto end;
1603 }
93ec662e
JD
1604end:
1605 return ret;
1606}
4ba92f18
PP
1607
1608static const char *get_man_bin_path(void)
1609{
b7dce40d 1610 char *env_man_path = lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV);
4ba92f18
PP
1611
1612 if (env_man_path) {
1613 return env_man_path;
1614 }
1615
1616 return DEFAULT_MAN_BIN_PATH;
1617}
1618
1619LTTNG_HIDDEN
4fc83d94
PP
1620int utils_show_help(int section, const char *page_name,
1621 const char *help_msg)
4ba92f18
PP
1622{
1623 char section_string[8];
1624 const char *man_bin_path = get_man_bin_path();
4fc83d94
PP
1625 int ret = 0;
1626
1627 if (help_msg) {
1628 printf("%s", help_msg);
1629 goto end;
1630 }
4ba92f18
PP
1631
1632 /* Section integer -> section string */
1633 ret = sprintf(section_string, "%d", section);
1634 assert(ret > 0 && ret < 8);
1635
1636 /*
1637 * Execute man pager.
1638 *
b07e7ef0 1639 * We provide -M to man here because LTTng-tools can
4ba92f18
PP
1640 * be installed outside /usr, in which case its man pages are
1641 * not located in the default /usr/share/man directory.
1642 */
b07e7ef0 1643 ret = execlp(man_bin_path, "man", "-M", MANPATH,
4ba92f18 1644 section_string, page_name, NULL);
4fc83d94
PP
1645
1646end:
4ba92f18
PP
1647 return ret;
1648}
This page took 0.118918 seconds and 4 git commands to generate.