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

Go to the source code of this file.

Data Structures

struct  pgNotify
 
struct  _PQprintOpt
 
struct  _PQconninfoOption
 
struct  PQArgBlock
 
struct  pgresAttDesc
 

Macros

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

Typedefs

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

Enumerations

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

Functions

PGconnPQconnectStart (const char *conninfo)
 
PGconnPQconnectStartParams (const char *const *keywords, const char *const *values, int expand_dbname)
 
PostgresPollingStatusType PQconnectPoll (PGconn *conn)
 
PGconnPQconnectdb (const char *conninfo)
 
PGconnPQconnectdbParams (const char *const *keywords, const char *const *values, int expand_dbname)
 
PGconnPQsetdbLogin (const char *pghost, const char *pgport, const char *pgoptions, const char *pgtty, const char *dbName, const char *login, const char *pwd)
 
void PQfinish (PGconn *conn)
 
PQconninfoOptionPQconndefaults (void)
 
PQconninfoOptionPQconninfoParse (const char *conninfo, char **errmsg)
 
PQconninfoOptionPQconninfo (PGconn *conn)
 
void PQconninfoFree (PQconninfoOption *connOptions)
 
int PQresetStart (PGconn *conn)
 
PostgresPollingStatusType PQresetPoll (PGconn *conn)
 
void PQreset (PGconn *conn)
 
PGcancelPQgetCancel (PGconn *conn)
 
void PQfreeCancel (PGcancel *cancel)
 
int PQcancel (PGcancel *cancel, char *errbuf, int errbufsize)
 
int PQrequestCancel (PGconn *conn)
 
char * PQdb (const PGconn *conn)
 
char * PQuser (const PGconn *conn)
 
char * PQpass (const PGconn *conn)
 
char * PQhost (const PGconn *conn)
 
char * PQhostaddr (const PGconn *conn)
 
char * PQport (const PGconn *conn)
 
char * PQtty (const PGconn *conn)
 
char * PQoptions (const PGconn *conn)
 
ConnStatusType PQstatus (const PGconn *conn)
 
PGTransactionStatusType PQtransactionStatus (const PGconn *conn)
 
const char * PQparameterStatus (const PGconn *conn, const char *paramName)
 
int PQprotocolVersion (const PGconn *conn)
 
int PQserverVersion (const PGconn *conn)
 
char * PQerrorMessage (const PGconn *conn)
 
int PQsocket (const PGconn *conn)
 
int PQbackendPID (const PGconn *conn)
 
PGpipelineStatus PQpipelineStatus (const PGconn *conn)
 
int PQconnectionNeedsPassword (const PGconn *conn)
 
int PQconnectionUsedPassword (const PGconn *conn)
 
int PQconnectionUsedGSSAPI (const PGconn *conn)
 
int PQclientEncoding (const PGconn *conn)
 
int PQsetClientEncoding (PGconn *conn, const char *encoding)
 
int PQsslInUse (PGconn *conn)
 
void * PQsslStruct (PGconn *conn, const char *struct_name)
 
const char * PQsslAttribute (PGconn *conn, const char *attribute_name)
 
const char *const * PQsslAttributeNames (PGconn *conn)
 
void * PQgetssl (PGconn *conn)
 
void PQinitSSL (int do_init)
 
void PQinitOpenSSL (int do_ssl, int do_crypto)
 
int PQgssEncInUse (PGconn *conn)
 
void * PQgetgssctx (PGconn *conn)
 
PGVerbosity PQsetErrorVerbosity (PGconn *conn, PGVerbosity verbosity)
 
PGContextVisibility PQsetErrorContextVisibility (PGconn *conn, PGContextVisibility show_context)
 
PQnoticeReceiver PQsetNoticeReceiver (PGconn *conn, PQnoticeReceiver proc, void *arg)
 
PQnoticeProcessor PQsetNoticeProcessor (PGconn *conn, PQnoticeProcessor proc, void *arg)
 
pgthreadlock_t PQregisterThreadLock (pgthreadlock_t newhandler)
 
void PQtrace (PGconn *conn, FILE *debug_port)
 
void PQuntrace (PGconn *conn)
 
void PQsetTraceFlags (PGconn *conn, int flags)
 
PGresultPQexec (PGconn *conn, const char *query)
 
