]> diplodocus.org Git - nmh/blob - sbr/makedir.c
10c46b1fae9dc82854a10710a44d0d0acc1bbb54
[nmh] / sbr / makedir.c
1 /* makedir.c -- make a directory
2 *
3 * This code is Copyright (c) 2002, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
6 */
7
8 /*
9 * Modified to try recursive create.
10 */
11
12 #include "h/mh.h"
13 #include "error.h"
14 #include "makedir.h"
15 #include <sys/file.h>
16
17 int
18 makedir (const char *dir)
19 {
20 char path[PATH_MAX];
21 char* folder_perms_ASCII;
22 mode_t folder_perms, saved_umask;
23 char* c;
24
25 context_save(); /* save the context file */
26 fflush(stdout);
27
28 if (!(folder_perms_ASCII = context_find ("folder-protect")))
29 folder_perms_ASCII = foldprot; /* defaults to "700" */
30
31 /* Because mh-profile.man documents "Folder-Protect:" as an octal constant,
32 and we don't want to force the user to remember to include a leading
33 zero, we call atooi(folder_perms_ASCII) here rather than
34 strtoul(folder_perms_ASCII, NULL, 0). Therefore, if anyone ever tries to
35 specify a mode in say, hex, they'll get garbage. (I guess nmh uses its
36 atooi() function rather than calling strtoul() with a radix of 8 because
37 some ancient platforms are missing that functionality. */
38 folder_perms = atooi(folder_perms_ASCII);
39
40 /* Folders have definite desired permissions that are set -- we don't want
41 to interact with the umask. Clear it temporarily. */
42 saved_umask = umask(0);
43
44 c = strncpy(path, dir, sizeof(path));
45
46 bool had_an_error = false;
47 while (!had_an_error && (c = strchr((c + 1), '/')) != NULL) {
48 *c = '\0';
49 if (access(path, X_OK)) {
50 if (errno != ENOENT){
51 advise (dir, "unable to create directory");
52 had_an_error = true;
53 }
54 /* Create an outer directory. */
55 if (mkdir(path, folder_perms)) {
56 advise (dir, "unable to create directory");
57 had_an_error = true;
58 }
59 }
60 *c = '/';
61 }
62
63 if (!had_an_error) {
64 /* Create the innermost nested subdirectory of the path we're being
65 asked to create. */
66 if (mkdir (dir, folder_perms) == -1) {
67 advise (dir, "unable to create directory");
68 had_an_error = true;
69 }
70 }
71
72 umask(saved_umask); /* put the user's umask back */
73
74 if (had_an_error)
75 return 0; /* opposite of UNIX error return convention */
76 return 1;
77 }