PostgreSQL Source Code  git master
libpq-fe.h File Reference
#include <stdio.h>
#include <time.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_cancel_conn PGcancelConn
 
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 , CONNECTION_ALLOCATED
}
 
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 ,
  PGRES_TUPLES_CHUNK
}
 
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)
 
PGcancelConnPQcancelCreate (PGconn *conn)
 
int PQcancelStart (PGcancelConn *cancelConn)
 
int PQcancelBlocking (PGcancelConn *cancelConn)
 
PostgresPollingStatusType PQcancelPoll (PGcancelConn *cancelConn)
 
ConnStatusType PQcancelStatus (const PGcancelConn *cancelConn)
 
int PQcancelSocket (const PGcancelConn *cancelConn)
 
char * PQcancelErrorMessage (const PGcancelConn *cancelConn)
 
void PQcancelReset (PGcancelConn *cancelConn)
 
void PQcancelFinish (PGcancelConn *cancelConn)
 
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)
 
int PQsetChunkedRowsMode (PGconn *conn, int chunkSize)
 
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)
 
int PQsendPipelineSync (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 PQsocketPoll (int sock, int forRead, int forWrite, time_t end_time)
 
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)
 
PGresultPQchangePassword (PGconn *conn, const char *user, const char *passwd)
 
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 37 of file libpq-fe.h.

◆ LIBPQ_HAS_SSL_LIBRARY_DETECTION

#define LIBPQ_HAS_SSL_LIBRARY_DETECTION   1

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

◆ LIBPQ_HAS_TRACE_FLAGS

#define LIBPQ_HAS_TRACE_FLAGS   1

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

◆ PG_COPYRES_ATTRS

#define PG_COPYRES_ATTRS   0x01

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

◆ PG_COPYRES_EVENTS

#define PG_COPYRES_EVENTS   0x04

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

◆ PG_COPYRES_NOTICEHOOKS

#define PG_COPYRES_NOTICEHOOKS   0x08

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

◆ PG_COPYRES_TUPLES

#define PG_COPYRES_TUPLES   0x02 /* Implies PG_COPYRES_ATTRS */

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

◆ PQ_QUERY_PARAM_MAX_LIMIT

#define PQ_QUERY_PARAM_MAX_LIMIT   65535

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

◆ PQfreeNotify

#define PQfreeNotify (   ptr)    PQfreemem(ptr)

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

◆ PQnoPasswordSupplied

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

Definition at line 597 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 304 of file libpq-fe.h.

◆ PQTRACE_REGRESS_MODE

#define PQTRACE_REGRESS_MODE   (1<<1)

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

◆ PQTRACE_SUPPRESS_TIMESTAMPS

#define PQTRACE_SUPPRESS_TIMESTAMPS   (1<<0)

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

Typedef Documentation

◆ PGcancel

typedef struct pg_cancel PGcancel

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

◆ PGcancelConn

typedef struct pg_cancel_conn PGcancelConn

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 432 of file libpq-fe.h.

◆ pqbool

typedef char pqbool

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

◆ PQconninfoOption

◆ PQnoticeProcessor

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

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

◆ PQnoticeReceiver

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

Definition at line 206 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 705 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 
CONNECTION_ALLOCATED 

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

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

◆ 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 
PGRES_TUPLES_CHUNK 

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

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

◆ PGContextVisibility

Enumerator
PQSHOW_CONTEXT_NEVER 
PQSHOW_CONTEXT_ERRORS 
PQSHOW_CONTEXT_ALWAYS 

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

138 {
139  PQSHOW_CONTEXT_NEVER, /* never show CONTEXT field */
140  PQSHOW_CONTEXT_ERRORS, /* show CONTEXT for errors only (default) */
141  PQSHOW_CONTEXT_ALWAYS /* always show CONTEXT field */
PGContextVisibility
Definition: libpq-fe.h:138
@ PQSHOW_CONTEXT_NEVER
Definition: libpq-fe.h:139
@ PQSHOW_CONTEXT_ALWAYS
Definition: libpq-fe.h:141
@ PQSHOW_CONTEXT_ERRORS
Definition: libpq-fe.h:140

◆ PGPing

enum PGPing
Enumerator
PQPING_OK 
PQPING_REJECT 
PQPING_NO_RESPONSE 
PQPING_NO_ATTEMPT 

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

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

◆ PGpipelineStatus

Enumerator
PQ_PIPELINE_OFF 
PQ_PIPELINE_ON 
PQ_PIPELINE_ABORTED 

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

161 {
PGpipelineStatus
Definition: libpq-fe.h:161
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:162
@ PQ_PIPELINE_ABORTED
Definition: libpq-fe.h:164
@ PQ_PIPELINE_ON
Definition: libpq-fe.h:163

◆ PGTransactionStatusType

Enumerator
PQTRANS_IDLE 
PQTRANS_ACTIVE 
PQTRANS_INTRANS 
PQTRANS_INERROR 
PQTRANS_UNKNOWN 

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

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

◆ PGVerbosity

Enumerator
PQERRORS_TERSE 
PQERRORS_DEFAULT 
PQERRORS_VERBOSE 
PQERRORS_SQLSTATE 

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

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

◆ PostgresPollingStatusType

Enumerator
PGRES_POLLING_FAILED 
PGRES_POLLING_READING 
PGRES_POLLING_WRITING 
PGRES_POLLING_OK 
PGRES_POLLING_ACTIVE 

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

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

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:2980
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3411
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:55
int isint
Definition: libpq-fe.h:258
int integer
Definition: libpq-fe.h:262
union PQArgBlock::@178 u
Oid fn_lo_close
Definition: libpq-int.h:287
PGlobjfuncs * lobjfuncs
Definition: libpq-int.h:517

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

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:1324
Oid fn_lo_create
Definition: libpq-int.h:289

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:1273
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:884
static char * filename
Definition: pg_dumpall.c:119
static char * buf
Definition: pg_test_fsync.c:73
#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:291

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:261
Oid fn_lo_lseek64
Definition: libpq-int.h:292

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

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

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

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

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

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

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

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:1245
Oid fn_lo_write
Definition: libpq-int.h:298

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 549 of file encnames.c.

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

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

Referenced by pg_valid_client_encoding(), and pg_valid_server_encoding().

◆ pg_encoding_to_char()

const char* pg_encoding_to_char ( int  encoding)

Definition at line 587 of file encnames.c.

588 {
590  {
591  const pg_enc2name *p = &pg_enc2name_tbl[encoding];
592 
593  Assert(encoding == p->encoding);
594  return p->name;
595  }
596  return "";
597 }
#define Assert(condition)
Definition: c.h:858
const pg_enc2name pg_enc2name_tbl[]
Definition: encnames.c:308
int32 encoding
Definition: pg_database.h:41
#define PG_VALID_ENCODING(_enc)
Definition: pg_wchar.h:287
pg_enc encoding
Definition: pg_wchar.h:342
const char * name
Definition: pg_wchar.h:341

References Assert, encoding, pg_enc2name::encoding, pg_enc2name::name, pg_enc2name_tbl, and PG_VALID_ENCODING.

◆ pg_valid_server_encoding_id()

int pg_valid_server_encoding_id ( int  encoding)

Definition at line 513 of file encnames.c.

514 {
516 }
#define PG_VALID_BE_ENCODING(_enc)
Definition: pg_wchar.h:281

References encoding, and PG_VALID_BE_ENCODING.

◆ PQbackendPID()

int PQbackendPID ( const PGconn conn)

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

7202 {
7203  if (!conn || conn->status != CONNECTION_OK)
7204  return 0;
7205  return conn->be_pid;
7206 }
int be_pid
Definition: libpq-int.h:508
ConnStatusType status
Definition: libpq-int.h:436

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

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

◆ PQbinaryTuples()

int PQbinaryTuples ( const PGresult res)

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

3498 {
3499  if (!res)
3500  return 0;
3501  return res->binary;
3502 }
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 462 of file fe-cancel.c.

463 {
464  int save_errno = SOCK_ERRNO;
465  pgsocket tmpsock = PGINVALID_SOCKET;
466  int maxlen;
467  struct
468  {
469  uint32 packetlen;
471  } crp;
472 
473  if (!cancel)
474  {
475  strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
476  /* strlcpy probably doesn't change errno, but be paranoid */
477  SOCK_ERRNO_SET(save_errno);
478  return false;
479  }
480 
481  /*
482  * We need to open a temporary connection to the postmaster. Do this with
483  * only kernel calls.
484  */
485  if ((tmpsock = socket(cancel->raddr.addr.ss_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
486  {
487  strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
488  goto cancel_errReturn;
489  }
490 
491  /*
492  * Since this connection will only be used to send a single packet of
493  * data, we don't need NODELAY. We also don't set the socket to
494  * nonblocking mode, because the API definition of PQcancel requires the
495  * cancel to be sent in a blocking way.
496  *
497  * We do set socket options related to keepalives and other TCP timeouts.
498  * This ensures that this function does not block indefinitely when
499  * reasonable keepalive and timeout settings have been provided.
500  */
501  if (cancel->raddr.addr.ss_family != AF_UNIX &&
502  cancel->keepalives != 0)
503  {
504 #ifndef WIN32
505  if (!optional_setsockopt(tmpsock, SOL_SOCKET, SO_KEEPALIVE, 1))
506  {
507  strlcpy(errbuf, "PQcancel() -- setsockopt(SO_KEEPALIVE) failed: ", errbufsize);
508  goto cancel_errReturn;
509  }
510 
511 #ifdef PG_TCP_KEEPALIVE_IDLE
512  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
513  cancel->keepalives_idle))
514  {
515  strlcpy(errbuf, "PQcancel() -- setsockopt(" PG_TCP_KEEPALIVE_IDLE_STR ") failed: ", errbufsize);
516  goto cancel_errReturn;
517  }
518 #endif
519 
520 #ifdef TCP_KEEPINTVL
521  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_KEEPINTVL,
522  cancel->keepalives_interval))
523  {
524  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_KEEPINTVL) failed: ", errbufsize);
525  goto cancel_errReturn;
526  }
527 #endif
528 
529 #ifdef TCP_KEEPCNT
530  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_KEEPCNT,
531  cancel->keepalives_count))
532  {
533  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_KEEPCNT) failed: ", errbufsize);
534  goto cancel_errReturn;
535  }
536 #endif
537 
538 #else /* WIN32 */
539 
540 #ifdef SIO_KEEPALIVE_VALS
541  if (!pqSetKeepalivesWin32(tmpsock,
542  cancel->keepalives_idle,
543  cancel->keepalives_interval))
544  {
545  strlcpy(errbuf, "PQcancel() -- WSAIoctl(SIO_KEEPALIVE_VALS) failed: ", errbufsize);
546  goto cancel_errReturn;
547  }
548 #endif /* SIO_KEEPALIVE_VALS */
549 #endif /* WIN32 */
550 
551  /* TCP_USER_TIMEOUT works the same way on Unix and Windows */
552 #ifdef TCP_USER_TIMEOUT
553  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_USER_TIMEOUT,
554  cancel->pgtcp_user_timeout))
555  {
556  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_USER_TIMEOUT) failed: ", errbufsize);
557  goto cancel_errReturn;
558  }
559 #endif
560  }
561 
562 retry3:
563  if (connect(tmpsock, (struct sockaddr *) &cancel->raddr.addr,
564  cancel->raddr.salen) < 0)
565  {
566  if (SOCK_ERRNO == EINTR)
567  /* Interrupted system call - we'll just try again */
568  goto retry3;
569  strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
570  goto cancel_errReturn;
571  }
572 
573  /* Create and send the cancel request packet. */
574 
575  crp.packetlen = pg_hton32((uint32) sizeof(crp));
576  crp.cp.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE);
577  crp.cp.backendPID = pg_hton32(cancel->be_pid);
578  crp.cp.cancelAuthCode = pg_hton32(cancel->be_key);
579 
580 retry4:
581  if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
582  {
583  if (SOCK_ERRNO == EINTR)
584  /* Interrupted system call - we'll just try again */
585  goto retry4;
586  strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
587  goto cancel_errReturn;
588  }
589 
590  /*
591  * Wait for the postmaster to close the connection, which indicates that
592  * it's processed the request. Without this delay, we might issue another
593  * command only to find that our cancel zaps that command instead of the
594  * one we thought we were canceling. Note we don't actually expect this
595  * read to obtain any data, we are just waiting for EOF to be signaled.
596  */
597 retry5:
598  if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
599  {
600  if (SOCK_ERRNO == EINTR)
601  /* Interrupted system call - we'll just try again */
602  goto retry5;
603  /* we ignore other error conditions */
604  }
605 
606  /* All done */
607  closesocket(tmpsock);
608  SOCK_ERRNO_SET(save_errno);
609  return true;
610 
611 cancel_errReturn:
612 
613  /*
614  * Make sure we don't overflow the error buffer. Leave space for the \n at
615  * the end, and for the terminating zero.
616  */
617  maxlen = errbufsize - strlen(errbuf) - 2;
618  if (maxlen >= 0)
619  {
620  /*
621  * We can't invoke strerror here, since it's not signal-safe. Settle
622  * for printing the decimal value of errno. Even that has to be done
623  * the hard way.
624  */
625  int val = SOCK_ERRNO;
626  char buf[32];
627  char *bufp;
628 
629  bufp = buf + sizeof(buf) - 1;
630  *bufp = '\0';
631  do
632  {
633  *(--bufp) = (val % 10) + '0';
634  val /= 10;
635  } while (val > 0);
636  bufp -= 6;
637  memcpy(bufp, "error ", 6);
638  strncat(errbuf, bufp, maxlen);
639  strcat(errbuf, "\n");
640  }
641  if (tmpsock != PGINVALID_SOCKET)
642  closesocket(tmpsock);
643  SOCK_ERRNO_SET(save_errno);
644  return false;
645 }
unsigned int uint32
Definition: c.h:506
static bool optional_setsockopt(int fd, int protoid, int optid, int value)
Definition: fe-cancel.c:430
long val
Definition: informix.c:670
#define SOCK_ERRNO
Definition: libpq-int.h:932
#define SOCK_ERRNO_SET(e)
Definition: libpq-int.h:934
#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: fe-cancel.c:45
int keepalives_interval
Definition: fe-cancel.c:48
int keepalives_idle
Definition: fe-cancel.c:47
int keepalives_count
Definition: fe-cancel.c:50
SockAddr raddr
Definition: fe-cancel.c:42
int be_pid
Definition: fe-cancel.c:43
int keepalives
Definition: fe-cancel.c:46
int be_key
Definition: fe-cancel.c:44
#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 DisconnectDatabase(), handle_sigint(), PQrequestCancel(), ShutdownWorkersHard(), sigTermHandler(), and test_cancel().

