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)
 
char * strsep (char **stringp, const char *delim)
 
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 513 of file port.h.

◆ HAVE_POLL

#define HAVE_POLL   1

Definition at line 514 of file port.h.

◆ HAVE_POLL_H

#define HAVE_POLL_H   1

Definition at line 515 of file port.h.

◆ HAVE_READLINK

#define HAVE_READLINK   1

Definition at line 516 of file port.h.

◆ HAVE_SETSID

#define HAVE_SETSID   1

Definition at line 517 of file port.h.

◆ HAVE_SHM_OPEN

#define HAVE_SHM_OPEN   1

Definition at line 518 of file port.h.

◆ HAVE_SYMLINK

#define HAVE_SYMLINK   1

Definition at line 519 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 481 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 447 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 490 of file port.h.

◆ qsort_arg_comparator

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

Definition at line 449 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 265 of file path.c.

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

188 {
189 #ifdef WIN32
190  char *ptr;
191 
192  /*
193  * GetShortPathName() will fail if the path does not exist, or short names
194  * are disabled on this file system. In both cases, we just return the
195  * original path. This is particularly useful for --sysconfdir, which
196  * might not exist.
197  */
198  GetShortPathName(path, path, MAXPGPATH - 1);
199 
200  /* Replace '\' with '/' */
201  for (ptr = path; *ptr; ptr++)
202  {
203  if (*ptr == '\\')
204  *ptr = '/';
205  }
206 #endif
207 }
#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:1163
#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:1004
#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:853
#define _(x)
Definition: elog.c:90
static char * argv0
Definition: pg_ctl.c:93
void join_path_components(char *ret_path, const char *head, const char *tail)
Definition: path.c:220
char * first_dir_separator(const char *filename)
Definition: path.c:105
void canonicalize_path(char *path)
Definition: path.c:265
char * first_path_var_separator(const char *pathlist)
Definition: path.c:122
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(), get_exec_path(), 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 310 of file exec.c.

312 {
313  char cmd[MAXPGPATH];
314  char *line;
315 
316  if (find_my_exec(argv0, retpath) < 0)
317  return -1;
318 
319  /* Trim off program name and keep just directory */
320  *last_dir_separator(retpath) = '\0';
321  canonicalize_path(retpath);
322 
323  /* Now append the other program's name */
324  snprintf(retpath + strlen(retpath), MAXPGPATH - strlen(retpath),
325  "/%s%s", target, EXE);
326 
327  if (validate_exec(retpath) != 0)
328  return -1;
329 
330  snprintf(cmd, sizeof(cmd), "\"%s\" -V", retpath);
331 
332  if ((line = pipe_read_line(cmd)) == NULL)
333  return -1;
334 
335  if (strcmp(line, versionstr) != 0)
336  {
337  pfree(line);
338  return -2;
339  }
340 
341  pfree(line);
342  return 0;
343 }
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:160
char * pipe_read_line(char *cmd)
Definition: exec.c:352
void pfree(void *pointer)
Definition: mcxt.c:1521
char * last_dir_separator(const char *filename)
Definition: path.c:140
#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(), get_exec_path(), getInstallationPaths(), getRestoreCommand(), isolation_start_test(), main(), and setup_bin_paths().

◆ first_dir_separator()

char* first_dir_separator ( const char *  filename)

Definition at line 105 of file path.c.

106 {
107  const char *p;
108 
109  for (p = skip_drive(filename); *p; p++)
110  if (IS_DIR_SEP(*p))
111  return unconstify(char *, p);
112  return NULL;
113 }
#define unconstify(underlying_type, expr)
Definition: c.h:1245
#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 122 of file path.c.

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

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:80
static void make_relative_path(char *ret_path, const char *target_path, const char *bin_path, const char *my_exec_path)
Definition: path.c:661

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 && home[0])
939  {
940  strlcpy(ret_path, home, MAXPGPATH);
941  return true;
942  }
943  else
944  {
945  struct passwd pwbuf;
946  struct passwd *pw;
947  char buf[1024];
948  int rc;
949 
950  rc = getpwuid_r(geteuid(), &pwbuf, buf, sizeof buf, &pw);
951  if (rc != 0 || !pw)
952  return false;
953  strlcpy(ret_path, pw->pw_dir, MAXPGPATH);
954  return true;
955  }
956 #else
957  char *tmppath;
958 
959  /*
960  * Note: We use getenv() here because the more modern SHGetFolderPath()
961  * would force the backend to link with shell32.lib, which eats valuable
962  * desktop heap. XXX This function is used only in psql, which already
963  * brings in shell32 via libpq. Moving this function to its own file
964  * would keep it out of the backend, freeing it from this concern.
965  */
966  tmppath = getenv("APPDATA");
967  if (!tmppath)
968  return false;
969  snprintf(ret_path, MAXPGPATH, "%s/postgresql", tmppath);
970  return true;
971 #endif
972 }

References buf, MAXPGPATH, 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 991 of file path.c.

992 {
993  trim_directory(path);
994 }

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

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

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

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:689
#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 220 of file path.c.

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

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

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

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

