1 /*-------------------------------------------------------------------------
4 * This file contains internal definitions meant to be used only by
5 * the frontend libpq library, not by applications that call it.
7 * An application can include this file if it wants to bypass the
8 * official API defined by libpq-fe.h, but code that does so is much
9 * more likely to break across PostgreSQL releases than code that uses
10 * only the official API.
12 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
15 * src/interfaces/libpq/libpq-int.h
17 *-------------------------------------------------------------------------
23 /* We assume libpq-fe.h has already been included. */
24 #include "libpq-events.h"
27 #include <sys/socket.h>
29 /* MinGW has sys/time.h, but MSVC doesn't */
35 #include "pthread-win32.h"
41 /* include stuff common to fe and be */
42 #include "libpq/pqcomm.h"
43 /* include stuff found in fe only */
44 #include "fe-auth-sasl.h"
45 #include "pqexpbuffer.h"
47 /* IWYU pragma: begin_exports */
49 #if defined(HAVE_GSSAPI_H)
52 #include <gssapi/gssapi.h>
55 /* IWYU pragma: end_exports */
58 #define SECURITY_WIN32
59 #if defined(WIN32) && !defined(_MSC_VER)
67 * Define a fake structure compatible with GSSAPI on Unix.
75 #endif /* ENABLE_SSPI */
78 #include <openssl/ssl.h>
79 #include <openssl/err.h>
81 #ifndef OPENSSL_NO_ENGINE
82 #define USE_SSL_ENGINE
84 #endif /* USE_OPENSSL */
86 #include "common/pg_prng.h"
89 * POSTGRES backend dependent Constants.
91 #define CMDSTATUS_LEN 64 /* should match COMPLETION_TAG_BUFSIZE */
94 * PGresult and the subsidiary types PGresAttDesc, PGresAttValue
95 * represent the result of a query (or more precisely, of a single SQL
96 * command --- a query string given to PQexec can contain multiple commands).
97 * Note we assume that a single command can return at most one tuple group,
98 * hence there is no need for multiple descriptor sets.
101 /* Subsidiary-storage management structure for PGresult.
102 * See space management routines in fe-exec.c for details.
103 * Note that space[k] refers to the k'th byte starting from the physical
104 * head of the block --- it's a union, not a struct!
106 typedef union pgresult_data PGresult_data
;
110 PGresult_data
*next
; /* link to next block, or NULL */
111 char space
[1]; /* dummy for accessing block as bytes */
114 /* Data about a single parameter of a prepared statement */
115 typedef struct pgresParamDesc
117 Oid typid
; /* type id */
121 * Data for a single attribute of a single tuple
123 * We use char* for Attribute values.
125 * The value pointer always points to a null-terminated area; we add a
126 * null (zero) byte after whatever the backend sends us. This is only
127 * particularly useful for text values ... with a binary value, the
128 * value might have embedded nulls, so the application can't use C string
129 * operators on it. But we add a null anyway for consistency.
130 * Note that the value itself does not contain a length word.
132 * A NULL attribute is a special case in two ways: its len field is NULL_LEN
133 * and its value field points to null_field in the owning PGresult. All the
134 * NULL attributes in a query result point to the same place (there's no need
135 * to store a null string separately for each one).
138 #define NULL_LEN (-1) /* pg_result len for NULL value */
140 typedef struct pgresAttValue
142 int len
; /* length in bytes of the value */
143 char *value
; /* actual value, plus terminating zero byte */
146 /* Typedef for message-field list entries */
147 typedef struct pgMessageField
149 struct pgMessageField
*next
; /* list link */
150 char code
; /* field code */
151 char contents
[FLEXIBLE_ARRAY_MEMBER
]; /* value, nul-terminated */
154 /* Fields needed for notice handling */
157 PQnoticeReceiver noticeRec
; /* notice message receiver */
159 PQnoticeProcessor noticeProc
; /* notice message processor */
163 typedef struct PGEvent
165 PGEventProc proc
; /* the function to call on events */
166 char *name
; /* used only for error messages */
167 void *passThrough
; /* pointer supplied at registration time */
168 void *data
; /* optional state (instance) data */
169 bool resultInitialized
; /* T if RESULTCREATE/COPY succeeded */
176 PGresAttDesc
*attDescs
;
177 PGresAttValue
**tuples
; /* each PGresult tuple is an array of
179 int tupArrSize
; /* allocated size of tuples array */
181 PGresParamDesc
*paramDescs
;
182 ExecStatusType resultStatus
;
183 char cmdStatus
[CMDSTATUS_LEN
]; /* cmd status from the query */
184 int binary
; /* binary tuple values if binary == 1,
188 * These fields are copied from the originating PGconn, so that operations
189 * on the PGresult don't have to reference the PGconn.
191 PGNoticeHooks noticeHooks
;
194 int client_encoding
; /* encoding id */
197 * Error information (all NULL if not an error result). errMsg is the
198 * "overall" error message returned by PQresultErrorMessage. If we have
199 * per-field info then it is stored in a linked list.
201 char *errMsg
; /* error message, or NULL if no error */
202 PGMessageField
*errFields
; /* message broken into fields */
203 char *errQuery
; /* text of triggering query, if available */
205 /* All NULL attributes in the query result point to this null string */
209 * Space management information. Note that attDescs and error stuff, if
210 * not null, point into allocated blocks. But tuples points to a
211 * separately malloc'd block, so that we can realloc it.
213 PGresult_data
*curBlock
; /* most recently allocated block */
214 int curOffset
; /* start offset of free space in block */
215 int spaceLeft
; /* number of free bytes remaining in block */
217 size_t memorySize
; /* total space allocated for this PGresult */
220 /* PGAsyncStatusType defines the state of the query-execution state machine */
223 PGASYNC_IDLE
, /* nothing's happening, dude */
224 PGASYNC_BUSY
, /* query in progress */
225 PGASYNC_READY
, /* query done, waiting for client to fetch
227 PGASYNC_READY_MORE
, /* query done, waiting for client to fetch
228 * result, more results expected from this
230 PGASYNC_COPY_IN
, /* Copy In data transfer in progress */
231 PGASYNC_COPY_OUT
, /* Copy Out data transfer in progress */
232 PGASYNC_COPY_BOTH
, /* Copy In/Out data transfer in progress */
233 PGASYNC_PIPELINE_IDLE
, /* "Idle" between commands in pipeline mode */
236 /* Bitmasks for allowed_enc_methods and failed_enc_methods */
238 #define ENC_PLAINTEXT 0x01
239 #define ENC_GSSAPI 0x02
242 /* Target server type (decoded value of target_session_attrs) */
245 SERVER_TYPE_ANY
= 0, /* Any server (default) */
246 SERVER_TYPE_READ_WRITE
, /* Read-write server */
247 SERVER_TYPE_READ_ONLY
, /* Read-only server */
248 SERVER_TYPE_PRIMARY
, /* Primary server */
249 SERVER_TYPE_STANDBY
, /* Standby server */
250 SERVER_TYPE_PREFER_STANDBY
, /* Prefer standby server */
251 SERVER_TYPE_PREFER_STANDBY_PASS2
/* second pass - behaves same as ANY */
252 } PGTargetServerType
;
254 /* Target server type (decoded value of load_balance_hosts) */
257 LOAD_BALANCE_DISABLE
= 0, /* Use the existing host order (default) */
258 LOAD_BALANCE_RANDOM
, /* Randomly shuffle the hosts */
261 /* Boolean value plus a not-known state, for GUCs we might have to fetch */
264 PG_BOOL_UNKNOWN
= 0, /* Currently unknown */
265 PG_BOOL_YES
, /* Yes (true) */
266 PG_BOOL_NO
/* No (false) */
269 /* Typedef for the EnvironmentOptions[] array */
270 typedef struct PQEnvironmentOption
272 const char *envName
, /* name of an environment variable */
273 *pgName
; /* name of corresponding SET variable */
274 } PQEnvironmentOption
;
276 /* Typedef for parameter-status list entries */
277 typedef struct pgParameterStatus
279 struct pgParameterStatus
*next
; /* list link */
280 char *name
; /* parameter name */
281 char *value
; /* parameter value */
282 /* Note: name and value are stored in same malloc block as struct is */
285 /* large-object-access data ... allocated only if large-object code is used. */
286 typedef struct pgLobjfuncs
288 Oid fn_lo_open
; /* OID of backend function lo_open */
289 Oid fn_lo_close
; /* OID of backend function lo_close */
290 Oid fn_lo_creat
; /* OID of backend function lo_creat */
291 Oid fn_lo_create
; /* OID of backend function lo_create */
292 Oid fn_lo_unlink
; /* OID of backend function lo_unlink */
293 Oid fn_lo_lseek
; /* OID of backend function lo_lseek */
294 Oid fn_lo_lseek64
; /* OID of backend function lo_lseek64 */
295 Oid fn_lo_tell
; /* OID of backend function lo_tell */
296 Oid fn_lo_tell64
; /* OID of backend function lo_tell64 */
297 Oid fn_lo_truncate
; /* OID of backend function lo_truncate */
298 Oid fn_lo_truncate64
; /* OID of function lo_truncate64 */
299 Oid fn_lo_read
; /* OID of backend function LOread */
300 Oid fn_lo_write
; /* OID of backend function LOwrite */
303 /* PGdataValue represents a data field value being passed to a row processor.
304 * It could be either text or binary data; text data is not zero-terminated.
305 * A SQL NULL is represented by len < 0; then value is still valid but there
306 * are no data bytes there.
308 typedef struct pgDataValue
310 int len
; /* data length in bytes, or <0 if NULL */
311 const char *value
; /* data value, without zero-termination */
314 /* Host address type enum for struct pg_conn_host */
315 typedef enum pg_conn_host_type
323 * PGQueryClass tracks which query protocol is in use for each command queue
324 * entry, or special operation in execution
328 PGQUERY_SIMPLE
, /* simple Query protocol (PQexec) */
329 PGQUERY_EXTENDED
, /* full Extended protocol (PQexecParams) */
330 PGQUERY_PREPARE
, /* Parse only (PQprepare) */
331 PGQUERY_DESCRIBE
, /* Describe Statement or Portal */
332 PGQUERY_SYNC
, /* Sync (at end of a pipeline) */
333 PGQUERY_CLOSE
/* Close Statement or Portal */
338 * valid values for pg_conn->current_auth_response. These are just for
339 * libpq internal use: since authentication response types all use the
340 * protocol byte 'p', fe-trace.c needs a way to distinguish them in order
341 * to print them correctly.
343 #define AUTH_RESPONSE_GSS 'G'
344 #define AUTH_RESPONSE_PASSWORD 'P'
345 #define AUTH_RESPONSE_SASL_INITIAL 'I'
346 #define AUTH_RESPONSE_SASL 'S'
349 * An entry in the pending command queue.
351 typedef struct PGcmdQueueEntry
353 PGQueryClass queryclass
; /* Query type */
354 char *query
; /* SQL command, or NULL if none/unknown/OOM */
355 struct PGcmdQueueEntry
*next
; /* list link */
359 * pg_conn_host stores all information about each of possibly several hosts
360 * mentioned in the connection string. Most fields are derived by splitting
361 * the relevant connection parameter (e.g., pghost) at commas.
363 typedef struct pg_conn_host
365 pg_conn_host_type type
; /* type of host address */
366 char *host
; /* host name or socket path */
367 char *hostaddr
; /* host numeric IP address */
368 char *port
; /* port number (always provided) */
369 char *password
; /* password for this host, read from the
370 * password file; NULL if not sought or not
371 * found in password file. */
375 * PGconn stores all the state data associated with a single connection
380 /* Saved values of connection options */
381 char *pghost
; /* the machine on which the server is running,
382 * or a path to a UNIX-domain socket, or a
383 * comma-separated list of machines and/or
384 * paths; if NULL, use DEFAULT_PGSOCKET_DIR */
385 char *pghostaddr
; /* the numeric IP address of the machine on
386 * which the server is running, or a
387 * comma-separated list of same. Takes
388 * precedence over pghost. */
389 char *pgport
; /* the server's communication port number, or
390 * a comma-separated list of ports */
391 char *connect_timeout
; /* connection timeout (numeric string) */
392 char *pgtcp_user_timeout
; /* tcp user timeout (numeric string) */
393 char *client_encoding_initial
; /* encoding to use */
394 char *pgoptions
; /* options to start the backend with */
395 char *appname
; /* application name */
396 char *fbappname
; /* fallback application name */
397 char *dbName
; /* database name */
398 char *replication
; /* connect as the replication standby? */
399 char *pgservice
; /* Postgres service, if any */
400 char *pguser
; /* Postgres username and password, if any */
402 char *pgpassfile
; /* path to a file containing password(s) */
403 char *channel_binding
; /* channel binding mode
404 * (require,prefer,disable) */
405 char *keepalives
; /* use TCP keepalives? */
406 char *keepalives_idle
; /* time between TCP keepalives */
407 char *keepalives_interval
; /* time between TCP keepalive
409 char *keepalives_count
; /* maximum number of TCP keepalive
411 char *sslmode
; /* SSL mode (require,prefer,allow,disable) */
412 char *sslnegotiation
; /* SSL initiation style (postgres,direct) */
413 char *sslcompression
; /* SSL compression (0 or 1) */
414 char *sslkey
; /* client key filename */
415 char *sslcert
; /* client certificate filename */
416 char *sslpassword
; /* client key file password */
417 char *sslcertmode
; /* client cert mode (require,allow,disable) */
418 char *sslrootcert
; /* root certificate filename */
419 char *sslcrl
; /* certificate revocation list filename */
420 char *sslcrldir
; /* certificate revocation list directory name */
421 char *sslsni
; /* use SSL SNI extension (0 or 1) */
422 char *requirepeer
; /* required peer credentials for local sockets */
423 char *gssencmode
; /* GSS mode (require,prefer,disable) */
424 char *krbsrvname
; /* Kerberos service name */
425 char *gsslib
; /* What GSS library to use ("gssapi" or
427 char *gssdelegation
; /* Try to delegate GSS credentials? (0 or 1) */
428 char *ssl_min_protocol_version
; /* minimum TLS protocol version */
429 char *ssl_max_protocol_version
; /* maximum TLS protocol version */
430 char *target_session_attrs
; /* desired session properties */
431 char *require_auth
; /* name of the expected auth method */
432 char *load_balance_hosts
; /* load balance over hosts */
433 char *scram_client_key
; /* base64-encoded SCRAM client key */
434 char *scram_server_key
; /* base64-encoded SCRAM server key */
436 bool cancelRequest
; /* true if this connection is used to send a
437 * cancel request, instead of being a normal
438 * connection that's used for queries */
440 /* Optional file to write trace info to */
444 /* Callback procedures for notice message processing */
445 PGNoticeHooks noticeHooks
;
447 /* Event procs registered via PQregisterEventProc */
448 PGEvent
*events
; /* expandable array of event data */
449 int nEvents
; /* number of active events */
450 int eventArraySize
; /* allocated array size */
452 /* Status indicators */
453 ConnStatusType status
;
454 PGAsyncStatusType asyncStatus
;
455 PGTransactionStatusType xactStatus
; /* never changes to ACTIVE */
456 char last_sqlstate
[6]; /* last reported SQLSTATE */
457 bool options_valid
; /* true if OK to attempt connection */
458 bool nonblocking
; /* whether this connection is using nonblock
459 * sending semantics */
460 PGpipelineStatus pipelineStatus
; /* status of pipeline mode */
461 bool partialResMode
; /* true if single-row or chunked mode */
462 bool singleRowMode
; /* return current query result row-by-row? */
463 int maxChunkSize
; /* return query result in chunks not exceeding
464 * this number of rows */
465 char copy_is_binary
; /* 1 = copy binary, 0 = copy text */
466 int copy_already_done
; /* # bytes already returned in COPY OUT */
467 PGnotify
*notifyHead
; /* oldest unreported Notify msg */
468 PGnotify
*notifyTail
; /* newest unreported Notify msg */
470 /* Support for multiple hosts in connection string */
471 int nconnhost
; /* # of hosts named in conn string */
472 int whichhost
; /* host we're currently trying/connected to */
473 pg_conn_host
*connhost
; /* details about each named host */
474 char *connip
; /* IP address for current network connection */
477 * The pending command queue as a singly-linked list. Head is the command
478 * currently in execution, tail is where new commands are added.
480 PGcmdQueueEntry
*cmd_queue_head
;
481 PGcmdQueueEntry
*cmd_queue_tail
;
484 * To save malloc traffic, we don't free entries right away; instead we
485 * save them in this list for possible reuse.
487 PGcmdQueueEntry
*cmd_queue_recycle
;
489 /* Connection data */
490 pgsocket sock
; /* FD for socket, PGINVALID_SOCKET if
492 SockAddr laddr
; /* Local address */
493 SockAddr raddr
; /* Remote address */
494 ProtocolVersion pversion
; /* FE/BE protocol version in use */
495 int sversion
; /* server version, e.g. 70401 for 7.4.1 */
496 bool auth_req_received
; /* true if any type of auth req received */
497 bool password_needed
; /* true if server demanded a password */
498 bool gssapi_used
; /* true if authenticated via gssapi */
499 bool sigpipe_so
; /* have we masked SIGPIPE via SO_NOSIGPIPE? */
500 bool sigpipe_flag
; /* can we mask SIGPIPE via MSG_NOSIGNAL? */
501 bool write_failed
; /* have we had a write failure on sock? */
502 char *write_err_msg
; /* write error message, or NULL if OOM */
504 bool auth_required
; /* require an authentication challenge from
506 uint32 allowed_auth_methods
; /* bitmask of acceptable AuthRequest
508 bool client_finished_auth
; /* have we finished our half of the
509 * authentication exchange? */
510 char current_auth_response
; /* used by pqTraceOutputMessage to
511 * know which auth response we're
514 /* Transient state needed while establishing connection */
515 PGTargetServerType target_server_type
; /* desired session properties */
516 PGLoadBalanceType load_balance_type
; /* desired load balancing
518 bool try_next_addr
; /* time to advance to next address/host? */
519 bool try_next_host
; /* time to advance to next connhost[]? */
520 int naddr
; /* number of addresses returned by getaddrinfo */
521 int whichaddr
; /* the address currently being tried */
522 AddrInfo
*addr
; /* the array of addresses for the currently
524 bool send_appname
; /* okay to send application_name? */
525 size_t scram_client_key_len
;
526 void *scram_client_key_binary
; /* binary SCRAM client key */
527 size_t scram_server_key_len
;
528 void *scram_server_key_binary
; /* binary SCRAM server key */
530 /* Miscellaneous stuff */
531 int be_pid
; /* PID of backend --- needed for cancels */
532 int be_key
; /* key of backend --- needed for cancels */
533 pgParameterStatus
*pstatus
; /* ParameterStatus data */
534 int client_encoding
; /* encoding id */
535 bool std_strings
; /* standard_conforming_strings */
536 PGTernaryBool default_transaction_read_only
; /* default_transaction_read_only */
537 PGTernaryBool in_hot_standby
; /* in_hot_standby */
538 PGVerbosity verbosity
; /* error/notice message verbosity */
539 PGContextVisibility show_context
; /* whether to show CONTEXT field */
540 PGlobjfuncs
*lobjfuncs
; /* private state for large-object access fns */
541 pg_prng_state prng_state
; /* prng state for load balancing connections */
544 /* Buffer for data received from backend and not yet processed */
545 char *inBuffer
; /* currently allocated buffer */
546 int inBufSize
; /* allocated size of buffer */
547 int inStart
; /* offset to first unconsumed data in buffer */
548 int inCursor
; /* next byte to tentatively consume */
549 int inEnd
; /* offset to first position after avail data */
551 /* Buffer for data not yet sent to backend */
552 char *outBuffer
; /* currently allocated buffer */
553 int outBufSize
; /* allocated size of buffer */
554 int outCount
; /* number of chars waiting in buffer */
556 /* State for constructing messages in outBuffer */
557 int outMsgStart
; /* offset to msg start (length word); if -1,
558 * msg has no length word */
559 int outMsgEnd
; /* offset to msg end (so far) */
561 /* Row processor interface workspace */
562 PGdataValue
*rowBuf
; /* array for passing values to rowProcessor */
563 int rowBufLen
; /* number of entries allocated in rowBuf */
566 * Status for asynchronous result construction. If result isn't NULL, it
567 * is a result being constructed or ready to return. If result is NULL
568 * and error_result is true, then we need to return a PGRES_FATAL_ERROR
569 * result, but haven't yet constructed it; text for the error has been
570 * appended to conn->errorMessage. (Delaying construction simplifies
571 * dealing with out-of-memory cases.) If saved_result isn't NULL, it is a
572 * PGresult that will replace "result" after we return that one; we use
573 * that in partial-result mode to remember the query's tuple metadata.
575 PGresult
*result
; /* result being constructed */
576 bool error_result
; /* do we need to make an ERROR result? */
577 PGresult
*saved_result
; /* original, empty result in partialResMode */
579 /* Assorted state for SASL, SSL, GSS, etc */
580 const pg_fe_sasl_mech
*sasl
;
582 int scram_sha_256_iterations
;
584 uint8 allowed_enc_methods
;
585 uint8 failed_enc_methods
;
586 uint8 current_enc_method
;
590 bool ssl_handshake_started
;
591 bool ssl_cert_requested
; /* Did the server ask us for a cert? */
592 bool ssl_cert_sent
; /* Did we send one in reply? */
593 bool last_read_was_eof
;
597 SSL
*ssl
; /* SSL status, if have SSL connection */
598 X509
*peer
; /* X509 cert of server */
599 #ifdef USE_SSL_ENGINE
600 ENGINE
*engine
; /* SSL engine, if any */
602 void *engine
; /* dummy field to keep struct the same if
603 * OpenSSL version changes */
605 #endif /* USE_OPENSSL */
609 gss_ctx_id_t gctx
; /* GSS context */
610 gss_name_t gtarg_nam
; /* GSS target name */
612 /* The following are encryption-only */
613 bool gssenc
; /* GSS encryption is usable */
614 gss_cred_id_t gcred
; /* GSS credential temp storage. */
616 /* GSS encryption I/O state --- see fe-secure-gssapi.c */
617 char *gss_SendBuffer
; /* Encrypted data waiting to be sent */
618 int gss_SendLength
; /* End of data available in gss_SendBuffer */
619 int gss_SendNext
; /* Next index to send a byte from
621 int gss_SendConsumed
; /* Number of source bytes encrypted but
622 * not yet reported as sent */
623 char *gss_RecvBuffer
; /* Received, encrypted data */
624 int gss_RecvLength
; /* End of data available in gss_RecvBuffer */
625 char *gss_ResultBuffer
; /* Decryption of data in gss_RecvBuffer */
626 int gss_ResultLength
; /* End of data available in
627 * gss_ResultBuffer */
628 int gss_ResultNext
; /* Next index to read a byte from
629 * gss_ResultBuffer */
630 uint32 gss_MaxPktSize
; /* Maximum size we can encrypt and fit the
631 * results into our output buffer */
635 CredHandle
*sspicred
; /* SSPI credentials handle */
636 CtxtHandle
*sspictx
; /* SSPI context */
637 char *sspitarget
; /* SSPI target name */
638 int usesspi
; /* Indicate if SSPI is in use on the
643 * Buffer for current error message. This is cleared at the start of any
644 * connection attempt or query cycle; after that, all code should append
645 * messages to it, never overwrite.
647 * In some situations we might report an error more than once in a query
648 * cycle. If so, errorMessage accumulates text from all the errors, and
649 * errorReported tracks how much we've already reported, so that the
650 * individual error PGresult objects don't contain duplicative text.
652 PQExpBufferData errorMessage
; /* expansible string */
653 int errorReported
; /* # bytes of string already reported */
655 /* Buffer for receiving various parts of messages */
656 PQExpBufferData workBuffer
; /* expansible string */
660 /* String descriptions of the ExecStatusTypes.
661 * direct use of this array is deprecated; call PQresStatus() instead.
663 extern char *const pgresStatus
[];
669 #define USER_CERT_FILE ".postgresql/postgresql.crt"
670 #define USER_KEY_FILE ".postgresql/postgresql.key"
671 #define ROOT_CERT_FILE ".postgresql/root.crt"
672 #define ROOT_CRL_FILE ".postgresql/root.crl"
674 /* On Windows, the "home" directory is already PostgreSQL-specific */
675 #define USER_CERT_FILE "postgresql.crt"
676 #define USER_KEY_FILE "postgresql.key"
677 #define ROOT_CERT_FILE "root.crt"
678 #define ROOT_CRL_FILE "root.crl"
684 * Internal functions of libpq
685 * Functions declared here need to be visible across files of libpq,
686 * but are not intended to be called by applications. We use the
687 * convention "pqXXX" for internal functions, vs. the "PQxxx" names
688 * used for application-visible routines.
692 /* === in fe-connect.c === */
694 extern void pqDropConnection(PGconn
*conn
, bool flushInput
);
695 extern bool pqConnectOptions2(PGconn
*conn
);
696 #if defined(WIN32) && defined(SIO_KEEPALIVE_VALS)
697 extern int pqSetKeepalivesWin32(pgsocket sock
, int idle
, int interval
);
699 extern int pqConnectDBStart(PGconn
*conn
);
700 extern int pqConnectDBComplete(PGconn
*conn
);
701 extern PGconn
*pqMakeEmptyPGconn(void);
702 extern void pqReleaseConnHosts(PGconn
*conn
);
703 extern void pqClosePGconn(PGconn
*conn
);
704 extern int pqPacketSend(PGconn
*conn
, char pack_type
,
705 const void *buf
, size_t buf_len
);
706 extern bool pqGetHomeDirectory(char *buf
, int bufsize
);
707 extern bool pqCopyPGconn(PGconn
*srcConn
, PGconn
*dstConn
);
708 extern bool pqParseIntParam(const char *value
, int *result
, PGconn
*conn
,
709 const char *context
);
711 extern pgthreadlock_t pg_g_threadlock
;
713 #define pglock_thread() pg_g_threadlock(true)
714 #define pgunlock_thread() pg_g_threadlock(false)
716 /* === in fe-exec.c === */
718 extern void pqSetResultError(PGresult
*res
, PQExpBuffer errorMessage
, int offset
);
719 extern void *pqResultAlloc(PGresult
*res
, size_t nBytes
, bool isBinary
);
720 extern char *pqResultStrdup(PGresult
*res
, const char *str
);
721 extern void pqClearAsyncResult(PGconn
*conn
);
722 extern void pqSaveErrorResult(PGconn
*conn
);
723 extern PGresult
*pqPrepareAsyncResult(PGconn
*conn
);
724 extern void pqInternalNotice(const PGNoticeHooks
*hooks
, const char *fmt
,...) pg_attribute_printf(2, 3);
725 extern void pqSaveMessageField(PGresult
*res
, char code
,
727 extern void pqSaveParameterStatus(PGconn
*conn
, const char *name
,
729 extern int pqRowProcessor(PGconn
*conn
, const char **errmsgp
);
730 extern void pqCommandQueueAdvance(PGconn
*conn
, bool isReadyForQuery
,
732 extern int PQsendQueryContinue(PGconn
*conn
, const char *query
);
734 /* === in fe-protocol3.c === */
736 extern char *pqBuildStartupPacket3(PGconn
*conn
, int *packetlen
,
737 const PQEnvironmentOption
*options
);
738 extern void pqParseInput3(PGconn
*conn
);
739 extern int pqGetErrorNotice3(PGconn
*conn
, bool isError
);
740 extern void pqBuildErrorMessage3(PQExpBuffer msg
, const PGresult
*res
,
741 PGVerbosity verbosity
, PGContextVisibility show_context
);
742 extern int pqGetNegotiateProtocolVersion3(PGconn
*conn
);
743 extern int pqGetCopyData3(PGconn
*conn
, char **buffer
, int async
);
744 extern int pqGetline3(PGconn
*conn
, char *s
, int maxlen
);
745 extern int pqGetlineAsync3(PGconn
*conn
, char *buffer
, int bufsize
);
746 extern int pqEndcopy3(PGconn
*conn
);
747 extern PGresult
*pqFunctionCall3(PGconn
*conn
, Oid fnid
,
748 int *result_buf
, int *actual_result_len
,
750 const PQArgBlock
*args
, int nargs
);
752 /* === in fe-misc.c === */
755 * "Get" and "Put" routines return 0 if successful, EOF if not. Note that for
756 * Get, EOF merely means the buffer is exhausted, not that there is
757 * necessarily any error.
759 extern int pqCheckOutBufferSpace(size_t bytes_needed
, PGconn
*conn
);
760 extern int pqCheckInBufferSpace(size_t bytes_needed
, PGconn
*conn
);
761 extern void pqParseDone(PGconn
*conn
, int newInStart
);
762 extern int pqGetc(char *result
, PGconn
*conn
);
763 extern int pqPutc(char c
, PGconn
*conn
);
764 extern int pqGets(PQExpBuffer buf
, PGconn
*conn
);
765 extern int pqGets_append(PQExpBuffer buf
, PGconn
*conn
);
766 extern int pqPuts(const char *s
, PGconn
*conn
);
767 extern int pqGetnchar(char *s
, size_t len
, PGconn
*conn
);
768 extern int pqSkipnchar(size_t len
, PGconn
*conn
);
769 extern int pqPutnchar(const char *s
, size_t len
, PGconn
*conn
);
770 extern int pqGetInt(int *result
, size_t bytes
, PGconn
*conn
);
771 extern int pqPutInt(int value
, size_t bytes
, PGconn
*conn
);
772 extern int pqPutMsgStart(char msg_type
, PGconn
*conn
);
773 extern int pqPutMsgEnd(PGconn
*conn
);
774 extern int pqReadData(PGconn
*conn
);
775 extern int pqFlush(PGconn
*conn
);
776 extern int pqWait(int forRead
, int forWrite
, PGconn
*conn
);
777 extern int pqWaitTimed(int forRead
, int forWrite
, PGconn
*conn
,
778 pg_usec_time_t end_time
);
779 extern int pqReadReady(PGconn
*conn
);
780 extern int pqWriteReady(PGconn
*conn
);
782 /* === in fe-secure.c === */
784 extern PostgresPollingStatusType
pqsecure_open_client(PGconn
*);
785 extern void pqsecure_close(PGconn
*);
786 extern ssize_t
pqsecure_read(PGconn
*, void *ptr
, size_t len
);
787 extern ssize_t
pqsecure_write(PGconn
*, const void *ptr
, size_t len
);
788 extern ssize_t
pqsecure_raw_read(PGconn
*, void *ptr
, size_t len
);
789 extern ssize_t
pqsecure_raw_write(PGconn
*, const void *ptr
, size_t len
);
792 extern int pq_block_sigpipe(sigset_t
*osigset
, bool *sigpipe_pending
);
793 extern void pq_reset_sigpipe(sigset_t
*osigset
, bool sigpipe_pending
,
800 * The SSL implementation provides these functions.
804 * Begin or continue negotiating a secure session.
806 extern PostgresPollingStatusType
pgtls_open_client(PGconn
*conn
);
809 * Close SSL connection.
811 extern void pgtls_close(PGconn
*conn
);
814 * Read data from a secure connection.
816 * On failure, this function is responsible for appending a suitable message
817 * to conn->errorMessage. The caller must still inspect errno, but only
818 * to determine whether to continue/retry after error.
820 extern ssize_t
pgtls_read(PGconn
*conn
, void *ptr
, size_t len
);
823 * Is there unread data waiting in the SSL read buffer?
825 extern bool pgtls_read_pending(PGconn
*conn
);
828 * Write data to a secure connection.
830 * On failure, this function is responsible for appending a suitable message
831 * to conn->errorMessage. The caller must still inspect errno, but only
832 * to determine whether to continue/retry after error.
834 extern ssize_t
pgtls_write(PGconn
*conn
, const void *ptr
, size_t len
);
837 * Get the hash of the server certificate, for SCRAM channel binding type
838 * tls-server-end-point.
840 * NULL is sent back to the caller in the event of an error, with an
841 * error message for the caller to consume.
843 extern char *pgtls_get_peer_certificate_hash(PGconn
*conn
, size_t *len
);
846 * Verify that the server certificate matches the host name we connected to.
848 * The certificate's Common Name and Subject Alternative Names are considered.
850 * Returns 1 if the name matches, and 0 if it does not. On error, returns
851 * -1, and sets the libpq error message.
854 extern int pgtls_verify_peer_name_matches_certificate_guts(PGconn
*conn
,
863 * Establish a GSSAPI-encrypted connection.
865 extern PostgresPollingStatusType
pqsecure_open_gss(PGconn
*conn
);
868 * Read and write functions for GSSAPI-encrypted connections, with internal
869 * buffering to handle nonblocking sockets.
871 extern ssize_t
pg_GSS_write(PGconn
*conn
, const void *ptr
, size_t len
);
872 extern ssize_t
pg_GSS_read(PGconn
*conn
, void *ptr
, size_t len
);
875 /* === in fe-trace.c === */
877 extern void pqTraceOutputMessage(PGconn
*conn
, const char *message
,
879 extern void pqTraceOutputNoTypeByteMessage(PGconn
*conn
, const char *message
);
880 extern void pqTraceOutputCharResponse(PGconn
*conn
, const char *responseType
,
883 /* === miscellaneous macros === */
886 * Reset the conn's error-reporting state.
888 #define pqClearConnErrorState(conn) \
889 (resetPQExpBuffer(&(conn)->errorMessage), \
890 (conn)->errorReported = 0)
893 * Check whether we have a PGresult pending to be returned --- either a
894 * constructed one in conn->result, or a "virtual" error result that we
895 * don't intend to materialize until the end of the query cycle.
897 #define pgHavePendingResult(conn) \
898 ((conn)->result != NULL || (conn)->error_result)
901 * this is so that we can check if a connection is non-blocking internally
902 * without the overhead of a function call
904 #define pqIsnonblocking(conn) ((conn)->nonblocking)
907 * Connection's outbuffer threshold, for pipeline mode.
909 #define OUTBUFFER_THRESHOLD 65536
912 extern char *libpq_gettext(const char *msgid
) pg_attribute_format_arg(1);
913 extern char *libpq_ngettext(const char *msgid
, const char *msgid_plural
, unsigned long n
) pg_attribute_format_arg(1) pg_attribute_format_arg(2);
915 #define libpq_gettext(x) (x)
916 #define libpq_ngettext(s, p, n) ((n) == 1 ? (s) : (p))
919 * libpq code should use the above, not _(), since that would use the
920 * surrounding programs's message catalog.
924 extern void libpq_append_error(PQExpBuffer errorMessage
, const char *fmt
,...) pg_attribute_printf(2, 3);
925 extern void libpq_append_conn_error(PGconn
*conn
, const char *fmt
,...) pg_attribute_printf(2, 3);
928 * These macros are needed to let error-handling code be portable between
929 * Unix and Windows. (ugh)
932 #define SOCK_ERRNO (WSAGetLastError())
933 #define SOCK_STRERROR winsock_strerror
934 #define SOCK_ERRNO_SET(e) WSASetLastError(e)
936 #define SOCK_ERRNO errno
937 #define SOCK_STRERROR strerror_r
938 #define SOCK_ERRNO_SET(e) (errno = (e))
941 #endif /* LIBPQ_INT_H */