PostgreSQL Source Code  git master
port.h File Reference
#include <ctype.h>
#include <netinet/in.h>
#include <arpa/inet.h>
Include dependency graph for port.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Macros

#define PGINVALID_SOCKET   (-1)
 
#define IS_NONWINDOWS_DIR_SEP(ch)   ((ch) == '/')
 
#define is_nonwindows_absolute_path(filename)
 
#define IS_WINDOWS_DIR_SEP(ch)   ((ch) == '/' || (ch) == '\\')
 
#define is_windows_absolute_path(filename)
 
#define IS_DIR_SEP(ch)   IS_NONWINDOWS_DIR_SEP(ch)
 
#define is_absolute_path(filename)   is_nonwindows_absolute_path(filename)
 
#define ALL_CONNECTION_FAILURE_ERRNOS
 
#define PG_BACKEND_VERSIONSTR   "postgres (PostgreSQL) " PG_VERSION "\n"
 
#define EXE   ""
 
#define DEVNULL   "/dev/null"
 
#define USE_REPL_SNPRINTF   1
 
#define pg_pread   pread
 
#define pg_pwrite   pwrite
 
#define vsnprintf   pg_vsnprintf
 
#define snprintf   pg_snprintf
 
#define vsprintf   pg_vsprintf
 
#define sprintf   pg_sprintf
 
#define vfprintf   pg_vfprintf
 
#define fprintf   pg_fprintf
 
#define vprintf   pg_vprintf
 
#define printf(...)   pg_printf(__VA_ARGS__)
 
#define strerror   pg_strerror
 
#define strerror_r   pg_strerror_r
 
#define PG_STRERROR_R_BUFLEN   256 /* Recommended buffer size for strerror_r */
 
#define TIMEZONE_GLOBAL   timezone
 
#define TZNAME_GLOBAL   tzname
 
#define closesocket   close
 
#define PG_IOLBF   _IOLBF
 
#define pgoff_t   off_t
 
#define qsort(a, b, c, d)   pg_qsort(a,b,c,d)
 
#define pg_backend_random   pg_strong_random
 
#define HAVE_GETRLIMIT   1
 
#define HAVE_POLL   1
 
#define HAVE_POLL_H   1
 
#define HAVE_READLINK   1
 
#define HAVE_SETSID   1
 
#define HAVE_SHM_OPEN   1
 
#define HAVE_SYMLINK   1
 

Typedefs

typedef int pgsocket
 
typedef unsigned int socklen_t
 
typedef int(* qsort_arg_comparator) (const void *a, const void *b, void *arg)
 
typedef void(* pqsigfunc) (SIGNAL_ARGS)
 

Functions

bool pg_set_noblock (pgsocket sock)
 
bool pg_set_block (pgsocket sock)
 
bool has_drive_prefix (const char *path)
 
char * first_dir_separator (const char *filename)
 
char * last_dir_separator (const char *filename)
 
char * first_path_var_separator (const char *pathlist)
 
void join_path_components (char *ret_path, const char *head, const char *tail)
 
void canonicalize_path (char *path)
 
void make_native_path (char *filename)
 
void cleanup_path (char *path)
 
bool path_contains_parent_reference (const char *path)
 
bool path_is_relative_and_below_cwd (const char *path)
 
bool path_is_prefix_of_path (const char *path1, const char *path2)
 
char * make_absolute_path (const char *path)
 
const char * get_progname (const char *argv0)
 
void get_share_path (const char *my_exec_path, char *ret_path)
 
void get_etc_path (const char *my_exec_path, char *ret_path)
 
void get_include_path (const char *my_exec_path, char *ret_path)
 
void get_pkginclude_path (const char *my_exec_path, char *ret_path)
 
void get_includeserver_path (const char *my_exec_path, char *ret_path)
 
void get_lib_path (const char *my_exec_path, char *ret_path)
 
void get_pkglib_path (const char *my_exec_path, char *ret_path)
 
void get_locale_path (const char *my_exec_path, char *ret_path)
 
void get_doc_path (const char *my_exec_path, char *ret_path)
 
void get_html_path (const char *my_exec_path, char *ret_path)
 
void get_man_path (const char *my_exec_path, char *ret_path)
 
bool get_home_path (char *ret_path)
 
void get_parent_directory (char *path)
 
char ** pgfnames (const char *path)
 
void pgfnames_cleanup (char **filenames)
 
void set_pglocale_pgservice (const char *argv0, const char *app)
 
int validate_exec (const char *path)
 
int find_my_exec (const char *argv0, char *retpath)
 
int find_other_exec (const char *argv0, const char *target, const char *versionstr, char *retpath)
 
char * pipe_read_line (char *cmd)
 
void pg_usleep (long microsec)
 
int pg_strcasecmp (const char *s1, const char *s2)
 
int pg_strncasecmp (const char *s1, const char *s2, size_t n)
 
unsigned char pg_toupper (unsigned char ch)
 
unsigned char pg_tolower (unsigned char ch)
 
unsigned char pg_ascii_toupper (unsigned char ch)
 
unsigned char pg_ascii_tolower (unsigned char ch)
 
