Header And Logo

PostgreSQL
| The world's most advanced open source database.

pqcomm.c

Go to the documentation of this file.
00001 /*-------------------------------------------------------------------------
00002  *
00003  * pqcomm.c
00004  *    Communication functions between the Frontend and the Backend
00005  *
00006  * These routines handle the low-level details of communication between
00007  * frontend and backend.  They just shove data across the communication
00008  * channel, and are ignorant of the semantics of the data --- or would be,
00009  * except for major brain damage in the design of the old COPY OUT protocol.
00010  * Unfortunately, COPY OUT was designed to commandeer the communication
00011  * channel (it just transfers data without wrapping it into messages).
00012  * No other messages can be sent while COPY OUT is in progress; and if the
00013  * copy is aborted by an ereport(ERROR), we need to close out the copy so that
00014  * the frontend gets back into sync.  Therefore, these routines have to be
00015  * aware of COPY OUT state.  (New COPY-OUT is message-based and does *not*
00016  * set the DoingCopyOut flag.)
00017  *
00018  * NOTE: generally, it's a bad idea to emit outgoing messages directly with
00019  * pq_putbytes(), especially if the message would require multiple calls
00020  * to send.  Instead, use the routines in pqformat.c to construct the message
00021  * in a buffer and then emit it in one call to pq_putmessage.  This ensures
00022  * that the channel will not be clogged by an incomplete message if execution
00023  * is aborted by ereport(ERROR) partway through the message.  The only
00024  * non-libpq code that should call pq_putbytes directly is old-style COPY OUT.
00025  *
00026  * At one time, libpq was shared between frontend and backend, but now
00027  * the backend's "backend/libpq" is quite separate from "interfaces/libpq".
00028  * All that remains is similarities of names to trap the unwary...
00029  *
00030  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
00031  * Portions Copyright (c) 1994, Regents of the University of California
00032  *
00033  *  src/backend/libpq/pqcomm.c
00034  *
00035  *-------------------------------------------------------------------------
00036  */
00037 
00038 /*------------------------
00039  * INTERFACE ROUTINES
00040  *
00041  * setup/teardown:
00042  *      StreamServerPort    - Open postmaster's server port
00043  *      StreamConnection    - Create new connection with client
00044  *      StreamClose         - Close a client/backend connection
00045  *      TouchSocketFiles    - Protect socket files against /tmp cleaners
00046  *      pq_init         - initialize libpq at backend startup
00047  *      pq_comm_reset   - reset libpq during error recovery
00048  *      pq_close        - shutdown libpq at backend exit
00049  *
00050  * low-level I/O:
00051  *      pq_getbytes     - get a known number of bytes from connection
00052  *      pq_getstring    - get a null terminated string from connection
00053  *      pq_getmessage   - get a message with length word from connection
00054  *      pq_getbyte      - get next byte from connection
00055  *      pq_peekbyte     - peek at next byte from connection
00056  *      pq_putbytes     - send bytes to connection (not flushed until pq_flush)
00057  *      pq_flush        - flush pending output
00058  *      pq_flush_if_writable - flush pending output if writable without blocking
00059  *      pq_getbyte_if_available - get a byte if available without blocking
00060  *
00061  * message-level I/O (and old-style-COPY-OUT cruft):
00062  *      pq_putmessage   - send a normal message (suppressed in COPY OUT mode)
00063  *      pq_putmessage_noblock - buffer a normal message (suppressed in COPY OUT)
00064  *      pq_startcopyout - inform libpq that a COPY OUT transfer is beginning
00065  *      pq_endcopyout   - end a COPY OUT transfer
00066  *
00067  *------------------------
00068  */
00069 #include "postgres.h"
00070 
00071 #include <signal.h>
00072 #include <fcntl.h>
00073 #include <grp.h>
00074 #include <unistd.h>
00075 #include <sys/file.h>
00076 #include <sys/socket.h>
00077 #include <sys/stat.h>
00078 #include <sys/time.h>
00079 #include <netdb.h>
00080 #include <netinet/in.h>
00081 #ifdef HAVE_NETINET_TCP_H
00082 #include <netinet/tcp.h>
00083 #endif
00084 #include <arpa/inet.h>
00085 #ifdef HAVE_UTIME_H
00086 #include <utime.h>
00087 #endif
00088 #ifdef WIN32_ONLY_COMPILER      /* mstcpip.h is missing on mingw */
00089 #include <mstcpip.h>
00090 #endif
00091 
00092 #include "libpq/ip.h"
00093 #include "libpq/libpq.h"
00094 #include "miscadmin.h"
00095 #include "storage/ipc.h"
00096 #include "utils/guc.h"
00097 #include "utils/memutils.h"
00098 
00099 /*
00100  * Configuration options
00101  */
00102 int         Unix_socket_permissions;
00103 char       *Unix_socket_group;
00104 
00105 
00106 /* Where the Unix socket files are (list of palloc'd strings) */
00107 static List *sock_paths = NIL;
00108 
00109 
00110 /*
00111  * Buffers for low-level I/O.
00112  *
00113  * The receive buffer is fixed size. Send buffer is usually 8k, but can be
00114  * enlarged by pq_putmessage_noblock() if the message doesn't fit otherwise.
00115  */
00116 
00117 #define PQ_SEND_BUFFER_SIZE 8192
00118 #define PQ_RECV_BUFFER_SIZE 8192
00119 
00120 static char *PqSendBuffer;
00121 static int  PqSendBufferSize;   /* Size send buffer */
00122 static int  PqSendPointer;      /* Next index to store a byte in PqSendBuffer */
00123 static int  PqSendStart;        /* Next index to send a byte in PqSendBuffer */
00124 
00125 static char PqRecvBuffer[PQ_RECV_BUFFER_SIZE];
00126 static int  PqRecvPointer;      /* Next index to read a byte from PqRecvBuffer */
00127 static int  PqRecvLength;       /* End of data available in PqRecvBuffer */
00128 
00129 /*
00130  * Message status
00131  */
00132 static bool PqCommBusy;
00133 static bool DoingCopyOut;
00134 
00135 
00136 /* Internal functions */
00137 static void pq_close(int code, Datum arg);
00138 static int  internal_putbytes(const char *s, size_t len);
00139 static int  internal_flush(void);
00140 static void pq_set_nonblocking(bool nonblocking);
00141 
00142 #ifdef HAVE_UNIX_SOCKETS
00143 static int  Lock_AF_UNIX(char *unixSocketDir, char *unixSocketPath);
00144 static int  Setup_AF_UNIX(char *sock_path);
00145 #endif   /* HAVE_UNIX_SOCKETS */
00146 
00147 
00148 /* --------------------------------
00149  *      pq_init - initialize libpq at backend startup
00150  * --------------------------------
00151  */
00152 void
00153 pq_init(void)
00154 {
00155     PqSendBufferSize = PQ_SEND_BUFFER_SIZE;
00156     PqSendBuffer = MemoryContextAlloc(TopMemoryContext, PqSendBufferSize);
00157     PqSendPointer = PqSendStart = PqRecvPointer = PqRecvLength = 0;
00158     PqCommBusy = false;
00159     DoingCopyOut = false;
00160     on_proc_exit(pq_close, 0);
00161 }
00162 
00163 /* --------------------------------
00164  *      pq_comm_reset - reset libpq during error recovery
00165  *
00166  * This is called from error recovery at the outer idle loop.  It's
00167  * just to get us out of trouble if we somehow manage to elog() from
00168  * inside a pqcomm.c routine (which ideally will never happen, but...)
00169  * --------------------------------
00170  */
00171 void
00172 pq_comm_reset(void)
00173 {
00174     /* Do not throw away pending data, but do reset the busy flag */
00175     PqCommBusy = false;
00176     /* We can abort any old-style COPY OUT, too */
00177     pq_endcopyout(true);
00178 }
00179 
00180 /* --------------------------------
00181  *      pq_close - shutdown libpq at backend exit
00182  *
00183  * Note: in a standalone backend MyProcPort will be null,
00184  * don't crash during exit...
00185  * --------------------------------
00186  */
00187 static void
00188 pq_close(int code, Datum arg)
00189 {
00190     if (MyProcPort != NULL)
00191     {
00192 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
00193 #ifdef ENABLE_GSS
00194         OM_uint32   min_s;
00195 
00196         /* Shutdown GSSAPI layer */
00197         if (MyProcPort->gss->ctx != GSS_C_NO_CONTEXT)
00198             gss_delete_sec_context(&min_s, &MyProcPort->gss->ctx, NULL);
00199 
00200         if (MyProcPort->gss->cred != GSS_C_NO_CREDENTIAL)
00201             gss_release_cred(&min_s, &MyProcPort->gss->cred);
00202 #endif   /* ENABLE_GSS */
00203         /* GSS and SSPI share the port->gss struct */
00204 
00205         free(MyProcPort->gss);
00206 #endif   /* ENABLE_GSS || ENABLE_SSPI */
00207 
00208         /* Cleanly shut down SSL layer */
00209         secure_close(MyProcPort);
00210 
00211         /*
00212          * Formerly we did an explicit close() here, but it seems better to
00213          * leave the socket open until the process dies.  This allows clients
00214          * to perform a "synchronous close" if they care --- wait till the
00215          * transport layer reports connection closure, and you can be sure the
00216          * backend has exited.
00217          *
00218          * We do set sock to PGINVALID_SOCKET to prevent any further I/O,
00219          * though.
00220          */
00221         MyProcPort->sock = PGINVALID_SOCKET;
00222     }
00223 }
00224 
00225 
00226 
00227 /*
00228  * Streams -- wrapper around Unix socket system calls
00229  *
00230  *
00231  *      Stream functions are used for vanilla TCP connection protocol.
00232  */
00233 
00234 
00235 /* StreamDoUnlink()
00236  * Shutdown routine for backend connection
00237  * If any Unix sockets are used for communication, explicitly close them.
00238  */
00239 #ifdef HAVE_UNIX_SOCKETS
00240 static void
00241 StreamDoUnlink(int code, Datum arg)
00242 {
00243     ListCell   *l;
00244 
00245     /* Loop through all created sockets... */
00246     foreach(l, sock_paths)
00247     {
00248         char       *sock_path = (char *) lfirst(l);
00249 
00250         unlink(sock_path);
00251     }
00252     /* Since we're about to exit, no need to reclaim storage */
00253     sock_paths = NIL;
00254 }
00255 #endif   /* HAVE_UNIX_SOCKETS */
00256 
00257 /*
00258  * StreamServerPort -- open a "listening" port to accept connections.
00259  *
00260  * family should be AF_UNIX or AF_UNSPEC; portNumber is the port number.
00261  * For AF_UNIX ports, hostName should be NULL and unixSocketDir must be
00262  * specified.  For TCP ports, hostName is either NULL for all interfaces or
00263  * the interface to listen on, and unixSocketDir is ignored (can be NULL).
00264  *
00265  * Successfully opened sockets are added to the ListenSocket[] array (of
00266  * length MaxListen), at the first position that isn't PGINVALID_SOCKET.
00267  *
00268  * RETURNS: STATUS_OK or STATUS_ERROR
00269  */
00270 
00271 int
00272 StreamServerPort(int family, char *hostName, unsigned short portNumber,
00273                  char *unixSocketDir,
00274                  pgsocket ListenSocket[], int MaxListen)
00275 {
00276     pgsocket    fd;
00277     int         err;
00278     int         maxconn;
00279     int         ret;
00280     char        portNumberStr[32];
00281     const char *familyDesc;
00282     char        familyDescBuf[64];
00283     char       *service;
00284     struct addrinfo *addrs = NULL,
00285                *addr;
00286     struct addrinfo hint;
00287     int         listen_index = 0;
00288     int         added = 0;
00289 
00290 #ifdef HAVE_UNIX_SOCKETS
00291     char        unixSocketPath[MAXPGPATH];
00292 #endif
00293 #if !defined(WIN32) || defined(IPV6_V6ONLY)
00294     int         one = 1;
00295 #endif
00296 
00297     /* Initialize hint structure */
00298     MemSet(&hint, 0, sizeof(hint));
00299     hint.ai_family = family;
00300     hint.ai_flags = AI_PASSIVE;
00301     hint.ai_socktype = SOCK_STREAM;
00302 
00303 #ifdef HAVE_UNIX_SOCKETS
00304     if (family == AF_UNIX)
00305     {
00306         /*
00307          * Create unixSocketPath from portNumber and unixSocketDir and lock
00308          * that file path
00309          */
00310         UNIXSOCK_PATH(unixSocketPath, portNumber, unixSocketDir);
00311         if (strlen(unixSocketPath) >= UNIXSOCK_PATH_BUFLEN)
00312         {
00313             ereport(LOG,
00314                     (errmsg("Unix-domain socket path \"%s\" is too long (maximum %d bytes)",
00315                             unixSocketPath,
00316                             (int) (UNIXSOCK_PATH_BUFLEN - 1))));
00317             return STATUS_ERROR;
00318         }
00319         if (Lock_AF_UNIX(unixSocketDir, unixSocketPath) != STATUS_OK)
00320             return STATUS_ERROR;
00321         service = unixSocketPath;
00322     }
00323     else
00324 #endif   /* HAVE_UNIX_SOCKETS */
00325     {
00326         snprintf(portNumberStr, sizeof(portNumberStr), "%d", portNumber);
00327         service = portNumberStr;
00328     }
00329 
00330     ret = pg_getaddrinfo_all(hostName, service, &hint, &addrs);
00331     if (ret || !addrs)
00332     {
00333         if (hostName)
00334             ereport(LOG,
00335                     (errmsg("could not translate host name \"%s\", service \"%s\" to address: %s",
00336                             hostName, service, gai_strerror(ret))));
00337         else
00338             ereport(LOG,
00339                  (errmsg("could not translate service \"%s\" to address: %s",
00340                          service, gai_strerror(ret))));
00341         if (addrs)
00342             pg_freeaddrinfo_all(hint.ai_family, addrs);
00343         return STATUS_ERROR;
00344     }
00345 
00346     for (addr = addrs; addr; addr = addr->ai_next)
00347     {
00348         if (!IS_AF_UNIX(family) && IS_AF_UNIX(addr->ai_family))
00349         {
00350             /*
00351              * Only set up a unix domain socket when they really asked for it.
00352              * The service/port is different in that case.
00353              */
00354             continue;
00355         }
00356 
00357         /* See if there is still room to add 1 more socket. */
00358         for (; listen_index < MaxListen; listen_index++)
00359         {
00360             if (ListenSocket[listen_index] == PGINVALID_SOCKET)
00361                 break;
00362         }
00363         if (listen_index >= MaxListen)
00364         {
00365             ereport(LOG,
00366                     (errmsg("could not bind to all requested addresses: MAXLISTEN (%d) exceeded",
00367                             MaxListen)));
00368             break;
00369         }
00370 
00371         /* set up family name for possible error messages */
00372         switch (addr->ai_family)
00373         {
00374             case AF_INET:
00375                 familyDesc = _("IPv4");
00376                 break;
00377 #ifdef HAVE_IPV6
00378             case AF_INET6:
00379                 familyDesc = _("IPv6");
00380                 break;
00381 #endif
00382 #ifdef HAVE_UNIX_SOCKETS
00383             case AF_UNIX:
00384                 familyDesc = _("Unix");
00385                 break;
00386 #endif
00387             default:
00388                 snprintf(familyDescBuf, sizeof(familyDescBuf),
00389                          _("unrecognized address family %d"),
00390                          addr->ai_family);
00391                 familyDesc = familyDescBuf;
00392                 break;
00393         }
00394 
00395         if ((fd = socket(addr->ai_family, SOCK_STREAM, 0)) < 0)
00396         {
00397             ereport(LOG,
00398                     (errcode_for_socket_access(),
00399             /* translator: %s is IPv4, IPv6, or Unix */
00400                      errmsg("could not create %s socket: %m",
00401                             familyDesc)));
00402             continue;
00403         }
00404 
00405 #ifndef WIN32
00406 
00407         /*
00408          * Without the SO_REUSEADDR flag, a new postmaster can't be started
00409          * right away after a stop or crash, giving "address already in use"
00410          * error on TCP ports.
00411          *
00412          * On win32, however, this behavior only happens if the
00413          * SO_EXLUSIVEADDRUSE is set. With SO_REUSEADDR, win32 allows multiple
00414          * servers to listen on the same address, resulting in unpredictable
00415          * behavior. With no flags at all, win32 behaves as Unix with
00416          * SO_REUSEADDR.
00417          */
00418         if (!IS_AF_UNIX(addr->ai_family))
00419         {
00420             if ((setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
00421                             (char *) &one, sizeof(one))) == -1)
00422             {
00423                 ereport(LOG,
00424                         (errcode_for_socket_access(),
00425                          errmsg("setsockopt(SO_REUSEADDR) failed: %m")));
00426                 closesocket(fd);
00427                 continue;
00428             }
00429         }
00430 #endif
00431 
00432 #ifdef IPV6_V6ONLY
00433         if (addr->ai_family == AF_INET6)
00434         {
00435             if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
00436                            (char *) &one, sizeof(one)) == -1)
00437             {
00438                 ereport(LOG,
00439                         (errcode_for_socket_access(),
00440                          errmsg("setsockopt(IPV6_V6ONLY) failed: %m")));
00441                 closesocket(fd);
00442                 continue;
00443             }
00444         }
00445 #endif
00446 
00447         /*
00448          * Note: This might fail on some OS's, like Linux older than
00449          * 2.4.21-pre3, that don't have the IPV6_V6ONLY socket option, and map
00450          * ipv4 addresses to ipv6.  It will show ::ffff:ipv4 for all ipv4
00451          * connections.
00452          */
00453         err = bind(fd, addr->ai_addr, addr->ai_addrlen);
00454         if (err < 0)
00455         {
00456             ereport(LOG,
00457                     (errcode_for_socket_access(),
00458             /* translator: %s is IPv4, IPv6, or Unix */
00459                      errmsg("could not bind %s socket: %m",
00460                             familyDesc),
00461                      (IS_AF_UNIX(addr->ai_family)) ?
00462                   errhint("Is another postmaster already running on port %d?"
00463                           " If not, remove socket file \"%s\" and retry.",
00464                           (int) portNumber, service) :
00465                   errhint("Is another postmaster already running on port %d?"
00466                           " If not, wait a few seconds and retry.",
00467                           (int) portNumber)));
00468             closesocket(fd);
00469             continue;
00470         }
00471 
00472 #ifdef HAVE_UNIX_SOCKETS
00473         if (addr->ai_family == AF_UNIX)
00474         {
00475             if (Setup_AF_UNIX(service) != STATUS_OK)
00476             {
00477                 closesocket(fd);
00478                 break;
00479             }
00480         }
00481 #endif
00482 
00483         /*
00484          * Select appropriate accept-queue length limit.  PG_SOMAXCONN is only
00485          * intended to provide a clamp on the request on platforms where an
00486          * overly large request provokes a kernel error (are there any?).
00487          */
00488         maxconn = MaxBackends * 2;
00489         if (maxconn > PG_SOMAXCONN)
00490             maxconn = PG_SOMAXCONN;
00491 
00492         err = listen(fd, maxconn);
00493         if (err < 0)
00494         {
00495             ereport(LOG,
00496                     (errcode_for_socket_access(),
00497             /* translator: %s is IPv4, IPv6, or Unix */
00498                      errmsg("could not listen on %s socket: %m",
00499                             familyDesc)));
00500             closesocket(fd);
00501             continue;
00502         }
00503         ListenSocket[listen_index] = fd;
00504         added++;
00505     }
00506 
00507     pg_freeaddrinfo_all(hint.ai_family, addrs);
00508 
00509     if (!added)
00510         return STATUS_ERROR;
00511 
00512     return STATUS_OK;
00513 }
00514 
00515 
00516 #ifdef HAVE_UNIX_SOCKETS
00517 
00518 /*
00519  * Lock_AF_UNIX -- configure unix socket file path
00520  */
00521 static int
00522 Lock_AF_UNIX(char *unixSocketDir, char *unixSocketPath)
00523 {
00524     /*
00525      * Grab an interlock file associated with the socket file.
00526      *
00527      * Note: there are two reasons for using a socket lock file, rather than
00528      * trying to interlock directly on the socket itself.  First, it's a lot
00529      * more portable, and second, it lets us remove any pre-existing socket
00530      * file without race conditions.
00531      */
00532     CreateSocketLockFile(unixSocketPath, true, unixSocketDir);
00533 
00534     /*
00535      * Once we have the interlock, we can safely delete any pre-existing
00536      * socket file to avoid failure at bind() time.
00537      */
00538     unlink(unixSocketPath);
00539 
00540     /*
00541      * Arrange to unlink the socket file(s) at proc_exit.  If this is the
00542      * first one, set up the on_proc_exit function to do it; then add this
00543      * socket file to the list of files to unlink.
00544      */
00545     if (sock_paths == NIL)
00546         on_proc_exit(StreamDoUnlink, 0);
00547 
00548     sock_paths = lappend(sock_paths, pstrdup(unixSocketPath));
00549 
00550     return STATUS_OK;
00551 }
00552 
00553 
00554 /*
00555  * Setup_AF_UNIX -- configure unix socket permissions
00556  */
00557 static int
00558 Setup_AF_UNIX(char *sock_path)
00559 {
00560     /*
00561      * Fix socket ownership/permission if requested.  Note we must do this
00562      * before we listen() to avoid a window where unwanted connections could
00563      * get accepted.
00564      */
00565     Assert(Unix_socket_group);
00566     if (Unix_socket_group[0] != '\0')
00567     {
00568 #ifdef WIN32
00569         elog(WARNING, "configuration item unix_socket_group is not supported on this platform");
00570 #else
00571         char       *endptr;
00572         unsigned long val;
00573         gid_t       gid;
00574 
00575         val = strtoul(Unix_socket_group, &endptr, 10);
00576         if (*endptr == '\0')
00577         {                       /* numeric group id */
00578             gid = val;
00579         }
00580         else
00581         {                       /* convert group name to id */
00582             struct group *gr;
00583 
00584             gr = getgrnam(Unix_socket_group);
00585             if (!gr)
00586             {
00587                 ereport(LOG,
00588                         (errmsg("group \"%s\" does not exist",
00589                                 Unix_socket_group)));
00590                 return STATUS_ERROR;
00591             }
00592             gid = gr->gr_gid;
00593         }
00594         if (chown(sock_path, -1, gid) == -1)
00595         {
00596             ereport(LOG,
00597                     (errcode_for_file_access(),
00598                      errmsg("could not set group of file \"%s\": %m",
00599                             sock_path)));
00600             return STATUS_ERROR;
00601         }
00602 #endif
00603     }
00604 
00605     if (chmod(sock_path, Unix_socket_permissions) == -1)
00606     {
00607         ereport(LOG,
00608                 (errcode_for_file_access(),
00609                  errmsg("could not set permissions of file \"%s\": %m",
00610                         sock_path)));
00611         return STATUS_ERROR;
00612     }
00613     return STATUS_OK;
00614 }
00615 #endif   /* HAVE_UNIX_SOCKETS */
00616 
00617 
00618 /*
00619  * StreamConnection -- create a new connection with client using
00620  *      server port.  Set port->sock to the FD of the new connection.
00621  *
00622  * ASSUME: that this doesn't need to be non-blocking because
00623  *      the Postmaster uses select() to tell when the server master
00624  *      socket is ready for accept().
00625  *
00626  * RETURNS: STATUS_OK or STATUS_ERROR
00627  */
00628 int
00629 StreamConnection(pgsocket server_fd, Port *port)
00630 {
00631     /* accept connection and fill in the client (remote) address */
00632     port->raddr.salen = sizeof(port->raddr.addr);
00633     if ((port->sock = accept(server_fd,
00634                              (struct sockaddr *) & port->raddr.addr,
00635                              &port->raddr.salen)) < 0)
00636     {
00637         ereport(LOG,
00638                 (errcode_for_socket_access(),
00639                  errmsg("could not accept new connection: %m")));
00640 
00641         /*
00642          * If accept() fails then postmaster.c will still see the server
00643          * socket as read-ready, and will immediately try again.  To avoid
00644          * uselessly sucking lots of CPU, delay a bit before trying again.
00645          * (The most likely reason for failure is being out of kernel file
00646          * table slots; we can do little except hope some will get freed up.)
00647          */
00648         pg_usleep(100000L);     /* wait 0.1 sec */
00649         return STATUS_ERROR;
00650     }
00651 
00652 #ifdef SCO_ACCEPT_BUG
00653 
00654     /*
00655      * UnixWare 7+ and OpenServer 5.0.4 are known to have this bug, but it
00656      * shouldn't hurt to catch it for all versions of those platforms.
00657      */
00658     if (port->raddr.addr.ss_family == 0)
00659         port->raddr.addr.ss_family = AF_UNIX;
00660 #endif
00661 
00662     /* fill in the server (local) address */
00663     port->laddr.salen = sizeof(port->laddr.addr);
00664     if (getsockname(port->sock,
00665                     (struct sockaddr *) & port->laddr.addr,
00666                     &port->laddr.salen) < 0)
00667     {
00668         elog(LOG, "getsockname() failed: %m");
00669         return STATUS_ERROR;
00670     }
00671 
00672     /* select NODELAY and KEEPALIVE options if it's a TCP connection */
00673     if (!IS_AF_UNIX(port->laddr.addr.ss_family))
00674     {
00675         int         on;
00676 
00677 #ifdef  TCP_NODELAY
00678         on = 1;
00679         if (setsockopt(port->sock, IPPROTO_TCP, TCP_NODELAY,
00680                        (char *) &on, sizeof(on)) < 0)
00681         {
00682             elog(LOG, "setsockopt(TCP_NODELAY) failed: %m");
00683             return STATUS_ERROR;
00684         }
00685 #endif
00686         on = 1;
00687         if (setsockopt(port->sock, SOL_SOCKET, SO_KEEPALIVE,
00688                        (char *) &on, sizeof(on)) < 0)
00689         {
00690             elog(LOG, "setsockopt(SO_KEEPALIVE) failed: %m");
00691             return STATUS_ERROR;
00692         }
00693 
00694 #ifdef WIN32
00695 
00696         /*
00697          * This is a Win32 socket optimization.  The ideal size is 32k.
00698          * http://support.microsoft.com/kb/823764/EN-US/
00699          */
00700         on = PQ_SEND_BUFFER_SIZE * 4;
00701         if (setsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &on,
00702                        sizeof(on)) < 0)
00703         {
00704             elog(LOG, "setsockopt(SO_SNDBUF) failed: %m");
00705             return STATUS_ERROR;
00706         }
00707 #endif
00708 
00709         /*
00710          * Also apply the current keepalive parameters.  If we fail to set a
00711          * parameter, don't error out, because these aren't universally
00712          * supported.  (Note: you might think we need to reset the GUC
00713          * variables to 0 in such a case, but it's not necessary because the
00714          * show hooks for these variables report the truth anyway.)
00715          */
00716         (void) pq_setkeepalivesidle(tcp_keepalives_idle, port);
00717         (void) pq_setkeepalivesinterval(tcp_keepalives_interval, port);
00718         (void) pq_setkeepalivescount(tcp_keepalives_count, port);
00719     }
00720 
00721     return STATUS_OK;
00722 }
00723 
00724 /*
00725  * StreamClose -- close a client/backend connection
00726  *
00727  * NOTE: this is NOT used to terminate a session; it is just used to release
00728  * the file descriptor in a process that should no longer have the socket
00729  * open.  (For example, the postmaster calls this after passing ownership
00730  * of the connection to a child process.)  It is expected that someone else
00731  * still has the socket open.  So, we only want to close the descriptor,
00732  * we do NOT want to send anything to the far end.
00733  */
00734 void
00735 StreamClose(pgsocket sock)
00736 {
00737     closesocket(sock);
00738 }
00739 
00740 /*
00741  * TouchSocketFiles -- mark socket files as recently accessed
00742  *
00743  * This routine should be called every so often to ensure that the socket
00744  * files have a recent mod date (ordinary operations on sockets usually won't
00745  * change the mod date).  That saves them from being removed by
00746  * overenthusiastic /tmp-directory-cleaner daemons.  (Another reason we should
00747  * never have put the socket file in /tmp...)
00748  */
00749 void
00750 TouchSocketFiles(void)
00751 {
00752     ListCell   *l;
00753 
00754     /* Loop through all created sockets... */
00755     foreach(l, sock_paths)
00756     {
00757         char       *sock_path = (char *) lfirst(l);
00758 
00759         /*
00760          * utime() is POSIX standard, utimes() is a common alternative. If we
00761          * have neither, there's no way to affect the mod or access time of
00762          * the socket :-(
00763          *
00764          * In either path, we ignore errors; there's no point in complaining.
00765          */
00766 #ifdef HAVE_UTIME
00767         utime(sock_path, NULL);
00768 #else                           /* !HAVE_UTIME */
00769 #ifdef HAVE_UTIMES
00770         utimes(sock_path, NULL);
00771 #endif   /* HAVE_UTIMES */
00772 #endif   /* HAVE_UTIME */
00773     }
00774 }
00775 
00776 
00777 /* --------------------------------
00778  * Low-level I/O routines begin here.
00779  *
00780  * These routines communicate with a frontend client across a connection
00781  * already established by the preceding routines.
00782  * --------------------------------
00783  */
00784 
00785 /* --------------------------------
00786  *            pq_set_nonblocking - set socket blocking/non-blocking
00787  *
00788  * Sets the socket non-blocking if nonblocking is TRUE, or sets it
00789  * blocking otherwise.
00790  * --------------------------------
00791  */
00792 static void
00793 pq_set_nonblocking(bool nonblocking)
00794 {
00795     if (MyProcPort->noblock == nonblocking)
00796         return;
00797 
00798 #ifdef WIN32
00799     pgwin32_noblock = nonblocking ? 1 : 0;
00800 #else
00801 
00802     /*
00803      * Use COMMERROR on failure, because ERROR would try to send the error to
00804      * the client, which might require changing the mode again, leading to
00805      * infinite recursion.
00806      */
00807     if (nonblocking)
00808     {
00809         if (!pg_set_noblock(MyProcPort->sock))
00810             ereport(COMMERROR,
00811                   (errmsg("could not set socket to nonblocking mode: %m")));
00812     }
00813     else
00814     {
00815         if (!pg_set_block(MyProcPort->sock))
00816             ereport(COMMERROR,
00817                     (errmsg("could not set socket to blocking mode: %m")));
00818     }
00819 #endif
00820     MyProcPort->noblock = nonblocking;
00821 }
00822 
00823 /* --------------------------------
00824  *      pq_recvbuf - load some bytes into the input buffer
00825  *
00826  *      returns 0 if OK, EOF if trouble
00827  * --------------------------------
00828  */
00829 static int
00830 pq_recvbuf(void)
00831 {
00832     if (PqRecvPointer > 0)
00833     {
00834         if (PqRecvLength > PqRecvPointer)
00835         {
00836             /* still some unread data, left-justify it in the buffer */
00837             memmove(PqRecvBuffer, PqRecvBuffer + PqRecvPointer,
00838                     PqRecvLength - PqRecvPointer);
00839             PqRecvLength -= PqRecvPointer;
00840             PqRecvPointer = 0;
00841         }
00842         else
00843             PqRecvLength = PqRecvPointer = 0;
00844     }
00845 
00846     /* Ensure that we're in blocking mode */
00847     pq_set_nonblocking(false);
00848 
00849     /* Can fill buffer from PqRecvLength and upwards */
00850     for (;;)
00851     {
00852         int         r;
00853 
00854         r = secure_read(MyProcPort, PqRecvBuffer + PqRecvLength,
00855                         PQ_RECV_BUFFER_SIZE - PqRecvLength);
00856 
00857         if (r < 0)
00858         {
00859             if (errno == EINTR)
00860                 continue;       /* Ok if interrupted */
00861 
00862             /*
00863              * Careful: an ereport() that tries to write to the client would
00864              * cause recursion to here, leading to stack overflow and core
00865              * dump!  This message must go *only* to the postmaster log.
00866              */
00867             ereport(COMMERROR,
00868                     (errcode_for_socket_access(),
00869                      errmsg("could not receive data from client: %m")));
00870             return EOF;
00871         }
00872         if (r == 0)
00873         {
00874             /*
00875              * EOF detected.  We used to write a log message here, but it's
00876              * better to expect the ultimate caller to do that.
00877              */
00878             return EOF;
00879         }
00880         /* r contains number of bytes read, so just incr length */
00881         PqRecvLength += r;
00882         return 0;
00883     }
00884 }
00885 
00886 /* --------------------------------
00887  *      pq_getbyte  - get a single byte from connection, or return EOF
00888  * --------------------------------
00889  */
00890 int
00891 pq_getbyte(void)
00892 {
00893     while (PqRecvPointer >= PqRecvLength)
00894     {
00895         if (pq_recvbuf())       /* If nothing in buffer, then recv some */
00896             return EOF;         /* Failed to recv data */
00897     }
00898     return (unsigned char) PqRecvBuffer[PqRecvPointer++];
00899 }
00900 
00901 /* --------------------------------
00902  *      pq_peekbyte     - peek at next byte from connection
00903  *
00904  *   Same as pq_getbyte() except we don't advance the pointer.
00905  * --------------------------------
00906  */
00907 int
00908 pq_peekbyte(void)
00909 {
00910     while (PqRecvPointer >= PqRecvLength)
00911     {
00912         if (pq_recvbuf())       /* If nothing in buffer, then recv some */
00913             return EOF;         /* Failed to recv data */
00914     }
00915     return (unsigned char) PqRecvBuffer[PqRecvPointer];
00916 }
00917 
00918 /* --------------------------------
00919  *      pq_getbyte_if_available - get a single byte from connection,
00920  *          if available
00921  *
00922  * The received byte is stored in *c. Returns 1 if a byte was read,
00923  * 0 if no data was available, or EOF if trouble.
00924  * --------------------------------
00925  */
00926 int
00927 pq_getbyte_if_available(unsigned char *c)
00928 {
00929     int         r;
00930 
00931     if (PqRecvPointer < PqRecvLength)
00932     {
00933         *c = PqRecvBuffer[PqRecvPointer++];
00934         return 1;
00935     }
00936 
00937     /* Put the socket into non-blocking mode */
00938     pq_set_nonblocking(true);
00939 
00940     r = secure_read(MyProcPort, c, 1);
00941     if (r < 0)
00942     {
00943         /*
00944          * Ok if no data available without blocking or interrupted (though
00945          * EINTR really shouldn't happen with a non-blocking socket). Report
00946          * other errors.
00947          */
00948         if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)
00949             r = 0;
00950         else
00951         {
00952             /*
00953              * Careful: an ereport() that tries to write to the client would
00954              * cause recursion to here, leading to stack overflow and core
00955              * dump!  This message must go *only* to the postmaster log.
00956              */
00957             ereport(COMMERROR,
00958                     (errcode_for_socket_access(),
00959                      errmsg("could not receive data from client: %m")));
00960             r = EOF;
00961         }
00962     }
00963     else if (r == 0)
00964     {
00965         /* EOF detected */
00966         r = EOF;
00967     }
00968 
00969     return r;
00970 }
00971 
00972 /* --------------------------------
00973  *      pq_getbytes     - get a known number of bytes from connection
00974  *
00975  *      returns 0 if OK, EOF if trouble
00976  * --------------------------------
00977  */
00978 int
00979 pq_getbytes(char *s, size_t len)
00980 {
00981     size_t      amount;
00982 
00983     while (len > 0)
00984     {
00985         while (PqRecvPointer >= PqRecvLength)
00986         {
00987             if (pq_recvbuf())   /* If nothing in buffer, then recv some */
00988                 return EOF;     /* Failed to recv data */
00989         }
00990         amount = PqRecvLength - PqRecvPointer;
00991         if (amount > len)
00992             amount = len;
00993         memcpy(s, PqRecvBuffer + PqRecvPointer, amount);
00994         PqRecvPointer += amount;
00995         s += amount;
00996         len -= amount;
00997     }
00998     return 0;
00999 }
01000 
01001 /* --------------------------------
01002  *      pq_discardbytes     - throw away a known number of bytes
01003  *
01004  *      same as pq_getbytes except we do not copy the data to anyplace.
01005  *      this is used for resynchronizing after read errors.
01006  *
01007  *      returns 0 if OK, EOF if trouble
01008  * --------------------------------
01009  */
01010 static int
01011 pq_discardbytes(size_t len)
01012 {
01013     size_t      amount;
01014 
01015     while (len > 0)
01016     {
01017         while (PqRecvPointer >= PqRecvLength)
01018         {
01019             if (pq_recvbuf())   /* If nothing in buffer, then recv some */
01020                 return EOF;     /* Failed to recv data */
01021         }
01022         amount = PqRecvLength - PqRecvPointer;
01023         if (amount > len)
01024             amount = len;
01025         PqRecvPointer += amount;
01026         len -= amount;
01027     }
01028     return 0;
01029 }
01030 
01031 /* --------------------------------
01032  *      pq_getstring    - get a null terminated string from connection
01033  *
01034  *      The return value is placed in an expansible StringInfo, which has
01035  *      already been initialized by the caller.
01036  *
01037  *      This is used only for dealing with old-protocol clients.  The idea
01038  *      is to produce a StringInfo that looks the same as we would get from
01039  *      pq_getmessage() with a newer client; we will then process it with
01040  *      pq_getmsgstring.  Therefore, no character set conversion is done here,
01041  *      even though this is presumably useful only for text.
01042  *
01043  *      returns 0 if OK, EOF if trouble
01044  * --------------------------------
01045  */
01046 int
01047 pq_getstring(StringInfo s)
01048 {
01049     int         i;
01050 
01051     resetStringInfo(s);
01052 
01053     /* Read until we get the terminating '\0' */
01054     for (;;)
01055     {
01056         while (PqRecvPointer >= PqRecvLength)
01057         {
01058             if (pq_recvbuf())   /* If nothing in buffer, then recv some */
01059                 return EOF;     /* Failed to recv data */
01060         }
01061 
01062         for (i = PqRecvPointer; i < PqRecvLength; i++)
01063         {
01064             if (PqRecvBuffer[i] == '\0')
01065             {
01066                 /* include the '\0' in the copy */
01067                 appendBinaryStringInfo(s, PqRecvBuffer + PqRecvPointer,
01068                                        i - PqRecvPointer + 1);
01069                 PqRecvPointer = i + 1;  /* advance past \0 */
01070                 return 0;
01071             }
01072         }
01073 
01074         /* If we're here we haven't got the \0 in the buffer yet. */
01075         appendBinaryStringInfo(s, PqRecvBuffer + PqRecvPointer,
01076                                PqRecvLength - PqRecvPointer);
01077         PqRecvPointer = PqRecvLength;
01078     }
01079 }
01080 
01081 
01082 /* --------------------------------
01083  *      pq_getmessage   - get a message with length word from connection
01084  *
01085  *      The return value is placed in an expansible StringInfo, which has
01086  *      already been initialized by the caller.
01087  *      Only the message body is placed in the StringInfo; the length word
01088  *      is removed.  Also, s->cursor is initialized to zero for convenience
01089  *      in scanning the message contents.
01090  *
01091  *      If maxlen is not zero, it is an upper limit on the length of the
01092  *      message we are willing to accept.  We abort the connection (by
01093  *      returning EOF) if client tries to send more than that.
01094  *
01095  *      returns 0 if OK, EOF if trouble
01096  * --------------------------------
01097  */
01098 int
01099 pq_getmessage(StringInfo s, int maxlen)
01100 {
01101     int32       len;
01102 
01103     resetStringInfo(s);
01104 
01105     /* Read message length word */
01106     if (pq_getbytes((char *) &len, 4) == EOF)
01107     {
01108         ereport(COMMERROR,
01109                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
01110                  errmsg("unexpected EOF within message length word")));
01111         return EOF;
01112     }
01113 
01114     len = ntohl(len);
01115 
01116     if (len < 4 ||
01117         (maxlen > 0 && len > maxlen))
01118     {
01119         ereport(COMMERROR,
01120                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
01121                  errmsg("invalid message length")));
01122         return EOF;
01123     }
01124 
01125     len -= 4;                   /* discount length itself */
01126 
01127     if (len > 0)
01128     {
01129         /*
01130          * Allocate space for message.  If we run out of room (ridiculously
01131          * large message), we will elog(ERROR), but we want to discard the
01132          * message body so as not to lose communication sync.
01133          */
01134         PG_TRY();
01135         {
01136             enlargeStringInfo(s, len);
01137         }
01138         PG_CATCH();
01139         {
01140             if (pq_discardbytes(len) == EOF)
01141                 ereport(COMMERROR,
01142                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
01143                          errmsg("incomplete message from client")));
01144             PG_RE_THROW();
01145         }
01146         PG_END_TRY();
01147 
01148         /* And grab the message */
01149         if (pq_getbytes(s->data, len) == EOF)
01150         {
01151             ereport(COMMERROR,
01152                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
01153                      errmsg("incomplete message from client")));
01154             return EOF;
01155         }
01156         s->len = len;
01157         /* Place a trailing null per StringInfo convention */
01158         s->data[len] = '\0';
01159     }
01160 
01161     return 0;
01162 }
01163 
01164 
01165 /* --------------------------------
01166  *      pq_putbytes     - send bytes to connection (not flushed until pq_flush)
01167  *
01168  *      returns 0 if OK, EOF if trouble
01169  * --------------------------------
01170  */
01171 int
01172 pq_putbytes(const char *s, size_t len)
01173 {
01174     int         res;
01175 
01176     /* Should only be called by old-style COPY OUT */
01177     Assert(DoingCopyOut);
01178     /* No-op if reentrant call */
01179     if (PqCommBusy)
01180         return 0;
01181     PqCommBusy = true;
01182     res = internal_putbytes(s, len);
01183     PqCommBusy = false;
01184     return res;
01185 }
01186 
01187 static int
01188 internal_putbytes(const char *s, size_t len)
01189 {
01190     size_t      amount;
01191 
01192     while (len > 0)
01193     {
01194         /* If buffer is full, then flush it out */
01195         if (PqSendPointer >= PqSendBufferSize)
01196         {
01197             pq_set_nonblocking(false);
01198             if (internal_flush())
01199                 return EOF;
01200         }
01201         amount = PqSendBufferSize - PqSendPointer;
01202         if (amount > len)
01203             amount = len;
01204         memcpy(PqSendBuffer + PqSendPointer, s, amount);
01205         PqSendPointer += amount;
01206         s += amount;
01207         len -= amount;
01208     }
01209     return 0;
01210 }
01211 
01212 /* --------------------------------
01213  *      pq_flush        - flush pending output
01214  *
01215  *      returns 0 if OK, EOF if trouble
01216  * --------------------------------
01217  */
01218 int
01219 pq_flush(void)
01220 {
01221     int         res;
01222 
01223     /* No-op if reentrant call */
01224     if (PqCommBusy)
01225         return 0;
01226     PqCommBusy = true;
01227     pq_set_nonblocking(false);
01228     res = internal_flush();
01229     PqCommBusy = false;
01230     return res;
01231 }
01232 
01233 /* --------------------------------
01234  *      internal_flush - flush pending output
01235  *
01236  * Returns 0 if OK (meaning everything was sent, or operation would block
01237  * and the socket is in non-blocking mode), or EOF if trouble.
01238  * --------------------------------
01239  */
01240 static int
01241 internal_flush(void)
01242 {
01243     static int  last_reported_send_errno = 0;
01244 
01245     char       *bufptr = PqSendBuffer + PqSendStart;
01246     char       *bufend = PqSendBuffer + PqSendPointer;
01247 
01248     while (bufptr < bufend)
01249     {
01250         int         r;
01251 
01252         r = secure_write(MyProcPort, bufptr, bufend - bufptr);
01253 
01254         if (r <= 0)
01255         {
01256             if (errno == EINTR)
01257                 continue;       /* Ok if we were interrupted */
01258 
01259             /*
01260              * Ok if no data writable without blocking, and the socket is in
01261              * non-blocking mode.
01262              */
01263             if (errno == EAGAIN ||
01264                 errno == EWOULDBLOCK)
01265             {
01266                 return 0;
01267             }
01268 
01269             /*
01270              * Careful: an ereport() that tries to write to the client would
01271              * cause recursion to here, leading to stack overflow and core
01272              * dump!  This message must go *only* to the postmaster log.
01273              *
01274              * If a client disconnects while we're in the midst of output, we
01275              * might write quite a bit of data before we get to a safe query
01276              * abort point.  So, suppress duplicate log messages.
01277              */
01278             if (errno != last_reported_send_errno)
01279             {
01280                 last_reported_send_errno = errno;
01281                 ereport(COMMERROR,
01282                         (errcode_for_socket_access(),
01283                          errmsg("could not send data to client: %m")));
01284             }
01285 
01286             /*
01287              * We drop the buffered data anyway so that processing can
01288              * continue, even though we'll probably quit soon. We also set a
01289              * flag that'll cause the next CHECK_FOR_INTERRUPTS to terminate
01290              * the connection.
01291              */
01292             PqSendStart = PqSendPointer = 0;
01293             ClientConnectionLost = 1;
01294             InterruptPending = 1;
01295             return EOF;
01296         }
01297 
01298         last_reported_send_errno = 0;   /* reset after any successful send */
01299         bufptr += r;
01300         PqSendStart += r;
01301     }
01302 
01303     PqSendStart = PqSendPointer = 0;
01304     return 0;
01305 }
01306 
01307 /* --------------------------------
01308  *      pq_flush_if_writable - flush pending output if writable without blocking
01309  *
01310  * Returns 0 if OK, or EOF if trouble.
01311  * --------------------------------
01312  */
01313 int
01314 pq_flush_if_writable(void)
01315 {
01316     int         res;
01317 
01318     /* Quick exit if nothing to do */
01319     if (PqSendPointer == PqSendStart)
01320         return 0;
01321 
01322     /* No-op if reentrant call */
01323     if (PqCommBusy)
01324         return 0;
01325 
01326     /* Temporarily put the socket into non-blocking mode */
01327     pq_set_nonblocking(true);
01328 
01329     PqCommBusy = true;
01330     res = internal_flush();
01331     PqCommBusy = false;
01332     return res;
01333 }
01334 
01335 /* --------------------------------
01336  *      pq_is_send_pending  - is there any pending data in the output buffer?
01337  * --------------------------------
01338  */
01339 bool
01340 pq_is_send_pending(void)
01341 {
01342     return (PqSendStart < PqSendPointer);
01343 }
01344 
01345 /* --------------------------------
01346  * Message-level I/O routines begin here.
01347  *
01348  * These routines understand about the old-style COPY OUT protocol.
01349  * --------------------------------
01350  */
01351 
01352 
01353 /* --------------------------------
01354  *      pq_putmessage   - send a normal message (suppressed in COPY OUT mode)
01355  *
01356  *      If msgtype is not '\0', it is a message type code to place before
01357  *      the message body.  If msgtype is '\0', then the message has no type
01358  *      code (this is only valid in pre-3.0 protocols).
01359  *
01360  *      len is the length of the message body data at *s.  In protocol 3.0
01361  *      and later, a message length word (equal to len+4 because it counts
01362  *      itself too) is inserted by this routine.
01363  *
01364  *      All normal messages are suppressed while old-style COPY OUT is in
01365  *      progress.  (In practice only a few notice messages might get emitted
01366  *      then; dropping them is annoying, but at least they will still appear
01367  *      in the postmaster log.)
01368  *
01369  *      We also suppress messages generated while pqcomm.c is busy.  This
01370  *      avoids any possibility of messages being inserted within other
01371  *      messages.  The only known trouble case arises if SIGQUIT occurs
01372  *      during a pqcomm.c routine --- quickdie() will try to send a warning
01373  *      message, and the most reasonable approach seems to be to drop it.
01374  *
01375  *      returns 0 if OK, EOF if trouble
01376  * --------------------------------
01377  */
01378 int
01379 pq_putmessage(char msgtype, const char *s, size_t len)
01380 {
01381     if (DoingCopyOut || PqCommBusy)
01382         return 0;
01383     PqCommBusy = true;
01384     if (msgtype)
01385         if (internal_putbytes(&msgtype, 1))
01386             goto fail;
01387     if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
01388     {
01389         uint32      n32;
01390 
01391         n32 = htonl((uint32) (len + 4));
01392         if (internal_putbytes((char *) &n32, 4))
01393             goto fail;
01394     }
01395     if (internal_putbytes(s, len))
01396         goto fail;
01397     PqCommBusy = false;
01398     return 0;
01399 
01400 fail:
01401     PqCommBusy = false;
01402     return EOF;
01403 }
01404 
01405 /* --------------------------------
01406  *      pq_putmessage_noblock   - like pq_putmessage, but never blocks
01407  *
01408  *      If the output buffer is too small to hold the message, the buffer
01409  *      is enlarged.
01410  */
01411 void
01412 pq_putmessage_noblock(char msgtype, const char *s, size_t len)
01413 {
01414     int res     PG_USED_FOR_ASSERTS_ONLY;
01415     int         required;
01416 
01417     /*
01418      * Ensure we have enough space in the output buffer for the message header
01419      * as well as the message itself.
01420      */
01421     required = PqSendPointer + 1 + 4 + len;
01422     if (required > PqSendBufferSize)
01423     {
01424         PqSendBuffer = repalloc(PqSendBuffer, required);
01425         PqSendBufferSize = required;
01426     }
01427     res = pq_putmessage(msgtype, s, len);
01428     Assert(res == 0);           /* should not fail when the message fits in
01429                                  * buffer */
01430 }
01431 
01432 
01433 /* --------------------------------
01434  *      pq_startcopyout - inform libpq that an old-style COPY OUT transfer
01435  *          is beginning
01436  * --------------------------------
01437  */
01438 void
01439 pq_startcopyout(void)
01440 {
01441     DoingCopyOut = true;
01442 }
01443 
01444 /* --------------------------------
01445  *      pq_endcopyout   - end an old-style COPY OUT transfer
01446  *
01447  *      If errorAbort is indicated, we are aborting a COPY OUT due to an error,
01448  *      and must send a terminator line.  Since a partial data line might have
01449  *      been emitted, send a couple of newlines first (the first one could
01450  *      get absorbed by a backslash...)  Note that old-style COPY OUT does
01451  *      not allow binary transfers, so a textual terminator is always correct.
01452  * --------------------------------
01453  */
01454 void
01455 pq_endcopyout(bool errorAbort)
01456 {
01457     if (!DoingCopyOut)
01458         return;
01459     if (errorAbort)
01460         pq_putbytes("\n\n\\.\n", 5);
01461     /* in non-error case, copy.c will have emitted the terminator line */
01462     DoingCopyOut = false;
01463 }
01464 
01465 
01466 /*
01467  * Support for TCP Keepalive parameters
01468  */
01469 
01470 /*
01471  * On Windows, we need to set both idle and interval at the same time.
01472  * We also cannot reset them to the default (setting to zero will
01473  * actually set them to zero, not default), therefor we fallback to
01474  * the out-of-the-box default instead.
01475  */
01476 #if defined(WIN32) && defined(SIO_KEEPALIVE_VALS)
01477 static int
01478 pq_setkeepaliveswin32(Port *port, int idle, int interval)
01479 {
01480     struct tcp_keepalive ka;
01481     DWORD       retsize;
01482 
01483     if (idle <= 0)
01484         idle = 2 * 60 * 60;     /* default = 2 hours */
01485     if (interval <= 0)
01486         interval = 1;           /* default = 1 second */
01487 
01488     ka.onoff = 1;
01489     ka.keepalivetime = idle * 1000;
01490     ka.keepaliveinterval = interval * 1000;
01491 
01492     if (WSAIoctl(port->sock,
01493                  SIO_KEEPALIVE_VALS,
01494                  (LPVOID) &ka,
01495                  sizeof(ka),
01496                  NULL,
01497                  0,
01498                  &retsize,
01499                  NULL,
01500                  NULL)
01501         != 0)
01502     {
01503         elog(LOG, "WSAIoctl(SIO_KEEPALIVE_VALS) failed: %ui",
01504              WSAGetLastError());
01505         return STATUS_ERROR;
01506     }
01507     if (port->keepalives_idle != idle)
01508         port->keepalives_idle = idle;
01509     if (port->keepalives_interval != interval)
01510         port->keepalives_interval = interval;
01511     return STATUS_OK;
01512 }
01513 #endif
01514 
01515 int
01516 pq_getkeepalivesidle(Port *port)
01517 {
01518 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPALIVE) || defined(WIN32)
01519     if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
01520         return 0;
01521 
01522     if (port->keepalives_idle != 0)
01523         return port->keepalives_idle;
01524 
01525     if (port->default_keepalives_idle == 0)
01526     {
01527 #ifndef WIN32
01528         ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_idle);
01529 
01530 #ifdef TCP_KEEPIDLE
01531         if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPIDLE,
01532                        (char *) &port->default_keepalives_idle,
01533                        &size) < 0)
01534         {
01535             elog(LOG, "getsockopt(TCP_KEEPIDLE) failed: %m");
01536             port->default_keepalives_idle = -1; /* don't know */
01537         }
01538 #else
01539         if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPALIVE,
01540                        (char *) &port->default_keepalives_idle,
01541                        &size) < 0)
01542         {
01543             elog(LOG, "getsockopt(TCP_KEEPALIVE) failed: %m");
01544             port->default_keepalives_idle = -1; /* don't know */
01545         }
01546 #endif   /* TCP_KEEPIDLE */
01547 #else                           /* WIN32 */
01548         /* We can't get the defaults on Windows, so return "don't know" */
01549         port->default_keepalives_idle = -1;
01550 #endif   /* WIN32 */
01551     }
01552 
01553     return port->default_keepalives_idle;
01554 #else
01555     return 0;
01556 #endif
01557 }
01558 
01559 int
01560 pq_setkeepalivesidle(int idle, Port *port)
01561 {
01562     if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
01563         return STATUS_OK;
01564 
01565 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPALIVE) || defined(SIO_KEEPALIVE_VALS)
01566     if (idle == port->keepalives_idle)
01567         return STATUS_OK;
01568 
01569 #ifndef WIN32
01570     if (port->default_keepalives_idle <= 0)
01571     {
01572         if (pq_getkeepalivesidle(port) < 0)
01573         {
01574             if (idle == 0)
01575                 return STATUS_OK;       /* default is set but unknown */
01576             else
01577                 return STATUS_ERROR;
01578         }
01579     }
01580 
01581     if (idle == 0)
01582         idle = port->default_keepalives_idle;
01583 
01584 #ifdef TCP_KEEPIDLE
01585     if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPIDLE,
01586                    (char *) &idle, sizeof(idle)) < 0)
01587     {
01588         elog(LOG, "setsockopt(TCP_KEEPIDLE) failed: %m");
01589         return STATUS_ERROR;
01590     }
01591 #else
01592     if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPALIVE,
01593                    (char *) &idle, sizeof(idle)) < 0)
01594     {
01595         elog(LOG, "setsockopt(TCP_KEEPALIVE) failed: %m");
01596         return STATUS_ERROR;
01597     }
01598 #endif
01599 
01600     port->keepalives_idle = idle;
01601 #else                           /* WIN32 */
01602     return pq_setkeepaliveswin32(port, idle, port->keepalives_interval);
01603 #endif
01604 #else                           /* TCP_KEEPIDLE || SIO_KEEPALIVE_VALS */
01605     if (idle != 0)
01606     {
01607         elog(LOG, "setting the keepalive idle time is not supported");
01608         return STATUS_ERROR;
01609     }
01610 #endif
01611     return STATUS_OK;
01612 }
01613 
01614 int
01615 pq_getkeepalivesinterval(Port *port)
01616 {
01617 #if defined(TCP_KEEPINTVL) || defined(SIO_KEEPALIVE_VALS)
01618     if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
01619         return 0;
01620 
01621     if (port->keepalives_interval != 0)
01622         return port->keepalives_interval;
01623 
01624     if (port->default_keepalives_interval == 0)
01625     {
01626 #ifndef WIN32
01627         ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_interval);
01628 
01629         if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
01630                        (char *) &port->default_keepalives_interval,
01631                        &size) < 0)
01632         {
01633             elog(LOG, "getsockopt(TCP_KEEPINTVL) failed: %m");
01634             port->default_keepalives_interval = -1;     /* don't know */
01635         }
01636 #else
01637         /* We can't get the defaults on Windows, so return "don't know" */
01638         port->default_keepalives_interval = -1;
01639 #endif   /* WIN32 */
01640     }
01641 
01642     return port->default_keepalives_interval;
01643 #else
01644     return 0;
01645 #endif
01646 }
01647 
01648 int
01649 pq_setkeepalivesinterval(int interval, Port *port)
01650 {
01651     if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
01652         return STATUS_OK;
01653 
01654 #if defined(TCP_KEEPINTVL) || defined (SIO_KEEPALIVE_VALS)
01655     if (interval == port->keepalives_interval)
01656         return STATUS_OK;
01657 
01658 #ifndef WIN32
01659     if (port->default_keepalives_interval <= 0)
01660     {
01661         if (pq_getkeepalivesinterval(port) < 0)
01662         {
01663             if (interval == 0)
01664                 return STATUS_OK;       /* default is set but unknown */
01665             else
01666                 return STATUS_ERROR;
01667         }
01668     }
01669 
01670     if (interval == 0)
01671         interval = port->default_keepalives_interval;
01672 
01673     if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPINTVL,
01674                    (char *) &interval, sizeof(interval)) < 0)
01675     {
01676         elog(LOG, "setsockopt(TCP_KEEPINTVL) failed: %m");
01677         return STATUS_ERROR;
01678     }
01679 
01680     port->keepalives_interval = interval;
01681 #else                           /* WIN32 */
01682     return pq_setkeepaliveswin32(port, port->keepalives_idle, interval);
01683 #endif
01684 #else
01685     if (interval != 0)
01686     {
01687         elog(LOG, "setsockopt(TCP_KEEPINTVL) not supported");
01688         return STATUS_ERROR;
01689     }
01690 #endif
01691 
01692     return STATUS_OK;
01693 }
01694 
01695 int
01696 pq_getkeepalivescount(Port *port)
01697 {
01698 #ifdef TCP_KEEPCNT
01699     if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
01700         return 0;
01701 
01702     if (port->keepalives_count != 0)
01703         return port->keepalives_count;
01704 
01705     if (port->default_keepalives_count == 0)
01706     {
01707         ACCEPT_TYPE_ARG3 size = sizeof(port->default_keepalives_count);
01708 
01709         if (getsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
01710                        (char *) &port->default_keepalives_count,
01711                        &size) < 0)
01712         {
01713             elog(LOG, "getsockopt(TCP_KEEPCNT) failed: %m");
01714             port->default_keepalives_count = -1;        /* don't know */
01715         }
01716     }
01717 
01718     return port->default_keepalives_count;
01719 #else
01720     return 0;
01721 #endif
01722 }
01723 
01724 int
01725 pq_setkeepalivescount(int count, Port *port)
01726 {
01727     if (port == NULL || IS_AF_UNIX(port->laddr.addr.ss_family))
01728         return STATUS_OK;
01729 
01730 #ifdef TCP_KEEPCNT
01731     if (count == port->keepalives_count)
01732         return STATUS_OK;
01733 
01734     if (port->default_keepalives_count <= 0)
01735     {
01736         if (pq_getkeepalivescount(port) < 0)
01737         {
01738             if (count == 0)
01739                 return STATUS_OK;       /* default is set but unknown */
01740             else
01741                 return STATUS_ERROR;
01742         }
01743     }
01744 
01745     if (count == 0)
01746         count = port->default_keepalives_count;
01747 
01748     if (setsockopt(port->sock, IPPROTO_TCP, TCP_KEEPCNT,
01749                    (char *) &count, sizeof(count)) < 0)
01750     {
01751         elog(LOG, "setsockopt(TCP_KEEPCNT) failed: %m");
01752         return STATUS_ERROR;
01753     }
01754 
01755     port->keepalives_count = count;
01756 #else
01757     if (count != 0)
01758     {
01759         elog(LOG, "setsockopt(TCP_KEEPCNT) not supported");
01760         return STATUS_ERROR;
01761     }
01762 #endif
01763 
01764     return STATUS_OK;
01765 }