Relicence all source and header files included in LGPL code
[lttng-tools.git] / src / common / utils.c
1 /*
2 * Copyright (C) 2012 David Goulet <dgoulet@efficios.com>
3 * Copyright (C) 2013 Jérémie Galarneau <jeremie.galarneau@efficios.com>
4 *
5 * SPDX-License-Identifier: LGPL-2.1-only
6 *
7 */
8
9 #include "common/macros.h"
10 #define _LGPL_SOURCE
11 #include <assert.h>
12 #include <ctype.h>
13 #include <fcntl.h>
14 #include <limits.h>
15 #include <stdlib.h>
16 #include <sys/stat.h>
17 #include <sys/types.h>
18 #include <unistd.h>
19 #include <inttypes.h>
20 #include <grp.h>
21 #include <pwd.h>
22 #include <sys/file.h>
23 #include <unistd.h>
24
25 #include <common/common.h>
26 #include <common/readwrite.h>
27 #include <common/runas.h>
28 #include <common/compat/getenv.h>
29 #include <common/compat/string.h>
30 #include <common/compat/dirent.h>
31 #include <common/compat/directory-handle.h>
32 #include <common/dynamic-buffer.h>
33 #include <common/string-utils/format.h>
34 #include <lttng/constant.h>
35
36 #include "utils.h"
37 #include "defaults.h"
38 #include "time.h"
39
40 #define PROC_MEMINFO_PATH "/proc/meminfo"
41 #define PROC_MEMINFO_MEMAVAILABLE_LINE "MemAvailable:"
42 #define PROC_MEMINFO_MEMTOTAL_LINE "MemTotal:"
43
44 /* The length of the longest field of `/proc/meminfo`. */
45 #define PROC_MEMINFO_FIELD_MAX_NAME_LEN 20
46
47 #if (PROC_MEMINFO_FIELD_MAX_NAME_LEN == 20)
48 #define MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "19"
49 #else
50 #error MAX_NAME_LEN_SCANF_IS_A_BROKEN_API must be updated to match (PROC_MEMINFO_FIELD_MAX_NAME_LEN - 1)
51 #endif
52
53 #define FALLBACK_USER_BUFLEN 16384
54 #define FALLBACK_GROUP_BUFLEN 16384
55
56 /*
57 * Create a pipe in dst.
58 */
59 LTTNG_HIDDEN
60 int utils_create_pipe(int *dst)
61 {
62 int ret;
63
64 if (dst == NULL) {
65 return -1;
66 }
67
68 ret = pipe(dst);
69 if (ret < 0) {
70 PERROR("create pipe");
71 }
72
73 return ret;
74 }
75
76 /*
77 * Create pipe and set CLOEXEC flag to both fd.
78 *
79 * Make sure the pipe opened by this function are closed at some point. Use
80 * utils_close_pipe().
81 */
82 LTTNG_HIDDEN
83 int utils_create_pipe_cloexec(int *dst)
84 {
85 int ret, i;
86
87 if (dst == NULL) {
88 return -1;
89 }
90
91 ret = utils_create_pipe(dst);
92 if (ret < 0) {
93 goto error;
94 }
95
96 for (i = 0; i < 2; i++) {
97 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
98 if (ret < 0) {
99 PERROR("fcntl pipe cloexec");
100 goto error;
101 }
102 }
103
104 error:
105 return ret;
106 }
107
108 /*
109 * Create pipe and set fd flags to FD_CLOEXEC and O_NONBLOCK.
110 *
111 * Make sure the pipe opened by this function are closed at some point. Use
112 * utils_close_pipe(). Using pipe() and fcntl rather than pipe2() to
113 * support OSes other than Linux 2.6.23+.
114 */
115 LTTNG_HIDDEN
116 int utils_create_pipe_cloexec_nonblock(int *dst)
117 {
118 int ret, i;
119
120 if (dst == NULL) {
121 return -1;
122 }
123
124 ret = utils_create_pipe(dst);
125 if (ret < 0) {
126 goto error;
127 }
128
129 for (i = 0; i < 2; i++) {
130 ret = fcntl(dst[i], F_SETFD, FD_CLOEXEC);
131 if (ret < 0) {
132 PERROR("fcntl pipe cloexec");
133 goto error;
134 }
135 /*
136 * Note: we override any flag that could have been
137 * previously set on the fd.
138 */
139 ret = fcntl(dst[i], F_SETFL, O_NONBLOCK);
140 if (ret < 0) {
141 PERROR("fcntl pipe nonblock");
142 goto error;
143 }
144 }
145
146 error:
147 return ret;
148 }
149
150 /*
151 * Close both read and write side of the pipe.
152 */
153 LTTNG_HIDDEN
154 void utils_close_pipe(int *src)
155 {
156 int i, ret;
157
158 if (src == NULL) {
159 return;
160 }
161
162 for (i = 0; i < 2; i++) {
163 /* Safety check */
164 if (src[i] < 0) {
165 continue;
166 }
167
168 ret = close(src[i]);
169 if (ret) {
170 PERROR("close pipe");
171 }
172 src[i] = -1;
173 }
174 }
175
176 /*
177 * Create a new string using two strings range.
178 */
179 LTTNG_HIDDEN
180 char *utils_strdupdelim(const char *begin, const char *end)
181 {
182 char *str;
183
184 str = zmalloc(end - begin + 1);
185 if (str == NULL) {
186 PERROR("zmalloc strdupdelim");
187 goto error;
188 }
189
190 memcpy(str, begin, end - begin);
191 str[end - begin] = '\0';
192
193 error:
194 return str;
195 }
196
197 /*
198 * Set CLOEXEC flag to the give file descriptor.
199 */
200 LTTNG_HIDDEN
201 int utils_set_fd_cloexec(int fd)
202 {
203 int ret;
204
205 if (fd < 0) {
206 ret = -EINVAL;
207 goto end;
208 }
209
210 ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
211 if (ret < 0) {
212 PERROR("fcntl cloexec");
213 ret = -errno;
214 }
215
216 end:
217 return ret;
218 }
219
220 /*
221 * Create pid file to the given path and filename.
222 */
223 LTTNG_HIDDEN
224 int utils_create_pid_file(pid_t pid, const char *filepath)
225 {
226 int ret;
227 FILE *fp;
228
229 assert(filepath);
230
231 fp = fopen(filepath, "w");
232 if (fp == NULL) {
233 PERROR("open pid file %s", filepath);
234 ret = -1;
235 goto error;
236 }
237
238 ret = fprintf(fp, "%d\n", (int) pid);
239 if (ret < 0) {
240 PERROR("fprintf pid file");
241 goto error;
242 }
243
244 if (fclose(fp)) {
245 PERROR("fclose");
246 }
247 DBG("Pid %d written in file %s", (int) pid, filepath);
248 ret = 0;
249 error:
250 return ret;
251 }
252
253 /*
254 * Create lock file to the given path and filename.
255 * Returns the associated file descriptor, -1 on error.
256 */
257 LTTNG_HIDDEN
258 int utils_create_lock_file(const char *filepath)
259 {
260 int ret;
261 int fd;
262 struct flock lock;
263
264 assert(filepath);
265
266 memset(&lock, 0, sizeof(lock));
267 fd = open(filepath, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR |
268 S_IRGRP | S_IWGRP);
269 if (fd < 0) {
270 PERROR("open lock file %s", filepath);
271 fd = -1;
272 goto error;
273 }
274
275 /*
276 * Attempt to lock the file. If this fails, there is
277 * already a process using the same lock file running
278 * and we should exit.
279 */
280 lock.l_whence = SEEK_SET;
281 lock.l_type = F_WRLCK;
282
283 ret = fcntl(fd, F_SETLK, &lock);
284 if (ret == -1) {
285 PERROR("fcntl lock file");
286 ERR("Could not get lock file %s, another instance is running.",
287 filepath);
288 if (close(fd)) {
289 PERROR("close lock file");
290 }
291 fd = ret;
292 goto error;
293 }
294
295 error:
296 return fd;
297 }
298
299 /*
300 * Create directory using the given path and mode.
301 *
302 * On success, return 0 else a negative error code.
303 */
304 LTTNG_HIDDEN
305 int utils_mkdir(const char *path, mode_t mode, int uid, int gid)
306 {
307 int ret;
308 struct lttng_directory_handle *handle;
309 const struct lttng_credentials creds = {
310 .uid = LTTNG_OPTIONAL_INIT_VALUE(uid),
311 .gid = LTTNG_OPTIONAL_INIT_VALUE(gid),
312 };
313
314 handle = lttng_directory_handle_create(NULL);
315 if (!handle) {
316 ret = -1;
317 goto end;
318 }
319 ret = lttng_directory_handle_create_subdirectory_as_user(
320 handle, path, mode,
321 (uid >= 0 || gid >= 0) ? &creds : NULL);
322 end:
323 lttng_directory_handle_put(handle);
324 return ret;
325 }
326
327 /*
328 * Recursively create directory using the given path and mode, under the
329 * provided uid and gid.
330 *
331 * On success, return 0 else a negative error code.
332 */
333 LTTNG_HIDDEN
334 int utils_mkdir_recursive(const char *path, mode_t mode, int uid, int gid)
335 {
336 int ret;
337 struct lttng_directory_handle *handle;
338 const struct lttng_credentials creds = {
339 .uid = LTTNG_OPTIONAL_INIT_VALUE(uid),
340 .gid = LTTNG_OPTIONAL_INIT_VALUE(gid),
341 };
342
343 handle = lttng_directory_handle_create(NULL);
344 if (!handle) {
345 ret = -1;
346 goto end;
347 }
348 ret = lttng_directory_handle_create_subdirectory_recursive_as_user(
349 handle, path, mode,
350 (uid >= 0 || gid >= 0) ? &creds : NULL);
351 end:
352 lttng_directory_handle_put(handle);
353 return ret;
354 }
355
356 /*
357 * out_stream_path is the output parameter.
358 *
359 * Return 0 on success or else a negative value.
360 */
361 LTTNG_HIDDEN
362 int utils_stream_file_path(const char *path_name, const char *file_name,
363 uint64_t size, uint64_t count, const char *suffix,
364 char *out_stream_path, size_t stream_path_len)
365 {
366 int ret;
367 char count_str[MAX_INT_DEC_LEN(count) + 1] = {};
368 const char *path_separator;
369
370 if (path_name && (path_name[0] == '\0' ||
371 path_name[strlen(path_name) - 1] == '/')) {
372 path_separator = "";
373 } else {
374 path_separator = "/";
375 }
376
377 path_name = path_name ? : "";
378 suffix = suffix ? : "";
379 if (size > 0) {
380 ret = snprintf(count_str, sizeof(count_str), "_%" PRIu64,
381 count);
382 assert(ret > 0 && ret < sizeof(count_str));
383 }
384
385 ret = snprintf(out_stream_path, stream_path_len, "%s%s%s%s%s",
386 path_name, path_separator, file_name, count_str,
387 suffix);
388 if (ret < 0 || ret >= stream_path_len) {
389 ERR("Truncation occurred while formatting stream path");
390 ret = -1;
391 } else {
392 ret = 0;
393 }
394 return ret;
395 }
396
397 /**
398 * Parse a string that represents a size in human readable format. It
399 * supports decimal integers suffixed by 'k', 'K', 'M' or 'G'.
400 *
401 * The suffix multiply the integer by:
402 * 'k': 1024
403 * 'M': 1024^2
404 * 'G': 1024^3
405 *
406 * @param str The string to parse.
407 * @param size Pointer to a uint64_t that will be filled with the
408 * resulting size.
409 *
410 * @return 0 on success, -1 on failure.
411 */
412 LTTNG_HIDDEN
413 int utils_parse_size_suffix(const char * const str, uint64_t * const size)
414 {
415 int ret;
416 uint64_t base_size;
417 long shift = 0;
418 const char *str_end;
419 char *num_end;
420
421 if (!str) {
422 DBG("utils_parse_size_suffix: received a NULL string.");
423 ret = -1;
424 goto end;
425 }
426
427 /* strtoull will accept a negative number, but we don't want to. */
428 if (strchr(str, '-') != NULL) {
429 DBG("utils_parse_size_suffix: invalid size string, should not contain '-'.");
430 ret = -1;
431 goto end;
432 }
433
434 /* str_end will point to the \0 */
435 str_end = str + strlen(str);
436 errno = 0;
437 base_size = strtoull(str, &num_end, 0);
438 if (errno != 0) {
439 PERROR("utils_parse_size_suffix strtoull");
440 ret = -1;
441 goto end;
442 }
443
444 if (num_end == str) {
445 /* strtoull parsed nothing, not good. */
446 DBG("utils_parse_size_suffix: strtoull had nothing good to parse.");
447 ret = -1;
448 goto end;
449 }
450
451 /* Check if a prefix is present. */
452 switch (*num_end) {
453 case 'G':
454 shift = GIBI_LOG2;
455 num_end++;
456 break;
457 case 'M': /* */
458 shift = MEBI_LOG2;
459 num_end++;
460 break;
461 case 'K':
462 case 'k':
463 shift = KIBI_LOG2;
464 num_end++;
465 break;
466 case '\0':
467 break;
468 default:
469 DBG("utils_parse_size_suffix: invalid suffix.");
470 ret = -1;
471 goto end;
472 }
473
474 /* Check for garbage after the valid input. */
475 if (num_end != str_end) {
476 DBG("utils_parse_size_suffix: Garbage after size string.");
477 ret = -1;
478 goto end;
479 }
480
481 *size = base_size << shift;
482
483 /* Check for overflow */
484 if ((*size >> shift) != base_size) {
485 DBG("utils_parse_size_suffix: oops, overflow detected.");
486 ret = -1;
487 goto end;
488 }
489
490 ret = 0;
491 end:
492 return ret;
493 }
494
495 /**
496 * Parse a string that represents a time in human readable format. It
497 * supports decimal integers suffixed by:
498 * "us" for microsecond,
499 * "ms" for millisecond,
500 * "s" for second,
501 * "m" for minute,
502 * "h" for hour
503 *
504 * The suffix multiply the integer by:
505 * "us" : 1
506 * "ms" : 1000
507 * "s" : 1000000
508 * "m" : 60000000
509 * "h" : 3600000000
510 *
511 * Note that unit-less numbers are assumed to be microseconds.
512 *
513 * @param str The string to parse, assumed to be NULL-terminated.
514 * @param time_us Pointer to a uint64_t that will be filled with the
515 * resulting time in microseconds.
516 *
517 * @return 0 on success, -1 on failure.
518 */
519 LTTNG_HIDDEN
520 int utils_parse_time_suffix(char const * const str, uint64_t * const time_us)
521 {
522 int ret;
523 uint64_t base_time;
524 uint64_t multiplier = 1;
525 const char *str_end;
526 char *num_end;
527
528 if (!str) {
529 DBG("utils_parse_time_suffix: received a NULL string.");
530 ret = -1;
531 goto end;
532 }
533
534 /* strtoull will accept a negative number, but we don't want to. */
535 if (strchr(str, '-') != NULL) {
536 DBG("utils_parse_time_suffix: invalid time string, should not contain '-'.");
537 ret = -1;
538 goto end;
539 }
540
541 /* str_end will point to the \0 */
542 str_end = str + strlen(str);
543 errno = 0;
544 base_time = strtoull(str, &num_end, 10);
545 if (errno != 0) {
546 PERROR("utils_parse_time_suffix strtoull on string \"%s\"", str);
547 ret = -1;
548 goto end;
549 }
550
551 if (num_end == str) {
552 /* strtoull parsed nothing, not good. */
553 DBG("utils_parse_time_suffix: strtoull had nothing good to parse.");
554 ret = -1;
555 goto end;
556 }
557
558 /* Check if a prefix is present. */
559 switch (*num_end) {
560 case 'u':
561 /*
562 * Microsecond (us)
563 *
564 * Skip the "us" if the string matches the "us" suffix,
565 * otherwise let the check for the end of the string handle
566 * the error reporting.
567 */
568 if (*(num_end + 1) == 's') {
569 num_end += 2;
570 }
571 break;
572 case 'm':
573 if (*(num_end + 1) == 's') {
574 /* Millisecond (ms) */
575 multiplier = USEC_PER_MSEC;
576 /* Skip the 's' */
577 num_end++;
578 } else {
579 /* Minute (m) */
580 multiplier = USEC_PER_MINUTE;
581 }
582 num_end++;
583 break;
584 case 's':
585 /* Second */
586 multiplier = USEC_PER_SEC;
587 num_end++;
588 break;
589 case 'h':
590 /* Hour */
591 multiplier = USEC_PER_HOURS;
592 num_end++;
593 break;
594 case '\0':
595 break;
596 default:
597 DBG("utils_parse_time_suffix: invalid suffix.");
598 ret = -1;
599 goto end;
600 }
601
602 /* Check for garbage after the valid input. */
603 if (num_end != str_end) {
604 DBG("utils_parse_time_suffix: Garbage after time string.");
605 ret = -1;
606 goto end;
607 }
608
609 *time_us = base_time * multiplier;
610
611 /* Check for overflow */
612 if ((*time_us / multiplier) != base_time) {
613 DBG("utils_parse_time_suffix: oops, overflow detected.");
614 ret = -1;
615 goto end;
616 }
617
618 ret = 0;
619 end:
620 return ret;
621 }
622
623 /*
624 * fls: returns the position of the most significant bit.
625 * Returns 0 if no bit is set, else returns the position of the most
626 * significant bit (from 1 to 32 on 32-bit, from 1 to 64 on 64-bit).
627 */
628 #if defined(__i386) || defined(__x86_64)
629 static inline unsigned int fls_u32(uint32_t x)
630 {
631 int r;
632
633 asm("bsrl %1,%0\n\t"
634 "jnz 1f\n\t"
635 "movl $-1,%0\n\t"
636 "1:\n\t"
637 : "=r" (r) : "rm" (x));
638 return r + 1;
639 }
640 #define HAS_FLS_U32
641 #endif
642
643 #if defined(__x86_64) && defined(__LP64__)
644 static inline
645 unsigned int fls_u64(uint64_t x)
646 {
647 long r;
648
649 asm("bsrq %1,%0\n\t"
650 "jnz 1f\n\t"
651 "movq $-1,%0\n\t"
652 "1:\n\t"
653 : "=r" (r) : "rm" (x));
654 return r + 1;
655 }
656 #define HAS_FLS_U64
657 #endif
658
659 #ifndef HAS_FLS_U64
660 static __attribute__((unused))
661 unsigned int fls_u64(uint64_t x)
662 {
663 unsigned int r = 64;
664
665 if (!x)
666 return 0;
667
668 if (!(x & 0xFFFFFFFF00000000ULL)) {
669 x <<= 32;
670 r -= 32;
671 }
672 if (!(x & 0xFFFF000000000000ULL)) {
673 x <<= 16;
674 r -= 16;
675 }
676 if (!(x & 0xFF00000000000000ULL)) {
677 x <<= 8;
678 r -= 8;
679 }
680 if (!(x & 0xF000000000000000ULL)) {
681 x <<= 4;
682 r -= 4;
683 }
684 if (!(x & 0xC000000000000000ULL)) {
685 x <<= 2;
686 r -= 2;
687 }
688 if (!(x & 0x8000000000000000ULL)) {
689 x <<= 1;
690 r -= 1;
691 }
692 return r;
693 }
694 #endif
695
696 #ifndef HAS_FLS_U32
697 static __attribute__((unused)) unsigned int fls_u32(uint32_t x)
698 {
699 unsigned int r = 32;
700
701 if (!x) {
702 return 0;
703 }
704 if (!(x & 0xFFFF0000U)) {
705 x <<= 16;
706 r -= 16;
707 }
708 if (!(x & 0xFF000000U)) {
709 x <<= 8;
710 r -= 8;
711 }
712 if (!(x & 0xF0000000U)) {
713 x <<= 4;
714 r -= 4;
715 }
716 if (!(x & 0xC0000000U)) {
717 x <<= 2;
718 r -= 2;
719 }
720 if (!(x & 0x80000000U)) {
721 x <<= 1;
722 r -= 1;
723 }
724 return r;
725 }
726 #endif
727
728 /*
729 * Return the minimum order for which x <= (1UL << order).
730 * Return -1 if x is 0.
731 */
732 LTTNG_HIDDEN
733 int utils_get_count_order_u32(uint32_t x)
734 {
735 if (!x) {
736 return -1;
737 }
738
739 return fls_u32(x - 1);
740 }
741
742 /*
743 * Return the minimum order for which x <= (1UL << order).
744 * Return -1 if x is 0.
745 */
746 LTTNG_HIDDEN
747 int utils_get_count_order_u64(uint64_t x)
748 {
749 if (!x) {
750 return -1;
751 }
752
753 return fls_u64(x - 1);
754 }
755
756 /**
757 * Obtain the value of LTTNG_HOME environment variable, if exists.
758 * Otherwise returns the value of HOME.
759 */
760 LTTNG_HIDDEN
761 const char *utils_get_home_dir(void)
762 {
763 char *val = NULL;
764 struct passwd *pwd;
765
766 val = lttng_secure_getenv(DEFAULT_LTTNG_HOME_ENV_VAR);
767 if (val != NULL) {
768 goto end;
769 }
770 val = lttng_secure_getenv(DEFAULT_LTTNG_FALLBACK_HOME_ENV_VAR);
771 if (val != NULL) {
772 goto end;
773 }
774
775 /* Fallback on the password file entry. */
776 pwd = getpwuid(getuid());
777 if (!pwd) {
778 goto end;
779 }
780 val = pwd->pw_dir;
781
782 DBG3("Home directory is '%s'", val);
783
784 end:
785 return val;
786 }
787
788 /**
789 * Get user's home directory. Dynamically allocated, must be freed
790 * by the caller.
791 */
792 LTTNG_HIDDEN
793 char *utils_get_user_home_dir(uid_t uid)
794 {
795 struct passwd pwd;
796 struct passwd *result;
797 char *home_dir = NULL;
798 char *buf = NULL;
799 long buflen;
800 int ret;
801
802 buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
803 if (buflen == -1) {
804 goto end;
805 }
806 retry:
807 buf = zmalloc(buflen);
808 if (!buf) {
809 goto end;
810 }
811
812 ret = getpwuid_r(uid, &pwd, buf, buflen, &result);
813 if (ret || !result) {
814 if (ret == ERANGE) {
815 free(buf);
816 buflen *= 2;
817 goto retry;
818 }
819 goto end;
820 }
821
822 home_dir = strdup(pwd.pw_dir);
823 end:
824 free(buf);
825 return home_dir;
826 }
827
828 /*
829 * With the given format, fill dst with the time of len maximum siz.
830 *
831 * Return amount of bytes set in the buffer or else 0 on error.
832 */
833 LTTNG_HIDDEN
834 size_t utils_get_current_time_str(const char *format, char *dst, size_t len)
835 {
836 size_t ret;
837 time_t rawtime;
838 struct tm *timeinfo;
839
840 assert(format);
841 assert(dst);
842
843 /* Get date and time for session path */
844 time(&rawtime);
845 timeinfo = localtime(&rawtime);
846 ret = strftime(dst, len, format, timeinfo);
847 if (ret == 0) {
848 ERR("Unable to strftime with format %s at dst %p of len %zu", format,
849 dst, len);
850 }
851
852 return ret;
853 }
854
855 /*
856 * Return 0 on success and set *gid to the group_ID matching the passed name.
857 * Else -1 if it cannot be found or an error occurred.
858 */
859 LTTNG_HIDDEN
860 int utils_get_group_id(const char *name, bool warn, gid_t *gid)
861 {
862 static volatile int warn_once;
863 int ret;
864 long sys_len;
865 size_t len;
866 struct group grp;
867 struct group *result;
868 struct lttng_dynamic_buffer buffer;
869
870 /* Get the system limit, if it exists. */
871 sys_len = sysconf(_SC_GETGR_R_SIZE_MAX);
872 if (sys_len == -1) {
873 len = 1024;
874 } else {
875 len = (size_t) sys_len;
876 }
877
878 lttng_dynamic_buffer_init(&buffer);
879 ret = lttng_dynamic_buffer_set_size(&buffer, len);
880 if (ret) {
881 ERR("Failed to allocate group info buffer");
882 ret = -1;
883 goto error;
884 }
885
886 while ((ret = getgrnam_r(name, &grp, buffer.data, buffer.size, &result)) == ERANGE) {
887 const size_t new_len = 2 * buffer.size;
888
889 /* Buffer is not big enough, increase its size. */
890 if (new_len < buffer.size) {
891 ERR("Group info buffer size overflow");
892 ret = -1;
893 goto error;
894 }
895
896 ret = lttng_dynamic_buffer_set_size(&buffer, new_len);
897 if (ret) {
898 ERR("Failed to grow group info buffer to %zu bytes",
899 new_len);
900 ret = -1;
901 goto error;
902 }
903 }
904 if (ret) {
905 if (ret == ESRCH) {
906 DBG("Could not find group file entry for group name '%s'",
907 name);
908 } else {
909 PERROR("Failed to get group file entry for group name '%s'",
910 name);
911 }
912
913 ret = -1;
914 goto error;
915 }
916
917 /* Group not found. */
918 if (!result) {
919 ret = -1;
920 goto error;
921 }
922
923 *gid = result->gr_gid;
924 ret = 0;
925
926 error:
927 if (ret && warn && !warn_once) {
928 WARN("No tracing group detected");
929 warn_once = 1;
930 }
931 lttng_dynamic_buffer_reset(&buffer);
932 return ret;
933 }
934
935 /*
936 * Return a newly allocated option string. This string is to be used as the
937 * optstring argument of getopt_long(), see GETOPT(3). opt_count is the number
938 * of elements in the long_options array. Returns NULL if the string's
939 * allocation fails.
940 */
941 LTTNG_HIDDEN
942 char *utils_generate_optstring(const struct option *long_options,
943 size_t opt_count)
944 {
945 int i;
946 size_t string_len = opt_count, str_pos = 0;
947 char *optstring;
948
949 /*
950 * Compute the necessary string length. One letter per option, two when an
951 * argument is necessary, and a trailing NULL.
952 */
953 for (i = 0; i < opt_count; i++) {
954 string_len += long_options[i].has_arg ? 1 : 0;
955 }
956
957 optstring = zmalloc(string_len);
958 if (!optstring) {
959 goto end;
960 }
961
962 for (i = 0; i < opt_count; i++) {
963 if (!long_options[i].name) {
964 /* Got to the trailing NULL element */
965 break;
966 }
967
968 if (long_options[i].val != '\0') {
969 optstring[str_pos++] = (char) long_options[i].val;
970 if (long_options[i].has_arg) {
971 optstring[str_pos++] = ':';
972 }
973 }
974 }
975
976 end:
977 return optstring;
978 }
979
980 /*
981 * Try to remove a hierarchy of empty directories, recursively. Don't unlink
982 * any file. Try to rmdir any empty directory within the hierarchy.
983 */
984 LTTNG_HIDDEN
985 int utils_recursive_rmdir(const char *path)
986 {
987 int ret;
988 struct lttng_directory_handle *handle;
989
990 handle = lttng_directory_handle_create(NULL);
991 if (!handle) {
992 ret = -1;
993 goto end;
994 }
995 ret = lttng_directory_handle_remove_subdirectory(handle, path);
996 end:
997 lttng_directory_handle_put(handle);
998 return ret;
999 }
1000
1001 LTTNG_HIDDEN
1002 int utils_truncate_stream_file(int fd, off_t length)
1003 {
1004 int ret;
1005 off_t lseek_ret;
1006
1007 ret = ftruncate(fd, length);
1008 if (ret < 0) {
1009 PERROR("ftruncate");
1010 goto end;
1011 }
1012 lseek_ret = lseek(fd, length, SEEK_SET);
1013 if (lseek_ret < 0) {
1014 PERROR("lseek");
1015 ret = -1;
1016 goto end;
1017 }
1018 end:
1019 return ret;
1020 }
1021
1022 static const char *get_man_bin_path(void)
1023 {
1024 char *env_man_path = lttng_secure_getenv(DEFAULT_MAN_BIN_PATH_ENV);
1025
1026 if (env_man_path) {
1027 return env_man_path;
1028 }
1029
1030 return DEFAULT_MAN_BIN_PATH;
1031 }
1032
1033 LTTNG_HIDDEN
1034 int utils_show_help(int section, const char *page_name,
1035 const char *help_msg)
1036 {
1037 char section_string[8];
1038 const char *man_bin_path = get_man_bin_path();
1039 int ret = 0;
1040
1041 if (help_msg) {
1042 printf("%s", help_msg);
1043 goto end;
1044 }
1045
1046 /* Section integer -> section string */
1047 ret = sprintf(section_string, "%d", section);
1048 assert(ret > 0 && ret < 8);
1049
1050 /*
1051 * Execute man pager.
1052 *
1053 * We provide -M to man here because LTTng-tools can
1054 * be installed outside /usr, in which case its man pages are
1055 * not located in the default /usr/share/man directory.
1056 */
1057 ret = execlp(man_bin_path, "man", "-M", MANPATH,
1058 section_string, page_name, NULL);
1059
1060 end:
1061 return ret;
1062 }
1063
1064 static
1065 int read_proc_meminfo_field(const char *field, size_t *value)
1066 {
1067 int ret;
1068 FILE *proc_meminfo;
1069 char name[PROC_MEMINFO_FIELD_MAX_NAME_LEN] = {};
1070
1071 proc_meminfo = fopen(PROC_MEMINFO_PATH, "r");
1072 if (!proc_meminfo) {
1073 PERROR("Failed to fopen() " PROC_MEMINFO_PATH);
1074 ret = -1;
1075 goto fopen_error;
1076 }
1077
1078 /*
1079 * Read the contents of /proc/meminfo line by line to find the right
1080 * field.
1081 */
1082 while (!feof(proc_meminfo)) {
1083 unsigned long value_kb;
1084
1085 ret = fscanf(proc_meminfo,
1086 "%" MAX_NAME_LEN_SCANF_IS_A_BROKEN_API "s %lu kB\n",
1087 name, &value_kb);
1088 if (ret == EOF) {
1089 /*
1090 * fscanf() returning EOF can indicate EOF or an error.
1091 */
1092 if (ferror(proc_meminfo)) {
1093 PERROR("Failed to parse " PROC_MEMINFO_PATH);
1094 }
1095 break;
1096 }
1097
1098 if (ret == 2 && strcmp(name, field) == 0) {
1099 /*
1100 * This number is displayed in kilo-bytes. Return the
1101 * number of bytes.
1102 */
1103 *value = ((size_t) value_kb) * 1024;
1104 ret = 0;
1105 goto found;
1106 }
1107 }
1108 /* Reached the end of the file without finding the right field. */
1109 ret = -1;
1110
1111 found:
1112 fclose(proc_meminfo);
1113 fopen_error:
1114 return ret;
1115 }
1116
1117 /*
1118 * Returns an estimate of the number of bytes of memory available based on the
1119 * the information in `/proc/meminfo`. The number returned by this function is
1120 * a best guess.
1121 */
1122 LTTNG_HIDDEN
1123 int utils_get_memory_available(size_t *value)
1124 {
1125 return read_proc_meminfo_field(PROC_MEMINFO_MEMAVAILABLE_LINE, value);
1126 }
1127
1128 /*
1129 * Returns the total size of the memory on the system in bytes based on the
1130 * the information in `/proc/meminfo`.
1131 */
1132 LTTNG_HIDDEN
1133 int utils_get_memory_total(size_t *value)
1134 {
1135 return read_proc_meminfo_field(PROC_MEMINFO_MEMTOTAL_LINE, value);
1136 }
1137
1138 LTTNG_HIDDEN
1139 int utils_change_working_directory(const char *path)
1140 {
1141 int ret;
1142
1143 assert(path);
1144
1145 DBG("Changing working directory to \"%s\"", path);
1146 ret = chdir(path);
1147 if (ret) {
1148 PERROR("Failed to change working directory to \"%s\"", path);
1149 goto end;
1150 }
1151
1152 /* Check for write access */
1153 if (access(path, W_OK)) {
1154 if (errno == EACCES) {
1155 /*
1156 * Do not treat this as an error since the permission
1157 * might change in the lifetime of the process
1158 */
1159 DBG("Working directory \"%s\" is not writable", path);
1160 } else {
1161 PERROR("Failed to check if working directory \"%s\" is writable",
1162 path);
1163 }
1164 }
1165
1166 end:
1167 return ret;
1168 }
1169
1170 LTTNG_HIDDEN
1171 enum lttng_error_code utils_user_id_from_name(const char *user_name, uid_t *uid)
1172 {
1173 struct passwd p, *pres;
1174 int ret;
1175 enum lttng_error_code ret_val = LTTNG_OK;
1176 char *buf = NULL;
1177 ssize_t buflen;
1178
1179 buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
1180 if (buflen < 0) {
1181 buflen = FALLBACK_USER_BUFLEN;
1182 }
1183
1184 buf = zmalloc(buflen);
1185 if (!buf) {
1186 ret_val = LTTNG_ERR_NOMEM;
1187 goto end;
1188 }
1189
1190 for (;;) {
1191 ret = getpwnam_r(user_name, &p, buf, buflen, &pres);
1192 switch (ret) {
1193 case EINTR:
1194 continue;
1195 case ERANGE:
1196 buflen *= 2;
1197 free(buf);
1198 buf = zmalloc(buflen);
1199 if (!buf) {
1200 ret_val = LTTNG_ERR_NOMEM;
1201 goto end;
1202 }
1203 continue;
1204 default:
1205 goto end_loop;
1206 }
1207 }
1208 end_loop:
1209
1210 switch (ret) {
1211 case 0:
1212 if (pres == NULL) {
1213 ret_val = LTTNG_ERR_USER_NOT_FOUND;
1214 } else {
1215 *uid = p.pw_uid;
1216 DBG("Lookup of tracker UID/VUID: name '%s' maps to uid %" PRId64,
1217 user_name, (int64_t) *uid);
1218 ret_val = LTTNG_OK;
1219 }
1220 break;
1221 case ENOENT:
1222 case ESRCH:
1223 case EBADF:
1224 case EPERM:
1225 ret_val = LTTNG_ERR_USER_NOT_FOUND;
1226 break;
1227 default:
1228 ret_val = LTTNG_ERR_NOMEM;
1229 }
1230 end:
1231 free(buf);
1232 return ret_val;
1233 }
1234
1235 LTTNG_HIDDEN
1236 enum lttng_error_code utils_group_id_from_name(
1237 const char *group_name, gid_t *gid)
1238 {
1239 struct group g, *gres;
1240 int ret;
1241 enum lttng_error_code ret_val = LTTNG_OK;
1242 char *buf = NULL;
1243 ssize_t buflen;
1244
1245 buflen = sysconf(_SC_GETGR_R_SIZE_MAX);
1246 if (buflen < 0) {
1247 buflen = FALLBACK_GROUP_BUFLEN;
1248 }
1249
1250 buf = zmalloc(buflen);
1251 if (!buf) {
1252 ret_val = LTTNG_ERR_NOMEM;
1253 goto end;
1254 }
1255
1256 for (;;) {
1257 ret = getgrnam_r(group_name, &g, buf, buflen, &gres);
1258 switch (ret) {
1259 case EINTR:
1260 continue;
1261 case ERANGE:
1262 buflen *= 2;
1263 free(buf);
1264 buf = zmalloc(buflen);
1265 if (!buf) {
1266 ret_val = LTTNG_ERR_NOMEM;
1267 goto end;
1268 }
1269 continue;
1270 default:
1271 goto end_loop;
1272 }
1273 }
1274 end_loop:
1275
1276 switch (ret) {
1277 case 0:
1278 if (gres == NULL) {
1279 ret_val = LTTNG_ERR_GROUP_NOT_FOUND;
1280 } else {
1281 *gid = g.gr_gid;
1282 DBG("Lookup of tracker GID/GUID: name '%s' maps to gid %" PRId64,
1283 group_name, (int64_t) *gid);
1284 ret_val = LTTNG_OK;
1285 }
1286 break;
1287 case ENOENT:
1288 case ESRCH:
1289 case EBADF:
1290 case EPERM:
1291 ret_val = LTTNG_ERR_GROUP_NOT_FOUND;
1292 break;
1293 default:
1294 ret_val = LTTNG_ERR_NOMEM;
1295 }
1296 end:
1297 free(buf);
1298 return ret_val;
1299 }
1300
1301 LTTNG_HIDDEN
1302 int utils_parse_unsigned_long_long(const char *str,
1303 unsigned long long *value)
1304 {
1305 int ret;
1306 char *endptr;
1307
1308 assert(str);
1309 assert(value);
1310
1311 errno = 0;
1312 *value = strtoull(str, &endptr, 10);
1313
1314 /* Conversion failed. Out of range? */
1315 if (errno != 0) {
1316 /* Don't print an error; allow the caller to log a better error. */
1317 DBG("Failed to parse string as unsigned long long number: string = '%s', errno = %d",
1318 str, errno);
1319 ret = -1;
1320 goto end;
1321 }
1322
1323 /* Not the end of the string or empty string. */
1324 if (*endptr || endptr == str) {
1325 DBG("Failed to parse string as unsigned long long number: string = '%s'",
1326 str);
1327 ret = -1;
1328 goto end;
1329 }
1330
1331 ret = 0;
1332
1333 end:
1334 return ret;
1335 }
This page took 0.089919 seconds and 4 git commands to generate.