Add support for UST application registration
[lttng-tools.git] / ltt-sessiond / utils.c
1 /*
2 * Copyright (C) 2011 - David Goulet <david.goulet@polymtl.ca>
3 * Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
4 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; only version 2
8 * of the License.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 */
19
20 #define _GNU_SOURCE
21 #include <errno.h>
22 #include <limits.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/types.h>
27 #include <sys/stat.h>
28 #include <unistd.h>
29
30 #include "utils.h"
31
32 /*
33 * Return pointer to home directory path using the env variable HOME.
34 *
35 * No home, NULL is returned.
36 */
37 const char *get_home_dir(void)
38 {
39 return ((const char *) getenv("HOME"));
40 }
41
42 /*
43 * Create recursively directory using the FULL path.
44 */
45 int mkdir_recursive(const char *path, mode_t mode, uid_t uid, gid_t gid)
46 {
47 int ret;
48 char *p, tmp[PATH_MAX];
49 size_t len;
50 mode_t old_umask;
51
52 ret = snprintf(tmp, sizeof(tmp), "%s", path);
53 if (ret < 0) {
54 perror("snprintf mkdir");
55 goto error;
56 }
57
58 len = ret;
59 if (tmp[len - 1] == '/') {
60 tmp[len - 1] = 0;
61 }
62
63 old_umask = umask(0);
64 for (p = tmp + 1; *p; p++) {
65 if (*p == '/') {
66 *p = 0;
67 ret = mkdir(tmp, mode);
68 if (ret < 0) {
69 if (!(errno == EEXIST)) {
70 perror("mkdir recursive");
71 ret = -errno;
72 goto umask_error;
73 }
74 } else if (ret == 0) {
75 /*
76 * We created the directory. Set its ownership to the
77 * user/group specified.
78 */
79 ret = chown(tmp, uid, gid);
80 if (ret < 0) {
81 perror("chown in mkdir recursive");
82 ret = -errno;
83 goto umask_error;
84 }
85 }
86 *p = '/';
87 }
88 }
89
90 ret = mkdir(tmp, mode);
91 if (ret < 0) {
92 ret = -errno;
93 } else if (ret == 0) {
94 /*
95 * We created the directory. Set its ownership to the user/group
96 * specified.
97 */
98 ret = chown(tmp, uid, gid);
99 if (ret < 0) {
100 perror("chown in mkdir recursive");
101 ret = -errno;
102 goto umask_error;
103 }
104 }
105
106 umask_error:
107 umask(old_umask);
108 error:
109 return ret;
110 }
This page took 0.031356 seconds and 4 git commands to generate.