◆ PQcancelBlocking()

int PQcancelBlocking ( PGcancelConn cancelConn)

Definition at line 171 of file fe-cancel.c.

172 {
174  return 0;
175  return pqConnectDBComplete(&cancelConn->conn);
176 }
static PGcancel *volatile cancelConn
Definition: cancel.c:43
int PQcancelStart(PGcancelConn *cancelConn)
Definition: fe-cancel.c:185
int pqConnectDBComplete(PGconn *conn)
Definition: fe-connect.c:2470

References cancelConn, PQcancelStart(), and pqConnectDBComplete().

Referenced by disconnectDatabase(), test_cancel(), and try_complete_step().

◆ PQcancelCreate()

PGcancelConn* PQcancelCreate ( PGconn conn)

Definition at line 65 of file fe-cancel.c.

66 {
68  pg_conn_host originalHost;
69 
70  if (cancelConn == NULL)
71  return NULL;
72 
73  /* Check we have an open connection */
74  if (!conn)
75  {
76  libpq_append_conn_error(cancelConn, "passed connection was NULL");
77  return (PGcancelConn *) cancelConn;
78  }
79 
80  if (conn->sock == PGINVALID_SOCKET)
81  {
82  libpq_append_conn_error(cancelConn, "passed connection is not open");
83  return (PGcancelConn *) cancelConn;
84  }
85 
86  /*
87  * Indicate that this connection is used to send a cancellation
88  */
89  cancelConn->cancelRequest = true;
90 
92  return (PGcancelConn *) cancelConn;
93 
94  /*
95  * Compute derived options
96  */
98  return (PGcancelConn *) cancelConn;
99 
100  /*
101  * Copy cancellation token data from the original connection
102  */
105 
106  /*
107  * Cancel requests should not iterate over all possible hosts. The request
108  * needs to be sent to the exact host and address that the original
109  * connection used. So we manually create the host and address arrays with
110  * a single element after freeing the host array that we generated from
111  * the connection options.
112  */
114  cancelConn->nconnhost = 1;
115  cancelConn->naddr = 1;
116 
117  cancelConn->connhost = calloc(cancelConn->nconnhost, sizeof(pg_conn_host));
118  if (!cancelConn->connhost)
119  goto oom_error;
120 
121  originalHost = conn->connhost[conn->whichhost];
122  if (originalHost.host)
123  {
124  cancelConn->connhost[0].host = strdup(originalHost.host);
125  if (!cancelConn->connhost[0].host)
126  goto oom_error;
127  }
128  if (originalHost.hostaddr)
129  {
130  cancelConn->connhost[0].hostaddr = strdup(originalHost.hostaddr);
131  if (!cancelConn->connhost[0].hostaddr)
132  goto oom_error;
133  }
134  if (originalHost.port)
135  {
136  cancelConn->connhost[0].port = strdup(originalHost.port);
137  if (!cancelConn->connhost[0].port)
138  goto oom_error;
139  }
140  if (originalHost.password)
141  {
142  cancelConn->connhost[0].password = strdup(originalHost.password);
143  if (!cancelConn->connhost[0].password)
144  goto oom_error;
145  }
146 
147  cancelConn->addr = calloc(cancelConn->naddr, sizeof(AddrInfo));
148  if (!cancelConn->connhost)
149  goto oom_error;
150 
151  cancelConn->addr[0].addr = conn->raddr;
152  cancelConn->addr[0].family = conn->raddr.addr.ss_family;
153 
155  return (PGcancelConn *) cancelConn;
156 
157 oom_error:
159  libpq_append_conn_error(cancelConn, "out of memory");
160  return (PGcancelConn *) cancelConn;
161 }
bool pqConnectOptions2(PGconn *conn)
Definition: fe-connect.c:1120
void pqReleaseConnHosts(PGconn *conn)
Definition: fe-connect.c:4726
PGconn * pqMakeEmptyPGconn(void)
Definition: fe-connect.c:4545
bool pqCopyPGconn(PGconn *srcConn, PGconn *dstConn)
Definition: fe-connect.c:956
#define calloc(a, b)
Definition: header.h:55
char * host
Definition: libpq-int.h:352
char * password
Definition: libpq-int.h:355
char * port
Definition: libpq-int.h:354
char * hostaddr
Definition: libpq-int.h:353
pgsocket sock
Definition: libpq-int.h:473
int be_key
Definition: libpq-int.h:509
SockAddr raddr
Definition: libpq-int.h:476
int whichhost
Definition: libpq-int.h:455
pg_conn_host * connhost
Definition: libpq-int.h:456

References SockAddr::addr, pg_cancel::be_key, pg_conn::be_key, pg_cancel::be_pid, pg_conn::be_pid, calloc, cancelConn, conn, CONNECTION_ALLOCATED, CONNECTION_BAD, pg_conn::connhost, pg_conn_host::host, pg_conn_host::hostaddr, libpq_append_conn_error(), pg_conn_host::password, PGINVALID_SOCKET, pg_conn_host::port, pqConnectOptions2(), pqCopyPGconn(), pqMakeEmptyPGconn(), pqReleaseConnHosts(), pg_conn::raddr, pg_conn::sock, pg_conn::status, and pg_conn::whichhost.

Referenced by disconnectDatabase(), libpqsrv_cancel(), test_cancel(), and try_complete_step().

◆ PQcancelErrorMessage()

char* PQcancelErrorMessage ( const PGcancelConn cancelConn)

Definition at line 305 of file fe-cancel.c.

306 {
307  return PQerrorMessage(&cancelConn->conn);
308 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7167

References cancelConn, and PQerrorMessage().

Referenced by libpqsrv_cancel(), test_cancel(), and try_complete_step().

◆ PQcancelFinish()

void PQcancelFinish ( PGcancelConn cancelConn)

Definition at line 333 of file fe-cancel.c.

334 {
335  PQfinish(&cancelConn->conn);
336 }
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4888

References cancelConn, and PQfinish().

Referenced by disconnectDatabase(), libpqsrv_cancel(), test_cancel(), and try_complete_step().

◆ PQcancelPoll()

PostgresPollingStatusType PQcancelPoll ( PGcancelConn cancelConn)

Definition at line 207 of file fe-cancel.c.

208 {
209  PGconn *conn = &cancelConn->conn;
210  int n;
211 
212  /*
213  * We leave most of the connection establishment to PQconnectPoll, since
214  * it's very similar to normal connection establishment. But once we get
215  * to the CONNECTION_AWAITING_RESPONSE we need to start doing our own
216  * thing.
217  */
219  {
220  return PQconnectPoll(conn);
221  }
222 
223  /*
224  * At this point we are waiting on the server to close the connection,
225  * which is its way of communicating that the cancel has been handled.
226  */
227 
228  n = pqReadData(conn);
229 
230  if (n == 0)
231  return PGRES_POLLING_READING;
232 
233 #ifndef WIN32
234 
235  /*
236  * If we receive an error report it, but only if errno is non-zero.
237  * Otherwise we assume it's an EOF, which is what we expect from the
238  * server.
239  *
240  * We skip this for Windows, because Windows is a bit special in its EOF
241  * behaviour for TCP. Sometimes it will error with an ECONNRESET when
242  * there is a clean connection closure. See these threads for details:
243  * https://www.postgresql.org/message-id/flat/90b34057-4176-7bb0-0dbb-9822a5f6425b%40greiz-reinsdorf.de
244  *
245  * https://www.postgresql.org/message-id/flat/CA%2BhUKG%2BOeoETZQ%3DQw5Ub5h3tmwQhBmDA%3DnuNO3KG%3DzWfUypFAw%40mail.gmail.com
246  *
247  * PQcancel ignores such errors and reports success for the cancellation
248  * anyway, so even if this is not always correct we do the same here.
249  */
250  if (n < 0 && errno != 0)
251  {
253  return PGRES_POLLING_FAILED;
254  }
255 #endif
256 
257  /*
258  * We don't expect any data, only connection closure. So if we strangely
259  * do receive some data we consider that an error.
260  */
261  if (n > 0)
262  {
263  libpq_append_conn_error(conn, "received unexpected response from server");
265  return PGRES_POLLING_FAILED;
266  }
267 
268  /*
269  * Getting here means that we received an EOF, which is what we were
270  * expecting -- the cancel request has completed.
271  */
272  cancelConn->conn.status = CONNECTION_OK;
274  return PGRES_POLLING_OK;
275 }
PostgresPollingStatusType PQconnectPoll(PGconn *conn)
Definition: fe-connect.c:2609
int pqReadData(PGconn *conn)
Definition: fe-misc.c:565
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:146
PQExpBufferData errorMessage
Definition: libpq-int.h:633

References cancelConn, conn, CONNECTION_AWAITING_RESPONSE, CONNECTION_BAD, CONNECTION_OK, pg_conn::errorMessage, libpq_append_conn_error(), PGRES_POLLING_FAILED, PGRES_POLLING_OK, PGRES_POLLING_READING, PQconnectPoll(), pqReadData(), resetPQExpBuffer(), and pg_conn::status.

Referenced by libpqsrv_cancel(), pqConnectDBComplete(), and test_cancel().

◆ PQcancelReset()

void PQcancelReset ( PGcancelConn cancelConn)

Definition at line 317 of file fe-cancel.c.

318 {
319  pqClosePGconn(&cancelConn->conn);
320  cancelConn->conn.status = CONNECTION_ALLOCATED;
321  cancelConn->conn.whichhost = 0;
322  cancelConn->conn.whichaddr = 0;
323  cancelConn->conn.try_next_host = false;
324  cancelConn->conn.try_next_addr = false;
325 }
void pqClosePGconn(PGconn *conn)
Definition: fe-connect.c:4842

References cancelConn, CONNECTION_ALLOCATED, and pqClosePGconn().

Referenced by test_cancel().

◆ PQcancelSocket()

int PQcancelSocket ( const PGcancelConn cancelConn)

Definition at line 294 of file fe-cancel.c.

295 {
296  return PQsocket(&cancelConn->conn);
297 }
int PQsocket(const PGconn *conn)
Definition: fe-connect.c:7193

References cancelConn, and PQsocket().

Referenced by libpqsrv_cancel(), and test_cancel().

◆ PQcancelStart()

int PQcancelStart ( PGcancelConn cancelConn)

Definition at line 185 of file fe-cancel.c.

186 {
187  if (!cancelConn || cancelConn->conn.status == CONNECTION_BAD)
188  return 0;
189 
190  if (cancelConn->conn.status != CONNECTION_ALLOCATED)
191  {
193  "cancel request is already being sent on this connection");
194  cancelConn->conn.status = CONNECTION_BAD;
195  return 0;
196  }
197 
198  return pqConnectDBStart(&cancelConn->conn);
199 }
int pqConnectDBStart(PGconn *conn)
Definition: fe-connect.c:2392

