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