1 /*-------------------------------------------------------------------------
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 --- or would be,
9 * except for major brain damage in the design of the old COPY OUT protocol.
10 * Unfortunately, COPY OUT was designed to commandeer the communication
11 * channel (it just transfers data without wrapping it into messages).
12 * No other messages can be sent while COPY OUT is in progress; and if the
13 * copy is aborted by an ereport(ERROR), we need to close out the copy so that
14 * the frontend gets back into sync. Therefore, these routines have to be
15 * aware of COPY OUT state. (New COPY-OUT is message-based and does *not*
16 * set the DoingCopyOut flag.)
18 * NOTE: generally, it's a bad idea to emit outgoing messages directly with
19 * pq_putbytes(), especially if the message would require multiple calls
20 * to send. Instead, use the routines in pqformat.c to construct the message
21 * in a buffer and then emit it in one call to pq_putmessage. This ensures
22 * that the channel will not be clogged by an incomplete message if execution
23 * is aborted by ereport(ERROR) partway through the message. The only
24 * non-libpq code that should call pq_putbytes directly is old-style COPY OUT.
26 * At one time, libpq was shared between frontend and backend, but now
27 * the backend's "backend/libpq" is quite separate from "interfaces/libpq".
28 * All that remains is similarities of names to trap the unwary...
30 * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
31 * Portions Copyright (c) 1994, Regents of the University of California
33 * src/backend/libpq/pqcomm.c
35 *-------------------------------------------------------------------------
38 /*------------------------
42 * StreamServerPort - Open postmaster's server port
43 * StreamConnection - Create new connection with client
44 * StreamClose - Close a client/backend connection
45 * TouchSocketFiles - Protect socket files against /tmp cleaners
46 * pq_init - initialize libpq at backend startup
47 * pq_comm_reset - reset libpq during error recovery
48 * pq_close - shutdown libpq at backend exit
51 * pq_getbytes - get a known number of bytes from connection
52 * pq_getstring - get a null terminated string from connection
53 * pq_getmessage - get a message with length word from connection
54 * pq_getbyte - get next byte from connection
55 * pq_peekbyte - peek at next byte from connection
56 * pq_putbytes - send bytes to connection (not flushed until pq_flush)
57 * pq_flush - flush pending output
58 * pq_flush_if_writable - flush pending output if writable without blocking
59 * pq_getbyte_if_available - get a byte if available without blocking
61 * message-level I/O (and old-style-COPY-OUT cruft):
62 * pq_putmessage - send a normal message (suppressed in COPY OUT mode)
63 * pq_putmessage_noblock - buffer a normal message (suppressed in COPY OUT)
64 * pq_startcopyout - inform libpq that a COPY OUT transfer is beginning
65 * pq_endcopyout - end a COPY OUT transfer
67 *------------------------
76 #include <sys/socket.h>
80 #include <netinet/in.h>
81 #ifdef HAVE_NETINET_TCP_H
82 #include <netinet/tcp.h>
84 #include <arpa/inet.h>
88 #ifdef WIN32_ONLY_COMPILER /* mstcpip.h is missing on mingw */
93 #include "libpq/libpq.h"
94 #include "miscadmin.h"
95 #include "storage/ipc.h"
96 #include "utils/guc.h"
97 #include "utils/memutils.h"
100 * Configuration options
102 int Unix_socket_permissions;
103 char *Unix_socket_group;
105 /* Where the Unix socket files are (list of palloc'd strings) */
106 static List *sock_paths = NIL;
109 * Buffers for low-level I/O.
111 * The receive buffer is fixed size. Send buffer is usually 8k, but can be
112 * enlarged by pq_putmessage_noblock() if the message doesn't fit otherwise.
115 #define PQ_SEND_BUFFER_SIZE 8192
116 #define PQ_RECV_BUFFER_SIZE 8192
118 static char *PqSendBuffer;
119 static int PqSendBufferSize; /* Size send buffer */
120 static int PqSendPointer; /* Next index to store a byte in PqSendBuffer */
121 static int PqSendStart; /* Next index to send a byte in PqSendBuffer */
123 static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE];
124 static int PqRecvPointer; /* Next index to read a byte from PqRecvBuffer */
125 static int PqRecvLength; /* End of data available in PqRecvBuffer */
130 static bool PqCommBusy; /* busy sending data to the client */
131 static bool PqCommReadingMsg; /* in the middle of reading a message */
132 static bool DoingCopyOut; /* in old-protocol COPY OUT processing */
135 /* Internal functions */
136 static void socket_comm_reset(void);
137 static void socket_close(int code, Datum arg);
138 static void socket_set_nonblocking(bool nonblocking);
139 static int socket_flush(void);
140 static int socket_flush_if_writable(void);
141 static bool socket_is_send_pending(void);
142 static int socket_putmessage(char msgtype, const char *s, size_t len);
143 static void socket_putmessage_noblock(char msgtype, const char *s, size_t len);
144 static void socket_startcopyout(void);
145 static void socket_endcopyout(bool errorAbort);
146 static int internal_putbytes(const char *s, size_t len);
147 static int internal_flush(void);
148 static void socket_set_nonblocking(bool nonblocking);
150 #ifdef HAVE_UNIX_SOCKETS
151 static int Lock_AF_UNIX(char *unixSocketDir, char *unixSocketPath);
152 static int Setup_AF_UNIX(char *sock_path);
153 #endif /* HAVE_UNIX_SOCKETS */
155 static PQcommMethods PqCommSocketMethods = {
158 socket_flush_if_writable,
159 socket_is_send_pending,
161 socket_putmessage_noblock,
166 PQcommMethods *PqCommMethods = &PqCommSocketMethods;
170 /* --------------------------------
171 * pq_init - initialize libpq at backend startup
172 * --------------------------------
177 PqSendBufferSize = PQ_SEND_BUFFER_SIZE;
178 PqSendBuffer = MemoryContextAlloc(TopMemoryContext, PqSendBufferSize);
179 PqSendPointer = PqSendStart = PqRecvPointer = PqRecvLength = 0;
181 PqCommReadingMsg = false;
182 DoingCopyOut = false;
183 on_proc_exit(socket_close, 0);
186 * In backends (as soon as forked) we operate the underlying socket in
187 * nonblocking mode and use latches to implement blocking semantics if
188 * needed. That allows us to provide safely interruptible reads and
191 * Use COMMERROR on failure, because ERROR would try to send the error to
192 * the client, which might require changing the mode again, leading to
193 * infinite recursion.
196 if (!pg_set_noblock(MyProcPort->sock))
198 (errmsg("could not set socket to nonblocking mode: %m")));
203 /* --------------------------------
204 * socket_comm_reset - reset libpq during error recovery
206 * This is called from error recovery at the outer idle loop. It's
207 * just to get us out of trouble if we somehow manage to elog() from
208 * inside a pqcomm.c routine (which ideally will never happen, but...)
209 * --------------------------------
212 socket_comm_reset(void)
214 /* Do not throw away pending data, but do reset the busy flag */
216 /* We can abort any old-style COPY OUT, too */
220 /* --------------------------------
221 * socket_close - shutdown libpq at backend exit
223 * This is the one pg_on_exit_callback in place during BackendInitialize().
224 * That function's unusual signal handling constrains that this callback be
225 * safe to run at any instant.
226 * --------------------------------
229 socket_close(int code, Datum arg)
231 /* Nothing to do in a standalone backend, where MyProcPort is NULL. */
232 if (MyProcPort != NULL)
234 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
239 * Shutdown GSSAPI layer. This section does nothing when interrupting
240 * BackendInitialize(), because pg_GSS_recvauth() makes first use of
243 if (MyProcPort->gss->ctx != GSS_C_NO_CONTEXT)
244 gss_delete_sec_context(&min_s, &MyProcPort->gss->ctx, NULL);
246 if (MyProcPort->gss->cred != GSS_C_NO_CREDENTIAL)
247 gss_release_cred(&min_s, &MyProcPort->gss->cred);
248 #endif /* ENABLE_GSS */
251 * GSS and SSPI share the port->gss struct. Since nowhere else does a
252 * postmaster child free this, doing so is safe when interrupting
253 * BackendInitialize().
255 free(MyProcPort->gss);
256 #endif /* ENABLE_GSS || ENABLE_SSPI */
259 * Cleanly shut down SSL layer. Nowhere else does a postmaster child
260 * call this, so this is safe when interrupting BackendInitialize().
262 secure_close(MyProcPort);
265 * Formerly we did an explicit close() here, but it seems better to
266 * leave the socket open until the process dies. This allows clients
267 * to perform a "synchronous close" if they care --- wait till the
268 * transport layer reports connection closure, and you can be sure the
269 * backend has exited.
271 * We do set sock to PGINVALID_SOCKET to prevent any further I/O,
274 MyProcPort->sock = PGINVALID_SOCKET;
281 * Streams -- wrapper around Unix socket system calls
284 * Stream functions are used for vanilla TCP connection protocol.
289 * Shutdown routine for backend connection
290 * If any Unix sockets are used for communication, explicitly close them.
292 #ifdef HAVE_UNIX_SOCKETS
294 StreamDoUnlink(int code, Datum arg)
298 /* Loop through all created sockets... */
299 foreach(l, sock_paths)
301 char *sock_path = (char *) lfirst(l);
305 /* Since we're about to exit, no need to reclaim storage */
308 #endif /* HAVE_UNIX_SOCKETS */
311 * StreamServerPort -- open a "listening" port to accept connections.
313 * family should be AF_UNIX or AF_UNSPEC; portNumber is the port number.
314 * For AF_UNIX ports, hostName should be NULL and unixSocketDir must be
315 * specified. For TCP ports, hostName is either NULL for all interfaces or
316 * the interface to listen on, and unixSocketDir is ignored (can be NULL).
318 * Successfully opened sockets are added to the ListenSocket[] array (of
319 * length MaxListen), at the first position that isn't PGINVALID_SOCKET.
321 * RETURNS: STATUS_OK or STATUS_ERROR
325 StreamServerPort(int family, char *hostName, unsigned short portNumber,
327 pgsocket ListenSocket[], int MaxListen)
333 char portNumberStr[32];
334 const char *familyDesc;
335 char familyDescBuf[64];
337 struct addrinfo *addrs = NULL,
339 struct addrinfo hint;
340 int listen_index = 0;
343 #ifdef HAVE_UNIX_SOCKETS
344 char unixSocketPath[MAXPGPATH];
346 #if !defined(WIN32) || defined(IPV6_V6ONLY)
350 /* Initialize hint structure */
351 MemSet(&hint, 0, sizeof(hint));
352 hint.ai_family = family;
353 hint.ai_flags = AI_PASSIVE;
354 hint.ai_socktype = SOCK_STREAM;
356 #ifdef HAVE_UNIX_SOCKETS
357 if (family == AF_UNIX)
360 * Create unixSocketPath from portNumber and unixSocketDir and lock
363 UNIXSOCK_PATH(unixSocketPath, portNumber, unixSocketDir);
364 if (strlen(unixSocketPath) >= UNIXSOCK_PATH_BUFLEN)
367 (errmsg("Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
369 (int) (UNIXSOCK_PATH_BUFLEN - 1))));
372 if (Lock_AF_UNIX(unixSocketDir, unixSocketPath) != STATUS_OK)
374 service = unixSocketPath;
377 #endif /* HAVE_UNIX_SOCKETS */
379 snprintf(portNumberStr, sizeof(portNumberStr), "%d", portNumber);
380 service = portNumberStr;
383 ret = pg_getaddrinfo_all(hostName, service, &hint, &addrs);
388 (errmsg("could not translate host name \"%s\", service \"%s\" to address: %s",
389 hostName, service, gai_strerror(ret))));
392 (errmsg("could not translate service \"%s\" to address: %s",
393 service, gai_strerror(ret))));
395 pg_freeaddrinfo_all(hint.ai_family, addrs);
399 for (addr = addrs; addr; addr = addr->ai_next)
401 if (!IS_AF_UNIX(family) && IS_AF_UNIX(addr->ai_family))
404 * Only set up a unix domain socket when they really asked for it.
405 * The service/port is different in that case.
410 /* See if there is still room to add 1 more socket. */
411 for (; listen_index < MaxListen; listen_index++)
413 if (ListenSocket[listen_index] == PGINVALID_SOCKET)
416 if (listen_index >= MaxListen)
419 (errmsg("could not bind to all requested addresses: MAXLISTEN (%d) exceeded",
424 /* set up family name for possible error messages */
425 switch (addr->ai_family)
428 familyDesc = _("IPv4");
432 familyDesc = _("IPv6");
435 #ifdef HAVE_UNIX_SOCKETS
437 familyDesc = _("Unix");
441 snprintf(familyDescBuf, sizeof(familyDescBuf),
442 _("unrecognized address family %d"),
444 familyDesc = familyDescBuf;
448 if ((fd = socket(addr->ai_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
451 (errcode_for_socket_access(),
452 /* translator: %s is IPv4, IPv6, or Unix */
453 errmsg("could not create %s socket: %m",
461 * Without the SO_REUSEADDR flag, a new postmaster can't be started
462 * right away after a stop or crash, giving "address already in use"
463 * error on TCP ports.
465 * On win32, however, this behavior only happens if the
466 * SO_EXLUSIVEADDRUSE is set. With SO_REUSEADDR, win32 allows multiple
467 * servers to listen on the same address, resulting in unpredictable
468 * behavior. With no flags at all, win32 behaves as Unix with
471 if (!IS_AF_UNIX(addr->ai_family))
473 if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
474 (char *) &one, sizeof(one))) == -1)
477 (errcode_for_socket_access(),
478 errmsg("setsockopt(SO_REUSEADDR) failed: %m")));
486 if (addr->ai_family == AF_INET6)
488 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
489 (char *) &one, sizeof(one)) == -1)
492 (errcode_for_socket_access(),
493 errmsg("setsockopt(IPV6_V6ONLY) failed: %m")));
501 * Note: This might fail on some OS's, like Linux older than
502 * 2.4.21-pre3, that don't have the IPV6_V6ONLY socket option, and map
503 * ipv4 addresses to ipv6. It will show ::ffff:ipv4 for all ipv4
506 err = bind(fd, addr->ai_addr, addr->ai_addrlen);
510 (errcode_for_socket_access(),
511 /* translator: %s is IPv4, IPv6, or Unix */
512 errmsg("could not bind %s socket: %m",
514 (IS_AF_UNIX(addr->ai_family)) ?
515 errhint("Is another postmaster already running on port %d?"
516 " If not, remove socket file \"%s\" and retry.",
517 (int) portNumber, service) :
518 errhint("Is another postmaster already running on port %d?"
519 " If not, wait a few seconds and retry.",
525 #ifdef HAVE_UNIX_SOCKETS
526 if (addr->ai_family == AF_UNIX)
528 if (Setup_AF_UNIX(service) != STATUS_OK)
537 * Select appropriate accept-queue length limit. PG_SOMAXCONN is only
538 * intended to provide a clamp on the request on platforms where an
539 * overly large request provokes a kernel error (are there any?).
541 maxconn = MaxBackends * 2;
542 if (maxconn > PG_SOMAXCONN)
543 maxconn = PG_SOMAXCONN;
545 err = listen(fd, maxconn);
549 (errcode_for_socket_access(),
550 /* translator: %s is IPv4, IPv6, or Unix */
551 errmsg("could not listen on %s socket: %m",
556 ListenSocket[listen_index] = fd;
560 pg_freeaddrinfo_all(hint.ai_family, addrs);
569 #ifdef HAVE_UNIX_SOCKETS
572 * Lock_AF_UNIX -- configure unix socket file path
575 Lock_AF_UNIX(char *unixSocketDir, char *unixSocketPath)
578 * Grab an interlock file associated with the socket file.
580 * Note: there are two reasons for using a socket lock file, rather than
581 * trying to interlock directly on the socket itself. First, it's a lot
582 * more portable, and second, it lets us remove any pre-existing socket
583 * file without race conditions.
585 CreateSocketLockFile(unixSocketPath, true, unixSocketDir);
588 * Once we have the interlock, we can safely delete any pre-existing
589 * socket file to avoid failure at bind() time.
591 unlink(unixSocketPath);
594 * Arrange to unlink the socket file(s) at proc_exit. If this is the
595 * first one, set up the on_proc_exit function to do it; then add this
596 * socket file to the list of files to unlink.
598 if (sock_paths == NIL)
599 on_proc_exit(StreamDoUnlink, 0);
601 sock_paths = lappend(sock_paths, pstrdup(unixSocketPath));
608 * Setup_AF_UNIX -- configure unix socket permissions
611 Setup_AF_UNIX(char *sock_path)
614 * Fix socket ownership/permission if requested. Note we must do this
615 * before we listen() to avoid a window where unwanted connections could
618 Assert(Unix_socket_group);
619 if (Unix_socket_group[0] != '\0')
622 elog(WARNING, "configuration item unix_socket_group is not supported on this platform");
628 val = strtoul(Unix_socket_group, &endptr, 10);
630 { /* numeric group id */
634 { /* convert group name to id */
637 gr = getgrnam(Unix_socket_group);
641 (errmsg("group \"%s\" does not exist",
642 Unix_socket_group)));
647 if (chown(sock_path, -1, gid) == -1)
650 (errcode_for_file_access(),
651 errmsg("could not set group of file \"%s\": %m",
658 if (chmod(sock_path, Unix_socket_permissions) == -1)
661 (errcode_for_file_access(),
662 errmsg("could not set permissions of file \"%s\": %m",
668 #endif /* HAVE_UNIX_SOCKETS */
672 * StreamConnection -- create a new connection with client using
673 * server port. Set port->sock to the FD of the new connection.
675 * ASSUME: that this doesn't need to be non-blocking because
676 * the Postmaster uses select() to tell when the server master
677 * socket is ready for accept().
679 * RETURNS: STATUS_OK or STATUS_ERROR
682 StreamConnection(pgsocket server_fd, Port *port)
684 /* accept connection and fill in the client (remote) address */
685 port->raddr.salen = sizeof(port->raddr.addr);
686 if ((port->sock = accept(server_fd,
687 (struct sockaddr *) & port->raddr.addr,
688 &port->raddr.salen)) == PGINVALID_SOCKET)
691 (errcode_for_socket_access(),
692 errmsg("could not accept new connection: %m")));
695 * If accept() fails then postmaster.c will still see the server
696 * socket as read-ready, and will immediately try again. To avoid
697 * uselessly sucking lots of CPU, delay a bit before trying again.
698 * (The most likely reason for failure is being out of kernel file
699 * table slots; we can do little except hope some will get freed up.)
701 pg_usleep(100000L); /* wait 0.1 sec */
705 #ifdef SCO_ACCEPT_BUG
708 * UnixWare 7+ and OpenServer 5.0.4 are known to have this bug, but it
709 * shouldn't hurt to catch it for all versions of those platforms.
711 if (port->raddr.addr.ss_family == 0)
712 port->raddr.addr.ss_family = AF_UNIX;
715 /* fill in the server (local) address */
716 port->laddr.salen = sizeof(port->laddr.addr);
717 if (getsockname(port->sock,
718 (struct sockaddr *) & port->laddr.addr,
719 &port->laddr.salen) < 0)
721 elog(LOG, "getsockname() failed: %m");
725 /* select NODELAY and KEEPALIVE options if it's a TCP connection */
726 if (!IS_AF_UNIX(port->laddr.addr.ss_family))
737 if (setsockopt(port->sock, IPPROTO_TCP, TCP_NODELAY,
738 (char *) &on, sizeof(on)) < 0)
740 elog(LOG, "setsockopt(TCP_NODELAY) failed: %m");
745 if (setsockopt(port->sock, SOL_SOCKET, SO_KEEPALIVE,
746 (char *) &on, sizeof(on)) < 0)
748 elog(LOG, "setsockopt(SO_KEEPALIVE) failed: %m");
755 * This is a Win32 socket optimization. The OS send buffer should be
756 * large enough to send the whole Postgres send buffer in one go, or
757 * performance suffers. The Postgres send buffer can be enlarged if a
758 * very large message needs to be sent, but we won't attempt to
759 * enlarge the OS buffer if that happens, so somewhat arbitrarily
760 * ensure that the OS buffer is at least PQ_SEND_BUFFER_SIZE * 4.
761 * (That's 32kB with the current default).
763 * The default OS buffer size used to be 8kB in earlier Windows
764 * versions, but was raised to 64kB in Windows 2012. So it shouldn't
765 * be necessary to change it in later versions anymore. Changing it
766 * unnecessarily can even reduce performance, because setting
767 * SO_SNDBUF in the application disables the "dynamic send buffering"
768 * feature that was introduced in Windows 7. So before fiddling with
769 * SO_SNDBUF, check if the current buffer size is already large enough
770 * and only increase it if necessary.
772 * See https://support.microsoft.com/kb/823764/EN-US/ and
773 * https://msdn.microsoft.com/en-us/library/bb736549%28v=vs.85%29.aspx
775 optlen = sizeof(oldopt);
776 if (getsockopt(server_fd, SOL_SOCKET, SO_SNDBUF, (char *) &oldopt,
779 elog(LOG, "getsockopt(SO_SNDBUF) failed: %m");
782 newopt = PQ_SEND_BUFFER_SIZE * 4;
785 if (setsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &newopt,
788 elog(LOG, "setsockopt(SO_SNDBUF) failed: %m");
795 * Also apply the current keepalive parameters. If we fail to set a
796 * parameter, don't error out, because these aren't universally
797 * supported. (Note: you might think we need to reset the GUC
798 * variables to 0 in such a case, but it's not necessary because the
799 * show hooks for these variables report the truth anyway.)
801 (void) pq_setkeepalivesidle(tcp_keepalives_idle, port);
802 (void) pq_setkeepalivesinterval(tcp_keepalives_interval, port);
803 (void) pq_setkeepalivescount(tcp_keepalives_count, port);
810 * StreamClose -- close a client/backend connection
812 * NOTE: this is NOT used to terminate a session; it is just used to release
813 * the file descriptor in a process that should no longer have the socket
814 * open. (For example, the postmaster calls this after passing ownership
815 * of the connection to a child process.) It is expected that someone else
816 * still has the socket open. So, we only want to close the descriptor,
817 * we do NOT want to send anything to the far end.
820 StreamClose(pgsocket sock)
826 * TouchSocketFiles -- mark socket files as recently accessed
828 * This routine should be called every so often to ensure that the socket
829 * files have a recent mod date (ordinary operations on sockets usually won't
830 * change the mod date). That saves them from being removed by
831 * overenthusiastic /tmp-directory-cleaner daemons. (Another reason we should
832 * never have put the socket file in /tmp...)
835 TouchSocketFiles(void)
839 /* Loop through all created sockets... */
840 foreach(l, sock_paths)
842 char *sock_path = (char *) lfirst(l);
845 * utime() is POSIX standard, utimes() is a common alternative. If we
846 * have neither, there's no way to affect the mod or access time of
849 * In either path, we ignore errors; there's no point in complaining.
852 utime(sock_path, NULL);
853 #else /* !HAVE_UTIME */
855 utimes(sock_path, NULL);
856 #endif /* HAVE_UTIMES */
857 #endif /* HAVE_UTIME */
862 /* --------------------------------
863 * Low-level I/O routines begin here.
865 * These routines communicate with a frontend client across a connection
866 * already established by the preceding routines.
867 * --------------------------------
870 /* --------------------------------
871 * socket_set_nonblocking - set socket blocking/non-blocking
873 * Sets the socket non-blocking if nonblocking is TRUE, or sets it
874 * blocking otherwise.
875 * --------------------------------
878 socket_set_nonblocking(bool nonblocking)
880 if (MyProcPort == NULL)
882 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
883 errmsg("there is no client connection")));
885 MyProcPort->noblock = nonblocking;
888 /* --------------------------------
889 * pq_recvbuf - load some bytes into the input buffer
891 * returns 0 if OK, EOF if trouble
892 * --------------------------------
897 if (PqRecvPointer > 0)
899 if (PqRecvLength > PqRecvPointer)
901 /* still some unread data, left-justify it in the buffer */
902 memmove(PqRecvBuffer, PqRecvBuffer + PqRecvPointer,
903 PqRecvLength - PqRecvPointer);
904 PqRecvLength -= PqRecvPointer;
908 PqRecvLength = PqRecvPointer = 0;
911 /* Ensure that we're in blocking mode */
912 socket_set_nonblocking(false);
914 /* Can fill buffer from PqRecvLength and upwards */
919 r = secure_read(MyProcPort, PqRecvBuffer + PqRecvLength,
920 PQ_RECV_BUFFER_SIZE - PqRecvLength);
925 continue; /* Ok if interrupted */
928 * Careful: an ereport() that tries to write to the client would
929 * cause recursion to here, leading to stack overflow and core
930 * dump! This message must go *only* to the postmaster log.
933 (errcode_for_socket_access(),
934 errmsg("could not receive data from client: %m")));
940 * EOF detected. We used to write a log message here, but it's
941 * better to expect the ultimate caller to do that.
945 /* r contains number of bytes read, so just incr length */
951 /* --------------------------------
952 * pq_getbyte - get a single byte from connection, or return EOF
953 * --------------------------------
958 Assert(PqCommReadingMsg);
960 while (PqRecvPointer >= PqRecvLength)
962 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
963 return EOF; /* Failed to recv data */
965 return (unsigned char) PqRecvBuffer[PqRecvPointer++];
968 /* --------------------------------
969 * pq_peekbyte - peek at next byte from connection
971 * Same as pq_getbyte() except we don't advance the pointer.
972 * --------------------------------
977 Assert(PqCommReadingMsg);
979 while (PqRecvPointer >= PqRecvLength)
981 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
982 return EOF; /* Failed to recv data */
984 return (unsigned char) PqRecvBuffer[PqRecvPointer];
987 /* --------------------------------
988 * pq_getbyte_if_available - get a single byte from connection,
991 * The received byte is stored in *c. Returns 1 if a byte was read,
992 * 0 if no data was available, or EOF if trouble.
993 * --------------------------------
996 pq_getbyte_if_available(unsigned char *c)
1000 Assert(PqCommReadingMsg);
1002 if (PqRecvPointer < PqRecvLength)
1004 *c = PqRecvBuffer[PqRecvPointer++];
1008 /* Put the socket into non-blocking mode */
1009 socket_set_nonblocking(true);
1011 r = secure_read(MyProcPort, c, 1);
1015 * Ok if no data available without blocking or interrupted (though
1016 * EINTR really shouldn't happen with a non-blocking socket). Report
1019 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
1024 * Careful: an ereport() that tries to write to the client would
1025 * cause recursion to here, leading to stack overflow and core
1026 * dump! This message must go *only* to the postmaster log.
1029 (errcode_for_socket_access(),
1030 errmsg("could not receive data from client: %m")));
1043 /* --------------------------------
1044 * pq_getbytes - get a known number of bytes from connection
1046 * returns 0 if OK, EOF if trouble
1047 * --------------------------------
1050 pq_getbytes(char *s, size_t len)
1054 Assert(PqCommReadingMsg);
1058 while (PqRecvPointer >= PqRecvLength)
1060 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1061 return EOF; /* Failed to recv data */
1063 amount = PqRecvLength - PqRecvPointer;
1066 memcpy(s, PqRecvBuffer + PqRecvPointer, amount);
1067 PqRecvPointer += amount;
1074 /* --------------------------------
1075 * pq_discardbytes - throw away a known number of bytes
1077 * same as pq_getbytes except we do not copy the data to anyplace.
1078 * this is used for resynchronizing after read errors.
1080 * returns 0 if OK, EOF if trouble
1081 * --------------------------------
1084 pq_discardbytes(size_t len)
1088 Assert(PqCommReadingMsg);
1092 while (PqRecvPointer >= PqRecvLength)
1094 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1095 return EOF; /* Failed to recv data */
1097 amount = PqRecvLength - PqRecvPointer;
1100 PqRecvPointer += amount;
1106 /* --------------------------------
1107 * pq_getstring - get a null terminated string from connection
1109 * The return value is placed in an expansible StringInfo, which has
1110 * already been initialized by the caller.
1112 * This is used only for dealing with old-protocol clients. The idea
1113 * is to produce a StringInfo that looks the same as we would get from
1114 * pq_getmessage() with a newer client; we will then process it with
1115 * pq_getmsgstring. Therefore, no character set conversion is done here,
1116 * even though this is presumably useful only for text.
1118 * returns 0 if OK, EOF if trouble
1119 * --------------------------------
1122 pq_getstring(StringInfo s)
1126 Assert(PqCommReadingMsg);
1130 /* Read until we get the terminating '\0' */
1133 while (PqRecvPointer >= PqRecvLength)
1135 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1136 return EOF; /* Failed to recv data */
1139 for (i = PqRecvPointer; i < PqRecvLength; i++)
1141 if (PqRecvBuffer[i] == '\0')
1143 /* include the '\0' in the copy */
1144 appendBinaryStringInfo(s, PqRecvBuffer + PqRecvPointer,
1145 i - PqRecvPointer + 1);
1146 PqRecvPointer = i + 1; /* advance past \0 */
1151 /* If we're here we haven't got the \0 in the buffer yet. */
1152 appendBinaryStringInfo(s, PqRecvBuffer + PqRecvPointer,
1153 PqRecvLength - PqRecvPointer);
1154 PqRecvPointer = PqRecvLength;
1159 /* --------------------------------
1160 * pq_startmsgread - begin reading a message from the client.
1162 * This must be called before any of the pq_get* functions.
1163 * --------------------------------
1166 pq_startmsgread(void)
1169 * There shouldn't be a read active already, but let's check just to be
1172 if (PqCommReadingMsg)
1174 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1175 errmsg("terminating connection because protocol sync was lost")));
1177 PqCommReadingMsg = true;
1181 /* --------------------------------
1182 * pq_endmsgread - finish reading message.
1184 * This must be called after reading a V2 protocol message with
1185 * pq_getstring() and friends, to indicate that we have read the whole
1186 * message. In V3 protocol, pq_getmessage() does this implicitly.
1187 * --------------------------------
1192 Assert(PqCommReadingMsg);
1194 PqCommReadingMsg = false;
1197 /* --------------------------------
1198 * pq_is_reading_msg - are we currently reading a message?
1200 * This is used in error recovery at the outer idle loop to detect if we have
1201 * lost protocol sync, and need to terminate the connection. pq_startmsgread()
1202 * will check for that too, but it's nicer to detect it earlier.
1203 * --------------------------------
1206 pq_is_reading_msg(void)
1208 return PqCommReadingMsg;
1211 /* --------------------------------
1212 * pq_getmessage - get a message with length word from connection
1214 * The return value is placed in an expansible StringInfo, which has
1215 * already been initialized by the caller.
1216 * Only the message body is placed in the StringInfo; the length word
1217 * is removed. Also, s->cursor is initialized to zero for convenience
1218 * in scanning the message contents.
1220 * If maxlen is not zero, it is an upper limit on the length of the
1221 * message we are willing to accept. We abort the connection (by
1222 * returning EOF) if client tries to send more than that.
1224 * returns 0 if OK, EOF if trouble
1225 * --------------------------------
1228 pq_getmessage(StringInfo s, int maxlen)
1232 Assert(PqCommReadingMsg);
1236 /* Read message length word */
1237 if (pq_getbytes((char *) &len, 4) == EOF)
1240 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1241 errmsg("unexpected EOF within message length word")));
1248 (maxlen > 0 && len > maxlen))
1251 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1252 errmsg("invalid message length")));
1256 len -= 4; /* discount length itself */
1261 * Allocate space for message. If we run out of room (ridiculously
1262 * large message), we will elog(ERROR), but we want to discard the
1263 * message body so as not to lose communication sync.
1267 enlargeStringInfo(s, len);
1271 if (pq_discardbytes(len) == EOF)
1273 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1274 errmsg("incomplete message from client")));
1276 /* we discarded the rest of the message so we're back in sync. */
1277 PqCommReadingMsg = false;
1282 /* And grab the message */
1283 if (pq_getbytes(s->data, len) == EOF)
1286 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1287 errmsg("incomplete message from client")));
1291 /* Place a trailing null per StringInfo convention */
1292 s->data[len] = '\0';
1295 /* finished reading the message. */
1296 PqCommReadingMsg = false;
1302 /* --------------------------------
1303 * pq_putbytes - send bytes to connection (not flushed until pq_flush)
1305 * returns 0 if OK, EOF if trouble
1306 * --------------------------------
1309 pq_putbytes(const char *s, size_t len)
1313 /* Should only be called by old-style COPY OUT */
1314 Assert(DoingCopyOut);
1315 /* No-op if reentrant call */
1319 res = internal_putbytes(s, len);
1325 internal_putbytes(const char *s, size_t len)
1331 /* If buffer is full, then flush it out */
1332 if (PqSendPointer >= PqSendBufferSize)
1334 socket_set_nonblocking(false);
1335 if (internal_flush())
1338 amount = PqSendBufferSize - PqSendPointer;
1341 memcpy(PqSendBuffer + PqSendPointer, s, amount);
1342 PqSendPointer += amount;
1349 /* --------------------------------
1350 * socket_flush - flush pending output
1352 * returns 0 if OK, EOF if trouble
1353 * --------------------------------
1360 /* No-op if reentrant call */
1364 socket_set_nonblocking(false);
1365 res = internal_flush();
1370 /* --------------------------------
1371 * internal_flush - flush pending output
1373 * Returns 0 if OK (meaning everything was sent, or operation would block
1374 * and the socket is in non-blocking mode), or EOF if trouble.
1375 * --------------------------------
1378 internal_flush(void)
1380 static int last_reported_send_errno = 0;
1382 char *bufptr = PqSendBuffer + PqSendStart;
1383 char *bufend = PqSendBuffer + PqSendPointer;
1385 while (bufptr < bufend)
1389 r = secure_write(MyProcPort, bufptr, bufend - bufptr);
1394 continue; /* Ok if we were interrupted */
1397 * Ok if no data writable without blocking, and the socket is in
1398 * non-blocking mode.
1400 if (errno == EAGAIN ||
1401 errno == EWOULDBLOCK)
1407 * Careful: an ereport() that tries to write to the client would
1408 * cause recursion to here, leading to stack overflow and core
1409 * dump! This message must go *only* to the postmaster log.
1411 * If a client disconnects while we're in the midst of output, we
1412 * might write quite a bit of data before we get to a safe query
1413 * abort point. So, suppress duplicate log messages.
1415 if (errno != last_reported_send_errno)
1417 last_reported_send_errno = errno;
1419 (errcode_for_socket_access(),
1420 errmsg("could not send data to client: %m")));
1424 * We drop the buffered data anyway so that processing can
1425 * continue, even though we'll probably quit soon. We also set a
1426 * flag that'll cause the next CHECK_FOR_INTERRUPTS to terminate
1429 PqSendStart = PqSendPointer = 0;
1430 ClientConnectionLost = 1;
1431 InterruptPending = 1;
1435 last_reported_send_errno = 0; /* reset after any successful send */
1440 PqSendStart = PqSendPointer = 0;
1444 /* --------------------------------
1445 * pq_flush_if_writable - flush pending output if writable without blocking
1447 * Returns 0 if OK, or EOF if trouble.
1448 * --------------------------------
1451 socket_flush_if_writable(void)
1455 /* Quick exit if nothing to do */
1456 if (PqSendPointer == PqSendStart)
1459 /* No-op if reentrant call */
1463 /* Temporarily put the socket into non-blocking mode */
1464 socket_set_nonblocking(true);
1467 res = internal_flush();
1472 /* --------------------------------
1473 * socket_is_send_pending - is there any pending data in the output buffer?
1474 * --------------------------------
1477 socket_is_send_pending(void)
1479 return (PqSendStart < PqSendPointer);
1482 /* --------------------------------
1483 * Message-level I/O routines begin here.
1485 * These routines understand about the old-style COPY OUT protocol.
1486 * --------------------------------
1490 /* --------------------------------
1491 * socket_putmessage - send a normal message (suppressed in COPY OUT mode)
1493 * If msgtype is not '\0', it is a message type code to place before
1494 * the message body. If msgtype is '\0', then the message has no type
1495 * code (this is only valid in pre-3.0 protocols).
1497 * len is the length of the message body data at *s. In protocol 3.0
1498 * and later, a message length word (equal to len+4 because it counts
1499 * itself too) is inserted by this routine.
1501 * All normal messages are suppressed while old-style COPY OUT is in
1502 * progress. (In practice only a few notice messages might get emitted
1503 * then; dropping them is annoying, but at least they will still appear
1504 * in the postmaster log.)
1506 * We also suppress messages generated while pqcomm.c is busy. This
1507 * avoids any possibility of messages being inserted within other
1508 * messages. The only known trouble case arises if SIGQUIT occurs
1509 * during a pqcomm.c routine --- quickdie() will try to send a warning
1510 * message, and the most reasonable approach seems to be to drop it.
1512 * returns 0 if OK, EOF if trouble
1513 * --------------------------------
1516 socket_putmessage(char msgtype, const char *s, size_t len)
1518 if (DoingCopyOut || PqCommBusy)
1522 if (internal_putbytes(&msgtype, 1))
1524 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
1528 n32 = htonl((uint32) (len + 4));
1529 if (internal_putbytes((char *) &n32, 4))
1532 if (internal_putbytes(s, len))
1542 /* --------------------------------
1543 * pq_putmessage_noblock - like pq_putmessage, but never blocks
1545 * If the output buffer is too small to hold the message, the buffer
1549 socket_putmessage_noblock(char msgtype, const char *s, size_t len)
1551 int res PG_USED_FOR_ASSERTS_ONLY;
1555 * Ensure we have enough space in the output buffer for the message header
1556 * as well as the message itself.
1558 required = PqSendPointer + 1 + 4 + len;
1559 if (required > PqSendBufferSize)
1561 PqSendBuffer = repalloc(PqSendBuffer, required);
1562 PqSendBufferSize = required;
1564 res = pq_putmessage(msgtype, s, len);
1565 Assert(res == 0); /* should not fail when the message fits in
1570 /* --------------------------------
1571 * socket_startcopyout - inform libpq that an old-style COPY OUT transfer
1573 * --------------------------------
1576 socket_startcopyout(void)
1578 DoingCopyOut = true;
1581 /* --------------------------------
1582 * socket_endcopyout - end an old-style COPY OUT transfer
1584 * If errorAbort is indicated, we are aborting a COPY OUT due to an error,
1585 * and must send a terminator line. Since a partial data line might have
1586 * been emitted, send a couple of newlines first (the first one could
1587 * get absorbed by a backslash...) Note that old-style COPY OUT does
1588 * not allow binary transfers, so a textual terminator is always correct.
1589 * --------------------------------
1592 socket_endcopyout(bool errorAbort)
1597 pq_putbytes("\n\n\\.\n", 5);
1598 /* in non-error case, copy.c will have emitted the terminator line */
1599 DoingCopyOut = false;
1603 * Support for TCP Keepalive parameters
1607 * On Windows, we need to set both idle and interval at the same time.
1608 * We also cannot reset them to the default (setting to zero will
1609 * actually set them to zero, not default), therefore we fallback to
1610 * the out-of-the-box default instead.
1612 #if defined(WIN32) && defined(SIO_KEEPALIVE_VALS)
1614 pq_setkeepaliveswin32(Port *port, int idle, int interval)
1616 struct tcp_keepalive ka;
1620 idle = 2 * 60 * 60; /* default = 2 hours */
1622 interval = 1; /* default = 1 second */
1625 ka.keepalivetime = idle * 1000;
1626 ka.keepaliveinterval = interval * 1000;
1628 if (WSAIoctl(port->sock,
1639 elog(LOG, "WSAIoctl(SIO_KEEPALIVE_VALS) failed: %ui",
1641 return STATUS_ERROR;
1643 if (port->keepalives_idle != idle)
1644 port->keepalives_idle = idle;
1645 if (port->keepalives_interval != interval)
1646 port->keepalives_interval = interval;
1652 pq_getkeepalivesidle(Port *port)
1654 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPALIVE) || defined(WIN32)
1655 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1658 if (port->keepalives_idle != 0)
1659 return port->keepalives_idle;
1661 if (port->default_keepalives_idle == 0)
1664 ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_idle);
1667 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPIDLE,
1668 (char *) &port->default_keepalives_idle,
1671 elog(LOG, "getsockopt(TCP_KEEPIDLE) failed: %m");
1672 port->default_keepalives_idle = -1; /* don't know */
1675 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPALIVE,
1676 (char *) &port->default_keepalives_idle,
1679 elog(LOG, "getsockopt(TCP_KEEPALIVE) failed: %m");
1680 port->default_keepalives_idle = -1; /* don't know */
1682 #endif /* TCP_KEEPIDLE */
1684 /* We can't get the defaults on Windows, so return "don't know" */
1685 port->default_keepalives_idle = -1;
1689 return port->default_keepalives_idle;
1696 pq_setkeepalivesidle(int idle, Port *port)
1698 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1701 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPALIVE) || defined(SIO_KEEPALIVE_VALS)
1702 if (idle == port->keepalives_idle)
1706 if (port->default_keepalives_idle <= 0)
1708 if (pq_getkeepalivesidle(port) < 0)
1711 return STATUS_OK; /* default is set but unknown */
1713 return STATUS_ERROR;
1718 idle = port->default_keepalives_idle;
1721 if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPIDLE,
1722 (char *) &idle, sizeof(idle)) < 0)
1724 elog(LOG, "setsockopt(TCP_KEEPIDLE) failed: %m");
1725 return STATUS_ERROR;
1728 if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPALIVE,
1729 (char *) &idle, sizeof(idle)) < 0)
1731 elog(LOG, "setsockopt(TCP_KEEPALIVE) failed: %m");
1732 return STATUS_ERROR;
1736 port->keepalives_idle = idle;
1738 return pq_setkeepaliveswin32(port, idle, port->keepalives_interval);
1740 #else /* TCP_KEEPIDLE || SIO_KEEPALIVE_VALS */
1743 elog(LOG, "setting the keepalive idle time is not supported");
1744 return STATUS_ERROR;
1751 pq_getkeepalivesinterval(Port *port)
1753 #if defined(TCP_KEEPINTVL) || defined(SIO_KEEPALIVE_VALS)
1754 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1757 if (port->keepalives_interval != 0)
1758 return port->keepalives_interval;
1760 if (port->default_keepalives_interval == 0)
1763 ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_interval);
1765 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1766 (char *) &port->default_keepalives_interval,
1769 elog(LOG, "getsockopt(TCP_KEEPINTVL) failed: %m");
1770 port->default_keepalives_interval = -1; /* don't know */
1773 /* We can't get the defaults on Windows, so return "don't know" */
1774 port->default_keepalives_interval = -1;
1778 return port->default_keepalives_interval;
1785 pq_setkeepalivesinterval(int interval, Port *port)
1787 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1790 #if defined(TCP_KEEPINTVL) || defined (SIO_KEEPALIVE_VALS)
1791 if (interval == port->keepalives_interval)
1795 if (port->default_keepalives_interval <= 0)
1797 if (pq_getkeepalivesinterval(port) < 0)
1800 return STATUS_OK; /* default is set but unknown */
1802 return STATUS_ERROR;
1807 interval = port->default_keepalives_interval;
1809 if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1810 (char *) &interval, sizeof(interval)) < 0)
1812 elog(LOG, "setsockopt(TCP_KEEPINTVL) failed: %m");
1813 return STATUS_ERROR;
1816 port->keepalives_interval = interval;
1818 return pq_setkeepaliveswin32(port, port->keepalives_idle, interval);
1823 elog(LOG, "setsockopt(TCP_KEEPINTVL) not supported");
1824 return STATUS_ERROR;
1832 pq_getkeepalivescount(Port *port)
1835 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1838 if (port->keepalives_count != 0)
1839 return port->keepalives_count;
1841 if (port->default_keepalives_count == 0)
1843 ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_count);
1845 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
1846 (char *) &port->default_keepalives_count,
1849 elog(LOG, "getsockopt(TCP_KEEPCNT) failed: %m");
1850 port->default_keepalives_count = -1; /* don't know */
1854 return port->default_keepalives_count;
1861 pq_setkeepalivescount(int count, Port *port)
1863 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1867 if (count == port->keepalives_count)
1870 if (port->default_keepalives_count <= 0)
1872 if (pq_getkeepalivescount(port) < 0)
1875 return STATUS_OK; /* default is set but unknown */
1877 return STATUS_ERROR;
1882 count = port->default_keepalives_count;
1884 if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
1885 (char *) &count, sizeof(count)) < 0)
1887 elog(LOG, "setsockopt(TCP_KEEPCNT) failed: %m");
1888 return STATUS_ERROR;
1891 port->keepalives_count = count;
1895 elog(LOG, "setsockopt(TCP_KEEPCNT) not supported");
1896 return STATUS_ERROR;