1 /*-------------------------------------------------------------------------
4 * portable path handling routines
6 * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
13 *-------------------------------------------------------------------------
19 #include "postgres_fe.h"
28 #define _WIN32_IE 0x0500
38 #include "pg_config_paths.h"
42 #define IS_PATH_VAR_SEP(ch) ((ch) == ':')
44 #define IS_PATH_VAR_SEP(ch) ((ch) == ';')
47 static void make_relative_path(char *ret_path, const char *target_path,
48 const char *bin_path, const char *my_exec_path);
49 static void trim_directory(char *path);
50 static void trim_trailing_separator(char *path);
56 * On Windows, a path may begin with "C:" or "//network/". Advance over
57 * this and point to the effective start of the path.
62 skip_drive(const char *path)
64 if (IS_DIR_SEP(path[0]) && IS_DIR_SEP(path[1]))
67 while (*path && !IS_DIR_SEP(*path))
70 else if (isalpha((unsigned char) path[0]) && path[1] == ':')
78 #define skip_drive(path) (path)
84 * Return true if the given pathname has a drive prefix.
87 has_drive_prefix(const char *path)
89 return skip_drive(path) != path;
95 * Find the location of the first directory separator, return
99 first_dir_separator(const char *filename)
103 for (p = skip_drive(filename); *p; p++)
110 * first_path_var_separator
112 * Find the location of the first path separator (i.e. ':' on
113 * Unix, ';' on Windows), return NULL if not found.
116 first_path_var_separator(const char *pathlist)
120 /* skip_drive is not needed */
121 for (p = pathlist; *p; p++)
122 if (IS_PATH_VAR_SEP(*p))
130 * Find the location of the last directory separator, return
134 last_dir_separator(const char *filename)
139 for (p = skip_drive(filename); *p; p++)
147 * make_native_path - on WIN32, change / to \ in the path
149 * This effectively undoes canonicalize_path.
151 * This is required because WIN32 COPY is an internal CMD.EXE
152 * command and doesn't process forward slashes in the same way
153 * as external commands. Quoting the first argument to COPY
154 * does not convert forward to backward slashes, but COPY does
155 * properly process quoted forward slashes in the second argument.
157 * COPY works with quoted forward slashes in the first argument
158 * only if the current directory is the same as the directory
159 * of the first argument.
162 make_native_path(char *filename)
167 for (p = filename; *p; p++)
175 * join_path_components - join two path components, inserting a slash
177 * We omit the slash if either given component is empty.
179 * ret_path is the output area (must be of size MAXPGPATH)
181 * ret_path can be the same as head, but not the same as tail.
184 join_path_components(char *ret_path,
185 const char *head, const char *tail)
187 if (ret_path != head)
188 strlcpy(ret_path, head, MAXPGPATH);
191 * Remove any leading "." in the tail component.
193 * Note: we used to try to remove ".." as well, but that's tricky to get
194 * right; now we just leave it to be done by canonicalize_path() later.
196 while (tail[0] == '.' && IS_DIR_SEP(tail[1]))
201 /* only separate with slash if head wasn't empty */
202 snprintf(ret_path + strlen(ret_path), MAXPGPATH - strlen(ret_path),
204 (*(skip_drive(head)) != '\0') ? "/" : "",
212 * o make Win32 path use Unix slashes
213 * o remove trailing quote on Win32
214 * o remove trailing slash
215 * o remove duplicate adjacent separators
216 * o remove trailing '.'
217 * o process trailing '..' ourselves
220 canonicalize_path(char *path)
225 bool was_sep = false;
230 * The Windows command processor will accept suitably quoted paths with
231 * forward slashes, but barfs badly with mixed forward and back slashes.
233 for (p = path; *p; p++)
240 * In Win32, if you do: prog.exe "a b" "\c\d\" the system will pass \c\d"
241 * as argv[2], so trim off trailing quote.
243 if (p > path && *(p - 1) == '"')
248 * Removing the trailing slash on a path means we never get ugly double
249 * trailing slashes. Also, Win32 can't stat() a directory with a trailing
250 * slash. Don't remove a leading slash, though.
252 trim_trailing_separator(path);
255 * Remove duplicate adjacent separators
259 /* Don't remove leading double-slash on Win32 */
264 for (; *p; p++, to_p++)
266 /* Handle many adjacent slashes, like "/a///b" */
267 while (*p == '/' && was_sep)
271 was_sep = (*p == '/');
276 * Remove any trailing uses of "." and process ".." ourselves
278 * Note that "/../.." should reduce to just "/", while "../.." has to be
279 * kept as-is. In the latter case we put back mistakenly trimmed ".."
280 * components below. Also note that we want a Windows drive spec to be
281 * visible to trim_directory(), but it's not part of the logic that's
282 * looking at the name components; hence distinction between path and
285 spath = skip_drive(path);
289 int len = strlen(spath);
291 if (len >= 2 && strcmp(spath + len - 2, "/.") == 0)
292 trim_directory(path);
293 else if (strcmp(spath, ".") == 0)
295 /* Want to leave "." alone, but "./.." has to become ".." */
296 if (pending_strips > 0)
300 else if ((len >= 3 && strcmp(spath + len - 3, "/..") == 0) ||
301 strcmp(spath, "..") == 0)
303 trim_directory(path);
306 else if (pending_strips > 0 && *spath != '\0')
308 /* trim a regular directory name canceled by ".." */
309 trim_directory(path);
311 /* foo/.. should become ".", not empty */
319 if (pending_strips > 0)
322 * We could only get here if path is now totally empty (other than a
323 * possible drive specifier on Windows). We have to put back one or
324 * more ".."'s that we took off.
326 while (--pending_strips > 0)
333 * Detect whether a path contains any parent-directory references ("..")
335 * The input *must* have been put through canonicalize_path previously.
337 * This is a bit tricky because we mustn't be fooled by "..a.." (legal)
338 * nor "C:.." (legal on Unix but not Windows).
341 path_contains_parent_reference(const char *path)
345 path = skip_drive(path); /* C: shouldn't affect our conclusion */
347 path_len = strlen(path);
350 * ".." could be the whole path; otherwise, if it's present it must be at
351 * the beginning, in the middle, or at the end.
353 if (strcmp(path, "..") == 0 ||
354 strncmp(path, "../", 3) == 0 ||
355 strstr(path, "/../") != NULL ||
356 (path_len >= 3 && strcmp(path + path_len - 3, "/..") == 0))
363 * Detect whether a path is only in or below the current working directory.
364 * An absolute path that matches the current working directory should
365 * return false (we only want relative to the cwd). We don't allow
366 * "/../" even if that would keep us under the cwd (it is too hard to
370 path_is_relative_and_below_cwd(const char *path)
372 if (is_absolute_path(path))
374 /* don't allow anything above the cwd */
375 else if (path_contains_parent_reference(path))
379 * On Win32, a drive letter _not_ followed by a slash, e.g. 'E:abc', is
380 * relative to the cwd on that drive, or the drive's root directory if
381 * that drive has no cwd. Because the path itself cannot tell us which is
382 * the case, we have to assume the worst, i.e. that it is not below the
383 * cwd. We could use GetFullPathName() to find the full path but that
384 * could change if the current directory for the drive changes underneath
385 * us, so we just disallow it.
387 else if (isalpha((unsigned char) path[0]) && path[1] == ':' &&
388 !IS_DIR_SEP(path[2]))
396 * Detect whether path1 is a prefix of path2 (including equality).
398 * This is pretty trivial, but it seems better to export a function than
399 * to export IS_DIR_SEP.
402 path_is_prefix_of_path(const char *path1, const char *path2)
404 int path1_len = strlen(path1);
406 if (strncmp(path1, path2, path1_len) == 0 &&
407 (IS_DIR_SEP(path2[path1_len]) || path2[path1_len] == '\0'))
413 * Extracts the actual name of the program as called -
414 * stripped of .exe suffix if any
417 get_progname(const char *argv0)
419 const char *nodir_name;
422 nodir_name = last_dir_separator(argv0);
426 nodir_name = skip_drive(argv0);
429 * Make a copy in case argv[0] is modified by ps_status. Leaks memory, but
432 progname = strdup(nodir_name);
433 if (progname == NULL)
435 fprintf(stderr, "%s: out of memory\n", nodir_name);
436 abort(); /* This could exit the postmaster */
439 #if defined(__CYGWIN__) || defined(WIN32)
440 /* strip ".exe" suffix, regardless of case */
441 if (strlen(progname) > sizeof(EXE) - 1 &&
442 pg_strcasecmp(progname + strlen(progname) - (sizeof(EXE) - 1), EXE) == 0)
443 progname[strlen(progname) - (sizeof(EXE) - 1)] = '\0';
451 * dir_strcmp: strcmp except any two DIR_SEP characters are considered equal,
452 * and we honor filesystem case insensitivity if known
455 dir_strcmp(const char *s1, const char *s2)
463 /* On windows, paths are case-insensitive */
464 pg_tolower((unsigned char) *s1) != pg_tolower((unsigned char) *s2)
466 && !(IS_DIR_SEP(*s1) && IS_DIR_SEP(*s2)))
467 return (int) *s1 - (int) *s2;
471 return 1; /* s1 longer */
473 return -1; /* s2 longer */
479 * make_relative_path - make a path relative to the actual binary location
481 * This function exists to support relocation of installation trees.
483 * ret_path is the output area (must be of size MAXPGPATH)
484 * target_path is the compiled-in path to the directory we want to find
485 * bin_path is the compiled-in path to the directory of executables
486 * my_exec_path is the actual location of my executable
488 * We determine the common prefix of target_path and bin_path, then compare
489 * the remainder of bin_path to the last directory component(s) of
490 * my_exec_path. If they match, build the result as the part of my_exec_path
491 * preceding the match, joined to the remainder of target_path. If no match,
492 * return target_path as-is.
495 * target_path = '/usr/local/share/postgresql'
496 * bin_path = '/usr/local/bin'
497 * my_exec_path = '/opt/pgsql/bin/postmaster'
498 * Given these inputs, the common prefix is '/usr/local/', the tail of
499 * bin_path is 'bin' which does match the last directory component of
500 * my_exec_path, so we would return '/opt/pgsql/share/postgresql'
503 make_relative_path(char *ret_path, const char *target_path,
504 const char *bin_path, const char *my_exec_path)
512 * Determine the common prefix --- note we require it to end on a
513 * directory separator, consider eg '/usr/lib' and '/usr/libexec'.
516 for (i = 0; target_path[i] && bin_path[i]; i++)
518 if (IS_DIR_SEP(target_path[i]) && IS_DIR_SEP(bin_path[i]))
520 else if (target_path[i] != bin_path[i])
524 goto no_match; /* no common prefix? */
525 tail_len = strlen(bin_path) - prefix_len;
528 * Set up my_exec_path without the actual executable name, and
529 * canonicalize to simplify comparison to bin_path.
531 strlcpy(ret_path, my_exec_path, MAXPGPATH);
532 trim_directory(ret_path); /* remove my executable name */
533 canonicalize_path(ret_path);
538 tail_start = (int) strlen(ret_path) - tail_len;
539 if (tail_start > 0 &&
540 IS_DIR_SEP(ret_path[tail_start - 1]) &&
541 dir_strcmp(ret_path + tail_start, bin_path + prefix_len) == 0)
543 ret_path[tail_start] = '\0';
544 trim_trailing_separator(ret_path);
545 join_path_components(ret_path, ret_path, target_path + prefix_len);
546 canonicalize_path(ret_path);
551 strlcpy(ret_path, target_path, MAXPGPATH);
552 canonicalize_path(ret_path);
559 * If the given pathname isn't already absolute, make it so, interpreting
560 * it relative to the current working directory.
562 * Also canonicalizes the path. The result is always a malloc'd copy.
564 * In backend, failure cases result in ereport(ERROR); in frontend,
565 * we write a complaint on stderr and return NULL.
567 * Note: interpretation of relative-path arguments during postmaster startup
568 * should happen before doing ChangeToDataDir(), else the user will probably
569 * not like the results.
572 make_absolute_path(const char *path)
576 /* Returning null for null input is convenient for some callers */
580 if (!is_absolute_path(path))
588 buf = malloc(buflen);
593 (errcode(ERRCODE_OUT_OF_MEMORY),
594 errmsg("out of memory")));
596 fprintf(stderr, _("out of memory\n"));
601 if (getcwd(buf, buflen))
603 else if (errno == ERANGE)
613 elog(ERROR, "could not get current working directory: %m");
615 fprintf(stderr, _("could not get current working directory: %s\n"),
622 new = malloc(strlen(buf) + strlen(path) + 2);
628 (errcode(ERRCODE_OUT_OF_MEMORY),
629 errmsg("out of memory")));
631 fprintf(stderr, _("out of memory\n"));
635 sprintf(new, "%s/%s", buf, path);
645 (errcode(ERRCODE_OUT_OF_MEMORY),
646 errmsg("out of memory")));
648 fprintf(stderr, _("out of memory\n"));
654 /* Make sure punctuation is canonical, too */
655 canonicalize_path(new);
665 get_share_path(const char *my_exec_path, char *ret_path)
667 make_relative_path(ret_path, PGSHAREDIR, PGBINDIR, my_exec_path);
674 get_etc_path(const char *my_exec_path, char *ret_path)
676 make_relative_path(ret_path, SYSCONFDIR, PGBINDIR, my_exec_path);
683 get_include_path(const char *my_exec_path, char *ret_path)
685 make_relative_path(ret_path, INCLUDEDIR, PGBINDIR, my_exec_path);
689 * get_pkginclude_path
692 get_pkginclude_path(const char *my_exec_path, char *ret_path)
694 make_relative_path(ret_path, PKGINCLUDEDIR, PGBINDIR, my_exec_path);
698 * get_includeserver_path
701 get_includeserver_path(const char *my_exec_path, char *ret_path)
703 make_relative_path(ret_path, INCLUDEDIRSERVER, PGBINDIR, my_exec_path);
710 get_lib_path(const char *my_exec_path, char *ret_path)
712 make_relative_path(ret_path, LIBDIR, PGBINDIR, my_exec_path);
719 get_pkglib_path(const char *my_exec_path, char *ret_path)
721 make_relative_path(ret_path, PKGLIBDIR, PGBINDIR, my_exec_path);
728 get_locale_path(const char *my_exec_path, char *ret_path)
730 make_relative_path(ret_path, LOCALEDIR, PGBINDIR, my_exec_path);
737 get_doc_path(const char *my_exec_path, char *ret_path)
739 make_relative_path(ret_path, DOCDIR, PGBINDIR, my_exec_path);
746 get_html_path(const char *my_exec_path, char *ret_path)
748 make_relative_path(ret_path, HTMLDIR, PGBINDIR, my_exec_path);
755 get_man_path(const char *my_exec_path, char *ret_path)
757 make_relative_path(ret_path, MANDIR, PGBINDIR, my_exec_path);
764 * On Unix, this actually returns the user's home directory. On Windows
765 * it returns the PostgreSQL-specific application data folder.
768 get_home_path(char *ret_path)
772 struct passwd pwdstr;
773 struct passwd *pwd = NULL;
775 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
777 strlcpy(ret_path, pwd->pw_dir, MAXPGPATH);
783 * Note: We use getenv here because the more modern
784 * SHGetSpecialFolderPath() will force us to link with shell32.lib which
785 * eats valuable desktop heap.
787 tmppath = getenv("APPDATA");
790 snprintf(ret_path, MAXPGPATH, "%s/postgresql", tmppath);
797 * get_parent_directory
799 * Modify the given string in-place to name the parent directory of the
802 * If the input is just a file name with no directory part, the result is
803 * an empty string, not ".". This is appropriate when the next step is
804 * join_path_components(), but might need special handling otherwise.
806 * Caution: this will not produce desirable results if the string ends
807 * with "..". For most callers this is not a problem since the string
808 * is already known to name a regular file. If in doubt, apply
809 * canonicalize_path() first.
812 get_parent_directory(char *path)
814 trim_directory(path);
821 * Trim trailing directory from path, that is, remove any trailing slashes,
822 * the last pathname component, and the slash just ahead of it --- but never
823 * remove a leading slash.
826 trim_directory(char *path)
830 path = skip_drive(path);
835 /* back up over trailing slash(es) */
836 for (p = path + strlen(path) - 1; IS_DIR_SEP(*p) && p > path; p--)
838 /* back up over directory name */
839 for (; !IS_DIR_SEP(*p) && p > path; p--)
841 /* if multiple slashes before directory name, remove 'em all */
842 for (; p > path && IS_DIR_SEP(*(p - 1)); p--)
844 /* don't erase a leading slash */
845 if (p == path && IS_DIR_SEP(*p))
852 * trim_trailing_separator
854 * trim off trailing slashes, but not a leading slash
857 trim_trailing_separator(char *path)
861 path = skip_drive(path);
862 p = path + strlen(path);
864 for (p--; p > path && IS_DIR_SEP(*p); p--)