PostgreSQL Source Code  git master
libpq-fe.h File Reference
#include <stdio.h>
#include "postgres_ext.h"
Include dependency graph for libpq-fe.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  pgNotify
 
struct  _PQprintOpt
 
struct  _PQconninfoOption
 
struct  PQArgBlock
 
struct  pgresAttDesc
 

Macros

#define LIBPQ_HAS_PIPELINING   1
 
#define LIBPQ_HAS_TRACE_FLAGS   1
 
#define LIBPQ_HAS_SSL_LIBRARY_DETECTION   1
 
#define PG_COPYRES_ATTRS   0x01
 
#define PG_COPYRES_TUPLES   0x02 /* Implies PG_COPYRES_ATTRS */
 
#define PG_COPYRES_EVENTS   0x04
 
#define PG_COPYRES_NOTICEHOOKS   0x08
 
#define PQsetdb(M_PGHOST, M_PGPORT, M_PGOPT, M_PGTTY, M_DBNAME)    PQsetdbLogin(M_PGHOST, M_PGPORT, M_PGOPT, M_PGTTY, M_DBNAME, NULL, NULL)
 
#define PQTRACE_SUPPRESS_TIMESTAMPS   (1<<0)
 
#define PQTRACE_REGRESS_MODE   (1<<1)
 
#define PQ_QUERY_PARAM_MAX_LIMIT   65535
 
#define PQfreeNotify(ptr)   PQfreemem(ptr)
 
#define PQnoPasswordSupplied   "fe_sendauth: no password supplied\n"
 

Typedefs

typedef struct pg_conn PGconn
 
typedef struct pg_result PGresult
 
typedef struct pg_cancel PGcancel
 
typedef struct pgNotify PGnotify
 
typedef void(* PQnoticeReceiver) (void *arg, const PGresult *res)
 
typedef void(* PQnoticeProcessor) (void *arg, const char *message)
 
typedef char pqbool
 
typedef struct _PQprintOpt PQprintOpt
 
typedef struct _PQconninfoOption PQconninfoOption
 
typedef struct pgresAttDesc PGresAttDesc
 
typedef void(* pgthreadlock_t) (int acquire)
 
typedef int(* PQsslKeyPassHook_OpenSSL_type) (char *buf, int size, PGconn *conn)
 

Enumerations

enum  ConnStatusType {
  CONNECTION_OK , CONNECTION_BAD , CONNECTION_STARTED , CONNECTION_MADE ,
  CONNECTION_AWAITING_RESPONSE , CONNECTION_AUTH_OK , CONNECTION_SETENV , CONNECTION_SSL_STARTUP ,
  CONNECTION_NEEDED , CONNECTION_CHECK_WRITABLE , CONNECTION_CONSUME , CONNECTION_GSS_STARTUP ,
  CONNECTION_CHECK_TARGET , CONNECTION_CHECK_STANDBY
}
 
enum  PostgresPollingStatusType {
  PGRES_POLLING_FAILED = 0 , PGRES_POLLING_READING , PGRES_POLLING_WRITING , PGRES_POLLING_OK ,
  PGRES_POLLING_ACTIVE
}
 
enum  ExecStatusType {
  PGRES_EMPTY_QUERY = 0 , PGRES_COMMAND_OK , PGRES_TUPLES_OK , PGRES_COPY_OUT ,
  PGRES_COPY_IN , PGRES_BAD_RESPONSE , PGRES_NONFATAL_ERROR , PGRES_FATAL_ERROR ,
  PGRES_COPY_BOTH , PGRES_SINGLE_TUPLE , PGRES_PIPELINE_SYNC , PGRES_PIPELINE_ABORTED
}
 
enum  PGTransactionStatusType {
  PQTRANS_IDLE , PQTRANS_ACTIVE , PQTRANS_INTRANS , PQTRANS_INERROR ,
  PQTRANS_UNKNOWN
}
 
enum  PGVerbosity { PQERRORS_TERSE , PQERRORS_DEFAULT , PQERRORS_VERBOSE , PQERRORS_SQLSTATE }
 
enum  PGContextVisibility { PQSHOW_CONTEXT_NEVER , PQSHOW_CONTEXT_ERRORS , PQSHOW_CONTEXT_ALWAYS }
 
enum  PGPing { PQPING_OK , PQPING_REJECT , PQPING_NO_RESPONSE , PQPING_NO_ATTEMPT }
 
enum  PGpipelineStatus { PQ_PIPELINE_OFF , PQ_PIPELINE_ON , PQ_PIPELINE_ABORTED }
 

Functions

PGconnPQconnectStart (const char *conninfo)
 
PGconnPQconnectStartParams (const char *const *keywords, const char *const *values, int expand_dbname)
 
PostgresPollingStatusType PQconnectPoll (PGconn *conn)
 
PGconnPQconnectdb (const char *conninfo)
 
PGconnPQconnectdbParams (const char *const *keywords, const char *const *values, int expand_dbname)
 
PGconnPQsetdbLogin (const char *pghost, const char *pgport, const char *pgoptions, const char *pgtty, const char *dbName, const char *login, const char *pwd)
 
void PQfinish (PGconn *conn)
 
PQconninfoOptionPQconndefaults (void)
 
PQconninfoOptionPQconninfoParse (const char *conninfo, char **errmsg)
 
PQconninfoOptionPQconninfo (PGconn *conn)
 
void PQconninfoFree (PQconninfoOption *connOptions)
 
int PQresetStart (PGconn *conn)
 
PostgresPollingStatusType PQresetPoll (PGconn *conn)
 
void PQreset (PGconn *conn)
 
PGcancelPQgetCancel (PGconn *conn)
 
void PQfreeCancel (PGcancel *cancel)
 
int PQcancel (PGcancel *cancel, char *errbuf, int errbufsize)
 
int PQrequestCancel (PGconn *conn)
 
char * PQdb (const PGconn *conn)
 
char * PQuser (const PGconn *conn)
 
char * PQpass (const PGconn *conn)
 
char * PQhost (const PGconn *conn)
 
char * PQhostaddr (const PGconn *conn)
 
char * PQport (const PGconn *conn)
 
char * PQtty (const PGconn *conn)
 
char * PQoptions (const PGconn *conn)
 
ConnStatusType PQstatus (const PGconn *conn)
 
PGTransactionStatusType PQtransactionStatus (const PGconn *conn)
 
const char * PQparameterStatus (const PGconn *conn, const char *paramName)
 
int PQprotocolVersion (const PGconn *conn)
 
int PQserverVersion (const PGconn *conn)
 
char * PQerrorMessage (const PGconn *conn)
 
int PQsocket (const PGconn *conn)
 
int PQbackendPID (const PGconn *conn)
 
PGpipelineStatus PQpipelineStatus (const PGconn *conn)
 
int PQconnectionNeedsPassword (const PGconn *conn)
 
int PQconnectionUsedPassword (const PGconn *conn)
 
int PQconnectionUsedGSSAPI (const PGconn *conn)
 
int PQclientEncoding (const PGconn *conn)
 
int PQsetClientEncoding (PGconn *conn, const char *encoding)
 
int PQsslInUse (PGconn *conn)
 
void * PQsslStruct (PGconn *conn, const char *struct_name)
 
const char * PQsslAttribute (PGconn *conn, const char *attribute_name)
 
const char *const * PQsslAttributeNames (PGconn *conn)
 
void * PQgetssl (PGconn *conn)
 
void PQinitSSL (int do_init)
 
void PQinitOpenSSL (int do_ssl, int do_crypto)
 
int PQgssEncInUse (PGconn *conn)
 
void * PQgetgssctx (PGconn *conn)
 
PGVerbosity PQsetErrorVerbosity (PGconn *conn, PGVerbosity verbosity)
 
PGContextVisibility PQsetErrorContextVisibility (PGconn *conn, PGContextVisibility show_context)
 
PQnoticeReceiver PQsetNoticeReceiver (PGconn *conn, PQnoticeReceiver proc, void *arg)
 
PQnoticeProcessor PQsetNoticeProcessor (PGconn *conn, PQnoticeProcessor proc, void *arg)
 
pgthreadlock_t PQregisterThreadLock (pgthreadlock_t newhandler)
 
void PQtrace (PGconn *conn, FILE *debug_port)
 
void PQuntrace (PGconn *conn)
 
void PQsetTraceFlags (PGconn *conn, int flags)
 
PGresultPQexec (PGconn *conn, const char *query)
 
