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