PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
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 pqsignal   pqsignal_be
 
#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 canonicalize_path_enc (char *path, int encoding)
 
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)
 
int timingsafe_bcmp (const void *b1, const void *b2, size_t len)
 
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_localeconv_r (const char *lc_monetary, const char *lc_numeric, struct lconv *output)
 
void pg_localeconv_free (struct lconv *lconv)
 
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)
 
void 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:402
#define ECONNABORTED
Definition: win32_port.h:372
#define EHOSTUNREACH
Definition: win32_port.h:396
#define ETIMEDOUT
Definition: win32_port.h:406
#define ENETRESET
Definition: win32_port.h:400
#define EHOSTDOWN
Definition: win32_port.h:394
#define ENETDOWN
Definition: win32_port.h:398
#define ECONNRESET
Definition: win32_port.h:374

Definition at line 122 of file port.h.

◆ closesocket

#define closesocket   close

Definition at line 377 of file port.h.

◆ DEVNULL

#define DEVNULL   "/dev/null"

Definition at line 161 of file port.h.

◆ EXE

#define EXE   ""

Definition at line 155 of file port.h.

◆ fprintf

#define fprintf   pg_fprintf

Definition at line 243 of file port.h.

◆ HAVE_GETRLIMIT

#define HAVE_GETRLIMIT   1

Definition at line 556 of file port.h.

◆ HAVE_POLL

#define HAVE_POLL   1

Definition at line 557 of file port.h.

◆ HAVE_POLL_H

#define HAVE_POLL_H   1

Definition at line 558 of file port.h.

◆ HAVE_READLINK

#define HAVE_READLINK   1

Definition at line 559 of file port.h.

◆ HAVE_SETSID

#define HAVE_SETSID   1

Definition at line 560 of file port.h.

◆ HAVE_SHM_OPEN

#define HAVE_SHM_OPEN   1

Definition at line 561 of file port.h.

◆ HAVE_SYMLINK

#define HAVE_SYMLINK   1

Definition at line 562 of file port.h.

◆ is_absolute_path

#define is_absolute_path (   filename)    is_nonwindows_absolute_path(filename)

Definition at line 104 of file port.h.

◆ IS_DIR_SEP

#define IS_DIR_SEP (   ch)    IS_NONWINDOWS_DIR_SEP(ch)

Definition at line 103 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:125

Definition at line 83 of file port.h.

◆ IS_NONWINDOWS_DIR_SEP

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

Definition at line 82 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:88

Definition at line 90 of file port.h.

◆ IS_WINDOWS_DIR_SEP

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

Definition at line 88 of file port.h.

◆ pg_backend_random

#define pg_backend_random   pg_strong_random

Definition at line 519 of file port.h.

◆ PG_BACKEND_VERSIONSTR

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

Definition at line 144 of file port.h.

◆ PG_IOLBF

#define PG_IOLBF   _IOLBF

Definition at line 389 of file port.h.

◆ pg_pread

#define pg_pread   pread

Definition at line 226 of file port.h.

◆ pg_pwrite

#define pg_pwrite   pwrite

Definition at line 227 of file port.h.

◆ PG_STRERROR_R_BUFLEN

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

Definition at line 257 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 401 of file port.h.

◆ pqsignal

#define pqsignal   pqsignal_be

Definition at line 531 of file port.h.

◆ printf

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

Definition at line 245 of file port.h.

◆ qsort

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

Definition at line 479 of file port.h.

◆ snprintf

#define snprintf   pg_snprintf

Definition at line 239 of file port.h.

◆ sprintf

#define sprintf   pg_sprintf

Definition at line 241 of file port.h.

◆ strerror

#define strerror   pg_strerror

Definition at line 252 of file port.h.

◆ strerror_r

#define strerror_r   pg_strerror_r

Definition at line 256 of file port.h.

◆ TIMEZONE_GLOBAL

#define TIMEZONE_GLOBAL   timezone

Definition at line 269 of file port.h.

◆ TZNAME_GLOBAL

#define TZNAME_GLOBAL   tzname

Definition at line 270 of file port.h.

◆ USE_REPL_SNPRINTF

#define USE_REPL_SNPRINTF   1

Definition at line 180 of file port.h.

◆ vfprintf

#define vfprintf   pg_vfprintf

Definition at line 242 of file port.h.

◆ vprintf

#define vprintf   pg_vprintf

Definition at line 244 of file port.h.

◆ vsnprintf

#define vsnprintf   pg_vsnprintf

Definition at line 238 of file port.h.

◆ vsprintf

#define vsprintf   pg_vsprintf

Definition at line 240 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 533 of file port.h.

◆ qsort_arg_comparator

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

Definition at line 481 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 size_t lim;
62 int 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

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

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

◆ canonicalize_path()

◆ canonicalize_path_enc()

void canonicalize_path_enc ( char *  path,
int  encoding 
)

Definition at line 344 of file path.c.

