f02ff1ec866487464f6f797f61f136a4029b9948
[lttng-tools.git] / src / common / utils.c
1 /*
2 * Copyright (C) 2012 - David Goulet <dgoulet@efficios.com>
3 * Copyright (C) 2013 - Raphaƫl Beamonte <raphael.beamonte@gmail.com>
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License, version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 * more details.
13 *
14 * You should have received a copy of the GNU General Public License along with
15 * this program; if not, write to the Free Software Foundation, Inc., 51
16 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17 */
18
19 #define _GNU_SOURCE
20 #include <assert.h>
21 #include <ctype.h>
22 #include <fcntl.h>
23 #include <limits.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/stat.h>
27 #include <sys/types.h>
28 #include <unistd.h>
29 #include <inttypes.h>
30 #include <grp.h>
31
32 #include <common/common.h>
33 #include <common/runas.h>
34
35 #include "utils.h"
36 #include "defaults.h"
37
38 /*
39 * Return a partial realpath(3) of the path even if the full path does not
40 * exist. For instance, with /tmp/test1/test2/test3, if test2/ does not exist
41 * but the /tmp/test1 does, the real path for /tmp/test1 is concatened with
42 * /test2/test3 then returned. In normal time, realpath(3) fails if the end
43 * point directory does not exist.
44 * In case resolved_path is NULL, the string returned was allocated in the
45 * function and thus need to be freed by the caller. The size argument allows
46 * to specify the size of the resolved_path argument if given, or the size to
47 * allocate.
48 */
49 LTTNG_HIDDEN
50 char *utils_partial_realpath(const char *path, char *resolved_path, size_t size)
51 {
52 char *cut_path, *try_path = NULL, *try_path_prev = NULL;
53 const char *next, *prev, *end;
54
55 /* Safety net */
56 if (path == NULL) {
57 goto error;
58 }
59
60 /*
61 * Identify the end of the path, we don't want to treat the
62 * last char if it is a '/', we will just keep it on the side
63 * to be added at the end, and return a value coherent with
64 * the path given as argument
65 */
66 end = path + strlen(path);
67 if (*(end-1) == '/') {
68 end--;
69 }
70
71 /* Initiate the values of the pointers before looping */
72 next = path;
73 prev = next;
74 /* Only to ensure try_path is not NULL to enter the while */
75 try_path = (char *)next;
76
77 /* Resolve the canonical path of the first part of the path */
78 while (try_path != NULL && next != end) {
79 /*
80 * If there is not any '/' left, we want to try with
81 * the full path
82 */
83 next = strpbrk(next + 1, "/");
84 if (next == NULL) {
85 next = end;
86 }
87
88 /* Cut the part we will be trying to resolve */
89 cut_path = strndup(path, next - path);
90
91 /* Try to resolve this part */
92 try_path = realpath((char *)cut_path, NULL);
93 if (try_path == NULL) {
94 /*
95 * There was an error, we just want to be assured it
96 * is linked to an unexistent directory, if it's another
97 * reason, we spawn an error
98 */
99 switch (errno) {
100 case ENOENT:
101 /* Ignore the error */
102 break;
103 default:
104 PERROR("realpath (partial_realpath)");
105 goto error;
106 break;
107 }
108 } else {
109 /* Save the place we are before trying the next step */
110 free(try_path_prev);
111 try_path_prev = try_path;
112 prev = next;
113 }
114
115 /* Free the allocated memory */
116 free(cut_path);
117 };
118
119 /* Allocate memory for the resolved path if necessary */
120 if (resolved_path == NULL) {
121 resolved_path = zmalloc(size);
122 if (resolved_path == NULL) {
123 PERROR("zmalloc resolved path");
124 goto error;
125 }
126 }
127
128 /*
129 * If we were able to solve at least partially the path, we can concatenate
130 * what worked and what didn't work
131 */
132 if (try_path_prev != NULL) {
133 /* If we risk to concatenate two '/', we remove one of them */
134 if (try_path_prev[strlen(try_path_prev) - 1] == '/' && prev[0] == '/') {
135 try_path_prev[strlen(try_path_prev) - 1] = '\0';
136 }
137
138 /*
139 * Duplicate the memory used by prev in case resolved_path and
140 * path are pointers for the same memory space
141 */
142 cut_path = strdup(prev);
143
144 /* Concatenate the strings */
145 snprintf(resolved_path, size, "%s%s", try_path_prev, cut_path);
146
147 /* Free the allocated memory */
148 free(cut_path);
149 free(try_path_prev);
150 /*
151 * Else, we just copy the path in our resolved_path to
152 * return it as is
153 */
154 } else {
155 strncpy(resolved_path, path, size);
156 }
157
158 /* Then we return the 'partially' resolved path */
159 return resolved_path;
160
161 error:
162 free(resolved_path);
163 return NULL;
164 }
165
166 /*
167 * Make a full resolution of the given path even if it doesn't exist.
168 * This function uses the utils_partial_realpath function to resolve
169 * symlinks and relatives paths at the start of the string, and
170 * implements functionnalities to resolve the './' and '../' strings
171 * in the middle of a path. This function is only necessary because
172 * realpath(3) does not accept to resolve unexistent paths.
173 * The returned string was allocated in the function, it is thus of
174 * the responsibility of the caller to free this memory.
175 */
176 LTTNG_HIDDEN
177 char *utils_expand_path(const char *path)
178 {
179 char *next, *previous, *slash, *start_path, *absolute_path = NULL;
180 char *last_token;
181 int is_dot, is_dotdot;
182
183 /* Safety net */
184 if (path == NULL) {
185 goto error;
186 }
187
188 /* Allocate memory for the absolute_path */
189 absolute_path = zmalloc(PATH_MAX);
190 if (absolute_path == NULL) {
191 PERROR("zmalloc expand path");
192 goto error;
193 }
194
195 /*
196 * If the path is not already absolute nor explicitly relative,
197 * consider we're in the current directory
198 */
199 if (*path != '/' && strncmp(path, "./", 2) != 0 &&
200 strncmp(path, "../", 3) != 0) {
201 snprintf(absolute_path, PATH_MAX, "./%s", path);
202 /* Else, we just copy the path */
203 } else {
204 strncpy(absolute_path, path, PATH_MAX);
205 }
206
207 /* Resolve partially our path */
208 absolute_path = utils_partial_realpath(absolute_path,
209 absolute_path, PATH_MAX);
210
211 /* As long as we find '/./' in the working_path string */
212 while ((next = strstr(absolute_path, "/./"))) {
213
214 /* We prepare the start_path not containing it */
215 start_path = strndup(absolute_path, next - absolute_path);
216
217 /* And we concatenate it with the part after this string */
218 snprintf(absolute_path, PATH_MAX, "%s%s", start_path, next + 2);
219
220 free(start_path);
221 }
222
223 /* As long as we find '/../' in the working_path string */
224 while ((next = strstr(absolute_path, "/../"))) {
225 /* We find the last level of directory */
226 previous = absolute_path;
227 while ((slash = strpbrk(previous, "/")) && slash != next) {
228 previous = slash + 1;
229 }
230
231 /* Then we prepare the start_path not containing it */
232 start_path = strndup(absolute_path, previous - absolute_path);
233
234 /* And we concatenate it with the part after the '/../' */
235 snprintf(absolute_path, PATH_MAX, "%s%s", start_path, next + 4);
236
237 /* We can free the memory used for the start path*/
238 free(start_path);
239
240 /* Then we verify for symlinks using partial_realpath */
241 absolute_path = utils_partial_realpath(absolute_path,
242 absolute_path, PATH_MAX);
243 }
244
245 /* Identify the last token */
246 last_token = strrchr(absolute_path, '/');
247
248 /* Verify that this token is not a relative path */
249 is_dotdot = (strcmp(last_token, "/..") == 0);
250 is_dot = (strcmp(last_token, "/.") == 0);
251
252 /* If it is, take action */
253 if (is_dot || is_dotdot) {
254 /* For both, remove this token */
255 *last_token = '\0';
256
257 /* If it was a reference to parent directory, go back one more time */
258 if (is_dotdot) {
259 last_token = strrchr(absolute_path, '/');
260
261 /* If there was only one level left, we keep the first '/' */
262 if (last_token == absolute_path) {
263 last_token++;
264 }
265
266 *last_token = '\0';
267 }
268 }
269
270 return absolute_path;
271
272 error:
273 free(absolute_path);
274 return NULL;
275 }
276
277 /*
278 * Create a pipe in dst.
279 */
280 LTTNG_HIDDEN
281 int utils_create_pipe(int *dst)
282 {
283 int ret;
284
285 if (dst == NULL) {
286 return -1;
287 }
288
289 ret = pipe(dst);
290 if (ret < 0) {
291 PERROR("create pipe");
292 }
293
294 return ret;
295 }
296
297 /*
298 * Create pipe and set CLOEXEC flag to both fd.
299 *
300 * Make sure the pipe opened by this function are closed at some point. Use
301 * utils_close_pipe().
302 */
303 LTTNG_HIDDEN
304 int utils_create_pipe_cloexec(int *dst)
305 {
306 int ret, i;
307
308 if (dst == NULL) {
309 return -1;
310 }
311
312 ret = utils_create_pipe(dst);
313 if (ret < 0) {
314 goto error;
315 }
316
317 for (i = 0; i < 2; i++) {
318 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
319 if (ret < 0) {
320 PERROR("fcntl pipe cloexec");
321 goto error;
322 }
323 }
324
325 error:
326 return ret;
327 }
328
329 /*
330 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
331 *
332 * Make sure the pipe opened by this function are closed at some point. Use
333 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
334 * support OSes other than Linux 2.6.23+.
335 */
336 LTTNG_HIDDEN
337 int utils_create_pipe_cloexec_nonblock(int *dst)
338 {
339 int ret, i;
340
341 if (dst == NULL) {
342 return -1;
343 }
344
345 ret = utils_create_pipe(dst);
346 if (ret < 0) {
347 goto error;
348 }
349
350 for (i = 0; i < 2; i++) {
351 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
352 if (ret < 0) {
353 PERROR("fcntl pipe cloexec");
354 goto error;
355 }
356 /*
357 * Note: we override any flag that could have been
358 * previously set on the fd.
359 */
360 ret = fcntl(dst[i], F_SETFL, O_NONBLOCK);
361 if (ret < 0) {
362 PERROR("fcntl pipe nonblock");
363 goto error;
364 }
365 }
366
367 error:
368 return ret;
369 }
370
371 /*
372 * Close both read and write side of the pipe.
373 */
374 LTTNG_HIDDEN
375 void utils_close_pipe(int *src)
376 {
377 int i, ret;
378
379 if (src == NULL) {
380 return;
381 }
382
383 for (i = 0; i < 2; i++) {
384 /* Safety check */
385 if (src[i] < 0) {
386 continue;
387 }
388
389 ret = close(src[i]);
390 if (ret) {
391 PERROR("close pipe");
392 }
393 }
394 }
395
396 /*
397 * Create a new string using two strings range.
398 */
399 LTTNG_HIDDEN
400 char *utils_strdupdelim(const char *begin, const char *end)
401 {
402 char *str;
403
404 str = zmalloc(end - begin + 1);
405 if (str == NULL) {
406 PERROR("zmalloc strdupdelim");
407 goto error;
408 }
409
410 memcpy(str, begin, end - begin);
411 str[end - begin] = '\0';
412
413 error:
414 return str;
415 }
416
417 /*
418 * Set CLOEXEC flag to the give file descriptor.
419 */
420 LTTNG_HIDDEN
421 int utils_set_fd_cloexec(int fd)
422 {
423 int ret;
424
425 if (fd < 0) {
426 ret = -EINVAL;
427 goto end;
428 }
429
430 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
431 if (ret < 0) {
432 PERROR("fcntl cloexec");
433 ret = -errno;
434 }
435
436 end:
437 return ret;
438 }
439
440 /*
441 * Create pid file to the given path and filename.
442 */
443 LTTNG_HIDDEN
444 int utils_create_pid_file(pid_t pid, const char *filepath)
445 {
446 int ret;
447 FILE *fp;
448
449 assert(filepath);
450
451 fp = fopen(filepath, "w");
452 if (fp == NULL) {
453 PERROR("open pid file %s", filepath);
454 ret = -1;
455 goto error;
456 }
457
458 ret = fprintf(fp, "%d\n", pid);
459 if (ret < 0) {
460 PERROR("fprintf pid file");
461 }
462
463 fclose(fp);
464 DBG("Pid %d written in file %s", pid, filepath);
465 error:
466 return ret;
467 }
468
469 /*
470 * Recursively create directory using the given path and mode.
471 *
472 * On success, return 0 else a negative error code.
473 */
474 LTTNG_HIDDEN
475 int utils_mkdir_recursive(const char *path, mode_t mode)
476 {
477 char *p, tmp[PATH_MAX];
478 size_t len;
479 int ret;
480
481 assert(path);
482
483 ret = snprintf(tmp, sizeof(tmp), "%s", path);
484 if (ret < 0) {
485 PERROR("snprintf mkdir");
486 goto error;
487 }
488
489 len = ret;
490 if (tmp[len - 1] == '/') {
491 tmp[len - 1] = 0;
492 }
493
494 for (p = tmp + 1; *p; p++) {
495 if (*p == '/') {
496 *p = 0;
497 if (tmp[strlen(tmp) - 1] == '.' &&
498 tmp[strlen(tmp) - 2] == '.' &&
499 tmp[strlen(tmp) - 3] == '/') {
500 ERR("Using '/../' is not permitted in the trace path (%s)",
501 tmp);
502 ret = -1;
503 goto error;
504 }
505 ret = mkdir(tmp, mode);
506 if (ret < 0) {
507 if (errno != EEXIST) {
508 PERROR("mkdir recursive");
509 ret = -errno;
510 goto error;
511 }
512 }
513 *p = '/';
514 }
515 }
516
517 ret = mkdir(tmp, mode);
518 if (ret < 0) {
519 if (errno != EEXIST) {
520 PERROR("mkdir recursive last piece");
521 ret = -errno;
522 } else {
523 ret = 0;
524 }
525 }
526
527 error:
528 return ret;
529 }
530
531 /*
532 * Create the stream tracefile on disk.
533 *
534 * Return 0 on success or else a negative value.
535 */
536 LTTNG_HIDDEN
537 int utils_create_stream_file(const char *path_name, char *file_name, uint64_t size,
538 uint64_t count, int uid, int gid, char *suffix)
539 {
540 int ret, out_fd, flags, mode;
541 char full_path[PATH_MAX], *path_name_suffix = NULL, *path;
542 char *extra = NULL;
543
544 assert(path_name);
545 assert(file_name);
546
547 ret = snprintf(full_path, sizeof(full_path), "%s/%s",
548 path_name, file_name);
549 if (ret < 0) {
550 PERROR("snprintf create output file");
551 goto error;
552 }
553
554 /* Setup extra string if suffix or/and a count is needed. */
555 if (size > 0 && suffix) {
556 ret = asprintf(&extra, "_%" PRIu64 "%s", count, suffix);
557 } else if (size > 0) {
558 ret = asprintf(&extra, "_%" PRIu64, count);
559 } else if (suffix) {
560 ret = asprintf(&extra, "%s", suffix);
561 }
562 if (ret < 0) {
563 PERROR("Allocating extra string to name");
564 goto error;
565 }
566
567 /*
568 * If we split the trace in multiple files, we have to add the count at the
569 * end of the tracefile name
570 */
571 if (extra) {
572 ret = asprintf(&path_name_suffix, "%s%s", full_path, extra);
573 if (ret < 0) {
574 PERROR("Allocating path name with extra string");
575 goto error_free_suffix;
576 }
577 path = path_name_suffix;
578 } else {
579 path = full_path;
580 }
581
582 flags = O_WRONLY | O_CREAT | O_TRUNC;
583 /* Open with 660 mode */
584 mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
585
586 if (uid < 0 || gid < 0) {
587 out_fd = open(path, flags, mode);
588 } else {
589 out_fd = run_as_open(path, flags, mode, uid, gid);
590 }
591 if (out_fd < 0) {
592 PERROR("open stream path %s", path);
593 goto error_open;
594 }
595 ret = out_fd;
596
597 error_open:
598 free(path_name_suffix);
599 error_free_suffix:
600 free(extra);
601 error:
602 return ret;
603 }
604
605 /*
606 * Change the output tracefile according to the given size and count The
607 * new_count pointer is set during this operation.
608 *
609 * From the consumer, the stream lock MUST be held before calling this function
610 * because we are modifying the stream status.
611 *
612 * Return 0 on success or else a negative value.
613 */
614 LTTNG_HIDDEN
615 int utils_rotate_stream_file(char *path_name, char *file_name, uint64_t size,
616 uint64_t count, int uid, int gid, int out_fd, uint64_t *new_count,
617 int *stream_fd)
618 {
619 int ret;
620
621 assert(new_count);
622 assert(stream_fd);
623
624 ret = close(out_fd);
625 if (ret < 0) {
626 PERROR("Closing tracefile");
627 goto error;
628 }
629
630 if (count > 0) {
631 *new_count = (*new_count + 1) % count;
632 } else {
633 (*new_count)++;
634 }
635
636 ret = utils_create_stream_file(path_name, file_name, size, *new_count,
637 uid, gid, 0);
638 if (ret < 0) {
639 goto error;
640 }
641 *stream_fd = ret;
642
643 /* Success. */
644 ret = 0;
645
646 error:
647 return ret;
648 }
649
650
651 /**
652 * Parse a string that represents a size in human readable format. It
653 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
654 *
655 * The suffix multiply the integer by:
656 * 'k': 1024
657 * 'M': 1024^2
658 * 'G': 1024^3
659 *
660 * @param str The string to parse.
661 * @param size Pointer to a uint64_t that will be filled with the
662 * resulting size.
663 *
664 * @return 0 on success, -1 on failure.
665 */
666 LTTNG_HIDDEN
667 int utils_parse_size_suffix(const char * const str, uint64_t * const size)
668 {
669 int ret;
670 uint64_t base_size;
671 long shift = 0;
672 const char *str_end;
673 char *num_end;
674
675 if (!str) {
676 DBG("utils_parse_size_suffix: received a NULL string.");
677 ret = -1;
678 goto end;
679 }
680
681 /* strtoull will accept a negative number, but we don't want to. */
682 if (strchr(str, '-') != NULL) {
683 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
684 ret = -1;
685 goto end;
686 }
687
688 /* str_end will point to the \0 */
689 str_end = str + strlen(str);
690 errno = 0;
691 base_size = strtoull(str, &num_end, 0);
692 if (errno != 0) {
693 PERROR("utils_parse_size_suffix strtoull");
694 ret = -1;
695 goto end;
696 }
697
698 if (num_end == str) {
699 /* strtoull parsed nothing, not good. */
700 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
701 ret = -1;
702 goto end;
703 }
704
705 /* Check if a prefix is present. */
706 switch (*num_end) {
707 case 'G':
708 shift = GIBI_LOG2;
709 num_end++;
710 break;
711 case 'M': /* */
712 shift = MEBI_LOG2;
713 num_end++;
714 break;
715 case 'K':
716 case 'k':
717 shift = KIBI_LOG2;
718 num_end++;
719 break;
720 case '\0':
721 break;
722 default:
723 DBG("utils_parse_size_suffix: invalid suffix.");
724 ret = -1;
725 goto end;
726 }
727
728 /* Check for garbage after the valid input. */
729 if (num_end != str_end) {
730 DBG("utils_parse_size_suffix: Garbage after size string.");
731 ret = -1;
732 goto end;
733 }
734
735 *size = base_size << shift;
736
737 /* Check for overflow */
738 if ((*size >> shift) != base_size) {
739 DBG("utils_parse_size_suffix: oops, overflow detected.");
740 ret = -1;
741 goto end;
742 }
743
744 ret = 0;
745 end:
746 return ret;
747 }
748
749 /*
750 * fls: returns the position of the most significant bit.
751 * Returns 0 if no bit is set, else returns the position of the most
752 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
753 */
754 #if defined(__i386) || defined(__x86_64)
755 static inline unsigned int fls_u32(uint32_t x)
756 {
757 int r;
758
759 asm("bsrl %1,%0\n\t"
760 "jnz 1f\n\t"
761 "movl $-1,%0\n\t"
762 "1:\n\t"
763 : "=r" (r) : "rm" (x));
764 return r + 1;
765 }
766 #define HAS_FLS_U32
767 #endif
768
769 #ifndef HAS_FLS_U32
770 static __attribute__((unused)) unsigned int fls_u32(uint32_t x)
771 {
772 unsigned int r = 32;
773
774 if (!x) {
775 return 0;
776 }
777 if (!(x & 0xFFFF0000U)) {
778 x <<= 16;
779 r -= 16;
780 }
781 if (!(x & 0xFF000000U)) {
782 x <<= 8;
783 r -= 8;
784 }
785 if (!(x & 0xF0000000U)) {
786 x <<= 4;
787 r -= 4;
788 }
789 if (!(x & 0xC0000000U)) {
790 x <<= 2;
791 r -= 2;
792 }
793 if (!(x & 0x80000000U)) {
794 x <<= 1;
795 r -= 1;
796 }
797 return r;
798 }
799 #endif
800
801 /*
802 * Return the minimum order for which x <= (1UL << order).
803 * Return -1 if x is 0.
804 */
805 LTTNG_HIDDEN
806 int utils_get_count_order_u32(uint32_t x)
807 {
808 if (!x) {
809 return -1;
810 }
811
812 return fls_u32(x - 1);
813 }
814
815 /**
816 * Obtain the value of LTTNG_HOME environment variable, if exists.
817 * Otherwise returns the value of HOME.
818 */
819 LTTNG_HIDDEN
820 char *utils_get_home_dir(void)
821 {
822 char *val = NULL;
823 struct passwd *pwd;
824
825 val = getenv(DEFAULT_LTTNG_HOME_ENV_VAR);
826 if (val != NULL) {
827 goto end;
828 }
829 val = getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR);
830 if (val != NULL) {
831 goto end;
832 }
833
834 /* Fallback on the password file entry. */
835 pwd = getpwuid(getuid());
836 if (!pwd) {
837 goto end;
838 }
839 val = pwd->pw_dir;
840
841 DBG3("Home directory is '%s'", val);
842
843 end:
844 return val;
845 }
846
847 /*
848 * With the given format, fill dst with the time of len maximum siz.
849 *
850 * Return amount of bytes set in the buffer or else 0 on error.
851 */
852 LTTNG_HIDDEN
853 size_t utils_get_current_time_str(const char *format, char *dst, size_t len)
854 {
855 size_t ret;
856 time_t rawtime;
857 struct tm *timeinfo;
858
859 assert(format);
860 assert(dst);
861
862 /* Get date and time for session path */
863 time(&rawtime);
864 timeinfo = localtime(&rawtime);
865 ret = strftime(dst, len, format, timeinfo);
866 if (ret == 0) {
867 ERR("Unable to strftime with format %s at dst %p of len %zu", format,
868 dst, len);
869 }
870
871 return ret;
872 }
873
874 /*
875 * Return the group ID matching name, else 0 if it cannot be found.
876 */
877 LTTNG_HIDDEN
878 gid_t utils_get_group_id(const char *name)
879 {
880 struct group *grp;
881
882 grp = getgrnam(name);
883 if (!grp) {
884 static volatile int warn_once;
885
886 if (!warn_once) {
887 WARN("No tracing group detected");
888 warn_once = 1;
889 }
890 return 0;
891 }
892 return grp->gr_gid;
893 }
This page took 0.051298 seconds and 3 git commands to generate.