1 /*-------------------------------------------------------------------------
4 * directory handling functions
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
9 * This includes replacement versions of functions that work on
10 * Win32 (NT4 and newer).
13 * $PostgreSQL: pgsql/src/port/dirmod.c,v 1.58 2009/06/11 14:49:15 momjian Exp $
15 *-------------------------------------------------------------------------
21 #include "postgres_fe.h"
24 /* Don't modify declarations in system headers */
25 #if defined(WIN32) || defined(__CYGWIN__)
34 #if defined(WIN32) || defined(__CYGWIN__)
39 #include <w32api/winioctl.h>
47 * On Windows, call non-macro versions of palloc; we can't reference
48 * CurrentMemoryContext in this file because of PGDLLIMPORT conflict.
50 #if defined(WIN32) || defined(__CYGWIN__)
53 #define palloc(sz) pgport_palloc(sz)
54 #define pstrdup(str) pgport_pstrdup(str)
59 * In frontend, fake palloc behavior with these
63 #define palloc(sz) fe_palloc(sz)
64 #define pstrdup(str) fe_pstrdup(str)
65 #define repalloc(pointer,sz) fe_repalloc(pointer,sz)
66 #define pfree(pointer) free(pointer)
73 if ((res = malloc(size)) == NULL)
75 fprintf(stderr, _("out of memory\n"));
82 fe_pstrdup(const char *string)
86 if ((res = strdup(string)) == NULL)
88 fprintf(stderr, _("out of memory\n"));
95 fe_repalloc(void *pointer, Size size)
99 if ((res = realloc(pointer, size)) == NULL)
101 fprintf(stderr, _("out of memory\n"));
106 #endif /* FRONTEND */
109 #if defined(WIN32) || defined(__CYGWIN__)
115 pgrename(const char *from, const char *to)
120 * We need to loop because even though PostgreSQL uses flags that allow
121 * rename while the file is open, other applications might have the file
122 * open without those flags. However, we won't wait indefinitely for
123 * someone else to close the file.
125 #if defined(WIN32) && !defined(__CYGWIN__)
126 while (!MoveFileEx(from, to, MOVEFILE_REPLACE_EXISTING))
128 while (rename(from, to) < 0)
131 #if defined(WIN32) && !defined(__CYGWIN__)
132 if (GetLastError() != ERROR_ACCESS_DENIED)
138 if (++loops > 300) /* time out after 30 sec */
140 pg_usleep(100000); /* us */
150 pgunlink(const char *path)
155 * We need to loop because even though PostgreSQL uses flags that allow
156 * unlink while the file is open, other applications might have the file
157 * open without those flags. However, we won't wait indefinitely for
158 * someone else to close the file.
165 if (++loops > 300) /* time out after 30 sec */
167 pg_usleep(100000); /* us */
172 /* We undefined these above; now redefine for possible use below */
173 #define rename(from, to) pgrename(from, to)
174 #define unlink(path) pgunlink(path)
175 #endif /* defined(WIN32) || defined(__CYGWIN__) */
178 #if defined(WIN32) && !defined(__CYGWIN__) /* Cygwin has its own symlinks */
183 * This struct is a replacement for REPARSE_DATA_BUFFER which is defined in VC6 winnt.h
184 * but omitted in later SDK functions.
185 * We only need the SymbolicLinkReparseBuffer part of the original struct's union.
190 WORD ReparseDataLength;
192 /* SymbolicLinkReparseBuffer */
193 WORD SubstituteNameOffset;
194 WORD SubstituteNameLength;
195 WORD PrintNameOffset;
196 WORD PrintNameLength;
198 } REPARSE_JUNCTION_DATA_BUFFER;
200 #define REPARSE_JUNCTION_DATA_BUFFER_HEADER_SIZE \
201 FIELD_OFFSET(REPARSE_JUNCTION_DATA_BUFFER, SubstituteNameOffset)
205 * pgsymlink - uses Win32 junction points
207 * For reference: http://www.codeproject.com/w2k/junctionpoints.asp
210 pgsymlink(const char *oldpath, const char *newpath)
214 char buffer[MAX_PATH * sizeof(WCHAR) + sizeof(REPARSE_JUNCTION_DATA_BUFFER)];
215 char nativeTarget[MAX_PATH];
216 char *p = nativeTarget;
217 REPARSE_JUNCTION_DATA_BUFFER *reparseBuf = (REPARSE_JUNCTION_DATA_BUFFER *) buffer;
219 CreateDirectory(newpath, 0);
220 dirhandle = CreateFile(newpath, GENERIC_READ | GENERIC_WRITE,
222 FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, 0);
224 if (dirhandle == INVALID_HANDLE_VALUE)
227 /* make sure we have an unparsed native win32 path */
228 if (memcmp("\\??\\", oldpath, 4))
229 sprintf(nativeTarget, "\\??\\%s", oldpath);
231 strcpy(nativeTarget, oldpath);
233 while ((p = strchr(p, '/')) != 0)
236 len = strlen(nativeTarget) * sizeof(WCHAR);
237 reparseBuf->ReparseTag = IO_REPARSE_TAG_MOUNT_POINT;
238 reparseBuf->ReparseDataLength = len + 12;
239 reparseBuf->Reserved = 0;
240 reparseBuf->SubstituteNameOffset = 0;
241 reparseBuf->SubstituteNameLength = len;
242 reparseBuf->PrintNameOffset = len + sizeof(WCHAR);
243 reparseBuf->PrintNameLength = 0;
244 MultiByteToWideChar(CP_ACP, 0, nativeTarget, -1,
245 reparseBuf->PathBuffer, MAX_PATH);
248 * FSCTL_SET_REPARSE_POINT is coded differently depending on SDK version;
249 * we use our own definition
251 if (!DeviceIoControl(dirhandle,
252 CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 41, METHOD_BUFFERED, FILE_ANY_ACCESS),
254 reparseBuf->ReparseDataLength + REPARSE_JUNCTION_DATA_BUFFER_HEADER_SIZE,
260 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
261 NULL, GetLastError(),
262 MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
263 (LPSTR) &msg, 0, NULL);
266 (errcode_for_file_access(),
267 errmsg("could not set junction for \"%s\": %s",
268 nativeTarget, msg)));
270 fprintf(stderr, _("could not set junction for \"%s\": %s\n"),
275 CloseHandle(dirhandle);
276 RemoveDirectory(newpath);
280 CloseHandle(dirhandle);
284 #endif /* defined(WIN32) && !defined(__CYGWIN__) */
290 * return a list of the names of objects in the argument directory. Caller
291 * must call pgfnames_cleanup later to free the memory allocated by this
295 pgfnames(const char *path)
301 int fnsize = 200; /* enough for many small dbs */
307 elog(WARNING, "could not open directory \"%s\": %m", path);
309 fprintf(stderr, _("could not open directory \"%s\": %s\n"),
310 path, strerror(errno));
315 filenames = (char **) palloc(fnsize * sizeof(char *));
318 while ((file = readdir(dir)) != NULL)
320 if (strcmp(file->d_name, ".") != 0 && strcmp(file->d_name, "..") != 0)
322 if (numnames + 1 >= fnsize)
325 filenames = (char **) repalloc(filenames,
326 fnsize * sizeof(char *));
328 filenames[numnames++] = pstrdup(file->d_name);
335 * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in
338 if (GetLastError() == ERROR_NO_MORE_FILES)
344 elog(WARNING, "could not read directory \"%s\": %m", path);
346 fprintf(stderr, _("could not read directory \"%s\": %s\n"),
347 path, strerror(errno));
351 filenames[numnames] = NULL;
362 * deallocate memory used for filenames
365 pgfnames_cleanup(char **filenames)
369 for (fn = filenames; *fn; fn++)
379 * Delete a directory tree recursively.
380 * Assumes path points to a valid directory.
381 * Deletes everything under path.
382 * If rmtopdir is true deletes the directory too.
383 * Returns true if successful, false if there was any problem.
384 * (The details of the problem are reported already, so caller
385 * doesn't really have to say anything more, but most do.)
388 rmtree(const char *path, bool rmtopdir)
391 char pathbuf[MAXPGPATH];
397 * we copy all the names out of the directory before we start modifying
400 filenames = pgfnames(path);
402 if (filenames == NULL)
405 /* now we have the names we can start removing things */
406 for (filename = filenames; *filename; filename++)
408 snprintf(pathbuf, MAXPGPATH, "%s/%s", path, *filename);
411 * It's ok if the file is not there anymore; we were just about to
414 * This is not an academic possibility. One scenario where this
415 * happens is when bgwriter has a pending unlink request for a file in
416 * a database that's being dropped. In dropdb(), we call
417 * ForgetDatabaseFsyncRequests() to flush out any such pending unlink
418 * requests, but because that's asynchronous, it's not guaranteed that
419 * the bgwriter receives the message in time.
421 if (lstat(pathbuf, &statbuf) != 0)
426 elog(WARNING, "could not stat file or directory \"%s\": %m",
429 fprintf(stderr, _("could not stat file or directory \"%s\": %s\n"),
430 pathbuf, strerror(errno));
437 if (S_ISDIR(statbuf.st_mode))
439 /* call ourselves recursively for a directory */
440 if (!rmtree(pathbuf, true))
442 /* we already reported the error */
448 if (unlink(pathbuf) != 0)
453 elog(WARNING, "could not remove file or directory \"%s\": %m",
456 fprintf(stderr, _("could not remove file or directory \"%s\": %s\n"),
457 pathbuf, strerror(errno));
467 if (rmdir(path) != 0)
470 elog(WARNING, "could not remove file or directory \"%s\": %m",
473 fprintf(stderr, _("could not remove file or directory \"%s\": %s\n"),
474 path, strerror(errno));
480 pgfnames_cleanup(filenames);
486 #if defined(WIN32) && !defined(__CYGWIN__)
491 * The stat() function in win32 is not guaranteed to update the st_size
492 * field when run. So we define our own version that uses the Win32 API
493 * to update this field.
496 pgwin32_safestat(const char *path, struct stat * buf)
499 WIN32_FILE_ATTRIBUTE_DATA attr;
505 if (!GetFileAttributesEx(path, GetFileExInfoStandard, &attr))
507 _dosmaperr(GetLastError());
512 * XXX no support for large files here, but we don't do that in general on
515 buf->st_size = attr.nFileSizeLow;