345{
346 char *p,
347 *to_p;
348 char *spath;
349 char *parsed;
350 char *unparse;
351 bool was_sep = false;
353 int pathdepth = 0; /* counts collected regular directory names */
354
355#ifdef WIN32
356
357 /*
358 * The Windows command processor will accept suitably quoted paths with
359 * forward slashes, but barfs badly with mixed forward and back slashes.
360 * Hence, start by converting all back slashes to forward slashes.
361 */
362 debackslash_path(path, encoding);
363
364 /*
365 * In Win32, if you do: prog.exe "a b" "\c\d\" the system will pass \c\d"
366 * as argv[2], so trim off trailing quote.
367 */
368 p = path + strlen(path);
369 if (p > path && *(p - 1) == '"')
370 *(p - 1) = '/';
371#endif
372
373 /*
374 * Removing the trailing slash on a path means we never get ugly double
375 * trailing slashes. Also, Win32 can't stat() a directory with a trailing
376 * slash. Don't remove a leading slash, though.
377 */
379
380 /*
381 * Remove duplicate adjacent separators
382 */
383 p = path;
384#ifdef WIN32
385 /* Don't remove leading double-slash on Win32 */
386 if (*p)
387 p++;
388#endif
389 to_p = p;
390 for (; *p; p++, to_p++)
391 {
392 /* Handle many adjacent slashes, like "/a///b" */
393 while (*p == '/' && was_sep)
394 p++;
395 if (to_p != p)
396 *to_p = *p;
397 was_sep = (*p == '/');
398 }
399 *to_p = '\0';
400
401 /*
402 * Remove any uses of "." and process ".." ourselves
403 *
404 * Note that "/../.." should reduce to just "/", while "../.." has to be
405 * kept as-is. Also note that we want a Windows drive spec to be visible
406 * to trim_directory(), but it's not part of the logic that's looking at
407 * the name components; hence distinction between path and spath.
408 *
409 * This loop overwrites the path in-place. This is safe since we'll never
410 * make the path longer. "unparse" points to where we are reading the
411 * path, "parse" to where we are writing.
412 */
413 spath = skip_drive(path);
414 if (*spath == '\0')
415 return; /* empty path is returned as-is */
416
417 if (*spath == '/')
418 {
420 /* Skip the leading slash for absolute path */
421 parsed = unparse = (spath + 1);
422 }
423 else
424 {
426 parsed = unparse = spath;
427 }
428
429 while (*unparse != '\0')
430 {
431 char *unparse_next;
432 bool is_double_dot;
433
434 /* Split off this dir name, and set unparse_next to the next one */
435 unparse_next = unparse;
436 while (*unparse_next && *unparse_next != '/')
437 unparse_next++;
438 if (*unparse_next != '\0')
439 *unparse_next++ = '\0';
440
441 /* Identify type of this dir name */
442 if (strcmp(unparse, ".") == 0)
443 {
444 /* We can ignore "." components in all cases */
445 unparse = unparse_next;
446 continue;
447 }
448
449 if (strcmp(unparse, "..") == 0)
450 is_double_dot = true;
451 else
452 {
453 /* adjacent separators were eliminated above */
454 Assert(*unparse != '\0');
455 is_double_dot = false;
456 }
457
458 switch (state)
459 {
461 /* We can ignore ".." immediately after / */
462 if (!is_double_dot)
463 {
464 /* Append first dir name (we already have leading slash) */
465 parsed = append_subdir_to_path(parsed, unparse);
467 pathdepth++;
468 }
469 break;
471 if (is_double_dot)
472 {
473 /* Remove last parsed dir */
474 /* (trim_directory won't remove the leading slash) */
475 *parsed = '\0';
476 parsed = trim_directory(path);
477 if (--pathdepth == 0)
479 }
480 else
481 {
482 /* Append normal dir */
483 *parsed++ = '/';
484 parsed = append_subdir_to_path(parsed, unparse);
485 pathdepth++;
486 }
487 break;
489 if (is_double_dot)
490 {
491 /* Append irreducible double-dot (..) */
492 parsed = append_subdir_to_path(parsed, unparse);
494 }
495 else
496 {
497 /* Append normal dir */
498 parsed = append_subdir_to_path(parsed, unparse);
500 pathdepth++;
501 }
502 break;
504 if (is_double_dot)
505 {
506 /* Remove last parsed dir */
507 *parsed = '\0';
508 parsed = trim_directory(path);
509 if (--pathdepth == 0)
510 {
511 /*
512 * If the output path is now empty, we're back to the
513 * INIT state. However, we could have processed a
514 * path like "../dir/.." and now be down to "..", in
515 * which case enter the correct state for that.
516 */
517 if (parsed == spath)
519 else
521 }
522 }
523 else
524 {
525 /* Append normal dir */
526 *parsed++ = '/';
527 parsed = append_subdir_to_path(parsed, unparse);
528 pathdepth++;
529 }
530 break;
532 if (is_double_dot)
533 {
534 /* Append next irreducible double-dot (..) */
535 *parsed++ = '/';
536 parsed = append_subdir_to_path(parsed, unparse);
537 }
538 else
539 {
540 /* Append normal dir */
541 *parsed++ = '/';
542 parsed = append_subdir_to_path(parsed, unparse);
543
544 /*
545 * We can now start counting normal dirs. But if later
546 * double-dots make us remove this dir again, we'd better
547 * revert to RELATIVE_WITH_PARENT_REF not INIT state.
548 */
550 pathdepth = 1;
551 }
552 break;
553 }
554
555 unparse = unparse_next;
556 }
557
558 /*
559 * If our output path is empty at this point, insert ".". We don't want
560 * to do this any earlier because it'd result in an extra dot in corner
561 * cases such as "../dir/..". Since we rejected the wholly-empty-path
562 * case above, there is certainly room.
563 */
564 if (parsed == spath)
565 *parsed++ = '.';
566
567 /* And finally, ensure the output path is nul-terminated. */
568 *parsed = '\0';
569}
Assert(PointerIsAligned(start, uint64))
static char * append_subdir_to_path(char *path, char *subdir)
Definition: path.c:1139
static void trim_trailing_separator(char *path)
Definition: path.c:1117
static char * trim_directory(char *path)
Definition: path.c:1085
#define skip_drive(path)
Definition: path.c:85
canonicalize_state
Definition: path.c:310
@ ABSOLUTE_WITH_N_DEPTH
Definition: path.c:313
@ RELATIVE_WITH_N_DEPTH
Definition: path.c:316
@ ABSOLUTE_PATH_INIT
Definition: path.c:311
@ RELATIVE_PATH_INIT
Definition: path.c:315
@ RELATIVE_WITH_PARENT_REF
Definition: path.c:318
int32 encoding
Definition: pg_database.h:41
Definition: regguts.h:323

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

