MI: add schemaVersion attribute to command schema
[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(new_count);
847 assert(stream_fd);
848
fe4477ee
JD
849 ret = close(out_fd);
850 if (ret < 0) {
851 PERROR("Closing tracefile");
852 goto error;
853 }
854
855 if (count > 0) {
7591bab1
MD
856 /*
857 * In tracefile rotation, for the relay daemon we need
858 * to unlink the old file if present, because it may
859 * still be open in reading by the live thread, and we
860 * need to ensure that we do not overwrite the content
861 * between get_index and get_packet. Since we have no
862 * way to verify integrity of the data content compared
863 * to the associated index, we need to ensure the reader
864 * has exclusive access to the file content, and that
865 * the open of the data file is performed in get_index.
866 * Unlinking the old file rather than overwriting it
867 * achieves this.
868 */
fe4477ee 869 *new_count = (*new_count + 1) % count;
7591bab1
MD
870 ret = utils_unlink_stream_file(path_name, file_name,
871 size, *new_count, uid, gid, 0);
872 if (ret < 0 && errno != ENOENT) {
873 goto error;
874 }
fe4477ee
JD
875 } else {
876 (*new_count)++;
877 }
878
309167d2
JD
879 ret = utils_create_stream_file(path_name, file_name, size, *new_count,
880 uid, gid, 0);
881 if (ret < 0) {
882 goto error;
883 }
884 *stream_fd = ret;
885
886 /* Success. */
887 ret = 0;
888
fe4477ee
JD
889error:
890 return ret;
891}
70d0b120 892
70d0b120
SM
893
894/**
895 * Parse a string that represents a size in human readable format. It
5983a922 896 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
70d0b120
SM
897 *
898 * The suffix multiply the integer by:
899 * 'k': 1024
900 * 'M': 1024^2
901 * 'G': 1024^3
902 *
903 * @param str The string to parse.
5983a922 904 * @param size Pointer to a uint64_t that will be filled with the
cfa9a5a2 905 * resulting size.
70d0b120
SM
906 *
907 * @return 0 on success, -1 on failure.
908 */
00a52467 909LTTNG_HIDDEN
5983a922 910int utils_parse_size_suffix(const char * const str, uint64_t * const size)
70d0b120 911{
70d0b120 912 int ret;
5983a922 913 uint64_t base_size;
70d0b120 914 long shift = 0;
5983a922
SM
915 const char *str_end;
916 char *num_end;
70d0b120
SM
917
918 if (!str) {
5983a922 919 DBG("utils_parse_size_suffix: received a NULL string.");
70d0b120
SM
920 ret = -1;
921 goto end;
922 }
923
5983a922
SM
924 /* strtoull will accept a negative number, but we don't want to. */
925 if (strchr(str, '-') != NULL) {
926 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
70d0b120 927 ret = -1;
5983a922 928 goto end;
70d0b120
SM
929 }
930
5983a922
SM
931 /* str_end will point to the \0 */
932 str_end = str + strlen(str);
70d0b120 933 errno = 0;
5983a922 934 base_size = strtoull(str, &num_end, 0);
70d0b120 935 if (errno != 0) {
5983a922 936 PERROR("utils_parse_size_suffix strtoull");
70d0b120 937 ret = -1;
5983a922
SM
938 goto end;
939 }
940
941 if (num_end == str) {
942 /* strtoull parsed nothing, not good. */
943 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
944 ret = -1;
945 goto end;
946 }
947
948 /* Check if a prefix is present. */
949 switch (*num_end) {
950 case 'G':
951 shift = GIBI_LOG2;
952 num_end++;
953 break;
954 case 'M': /* */
955 shift = MEBI_LOG2;
956 num_end++;
957 break;
958 case 'K':
959 case 'k':
960 shift = KIBI_LOG2;
961 num_end++;
962 break;
963 case '\0':
964 break;
965 default:
966 DBG("utils_parse_size_suffix: invalid suffix.");
967 ret = -1;
968 goto end;
969 }
970
971 /* Check for garbage after the valid input. */
972 if (num_end != str_end) {
973 DBG("utils_parse_size_suffix: Garbage after size string.");
974 ret = -1;
975 goto end;
70d0b120
SM
976 }
977
978 *size = base_size << shift;
979
980 /* Check for overflow */
981 if ((*size >> shift) != base_size) {
5983a922 982 DBG("utils_parse_size_suffix: oops, overflow detected.");
70d0b120 983 ret = -1;
5983a922 984 goto end;
70d0b120
SM
985 }
986
987 ret = 0;
70d0b120
SM
988end:
989 return ret;
990}
cfa9a5a2
DG
991
992/*
993 * fls: returns the position of the most significant bit.
994 * Returns 0 if no bit is set, else returns the position of the most
995 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
996 */
997#if defined(__i386) || defined(__x86_64)
998static inline unsigned int fls_u32(uint32_t x)
999{
1000 int r;
1001
1002 asm("bsrl %1,%0\n\t"
1003 "jnz 1f\n\t"
1004 "movl $-1,%0\n\t"
1005 "1:\n\t"
1006 : "=r" (r) : "rm" (x));
1007 return r + 1;
1008}
1009#define HAS_FLS_U32
1010#endif
1011
1012#ifndef HAS_FLS_U32
1013static __attribute__((unused)) unsigned int fls_u32(uint32_t x)
1014{
1015 unsigned int r = 32;
1016
1017 if (!x) {
1018 return 0;
1019 }
1020 if (!(x & 0xFFFF0000U)) {
1021 x <<= 16;
1022 r -= 16;
1023 }
1024 if (!(x & 0xFF000000U)) {
1025 x <<= 8;
1026 r -= 8;
1027 }
1028 if (!(x & 0xF0000000U)) {
1029 x <<= 4;
1030 r -= 4;
1031 }
1032 if (!(x & 0xC0000000U)) {
1033 x <<= 2;
1034 r -= 2;
1035 }
1036 if (!(x & 0x80000000U)) {
1037 x <<= 1;
1038 r -= 1;
1039 }
1040 return r;
1041}
1042#endif
1043
1044/*
1045 * Return the minimum order for which x <= (1UL << order).
1046 * Return -1 if x is 0.
1047 */
1048LTTNG_HIDDEN
1049int utils_get_count_order_u32(uint32_t x)
1050{
1051 if (!x) {
1052 return -1;
1053 }
1054
1055 return fls_u32(x - 1);
1056}
feb0f3e5
AM
1057
1058/**
1059 * Obtain the value of LTTNG_HOME environment variable, if exists.
1060 * Otherwise returns the value of HOME.
1061 */
00a52467 1062LTTNG_HIDDEN
feb0f3e5
AM
1063char *utils_get_home_dir(void)
1064{
1065 char *val = NULL;
04135dbd
DG
1066 struct passwd *pwd;
1067
e8fa9fb0 1068 val = lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR);
feb0f3e5 1069 if (val != NULL) {
04135dbd
DG
1070 goto end;
1071 }
e8fa9fb0 1072 val = lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR);
04135dbd
DG
1073 if (val != NULL) {
1074 goto end;
feb0f3e5 1075 }
04135dbd
DG
1076
1077 /* Fallback on the password file entry. */
1078 pwd = getpwuid(getuid());
1079 if (!pwd) {
1080 goto end;
1081 }
1082 val = pwd->pw_dir;
1083
1084 DBG3("Home directory is '%s'", val);
1085
1086end:
1087 return val;
feb0f3e5 1088}
26fe5938 1089
fb198a11
JG
1090/**
1091 * Get user's home directory. Dynamically allocated, must be freed
1092 * by the caller.
1093 */
1094LTTNG_HIDDEN
1095char *utils_get_user_home_dir(uid_t uid)
1096{
1097 struct passwd pwd;
1098 struct passwd *result;
1099 char *home_dir = NULL;
1100 char *buf = NULL;
1101 long buflen;
1102 int ret;
1103
1104 buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
1105 if (buflen == -1) {
1106 goto end;
1107 }
1108retry:
1109 buf = zmalloc(buflen);
1110 if (!buf) {
1111 goto end;
1112 }
1113
1114 ret = getpwuid_r(uid, &pwd, buf, buflen, &result);
1115 if (ret || !result) {
1116 if (ret == ERANGE) {
1117 free(buf);
1118 buflen *= 2;
1119 goto retry;
1120 }
1121 goto end;
1122 }
1123
1124 home_dir = strdup(pwd.pw_dir);
1125end:
1126 free(buf);
1127 return home_dir;
1128}
1129
fbb9748b
JG
1130/*
1131 * Obtain the value of LTTNG_KMOD_PROBES environment variable, if exists.
c9d42407 1132 * Otherwise returns NULL.
fbb9748b
JG
1133 */
1134LTTNG_HIDDEN
1135char *utils_get_kmod_probes_list(void)
1136{
e8fa9fb0 1137 return lttng_secure_getenv(DEFAULT_LTTNG_KMOD_PROBES);
fbb9748b
JG
1138}
1139
c9d42407
PP
1140/*
1141 * Obtain the value of LTTNG_EXTRA_KMOD_PROBES environment variable, if
1142 * exists. Otherwise returns NULL.
1143 */
1144LTTNG_HIDDEN
1145char *utils_get_extra_kmod_probes_list(void)
1146{
e8fa9fb0 1147 return lttng_secure_getenv(DEFAULT_LTTNG_EXTRA_KMOD_PROBES);
c9d42407
PP
1148}
1149
26fe5938
DG
1150/*
1151 * With the given format, fill dst with the time of len maximum siz.
1152 *
1153 * Return amount of bytes set in the buffer or else 0 on error.
1154 */
1155LTTNG_HIDDEN
1156size_t utils_get_current_time_str(const char *format, char *dst, size_t len)
1157{
1158 size_t ret;
1159 time_t rawtime;
1160 struct tm *timeinfo;
1161
1162 assert(format);
1163 assert(dst);
1164
1165 /* Get date and time for session path */
1166 time(&rawtime);
1167 timeinfo = localtime(&rawtime);
1168 ret = strftime(dst, len, format, timeinfo);
1169 if (ret == 0) {
68e6efdd 1170 ERR("Unable to strftime with format %s at dst %p of len %zu", format,
26fe5938
DG
1171 dst, len);
1172 }
1173
1174 return ret;
1175}
6c71277b
MD
1176
1177/*
1178 * Return the group ID matching name, else 0 if it cannot be found.
1179 */
1180LTTNG_HIDDEN
1181gid_t utils_get_group_id(const char *name)
1182{
1183 struct group *grp;
1184
1185 grp = getgrnam(name);
1186 if (!grp) {
1187 static volatile int warn_once;
1188
1189 if (!warn_once) {
1190 WARN("No tracing group detected");
1191 warn_once = 1;
1192 }
1193 return 0;
1194 }
1195 return grp->gr_gid;
1196}
8db0dc00
JG
1197
1198/*
1199 * Return a newly allocated option string. This string is to be used as the
1200 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1201 * of elements in the long_options array. Returns NULL if the string's
1202 * allocation fails.
1203 */
1204LTTNG_HIDDEN
1205char *utils_generate_optstring(const struct option *long_options,
1206 size_t opt_count)
1207{
1208 int i;
1209 size_t string_len = opt_count, str_pos = 0;
1210 char *optstring;
1211
1212 /*
1213 * Compute the necessary string length. One letter per option, two when an
1214 * argument is necessary, and a trailing NULL.
1215 */
1216 for (i = 0; i < opt_count; i++) {
1217 string_len += long_options[i].has_arg ? 1 : 0;
1218 }
1219
1220 optstring = zmalloc(string_len);
1221 if (!optstring) {
1222 goto end;
1223 }
1224
1225 for (i = 0; i < opt_count; i++) {
1226 if (!long_options[i].name) {
1227 /* Got to the trailing NULL element */
1228 break;
1229 }
1230
a596dcb9
JG
1231 if (long_options[i].val != '\0') {
1232 optstring[str_pos++] = (char) long_options[i].val;
1233 if (long_options[i].has_arg) {
1234 optstring[str_pos++] = ':';
1235 }
8db0dc00
JG
1236 }
1237 }
1238
1239end:
1240 return optstring;
1241}
3d071855
MD
1242
1243/*
1244 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
9529ec1b 1245 * any file. Try to rmdir any empty directory within the hierarchy.
3d071855
MD
1246 */
1247LTTNG_HIDDEN
1248int utils_recursive_rmdir(const char *path)
1249{
1250 DIR *dir;
7a946beb 1251 size_t path_len;
9529ec1b 1252 int dir_fd, ret = 0, closeret, is_empty = 1;
3d071855
MD
1253 struct dirent *entry;
1254
1255 /* Open directory */
1256 dir = opendir(path);
1257 if (!dir) {
1258 PERROR("Cannot open '%s' path", path);
1259 return -1;
1260 }
5a2451c9 1261 dir_fd = lttng_dirfd(dir);
3d071855 1262 if (dir_fd < 0) {
5a2451c9 1263 PERROR("lttng_dirfd");
3d071855
MD
1264 return -1;
1265 }
1266
7a946beb 1267 path_len = strlen(path);
3d071855 1268 while ((entry = readdir(dir))) {
7a946beb
MJ
1269 struct stat st;
1270 size_t name_len;
1271 char filename[PATH_MAX];
1272
3763af87
JG
1273 if (!strcmp(entry->d_name, ".")
1274 || !strcmp(entry->d_name, "..")) {
1275 continue;
1276 }
1277
7a946beb
MJ
1278 name_len = strlen(entry->d_name);
1279 if (path_len + name_len + 2 > sizeof(filename)) {
1280 ERR("Failed to remove file: path name too long (%s/%s)",
1281 path, entry->d_name);
1282 continue;
1283 }
1284 if (snprintf(filename, sizeof(filename), "%s/%s",
1285 path, entry->d_name) < 0) {
1286 ERR("Failed to format path.");
1287 continue;
1288 }
1289
1290 if (stat(filename, &st)) {
1291 PERROR("stat");
1292 continue;
1293 }
1294
1295 if (S_ISDIR(st.st_mode)) {
3d071855
MD
1296 char subpath[PATH_MAX];
1297
1298 strncpy(subpath, path, PATH_MAX);
1299 subpath[PATH_MAX - 1] = '\0';
1300 strncat(subpath, "/",
1301 PATH_MAX - strlen(subpath) - 1);
1302 strncat(subpath, entry->d_name,
1303 PATH_MAX - strlen(subpath) - 1);
9529ec1b
MD
1304 if (utils_recursive_rmdir(subpath)) {
1305 is_empty = 0;
3d071855 1306 }
7a946beb 1307 } else if (S_ISREG(st.st_mode)) {
9529ec1b 1308 is_empty = 0;
7a946beb 1309 } else {
3d071855
MD
1310 ret = -EINVAL;
1311 goto end;
1312 }
1313 }
1314end:
1315 closeret = closedir(dir);
1316 if (closeret) {
1317 PERROR("closedir");
1318 }
9529ec1b 1319 if (is_empty) {
3d071855
MD
1320 DBG3("Attempting rmdir %s", path);
1321 ret = rmdir(path);
1322 }
1323 return ret;
1324}
This page took 0.107575 seconds and 5 git commands to generate.