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