Referenced by canonicalize_path(), do_copy(), exec_command_edit(), exec_command_write(), and process_file().

◆ cleanup_path()

void cleanup_path ( char *  path)

Definition at line 258 of file path.c.

259{
260#ifdef WIN32
261 /*
262 * GetShortPathName() will fail if the path does not exist, or short names
263 * are disabled on this file system. In both cases, we just return the
264 * original path. This is particularly useful for --sysconfdir, which
265 * might not exist.
266 */
267 GetShortPathName(path, path, MAXPGPATH - 1);
268
269 /* Replace '\' with '/' */
270 /* All server-safe encodings are alike here, so just use PG_SQL_ASCII */
271 debackslash_path(path, PG_SQL_ASCII);
272#endif
273}
#define MAXPGPATH

References MAXPGPATH, and PG_SQL_ASCII.

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:1134
#define malloc(a)
Definition: header.h:50
int j
Definition: isn.c:78
int i
Definition: isn.c:77
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:72

References buf, bzero_p, and len.

Referenced by freePGconn(), oauth_exchange(), passwordFromFile(), pg_cryptohash_create(), pg_cryptohash_free(), pg_hmac_create(), pg_hmac_free(), pqClearOAuthToken(), 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:975
#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:854
#define _(x)
Definition: elog.c:91
static char * argv0
Definition: pg_ctl.c:93
void join_path_components(char *ret_path, const char *head, const char *tail)
Definition: path.c:286
char * first_path_var_separator(const char *pathlist)
Definition: path.c:127
void canonicalize_path(char *path)
Definition: path.c:337
char * first_dir_separator(const char *filename)
Definition: path.c:110
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:1524
char * last_dir_separator(const char *filename)
Definition: path.c:145
#define snprintf
Definition: port.h:239
#define EXE
Definition: port.h:155

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

111{
112 const char *p;
113
114 for (p = skip_drive(filename); *p; p++)
115 if (IS_DIR_SEP(*p))
116 return unconstify(char *, p);
117 return NULL;
118}
#define unconstify(underlying_type, expr)
Definition: c.h:1216
#define IS_DIR_SEP(ch)
Definition: port.h:103

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_path(), find_my_exec(), load_libraries(), and substitute_path_macro().

◆ first_path_var_separator()

char * first_path_var_separator ( const char *  pathlist)

Definition at line 127 of file path.c.

128{
129 const char *p;
130
131 /* skip_drive is not needed */
132 for (p = pathlist; *p; p++)
133 if (IS_PATH_VAR_SEP(*p))
134 return unconstify(char *, p);
135 return NULL;
136}
#define IS_PATH_VAR_SEP(ch)
Definition: path.c:44

References IS_PATH_VAR_SEP, and unconstify.

Referenced by find_in_path(), find_my_exec(), and get_extension_control_directories().

◆ get_doc_path()

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

Definition at line 974 of file path.c.

975{
976 make_relative_path(ret_path, DOCDIR, PGBINDIR, my_exec_path);
977}
char my_exec_path[MAXPGPATH]
Definition: globals.c:81
static void make_relative_path(char *ret_path, const char *target_path, const char *bin_path, const char *my_exec_path)
Definition: path.c:738

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

