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, char *line, int maxsize)
 
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)
 

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:407
#define ECONNABORTED
Definition: win32_port.h:377
#define EHOSTUNREACH
Definition: win32_port.h:401
#define ETIMEDOUT
Definition: win32_port.h:411
#define ENETRESET
Definition: win32_port.h:405
#define EHOSTDOWN
Definition: win32_port.h:399
#define ENETDOWN
Definition: win32_port.h:403
#define ECONNRESET
Definition: win32_port.h:379

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 510 of file port.h.

◆ HAVE_POLL

#define HAVE_POLL   1

Definition at line 511 of file port.h.

◆ HAVE_POLL_H

#define HAVE_POLL_H   1

Definition at line 512 of file port.h.

◆ HAVE_READLINK

#define HAVE_READLINK   1

Definition at line 513 of file port.h.

◆ HAVE_SETSID

#define HAVE_SETSID   1

Definition at line 514 of file port.h.

◆ HAVE_SHM_OPEN

#define HAVE_SHM_OPEN   1

Definition at line 515 of file port.h.

◆ HAVE_SYMLINK

#define HAVE_SYMLINK   1

Definition at line 516 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:119

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 479 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 445 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 488 of file port.h.

◆ qsort_arg_comparator

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

Definition at line 447 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:747

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

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:1048
static void trim_trailing_separator(char *path)
Definition: path.c:1026
static char * trim_directory(char *path)
Definition: path.c:994
#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:318

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(), 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(), parseCommandLine(), process_file(), resolve_symlinks(), 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:1102
#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:67

References buf, bzero_p, and len.

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

◆ find_my_exec()

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

Definition at line 152 of file exec.c.

153 {
154  char cwd[MAXPGPATH],
155  test_path[MAXPGPATH];
156  char *path;
157 
158  if (!getcwd(cwd, MAXPGPATH))
159  {
161  _("could not identify current directory: %m"));
162  return -1;
163  }
164 
165  /*
166  * If argv0 contains a separator, then PATH wasn't used.
167  */
168  if (first_dir_separator(argv0) != NULL)
169  {
170  if (is_absolute_path(argv0))
171  strlcpy(retpath, argv0, MAXPGPATH);
172  else
173  join_path_components(retpath, cwd, argv0);
174  canonicalize_path(retpath);
175 
176  if (validate_exec(retpath) == 0)
177  return resolve_symlinks(retpath);
178 
179  log_error(errcode(ERRCODE_WRONG_OBJECT_TYPE),
180  _("invalid binary \"%s\": %m"), retpath);
181  return -1;
182  }
183 
184 #ifdef WIN32
185  /* Win32 checks the current directory first for names without slashes */
186  join_path_components(retpath, cwd, argv0);
187  if (validate_exec(retpath) == 0)
188  return resolve_symlinks(retpath);
189 #endif
190 
191  /*
192  * Since no explicit path was supplied, the user must have been relying on
193  * PATH. We'll search the same PATH.
194  */
195  if ((path = getenv("PATH")) && *path)
196  {
197  char *startp = NULL,
198  *endp = NULL;
199 
200  do
201  {
202  if (!startp)
203  startp = path;
204  else
205  startp = endp + 1;
206 
207  endp = first_path_var_separator(startp);
208  if (!endp)
209  endp = startp + strlen(startp); /* point to end */
210 
211  strlcpy(test_path, startp, Min(endp - startp + 1, MAXPGPATH));
212 
213  if (is_absolute_path(test_path))
214  join_path_components(retpath, test_path, argv0);
215  else
216  {
217  join_path_components(retpath, cwd, test_path);
218  join_path_components(retpath, retpath, argv0);
219  }
220  canonicalize_path(retpath);
221 
222  switch (validate_exec(retpath))
223  {
224  case 0: /* found ok */
225  return resolve_symlinks(retpath);
226  case -1: /* wasn't even a candidate, keep looking */
227  break;
228  case -2: /* found but disqualified */
229  log_error(errcode(ERRCODE_WRONG_OBJECT_TYPE),
230  _("could not read binary \"%s\": %m"),
231  retpath);
232  break;
233  }
234  } while (*endp);
235  }
236 
237  log_error(errcode(ERRCODE_UNDEFINED_FILE),
238  _("could not find a \"%s\" to execute"), argv0);
239  return -1;
240 }
#define Min(x, y)
Definition: c.h:937
#define log_error(errcodefn,...)
Definition: exec.c:54
int validate_exec(const char *path)
Definition: exec.c:80
static int resolve_symlinks(char *path)
Definition: exec.c:259
int errcode_for_file_access(void)
Definition: elog.c:718
int errcode(int sqlerrcode)
Definition: elog.c:695
#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
#define is_absolute_path(filename)
Definition: port.h:103
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(), errcode_for_file_access(), first_dir_separator(), first_path_var_separator(), is_absolute_path, join_path_components(), log_error, MAXPGPATH, Min, resolve_symlinks(), 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 351 of file exec.c.