PGresultPQexecParams (PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
PGresultPQprepare (PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
 
PGresultPQexecPrepared (PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
int PQsendQuery (PGconn *conn, const char *query)
 
int PQsendQueryParams (PGconn *conn, const char *command, int nParams, const Oid *paramTypes, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
int PQsendPrepare (PGconn *conn, const char *stmtName, const char *query, int nParams, const Oid *paramTypes)
 
int PQsendQueryPrepared (PGconn *conn, const char *stmtName, int nParams, const char *const *paramValues, const int *paramLengths, const int *paramFormats, int resultFormat)
 
int PQsetSingleRowMode (PGconn *conn)
 
PGresultPQgetResult (PGconn *conn)
 
int PQisBusy (PGconn *conn)
 
int PQconsumeInput (PGconn *conn)
 
int PQenterPipelineMode (PGconn *conn)
 
int PQexitPipelineMode (PGconn *conn)
 
int PQpipelineSync (PGconn *conn)
 
int PQsendFlushRequest (PGconn *conn)
 
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 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 36 of file libpq-fe.h.

◆ LIBPQ_HAS_SSL_LIBRARY_DETECTION

#define LIBPQ_HAS_SSL_LIBRARY_DETECTION   1

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

◆ LIBPQ_HAS_TRACE_FLAGS

#define LIBPQ_HAS_TRACE_FLAGS   1

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

◆ PG_COPYRES_ATTRS

#define PG_COPYRES_ATTRS   0x01

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

◆ PG_COPYRES_EVENTS

#define PG_COPYRES_EVENTS   0x04

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

◆ PG_COPYRES_NOTICEHOOKS

#define PG_COPYRES_NOTICEHOOKS   0x08

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

◆ PG_COPYRES_TUPLES

#define PG_COPYRES_TUPLES   0x02 /* Implies PG_COPYRES_ATTRS */

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

◆ PQ_QUERY_PARAM_MAX_LIMIT

#define PQ_QUERY_PARAM_MAX_LIMIT   65535

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

◆ PQfreeNotify

#define PQfreeNotify (   ptr)    PQfreemem(ptr)

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

◆ PQnoPasswordSupplied

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

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

◆ PQsetdb

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

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

◆ PQTRACE_REGRESS_MODE

#define PQTRACE_REGRESS_MODE   (1<<1)

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

◆ PQTRACE_SUPPRESS_TIMESTAMPS

#define PQTRACE_SUPPRESS_TIMESTAMPS   (1<<0)

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

Typedef Documentation

◆ PGcancel

typedef struct pg_cancel PGcancel

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

◆ PGconn

typedef struct pg_conn PGconn

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

◆ PGnotify

typedef struct pgNotify PGnotify

◆ PGresAttDesc

typedef struct pgresAttDesc PGresAttDesc

◆ PGresult

typedef struct pg_result PGresult

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

◆ pgthreadlock_t

typedef void(* pgthreadlock_t) (int acquire)

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

◆ pqbool

typedef char pqbool

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

◆ PQconninfoOption

◆ PQnoticeProcessor

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

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

◆ PQnoticeReceiver

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

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

◆ PQprintOpt

typedef struct _PQprintOpt PQprintOpt

◆ PQsslKeyPassHook_OpenSSL_type

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

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

Enumeration Type Documentation

◆ ConnStatusType

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

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

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

◆ ExecStatusType

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

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

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

◆ PGContextVisibility

Enumerator
PQSHOW_CONTEXT_NEVER 
PQSHOW_CONTEXT_ERRORS 
PQSHOW_CONTEXT_ALWAYS 

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

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

◆ PGPing

enum PGPing
Enumerator
PQPING_OK 
PQPING_REJECT 
PQPING_NO_RESPONSE 
PQPING_NO_ATTEMPT 

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

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

◆ PGpipelineStatus

Enumerator
PQ_PIPELINE_OFF 
PQ_PIPELINE_ON 
PQ_PIPELINE_ABORTED 

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

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

◆ PGTransactionStatusType

Enumerator
PQTRANS_IDLE 
PQTRANS_ACTIVE 
PQTRANS_INTRANS 
PQTRANS_INERROR 
PQTRANS_UNKNOWN 

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

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

◆ PGVerbosity

Enumerator
PQERRORS_TERSE 
PQERRORS_DEFAULT 
PQERRORS_VERBOSE 
PQERRORS_SQLSTATE 

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

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

◆ PostgresPollingStatusType

Enumerator
PGRES_POLLING_FAILED 
PGRES_POLLING_READING 
PGRES_POLLING_WRITING 
PGRES_POLLING_OK 
PGRES_POLLING_ACTIVE 

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

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

Function Documentation

◆ lo_close()

int lo_close ( PGconn conn,
int  fd 
)

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

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

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

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

◆ lo_creat()

Oid lo_creat ( PGconn conn,
int  mode 
)

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

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

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

Referenced by importFile(), and lo_import_internal().

◆ lo_create()

Oid lo_create ( PGconn conn,
Oid  lobjId 
)

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

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

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

Referenced by lo_import_internal(), and StartRestoreLO().

◆ lo_export()

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

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

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

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

Referenced by overwrite(), and pickout().

◆ lo_lseek64()

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

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

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

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

Referenced by overwrite(), and pickout().

◆ lo_open()

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

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

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

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

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

◆ lo_read()

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

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

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

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

Referenced by lo_export().

◆ lo_tell()

int lo_tell ( PGconn conn,
int  fd 
)

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

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

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

◆ lo_tell64()

pg_int64 lo_tell64 ( PGconn conn,
int  fd 
)

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

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

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

Referenced by pickout().

◆ lo_truncate()

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

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

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

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

◆ lo_truncate64()

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

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

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

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

Referenced by my_truncate().

◆ lo_unlink()

int lo_unlink ( PGconn conn,
Oid  lobjId 
)

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

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

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

Referenced by do_lo_unlink(), and vacuumlo().

◆ lo_write()

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

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

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

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

Referenced by lo_import_internal().

◆ pg_char_to_encoding()

int pg_char_to_encoding ( const char *  name)

Definition at line 550 of file encnames.c.

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

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

Referenced by pg_valid_client_encoding(), and pg_valid_server_encoding().

◆ pg_encoding_to_char()

const char* pg_encoding_to_char ( int  encoding)

Definition at line 588 of file encnames.c.

589 {
591  {
592  const pg_enc2name *p = &pg_enc2name_tbl[encoding];
593 
594  Assert(encoding == p->encoding);
595  return p->name;
596  }
597  return "";
598 }
const pg_enc2name pg_enc2name_tbl[]
Definition: encnames.c:309
Assert(fmt[strlen(fmt) - 1] !='\n')
int32 encoding
Definition: pg_database.h:41
#define PG_VALID_ENCODING(_enc)
Definition: pg_wchar.h:288
pg_enc encoding
Definition: pg_wchar.h:343
const char * name
Definition: pg_wchar.h:342

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

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

References encoding, and PG_VALID_BE_ENCODING.

◆ PQbackendPID()

int PQbackendPID ( const PGconn conn)

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

6876 {
6877  if (!conn || conn->status != CONNECTION_OK)
6878  return 0;
6879  return conn->be_pid;
6880 }
int be_pid
Definition: libpq-int.h:494
ConnStatusType status
Definition: libpq-int.h:425

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

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

◆ PQbinaryTuples()

int PQbinaryTuples ( const PGresult res)

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

3458 {
3459  if (!res)
3460  return 0;
3461  return res->binary;
3462 }
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 148 of file fe-cancel.c.

149 {
150  int save_errno = SOCK_ERRNO;
151  pgsocket tmpsock = PGINVALID_SOCKET;
152  int maxlen;
153  struct
154  {
155  uint32 packetlen;
157  } crp;
158 
159  if (!cancel)
160  {
161  strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
162  /* strlcpy probably doesn't change errno, but be paranoid */
163  SOCK_ERRNO_SET(save_errno);
164  return false;
165  }
166 
167  /*
168  * We need to open a temporary connection to the postmaster. Do this with
169  * only kernel calls.
170  */
171  if ((tmpsock = socket(cancel->raddr.addr.ss_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
172  {
173  strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
174  goto cancel_errReturn;
175  }
176 
177  /*
178  * Since this connection will only be used to send a single packet of
179  * data, we don't need NODELAY. We also don't set the socket to
180  * nonblocking mode, because the API definition of PQcancel requires the
181  * cancel to be sent in a blocking way.
182  *
183  * We do set socket options related to keepalives and other TCP timeouts.
184  * This ensures that this function does not block indefinitely when
185  * reasonable keepalive and timeout settings have been provided.
186  */
187  if (cancel->raddr.addr.ss_family != AF_UNIX &&
188  cancel->keepalives != 0)
189  {
190 #ifndef WIN32
191  if (!optional_setsockopt(tmpsock, SOL_SOCKET, SO_KEEPALIVE, 1))
192  {
193  strlcpy(errbuf, "PQcancel() -- setsockopt(SO_KEEPALIVE) failed: ", errbufsize);
194  goto cancel_errReturn;
195  }
196 
197 #ifdef PG_TCP_KEEPALIVE_IDLE
198  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
199  cancel->keepalives_idle))
200  {
201  strlcpy(errbuf, "PQcancel() -- setsockopt(" PG_TCP_KEEPALIVE_IDLE_STR ") failed: ", errbufsize);
202  goto cancel_errReturn;
203  }
204 #endif
205 
206 #ifdef TCP_KEEPINTVL
207  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_KEEPINTVL,
208  cancel->keepalives_interval))
209  {
210  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_KEEPINTVL) failed: ", errbufsize);
211  goto cancel_errReturn;
212  }
213 #endif
214 
215 #ifdef TCP_KEEPCNT
216  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_KEEPCNT,
217  cancel->keepalives_count))
218  {
219  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_KEEPCNT) failed: ", errbufsize);
220  goto cancel_errReturn;
221  }
222 #endif
223 
224 #else /* WIN32 */
225 
226 #ifdef SIO_KEEPALIVE_VALS
227  if (!pqSetKeepalivesWin32(tmpsock,
228  cancel->keepalives_idle,
229  cancel->keepalives_interval))
230  {
231  strlcpy(errbuf, "PQcancel() -- WSAIoctl(SIO_KEEPALIVE_VALS) failed: ", errbufsize);
232  goto cancel_errReturn;
233  }
234 #endif /* SIO_KEEPALIVE_VALS */
235 #endif /* WIN32 */
236 
237  /* TCP_USER_TIMEOUT works the same way on Unix and Windows */
238 #ifdef TCP_USER_TIMEOUT
239  if (!optional_setsockopt(tmpsock, IPPROTO_TCP, TCP_USER_TIMEOUT,
240  cancel->pgtcp_user_timeout))
241  {
242  strlcpy(errbuf, "PQcancel() -- setsockopt(TCP_USER_TIMEOUT) failed: ", errbufsize);
243  goto cancel_errReturn;
244  }
245 #endif
246  }
247 
248 retry3:
249  if (connect(tmpsock, (struct sockaddr *) &cancel->raddr.addr,
250  cancel->raddr.salen) < 0)
251  {
252  if (SOCK_ERRNO == EINTR)
253  /* Interrupted system call - we'll just try again */
254  goto retry3;
255  strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
256  goto cancel_errReturn;
257  }
258 
259  /* Create and send the cancel request packet. */
260 
261  crp.packetlen = pg_hton32((uint32) sizeof(crp));
262  crp.cp.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE);
263  crp.cp.backendPID = pg_hton32(cancel->be_pid);
264  crp.cp.cancelAuthCode = pg_hton32(cancel->be_key);
265 
266 retry4:
267  if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
268  {
269  if (SOCK_ERRNO == EINTR)
270  /* Interrupted system call - we'll just try again */
271  goto retry4;
272  strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
273  goto cancel_errReturn;
274  }
275 
276  /*
277  * Wait for the postmaster to close the connection, which indicates that
278  * it's processed the request. Without this delay, we might issue another
279  * command only to find that our cancel zaps that command instead of the
280  * one we thought we were canceling. Note we don't actually expect this
281  * read to obtain any data, we are just waiting for EOF to be signaled.
282  */
283 retry5:
284  if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
285  {
286  if (SOCK_ERRNO == EINTR)
287  /* Interrupted system call - we'll just try again */
288  goto retry5;
289  /* we ignore other error conditions */
290  }
291 
292  /* All done */
293  closesocket(tmpsock);
294  SOCK_ERRNO_SET(save_errno);
295  return true;
296 
297 cancel_errReturn:
298 
299  /*
300  * Make sure we don't overflow the error buffer. Leave space for the \n at
301  * the end, and for the terminating zero.
302  */
303  maxlen = errbufsize - strlen(errbuf) - 2;
304  if (maxlen >= 0)
305  {
306  /*
307  * We can't invoke strerror here, since it's not signal-safe. Settle
308  * for printing the decimal value of errno. Even that has to be done
309  * the hard way.
310  */
311  int val = SOCK_ERRNO;
312  char buf[32];
313  char *bufp;
314 
315  bufp = buf + sizeof(buf) - 1;
316  *bufp = '\0';
317  do
318  {
319  *(--bufp) = (val % 10) + '0';
320  val /= 10;
321  } while (val > 0);
322  bufp -= 6;
323  memcpy(bufp, "error ", 6);
324  strncat(errbuf, bufp, maxlen);
325  strcat(errbuf, "\n");
326  }
327  if (tmpsock != PGINVALID_SOCKET)
328  closesocket(tmpsock);
329  SOCK_ERRNO_SET(save_errno);
330  return false;
331 }
unsigned int uint32
Definition: c.h:495
static bool optional_setsockopt(int fd, int protoid, int optid, int value)
Definition: fe-cancel.c:116
long val
Definition: informix.c:664
#define SOCK_ERRNO
Definition: libpq-int.h:933
#define SOCK_ERRNO_SET(e)
Definition: libpq-int.h:935
#define pg_hton32(x)
Definition: pg_bswap.h:121
int pgsocket
Definition: port.h:29
#define PGINVALID_SOCKET
Definition: port.h:31
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define closesocket
Definition: port.h:349
#define CANCEL_REQUEST_CODE
Definition: pqcomm.h:132
ProtocolVersion MsgType
Definition: pqcomm.h:101
struct sockaddr_storage addr
Definition: pqcomm.h:32
socklen_t salen
Definition: pqcomm.h:33
int pgtcp_user_timeout
Definition: libpq-int.h:633
int keepalives_interval
Definition: libpq-int.h:636
int keepalives_idle
Definition: libpq-int.h:635
int keepalives_count
Definition: libpq-int.h:638
SockAddr raddr
Definition: libpq-int.h:630
int be_pid
Definition: libpq-int.h:631
int keepalives
Definition: libpq-int.h:634
int be_key
Definition: libpq-int.h:632
#define EINTR
Definition: win32_port.h:374
#define recv(s, buf, len, flags)
Definition: win32_port.h:496
#define send(s, buf, len, flags)
Definition: win32_port.h:497
#define socket(af, type, protocol)
Definition: win32_port.h:490
#define connect(s, name, namelen)
Definition: win32_port.h:494

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

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