PGresultPQexecParams (PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
PGresultPQprepare (PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
 
PGresultPQexecPrepared (PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
int PQsendQuery (PGconn *conn, const char *query)
 
int PQsendQueryParams (PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
int PQsendPrepare (PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
 
int PQsendQueryPrepared (PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
int PQsetSingleRowMode (PGconn *conn)
 
PGresultPQgetResult (PGconn *conn)
 
int PQisBusy (PGconn *conn)
 
int PQconsumeInput (PGconn *conn)
 
int PQenterPipelineMode (PGconn *conn)
 
int PQexitPipelineMode (PGconn *conn)
 
int PQpipelineSync (PGconn *conn)
 
int PQsendFlushRequest (PGconn *conn)
 
PGnotifyPQnotifies (PGconn *conn)
 
int PQputCopyData (PGconn *conn, const char *buffer, int nbytes)
 
int PQputCopyEnd (PGconn *conn, const char *errormsg)
 
int PQgetCopyData (PGconn *conn, char **buffer, int async)
 
int PQgetline (PGconn *conn, char *buffer, int length)
 
int PQputline (PGconn *conn, const char *string)
 
int PQgetlineAsync (PGconn *conn, char *buffer, int bufsize)
 
int PQputnbytes (PGconn *conn, const char *buffer, int nbytes)
 
int PQendcopy (PGconn *conn)
 
int PQsetnonblocking (PGconn *conn, int arg)
 
int PQisnonblocking (const PGconn *conn)
 
int PQisthreadsafe (void)
 
PGPing PQping (const char *conninfo)
 
PGPing PQpingParams (const char *const *keywords, const char *const *values, int expand_dbname)
 
int PQflush (PGconn *conn)
 
PGresultPQfn (PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
 
ExecStatusType PQresultStatus (const PGresult *res)
 
char * PQresStatus (ExecStatusType status)
 
char * PQresultErrorMessage (const PGresult *res)
 
char * PQresultVerboseErrorMessage (const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
 
char * PQresultErrorField (const PGresult *res, int fieldcode)
 
int PQntuples (const PGresult *res)
 
int PQnfields (const PGresult *res)
 
int PQbinaryTuples (const PGresult *res)
 
char * PQfname (const PGresult *res, int field_num)
 
int PQfnumber (const PGresult *res, const char *field_name)
 
Oid PQftable (const PGresult *res, int field_num)
 
int PQftablecol (const PGresult *res, int field_num)
 
int PQfformat (const PGresult *res, int field_num)
 
Oid PQftype (const PGresult *res, int field_num)
 
int PQfsize (const PGresult *res, int field_num)
 
int PQfmod (const PGresult *res, int field_num)
 
char * PQcmdStatus (PGresult *res)
 
char * PQoidStatus (const PGresult *res)
 
Oid PQoidValue (const PGresult *res)
 
char * PQcmdTuples (PGresult *res)
 
char * PQgetvalue (const PGresult *res, int tup_num, int field_num)
 
int PQgetlength (const PGresult *res, int tup_num, int field_num)
 
int PQgetisnull (const PGresult *res, int tup_num, int field_num)
 
int PQnparams (const PGresult *res)
 
Oid PQparamtype (const PGresult *res, int param_num)
 
PGresultPQdescribePrepared (PGconn *conn, const char *stmt)
 
PGresultPQdescribePortal (PGconn *conn, const char *portal)
 
int PQsendDescribePrepared (PGconn *conn, const char *stmt)
 
int PQsendDescribePortal (PGconn *conn, const char *portal)
 
PGresultPQclosePrepared (PGconn *conn, const char *stmt)
 
PGresultPQclosePortal (PGconn *conn, const char *portal)
 
int PQsendClosePrepared (PGconn *conn, const char *stmt)
 
int PQsendClosePortal (PGconn *conn, const char *portal)
 
void PQclear (PGresult *res)
 
void PQfreemem (void *ptr)
 
PGresultPQmakeEmptyPGresult (PGconn *conn, ExecStatusType status)
 
PGresultPQcopyResult (const PGresult *src, int flags)
 
int PQsetResultAttrs (PGresult *res, int numAttributes, PGresAttDesc *attDescs)
 
void * PQresultAlloc (PGresult *res, size_t nBytes)
 
size_t PQresultMemorySize (const PGresult *res)
 
int PQsetvalue (PGresult *res, int tup_num, int field_num, char *value, int len)
 
size_t PQescapeStringConn (PGconn *conn, char *to, const char *from, size_t length, int *error)
 
char * PQescapeLiteral (PGconn *conn, const char *str, size_t len)
 
char * PQescapeIdentifier (PGconn *conn, const char *str, size_t len)
 
unsigned char * PQescapeByteaConn (PGconn *conn, const unsigned char *from, size_t from_length, size_t *to_length)
 
unsigned char * PQunescapeBytea (const unsigned char *strtext, size_t *retbuflen)
 
size_t PQescapeString (char *to, const char *from, size_t length)
 
unsigned char * PQescapeBytea (const unsigned char *from, size_t from_length, size_t *to_length)
 
void PQprint (FILE *fout, const PGresult *res, const PQprintOpt *po)
 
void PQdisplayTuples (const PGresult *res, FILE *fp, int fillAlign, const char *fieldSep, int printHeader, int quiet)
 
void PQprintTuples (const PGresult *res, FILE *fout, int PrintAttNames, int TerseOutput, int colWidth)
 
int lo_open (PGconn *conn, Oid lobjId, int mode)
 
int lo_close (PGconn *conn, int fd)
 
int lo_read (PGconn *conn, int fd, char *buf, size_t len)
 
int lo_write (PGconn *conn, int fd, const char *buf, size_t len)
 
int lo_lseek (PGconn *conn, int fd, int offset, int whence)
 
pg_int64 lo_lseek64 (PGconn *conn, int fd, pg_int64 offset, int whence)
 
Oid lo_creat (PGconn *conn, int mode)
 
Oid lo_create (PGconn *conn, Oid lobjId)
 
int lo_tell (PGconn *conn, int fd)
 
pg_int64 lo_tell64 (PGconn *conn, int fd)
 
int lo_truncate (PGconn *conn, int fd, size_t len)
 
int lo_truncate64 (PGconn *conn, int fd, pg_int64 len)
 
int lo_unlink (PGconn *conn, Oid lobjId)
 
Oid lo_import (PGconn *conn, const char *filename)
 
Oid lo_import_with_oid (PGconn *conn, const char *filename, Oid lobjId)
 
int lo_export (PGconn *conn, Oid lobjId, const char *filename)
 
int PQlibVersion (void)
 
int PQmblen (const char *s, int encoding)
 
int PQmblenBounded (const char *s, int encoding)
 
int PQdsplen (const char *s, int encoding)
 
int PQenv2encoding (void)
 
char * PQencryptPassword (const char *passwd, const char *user)
 
char * PQencryptPasswordConn (PGconn *conn, const char *passwd, const char *user, const char *algorithm)
 
int pg_char_to_encoding (const char *name)
 
const char * pg_encoding_to_char (int encoding)
 
int pg_valid_server_encoding_id (int encoding)
 
PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL (void)
 
void PQsetSSLKeyPassHook_OpenSSL (PQsslKeyPassHook_OpenSSL_type hook)
 
int PQdefaultSSLKeyPassHook_OpenSSL (char *buf, int size, PGconn *conn)
 

Macro Definition Documentation

◆ LIBPQ_HAS_PIPELINING

#define LIBPQ_HAS_PIPELINING   1

Definition at line 36 of file libpq-fe.h.

◆ LIBPQ_HAS_SSL_LIBRARY_DETECTION

#define LIBPQ_HAS_SSL_LIBRARY_DETECTION   1

Definition at line 40 of file libpq-fe.h.

◆ LIBPQ_HAS_TRACE_FLAGS

#define LIBPQ_HAS_TRACE_FLAGS   1

Definition at line 38 of file libpq-fe.h.

◆ PG_COPYRES_ATTRS

#define PG_COPYRES_ATTRS   0x01

Definition at line 45 of file libpq-fe.h.

◆ PG_COPYRES_EVENTS

#define PG_COPYRES_EVENTS   0x04

Definition at line 47 of file libpq-fe.h.

◆ PG_COPYRES_NOTICEHOOKS

#define PG_COPYRES_NOTICEHOOKS   0x08

Definition at line 48 of file libpq-fe.h.

◆ PG_COPYRES_TUPLES

#define PG_COPYRES_TUPLES   0x02 /* Implies PG_COPYRES_ATTRS */

Definition at line 46 of file libpq-fe.h.

◆ PQ_QUERY_PARAM_MAX_LIMIT

#define PQ_QUERY_PARAM_MAX_LIMIT   65535

Definition at line 444 of file libpq-fe.h.

◆ PQfreeNotify

#define PQfreeNotify (   ptr)    PQfreemem(ptr)

Definition at line 564 of file libpq-fe.h.

◆ PQnoPasswordSupplied

#define PQnoPasswordSupplied   "fe_sendauth: no password supplied\n"

Definition at line 568 of file libpq-fe.h.

◆ PQsetdb

#define PQsetdb (   M_PGHOST,
  M_PGPORT,
  M_PGOPT,
  M_PGTTY,
  M_DBNAME 
)     PQsetdbLogin(M_PGHOST, M_PGPORT, M_PGOPT, M_PGTTY, M_DBNAME, NULL, NULL)

Definition at line 295 of file libpq-fe.h.

◆ PQTRACE_REGRESS_MODE

#define PQTRACE_REGRESS_MODE   (1<<1)

Definition at line 417 of file libpq-fe.h.

◆ PQTRACE_SUPPRESS_TIMESTAMPS

#define PQTRACE_SUPPRESS_TIMESTAMPS   (1<<0)

Definition at line 415 of file libpq-fe.h.

Typedef Documentation

◆ PGcancel

typedef struct pg_cancel PGcancel

Definition at line 1 of file libpq-fe.h.

◆ PGconn

typedef struct pg_conn PGconn

Definition at line 1 of file libpq-fe.h.

◆ PGnotify

typedef struct pgNotify PGnotify

◆ PGresAttDesc

typedef struct pgresAttDesc PGresAttDesc

◆ PGresult

typedef struct pg_result PGresult

Definition at line 1 of file libpq-fe.h.

◆ pgthreadlock_t

typedef void(* pgthreadlock_t) (int acquire)

Definition at line 405 of file libpq-fe.h.

◆ pqbool

typedef char pqbool

Definition at line 201 of file libpq-fe.h.

◆ PQconninfoOption

◆ PQnoticeProcessor

typedef void(* PQnoticeProcessor) (void *arg, const char *message)

Definition at line 198 of file libpq-fe.h.

◆ PQnoticeReceiver

typedef void(* PQnoticeReceiver) (void *arg, const PGresult *res)

Definition at line 197 of file libpq-fe.h.

◆ PQprintOpt

typedef struct _PQprintOpt PQprintOpt

◆ PQsslKeyPassHook_OpenSSL_type

typedef int(* PQsslKeyPassHook_OpenSSL_type) (char *buf, int size, PGconn *conn)

Definition at line 672 of file libpq-fe.h.

Enumeration Type Documentation

◆ ConnStatusType

Enumerator
CONNECTION_OK 
CONNECTION_BAD 
CONNECTION_STARTED 
CONNECTION_MADE 
CONNECTION_AWAITING_RESPONSE 
CONNECTION_AUTH_OK 
CONNECTION_SETENV 
CONNECTION_SSL_STARTUP 
CONNECTION_NEEDED 
CONNECTION_CHECK_WRITABLE 
CONNECTION_CONSUME 
CONNECTION_GSS_STARTUP 
CONNECTION_CHECK_TARGET 
CONNECTION_CHECK_STANDBY 

Definition at line 58 of file libpq-fe.h.

59 {
62  /* Non-blocking mode only below here */
63 
64  /*
65  * The existence of these should never be relied upon - they should only
66  * be used for user feedback or similar purposes.
67  */
68  CONNECTION_STARTED, /* Waiting for connection to be made. */
69  CONNECTION_MADE, /* Connection OK; waiting to send. */
70  CONNECTION_AWAITING_RESPONSE, /* Waiting for a response from the
71  * postmaster. */
72  CONNECTION_AUTH_OK, /* Received authentication; waiting for
73  * backend startup. */
74  CONNECTION_SETENV, /* This state is no longer used. */
75  CONNECTION_SSL_STARTUP, /* Negotiating SSL. */
76  CONNECTION_NEEDED, /* Internal state: connect() needed */
77  CONNECTION_CHECK_WRITABLE, /* Checking if session is read-write. */
78  CONNECTION_CONSUME, /* Consuming any extra messages. */
79  CONNECTION_GSS_STARTUP, /* Negotiating GSSAPI. */
80  CONNECTION_CHECK_TARGET, /* Checking target server properties. */
81  CONNECTION_CHECK_STANDBY /* Checking if server is in standby mode. */
ConnStatusType
Definition: libpq-fe.h:59
@ CONNECTION_CONSUME
Definition: libpq-fe.h:78
@ CONNECTION_CHECK_STANDBY
Definition: libpq-fe.h:81
@ CONNECTION_STARTED
Definition: libpq-fe.h:68
@ CONNECTION_AWAITING_RESPONSE
Definition: libpq-fe.h:70
@ CONNECTION_MADE
Definition: libpq-fe.h:69
@ CONNECTION_CHECK_WRITABLE
Definition: libpq-fe.h:77
@ CONNECTION_BAD
Definition: libpq-fe.h:61
@ CONNECTION_OK
Definition: libpq-fe.h:60
@ CONNECTION_GSS_STARTUP
Definition: libpq-fe.h:79
@ CONNECTION_SSL_STARTUP
Definition: libpq-fe.h:75
@ CONNECTION_AUTH_OK
Definition: libpq-fe.h:72
@ CONNECTION_CHECK_TARGET
Definition: libpq-fe.h:80
@ CONNECTION_NEEDED
Definition: libpq-fe.h:76
@ CONNECTION_SETENV
Definition: libpq-fe.h:74

◆ ExecStatusType

Enumerator
PGRES_EMPTY_QUERY 
PGRES_COMMAND_OK 
PGRES_TUPLES_OK 
PGRES_COPY_OUT 
PGRES_COPY_IN 
PGRES_BAD_RESPONSE 
PGRES_NONFATAL_ERROR 
PGRES_FATAL_ERROR 
PGRES_COPY_BOTH 
PGRES_SINGLE_TUPLE 
PGRES_PIPELINE_SYNC 
PGRES_PIPELINE_ABORTED 

Definition at line 94 of file libpq-fe.h.

95 {
96  PGRES_EMPTY_QUERY = 0, /* empty query string was executed */
97  PGRES_COMMAND_OK, /* a query command that doesn't return
98  * anything was executed properly by the
99  * backend */
100  PGRES_TUPLES_OK, /* a query command that returns tuples was
101  * executed properly by the backend, PGresult
102  * contains the result tuples */
103  PGRES_COPY_OUT, /* Copy Out data transfer in progress */
104  PGRES_COPY_IN, /* Copy In data transfer in progress */
105  PGRES_BAD_RESPONSE, /* an unexpected response was recv'd from the
106  * backend */
107  PGRES_NONFATAL_ERROR, /* notice or warning message */
108  PGRES_FATAL_ERROR, /* query failed */
109  PGRES_COPY_BOTH, /* Copy In/Out data transfer in progress */
110  PGRES_SINGLE_TUPLE, /* single tuple from larger resultset */
111  PGRES_PIPELINE_SYNC, /* pipeline synchronization point */
112  PGRES_PIPELINE_ABORTED /* Command didn't run because of an abort
113  * earlier in a pipeline */
ExecStatusType
Definition: libpq-fe.h:95
@ PGRES_COPY_IN
Definition: libpq-fe.h:104
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:109
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:97
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:108
@ PGRES_SINGLE_TUPLE
Definition: libpq-fe.h:110
@ PGRES_COPY_OUT
Definition: libpq-fe.h:103
@ PGRES_EMPTY_QUERY
Definition: libpq-fe.h:96
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:111
@ PGRES_BAD_RESPONSE
Definition: libpq-fe.h:105
@ PGRES_PIPELINE_ABORTED
Definition: libpq-fe.h:112
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:107
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:100

◆ PGContextVisibility

Enumerator
PQSHOW_CONTEXT_NEVER 
PQSHOW_CONTEXT_ERRORS 
PQSHOW_CONTEXT_ALWAYS 

Definition at line 133 of file libpq-fe.h.

134 {
135  PQSHOW_CONTEXT_NEVER, /* never show CONTEXT field */
136  PQSHOW_CONTEXT_ERRORS, /* show CONTEXT for errors only (default) */
137  PQSHOW_CONTEXT_ALWAYS /* always show CONTEXT field */
PGContextVisibility
Definition: libpq-fe.h:134
@ PQSHOW_CONTEXT_NEVER
Definition: libpq-fe.h:135
@ PQSHOW_CONTEXT_ALWAYS
Definition: libpq-fe.h:137
@ PQSHOW_CONTEXT_ERRORS
Definition: libpq-fe.h:136

◆ PGPing

enum PGPing
Enumerator
PQPING_OK 
PQPING_REJECT 
PQPING_NO_RESPONSE 
PQPING_NO_ATTEMPT 

Definition at line 145 of file libpq-fe.h.

146 {
147  PQPING_OK, /* server is accepting connections */
148  PQPING_REJECT, /* server is alive but rejecting connections */
149  PQPING_NO_RESPONSE, /* could not establish connection */
150  PQPING_NO_ATTEMPT /* connection not attempted (bad params) */
151 } PGPing;
PGPing
Definition: libpq-fe.h:146
@ PQPING_OK
Definition: libpq-fe.h:147
@ PQPING_REJECT
Definition: libpq-fe.h:148
@ PQPING_NO_RESPONSE
Definition: libpq-fe.h:149
@ PQPING_NO_ATTEMPT
Definition: libpq-fe.h:150

◆ PGpipelineStatus

Enumerator
PQ_PIPELINE_OFF 
PQ_PIPELINE_ON 
PQ_PIPELINE_ABORTED 

Definition at line 156 of file libpq-fe.h.

157 {
PGpipelineStatus
Definition: libpq-fe.h:157
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:158
@ PQ_PIPELINE_ABORTED
Definition: libpq-fe.h:160
@ PQ_PIPELINE_ON
Definition: libpq-fe.h:159

◆ PGTransactionStatusType

Enumerator
PQTRANS_IDLE 
PQTRANS_ACTIVE 
PQTRANS_INTRANS 
PQTRANS_INERROR 
PQTRANS_UNKNOWN 

Definition at line 116 of file libpq-fe.h.

117 {
118  PQTRANS_IDLE, /* connection idle */
119  PQTRANS_ACTIVE, /* command in progress */
120  PQTRANS_INTRANS, /* idle, within transaction block */
121  PQTRANS_INERROR, /* idle, within failed transaction */
122  PQTRANS_UNKNOWN /* cannot determine status */
PGTransactionStatusType
Definition: libpq-fe.h:117
@ PQTRANS_INTRANS
Definition: libpq-fe.h:120
@ PQTRANS_IDLE
Definition: libpq-fe.h:118
@ PQTRANS_ACTIVE
Definition: libpq-fe.h:119
@ PQTRANS_UNKNOWN
Definition: libpq-fe.h:122
@ PQTRANS_INERROR
Definition: libpq-fe.h:121

◆ PGVerbosity

Enumerator
PQERRORS_TERSE 
PQERRORS_DEFAULT 
PQERRORS_VERBOSE 
PQERRORS_SQLSTATE 

Definition at line 125 of file libpq-fe.h.

126 {
127  PQERRORS_TERSE, /* single-line error messages */
128  PQERRORS_DEFAULT, /* recommended style */
129  PQERRORS_VERBOSE, /* all the facts, ma'am */
130  PQERRORS_SQLSTATE /* only error severity and SQLSTATE code */
131 } PGVerbosity;
PGVerbosity
Definition: libpq-fe.h:126
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:129
@ PQERRORS_DEFAULT
Definition: libpq-fe.h:128
@ PQERRORS_TERSE
Definition: libpq-fe.h:127
@ PQERRORS_SQLSTATE
Definition: libpq-fe.h:130

◆ PostgresPollingStatusType

Enumerator
PGRES_POLLING_FAILED 
PGRES_POLLING_READING 
PGRES_POLLING_WRITING 
PGRES_POLLING_OK 
PGRES_POLLING_ACTIVE 

Definition at line 84 of file libpq-fe.h.

85 {
87  PGRES_POLLING_READING, /* These two indicate that one may */
88  PGRES_POLLING_WRITING, /* use select before polling again. */
90  PGRES_POLLING_ACTIVE /* unused; keep for awhile for backwards
91  * compatibility */
PostgresPollingStatusType
Definition: libpq-fe.h:85
@ PGRES_POLLING_ACTIVE
Definition: libpq-fe.h:90
@ PGRES_POLLING_OK
Definition: libpq-fe.h:89
@ PGRES_POLLING_READING
Definition: libpq-fe.h:87
@ PGRES_POLLING_WRITING
Definition: libpq-fe.h:88
@ PGRES_POLLING_FAILED
Definition: libpq-fe.h:86

Function Documentation

◆ lo_close()

int lo_close ( PGconn conn,
int  fd 
)

Definition at line 96 of file fe-lobj.c.

97 {
98  PQArgBlock argv[1];
99  PGresult *res;
100  int retval;
101  int result_len;
102 
103  if (lo_initialize(conn) < 0)
104  return -1;
105 
106  argv[0].isint = 1;
107  argv[0].len = 4;
108  argv[0].u.integer = fd;
110  &retval, &result_len, 1, argv, 1);
112  {
113  PQclear(res);
114  return retval;
115  }
116  else
117  {
118  PQclear(res);
119  return -1;
120  }
121 }
PGresult * PQfn(PGconn *conn, int fnid, int *result_buf, int *result_len, int result_is_int, const PQArgBlock *args, int nargs)
Definition: fe-exec.c:2946
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3325
static int lo_initialize(PGconn *conn)
Definition: fe-lobj.c:843
static int fd(const char *x, int i)
Definition: preproc-init.c:105
PGconn * conn
Definition: streamutil.c:54
int isint
Definition: libpq-fe.h:249
int integer
Definition: libpq-fe.h:253
union PQArgBlock::@170 u
Oid fn_lo_close
Definition: libpq-int.h:281
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:503

References conn, fd(), pgLobjfuncs::fn_lo_close, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by dumpLOs(), EndRestoreLO(), exportFile(), importFile(), lo_export(), lo_import_internal(), my_truncate(), overwrite(), and pickout().

◆ lo_creat()

Oid lo_creat ( PGconn conn,
int  mode 
)

Definition at line 438 of file fe-lobj.c.

439 {
440  PQArgBlock argv[1];
441  PGresult *res;
442  int retval;
443  int result_len;
444 
445  if (lo_initialize(conn) < 0)
446  return InvalidOid;
447 
448  argv[0].isint = 1;
449  argv[0].len = 4;
450  argv[0].u.integer = mode;
452  &retval, &result_len, 1, argv, 1);
454  {
455  PQclear(res);
456  return (Oid) retval;
457  }
458  else
459  {
460  PQclear(res);
461  return InvalidOid;
462  }
463 }
static PgChecksumMode mode
Definition: pg_checksums.c:56
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
Oid fn_lo_creat
Definition: libpq-int.h:282

References conn, pgLobjfuncs::fn_lo_creat, PQArgBlock::integer, InvalidOid, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, mode, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by importFile(), and lo_import_internal().

◆ lo_create()

Oid lo_create ( PGconn conn,
Oid  lobjId 
)

Definition at line 474 of file fe-lobj.c.

475 {
476  PQArgBlock argv[1];
477  PGresult *res;
478  int retval;
479  int result_len;
480 
481  if (lo_initialize(conn) < 0)
482  return InvalidOid;
483 
484  /* Must check this on-the-fly because it's not there pre-8.1 */
485  if (conn->lobjfuncs->fn_lo_create == 0)
486  {
487  libpq_append_conn_error(conn, "cannot determine OID of function %s",
488  "lo_create");
489  return InvalidOid;
490  }
491 
492  argv[0].isint = 1;
493  argv[0].len = 4;
494  argv[0].u.integer = lobjId;
496  &retval, &result_len, 1, argv, 1);
498  {
499  PQclear(res);
500  return (Oid) retval;
501  }
502  else
503  {
504  PQclear(res);
505  return InvalidOid;
506  }
507 }
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition: fe-misc.c:1312
Oid fn_lo_create
Definition: libpq-int.h:283

References conn, pgLobjfuncs::fn_lo_create, PQArgBlock::integer, InvalidOid, PQArgBlock::isint, PQArgBlock::len, libpq_append_conn_error(), lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by lo_import_internal(), and StartRestoreLO().

◆ lo_export()

int lo_export ( PGconn conn,
Oid  lobjId,
const char *  filename 
)

Definition at line 748 of file fe-lobj.c.

749 {
750  int result = 1;
751  int fd;
752  int nbytes,
753  tmp;
754  char buf[LO_BUFSIZE];
755  int lobj;
756  char sebuf[PG_STRERROR_R_BUFLEN];
757 
758  /*
759  * open the large object.
760  */
761  lobj = lo_open(conn, lobjId, INV_READ);
762  if (lobj == -1)
763  {
764  /* we assume lo_open() already set a suitable error message */
765  return -1;
766  }
767 
768  /*
769  * create the file to be written to
770  */
771  fd = open(filename, O_CREAT | O_WRONLY | O_TRUNC | PG_BINARY, 0666);
772  if (fd < 0)
773  {
774  /* We must do lo_close before setting the errorMessage */
775  int save_errno = errno;
776 
777  (void) lo_close(conn, lobj);
778  /* deliberately overwrite any error from lo_close */
780  libpq_append_conn_error(conn, "could not open file \"%s\": %s",
781  filename,
782  strerror_r(save_errno, sebuf, sizeof(sebuf)));
783  return -1;
784  }
785 
786  /*
787  * read in from the large object and write to the file
788  */
789  while ((nbytes = lo_read(conn, lobj, buf, LO_BUFSIZE)) > 0)
790  {
791  tmp = write(fd, buf, nbytes);
792  if (tmp != nbytes)
793  {
794  /* We must do lo_close before setting the errorMessage */
795  int save_errno = errno;
796 
797  (void) lo_close(conn, lobj);
798  (void) close(fd);
799  /* deliberately overwrite any error from lo_close */
801  libpq_append_conn_error(conn, "could not write to file \"%s\": %s",
802  filename,
803  strerror_r(save_errno, sebuf, sizeof(sebuf)));
804  return -1;
805  }
806  }
807 
808  /*
809  * If lo_read() failed, we are now in an aborted transaction so there's no
810  * need for lo_close(); furthermore, if we tried it we'd overwrite the
811  * useful error result with a useless one. So skip lo_close() if we got a
812  * failure result.
813  */
814  if (nbytes < 0 ||
815  lo_close(conn, lobj) != 0)
816  {
817  /* assume lo_read() or lo_close() left a suitable error message */
818  result = -1;
819  }
820 
821  /* if we already failed, don't overwrite that msg with a close error */
822  if (close(fd) != 0 && result >= 0)
823  {
824  libpq_append_conn_error(conn, "could not write to file \"%s\": %s",
825  filename, strerror_r(errno, sebuf, sizeof(sebuf)));
826  result = -1;
827  }
828 
829  return result;
830 }
#define PG_BINARY
Definition: c.h:1283
int lo_close(PGconn *conn, int fd)
Definition: fe-lobj.c:96
#define LO_BUFSIZE
Definition: fe-lobj.c:42
int lo_read(PGconn *conn, int fd, char *buf, size_t len)
Definition: fe-lobj.c:245
int lo_open(PGconn *conn, Oid lobjId, int mode)
Definition: fe-lobj.c:57
#define close(a)
Definition: win32.h:12
#define write(a, b, c)
Definition: win32.h:14
#define INV_READ
Definition: libpq-fs.h:22
#define pqClearConnErrorState(conn)
Definition: libpq-int.h:873
static char * filename
Definition: pg_dumpall.c:119
static char * buf
Definition: pg_test_fsync.c:67
#define PG_STRERROR_R_BUFLEN
Definition: port.h:256
#define strerror_r
Definition: port.h:255

References buf, close, conn, fd(), filename, INV_READ, libpq_append_conn_error(), LO_BUFSIZE, lo_close(), lo_open(), lo_read(), PG_BINARY, PG_STRERROR_R_BUFLEN, pqClearConnErrorState, strerror_r, and write.

Referenced by do_lo_export(), and main().

◆ lo_import()

Oid lo_import ( PGconn conn,
const char *  filename 
)

Definition at line 626 of file fe-lobj.c.

627 {
629 }
static Oid lo_import_internal(PGconn *conn, const char *filename, Oid oid)
Definition: fe-lobj.c:647

References conn, filename, InvalidOid, and lo_import_internal().

Referenced by do_lo_import(), and main().

◆ lo_import_with_oid()

Oid lo_import_with_oid ( PGconn conn,
const char *  filename,
Oid  lobjId 
)

Definition at line 641 of file fe-lobj.c.

642 {
643  return lo_import_internal(conn, filename, lobjId);
644 }

References conn, filename, and lo_import_internal().

◆ lo_lseek()

int lo_lseek ( PGconn conn,
int  fd,
int  offset,
int  whence 
)

Definition at line 344 of file fe-lobj.c.

345 {
346  PQArgBlock argv[3];
347  PGresult *res;
348  int retval;
349  int result_len;
350 
351  if (lo_initialize(conn) < 0)
352  return -1;
353 
354  argv[0].isint = 1;
355  argv[0].len = 4;
356  argv[0].u.integer = fd;
357 
358  argv[1].isint = 1;
359  argv[1].len = 4;
360  argv[1].u.integer = offset;
361 
362  argv[2].isint = 1;
363  argv[2].len = 4;
364  argv[2].u.integer = whence;
365 
367  &retval, &result_len, 1, argv, 3);
369  {
370  PQclear(res);
371  return retval;
372  }
373  else
374  {
375  PQclear(res);
376  return -1;
377  }
378 }
Oid fn_lo_lseek
Definition: libpq-int.h:285

References conn, fd(), pgLobjfuncs::fn_lo_lseek, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by overwrite(), and pickout().

◆ lo_lseek64()

pg_int64 lo_lseek64 ( PGconn conn,
int  fd,
pg_int64  offset,
int  whence 
)

Definition at line 385 of file fe-lobj.c.

386 {
387  PQArgBlock argv[3];
388  PGresult *res;
389  pg_int64 retval;
390  int result_len;
391 
392  if (lo_initialize(conn) < 0)
393  return -1;
394 
395  if (conn->lobjfuncs->fn_lo_lseek64 == 0)
396  {
397  libpq_append_conn_error(conn, "cannot determine OID of function %s",
398  "lo_lseek64");
399  return -1;
400  }
401 
402  argv[0].isint = 1;
403  argv[0].len = 4;
404  argv[0].u.integer = fd;
405 
406  offset = lo_hton64(offset);
407  argv[1].isint = 0;
408  argv[1].len = 8;
409  argv[1].u.ptr = (int *) &offset;
410 
411  argv[2].isint = 1;
412  argv[2].len = 4;
413  argv[2].u.integer = whence;
414 
416  (void *) &retval, &result_len, 0, argv, 3);
417  if (PQresultStatus(res) == PGRES_COMMAND_OK && result_len == 8)
418  {
419  PQclear(res);
420  return lo_ntoh64(retval);
421  }
422  else
423  {
424  PQclear(res);
425  return -1;
426  }
427 }
static pg_int64 lo_ntoh64(pg_int64 net64)
Definition: fe-lobj.c:1048
static pg_int64 lo_hton64(pg_int64 host64)
Definition: fe-lobj.c:1023
PG_INT64_TYPE pg_int64
Definition: postgres_ext.h:47
int * ptr
Definition: libpq-fe.h:252
Oid fn_lo_lseek64
Definition: libpq-int.h:286

References conn, fd(), pgLobjfuncs::fn_lo_lseek64, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_append_conn_error(), lo_hton64(), lo_initialize(), lo_ntoh64(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), PQArgBlock::ptr, res, and PQArgBlock::u.

Referenced by overwrite(), and pickout().

◆ lo_open()

int lo_open ( PGconn conn,
Oid  lobjId,
int  mode 
)

Definition at line 57 of file fe-lobj.c.

58 {
59  int fd;
60  int result_len;
61  PQArgBlock argv[2];
62  PGresult *res;
63 
64  if (lo_initialize(conn) < 0)
65  return -1;
66 
67  argv[0].isint = 1;
68  argv[0].len = 4;
69  argv[0].u.integer = lobjId;
70 
71  argv[1].isint = 1;
72  argv[1].len = 4;
73  argv[1].u.integer = mode;
74 
75  res = PQfn(conn, conn->lobjfuncs->fn_lo_open, &fd, &result_len, 1, argv, 2);
77  {
78  PQclear(res);
79  return fd;
80  }
81  else
82  {
83  PQclear(res);
84  return -1;
85  }
86 }
Oid fn_lo_open
Definition: libpq-int.h:280

References conn, fd(), pgLobjfuncs::fn_lo_open, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, mode, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by dumpLOs(), exportFile(), importFile(), lo_export(), lo_import_internal(), my_truncate(), overwrite(), pickout(), and StartRestoreLO().

◆ lo_read()

int lo_read ( PGconn conn,
int  fd,
char *  buf,
size_t  len 
)

Definition at line 245 of file fe-lobj.c.

246 {
247  PQArgBlock argv[2];
248  PGresult *res;
249  int result_len;
250 
251  if (lo_initialize(conn) < 0)
252  return -1;
253 
254  /*
255  * Long ago, somebody thought it'd be a good idea to declare this function
256  * as taking size_t ... but the underlying backend function only accepts a
257  * signed int32 length. So throw error if the given value overflows
258  * int32.
259  */
260  if (len > (size_t) INT_MAX)
261  {
262  libpq_append_conn_error(conn, "argument of lo_read exceeds integer range");
263  return -1;
264  }
265 
266  argv[0].isint = 1;
267  argv[0].len = 4;
268  argv[0].u.integer = fd;
269 
270  argv[1].isint = 1;
271  argv[1].len = 4;
272  argv[1].u.integer = (int) len;
273 
275  (void *) buf, &result_len, 0, argv, 2);
277  {
278  PQclear(res);
279  return result_len;
280  }
281  else
282  {
283  PQclear(res);
284  return -1;
285  }
286 }
const void size_t len
Oid fn_lo_read
Definition: libpq-int.h:291

References buf, conn, fd(), pgLobjfuncs::fn_lo_read, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, len, libpq_append_conn_error(), lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by lo_export().

◆ lo_tell()

int lo_tell ( PGconn conn,
int  fd 
)

Definition at line 515 of file fe-lobj.c.

516 {
517  int retval;
518  PQArgBlock argv[1];
519  PGresult *res;
520  int result_len;
521 
522  if (lo_initialize(conn) < 0)
523  return -1;
524 
525  argv[0].isint = 1;
526  argv[0].len = 4;
527  argv[0].u.integer = fd;
528 
530  &retval, &result_len, 1, argv, 1);
532  {
533  PQclear(res);
534  return retval;
535  }
536  else
537  {
538  PQclear(res);
539  return -1;
540  }
541 }
Oid fn_lo_tell
Definition: libpq-int.h:287

References conn, fd(), pgLobjfuncs::fn_lo_tell, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

◆ lo_tell64()

pg_int64 lo_tell64 ( PGconn conn,
int  fd 
)

Definition at line 548 of file fe-lobj.c.

549 {
550  pg_int64 retval;
551  PQArgBlock argv[1];
552  PGresult *res;
553  int result_len;
554 
555  if (lo_initialize(conn) < 0)
556  return -1;
557 
558  if (conn->lobjfuncs->fn_lo_tell64 == 0)
559  {
560  libpq_append_conn_error(conn, "cannot determine OID of function %s",
561  "lo_tell64");
562  return -1;
563  }
564 
565  argv[0].isint = 1;
566  argv[0].len = 4;
567  argv[0].u.integer = fd;
568 
570  (void *) &retval, &result_len, 0, argv, 1);
571  if (PQresultStatus(res) == PGRES_COMMAND_OK && result_len == 8)
572  {
573  PQclear(res);
574  return lo_ntoh64(retval);
575  }
576  else
577  {
578  PQclear(res);
579  return -1;
580  }
581 }
Oid fn_lo_tell64
Definition: libpq-int.h:288

References conn, fd(), pgLobjfuncs::fn_lo_tell64, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, libpq_append_conn_error(), lo_initialize(), lo_ntoh64(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by pickout().

◆ lo_truncate()

int lo_truncate ( PGconn conn,
int  fd,
size_t  len 
)

Definition at line 131 of file fe-lobj.c.

132 {
133  PQArgBlock argv[2];
134  PGresult *res;
135  int retval;
136  int result_len;
137 
138  if (lo_initialize(conn) < 0)
139  return -1;
140 
141  /* Must check this on-the-fly because it's not there pre-8.3 */
142  if (conn->lobjfuncs->fn_lo_truncate == 0)
143  {
144  libpq_append_conn_error(conn, "cannot determine OID of function %s",
145  "lo_truncate");
146  return -1;
147  }
148 
149  /*
150  * Long ago, somebody thought it'd be a good idea to declare this function
151  * as taking size_t ... but the underlying backend function only accepts a
152  * signed int32 length. So throw error if the given value overflows
153  * int32. (A possible alternative is to automatically redirect the call
154  * to lo_truncate64; but if the caller wanted to rely on that backend
155  * function being available, he could have called lo_truncate64 for
156  * himself.)
157  */
158  if (len > (size_t) INT_MAX)
159  {
160  libpq_append_conn_error(conn, "argument of lo_truncate exceeds integer range");
161  return -1;
162  }
163 
164  argv[0].isint = 1;
165  argv[0].len = 4;
166  argv[0].u.integer = fd;
167 
168  argv[1].isint = 1;
169  argv[1].len = 4;
170  argv[1].u.integer = (int) len;
171 
173  &retval, &result_len, 1, argv, 2);
174 
176  {
177  PQclear(res);
178  return retval;
179  }
180  else
181  {
182  PQclear(res);
183  return -1;
184  }
185 }
Oid fn_lo_truncate
Definition: libpq-int.h:289

References conn, fd(), pgLobjfuncs::fn_lo_truncate, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, len, libpq_append_conn_error(), lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

◆ lo_truncate64()

int lo_truncate64 ( PGconn conn,
int  fd,
pg_int64  len 
)

Definition at line 195 of file fe-lobj.c.

196 {
197  PQArgBlock argv[2];
198  PGresult *res;
199  int retval;
200  int result_len;
201 
202  if (lo_initialize(conn) < 0)
203  return -1;
204 
205  if (conn->lobjfuncs->fn_lo_truncate64 == 0)
206  {
207  libpq_append_conn_error(conn, "cannot determine OID of function %s",
208  "lo_truncate64");
209  return -1;
210  }
211 
212  argv[0].isint = 1;
213  argv[0].len = 4;
214  argv[0].u.integer = fd;
215 
216  len = lo_hton64(len);
217  argv[1].isint = 0;
218  argv[1].len = 8;
219  argv[1].u.ptr = (int *) &len;
220 
222  &retval, &result_len, 1, argv, 2);
223 
225  {
226  PQclear(res);
227  return retval;
228  }
229  else
230  {
231  PQclear(res);
232  return -1;
233  }
234 }
Oid fn_lo_truncate64
Definition: libpq-int.h:290

References conn, fd(), pgLobjfuncs::fn_lo_truncate64, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, len, libpq_append_conn_error(), lo_hton64(), lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), PQArgBlock::ptr, res, and PQArgBlock::u.

Referenced by my_truncate().

◆ lo_unlink()

int lo_unlink ( PGconn conn,
Oid  lobjId 
)

Definition at line 589 of file fe-lobj.c.

590 {
591  PQArgBlock argv[1];
592  PGresult *res;
593  int result_len;
594  int retval;
595 
596  if (lo_initialize(conn) < 0)
597  return -1;
598 
599  argv[0].isint = 1;
600  argv[0].len = 4;
601  argv[0].u.integer = lobjId;
602 
604  &retval, &result_len, 1, argv, 1);
606  {
607  PQclear(res);
608  return retval;
609  }
610  else
611  {
612  PQclear(res);
613  return -1;
614  }
615 }
Oid fn_lo_unlink
Definition: libpq-int.h:284

References conn, pgLobjfuncs::fn_lo_unlink, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), res, and PQArgBlock::u.

Referenced by do_lo_unlink(), and vacuumlo().

◆ lo_write()

int lo_write ( PGconn conn,
int  fd,
const char *  buf,
size_t  len 
)

Definition at line 295 of file fe-lobj.c.

296 {
297  PQArgBlock argv[2];
298  PGresult *res;
299  int result_len;
300  int retval;
301 
302  if (lo_initialize(conn) < 0)
303  return -1;
304 
305  /*
306  * Long ago, somebody thought it'd be a good idea to declare this function
307  * as taking size_t ... but the underlying backend function only accepts a
308  * signed int32 length. So throw error if the given value overflows
309  * int32.
310  */
311  if (len > (size_t) INT_MAX)
312  {
313  libpq_append_conn_error(conn, "argument of lo_write exceeds integer range");
314  return -1;
315  }
316 
317  argv[0].isint = 1;
318  argv[0].len = 4;
319  argv[0].u.integer = fd;
320 
321  argv[1].isint = 0;
322  argv[1].len = (int) len;
323  argv[1].u.ptr = (int *) unconstify(char *, buf);
324 
326  &retval, &result_len, 1, argv, 2);
328  {
329  PQclear(res);
330  return retval;
331  }
332  else
333  {
334  PQclear(res);
335  return -1;
336  }
337 }
#define unconstify(underlying_type, expr)
Definition: c.h:1255
Oid fn_lo_write
Definition: libpq-int.h:292