353 {
354  char cmd[MAXPGPATH];
355  char line[MAXPGPATH];
356 
357  if (find_my_exec(argv0, retpath) < 0)
358  return -1;
359 
360  /* Trim off program name and keep just directory */
361  *last_dir_separator(retpath) = '\0';
362  canonicalize_path(retpath);
363 
364  /* Now append the other program's name */
365  snprintf(retpath + strlen(retpath), MAXPGPATH - strlen(retpath),
366  "/%s%s", target, EXE);
367 
368  if (validate_exec(retpath) != 0)
369  return -1;
370 
371  snprintf(cmd, sizeof(cmd), "\"%s\" -V", retpath);
372 
373  if (!pipe_read_line(cmd, line, sizeof(line)))
374  return -1;
375 
376  if (strcmp(line, versionstr) != 0)
377  return -2;
378 
379  return 0;
380 }
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:152
char * pipe_read_line(char *cmd, char *line, int maxsize)
Definition: exec.c:387
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, 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:1181
#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 897 of file path.c.

898 {
899  make_relative_path(ret_path, DOCDIR, PGBINDIR, my_exec_path);
900 }
char my_exec_path[MAXPGPATH]
Definition: globals.c:76
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 834 of file path.c.

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

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 928 of file path.c.

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

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 906 of file path.c.

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

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 843 of file path.c.

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

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 861 of file path.c.

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

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 870 of file path.c.

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

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 888 of file path.c.

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

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 915 of file path.c.

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

References make_relative_path(), and my_exec_path.

Referenced by get_configdata().

◆ get_parent_directory()

void get_parent_directory ( char *  path)

Definition at line 977 of file path.c.

978 {
979  trim_directory(path);
980 }

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 852 of file path.c.

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

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 879 of file path.c.

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

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:45
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:247
int uid_t
Definition: win32_port.h:246

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(), process_file(), and resolve_symlinks().

◆ 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(), resolve_symlinks(), sendDir(), sendFile(), setup(), and setup_bin_paths().

◆ 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: %s\n"),
776  strerror(errno));
777  return NULL;
778 #endif
779  }
780  }
781 
782  new = malloc(strlen(buf) + strlen(path) + 2);
783  if (!new)
784  {
785  free(buf);
786 #ifndef FRONTEND
787  ereport(ERROR,
788  (errcode(ERRCODE_OUT_OF_MEMORY),
789  errmsg("out of memory")));
790 #else
791  fprintf(stderr, _("out of memory\n"));
792  return NULL;
793 #endif
794  }
795  sprintf(new, "%s/%s", buf, path);
796  free(buf);
797  }
798  else
799  {
800  new = strdup(path);
801  if (!new)
802  {
803 #ifndef FRONTEND
804  ereport(ERROR,
805  (errcode(ERRCODE_OUT_OF_MEMORY),
806  errmsg("out of memory")));
807 #else
808  fprintf(stderr, _("out of memory\n"));
809  return NULL;
810 #endif
811  }
812  }
813 
814  /* Make sure punctuation is canonical, too */
815  canonicalize_path(new);
816 
817  return new;
818 }
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
#define free(a)
Definition: header.h:65
void canonicalize_path(char *path)
Definition: path.c:264
#define sprintf
Definition: port.h:240
#define strerror
Definition: port.h:251

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

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 422 of file exec.c.

423 {
424  int exitstatus;
425  char *reason;
426 
427  exitstatus = pclose(stream);
428 
429  if (exitstatus == 0)
430  return 0; /* all is well */
431 
432  if (exitstatus == -1)
433  {
434  /* pclose() itself failed, and hopefully set errno */
435  log_error(errcode(ERRCODE_SYSTEM_ERROR),
436  _("%s() failed: %m"), "pclose");
437  }
438  else
439  {
440  reason = wait_result_to_str(exitstatus);
441  log_error(errcode(ERRCODE_SYSTEM_ERROR),
442  "%s", reason);
443  pfree(reason);
444  }
445  return exitstatus;
446 }
void pfree(void *pointer)
Definition: mcxt.c:1306
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_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 71 of file thread.c.