912{
913 make_relative_path(ret_path, SYSCONFDIR, PGBINDIR, my_exec_path);
914}

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

1006{
1007#ifndef WIN32
1008 /*
1009 * We first consult $HOME. If that's unset, try to get the info from
1010 * <pwd.h>.
1011 */
1012 const char *home;
1013
1014 home = getenv("HOME");
1015 if (home && home[0])
1016 {
1017 strlcpy(ret_path, home, MAXPGPATH);
1018 return true;
1019 }
1020 else
1021 {
1022 struct passwd pwbuf;
1023 struct passwd *pw;
1024 char buf[1024];
1025 int rc;
1026
1027 rc = getpwuid_r(geteuid(), &pwbuf, buf, sizeof buf, &pw);
1028 if (rc != 0 || !pw)
1029 return false;
1030 strlcpy(ret_path, pw->pw_dir, MAXPGPATH);
1031 return true;
1032 }
1033#else
1034 char *tmppath;
1035
1036 /*
1037 * Note: We use getenv() here because the more modern SHGetFolderPath()
1038 * would force the backend to link with shell32.lib, which eats valuable
1039 * desktop heap. XXX This function is used only in psql, which already
1040 * brings in shell32 via libpq. Moving this function to its own file
1041 * would keep it out of the backend, freeing it from this concern.
1042 */
1043 tmppath = getenv("APPDATA");
1044 if (!tmppath)
1045 return false;
1046 snprintf(ret_path, MAXPGPATH, "%s/postgresql", tmppath);
1047 return true;
1048#endif
1049}

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

984{
985 make_relative_path(ret_path, HTMLDIR, PGBINDIR, my_exec_path);
986}

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

921{
922 make_relative_path(ret_path, INCLUDEDIR, PGBINDIR, my_exec_path);
923}

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

939{
940 make_relative_path(ret_path, INCLUDEDIRSERVER, PGBINDIR, my_exec_path);
941}

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

948{
949 make_relative_path(ret_path, LIBDIR, PGBINDIR, my_exec_path);
950}

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

966{
967 make_relative_path(ret_path, LOCALEDIR, PGBINDIR, my_exec_path);
968}

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

993{
994 make_relative_path(ret_path, MANDIR, PGBINDIR, my_exec_path);
995}

References make_relative_path(), and my_exec_path.

Referenced by get_configdata().

◆ get_parent_directory()

void get_parent_directory ( char *  path)

Definition at line 1068 of file path.c.

1069{
1070 trim_directory(path);
1071}

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

930{
931 make_relative_path(ret_path, PKGINCLUDEDIR, PGBINDIR, my_exec_path);
932}

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

957{
958 make_relative_path(ret_path, PKGLIBDIR, PGBINDIR, my_exec_path);
959}

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

653{
654 const char *nodir_name;
655 char *progname;
656
657 nodir_name = last_dir_separator(argv0);
658 if (nodir_name)
659 nodir_name++;
660 else
661 nodir_name = skip_drive(argv0);
662
663 /*
664 * Make a copy in case argv[0] is modified by ps_status. Leaks memory, but
665 * called only once.
666 */
667 progname = strdup(nodir_name);
668 if (progname == NULL)
669 {
670 fprintf(stderr, "%s: out of memory\n", nodir_name);
671 abort(); /* This could exit the postmaster */
672 }
673
674#if defined(__CYGWIN__) || defined(WIN32)
675 /* strip ".exe" suffix, regardless of case */
676 if (strlen(progname) > sizeof(EXE) - 1 &&
677 pg_strcasecmp(progname + strlen(progname) - (sizeof(EXE) - 1), EXE) == 0)
678 progname[strlen(progname) - (sizeof(EXE) - 1)] = '\0';
679#endif
680
681 return progname;
682}
#define fprintf(file, fmt, msg)
Definition: cubescan.l:21
const char * progname
Definition: main.c:44
char * last_dir_separator(const char *filename)
Definition: path.c:145
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36

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:235
int uid_t
Definition: win32_port.h:234

Referenced by auth_peer(), and PQconnectPoll().

◆ has_drive_prefix()

bool has_drive_prefix ( const char *  path)

Definition at line 94 of file path.c.

95{
96#ifdef WIN32
97 return skip_drive(path) != path;
98#else
99 return false;
100#endif
101}

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

288{
289 if (ret_path != head)
290 strlcpy(ret_path, head, MAXPGPATH);
291
292 /*
293 * We used to try to simplify some cases involving "." and "..", but now
294 * we just leave that to be done by canonicalize_path() later.
295 */
296
297 if (*tail)
298 {
299 /* only separate with slash if head wasn't empty */
300 snprintf(ret_path + strlen(ret_path), MAXPGPATH - strlen(ret_path),
301 "%s%s",
302 (*(skip_drive(head)) != '\0') ? "/" : "",
303 tail);
304 }
305}

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

