Be more wary about OpenSSL not setting errno on error.
[pgsql.git] / src / backend / libpq / pqcomm.c
blob67535449a665fea28ac3ca555e1b1cfd1ce8e0aa
1 /*-------------------------------------------------------------------------
3 * pqcomm.c
4 * Communication functions between the Frontend and the Backend
6 * These routines handle the low-level details of communication between
7 * frontend and backend. They just shove data across the communication
8 * channel, and are ignorant of the semantics of the data.
10 * To emit an outgoing message, use the routines in pqformat.c to construct
11 * the message in a buffer and then emit it in one call to pq_putmessage.
12 * There are no functions to send raw bytes or partial messages; this
13 * ensures that the channel will not be clogged by an incomplete message if
14 * execution is aborted by ereport(ERROR) partway through the message.
16 * At one time, libpq was shared between frontend and backend, but now
17 * the backend's "backend/libpq" is quite separate from "interfaces/libpq".
18 * All that remains is similarities of names to trap the unwary...
20 * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
21 * Portions Copyright (c) 1994, Regents of the University of California
23 * src/backend/libpq/pqcomm.c
25 *-------------------------------------------------------------------------
28 /*------------------------
29 * INTERFACE ROUTINES
31 * setup/teardown:
32 * StreamServerPort - Open postmaster's server port
33 * StreamConnection - Create new connection with client
34 * StreamClose - Close a client/backend connection
35 * TouchSocketFiles - Protect socket files against /tmp cleaners
36 * pq_init - initialize libpq at backend startup
37 * socket_comm_reset - reset libpq during error recovery
38 * socket_close - shutdown libpq at backend exit
40 * low-level I/O:
41 * pq_getbytes - get a known number of bytes from connection
42 * pq_getmessage - get a message with length word from connection
43 * pq_getbyte - get next byte from connection
44 * pq_peekbyte - peek at next byte from connection
45 * pq_flush - flush pending output
46 * pq_flush_if_writable - flush pending output if writable without blocking
47 * pq_getbyte_if_available - get a byte if available without blocking
49 * message-level I/O
50 * pq_putmessage - send a normal message (suppressed in COPY OUT mode)
51 * pq_putmessage_noblock - buffer a normal message (suppressed in COPY OUT)
53 *------------------------
55 #include "postgres.h"
57 #ifdef HAVE_POLL_H
58 #include <poll.h>
59 #endif
60 #include <signal.h>
61 #include <fcntl.h>
62 #include <grp.h>
63 #include <unistd.h>
64 #include <sys/file.h>
65 #include <sys/socket.h>
66 #include <sys/stat.h>
67 #include <sys/time.h>
68 #include <netdb.h>
69 #include <netinet/in.h>
70 #include <netinet/tcp.h>
71 #include <utime.h>
72 #ifdef WIN32
73 #include <mstcpip.h>
74 #endif
76 #include "common/ip.h"
77 #include "libpq/libpq.h"
78 #include "miscadmin.h"
79 #include "port/pg_bswap.h"
80 #include "storage/ipc.h"
81 #include "utils/guc_hooks.h"
82 #include "utils/memutils.h"
85 * Cope with the various platform-specific ways to spell TCP keepalive socket
86 * options. This doesn't cover Windows, which as usual does its own thing.
88 #if defined(TCP_KEEPIDLE)
89 /* TCP_KEEPIDLE is the name of this option on Linux and *BSD */
90 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPIDLE
91 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPIDLE"
92 #elif defined(TCP_KEEPALIVE_THRESHOLD)
93 /* TCP_KEEPALIVE_THRESHOLD is the name of this option on Solaris >= 11 */
94 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE_THRESHOLD
95 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE_THRESHOLD"
96 #elif defined(TCP_KEEPALIVE) && defined(__darwin__)
97 /* TCP_KEEPALIVE is the name of this option on macOS */
98 /* Caution: Solaris has this symbol but it means something different */
99 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE
100 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE"
101 #endif
104 * Configuration options
106 int Unix_socket_permissions;
107 char *Unix_socket_group;
109 /* Where the Unix socket files are (list of palloc'd strings) */
110 static List *sock_paths = NIL;
113 * Buffers for low-level I/O.
115 * The receive buffer is fixed size. Send buffer is usually 8k, but can be
116 * enlarged by pq_putmessage_noblock() if the message doesn't fit otherwise.
119 #define PQ_SEND_BUFFER_SIZE 8192
120 #define PQ_RECV_BUFFER_SIZE 8192
122 static char *PqSendBuffer;
123 static int PqSendBufferSize; /* Size send buffer */
124 static int PqSendPointer; /* Next index to store a byte in PqSendBuffer */
125 static int PqSendStart; /* Next index to send a byte in PqSendBuffer */
127 static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE];
128 static int PqRecvPointer; /* Next index to read a byte from PqRecvBuffer */
129 static int PqRecvLength; /* End of data available in PqRecvBuffer */
132 * Message status
134 static bool PqCommBusy; /* busy sending data to the client */
135 static bool PqCommReadingMsg; /* in the middle of reading a message */
138 /* Internal functions */
139 static void socket_comm_reset(void);
140 static void socket_close(int code, Datum arg);
141 static void socket_set_nonblocking(bool nonblocking);
142 static int socket_flush(void);
143 static int socket_flush_if_writable(void);
144 static bool socket_is_send_pending(void);
145 static int socket_putmessage(char msgtype, const char *s, size_t len);
146 static void socket_putmessage_noblock(char msgtype, const char *s, size_t len);
147 static int internal_putbytes(const char *s, size_t len);
148 static int internal_flush(void);
150 static int Lock_AF_UNIX(const char *unixSocketDir, const char *unixSocketPath);
151 static int Setup_AF_UNIX(const char *sock_path);
153 static const PQcommMethods PqCommSocketMethods = {
154 socket_comm_reset,
155 socket_flush,
156 socket_flush_if_writable,
157 socket_is_send_pending,
158 socket_putmessage,
159 socket_putmessage_noblock
162 const PQcommMethods *PqCommMethods = &PqCommSocketMethods;
164 WaitEventSet *FeBeWaitSet;
167 /* --------------------------------
168 * pq_init - initialize libpq at backend startup
169 * --------------------------------
171 void
172 pq_init(void)
174 int socket_pos PG_USED_FOR_ASSERTS_ONLY;
175 int latch_pos PG_USED_FOR_ASSERTS_ONLY;
177 /* initialize state variables */
178 PqSendBufferSize = PQ_SEND_BUFFER_SIZE;
179 PqSendBuffer = MemoryContextAlloc(TopMemoryContext, PqSendBufferSize);
180 PqSendPointer = PqSendStart = PqRecvPointer = PqRecvLength = 0;
181 PqCommBusy = false;
182 PqCommReadingMsg = false;
184 /* set up process-exit hook to close the socket */
185 on_proc_exit(socket_close, 0);
188 * In backends (as soon as forked) we operate the underlying socket in
189 * nonblocking mode and use latches to implement blocking semantics if
190 * needed. That allows us to provide safely interruptible reads and
191 * writes.
193 * Use COMMERROR on failure, because ERROR would try to send the error to
194 * the client, which might require changing the mode again, leading to
195 * infinite recursion.
197 #ifndef WIN32
198 if (!pg_set_noblock(MyProcPort->sock))
199 ereport(COMMERROR,
200 (errmsg("could not set socket to nonblocking mode: %m")));
201 #endif
203 #ifndef WIN32
205 /* Don't give the socket to any subprograms we execute. */
206 if (fcntl(MyProcPort->sock, F_SETFD, FD_CLOEXEC) < 0)
207 elog(FATAL, "fcntl(F_SETFD) failed on socket: %m");
208 #endif
210 FeBeWaitSet = CreateWaitEventSet(TopMemoryContext, FeBeWaitSetNEvents);
211 socket_pos = AddWaitEventToSet(FeBeWaitSet, WL_SOCKET_WRITEABLE,
212 MyProcPort->sock, NULL, NULL);
213 latch_pos = AddWaitEventToSet(FeBeWaitSet, WL_LATCH_SET, PGINVALID_SOCKET,
214 MyLatch, NULL);
215 AddWaitEventToSet(FeBeWaitSet, WL_POSTMASTER_DEATH, PGINVALID_SOCKET,
216 NULL, NULL);
219 * The event positions match the order we added them, but let's sanity
220 * check them to be sure.
222 Assert(socket_pos == FeBeWaitSetSocketPos);
223 Assert(latch_pos == FeBeWaitSetLatchPos);
226 /* --------------------------------
227 * socket_comm_reset - reset libpq during error recovery
229 * This is called from error recovery at the outer idle loop. It's
230 * just to get us out of trouble if we somehow manage to elog() from
231 * inside a pqcomm.c routine (which ideally will never happen, but...)
232 * --------------------------------
234 static void
235 socket_comm_reset(void)
237 /* Do not throw away pending data, but do reset the busy flag */
238 PqCommBusy = false;
241 /* --------------------------------
242 * socket_close - shutdown libpq at backend exit
244 * This is the one pg_on_exit_callback in place during BackendInitialize().
245 * That function's unusual signal handling constrains that this callback be
246 * safe to run at any instant.
247 * --------------------------------
249 static void
250 socket_close(int code, Datum arg)
252 /* Nothing to do in a standalone backend, where MyProcPort is NULL. */
253 if (MyProcPort != NULL)
255 #ifdef ENABLE_GSS
257 * Shutdown GSSAPI layer. This section does nothing when interrupting
258 * BackendInitialize(), because pg_GSS_recvauth() makes first use of
259 * "ctx" and "cred".
261 * Note that we don't bother to free MyProcPort->gss, since we're
262 * about to exit anyway.
264 if (MyProcPort->gss)
266 OM_uint32 min_s;
268 if (MyProcPort->gss->ctx != GSS_C_NO_CONTEXT)
269 gss_delete_sec_context(&min_s, &MyProcPort->gss->ctx, NULL);
271 if (MyProcPort->gss->cred != GSS_C_NO_CREDENTIAL)
272 gss_release_cred(&min_s, &MyProcPort->gss->cred);
274 #endif /* ENABLE_GSS */
277 * Cleanly shut down SSL layer. Nowhere else does a postmaster child
278 * call this, so this is safe when interrupting BackendInitialize().
280 secure_close(MyProcPort);
283 * Formerly we did an explicit close() here, but it seems better to
284 * leave the socket open until the process dies. This allows clients
285 * to perform a "synchronous close" if they care --- wait till the
286 * transport layer reports connection closure, and you can be sure the
287 * backend has exited.
289 * We do set sock to PGINVALID_SOCKET to prevent any further I/O,
290 * though.
292 MyProcPort->sock = PGINVALID_SOCKET;
299 * Streams -- wrapper around Unix socket system calls
302 * Stream functions are used for vanilla TCP connection protocol.
307 * StreamServerPort -- open a "listening" port to accept connections.
309 * family should be AF_UNIX or AF_UNSPEC; portNumber is the port number.
310 * For AF_UNIX ports, hostName should be NULL and unixSocketDir must be
311 * specified. For TCP ports, hostName is either NULL for all interfaces or
312 * the interface to listen on, and unixSocketDir is ignored (can be NULL).
314 * Successfully opened sockets are added to the ListenSocket[] array (of
315 * length MaxListen), at the first position that isn't PGINVALID_SOCKET.
317 * RETURNS: STATUS_OK or STATUS_ERROR
321 StreamServerPort(int family, const char *hostName, unsigned short portNumber,
322 const char *unixSocketDir,
323 pgsocket ListenSocket[], int MaxListen)
325 pgsocket fd;
326 int err;
327 int maxconn;
328 int ret;
329 char portNumberStr[32];
330 const char *familyDesc;
331 char familyDescBuf[64];
332 const char *addrDesc;
333 char addrBuf[NI_MAXHOST];
334 char *service;
335 struct addrinfo *addrs = NULL,
336 *addr;
337 struct addrinfo hint;
338 int listen_index = 0;
339 int added = 0;
340 char unixSocketPath[MAXPGPATH];
341 #if !defined(WIN32) || defined(IPV6_V6ONLY)
342 int one = 1;
343 #endif
345 /* Initialize hint structure */
346 MemSet(&hint, 0, sizeof(hint));
347 hint.ai_family = family;
348 hint.ai_flags = AI_PASSIVE;
349 hint.ai_socktype = SOCK_STREAM;
351 if (family == AF_UNIX)
354 * Create unixSocketPath from portNumber and unixSocketDir and lock
355 * that file path
357 UNIXSOCK_PATH(unixSocketPath, portNumber, unixSocketDir);
358 if (strlen(unixSocketPath) >= UNIXSOCK_PATH_BUFLEN)
360 ereport(LOG,
361 (errmsg("Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
362 unixSocketPath,
363 (int) (UNIXSOCK_PATH_BUFLEN - 1))));
364 return STATUS_ERROR;
366 if (Lock_AF_UNIX(unixSocketDir, unixSocketPath) != STATUS_OK)
367 return STATUS_ERROR;
368 service = unixSocketPath;
370 else
372 snprintf(portNumberStr, sizeof(portNumberStr), "%d", portNumber);
373 service = portNumberStr;
376 ret = pg_getaddrinfo_all(hostName, service, &hint, &addrs);
377 if (ret || !addrs)
379 if (hostName)
380 ereport(LOG,
381 (errmsg("could not translate host name \"%s\", service \"%s\" to address: %s",
382 hostName, service, gai_strerror(ret))));
383 else
384 ereport(LOG,
385 (errmsg("could not translate service \"%s\" to address: %s",
386 service, gai_strerror(ret))));
387 if (addrs)
388 pg_freeaddrinfo_all(hint.ai_family, addrs);
389 return STATUS_ERROR;
392 for (addr = addrs; addr; addr = addr->ai_next)
394 if (family != AF_UNIX && addr->ai_family == AF_UNIX)
397 * Only set up a unix domain socket when they really asked for it.
398 * The service/port is different in that case.
400 continue;
403 /* See if there is still room to add 1 more socket. */
404 for (; listen_index < MaxListen; listen_index++)
406 if (ListenSocket[listen_index] == PGINVALID_SOCKET)
407 break;
409 if (listen_index >= MaxListen)
411 ereport(LOG,
412 (errmsg("could not bind to all requested addresses: MAXLISTEN (%d) exceeded",
413 MaxListen)));
414 break;
417 /* set up address family name for log messages */
418 switch (addr->ai_family)
420 case AF_INET:
421 familyDesc = _("IPv4");
422 break;
423 case AF_INET6:
424 familyDesc = _("IPv6");
425 break;
426 case AF_UNIX:
427 familyDesc = _("Unix");
428 break;
429 default:
430 snprintf(familyDescBuf, sizeof(familyDescBuf),
431 _("unrecognized address family %d"),
432 addr->ai_family);
433 familyDesc = familyDescBuf;
434 break;
437 /* set up text form of address for log messages */
438 if (addr->ai_family == AF_UNIX)
439 addrDesc = unixSocketPath;
440 else
442 pg_getnameinfo_all((const struct sockaddr_storage *) addr->ai_addr,
443 addr->ai_addrlen,
444 addrBuf, sizeof(addrBuf),
445 NULL, 0,
446 NI_NUMERICHOST);
447 addrDesc = addrBuf;
450 if ((fd = socket(addr->ai_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
452 ereport(LOG,
453 (errcode_for_socket_access(),
454 /* translator: first %s is IPv4, IPv6, or Unix */
455 errmsg("could not create %s socket for address \"%s\": %m",
456 familyDesc, addrDesc)));
457 continue;
460 #ifndef WIN32
463 * Without the SO_REUSEADDR flag, a new postmaster can't be started
464 * right away after a stop or crash, giving "address already in use"
465 * error on TCP ports.
467 * On win32, however, this behavior only happens if the
468 * SO_EXCLUSIVEADDRUSE is set. With SO_REUSEADDR, win32 allows
469 * multiple servers to listen on the same address, resulting in
470 * unpredictable behavior. With no flags at all, win32 behaves as Unix
471 * with SO_REUSEADDR.
473 if (addr->ai_family != AF_UNIX)
475 if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
476 (char *) &one, sizeof(one))) == -1)
478 ereport(LOG,
479 (errcode_for_socket_access(),
480 /* translator: third %s is IPv4, IPv6, or Unix */
481 errmsg("%s(%s) failed for %s address \"%s\": %m",
482 "setsockopt", "SO_REUSEADDR",
483 familyDesc, addrDesc)));
484 closesocket(fd);
485 continue;
488 #endif
490 #ifdef IPV6_V6ONLY
491 if (addr->ai_family == AF_INET6)
493 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
494 (char *) &one, sizeof(one)) == -1)
496 ereport(LOG,
497 (errcode_for_socket_access(),
498 /* translator: third %s is IPv4, IPv6, or Unix */
499 errmsg("%s(%s) failed for %s address \"%s\": %m",
500 "setsockopt", "IPV6_V6ONLY",
501 familyDesc, addrDesc)));
502 closesocket(fd);
503 continue;
506 #endif
509 * Note: This might fail on some OS's, like Linux older than
510 * 2.4.21-pre3, that don't have the IPV6_V6ONLY socket option, and map
511 * ipv4 addresses to ipv6. It will show ::ffff:ipv4 for all ipv4
512 * connections.
514 err = bind(fd, addr->ai_addr, addr->ai_addrlen);
515 if (err < 0)
517 int saved_errno = errno;
519 ereport(LOG,
520 (errcode_for_socket_access(),
521 /* translator: first %s is IPv4, IPv6, or Unix */
522 errmsg("could not bind %s address \"%s\": %m",
523 familyDesc, addrDesc),
524 saved_errno == EADDRINUSE ?
525 (addr->ai_family == AF_UNIX ?
526 errhint("Is another postmaster already running on port %d?",
527 (int) portNumber) :
528 errhint("Is another postmaster already running on port %d?"
529 " If not, wait a few seconds and retry.",
530 (int) portNumber)) : 0));
531 closesocket(fd);
532 continue;
535 if (addr->ai_family == AF_UNIX)
537 if (Setup_AF_UNIX(service) != STATUS_OK)
539 closesocket(fd);
540 break;
545 * Select appropriate accept-queue length limit. It seems reasonable
546 * to use a value similar to the maximum number of child processes
547 * that the postmaster will permit.
549 maxconn = MaxConnections * 2;
551 err = listen(fd, maxconn);
552 if (err < 0)
554 ereport(LOG,
555 (errcode_for_socket_access(),
556 /* translator: first %s is IPv4, IPv6, or Unix */
557 errmsg("could not listen on %s address \"%s\": %m",
558 familyDesc, addrDesc)));
559 closesocket(fd);
560 continue;
563 if (addr->ai_family == AF_UNIX)
564 ereport(LOG,
565 (errmsg("listening on Unix socket \"%s\"",
566 addrDesc)));
567 else
568 ereport(LOG,
569 /* translator: first %s is IPv4 or IPv6 */
570 (errmsg("listening on %s address \"%s\", port %d",
571 familyDesc, addrDesc, (int) portNumber)));
573 ListenSocket[listen_index] = fd;
574 added++;
577 pg_freeaddrinfo_all(hint.ai_family, addrs);
579 if (!added)
580 return STATUS_ERROR;
582 return STATUS_OK;
587 * Lock_AF_UNIX -- configure unix socket file path
589 static int
590 Lock_AF_UNIX(const char *unixSocketDir, const char *unixSocketPath)
592 /* no lock file for abstract sockets */
593 if (unixSocketPath[0] == '@')
594 return STATUS_OK;
597 * Grab an interlock file associated with the socket file.
599 * Note: there are two reasons for using a socket lock file, rather than
600 * trying to interlock directly on the socket itself. First, it's a lot
601 * more portable, and second, it lets us remove any pre-existing socket
602 * file without race conditions.
604 CreateSocketLockFile(unixSocketPath, true, unixSocketDir);
607 * Once we have the interlock, we can safely delete any pre-existing
608 * socket file to avoid failure at bind() time.
610 (void) unlink(unixSocketPath);
613 * Remember socket file pathnames for later maintenance.
615 sock_paths = lappend(sock_paths, pstrdup(unixSocketPath));
617 return STATUS_OK;
622 * Setup_AF_UNIX -- configure unix socket permissions
624 static int
625 Setup_AF_UNIX(const char *sock_path)
627 /* no file system permissions for abstract sockets */
628 if (sock_path[0] == '@')
629 return STATUS_OK;
632 * Fix socket ownership/permission if requested. Note we must do this
633 * before we listen() to avoid a window where unwanted connections could
634 * get accepted.
636 Assert(Unix_socket_group);
637 if (Unix_socket_group[0] != '\0')
639 #ifdef WIN32
640 elog(WARNING, "configuration item unix_socket_group is not supported on this platform");
641 #else
642 char *endptr;
643 unsigned long val;
644 gid_t gid;
646 val = strtoul(Unix_socket_group, &endptr, 10);
647 if (*endptr == '\0')
648 { /* numeric group id */
649 gid = val;
651 else
652 { /* convert group name to id */
653 struct group *gr;
655 gr = getgrnam(Unix_socket_group);
656 if (!gr)
658 ereport(LOG,
659 (errmsg("group \"%s\" does not exist",
660 Unix_socket_group)));
661 return STATUS_ERROR;
663 gid = gr->gr_gid;
665 if (chown(sock_path, -1, gid) == -1)
667 ereport(LOG,
668 (errcode_for_file_access(),
669 errmsg("could not set group of file \"%s\": %m",
670 sock_path)));
671 return STATUS_ERROR;
673 #endif
676 if (chmod(sock_path, Unix_socket_permissions) == -1)
678 ereport(LOG,
679 (errcode_for_file_access(),
680 errmsg("could not set permissions of file \"%s\": %m",
681 sock_path)));
682 return STATUS_ERROR;
684 return STATUS_OK;
689 * StreamConnection -- create a new connection with client using
690 * server port. Set port->sock to the FD of the new connection.
692 * ASSUME: that this doesn't need to be non-blocking because
693 * the Postmaster waits for the socket to be ready to accept().
695 * RETURNS: STATUS_OK or STATUS_ERROR
698 StreamConnection(pgsocket server_fd, Port *port)
700 /* accept connection and fill in the client (remote) address */
701 port->raddr.salen = sizeof(port->raddr.addr);
702 if ((port->sock = accept(server_fd,
703 (struct sockaddr *) &port->raddr.addr,
704 &port->raddr.salen)) == PGINVALID_SOCKET)
706 ereport(LOG,
707 (errcode_for_socket_access(),
708 errmsg("could not accept new connection: %m")));
711 * If accept() fails then postmaster.c will still see the server
712 * socket as read-ready, and will immediately try again. To avoid
713 * uselessly sucking lots of CPU, delay a bit before trying again.
714 * (The most likely reason for failure is being out of kernel file
715 * table slots; we can do little except hope some will get freed up.)
717 pg_usleep(100000L); /* wait 0.1 sec */
718 return STATUS_ERROR;
721 /* fill in the server (local) address */
722 port->laddr.salen = sizeof(port->laddr.addr);
723 if (getsockname(port->sock,
724 (struct sockaddr *) &port->laddr.addr,
725 &port->laddr.salen) < 0)
727 ereport(LOG,
728 (errmsg("%s() failed: %m", "getsockname")));
729 return STATUS_ERROR;
732 /* select NODELAY and KEEPALIVE options if it's a TCP connection */
733 if (port->laddr.addr.ss_family != AF_UNIX)
735 int on;
736 #ifdef WIN32
737 int oldopt;
738 int optlen;
739 int newopt;
740 #endif
742 #ifdef TCP_NODELAY
743 on = 1;
744 if (setsockopt(port->sock, IPPROTO_TCP, TCP_NODELAY,
745 (char *) &on, sizeof(on)) < 0)
747 ereport(LOG,
748 (errmsg("%s(%s) failed: %m", "setsockopt", "TCP_NODELAY")));
749 return STATUS_ERROR;
751 #endif
752 on = 1;
753 if (setsockopt(port->sock, SOL_SOCKET, SO_KEEPALIVE,
754 (char *) &on, sizeof(on)) < 0)
756 ereport(LOG,
757 (errmsg("%s(%s) failed: %m", "setsockopt", "SO_KEEPALIVE")));
758 return STATUS_ERROR;
761 #ifdef WIN32
764 * This is a Win32 socket optimization. The OS send buffer should be
765 * large enough to send the whole Postgres send buffer in one go, or
766 * performance suffers. The Postgres send buffer can be enlarged if a
767 * very large message needs to be sent, but we won't attempt to
768 * enlarge the OS buffer if that happens, so somewhat arbitrarily
769 * ensure that the OS buffer is at least PQ_SEND_BUFFER_SIZE * 4.
770 * (That's 32kB with the current default).
772 * The default OS buffer size used to be 8kB in earlier Windows
773 * versions, but was raised to 64kB in Windows 2012. So it shouldn't
774 * be necessary to change it in later versions anymore. Changing it
775 * unnecessarily can even reduce performance, because setting
776 * SO_SNDBUF in the application disables the "dynamic send buffering"
777 * feature that was introduced in Windows 7. So before fiddling with
778 * SO_SNDBUF, check if the current buffer size is already large enough
779 * and only increase it if necessary.
781 * See https://support.microsoft.com/kb/823764/EN-US/ and
782 * https://msdn.microsoft.com/en-us/library/bb736549%28v=vs.85%29.aspx
784 optlen = sizeof(oldopt);
785 if (getsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &oldopt,
786 &optlen) < 0)
788 ereport(LOG,
789 (errmsg("%s(%s) failed: %m", "getsockopt", "SO_SNDBUF")));
790 return STATUS_ERROR;
792 newopt = PQ_SEND_BUFFER_SIZE * 4;
793 if (oldopt < newopt)
795 if (setsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &newopt,
796 sizeof(newopt)) < 0)
798 ereport(LOG,
799 (errmsg("%s(%s) failed: %m", "setsockopt", "SO_SNDBUF")));
800 return STATUS_ERROR;
803 #endif
806 * Also apply the current keepalive parameters. If we fail to set a
807 * parameter, don't error out, because these aren't universally
808 * supported. (Note: you might think we need to reset the GUC
809 * variables to 0 in such a case, but it's not necessary because the
810 * show hooks for these variables report the truth anyway.)
812 (void) pq_setkeepalivesidle(tcp_keepalives_idle, port);
813 (void) pq_setkeepalivesinterval(tcp_keepalives_interval, port);
814 (void) pq_setkeepalivescount(tcp_keepalives_count, port);
815 (void) pq_settcpusertimeout(tcp_user_timeout, port);
818 return STATUS_OK;
822 * StreamClose -- close a client/backend connection
824 * NOTE: this is NOT used to terminate a session; it is just used to release
825 * the file descriptor in a process that should no longer have the socket
826 * open. (For example, the postmaster calls this after passing ownership
827 * of the connection to a child process.) It is expected that someone else
828 * still has the socket open. So, we only want to close the descriptor,
829 * we do NOT want to send anything to the far end.
831 void
832 StreamClose(pgsocket sock)
834 closesocket(sock);
838 * TouchSocketFiles -- mark socket files as recently accessed
840 * This routine should be called every so often to ensure that the socket
841 * files have a recent mod date (ordinary operations on sockets usually won't
842 * change the mod date). That saves them from being removed by
843 * overenthusiastic /tmp-directory-cleaner daemons. (Another reason we should
844 * never have put the socket file in /tmp...)
846 void
847 TouchSocketFiles(void)
849 ListCell *l;
851 /* Loop through all created sockets... */
852 foreach(l, sock_paths)
854 char *sock_path = (char *) lfirst(l);
856 /* Ignore errors; there's no point in complaining */
857 (void) utime(sock_path, NULL);
862 * RemoveSocketFiles -- unlink socket files at postmaster shutdown
864 void
865 RemoveSocketFiles(void)
867 ListCell *l;
869 /* Loop through all created sockets... */
870 foreach(l, sock_paths)
872 char *sock_path = (char *) lfirst(l);
874 /* Ignore any error. */
875 (void) unlink(sock_path);
877 /* Since we're about to exit, no need to reclaim storage */
878 sock_paths = NIL;
882 /* --------------------------------
883 * Low-level I/O routines begin here.
885 * These routines communicate with a frontend client across a connection
886 * already established by the preceding routines.
887 * --------------------------------
890 /* --------------------------------
891 * socket_set_nonblocking - set socket blocking/non-blocking
893 * Sets the socket non-blocking if nonblocking is true, or sets it
894 * blocking otherwise.
895 * --------------------------------
897 static void
898 socket_set_nonblocking(bool nonblocking)
900 if (MyProcPort == NULL)
901 ereport(ERROR,
902 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
903 errmsg("there is no client connection")));
905 MyProcPort->noblock = nonblocking;
908 /* --------------------------------
909 * pq_recvbuf - load some bytes into the input buffer
911 * returns 0 if OK, EOF if trouble
912 * --------------------------------
914 static int
915 pq_recvbuf(void)
917 if (PqRecvPointer > 0)
919 if (PqRecvLength > PqRecvPointer)
921 /* still some unread data, left-justify it in the buffer */
922 memmove(PqRecvBuffer, PqRecvBuffer + PqRecvPointer,
923 PqRecvLength - PqRecvPointer);
924 PqRecvLength -= PqRecvPointer;
925 PqRecvPointer = 0;
927 else
928 PqRecvLength = PqRecvPointer = 0;
931 /* Ensure that we're in blocking mode */
932 socket_set_nonblocking(false);
934 /* Can fill buffer from PqRecvLength and upwards */
935 for (;;)
937 int r;
939 errno = 0;
941 r = secure_read(MyProcPort, PqRecvBuffer + PqRecvLength,
942 PQ_RECV_BUFFER_SIZE - PqRecvLength);
944 if (r < 0)
946 if (errno == EINTR)
947 continue; /* Ok if interrupted */
950 * Careful: an ereport() that tries to write to the client would
951 * cause recursion to here, leading to stack overflow and core
952 * dump! This message must go *only* to the postmaster log.
954 * If errno is zero, assume it's EOF and let the caller complain.
956 if (errno != 0)
957 ereport(COMMERROR,
958 (errcode_for_socket_access(),
959 errmsg("could not receive data from client: %m")));
960 return EOF;
962 if (r == 0)
965 * EOF detected. We used to write a log message here, but it's
966 * better to expect the ultimate caller to do that.
968 return EOF;
970 /* r contains number of bytes read, so just incr length */
971 PqRecvLength += r;
972 return 0;
976 /* --------------------------------
977 * pq_getbyte - get a single byte from connection, or return EOF
978 * --------------------------------
981 pq_getbyte(void)
983 Assert(PqCommReadingMsg);
985 while (PqRecvPointer >= PqRecvLength)
987 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
988 return EOF; /* Failed to recv data */
990 return (unsigned char) PqRecvBuffer[PqRecvPointer++];
993 /* --------------------------------
994 * pq_peekbyte - peek at next byte from connection
996 * Same as pq_getbyte() except we don't advance the pointer.
997 * --------------------------------
1000 pq_peekbyte(void)
1002 Assert(PqCommReadingMsg);
1004 while (PqRecvPointer >= PqRecvLength)
1006 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1007 return EOF; /* Failed to recv data */
1009 return (unsigned char) PqRecvBuffer[PqRecvPointer];
1012 /* --------------------------------
1013 * pq_getbyte_if_available - get a single byte from connection,
1014 * if available
1016 * The received byte is stored in *c. Returns 1 if a byte was read,
1017 * 0 if no data was available, or EOF if trouble.
1018 * --------------------------------
1021 pq_getbyte_if_available(unsigned char *c)
1023 int r;
1025 Assert(PqCommReadingMsg);
1027 if (PqRecvPointer < PqRecvLength)
1029 *c = PqRecvBuffer[PqRecvPointer++];
1030 return 1;
1033 /* Put the socket into non-blocking mode */
1034 socket_set_nonblocking(true);
1036 errno = 0;
1038 r = secure_read(MyProcPort, c, 1);
1039 if (r < 0)
1042 * Ok if no data available without blocking or interrupted (though
1043 * EINTR really shouldn't happen with a non-blocking socket). Report
1044 * other errors.
1046 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
1047 r = 0;
1048 else
1051 * Careful: an ereport() that tries to write to the client would
1052 * cause recursion to here, leading to stack overflow and core
1053 * dump! This message must go *only* to the postmaster log.
1055 * If errno is zero, assume it's EOF and let the caller complain.
1057 if (errno != 0)
1058 ereport(COMMERROR,
1059 (errcode_for_socket_access(),
1060 errmsg("could not receive data from client: %m")));
1061 r = EOF;
1064 else if (r == 0)
1066 /* EOF detected */
1067 r = EOF;
1070 return r;
1073 /* --------------------------------
1074 * pq_getbytes - get a known number of bytes from connection
1076 * returns 0 if OK, EOF if trouble
1077 * --------------------------------
1080 pq_getbytes(char *s, size_t len)
1082 size_t amount;
1084 Assert(PqCommReadingMsg);
1086 while (len > 0)
1088 while (PqRecvPointer >= PqRecvLength)
1090 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1091 return EOF; /* Failed to recv data */
1093 amount = PqRecvLength - PqRecvPointer;
1094 if (amount > len)
1095 amount = len;
1096 memcpy(s, PqRecvBuffer + PqRecvPointer, amount);
1097 PqRecvPointer += amount;
1098 s += amount;
1099 len -= amount;
1101 return 0;
1104 /* --------------------------------
1105 * pq_discardbytes - throw away a known number of bytes
1107 * same as pq_getbytes except we do not copy the data to anyplace.
1108 * this is used for resynchronizing after read errors.
1110 * returns 0 if OK, EOF if trouble
1111 * --------------------------------
1113 static int
1114 pq_discardbytes(size_t len)
1116 size_t amount;
1118 Assert(PqCommReadingMsg);
1120 while (len > 0)
1122 while (PqRecvPointer >= PqRecvLength)
1124 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1125 return EOF; /* Failed to recv data */
1127 amount = PqRecvLength - PqRecvPointer;
1128 if (amount > len)
1129 amount = len;
1130 PqRecvPointer += amount;
1131 len -= amount;
1133 return 0;
1136 /* --------------------------------
1137 * pq_buffer_has_data - is any buffered data available to read?
1139 * This will *not* attempt to read more data.
1140 * --------------------------------
1142 bool
1143 pq_buffer_has_data(void)
1145 return (PqRecvPointer < PqRecvLength);
1149 /* --------------------------------
1150 * pq_startmsgread - begin reading a message from the client.
1152 * This must be called before any of the pq_get* functions.
1153 * --------------------------------
1155 void
1156 pq_startmsgread(void)
1159 * There shouldn't be a read active already, but let's check just to be
1160 * sure.
1162 if (PqCommReadingMsg)
1163 ereport(FATAL,
1164 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1165 errmsg("terminating connection because protocol synchronization was lost")));
1167 PqCommReadingMsg = true;
1171 /* --------------------------------
1172 * pq_endmsgread - finish reading message.
1174 * This must be called after reading a message with pq_getbytes()
1175 * and friends, to indicate that we have read the whole message.
1176 * pq_getmessage() does this implicitly.
1177 * --------------------------------
1179 void
1180 pq_endmsgread(void)
1182 Assert(PqCommReadingMsg);
1184 PqCommReadingMsg = false;
1187 /* --------------------------------
1188 * pq_is_reading_msg - are we currently reading a message?
1190 * This is used in error recovery at the outer idle loop to detect if we have
1191 * lost protocol sync, and need to terminate the connection. pq_startmsgread()
1192 * will check for that too, but it's nicer to detect it earlier.
1193 * --------------------------------
1195 bool
1196 pq_is_reading_msg(void)
1198 return PqCommReadingMsg;
1201 /* --------------------------------
1202 * pq_getmessage - get a message with length word from connection
1204 * The return value is placed in an expansible StringInfo, which has
1205 * already been initialized by the caller.
1206 * Only the message body is placed in the StringInfo; the length word
1207 * is removed. Also, s->cursor is initialized to zero for convenience
1208 * in scanning the message contents.
1210 * maxlen is the upper limit on the length of the
1211 * message we are willing to accept. We abort the connection (by
1212 * returning EOF) if client tries to send more than that.
1214 * returns 0 if OK, EOF if trouble
1215 * --------------------------------
1218 pq_getmessage(StringInfo s, int maxlen)
1220 int32 len;
1222 Assert(PqCommReadingMsg);
1224 resetStringInfo(s);
1226 /* Read message length word */
1227 if (pq_getbytes((char *) &len, 4) == EOF)
1229 ereport(COMMERROR,
1230 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1231 errmsg("unexpected EOF within message length word")));
1232 return EOF;
1235 len = pg_ntoh32(len);
1237 if (len < 4 || len > maxlen)
1239 ereport(COMMERROR,
1240 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1241 errmsg("invalid message length")));
1242 return EOF;
1245 len -= 4; /* discount length itself */
1247 if (len > 0)
1250 * Allocate space for message. If we run out of room (ridiculously
1251 * large message), we will elog(ERROR), but we want to discard the
1252 * message body so as not to lose communication sync.
1254 PG_TRY();
1256 enlargeStringInfo(s, len);
1258 PG_CATCH();
1260 if (pq_discardbytes(len) == EOF)
1261 ereport(COMMERROR,
1262 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1263 errmsg("incomplete message from client")));
1265 /* we discarded the rest of the message so we're back in sync. */
1266 PqCommReadingMsg = false;
1267 PG_RE_THROW();
1269 PG_END_TRY();
1271 /* And grab the message */
1272 if (pq_getbytes(s->data, len) == EOF)
1274 ereport(COMMERROR,
1275 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1276 errmsg("incomplete message from client")));
1277 return EOF;
1279 s->len = len;
1280 /* Place a trailing null per StringInfo convention */
1281 s->data[len] = '\0';
1284 /* finished reading the message. */
1285 PqCommReadingMsg = false;
1287 return 0;
1291 static int
1292 internal_putbytes(const char *s, size_t len)
1294 size_t amount;
1296 while (len > 0)
1298 /* If buffer is full, then flush it out */
1299 if (PqSendPointer >= PqSendBufferSize)
1301 socket_set_nonblocking(false);
1302 if (internal_flush())
1303 return EOF;
1305 amount = PqSendBufferSize - PqSendPointer;
1306 if (amount > len)
1307 amount = len;
1308 memcpy(PqSendBuffer + PqSendPointer, s, amount);
1309 PqSendPointer += amount;
1310 s += amount;
1311 len -= amount;
1313 return 0;
1316 /* --------------------------------
1317 * socket_flush - flush pending output
1319 * returns 0 if OK, EOF if trouble
1320 * --------------------------------
1322 static int
1323 socket_flush(void)
1325 int res;
1327 /* No-op if reentrant call */
1328 if (PqCommBusy)
1329 return 0;
1330 PqCommBusy = true;
1331 socket_set_nonblocking(false);
1332 res = internal_flush();
1333 PqCommBusy = false;
1334 return res;
1337 /* --------------------------------
1338 * internal_flush - flush pending output
1340 * Returns 0 if OK (meaning everything was sent, or operation would block
1341 * and the socket is in non-blocking mode), or EOF if trouble.
1342 * --------------------------------
1344 static int
1345 internal_flush(void)
1347 static int last_reported_send_errno = 0;
1349 char *bufptr = PqSendBuffer + PqSendStart;
1350 char *bufend = PqSendBuffer + PqSendPointer;
1352 while (bufptr < bufend)
1354 int r;
1356 r = secure_write(MyProcPort, bufptr, bufend - bufptr);
1358 if (r <= 0)
1360 if (errno == EINTR)
1361 continue; /* Ok if we were interrupted */
1364 * Ok if no data writable without blocking, and the socket is in
1365 * non-blocking mode.
1367 if (errno == EAGAIN ||
1368 errno == EWOULDBLOCK)
1370 return 0;
1374 * Careful: an ereport() that tries to write to the client would
1375 * cause recursion to here, leading to stack overflow and core
1376 * dump! This message must go *only* to the postmaster log.
1378 * If a client disconnects while we're in the midst of output, we
1379 * might write quite a bit of data before we get to a safe query
1380 * abort point. So, suppress duplicate log messages.
1382 if (errno != last_reported_send_errno)
1384 last_reported_send_errno = errno;
1385 ereport(COMMERROR,
1386 (errcode_for_socket_access(),
1387 errmsg("could not send data to client: %m")));
1391 * We drop the buffered data anyway so that processing can
1392 * continue, even though we'll probably quit soon. We also set a
1393 * flag that'll cause the next CHECK_FOR_INTERRUPTS to terminate
1394 * the connection.
1396 PqSendStart = PqSendPointer = 0;
1397 ClientConnectionLost = 1;
1398 InterruptPending = 1;
1399 return EOF;
1402 last_reported_send_errno = 0; /* reset after any successful send */
1403 bufptr += r;
1404 PqSendStart += r;
1407 PqSendStart = PqSendPointer = 0;
1408 return 0;
1411 /* --------------------------------
1412 * pq_flush_if_writable - flush pending output if writable without blocking
1414 * Returns 0 if OK, or EOF if trouble.
1415 * --------------------------------
1417 static int
1418 socket_flush_if_writable(void)
1420 int res;
1422 /* Quick exit if nothing to do */
1423 if (PqSendPointer == PqSendStart)
1424 return 0;
1426 /* No-op if reentrant call */
1427 if (PqCommBusy)
1428 return 0;
1430 /* Temporarily put the socket into non-blocking mode */
1431 socket_set_nonblocking(true);
1433 PqCommBusy = true;
1434 res = internal_flush();
1435 PqCommBusy = false;
1436 return res;
1439 /* --------------------------------
1440 * socket_is_send_pending - is there any pending data in the output buffer?
1441 * --------------------------------
1443 static bool
1444 socket_is_send_pending(void)
1446 return (PqSendStart < PqSendPointer);
1449 /* --------------------------------
1450 * Message-level I/O routines begin here.
1451 * --------------------------------
1455 /* --------------------------------
1456 * socket_putmessage - send a normal message (suppressed in COPY OUT mode)
1458 * msgtype is a message type code to place before the message body.
1460 * len is the length of the message body data at *s. A message length
1461 * word (equal to len+4 because it counts itself too) is inserted by this
1462 * routine.
1464 * We suppress messages generated while pqcomm.c is busy. This
1465 * avoids any possibility of messages being inserted within other
1466 * messages. The only known trouble case arises if SIGQUIT occurs
1467 * during a pqcomm.c routine --- quickdie() will try to send a warning
1468 * message, and the most reasonable approach seems to be to drop it.
1470 * returns 0 if OK, EOF if trouble
1471 * --------------------------------
1473 static int
1474 socket_putmessage(char msgtype, const char *s, size_t len)
1476 uint32 n32;
1478 Assert(msgtype != 0);
1480 if (PqCommBusy)
1481 return 0;
1482 PqCommBusy = true;
1483 if (internal_putbytes(&msgtype, 1))
1484 goto fail;
1486 n32 = pg_hton32((uint32) (len + 4));
1487 if (internal_putbytes((char *) &n32, 4))
1488 goto fail;
1490 if (internal_putbytes(s, len))
1491 goto fail;
1492 PqCommBusy = false;
1493 return 0;
1495 fail:
1496 PqCommBusy = false;
1497 return EOF;
1500 /* --------------------------------
1501 * pq_putmessage_noblock - like pq_putmessage, but never blocks
1503 * If the output buffer is too small to hold the message, the buffer
1504 * is enlarged.
1506 static void
1507 socket_putmessage_noblock(char msgtype, const char *s, size_t len)
1509 int res PG_USED_FOR_ASSERTS_ONLY;
1510 int required;
1513 * Ensure we have enough space in the output buffer for the message header
1514 * as well as the message itself.
1516 required = PqSendPointer + 1 + 4 + len;
1517 if (required > PqSendBufferSize)
1519 PqSendBuffer = repalloc(PqSendBuffer, required);
1520 PqSendBufferSize = required;
1522 res = pq_putmessage(msgtype, s, len);
1523 Assert(res == 0); /* should not fail when the message fits in
1524 * buffer */
1527 /* --------------------------------
1528 * pq_putmessage_v2 - send a message in protocol version 2
1530 * msgtype is a message type code to place before the message body.
1532 * We no longer support protocol version 2, but we have kept this
1533 * function so that if a client tries to connect with protocol version 2,
1534 * as a courtesy we can still send the "unsupported protocol version"
1535 * error to the client in the old format.
1537 * Like in pq_putmessage(), we suppress messages generated while
1538 * pqcomm.c is busy.
1540 * returns 0 if OK, EOF if trouble
1541 * --------------------------------
1544 pq_putmessage_v2(char msgtype, const char *s, size_t len)
1546 Assert(msgtype != 0);
1548 if (PqCommBusy)
1549 return 0;
1550 PqCommBusy = true;
1551 if (internal_putbytes(&msgtype, 1))
1552 goto fail;
1554 if (internal_putbytes(s, len))
1555 goto fail;
1556 PqCommBusy = false;
1557 return 0;
1559 fail:
1560 PqCommBusy = false;
1561 return EOF;
1565 * Support for TCP Keepalive parameters
1569 * On Windows, we need to set both idle and interval at the same time.
1570 * We also cannot reset them to the default (setting to zero will
1571 * actually set them to zero, not default), therefore we fallback to
1572 * the out-of-the-box default instead.
1574 #if defined(WIN32) && defined(SIO_KEEPALIVE_VALS)
1575 static int
1576 pq_setkeepaliveswin32(Port *port, int idle, int interval)
1578 struct tcp_keepalive ka;
1579 DWORD retsize;
1581 if (idle <= 0)
1582 idle = 2 * 60 * 60; /* default = 2 hours */
1583 if (interval <= 0)
1584 interval = 1; /* default = 1 second */
1586 ka.onoff = 1;
1587 ka.keepalivetime = idle * 1000;
1588 ka.keepaliveinterval = interval * 1000;
1590 if (WSAIoctl(port->sock,
1591 SIO_KEEPALIVE_VALS,
1592 (LPVOID) &ka,
1593 sizeof(ka),
1594 NULL,
1596 &retsize,
1597 NULL,
1598 NULL)
1599 != 0)
1601 ereport(LOG,
1602 (errmsg("%s(%s) failed: error code %d",
1603 "WSAIoctl", "SIO_KEEPALIVE_VALS", WSAGetLastError())));
1604 return STATUS_ERROR;
1606 if (port->keepalives_idle != idle)
1607 port->keepalives_idle = idle;
1608 if (port->keepalives_interval != interval)
1609 port->keepalives_interval = interval;
1610 return STATUS_OK;
1612 #endif
1615 pq_getkeepalivesidle(Port *port)
1617 #if defined(PG_TCP_KEEPALIVE_IDLE) || defined(SIO_KEEPALIVE_VALS)
1618 if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
1619 return 0;
1621 if (port->keepalives_idle != 0)
1622 return port->keepalives_idle;
1624 if (port->default_keepalives_idle == 0)
1626 #ifndef WIN32
1627 socklen_t size = sizeof(port->default_keepalives_idle);
1629 if (getsockopt(port->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
1630 (char *) &port->default_keepalives_idle,
1631 &size) < 0)
1633 ereport(LOG,
1634 (errmsg("%s(%s) failed: %m", "getsockopt", PG_TCP_KEEPALIVE_IDLE_STR)));
1635 port->default_keepalives_idle = -1; /* don't know */
1637 #else /* WIN32 */
1638 /* We can't get the defaults on Windows, so return "don't know" */
1639 port->default_keepalives_idle = -1;
1640 #endif /* WIN32 */
1643 return port->default_keepalives_idle;
1644 #else
1645 return 0;
1646 #endif
1650 pq_setkeepalivesidle(int idle, Port *port)
1652 if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
1653 return STATUS_OK;
1655 /* check SIO_KEEPALIVE_VALS here, not just WIN32, as some toolchains lack it */
1656 #if defined(PG_TCP_KEEPALIVE_IDLE) || defined(SIO_KEEPALIVE_VALS)
1657 if (idle == port->keepalives_idle)
1658 return STATUS_OK;
1660 #ifndef WIN32
1661 if (port->default_keepalives_idle <= 0)
1663 if (pq_getkeepalivesidle(port) < 0)
1665 if (idle == 0)
1666 return STATUS_OK; /* default is set but unknown */
1667 else
1668 return STATUS_ERROR;
1672 if (idle == 0)
1673 idle = port->default_keepalives_idle;
1675 if (setsockopt(port->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
1676 (char *) &idle, sizeof(idle)) < 0)
1678 ereport(LOG,
1679 (errmsg("%s(%s) failed: %m", "setsockopt", PG_TCP_KEEPALIVE_IDLE_STR)));
1680 return STATUS_ERROR;
1683 port->keepalives_idle = idle;
1684 #else /* WIN32 */
1685 return pq_setkeepaliveswin32(port, idle, port->keepalives_interval);
1686 #endif
1687 #else
1688 if (idle != 0)
1690 ereport(LOG,
1691 (errmsg("setting the keepalive idle time is not supported")));
1692 return STATUS_ERROR;
1694 #endif
1696 return STATUS_OK;
1700 pq_getkeepalivesinterval(Port *port)
1702 #if defined(TCP_KEEPINTVL) || defined(SIO_KEEPALIVE_VALS)
1703 if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
1704 return 0;
1706 if (port->keepalives_interval != 0)
1707 return port->keepalives_interval;
1709 if (port->default_keepalives_interval == 0)
1711 #ifndef WIN32
1712 socklen_t size = sizeof(port->default_keepalives_interval);
1714 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1715 (char *) &port->default_keepalives_interval,
1716 &size) < 0)
1718 ereport(LOG,
1719 (errmsg("%s(%s) failed: %m", "getsockopt", "TCP_KEEPINTVL")));
1720 port->default_keepalives_interval = -1; /* don't know */
1722 #else
1723 /* We can't get the defaults on Windows, so return "don't know" */
1724 port->default_keepalives_interval = -1;
1725 #endif /* WIN32 */
1728 return port->default_keepalives_interval;
1729 #else
1730 return 0;
1731 #endif
1735 pq_setkeepalivesinterval(int interval, Port *port)
1737 if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
1738 return STATUS_OK;
1740 #if defined(TCP_KEEPINTVL) || defined(SIO_KEEPALIVE_VALS)
1741 if (interval == port->keepalives_interval)
1742 return STATUS_OK;
1744 #ifndef WIN32
1745 if (port->default_keepalives_interval <= 0)
1747 if (pq_getkeepalivesinterval(port) < 0)
1749 if (interval == 0)
1750 return STATUS_OK; /* default is set but unknown */
1751 else
1752 return STATUS_ERROR;
1756 if (interval == 0)
1757 interval = port->default_keepalives_interval;
1759 if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1760 (char *) &interval, sizeof(interval)) < 0)
1762 ereport(LOG,
1763 (errmsg("%s(%s) failed: %m", "setsockopt", "TCP_KEEPINTVL")));
1764 return STATUS_ERROR;
1767 port->keepalives_interval = interval;
1768 #else /* WIN32 */
1769 return pq_setkeepaliveswin32(port, port->keepalives_idle, interval);
1770 #endif
1771 #else
1772 if (interval != 0)
1774 ereport(LOG,
1775 (errmsg("%s(%s) not supported", "setsockopt", "TCP_KEEPINTVL")));
1776 return STATUS_ERROR;
1778 #endif
1780 return STATUS_OK;
1784 pq_getkeepalivescount(Port *port)
1786 #ifdef TCP_KEEPCNT
1787 if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
1788 return 0;
1790 if (port->keepalives_count != 0)
1791 return port->keepalives_count;
1793 if (port->default_keepalives_count == 0)
1795 socklen_t size = sizeof(port->default_keepalives_count);
1797 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
1798 (char *) &port->default_keepalives_count,
1799 &size) < 0)
1801 ereport(LOG,
1802 (errmsg("%s(%s) failed: %m", "getsockopt", "TCP_KEEPCNT")));
1803 port->default_keepalives_count = -1; /* don't know */
1807 return port->default_keepalives_count;
1808 #else
1809 return 0;
1810 #endif
1814 pq_setkeepalivescount(int count, Port *port)
1816 if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
1817 return STATUS_OK;
1819 #ifdef TCP_KEEPCNT
1820 if (count == port->keepalives_count)
1821 return STATUS_OK;
1823 if (port->default_keepalives_count <= 0)
1825 if (pq_getkeepalivescount(port) < 0)
1827 if (count == 0)
1828 return STATUS_OK; /* default is set but unknown */
1829 else
1830 return STATUS_ERROR;
1834 if (count == 0)
1835 count = port->default_keepalives_count;
1837 if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
1838 (char *) &count, sizeof(count)) < 0)
1840 ereport(LOG,
1841 (errmsg("%s(%s) failed: %m", "setsockopt", "TCP_KEEPCNT")));
1842 return STATUS_ERROR;
1845 port->keepalives_count = count;
1846 #else
1847 if (count != 0)
1849 ereport(LOG,
1850 (errmsg("%s(%s) not supported", "setsockopt", "TCP_KEEPCNT")));
1851 return STATUS_ERROR;
1853 #endif
1855 return STATUS_OK;
1859 pq_gettcpusertimeout(Port *port)
1861 #ifdef TCP_USER_TIMEOUT
1862 if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
1863 return 0;
1865 if (port->tcp_user_timeout != 0)
1866 return port->tcp_user_timeout;
1868 if (port->default_tcp_user_timeout == 0)
1870 socklen_t size = sizeof(port->default_tcp_user_timeout);
1872 if (getsockopt(port->sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
1873 (char *) &port->default_tcp_user_timeout,
1874 &size) < 0)
1876 ereport(LOG,
1877 (errmsg("%s(%s) failed: %m", "getsockopt", "TCP_USER_TIMEOUT")));
1878 port->default_tcp_user_timeout = -1; /* don't know */
1882 return port->default_tcp_user_timeout;
1883 #else
1884 return 0;
1885 #endif
1889 pq_settcpusertimeout(int timeout, Port *port)
1891 if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
1892 return STATUS_OK;
1894 #ifdef TCP_USER_TIMEOUT
1895 if (timeout == port->tcp_user_timeout)
1896 return STATUS_OK;
1898 if (port->default_tcp_user_timeout <= 0)
1900 if (pq_gettcpusertimeout(port) < 0)
1902 if (timeout == 0)
1903 return STATUS_OK; /* default is set but unknown */
1904 else
1905 return STATUS_ERROR;
1909 if (timeout == 0)
1910 timeout = port->default_tcp_user_timeout;
1912 if (setsockopt(port->sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
1913 (char *) &timeout, sizeof(timeout)) < 0)
1915 ereport(LOG,
1916 (errmsg("%s(%s) failed: %m", "setsockopt", "TCP_USER_TIMEOUT")));
1917 return STATUS_ERROR;
1920 port->tcp_user_timeout = timeout;
1921 #else
1922 if (timeout != 0)
1924 ereport(LOG,
1925 (errmsg("%s(%s) not supported", "setsockopt", "TCP_USER_TIMEOUT")));
1926 return STATUS_ERROR;
1928 #endif
1930 return STATUS_OK;
1934 * GUC assign_hook for tcp_keepalives_idle
1936 void
1937 assign_tcp_keepalives_idle(int newval, void *extra)
1940 * The kernel API provides no way to test a value without setting it; and
1941 * once we set it we might fail to unset it. So there seems little point
1942 * in fully implementing the check-then-assign GUC API for these
1943 * variables. Instead we just do the assignment on demand.
1944 * pq_setkeepalivesidle reports any problems via ereport(LOG).
1946 * This approach means that the GUC value might have little to do with the
1947 * actual kernel value, so we use a show_hook that retrieves the kernel
1948 * value rather than trusting GUC's copy.
1950 (void) pq_setkeepalivesidle(newval, MyProcPort);
1954 * GUC show_hook for tcp_keepalives_idle
1956 const char *
1957 show_tcp_keepalives_idle(void)
1959 /* See comments in assign_tcp_keepalives_idle */
1960 static char nbuf[16];
1962 snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesidle(MyProcPort));
1963 return nbuf;
1967 * GUC assign_hook for tcp_keepalives_interval
1969 void
1970 assign_tcp_keepalives_interval(int newval, void *extra)
1972 /* See comments in assign_tcp_keepalives_idle */
1973 (void) pq_setkeepalivesinterval(newval, MyProcPort);
1977 * GUC show_hook for tcp_keepalives_interval
1979 const char *
1980 show_tcp_keepalives_interval(void)
1982 /* See comments in assign_tcp_keepalives_idle */
1983 static char nbuf[16];
1985 snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesinterval(MyProcPort));
1986 return nbuf;
1990 * GUC assign_hook for tcp_keepalives_count
1992 void
1993 assign_tcp_keepalives_count(int newval, void *extra)
1995 /* See comments in assign_tcp_keepalives_idle */
1996 (void) pq_setkeepalivescount(newval, MyProcPort);
2000 * GUC show_hook for tcp_keepalives_count
2002 const char *
2003 show_tcp_keepalives_count(void)
2005 /* See comments in assign_tcp_keepalives_idle */
2006 static char nbuf[16];
2008 snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivescount(MyProcPort));
2009 return nbuf;
2013 * GUC assign_hook for tcp_user_timeout
2015 void
2016 assign_tcp_user_timeout(int newval, void *extra)
2018 /* See comments in assign_tcp_keepalives_idle */
2019 (void) pq_settcpusertimeout(newval, MyProcPort);
2023 * GUC show_hook for tcp_user_timeout
2025 const char *
2026 show_tcp_user_timeout(void)
2028 /* See comments in assign_tcp_keepalives_idle */
2029 static char nbuf[16];
2031 snprintf(nbuf, sizeof(nbuf), "%d", pq_gettcpusertimeout(MyProcPort));
2032 return nbuf;
2036 * Check if the client is still connected.
2038 bool
2039 pq_check_connection(void)
2041 WaitEvent events[FeBeWaitSetNEvents];
2042 int rc;
2045 * It's OK to modify the socket event filter without restoring, because
2046 * all FeBeWaitSet socket wait sites do the same.
2048 ModifyWaitEvent(FeBeWaitSet, FeBeWaitSetSocketPos, WL_SOCKET_CLOSED, NULL);
2050 retry:
2051 rc = WaitEventSetWait(FeBeWaitSet, 0, events, lengthof(events), 0);
2052 for (int i = 0; i < rc; ++i)
2054 if (events[i].events & WL_SOCKET_CLOSED)
2055 return false;
2056 if (events[i].events & WL_LATCH_SET)
2059 * A latch event might be preventing other events from being
2060 * reported. Reset it and poll again. No need to restore it
2061 * because no code should expect latches to survive across
2062 * CHECK_FOR_INTERRUPTS().
2064 ResetLatch(MyLatch);
2065 goto retry;
2069 return true;