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-2009, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
15 * $PostgreSQL: pgsql/src/interfaces/libpq/libpq-int.h,v 1.140 2009/04/19 22:37:13 tgl Exp $
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>
82 * POSTGRES backend dependent Constants.
84 #define CMDSTATUS_LEN 64 /* should match COMPLETION_TAG_BUFSIZE */
87 * PGresult and the subsidiary types PGresAttDesc, PGresAttValue
88 * represent the result of a query (or more precisely, of a single SQL
89 * command --- a query string given to PQexec can contain multiple commands).
90 * Note we assume that a single command can return at most one tuple group,
91 * hence there is no need for multiple descriptor sets.
94 /* Subsidiary-storage management structure for PGresult.
95 * See space management routines in fe-exec.c for details.
96 * Note that space[k] refers to the k'th byte starting from the physical
97 * head of the block --- it's a union, not a struct!
99 typedef union pgresult_data PGresult_data;
103 PGresult_data *next; /* link to next block, or NULL */
104 char space[1]; /* dummy for accessing block as bytes */
107 /* Data about a single parameter of a prepared statement */
108 typedef struct pgresParamDesc
110 Oid typid; /* type id */
114 * Data for a single attribute of a single tuple
116 * We use char* for Attribute values.
118 * The value pointer always points to a null-terminated area; we add a
119 * null (zero) byte after whatever the backend sends us. This is only
120 * particularly useful for text values ... with a binary value, the
121 * value might have embedded nulls, so the application can't use C string
122 * operators on it. But we add a null anyway for consistency.
123 * Note that the value itself does not contain a length word.
125 * A NULL attribute is a special case in two ways: its len field is NULL_LEN
126 * and its value field points to null_field in the owning PGresult. All the
127 * NULL attributes in a query result point to the same place (there's no need
128 * to store a null string separately for each one).
131 #define NULL_LEN (-1) /* pg_result len for NULL value */
133 typedef struct pgresAttValue
135 int len; /* length in bytes of the value */
136 char *value; /* actual value, plus terminating zero byte */
139 /* Typedef for message-field list entries */
140 typedef struct pgMessageField
142 struct pgMessageField *next; /* list link */
143 char code; /* field code */
144 char contents[1]; /* field value (VARIABLE LENGTH) */
147 /* Fields needed for notice handling */
150 PQnoticeReceiver noticeRec; /* notice message receiver */
152 PQnoticeProcessor noticeProc; /* notice message processor */
156 typedef struct PGEvent
158 PGEventProc proc; /* the function to call on events */
159 char *name; /* used only for error messages */
160 void *passThrough; /* pointer supplied at registration time */
161 void *data; /* optional state (instance) data */
162 bool resultInitialized; /* T if RESULTCREATE/COPY succeeded */
169 PGresAttDesc *attDescs;
170 PGresAttValue **tuples; /* each PGresTuple is an array of
172 int tupArrSize; /* allocated size of tuples array */
174 PGresParamDesc *paramDescs;
175 ExecStatusType resultStatus;
176 char cmdStatus[CMDSTATUS_LEN]; /* cmd status from the query */
177 int binary; /* binary tuple values if binary == 1,
181 * These fields are copied from the originating PGconn, so that operations
182 * on the PGresult don't have to reference the PGconn.
184 PGNoticeHooks noticeHooks;
187 int client_encoding; /* encoding id */
190 * Error information (all NULL if not an error result). errMsg is the
191 * "overall" error message returned by PQresultErrorMessage. If we have
192 * per-field info then it is stored in a linked list.
194 char *errMsg; /* error message, or NULL if no error */
195 PGMessageField *errFields; /* message broken into fields */
197 /* All NULL attributes in the query result point to this null string */
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.
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 */
210 /* PGAsyncStatusType defines the state of the query-execution state machine */
213 PGASYNC_IDLE, /* nothing's happening, dude */
214 PGASYNC_BUSY, /* query in progress */
215 PGASYNC_READY, /* result ready for PQgetResult */
216 PGASYNC_COPY_IN, /* Copy In data transfer in progress */
217 PGASYNC_COPY_OUT /* Copy Out data transfer in progress */
220 /* PGQueryClass tracks which query protocol we are now executing */
223 PGQUERY_SIMPLE, /* simple Query protocol (PQexec) */
224 PGQUERY_EXTENDED, /* full Extended protocol (PQexecParams) */
225 PGQUERY_PREPARE, /* Parse only (PQprepare) */
226 PGQUERY_DESCRIBE /* Describe Statement or Portal */
229 /* PGSetenvStatusType defines the state of the PQSetenv state machine */
230 /* (this is used only for 2.0-protocol connections) */
233 SETENV_STATE_OPTION_SEND, /* About to send an Environment Option */
234 SETENV_STATE_OPTION_WAIT, /* Waiting for above send to complete */
235 SETENV_STATE_QUERY1_SEND, /* About to send a status query */
236 SETENV_STATE_QUERY1_WAIT, /* Waiting for query to complete */
237 SETENV_STATE_QUERY2_SEND, /* About to send a status query */
238 SETENV_STATE_QUERY2_WAIT, /* Waiting for query to complete */
240 } PGSetenvStatusType;
242 /* Typedef for the EnvironmentOptions[] array */
243 typedef struct PQEnvironmentOption
245 const char *envName, /* name of an environment variable */
246 *pgName; /* name of corresponding SET variable */
247 } PQEnvironmentOption;
249 /* Typedef for parameter-status list entries */
250 typedef struct pgParameterStatus
252 struct pgParameterStatus *next; /* list link */
253 char *name; /* parameter name */
254 char *value; /* parameter value */
255 /* Note: name and value are stored in same malloc block as struct is */
258 /* large-object-access data ... allocated only if large-object code is used. */
259 typedef struct pgLobjfuncs
261 Oid fn_lo_open; /* OID of backend function lo_open */
262 Oid fn_lo_close; /* OID of backend function lo_close */
263 Oid fn_lo_creat; /* OID of backend function lo_creat */
264 Oid fn_lo_create; /* OID of backend function lo_create */
265 Oid fn_lo_unlink; /* OID of backend function lo_unlink */
266 Oid fn_lo_lseek; /* OID of backend function lo_lseek */
267 Oid fn_lo_tell; /* OID of backend function lo_tell */
268 Oid fn_lo_truncate; /* OID of backend function lo_truncate */
269 Oid fn_lo_read; /* OID of backend function LOread */
270 Oid fn_lo_write; /* OID of backend function LOwrite */
274 * PGconn stores all the state data associated with a single connection
279 /* Saved values of connection options */
280 char *pghost; /* the machine on which the server is running */
281 char *pghostaddr; /* the IPv4 address of the machine on which
282 * the server is running, in IPv4
283 * numbers-and-dots notation. Takes precedence
285 char *pgport; /* the server's communication port */
286 char *pgunixsocket; /* the Unix-domain socket that the server is
287 * listening on; if NULL, uses a default
288 * constructed from pgport */
289 char *pgtty; /* tty on which the backend messages is
290 * displayed (OBSOLETE, NOT USED) */
291 char *connect_timeout; /* connection timeout (numeric string) */
292 char *pgoptions; /* options to start the backend with */
293 char *dbName; /* database name */
294 char *pguser; /* Postgres username and password, if any */
296 char *sslmode; /* SSL mode (require,prefer,allow,disable) */
297 char *sslverify; /* Verify server SSL certificate (none,chain,cn) */
298 char *sslkey; /* client key filename */
299 char *sslcert; /* client certificate filename */
300 char *sslrootcert; /* root certificate filename */
301 char *sslcrl; /* certificate revocation list filename */
303 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
304 char *krbsrvname; /* Kerberos service name */
307 /* Optional file to write trace info to */
310 /* Callback procedures for notice message processing */
311 PGNoticeHooks noticeHooks;
313 /* Event procs registered via PQregisterEventProc */
314 PGEvent *events; /* expandable array of event data */
315 int nEvents; /* number of active events */
316 int eventArraySize; /* allocated array size */
318 /* Status indicators */
319 ConnStatusType status;
320 PGAsyncStatusType asyncStatus;
321 PGTransactionStatusType xactStatus; /* never changes to ACTIVE */
322 PGQueryClass queryclass;
323 char *last_query; /* last SQL command, or NULL if unknown */
324 bool options_valid; /* true if OK to attempt connection */
325 bool nonblocking; /* whether this connection is using nonblock
326 * sending semantics */
327 char copy_is_binary; /* 1 = copy binary, 0 = copy text */
328 int copy_already_done; /* # bytes already returned in COPY
330 PGnotify *notifyHead; /* oldest unreported Notify msg */
331 PGnotify *notifyTail; /* newest unreported Notify msg */
333 /* Connection data */
334 int sock; /* Unix FD for socket, -1 if not connected */
335 SockAddr laddr; /* Local address */
336 SockAddr raddr; /* Remote address */
337 ProtocolVersion pversion; /* FE/BE protocol version in use */
338 int sversion; /* server version, e.g. 70401 for 7.4.1 */
339 bool password_needed; /* true if server demanded a password */
341 /* Transient state needed while establishing connection */
342 struct addrinfo *addrlist; /* list of possible backend addresses */
343 struct addrinfo *addr_cur; /* the one currently being tried */
344 int addrlist_family; /* needed to know how to free addrlist */
345 PGSetenvStatusType setenv_state; /* for 2.0 protocol only */
346 const PQEnvironmentOption *next_eo;
348 /* Miscellaneous stuff */
349 int be_pid; /* PID of backend --- needed for cancels */
350 int be_key; /* key of backend --- needed for cancels */
351 char md5Salt[4]; /* password salt received from backend */
352 pgParameterStatus *pstatus; /* ParameterStatus data */
353 int client_encoding; /* encoding id */
354 bool std_strings; /* standard_conforming_strings */
355 PGVerbosity verbosity; /* error/notice message verbosity */
356 PGlobjfuncs *lobjfuncs; /* private state for large-object access fns */
358 /* Buffer for data received from backend and not yet processed */
359 char *inBuffer; /* currently allocated buffer */
360 int inBufSize; /* allocated size of buffer */
361 int inStart; /* offset to first unconsumed data in buffer */
362 int inCursor; /* next byte to tentatively consume */
363 int inEnd; /* offset to first position after avail data */
365 /* Buffer for data not yet sent to backend */
366 char *outBuffer; /* currently allocated buffer */
367 int outBufSize; /* allocated size of buffer */
368 int outCount; /* number of chars waiting in buffer */
370 /* State for constructing messages in outBuffer */
371 int outMsgStart; /* offset to msg start (length word); if -1,
372 * msg has no length word */
373 int outMsgEnd; /* offset to msg end (so far) */
375 /* Status for asynchronous result construction */
376 PGresult *result; /* result being constructed */
377 PGresAttValue *curTuple; /* tuple currently being read */
380 bool allow_ssl_try; /* Allowed to try SSL negotiation */
381 bool wait_ssl_try; /* Delay SSL negotiation until after
382 * attempting normal connection */
383 SSL *ssl; /* SSL status, if have SSL connection */
384 X509 *peer; /* X509 cert of server */
385 char peer_dn[256 + 1]; /* peer distinguished name */
386 char peer_cn[SM_USER + 1]; /* peer common name */
390 gss_ctx_id_t gctx; /* GSS context */
391 gss_name_t gtarg_nam; /* GSS target name */
392 gss_buffer_desc ginbuf; /* GSS input token */
393 gss_buffer_desc goutbuf; /* GSS output token */
398 gss_buffer_desc ginbuf; /* GSS input token */
400 char *gsslib; /* What GSS librart to use ("gssapi" or
403 CredHandle *sspicred; /* SSPI credentials handle */
404 CtxtHandle *sspictx; /* SSPI context */
405 char *sspitarget; /* SSPI target name */
406 int usesspi; /* Indicate if SSPI is in use on the
411 /* Buffer for current error message */
412 PQExpBufferData errorMessage; /* expansible string */
414 /* Buffer for receiving various parts of messages */
415 PQExpBufferData workBuffer; /* expansible string */
418 /* PGcancel stores all data necessary to cancel a connection. A copy of this
419 * data is required to safely cancel a connection running on a different
424 SockAddr raddr; /* Remote address */
425 int be_pid; /* PID of backend --- needed for cancels */
426 int be_key; /* key of backend --- needed for cancels */
430 /* String descriptions of the ExecStatusTypes.
431 * direct use of this array is deprecated; call PQresStatus() instead.
433 extern char *const pgresStatus[];
436 * Internal functions of libpq
437 * Functions declared here need to be visible across files of libpq,
438 * but are not intended to be called by applications. We use the
439 * convention "pqXXX" for internal functions, vs. the "PQxxx" names
440 * used for application-visible routines.
444 /* === in fe-connect.c === */
446 extern int pqPacketSend(PGconn *conn, char pack_type,
447 const void *buf, size_t buf_len);
448 extern bool pqGetHomeDirectory(char *buf, int bufsize);
450 #ifdef ENABLE_THREAD_SAFETY
451 extern pgthreadlock_t pg_g_threadlock;
453 #define PGTHREAD_ERROR(msg) \
455 fprintf(stderr, "%s\n", msg); \
460 #define pglock_thread() pg_g_threadlock(true)
461 #define pgunlock_thread() pg_g_threadlock(false)
463 #define pglock_thread() ((void) 0)
464 #define pgunlock_thread() ((void) 0)
467 /* === in fe-exec.c === */
469 extern void pqSetResultError(PGresult *res, const char *msg);
470 extern void pqCatenateResultError(PGresult *res, const char *msg);
471 extern void *pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary);
472 extern char *pqResultStrdup(PGresult *res, const char *str);
473 extern void pqClearAsyncResult(PGconn *conn);
474 extern void pqSaveErrorResult(PGconn *conn);
475 extern PGresult *pqPrepareAsyncResult(PGconn *conn);
477 pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
478 /* This lets gcc check the format string for consistency. */
479 __attribute__((format(printf, 2, 3)));
480 extern int pqAddTuple(PGresult *res, PGresAttValue *tup);
481 extern void pqSaveMessageField(PGresult *res, char code,
483 extern void pqSaveParameterStatus(PGconn *conn, const char *name,
485 extern void pqHandleSendFailure(PGconn *conn);
487 /* === in fe-protocol2.c === */
489 extern PostgresPollingStatusType pqSetenvPoll(PGconn *conn);
491 extern char *pqBuildStartupPacket2(PGconn *conn, int *packetlen,
492 const PQEnvironmentOption *options);
493 extern void pqParseInput2(PGconn *conn);
494 extern int pqGetCopyData2(PGconn *conn, char **buffer, int async);
495 extern int pqGetline2(PGconn *conn, char *s, int maxlen);
496 extern int pqGetlineAsync2(PGconn *conn, char *buffer, int bufsize);
497 extern int pqEndcopy2(PGconn *conn);
498 extern PGresult *pqFunctionCall2(PGconn *conn, Oid fnid,
499 int *result_buf, int *actual_result_len,
501 const PQArgBlock *args, int nargs);
503 /* === in fe-protocol3.c === */
505 extern char *pqBuildStartupPacket3(PGconn *conn, int *packetlen,
506 const PQEnvironmentOption *options);
507 extern void pqParseInput3(PGconn *conn);
508 extern int pqGetErrorNotice3(PGconn *conn, bool isError);
509 extern int pqGetCopyData3(PGconn *conn, char **buffer, int async);
510 extern int pqGetline3(PGconn *conn, char *s, int maxlen);
511 extern int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize);
512 extern int pqEndcopy3(PGconn *conn);
513 extern PGresult *pqFunctionCall3(PGconn *conn, Oid fnid,
514 int *result_buf, int *actual_result_len,
516 const PQArgBlock *args, int nargs);
518 /* === in fe-misc.c === */
521 * "Get" and "Put" routines return 0 if successful, EOF if not. Note that for
522 * Get, EOF merely means the buffer is exhausted, not that there is
523 * necessarily any error.
525 extern int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn);
526 extern int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn);
527 extern int pqGetc(char *result, PGconn *conn);
528 extern int pqPutc(char c, PGconn *conn);
529 extern int pqGets(PQExpBuffer buf, PGconn *conn);
530 extern int pqGets_append(PQExpBuffer buf, PGconn *conn);
531 extern int pqPuts(const char *s, PGconn *conn);
532 extern int pqGetnchar(char *s, size_t len, PGconn *conn);
533 extern int pqPutnchar(const char *s, size_t len, PGconn *conn);
534 extern int pqGetInt(int *result, size_t bytes, PGconn *conn);
535 extern int pqPutInt(int value, size_t bytes, PGconn *conn);
536 extern int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn);
537 extern int pqPutMsgEnd(PGconn *conn);
538 extern int pqReadData(PGconn *conn);
539 extern int pqFlush(PGconn *conn);
540 extern int pqWait(int forRead, int forWrite, PGconn *conn);
541 extern int pqWaitTimed(int forRead, int forWrite, PGconn *conn,
543 extern int pqReadReady(PGconn *conn);
544 extern int pqWriteReady(PGconn *conn);
546 /* === in fe-secure.c === */
548 extern int pqsecure_initialize(PGconn *);
549 extern void pqsecure_destroy(void);
550 extern PostgresPollingStatusType pqsecure_open_client(PGconn *);
551 extern void pqsecure_close(PGconn *);
552 extern ssize_t pqsecure_read(PGconn *, void *ptr, size_t len);
553 extern ssize_t pqsecure_write(PGconn *, const void *ptr, size_t len);
555 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
556 extern int pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending);
557 extern void pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending,
562 * this is so that we can check if a connection is non-blocking internally
563 * without the overhead of a function call
565 #define pqIsnonblocking(conn) ((conn)->nonblocking)
569 libpq_gettext(const char *msgid)
570 __attribute__((format_arg(1)));
572 #define libpq_gettext(x) (x)
576 * These macros are needed to let error-handling code be portable between
577 * Unix and Windows. (ugh)
580 #define SOCK_ERRNO (WSAGetLastError())
581 #define SOCK_STRERROR winsock_strerror
582 #define SOCK_ERRNO_SET(e) WSASetLastError(e)
584 #define SOCK_ERRNO errno
585 #define SOCK_STRERROR pqStrerror
586 #define SOCK_ERRNO_SET(e) (errno = (e))
589 #endif /* LIBPQ_INT_H */