LCOV - differential code coverage report
Current view: top level - src/interfaces/libpq - fe-misc.c (source / functions) Coverage Total Hit UNC LBC UIC UBC GBC GIC GNC CBC EUB ECB DCB
Current: Differential Code Coverage HEAD vs 15 Lines: 73.0 % 397 290 27 18 68 16 17 159 22 92 72 157 3
Current Date: 2023-04-08 17:13:01 Functions: 91.4 % 35 32 3 30 2 3 32
Baseline: 15 Line coverage date bins:
Baseline Date: 2023-04-08 15:09:40 (120,180] days: 81.5 % 27 22 5 22
Legend: Lines: hit not hit (240..) days: 72.4 % 370 268 18 68 16 17 159 92 72 157
Function coverage date bins:
(120,180] days: 100.0 % 2 2 2
(240..) days: 45.5 % 66 30 3 30 3 30

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

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