References cancelConn, CONNECTION_ALLOCATED, CONNECTION_BAD, libpq_append_conn_error(), and pqConnectDBStart().

Referenced by libpqsrv_cancel(), PQcancelBlocking(), and test_cancel().

◆ PQcancelStatus()

ConnStatusType PQcancelStatus ( const PGcancelConn cancelConn)

Definition at line 283 of file fe-cancel.c.

284 {
285  return PQstatus(&cancelConn->conn);
286 }
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:7114

References cancelConn, and PQstatus().

Referenced by test_cancel().

◆ PQchangePassword()

PGresult* PQchangePassword ( PGconn conn,
const char *  user,
const char *  passwd 
)

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

1401 {
1402  char *encrypted_password = PQencryptPasswordConn(conn, passwd,
1403  user, NULL);
1404 
1405  if (!encrypted_password)
1406  {
1407  /* PQencryptPasswordConn() already registered the error */
1408  return NULL;
1409  }
1410  else
1411  {
1412  char *fmtpw = PQescapeLiteral(conn, encrypted_password,
1413  strlen(encrypted_password));
1414 
1415  /* no longer needed, so clean up now */
1416  PQfreemem(encrypted_password);
1417 
1418  if (!fmtpw)
1419  {
1420  /* PQescapeLiteral() already registered the error */
1421  return NULL;
1422  }
1423  else
1424  {
1425  char *fmtuser = PQescapeIdentifier(conn, user, strlen(user));
1426 
1427  if (!fmtuser)
1428  {
1429  /* PQescapeIdentifier() already registered the error */
1430  PQfreemem(fmtpw);
1431  return NULL;
1432  }
1433  else
1434  {
1436  PGresult *res;
1437 
1438  initPQExpBuffer(&buf);
1439  printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD %s",
1440  fmtuser, fmtpw);
1441 
1442  res = PQexec(conn, buf.data);
1443 
1444  /* clean up */
1445  termPQExpBuffer(&buf);
1446  PQfreemem(fmtuser);
1447  PQfreemem(fmtpw);
1448 
1449  return res;
1450  }
1451  }
1452  }
1453 }
char * PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm)
Definition: fe-auth.c:1275
void PQfreemem(void *ptr)
Definition: fe-exec.c:4032
char * PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4310
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4304
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2262
static char * user
Definition: pg_regress.c:120
void printfPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:235
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129

References buf, conn, initPQExpBuffer(), PQencryptPasswordConn(), PQescapeIdentifier(), PQescapeLiteral(), PQexec(), PQfreemem(), printfPQExpBuffer(), res, termPQExpBuffer(), and user.

Referenced by exec_command_password().

◆ PQclear()

void PQclear ( PGresult res)

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

722 {
723  PGresult_data *block;
724  int i;
725 
726  /* As a convenience, do nothing for a NULL pointer */
727  if (!res)
728  return;
729  /* Also, do nothing if the argument is OOM_result */
730  if ((const PGresult *) res == &OOM_result)
731  return;
732 
733  /* Close down any events we may have */
734  for (i = 0; i < res->nEvents; i++)
735  {
736  /* only send DESTROY to successfully-initialized event procs */
738  {
740 
741  evt.result = res;
742  (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
743  res->events[i].passThrough);
744  }
745  free(res->events[i].name);
746  }
747 
748  free(res->events);
749 
750  /* Free all the subsidiary blocks */
751  while ((block = res->curBlock) != NULL)
752  {
753  res->curBlock = block->next;
754  free(block);
755  }
756 
757  /* Free the top-level tuple pointer array */
758  free(res->tuples);
759 
760  /* zero out the pointer fields to catch programming errors */
761  res->attDescs = NULL;
762  res->tuples = NULL;
763  res->paramDescs = NULL;
764  res->errFields = NULL;
765  res->events = NULL;
766  res->nEvents = 0;
767  /* res->curBlock was zeroed out earlier */
768 
769  /* Free the PGresult structure itself */
770  free(res);
771 }
static const PGresult OOM_result
Definition: fe-exec.c:49
#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(), and PQmakeEmptyPGresult().

◆ PQclientEncoding()

int PQclientEncoding ( const PGconn conn)

◆ PQclosePortal()

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

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

2540 {
2541  if (!PQexecStart(conn))
2542  return NULL;
2543  if (!PQsendTypedCommand(conn, PqMsg_Close, 'P', portal))
2544  return NULL;
2545  return PQexecFinish(conn);
2546 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2410
static int PQsendTypedCommand(PGconn *conn, char command, char type, const char *target)
Definition: fe-exec.c:2589
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2344
#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 2521 of file fe-exec.c.

2522 {
2523  if (!PQexecStart(conn))
2524  return NULL;
2525  if (!PQsendTypedCommand(conn, PqMsg_Close, 'S', stmt))
2526  return NULL;
2527  return PQexecFinish(conn);
2528 }
#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 3752 of file fe-exec.c.

3753 {
3754  if (!res)
3755  return NULL;
3756  return res->cmdStatus;
3757 }
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:181

References pg_result::cmdStatus, and res.

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

◆ PQcmdTuples()

char* PQcmdTuples ( PGresult res)

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

3823 {
3824  char *p,
3825  *c;
3826 
3827  if (!res)
3828  return "";
3829 
3830  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3831  {
3832  p = res->cmdStatus + 7;
3833  /* INSERT: skip oid and space */
3834  while (*p && *p != ' ')
3835  p++;
3836  if (*p == 0)
3837  goto interpret_error; /* no space? */
3838  p++;
3839  }
3840  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3841  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3842  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3843  p = res->cmdStatus + 7;
3844  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0 ||
3845  strncmp(res->cmdStatus, "MERGE ", 6) == 0)
3846  p = res->cmdStatus + 6;
3847  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3848  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3849  p = res->cmdStatus + 5;
3850  else
3851  return "";
3852 
3853  /* check that we have an integer (at least one digit, nothing else) */
3854  for (c = p; *c; c++)
3855  {
3856  if (!isdigit((unsigned char) *c))
3857  goto interpret_error;
3858  }
3859  if (c == p)
3860  goto interpret_error;
3861 
3862  return p;
3863 
3864 interpret_error:
3866  "could not interpret result from server: %s",
3867  res->cmdStatus);
3868  return "";
3869 }
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:938
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 1881 of file fe-connect.c.

1882 {
1883  PQExpBufferData errorBuf;
1884  PQconninfoOption *connOptions;
1885 
1886  /* We don't actually report any errors here, but callees want a buffer */
1887  initPQExpBuffer(&errorBuf);
1888  if (PQExpBufferDataBroken(errorBuf))
1889  return NULL; /* out of memory already :-( */
1890 
1891  connOptions = conninfo_init(&errorBuf);
1892  if (connOptions != NULL)
1893  {
1894  /* pass NULL errorBuf to ignore errors */
1895  if (!conninfo_add_defaults(connOptions, NULL))
1896  {
1897  PQconninfoFree(connOptions);
1898  connOptions = NULL;
1899  }
1900  }
1901 
1902  termPQExpBuffer(&errorBuf);
1903  return connOptions;
1904 }
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:5770
static bool conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
Definition: fe-connect.c:6197
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:7000
#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(), GetDbnameFromConnectionOptions(), InitPgFdwOptions(), and main().

◆ PQconnectdb()

PGconn* PQconnectdb ( const char *  conninfo)

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

745 {
746  PGconn *conn = PQconnectStart(conninfo);
747 
748  if (conn && conn->status != CONNECTION_BAD)
749  (void) pqConnectDBComplete(conn);
750 
751  return conn;
752 }
PGconn * PQconnectStart(const char *conninfo)
Definition: fe-connect.c:872

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

Referenced by connect_database(), get_db_conn(), and main().

◆ PQconnectdbParams()

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

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

692 {
693  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
694 
695  if (conn && conn->status != CONNECTION_BAD)
696  (void) pqConnectDBComplete(conn);
697 
698  return conn;
699 }
static Datum values[MAXATTR]
Definition: bootstrap.c:152
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:791

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

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

◆ PQconnectionNeedsPassword()

int PQconnectionNeedsPassword ( const PGconn conn)

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

7219 {
7220  char *password;
7221 
7222  if (!conn)
7223  return false;
7224  password = PQpass(conn);
7225  if (conn->password_needed &&
7226  (password == NULL || password[0] == '\0'))
7227  return true;
7228  else
7229  return false;
7230 }
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:7029
static char * password
Definition: streamutil.c:54
bool password_needed
Definition: libpq-int.h:480

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 7244 of file fe-connect.c.

7245 {
7246  if (!conn)
7247  return false;
7248  if (conn->gssapi_used)
7249  return true;
7250  else
7251  return false;
7252 }
bool gssapi_used
Definition: libpq-int.h:481

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 7233 of file fe-connect.c.

7234 {
7235  if (!conn)
7236  return false;
7237  if (conn->password_needed)
7238  return true;
7239  else
7240  return false;
7241 }

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 2609 of file fe-connect.c.