References buf, conn, fd(), pgLobjfuncs::fn_lo_write, PQArgBlock::integer, PQArgBlock::isint, PQArgBlock::len, len, libpq_append_conn_error(), lo_initialize(), pg_conn::lobjfuncs, PGRES_COMMAND_OK, PQclear(), PQfn(), PQresultStatus(), PQArgBlock::ptr, res, PQArgBlock::u, and unconstify.

Referenced by lo_import_internal().

◆ pg_char_to_encoding()

int pg_char_to_encoding ( const char *  name)

Definition at line 550 of file encnames.c.

551 {
552  unsigned int nel = lengthof(pg_encname_tbl);
553  const pg_encname *base = pg_encname_tbl,
554  *last = base + nel - 1,
555  *position;
556  int result;
557  char buff[NAMEDATALEN],
558  *key;
559 
560  if (name == NULL || *name == '\0')
561  return -1;
562 
563  if (strlen(name) >= NAMEDATALEN)
564  return -1; /* it's certainly not in the table */
565 
566  key = clean_encoding_name(name, buff);
567 
568  while (last >= base)
569  {
570  position = base + ((last - base) >> 1);
571  result = key[0] - position->name[0];
572 
573  if (result == 0)
574  {
575  result = strcmp(key, position->name);
576  if (result == 0)
577  return position->encoding;
578  }
579  if (result < 0)
580  last = position - 1;
581  else
582  base = position + 1;
583  }
584  return -1;
585 }
#define lengthof(array)
Definition: c.h:777
static const pg_encname pg_encname_tbl[]
Definition: encnames.c:39
static char * clean_encoding_name(const char *key, char *newkey)
Definition: encnames.c:525
#define NAMEDATALEN
const char * name

References clean_encoding_name(), sort-test::key, lengthof, name, NAMEDATALEN, and pg_encname_tbl.

Referenced by CreateConversionCommand(), length_in_encoding(), main(), PG_char_to_encoding(), pg_convert(), pg_get_utf8_id(), pg_valid_client_encoding(), pg_valid_server_encoding(), PQenv2encoding(), pqSaveParameterStatus(), ProcessCopyOptions(), processEncodingEntry(), test_enc_conversion(), and to_ascii_encname().

◆ pg_encoding_to_char()

◆ pg_valid_server_encoding_id()

int pg_valid_server_encoding_id ( int  encoding)

Definition at line 514 of file encnames.c.

515 {
517 }
#define PG_VALID_BE_ENCODING(_enc)
Definition: pg_wchar.h:281

References encoding, and PG_VALID_BE_ENCODING.

Referenced by setup_locale_encoding().

◆ PQbackendPID()

int PQbackendPID ( const PGconn conn)

Definition at line 7282 of file fe-connect.c.

7283 {
7284  if (!conn || conn->status != CONNECTION_OK)
7285  return 0;
7286  return conn->be_pid;
7287 }
int be_pid
Definition: libpq-int.h:494
ConnStatusType status
Definition: libpq-int.h:425

References pg_conn::be_pid, conn, CONNECTION_OK, and pg_conn::status.

Referenced by get_prompt(), libpqrcv_get_backend_pid(), main(), and StartLogStreamer().

◆ PQbinaryTuples()

int PQbinaryTuples ( const PGresult res)

Definition at line 3411 of file fe-exec.c.

3412 {
3413  if (!res)
3414  return 0;
3415  return res->binary;
3416 }
int binary
Definition: libpq-int.h:182

References pg_result::binary, and res.

Referenced by HandleCopyResult().

◆ PQcancel()

int PQcancel ( PGcancel cancel,
char *  errbuf,
int  errbufsize 
)

Definition at line 4821 of file fe-connect.c.

4822 {
4823  int save_errno = SOCK_ERRNO;
4824  pgsocket tmpsock = PGINVALID_SOCKET;
4825  int maxlen;
4826  struct
4827  {
4828  uint32 packetlen;
4830  } crp;
4831 
4832  if (!cancel)
4833  {
4834  strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
4835  /* strlcpy probably doesn't change errno, but be paranoid */
4836  SOCK_ERRNO_SET(save_errno);
4837  return false;
4838  }
4839 
4840  /*
4841  * We need to open a temporary connection to the postmaster. Do this with
4842  * only kernel calls.
4843  */
4844  if ((tmpsock = socket(cancel->raddr.addr.ss_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
4845  {
4846  strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
4847  goto cancel_errReturn;
4848  }
4849 
4850  /*
4851  * Since this connection will only be used to send a single packet of
4852  * data, we don't need NODELAY. We also don't set the socket to
4853  * nonblocking mode, because the API definition of PQcancel requires the
4854  * cancel to be sent in a blocking way.
4855  *
4856  * We do set socket options related to keepalives and other TCP timeouts.
4857  * This ensures that this function does not block indefinitely when
4858  * reasonable keepalive and timeout settings have been provided.
4859  */
4860  if (cancel->raddr.addr.ss_family != AF_UNIX &&
4861  cancel->keepalives != 0)
4862  {
4863 #ifndef WIN32
4864  if (!optional_setsockopt(tmpsock, SOL_SOCKET, SO_KEEPALIVE, 1))
4865  {
4866  strlcpy(errbuf, "PQcancel() -- setsockopt(SO_KEEPALIVE) failed: ", errbufsize);
4867  goto cancel_errReturn;
4868  }
4869 
4870 #ifdef PG_TCP_KEEPALIVE_IDLE
4871  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
4872  cancel->keepalives_idle))
4873  {
4874  strlcpy(errbuf, "PQcancel() -- setsockopt(" PG_TCP_KEEPALIVE_IDLE_STR ") failed: ", errbufsize);
4875  goto cancel_errReturn;
4876  }
4877 #endif
4878 
4879 #ifdef TCP_KEEPINTVL
4880  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_KEEPINTVL,
4881  cancel->keepalives_interval))
4882  {
4883  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_KEEPINTVL) failed: ", errbufsize);
4884  goto cancel_errReturn;
4885  }
4886 #endif
4887 
4888 #ifdef TCP_KEEPCNT
4889  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_KEEPCNT,
4890  cancel->keepalives_count))
4891  {
4892  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_KEEPCNT) failed: ", errbufsize);
4893  goto cancel_errReturn;
4894  }
4895 #endif
4896 
4897 #else /* WIN32 */
4898 
4899 #ifdef SIO_KEEPALIVE_VALS
4900  if (!setKeepalivesWin32(tmpsock,
4901  cancel->keepalives_idle,
4902  cancel->keepalives_interval))
4903  {
4904  strlcpy(errbuf, "PQcancel() -- WSAIoctl(SIO_KEEPALIVE_VALS) failed: ", errbufsize);
4905  goto cancel_errReturn;
4906  }
4907 #endif /* SIO_KEEPALIVE_VALS */
4908 #endif /* WIN32 */
4909 
4910  /* TCP_USER_TIMEOUT works the same way on Unix and Windows */
4911 #ifdef TCP_USER_TIMEOUT
4912  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_USER_TIMEOUT,
4913  cancel->pgtcp_user_timeout))
4914  {
4915  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_USER_TIMEOUT) failed: ", errbufsize);
4916  goto cancel_errReturn;
4917  }
4918 #endif
4919  }
4920 
4921 retry3:
4922  if (connect(tmpsock, (struct sockaddr *) &cancel->raddr.addr,
4923  cancel->raddr.salen) < 0)
4924  {
4925  if (SOCK_ERRNO == EINTR)
4926  /* Interrupted system call - we'll just try again */
4927  goto retry3;
4928  strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
4929  goto cancel_errReturn;
4930  }
4931 
4932  /* Create and send the cancel request packet. */
4933 
4934  crp.packetlen = pg_hton32((uint32) sizeof(crp));
4935  crp.cp.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE);
4936  crp.cp.backendPID = pg_hton32(cancel->be_pid);
4937  crp.cp.cancelAuthCode = pg_hton32(cancel->be_key);
4938 
4939 retry4:
4940  if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
4941  {
4942  if (SOCK_ERRNO == EINTR)
4943  /* Interrupted system call - we'll just try again */
4944  goto retry4;
4945  strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
4946  goto cancel_errReturn;
4947  }
4948 
4949  /*
4950  * Wait for the postmaster to close the connection, which indicates that
4951  * it's processed the request. Without this delay, we might issue another
4952  * command only to find that our cancel zaps that command instead of the
4953  * one we thought we were canceling. Note we don't actually expect this
4954  * read to obtain any data, we are just waiting for EOF to be signaled.
4955  */
4956 retry5:
4957  if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
4958  {
4959  if (SOCK_ERRNO == EINTR)
4960  /* Interrupted system call - we'll just try again */
4961  goto retry5;
4962  /* we ignore other error conditions */
4963  }
4964 
4965  /* All done */
4966  closesocket(tmpsock);
4967  SOCK_ERRNO_SET(save_errno);
4968  return true;
4969 
4970 cancel_errReturn:
4971 
4972  /*
4973  * Make sure we don't overflow the error buffer. Leave space for the \n at
4974  * the end, and for the terminating zero.
4975  */
4976  maxlen = errbufsize - strlen(errbuf) - 2;
4977  if (maxlen >= 0)
4978  {
4979  /*
4980  * We can't invoke strerror here, since it's not signal-safe. Settle
4981  * for printing the decimal value of errno. Even that has to be done
4982  * the hard way.
4983  */
4984  int val = SOCK_ERRNO;
4985  char buf[32];
4986  char *bufp;
4987 
4988  bufp = buf + sizeof(buf) - 1;
4989  *bufp = '\0';
4990  do
4991  {
4992  *(--bufp) = (val % 10) + '0';
4993  val /= 10;
4994  } while (val > 0);
4995  bufp -= 6;
4996  memcpy(bufp, "error ", 6);
4997  strncat(errbuf, bufp, maxlen);
4998  strcat(errbuf, "\n");
4999  }
5000  if (tmpsock != PGINVALID_SOCKET)
5001  closesocket(tmpsock);
5002  SOCK_ERRNO_SET(save_errno);
5003  return false;
5004 }
unsigned int uint32
Definition: c.h:495
static bool optional_setsockopt(int fd, int protoid, int optid, int value)
Definition: fe-connect.c:4789
long val
Definition: informix.c:664
#define SOCK_ERRNO
Definition: libpq-int.h:921
#define SOCK_ERRNO_SET(e)
Definition: libpq-int.h:923
#define pg_hton32(x)
Definition: pg_bswap.h:121
int pgsocket
Definition: port.h:29
#define PGINVALID_SOCKET
Definition: port.h:31
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define closesocket
Definition: port.h:349
#define CANCEL_REQUEST_CODE
Definition: pqcomm.h:132
ProtocolVersion MsgType
Definition: pqcomm.h:101
struct sockaddr_storage addr
Definition: pqcomm.h:32
socklen_t salen
Definition: pqcomm.h:33
int pgtcp_user_timeout
Definition: libpq-int.h:633
int keepalives_interval
Definition: libpq-int.h:636
int keepalives_idle
Definition: libpq-int.h:635
int keepalives_count
Definition: libpq-int.h:638
SockAddr raddr
Definition: libpq-int.h:630
int be_pid
Definition: libpq-int.h:631
int keepalives
Definition: libpq-int.h:634
int be_key
Definition: libpq-int.h:632
#define EINTR
Definition: win32_port.h:374
#define recv(s, buf, len, flags)
Definition: win32_port.h:496
#define send(s, buf, len, flags)
Definition: win32_port.h:497
#define socket(af, type, protocol)
Definition: win32_port.h:490
#define connect(s, name, namelen)
Definition: win32_port.h:494