72 {
73  char pwdbuf[BUFSIZ];
74  struct passwd pwdstr;
75  struct passwd *pw = NULL;
76  int pwerr;
77 
78  pwerr = getpwuid_r(user_id, &pwdstr, pwdbuf, sizeof(pwdbuf), &pw);
79  if (pw != NULL)
80  {
81  strlcpy(buffer, pw->pw_dir, buflen);
82  return true;
83  }
84  if (pwerr != 0)
85  snprintf(buffer, buflen,
86  _("could not look up local user ID %d: %s"),
87  (int) user_id,
88  strerror_r(pwerr, pwdbuf, sizeof(pwdbuf)));
89  else
90  snprintf(buffer, buflen,
91  _("local user with ID %d does not exist"),
92  (int) user_id);
93  return false;
94 }
#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 35 of file thread.c.

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

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:373

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

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:286
#define S_IRWXG
Definition: win32_port.h:312
#define S_IRWXO
Definition: win32_port.h:324
#define S_ISDIR(m)
Definition: win32_port.h:327
#define mkdir(a, b)
Definition: win32_port.h:80
#define S_IWUSR
Definition: win32_port.h:294
#define S_IXUSR
Definition: win32_port.h:297
#define S_IRWXU
Definition: win32_port.h:300

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_xlog_or_symlink(), 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,
  ... 
)

◆ 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:1094
char * s1
char * s2

References IS_HIGHBIT_SET, s1, and s2.

Referenced by AlterType(), appendPGArray(), array_out(), build_startup_packet(), check_datestyle(), check_ident_usermap(), 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(), defGetTypeLength(), DefineAggregate(), DefineCollation(), DefineType(), do_pset(), dumpSubscription(), echo_hidden_hook(), echo_hook(), equivalent_locale(), evaluateSleep(), exec_command(), ExecVacuum(), find_matching_ts_config(), get_collation_actual_version(), get_progname(), GetAttributeStorage(), GetCommandTagEnum(), getMetaCommand(), helpSQL(), 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(), ReadArrayStr(), 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 @143 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(), equivalent_locale(), float4in(), float8in_internal_opt_error(), get_collation_actual_version(), helpSQL(), 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(), 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:369

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 42 of file pgstrsignal.c.

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

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 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_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:295
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, select, and unlikely.

Referenced by _bt_pendingfsm_finalize(), auth_delay_checks(), AutoVacLauncherMain(), AutoVacWorkerMain(), BackendInitialize(), BackgroundWriterMain(), CheckpointerMain(), ConditionalXactLockTableWait(), CountOtherDBBackends(), CreateCheckPoint(), do_watch(), exec_prog(), FileRead(), FileWrite(), GetMultiXactIdMembers(), InitPostgres(), main(), perform_spin_delay(), pgarch_ArchiverCopyLoop(), pgwin32_recv(), read_local_xlog_page_guts(), regression_main(), RequestCheckpoint(), ResolveRecoveryConflictWithDatabase(), ResolveRecoveryConflictWithVirtualXIDs(), ServerLoop(), StartBackgroundWorker(), StartupXLOG(), StreamConnection(), threadRun(), 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:1483
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1321
void * palloc(Size size)
Definition: mcxt.c:1199
#define pg_log_warning(...)
Definition: pgfnames.c:24

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

Referenced by rmtree(), and 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)

References fn(), and pfree().

Referenced by rmtree(), and scan_available_timezones().

◆ pipe_read_line()

char* pipe_read_line ( char *  cmd,
char *  line,
int  maxsize 
)

Definition at line 387 of file exec.c.

388 {
389  FILE *pgver;
390 
391  fflush(NULL);
392 
393  errno = 0;
394  if ((pgver = popen(cmd, "r")) == NULL)
395  {
396  perror("popen failure");
397  return NULL;
398  }
399 
400  errno = 0;
401  if (fgets(line, maxsize, pgver) == NULL)
402  {
403  if (feof(pgver))
404  fprintf(stderr, "no data was returned by command \"%s\"\n", cmd);
405  else
406  perror("fgets failure");
407  pclose(pgver); /* no error checking */
408  return NULL;
409  }
410 
411  if (pclose_check(pgver))
412  return NULL;
413 
414  return line;
415 }
int pclose_check(FILE *stream)
Definition: exec.c:422
static void const char fflush(stdout)

References fflush(), fprintf, and pclose_check().

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

◆ pqsignal()

pqsigfunc pqsignal ( int  signo,
pqsigfunc  func 
)

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

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

References SIG_ERR, SIGALRM, and SIGCHLD.

