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-2016, 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);
149 #ifdef HAVE_UNIX_SOCKETS
150 static int Lock_AF_UNIX(char *unixSocketDir, char *unixSocketPath);
151 static int Setup_AF_UNIX(char *sock_path);
152 #endif /* HAVE_UNIX_SOCKETS */
154 static PQcommMethods PqCommSocketMethods = {
157 socket_flush_if_writable,
158 socket_is_send_pending,
160 socket_putmessage_noblock,
165 PQcommMethods *PqCommMethods = &PqCommSocketMethods;
167 WaitEventSet *FeBeWaitSet;
170 /* --------------------------------
171 * pq_init - initialize libpq at backend startup
172 * --------------------------------
177 /* initialize state variables */
178 PqSendBufferSize = PQ_SEND_BUFFER_SIZE;
179 PqSendBuffer = MemoryContextAlloc(TopMemoryContext, PqSendBufferSize);
180 PqSendPointer = PqSendStart = PqRecvPointer = PqRecvLength = 0;
182 PqCommReadingMsg = false;
183 DoingCopyOut = false;
185 /* set up process-exit hook to close the socket */
186 on_proc_exit(socket_close, 0);
189 * In backends (as soon as forked) we operate the underlying socket in
190 * nonblocking mode and use latches to implement blocking semantics if
191 * needed. That allows us to provide safely interruptible reads and
194 * Use COMMERROR on failure, because ERROR would try to send the error to
195 * the client, which might require changing the mode again, leading to
196 * infinite recursion.
199 if (!pg_set_noblock(MyProcPort->sock))
201 (errmsg("could not set socket to nonblocking mode: %m")));
204 FeBeWaitSet = CreateWaitEventSet(TopMemoryContext, 3);
205 AddWaitEventToSet(FeBeWaitSet, WL_SOCKET_WRITEABLE, MyProcPort->sock,
207 AddWaitEventToSet(FeBeWaitSet, WL_LATCH_SET, -1, MyLatch, NULL);
208 AddWaitEventToSet(FeBeWaitSet, WL_POSTMASTER_DEATH, -1, NULL, NULL);
211 /* --------------------------------
212 * socket_comm_reset - reset libpq during error recovery
214 * This is called from error recovery at the outer idle loop. It's
215 * just to get us out of trouble if we somehow manage to elog() from
216 * inside a pqcomm.c routine (which ideally will never happen, but...)
217 * --------------------------------
220 socket_comm_reset(void)
222 /* Do not throw away pending data, but do reset the busy flag */
224 /* We can abort any old-style COPY OUT, too */
228 /* --------------------------------
229 * socket_close - shutdown libpq at backend exit
231 * This is the one pg_on_exit_callback in place during BackendInitialize().
232 * That function's unusual signal handling constrains that this callback be
233 * safe to run at any instant.
234 * --------------------------------
237 socket_close(int code, Datum arg)
239 /* Nothing to do in a standalone backend, where MyProcPort is NULL. */
240 if (MyProcPort != NULL)
242 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
247 * Shutdown GSSAPI layer. This section does nothing when interrupting
248 * BackendInitialize(), because pg_GSS_recvauth() makes first use of
251 if (MyProcPort->gss->ctx != GSS_C_NO_CONTEXT)
252 gss_delete_sec_context(&min_s, &MyProcPort->gss->ctx, NULL);
254 if (MyProcPort->gss->cred != GSS_C_NO_CREDENTIAL)
255 gss_release_cred(&min_s, &MyProcPort->gss->cred);
256 #endif /* ENABLE_GSS */
259 * GSS and SSPI share the port->gss struct. Since nowhere else does a
260 * postmaster child free this, doing so is safe when interrupting
261 * BackendInitialize().
263 free(MyProcPort->gss);
264 #endif /* ENABLE_GSS || ENABLE_SSPI */
267 * Cleanly shut down SSL layer. Nowhere else does a postmaster child
268 * call this, so this is safe when interrupting BackendInitialize().
270 secure_close(MyProcPort);
273 * Formerly we did an explicit close() here, but it seems better to
274 * leave the socket open until the process dies. This allows clients
275 * to perform a "synchronous close" if they care --- wait till the
276 * transport layer reports connection closure, and you can be sure the
277 * backend has exited.
279 * We do set sock to PGINVALID_SOCKET to prevent any further I/O,
282 MyProcPort->sock = PGINVALID_SOCKET;
289 * Streams -- wrapper around Unix socket system calls
292 * Stream functions are used for vanilla TCP connection protocol.
297 * StreamServerPort -- open a "listening" port to accept connections.
299 * family should be AF_UNIX or AF_UNSPEC; portNumber is the port number.
300 * For AF_UNIX ports, hostName should be NULL and unixSocketDir must be
301 * specified. For TCP ports, hostName is either NULL for all interfaces or
302 * the interface to listen on, and unixSocketDir is ignored (can be NULL).
304 * Successfully opened sockets are added to the ListenSocket[] array (of
305 * length MaxListen), at the first position that isn't PGINVALID_SOCKET.
307 * RETURNS: STATUS_OK or STATUS_ERROR
311 StreamServerPort(int family, char *hostName, unsigned short portNumber,
313 pgsocket ListenSocket[], int MaxListen)
319 char portNumberStr[32];
320 const char *familyDesc;
321 char familyDescBuf[64];
323 struct addrinfo *addrs = NULL,
325 struct addrinfo hint;
326 int listen_index = 0;
329 #ifdef HAVE_UNIX_SOCKETS
330 char unixSocketPath[MAXPGPATH];
332 #if !defined(WIN32) || defined(IPV6_V6ONLY)
336 /* Initialize hint structure */
337 MemSet(&hint, 0, sizeof(hint));
338 hint.ai_family = family;
339 hint.ai_flags = AI_PASSIVE;
340 hint.ai_socktype = SOCK_STREAM;
342 #ifdef HAVE_UNIX_SOCKETS
343 if (family == AF_UNIX)
346 * Create unixSocketPath from portNumber and unixSocketDir and lock
349 UNIXSOCK_PATH(unixSocketPath, portNumber, unixSocketDir);
350 if (strlen(unixSocketPath) >= UNIXSOCK_PATH_BUFLEN)
353 (errmsg("Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
355 (int) (UNIXSOCK_PATH_BUFLEN - 1))));
358 if (Lock_AF_UNIX(unixSocketDir, unixSocketPath) != STATUS_OK)
360 service = unixSocketPath;
363 #endif /* HAVE_UNIX_SOCKETS */
365 snprintf(portNumberStr, sizeof(portNumberStr), "%d", portNumber);
366 service = portNumberStr;
369 ret = pg_getaddrinfo_all(hostName, service, &hint, &addrs);
374 (errmsg("could not translate host name \"%s\", service \"%s\" to address: %s",
375 hostName, service, gai_strerror(ret))));
378 (errmsg("could not translate service \"%s\" to address: %s",
379 service, gai_strerror(ret))));
381 pg_freeaddrinfo_all(hint.ai_family, addrs);
385 for (addr = addrs; addr; addr = addr->ai_next)
387 if (!IS_AF_UNIX(family) && IS_AF_UNIX(addr->ai_family))
390 * Only set up a unix domain socket when they really asked for it.
391 * The service/port is different in that case.
396 /* See if there is still room to add 1 more socket. */
397 for (; listen_index < MaxListen; listen_index++)
399 if (ListenSocket[listen_index] == PGINVALID_SOCKET)
402 if (listen_index >= MaxListen)
405 (errmsg("could not bind to all requested addresses: MAXLISTEN (%d) exceeded",
410 /* set up family name for possible error messages */
411 switch (addr->ai_family)
414 familyDesc = _("IPv4");
418 familyDesc = _("IPv6");
421 #ifdef HAVE_UNIX_SOCKETS
423 familyDesc = _("Unix");
427 snprintf(familyDescBuf, sizeof(familyDescBuf),
428 _("unrecognized address family %d"),
430 familyDesc = familyDescBuf;
434 if ((fd = socket(addr->ai_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
437 (errcode_for_socket_access(),
438 /* translator: %s is IPv4, IPv6, or Unix */
439 errmsg("could not create %s socket: %m",
447 * Without the SO_REUSEADDR flag, a new postmaster can't be started
448 * right away after a stop or crash, giving "address already in use"
449 * error on TCP ports.
451 * On win32, however, this behavior only happens if the
452 * SO_EXLUSIVEADDRUSE is set. With SO_REUSEADDR, win32 allows multiple
453 * servers to listen on the same address, resulting in unpredictable
454 * behavior. With no flags at all, win32 behaves as Unix with
457 if (!IS_AF_UNIX(addr->ai_family))
459 if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
460 (char *) &one, sizeof(one))) == -1)
463 (errcode_for_socket_access(),
464 errmsg("setsockopt(SO_REUSEADDR) failed: %m")));
472 if (addr->ai_family == AF_INET6)
474 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
475 (char *) &one, sizeof(one)) == -1)
478 (errcode_for_socket_access(),
479 errmsg("setsockopt(IPV6_V6ONLY) failed: %m")));
487 * Note: This might fail on some OS's, like Linux older than
488 * 2.4.21-pre3, that don't have the IPV6_V6ONLY socket option, and map
489 * ipv4 addresses to ipv6. It will show ::ffff:ipv4 for all ipv4
492 err = bind(fd, addr->ai_addr, addr->ai_addrlen);
496 (errcode_for_socket_access(),
497 /* translator: %s is IPv4, IPv6, or Unix */
498 errmsg("could not bind %s socket: %m",
500 (IS_AF_UNIX(addr->ai_family)) ?
501 errhint("Is another postmaster already running on port %d?"
502 " If not, remove socket file \"%s\" and retry.",
503 (int) portNumber, service) :
504 errhint("Is another postmaster already running on port %d?"
505 " If not, wait a few seconds and retry.",
511 #ifdef HAVE_UNIX_SOCKETS
512 if (addr->ai_family == AF_UNIX)
514 if (Setup_AF_UNIX(service) != STATUS_OK)
523 * Select appropriate accept-queue length limit. PG_SOMAXCONN is only
524 * intended to provide a clamp on the request on platforms where an
525 * overly large request provokes a kernel error (are there any?).
527 maxconn = MaxBackends * 2;
528 if (maxconn > PG_SOMAXCONN)
529 maxconn = PG_SOMAXCONN;
531 err = listen(fd, maxconn);
535 (errcode_for_socket_access(),
536 /* translator: %s is IPv4, IPv6, or Unix */
537 errmsg("could not listen on %s socket: %m",
542 ListenSocket[listen_index] = fd;
546 pg_freeaddrinfo_all(hint.ai_family, addrs);
555 #ifdef HAVE_UNIX_SOCKETS
558 * Lock_AF_UNIX -- configure unix socket file path
561 Lock_AF_UNIX(char *unixSocketDir, char *unixSocketPath)
564 * Grab an interlock file associated with the socket file.
566 * Note: there are two reasons for using a socket lock file, rather than
567 * trying to interlock directly on the socket itself. First, it's a lot
568 * more portable, and second, it lets us remove any pre-existing socket
569 * file without race conditions.
571 CreateSocketLockFile(unixSocketPath, true, unixSocketDir);
574 * Once we have the interlock, we can safely delete any pre-existing
575 * socket file to avoid failure at bind() time.
577 (void) unlink(unixSocketPath);
580 * Remember socket file pathnames for later maintenance.
582 sock_paths = lappend(sock_paths, pstrdup(unixSocketPath));
589 * Setup_AF_UNIX -- configure unix socket permissions
592 Setup_AF_UNIX(char *sock_path)
595 * Fix socket ownership/permission if requested. Note we must do this
596 * before we listen() to avoid a window where unwanted connections could
599 Assert(Unix_socket_group);
600 if (Unix_socket_group[0] != '\0')
603 elog(WARNING, "configuration item unix_socket_group is not supported on this platform");
609 val = strtoul(Unix_socket_group, &endptr, 10);
611 { /* numeric group id */
615 { /* convert group name to id */
618 gr = getgrnam(Unix_socket_group);
622 (errmsg("group \"%s\" does not exist",
623 Unix_socket_group)));
628 if (chown(sock_path, -1, gid) == -1)
631 (errcode_for_file_access(),
632 errmsg("could not set group of file \"%s\": %m",
639 if (chmod(sock_path, Unix_socket_permissions) == -1)
642 (errcode_for_file_access(),
643 errmsg("could not set permissions of file \"%s\": %m",
649 #endif /* HAVE_UNIX_SOCKETS */
653 * StreamConnection -- create a new connection with client using
654 * server port. Set port->sock to the FD of the new connection.
656 * ASSUME: that this doesn't need to be non-blocking because
657 * the Postmaster uses select() to tell when the server master
658 * socket is ready for accept().
660 * RETURNS: STATUS_OK or STATUS_ERROR
663 StreamConnection(pgsocket server_fd, Port *port)
665 /* accept connection and fill in the client (remote) address */
666 port->raddr.salen = sizeof(port->raddr.addr);
667 if ((port->sock = accept(server_fd,
668 (struct sockaddr *) & port->raddr.addr,
669 &port->raddr.salen)) == PGINVALID_SOCKET)
672 (errcode_for_socket_access(),
673 errmsg("could not accept new connection: %m")));
676 * If accept() fails then postmaster.c will still see the server
677 * socket as read-ready, and will immediately try again. To avoid
678 * uselessly sucking lots of CPU, delay a bit before trying again.
679 * (The most likely reason for failure is being out of kernel file
680 * table slots; we can do little except hope some will get freed up.)
682 pg_usleep(100000L); /* wait 0.1 sec */
686 #ifdef SCO_ACCEPT_BUG
689 * UnixWare 7+ and OpenServer 5.0.4 are known to have this bug, but it
690 * shouldn't hurt to catch it for all versions of those platforms.
692 if (port->raddr.addr.ss_family == 0)
693 port->raddr.addr.ss_family = AF_UNIX;
696 /* fill in the server (local) address */
697 port->laddr.salen = sizeof(port->laddr.addr);
698 if (getsockname(port->sock,
699 (struct sockaddr *) & port->laddr.addr,
700 &port->laddr.salen) < 0)
702 elog(LOG, "getsockname() failed: %m");
706 /* select NODELAY and KEEPALIVE options if it's a TCP connection */
707 if (!IS_AF_UNIX(port->laddr.addr.ss_family))
718 if (setsockopt(port->sock, IPPROTO_TCP, TCP_NODELAY,
719 (char *) &on, sizeof(on)) < 0)
721 elog(LOG, "setsockopt(TCP_NODELAY) failed: %m");
726 if (setsockopt(port->sock, SOL_SOCKET, SO_KEEPALIVE,
727 (char *) &on, sizeof(on)) < 0)
729 elog(LOG, "setsockopt(SO_KEEPALIVE) failed: %m");
736 * This is a Win32 socket optimization. The OS send buffer should be
737 * large enough to send the whole Postgres send buffer in one go, or
738 * performance suffers. The Postgres send buffer can be enlarged if a
739 * very large message needs to be sent, but we won't attempt to
740 * enlarge the OS buffer if that happens, so somewhat arbitrarily
741 * ensure that the OS buffer is at least PQ_SEND_BUFFER_SIZE * 4.
742 * (That's 32kB with the current default).
744 * The default OS buffer size used to be 8kB in earlier Windows
745 * versions, but was raised to 64kB in Windows 2012. So it shouldn't
746 * be necessary to change it in later versions anymore. Changing it
747 * unnecessarily can even reduce performance, because setting
748 * SO_SNDBUF in the application disables the "dynamic send buffering"
749 * feature that was introduced in Windows 7. So before fiddling with
750 * SO_SNDBUF, check if the current buffer size is already large enough
751 * and only increase it if necessary.
753 * See https://support.microsoft.com/kb/823764/EN-US/ and
754 * https://msdn.microsoft.com/en-us/library/bb736549%28v=vs.85%29.aspx
756 optlen = sizeof(oldopt);
757 if (getsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &oldopt,
760 elog(LOG, "getsockopt(SO_SNDBUF) failed: %m");
763 newopt = PQ_SEND_BUFFER_SIZE * 4;
766 if (setsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &newopt,
769 elog(LOG, "setsockopt(SO_SNDBUF) failed: %m");
776 * Also apply the current keepalive parameters. If we fail to set a
777 * parameter, don't error out, because these aren't universally
778 * supported. (Note: you might think we need to reset the GUC
779 * variables to 0 in such a case, but it's not necessary because the
780 * show hooks for these variables report the truth anyway.)
782 (void) pq_setkeepalivesidle(tcp_keepalives_idle, port);
783 (void) pq_setkeepalivesinterval(tcp_keepalives_interval, port);
784 (void) pq_setkeepalivescount(tcp_keepalives_count, port);
791 * StreamClose -- close a client/backend connection
793 * NOTE: this is NOT used to terminate a session; it is just used to release
794 * the file descriptor in a process that should no longer have the socket
795 * open. (For example, the postmaster calls this after passing ownership
796 * of the connection to a child process.) It is expected that someone else
797 * still has the socket open. So, we only want to close the descriptor,
798 * we do NOT want to send anything to the far end.
801 StreamClose(pgsocket sock)
807 * TouchSocketFiles -- mark socket files as recently accessed
809 * This routine should be called every so often to ensure that the socket
810 * files have a recent mod date (ordinary operations on sockets usually won't
811 * change the mod date). That saves them from being removed by
812 * overenthusiastic /tmp-directory-cleaner daemons. (Another reason we should
813 * never have put the socket file in /tmp...)
816 TouchSocketFiles(void)
820 /* Loop through all created sockets... */
821 foreach(l, sock_paths)
823 char *sock_path = (char *) lfirst(l);
826 * utime() is POSIX standard, utimes() is a common alternative. If we
827 * have neither, there's no way to affect the mod or access time of
830 * In either path, we ignore errors; there's no point in complaining.
833 utime(sock_path, NULL);
834 #else /* !HAVE_UTIME */
836 utimes(sock_path, NULL);
837 #endif /* HAVE_UTIMES */
838 #endif /* HAVE_UTIME */
843 * RemoveSocketFiles -- unlink socket files at postmaster shutdown
846 RemoveSocketFiles(void)
850 /* Loop through all created sockets... */
851 foreach(l, sock_paths)
853 char *sock_path = (char *) lfirst(l);
855 /* Ignore any error. */
856 (void) unlink(sock_path);
858 /* Since we're about to exit, no need to reclaim storage */
863 /* --------------------------------
864 * Low-level I/O routines begin here.
866 * These routines communicate with a frontend client across a connection
867 * already established by the preceding routines.
868 * --------------------------------
871 /* --------------------------------
872 * socket_set_nonblocking - set socket blocking/non-blocking
874 * Sets the socket non-blocking if nonblocking is TRUE, or sets it
875 * blocking otherwise.
876 * --------------------------------
879 socket_set_nonblocking(bool nonblocking)
881 if (MyProcPort == NULL)
883 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
884 errmsg("there is no client connection")));
886 MyProcPort->noblock = nonblocking;
889 /* --------------------------------
890 * pq_recvbuf - load some bytes into the input buffer
892 * returns 0 if OK, EOF if trouble
893 * --------------------------------
898 if (PqRecvPointer > 0)
900 if (PqRecvLength > PqRecvPointer)
902 /* still some unread data, left-justify it in the buffer */
903 memmove(PqRecvBuffer, PqRecvBuffer + PqRecvPointer,
904 PqRecvLength - PqRecvPointer);
905 PqRecvLength -= PqRecvPointer;
909 PqRecvLength = PqRecvPointer = 0;
912 /* Ensure that we're in blocking mode */
913 socket_set_nonblocking(false);
915 /* Can fill buffer from PqRecvLength and upwards */
920 r = secure_read(MyProcPort, PqRecvBuffer + PqRecvLength,
921 PQ_RECV_BUFFER_SIZE - PqRecvLength);
926 continue; /* Ok if interrupted */
929 * Careful: an ereport() that tries to write to the client would
930 * cause recursion to here, leading to stack overflow and core
931 * dump! This message must go *only* to the postmaster log.
934 (errcode_for_socket_access(),
935 errmsg("could not receive data from client: %m")));
941 * EOF detected. We used to write a log message here, but it's
942 * better to expect the ultimate caller to do that.
946 /* r contains number of bytes read, so just incr length */
952 /* --------------------------------
953 * pq_getbyte - get a single byte from connection, or return EOF
954 * --------------------------------
959 Assert(PqCommReadingMsg);
961 while (PqRecvPointer >= PqRecvLength)
963 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
964 return EOF; /* Failed to recv data */
966 return (unsigned char) PqRecvBuffer[PqRecvPointer++];
969 /* --------------------------------
970 * pq_peekbyte - peek at next byte from connection
972 * Same as pq_getbyte() except we don't advance the pointer.
973 * --------------------------------
978 Assert(PqCommReadingMsg);
980 while (PqRecvPointer >= PqRecvLength)
982 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
983 return EOF; /* Failed to recv data */
985 return (unsigned char) PqRecvBuffer[PqRecvPointer];
988 /* --------------------------------
989 * pq_getbyte_if_available - get a single byte from connection,
992 * The received byte is stored in *c. Returns 1 if a byte was read,
993 * 0 if no data was available, or EOF if trouble.
994 * --------------------------------
997 pq_getbyte_if_available(unsigned char *c)
1001 Assert(PqCommReadingMsg);
1003 if (PqRecvPointer < PqRecvLength)
1005 *c = PqRecvBuffer[PqRecvPointer++];
1009 /* Put the socket into non-blocking mode */
1010 socket_set_nonblocking(true);
1012 r = secure_read(MyProcPort, c, 1);
1016 * Ok if no data available without blocking or interrupted (though
1017 * EINTR really shouldn't happen with a non-blocking socket). Report
1020 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
1025 * Careful: an ereport() that tries to write to the client would
1026 * cause recursion to here, leading to stack overflow and core
1027 * dump! This message must go *only* to the postmaster log.
1030 (errcode_for_socket_access(),
1031 errmsg("could not receive data from client: %m")));
1044 /* --------------------------------
1045 * pq_getbytes - get a known number of bytes from connection
1047 * returns 0 if OK, EOF if trouble
1048 * --------------------------------
1051 pq_getbytes(char *s, size_t len)
1055 Assert(PqCommReadingMsg);
1059 while (PqRecvPointer >= PqRecvLength)
1061 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1062 return EOF; /* Failed to recv data */
1064 amount = PqRecvLength - PqRecvPointer;
1067 memcpy(s, PqRecvBuffer + PqRecvPointer, amount);
1068 PqRecvPointer += amount;
1075 /* --------------------------------
1076 * pq_discardbytes - throw away a known number of bytes
1078 * same as pq_getbytes except we do not copy the data to anyplace.
1079 * this is used for resynchronizing after read errors.
1081 * returns 0 if OK, EOF if trouble
1082 * --------------------------------
1085 pq_discardbytes(size_t len)
1089 Assert(PqCommReadingMsg);
1093 while (PqRecvPointer >= PqRecvLength)
1095 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1096 return EOF; /* Failed to recv data */
1098 amount = PqRecvLength - PqRecvPointer;
1101 PqRecvPointer += amount;
1107 /* --------------------------------
1108 * pq_getstring - get a null terminated string from connection
1110 * The return value is placed in an expansible StringInfo, which has
1111 * already been initialized by the caller.
1113 * This is used only for dealing with old-protocol clients. The idea
1114 * is to produce a StringInfo that looks the same as we would get from
1115 * pq_getmessage() with a newer client; we will then process it with
1116 * pq_getmsgstring. Therefore, no character set conversion is done here,
1117 * even though this is presumably useful only for text.
1119 * returns 0 if OK, EOF if trouble
1120 * --------------------------------
1123 pq_getstring(StringInfo s)
1127 Assert(PqCommReadingMsg);
1131 /* Read until we get the terminating '\0' */
1134 while (PqRecvPointer >= PqRecvLength)
1136 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1137 return EOF; /* Failed to recv data */
1140 for (i = PqRecvPointer; i < PqRecvLength; i++)
1142 if (PqRecvBuffer[i] == '\0')
1144 /* include the '\0' in the copy */
1145 appendBinaryStringInfo(s, PqRecvBuffer + PqRecvPointer,
1146 i - PqRecvPointer + 1);
1147 PqRecvPointer = i + 1; /* advance past \0 */
1152 /* If we're here we haven't got the \0 in the buffer yet. */
1153 appendBinaryStringInfo(s, PqRecvBuffer + PqRecvPointer,
1154 PqRecvLength - PqRecvPointer);
1155 PqRecvPointer = PqRecvLength;
1160 /* --------------------------------
1161 * pq_startmsgread - begin reading a message from the client.
1163 * This must be called before any of the pq_get* functions.
1164 * --------------------------------
1167 pq_startmsgread(void)
1170 * There shouldn't be a read active already, but let's check just to be
1173 if (PqCommReadingMsg)
1175 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1176 errmsg("terminating connection because protocol synchronization was lost")));
1178 PqCommReadingMsg = true;
1182 /* --------------------------------
1183 * pq_endmsgread - finish reading message.
1185 * This must be called after reading a V2 protocol message with
1186 * pq_getstring() and friends, to indicate that we have read the whole
1187 * message. In V3 protocol, pq_getmessage() does this implicitly.
1188 * --------------------------------
1193 Assert(PqCommReadingMsg);
1195 PqCommReadingMsg = false;
1198 /* --------------------------------
1199 * pq_is_reading_msg - are we currently reading a message?
1201 * This is used in error recovery at the outer idle loop to detect if we have
1202 * lost protocol sync, and need to terminate the connection. pq_startmsgread()
1203 * will check for that too, but it's nicer to detect it earlier.
1204 * --------------------------------
1207 pq_is_reading_msg(void)
1209 return PqCommReadingMsg;
1212 /* --------------------------------
1213 * pq_getmessage - get a message with length word from connection
1215 * The return value is placed in an expansible StringInfo, which has
1216 * already been initialized by the caller.
1217 * Only the message body is placed in the StringInfo; the length word
1218 * is removed. Also, s->cursor is initialized to zero for convenience
1219 * in scanning the message contents.
1221 * If maxlen is not zero, it is an upper limit on the length of the
1222 * message we are willing to accept. We abort the connection (by
1223 * returning EOF) if client tries to send more than that.
1225 * returns 0 if OK, EOF if trouble
1226 * --------------------------------
1229 pq_getmessage(StringInfo s, int maxlen)
1233 Assert(PqCommReadingMsg);
1237 /* Read message length word */
1238 if (pq_getbytes((char *) &len, 4) == EOF)
1241 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1242 errmsg("unexpected EOF within message length word")));
1249 (maxlen > 0 && len > maxlen))
1252 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1253 errmsg("invalid message length")));
1257 len -= 4; /* discount length itself */
1262 * Allocate space for message. If we run out of room (ridiculously
1263 * large message), we will elog(ERROR), but we want to discard the
1264 * message body so as not to lose communication sync.
1268 enlargeStringInfo(s, len);
1272 if (pq_discardbytes(len) == EOF)
1274 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1275 errmsg("incomplete message from client")));
1277 /* we discarded the rest of the message so we're back in sync. */
1278 PqCommReadingMsg = false;
1283 /* And grab the message */
1284 if (pq_getbytes(s->data, len) == EOF)
1287 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1288 errmsg("incomplete message from client")));
1292 /* Place a trailing null per StringInfo convention */
1293 s->data[len] = '\0';
1296 /* finished reading the message. */
1297 PqCommReadingMsg = false;
1303 /* --------------------------------
1304 * pq_putbytes - send bytes to connection (not flushed until pq_flush)
1306 * returns 0 if OK, EOF if trouble
1307 * --------------------------------
1310 pq_putbytes(const char *s, size_t len)
1314 /* Should only be called by old-style COPY OUT */
1315 Assert(DoingCopyOut);
1316 /* No-op if reentrant call */
1320 res = internal_putbytes(s, len);
1326 internal_putbytes(const char *s, size_t len)
1332 /* If buffer is full, then flush it out */
1333 if (PqSendPointer >= PqSendBufferSize)
1335 socket_set_nonblocking(false);
1336 if (internal_flush())
1339 amount = PqSendBufferSize - PqSendPointer;
1342 memcpy(PqSendBuffer + PqSendPointer, s, amount);
1343 PqSendPointer += amount;
1350 /* --------------------------------
1351 * socket_flush - flush pending output
1353 * returns 0 if OK, EOF if trouble
1354 * --------------------------------
1361 /* No-op if reentrant call */
1365 socket_set_nonblocking(false);
1366 res = internal_flush();
1371 /* --------------------------------
1372 * internal_flush - flush pending output
1374 * Returns 0 if OK (meaning everything was sent, or operation would block
1375 * and the socket is in non-blocking mode), or EOF if trouble.
1376 * --------------------------------
1379 internal_flush(void)
1381 static int last_reported_send_errno = 0;
1383 char *bufptr = PqSendBuffer + PqSendStart;
1384 char *bufend = PqSendBuffer + PqSendPointer;
1386 while (bufptr < bufend)
1390 r = secure_write(MyProcPort, bufptr, bufend - bufptr);
1395 continue; /* Ok if we were interrupted */
1398 * Ok if no data writable without blocking, and the socket is in
1399 * non-blocking mode.
1401 if (errno == EAGAIN ||
1402 errno == EWOULDBLOCK)
1408 * Careful: an ereport() that tries to write to the client would
1409 * cause recursion to here, leading to stack overflow and core
1410 * dump! This message must go *only* to the postmaster log.
1412 * If a client disconnects while we're in the midst of output, we
1413 * might write quite a bit of data before we get to a safe query
1414 * abort point. So, suppress duplicate log messages.
1416 if (errno != last_reported_send_errno)
1418 last_reported_send_errno = errno;
1420 (errcode_for_socket_access(),
1421 errmsg("could not send data to client: %m")));
1425 * We drop the buffered data anyway so that processing can
1426 * continue, even though we'll probably quit soon. We also set a
1427 * flag that'll cause the next CHECK_FOR_INTERRUPTS to terminate
1430 PqSendStart = PqSendPointer = 0;
1431 ClientConnectionLost = 1;
1432 InterruptPending = 1;
1436 last_reported_send_errno = 0; /* reset after any successful send */
1441 PqSendStart = PqSendPointer = 0;
1445 /* --------------------------------
1446 * pq_flush_if_writable - flush pending output if writable without blocking
1448 * Returns 0 if OK, or EOF if trouble.
1449 * --------------------------------
1452 socket_flush_if_writable(void)
1456 /* Quick exit if nothing to do */
1457 if (PqSendPointer == PqSendStart)
1460 /* No-op if reentrant call */
1464 /* Temporarily put the socket into non-blocking mode */
1465 socket_set_nonblocking(true);
1468 res = internal_flush();
1473 /* --------------------------------
1474 * socket_is_send_pending - is there any pending data in the output buffer?
1475 * --------------------------------
1478 socket_is_send_pending(void)
1480 return (PqSendStart < PqSendPointer);
1483 /* --------------------------------
1484 * Message-level I/O routines begin here.
1486 * These routines understand about the old-style COPY OUT protocol.
1487 * --------------------------------
1491 /* --------------------------------
1492 * socket_putmessage - send a normal message (suppressed in COPY OUT mode)
1494 * If msgtype is not '\0', it is a message type code to place before
1495 * the message body. If msgtype is '\0', then the message has no type
1496 * code (this is only valid in pre-3.0 protocols).
1498 * len is the length of the message body data at *s. In protocol 3.0
1499 * and later, a message length word (equal to len+4 because it counts
1500 * itself too) is inserted by this routine.
1502 * All normal messages are suppressed while old-style COPY OUT is in
1503 * progress. (In practice only a few notice messages might get emitted
1504 * then; dropping them is annoying, but at least they will still appear
1505 * in the postmaster log.)
1507 * We also suppress messages generated while pqcomm.c is busy. This
1508 * avoids any possibility of messages being inserted within other
1509 * messages. The only known trouble case arises if SIGQUIT occurs
1510 * during a pqcomm.c routine --- quickdie() will try to send a warning
1511 * message, and the most reasonable approach seems to be to drop it.
1513 * returns 0 if OK, EOF if trouble
1514 * --------------------------------
1517 socket_putmessage(char msgtype, const char *s, size_t len)
1519 if (DoingCopyOut || PqCommBusy)
1523 if (internal_putbytes(&msgtype, 1))
1525 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
1529 n32 = htonl((uint32) (len + 4));
1530 if (internal_putbytes((char *) &n32, 4))
1533 if (internal_putbytes(s, len))
1543 /* --------------------------------
1544 * pq_putmessage_noblock - like pq_putmessage, but never blocks
1546 * If the output buffer is too small to hold the message, the buffer
1550 socket_putmessage_noblock(char msgtype, const char *s, size_t len)
1552 int res PG_USED_FOR_ASSERTS_ONLY;
1556 * Ensure we have enough space in the output buffer for the message header
1557 * as well as the message itself.
1559 required = PqSendPointer + 1 + 4 + len;
1560 if (required > PqSendBufferSize)
1562 PqSendBuffer = repalloc(PqSendBuffer, required);
1563 PqSendBufferSize = required;
1565 res = pq_putmessage(msgtype, s, len);
1566 Assert(res == 0); /* should not fail when the message fits in
1571 /* --------------------------------
1572 * socket_startcopyout - inform libpq that an old-style COPY OUT transfer
1574 * --------------------------------
1577 socket_startcopyout(void)
1579 DoingCopyOut = true;
1582 /* --------------------------------
1583 * socket_endcopyout - end an old-style COPY OUT transfer
1585 * If errorAbort is indicated, we are aborting a COPY OUT due to an error,
1586 * and must send a terminator line. Since a partial data line might have
1587 * been emitted, send a couple of newlines first (the first one could
1588 * get absorbed by a backslash...) Note that old-style COPY OUT does
1589 * not allow binary transfers, so a textual terminator is always correct.
1590 * --------------------------------
1593 socket_endcopyout(bool errorAbort)
1598 pq_putbytes("\n\n\\.\n", 5);
1599 /* in non-error case, copy.c will have emitted the terminator line */
1600 DoingCopyOut = false;
1604 * Support for TCP Keepalive parameters
1608 * On Windows, we need to set both idle and interval at the same time.
1609 * We also cannot reset them to the default (setting to zero will
1610 * actually set them to zero, not default), therefore we fallback to
1611 * the out-of-the-box default instead.
1613 #if defined(WIN32) && defined(SIO_KEEPALIVE_VALS)
1615 pq_setkeepaliveswin32(Port *port, int idle, int interval)
1617 struct tcp_keepalive ka;
1621 idle = 2 * 60 * 60; /* default = 2 hours */
1623 interval = 1; /* default = 1 second */
1626 ka.keepalivetime = idle * 1000;
1627 ka.keepaliveinterval = interval * 1000;
1629 if (WSAIoctl(port->sock,
1640 elog(LOG, "WSAIoctl(SIO_KEEPALIVE_VALS) failed: %ui",
1642 return STATUS_ERROR;
1644 if (port->keepalives_idle != idle)
1645 port->keepalives_idle = idle;
1646 if (port->keepalives_interval != interval)
1647 port->keepalives_interval = interval;
1653 pq_getkeepalivesidle(Port *port)
1655 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPALIVE) || defined(WIN32)
1656 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1659 if (port->keepalives_idle != 0)
1660 return port->keepalives_idle;
1662 if (port->default_keepalives_idle == 0)
1665 ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_idle);
1668 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPIDLE,
1669 (char *) &port->default_keepalives_idle,
1672 elog(LOG, "getsockopt(TCP_KEEPIDLE) failed: %m");
1673 port->default_keepalives_idle = -1; /* don't know */
1676 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPALIVE,
1677 (char *) &port->default_keepalives_idle,
1680 elog(LOG, "getsockopt(TCP_KEEPALIVE) failed: %m");
1681 port->default_keepalives_idle = -1; /* don't know */
1683 #endif /* TCP_KEEPIDLE */
1685 /* We can't get the defaults on Windows, so return "don't know" */
1686 port->default_keepalives_idle = -1;
1690 return port->default_keepalives_idle;
1697 pq_setkeepalivesidle(int idle, Port *port)
1699 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1702 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPALIVE) || defined(SIO_KEEPALIVE_VALS)
1703 if (idle == port->keepalives_idle)
1707 if (port->default_keepalives_idle <= 0)
1709 if (pq_getkeepalivesidle(port) < 0)
1712 return STATUS_OK; /* default is set but unknown */
1714 return STATUS_ERROR;
1719 idle = port->default_keepalives_idle;
1722 if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPIDLE,
1723 (char *) &idle, sizeof(idle)) < 0)
1725 elog(LOG, "setsockopt(TCP_KEEPIDLE) failed: %m");
1726 return STATUS_ERROR;
1729 if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPALIVE,
1730 (char *) &idle, sizeof(idle)) < 0)
1732 elog(LOG, "setsockopt(TCP_KEEPALIVE) failed: %m");
1733 return STATUS_ERROR;
1737 port->keepalives_idle = idle;
1739 return pq_setkeepaliveswin32(port, idle, port->keepalives_interval);
1741 #else /* TCP_KEEPIDLE || SIO_KEEPALIVE_VALS */
1744 elog(LOG, "setting the keepalive idle time is not supported");
1745 return STATUS_ERROR;
1752 pq_getkeepalivesinterval(Port *port)
1754 #if defined(TCP_KEEPINTVL) || defined(SIO_KEEPALIVE_VALS)
1755 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1758 if (port->keepalives_interval != 0)
1759 return port->keepalives_interval;
1761 if (port->default_keepalives_interval == 0)
1764 ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_interval);
1766 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1767 (char *) &port->default_keepalives_interval,
1770 elog(LOG, "getsockopt(TCP_KEEPINTVL) failed: %m");
1771 port->default_keepalives_interval = -1; /* don't know */
1774 /* We can't get the defaults on Windows, so return "don't know" */
1775 port->default_keepalives_interval = -1;
1779 return port->default_keepalives_interval;
1786 pq_setkeepalivesinterval(int interval, Port *port)
1788 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1791 #if defined(TCP_KEEPINTVL) || defined (SIO_KEEPALIVE_VALS)
1792 if (interval == port->keepalives_interval)
1796 if (port->default_keepalives_interval <= 0)
1798 if (pq_getkeepalivesinterval(port) < 0)
1801 return STATUS_OK; /* default is set but unknown */
1803 return STATUS_ERROR;
1808 interval = port->default_keepalives_interval;
1810 if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1811 (char *) &interval, sizeof(interval)) < 0)
1813 elog(LOG, "setsockopt(TCP_KEEPINTVL) failed: %m");
1814 return STATUS_ERROR;
1817 port->keepalives_interval = interval;
1819 return pq_setkeepaliveswin32(port, port->keepalives_idle, interval);
1824 elog(LOG, "setsockopt(TCP_KEEPINTVL) not supported");
1825 return STATUS_ERROR;
1833 pq_getkeepalivescount(Port *port)
1836 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1839 if (port->keepalives_count != 0)
1840 return port->keepalives_count;
1842 if (port->default_keepalives_count == 0)
1844 ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_count);
1846 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
1847 (char *) &port->default_keepalives_count,
1850 elog(LOG, "getsockopt(TCP_KEEPCNT) failed: %m");
1851 port->default_keepalives_count = -1; /* don't know */
1855 return port->default_keepalives_count;
1862 pq_setkeepalivescount(int count, Port *port)
1864 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1868 if (count == port->keepalives_count)
1871 if (port->default_keepalives_count <= 0)
1873 if (pq_getkeepalivescount(port) < 0)
1876 return STATUS_OK; /* default is set but unknown */
1878 return STATUS_ERROR;
1883 count = port->default_keepalives_count;
1885 if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
1886 (char *) &count, sizeof(count)) < 0)
1888 elog(LOG, "setsockopt(TCP_KEEPCNT) failed: %m");
1889 return STATUS_ERROR;
1892 port->keepalives_count = count;
1896 elog(LOG, "setsockopt(TCP_KEEPCNT) not supported");
1897 return STATUS_ERROR;