Debian Codegraph @

src/interfaces/libpq/libpq-int.h

raw
1 /*-------------------------------------------------------------------------
2 *
3 * libpq-int.h
4 * This file contains internal definitions meant to be used only by
5 * the frontend libpq library, not by applications that call it.
6 *
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.
11 *
12 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
14 *
15 * src/interfaces/libpq/libpq-int.h
16 *
17 *-------------------------------------------------------------------------
18 */
19
20 #ifndef LIBPQ_INT_H
21 #define LIBPQ_INT_H
22
23 /* We assume libpq-fe.h has already been included. */
24 #include "libpq-events.h"
25
26 #include <netdb.h>
27 #include <sys/socket.h>
28 #include <time.h>
29 /* MinGW has sys/time.h, but MSVC doesn't */
30 #ifndef _MSC_VER
31 #include <sys/time.h>
32 #endif
33
34 #ifdef WIN32
35 #include "pthread-win32.h"
36 #else
37 #include <pthread.h>
38 #endif
39 #include <signal.h>
40
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"
46
47 #include "libpq/pg-gssapi.h"
48
49 #ifdef ENABLE_SSPI
50 #define SECURITY_WIN32
51 #if defined(WIN32) && !defined(_MSC_VER)
52 #include <ntsecapi.h>
53 #endif
54 #include <security.h>
55 #undef SECURITY_WIN32
56
57 #ifndef ENABLE_GSS
58 /*
59 * Define a fake structure compatible with GSSAPI on Unix.
60 */
61 typedef struct
62 {
63 void *value;
64 int length;
65 } gss_buffer_desc;
66 #endif
67 #endif /* ENABLE_SSPI */
68
69 #ifdef USE_OPENSSL
70 #include <openssl/ssl.h>
71 #include <openssl/err.h>
72
73 #ifndef OPENSSL_NO_ENGINE
74 #define USE_SSL_ENGINE
75 #endif
76 #endif /* USE_OPENSSL */
77
78 #include "common/pg_prng.h"
79
80 /*
81 * POSTGRES backend dependent Constants.
82 */
83 #define CMDSTATUS_LEN 64 /* should match COMPLETION_TAG_BUFSIZE */
84
85 /*
86 * PGresult and the subsidiary types PGresAttDesc, PGresAttValue
87 * represent the result of a query (or more precisely, of a single SQL
88 * command --- a query string given to PQexec can contain multiple commands).
89 * Note we assume that a single command can return at most one tuple group,
90 * hence there is no need for multiple descriptor sets.
91 */
92
93 /* Subsidiary-storage management structure for PGresult.
94 * See space management routines in fe-exec.c for details.
95 * Note that space[k] refers to the k'th byte starting from the physical
96 * head of the block --- it's a union, not a struct!
97 */
98 typedef union pgresult_data PGresult_data;
99
100 union pgresult_data
101 {
102 PGresult_data *next; /* link to next block, or NULL */
103 char space[1]; /* dummy for accessing block as bytes */
104 };
105
106 /* Data about a single parameter of a prepared statement */
107 typedef struct pgresParamDesc
108 {
109 Oid typid; /* type id */
110 } PGresParamDesc;
111
112 /*
113 * Data for a single attribute of a single tuple
114 *
115 * We use char* for Attribute values.
116 *
117 * The value pointer always points to a null-terminated area; we add a
118 * null (zero) byte after whatever the backend sends us. This is only
119 * particularly useful for text values ... with a binary value, the
120 * value might have embedded nulls, so the application can't use C string
121 * operators on it. But we add a null anyway for consistency.
122 * Note that the value itself does not contain a length word.
123 *
124 * A NULL attribute is a special case in two ways: its len field is NULL_LEN
125 * and its value field points to null_field in the owning PGresult. All the
126 * NULL attributes in a query result point to the same place (there's no need
127 * to store a null string separately for each one).
128 */
129
130 #define NULL_LEN (-1) /* pg_result len for NULL value */
131
132 typedef struct pgresAttValue
133 {
134 int len; /* length in bytes of the value */
135 char *value; /* actual value, plus terminating zero byte */
136 } PGresAttValue;
137
138 /* Typedef for message-field list entries */
139 typedef struct pgMessageField
140 {
141 struct pgMessageField *next; /* list link */
142 char code; /* field code */
143 char contents[FLEXIBLE_ARRAY_MEMBER]; /* value, nul-terminated */
144 } PGMessageField;
145
146 /* Fields needed for notice handling */
147 typedef struct
148 {
149 PQnoticeReceiver noticeRec; /* notice message receiver */
150 void *noticeRecArg;
151 PQnoticeProcessor noticeProc; /* notice message processor */
152 void *noticeProcArg;
153 } PGNoticeHooks;
154
155 typedef struct PGEvent
156 {
157 PGEventProc proc; /* the function to call on events */
158 char *name; /* used only for error messages */
159 void *passThrough; /* pointer supplied at registration time */
160 void *data; /* optional state (instance) data */
161 bool resultInitialized; /* T if RESULTCREATE/COPY succeeded */
162 } PGEvent;
163
164 struct pg_result
165 {
166 int ntups;
167 int numAttributes;
168 PGresAttDesc *attDescs;
169 PGresAttValue **tuples; /* each PGresult tuple is an array of
170 * PGresAttValue's */
171 int tupArrSize; /* allocated size of tuples array */
172 int numParameters;
173 PGresParamDesc *paramDescs;
174 ExecStatusType resultStatus;
175 char cmdStatus[CMDSTATUS_LEN]; /* cmd status from the query */
176 int binary; /* binary tuple values if binary == 1,
177 * otherwise text */
178
179 /*
180 * These fields are copied from the originating PGconn, so that operations
181 * on the PGresult don't have to reference the PGconn.
182 */
183 PGNoticeHooks noticeHooks;
184 PGEvent *events;
185 int nEvents;
186 int client_encoding; /* encoding id */
187
188 /*
189 * Error information (all NULL if not an error result). errMsg is the
190 * "overall" error message returned by PQresultErrorMessage. If we have
191 * per-field info then it is stored in a linked list.
192 */
193 char *errMsg; /* error message, or NULL if no error */
194 PGMessageField *errFields; /* message broken into fields */
195 char *errQuery; /* text of triggering query, if available */
196
197 /* All NULL attributes in the query result point to this null string */
198 char null_field[1];
199
200 /*
201 * Space management information. Note that attDescs and error stuff, if
202 * not null, point into allocated blocks. But tuples points to a
203 * separately malloc'd block, so that we can realloc it.
204 */
205 PGresult_data *curBlock; /* most recently allocated block */
206 int curOffset; /* start offset of free space in block */
207 int spaceLeft; /* number of free bytes remaining in block */
208
209 size_t memorySize; /* total space allocated for this PGresult */
210 };
211
212 /* PGAsyncStatusType defines the state of the query-execution state machine */
213 typedef enum
214 {
215 PGASYNC_IDLE, /* nothing's happening, dude */
216 PGASYNC_BUSY, /* query in progress */
217 PGASYNC_READY, /* query done, waiting for client to fetch
218 * result */
219 PGASYNC_READY_MORE, /* query done, waiting for client to fetch
220 * result, more results expected from this
221 * query */
222 PGASYNC_COPY_IN, /* Copy In data transfer in progress */
223 PGASYNC_COPY_OUT, /* Copy Out data transfer in progress */
224 PGASYNC_COPY_BOTH, /* Copy In/Out data transfer in progress */
225 PGASYNC_PIPELINE_IDLE, /* "Idle" between commands in pipeline mode */
226 } PGAsyncStatusType;
227
228 /* Bitmasks for allowed_enc_methods and failed_enc_methods */
229 #define ENC_ERROR 0
230 #define ENC_PLAINTEXT 0x01
231 #define ENC_GSSAPI 0x02
232 #define ENC_SSL 0x04
233
234 /* Target server type (decoded value of target_session_attrs) */
235 typedef enum
236 {
237 SERVER_TYPE_ANY = 0, /* Any server (default) */
238 SERVER_TYPE_READ_WRITE, /* Read-write server */
239 SERVER_TYPE_READ_ONLY, /* Read-only server */
240 SERVER_TYPE_PRIMARY, /* Primary server */
241 SERVER_TYPE_STANDBY, /* Standby server */
242 SERVER_TYPE_PREFER_STANDBY, /* Prefer standby server */
243 SERVER_TYPE_PREFER_STANDBY_PASS2 /* second pass - behaves same as ANY */
244 } PGTargetServerType;
245
246 /* Target server type (decoded value of load_balance_hosts) */
247 typedef enum
248 {
249 LOAD_BALANCE_DISABLE = 0, /* Use the existing host order (default) */
250 LOAD_BALANCE_RANDOM, /* Randomly shuffle the hosts */
251 } PGLoadBalanceType;
252
253 /* Boolean value plus a not-known state, for GUCs we might have to fetch */
254 typedef enum
255 {
256 PG_BOOL_UNKNOWN = 0, /* Currently unknown */
257 PG_BOOL_YES, /* Yes (true) */
258 PG_BOOL_NO /* No (false) */
259 } PGTernaryBool;
260
261 /* Typedef for the EnvironmentOptions[] array */
262 typedef struct PQEnvironmentOption
263 {
264 const char *envName, /* name of an environment variable */
265 *pgName; /* name of corresponding SET variable */
266 } PQEnvironmentOption;
267
268 /* Typedef for parameter-status list entries */
269 typedef struct pgParameterStatus
270 {
271 struct pgParameterStatus *next; /* list link */
272 char *name; /* parameter name */
273 char *value; /* parameter value */
274 /* Note: name and value are stored in same malloc block as struct is */
275 } pgParameterStatus;
276
277 /* large-object-access data ... allocated only if large-object code is used. */
278 typedef struct pgLobjfuncs
279 {
280 Oid fn_lo_open; /* OID of backend function lo_open */
281 Oid fn_lo_close; /* OID of backend function lo_close */
282 Oid fn_lo_creat; /* OID of backend function lo_creat */
283 Oid fn_lo_create; /* OID of backend function lo_create */
284 Oid fn_lo_unlink; /* OID of backend function lo_unlink */
285 Oid fn_lo_lseek; /* OID of backend function lo_lseek */
286 Oid fn_lo_lseek64; /* OID of backend function lo_lseek64 */
287 Oid fn_lo_tell; /* OID of backend function lo_tell */
288 Oid fn_lo_tell64; /* OID of backend function lo_tell64 */
289 Oid fn_lo_truncate; /* OID of backend function lo_truncate */
290 Oid fn_lo_truncate64; /* OID of function lo_truncate64 */
291 Oid fn_lo_read; /* OID of backend function LOread */
292 Oid fn_lo_write; /* OID of backend function LOwrite */
293 } PGlobjfuncs;
294
295 /* PGdataValue represents a data field value being passed to a row processor.
296 * It could be either text or binary data; text data is not zero-terminated.
297 * A SQL NULL is represented by len < 0; then value is still valid but there
298 * are no data bytes there.
299 */
300 typedef struct pgDataValue
301 {
302 int len; /* data length in bytes, or <0 if NULL */
303 const char *value; /* data value, without zero-termination */
304 } PGdataValue;
305
306 /* Host address type enum for struct pg_conn_host */
307 typedef enum pg_conn_host_type
308 {
309 CHT_HOST_NAME,
310 CHT_HOST_ADDRESS,
311 CHT_UNIX_SOCKET
312 } pg_conn_host_type;
313
314 /*
315 * PGQueryClass tracks which query protocol is in use for each command queue
316 * entry, or special operation in execution
317 */
318 typedef enum
319 {
320 PGQUERY_SIMPLE, /* simple Query protocol (PQexec) */
321 PGQUERY_EXTENDED, /* full Extended protocol (PQexecParams) */
322 PGQUERY_PREPARE, /* Parse only (PQprepare) */
323 PGQUERY_DESCRIBE, /* Describe Statement or Portal */
324 PGQUERY_SYNC, /* Sync (at end of a pipeline) */
325 PGQUERY_CLOSE /* Close Statement or Portal */
326 } PGQueryClass;
327
328
329 /*
330 * valid values for pg_conn->current_auth_response. These are just for
331 * libpq internal use: since authentication response types all use the
332 * protocol byte 'p', fe-trace.c needs a way to distinguish them in order
333 * to print them correctly.
334 */
335 #define AUTH_RESPONSE_GSS 'G'
336 #define AUTH_RESPONSE_PASSWORD 'P'
337 #define AUTH_RESPONSE_SASL_INITIAL 'I'
338 #define AUTH_RESPONSE_SASL 'S'
339
340 /*
341 * An entry in the pending command queue.
342 */
343 typedef struct PGcmdQueueEntry
344 {
345 PGQueryClass queryclass; /* Query type */
346 char *query; /* SQL command, or NULL if none/unknown/OOM */
347 struct PGcmdQueueEntry *next; /* list link */
348 } PGcmdQueueEntry;
349
350 /*
351 * pg_conn_host stores all information about each of possibly several hosts
352 * mentioned in the connection string. Most fields are derived by splitting
353 * the relevant connection parameter (e.g., pghost) at commas.
354 */
355 typedef struct pg_conn_host
356 {
357 pg_conn_host_type type; /* type of host address */
358 char *host; /* host name or socket path */
359 char *hostaddr; /* host numeric IP address */
360 char *port; /* port number (if NULL or empty, use
361 * DEF_PGPORT[_STR]) */
362 char *password; /* password for this host, read from the
363 * password file; NULL if not sought or not
364 * found in password file. */
365 } pg_conn_host;
366
367 /*
368 * PGconn stores all the state data associated with a single connection
369 * to a backend.
370 */
371 struct pg_conn
372 {
373 /* Saved values of connection options */
374 char *pghost; /* the machine on which the server is running,
375 * or a path to a UNIX-domain socket, or a
376 * comma-separated list of machines and/or
377 * paths; if NULL, use DEFAULT_PGSOCKET_DIR */
378 char *pghostaddr; /* the numeric IP address of the machine on
379 * which the server is running, or a
380 * comma-separated list of same. Takes
381 * precedence over pghost. */
382 char *pgport; /* the server's communication port number, or
383 * a comma-separated list of ports */
384 char *connect_timeout; /* connection timeout (numeric string) */
385 char *pgtcp_user_timeout; /* tcp user timeout (numeric string) */
386 char *client_encoding_initial; /* encoding to use */
387 char *pgoptions; /* options to start the backend with */
388 char *appname; /* application name */
389 char *fbappname; /* fallback application name */
390 char *dbName; /* database name */
391 char *replication; /* connect as the replication standby? */
392 char *pgservice; /* Postgres service, if any */
393 char *pguser; /* Postgres username and password, if any */
394 char *pgpass;
395 char *pgpassfile; /* path to a file containing password(s) */
396 char *channel_binding; /* channel binding mode
397 * (require,prefer,disable) */
398 char *keepalives; /* use TCP keepalives? */
399 char *keepalives_idle; /* time between TCP keepalives */
400 char *keepalives_interval; /* time between TCP keepalive
401 * retransmits */
402 char *keepalives_count; /* maximum number of TCP keepalive
403 * retransmits */
404 char *sslmode; /* SSL mode (require,prefer,allow,disable) */
405 char *sslnegotiation; /* SSL initiation style (postgres,direct) */
406 char *sslcompression; /* SSL compression (0 or 1) */
407 char *sslkey; /* client key filename */
408 char *sslcert; /* client certificate filename */
409 char *sslpassword; /* client key file password */
410 char *sslcertmode; /* client cert mode (require,allow,disable) */
411 char *sslrootcert; /* root certificate filename */
412 char *sslcrl; /* certificate revocation list filename */
413 char *sslcrldir; /* certificate revocation list directory name */
414 char *sslsni; /* use SSL SNI extension (0 or 1) */
415 char *requirepeer; /* required peer credentials for local sockets */
416 char *gssencmode; /* GSS mode (require,prefer,disable) */
417 char *krbsrvname; /* Kerberos service name */
418 char *gsslib; /* What GSS library to use ("gssapi" or
419 * "sspi") */
420 char *gssdelegation; /* Try to delegate GSS credentials? (0 or 1) */
421 char *min_protocol_version; /* minimum used protocol version */
422 char *max_protocol_version; /* maximum used protocol version */
423 char *ssl_min_protocol_version; /* minimum TLS protocol version */
424 char *ssl_max_protocol_version; /* maximum TLS protocol version */
425 char *target_session_attrs; /* desired session properties */
426 char *require_auth; /* name of the expected auth method */
427 char *load_balance_hosts; /* load balance over hosts */
428 char *scram_client_key; /* base64-encoded SCRAM client key */
429 char *scram_server_key; /* base64-encoded SCRAM server key */
430 char *sslkeylogfile; /* where should the client write ssl keylogs */
431
432 bool cancelRequest; /* true if this connection is used to send a
433 * cancel request, instead of being a normal
434 * connection that's used for queries */
435
436 /* OAuth v2 */
437 char *oauth_issuer; /* token issuer/URL */
438 char *oauth_issuer_id; /* token issuer identifier */
439 char *oauth_discovery_uri; /* URI of the issuer's discovery
440 * document */
441 char *oauth_client_id; /* client identifier */
442 char *oauth_client_secret; /* client secret */
443 char *oauth_scope; /* access token scope */
444 char *oauth_token; /* access token */
445 bool oauth_want_retry; /* should we retry on failure? */
446
447 /* Optional file to write trace info to */
448 FILE *Pfdebug;
449 int traceFlags;
450
451 /* Callback procedures for notice message processing */
452 PGNoticeHooks noticeHooks;
453
454 /* Event procs registered via PQregisterEventProc */
455 PGEvent *events; /* expandable array of event data */
456 int nEvents; /* number of active events */
457 int eventArraySize; /* allocated array size */
458
459 /* Status indicators */
460 ConnStatusType status;
461 PGAsyncStatusType asyncStatus;
462 PGTransactionStatusType xactStatus; /* never changes to ACTIVE */
463 char last_sqlstate[6]; /* last reported SQLSTATE */
464 bool options_valid; /* true if OK to attempt connection */
465 bool nonblocking; /* whether this connection is using nonblock
466 * sending semantics */
467 PGpipelineStatus pipelineStatus; /* status of pipeline mode */
468 bool partialResMode; /* true if single-row or chunked mode */
469 bool singleRowMode; /* return current query result row-by-row? */
470 int maxChunkSize; /* return query result in chunks not exceeding
471 * this number of rows */
472 char copy_is_binary; /* 1 = copy binary, 0 = copy text */
473 int copy_already_done; /* # bytes already returned in COPY OUT */
474 PGnotify *notifyHead; /* oldest unreported Notify msg */
475 PGnotify *notifyTail; /* newest unreported Notify msg */
476
477 /* Support for multiple hosts in connection string */
478 int nconnhost; /* # of hosts named in conn string */
479 int whichhost; /* host we're currently trying/connected to */
480 pg_conn_host *connhost; /* details about each named host */
481 char *connip; /* IP address for current network connection */
482
483 /*
484 * The pending command queue as a singly-linked list. Head is the command
485 * currently in execution, tail is where new commands are added.
486 */
487 PGcmdQueueEntry *cmd_queue_head;
488 PGcmdQueueEntry *cmd_queue_tail;
489
490 /*
491 * To save malloc traffic, we don't free entries right away; instead we
492 * save them in this list for possible reuse.
493 */
494 PGcmdQueueEntry *cmd_queue_recycle;
495
496 /* Connection data */
497 pgsocket sock; /* FD for socket, PGINVALID_SOCKET if
498 * unconnected */
499 SockAddr laddr; /* Local address */
500 SockAddr raddr; /* Remote address */
501 ProtocolVersion pversion; /* FE/BE protocol version in use */
502 int sversion; /* server version, e.g. 70401 for 7.4.1 */
503 bool pversion_negotiated; /* true if NegotiateProtocolVersion
504 * was received */
505 bool auth_req_received; /* true if any type of auth req received */
506 bool password_needed; /* true if server demanded a password */
507 bool gssapi_used; /* true if authenticated via gssapi */
508 bool sigpipe_so; /* have we masked SIGPIPE via SO_NOSIGPIPE? */
509 bool sigpipe_flag; /* can we mask SIGPIPE via MSG_NOSIGNAL? */
510 bool write_failed; /* have we had a write failure on sock? */
511 char *write_err_msg; /* write error message, or NULL if OOM */
512
513 bool auth_required; /* require an authentication challenge from
514 * the server? */
515 uint32 allowed_auth_methods; /* bitmask of acceptable AuthRequest
516 * codes */
517 const pg_fe_sasl_mech *allowed_sasl_mechs[2]; /* and acceptable SASL
518 * mechanisms */
519 bool client_finished_auth; /* have we finished our half of the
520 * authentication exchange? */
521 char current_auth_response; /* used by pqTraceOutputMessage to
522 * know which auth response we're
523 * sending */
524
525 /* Callbacks for external async authentication */
526 PostgresPollingStatusType (*async_auth) (PGconn *conn);
527 void (*cleanup_async_auth) (PGconn *conn);
528 pgsocket altsock; /* alternative socket for client to poll */
529
530
531 /* Transient state needed while establishing connection */
532 PGTargetServerType target_server_type; /* desired session properties */
533 PGLoadBalanceType load_balance_type; /* desired load balancing
534 * algorithm */
535 bool try_next_addr; /* time to advance to next address/host? */
536 bool try_next_host; /* time to advance to next connhost[]? */
537 int naddr; /* number of addresses returned by getaddrinfo */
538 int whichaddr; /* the address currently being tried */
539 AddrInfo *addr; /* the array of addresses for the currently
540 * tried host */
541 bool send_appname; /* okay to send application_name? */
542 size_t scram_client_key_len;
543 uint8 *scram_client_key_binary; /* binary SCRAM client key */
544 size_t scram_server_key_len;
545 uint8 *scram_server_key_binary; /* binary SCRAM server key */
546 ProtocolVersion min_pversion; /* protocol version to request */
547 ProtocolVersion max_pversion; /* protocol version to request */
548
549 /* Miscellaneous stuff */
550 int be_pid; /* PID of backend --- needed for cancels */
551 int be_cancel_key_len;
552 uint8 *be_cancel_key; /* query cancellation key */
553 pgParameterStatus *pstatus; /* ParameterStatus data */
554 int client_encoding; /* encoding id */
555 bool std_strings; /* standard_conforming_strings */
556 PGTernaryBool default_transaction_read_only; /* default_transaction_read_only */
557 PGTernaryBool in_hot_standby; /* in_hot_standby */
558 PGVerbosity verbosity; /* error/notice message verbosity */
559 PGContextVisibility show_context; /* whether to show CONTEXT field */
560 PGlobjfuncs *lobjfuncs; /* private state for large-object access fns */
561 pg_prng_state prng_state; /* prng state for load balancing connections */
562
563
564 /*
565 * Buffer for data received from backend and not yet processed.
566 *
567 * NB: We rely on a maximum inBufSize/outBufSize of INT_MAX (and therefore
568 * an INT_MAX upper bound on the size of any and all packet contents) to
569 * avoid overflow; for example in reportErrorPosition(). Changing the type
570 * would require not only an adjustment to the overflow protection in
571 * pqCheck{In,Out}BufferSpace(), but also a careful audit of all libpq
572 * code that uses ints during size calculations.
573 */
574 char *inBuffer; /* currently allocated buffer */
575 int inBufSize; /* allocated size of buffer */
576 int inStart; /* offset to first unconsumed data in buffer */
577 int inCursor; /* next byte to tentatively consume */
578 int inEnd; /* offset to first position after avail data */
579
580 /* Buffer for data not yet sent to backend */
581 char *outBuffer; /* currently allocated buffer */
582 int outBufSize; /* allocated size of buffer */
583 int outCount; /* number of chars waiting in buffer */
584
585 /* State for constructing messages in outBuffer */
586 int outMsgStart; /* offset to msg start (length word); if -1,
587 * msg has no length word */
588 int outMsgEnd; /* offset to msg end (so far) */
589
590 /* Row processor interface workspace */
591 PGdataValue *rowBuf; /* array for passing values to rowProcessor */
592 int rowBufLen; /* number of entries allocated in rowBuf */
593
594 /*
595 * Status for asynchronous result construction. If result isn't NULL, it
596 * is a result being constructed or ready to return. If result is NULL
597 * and error_result is true, then we need to return a PGRES_FATAL_ERROR
598 * result, but haven't yet constructed it; text for the error has been
599 * appended to conn->errorMessage. (Delaying construction simplifies
600 * dealing with out-of-memory cases.) If saved_result isn't NULL, it is a
601 * PGresult that will replace "result" after we return that one; we use
602 * that in partial-result mode to remember the query's tuple metadata.
603 */
604 PGresult *result; /* result being constructed */
605 bool error_result; /* do we need to make an ERROR result? */
606 PGresult *saved_result; /* original, empty result in partialResMode */
607
608 /* Assorted state for SASL, SSL, GSS, etc */
609 const pg_fe_sasl_mech *sasl;
610 void *sasl_state;
611 int scram_sha_256_iterations;
612
613 uint8 allowed_enc_methods;
614 uint8 failed_enc_methods;
615 uint8 current_enc_method;
616
617 /* SSL structures */
618 bool ssl_in_use;
619 bool ssl_handshake_started;
620 bool ssl_cert_requested; /* Did the server ask us for a cert? */
621 bool ssl_cert_sent; /* Did we send one in reply? */
622 bool last_read_was_eof;
623
624 #ifdef USE_SSL
625 #ifdef USE_OPENSSL
626 SSL *ssl; /* SSL status, if have SSL connection */
627 X509 *peer; /* X509 cert of server */
628 #ifdef USE_SSL_ENGINE
629 ENGINE *engine; /* SSL engine, if any */
630 #else
631 void *engine; /* dummy field to keep struct the same if
632 * OpenSSL version changes */
633 #endif
634 #endif /* USE_OPENSSL */
635 #endif /* USE_SSL */
636
637 #ifdef ENABLE_GSS
638 gss_ctx_id_t gctx; /* GSS context */
639 gss_name_t gtarg_nam; /* GSS target name */
640
641 /* The following are encryption-only */
642 bool gssenc; /* GSS encryption is usable */
643 gss_cred_id_t gcred; /* GSS credential temp storage. */
644
645 /* GSS encryption I/O state --- see fe-secure-gssapi.c */
646 char *gss_SendBuffer; /* Encrypted data waiting to be sent */
647 int gss_SendLength; /* End of data available in gss_SendBuffer */
648 int gss_SendNext; /* Next index to send a byte from
649 * gss_SendBuffer */
650 int gss_SendConsumed; /* Number of source bytes encrypted but
651 * not yet reported as sent */
652 char *gss_RecvBuffer; /* Received, encrypted data */
653 int gss_RecvLength; /* End of data available in gss_RecvBuffer */
654 char *gss_ResultBuffer; /* Decryption of data in gss_RecvBuffer */
655 int gss_ResultLength; /* End of data available in
656 * gss_ResultBuffer */
657 int gss_ResultNext; /* Next index to read a byte from
658 * gss_ResultBuffer */
659 uint32 gss_MaxPktSize; /* Maximum size we can encrypt and fit the
660 * results into our output buffer */
661 #endif
662
663 #ifdef ENABLE_SSPI
664 CredHandle *sspicred; /* SSPI credentials handle */
665 CtxtHandle *sspictx; /* SSPI context */
666 char *sspitarget; /* SSPI target name */
667 int usesspi; /* Indicate if SSPI is in use on the
668 * connection */
669 #endif
670
671 /*
672 * Buffer for current error message. This is cleared at the start of any
673 * connection attempt or query cycle; after that, all code should append
674 * messages to it, never overwrite.
675 *
676 * In some situations we might report an error more than once in a query
677 * cycle. If so, errorMessage accumulates text from all the errors, and
678 * errorReported tracks how much we've already reported, so that the
679 * individual error PGresult objects don't contain duplicative text.
680 */
681 PQExpBufferData errorMessage; /* expansible string */
682 int errorReported; /* # bytes of string already reported */
683
684 /* Buffer for receiving various parts of messages */
685 PQExpBufferData workBuffer; /* expansible string */
686 };
687
688
689 /* String descriptions of the ExecStatusTypes.
690 * direct use of this array is deprecated; call PQresStatus() instead.
691 */
692 extern char *const pgresStatus[];
693
694
695 #ifdef USE_SSL
696
697 #ifndef WIN32
698 #define USER_CERT_FILE ".postgresql/postgresql.crt"
699 #define USER_KEY_FILE ".postgresql/postgresql.key"
700 #define ROOT_CERT_FILE ".postgresql/root.crt"
701 #define ROOT_CRL_FILE ".postgresql/root.crl"
702 #else
703 /* On Windows, the "home" directory is already PostgreSQL-specific */
704 #define USER_CERT_FILE "postgresql.crt"
705 #define USER_KEY_FILE "postgresql.key"
706 #define ROOT_CERT_FILE "root.crt"
707 #define ROOT_CRL_FILE "root.crl"
708 #endif
709
710 #endif /* USE_SSL */
711
712 /* ----------------
713 * Internal functions of libpq
714 * Functions declared here need to be visible across files of libpq,
715 * but are not intended to be called by applications. We use the
716 * convention "pqXXX" for internal functions, vs. the "PQxxx" names
717 * used for application-visible routines.
718 * ----------------
719 */
720
721 /* === in fe-connect.c === */
722
723 extern void pqDropConnection(PGconn *conn, bool flushInput);
724 extern bool pqConnectOptions2(PGconn *conn);
725 #if defined(WIN32) && defined(SIO_KEEPALIVE_VALS)
726 extern int pqSetKeepalivesWin32(pgsocket sock, int idle, int interval);
727 #endif
728 extern int pqConnectDBStart(PGconn *conn);
729 extern int pqConnectDBComplete(PGconn *conn);
730 extern PGconn *pqMakeEmptyPGconn(void);
731 extern void pqReleaseConnHosts(PGconn *conn);
732 extern void pqClosePGconn(PGconn *conn);
733 extern int pqPacketSend(PGconn *conn, char pack_type,
734 const void *buf, size_t buf_len);
735 extern bool pqGetHomeDirectory(char *buf, int bufsize);
736 extern bool pqCopyPGconn(PGconn *srcConn, PGconn *dstConn);
737 extern bool pqParseIntParam(const char *value, int *result, PGconn *conn,
738 const char *context);
739
740 extern pgthreadlock_t pg_g_threadlock;
741
742 #define pglock_thread() pg_g_threadlock(true)
743 #define pgunlock_thread() pg_g_threadlock(false)
744
745 /* === in fe-exec.c === */
746
747 extern void pqSetResultError(PGresult *res, PQExpBuffer errorMessage, int offset);
748 extern void *pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary);
749 extern char *pqResultStrdup(PGresult *res, const char *str);
750 extern void pqClearAsyncResult(PGconn *conn);
751 extern void pqSaveErrorResult(PGconn *conn);
752 extern PGresult *pqPrepareAsyncResult(PGconn *conn);
753 extern void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...) pg_attribute_printf(2, 3);
754 extern void pqSaveMessageField(PGresult *res, char code,
755 const char *value);
756 extern int pqSaveParameterStatus(PGconn *conn, const char *name,
757 const char *value);
758 extern int pqRowProcessor(PGconn *conn, const char **errmsgp);
759 extern void pqCommandQueueAdvance(PGconn *conn, bool isReadyForQuery,
760 bool gotSync);
761 extern int PQsendQueryContinue(PGconn *conn, const char *query);
762 extern PGresult *PQnfn(PGconn *conn, int fnid, int *result_buf, int buf_size,
763 int *result_len, int result_is_int,
764 const PQArgBlock *args, int nargs);
765
766 /* === in fe-protocol3.c === */
767
768 extern char *pqBuildStartupPacket3(PGconn *conn, int *packetlen,
769 const PQEnvironmentOption *options);
770 extern void pqParseInput3(PGconn *conn);
771 extern int pqGetErrorNotice3(PGconn *conn, bool isError);
772 extern void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res,
773 PGVerbosity verbosity, PGContextVisibility show_context);
774 extern int pqGetNegotiateProtocolVersion3(PGconn *conn);
775 extern int pqGetCopyData3(PGconn *conn, char **buffer, int async);
776 extern int pqGetline3(PGconn *conn, char *s, int maxlen);
777 extern int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize);
778 extern int pqEndcopy3(PGconn *conn);
779 extern PGresult *pqFunctionCall3(PGconn *conn, Oid fnid,
780 int *result_buf, int buf_size,
781 int *actual_result_len,
782 int result_is_int,
783 const PQArgBlock *args, int nargs);
784
785 /* === in fe-cancel.c === */
786
787 extern int PQsendCancelRequest(PGconn *cancelConn);
788
789 /* === in fe-misc.c === */
790
791 /*
792 * "Get" and "Put" routines return 0 if successful, EOF if not. Note that for
793 * Get, EOF merely means the buffer is exhausted, not that there is
794 * necessarily any error.
795 */
796 extern int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn);
797 extern int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn);
798 extern void pqParseDone(PGconn *conn, int newInStart);
799 extern int pqGetc(char *result, PGconn *conn);
800 extern int pqPutc(char c, PGconn *conn);
801 extern int pqGets(PQExpBuffer buf, PGconn *conn);
802 extern int pqGets_append(PQExpBuffer buf, PGconn *conn);
803 extern int pqPuts(const char *s, PGconn *conn);
804 extern int pqGetnchar(void *s, size_t len, PGconn *conn);
805 extern int pqSkipnchar(size_t len, PGconn *conn);
806 extern int pqPutnchar(const void *s, size_t len, PGconn *conn);
807 extern int pqGetInt(int *result, size_t bytes, PGconn *conn);
808 extern int pqPutInt(int value, size_t bytes, PGconn *conn);
809 extern int pqPutMsgStart(char msg_type, PGconn *conn);
810 extern int pqPutMsgEnd(PGconn *conn);
811 extern int pqReadData(PGconn *conn);
812 extern int pqFlush(PGconn *conn);
813 extern int pqWait(int forRead, int forWrite, PGconn *conn);
814 extern int pqWaitTimed(int forRead, int forWrite, PGconn *conn,
815 pg_usec_time_t end_time);
816 extern int pqReadReady(PGconn *conn);
817 extern int pqWriteReady(PGconn *conn);
818
819 /* === in fe-secure.c === */
820
821 extern PostgresPollingStatusType pqsecure_open_client(PGconn *);
822 extern void pqsecure_close(PGconn *);
823 extern ssize_t pqsecure_read(PGconn *, void *ptr, size_t len);
824 extern ssize_t pqsecure_bytes_pending(PGconn *);
825 extern ssize_t pqsecure_write(PGconn *, const void *ptr, size_t len);
826 extern ssize_t pqsecure_raw_read(PGconn *, void *ptr, size_t len);
827 extern ssize_t pqsecure_raw_write(PGconn *, const void *ptr, size_t len);
828
829 #if !defined(WIN32)
830 extern int pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending);
831 extern void pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending,
832 bool got_epipe);
833 #endif
834
835 /* === SSL === */
836
837 /*
838 * The SSL implementation provides these functions.
839 */
840
841 /*
842 * Begin or continue negotiating a secure session.
843 */
844 extern PostgresPollingStatusType pgtls_open_client(PGconn *conn);
845
846 /*
847 * Close SSL connection.
848 */
849 extern void pgtls_close(PGconn *conn);
850
851 /*
852 * Read data from a secure connection.
853 *
854 * On failure, this function is responsible for appending a suitable message
855 * to conn->errorMessage. The caller must still inspect errno, but only
856 * to determine whether to continue/retry after error.
857 */
858 extern ssize_t pgtls_read(PGconn *conn, void *ptr, size_t len);
859
860 /*
861 * Return the number of bytes available in the transport buffer.
862 */
863 extern ssize_t pgtls_bytes_pending(PGconn *conn);
864
865 /*
866 * Write data to a secure connection.
867 *
868 * On failure, this function is responsible for appending a suitable message
869 * to conn->errorMessage. The caller must still inspect errno, but only
870 * to determine whether to continue/retry after error.
871 */
872 extern ssize_t pgtls_write(PGconn *conn, const void *ptr, size_t len);
873
874 /*
875 * Get the hash of the server certificate, for SCRAM channel binding type
876 * tls-server-end-point.
877 *
878 * NULL is sent back to the caller in the event of an error, with an
879 * error message for the caller to consume.
880 */
881 extern char *pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len);
882
883 /*
884 * Verify that the server certificate matches the host name we connected to.
885 *
886 * The certificate's Common Name and Subject Alternative Names are considered.
887 *
888 * Returns 1 if the name matches, and 0 if it does not. On error, returns
889 * -1, and sets the libpq error message.
890 *
891 */
892 extern int pgtls_verify_peer_name_matches_certificate_guts(PGconn *conn,
893 int *names_examined,
894 char **first_name);
895
896 /* === GSSAPI === */
897
898 #ifdef ENABLE_GSS
899
900 /*
901 * Establish a GSSAPI-encrypted connection.
902 */
903 extern PostgresPollingStatusType pqsecure_open_gss(PGconn *conn);
904
905 /*
906 * Read and write functions for GSSAPI-encrypted connections, with internal
907 * buffering to handle nonblocking sockets.
908 */
909 extern ssize_t pg_GSS_write(PGconn *conn, const void *ptr, size_t len);
910 extern ssize_t pg_GSS_read(PGconn *conn, void *ptr, size_t len);
911 extern ssize_t pg_GSS_bytes_pending(PGconn *conn);
912 #endif
913
914 /* === in fe-trace.c === */
915
916 extern void pqTraceOutputMessage(PGconn *conn, const char *message,
917 bool toServer);
918 extern void pqTraceOutputNoTypeByteMessage(PGconn *conn, const char *message);
919 extern void pqTraceOutputCharResponse(PGconn *conn, const char *responseType,
920 char response);
921
922 /* === miscellaneous macros === */
923
924 /*
925 * Reset the conn's error-reporting state.
926 */
927 #define pqClearConnErrorState(conn) \
928 (resetPQExpBuffer(&(conn)->errorMessage), \
929 (conn)->errorReported = 0)
930
931 /*
932 * Check whether we have a PGresult pending to be returned --- either a
933 * constructed one in conn->result, or a "virtual" error result that we
934 * don't intend to materialize until the end of the query cycle.
935 */
936 #define pgHavePendingResult(conn) \
937 ((conn)->result != NULL || (conn)->error_result)
938
939 /*
940 * this is so that we can check if a connection is non-blocking internally
941 * without the overhead of a function call
942 */
943 #define pqIsnonblocking(conn) ((conn)->nonblocking)
944
945 /*
946 * Connection's outbuffer threshold, for pipeline mode.
947 */
948 #define OUTBUFFER_THRESHOLD 65536
949
950 #ifdef ENABLE_NLS
951 extern char *libpq_gettext(const char *msgid) pg_attribute_format_arg(1);
952 extern char *libpq_ngettext(const char *msgid, const char *msgid_plural, unsigned long n) pg_attribute_format_arg(1) pg_attribute_format_arg(2);
953 #else
954 #define libpq_gettext(x) (x)
955 #define libpq_ngettext(s, p, n) ((n) == 1 ? (s) : (p))
956 #endif
957 /*
958 * libpq code should use the above, not _(), since that would use the
959 * surrounding programs's message catalog.
960 */
961 #undef _
962
963 extern void libpq_append_error(PQExpBuffer errorMessage, const char *fmt,...) pg_attribute_printf(2, 3);
964 extern void libpq_append_conn_error(PGconn *conn, const char *fmt,...) pg_attribute_printf(2, 3);
965
966 /*
967 * These macros are needed to let error-handling code be portable between
968 * Unix and Windows. (ugh)
969 */
970 #ifdef WIN32
971 #define SOCK_ERRNO (WSAGetLastError())
972 #define SOCK_STRERROR winsock_strerror
973 #define SOCK_ERRNO_SET(e) WSASetLastError(e)
974 #else
975 #define SOCK_ERRNO errno
976 #define SOCK_STRERROR strerror_r
977 #define SOCK_ERRNO_SET(e) (errno = (e))
978 #endif
979
980 #endif /* LIBPQ_INT_H */