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-2014, 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 "postgres_fe.h"
25 #include "libpq-events.h"
28 #include <sys/types.h>
33 #ifdef ENABLE_THREAD_SAFETY
35 #include "pthread-win32.h"
42 /* include stuff common to fe and be */
43 #include "getaddrinfo.h"
44 #include "libpq/pqcomm.h"
45 /* include stuff found in fe only */
46 #include "pqexpbuffer.h"
49 #if defined(HAVE_GSSAPI_H)
52 #include <gssapi/gssapi.h>
57 #define SECURITY_WIN32
58 #if defined(WIN32) && !defined(WIN32_ONLY_COMPILER)
66 * Define a fake structure compatible with GSSAPI on Unix.
74 #endif /* ENABLE_SSPI */
77 #include <openssl/ssl.h>
78 #include <openssl/err.h>
80 #if (SSLEAY_VERSION_NUMBER >= 0x00907000L) && !defined(OPENSSL_NO_ENGINE)
81 #define USE_SSL_ENGINE
86 * POSTGRES backend dependent Constants.
88 #define CMDSTATUS_LEN 64 /* should match COMPLETION_TAG_BUFSIZE */
91 * PGresult and the subsidiary types PGresAttDesc, PGresAttValue
92 * represent the result of a query (or more precisely, of a single SQL
93 * command --- a query string given to PQexec can contain multiple commands).
94 * Note we assume that a single command can return at most one tuple group,
95 * hence there is no need for multiple descriptor sets.
98 /* Subsidiary-storage management structure for PGresult.
99 * See space management routines in fe-exec.c for details.
100 * Note that space[k] refers to the k'th byte starting from the physical
101 * head of the block --- it's a union, not a struct!
103 typedef union pgresult_data PGresult_data;
107 PGresult_data *next; /* link to next block, or NULL */
108 char space[1]; /* dummy for accessing block as bytes */
111 /* Data about a single parameter of a prepared statement */
112 typedef struct pgresParamDesc
114 Oid typid; /* type id */
118 * Data for a single attribute of a single tuple
120 * We use char* for Attribute values.
122 * The value pointer always points to a null-terminated area; we add a
123 * null (zero) byte after whatever the backend sends us. This is only
124 * particularly useful for text values ... with a binary value, the
125 * value might have embedded nulls, so the application can't use C string
126 * operators on it. But we add a null anyway for consistency.
127 * Note that the value itself does not contain a length word.
129 * A NULL attribute is a special case in two ways: its len field is NULL_LEN
130 * and its value field points to null_field in the owning PGresult. All the
131 * NULL attributes in a query result point to the same place (there's no need
132 * to store a null string separately for each one).
135 #define NULL_LEN (-1) /* pg_result len for NULL value */
137 typedef struct pgresAttValue
139 int len; /* length in bytes of the value */
140 char *value; /* actual value, plus terminating zero byte */
143 /* Typedef for message-field list entries */
144 typedef struct pgMessageField
146 struct pgMessageField *next; /* list link */
147 char code; /* field code */
148 char contents[1]; /* field value (VARIABLE LENGTH) */
151 /* Fields needed for notice handling */
154 PQnoticeReceiver noticeRec; /* notice message receiver */
156 PQnoticeProcessor noticeProc; /* notice message processor */
160 typedef struct PGEvent
162 PGEventProc proc; /* the function to call on events */
163 char *name; /* used only for error messages */
164 void *passThrough; /* pointer supplied at registration time */
165 void *data; /* optional state (instance) data */
166 bool resultInitialized; /* T if RESULTCREATE/COPY succeeded */
173 PGresAttDesc *attDescs;
174 PGresAttValue **tuples; /* each PGresTuple is an array of
176 int tupArrSize; /* allocated size of tuples array */
178 PGresParamDesc *paramDescs;
179 ExecStatusType resultStatus;
180 char cmdStatus[CMDSTATUS_LEN]; /* cmd status from the query */
181 int binary; /* binary tuple values if binary == 1,
185 * These fields are copied from the originating PGconn, so that operations
186 * on the PGresult don't have to reference the PGconn.
188 PGNoticeHooks noticeHooks;
191 int client_encoding; /* encoding id */
194 * Error information (all NULL if not an error result). errMsg is the
195 * "overall" error message returned by PQresultErrorMessage. If we have
196 * per-field info then it is stored in a linked list.
198 char *errMsg; /* error message, or NULL if no error */
199 PGMessageField *errFields; /* message broken into fields */
201 /* All NULL attributes in the query result point to this null string */
205 * Space management information. Note that attDescs and error stuff, if
206 * not null, point into allocated blocks. But tuples points to a
207 * separately malloc'd block, so that we can realloc it.
209 PGresult_data *curBlock; /* most recently allocated block */
210 int curOffset; /* start offset of free space in block */
211 int spaceLeft; /* number of free bytes remaining in block */
214 /* PGAsyncStatusType defines the state of the query-execution state machine */
217 PGASYNC_IDLE, /* nothing's happening, dude */
218 PGASYNC_BUSY, /* query in progress */
219 PGASYNC_READY, /* result ready for PQgetResult */
220 PGASYNC_COPY_IN, /* Copy In data transfer in progress */
221 PGASYNC_COPY_OUT, /* Copy Out data transfer in progress */
222 PGASYNC_COPY_BOTH /* Copy In/Out data transfer in progress */
225 /* PGQueryClass tracks which query protocol we are now executing */
228 PGQUERY_SIMPLE, /* simple Query protocol (PQexec) */
229 PGQUERY_EXTENDED, /* full Extended protocol (PQexecParams) */
230 PGQUERY_PREPARE, /* Parse only (PQprepare) */
231 PGQUERY_DESCRIBE /* Describe Statement or Portal */
234 /* PGSetenvStatusType defines the state of the PQSetenv state machine */
235 /* (this is used only for 2.0-protocol connections) */
238 SETENV_STATE_CLIENT_ENCODING_SEND, /* About to send an Environment Option */
239 SETENV_STATE_CLIENT_ENCODING_WAIT, /* Waiting for above send to complete */
240 SETENV_STATE_OPTION_SEND, /* About to send an Environment Option */
241 SETENV_STATE_OPTION_WAIT, /* Waiting for above send to complete */
242 SETENV_STATE_QUERY1_SEND, /* About to send a status query */
243 SETENV_STATE_QUERY1_WAIT, /* Waiting for query to complete */
244 SETENV_STATE_QUERY2_SEND, /* About to send a status query */
245 SETENV_STATE_QUERY2_WAIT, /* Waiting for query to complete */
247 } PGSetenvStatusType;
249 /* Typedef for the EnvironmentOptions[] array */
250 typedef struct PQEnvironmentOption
252 const char *envName, /* name of an environment variable */
253 *pgName; /* name of corresponding SET variable */
254 } PQEnvironmentOption;
256 /* Typedef for parameter-status list entries */
257 typedef struct pgParameterStatus
259 struct pgParameterStatus *next; /* list link */
260 char *name; /* parameter name */
261 char *value; /* parameter value */
262 /* Note: name and value are stored in same malloc block as struct is */
265 /* large-object-access data ... allocated only if large-object code is used. */
266 typedef struct pgLobjfuncs
268 Oid fn_lo_open; /* OID of backend function lo_open */
269 Oid fn_lo_close; /* OID of backend function lo_close */
270 Oid fn_lo_creat; /* OID of backend function lo_creat */
271 Oid fn_lo_create; /* OID of backend function lo_create */
272 Oid fn_lo_unlink; /* OID of backend function lo_unlink */
273 Oid fn_lo_lseek; /* OID of backend function lo_lseek */
274 Oid fn_lo_lseek64; /* OID of backend function lo_lseek64 */
275 Oid fn_lo_tell; /* OID of backend function lo_tell */
276 Oid fn_lo_tell64; /* OID of backend function lo_tell64 */
277 Oid fn_lo_truncate; /* OID of backend function lo_truncate */
278 Oid fn_lo_truncate64; /* OID of function lo_truncate64 */
279 Oid fn_lo_read; /* OID of backend function LOread */
280 Oid fn_lo_write; /* OID of backend function LOwrite */
283 /* PGdataValue represents a data field value being passed to a row processor.
284 * It could be either text or binary data; text data is not zero-terminated.
285 * A SQL NULL is represented by len < 0; then value is still valid but there
286 * are no data bytes there.
288 typedef struct pgDataValue
290 int len; /* data length in bytes, or <0 if NULL */
291 const char *value; /* data value, without zero-termination */
295 * PGconn stores all the state data associated with a single connection
300 /* Saved values of connection options */
301 char *pghost; /* the machine on which the server is running */
302 char *pghostaddr; /* the numeric IP address of the machine on
303 * which the server is running. Takes
304 * precedence over above. */
305 char *pgport; /* the server's communication port */
306 char *pgunixsocket; /* the Unix-domain socket that the server is
307 * listening on; if NULL, uses a default
308 * constructed from pgport */
309 char *pgtty; /* tty on which the backend messages is
310 * displayed (OBSOLETE, NOT USED) */
311 char *connect_timeout; /* connection timeout (numeric string) */
312 char *client_encoding_initial; /* encoding to use */
313 char *pgoptions; /* options to start the backend with */
314 char *appname; /* application name */
315 char *fbappname; /* fallback application name */
316 char *dbName; /* database name */
317 char *replication; /* connect as the replication standby? */
318 char *pguser; /* Postgres username and password, if any */
320 char *keepalives; /* use TCP keepalives? */
321 char *keepalives_idle; /* time between TCP keepalives */
322 char *keepalives_interval; /* time between TCP keepalive
324 char *keepalives_count; /* maximum number of TCP keepalive
326 char *sslmode; /* SSL mode (require,prefer,allow,disable) */
327 char *sslcompression; /* SSL compression (0 or 1) */
328 char *sslkey; /* client key filename */
329 char *sslcert; /* client certificate filename */
330 char *sslrootcert; /* root certificate filename */
331 char *sslcrl; /* certificate revocation list filename */
332 char *requirepeer; /* required peer credentials for local sockets */
334 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
335 char *krbsrvname; /* Kerberos service name */
338 /* Optional file to write trace info to */
341 /* Callback procedures for notice message processing */
342 PGNoticeHooks noticeHooks;
344 /* Event procs registered via PQregisterEventProc */
345 PGEvent *events; /* expandable array of event data */
346 int nEvents; /* number of active events */
347 int eventArraySize; /* allocated array size */
349 /* Status indicators */
350 ConnStatusType status;
351 PGAsyncStatusType asyncStatus;
352 PGTransactionStatusType xactStatus; /* never changes to ACTIVE */
353 PGQueryClass queryclass;
354 char *last_query; /* last SQL command, or NULL if unknown */
355 char last_sqlstate[6]; /* last reported SQLSTATE */
356 bool options_valid; /* true if OK to attempt connection */
357 bool nonblocking; /* whether this connection is using nonblock
358 * sending semantics */
359 bool singleRowMode; /* return current query result row-by-row? */
360 char copy_is_binary; /* 1 = copy binary, 0 = copy text */
361 int copy_already_done; /* # bytes already returned in COPY
363 PGnotify *notifyHead; /* oldest unreported Notify msg */
364 PGnotify *notifyTail; /* newest unreported Notify msg */
366 /* Connection data */
367 /* See PQconnectPoll() for how we use 'int' and not 'pgsocket'. */
368 pgsocket sock; /* FD for socket, PGINVALID_SOCKET if unconnected */
369 SockAddr laddr; /* Local address */
370 SockAddr raddr; /* Remote address */
371 ProtocolVersion pversion; /* FE/BE protocol version in use */
372 int sversion; /* server version, e.g. 70401 for 7.4.1 */
373 bool auth_req_received; /* true if any type of auth req
375 bool password_needed; /* true if server demanded a password */
376 bool dot_pgpass_used; /* true if used .pgpass */
377 bool sigpipe_so; /* have we masked SIGPIPE via SO_NOSIGPIPE? */
378 bool sigpipe_flag; /* can we mask SIGPIPE via MSG_NOSIGNAL? */
380 /* Transient state needed while establishing connection */
381 struct addrinfo *addrlist; /* list of possible backend addresses */
382 struct addrinfo *addr_cur; /* the one currently being tried */
383 int addrlist_family; /* needed to know how to free addrlist */
384 PGSetenvStatusType setenv_state; /* for 2.0 protocol only */
385 const PQEnvironmentOption *next_eo;
386 bool send_appname; /* okay to send application_name? */
388 /* Miscellaneous stuff */
389 int be_pid; /* PID of backend --- needed for cancels */
390 int be_key; /* key of backend --- needed for cancels */
391 char md5Salt[4]; /* password salt received from backend */
392 pgParameterStatus *pstatus; /* ParameterStatus data */
393 int client_encoding; /* encoding id */
394 bool std_strings; /* standard_conforming_strings */
395 PGVerbosity verbosity; /* error/notice message verbosity */
396 PGlobjfuncs *lobjfuncs; /* private state for large-object access fns */
398 /* Buffer for data received from backend and not yet processed */
399 char *inBuffer; /* currently allocated buffer */
400 int inBufSize; /* allocated size of buffer */
401 int inStart; /* offset to first unconsumed data in buffer */
402 int inCursor; /* next byte to tentatively consume */
403 int inEnd; /* offset to first position after avail data */
405 /* Buffer for data not yet sent to backend */
406 char *outBuffer; /* currently allocated buffer */
407 int outBufSize; /* allocated size of buffer */
408 int outCount; /* number of chars waiting in buffer */
410 /* State for constructing messages in outBuffer */
411 int outMsgStart; /* offset to msg start (length word); if -1,
412 * msg has no length word */
413 int outMsgEnd; /* offset to msg end (so far) */
415 /* Row processor interface workspace */
416 PGdataValue *rowBuf; /* array for passing values to rowProcessor */
417 int rowBufLen; /* number of entries allocated in rowBuf */
419 /* Status for asynchronous result construction */
420 PGresult *result; /* result being constructed */
421 PGresult *next_result; /* next result (used in single-row mode) */
423 /* Assorted state for SSL, GSS, etc */
426 bool allow_ssl_try; /* Allowed to try SSL negotiation */
427 bool wait_ssl_try; /* Delay SSL negotiation until after
428 * attempting normal connection */
429 SSL *ssl; /* SSL status, if have SSL connection */
430 X509 *peer; /* X509 cert of server */
431 #ifdef USE_SSL_ENGINE
432 ENGINE *engine; /* SSL engine, if any */
434 void *engine; /* dummy field to keep struct the same if
435 * OpenSSL version changes */
440 gss_ctx_id_t gctx; /* GSS context */
441 gss_name_t gtarg_nam; /* GSS target name */
442 gss_buffer_desc ginbuf; /* GSS input token */
443 gss_buffer_desc goutbuf; /* GSS output token */
448 gss_buffer_desc ginbuf; /* GSS input token */
450 char *gsslib; /* What GSS librart to use ("gssapi" or
453 CredHandle *sspicred; /* SSPI credentials handle */
454 CtxtHandle *sspictx; /* SSPI context */
455 char *sspitarget; /* SSPI target name */
456 int usesspi; /* Indicate if SSPI is in use on the
460 /* Buffer for current error message */
461 PQExpBufferData errorMessage; /* expansible string */
463 /* Buffer for receiving various parts of messages */
464 PQExpBufferData workBuffer; /* expansible string */
467 /* PGcancel stores all data necessary to cancel a connection. A copy of this
468 * data is required to safely cancel a connection running on a different
473 SockAddr raddr; /* Remote address */
474 int be_pid; /* PID of backend --- needed for cancels */
475 int be_key; /* key of backend --- needed for cancels */
479 /* String descriptions of the ExecStatusTypes.
480 * direct use of this array is deprecated; call PQresStatus() instead.
482 extern char *const pgresStatus[];
485 * Internal functions of libpq
486 * Functions declared here need to be visible across files of libpq,
487 * but are not intended to be called by applications. We use the
488 * convention "pqXXX" for internal functions, vs. the "PQxxx" names
489 * used for application-visible routines.
493 /* === in fe-connect.c === */
495 extern void pqDropConnection(PGconn *conn);
496 extern int pqPacketSend(PGconn *conn, char pack_type,
497 const void *buf, size_t buf_len);
498 extern bool pqGetHomeDirectory(char *buf, int bufsize);
500 #ifdef ENABLE_THREAD_SAFETY
501 extern pgthreadlock_t pg_g_threadlock;
503 #define PGTHREAD_ERROR(msg) \
505 fprintf(stderr, "%s\n", msg); \
510 #define pglock_thread() pg_g_threadlock(true)
511 #define pgunlock_thread() pg_g_threadlock(false)
513 #define pglock_thread() ((void) 0)
514 #define pgunlock_thread() ((void) 0)
517 /* === in fe-exec.c === */
519 extern void pqSetResultError(PGresult *res, const char *msg);
520 extern void pqCatenateResultError(PGresult *res, const char *msg);
521 extern void *pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary);
522 extern char *pqResultStrdup(PGresult *res, const char *str);
523 extern void pqClearAsyncResult(PGconn *conn);
524 extern void pqSaveErrorResult(PGconn *conn);
525 extern PGresult *pqPrepareAsyncResult(PGconn *conn);
527 pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
528 /* This lets gcc check the format string for consistency. */
529 __attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 3)));
530 extern void pqSaveMessageField(PGresult *res, char code,
532 extern void pqSaveParameterStatus(PGconn *conn, const char *name,
534 extern int pqRowProcessor(PGconn *conn, const char **errmsgp);
535 extern void pqHandleSendFailure(PGconn *conn);
537 /* === in fe-protocol2.c === */
539 extern PostgresPollingStatusType pqSetenvPoll(PGconn *conn);
541 extern char *pqBuildStartupPacket2(PGconn *conn, int *packetlen,
542 const PQEnvironmentOption *options);
543 extern void pqParseInput2(PGconn *conn);
544 extern int pqGetCopyData2(PGconn *conn, char **buffer, int async);
545 extern int pqGetline2(PGconn *conn, char *s, int maxlen);
546 extern int pqGetlineAsync2(PGconn *conn, char *buffer, int bufsize);
547 extern int pqEndcopy2(PGconn *conn);
548 extern PGresult *pqFunctionCall2(PGconn *conn, Oid fnid,
549 int *result_buf, int *actual_result_len,
551 const PQArgBlock *args, int nargs);
553 /* === in fe-protocol3.c === */
555 extern char *pqBuildStartupPacket3(PGconn *conn, int *packetlen,
556 const PQEnvironmentOption *options);
557 extern void pqParseInput3(PGconn *conn);
558 extern int pqGetErrorNotice3(PGconn *conn, bool isError);
559 extern int pqGetCopyData3(PGconn *conn, char **buffer, int async);
560 extern int pqGetline3(PGconn *conn, char *s, int maxlen);
561 extern int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize);
562 extern int pqEndcopy3(PGconn *conn);
563 extern PGresult *pqFunctionCall3(PGconn *conn, Oid fnid,
564 int *result_buf, int *actual_result_len,
566 const PQArgBlock *args, int nargs);
568 /* === in fe-misc.c === */
571 * "Get" and "Put" routines return 0 if successful, EOF if not. Note that for
572 * Get, EOF merely means the buffer is exhausted, not that there is
573 * necessarily any error.
575 extern int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn);
576 extern int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn);
577 extern int pqGetc(char *result, PGconn *conn);
578 extern int pqPutc(char c, PGconn *conn);
579 extern int pqGets(PQExpBuffer buf, PGconn *conn);
580 extern int pqGets_append(PQExpBuffer buf, PGconn *conn);
581 extern int pqPuts(const char *s, PGconn *conn);
582 extern int pqGetnchar(char *s, size_t len, PGconn *conn);
583 extern int pqSkipnchar(size_t len, PGconn *conn);
584 extern int pqPutnchar(const char *s, size_t len, PGconn *conn);
585 extern int pqGetInt(int *result, size_t bytes, PGconn *conn);
586 extern int pqPutInt(int value, size_t bytes, PGconn *conn);
587 extern int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn);
588 extern int pqPutMsgEnd(PGconn *conn);
589 extern int pqReadData(PGconn *conn);
590 extern int pqFlush(PGconn *conn);
591 extern int pqWait(int forRead, int forWrite, PGconn *conn);
592 extern int pqWaitTimed(int forRead, int forWrite, PGconn *conn,
594 extern int pqReadReady(PGconn *conn);
595 extern int pqWriteReady(PGconn *conn);
597 /* === in fe-secure.c === */
599 extern int pqsecure_initialize(PGconn *);
600 extern void pqsecure_destroy(void);
601 extern PostgresPollingStatusType pqsecure_open_client(PGconn *);
602 extern void pqsecure_close(PGconn *);
603 extern ssize_t pqsecure_read(PGconn *, void *ptr, size_t len);
604 extern ssize_t pqsecure_write(PGconn *, const void *ptr, size_t len);
606 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
607 extern int pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending);
608 extern void pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending,
613 * this is so that we can check if a connection is non-blocking internally
614 * without the overhead of a function call
616 #define pqIsnonblocking(conn) ((conn)->nonblocking)
620 libpq_gettext(const char *msgid)
621 __attribute__((format_arg(1)));
623 #define libpq_gettext(x) (x)
627 * These macros are needed to let error-handling code be portable between
628 * Unix and Windows. (ugh)
631 #define SOCK_ERRNO (WSAGetLastError())
632 #define SOCK_STRERROR winsock_strerror
633 #define SOCK_ERRNO_SET(e) WSASetLastError(e)
635 #define SOCK_ERRNO errno
636 #define SOCK_STRERROR pqStrerror
637 #define SOCK_ERRNO_SET(e) (errno = (e))
640 #endif /* LIBPQ_INT_H */