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