◆ PQchangePassword()

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

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

1403 {
1404  char *encrypted_password = PQencryptPasswordConn(conn, passwd,
1405  user, NULL);
1406 
1407  if (!encrypted_password)
1408  {
1409  /* PQencryptPasswordConn() already registered the error */
1410  return NULL;
1411  }
1412  else
1413  {
1414  char *fmtpw = PQescapeLiteral(conn, encrypted_password,
1415  strlen(encrypted_password));
1416 
1417  /* no longer needed, so clean up now */
1418  PQfreemem(encrypted_password);
1419 
1420  if (!fmtpw)
1421  {
1422  /* PQescapeLiteral() already registered the error */
1423  return NULL;
1424  }
1425  else
1426  {
1427  char *fmtuser = PQescapeIdentifier(conn, user, strlen(user));
1428 
1429  if (!fmtuser)
1430  {
1431  /* PQescapeIdentifier() already registered the error */
1432  PQfreemem(fmtpw);
1433  return NULL;
1434  }
1435  else
1436  {
1438  PGresult *res;
1439 
1440  initPQExpBuffer(&buf);
1441  printfPQExpBuffer(&buf, "ALTER USER %s PASSWORD %s",
1442  fmtuser, fmtpw);
1443 
1444  res = PQexec(conn, buf.data);
1445 
1446  /* clean up */
1447  termPQExpBuffer(&buf);
1448  PQfreemem(fmtuser);
1449  PQfreemem(fmtpw);
1450 
1451  return res;
1452  }
1453  }
1454  }
1455 }
char * PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm)
Definition: fe-auth.c:1277
void PQfreemem(void *ptr)
Definition: fe-exec.c:3992
char * PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4270
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4264
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:2224
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 719 of file fe-exec.c.

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

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

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