Referenced by ApplyLauncherMain(), ApplyWorkerMain(), autoprewarm_database_main(), autoprewarm_main(), AutoVacLauncherMain(), AutoVacWorkerMain(), BackendInitialize(), BackgroundWriterMain(), bootstrap_signals(), CheckpointerMain(), disable_sigpipe_trap(), do_start(), InitializeLatchSupport(), InitializeTimeouts(), InitPostmasterChild(), main(), make_temp_sockdir(), OpenPipeStream(), ParallelBackupStart(), ParallelWorkerMain(), pg_crc32c_armv8_available(), PgArchiverMain(), plperl_init_interp(), PostgresMain(), PostmasterDeathSignalInit(), PQprint(), restore_sigpipe_trap(), setalarm(), setup_cancel_handler(), setup_signals(), ShutdownLatchSupport(), signal_remove_temp(), sigTermHandler(), StartBackgroundWorker(), StartupProcessMain(), SysLoggerMain(), test_shm_mq_main(), trap_sigint_during_startup(), trapsig(), WalReceiverMain(), WalSndSignals(), and WalWriterMain().

◆ qsort_arg()

◆ qsort_interruptible()

◆ rmtree()

bool rmtree ( const char *  path,
bool  rmtopdir 
)

Definition at line 42 of file rmtree.c.

43 {
44  bool result = true;
45  char pathbuf[MAXPGPATH];
46  char **filenames;
47  char **filename;
48  struct stat statbuf;
49 
50  /*
51  * we copy all the names out of the directory before we start modifying
52  * it.
53  */
54  filenames = pgfnames(path);
55 
56  if (filenames == NULL)
57  return false;
58 
59  /* now we have the names we can start removing things */
60  for (filename = filenames; *filename; filename++)
61  {
62  snprintf(pathbuf, MAXPGPATH, "%s/%s", path, *filename);
63 
64  /*
65  * It's ok if the file is not there anymore; we were just about to
66  * delete it anyway.
67  *
68  * This is not an academic possibility. One scenario where this
69  * happens is when bgwriter has a pending unlink request for a file in
70  * a database that's being dropped. In dropdb(), we call
71  * ForgetDatabaseSyncRequests() to flush out any such pending unlink
72  * requests, but because that's asynchronous, it's not guaranteed that
73  * the bgwriter receives the message in time.
74  */
75  if (lstat(pathbuf, &statbuf) != 0)
76  {
77  if (errno != ENOENT)
78  {
79  pg_log_warning("could not stat file or directory \"%s\": %m",
80  pathbuf);
81  result = false;
82  }
83  continue;
84  }
85 
86  if (S_ISDIR(statbuf.st_mode))
87  {
88  /* call ourselves recursively for a directory */
89  if (!rmtree(pathbuf, true))
90  {
91  /* we already reported the error */
92  result = false;
93  }
94  }
95  else
96  {
97  if (unlink(pathbuf) != 0)
98  {
99  if (errno != ENOENT)
100  {
101  pg_log_warning("could not remove file or directory \"%s\": %m",
102  pathbuf);
103  result = false;
104  }
105  }
106  }
107  }
108 
109  if (rmtopdir)
110  {
111  if (rmdir(path) != 0)
112  {
113  pg_log_warning("could not remove file or directory \"%s\": %m",
114  path);
115  result = false;
116  }
117  }
118 
119  pgfnames_cleanup(filenames);
120 
121  return result;
122 }
void pgfnames_cleanup(char **filenames)
Definition: pgfnames.c:86
char ** pgfnames(const char *path)
Definition: pgfnames.c:37
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:42
#define pg_log_warning(...)
Definition: rmtree.c:24
#define lstat(path, sb)
Definition: win32_port.h:287

References filename, lstat, MAXPGPATH, pg_log_warning, pgfnames(), pgfnames_cleanup(), S_ISDIR, snprintf, and stat::st_mode.

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 460 of file exec.c.

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

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 _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(), createNewConnection(), DCH_cache_getnew(), DefineRelation(), descriptor_variable(), DetermineTimeZoneAbbrevOffsetInternal(), ensureCleanShutdown(), ExecuteRecoveryCommand(), 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(), 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(), 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_file(), process_postgres_switches(), px_crypt_des(), recoveryStopsAfter(), RequestNamedLWLockTranche(), RequestXLogStreaming(), resolve_symlinks(), results_differ(), rot13_passphrase(), scan_available_timezones(), scan_directory(), scan_directory_ci(), SerializeLibraryState(), set_ps_display(), setup_bin_paths(), shell_archive_file(), SimpleLruInit(), SSLerrmessage(), tar_close(), timestamptz_to_str(), uuid_generate_internal(), validate_exec(), 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 80 of file exec.c.

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

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:160
#define WIFSIGNALED(w)
Definition: win32_port.h:161
#define WEXITSTATUS(w)
Definition: win32_port.h:162

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:163

References WEXITSTATUS, WIFEXITED, WIFSIGNALED, and WTERMSIG.

Referenced by ClosePipeFromProgram(), and RestoreArchivedFile().

◆ 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:42

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