gooderp18绿色标准版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

819 line
29KB

  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-2019, PostgreSQL Global Development Group
  13. * Portions Copyright (c) 1994, Regents of the University of California
  14. *
  15. * src/interfaces/libpq/libpq-int.h
  16. *
  17. *-------------------------------------------------------------------------
  18. */
  19. #ifndef LIBPQ_INT_H
  20. #define LIBPQ_INT_H
  21. /* We assume libpq-fe.h has already been included. */
  22. #include "libpq-events.h"
  23. #include <time.h>
  24. #ifndef WIN32
  25. #include <sys/time.h>
  26. #endif
  27. #ifdef ENABLE_THREAD_SAFETY
  28. #ifdef WIN32
  29. #include "pthread-win32.h"
  30. #else
  31. #include <pthread.h>
  32. #endif
  33. #include <signal.h>
  34. #endif
  35. /* include stuff common to fe and be */
  36. #include "getaddrinfo.h"
  37. #include "libpq/pqcomm.h"
  38. /* include stuff found in fe only */
  39. #include "pqexpbuffer.h"
  40. #ifdef ENABLE_GSS
  41. #if defined(HAVE_GSSAPI_H)
  42. #include <gssapi.h>
  43. #else
  44. #include <gssapi/gssapi.h>
  45. #endif
  46. #endif
  47. #ifdef ENABLE_SSPI
  48. #define SECURITY_WIN32
  49. #if defined(WIN32) && !defined(_MSC_VER)
  50. #include <ntsecapi.h>
  51. #endif
  52. #include <security.h>
  53. #undef SECURITY_WIN32
  54. #ifndef ENABLE_GSS
  55. /*
  56. * Define a fake structure compatible with GSSAPI on Unix.
  57. */
  58. typedef struct
  59. {
  60. void *value;
  61. int length;
  62. } gss_buffer_desc;
  63. #endif
  64. #endif /* ENABLE_SSPI */
  65. #ifdef USE_OPENSSL
  66. #include <openssl/ssl.h>
  67. #include <openssl/err.h>
  68. #ifndef OPENSSL_NO_ENGINE
  69. #define USE_SSL_ENGINE
  70. #endif
  71. #endif /* USE_OPENSSL */
  72. /*
  73. * POSTGRES backend dependent Constants.
  74. */
  75. #define CMDSTATUS_LEN 64 /* should match COMPLETION_TAG_BUFSIZE */
  76. /*
  77. * PGresult and the subsidiary types PGresAttDesc, PGresAttValue
  78. * represent the result of a query (or more precisely, of a single SQL
  79. * command --- a query string given to PQexec can contain multiple commands).
  80. * Note we assume that a single command can return at most one tuple group,
  81. * hence there is no need for multiple descriptor sets.
  82. */
  83. /* Subsidiary-storage management structure for PGresult.
  84. * See space management routines in fe-exec.c for details.
  85. * Note that space[k] refers to the k'th byte starting from the physical
  86. * head of the block --- it's a union, not a struct!
  87. */
  88. typedef union pgresult_data PGresult_data;
  89. union pgresult_data
  90. {
  91. PGresult_data *next; /* link to next block, or NULL */
  92. char space[1]; /* dummy for accessing block as bytes */
  93. };
  94. /* Data about a single parameter of a prepared statement */
  95. typedef struct pgresParamDesc
  96. {
  97. Oid typid; /* type id */
  98. } PGresParamDesc;
  99. /*
  100. * Data for a single attribute of a single tuple
  101. *
  102. * We use char* for Attribute values.
  103. *
  104. * The value pointer always points to a null-terminated area; we add a
  105. * null (zero) byte after whatever the backend sends us. This is only
  106. * particularly useful for text values ... with a binary value, the
  107. * value might have embedded nulls, so the application can't use C string
  108. * operators on it. But we add a null anyway for consistency.
  109. * Note that the value itself does not contain a length word.
  110. *
  111. * A NULL attribute is a special case in two ways: its len field is NULL_LEN
  112. * and its value field points to null_field in the owning PGresult. All the
  113. * NULL attributes in a query result point to the same place (there's no need
  114. * to store a null string separately for each one).
  115. */
  116. #define NULL_LEN (-1) /* pg_result len for NULL value */
  117. typedef struct pgresAttValue
  118. {
  119. int len; /* length in bytes of the value */
  120. char *value; /* actual value, plus terminating zero byte */
  121. } PGresAttValue;
  122. /* Typedef for message-field list entries */
  123. typedef struct pgMessageField
  124. {
  125. struct pgMessageField *next; /* list link */
  126. char code; /* field code */
  127. char contents[FLEXIBLE_ARRAY_MEMBER]; /* value, nul-terminated */
  128. } PGMessageField;
  129. /* Fields needed for notice handling */
  130. typedef struct
  131. {
  132. PQnoticeReceiver noticeRec; /* notice message receiver */
  133. void *noticeRecArg;
  134. PQnoticeProcessor noticeProc; /* notice message processor */
  135. void *noticeProcArg;
  136. } PGNoticeHooks;
  137. typedef struct PGEvent
  138. {
  139. PGEventProc proc; /* the function to call on events */
  140. char *name; /* used only for error messages */
  141. void *passThrough; /* pointer supplied at registration time */
  142. void *data; /* optional state (instance) data */
  143. bool resultInitialized; /* T if RESULTCREATE/COPY succeeded */
  144. } PGEvent;
  145. struct pg_result
  146. {
  147. int ntups;
  148. int numAttributes;
  149. PGresAttDesc *attDescs;
  150. PGresAttValue **tuples; /* each PGresTuple is an array of
  151. * PGresAttValue's */
  152. int tupArrSize; /* allocated size of tuples array */
  153. int numParameters;
  154. PGresParamDesc *paramDescs;
  155. ExecStatusType resultStatus;
  156. char cmdStatus[CMDSTATUS_LEN]; /* cmd status from the query */
  157. int binary; /* binary tuple values if binary == 1,
  158. * otherwise text */
  159. /*
  160. * These fields are copied from the originating PGconn, so that operations
  161. * on the PGresult don't have to reference the PGconn.
  162. */
  163. PGNoticeHooks noticeHooks;
  164. PGEvent *events;
  165. int nEvents;
  166. int client_encoding; /* encoding id */
  167. /*
  168. * Error information (all NULL if not an error result). errMsg is the
  169. * "overall" error message returned by PQresultErrorMessage. If we have
  170. * per-field info then it is stored in a linked list.
  171. */
  172. char *errMsg; /* error message, or NULL if no error */
  173. PGMessageField *errFields; /* message broken into fields */
  174. char *errQuery; /* text of triggering query, if available */
  175. /* All NULL attributes in the query result point to this null string */
  176. char null_field[1];
  177. /*
  178. * Space management information. Note that attDescs and error stuff, if
  179. * not null, point into allocated blocks. But tuples points to a
  180. * separately malloc'd block, so that we can realloc it.
  181. */
  182. PGresult_data *curBlock; /* most recently allocated block */
  183. int curOffset; /* start offset of free space in block */
  184. int spaceLeft; /* number of free bytes remaining in block */
  185. size_t memorySize; /* total space allocated for this PGresult */
  186. };
  187. /* PGAsyncStatusType defines the state of the query-execution state machine */
  188. typedef enum
  189. {
  190. PGASYNC_IDLE, /* nothing's happening, dude */
  191. PGASYNC_BUSY, /* query in progress */
  192. PGASYNC_READY, /* result ready for PQgetResult */
  193. PGASYNC_COPY_IN, /* Copy In data transfer in progress */
  194. PGASYNC_COPY_OUT, /* Copy Out data transfer in progress */
  195. PGASYNC_COPY_BOTH /* Copy In/Out data transfer in progress */
  196. } PGAsyncStatusType;
  197. /* PGQueryClass tracks which query protocol we are now executing */
  198. typedef enum
  199. {
  200. PGQUERY_SIMPLE, /* simple Query protocol (PQexec) */
  201. PGQUERY_EXTENDED, /* full Extended protocol (PQexecParams) */
  202. PGQUERY_PREPARE, /* Parse only (PQprepare) */
  203. PGQUERY_DESCRIBE /* Describe Statement or Portal */
  204. } PGQueryClass;
  205. /* PGSetenvStatusType defines the state of the PQSetenv state machine */
  206. /* (this is used only for 2.0-protocol connections) */
  207. typedef enum
  208. {
  209. SETENV_STATE_CLIENT_ENCODING_SEND, /* About to send an Environment Option */
  210. SETENV_STATE_CLIENT_ENCODING_WAIT, /* Waiting for above send to complete */
  211. SETENV_STATE_OPTION_SEND, /* About to send an Environment Option */
  212. SETENV_STATE_OPTION_WAIT, /* Waiting for above send to complete */
  213. SETENV_STATE_QUERY1_SEND, /* About to send a status query */
  214. SETENV_STATE_QUERY1_WAIT, /* Waiting for query to complete */
  215. SETENV_STATE_QUERY2_SEND, /* About to send a status query */
  216. SETENV_STATE_QUERY2_WAIT, /* Waiting for query to complete */
  217. SETENV_STATE_IDLE
  218. } PGSetenvStatusType;
  219. /* Typedef for the EnvironmentOptions[] array */
  220. typedef struct PQEnvironmentOption
  221. {
  222. const char *envName, /* name of an environment variable */
  223. *pgName; /* name of corresponding SET variable */
  224. } PQEnvironmentOption;
  225. /* Typedef for parameter-status list entries */
  226. typedef struct pgParameterStatus
  227. {
  228. struct pgParameterStatus *next; /* list link */
  229. char *name; /* parameter name */
  230. char *value; /* parameter value */
  231. /* Note: name and value are stored in same malloc block as struct is */
  232. } pgParameterStatus;
  233. /* large-object-access data ... allocated only if large-object code is used. */
  234. typedef struct pgLobjfuncs
  235. {
  236. Oid fn_lo_open; /* OID of backend function lo_open */
  237. Oid fn_lo_close; /* OID of backend function lo_close */
  238. Oid fn_lo_creat; /* OID of backend function lo_creat */
  239. Oid fn_lo_create; /* OID of backend function lo_create */
  240. Oid fn_lo_unlink; /* OID of backend function lo_unlink */
  241. Oid fn_lo_lseek; /* OID of backend function lo_lseek */
  242. Oid fn_lo_lseek64; /* OID of backend function lo_lseek64 */
  243. Oid fn_lo_tell; /* OID of backend function lo_tell */
  244. Oid fn_lo_tell64; /* OID of backend function lo_tell64 */
  245. Oid fn_lo_truncate; /* OID of backend function lo_truncate */
  246. Oid fn_lo_truncate64; /* OID of function lo_truncate64 */
  247. Oid fn_lo_read; /* OID of backend function LOread */
  248. Oid fn_lo_write; /* OID of backend function LOwrite */
  249. } PGlobjfuncs;
  250. /* PGdataValue represents a data field value being passed to a row processor.
  251. * It could be either text or binary data; text data is not zero-terminated.
  252. * A SQL NULL is represented by len < 0; then value is still valid but there
  253. * are no data bytes there.
  254. */
  255. typedef struct pgDataValue
  256. {
  257. int len; /* data length in bytes, or <0 if NULL */
  258. const char *value; /* data value, without zero-termination */
  259. } PGdataValue;
  260. /* Host address type enum for struct pg_conn_host */
  261. typedef enum pg_conn_host_type
  262. {
  263. CHT_HOST_NAME,
  264. CHT_HOST_ADDRESS,
  265. CHT_UNIX_SOCKET
  266. } pg_conn_host_type;
  267. /*
  268. * pg_conn_host stores all information about each of possibly several hosts
  269. * mentioned in the connection string. Most fields are derived by splitting
  270. * the relevant connection parameter (e.g., pghost) at commas.
  271. */
  272. typedef struct pg_conn_host
  273. {
  274. pg_conn_host_type type; /* type of host address */
  275. char *host; /* host name or socket path */
  276. char *hostaddr; /* host numeric IP address */
  277. char *port; /* port number (always provided) */
  278. char *password; /* password for this host, read from the
  279. * password file; NULL if not sought or not
  280. * found in password file. */
  281. } pg_conn_host;
  282. /*
  283. * PGconn stores all the state data associated with a single connection
  284. * to a backend.
  285. */
  286. struct pg_conn
  287. {
  288. /* Saved values of connection options */
  289. char *pghost; /* the machine on which the server is running,
  290. * or a path to a UNIX-domain socket, or a
  291. * comma-separated list of machines and/or
  292. * paths; if NULL, use DEFAULT_PGSOCKET_DIR */
  293. char *pghostaddr; /* the numeric IP address of the machine on
  294. * which the server is running, or a
  295. * comma-separated list of same. Takes
  296. * precedence over pghost. */
  297. char *pgport; /* the server's communication port number, or
  298. * a comma-separated list of ports */
  299. char *pgtty; /* tty on which the backend messages is
  300. * displayed (OBSOLETE, NOT USED) */
  301. char *connect_timeout; /* connection timeout (numeric string) */
  302. char *pgtcp_user_timeout; /* tcp user timeout (numeric string) */
  303. char *client_encoding_initial; /* encoding to use */
  304. char *pgoptions; /* options to start the backend with */
  305. char *appname; /* application name */
  306. char *fbappname; /* fallback application name */
  307. char *dbName; /* database name */
  308. char *replication; /* connect as the replication standby? */
  309. char *pguser; /* Postgres username and password, if any */
  310. char *pgpass;
  311. char *pgpassfile; /* path to a file containing password(s) */
  312. char *keepalives; /* use TCP keepalives? */
  313. char *keepalives_idle; /* time between TCP keepalives */
  314. char *keepalives_interval; /* time between TCP keepalive
  315. * retransmits */
  316. char *keepalives_count; /* maximum number of TCP keepalive
  317. * retransmits */
  318. char *sslmode; /* SSL mode (require,prefer,allow,disable) */
  319. char *sslcompression; /* SSL compression (0 or 1) */
  320. char *sslkey; /* client key filename */
  321. char *sslcert; /* client certificate filename */
  322. char *sslrootcert; /* root certificate filename */
  323. char *sslcrl; /* certificate revocation list filename */
  324. char *requirepeer; /* required peer credentials for local sockets */
  325. char *gssencmode; /* GSS mode (require,prefer,disable) */
  326. char *krbsrvname; /* Kerberos service name */
  327. char *gsslib; /* What GSS library to use ("gssapi" or
  328. * "sspi") */
  329. /* Type of connection to make. Possible values: any, read-write. */
  330. char *target_session_attrs;
  331. /* Optional file to write trace info to */
  332. FILE *Pfdebug;
  333. /* Callback procedures for notice message processing */
  334. PGNoticeHooks noticeHooks;
  335. /* Event procs registered via PQregisterEventProc */
  336. PGEvent *events; /* expandable array of event data */
  337. int nEvents; /* number of active events */
  338. int eventArraySize; /* allocated array size */
  339. /* Status indicators */
  340. ConnStatusType status;
  341. PGAsyncStatusType asyncStatus;
  342. PGTransactionStatusType xactStatus; /* never changes to ACTIVE */
  343. PGQueryClass queryclass;
  344. char *last_query; /* last SQL command, or NULL if unknown */
  345. char last_sqlstate[6]; /* last reported SQLSTATE */
  346. bool options_valid; /* true if OK to attempt connection */
  347. bool nonblocking; /* whether this connection is using nonblock
  348. * sending semantics */
  349. bool singleRowMode; /* return current query result row-by-row? */
  350. char copy_is_binary; /* 1 = copy binary, 0 = copy text */
  351. int copy_already_done; /* # bytes already returned in COPY OUT */
  352. PGnotify *notifyHead; /* oldest unreported Notify msg */
  353. PGnotify *notifyTail; /* newest unreported Notify msg */
  354. /* Support for multiple hosts in connection string */
  355. int nconnhost; /* # of hosts named in conn string */
  356. int whichhost; /* host we're currently trying/connected to */
  357. pg_conn_host *connhost; /* details about each named host */
  358. char *connip; /* IP address for current network connection */
  359. /* Connection data */
  360. pgsocket sock; /* FD for socket, PGINVALID_SOCKET if
  361. * unconnected */
  362. SockAddr laddr; /* Local address */
  363. SockAddr raddr; /* Remote address */
  364. ProtocolVersion pversion; /* FE/BE protocol version in use */
  365. int sversion; /* server version, e.g. 70401 for 7.4.1 */
  366. bool auth_req_received; /* true if any type of auth req received */
  367. bool password_needed; /* true if server demanded a password */
  368. bool sigpipe_so; /* have we masked SIGPIPE via SO_NOSIGPIPE? */
  369. bool sigpipe_flag; /* can we mask SIGPIPE via MSG_NOSIGNAL? */
  370. bool write_failed; /* have we had a write failure on sock? */
  371. char *write_err_msg; /* write error message, or NULL if OOM */
  372. /* Transient state needed while establishing connection */
  373. bool try_next_addr; /* time to advance to next address/host? */
  374. bool try_next_host; /* time to advance to next connhost[]? */
  375. struct addrinfo *addrlist; /* list of addresses for current connhost */
  376. struct addrinfo *addr_cur; /* the one currently being tried */
  377. int addrlist_family; /* needed to know how to free addrlist */
  378. PGSetenvStatusType setenv_state; /* for 2.0 protocol only */
  379. const PQEnvironmentOption *next_eo;
  380. bool send_appname; /* okay to send application_name? */
  381. /* Miscellaneous stuff */
  382. int be_pid; /* PID of backend --- needed for cancels */
  383. int be_key; /* key of backend --- needed for cancels */
  384. pgParameterStatus *pstatus; /* ParameterStatus data */
  385. int client_encoding; /* encoding id */
  386. bool std_strings; /* standard_conforming_strings */
  387. PGVerbosity verbosity; /* error/notice message verbosity */
  388. PGContextVisibility show_context; /* whether to show CONTEXT field */
  389. PGlobjfuncs *lobjfuncs; /* private state for large-object access fns */
  390. /* Buffer for data received from backend and not yet processed */
  391. char *inBuffer; /* currently allocated buffer */
  392. int inBufSize; /* allocated size of buffer */
  393. int inStart; /* offset to first unconsumed data in buffer */
  394. int inCursor; /* next byte to tentatively consume */
  395. int inEnd; /* offset to first position after avail data */
  396. /* Buffer for data not yet sent to backend */
  397. char *outBuffer; /* currently allocated buffer */
  398. int outBufSize; /* allocated size of buffer */
  399. int outCount; /* number of chars waiting in buffer */
  400. /* State for constructing messages in outBuffer */
  401. int outMsgStart; /* offset to msg start (length word); if -1,
  402. * msg has no length word */
  403. int outMsgEnd; /* offset to msg end (so far) */
  404. /* Row processor interface workspace */
  405. PGdataValue *rowBuf; /* array for passing values to rowProcessor */
  406. int rowBufLen; /* number of entries allocated in rowBuf */
  407. /* Status for asynchronous result construction */
  408. PGresult *result; /* result being constructed */
  409. PGresult *next_result; /* next result (used in single-row mode) */
  410. /* Assorted state for SASL, SSL, GSS, etc */
  411. void *sasl_state;
  412. /* SSL structures */
  413. bool ssl_in_use;
  414. #ifdef USE_SSL
  415. bool allow_ssl_try; /* Allowed to try SSL negotiation */
  416. bool wait_ssl_try; /* Delay SSL negotiation until after
  417. * attempting normal connection */
  418. #ifdef USE_OPENSSL
  419. SSL *ssl; /* SSL status, if have SSL connection */
  420. X509 *peer; /* X509 cert of server */
  421. #ifdef USE_SSL_ENGINE
  422. ENGINE *engine; /* SSL engine, if any */
  423. #else
  424. void *engine; /* dummy field to keep struct the same if
  425. * OpenSSL version changes */
  426. #endif
  427. #endif /* USE_OPENSSL */
  428. #endif /* USE_SSL */
  429. #ifdef ENABLE_GSS
  430. gss_ctx_id_t gctx; /* GSS context */
  431. gss_name_t gtarg_nam; /* GSS target name */
  432. /* The following are encryption-only */
  433. bool try_gss; /* GSS attempting permitted */
  434. bool gssenc; /* GSS encryption is usable */
  435. gss_cred_id_t gcred; /* GSS credential temp storage. */
  436. /* GSS encryption I/O state --- see fe-secure-gssapi.c */
  437. char *gss_SendBuffer; /* Encrypted data waiting to be sent */
  438. int gss_SendLength; /* End of data available in gss_SendBuffer */
  439. int gss_SendNext; /* Next index to send a byte from
  440. * gss_SendBuffer */
  441. int gss_SendConsumed; /* Number of *unencrypted* bytes consumed
  442. * for current contents of gss_SendBuffer */
  443. char *gss_RecvBuffer; /* Received, encrypted data */
  444. int gss_RecvLength; /* End of data available in gss_RecvBuffer */
  445. char *gss_ResultBuffer; /* Decryption of data in gss_RecvBuffer */
  446. int gss_ResultLength; /* End of data available in
  447. * gss_ResultBuffer */
  448. int gss_ResultNext; /* Next index to read a byte from
  449. * gss_ResultBuffer */
  450. uint32 gss_MaxPktSize; /* Maximum size we can encrypt and fit the
  451. * results into our output buffer */
  452. #endif
  453. #ifdef ENABLE_SSPI
  454. CredHandle *sspicred; /* SSPI credentials handle */
  455. CtxtHandle *sspictx; /* SSPI context */
  456. char *sspitarget; /* SSPI target name */
  457. int usesspi; /* Indicate if SSPI is in use on the
  458. * connection */
  459. #endif
  460. /* Buffer for current error message */
  461. PQExpBufferData errorMessage; /* expansible string */
  462. /* Buffer for receiving various parts of messages */
  463. PQExpBufferData workBuffer; /* expansible string */
  464. };
  465. /* PGcancel stores all data necessary to cancel a connection. A copy of this
  466. * data is required to safely cancel a connection running on a different
  467. * thread.
  468. */
  469. struct pg_cancel
  470. {
  471. SockAddr raddr; /* Remote address */
  472. int be_pid; /* PID of backend --- needed for cancels */
  473. int be_key; /* key of backend --- needed for cancels */
  474. };
  475. /* String descriptions of the ExecStatusTypes.
  476. * direct use of this array is deprecated; call PQresStatus() instead.
  477. */
  478. extern char *const pgresStatus[];
  479. #ifdef USE_SSL
  480. #ifndef WIN32
  481. #define USER_CERT_FILE ".postgresql/postgresql.crt"
  482. #define USER_KEY_FILE ".postgresql/postgresql.key"
  483. #define ROOT_CERT_FILE ".postgresql/root.crt"
  484. #define ROOT_CRL_FILE ".postgresql/root.crl"
  485. #else
  486. /* On Windows, the "home" directory is already PostgreSQL-specific */
  487. #define USER_CERT_FILE "postgresql.crt"
  488. #define USER_KEY_FILE "postgresql.key"
  489. #define ROOT_CERT_FILE "root.crt"
  490. #define ROOT_CRL_FILE "root.crl"
  491. #endif
  492. #endif /* USE_SSL */
  493. /* ----------------
  494. * Internal functions of libpq
  495. * Functions declared here need to be visible across files of libpq,
  496. * but are not intended to be called by applications. We use the
  497. * convention "pqXXX" for internal functions, vs. the "PQxxx" names
  498. * used for application-visible routines.
  499. * ----------------
  500. */
  501. /* === in fe-connect.c === */
  502. extern void pqDropConnection(PGconn *conn, bool flushInput);
  503. extern int pqPacketSend(PGconn *conn, char pack_type,
  504. const void *buf, size_t buf_len);
  505. extern bool pqGetHomeDirectory(char *buf, int bufsize);
  506. #ifdef ENABLE_THREAD_SAFETY
  507. extern pgthreadlock_t pg_g_threadlock;
  508. #define PGTHREAD_ERROR(msg) \
  509. do { \
  510. fprintf(stderr, "%s\n", msg); \
  511. abort(); \
  512. } while (0)
  513. #define pglock_thread() pg_g_threadlock(true)
  514. #define pgunlock_thread() pg_g_threadlock(false)
  515. #else
  516. #define pglock_thread() ((void) 0)
  517. #define pgunlock_thread() ((void) 0)
  518. #endif
  519. /* === in fe-exec.c === */
  520. extern void pqSetResultError(PGresult *res, const char *msg);
  521. extern void pqCatenateResultError(PGresult *res, const char *msg);
  522. extern void *pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary);
  523. extern char *pqResultStrdup(PGresult *res, const char *str);
  524. extern void pqClearAsyncResult(PGconn *conn);
  525. extern void pqSaveErrorResult(PGconn *conn);
  526. extern PGresult *pqPrepareAsyncResult(PGconn *conn);
  527. extern void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...) pg_attribute_printf(2, 3);
  528. extern void pqSaveMessageField(PGresult *res, char code,
  529. const char *value);
  530. extern void pqSaveParameterStatus(PGconn *conn, const char *name,
  531. const char *value);
  532. extern int pqRowProcessor(PGconn *conn, const char **errmsgp);
  533. /* === in fe-protocol2.c === */
  534. extern PostgresPollingStatusType pqSetenvPoll(PGconn *conn);
  535. extern char *pqBuildStartupPacket2(PGconn *conn, int *packetlen,
  536. const PQEnvironmentOption *options);
  537. extern void pqParseInput2(PGconn *conn);
  538. extern int pqGetCopyData2(PGconn *conn, char **buffer, int async);
  539. extern int pqGetline2(PGconn *conn, char *s, int maxlen);
  540. extern int pqGetlineAsync2(PGconn *conn, char *buffer, int bufsize);
  541. extern int pqEndcopy2(PGconn *conn);
  542. extern PGresult *pqFunctionCall2(PGconn *conn, Oid fnid,
  543. int *result_buf, int *actual_result_len,
  544. int result_is_int,
  545. const PQArgBlock *args, int nargs);
  546. /* === in fe-protocol3.c === */
  547. extern char *pqBuildStartupPacket3(PGconn *conn, int *packetlen,
  548. const PQEnvironmentOption *options);
  549. extern void pqParseInput3(PGconn *conn);
  550. extern int pqGetErrorNotice3(PGconn *conn, bool isError);
  551. extern void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res,
  552. PGVerbosity verbosity, PGContextVisibility show_context);
  553. extern int pqGetCopyData3(PGconn *conn, char **buffer, int async);
  554. extern int pqGetline3(PGconn *conn, char *s, int maxlen);
  555. extern int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize);
  556. extern int pqEndcopy3(PGconn *conn);
  557. extern PGresult *pqFunctionCall3(PGconn *conn, Oid fnid,
  558. int *result_buf, int *actual_result_len,
  559. int result_is_int,
  560. const PQArgBlock *args, int nargs);
  561. /* === in fe-misc.c === */
  562. /*
  563. * "Get" and "Put" routines return 0 if successful, EOF if not. Note that for
  564. * Get, EOF merely means the buffer is exhausted, not that there is
  565. * necessarily any error.
  566. */
  567. extern int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn);
  568. extern int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn);
  569. extern int pqGetc(char *result, PGconn *conn);
  570. extern int pqPutc(char c, PGconn *conn);
  571. extern int pqGets(PQExpBuffer buf, PGconn *conn);
  572. extern int pqGets_append(PQExpBuffer buf, PGconn *conn);
  573. extern int pqPuts(const char *s, PGconn *conn);
  574. extern int pqGetnchar(char *s, size_t len, PGconn *conn);
  575. extern int pqSkipnchar(size_t len, PGconn *conn);
  576. extern int pqPutnchar(const char *s, size_t len, PGconn *conn);
  577. extern int pqGetInt(int *result, size_t bytes, PGconn *conn);
  578. extern int pqPutInt(int value, size_t bytes, PGconn *conn);
  579. extern int pqPutMsgStart(char msg_type, bool force_len, PGconn *conn);
  580. extern int pqPutMsgEnd(PGconn *conn);
  581. extern int pqReadData(PGconn *conn);
  582. extern int pqFlush(PGconn *conn);
  583. extern int pqWait(int forRead, int forWrite, PGconn *conn);
  584. extern int pqWaitTimed(int forRead, int forWrite, PGconn *conn,
  585. time_t finish_time);
  586. extern int pqReadReady(PGconn *conn);
  587. extern int pqWriteReady(PGconn *conn);
  588. /* === in fe-secure.c === */
  589. extern int pqsecure_initialize(PGconn *);
  590. extern void pqsecure_destroy(void);
  591. extern PostgresPollingStatusType pqsecure_open_client(PGconn *);
  592. extern void pqsecure_close(PGconn *);
  593. extern ssize_t pqsecure_read(PGconn *, void *ptr, size_t len);
  594. extern ssize_t pqsecure_write(PGconn *, const void *ptr, size_t len);
  595. extern ssize_t pqsecure_raw_read(PGconn *, void *ptr, size_t len);
  596. extern ssize_t pqsecure_raw_write(PGconn *, const void *ptr, size_t len);
  597. #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
  598. extern int pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending);
  599. extern void pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending,
  600. bool got_epipe);
  601. #endif
  602. /* === SSL === */
  603. /*
  604. * The SSL implementation provides these functions.
  605. */
  606. /*
  607. * Implementation of PQinitSSL().
  608. */
  609. extern void pgtls_init_library(bool do_ssl, int do_crypto);
  610. /*
  611. * Initialize SSL library.
  612. *
  613. * The conn parameter is only used to be able to pass back an error
  614. * message - no connection-local setup is made here.
  615. *
  616. * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
  617. */
  618. extern int pgtls_init(PGconn *conn);
  619. /*
  620. * Begin or continue negotiating a secure session.
  621. */
  622. extern PostgresPollingStatusType pgtls_open_client(PGconn *conn);
  623. /*
  624. * Close SSL connection.
  625. */
  626. extern void pgtls_close(PGconn *conn);
  627. /*
  628. * Read data from a secure connection.
  629. *
  630. * On failure, this function is responsible for putting a suitable message
  631. * into conn->errorMessage. The caller must still inspect errno, but only
  632. * to determine whether to continue/retry after error.
  633. */
  634. extern ssize_t pgtls_read(PGconn *conn, void *ptr, size_t len);
  635. /*
  636. * Is there unread data waiting in the SSL read buffer?
  637. */
  638. extern bool pgtls_read_pending(PGconn *conn);
  639. /*
  640. * Write data to a secure connection.
  641. *
  642. * On failure, this function is responsible for putting a suitable message
  643. * into conn->errorMessage. The caller must still inspect errno, but only
  644. * to determine whether to continue/retry after error.
  645. */
  646. extern ssize_t pgtls_write(PGconn *conn, const void *ptr, size_t len);
  647. /*
  648. * Get the hash of the server certificate, for SCRAM channel binding type
  649. * tls-server-end-point.
  650. *
  651. * NULL is sent back to the caller in the event of an error, with an
  652. * error message for the caller to consume.
  653. *
  654. * This is not supported with old versions of OpenSSL that don't have
  655. * the X509_get_signature_nid() function.
  656. */
  657. #if defined(USE_OPENSSL) && defined(HAVE_X509_GET_SIGNATURE_NID)
  658. #define HAVE_PGTLS_GET_PEER_CERTIFICATE_HASH
  659. extern char *pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len);
  660. #endif
  661. /*
  662. * Verify that the server certificate matches the host name we connected to.
  663. *
  664. * The certificate's Common Name and Subject Alternative Names are considered.
  665. *
  666. * Returns 1 if the name matches, and 0 if it does not. On error, returns
  667. * -1, and sets the libpq error message.
  668. *
  669. */
  670. extern int pgtls_verify_peer_name_matches_certificate_guts(PGconn *conn,
  671. int *names_examined,
  672. char **first_name);
  673. /* === GSSAPI === */
  674. #ifdef ENABLE_GSS
  675. /*
  676. * Establish a GSSAPI-encrypted connection.
  677. */
  678. extern PostgresPollingStatusType pqsecure_open_gss(PGconn *conn);
  679. /*
  680. * Read and write functions for GSSAPI-encrypted connections, with internal
  681. * buffering to handle nonblocking sockets.
  682. */
  683. extern ssize_t pg_GSS_write(PGconn *conn, const void *ptr, size_t len);
  684. extern ssize_t pg_GSS_read(PGconn *conn, void *ptr, size_t len);
  685. #endif
  686. /* === miscellaneous macros === */
  687. /*
  688. * this is so that we can check if a connection is non-blocking internally
  689. * without the overhead of a function call
  690. */
  691. #define pqIsnonblocking(conn) ((conn)->nonblocking)
  692. #ifdef ENABLE_NLS
  693. extern char *libpq_gettext(const char *msgid) pg_attribute_format_arg(1);
  694. extern char *libpq_ngettext(const char *msgid, const char *msgid_plural, unsigned long n) pg_attribute_format_arg(1) pg_attribute_format_arg(2);
  695. #else
  696. #define libpq_gettext(x) (x)
  697. #define libpq_ngettext(s, p, n) ((n) == 1 ? (s) : (p))
  698. #endif
  699. /*
  700. * These macros are needed to let error-handling code be portable between
  701. * Unix and Windows. (ugh)
  702. */
  703. #ifdef WIN32
  704. #define SOCK_ERRNO (WSAGetLastError())
  705. #define SOCK_STRERROR winsock_strerror
  706. #define SOCK_ERRNO_SET(e) WSASetLastError(e)
  707. #else
  708. #define SOCK_ERRNO errno
  709. #define SOCK_STRERROR strerror_r
  710. #define SOCK_ERRNO_SET(e) (errno = (e))
  711. #endif
  712. #endif /* LIBPQ_INT_H */
上海开阖软件有限公司 沪ICP备12045867号-1