2610 {
2611  bool reset_connection_state_machine = false;
2612  bool need_new_connection = false;
2613  PGresult *res;
2614  char sebuf[PG_STRERROR_R_BUFLEN];
2615  int optval;
2616 
2617  if (conn == NULL)
2618  return PGRES_POLLING_FAILED;
2619 
2620  /* Get the new data */
2621  switch (conn->status)
2622  {
2623  /*
2624  * We really shouldn't have been polled in these two cases, but we
2625  * can handle it.
2626  */
2627  case CONNECTION_BAD:
2628  return PGRES_POLLING_FAILED;
2629  case CONNECTION_OK:
2630  return PGRES_POLLING_OK;
2631 
2632  /* These are reading states */
2634  case CONNECTION_AUTH_OK:
2636  case CONNECTION_CONSUME:
2638  {
2639  /* Load waiting data */
2640  int n = pqReadData(conn);
2641 
2642  if (n < 0)
2643  goto error_return;
2644  if (n == 0)
2645  return PGRES_POLLING_READING;
2646 
2647  break;
2648  }
2649 
2650  /* These are writing states, so we just proceed. */
2651  case CONNECTION_STARTED:
2652  case CONNECTION_MADE:
2653  break;
2654 
2655  /* Special cases: proceed without waiting. */
2657  case CONNECTION_NEEDED:
2660  break;
2661 
2662  default:
2663  libpq_append_conn_error(conn, "invalid connection state, probably indicative of memory corruption");
2664  goto error_return;
2665  }
2666 
2667 
2668 keep_going: /* We will come back to here until there is
2669  * nothing left to do. */
2670 
2671  /* Time to advance to next address, or next host if no more addresses? */
2672  if (conn->try_next_addr)
2673  {
2674  if (conn->whichaddr < conn->naddr)
2675  {
2676  conn->whichaddr++;
2677  reset_connection_state_machine = true;
2678  }
2679  else
2680  conn->try_next_host = true;
2681  conn->try_next_addr = false;
2682  }
2683 
2684  /* Time to advance to next connhost[] entry? */
2685  if (conn->try_next_host)
2686  {
2687  pg_conn_host *ch;
2688  struct addrinfo hint;
2689  struct addrinfo *addrlist;
2690  int thisport;
2691  int ret;
2692  char portstr[MAXPGPATH];
2693 
2694  if (conn->whichhost + 1 < conn->nconnhost)
2695  conn->whichhost++;
2696  else
2697  {
2698  /*
2699  * Oops, no more hosts.
2700  *
2701  * If we are trying to connect in "prefer-standby" mode, then drop
2702  * the standby requirement and start over. Don't do this for
2703  * cancel requests though, since we are certain the list of
2704  * servers won't change as the target_server_type option is not
2705  * applicable to those connections.
2706  *
2707  * Otherwise, an appropriate error message is already set up, so
2708  * we just need to set the right status.
2709  */
2711  conn->nconnhost > 0 &&
2712  !conn->cancelRequest)
2713  {
2715  conn->whichhost = 0;
2716  }
2717  else
2718  goto error_return;
2719  }
2720 
2721  /* Drop any address info for previous host */
2723 
2724  /*
2725  * Look up info for the new host. On failure, log the problem in
2726  * conn->errorMessage, then loop around to try the next host. (Note
2727  * we don't clear try_next_host until we've succeeded.)
2728  */
2729  ch = &conn->connhost[conn->whichhost];
2730 
2731  /* Initialize hint structure */
2732  MemSet(&hint, 0, sizeof(hint));
2733  hint.ai_socktype = SOCK_STREAM;
2734  hint.ai_family = AF_UNSPEC;
2735 
2736  /* Figure out the port number we're going to use. */
2737  if (ch->port == NULL || ch->port[0] == '\0')
2738  thisport = DEF_PGPORT;
2739  else
2740  {
2741  if (!pqParseIntParam(ch->port, &thisport, conn, "port"))
2742  goto error_return;
2743 
2744  if (thisport < 1 || thisport > 65535)
2745  {
2746  libpq_append_conn_error(conn, "invalid port number: \"%s\"", ch->port);
2747  goto keep_going;
2748  }
2749  }
2750  snprintf(portstr, sizeof(portstr), "%d", thisport);
2751 
2752  /* Use pg_getaddrinfo_all() to resolve the address */
2753  switch (ch->type)
2754  {
2755  case CHT_HOST_NAME:
2756  ret = pg_getaddrinfo_all(ch->host, portstr, &hint,
2757  &addrlist);
2758  if (ret || !addrlist)
2759  {
2760  libpq_append_conn_error(conn, "could not translate host name \"%s\" to address: %s",
2761  ch->host, gai_strerror(ret));
2762  goto keep_going;
2763  }
2764  break;
2765 
2766  case CHT_HOST_ADDRESS:
2767  hint.ai_flags = AI_NUMERICHOST;
2768  ret = pg_getaddrinfo_all(ch->hostaddr, portstr, &hint,
2769  &addrlist);
2770  if (ret || !addrlist)
2771  {
2772  libpq_append_conn_error(conn, "could not parse network address \"%s\": %s",
2773  ch->hostaddr, gai_strerror(ret));
2774  goto keep_going;
2775  }
2776  break;
2777 
2778  case CHT_UNIX_SOCKET:
2779  hint.ai_family = AF_UNIX;
2780  UNIXSOCK_PATH(portstr, thisport, ch->host);
2781  if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
2782  {
2783  libpq_append_conn_error(conn, "Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
2784  portstr,
2785  (int) (UNIXSOCK_PATH_BUFLEN - 1));
2786  goto keep_going;
2787  }
2788 
2789  /*
2790  * NULL hostname tells pg_getaddrinfo_all to parse the service
2791  * name as a Unix-domain socket path.
2792  */
2793  ret = pg_getaddrinfo_all(NULL, portstr, &hint,
2794  &addrlist);
2795  if (ret || !addrlist)
2796  {
2797  libpq_append_conn_error(conn, "could not translate Unix-domain socket path \"%s\" to address: %s",
2798  portstr, gai_strerror(ret));
2799  goto keep_going;
2800  }
2801  break;
2802  }
2803 
2804  /*
2805  * Store a copy of the addrlist in private memory so we can perform
2806  * randomization for load balancing.
2807  */
2808  ret = store_conn_addrinfo(conn, addrlist);
2809  pg_freeaddrinfo_all(hint.ai_family, addrlist);
2810  if (ret)
2811  goto error_return; /* message already logged */
2812 
2813  /*
2814  * If random load balancing is enabled we shuffle the addresses.
2815  */
2817  {
2818  /*
2819  * This is the "inside-out" variant of the Fisher-Yates shuffle
2820  * algorithm. Notionally, we append each new value to the array
2821  * and then swap it with a randomly-chosen array element (possibly
2822  * including itself, else we fail to generate permutations with
2823  * the last integer last). The swap step can be optimized by
2824  * combining it with the insertion.
2825  *
2826  * We don't need to initialize conn->prng_state here, because that
2827  * already happened in pqConnectOptions2.
2828  */
2829  for (int i = 1; i < conn->naddr; i++)
2830  {
2831  int j = pg_prng_uint64_range(&conn->prng_state, 0, i);
2832  AddrInfo temp = conn->addr[j];
2833 
2834  conn->addr[j] = conn->addr[i];
2835  conn->addr[i] = temp;
2836  }
2837  }
2838 
2839  reset_connection_state_machine = true;
2840  conn->try_next_host = false;
2841  }
2842 
2843  /* Reset connection state machine? */
2844  if (reset_connection_state_machine)
2845  {
2846  /*
2847  * (Re) initialize our connection control variables for a set of
2848  * connection attempts to a single server address. These variables
2849  * must persist across individual connection attempts, but we must
2850  * reset them when we start to consider a new server.
2851  */
2852  conn->pversion = PG_PROTOCOL(3, 0);
2853  conn->send_appname = true;
2854  conn->failed_enc_methods = 0;
2855  conn->current_enc_method = 0;
2857  reset_connection_state_machine = false;
2858  need_new_connection = true;
2859  }
2860 
2861  /* Force a new connection (perhaps to the same server as before)? */
2862  if (need_new_connection)
2863  {
2864  /* Drop any existing connection */
2865  pqDropConnection(conn, true);
2866 
2867  /* Reset all state obtained from old server */
2869 
2870  /* Drop any PGresult we might have, too */
2875 
2876  /* Reset conn->status to put the state machine in the right state */
2878 
2879  need_new_connection = false;
2880  }
2881 
2882  /*
2883  * Decide what to do next, if server rejects SSL or GSS negotiation, but
2884  * the connection is still valid. If there are no options left, error out
2885  * with 'msg'.
2886  */
2887 #define ENCRYPTION_NEGOTIATION_FAILED(msg) \
2888  do { \
2889  switch (encryption_negotiation_failed(conn)) \
2890  { \
2891  case 0: \
2892  libpq_append_conn_error(conn, (msg)); \
2893  goto error_return; \
2894  case 1: \
2895  conn->status = CONNECTION_MADE; \
2896  return PGRES_POLLING_WRITING; \
2897  case 2: \
2898  need_new_connection = true; \
2899  goto keep_going; \
2900  } \
2901  } while(0);
2902 
2903  /*
2904  * Decide what to do next, if connection fails. If there are no options
2905  * left, return with an error. The error message has already been written
2906  * to the connection's error buffer.
2907  */
2908 #define CONNECTION_FAILED() \
2909  do { \
2910  if (connection_failed(conn)) \
2911  { \
2912  need_new_connection = true; \
2913  goto keep_going; \
2914  } \
2915  else \
2916  goto error_return; \
2917  } while(0);
2918 
2919  /* Now try to advance the state machine for this connection */
2920  switch (conn->status)
2921  {
2922  case CONNECTION_NEEDED:
2923  {
2924  /*
2925  * Try to initiate a connection to one of the addresses
2926  * returned by pg_getaddrinfo_all(). conn->whichaddr is the
2927  * next one to try.
2928  *
2929  * The extra level of braces here is historical. It's not
2930  * worth reindenting this whole switch case to remove 'em.
2931  */
2932  {
2933  char host_addr[NI_MAXHOST];
2934  int sock_type;
2935  AddrInfo *addr_cur;
2936 
2937  /*
2938  * Advance to next possible host, if we've tried all of
2939  * the addresses for the current host.
2940  */
2941  if (conn->whichaddr == conn->naddr)
2942  {
2943  conn->try_next_host = true;
2944  goto keep_going;
2945  }
2946  addr_cur = &conn->addr[conn->whichaddr];
2947 
2948  /* Remember current address for possible use later */
2949  memcpy(&conn->raddr, &addr_cur->addr, sizeof(SockAddr));
2950 
2951 #ifdef ENABLE_GSS
2952 
2953  /*
2954  * Before establishing the connection, check if it's
2955  * doomed to fail because gssencmode='require' but GSSAPI
2956  * is not available.
2957  */
2958  if (conn->gssencmode[0] == 'r')
2959  {
2960  if (conn->raddr.addr.ss_family == AF_UNIX)
2961  {
2963  "GSSAPI encryption required but it is not supported over a local socket");
2964  goto error_return;
2965  }
2966  if (conn->gcred == GSS_C_NO_CREDENTIAL)
2967  {
2968  if (!pg_GSS_have_cred_cache(&conn->gcred))
2969  {
2971  "GSSAPI encryption required but no credential cache");
2972  goto error_return;
2973  }
2974  }
2975  }
2976 #endif
2977 
2978  /*
2979  * Choose the encryption method to try first. Do this
2980  * before establishing the connection, so that if none of
2981  * the modes allowed by the connections options are
2982  * available, we can error out before establishing the
2983  * connection.
2984  */
2986  goto error_return;
2987 
2988  /*
2989  * Set connip, too. Note we purposely ignore strdup
2990  * failure; not a big problem if it fails.
2991  */
2992  if (conn->connip != NULL)
2993  {
2994  free(conn->connip);
2995  conn->connip = NULL;
2996  }
2997  getHostaddr(conn, host_addr, NI_MAXHOST);
2998  if (host_addr[0])
2999  conn->connip = strdup(host_addr);
3000 
3001  /* Try to create the socket */
3002  sock_type = SOCK_STREAM;
3003 #ifdef SOCK_CLOEXEC
3004 
3005  /*
3006  * Atomically mark close-on-exec, if possible on this
3007  * platform, so that there isn't a window where a
3008  * subprogram executed by another thread inherits the
3009  * socket. See fallback code below.
3010  */
3011  sock_type |= SOCK_CLOEXEC;
3012 #endif
3013 #ifdef SOCK_NONBLOCK
3014 
3015  /*
3016  * We might as well skip a system call for nonblocking
3017  * mode too, if we can.
3018  */
3019  sock_type |= SOCK_NONBLOCK;
3020 #endif
3021  conn->sock = socket(addr_cur->family, sock_type, 0);
3022  if (conn->sock == PGINVALID_SOCKET)
3023  {
3024  int errorno = SOCK_ERRNO;
3025 
3026  /*
3027  * Silently ignore socket() failure if we have more
3028  * addresses to try; this reduces useless chatter in
3029  * cases where the address list includes both IPv4 and
3030  * IPv6 but kernel only accepts one family.
3031  */
3032  if (conn->whichaddr < conn->naddr ||
3033  conn->whichhost + 1 < conn->nconnhost)
3034  {
3035  conn->try_next_addr = true;
3036  goto keep_going;
3037  }
3038  emitHostIdentityInfo(conn, host_addr);
3039  libpq_append_conn_error(conn, "could not create socket: %s",
3040  SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)));
3041  goto error_return;
3042  }
3043 
3044  /*
3045  * Once we've identified a target address, all errors
3046  * except the preceding socket()-failure case should be
3047  * prefixed with host-identity information. (If the
3048  * connection succeeds, the contents of conn->errorMessage
3049  * won't matter, so this is harmless.)
3050  */
3051  emitHostIdentityInfo(conn, host_addr);
3052 
3053  /*
3054  * Select socket options: no delay of outgoing data for
3055  * TCP sockets, nonblock mode, close-on-exec. Try the
3056  * next address if any of this fails.
3057  */
3058  if (addr_cur->family != AF_UNIX)
3059  {
3060  if (!connectNoDelay(conn))
3061  {
3062  /* error message already created */
3063  conn->try_next_addr = true;
3064  goto keep_going;
3065  }
3066  }
3067 #ifndef SOCK_NONBLOCK
3068  if (!pg_set_noblock(conn->sock))
3069  {
3070  libpq_append_conn_error(conn, "could not set socket to nonblocking mode: %s",
3071  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3072  conn->try_next_addr = true;
3073  goto keep_going;
3074  }
3075 #endif
3076 
3077 #ifndef SOCK_CLOEXEC
3078 #ifdef F_SETFD
3079  if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
3080  {
3081  libpq_append_conn_error(conn, "could not set socket to close-on-exec mode: %s",
3082  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3083  conn->try_next_addr = true;
3084  goto keep_going;
3085  }
3086 #endif /* F_SETFD */
3087 #endif
3088 
3089  if (addr_cur->family != AF_UNIX)
3090  {
3091 #ifndef WIN32
3092  int on = 1;
3093 #endif
3094  int usekeepalives = useKeepalives(conn);
3095  int err = 0;
3096 
3097  if (usekeepalives < 0)
3098  {
3099  libpq_append_conn_error(conn, "keepalives parameter must be an integer");
3100  err = 1;
3101  }
3102  else if (usekeepalives == 0)
3103  {
3104  /* Do nothing */
3105  }
3106 #ifndef WIN32
3107  else if (setsockopt(conn->sock,
3108  SOL_SOCKET, SO_KEEPALIVE,
3109  (char *) &on, sizeof(on)) < 0)
3110  {
3111  libpq_append_conn_error(conn, "%s(%s) failed: %s",
3112  "setsockopt",
3113  "SO_KEEPALIVE",
3114  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3115  err = 1;
3116  }
3117  else if (!setKeepalivesIdle(conn)
3119  || !setKeepalivesCount(conn))
3120  err = 1;
3121 #else /* WIN32 */
3122 #ifdef SIO_KEEPALIVE_VALS
3123  else if (!prepKeepalivesWin32(conn))
3124  err = 1;
3125 #endif /* SIO_KEEPALIVE_VALS */
3126 #endif /* WIN32 */
3127  else if (!setTCPUserTimeout(conn))
3128  err = 1;
3129 
3130  if (err)
3131  {
3132  conn->try_next_addr = true;
3133  goto keep_going;
3134  }
3135  }
3136 
3137  /*----------
3138  * We have three methods of blocking SIGPIPE during
3139  * send() calls to this socket:
3140  *
3141  * - setsockopt(sock, SO_NOSIGPIPE)
3142  * - send(sock, ..., MSG_NOSIGNAL)
3143  * - setting the signal mask to SIG_IGN during send()
3144  *
3145  * The third method requires three syscalls per send,
3146  * so we prefer either of the first two, but they are
3147  * less portable. The state is tracked in the following
3148  * members of PGconn:
3149  *
3150  * conn->sigpipe_so - we have set up SO_NOSIGPIPE
3151  * conn->sigpipe_flag - we're specifying MSG_NOSIGNAL
3152  *
3153  * If we can use SO_NOSIGPIPE, then set sigpipe_so here
3154  * and we're done. Otherwise, set sigpipe_flag so that
3155  * we will try MSG_NOSIGNAL on sends. If we get an error
3156  * with MSG_NOSIGNAL, we'll clear that flag and revert to
3157  * signal masking.
3158  *----------
3159  */
3160  conn->sigpipe_so = false;
3161 #ifdef MSG_NOSIGNAL
3162  conn->sigpipe_flag = true;
3163 #else
3164  conn->sigpipe_flag = false;
3165 #endif /* MSG_NOSIGNAL */
3166 
3167 #ifdef SO_NOSIGPIPE
3168  optval = 1;
3169  if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
3170  (char *) &optval, sizeof(optval)) == 0)
3171  {
3172  conn->sigpipe_so = true;
3173  conn->sigpipe_flag = false;
3174  }
3175 #endif /* SO_NOSIGPIPE */
3176 
3177  /*
3178  * Start/make connection. This should not block, since we
3179  * are in nonblock mode. If it does, well, too bad.
3180  */
3181  if (connect(conn->sock, (struct sockaddr *) &addr_cur->addr.addr,
3182  addr_cur->addr.salen) < 0)
3183  {
3184  if (SOCK_ERRNO == EINPROGRESS ||
3185 #ifdef WIN32
3186  SOCK_ERRNO == EWOULDBLOCK ||
3187 #endif
3188  SOCK_ERRNO == EINTR)
3189  {
3190  /*
3191  * This is fine - we're in non-blocking mode, and
3192  * the connection is in progress. Tell caller to
3193  * wait for write-ready on socket.
3194  */
3196  return PGRES_POLLING_WRITING;
3197  }
3198  /* otherwise, trouble */
3199  }
3200  else
3201  {
3202  /*
3203  * Hm, we're connected already --- seems the "nonblock
3204  * connection" wasn't. Advance the state machine and
3205  * go do the next stuff.
3206  */
3208  goto keep_going;
3209  }
3210 
3211  /*
3212  * This connection failed. Add the error report to
3213  * conn->errorMessage, then try the next address if any.
3214  */
3216  conn->try_next_addr = true;
3217  goto keep_going;
3218  }
3219  }
3220 
3221  case CONNECTION_STARTED:
3222  {
3223  socklen_t optlen = sizeof(optval);
3224 
3225  /*
3226  * Write ready, since we've made it here, so the connection
3227  * has been made ... or has failed.
3228  */
3229 
3230  /*
3231  * Now check (using getsockopt) that there is not an error
3232  * state waiting for us on the socket.
3233  */
3234 
3235  if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
3236  (char *) &optval, &optlen) == -1)
3237  {
3238  libpq_append_conn_error(conn, "could not get socket error status: %s",
3239  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3240  goto error_return;
3241  }
3242  else if (optval != 0)
3243  {
3244  /*
3245  * When using a nonblocking connect, we will typically see
3246  * connect failures at this point, so provide a friendly
3247  * error message.
3248  */
3249  connectFailureMessage(conn, optval);
3250 
3251  /*
3252  * Try the next address if any, just as in the case where
3253  * connect() returned failure immediately.
3254  */
3255  conn->try_next_addr = true;
3256  goto keep_going;
3257  }
3258 
3259  /* Fill in the client address */
3260  conn->laddr.salen = sizeof(conn->laddr.addr);
3261  if (getsockname(conn->sock,
3262  (struct sockaddr *) &conn->laddr.addr,
3263  &conn->laddr.salen) < 0)
3264  {
3265  libpq_append_conn_error(conn, "could not get client address from socket: %s",
3266  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3267  goto error_return;
3268  }
3269 
3270  /*
3271  * Implement requirepeer check, if requested and it's a
3272  * Unix-domain socket.
3273  */
3274  if (conn->requirepeer && conn->requirepeer[0] &&
3275  conn->raddr.addr.ss_family == AF_UNIX)
3276  {
3277 #ifndef WIN32
3278  char *remote_username;
3279 #endif
3280  uid_t uid;
3281  gid_t gid;
3282 
3283  errno = 0;
3284  if (getpeereid(conn->sock, &uid, &gid) != 0)
3285  {
3286  /*
3287  * Provide special error message if getpeereid is a
3288  * stub
3289  */
3290  if (errno == ENOSYS)
3291  libpq_append_conn_error(conn, "requirepeer parameter is not supported on this platform");
3292  else
3293  libpq_append_conn_error(conn, "could not get peer credentials: %s",
3294  strerror_r(errno, sebuf, sizeof(sebuf)));
3295  goto error_return;
3296  }
3297 
3298 #ifndef WIN32
3299  remote_username = pg_fe_getusername(uid,
3300  &conn->errorMessage);
3301  if (remote_username == NULL)
3302  goto error_return; /* message already logged */
3303 
3304  if (strcmp(remote_username, conn->requirepeer) != 0)
3305  {
3306  libpq_append_conn_error(conn, "requirepeer specifies \"%s\", but actual peer user name is \"%s\"",
3307  conn->requirepeer, remote_username);
3308  free(remote_username);
3309  goto error_return;
3310  }
3311  free(remote_username);
3312 #else /* WIN32 */
3313  /* should have failed with ENOSYS above */
3314  Assert(false);
3315 #endif /* WIN32 */
3316  }
3317 
3318  /*
3319  * Make sure we can write before advancing to next step.
3320  */
3322  return PGRES_POLLING_WRITING;
3323  }
3324 
3325  case CONNECTION_MADE:
3326  {
3327  char *startpacket;
3328  int packetlen;
3329 
3330 #ifdef ENABLE_GSS
3331 
3332  /*
3333  * If GSSAPI encryption is enabled, send a packet to the
3334  * server asking for GSSAPI Encryption and proceed with GSSAPI
3335  * handshake. We will come back here after GSSAPI encryption
3336  * has been established, with conn->gctx set.
3337  */
3338  if (conn->current_enc_method == ENC_GSSAPI && !conn->gctx)
3339  {
3341 
3342  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3343  {
3344  libpq_append_conn_error(conn, "could not send GSSAPI negotiation packet: %s",
3345  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3346  goto error_return;
3347  }
3348 
3349  /* Ok, wait for response */
3351  return PGRES_POLLING_READING;
3352  }
3353 #endif
3354 
3355 #ifdef USE_SSL
3356 
3357  /*
3358  * Enable the libcrypto callbacks before checking if SSL needs
3359  * to be done. This is done before sending the startup packet
3360  * as depending on the type of authentication done, like MD5
3361  * or SCRAM that use cryptohashes, the callbacks would be
3362  * required even without a SSL connection
3363  */
3364  if (pqsecure_initialize(conn, false, true) < 0)
3365  goto error_return;
3366 
3367  /*
3368  * If SSL is enabled, start the SSL negotiation. We will come
3369  * back here after SSL encryption has been established, with
3370  * ssl_in_use set.
3371  */
3373  {
3374  /*
3375  * If traditional postgres SSL negotiation is used, send
3376  * the SSL request. In direct negotiation, jump straight
3377  * into the SSL handshake.
3378  */
3379  if (conn->sslnegotiation[0] == 'p')
3380  {
3381  ProtocolVersion pv;
3382 
3383  /*
3384  * Send the SSL request packet.
3385  *
3386  * Theoretically, this could block, but it really
3387  * shouldn't since we only got here if the socket is
3388  * write-ready.
3389  */
3391  if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
3392  {
3393  libpq_append_conn_error(conn, "could not send SSL negotiation packet: %s",
3394  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3395  goto error_return;
3396  }
3397  /* Ok, wait for response */
3399  return PGRES_POLLING_READING;
3400  }
3401  else
3402  {
3403  Assert(conn->sslnegotiation[0] == 'd');
3405  return PGRES_POLLING_WRITING;
3406  }
3407  }
3408 #endif /* USE_SSL */
3409 
3410  /*
3411  * For cancel requests this is as far as we need to go in the
3412  * connection establishment. Now we can actually send our
3413  * cancellation request.
3414  */
3415  if (conn->cancelRequest)
3416  {
3417  CancelRequestPacket cancelpacket;
3418 
3419  packetlen = sizeof(cancelpacket);
3421  cancelpacket.backendPID = pg_hton32(conn->be_pid);
3422  cancelpacket.cancelAuthCode = pg_hton32(conn->be_key);
3423  if (pqPacketSend(conn, 0, &cancelpacket, packetlen) != STATUS_OK)
3424  {
3425  libpq_append_conn_error(conn, "could not send cancel packet: %s",
3426  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3427  goto error_return;
3428  }
3430  return PGRES_POLLING_READING;
3431  }
3432 
3433  /*
3434  * We have now established encryption, or we are happy to
3435  * proceed without.
3436  */
3437 
3438  /* Build the startup packet. */
3439  startpacket = pqBuildStartupPacket3(conn, &packetlen,
3441  if (!startpacket)
3442  {
3443  libpq_append_conn_error(conn, "out of memory");
3444  goto error_return;
3445  }
3446 
3447  /*
3448  * Send the startup packet.
3449  *
3450  * Theoretically, this could block, but it really shouldn't
3451  * since we only got here if the socket is write-ready.
3452  */
3453  if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
3454  {
3455  libpq_append_conn_error(conn, "could not send startup packet: %s",
3456  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
3457  free(startpacket);
3458  goto error_return;
3459  }
3460 
3461  free(startpacket);
3462 
3464  return PGRES_POLLING_READING;
3465  }
3466 
3467  /*
3468  * Handle SSL negotiation: wait for postmaster messages and
3469  * respond as necessary.
3470  */
3472  {
3473 #ifdef USE_SSL
3474  PostgresPollingStatusType pollres;
3475 
3476  /*
3477  * On first time through with traditional SSL negotiation, get
3478  * the postmaster's response to our SSLRequest packet. With
3479  * sslnegotiation='direct', go straight to initiating SSL.
3480  */
3481  if (!conn->ssl_in_use && conn->sslnegotiation[0] == 'p')
3482  {
3483  /*
3484  * We use pqReadData here since it has the logic to
3485  * distinguish no-data-yet from connection closure. Since
3486  * conn->ssl isn't set, a plain recv() will occur.
3487  */
3488  char SSLok;
3489  int rdresult;
3490 
3491  rdresult = pqReadData(conn);
3492  if (rdresult < 0)
3493  {
3494  /* errorMessage is already filled in */
3495  goto error_return;
3496  }
3497  if (rdresult == 0)
3498  {
3499  /* caller failed to wait for data */
3500  return PGRES_POLLING_READING;
3501  }
3502  if (pqGetc(&SSLok, conn) < 0)
3503  {
3504  /* should not happen really */
3505  return PGRES_POLLING_READING;
3506  }
3507  if (SSLok == 'S')
3508  {
3509  /* mark byte consumed */
3510  conn->inStart = conn->inCursor;
3511  }
3512  else if (SSLok == 'N')
3513  {
3514  /* mark byte consumed */
3515  conn->inStart = conn->inCursor;
3516 
3517  /*
3518  * The connection is still valid, so if it's OK to
3519  * continue without SSL, we can proceed using this
3520  * connection. Otherwise return with an error.
3521  */
3522  ENCRYPTION_NEGOTIATION_FAILED("server does not support SSL, but SSL was required");
3523  }
3524  else if (SSLok == 'E')
3525  {
3526  /*
3527  * Server failure of some sort, such as failure to
3528  * fork a backend process. We need to process and
3529  * report the error message, which might be formatted
3530  * according to either protocol 2 or protocol 3.
3531  * Rather than duplicate the code for that, we flip
3532  * into AWAITING_RESPONSE state and let the code there
3533  * deal with it. Note we have *not* consumed the "E"
3534  * byte here.
3535  */
3537  goto keep_going;
3538  }
3539  else
3540  {
3541  libpq_append_conn_error(conn, "received invalid response to SSL negotiation: %c",
3542  SSLok);
3543  goto error_return;
3544  }
3545  }
3546 
3547  /*
3548  * Set up global SSL state if required. The crypto state has
3549  * already been set if libpq took care of doing that, so there
3550  * is no need to make that happen again.
3551  */
3552  if (pqsecure_initialize(conn, true, false) != 0)
3553  goto error_return;
3554 
3555  /*
3556  * Begin or continue the SSL negotiation process.
3557  */
3558  pollres = pqsecure_open_client(conn);
3559  if (pollres == PGRES_POLLING_OK)
3560  {
3561  /*
3562  * At this point we should have no data already buffered.
3563  * If we do, it was received before we performed the SSL
3564  * handshake, so it wasn't encrypted and indeed may have
3565  * been injected by a man-in-the-middle.
3566  */
3567  if (conn->inCursor != conn->inEnd)
3568  {
3569  libpq_append_conn_error(conn, "received unencrypted data after SSL response");
3570  goto error_return;
3571  }
3572 
3573  /* SSL handshake done, ready to send startup packet */
3575  return PGRES_POLLING_WRITING;
3576  }
3577  if (pollres == PGRES_POLLING_FAILED)
3578  {
3579  /*
3580  * Failed direct ssl connection, possibly try a new
3581  * connection with postgres negotiation
3582  */
3584  }
3585  /* Else, return POLLING_READING or POLLING_WRITING status */
3586  return pollres;
3587 #else /* !USE_SSL */
3588  /* can't get here */
3589  goto error_return;
3590 #endif /* USE_SSL */
3591  }
3592 
3594  {
3595 #ifdef ENABLE_GSS
3596  PostgresPollingStatusType pollres;
3597 
3598  /*
3599  * If we haven't yet, get the postmaster's response to our
3600  * negotiation packet
3601  */
3602  if (!conn->gctx)
3603  {
3604  char gss_ok;
3605  int rdresult = pqReadData(conn);
3606 
3607  if (rdresult < 0)
3608  /* pqReadData fills in error message */
3609  goto error_return;
3610  else if (rdresult == 0)
3611  /* caller failed to wait for data */
3612  return PGRES_POLLING_READING;
3613  if (pqGetc(&gss_ok, conn) < 0)
3614  /* shouldn't happen... */
3615  return PGRES_POLLING_READING;
3616 
3617  if (gss_ok == 'E')
3618  {
3619  /*
3620  * Server failure of some sort, possibly protocol
3621  * version support failure. We need to process and
3622  * report the error message, which might be formatted
3623  * according to either protocol 2 or protocol 3.
3624  * Rather than duplicate the code for that, we flip
3625  * into AWAITING_RESPONSE state and let the code there
3626  * deal with it. Note we have *not* consumed the "E"
3627  * byte here.
3628  */
3630  goto keep_going;
3631  }
3632 
3633  /* mark byte consumed */
3634  conn->inStart = conn->inCursor;
3635 
3636  if (gss_ok == 'N')
3637  {
3638  /*
3639  * The connection is still valid, so if it's OK to
3640  * continue without GSS, we can proceed using this
3641  * connection. Otherwise return with an error.
3642  */
3643  ENCRYPTION_NEGOTIATION_FAILED("server doesn't support GSSAPI encryption, but it was required");
3644  }
3645  else if (gss_ok != 'G')
3646  {
3647  libpq_append_conn_error(conn, "received invalid response to GSSAPI negotiation: %c",
3648  gss_ok);
3649  goto error_return;
3650  }
3651  }
3652 
3653  /* Begin or continue GSSAPI negotiation */
3654  pollres = pqsecure_open_gss(conn);
3655  if (pollres == PGRES_POLLING_OK)
3656  {
3657  /*
3658  * At this point we should have no data already buffered.
3659  * If we do, it was received before we performed the GSS
3660  * handshake, so it wasn't encrypted and indeed may have
3661  * been injected by a man-in-the-middle.
3662  */
3663  if (conn->inCursor != conn->inEnd)
3664  {
3665  libpq_append_conn_error(conn, "received unencrypted data after GSSAPI encryption response");
3666  goto error_return;
3667  }
3668 
3669  /* All set for startup packet */
3671  return PGRES_POLLING_WRITING;
3672  }
3673  else if (pollres == PGRES_POLLING_FAILED)
3674  {
3676  }
3677  /* Else, return POLLING_READING or POLLING_WRITING status */
3678  return pollres;
3679 #else /* !ENABLE_GSS */
3680  /* unreachable */
3681  goto error_return;
3682 #endif /* ENABLE_GSS */
3683  }
3684 
3685  /*
3686  * Handle authentication exchange: wait for postmaster messages
3687  * and respond as necessary.
3688  */
3690  {
3691  char beresp;
3692  int msgLength;
3693  int avail;
3694  AuthRequest areq;
3695  int res;
3696 
3697  /*
3698  * Scan the message from current point (note that if we find
3699  * the message is incomplete, we will return without advancing
3700  * inStart, and resume here next time).
3701  */
3702  conn->inCursor = conn->inStart;
3703 
3704  /* Read type byte */
3705  if (pqGetc(&beresp, conn))
3706  {
3707  /* We'll come back when there is more data */
3708  return PGRES_POLLING_READING;
3709  }
3710 
3711  /*
3712  * Validate message type: we expect only an authentication
3713  * request, NegotiateProtocolVersion, or an error here.
3714  * Anything else probably means it's not Postgres on the other
3715  * end at all.
3716  */
3717  if (beresp != PqMsg_AuthenticationRequest &&
3718  beresp != PqMsg_ErrorResponse &&
3720  {
3721  libpq_append_conn_error(conn, "expected authentication request from server, but received %c",
3722  beresp);
3723  goto error_return;
3724  }
3725 
3726  /* Read message length word */
3727  if (pqGetInt(&msgLength, 4, conn))
3728  {
3729  /* We'll come back when there is more data */
3730  return PGRES_POLLING_READING;
3731  }
3732 
3733  /*
3734  * Try to validate message length before using it.
3735  *
3736  * Authentication requests can't be very large, although GSS
3737  * auth requests may not be that small. Same for
3738  * NegotiateProtocolVersion.
3739  *
3740  * Errors can be a little larger, but not huge. If we see a
3741  * large apparent length in an error, it means we're really
3742  * talking to a pre-3.0-protocol server; cope. (Before
3743  * version 14, the server also used the old protocol for
3744  * errors that happened before processing the startup packet.)
3745  */
3746  if (beresp == PqMsg_AuthenticationRequest &&
3747  (msgLength < 8 || msgLength > 2000))
3748  {
3749  libpq_append_conn_error(conn, "received invalid authentication request");
3750  goto error_return;
3751  }
3752  if (beresp == PqMsg_NegotiateProtocolVersion &&
3753  (msgLength < 8 || msgLength > 2000))
3754  {
3755  libpq_append_conn_error(conn, "received invalid protocol negotiation message");
3756  goto error_return;
3757  }
3758 
3759 #define MAX_ERRLEN 30000
3760  if (beresp == PqMsg_ErrorResponse &&
3761  (msgLength < 8 || msgLength > MAX_ERRLEN))
3762  {
3763  /* Handle error from a pre-3.0 server */
3764  conn->inCursor = conn->inStart + 1; /* reread data */
3766  {
3767  /*
3768  * We may not have authenticated the server yet, so
3769  * don't let the buffer grow forever.
3770  */
3771  avail = conn->inEnd - conn->inCursor;
3772  if (avail > MAX_ERRLEN)
3773  {
3774  libpq_append_conn_error(conn, "received invalid error message");
3775  goto error_return;
3776  }
3777 
3778  /* We'll come back when there is more data */
3779  return PGRES_POLLING_READING;
3780  }
3781  /* OK, we read the message; mark data consumed */
3782  conn->inStart = conn->inCursor;
3783 
3784  /*
3785  * Before 7.2, the postmaster didn't always end its
3786  * messages with a newline, so add one if needed to
3787  * conform to libpq conventions.
3788  */
3789  if (conn->errorMessage.len == 0 ||
3790  conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3791  {
3793  }
3794 
3795  goto error_return;
3796  }
3797 #undef MAX_ERRLEN
3798 
3799  /*
3800  * Can't process if message body isn't all here yet.
3801  *
3802  * After this check passes, any further EOF during parsing
3803  * implies that the server sent a bad/truncated message.
3804  * Reading more bytes won't help in that case, so don't return
3805  * PGRES_POLLING_READING after this point.
3806  */
3807  msgLength -= 4;
3808  avail = conn->inEnd - conn->inCursor;
3809  if (avail < msgLength)
3810  {
3811  /*
3812  * Before returning, try to enlarge the input buffer if
3813  * needed to hold the whole message; see notes in
3814  * pqParseInput3.
3815  */
3816  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
3817  conn))
3818  goto error_return;
3819  /* We'll come back when there is more data */
3820  return PGRES_POLLING_READING;
3821  }
3822 
3823  /* Handle errors. */
3824  if (beresp == PqMsg_ErrorResponse)
3825  {
3826  if (pqGetErrorNotice3(conn, true))
3827  {
3828  libpq_append_conn_error(conn, "received invalid error message");
3829  goto error_return;
3830  }
3831  /* OK, we read the message; mark data consumed */
3832  conn->inStart = conn->inCursor;
3833 
3834  /*
3835  * If error is "cannot connect now", try the next host if
3836  * any (but we don't want to consider additional addresses
3837  * for this host, nor is there much point in changing SSL
3838  * or GSS mode). This is helpful when dealing with
3839  * standby servers that might not be in hot-standby state.
3840  */
3841  if (strcmp(conn->last_sqlstate,
3843  {
3844  conn->try_next_host = true;
3845  goto keep_going;
3846  }
3847 
3848  /* Check to see if we should mention pgpassfile */
3850 
3852  }
3853  else if (beresp == PqMsg_NegotiateProtocolVersion)
3854  {
3856  {
3857  libpq_append_conn_error(conn, "received invalid protocol negotiation message");
3858  goto error_return;
3859  }
3860  /* OK, we read the message; mark data consumed */
3861  conn->inStart = conn->inCursor;
3862  goto error_return;
3863  }
3864 
3865  /* It is an authentication request. */
3866  conn->auth_req_received = true;
3867 
3868  /* Get the type of request. */
3869  if (pqGetInt((int *) &areq, 4, conn))
3870  {
3871  /* can't happen because we checked the length already */
3872  libpq_append_conn_error(conn, "received invalid authentication request");
3873  goto error_return;
3874  }
3875  msgLength -= 4;
3876 
3877  /*
3878  * Process the rest of the authentication request message, and
3879  * respond to it if necessary.
3880  *
3881  * Note that conn->pghost must be non-NULL if we are going to
3882  * avoid the Kerberos code doing a hostname look-up.
3883  */
3884  res = pg_fe_sendauth(areq, msgLength, conn);
3885 
3886  /* OK, we have processed the message; mark data consumed */
3887  conn->inStart = conn->inCursor;
3888 
3889  if (res != STATUS_OK)
3890  goto error_return;
3891 
3892  /*
3893  * Just make sure that any data sent by pg_fe_sendauth is
3894  * flushed out. Although this theoretically could block, it
3895  * really shouldn't since we don't send large auth responses.
3896  */
3897  if (pqFlush(conn))
3898  goto error_return;
3899 
3900  if (areq == AUTH_REQ_OK)
3901  {
3902  /* We are done with authentication exchange */
3904 
3905  /*
3906  * Set asyncStatus so that PQgetResult will think that
3907  * what comes back next is the result of a query. See
3908  * below.
3909  */
3911  }
3912 
3913  /* Look to see if we have more data yet. */
3914  goto keep_going;
3915  }
3916 
3917  case CONNECTION_AUTH_OK:
3918  {
3919  /*
3920  * Now we expect to hear from the backend. A ReadyForQuery
3921  * message indicates that startup is successful, but we might
3922  * also get an Error message indicating failure. (Notice
3923  * messages indicating nonfatal warnings are also allowed by
3924  * the protocol, as are ParameterStatus and BackendKeyData
3925  * messages.) Easiest way to handle this is to let
3926  * PQgetResult() read the messages. We just have to fake it
3927  * out about the state of the connection, by setting
3928  * asyncStatus = PGASYNC_BUSY (done above).
3929  */
3930 
3931  if (PQisBusy(conn))
3932  return PGRES_POLLING_READING;
3933 
3934  res = PQgetResult(conn);
3935 
3936  /*
3937  * NULL return indicating we have gone to IDLE state is
3938  * expected
3939  */
3940  if (res)
3941  {
3943  libpq_append_conn_error(conn, "unexpected message from server during startup");
3944  else if (conn->send_appname &&
3945  (conn->appname || conn->fbappname))
3946  {
3947  /*
3948  * If we tried to send application_name, check to see
3949  * if the error is about that --- pre-9.0 servers will
3950  * reject it at this stage of the process. If so,
3951  * close the connection and retry without sending
3952  * application_name. We could possibly get a false
3953  * SQLSTATE match here and retry uselessly, but there
3954  * seems no great harm in that; we'll just get the
3955  * same error again if it's unrelated.
3956  */
3957  const char *sqlstate;
3958 
3960  if (sqlstate &&
3961  strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
3962  {
3963  PQclear(res);
3964  conn->send_appname = false;
3965  need_new_connection = true;
3966  goto keep_going;
3967  }
3968  }
3969 
3970  /*
3971  * if the resultStatus is FATAL, then conn->errorMessage
3972  * already has a copy of the error; needn't copy it back.
3973  * But add a newline if it's not there already, since
3974  * postmaster error messages may not have one.
3975  */
3976  if (conn->errorMessage.len <= 0 ||
3977  conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
3979  PQclear(res);
3980  goto error_return;
3981  }
3982 
3983  /* Almost there now ... */
3985  goto keep_going;
3986  }
3987 
3989  {
3990  /*
3991  * If a read-write, read-only, primary, or standby connection
3992  * is required, see if we have one.
3993  */
3996  {
3997  bool read_only_server;
3998 
3999  /*
4000  * If the server didn't report
4001  * "default_transaction_read_only" or "in_hot_standby" at
4002  * startup, we must determine its state by sending the
4003  * query "SHOW transaction_read_only". This GUC exists in
4004  * all server versions that support 3.0 protocol.
4005  */
4008  {
4009  /*
4010  * We use PQsendQueryContinue so that
4011  * conn->errorMessage does not get cleared. We need
4012  * to preserve any error messages related to previous
4013  * hosts we have tried and failed to connect to.
4014  */
4017  "SHOW transaction_read_only"))
4018  goto error_return;
4019  /* We'll return to this state when we have the answer */
4021  return PGRES_POLLING_READING;
4022  }
4023 
4024  /* OK, we can make the test */
4025  read_only_server =
4028 
4030  read_only_server : !read_only_server)
4031  {
4032  /* Wrong server state, reject and try the next host */
4034  libpq_append_conn_error(conn, "session is read-only");
4035  else
4036  libpq_append_conn_error(conn, "session is not read-only");
4037 
4038  /* Close connection politely. */
4041 
4042  /*
4043  * Try next host if any, but we don't want to consider
4044  * additional addresses for this host.
4045  */
4046  conn->try_next_host = true;
4047  goto keep_going;
4048  }
4049  }
4053  {
4054  /*
4055  * If the server didn't report "in_hot_standby" at
4056  * startup, we must determine its state by sending the
4057  * query "SELECT pg_catalog.pg_is_in_recovery()". Servers
4058  * before 9.0 don't have that function, but by the same
4059  * token they don't have any standby mode, so we may just
4060  * assume the result.
4061  */
4062  if (conn->sversion < 90000)
4064 
4066  {
4067  /*
4068  * We use PQsendQueryContinue so that
4069  * conn->errorMessage does not get cleared. We need
4070  * to preserve any error messages related to previous
4071  * hosts we have tried and failed to connect to.
4072  */
4075  "SELECT pg_catalog.pg_is_in_recovery()"))
4076  goto error_return;
4077  /* We'll return to this state when we have the answer */
4079  return PGRES_POLLING_READING;
4080  }
4081 
4082  /* OK, we can make the test */
4086  {
4087  /* Wrong server state, reject and try the next host */
4089  libpq_append_conn_error(conn, "server is in hot standby mode");
4090  else
4091  libpq_append_conn_error(conn, "server is not in hot standby mode");
4092 
4093  /* Close connection politely. */
4096 
4097  /*
4098  * Try next host if any, but we don't want to consider
4099  * additional addresses for this host.
4100  */
4101  conn->try_next_host = true;
4102  goto keep_going;
4103  }
4104  }
4105 
4106  /*
4107  * For non cancel requests we can release the address list
4108  * now. For cancel requests we never actually resolve
4109  * addresses and instead the addrinfo exists for the lifetime
4110  * of the connection.
4111  */
4112  if (!conn->cancelRequest)
4114 
4115  /*
4116  * Contents of conn->errorMessage are no longer interesting
4117  * (and it seems some clients expect it to be empty after a
4118  * successful connection).
4119  */
4121 
4122  /* We are open for business! */
4124  return PGRES_POLLING_OK;
4125  }
4126 
4127  case CONNECTION_CONSUME:
4128  {
4129  /*
4130  * This state just makes sure the connection is idle after
4131  * we've obtained the result of a SHOW or SELECT query. Once
4132  * we're clear, return to CONNECTION_CHECK_TARGET state to
4133  * decide what to do next. We must transiently set status =
4134  * CONNECTION_OK in order to use the result-consuming
4135  * subroutines.
4136  */
4138  if (!PQconsumeInput(conn))
4139  goto error_return;
4140 
4141  if (PQisBusy(conn))
4142  {
4144  return PGRES_POLLING_READING;
4145  }
4146 
4147  /* Call PQgetResult() again until we get a NULL result */
4148  res = PQgetResult(conn);
4149  if (res != NULL)
4150  {
4151  PQclear(res);
4153  return PGRES_POLLING_READING;
4154  }
4155 
4157  goto keep_going;
4158  }
4159 
4161  {
4162  /*
4163  * Waiting for result of "SHOW transaction_read_only". We
4164  * must transiently set status = CONNECTION_OK in order to use
4165  * the result-consuming subroutines.
4166  */
4168  if (!PQconsumeInput(conn))
4169  goto error_return;
4170 
4171  if (PQisBusy(conn))
4172  {
4174  return PGRES_POLLING_READING;
4175  }
4176 
4177  res = PQgetResult(conn);
4178  if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
4179  PQntuples(res) == 1)
4180  {
4181  char *val = PQgetvalue(res, 0, 0);
4182 
4183  /*
4184  * "transaction_read_only = on" proves that at least one
4185  * of default_transaction_read_only and in_hot_standby is
4186  * on, but we don't actually know which. We don't care
4187  * though for the purpose of identifying a read-only
4188  * session, so satisfy the CONNECTION_CHECK_TARGET code by
4189  * claiming they are both on. On the other hand, if it's
4190  * a read-write session, they are certainly both off.
4191  */
4192  if (strncmp(val, "on", 2) == 0)
4193  {
4196  }
4197  else
4198  {
4201  }
4202  PQclear(res);
4203 
4204  /* Finish reading messages before continuing */
4206  goto keep_going;
4207  }
4208 
4209  /* Something went wrong with "SHOW transaction_read_only". */
4210  PQclear(res);
4211 
4212  /* Append error report to conn->errorMessage. */
4213  libpq_append_conn_error(conn, "\"%s\" failed",
4214  "SHOW transaction_read_only");
4215 
4216  /* Close connection politely. */
4219 
4220  /* Try next host. */
4221  conn->try_next_host = true;
4222  goto keep_going;
4223  }
4224 
4226  {
4227  /*
4228  * Waiting for result of "SELECT pg_is_in_recovery()". We
4229  * must transiently set status = CONNECTION_OK in order to use
4230  * the result-consuming subroutines.
4231  */
4233  if (!PQconsumeInput(conn))
4234  goto error_return;
4235 
4236  if (PQisBusy(conn))
4237  {
4239  return PGRES_POLLING_READING;
4240  }
4241 
4242  res = PQgetResult(conn);
4243  if (res && PQresultStatus(res) == PGRES_TUPLES_OK &&
4244  PQntuples(res) == 1)
4245  {
4246  char *val = PQgetvalue(res, 0, 0);
4247 
4248  if (strncmp(val, "t", 1) == 0)
4250  else
4252  PQclear(res);
4253 
4254  /* Finish reading messages before continuing */
4256  goto keep_going;
4257  }
4258 
4259  /* Something went wrong with "SELECT pg_is_in_recovery()". */
4260  PQclear(res);
4261 
4262  /* Append error report to conn->errorMessage. */
4263  libpq_append_conn_error(conn, "\"%s\" failed",
4264  "SELECT pg_is_in_recovery()");
4265 
4266  /* Close connection politely. */
4269 
4270  /* Try next host. */
4271  conn->try_next_host = true;
4272  goto keep_going;
4273  }
4274 
4275  default:
4277  "invalid connection state %d, probably indicative of memory corruption",
4278  conn->status);
4279  goto error_return;
4280  }
4281 
4282  /* Unreachable */
4283 
4284 error_return:
4285 
4286  /*
4287  * We used to close the socket at this point, but that makes it awkward
4288  * for those above us if they wish to remove this socket from their own
4289  * records (an fd_set for example). We'll just have this socket closed
4290  * when PQfinish is called (which is compulsory even after an error, since
4291  * the connection structure must be freed).
4292  */
4294  return PGRES_POLLING_FAILED;
4295 }
#define STATUS_OK
Definition: c.h:1169
#define MemSet(start, val, len)
Definition: c.h:1020
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:960
char * pg_fe_getusername(uid_t user_id, PQExpBuffer errorMessage)
Definition: fe-auth.c:1168
#define MAX_ERRLEN
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:471
static const PQEnvironmentOption EnvironmentOptions[]
Definition: fe-connect.c:372
#define CONNECTION_FAILED()
static void sendTerminateConn(PGconn *conn)
Definition: fe-connect.c:4808
static int setKeepalivesCount(PGconn *conn)
Definition: fe-connect.c:2256
static int useKeepalives(PGconn *conn)
Definition: fe-connect.c:2169
static int store_conn_addrinfo(PGconn *conn, struct addrinfo *addrlist)
Definition: fe-connect.c:4755
static void connectFailureMessage(PGconn *conn, int errorno)
Definition: fe-connect.c:2149
static void release_conn_addrinfo(PGconn *conn)
Definition: fe-connect.c:4794
#define ERRCODE_APPNAME_UNKNOWN
Definition: fe-connect.c:86
static int setKeepalivesInterval(PGconn *conn)
Definition: fe-connect.c:2221
static int setKeepalivesIdle(PGconn *conn)
Definition: fe-connect.c:2187
bool pqParseIntParam(const char *value, int *result, PGconn *conn, const char *context)
Definition: fe-connect.c:7702
static void pgpassfileWarning(PGconn *conn)
Definition: fe-connect.c:7573
static void emitHostIdentityInfo(PGconn *conn, const char *host_addr)
Definition: fe-connect.c:2093
static int setTCPUserTimeout(PGconn *conn)
Definition: fe-connect.c:2353
static void pqDropServerData(PGconn *conn)
Definition: fe-connect.c:584
static int connectNoDelay(PGconn *conn)
Definition: fe-connect.c:2034
static void getHostaddr(PGconn *conn, char *host_addr, int host_addr_len)
Definition: fe-connect.c:2060
#define ERRCODE_CANNOT_CONNECT_NOW
Definition: fe-connect.c:91
#define ENCRYPTION_NEGOTIATION_FAILED(msg)
static bool init_allowed_encryption_methods(PGconn *conn)
Definition: fe-connect.c:4301
int pqPacketSend(PGconn *conn, char pack_type, const void *buf, size_t buf_len)
Definition: fe-connect.c:4996
int PQsendQueryContinue(PGconn *conn, const char *query)
Definition: fe-exec.c:1422
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3481
int PQconsumeInput(PGconn *conn)
Definition: fe-exec.c:1984
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3876
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:779
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2031
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3466
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2062
bool pg_GSS_have_cred_cache(gss_cred_id_t *cred_out)
int pqFlush(PGconn *conn)
Definition: fe-misc.c:953
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:77
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:216
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:351
int pqGets_append(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:142
int pqGetNegotiateProtocolVersion3(PGconn *conn)
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:882
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:256
#define SOCK_STRERROR
Definition: libpq-int.h:933
#define ENC_GSSAPI
Definition: libpq-int.h:237
#define ENC_SSL
Definition: libpq-int.h:238
@ CHT_UNIX_SOCKET
Definition: libpq-int.h:317
@ CHT_HOST_ADDRESS
Definition: libpq-int.h:316
@ CHT_HOST_NAME
Definition: libpq-int.h:315
@ PG_BOOL_YES
Definition: libpq-int.h:263
@ PG_BOOL_NO
Definition: libpq-int.h:264
@ PG_BOOL_UNKNOWN
Definition: libpq-int.h:262
@ SERVER_TYPE_STANDBY
Definition: libpq-int.h:247
@ SERVER_TYPE_PRIMARY
Definition: libpq-int.h:246
@ SERVER_TYPE_READ_WRITE
Definition: libpq-int.h:244
@ SERVER_TYPE_PREFER_STANDBY_PASS2
Definition: libpq-int.h:249
@ SERVER_TYPE_PREFER_STANDBY
Definition: libpq-int.h:248
@ SERVER_TYPE_READ_ONLY
Definition: libpq-int.h:245
#define MAXPGPATH
uint64 pg_prng_uint64_range(pg_prng_state *state, uint64 rmin, uint64 rmax)
Definition: pg_prng.c:144
static char portstr[16]
Definition: pg_regress.c:117
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:167
#define NEGOTIATE_SSL_CODE
Definition: pqcomm.h:166
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
const char * gai_strerror(int ecode)
int family
Definition: pqcomm.h:38
SockAddr addr
Definition: pqcomm.h:39
MsgType cancelRequestCode
Definition: pqcomm.h:137
uint32 backendPID
Definition: pqcomm.h:138
uint32 cancelAuthCode
Definition: pqcomm.h:139
pg_conn_host_type type
Definition: libpq-int.h:351
SockAddr laddr
Definition: libpq-int.h:475
bool try_next_host
Definition: libpq-int.h:500
AddrInfo * addr
Definition: libpq-int.h:503
uint8 failed_enc_methods
Definition: libpq-int.h:562
char * sslnegotiation
Definition: libpq-int.h:397
bool sigpipe_flag
Definition: libpq-int.h:483
int nconnhost
Definition: libpq-int.h:454
ProtocolVersion pversion
Definition: libpq-int.h:477
bool send_appname
Definition: libpq-int.h:505
PGTransactionStatusType xactStatus
Definition: libpq-int.h:438
bool cancelRequest
Definition: libpq-int.h:419
int inCursor
Definition: libpq-int.h:525
PGTernaryBool in_hot_standby
Definition: libpq-int.h:514
int inEnd
Definition: libpq-int.h:526
char * fbappname
Definition: libpq-int.h:382
uint8 current_enc_method
Definition: libpq-int.h:563
int naddr
Definition: libpq-int.h:501
int inStart
Definition: libpq-int.h:524
char * connip
Definition: libpq-int.h:457
int sversion
Definition: libpq-int.h:478
bool auth_req_received
Definition: libpq-int.h:479
PGTernaryBool default_transaction_read_only
Definition: libpq-int.h:513
bool sigpipe_so
Definition: libpq-int.h:482
int whichaddr
Definition: libpq-int.h:502
char * appname
Definition: libpq-int.h:381
pg_prng_state prng_state
Definition: libpq-int.h:518
char * gssencmode
Definition: libpq-int.h:408
char last_sqlstate[6]
Definition: libpq-int.h:439
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:437
PGLoadBalanceType load_balance_type
Definition: libpq-int.h:497
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:443
uint8 allowed_enc_methods
Definition: libpq-int.h:561
PGTargetServerType target_server_type
Definition: libpq-int.h:496
bool try_next_addr
Definition: libpq-int.h:499
char * requirepeer
Definition: libpq-int.h:407
bool ssl_in_use
Definition: libpq-int.h:566
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, pg_conn::allowed_enc_methods, appendPQExpBufferChar(), pg_conn::appname, Assert, pg_conn::asyncStatus, AUTH_REQ_OK, pg_conn::auth_req_received, CancelRequestPacket::backendPID, pg_conn::be_key, pg_conn::be_pid, CANCEL_REQUEST_CODE, CancelRequestPacket::cancelAuthCode, pg_conn::cancelRequest, CancelRequestPacket::cancelRequestCode, 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_FAILED, CONNECTION_GSS_STARTUP, CONNECTION_MADE, CONNECTION_NEEDED, CONNECTION_OK, CONNECTION_SSL_STARTUP, CONNECTION_STARTED, connectNoDelay(), pg_conn::connhost, pg_conn::connip, pg_conn::current_enc_method, PQExpBufferData::data, pg_conn::default_transaction_read_only, EINPROGRESS, EINTR, emitHostIdentityInfo(), ENC_GSSAPI, ENC_SSL, ENCRYPTION_NEGOTIATION_FAILED, EnvironmentOptions, err(), ERRCODE_APPNAME_UNKNOWN, ERRCODE_CANNOT_CONNECT_NOW, pg_conn::errorMessage, EWOULDBLOCK, pg_conn::failed_enc_methods, AddrInfo::family, pg_conn::fbappname, free, gai_strerror(), 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, init_allowed_encryption_methods(), 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, 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, portstr, 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(), pqParseIntParam(), 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::sslnegotiation, 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 libpqrcv_connect(), libpqsrv_connect_internal(), PQcancelPoll(), pqConnectDBComplete(), pqConnectDBStart(), PQresetPoll(), and wait_until_connected().

◆ PQconnectStart()

PGconn* PQconnectStart ( const char *  conninfo)

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

873 {
874  PGconn *conn;
875 
876  /*
877  * Allocate memory for the conn structure. Note that we also expect this
878  * to initialize conn->errorMessage to empty. All subsequent steps during
879  * connection initialization will only append to that buffer.
880  */
882  if (conn == NULL)
883  return NULL;
884 
885  /*
886  * Parse the conninfo string
887  */
888  if (!connectOptions1(conn, conninfo))
889  return conn;
890 
891  /*
892  * Compute derived options
893  */
894  if (!pqConnectOptions2(conn))
895  return conn;
896 
897  /*
898  * Connect to the database
899  */
900  if (!pqConnectDBStart(conn))
901  {
902  /* Just in case we failed to set it in pqConnectDBStart */
904  }
905 
906  return conn;
907 }
static bool connectOptions1(PGconn *conn, const char *conninfo)
Definition: fe-connect.c:997

References conn, CONNECTION_BAD, connectOptions1(), pqConnectDBStart(), pqConnectOptions2(), pqMakeEmptyPGconn(), 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 791 of file fe-connect.c.

794 {
795  PGconn *conn;
796  PQconninfoOption *connOptions;
797 
798  /*
799  * Allocate memory for the conn structure. Note that we also expect this
800  * to initialize conn->errorMessage to empty. All subsequent steps during
801  * connection initialization will only append to that buffer.
802  */
804  if (conn == NULL)
805  return NULL;
806 
807  /*
808  * Parse the conninfo arrays
809  */
810  connOptions = conninfo_array_parse(keywords, values,
811  &conn->errorMessage,
812  true, expand_dbname);
813  if (connOptions == NULL)
814  {
816  /* errorMessage is already set */
817  return conn;
818  }
819 
820  /*
821  * Move option values into conn structure
822  */
823  if (!fillPGconn(conn, connOptions))
824  {
825  PQconninfoFree(connOptions);
826  return conn;
827  }
828 
829  /*
830  * Free the option info - all is in conn now
831  */
832  PQconninfoFree(connOptions);
833 
834  /*
835  * Compute derived options
836  */
837  if (!pqConnectOptions2(conn))
838  return conn;
839 
840  /*
841  * Connect to the database
842  */
843  if (!pqConnectDBStart(conn))
844  {
845  /* Just in case we failed to set it in pqConnectDBStart */
847  }
848 
849  return conn;
850 }
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:6039
static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
Definition: fe-connect.c:918

References conn, CONNECTION_BAD, conninfo_array_parse(), pg_conn::errorMessage, fillPGconn(), pqConnectDBStart(), pqConnectOptions2(), PQconninfoFree(), pqMakeEmptyPGconn(), pg_conn::status, and values.

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

◆ PQconninfo()

PQconninfoOption* PQconninfo ( PGconn conn)

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

6957 {
6958  PQExpBufferData errorBuf;
6959  PQconninfoOption *connOptions;
6960 
6961  if (conn == NULL)
6962  return NULL;
6963 
6964  /*
6965  * We don't actually report any errors here, but callees want a buffer,
6966  * and we prefer not to trash the conn's errorMessage.
6967  */
6968  initPQExpBuffer(&errorBuf);
6969  if (PQExpBufferDataBroken(errorBuf))
6970  return NULL; /* out of memory already :-( */
6971 
6972  connOptions = conninfo_init(&errorBuf);
6973 
6974  if (connOptions != NULL)
6975  {
6977 
6978  for (option = PQconninfoOptions; option->keyword; option++)
6979  {
6980  char **connmember;
6981 
6982  if (option->connofs < 0)
6983  continue;
6984 
6985  connmember = (char **) ((char *) conn + option->connofs);
6986 
6987  if (*connmember)
6988  conninfo_storeval(connOptions, option->keyword, *connmember,
6989  &errorBuf, true, false);
6990  }
6991  }
6992 
6993  termPQExpBuffer(&errorBuf);
6994 
6995  return connOptions;
6996 }
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
Definition: fe-connect.c:6874
static const internalPQconninfoOption PQconninfoOptions[]
Definition: fe-connect.c:190

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

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

◆ PQconninfoFree()

◆ PQconninfoParse()

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

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

5749 {
5750  PQExpBufferData errorBuf;
5751  PQconninfoOption *connOptions;
5752 
5753  if (errmsg)
5754  *errmsg = NULL; /* default */
5755  initPQExpBuffer(&errorBuf);
5756  if (PQExpBufferDataBroken(errorBuf))
5757  return NULL; /* out of memory already :-( */
5758  connOptions = parse_connection_string(conninfo, &errorBuf, false);
5759  if (connOptions == NULL && errmsg)
5760  *errmsg = errorBuf.data;
5761  else
5762  termPQExpBuffer(&errorBuf);
5763  return connOptions;
5764 }
int errmsg(const char *fmt,...)
Definition: elog.c:1070
static PQconninfoOption * parse_connection_string(const char *connstr, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:5809