Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * libpq-be-fe-helpers.h
4 : : * Helper functions for using libpq in extensions
5 : : *
6 : : * Code built directly into the backend is not allowed to link to libpq
7 : : * directly. Extension code is allowed to use libpq however. However, libpq
8 : : * used in extensions has to be careful not to block inside libpq, otherwise
9 : : * interrupts will not be processed, leading to issues like unresolvable
10 : : * deadlocks. Backend code also needs to take care to acquire/release an
11 : : * external fd for the connection, otherwise fd.c's accounting of fd's is
12 : : * broken.
13 : : *
14 : : * This file provides helper functions to make it easier to comply with these
15 : : * rules. It is a header only library as it needs to be linked into each
16 : : * extension using libpq, and it seems too small to be worth adding a
17 : : * dedicated static library for.
18 : : *
19 : : * TODO: For historical reasons the connections established here are not put
20 : : * into non-blocking mode. That can lead to blocking even when only the async
21 : : * libpq functions are used. This should be fixed.
22 : : *
23 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
24 : : * Portions Copyright (c) 1994, Regents of the University of California
25 : : *
26 : : * src/include/libpq/libpq-be-fe-helpers.h
27 : : *
28 : : *-------------------------------------------------------------------------
29 : : */
30 : : #ifndef LIBPQ_BE_FE_HELPERS_H
31 : : #define LIBPQ_BE_FE_HELPERS_H
32 : :
33 : : #include "libpq/libpq-be-fe.h"
34 : : #include "miscadmin.h"
35 : : #include "storage/fd.h"
36 : : #include "storage/latch.h"
37 : : #include "utils/timestamp.h"
38 : : #include "utils/wait_event.h"
39 : :
40 : :
41 : : extern bool libpqsrv_is_valid_proxy_option(const char *keyword);
42 : :
43 : : static inline void libpqsrv_connect_prepare(void);
44 : : static inline void libpqsrv_connect_complete(PGconn *conn, uint32 wait_event_info);
45 : : static inline PGresult *libpqsrv_get_result_last(PGconn *conn, uint32 wait_event_info);
46 : : static inline PGresult *libpqsrv_get_result(PGconn *conn, uint32 wait_event_info);
47 : :
48 : : /*
49 : : * Ensures that the provided conninfo options are considered safe for use by
50 : : * server-side proxies (FDWs, subscriptions, et al).
51 : : *
52 : : * Server extensions should call this function, which will ereport(ERROR) if an
53 : : * unblessed libpq parameter has been passed, before calling libpqsrv_connect or
54 : : * its variants. This keeps new options from later libpq versions from breaking
55 : : * security assumptions for existing releases during a platform library update.
56 : : *
57 : : * Note that the list of blessed options is subject to change during minor
58 : : * version updates within a major release line.
59 : : */
60 : : static inline void
61 : 991 : libpqsrv_check_proxy_conninfo_opts(const PQconninfoOption *opts)
62 : : {
63 : : const PQconninfoOption *opt;
64 : :
65 [ + + ]: 51434 : for (opt = opts; opt->keyword != NULL; opt++)
66 : : {
67 [ + + + + ]: 50521 : if (opt->val != NULL && !libpqsrv_is_valid_proxy_option(opt->keyword))
68 [ + - ]: 78 : ereport(ERROR,
69 : : errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
70 : : errmsg("permission denied to set connection option \"%s\"",
71 : : opt->keyword));
72 : : }
73 : 913 : }
74 : :
75 : : /*
76 : : * Like libpqsrv_check_proxy_conninfo_opts() above, but additionally parses the
77 : : * conninfo string for the caller.
78 : : */
79 : : static inline void
80 : 993 : libpqsrv_check_proxy_conninfo(const char *conninfo)
81 : : {
82 : : PQconninfoOption *options;
83 : : char *error;
84 : :
85 : 993 : options = PQconninfoParse(conninfo, &error);
86 : :
87 [ + + ]: 993 : PG_TRY();
88 : : {
89 [ + + ]: 993 : if (!options)
90 : : {
91 : : /*
92 : : * Most likely an invalid connection string, but it could also be
93 : : * memory problems. The message and detail here are chosen to
94 : : * mimic the historical behavior of dblink.
95 : : */
96 [ + - + - : 2 : ereport(ERROR,
+ - ]
97 : : error
98 : : ? errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION)
99 : : : errcode(ERRCODE_OUT_OF_MEMORY),
100 : : errmsg("could not establish connection"),
101 : : error
102 : : ? errdetail_internal("%s", pchomp(error))
103 : : : errdetail("out of memory"));
104 : : }
105 : :
106 : 991 : libpqsrv_check_proxy_conninfo_opts(options);
107 : : }
108 : 80 : PG_FINALLY();
109 : : {
110 [ + + ]: 993 : if (error)
111 : 2 : PQfreemem(error);
112 [ + + ]: 993 : if (options)
113 : 991 : PQconninfoFree(options);
114 : : }
115 [ + + ]: 993 : PG_END_TRY();
116 : 913 : }
117 : :
118 : : /*
119 : : * Start a connection using PQconnectStart().
120 : : *
121 : : * The returned connection has not yet completed its startup sequence. Callers
122 : : * may perform per-connection setup, such as installing a notice receiver,
123 : : * before calling libpqsrv_connect_complete().
124 : : *
125 : : * Callers must call libpqsrv_connect_complete(), even if this function returns
126 : : * NULL, because libpqsrv_connect_prepare() may already have reserved an
127 : : * external FD that must be released.
128 : : */
129 : : static inline PGconn *
130 : 24 : libpqsrv_connect_start(const char *conninfo)
131 : : {
132 : 24 : libpqsrv_connect_prepare();
133 : :
134 : 24 : return PQconnectStart(conninfo);
135 : : }
136 : :
137 : : /*
138 : : * PQconnectdb() wrapper that reserves a file descriptor and processes
139 : : * interrupts during connection establishment.
140 : : *
141 : : * Throws an error if AcquireExternalFD() fails, but does not throw if
142 : : * connection establishment itself fails. Callers need to use PQstatus() to
143 : : * check if connection establishment succeeded.
144 : : */
145 : : static inline PGconn *
146 : : libpqsrv_connect(const char *conninfo, uint32 wait_event_info)
147 : : {
148 : : PGconn *conn;
149 : :
150 : : conn = libpqsrv_connect_start(conninfo);
151 : :
152 : : libpqsrv_connect_complete(conn, wait_event_info);
153 : :
154 : : return conn;
155 : : }
156 : :
157 : : /*
158 : : * Start a connection using PQconnectStartParams().
159 : : *
160 : : * See libpqsrv_connect_start() for the resource-lifetime rules.
161 : : */
162 : : static inline PGconn *
163 : 1289 : libpqsrv_connect_params_start(const char *const *keywords,
164 : : const char *const *values,
165 : : int expand_dbname)
166 : : {
167 : 1289 : libpqsrv_connect_prepare();
168 : :
169 : 1289 : return PQconnectStartParams(keywords, values, expand_dbname);
170 : : }
171 : :
172 : : /*
173 : : * Like libpqsrv_connect(), except that this is a wrapper for
174 : : * PQconnectdbParams().
175 : : */
176 : : static inline PGconn *
177 : : libpqsrv_connect_params(const char *const *keywords,
178 : : const char *const *values,
179 : : int expand_dbname,
180 : : uint32 wait_event_info)
181 : : {
182 : : PGconn *conn;
183 : :
184 : : conn = libpqsrv_connect_params_start(keywords, values, expand_dbname);
185 : :
186 : : libpqsrv_connect_complete(conn, wait_event_info);
187 : :
188 : : return conn;
189 : : }
190 : :
191 : : /*
192 : : * PQfinish() wrapper that additionally releases the reserved file descriptor.
193 : : *
194 : : * It is allowed to call this with NULL only when the external FD reservation
195 : : * has already been released, for example after calling
196 : : * libpqsrv_connect_complete() with a NULL connection.
197 : : */
198 : : static inline void
199 : 1303 : libpqsrv_disconnect(PGconn *conn)
200 : : {
201 : : /*
202 : : * If no connection was established, we haven't reserved an FD for it (or
203 : : * already released it). This rule makes it easier to write PG_CATCH()
204 : : * handlers for this facility's users.
205 : : *
206 : : * See also libpqsrv_connect_complete().
207 : : */
208 [ + + ]: 1303 : if (conn == NULL)
209 : 3 : return;
210 : :
211 : 1300 : ReleaseExternalFD();
212 : 1300 : PQfinish(conn);
213 : : }
214 : :
215 : :
216 : : /* lower-level connection helper functions follow */
217 : :
218 : :
219 : : /*
220 : : * Helper function for all connection establishment functions.
221 : : */
222 : : static inline void
223 : 1313 : libpqsrv_connect_prepare(void)
224 : : {
225 : : /*
226 : : * We must obey fd.c's limit on non-virtual file descriptors. Assume that
227 : : * a PGconn represents one long-lived FD. (Doing this here also ensures
228 : : * that VFDs are closed if needed to make room.)
229 : : */
230 [ - + ]: 1313 : if (!AcquireExternalFD())
231 : : {
232 : : #ifndef WIN32 /* can't write #if within ereport() macro */
233 [ # # ]: 0 : ereport(ERROR,
234 : : (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
235 : : errmsg("could not establish connection"),
236 : : errdetail("There are too many open files on the local server."),
237 : : errhint("Raise the server's \"max_files_per_process\" and/or \"ulimit -n\" limits.")));
238 : : #else
239 : : ereport(ERROR,
240 : : (errcode(ERRCODE_SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION),
241 : : errmsg("could not establish connection"),
242 : : errdetail("There are too many open files on the local server."),
243 : : errhint("Raise the server's \"max_files_per_process\" setting.")));
244 : : #endif
245 : : }
246 : 1313 : }
247 : :
248 : : /*
249 : : * Complete a connection started by libpqsrv_connect_start() or
250 : : * libpqsrv_connect_params_start().
251 : : */
252 : : static inline void
253 : 1313 : libpqsrv_connect_complete(PGconn *conn, uint32 wait_event_info)
254 : : {
255 : : /*
256 : : * With conn == NULL libpqsrv_disconnect() wouldn't release the FD. So do
257 : : * that here.
258 : : */
259 [ - + ]: 1313 : if (conn == NULL)
260 : : {
261 : 0 : ReleaseExternalFD();
262 : 0 : return;
263 : : }
264 : :
265 : : /*
266 : : * Can't wait without a socket. Note that we don't want to close the libpq
267 : : * connection yet, so callers can emit a useful error.
268 : : */
269 [ + + ]: 1313 : if (PQstatus(conn) == CONNECTION_BAD)
270 : 89 : return;
271 : :
272 : : /*
273 : : * WaitLatchOrSocket() can conceivably fail, handle that case here instead
274 : : * of requiring all callers to do so.
275 : : */
276 [ + - ]: 1224 : PG_TRY();
277 : : {
278 : : PostgresPollingStatusType status;
279 : :
280 : : /*
281 : : * Poll connection until we have OK or FAILED status.
282 : : *
283 : : * Per spec for PQconnectPoll, first wait till socket is write-ready.
284 : : */
285 : 1224 : status = PGRES_POLLING_WRITING;
286 [ + + + + ]: 5731 : while (status != PGRES_POLLING_OK && status != PGRES_POLLING_FAILED)
287 : : {
288 : : int io_flag;
289 : : int rc;
290 : :
291 [ + + ]: 3286 : if (status == PGRES_POLLING_READING)
292 : 1240 : io_flag = WL_SOCKET_READABLE;
293 : : #ifdef WIN32
294 : :
295 : : /*
296 : : * Windows needs a different test while waiting for
297 : : * connection-made
298 : : */
299 : : else if (PQstatus(conn) == CONNECTION_STARTED)
300 : : io_flag = WL_SOCKET_CONNECTED;
301 : : #endif
302 : : else
303 : 2046 : io_flag = WL_SOCKET_WRITEABLE;
304 : :
305 : 3286 : rc = WaitLatchOrSocket(MyLatch,
306 : : WL_EXIT_ON_PM_DEATH | WL_LATCH_SET | io_flag,
307 : : PQsocket(conn),
308 : : 0,
309 : : wait_event_info);
310 : :
311 : : /* Interrupted? */
312 [ + + ]: 3286 : if (rc & WL_LATCH_SET)
313 : : {
314 : 826 : ResetLatch(MyLatch);
315 [ + + ]: 826 : CHECK_FOR_INTERRUPTS();
316 : : }
317 : :
318 : : /* If socket is ready, advance the libpq state machine */
319 [ + + ]: 3283 : if (rc & io_flag)
320 : 2460 : status = PQconnectPoll(conn);
321 : : }
322 : : }
323 : 0 : PG_CATCH();
324 : : {
325 : : /*
326 : : * If an error is thrown here, the callers won't call
327 : : * libpqsrv_disconnect() with a conn, so release resources
328 : : * immediately.
329 : : */
330 : 0 : ReleaseExternalFD();
331 : 0 : PQfinish(conn);
332 : :
333 : 0 : PG_RE_THROW();
334 : : }
335 [ - + ]: 1221 : PG_END_TRY();
336 : : }
337 : :
338 : : /*
339 : : * PQexec() wrapper that processes interrupts.
340 : : *
341 : : * Unless PQsetnonblocking(conn, 1) is in effect, this can't process
342 : : * interrupts while pushing the query text to the server. Consider that
343 : : * setting if query strings can be long relative to TCP buffer size.
344 : : *
345 : : * This has the preconditions of PQsendQuery(), not those of PQexec(). Most
346 : : * notably, PQexec() would silently discard any prior query results.
347 : : */
348 : : static inline PGresult *
349 : 4867 : libpqsrv_exec(PGconn *conn, const char *query, uint32 wait_event_info)
350 : : {
351 [ - + ]: 4867 : if (!PQsendQuery(conn, query))
352 : 0 : return NULL;
353 : 4867 : return libpqsrv_get_result_last(conn, wait_event_info);
354 : : }
355 : :
356 : : /*
357 : : * PQexecParams() wrapper that processes interrupts.
358 : : *
359 : : * See notes at libpqsrv_exec().
360 : : */
361 : : static inline PGresult *
362 : : libpqsrv_exec_params(PGconn *conn,
363 : : const char *command,
364 : : int nParams,
365 : : const Oid *paramTypes,
366 : : const char *const *paramValues,
367 : : const int *paramLengths,
368 : : const int *paramFormats,
369 : : int resultFormat,
370 : : uint32 wait_event_info)
371 : : {
372 : : if (!PQsendQueryParams(conn, command, nParams, paramTypes, paramValues,
373 : : paramLengths, paramFormats, resultFormat))
374 : : return NULL;
375 : : return libpqsrv_get_result_last(conn, wait_event_info);
376 : : }
377 : :
378 : : /*
379 : : * Like PQexec(), loop over PQgetResult() until it returns NULL or another
380 : : * terminal state. Return the last non-NULL result or the terminal state.
381 : : */
382 : : static inline PGresult *
383 : 14915 : libpqsrv_get_result_last(PGconn *conn, uint32 wait_event_info)
384 : : {
385 : 14915 : PGresult *lastResult = NULL;
386 : :
387 : : for (;;)
388 : 13970 : {
389 : : /* Wait for, and collect, the next PGresult. */
390 : : PGresult *result;
391 : :
392 : 28885 : result = libpqsrv_get_result(conn, wait_event_info);
393 [ + + ]: 28884 : if (result == NULL)
394 : 13964 : break; /* query is complete, or failure */
395 : :
396 : : /*
397 : : * Emulate PQexec()'s behavior of returning the last result when there
398 : : * are many.
399 : : */
400 : 14920 : PQclear(lastResult);
401 : 14920 : lastResult = result;
402 : :
403 [ + - + + ]: 29840 : if (PQresultStatus(lastResult) == PGRES_COPY_IN ||
404 [ + + ]: 29619 : PQresultStatus(lastResult) == PGRES_COPY_OUT ||
405 [ + + ]: 28673 : PQresultStatus(lastResult) == PGRES_COPY_BOTH ||
406 : 13974 : PQstatus(conn) == CONNECTION_BAD)
407 : : break;
408 : : }
409 : 14914 : return lastResult;
410 : : }
411 : :
412 : : /*
413 : : * Perform the equivalent of PQgetResult(), but watch for interrupts.
414 : : */
415 : : static inline PGresult *
416 : 30363 : libpqsrv_get_result(PGconn *conn, uint32 wait_event_info)
417 : : {
418 : : /*
419 : : * Collect data until PQgetResult is ready to get the result without
420 : : * blocking.
421 : : */
422 [ + + ]: 45162 : while (PQisBusy(conn))
423 : : {
424 : : int rc;
425 : :
426 : 14857 : rc = WaitLatchOrSocket(MyLatch,
427 : : WL_EXIT_ON_PM_DEATH | WL_LATCH_SET |
428 : : WL_SOCKET_READABLE,
429 : : PQsocket(conn),
430 : : 0,
431 : : wait_event_info);
432 : :
433 : : /* Interrupted? */
434 [ + + ]: 14857 : if (rc & WL_LATCH_SET)
435 : : {
436 : 22 : ResetLatch(MyLatch);
437 [ + + ]: 22 : CHECK_FOR_INTERRUPTS();
438 : : }
439 : :
440 : : /* Consume whatever data is available from the socket */
441 [ + + ]: 14856 : if (PQconsumeInput(conn) == 0)
442 : : {
443 : : /* trouble; expect PQgetResult() to return NULL */
444 : 57 : break;
445 : : }
446 : : }
447 : :
448 : : /* Now we can collect and return the next PGresult */
449 : 30362 : return PQgetResult(conn);
450 : : }
451 : :
452 : : /*
453 : : * Submit a cancel request to the given connection, waiting only until
454 : : * the given time.
455 : : *
456 : : * We sleep interruptibly until we receive confirmation that the cancel
457 : : * request has been accepted, and if it is, return NULL; if the cancel
458 : : * request fails, return an error message string (which is not to be
459 : : * freed).
460 : : *
461 : : * For other problems (to wit: OOM when strdup'ing an error message from
462 : : * libpq), this function can ereport(ERROR).
463 : : *
464 : : * Note: this function leaks a string's worth of memory when reporting
465 : : * libpq errors. Make sure to call it in a transient memory context.
466 : : */
467 : : static inline const char *
468 : 3 : libpqsrv_cancel(PGconn *conn, TimestampTz endtime)
469 : : {
470 : : PGcancelConn *cancel_conn;
471 : 3 : const char *error = NULL;
472 : :
473 : 3 : cancel_conn = PQcancelCreate(conn);
474 [ - + ]: 3 : if (cancel_conn == NULL)
475 : 0 : return "out of memory";
476 : :
477 : : /* In what follows, do not leak any PGcancelConn on any errors. */
478 : :
479 [ + - ]: 3 : PG_TRY();
480 : : {
481 [ - + ]: 3 : if (!PQcancelStart(cancel_conn))
482 : : {
483 : 0 : error = pchomp(PQcancelErrorMessage(cancel_conn));
484 : 0 : goto exit;
485 : : }
486 : :
487 : : for (;;)
488 : 3 : {
489 : : PostgresPollingStatusType pollres;
490 : : TimestampTz now;
491 : : long cur_timeout;
492 : 6 : int waitEvents = WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH;
493 : :
494 : 6 : pollres = PQcancelPoll(cancel_conn);
495 [ + + ]: 6 : if (pollres == PGRES_POLLING_OK)
496 : 3 : break; /* success! */
497 : :
498 : : /* If timeout has expired, give up, else get sleep time. */
499 : 3 : now = GetCurrentTimestamp();
500 : 3 : cur_timeout = TimestampDifferenceMilliseconds(now, endtime);
501 [ - + ]: 3 : if (cur_timeout <= 0)
502 : : {
503 : 0 : error = "cancel request timed out";
504 : 0 : break;
505 : : }
506 : :
507 [ + - - ]: 3 : switch (pollres)
508 : : {
509 : 3 : case PGRES_POLLING_READING:
510 : 3 : waitEvents |= WL_SOCKET_READABLE;
511 : 3 : break;
512 : 0 : case PGRES_POLLING_WRITING:
513 : 0 : waitEvents |= WL_SOCKET_WRITEABLE;
514 : 0 : break;
515 : 0 : default:
516 : 0 : error = pchomp(PQcancelErrorMessage(cancel_conn));
517 : 0 : goto exit;
518 : : }
519 : :
520 : : /* Sleep until there's something to do */
521 : 3 : WaitLatchOrSocket(MyLatch, waitEvents, PQcancelSocket(cancel_conn),
522 : : cur_timeout, PG_WAIT_CLIENT);
523 : :
524 : 3 : ResetLatch(MyLatch);
525 : :
526 [ - + ]: 3 : CHECK_FOR_INTERRUPTS();
527 : : }
528 : 3 : exit: ;
529 : : }
530 : 0 : PG_FINALLY();
531 : : {
532 : 3 : PQcancelFinish(cancel_conn);
533 : : }
534 [ - + ]: 3 : PG_END_TRY();
535 : :
536 : 3 : return error;
537 : : }
538 : :
539 : : /*
540 : : * libpqsrv_notice_receiver
541 : : *
542 : : * Custom notice receiver for libpq connections.
543 : : *
544 : : * This function is intended to be set via PQsetNoticeReceiver() so that
545 : : * NOTICE, WARNING, and similar messages from the connection are reported via
546 : : * ereport(), instead of being printed to stderr.
547 : : *
548 : : * Because this will be called from libpq with a "real" (not wrapped)
549 : : * PGresult, we need to temporarily ignore libpq-be-fe.h's wrapper macros
550 : : * for PGresult and also PQresultErrorMessage, and put back the wrappers
551 : : * afterwards. That's not pretty, but there seems no better alternative.
552 : : */
553 : : #undef PGresult
554 : : #undef PQresultErrorMessage
555 : :
556 : : static inline void
557 : 17 : libpqsrv_notice_receiver(void *arg, const PGresult *res)
558 : : {
559 : : const char *message;
560 : : int len;
561 : 17 : const char *prefix = (const char *) arg;
562 : :
563 : : /*
564 : : * Trim the trailing newline from the message text returned from
565 : : * PQresultErrorMessage(), as it always includes one, to produce cleaner
566 : : * log output.
567 : : */
568 : 17 : message = PQresultErrorMessage(res);
569 : 17 : len = strlen(message);
570 [ + - + - ]: 17 : if (len > 0 && message[len - 1] == '\n')
571 : 17 : len--;
572 : :
573 : : /*
574 : : * Omit the local statement and context from each remote message. They can
575 : : * help identify the caller, but repeating them for every message could
576 : : * greatly increase log volume.
577 : : */
578 [ + - ]: 17 : ereport(LOG,
579 : : errmsg_internal("%s: %.*s", prefix, len, message),
580 : : errhidestmt(true),
581 : : errhidecontext(true));
582 : 17 : }
583 : :
584 : : #define PGresult libpqsrv_PGresult
585 : : #define PQresultErrorMessage libpqsrv_PQresultErrorMessage
586 : :
587 : : #endif /* LIBPQ_BE_FE_HELPERS_H */
|