146{
147 const char *p,
148 *ret = NULL;
149
150 for (p = skip_drive(filename); *p; p++)
151 if (IS_DIR_SEP(*p))
152 ret = p;
153 return unconstify(char *, ret);
154}

References filename, IS_DIR_SEP, skip_drive, and unconstify.

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

◆ make_absolute_path()

char * make_absolute_path ( const char *  path)

Definition at line 807 of file path.c.

808{
809 char *new;
810
811 /* Returning null for null input is convenient for some callers */
812 if (path == NULL)
813 return NULL;
814
815 if (!is_absolute_path(path))
816 {
817 char *buf;
818 size_t buflen;
819
820 buflen = MAXPGPATH;
821 for (;;)
822 {
823 buf = malloc(buflen);
824 if (!buf)
825 {
826#ifndef FRONTEND
828 (errcode(ERRCODE_OUT_OF_MEMORY),
829 errmsg("out of memory")));
830#else
831 fprintf(stderr, _("out of memory\n"));
832 return NULL;
833#endif
834 }
835
836 if (getcwd(buf, buflen))
837 break;
838 else if (errno == ERANGE)
839 {
840 free(buf);
841 buflen *= 2;
842 continue;
843 }
844 else
845 {
846 int save_errno = errno;
847
848 free(buf);
849 errno = save_errno;
850#ifndef FRONTEND
851 elog(ERROR, "could not get current working directory: %m");
852#else
853 fprintf(stderr, _("could not get current working directory: %m\n"));
854 return NULL;
855#endif
856 }
857 }
858
859 new = malloc(strlen(buf) + strlen(path) + 2);
860 if (!new)
861 {
862 free(buf);
863#ifndef FRONTEND
865 (errcode(ERRCODE_OUT_OF_MEMORY),
866 errmsg("out of memory")));
867#else
868 fprintf(stderr, _("out of memory\n"));
869 return NULL;
870#endif
871 }
872 sprintf(new, "%s/%s", buf, path);
873 free(buf);
874 }
875 else
876 {
877 new = strdup(path);
878 if (!new)
879 {
880#ifndef FRONTEND
882 (errcode(ERRCODE_OUT_OF_MEMORY),
883 errmsg("out of memory")));
884#else
885 fprintf(stderr, _("out of memory\n"));
886 return NULL;
887#endif
888 }
889 }
890
891 /* Make sure punctuation is canonical, too */
893
894 return new;
895}
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
#define ereport(elevel,...)
Definition: elog.h:149
#define free(a)
Definition: header.h:65
void canonicalize_path(char *path)
Definition: path.c:337
#define is_absolute_path(filename)
Definition: port.h:104
#define sprintf
Definition: port.h:241

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

237{
238#ifdef WIN32
239 char *p;
240
241 for (p = filename; *p; p++)
242 if (*p == '/')
243 *p = '\\';
244#endif
245}

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

578{
579 /*
580 * Once canonicalized, an absolute path cannot contain any ".." at all,
581 * while a relative path could contain ".."(s) only at the start. So it
582 * is sufficient to check the start of the path, after skipping any
583 * Windows drive/network specifier.
584 */
585 path = skip_drive(path); /* C: shouldn't affect our conclusion */
586
587 if (path[0] == '.' &&
588 path[1] == '.' &&
589 (path[2] == '\0' || path[2] == '/'))
590 return true;
591
592 return false;
593}

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

638{
639 int path1_len = strlen(path1);
640
641 if (strncmp(path1, path2, path1_len) == 0 &&
642 (IS_DIR_SEP(path2[path1_len]) || path2[path1_len] == '\0'))
643 return true;
644 return false;
645}

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

605{
606 if (is_absolute_path(path))
607 return false;
608 /* don't allow anything above the cwd */
609 else if (path_contains_parent_reference(path))
610 return false;
611#ifdef WIN32
612
613 /*
614 * On Win32, a drive letter _not_ followed by a slash, e.g. 'E:abc', is
615 * relative to the cwd on that drive, or the drive's root directory if
616 * that drive has no cwd. Because the path itself cannot tell us which is
617 * the case, we have to assume the worst, i.e. that it is not below the
618 * cwd. We could use GetFullPathName() to find the full path but that
619 * could change if the current directory for the drive changes underneath
620 * us, so we just disallow it.
621 */
622 else if (isalpha((unsigned char) path[0]) && path[1] == ':' &&
623 !IS_DIR_SEP(path[2]))
624 return false;
625#endif
626 else
627 return true;
628}
bool path_contains_parent_reference(const char *path)
Definition: path.c:577

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(), pg_wc_toupper(), and roman_to_int().

◆ 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_or_open_dir(), 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 301 of file chklocale.c.

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

References _, encoding_match_list, ereport, errmsg(), fprintf, free, i, locale_t, encoding_match::pg_enc_code, PG_SQL_ASCII, pg_strcasecmp(), PG_UTF8, setlocale, encoding_match::system_enc_name, and WARNING.

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

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

