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

Generated by: LCOV version 1.14