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-2010, PostgreSQL Global Development Group
31 * Portions Copyright (c) 1994, Regents of the University of California
33 * $PostgreSQL: pgsql/src/backend/libpq/pqcomm.c,v 1.202 2010/01/15 09:19:02 heikki Exp $
35 *-------------------------------------------------------------------------
38 /*------------------------
42 * StreamServerPort - Open postmaster's server port
43 * StreamConnection - Create new connection with client
44 * StreamClose - Close a client/backend connection
45 * TouchSocketFile - Protect socket file 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_getbyte_if_available - get a byte if available without blocking
60 * message-level I/O (and old-style-COPY-OUT cruft):
61 * pq_putmessage - send a normal message (suppressed in COPY OUT mode)
62 * pq_startcopyout - inform libpq that a COPY OUT transfer is beginning
63 * pq_endcopyout - end a COPY OUT transfer
65 *------------------------
74 #include <sys/socket.h>
78 #include <netinet/in.h>
79 #ifdef HAVE_NETINET_TCP_H
80 #include <netinet/tcp.h>
82 #include <arpa/inet.h>
88 #include "libpq/libpq.h"
89 #include "miscadmin.h"
90 #include "storage/ipc.h"
91 #include "utils/guc.h"
94 * Configuration options
96 int Unix_socket_permissions;
97 char *Unix_socket_group;
100 /* Where the Unix socket file is */
101 static char sock_path[MAXPGPATH];
105 * Buffers for low-level I/O
108 #define PQ_BUFFER_SIZE 8192
110 static char PqSendBuffer[PQ_BUFFER_SIZE];
111 static int PqSendPointer; /* Next index to store a byte in PqSendBuffer */
113 static char PqRecvBuffer[PQ_BUFFER_SIZE];
114 static int PqRecvPointer; /* Next index to read a byte from PqRecvBuffer */
115 static int PqRecvLength; /* End of data available in PqRecvBuffer */
120 static bool PqCommBusy;
121 static bool DoingCopyOut;
124 /* Internal functions */
125 static void pq_close(int code, Datum arg);
126 static int internal_putbytes(const char *s, size_t len);
127 static int internal_flush(void);
129 #ifdef HAVE_UNIX_SOCKETS
130 static int Lock_AF_UNIX(unsigned short portNumber, char *unixSocketName);
131 static int Setup_AF_UNIX(void);
132 #endif /* HAVE_UNIX_SOCKETS */
135 /* --------------------------------
136 * pq_init - initialize libpq at backend startup
137 * --------------------------------
142 PqSendPointer = PqRecvPointer = PqRecvLength = 0;
144 DoingCopyOut = false;
145 on_proc_exit(pq_close, 0);
148 /* --------------------------------
149 * pq_comm_reset - reset libpq during error recovery
151 * This is called from error recovery at the outer idle loop. It's
152 * just to get us out of trouble if we somehow manage to elog() from
153 * inside a pqcomm.c routine (which ideally will never happen, but...)
154 * --------------------------------
159 /* Do not throw away pending data, but do reset the busy flag */
161 /* We can abort any old-style COPY OUT, too */
165 /* --------------------------------
166 * pq_close - shutdown libpq at backend exit
168 * Note: in a standalone backend MyProcPort will be null,
169 * don't crash during exit...
170 * --------------------------------
173 pq_close(int code, Datum arg)
175 if (MyProcPort != NULL)
177 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
181 /* Shutdown GSSAPI layer */
182 if (MyProcPort->gss->ctx != GSS_C_NO_CONTEXT)
183 gss_delete_sec_context(&min_s, &MyProcPort->gss->ctx, NULL);
185 if (MyProcPort->gss->cred != GSS_C_NO_CREDENTIAL)
186 gss_release_cred(&min_s, &MyProcPort->gss->cred);
187 #endif /* ENABLE_GSS */
188 /* GSS and SSPI share the port->gss struct */
190 free(MyProcPort->gss);
191 #endif /* ENABLE_GSS || ENABLE_SSPI */
193 /* Cleanly shut down SSL layer */
194 secure_close(MyProcPort);
197 * Formerly we did an explicit close() here, but it seems better to
198 * leave the socket open until the process dies. This allows clients
199 * to perform a "synchronous close" if they care --- wait till the
200 * transport layer reports connection closure, and you can be sure the
201 * backend has exited.
203 * We do set sock to PGINVALID_SOCKET to prevent any further I/O, though.
205 MyProcPort->sock = PGINVALID_SOCKET;
212 * Streams -- wrapper around Unix socket system calls
215 * Stream functions are used for vanilla TCP connection protocol.
220 * Shutdown routine for backend connection
221 * If a Unix socket is used for communication, explicitly close it.
223 #ifdef HAVE_UNIX_SOCKETS
225 StreamDoUnlink(int code, Datum arg)
227 Assert(sock_path[0]);
230 #endif /* HAVE_UNIX_SOCKETS */
233 * StreamServerPort -- open a "listening" port to accept connections.
235 * Successfully opened sockets are added to the ListenSocket[] array,
236 * at the first position that isn't PGINVALID_SOCKET.
238 * RETURNS: STATUS_OK or STATUS_ERROR
242 StreamServerPort(int family, char *hostName, unsigned short portNumber,
243 char *unixSocketName,
244 pgsocket ListenSocket[], int MaxListen)
250 char portNumberStr[32];
251 const char *familyDesc;
252 char familyDescBuf[64];
254 struct addrinfo *addrs = NULL,
256 struct addrinfo hint;
257 int listen_index = 0;
260 #if !defined(WIN32) || defined(IPV6_V6ONLY)
264 /* Initialize hint structure */
265 MemSet(&hint, 0, sizeof(hint));
266 hint.ai_family = family;
267 hint.ai_flags = AI_PASSIVE;
268 hint.ai_socktype = SOCK_STREAM;
270 #ifdef HAVE_UNIX_SOCKETS
271 if (family == AF_UNIX)
273 /* Lock_AF_UNIX will also fill in sock_path. */
274 if (Lock_AF_UNIX(portNumber, unixSocketName) != STATUS_OK)
279 #endif /* HAVE_UNIX_SOCKETS */
281 snprintf(portNumberStr, sizeof(portNumberStr), "%d", portNumber);
282 service = portNumberStr;
285 ret = pg_getaddrinfo_all(hostName, service, &hint, &addrs);
290 (errmsg("could not translate host name \"%s\", service \"%s\" to address: %s",
291 hostName, service, gai_strerror(ret))));
294 (errmsg("could not translate service \"%s\" to address: %s",
295 service, gai_strerror(ret))));
297 pg_freeaddrinfo_all(hint.ai_family, addrs);
301 for (addr = addrs; addr; addr = addr->ai_next)
303 if (!IS_AF_UNIX(family) && IS_AF_UNIX(addr->ai_family))
306 * Only set up a unix domain socket when they really asked for it.
307 * The service/port is different in that case.
312 /* See if there is still room to add 1 more socket. */
313 for (; listen_index < MaxListen; listen_index++)
315 if (ListenSocket[listen_index] == PGINVALID_SOCKET)
318 if (listen_index >= MaxListen)
321 (errmsg("could not bind to all requested addresses: MAXLISTEN (%d) exceeded",
326 /* set up family name for possible error messages */
327 switch (addr->ai_family)
330 familyDesc = _("IPv4");
334 familyDesc = _("IPv6");
337 #ifdef HAVE_UNIX_SOCKETS
339 familyDesc = _("Unix");
343 snprintf(familyDescBuf, sizeof(familyDescBuf),
344 _("unrecognized address family %d"),
346 familyDesc = familyDescBuf;
350 if ((fd = socket(addr->ai_family, SOCK_STREAM, 0)) < 0)
353 (errcode_for_socket_access(),
354 /* translator: %s is IPv4, IPv6, or Unix */
355 errmsg("could not create %s socket: %m",
363 * Without the SO_REUSEADDR flag, a new postmaster can't be started
364 * right away after a stop or crash, giving "address already in use"
365 * error on TCP ports.
367 * On win32, however, this behavior only happens if the
368 * SO_EXLUSIVEADDRUSE is set. With SO_REUSEADDR, win32 allows multiple
369 * servers to listen on the same address, resulting in unpredictable
370 * behavior. With no flags at all, win32 behaves as Unix with
373 if (!IS_AF_UNIX(addr->ai_family))
375 if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
376 (char *) &one, sizeof(one))) == -1)
379 (errcode_for_socket_access(),
380 errmsg("setsockopt(SO_REUSEADDR) failed: %m")));
388 if (addr->ai_family == AF_INET6)
390 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
391 (char *) &one, sizeof(one)) == -1)
394 (errcode_for_socket_access(),
395 errmsg("setsockopt(IPV6_V6ONLY) failed: %m")));
403 * Note: This might fail on some OS's, like Linux older than
404 * 2.4.21-pre3, that don't have the IPV6_V6ONLY socket option, and map
405 * ipv4 addresses to ipv6. It will show ::ffff:ipv4 for all ipv4
408 err = bind(fd, addr->ai_addr, addr->ai_addrlen);
412 (errcode_for_socket_access(),
413 /* translator: %s is IPv4, IPv6, or Unix */
414 errmsg("could not bind %s socket: %m",
416 (IS_AF_UNIX(addr->ai_family)) ?
417 errhint("Is another postmaster already running on port %d?"
418 " If not, remove socket file \"%s\" and retry.",
419 (int) portNumber, sock_path) :
420 errhint("Is another postmaster already running on port %d?"
421 " If not, wait a few seconds and retry.",
427 #ifdef HAVE_UNIX_SOCKETS
428 if (addr->ai_family == AF_UNIX)
430 if (Setup_AF_UNIX() != STATUS_OK)
439 * Select appropriate accept-queue length limit. PG_SOMAXCONN is only
440 * intended to provide a clamp on the request on platforms where an
441 * overly large request provokes a kernel error (are there any?).
443 maxconn = MaxBackends * 2;
444 if (maxconn > PG_SOMAXCONN)
445 maxconn = PG_SOMAXCONN;
447 err = listen(fd, maxconn);
451 (errcode_for_socket_access(),
452 /* translator: %s is IPv4, IPv6, or Unix */
453 errmsg("could not listen on %s socket: %m",
458 ListenSocket[listen_index] = fd;
462 pg_freeaddrinfo_all(hint.ai_family, addrs);
471 #ifdef HAVE_UNIX_SOCKETS
474 * Lock_AF_UNIX -- configure unix socket file path
477 Lock_AF_UNIX(unsigned short portNumber, char *unixSocketName)
479 UNIXSOCK_PATH(sock_path, portNumber, unixSocketName);
482 * Grab an interlock file associated with the socket file.
484 CreateSocketLockFile(sock_path, true);
487 * Once we have the interlock, we can safely delete any pre-existing
488 * socket file to avoid failure at bind() time.
497 * Setup_AF_UNIX -- configure unix socket permissions
502 /* Arrange to unlink the socket file at exit */
503 on_proc_exit(StreamDoUnlink, 0);
506 * Fix socket ownership/permission if requested. Note we must do this
507 * before we listen() to avoid a window where unwanted connections could
510 Assert(Unix_socket_group);
511 if (Unix_socket_group[0] != '\0')
514 elog(WARNING, "configuration item unix_socket_group is not supported on this platform");
520 val = strtoul(Unix_socket_group, &endptr, 10);
522 { /* numeric group id */
526 { /* convert group name to id */
529 gr = getgrnam(Unix_socket_group);
533 (errmsg("group \"%s\" does not exist",
534 Unix_socket_group)));
539 if (chown(sock_path, -1, gid) == -1)
542 (errcode_for_file_access(),
543 errmsg("could not set group of file \"%s\": %m",
550 if (chmod(sock_path, Unix_socket_permissions) == -1)
553 (errcode_for_file_access(),
554 errmsg("could not set permissions of file \"%s\": %m",
560 #endif /* HAVE_UNIX_SOCKETS */
564 * StreamConnection -- create a new connection with client using
565 * server port. Set port->sock to the FD of the new connection.
567 * ASSUME: that this doesn't need to be non-blocking because
568 * the Postmaster uses select() to tell when the server master
569 * socket is ready for accept().
571 * RETURNS: STATUS_OK or STATUS_ERROR
574 StreamConnection(pgsocket server_fd, Port *port)
576 /* accept connection and fill in the client (remote) address */
577 port->raddr.salen = sizeof(port->raddr.addr);
578 if ((port->sock = accept(server_fd,
579 (struct sockaddr *) & port->raddr.addr,
580 &port->raddr.salen)) < 0)
583 (errcode_for_socket_access(),
584 errmsg("could not accept new connection: %m")));
587 * If accept() fails then postmaster.c will still see the server
588 * socket as read-ready, and will immediately try again. To avoid
589 * uselessly sucking lots of CPU, delay a bit before trying again.
590 * (The most likely reason for failure is being out of kernel file
591 * table slots; we can do little except hope some will get freed up.)
593 pg_usleep(100000L); /* wait 0.1 sec */
597 #ifdef SCO_ACCEPT_BUG
600 * UnixWare 7+ and OpenServer 5.0.4 are known to have this bug, but it
601 * shouldn't hurt to catch it for all versions of those platforms.
603 if (port->raddr.addr.ss_family == 0)
604 port->raddr.addr.ss_family = AF_UNIX;
607 /* fill in the server (local) address */
608 port->laddr.salen = sizeof(port->laddr.addr);
609 if (getsockname(port->sock,
610 (struct sockaddr *) & port->laddr.addr,
611 &port->laddr.salen) < 0)
613 elog(LOG, "getsockname() failed: %m");
617 /* select NODELAY and KEEPALIVE options if it's a TCP connection */
618 if (!IS_AF_UNIX(port->laddr.addr.ss_family))
624 if (setsockopt(port->sock, IPPROTO_TCP, TCP_NODELAY,
625 (char *) &on, sizeof(on)) < 0)
627 elog(LOG, "setsockopt(TCP_NODELAY) failed: %m");
632 if (setsockopt(port->sock, SOL_SOCKET, SO_KEEPALIVE,
633 (char *) &on, sizeof(on)) < 0)
635 elog(LOG, "setsockopt(SO_KEEPALIVE) failed: %m");
642 * This is a Win32 socket optimization. The ideal size is 32k.
643 * http://support.microsoft.com/kb/823764/EN-US/
645 on = PQ_BUFFER_SIZE * 4;
646 if (setsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &on,
649 elog(LOG, "setsockopt(SO_SNDBUF) failed: %m");
655 * Also apply the current keepalive parameters. If we fail to set a
656 * parameter, don't error out, because these aren't universally
657 * supported. (Note: you might think we need to reset the GUC
658 * variables to 0 in such a case, but it's not necessary because the
659 * show hooks for these variables report the truth anyway.)
661 (void) pq_setkeepalivesidle(tcp_keepalives_idle, port);
662 (void) pq_setkeepalivesinterval(tcp_keepalives_interval, port);
663 (void) pq_setkeepalivescount(tcp_keepalives_count, port);
670 * StreamClose -- close a client/backend connection
672 * NOTE: this is NOT used to terminate a session; it is just used to release
673 * the file descriptor in a process that should no longer have the socket
674 * open. (For example, the postmaster calls this after passing ownership
675 * of the connection to a child process.) It is expected that someone else
676 * still has the socket open. So, we only want to close the descriptor,
677 * we do NOT want to send anything to the far end.
680 StreamClose(pgsocket sock)
686 * TouchSocketFile -- mark socket file as recently accessed
688 * This routine should be called every so often to ensure that the socket
689 * file has a recent mod date (ordinary operations on sockets usually won't
690 * change the mod date). That saves it from being removed by
691 * overenthusiastic /tmp-directory-cleaner daemons. (Another reason we should
692 * never have put the socket file in /tmp...)
695 TouchSocketFile(void)
697 /* Do nothing if we did not create a socket... */
698 if (sock_path[0] != '\0')
701 * utime() is POSIX standard, utimes() is a common alternative. If we
702 * have neither, there's no way to affect the mod or access time of
705 * In either path, we ignore errors; there's no point in complaining.
708 utime(sock_path, NULL);
709 #else /* !HAVE_UTIME */
711 utimes(sock_path, NULL);
712 #endif /* HAVE_UTIMES */
713 #endif /* HAVE_UTIME */
718 /* --------------------------------
719 * Low-level I/O routines begin here.
721 * These routines communicate with a frontend client across a connection
722 * already established by the preceding routines.
723 * --------------------------------
727 /* --------------------------------
728 * pq_recvbuf - load some bytes into the input buffer
730 * returns 0 if OK, EOF if trouble
731 * --------------------------------
736 if (PqRecvPointer > 0)
738 if (PqRecvLength > PqRecvPointer)
740 /* still some unread data, left-justify it in the buffer */
741 memmove(PqRecvBuffer, PqRecvBuffer + PqRecvPointer,
742 PqRecvLength - PqRecvPointer);
743 PqRecvLength -= PqRecvPointer;
747 PqRecvLength = PqRecvPointer = 0;
750 /* Can fill buffer from PqRecvLength and upwards */
755 r = secure_read(MyProcPort, PqRecvBuffer + PqRecvLength,
756 PQ_BUFFER_SIZE - PqRecvLength);
761 continue; /* Ok if interrupted */
764 * Careful: an ereport() that tries to write to the client would
765 * cause recursion to here, leading to stack overflow and core
766 * dump! This message must go *only* to the postmaster log.
769 (errcode_for_socket_access(),
770 errmsg("could not receive data from client: %m")));
776 * EOF detected. We used to write a log message here, but it's
777 * better to expect the ultimate caller to do that.
781 /* r contains number of bytes read, so just incr length */
787 /* --------------------------------
788 * pq_getbyte - get a single byte from connection, or return EOF
789 * --------------------------------
794 while (PqRecvPointer >= PqRecvLength)
796 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
797 return EOF; /* Failed to recv data */
799 return (unsigned char) PqRecvBuffer[PqRecvPointer++];
802 /* --------------------------------
803 * pq_peekbyte - peek at next byte from connection
805 * Same as pq_getbyte() except we don't advance the pointer.
806 * --------------------------------
811 while (PqRecvPointer >= PqRecvLength)
813 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
814 return EOF; /* Failed to recv data */
816 return (unsigned char) PqRecvBuffer[PqRecvPointer];
820 /* --------------------------------
821 * pq_getbyte_if_available - get a single byte from connection,
824 * The received byte is stored in *c. Returns 1 if a byte was read, 0 if
825 * if no data was available, or EOF.
826 * --------------------------------
829 pq_getbyte_if_available(unsigned char *c)
833 if (PqRecvPointer < PqRecvLength)
835 *c = PqRecvBuffer[PqRecvPointer++];
839 /* Temporarily put the socket into non-blocking mode */
840 if (!pg_set_noblock(MyProcPort->sock))
842 (errmsg("couldn't put socket to non-blocking mode: %m")));
843 MyProcPort->noblock = true;
846 r = secure_read(MyProcPort, c, 1);
851 * The rest of the backend code assumes the socket is in blocking
852 * mode, so treat failure as FATAL.
854 if (!pg_set_block(MyProcPort->sock))
856 (errmsg("couldn't put socket to blocking mode: %m")));
857 MyProcPort->noblock = false;
861 if (!pg_set_block(MyProcPort->sock))
863 (errmsg("couldn't put socket to blocking mode: %m")));
864 MyProcPort->noblock = false;
869 /* --------------------------------
870 * pq_getbytes - get a known number of bytes from connection
872 * returns 0 if OK, EOF if trouble
873 * --------------------------------
876 pq_getbytes(char *s, size_t len)
882 while (PqRecvPointer >= PqRecvLength)
884 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
885 return EOF; /* Failed to recv data */
887 amount = PqRecvLength - PqRecvPointer;
890 memcpy(s, PqRecvBuffer + PqRecvPointer, amount);
891 PqRecvPointer += amount;
898 /* --------------------------------
899 * pq_discardbytes - throw away a known number of bytes
901 * same as pq_getbytes except we do not copy the data to anyplace.
902 * this is used for resynchronizing after read errors.
904 * returns 0 if OK, EOF if trouble
905 * --------------------------------
908 pq_discardbytes(size_t len)
914 while (PqRecvPointer >= PqRecvLength)
916 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
917 return EOF; /* Failed to recv data */
919 amount = PqRecvLength - PqRecvPointer;
922 PqRecvPointer += amount;
928 /* --------------------------------
929 * pq_getstring - get a null terminated string from connection
931 * The return value is placed in an expansible StringInfo, which has
932 * already been initialized by the caller.
934 * This is used only for dealing with old-protocol clients. The idea
935 * is to produce a StringInfo that looks the same as we would get from
936 * pq_getmessage() with a newer client; we will then process it with
937 * pq_getmsgstring. Therefore, no character set conversion is done here,
938 * even though this is presumably useful only for text.
940 * returns 0 if OK, EOF if trouble
941 * --------------------------------
944 pq_getstring(StringInfo s)
950 /* Read until we get the terminating '\0' */
953 while (PqRecvPointer >= PqRecvLength)
955 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
956 return EOF; /* Failed to recv data */
959 for (i = PqRecvPointer; i < PqRecvLength; i++)
961 if (PqRecvBuffer[i] == '\0')
963 /* include the '\0' in the copy */
964 appendBinaryStringInfo(s, PqRecvBuffer + PqRecvPointer,
965 i - PqRecvPointer + 1);
966 PqRecvPointer = i + 1; /* advance past \0 */
971 /* If we're here we haven't got the \0 in the buffer yet. */
972 appendBinaryStringInfo(s, PqRecvBuffer + PqRecvPointer,
973 PqRecvLength - PqRecvPointer);
974 PqRecvPointer = PqRecvLength;
979 /* --------------------------------
980 * pq_getmessage - get a message with length word from connection
982 * The return value is placed in an expansible StringInfo, which has
983 * already been initialized by the caller.
984 * Only the message body is placed in the StringInfo; the length word
985 * is removed. Also, s->cursor is initialized to zero for convenience
986 * in scanning the message contents.
988 * If maxlen is not zero, it is an upper limit on the length of the
989 * message we are willing to accept. We abort the connection (by
990 * returning EOF) if client tries to send more than that.
992 * returns 0 if OK, EOF if trouble
993 * --------------------------------
996 pq_getmessage(StringInfo s, int maxlen)
1002 /* Read message length word */
1003 if (pq_getbytes((char *) &len, 4) == EOF)
1006 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1007 errmsg("unexpected EOF within message length word")));
1014 (maxlen > 0 && len > maxlen))
1017 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1018 errmsg("invalid message length")));
1022 len -= 4; /* discount length itself */
1027 * Allocate space for message. If we run out of room (ridiculously
1028 * large message), we will elog(ERROR), but we want to discard the
1029 * message body so as not to lose communication sync.
1033 enlargeStringInfo(s, len);
1037 if (pq_discardbytes(len) == EOF)
1039 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1040 errmsg("incomplete message from client")));
1045 /* And grab the message */
1046 if (pq_getbytes(s->data, len) == EOF)
1049 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1050 errmsg("incomplete message from client")));
1054 /* Place a trailing null per StringInfo convention */
1055 s->data[len] = '\0';
1062 /* --------------------------------
1063 * pq_putbytes - send bytes to connection (not flushed until pq_flush)
1065 * returns 0 if OK, EOF if trouble
1066 * --------------------------------
1069 pq_putbytes(const char *s, size_t len)
1073 /* Should only be called by old-style COPY OUT */
1074 Assert(DoingCopyOut);
1075 /* No-op if reentrant call */
1079 res = internal_putbytes(s, len);
1085 internal_putbytes(const char *s, size_t len)
1091 /* If buffer is full, then flush it out */
1092 if (PqSendPointer >= PQ_BUFFER_SIZE)
1093 if (internal_flush())
1095 amount = PQ_BUFFER_SIZE - PqSendPointer;
1098 memcpy(PqSendBuffer + PqSendPointer, s, amount);
1099 PqSendPointer += amount;
1106 /* --------------------------------
1107 * pq_flush - flush pending output
1109 * returns 0 if OK, EOF if trouble
1110 * --------------------------------
1117 /* No-op if reentrant call */
1121 res = internal_flush();
1127 internal_flush(void)
1129 static int last_reported_send_errno = 0;
1131 char *bufptr = PqSendBuffer;
1132 char *bufend = PqSendBuffer + PqSendPointer;
1134 while (bufptr < bufend)
1138 r = secure_write(MyProcPort, bufptr, bufend - bufptr);
1143 continue; /* Ok if we were interrupted */
1146 * Careful: an ereport() that tries to write to the client would
1147 * cause recursion to here, leading to stack overflow and core
1148 * dump! This message must go *only* to the postmaster log.
1150 * If a client disconnects while we're in the midst of output, we
1151 * might write quite a bit of data before we get to a safe query
1152 * abort point. So, suppress duplicate log messages.
1154 if (errno != last_reported_send_errno)
1156 last_reported_send_errno = errno;
1158 (errcode_for_socket_access(),
1159 errmsg("could not send data to client: %m")));
1163 * We drop the buffered data anyway so that processing can
1164 * continue, even though we'll probably quit soon.
1170 last_reported_send_errno = 0; /* reset after any successful send */
1179 /* --------------------------------
1180 * Message-level I/O routines begin here.
1182 * These routines understand about the old-style COPY OUT protocol.
1183 * --------------------------------
1187 /* --------------------------------
1188 * pq_putmessage - send a normal message (suppressed in COPY OUT mode)
1190 * If msgtype is not '\0', it is a message type code to place before
1191 * the message body. If msgtype is '\0', then the message has no type
1192 * code (this is only valid in pre-3.0 protocols).
1194 * len is the length of the message body data at *s. In protocol 3.0
1195 * and later, a message length word (equal to len+4 because it counts
1196 * itself too) is inserted by this routine.
1198 * All normal messages are suppressed while old-style COPY OUT is in
1199 * progress. (In practice only a few notice messages might get emitted
1200 * then; dropping them is annoying, but at least they will still appear
1201 * in the postmaster log.)
1203 * We also suppress messages generated while pqcomm.c is busy. This
1204 * avoids any possibility of messages being inserted within other
1205 * messages. The only known trouble case arises if SIGQUIT occurs
1206 * during a pqcomm.c routine --- quickdie() will try to send a warning
1207 * message, and the most reasonable approach seems to be to drop it.
1209 * returns 0 if OK, EOF if trouble
1210 * --------------------------------
1213 pq_putmessage(char msgtype, const char *s, size_t len)
1215 if (DoingCopyOut || PqCommBusy)
1219 if (internal_putbytes(&msgtype, 1))
1221 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
1225 n32 = htonl((uint32) (len + 4));
1226 if (internal_putbytes((char *) &n32, 4))
1229 if (internal_putbytes(s, len))
1239 /* --------------------------------
1240 * pq_startcopyout - inform libpq that an old-style COPY OUT transfer
1242 * --------------------------------
1245 pq_startcopyout(void)
1247 DoingCopyOut = true;
1250 /* --------------------------------
1251 * pq_endcopyout - end an old-style COPY OUT transfer
1253 * If errorAbort is indicated, we are aborting a COPY OUT due to an error,
1254 * and must send a terminator line. Since a partial data line might have
1255 * been emitted, send a couple of newlines first (the first one could
1256 * get absorbed by a backslash...) Note that old-style COPY OUT does
1257 * not allow binary transfers, so a textual terminator is always correct.
1258 * --------------------------------
1261 pq_endcopyout(bool errorAbort)
1266 pq_putbytes("\n\n\\.\n", 5);
1267 /* in non-error case, copy.c will have emitted the terminator line */
1268 DoingCopyOut = false;
1273 * Support for TCP Keepalive parameters
1277 pq_getkeepalivesidle(Port *port)
1280 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1283 if (port->keepalives_idle != 0)
1284 return port->keepalives_idle;
1286 if (port->default_keepalives_idle == 0)
1288 ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_idle);
1290 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPIDLE,
1291 (char *) &port->default_keepalives_idle,
1294 elog(LOG, "getsockopt(TCP_KEEPIDLE) failed: %m");
1295 port->default_keepalives_idle = -1; /* don't know */
1299 return port->default_keepalives_idle;
1306 pq_setkeepalivesidle(int idle, Port *port)
1308 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1312 if (idle == port->keepalives_idle)
1315 if (port->default_keepalives_idle <= 0)
1317 if (pq_getkeepalivesidle(port) < 0)
1320 return STATUS_OK; /* default is set but unknown */
1322 return STATUS_ERROR;
1327 idle = port->default_keepalives_idle;
1329 if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPIDLE,
1330 (char *) &idle, sizeof(idle)) < 0)
1332 elog(LOG, "setsockopt(TCP_KEEPIDLE) failed: %m");
1333 return STATUS_ERROR;
1336 port->keepalives_idle = idle;
1340 elog(LOG, "setsockopt(TCP_KEEPIDLE) not supported");
1341 return STATUS_ERROR;
1349 pq_getkeepalivesinterval(Port *port)
1351 #ifdef TCP_KEEPINTVL
1352 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1355 if (port->keepalives_interval != 0)
1356 return port->keepalives_interval;
1358 if (port->default_keepalives_interval == 0)
1360 ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_interval);
1362 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1363 (char *) &port->default_keepalives_interval,
1366 elog(LOG, "getsockopt(TCP_KEEPINTVL) failed: %m");
1367 port->default_keepalives_interval = -1; /* don't know */
1371 return port->default_keepalives_interval;
1378 pq_setkeepalivesinterval(int interval, Port *port)
1380 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1383 #ifdef TCP_KEEPINTVL
1384 if (interval == port->keepalives_interval)
1387 if (port->default_keepalives_interval <= 0)
1389 if (pq_getkeepalivesinterval(port) < 0)
1392 return STATUS_OK; /* default is set but unknown */
1394 return STATUS_ERROR;
1399 interval = port->default_keepalives_interval;
1401 if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1402 (char *) &interval, sizeof(interval)) < 0)
1404 elog(LOG, "setsockopt(TCP_KEEPINTVL) failed: %m");
1405 return STATUS_ERROR;
1408 port->keepalives_interval = interval;
1412 elog(LOG, "setsockopt(TCP_KEEPINTVL) not supported");
1413 return STATUS_ERROR;
1421 pq_getkeepalivescount(Port *port)
1424 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1427 if (port->keepalives_count != 0)
1428 return port->keepalives_count;
1430 if (port->default_keepalives_count == 0)
1432 ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_count);
1434 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
1435 (char *) &port->default_keepalives_count,
1438 elog(LOG, "getsockopt(TCP_KEEPCNT) failed: %m");
1439 port->default_keepalives_count = -1; /* don't know */
1443 return port->default_keepalives_count;
1450 pq_setkeepalivescount(int count, Port *port)
1452 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1456 if (count == port->keepalives_count)
1459 if (port->default_keepalives_count <= 0)
1461 if (pq_getkeepalivescount(port) < 0)
1464 return STATUS_OK; /* default is set but unknown */
1466 return STATUS_ERROR;
1471 count = port->default_keepalives_count;
1473 if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
1474 (char *) &count, sizeof(count)) < 0)
1476 elog(LOG, "setsockopt(TCP_KEEPCNT) failed: %m");
1477 return STATUS_ERROR;
1480 port->keepalives_count = count;
1484 elog(LOG, "setsockopt(TCP_KEEPCNT) not supported");
1485 return STATUS_ERROR;