◆ PQclientEncoding()

int PQclientEncoding ( const PGconn conn)

◆ PQclosePortal()

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

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

2502 {
2503  if (!PQexecStart(conn))
2504  return NULL;
2505  if (!PQsendTypedCommand(conn, PqMsg_Close, 'P', portal))
2506  return NULL;
2507  return PQexecFinish(conn);
2508 }
static PGresult * PQexecFinish(PGconn *conn)
Definition: fe-exec.c:2372
static int PQsendTypedCommand(PGconn *conn, char command, char type, const char *target)
Definition: fe-exec.c:2551
static bool PQexecStart(PGconn *conn)
Definition: fe-exec.c:2306
#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 2483 of file fe-exec.c.

2484 {
2485  if (!PQexecStart(conn))
2486  return NULL;
2487  if (!PQsendTypedCommand(conn, PqMsg_Close, 'S', stmt))
2488  return NULL;
2489  return PQexecFinish(conn);
2490 }
#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 3712 of file fe-exec.c.

3713 {
3714  if (!res)
3715  return NULL;
3716  return res->cmdStatus;
3717 }
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:181

References pg_result::cmdStatus, and res.

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

◆ PQcmdTuples()

char* PQcmdTuples ( PGresult res)

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

3783 {
3784  char *p,
3785  *c;
3786 
3787  if (!res)
3788  return "";
3789 
3790  if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
3791  {
3792  p = res->cmdStatus + 7;
3793  /* INSERT: skip oid and space */
3794  while (*p && *p != ' ')
3795  p++;
3796  if (*p == 0)
3797  goto interpret_error; /* no space? */
3798  p++;
3799  }
3800  else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
3801  strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
3802  strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
3803  p = res->cmdStatus + 7;
3804  else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0 ||
3805  strncmp(res->cmdStatus, "MERGE ", 6) == 0)
3806  p = res->cmdStatus + 6;
3807  else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
3808  strncmp(res->cmdStatus, "COPY ", 5) == 0)
3809  p = res->cmdStatus + 5;
3810  else
3811  return "";
3812 
3813  /* check that we have an integer (at least one digit, nothing else) */
3814  for (c = p; *c; c++)
3815  {
3816  if (!isdigit((unsigned char) *c))
3817  goto interpret_error;
3818  }
3819  if (c == p)
3820  goto interpret_error;
3821 
3822  return p;
3823 
3824 interpret_error:
3826  "could not interpret result from server: %s",
3827  res->cmdStatus);
3828  return "";
3829 }
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:936
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 1771 of file fe-connect.c.

