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