731 {
732  char *new;
733 
734  /* Returning null for null input is convenient for some callers */
735  if (path == NULL)
736  return NULL;
737 
738  if (!is_absolute_path(path))
739  {
740  char *buf;
741  size_t buflen;
742 
743  buflen = MAXPGPATH;
744  for (;;)
745  {
746  buf = malloc(buflen);
747  if (!buf)
748  {
749 #ifndef FRONTEND
750  ereport(ERROR,
751  (errcode(ERRCODE_OUT_OF_MEMORY),
752  errmsg("out of memory")));
753 #else
754  fprintf(stderr, _("out of memory\n"));
755  return NULL;
756 #endif
757  }
758 
759  if (getcwd(buf, buflen))
760  break;
761  else if (errno == ERANGE)
762  {
763  free(buf);
764  buflen *= 2;
765  continue;
766  }
767  else
768  {
769  int save_errno = errno;
770 
771  free(buf);
772  errno = save_errno;
773 #ifndef FRONTEND
774  elog(ERROR, "could not get current working directory: %m");
775 #else
776  fprintf(stderr, _("could not get current working directory: %m\n"));
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:1070
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define ereport(elevel,...)
Definition: elog.h:149
#define free(a)
Definition: header.h:65
void canonicalize_path(char *path)
Definition: path.c:265
#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 168 of file path.c.

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

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

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

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

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

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

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

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

392 {
393  int exitstatus;
394  char *reason;
395 
396  exitstatus = pclose(stream);
397 
398  if (exitstatus == 0)
399  return 0; /* all is well */
400 
401  if (exitstatus == -1)
402  {
403  /* pclose() itself failed, and hopefully set errno */
404  log_error(errcode(ERRCODE_SYSTEM_ERROR),
405  _("%s() failed: %m"), "pclose");
406  }
407  else
408  {
409  reason = wait_result_to_str(exitstatus);
410  log_error(errcode(ERRCODE_SYSTEM_ERROR),
411  "%s", reason);
412  pfree(reason);
413  }
414  return exitstatus;
415 }
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 
)

Definition at line 305 of file chklocale.c.

306 {
307  char *sys;
308  int i;
309 
310 #ifndef WIN32
311  locale_t loc;
312 #endif
313 
314  /* Get the CODESET property, and also LC_CTYPE if not passed in */
315  if (!ctype)
316  ctype = setlocale(LC_CTYPE, NULL);
317 
318 
319  /* If locale is C or POSIX, we can allow all encodings */
320  if (pg_strcasecmp(ctype, "C") == 0 ||
321  pg_strcasecmp(ctype, "POSIX") == 0)
322  return PG_SQL_ASCII;
323 
324 
325 #ifndef WIN32
326  loc = newlocale(LC_CTYPE_MASK, ctype, (locale_t) 0);
327  if (loc == (locale_t) 0)
328  return -1; /* bogus ctype passed in? */
329 
330  sys = nl_langinfo_l(CODESET, loc);
331  if (sys)
332  sys = strdup(sys);
333 
334  freelocale(loc);
335 #else
336  sys = win32_get_codeset(ctype);
337 #endif
338 
339  if (!sys)
340  return -1; /* out of memory; unlikely */
341 
342  /* Check the table */
343  for (i = 0; encoding_match_list[i].system_enc_name; i++)
344  {
345  if (pg_strcasecmp(sys, encoding_match_list[i].system_enc_name) == 0)
346  {
347  free(sys);
349  }
350  }
351 
352  /* Special-case kluges for particular platforms go here */
353 
354 #ifdef __darwin__
355 
356  /*
357  * Current macOS has many locales that report an empty string for CODESET,
358  * but they all seem to actually use UTF-8.
359  */
360  if (strlen(sys) == 0)
361  {
362  free(sys);
363  return PG_UTF8;
364  }
365 #endif
366 
367  /*
368  * We print a warning if we got a CODESET string but couldn't recognize
369  * it. This means we need another entry in the table.
370  */
371  if (write_message)
372  {
373 #ifdef FRONTEND
374  fprintf(stderr, _("could not determine encoding for locale \"%s\": codeset is \"%s\""),
375  ctype, sys);
376  /* keep newline separate so there's only one translatable string */
377  fputc('\n', stderr);
378 #else
380  (errmsg("could not determine encoding for locale \"%s\": codeset is \"%s\"",
381  ctype, sys)));
382 #endif
383  }
384 
385  free(sys);
386  return -1;
387 }
static const struct encoding_match encoding_match_list[]
Definition: chklocale.c:49
#define WARNING
Definition: elog.h:36
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
@ PG_UTF8
Definition: pg_wchar.h:232
enum pg_enc pg_enc_code
Definition: chklocale.c:45
const char * system_enc_name
Definition: chklocale.c:46
#define locale_t
Definition: win32_port.h:442
#define setlocale(a, b)
Definition: win32_port.h:485

Referenced by cache_locale_time(), check_encoding_locale_matches(), check_locale_encoding(), main(), PGLC_localeconv(), pqConnectOptions2(), PQsetClientEncoding(), and setup_locale_encoding().

◆ 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:1155
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_restrict_nonsystem_relation_kind(), check_usermap(), check_wal_consistency_checking(), comp_keyword_case_hook(), config_enum_lookup_by_name(), convert_any_priv_string(), createdb(), defGetBoolean(), defGetCopyHeaderChoice(), defGetCopyLogVerbosityChoice(), 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(), pgstat_register_kind(), 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 }
const char * str
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 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 @157 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, 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(), 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 156 of file pg_strong_random.c.

157 {
158  int f;
159  char *p = buf;
160  ssize_t res;
161 
162  f = open("/dev/urandom", O_RDONLY, 0);
163  if (f == -1)
164  return false;
165 
166  while (len)
167  {
168  res = read(f, p, len);
169  if (res <= 0)
170  {
171  if (errno == EINTR)
172  continue; /* interrupted by signal, just retry */
173 
174  close(f);
175  return false;
176  }
177 
178  p += res;
179  len -= res;
180  }
181 
182  close(f);
183  return true;
184 }
#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(), PostgresMain(), px_gen_salt(), set_random_seed(), and write_prefix().

◆ pg_strong_random_init()

void pg_strong_random_init ( void  )

Definition at line 150 of file pg_strong_random.c.

151 {
152  /* No initialization needed */
153 }

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(), pg_ctl_status(), 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(), 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(), and pg_tzset().

◆ 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:311
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(), 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_end_recovery(), 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:1696
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1541
void * palloc(Size size)
Definition: mcxt.c:1317
#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 352 of file exec.c.

353 {
354  FILE *pipe_cmd;
355  char *line;
356 
357  fflush(NULL);
358 
359  errno = 0;
360  if ((pipe_cmd = popen(cmd, "r")) == NULL)
361  {
362  log_error(errcode(ERRCODE_SYSTEM_ERROR),
363  _("could not execute command \"%s\": %m"), cmd);
364  return NULL;
365  }
366 
367  /* Make sure popen() didn't change errno */
368  errno = 0;
369  line = pg_get_line(pipe_cmd, NULL);
370 
371  if (line == NULL)
372  {
373  if (ferror(pipe_cmd))
375  _("could not read from command \"%s\": %m"), cmd);
376  else
377  log_error(errcode(ERRCODE_NO_DATA),
378  _("no data was returned by command \"%s\""), cmd);
379  }
380 
381  (void) pclose_check(pipe_cmd);
382 
383  return line;
384 }
int pclose_check(FILE *stream)
Definition: exec.c:391
int errcode_for_file_access(void)
Definition: elog.c:876
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:526
@ 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 429 of file exec.c.

