Get rid of pgpass_from_client tracking inside libpq --- given the conclusion
[PostgreSQL.git] / src / interfaces / libpq / libpq-int.h
blobe5d21b39a2f8a4a88508047f59b86a30337f4330
1 /*-------------------------------------------------------------------------
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.
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-2008, PostgreSQL Global Development Group
13 * Portions Copyright (c) 1994, Regents of the University of California
15 * $PostgreSQL$
17 *-------------------------------------------------------------------------
20 #ifndef LIBPQ_INT_H
21 #define LIBPQ_INT_H
23 /* We assume libpq-fe.h has already been included. */
24 #include "postgres_fe.h"
25 #include "libpq-events.h"
27 #include <time.h>
28 #include <sys/types.h>
29 #ifndef WIN32
30 #include <sys/time.h>
31 #endif
33 #ifdef ENABLE_THREAD_SAFETY
34 #ifdef WIN32
35 #include "pthread-win32.h"
36 #else
37 #include <pthread.h>
38 #endif
39 #include <signal.h>
40 #endif
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"
48 #ifdef ENABLE_GSS
49 #if defined(HAVE_GSSAPI_H)
50 #include <gssapi.h>
51 #else
52 #include <gssapi/gssapi.h>
53 #endif
54 #endif
56 #ifdef ENABLE_SSPI
57 #define SECURITY_WIN32
58 #include <security.h>
59 #undef SECURITY_WIN32
61 #ifndef ENABLE_GSS
63 * Define a fake structure compatible with GSSAPI on Unix.
65 typedef struct
67 void *value;
68 int length;
69 } gss_buffer_desc;
70 #endif
71 #endif /* ENABLE_SSPI */
73 #ifdef USE_SSL
74 #include <openssl/ssl.h>
75 #include <openssl/err.h>
76 #endif
79 * POSTGRES backend dependent Constants.
81 #define CMDSTATUS_LEN 64 /* should match COMPLETION_TAG_BUFSIZE */
84 * PGresult and the subsidiary types PGresAttDesc, PGresAttValue
85 * represent the result of a query (or more precisely, of a single SQL
86 * command --- a query string given to PQexec can contain multiple commands).
87 * Note we assume that a single command can return at most one tuple group,
88 * hence there is no need for multiple descriptor sets.
91 /* Subsidiary-storage management structure for PGresult.
92 * See space management routines in fe-exec.c for details.
93 * Note that space[k] refers to the k'th byte starting from the physical
94 * head of the block --- it's a union, not a struct!
96 typedef union pgresult_data PGresult_data;
98 union pgresult_data
100 PGresult_data *next; /* link to next block, or NULL */
101 char space[1]; /* dummy for accessing block as bytes */
104 /* Data about a single parameter of a prepared statement */
105 typedef struct pgresParamDesc
107 Oid typid; /* type id */
108 } PGresParamDesc;
111 * Data for a single attribute of a single tuple
113 * We use char* for Attribute values.
115 * The value pointer always points to a null-terminated area; we add a
116 * null (zero) byte after whatever the backend sends us. This is only
117 * particularly useful for text values ... with a binary value, the
118 * value might have embedded nulls, so the application can't use C string
119 * operators on it. But we add a null anyway for consistency.
120 * Note that the value itself does not contain a length word.
122 * A NULL attribute is a special case in two ways: its len field is NULL_LEN
123 * and its value field points to null_field in the owning PGresult. All the
124 * NULL attributes in a query result point to the same place (there's no need
125 * to store a null string separately for each one).
128 #define NULL_LEN (-1) /* pg_result len for NULL value */
130 typedef struct pgresAttValue
132 int len; /* length in bytes of the value */
133 char *value; /* actual value, plus terminating zero byte */
134 } PGresAttValue;
136 /* Typedef for message-field list entries */
137 typedef struct pgMessageField
139 struct pgMessageField *next; /* list link */
140 char code; /* field code */
141 char contents[1]; /* field value (VARIABLE LENGTH) */
142 } PGMessageField;
144 /* Fields needed for notice handling */
145 typedef struct
147 PQnoticeReceiver noticeRec; /* notice message receiver */
148 void *noticeRecArg;
149 PQnoticeProcessor noticeProc; /* notice message processor */
150 void *noticeProcArg;
151 } PGNoticeHooks;
153 typedef struct PGEvent
155 PGEventProc proc; /* the function to call on events */
156 char *name; /* used only for error messages */
157 void *passThrough; /* pointer supplied at registration time */
158 void *data; /* optional state (instance) data */
159 bool resultInitialized; /* T if RESULTCREATE/COPY succeeded */
160 } PGEvent;
162 struct pg_result
164 int ntups;
165 int numAttributes;
166 PGresAttDesc *attDescs;
167 PGresAttValue **tuples; /* each PGresTuple is an array of
168 * PGresAttValue's */
169 int tupArrSize; /* allocated size of tuples array */
170 int numParameters;
171 PGresParamDesc *paramDescs;
172 ExecStatusType resultStatus;
173 char cmdStatus[CMDSTATUS_LEN]; /* cmd status from the query */
174 int binary; /* binary tuple values if binary == 1,
175 * otherwise text */
178 * These fields are copied from the originating PGconn, so that operations
179 * on the PGresult don't have to reference the PGconn.
181 PGNoticeHooks noticeHooks;
182 PGEvent *events;
183 int nEvents;
184 int client_encoding; /* encoding id */
187 * Error information (all NULL if not an error result). errMsg is the
188 * "overall" error message returned by PQresultErrorMessage. If we have
189 * per-field info then it is stored in a linked list.
191 char *errMsg; /* error message, or NULL if no error */
192 PGMessageField *errFields; /* message broken into fields */
194 /* All NULL attributes in the query result point to this null string */
195 char null_field[1];
198 * Space management information. Note that attDescs and error stuff, if
199 * not null, point into allocated blocks. But tuples points to a
200 * separately malloc'd block, so that we can realloc it.
202 PGresult_data *curBlock; /* most recently allocated block */
203 int curOffset; /* start offset of free space in block */
204 int spaceLeft; /* number of free bytes remaining in block */
207 /* PGAsyncStatusType defines the state of the query-execution state machine */
208 typedef enum
210 PGASYNC_IDLE, /* nothing's happening, dude */
211 PGASYNC_BUSY, /* query in progress */
212 PGASYNC_READY, /* result ready for PQgetResult */
213 PGASYNC_COPY_IN, /* Copy In data transfer in progress */
214 PGASYNC_COPY_OUT /* Copy Out data transfer in progress */
215 } PGAsyncStatusType;
217 /* PGQueryClass tracks which query protocol we are now executing */
218 typedef enum
220 PGQUERY_SIMPLE, /* simple Query protocol (PQexec) */
221 PGQUERY_EXTENDED, /* full Extended protocol (PQexecParams) */
222 PGQUERY_PREPARE, /* Parse only (PQprepare) */
223 PGQUERY_DESCRIBE /* Describe Statement or Portal */
224 } PGQueryClass;
226 /* PGSetenvStatusType defines the state of the PQSetenv state machine */
227 /* (this is used only for 2.0-protocol connections) */
228 typedef enum
230 SETENV_STATE_OPTION_SEND, /* About to send an Environment Option */
231 SETENV_STATE_OPTION_WAIT, /* Waiting for above send to complete */
232 SETENV_STATE_QUERY1_SEND, /* About to send a status query */
233 SETENV_STATE_QUERY1_WAIT, /* Waiting for query to complete */
234 SETENV_STATE_QUERY2_SEND, /* About to send a status query */
235 SETENV_STATE_QUERY2_WAIT, /* Waiting for query to complete */
236 SETENV_STATE_IDLE
237 } PGSetenvStatusType;
239 /* Typedef for the EnvironmentOptions[] array */
240 typedef struct PQEnvironmentOption
242 const char *envName, /* name of an environment variable */
243 *pgName; /* name of corresponding SET variable */
244 } PQEnvironmentOption;
246 /* Typedef for parameter-status list entries */
247 typedef struct pgParameterStatus
249 struct pgParameterStatus *next; /* list link */
250 char *name; /* parameter name */
251 char *value; /* parameter value */
252 /* Note: name and value are stored in same malloc block as struct is */
253 } pgParameterStatus;
255 /* large-object-access data ... allocated only if large-object code is used. */
256 typedef struct pgLobjfuncs
258 Oid fn_lo_open; /* OID of backend function lo_open */
259 Oid fn_lo_close; /* OID of backend function lo_close */
260 Oid fn_lo_creat; /* OID of backend function lo_creat */
261 Oid fn_lo_create; /* OID of backend function lo_create */
262 Oid fn_lo_unlink; /* OID of backend function lo_unlink */
263 Oid fn_lo_lseek; /* OID of backend function lo_lseek */
264 Oid fn_lo_tell; /* OID of backend function lo_tell */
265 Oid fn_lo_truncate; /* OID of backend function lo_truncate */
266 Oid fn_lo_read; /* OID of backend function LOread */
267 Oid fn_lo_write; /* OID of backend function LOwrite */
268 } PGlobjfuncs;
271 * PGconn stores all the state data associated with a single connection
272 * to a backend.
274 struct pg_conn
276 /* Saved values of connection options */
277 char *pghost; /* the machine on which the server is running */
278 char *pghostaddr; /* the IPv4 address of the machine on which
279 * the server is running, in IPv4
280 * numbers-and-dots notation. Takes precedence
281 * over above. */
282 char *pgport; /* the server's communication port */
283 char *pgunixsocket; /* the Unix-domain socket that the server is
284 * listening on; if NULL, uses a default
285 * constructed from pgport */
286 char *pgtty; /* tty on which the backend messages is
287 * displayed (OBSOLETE, NOT USED) */
288 char *connect_timeout; /* connection timeout (numeric string) */
289 char *pgoptions; /* options to start the backend with */
290 char *dbName; /* database name */
291 char *pguser; /* Postgres username and password, if any */
292 char *pgpass;
293 char *sslmode; /* SSL mode (require,prefer,allow,disable) */
294 #if defined(KRB5) || defined(ENABLE_GSS) || defined(ENABLE_SSPI)
295 char *krbsrvname; /* Kerberos service name */
296 #endif
298 /* Optional file to write trace info to */
299 FILE *Pfdebug;
301 /* Callback procedures for notice message processing */
302 PGNoticeHooks noticeHooks;
304 /* Event procs registered via PQregisterEventProc */
305 PGEvent *events; /* expandable array of event data */
306 int nEvents; /* number of active events */
307 int eventArraySize; /* allocated array size */
309 /* Status indicators */
310 ConnStatusType status;
311 PGAsyncStatusType asyncStatus;
312 PGTransactionStatusType xactStatus; /* never changes to ACTIVE */
313 PGQueryClass queryclass;
314 char *last_query; /* last SQL command, or NULL if unknown */
315 bool options_valid; /* true if OK to attempt connection */
316 bool nonblocking; /* whether this connection is using nonblock
317 * sending semantics */
318 char copy_is_binary; /* 1 = copy binary, 0 = copy text */
319 int copy_already_done; /* # bytes already returned in COPY
320 * OUT */
321 PGnotify *notifyHead; /* oldest unreported Notify msg */
322 PGnotify *notifyTail; /* newest unreported Notify msg */
324 /* Connection data */
325 int sock; /* Unix FD for socket, -1 if not connected */
326 SockAddr laddr; /* Local address */
327 SockAddr raddr; /* Remote address */
328 ProtocolVersion pversion; /* FE/BE protocol version in use */
329 int sversion; /* server version, e.g. 70401 for 7.4.1 */
330 bool password_needed; /* true if server demanded a password */
332 /* Transient state needed while establishing connection */
333 struct addrinfo *addrlist; /* list of possible backend addresses */
334 struct addrinfo *addr_cur; /* the one currently being tried */
335 int addrlist_family; /* needed to know how to free addrlist */
336 PGSetenvStatusType setenv_state; /* for 2.0 protocol only */
337 const PQEnvironmentOption *next_eo;
339 /* Miscellaneous stuff */
340 int be_pid; /* PID of backend --- needed for cancels */
341 int be_key; /* key of backend --- needed for cancels */
342 char md5Salt[4]; /* password salt received from backend */
343 char cryptSalt[2]; /* password salt received from backend */
344 pgParameterStatus *pstatus; /* ParameterStatus data */
345 int client_encoding; /* encoding id */
346 bool std_strings; /* standard_conforming_strings */
347 PGVerbosity verbosity; /* error/notice message verbosity */
348 PGlobjfuncs *lobjfuncs; /* private state for large-object access fns */
350 /* Buffer for data received from backend and not yet processed */
351 char *inBuffer; /* currently allocated buffer */
352 int inBufSize; /* allocated size of buffer */
353 int inStart; /* offset to first unconsumed data in buffer */
354 int inCursor; /* next byte to tentatively consume */
355 int inEnd; /* offset to first position after avail data */
357 /* Buffer for data not yet sent to backend */
358 char *outBuffer; /* currently allocated buffer */
359 int outBufSize; /* allocated size of buffer */
360 int outCount; /* number of chars waiting in buffer */
362 /* State for constructing messages in outBuffer */
363 int outMsgStart; /* offset to msg start (length word); if -1,
364 * msg has no length word */
365 int outMsgEnd; /* offset to msg end (so far) */
367 /* Status for asynchronous result construction */
368 PGresult *result; /* result being constructed */
369 PGresAttValue *curTuple; /* tuple currently being read */
371 #ifdef USE_SSL
372 bool allow_ssl_try; /* Allowed to try SSL negotiation */
373 bool wait_ssl_try; /* Delay SSL negotiation until after
374 * attempting normal connection */
375 SSL *ssl; /* SSL status, if have SSL connection */
376 X509 *peer; /* X509 cert of server */
377 char peer_dn[256 + 1]; /* peer distinguished name */
378 char peer_cn[SM_USER + 1]; /* peer common name */
379 #endif
381 #ifdef ENABLE_GSS
382 gss_ctx_id_t gctx; /* GSS context */
383 gss_name_t gtarg_nam; /* GSS target name */
384 gss_buffer_desc ginbuf; /* GSS input token */
385 gss_buffer_desc goutbuf; /* GSS output token */
386 #endif
388 #ifdef ENABLE_SSPI
389 #ifndef ENABLE_GSS
390 gss_buffer_desc ginbuf; /* GSS input token */
391 #else
392 char *gsslib; /* What GSS librart to use ("gssapi" or
393 * "sspi") */
394 #endif
395 CredHandle *sspicred; /* SSPI credentials handle */
396 CtxtHandle *sspictx; /* SSPI context */
397 char *sspitarget; /* SSPI target name */
398 int usesspi; /* Indicate if SSPI is in use on the
399 * connection */
400 #endif
403 /* Buffer for current error message */
404 PQExpBufferData errorMessage; /* expansible string */
406 /* Buffer for receiving various parts of messages */
407 PQExpBufferData workBuffer; /* expansible string */
410 /* PGcancel stores all data necessary to cancel a connection. A copy of this
411 * data is required to safely cancel a connection running on a different
412 * thread.
414 struct pg_cancel
416 SockAddr raddr; /* Remote address */
417 int be_pid; /* PID of backend --- needed for cancels */
418 int be_key; /* key of backend --- needed for cancels */
422 /* String descriptions of the ExecStatusTypes.
423 * direct use of this array is deprecated; call PQresStatus() instead.
425 extern char *const pgresStatus[];
427 /* ----------------
428 * Internal functions of libpq
429 * Functions declared here need to be visible across files of libpq,
430 * but are not intended to be called by applications. We use the
431 * convention "pqXXX" for internal functions, vs. the "PQxxx" names
432 * used for application-visible routines.
433 * ----------------
436 /* === in fe-connect.c === */
438 extern int pqPacketSend(PGconn *conn, char pack_type,
439 const void *buf, size_t buf_len);
440 extern bool pqGetHomeDirectory(char *buf, int bufsize);
442 #ifdef ENABLE_THREAD_SAFETY
443 extern pgthreadlock_t pg_g_threadlock;
445 #define PGTHREAD_ERROR(msg) \
446 do { \
447 fprintf(stderr, "%s\n", msg); \
448 exit(1); \
449 } while (0)
452 #define pglock_thread() pg_g_threadlock(true)
453 #define pgunlock_thread() pg_g_threadlock(false)
454 #else
455 #define pglock_thread() ((void) 0)
456 #define pgunlock_thread() ((void) 0)
457 #endif
459 /* === in fe-exec.c === */
461 extern void pqSetResultError(PGresult *res, const char *msg);
462 extern void pqCatenateResultError(PGresult *res, const char *msg);
463 extern void *pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary);
464 extern char *pqResultStrdup(PGresult *res, const char *str);
465 extern void pqClearAsyncResult(PGconn *conn);
466 extern void pqSaveErrorResult(PGconn *conn);
467 extern PGresult *pqPrepareAsyncResult(PGconn *conn);
468 extern void
469 pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
470 /* This lets gcc check the format string for consistency. */
471 __attribute__((format(printf, 2, 3)));
472 extern int pqAddTuple(PGresult *res, PGresAttValue *tup);
473 extern void pqSaveMessageField(PGresult *res, char code,
474 const char *value);
475 extern void pqSaveParameterStatus(PGconn *conn, const char *name,
476 const char *value);
477 extern void pqHandleSendFailure(PGconn *conn);
479 /* === in fe-protocol2.c === */
481 extern PostgresPollingStatusType pqSetenvPoll(PGconn *conn);
483 extern char *pqBuildStartupPacket2(PGconn *conn, int *packetlen,
484 const PQEnvironmentOption *options);
485 extern void pqParseInput2(PGconn *conn);
486 extern int pqGetCopyData2(PGconn *conn, char **buffer, int async);
487 extern int pqGetline2(PGconn *conn, char *s, int maxlen);
488 extern int pqGetlineAsync2(PGconn *conn, char *buffer, int bufsize);
489 extern int pqEndcopy2(PGconn *conn);
490 extern PGresult *pqFunctionCall2(PGconn *conn, Oid fnid,
491 int *result_buf, int *actual_result_len,
492 int result_is_int,
493 const PQArgBlock *args, int nargs);
495 /* === in fe-protocol3.c === */
497 extern char *pqBuildStartupPacket3(PGconn *conn, int *packetlen,
498 const PQEnvironmentOption *options);
499 extern void pqParseInput3(PGconn *conn);
500 extern int pqGetErrorNotice3(PGconn *conn, bool isError);
501 extern int pqGetCopyData3(PGconn *conn, char **buffer, int async);
502 extern int pqGetline3(PGconn *conn, char *s, int maxlen);
503 extern int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize);
504 extern int pqEndcopy3(PGconn *conn);
505 extern PGresult *pqFunctionCall3(PGconn *conn, Oid fnid,
506 int *result_buf, int *actual_result_len,
507 int result_is_int,
508 const PQArgBlock *args, int nargs);
510 /* === in fe-misc.c === */
513 * "Get" and "Put" routines return 0 if successful, EOF if not. Note that for
514 * Get, EOF merely means the buffer is exhausted, not that there is
515 * necessarily any error.
517 extern int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn);
518 extern int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn);
519 extern int pqGetc(char *result, PGconn *conn);
520 extern int pqPutc(char c, PGconn *conn);
521 extern int pqGets(PQExpBuffer buf, PGconn *conn);
522 extern int pqPuts(const char *s, PGconn *conn);
523 extern int pqGetnchar(char *s, size_t len, PGconn *conn);
524 extern int pqPutnchar(const char *s, size_t len, PGconn *conn);
525 extern int pqGetInt(int *result, size_t bytes, PGconn *conn);
526 extern int pqPutInt(int value, size_t bytes, PGconn *conn);
527 extern int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn);
528 extern int pqPutMsgEnd(PGconn *conn);
529 extern int pqReadData(PGconn *conn);
530 extern int pqFlush(PGconn *conn);
531 extern int pqWait(int forRead, int forWrite, PGconn *conn);
532 extern int pqWaitTimed(int forRead, int forWrite, PGconn *conn,
533 time_t finish_time);
534 extern int pqReadReady(PGconn *conn);
535 extern int pqWriteReady(PGconn *conn);
537 /* === in fe-secure.c === */
539 extern int pqsecure_initialize(PGconn *);
540 extern void pqsecure_destroy(void);
541 extern PostgresPollingStatusType pqsecure_open_client(PGconn *);
542 extern void pqsecure_close(PGconn *);
543 extern ssize_t pqsecure_read(PGconn *, void *ptr, size_t len);
544 extern ssize_t pqsecure_write(PGconn *, const void *ptr, size_t len);
546 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
547 extern int pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending);
548 extern void pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending,
549 bool got_epipe);
550 #endif
553 * this is so that we can check if a connection is non-blocking internally
554 * without the overhead of a function call
556 #define pqIsnonblocking(conn) ((conn)->nonblocking)
558 #ifdef ENABLE_NLS
559 extern char *
560 libpq_gettext(const char *msgid)
561 __attribute__((format_arg(1)));
562 #else
563 #define libpq_gettext(x) (x)
564 #endif
567 * These macros are needed to let error-handling code be portable between
568 * Unix and Windows. (ugh)
570 #ifdef WIN32
571 #define SOCK_ERRNO (WSAGetLastError())
572 #define SOCK_STRERROR winsock_strerror
573 #define SOCK_ERRNO_SET(e) WSASetLastError(e)
574 #else
575 #define SOCK_ERRNO errno
576 #define SOCK_STRERROR pqStrerror
577 #define SOCK_ERRNO_SET(e) (errno = (e))
578 #endif
580 #endif /* LIBPQ_INT_H */