1 /*-------------------------------------------------------------------------
4 * portable path handling routines
6 * Portions Copyright (c) 1996-2017, 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)
90 return skip_drive(path) != path;
99 * Find the location of the first directory separator, return
103 first_dir_separator(const char *filename)
107 for (p = skip_drive(filename); *p; p++)
114 * first_path_var_separator
116 * Find the location of the first path separator (i.e. ':' on
117 * Unix, ';' on Windows), return NULL if not found.
120 first_path_var_separator(const char *pathlist)
124 /* skip_drive is not needed */
125 for (p = pathlist; *p; p++)
126 if (IS_PATH_VAR_SEP(*p))
134 * Find the location of the last directory separator, return
138 last_dir_separator(const char *filename)
143 for (p = skip_drive(filename); *p; p++)
151 * make_native_path - on WIN32, change / to \ in the path
153 * This effectively undoes canonicalize_path.
155 * This is required because WIN32 COPY is an internal CMD.EXE
156 * command and doesn't process forward slashes in the same way
157 * as external commands. Quoting the first argument to COPY
158 * does not convert forward to backward slashes, but COPY does
159 * properly process quoted forward slashes in the second argument.
161 * COPY works with quoted forward slashes in the first argument
162 * only if the current directory is the same as the directory
163 * of the first argument.
166 make_native_path(char *filename)
171 for (p = filename; *p; p++)
179 * This function cleans up the paths for use with either cmd.exe or Msys
180 * on Windows. We need them to use filenames without spaces, for which a
181 * short filename is the safest equivalent, eg:
185 cleanup_path(char *path)
191 * GetShortPathName() will fail if the path does not exist, or short names
192 * are disabled on this file system. In both cases, we just return the
193 * original path. This is particularly useful for --sysconfdir, which
196 GetShortPathName(path, path, MAXPGPATH - 1);
198 /* Replace '\' with '/' */
199 for (ptr = path; *ptr; ptr++)
209 * join_path_components - join two path components, inserting a slash
211 * We omit the slash if either given component is empty.
213 * ret_path is the output area (must be of size MAXPGPATH)
215 * ret_path can be the same as head, but not the same as tail.
218 join_path_components(char *ret_path,
219 const char *head, const char *tail)
221 if (ret_path != head)
222 strlcpy(ret_path, head, MAXPGPATH);
225 * Remove any leading "." in the tail component.
227 * Note: we used to try to remove ".." as well, but that's tricky to get
228 * right; now we just leave it to be done by canonicalize_path() later.
230 while (tail[0] == '.' && IS_DIR_SEP(tail[1]))
235 /* only separate with slash if head wasn't empty */
236 snprintf(ret_path + strlen(ret_path), MAXPGPATH - strlen(ret_path),
238 (*(skip_drive(head)) != '\0') ? "/" : "",
246 * o make Win32 path use Unix slashes
247 * o remove trailing quote on Win32
248 * o remove trailing slash
249 * o remove duplicate adjacent separators
250 * o remove trailing '.'
251 * o process trailing '..' ourselves
254 canonicalize_path(char *path)
259 bool was_sep = false;
265 * The Windows command processor will accept suitably quoted paths with
266 * forward slashes, but barfs badly with mixed forward and back slashes.
268 for (p = path; *p; p++)
275 * In Win32, if you do: prog.exe "a b" "\c\d\" the system will pass \c\d"
276 * as argv[2], so trim off trailing quote.
278 if (p > path && *(p - 1) == '"')
283 * Removing the trailing slash on a path means we never get ugly double
284 * trailing slashes. Also, Win32 can't stat() a directory with a trailing
285 * slash. Don't remove a leading slash, though.
287 trim_trailing_separator(path);
290 * Remove duplicate adjacent separators
294 /* Don't remove leading double-slash on Win32 */
299 for (; *p; p++, to_p++)
301 /* Handle many adjacent slashes, like "/a///b" */
302 while (*p == '/' && was_sep)
306 was_sep = (*p == '/');
311 * Remove any trailing uses of "." and process ".." ourselves
313 * Note that "/../.." should reduce to just "/", while "../.." has to be
314 * kept as-is. In the latter case we put back mistakenly trimmed ".."
315 * components below. Also note that we want a Windows drive spec to be
316 * visible to trim_directory(), but it's not part of the logic that's
317 * looking at the name components; hence distinction between path and
320 spath = skip_drive(path);
324 int len = strlen(spath);
326 if (len >= 2 && strcmp(spath + len - 2, "/.") == 0)
327 trim_directory(path);
328 else if (strcmp(spath, ".") == 0)
330 /* Want to leave "." alone, but "./.." has to become ".." */
331 if (pending_strips > 0)
335 else if ((len >= 3 && strcmp(spath + len - 3, "/..") == 0) ||
336 strcmp(spath, "..") == 0)
338 trim_directory(path);
341 else if (pending_strips > 0 && *spath != '\0')
343 /* trim a regular directory name canceled by ".." */
344 trim_directory(path);
346 /* foo/.. should become ".", not empty */
354 if (pending_strips > 0)
357 * We could only get here if path is now totally empty (other than a
358 * possible drive specifier on Windows). We have to put back one or
359 * more ".."'s that we took off.
361 while (--pending_strips > 0)
368 * Detect whether a path contains any parent-directory references ("..")
370 * The input *must* have been put through canonicalize_path previously.
372 * This is a bit tricky because we mustn't be fooled by "..a.." (legal)
373 * nor "C:.." (legal on Unix but not Windows).
376 path_contains_parent_reference(const char *path)
380 path = skip_drive(path); /* C: shouldn't affect our conclusion */
382 path_len = strlen(path);
385 * ".." could be the whole path; otherwise, if it's present it must be at
386 * the beginning, in the middle, or at the end.
388 if (strcmp(path, "..") == 0 ||
389 strncmp(path, "../", 3) == 0 ||
390 strstr(path, "/../") != NULL ||
391 (path_len >= 3 && strcmp(path + path_len - 3, "/..") == 0))
398 * Detect whether a path is only in or below the current working directory.
399 * An absolute path that matches the current working directory should
400 * return false (we only want relative to the cwd). We don't allow
401 * "/../" even if that would keep us under the cwd (it is too hard to
405 path_is_relative_and_below_cwd(const char *path)
407 if (is_absolute_path(path))
409 /* don't allow anything above the cwd */
410 else if (path_contains_parent_reference(path))
415 * On Win32, a drive letter _not_ followed by a slash, e.g. 'E:abc', is
416 * relative to the cwd on that drive, or the drive's root directory if
417 * that drive has no cwd. Because the path itself cannot tell us which is
418 * the case, we have to assume the worst, i.e. that it is not below the
419 * cwd. We could use GetFullPathName() to find the full path but that
420 * could change if the current directory for the drive changes underneath
421 * us, so we just disallow it.
423 else if (isalpha((unsigned char) path[0]) && path[1] == ':' &&
424 !IS_DIR_SEP(path[2]))
432 * Detect whether path1 is a prefix of path2 (including equality).
434 * This is pretty trivial, but it seems better to export a function than
435 * to export IS_DIR_SEP.
438 path_is_prefix_of_path(const char *path1, const char *path2)
440 int path1_len = strlen(path1);
442 if (strncmp(path1, path2, path1_len) == 0 &&
443 (IS_DIR_SEP(path2[path1_len]) || path2[path1_len] == '\0'))
449 * Extracts the actual name of the program as called -
450 * stripped of .exe suffix if any
453 get_progname(const char *argv0)
455 const char *nodir_name;
458 nodir_name = last_dir_separator(argv0);
462 nodir_name = skip_drive(argv0);
465 * Make a copy in case argv[0] is modified by ps_status. Leaks memory, but
468 progname = strdup(nodir_name);
469 if (progname == NULL)
471 fprintf(stderr, "%s: out of memory\n", nodir_name);
472 abort(); /* This could exit the postmaster */
475 #if defined(__CYGWIN__) || defined(WIN32)
476 /* strip ".exe" suffix, regardless of case */
477 if (strlen(progname) > sizeof(EXE) - 1 &&
478 pg_strcasecmp(progname + strlen(progname) - (sizeof(EXE) - 1), EXE) == 0)
479 progname[strlen(progname) - (sizeof(EXE) - 1)] = '\0';
487 * dir_strcmp: strcmp except any two DIR_SEP characters are considered equal,
488 * and we honor filesystem case insensitivity if known
491 dir_strcmp(const char *s1, const char *s2)
499 /* On windows, paths are case-insensitive */
500 pg_tolower((unsigned char) *s1) != pg_tolower((unsigned char) *s2)
502 && !(IS_DIR_SEP(*s1) && IS_DIR_SEP(*s2)))
503 return (int) *s1 - (int) *s2;
507 return 1; /* s1 longer */
509 return -1; /* s2 longer */
515 * make_relative_path - make a path relative to the actual binary location
517 * This function exists to support relocation of installation trees.
519 * ret_path is the output area (must be of size MAXPGPATH)
520 * target_path is the compiled-in path to the directory we want to find
521 * bin_path is the compiled-in path to the directory of executables
522 * my_exec_path is the actual location of my executable
524 * We determine the common prefix of target_path and bin_path, then compare
525 * the remainder of bin_path to the last directory component(s) of
526 * my_exec_path. If they match, build the result as the part of my_exec_path
527 * preceding the match, joined to the remainder of target_path. If no match,
528 * return target_path as-is.
531 * target_path = '/usr/local/share/postgresql'
532 * bin_path = '/usr/local/bin'
533 * my_exec_path = '/opt/pgsql/bin/postmaster'
534 * Given these inputs, the common prefix is '/usr/local/', the tail of
535 * bin_path is 'bin' which does match the last directory component of
536 * my_exec_path, so we would return '/opt/pgsql/share/postgresql'
539 make_relative_path(char *ret_path, const char *target_path,
540 const char *bin_path, const char *my_exec_path)
548 * Determine the common prefix --- note we require it to end on a
549 * directory separator, consider eg '/usr/lib' and '/usr/libexec'.
552 for (i = 0; target_path[i] && bin_path[i]; i++)
554 if (IS_DIR_SEP(target_path[i]) && IS_DIR_SEP(bin_path[i]))
556 else if (target_path[i] != bin_path[i])
560 goto no_match; /* no common prefix? */
561 tail_len = strlen(bin_path) - prefix_len;
564 * Set up my_exec_path without the actual executable name, and
565 * canonicalize to simplify comparison to bin_path.
567 strlcpy(ret_path, my_exec_path, MAXPGPATH);
568 trim_directory(ret_path); /* remove my executable name */
569 canonicalize_path(ret_path);
574 tail_start = (int) strlen(ret_path) - tail_len;
575 if (tail_start > 0 &&
576 IS_DIR_SEP(ret_path[tail_start - 1]) &&
577 dir_strcmp(ret_path + tail_start, bin_path + prefix_len) == 0)
579 ret_path[tail_start] = '\0';
580 trim_trailing_separator(ret_path);
581 join_path_components(ret_path, ret_path, target_path + prefix_len);
582 canonicalize_path(ret_path);
587 strlcpy(ret_path, target_path, MAXPGPATH);
588 canonicalize_path(ret_path);
595 * If the given pathname isn't already absolute, make it so, interpreting
596 * it relative to the current working directory.
598 * Also canonicalizes the path. The result is always a malloc'd copy.
600 * In backend, failure cases result in ereport(ERROR); in frontend,
601 * we write a complaint on stderr and return NULL.
603 * Note: interpretation of relative-path arguments during postmaster startup
604 * should happen before doing ChangeToDataDir(), else the user will probably
605 * not like the results.
608 make_absolute_path(const char *path)
612 /* Returning null for null input is convenient for some callers */
616 if (!is_absolute_path(path))
624 buf = malloc(buflen);
629 (errcode(ERRCODE_OUT_OF_MEMORY),
630 errmsg("out of memory")));
632 fprintf(stderr, _("out of memory\n"));
637 if (getcwd(buf, buflen))
639 else if (errno == ERANGE)
647 int save_errno = errno;
652 elog(ERROR, "could not get current working directory: %m");
654 fprintf(stderr, _("could not get current working directory: %s\n"),
661 new = malloc(strlen(buf) + strlen(path) + 2);
667 (errcode(ERRCODE_OUT_OF_MEMORY),
668 errmsg("out of memory")));
670 fprintf(stderr, _("out of memory\n"));
674 sprintf(new, "%s/%s", buf, path);
684 (errcode(ERRCODE_OUT_OF_MEMORY),
685 errmsg("out of memory")));
687 fprintf(stderr, _("out of memory\n"));
693 /* Make sure punctuation is canonical, too */
694 canonicalize_path(new);
704 get_share_path(const char *my_exec_path, char *ret_path)
706 make_relative_path(ret_path, PGSHAREDIR, PGBINDIR, my_exec_path);
713 get_etc_path(const char *my_exec_path, char *ret_path)
715 make_relative_path(ret_path, SYSCONFDIR, PGBINDIR, my_exec_path);
722 get_include_path(const char *my_exec_path, char *ret_path)
724 make_relative_path(ret_path, INCLUDEDIR, PGBINDIR, my_exec_path);
728 * get_pkginclude_path
731 get_pkginclude_path(const char *my_exec_path, char *ret_path)
733 make_relative_path(ret_path, PKGINCLUDEDIR, PGBINDIR, my_exec_path);
737 * get_includeserver_path
740 get_includeserver_path(const char *my_exec_path, char *ret_path)
742 make_relative_path(ret_path, INCLUDEDIRSERVER, PGBINDIR, my_exec_path);
749 get_lib_path(const char *my_exec_path, char *ret_path)
751 make_relative_path(ret_path, LIBDIR, PGBINDIR, my_exec_path);
758 get_pkglib_path(const char *my_exec_path, char *ret_path)
760 make_relative_path(ret_path, PKGLIBDIR, PGBINDIR, my_exec_path);
767 get_locale_path(const char *my_exec_path, char *ret_path)
769 make_relative_path(ret_path, LOCALEDIR, PGBINDIR, my_exec_path);
776 get_doc_path(const char *my_exec_path, char *ret_path)
778 make_relative_path(ret_path, DOCDIR, PGBINDIR, my_exec_path);
785 get_html_path(const char *my_exec_path, char *ret_path)
787 make_relative_path(ret_path, HTMLDIR, PGBINDIR, my_exec_path);
794 get_man_path(const char *my_exec_path, char *ret_path)
796 make_relative_path(ret_path, MANDIR, PGBINDIR, my_exec_path);
803 * On Unix, this actually returns the user's home directory. On Windows
804 * it returns the PostgreSQL-specific application data folder.
807 get_home_path(char *ret_path)
811 struct passwd pwdstr;
812 struct passwd *pwd = NULL;
814 (void) pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd);
817 strlcpy(ret_path, pwd->pw_dir, MAXPGPATH);
823 * Note: We use getenv() here because the more modern SHGetFolderPath()
824 * would force the backend to link with shell32.lib, which eats valuable
825 * desktop heap. XXX This function is used only in psql, which already
826 * brings in shell32 via libpq. Moving this function to its own file
827 * would keep it out of the backend, freeing it from this concern.
829 tmppath = getenv("APPDATA");
832 snprintf(ret_path, MAXPGPATH, "%s/postgresql", tmppath);
839 * get_parent_directory
841 * Modify the given string in-place to name the parent directory of the
844 * If the input is just a file name with no directory part, the result is
845 * an empty string, not ".". This is appropriate when the next step is
846 * join_path_components(), but might need special handling otherwise.
848 * Caution: this will not produce desirable results if the string ends
849 * with "..". For most callers this is not a problem since the string
850 * is already known to name a regular file. If in doubt, apply
851 * canonicalize_path() first.
854 get_parent_directory(char *path)
856 trim_directory(path);
863 * Trim trailing directory from path, that is, remove any trailing slashes,
864 * the last pathname component, and the slash just ahead of it --- but never
865 * remove a leading slash.
868 trim_directory(char *path)
872 path = skip_drive(path);
877 /* back up over trailing slash(es) */
878 for (p = path + strlen(path) - 1; IS_DIR_SEP(*p) && p > path; p--)
880 /* back up over directory name */
881 for (; !IS_DIR_SEP(*p) && p > path; p--)
883 /* if multiple slashes before directory name, remove 'em all */
884 for (; p > path && IS_DIR_SEP(*(p - 1)); p--)
886 /* don't erase a leading slash */
887 if (p == path && IS_DIR_SEP(*p))
894 * trim_trailing_separator
896 * trim off trailing slashes, but not a leading slash
899 trim_trailing_separator(char *path)
903 path = skip_drive(path);
904 p = path + strlen(path);
906 for (p--; p > path && IS_DIR_SEP(*p); p--)