void pg_localeconv_free ( struct lconv *  lconv)

Definition at line 104 of file pg_localeconv_r.c.

105{
106 for (int i = 0; i < lengthof(table); ++i)
107 if (table[i].is_string)
108 free(*lconv_string_member(lconv, i));
109}
#define lengthof(array)
Definition: c.h:759
static char ** lconv_string_member(struct lconv *lconv, int i)
static const struct lconv_member_info table[]

References free, i, lconv_member_info::is_string, lconv_string_member(), lengthof, and table.

Referenced by pg_localeconv_copy_members(), and PGLC_localeconv().

◆ pg_localeconv_r()

int pg_localeconv_r ( const char *  lc_monetary,
const char *  lc_numeric,
struct lconv *  output 
)

Definition at line 231 of file pg_localeconv_r.c.

234{
235#ifdef WIN32
236 wchar_t *save_lc_ctype = NULL;
237 wchar_t *save_lc_monetary = NULL;
238 wchar_t *save_lc_numeric = NULL;
239 int save_config_thread_locale;
240 int result = -1;
241
242 /* Put setlocale() into thread-local mode. */
243 save_config_thread_locale = _configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
244
245 /*
246 * Capture the current values as wide strings. Otherwise, we might not be
247 * able to restore them if their names contain non-ASCII characters and
248 * the intermediate locale changes the expected encoding. We don't want
249 * to leave the caller in an unexpected state by failing to restore, or
250 * crash the runtime library.
251 */
252 save_lc_ctype = _wsetlocale(LC_CTYPE, NULL);
253 if (!save_lc_ctype || !(save_lc_ctype = wcsdup(save_lc_ctype)))
254 goto exit;
255 save_lc_monetary = _wsetlocale(LC_MONETARY, NULL);
256 if (!save_lc_monetary || !(save_lc_monetary = wcsdup(save_lc_monetary)))
257 goto exit;
258 save_lc_numeric = _wsetlocale(LC_NUMERIC, NULL);
259 if (!save_lc_numeric || !(save_lc_numeric = wcsdup(save_lc_numeric)))
260 goto exit;
261
262 memset(output, 0, sizeof(*output));
263
264 /* Copy the LC_MONETARY members. */
265 if (!setlocale(LC_ALL, lc_monetary))
266 goto exit;
267 result = pg_localeconv_copy_members(output, localeconv(), LC_MONETARY);
268 if (result != 0)
269 goto exit;
270
271 /* Copy the LC_NUMERIC members. */
272 if (!setlocale(LC_ALL, lc_numeric))
273 goto exit;
274 result = pg_localeconv_copy_members(output, localeconv(), LC_NUMERIC);
275
276exit:
277 /* Restore everything we changed. */
278 if (save_lc_ctype)
279 {
280 _wsetlocale(LC_CTYPE, save_lc_ctype);
281 free(save_lc_ctype);
282 }
283 if (save_lc_monetary)
284 {
285 _wsetlocale(LC_MONETARY, save_lc_monetary);
286 free(save_lc_monetary);
287 }
288 if (save_lc_numeric)
289 {
290 _wsetlocale(LC_NUMERIC, save_lc_numeric);
291 free(save_lc_numeric);
292 }
293 _configthreadlocale(save_config_thread_locale);
294
295 return result;
296
297#else /* !WIN32 */
298 locale_t monetary_locale;
299 locale_t numeric_locale;
300 int result;
301
302 /*
303 * All variations on Unix require locale_t objects for LC_MONETARY and
304 * LC_NUMERIC. We'll set all locale categories, so that we can don't have
305 * to worry about POSIX's undefined behavior if LC_CTYPE's encoding
306 * doesn't match.
307 */
308 errno = ENOENT;
309 monetary_locale = newlocale(LC_ALL_MASK, lc_monetary, 0);
310 if (monetary_locale == 0)
311 return -1;
312 numeric_locale = newlocale(LC_ALL_MASK, lc_numeric, 0);
313 if (numeric_locale == 0)
314 {
315 freelocale(monetary_locale);
316 return -1;
317 }
318
319 memset(output, 0, sizeof(*output));
320#if defined(TRANSLATE_FROM_LANGINFO)
321 /* Copy from non-standard nl_langinfo_l() extended items. */
322 result = pg_localeconv_from_langinfo(output,
323 monetary_locale,
324 numeric_locale);
325#elif defined(HAVE_LOCALECONV_L)
326 /* Copy the LC_MONETARY members from a thread-safe lconv object. */
328 localeconv_l(monetary_locale),
329 LC_MONETARY);
330 if (result == 0)
331 {
332 /* Copy the LC_NUMERIC members from a thread-safe lconv object. */
334 localeconv_l(numeric_locale),
335 LC_NUMERIC);
336 }
337#else
338 /* We have nothing better than standard POSIX facilities. */
339 {
341 locale_t save_locale;
342
343 pthread_mutex_lock(&big_lock);
344 /* Copy the LC_MONETARY members. */
345 save_locale = uselocale(monetary_locale);
347 localeconv(),
348 LC_MONETARY);
349 if (result == 0)
350 {
351 /* Copy the LC_NUMERIC members. */
352 uselocale(numeric_locale);
354 localeconv(),
355 LC_NUMERIC);
356 }
357 pthread_mutex_unlock(&big_lock);
358
359 uselocale(save_locale);
360 }
361#endif
362
363 freelocale(monetary_locale);
364 freelocale(numeric_locale);
365
366 return result;
367#endif /* !WIN32 */
368}
FILE * output
static char * lc_numeric
Definition: initdb.c:144
static char * lc_monetary
Definition: initdb.c:143
static int pg_localeconv_copy_members(struct lconv *dst, struct lconv *src, int category)
int pthread_mutex_unlock(pthread_mutex_t *mp)
Definition: pthread-win32.c:60
int pthread_mutex_lock(pthread_mutex_t *mp)
Definition: pthread-win32.c:42
#define PTHREAD_MUTEX_INITIALIZER
Definition: pthread-win32.h:16

