Disallow empty passwords in LDAP authentication, the same way
[PostgreSQL.git] / src / backend / libpq / pqcomm.c
blob5782b2321b1da3060701323c430f8cd69b82b120
1 /*-------------------------------------------------------------------------
3 * pqcomm.c
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
33 * $PostgreSQL$
35 *-------------------------------------------------------------------------
38 /*------------------------
39 * INTERFACE ROUTINES
41 * setup/teardown:
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
50 * low-level I/O:
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 *------------------------
66 #include "postgres.h"
68 #include <signal.h>
69 #include <fcntl.h>
70 #include <grp.h>
71 #include <unistd.h>
72 #include <sys/file.h>
73 #include <sys/socket.h>
74 #include <sys/stat.h>
75 #include <sys/time.h>
76 #include <netdb.h>
77 #include <netinet/in.h>
78 #ifdef HAVE_NETINET_TCP_H
79 #include <netinet/tcp.h>
80 #endif
81 #include <arpa/inet.h>
82 #ifdef HAVE_UTIME_H
83 #include <utime.h>
84 #endif
86 #include "libpq/ip.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 */
117 * Message status
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 * --------------------------------
138 void
139 pq_init(void)
141 PqSendPointer = PqRecvPointer = PqRecvLength = 0;
142 PqCommBusy = false;
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 * --------------------------------
155 void
156 pq_comm_reset(void)
158 /* Do not throw away pending data, but do reset the busy flag */
159 PqCommBusy = false;
160 /* We can abort any old-style COPY OUT, too */
161 pq_endcopyout(true);
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 * --------------------------------
171 static void
172 pq_close(int code, Datum arg)
174 if (MyProcPort != NULL)
176 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
177 #ifdef ENABLE_GSS
178 OM_uint32 min_s;
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.
218 /* StreamDoUnlink()
219 * Shutdown routine for backend connection
220 * If a Unix socket is used for communication, explicitly close it.
222 #ifdef HAVE_UNIX_SOCKETS
223 static void
224 StreamDoUnlink(int code, Datum arg)
226 Assert(sock_path[0]);
227 unlink(sock_path);
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)
245 int fd,
246 err;
247 int maxconn;
248 int ret;
249 char portNumberStr[32];
250 const char *familyDesc;
251 char familyDescBuf[64];
252 char *service;
253 struct addrinfo *addrs = NULL,
254 *addr;
255 struct addrinfo hint;
256 int listen_index = 0;
257 int added = 0;
259 #if !defined(WIN32) || defined(IPV6_V6ONLY)
260 int one = 1;
261 #endif
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)
274 return STATUS_ERROR;
275 service = sock_path;
277 else
278 #endif /* HAVE_UNIX_SOCKETS */
280 snprintf(portNumberStr, sizeof(portNumberStr), "%d", portNumber);
281 service = portNumberStr;
284 ret = pg_getaddrinfo_all(hostName, service, &hint, &addrs);
285 if (ret || !addrs)
287 if (hostName)
288 ereport(LOG,
289 (errmsg("could not translate host name \"%s\", service \"%s\" to address: %s",
290 hostName, service, gai_strerror(ret))));
291 else
292 ereport(LOG,
293 (errmsg("could not translate service \"%s\" to address: %s",
294 service, gai_strerror(ret))));
295 if (addrs)
296 pg_freeaddrinfo_all(hint.ai_family, addrs);
297 return STATUS_ERROR;
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.
308 continue;
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)
315 break;
317 if (listen_index >= MaxListen)
319 ereport(LOG,
320 (errmsg("could not bind to all requested addresses: MAXLISTEN (%d) exceeded",
321 MaxListen)));
322 break;
325 /* set up family name for possible error messages */
326 switch (addr->ai_family)
328 case AF_INET:
329 familyDesc = _("IPv4");
330 break;
331 #ifdef HAVE_IPV6
332 case AF_INET6:
333 familyDesc = _("IPv6");
334 break;
335 #endif
336 #ifdef HAVE_UNIX_SOCKETS
337 case AF_UNIX:
338 familyDesc = _("Unix");
339 break;
340 #endif
341 default:
342 snprintf(familyDescBuf, sizeof(familyDescBuf),
343 _("unrecognized address family %d"),
344 addr->ai_family);
345 familyDesc = familyDescBuf;
346 break;
349 if ((fd = socket(addr->ai_family, SOCK_STREAM, 0)) < 0)
351 ereport(LOG,
352 (errcode_for_socket_access(),
353 /* translator: %s is IPv4, IPv6, or Unix */
354 errmsg("could not create %s socket: %m",
355 familyDesc)));
356 continue;
359 #ifndef WIN32
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
370 * SO_REUSEADDR.
372 if (!IS_AF_UNIX(addr->ai_family))
374 if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
375 (char *) &one, sizeof(one))) == -1)
377 ereport(LOG,
378 (errcode_for_socket_access(),
379 errmsg("setsockopt(SO_REUSEADDR) failed: %m")));
380 closesocket(fd);
381 continue;
384 #endif
386 #ifdef IPV6_V6ONLY
387 if (addr->ai_family == AF_INET6)
389 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
390 (char *) &one, sizeof(one)) == -1)
392 ereport(LOG,
393 (errcode_for_socket_access(),
394 errmsg("setsockopt(IPV6_V6ONLY) failed: %m")));
395 closesocket(fd);
396 continue;
399 #endif
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
405 * connections.
407 err = bind(fd, addr->ai_addr, addr->ai_addrlen);
408 if (err < 0)
410 ereport(LOG,
411 (errcode_for_socket_access(),
412 /* translator: %s is IPv4, IPv6, or Unix */
413 errmsg("could not bind %s socket: %m",
414 familyDesc),
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.",
421 (int) portNumber)));
422 closesocket(fd);
423 continue;
426 #ifdef HAVE_UNIX_SOCKETS
427 if (addr->ai_family == AF_UNIX)
429 if (Setup_AF_UNIX() != STATUS_OK)
431 closesocket(fd);
432 break;
435 #endif
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);
447 if (err < 0)
449 ereport(LOG,
450 (errcode_for_socket_access(),
451 /* translator: %s is IPv4, IPv6, or Unix */
452 errmsg("could not listen on %s socket: %m",
453 familyDesc)));
454 closesocket(fd);
455 continue;
457 ListenSocket[listen_index] = fd;
458 added++;
461 pg_freeaddrinfo_all(hint.ai_family, addrs);
463 if (!added)
464 return STATUS_ERROR;
466 return STATUS_OK;
470 #ifdef HAVE_UNIX_SOCKETS
473 * Lock_AF_UNIX -- configure unix socket file path
475 static int
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.
489 unlink(sock_path);
491 return STATUS_OK;
496 * Setup_AF_UNIX -- configure unix socket permissions
498 static int
499 Setup_AF_UNIX(void)
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
507 * get accepted.
509 Assert(Unix_socket_group);
510 if (Unix_socket_group[0] != '\0')
512 #ifdef WIN32
513 elog(WARNING, "configuration item unix_socket_group is not supported on this platform");
514 #else
515 char *endptr;
516 unsigned long val;
517 gid_t gid;
519 val = strtoul(Unix_socket_group, &endptr, 10);
520 if (*endptr == '\0')
521 { /* numeric group id */
522 gid = val;
524 else
525 { /* convert group name to id */
526 struct group *gr;
528 gr = getgrnam(Unix_socket_group);
529 if (!gr)
531 ereport(LOG,
532 (errmsg("group \"%s\" does not exist",
533 Unix_socket_group)));
534 return STATUS_ERROR;
536 gid = gr->gr_gid;
538 if (chown(sock_path, -1, gid) == -1)
540 ereport(LOG,
541 (errcode_for_file_access(),
542 errmsg("could not set group of file \"%s\": %m",
543 sock_path)));
544 return STATUS_ERROR;
546 #endif
549 if (chmod(sock_path, Unix_socket_permissions) == -1)
551 ereport(LOG,
552 (errcode_for_file_access(),
553 errmsg("could not set permissions of file \"%s\": %m",
554 sock_path)));
555 return STATUS_ERROR;
557 return STATUS_OK;
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)
581 ereport(LOG,
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 */
593 return STATUS_ERROR;
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;
604 #endif
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");
613 return STATUS_ERROR;
616 /* select NODELAY and KEEPALIVE options if it's a TCP connection */
617 if (!IS_AF_UNIX(port->laddr.addr.ss_family))
619 int on;
621 #ifdef TCP_NODELAY
622 on = 1;
623 if (setsockopt(port->sock, IPPROTO_TCP, TCP_NODELAY,
624 (char *) &on, sizeof(on)) < 0)
626 elog(LOG, "setsockopt(TCP_NODELAY) failed: %m");
627 return STATUS_ERROR;
629 #endif
630 on = 1;
631 if (setsockopt(port->sock, SOL_SOCKET, SO_KEEPALIVE,
632 (char *) &on, sizeof(on)) < 0)
634 elog(LOG, "setsockopt(SO_KEEPALIVE) failed: %m");
635 return STATUS_ERROR;
638 #ifdef WIN32
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,
646 sizeof(on)) < 0)
648 elog(LOG, "setsockopt(SO_SNDBUF) failed: %m");
649 return STATUS_ERROR;
651 #endif
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);
665 return STATUS_OK;
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.
678 void
679 StreamClose(int sock)
681 closesocket(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...)
693 void
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
702 * the socket :-(
704 * In either path, we ignore errors; there's no point in complaining.
706 #ifdef HAVE_UTIME
707 utime(sock_path, NULL);
708 #else /* !HAVE_UTIME */
709 #ifdef HAVE_UTIMES
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 * --------------------------------
732 static int
733 pq_recvbuf(void)
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;
743 PqRecvPointer = 0;
745 else
746 PqRecvLength = PqRecvPointer = 0;
749 /* Can fill buffer from PqRecvLength and upwards */
750 for (;;)
752 int r;
754 r = secure_read(MyProcPort, PqRecvBuffer + PqRecvLength,
755 PQ_BUFFER_SIZE - PqRecvLength);
757 if (r < 0)
759 if (errno == EINTR)
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.
767 ereport(COMMERROR,
768 (errcode_for_socket_access(),
769 errmsg("could not receive data from client: %m")));
770 return EOF;
772 if (r == 0)
775 * EOF detected. We used to write a log message here, but it's
776 * better to expect the ultimate caller to do that.
778 return EOF;
780 /* r contains number of bytes read, so just incr length */
781 PqRecvLength += r;
782 return 0;
786 /* --------------------------------
787 * pq_getbyte - get a single byte from connection, or return EOF
788 * --------------------------------
791 pq_getbyte(void)
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 * --------------------------------
808 pq_peekbyte(void)
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)
827 size_t amount;
829 while (len > 0)
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;
837 if (amount > len)
838 amount = len;
839 memcpy(s, PqRecvBuffer + PqRecvPointer, amount);
840 PqRecvPointer += amount;
841 s += amount;
842 len -= amount;
844 return 0;
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 * --------------------------------
856 static int
857 pq_discardbytes(size_t len)
859 size_t amount;
861 while (len > 0)
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;
869 if (amount > len)
870 amount = len;
871 PqRecvPointer += amount;
872 len -= amount;
874 return 0;
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)
895 int i;
897 resetStringInfo(s);
899 /* Read until we get the terminating '\0' */
900 for (;;)
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 */
916 return 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)
947 int32 len;
949 resetStringInfo(s);
951 /* Read message length word */
952 if (pq_getbytes((char *) &len, 4) == EOF)
954 ereport(COMMERROR,
955 (errcode(ERRCODE_PROTOCOL_VIOLATION),
956 errmsg("unexpected EOF within message length word")));
957 return EOF;
960 len = ntohl(len);
962 if (len < 4 ||
963 (maxlen > 0 && len > maxlen))
965 ereport(COMMERROR,
966 (errcode(ERRCODE_PROTOCOL_VIOLATION),
967 errmsg("invalid message length")));
968 return EOF;
971 len -= 4; /* discount length itself */
973 if (len > 0)
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.
980 PG_TRY();
982 enlargeStringInfo(s, len);
984 PG_CATCH();
986 if (pq_discardbytes(len) == EOF)
987 ereport(COMMERROR,
988 (errcode(ERRCODE_PROTOCOL_VIOLATION),
989 errmsg("incomplete message from client")));
990 PG_RE_THROW();
992 PG_END_TRY();
994 /* And grab the message */
995 if (pq_getbytes(s->data, len) == EOF)
997 ereport(COMMERROR,
998 (errcode(ERRCODE_PROTOCOL_VIOLATION),
999 errmsg("incomplete message from client")));
1000 return EOF;
1002 s->len = len;
1003 /* Place a trailing null per StringInfo convention */
1004 s->data[len] = '\0';
1007 return 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)
1020 int res;
1022 /* Should only be called by old-style COPY OUT */
1023 Assert(DoingCopyOut);
1024 /* No-op if reentrant call */
1025 if (PqCommBusy)
1026 return 0;
1027 PqCommBusy = true;
1028 res = internal_putbytes(s, len);
1029 PqCommBusy = false;
1030 return res;
1033 static int
1034 internal_putbytes(const char *s, size_t len)
1036 size_t amount;
1038 while (len > 0)
1040 /* If buffer is full, then flush it out */
1041 if (PqSendPointer >= PQ_BUFFER_SIZE)
1042 if (internal_flush())
1043 return EOF;
1044 amount = PQ_BUFFER_SIZE - PqSendPointer;
1045 if (amount > len)
1046 amount = len;
1047 memcpy(PqSendBuffer + PqSendPointer, s, amount);
1048 PqSendPointer += amount;
1049 s += amount;
1050 len -= amount;
1052 return 0;
1055 /* --------------------------------
1056 * pq_flush - flush pending output
1058 * returns 0 if OK, EOF if trouble
1059 * --------------------------------
1062 pq_flush(void)
1064 int res;
1066 /* No-op if reentrant call */
1067 if (PqCommBusy)
1068 return 0;
1069 PqCommBusy = true;
1070 res = internal_flush();
1071 PqCommBusy = false;
1072 return res;
1075 static int
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)
1085 int r;
1087 r = secure_write(MyProcPort, bufptr, bufend - bufptr);
1089 if (r <= 0)
1091 if (errno == EINTR)
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;
1106 ereport(COMMERROR,
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.
1115 PqSendPointer = 0;
1116 return EOF;
1119 last_reported_send_errno = 0; /* reset after any successful send */
1120 bufptr += r;
1123 PqSendPointer = 0;
1124 return 0;
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)
1165 return 0;
1166 PqCommBusy = true;
1167 if (msgtype)
1168 if (internal_putbytes(&msgtype, 1))
1169 goto fail;
1170 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
1172 uint32 n32;
1174 n32 = htonl((uint32) (len + 4));
1175 if (internal_putbytes((char *) &n32, 4))
1176 goto fail;
1178 if (internal_putbytes(s, len))
1179 goto fail;
1180 PqCommBusy = false;
1181 return 0;
1183 fail:
1184 PqCommBusy = false;
1185 return EOF;
1188 /* --------------------------------
1189 * pq_startcopyout - inform libpq that an old-style COPY OUT transfer
1190 * is beginning
1191 * --------------------------------
1193 void
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 * --------------------------------
1209 void
1210 pq_endcopyout(bool errorAbort)
1212 if (!DoingCopyOut)
1213 return;
1214 if (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)
1228 #ifdef TCP_KEEPIDLE
1229 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1230 return 0;
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,
1241 &size) < 0)
1243 elog(LOG, "getsockopt(TCP_KEEPIDLE) failed: %m");
1244 port->default_keepalives_idle = -1; /* don't know */
1248 return port->default_keepalives_idle;
1249 #else
1250 return 0;
1251 #endif
1255 pq_setkeepalivesidle(int idle, Port *port)
1257 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1258 return STATUS_OK;
1260 #ifdef TCP_KEEPIDLE
1261 if (idle == port->keepalives_idle)
1262 return STATUS_OK;
1264 if (port->default_keepalives_idle <= 0)
1266 if (pq_getkeepalivesidle(port) < 0)
1268 if (idle == 0)
1269 return STATUS_OK; /* default is set but unknown */
1270 else
1271 return STATUS_ERROR;
1275 if (idle == 0)
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;
1286 #else
1287 if (idle != 0)
1289 elog(LOG, "setsockopt(TCP_KEEPIDLE) not supported");
1290 return STATUS_ERROR;
1292 #endif
1294 return STATUS_OK;
1298 pq_getkeepalivesinterval(Port *port)
1300 #ifdef TCP_KEEPINTVL
1301 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1302 return 0;
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,
1313 &size) < 0)
1315 elog(LOG, "getsockopt(TCP_KEEPINTVL) failed: %m");
1316 port->default_keepalives_interval = -1; /* don't know */
1320 return port->default_keepalives_interval;
1321 #else
1322 return 0;
1323 #endif
1327 pq_setkeepalivesinterval(int interval, Port *port)
1329 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1330 return STATUS_OK;
1332 #ifdef TCP_KEEPINTVL
1333 if (interval == port->keepalives_interval)
1334 return STATUS_OK;
1336 if (port->default_keepalives_interval <= 0)
1338 if (pq_getkeepalivesinterval(port) < 0)
1340 if (interval == 0)
1341 return STATUS_OK; /* default is set but unknown */
1342 else
1343 return STATUS_ERROR;
1347 if (interval == 0)
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;
1358 #else
1359 if (interval != 0)
1361 elog(LOG, "setsockopt(TCP_KEEPINTVL) not supported");
1362 return STATUS_ERROR;
1364 #endif
1366 return STATUS_OK;
1370 pq_getkeepalivescount(Port *port)
1372 #ifdef TCP_KEEPCNT
1373 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1374 return 0;
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,
1385 &size) < 0)
1387 elog(LOG, "getsockopt(TCP_KEEPCNT) failed: %m");
1388 port->default_keepalives_count = -1; /* don't know */
1392 return port->default_keepalives_count;
1393 #else
1394 return 0;
1395 #endif
1399 pq_setkeepalivescount(int count, Port *port)
1401 if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1402 return STATUS_OK;
1404 #ifdef TCP_KEEPCNT
1405 if (count == port->keepalives_count)
1406 return STATUS_OK;
1408 if (port->default_keepalives_count <= 0)
1410 if (pq_getkeepalivescount(port) < 0)
1412 if (count == 0)
1413 return STATUS_OK; /* default is set but unknown */
1414 else
1415 return STATUS_ERROR;
1419 if (count == 0)
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;
1430 #else
1431 if (count != 0)
1433 elog(LOG, "setsockopt(TCP_KEEPCNT) not supported");
1434 return STATUS_ERROR;
1436 #endif
1438 return STATUS_OK;