1772 {
1773  PQExpBufferData errorBuf;
1774  PQconninfoOption *connOptions;
1775 
1776  /* We don't actually report any errors here, but callees want a buffer */
1777  initPQExpBuffer(&errorBuf);
1778  if (PQExpBufferDataBroken(errorBuf))
1779  return NULL; /* out of memory already :-( */
1780 
1781  connOptions = conninfo_init(&errorBuf);
1782  if (connOptions != NULL)
1783  {
1784  /* pass NULL errorBuf to ignore errors */
1785  if (!conninfo_add_defaults(connOptions, NULL))
1786  {
1787  PQconninfoFree(connOptions);
1788  connOptions = NULL;
1789  }
1790  }
1791 
1792  termPQExpBuffer(&errorBuf);
1793  return connOptions;
1794 }
static PQconninfoOption * conninfo_init(PQExpBuffer errorMessage)
Definition: fe-connect.c:5444
static bool conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
Definition: fe-connect.c:5871
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:6674
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67

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

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

◆ PQconnectdb()

PGconn* PQconnectdb ( const char *  conninfo)

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

725 {
726  PGconn *conn = PQconnectStart(conninfo);
727 
728  if (conn && conn->status != CONNECTION_BAD)
729  (void) pqConnectDBComplete(conn);
730 
731  return conn;
732 }
PGconn * PQconnectStart(const char *conninfo)
Definition: fe-connect.c:852
int pqConnectDBComplete(PGconn *conn)
Definition: fe-connect.c:2352

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

