PostgreSQL Source Code  git master
pgmkdirp.c File Reference
#include "c.h"
#include <sys/stat.h>
Include dependency graph for pgmkdirp.c:

Go to the source code of this file.

Functions

int pg_mkdir_p (char *path, int omode)
 

Function Documentation

◆ pg_mkdir_p()

int pg_mkdir_p ( char *  path,
int  omode 
)

Definition at line 57 of file pgmkdirp.c.

58 {
59  struct stat sb;
60  mode_t numask,
61  oumask;
62  int last,
63  retval;
64  char *p;
65 
66  retval = 0;
67  p = path;
68 
69 #ifdef WIN32
70  /* skip network and drive specifiers for win32 */
71  if (strlen(p) >= 2)
72  {
73  if (p[0] == '/' && p[1] == '/')
74  {
75  /* network drive */
76  p = strstr(p + 2, "/");
77  if (p == NULL)
78  {
79  errno = EINVAL;
80  return -1;
81  }
82  }
83  else if (p[1] == ':' &&
84  ((p[0] >= 'a' && p[0] <= 'z') ||
85  (p[0] >= 'A' && p[0] <= 'Z')))
86  {
87  /* local drive */
88  p += 2;
89  }
90  }
91 #endif
92 
93  /*
94  * POSIX 1003.2: For each dir operand that does not name an existing
95  * directory, effects equivalent to those caused by the following command
96  * shall occur:
97  *
98  * mkdir -p -m $(umask -S),u+wx $(dirname dir) && mkdir [-m mode] dir
99  *
100  * We change the user's umask and then restore it, instead of doing
101  * chmod's. Note we assume umask() can't change errno.
102  */
103  oumask = umask(0);
104  numask = oumask & ~(S_IWUSR | S_IXUSR);
105  (void) umask(numask);
106 
107  if (p[0] == '/') /* Skip leading '/'. */
108  ++p;
109  for (last = 0; !last; ++p)
110  {
111  if (p[0] == '\0')
112  last = 1;
113  else if (p[0] != '/')
114  continue;
115  *p = '\0';
116  if (!last && p[1] == '\0')
117  last = 1;
118 
119  if (last)
120  (void) umask(oumask);
121 
122  /* check for pre-existing directory */
123  if (stat(path, &sb) == 0)
124  {
125  if (!S_ISDIR(sb.st_mode))
126  {
127  if (last)
128  errno = EEXIST;
129  else
130  errno = ENOTDIR;
131  retval = -1;
132  break;
133  }
134  }
135  else if (mkdir(path, last ? omode : S_IRWXU | S_IRWXG | S_IRWXO) < 0)
136  {
137  retval = -1;
138  break;
139  }
140  if (!last)
141  *p = '/';
142  }
143 
144  /* ensure we restored umask */
145  (void) umask(oumask);
146 
147  return retval;
148 }
#define stat
Definition: win32_port.h:284
#define S_IRWXG
Definition: win32_port.h:310
#define S_IRWXO
Definition: win32_port.h:322
#define S_ISDIR(m)
Definition: win32_port.h:325
#define mkdir(a, b)
Definition: win32_port.h:80
#define S_IWUSR
Definition: win32_port.h:292
#define S_IXUSR
Definition: win32_port.h:295
#define S_IRWXU
Definition: win32_port.h:298

References mkdir, S_IRWXG, S_IRWXO, S_IRWXU, S_ISDIR, S_IWUSR, S_IXUSR, stat::st_mode, and stat.

Referenced by create_data_directory(), create_fullpage_directory(), create_output_directory(), create_xlog_or_symlink(), main(), recovery_create_dbdir(), StartLogStreamer(), TablespaceCreateDbspace(), and verify_dir_is_empty_or_create().