int pg_vsnprintf (char *str, size_t count, const char *fmt, va_list args) pg_attribute_printf(3
 
int int pg_snprintf (char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
 
int int int pg_vsprintf (char *str, const char *fmt, va_list args) pg_attribute_printf(2
 
int int int int pg_sprintf (char *str, const char *fmt,...) pg_attribute_printf(2
 
int int int int int pg_vfprintf (FILE *stream, const char *fmt, va_list args) pg_attribute_printf(2
 
int int int int int int pg_fprintf (FILE *stream, const char *fmt,...) pg_attribute_printf(2
 
int int int int int int int pg_vprintf (const char *fmt, va_list args) pg_attribute_printf(1
 
int int int int int int int int pg_printf (const char *fmt,...) pg_attribute_printf(1
 
int pg_strfromd (char *str, size_t count, int precision, double value)
 
char * pg_strerror (int errnum)
 
char * pg_strerror_r (int errnum, char *buf, size_t buflen)
 
const char * pg_strsignal (int signum)
 
int pclose_check (FILE *stream)
 
bool rmtree (const char *path, bool rmtopdir)
 
int getpeereid (int sock, uid_t *uid, gid_t *gid)
 
void explicit_bzero (void *buf, size_t len)
 
char * mkdtemp (char *path)
 
int inet_aton (const char *cp, struct in_addr *addr)
 
size_t strlcat (char *dst, const char *src, size_t siz)
 
size_t strlcpy (char *dst, const char *src, size_t siz)
 
size_t strnlen (const char *str, size_t maxlen)
 
bool pg_get_user_name (uid_t user_id, char *buffer, size_t buflen)
 
bool pg_get_user_home_dir (uid_t user_id, char *buffer, size_t buflen)
 
void pg_qsort (void *base, size_t nel, size_t elsize, int(*cmp)(const void *, const void *))
 
int pg_qsort_strcmp (const void *a, const void *b)
 
void qsort_arg (void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
 
void qsort_interruptible (void *base, size_t nel, size_t elsize, qsort_arg_comparator cmp, void *arg)
 
void * bsearch_arg (const void *key, const void *base0, size_t nmemb, size_t size, int(*compar)(const void *, const void *, void *), void *arg)
 
int pg_get_encoding_from_locale (const char *ctype, bool write_message)
 
char * pg_inet_net_ntop (int af, const void *src, int bits, char *dst, size_t size)
 
void pg_strong_random_init (void)
 
bool pg_strong_random (void *buf, size_t len)
 
int pg_check_dir (const char *dir)
 
int pg_mkdir_p (char *path, int omode)
 
pqsigfunc pqsignal (int signo, pqsigfunc func)
 
char * escape_single_quotes_ascii (const char *src)
 
char * wait_result_to_str (int exitstatus)
 
bool wait_result_is_signal (int exit_status, int signum)
 
bool wait_result_is_any_signal (int exit_status, bool include_command_not_found)
 
int wait_result_to_exit_code (int exit_status)
 

Macro Definition Documentation

◆ ALL_CONNECTION_FAILURE_ERRNOS

#define ALL_CONNECTION_FAILURE_ERRNOS
Value:
EPIPE: \
case ECONNRESET: \
case ECONNABORTED: \
case EHOSTDOWN: \
case EHOSTUNREACH: \
case ENETDOWN: \
case ENETRESET: \
case ENETUNREACH: \
case ETIMEDOUT
#define ENETUNREACH
Definition: win32_port.h:412
#define ECONNABORTED
Definition: win32_port.h:382
#define EHOSTUNREACH
Definition: win32_port.h:406
#define ETIMEDOUT
Definition: win32_port.h:416
#define ENETRESET
Definition: win32_port.h:410
#define EHOSTDOWN
Definition: win32_port.h:404
#define ENETDOWN
Definition: win32_port.h:408
#define ECONNRESET
Definition: win32_port.h:384

Definition at line 121 of file port.h.

◆ closesocket

#define closesocket   close

Definition at line 349 of file port.h.

◆ DEVNULL

#define DEVNULL   "/dev/null"

Definition at line 160 of file port.h.

◆ EXE

#define EXE   ""

Definition at line 154 of file port.h.

◆ fprintf

#define fprintf   pg_fprintf

Definition at line 242 of file port.h.

◆ HAVE_GETRLIMIT

#define HAVE_GETRLIMIT   1

Definition at line 515 of file port.h.

◆ HAVE_POLL

#define HAVE_POLL   1

Definition at line 516 of file port.h.

◆ HAVE_POLL_H

#define HAVE_POLL_H   1

Definition at line 517 of file port.h.

◆ HAVE_READLINK

#define HAVE_READLINK   1

Definition at line 518 of file port.h.

◆ HAVE_SETSID

#define HAVE_SETSID   1

Definition at line 519 of file port.h.

◆ HAVE_SHM_OPEN

#define HAVE_SHM_OPEN   1

Definition at line 520 of file port.h.

◆ HAVE_SYMLINK

#define HAVE_SYMLINK   1

Definition at line 521 of file port.h.

◆ is_absolute_path

#define is_absolute_path (   filename)    is_nonwindows_absolute_path(filename)

Definition at line 103 of file port.h.

◆ IS_DIR_SEP

#define IS_DIR_SEP (   ch)    IS_NONWINDOWS_DIR_SEP(ch)

Definition at line 102 of file port.h.

◆ is_nonwindows_absolute_path

#define is_nonwindows_absolute_path (   filename)
Value:
( \
IS_NONWINDOWS_DIR_SEP((filename)[0]) \
)
static char * filename
Definition: pg_dumpall.c:121

Definition at line 82 of file port.h.

◆ IS_NONWINDOWS_DIR_SEP

#define IS_NONWINDOWS_DIR_SEP (   ch)    ((ch) == '/')

Definition at line 81 of file port.h.

◆ is_windows_absolute_path

#define is_windows_absolute_path (   filename)
Value:
( \
IS_WINDOWS_DIR_SEP((filename)[0]) || \
(isalpha((unsigned char) ((filename)[0])) && (filename)[1] == ':' && \
)
#define IS_WINDOWS_DIR_SEP(ch)
Definition: port.h:87

Definition at line 89 of file port.h.

◆ IS_WINDOWS_DIR_SEP

#define IS_WINDOWS_DIR_SEP (   ch)    ((ch) == '/' || (ch) == '\\')

Definition at line 87 of file port.h.

◆ pg_backend_random

#define pg_backend_random   pg_strong_random

Definition at line 483 of file port.h.

◆ PG_BACKEND_VERSIONSTR

#define PG_BACKEND_VERSIONSTR   "postgres (PostgreSQL) " PG_VERSION "\n"

Definition at line 143 of file port.h.

◆ PG_IOLBF

#define PG_IOLBF   _IOLBF

Definition at line 361 of file port.h.

◆ pg_pread

#define pg_pread   pread

Definition at line 225 of file port.h.

◆ pg_pwrite

#define pg_pwrite   pwrite

Definition at line 226 of file port.h.

◆ PG_STRERROR_R_BUFLEN

#define PG_STRERROR_R_BUFLEN   256 /* Recommended buffer size for strerror_r */

Definition at line 256 of file port.h.

◆ PGINVALID_SOCKET

#define PGINVALID_SOCKET   (-1)

Definition at line 31 of file port.h.

◆ pgoff_t

#define pgoff_t   off_t

Definition at line 373 of file port.h.

◆ printf

#define printf (   ...)    pg_printf(__VA_ARGS__)

Definition at line 244 of file port.h.

◆ qsort

#define qsort (   a,
  b,
  c,
 
)    pg_qsort(a,b,c,d)

Definition at line 449 of file port.h.

◆ snprintf

#define snprintf   pg_snprintf

Definition at line 238 of file port.h.

◆ sprintf

#define sprintf   pg_sprintf

Definition at line 240 of file port.h.

◆ strerror

#define strerror   pg_strerror

Definition at line 251 of file port.h.

◆ strerror_r

#define strerror_r   pg_strerror_r

Definition at line 255 of file port.h.

◆ TIMEZONE_GLOBAL

#define TIMEZONE_GLOBAL   timezone

Definition at line 268 of file port.h.

◆ TZNAME_GLOBAL

#define TZNAME_GLOBAL   tzname

Definition at line 269 of file port.h.

◆ USE_REPL_SNPRINTF

#define USE_REPL_SNPRINTF   1

Definition at line 179 of file port.h.

◆ vfprintf

#define vfprintf   pg_vfprintf

Definition at line 241 of file port.h.

◆ vprintf

#define vprintf   pg_vprintf

Definition at line 243 of file port.h.

◆ vsnprintf

#define vsnprintf   pg_vsnprintf

Definition at line 237 of file port.h.

◆ vsprintf

#define vsprintf   pg_vsprintf

Definition at line 239 of file port.h.

Typedef Documentation

◆ pgsocket

typedef int pgsocket

Definition at line 29 of file port.h.

◆ pqsigfunc

typedef void(* pqsigfunc) (SIGNAL_ARGS)

Definition at line 492 of file port.h.

◆ qsort_arg_comparator

typedef int(* qsort_arg_comparator) (const void *a, const void *b, void *arg)

Definition at line 451 of file port.h.

◆ socklen_t

typedef unsigned int socklen_t

Definition at line 40 of file port.h.

Function Documentation

◆ bsearch_arg()

void* bsearch_arg ( const void *  key,
const void *  base0,
size_t  nmemb,
size_t  size,
int(*)(const void *, const void *, void *)  compar,
void *  arg 
)

Definition at line 55 of file bsearch_arg.c.

59 {
60  const char *base = (const char *) base0;
61  int lim,
62  cmp;
63  const void *p;
64 
65  for (lim = nmemb; lim != 0; lim >>= 1)
66  {
67  p = base + (lim >> 1) * size;
68  cmp = (*compar) (key, p, arg);
69  if (cmp == 0)
70  return (void *) p;
71  if (cmp > 0)
72  { /* key > p: move right */
73  base = (const char *) p + size;
74  lim--;
75  } /* else move left */
76  }
77  return (NULL);
78 }
void * arg
static int cmp(const chr *x, const chr *y, size_t len)
Definition: regc_locale.c:743
static pg_noinline void Size size
Definition: slab.c:607

References arg, cmp(), sort-test::key, and size.

Referenced by AssertCheckRanges(), range_contains_value(), statext_mcv_build(), and statext_mcv_serialize().

◆ canonicalize_path()

void canonicalize_path ( char *  path)

Definition at line 264 of file path.c.

265 {
266  char *p,
267  *to_p;
268  char *spath;
269  char *parsed;
270  char *unparse;
271  bool was_sep = false;
273  int pathdepth = 0; /* counts collected regular directory names */
274 
275 #ifdef WIN32
276 
277  /*
278  * The Windows command processor will accept suitably quoted paths with
279  * forward slashes, but barfs badly with mixed forward and back slashes.
280  */
281  for (p = path; *p; p++)
282  {
283  if (*p == '\\')
284  *p = '/';
285  }
286 
287  /*
288  * In Win32, if you do: prog.exe "a b" "\c\d\" the system will pass \c\d"
289  * as argv[2], so trim off trailing quote.
290  */
291  if (p > path && *(p - 1) == '"')
292  *(p - 1) = '/';
293 #endif
294 
295  /*
296  * Removing the trailing slash on a path means we never get ugly double
297  * trailing slashes. Also, Win32 can't stat() a directory with a trailing
298  * slash. Don't remove a leading slash, though.
299  */
301 
302  /*
303  * Remove duplicate adjacent separators
304  */
305  p = path;
306 #ifdef WIN32
307  /* Don't remove leading double-slash on Win32 */
308  if (*p)
309  p++;
310 #endif
311  to_p = p;
312  for (; *p; p++, to_p++)
313  {
314  /* Handle many adjacent slashes, like "/a///b" */
315  while (*p == '/' && was_sep)
316  p++;
317  if (to_p != p)
318  *to_p = *p;
319  was_sep = (*p == '/');
320  }
321  *to_p = '\0';
322 
323  /*
324  * Remove any uses of "." and process ".." ourselves
325  *
326  * Note that "/../.." should reduce to just "/", while "../.." has to be
327  * kept as-is. Also note that we want a Windows drive spec to be visible
328  * to trim_directory(), but it's not part of the logic that's looking at
329  * the name components; hence distinction between path and spath.
330  *
331  * This loop overwrites the path in-place. This is safe since we'll never
332  * make the path longer. "unparse" points to where we are reading the
333  * path, "parse" to where we are writing.
334  */
335  spath = skip_drive(path);
336  if (*spath == '\0')
337  return; /* empty path is returned as-is */
338 
339  if (*spath == '/')
340  {
342  /* Skip the leading slash for absolute path */
343  parsed = unparse = (spath + 1);
344  }
345  else
346  {
348  parsed = unparse = spath;
349  }
350 
351  while (*unparse != '\0')
352  {
353  char *unparse_next;
354  bool is_double_dot;
355 
356  /* Split off this dir name, and set unparse_next to the next one */
357  unparse_next = unparse;
358  while (*unparse_next && *unparse_next != '/')
359  unparse_next++;
360  if (*unparse_next != '\0')
361  *unparse_next++ = '\0';
362 
363  /* Identify type of this dir name */
364  if (strcmp(unparse, ".") == 0)
365  {
366  /* We can ignore "." components in all cases */
367  unparse = unparse_next;
368  continue;
369  }
370 
371  if (strcmp(unparse, "..") == 0)
372  is_double_dot = true;
373  else
374  {
375  /* adjacent separators were eliminated above */
376  Assert(*unparse != '\0');
377  is_double_dot = false;
378  }
379 
380  switch (state)
381  {
382  case ABSOLUTE_PATH_INIT:
383  /* We can ignore ".." immediately after / */
384  if (!is_double_dot)
385  {
386  /* Append first dir name (we already have leading slash) */
387  parsed = append_subdir_to_path(parsed, unparse);
389  pathdepth++;
390  }
391  break;
393  if (is_double_dot)
394  {
395  /* Remove last parsed dir */
396  /* (trim_directory won't remove the leading slash) */
397  *parsed = '\0';
398  parsed = trim_directory(path);
399  if (--pathdepth == 0)
401  }
402  else
403  {
404  /* Append normal dir */
405  *parsed++ = '/';
406  parsed = append_subdir_to_path(parsed, unparse);
407  pathdepth++;
408  }
409  break;
410  case RELATIVE_PATH_INIT:
411  if (is_double_dot)
412  {
413  /* Append irreducible double-dot (..) */
414  parsed = append_subdir_to_path(parsed, unparse);
416  }
417  else
418  {
419  /* Append normal dir */
420  parsed = append_subdir_to_path(parsed, unparse);
422  pathdepth++;
423  }
424  break;
426  if (is_double_dot)
427  {
428  /* Remove last parsed dir */
429  *parsed = '\0';
430  parsed = trim_directory(path);
431  if (--pathdepth == 0)
432  {
433  /*
434  * If the output path is now empty, we're back to the
435  * INIT state. However, we could have processed a
436  * path like "../dir/.." and now be down to "..", in
437  * which case enter the correct state for that.
438  */
439  if (parsed == spath)
441  else
443  }
444  }
445  else
446  {
447  /* Append normal dir */
448  *parsed++ = '/';
449  parsed = append_subdir_to_path(parsed, unparse);
450  pathdepth++;
451  }
452  break;
454  if (is_double_dot)
455  {
456  /* Append next irreducible double-dot (..) */
457  *parsed++ = '/';
458  parsed = append_subdir_to_path(parsed, unparse);
459  }
460  else
461  {
462  /* Append normal dir */
463  *parsed++ = '/';
464  parsed = append_subdir_to_path(parsed, unparse);
465 
466  /*
467  * We can now start counting normal dirs. But if later
468  * double-dots make us remove this dir again, we'd better
469  * revert to RELATIVE_WITH_PARENT_REF not INIT state.
470  */
472  pathdepth = 1;
473  }
474  break;
475  }
476 
477  unparse = unparse_next;
478  }
479 
480  /*
481  * If our output path is empty at this point, insert ".". We don't want
482  * to do this any earlier because it'd result in an extra dot in corner
483  * cases such as "../dir/..". Since we rejected the wholly-empty-path
484  * case above, there is certainly room.
485  */
486  if (parsed == spath)
487  *parsed++ = '.';
488 
489  /* And finally, ensure the output path is nul-terminated. */
490  *parsed = '\0';
491 }
Assert(fmt[strlen(fmt) - 1] !='\n')
static char * append_subdir_to_path(char *path, char *subdir)
Definition: path.c:1047
static void trim_trailing_separator(char *path)
Definition: path.c:1025
static char * trim_directory(char *path)
Definition: path.c:993
#define skip_drive(path)
Definition: path.c:79
canonicalize_state
Definition: path.c:243
@ ABSOLUTE_WITH_N_DEPTH
Definition: path.c:246
@ RELATIVE_WITH_N_DEPTH
Definition: path.c:249
@ ABSOLUTE_PATH_INIT
Definition: path.c:244
@ RELATIVE_PATH_INIT
Definition: path.c:248
@ RELATIVE_WITH_PARENT_REF
Definition: path.c:251
Definition: regguts.h:323

References ABSOLUTE_PATH_INIT, ABSOLUTE_WITH_N_DEPTH, append_subdir_to_path(), Assert(), RELATIVE_PATH_INIT, RELATIVE_WITH_N_DEPTH, RELATIVE_WITH_PARENT_REF, skip_drive, trim_directory(), and trim_trailing_separator().

Referenced by AbsoluteConfigLocation(), add_tablespace_mapping(), adjust_data_dir(), check_canonical_path(), check_required_directory(), convert_and_check_filename(), create_script_for_old_cluster_deletion(), create_xlog_or_symlink(), CreateTableSpace(), do_copy(), exec_command_edit(), exec_command_write(), find_in_dynamic_libpath(), find_my_exec(), find_other_exec(), get_tablespace_mapping(), GetConfFilesInDir(), main(), make_absolute_path(), make_relative_path(), normalize_exec_path(), parseCommandLine(), process_file(), scan_for_existing_tablespaces(), setup(), setup_bin_paths(), setup_pgdata(), SplitDirectoriesString(), tablespace_list_append(), and test_canonicalize_path().

◆ cleanup_path()

void cleanup_path ( char *  path)

Definition at line 186 of file path.c.

187 {
188 #ifdef WIN32
189  char *ptr;
190 
191  /*
192  * GetShortPathName() will fail if the path does not exist, or short names
193  * are disabled on this file system. In both cases, we just return the
194  * original path. This is particularly useful for --sysconfdir, which
195  * might not exist.
196  */
197  GetShortPathName(path, path, MAXPGPATH - 1);
198 
199  /* Replace '\' with '/' */
200  for (ptr = path; *ptr; ptr++)
201  {
202  if (*ptr == '\\')
203  *ptr = '/';
204  }
205 #endif
206 }
#define MAXPGPATH

References MAXPGPATH.

Referenced by get_configdata().

◆ escape_single_quotes_ascii()

char* escape_single_quotes_ascii ( const char *  src)

Definition at line 33 of file quotes.c.

34 {
35  int len = strlen(src),
36  i,
37  j;
38  char *result = malloc(len * 2 + 1);
39 
40  if (!result)
41  return NULL;
42 
43  for (i = 0, j = 0; i < len; i++)
44  {
45  if (SQL_STR_DOUBLE(src[i], true))
46  result[j++] = src[i];
47  result[j++] = src[i];
48  }
49  result[j] = '\0';
50  return result;
51 }
#define SQL_STR_DOUBLE(ch, escape_backslash)
Definition: c.h:1150
#define malloc(a)
Definition: header.h:50
int j
Definition: isn.c:74
int i
Definition: isn.c:73
const void size_t len

References i, j, len, malloc, and SQL_STR_DOUBLE.

Referenced by escape_quotes(), and write_auto_conf_file().

◆ explicit_bzero()

void explicit_bzero ( void *  buf,
size_t  len 
)

Definition at line 50 of file explicit_bzero.c.

51 {
52  bzero_p(buf, len);
53 }
static void(*volatile bzero_p)(void *, size_t)
static char * buf
Definition: pg_test_fsync.c:73

References buf, bzero_p, and len.

Referenced by freePGconn(), passwordFromFile(), pg_cryptohash_create(), pg_cryptohash_free(), pg_hmac_create(), pg_hmac_free(), pqReleaseConnHosts(), and run_ssl_passphrase_command().

◆ find_my_exec()

int find_my_exec ( const char *  argv0,
char *  retpath 
)

Definition at line 160 of file exec.c.

161 {
162  char *path;
163 
164  /*
165  * If argv0 contains a separator, then PATH wasn't used.
166  */
167  strlcpy(retpath, argv0, MAXPGPATH);
168  if (first_dir_separator(retpath) != NULL)
169  {
170  if (validate_exec(retpath) == 0)
171  return normalize_exec_path(retpath);
172 
173  log_error(errcode(ERRCODE_WRONG_OBJECT_TYPE),
174  _("invalid binary \"%s\": %m"), retpath);
175  return -1;
176  }
177 
178 #ifdef WIN32
179  /* Win32 checks the current directory first for names without slashes */
180  if (validate_exec(retpath) == 0)
181  return normalize_exec_path(retpath);
182 #endif
183 
184  /*
185  * Since no explicit path was supplied, the user must have been relying on
186  * PATH. We'll search the same PATH.
187  */
188  if ((path = getenv("PATH")) && *path)
189  {
190  char *startp = NULL,
191  *endp = NULL;
192 
193  do
194  {
195  if (!startp)
196  startp = path;
197  else
198  startp = endp + 1;
199 
200  endp = first_path_var_separator(startp);
201  if (!endp)
202  endp = startp + strlen(startp); /* point to end */
203 
204  strlcpy(retpath, startp, Min(endp - startp + 1, MAXPGPATH));
205 
206  join_path_components(retpath, retpath, argv0);
207  canonicalize_path(retpath);
208 
209  switch (validate_exec(retpath))
210  {
211  case 0: /* found ok */
212  return normalize_exec_path(retpath);
213  case -1: /* wasn't even a candidate, keep looking */
214  break;
215  case -2: /* found but disqualified */
216  log_error(errcode(ERRCODE_WRONG_OBJECT_TYPE),
217  _("could not read binary \"%s\": %m"),
218  retpath);
219  break;
220  }
221  } while (*endp);
222  }
223 
224  log_error(errcode(ERRCODE_UNDEFINED_FILE),
225  _("could not find a \"%s\" to execute"), argv0);
226  return -1;
227 }
#define Min(x, y)
Definition: c.h:991
#define log_error(errcodefn,...)
Definition: exec.c:65
int validate_exec(const char *path)
Definition: exec.c:88
static int normalize_exec_path(char *path)
Definition: exec.c:241
int errcode(int sqlerrcode)
Definition: elog.c:859
#define _(x)
Definition: elog.c:90
static char * argv0
Definition: pg_ctl.c:92
void join_path_components(char *ret_path, const char *head, const char *tail)
Definition: path.c:219
char * first_dir_separator(const char *filename)
Definition: path.c:104
void canonicalize_path(char *path)
Definition: path.c:264
char * first_path_var_separator(const char *pathlist)
Definition: path.c:121
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45

References _, argv0, canonicalize_path(), errcode(), first_dir_separator(), first_path_var_separator(), join_path_components(), log_error, MAXPGPATH, Min, normalize_exec_path(), strlcpy(), and validate_exec().

Referenced by ensureCleanShutdown(), find_other_exec(), find_other_exec_or_die(), getInstallationPaths(), getRestoreCommand(), InitStandaloneProcess(), main(), process_psqlrc(), set_pglocale_pgservice(), setup(), and setup_bin_paths().

◆ find_other_exec()

int find_other_exec ( const char *  argv0,
const char *  target,
const char *  versionstr,
char *  retpath 
)

Definition at line 329 of file exec.c.

331 {
332  char cmd[MAXPGPATH];
333  char *line;
334 
335  if (find_my_exec(argv0, retpath) < 0)
336  return -1;
337 
338  /* Trim off program name and keep just directory */
339  *last_dir_separator(retpath) = '\0';
340  canonicalize_path(retpath);
341 
342  /* Now append the other program's name */
343  snprintf(retpath + strlen(retpath), MAXPGPATH - strlen(retpath),
344  "/%s%s", target, EXE);
345 
346  if (validate_exec(retpath) != 0)
347  return -1;
348 
349  snprintf(cmd, sizeof(cmd), "\"%s\" -V", retpath);
350 
351  if ((line = pipe_read_line(cmd)) == NULL)
352  return -1;
353 
354  if (strcmp(line, versionstr) != 0)
355  {
356  pfree(line);
357  return -2;
358  }
359 
360  pfree(line);
361  return 0;
362 }
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:160
char * pipe_read_line(char *cmd)
Definition: exec.c:371
void pfree(void *pointer)
Definition: mcxt.c:1508
char * last_dir_separator(const char *filename)
Definition: path.c:139
#define snprintf
Definition: port.h:238
#define EXE
Definition: port.h:154

References argv0, canonicalize_path(), EXE, find_my_exec(), last_dir_separator(), MAXPGPATH, pfree(), pipe_read_line(), snprintf, and validate_exec().

Referenced by ensureCleanShutdown(), find_other_exec_or_die(), getInstallationPaths(), getRestoreCommand(), isolation_start_test(), main(), and setup_bin_paths().

◆ first_dir_separator()

char* first_dir_separator ( const char *  filename)

Definition at line 104 of file path.c.

105 {
106  const char *p;
107 
108  for (p = skip_drive(filename); *p; p++)
109  if (IS_DIR_SEP(*p))
110  return unconstify(char *, p);
111  return NULL;
112 }
#define unconstify(underlying_type, expr)
Definition: c.h:1232
#define IS_DIR_SEP(ch)
Definition: port.h:102

References filename, IS_DIR_SEP, skip_drive, and unconstify.

Referenced by check_restricted_library_name(), check_valid_extension_name(), check_valid_version_name(), expand_dynamic_library_name(), find_in_dynamic_libpath(), find_my_exec(), load_libraries(), and substitute_libpath_macro().

◆ first_path_var_separator()

char* first_path_var_separator ( const char *  pathlist)

Definition at line 121 of file path.c.

122 {
123  const char *p;
124 
125  /* skip_drive is not needed */
126  for (p = pathlist; *p; p++)
127  if (IS_PATH_VAR_SEP(*p))
128  return unconstify(char *, p);
129  return NULL;
130 }
#define IS_PATH_VAR_SEP(ch)
Definition: path.c:42

References IS_PATH_VAR_SEP, and unconstify.

Referenced by find_in_dynamic_libpath(), and find_my_exec().

◆ get_doc_path()

void get_doc_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 896 of file path.c.

897 {
898  make_relative_path(ret_path, DOCDIR, PGBINDIR, my_exec_path);
899 }
char my_exec_path[MAXPGPATH]
Definition: globals.c:78
static void make_relative_path(char *ret_path, const char *target_path, const char *bin_path, const char *my_exec_path)
Definition: path.c:660

References make_relative_path(), and my_exec_path.

Referenced by get_configdata().

◆ get_etc_path()

void get_etc_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 833 of file path.c.

834 {
835  make_relative_path(ret_path, SYSCONFDIR, PGBINDIR, my_exec_path);
836 }

References make_relative_path(), and my_exec_path.

Referenced by get_configdata(), process_psqlrc(), and set_pglocale_pgservice().

◆ get_home_path()

bool get_home_path ( char *  ret_path)

Definition at line 927 of file path.c.

928 {
929 #ifndef WIN32
930  /*
931  * We first consult $HOME. If that's unset, try to get the info from
932  * <pwd.h>.
933  */
934  const char *home;
935 
936  home = getenv("HOME");
937  if (home == NULL || home[0] == '\0')
938  return pg_get_user_home_dir(geteuid(), ret_path, MAXPGPATH);
939  strlcpy(ret_path, home, MAXPGPATH);
940  return true;
941 #else
942  char *tmppath;
943 
944  /*
945  * Note: We use getenv() here because the more modern SHGetFolderPath()
946  * would force the backend to link with shell32.lib, which eats valuable
947  * desktop heap. XXX This function is used only in psql, which already
948  * brings in shell32 via libpq. Moving this function to its own file
949  * would keep it out of the backend, freeing it from this concern.
950  */
951  tmppath = getenv("APPDATA");
952  if (!tmppath)
953  return false;
954  snprintf(ret_path, MAXPGPATH, "%s/postgresql", tmppath);
955  return true;
956 #endif
957 }
bool pg_get_user_home_dir(uid_t user_id, char *buffer, size_t buflen)
Definition: user.c:64

References MAXPGPATH, pg_get_user_home_dir(), snprintf, and strlcpy().

Referenced by expand_tilde(), initializeInput(), and process_psqlrc().

◆ get_html_path()

void get_html_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 905 of file path.c.

906 {
907  make_relative_path(ret_path, HTMLDIR, PGBINDIR, my_exec_path);
908 }

References make_relative_path(), and my_exec_path.

Referenced by get_configdata().

◆ get_include_path()

void get_include_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 842 of file path.c.

843 {
844  make_relative_path(ret_path, INCLUDEDIR, PGBINDIR, my_exec_path);
845 }

References make_relative_path(), and my_exec_path.

Referenced by get_configdata(), and main().

◆ get_includeserver_path()

void get_includeserver_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 860 of file path.c.

861 {
862  make_relative_path(ret_path, INCLUDEDIRSERVER, PGBINDIR, my_exec_path);
863 }

References make_relative_path(), and my_exec_path.

Referenced by get_configdata().

◆ get_lib_path()

void get_lib_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 869 of file path.c.

870 {
871  make_relative_path(ret_path, LIBDIR, PGBINDIR, my_exec_path);
872 }

References make_relative_path(), and my_exec_path.

Referenced by get_configdata().

◆ get_locale_path()

void get_locale_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 887 of file path.c.

888 {
889  make_relative_path(ret_path, LOCALEDIR, PGBINDIR, my_exec_path);
890 }

References make_relative_path(), and my_exec_path.

Referenced by get_configdata(), pg_bindtextdomain(), and set_pglocale_pgservice().

◆ get_man_path()

void get_man_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 914 of file path.c.

915 {
916  make_relative_path(ret_path, MANDIR, PGBINDIR, my_exec_path);
917 }

References make_relative_path(), and my_exec_path.

Referenced by get_configdata().

◆ get_parent_directory()

void get_parent_directory ( char *  path)

Definition at line 976 of file path.c.

977 {
978  trim_directory(path);
979 }

References trim_directory().

Referenced by AbsoluteConfigLocation(), dbase_redo(), destroy_tablespace_directories(), fsync_parent_path(), main(), and process_file().

◆ get_pkginclude_path()

void get_pkginclude_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 851 of file path.c.

852 {
853  make_relative_path(ret_path, PKGINCLUDEDIR, PGBINDIR, my_exec_path);
854 }

References make_relative_path(), and my_exec_path.

Referenced by get_configdata(), and main().

◆ get_pkglib_path()

void get_pkglib_path ( const char *  my_exec_path,
char *  ret_path 
)

Definition at line 878 of file path.c.

879 {
880  make_relative_path(ret_path, PKGLIBDIR, PGBINDIR, my_exec_path);
881 }

References make_relative_path(), and my_exec_path.

Referenced by get_configdata(), getInstallationPaths(), and InitStandaloneProcess().

◆ get_progname()

const char* get_progname ( const char *  argv0)

Definition at line 574 of file path.c.

575 {
576  const char *nodir_name;
577  char *progname;
578 
579  nodir_name = last_dir_separator(argv0);
580  if (nodir_name)
581  nodir_name++;
582  else
583  nodir_name = skip_drive(argv0);
584 
585  /*
586  * Make a copy in case argv[0] is modified by ps_status. Leaks memory, but
587  * called only once.
588  */
589  progname = strdup(nodir_name);
590  if (progname == NULL)
591  {
592  fprintf(stderr, "%s: out of memory\n", nodir_name);
593  abort(); /* This could exit the postmaster */
594  }
595 
596 #if defined(__CYGWIN__) || defined(WIN32)
597  /* strip ".exe" suffix, regardless of case */
598  if (strlen(progname) > sizeof(EXE) - 1 &&
599  pg_strcasecmp(progname + strlen(progname) - (sizeof(EXE) - 1), EXE) == 0)
600  progname[strlen(progname) - (sizeof(EXE) - 1)] = '\0';
601 #endif
602 
603  return progname;
604 }
const char * progname
Definition: main.c:44
char * last_dir_separator(const char *filename)
Definition: path.c:139
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define fprintf
Definition: port.h:242

References argv0, EXE, fprintf, last_dir_separator(), pg_strcasecmp(), progname, and skip_drive.

Referenced by get_opts(), handle_help_version_opts(), main(), parseCommandLine(), pg_logging_init(), and regression_main().

◆ get_share_path()

void get_share_path ( const char *  my_exec_path,
char *  ret_path 
)

◆ getpeereid()

int getpeereid ( int  sock,
uid_t uid,
gid_t gid 
)

Definition at line 33 of file getpeereid.c.

34 {
35 #if defined(SO_PEERCRED)
36  /* Linux: use getsockopt(SO_PEERCRED) */
37  struct ucred peercred;
38  socklen_t so_len = sizeof(peercred);
39 
40  if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &peercred, &so_len) != 0 ||
41  so_len != sizeof(peercred))
42  return -1;
43  *uid = peercred.uid;
44  *gid = peercred.gid;
45  return 0;
46 #elif defined(LOCAL_PEERCRED)
47  /* Debian with FreeBSD kernel: use getsockopt(LOCAL_PEERCRED) */
48  struct xucred peercred;
49  socklen_t so_len = sizeof(peercred);
50 
51  if (getsockopt(sock, 0, LOCAL_PEERCRED, &peercred, &so_len) != 0 ||
52  so_len != sizeof(peercred) ||
53  peercred.cr_version != XUCRED_VERSION)
54  return -1;
55  *uid = peercred.cr_uid;
56  *gid = peercred.cr_gid;
57  return 0;
58 #elif defined(HAVE_GETPEERUCRED)
59  /* Solaris: use getpeerucred() */
60  ucred_t *ucred;
61 
62  ucred = NULL; /* must be initialized to NULL */
63  if (getpeerucred(sock, &ucred) == -1)
64  return -1;
65 
66  *uid = ucred_geteuid(ucred);
67  *gid = ucred_getegid(ucred);
68  ucred_free(ucred);
69 
70  if (*uid == (uid_t) (-1) || *gid == (gid_t) (-1))
71  return -1;
72  return 0;
73 #else
74  /* No implementation available on this platform */
75  errno = ENOSYS;
76  return -1;
77 #endif
78 }
unsigned int socklen_t
Definition: port.h:40
int gid_t
Definition: win32_port.h:245
int uid_t
Definition: win32_port.h:244

Referenced by auth_peer(), and PQconnectPoll().

◆ has_drive_prefix()

bool has_drive_prefix ( const char *  path)

Definition at line 88 of file path.c.

89 {
90 #ifdef WIN32
91  return skip_drive(path) != path;
92 #else
93  return false;
94 #endif
95 }

References skip_drive.

Referenced by process_file().

◆ inet_aton()

int inet_aton ( const char *  cp,
struct in_addr *  addr 
)

Definition at line 56 of file inet_aton.c.

57 {
58  unsigned int val;
59  int base,
60  n;
61  char c;
62  u_int parts[4];
63  u_int *pp = parts;
64 
65  for (;;)
66  {
67  /*
68  * Collect number up to ``.''. Values are specified as for C: 0x=hex,
69  * 0=octal, other=decimal.
70  */
71  val = 0;
72  base = 10;
73  if (*cp == '0')
74  {
75  if (*++cp == 'x' || *cp == 'X')
76  base = 16, cp++;
77  else
78  base = 8;
79  }
80  while ((c = *cp) != '\0')
81  {
82  if (isdigit((unsigned char) c))
83  {
84  val = (val * base) + (c - '0');
85  cp++;
86  continue;
87  }
88  if (base == 16 && isxdigit((unsigned char) c))
89  {
90  val = (val << 4) +
91  (c + 10 - (islower((unsigned char) c) ? 'a' : 'A'));
92  cp++;
93  continue;
94  }
95  break;
96  }
97  if (*cp == '.')
98  {
99  /*
100  * Internet format: a.b.c.d a.b.c (with c treated as 16-bits)
101  * a.b (with b treated as 24 bits)
102  */
103  if (pp >= parts + 3 || val > 0xff)
104  return 0;
105  *pp++ = val, cp++;
106  }
107  else
108  break;
109  }
110 
111  /*
112  * Check for trailing junk.
113  */
114  while (*cp)
115  if (!isspace((unsigned char) *cp++))
116  return 0;
117 
118  /*
119  * Concoct the address according to the number of parts specified.
120  */
121  n = pp - parts + 1;
122  switch (n)
123  {
124 
125  case 1: /* a -- 32 bits */
126  break;
127 
128  case 2: /* a.b -- 8.24 bits */
129  if (val > 0xffffff)
130  return 0;
131  val |= parts[0] << 24;
132  break;
133 
134  case 3: /* a.b.c -- 8.8.16 bits */
135  if (val > 0xffff)
136  return 0;
137  val |= (parts[0] << 24) | (parts[1] << 16);
138  break;
139 
140  case 4: /* a.b.c.d -- 8.8.8.8 bits */
141  if (val > 0xff)
142  return 0;
143  val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
144  break;
145  }
146  if (addr)
147  addr->s_addr = pg_hton32(val);
148  return 1;
149 }
long val
Definition: informix.c:664
#define pg_hton32(x)
Definition: pg_bswap.h:121
char * c

References pg_hton32, and val.

Referenced by is_ip_address(), and pq_verify_peer_name_matches_certificate_ip().

◆ join_path_components()

void join_path_components ( char *  ret_path,
const char *  head,
const char *  tail 
)

Definition at line 219 of file path.c.

221 {
222  if (ret_path != head)
223  strlcpy(ret_path, head, MAXPGPATH);
224 
225  /*
226  * We used to try to simplify some cases involving "." and "..", but now
227  * we just leave that to be done by canonicalize_path() later.
228  */
229 
230  if (*tail)
231  {
232  /* only separate with slash if head wasn't empty */
233  snprintf(ret_path + strlen(ret_path), MAXPGPATH - strlen(ret_path),
234  "%s%s",
235  (*(skip_drive(head)) != '\0') ? "/" : "",
236  tail);
237  }
238 }

References MAXPGPATH, skip_drive, snprintf, and strlcpy().

Referenced by AbsoluteConfigLocation(), find_my_exec(), GetConfFilesInDir(), main(), make_relative_path(), and process_file().

◆ last_dir_separator()

char* last_dir_separator ( const char *  filename)

Definition at line 139 of file path.c.

140 {
141  const char *p,
142  *ret = NULL;
143 
144  for (p = skip_drive(filename); *p; p++)
145  if (IS_DIR_SEP(*p))
146  ret = p;
147  return unconstify(char *, ret);
148 }

References filename, IS_DIR_SEP, skip_drive, and unconstify.

Referenced by check_file_excluded(), ECPGconnect(), find_other_exec(), get_progname(), main(), sendDir(), setup(), setup_bin_paths(), and should_allow_existing_directory().

◆ make_absolute_path()

char* make_absolute_path ( const char *  path)

Definition at line 729 of file path.c.

730 {
731  char *new;
732 
733  /* Returning null for null input is convenient for some callers */
734  if (path == NULL)
735  return NULL;
736 
737  if (!is_absolute_path(path))
738  {
739  char *buf;
740  size_t buflen;
741 
742  buflen = MAXPGPATH;
743  for (;;)
744  {
745  buf = malloc(buflen);
746  if (!buf)
747  {
748 #ifndef FRONTEND
749  ereport(ERROR,
750  (errcode(ERRCODE_OUT_OF_MEMORY),
751  errmsg("out of memory")));
752 #else
753  fprintf(stderr, _("out of memory\n"));
754  return NULL;
755 #endif
756  }
757 
758  if (getcwd(buf, buflen))
759  break;
760  else if (errno == ERANGE)
761  {
762  free(buf);
763  buflen *= 2;
764  continue;
765  }
766  else
767  {
768  int save_errno = errno;
769 
770  free(buf);
771  errno = save_errno;
772 #ifndef FRONTEND
773  elog(ERROR, "could not get current working directory: %m");
774 #else
775  fprintf(stderr, _("could not get current working directory: %m\n"));
776  return NULL;
777 #endif
778  }
779  }
780 
781  new = malloc(strlen(buf) + strlen(path) + 2);
782  if (!new)
783  {
784  free(buf);
785 #ifndef FRONTEND
786  ereport(ERROR,
787  (errcode(ERRCODE_OUT_OF_MEMORY),
788  errmsg("out of memory")));
789 #else
790  fprintf(stderr, _("out of memory\n"));
791  return NULL;
792 #endif
793  }
794  sprintf(new, "%s/%s", buf, path);
795  free(buf);
796  }
797  else
798  {
799  new = strdup(path);
800  if (!new)
801  {
802 #ifndef FRONTEND
803  ereport(ERROR,
804  (errcode(ERRCODE_OUT_OF_MEMORY),
805  errmsg("out of memory")));
806 #else
807  fprintf(stderr, _("out of memory\n"));
808  return NULL;
809 #endif
810  }
811  }
812 
813  /* Make sure punctuation is canonical, too */
814  canonicalize_path(new);
815 
816  return new;
817 }
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:224
#define ereport(elevel,...)
Definition: elog.h:149
#define free(a)
Definition: header.h:65
void canonicalize_path(char *path)
Definition: path.c:264
#define is_absolute_path(filename)
Definition: port.h:103
#define sprintf
Definition: port.h:240

References _, buf, canonicalize_path(), elog, ereport, errcode(), errmsg(), ERROR, fprintf, free, is_absolute_path, malloc, MAXPGPATH, and sprintf.

Referenced by regression_main(), SelectConfigFiles(), and SetDataDir().

◆ make_native_path()

void make_native_path ( char *  filename)

Definition at line 167 of file path.c.

168 {
169 #ifdef WIN32
170  char *p;
171 
172  for (p = filename; *p; p++)
173  if (*p == '/')
174  *p = '\\';
175 #endif
176 }

References filename.

Referenced by BuildRestoreCommand(), main(), and shell_archive_file().

◆ mkdtemp()

char* mkdtemp ( char *  path)

Definition at line 286 of file mkdtemp.c.

287 {
288  _DIAGASSERT(path != NULL);
289 
290  return GETTEMP(path, NULL, 1) ? path : NULL;
291 }
static int GETTEMP(char *path, int *doopen, int domkdir)
Definition: mkdtemp.c:94
#define _DIAGASSERT(x)
Definition: mkdtemp.c:21

References _DIAGASSERT, and GETTEMP().

Referenced by make_temp_sockdir().

◆ path_contains_parent_reference()

bool path_contains_parent_reference ( const char *  path)

Definition at line 499 of file path.c.

500 {
501  /*
502  * Once canonicalized, an absolute path cannot contain any ".." at all,
503  * while a relative path could contain ".."(s) only at the start. So it
504  * is sufficient to check the start of the path, after skipping any
505  * Windows drive/network specifier.
506  */
507  path = skip_drive(path); /* C: shouldn't affect our conclusion */
508 
509  if (path[0] == '.' &&
510  path[1] == '.' &&
511  (path[2] == '\0' || path[2] == '/'))
512  return true;
513 
514  return false;
515 }

References skip_drive.

Referenced by path_is_relative_and_below_cwd().

◆ path_is_prefix_of_path()

bool path_is_prefix_of_path ( const char *  path1,
const char *  path2 
)

Definition at line 559 of file path.c.

560 {
561  int path1_len = strlen(path1);
562 
563  if (strncmp(path1, path2, path1_len) == 0 &&
564  (IS_DIR_SEP(path2[path1_len]) || path2[path1_len] == '\0'))
565  return true;
566  return false;
567 }

References IS_DIR_SEP.

Referenced by convert_and_check_filename(), create_script_for_old_cluster_deletion(), CreateTableSpace(), and parseCommandLine().

◆ path_is_relative_and_below_cwd()

bool path_is_relative_and_below_cwd ( const char *  path)

Definition at line 526 of file path.c.

527 {
528  if (is_absolute_path(path))
529  return false;
530  /* don't allow anything above the cwd */
531  else if (path_contains_parent_reference(path))
532  return false;
533 #ifdef WIN32
534 
535  /*
536  * On Win32, a drive letter _not_ followed by a slash, e.g. 'E:abc', is
537  * relative to the cwd on that drive, or the drive's root directory if
538  * that drive has no cwd. Because the path itself cannot tell us which is
539  * the case, we have to assume the worst, i.e. that it is not below the
540  * cwd. We could use GetFullPathName() to find the full path but that
541  * could change if the current directory for the drive changes underneath
542  * us, so we just disallow it.
543  */
544  else if (isalpha((unsigned char) path[0]) && path[1] == ':' &&
545  !IS_DIR_SEP(path[2]))
546  return false;
547 #endif
548  else
549  return true;
550 }
bool path_contains_parent_reference(const char *path)
Definition: path.c:499

References is_absolute_path, IS_DIR_SEP, and path_contains_parent_reference().

Referenced by convert_and_check_filename().

◆ pclose_check()

int pclose_check ( FILE *  stream)

Definition at line 410 of file exec.c.

411 {
412  int exitstatus;
413  char *reason;
414 
415  exitstatus = pclose(stream);
416 
417  if (exitstatus == 0)
418  return 0; /* all is well */
419 
420  if (exitstatus == -1)
421  {
422  /* pclose() itself failed, and hopefully set errno */
423  log_error(errcode(ERRCODE_SYSTEM_ERROR),
424  _("%s() failed: %m"), "pclose");
425  }
426  else
427  {
428  reason = wait_result_to_str(exitstatus);
429  log_error(errcode(ERRCODE_SYSTEM_ERROR),
430  "%s", reason);
431  pfree(reason);
432  }
433  return exitstatus;
434 }
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:33

References _, errcode(), log_error, pfree(), and wait_result_to_str().

Referenced by pipe_read_line().

◆ pg_ascii_tolower()

unsigned char pg_ascii_tolower ( unsigned char  ch)

Definition at line 146 of file pgstrcasecmp.c.

147 {
148  if (ch >= 'A' && ch <= 'Z')
149  ch += 'a' - 'A';
150  return ch;
151 }

Referenced by asc_initcap(), asc_tolower(), pg_wc_tolower(), SB_lower_char(), and seq_search_ascii().

◆ pg_ascii_toupper()

unsigned char pg_ascii_toupper ( unsigned char  ch)

Definition at line 135 of file pgstrcasecmp.c.

136 {
137  if (ch >= 'a' && ch <= 'z')
138  ch += 'A' - 'a';
139  return ch;
140 }

Referenced by asc_initcap(), asc_toupper(), filter_list_to_array(), and pg_wc_toupper().

◆ pg_check_dir()

int pg_check_dir ( const char *  dir)

Definition at line 33 of file pgcheckdir.c.

34 {
35  int result = 1;
36  DIR *chkdir;
37  struct dirent *file;
38  bool dot_found = false;
39  bool mount_found = false;
40  int readdir_errno;
41 
42  chkdir = opendir(dir);
43  if (chkdir == NULL)
44  return (errno == ENOENT) ? 0 : -1;
45 
46  while (errno = 0, (file = readdir(chkdir)) != NULL)
47  {
48  if (strcmp(".", file->d_name) == 0 ||
49  strcmp("..", file->d_name) == 0)
50  {
51  /* skip this and parent directory */
52  continue;
53  }
54 #ifndef WIN32
55  /* file starts with "." */
56  else if (file->d_name[0] == '.')
57  {
58  dot_found = true;
59  }
60  /* lost+found directory */
61  else if (strcmp("lost+found", file->d_name) == 0)
62  {
63  mount_found = true;
64  }
65 #endif
66  else
67  {
68  result = 4; /* not empty */
69  break;
70  }
71  }
72 
73  if (errno)
74  result = -1; /* some kind of I/O error? */
75 
76  /* Close chkdir and avoid overwriting the readdir errno on success */
77  readdir_errno = errno;
78  if (closedir(chkdir))
79  result = -1; /* error executing closedir */
80  else
81  errno = readdir_errno;
82 
83  /* We report on mount point if we find a lost+found directory */
84  if (result == 1 && mount_found)
85  result = 3;
86 
87  /* We report on dot-files if we _only_ find dot files */
88  if (result == 1 && dot_found)
89  result = 2;
90 
91  return result;
92 }
int closedir(DIR *)
Definition: dirent.c:127
struct dirent * readdir(DIR *)
Definition: dirent.c:78
DIR * opendir(const char *)
Definition: dirent.c:33
Definition: dirent.c:26
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15

References closedir(), dirent::d_name, opendir(), and readdir().

Referenced by bbsink_server_new(), cleanup_output_dirs(), create_data_directory(), create_fullpage_directory(), create_output_directory(), create_xlog_or_symlink(), main(), and verify_dir_is_empty_or_create().

◆ pg_fprintf()

int int int int int int pg_fprintf ( FILE *  stream,
const char *  fmt,
  ... 
)

◆ pg_get_encoding_from_locale()

int pg_get_encoding_from_locale ( const char *  ctype,
bool  write_message 
)

◆ pg_get_user_home_dir()

bool pg_get_user_home_dir ( uid_t  user_id,
char *  buffer,
size_t  buflen 
)

Definition at line 64 of file user.c.

65 {
66  char pwdbuf[BUFSIZ];
67  struct passwd pwdstr;
68  struct passwd *pw = NULL;
69  int pwerr;
70 
71  pwerr = getpwuid_r(user_id, &pwdstr, pwdbuf, sizeof(pwdbuf), &pw);
72  if (pw != NULL)
73  {
74  strlcpy(buffer, pw->pw_dir, buflen);
75  return true;
76  }
77  if (pwerr != 0)
78  snprintf(buffer, buflen,
79  _("could not look up local user ID %d: %s"),
80  (int) user_id,
81  strerror_r(pwerr, pwdbuf, sizeof(pwdbuf)));
82  else
83  snprintf(buffer, buflen,
84  _("local user with ID %d does not exist"),
85  (int) user_id);
86  return false;
87 }
#define strerror_r
Definition: port.h:255

References _, snprintf, strerror_r, and strlcpy().

Referenced by get_home_path(), and pqGetHomeDirectory().

◆ pg_get_user_name()

bool pg_get_user_name ( uid_t  user_id,
char *  buffer,
size_t  buflen 
)

Definition at line 28 of file user.c.

29 {
30  char pwdbuf[BUFSIZ];
31  struct passwd pwdstr;
32  struct passwd *pw = NULL;
33  int pwerr;
34 
35  pwerr = getpwuid_r(user_id, &pwdstr, pwdbuf, sizeof(pwdbuf), &pw);
36  if (pw != NULL)
37  {
38  strlcpy(buffer, pw->pw_name, buflen);
39  return true;
40  }
41  if (pwerr != 0)
42  snprintf(buffer, buflen,
43  _("could not look up local user ID %d: %s"),
44  (int) user_id,
45  strerror_r(pwerr, pwdbuf, sizeof(pwdbuf)));
46  else
47  snprintf(buffer, buflen,
48  _("local user with ID %d does not exist"),
49  (int) user_id);
50  return false;
51 }

References _, snprintf, strerror_r, and strlcpy().

Referenced by pg_fe_getusername().

◆ pg_inet_net_ntop()

char* pg_inet_net_ntop ( int  af,
const void *  src,
int  bits,
char *  dst,
size_t  size 
)

Definition at line 77 of file inet_net_ntop.c.

78 {
79  /*
80  * We need to cover both the address family constants used by the PG inet
81  * type (PGSQL_AF_INET and PGSQL_AF_INET6) and those used by the system
82  * libraries (AF_INET and AF_INET6). We can safely assume PGSQL_AF_INET
83  * == AF_INET, but the INET6 constants are very likely to be different.
84  */
85  switch (af)
86  {
87  case PGSQL_AF_INET:
88  return (inet_net_ntop_ipv4(src, bits, dst, size));
89  case PGSQL_AF_INET6:
90 #if AF_INET6 != PGSQL_AF_INET6
91  case AF_INET6:
92 #endif
93  return (inet_net_ntop_ipv6(src, bits, dst, size));
94  default:
95  errno = EAFNOSUPPORT;
96  return (NULL);
97  }
98 }
static char * inet_net_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size)
static char * inet_net_ntop_ipv4(const u_char *src, int bits, char *dst, size_t size)
#define PGSQL_AF_INET
Definition: inet.h:39
#define PGSQL_AF_INET6
Definition: inet.h:40
#define EAFNOSUPPORT
Definition: win32_port.h:378

References EAFNOSUPPORT, inet_net_ntop_ipv4(), inet_net_ntop_ipv6(), PGSQL_AF_INET, PGSQL_AF_INET6, and size.

Referenced by getHostaddr(), inet_abbrev(), network_host(), network_out(), network_show(), and pq_verify_peer_name_matches_certificate_ip().

◆ 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().

◆ pg_printf()

int int int int int int int int pg_printf ( const char *  fmt,
  ... 
)

◆ pg_qsort()

void pg_qsort ( void *  base,
size_t  nel,
size_t  elsize,
int(*)(const void *, const void *)  cmp 
)

◆ pg_qsort_strcmp()

int pg_qsort_strcmp ( const void *  a,
const void *  b 
)

Definition at line 19 of file qsort.c.

20 {
21  return strcmp(*(const char *const *) a, *(const char *const *) b);
22 }
int b
Definition: isn.c:70
int a
Definition: isn.c:69

References a, and b.

Referenced by GetConfFilesInDir(), readstoplist(), and searchstoplist().

◆ pg_set_block()

bool pg_set_block ( pgsocket  sock)

Definition at line 49 of file noblock.c.

50 {
51 #if !defined(WIN32)
52  int flags;
53 
54  flags = fcntl(sock, F_GETFL);
55  if (flags < 0)
56  return false;
57  if (fcntl(sock, F_SETFL, (flags & ~O_NONBLOCK)) == -1)
58  return false;
59  return true;
60 #else
61  unsigned long ioctlsocket_ret = 0;
62 
63  /* Returns non-0 on failure, while fcntl() returns -1 on failure */
64  return (ioctlsocket(sock, FIONBIO, &ioctlsocket_ret) == 0);
65 #endif
66 }

◆ pg_set_noblock()

bool pg_set_noblock ( pgsocket  sock)

Definition at line 25 of file noblock.c.

26 {
27 #if !defined(WIN32)
28  int flags;
29 
30  flags = fcntl(sock, F_GETFL);
31  if (flags < 0)
32  return false;
33  if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) == -1)
34  return false;
35  return true;
36 #else
37  unsigned long ioctlsocket_ret = 1;
38 
39  /* Returns non-0 on failure, while fcntl() returns -1 on failure */
40  return (ioctlsocket(sock, FIONBIO, &ioctlsocket_ret) == 0);
41 #endif
42 }

Referenced by pq_init(), PQconnectPoll(), and report_fork_failure_to_client().

◆ pg_snprintf()

int int pg_snprintf ( char *  str,
size_t  count,
const char *  fmt,
  ... 
)

Referenced by initPopulateTable().

◆ pg_sprintf()

int int int int pg_sprintf ( char *  str,
const char *  fmt,
  ... 
)

◆ pg_strcasecmp()

int pg_strcasecmp ( const char *  s1,
const char *  s2 
)

Definition at line 36 of file pgstrcasecmp.c.

37 {
38  for (;;)
39  {
40  unsigned char ch1 = (unsigned char) *s1++;
41  unsigned char ch2 = (unsigned char) *s2++;
42 
43  if (ch1 != ch2)
44  {
45  if (ch1 >= 'A' && ch1 <= 'Z')
46  ch1 += 'a' - 'A';
47  else if (IS_HIGHBIT_SET(ch1) && isupper(ch1))
48  ch1 = tolower(ch1);
49 
50  if (ch2 >= 'A' && ch2 <= 'Z')
51  ch2 += 'a' - 'A';
52  else if (IS_HIGHBIT_SET(ch2) && isupper(ch2))
53  ch2 = tolower(ch2);
54 
55  if (ch1 != ch2)
56  return (int) ch1 - (int) ch2;
57  }
58  if (ch1 == 0)
59  break;
60  }
61  return 0;
62 }
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1142
char * s1
char * s2

References IS_HIGHBIT_SET, s1, and s2.

Referenced by AlterType(), appendPGArray(), array_out(), build_startup_packet(), check_createrole_self_grant(), check_datestyle(), check_debug_io_direct(), check_log_destination(), check_publications_origin(), check_usermap(), check_wal_consistency_checking(), comp_keyword_case_hook(), config_enum_lookup_by_name(), convert_any_priv_string(), createdb(), defGetBoolean(), defGetCopyHeaderChoice(), defGetCopyOnErrorChoice(), defGetStreamingMode(), defGetTypeLength(), DefineAggregate(), DefineCollation(), DefineType(), do_pset(), dumpSubscription(), echo_hidden_hook(), echo_hook(), evaluateSleep(), exec_command(), ExecVacuum(), expect_boolean_value(), find_matching_ts_config(), get_collation_actual_version(), get_progname(), GetAttributeStorage(), GetCommandTagEnum(), getMetaCommand(), histcontrol_hook(), hostname_match(), IsReservedOriginName(), locate_stem_module(), lookup_prop_name(), main(), makeVariableValue(), map_typename_pattern(), on_error_rollback_hook(), parse_basebackup_options(), parse_hstore(), parse_one_reloption(), parse_output_parameters(), parse_slash_copy(), parse_subscription_options(), parseArchiveFormat(), parseNameAndArgTypes(), ParseVariableBool(), pg_checksum_parse_type(), pg_fe_sendauth(), pg_find_encoding(), pg_size_bytes(), pg_stat_get_progress_info(), pgp_get_cipher_code(), pgp_get_digest_code(), pgstat_get_kind_from_str(), PGTYPEStimestamp_defmt_scan(), plperl_trigger_handler(), plpgsql_extra_checks_check_hook(), PLy_exec_trigger(), pq_verify_peer_name_matches_certificate_name(), process_backslash_command(), prsd_headline(), px_gen_salt(), px_resolve_alias(), ReadArrayToken(), RegisterCustomRmgr(), show_context_hook(), splitTzLine(), ssl_protocol_version_to_openssl(), sslVerifyProtocolRange(), sslVerifyProtocolVersion(), SyncRepGetStandbyPriority(), unicode_norm_form_from_string(), validate_exec(), variable_is_guc_list_quote(), verbosity_hook(), verify_heapam(), wildcard_certificate_match(), and xmlpi().

◆ pg_strerror()

char* pg_strerror ( int  errnum)

Definition at line 35 of file strerror.c.

36 {
37  static char errorstr_buf[PG_STRERROR_R_BUFLEN];
38 
39  return pg_strerror_r(errnum, errorstr_buf, sizeof(errorstr_buf));
40 }
#define PG_STRERROR_R_BUFLEN
Definition: port.h:256
char * pg_strerror_r(int errnum, char *buf, size_t buflen)
Definition: strerror.c:46

References pg_strerror_r(), and PG_STRERROR_R_BUFLEN.

◆ pg_strerror_r()

char* pg_strerror_r ( int  errnum,
char *  buf,
size_t  buflen 
)

Definition at line 46 of file strerror.c.

47 {
48  char *str;
49 
50  /* If it's a Windows Winsock error, that needs special handling */
51 #ifdef WIN32
52  /* Winsock error code range, per WinError.h */
53  if (errnum >= 10000 && errnum <= 11999)
54  return win32_socket_strerror(errnum, buf, buflen);
55 #endif
56 
57  /* Try the platform's strerror_r(), or maybe just strerror() */
58  str = gnuish_strerror_r(errnum, buf, buflen);
59 
60  /*
61  * Some strerror()s return an empty string for out-of-range errno. This
62  * is ANSI C spec compliant, but not exactly useful. Also, we may get
63  * back strings of question marks if libc cannot transcode the message to
64  * the codeset specified by LC_CTYPE. If we get nothing useful, first try
65  * get_errno_symbol(), and if that fails, print the numeric errno.
66  */
67  if (str == NULL || *str == '\0' || *str == '?')
68  str = get_errno_symbol(errnum);
69 
70  if (str == NULL)
71  {
72  snprintf(buf, buflen, _("operating system error %d"), errnum);
73  str = buf;
74  }
75 
76  return str;
77 }
static char * get_errno_symbol(int errnum)
Definition: strerror.c:113
static char * gnuish_strerror_r(int errnum, char *buf, size_t buflen)
Definition: strerror.c:85

References _, buf, get_errno_symbol(), gnuish_strerror_r(), snprintf, and generate_unaccent_rules::str.

Referenced by pg_strerror().

◆ pg_strfromd()

int pg_strfromd ( char *  str,
size_t  count,
int  precision,
double  value 
)

Definition at line 1285 of file snprintf.c.

1286 {
1287  PrintfTarget target;
1288  int signvalue = 0;
1289  int vallen;
1290  char fmt[8];
1291  char convert[64];
1292 
1293  /* Set up the target like pg_snprintf, but require nonempty buffer */
1294  Assert(count > 0);
1295  target.bufstart = target.bufptr = str;
1296  target.bufend = str + count - 1;
1297  target.stream = NULL;
1298  target.nchars = 0;
1299  target.failed = false;
1300 
1301  /*
1302  * We bound precision to a reasonable range; the combination of this and
1303  * the knowledge that we're using "g" format without padding allows the
1304  * convert[] buffer to be reasonably small.
1305  */
1306  if (precision < 1)
1307  precision = 1;
1308  else if (precision > 32)
1309  precision = 32;
1310 
1311  /*
1312  * The rest is just an inlined version of the fmtfloat() logic above,
1313  * simplified using the knowledge that no padding is wanted.
1314  */
1315  if (isnan(value))
1316  {
1317  strcpy(convert, "NaN");
1318  vallen = 3;
1319  }
1320  else
1321  {
1322  static const double dzero = 0.0;
1323 
1324  if (value < 0.0 ||
1325  (value == 0.0 &&
1326  memcmp(&value, &dzero, sizeof(double)) != 0))
1327  {
1328  signvalue = '-';
1329  value = -value;
1330  }
1331 
1332  if (isinf(value))
1333  {
1334  strcpy(convert, "Infinity");
1335  vallen = 8;
1336  }
1337  else
1338  {
1339  fmt[0] = '%';
1340  fmt[1] = '.';
1341  fmt[2] = '*';
1342  fmt[3] = 'g';
1343  fmt[4] = '\0';
1344  vallen = snprintf(convert, sizeof(convert), fmt, precision, value);
1345  if (vallen < 0)
1346  {
1347  target.failed = true;
1348  goto fail;
1349  }
1350 
1351 #ifdef WIN32
1352  if (vallen >= 6 &&
1353  convert[vallen - 5] == 'e' &&
1354  convert[vallen - 3] == '0')
1355  {
1356  convert[vallen - 3] = convert[vallen - 2];
1357  convert[vallen - 2] = convert[vallen - 1];
1358  vallen--;
1359  }
1360 #endif
1361  }
1362  }
1363 
1364  if (signvalue)
1365  dopr_outch(signvalue, &target);
1366 
1367  dostr(convert, vallen, &target);
1368 
1369 fail:
1370  *(target.bufptr) = '\0';
1371  return target.failed ? -1 : (target.bufptr - target.bufstart
1372  + target.nchars);
1373 }
static struct @150 value
static void const char * fmt
static void dostr(const char *str, int slen, PrintfTarget *target)
Definition: snprintf.c:1377
static void dopr_outch(int c, PrintfTarget *target)
Definition: snprintf.c:1414
bool failed
Definition: snprintf.c:133
char * bufstart
Definition: snprintf.c:128
char * bufend
Definition: snprintf.c:129
char * bufptr
Definition: snprintf.c:127
FILE * stream
Definition: snprintf.c:131
static void convert(const int32 val, char *const buf)
Definition: zic.c:1992

References Assert(), PrintfTarget::bufend, PrintfTarget::bufptr, PrintfTarget::bufstart, convert(), dopr_outch(), dostr(), PrintfTarget::failed, fmt, PrintfTarget::nchars, snprintf, generate_unaccent_rules::str, PrintfTarget::stream, and value.

Referenced by float4out(), and float8out_internal().

◆ pg_strncasecmp()

int pg_strncasecmp ( const char *  s1,
const char *  s2,
size_t  n 
)

Definition at line 69 of file pgstrcasecmp.c.

70 {
71  while (n-- > 0)
72  {
73  unsigned char ch1 = (unsigned char) *s1++;
74  unsigned char ch2 = (unsigned char) *s2++;
75 
76  if (ch1 != ch2)
77  {
78  if (ch1 >= 'A' && ch1 <= 'Z')
79  ch1 += 'a' - 'A';
80  else if (IS_HIGHBIT_SET(ch1) && isupper(ch1))
81  ch1 = tolower(ch1);
82 
83  if (ch2 >= 'A' && ch2 <= 'Z')
84  ch2 += 'a' - 'A';
85  else if (IS_HIGHBIT_SET(ch2) && isupper(ch2))
86  ch2 = tolower(ch2);
87 
88  if (ch1 != ch2)
89  return (int) ch1 - (int) ch2;
90  }
91  if (ch1 == 0)
92  break;
93  }
94  return 0;
95 }

References IS_HIGHBIT_SET, s1, and s2.

Referenced by check_datestyle(), check_special_value(), check_timezone(), command_no_begin(), do_pset(), float4in_internal(), float8in_internal(), get_collation_actual_version(), is_select_command(), MainLoop(), makeVariableValue(), map_sql_identifier_to_xml_name(), multirange_in(), numeric_in(), parse_bool_with_len(), parse_jsonb_index_flags(), parse_or_operator(), ParseTzFile(), ParseVariableBool(), range_parse(), replace_guc_value(), scan_directory_ci(), set_unicode_line_style(), set_var_from_str(), and SpecialTags().

◆ pg_strong_random()

bool pg_strong_random ( void *  buf,
size_t  len 
)

Definition at line 153 of file pg_strong_random.c.

154 {
155  int f;
156  char *p = buf;
157  ssize_t res;
158 
159  f = open("/dev/urandom", O_RDONLY, 0);
160  if (f == -1)
161  return false;
162 
163  while (len)
164  {
165  res = read(f, p, len);
166  if (res <= 0)
167  {
168  if (errno == EINTR)
169  continue; /* interrupted by signal, just retry */
170 
171  close(f);
172  return false;
173  }
174 
175  p += res;
176  len -= res;
177  }
178 
179  close(f);
180  return true;
181 }
#define close(a)
Definition: win32.h:12
#define read(a, b, c)
Definition: win32.h:13
#define EINTR
Definition: win32_port.h:374

References buf, close, EINTR, len, read, and res.

Referenced by build_client_first_message(), build_server_first_message(), CheckMD5Auth(), gen_random_uuid(), init_sess_key(), InitControlFile(), pad_eme_pkcs1_v15(), PerformRadiusTransaction(), pg_be_scram_build_secret(), pg_fe_scram_build_secret(), pg_random_bytes(), pgp_s2k_fill(), px_gen_salt(), RandomCancelKey(), set_random_seed(), and write_prefix().

◆ pg_strong_random_init()

void pg_strong_random_init ( void  )

Definition at line 147 of file pg_strong_random.c.

148 {
149  /* No initialization needed */
150 }

Referenced by fork_process().

◆ pg_strsignal()

const char* pg_strsignal ( int  signum)

Definition at line 39 of file pgstrsignal.c.

40 {
41  const char *result;
42 
43  /*
44  * If we have strsignal(3), use that --- but check its result for NULL.
45  */
46 #ifdef HAVE_STRSIGNAL
47  result = strsignal(signum);
48  if (result == NULL)
49  result = "unrecognized signal";
50 #else
51 
52  /*
53  * We used to have code here to try to use sys_siglist[] if available.
54  * However, it seems that all platforms with sys_siglist[] have also had
55  * strsignal() for many years now, so that was just a waste of code.
56  */
57  result = "(signal names not available on this platform)";
58 #endif
59 
60  return result;
61 }

Referenced by log_child_failure(), LogChildExit(), shell_archive_file(), and wait_result_to_str().

◆ pg_tolower()

unsigned char pg_tolower ( unsigned char  ch)

Definition at line 122 of file pgstrcasecmp.c.

123 {
124  if (ch >= 'A' && ch <= 'Z')
125  ch += 'a' - 'A';
126  else if (IS_HIGHBIT_SET(ch) && isupper(ch))
127  ch = tolower(ch);
128  return ch;
129 }

References IS_HIGHBIT_SET.

Referenced by DecodeTimezoneAbbrevPrefix(), dir_strcmp(), ParseDateTime(), patternToSQLRegex(), PGTYPESdate_defmt_asc(), PQfnumber(), SB_lower_char(), str_initcap(), str_tolower(), and validateTzEntry().

◆ pg_toupper()

unsigned char pg_toupper ( unsigned char  ch)

Definition at line 105 of file pgstrcasecmp.c.

106 {
107  if (ch >= 'a' && ch <= 'z')
108  ch += 'A' - 'a';
109  else if (IS_HIGHBIT_SET(ch) && islower(ch))
110  ch = toupper(ch);
111  return ch;
112 }

References IS_HIGHBIT_SET.

Referenced by cash_words(), DetermineTimeZoneAbbrevOffsetInternal(), pg_split_walfile_name(), pg_timezone_abbrevs(), pg_tzset(), str_initcap(), and str_toupper().

◆ pg_usleep()

void pg_usleep ( long  microsec)

Definition at line 53 of file signal.c.

54 {
55  if (unlikely(pgwin32_signal_event == NULL))
56  {
57  /*
58  * If we're reached by pgwin32_open_handle() early in startup before
59  * the signal event is set up, just fall back to a regular
60  * non-interruptible sleep.
61  */
62  SleepEx((microsec < 500 ? 1 : (microsec + 500) / 1000), FALSE);
63  return;
64  }
65 
66  if (WaitForSingleObject(pgwin32_signal_event,
67  (microsec < 500 ? 1 : (microsec + 500) / 1000))
68  == WAIT_OBJECT_0)
69  {
71  errno = EINTR;
72  return;
73  }
74 }
#define unlikely(x)
Definition: c.h:298
void pgwin32_dispatch_queued_signals(void)
Definition: signal.c:120
HANDLE pgwin32_signal_event
Definition: signal.c:27

References EINTR, pgwin32_dispatch_queued_signals(), pgwin32_signal_event, and unlikely.

Referenced by _bt_pendingfsm_finalize(), AcceptConnection(), auth_delay_checks(), AutoVacWorkerMain(), BackendInitialize(), BackgroundWorkerMain(), BackgroundWriterMain(), CheckpointerMain(), ConditionalXactLockTableWait(), CountOtherDBBackends(), CreateCheckPoint(), do_watch(), exec_prog(), FileReadV(), FileWriteV(), get_controlfile_by_exact_path(), GetMultiXactIdMembers(), InitPostgres(), main(), perform_spin_delay(), pgarch_ArchiverCopyLoop(), pgwin32_recv(), read_local_xlog_page_guts(), regression_main(), RequestCheckpoint(), ResolveRecoveryConflictWithDatabase(), ResolveRecoveryConflictWithVirtualXIDs(), StartupXLOG(), threadRun(), vacuum_delay_point(), wait_for_connection_state(), wait_for_postmaster_promote(), wait_for_postmaster_start(), wait_for_postmaster_stop(), wait_pid(), WaitExceedsMaxStandbyDelay(), WALDumpOpenSegment(), WalSndWaitStopping(), WalWriterMain(), XactLockTableWait(), and XLogFlush().

◆ pg_vfprintf()

int int int int int pg_vfprintf ( FILE *  stream,
const char *  fmt,
va_list  args 
)

◆ pg_vprintf()

int int int int int int int pg_vprintf ( const char *  fmt,
va_list  args 
)

◆ pg_vsnprintf()

int pg_vsnprintf ( char *  str,
size_t  count,
const char *  fmt,
va_list  args 
)

◆ pg_vsprintf()

int int int pg_vsprintf ( char *  str,
const char *  fmt,
va_list  args 
)

◆ pgfnames()

char** pgfnames ( const char *  path)

Definition at line 37 of file pgfnames.c.

38 {
39  DIR *dir;
40  struct dirent *file;
41  char **filenames;
42  int numnames = 0;
43  int fnsize = 200; /* enough for many small dbs */
44 
45  dir = opendir(path);
46  if (dir == NULL)
47  {
48  pg_log_warning("could not open directory \"%s\": %m", path);
49  return NULL;
50  }
51 
52  filenames = (char **) palloc(fnsize * sizeof(char *));
53 
54  while (errno = 0, (file = readdir(dir)) != NULL)
55  {
56  if (strcmp(file->d_name, ".") != 0 && strcmp(file->d_name, "..") != 0)
57  {
58  if (numnames + 1 >= fnsize)
59  {
60  fnsize *= 2;
61  filenames = (char **) repalloc(filenames,
62  fnsize * sizeof(char *));
63  }
64  filenames[numnames++] = pstrdup(file->d_name);
65  }
66  }
67 
68  if (errno)
69  pg_log_warning("could not read directory \"%s\": %m", path);
70 
71  filenames[numnames] = NULL;
72 
73  if (closedir(dir))
74  pg_log_warning("could not close directory \"%s\": %m", path);
75 
76  return filenames;
77 }
char * pstrdup(const char *in)
Definition: mcxt.c:1683
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1528
void * palloc(Size size)
Definition: mcxt.c:1304
#define pg_log_warning(...)
Definition: pgfnames.c:24

References closedir(), dirent::d_name, opendir(), palloc(), pg_log_warning, pstrdup(), readdir(), and repalloc().

Referenced by scan_available_timezones().

◆ pgfnames_cleanup()

void pgfnames_cleanup ( char **  filenames)

Definition at line 86 of file pgfnames.c.

87 {
88  char **fn;
89 
90  for (fn = filenames; *fn; fn++)
91  pfree(*fn);
92 
93  pfree(filenames);
94 }
static void * fn(void *arg)
Definition: thread-alloc.c:119

References fn(), and pfree().

Referenced by scan_available_timezones().

◆ pipe_read_line()

char* pipe_read_line ( char *  cmd)

Definition at line 371 of file exec.c.

372 {
373  FILE *pipe_cmd;
374  char *line;
375 
376  fflush(NULL);
377 
378  errno = 0;
379  if ((pipe_cmd = popen(cmd, "r")) == NULL)
380  {
381  log_error(errcode(ERRCODE_SYSTEM_ERROR),
382  _("could not execute command \"%s\": %m"), cmd);
383  return NULL;
384  }
385 
386  /* Make sure popen() didn't change errno */
387  errno = 0;
388  line = pg_get_line(pipe_cmd, NULL);
389 
390  if (line == NULL)
391  {
392  if (ferror(pipe_cmd))
394  _("could not read from command \"%s\": %m"), cmd);
395  else
396  log_error(errcode(ERRCODE_NO_DATA),
397  _("no data was returned by command \"%s\""), cmd);
398  }
399 
400  (void) pclose_check(pipe_cmd);
401 
402  return line;
403 }
int pclose_check(FILE *stream)
Definition: exec.c:410
int errcode_for_file_access(void)
Definition: elog.c:882
static void const char fflush(stdout)
char * pg_get_line(FILE *stream, PromptInterruptContext *prompt_ctx)
Definition: pg_get_line.c:59

References _, errcode(), errcode_for_file_access(), fflush(), log_error, pclose_check(), and pg_get_line().

Referenced by check_exec(), find_other_exec(), and getRestoreCommand().

◆ pqsignal()

pqsigfunc pqsignal ( int  signo,
pqsigfunc  func 
)

Definition at line 34 of file legacy-pqsignal.c.

35 {
36 #ifndef WIN32
37  struct sigaction act,
38  oact;
39 
40  act.sa_handler = func;
41  sigemptyset(&act.sa_mask);
42  act.sa_flags = 0;
43  if (signo != SIGALRM)
44  act.sa_flags |= SA_RESTART;
45 #ifdef SA_NOCLDSTOP
46  if (signo == SIGCHLD)
47  act.sa_flags |= SA_NOCLDSTOP;
48 #endif
49  if (sigaction(signo, &act, &oact) < 0)
50  return SIG_ERR;
51  return oact.sa_handler;
52 #else /* WIN32 */
53  return signal(signo, func);
54 #endif
55 }
#define SIGCHLD
Definition: win32_port.h:178
#define SIG_ERR
Definition: win32_port.h:164
#define SIGALRM
Definition: win32_port.h:174

References SIG_ERR, SIGALRM, and SIGCHLD.

Referenced by ApplyLauncherMain(), autoprewarm_database_main(), autoprewarm_main(), AutoVacWorkerMain(), BackendInitialize(), BackgroundWorkerMain(), BackgroundWriterMain(), bootstrap_signals(), CheckpointerMain(), disable_sigpipe_trap(), do_start(), InitializeLatchSupport(), InitializeTimeouts(), InitPostmasterChild(), main(), make_temp_sockdir(), OpenPipeStream(), ParallelApplyWorkerMain(), ParallelBackupStart(), ParallelWorkerMain(), pg_crc32c_armv8_available(), PgArchiverMain(), plperl_init_interp(), PostgresMain(), PostmasterDeathSignalInit(), PostmasterMain(), ReplSlotSyncWorkerMain(), restore_sigpipe_trap(), set_cancel_handler(), setalarm(), setup_cancel_handler(), setup_signals(), SetupApplyOrSyncWorker(), ShutdownLatchSupport(), signal_remove_temp(), sigTermHandler(), StartupProcessMain(), SysLoggerMain(), test_shm_mq_main(), trap_sigint_during_startup(), trapsig(), WalReceiverMain(), WalSndSignals(), WalSummarizerMain(), WalWriterMain(), and worker_spi_main().

◆ qsort_arg()

◆ qsort_interruptible()

◆ rmtree()

bool rmtree ( const char *  path,
bool  rmtopdir 
)

Definition at line 50 of file rmtree.c.

51 {
52  char pathbuf[MAXPGPATH];
53  DIR *dir;
54  struct dirent *de;
55  bool result = true;
56  size_t dirnames_size = 0;
57  size_t dirnames_capacity = 8;
58  char **dirnames;
59 
60  dir = OPENDIR(path);
61  if (dir == NULL)
62  {
63  pg_log_warning("could not open directory \"%s\": %m", path);
64  return false;
65  }
66 
67  dirnames = (char **) palloc(sizeof(char *) * dirnames_capacity);
68 
69  while (errno = 0, (de = readdir(dir)))
70  {
71  if (strcmp(de->d_name, ".") == 0 ||
72  strcmp(de->d_name, "..") == 0)
73  continue;
74  snprintf(pathbuf, sizeof(pathbuf), "%s/%s", path, de->d_name);
75  switch (get_dirent_type(pathbuf, de, false, LOG_LEVEL))
76  {
77  case PGFILETYPE_ERROR:
78  /* already logged, press on */
79  break;
80  case PGFILETYPE_DIR:
81 
82  /*
83  * Defer recursion until after we've closed this directory, to
84  * avoid using more than one file descriptor at a time.
85  */
86  if (dirnames_size == dirnames_capacity)
87  {
88  dirnames = repalloc(dirnames,
89  sizeof(char *) * dirnames_capacity * 2);
90  dirnames_capacity *= 2;
91  }
92  dirnames[dirnames_size++] = pstrdup(pathbuf);
93  break;
94  default:
95  if (unlink(pathbuf) != 0 && errno != ENOENT)
96  {
97  pg_log_warning("could not remove file \"%s\": %m", pathbuf);
98  result = false;
99  }
100  break;
101  }
102  }
103 
104  if (errno != 0)
105  {
106  pg_log_warning("could not read directory \"%s\": %m", path);
107  result = false;
108  }
109 
110  CLOSEDIR(dir);
111 
112  /* Now recurse into the subdirectories we found. */
113  for (size_t i = 0; i < dirnames_size; ++i)
114  {
115  if (!rmtree(dirnames[i], true))
116  result = false;
117  pfree(dirnames[i]);
118  }
119 
120  if (rmtopdir)
121  {
122  if (rmdir(path) != 0)
123  {
124  pg_log_warning("could not remove directory \"%s\": %m", path);
125  result = false;
126  }
127  }
128 
129  pfree(dirnames);
130 
131  return result;
132 }
PGFileType get_dirent_type(const char *path, const struct dirent *de, bool look_through_symlinks, int elevel)
Definition: file_utils.c:525
@ PGFILETYPE_DIR
Definition: file_utils.h:23
@ PGFILETYPE_ERROR
Definition: file_utils.h:20
#define LOG_LEVEL
Definition: rmtree.c:28
#define OPENDIR(x)
Definition: rmtree.c:29
#define CLOSEDIR(x)
Definition: rmtree.c:30
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:50
#define pg_log_warning(...)
Definition: rmtree.c:27

References CLOSEDIR, dirent::d_name, get_dirent_type(), i, LOG_LEVEL, MAXPGPATH, OPENDIR, palloc(), pfree(), pg_log_warning, PGFILETYPE_DIR, PGFILETYPE_ERROR, pstrdup(), readdir(), repalloc(), and snprintf.

Referenced by cleanup_directories_atexit(), cleanup_output_dirs(), CreateSlotOnDisk(), dbase_redo(), movedb(), movedb_failure_callback(), regression_main(), remove_dbtablespaces(), remove_new_subdir(), ReplicationSlotDropPtr(), RestoreSlotFromDisk(), and StartupReplicationSlots().

◆ set_pglocale_pgservice()

void set_pglocale_pgservice ( const char *  argv0,
const char *  app 
)

Definition at line 448 of file exec.c.

449 {
450  char path[MAXPGPATH];
451  char my_exec_path[MAXPGPATH];
452 
453  /* don't set LC_ALL in the backend */
454  if (strcmp(app, PG_TEXTDOMAIN("postgres")) != 0)
455  {
456  setlocale(LC_ALL, "");
457 
458  /*
459  * One could make a case for reproducing here PostmasterMain()'s test
460  * for whether the process is multithreaded. Unlike the postmaster,
461  * no frontend program calls sigprocmask() or otherwise provides for
462  * mutual exclusion between signal handlers. While frontends using
463  * fork(), if multithreaded, are formally exposed to undefined
464  * behavior, we have not witnessed a concrete bug. Therefore,
465  * complaining about multithreading here may be mere pedantry.
466  */
467  }
468 
469  if (find_my_exec(argv0, my_exec_path) < 0)
470  return;
471 
472 #ifdef ENABLE_NLS
474  bindtextdomain(app, path);
475  textdomain(app);
476  /* set for libpq to use, but don't override existing setting */
477  setenv("PGLOCALEDIR", path, 0);
478 #endif
479 
480  if (getenv("PGSYSCONFDIR") == NULL)
481  {
482  get_etc_path(my_exec_path, path);
483  /* set for libpq to use */
484  setenv("PGSYSCONFDIR", path, 0);
485  }
486 }
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1201
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:887
void get_etc_path(const char *my_exec_path, char *ret_path)
Definition: path.c:833
#define setenv(x, y, z)
Definition: win32_port.h:537
#define setlocale(a, b)
Definition: win32_port.h:467

References argv0, find_my_exec(), get_etc_path(), get_locale_path(), MAXPGPATH, my_exec_path, PG_TEXTDOMAIN, setenv, and setlocale.

Referenced by main(), and regression_main().

◆ strlcat()

size_t strlcat ( char *  dst,
const char *  src,
size_t  siz 
)

Definition at line 33 of file strlcat.c.

34 {
35  char *d = dst;
36  const char *s = src;
37  size_t n = siz;
38  size_t dlen;
39 
40  /* Find the end of dst and adjust bytes left but don't go past end */
41  while (n-- != 0 && *d != '\0')
42  d++;
43  dlen = d - dst;
44  n = siz - dlen;
45 
46  if (n == 0)
47  return (dlen + strlen(s));
48  while (*s != '\0')
49  {
50  if (n != 1)
51  {
52  *d++ = *s;
53  n--;
54  }
55  s++;
56  }
57  *d = '\0';
58 
59  return (dlen + (s - src)); /* count does not include NUL */
60 }

Referenced by _PrepParallelRestore(), CreateBackupStreamer(), CreateLockFile(), get_configdata(), get_prompt(), and pqsecure_raw_write().

◆ strlcpy()

size_t strlcpy ( char *  dst,
const char *  src,
size_t  siz 
)

Definition at line 45 of file strlcpy.c.

46 {
47  char *d = dst;
48  const char *s = src;
49  size_t n = siz;
50 
51  /* Copy as many bytes as will fit */
52  if (n != 0)
53  {
54  while (--n != 0)
55  {
56  if ((*d++ = *s++) == '\0')
57  break;
58  }
59  }
60 
61  /* Not enough room in dst, add NUL and traverse rest of src */
62  if (n == 0)
63  {
64  if (siz != 0)
65  *d = '\0'; /* NUL-terminate dst */
66  while (*s++)
67  ;
68  }
69 
70  return (s - src - 1); /* count does not include NUL */
71 }

Referenced by _pgstat64(), _tarGetHeader(), AbsoluteConfigLocation(), abstime2tm(), BaseBackup(), bbstreamer_inject_file(), bbstreamer_tar_header(), be_tls_get_peer_issuer_name(), be_tls_get_peer_serial(), be_tls_get_peer_subject_name(), BootstrapModeMain(), ChooseConstraintName(), ChooseExtendedStatisticName(), ChooseExtendedStatisticNameAddition(), ChooseForeignKeyConstraintNameAddition(), ChooseIndexNameAddition(), ChooseRelationName(), CleanupPriorWALFiles(), close_walfile(), ConvertTimeZoneAbbrevs(), create_script_for_old_cluster_deletion(), DCH_cache_getnew(), DefineRelation(), descriptor_variable(), DetermineTimeZoneAbbrevOffsetInternal(), ensureCleanShutdown(), expand_tilde(), fetch_fp_info(), find_in_dynamic_libpath(), find_my_exec(), find_other_exec_or_die(), from_char_parse_int_len(), fsync_parent_path(), get_configdata(), get_control_data(), get_home_path(), get_prompt(), get_tablespace_mapping(), getRestoreCommand(), gnuish_strerror_r(), hash_create(), identify_system_timezone(), initialize_SSL(), InitPostgres(), injection_wait(), InjectionPointAttach(), isolation_init(), join_path_components(), KeepFileRestoredFromArchive(), logfile_getname(), logicalrep_read_begin_prepare(), logicalrep_read_commit_prepared(), logicalrep_read_prepare_common(), logicalrep_read_rollback_prepared(), main(), make_oper_cache_key(), make_relative_path(), mdsyncfiletag(), mdunlinkfiletag(), normalize_exec_path(), NUM_cache_getnew(), ParseAbortRecord(), parseCommandLine(), ParseCommitRecord(), ParseLongOption(), parseServiceInfo(), pg_get_user_home_dir(), pg_get_user_name(), pg_getnameinfo_all(), pg_open_tzfile(), pg_perm_setlocale(), pg_stat_get_wal_receiver(), pg_timezone_abbrevs(), pg_TZDIR(), pg_tzenumerate_next(), pgstat_bestart(), postprocess_sql_command(), PQcancel(), pqGetErrorNotice3(), pqGetHomeDirectory(), pqParseInput3(), PQrequestCancel(), process_directory_recursively(), process_file(), process_postgres_switches(), px_crypt_des(), recoveryStopsAfter(), RequestNamedLWLockTranche(), RequestXLogStreaming(), results_differ(), rot13_passphrase(), scan_available_timezones(), scan_directory(), scan_directory_ci(), scan_for_existing_tablespaces(), SerializeLibraryState(), setup_bin_paths(), SimpleLruInit(), SSLerrmessage(), tar_close(), timestamptz_to_str(), uuid_generate_internal(), validate_exec(), WaitEventExtensionNew(), WalReceiverMain(), and XLogRestorePoint().

◆ strnlen()

size_t strnlen ( const char *  str,
size_t  maxlen 
)

Definition at line 26 of file strnlen.c.

27 {
28  const char *p = str;
29 
30  while (maxlen-- > 0 && *p)
31  p++;
32  return p - str;
33 }

References generate_unaccent_rules::str.

Referenced by fmtstr(), pg_encoding_mblen_bounded(), pnstrdup(), and PQmblenBounded().

◆ validate_exec()

int validate_exec ( const char *  path)

Definition at line 88 of file exec.c.

89 {
90  struct stat buf;
91  int is_r;
92  int is_x;
93 
94 #ifdef WIN32
95  char path_exe[MAXPGPATH + sizeof(".exe") - 1];
96 
97  /* Win32 requires a .exe suffix for stat() */
98  if (strlen(path) < strlen(".exe") ||
99  pg_strcasecmp(path + strlen(path) - strlen(".exe"), ".exe") != 0)
100  {
101  strlcpy(path_exe, path, sizeof(path_exe) - 4);
102  strcat(path_exe, ".exe");
103  path = path_exe;
104  }
105 #endif
106 
107  /*
108  * Ensure that the file exists and is a regular file.
109  *
110  * XXX if you have a broken system where stat() looks at the symlink
111  * instead of the underlying file, you lose.
112  */
113  if (stat(path, &buf) < 0)
114  return -1;
115 
116  if (!S_ISREG(buf.st_mode))
117  {
118  /*
119  * POSIX offers no errno code that's simply "not a regular file". If
120  * it's a directory we can use EISDIR. Otherwise, it's most likely a
121  * device special file, and EPERM (Operation not permitted) isn't too
122  * horribly off base.
123  */
124  errno = S_ISDIR(buf.st_mode) ? EISDIR : EPERM;
125  return -1;
126  }
127 
128  /*
129  * Ensure that the file is both executable and readable (required for
130  * dynamic loading).
131  */
132 #ifndef WIN32
133  is_r = (access(path, R_OK) == 0);
134  is_x = (access(path, X_OK) == 0);
135  /* access() will set errno if it returns -1 */
136 #else
137  is_r = buf.st_mode & S_IRUSR;
138  is_x = buf.st_mode & S_IXUSR;
139  errno = EACCES; /* appropriate thing if we return nonzero */
140 #endif
141  return is_x ? (is_r ? 0 : -2) : -1;
142 }
short access
Definition: preproc-type.c:36
#define S_IRUSR
Definition: win32_port.h:289
#define S_ISREG(m)
Definition: win32_port.h:328

References buf, MAXPGPATH, pg_strcasecmp(), S_IRUSR, S_ISDIR, S_ISREG, S_IXUSR, stat, and strlcpy().

Referenced by check_exec(), find_my_exec(), and find_other_exec().

◆ wait_result_is_any_signal()

bool wait_result_is_any_signal ( int  exit_status,
bool  include_command_not_found 
)

Definition at line 121 of file wait_error.c.

122 {
123  if (WIFSIGNALED(exit_status))
124  return true;
125  if (WIFEXITED(exit_status) &&
126  WEXITSTATUS(exit_status) > (include_command_not_found ? 125 : 128))
127  return true;
128  return false;
129 }
#define WIFEXITED(w)
Definition: win32_port.h:152
#define WIFSIGNALED(w)
Definition: win32_port.h:153
#define WEXITSTATUS(w)
Definition: win32_port.h:154

References WEXITSTATUS, WIFEXITED, and WIFSIGNALED.

Referenced by ExecuteRecoveryCommand(), RestoreArchivedFile(), and shell_archive_file().

◆ wait_result_is_signal()

bool wait_result_is_signal ( int  exit_status,
int  signum 
)

Definition at line 102 of file wait_error.c.

103 {
104  if (WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum)
105  return true;
106  if (WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == 128 + signum)
107  return true;
108  return false;
109 }
#define WTERMSIG(w)
Definition: win32_port.h:155

References WEXITSTATUS, WIFEXITED, WIFSIGNALED, and WTERMSIG.

Referenced by ClosePipeFromProgram(), and RestoreArchivedFile().

◆ wait_result_to_exit_code()

int wait_result_to_exit_code ( int  exit_status)

Definition at line 138 of file wait_error.c.

139 {
140  if (exit_status == -1)
141  return -1; /* failure of pclose() or system() */
142  if (WIFEXITED(exit_status))
143  return WEXITSTATUS(exit_status);
144  if (WIFSIGNALED(exit_status))
145  return 128 + WTERMSIG(exit_status);
146  /* On many systems, this is unreachable */
147  return -1;
148 }

References WEXITSTATUS, WIFEXITED, WIFSIGNALED, and WTERMSIG.

Referenced by SetShellResultVariables().

◆ wait_result_to_str()

char* wait_result_to_str ( int  exitstatus)

Definition at line 33 of file wait_error.c.

34 {
35  char str[512];
36 
37  /*
38  * To simplify using this after pclose() and system(), handle status -1
39  * first. In that case, there is no wait result but some error indicated
40  * by errno.
41  */
42  if (exitstatus == -1)
43  {
44  snprintf(str, sizeof(str), "%m");
45  }
46  else if (WIFEXITED(exitstatus))
47  {
48  /*
49  * Give more specific error message for some common exit codes that
50  * have a special meaning in shells.
51  */
52  switch (WEXITSTATUS(exitstatus))
53  {
54  case 126:
55  snprintf(str, sizeof(str), _("command not executable"));
56  break;
57 
58  case 127:
59  snprintf(str, sizeof(str), _("command not found"));
60  break;
61 
62  default:
63  snprintf(str, sizeof(str),
64  _("child process exited with exit code %d"),
65  WEXITSTATUS(exitstatus));
66  }
67  }
68  else if (WIFSIGNALED(exitstatus))
69  {
70 #if defined(WIN32)
71  snprintf(str, sizeof(str),
72  _("child process was terminated by exception 0x%X"),
73  WTERMSIG(exitstatus));
74 #else
75  snprintf(str, sizeof(str),
76  _("child process was terminated by signal %d: %s"),
77  WTERMSIG(exitstatus), pg_strsignal(WTERMSIG(exitstatus)));
78 #endif
79  }
80  else
81  snprintf(str, sizeof(str),
82  _("child process exited with unrecognized status %d"),
83  exitstatus);
84 
85  return pstrdup(str);
86 }
const char * pg_strsignal(int signum)
Definition: pgstrsignal.c:39

References _, pg_strsignal(), pstrdup(), snprintf, generate_unaccent_rules::str, WEXITSTATUS, WIFEXITED, WIFSIGNALED, and WTERMSIG.

Referenced by adjust_data_dir(), BaseBackup(), ClosePipeFromProgram(), ClosePipeToProgram(), do_copy(), exec_command_write(), ExecuteRecoveryCommand(), get_bin_version(), get_control_data(), pclose_check(), RestoreArchivedFile(), run_ssl_passphrase_command(), and shell_finish_command().