References free, lc_monetary, lc_numeric, locale_t, output, pg_localeconv_copy_members(), PTHREAD_MUTEX_INITIALIZER, pthread_mutex_lock(), pthread_mutex_unlock(), and setlocale.

Referenced by PGLC_localeconv().

◆ 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:274
#define S_IRWXG
Definition: win32_port.h:300
#define S_IRWXO
Definition: win32_port.h:312
#define S_ISDIR(m)
Definition: win32_port.h:315
#define mkdir(a, b)
Definition: win32_port.h:80
#define S_IWUSR
Definition: win32_port.h:282
#define S_IXUSR
Definition: win32_port.h:285
#define S_IRWXU
Definition: win32_port.h:288

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(), prepare_for_swap(), 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:74
int a
Definition: isn.c:73

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:1126
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(), defGetGeneratedColsOption(), 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_arg_by_name(), get_collation_actual_version_libc(), get_dbnames_list_to_restore(), 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(), parseCommandLine(), parseDumpFormat(), parseNameAndArgTypes(), ParseVariableBool(), pg_checksum_parse_type(), pg_fe_sendauth(), pg_find_encoding(), pg_get_encoding_from_locale(), 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(), stats_fill_fcinfo_from_arg_pairs(), SyncRepGetStandbyPriority(), unicode_norm_form_from_string(), validate_exec(), validate_log_connections_options(), 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:257
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 1318 of file snprintf.c.

1319{
1320 PrintfTarget target;
1321 int signvalue = 0;
1322 int vallen;
1323 char fmt[8];
1324 char convert[64];
1325
1326 /* Set up the target like pg_snprintf, but require nonempty buffer */
1327 Assert(count > 0);
1328 target.bufstart = target.bufptr = str;
1329 target.bufend = str + count - 1;
1330 target.stream = NULL;
1331 target.nchars = 0;
1332 target.failed = false;
1333
1334 /*
1335 * We bound precision to a reasonable range; the combination of this and
1336 * the knowledge that we're using "g" format without padding allows the
1337 * convert[] buffer to be reasonably small.
1338 */
1339 if (precision < 1)
1340 precision = 1;
1341 else if (precision > 32)
1342 precision = 32;
1343
1344 /*
1345 * The rest is just an inlined version of the fmtfloat() logic above,
1346 * simplified using the knowledge that no padding is wanted.
1347 */
1348 if (isnan(value))
1349 {
1350 strcpy(convert, "NaN");
1351 vallen = 3;
1352 }
1353 else
1354 {
1355 static const double dzero = 0.0;
1356
1357 if (value < 0.0 ||
1358 (value == 0.0 &&
1359 memcmp(&value, &dzero, sizeof(double)) != 0))
1360 {
1361 signvalue = '-';
1362 value = -value;
1363 }
1364
1365 if (isinf(value))
1366 {
1367 strcpy(convert, "Infinity");
1368 vallen = 8;
1369 }
1370 else
1371 {
1372 fmt[0] = '%';
1373 fmt[1] = '.';
1374 fmt[2] = '*';
1375 fmt[3] = 'g';
1376 fmt[4] = '\0';
1377 vallen = snprintf(convert, sizeof(convert), fmt, precision, value);
1378 if (vallen < 0)
1379 {
1380 target.failed = true;
1381 goto fail;
1382 }
1383
1384#ifdef WIN32
1385 if (vallen >= 6 &&
1386 convert[vallen - 5] == 'e' &&
1387 convert[vallen - 3] == '0')
1388 {
1389 convert[vallen - 3] = convert[vallen - 2];
1390 convert[vallen - 2] = convert[vallen - 1];
1391 vallen--;
1392 }
1393#endif
1394 }
1395 }
1396
1397 if (signvalue)
1398 dopr_outch(signvalue, &target);
1399
1400 dostr(convert, vallen, &target);
1401
1402fail:
1403 *(target.bufptr) = '\0';
1404 return target.failed ? -1 : (target.bufptr - target.bufstart
1405 + target.nchars);
1406}
static struct @165 value
static void dostr(const char *str, int slen, PrintfTarget *target)
Definition: snprintf.c:1410
static void dopr_outch(int c, PrintfTarget *target)
Definition: snprintf.c:1447
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, 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_content_type(), check_datestyle(), check_for_device_flow(), check_special_value(), check_timezone(), checkKeyword(), command_no_begin(), do_pset(), float4in_internal(), float8in_internal(), get_collation_actual_version_libc(), helpSQL(), issuer_from_well_known_uri(), 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(), SpecialTags(), and validate_token_format().

