]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/libpq-int.h
f2acf2af20a2727f2fdc157f02303d956a0e80a7
[postgresql] / src / interfaces / libpq / libpq-int.h
1 /*-------------------------------------------------------------------------
2  *
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.
6  *
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.
11  *
12  * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
13  * Portions Copyright (c) 1994, Regents of the University of California
14  *
15  * $PostgreSQL: pgsql/src/interfaces/libpq/libpq-int.h,v 1.85 2004/03/05 01:53:59 tgl Exp $
16  *
17  *-------------------------------------------------------------------------
18  */
19
20 #ifndef LIBPQ_INT_H
21 #define LIBPQ_INT_H
22
23 /* We assume libpq-fe.h has already been included. */
24 #include "postgres_fe.h"
25
26 #include <time.h>
27 #include <sys/types.h>
28 #ifndef WIN32
29 #include <sys/time.h>
30 #endif
31
32 #ifdef ENABLE_THREAD_SAFETY
33 #include <pthread.h>
34 #endif
35
36 #if defined(WIN32) && (!defined(ssize_t))
37 typedef int ssize_t;                    /* ssize_t doesn't exist in VC (at least
38                                                                  * not VC6) */
39 #endif
40
41 /* include stuff common to fe and be */
42 #include "getaddrinfo.h"
43 #include "libpq/pqcomm.h"
44 #include "lib/dllist.h"
45 /* include stuff found in fe only */
46 #include "pqexpbuffer.h"
47
48 #ifdef USE_SSL
49 #include <openssl/ssl.h>
50 #include <openssl/err.h>
51 #endif
52
53 /*
54  * POSTGRES backend dependent Constants.
55  */
56 #define PQERRORMSG_LENGTH 1024
57 #define CMDSTATUS_LEN 40
58
59 /*
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.
65  */
66
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!
71  */
72 typedef union pgresult_data PGresult_data;
73
74 union pgresult_data
75 {
76         PGresult_data *next;            /* link to next block, or NULL */
77         char            space[1];               /* dummy for accessing block as bytes */
78 };
79
80 /* Data about a single attribute (column) of a query result */
81
82 typedef struct pgresAttDesc
83 {
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 */
91 }       PGresAttDesc;
92
93 /*
94  * Data for a single attribute of a single tuple
95  *
96  * We use char* for Attribute values.
97  *
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.
104  *
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).
109  */
110
111 #define NULL_LEN                (-1)    /* pg_result len for NULL value */
112
113 typedef struct pgresAttValue
114 {
115         int                     len;                    /* length in bytes of the value */
116         char       *value;                      /* actual value, plus terminating zero
117                                                                  * byte */
118 }       PGresAttValue;
119
120 /* Typedef for message-field list entries */
121 typedef struct pgMessageField
122 {
123         struct pgMessageField *next;    /* list link */
124         char            code;                   /* field code */
125         char            contents[1];    /* field value (VARIABLE LENGTH) */
126 }       PGMessageField;
127
128 /* Fields needed for notice handling */
129 typedef struct
130 {
131         PQnoticeReceiver noticeRec; /* notice message receiver */
132         void       *noticeRecArg;
133         PQnoticeProcessor noticeProc;           /* notice message processor */
134         void       *noticeProcArg;
135 }       PGNoticeHooks;
136
137 struct pg_result
138 {
139         int                     ntups;
140         int                     numAttributes;
141         PGresAttDesc *attDescs;
142         PGresAttValue **tuples;         /* each PGresTuple is an array of
143                                                                  * PGresAttValue's */
144         int                     tupArrSize;             /* allocated size of tuples array */
145         ExecStatusType resultStatus;
146         char            cmdStatus[CMDSTATUS_LEN];               /* cmd status from the
147                                                                                                  * query */
148         int                     binary;                 /* binary tuple values if binary == 1,
149                                                                  * otherwise text */
150
151         /*
152          * These fields are copied from the originating PGconn, so that
153          * operations on the PGresult don't have to reference the PGconn.
154          */
155         PGNoticeHooks noticeHooks;
156         int                     client_encoding;        /* encoding id */
157
158         /*
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.
162          */
163         char       *errMsg;                     /* error message, or NULL if no error */
164         PGMessageField *errFields;      /* message broken into fields */
165
166         /* All NULL attributes in the query result point to this null string */
167         char            null_field[1];
168
169         /*
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.
173          */
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 */
177 };
178
179 /* PGAsyncStatusType defines the state of the query-execution state machine */
180 typedef enum
181 {
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 */
187 }       PGAsyncStatusType;
188
189 /* PGSetenvStatusType defines the state of the PQSetenv state machine */
190 /* (this is used only for 2.0-protocol connections) */
191 typedef enum
192 {
193         SETENV_STATE_OPTION_SEND,       /* About to send an Environment Option */
194         SETENV_STATE_OPTION_WAIT,       /* Waiting for above send to complete */
195         SETENV_STATE_QUERY1_SEND,       /* About to send a status query */
196         SETENV_STATE_QUERY1_WAIT,       /* Waiting for query to complete */
197         SETENV_STATE_QUERY2_SEND,       /* About to send a status query */
198         SETENV_STATE_QUERY2_WAIT,       /* Waiting for query to complete */
199         SETENV_STATE_IDLE
200 }       PGSetenvStatusType;
201
202 /* Typedef for the EnvironmentOptions[] array */
203 typedef struct PQEnvironmentOption
204 {
205         const char *envName,            /* name of an environment variable */
206                            *pgName;                     /* name of corresponding SET variable */
207 }       PQEnvironmentOption;
208
209 /* Typedef for parameter-status list entries */
210 typedef struct pgParameterStatus
211 {
212         struct pgParameterStatus *next;         /* list link */
213         char       *name;                       /* parameter name */
214         char       *value;                      /* parameter value */
215         /* Note: name and value are stored in same malloc block as struct is */
216 }       pgParameterStatus;
217
218 /* large-object-access data ... allocated only if large-object code is used. */
219 typedef struct pgLobjfuncs
220 {
221         Oid                     fn_lo_open;             /* OID of backend function lo_open              */
222         Oid                     fn_lo_close;    /* OID of backend function lo_close             */
223         Oid                     fn_lo_creat;    /* OID of backend function lo_creat             */
224         Oid                     fn_lo_unlink;   /* OID of backend function lo_unlink    */
225         Oid                     fn_lo_lseek;    /* OID of backend function lo_lseek             */
226         Oid                     fn_lo_tell;             /* OID of backend function lo_tell              */
227         Oid                     fn_lo_read;             /* OID of backend function LOread               */
228         Oid                     fn_lo_write;    /* OID of backend function LOwrite              */
229 }       PGlobjfuncs;
230
231 /*
232  * PGconn stores all the state data associated with a single connection
233  * to a backend.
234  */
235 struct pg_conn
236 {
237         /* Saved values of connection options */
238         char       *pghost;                     /* the machine on which the server is
239                                                                  * running */
240         char       *pghostaddr;         /* the IPv4 address of the machine on
241                                                                  * which the server is running, in IPv4
242                                                                  * numbers-and-dots notation. Takes
243                                                                  * precedence over above. */
244         char       *pgport;                     /* the server's communication port */
245         char       *pgunixsocket;       /* the Unix-domain socket that the server
246                                                                  * is listening on; if NULL, uses a
247                                                                  * default constructed from pgport */
248         char       *pgtty;                      /* tty on which the backend messages is
249                                                                  * displayed (OBSOLETE, NOT USED) */
250         char       *connect_timeout;    /* connection timeout (numeric string) */
251         char       *pgoptions;          /* options to start the backend with */
252         char       *dbName;                     /* database name */
253         char       *pguser;                     /* Postgres username and password, if any */
254         char       *pgpass;
255         char       *sslmode;            /* SSL mode (require,prefer,allow,disable) */
256
257         /* Optional file to write trace info to */
258         FILE       *Pfdebug;
259
260         /* Callback procedures for notice message processing */
261         PGNoticeHooks noticeHooks;
262
263         /* Status indicators */
264         ConnStatusType status;
265         PGAsyncStatusType asyncStatus;
266         PGTransactionStatusType xactStatus;
267         /* note: xactStatus never changes to ACTIVE */
268         bool            nonblocking;    /* whether this connection is using
269                                                                  * nonblock sending semantics */
270         bool            ext_query;              /* was our last query sent with extended
271                                                                  * query protocol? */
272         char            copy_is_binary; /* 1 = copy binary, 0 = copy text */
273         int                     copy_already_done;              /* # bytes already returned in
274                                                                                  * COPY OUT */
275         Dllist     *notifyList;         /* Notify msgs not yet handed to
276                                                                  * application */
277
278         /* Connection data */
279         int                     sock;                   /* Unix FD for socket, -1 if not connected */
280         SockAddr        laddr;                  /* Local address */
281         SockAddr        raddr;                  /* Remote address */
282         ProtocolVersion pversion;       /* FE/BE protocol version in use */
283         int                     sversion;               /* server version, e.g. 70401 for 7.4.1 */
284
285         /* Transient state needed while establishing connection */
286         struct addrinfo *addrlist;      /* list of possible backend addresses */
287         struct addrinfo *addr_cur;      /* the one currently being tried */
288         int                     addrlist_family;        /* needed to know how to free addrlist */
289         PGSetenvStatusType setenv_state;        /* for 2.0 protocol only */
290         const PQEnvironmentOption *next_eo;
291
292         /* Miscellaneous stuff */
293         int                     be_pid;                 /* PID of backend --- needed for cancels */
294         int                     be_key;                 /* key of backend --- needed for cancels */
295         char            md5Salt[4];             /* password salt received from backend */
296         char            cryptSalt[2];   /* password salt received from backend */
297         pgParameterStatus *pstatus; /* ParameterStatus data */
298         int                     client_encoding;        /* encoding id */
299         PGVerbosity verbosity;          /* error/notice message verbosity */
300         PGlobjfuncs *lobjfuncs;         /* private state for large-object access
301                                                                  * fns */
302
303         /* Buffer for data received from backend and not yet processed */
304         char       *inBuffer;           /* currently allocated buffer */
305         int                     inBufSize;              /* allocated size of buffer */
306         int                     inStart;                /* offset to first unconsumed data in
307                                                                  * buffer */
308         int                     inCursor;               /* next byte to tentatively consume */
309         int                     inEnd;                  /* offset to first position after avail
310                                                                  * data */
311
312         /* Buffer for data not yet sent to backend */
313         char       *outBuffer;          /* currently allocated buffer */
314         int                     outBufSize;             /* allocated size of buffer */
315         int                     outCount;               /* number of chars waiting in buffer */
316
317         /* State for constructing messages in outBuffer */
318         int                     outMsgStart;    /* offset to msg start (length word); if
319                                                                  * -1, msg has no length word */
320         int                     outMsgEnd;              /* offset to msg end (so far) */
321
322         /* Status for asynchronous result construction */
323         PGresult   *result;                     /* result being constructed */
324         PGresAttValue *curTuple;        /* tuple currently being read */
325
326 #ifdef USE_SSL
327         bool            allow_ssl_try;  /* Allowed to try SSL negotiation */
328         bool            wait_ssl_try;   /* Delay SSL negotiation until after
329                                                                  * attempting normal connection */
330         SSL                *ssl;                        /* SSL status, if have SSL connection */
331         X509       *peer;                       /* X509 cert of server */
332         char            peer_dn[256 + 1];               /* peer distinguished name */
333         char            peer_cn[SM_USER + 1];   /* peer common name */
334 #endif
335
336         /* Buffer for current error message */
337         PQExpBufferData errorMessage;           /* expansible string */
338
339         /* Buffer for receiving various parts of messages */
340         PQExpBufferData workBuffer; /* expansible string */
341 };
342
343 /* String descriptions of the ExecStatusTypes.
344  * direct use of this array is deprecated; call PQresStatus() instead.
345  */
346 extern char *const pgresStatus[];
347
348 /* ----------------
349  * Internal functions of libpq
350  * Functions declared here need to be visible across files of libpq,
351  * but are not intended to be called by applications.  We use the
352  * convention "pqXXX" for internal functions, vs. the "PQxxx" names
353  * used for application-visible routines.
354  * ----------------
355  */
356
357 /* === in fe-connect.c === */
358
359 extern int pqPacketSend(PGconn *conn, char pack_type,
360                          const void *buf, size_t buf_len);
361
362 /* === in fe-exec.c === */
363
364 extern void pqSetResultError(PGresult *res, const char *msg);
365 extern void pqCatenateResultError(PGresult *res, const char *msg);
366 extern void *pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary);
367 extern char *pqResultStrdup(PGresult *res, const char *str);
368 extern void pqClearAsyncResult(PGconn *conn);
369 extern void pqSaveErrorResult(PGconn *conn);
370 extern PGresult *pqPrepareAsyncResult(PGconn *conn);
371 extern void
372 pqInternalNotice(const PGNoticeHooks * hooks, const char *fmt,...)
373 /* This lets gcc check the format string for consistency. */
374 __attribute__((format(printf, 2, 3)));
375 extern int      pqAddTuple(PGresult *res, PGresAttValue * tup);
376 extern void pqSaveMessageField(PGresult *res, char code,
377                                    const char *value);
378 extern void pqSaveParameterStatus(PGconn *conn, const char *name,
379                                           const char *value);
380 extern void pqHandleSendFailure(PGconn *conn);
381
382 /* === in fe-protocol2.c === */
383
384 extern PostgresPollingStatusType pqSetenvPoll(PGconn *conn);
385
386 extern char *pqBuildStartupPacket2(PGconn *conn, int *packetlen,
387                                           const PQEnvironmentOption * options);
388 extern void pqParseInput2(PGconn *conn);
389 extern int      pqGetCopyData2(PGconn *conn, char **buffer, int async);
390 extern int      pqGetline2(PGconn *conn, char *s, int maxlen);
391 extern int      pqGetlineAsync2(PGconn *conn, char *buffer, int bufsize);
392 extern int      pqEndcopy2(PGconn *conn);
393 extern PGresult *pqFunctionCall2(PGconn *conn, Oid fnid,
394                                 int *result_buf, int *actual_result_len,
395                                 int result_is_int,
396                                 const PQArgBlock *args, int nargs);
397
398 /* === in fe-protocol3.c === */
399
400 extern char *pqBuildStartupPacket3(PGconn *conn, int *packetlen,
401                                           const PQEnvironmentOption * options);
402 extern void pqParseInput3(PGconn *conn);
403 extern int      pqGetErrorNotice3(PGconn *conn, bool isError);
404 extern int      pqGetCopyData3(PGconn *conn, char **buffer, int async);
405 extern int      pqGetline3(PGconn *conn, char *s, int maxlen);
406 extern int      pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize);
407 extern int      pqEndcopy3(PGconn *conn);
408 extern PGresult *pqFunctionCall3(PGconn *conn, Oid fnid,
409                                 int *result_buf, int *actual_result_len,
410                                 int result_is_int,
411                                 const PQArgBlock *args, int nargs);
412
413 /* === in fe-misc.c === */
414
415  /*
416   * "Get" and "Put" routines return 0 if successful, EOF if not. Note that
417   * for Get, EOF merely means the buffer is exhausted, not that there is
418   * necessarily any error.
419   */
420 extern int      pqCheckOutBufferSpace(int bytes_needed, PGconn *conn);
421 extern int      pqCheckInBufferSpace(int bytes_needed, PGconn *conn);
422 extern int      pqGetc(char *result, PGconn *conn);
423 extern int      pqPutc(char c, PGconn *conn);
424 extern int      pqGets(PQExpBuffer buf, PGconn *conn);
425 extern int      pqPuts(const char *s, PGconn *conn);
426 extern int      pqGetnchar(char *s, size_t len, PGconn *conn);
427 extern int      pqPutnchar(const char *s, size_t len, PGconn *conn);
428 extern int      pqGetInt(int *result, size_t bytes, PGconn *conn);
429 extern int      pqPutInt(int value, size_t bytes, PGconn *conn);
430 extern int      pqPutMsgStart(char msg_type, bool force_len, PGconn *conn);
431 extern int      pqPutMsgEnd(PGconn *conn);
432 extern int      pqReadData(PGconn *conn);
433 extern int      pqFlush(PGconn *conn);
434 extern int      pqWait(int forRead, int forWrite, PGconn *conn);
435 extern int pqWaitTimed(int forRead, int forWrite, PGconn *conn,
436                         time_t finish_time);
437 extern int      pqReadReady(PGconn *conn);
438 extern int      pqWriteReady(PGconn *conn);
439
440 /* === in fe-secure.c === */
441
442 extern int      pqsecure_initialize(PGconn *);
443 extern void pqsecure_destroy(void);
444 extern PostgresPollingStatusType pqsecure_open_client(PGconn *);
445 extern void pqsecure_close(PGconn *);
446 extern ssize_t pqsecure_read(PGconn *, void *ptr, size_t len);
447 extern ssize_t pqsecure_write(PGconn *, const void *ptr, size_t len);
448 #ifdef ENABLE_THREAD_SAFETY
449 extern void check_sigpipe_handler(void);
450 extern pthread_key_t thread_in_send;
451 #endif
452
453 /*
454  * this is so that we can check if a connection is non-blocking internally
455  * without the overhead of a function call
456  */
457 #define pqIsnonblocking(conn)   ((conn)->nonblocking)
458
459 #ifdef ENABLE_NLS
460 extern char *
461 libpq_gettext(const char *msgid)
462 __attribute__((format_arg(1)));
463
464 #else
465 #define libpq_gettext(x) (x)
466 #endif
467
468 /*
469  * These macros are needed to let error-handling code be portable between
470  * Unix and Windows.  (ugh)
471  */
472 #ifdef WIN32
473 #define SOCK_ERRNO (WSAGetLastError())
474 #define SOCK_STRERROR winsock_strerror
475 #define SOCK_ERRNO_SET(e) WSASetLastError(e)
476 #else
477 #define SOCK_ERRNO errno
478 #define SOCK_STRERROR pqStrerror
479 #define SOCK_ERRNO_SET(e) errno=e
480 #endif
481
482 #endif   /* LIBPQ_INT_H */