LCOV - differential code coverage report
Current view: top level - src/interfaces/libpq - fe-misc.c (source / functions) Coverage Total Hit UBC CBC
Current: 77aeca80249c9e640c811e80633a2e334a9320de vs 38afc3dcb25c45b744d4025029ce0a6c90b7059f Lines: 74.5 % 443 330 113 330
Current Date: 2026-07-25 19:08:27 +0900 Functions: 90.0 % 40 36 4 36
Baseline: lcov-20260725-baseline Branches: 61.1 % 262 160 102 160
Baseline Date: 2026-07-25 19:09:19 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 56.0 % 25 14 11 14
(30,360] days: 40.0 % 5 2 3 2
(360..) days: 76.0 % 413 314 99 314
Function coverage date bins:
(7,30] days: 100.0 % 2 2 2
(30,360] days: 66.7 % 3 2 1 2
(360..) days: 91.4 % 35 32 3 32
Branch coverage date bins:
(7,30] days: 50.0 % 20 10 10 10
(360..) days: 62.0 % 242 150 92 150

 Age         Owner                    Branch data    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-2026, PostgreSQL Global Development Group
                                 23                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                 24                 :                :  *
                                 25                 :                :  * IDENTIFICATION
                                 26                 :                :  *    src/interfaces/libpq/fe-misc.c
                                 27                 :                :  *
                                 28                 :                :  *-------------------------------------------------------------------------
                                 29                 :                :  */
                                 30                 :                : 
                                 31                 :                : #include "postgres_fe.h"
                                 32                 :                : 
                                 33                 :                : #include <signal.h>
                                 34                 :                : #include <time.h>
                                 35                 :                : 
                                 36                 :                : #ifdef WIN32
                                 37                 :                : #include "win32.h"
                                 38                 :                : #else
                                 39                 :                : #include <unistd.h>
                                 40                 :                : #include <sys/select.h>
                                 41                 :                : #include <sys/time.h>
                                 42                 :                : #endif
                                 43                 :                : 
                                 44                 :                : #ifdef HAVE_POLL_H
                                 45                 :                : #include <poll.h>
                                 46                 :                : #endif
                                 47                 :                : 
                                 48                 :                : #include "libpq-fe.h"
                                 49                 :                : #include "libpq-int.h"
                                 50                 :                : #include "mb/pg_wchar.h"
                                 51                 :                : #include "pg_config_paths.h"
                                 52                 :                : #include "port/pg_bswap.h"
                                 53                 :                : 
                                 54                 :                : static int  pqPutMsgBytes(const void *buf, size_t len, PGconn *conn);
                                 55                 :                : static int  pqSendSome(PGconn *conn, int len);
                                 56                 :                : static int  pqSocketCheck(PGconn *conn, int forRead, int forWrite,
                                 57                 :                :                           pg_usec_time_t end_time);
                                 58                 :                : static int  pqReadData_internal(PGconn *conn);
                                 59                 :                : static int  pqDrainPending(PGconn *conn);
                                 60                 :                : 
                                 61                 :                : /*
                                 62                 :                :  * PQlibVersion: return the libpq version number
                                 63                 :                :  */
                                 64                 :                : int
 5694 magnus@hagander.net        65                 :UBC           0 : PQlibVersion(void)
                                 66                 :                : {
                                 67                 :              0 :     return PG_VERSION_NUM;
                                 68                 :                : }
                                 69                 :                : 
                                 70                 :                : 
                                 71                 :                : /*
                                 72                 :                :  * pqGetc: read 1 character from the connection
                                 73                 :                :  *
                                 74                 :                :  *  All these routines return 0 on success, EOF on error.
                                 75                 :                :  *  Note that for the Get routines, EOF only means there is not enough
                                 76                 :                :  *  data in the buffer, not that there is necessarily a hard error.
                                 77                 :                :  */
                                 78                 :                : int
10307 bruce@momjian.us           79                 :CBC    11527597 : pqGetc(char *result, PGconn *conn)
                                 80                 :                : {
                                 81         [ +  + ]:       11527597 :     if (conn->inCursor >= conn->inEnd)
                                 82                 :        1915867 :         return EOF;
                                 83                 :                : 
                                 84                 :        9611730 :     *result = conn->inBuffer[conn->inCursor++];
                                 85                 :                : 
                                 86                 :        9611730 :     return 0;
                                 87                 :                : }
                                 88                 :                : 
                                 89                 :                : 
                                 90                 :                : /*
                                 91                 :                :  * pqPutc: write 1 char to the current message
                                 92                 :                :  */
                                 93                 :                : int
 9150 peter_e@gmx.net            94                 :          12722 : pqPutc(char c, PGconn *conn)
                                 95                 :                : {
 8498 tgl@sss.pgh.pa.us          96         [ -  + ]:          12722 :     if (pqPutMsgBytes(&c, 1, conn))
 9150 peter_e@gmx.net            97                 :UBC           0 :         return EOF;
                                 98                 :                : 
 9150 peter_e@gmx.net            99                 :CBC       12722 :     return 0;
                                100                 :                : }
                                101                 :                : 
                                102                 :                : 
                                103                 :                : /*
                                104                 :                :  * pqGets[_append]:
                                105                 :                :  * read a null-terminated string from the connection,
                                106                 :                :  * and store it in an expansible PQExpBuffer.
                                107                 :                :  * If we run out of memory, all of the string is still read,
                                108                 :                :  * but the excess characters are silently discarded.
                                109                 :                :  */
                                110                 :                : static int
 6480 magnus@hagander.net       111                 :        1900731 : pqGets_internal(PQExpBuffer buf, PGconn *conn, bool resetbuffer)
                                112                 :                : {
                                113                 :                :     /* Copy conn data to locals for faster search loop */
10189 bruce@momjian.us          114                 :        1900731 :     char       *inBuffer = conn->inBuffer;
                                115                 :        1900731 :     int         inCursor = conn->inCursor;
                                116                 :        1900731 :     int         inEnd = conn->inEnd;
                                117                 :                :     int         slen;
                                118                 :                : 
10307                           119   [ +  -  +  + ]:       23896944 :     while (inCursor < inEnd && inBuffer[inCursor])
                                120                 :       21996213 :         inCursor++;
                                121                 :                : 
                                122         [ -  + ]:        1900731 :     if (inCursor >= inEnd)
10307 bruce@momjian.us          123                 :UBC           0 :         return EOF;
                                124                 :                : 
10307 bruce@momjian.us          125                 :CBC     1900731 :     slen = inCursor - conn->inCursor;
                                126                 :                : 
 6480 magnus@hagander.net       127         [ +  - ]:        1900731 :     if (resetbuffer)
                                128                 :        1900731 :         resetPQExpBuffer(buf);
                                129                 :                : 
 9825 tgl@sss.pgh.pa.us         130                 :        1900731 :     appendBinaryPQExpBuffer(buf, inBuffer + conn->inCursor, slen);
                                131                 :                : 
10307 bruce@momjian.us          132                 :        1900731 :     conn->inCursor = ++inCursor;
                                133                 :                : 
                                134                 :        1900731 :     return 0;
                                135                 :                : }
                                136                 :                : 
                                137                 :                : int
 6480 magnus@hagander.net       138                 :        1900731 : pqGets(PQExpBuffer buf, PGconn *conn)
                                139                 :                : {
                                140                 :        1900731 :     return pqGets_internal(buf, conn, true);
                                141                 :                : }
                                142                 :                : 
                                143                 :                : int
 6480 magnus@hagander.net       144                 :UBC           0 : pqGets_append(PQExpBuffer buf, PGconn *conn)
                                145                 :                : {
                                146                 :              0 :     return pqGets_internal(buf, conn, false);
                                147                 :                : }
                                148                 :                : 
                                149                 :                : 
                                150                 :                : /*
                                151                 :                :  * pqPuts: write a null-terminated string to the current message
                                152                 :                :  */
                                153                 :                : int
