PostgreSQL Source Code  git master
pqcomm.c
Go to the documentation of this file.
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.
9  *
10  * To emit an outgoing message, use the routines in pqformat.c to construct
11  * the message in a buffer and then emit it in one call to pq_putmessage.
12  * There are no functions to send raw bytes or partial messages; this
13  * ensures that the channel will not be clogged by an incomplete message if
14  * execution is aborted by ereport(ERROR) partway through the message.
15  *
16  * At one time, libpq was shared between frontend and backend, but now
17  * the backend's "backend/libpq" is quite separate from "interfaces/libpq".
18  * All that remains is similarities of names to trap the unwary...
19  *
20  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
21  * Portions Copyright (c) 1994, Regents of the University of California
22  *
23  * src/backend/libpq/pqcomm.c
24  *
25  *-------------------------------------------------------------------------
26  */
27 
28 /*------------------------
29  * INTERFACE ROUTINES
30  *
31  * setup/teardown:
32  * StreamServerPort - Open postmaster's server port
33  * StreamConnection - Create new connection with client
34  * StreamClose - Close a client/backend connection
35  * TouchSocketFiles - Protect socket files against /tmp cleaners
36  * pq_init - initialize libpq at backend startup
37  * socket_comm_reset - reset libpq during error recovery
38  * socket_close - shutdown libpq at backend exit
39  *
40  * low-level I/O:
41  * pq_getbytes - get a known number of bytes from connection
42  * pq_getmessage - get a message with length word from connection
43  * pq_getbyte - get next byte from connection
44  * pq_peekbyte - peek at next byte from connection
45  * pq_flush - flush pending output
46  * pq_flush_if_writable - flush pending output if writable without blocking
47  * pq_getbyte_if_available - get a byte if available without blocking
48  *
49  * message-level I/O
50  * pq_putmessage - send a normal message (suppressed in COPY OUT mode)
51  * pq_putmessage_noblock - buffer a normal message (suppressed in COPY OUT)
52  *
53  *------------------------
54  */
55 #include "postgres.h"
56 
57 #ifdef HAVE_POLL_H
58 #include <poll.h>
59 #endif
60 #include <signal.h>
61 #include <fcntl.h>
62 #include <grp.h>
63 #include <unistd.h>
64 #include <sys/file.h>
65 #include <sys/socket.h>
66 #include <sys/stat.h>
67 #include <sys/time.h>
68 #include <netdb.h>
69 #include <netinet/in.h>
70 #include <netinet/tcp.h>
71 #include <utime.h>
72 #ifdef WIN32
73 #include <mstcpip.h>
74 #endif
75 
76 #include "common/ip.h"
77 #include "libpq/libpq.h"
78 #include "miscadmin.h"
79 #include "port/pg_bswap.h"
80 #include "storage/ipc.h"
81 #include "utils/guc_hooks.h"
82 #include "utils/memutils.h"
83 
84 /*
85  * Cope with the various platform-specific ways to spell TCP keepalive socket
86  * options. This doesn't cover Windows, which as usual does its own thing.
87  */
88 #if defined(TCP_KEEPIDLE)
89 /* TCP_KEEPIDLE is the name of this option on Linux and *BSD */
90 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPIDLE
91 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPIDLE"
92 #elif defined(TCP_KEEPALIVE_THRESHOLD)
93 /* TCP_KEEPALIVE_THRESHOLD is the name of this option on Solaris >= 11 */
94 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE_THRESHOLD
95 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE_THRESHOLD"
96 #elif defined(TCP_KEEPALIVE) && defined(__darwin__)
97 /* TCP_KEEPALIVE is the name of this option on macOS */
98 /* Caution: Solaris has this symbol but it means something different */
99 #define PG_TCP_KEEPALIVE_IDLE TCP_KEEPALIVE
100 #define PG_TCP_KEEPALIVE_IDLE_STR "TCP_KEEPALIVE"
101 #endif
102 
103 /*
104  * Configuration options
105  */
108 
109 /* Where the Unix socket files are (list of palloc'd strings) */
110 static List *sock_paths = NIL;
111 
112 /*
113  * Buffers for low-level I/O.
114  *
115  * The receive buffer is fixed size. Send buffer is usually 8k, but can be
116  * enlarged by pq_putmessage_noblock() if the message doesn't fit otherwise.
117  */
118 
119 #define PQ_SEND_BUFFER_SIZE 8192
120 #define PQ_RECV_BUFFER_SIZE 8192
121 
122 static char *PqSendBuffer;
123 static int PqSendBufferSize; /* Size send buffer */
124 static int PqSendPointer; /* Next index to store a byte in PqSendBuffer */
125 static int PqSendStart; /* Next index to send a byte in PqSendBuffer */
126 
128 static int PqRecvPointer; /* Next index to read a byte from PqRecvBuffer */
129 static int PqRecvLength; /* End of data available in PqRecvBuffer */
130 
131 /*
132  * Message status
133  */
134 static bool PqCommBusy; /* busy sending data to the client */
135 static bool PqCommReadingMsg; /* in the middle of reading a message */
136 
137 
138 /* Internal functions */
139 static void socket_comm_reset(void);
140 static void socket_close(int code, Datum arg);
141 static void socket_set_nonblocking(bool nonblocking);
142 static int socket_flush(void);
143 static int socket_flush_if_writable(void);
144 static bool socket_is_send_pending(void);
145 static int socket_putmessage(char msgtype, const char *s, size_t len);
146 static void socket_putmessage_noblock(char msgtype, const char *s, size_t len);
147 static int internal_putbytes(const char *s, size_t len);
148 static int internal_flush(void);
149 
150 static int Lock_AF_UNIX(const char *unixSocketDir, const char *unixSocketPath);
151 static int Setup_AF_UNIX(const char *sock_path);
152 
155  socket_flush,
160 };
161 
163 
165 
166 
167 /* --------------------------------
168  * pq_init - initialize libpq at backend startup
169  * --------------------------------
170  */
171 void
172 pq_init(void)
173 {
174  int socket_pos PG_USED_FOR_ASSERTS_ONLY;
175  int latch_pos PG_USED_FOR_ASSERTS_ONLY;
176 
177  /* initialize state variables */
181  PqCommBusy = false;
182  PqCommReadingMsg = false;
183 
184  /* set up process-exit hook to close the socket */
186 
187  /*
188  * In backends (as soon as forked) we operate the underlying socket in
189  * nonblocking mode and use latches to implement blocking semantics if
190  * needed. That allows us to provide safely interruptible reads and
191  * writes.
192  *
193  * Use COMMERROR on failure, because ERROR would try to send the error to
194  * the client, which might require changing the mode again, leading to
195  * infinite recursion.
196  */
197 #ifndef WIN32
200  (errmsg("could not set socket to nonblocking mode: %m")));
201 #endif
202 
205  MyProcPort->sock, NULL, NULL);
207  MyLatch, NULL);
209  NULL, NULL);
210 
211  /*
212  * The event positions match the order we added them, but let's sanity
213  * check them to be sure.
214  */
215  Assert(socket_pos == FeBeWaitSetSocketPos);
216  Assert(latch_pos == FeBeWaitSetLatchPos);
217 }
218 
219 /* --------------------------------
220  * socket_comm_reset - reset libpq during error recovery
221  *
222  * This is called from error recovery at the outer idle loop. It's
223  * just to get us out of trouble if we somehow manage to elog() from
224  * inside a pqcomm.c routine (which ideally will never happen, but...)
225  * --------------------------------
226  */
227 static void
229 {
230  /* Do not throw away pending data, but do reset the busy flag */
231  PqCommBusy = false;
232 }
233 
234 /* --------------------------------
235  * socket_close - shutdown libpq at backend exit
236  *
237  * This is the one pg_on_exit_callback in place during BackendInitialize().
238  * That function's unusual signal handling constrains that this callback be
239  * safe to run at any instant.
240  * --------------------------------
241  */
242 static void
244 {
245  /* Nothing to do in a standalone backend, where MyProcPort is NULL. */
246  if (MyProcPort != NULL)
247  {
248 #ifdef ENABLE_GSS
249  /*
250  * Shutdown GSSAPI layer. This section does nothing when interrupting
251  * BackendInitialize(), because pg_GSS_recvauth() makes first use of
252  * "ctx" and "cred".
253  *
254  * Note that we don't bother to free MyProcPort->gss, since we're
255  * about to exit anyway.
256  */
257  if (MyProcPort->gss)
258  {
259  OM_uint32 min_s;
260 
261  if (MyProcPort->gss->ctx != GSS_C_NO_CONTEXT)
262  gss_delete_sec_context(&min_s, &MyProcPort->gss->ctx, NULL);
263 
264  if (MyProcPort->gss->cred != GSS_C_NO_CREDENTIAL)
265  gss_release_cred(&min_s, &MyProcPort->gss->cred);
266  }
267 #endif /* ENABLE_GSS */
268 
269  /*
270  * Cleanly shut down SSL layer. Nowhere else does a postmaster child
271  * call this, so this is safe when interrupting BackendInitialize().
272  */
274 
275  /*
276  * Formerly we did an explicit close() here, but it seems better to
277  * leave the socket open until the process dies. This allows clients
278  * to perform a "synchronous close" if they care --- wait till the
279  * transport layer reports connection closure, and you can be sure the
280  * backend has exited.
281  *
282  * We do set sock to PGINVALID_SOCKET to prevent any further I/O,
283  * though.
284  */
286  }
287 }
288 
289 
290 
291 /*
292  * Streams -- wrapper around Unix socket system calls
293  *
294  *
295  * Stream functions are used for vanilla TCP connection protocol.
296  */
297 
298 
299 /*
300  * StreamServerPort -- open a "listening" port to accept connections.
301  *
302  * family should be AF_UNIX or AF_UNSPEC; portNumber is the port number.
303  * For AF_UNIX ports, hostName should be NULL and unixSocketDir must be
304  * specified. For TCP ports, hostName is either NULL for all interfaces or
305  * the interface to listen on, and unixSocketDir is ignored (can be NULL).
306  *
307  * Successfully opened sockets are added to the ListenSocket[] array (of
308  * length MaxListen), at the first position that isn't PGINVALID_SOCKET.
309  *
310  * RETURNS: STATUS_OK or STATUS_ERROR
311  */
312 
313 int
314 StreamServerPort(int family, const char *hostName, unsigned short portNumber,
315  const char *unixSocketDir,
316  pgsocket ListenSocket[], int MaxListen)
317 {
318  pgsocket fd;
319  int err;
320  int maxconn;
321  int ret;
322  char portNumberStr[32];
323  const char *familyDesc;
324  char familyDescBuf[64];
325  const char *addrDesc;
326  char addrBuf[NI_MAXHOST];
327  char *service;
328  struct addrinfo *addrs = NULL,
329  *addr;
330  struct addrinfo hint;
331  int listen_index = 0;
332  int added = 0;
333  char unixSocketPath[MAXPGPATH];
334 #if !defined(WIN32) || defined(IPV6_V6ONLY)
335  int one = 1;
336 #endif
337 
338  /* Initialize hint structure */
339  MemSet(&hint, 0, sizeof(hint));
340  hint.ai_family = family;
341  hint.ai_flags = AI_PASSIVE;
342  hint.ai_socktype = SOCK_STREAM;
343 
344  if (family == AF_UNIX)
345  {
346  /*
347  * Create unixSocketPath from portNumber and unixSocketDir and lock
348  * that file path
349  */
350  UNIXSOCK_PATH(unixSocketPath, portNumber, unixSocketDir);
351  if (strlen(unixSocketPath) >= UNIXSOCK_PATH_BUFLEN)
352  {
353  ereport(LOG,
354  (errmsg("Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
355  unixSocketPath,
356  (int) (UNIXSOCK_PATH_BUFLEN - 1))));
357  return STATUS_ERROR;
358  }
359  if (Lock_AF_UNIX(unixSocketDir, unixSocketPath) != STATUS_OK)
360  return STATUS_ERROR;
361  service = unixSocketPath;
362  }
363  else
364  {
365  snprintf(portNumberStr, sizeof(portNumberStr), "%d", portNumber);
366  service = portNumberStr;
367  }
368 
369  ret = pg_getaddrinfo_all(hostName, service, &hint, &addrs);
370  if (ret || !addrs)
371  {
372  if (hostName)
373  ereport(LOG,
374  (errmsg("could not translate host name \"%s\", service \"%s\" to address: %s",
375  hostName, service, gai_strerror(ret))));
376  else
377  ereport(LOG,
378  (errmsg("could not translate service \"%s\" to address: %s",
379  service, gai_strerror(ret))));
380  if (addrs)
381  pg_freeaddrinfo_all(hint.ai_family, addrs);
382  return STATUS_ERROR;
383  }
384 
385  for (addr = addrs; addr; addr = addr->ai_next)
386  {
387  if (family != AF_UNIX && addr->ai_family == AF_UNIX)
388  {
389  /*
390  * Only set up a unix domain socket when they really asked for it.
391  * The service/port is different in that case.
392  */
393  continue;
394  }
395 
396  /* See if there is still room to add 1 more socket. */
397  for (; listen_index < MaxListen; listen_index++)
398  {
399  if (ListenSocket[listen_index] == PGINVALID_SOCKET)
400  break;
401  }
402  if (listen_index >= MaxListen)
403  {
404  ereport(LOG,
405  (errmsg("could not bind to all requested addresses: MAXLISTEN (%d) exceeded",
406  MaxListen)));
407  break;
408  }
409 
410  /* set up address family name for log messages */
411  switch (addr->ai_family)
412  {
413  case AF_INET:
414  familyDesc = _("IPv4");
415  break;
416  case AF_INET6:
417  familyDesc = _("IPv6");
418  break;
419  case AF_UNIX:
420  familyDesc = _("Unix");
421  break;
422  default:
423  snprintf(familyDescBuf, sizeof(familyDescBuf),
424  _("unrecognized address family %d"),
425  addr->ai_family);
426  familyDesc = familyDescBuf;
427  break;
428  }
429 
430  /* set up text form of address for log messages */
431  if (addr->ai_family == AF_UNIX)
432  addrDesc = unixSocketPath;
433  else
434  {
435  pg_getnameinfo_all((const struct sockaddr_storage *) addr->ai_addr,
436  addr->ai_addrlen,
437  addrBuf, sizeof(addrBuf),
438  NULL, 0,
439  NI_NUMERICHOST);
440  addrDesc = addrBuf;
441  }
442 
443  if ((fd = socket(addr->ai_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
444  {
445  ereport(LOG,
447  /* translator: first %s is IPv4, IPv6, or Unix */
448  errmsg("could not create %s socket for address \"%s\": %m",
449  familyDesc, addrDesc)));
450  continue;
451  }
452 
453 #ifndef WIN32
454 
455  /*
456  * Without the SO_REUSEADDR flag, a new postmaster can't be started
457  * right away after a stop or crash, giving "address already in use"
458  * error on TCP ports.
459  *
460  * On win32, however, this behavior only happens if the
461  * SO_EXCLUSIVEADDRUSE is set. With SO_REUSEADDR, win32 allows
462  * multiple servers to listen on the same address, resulting in
463  * unpredictable behavior. With no flags at all, win32 behaves as Unix
464  * with SO_REUSEADDR.
465  */
466  if (addr->ai_family != AF_UNIX)
467  {
468  if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
469  (char *) &one, sizeof(one))) == -1)
470  {
471  ereport(LOG,
473  /* translator: third %s is IPv4, IPv6, or Unix */
474  errmsg("%s(%s) failed for %s address \"%s\": %m",
475  "setsockopt", "SO_REUSEADDR",
476  familyDesc, addrDesc)));
477  closesocket(fd);
478  continue;
479  }
480  }
481 #endif
482 
483 #ifdef IPV6_V6ONLY
484  if (addr->ai_family == AF_INET6)
485  {
486  if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
487  (char *) &one, sizeof(one)) == -1)
488  {
489  ereport(LOG,
491  /* translator: third %s is IPv4, IPv6, or Unix */
492  errmsg("%s(%s) failed for %s address \"%s\": %m",
493  "setsockopt", "IPV6_V6ONLY",
494  familyDesc, addrDesc)));
495  closesocket(fd);
496  continue;
497  }
498  }
499 #endif
500 
501  /*
502  * Note: This might fail on some OS's, like Linux older than
503  * 2.4.21-pre3, that don't have the IPV6_V6ONLY socket option, and map
504  * ipv4 addresses to ipv6. It will show ::ffff:ipv4 for all ipv4
505  * connections.
506  */
507  err = bind(fd, addr->ai_addr, addr->ai_addrlen);
508  if (err < 0)
509  {
510  int saved_errno = errno;
511 
512  ereport(LOG,
514  /* translator: first %s is IPv4, IPv6, or Unix */
515  errmsg("could not bind %s address \"%s\": %m",
516  familyDesc, addrDesc),
517  saved_errno == EADDRINUSE ?
518  (addr->ai_family == AF_UNIX ?
519  errhint("Is another postmaster already running on port %d?",
520  (int) portNumber) :
521  errhint("Is another postmaster already running on port %d?"
522  " If not, wait a few seconds and retry.",
523  (int) portNumber)) : 0));
524  closesocket(fd);
525  continue;
526  }
527 
528  if (addr->ai_family == AF_UNIX)
529  {
530  if (Setup_AF_UNIX(service) != STATUS_OK)
531  {
532  closesocket(fd);
533  break;
534  }
535  }
536 
537  /*
538  * Select appropriate accept-queue length limit. It seems reasonable
539  * to use a value similar to the maximum number of child processes
540  * that the postmaster will permit.
541  */
542  maxconn = MaxConnections * 2;
543 
544  err = listen(fd, maxconn);
545  if (err < 0)
546  {
547  ereport(LOG,
549  /* translator: first %s is IPv4, IPv6, or Unix */
550  errmsg("could not listen on %s address \"%s\": %m",
551  familyDesc, addrDesc)));
552  closesocket(fd);
553  continue;
554  }
555 
556  if (addr->ai_family == AF_UNIX)
557  ereport(LOG,
558  (errmsg("listening on Unix socket \"%s\"",
559  addrDesc)));
560  else
561  ereport(LOG,
562  /* translator: first %s is IPv4 or IPv6 */
563  (errmsg("listening on %s address \"%s\", port %d",
564  familyDesc, addrDesc, (int) portNumber)));
565 
566  ListenSocket[listen_index] = fd;
567  added++;
568  }
569 
570  pg_freeaddrinfo_all(hint.ai_family, addrs);
571 
572  if (!added)
573  return STATUS_ERROR;
574 
575  return STATUS_OK;
576 }
577 
578 
579 /*
580  * Lock_AF_UNIX -- configure unix socket file path
581  */
582 static int
583 Lock_AF_UNIX(const char *unixSocketDir, const char *unixSocketPath)
584 {
585  /* no lock file for abstract sockets */
586  if (unixSocketPath[0] == '@')
587  return STATUS_OK;
588 
589  /*
590  * Grab an interlock file associated with the socket file.
591  *
592  * Note: there are two reasons for using a socket lock file, rather than
593  * trying to interlock directly on the socket itself. First, it's a lot
594  * more portable, and second, it lets us remove any pre-existing socket
595  * file without race conditions.
596  */
597  CreateSocketLockFile(unixSocketPath, true, unixSocketDir);
598 
599  /*
600  * Once we have the interlock, we can safely delete any pre-existing
601  * socket file to avoid failure at bind() time.
602  */
603  (void) unlink(unixSocketPath);
604 
605  /*
606  * Remember socket file pathnames for later maintenance.
607  */
608  sock_paths = lappend(sock_paths, pstrdup(unixSocketPath));
609 
610  return STATUS_OK;
611 }
612 
613 
614 /*
615  * Setup_AF_UNIX -- configure unix socket permissions
616  */
617 static int
618 Setup_AF_UNIX(const char *sock_path)
619 {
620  /* no file system permissions for abstract sockets */
621  if (sock_path[0] == '@')
622  return STATUS_OK;
623 
624  /*
625  * Fix socket ownership/permission if requested. Note we must do this
626  * before we listen() to avoid a window where unwanted connections could
627  * get accepted.
628  */
630  if (Unix_socket_group[0] != '\0')
631  {
632 #ifdef WIN32
633  elog(WARNING, "configuration item unix_socket_group is not supported on this platform");
634 #else
635  char *endptr;
636  unsigned long val;
637  gid_t gid;
638 
639  val = strtoul(Unix_socket_group, &endptr, 10);
640  if (*endptr == '\0')
641  { /* numeric group id */
642  gid = val;
643  }
644  else
645  { /* convert group name to id */
646  struct group *gr;
647 
648  gr = getgrnam(Unix_socket_group);
649  if (!gr)
650  {
651  ereport(LOG,
652  (errmsg("group \"%s\" does not exist",
654  return STATUS_ERROR;
655  }
656  gid = gr->gr_gid;
657  }
658  if (chown(sock_path, -1, gid) == -1)
659  {
660  ereport(LOG,
662  errmsg("could not set group of file \"%s\": %m",
663  sock_path)));
664  return STATUS_ERROR;
665  }
666 #endif
667  }
668 
669  if (chmod(sock_path, Unix_socket_permissions) == -1)
670  {
671  ereport(LOG,
673  errmsg("could not set permissions of file \"%s\": %m",
674  sock_path)));
675  return STATUS_ERROR;
676  }
677  return STATUS_OK;
678 }
679 
680 
681 /*
682  * StreamConnection -- create a new connection with client using
683  * server port. Set port->sock to the FD of the new connection.
684  *
685  * ASSUME: that this doesn't need to be non-blocking because
686  * the Postmaster uses select() to tell when the socket is ready for
687  * accept().
688  *
689  * RETURNS: STATUS_OK or STATUS_ERROR
690  */
691 int
693 {
694  /* accept connection and fill in the client (remote) address */
695  port->raddr.salen = sizeof(port->raddr.addr);
696  if ((port->sock = accept(server_fd,
697  (struct sockaddr *) &port->raddr.addr,
698  &port->raddr.salen)) == PGINVALID_SOCKET)
699  {
700  ereport(LOG,
702  errmsg("could not accept new connection: %m")));
703 
704  /*
705  * If accept() fails then postmaster.c will still see the server
706  * socket as read-ready, and will immediately try again. To avoid
707  * uselessly sucking lots of CPU, delay a bit before trying again.
708  * (The most likely reason for failure is being out of kernel file
709  * table slots; we can do little except hope some will get freed up.)
710  */
711  pg_usleep(100000L); /* wait 0.1 sec */
712  return STATUS_ERROR;
713  }
714 
715  /* fill in the server (local) address */
716  port->laddr.salen = sizeof(port->laddr.addr);
717  if (getsockname(port->sock,
718  (struct sockaddr *) &port->laddr.addr,
719  &port->laddr.salen) < 0)
720  {
721  ereport(LOG,
722  (errmsg("%s() failed: %m", "getsockname")));
723  return STATUS_ERROR;
724  }
725 
726  /* select NODELAY and KEEPALIVE options if it's a TCP connection */
727  if (port->laddr.addr.ss_family != AF_UNIX)
728  {
729  int on;
730 #ifdef WIN32
731  int oldopt;
732  int optlen;
733  int newopt;
734 #endif
735 
736 #ifdef TCP_NODELAY
737  on = 1;
738  if (setsockopt(port->sock, IPPROTO_TCP, TCP_NODELAY,
739  (char *) &on, sizeof(on)) < 0)
740  {
741  ereport(LOG,
742  (errmsg("%s(%s) failed: %m", "setsockopt", "TCP_NODELAY")));
743  return STATUS_ERROR;
744  }
745 #endif
746  on = 1;
747  if (setsockopt(port->sock, SOL_SOCKET, SO_KEEPALIVE,
748  (char *) &on, sizeof(on)) < 0)
749  {
750  ereport(LOG,
751  (errmsg("%s(%s) failed: %m", "setsockopt", "SO_KEEPALIVE")));
752  return STATUS_ERROR;
753  }
754 
755 #ifdef WIN32
756 
757  /*
758  * This is a Win32 socket optimization. The OS send buffer should be
759  * large enough to send the whole Postgres send buffer in one go, or
760  * performance suffers. The Postgres send buffer can be enlarged if a
761  * very large message needs to be sent, but we won't attempt to
762  * enlarge the OS buffer if that happens, so somewhat arbitrarily
763  * ensure that the OS buffer is at least PQ_SEND_BUFFER_SIZE * 4.
764  * (That's 32kB with the current default).
765  *
766  * The default OS buffer size used to be 8kB in earlier Windows
767  * versions, but was raised to 64kB in Windows 2012. So it shouldn't
768  * be necessary to change it in later versions anymore. Changing it
769  * unnecessarily can even reduce performance, because setting
770  * SO_SNDBUF in the application disables the "dynamic send buffering"
771  * feature that was introduced in Windows 7. So before fiddling with
772  * SO_SNDBUF, check if the current buffer size is already large enough
773  * and only increase it if necessary.
774  *
775  * See https://support.microsoft.com/kb/823764/EN-US/ and
776  * https://msdn.microsoft.com/en-us/library/bb736549%28v=vs.85%29.aspx
777  */
778  optlen = sizeof(oldopt);
779  if (getsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &oldopt,
780  &optlen) < 0)
781  {
782  ereport(LOG,
783  (errmsg("%s(%s) failed: %m", "getsockopt", "SO_SNDBUF")));
784  return STATUS_ERROR;
785  }
786  newopt = PQ_SEND_BUFFER_SIZE * 4;
787  if (oldopt < newopt)
788  {
789  if (setsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &newopt,
790  sizeof(newopt)) < 0)
791  {
792  ereport(LOG,
793  (errmsg("%s(%s) failed: %m", "setsockopt", "SO_SNDBUF")));
794  return STATUS_ERROR;
795  }
796  }
797 #endif
798 
799  /*
800  * Also apply the current keepalive parameters. If we fail to set a
801  * parameter, don't error out, because these aren't universally
802  * supported. (Note: you might think we need to reset the GUC
803  * variables to 0 in such a case, but it's not necessary because the
804  * show hooks for these variables report the truth anyway.)
805  */
810  }
811 
812  return STATUS_OK;
813 }
814 
815 /*
816  * StreamClose -- close a client/backend connection
817  *
818  * NOTE: this is NOT used to terminate a session; it is just used to release
819  * the file descriptor in a process that should no longer have the socket
820  * open. (For example, the postmaster calls this after passing ownership
821  * of the connection to a child process.) It is expected that someone else
822  * still has the socket open. So, we only want to close the descriptor,
823  * we do NOT want to send anything to the far end.
824  */
825 void
827 {
828  closesocket(sock);
829 }
830 
831 /*
832  * TouchSocketFiles -- mark socket files as recently accessed
833  *
834  * This routine should be called every so often to ensure that the socket
835  * files have a recent mod date (ordinary operations on sockets usually won't
836  * change the mod date). That saves them from being removed by
837  * overenthusiastic /tmp-directory-cleaner daemons. (Another reason we should
838  * never have put the socket file in /tmp...)
839  */
840 void
842 {
843  ListCell *l;
844 
845  /* Loop through all created sockets... */
846  foreach(l, sock_paths)
847  {
848  char *sock_path = (char *) lfirst(l);
849 
850  /* Ignore errors; there's no point in complaining */
851  (void) utime(sock_path, NULL);
852  }
853 }
854 
855 /*
856  * RemoveSocketFiles -- unlink socket files at postmaster shutdown
857  */
858 void
860 {
861  ListCell *l;
862 
863  /* Loop through all created sockets... */
864  foreach(l, sock_paths)
865  {
866  char *sock_path = (char *) lfirst(l);
867 
868  /* Ignore any error. */
869  (void) unlink(sock_path);
870  }
871  /* Since we're about to exit, no need to reclaim storage */
872  sock_paths = NIL;
873 }
874 
875 
876 /* --------------------------------
877  * Low-level I/O routines begin here.
878  *
879  * These routines communicate with a frontend client across a connection
880  * already established by the preceding routines.
881  * --------------------------------
882  */
883 
884 /* --------------------------------
885  * socket_set_nonblocking - set socket blocking/non-blocking
886  *
887  * Sets the socket non-blocking if nonblocking is true, or sets it
888  * blocking otherwise.
889  * --------------------------------
890  */
891 static void
892 socket_set_nonblocking(bool nonblocking)
893 {
894  if (MyProcPort == NULL)
895  ereport(ERROR,
896  (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
897  errmsg("there is no client connection")));
898 
899  MyProcPort->noblock = nonblocking;
900 }
901 
902 /* --------------------------------
903  * pq_recvbuf - load some bytes into the input buffer
904  *
905  * returns 0 if OK, EOF if trouble
906  * --------------------------------
907  */
908 static int
910 {
911  if (PqRecvPointer > 0)
912  {
914  {
915  /* still some unread data, left-justify it in the buffer */
919  PqRecvPointer = 0;
920  }
921  else
923  }
924 
925  /* Ensure that we're in blocking mode */
926  socket_set_nonblocking(false);
927 
928  /* Can fill buffer from PqRecvLength and upwards */
929  for (;;)
930  {
931  int r;
932 
935 
936  if (r < 0)
937  {
938  if (errno == EINTR)
939  continue; /* Ok if interrupted */
940 
941  /*
942  * Careful: an ereport() that tries to write to the client would
943  * cause recursion to here, leading to stack overflow and core
944  * dump! This message must go *only* to the postmaster log.
945  */
948  errmsg("could not receive data from client: %m")));
949  return EOF;
950  }
951  if (r == 0)
952  {
953  /*
954  * EOF detected. We used to write a log message here, but it's
955  * better to expect the ultimate caller to do that.
956  */
957  return EOF;
958  }
959  /* r contains number of bytes read, so just incr length */
960  PqRecvLength += r;
961  return 0;
962  }
963 }
964 
965 /* --------------------------------
966  * pq_getbyte - get a single byte from connection, or return EOF
967  * --------------------------------
968  */
969 int
971 {
973 
974  while (PqRecvPointer >= PqRecvLength)
975  {
976  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
977  return EOF; /* Failed to recv data */
978  }
979  return (unsigned char) PqRecvBuffer[PqRecvPointer++];
980 }
981 
982 /* --------------------------------
983  * pq_peekbyte - peek at next byte from connection
984  *
985  * Same as pq_getbyte() except we don't advance the pointer.
986  * --------------------------------
987  */
988 int
990 {
992 
993  while (PqRecvPointer >= PqRecvLength)
994  {
995  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
996  return EOF; /* Failed to recv data */
997  }
998  return (unsigned char) PqRecvBuffer[PqRecvPointer];
999 }
1000 
1001 /* --------------------------------
1002  * pq_getbyte_if_available - get a single byte from connection,
1003  * if available
1004  *
1005  * The received byte is stored in *c. Returns 1 if a byte was read,
1006  * 0 if no data was available, or EOF if trouble.
1007  * --------------------------------
1008  */
1009 int
1011 {
1012  int r;
1013 
1015 
1017  {
1019  return 1;
1020  }
1021 
1022  /* Put the socket into non-blocking mode */
1023  socket_set_nonblocking(true);
1024 
1025  r = secure_read(MyProcPort, c, 1);
1026  if (r < 0)
1027  {
1028  /*
1029  * Ok if no data available without blocking or interrupted (though
1030  * EINTR really shouldn't happen with a non-blocking socket). Report
1031  * other errors.
1032  */
1033  if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
1034  r = 0;
1035  else
1036  {
1037  /*
1038  * Careful: an ereport() that tries to write to the client would
1039  * cause recursion to here, leading to stack overflow and core
1040  * dump! This message must go *only* to the postmaster log.
1041  */
1044  errmsg("could not receive data from client: %m")));
1045  r = EOF;
1046  }
1047  }
1048  else if (r == 0)
1049  {
1050  /* EOF detected */
1051  r = EOF;
1052  }
1053 
1054  return r;
1055 }
1056 
1057 /* --------------------------------
1058  * pq_getbytes - get a known number of bytes from connection
1059  *
1060  * returns 0 if OK, EOF if trouble
1061  * --------------------------------
1062  */
1063 int
1064 pq_getbytes(char *s, size_t len)
1065 {
1066  size_t amount;
1067 
1069 
1070  while (len > 0)
1071  {
1072  while (PqRecvPointer >= PqRecvLength)
1073  {
1074  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1075  return EOF; /* Failed to recv data */
1076  }
1077  amount = PqRecvLength - PqRecvPointer;
1078  if (amount > len)
1079  amount = len;
1080  memcpy(s, PqRecvBuffer + PqRecvPointer, amount);
1081  PqRecvPointer += amount;
1082  s += amount;
1083  len -= amount;
1084  }
1085  return 0;
1086 }
1087 
1088 /* --------------------------------
1089  * pq_discardbytes - throw away a known number of bytes
1090  *
1091  * same as pq_getbytes except we do not copy the data to anyplace.
1092  * this is used for resynchronizing after read errors.
1093  *
1094  * returns 0 if OK, EOF if trouble
1095  * --------------------------------
1096  */
1097 static int
1099 {
1100  size_t amount;
1101 
1103 
1104  while (len > 0)
1105  {
1106  while (PqRecvPointer >= PqRecvLength)
1107  {
1108  if (pq_recvbuf()) /* If nothing in buffer, then recv some */
1109  return EOF; /* Failed to recv data */
1110  }
1111  amount = PqRecvLength - PqRecvPointer;
1112  if (amount > len)
1113  amount = len;
1114  PqRecvPointer += amount;
1115  len -= amount;
1116  }
1117  return 0;
1118 }
1119 
1120 /* --------------------------------
1121  * pq_buffer_has_data - is any buffered data available to read?
1122  *
1123  * This will *not* attempt to read more data.
1124  * --------------------------------
1125  */
1126 bool
1128 {
1129  return (PqRecvPointer < PqRecvLength);
1130 }
1131 
1132 
1133 /* --------------------------------
1134  * pq_startmsgread - begin reading a message from the client.
1135  *
1136  * This must be called before any of the pq_get* functions.
1137  * --------------------------------
1138  */
1139 void
1141 {
1142  /*
1143  * There shouldn't be a read active already, but let's check just to be
1144  * sure.
1145  */
1146  if (PqCommReadingMsg)
1147  ereport(FATAL,
1148  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1149  errmsg("terminating connection because protocol synchronization was lost")));
1150 
1151  PqCommReadingMsg = true;
1152 }
1153 
1154 
1155 /* --------------------------------
1156  * pq_endmsgread - finish reading message.
1157  *
1158  * This must be called after reading a message with pq_getbytes()
1159  * and friends, to indicate that we have read the whole message.
1160  * pq_getmessage() does this implicitly.
1161  * --------------------------------
1162  */
1163 void
1165 {
1167 
1168  PqCommReadingMsg = false;
1169 }
1170 
1171 /* --------------------------------
1172  * pq_is_reading_msg - are we currently reading a message?
1173  *
1174  * This is used in error recovery at the outer idle loop to detect if we have
1175  * lost protocol sync, and need to terminate the connection. pq_startmsgread()
1176  * will check for that too, but it's nicer to detect it earlier.
1177  * --------------------------------
1178  */
1179 bool
1181 {
1182  return PqCommReadingMsg;
1183 }
1184 
1185 /* --------------------------------
1186  * pq_getmessage - get a message with length word from connection
1187  *
1188  * The return value is placed in an expansible StringInfo, which has
1189  * already been initialized by the caller.
1190  * Only the message body is placed in the StringInfo; the length word
1191  * is removed. Also, s->cursor is initialized to zero for convenience
1192  * in scanning the message contents.
1193  *
1194  * maxlen is the upper limit on the length of the
1195  * message we are willing to accept. We abort the connection (by
1196  * returning EOF) if client tries to send more than that.
1197  *
1198  * returns 0 if OK, EOF if trouble
1199  * --------------------------------
1200  */
1201 int
1203 {
1204  int32 len;
1205 
1207 
1208  resetStringInfo(s);
1209 
1210  /* Read message length word */
1211  if (pq_getbytes((char *) &len, 4) == EOF)
1212  {
1214  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1215  errmsg("unexpected EOF within message length word")));
1216  return EOF;
1217  }
1218 
1219  len = pg_ntoh32(len);
1220 
1221  if (len < 4 || len > maxlen)
1222  {
1224  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1225  errmsg("invalid message length")));
1226  return EOF;
1227  }
1228 
1229  len -= 4; /* discount length itself */
1230 
1231  if (len > 0)
1232  {
1233  /*
1234  * Allocate space for message. If we run out of room (ridiculously
1235  * large message), we will elog(ERROR), but we want to discard the
1236  * message body so as not to lose communication sync.
1237  */
1238  PG_TRY();
1239  {
1240  enlargeStringInfo(s, len);
1241  }
1242  PG_CATCH();
1243  {
1244  if (pq_discardbytes(len) == EOF)
1246  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1247  errmsg("incomplete message from client")));
1248 
1249  /* we discarded the rest of the message so we're back in sync. */
1250  PqCommReadingMsg = false;
1251  PG_RE_THROW();
1252  }
1253  PG_END_TRY();
1254 
1255  /* And grab the message */
1256  if (pq_getbytes(s->data, len) == EOF)
1257  {
1259  (errcode(ERRCODE_PROTOCOL_VIOLATION),
1260  errmsg("incomplete message from client")));
1261  return EOF;
1262  }
1263  s->len = len;
1264  /* Place a trailing null per StringInfo convention */
1265  s->data[len] = '\0';
1266  }
1267 
1268  /* finished reading the message. */
1269  PqCommReadingMsg = false;
1270 
1271  return 0;
1272 }
1273 
1274 
1275 static int
1276 internal_putbytes(const char *s, size_t len)
1277 {
1278  size_t amount;
1279 
1280  while (len > 0)
1281  {
1282  /* If buffer is full, then flush it out */
1284  {
1285  socket_set_nonblocking(false);
1286  if (internal_flush())
1287  return EOF;
1288  }
1289  amount = PqSendBufferSize - PqSendPointer;
1290  if (amount > len)
1291  amount = len;
1292  memcpy(PqSendBuffer + PqSendPointer, s, amount);
1293  PqSendPointer += amount;
1294  s += amount;
1295  len -= amount;
1296  }
1297  return 0;
1298 }
1299 
1300 /* --------------------------------
1301  * socket_flush - flush pending output
1302  *
1303  * returns 0 if OK, EOF if trouble
1304  * --------------------------------
1305  */
1306 static int
1308 {
1309  int res;
1310 
1311  /* No-op if reentrant call */
1312  if (PqCommBusy)
1313  return 0;
1314  PqCommBusy = true;
1315  socket_set_nonblocking(false);
1316  res = internal_flush();
1317  PqCommBusy = false;
1318  return res;
1319 }
1320 
1321 /* --------------------------------
1322  * internal_flush - flush pending output
1323  *
1324  * Returns 0 if OK (meaning everything was sent, or operation would block
1325  * and the socket is in non-blocking mode), or EOF if trouble.
1326  * --------------------------------
1327  */
1328 static int
1330 {
1331  static int last_reported_send_errno = 0;
1332 
1333  char *bufptr = PqSendBuffer + PqSendStart;
1334  char *bufend = PqSendBuffer + PqSendPointer;
1335 
1336  while (bufptr < bufend)
1337  {
1338  int r;
1339 
1340  r = secure_write(MyProcPort, bufptr, bufend - bufptr);
1341 
1342  if (r <= 0)
1343  {
1344  if (errno == EINTR)
1345  continue; /* Ok if we were interrupted */
1346 
1347  /*
1348  * Ok if no data writable without blocking, and the socket is in
1349  * non-blocking mode.
1350  */
1351  if (errno == EAGAIN ||
1352  errno == EWOULDBLOCK)
1353  {
1354  return 0;
1355  }
1356 
1357  /*
1358  * Careful: an ereport() that tries to write to the client would
1359  * cause recursion to here, leading to stack overflow and core
1360  * dump! This message must go *only* to the postmaster log.
1361  *
1362  * If a client disconnects while we're in the midst of output, we
1363  * might write quite a bit of data before we get to a safe query
1364  * abort point. So, suppress duplicate log messages.
1365  */
1366  if (errno != last_reported_send_errno)
1367  {
1368  last_reported_send_errno = errno;
1371  errmsg("could not send data to client: %m")));
1372  }
1373 
1374  /*
1375  * We drop the buffered data anyway so that processing can
1376  * continue, even though we'll probably quit soon. We also set a
1377  * flag that'll cause the next CHECK_FOR_INTERRUPTS to terminate
1378  * the connection.
1379  */
1380  PqSendStart = PqSendPointer = 0;
1382  InterruptPending = 1;
1383  return EOF;
1384  }
1385 
1386  last_reported_send_errno = 0; /* reset after any successful send */
1387  bufptr += r;
1388  PqSendStart += r;
1389  }
1390 
1391  PqSendStart = PqSendPointer = 0;
1392  return 0;
1393 }
1394 
1395 /* --------------------------------
1396  * pq_flush_if_writable - flush pending output if writable without blocking
1397  *
1398  * Returns 0 if OK, or EOF if trouble.
1399  * --------------------------------
1400  */
1401 static int
1403 {
1404  int res;
1405 
1406  /* Quick exit if nothing to do */
1407  if (PqSendPointer == PqSendStart)
1408  return 0;
1409 
1410  /* No-op if reentrant call */
1411  if (PqCommBusy)
1412  return 0;
1413 
1414  /* Temporarily put the socket into non-blocking mode */
1415  socket_set_nonblocking(true);
1416 
1417  PqCommBusy = true;
1418  res = internal_flush();
1419  PqCommBusy = false;
1420  return res;
1421 }
1422 
1423 /* --------------------------------
1424  * socket_is_send_pending - is there any pending data in the output buffer?
1425  * --------------------------------
1426  */
1427 static bool
1429 {
1430  return (PqSendStart < PqSendPointer);
1431 }
1432 
1433 /* --------------------------------
1434  * Message-level I/O routines begin here.
1435  * --------------------------------
1436  */
1437 
1438 
1439 /* --------------------------------
1440  * socket_putmessage - send a normal message (suppressed in COPY OUT mode)
1441  *
1442  * msgtype is a message type code to place before the message body.
1443  *
1444  * len is the length of the message body data at *s. A message length
1445  * word (equal to len+4 because it counts itself too) is inserted by this
1446  * routine.
1447  *
1448  * We suppress messages generated while pqcomm.c is busy. This
1449  * avoids any possibility of messages being inserted within other
1450  * messages. The only known trouble case arises if SIGQUIT occurs
1451  * during a pqcomm.c routine --- quickdie() will try to send a warning
1452  * message, and the most reasonable approach seems to be to drop it.
1453  *
1454  * returns 0 if OK, EOF if trouble
1455  * --------------------------------
1456  */
1457 static int
1458 socket_putmessage(char msgtype, const char *s, size_t len)
1459 {
1460  uint32 n32;
1461 
1462  Assert(msgtype != 0);
1463 
1464  if (PqCommBusy)
1465  return 0;
1466  PqCommBusy = true;
1467  if (internal_putbytes(&msgtype, 1))
1468  goto fail;
1469 
1470  n32 = pg_hton32((uint32) (len + 4));
1471  if (internal_putbytes((char *) &n32, 4))
1472  goto fail;
1473 
1474  if (internal_putbytes(s, len))
1475  goto fail;
1476  PqCommBusy = false;
1477  return 0;
1478 
1479 fail:
1480  PqCommBusy = false;
1481  return EOF;
1482 }
1483 
1484 /* --------------------------------
1485  * pq_putmessage_noblock - like pq_putmessage, but never blocks
1486  *
1487  * If the output buffer is too small to hold the message, the buffer
1488  * is enlarged.
1489  */
1490 static void
1491 socket_putmessage_noblock(char msgtype, const char *s, size_t len)
1492 {
1494  int required;
1495 
1496  /*
1497  * Ensure we have enough space in the output buffer for the message header
1498  * as well as the message itself.
1499  */
1500  required = PqSendPointer + 1 + 4 + len;
1501  if (required > PqSendBufferSize)
1502  {
1505  }
1506  res = pq_putmessage(msgtype, s, len);
1507  Assert(res == 0); /* should not fail when the message fits in
1508  * buffer */
1509 }
1510 
1511 /* --------------------------------
1512  * pq_putmessage_v2 - send a message in protocol version 2
1513  *
1514  * msgtype is a message type code to place before the message body.
1515  *
1516  * We no longer support protocol version 2, but we have kept this
1517  * function so that if a client tries to connect with protocol version 2,
1518  * as a courtesy we can still send the "unsupported protocol version"
1519  * error to the client in the old format.
1520  *
1521  * Like in pq_putmessage(), we suppress messages generated while
1522  * pqcomm.c is busy.
1523  *
1524  * returns 0 if OK, EOF if trouble
1525  * --------------------------------
1526  */
1527 int
1528 pq_putmessage_v2(char msgtype, const char *s, size_t len)
1529 {
1530  Assert(msgtype != 0);
1531 
1532  if (PqCommBusy)
1533  return 0;
1534  PqCommBusy = true;
1535  if (internal_putbytes(&msgtype, 1))
1536  goto fail;
1537 
1538  if (internal_putbytes(s, len))
1539  goto fail;
1540  PqCommBusy = false;
1541  return 0;
1542 
1543 fail:
1544  PqCommBusy = false;
1545  return EOF;
1546 }
1547 
1548 /*
1549  * Support for TCP Keepalive parameters
1550  */
1551 
1552 /*
1553  * On Windows, we need to set both idle and interval at the same time.
1554  * We also cannot reset them to the default (setting to zero will
1555  * actually set them to zero, not default), therefore we fallback to
1556  * the out-of-the-box default instead.
1557  */
1558 #if defined(WIN32) && defined(SIO_KEEPALIVE_VALS)
1559 static int
1560 pq_setkeepaliveswin32(Port *port, int idle, int interval)
1561 {
1562  struct tcp_keepalive ka;
1563  DWORD retsize;
1564 
1565  if (idle <= 0)
1566  idle = 2 * 60 * 60; /* default = 2 hours */
1567  if (interval <= 0)
1568  interval = 1; /* default = 1 second */
1569 
1570  ka.onoff = 1;
1571  ka.keepalivetime = idle * 1000;
1572  ka.keepaliveinterval = interval * 1000;
1573 
1574  if (WSAIoctl(port->sock,
1575  SIO_KEEPALIVE_VALS,
1576  (LPVOID) &ka,
1577  sizeof(ka),
1578  NULL,
1579  0,
1580  &retsize,
1581  NULL,
1582  NULL)
1583  != 0)
1584  {
1585  ereport(LOG,
1586  (errmsg("%s(%s) failed: error code %d",
1587  "WSAIoctl", "SIO_KEEPALIVE_VALS", WSAGetLastError())));
1588  return STATUS_ERROR;
1589  }
1590  if (port->keepalives_idle != idle)
1591  port->keepalives_idle = idle;
1592  if (port->keepalives_interval != interval)
1593  port->keepalives_interval = interval;
1594  return STATUS_OK;
1595 }
1596 #endif
1597 
1598 int
1600 {
1601 #if defined(PG_TCP_KEEPALIVE_IDLE) || defined(SIO_KEEPALIVE_VALS)
1602  if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
1603  return 0;
1604 
1605  if (port->keepalives_idle != 0)
1606  return port->keepalives_idle;
1607 
1608  if (port->default_keepalives_idle == 0)
1609  {
1610 #ifndef WIN32
1611  socklen_t size = sizeof(port->default_keepalives_idle);
1612 
1613  if (getsockopt(port->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
1614  (char *) &port->default_keepalives_idle,
1615  &size) < 0)
1616  {
1617  ereport(LOG,
1618  (errmsg("%s(%s) failed: %m", "getsockopt", PG_TCP_KEEPALIVE_IDLE_STR)));
1619  port->default_keepalives_idle = -1; /* don't know */
1620  }
1621 #else /* WIN32 */
1622  /* We can't get the defaults on Windows, so return "don't know" */
1623  port->default_keepalives_idle = -1;
1624 #endif /* WIN32 */
1625  }
1626 
1627  return port->default_keepalives_idle;
1628 #else
1629  return 0;
1630 #endif
1631 }
1632 
1633 int
1635 {
1636  if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
1637  return STATUS_OK;
1638 
1639 /* check SIO_KEEPALIVE_VALS here, not just WIN32, as some toolchains lack it */
1640 #if defined(PG_TCP_KEEPALIVE_IDLE) || defined(SIO_KEEPALIVE_VALS)
1641  if (idle == port->keepalives_idle)
1642  return STATUS_OK;
1643 
1644 #ifndef WIN32
1645  if (port->default_keepalives_idle <= 0)
1646  {
1647  if (pq_getkeepalivesidle(port) < 0)
1648  {
1649  if (idle == 0)
1650  return STATUS_OK; /* default is set but unknown */
1651  else
1652  return STATUS_ERROR;
1653  }
1654  }
1655 
1656  if (idle == 0)
1657  idle = port->default_keepalives_idle;
1658 
1659  if (setsockopt(port->sock, IPPROTO_TCP, PG_TCP_KEEPALIVE_IDLE,
1660  (char *) &idle, sizeof(idle)) < 0)
1661  {
1662  ereport(LOG,
1663  (errmsg("%s(%s) failed: %m", "setsockopt", PG_TCP_KEEPALIVE_IDLE_STR)));
1664  return STATUS_ERROR;
1665  }
1666 
1667  port->keepalives_idle = idle;
1668 #else /* WIN32 */
1669  return pq_setkeepaliveswin32(port, idle, port->keepalives_interval);
1670 #endif
1671 #else
1672  if (idle != 0)
1673  {
1674  ereport(LOG,
1675  (errmsg("setting the keepalive idle time is not supported")));
1676  return STATUS_ERROR;
1677  }
1678 #endif
1679 
1680  return STATUS_OK;
1681 }
1682 
1683 int
1685 {
1686 #if defined(TCP_KEEPINTVL) || defined(SIO_KEEPALIVE_VALS)
1687  if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
1688  return 0;
1689 
1690  if (port->keepalives_interval != 0)
1691  return port->keepalives_interval;
1692 
1693  if (port->default_keepalives_interval == 0)
1694  {
1695 #ifndef WIN32
1696  socklen_t size = sizeof(port->default_keepalives_interval);
1697 
1698  if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1699  (char *) &port->default_keepalives_interval,
1700  &size) < 0)
1701  {
1702  ereport(LOG,
1703  (errmsg("%s(%s) failed: %m", "getsockopt", "TCP_KEEPINTVL")));
1704  port->default_keepalives_interval = -1; /* don't know */
1705  }
1706 #else
1707  /* We can't get the defaults on Windows, so return "don't know" */
1708  port->default_keepalives_interval = -1;
1709 #endif /* WIN32 */
1710  }
1711 
1712  return port->default_keepalives_interval;
1713 #else
1714  return 0;
1715 #endif
1716 }
1717 
1718 int
1720 {
1721  if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
1722  return STATUS_OK;
1723 
1724 #if defined(TCP_KEEPINTVL) || defined(SIO_KEEPALIVE_VALS)
1725  if (interval == port->keepalives_interval)
1726  return STATUS_OK;
1727 
1728 #ifndef WIN32
1729  if (port->default_keepalives_interval <= 0)
1730  {
1731  if (pq_getkeepalivesinterval(port) < 0)
1732  {
1733  if (interval == 0)
1734  return STATUS_OK; /* default is set but unknown */
1735  else
1736  return STATUS_ERROR;
1737  }
1738  }
1739 
1740  if (interval == 0)
1741  interval = port->default_keepalives_interval;
1742 
1743  if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1744  (char *) &interval, sizeof(interval)) < 0)
1745  {
1746  ereport(LOG,
1747  (errmsg("%s(%s) failed: %m", "setsockopt", "TCP_KEEPINTVL")));
1748  return STATUS_ERROR;
1749  }
1750 
1751  port->keepalives_interval = interval;
1752 #else /* WIN32 */
1753  return pq_setkeepaliveswin32(port, port->keepalives_idle, interval);
1754 #endif
1755 #else
1756  if (interval != 0)
1757  {
1758  ereport(LOG,
1759  (errmsg("%s(%s) not supported", "setsockopt", "TCP_KEEPINTVL")));
1760  return STATUS_ERROR;
1761  }
1762 #endif
1763 
1764  return STATUS_OK;
1765 }
1766 
1767 int
1769 {
1770 #ifdef TCP_KEEPCNT
1771  if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
1772  return 0;
1773 
1774  if (port->keepalives_count != 0)
1775  return port->keepalives_count;
1776 
1777  if (port->default_keepalives_count == 0)
1778  {
1779  socklen_t size = sizeof(port->default_keepalives_count);
1780 
1781  if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
1782  (char *) &port->default_keepalives_count,
1783  &size) < 0)
1784  {
1785  ereport(LOG,
1786  (errmsg("%s(%s) failed: %m", "getsockopt", "TCP_KEEPCNT")));
1787  port->default_keepalives_count = -1; /* don't know */
1788  }
1789  }
1790 
1791  return port->default_keepalives_count;
1792 #else
1793  return 0;
1794 #endif
1795 }
1796 
1797 int
1799 {
1800  if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
1801  return STATUS_OK;
1802 
1803 #ifdef TCP_KEEPCNT
1804  if (count == port->keepalives_count)
1805  return STATUS_OK;
1806 
1807  if (port->default_keepalives_count <= 0)
1808  {
1809  if (pq_getkeepalivescount(port) < 0)
1810  {
1811  if (count == 0)
1812  return STATUS_OK; /* default is set but unknown */
1813  else
1814  return STATUS_ERROR;
1815  }
1816  }
1817 
1818  if (count == 0)
1819  count = port->default_keepalives_count;
1820 
1821  if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
1822  (char *) &count, sizeof(count)) < 0)
1823  {
1824  ereport(LOG,
1825  (errmsg("%s(%s) failed: %m", "setsockopt", "TCP_KEEPCNT")));
1826  return STATUS_ERROR;
1827  }
1828 
1829  port->keepalives_count = count;
1830 #else
1831  if (count != 0)
1832  {
1833  ereport(LOG,
1834  (errmsg("%s(%s) not supported", "setsockopt", "TCP_KEEPCNT")));
1835  return STATUS_ERROR;
1836  }
1837 #endif
1838 
1839  return STATUS_OK;
1840 }
1841 
1842 int
1844 {
1845 #ifdef TCP_USER_TIMEOUT
1846  if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
1847  return 0;
1848 
1849  if (port->tcp_user_timeout != 0)
1850  return port->tcp_user_timeout;
1851 
1852  if (port->default_tcp_user_timeout == 0)
1853  {
1854  socklen_t size = sizeof(port->default_tcp_user_timeout);
1855 
1856  if (getsockopt(port->sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
1857  (char *) &port->default_tcp_user_timeout,
1858  &size) < 0)
1859  {
1860  ereport(LOG,
1861  (errmsg("%s(%s) failed: %m", "getsockopt", "TCP_USER_TIMEOUT")));
1862  port->default_tcp_user_timeout = -1; /* don't know */
1863  }
1864  }
1865 
1866  return port->default_tcp_user_timeout;
1867 #else
1868  return 0;
1869 #endif
1870 }
1871 
1872 int
1874 {
1875  if (port == NULL || port->laddr.addr.ss_family == AF_UNIX)
1876  return STATUS_OK;
1877 
1878 #ifdef TCP_USER_TIMEOUT
1879  if (timeout == port->tcp_user_timeout)
1880  return STATUS_OK;
1881 
1882  if (port->default_tcp_user_timeout <= 0)
1883  {
1884  if (pq_gettcpusertimeout(port) < 0)
1885  {
1886  if (timeout == 0)
1887  return STATUS_OK; /* default is set but unknown */
1888  else
1889  return STATUS_ERROR;
1890  }
1891  }
1892 
1893  if (timeout == 0)
1894  timeout = port->default_tcp_user_timeout;
1895 
1896  if (setsockopt(port->sock, IPPROTO_TCP, TCP_USER_TIMEOUT,
1897  (char *) &timeout, sizeof(timeout)) < 0)
1898  {
1899  ereport(LOG,
1900  (errmsg("%s(%s) failed: %m", "setsockopt", "TCP_USER_TIMEOUT")));
1901  return STATUS_ERROR;
1902  }
1903 
1904  port->tcp_user_timeout = timeout;
1905 #else
1906  if (timeout != 0)
1907  {
1908  ereport(LOG,
1909  (errmsg("%s(%s) not supported", "setsockopt", "TCP_USER_TIMEOUT")));
1910  return STATUS_ERROR;
1911  }
1912 #endif
1913 
1914  return STATUS_OK;
1915 }
1916 
1917 /*
1918  * GUC assign_hook for tcp_keepalives_idle
1919  */
1920 void
1922 {
1923  /*
1924  * The kernel API provides no way to test a value without setting it; and
1925  * once we set it we might fail to unset it. So there seems little point
1926  * in fully implementing the check-then-assign GUC API for these
1927  * variables. Instead we just do the assignment on demand.
1928  * pq_setkeepalivesidle reports any problems via ereport(LOG).
1929  *
1930  * This approach means that the GUC value might have little to do with the
1931  * actual kernel value, so we use a show_hook that retrieves the kernel
1932  * value rather than trusting GUC's copy.
1933  */
1935 }
1936 
1937 /*
1938  * GUC show_hook for tcp_keepalives_idle
1939  */
1940 const char *
1942 {
1943  /* See comments in assign_tcp_keepalives_idle */
1944  static char nbuf[16];
1945 
1946  snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesidle(MyProcPort));
1947  return nbuf;
1948 }
1949 
1950 /*
1951  * GUC assign_hook for tcp_keepalives_interval
1952  */
1953 void
1955 {
1956  /* See comments in assign_tcp_keepalives_idle */
1958 }
1959 
1960 /*
1961  * GUC show_hook for tcp_keepalives_interval
1962  */
1963 const char *
1965 {
1966  /* See comments in assign_tcp_keepalives_idle */
1967  static char nbuf[16];
1968 
1969  snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivesinterval(MyProcPort));
1970  return nbuf;
1971 }
1972 
1973 /*
1974  * GUC assign_hook for tcp_keepalives_count
1975  */
1976 void
1978 {
1979  /* See comments in assign_tcp_keepalives_idle */
1981 }
1982 
1983 /*
1984  * GUC show_hook for tcp_keepalives_count
1985  */
1986 const char *
1988 {
1989  /* See comments in assign_tcp_keepalives_idle */
1990  static char nbuf[16];
1991 
1992  snprintf(nbuf, sizeof(nbuf), "%d", pq_getkeepalivescount(MyProcPort));
1993  return nbuf;
1994 }
1995 
1996 /*
1997  * GUC assign_hook for tcp_user_timeout
1998  */
1999 void
2001 {
2002  /* See comments in assign_tcp_keepalives_idle */
2004 }
2005 
2006 /*
2007  * GUC show_hook for tcp_user_timeout
2008  */
2009 const char *
2011 {
2012  /* See comments in assign_tcp_keepalives_idle */
2013  static char nbuf[16];
2014 
2015  snprintf(nbuf, sizeof(nbuf), "%d", pq_gettcpusertimeout(MyProcPort));
2016  return nbuf;
2017 }
2018 
2019 /*
2020  * Check if the client is still connected.
2021  */
2022 bool
2024 {
2025  WaitEvent events[FeBeWaitSetNEvents];
2026  int rc;
2027 
2028  /*
2029  * It's OK to modify the socket event filter without restoring, because
2030  * all FeBeWaitSet socket wait sites do the same.
2031  */
2033 
2034 retry:
2035  rc = WaitEventSetWait(FeBeWaitSet, 0, events, lengthof(events), 0);
2036  for (int i = 0; i < rc; ++i)
2037  {
2038  if (events[i].events & WL_SOCKET_CLOSED)
2039  return false;
2040  if (events[i].events & WL_LATCH_SET)
2041  {
2042  /*
2043  * A latch event might be preventing other events from being
2044  * reported. Reset it and poll again. No need to restore it
2045  * because no code should expect latches to survive across
2046  * CHECK_FOR_INTERRUPTS().
2047  */
2049  goto retry;
2050  }
2051  }
2052 
2053  return true;
2054 }
ssize_t secure_write(Port *port, void *ptr, size_t len)
Definition: be-secure.c:258
void secure_close(Port *port)
Definition: be-secure.c:133
ssize_t secure_read(Port *port, void *ptr, size_t len)
Definition: be-secure.c:145
unsigned int uint32
Definition: c.h:442
#define STATUS_OK
Definition: c.h:1108
signed int int32
Definition: c.h:430
#define lengthof(array)
Definition: c.h:724
#define MemSet(start, val, len)
Definition: c.h:953
#define STATUS_ERROR
Definition: c.h:1109
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:166
int errcode_for_socket_access(void)
Definition: elog.c:789
int errcode_for_file_access(void)
Definition: elog.c:718
int errhint(const char *fmt,...)
Definition: elog.c:1153
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define _(x)
Definition: elog.c:90
#define LOG
Definition: elog.h:27
#define PG_RE_THROW()
Definition: elog.h:350
#define COMMERROR
Definition: elog.h:29
#define FATAL
Definition: elog.h:37
#define PG_TRY(...)
Definition: elog.h:309
#define WARNING
Definition: elog.h:32
#define PG_END_TRY(...)
Definition: elog.h:334
#define ERROR
Definition: elog.h:35
#define PG_CATCH(...)
Definition: elog.h:319
#define ereport(elevel,...)
Definition: elog.h:145
volatile sig_atomic_t InterruptPending
Definition: globals.c:30
int MaxConnections
Definition: globals.c:137
volatile sig_atomic_t ClientConnectionLost
Definition: globals.c:34
struct Port * MyProcPort
Definition: globals.c:47
struct Latch * MyLatch
Definition: globals.c:58
#define newval
int tcp_keepalives_idle
Definition: guc_tables.c:512
int tcp_keepalives_interval
Definition: guc_tables.c:513
int tcp_keepalives_count
Definition: guc_tables.c:514
int tcp_user_timeout
Definition: guc_tables.c:515
long val
Definition: informix.c:664
void pg_freeaddrinfo_all(int hint_ai_family, struct addrinfo *ai)
Definition: ip.c:82
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition: ip.c:114
int pg_getaddrinfo_all(const char *hostname, const char *servname, const struct addrinfo *hintp, struct addrinfo **result)
Definition: ip.c:53
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:305
int i
Definition: isn.c:73
WaitEventSet * CreateWaitEventSet(MemoryContext context, int nevents)
Definition: latch.c:707
void ModifyWaitEvent(WaitEventSet *set, int pos, uint32 events, Latch *latch)
Definition: latch.c:972
int AddWaitEventToSet(WaitEventSet *set, uint32 events, pgsocket fd, Latch *latch, void *user_data)
Definition: latch.c:886
int WaitEventSetWait(WaitEventSet *set, long timeout, WaitEvent *occurred_events, int nevents, uint32 wait_event_info)
Definition: latch.c:1345
void ResetLatch(Latch *latch)
Definition: latch.c:683
#define WL_SOCKET_CLOSED
Definition: latch.h:137
#define WL_LATCH_SET
Definition: latch.h:125
#define WL_POSTMASTER_DEATH
Definition: latch.h:129
#define WL_SOCKET_WRITEABLE
Definition: latch.h:127
#define pq_putmessage(msgtype, s, len)
Definition: libpq.h:49
#define FeBeWaitSetLatchPos
Definition: libpq.h:64
#define FeBeWaitSetNEvents
Definition: libpq.h:65
#define FeBeWaitSetSocketPos
Definition: libpq.h:63
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend(List *list, void *datum)
Definition: list.c:338
char * pstrdup(const char *in)
Definition: mcxt.c:1483
MemoryContext TopMemoryContext
Definition: mcxt.c:130
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1321
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:994
void CreateSocketLockFile(const char *socketfile, bool amPostmaster, const char *socketDir)
Definition: miscinit.c:1451
void * arg
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
#define pg_hton32(x)
Definition: pg_bswap.h:121
#define MAXPGPATH
const void size_t len
#define lfirst(lc)
Definition: pg_list.h:170
#define NIL
Definition: pg_list.h:66
static int port
Definition: pg_regress.c:90
bool pg_set_noblock(pgsocket sock)
Definition: noblock.c:25
int pgsocket
Definition: port.h:29
#define snprintf
Definition: port.h:238
unsigned int socklen_t
Definition: port.h:40
#define PGINVALID_SOCKET
Definition: port.h:31
#define closesocket
Definition: port.h:349
uintptr_t Datum
Definition: postgres.h:412
static pgsocket ListenSocket[MAXLISTEN]
Definition: postmaster.c:220
static int PqRecvLength
Definition: pqcomm.c:129
int pq_setkeepalivesinterval(int interval, Port *port)
Definition: pqcomm.c:1719
void assign_tcp_keepalives_count(int newval, void *extra)
Definition: pqcomm.c:1977
const PQcommMethods * PqCommMethods
Definition: pqcomm.c:162
static int pq_recvbuf(void)
Definition: pqcomm.c:909
static int PqSendStart
Definition: pqcomm.c:125
int Unix_socket_permissions
Definition: pqcomm.c:106
static int internal_flush(void)
Definition: pqcomm.c:1329
static void socket_set_nonblocking(bool nonblocking)
Definition: pqcomm.c:892
int pq_peekbyte(void)
Definition: pqcomm.c:989
int pq_getbyte_if_available(unsigned char *c)
Definition: pqcomm.c:1010
static int socket_flush_if_writable(void)
Definition: pqcomm.c:1402
int pq_getkeepalivescount(Port *port)
Definition: pqcomm.c:1768
#define PQ_RECV_BUFFER_SIZE
Definition: pqcomm.c:120
int pq_getkeepalivesinterval(Port *port)
Definition: pqcomm.c:1684
static int PqSendPointer
Definition: pqcomm.c:124
static int pq_discardbytes(size_t len)
Definition: pqcomm.c:1098
int pq_settcpusertimeout(int timeout, Port *port)
Definition: pqcomm.c:1873
int pq_getmessage(StringInfo s, int maxlen)
Definition: pqcomm.c:1202
static const PQcommMethods PqCommSocketMethods
Definition: pqcomm.c:153
const char * show_tcp_keepalives_interval(void)
Definition: pqcomm.c:1964
int pq_getbytes(char *s, size_t len)
Definition: pqcomm.c:1064
static bool PqCommReadingMsg
Definition: pqcomm.c:135
char * Unix_socket_group
Definition: pqcomm.c:107
void StreamClose(pgsocket sock)
Definition: pqcomm.c:826
static int socket_flush(void)
Definition: pqcomm.c:1307
const char * show_tcp_user_timeout(void)
Definition: pqcomm.c:2010
#define PQ_SEND_BUFFER_SIZE
Definition: pqcomm.c:119
int pq_setkeepalivesidle(int idle, Port *port)
Definition: pqcomm.c:1634
int StreamServerPort(int family, const char *hostName, unsigned short portNumber, const char *unixSocketDir, pgsocket ListenSocket[], int MaxListen)
Definition: pqcomm.c:314
static void socket_comm_reset(void)
Definition: pqcomm.c:228
WaitEventSet * FeBeWaitSet
Definition: pqcomm.c:164
static char * PqSendBuffer
Definition: pqcomm.c:122
static int Lock_AF_UNIX(const char *unixSocketDir, const char *unixSocketPath)
Definition: pqcomm.c:583
int pq_getkeepalivesidle(Port *port)
Definition: pqcomm.c:1599
void pq_endmsgread(void)
Definition: pqcomm.c:1164
static List * sock_paths
Definition: pqcomm.c:110
void TouchSocketFiles(void)
Definition: pqcomm.c:841
static bool PqCommBusy
Definition: pqcomm.c:134
int pq_getbyte(void)
Definition: pqcomm.c:970
static bool socket_is_send_pending(void)
Definition: pqcomm.c:1428
void assign_tcp_keepalives_idle(int newval, void *extra)
Definition: pqcomm.c:1921
static int socket_putmessage(char msgtype, const char *s, size_t len)
Definition: pqcomm.c:1458
static void socket_putmessage_noblock(char msgtype, const char *s, size_t len)
Definition: pqcomm.c:1491
bool pq_buffer_has_data(void)
Definition: pqcomm.c:1127
static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE]
Definition: pqcomm.c:127
static int PqRecvPointer
Definition: pqcomm.c:128
void pq_init(void)
Definition: pqcomm.c:172
static void socket_close(int code, Datum arg)
Definition: pqcomm.c:243
void assign_tcp_user_timeout(int newval, void *extra)
Definition: pqcomm.c:2000
int pq_putmessage_v2(char msgtype, const char *s, size_t len)
Definition: pqcomm.c:1528
const char * show_tcp_keepalives_idle(void)
Definition: pqcomm.c:1941
static int Setup_AF_UNIX(const char *sock_path)
Definition: pqcomm.c:618
bool pq_is_reading_msg(void)
Definition: pqcomm.c:1180
void RemoveSocketFiles(void)
Definition: pqcomm.c:859
int pq_gettcpusertimeout(Port *port)
Definition: pqcomm.c:1843
bool pq_check_connection(void)
Definition: pqcomm.c:2023
static int PqSendBufferSize
Definition: pqcomm.c:123
const char * show_tcp_keepalives_count(void)
Definition: pqcomm.c:1987
void assign_tcp_keepalives_interval(int newval, void *extra)
Definition: pqcomm.c:1954
void pq_startmsgread(void)
Definition: pqcomm.c:1140
int pq_setkeepalivescount(int count, Port *port)
Definition: pqcomm.c:1798
int StreamConnection(pgsocket server_fd, Port *port)
Definition: pqcomm.c:692
static int internal_putbytes(const char *s, size_t len)
Definition: pqcomm.c:1276
#define UNIXSOCK_PATH(path, port, sockdir)
Definition: pqcomm.h:32
#define UNIXSOCK_PATH_BUFLEN
Definition: pqcomm.h:48
char * c
static int fd(const char *x, int i)
Definition: preproc-init.c:105
void pg_usleep(long microsec)
Definition: signal.c:53
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:283
Definition: pg_list.h:52
Definition: libpq-be.h:146
void * gss
Definition: libpq-be.h:210
pgsocket sock
Definition: libpq-be.h:147
bool noblock
Definition: libpq-be.h:148
#define bind(s, addr, addrlen)
Definition: win32_port.h:488
#define EINTR
Definition: win32_port.h:369
#define EWOULDBLOCK
Definition: win32_port.h:375
#define EADDRINUSE
Definition: win32_port.h:395
int gid_t
Definition: win32_port.h:247
#define socket(af, type, protocol)
Definition: win32_port.h:487
#define accept(s, addr, addrlen)
Definition: win32_port.h:490
#define listen(s, backlog)
Definition: win32_port.h:489
#define EAGAIN
Definition: win32_port.h:367