References SockAddr::addr, pg_cancel::be_key, pg_cancel::be_pid, buf, CANCEL_REQUEST_CODE, closesocket, connect, EINTR, pg_cancel::keepalives, pg_cancel::keepalives_count, pg_cancel::keepalives_idle, pg_cancel::keepalives_interval, optional_setsockopt(), pg_hton32, PGINVALID_SOCKET, pg_cancel::pgtcp_user_timeout, pg_cancel::raddr, recv, SockAddr::salen, send, SOCK_ERRNO, SOCK_ERRNO_SET, socket, strlcpy(), and val.

Referenced by dblink_cancel_query(), DisconnectDatabase(), disconnectDatabase(), handle_sigint(), pgfdw_cancel_query_begin(), PQrequestCancel(), ShutdownWorkersHard(), sigTermHandler(), and try_complete_step().

◆ PQclear()

void PQclear ( PGresult res)

Definition at line 718 of file fe-exec.c.

719 {
720  PGresult_data *block;
721  int i;
722 
723  /* As a convenience, do nothing for a NULL pointer */
724  if (!res)
725  return;
726  /* Also, do nothing if the argument is OOM_result */
727  if ((const PGresult *) res == &OOM_result)
728  return;
729 
730  /* Close down any events we may have */
731  for (i = 0; i < res->nEvents; i++)
732  {
733  /* only send DESTROY to successfully-initialized event procs */
735  {
737 
738  evt.result = res;
739  (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
740  res->events[i].passThrough);
741  }
742  free(res->events[i].name);
743  }
744 
745  free(res->events);
746 
747  /* Free all the subsidiary blocks */
748  while ((block = res->curBlock) != NULL)
749  {
750  res->curBlock = block->next;
751  free(block);
752  }
753 
754  /* Free the top-level tuple pointer array */
755  free(res->tuples);
756 
757  /* zero out the pointer fields to catch programming errors */
758  res->attDescs = NULL;
759  res->tuples = NULL;
760  res->paramDescs = NULL;
761  res->errFields = NULL;
762  res->events = NULL;
763  res->nEvents = 0;
764  /* res->curBlock was zeroed out earlier */
765 
766  /* Free the PGresult structure itself */
767  free(res);
768 }
static const PGresult OOM_result
Definition: fe-exec.c:48
#define free(a)
Definition: header.h:65
int i
Definition: isn.c:73
@ PGEVT_RESULTDESTROY
Definition: libpq-events.h:34
void * passThrough
Definition: libpq-int.h:165
char * name
Definition: libpq-int.h:164
PGEventProc proc
Definition: libpq-int.h:163
bool resultInitialized
Definition: libpq-int.h:167
int nEvents
Definition: libpq-int.h:191
PGresAttValue ** tuples
Definition: libpq-int.h:175
PGresAttDesc * attDescs
Definition: libpq-int.h:174
PGMessageField * errFields
Definition: libpq-int.h:200
PGresParamDesc * paramDescs
Definition: libpq-int.h:179
PGEvent * events
Definition: libpq-int.h:190
PGresult_data * curBlock
Definition: libpq-int.h:211
PGresult_data * next
Definition: libpq-int.h:108

References pg_result::attDescs, pg_result::curBlock, pg_result::errFields, pg_result::events, free, i, PGEvent::name, pg_result::nEvents, pgresult_data::next, OOM_result, pg_result::paramDescs, PGEvent::passThrough, PGEVT_RESULTDESTROY, PGEvent::proc, res, PGEventResultDestroy::result, PGEvent::resultInitialized, and pg_result::tuples.

Referenced by pqClearAsyncResult(), PQcopyResult(), PQexecFinish(), PQexecStart(), pqInternalNotice(), PQmakeEmptyPGresult(), and pqRowProcessor().

◆ PQclientEncoding()

int PQclientEncoding ( const PGconn conn)

◆ PQclosePortal()

PGresult* PQclosePortal ( PGconn conn,
const char *  portal 
)

Definition at line 2505 of file fe-exec.c.

2506 {
2507  if (!PQexecStart(conn))
2508  return NULL;
2509  if (!PQsendTypedCommand(conn, PqMsg_Close, 'P', portal))
2510  return NULL;
2511  return PQexecFinish(conn);
2512 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2376
static int PQsendTypedCommand(PGconn *conn, char command, char type, const char *target)
Definition: fe-exec.c:2555
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2310
#define PqMsg_Close
Definition: protocol.h:20

References conn, PQexecFinish(), PQexecStart(), PqMsg_Close, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQclosePrepared()

PGresult* PQclosePrepared ( PGconn conn,
const char *  stmt 
)

Definition at line 2487 of file fe-exec.c.

2488 {
2489  if (!PQexecStart(conn))
2490  return NULL;
2491  if (!PQsendTypedCommand(conn, PqMsg_Close, 'S', stmt))
2492  return NULL;
2493  return PQexecFinish(conn);
2494 }
#define stmt
Definition: indent_codes.h:59

References conn, PQexecFinish(), PQexecStart(), PqMsg_Close, PQsendTypedCommand(), and stmt.

Referenced by test_prepared().

◆ PQcmdStatus()

char* PQcmdStatus ( PGresult res)

Definition at line 3666 of file fe-exec.c.

3667 {
3668  if (!res)
3669  return NULL;
3670  return res->cmdStatus;
3671 }
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:181

References pg_result::cmdStatus, and res.

Referenced by dblink_exec(), ecpg_process_output(), ExecQueryAndProcessResults(), materializeResult(), PrintQueryResult(), PrintQueryStatus(), and test_pipelined_insert().

◆ PQcmdTuples()

char* PQcmdTuples ( PGresult res)

Definition at line 3736 of file fe-exec.c.

3737 {
3738  char *p,
3739  *c;
3740 
3741  if (!res)
3742  return "";
3743 
3744  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3745  {
3746  p = res->cmdStatus + 7;
3747  /* INSERT: skip oid and space */
3748  while (*p && *p != ' ')
3749  p++;
3750  if (*p == 0)
3751  goto interpret_error; /* no space? */
3752  p++;
3753  }
3754  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3755  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3756  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3757  p = res->cmdStatus + 7;
3758  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0 ||
3759  strncmp(res->cmdStatus, "MERGE ", 6) == 0)
3760  p = res->cmdStatus + 6;
3761  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3762  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3763  p = res->cmdStatus + 5;
3764  else
3765  return "";
3766 
3767  /* check that we have an integer (at least one digit, nothing else) */
3768  for (c = p; *c; c++)
3769  {
3770  if (!isdigit((unsigned char) *c))
3771  goto interpret_error;
3772  }
3773  if (c == p)
3774  goto interpret_error;
3775 
3776  return p;
3777 
3778 interpret_error:
3780  "could not interpret result from server: %s",
3781  res->cmdStatus);
3782  return "";
3783 }
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:933
char * c
PGNoticeHooks noticeHooks
Definition: libpq-int.h:189

References pg_result::cmdStatus, pg_result::noticeHooks, pqInternalNotice(), and res.

Referenced by ecpg_process_output(), execute_dml_stmt(), execute_foreign_modify(), and SetResultVariables().

◆ PQconndefaults()

PQconninfoOption* PQconndefaults ( void  )

Definition at line 1778 of file fe-connect.c.

1779 {
1780  PQExpBufferData errorBuf;
1781  PQconninfoOption *connOptions;
1782 
1783  /* We don't actually report any errors here, but callees want a buffer */
1784  initPQExpBuffer(&errorBuf);
1785  if (PQExpBufferDataBroken(errorBuf))
1786  return NULL; /* out of memory already :-( */
1787 
1788  connOptions = conninfo_init(&errorBuf);
1789  if (connOptions != NULL)
1790  {
1791  /* pass NULL errorBuf to ignore errors */
1792  if (!conninfo_add_defaults(connOptions, NULL))
1793  {
1794  PQconninfoFree(connOptions);
1795  connOptions = NULL;
1796  }
1797  }
1798 
1799  termPQExpBuffer(&errorBuf);
1800  return connOptions;
1801 }
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:5851
static bool conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
Definition: fe-connect.c:6278
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:7081
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67

References conninfo_add_defaults(), conninfo_init(), initPQExpBuffer(), PQconninfoFree(), PQExpBufferDataBroken, and termPQExpBuffer().

Referenced by check_pghost_envvar(), dblink_fdw_validator(), do_connect(), get_connect_string(), InitPgFdwOptions(), and main().

◆ PQconnectdb()

PGconn* PQconnectdb ( const char *  conninfo)

Definition at line 731 of file fe-connect.c.

732 {
733  PGconn *conn = PQconnectStart(conninfo);
734 
735  if (conn && conn->status != CONNECTION_BAD)
736  (void) connectDBComplete(conn);
737 
738  return conn;
739 }
PGconn * PQconnectStart(const char *conninfo)
Definition: fe-connect.c:859
static int connectDBComplete(PGconn *conn)
Definition: fe-connect.c:2405

References conn, connectDBComplete(), CONNECTION_BAD, PQconnectStart(), and pg_conn::status.

Referenced by get_db_conn(), and main().

◆ PQconnectdbParams()

PGconn* PQconnectdbParams ( const char *const *  keywords,
const char *const *  values,
int  expand_dbname 
)

Definition at line 676 of file fe-connect.c.