Referenced by get_db_conn(), and main().

◆ PQconnectdbParams()

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

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

672 {
673  PGconn *conn = PQconnectStartParams(keywords, values, expand_dbname);
674 
675  if (conn && conn->status != CONNECTION_BAD)
676  (void) pqConnectDBComplete(conn);
677 
678  return conn;
679 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
PGconn * PQconnectStartParams(const char *const *keywords, const char *const *values, int expand_dbname)
Definition: fe-connect.c:771

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

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

◆ PQconnectionNeedsPassword()

int PQconnectionNeedsPassword ( const PGconn conn)

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

6893 {
6894  char *password;
6895 
6896  if (!conn)
6897  return false;
6898  password = PQpass(conn);
6899  if (conn->password_needed &&
6900  (password == NULL || password[0] == '\0'))
6901  return true;
6902  else
6903  return false;
6904 }
char * PQpass(const PGconn *conn)
Definition: fe-connect.c:6703
static char * password
Definition: streamutil.c:53
bool password_needed
Definition: libpq-int.h:466

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

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

◆ PQconnectionUsedGSSAPI()

int PQconnectionUsedGSSAPI ( const PGconn conn)

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

6919 {
6920  if (!conn)
6921  return false;
6922  if (conn->gssapi_used)
6923  return true;
6924  else
6925  return false;
6926 }
bool gssapi_used
Definition: libpq-int.h:467

References conn, and pg_conn::gssapi_used.

Referenced by dblink_security_check(), and pgfdw_security_check().

◆ PQconnectionUsedPassword()

int PQconnectionUsedPassword ( const PGconn conn)

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

6908 {
6909  if (!conn)
6910  return false;
6911  if (conn->password_needed)
6912  return true;
6913  else
6914  return false;
6915 }

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

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

References AddrInfo::addr, SockAddr::addr, pg_conn::addr, appendPQExpBufferChar(), pg_conn::appname, Assert(), pg_conn::asyncStatus, AUTH_REQ_OK, pg_conn::auth_req_received, CHT_HOST_ADDRESS, CHT_HOST_NAME, CHT_UNIX_SOCKET, conn, connect, connectFailureMessage(), CONNECTION_AUTH_OK, CONNECTION_AWAITING_RESPONSE, CONNECTION_BAD, CONNECTION_CHECK_STANDBY, CONNECTION_CHECK_TARGET, CONNECTION_CHECK_WRITABLE, CONNECTION_CONSUME, CONNECTION_GSS_STARTUP, CONNECTION_MADE, CONNECTION_NEEDED, CONNECTION_OK, CONNECTION_SSL_STARTUP, CONNECTION_STARTED, connectNoDelay(), pg_conn::connhost, pg_conn::connip, PQExpBufferData::data, pg_conn::default_transaction_read_only, EINPROGRESS, EINTR, emitHostIdentityInfo(), EnvironmentOptions, err(), ERRCODE_APPNAME_UNKNOWN, ERRCODE_CANNOT_CONNECT_NOW, pg_conn::errorMessage, EWOULDBLOCK, AddrInfo::family, pg_conn::fbappname, free, 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, 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::sslmode, pg_conn::status, STATUS_OK, store_conn_addrinfo(), strerror_r, pg_conn::sversion, pg_conn::target_server_type, pg_conn::try_next_addr, pg_conn::try_next_host, pg_conn_host::type, UNIXSOCK_PATH, UNIXSOCK_PATH_BUFLEN, useKeepalives(), val, pg_conn::whichaddr, pg_conn::whichhost, and pg_conn::xactStatus.

Referenced by libpqrcv_connect(), libpqsrv_connect_internal(), pqConnectDBComplete(), pqConnectDBStart(), and PQresetPoll().

◆ PQconnectStart()

PGconn* PQconnectStart ( const char *  conninfo)

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

853 {
854  PGconn *conn;
855 
856  /*
857  * Allocate memory for the conn structure. Note that we also expect this
858  * to initialize conn->errorMessage to empty. All subsequent steps during
859  * connection initialization will only append to that buffer.
860  */
862  if (conn == NULL)
863  return NULL;
864 
865  /*
866  * Parse the conninfo string
867  */
868  if (!connectOptions1(conn, conninfo))
869  return conn;
870 
871  /*
872  * Compute derived options
873  */
874  if (!pqConnectOptions2(conn))
875  return conn;
876 
877  /*
878  * Connect to the database
879  */
880  if (!pqConnectDBStart(conn))
881  {
882  /* Just in case we failed to set it in pqConnectDBStart */
884  }
885 
886  return conn;
887 }
static bool connectOptions1(PGconn *conn, const char *conninfo)
Definition: fe-connect.c:938
bool pqConnectOptions2(PGconn *conn)
Definition: fe-connect.c:1061
PGconn * pqMakeEmptyPGconn(void)
Definition: fe-connect.c:4235
int pqConnectDBStart(PGconn *conn)
Definition: fe-connect.c:2282

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

774 {
775  PGconn *conn;
776  PQconninfoOption *connOptions;
777 
778  /*
779  * Allocate memory for the conn structure. Note that we also expect this
780  * to initialize conn->errorMessage to empty. All subsequent steps during
781  * connection initialization will only append to that buffer.
782  */
784  if (conn == NULL)
785  return NULL;
786 
787  /*
788  * Parse the conninfo arrays
789  */
790  connOptions = conninfo_array_parse(keywords, values,
791  &conn->errorMessage,
792  true, expand_dbname);
793  if (connOptions == NULL)
794  {
796  /* errorMessage is already set */
797  return conn;
798  }
799 
800  /*
801  * Move option values into conn structure
802  */
803  if (!fillPGconn(conn, connOptions))
804  {
805  PQconninfoFree(connOptions);
806  return conn;
807  }
808 
809  /*
810  * Free the option info - all is in conn now
811  */
812  PQconninfoFree(connOptions);
813 
814  /*
815  * Compute derived options
816  */
817  if (!pqConnectOptions2(conn))
818  return conn;
819 
820  /*
821  * Connect to the database
822  */
823  if (!pqConnectDBStart(conn))
824  {
825  /* Just in case we failed to set it in pqConnectDBStart */
827  }
828 
829  return conn;
830 }
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:5713
static bool fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
Definition: fe-connect.c:898

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

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

◆ PQconninfo()

PQconninfoOption* PQconninfo ( PGconn conn)

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

6631 {
6632  PQExpBufferData errorBuf;
6633  PQconninfoOption *connOptions;
6634 
6635  if (conn == NULL)
6636  return NULL;
6637 
6638  /*
6639  * We don't actually report any errors here, but callees want a buffer,
6640  * and we prefer not to trash the conn's errorMessage.
6641  */
6642  initPQExpBuffer(&errorBuf);
6643  if (PQExpBufferDataBroken(errorBuf))
6644  return NULL; /* out of memory already :-( */
6645 
6646  connOptions = conninfo_init(&errorBuf);
6647 
6648  if (connOptions != NULL)
6649  {
6651 
6652  for (option = PQconninfoOptions; option->keyword; option++)
6653  {
6654  char **connmember;
6655 
6656  if (option->connofs < 0)
6657  continue;
6658 
6659  connmember = (char **) ((char *) conn + option->connofs);
6660 
6661  if (*connmember)
6662  conninfo_storeval(connOptions, option->keyword, *connmember,
6663  &errorBuf, true, false);
6664  }
6665  }
6666 
6667  termPQExpBuffer(&errorBuf);
6668 
6669  return connOptions;
6670 }
static PQconninfoOption * conninfo_storeval(PQconninfoOption *connOptions, const char *keyword, const char *value, PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode)
Definition: fe-connect.c:6548
static const internalPQconninfoOption PQconninfoOptions[]
Definition: fe-connect.c:189

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

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

◆ PQconninfoFree()

void PQconninfoFree ( PQconninfoOption connOptions)

◆ PQconninfoParse()

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

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

5423 {
5424  PQExpBufferData errorBuf;
5425  PQconninfoOption *connOptions;
5426 
5427  if (errmsg)
5428  *errmsg = NULL; /* default */
5429  initPQExpBuffer(&errorBuf);
5430  if (PQExpBufferDataBroken(errorBuf))
5431  return NULL; /* out of memory already :-( */
5432  connOptions = parse_connection_string(conninfo, &errorBuf, false);
5433  if (connOptions == NULL && errmsg)
5434  *errmsg = errorBuf.data;
5435  else
5436  termPQExpBuffer(&errorBuf);
5437  return connOptions;
5438 }
int errmsg(const char *fmt,...)
Definition: elog.c:1075
static PQconninfoOption * parse_connection_string(const char *connstr, PQExpBuffer errorMessage, bool use_defaults)
Definition: fe-connect.c:5483

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

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

◆ PQconsumeInput()

int PQconsumeInput ( PGconn conn)

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

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

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

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

◆ PQcopyResult()

PGresult* PQcopyResult ( const PGresult src,
int  flags 
)

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

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

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

Referenced by pqRowProcessor().

◆ PQdb()

◆ PQdefaultSSLKeyPassHook_OpenSSL()

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

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

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

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

Referenced by PQssl_passwd_cb().

◆ PQdescribePortal()

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

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

2437 {
2438  if (!PQexecStart(conn))
2439  return NULL;
2440  if (!PQsendTypedCommand(conn, PqMsg_Describe, 'P', portal))
2441  return NULL;
2442  return PQexecFinish(conn);
2443 }
#define PqMsg_Describe
Definition: protocol.h:21

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

Referenced by test_prepared().

◆ PQdescribePrepared()

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

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

2418 {
2419  if (!PQexecStart(conn))
2420  return NULL;
2422  return NULL;
2423  return PQexecFinish(conn);
2424 }

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

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

◆ PQdisplayTuples()

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

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

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

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

◆ PQdsplen()

int PQdsplen ( const char *  s,
int  encoding 
)

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

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

References encoding, and pg_encoding_dsplen().

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

◆ PQencryptPassword()

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