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-2006, 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.112 2006/03/14 22:48:23 tgl Exp $
17 *-------------------------------------------------------------------------
23 /* We assume libpq-fe.h has already been included. */
24 #include "postgres_fe.h"
27 #include <sys/types.h>
32 #ifdef ENABLE_THREAD_SAFETY
34 #include "pthread-win32.h"
41 #ifdef WIN32_CLIENT_ONLY
42 typedef int ssize_t; /* ssize_t doesn't exist in VC (at least not
46 /* include stuff common to fe and be */
47 #include "getaddrinfo.h"
48 #include "libpq/pqcomm.h"
49 /* include stuff found in fe only */
50 #include "pqexpbuffer.h"
53 #include <openssl/ssl.h>
54 #include <openssl/err.h>
58 * POSTGRES backend dependent Constants.
60 #define PQERRORMSG_LENGTH 1024
61 #define CMDSTATUS_LEN 40
64 * PGresult and the subsidiary types PGresAttDesc, PGresAttValue
65 * represent the result of a query (or more precisely, of a single SQL
66 * command --- a query string given to PQexec can contain multiple commands).
67 * Note we assume that a single command can return at most one tuple group,
68 * hence there is no need for multiple descriptor sets.
71 /* Subsidiary-storage management structure for PGresult.
72 * See space management routines in fe-exec.c for details.
73 * Note that space[k] refers to the k'th byte starting from the physical
74 * head of the block --- it's a union, not a struct!
76 typedef union pgresult_data PGresult_data;
80 PGresult_data *next; /* link to next block, or NULL */
81 char space[1]; /* dummy for accessing block as bytes */
84 /* Data about a single attribute (column) of a query result */
86 typedef struct pgresAttDesc
88 char *name; /* column name */
89 Oid tableid; /* source table, if known */
90 int columnid; /* source column, if known */
91 int format; /* format code for value (text/binary) */
92 Oid typid; /* type id */
93 int typlen; /* type size */
94 int atttypmod; /* type-specific modifier info */
98 * Data for a single attribute of a single tuple
100 * We use char* for Attribute values.
102 * The value pointer always points to a null-terminated area; we add a
103 * null (zero) byte after whatever the backend sends us. This is only
104 * particularly useful for text values ... with a binary value, the
105 * value might have embedded nulls, so the application can't use C string
106 * operators on it. But we add a null anyway for consistency.
107 * Note that the value itself does not contain a length word.
109 * A NULL attribute is a special case in two ways: its len field is NULL_LEN
110 * and its value field points to null_field in the owning PGresult. All the
111 * NULL attributes in a query result point to the same place (there's no need
112 * to store a null string separately for each one).
115 #define NULL_LEN (-1) /* pg_result len for NULL value */
117 typedef struct pgresAttValue
119 int len; /* length in bytes of the value */
120 char *value; /* actual value, plus terminating zero byte */
123 /* Typedef for message-field list entries */
124 typedef struct pgMessageField
126 struct pgMessageField *next; /* list link */
127 char code; /* field code */
128 char contents[1]; /* field value (VARIABLE LENGTH) */
131 /* Fields needed for notice handling */
134 PQnoticeReceiver noticeRec; /* notice message receiver */
136 PQnoticeProcessor noticeProc; /* notice message processor */
144 PGresAttDesc *attDescs;
145 PGresAttValue **tuples; /* each PGresTuple is an array of
147 int tupArrSize; /* allocated size of tuples array */
148 ExecStatusType resultStatus;
149 char cmdStatus[CMDSTATUS_LEN]; /* cmd status from the query */
150 int binary; /* binary tuple values if binary == 1,
154 * These fields are copied from the originating PGconn, so that operations
155 * on the PGresult don't have to reference the PGconn.
157 PGNoticeHooks noticeHooks;
158 int client_encoding; /* encoding id */
161 * Error information (all NULL if not an error result). errMsg is the
162 * "overall" error message returned by PQresultErrorMessage. If we have
163 * per-field info then it is stored in a linked list.
165 char *errMsg; /* error message, or NULL if no error */
166 PGMessageField *errFields; /* message broken into fields */
168 /* All NULL attributes in the query result point to this null string */
172 * Space management information. Note that attDescs and error stuff, if
173 * not null, point into allocated blocks. But tuples points to a
174 * separately malloc'd block, so that we can realloc it.
176 PGresult_data *curBlock; /* most recently allocated block */
177 int curOffset; /* start offset of free space in block */
178 int spaceLeft; /* number of free bytes remaining in block */
181 /* PGAsyncStatusType defines the state of the query-execution state machine */
184 PGASYNC_IDLE, /* nothing's happening, dude */
185 PGASYNC_BUSY, /* query in progress */
186 PGASYNC_READY, /* result ready for PQgetResult */
187 PGASYNC_COPY_IN, /* Copy In data transfer in progress */
188 PGASYNC_COPY_OUT /* Copy Out data transfer in progress */
191 /* PGQueryClass tracks which query protocol we are now executing */
194 PGQUERY_SIMPLE, /* simple Query protocol (PQexec) */
195 PGQUERY_EXTENDED, /* full Extended protocol (PQexecParams) */
196 PGQUERY_PREPARE /* Parse only (PQprepare) */
199 /* PGSetenvStatusType defines the state of the PQSetenv state machine */
200 /* (this is used only for 2.0-protocol connections) */
203 SETENV_STATE_OPTION_SEND, /* About to send an Environment Option */
204 SETENV_STATE_OPTION_WAIT, /* Waiting for above send to complete */
205 SETENV_STATE_QUERY1_SEND, /* About to send a status query */
206 SETENV_STATE_QUERY1_WAIT, /* Waiting for query to complete */
207 SETENV_STATE_QUERY2_SEND, /* About to send a status query */
208 SETENV_STATE_QUERY2_WAIT, /* Waiting for query to complete */
210 } PGSetenvStatusType;
212 /* Typedef for the EnvironmentOptions[] array */
213 typedef struct PQEnvironmentOption
215 const char *envName, /* name of an environment variable */
216 *pgName; /* name of corresponding SET variable */
217 } PQEnvironmentOption;
219 /* Typedef for parameter-status list entries */
220 typedef struct pgParameterStatus
222 struct pgParameterStatus *next; /* list link */
223 char *name; /* parameter name */
224 char *value; /* parameter value */
225 /* Note: name and value are stored in same malloc block as struct is */
228 /* large-object-access data ... allocated only if large-object code is used. */
229 typedef struct pgLobjfuncs
231 Oid fn_lo_open; /* OID of backend function lo_open */
232 Oid fn_lo_close; /* OID of backend function lo_close */
233 Oid fn_lo_creat; /* OID of backend function lo_creat */
234 Oid fn_lo_create; /* OID of backend function lo_create */
235 Oid fn_lo_unlink; /* OID of backend function lo_unlink */
236 Oid fn_lo_lseek; /* OID of backend function lo_lseek */
237 Oid fn_lo_tell; /* OID of backend function lo_tell */
238 Oid fn_lo_read; /* OID of backend function LOread */
239 Oid fn_lo_write; /* OID of backend function LOwrite */
243 * PGconn stores all the state data associated with a single connection
248 /* Saved values of connection options */
249 char *pghost; /* the machine on which the server is running */
250 char *pghostaddr; /* the IPv4 address of the machine on which
251 * the server is running, in IPv4
252 * numbers-and-dots notation. Takes precedence
254 char *pgport; /* the server's communication port */
255 char *pgunixsocket; /* the Unix-domain socket that the server is
256 * listening on; if NULL, uses a default
257 * constructed from pgport */
258 char *pgtty; /* tty on which the backend messages is
259 * displayed (OBSOLETE, NOT USED) */
260 char *connect_timeout; /* connection timeout (numeric string) */
261 char *pgoptions; /* options to start the backend with */
262 char *dbName; /* database name */
263 char *pguser; /* Postgres username and password, if any */
265 char *sslmode; /* SSL mode (require,prefer,allow,disable) */
267 char *krbsrvname; /* Kerberos service name */
270 /* Optional file to write trace info to */
273 /* Callback procedures for notice message processing */
274 PGNoticeHooks noticeHooks;
276 /* Status indicators */
277 ConnStatusType status;
278 PGAsyncStatusType asyncStatus;
279 PGTransactionStatusType xactStatus; /* never changes to ACTIVE */
280 PGQueryClass queryclass;
281 char *last_query; /* last SQL command, or NULL if unknown */
282 bool options_valid; /* true if OK to attempt connection */
283 bool nonblocking; /* whether this connection is using nonblock
284 * sending semantics */
285 char copy_is_binary; /* 1 = copy binary, 0 = copy text */
286 int copy_already_done; /* # bytes already returned in COPY
288 PGnotify *notifyHead; /* oldest unreported Notify msg */
289 PGnotify *notifyTail; /* newest unreported Notify msg */
291 /* Connection data */
292 int sock; /* Unix FD for socket, -1 if not connected */
293 SockAddr laddr; /* Local address */
294 SockAddr raddr; /* Remote address */
295 ProtocolVersion pversion; /* FE/BE protocol version in use */
296 int sversion; /* server version, e.g. 70401 for 7.4.1 */
298 /* Transient state needed while establishing connection */
299 struct addrinfo *addrlist; /* list of possible backend addresses */
300 struct addrinfo *addr_cur; /* the one currently being tried */
301 int addrlist_family; /* needed to know how to free addrlist */
302 PGSetenvStatusType setenv_state; /* for 2.0 protocol only */
303 const PQEnvironmentOption *next_eo;
305 /* Miscellaneous stuff */
306 int be_pid; /* PID of backend --- needed for cancels */
307 int be_key; /* key of backend --- needed for cancels */
308 char md5Salt[4]; /* password salt received from backend */
309 char cryptSalt[2]; /* password salt received from backend */
310 pgParameterStatus *pstatus; /* ParameterStatus data */
311 int client_encoding; /* encoding id */
312 PGVerbosity verbosity; /* error/notice message verbosity */
313 PGlobjfuncs *lobjfuncs; /* private state for large-object access fns */
315 /* Buffer for data received from backend and not yet processed */
316 char *inBuffer; /* currently allocated buffer */
317 int inBufSize; /* allocated size of buffer */
318 int inStart; /* offset to first unconsumed data in buffer */
319 int inCursor; /* next byte to tentatively consume */
320 int inEnd; /* offset to first position after avail data */
322 /* Buffer for data not yet sent to backend */
323 char *outBuffer; /* currently allocated buffer */
324 int outBufSize; /* allocated size of buffer */
325 int outCount; /* number of chars waiting in buffer */
327 /* State for constructing messages in outBuffer */
328 int outMsgStart; /* offset to msg start (length word); if -1,
329 * msg has no length word */
330 int outMsgEnd; /* offset to msg end (so far) */
332 /* Status for asynchronous result construction */
333 PGresult *result; /* result being constructed */
334 PGresAttValue *curTuple; /* tuple currently being read */
337 bool allow_ssl_try; /* Allowed to try SSL negotiation */
338 bool wait_ssl_try; /* Delay SSL negotiation until after
339 * attempting normal connection */
340 SSL *ssl; /* SSL status, if have SSL connection */
341 X509 *peer; /* X509 cert of server */
342 char peer_dn[256 + 1]; /* peer distinguished name */
343 char peer_cn[SM_USER + 1]; /* peer common name */
346 /* Buffer for current error message */
347 PQExpBufferData errorMessage; /* expansible string */
349 /* Buffer for receiving various parts of messages */
350 PQExpBufferData workBuffer; /* expansible string */
353 /* PGcancel stores all data necessary to cancel a connection. A copy of this
354 * data is required to safely cancel a connection running on a different
359 SockAddr raddr; /* Remote address */
360 int be_pid; /* PID of backend --- needed for cancels */
361 int be_key; /* key of backend --- needed for cancels */
365 /* String descriptions of the ExecStatusTypes.
366 * direct use of this array is deprecated; call PQresStatus() instead.
368 extern char *const pgresStatus[];
371 * Internal functions of libpq
372 * Functions declared here need to be visible across files of libpq,
373 * but are not intended to be called by applications. We use the
374 * convention "pqXXX" for internal functions, vs. the "PQxxx" names
375 * used for application-visible routines.
379 /* === in fe-connect.c === */
381 extern int pqPacketSend(PGconn *conn, char pack_type,
382 const void *buf, size_t buf_len);
383 extern bool pqGetHomeDirectory(char *buf, int bufsize);
385 #ifdef ENABLE_THREAD_SAFETY
386 extern pgthreadlock_t pg_g_threadlock;
388 #define pglock_thread() pg_g_threadlock(true)
389 #define pgunlock_thread() pg_g_threadlock(false)
391 #define pglock_thread() ((void) 0)
392 #define pgunlock_thread() ((void) 0)
396 /* === in fe-exec.c === */
398 extern void pqSetResultError(PGresult *res, const char *msg);
399 extern void pqCatenateResultError(PGresult *res, const char *msg);
400 extern void *pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary);
401 extern char *pqResultStrdup(PGresult *res, const char *str);
402 extern void pqClearAsyncResult(PGconn *conn);
403 extern void pqSaveErrorResult(PGconn *conn);
404 extern PGresult *pqPrepareAsyncResult(PGconn *conn);
406 pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
407 /* This lets gcc check the format string for consistency. */
408 __attribute__((format(printf, 2, 3)));
409 extern int pqAddTuple(PGresult *res, PGresAttValue *tup);
410 extern void pqSaveMessageField(PGresult *res, char code,
412 extern void pqSaveParameterStatus(PGconn *conn, const char *name,
414 extern void pqHandleSendFailure(PGconn *conn);
416 /* === in fe-protocol2.c === */
418 extern PostgresPollingStatusType pqSetenvPoll(PGconn *conn);
420 extern char *pqBuildStartupPacket2(PGconn *conn, int *packetlen,
421 const PQEnvironmentOption *options);
422 extern void pqParseInput2(PGconn *conn);
423 extern int pqGetCopyData2(PGconn *conn, char **buffer, int async);
424 extern int pqGetline2(PGconn *conn, char *s, int maxlen);
425 extern int pqGetlineAsync2(PGconn *conn, char *buffer, int bufsize);
426 extern int pqEndcopy2(PGconn *conn);
427 extern PGresult *pqFunctionCall2(PGconn *conn, Oid fnid,
428 int *result_buf, int *actual_result_len,
430 const PQArgBlock *args, int nargs);
432 /* === in fe-protocol3.c === */
434 extern char *pqBuildStartupPacket3(PGconn *conn, int *packetlen,
435 const PQEnvironmentOption *options);
436 extern void pqParseInput3(PGconn *conn);
437 extern int pqGetErrorNotice3(PGconn *conn, bool isError);
438 extern int pqGetCopyData3(PGconn *conn, char **buffer, int async);
439 extern int pqGetline3(PGconn *conn, char *s, int maxlen);
440 extern int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize);
441 extern int pqEndcopy3(PGconn *conn);
442 extern PGresult *pqFunctionCall3(PGconn *conn, Oid fnid,
443 int *result_buf, int *actual_result_len,
445 const PQArgBlock *args, int nargs);
447 /* === in fe-misc.c === */
450 * "Get" and "Put" routines return 0 if successful, EOF if not. Note that for
451 * Get, EOF merely means the buffer is exhausted, not that there is
452 * necessarily any error.
454 extern int pqCheckOutBufferSpace(int bytes_needed, PGconn *conn);
455 extern int pqCheckInBufferSpace(int bytes_needed, PGconn *conn);
456 extern int pqGetc(char *result, PGconn *conn);
457 extern int pqPutc(char c, PGconn *conn);
458 extern int pqGets(PQExpBuffer buf, PGconn *conn);
459 extern int pqPuts(const char *s, PGconn *conn);
460 extern int pqGetnchar(char *s, size_t len, PGconn *conn);
461 extern int pqPutnchar(const char *s, size_t len, PGconn *conn);
462 extern int pqGetInt(int *result, size_t bytes, PGconn *conn);
463 extern int pqPutInt(int value, size_t bytes, PGconn *conn);
464 extern int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn);
465 extern int pqPutMsgEnd(PGconn *conn);
466 extern int pqReadData(PGconn *conn);
467 extern int pqFlush(PGconn *conn);
468 extern int pqWait(int forRead, int forWrite, PGconn *conn);
469 extern int pqWaitTimed(int forRead, int forWrite, PGconn *conn,
471 extern int pqReadReady(PGconn *conn);
472 extern int pqWriteReady(PGconn *conn);
474 /* === in fe-secure.c === */
476 extern int pqsecure_initialize(PGconn *);
477 extern void pqsecure_destroy(void);
478 extern PostgresPollingStatusType pqsecure_open_client(PGconn *);
479 extern void pqsecure_close(PGconn *);
480 extern ssize_t pqsecure_read(PGconn *, void *ptr, size_t len);
481 extern ssize_t pqsecure_write(PGconn *, const void *ptr, size_t len);
483 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
484 extern int pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending);
485 extern void pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending,
490 * this is so that we can check if a connection is non-blocking internally
491 * without the overhead of a function call
493 #define pqIsnonblocking(conn) ((conn)->nonblocking)
497 libpq_gettext(const char *msgid)
498 __attribute__((format_arg(1)));
500 #define libpq_gettext(x) (x)
504 * These macros are needed to let error-handling code be portable between
505 * Unix and Windows. (ugh)
508 #define SOCK_ERRNO (WSAGetLastError())
509 #define SOCK_STRERROR winsock_strerror
510 #define SOCK_ERRNO_SET(e) WSASetLastError(e)
512 #define SOCK_ERRNO errno
513 #define SOCK_STRERROR pqStrerror
514 #define SOCK_ERRNO_SET(e) (errno = (e))
517 #endif /* LIBPQ_INT_H */