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-2005, 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.104 2005/06/27 02:04:26 neilc 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
37 #ifdef WIN32_CLIENT_ONLY
38 typedef int ssize_t; /* ssize_t doesn't exist in VC (at least
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 #include <openssl/ssl.h>
50 #include <openssl/err.h>
54 * POSTGRES backend dependent Constants.
56 #define PQERRORMSG_LENGTH 1024
57 #define CMDSTATUS_LEN 40
60 * PGresult and the subsidiary types PGresAttDesc, PGresAttValue
61 * represent the result of a query (or more precisely, of a single SQL
62 * command --- a query string given to PQexec can contain multiple commands).
63 * Note we assume that a single command can return at most one tuple group,
64 * hence there is no need for multiple descriptor sets.
67 /* Subsidiary-storage management structure for PGresult.
68 * See space management routines in fe-exec.c for details.
69 * Note that space[k] refers to the k'th byte starting from the physical
70 * head of the block --- it's a union, not a struct!
72 typedef union pgresult_data PGresult_data;
76 PGresult_data *next; /* link to next block, or NULL */
77 char space[1]; /* dummy for accessing block as bytes */
80 /* Data about a single attribute (column) of a query result */
82 typedef struct pgresAttDesc
84 char *name; /* column name */
85 Oid tableid; /* source table, if known */
86 int columnid; /* source column, if known */
87 int format; /* format code for value (text/binary) */
88 Oid typid; /* type id */
89 int typlen; /* type size */
90 int atttypmod; /* type-specific modifier info */
94 * Data for a single attribute of a single tuple
96 * We use char* for Attribute values.
98 * The value pointer always points to a null-terminated area; we add a
99 * null (zero) byte after whatever the backend sends us. This is only
100 * particularly useful for text values ... with a binary value, the
101 * value might have embedded nulls, so the application can't use C string
102 * operators on it. But we add a null anyway for consistency.
103 * Note that the value itself does not contain a length word.
105 * A NULL attribute is a special case in two ways: its len field is NULL_LEN
106 * and its value field points to null_field in the owning PGresult. All the
107 * NULL attributes in a query result point to the same place (there's no need
108 * to store a null string separately for each one).
111 #define NULL_LEN (-1) /* pg_result len for NULL value */
113 typedef struct pgresAttValue
115 int len; /* length in bytes of the value */
116 char *value; /* actual value, plus terminating zero
120 /* Typedef for message-field list entries */
121 typedef struct pgMessageField
123 struct pgMessageField *next; /* list link */
124 char code; /* field code */
125 char contents[1]; /* field value (VARIABLE LENGTH) */
128 /* Fields needed for notice handling */
131 PQnoticeReceiver noticeRec; /* notice message receiver */
133 PQnoticeProcessor noticeProc; /* notice message processor */
141 PGresAttDesc *attDescs;
142 PGresAttValue **tuples; /* each PGresTuple is an array of
144 int tupArrSize; /* allocated size of tuples array */
145 ExecStatusType resultStatus;
146 char cmdStatus[CMDSTATUS_LEN]; /* cmd status from the
148 int binary; /* binary tuple values if binary == 1,
152 * These fields are copied from the originating PGconn, so that
153 * operations on the PGresult don't have to reference the PGconn.
155 PGNoticeHooks noticeHooks;
156 int client_encoding; /* encoding id */
159 * Error information (all NULL if not an error result). errMsg is the
160 * "overall" error message returned by PQresultErrorMessage. If we
161 * have per-field info then it is stored in a linked list.
163 char *errMsg; /* error message, or NULL if no error */
164 PGMessageField *errFields; /* message broken into fields */
166 /* All NULL attributes in the query result point to this null string */
170 * Space management information. Note that attDescs and error stuff,
171 * if not null, point into allocated blocks. But tuples points to a
172 * separately malloc'd block, so that we can realloc it.
174 PGresult_data *curBlock; /* most recently allocated block */
175 int curOffset; /* start offset of free space in block */
176 int spaceLeft; /* number of free bytes remaining in block */
179 /* PGAsyncStatusType defines the state of the query-execution state machine */
182 PGASYNC_IDLE, /* nothing's happening, dude */
183 PGASYNC_BUSY, /* query in progress */
184 PGASYNC_READY, /* result ready for PQgetResult */
185 PGASYNC_COPY_IN, /* Copy In data transfer in progress */
186 PGASYNC_COPY_OUT /* Copy Out data transfer in progress */
189 /* PGQueryClass tracks which query protocol we are now executing */
192 PGQUERY_SIMPLE, /* simple Query protocol (PQexec) */
193 PGQUERY_EXTENDED, /* full Extended protocol (PQexecParams) */
194 PGQUERY_PREPARE /* Parse only (PQprepare) */
197 /* PGSetenvStatusType defines the state of the PQSetenv state machine */
198 /* (this is used only for 2.0-protocol connections) */
201 SETENV_STATE_OPTION_SEND, /* About to send an Environment Option */
202 SETENV_STATE_OPTION_WAIT, /* Waiting for above send to complete */
203 SETENV_STATE_QUERY1_SEND, /* About to send a status query */
204 SETENV_STATE_QUERY1_WAIT, /* Waiting for query to complete */
205 SETENV_STATE_QUERY2_SEND, /* About to send a status query */
206 SETENV_STATE_QUERY2_WAIT, /* Waiting for query to complete */
208 } PGSetenvStatusType;
210 /* Typedef for the EnvironmentOptions[] array */
211 typedef struct PQEnvironmentOption
213 const char *envName, /* name of an environment variable */
214 *pgName; /* name of corresponding SET variable */
215 } PQEnvironmentOption;
217 /* Typedef for parameter-status list entries */
218 typedef struct pgParameterStatus
220 struct pgParameterStatus *next; /* list link */
221 char *name; /* parameter name */
222 char *value; /* parameter value */
223 /* Note: name and value are stored in same malloc block as struct is */
226 /* large-object-access data ... allocated only if large-object code is used. */
227 typedef struct pgLobjfuncs
229 Oid fn_lo_open; /* OID of backend function lo_open */
230 Oid fn_lo_close; /* OID of backend function lo_close */
231 Oid fn_lo_creat; /* OID of backend function lo_creat */
232 Oid fn_lo_create; /* OID of backend function lo_create */
233 Oid fn_lo_unlink; /* OID of backend function lo_unlink */
234 Oid fn_lo_lseek; /* OID of backend function lo_lseek */
235 Oid fn_lo_tell; /* OID of backend function lo_tell */
236 Oid fn_lo_read; /* OID of backend function LOread */
237 Oid fn_lo_write; /* OID of backend function LOwrite */
241 * PGconn stores all the state data associated with a single connection
246 /* Saved values of connection options */
247 char *pghost; /* the machine on which the server is
249 char *pghostaddr; /* the IPv4 address of the machine on
250 * which the server is running, in IPv4
251 * numbers-and-dots notation. Takes
252 * precedence over above. */
253 char *pgport; /* the server's communication port */
254 char *pgunixsocket; /* the Unix-domain socket that the server
255 * is listening on; if NULL, uses a
256 * default constructed from pgport */
257 char *pgtty; /* tty on which the backend messages is
258 * displayed (OBSOLETE, NOT USED) */
259 char *connect_timeout; /* connection timeout (numeric string) */
260 char *pgoptions; /* options to start the backend with */
261 char *dbName; /* database name */
262 char *pguser; /* Postgres username and password, if any */
264 char *sslmode; /* SSL mode (require,prefer,allow,disable) */
266 char *krbsrvname; /* Kerberos service name */
269 /* Optional file to write trace info to */
272 /* Callback procedures for notice message processing */
273 PGNoticeHooks noticeHooks;
275 /* Status indicators */
276 ConnStatusType status;
277 PGAsyncStatusType asyncStatus;
278 PGTransactionStatusType xactStatus;
279 /* note: xactStatus never changes to ACTIVE */
280 PGQueryClass queryclass;
281 bool nonblocking; /* whether this connection is using
282 * nonblock sending semantics */
283 char copy_is_binary; /* 1 = copy binary, 0 = copy text */
284 int copy_already_done; /* # bytes already returned in
286 PGnotify *notifyHead; /* oldest unreported Notify msg */
287 PGnotify *notifyTail; /* newest unreported Notify msg */
289 /* Connection data */
290 int sock; /* Unix FD for socket, -1 if not connected */
291 SockAddr laddr; /* Local address */
292 SockAddr raddr; /* Remote address */
293 ProtocolVersion pversion; /* FE/BE protocol version in use */
294 int sversion; /* server version, e.g. 70401 for 7.4.1 */
296 /* Transient state needed while establishing connection */
297 struct addrinfo *addrlist; /* list of possible backend addresses */
298 struct addrinfo *addr_cur; /* the one currently being tried */
299 int addrlist_family; /* needed to know how to free addrlist */
300 PGSetenvStatusType setenv_state; /* for 2.0 protocol only */
301 const PQEnvironmentOption *next_eo;
303 /* Miscellaneous stuff */
304 int be_pid; /* PID of backend --- needed for cancels */
305 int be_key; /* key of backend --- needed for cancels */
306 char md5Salt[4]; /* password salt received from backend */
307 char cryptSalt[2]; /* password salt received from backend */
308 pgParameterStatus *pstatus; /* ParameterStatus data */
309 int client_encoding; /* encoding id */
310 PGVerbosity verbosity; /* error/notice message verbosity */
311 PGlobjfuncs *lobjfuncs; /* private state for large-object access
314 /* Buffer for data received from backend and not yet processed */
315 char *inBuffer; /* currently allocated buffer */
316 int inBufSize; /* allocated size of buffer */
317 int inStart; /* offset to first unconsumed data in
319 int inCursor; /* next byte to tentatively consume */
320 int inEnd; /* offset to first position after avail
323 /* Buffer for data not yet sent to backend */
324 char *outBuffer; /* currently allocated buffer */
325 int outBufSize; /* allocated size of buffer */
326 int outCount; /* number of chars waiting in buffer */
328 /* State for constructing messages in outBuffer */
329 int outMsgStart; /* offset to msg start (length word); if
330 * -1, msg has no length word */
331 int outMsgEnd; /* offset to msg end (so far) */
333 /* Status for asynchronous result construction */
334 PGresult *result; /* result being constructed */
335 PGresAttValue *curTuple; /* tuple currently being read */
338 bool allow_ssl_try; /* Allowed to try SSL negotiation */
339 bool wait_ssl_try; /* Delay SSL negotiation until after
340 * attempting normal connection */
341 SSL *ssl; /* SSL status, if have SSL connection */
342 X509 *peer; /* X509 cert of server */
343 char peer_dn[256 + 1]; /* peer distinguished name */
344 char peer_cn[SM_USER + 1]; /* peer common name */
347 /* Buffer for current error message */
348 PQExpBufferData errorMessage; /* expansible string */
350 /* Buffer for receiving various parts of messages */
351 PQExpBufferData workBuffer; /* expansible string */
354 /* PGcancel stores all data necessary to cancel a connection. A copy of this
355 * data is required to safely cancel a connection running on a different
360 SockAddr raddr; /* Remote address */
361 int be_pid; /* PID of backend --- needed for cancels */
362 int be_key; /* key of backend --- needed for cancels */
366 /* String descriptions of the ExecStatusTypes.
367 * direct use of this array is deprecated; call PQresStatus() instead.
369 extern char *const pgresStatus[];
372 * Internal functions of libpq
373 * Functions declared here need to be visible across files of libpq,
374 * but are not intended to be called by applications. We use the
375 * convention "pqXXX" for internal functions, vs. the "PQxxx" names
376 * used for application-visible routines.
380 /* === in fe-connect.c === */
382 extern int pqPacketSend(PGconn *conn, char pack_type,
383 const void *buf, size_t buf_len);
384 extern bool pqGetHomeDirectory(char *buf, int bufsize);
386 #ifdef ENABLE_THREAD_SAFETY
387 extern pgthreadlock_t pg_g_threadlock;
389 #define pglock_thread() pg_g_threadlock(true)
390 #define pgunlock_thread() pg_g_threadlock(false)
392 #define pglock_thread() ((void) 0)
393 #define pgunlock_thread() ((void) 0)
397 /* === in fe-exec.c === */
399 extern void pqSetResultError(PGresult *res, const char *msg);
400 extern void pqCatenateResultError(PGresult *res, const char *msg);
401 extern void *pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary);
402 extern char *pqResultStrdup(PGresult *res, const char *str);
403 extern void pqClearAsyncResult(PGconn *conn);
404 extern void pqSaveErrorResult(PGconn *conn);
405 extern PGresult *pqPrepareAsyncResult(PGconn *conn);
407 pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt, ...)
408 /* This lets gcc check the format string for consistency. */
409 __attribute__((format(printf, 2, 3)));
410 extern int pqAddTuple(PGresult *res, PGresAttValue *tup);
411 extern void pqSaveMessageField(PGresult *res, char code,
413 extern void pqSaveParameterStatus(PGconn *conn, const char *name,
415 extern void pqHandleSendFailure(PGconn *conn);
417 /* === in fe-protocol2.c === */
419 extern PostgresPollingStatusType pqSetenvPoll(PGconn *conn);
421 extern char *pqBuildStartupPacket2(PGconn *conn, int *packetlen,
422 const PQEnvironmentOption *options);
423 extern void pqParseInput2(PGconn *conn);
424 extern int pqGetCopyData2(PGconn *conn, char **buffer, int async);
425 extern int pqGetline2(PGconn *conn, char *s, int maxlen);
426 extern int pqGetlineAsync2(PGconn *conn, char *buffer, int bufsize);
427 extern int pqEndcopy2(PGconn *conn);
428 extern PGresult *pqFunctionCall2(PGconn *conn, Oid fnid,
429 int *result_buf, int *actual_result_len,
431 const PQArgBlock *args, int nargs);
433 /* === in fe-protocol3.c === */
435 extern char *pqBuildStartupPacket3(PGconn *conn, int *packetlen,
436 const PQEnvironmentOption *options);
437 extern void pqParseInput3(PGconn *conn);
438 extern int pqGetErrorNotice3(PGconn *conn, bool isError);
439 extern int pqGetCopyData3(PGconn *conn, char **buffer, int async);
440 extern int pqGetline3(PGconn *conn, char *s, int maxlen);
441 extern int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize);
442 extern int pqEndcopy3(PGconn *conn);
443 extern PGresult *pqFunctionCall3(PGconn *conn, Oid fnid,
444 int *result_buf, int *actual_result_len,
446 const PQArgBlock *args, int nargs);
448 /* === in fe-misc.c === */
451 * "Get" and "Put" routines return 0 if successful, EOF if not. Note that
452 * for Get, EOF merely means the buffer is exhausted, not that there is
453 * necessarily any error.
455 extern int pqCheckOutBufferSpace(int bytes_needed, PGconn *conn);
456 extern int pqCheckInBufferSpace(int bytes_needed, PGconn *conn);
457 extern int pqGetc(char *result, PGconn *conn);
458 extern int pqPutc(char c, PGconn *conn);
459 extern int pqGets(PQExpBuffer buf, PGconn *conn);
460 extern int pqPuts(const char *s, PGconn *conn);
461 extern int pqGetnchar(char *s, size_t len, PGconn *conn);
462 extern int pqPutnchar(const char *s, size_t len, PGconn *conn);
463 extern int pqGetInt(int *result, size_t bytes, PGconn *conn);
464 extern int pqPutInt(int value, size_t bytes, PGconn *conn);
465 extern int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn);
466 extern int pqPutMsgEnd(PGconn *conn);
467 extern int pqReadData(PGconn *conn);
468 extern int pqFlush(PGconn *conn);
469 extern int pqWait(int forRead, int forWrite, PGconn *conn);
470 extern int pqWaitTimed(int forRead, int forWrite, PGconn *conn,
472 extern int pqReadReady(PGconn *conn);
473 extern int pqWriteReady(PGconn *conn);
475 /* === in fe-secure.c === */
477 extern int pqsecure_initialize(PGconn *);
478 extern void pqsecure_destroy(void);
479 extern PostgresPollingStatusType pqsecure_open_client(PGconn *);
480 extern void pqsecure_close(PGconn *);
481 extern ssize_t pqsecure_read(PGconn *, void *ptr, size_t len);
482 extern ssize_t pqsecure_write(PGconn *, const void *ptr, size_t len);
484 #ifdef ENABLE_THREAD_SAFETY
485 extern int pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending);
486 extern void pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending,
491 * this is so that we can check if a connection is non-blocking internally
492 * without the overhead of a function call
494 #define pqIsnonblocking(conn) ((conn)->nonblocking)
498 libpq_gettext(const char *msgid)
499 __attribute__((format_arg(1)));
502 #define libpq_gettext(x) (x)
506 * These macros are needed to let error-handling code be portable between
507 * Unix and Windows. (ugh)
510 #define SOCK_ERRNO (WSAGetLastError())
511 #define SOCK_STRERROR winsock_strerror
512 #define SOCK_ERRNO_SET(e) WSASetLastError(e)
514 #define SOCK_ERRNO errno
515 #define SOCK_STRERROR pqStrerror
516 #define SOCK_ERRNO_SET(e) (errno = (e))
519 #endif /* LIBPQ_INT_H */