679 {
680  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
681 
682  if (conn && conn->status != CONNECTION_BAD)
683  (void) connectDBComplete(conn);
684 
685  return conn;
686 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:778

References conn, connectDBComplete(), CONNECTION_BAD, PQconnectStartParams(), pg_conn::status, and values.

Referenced by ConnectDatabase(), connectDatabase(), do_connect(), doConnect(), ECPGconnect(), GetConnection(), main(), sql_conn(), and vacuumlo().

◆ PQconnectionNeedsPassword()

int PQconnectionNeedsPassword ( const PGconn conn)

Definition at line 7299 of file fe-connect.c.

7300 {
7301  char *password;
7302 
7303  if (!conn)
7304  return false;
7305  password = PQpass(conn);
7306  if (conn->password_needed &&
7307  (password == NULL || password[0] == '\0'))
7308  return true;
7309  else
7310  return false;
7311 }
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:7110
static char * password
Definition: streamutil.c:53
bool password_needed
Definition: libpq-int.h:466

References conn, password, pg_conn::password_needed, and PQpass().

Referenced by ConnectDatabase(), connectDatabase(), do_connect(), doConnect(), GetConnection(), main(), sql_conn(), and vacuumlo().

◆ PQconnectionUsedGSSAPI()

int PQconnectionUsedGSSAPI ( const PGconn conn)

Definition at line 7325 of file fe-connect.c.

7326 {
7327  if (!conn)
7328  return false;
7329  if (conn->gssapi_used)
7330  return true;
7331  else
7332  return false;
7333 }
bool gssapi_used
Definition: libpq-int.h:467

References conn, and pg_conn::gssapi_used.

Referenced by dblink_security_check(), and pgfdw_security_check().

◆ PQconnectionUsedPassword()

int PQconnectionUsedPassword ( const PGconn conn)

Definition at line 7314 of file fe-connect.c.

7315 {
7316  if (!conn)
7317  return false;
7318  if (conn->password_needed)
7319  return true;
7320  else
7321  return false;
7322 }

References conn, and pg_conn::password_needed.

Referenced by ConnectDatabase(), dblink_security_check(), libpqrcv_connect(), and pgfdw_security_check().

◆ PQconnectPoll()

PostgresPollingStatusType PQconnectPoll ( PGconn conn)

Definition at line 2541 of file fe-connect.c.

2542 {
2543  bool reset_connection_state_machine = false;
2544  bool need_new_connection = false;
2545  PGresult *res;
2546  char sebuf[PG_STRERROR_R_BUFLEN];
2547  int optval;
2548 
2549  if (conn == NULL)
2550  return PGRES_POLLING_FAILED;
2551 
2552  /* Get the new data */
2553  switch (conn->status)
2554  {
2555  /*
2556  * We really shouldn't have been polled in these two cases, but we
2557  * can handle it.
2558  */
2559  case CONNECTION_BAD:
2560  return PGRES_POLLING_FAILED;
2561  case CONNECTION_OK:
2562  return PGRES_POLLING_OK;
2563 
2564  /* These are reading states */
2566  case CONNECTION_AUTH_OK:
2568  case CONNECTION_CONSUME:
2570  {
2571  /* Load waiting data */
2572  int n = pqReadData(conn);
2573 
2574  if (n < 0)
2575  goto error_return;
2576  if (n == 0)
2577  return PGRES_POLLING_READING;
2578 
2579  break;
2580  }
2581 
2582  /* These are writing states, so we just proceed. */
2583  case CONNECTION_STARTED:
2584  case CONNECTION_MADE:
2585  break;
2586 
2587  /* Special cases: proceed without waiting. */
2589  case CONNECTION_NEEDED:
2592  break;
2593 
2594  default:
2595  libpq_append_conn_error(conn, "invalid connection state, probably indicative of memory corruption");
2596  goto error_return;
2597  }
2598 
2599 
2600 keep_going: /* We will come back to here until there is
2601  * nothing left to do. */
2602 
2603  /* Time to advance to next address, or next host if no more addresses? */
2604  if (conn->try_next_addr)
2605  {
2606  if (conn->whichaddr < conn->naddr)
2607  {
2608  conn->whichaddr++;
2609  reset_connection_state_machine = true;
2610  }
2611  else
2612  conn->try_next_host = true;
2613  conn->try_next_addr = false;
2614  }
2615 
2616  /* Time to advance to next connhost[] entry? */
2617  if (conn->try_next_host)
2618  {
2619  pg_conn_host *ch;
2620  struct addrinfo hint;
2621  struct addrinfo *addrlist;
2622  int thisport;
2623  int ret;
2624  char portstr[MAXPGPATH];
2625 
2626  if (conn->whichhost + 1 < conn->nconnhost)
2627  conn->whichhost++;
2628  else
2629  {
2630  /*
2631  * Oops, no more hosts.
2632  *
2633  * If we are trying to connect in "prefer-standby" mode, then drop
2634  * the standby requirement and start over.
2635  *
2636  * Otherwise, an appropriate error message is already set up, so
2637  * we just need to set the right status.
2638  */
2640  conn->nconnhost > 0)
2641  {
2643  conn->whichhost = 0;
2644  }
2645  else
2646  goto error_return;
2647  }
2648 
2649  /* Drop any address info for previous host */
2651 
2652  /*
2653  * Look up info for the new host. On failure, log the problem in
2654  * conn->errorMessage, then loop around to try the next host. (Note
2655  * we don't clear try_next_host until we've succeeded.)
2656  */
2657  ch = &conn->connhost[conn->whichhost];
2658 
2659  /* Initialize hint structure */
2660  MemSet(&hint, 0, sizeof(hint));
2661  hint.ai_socktype = SOCK_STREAM;
2662  hint.ai_family = AF_UNSPEC;
2663 
2664  /* Figure out the port number we're going to use. */
2665  if (ch->port == NULL || ch->port[0] == '\0')
2666  thisport = DEF_PGPORT;
2667  else
2668  {
2669  if (!parse_int_param(ch->port, &thisport, conn, "port"))
2670  goto error_return;
2671 
2672  if (thisport < 1 || thisport > 65535)
2673  {
2674  libpq_append_conn_error(conn, "invalid port number: \"%s\"", ch->port);
2675  goto keep_going;
2676  }
2677  }
2678  snprintf(portstr, sizeof(portstr), "%d", thisport);
2679 
2680  /* Use pg_getaddrinfo_all() to resolve the address */
2681  switch (ch->type)
2682  {
2683  case CHT_HOST_NAME:
2684  ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
2685  &addrlist);
2686  if (ret || !addrlist)
2687  {
2688  libpq_append_conn_error(conn, "could not translate host name \"%s\" to address: %s",
2689  ch->host, gai_strerror(ret));
2690  goto keep_going;
2691  }
2692  break;
2693 
2694  case CHT_HOST_ADDRESS:
2695  hint.ai_flags = AI_NUMERICHOST;
2696  ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,
2697  &addrlist);
2698  if (ret || !addrlist)
2699  {
2700  libpq_append_conn_error(conn, "could not parse network address \"%s\": %s",
2701  ch->hostaddr, gai_strerror(ret));
2702  goto keep_going;
2703  }
2704  break;
2705 
2706  case CHT_UNIX_SOCKET:
2707  hint.ai_family = AF_UNIX;
2708  UNIXSOCK_PATH(portstr, thisport, ch->host);
2709  if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
2710  {
2711  libpq_append_conn_error(conn, "Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
2712  portstr,
2713  (int) (UNIXSOCK_PATH_BUFLEN - 1));
2714  goto keep_going;
2715  }
2716 
2717  /*
2718  * NULL hostname tells pg_getaddrinfo_all to parse the service
2719  * name as a Unix-domain socket path.
2720  */
2721  ret = pg_getaddrinfo_all(NULL, portstr, &hint,
2722  &addrlist);
2723  if (ret || !addrlist)
2724  {
2725  libpq_append_conn_error(conn, "could not translate Unix-domain socket path \"%s\" to address: %s",
2726  portstr, gai_strerror(ret));
2727  goto keep_going;
2728  }
2729  break;
2730  }
2731 
2732  /*
2733  * Store a copy of the addrlist in private memory so we can perform
2734  * randomization for load balancing.
2735  */
2736  ret = store_conn_addrinfo(conn, addrlist);
2737  pg_freeaddrinfo_all(hint.ai_family, addrlist);
2738  if (ret)
2739  goto error_return; /* message already logged */
2740 
2741  /*
2742  * If random load balancing is enabled we shuffle the addresses.
2743  */
2745  {
2746  /*
2747  * This is the "inside-out" variant of the Fisher-Yates shuffle
2748  * algorithm. Notionally, we append each new value to the array
2749  * and then swap it with a randomly-chosen array element (possibly
2750  * including itself, else we fail to generate permutations with
2751  * the last integer last). The swap step can be optimized by
2752  * combining it with the insertion.
2753  *
2754  * We don't need to initialize conn->prng_state here, because that
2755  * already happened in connectOptions2.
2756  */
2757  for (int i = 1; i < conn->naddr; i++)
2758  {
2759  int j = pg_prng_uint64_range(&conn->prng_state, 0, i);
2760  AddrInfo temp = conn->addr[j];
2761 
2762  conn->addr[j] = conn->addr[i];
2763  conn->addr[i] = temp;
2764  }
2765  }
2766 
2767  reset_connection_state_machine = true;
2768  conn->try_next_host = false;
2769  }
2770 
2771  /* Reset connection state machine? */
2772  if (reset_connection_state_machine)
2773  {
2774  /*
2775  * (Re) initialize our connection control variables for a set of
2776  * connection attempts to a single server address. These variables
2777  * must persist across individual connection attempts, but we must
2778  * reset them when we start to consider a new server.
2779  */
2780  conn->pversion = PG_PROTOCOL(3, 0);
2781  conn->send_appname = true;
2782 #ifdef USE_SSL
2783  /* initialize these values based on SSL mode */
2784  conn->allow_ssl_try = (conn->sslmode[0] != 'd'); /* "disable" */
2785  conn->wait_ssl_try = (conn->sslmode[0] == 'a'); /* "allow" */
2786 #endif
2787 #ifdef ENABLE_GSS
2788  conn->try_gss = (conn->gssencmode[0] != 'd'); /* "disable" */
2789 #endif
2790 
2791  reset_connection_state_machine = false;
2792  need_new_connection = true;
2793  }
2794 
2795  /* Force a new connection (perhaps to the same server as before)? */
2796  if (need_new_connection)
2797  {
2798  /* Drop any existing connection */
2799  pqDropConnection(conn, true);
2800 
2801  /* Reset all state obtained from old server */
2803 
2804  /* Drop any PGresult we might have, too */
2809 
2810  /* Reset conn->status to put the state machine in the right state */
2812 
2813  need_new_connection = false;
2814  }
2815 
2816  /* Now try to advance the state machine for this connection */
2817  switch (conn->status)
2818  {
2819  case CONNECTION_NEEDED:
2820  {
2821  /*
2822  * Try to initiate a connection to one of the addresses
2823  * returned by pg_getaddrinfo_all(). conn->whichaddr is the
2824  * next one to try.
2825  *
2826  * The extra level of braces here is historical. It's not
2827  * worth reindenting this whole switch case to remove 'em.
2828  */
2829  {
2830  char host_addr[NI_MAXHOST];
2831  int sock_type;
2832  AddrInfo *addr_cur;
2833 
2834  /*
2835  * Advance to next possible host, if we've tried all of
2836  * the addresses for the current host.
2837  */
2838  if (conn->whichaddr == conn->naddr)
2839  {
2840  conn->try_next_host = true;
2841  goto keep_going;
2842  }
2843  addr_cur = &conn->addr[conn->whichaddr];
2844 
2845  /* Remember current address for possible use later */
2846  memcpy(&conn->raddr, &addr_cur->addr, sizeof(SockAddr));
2847 
2848  /*
2849  * Set connip, too. Note we purposely ignore strdup
2850  * failure; not a big problem if it fails.
2851  */
2852  if (conn->connip != NULL)
2853  {
2854  free(conn->connip);
2855  conn->connip = NULL;
2856  }
2857  getHostaddr(conn, host_addr, NI_MAXHOST);
2858  if (host_addr[0])
2859  conn->connip = strdup(host_addr);
2860 
2861  /* Try to create the socket */
2862  sock_type = SOCK_STREAM;
2863 #ifdef SOCK_CLOEXEC
2864 
2865  /*
2866  * Atomically mark close-on-exec, if possible on this
2867  * platform, so that there isn't a window where a
2868  * subprogram executed by another thread inherits the
2869  * socket. See fallback code below.
2870  */
2871  sock_type |= SOCK_CLOEXEC;
2872 #endif
2873 #ifdef SOCK_NONBLOCK
2874 
2875  /*
2876  * We might as well skip a system call for nonblocking
2877  * mode too, if we can.
2878  */
2879  sock_type |= SOCK_NONBLOCK;
2880 #endif
2881  conn->sock = socket(addr_cur->family, sock_type, 0);
2882  if (conn->sock == PGINVALID_SOCKET)
2883  {
2884  int errorno = SOCK_ERRNO;
2885 
2886  /*
2887  * Silently ignore socket() failure if we have more
2888  * addresses to try; this reduces useless chatter in
2889  * cases where the address list includes both IPv4 and
2890  * IPv6 but kernel only accepts one family.
2891  */
2892  if (conn->whichaddr < conn->naddr ||
2893  conn->whichhost + 1 < conn->nconnhost)
2894  {
2895  conn->try_next_addr = true;
2896  goto keep_going;
2897  }
2898  emitHostIdentityInfo(conn, host_addr);
2899  libpq_append_conn_error(conn, "could not create socket: %s",
2900  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
2901  goto error_return;
2902  }
2903 
2904  /*
2905  * Once we've identified a target address, all errors
2906  * except the preceding socket()-failure case should be
2907  * prefixed with host-identity information. (If the
2908  * connection succeeds, the contents of conn->errorMessage
2909  * won't matter, so this is harmless.)
2910  */
2911  emitHostIdentityInfo(conn, host_addr);
2912 
2913  /*
2914  * Select socket options: no delay of outgoing data for
2915  * TCP sockets, nonblock mode, close-on-exec. Try the
2916  * next address if any of this fails.
2917  */
2918  if (addr_cur->family != AF_UNIX)
2919  {
2920  if (!connectNoDelay(conn))
2921  {
2922  /* error message already created */
2923  conn->try_next_addr = true;
2924  goto keep_going;
2925  }
2926  }
2927 #ifndef SOCK_NONBLOCK
2928  if (!pg_set_noblock(conn->sock))
2929  {
2930  libpq_append_conn_error(conn, "could not set socket to nonblocking mode: %s",
2931  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2932  conn->try_next_addr = true;
2933  goto keep_going;
2934  }
2935 #endif
2936 
2937 #ifndef SOCK_CLOEXEC
2938 #ifdef F_SETFD
2939  if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
2940  {
2941  libpq_append_conn_error(conn, "could not set socket to close-on-exec mode: %s",
2942  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2943  conn->try_next_addr = true;
2944  goto keep_going;
2945  }
2946 #endif /* F_SETFD */
2947 #endif
2948 
2949  if (addr_cur->family != AF_UNIX)
2950  {
2951 #ifndef WIN32
2952  int on = 1;
2953 #endif
2954  int usekeepalives = useKeepalives(conn);
2955  int err = 0;
2956 
2957  if (usekeepalives < 0)
2958  {
2959  libpq_append_conn_error(conn, "keepalives parameter must be an integer");
2960  err = 1;
2961  }
2962  else if (usekeepalives == 0)
2963  {
2964  /* Do nothing */
2965  }
2966 #ifndef WIN32
2967  else if (setsockopt(conn->sock,
2968  SOL_SOCKET, SO_KEEPALIVE,
2969  (char *) &on, sizeof(on)) < 0)
2970  {
2971  libpq_append_conn_error(conn, "%s(%s) failed: %s",
2972  "setsockopt",
2973  "SO_KEEPALIVE",
2974  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2975  err = 1;
2976  }
2977  else if (!setKeepalivesIdle(conn)
2979  || !setKeepalivesCount(conn))
2980  err = 1;
2981 #else /* WIN32 */
2982 #ifdef SIO_KEEPALIVE_VALS
2983  else if (!prepKeepalivesWin32(conn))
2984  err = 1;
2985 #endif /* SIO_KEEPALIVE_VALS */
2986 #endif /* WIN32 */
2987  else if (!setTCPUserTimeout(conn))
2988  err = 1;
2989 
2990  if (err)
2991  {
2992  conn->try_next_addr = true;
2993  goto keep_going;
2994  }
2995  }
2996 
2997  /*----------
2998  * We have three methods of blocking SIGPIPE during
2999  * send() calls to this socket:
3000  *
3001  * - setsockopt(sock, SO_NOSIGPIPE)
3002  * - send(sock, ..., MSG_NOSIGNAL)
3003  * - setting the signal mask to SIG_IGN during send()
3004  *
3005  * The third method requires three syscalls per send,
3006  * so we prefer either of the first two, but they are
3007  * less portable. The state is tracked in the following
3008  * members of PGconn:
3009  *
3010  * conn->sigpipe_so - we have set up SO_NOSIGPIPE
3011  * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
3012  *
3013  * If we can use SO_NOSIGPIPE, then set sigpipe_so here
3014  * and we're done. Otherwise, set sigpipe_flag so that
3015  * we will try MSG_NOSIGNAL on sends. If we get an error
3016  * with MSG_NOSIGNAL, we'll clear that flag and revert to
3017  * signal masking.
3018  *----------
3019  */
3020  conn->sigpipe_so = false;
3021 #ifdef MSG_NOSIGNAL
3022  conn->sigpipe_flag = true;
3023 #else
3024  conn->sigpipe_flag = false;
3025 #endif /* MSG_NOSIGNAL */
3026 
3027 #ifdef SO_NOSIGPIPE
3028  optval = 1;
3029  if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
3030  (char *) &optval, sizeof(optval)) == 0)
3031  {
3032  conn->sigpipe_so = true;
3033  conn->sigpipe_flag = false;
3034  }
3035 #endif /* SO_NOSIGPIPE */
3036 
3037  /*
3038  * Start/make connection. This should not block, since we
3039  * are in nonblock mode. If it does, well, too bad.
3040  */
3041  if (connect(conn->sock, (struct sockaddr *) &addr_cur->addr.addr,
3042  addr_cur->addr.salen) < 0)
3043  {
3044  if (SOCK_ERRNO == EINPROGRESS ||
3045 #ifdef WIN32
3046  SOCK_ERRNO == EWOULDBLOCK ||
3047 #endif
3048  SOCK_ERRNO == EINTR)
3049  {
3050  /*
3051  * This is fine - we're in non-blocking mode, and
3052  * the connection is in progress. Tell caller to
3053  * wait for write-ready on socket.
3054  */
3056  return PGRES_POLLING_WRITING;
3057  }
3058  /* otherwise, trouble */
3059  }
3060  else
3061  {
3062  /*
3063  * Hm, we're connected already --- seems the "nonblock
3064  * connection" wasn't. Advance the state machine and
3065  * go do the next stuff.
3066  */
3068  goto keep_going;
3069  }
3070 
3071  /*
3072  * This connection failed. Add the error report to
3073  * conn->errorMessage, then try the next address if any.
3074  */
3076  conn->try_next_addr = true;
3077  goto keep_going;
3078  }
3079  }
3080 
3081  case CONNECTION_STARTED:
3082  {
3083  socklen_t optlen = sizeof(optval);
3084 
3085  /*
3086  * Write ready, since we've made it here, so the connection
3087  * has been made ... or has failed.
3088  */
3089 
3090  /*
3091  * Now check (using getsockopt) that there is not an error
3092  * state waiting for us on the socket.
3093  */
3094 
3095  if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
3096  (char *) &optval, &optlen) == -1)
3097  {
3098  libpq_append_conn_error(conn, "could not get socket error status: %s",
3099  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3100  goto error_return;
3101  }
3102  else if (optval != 0)
3103  {
3104  /*
3105  * When using a nonblocking connect, we will typically see
3106  * connect failures at this point, so provide a friendly
3107  * error message.
3108  */
3109  connectFailureMessage(conn, optval);
3110 
3111  /*
3112  * Try the next address if any, just as in the case where
3113  * connect() returned failure immediately.
3114  */
3115  conn->try_next_addr = true;
3116  goto keep_going;
3117  }
3118 
3119  /* Fill in the client address */
3120  conn->laddr.salen = sizeof(conn->laddr.addr);
3121  if (getsockname(conn->sock,
3122  (struct sockaddr *) &conn->laddr.addr,
3123  &conn->laddr.salen) < 0)
3124  {
3125  libpq_append_conn_error(conn, "could not get client address from socket: %s",
3126  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3127  goto error_return;
3128  }
3129 
3130  /*
3131  * Make sure we can write before advancing to next step.
3132  */
3134  return PGRES_POLLING_WRITING;
3135  }
3136 
3137  case CONNECTION_MADE:
3138  {
3139  char *startpacket;
3140  int packetlen;
3141 
3142  /*
3143  * Implement requirepeer check, if requested and it's a
3144  * Unix-domain socket.
3145  */
3146  if (conn->requirepeer && conn->requirepeer[0] &&
3147  conn->raddr.addr.ss_family == AF_UNIX)
3148  {
3149 #ifndef WIN32
3150  char *remote_username;
3151 #endif
3152  uid_t uid;
3153  gid_t gid;
3154 
3155  errno = 0;
3156  if (getpeereid(conn->sock, &uid, &gid) != 0)
3157  {
3158  /*
3159  * Provide special error message if getpeereid is a
3160  * stub
3161  */
3162  if (errno == ENOSYS)
3163  libpq_append_conn_error(conn, "requirepeer parameter is not supported on this platform");
3164  else
3165  libpq_append_conn_error(conn, "could not get peer credentials: %s",
3166  strerror_r(errno, sebuf, sizeof(sebuf)));
3167  goto error_return;
3168  }
3169 
3170 #ifndef WIN32
3171  remote_username = pg_fe_getusername(uid,
3172  &conn->errorMessage);
3173  if (remote_username == NULL)
3174  goto error_return; /* message already logged */
3175 
3176  if (strcmp(remote_username, conn->requirepeer) != 0)
3177  {
3178  libpq_append_conn_error(conn, "requirepeer specifies \"%s\", but actual peer user name is \"%s\"",
3179  conn->requirepeer, remote_username);
3180  free(remote_username);
3181  goto error_return;
3182  }
3183  free(remote_username);
3184 #else /* WIN32 */
3185  /* should have failed with ENOSYS above */
3186  Assert(false);
3187 #endif /* WIN32 */
3188  }
3189 
3190  if (conn->raddr.addr.ss_family == AF_UNIX)
3191  {
3192  /* Don't request SSL or GSSAPI over Unix sockets */
3193 #ifdef USE_SSL
3194  conn->allow_ssl_try = false;
3195 #endif
3196 #ifdef ENABLE_GSS
3197  conn->try_gss = false;
3198 #endif
3199  }
3200 
3201 #ifdef ENABLE_GSS
3202 
3203  /*
3204  * If GSSAPI encryption is enabled, then call
3205  * pg_GSS_have_cred_cache() which will return true if we can
3206  * acquire credentials (and give us a handle to use in
3207  * conn->gcred), and then send a packet to the server asking
3208  * for GSSAPI Encryption (and skip past SSL negotiation and
3209  * regular startup below).
3210  */
3211  if (conn->try_gss && !conn->gctx)
3212  conn->try_gss = pg_GSS_have_cred_cache(&conn->gcred);
3213  if (conn->try_gss && !conn->gctx)
3214  {
3216 
3217  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3218  {
3219  libpq_append_conn_error(conn, "could not send GSSAPI negotiation packet: %s",
3220  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3221  goto error_return;
3222  }
3223 
3224  /* Ok, wait for response */
3226  return PGRES_POLLING_READING;
3227  }
3228  else if (!conn->gctx && conn->gssencmode[0] == 'r')
3229  {
3231  "GSSAPI encryption required but was impossible (possibly no credential cache, no server support, or using a local socket)");
3232  goto error_return;
3233  }
3234 #endif
3235 
3236 #ifdef USE_SSL
3237 
3238  /*
3239  * Enable the libcrypto callbacks before checking if SSL needs
3240  * to be done. This is done before sending the startup packet
3241  * as depending on the type of authentication done, like MD5
3242  * or SCRAM that use cryptohashes, the callbacks would be
3243  * required even without a SSL connection
3244  */
3245  if (pqsecure_initialize(conn, false, true) < 0)
3246  goto error_return;
3247 
3248  /*
3249  * If SSL is enabled and we haven't already got encryption of
3250  * some sort running, request SSL instead of sending the
3251  * startup message.
3252  */
3253  if (conn->allow_ssl_try && !conn->wait_ssl_try &&
3254  !conn->ssl_in_use
3255 #ifdef ENABLE_GSS
3256  && !conn->gssenc
3257 #endif
3258  )
3259  {
3260  ProtocolVersion pv;
3261 
3262  /*
3263  * Send the SSL request packet.
3264  *
3265  * Theoretically, this could block, but it really
3266  * shouldn't since we only got here if the socket is
3267  * write-ready.
3268  */
3270  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3271  {
3272  libpq_append_conn_error(conn, "could not send SSL negotiation packet: %s",
3273  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3274  goto error_return;
3275  }
3276  /* Ok, wait for response */
3278  return PGRES_POLLING_READING;
3279  }
3280 #endif /* USE_SSL */
3281 
3282  /*
3283  * Build the startup packet.
3284  */
3285  startpacket = pqBuildStartupPacket3(conn, &packetlen,
3287  if (!startpacket)
3288  {
3289  libpq_append_conn_error(conn, "out of memory");
3290  goto error_return;
3291  }
3292 
3293  /*
3294  * Send the startup packet.
3295  *
3296  * Theoretically, this could block, but it really shouldn't
3297  * since we only got here if the socket is write-ready.
3298  */
3299  if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
3300  {
3301  libpq_append_conn_error(conn, "could not send startup packet: %s",
3302  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3303  free(startpacket);
3304  goto error_return;
3305  }
3306 
3307  free(startpacket);
3308 
3310  return PGRES_POLLING_READING;
3311  }
3312 
3313  /*
3314  * Handle SSL negotiation: wait for postmaster messages and
3315  * respond as necessary.
3316  */
3318  {
3319 #ifdef USE_SSL
3320  PostgresPollingStatusType pollres;
3321 
3322  /*
3323  * On first time through, get the postmaster's response to our
3324  * SSL negotiation packet.
3325  */
3326  if (!conn->ssl_in_use)
3327  {
3328  /*
3329  * We use pqReadData here since it has the logic to
3330  * distinguish no-data-yet from connection closure. Since
3331  * conn->ssl isn't set, a plain recv() will occur.
3332  */
3333  char SSLok;
3334  int rdresult;
3335 
3336  rdresult = pqReadData(conn);
3337  if (rdresult < 0)
3338  {
3339  /* errorMessage is already filled in */
3340  goto error_return;
3341  }
3342  if (rdresult == 0)
3343  {
3344  /* caller failed to wait for data */
3345  return PGRES_POLLING_READING;
3346  }
3347  if (pqGetc(&SSLok, conn) < 0)
3348  {
3349  /* should not happen really */
3350  return PGRES_POLLING_READING;
3351  }
3352  if (SSLok == 'S')
3353  {
3354  /* mark byte consumed */
3355  conn->inStart = conn->inCursor;
3356 
3357  /*
3358  * Set up global SSL state if required. The crypto
3359  * state has already been set if libpq took care of
3360  * doing that, so there is no need to make that happen
3361  * again.
3362  */
3363  if (pqsecure_initialize(conn, true, false) != 0)
3364  goto error_return;
3365  }
3366  else if (SSLok == 'N')
3367  {
3368  /* mark byte consumed */
3369  conn->inStart = conn->inCursor;
3370  /* OK to do without SSL? */
3371  if (conn->sslmode[0] == 'r' || /* "require" */
3372  conn->sslmode[0] == 'v') /* "verify-ca" or
3373  * "verify-full" */
3374  {
3375  /* Require SSL, but server does not want it */
3376  libpq_append_conn_error(conn, "server does not support SSL, but SSL was required");
3377  goto error_return;
3378  }
3379  /* Otherwise, proceed with normal startup */
3380  conn->allow_ssl_try = false;
3381  /* We can proceed using this connection */
3383  return PGRES_POLLING_WRITING;
3384  }
3385  else if (SSLok == 'E')
3386  {
3387  /*
3388  * Server failure of some sort, such as failure to
3389  * fork a backend process. We need to process and
3390  * report the error message, which might be formatted
3391  * according to either protocol 2 or protocol 3.
3392  * Rather than duplicate the code for that, we flip
3393  * into AWAITING_RESPONSE state and let the code there
3394  * deal with it. Note we have *not* consumed the "E"
3395  * byte here.
3396  */
3398  goto keep_going;
3399  }
3400  else
3401  {
3402  libpq_append_conn_error(conn, "received invalid response to SSL negotiation: %c",
3403  SSLok);
3404  goto error_return;
3405  }
3406  }
3407 
3408  /*
3409  * Begin or continue the SSL negotiation process.
3410  */
3411  pollres = pqsecure_open_client(conn);
3412  if (pollres == PGRES_POLLING_OK)
3413  {
3414  /*
3415  * At this point we should have no data already buffered.
3416  * If we do, it was received before we performed the SSL
3417  * handshake, so it wasn't encrypted and indeed may have
3418  * been injected by a man-in-the-middle.
3419  */
3420  if (conn->inCursor != conn->inEnd)
3421  {
3422  libpq_append_conn_error(conn, "received unencrypted data after SSL response");
3423  goto error_return;
3424  }
3425 
3426  /* SSL handshake done, ready to send startup packet */
3428  return PGRES_POLLING_WRITING;
3429  }
3430  if (pollres == PGRES_POLLING_FAILED)
3431  {
3432  /*
3433  * Failed ... if sslmode is "prefer" then do a non-SSL
3434  * retry
3435  */
3436  if (conn->sslmode[0] == 'p' /* "prefer" */
3437  && conn->allow_ssl_try /* redundant? */
3438  && !conn->wait_ssl_try) /* redundant? */
3439  {
3440  /* only retry once */
3441  conn->allow_ssl_try = false;
3442  need_new_connection = true;
3443  goto keep_going;
3444  }
3445  /* Else it's a hard failure */
3446  goto error_return;
3447  }
3448  /* Else, return POLLING_READING or POLLING_WRITING status */
3449  return pollres;
3450 #else /* !USE_SSL */
3451  /* can't get here */
3452  goto error_return;
3453 #endif /* USE_SSL */
3454  }
3455 
3457  {
3458 #ifdef ENABLE_GSS
3459  PostgresPollingStatusType pollres;
3460 
3461  /*
3462  * If we haven't yet, get the postmaster's response to our
3463  * negotiation packet
3464  */
3465  if (conn->try_gss && !conn->gctx)
3466  {
3467  char gss_ok;
3468  int rdresult = pqReadData(conn);
3469 
3470  if (rdresult < 0)
3471  /* pqReadData fills in error message */
3472  goto error_return;
3473  else if (rdresult == 0)
3474  /* caller failed to wait for data */
3475  return PGRES_POLLING_READING;
3476  if (pqGetc(&gss_ok, conn) < 0)
3477  /* shouldn't happen... */
3478  return PGRES_POLLING_READING;
3479 
3480  if (gss_ok == 'E')
3481  {
3482  /*
3483  * Server failure of some sort. Assume it's a
3484  * protocol version support failure, and let's see if
3485  * we can't recover (if it's not, we'll get a better
3486  * error message on retry). Server gets fussy if we
3487  * don't hang up the socket, though.
3488  */
3489  conn->try_gss = false;
3490  need_new_connection = true;
3491  goto keep_going;
3492  }
3493 
3494  /* mark byte consumed */
3495  conn->inStart = conn->inCursor;
3496 
3497  if (gss_ok == 'N')
3498  {
3499  /* Server doesn't want GSSAPI; fall back if we can */
3500  if (conn->gssencmode[0] == 'r')
3501  {
3502  libpq_append_conn_error(conn, "server doesn't support GSSAPI encryption, but it was required");
3503  goto error_return;
3504  }
3505 
3506  conn->try_gss = false;
3507  /* We can proceed using this connection */
3509  return PGRES_POLLING_WRITING;
3510  }
3511  else if (gss_ok != 'G')
3512  {
3513  libpq_append_conn_error(conn, "received invalid response to GSSAPI negotiation: %c",
3514  gss_ok);
3515  goto error_return;
3516  }
3517  }
3518 
3519  /* Begin or continue GSSAPI negotiation */
3520  pollres = pqsecure_open_gss(conn);
3521  if (pollres == PGRES_POLLING_OK)
3522  {
3523  /*
3524  * At this point we should have no data already buffered.
3525  * If we do, it was received before we performed the GSS
3526  * handshake, so it wasn't encrypted and indeed may have
3527  * been injected by a man-in-the-middle.
3528  */
3529  if (conn->inCursor != conn->inEnd)
3530  {
3531  libpq_append_conn_error(conn, "received unencrypted data after GSSAPI encryption response");
3532  goto error_return;
3533  }
3534 
3535  /* All set for startup packet */
3537  return PGRES_POLLING_WRITING;
3538  }
3539  else if (pollres == PGRES_POLLING_FAILED)
3540  {
3541  if (conn->gssencmode[0] == 'p')
3542  {
3543  /*
3544  * We failed, but we can retry on "prefer". Have to
3545  * drop the current connection to do so, though.
3546  */
3547  conn->try_gss = false;
3548  need_new_connection = true;
3549  goto keep_going;
3550  }
3551  /* Else it's a hard failure */
3552  goto error_return;
3553  }
3554  /* Else, return POLLING_READING or POLLING_WRITING status */
3555  return pollres;
3556 #else /* !ENABLE_GSS */
3557  /* unreachable */
3558  goto error_return;
3559 #endif /* ENABLE_GSS */
3560  }
3561 
3562  /*
3563  * Handle authentication exchange: wait for postmaster messages
3564  * and respond as necessary.
3565  */
3567  {
3568  char beresp;
3569  int msgLength;
3570  int avail;
3571  AuthRequest areq;
3572  int res;
3573 
3574  /*
3575  * Scan the message from current point (note that if we find
3576  * the message is incomplete, we will return without advancing
3577  * inStart, and resume here next time).
3578  */
3579  conn->inCursor = conn->inStart;
3580 
3581  /* Read type byte */
3582  if (pqGetc(&beresp, conn))
3583  {
3584  /* We'll come back when there is more data */
3585  return PGRES_POLLING_READING;
3586  }
3587 
3588  /*
3589  * Validate message type: we expect only an authentication
3590  * request, NegotiateProtocolVersion, or an error here.
3591  * Anything else probably means it's not Postgres on the other
3592  * end at all.
3593  */
3594  if (beresp != PqMsg_AuthenticationRequest &&
3595  beresp != PqMsg_ErrorResponse &&
3597  {
3598  libpq_append_conn_error(conn, "expected authentication request from server, but received %c",
3599  beresp);
3600  goto error_return;
3601  }
3602 
3603  /* Read message length word */
3604  if (pqGetInt(&msgLength, 4, conn))
3605  {
3606  /* We'll come back when there is more data */
3607  return PGRES_POLLING_READING;
3608  }
3609 
3610  /*
3611  * Try to validate message length before using it.
3612  *
3613  * Authentication requests can't be very large, although GSS
3614  * auth requests may not be that small. Same for
3615  * NegotiateProtocolVersion.
3616  *
3617  * Errors can be a little larger, but not huge. If we see a
3618  * large apparent length in an error, it means we're really
3619  * talking to a pre-3.0-protocol server; cope. (Before
3620  * version 14, the server also used the old protocol for
3621  * errors that happened before processing the startup packet.)
3622  */
3623  if (beresp == PqMsg_AuthenticationRequest &&
3624  (msgLength < 8 || msgLength > 2000))
3625  {
3626  libpq_append_conn_error(conn, "received invalid authentication request");
3627  goto error_return;
3628  }
3629  if (beresp == PqMsg_NegotiateProtocolVersion &&
3630  (msgLength < 8 || msgLength > 2000))
3631  {
3632  libpq_append_conn_error(conn, "received invalid protocol negotiation message");
3633  goto error_return;
3634  }
3635 
3636 #define MAX_ERRLEN 30000
3637  if (beresp == PqMsg_ErrorResponse &&
3638  (msgLength < 8 || msgLength > MAX_ERRLEN))
3639  {
3640  /* Handle error from a pre-3.0 server */
3641  conn->inCursor = conn->inStart + 1; /* reread data */
3643  {
3644  /*
3645  * We may not have authenticated the server yet, so
3646  * don't let the buffer grow forever.
3647  */
3648  avail = conn->inEnd - conn->inCursor;
3649  if (avail > MAX_ERRLEN)
3650  {
3651  libpq_append_conn_error(conn, "received invalid error message");
3652  goto error_return;
3653  }
3654 
3655  /* We'll come back when there is more data */
3656  return PGRES_POLLING_READING;
3657  }
3658  /* OK, we read the message; mark data consumed */
3659  conn->inStart = conn->inCursor;
3660 
3661  /*
3662  * Before 7.2, the postmaster didn't always end its
3663  * messages with a newline, so add one if needed to
3664  * conform to libpq conventions.
3665  */
3666  if (conn->errorMessage.len == 0 ||
3667  conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3668  {
3670  }
3671 
3672  goto error_return;
3673  }
3674 #undef MAX_ERRLEN
3675 
3676  /*
3677  * Can't process if message body isn't all here yet.
3678  *
3679  * After this check passes, any further EOF during parsing
3680  * implies that the server sent a bad/truncated message.
3681  * Reading more bytes won't help in that case, so don't return
3682  * PGRES_POLLING_READING after this point.
3683  */
3684  msgLength -= 4;
3685  avail = conn->inEnd - conn->inCursor;
3686  if (avail < msgLength)
3687  {
3688  /*
3689  * Before returning, try to enlarge the input buffer if
3690  * needed to hold the whole message; see notes in
3691  * pqParseInput3.
3692  */
3693  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
3694  conn))
3695  goto error_return;
3696  /* We'll come back when there is more data */
3697  return PGRES_POLLING_READING;
3698  }
3699 
3700  /* Handle errors. */
3701  if (beresp == PqMsg_ErrorResponse)
3702  {
3703  if (pqGetErrorNotice3(conn, true))
3704  {
3705  libpq_append_conn_error(conn, "received invalid error message");
3706  goto error_return;
3707  }
3708  /* OK, we read the message; mark data consumed */
3709  conn->inStart = conn->inCursor;
3710 
3711  /*
3712  * If error is "cannot connect now", try the next host if
3713  * any (but we don't want to consider additional addresses
3714  * for this host, nor is there much point in changing SSL
3715  * or GSS mode). This is helpful when dealing with
3716  * standby servers that might not be in hot-standby state.
3717  */
3718  if (strcmp(conn->last_sqlstate,
3720  {
3721  conn->try_next_host = true;
3722  goto keep_going;
3723  }
3724 
3725  /* Check to see if we should mention pgpassfile */
3727 
3728 #ifdef ENABLE_GSS
3729 
3730  /*
3731  * If gssencmode is "prefer" and we're using GSSAPI, retry
3732  * without it.
3733  */
3734  if (conn->gssenc && conn->gssencmode[0] == 'p')
3735  {
3736  /* only retry once */
3737  conn->try_gss = false;
3738  need_new_connection = true;
3739  goto keep_going;
3740  }
3741 #endif
3742 
3743 #ifdef USE_SSL
3744 
3745  /*
3746  * if sslmode is "allow" and we haven't tried an SSL
3747  * connection already, then retry with an SSL connection
3748  */
3749  if (conn->sslmode[0] == 'a' /* "allow" */
3750  && !conn->ssl_in_use
3751  && conn->allow_ssl_try
3752  && conn->wait_ssl_try)
3753  {
3754  /* only retry once */
3755  conn->wait_ssl_try = false;
3756  need_new_connection = true;
3757  goto keep_going;
3758  }
3759 
3760  /*
3761  * if sslmode is "prefer" and we're in an SSL connection,
3762  * then do a non-SSL retry
3763  */
3764  if (conn->sslmode[0] == 'p' /* "prefer" */
3765  && conn->ssl_in_use
3766  && conn->allow_ssl_try /* redundant? */
3767  && !conn->wait_ssl_try) /* redundant? */
3768  {
3769  /* only retry once */
3770  conn->allow_ssl_try = false;
3771  need_new_connection = true;
3772  goto keep_going;
3773  }
3774 #endif
3775 
3776  goto error_return;
3777  }
3778  else if (beresp == PqMsg_NegotiateProtocolVersion)
3779  {
3781  {
3782  libpq_append_conn_error(conn, "received invalid protocol negotiation message");
3783  goto error_return;
3784  }
3785  /* OK, we read the message; mark data consumed */
3786  conn->inStart = conn->inCursor;
3787  goto error_return;
3788  }
3789 
3790  /* It is an authentication request. */
3791  conn->auth_req_received = true;
3792 
3793  /* Get the type of request. */
3794  if (pqGetInt((int *) &areq, 4, conn))
3795  {
3796  /* can't happen because we checked the length already */
3797  libpq_append_conn_error(conn, "received invalid authentication request");
3798  goto error_return;
3799  }
3800  msgLength -= 4;
3801 
3802  /*
3803  * Process the rest of the authentication request message, and
3804  * respond to it if necessary.
3805  *
3806  * Note that conn->pghost must be non-NULL if we are going to
3807  * avoid the Kerberos code doing a hostname look-up.
3808  */
3809  res = pg_fe_sendauth(areq, msgLength, conn);
3810 
3811  /* OK, we have processed the message; mark data consumed */
3812  conn->inStart = conn->inCursor;
3813 
3814  if (res != STATUS_OK)
3815  goto error_return;
3816 
3817  /*
3818  * Just make sure that any data sent by pg_fe_sendauth is
3819  * flushed out. Although this theoretically could block, it
3820  * really shouldn't since we don't send large auth responses.
3821  */
3822  if (pqFlush(conn))
3823  goto error_return;
3824 
3825  if (areq == AUTH_REQ_OK)
3826  {
3827  /* We are done with authentication exchange */
3829 
3830  /*
3831  * Set asyncStatus so that PQgetResult will think that
3832  * what comes back next is the result of a query. See
3833  * below.
3834  */
3836  }
3837 
3838  /* Look to see if we have more data yet. */
3839  goto keep_going;
3840  }
3841 
3842  case CONNECTION_AUTH_OK:
3843  {
3844  /*
3845  * Now we expect to hear from the backend. A ReadyForQuery
3846  * message indicates that startup is successful, but we might
3847  * also get an Error message indicating failure. (Notice
3848  * messages indicating nonfatal warnings are also allowed by
3849  * the protocol, as are ParameterStatus and BackendKeyData
3850  * messages.) Easiest way to handle this is to let
3851  * PQgetResult() read the messages. We just have to fake it
3852  * out about the state of the connection, by setting
3853  * asyncStatus = PGASYNC_BUSY (done above).
3854  */
3855 
3856  if (PQisBusy(conn))
3857  return PGRES_POLLING_READING;
3858 
3859  res = PQgetResult(conn);
3860 
3861  /*
3862  * NULL return indicating we have gone to IDLE state is
3863  * expected
3864  */
3865  if (res)
3866  {
3868  libpq_append_conn_error(conn, "unexpected message from server during startup");
3869  else if (conn->send_appname &&
3870  (conn->appname || conn->fbappname))
3871  {
3872  /*
3873  * If we tried to send application_name, check to see
3874  * if the error is about that --- pre-9.0 servers will
3875  * reject it at this stage of the process. If so,
3876  * close the connection and retry without sending
3877  * application_name. We could possibly get a false
3878  * SQLSTATE match here and retry uselessly, but there
3879  * seems no great harm in that; we'll just get the
3880  * same error again if it's unrelated.
3881  */
3882  const char *sqlstate;
3883 
3885  if (sqlstate &&
3886  strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
3887  {
3888  PQclear(res);
3889  conn->send_appname = false;
3890  need_new_connection = true;
3891  goto keep_going;
3892  }
3893  }
3894 
3895  /*
3896  * if the resultStatus is FATAL, then conn->errorMessage
3897  * already has a copy of the error; needn't copy it back.
3898  * But add a newline if it's not there already, since
3899  * postmaster error messages may not have one.
3900  */
3901  if (conn->errorMessage.len <= 0 ||
3902  conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3904  PQclear(res);
3905  goto error_return;
3906  }
3907 
3908  /* Almost there now ... */
3910  goto keep_going;
3911  }
3912 
3914  {
3915  /*
3916  * If a read-write, read-only, primary, or standby connection
3917  * is required, see if we have one.
3918  */
3921  {
3922  bool read_only_server;
3923 
3924  /*
3925  * If the server didn't report
3926  * "default_transaction_read_only" or "in_hot_standby" at
3927  * startup, we must determine its state by sending the
3928  * query "SHOW transaction_read_only". This GUC exists in
3929  * all server versions that support 3.0 protocol.
3930  */
3933  {
3934  /*
3935  * We use PQsendQueryContinue so that
3936  * conn->errorMessage does not get cleared. We need
3937  * to preserve any error messages related to previous
3938  * hosts we have tried and failed to connect to.
3939  */
3942  "SHOW transaction_read_only"))
3943  goto error_return;
3944  /* We'll return to this state when we have the answer */
3946  return PGRES_POLLING_READING;
3947  }
3948 
3949  /* OK, we can make the test */
3950  read_only_server =
3953 
3955  read_only_server : !read_only_server)
3956  {
3957  /* Wrong server state, reject and try the next host */
3959  libpq_append_conn_error(conn, "session is read-only");
3960  else
3961  libpq_append_conn_error(conn, "session is not read-only");
3962 
3963  /* Close connection politely. */
3966 
3967  /*
3968  * Try next host if any, but we don't want to consider
3969  * additional addresses for this host.
3970  */
3971  conn->try_next_host = true;
3972  goto keep_going;
3973  }
3974  }
3978  {
3979  /*
3980  * If the server didn't report "in_hot_standby" at
3981  * startup, we must determine its state by sending the
3982  * query "SELECT pg_catalog.pg_is_in_recovery()". Servers
3983  * before 9.0 don't have that function, but by the same
3984  * token they don't have any standby mode, so we may just
3985  * assume the result.
3986  */
3987  if (conn->sversion < 90000)
3989 
3991  {
3992  /*
3993  * We use PQsendQueryContinue so that
3994  * conn->errorMessage does not get cleared. We need
3995  * to preserve any error messages related to previous
3996  * hosts we have tried and failed to connect to.
3997  */
4000  "SELECT pg_catalog.pg_is_in_recovery()"))
4001  goto error_return;
4002  /* We'll return to this state when we have the answer */
4004  return PGRES_POLLING_READING;
4005  }
4006 
4007  /* OK, we can make the test */
4011  {
4012  /* Wrong server state, reject and try the next host */
4014  libpq_append_conn_error(conn, "server is in hot standby mode");
4015  else
4016  libpq_append_conn_error(conn, "server is not in hot standby mode");
4017 
4018  /* Close connection politely. */
4021 
4022  /*
4023  * Try next host if any, but we don't want to consider
4024  * additional addresses for this host.
4025  */
4026  conn->try_next_host = true;
4027  goto keep_going;
4028  }
4029  }
4030 
4031  /* We can release the address list now. */
4033 
4034  /*
4035  * Contents of conn->errorMessage are no longer interesting
4036  * (and it seems some clients expect it to be empty after a
4037  * successful connection).
4038  */
4040 
4041  /* We are open for business! */
4043  return PGRES_POLLING_OK;
4044  }
4045 
4046  case CONNECTION_CONSUME:
4047  {
4048  /*
4049  * This state just makes sure the connection is idle after
4050  * we've obtained the result of a SHOW or SELECT query. Once
4051  * we're clear, return to CONNECTION_CHECK_TARGET state to
4052  * decide what to do next. We must transiently set status =
4053  * CONNECTION_OK in order to use the result-consuming
4054  * subroutines.
4055  */
4057  if (!PQconsumeInput(conn))
4058  goto error_return;
4059 
4060  if (PQisBusy(conn))
4061  {
4063  return PGRES_POLLING_READING;
4064  }
4065 
4066  /* Call PQgetResult() again until we get a NULL result */
4067  res = PQgetResult(conn);
4068  if (res != NULL)
4069  {
4070  PQclear(res);
4072  return PGRES_POLLING_READING;
4073  }
4074 
4076  goto keep_going;
4077  }
4078 
4080  {
4081  /*
4082  * Waiting for result of "SHOW transaction_read_only". We
4083  * must transiently set status = CONNECTION_OK in order to use
4084  * the result-consuming subroutines.
4085  */
4087  if (!PQconsumeInput(conn))
4088  goto error_return;
4089 
4090  if (PQisBusy(conn))
4091  {
4093  return PGRES_POLLING_READING;
4094  }
4095 
4096  res = PQgetResult(conn);
4097  if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
4098  PQntuples(res) == 1)
4099  {
4100  char *val = PQgetvalue(res, 0, 0);
4101 
4102  /*
4103  * "transaction_read_only = on" proves that at least one
4104  * of default_transaction_read_only and in_hot_standby is
4105  * on, but we don't actually know which. We don't care
4106  * though for the purpose of identifying a read-only
4107  * session, so satisfy the CONNECTION_CHECK_TARGET code by
4108  * claiming they are both on. On the other hand, if it's
4109  * a read-write session, they are certainly both off.
4110  */
4111  if (strncmp(val, "on", 2) == 0)
4112  {
4115  }
4116  else
4117  {
4120  }
4121  PQclear(res);
4122 
4123  /* Finish reading messages before continuing */
4125  goto keep_going;
4126  }
4127 
4128  /* Something went wrong with "SHOW transaction_read_only". */
4129  PQclear(res);
4130 
4131  /* Append error report to conn->errorMessage. */
4132  libpq_append_conn_error(conn, "\"%s\" failed",
4133  "SHOW transaction_read_only");
4134 
4135  /* Close connection politely. */
4138 
4139  /* Try next host. */
4140  conn->try_next_host = true;
4141  goto keep_going;
4142  }
4143 
4145  {
4146  /*
4147  * Waiting for result of "SELECT pg_is_in_recovery()". We
4148  * must transiently set status = CONNECTION_OK in order to use
4149  * the result-consuming subroutines.
4150  */
4152  if (!PQconsumeInput(conn))
4153  goto error_return;
4154 
4155  if (PQisBusy(conn))
4156  {
4158  return PGRES_POLLING_READING;
4159  }
4160 
4161  res = PQgetResult(conn);
4162  if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
4163  PQntuples(res) == 1)
4164  {
4165  char *val = PQgetvalue(res, 0, 0);
4166 
4167  if (strncmp(val, "t", 1) == 0)
4169  else
4171  PQclear(res);
4172 
4173  /* Finish reading messages before continuing */
4175  goto keep_going;
4176  }
4177 
4178  /* Something went wrong with "SELECT pg_is_in_recovery()". */
4179  PQclear(res);
4180 
4181  /* Append error report to conn->errorMessage. */
4182  libpq_append_conn_error(conn, "\"%s\" failed",
4183  "SELECT pg_is_in_recovery()");
4184 
4185  /* Close connection politely. */
4188 
4189  /* Try next host. */
4190  conn->try_next_host = true;
4191  goto keep_going;
4192  }
4193 
4194  default:
4196  "invalid connection state %d, probably indicative of memory corruption",
4197  conn->status);
4198  goto error_return;
4199  }
4200 
4201  /* Unreachable */
4202 
4203 error_return:
4204 
4205  /*
4206  * We used to close the socket at this point, but that makes it awkward
4207  * for those above us if they wish to remove this socket from their own
4208  * records (an fd_set for example). We'll just have this socket closed
4209  * when PQfinish is called (which is compulsory even after an error, since
4210  * the connection structure must be freed).
4211  */
4213  return PGRES_POLLING_FAILED;
4214 }
#define STATUS_OK
Definition: c.h:1182
#define MemSet(start, val, len)
Definition: c.h:1009
void err(int eval, const char *fmt,...)
Definition: err.c:43
int pg_fe_sendauth(AuthRequest areq, int payloadlen, PGconn *conn)
Definition: fe-auth.c:962
char * pg_fe_getusername(uid_t user_id, PQExpBuffer errorMessage)
Definition: fe-auth.c:1170
#define MAX_ERRLEN
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:467
static const PQEnvironmentOption EnvironmentOptions[]
Definition: fe-connect.c:367
static void sendTerminateConn(PGconn *conn)
Definition: fe-connect.c:4536
static int setKeepalivesCount(PGconn *conn)
Definition: fe-connect.c:2199
static int useKeepalives(PGconn *conn)
Definition: fe-connect.c:2066
static int store_conn_addrinfo(PGconn *conn, struct addrinfo *addrlist)
Definition: fe-connect.c:4483
static void connectFailureMessage(PGconn *conn, int errorno)
Definition: fe-connect.c:2046
static void release_conn_addrinfo(PGconn *conn)
Definition: fe-connect.c:4522
#define ERRCODE_APPNAME_UNKNOWN
Definition: fe-connect.c:86
static int setKeepalivesInterval(PGconn *conn)
Definition: fe-connect.c:2164
static int setKeepalivesIdle(PGconn *conn)
Definition: fe-connect.c:2130
static void pgpassfileWarning(PGconn *conn)
Definition: fe-connect.c:7654
static bool parse_int_param(const char *value, int *result, PGconn *conn, const char *context)
Definition: fe-connect.c:2085
static void emitHostIdentityInfo(PGconn *conn, const char *host_addr)
Definition: fe-connect.c:1990
static int setTCPUserTimeout(PGconn *conn)
Definition: fe-connect.c:2296
static void pqDropServerData(PGconn *conn)
Definition: fe-connect.c:580
static int connectNoDelay(PGconn *conn)
Definition: fe-connect.c:1931
static void getHostaddr(PGconn *conn, char *host_addr, int host_addr_len)
Definition: fe-connect.c:1957
#define ERRCODE_CANNOT_CONNECT_NOW
Definition: fe-connect.c:91
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:5077
int PQsendQueryContinue(PGconn *conn, const char *query)
Definition: fe-exec.c:1428
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3395
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1957
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3790
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:776
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2004
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3380
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2035
bool pg_GSS_have_cred_cache(gss_cred_id_t *cred_out)
int pqReadData(PGconn *conn)
Definition: fe-misc.c:566
int pqFlush(PGconn *conn)
Definition: fe-misc.c:954
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:78
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:217
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:352
int pqGets_append(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:143
int pqGetNegotiateProtocolVersion3(PGconn *conn)
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:886
char * pqBuildStartupPacket3(PGconn *conn, int *packetlen, const PQEnvironmentOption *options)
PostgresPollingStatusType pqsecure_open_gss(PGconn *conn)
PostgresPollingStatusType pqsecure_open_client(PGconn *conn)
Definition: fe-secure.c:153
int pqsecure_initialize(PGconn *conn, bool do_ssl, bool do_crypto)
Definition: fe-secure.c:138
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:82
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:53
int j
Definition: isn.c:74
@ PGASYNC_IDLE
Definition: libpq-int.h:221
@ PGASYNC_BUSY
Definition: libpq-int.h:222
@ LOAD_BALANCE_RANDOM
Definition: libpq-int.h:250
#define SOCK_STRERROR
Definition: libpq-int.h:922
@ CHT_UNIX_SOCKET
Definition: libpq-int.h:311
@ CHT_HOST_ADDRESS
Definition: libpq-int.h:310
@ CHT_HOST_NAME
Definition: libpq-int.h:309
@ PG_BOOL_YES
Definition: libpq-int.h:257
@ PG_BOOL_NO
Definition: libpq-int.h:258
@ PG_BOOL_UNKNOWN
Definition: libpq-int.h:256
@ SERVER_TYPE_STANDBY
Definition: libpq-int.h:241
@ SERVER_TYPE_PRIMARY
Definition: libpq-int.h:240
@ SERVER_TYPE_READ_WRITE
Definition: libpq-int.h:238
@ SERVER_TYPE_PREFER_STANDBY_PASS2
Definition: libpq-int.h:243
@ SERVER_TYPE_PREFER_STANDBY
Definition: libpq-int.h:242
@ SERVER_TYPE_READ_ONLY
Definition: libpq-int.h:239
#define MAXPGPATH
uint64 pg_prng_uint64_range(pg_prng_state *state, uint64 rmin, uint64 rmax)
Definition: pg_prng.c:144
bool pg_set_noblock(pgsocket sock)
Definition: noblock.c:25
#define snprintf
Definition: port.h:238
unsigned int socklen_t
Definition: port.h:40
int getpeereid(int sock, uid_t *uid, gid_t *gid)
Definition: getpeereid.c:33
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:56
#define UNIXSOCK_PATH(path, port, sockdir)
Definition: pqcomm.h:44
#define UNIXSOCK_PATH_BUFLEN
Definition: pqcomm.h:60
#define NEGOTIATE_GSS_CODE
Definition: pqcomm.h:148
#define NEGOTIATE_SSL_CODE
Definition: pqcomm.h:147
uint32 ProtocolVersion
Definition: pqcomm.h:99
uint32 AuthRequest
Definition: pqcomm.h:121
#define PG_PROTOCOL(m, n)
Definition: pqcomm.h:89
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:378
#define AUTH_REQ_OK
Definition: protocol.h:70
#define PqMsg_AuthenticationRequest
Definition: protocol.h:50
#define PqMsg_NegotiateProtocolVersion
Definition: protocol.h:59
#define PqMsg_ErrorResponse
Definition: protocol.h:44
int family
Definition: pqcomm.h:38
SockAddr addr
Definition: pqcomm.h:39
char * host
Definition: libpq-int.h:346
char * port
Definition: libpq-int.h:348
char * hostaddr
Definition: libpq-int.h:347
pg_conn_host_type type
Definition: libpq-int.h:345
SockAddr laddr
Definition: libpq-int.h:461
bool try_next_host
Definition: libpq-int.h:486
AddrInfo * addr
Definition: libpq-int.h:489
bool sigpipe_flag
Definition: libpq-int.h:469
int nconnhost
Definition: libpq-int.h:440
pgsocket sock
Definition: libpq-int.h:459
ProtocolVersion pversion
Definition: libpq-int.h:463
bool send_appname
Definition: libpq-int.h:491
PGTransactionStatusType xactStatus
Definition: libpq-int.h:427
int inCursor
Definition: libpq-int.h:511
PGTernaryBool in_hot_standby
Definition: libpq-int.h:500
int inEnd
Definition: libpq-int.h:512
char * fbappname
Definition: libpq-int.h:376
int naddr
Definition: libpq-int.h:487
int inStart
Definition: libpq-int.h:510
char * connip
Definition: libpq-int.h:443
int sversion
Definition: libpq-int.h:464
bool auth_req_received
Definition: libpq-int.h:465
PGTernaryBool default_transaction_read_only
Definition: libpq-int.h:499
bool sigpipe_so
Definition: libpq-int.h:468
int whichaddr
Definition: libpq-int.h:488
char * appname
Definition: libpq-int.h:375
char * sslmode
Definition: libpq-int.h:390
pg_prng_state prng_state
Definition: libpq-int.h:504
PQExpBufferData errorMessage
Definition: libpq-int.h:617
char * gssencmode
Definition: libpq-int.h:401
char last_sqlstate[6]
Definition: libpq-int.h:428
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:426
PGLoadBalanceType load_balance_type
Definition: libpq-int.h:483
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:432
PGTargetServerType target_server_type
Definition: libpq-int.h:482
SockAddr raddr
Definition: libpq-int.h:462
bool try_next_addr
Definition: libpq-int.h:485
int whichhost
Definition: libpq-int.h:441
char * requirepeer
Definition: libpq-int.h:400
pg_conn_host * connhost
Definition: libpq-int.h:442
bool ssl_in_use
Definition: libpq-int.h:547
ExecStatusType resultStatus
Definition: libpq-int.h:180
#define EWOULDBLOCK
Definition: win32_port.h:380
#define EINPROGRESS
Definition: win32_port.h:386
int gid_t
Definition: win32_port.h:245
int uid_t
Definition: win32_port.h:244

References AddrInfo::addr, SockAddr::addr, pg_conn::addr, appendPQExpBufferChar(), pg_conn::appname, Assert(), pg_conn::asyncStatus, AUTH_REQ_OK, pg_conn::auth_req_received, CHT_HOST_ADDRESS, CHT_HOST_NAME, CHT_UNIX_SOCKET, conn, connect, connectFailureMessage(), CONNECTION_AUTH_OK, CONNECTION_AWAITING_RESPONSE, CONNECTION_BAD, CONNECTION_CHECK_STANDBY, CONNECTION_CHECK_TARGET, CONNECTION_CHECK_WRITABLE, CONNECTION_CONSUME, CONNECTION_GSS_STARTUP, CONNECTION_MADE, CONNECTION_NEEDED, CONNECTION_OK, CONNECTION_SSL_STARTUP, CONNECTION_STARTED, connectNoDelay(), pg_conn::connhost, pg_conn::connip, PQExpBufferData::data, pg_conn::default_transaction_read_only, EINPROGRESS, EINTR, emitHostIdentityInfo(), EnvironmentOptions, err(), ERRCODE_APPNAME_UNKNOWN, ERRCODE_CANNOT_CONNECT_NOW, pg_conn::errorMessage, EWOULDBLOCK, AddrInfo::family, pg_conn::fbappname, free, getHostaddr(), getpeereid(), pg_conn::gssencmode, pg_conn_host::host, pg_conn_host::hostaddr, i, pg_conn::in_hot_standby, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, j, pg_conn::laddr, pg_conn::last_sqlstate, PQExpBufferData::len, libpq_append_conn_error(), LOAD_BALANCE_RANDOM, pg_conn::load_balance_type, MAX_ERRLEN, MAXPGPATH, MemSet, pg_conn::naddr, pg_conn::nconnhost, NEGOTIATE_GSS_CODE, NEGOTIATE_SSL_CODE, parse_int_param(), PG_BOOL_NO, PG_BOOL_UNKNOWN, PG_BOOL_YES, PG_DIAG_SQLSTATE, pg_fe_getusername(), pg_fe_sendauth(), pg_freeaddrinfo_all(), pg_getaddrinfo_all(), pg_GSS_have_cred_cache(), pg_hton32, pg_prng_uint64_range(), PG_PROTOCOL, pg_set_noblock(), PG_STRERROR_R_BUFLEN, PGASYNC_BUSY, PGASYNC_IDLE, PGINVALID_SOCKET, pgpassfileWarning(), PGRES_FATAL_ERROR, PGRES_POLLING_FAILED, PGRES_POLLING_OK, PGRES_POLLING_READING, PGRES_POLLING_WRITING, PGRES_TUPLES_OK, pg_conn::pipelineStatus, pg_conn_host::port, PQ_PIPELINE_OFF, pqBuildStartupPacket3(), pqCheckInBufferSpace(), PQclear(), pqClearAsyncResult(), pqClearConnErrorState, PQconsumeInput(), pqDropConnection(), pqDropServerData(), pqFlush(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGetNegotiateProtocolVersion3(), PQgetResult(), pqGets_append(), PQgetvalue(), PQisBusy(), PqMsg_AuthenticationRequest, PqMsg_ErrorResponse, PqMsg_NegotiateProtocolVersion, PQntuples(), pqPacketSend(), pqReadData(), PQresultErrorField(), PQresultStatus(), pqsecure_initialize(), pqsecure_open_client(), pqsecure_open_gss(), PQsendQueryContinue(), PQTRANS_IDLE, pg_conn::prng_state, pg_conn::pversion, pg_conn::raddr, release_conn_addrinfo(), pg_conn::requirepeer, res, pg_result::resultStatus, SockAddr::salen, pg_conn::send_appname, sendTerminateConn(), SERVER_TYPE_PREFER_STANDBY, SERVER_TYPE_PREFER_STANDBY_PASS2, SERVER_TYPE_PRIMARY, SERVER_TYPE_READ_ONLY, SERVER_TYPE_READ_WRITE, SERVER_TYPE_STANDBY, setKeepalivesCount(), setKeepalivesIdle(), setKeepalivesInterval(), setTCPUserTimeout(), pg_conn::sigpipe_flag, pg_conn::sigpipe_so, snprintf, pg_conn::sock, SOCK_ERRNO, SOCK_STRERROR, socket, pg_conn::ssl_in_use, pg_conn::sslmode, pg_conn::status, STATUS_OK, store_conn_addrinfo(), strerror_r, pg_conn::sversion, pg_conn::target_server_type, pg_conn::try_next_addr, pg_conn::try_next_host, pg_conn_host::type, UNIXSOCK_PATH, UNIXSOCK_PATH_BUFLEN, useKeepalives(), val, pg_conn::whichaddr, pg_conn::whichhost, and pg_conn::xactStatus.

Referenced by connectDBComplete(), connectDBStart(), libpqsrv_connect_internal(), and PQresetPoll().

◆ PQconnectStart()

PGconn* PQconnectStart ( const char *  conninfo)

Definition at line 859 of file fe-connect.c.

860 {
861  PGconn *conn;
862 
863  /*
864  * Allocate memory for the conn structure. Note that we also expect this
865  * to initialize conn->errorMessage to empty. All subsequent steps during
866  * connection initialization will only append to that buffer.
867  */
868  conn = makeEmptyPGconn();
869  if (conn == NULL)
870  return NULL;
871 
872  /*
873  * Parse the conninfo string
874  */
875  if (!connectOptions1(conn, conninfo))
876  return conn;
877 
878  /*
879  * Compute derived options
880  */
881  if (!connectOptions2(conn))
882  return conn;
883 
884  /*
885  * Connect to the database
886  */
887  if (!connectDBStart(conn))
888  {
889  /* Just in case we failed to set it in connectDBStart */
891  }
892 
893  return conn;
894 }
static bool connectOptions1(PGconn *conn, const char *conninfo)
Definition: fe-connect.c:945
static bool connectOptions2(PGconn *conn)
Definition: fe-connect.c:1068
static PGconn * makeEmptyPGconn(void)
Definition: fe-connect.c:4288
static int connectDBStart(PGconn *conn)
Definition: fe-connect.c:2335

References conn, connectDBStart(), CONNECTION_BAD, connectOptions1(), connectOptions2(), makeEmptyPGconn(), and pg_conn::status.

Referenced by libpqsrv_connect(), PQconnectdb(), and PQping().

◆ PQconnectStartParams()

PGconn* PQconnectStartParams ( const char *const *  keywords,
const char *const *  values,
int  expand_dbname 
)

Definition at line 778 of file fe-connect.c.

781 {
782  PGconn *conn;
783  PQconninfoOption *connOptions;
784 
785  /*
786  * Allocate memory for the conn structure. Note that we also expect this
787  * to initialize conn->errorMessage to empty. All subsequent steps during
788  * connection initialization will only append to that buffer.
789  */
790  conn = makeEmptyPGconn();
791  if (conn == NULL)
792  return NULL;
793 
794  /*
795  * Parse the conninfo arrays
796  */
797  connOptions = conninfo_array_parse(keywords, values,
798  &conn->errorMessage,
799  true, expand_dbname);
800  if (connOptions == NULL)
801  {
803  /* errorMessage is already set */
804  return conn;
805  }
806 
807  /*
808  * Move option values into conn structure
809  */
810  if (!fillPGconn(conn, connOptions))
811  {
812  PQconninfoFree(connOptions);
813  return conn;
814  }
815 
816  /*
817  * Free the option info - all is in conn now
818  */
819  PQconninfoFree(connOptions);
820 
821  /*
822  * Compute derived options
823  */
824  if (!connectOptions2(conn))
825  return conn;
826 
827  /*
828  * Connect to the database
829  */
830  if (!connectDBStart(conn))
831  {
832  /* Just in case we failed to set it in connectDBStart */
834  }
835 
836  return conn;
837 }
static PQconninfoOption * conninfo_array_parse(const char *const *keywords, const char *const *values, PQExpBuffer errorMessage, bool use_defaults, int expand_dbname)
Definition: fe-connect.c:6120
static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
Definition: fe-connect.c:905

References conn, connectDBStart(), CONNECTION_BAD, connectOptions2(), conninfo_array_parse(), pg_conn::errorMessage, fillPGconn(), makeEmptyPGconn(), PQconninfoFree(), pg_conn::status, and values.

Referenced by libpqsrv_connect_params(), PQconnectdbParams(), and PQpingParams().

◆ PQconninfo()

PQconninfoOption* PQconninfo ( PGconn conn)

Definition at line 7037 of file fe-connect.c.

7038 {
7039  PQExpBufferData errorBuf;
7040  PQconninfoOption *connOptions;
7041 
7042  if (conn == NULL)
7043  return NULL;
7044 
7045  /*
7046  * We don't actually report any errors here, but callees want a buffer,
7047  * and we prefer not to trash the conn's errorMessage.
7048  */
7049  initPQExpBuffer(&errorBuf);
7050  if (PQExpBufferDataBroken(errorBuf))
7051  return NULL; /* out of memory already :-( */
7052 
7053  connOptions = conninfo_init(&errorBuf);
7054 
7055  if (connOptions != NULL)
7056  {
7058 
7059  for (option = PQconninfoOptions; option->keyword; option++)
7060  {
7061  char **connmember;
7062 
7063  if (option->connofs < 0)
7064  continue;
7065 
7066  connmember = (char **) ((char *) conn + option->connofs);
7067 
7068  if (*connmember)
7069  conninfo_storeval(connOptions, option->keyword, *connmember,
7070  &errorBuf, true, false);
7071  }
7072  }
7073 
7074  termPQExpBuffer(&errorBuf);
7075 
7076  return connOptions;
7077 }
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
Definition: fe-connect.c:6955
static const internalPQconninfoOption PQconninfoOptions[]
Definition: fe-connect.c:189

References conn, conninfo_init(), conninfo_storeval(), initPQExpBuffer(), PQconninfoOptions, PQExpBufferDataBroken, and termPQExpBuffer().

Referenced by do_connect(), GenerateRecoveryConfig(), and libpqrcv_get_conninfo().

◆ PQconninfoFree()

void PQconninfoFree ( PQconninfoOption connOptions)

Definition at line 7081 of file fe-connect.c.

7082 {
7083  if (connOptions == NULL)
7084  return;
7085 
7086  for (PQconninfoOption *option = connOptions; option->keyword != NULL; option++)
7087  free(option->val);
7088  free(connOptions);
7089 }
int val
Definition: getopt_long.h:21

References free, and option::val.

Referenced by check_pghost_envvar(), connectDatabase(), connectOptions1(), conninfo_array_parse(), conninfo_parse(), conninfo_uri_parse(), dblink_connstr_has_pw(), do_connect(), GenerateRecoveryConfig(), GetConnection(), libpqrcv_check_conninfo(), libpqrcv_get_conninfo(), PQconndefaults(), and PQconnectStartParams().

◆ PQconninfoParse()

PQconninfoOption* PQconninfoParse ( const char *  conninfo,
char **  errmsg 
)

Definition at line 5829 of file fe-connect.c.

5830 {
5831  PQExpBufferData errorBuf;
5832  PQconninfoOption *connOptions;
5833 
5834  if (errmsg)
5835  *errmsg = NULL; /* default */
5836  initPQExpBuffer(&errorBuf);
5837  if (PQExpBufferDataBroken(errorBuf))
5838  return NULL; /* out of memory already :-( */
5839  connOptions = parse_connection_string(conninfo, &errorBuf, false);
5840  if (connOptions == NULL && errmsg)
5841  *errmsg = errorBuf.data;
5842  else
5843  termPQExpBuffer(&errorBuf);
5844  return connOptions;
5845 }
int errmsg(const char *fmt,...)
Definition: elog.c:1069
static PQconninfoOption * parse_connection_string(const char *connstr, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:5890

References PQExpBufferData::data, errmsg(), initPQExpBuffer(), parse_connection_string(), PQExpBufferDataBroken, and termPQExpBuffer().

Referenced by connectDatabase(), dblink_connstr_has_pw(), do_connect(), GetConnection(), libpqrcv_check_conninfo(), and main().

◆ PQconsumeInput()

int PQconsumeInput ( PGconn conn)

Definition at line 1957 of file fe-exec.c.

1958 {
1959  if (!conn)
1960  return 0;
1961 
1962  /*
1963  * for non-blocking connections try to flush the send-queue, otherwise we
1964  * may never get a response for something that may not have already been
1965  * sent because it's in our write buffer!
1966  */
1967  if (pqIsnonblocking(conn))
1968  {
1969  if (pqFlush(conn) < 0)
1970  return 0;
1971  }
1972 
1973  /*
1974  * Load more data, if available. We do this no matter what state we are
1975  * in, since we are probably getting called because the application wants
1976  * to get rid of a read-select condition. Note that we will NOT block
1977  * waiting for more input.
1978  */
1979  if (pqReadData(conn) < 0)
1980  return 0;
1981 
1982  /* Parsing of the data waits till later. */
1983  return 1;
1984 }
#define pqIsnonblocking(conn)
Definition: libpq-int.h:889

References conn, pqFlush(), pqIsnonblocking, and pqReadData().

Referenced by advanceConnectionState(), CopyStreamReceive(), dblink_get_notify(), dblink_is_busy(), do_sql_command_end(), ecpg_process_output(), libpqrcv_PQgetResult(), libpqrcv_receive(), main(), pgfdw_cancel_query_end(), pgfdw_exec_cleanup_query_end(), pgfdw_get_cleanup_result(), pgfdw_get_result(), postgresForeignAsyncNotify(), PQconnectPoll(), PrintNotifications(), StreamLogicalLog(), test_nosync(), test_pipelined_insert(), test_uniqviol(), try_complete_step(), and wait_on_slots().

◆ PQcopyResult()

PGresult* PQcopyResult ( const PGresult src,
int  flags 
)

Definition at line 315 of file fe-exec.c.

316 {
317  PGresult *dest;
318  int i;
319 
320  if (!src)
321  return NULL;
322 
324  if (!dest)
325  return NULL;
326 
327  /* Always copy these over. Is cmdStatus really useful here? */
328  dest->client_encoding = src->client_encoding;
329  strcpy(dest->cmdStatus, src->cmdStatus);
330 
331  /* Wants attrs? */
332  if (flags & (PG_COPYRES_ATTRS | PG_COPYRES_TUPLES))
333  {
334  if (!PQsetResultAttrs(dest, src->numAttributes, src->attDescs))
335  {
336  PQclear(dest);
337  return NULL;
338  }
339  }
340 
341  /* Wants to copy tuples? */
342  if (flags & PG_COPYRES_TUPLES)
343  {
344  int tup,
345  field;
346 
347  for (tup = 0; tup < src->ntups; tup++)
348  {
349  for (field = 0; field < src->numAttributes; field++)
350  {
351  if (!PQsetvalue(dest, tup, field,
352  src->tuples[tup][field].value,
353  src->tuples[tup][field].len))
354  {
355  PQclear(dest);
356  return NULL;
357  }
358  }
359  }
360  }
361 
362  /* Wants to copy notice hooks? */
363  if (flags & PG_COPYRES_NOTICEHOOKS)
364  dest->noticeHooks = src->noticeHooks;
365 
366  /* Wants to copy PGEvents? */
367  if ((flags & PG_COPYRES_EVENTS) && src->nEvents > 0)
368  {
369  dest->events = dupEvents(src->events, src->nEvents,
370  &dest->memorySize);
371  if (!dest->events)
372  {
373  PQclear(dest);
374  return NULL;
375  }
376  dest->nEvents = src->nEvents;
377  }
378 
379  /* Okay, trigger PGEVT_RESULTCOPY event */
380  for (i = 0; i < dest->nEvents; i++)
381  {
382  /* We don't fire events that had some previous failure */
383  if (src->events[i].resultInitialized)
384  {
385  PGEventResultCopy evt;
386 
387  evt.src = src;
388  evt.dest = dest;
389  if (dest->events[i].proc(PGEVT_RESULTCOPY, &evt,
390  dest->events[i].passThrough))
391  dest->events[i].resultInitialized = true;
392  }
393  }
394 
395  return dest;
396 }
int PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs)
Definition: fe-exec.c:246
void PQclear(PGresult *res)
Definition: fe-exec.c:718
static PGEvent * dupEvents(PGEvent *events, int count, size_t *memSize)
Definition: fe-exec.c:405
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:157
int PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len)
Definition: fe-exec.c:449
@ PGEVT_RESULTCOPY
Definition: libpq-events.h:33
#define PG_COPYRES_TUPLES
Definition: libpq-fe.h:46
#define PG_COPYRES_ATTRS
Definition: libpq-fe.h:45
#define PG_COPYRES_EVENTS
Definition: libpq-fe.h:47
#define PG_COPYRES_NOTICEHOOKS
Definition: libpq-fe.h:48
const PGresult * src
Definition: libpq-events.h:60
PGresult * dest
Definition: libpq-events.h:61
int ntups
Definition: libpq-int.h:172
int numAttributes
Definition: libpq-int.h:173
int client_encoding
Definition: libpq-int.h:192
char * value
Definition: libpq-int.h:141

References pg_result::attDescs, pg_result::client_encoding, pg_result::cmdStatus, generate_unaccent_rules::dest, PGEventResultCopy::dest, dupEvents(), pg_result::events, i, pgresAttValue::len, pg_result::nEvents, pg_result::noticeHooks, pg_result::ntups, pg_result::numAttributes, PG_COPYRES_ATTRS, PG_COPYRES_EVENTS, PG_COPYRES_NOTICEHOOKS, PG_COPYRES_TUPLES, PGEVT_RESULTCOPY, PGRES_TUPLES_OK, PQclear(), PQmakeEmptyPGresult(), PQsetResultAttrs(), PQsetvalue(), PGEvent::resultInitialized, PGEventResultCopy::src, pg_result::tuples, and pgresAttValue::value.

Referenced by pqRowProcessor().

◆ PQdb()

◆ PQdefaultSSLKeyPassHook_OpenSSL()

int PQdefaultSSLKeyPassHook_OpenSSL ( char *  buf,
int  size,
PGconn conn 
)

Definition at line 1966 of file fe-secure-openssl.c.

1967 {
1968  if (conn && conn->sslpassword)
1969  {
1970  if (strlen(conn->sslpassword) + 1 > size)
1971  fprintf(stderr, libpq_gettext("WARNING: sslpassword truncated\n"));
1972  strncpy(buf, conn->sslpassword, size);
1973  buf[size - 1] = '\0';
1974  return strlen(buf);
1975  }
1976  else
1977  {
1978  buf[0] = '\0';
1979  return 0;
1980  }
1981 }
#define libpq_gettext(x)
Definition: libpq-int.h:900
#define fprintf
Definition: port.h:242
char * sslpassword
Definition: libpq-int.h:394

References buf, conn, fprintf, libpq_gettext, and pg_conn::sslpassword.

Referenced by PQssl_passwd_cb().

◆ PQdescribePortal()

PGresult* PQdescribePortal ( PGconn conn,
const char *  portal 
)

Definition at line 2440 of file fe-exec.c.

2441 {
2442  if (!PQexecStart(conn))
2443  return NULL;
2444  if (!PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal))
2445  return NULL;
2446  return PQexecFinish(conn);
2447 }
#define PqMsg_Describe
Definition: protocol.h:21

