LCOV - code coverage report
Current view: top level - src/interfaces/libpq - fe-misc.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 305 411 74.2 %
Date: 2025-02-21 17:14:59 Functions: 34 37 91.9 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  *   FILE
       4             :  *      fe-misc.c
       5             :  *
       6             :  *   DESCRIPTION
       7             :  *       miscellaneous useful functions
       8             :  *
       9             :  * The communication routines here are analogous to the ones in
      10             :  * backend/libpq/pqcomm.c and backend/libpq/pqformat.c, but operate
      11             :  * in the considerably different environment of the frontend libpq.
      12             :  * In particular, we work with a bare nonblock-mode socket, rather than
      13             :  * a stdio stream, so that we can avoid unwanted blocking of the application.
      14             :  *
      15             :  * XXX: MOVE DEBUG PRINTOUT TO HIGHER LEVEL.  As is, block and restart
      16             :  * will cause repeat printouts.
      17             :  *
      18             :  * We must speak the same transmitted data representations as the backend
      19             :  * routines.
      20             :  *
      21             :  *
      22             :  * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
      23             :  * Portions Copyright (c) 1994, Regents of the University of California
      24             :  *
      25             :  * IDENTIFICATION
      26             :  *    src/interfaces/libpq/fe-misc.c
      27             :  *
      28             :  *-------------------------------------------------------------------------
      29             :  */
      30             : 
      31             : #include "postgres_fe.h"
      32             : 
      33             : #include <signal.h>
      34             : #include <time.h>
      35             : 
      36             : #ifdef WIN32
      37             : #include "win32.h"
      38             : #else
      39             : #include <unistd.h>
      40             : #include <sys/select.h>
      41             : #include <sys/time.h>
      42             : #endif
      43             : 
      44             : #ifdef HAVE_POLL_H
      45             : #include <poll.h>
      46             : #endif
      47             : 
      48             : #include "libpq-fe.h"
      49             : #include "libpq-int.h"
      50             : #include "mb/pg_wchar.h"
      51             : #include "pg_config_paths.h"
      52             : #include "port/pg_bswap.h"
      53             : 
      54             : static int  pqPutMsgBytes(const void *buf, size_t len, PGconn *conn);
      55             : static int  pqSendSome(PGconn *conn, int len);
      56             : static int  pqSocketCheck(PGconn *conn, int forRead, int forWrite,
      57             :                           pg_usec_time_t end_time);
      58             : 
      59             : /*
      60             :  * PQlibVersion: return the libpq version number
      61             :  */
      62             : int
      63           0 : PQlibVersion(void)
      64             : {
      65           0 :     return PG_VERSION_NUM;
      66             : }
      67             : 
      68             : 
      69             : /*
      70             :  * pqGetc: get 1 character from the connection
      71             :  *
      72             :  *  All these routines return 0 on success, EOF on error.
      73             :  *  Note that for the Get routines, EOF only means there is not enough
      74             :  *  data in the buffer, not that there is necessarily a hard error.
      75             :  */
      76             : int
      77    20520810 : pqGetc(char *result, PGconn *conn)
      78             : {
      79    20520810 :     if (conn->inCursor >= conn->inEnd)
      80     3088078 :         return EOF;
      81             : 
      82    17432732 :     *result = conn->inBuffer[conn->inCursor++];
      83             : 
      84    17432732 :     return 0;
      85             : }
      86             : 
      87             : 
      88             : /*
      89             :  * pqPutc: write 1 char to the current message
      90             :  */
      91             : int
      92       22276 : pqPutc(char c, PGconn *conn)
      93             : {
      94       22276 :     if (pqPutMsgBytes(&c, 1, conn))
      95           0 :         return EOF;
      96             : 
      97       22276 :     return 0;
      98             : }
      99             : 
     100             : 
     101             : /*
     102             :  * pqGets[_append]:
     103             :  * get a null-terminated string from the connection,
     104             :  * and store it in an expansible PQExpBuffer.
     105             :  * If we run out of memory, all of the string is still read,
     106             :  * but the excess characters are silently discarded.
     107             :  */
     108             : static int
     109     4234062 : pqGets_internal(PQExpBuffer buf, PGconn *conn, bool resetbuffer)
     110             : {
     111             :     /* Copy conn data to locals for faster search loop */
     112     4234062 :     char       *inBuffer = conn->inBuffer;
     113     4234062 :     int         inCursor = conn->inCursor;
     114     4234062 :     int         inEnd = conn->inEnd;
     115             :     int         slen;
     116             : 
     117    80921196 :     while (inCursor < inEnd && inBuffer[inCursor])
     118    76687134 :         inCursor++;
     119             : 
     120     4234062 :     if (inCursor >= inEnd)
     121           0 :         return EOF;
     122             : 
     123     4234062 :     slen = inCursor - conn->inCursor;
     124             : 
     125     4234062 :     if (resetbuffer)
     126     4234062 :         resetPQExpBuffer(buf);
     127             : 
     128     4234062 :     appendBinaryPQExpBuffer(buf, inBuffer + conn->inCursor, slen);
     129             : 
     130     4234062 :     conn->inCursor = ++inCursor;
     131             : 
     132     4234062 :     return 0;
     133             : }
     134             : 
     135             : int
     136     4234062 : pqGets(PQExpBuffer buf, PGconn *conn)
     137             : {
     138     4234062 :     return pqGets_internal(buf, conn, true);
     139             : }
     140             : 
     141             : int
     142           0 : pqGets_append(PQExpBuffer buf, PGconn *conn)
     143             : {
     144           0 :     return pqGets_internal(buf, conn, false);
     145             : }
     146             : 
     147             : 
     148             : /*
     149             :  * pqPuts: write a null-terminated string to the current message
     150             :  */
     151             : int
     152      708860 : pqPuts(const char *s, PGconn *conn)
     153             : {
     154      708860 :     if (pqPutMsgBytes(s, strlen(s) + 1, conn))
     155           0 :         return EOF;
     156             : 
     157      708860 :     return 0;
     158             : }
     159             : 
     160             : /*
     161             :  * pqGetnchar:
     162             :  *  get a string of exactly len bytes in buffer s, no null termination
     163             :  */
     164             : int
     165         922 : pqGetnchar(char *s, size_t len, PGconn *conn)
     166             : {
     167         922 :     if (len > (size_t) (conn->inEnd - conn->inCursor))
     168           0 :         return EOF;
     169             : 
     170         922 :     memcpy(s, conn->inBuffer + conn->inCursor, len);
     171             :     /* no terminating null */
     172             : 
     173         922 :     conn->inCursor += len;
     174             : 
     175         922 :     return 0;
     176             : }
     177             : 
     178             : /*
     179             :  * pqSkipnchar:
     180             :  *  skip over len bytes in input buffer.
     181             :  *
     182             :  * Note: this is primarily useful for its debug output, which should
     183             :  * be exactly the same as for pqGetnchar.  We assume the data in question
     184             :  * will actually be used, but just isn't getting copied anywhere as yet.
     185             :  */
     186             : int
     187    29403800 : pqSkipnchar(size_t len, PGconn *conn)
     188             : {
     189    29403800 :     if (len > (size_t) (conn->inEnd - conn->inCursor))
     190           0 :         return EOF;
     191             : 
     192    29403800 :     conn->inCursor += len;
     193             : 
     194    29403800 :     return 0;
     195             : }
     196             : 
     197             : /*
     198             :  * pqPutnchar:
     199             :  *  write exactly len bytes to the current message
     200             :  */
     201             : int
     202      551838 : pqPutnchar(const char *s, size_t len, PGconn *conn)
     203             : {
     204      551838 :     if (pqPutMsgBytes(s, len, conn))
     205           0 :         return EOF;
     206             : 
     207      551838 :     return 0;
     208             : }
     209             : 
     210             : /*
     211             :  * pqGetInt
     212             :  *  read a 2 or 4 byte integer and convert from network byte order
     213             :  *  to local byte order
     214             :  */
     215             : int
     216    60906276 : pqGetInt(int *result, size_t bytes, PGconn *conn)
     217             : {
     218             :     uint16      tmp2;
     219             :     uint32      tmp4;
     220             : 
     221    60906276 :     switch (bytes)
     222             :     {
     223    10695148 :         case 2:
     224    10695148 :             if (conn->inCursor + 2 > conn->inEnd)
     225           0 :                 return EOF;
     226    10695148 :             memcpy(&tmp2, conn->inBuffer + conn->inCursor, 2);
     227    10695148 :             conn->inCursor += 2;
     228    10695148 :             *result = (int) pg_ntoh16(tmp2);
     229    10695148 :             break;
     230    50211128 :         case 4:
     231    50211128 :             if (conn->inCursor + 4 > conn->inEnd)
     232        4480 :                 return EOF;
     233    50206648 :             memcpy(&tmp4, conn->inBuffer + conn->inCursor, 4);
     234    50206648 :             conn->inCursor += 4;
     235    50206648 :             *result = (int) pg_ntoh32(tmp4);
     236    50206648 :             break;
     237           0 :         default:
     238           0 :             pqInternalNotice(&conn->noticeHooks,
     239             :                              "integer of size %lu not supported by pqGetInt",
     240             :                              (unsigned long) bytes);
     241           0 :             return EOF;
     242             :     }
     243             : 
     244    60901796 :     return 0;
     245             : }
     246             : 
     247             : /*
     248             :  * pqPutInt
     249             :  * write an integer of 2 or 4 bytes, converting from host byte order
     250             :  * to network byte order.
     251             :  */
     252             : int
     253      175322 : pqPutInt(int value, size_t bytes, PGconn *conn)
     254             : {
     255             :     uint16      tmp2;
     256             :     uint32      tmp4;
     257             : 
     258      175322 :     switch (bytes)
     259             :     {
     260      114582 :         case 2:
     261      114582 :             tmp2 = pg_hton16((uint16) value);
     262      114582 :             if (pqPutMsgBytes((const char *) &tmp2, 2, conn))
     263           0 :                 return EOF;
     264      114582 :             break;
     265       60740 :         case 4:
     266       60740 :             tmp4 = pg_hton32((uint32) value);
     267       60740 :             if (pqPutMsgBytes((const char *) &tmp4, 4, conn))
     268           0 :                 return EOF;
     269       60740 :             break;
     270           0 :         default:
     271           0 :             pqInternalNotice(&conn->noticeHooks,
     272             :                              "integer of size %lu not supported by pqPutInt",
     273             :                              (unsigned long) bytes);
     274           0 :             return EOF;
     275             :     }
     276             : 
     277      175322 :     return 0;
     278             : }
     279             : 
     280             : /*
     281             :  * Make sure conn's output buffer can hold bytes_needed bytes (caller must
     282             :  * include already-stored data into the value!)
     283             :  *
     284             :  * Returns 0 on success, EOF if failed to enlarge buffer
     285             :  */
     286             : int
     287     2709302 : pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
     288             : {
     289     2709302 :     int         newsize = conn->outBufSize;
     290             :     char       *newbuf;
     291             : 
     292             :     /* Quick exit if we have enough space */
     293     2709302 :     if (bytes_needed <= (size_t) newsize)
     294     2709244 :         return 0;
     295             : 
     296             :     /*
     297             :      * If we need to enlarge the buffer, we first try to double it in size; if
     298             :      * that doesn't work, enlarge in multiples of 8K.  This avoids thrashing
     299             :      * the malloc pool by repeated small enlargements.
     300             :      *
     301             :      * Note: tests for newsize > 0 are to catch integer overflow.
     302             :      */
     303             :     do
     304             :     {
     305         146 :         newsize *= 2;
     306         146 :     } while (newsize > 0 && bytes_needed > (size_t) newsize);
     307             : 
     308          58 :     if (newsize > 0 && bytes_needed <= (size_t) newsize)
     309             :     {
     310          58 :         newbuf = realloc(conn->outBuffer, newsize);
     311          58 :         if (newbuf)
     312             :         {
     313             :             /* realloc succeeded */
     314          58 :             conn->outBuffer = newbuf;
     315          58 :             conn->outBufSize = newsize;
     316          58 :             return 0;
     317             :         }
     318             :     }
     319             : 
     320           0 :     newsize = conn->outBufSize;
     321             :     do
     322             :     {
     323           0 :         newsize += 8192;
     324           0 :     } while (newsize > 0 && bytes_needed > (size_t) newsize);
     325             : 
     326           0 :     if (newsize > 0 && bytes_needed <= (size_t) newsize)
     327             :     {
     328           0 :         newbuf = realloc(conn->outBuffer, newsize);
     329           0 :         if (newbuf)
     330             :         {
     331             :             /* realloc succeeded */
     332           0 :             conn->outBuffer = newbuf;
     333           0 :             conn->outBufSize = newsize;
     334           0 :             return 0;
     335             :         }
     336             :     }
     337             : 
     338             :     /* realloc failed. Probably out of memory */
     339           0 :     appendPQExpBufferStr(&conn->errorMessage,
     340             :                          "cannot allocate memory for output buffer\n");
     341           0 :     return EOF;
     342             : }
     343             : 
     344             : /*
     345             :  * Make sure conn's input buffer can hold bytes_needed bytes (caller must
     346             :  * include already-stored data into the value!)
     347             :  *
     348             :  * Returns 0 on success, EOF if failed to enlarge buffer
     349             :  */
     350             : int
     351      454068 : pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
     352             : {
     353      454068 :     int         newsize = conn->inBufSize;
     354             :     char       *newbuf;
     355             : 
     356             :     /* Quick exit if we have enough space */
     357      454068 :     if (bytes_needed <= (size_t) newsize)
     358      222166 :         return 0;
     359             : 
     360             :     /*
     361             :      * Before concluding that we need to enlarge the buffer, left-justify
     362             :      * whatever is in it and recheck.  The caller's value of bytes_needed
     363             :      * includes any data to the left of inStart, but we can delete that in
     364             :      * preference to enlarging the buffer.  It's slightly ugly to have this
     365             :      * function do this, but it's better than making callers worry about it.
     366             :      */
     367      231902 :     bytes_needed -= conn->inStart;
     368             : 
     369      231902 :     if (conn->inStart < conn->inEnd)
     370             :     {
     371      231902 :         if (conn->inStart > 0)
     372             :         {
     373      231340 :             memmove(conn->inBuffer, conn->inBuffer + conn->inStart,
     374      231340 :                     conn->inEnd - conn->inStart);
     375      231340 :             conn->inEnd -= conn->inStart;
     376      231340 :             conn->inCursor -= conn->inStart;
     377      231340 :             conn->inStart = 0;
     378             :         }
     379             :     }
     380             :     else
     381             :     {
     382             :         /* buffer is logically empty, reset it */
     383           0 :         conn->inStart = conn->inCursor = conn->inEnd = 0;
     384             :     }
     385             : 
     386             :     /* Recheck whether we have enough space */
     387      231902 :     if (bytes_needed <= (size_t) newsize)
     388      230492 :         return 0;
     389             : 
     390             :     /*
     391             :      * If we need to enlarge the buffer, we first try to double it in size; if
     392             :      * that doesn't work, enlarge in multiples of 8K.  This avoids thrashing
     393             :      * the malloc pool by repeated small enlargements.
     394             :      *
     395             :      * Note: tests for newsize > 0 are to catch integer overflow.
     396             :      */
     397             :     do
     398             :     {
     399        2502 :         newsize *= 2;
     400        2502 :     } while (newsize > 0 && bytes_needed > (size_t) newsize);
     401             : 
     402        1410 :     if (newsize > 0 && bytes_needed <= (size_t) newsize)
     403             :     {
     404        1410 :         newbuf = realloc(conn->inBuffer, newsize);
     405        1410 :         if (newbuf)
     406             :         {
     407             :             /* realloc succeeded */
     408        1410 :             conn->inBuffer = newbuf;
     409        1410 :             conn->inBufSize = newsize;
     410        1410 :             return 0;
     411             :         }
     412             :     }
     413             : 
     414           0 :     newsize = conn->inBufSize;
     415             :     do
     416             :     {
     417           0 :         newsize += 8192;
     418           0 :     } while (newsize > 0 && bytes_needed > (size_t) newsize);
     419             : 
     420           0 :     if (newsize > 0 && bytes_needed <= (size_t) newsize)
     421             :     {
     422           0 :         newbuf = realloc(conn->inBuffer, newsize);
     423           0 :         if (newbuf)
     424             :         {
     425             :             /* realloc succeeded */
     426           0 :             conn->inBuffer = newbuf;
     427           0 :             conn->inBufSize = newsize;
     428           0 :             return 0;
     429             :         }
     430             :     }
     431             : 
     432             :     /* realloc failed. Probably out of memory */
     433           0 :     appendPQExpBufferStr(&conn->errorMessage,
     434             :                          "cannot allocate memory for input buffer\n");
     435           0 :     return EOF;
     436             : }
     437             : 
     438             : /*
     439             :  * pqParseDone: after a server-to-client message has successfully
     440             :  * been parsed, advance conn->inStart to account for it.
     441             :  */
     442             : void
     443    13773494 : pqParseDone(PGconn *conn, int newInStart)
     444             : {
     445             :     /* trace server-to-client message */
     446    13773494 :     if (conn->Pfdebug)
     447         434 :         pqTraceOutputMessage(conn, conn->inBuffer + conn->inStart, false);
     448             : 
     449             :     /* Mark message as done */
     450    13773494 :     conn->inStart = newInStart;
     451    13773494 : }
     452             : 
     453             : /*
     454             :  * pqPutMsgStart: begin construction of a message to the server
     455             :  *
     456             :  * msg_type is the message type byte, or 0 for a message without type byte
     457             :  * (only startup messages have no type byte)
     458             :  *
     459             :  * Returns 0 on success, EOF on error
     460             :  *
     461             :  * The idea here is that we construct the message in conn->outBuffer,
     462             :  * beginning just past any data already in outBuffer (ie, at
     463             :  * outBuffer+outCount).  We enlarge the buffer as needed to hold the message.
     464             :  * When the message is complete, we fill in the length word (if needed) and
     465             :  * then advance outCount past the message, making it eligible to send.
     466             :  *
     467             :  * The state variable conn->outMsgStart points to the incomplete message's
     468             :  * length word: it is either outCount or outCount+1 depending on whether
     469             :  * there is a type byte.  The state variable conn->outMsgEnd is the end of
     470             :  * the data collected so far.
     471             :  */
     472             : int
     473     1250966 : pqPutMsgStart(char msg_type, PGconn *conn)
     474             : {
     475             :     int         lenPos;
     476             :     int         endPos;
     477             : 
     478             :     /* allow room for message type byte */
     479     1250966 :     if (msg_type)
     480     1223746 :         endPos = conn->outCount + 1;
     481             :     else
     482       27220 :         endPos = conn->outCount;
     483             : 
     484             :     /* do we want a length word? */
     485     1250966 :     lenPos = endPos;
     486             :     /* allow room for message length */
     487     1250966 :     endPos += 4;
     488             : 
     489             :     /* make sure there is room for message header */
     490     1250966 :     if (pqCheckOutBufferSpace(endPos, conn))
     491           0 :         return EOF;
     492             :     /* okay, save the message type byte if any */
     493     1250966 :     if (msg_type)
     494     1223746 :         conn->outBuffer[conn->outCount] = msg_type;
     495             :     /* set up the message pointers */
     496     1250966 :     conn->outMsgStart = lenPos;
     497     1250966 :     conn->outMsgEnd = endPos;
     498             :     /* length word, if needed, will be filled in by pqPutMsgEnd */
     499             : 
     500     1250966 :     return 0;
     501             : }
     502             : 
     503             : /*
     504             :  * pqPutMsgBytes: add bytes to a partially-constructed message
     505             :  *
     506             :  * Returns 0 on success, EOF on error
     507             :  */
     508             : static int
     509     1458296 : pqPutMsgBytes(const void *buf, size_t len, PGconn *conn)
     510             : {
     511             :     /* make sure there is room for it */
     512     1458296 :     if (pqCheckOutBufferSpace(conn->outMsgEnd + len, conn))
     513           0 :         return EOF;
     514             :     /* okay, save the data */
     515     1458296 :     memcpy(conn->outBuffer + conn->outMsgEnd, buf, len);
     516     1458296 :     conn->outMsgEnd += len;
     517             :     /* no Pfdebug call here, caller should do it */
     518     1458296 :     return 0;
     519             : }
     520             : 
     521             : /*
     522             :  * pqPutMsgEnd: finish constructing a message and possibly send it
     523             :  *
     524             :  * Returns 0 on success, EOF on error
     525             :  *
     526             :  * We don't actually send anything here unless we've accumulated at least
     527             :  * 8K worth of data (the typical size of a pipe buffer on Unix systems).
     528             :  * This avoids sending small partial packets.  The caller must use pqFlush
     529             :  * when it's important to flush all the data out to the server.
     530             :  */
     531             : int
     532     1250966 : pqPutMsgEnd(PGconn *conn)
     533             : {
     534             :     /* Fill in length word if needed */
     535     1250966 :     if (conn->outMsgStart >= 0)
     536             :     {
     537     1250966 :         uint32      msgLen = conn->outMsgEnd - conn->outMsgStart;
     538             : 
     539     1250966 :         msgLen = pg_hton32(msgLen);
     540     1250966 :         memcpy(conn->outBuffer + conn->outMsgStart, &msgLen, 4);
     541             :     }
     542             : 
     543             :     /* trace client-to-server message */
     544     1250966 :     if (conn->Pfdebug)
     545             :     {
     546         394 :         if (conn->outCount < conn->outMsgStart)
     547         394 :             pqTraceOutputMessage(conn, conn->outBuffer + conn->outCount, true);
     548             :         else
     549           0 :             pqTraceOutputNoTypeByteMessage(conn,
     550           0 :                                            conn->outBuffer + conn->outMsgStart);
     551             :     }
     552             : 
     553             :     /* Make message eligible to send */
     554     1250966 :     conn->outCount = conn->outMsgEnd;
     555             : 
     556     1250966 :     if (conn->outCount >= 8192)
     557             :     {
     558        2064 :         int         toSend = conn->outCount - (conn->outCount % 8192);
     559             : 
     560        2064 :         if (pqSendSome(conn, toSend) < 0)
     561           0 :             return EOF;
     562             :         /* in nonblock mode, don't complain if unable to send it all */
     563             :     }
     564             : 
     565     1250966 :     return 0;
     566             : }
     567             : 
     568             : /* ----------
     569             :  * pqReadData: read more data, if any is available
     570             :  * Possible return values:
     571             :  *   1: successfully loaded at least one more byte
     572             :  *   0: no data is presently available, but no error detected
     573             :  *  -1: error detected (including EOF = connection closure);
     574             :  *      conn->errorMessage set
     575             :  * NOTE: callers must not assume that pointers or indexes into conn->inBuffer
     576             :  * remain valid across this call!
     577             :  * ----------
     578             :  */
     579             : int
     580     2010372 : pqReadData(PGconn *conn)
     581             : {
     582     2010372 :     int         someread = 0;
     583             :     int         nread;
     584             : 
     585     2010372 :     if (conn->sock == PGINVALID_SOCKET)
     586             :     {
     587           4 :         libpq_append_conn_error(conn, "connection not open");
     588           4 :         return -1;
     589             :     }
     590             : 
     591             :     /* Left-justify any data in the buffer to make room */
     592     2010368 :     if (conn->inStart < conn->inEnd)
     593             :     {
     594      430776 :         if (conn->inStart > 0)
     595             :         {
     596      143320 :             memmove(conn->inBuffer, conn->inBuffer + conn->inStart,
     597      143320 :                     conn->inEnd - conn->inStart);
     598      143320 :             conn->inEnd -= conn->inStart;
     599      143320 :             conn->inCursor -= conn->inStart;
     600      143320 :             conn->inStart = 0;
     601             :         }
     602             :     }
     603             :     else
     604             :     {
     605             :         /* buffer is logically empty, reset it */
     606     1579592 :         conn->inStart = conn->inCursor = conn->inEnd = 0;
     607             :     }
     608             : 
     609             :     /*
     610             :      * If the buffer is fairly full, enlarge it. We need to be able to enlarge
     611             :      * the buffer in case a single message exceeds the initial buffer size. We
     612             :      * enlarge before filling the buffer entirely so as to avoid asking the
     613             :      * kernel for a partial packet. The magic constant here should be large
     614             :      * enough for a TCP packet or Unix pipe bufferload.  8K is the usual pipe
     615             :      * buffer size, so...
     616             :      */
     617     2010368 :     if (conn->inBufSize - conn->inEnd < 8192)
     618             :     {
     619          12 :         if (pqCheckInBufferSpace(conn->inEnd + (size_t) 8192, conn))
     620             :         {
     621             :             /*
     622             :              * We don't insist that the enlarge worked, but we need some room
     623             :              */
     624           0 :             if (conn->inBufSize - conn->inEnd < 100)
     625           0 :                 return -1;      /* errorMessage already set */
     626             :         }
     627             :     }
     628             : 
     629             :     /* OK, try to read some data */
     630     2010368 : retry3:
     631     4329572 :     nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
     632     2164786 :                           conn->inBufSize - conn->inEnd);
     633     2164786 :     if (nread < 0)
     634             :     {
     635      644676 :         switch (SOCK_ERRNO)
     636             :         {
     637           0 :             case EINTR:
     638           0 :                 goto retry3;
     639             : 
     640             :                 /* Some systems return EAGAIN/EWOULDBLOCK for no data */
     641             : #ifdef EAGAIN
     642      644632 :             case EAGAIN:
     643      644632 :                 return someread;
     644             : #endif
     645             : #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
     646             :             case EWOULDBLOCK:
     647             :                 return someread;
     648             : #endif
     649             : 
     650             :                 /* We might get ECONNRESET etc here if connection failed */
     651          44 :             case ALL_CONNECTION_FAILURE_ERRNOS:
     652          44 :                 goto definitelyFailed;
     653             : 
     654           0 :             default:
     655             :                 /* pqsecure_read set the error message for us */
     656           0 :                 return -1;
     657             :         }
     658             :     }
     659     1520110 :     if (nread > 0)
     660             :     {
     661     1519760 :         conn->inEnd += nread;
     662             : 
     663             :         /*
     664             :          * Hack to deal with the fact that some kernels will only give us back
     665             :          * 1 packet per recv() call, even if we asked for more and there is
     666             :          * more available.  If it looks like we are reading a long message,
     667             :          * loop back to recv() again immediately, until we run out of data or
     668             :          * buffer space.  Without this, the block-and-restart behavior of
     669             :          * libpq's higher levels leads to O(N^2) performance on long messages.
     670             :          *
     671             :          * Since we left-justified the data above, conn->inEnd gives the
     672             :          * amount of data already read in the current message.  We consider
     673             :          * the message "long" once we have acquired 32k ...
     674             :          */
     675     1519760 :         if (conn->inEnd > 32768 &&
     676      339032 :             (conn->inBufSize - conn->inEnd) >= 8192)
     677             :         {
     678      154418 :             someread = 1;
     679      154418 :             goto retry3;
     680             :         }
     681     1365342 :         return 1;
     682             :     }
     683             : 
     684         350 :     if (someread)
     685           0 :         return 1;               /* got a zero read after successful tries */
     686             : 
     687             :     /*
     688             :      * A return value of 0 could mean just that no data is now available, or
     689             :      * it could mean EOF --- that is, the server has closed the connection.
     690             :      * Since we have the socket in nonblock mode, the only way to tell the
     691             :      * difference is to see if select() is saying that the file is ready.
     692             :      * Grumble.  Fortunately, we don't expect this path to be taken much,
     693             :      * since in normal practice we should not be trying to read data unless
     694             :      * the file selected for reading already.
     695             :      *
     696             :      * In SSL mode it's even worse: SSL_read() could say WANT_READ and then
     697             :      * data could arrive before we make the pqReadReady() test, but the second
     698             :      * SSL_read() could still say WANT_READ because the data received was not
     699             :      * a complete SSL record.  So we must play dumb and assume there is more
     700             :      * data, relying on the SSL layer to detect true EOF.
     701             :      */
     702             : 
     703             : #ifdef USE_SSL
     704         350 :     if (conn->ssl_in_use)
     705         166 :         return 0;
     706             : #endif
     707             : 
     708         184 :     switch (pqReadReady(conn))
     709             :     {
     710           0 :         case 0:
     711             :             /* definitely no data available */
     712           0 :             return 0;
     713         184 :         case 1:
     714             :             /* ready for read */
     715         184 :             break;
     716           0 :         default:
     717             :             /* we override pqReadReady's message with something more useful */
     718           0 :             goto definitelyEOF;
     719             :     }
     720             : 
     721             :     /*
     722             :      * Still not sure that it's EOF, because some data could have just
     723             :      * arrived.
     724             :      */
     725         184 : retry4:
     726         368 :     nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
     727         184 :                           conn->inBufSize - conn->inEnd);
     728         184 :     if (nread < 0)
     729             :     {
     730           0 :         switch (SOCK_ERRNO)
     731             :         {
     732           0 :             case EINTR:
     733           0 :                 goto retry4;
     734             : 
     735             :                 /* Some systems return EAGAIN/EWOULDBLOCK for no data */
     736             : #ifdef EAGAIN
     737           0 :             case EAGAIN:
     738           0 :                 return 0;
     739             : #endif
     740             : #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
     741             :             case EWOULDBLOCK:
     742             :                 return 0;
     743             : #endif
     744             : 
     745             :                 /* We might get ECONNRESET etc here if connection failed */
     746           0 :             case ALL_CONNECTION_FAILURE_ERRNOS:
     747           0 :                 goto definitelyFailed;
     748             : 
     749           0 :             default:
     750             :                 /* pqsecure_read set the error message for us */
     751           0 :                 return -1;
     752             :         }
     753             :     }
     754         184 :     if (nread > 0)
     755             :     {
     756           0 :         conn->inEnd += nread;
     757           0 :         return 1;
     758             :     }
     759             : 
     760             :     /*
     761             :      * OK, we are getting a zero read even though select() says ready. This
     762             :      * means the connection has been closed.  Cope.
     763             :      */
     764         184 : definitelyEOF:
     765         184 :     libpq_append_conn_error(conn, "server closed the connection unexpectedly\n"
     766             :                             "\tThis probably means the server terminated abnormally\n"
     767             :                             "\tbefore or while processing the request.");
     768             : 
     769             :     /* Come here if lower-level code already set a suitable errorMessage */
     770         228 : definitelyFailed:
     771             :     /* Do *not* drop any already-read data; caller still wants it */
     772         228 :     pqDropConnection(conn, false);
     773         228 :     conn->status = CONNECTION_BAD;   /* No more connection to backend */
     774         228 :     return -1;
     775             : }
     776             : 
     777             : /*
     778             :  * pqSendSome: send data waiting in the output buffer.
     779             :  *
     780             :  * len is how much to try to send (typically equal to outCount, but may
     781             :  * be less).
     782             :  *
     783             :  * Return 0 on success, -1 on failure and 1 when not all data could be sent
     784             :  * because the socket would block and the connection is non-blocking.
     785             :  *
     786             :  * Note that this is also responsible for consuming data from the socket
     787             :  * (putting it in conn->inBuffer) in any situation where we can't send
     788             :  * all the specified data immediately.
     789             :  *
     790             :  * If a socket-level write failure occurs, conn->write_failed is set and the
     791             :  * error message is saved in conn->write_err_msg, but we clear the output
     792             :  * buffer and return zero anyway; this is because callers should soldier on
     793             :  * until we have read what we can from the server and checked for an error
     794             :  * message.  write_err_msg should be reported only when we are unable to
     795             :  * obtain a server error first.  Much of that behavior is implemented at
     796             :  * lower levels, but this function deals with some edge cases.
     797             :  */
     798             : static int
     799      777050 : pqSendSome(PGconn *conn, int len)
     800             : {
     801      777050 :     char       *ptr = conn->outBuffer;
     802      777050 :     int         remaining = conn->outCount;
     803      777050 :     int         result = 0;
     804             : 
     805             :     /*
     806             :      * If we already had a write failure, we will never again try to send data
     807             :      * on that connection.  Even if the kernel would let us, we've probably
     808             :      * lost message boundary sync with the server.  conn->write_failed
     809             :      * therefore persists until the connection is reset, and we just discard
     810             :      * all data presented to be written.  However, as long as we still have a
     811             :      * valid socket, we should continue to absorb data from the backend, so
     812             :      * that we can collect any final error messages.
     813             :      */
     814      777050 :     if (conn->write_failed)
     815             :     {
     816             :         /* conn->write_err_msg should be set up already */
     817           0 :         conn->outCount = 0;
     818             :         /* Absorb input data if any, and detect socket closure */
     819           0 :         if (conn->sock != PGINVALID_SOCKET)
     820             :         {
     821           0 :             if (pqReadData(conn) < 0)
     822           0 :                 return -1;
     823             :         }
     824           0 :         return 0;
     825             :     }
     826             : 
     827      777050 :     if (conn->sock == PGINVALID_SOCKET)
     828             :     {
     829           0 :         conn->write_failed = true;
     830             :         /* Store error message in conn->write_err_msg, if possible */
     831             :         /* (strdup failure is OK, we'll cope later) */
     832           0 :         conn->write_err_msg = strdup(libpq_gettext("connection not open\n"));
     833             :         /* Discard queued data; no chance it'll ever be sent */
     834           0 :         conn->outCount = 0;
     835           0 :         return 0;
     836             :     }
     837             : 
     838             :     /* while there's still data to send */
     839     1554372 :     while (len > 0)
     840             :     {
     841             :         int         sent;
     842             : 
     843             : #ifndef WIN32
     844      777328 :         sent = pqsecure_write(conn, ptr, len);
     845             : #else
     846             : 
     847             :         /*
     848             :          * Windows can fail on large sends, per KB article Q201213. The
     849             :          * failure-point appears to be different in different versions of
     850             :          * Windows, but 64k should always be safe.
     851             :          */
     852             :         sent = pqsecure_write(conn, ptr, Min(len, 65536));
     853             : #endif
     854             : 
     855      777328 :         if (sent < 0)
     856             :         {
     857             :             /* Anything except EAGAIN/EWOULDBLOCK/EINTR is trouble */
     858         284 :             switch (SOCK_ERRNO)
     859             :             {
     860             : #ifdef EAGAIN
     861         284 :                 case EAGAIN:
     862         284 :                     break;
     863             : #endif
     864             : #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
     865             :                 case EWOULDBLOCK:
     866             :                     break;
     867             : #endif
     868           0 :                 case EINTR:
     869           0 :                     continue;
     870             : 
     871           0 :                 default:
     872             :                     /* Discard queued data; no chance it'll ever be sent */
     873           0 :                     conn->outCount = 0;
     874             : 
     875             :                     /* Absorb input data if any, and detect socket closure */
     876           0 :                     if (conn->sock != PGINVALID_SOCKET)
     877             :                     {
     878           0 :                         if (pqReadData(conn) < 0)
     879           0 :                             return -1;
     880             :                     }
     881             : 
     882             :                     /*
     883             :                      * Lower-level code should already have filled
     884             :                      * conn->write_err_msg (and set conn->write_failed) or
     885             :                      * conn->errorMessage.  In the former case, we pretend
     886             :                      * there's no problem; the write_failed condition will be
     887             :                      * dealt with later.  Otherwise, report the error now.
     888             :                      */
     889           0 :                     if (conn->write_failed)
     890           0 :                         return 0;
     891             :                     else
     892           0 :                         return -1;
     893             :             }
     894             :         }
     895             :         else
     896             :         {
     897      777044 :             ptr += sent;
     898      777044 :             len -= sent;
     899      777044 :             remaining -= sent;
     900             :         }
     901             : 
     902      777328 :         if (len > 0)
     903             :         {
     904             :             /*
     905             :              * We didn't send it all, wait till we can send more.
     906             :              *
     907             :              * There are scenarios in which we can't send data because the
     908             :              * communications channel is full, but we cannot expect the server
     909             :              * to clear the channel eventually because it's blocked trying to
     910             :              * send data to us.  (This can happen when we are sending a large
     911             :              * amount of COPY data, and the server has generated lots of
     912             :              * NOTICE responses.)  To avoid a deadlock situation, we must be
     913             :              * prepared to accept and buffer incoming data before we try
     914             :              * again.  Furthermore, it is possible that such incoming data
     915             :              * might not arrive until after we've gone to sleep.  Therefore,
     916             :              * we wait for either read ready or write ready.
     917             :              *
     918             :              * In non-blocking mode, we don't wait here directly, but return 1
     919             :              * to indicate that data is still pending.  The caller should wait
     920             :              * for both read and write ready conditions, and call
     921             :              * PQconsumeInput() on read ready, but just in case it doesn't, we
     922             :              * call pqReadData() ourselves before returning.  That's not
     923             :              * enough if the data has not arrived yet, but it's the best we
     924             :              * can do, and works pretty well in practice.  (The documentation
     925             :              * used to say that you only need to wait for write-ready, so
     926             :              * there are still plenty of applications like that out there.)
     927             :              *
     928             :              * Note that errors here don't result in write_failed becoming
     929             :              * set.
     930             :              */
     931         284 :             if (pqReadData(conn) < 0)
     932             :             {
     933           0 :                 result = -1;    /* error message already set up */
     934           0 :                 break;
     935             :             }
     936             : 
     937         284 :             if (pqIsnonblocking(conn))
     938             :             {
     939           6 :                 result = 1;
     940           6 :                 break;
     941             :             }
     942             : 
     943         278 :             if (pqWait(true, true, conn))
     944             :             {
     945           0 :                 result = -1;
     946           0 :                 break;
     947             :             }
     948             :         }
     949             :     }
     950             : 
     951             :     /* shift the remaining contents of the buffer */
     952      777050 :     if (remaining > 0)
     953        2064 :         memmove(conn->outBuffer, ptr, remaining);
     954      777050 :     conn->outCount = remaining;
     955             : 
     956      777050 :     return result;
     957             : }
     958             : 
     959             : 
     960             : /*
     961             :  * pqFlush: send any data waiting in the output buffer
     962             :  *
     963             :  * Return 0 on success, -1 on failure and 1 when not all data could be sent
     964             :  * because the socket would block and the connection is non-blocking.
     965             :  * (See pqSendSome comments about how failure should be handled.)
     966             :  */
     967             : int
     968     1531546 : pqFlush(PGconn *conn)
     969             : {
     970     1531546 :     if (conn->outCount > 0)
     971             :     {
     972      774986 :         if (conn->Pfdebug)
     973         108 :             fflush(conn->Pfdebug);
     974             : 
     975      774986 :         return pqSendSome(conn, conn->outCount);
     976             :     }
     977             : 
     978      756560 :     return 0;
     979             : }
     980             : 
     981             : 
     982             : /*
     983             :  * pqWait: wait until we can read or write the connection socket
     984             :  *
     985             :  * JAB: If SSL enabled and used and forRead, buffered bytes short-circuit the
     986             :  * call to select().
     987             :  *
     988             :  * We also stop waiting and return if the kernel flags an exception condition
     989             :  * on the socket.  The actual error condition will be detected and reported
     990             :  * when the caller tries to read or write the socket.
     991             :  */
     992             : int
     993     1043446 : pqWait(int forRead, int forWrite, PGconn *conn)
     994             : {
     995     1043446 :     return pqWaitTimed(forRead, forWrite, conn, -1);
     996             : }
     997             : 
     998             : /*
     999             :  * pqWaitTimed: wait, but not past end_time.
    1000             :  *
    1001             :  * Returns -1 on failure, 0 if the socket is readable/writable, 1 if it timed out.
    1002             :  *
    1003             :  * The timeout is specified by end_time, which is the int64 number of
    1004             :  * microseconds since the Unix epoch (that is, time_t times 1 million).
    1005             :  * Timeout is infinite if end_time is -1.  Timeout is immediate (no blocking)
    1006             :  * if end_time is 0 (or indeed, any time before now).
    1007             :  */
    1008             : int
    1009     1094794 : pqWaitTimed(int forRead, int forWrite, PGconn *conn, pg_usec_time_t end_time)
    1010             : {
    1011             :     int         result;
    1012             : 
    1013     1094794 :     result = pqSocketCheck(conn, forRead, forWrite, end_time);
    1014             : 
    1015     1094794 :     if (result < 0)
    1016           4 :         return -1;              /* errorMessage is already set */
    1017             : 
    1018     1094790 :     if (result == 0)
    1019             :     {
    1020           0 :         libpq_append_conn_error(conn, "timeout expired");
    1021           0 :         return 1;
    1022             :     }
    1023             : 
    1024     1094790 :     return 0;
    1025             : }
    1026             : 
    1027             : /*
    1028             :  * pqReadReady: is select() saying the file is ready to read?
    1029             :  * Returns -1 on failure, 0 if not ready, 1 if ready.
    1030             :  */
    1031             : int
    1032         184 : pqReadReady(PGconn *conn)
    1033             : {
    1034         184 :     return pqSocketCheck(conn, 1, 0, 0);
    1035             : }
    1036             : 
    1037             : /*
    1038             :  * pqWriteReady: is select() saying the file is ready to write?
    1039             :  * Returns -1 on failure, 0 if not ready, 1 if ready.
    1040             :  */
    1041             : int
    1042           0 : pqWriteReady(PGconn *conn)
    1043             : {
    1044           0 :     return pqSocketCheck(conn, 0, 1, 0);
    1045             : }
    1046             : 
    1047             : /*
    1048             :  * Checks a socket, using poll or select, for data to be read, written,
    1049             :  * or both.  Returns >0 if one or more conditions are met, 0 if it timed
    1050             :  * out, -1 if an error occurred.
    1051             :  *
    1052             :  * If an altsock is set for asynchronous authentication, that will be used in
    1053             :  * preference to the "server" socket. Otherwise, if SSL is in use, the SSL
    1054             :  * buffer is checked prior to checking the socket for read data directly.
    1055             :  */
    1056             : static int
    1057     1094978 : pqSocketCheck(PGconn *conn, int forRead, int forWrite, pg_usec_time_t end_time)
    1058             : {
    1059             :     int         result;
    1060             :     pgsocket    sock;
    1061             : 
    1062     1094978 :     if (!conn)
    1063           0 :         return -1;
    1064             : 
    1065     1094978 :     if (conn->altsock != PGINVALID_SOCKET)
    1066           0 :         sock = conn->altsock;
    1067             :     else
    1068             :     {
    1069     1094978 :         sock = conn->sock;
    1070     1094978 :         if (sock == PGINVALID_SOCKET)
    1071             :         {
    1072           4 :             libpq_append_conn_error(conn, "invalid socket");
    1073           4 :             return -1;
    1074             :         }
    1075             : 
    1076             : #ifdef USE_SSL
    1077             :         /* Check for SSL library buffering read bytes */
    1078     1094974 :         if (forRead && conn->ssl_in_use && pgtls_read_pending(conn))
    1079             :         {
    1080             :             /* short-circuit the select */
    1081           0 :             return 1;
    1082             :         }
    1083             : #endif
    1084             :     }
    1085             : 
    1086             :     /* We will retry as long as we get EINTR */
    1087             :     do
    1088     1094978 :         result = PQsocketPoll(sock, forRead, forWrite, end_time);
    1089     1094978 :     while (result < 0 && SOCK_ERRNO == EINTR);
    1090             : 
    1091     1094974 :     if (result < 0)
    1092             :     {
    1093             :         char        sebuf[PG_STRERROR_R_BUFLEN];
    1094             : 
    1095           0 :         libpq_append_conn_error(conn, "%s() failed: %s", "select",
    1096           0 :                                 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
    1097             :     }
    1098             : 
    1099     1094974 :     return result;
    1100             : }
    1101             : 
    1102             : 
    1103             : /*
    1104             :  * Check a file descriptor for read and/or write data, possibly waiting.
    1105             :  * If neither forRead nor forWrite are set, immediately return a timeout
    1106             :  * condition (without waiting).  Return >0 if condition is met, 0
    1107             :  * if a timeout occurred, -1 if an error or interrupt occurred.
    1108             :  *
    1109             :  * The timeout is specified by end_time, which is the int64 number of
    1110             :  * microseconds since the Unix epoch (that is, time_t times 1 million).
    1111             :  * Timeout is infinite if end_time is -1.  Timeout is immediate (no blocking)
    1112             :  * if end_time is 0 (or indeed, any time before now).
    1113             :  */
    1114             : int
    1115     1095638 : PQsocketPoll(int sock, int forRead, int forWrite, pg_usec_time_t end_time)
    1116             : {
    1117             :     /* We use poll(2) if available, otherwise select(2) */
    1118             : #ifdef HAVE_POLL
    1119             :     struct pollfd input_fd;
    1120             :     int         timeout_ms;
    1121             : 
    1122     1095638 :     if (!forRead && !forWrite)
    1123           0 :         return 0;
    1124             : 
    1125     1095638 :     input_fd.fd = sock;
    1126     1095638 :     input_fd.events = POLLERR;
    1127     1095638 :     input_fd.revents = 0;
    1128             : 
    1129     1095638 :     if (forRead)
    1130     1069718 :         input_fd.events |= POLLIN;
    1131     1095638 :     if (forWrite)
    1132       26198 :         input_fd.events |= POLLOUT;
    1133             : 
    1134             :     /* Compute appropriate timeout interval */
    1135     1095638 :     if (end_time == -1)
    1136     1094766 :         timeout_ms = -1;
    1137         872 :     else if (end_time == 0)
    1138         184 :         timeout_ms = 0;
    1139             :     else
    1140             :     {
    1141         688 :         pg_usec_time_t now = PQgetCurrentTimeUSec();
    1142             : 
    1143         688 :         if (end_time > now)
    1144         688 :             timeout_ms = (end_time - now) / 1000;
    1145             :         else
    1146           0 :             timeout_ms = 0;
    1147             :     }
    1148             : 
    1149     1095638 :     return poll(&input_fd, 1, timeout_ms);
    1150             : #else                           /* !HAVE_POLL */
    1151             : 
    1152             :     fd_set      input_mask;
    1153             :     fd_set      output_mask;
    1154             :     fd_set      except_mask;
    1155             :     struct timeval timeout;
    1156             :     struct timeval *ptr_timeout;
    1157             : 
    1158             :     if (!forRead && !forWrite)
    1159             :         return 0;
    1160             : 
    1161             :     FD_ZERO(&input_mask);
    1162             :     FD_ZERO(&output_mask);
    1163             :     FD_ZERO(&except_mask);
    1164             :     if (forRead)
    1165             :         FD_SET(sock, &input_mask);
    1166             : 
    1167             :     if (forWrite)
    1168             :         FD_SET(sock, &output_mask);
    1169             :     FD_SET(sock, &except_mask);
    1170             : 
    1171             :     /* Compute appropriate timeout interval */
    1172             :     if (end_time == -1)
    1173             :         ptr_timeout = NULL;
    1174             :     else if (end_time == 0)
    1175             :     {
    1176             :         timeout.tv_sec = 0;
    1177             :         timeout.tv_usec = 0;
    1178             :         ptr_timeout = &timeout;
    1179             :     }
    1180             :     else
    1181             :     {
    1182             :         pg_usec_time_t now = PQgetCurrentTimeUSec();
    1183             : 
    1184             :         if (end_time > now)
    1185             :         {
    1186             :             timeout.tv_sec = (end_time - now) / 1000000;
    1187             :             timeout.tv_usec = (end_time - now) % 1000000;
    1188             :         }
    1189             :         else
    1190             :         {
    1191             :             timeout.tv_sec = 0;
    1192             :             timeout.tv_usec = 0;
    1193             :         }
    1194             :         ptr_timeout = &timeout;
    1195             :     }
    1196             : 
    1197             :     return select(sock + 1, &input_mask, &output_mask,
    1198             :                   &except_mask, ptr_timeout);
    1199             : #endif                          /* HAVE_POLL */
    1200             : }
    1201             : 
    1202             : /*
    1203             :  * PQgetCurrentTimeUSec: get current time with microsecond precision
    1204             :  *
    1205             :  * This provides a platform-independent way of producing a reference
    1206             :  * value for PQsocketPoll's timeout parameter.
    1207             :  */
    1208             : pg_usec_time_t
    1209        1356 : PQgetCurrentTimeUSec(void)
    1210             : {
    1211             :     struct timeval tval;
    1212             : 
    1213        1356 :     gettimeofday(&tval, NULL);
    1214        1356 :     return (pg_usec_time_t) tval.tv_sec * 1000000 + tval.tv_usec;
    1215             : }
    1216             : 
    1217             : 
    1218             : /*
    1219             :  * A couple of "miscellaneous" multibyte related functions. They used
    1220             :  * to be in fe-print.c but that file is doomed.
    1221             :  */
    1222             : 
    1223             : /*
    1224             :  * Returns the byte length of the character beginning at s, using the
    1225             :  * specified encoding.
    1226             :  *
    1227             :  * Caution: when dealing with text that is not certainly valid in the
    1228             :  * specified encoding, the result may exceed the actual remaining
    1229             :  * string length.  Callers that are not prepared to deal with that
    1230             :  * should use PQmblenBounded() instead.
    1231             :  */
    1232             : int
    1233    52460122 : PQmblen(const char *s, int encoding)
    1234             : {
    1235    52460122 :     return pg_encoding_mblen(encoding, s);
    1236             : }
    1237             : 
    1238             : /*
    1239             :  * Returns the byte length of the character beginning at s, using the
    1240             :  * specified encoding; but not more than the distance to end of string.
    1241             :  */
    1242             : int
    1243      776646 : PQmblenBounded(const char *s, int encoding)
    1244             : {
    1245      776646 :     return strnlen(s, pg_encoding_mblen(encoding, s));
    1246             : }
    1247             : 
    1248             : /*
    1249             :  * Returns the display length of the character beginning at s, using the
    1250             :  * specified encoding.
    1251             :  */
    1252             : int
    1253    52460102 : PQdsplen(const char *s, int encoding)
    1254             : {
    1255    52460102 :     return pg_encoding_dsplen(encoding, s);
    1256             : }
    1257             : 
    1258             : /*
    1259             :  * Get encoding id from environment variable PGCLIENTENCODING.
    1260             :  */
    1261             : int
    1262       19108 : PQenv2encoding(void)
    1263             : {
    1264             :     char       *str;
    1265       19108 :     int         encoding = PG_SQL_ASCII;
    1266             : 
    1267       19108 :     str = getenv("PGCLIENTENCODING");
    1268       19108 :     if (str && *str != '\0')
    1269             :     {
    1270          12 :         encoding = pg_char_to_encoding(str);
    1271          12 :         if (encoding < 0)
    1272           0 :             encoding = PG_SQL_ASCII;
    1273             :     }
    1274       19108 :     return encoding;
    1275             : }
    1276             : 
    1277             : 
    1278             : #ifdef ENABLE_NLS
    1279             : 
    1280             : static void
    1281      186302 : libpq_binddomain(void)
    1282             : {
    1283             :     /*
    1284             :      * At least on Windows, there are gettext implementations that fail if
    1285             :      * multiple threads call bindtextdomain() concurrently.  Use a mutex and
    1286             :      * flag variable to ensure that we call it just once per process.  It is
    1287             :      * not known that similar bugs exist on non-Windows platforms, but we
    1288             :      * might as well do it the same way everywhere.
    1289             :      */
    1290             :     static volatile bool already_bound = false;
    1291             :     static pthread_mutex_t binddomain_mutex = PTHREAD_MUTEX_INITIALIZER;
    1292             : 
    1293      186302 :     if (!already_bound)
    1294             :     {
    1295             :         /* bindtextdomain() does not preserve errno */
    1296             : #ifdef WIN32
    1297             :         int         save_errno = GetLastError();
    1298             : #else
    1299       23344 :         int         save_errno = errno;
    1300             : #endif
    1301             : 
    1302       23344 :         (void) pthread_mutex_lock(&binddomain_mutex);
    1303             : 
    1304       23344 :         if (!already_bound)
    1305             :         {
    1306             :             const char *ldir;
    1307             : 
    1308             :             /*
    1309             :              * No relocatable lookup here because the calling executable could
    1310             :              * be anywhere
    1311             :              */
    1312       23344 :             ldir = getenv("PGLOCALEDIR");
    1313       23344 :             if (!ldir)
    1314         240 :                 ldir = LOCALEDIR;
    1315       23344 :             bindtextdomain(PG_TEXTDOMAIN("libpq"), ldir);
    1316       23344 :             already_bound = true;
    1317             :         }
    1318             : 
    1319       23344 :         (void) pthread_mutex_unlock(&binddomain_mutex);
    1320             : 
    1321             : #ifdef WIN32
    1322             :         SetLastError(save_errno);
    1323             : #else
    1324       23344 :         errno = save_errno;
    1325             : #endif
    1326             :     }
    1327      186302 : }
    1328             : 
    1329             : char *
    1330      186288 : libpq_gettext(const char *msgid)
    1331             : {
    1332      186288 :     libpq_binddomain();
    1333      186288 :     return dgettext(PG_TEXTDOMAIN("libpq"), msgid);
    1334             : }
    1335             : 
    1336             : char *
    1337          14 : libpq_ngettext(const char *msgid, const char *msgid_plural, unsigned long n)
    1338             : {
    1339          14 :     libpq_binddomain();
    1340          14 :     return dngettext(PG_TEXTDOMAIN("libpq"), msgid, msgid_plural, n);
    1341             : }
    1342             : 
    1343             : #endif                          /* ENABLE_NLS */
    1344             : 
    1345             : 
    1346             : /*
    1347             :  * Append a formatted string to the given buffer, after translating it.  A
    1348             :  * newline is automatically appended; the format should not end with a
    1349             :  * newline.
    1350             :  */
    1351             : void
    1352          54 : libpq_append_error(PQExpBuffer errorMessage, const char *fmt,...)
    1353             : {
    1354          54 :     int         save_errno = errno;
    1355             :     bool        done;
    1356             :     va_list     args;
    1357             : 
    1358             :     Assert(fmt[strlen(fmt) - 1] != '\n');
    1359             : 
    1360          54 :     if (PQExpBufferBroken(errorMessage))
    1361           0 :         return;                 /* already failed */
    1362             : 
    1363             :     /* Loop in case we have to retry after enlarging the buffer. */
    1364             :     do
    1365             :     {
    1366          54 :         errno = save_errno;
    1367          54 :         va_start(args, fmt);
    1368          54 :         done = appendPQExpBufferVA(errorMessage, libpq_gettext(fmt), args);
    1369          54 :         va_end(args);
    1370          54 :     } while (!done);
    1371             : 
    1372          54 :     appendPQExpBufferChar(errorMessage, '\n');
    1373             : }
    1374             : 
    1375             : /*
    1376             :  * Append a formatted string to the error message buffer of the given
    1377             :  * connection, after translating it.  A newline is automatically appended; the
    1378             :  * format should not end with a newline.
    1379             :  */
    1380             : void
    1381        1246 : libpq_append_conn_error(PGconn *conn, const char *fmt,...)
    1382             : {
    1383        1246 :     int         save_errno = errno;
    1384             :     bool        done;
    1385             :     va_list     args;
    1386             : 
    1387             :     Assert(fmt[strlen(fmt) - 1] != '\n');
    1388             : 
    1389        1246 :     if (PQExpBufferBroken(&conn->errorMessage))
    1390           0 :         return;                 /* already failed */
    1391             : 
    1392             :     /* Loop in case we have to retry after enlarging the buffer. */
    1393             :     do
    1394             :     {
    1395        1254 :         errno = save_errno;
    1396        1254 :         va_start(args, fmt);
    1397        1254 :         done = appendPQExpBufferVA(&conn->errorMessage, libpq_gettext(fmt), args);
    1398        1254 :         va_end(args);
    1399        1254 :     } while (!done);
    1400             : 
    1401        1246 :     appendPQExpBufferChar(&conn->errorMessage, '\n');
    1402             : }

Generated by: LCOV version 1.14