◆ pg_strong_random()

bool pg_strong_random ( void *  buf,
size_t  len 
)

Definition at line 150 of file pg_strong_random.c.

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

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

Referenced by build_client_first_message(), build_server_first_message(), CheckMD5Auth(), gen_random_uuid(), generate_uuidv7(), 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 144 of file pg_strong_random.c.

145{
146 /* No initialization needed */
147}

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(), dequote_downcase_identifier(), dir_strcmp(), ParseDateTime(), patternToSQLRegex(), PGTYPESdate_defmt_asc(), PQfnumber(), SB_lower_char(), strlower_libc_sb(), strtitle_libc_sb(), 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_abbrevs(), pg_tzset(), strtitle_libc_sb(), strupper_libc_sb(), and TimeZoneAbbrevIsKnown().

◆ 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:347
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(), AutoVacLauncherMain(), 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:1699
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1544
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:877
char * pg_get_line(FILE *stream, PromptInterruptContext *prompt_ctx)
Definition: pg_get_line.c:59

References _, errcode(), errcode_for_file_access(), 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 42 of file legacy-pqsignal.c.

43{
44#ifndef WIN32
45 struct sigaction act,
46 oact;
47
48 act.sa_handler = func;
49 sigemptyset(&act.sa_mask);
50 act.sa_flags = 0;
51 if (signo != SIGALRM)
52 act.sa_flags |= SA_RESTART;
53#ifdef SA_NOCLDSTOP
54 if (signo == SIGCHLD)
55 act.sa_flags |= SA_NOCLDSTOP;
56#endif
57 if (sigaction(signo, &act, &oact) < 0)
58 return SIG_ERR;
59 return oact.sa_handler;
60#else /* WIN32 */
61 return signal(signo, func);
62#endif
63}
#define SIGCHLD
Definition: win32_port.h:168
#define SIGALRM
Definition: win32_port.h:164

References SIGALRM, and SIGCHLD.

◆ 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 {
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:547
@ 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(), rmtree(), 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(), rmtree(), 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];
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
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 {
464 /* set for libpq to use */
465 setenv("PGSYSCONFDIR", path, 0);
466 }
467}
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1185
void get_locale_path(const char *my_exec_path, char *ret_path)
Definition: path.c:965
void get_etc_path(const char *my_exec_path, char *ret_path)
Definition: path.c:911
#define setenv(x, y, z)
Definition: win32_port.h:545

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(), DecodeTimezoneAbbrev(), DefineRelation(), descriptor_variable(), DetermineTimeZoneAbbrevOffsetInternal(), do_pg_backup_start(), ensureCleanShutdown(), expand_tilde(), fetch_fp_info(), find_in_path(), 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_extension_control_directories(), 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(), parse_include(), ParseAbortRecord(), parseCommandLine(), ParseCommitRecord(), ParseLongOption(), parseServiceInfo(), pg_getnameinfo_all(), pg_open_tzfile(), pg_perm_setlocale(), pg_stat_get_wal_receiver(), pg_timezone_abbrevs_abbrevs(), pg_TZDIR(), pg_tzenumerate_next(), pgstat_bestart_initial(), pgstat_bestart_security(), 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(), tarCreateHeader(), timestamptz_to_str(), TimeZoneAbbrevIsKnown(), 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(), GetRelationPath(), pg_encoding_mblen_bounded(), pnstrdup(), PQescapeInternal(), PQescapeStringInternal(), PQmblenBounded(), test_enc_setup(), and test_one_vector_escape().

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

◆ timingsafe_bcmp()

int timingsafe_bcmp ( const void *  b1,
const void *  b2,
size_t  len 
)

Definition at line 30 of file timingsafe_bcmp.c.

31{
32#ifdef USE_SSL
33 return CRYPTO_memcmp(b1, b2, n);
34#else
35 const unsigned char *p1 = b1,
36 *p2 = b2;
37 int ret = 0;
38
39 for (; n > 0; n--)
40 ret |= *p1++ ^ *p2++;
41 return (ret != 0);
42#endif
43}

Referenced by SendCancelRequest().

◆ 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:279
#define S_ISREG(m)
Definition: win32_port.h:318

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:150
#define WIFSIGNALED(w)
Definition: win32_port.h:151
#define WEXITSTATUS(w)
Definition: win32_port.h:152

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

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