Misleading error handling: utils_create_pid_file() should return 0 on success
[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>
81b86775
DG
35
36#include <common/common.h>
fe4477ee 37#include <common/runas.h>
81b86775
DG
38
39#include "utils.h"
feb0f3e5 40#include "defaults.h"
81b86775 41
5154230f
RB
42/*
43 * Return a partial realpath(3) of the path even if the full path does not
44 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
45 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
46 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
47 * point directory does not exist.
48 * In case resolved_path is NULL, the string returned was allocated in the
49 * function and thus need to be freed by the caller. The size argument allows
50 * to specify the size of the resolved_path argument if given, or the size to
51 * allocate.
52 */
53LTTNG_HIDDEN
54char *utils_partial_realpath(const char *path, char *resolved_path, size_t size)
55{
56 char *cut_path, *try_path = NULL, *try_path_prev = NULL;
57 const char *next, *prev, *end;
58
59 /* Safety net */
60 if (path == NULL) {
61 goto error;
62 }
63
64 /*
65 * Identify the end of the path, we don't want to treat the
66 * last char if it is a '/', we will just keep it on the side
67 * to be added at the end, and return a value coherent with
68 * the path given as argument
69 */
70 end = path + strlen(path);
71 if (*(end-1) == '/') {
72 end--;
73 }
74
75 /* Initiate the values of the pointers before looping */
76 next = path;
77 prev = next;
78 /* Only to ensure try_path is not NULL to enter the while */
79 try_path = (char *)next;
80
81 /* Resolve the canonical path of the first part of the path */
82 while (try_path != NULL && next != end) {
83 /*
84 * If there is not any '/' left, we want to try with
85 * the full path
86 */
87 next = strpbrk(next + 1, "/");
88 if (next == NULL) {
89 next = end;
90 }
91
92 /* Cut the part we will be trying to resolve */
93 cut_path = strndup(path, next - path);
d9dbcf5e
MD
94 if (cut_path == NULL) {
95 PERROR("strndup");
96 goto error;
97 }
5154230f
RB
98
99 /* Try to resolve this part */
100 try_path = realpath((char *)cut_path, NULL);
101 if (try_path == NULL) {
102 /*
103 * There was an error, we just want to be assured it
104 * is linked to an unexistent directory, if it's another
105 * reason, we spawn an error
106 */
107 switch (errno) {
108 case ENOENT:
109 /* Ignore the error */
110 break;
111 default:
112 PERROR("realpath (partial_realpath)");
113 goto error;
114 break;
115 }
116 } else {
117 /* Save the place we are before trying the next step */
118 free(try_path_prev);
119 try_path_prev = try_path;
120 prev = next;
121 }
122
123 /* Free the allocated memory */
124 free(cut_path);
125 };
126
127 /* Allocate memory for the resolved path if necessary */
128 if (resolved_path == NULL) {
129 resolved_path = zmalloc(size);
130 if (resolved_path == NULL) {
131 PERROR("zmalloc resolved path");
132 goto error;
133 }
134 }
135
136 /*
137 * If we were able to solve at least partially the path, we can concatenate
138 * what worked and what didn't work
139 */
140 if (try_path_prev != NULL) {
141 /* If we risk to concatenate two '/', we remove one of them */
142 if (try_path_prev[strlen(try_path_prev) - 1] == '/' && prev[0] == '/') {
143 try_path_prev[strlen(try_path_prev) - 1] = '\0';
144 }
145
146 /*
147 * Duplicate the memory used by prev in case resolved_path and
148 * path are pointers for the same memory space
149 */
150 cut_path = strdup(prev);
d9dbcf5e
MD
151 if (cut_path == NULL) {
152 PERROR("strdup");
153 goto error;
154 }
5154230f
RB
155
156 /* Concatenate the strings */
157 snprintf(resolved_path, size, "%s%s", try_path_prev, cut_path);
158
159 /* Free the allocated memory */
160 free(cut_path);
161 free(try_path_prev);
162 /*
163 * Else, we just copy the path in our resolved_path to
164 * return it as is
165 */
166 } else {
167 strncpy(resolved_path, path, size);
168 }
169
170 /* Then we return the 'partially' resolved path */
171 return resolved_path;
172
173error:
174 free(resolved_path);
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);
d9dbcf5e
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);
d9dbcf5e
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");
e205d79b 480 goto error;
35f90c40
DG
481 }
482
e205d79b
MD
483 if (fclose(fp)) {
484 PERROR("fclose");
485 }
35f90c40 486 DBG("Pid %d written in file %s", pid, filepath);
e205d79b 487 ret = 0;
35f90c40
DG
488error:
489 return ret;
490}
2d851108 491
c9cb3e7d
JG
492/*
493 * Create lock file to the given path and filename.
494 * Returns the associated file descriptor, -1 on error.
495 */
496LTTNG_HIDDEN
497int utils_create_lock_file(const char *filepath)
498{
499 int ret;
500 int fd;
501
502 assert(filepath);
503
504 fd = open(filepath, O_CREAT,
505 O_WRONLY | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
506 if (fd < 0) {
507 PERROR("open lock file %s", filepath);
508 ret = -1;
509 goto error;
510 }
511
512 /*
513 * Attempt to lock the file. If this fails, there is
514 * already a process using the same lock file running
515 * and we should exit.
516 */
517 ret = flock(fd, LOCK_EX | LOCK_NB);
518 if (ret) {
519 WARN("Could not get lock file %s, another instance is running.",
520 filepath);
ffb0b851
JG
521 if (close(fd)) {
522 PERROR("close lock file");
523 }
c9cb3e7d
JG
524 fd = ret;
525 goto error;
526 }
527
528error:
529 return fd;
530}
531
2d851108
DG
532/*
533 * Recursively create directory using the given path and mode.
534 *
535 * On success, return 0 else a negative error code.
536 */
90e535ef 537LTTNG_HIDDEN
2d851108
DG
538int utils_mkdir_recursive(const char *path, mode_t mode)
539{
540 char *p, tmp[PATH_MAX];
2d851108
DG
541 size_t len;
542 int ret;
543
544 assert(path);
545
546 ret = snprintf(tmp, sizeof(tmp), "%s", path);
547 if (ret < 0) {
548 PERROR("snprintf mkdir");
549 goto error;
550 }
551
552 len = ret;
553 if (tmp[len - 1] == '/') {
554 tmp[len - 1] = 0;
555 }
556
557 for (p = tmp + 1; *p; p++) {
558 if (*p == '/') {
559 *p = 0;
560 if (tmp[strlen(tmp) - 1] == '.' &&
561 tmp[strlen(tmp) - 2] == '.' &&
562 tmp[strlen(tmp) - 3] == '/') {
563 ERR("Using '/../' is not permitted in the trace path (%s)",
564 tmp);
565 ret = -1;
566 goto error;
567 }
0c7bcad5 568 ret = mkdir(tmp, mode);
2d851108 569 if (ret < 0) {
0c7bcad5
MD
570 if (errno != EEXIST) {
571 PERROR("mkdir recursive");
572 ret = -errno;
573 goto error;
2d851108
DG
574 }
575 }
576 *p = '/';
577 }
578 }
579
580 ret = mkdir(tmp, mode);
581 if (ret < 0) {
582 if (errno != EEXIST) {
583 PERROR("mkdir recursive last piece");
584 ret = -errno;
585 } else {
586 ret = 0;
587 }
588 }
589
590error:
591 return ret;
592}
fe4477ee
JD
593
594/*
595 * Create the stream tracefile on disk.
596 *
597 * Return 0 on success or else a negative value.
598 */
bc182241 599LTTNG_HIDDEN
07b86b52 600int utils_create_stream_file(const char *path_name, char *file_name, uint64_t size,
309167d2 601 uint64_t count, int uid, int gid, char *suffix)
fe4477ee 602{
be96a7d1 603 int ret, out_fd, flags, mode;
309167d2
JD
604 char full_path[PATH_MAX], *path_name_suffix = NULL, *path;
605 char *extra = NULL;
fe4477ee
JD
606
607 assert(path_name);
608 assert(file_name);
609
610 ret = snprintf(full_path, sizeof(full_path), "%s/%s",
611 path_name, file_name);
612 if (ret < 0) {
613 PERROR("snprintf create output file");
614 goto error;
615 }
616
309167d2
JD
617 /* Setup extra string if suffix or/and a count is needed. */
618 if (size > 0 && suffix) {
619 ret = asprintf(&extra, "_%" PRIu64 "%s", count, suffix);
620 } else if (size > 0) {
621 ret = asprintf(&extra, "_%" PRIu64, count);
622 } else if (suffix) {
623 ret = asprintf(&extra, "%s", suffix);
624 }
625 if (ret < 0) {
626 PERROR("Allocating extra string to name");
627 goto error;
628 }
629
fe4477ee
JD
630 /*
631 * If we split the trace in multiple files, we have to add the count at the
632 * end of the tracefile name
633 */
309167d2
JD
634 if (extra) {
635 ret = asprintf(&path_name_suffix, "%s%s", full_path, extra);
fe4477ee 636 if (ret < 0) {
309167d2
JD
637 PERROR("Allocating path name with extra string");
638 goto error_free_suffix;
fe4477ee 639 }
309167d2 640 path = path_name_suffix;
fe4477ee
JD
641 } else {
642 path = full_path;
643 }
644
be96a7d1 645 flags = O_WRONLY | O_CREAT | O_TRUNC;
0f907de1 646 /* Open with 660 mode */
be96a7d1
DG
647 mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
648
649 if (uid < 0 || gid < 0) {
650 out_fd = open(path, flags, mode);
651 } else {
652 out_fd = run_as_open(path, flags, mode, uid, gid);
653 }
fe4477ee
JD
654 if (out_fd < 0) {
655 PERROR("open stream path %s", path);
656 goto error_open;
657 }
658 ret = out_fd;
659
660error_open:
309167d2
JD
661 free(path_name_suffix);
662error_free_suffix:
663 free(extra);
fe4477ee
JD
664error:
665 return ret;
666}
667
668/*
669 * Change the output tracefile according to the given size and count The
670 * new_count pointer is set during this operation.
671 *
672 * From the consumer, the stream lock MUST be held before calling this function
673 * because we are modifying the stream status.
674 *
675 * Return 0 on success or else a negative value.
676 */
bc182241 677LTTNG_HIDDEN
fe4477ee 678int utils_rotate_stream_file(char *path_name, char *file_name, uint64_t size,
309167d2
JD
679 uint64_t count, int uid, int gid, int out_fd, uint64_t *new_count,
680 int *stream_fd)
fe4477ee
JD
681{
682 int ret;
683
309167d2
JD
684 assert(new_count);
685 assert(stream_fd);
686
fe4477ee
JD
687 ret = close(out_fd);
688 if (ret < 0) {
689 PERROR("Closing tracefile");
690 goto error;
691 }
692
693 if (count > 0) {
694 *new_count = (*new_count + 1) % count;
695 } else {
696 (*new_count)++;
697 }
698
309167d2
JD
699 ret = utils_create_stream_file(path_name, file_name, size, *new_count,
700 uid, gid, 0);
701 if (ret < 0) {
702 goto error;
703 }
704 *stream_fd = ret;
705
706 /* Success. */
707 ret = 0;
708
fe4477ee
JD
709error:
710 return ret;
711}
70d0b120 712
70d0b120
SM
713
714/**
715 * Parse a string that represents a size in human readable format. It
5983a922 716 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
70d0b120
SM
717 *
718 * The suffix multiply the integer by:
719 * 'k': 1024
720 * 'M': 1024^2
721 * 'G': 1024^3
722 *
723 * @param str The string to parse.
5983a922 724 * @param size Pointer to a uint64_t that will be filled with the
cfa9a5a2 725 * resulting size.
70d0b120
SM
726 *
727 * @return 0 on success, -1 on failure.
728 */
00a52467 729LTTNG_HIDDEN
5983a922 730int utils_parse_size_suffix(const char * const str, uint64_t * const size)
70d0b120 731{
70d0b120 732 int ret;
5983a922 733 uint64_t base_size;
70d0b120 734 long shift = 0;
5983a922
SM
735 const char *str_end;
736 char *num_end;
70d0b120
SM
737
738 if (!str) {
5983a922 739 DBG("utils_parse_size_suffix: received a NULL string.");
70d0b120
SM
740 ret = -1;
741 goto end;
742 }
743
5983a922
SM
744 /* strtoull will accept a negative number, but we don't want to. */
745 if (strchr(str, '-') != NULL) {
746 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
70d0b120 747 ret = -1;
5983a922 748 goto end;
70d0b120
SM
749 }
750
5983a922
SM
751 /* str_end will point to the \0 */
752 str_end = str + strlen(str);
70d0b120 753 errno = 0;
5983a922 754 base_size = strtoull(str, &num_end, 0);
70d0b120 755 if (errno != 0) {
5983a922 756 PERROR("utils_parse_size_suffix strtoull");
70d0b120 757 ret = -1;
5983a922
SM
758 goto end;
759 }
760
761 if (num_end == str) {
762 /* strtoull parsed nothing, not good. */
763 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
764 ret = -1;
765 goto end;
766 }
767
768 /* Check if a prefix is present. */
769 switch (*num_end) {
770 case 'G':
771 shift = GIBI_LOG2;
772 num_end++;
773 break;
774 case 'M': /* */
775 shift = MEBI_LOG2;
776 num_end++;
777 break;
778 case 'K':
779 case 'k':
780 shift = KIBI_LOG2;
781 num_end++;
782 break;
783 case '\0':
784 break;
785 default:
786 DBG("utils_parse_size_suffix: invalid suffix.");
787 ret = -1;
788 goto end;
789 }
790
791 /* Check for garbage after the valid input. */
792 if (num_end != str_end) {
793 DBG("utils_parse_size_suffix: Garbage after size string.");
794 ret = -1;
795 goto end;
70d0b120
SM
796 }
797
798 *size = base_size << shift;
799
800 /* Check for overflow */
801 if ((*size >> shift) != base_size) {
5983a922 802 DBG("utils_parse_size_suffix: oops, overflow detected.");
70d0b120 803 ret = -1;
5983a922 804 goto end;
70d0b120
SM
805 }
806
807 ret = 0;
70d0b120
SM
808end:
809 return ret;
810}
cfa9a5a2
DG
811
812/*
813 * fls: returns the position of the most significant bit.
814 * Returns 0 if no bit is set, else returns the position of the most
815 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
816 */
817#if defined(__i386) || defined(__x86_64)
818static inline unsigned int fls_u32(uint32_t x)
819{
820 int r;
821
822 asm("bsrl %1,%0\n\t"
823 "jnz 1f\n\t"
824 "movl $-1,%0\n\t"
825 "1:\n\t"
826 : "=r" (r) : "rm" (x));
827 return r + 1;
828}
829#define HAS_FLS_U32
830#endif
831
832#ifndef HAS_FLS_U32
833static __attribute__((unused)) unsigned int fls_u32(uint32_t x)
834{
835 unsigned int r = 32;
836
837 if (!x) {
838 return 0;
839 }
840 if (!(x & 0xFFFF0000U)) {
841 x <<= 16;
842 r -= 16;
843 }
844 if (!(x & 0xFF000000U)) {
845 x <<= 8;
846 r -= 8;
847 }
848 if (!(x & 0xF0000000U)) {
849 x <<= 4;
850 r -= 4;
851 }
852 if (!(x & 0xC0000000U)) {
853 x <<= 2;
854 r -= 2;
855 }
856 if (!(x & 0x80000000U)) {
857 x <<= 1;
858 r -= 1;
859 }
860 return r;
861}
862#endif
863
864/*
865 * Return the minimum order for which x <= (1UL << order).
866 * Return -1 if x is 0.
867 */
868LTTNG_HIDDEN
869int utils_get_count_order_u32(uint32_t x)
870{
871 if (!x) {
872 return -1;
873 }
874
875 return fls_u32(x - 1);
876}
feb0f3e5
AM
877
878/**
879 * Obtain the value of LTTNG_HOME environment variable, if exists.
880 * Otherwise returns the value of HOME.
881 */
00a52467 882LTTNG_HIDDEN
feb0f3e5
AM
883char *utils_get_home_dir(void)
884{
885 char *val = NULL;
04135dbd
DG
886 struct passwd *pwd;
887
feb0f3e5
AM
888 val = getenv(DEFAULT_LTTNG_HOME_ENV_VAR);
889 if (val != NULL) {
04135dbd
DG
890 goto end;
891 }
892 val = getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR);
893 if (val != NULL) {
894 goto end;
feb0f3e5 895 }
04135dbd
DG
896
897 /* Fallback on the password file entry. */
898 pwd = getpwuid(getuid());
899 if (!pwd) {
900 goto end;
901 }
902 val = pwd->pw_dir;
903
904 DBG3("Home directory is '%s'", val);
905
906end:
907 return val;
feb0f3e5 908}
26fe5938 909
fb198a11
JG
910/**
911 * Get user's home directory. Dynamically allocated, must be freed
912 * by the caller.
913 */
914LTTNG_HIDDEN
915char *utils_get_user_home_dir(uid_t uid)
916{
917 struct passwd pwd;
918 struct passwd *result;
919 char *home_dir = NULL;
920 char *buf = NULL;
921 long buflen;
922 int ret;
923
924 buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
925 if (buflen == -1) {
926 goto end;
927 }
928retry:
929 buf = zmalloc(buflen);
930 if (!buf) {
931 goto end;
932 }
933
934 ret = getpwuid_r(uid, &pwd, buf, buflen, &result);
935 if (ret || !result) {
936 if (ret == ERANGE) {
937 free(buf);
938 buflen *= 2;
939 goto retry;
940 }
941 goto end;
942 }
943
944 home_dir = strdup(pwd.pw_dir);
945end:
946 free(buf);
947 return home_dir;
948}
949
fbb9748b
JG
950/*
951 * Obtain the value of LTTNG_KMOD_PROBES environment variable, if exists.
c9d42407 952 * Otherwise returns NULL.
fbb9748b
JG
953 */
954LTTNG_HIDDEN
955char *utils_get_kmod_probes_list(void)
956{
957 return getenv(DEFAULT_LTTNG_KMOD_PROBES);
958}
959
c9d42407
PP
960/*
961 * Obtain the value of LTTNG_EXTRA_KMOD_PROBES environment variable, if
962 * exists. Otherwise returns NULL.
963 */
964LTTNG_HIDDEN
965char *utils_get_extra_kmod_probes_list(void)
966{
967 return getenv(DEFAULT_LTTNG_EXTRA_KMOD_PROBES);
968}
969
26fe5938
DG
970/*
971 * With the given format, fill dst with the time of len maximum siz.
972 *
973 * Return amount of bytes set in the buffer or else 0 on error.
974 */
975LTTNG_HIDDEN
976size_t utils_get_current_time_str(const char *format, char *dst, size_t len)
977{
978 size_t ret;
979 time_t rawtime;
980 struct tm *timeinfo;
981
982 assert(format);
983 assert(dst);
984
985 /* Get date and time for session path */
986 time(&rawtime);
987 timeinfo = localtime(&rawtime);
988 ret = strftime(dst, len, format, timeinfo);
989 if (ret == 0) {
68e6efdd 990 ERR("Unable to strftime with format %s at dst %p of len %zu", format,
26fe5938
DG
991 dst, len);
992 }
993
994 return ret;
995}
6c71277b
MD
996
997/*
998 * Return the group ID matching name, else 0 if it cannot be found.
999 */
1000LTTNG_HIDDEN
1001gid_t utils_get_group_id(const char *name)
1002{
1003 struct group *grp;
1004
1005 grp = getgrnam(name);
1006 if (!grp) {
1007 static volatile int warn_once;
1008
1009 if (!warn_once) {
1010 WARN("No tracing group detected");
1011 warn_once = 1;
1012 }
1013 return 0;
1014 }
1015 return grp->gr_gid;
1016}
8db0dc00
JG
1017
1018/*
1019 * Return a newly allocated option string. This string is to be used as the
1020 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
1021 * of elements in the long_options array. Returns NULL if the string's
1022 * allocation fails.
1023 */
1024LTTNG_HIDDEN
1025char *utils_generate_optstring(const struct option *long_options,
1026 size_t opt_count)
1027{
1028 int i;
1029 size_t string_len = opt_count, str_pos = 0;
1030 char *optstring;
1031
1032 /*
1033 * Compute the necessary string length. One letter per option, two when an
1034 * argument is necessary, and a trailing NULL.
1035 */
1036 for (i = 0; i < opt_count; i++) {
1037 string_len += long_options[i].has_arg ? 1 : 0;
1038 }
1039
1040 optstring = zmalloc(string_len);
1041 if (!optstring) {
1042 goto end;
1043 }
1044
1045 for (i = 0; i < opt_count; i++) {
1046 if (!long_options[i].name) {
1047 /* Got to the trailing NULL element */
1048 break;
1049 }
1050
1051 optstring[str_pos++] = (char)long_options[i].val;
1052 if (long_options[i].has_arg) {
1053 optstring[str_pos++] = ':';
1054 }
1055 }
1056
1057end:
1058 return optstring;
1059}
This page took 0.076919 seconds and 4 git commands to generate.