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-2009, PostgreSQL Global Development Group
31 * Portions Copyright (c) 1994, Regents of the University of California
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
59 * message-level I/O (and old-style-COPY-OUT cruft):
60 * pq_putmessage - send a normal message (suppressed in COPY OUT mode)
61 * pq_startcopyout - inform libpq that a COPY OUT transfer is beginning
62 * pq_endcopyout - end a COPY OUT transfer
64 *------------------------
73 #include <sys/socket.h>
77 #include <netinet/in.h>
78 #ifdef HAVE_NETINET_TCP_H
79 #include <netinet/tcp.h>
81 #include <arpa/inet.h>
87 #include "libpq/libpq.h"
88 #include "miscadmin.h"
89 #include "storage/ipc.h"
90 #include "utils/guc.h"
93 * Configuration options
95 int Unix_socket_permissions
;
96 char *Unix_socket_group
;
99 /* Where the Unix socket file is */
100 static char sock_path
[MAXPGPATH
];
104 * Buffers for low-level I/O
107 #define PQ_BUFFER_SIZE 8192
109 static char PqSendBuffer
[PQ_BUFFER_SIZE
];
110 static int PqSendPointer
; /* Next index to store a byte in PqSendBuffer */
112 static char PqRecvBuffer
[PQ_BUFFER_SIZE
];
113 static int PqRecvPointer
; /* Next index to read a byte from PqRecvBuffer */
114 static int PqRecvLength
; /* End of data available in PqRecvBuffer */
119 static bool PqCommBusy
;
120 static bool DoingCopyOut
;
123 /* Internal functions */
124 static void pq_close(int code
, Datum arg
);
125 static int internal_putbytes(const char *s
, size_t len
);
126 static int internal_flush(void);
128 #ifdef HAVE_UNIX_SOCKETS
129 static int Lock_AF_UNIX(unsigned short portNumber
, char *unixSocketName
);
130 static int Setup_AF_UNIX(void);
131 #endif /* HAVE_UNIX_SOCKETS */
134 /* --------------------------------
135 * pq_init - initialize libpq at backend startup
136 * --------------------------------
141 PqSendPointer
= PqRecvPointer
= PqRecvLength
= 0;
143 DoingCopyOut
= false;
144 on_proc_exit(pq_close
, 0);
147 /* --------------------------------
148 * pq_comm_reset - reset libpq during error recovery
150 * This is called from error recovery at the outer idle loop. It's
151 * just to get us out of trouble if we somehow manage to elog() from
152 * inside a pqcomm.c routine (which ideally will never happen, but...)
153 * --------------------------------
158 /* Do not throw away pending data, but do reset the busy flag */
160 /* We can abort any old-style COPY OUT, too */
164 /* --------------------------------
165 * pq_close - shutdown libpq at backend exit
167 * Note: in a standalone backend MyProcPort will be null,
168 * don't crash during exit...
169 * --------------------------------
172 pq_close(int code
, Datum arg
)
174 if (MyProcPort
!= NULL
)
176 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
180 /* Shutdown GSSAPI layer */
181 if (MyProcPort
->gss
->ctx
!= GSS_C_NO_CONTEXT
)
182 gss_delete_sec_context(&min_s
, &MyProcPort
->gss
->ctx
, NULL
);
184 if (MyProcPort
->gss
->cred
!= GSS_C_NO_CREDENTIAL
)
185 gss_release_cred(&min_s
, &MyProcPort
->gss
->cred
);
186 #endif /* ENABLE_GSS */
187 /* GSS and SSPI share the port->gss struct */
189 free(MyProcPort
->gss
);
190 #endif /* ENABLE_GSS || ENABLE_SSPI */
192 /* Cleanly shut down SSL layer */
193 secure_close(MyProcPort
);
196 * Formerly we did an explicit close() here, but it seems better to
197 * leave the socket open until the process dies. This allows clients
198 * to perform a "synchronous close" if they care --- wait till the
199 * transport layer reports connection closure, and you can be sure the
200 * backend has exited.
202 * We do set sock to -1 to prevent any further I/O, though.
204 MyProcPort
->sock
= -1;
211 * Streams -- wrapper around Unix socket system calls
214 * Stream functions are used for vanilla TCP connection protocol.
219 * Shutdown routine for backend connection
220 * If a Unix socket is used for communication, explicitly close it.
222 #ifdef HAVE_UNIX_SOCKETS
224 StreamDoUnlink(int code
, Datum arg
)
226 Assert(sock_path
[0]);
229 #endif /* HAVE_UNIX_SOCKETS */
232 * StreamServerPort -- open a "listening" port to accept connections.
234 * Successfully opened sockets are added to the ListenSocket[] array,
235 * at the first position that isn't -1.
237 * RETURNS: STATUS_OK or STATUS_ERROR
241 StreamServerPort(int family
, char *hostName
, unsigned short portNumber
,
242 char *unixSocketName
,
243 int ListenSocket
[], int MaxListen
)
249 char portNumberStr
[32];
250 const char *familyDesc
;
251 char familyDescBuf
[64];
253 struct addrinfo
*addrs
= NULL
,
255 struct addrinfo hint
;
256 int listen_index
= 0;
259 #if !defined(WIN32) || defined(IPV6_V6ONLY)
263 /* Initialize hint structure */
264 MemSet(&hint
, 0, sizeof(hint
));
265 hint
.ai_family
= family
;
266 hint
.ai_flags
= AI_PASSIVE
;
267 hint
.ai_socktype
= SOCK_STREAM
;
269 #ifdef HAVE_UNIX_SOCKETS
270 if (family
== AF_UNIX
)
272 /* Lock_AF_UNIX will also fill in sock_path. */
273 if (Lock_AF_UNIX(portNumber
, unixSocketName
) != STATUS_OK
)
278 #endif /* HAVE_UNIX_SOCKETS */
280 snprintf(portNumberStr
, sizeof(portNumberStr
), "%d", portNumber
);
281 service
= portNumberStr
;
284 ret
= pg_getaddrinfo_all(hostName
, service
, &hint
, &addrs
);
289 (errmsg("could not translate host name \"%s\", service \"%s\" to address: %s",
290 hostName
, service
, gai_strerror(ret
))));
293 (errmsg("could not translate service \"%s\" to address: %s",
294 service
, gai_strerror(ret
))));
296 pg_freeaddrinfo_all(hint
.ai_family
, addrs
);
300 for (addr
= addrs
; addr
; addr
= addr
->ai_next
)
302 if (!IS_AF_UNIX(family
) && IS_AF_UNIX(addr
->ai_family
))
305 * Only set up a unix domain socket when they really asked for it.
306 * The service/port is different in that case.
311 /* See if there is still room to add 1 more socket. */
312 for (; listen_index
< MaxListen
; listen_index
++)
314 if (ListenSocket
[listen_index
] == -1)
317 if (listen_index
>= MaxListen
)
320 (errmsg("could not bind to all requested addresses: MAXLISTEN (%d) exceeded",
325 /* set up family name for possible error messages */
326 switch (addr
->ai_family
)
329 familyDesc
= _("IPv4");
333 familyDesc
= _("IPv6");
336 #ifdef HAVE_UNIX_SOCKETS
338 familyDesc
= _("Unix");
342 snprintf(familyDescBuf
, sizeof(familyDescBuf
),
343 _("unrecognized address family %d"),
345 familyDesc
= familyDescBuf
;
349 if ((fd
= socket(addr
->ai_family
, SOCK_STREAM
, 0)) < 0)
352 (errcode_for_socket_access(),
353 /* translator: %s is IPv4, IPv6, or Unix */
354 errmsg("could not create %s socket: %m",
362 * Without the SO_REUSEADDR flag, a new postmaster can't be started
363 * right away after a stop or crash, giving "address already in use"
364 * error on TCP ports.
366 * On win32, however, this behavior only happens if the
367 * SO_EXLUSIVEADDRUSE is set. With SO_REUSEADDR, win32 allows multiple
368 * servers to listen on the same address, resulting in unpredictable
369 * behavior. With no flags at all, win32 behaves as Unix with
372 if (!IS_AF_UNIX(addr
->ai_family
))
374 if ((setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
375 (char *) &one
, sizeof(one
))) == -1)
378 (errcode_for_socket_access(),
379 errmsg("setsockopt(SO_REUSEADDR) failed: %m")));
387 if (addr
->ai_family
== AF_INET6
)
389 if (setsockopt(fd
, IPPROTO_IPV6
, IPV6_V6ONLY
,
390 (char *) &one
, sizeof(one
)) == -1)
393 (errcode_for_socket_access(),
394 errmsg("setsockopt(IPV6_V6ONLY) failed: %m")));
402 * Note: This might fail on some OS's, like Linux older than
403 * 2.4.21-pre3, that don't have the IPV6_V6ONLY socket option, and map
404 * ipv4 addresses to ipv6. It will show ::ffff:ipv4 for all ipv4
407 err
= bind(fd
, addr
->ai_addr
, addr
->ai_addrlen
);
411 (errcode_for_socket_access(),
412 /* translator: %s is IPv4, IPv6, or Unix */
413 errmsg("could not bind %s socket: %m",
415 (IS_AF_UNIX(addr
->ai_family
)) ?
416 errhint("Is another postmaster already running on port %d?"
417 " If not, remove socket file \"%s\" and retry.",
418 (int) portNumber
, sock_path
) :
419 errhint("Is another postmaster already running on port %d?"
420 " If not, wait a few seconds and retry.",
426 #ifdef HAVE_UNIX_SOCKETS
427 if (addr
->ai_family
== AF_UNIX
)
429 if (Setup_AF_UNIX() != STATUS_OK
)
438 * Select appropriate accept-queue length limit. PG_SOMAXCONN is only
439 * intended to provide a clamp on the request on platforms where an
440 * overly large request provokes a kernel error (are there any?).
442 maxconn
= MaxBackends
* 2;
443 if (maxconn
> PG_SOMAXCONN
)
444 maxconn
= PG_SOMAXCONN
;
446 err
= listen(fd
, maxconn
);
450 (errcode_for_socket_access(),
451 /* translator: %s is IPv4, IPv6, or Unix */
452 errmsg("could not listen on %s socket: %m",
457 ListenSocket
[listen_index
] = fd
;
461 pg_freeaddrinfo_all(hint
.ai_family
, addrs
);
470 #ifdef HAVE_UNIX_SOCKETS
473 * Lock_AF_UNIX -- configure unix socket file path
476 Lock_AF_UNIX(unsigned short portNumber
, char *unixSocketName
)
478 UNIXSOCK_PATH(sock_path
, portNumber
, unixSocketName
);
481 * Grab an interlock file associated with the socket file.
483 CreateSocketLockFile(sock_path
, true);
486 * Once we have the interlock, we can safely delete any pre-existing
487 * socket file to avoid failure at bind() time.
496 * Setup_AF_UNIX -- configure unix socket permissions
501 /* Arrange to unlink the socket file at exit */
502 on_proc_exit(StreamDoUnlink
, 0);
505 * Fix socket ownership/permission if requested. Note we must do this
506 * before we listen() to avoid a window where unwanted connections could
509 Assert(Unix_socket_group
);
510 if (Unix_socket_group
[0] != '\0')
513 elog(WARNING
, "configuration item unix_socket_group is not supported on this platform");
519 val
= strtoul(Unix_socket_group
, &endptr
, 10);
521 { /* numeric group id */
525 { /* convert group name to id */
528 gr
= getgrnam(Unix_socket_group
);
532 (errmsg("group \"%s\" does not exist",
533 Unix_socket_group
)));
538 if (chown(sock_path
, -1, gid
) == -1)
541 (errcode_for_file_access(),
542 errmsg("could not set group of file \"%s\": %m",
549 if (chmod(sock_path
, Unix_socket_permissions
) == -1)
552 (errcode_for_file_access(),
553 errmsg("could not set permissions of file \"%s\": %m",
559 #endif /* HAVE_UNIX_SOCKETS */
563 * StreamConnection -- create a new connection with client using
564 * server port. Set port->sock to the FD of the new connection.
566 * ASSUME: that this doesn't need to be non-blocking because
567 * the Postmaster uses select() to tell when the server master
568 * socket is ready for accept().
570 * RETURNS: STATUS_OK or STATUS_ERROR
573 StreamConnection(int server_fd
, Port
*port
)
575 /* accept connection and fill in the client (remote) address */
576 port
->raddr
.salen
= sizeof(port
->raddr
.addr
);
577 if ((port
->sock
= accept(server_fd
,
578 (struct sockaddr
*) & port
->raddr
.addr
,
579 &port
->raddr
.salen
)) < 0)
582 (errcode_for_socket_access(),
583 errmsg("could not accept new connection: %m")));
586 * If accept() fails then postmaster.c will still see the server
587 * socket as read-ready, and will immediately try again. To avoid
588 * uselessly sucking lots of CPU, delay a bit before trying again.
589 * (The most likely reason for failure is being out of kernel file
590 * table slots; we can do little except hope some will get freed up.)
592 pg_usleep(100000L); /* wait 0.1 sec */
596 #ifdef SCO_ACCEPT_BUG
599 * UnixWare 7+ and OpenServer 5.0.4 are known to have this bug, but it
600 * shouldn't hurt to catch it for all versions of those platforms.
602 if (port
->raddr
.addr
.ss_family
== 0)
603 port
->raddr
.addr
.ss_family
= AF_UNIX
;
606 /* fill in the server (local) address */
607 port
->laddr
.salen
= sizeof(port
->laddr
.addr
);
608 if (getsockname(port
->sock
,
609 (struct sockaddr
*) & port
->laddr
.addr
,
610 &port
->laddr
.salen
) < 0)
612 elog(LOG
, "getsockname() failed: %m");
616 /* select NODELAY and KEEPALIVE options if it's a TCP connection */
617 if (!IS_AF_UNIX(port
->laddr
.addr
.ss_family
))
623 if (setsockopt(port
->sock
, IPPROTO_TCP
, TCP_NODELAY
,
624 (char *) &on
, sizeof(on
)) < 0)
626 elog(LOG
, "setsockopt(TCP_NODELAY) failed: %m");
631 if (setsockopt(port
->sock
, SOL_SOCKET
, SO_KEEPALIVE
,
632 (char *) &on
, sizeof(on
)) < 0)
634 elog(LOG
, "setsockopt(SO_KEEPALIVE) failed: %m");
641 * This is a Win32 socket optimization. The ideal size is 32k.
642 * http://support.microsoft.com/kb/823764/EN-US/
644 on
= PQ_BUFFER_SIZE
* 4;
645 if (setsockopt(port
->sock
, SOL_SOCKET
, SO_SNDBUF
, (char *) &on
,
648 elog(LOG
, "setsockopt(SO_SNDBUF) failed: %m");
654 * Also apply the current keepalive parameters. If we fail to set a
655 * parameter, don't error out, because these aren't universally
656 * supported. (Note: you might think we need to reset the GUC
657 * variables to 0 in such a case, but it's not necessary because the
658 * show hooks for these variables report the truth anyway.)
660 (void) pq_setkeepalivesidle(tcp_keepalives_idle
, port
);
661 (void) pq_setkeepalivesinterval(tcp_keepalives_interval
, port
);
662 (void) pq_setkeepalivescount(tcp_keepalives_count
, port
);
669 * StreamClose -- close a client/backend connection
671 * NOTE: this is NOT used to terminate a session; it is just used to release
672 * the file descriptor in a process that should no longer have the socket
673 * open. (For example, the postmaster calls this after passing ownership
674 * of the connection to a child process.) It is expected that someone else
675 * still has the socket open. So, we only want to close the descriptor,
676 * we do NOT want to send anything to the far end.
679 StreamClose(int sock
)
685 * TouchSocketFile -- mark socket file as recently accessed
687 * This routine should be called every so often to ensure that the socket
688 * file has a recent mod date (ordinary operations on sockets usually won't
689 * change the mod date). That saves it from being removed by
690 * overenthusiastic /tmp-directory-cleaner daemons. (Another reason we should
691 * never have put the socket file in /tmp...)
694 TouchSocketFile(void)
696 /* Do nothing if we did not create a socket... */
697 if (sock_path
[0] != '\0')
700 * utime() is POSIX standard, utimes() is a common alternative. If we
701 * have neither, there's no way to affect the mod or access time of
704 * In either path, we ignore errors; there's no point in complaining.
707 utime(sock_path
, NULL
);
708 #else /* !HAVE_UTIME */
710 utimes(sock_path
, NULL
);
711 #endif /* HAVE_UTIMES */
712 #endif /* HAVE_UTIME */
717 /* --------------------------------
718 * Low-level I/O routines begin here.
720 * These routines communicate with a frontend client across a connection
721 * already established by the preceding routines.
722 * --------------------------------
726 /* --------------------------------
727 * pq_recvbuf - load some bytes into the input buffer
729 * returns 0 if OK, EOF if trouble
730 * --------------------------------
735 if (PqRecvPointer
> 0)
737 if (PqRecvLength
> PqRecvPointer
)
739 /* still some unread data, left-justify it in the buffer */
740 memmove(PqRecvBuffer
, PqRecvBuffer
+ PqRecvPointer
,
741 PqRecvLength
- PqRecvPointer
);
742 PqRecvLength
-= PqRecvPointer
;
746 PqRecvLength
= PqRecvPointer
= 0;
749 /* Can fill buffer from PqRecvLength and upwards */
754 r
= secure_read(MyProcPort
, PqRecvBuffer
+ PqRecvLength
,
755 PQ_BUFFER_SIZE
- PqRecvLength
);
760 continue; /* Ok if interrupted */
763 * Careful: an ereport() that tries to write to the client would
764 * cause recursion to here, leading to stack overflow and core
765 * dump! This message must go *only* to the postmaster log.
768 (errcode_for_socket_access(),
769 errmsg("could not receive data from client: %m")));
775 * EOF detected. We used to write a log message here, but it's
776 * better to expect the ultimate caller to do that.
780 /* r contains number of bytes read, so just incr length */
786 /* --------------------------------
787 * pq_getbyte - get a single byte from connection, or return EOF
788 * --------------------------------
793 while (PqRecvPointer
>= PqRecvLength
)
795 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
796 return EOF
; /* Failed to recv data */
798 return (unsigned char) PqRecvBuffer
[PqRecvPointer
++];
801 /* --------------------------------
802 * pq_peekbyte - peek at next byte from connection
804 * Same as pq_getbyte() except we don't advance the pointer.
805 * --------------------------------
810 while (PqRecvPointer
>= PqRecvLength
)
812 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
813 return EOF
; /* Failed to recv data */
815 return (unsigned char) PqRecvBuffer
[PqRecvPointer
];
818 /* --------------------------------
819 * pq_getbytes - get a known number of bytes from connection
821 * returns 0 if OK, EOF if trouble
822 * --------------------------------
825 pq_getbytes(char *s
, size_t len
)
831 while (PqRecvPointer
>= PqRecvLength
)
833 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
834 return EOF
; /* Failed to recv data */
836 amount
= PqRecvLength
- PqRecvPointer
;
839 memcpy(s
, PqRecvBuffer
+ PqRecvPointer
, amount
);
840 PqRecvPointer
+= amount
;
847 /* --------------------------------
848 * pq_discardbytes - throw away a known number of bytes
850 * same as pq_getbytes except we do not copy the data to anyplace.
851 * this is used for resynchronizing after read errors.
853 * returns 0 if OK, EOF if trouble
854 * --------------------------------
857 pq_discardbytes(size_t len
)
863 while (PqRecvPointer
>= PqRecvLength
)
865 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
866 return EOF
; /* Failed to recv data */
868 amount
= PqRecvLength
- PqRecvPointer
;
871 PqRecvPointer
+= amount
;
877 /* --------------------------------
878 * pq_getstring - get a null terminated string from connection
880 * The return value is placed in an expansible StringInfo, which has
881 * already been initialized by the caller.
883 * This is used only for dealing with old-protocol clients. The idea
884 * is to produce a StringInfo that looks the same as we would get from
885 * pq_getmessage() with a newer client; we will then process it with
886 * pq_getmsgstring. Therefore, no character set conversion is done here,
887 * even though this is presumably useful only for text.
889 * returns 0 if OK, EOF if trouble
890 * --------------------------------
893 pq_getstring(StringInfo s
)
899 /* Read until we get the terminating '\0' */
902 while (PqRecvPointer
>= PqRecvLength
)
904 if (pq_recvbuf()) /* If nothing in buffer, then recv some */
905 return EOF
; /* Failed to recv data */
908 for (i
= PqRecvPointer
; i
< PqRecvLength
; i
++)
910 if (PqRecvBuffer
[i
] == '\0')
912 /* include the '\0' in the copy */
913 appendBinaryStringInfo(s
, PqRecvBuffer
+ PqRecvPointer
,
914 i
- PqRecvPointer
+ 1);
915 PqRecvPointer
= i
+ 1; /* advance past \0 */
920 /* If we're here we haven't got the \0 in the buffer yet. */
921 appendBinaryStringInfo(s
, PqRecvBuffer
+ PqRecvPointer
,
922 PqRecvLength
- PqRecvPointer
);
923 PqRecvPointer
= PqRecvLength
;
928 /* --------------------------------
929 * pq_getmessage - get a message with length word from connection
931 * The return value is placed in an expansible StringInfo, which has
932 * already been initialized by the caller.
933 * Only the message body is placed in the StringInfo; the length word
934 * is removed. Also, s->cursor is initialized to zero for convenience
935 * in scanning the message contents.
937 * If maxlen is not zero, it is an upper limit on the length of the
938 * message we are willing to accept. We abort the connection (by
939 * returning EOF) if client tries to send more than that.
941 * returns 0 if OK, EOF if trouble
942 * --------------------------------
945 pq_getmessage(StringInfo s
, int maxlen
)
951 /* Read message length word */
952 if (pq_getbytes((char *) &len
, 4) == EOF
)
955 (errcode(ERRCODE_PROTOCOL_VIOLATION
),
956 errmsg("unexpected EOF within message length word")));
963 (maxlen
> 0 && len
> maxlen
))
966 (errcode(ERRCODE_PROTOCOL_VIOLATION
),
967 errmsg("invalid message length")));
971 len
-= 4; /* discount length itself */
976 * Allocate space for message. If we run out of room (ridiculously
977 * large message), we will elog(ERROR), but we want to discard the
978 * message body so as not to lose communication sync.
982 enlargeStringInfo(s
, len
);
986 if (pq_discardbytes(len
) == EOF
)
988 (errcode(ERRCODE_PROTOCOL_VIOLATION
),
989 errmsg("incomplete message from client")));
994 /* And grab the message */
995 if (pq_getbytes(s
->data
, len
) == EOF
)
998 (errcode(ERRCODE_PROTOCOL_VIOLATION
),
999 errmsg("incomplete message from client")));
1003 /* Place a trailing null per StringInfo convention */
1004 s
->data
[len
] = '\0';
1011 /* --------------------------------
1012 * pq_putbytes - send bytes to connection (not flushed until pq_flush)
1014 * returns 0 if OK, EOF if trouble
1015 * --------------------------------
1018 pq_putbytes(const char *s
, size_t len
)
1022 /* Should only be called by old-style COPY OUT */
1023 Assert(DoingCopyOut
);
1024 /* No-op if reentrant call */
1028 res
= internal_putbytes(s
, len
);
1034 internal_putbytes(const char *s
, size_t len
)
1040 /* If buffer is full, then flush it out */
1041 if (PqSendPointer
>= PQ_BUFFER_SIZE
)
1042 if (internal_flush())
1044 amount
= PQ_BUFFER_SIZE
- PqSendPointer
;
1047 memcpy(PqSendBuffer
+ PqSendPointer
, s
, amount
);
1048 PqSendPointer
+= amount
;
1055 /* --------------------------------
1056 * pq_flush - flush pending output
1058 * returns 0 if OK, EOF if trouble
1059 * --------------------------------
1066 /* No-op if reentrant call */
1070 res
= internal_flush();
1076 internal_flush(void)
1078 static int last_reported_send_errno
= 0;
1080 char *bufptr
= PqSendBuffer
;
1081 char *bufend
= PqSendBuffer
+ PqSendPointer
;
1083 while (bufptr
< bufend
)
1087 r
= secure_write(MyProcPort
, bufptr
, bufend
- bufptr
);
1092 continue; /* Ok if we were interrupted */
1095 * Careful: an ereport() that tries to write to the client would
1096 * cause recursion to here, leading to stack overflow and core
1097 * dump! This message must go *only* to the postmaster log.
1099 * If a client disconnects while we're in the midst of output, we
1100 * might write quite a bit of data before we get to a safe query
1101 * abort point. So, suppress duplicate log messages.
1103 if (errno
!= last_reported_send_errno
)
1105 last_reported_send_errno
= errno
;
1107 (errcode_for_socket_access(),
1108 errmsg("could not send data to client: %m")));
1112 * We drop the buffered data anyway so that processing can
1113 * continue, even though we'll probably quit soon.
1119 last_reported_send_errno
= 0; /* reset after any successful send */
1128 /* --------------------------------
1129 * Message-level I/O routines begin here.
1131 * These routines understand about the old-style COPY OUT protocol.
1132 * --------------------------------
1136 /* --------------------------------
1137 * pq_putmessage - send a normal message (suppressed in COPY OUT mode)
1139 * If msgtype is not '\0', it is a message type code to place before
1140 * the message body. If msgtype is '\0', then the message has no type
1141 * code (this is only valid in pre-3.0 protocols).
1143 * len is the length of the message body data at *s. In protocol 3.0
1144 * and later, a message length word (equal to len+4 because it counts
1145 * itself too) is inserted by this routine.
1147 * All normal messages are suppressed while old-style COPY OUT is in
1148 * progress. (In practice only a few notice messages might get emitted
1149 * then; dropping them is annoying, but at least they will still appear
1150 * in the postmaster log.)
1152 * We also suppress messages generated while pqcomm.c is busy. This
1153 * avoids any possibility of messages being inserted within other
1154 * messages. The only known trouble case arises if SIGQUIT occurs
1155 * during a pqcomm.c routine --- quickdie() will try to send a warning
1156 * message, and the most reasonable approach seems to be to drop it.
1158 * returns 0 if OK, EOF if trouble
1159 * --------------------------------
1162 pq_putmessage(char msgtype
, const char *s
, size_t len
)
1164 if (DoingCopyOut
|| PqCommBusy
)
1168 if (internal_putbytes(&msgtype
, 1))
1170 if (PG_PROTOCOL_MAJOR(FrontendProtocol
) >= 3)
1174 n32
= htonl((uint32
) (len
+ 4));
1175 if (internal_putbytes((char *) &n32
, 4))
1178 if (internal_putbytes(s
, len
))
1188 /* --------------------------------
1189 * pq_startcopyout - inform libpq that an old-style COPY OUT transfer
1191 * --------------------------------
1194 pq_startcopyout(void)
1196 DoingCopyOut
= true;
1199 /* --------------------------------
1200 * pq_endcopyout - end an old-style COPY OUT transfer
1202 * If errorAbort is indicated, we are aborting a COPY OUT due to an error,
1203 * and must send a terminator line. Since a partial data line might have
1204 * been emitted, send a couple of newlines first (the first one could
1205 * get absorbed by a backslash...) Note that old-style COPY OUT does
1206 * not allow binary transfers, so a textual terminator is always correct.
1207 * --------------------------------
1210 pq_endcopyout(bool errorAbort
)
1215 pq_putbytes("\n\n\\.\n", 5);
1216 /* in non-error case, copy.c will have emitted the terminator line */
1217 DoingCopyOut
= false;
1222 * Support for TCP Keepalive parameters
1226 pq_getkeepalivesidle(Port
*port
)
1229 if (port
== NULL
|| IS_AF_UNIX(port
->laddr
.addr
.ss_family
))
1232 if (port
->keepalives_idle
!= 0)
1233 return port
->keepalives_idle
;
1235 if (port
->default_keepalives_idle
== 0)
1237 ACCEPT_TYPE_ARG3 size
= sizeof(port
->default_keepalives_idle
);
1239 if (getsockopt(port
->sock
, IPPROTO_TCP
, TCP_KEEPIDLE
,
1240 (char *) &port
->default_keepalives_idle
,
1243 elog(LOG
, "getsockopt(TCP_KEEPIDLE) failed: %m");
1244 port
->default_keepalives_idle
= -1; /* don't know */
1248 return port
->default_keepalives_idle
;
1255 pq_setkeepalivesidle(int idle
, Port
*port
)
1257 if (port
== NULL
|| IS_AF_UNIX(port
->laddr
.addr
.ss_family
))
1261 if (idle
== port
->keepalives_idle
)
1264 if (port
->default_keepalives_idle
<= 0)
1266 if (pq_getkeepalivesidle(port
) < 0)
1269 return STATUS_OK
; /* default is set but unknown */
1271 return STATUS_ERROR
;
1276 idle
= port
->default_keepalives_idle
;
1278 if (setsockopt(port
->sock
, IPPROTO_TCP
, TCP_KEEPIDLE
,
1279 (char *) &idle
, sizeof(idle
)) < 0)
1281 elog(LOG
, "setsockopt(TCP_KEEPIDLE) failed: %m");
1282 return STATUS_ERROR
;
1285 port
->keepalives_idle
= idle
;
1289 elog(LOG
, "setsockopt(TCP_KEEPIDLE) not supported");
1290 return STATUS_ERROR
;
1298 pq_getkeepalivesinterval(Port
*port
)
1300 #ifdef TCP_KEEPINTVL
1301 if (port
== NULL
|| IS_AF_UNIX(port
->laddr
.addr
.ss_family
))
1304 if (port
->keepalives_interval
!= 0)
1305 return port
->keepalives_interval
;
1307 if (port
->default_keepalives_interval
== 0)
1309 ACCEPT_TYPE_ARG3 size
= sizeof(port
->default_keepalives_interval
);
1311 if (getsockopt(port
->sock
, IPPROTO_TCP
, TCP_KEEPINTVL
,
1312 (char *) &port
->default_keepalives_interval
,
1315 elog(LOG
, "getsockopt(TCP_KEEPINTVL) failed: %m");
1316 port
->default_keepalives_interval
= -1; /* don't know */
1320 return port
->default_keepalives_interval
;
1327 pq_setkeepalivesinterval(int interval
, Port
*port
)
1329 if (port
== NULL
|| IS_AF_UNIX(port
->laddr
.addr
.ss_family
))
1332 #ifdef TCP_KEEPINTVL
1333 if (interval
== port
->keepalives_interval
)
1336 if (port
->default_keepalives_interval
<= 0)
1338 if (pq_getkeepalivesinterval(port
) < 0)
1341 return STATUS_OK
; /* default is set but unknown */
1343 return STATUS_ERROR
;
1348 interval
= port
->default_keepalives_interval
;
1350 if (setsockopt(port
->sock
, IPPROTO_TCP
, TCP_KEEPINTVL
,
1351 (char *) &interval
, sizeof(interval
)) < 0)
1353 elog(LOG
, "setsockopt(TCP_KEEPINTVL) failed: %m");
1354 return STATUS_ERROR
;
1357 port
->keepalives_interval
= interval
;
1361 elog(LOG
, "setsockopt(TCP_KEEPINTVL) not supported");
1362 return STATUS_ERROR
;
1370 pq_getkeepalivescount(Port
*port
)
1373 if (port
== NULL
|| IS_AF_UNIX(port
->laddr
.addr
.ss_family
))
1376 if (port
->keepalives_count
!= 0)
1377 return port
->keepalives_count
;
1379 if (port
->default_keepalives_count
== 0)
1381 ACCEPT_TYPE_ARG3 size
= sizeof(port
->default_keepalives_count
);
1383 if (getsockopt(port
->sock
, IPPROTO_TCP
, TCP_KEEPCNT
,
1384 (char *) &port
->default_keepalives_count
,
1387 elog(LOG
, "getsockopt(TCP_KEEPCNT) failed: %m");
1388 port
->default_keepalives_count
= -1; /* don't know */
1392 return port
->default_keepalives_count
;
1399 pq_setkeepalivescount(int count
, Port
*port
)
1401 if (port
== NULL
|| IS_AF_UNIX(port
->laddr
.addr
.ss_family
))
1405 if (count
== port
->keepalives_count
)
1408 if (port
->default_keepalives_count
<= 0)
1410 if (pq_getkeepalivescount(port
) < 0)
1413 return STATUS_OK
; /* default is set but unknown */
1415 return STATUS_ERROR
;
1420 count
= port
->default_keepalives_count
;
1422 if (setsockopt(port
->sock
, IPPROTO_TCP
, TCP_KEEPCNT
,
1423 (char *) &count
, sizeof(count
)) < 0)
1425 elog(LOG
, "setsockopt(TCP_KEEPCNT) failed: %m");
1426 return STATUS_ERROR
;
1429 port
->keepalives_count
= count
;
1433 elog(LOG
, "setsockopt(TCP_KEEPCNT) not supported");
1434 return STATUS_ERROR
;