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-2013, 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;
106 /* Where the Unix socket files are (list of palloc'd strings) */
107 static List *sock_paths = NIL;
111 * Buffers for low-level I/O.
113 * The receive buffer is fixed size. Send buffer is usually 8k, but can be
114 * enlarged by pq_putmessage_noblock() if the message doesn't fit otherwise.
117 #define PQ_SEND_BUFFER_SIZE 8192
118 #define PQ_RECV_BUFFER_SIZE 8192
120 static char *PqSendBuffer;
121 static int PqSendBufferSize; /* Size send buffer */
122 static int PqSendPointer; /* Next index to store a byte in PqSendBuffer */
123 static int PqSendStart; /* Next index to send a byte in PqSendBuffer */
125 static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE];
126 static int PqRecvPointer; /* Next index to read a byte from PqRecvBuffer */
127 static int PqRecvLength; /* End of data available in PqRecvBuffer */
132 static bool PqCommBusy;
133 static bool DoingCopyOut;
136 /* Internal functions */
137 static void pq_close(int code, Datum arg);
138 static int internal_putbytes(const char *s, size_t len);
139 static int internal_flush(void);
140 static void pq_set_nonblocking(bool nonblocking);
142 #ifdef HAVE_UNIX_SOCKETS
143 static int Lock_AF_UNIX(char *unixSocketDir, char *unixSocketPath);
144 static int Setup_AF_UNIX(char *sock_path);
145 #endif /* HAVE_UNIX_SOCKETS */
148 /* --------------------------------
149 * pq_init - initialize libpq at backend startup
150 * --------------------------------
155 PqSendBufferSize = PQ_SEND_BUFFER_SIZE;
156 PqSendBuffer = MemoryContextAlloc(TopMemoryContext, PqSendBufferSize);
157 PqSendPointer = PqSendStart = PqRecvPointer = PqRecvLength = 0;
159 DoingCopyOut = false;
160 on_proc_exit(pq_close, 0);
163 /* --------------------------------
164 * pq_comm_reset - reset libpq during error recovery
166 * This is called from error recovery at the outer idle loop. It's
167 * just to get us out of trouble if we somehow manage to elog() from
168 * inside a pqcomm.c routine (which ideally will never happen, but...)
169 * --------------------------------
174 /* Do not throw away pending data, but do reset the busy flag */
176 /* We can abort any old-style COPY OUT, too */
180 /* --------------------------------
181 * pq_close - shutdown libpq at backend exit
183 * Note: in a standalone backend MyProcPort will be null,
184 * don't crash during exit...
185 * --------------------------------
188 pq_close(int code, Datum arg)
190 if (MyProcPort != NULL)
192 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
196 /* Shutdown GSSAPI layer */
197 if (MyProcPort->gss->ctx != GSS_C_NO_CONTEXT)
198 gss_delete_sec_context(&min_s, &MyProcPort->gss->ctx, NULL);
200 if (MyProcPort->gss->cred != GSS_C_NO_CREDENTIAL)
201 gss_release_cred(&min_s, &MyProcPort->gss->cred);
202 #endif /* ENABLE_GSS */
203 /* GSS and SSPI share the port->gss struct */
205 free(MyProcPort->gss);
206 #endif /* ENABLE_GSS || ENABLE_SSPI */
208 /* Cleanly shut down SSL layer */
209 secure_close(MyProcPort);
212 * Formerly we did an explicit close() here, but it seems better to
213 * leave the socket open until the process dies. This allows clients
214 * to perform a "synchronous close" if they care --- wait till the
215 * transport layer reports connection closure, and you can be sure the
216 * backend has exited.
218 * We do set sock to PGINVALID_SOCKET to prevent any further I/O,
221 MyProcPort->sock = PGINVALID_SOCKET;
228 * Streams -- wrapper around Unix socket system calls
231 * Stream functions are used for vanilla TCP connection protocol.
236 * Shutdown routine for backend connection
237 * If any Unix sockets are used for communication, explicitly close them.
239 #ifdef HAVE_UNIX_SOCKETS
241 StreamDoUnlink(int code, Datum arg)
245 /* Loop through all created sockets... */
246 foreach(l, sock_paths)
248 char *sock_path = (char *) lfirst(l);
252 /* Since we're about to exit, no need to reclaim storage */
255 #endif /* HAVE_UNIX_SOCKETS */
258 * StreamServerPort -- open a "listening" port to accept connections.
260 * family should be AF_UNIX or AF_UNSPEC; portNumber is the port number.
261 * For AF_UNIX ports, hostName should be NULL and unixSocketDir must be
262 * specified. For TCP ports, hostName is either NULL for all interfaces or
263 * the interface to listen on, and unixSocketDir is ignored (can be NULL).
265 * Successfully opened sockets are added to the ListenSocket[] array (of
266 * length MaxListen), at the first position that isn't PGINVALID_SOCKET.
268 * RETURNS: STATUS_OK or STATUS_ERROR
272 StreamServerPort(int family, char *hostName, unsigned short portNumber,
274 pgsocket ListenSocket[], int MaxListen)
280 char portNumberStr[32];
281 const char *familyDesc;
282 char familyDescBuf[64];
284 struct addrinfo *addrs = NULL,
286 struct addrinfo hint;
287 int listen_index = 0;
290 #ifdef HAVE_UNIX_SOCKETS
291 char unixSocketPath[MAXPGPATH];
293 #if !defined(WIN32) || defined(IPV6_V6ONLY)
297 /* Initialize hint structure */
298 MemSet(&hint, 0, sizeof(hint));
299 hint.ai_family = family;
300 hint.ai_flags = AI_PASSIVE;
301 hint.ai_socktype = SOCK_STREAM;
303 #ifdef HAVE_UNIX_SOCKETS
304 if (family == AF_UNIX)
307 * Create unixSocketPath from portNumber and unixSocketDir and lock
310 UNIXSOCK_PATH(unixSocketPath, portNumber, unixSocketDir);
311 if (strlen(unixSocketPath) >= UNIXSOCK_PATH_BUFLEN)
314 (errmsg("Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
316 (int) (UNIXSOCK_PATH_BUFLEN - 1))));
319 if (Lock_AF_UNIX(unixSocketDir, unixSocketPath) != STATUS_OK)
321 service = unixSocketPath;
324 #endif /* HAVE_UNIX_SOCKETS */
326 snprintf(portNumberStr, sizeof(portNumberStr), "%d", portNumber);
327 service = portNumberStr;
330 ret = pg_getaddrinfo_all(hostName, service, &hint, &addrs);
335 (errmsg("could not translate host name \"%s\", service \"%s\" to address: %s",
336 hostName, service, gai_strerror(ret))));
339 (errmsg("could not translate service \"%s\" to address: %s",
340 service, gai_strerror(ret))));
342 pg_freeaddrinfo_all(hint.ai_family, addrs);
346 for (addr = addrs; addr; addr = addr->ai_next)
348 if (!IS_AF_UNIX(family) && IS_AF_UNIX(addr->ai_family))
351 * Only set up a unix domain socket when they really asked for it.
352 * The service/port is different in that case.
357 /* See if there is still room to add 1 more socket. */
358 for (; listen_index < MaxListen; listen_index++)
360 if (ListenSocket[listen_index] == PGINVALID_SOCKET)
363 if (listen_index >= MaxListen)
366 (errmsg("could not bind to all requested addresses: MAXLISTEN (%d) exceeded",
371 /* set up family name for possible error messages */
372 switch (addr->ai_family)
375 familyDesc = _("IPv4");
379 familyDesc = _("IPv6");
382 #ifdef HAVE_UNIX_SOCKETS
384 familyDesc = _("Unix");
388 snprintf(familyDescBuf, sizeof(familyDescBuf),
389 _("unrecognized address family %d"),
391 familyDesc = familyDescBuf;
395 if ((fd = socket(addr->ai_family, SOCK_STREAM, 0)) < 0)
398 (errcode_for_socket_access(),
399 /* translator: %s is IPv4, IPv6, or Unix */
400 errmsg("could not create %s socket: %m",
408 * Without the SO_REUSEADDR flag, a new postmaster can't be started
409 * right away after a stop or crash, giving "address already in use"
410 * error on TCP ports.
412 * On win32, however, this behavior only happens if the
413 * SO_EXLUSIVEADDRUSE is set. With SO_REUSEADDR, win32 allows multiple
414 * servers to listen on the same address, resulting in unpredictable
415 * behavior. With no flags at all, win32 behaves as Unix with
418 if (!IS_AF_UNIX(addr->ai_family))
420 if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
421 (char *) &one, sizeof(one))) == -1)
424 (errcode_for_socket_access(),
425 errmsg("setsockopt(SO_REUSEADDR) failed: %m")));
433 if (addr->ai_family == AF_INET6)
435 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
436 (char *) &one, sizeof(one)) == -1)
439 (errcode_for_socket_access(),
440 errmsg("setsockopt(IPV6_V6ONLY) failed: %m")));
448 * Note: This might fail on some OS's, like Linux older than
449 * 2.4.21-pre3, that don't have the IPV6_V6ONLY socket option, and map
450 * ipv4 addresses to ipv6. It will show ::ffff:ipv4 for all ipv4
453 err = bind(fd, addr->ai_addr, addr->ai_addrlen);
457 (errcode_for_socket_access(),
458 /* translator: %s is IPv4, IPv6, or Unix */
459 errmsg("could not bind %s socket: %m",
461 (IS_AF_UNIX(addr->ai_family)) ?
462 errhint("Is another postmaster already running on port %d?"
463 " If not, remove socket file \"%s\" and retry.",
464 (int) portNumber, service) :
465 errhint("Is another postmaster already running on port %d?"
466 " If not, wait a few seconds and retry.",
472 #ifdef HAVE_UNIX_SOCKETS
473 if (addr->ai_family == AF_UNIX)
475 if (Setup_AF_UNIX(service) != STATUS_OK)
484 * Select appropriate accept-queue length limit. PG_SOMAXCONN is only
485 * intended to provide a clamp on the request on platforms where an
486 * overly large request provokes a kernel error (are there any?).
488 maxconn = MaxBackends * 2;
489 if (maxconn > PG_SOMAXCONN)
490 maxconn = PG_SOMAXCONN;
492 err = listen(fd, maxconn);
496 (errcode_for_socket_access(),
497 /* translator: %s is IPv4, IPv6, or Unix */
498 errmsg("could not listen on %s socket: %m",
503 ListenSocket[listen_index] = fd;
507 pg_freeaddrinfo_all(hint.ai_family, addrs);
516 #ifdef HAVE_UNIX_SOCKETS
519 * Lock_AF_UNIX -- configure unix socket file path
522 Lock_AF_UNIX(char *unixSocketDir, char *unixSocketPath)
525 * Grab an interlock file associated with the socket file.
527 * Note: there are two reasons for using a socket lock file, rather than
528 * trying to interlock directly on the socket itself. First, it's a lot
529 * more portable, and second, it lets us remove any pre-existing socket
530 * file without race conditions.
532 CreateSocketLockFile(unixSocketPath, true, unixSocketDir);
535 * Once we have the interlock, we can safely delete any pre-existing
536 * socket file to avoid failure at bind() time.
538 unlink(unixSocketPath);
541 * Arrange to unlink the socket file(s) at proc_exit. If this is the
542 * first one, set up the on_proc_exit function to do it; then add this
543 * socket file to the list of files to unlink.
545 if (sock_paths == NIL)
546 on_proc_exit(StreamDoUnlink, 0);
548 sock_paths = lappend(sock_paths, pstrdup(unixSocketPath));
555 * Setup_AF_UNIX -- configure unix socket permissions
558 Setup_AF_UNIX(char *sock_path)
561 * Fix socket ownership/permission if requested. Note we must do this
562 * before we listen() to avoid a window where unwanted connections could
565 Assert(Unix_socket_group);
566 if (Unix_socket_group[0] != '\0')
569 elog(WARNING, "configuration item unix_socket_group is not supported on this platform");
575 val = strtoul(Unix_socket_group, &endptr, 10);
577 { /* numeric group id */
581 { /* convert group name to id */
584 gr = getgrnam(Unix_socket_group);
588 (errmsg("group \"%s\" does not exist",
589 Unix_socket_group)));
594 if (chown(sock_path, -1, gid) == -1)
597 (errcode_for_file_access(),
598 errmsg("could not set group of file \"%s\": %m",
605 if (chmod(sock_path, Unix_socket_permissions) == -1)
608 (errcode_for_file_access(),
609 errmsg("could not set permissions of file \"%s\": %m",
615 #endif /* HAVE_UNIX_SOCKETS */
619 * StreamConnection -- create a new connection with client using
620 * server port. Set port->sock to the FD of the new connection.
622 * ASSUME: that this doesn't need to be non-blocking because
623 * the Postmaster uses select() to tell when the server master
624 * socket is ready for accept().
626 * RETURNS: STATUS_OK or STATUS_ERROR
629 StreamConnection(pgsocket server_fd, Port *port)
631 /* accept connection and fill in the client (remote) address */
632 port->raddr.salen = sizeof(port->raddr.addr);
633 if ((port->sock = accept(server_fd,
634 (struct sockaddr *) & port->raddr.addr,
635 &port->raddr.salen)) < 0)
638 (errcode_for_socket_access(),
639 errmsg("could not accept new connection: %m")));
642 * If accept() fails then postmaster.c will still see the server
643 * socket as read-ready, and will immediately try again. To avoid
644 * uselessly sucking lots of CPU, delay a bit before trying again.
645 * (The most likely reason for failure is being out of kernel file
646 * table slots; we can do little except hope some will get freed up.)
648 pg_usleep(100000L); /* wait 0.1 sec */
652 #ifdef SCO_ACCEPT_BUG
655 * UnixWare 7+ and OpenServer 5.0.4 are known to have this bug, but it
656 * shouldn't hurt to catch it for all versions of those platforms.
658 if (port->raddr.addr.ss_family == 0)
659 port->raddr.addr.ss_family = AF_UNIX;
662 /* fill in the server (local) address */
663 port->laddr.salen = sizeof(port->laddr.addr);
664 if (getsockname(port->sock,
665 (struct sockaddr *) & port->laddr.addr,
666 &port->laddr.salen) < 0)
668 elog(LOG, "getsockname() failed: %m");
672 /* select NODELAY and KEEPALIVE options if it's a TCP connection */
673 if (!IS_AF_UNIX(port->laddr.addr.ss_family))
679 if (setsockopt(port->sock, IPPROTO_TCP, TCP_NODELAY,
680 (char *) &on, sizeof(on)) < 0)
682 elog(LOG, "setsockopt(TCP_NODELAY) failed: %m");
687 if (setsockopt(port->sock, SOL_SOCKET, SO_KEEPALIVE,
688 (char *) &on, sizeof(on)) < 0)
690 elog(LOG, "setsockopt(SO_KEEPALIVE) failed: %m");
697 * This is a Win32 socket optimization. The ideal size is 32k.
698 * http://support.microsoft.com/kb/823764/EN-US/
700 on = PQ_SEND_BUFFER_SIZE * 4;
701 if (setsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &on,
704 elog(LOG, "setsockopt(SO_SNDBUF) failed: %m");
710 * Also apply the current keepalive parameters. If we fail to set a
711 * parameter, don't error out, because these aren't universally
712 * supported. (Note: you might think we need to reset the GUC
713 * variables to 0 in such a case, but it's not necessary because the
714 * show hooks for these variables report the truth anyway.)
716 (void) pq_setkeepalivesidle(tcp_keepalives_idle, port);
717 (void) pq_setkeepalivesinterval(tcp_keepalives_interval, port);
718 (void) pq_setkeepalivescount(tcp_keepalives_count, port);
725 * StreamClose -- close a client/backend connection
727 * NOTE: this is NOT used to terminate a session; it is just used to release
728 * the file descriptor in a process that should no longer have the socket
729 * open. (For example, the postmaster calls this after passing ownership
730 * of the connection to a child process.) It is expected that someone else
731 * still has the socket open. So, we only want to close the descriptor,
732 * we do NOT want to send anything to the far end.
735 StreamClose(pgsocket sock)
741 * TouchSocketFiles -- mark socket files as recently accessed
743 * This routine should be called every so often to ensure that the socket
744 * files have a recent mod date (ordinary operations on sockets usually won't
745 * change the mod date). That saves them from being removed by
746 * overenthusiastic /tmp-directory-cleaner daemons. (Another reason we should
747 * never have put the socket file in /tmp...)
750 TouchSocketFiles(void)
754 /* Loop through all created sockets... */
755 foreach(l, sock_paths)
757 char *sock_path = (char *) lfirst(l);
760 * utime() is POSIX standard, utimes() is a common alternative. If we
761 * have neither, there's no way to affect the mod or access time of
764 * In either path, we ignore errors; there's no point in complaining.
767 utime(sock_path, NULL);
768 #else /* !HAVE_UTIME */
770 utimes(sock_path, NULL);
771 #endif /* HAVE_UTIMES */
772 #endif /* HAVE_UTIME */
777 /* --------------------------------
778 * Low-level I/O routines begin here.
780 * These routines communicate with a frontend client across a connection
781 * already established by the preceding routines.
782 * --------------------------------
785 /* --------------------------------
786 * pq_set_nonblocking - set socket blocking/non-blocking
788 * Sets the socket non-blocking if nonblocking is TRUE, or sets it
789 * blocking otherwise.
790 * --------------------------------
793 pq_set_nonblocking(bool nonblocking)
795 if (MyProcPort->noblock == nonblocking)
799 pgwin32_noblock = nonblocking ? 1 : 0;
803 * Use COMMERROR on failure, because ERROR would try to send the error to
804 * the client, which might require changing the mode again, leading to
805 * infinite recursion.
809 if (!pg_set_noblock(MyProcPort->sock))
811 (errmsg("could not set socket to nonblocking mode: %m")));
815 if (!pg_set_block(MyProcPort->sock))
817 (errmsg("could not set socket to blocking mode: %m")));
820 MyProcPort->noblock = nonblocking;
823 /* --------------------------------
824 * pq_recvbuf - load some bytes into the input buffer
826 * returns 0 if OK, EOF if trouble
827 * --------------------------------
832 if (PqRecvPointer > 0)
834 if (PqRecvLength > PqRecvPointer)
836 /* still some unread data, left-justify it in the buffer */
837 memmove(PqRecvBuffer, PqRecvBuffer + PqRecvPointer,
838 PqRecvLength - PqRecvPointer);
839 PqRecvLength -= PqRecvPointer;
843 PqRecvLength = PqRecvPointer = 0;
846 /* Ensure that we're in blocking mode */
847 pq_set_nonblocking(false);
849 /* Can fill buffer from PqRecvLength and upwards */
854 r = secure_read(MyProcPort, PqRecvBuffer + PqRecvLength,
855 PQ_RECV_BUFFER_SIZE - PqRecvLength);
860 continue; /* Ok if interrupted */
863 * Careful: an ereport() that tries to write to the client would
864 * cause recursion to here, leading to stack overflow and core
865 * dump! This message must go *only* to the postmaster log.
868 (errcode_for_socket_access(),
869 errmsg("could not receive data from client: %m")));
875 * EOF detected. We used to write a log message here, but it's
876 * better to expect the ultimate caller to do that.
880 /* r contains number of bytes read, so just incr length */
886 /* --------------------------------
887 * pq_getbyte - get a single byte from connection, or return EOF
888 * --------------------------------
893 while (PqRecvPointer >= PqRecvLength)
895 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
896 return EOF; /* Failed to recv data */
898 return (unsigned char) PqRecvBuffer[PqRecvPointer++];
901 /* --------------------------------
902 * pq_peekbyte - peek at next byte from connection
904 * Same as pq_getbyte() except we don't advance the pointer.
905 * --------------------------------
910 while (PqRecvPointer >= PqRecvLength)
912 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
913 return EOF; /* Failed to recv data */
915 return (unsigned char) PqRecvBuffer[PqRecvPointer];
918 /* --------------------------------
919 * pq_getbyte_if_available - get a single byte from connection,
922 * The received byte is stored in *c. Returns 1 if a byte was read,
923 * 0 if no data was available, or EOF if trouble.
924 * --------------------------------
927 pq_getbyte_if_available(unsigned char *c)
931 if (PqRecvPointer < PqRecvLength)
933 *c = PqRecvBuffer[PqRecvPointer++];
937 /* Put the socket into non-blocking mode */
938 pq_set_nonblocking(true);
940 r = secure_read(MyProcPort, c, 1);
944 * Ok if no data available without blocking or interrupted (though
945 * EINTR really shouldn't happen with a non-blocking socket). Report
948 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
953 * Careful: an ereport() that tries to write to the client would
954 * cause recursion to here, leading to stack overflow and core
955 * dump! This message must go *only* to the postmaster log.
958 (errcode_for_socket_access(),
959 errmsg("could not receive data from client: %m")));
972 /* --------------------------------
973 * pq_getbytes - get a known number of bytes from connection
975 * returns 0 if OK, EOF if trouble
976 * --------------------------------
979 pq_getbytes(char *s, size_t len)
985 while (PqRecvPointer >= PqRecvLength)
987 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
988 return EOF; /* Failed to recv data */
990 amount = PqRecvLength - PqRecvPointer;
993 memcpy(s, PqRecvBuffer + PqRecvPointer, amount);
994 PqRecvPointer += amount;
1001 /* --------------------------------
1002 * pq_discardbytes - throw away a known number of bytes
1004 * same as pq_getbytes except we do not copy the data to anyplace.
1005 * this is used for resynchronizing after read errors.
1007 * returns 0 if OK, EOF if trouble
1008 * --------------------------------
1011 pq_discardbytes(size_t len)
1017 while (PqRecvPointer >= PqRecvLength)
1019 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1020 return EOF; /* Failed to recv data */
1022 amount = PqRecvLength - PqRecvPointer;
1025 PqRecvPointer += amount;
1031 /* --------------------------------
1032 * pq_getstring - get a null terminated string from connection
1034 * The return value is placed in an expansible StringInfo, which has
1035 * already been initialized by the caller.
1037 * This is used only for dealing with old-protocol clients. The idea
1038 * is to produce a StringInfo that looks the same as we would get from
1039 * pq_getmessage() with a newer client; we will then process it with
1040 * pq_getmsgstring. Therefore, no character set conversion is done here,
1041 * even though this is presumably useful only for text.
1043 * returns 0 if OK, EOF if trouble
1044 * --------------------------------
1047 pq_getstring(StringInfo s)
1053 /* Read until we get the terminating '\0' */
1056 while (PqRecvPointer >= PqRecvLength)
1058 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1059 return EOF; /* Failed to recv data */
1062 for (i = PqRecvPointer; i < PqRecvLength; i++)
1064 if (PqRecvBuffer[i] == '\0')
1066 /* include the '\0' in the copy */
1067 appendBinaryStringInfo(s, PqRecvBuffer + PqRecvPointer,
1068 i - PqRecvPointer + 1);
1069 PqRecvPointer = i + 1; /* advance past \0 */
1074 /* If we're here we haven't got the \0 in the buffer yet. */
1075 appendBinaryStringInfo(s, PqRecvBuffer + PqRecvPointer,
1076 PqRecvLength - PqRecvPointer);
1077 PqRecvPointer = PqRecvLength;
1082 /* --------------------------------
1083 * pq_getmessage - get a message with length word from connection
1085 * The return value is placed in an expansible StringInfo, which has
1086 * already been initialized by the caller.
1087 * Only the message body is placed in the StringInfo; the length word
1088 * is removed. Also, s->cursor is initialized to zero for convenience
1089 * in scanning the message contents.
1091 * If maxlen is not zero, it is an upper limit on the length of the
1092 * message we are willing to accept. We abort the connection (by
1093 * returning EOF) if client tries to send more than that.
1095 * returns 0 if OK, EOF if trouble
1096 * --------------------------------
1099 pq_getmessage(StringInfo s, int maxlen)
1105 /* Read message length word */
1106 if (pq_getbytes((char *) &len, 4) == EOF)
1109 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1110 errmsg("unexpected EOF within message length word")));
1117 (maxlen > 0 && len > maxlen))
1120 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1121 errmsg("invalid message length")));
1125 len -= 4; /* discount length itself */
1130 * Allocate space for message. If we run out of room (ridiculously
1131 * large message), we will elog(ERROR), but we want to discard the
1132 * message body so as not to lose communication sync.
1136 enlargeStringInfo(s, len);
1140 if (pq_discardbytes(len) == EOF)
1142 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1143 errmsg("incomplete message from client")));
1148 /* And grab the message */
1149 if (pq_getbytes(s->data, len) == EOF)
1152 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1153 errmsg("incomplete message from client")));
1157 /* Place a trailing null per StringInfo convention */
1158 s->data[len] = '\0';
1165 /* --------------------------------
1166 * pq_putbytes - send bytes to connection (not flushed until pq_flush)
1168 * returns 0 if OK, EOF if trouble
1169 * --------------------------------
1172 pq_putbytes(const char *s, size_t len)
1176 /* Should only be called by old-style COPY OUT */
1177 Assert(DoingCopyOut);
1178 /* No-op if reentrant call */
1182 res = internal_putbytes(s, len);
1188 internal_putbytes(const char *s, size_t len)
1194 /* If buffer is full, then flush it out */
1195 if (PqSendPointer >= PqSendBufferSize)
1197 pq_set_nonblocking(false);
1198 if (internal_flush())
1201 amount = PqSendBufferSize - PqSendPointer;
1204 memcpy(PqSendBuffer + PqSendPointer, s, amount);
1205 PqSendPointer += amount;
1212 /* --------------------------------
1213 * pq_flush - flush pending output
1215 * returns 0 if OK, EOF if trouble
1216 * --------------------------------
1223 /* No-op if reentrant call */
1227 pq_set_nonblocking(false);
1228 res = internal_flush();
1233 /* --------------------------------
1234 * internal_flush - flush pending output
1236 * Returns 0 if OK (meaning everything was sent, or operation would block
1237 * and the socket is in non-blocking mode), or EOF if trouble.
1238 * --------------------------------
1241 internal_flush(void)
1243 static int last_reported_send_errno = 0;
1245 char *bufptr = PqSendBuffer + PqSendStart;
1246 char *bufend = PqSendBuffer + PqSendPointer;
1248 while (bufptr < bufend)
1252 r = secure_write(MyProcPort, bufptr, bufend - bufptr);
1257 continue; /* Ok if we were interrupted */
1260 * Ok if no data writable without blocking, and the socket is in
1261 * non-blocking mode.
1263 if (errno == EAGAIN ||
1264 errno == EWOULDBLOCK)
1270 * Careful: an ereport() that tries to write to the client would
1271 * cause recursion to here, leading to stack overflow and core
1272 * dump! This message must go *only* to the postmaster log.
1274 * If a client disconnects while we're in the midst of output, we
1275 * might write quite a bit of data before we get to a safe query
1276 * abort point. So, suppress duplicate log messages.
1278 if (errno != last_reported_send_errno)
1280 last_reported_send_errno = errno;
1282 (errcode_for_socket_access(),
1283 errmsg("could not send data to client: %m")));
1287 * We drop the buffered data anyway so that processing can
1288 * continue, even though we'll probably quit soon. We also set a
1289 * flag that'll cause the next CHECK_FOR_INTERRUPTS to terminate
1292 PqSendStart = PqSendPointer = 0;
1293 ClientConnectionLost = 1;
1294 InterruptPending = 1;
1298 last_reported_send_errno = 0; /* reset after any successful send */
1303 PqSendStart = PqSendPointer = 0;
1307 /* --------------------------------
1308 * pq_flush_if_writable - flush pending output if writable without blocking
1310 * Returns 0 if OK, or EOF if trouble.
1311 * --------------------------------
1314 pq_flush_if_writable(void)
1318 /* Quick exit if nothing to do */
1319 if (PqSendPointer == PqSendStart)
1322 /* No-op if reentrant call */
1326 /* Temporarily put the socket into non-blocking mode */
1327 pq_set_nonblocking(true);
1330 res = internal_flush();
1335 /* --------------------------------
1336 * pq_is_send_pending - is there any pending data in the output buffer?
1337 * --------------------------------
1340 pq_is_send_pending(void)
1342 return (PqSendStart < PqSendPointer);
1345 /* --------------------------------
1346 * Message-level I/O routines begin here.
1348 * These routines understand about the old-style COPY OUT protocol.
1349 * --------------------------------
1353 /* --------------------------------
1354 * pq_putmessage - send a normal message (suppressed in COPY OUT mode)
1356 * If msgtype is not '\0', it is a message type code to place before
1357 * the message body. If msgtype is '\0', then the message has no type
1358 * code (this is only valid in pre-3.0 protocols).
1360 * len is the length of the message body data at *s. In protocol 3.0
1361 * and later, a message length word (equal to len+4 because it counts
1362 * itself too) is inserted by this routine.
1364 * All normal messages are suppressed while old-style COPY OUT is in
1365 * progress. (In practice only a few notice messages might get emitted
1366 * then; dropping them is annoying, but at least they will still appear
1367 * in the postmaster log.)
1369 * We also suppress messages generated while pqcomm.c is busy. This
1370 * avoids any possibility of messages being inserted within other
1371 * messages. The only known trouble case arises if SIGQUIT occurs
1372 * during a pqcomm.c routine --- quickdie() will try to send a warning
1373 * message, and the most reasonable approach seems to be to drop it.
1375 * returns 0 if OK, EOF if trouble
1376 * --------------------------------
1379 pq_putmessage(char msgtype, const char *s, size_t len)
1381 if (DoingCopyOut || PqCommBusy)
1385 if (internal_putbytes(&msgtype, 1))
1387 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
1391 n32 = htonl((uint32) (len + 4));
1392 if (internal_putbytes((char *) &n32, 4))
1395 if (internal_putbytes(s, len))
1405 /* --------------------------------
1406 * pq_putmessage_noblock - like pq_putmessage, but never blocks
1408 * If the output buffer is too small to hold the message, the buffer
1412 pq_putmessage_noblock(char msgtype, const char *s, size_t len)
1414 int res PG_USED_FOR_ASSERTS_ONLY;
1418 * Ensure we have enough space in the output buffer for the message header
1419 * as well as the message itself.
1421 required = PqSendPointer + 1 + 4 + len;
1422 if (required > PqSendBufferSize)
1424 PqSendBuffer = repalloc(PqSendBuffer, required);
1425 PqSendBufferSize = required;
1427 res = pq_putmessage(msgtype, s, len);
1428 Assert(res == 0); /* should not fail when the message fits in
1433 /* --------------------------------
1434 * pq_startcopyout - inform libpq that an old-style COPY OUT transfer
1436 * --------------------------------
1439 pq_startcopyout(void)
1441 DoingCopyOut = true;
1444 /* --------------------------------
1445 * pq_endcopyout - end an old-style COPY OUT transfer
1447 * If errorAbort is indicated, we are aborting a COPY OUT due to an error,
1448 * and must send a terminator line. Since a partial data line might have
1449 * been emitted, send a couple of newlines first (the first one could
1450 * get absorbed by a backslash...) Note that old-style COPY OUT does
1451 * not allow binary transfers, so a textual terminator is always correct.
1452 * --------------------------------
1455 pq_endcopyout(bool errorAbort)
1460 pq_putbytes("\n\n\\.\n", 5);
1461 /* in non-error case, copy.c will have emitted the terminator line */
1462 DoingCopyOut = false;
1467 * Support for TCP Keepalive parameters
1471 * On Windows, we need to set both idle and interval at the same time.
1472 * We also cannot reset them to the default (setting to zero will
1473 * actually set them to zero, not default), therefor we fallback to
1474 * the out-of-the-box default instead.
1476 #if defined(WIN32) && defined(SIO_KEEPALIVE_VALS)
1478 pq_setkeepaliveswin32(Port *port, int idle, int interval)
1480 struct tcp_keepalive ka;
1484 idle = 2 * 60 * 60; /* default = 2 hours */
1486 interval = 1; /* default = 1 second */
1489 ka.keepalivetime = idle * 1000;
1490 ka.keepaliveinterval = interval * 1000;
1492 if (WSAIoctl(port->sock,
1503 elog(LOG, "WSAIoctl(SIO_KEEPALIVE_VALS) failed: %ui",
1505 return STATUS_ERROR;
1507 if (port->keepalives_idle != idle)
1508 port->keepalives_idle = idle;
1509 if (port->keepalives_interval != interval)
1510 port->keepalives_interval = interval;
1516 pq_getkeepalivesidle(Port *port)
1518 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPALIVE) || defined(WIN32)
1519 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1522 if (port->keepalives_idle != 0)
1523 return port->keepalives_idle;
1525 if (port->default_keepalives_idle == 0)
1528 ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_idle);
1531 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPIDLE,
1532 (char *) &port->default_keepalives_idle,
1535 elog(LOG, "getsockopt(TCP_KEEPIDLE) failed: %m");
1536 port->default_keepalives_idle = -1; /* don't know */
1539 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPALIVE,
1540 (char *) &port->default_keepalives_idle,
1543 elog(LOG, "getsockopt(TCP_KEEPALIVE) failed: %m");
1544 port->default_keepalives_idle = -1; /* don't know */
1546 #endif /* TCP_KEEPIDLE */
1548 /* We can't get the defaults on Windows, so return "don't know" */
1549 port->default_keepalives_idle = -1;
1553 return port->default_keepalives_idle;
1560 pq_setkeepalivesidle(int idle, Port *port)
1562 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1565 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPALIVE) || defined(SIO_KEEPALIVE_VALS)
1566 if (idle == port->keepalives_idle)
1570 if (port->default_keepalives_idle <= 0)
1572 if (pq_getkeepalivesidle(port) < 0)
1575 return STATUS_OK; /* default is set but unknown */
1577 return STATUS_ERROR;
1582 idle = port->default_keepalives_idle;
1585 if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPIDLE,
1586 (char *) &idle, sizeof(idle)) < 0)
1588 elog(LOG, "setsockopt(TCP_KEEPIDLE) failed: %m");
1589 return STATUS_ERROR;
1592 if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPALIVE,
1593 (char *) &idle, sizeof(idle)) < 0)
1595 elog(LOG, "setsockopt(TCP_KEEPALIVE) failed: %m");
1596 return STATUS_ERROR;
1600 port->keepalives_idle = idle;
1602 return pq_setkeepaliveswin32(port, idle, port->keepalives_interval);
1604 #else /* TCP_KEEPIDLE || SIO_KEEPALIVE_VALS */
1607 elog(LOG, "setting the keepalive idle time is not supported");
1608 return STATUS_ERROR;
1615 pq_getkeepalivesinterval(Port *port)
1617 #if defined(TCP_KEEPINTVL) || defined(SIO_KEEPALIVE_VALS)
1618 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1621 if (port->keepalives_interval != 0)
1622 return port->keepalives_interval;
1624 if (port->default_keepalives_interval == 0)
1627 ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_interval);
1629 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1630 (char *) &port->default_keepalives_interval,
1633 elog(LOG, "getsockopt(TCP_KEEPINTVL) failed: %m");
1634 port->default_keepalives_interval = -1; /* don't know */
1637 /* We can't get the defaults on Windows, so return "don't know" */
1638 port->default_keepalives_interval = -1;
1642 return port->default_keepalives_interval;
1649 pq_setkeepalivesinterval(int interval, Port *port)
1651 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1654 #if defined(TCP_KEEPINTVL) || defined (SIO_KEEPALIVE_VALS)
1655 if (interval == port->keepalives_interval)
1659 if (port->default_keepalives_interval <= 0)
1661 if (pq_getkeepalivesinterval(port) < 0)
1664 return STATUS_OK; /* default is set but unknown */
1666 return STATUS_ERROR;
1671 interval = port->default_keepalives_interval;
1673 if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1674 (char *) &interval, sizeof(interval)) < 0)
1676 elog(LOG, "setsockopt(TCP_KEEPINTVL) failed: %m");
1677 return STATUS_ERROR;
1680 port->keepalives_interval = interval;
1682 return pq_setkeepaliveswin32(port, port->keepalives_idle, interval);
1687 elog(LOG, "setsockopt(TCP_KEEPINTVL) not supported");
1688 return STATUS_ERROR;
1696 pq_getkeepalivescount(Port *port)
1699 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1702 if (port->keepalives_count != 0)
1703 return port->keepalives_count;
1705 if (port->default_keepalives_count == 0)
1707 ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_count);
1709 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
1710 (char *) &port->default_keepalives_count,
1713 elog(LOG, "getsockopt(TCP_KEEPCNT) failed: %m");
1714 port->default_keepalives_count = -1; /* don't know */
1718 return port->default_keepalives_count;
1725 pq_setkeepalivescount(int count, Port *port)
1727 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1731 if (count == port->keepalives_count)
1734 if (port->default_keepalives_count <= 0)
1736 if (pq_getkeepalivescount(port) < 0)
1739 return STATUS_OK; /* default is set but unknown */
1741 return STATUS_ERROR;
1746 count = port->default_keepalives_count;
1748 if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
1749 (char *) &count, sizeof(count)) < 0)
1751 elog(LOG, "setsockopt(TCP_KEEPCNT) failed: %m");
1752 return STATUS_ERROR;
1755 port->keepalives_count = count;
1759 elog(LOG, "setsockopt(TCP_KEEPCNT) not supported");
1760 return STATUS_ERROR;