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