430 {
431  char path[MAXPGPATH];
432  char my_exec_path[MAXPGPATH];
433 
434  /* don't set LC_ALL in the backend */
435  if (strcmp(app, PG_TEXTDOMAIN("postgres")) != 0)
436  {
437  setlocale(LC_ALL, "");
438 
439  /*
440  * One could make a case for reproducing here PostmasterMain()'s test
441  * for whether the process is multithreaded. Unlike the postmaster,
442  * no frontend program calls sigprocmask() or otherwise provides for
443  * mutual exclusion between signal handlers. While frontends using
444  * fork(), if multithreaded, are formally exposed to undefined
445  * behavior, we have not witnessed a concrete bug. Therefore,
446  * complaining about multithreading here may be mere pedantry.
447  */
448  }
449 
450  if (find_my_exec(argv0, my_exec_path) < 0)
451  return;
452 
453 #ifdef ENABLE_NLS
455  bindtextdomain(app, path);
456  textdomain(app);
457  /* set for libpq to use, but don't override existing setting */
458  setenv("PGLOCALEDIR", path, 0);
459 #endif
460 
461  if (getenv("PGSYSCONFDIR") == NULL)
462  {
463  get_etc_path(my_exec_path, path);
464  /* set for libpq to use */
465  setenv("PGSYSCONFDIR", path, 0);
466  }
467 }
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1214
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:555

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(), astreamer_inject_file(), astreamer_tar_header(), BaseBackup(), 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(), do_pg_backup_start(), 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_exec_path(), 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_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(), WaitEventCustomNew(), 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 str.

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

◆ strsep()

char* strsep ( char **  stringp,
const char *  delim 
)

Definition at line 49 of file strsep.c.

50 {
51  char *s;
52  const char *spanp;
53  int c,
54  sc;
55  char *tok;
56 
57  if ((s = *stringp) == NULL)
58  return (NULL);
59  for (tok = s;;)
60  {
61  c = *s++;
62  spanp = delim;
63  do
64  {
65  if ((sc = *spanp++) == c)
66  {
67  if (c == 0)
68  s = NULL;
69  else
70  s[-1] = 0;
71  *stringp = s;
72  return (tok);
73  }
74  } while (sc != 0);
75  }
76  /* NOTREACHED */
77 }

Referenced by parse_scram_secret(), pg_logging_init(), and split_to_stringlist().

◆ 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, 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(), modify_subscriber_sysid(), pclose_check(), RestoreArchivedFile(), run_ssl_passphrase_command(), and shell_finish_command().