]> granicus.if.org Git - postgresql/blob - src/backend/libpq/pqcomm.c
Run pgindent on 9.2 source tree in preparation for first 9.3
[postgresql] / src / backend / libpq / pqcomm.c
1 /*-------------------------------------------------------------------------
2  *
3  * pqcomm.c
4  *        Communication functions between the Frontend and the Backend
5  *
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.)
17  *
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.
25  *
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...
29  *
30  * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
31  * Portions Copyright (c) 1994, Regents of the University of California
32  *
33  *      src/backend/libpq/pqcomm.c
34  *
35  *-------------------------------------------------------------------------
36  */
37
38 /*------------------------
39  * INTERFACE ROUTINES
40  *
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
49  *
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
58  *              pq_flush_if_writable - flush pending output if writable without blocking
59  *              pq_getbyte_if_available - get a byte if available without blocking
60  *
61  * message-level I/O (and old-style-COPY-OUT cruft):
62  *              pq_putmessage   - send a normal message (suppressed in COPY OUT mode)
63  *              pq_putmessage_noblock - buffer a normal message (suppressed in COPY OUT)
64  *              pq_startcopyout - inform libpq that a COPY OUT transfer is beginning
65  *              pq_endcopyout   - end a COPY OUT transfer
66  *
67  *------------------------
68  */
69 #include "postgres.h"
70
71 #include <signal.h>
72 #include <fcntl.h>
73 #include <grp.h>
74 #include <unistd.h>
75 #include <sys/file.h>
76 #include <sys/socket.h>
77 #include <sys/stat.h>
78 #include <sys/time.h>
79 #include <netdb.h>
80 #include <netinet/in.h>
81 #ifdef HAVE_NETINET_TCP_H
82 #include <netinet/tcp.h>
83 #endif
84 #include <arpa/inet.h>
85 #ifdef HAVE_UTIME_H
86 #include <utime.h>
87 #endif
88 #ifdef WIN32_ONLY_COMPILER              /* mstcpip.h is missing on mingw */
89 #include <mstcpip.h>
90 #endif
91
92 #include "libpq/ip.h"
93 #include "libpq/libpq.h"
94 #include "miscadmin.h"
95 #include "storage/ipc.h"
96 #include "utils/guc.h"
97 #include "utils/memutils.h"
98
99 /*
100  * Configuration options
101  */
102 int                     Unix_socket_permissions;
103 char       *Unix_socket_group;
104
105
106 /* Where the Unix socket file is */
107 static char sock_path[MAXPGPATH];
108
109
110 /*
111  * Buffers for low-level I/O.
112  *
113  * The receive buffer is fixed size. Send buffer is usually 8k, but can be
114  * enlarged by pq_putmessage_noblock() if the message doesn't fit otherwise.
115  */
116
117 #define PQ_SEND_BUFFER_SIZE 8192
118 #define PQ_RECV_BUFFER_SIZE 8192
119
120 static char *PqSendBuffer;
121 static int      PqSendBufferSize;       /* Size send buffer */
122 static int      PqSendPointer;          /* Next index to store a byte in PqSendBuffer */
123 static int      PqSendStart;            /* Next index to send a byte in PqSendBuffer */
124
125 static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE];
126 static int      PqRecvPointer;          /* Next index to read a byte from PqRecvBuffer */
127 static int      PqRecvLength;           /* End of data available in PqRecvBuffer */
128
129 /*
130  * Message status
131  */
132 static bool PqCommBusy;
133 static bool DoingCopyOut;
134
135
136 /* Internal functions */
137 static void pq_close(int code, Datum arg);
138 static int      internal_putbytes(const char *s, size_t len);
139 static int      internal_flush(void);
140 static void pq_set_nonblocking(bool nonblocking);
141
142 #ifdef HAVE_UNIX_SOCKETS
143 static int      Lock_AF_UNIX(unsigned short portNumber, char *unixSocketName);
144 static int      Setup_AF_UNIX(void);
145 #endif   /* HAVE_UNIX_SOCKETS */
146
147
148 /* --------------------------------
149  *              pq_init - initialize libpq at backend startup
150  * --------------------------------
151  */
152 void
153 pq_init(void)
154 {
155         PqSendBufferSize = PQ_SEND_BUFFER_SIZE;
156         PqSendBuffer = MemoryContextAlloc(TopMemoryContext, PqSendBufferSize);
157         PqSendPointer = PqSendStart = PqRecvPointer = PqRecvLength = 0;
158         PqCommBusy = false;
159         DoingCopyOut = false;
160         on_proc_exit(pq_close, 0);
161 }
162
163 /* --------------------------------
164  *              pq_comm_reset - reset libpq during error recovery
165  *
166  * This is called from error recovery at the outer idle loop.  It's
167  * just to get us out of trouble if we somehow manage to elog() from
168  * inside a pqcomm.c routine (which ideally will never happen, but...)
169  * --------------------------------
170  */
171 void
172 pq_comm_reset(void)
173 {
174         /* Do not throw away pending data, but do reset the busy flag */
175         PqCommBusy = false;
176         /* We can abort any old-style COPY OUT, too */
177         pq_endcopyout(true);
178 }
179
180 /* --------------------------------
181  *              pq_close - shutdown libpq at backend exit
182  *
183  * Note: in a standalone backend MyProcPort will be null,
184  * don't crash during exit...
185  * --------------------------------
186  */
187 static void
188 pq_close(int code, Datum arg)
189 {
190         if (MyProcPort != NULL)
191         {
192 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
193 #ifdef ENABLE_GSS
194                 OM_uint32       min_s;
195
196                 /* Shutdown GSSAPI layer */
197                 if (MyProcPort->gss->ctx != GSS_C_NO_CONTEXT)
198                         gss_delete_sec_context(&min_s, &MyProcPort->gss->ctx, NULL);
199
200                 if (MyProcPort->gss->cred != GSS_C_NO_CREDENTIAL)
201                         gss_release_cred(&min_s, &MyProcPort->gss->cred);
202 #endif   /* ENABLE_GSS */
203                 /* GSS and SSPI share the port->gss struct */
204
205                 free(MyProcPort->gss);
206 #endif   /* ENABLE_GSS || ENABLE_SSPI */
207
208                 /* Cleanly shut down SSL layer */
209                 secure_close(MyProcPort);
210
211                 /*
212                  * Formerly we did an explicit close() here, but it seems better to
213                  * leave the socket open until the process dies.  This allows clients
214                  * to perform a "synchronous close" if they care --- wait till the
215                  * transport layer reports connection closure, and you can be sure the
216                  * backend has exited.
217                  *
218                  * We do set sock to PGINVALID_SOCKET to prevent any further I/O,
219                  * though.
220                  */
221                 MyProcPort->sock = PGINVALID_SOCKET;
222         }
223 }
224
225
226
227 /*
228  * Streams -- wrapper around Unix socket system calls
229  *
230  *
231  *              Stream functions are used for vanilla TCP connection protocol.
232  */
233
234
235 /* StreamDoUnlink()
236  * Shutdown routine for backend connection
237  * If a Unix socket is used for communication, explicitly close it.
238  */
239 #ifdef HAVE_UNIX_SOCKETS
240 static void
241 StreamDoUnlink(int code, Datum arg)
242 {
243         Assert(sock_path[0]);
244         unlink(sock_path);
245 }
246 #endif   /* HAVE_UNIX_SOCKETS */
247
248 /*
249  * StreamServerPort -- open a "listening" port to accept connections.
250  *
251  * Successfully opened sockets are added to the ListenSocket[] array,
252  * at the first position that isn't PGINVALID_SOCKET.
253  *
254  * RETURNS: STATUS_OK or STATUS_ERROR
255  */
256
257 int
258 StreamServerPort(int family, char *hostName, unsigned short portNumber,
259                                  char *unixSocketName,
260                                  pgsocket ListenSocket[], int MaxListen)
261 {
262         pgsocket        fd;
263         int                     err;
264         int                     maxconn;
265         int                     ret;
266         char            portNumberStr[32];
267         const char *familyDesc;
268         char            familyDescBuf[64];
269         char       *service;
270         struct addrinfo *addrs = NULL,
271                            *addr;
272         struct addrinfo hint;
273         int                     listen_index = 0;
274         int                     added = 0;
275
276 #if !defined(WIN32) || defined(IPV6_V6ONLY)
277         int                     one = 1;
278 #endif
279
280         /* Initialize hint structure */
281         MemSet(&hint, 0, sizeof(hint));
282         hint.ai_family = family;
283         hint.ai_flags = AI_PASSIVE;
284         hint.ai_socktype = SOCK_STREAM;
285
286 #ifdef HAVE_UNIX_SOCKETS
287         if (family == AF_UNIX)
288         {
289                 /* Lock_AF_UNIX will also fill in sock_path. */
290                 if (Lock_AF_UNIX(portNumber, unixSocketName) != STATUS_OK)
291                         return STATUS_ERROR;
292                 service = sock_path;
293         }
294         else
295 #endif   /* HAVE_UNIX_SOCKETS */
296         {
297                 snprintf(portNumberStr, sizeof(portNumberStr), "%d", portNumber);
298                 service = portNumberStr;
299         }
300
301         ret = pg_getaddrinfo_all(hostName, service, &hint, &addrs);
302         if (ret || !addrs)
303         {
304                 if (hostName)
305                         ereport(LOG,
306                                         (errmsg("could not translate host name \"%s\", service \"%s\" to address: %s",
307                                                         hostName, service, gai_strerror(ret))));
308                 else
309                         ereport(LOG,
310                                  (errmsg("could not translate service \"%s\" to address: %s",
311                                                  service, gai_strerror(ret))));
312                 if (addrs)
313                         pg_freeaddrinfo_all(hint.ai_family, addrs);
314                 return STATUS_ERROR;
315         }
316
317         for (addr = addrs; addr; addr = addr->ai_next)
318         {
319                 if (!IS_AF_UNIX(family) && IS_AF_UNIX(addr->ai_family))
320                 {
321                         /*
322                          * Only set up a unix domain socket when they really asked for it.
323                          * The service/port is different in that case.
324                          */
325                         continue;
326                 }
327
328                 /* See if there is still room to add 1 more socket. */
329                 for (; listen_index < MaxListen; listen_index++)
330                 {
331                         if (ListenSocket[listen_index] == PGINVALID_SOCKET)
332                                 break;
333                 }
334                 if (listen_index >= MaxListen)
335                 {
336                         ereport(LOG,
337                                         (errmsg("could not bind to all requested addresses: MAXLISTEN (%d) exceeded",
338                                                         MaxListen)));
339                         break;
340                 }
341
342                 /* set up family name for possible error messages */
343                 switch (addr->ai_family)
344                 {
345                         case AF_INET:
346                                 familyDesc = _("IPv4");
347                                 break;
348 #ifdef HAVE_IPV6
349                         case AF_INET6:
350                                 familyDesc = _("IPv6");
351                                 break;
352 #endif
353 #ifdef HAVE_UNIX_SOCKETS
354                         case AF_UNIX:
355                                 familyDesc = _("Unix");
356                                 break;
357 #endif
358                         default:
359                                 snprintf(familyDescBuf, sizeof(familyDescBuf),
360                                                  _("unrecognized address family %d"),
361                                                  addr->ai_family);
362                                 familyDesc = familyDescBuf;
363                                 break;
364                 }
365
366                 if ((fd = socket(addr->ai_family, SOCK_STREAM, 0)) < 0)
367                 {
368                         ereport(LOG,
369                                         (errcode_for_socket_access(),
370                         /* translator: %s is IPv4, IPv6, or Unix */
371                                          errmsg("could not create %s socket: %m",
372                                                         familyDesc)));
373                         continue;
374                 }
375
376 #ifndef WIN32
377
378                 /*
379                  * Without the SO_REUSEADDR flag, a new postmaster can't be started
380                  * right away after a stop or crash, giving "address already in use"
381                  * error on TCP ports.
382                  *
383                  * On win32, however, this behavior only happens if the
384                  * SO_EXLUSIVEADDRUSE is set. With SO_REUSEADDR, win32 allows multiple
385                  * servers to listen on the same address, resulting in unpredictable
386                  * behavior. With no flags at all, win32 behaves as Unix with
387                  * SO_REUSEADDR.
388                  */
389                 if (!IS_AF_UNIX(addr->ai_family))
390                 {
391                         if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
392                                                         (char *) &one, sizeof(one))) == -1)
393                         {
394                                 ereport(LOG,
395                                                 (errcode_for_socket_access(),
396                                                  errmsg("setsockopt(SO_REUSEADDR) failed: %m")));
397                                 closesocket(fd);
398                                 continue;
399                         }
400                 }
401 #endif
402
403 #ifdef IPV6_V6ONLY
404                 if (addr->ai_family == AF_INET6)
405                 {
406                         if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
407                                                    (char *) &one, sizeof(one)) == -1)
408                         {
409                                 ereport(LOG,
410                                                 (errcode_for_socket_access(),
411                                                  errmsg("setsockopt(IPV6_V6ONLY) failed: %m")));
412                                 closesocket(fd);
413                                 continue;
414                         }
415                 }
416 #endif
417
418                 /*
419                  * Note: This might fail on some OS's, like Linux older than
420                  * 2.4.21-pre3, that don't have the IPV6_V6ONLY socket option, and map
421                  * ipv4 addresses to ipv6.      It will show ::ffff:ipv4 for all ipv4
422                  * connections.
423                  */
424                 err = bind(fd, addr->ai_addr, addr->ai_addrlen);
425                 if (err < 0)
426                 {
427                         ereport(LOG,
428                                         (errcode_for_socket_access(),
429                         /* translator: %s is IPv4, IPv6, or Unix */
430                                          errmsg("could not bind %s socket: %m",
431                                                         familyDesc),
432                                          (IS_AF_UNIX(addr->ai_family)) ?
433                                   errhint("Is another postmaster already running on port %d?"
434                                                   " If not, remove socket file \"%s\" and retry.",
435                                                   (int) portNumber, sock_path) :
436                                   errhint("Is another postmaster already running on port %d?"
437                                                   " If not, wait a few seconds and retry.",
438                                                   (int) portNumber)));
439                         closesocket(fd);
440                         continue;
441                 }
442
443 #ifdef HAVE_UNIX_SOCKETS
444                 if (addr->ai_family == AF_UNIX)
445                 {
446                         if (Setup_AF_UNIX() != STATUS_OK)
447                         {
448                                 closesocket(fd);
449                                 break;
450                         }
451                 }
452 #endif
453
454                 /*
455                  * Select appropriate accept-queue length limit.  PG_SOMAXCONN is only
456                  * intended to provide a clamp on the request on platforms where an
457                  * overly large request provokes a kernel error (are there any?).
458                  */
459                 maxconn = MaxBackends * 2;
460                 if (maxconn > PG_SOMAXCONN)
461                         maxconn = PG_SOMAXCONN;
462
463                 err = listen(fd, maxconn);
464                 if (err < 0)
465                 {
466                         ereport(LOG,
467                                         (errcode_for_socket_access(),
468                         /* translator: %s is IPv4, IPv6, or Unix */
469                                          errmsg("could not listen on %s socket: %m",
470                                                         familyDesc)));
471                         closesocket(fd);
472                         continue;
473                 }
474                 ListenSocket[listen_index] = fd;
475                 added++;
476         }
477
478         pg_freeaddrinfo_all(hint.ai_family, addrs);
479
480         if (!added)
481                 return STATUS_ERROR;
482
483         return STATUS_OK;
484 }
485
486
487 #ifdef HAVE_UNIX_SOCKETS
488
489 /*
490  * Lock_AF_UNIX -- configure unix socket file path
491  */
492 static int
493 Lock_AF_UNIX(unsigned short portNumber, char *unixSocketName)
494 {
495         UNIXSOCK_PATH(sock_path, portNumber, unixSocketName);
496
497         /*
498          * Grab an interlock file associated with the socket file.
499          *
500          * Note: there are two reasons for using a socket lock file, rather than
501          * trying to interlock directly on the socket itself.  First, it's a lot
502          * more portable, and second, it lets us remove any pre-existing socket
503          * file without race conditions.
504          */
505         CreateSocketLockFile(sock_path, true);
506
507         /*
508          * Once we have the interlock, we can safely delete any pre-existing
509          * socket file to avoid failure at bind() time.
510          */
511         unlink(sock_path);
512
513         return STATUS_OK;
514 }
515
516
517 /*
518  * Setup_AF_UNIX -- configure unix socket permissions
519  */
520 static int
521 Setup_AF_UNIX(void)
522 {
523         /* Arrange to unlink the socket file at exit */
524         on_proc_exit(StreamDoUnlink, 0);
525
526         /*
527          * Fix socket ownership/permission if requested.  Note we must do this
528          * before we listen() to avoid a window where unwanted connections could
529          * get accepted.
530          */
531         Assert(Unix_socket_group);
532         if (Unix_socket_group[0] != '\0')
533         {
534 #ifdef WIN32
535                 elog(WARNING, "configuration item unix_socket_group is not supported on this platform");
536 #else
537                 char       *endptr;
538                 unsigned long val;
539                 gid_t           gid;
540
541                 val = strtoul(Unix_socket_group, &endptr, 10);
542                 if (*endptr == '\0')
543                 {                                               /* numeric group id */
544                         gid = val;
545                 }
546                 else
547                 {                                               /* convert group name to id */
548                         struct group *gr;
549
550                         gr = getgrnam(Unix_socket_group);
551                         if (!gr)
552                         {
553                                 ereport(LOG,
554                                                 (errmsg("group \"%s\" does not exist",
555                                                                 Unix_socket_group)));
556                                 return STATUS_ERROR;
557                         }
558                         gid = gr->gr_gid;
559                 }
560                 if (chown(sock_path, -1, gid) == -1)
561                 {
562                         ereport(LOG,
563                                         (errcode_for_file_access(),
564                                          errmsg("could not set group of file \"%s\": %m",
565                                                         sock_path)));
566                         return STATUS_ERROR;
567                 }
568 #endif
569         }
570
571         if (chmod(sock_path, Unix_socket_permissions) == -1)
572         {
573                 ereport(LOG,
574                                 (errcode_for_file_access(),
575                                  errmsg("could not set permissions of file \"%s\": %m",
576                                                 sock_path)));
577                 return STATUS_ERROR;
578         }
579         return STATUS_OK;
580 }
581 #endif   /* HAVE_UNIX_SOCKETS */
582
583
584 /*
585  * StreamConnection -- create a new connection with client using
586  *              server port.  Set port->sock to the FD of the new connection.
587  *
588  * ASSUME: that this doesn't need to be non-blocking because
589  *              the Postmaster uses select() to tell when the server master
590  *              socket is ready for accept().
591  *
592  * RETURNS: STATUS_OK or STATUS_ERROR
593  */
594 int
595 StreamConnection(pgsocket server_fd, Port *port)
596 {
597         /* accept connection and fill in the client (remote) address */
598         port->raddr.salen = sizeof(port->raddr.addr);
599         if ((port->sock = accept(server_fd,
600                                                          (struct sockaddr *) & port->raddr.addr,
601                                                          &port->raddr.salen)) < 0)
602         {
603                 ereport(LOG,
604                                 (errcode_for_socket_access(),
605                                  errmsg("could not accept new connection: %m")));
606
607                 /*
608                  * If accept() fails then postmaster.c will still see the server
609                  * socket as read-ready, and will immediately try again.  To avoid
610                  * uselessly sucking lots of CPU, delay a bit before trying again.
611                  * (The most likely reason for failure is being out of kernel file
612                  * table slots; we can do little except hope some will get freed up.)
613                  */
614                 pg_usleep(100000L);             /* wait 0.1 sec */
615                 return STATUS_ERROR;
616         }
617
618 #ifdef SCO_ACCEPT_BUG
619
620         /*
621          * UnixWare 7+ and OpenServer 5.0.4 are known to have this bug, but it
622          * shouldn't hurt to catch it for all versions of those platforms.
623          */
624         if (port->raddr.addr.ss_family == 0)
625                 port->raddr.addr.ss_family = AF_UNIX;
626 #endif
627
628         /* fill in the server (local) address */
629         port->laddr.salen = sizeof(port->laddr.addr);
630         if (getsockname(port->sock,
631                                         (struct sockaddr *) & port->laddr.addr,
632                                         &port->laddr.salen) < 0)
633         {
634                 elog(LOG, "getsockname() failed: %m");
635                 return STATUS_ERROR;
636         }
637
638         /* select NODELAY and KEEPALIVE options if it's a TCP connection */
639         if (!IS_AF_UNIX(port->laddr.addr.ss_family))
640         {
641                 int                     on;
642
643 #ifdef  TCP_NODELAY
644                 on = 1;
645                 if (setsockopt(port->sock, IPPROTO_TCP, TCP_NODELAY,
646                                            (char *) &on, sizeof(on)) < 0)
647                 {
648                         elog(LOG, "setsockopt(TCP_NODELAY) failed: %m");
649                         return STATUS_ERROR;
650                 }
651 #endif
652                 on = 1;
653                 if (setsockopt(port->sock, SOL_SOCKET, SO_KEEPALIVE,
654                                            (char *) &on, sizeof(on)) < 0)
655                 {
656                         elog(LOG, "setsockopt(SO_KEEPALIVE) failed: %m");
657                         return STATUS_ERROR;
658                 }
659
660 #ifdef WIN32
661
662                 /*
663                  * This is a Win32 socket optimization.  The ideal size is 32k.
664                  * http://support.microsoft.com/kb/823764/EN-US/
665                  */
666                 on = PQ_SEND_BUFFER_SIZE * 4;
667                 if (setsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &on,
668                                            sizeof(on)) < 0)
669                 {
670                         elog(LOG, "setsockopt(SO_SNDBUF) failed: %m");
671                         return STATUS_ERROR;
672                 }
673 #endif
674
675                 /*
676                  * Also apply the current keepalive parameters.  If we fail to set a
677                  * parameter, don't error out, because these aren't universally
678                  * supported.  (Note: you might think we need to reset the GUC
679                  * variables to 0 in such a case, but it's not necessary because the
680                  * show hooks for these variables report the truth anyway.)
681                  */
682                 (void) pq_setkeepalivesidle(tcp_keepalives_idle, port);
683                 (void) pq_setkeepalivesinterval(tcp_keepalives_interval, port);
684                 (void) pq_setkeepalivescount(tcp_keepalives_count, port);
685         }
686
687         return STATUS_OK;
688 }
689
690 /*
691  * StreamClose -- close a client/backend connection
692  *
693  * NOTE: this is NOT used to terminate a session; it is just used to release
694  * the file descriptor in a process that should no longer have the socket
695  * open.  (For example, the postmaster calls this after passing ownership
696  * of the connection to a child process.)  It is expected that someone else
697  * still has the socket open.  So, we only want to close the descriptor,
698  * we do NOT want to send anything to the far end.
699  */
700 void
701 StreamClose(pgsocket sock)
702 {
703         closesocket(sock);
704 }
705
706 /*
707  * TouchSocketFile -- mark socket file as recently accessed
708  *
709  * This routine should be called every so often to ensure that the socket
710  * file has a recent mod date (ordinary operations on sockets usually won't
711  * change the mod date).  That saves it from being removed by
712  * overenthusiastic /tmp-directory-cleaner daemons.  (Another reason we should
713  * never have put the socket file in /tmp...)
714  */
715 void
716 TouchSocketFile(void)
717 {
718         /* Do nothing if we did not create a socket... */
719         if (sock_path[0] != '\0')
720         {
721                 /*
722                  * utime() is POSIX standard, utimes() is a common alternative. If we
723                  * have neither, there's no way to affect the mod or access time of
724                  * the socket :-(
725                  *
726                  * In either path, we ignore errors; there's no point in complaining.
727                  */
728 #ifdef HAVE_UTIME
729                 utime(sock_path, NULL);
730 #else                                                   /* !HAVE_UTIME */
731 #ifdef HAVE_UTIMES
732                 utimes(sock_path, NULL);
733 #endif   /* HAVE_UTIMES */
734 #endif   /* HAVE_UTIME */
735         }
736 }
737
738
739 /* --------------------------------
740  * Low-level I/O routines begin here.
741  *
742  * These routines communicate with a frontend client across a connection
743  * already established by the preceding routines.
744  * --------------------------------
745  */
746
747 /* --------------------------------
748  *                        pq_set_nonblocking - set socket blocking/non-blocking
749  *
750  * Sets the socket non-blocking if nonblocking is TRUE, or sets it
751  * blocking otherwise.
752  * --------------------------------
753  */
754 static void
755 pq_set_nonblocking(bool nonblocking)
756 {
757         if (MyProcPort->noblock == nonblocking)
758                 return;
759
760 #ifdef WIN32
761         pgwin32_noblock = nonblocking ? 1 : 0;
762 #else
763
764         /*
765          * Use COMMERROR on failure, because ERROR would try to send the error to
766          * the client, which might require changing the mode again, leading to
767          * infinite recursion.
768          */
769         if (nonblocking)
770         {
771                 if (!pg_set_noblock(MyProcPort->sock))
772                         ereport(COMMERROR,
773                                   (errmsg("could not set socket to non-blocking mode: %m")));
774         }
775         else
776         {
777                 if (!pg_set_block(MyProcPort->sock))
778                         ereport(COMMERROR,
779                                         (errmsg("could not set socket to blocking mode: %m")));
780         }
781 #endif
782         MyProcPort->noblock = nonblocking;
783 }
784
785 /* --------------------------------
786  *              pq_recvbuf - load some bytes into the input buffer
787  *
788  *              returns 0 if OK, EOF if trouble
789  * --------------------------------
790  */
791 static int
792 pq_recvbuf(void)
793 {
794         if (PqRecvPointer > 0)
795         {
796                 if (PqRecvLength > PqRecvPointer)
797                 {
798                         /* still some unread data, left-justify it in the buffer */
799                         memmove(PqRecvBuffer, PqRecvBuffer + PqRecvPointer,
800                                         PqRecvLength - PqRecvPointer);
801                         PqRecvLength -= PqRecvPointer;
802                         PqRecvPointer = 0;
803                 }
804                 else
805                         PqRecvLength = PqRecvPointer = 0;
806         }
807
808         /* Ensure that we're in blocking mode */
809         pq_set_nonblocking(false);
810
811         /* Can fill buffer from PqRecvLength and upwards */
812         for (;;)
813         {
814                 int                     r;
815
816                 r = secure_read(MyProcPort, PqRecvBuffer + PqRecvLength,
817                                                 PQ_RECV_BUFFER_SIZE - PqRecvLength);
818
819                 if (r < 0)
820                 {
821                         if (errno == EINTR)
822                                 continue;               /* Ok if interrupted */
823
824                         /*
825                          * Careful: an ereport() that tries to write to the client would
826                          * cause recursion to here, leading to stack overflow and core
827                          * dump!  This message must go *only* to the postmaster log.
828                          */
829                         ereport(COMMERROR,
830                                         (errcode_for_socket_access(),
831                                          errmsg("could not receive data from client: %m")));
832                         return EOF;
833                 }
834                 if (r == 0)
835                 {
836                         /*
837                          * EOF detected.  We used to write a log message here, but it's
838                          * better to expect the ultimate caller to do that.
839                          */
840                         return EOF;
841                 }
842                 /* r contains number of bytes read, so just incr length */
843                 PqRecvLength += r;
844                 return 0;
845         }
846 }
847
848 /* --------------------------------
849  *              pq_getbyte      - get a single byte from connection, or return EOF
850  * --------------------------------
851  */
852 int
853 pq_getbyte(void)
854 {
855         while (PqRecvPointer >= PqRecvLength)
856         {
857                 if (pq_recvbuf())               /* If nothing in buffer, then recv some */
858                         return EOF;                     /* Failed to recv data */
859         }
860         return (unsigned char) PqRecvBuffer[PqRecvPointer++];
861 }
862
863 /* --------------------------------
864  *              pq_peekbyte             - peek at next byte from connection
865  *
866  *       Same as pq_getbyte() except we don't advance the pointer.
867  * --------------------------------
868  */
869 int
870 pq_peekbyte(void)
871 {
872         while (PqRecvPointer >= PqRecvLength)
873         {
874                 if (pq_recvbuf())               /* If nothing in buffer, then recv some */
875                         return EOF;                     /* Failed to recv data */
876         }
877         return (unsigned char) PqRecvBuffer[PqRecvPointer];
878 }
879
880 /* --------------------------------
881  *              pq_getbyte_if_available - get a single byte from connection,
882  *                      if available
883  *
884  * The received byte is stored in *c. Returns 1 if a byte was read,
885  * 0 if no data was available, or EOF if trouble.
886  * --------------------------------
887  */
888 int
889 pq_getbyte_if_available(unsigned char *c)
890 {
891         int                     r;
892
893         if (PqRecvPointer < PqRecvLength)
894         {
895                 *c = PqRecvBuffer[PqRecvPointer++];
896                 return 1;
897         }
898
899         /* Put the socket into non-blocking mode */
900         pq_set_nonblocking(true);
901
902         r = secure_read(MyProcPort, c, 1);
903         if (r < 0)
904         {
905                 /*
906                  * Ok if no data available without blocking or interrupted (though
907                  * EINTR really shouldn't happen with a non-blocking socket). Report
908                  * other errors.
909                  */
910                 if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
911                         r = 0;
912                 else
913                 {
914                         /*
915                          * Careful: an ereport() that tries to write to the client would
916                          * cause recursion to here, leading to stack overflow and core
917                          * dump!  This message must go *only* to the postmaster log.
918                          */
919                         ereport(COMMERROR,
920                                         (errcode_for_socket_access(),
921                                          errmsg("could not receive data from client: %m")));
922                         r = EOF;
923                 }
924         }
925         else if (r == 0)
926         {
927                 /* EOF detected */
928                 r = EOF;
929         }
930
931         return r;
932 }
933
934 /* --------------------------------
935  *              pq_getbytes             - get a known number of bytes from connection
936  *
937  *              returns 0 if OK, EOF if trouble
938  * --------------------------------
939  */
940 int
941 pq_getbytes(char *s, size_t len)
942 {
943         size_t          amount;
944
945         while (len > 0)
946         {
947                 while (PqRecvPointer >= PqRecvLength)
948                 {
949                         if (pq_recvbuf())       /* If nothing in buffer, then recv some */
950                                 return EOF;             /* Failed to recv data */
951                 }
952                 amount = PqRecvLength - PqRecvPointer;
953                 if (amount > len)
954                         amount = len;
955                 memcpy(s, PqRecvBuffer + PqRecvPointer, amount);
956                 PqRecvPointer += amount;
957                 s += amount;
958                 len -= amount;
959         }
960         return 0;
961 }
962
963 /* --------------------------------
964  *              pq_discardbytes         - throw away a known number of bytes
965  *
966  *              same as pq_getbytes except we do not copy the data to anyplace.
967  *              this is used for resynchronizing after read errors.
968  *
969  *              returns 0 if OK, EOF if trouble
970  * --------------------------------
971  */
972 static int
973 pq_discardbytes(size_t len)
974 {
975         size_t          amount;
976
977         while (len > 0)
978         {
979                 while (PqRecvPointer >= PqRecvLength)
980                 {
981                         if (pq_recvbuf())       /* If nothing in buffer, then recv some */
982                                 return EOF;             /* Failed to recv data */
983                 }
984                 amount = PqRecvLength - PqRecvPointer;
985                 if (amount > len)
986                         amount = len;
987                 PqRecvPointer += amount;
988                 len -= amount;
989         }
990         return 0;
991 }
992
993 /* --------------------------------
994  *              pq_getstring    - get a null terminated string from connection
995  *
996  *              The return value is placed in an expansible StringInfo, which has
997  *              already been initialized by the caller.
998  *
999  *              This is used only for dealing with old-protocol clients.  The idea
1000  *              is to produce a StringInfo that looks the same as we would get from
1001  *              pq_getmessage() with a newer client; we will then process it with
1002  *              pq_getmsgstring.  Therefore, no character set conversion is done here,
1003  *              even though this is presumably useful only for text.
1004  *
1005  *              returns 0 if OK, EOF if trouble
1006  * --------------------------------
1007  */
1008 int
1009 pq_getstring(StringInfo s)
1010 {
1011         int                     i;
1012
1013         resetStringInfo(s);
1014
1015         /* Read until we get the terminating '\0' */
1016         for (;;)
1017         {
1018                 while (PqRecvPointer >= PqRecvLength)
1019                 {
1020                         if (pq_recvbuf())       /* If nothing in buffer, then recv some */
1021                                 return EOF;             /* Failed to recv data */
1022                 }
1023
1024                 for (i = PqRecvPointer; i < PqRecvLength; i++)
1025                 {
1026                         if (PqRecvBuffer[i] == '\0')
1027                         {
1028                                 /* include the '\0' in the copy */
1029                                 appendBinaryStringInfo(s, PqRecvBuffer + PqRecvPointer,
1030                                                                            i - PqRecvPointer + 1);
1031                                 PqRecvPointer = i + 1;  /* advance past \0 */
1032                                 return 0;
1033                         }
1034                 }
1035
1036                 /* If we're here we haven't got the \0 in the buffer yet. */
1037                 appendBinaryStringInfo(s, PqRecvBuffer + PqRecvPointer,
1038                                                            PqRecvLength - PqRecvPointer);
1039                 PqRecvPointer = PqRecvLength;
1040         }
1041 }
1042
1043
1044 /* --------------------------------
1045  *              pq_getmessage   - get a message with length word from connection
1046  *
1047  *              The return value is placed in an expansible StringInfo, which has
1048  *              already been initialized by the caller.
1049  *              Only the message body is placed in the StringInfo; the length word
1050  *              is removed.  Also, s->cursor is initialized to zero for convenience
1051  *              in scanning the message contents.
1052  *
1053  *              If maxlen is not zero, it is an upper limit on the length of the
1054  *              message we are willing to accept.  We abort the connection (by
1055  *              returning EOF) if client tries to send more than that.
1056  *
1057  *              returns 0 if OK, EOF if trouble
1058  * --------------------------------
1059  */
1060 int
1061 pq_getmessage(StringInfo s, int maxlen)
1062 {
1063         int32           len;
1064
1065         resetStringInfo(s);
1066
1067         /* Read message length word */
1068         if (pq_getbytes((char *) &len, 4) == EOF)
1069         {
1070                 ereport(COMMERROR,
1071                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1072                                  errmsg("unexpected EOF within message length word")));
1073                 return EOF;
1074         }
1075
1076         len = ntohl(len);
1077
1078         if (len < 4 ||
1079                 (maxlen > 0 && len > maxlen))
1080         {
1081                 ereport(COMMERROR,
1082                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1083                                  errmsg("invalid message length")));
1084                 return EOF;
1085         }
1086
1087         len -= 4;                                       /* discount length itself */
1088
1089         if (len > 0)
1090         {
1091                 /*
1092                  * Allocate space for message.  If we run out of room (ridiculously
1093                  * large message), we will elog(ERROR), but we want to discard the
1094                  * message body so as not to lose communication sync.
1095                  */
1096                 PG_TRY();
1097                 {
1098                         enlargeStringInfo(s, len);
1099                 }
1100                 PG_CATCH();
1101                 {
1102                         if (pq_discardbytes(len) == EOF)
1103                                 ereport(COMMERROR,
1104                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1105                                                  errmsg("incomplete message from client")));
1106                         PG_RE_THROW();
1107                 }
1108                 PG_END_TRY();
1109
1110                 /* And grab the message */
1111                 if (pq_getbytes(s->data, len) == EOF)
1112                 {
1113                         ereport(COMMERROR,
1114                                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
1115                                          errmsg("incomplete message from client")));
1116                         return EOF;
1117                 }
1118                 s->len = len;
1119                 /* Place a trailing null per StringInfo convention */
1120                 s->data[len] = '\0';
1121         }
1122
1123         return 0;
1124 }
1125
1126
1127 /* --------------------------------
1128  *              pq_putbytes             - send bytes to connection (not flushed until pq_flush)
1129  *
1130  *              returns 0 if OK, EOF if trouble
1131  * --------------------------------
1132  */
1133 int
1134 pq_putbytes(const char *s, size_t len)
1135 {
1136         int                     res;
1137
1138         /* Should only be called by old-style COPY OUT */
1139         Assert(DoingCopyOut);
1140         /* No-op if reentrant call */
1141         if (PqCommBusy)
1142                 return 0;
1143         PqCommBusy = true;
1144         res = internal_putbytes(s, len);
1145         PqCommBusy = false;
1146         return res;
1147 }
1148
1149 static int
1150 internal_putbytes(const char *s, size_t len)
1151 {
1152         size_t          amount;
1153
1154         while (len > 0)
1155         {
1156                 /* If buffer is full, then flush it out */
1157                 if (PqSendPointer >= PqSendBufferSize)
1158                 {
1159                         pq_set_nonblocking(false);
1160                         if (internal_flush())
1161                                 return EOF;
1162                 }
1163                 amount = PqSendBufferSize - PqSendPointer;
1164                 if (amount > len)
1165                         amount = len;
1166                 memcpy(PqSendBuffer + PqSendPointer, s, amount);
1167                 PqSendPointer += amount;
1168                 s += amount;
1169                 len -= amount;
1170         }
1171         return 0;
1172 }
1173
1174 /* --------------------------------
1175  *              pq_flush                - flush pending output
1176  *
1177  *              returns 0 if OK, EOF if trouble
1178  * --------------------------------
1179  */
1180 int
1181 pq_flush(void)
1182 {
1183         int                     res;
1184
1185         /* No-op if reentrant call */
1186         if (PqCommBusy)
1187                 return 0;
1188         PqCommBusy = true;
1189         pq_set_nonblocking(false);
1190         res = internal_flush();
1191         PqCommBusy = false;
1192         return res;
1193 }
1194
1195 /* --------------------------------
1196  *              internal_flush - flush pending output
1197  *
1198  * Returns 0 if OK (meaning everything was sent, or operation would block
1199  * and the socket is in non-blocking mode), or EOF if trouble.
1200  * --------------------------------
1201  */
1202 static int
1203 internal_flush(void)
1204 {
1205         static int      last_reported_send_errno = 0;
1206
1207         char       *bufptr = PqSendBuffer + PqSendStart;
1208         char       *bufend = PqSendBuffer + PqSendPointer;
1209
1210         while (bufptr < bufend)
1211         {
1212                 int                     r;
1213
1214                 r = secure_write(MyProcPort, bufptr, bufend - bufptr);
1215
1216                 if (r <= 0)
1217                 {
1218                         if (errno == EINTR)
1219                                 continue;               /* Ok if we were interrupted */
1220
1221                         /*
1222                          * Ok if no data writable without blocking, and the socket is in
1223                          * non-blocking mode.
1224                          */
1225                         if (errno == EAGAIN ||
1226                                 errno == EWOULDBLOCK)
1227                         {
1228                                 return 0;
1229                         }
1230
1231                         /*
1232                          * Careful: an ereport() that tries to write to the client would
1233                          * cause recursion to here, leading to stack overflow and core
1234                          * dump!  This message must go *only* to the postmaster log.
1235                          *
1236                          * If a client disconnects while we're in the midst of output, we
1237                          * might write quite a bit of data before we get to a safe query
1238                          * abort point.  So, suppress duplicate log messages.
1239                          */
1240                         if (errno != last_reported_send_errno)
1241                         {
1242                                 last_reported_send_errno = errno;
1243                                 ereport(COMMERROR,
1244                                                 (errcode_for_socket_access(),
1245                                                  errmsg("could not send data to client: %m")));
1246                         }
1247
1248                         /*
1249                          * We drop the buffered data anyway so that processing can
1250                          * continue, even though we'll probably quit soon. We also set a
1251                          * flag that'll cause the next CHECK_FOR_INTERRUPTS to terminate
1252                          * the connection.
1253                          */
1254                         PqSendStart = PqSendPointer = 0;
1255                         ClientConnectionLost = 1;
1256                         InterruptPending = 1;
1257                         return EOF;
1258                 }
1259
1260                 last_reported_send_errno = 0;   /* reset after any successful send */
1261                 bufptr += r;
1262                 PqSendStart += r;
1263         }
1264
1265         PqSendStart = PqSendPointer = 0;
1266         return 0;
1267 }
1268
1269 /* --------------------------------
1270  *              pq_flush_if_writable - flush pending output if writable without blocking
1271  *
1272  * Returns 0 if OK, or EOF if trouble.
1273  * --------------------------------
1274  */
1275 int
1276 pq_flush_if_writable(void)
1277 {
1278         int                     res;
1279
1280         /* Quick exit if nothing to do */
1281         if (PqSendPointer == PqSendStart)
1282                 return 0;
1283
1284         /* No-op if reentrant call */
1285         if (PqCommBusy)
1286                 return 0;
1287
1288         /* Temporarily put the socket into non-blocking mode */
1289         pq_set_nonblocking(true);
1290
1291         PqCommBusy = true;
1292         res = internal_flush();
1293         PqCommBusy = false;
1294         return res;
1295 }
1296
1297 /* --------------------------------
1298  *              pq_is_send_pending      - is there any pending data in the output buffer?
1299  * --------------------------------
1300  */
1301 bool
1302 pq_is_send_pending(void)
1303 {
1304         return (PqSendStart < PqSendPointer);
1305 }
1306
1307 /* --------------------------------
1308  * Message-level I/O routines begin here.
1309  *
1310  * These routines understand about the old-style COPY OUT protocol.
1311  * --------------------------------
1312  */
1313
1314
1315 /* --------------------------------
1316  *              pq_putmessage   - send a normal message (suppressed in COPY OUT mode)
1317  *
1318  *              If msgtype is not '\0', it is a message type code to place before
1319  *              the message body.  If msgtype is '\0', then the message has no type
1320  *              code (this is only valid in pre-3.0 protocols).
1321  *
1322  *              len is the length of the message body data at *s.  In protocol 3.0
1323  *              and later, a message length word (equal to len+4 because it counts
1324  *              itself too) is inserted by this routine.
1325  *
1326  *              All normal messages are suppressed while old-style COPY OUT is in
1327  *              progress.  (In practice only a few notice messages might get emitted
1328  *              then; dropping them is annoying, but at least they will still appear
1329  *              in the postmaster log.)
1330  *
1331  *              We also suppress messages generated while pqcomm.c is busy.  This
1332  *              avoids any possibility of messages being inserted within other
1333  *              messages.  The only known trouble case arises if SIGQUIT occurs
1334  *              during a pqcomm.c routine --- quickdie() will try to send a warning
1335  *              message, and the most reasonable approach seems to be to drop it.
1336  *
1337  *              returns 0 if OK, EOF if trouble
1338  * --------------------------------
1339  */
1340 int
1341 pq_putmessage(char msgtype, const char *s, size_t len)
1342 {
1343         if (DoingCopyOut || PqCommBusy)
1344                 return 0;
1345         PqCommBusy = true;
1346         if (msgtype)
1347                 if (internal_putbytes(&msgtype, 1))
1348                         goto fail;
1349         if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
1350         {
1351                 uint32          n32;
1352
1353                 n32 = htonl((uint32) (len + 4));
1354                 if (internal_putbytes((char *) &n32, 4))
1355                         goto fail;
1356         }
1357         if (internal_putbytes(s, len))
1358                 goto fail;
1359         PqCommBusy = false;
1360         return 0;
1361
1362 fail:
1363         PqCommBusy = false;
1364         return EOF;
1365 }
1366
1367 /* --------------------------------
1368  *              pq_putmessage_noblock   - like pq_putmessage, but never blocks
1369  *
1370  *              If the output buffer is too small to hold the message, the buffer
1371  *              is enlarged.
1372  */
1373 void
1374 pq_putmessage_noblock(char msgtype, const char *s, size_t len)
1375 {
1376         int res         PG_USED_FOR_ASSERTS_ONLY;
1377         int                     required;
1378
1379         /*
1380          * Ensure we have enough space in the output buffer for the message header
1381          * as well as the message itself.
1382          */
1383         required = PqSendPointer + 1 + 4 + len;
1384         if (required > PqSendBufferSize)
1385         {
1386                 PqSendBuffer = repalloc(PqSendBuffer, required);
1387                 PqSendBufferSize = required;
1388         }
1389         res = pq_putmessage(msgtype, s, len);
1390         Assert(res == 0);                       /* should not fail when the message fits in
1391                                                                  * buffer */
1392 }
1393
1394
1395 /* --------------------------------
1396  *              pq_startcopyout - inform libpq that an old-style COPY OUT transfer
1397  *                      is beginning
1398  * --------------------------------
1399  */
1400 void
1401 pq_startcopyout(void)
1402 {
1403         DoingCopyOut = true;
1404 }
1405
1406 /* --------------------------------
1407  *              pq_endcopyout   - end an old-style COPY OUT transfer
1408  *
1409  *              If errorAbort is indicated, we are aborting a COPY OUT due to an error,
1410  *              and must send a terminator line.  Since a partial data line might have
1411  *              been emitted, send a couple of newlines first (the first one could
1412  *              get absorbed by a backslash...)  Note that old-style COPY OUT does
1413  *              not allow binary transfers, so a textual terminator is always correct.
1414  * --------------------------------
1415  */
1416 void
1417 pq_endcopyout(bool errorAbort)
1418 {
1419         if (!DoingCopyOut)
1420                 return;
1421         if (errorAbort)
1422                 pq_putbytes("\n\n\\.\n", 5);
1423         /* in non-error case, copy.c will have emitted the terminator line */
1424         DoingCopyOut = false;
1425 }
1426
1427
1428 /*
1429  * Support for TCP Keepalive parameters
1430  */
1431
1432 /*
1433  * On Windows, we need to set both idle and interval at the same time.
1434  * We also cannot reset them to the default (setting to zero will
1435  * actually set them to zero, not default), therefor we fallback to
1436  * the out-of-the-box default instead.
1437  */
1438 #if defined(WIN32) && defined(SIO_KEEPALIVE_VALS)
1439 static int
1440 pq_setkeepaliveswin32(Port *port, int idle, int interval)
1441 {
1442         struct tcp_keepalive ka;
1443         DWORD           retsize;
1444
1445         if (idle <= 0)
1446                 idle = 2 * 60 * 60;             /* default = 2 hours */
1447         if (interval <= 0)
1448                 interval = 1;                   /* default = 1 second */
1449
1450         ka.onoff = 1;
1451         ka.keepalivetime = idle * 1000;
1452         ka.keepaliveinterval = interval * 1000;
1453
1454         if (WSAIoctl(port->sock,
1455                                  SIO_KEEPALIVE_VALS,
1456                                  (LPVOID) &ka,
1457                                  sizeof(ka),
1458                                  NULL,
1459                                  0,
1460                                  &retsize,
1461                                  NULL,
1462                                  NULL)
1463                 != 0)
1464         {
1465                 elog(LOG, "WSAIoctl(SIO_KEEPALIVE_VALS) failed: %ui",
1466                          WSAGetLastError());
1467                 return STATUS_ERROR;
1468         }
1469         if (port->keepalives_idle != idle)
1470                 port->keepalives_idle = idle;
1471         if (port->keepalives_interval != interval)
1472                 port->keepalives_interval = interval;
1473         return STATUS_OK;
1474 }
1475 #endif
1476
1477 int
1478 pq_getkeepalivesidle(Port *port)
1479 {
1480 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPALIVE) || defined(WIN32)
1481         if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1482                 return 0;
1483
1484         if (port->keepalives_idle != 0)
1485                 return port->keepalives_idle;
1486
1487         if (port->default_keepalives_idle == 0)
1488         {
1489 #ifndef WIN32
1490                 ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_idle);
1491
1492 #ifdef TCP_KEEPIDLE
1493                 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPIDLE,
1494                                            (char *) &port->default_keepalives_idle,
1495                                            &size) < 0)
1496                 {
1497                         elog(LOG, "getsockopt(TCP_KEEPIDLE) failed: %m");
1498                         port->default_keepalives_idle = -1; /* don't know */
1499                 }
1500 #else
1501                 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPALIVE,
1502                                            (char *) &port->default_keepalives_idle,
1503                                            &size) < 0)
1504                 {
1505                         elog(LOG, "getsockopt(TCP_KEEPALIVE) failed: %m");
1506                         port->default_keepalives_idle = -1; /* don't know */
1507                 }
1508 #endif   /* TCP_KEEPIDLE */
1509 #else                                                   /* WIN32 */
1510                 /* We can't get the defaults on Windows, so return "don't know" */
1511                 port->default_keepalives_idle = -1;
1512 #endif   /* WIN32 */
1513         }
1514
1515         return port->default_keepalives_idle;
1516 #else
1517         return 0;
1518 #endif
1519 }
1520
1521 int
1522 pq_setkeepalivesidle(int idle, Port *port)
1523 {
1524         if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1525                 return STATUS_OK;
1526
1527 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPALIVE) || defined(SIO_KEEPALIVE_VALS)
1528         if (idle == port->keepalives_idle)
1529                 return STATUS_OK;
1530
1531 #ifndef WIN32
1532         if (port->default_keepalives_idle <= 0)
1533         {
1534                 if (pq_getkeepalivesidle(port) < 0)
1535                 {
1536                         if (idle == 0)
1537                                 return STATUS_OK;               /* default is set but unknown */
1538                         else
1539                                 return STATUS_ERROR;
1540                 }
1541         }
1542
1543         if (idle == 0)
1544                 idle = port->default_keepalives_idle;
1545
1546 #ifdef TCP_KEEPIDLE
1547         if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPIDLE,
1548                                    (char *) &idle, sizeof(idle)) < 0)
1549         {
1550                 elog(LOG, "setsockopt(TCP_KEEPIDLE) failed: %m");
1551                 return STATUS_ERROR;
1552         }
1553 #else
1554         if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPALIVE,
1555                                    (char *) &idle, sizeof(idle)) < 0)
1556         {
1557                 elog(LOG, "setsockopt(TCP_KEEPALIVE) failed: %m");
1558                 return STATUS_ERROR;
1559         }
1560 #endif
1561
1562         port->keepalives_idle = idle;
1563 #else                                                   /* WIN32 */
1564         return pq_setkeepaliveswin32(port, idle, port->keepalives_interval);
1565 #endif
1566 #else                                                   /* TCP_KEEPIDLE || SIO_KEEPALIVE_VALS */
1567         if (idle != 0)
1568         {
1569                 elog(LOG, "setting the keepalive idle time is not supported");
1570                 return STATUS_ERROR;
1571         }
1572 #endif
1573         return STATUS_OK;
1574 }
1575
1576 int
1577 pq_getkeepalivesinterval(Port *port)
1578 {
1579 #if defined(TCP_KEEPINTVL) || defined(SIO_KEEPALIVE_VALS)
1580         if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1581                 return 0;
1582
1583         if (port->keepalives_interval != 0)
1584                 return port->keepalives_interval;
1585
1586         if (port->default_keepalives_interval == 0)
1587         {
1588 #ifndef WIN32
1589                 ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_interval);
1590
1591                 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1592                                            (char *) &port->default_keepalives_interval,
1593                                            &size) < 0)
1594                 {
1595                         elog(LOG, "getsockopt(TCP_KEEPINTVL) failed: %m");
1596                         port->default_keepalives_interval = -1;         /* don't know */
1597                 }
1598 #else
1599                 /* We can't get the defaults on Windows, so return "don't know" */
1600                 port->default_keepalives_interval = -1;
1601 #endif   /* WIN32 */
1602         }
1603
1604         return port->default_keepalives_interval;
1605 #else
1606         return 0;
1607 #endif
1608 }
1609
1610 int
1611 pq_setkeepalivesinterval(int interval, Port *port)
1612 {
1613         if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1614                 return STATUS_OK;
1615
1616 #if defined(TCP_KEEPINTVL) || defined (SIO_KEEPALIVE_VALS)
1617         if (interval == port->keepalives_interval)
1618                 return STATUS_OK;
1619
1620 #ifndef WIN32
1621         if (port->default_keepalives_interval <= 0)
1622         {
1623                 if (pq_getkeepalivesinterval(port) < 0)
1624                 {
1625                         if (interval == 0)
1626                                 return STATUS_OK;               /* default is set but unknown */
1627                         else
1628                                 return STATUS_ERROR;
1629                 }
1630         }
1631
1632         if (interval == 0)
1633                 interval = port->default_keepalives_interval;
1634
1635         if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1636                                    (char *) &interval, sizeof(interval)) < 0)
1637         {
1638                 elog(LOG, "setsockopt(TCP_KEEPINTVL) failed: %m");
1639                 return STATUS_ERROR;
1640         }
1641
1642         port->keepalives_interval = interval;
1643 #else                                                   /* WIN32 */
1644         return pq_setkeepaliveswin32(port, port->keepalives_idle, interval);
1645 #endif
1646 #else
1647         if (interval != 0)
1648         {
1649                 elog(LOG, "setsockopt(TCP_KEEPINTVL) not supported");
1650                 return STATUS_ERROR;
1651         }
1652 #endif
1653
1654         return STATUS_OK;
1655 }
1656
1657 int
1658 pq_getkeepalivescount(Port *port)
1659 {
1660 #ifdef TCP_KEEPCNT
1661         if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1662                 return 0;
1663
1664         if (port->keepalives_count != 0)
1665                 return port->keepalives_count;
1666
1667         if (port->default_keepalives_count == 0)
1668         {
1669                 ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_count);
1670
1671                 if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
1672                                            (char *) &port->default_keepalives_count,
1673                                            &size) < 0)
1674                 {
1675                         elog(LOG, "getsockopt(TCP_KEEPCNT) failed: %m");
1676                         port->default_keepalives_count = -1;            /* don't know */
1677                 }
1678         }
1679
1680         return port->default_keepalives_count;
1681 #else
1682         return 0;
1683 #endif
1684 }
1685
1686 int
1687 pq_setkeepalivescount(int count, Port *port)
1688 {
1689         if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
1690                 return STATUS_OK;
1691
1692 #ifdef TCP_KEEPCNT
1693         if (count == port->keepalives_count)
1694                 return STATUS_OK;
1695
1696         if (port->default_keepalives_count <= 0)
1697         {
1698                 if (pq_getkeepalivescount(port) < 0)
1699                 {
1700                         if (count == 0)
1701                                 return STATUS_OK;               /* default is set but unknown */
1702                         else
1703                                 return STATUS_ERROR;
1704                 }
1705         }
1706
1707         if (count == 0)
1708                 count = port->default_keepalives_count;
1709
1710         if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
1711                                    (char *) &count, sizeof(count)) < 0)
1712         {
1713                 elog(LOG, "setsockopt(TCP_KEEPCNT) failed: %m");
1714                 return STATUS_ERROR;
1715         }
1716
1717         port->keepalives_count = count;
1718 #else
1719         if (count != 0)
1720         {
1721                 elog(LOG, "setsockopt(TCP_KEEPCNT) not supported");
1722                 return STATUS_ERROR;
1723         }
1724 #endif
1725
1726         return STATUS_OK;
1727 }