10307 bruce@momjian.us          154                 :CBC      458655 : pqPuts(const char *s, PGconn *conn)
                                155                 :                : {
 8498 tgl@sss.pgh.pa.us         156         [ -  + ]:         458655 :     if (pqPutMsgBytes(s, strlen(s) + 1, conn))
10307 bruce@momjian.us          157                 :UBC           0 :         return EOF;
                                158                 :                : 
10307 bruce@momjian.us          159                 :CBC      458655 :     return 0;
                                160                 :                : }
                                161                 :                : 
                                162                 :                : /*
                                163                 :                :  * pqGetnchar:
                                164                 :                :  *  read exactly len bytes in buffer s, no null termination
                                165                 :                :  */
                                166                 :                : int
  443 heikki.linnakangas@i      167                 :          15686 : pqGetnchar(void *s, size_t len, PGconn *conn)
                                168                 :                : {
 6274 meskes@postgresql.or      169         [ -  + ]:          15686 :     if (len > (size_t) (conn->inEnd - conn->inCursor))
10307 bruce@momjian.us          170                 :UBC           0 :         return EOF;
                                171                 :                : 
10307 bruce@momjian.us          172                 :CBC       15686 :     memcpy(s, conn->inBuffer + conn->inCursor, len);
                                173                 :                :     /* no terminating null */
                                174                 :                : 
                                175                 :          15686 :     conn->inCursor += len;
                                176                 :                : 
                                177                 :          15686 :     return 0;
                                178                 :                : }
                                179                 :                : 
                                180                 :                : /*
                                181                 :                :  * pqSkipnchar:
                                182                 :                :  *  skip over len bytes in input buffer.
                                183                 :                :  *
                                184                 :                :  * Note: this is primarily useful for its debug output, which should
                                185                 :                :  * be exactly the same as for pqGetnchar.  We assume the data in question
                                186                 :                :  * will actually be used, but just isn't getting copied anywhere as yet.
                                187                 :                :  */
                                188                 :                : int
 5225 tgl@sss.pgh.pa.us         189                 :       18696647 : pqSkipnchar(size_t len, PGconn *conn)
                                190                 :                : {
                                191         [ -  + ]:       18696647 :     if (len > (size_t) (conn->inEnd - conn->inCursor))
 5225 tgl@sss.pgh.pa.us         192                 :UBC           0 :         return EOF;
                                193                 :                : 
 5225 tgl@sss.pgh.pa.us         194                 :CBC    18696647 :     conn->inCursor += len;
                                195                 :                : 
                                196                 :       18696647 :     return 0;
                                197                 :                : }
                                198                 :                : 
                                199                 :                : /*
                                200                 :                :  * pqPutnchar:
                                201                 :                :  *  write exactly len bytes to the current message
                                202                 :                :  */
                                203                 :                : int
  443 heikki.linnakangas@i      204                 :         391085 : pqPutnchar(const void *s, size_t len, PGconn *conn)
                                205                 :                : {
 8498 tgl@sss.pgh.pa.us         206         [ -  + ]:         391085 :     if (pqPutMsgBytes(s, len, conn))
10307 bruce@momjian.us          207                 :UBC           0 :         return EOF;
                                208                 :                : 
10307 bruce@momjian.us          209                 :CBC      391085 :     return 0;
                                210                 :                : }
                                211                 :                : 
                                212                 :                : /*
                                213                 :                :  * pqGetInt
                                214                 :                :  *  read a 2 or 4 byte integer and convert from network byte order
                                215                 :                :  *  to local byte order
                                216                 :                :  */
                                217                 :                : int
 9753                           218                 :       36745094 : pqGetInt(int *result, size_t bytes, PGconn *conn)
                                219                 :                : {
                                220                 :                :     uint16      tmp2;
                                221                 :                :     uint32      tmp4;
                                222                 :                : 
10548                           223      [ +  +  - ]:       36745094 :     switch (bytes)
                                224                 :                :     {
10547                           225                 :        6043570 :         case 2:
10307                           226         [ -  + ]:        6043570 :             if (conn->inCursor + 2 > conn->inEnd)
10307 bruce@momjian.us          227                 :UBC           0 :                 return EOF;
10307 bruce@momjian.us          228                 :CBC     6043570 :             memcpy(&tmp2, conn->inBuffer + conn->inCursor, 2);
                                229                 :        6043570 :             conn->inCursor += 2;
 3219 andres@anarazel.de        230                 :        6043570 :             *result = (int) pg_ntoh16(tmp2);
10547 bruce@momjian.us          231                 :        6043570 :             break;
                                232                 :       30701524 :         case 4:
10307                           233         [ +  + ]:       30701524 :             if (conn->inCursor + 4 > conn->inEnd)
                                234                 :           2420 :                 return EOF;
                                235                 :       30699104 :             memcpy(&tmp4, conn->inBuffer + conn->inCursor, 4);
                                236                 :       30699104 :             conn->inCursor += 4;
 3219 andres@anarazel.de        237                 :       30699104 :             *result = (int) pg_ntoh32(tmp4);
10547 bruce@momjian.us          238                 :       30699104 :             break;
10547 bruce@momjian.us          239                 :UBC           0 :         default:
 8433 tgl@sss.pgh.pa.us         240                 :              0 :             pqInternalNotice(&conn->noticeHooks,
                                241                 :                :                              "integer of size %zu not supported by pqGetInt",
                                242                 :                :                              bytes);
10307 bruce@momjian.us          243                 :              0 :             return EOF;
                                244                 :                :     }
                                245                 :                : 
10307 bruce@momjian.us          246                 :CBC    36742674 :     return 0;
                                247                 :                : }
                                248                 :                : 
                                249                 :                : /*
                                250                 :                :  * pqPutInt
                                251                 :                :  * write an integer of 2 or 4 bytes, converting from host byte order
                                252                 :                :  * to network byte order.
                                253                 :                :  */
                                254                 :                : int
 9753                           255                 :          96578 : pqPutInt(int value, size_t bytes, PGconn *conn)
                                256                 :                : {
                                257                 :                :     uint16      tmp2;
                                258                 :                :     uint32      tmp4;
                                259                 :                : 
10548                           260      [ +  +  - ]:          96578 :     switch (bytes)
                                261                 :                :     {
10547                           262                 :          62275 :         case 2:
 3219 andres@anarazel.de        263                 :          62275 :             tmp2 = pg_hton16((uint16) value);
 8498 tgl@sss.pgh.pa.us         264         [ -  + ]:          62275 :             if (pqPutMsgBytes((const char *) &tmp2, 2, conn))
10307 bruce@momjian.us          265                 :UBC           0 :                 return EOF;
10547 bruce@momjian.us          266                 :CBC       62275 :             break;
                                267                 :          34303 :         case 4:
 3219 andres@anarazel.de        268                 :          34303 :             tmp4 = pg_hton32((uint32) value);
 8498 tgl@sss.pgh.pa.us         269         [ -  + ]:          34303 :             if (pqPutMsgBytes((const char *) &tmp4, 4, conn))
10307 bruce@momjian.us          270                 :UBC           0 :                 return EOF;
10547 bruce@momjian.us          271                 :CBC       34303 :             break;
10547 bruce@momjian.us          272                 :UBC           0 :         default:
 8433 tgl@sss.pgh.pa.us         273                 :              0 :             pqInternalNotice(&conn->noticeHooks,
                                274                 :                :                              "integer of size %zu not supported by pqPutInt",
                                275                 :                :                              bytes);
10307 bruce@momjian.us          276                 :              0 :             return EOF;
                                277                 :                :     }
                                278                 :                : 
10307 bruce@momjian.us          279                 :CBC       96578 :     return 0;
                                280                 :                : }
                                281                 :                : 
                                282                 :                : /*
                                283                 :                :  * Make sure conn's output buffer can hold bytes_needed bytes (caller must
                                284                 :                :  * include already-stored data into the value!)
                                285                 :                :  *
                                286                 :                :  * Returns 0 on success, EOF if failed to enlarge buffer
                                287                 :                :  */
                                288                 :                : int
 6631 tgl@sss.pgh.pa.us         289                 :        1805015 : pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
                                290                 :                : {
 8498                           291                 :        1805015 :     int         newsize = conn->outBufSize;
                                292                 :                :     char       *newbuf;
                                293                 :                : 
                                294                 :                :     /* Quick exit if we have enough space */
 6631                           295         [ +  + ]:        1805015 :     if (bytes_needed <= (size_t) newsize)
 8498                           296                 :        1804975 :         return 0;
                                297                 :                : 
                                298                 :                :     /*
                                299                 :                :      * If we need to enlarge the buffer, we first try to double it in size; if
                                300                 :                :      * that doesn't work, enlarge in multiples of 8K.  This avoids thrashing
                                301                 :                :      * the malloc pool by repeated small enlargements.
                                302                 :                :      *
                                303                 :                :      * Note: tests for newsize > 0 are to catch integer overflow.
                                304                 :                :      */
                                305                 :                :     do
                                306                 :                :     {
                                307                 :             95 :         newsize *= 2;
 6631                           308   [ +  -  +  + ]:             95 :     } while (newsize > 0 && bytes_needed > (size_t) newsize);
                                309                 :                : 
                                310   [ +  -  +  - ]:             40 :     if (newsize > 0 && bytes_needed <= (size_t) newsize)
                                311                 :                :     {
 8498                           312                 :             40 :         newbuf = realloc(conn->outBuffer, newsize);
                                313         [ +  - ]:             40 :         if (newbuf)
                                314                 :                :         {
                                315                 :                :             /* realloc succeeded */
                                316                 :             40 :             conn->outBuffer = newbuf;
                                317                 :             40 :             conn->outBufSize = newsize;
                                318                 :             40 :             return 0;
                                319                 :                :         }
                                320                 :                :     }
                                321                 :                : 
 8498 tgl@sss.pgh.pa.us         322                 :UBC           0 :     newsize = conn->outBufSize;
                                323                 :                :     do
                                324                 :                :     {
                                325                 :              0 :         newsize += 8192;
 6631                           326   [ #  #  #  # ]:              0 :     } while (newsize > 0 && bytes_needed > (size_t) newsize);
                                327                 :                : 
                                328   [ #  #  #  # ]:              0 :     if (newsize > 0 && bytes_needed <= (size_t) newsize)
                                329                 :                :     {
 8498                           330                 :              0 :         newbuf = realloc(conn->outBuffer, newsize);
                                331         [ #  # ]:              0 :         if (newbuf)
                                332                 :                :         {
                                333                 :                :             /* realloc succeeded */
                                334                 :              0 :             conn->outBuffer = newbuf;
                                335                 :              0 :             conn->outBufSize = newsize;
                                336                 :              0 :             return 0;
                                337                 :                :         }
                                338                 :                :     }
                                339                 :                : 
                                340                 :                :     /* realloc failed. Probably out of memory */
 2021                           341                 :              0 :     appendPQExpBufferStr(&conn->errorMessage,
                                342                 :                :                          "cannot allocate memory for output buffer\n");
 8498                           343                 :              0 :     return EOF;
                                344                 :                : }
                                345                 :                : 
                                346                 :                : /*
                                347                 :                :  * Make sure conn's input buffer can hold bytes_needed bytes (caller must
                                348                 :                :  * include already-stored data into the value!)
                                349                 :                :  *
                                350                 :                :  * Returns 0 on success, EOF if failed to enlarge buffer
                                351                 :                :  */
                                352                 :                : int
 6631 tgl@sss.pgh.pa.us         353                 :CBC      345173 : pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
                                354                 :                : {
 8495                           355                 :         345173 :     int         newsize = conn->inBufSize;
                                356                 :                :     char       *newbuf;
                                357                 :                : 
                                358                 :                :     /* Quick exit if we have enough space */
 4462                           359         [ +  + ]:         345173 :     if (bytes_needed <= (size_t) newsize)
                                360                 :         225236 :         return 0;
                                361                 :                : 
                                362                 :                :     /*
                                363                 :                :      * Before concluding that we need to enlarge the buffer, left-justify
                                364                 :                :      * whatever is in it and recheck.  The caller's value of bytes_needed
                                365                 :                :      * includes any data to the left of inStart, but we can delete that in
                                366                 :                :      * preference to enlarging the buffer.  It's slightly ugly to have this
                                367                 :                :      * function do this, but it's better than making callers worry about it.
                                368                 :                :      */
                                369                 :         119937 :     bytes_needed -= conn->inStart;
                                370                 :                : 
                                371         [ +  - ]:         119937 :     if (conn->inStart < conn->inEnd)
                                372                 :                :     {
                                373         [ +  + ]:         119937 :         if (conn->inStart > 0)
                                374                 :                :         {
                                375                 :         119675 :             memmove(conn->inBuffer, conn->inBuffer + conn->inStart,
                                376                 :         119675 :                     conn->inEnd - conn->inStart);
                                377                 :         119675 :             conn->inEnd -= conn->inStart;
                                378                 :         119675 :             conn->inCursor -= conn->inStart;
                                379                 :         119675 :             conn->inStart = 0;
                                380                 :                :         }
                                381                 :                :     }
                                382                 :                :     else
                                383                 :                :     {
                                384                 :                :         /* buffer is logically empty, reset it */
 4462 tgl@sss.pgh.pa.us         385                 :UBC           0 :         conn->inStart = conn->inCursor = conn->inEnd = 0;
                                386                 :                :     }
                                387                 :                : 
                                388                 :                :     /* Recheck whether we have enough space */
 6631 tgl@sss.pgh.pa.us         389         [ +  + ]:CBC      119937 :     if (bytes_needed <= (size_t) newsize)
 8495                           390                 :         119270 :         return 0;
                                391                 :                : 
                                392                 :                :     /*
                                393                 :                :      * If we need to enlarge the buffer, we first try to double it in size; if
                                394                 :                :      * that doesn't work, enlarge in multiples of 8K.  This avoids thrashing
                                395                 :                :      * the malloc pool by repeated small enlargements.
                                396                 :                :      *
                                397                 :                :      * Note: tests for newsize > 0 are to catch integer overflow.
                                398                 :                :      */
                                399                 :                :     do
                                400                 :                :     {
                                401                 :           1485 :         newsize *= 2;
 6631                           402   [ +  -  +  + ]:           1485 :     } while (newsize > 0 && bytes_needed > (size_t) newsize);
                                403                 :                : 
                                404   [ +  -  +  - ]:            667 :     if (newsize > 0 && bytes_needed <= (size_t) newsize)
                                405                 :                :     {
 8495                           406                 :            667 :         newbuf = realloc(conn->inBuffer, newsize);
                                407         [ +  - ]:            667 :         if (newbuf)
                                408                 :                :         {
                                409                 :                :             /* realloc succeeded */
                                410                 :            667 :             conn->inBuffer = newbuf;
                                411                 :            667 :             conn->inBufSize = newsize;
                                412                 :            667 :             return 0;
                                413                 :                :         }
                                414                 :                :     }
                                415                 :                : 
 8495 tgl@sss.pgh.pa.us         416                 :UBC           0 :     newsize = conn->inBufSize;
                                417                 :                :     do
                                418                 :                :     {
                                419                 :              0 :         newsize += 8192;
 6631                           420   [ #  #  #  # ]:              0 :     } while (newsize > 0 && bytes_needed > (size_t) newsize);
                                421                 :                : 
                                422   [ #  #  #  # ]:              0 :     if (newsize > 0 && bytes_needed <= (size_t) newsize)
                                423                 :                :     {
 8495                           424                 :              0 :         newbuf = realloc(conn->inBuffer, newsize);
                                425         [ #  # ]:              0 :         if (newbuf)
                                426                 :                :         {
                                427                 :                :             /* realloc succeeded */
                                428                 :              0 :             conn->inBuffer = newbuf;
                                429                 :              0 :             conn->inBufSize = newsize;
                                430                 :              0 :             return 0;
                                431                 :                :         }
                                432                 :                :     }
                                433                 :                : 
                                434                 :                :     /* realloc failed. Probably out of memory */
 2021                           435                 :              0 :     appendPQExpBufferStr(&conn->errorMessage,
                                436                 :                :                          "cannot allocate memory for input buffer\n");
 8495                           437                 :              0 :     return EOF;
                                438                 :                : }
                                439                 :                : 
                                440                 :                : /*
                                441                 :                :  * pqParseDone: after a server-to-client message has successfully
                                442                 :                :  * been parsed, advance conn->inStart to account for it.
                                443                 :                :  */
                                444                 :                : void
  708 alvherre@alvh.no-ip.      445                 :CBC     7892802 : pqParseDone(PGconn *conn, int newInStart)
                                446                 :                : {
                                447                 :                :     /* trace server-to-client message */
                                448         [ +  + ]:        7892802 :     if (conn->Pfdebug)
                                449                 :            217 :         pqTraceOutputMessage(conn, conn->inBuffer + conn->inStart, false);
                                450                 :                : 
                                451                 :                :     /* Mark message as done */
                                452                 :        7892802 :     conn->inStart = newInStart;
                                453                 :        7892802 : }
                                454                 :                : 
                                455                 :                : /*
                                456                 :                :  * pqPutMsgStart: begin construction of a message to the server
                                457                 :                :  *
                                458                 :                :  * msg_type is the message type byte, or 0 for a message without type byte
                                459                 :                :  * (only startup messages have no type byte)
                                460                 :                :  *
                                461                 :                :  * Returns 0 on success, EOF on error
                                462                 :                :  *
                                463                 :                :  * The idea here is that we construct the message in conn->outBuffer,
                                464                 :                :  * beginning just past any data already in outBuffer (ie, at
                                465                 :                :  * outBuffer+outCount).  We enlarge the buffer as needed to hold the message.
                                466                 :                :  * When the message is complete, we fill in the length word (if needed) and
                                467                 :                :  * then advance outCount past the message, making it eligible to send.
                                468                 :                :  *
                                469                 :                :  * The state variable conn->outMsgStart points to the incomplete message's
                                470                 :                :  * length word: it is either outCount or outCount+1 depending on whether
                                471                 :                :  * there is a type byte.  The state variable conn->outMsgEnd is the end of
                                472                 :                :  * the data collected so far.
                                473                 :                :  */
                                474                 :                : int
 1969 heikki.linnakangas@i      475                 :         845950 : pqPutMsgStart(char msg_type, PGconn *conn)
                                476                 :                : {
                                477                 :                :     int         lenPos;
                                478                 :                :     int         endPos;
                                479                 :                : 
                                480                 :                :     /* allow room for message type byte */
 8498 tgl@sss.pgh.pa.us         481         [ +  + ]:         845950 :     if (msg_type)
 8448                           482                 :         830335 :         endPos = conn->outCount + 1;
                                483                 :                :     else
                                484                 :          15615 :         endPos = conn->outCount;
                                485                 :                : 
                                486                 :                :     /* do we want a length word? */
 1969 heikki.linnakangas@i      487                 :         845950 :     lenPos = endPos;
                                488                 :                :     /* allow room for message length */
                                489                 :         845950 :     endPos += 4;
                                490                 :                : 
                                491                 :                :     /* make sure there is room for message header */
 8448 tgl@sss.pgh.pa.us         492         [ -  + ]:         845950 :     if (pqCheckOutBufferSpace(endPos, conn))
 8498 tgl@sss.pgh.pa.us         493                 :UBC           0 :         return EOF;
                                494                 :                :     /* okay, save the message type byte if any */
 8498 tgl@sss.pgh.pa.us         495         [ +  + ]:CBC      845950 :     if (msg_type)
                                496                 :         830335 :         conn->outBuffer[conn->outCount] = msg_type;
                                497                 :                :     /* set up the message pointers */
                                498                 :         845950 :     conn->outMsgStart = lenPos;
 8448                           499                 :         845950 :     conn->outMsgEnd = endPos;
                                500                 :                :     /* length word, if needed, will be filled in by pqPutMsgEnd */
                                501                 :                : 
 8498                           502                 :         845950 :     return 0;
                                503                 :                : }
                                504                 :                : 
                                505                 :                : /*
                                506                 :                :  * pqPutMsgBytes: add bytes to a partially-constructed message
                                507                 :                :  *
                                508                 :                :  * Returns 0 on success, EOF on error
                                509                 :                :  */
                                510                 :                : static int
                                511                 :         959040 : pqPutMsgBytes(const void *buf, size_t len, PGconn *conn)
                                512                 :                : {
                                513                 :                :     /* make sure there is room for it */
 8495                           514         [ -  + ]:         959040 :     if (pqCheckOutBufferSpace(conn->outMsgEnd + len, conn))
 8498 tgl@sss.pgh.pa.us         515                 :UBC           0 :         return EOF;
                                516                 :                :     /* okay, save the data */
 8498 tgl@sss.pgh.pa.us         517                 :CBC      959040 :     memcpy(conn->outBuffer + conn->outMsgEnd, buf, len);
                                518                 :         959040 :     conn->outMsgEnd += len;
                                519                 :                :     /* no Pfdebug call here, caller should do it */
                                520                 :         959040 :     return 0;
                                521                 :                : }
                                522                 :                : 
                                523                 :                : /*
                                524                 :                :  * pqPutMsgEnd: finish constructing a message and possibly send it
                                525                 :                :  *
                                526                 :                :  * Returns 0 on success, EOF on error
                                527                 :                :  *
                                528                 :                :  * We don't actually send anything here unless we've accumulated at least
                                529                 :                :  * 8K worth of data (the typical size of a pipe buffer on Unix systems).
                                530                 :                :  * This avoids sending small partial packets.  The caller must use pqFlush
                                531                 :                :  * when it's important to flush all the data out to the server.
                                532                 :                :  */
                                533                 :                : int
                                534                 :         845950 : pqPutMsgEnd(PGconn *conn)
                                535                 :                : {
                                536                 :                :     /* Fill in length word if needed */
 8448                           537         [ +  - ]:         845950 :     if (conn->outMsgStart >= 0)
                                538                 :                :     {
                                539                 :         845950 :         uint32      msgLen = conn->outMsgEnd - conn->outMsgStart;
                                540                 :                : 
 3219 andres@anarazel.de        541                 :         845950 :         msgLen = pg_hton32(msgLen);
 8448 tgl@sss.pgh.pa.us         542                 :         845950 :         memcpy(conn->outBuffer + conn->outMsgStart, &msgLen, 4);
                                543                 :                :     }
                                544                 :                : 
                                545                 :                :     /* trace client-to-server message */
 1943 alvherre@alvh.no-ip.      546         [ +  + ]:         845950 :     if (conn->Pfdebug)
                                547                 :                :     {
                                548         [ +  - ]:            197 :         if (conn->outCount < conn->outMsgStart)
                                549                 :            197 :             pqTraceOutputMessage(conn, conn->outBuffer + conn->outCount, true);
                                550                 :                :         else
 1943 alvherre@alvh.no-ip.      551                 :UBC           0 :             pqTraceOutputNoTypeByteMessage(conn,
                                552                 :              0 :                                            conn->outBuffer + conn->outMsgStart);
                                553                 :                :     }
                                554                 :                : 
                                555                 :                :     /* Make message eligible to send */
 8498 tgl@sss.pgh.pa.us         556                 :CBC      845950 :     conn->outCount = conn->outMsgEnd;
                                557                 :                : 
                                558                 :                :     /* If appropriate, try to push out some data */
                                559         [ +  + ]:         845950 :     if (conn->outCount >= 8192)
                                560                 :                :     {
  410                           561                 :           1229 :         int         toSend = conn->outCount;
                                562                 :                : 
                                563                 :                :         /*
                                564                 :                :          * On Unix-pipe connections, it seems profitable to prefer sending
                                565                 :                :          * pipe-buffer-sized packets not randomly-sized ones, so retain the
                                566                 :                :          * last partial-8K chunk in our buffer for now.  On TCP connections,
                                567                 :                :          * the advantage of that is far less clear.  Moreover, it flat out
                                568                 :                :          * isn't safe when using SSL or GSSAPI, because those code paths have
                                569                 :                :          * API stipulations that if they fail to send all the data that was
                                570                 :                :          * offered in the previous write attempt, we mustn't offer less data
                                571                 :                :          * in this write attempt.  The previous write attempt might've been
                                572                 :                :          * pqFlush attempting to send everything in the buffer, so we mustn't
                                573                 :                :          * offer less now.  (Presently, we won't try to use SSL or GSSAPI on
                                574                 :                :          * Unix connections, so those checks are just Asserts.  They'll have
                                575                 :                :          * to become part of the regular if-test if we ever change that.)
                                576                 :                :          */
                                577         [ +  - ]:           1229 :         if (conn->raddr.addr.ss_family == AF_UNIX)
                                578                 :                :         {
                                579                 :                : #ifdef USE_SSL
                                580         [ -  + ]:           1229 :             Assert(!conn->ssl_in_use);
                                581                 :                : #endif
                                582                 :                : #ifdef ENABLE_GSS
                                583         [ -  + ]:           1229 :             Assert(!conn->gssenc);
                                584                 :                : #endif
                                585                 :           1229 :             toSend -= toSend % 8192;
                                586                 :                :         }
                                587                 :                : 
 8498                           588         [ -  + ]:           1229 :         if (pqSendSome(conn, toSend) < 0)
 8498 tgl@sss.pgh.pa.us         589                 :UBC           0 :             return EOF;
                                590                 :                :         /* in nonblock mode, don't complain if unable to send it all */
                                591                 :                :     }
                                592                 :                : 
 8498 tgl@sss.pgh.pa.us         593                 :CBC      845950 :     return 0;
                                594                 :                : }
                                595                 :                : 
                                596                 :                : /* ----------
                                597                 :                :  * pqReadData: read more data, if any is available
                                598                 :                :  *
                                599                 :                :  * Upon a successful return, callers may assume that either 1) all available
                                600                 :                :  * bytes have been consumed from the socket, or 2) the socket is still marked
                                601                 :                :  * readable by the OS.  (In other words: after a successful pqReadData, it's
                                602                 :                :  * safe to tell a client to poll for readable bytes on the socket without any
                                603                 :                :  * further draining of the SSL/GSS transport buffers.)
                                604                 :                :  *
                                605                 :                :  * Possible return values:
                                606                 :                :  *   1: successfully loaded at least one more byte
                                607                 :                :  *   0: no data is presently available, but no error detected
                                608                 :                :  *  -1: error detected (including EOF = connection closure);
                                609                 :                :  *      conn->errorMessage set
                                610                 :                :  * NOTE: callers must not assume that pointers or indexes into conn->inBuffer
                                611                 :                :  * remain valid across this call!
                                612                 :                :  * ----------
                                613                 :                :  */
                                614                 :                : int
10307 bruce@momjian.us          615                 :        1213335 : pqReadData(PGconn *conn)
                                616                 :                : {
                                617                 :                :     int         available;
                                618                 :                : 
 4483                           619         [ +  + ]:        1213335 :     if (conn->sock == PGINVALID_SOCKET)
                                620                 :                :     {
 1348 peter@eisentraut.org      621                 :              3 :         libpq_append_conn_error(conn, "connection not open");
10307 bruce@momjian.us          622                 :              3 :         return -1;
                                623                 :                :     }
                                624                 :                : 
   18 heikki.linnakangas@i      625                 :        1213332 :     available = pqReadData_internal(conn);
                                626         [ +  + ]:        1213332 :     if (available < 0)
                                627                 :            135 :         return -1;
                                628         [ +  + ]:        1213197 :     else if (available > 0)
                                629                 :                :     {
                                630                 :                :         /*
                                631                 :                :          * Make sure there are no bytes stuck in layers between conn->inBuffer
                                632                 :                :          * and the socket, to make it safe for clients to poll on PQsocket().
                                633                 :                :          */
                                634         [ -  + ]:         824377 :         if (pqDrainPending(conn))
   18 heikki.linnakangas@i      635                 :UBC           0 :             return -1;
                                636                 :                :     }
                                637                 :                :     else
                                638                 :                :     {
                                639                 :                :         /*
                                640                 :                :          * If we're not returning any bytes from the underlying transport,
                                641                 :                :          * that must imply there aren't any in the transport buffer...
                                642                 :                :          */
   18 heikki.linnakangas@i      643         [ -  + ]:CBC      388820 :         Assert(pqsecure_bytes_pending(conn) == 0);
                                644                 :                :     }
                                645                 :                : 
                                646                 :        1213197 :     return available;
                                647                 :                : }
                                648                 :                : 
                                649                 :                : /*
                                650                 :                :  * Workhorse for pqReadData().  It's kept separate from the pqDrainPending()
                                651                 :                :  * logic to avoid adding to this function's goto complexity.
                                652                 :                :  */
                                653                 :                : static int
                                654                 :        1213332 : pqReadData_internal(PGconn *conn)
                                655                 :                : {
                                656                 :        1213332 :     int         someread = 0;
                                657                 :                :     ssize_t     nread;
                                658                 :                : 
                                659                 :                :     /* Left-justify any data in the buffer to make room */
10307 bruce@momjian.us          660         [ +  + ]:        1213332 :     if (conn->inStart < conn->inEnd)
                                661                 :                :     {
 9189 tgl@sss.pgh.pa.us         662         [ +  + ]:         262324 :         if (conn->inStart > 0)
                                663                 :                :         {
                                664                 :          75230 :             memmove(conn->inBuffer, conn->inBuffer + conn->inStart,
                                665                 :          75230 :                     conn->inEnd - conn->inStart);
                                666                 :          75230 :             conn->inEnd -= conn->inStart;
                                667                 :          75230 :             conn->inCursor -= conn->inStart;
                                668                 :          75230 :             conn->inStart = 0;
                                669                 :                :         }
                                670                 :                :     }
                                671                 :                :     else
                                672                 :                :     {
                                673                 :                :         /* buffer is logically empty, reset it */
10307 bruce@momjian.us          674                 :         951008 :         conn->inStart = conn->inCursor = conn->inEnd = 0;
                                675                 :                :     }
                                676                 :                : 
                                677                 :                :     /*
                                678                 :                :      * If the buffer is fairly full, enlarge it. We need to be able to enlarge
                                679                 :                :      * the buffer in case a single message exceeds the initial buffer size. We
                                680                 :                :      * enlarge before filling the buffer entirely so as to avoid asking the
                                681                 :                :      * kernel for a partial packet. The magic constant here should be large
                                682                 :                :      * enough for a TCP packet or Unix pipe bufferload.  8K is the usual pipe
                                683                 :                :      * buffer size, so...
                                684                 :                :      */
 9825 tgl@sss.pgh.pa.us         685         [ +  + ]:        1213332 :     if (conn->inBufSize - conn->inEnd < 8192)
                                686                 :                :     {
 6631                           687         [ +  - ]:              3 :         if (pqCheckInBufferSpace(conn->inEnd + (size_t) 8192, conn))
                                688                 :                :         {
                                689                 :                :             /*
                                690                 :                :              * We don't insist that the enlarge worked, but we need some room
                                691                 :                :              */
 8495 tgl@sss.pgh.pa.us         692         [ #  # ]:UBC           0 :             if (conn->inBufSize - conn->inEnd < 100)
                                693                 :              0 :                 return -1;      /* errorMessage already set */
                                694                 :                :         }
                                695                 :                :     }
                                696                 :                : 
                                697                 :                :     /* OK, try to read some data */
 8867 bruce@momjian.us          698                 :CBC     1325852 : retry3:
 8806 tgl@sss.pgh.pa.us         699                 :        1325852 :     nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
 8725 bruce@momjian.us          700                 :        1325852 :                           conn->inBufSize - conn->inEnd);
10307                           701         [ +  + ]:        1325852 :     if (nread < 0)
                                702                 :                :     {
 2114 tgl@sss.pgh.pa.us         703   [ -  +  +  - ]:         493357 :         switch (SOCK_ERRNO)
                                704                 :                :         {
 2114 tgl@sss.pgh.pa.us         705                 :UBC           0 :             case EINTR:
                                706                 :              0 :                 goto retry3;
                                707                 :                : 
                                708                 :                :                 /* Some systems return EAGAIN/EWOULDBLOCK for no data */
                                709                 :                : #ifdef EAGAIN
 2114 tgl@sss.pgh.pa.us         710                 :CBC      493339 :             case EAGAIN:
                                711                 :         493339 :                 return someread;
                                712                 :                : #endif
                                713                 :                : #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
                                714                 :                :             case EWOULDBLOCK:
                                715                 :                :                 return someread;
                                716                 :                : #endif
                                717                 :                : 
                                718                 :                :                 /* We might get ECONNRESET etc here if connection failed */
                                719                 :             18 :             case ALL_CONNECTION_FAILURE_ERRNOS:
                                720                 :             18 :                 goto definitelyFailed;
                                721                 :                : 
 2114 tgl@sss.pgh.pa.us         722                 :UBC           0 :             default:
                                723                 :                :                 /* pqsecure_read set the error message for us */
                                724                 :              0 :                 return -1;
                                725                 :                :         }
                                726                 :                :     }
10307 bruce@momjian.us          727         [ +  + ]:CBC      832495 :     if (nread > 0)
                                728                 :                :     {
                                729                 :         832276 :         conn->inEnd += nread;
                                730                 :                : 
                                731                 :                :         /*
                                732                 :                :          * Hack to deal with the fact that some kernels will only give us back
                                733                 :                :          * 1 packet per recv() call, even if we asked for more and there is
                                734                 :                :          * more available.  If it looks like we are reading a long message,
                                735                 :                :          * loop back to recv() again immediately, until we run out of data or
                                736                 :                :          * buffer space.  Without this, the block-and-restart behavior of
                                737                 :                :          * libpq's higher levels leads to O(N^2) performance on long messages.
                                738                 :                :          *
                                739                 :                :          * Since we left-justified the data above, conn->inEnd gives the
                                740                 :                :          * amount of data already read in the current message.  We consider
                                741                 :                :          * the message "long" once we have acquired 32k ...
                                742                 :                :          */
 9812 tgl@sss.pgh.pa.us         743         [ +  + ]:         832276 :         if (conn->inEnd > 32768 &&
                                744         [ +  + ]:         208690 :             (conn->inBufSize - conn->inEnd) >= 8192)
                                745                 :                :         {
                                746                 :         112520 :             someread = 1;
 8867 bruce@momjian.us          747                 :         112520 :             goto retry3;
                                748                 :                :         }
10307                           749                 :         719756 :         return 1;
                                750                 :                :     }
                                751                 :                : 
 9812 tgl@sss.pgh.pa.us         752         [ -  + ]:            219 :     if (someread)
 9812 tgl@sss.pgh.pa.us         753                 :UBC           0 :         return 1;               /* got a zero read after successful tries */
                                754                 :                : 
                                755                 :                :     /*
                                756                 :                :      * A return value of 0 could mean just that no data is now available, or
                                757                 :                :      * it could mean EOF --- that is, the server has closed the connection.
                                758                 :                :      * Since we have the socket in nonblock mode, the only way to tell the
                                759                 :                :      * difference is to see if select() is saying that the file is ready.
                                760                 :                :      * Grumble.  Fortunately, we don't expect this path to be taken much,
                                761                 :                :      * since in normal practice we should not be trying to read data unless
                                762                 :                :      * the file selected for reading already.
                                763                 :                :      *
                                764                 :                :      * In SSL mode it's even worse: SSL_read() could say WANT_READ and then
                                765                 :                :      * data could arrive before we make the pqReadReady() test, but the second
                                766                 :                :      * SSL_read() could still say WANT_READ because the data received was not
                                767                 :                :      * a complete SSL record.  So we must play dumb and assume there is more
                                768                 :                :      * data, relying on the SSL layer to detect true EOF.
                                769                 :                :      */
                                770                 :                : 
                                771                 :                : #ifdef USE_SSL
 4366 heikki.linnakangas@i      772         [ +  + ]:CBC         219 :     if (conn->ssl_in_use)
 8391 tgl@sss.pgh.pa.us         773                 :            102 :         return 0;
                                774                 :                : #endif
                                775                 :                : 
 9734 bruce@momjian.us          776      [ -  +  - ]:            117 :     switch (pqReadReady(conn))
                                777                 :                :     {
 9734 bruce@momjian.us          778                 :UBC           0 :         case 0:
                                779                 :                :             /* definitely no data available */
                                780                 :              0 :             return 0;
 9734 bruce@momjian.us          781                 :CBC         117 :         case 1:
                                782                 :                :             /* ready for read */
                                783                 :            117 :             break;
 9734 bruce@momjian.us          784                 :UBC           0 :         default:
                                785                 :                :             /* we override pqReadReady's message with something more useful */
 4294 tgl@sss.pgh.pa.us         786                 :              0 :             goto definitelyEOF;
                                787                 :                :     }
                                788                 :                : 
                                789                 :                :     /*
                                790                 :                :      * Still not sure that it's EOF, because some data could have just
                                791                 :                :      * arrived.
                                792                 :                :      */
 8867 bruce@momjian.us          793                 :CBC         117 : retry4:
 8806 tgl@sss.pgh.pa.us         794                 :            117 :     nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
                                795                 :            117 :                           conn->inBufSize - conn->inEnd);
10307 bruce@momjian.us          796         [ -  + ]:            117 :     if (nread < 0)
                                797                 :                :     {
 2114 tgl@sss.pgh.pa.us         798   [ #  #  #  # ]:UBC           0 :         switch (SOCK_ERRNO)
                                799                 :                :         {
                                800                 :              0 :             case EINTR:
                                801                 :              0 :                 goto retry4;
                                802                 :                : 
                                803                 :                :                 /* Some systems return EAGAIN/EWOULDBLOCK for no data */
                                804                 :                : #ifdef EAGAIN
                                805                 :              0 :             case EAGAIN:
                                806                 :              0 :                 return 0;
                                807                 :                : #endif
                                808                 :                : #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
                                809                 :                :             case EWOULDBLOCK:
                                810                 :                :                 return 0;
                                811                 :                : #endif
                                812                 :                : 
                                813                 :                :                 /* We might get ECONNRESET etc here if connection failed */
                                814                 :              0 :             case ALL_CONNECTION_FAILURE_ERRNOS:
                                815                 :              0 :                 goto definitelyFailed;
                                816                 :                : 
                                817                 :              0 :             default:
                                818                 :                :                 /* pqsecure_read set the error message for us */
                                819                 :              0 :                 return -1;
                                820                 :                :         }
                                821                 :                :     }
10307 bruce@momjian.us          822         [ -  + ]:CBC         117 :     if (nread > 0)
                                823                 :                :     {
10307 bruce@momjian.us          824                 :UBC           0 :         conn->inEnd += nread;
                                825                 :              0 :         return 1;
                                826                 :                :     }
                                827                 :                : 
                                828                 :                :     /*
                                829                 :                :      * OK, we are getting a zero read even though select() says ready. This
                                830                 :                :      * means the connection has been closed.  Cope.
                                831                 :                :      */
 4294 tgl@sss.pgh.pa.us         832                 :CBC         117 : definitelyEOF:
 1348 peter@eisentraut.org      833                 :            117 :     libpq_append_conn_error(conn, "server closed the connection unexpectedly\n"
                                834                 :                :                             "\tThis probably means the server terminated abnormally\n"
                                835                 :                :                             "\tbefore or while processing the request.");
                                836                 :                : 
                                837                 :                :     /* Come here if lower-level code already set a suitable errorMessage */
10170 bruce@momjian.us          838                 :            135 : definitelyFailed:
                                839                 :                :     /* Do *not* drop any already-read data; caller still wants it */
 3908 tgl@sss.pgh.pa.us         840                 :            135 :     pqDropConnection(conn, false);
 3321                           841                 :            135 :     conn->status = CONNECTION_BAD;   /* No more connection to backend */
10307 bruce@momjian.us          842                 :            135 :     return -1;
                                843                 :                : }
                                844                 :                : 
                                845                 :                : /*---
                                846                 :                :  * Drain any transport data that is already buffered in userspace and add it
                                847                 :                :  * to conn->inBuffer, enlarging inBuffer if necessary.  The drain fails if
                                848                 :                :  * inBuffer cannot be made to hold all available transport data.
                                849                 :                :  *
                                850                 :                :  * We assume that the underlying secure transport implementation does not
                                851                 :                :  * attempt to read any more data from the socket while draining the transport
                                852                 :                :  * buffer.  After a successful return, pqsecure_bytes_pending() must be zero.
                                853                 :                :  *
                                854                 :                :  * This operation is necessary to prevent deadlock, due to a layering
                                855                 :                :  * violation designed into our asynchronous client API: pqReadData() and all
                                856                 :                :  * the parsing routines above it receive data from the SSL/GSS transport
                                857                 :                :  * buffer, but clients poll on the raw PQsocket() handle.  So data can be
                                858                 :                :  * "lost" in the intermediate layer if we don't take it out here.
                                859                 :                :  *
                                860                 :                :  * To illustrate what we're trying to prevent, say that the server is sending
                                861                 :                :  * two messages at once in response to a query (Aaaa and Bb), the libpq buffer
                                862                 :                :  * is five characters in size, and TLS records max out at three-character
                                863                 :                :  * payloads.  Here's what would happen if pqReadData() didn't call
                                864                 :                :  * pqDrainPending():
                                865                 :                :  *
                                866                 :                :  *   Client    libpq      SSL      Socket
                                867                 :                :  *     |         |         |         |
                                868                 :                :  *     |      [     ]    [   ]     [   ]    [1] Buffers are empty, client is
                                869                 :                :  *     x --------------------------> |          polling on socket
                                870                 :                :  *     |         |         |         |
                                871                 :                :  *     |      [     ]    [   ]     [xxx]    [2] First record is received; poll
                                872                 :                :  *     | <-------------------------- |          signals read-ready
                                873                 :                :  *     |         |         |         |
                                874                 :                :  *     x ---> [     ]    [   ]     [xxx]    [3] Client calls PQconsumeInput()
                                875                 :                :  *     |         |         |         |
                                876                 :                :  *     |      [     ] -> [   ]     [xxx]    [4] libpq calls pqReadData() to fill
                                877                 :                :  *     |         |         |         |          the receive buffer
                                878                 :                :  *     |      [     ]    [Aaa] <-- [   ]    [5] SSL pulls payload off the wire
                                879                 :                :  *     |         |         |         |          and decrypts it
                                880                 :                :  *     |      [Aaa  ] <- [   ]     [   ]    [6] pqsecure_read() takes all data
                                881                 :                :  *     |         |         |         |
                                882                 :                :  *     | <--- [Aaa  ]    [   ]     [   ]    [7] PQconsumeInput() returns with a
                                883                 :                :  *     x --------------------------> |          partial message, PQisBusy() is
                                884                 :                :  *     |         |         |         |          still true, client polls again
                                885                 :                :  *     |      [Aaa  ]    [   ]     [xxx]    [8] Second record is received; poll
                                886                 :                :  *     | <-------------------------- |          signals read-ready
                                887                 :                :  *     |         |         |         |
                                888                 :                :  *     x ---> [Aaa  ]    [   ]     [xxx]    [9] Client calls PQconsumeInput()
                                889                 :                :  *     |         |         |         |
                                890                 :                :  *     |      [Aaa  ] -> [   ]     [xxx]   [10] libpq calls pqReadData() to fill
                                891                 :                :  *     |         |         |         |          the receive buffer
                                892                 :                :  *     |      [Aaa  ]    [aBb] <-- [   ]   [11] SSL decrypts
                                893                 :                :  *     |         |         |         |
                                894                 :                :  *     |      [AaaaB] <- [b  ]     [   ]   [12] pqsecure_read() fills its
                                895                 :                :  *     |         |         |         |          buffer, taking only two bytes
                                896                 :                :  *     | <--- [AaaaB]    [b  ]     [   ]   [13] PQconsumeInput() returns with a
                                897                 :                :  *     |         |         |         |          complete message buffered;
                                898                 :                :  *     |         |         |         |          PQisBusy() is false
                                899                 :                :  *     x ---> [AaaaB]    [b  ]     [   ]   [14] Client calls PQgetResult()
                                900                 :                :  *     |         |         |         |
                                901                 :                :  *     | <--- [B    ]    [b  ]     [   ]   [15] Aaaa is returned; PQisBusy() is
                                902                 :                :  *     x --------------------------> |          true and client polls again
                                903                 :                :  *     .         |         |         .
                                904                 :                :  *     .      [B    ]    [b  ]       .     [16] No packets, and client hangs.
                                905                 :                :  *     .         |         |         .
                                906                 :                :  *
                                907                 :                :  * The pqDrainPending() call fixes the above scenario at step [13].  Before
                                908                 :                :  * returning to the Client, it first expands the libpq buffer and moves the
                                909                 :                :  * remaining data from the SSL buffer to the libpq buffer.
                                910                 :                :  *
                                911                 :                :  * The function returns 0 on success and -1 on error.  Success means that
                                912                 :                :  * there was no data pending or it was successfully drained to conn->inBuffer.
                                913                 :                :  * On error, conn->errorMessage is set.
                                914                 :                :  */
                                915                 :                : static int
   18 heikki.linnakangas@i      916                 :         824377 : pqDrainPending(PGconn *conn)
                                917                 :                : {
                                918                 :                :     ssize_t     bytes_pending;
                                919                 :                :     ssize_t     nread;
                                920                 :                : 
                                921                 :         824377 :     bytes_pending = pqsecure_bytes_pending(conn);
                                922         [ +  - ]:         824377 :     if (bytes_pending <= 0)
                                923                 :         824377 :         return bytes_pending;
                                924                 :                : 
                                925                 :                :     /* Expand the input buffer if necessary. */
   18 heikki.linnakangas@i      926         [ #  # ]:UBC           0 :     if (pqCheckInBufferSpace(conn->inEnd + (size_t) bytes_pending, conn))
                                927                 :              0 :         return -1;              /* errorMessage already set */
                                928                 :                : 
                                929                 :              0 :     nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
                                930                 :                :                           bytes_pending);
                                931                 :                : 
                                932                 :                :     /*
                                933                 :                :      * When there are bytes pending, pqsecure_read() is not supposed to fail
                                934                 :                :      * or do a short read, but let's check anyway to be safe.
                                935                 :                :      */
   16                           936         [ #  # ]:              0 :     if (nread < 0)
                                937                 :              0 :         return -1;
                                938                 :              0 :     conn->inEnd += nread;
   18                           939         [ #  # ]:              0 :     if (nread != bytes_pending)
                                940                 :                :     {
                                941                 :              0 :         libpq_append_conn_error(conn,
                                942                 :                :                                 "drained only %zd of %zd pending bytes in transport buffer",
                                943                 :                :                                 nread, bytes_pending);
                                944                 :              0 :         return -1;
                                945                 :                :     }
                                946                 :              0 :     return 0;
                                947                 :                : }
                                948                 :                : 
                                949                 :                : /*
                                950                 :                :  * pqSendSome: send data waiting in the output buffer.
                                951                 :                :  *
                                952                 :                :  * len is how much to try to send (typically equal to outCount, but may
                                953                 :                :  * be less).
                                954                 :                :  *
                                955                 :                :  * Return 0 on success, -1 on failure and 1 when not all data could be sent
                                956                 :                :  * because the socket would block and the connection is non-blocking.
                                957                 :                :  *
                                958                 :                :  * Note that this is also responsible for consuming data from the socket
                                959                 :                :  * (putting it in conn->inBuffer) in any situation where we can't send
                                960                 :                :  * all the specified data immediately.
                                961                 :                :  *
                                962                 :                :  * If a socket-level write failure occurs, conn->write_failed is set and the
                                963                 :                :  * error message is saved in conn->write_err_msg, but we clear the output
                                964                 :                :  * buffer and return zero anyway; this is because callers should soldier on
                                965                 :                :  * until we have read what we can from the server and checked for an error
                                966                 :                :  * message.  write_err_msg should be reported only when we are unable to
                                967                 :                :  * obtain a server error first.  Much of that behavior is implemented at
                                968                 :                :  * lower levels, but this function deals with some edge cases.
                                969                 :                :  */
                                970                 :                : static int
 8498 tgl@sss.pgh.pa.us         971                 :CBC      604987 : pqSendSome(PGconn *conn, int len)
                                972                 :                : {
10189 bruce@momjian.us          973                 :         604987 :     char       *ptr = conn->outBuffer;
 8498 tgl@sss.pgh.pa.us         974                 :         604987 :     int         remaining = conn->outCount;
                                975                 :         604987 :     int         result = 0;
                                976                 :                : 
                                977                 :                :     /*
                                978                 :                :      * If we already had a write failure, we will never again try to send data
                                979                 :                :      * on that connection.  Even if the kernel would let us, we've probably
                                980                 :                :      * lost message boundary sync with the server.  conn->write_failed
                                981                 :                :      * therefore persists until the connection is reset, and we just discard
                                982                 :                :      * all data presented to be written.  However, as long as we still have a
                                983                 :                :      * valid socket, we should continue to absorb data from the backend, so
                                984                 :                :      * that we can collect any final error messages.
                                985                 :                :      */
 2685                           986         [ +  + ]:         604987 :     if (conn->write_failed)
                                987                 :                :     {
                                988                 :                :         /* conn->write_err_msg should be set up already */
                                989                 :              3 :         conn->outCount = 0;
                                990                 :                :         /* Absorb input data if any, and detect socket closure */
 2239                           991         [ +  - ]:              3 :         if (conn->sock != PGINVALID_SOCKET)
                                992                 :                :         {
                                993         [ +  - ]:              3 :             if (pqReadData(conn) < 0)
                                994                 :              3 :                 return -1;
                                995                 :                :         }
 2685 tgl@sss.pgh.pa.us         996                 :UBC           0 :         return 0;
                                997                 :                :     }
                                998                 :                : 
 4483 bruce@momjian.us          999         [ -  + ]:CBC      604984 :     if (conn->sock == PGINVALID_SOCKET)
                               1000                 :                :     {
 2685 tgl@sss.pgh.pa.us        1001                 :UBC           0 :         conn->write_failed = true;
                               1002                 :                :         /* Store error message in conn->write_err_msg, if possible */
                               1003                 :                :         /* (strdup failure is OK, we'll cope later) */
 2021                          1004                 :              0 :         conn->write_err_msg = strdup(libpq_gettext("connection not open\n"));
                               1005                 :                :         /* Discard queued data; no chance it'll ever be sent */
 4546                          1006                 :              0 :         conn->outCount = 0;
 2685                          1007                 :              0 :         return 0;
                               1008                 :                :     }
                               1009                 :                : 
                               1010                 :                :     /* while there's still data to send */
10307 bruce@momjian.us         1011         [ +  + ]:CBC     1210233 :     while (len > 0)
                               1012                 :                :     {
                               1013                 :                :         ssize_t     sent;
                               1014                 :                : 
                               1015                 :                : #ifndef WIN32
 8806 tgl@sss.pgh.pa.us        1016                 :         605252 :         sent = pqsecure_write(conn, ptr, len);
                               1017                 :                : #else
                               1018                 :                : 
                               1019                 :                :         /*
                               1020                 :                :          * Windows can fail on large sends, per KB article Q201213. The
                               1021                 :                :          * failure-point appears to be different in different versions of
                               1022                 :                :          * Windows, but 64k should always be safe.
                               1023                 :                :          */
                               1024                 :                :         sent = pqsecure_write(conn, ptr, Min(len, 65536));
                               1025                 :                : #endif
                               1026                 :                : 
10307 bruce@momjian.us         1027         [ +  + ]:         605252 :         if (sent < 0)
                               1028                 :                :         {
                               1029                 :                :             /* Anything except EAGAIN/EWOULDBLOCK/EINTR is trouble */
 9104                          1030      [ +  -  - ]:            271 :             switch (SOCK_ERRNO)
                               1031                 :                :             {
                               1032                 :                : #ifdef EAGAIN
10307                          1033                 :            271 :                 case EAGAIN:
                               1034                 :            271 :                     break;
                               1035                 :                : #endif
                               1036                 :                : #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
                               1037                 :                :                 case EWOULDBLOCK:
                               1038                 :                :                     break;
                               1039                 :                : #endif
 9685 bruce@momjian.us         1040                 :UBC           0 :                 case EINTR:
                               1041                 :              0 :                     continue;
                               1042                 :                : 
 5480 tgl@sss.pgh.pa.us        1043                 :              0 :                 default:
                               1044                 :                :                     /* Discard queued data; no chance it'll ever be sent */
 8498                          1045                 :              0 :                     conn->outCount = 0;
                               1046                 :                : 
                               1047                 :                :                     /* Absorb input data if any, and detect socket closure */
 2239                          1048         [ #  # ]:              0 :                     if (conn->sock != PGINVALID_SOCKET)
                               1049                 :                :                     {
                               1050         [ #  # ]:              0 :                         if (pqReadData(conn) < 0)
                               1051                 :              0 :                             return -1;
                               1052                 :                :                     }
                               1053                 :                : 
                               1054                 :                :                     /*
                               1055                 :                :                      * Lower-level code should already have filled
                               1056                 :                :                      * conn->write_err_msg (and set conn->write_failed) or
                               1057                 :                :                      * conn->errorMessage.  In the former case, we pretend
                               1058                 :                :                      * there's no problem; the write_failed condition will be
                               1059                 :                :                      * dealt with later.  Otherwise, report the error now.
                               1060                 :                :                      */
 1624                          1061         [ #  # ]:              0 :                     if (conn->write_failed)
                               1062                 :              0 :                         return 0;
                               1063                 :                :                     else
                               1064                 :              0 :                         return -1;
                               1065                 :                :             }
                               1066                 :                :         }
                               1067                 :                :         else
                               1068                 :                :         {
10307 bruce@momjian.us         1069                 :CBC      604981 :             ptr += sent;
                               1070                 :         604981 :             len -= sent;
 8498 tgl@sss.pgh.pa.us        1071                 :         604981 :             remaining -= sent;
                               1072                 :                :         }
                               1073                 :                : 
10307 bruce@momjian.us         1074         [ +  + ]:         605252 :         if (len > 0)
                               1075                 :                :         {
                               1076                 :                :             /*
                               1077                 :                :              * We didn't send it all, wait till we can send more.
                               1078                 :                :              *
                               1079                 :                :              * There are scenarios in which we can't send data because the
                               1080                 :                :              * communications channel is full, but we cannot expect the server
                               1081                 :                :              * to clear the channel eventually because it's blocked trying to
                               1082                 :                :              * send data to us.  (This can happen when we are sending a large
                               1083                 :                :              * amount of COPY data, and the server has generated lots of
                               1084                 :                :              * NOTICE responses.)  To avoid a deadlock situation, we must be
                               1085                 :                :              * prepared to accept and buffer incoming data before we try
                               1086                 :                :              * again.  Furthermore, it is possible that such incoming data
                               1087                 :                :              * might not arrive until after we've gone to sleep.  Therefore,
                               1088                 :                :              * we wait for either read ready or write ready.
                               1089                 :                :              *
                               1090                 :                :              * In non-blocking mode, we don't wait here directly, but return 1
                               1091                 :                :              * to indicate that data is still pending.  The caller should wait
                               1092                 :                :              * for both read and write ready conditions, and call
                               1093                 :                :              * PQconsumeInput() on read ready, but just in case it doesn't, we
                               1094                 :                :              * call pqReadData() ourselves before returning.  That's not
                               1095                 :                :              * enough if the data has not arrived yet, but it's the best we
                               1096                 :                :              * can do, and works pretty well in practice.  (The documentation
                               1097                 :                :              * used to say that you only need to wait for write-ready, so
                               1098                 :                :              * there are still plenty of applications like that out there.)
                               1099                 :                :              *
                               1100                 :                :              * Note that errors here don't result in write_failed becoming
                               1101                 :                :              * set.
                               1102                 :                :              */
 8315 tgl@sss.pgh.pa.us        1103         [ -  + ]:            271 :             if (pqReadData(conn) < 0)
                               1104                 :                :             {
 8315 tgl@sss.pgh.pa.us        1105                 :UBC           0 :                 result = -1;    /* error message already set up */
                               1106                 :              0 :                 break;
                               1107                 :                :             }
                               1108                 :                : 
 4170 heikki.linnakangas@i     1109         [ +  + ]:CBC         271 :             if (pqIsnonblocking(conn))
                               1110                 :                :             {
                               1111                 :              3 :                 result = 1;
                               1112                 :              3 :                 break;
                               1113                 :                :             }
                               1114                 :                : 
 3265 peter_e@gmx.net          1115         [ -  + ]:            268 :             if (pqWait(true, true, conn))
                               1116                 :                :             {
 8498 tgl@sss.pgh.pa.us        1117                 :UBC           0 :                 result = -1;
                               1118                 :              0 :                 break;
                               1119                 :                :             }
                               1120                 :                :         }
                               1121                 :                :     }
                               1122                 :                : 
                               1123                 :                :     /* shift the remaining contents of the buffer */
 8498 tgl@sss.pgh.pa.us        1124         [ +  + ]:CBC      604984 :     if (remaining > 0)
                               1125                 :           1229 :         memmove(conn->outBuffer, ptr, remaining);
                               1126                 :         604984 :     conn->outCount = remaining;
                               1127                 :                : 
                               1128                 :         604984 :     return result;
                               1129                 :                : }
                               1130                 :                : 
                               1131                 :                : 
                               1132                 :                : /*
                               1133                 :                :  * pqFlush: send any data waiting in the output buffer
                               1134                 :                :  *
                               1135                 :                :  * Return 0 on success, -1 on failure and 1 when not all data could be sent
                               1136                 :                :  * because the socket would block and the connection is non-blocking.
                               1137                 :                :  * (See pqSendSome comments about how failure should be handled.)
                               1138                 :                :  */
                               1139                 :                : int
 8908 bruce@momjian.us         1140                 :        1053389 : pqFlush(PGconn *conn)
                               1141                 :                : {
 8498 tgl@sss.pgh.pa.us        1142         [ +  + ]:        1053389 :     if (conn->outCount > 0)
                               1143                 :                :     {
 1943 alvherre@alvh.no-ip.     1144         [ +  + ]:         603758 :         if (conn->Pfdebug)
                               1145                 :             54 :             fflush(conn->Pfdebug);
                               1146                 :                : 
 8498 tgl@sss.pgh.pa.us        1147                 :         603758 :         return pqSendSome(conn, conn->outCount);
                               1148                 :                :     }
                               1149                 :                : 
 8908 bruce@momjian.us         1150                 :         449631 :     return 0;
                               1151                 :                : }
                               1152                 :                : 
                               1153                 :                : 
                               1154                 :                : /*
                               1155                 :                :  * pqWait: wait until we can read or write the connection socket
                               1156                 :                :  *
                               1157                 :                :  * JAB: If SSL enabled and used and forRead, buffered bytes short-circuit the
                               1158                 :                :  * call to select().
                               1159                 :                :  *
                               1160                 :                :  * We also stop waiting and return if the kernel flags an exception condition
                               1161                 :                :  * on the socket.  The actual error condition will be detected and reported
                               1162                 :                :  * when the caller tries to read or write the socket.
                               1163                 :                :  */
                               1164                 :                : int
10307                          1165                 :         605218 : pqWait(int forRead, int forWrite, PGconn *conn)
                               1166                 :                : {
  772 tgl@sss.pgh.pa.us        1167                 :         605218 :     return pqWaitTimed(forRead, forWrite, conn, -1);
                               1168                 :                : }
                               1169                 :                : 
                               1170                 :                : /*
                               1171                 :                :  * pqWaitTimed: wait, but not past end_time.
                               1172                 :                :  *
                               1173                 :                :  * Returns -1 on failure, 0 if the socket is readable/writable, 1 if it timed out.
                               1174                 :                :  *
                               1175                 :                :  * The timeout is specified by end_time, which is the int64 number of
                               1176                 :                :  * microseconds since the Unix epoch (that is, time_t times 1 million).
                               1177                 :                :  * Timeout is infinite if end_time is -1.  Timeout is immediate (no blocking)
                               1178                 :                :  * if end_time is 0 (or indeed, any time before now).
                               1179                 :                :  */
                               1180                 :                : int
                               1181                 :         633873 : pqWaitTimed(int forRead, int forWrite, PGconn *conn, pg_usec_time_t end_time)
                               1182                 :                : {
                               1183                 :                :     int         result;
                               1184                 :                : 
                               1185                 :         633873 :     result = pqSocketCheck(conn, forRead, forWrite, end_time);
                               1186                 :                : 
 8542                          1187         [ +  + ]:         633873 :     if (result < 0)
 3354 rhaas@postgresql.org     1188                 :             48 :         return -1;              /* errorMessage is already set */
                               1189                 :                : 
 8542 tgl@sss.pgh.pa.us        1190         [ +  + ]:         633825 :     if (result == 0)
                               1191                 :                :     {
 1348 peter@eisentraut.org     1192                 :              1 :         libpq_append_conn_error(conn, "timeout expired");
 3354 rhaas@postgresql.org     1193                 :              1 :         return 1;
                               1194                 :                :     }
                               1195                 :                : 
 8542 tgl@sss.pgh.pa.us        1196                 :         633824 :     return 0;
                               1197                 :                : }
                               1198                 :                : 
                               1199                 :                : /*
                               1200                 :                :  * pqReadReady: is select() saying the file is ready to read?
                               1201                 :                :  * Returns -1 on failure, 0 if not ready, 1 if ready.
                               1202                 :                :  */
                               1203                 :                : int
 8498                          1204                 :            117 : pqReadReady(PGconn *conn)
                               1205                 :                : {
  772                          1206                 :            117 :     return pqSocketCheck(conn, 1, 0, 0);
                               1207                 :                : }
                               1208                 :                : 
                               1209                 :                : /*
                               1210                 :                :  * pqWriteReady: is select() saying the file is ready to write?
                               1211                 :                :  * Returns -1 on failure, 0 if not ready, 1 if ready.
                               1212                 :                :  */
                               1213                 :                : int
 8498 tgl@sss.pgh.pa.us        1214                 :UBC           0 : pqWriteReady(PGconn *conn)
                               1215                 :                : {
  772                          1216                 :              0 :     return pqSocketCheck(conn, 0, 1, 0);
                               1217                 :                : }
                               1218                 :                : 
                               1219                 :                : /*
                               1220                 :                :  * Checks a socket, using poll or select, for data to be read, written,
                               1221                 :                :  * or both.  Returns >0 if one or more conditions are met, 0 if it timed
                               1222                 :                :  * out, -1 if an error occurred.
                               1223                 :                :  *
                               1224                 :                :  * If an altsock is set for asynchronous authentication, that will be used in
                               1225                 :                :  * preference to the "server" socket. Otherwise, if SSL is in use, the SSL
                               1226                 :                :  * buffer is checked prior to checking the socket for read data directly.
                               1227                 :                :  */
                               1228                 :                : static int
  772 tgl@sss.pgh.pa.us        1229                 :CBC      633990 : pqSocketCheck(PGconn *conn, int forRead, int forWrite, pg_usec_time_t end_time)
                               1230                 :                : {
                               1231                 :                :     int         result;
                               1232                 :                :     pgsocket    sock;
                               1233                 :                : 
 8542                          1234         [ -  + ]:         633990 :     if (!conn)
 8542 tgl@sss.pgh.pa.us        1235                 :UBC           0 :         return -1;
                               1236                 :                : 
  534 dgustafsson@postgres     1237         [ +  + ]:CBC      633990 :     if (conn->altsock != PGINVALID_SOCKET)
                               1238                 :              1 :         sock = conn->altsock;
                               1239                 :                :     else
                               1240                 :                :     {
                               1241                 :         633989 :         sock = conn->sock;
                               1242         [ +  + ]:         633989 :         if (sock == PGINVALID_SOCKET)
                               1243                 :                :         {
                               1244                 :             48 :             libpq_append_conn_error(conn, "invalid socket");
                               1245                 :             48 :             return -1;
                               1246                 :                :         }
                               1247                 :                : 
                               1248                 :                :         /* Check for SSL/GSS library buffering read bytes */
   18 heikki.linnakangas@i     1249   [ +  +  -  + ]:         633941 :         if (forRead && pqsecure_bytes_pending(conn) != 0)
                               1250                 :                :         {
                               1251                 :                :             /* short-circuit the select */
  534 dgustafsson@postgres     1252                 :UBC           0 :             return 1;
                               1253                 :                :         }
                               1254                 :                :     }
                               1255                 :                : 
                               1256                 :                :     /* We will retry as long as we get EINTR */
                               1257                 :                :     do
  534 dgustafsson@postgres     1258                 :CBC      633944 :         result = PQsocketPoll(sock, forRead, forWrite, end_time);
 8542 tgl@sss.pgh.pa.us        1259   [ +  +  +  - ]:         633944 :     while (result < 0 && SOCK_ERRNO == EINTR);
                               1260                 :                : 
                               1261         [ -  + ]:         633942 :     if (result < 0)
                               1262                 :                :     {
                               1263                 :                :         char        sebuf[PG_STRERROR_R_BUFLEN];
                               1264                 :                : 
 1348 peter@eisentraut.org     1265                 :UBC           0 :         libpq_append_conn_error(conn, "%s() failed: %s", "select",
 1163 tgl@sss.pgh.pa.us        1266                 :              0 :                                 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
                               1267                 :                :     }
                               1268                 :                : 
 8542 tgl@sss.pgh.pa.us        1269                 :CBC      633942 :     return result;
                               1270                 :                : }
                               1271                 :                : 
                               1272                 :                : 
                               1273                 :                : /*
                               1274                 :                :  * Check a file descriptor for read and/or write data, possibly waiting.
                               1275                 :                :  * If neither forRead nor forWrite are set, immediately return a timeout
                               1276                 :                :  * condition (without waiting).  Return >0 if condition is met, 0
                               1277                 :                :  * if a timeout occurred, -1 if an error or interrupt occurred.
                               1278                 :                :  *
                               1279                 :                :  * The timeout is specified by end_time, which is the int64 number of
                               1280                 :                :  * microseconds since the Unix epoch (that is, time_t times 1 million).
                               1281                 :                :  * Timeout is infinite if end_time is -1.  Timeout is immediate (no blocking)
                               1282                 :                :  * if end_time is 0 (or indeed, any time before now).
                               1283                 :                :  */
                               1284                 :                : int
  772                          1285                 :         634386 : PQsocketPoll(int sock, int forRead, int forWrite, pg_usec_time_t end_time)
                               1286                 :                : {
                               1287                 :                :     /* We use poll(2) if available, otherwise select(2) */
                               1288                 :                : #ifdef HAVE_POLL
                               1289                 :                :     struct pollfd input_fd;
                               1290                 :                :     int         timeout_ms;
                               1291                 :                : 
 8498                          1292   [ +  +  -  + ]:         634386 :     if (!forRead && !forWrite)
 8498 tgl@sss.pgh.pa.us        1293                 :UBC           0 :         return 0;
                               1294                 :                : 
 8391 bruce@momjian.us         1295                 :CBC      634386 :     input_fd.fd = sock;
                               1296                 :         634386 :     input_fd.events = POLLERR;
 8542 tgl@sss.pgh.pa.us        1297                 :         634386 :     input_fd.revents = 0;
                               1298                 :                : 
                               1299         [ +  + ]:         634386 :     if (forRead)
                               1300                 :         619974 :         input_fd.events |= POLLIN;
                               1301         [ +  + ]:         634386 :     if (forWrite)
                               1302                 :          14680 :         input_fd.events |= POLLOUT;
                               1303                 :                : 
                               1304                 :                :     /* Compute appropriate timeout interval */
  772                          1305         [ +  + ]:         634386 :     if (end_time == -1)
 8542                          1306                 :         633813 :         timeout_ms = -1;
  772                          1307         [ +  + ]:            573 :     else if (end_time == 0)
                               1308                 :            117 :         timeout_ms = 0;
                               1309                 :                :     else
                               1310                 :                :     {
                               1311                 :            456 :         pg_usec_time_t now = PQgetCurrentTimeUSec();
                               1312                 :                : 
 8542                          1313         [ +  - ]:            456 :         if (end_time > now)
  772                          1314                 :            456 :             timeout_ms = (end_time - now) / 1000;
                               1315                 :                :         else
 8542 tgl@sss.pgh.pa.us        1316                 :UBC           0 :             timeout_ms = 0;
                               1317                 :                :     }
                               1318                 :                : 
 8542 tgl@sss.pgh.pa.us        1319                 :CBC      634386 :     return poll(&input_fd, 1, timeout_ms);
                               1320                 :                : #else                           /* !HAVE_POLL */
                               1321                 :                : 
                               1322                 :                :     fd_set      input_mask;
                               1323                 :                :     fd_set      output_mask;
                               1324                 :                :     fd_set      except_mask;
                               1325                 :                :     struct timeval timeout;
                               1326                 :                :     struct timeval *ptr_timeout;
                               1327                 :                : 
                               1328                 :                :     if (!forRead && !forWrite)
                               1329                 :                :         return 0;
                               1330                 :                : 
                               1331                 :                :     FD_ZERO(&input_mask);
                               1332                 :                :     FD_ZERO(&output_mask);
                               1333                 :                :     FD_ZERO(&except_mask);
                               1334                 :                :     if (forRead)
                               1335                 :                :         FD_SET(sock, &input_mask);
                               1336                 :                : 
                               1337                 :                :     if (forWrite)
                               1338                 :                :         FD_SET(sock, &output_mask);
                               1339                 :                :     FD_SET(sock, &except_mask);
                               1340                 :                : 
                               1341                 :                :     /* Compute appropriate timeout interval */
                               1342                 :                :     if (end_time == -1)
                               1343                 :                :         ptr_timeout = NULL;
                               1344                 :                :     else if (end_time == 0)
                               1345                 :                :     {
                               1346                 :                :         timeout.tv_sec = 0;
                               1347                 :                :         timeout.tv_usec = 0;
                               1348                 :                :         ptr_timeout = &timeout;
                               1349                 :                :     }
                               1350                 :                :     else
                               1351                 :                :     {
                               1352                 :                :         pg_usec_time_t now = PQgetCurrentTimeUSec();
                               1353                 :                : 
                               1354                 :                :         if (end_time > now)
                               1355                 :                :         {
                               1356                 :                :             timeout.tv_sec = (end_time - now) / 1000000;
                               1357                 :                :             timeout.tv_usec = (end_time - now) % 1000000;
                               1358                 :                :         }
                               1359                 :                :         else
                               1360                 :                :         {
                               1361                 :                :             timeout.tv_sec = 0;
                               1362                 :                :             timeout.tv_usec = 0;
                               1363                 :                :         }
                               1364                 :                :         ptr_timeout = &timeout;
                               1365                 :                :     }
                               1366                 :                : 
                               1367                 :                :     return select(sock + 1, &input_mask, &output_mask,
                               1368                 :                :                   &except_mask, ptr_timeout);
                               1369                 :                : #endif                          /* HAVE_POLL */
                               1370                 :                : }
                               1371                 :                : 
                               1372                 :                : /*
                               1373                 :                :  * PQgetCurrentTimeUSec: get current time with microsecond precision
                               1374                 :                :  *
                               1375                 :                :  * This provides a platform-independent way of producing a reference
                               1376                 :                :  * value for PQsocketPoll's timeout parameter.
                               1377                 :                :  */
                               1378                 :                : pg_usec_time_t
  772                          1379                 :            905 : PQgetCurrentTimeUSec(void)
                               1380                 :                : {
                               1381                 :                :     struct timeval tval;
                               1382                 :                : 
                               1383                 :            905 :     gettimeofday(&tval, NULL);
                               1384                 :            905 :     return (pg_usec_time_t) tval.tv_sec * 1000000 + tval.tv_usec;
                               1385                 :                : }
                               1386                 :                : 
                               1387                 :                : 
                               1388                 :                : /*
                               1389                 :                :  * A couple of "miscellaneous" multibyte related functions. They used
                               1390                 :                :  * to be in fe-print.c but that file is doomed.
                               1391                 :                :  */
                               1392                 :                : 
                               1393                 :                : /*
                               1394                 :                :  * Like pg_encoding_mblen().  Use this in callers that want the
                               1395                 :                :  * dynamically-linked libpq's stance on encodings, even if that means
                               1396                 :                :  * different behavior in different startups of the executable.
                               1397                 :                :  */
                               1398                 :                : int
 7609                          1399                 :       29736439 : PQmblen(const char *s, int encoding)
                               1400                 :                : {
 7500 neilc@samurai.com        1401                 :       29736439 :     return pg_encoding_mblen(encoding, s);
                               1402                 :                : }
                               1403                 :                : 
                               1404                 :                : /*
                               1405                 :                :  * Like pg_encoding_mblen_bounded().  Use this in callers that want the
                               1406                 :                :  * dynamically-linked libpq's stance on encodings, even if that means
                               1407                 :                :  * different behavior in different startups of the executable.
                               1408                 :                :  */
                               1409                 :                : int
 1874 tgl@sss.pgh.pa.us        1410                 :         651082 : PQmblenBounded(const char *s, int encoding)
                               1411                 :                : {
                               1412                 :         651082 :     return strnlen(s, pg_encoding_mblen(encoding, s));
                               1413                 :                : }
                               1414                 :                : 
                               1415                 :                : /*
                               1416                 :                :  * Returns the display length of the character beginning at s, using the
                               1417                 :                :  * specified encoding.
                               1418                 :                :  */
                               1419                 :                : int
 7609                          1420                 :       29736748 : PQdsplen(const char *s, int encoding)
                               1421                 :                : {
 7500 neilc@samurai.com        1422                 :       29736748 :     return pg_encoding_dsplen(encoding, s);
                               1423                 :                : }
                               1424                 :                : 
                               1425                 :                : /*
                               1426                 :                :  * Get encoding id from environment variable PGCLIENTENCODING.
                               1427                 :                :  */
                               1428                 :                : int
 9674 peter_e@gmx.net          1429                 :          10576 : PQenv2encoding(void)
                               1430                 :                : {
                               1431                 :                :     char       *str;
 9088 ishii@postgresql.org     1432                 :          10576 :     int         encoding = PG_SQL_ASCII;
                               1433                 :                : 
 9674 peter_e@gmx.net          1434                 :          10576 :     str = getenv("PGCLIENTENCODING");
                               1435   [ +  +  +  - ]:          10576 :     if (str && *str != '\0')
                               1436                 :                :     {
                               1437                 :              6 :         encoding = pg_char_to_encoding(str);
 6860 tgl@sss.pgh.pa.us        1438         [ -  + ]:              6 :         if (encoding < 0)
 6860 tgl@sss.pgh.pa.us        1439                 :UBC           0 :             encoding = PG_SQL_ASCII;
                               1440                 :                :     }
 7500 neilc@samurai.com        1441                 :CBC       10576 :     return encoding;
                               1442                 :                : }
                               1443                 :                : 
                               1444                 :                : 
                               1445                 :                : #ifdef ENABLE_NLS
                               1446                 :                : 
                               1447                 :                : static void
 2256 noah@leadboat.com        1448                 :          37997 : libpq_binddomain(void)
                               1449                 :                : {
                               1450                 :                :     /*
                               1451                 :                :      * At least on Windows, there are gettext implementations that fail if
                               1452                 :                :      * multiple threads call bindtextdomain() concurrently.  Use a mutex and
                               1453                 :                :      * flag variable to ensure that we call it just once per process.  It is
                               1454                 :                :      * not known that similar bugs exist on non-Windows platforms, but we
                               1455                 :                :      * might as well do it the same way everywhere.
                               1456                 :                :      */
                               1457                 :                :     static volatile bool already_bound = false;
                               1458                 :                :     static pthread_mutex_t binddomain_mutex = PTHREAD_MUTEX_INITIALIZER;
                               1459                 :                : 
 9141 peter_e@gmx.net          1460         [ +  + ]:          37997 :     if (!already_bound)
                               1461                 :                :     {
                               1462                 :                :         /* bindtextdomain() does not preserve errno */
                               1463                 :                : #ifdef WIN32
                               1464                 :                :         int         save_errno = GetLastError();
                               1465                 :                : #else
 7588 bruce@momjian.us         1466                 :          13080 :         int         save_errno = errno;
                               1467                 :                : #endif
                               1468                 :                : 
  897 tgl@sss.pgh.pa.us        1469                 :          13080 :         (void) pthread_mutex_lock(&binddomain_mutex);
                               1470                 :                : 
                               1471         [ +  - ]:          13080 :         if (!already_bound)
                               1472                 :                :         {
                               1473                 :                :             const char *ldir;
                               1474                 :                : 
                               1475                 :                :             /*
                               1476                 :                :              * No relocatable lookup here because the calling executable could
                               1477                 :                :              * be anywhere
                               1478                 :                :              */
                               1479                 :          13080 :             ldir = getenv("PGLOCALEDIR");
                               1480         [ +  + ]:          13080 :             if (!ldir)
                               1481                 :            139 :                 ldir = LOCALEDIR;
                               1482                 :          13080 :             bindtextdomain(PG_TEXTDOMAIN("libpq"), ldir);
                               1483                 :          13080 :             already_bound = true;
                               1484                 :                :         }
                               1485                 :                : 
                               1486                 :          13080 :         (void) pthread_mutex_unlock(&binddomain_mutex);
                               1487                 :                : 
                               1488                 :                : #ifdef WIN32
                               1489                 :                :         SetLastError(save_errno);
                               1490                 :                : #else
 7689                          1491                 :          13080 :         errno = save_errno;
                               1492                 :                : #endif
                               1493                 :                :     }
 4334 heikki.linnakangas@i     1494                 :          37997 : }
                               1495                 :                : 
                               1496                 :                : char *
                               1497                 :          37990 : libpq_gettext(const char *msgid)
                               1498                 :                : {
                               1499                 :          37990 :     libpq_binddomain();
 6435 peter_e@gmx.net          1500                 :          37990 :     return dgettext(PG_TEXTDOMAIN("libpq"), msgid);
                               1501                 :                : }
                               1502                 :                : 
                               1503                 :                : char *
 4334 heikki.linnakangas@i     1504                 :              7 : libpq_ngettext(const char *msgid, const char *msgid_plural, unsigned long n)
                               1505                 :                : {
                               1506                 :              7 :     libpq_binddomain();
                               1507                 :              7 :     return dngettext(PG_TEXTDOMAIN("libpq"), msgid, msgid_plural, n);
                               1508                 :                : }
                               1509                 :                : 
                               1510                 :                : #endif                          /* ENABLE_NLS */
                               1511                 :                : 
                               1512                 :                : 
                               1513                 :                : /*
                               1514                 :                :  * Append a formatted string to the given buffer, after translating it.  A
                               1515                 :                :  * newline is automatically appended; the format should not end with a
                               1516                 :                :  * newline.
                               1517                 :                :  */
                               1518                 :                : void
   73 tgl@sss.pgh.pa.us        1519                 :             38 : libpq_append_error(PQExpBuffer errorMessage, const char *fmt, ...)
                               1520                 :                : {
 1348 peter@eisentraut.org     1521                 :             38 :     int         save_errno = errno;
                               1522                 :                :     bool        done;
                               1523                 :                :     va_list     args;
                               1524                 :                : 
                               1525         [ -  + ]:             38 :     Assert(fmt[strlen(fmt) - 1] != '\n');
                               1526                 :                : 
                               1527   [ +  -  -  + ]:             38 :     if (PQExpBufferBroken(errorMessage))
 1348 peter@eisentraut.org     1528                 :UBC           0 :         return;                 /* already failed */
                               1529                 :                : 
                               1530                 :                :     /* Loop in case we have to retry after enlarging the buffer. */
                               1531                 :                :     do
                               1532                 :                :     {
 1348 peter@eisentraut.org     1533                 :CBC          38 :         errno = save_errno;
                               1534                 :             38 :         va_start(args, fmt);
                               1535                 :             38 :         done = appendPQExpBufferVA(errorMessage, libpq_gettext(fmt), args);
                               1536                 :             38 :         va_end(args);
                               1537         [ -  + ]:             38 :     } while (!done);
                               1538                 :                : 
                               1539                 :             38 :     appendPQExpBufferChar(errorMessage, '\n');
                               1540                 :                : }
                               1541                 :                : 
                               1542                 :                : /*
                               1543                 :                :  * Append a formatted string to the error message buffer of the given
                               1544                 :                :  * connection, after translating it.  A newline is automatically appended; the
                               1545                 :                :  * format should not end with a newline.
                               1546                 :                :  */
                               1547                 :                : void
   73 tgl@sss.pgh.pa.us        1548                 :            740 : libpq_append_conn_error(PGconn *conn, const char *fmt, ...)
                               1549                 :                : {
 1348 peter@eisentraut.org     1550                 :            740 :     int         save_errno = errno;
                               1551                 :                :     bool        done;
                               1552                 :                :     va_list     args;
                               1553                 :                : 
                               1554         [ -  + ]:            740 :     Assert(fmt[strlen(fmt) - 1] != '\n');
                               1555                 :                : 
                               1556   [ +  -  -  + ]:            740 :     if (PQExpBufferBroken(&conn->errorMessage))
 1348 peter@eisentraut.org     1557                 :UBC           0 :         return;                 /* already failed */
                               1558                 :                : 
                               1559                 :                :     /* Loop in case we have to retry after enlarging the buffer. */
                               1560                 :                :     do
                               1561                 :                :     {
 1348 peter@eisentraut.org     1562                 :CBC         746 :         errno = save_errno;
                               1563                 :            746 :         va_start(args, fmt);
                               1564                 :            746 :         done = appendPQExpBufferVA(&conn->errorMessage, libpq_gettext(fmt), args);
                               1565                 :            746 :         va_end(args);
                               1566         [ +  + ]:            746 :     } while (!done);
                               1567                 :                : 
                               1568                 :            740 :     appendPQExpBufferChar(&conn->errorMessage, '\n');
                               1569                 :                : }
                               1570                 :                : 
                               1571                 :                : /*
                               1572                 :                :  * For 19beta only, some protocol errors will have additional information
                               1573                 :                :  * appended to help with the "grease" campaign.
                               1574                 :                :  */
                               1575                 :                : void
  152 jchampion@postgresql     1576                 :UBC           0 : libpq_append_grease_info(PGconn *conn)
                               1577                 :                : {
                               1578                 :                :     /* translator: %s is a URL */
                               1579                 :              0 :     libpq_append_conn_error(conn,
                               1580                 :                :                             "\tThis indicates a bug in either the server being contacted\n"
                               1581                 :                :                             "\tor a proxy handling the connection. Please consider\n"
                               1582                 :                :                             "\treporting this to the maintainers of that software.\n"
                               1583                 :                :                             "\tFor more information, including instructions on how to\n"
                               1584                 :                :                             "\twork around this issue for now, visit\n"
                               1585                 :                :                             "\t\t%s",
                               1586                 :                :                             "https://wiki.postgresql.org/wiki/Grease");
                               1587                 :              0 : }
        

Generated by: LCOV version 2.0-1