References conn, PQexecFinish(), PQexecStart(), PqMsg_Describe, and PQsendTypedCommand().

Referenced by test_prepared().

◆ PQdescribePrepared()

PGresult* PQdescribePrepared ( PGconn conn,
const char *  stmt 
)

Definition at line 2421 of file fe-exec.c.

2422 {
2423  if (!PQexecStart(conn))
2424  return NULL;
2426  return NULL;
2427  return PQexecFinish(conn);
2428 }

References conn, PQexecFinish(), PQexecStart(), PqMsg_Describe, PQsendTypedCommand(), and stmt.

Referenced by DescribeQuery(), ECPGdescribe(), and test_prepared().

◆ PQdisplayTuples()

void PQdisplayTuples ( const PGresult res,
FILE *  fp,
int  fillAlign,
const char *  fieldSep,
int  printHeader,
int  quiet 
)

Definition at line 574 of file fe-print.c.

581 {
582 #define DEFAULT_FIELD_SEP " "
583 
584  int i,
585  j;
586  int nFields;
587  int nTuples;
588  int *fLength = NULL;
589 
590  if (fieldSep == NULL)
591  fieldSep = DEFAULT_FIELD_SEP;
592 
593  /* Get some useful info about the results */
594  nFields = PQnfields(res);
595  nTuples = PQntuples(res);
596 
597  if (fp == NULL)
598  fp = stdout;
599 
600  /* Figure the field lengths to align to */
601  /* will be somewhat time consuming for very large results */
602  if (fillAlign)
603  {
604  fLength = (int *) malloc(nFields * sizeof(int));
605  if (!fLength)
606  {
607  fprintf(stderr, libpq_gettext("out of memory\n"));
608  return;
609  }
610 
611  for (j = 0; j < nFields; j++)
612  {
613  fLength[j] = strlen(PQfname(res, j));
614  for (i = 0; i < nTuples; i++)
615  {
616  int flen = PQgetlength(res, i, j);
617 
618  if (flen > fLength[j])
619  fLength[j] = flen;
620  }
621  }
622  }
623 
624  if (printHeader)
625  {
626  /* first, print out the attribute names */
627  for (i = 0; i < nFields; i++)
628  {
629  fputs(PQfname(res, i), fp);
630  if (fillAlign)
631  fill(strlen(PQfname(res, i)), fLength[i], ' ', fp);
632  fputs(fieldSep, fp);
633  }
634  fprintf(fp, "\n");
635 
636  /* Underline the attribute names */
637  for (i = 0; i < nFields; i++)
638  {
639  if (fillAlign)
640  fill(0, fLength[i], '-', fp);
641  fputs(fieldSep, fp);
642  }
643  fprintf(fp, "\n");
644  }
645 
646  /* next, print out the instances */
647  for (i = 0; i < nTuples; i++)
648  {
649  for (j = 0; j < nFields; j++)
650  {
651  fprintf(fp, "%s", PQgetvalue(res, i, j));
652  if (fillAlign)
653  fill(strlen(PQgetvalue(res, i, j)), fLength[j], ' ', fp);
654  fputs(fieldSep, fp);
655  }
656  fprintf(fp, "\n");
657  }
658 
659  if (!quiet)
660  fprintf(fp, "\nQuery returned %d row%s.\n", PQntuples(res),
661  (PQntuples(res) == 1) ? "" : "s");
662 
663  fflush(fp);
664 
665  free(fLength);
666 }
int PQgetlength(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3801
char * PQfname(const PGresult *res, int field_num)
Definition: fe-exec.c:3481
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3403
static void fill(int length, int max, char filler, FILE *fp)
Definition: fe-print.c:755
#define DEFAULT_FIELD_SEP
#define malloc(a)
Definition: header.h:50
static void const char fflush(stdout)

References DEFAULT_FIELD_SEP, fflush(), fill(), fprintf, free, i, j, libpq_gettext, malloc, PQfname(), PQgetlength(), PQgetvalue(), PQnfields(), PQntuples(), res, and generate_unaccent_rules::stdout.

◆ PQdsplen()

int PQdsplen ( const char *  s,
int  encoding 
)

Definition at line 1197 of file fe-misc.c.

1198 {
1199  return pg_encoding_dsplen(encoding, s);
1200 }
int pg_encoding_dsplen(int encoding, const char *mbstr)
Definition: wchar.c:2151

References encoding, and pg_encoding_dsplen().

Referenced by get_prompt(), pg_wcsformat(), pg_wcssize(), pg_wcswidth(), and strlen_max_width().

◆ PQencryptPassword()

char* PQencryptPassword ( const char *  passwd,
const char *  user 
)

Definition at line 1234 of file fe-auth.c.

1235 {
1236  char *crypt_pwd;
1237  const char *errstr = NULL;
1238 
1239  crypt_pwd = malloc(MD5_PASSWD_LEN + 1);
1240  if (!crypt_pwd)
1241  return NULL;
1242 
1243  if (!pg_md5_encrypt(passwd, user, strlen(user), crypt_pwd, &errstr))
1244  {
1245  free(crypt_pwd);
1246  return NULL;
1247  }
1248 
1249  return crypt_pwd;
1250 }
#define MD5_PASSWD_LEN
Definition: md5.h:26
bool pg_md5_encrypt(const char *passwd, const char *salt, size_t salt_len, char *buf, const char **errstr)
Definition: md5_common.c:144
static char * user
Definition: pg_regress.c:112

References free, malloc, MD5_PASSWD_LEN, pg_md5_encrypt(), and user.

◆ PQencryptPasswordConn()

char* PQencryptPasswordConn ( PGconn conn,
const char *  passwd,
const char *  user,
const char *  algorithm 
)

Definition at line 1277 of file fe-auth.c.

1279 {
1280 #define MAX_ALGORITHM_NAME_LEN 50
1281  char algobuf[MAX_ALGORITHM_NAME_LEN + 1];
1282  char *crypt_pwd = NULL;
1283 
1284  if (!conn)
1285  return NULL;
1286 
1288 
1289  /* If no algorithm was given, ask the server. */
1290  if (algorithm == NULL)
1291  {
1292  PGresult *res;
1293  char *val;
1294 
1295  res = PQexec(conn, "show password_encryption");
1296  if (res == NULL)
1297  {
1298  /* PQexec() should've set conn->errorMessage already */
1299  return NULL;
1300  }
1302  {
1303  /* PQexec() should've set conn->errorMessage already */
1304  PQclear(res);
1305  return NULL;
1306  }
1307  if (PQntuples(res) != 1 || PQnfields(res) != 1)
1308  {
1309  PQclear(res);
1310  libpq_append_conn_error(conn, "unexpected shape of result set returned for SHOW");
1311  return NULL;
1312  }
1313  val = PQgetvalue(res, 0, 0);
1314 
1315  if (strlen(val) > MAX_ALGORITHM_NAME_LEN)
1316  {
1317  PQclear(res);
1318  libpq_append_conn_error(conn, "password_encryption value too long");
1319  return NULL;
1320  }
1321  strcpy(algobuf, val);
1322  PQclear(res);
1323 
1324  algorithm = algobuf;
1325  }
1326 
1327  /*
1328  * Also accept "on" and "off" as aliases for "md5", because