LCOV - differential code coverage report
Current view: top level - src/interfaces/libpq - fe-misc.c (source / functions) Coverage Total Hit UNC LBC UIC UBC GBC GIC GNC CBC EUB ECB DCB
Current: Differential Code Coverage HEAD vs 15 Lines: 73.0 % 397 290 27 18 68 16 17 159 22 92 72 157 3
Current Date: 2023-04-08 15:15:32 Functions: 91.4 % 35 32 3 30 2 3 32
Baseline: 15
Baseline Date: 2023-04-08 15:09:40
Legend: Lines: hit not hit

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

Generated by: LCOV version v1.16-55-g56c0a2a