LCOV - differential code coverage report
Current view: top level - src/interfaces/libpq - fe-protocol3.c (source / functions) Coverage Total Hit UBC GNC CBC
Current: f76c13edadc2b319036e0d238703ed56bb23f934 vs 9e17d25e79d4756be08b4a5521b4b58450217137 Lines: 61.8 % 1000 618 382 618
Current Date: 2026-09-20 14:13:17 +0900 Functions: 78.3 % 23 18 5 1 17
Baseline: lcov-20260920-baseline Branches: 56.0 % 854 478 376 478
Baseline Date: 2026-09-20 14:13:13 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 0.0 % 1 0 1
(30,360] days: 45.8 % 24 11 13 11
(360..) days: 62.3 % 975 607 368 607
Function coverage date bins:
(360..) days: 78.3 % 23 18 5 1 17
Branch coverage date bins:
(30,360] days: 34.6 % 26 9 17 9
(360..) days: 56.6 % 828 469 359 469

 Age         Owner                    Branch data    TLA  Line data    Source code
                                  1                 :                : /*-------------------------------------------------------------------------
                                  2                 :                :  *
                                  3                 :                :  * fe-protocol3.c
                                  4                 :                :  *    functions that are specific to frontend/backend protocol version 3
                                  5                 :                :  *
                                  6                 :                :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
                                  7                 :                :  * Portions Copyright (c) 1994, Regents of the University of California
                                  8                 :                :  *
                                  9                 :                :  *
                                 10                 :                :  * IDENTIFICATION
                                 11                 :                :  *    src/interfaces/libpq/fe-protocol3.c
                                 12                 :                :  *
                                 13                 :                :  *-------------------------------------------------------------------------
                                 14                 :                :  */
                                 15                 :                : #include "postgres_fe.h"
                                 16                 :                : 
                                 17                 :                : #include <ctype.h>
                                 18                 :                : #include <fcntl.h>
                                 19                 :                : #include <limits.h>
                                 20                 :                : 
                                 21                 :                : #ifdef WIN32
                                 22                 :                : #include "win32.h"
                                 23                 :                : #else
                                 24                 :                : #include <unistd.h>
                                 25                 :                : #include <netinet/tcp.h>
                                 26                 :                : #endif
                                 27                 :                : 
                                 28                 :                : #include "common/int.h"
                                 29                 :                : #include "libpq-fe.h"
                                 30                 :                : #include "libpq-int.h"
                                 31                 :                : #include "mb/pg_wchar.h"
                                 32                 :                : #include "port/pg_bswap.h"
                                 33                 :                : 
                                 34                 :                : /*
                                 35                 :                :  * This macro lists the backend message types that could be "long" (more
                                 36                 :                :  * than a couple of kilobytes).
                                 37                 :                :  */
                                 38                 :                : #define VALID_LONG_MESSAGE_TYPE(id) \
                                 39                 :                :     ((id) == PqMsg_CopyData || \
                                 40                 :                :      (id) == PqMsg_DataRow || \
                                 41                 :                :      (id) == PqMsg_ErrorResponse || \
                                 42                 :                :      (id) == PqMsg_FunctionCallResponse || \
                                 43                 :                :      (id) == PqMsg_NoticeResponse || \
                                 44                 :                :      (id) == PqMsg_NotificationResponse || \
                                 45                 :                :      (id) == PqMsg_RowDescription || \
                                 46                 :                :      (id) == PqMsg_ParameterDescription)
                                 47                 :                : 
                                 48                 :                : 
                                 49                 :                : static void handleFatalError(PGconn *conn);
                                 50                 :                : static void handleSyncLoss(PGconn *conn, char id, int msgLength);
                                 51                 :                : static int  getRowDescriptions(PGconn *conn, int msgLength);
                                 52                 :                : static int  getParamDescriptions(PGconn *conn, int msgLength);
                                 53                 :                : static int  getAnotherTuple(PGconn *conn, int msgLength);
                                 54                 :                : static int  getParameterStatus(PGconn *conn);
                                 55                 :                : static int  getBackendKeyData(PGconn *conn, int msgLength);
                                 56                 :                : static int  getNotify(PGconn *conn);
                                 57                 :                : static int  getCopyStart(PGconn *conn, ExecStatusType copytype);
                                 58                 :                : static int  getReadyForQuery(PGconn *conn);
                                 59                 :                : static void reportErrorPosition(PQExpBuffer msg, const char *query,
                                 60                 :                :                                 int loc, int encoding);
                                 61                 :                : static size_t build_startup_packet(const PGconn *conn, char *packet,
                                 62                 :                :                                    const PQEnvironmentOption *options);
                                 63                 :                : 
                                 64                 :                : 
                                 65                 :                : /*
                                 66                 :                :  * parseInput: if appropriate, parse input data from backend
                                 67                 :                :  * until input is exhausted or a stopping state is reached.
                                 68                 :                :  * Note that this function will NOT attempt to read more data from the backend.
                                 69                 :                :  */
                                 70                 :                : void
 8505 tgl@sss.pgh.pa.us          71                 :CBC     2145714 : pqParseInput3(PGconn *conn)
                                 72                 :                : {
                                 73                 :                :     char        id;
                                 74                 :                :     int         msgLength;
                                 75                 :                :     int         avail;
                                 76                 :                : 
                                 77                 :                :     /*
                                 78                 :                :      * Loop to parse successive complete messages available in the buffer.
                                 79                 :                :      */
                                 80                 :                :     for (;;)
                                 81                 :                :     {
                                 82                 :                :         /*
                                 83                 :                :          * Try to read a message.  First get the type code and length. Return
                                 84                 :                :          * if not enough data.
                                 85                 :                :          */
                                 86                 :        7409590 :         conn->inCursor = conn->inStart;
                                 87         [ +  + ]:        7409590 :         if (pqGetc(&id, conn))
                                 88                 :        1598330 :             return;
                                 89         [ +  + ]:        5811260 :         if (pqGetInt(&msgLength, 4, conn))
                                 90                 :           1398 :             return;
                                 91                 :                : 
                                 92                 :                :         /*
                                 93                 :                :          * Try to validate message type/length here.  A length less than 4 is
                                 94                 :                :          * definitely broken.  Large lengths should only be believed for a few
                                 95                 :                :          * message types.
                                 96                 :                :          */
                                 97         [ -  + ]:        5809862 :         if (msgLength < 4)
                                 98                 :                :         {
 8505 tgl@sss.pgh.pa.us          99                 :UBC           0 :             handleSyncLoss(conn, id, msgLength);
                                100                 :              0 :             return;
                                101                 :                :         }
 8302 tgl@sss.pgh.pa.us         102   [ +  +  +  +  :CBC     5809862 :         if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
                                     +  +  -  +  -  
                                     -  -  -  -  -  
                                        -  -  -  - ]
                                103                 :                :         {
 8505 tgl@sss.pgh.pa.us         104                 :UBC           0 :             handleSyncLoss(conn, id, msgLength);
                                105                 :              0 :             return;
                                106                 :                :         }
                                107                 :                : 
                                108                 :                :         /*
                                109                 :                :          * Can't process if message body isn't all here yet.
                                110                 :                :          */
 8505 tgl@sss.pgh.pa.us         111                 :CBC     5809862 :         msgLength -= 4;
                                112                 :        5809862 :         avail = conn->inEnd - conn->inCursor;
                                113         [ +  + ]:        5809862 :         if (avail < msgLength)
                                114                 :                :         {
                                115                 :                :             /*
                                116                 :                :              * Before returning, enlarge the input buffer if needed to hold
                                117                 :                :              * the whole message.  This is better than leaving it to
                                118                 :                :              * pqReadData because we can avoid multiple cycles of realloc()
                                119                 :                :              * when the message is large; also, we can implement a reasonable
                                120                 :                :              * recovery strategy if we are unable to make the buffer big
                                121                 :                :              * enough.
                                122                 :                :              */
 6688                           123         [ -  + ]:          75238 :             if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
                                124                 :                :                                      conn))
                                125                 :                :             {
                                126                 :                :                 /*
                                127                 :                :                  * Abandon the connection.  There's not much else we can
                                128                 :                :                  * safely do; we can't just ignore the message or we could
                                129                 :                :                  * miss important changes to the connection state.
                                130                 :                :                  * pqCheckInBufferSpace() already reported the error.
                                131                 :                :                  */
  394 heikki.linnakangas@i      132                 :UBC           0 :                 handleFatalError(conn);
                                133                 :                :             }
 8505 tgl@sss.pgh.pa.us         134                 :CBC       75238 :             return;
                                135                 :                :         }
                                136                 :                : 
                                137                 :                :         /*
                                138                 :                :          * NOTIFY and NOTICE messages can happen in any state; always process
                                139                 :                :          * them right away.
                                140                 :                :          *
                                141                 :                :          * Most other messages should only be processed while in BUSY state.
                                142                 :                :          * (In particular, in READY state we hold off further parsing until
                                143                 :                :          * the application collects the current PGresult.)
                                144                 :                :          *
                                145                 :                :          * However, if the state is IDLE then we got trouble; we need to deal
                                146                 :                :          * with the unexpected message somehow.
                                147                 :                :          *
                                148                 :                :          * ParameterStatus ('S') messages are a special case: in IDLE state we
                                149                 :                :          * must process 'em (this case could happen if a new value was adopted
                                150                 :                :          * from config file due to SIGHUP), but otherwise we hold off until
                                151                 :                :          * BUSY state.
                                152                 :                :          */
 1125 nathan@postgresql.or      153         [ +  + ]:        5734624 :         if (id == PqMsg_NotificationResponse)
                                154                 :                :         {
 8505 tgl@sss.pgh.pa.us         155         [ -  + ]:             53 :             if (getNotify(conn))
 8505 tgl@sss.pgh.pa.us         156                 :UBC           0 :                 return;
                                157                 :                :         }
 1125 nathan@postgresql.or      158         [ +  + ]:CBC     5734571 :         else if (id == PqMsg_NoticeResponse)
                                159                 :                :         {
 8505 tgl@sss.pgh.pa.us         160         [ -  + ]:          16184 :             if (pqGetErrorNotice3(conn, false))
 8505 tgl@sss.pgh.pa.us         161                 :UBC           0 :                 return;
                                162                 :                :         }
 8505 tgl@sss.pgh.pa.us         163         [ +  + ]:CBC     5718387 :         else if (conn->asyncStatus != PGASYNC_BUSY)
                                164                 :                :         {
                                165                 :                :             /* If not IDLE state, just wait ... */
                                166         [ +  - ]:         470748 :             if (conn->asyncStatus != PGASYNC_IDLE)
                                167                 :         470748 :                 return;
                                168                 :                : 
                                169                 :                :             /*
                                170                 :                :              * Unexpected message in IDLE state; need to recover somehow.
                                171                 :                :              * ERROR messages are handled using the notice processor;
                                172                 :                :              * ParameterStatus is handled normally; anything else is just
                                173                 :                :              * dropped on the floor after displaying a suitable warning
                                174                 :                :              * notice.  (An ERROR is very possibly the backend telling us why
                                175                 :                :              * it is about to close the connection, so we don't want to just
                                176                 :                :              * discard it...)
                                177                 :                :              */
 1125 nathan@postgresql.or      178         [ #  # ]:UBC           0 :             if (id == PqMsg_ErrorResponse)
                                179                 :                :             {
 8448 bruce@momjian.us          180         [ #  # ]:              0 :                 if (pqGetErrorNotice3(conn, false /* treat as notice */ ))
 8505 tgl@sss.pgh.pa.us         181                 :              0 :                     return;
                                182                 :                :             }
 1125 nathan@postgresql.or      183         [ #  # ]:              0 :             else if (id == PqMsg_ParameterStatus)
                                184                 :                :             {
 8505 tgl@sss.pgh.pa.us         185         [ #  # ]:              0 :                 if (getParameterStatus(conn))
                                186                 :              0 :                     return;
                                187                 :                :             }
                                188                 :                :             else
                                189                 :                :             {
                                190                 :                :                 /* Any other case is unexpected and we summarily skip it */
 8490                           191                 :              0 :                 pqInternalNotice(&conn->noticeHooks,
                                192                 :                :                                  "message type 0x%02x arrived from server while idle",
                                193                 :                :                                  id);
                                194                 :                :                 /* Discard the unexpected message */
 8505                           195                 :              0 :                 conn->inCursor += msgLength;
                                196                 :                :             }
                                197                 :                :         }
                                198                 :                :         else
                                199                 :                :         {
                                200                 :                :             /*
                                201                 :                :              * In BUSY state, we can process everything.
                                202                 :                :              */
 8505 tgl@sss.pgh.pa.us         203   [ +  +  +  +  :CBC     5247639 :             switch (id)
                                     +  +  +  +  +  
                                     +  +  +  +  +  
                                        +  +  +  +  
                                                 - ]
                                204                 :                :             {
 1125 nathan@postgresql.or      205                 :         393283 :                 case PqMsg_CommandComplete:
 8505 tgl@sss.pgh.pa.us         206         [ -  + ]:         393283 :                     if (pqGets(&conn->workBuffer, conn))
 8505 tgl@sss.pgh.pa.us         207                 :UBC           0 :                         return;
 1613 tgl@sss.pgh.pa.us         208   [ +  +  +  - ]:CBC      393283 :                     if (!pgHavePendingResult(conn))
                                209                 :                :                     {
 8505                           210                 :         195315 :                         conn->result = PQmakeEmptyPGresult(conn,
                                211                 :                :                                                            PGRES_COMMAND_OK);
 7770 neilc@samurai.com         212         [ -  + ]:         195315 :                         if (!conn->result)
                                213                 :                :                         {
 1405 peter@eisentraut.org      214                 :UBC           0 :                             libpq_append_conn_error(conn, "out of memory");
 4093 heikki.linnakangas@i      215                 :              0 :                             pqSaveErrorResult(conn);
                                216                 :                :                         }
                                217                 :                :                     }
 4093 heikki.linnakangas@i      218         [ +  - ]:CBC      393283 :                     if (conn->result)
                                219                 :         393283 :                         strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
                                220                 :                :                                 CMDSTATUS_LEN);
 8505 tgl@sss.pgh.pa.us         221                 :         393283 :                     conn->asyncStatus = PGASYNC_READY;
                                222                 :         393283 :                     break;
 1125 nathan@postgresql.or      223                 :          31125 :                 case PqMsg_ErrorResponse:
 8505 tgl@sss.pgh.pa.us         224         [ -  + ]:          31125 :                     if (pqGetErrorNotice3(conn, true))
 8505 tgl@sss.pgh.pa.us         225                 :UBC           0 :                         return;
 8505 tgl@sss.pgh.pa.us         226                 :CBC       31125 :                     conn->asyncStatus = PGASYNC_READY;
                                227                 :          31125 :                     break;
 1125 nathan@postgresql.or      228                 :         418704 :                 case PqMsg_ReadyForQuery:
 8492 tgl@sss.pgh.pa.us         229         [ -  + ]:         418704 :                     if (getReadyForQuery(conn))
 8505 tgl@sss.pgh.pa.us         230                 :UBC           0 :                         return;
 2015 alvherre@alvh.no-ip.      231         [ +  + ]:CBC      418704 :                     if (conn->pipelineStatus != PQ_PIPELINE_OFF)
                                232                 :                :                     {
                                233                 :            385 :                         conn->result = PQmakeEmptyPGresult(conn,
                                234                 :                :                                                            PGRES_PIPELINE_SYNC);
                                235         [ -  + ]:            385 :                         if (!conn->result)
                                236                 :                :                         {
 1405 peter@eisentraut.org      237                 :UBC           0 :                             libpq_append_conn_error(conn, "out of memory");
 2015 alvherre@alvh.no-ip.      238                 :              0 :                             pqSaveErrorResult(conn);
                                239                 :                :                         }
                                240                 :                :                         else
                                241                 :                :                         {
 2015 alvherre@alvh.no-ip.      242                 :CBC         385 :                             conn->pipelineStatus = PQ_PIPELINE_ON;
                                243                 :            385 :                             conn->asyncStatus = PGASYNC_READY;
                                244                 :                :                         }
                                245                 :                :                     }
                                246                 :                :                     else
                                247                 :                :                     {
                                248                 :                :                         /* Advance the command queue and set us idle */
 1020                           249                 :         418319 :                         pqCommandQueueAdvance(conn, true, false);
 2015                           250                 :         418319 :                         conn->asyncStatus = PGASYNC_IDLE;
                                251                 :                :                     }
 8505 tgl@sss.pgh.pa.us         252                 :         418704 :                     break;
 1125 nathan@postgresql.or      253                 :           1116 :                 case PqMsg_EmptyQueryResponse:
 1613 tgl@sss.pgh.pa.us         254   [ +  -  +  - ]:           1116 :                     if (!pgHavePendingResult(conn))
                                255                 :                :                     {
 8505                           256                 :           1116 :                         conn->result = PQmakeEmptyPGresult(conn,
                                257                 :                :                                                            PGRES_EMPTY_QUERY);
 7770 neilc@samurai.com         258         [ -  + ]:           1116 :                         if (!conn->result)
                                259                 :                :                         {
 1405 peter@eisentraut.org      260                 :UBC           0 :                             libpq_append_conn_error(conn, "out of memory");
 4093 heikki.linnakangas@i      261                 :              0 :                             pqSaveErrorResult(conn);
                                262                 :                :                         }
                                263                 :                :                     }
 8505 tgl@sss.pgh.pa.us         264                 :CBC        1116 :                     conn->asyncStatus = PGASYNC_READY;
                                265                 :           1116 :                     break;
 1125 nathan@postgresql.or      266                 :           4637 :                 case PqMsg_ParseComplete:
                                267                 :                :                     /* If we're doing PQprepare, we're done; else ignore */
 2015 alvherre@alvh.no-ip.      268         [ +  - ]:           4637 :                     if (conn->cmd_queue_head &&
                                269         [ +  + ]:           4637 :                         conn->cmd_queue_head->queryclass == PGQUERY_PREPARE)
                                270                 :                :                     {
 1613 tgl@sss.pgh.pa.us         271   [ +  -  +  - ]:           1423 :                         if (!pgHavePendingResult(conn))
                                272                 :                :                         {
 8007                           273                 :           1423 :                             conn->result = PQmakeEmptyPGresult(conn,
                                274                 :                :                                                                PGRES_COMMAND_OK);
 7770 neilc@samurai.com         275         [ -  + ]:           1423 :                             if (!conn->result)
                                276                 :                :                             {
 1405 peter@eisentraut.org      277                 :UBC           0 :                                 libpq_append_conn_error(conn, "out of memory");
 4093 heikki.linnakangas@i      278                 :              0 :                                 pqSaveErrorResult(conn);
                                279                 :                :                             }
                                280                 :                :                         }
 8007 tgl@sss.pgh.pa.us         281                 :CBC        1423 :                         conn->asyncStatus = PGASYNC_READY;
                                282                 :                :                     }
                                283                 :           4637 :                     break;
 1125 nathan@postgresql.or      284                 :          11938 :                 case PqMsg_BindComplete:
                                285                 :                :                     /* Nothing to do for this message type */
 1174 michael@paquier.xyz       286                 :          11938 :                     break;
 1125 nathan@postgresql.or      287                 :             21 :                 case PqMsg_CloseComplete:
                                288                 :                :                     /* If we're doing PQsendClose, we're done; else ignore */
 1174 michael@paquier.xyz       289         [ +  - ]:             21 :                     if (conn->cmd_queue_head &&
                                290         [ +  - ]:             21 :                         conn->cmd_queue_head->queryclass == PGQUERY_CLOSE)
                                291                 :                :                     {
                                292   [ +  -  +  - ]:             21 :                         if (!pgHavePendingResult(conn))
                                293                 :                :                         {
                                294                 :             21 :                             conn->result = PQmakeEmptyPGresult(conn,
                                295                 :                :                                                                PGRES_COMMAND_OK);
                                296         [ -  + ]:             21 :                             if (!conn->result)
                                297                 :                :                             {
 1174 michael@paquier.xyz       298                 :UBC           0 :                                 libpq_append_conn_error(conn, "out of memory");
                                299                 :              0 :                                 pqSaveErrorResult(conn);
                                300                 :                :                             }
                                301                 :                :                         }
 1174 michael@paquier.xyz       302                 :CBC          21 :                         conn->asyncStatus = PGASYNC_READY;
                                303                 :                :                     }
 8492 tgl@sss.pgh.pa.us         304                 :             21 :                     break;
 1125 nathan@postgresql.or      305                 :         244613 :                 case PqMsg_ParameterStatus:
 8505 tgl@sss.pgh.pa.us         306         [ -  + ]:         244613 :                     if (getParameterStatus(conn))
 8505 tgl@sss.pgh.pa.us         307                 :UBC           0 :                         return;
 8505 tgl@sss.pgh.pa.us         308                 :CBC      244613 :                     break;
 1125 nathan@postgresql.or      309                 :          15707 :                 case PqMsg_BackendKeyData:
                                310                 :                : 
                                311                 :                :                     /*
                                312                 :                :                      * This is expected only during backend startup, but it's
                                313                 :                :                      * just as easy to handle it as part of the main loop.
                                314                 :                :                      * Save the data and continue processing.
                                315                 :                :                      */
  536 heikki.linnakangas@i      316         [ -  + ]:          15707 :                     if (getBackendKeyData(conn, msgLength))
 8505 tgl@sss.pgh.pa.us         317                 :UBC           0 :                         return;
 8505 tgl@sss.pgh.pa.us         318                 :CBC       15707 :                     break;
 1125 nathan@postgresql.or      319                 :         203118 :                 case PqMsg_RowDescription:
 1675 tgl@sss.pgh.pa.us         320         [ +  - ]:         203118 :                     if (conn->error_result ||
                                321         [ +  + ]:         203118 :                         (conn->result != NULL &&
                                322         [ -  + ]:             50 :                          conn->result->resultStatus == PGRES_FATAL_ERROR))
                                323                 :                :                     {
                                324                 :                :                         /*
                                325                 :                :                          * We've already choked for some reason.  Just discard
                                326                 :                :                          * the data till we get to the end of the query.
                                327                 :                :                          */
 3933 heikki.linnakangas@i      328                 :UBC           0 :                         conn->inCursor += msgLength;
                                329                 :                :                     }
 3933 heikki.linnakangas@i      330         [ +  + ]:CBC      203118 :                     else if (conn->result == NULL ||
 2015 alvherre@alvh.no-ip.      331         [ +  - ]:             50 :                              (conn->cmd_queue_head &&
                                332         [ +  - ]:             50 :                               conn->cmd_queue_head->queryclass == PGQUERY_DESCRIBE))
                                333                 :                :                     {
                                334                 :                :                         /* First 'T' in a query sequence */
 5282 tgl@sss.pgh.pa.us         335         [ -  + ]:         203118 :                         if (getRowDescriptions(conn, msgLength))
 8505 tgl@sss.pgh.pa.us         336                 :UBC           0 :                             return;
                                337                 :                :                     }
                                338                 :                :                     else
                                339                 :                :                     {
                                340                 :                :                         /*
                                341                 :                :                          * A new 'T' message is treated as the start of
                                342                 :                :                          * another PGresult.  (It is not clear that this is
                                343                 :                :                          * really possible with the current backend.) We stop
                                344                 :                :                          * parsing until the application accepts the current
                                345                 :                :                          * result.
                                346                 :                :                          */
                                347                 :              0 :                         conn->asyncStatus = PGASYNC_READY;
                                348                 :              0 :                         return;
                                349                 :                :                     }
 8505 tgl@sss.pgh.pa.us         350                 :CBC      203118 :                     break;
 1125 nathan@postgresql.or      351                 :           5195 :                 case PqMsg_NoData:
                                352                 :                : 
                                353                 :                :                     /*
                                354                 :                :                      * NoData indicates that we will not be seeing a
                                355                 :                :                      * RowDescription message because the statement or portal
                                356                 :                :                      * inquired about doesn't return rows.
                                357                 :                :                      *
                                358                 :                :                      * If we're doing a Describe, we have to pass something
                                359                 :                :                      * back to the client, so set up a COMMAND_OK result,
                                360                 :                :                      * instead of PGRES_TUPLES_OK.  Otherwise we can just
                                361                 :                :                      * ignore this message.
                                362                 :                :                      */
 2015 alvherre@alvh.no-ip.      363         [ +  - ]:           5195 :                     if (conn->cmd_queue_head &&
                                364         [ +  + ]:           5195 :                         conn->cmd_queue_head->queryclass == PGQUERY_DESCRIBE)
                                365                 :                :                     {
 1613 tgl@sss.pgh.pa.us         366   [ -  +  -  - ]:              8 :                         if (!pgHavePendingResult(conn))
                                367                 :                :                         {
 6463 tgl@sss.pgh.pa.us         368                 :UBC           0 :                             conn->result = PQmakeEmptyPGresult(conn,
                                369                 :                :                                                                PGRES_COMMAND_OK);
                                370         [ #  # ]:              0 :                             if (!conn->result)
                                371                 :                :                             {
 1405 peter@eisentraut.org      372                 :              0 :                                 libpq_append_conn_error(conn, "out of memory");
 4093 heikki.linnakangas@i      373                 :              0 :                                 pqSaveErrorResult(conn);
                                374                 :                :                             }
                                375                 :                :                         }
 7338 tgl@sss.pgh.pa.us         376                 :CBC           8 :                         conn->asyncStatus = PGASYNC_READY;
                                377                 :                :                     }
                                378                 :           5195 :                     break;
 1125 nathan@postgresql.or      379                 :             58 :                 case PqMsg_ParameterDescription:
 3933 heikki.linnakangas@i      380         [ -  + ]:             58 :                     if (getParamDescriptions(conn, msgLength))
 7338 tgl@sss.pgh.pa.us         381                 :UBC           0 :                         return;
 2019 tgl@sss.pgh.pa.us         382                 :CBC          58 :                     break;
 1125 nathan@postgresql.or      383                 :        3905895 :                 case PqMsg_DataRow:
 8505 tgl@sss.pgh.pa.us         384         [ +  - ]:        3905895 :                     if (conn->result != NULL &&
  897                           385         [ +  + ]:        3905895 :                         (conn->result->resultStatus == PGRES_TUPLES_OK ||
                                386         [ +  - ]:            123 :                          conn->result->resultStatus == PGRES_TUPLES_CHUNK))
                                387                 :                :                     {
                                388                 :                :                         /* Read another tuple of a normal query response */
 8505                           389         [ -  + ]:        3905895 :                         if (getAnotherTuple(conn, msgLength))
 8505 tgl@sss.pgh.pa.us         390                 :UBC           0 :                             return;
                                391                 :                :                     }
 1675                           392         [ #  # ]:              0 :                     else if (conn->error_result ||
                                393         [ #  # ]:              0 :                              (conn->result != NULL &&
                                394         [ #  # ]:              0 :                               conn->result->resultStatus == PGRES_FATAL_ERROR))
                                395                 :                :                     {
                                396                 :                :                         /*
                                397                 :                :                          * We've already choked for some reason.  Just discard
                                398                 :                :                          * tuples till we get to the end of the query.
                                399                 :                :                          */
 8505                           400                 :              0 :                         conn->inCursor += msgLength;
                                401                 :                :                     }
                                402                 :                :                     else
                                403                 :                :                     {
                                404                 :                :                         /* Set up to report error at end of query */
 1405 peter@eisentraut.org      405                 :              0 :                         libpq_append_conn_error(conn, "server sent data (\"D\" message) without prior row description (\"T\" message)");
 8505 tgl@sss.pgh.pa.us         406                 :              0 :                         pqSaveErrorResult(conn);
                                407                 :                :                         /* Discard the unexpected message */
                                408                 :              0 :                         conn->inCursor += msgLength;
                                409                 :                :                     }
 8505 tgl@sss.pgh.pa.us         410                 :CBC     3905895 :                     break;
 1125 nathan@postgresql.or      411                 :            716 :                 case PqMsg_CopyInResponse:
 8492 tgl@sss.pgh.pa.us         412         [ -  + ]:            716 :                     if (getCopyStart(conn, PGRES_COPY_IN))
 8505 tgl@sss.pgh.pa.us         413                 :UBC           0 :                         return;
 8505 tgl@sss.pgh.pa.us         414                 :CBC         716 :                     conn->asyncStatus = PGASYNC_COPY_IN;
                                415                 :            716 :                     break;
 1125 nathan@postgresql.or      416                 :           5145 :                 case PqMsg_CopyOutResponse:
 8492 tgl@sss.pgh.pa.us         417         [ -  + ]:           5145 :                     if (getCopyStart(conn, PGRES_COPY_OUT))
 8505 tgl@sss.pgh.pa.us         418                 :UBC           0 :                         return;
 8505 tgl@sss.pgh.pa.us         419                 :CBC        5145 :                     conn->asyncStatus = PGASYNC_COPY_OUT;
                                420                 :           5145 :                     conn->copy_already_done = 0;
                                421                 :           5145 :                     break;
 1125 nathan@postgresql.or      422                 :            834 :                 case PqMsg_CopyBothResponse:
 5762 rhaas@postgresql.org      423         [ -  + ]:            834 :                     if (getCopyStart(conn, PGRES_COPY_BOTH))
 5762 rhaas@postgresql.org      424                 :UBC           0 :                         return;
 5762 rhaas@postgresql.org      425                 :CBC         834 :                     conn->asyncStatus = PGASYNC_COPY_BOTH;
                                426                 :            834 :                     conn->copy_already_done = 0;
                                427                 :            834 :                     break;
 1125 nathan@postgresql.or      428                 :              3 :                 case PqMsg_CopyData:
                                429                 :                : 
                                430                 :                :                     /*
                                431                 :                :                      * If we see Copy Data, just silently drop it.  This would
                                432                 :                :                      * only occur if application exits COPY OUT mode too
                                433                 :                :                      * early.
                                434                 :                :                      */
 8505 tgl@sss.pgh.pa.us         435                 :              3 :                     conn->inCursor += msgLength;
                                436                 :              3 :                     break;
 1125 nathan@postgresql.or      437                 :           5531 :                 case PqMsg_CopyDone:
                                438                 :                : 
                                439                 :                :                     /*
                                440                 :                :                      * If we see Copy Done, just silently drop it.  This is
                                441                 :                :                      * the normal case during PQendcopy.  We will keep
                                442                 :                :                      * swallowing data, expecting to see command-complete for
                                443                 :                :                      * the COPY command.
                                444                 :                :                      */
 8505 tgl@sss.pgh.pa.us         445                 :           5531 :                     break;
 8505 tgl@sss.pgh.pa.us         446                 :UBC           0 :                 default:
 1405 peter@eisentraut.org      447                 :              0 :                     libpq_append_conn_error(conn, "unexpected response from server; first received character was \"%c\"", id);
                                448                 :                :                     /* build an error result holding the error message */
 8505 tgl@sss.pgh.pa.us         449                 :              0 :                     pqSaveErrorResult(conn);
                                450                 :                :                     /* not sure if we will see more, so go to ready state */
                                451                 :              0 :                     conn->asyncStatus = PGASYNC_READY;
                                452                 :                :                     /* Discard the unexpected message */
                                453                 :              0 :                     conn->inCursor += msgLength;
                                454                 :              0 :                     break;
                                455                 :                :             }                   /* switch on protocol character */
                                456                 :                :         }
                                457                 :                :         /* Successfully consumed this message */
 8505 tgl@sss.pgh.pa.us         458         [ +  - ]:CBC     5263876 :         if (conn->inCursor == conn->inStart + 5 + msgLength)
                                459                 :                :         {
                                460                 :                :             /* Normal case: parsing agrees with specified length */
  765 alvherre@alvh.no-ip.      461                 :        5263876 :             pqParseDone(conn, conn->inCursor);
                                462                 :                :         }
  394 heikki.linnakangas@i      463   [ #  #  #  # ]:UBC           0 :         else if (conn->error_result && conn->status == CONNECTION_BAD)
                                464                 :                :         {
                                465                 :                :             /* The connection was abandoned and we already reported it */
                                466                 :              0 :             return;
                                467                 :                :         }
                                468                 :                :         else
                                469                 :                :         {
                                470                 :                :             /* Trouble --- report it */
 1405 peter@eisentraut.org      471                 :              0 :             libpq_append_conn_error(conn, "message contents do not agree with length in message type \"%c\"", id);
                                472                 :                :             /* build an error result holding the error message */
 8505 tgl@sss.pgh.pa.us         473                 :              0 :             pqSaveErrorResult(conn);
                                474                 :              0 :             conn->asyncStatus = PGASYNC_READY;
                                475                 :                :             /* trust the specified message length as what to skip */
                                476                 :              0 :             conn->inStart += 5 + msgLength;
                                477                 :                :         }
                                478                 :                :     }
                                479                 :                : }
                                480                 :                : 
                                481                 :                : /*
                                482                 :                :  * handleFatalError: clean up after a nonrecoverable error
                                483                 :                :  *
                                484                 :                :  * This is for errors where we need to abandon the connection.  The caller has
                                485                 :                :  * already saved the error message in conn->errorMessage.
                                486                 :                :  */
                                487                 :                : static void
  394 heikki.linnakangas@i      488                 :              0 : handleFatalError(PGconn *conn)
                                489                 :                : {
                                490                 :                :     /* build an error result holding the error message */
 8505 tgl@sss.pgh.pa.us         491                 :              0 :     pqSaveErrorResult(conn);
 2015 alvherre@alvh.no-ip.      492                 :              0 :     conn->asyncStatus = PGASYNC_READY;   /* drop out of PQgetResult wait loop */
                                493                 :                :     /* flush input data since we're giving up on processing it */
 3965 tgl@sss.pgh.pa.us         494                 :              0 :     pqDropConnection(conn, true);
 3378                           495                 :              0 :     conn->status = CONNECTION_BAD;   /* No more connection to backend */
 8505                           496                 :              0 : }
                                497                 :                : 
                                498                 :                : /*
                                499                 :                :  * handleSyncLoss: clean up after loss of message-boundary sync
                                500                 :                :  *
                                501                 :                :  * There isn't really a lot we can do here except abandon the connection.
                                502                 :                :  */
                                503                 :                : static void
  394 heikki.linnakangas@i      504                 :              0 : handleSyncLoss(PGconn *conn, char id, int msgLength)
                                505                 :                : {
                                506                 :              0 :     libpq_append_conn_error(conn, "lost synchronization with server: got message type \"%c\", length %d",
                                507                 :                :                             id, msgLength);
                                508                 :              0 :     handleFatalError(conn);
                                509                 :              0 : }
                                510                 :                : 
                                511                 :                : /*
                                512                 :                :  * parseInput subroutine to read a 'T' (row descriptions) message.
                                513                 :                :  * We'll build a new PGresult structure (unless called for a Describe
                                514                 :                :  * command for a prepared statement) containing the attribute data.
                                515                 :                :  * Returns: 0 if processed message successfully, EOF to suspend parsing
                                516                 :                :  * (the latter case is not actually used currently).
                                517                 :                :  */
                                518                 :                : static int
 5282 tgl@sss.pgh.pa.us         519                 :CBC      203118 : getRowDescriptions(PGconn *conn, int msgLength)
                                520                 :                : {
                                521                 :                :     PGresult   *result;
                                522                 :                :     int         nfields;
                                523                 :                :     const char *errmsg;
                                524                 :                :     int         i;
                                525                 :                : 
                                526                 :                :     /*
                                527                 :                :      * When doing Describe for a prepared statement, there'll already be a
                                528                 :                :      * PGresult created by getParamDescriptions, and we should fill data into
                                529                 :                :      * that.  Otherwise, create a new, empty PGresult.
                                530                 :                :      */
 2015 alvherre@alvh.no-ip.      531         [ +  - ]:         203118 :     if (!conn->cmd_queue_head ||
                                532         [ +  - ]:         203118 :         (conn->cmd_queue_head &&
                                533         [ +  + ]:         203118 :          conn->cmd_queue_head->queryclass == PGQUERY_DESCRIBE))
                                534                 :                :     {
 7338 tgl@sss.pgh.pa.us         535         [ +  + ]:             51 :         if (conn->result)
                                536                 :             50 :             result = conn->result;
                                537                 :                :         else
                                538                 :              1 :             result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
                                539                 :                :     }
                                540                 :                :     else
                                541                 :         203067 :         result = PQmakeEmptyPGresult(conn, PGRES_TUPLES_OK);
 7770 neilc@samurai.com         542         [ -  + ]:         203118 :     if (!result)
                                543                 :                :     {
 5282 tgl@sss.pgh.pa.us         544                 :UBC           0 :         errmsg = NULL;          /* means "out of memory", see below */
                                545                 :              0 :         goto advance_and_error;
                                546                 :                :     }
                                547                 :                : 
                                548                 :                :     /* parseInput already read the 'T' label and message length. */
                                549                 :                :     /* the next two bytes are the number of fields */
 8505 tgl@sss.pgh.pa.us         550         [ -  + ]:CBC      203118 :     if (pqGetInt(&(result->numAttributes), 2, conn))
                                551                 :                :     {
                                552                 :                :         /* We should not run out of data here, so complain */
 5282 tgl@sss.pgh.pa.us         553                 :UBC           0 :         errmsg = libpq_gettext("insufficient data in \"T\" message");
                                554                 :              0 :         goto advance_and_error;
                                555                 :                :     }
 8505 tgl@sss.pgh.pa.us         556                 :CBC      203118 :     nfields = result->numAttributes;
                                557                 :                : 
                                558                 :                :     /* allocate space for the attribute descriptors */
                                559         [ +  + ]:         203118 :     if (nfields > 0)
                                560                 :                :     {
                                561                 :         202888 :         result->attDescs = (PGresAttDesc *)
 3322 peter_e@gmx.net           562                 :         202888 :             pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
 7770 neilc@samurai.com         563         [ -  + ]:         202888 :         if (!result->attDescs)
                                564                 :                :         {
 5282 tgl@sss.pgh.pa.us         565                 :UBC           0 :             errmsg = NULL;      /* means "out of memory", see below */
                                566                 :              0 :             goto advance_and_error;
                                567                 :                :         }
 7770 neilc@samurai.com         568   [ +  -  +  -  :CBC     2644944 :         MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
                                     +  -  +  +  +  
                                                 + ]
                                569                 :                :     }
                                570                 :                : 
                                571                 :                :     /* result->binary is true only if ALL columns are binary */
 8492 tgl@sss.pgh.pa.us         572                 :         203118 :     result->binary = (nfields > 0) ? 1 : 0;
                                573                 :                : 
                                574                 :                :     /* get type info */
 8505                           575         [ +  + ]:         822202 :     for (i = 0; i < nfields; i++)
                                576                 :                :     {
                                577                 :                :         int         tableid;
                                578                 :                :         int         columnid;
                                579                 :                :         int         typid;
                                580                 :                :         int         typlen;
                                581                 :                :         int         atttypmod;
                                582                 :                :         int         format;
                                583                 :                : 
                                584   [ +  -  +  - ]:        1238168 :         if (pqGets(&conn->workBuffer, conn) ||
                                585         [ +  - ]:        1238168 :             pqGetInt(&tableid, 4, conn) ||
                                586         [ +  - ]:        1238168 :             pqGetInt(&columnid, 2, conn) ||
                                587         [ +  - ]:        1238168 :             pqGetInt(&typid, 4, conn) ||
                                588         [ +  - ]:        1238168 :             pqGetInt(&typlen, 2, conn) ||
                                589         [ -  + ]:        1238168 :             pqGetInt(&atttypmod, 4, conn) ||
                                590                 :         619084 :             pqGetInt(&format, 2, conn))
                                591                 :                :         {
                                592                 :                :             /* We should not run out of data here, so complain */
 5282 tgl@sss.pgh.pa.us         593                 :UBC           0 :             errmsg = libpq_gettext("insufficient data in \"T\" message");
                                594                 :              0 :             goto advance_and_error;
                                595                 :                :         }
                                596                 :                : 
                                597                 :                :         /*
                                598                 :                :          * Since pqGetInt treats 2-byte integers as unsigned, we need to
                                599                 :                :          * coerce these results to signed form.
                                600                 :                :          */
 8505 tgl@sss.pgh.pa.us         601                 :CBC      619084 :         columnid = (int) ((int16) columnid);
                                602                 :         619084 :         typlen = (int) ((int16) typlen);
                                603                 :         619084 :         format = (int) ((int16) format);
                                604                 :                : 
                                605                 :        1238168 :         result->attDescs[i].name = pqResultStrdup(result,
                                606                 :         619084 :                                                   conn->workBuffer.data);
 7770 neilc@samurai.com         607         [ -  + ]:         619084 :         if (!result->attDescs[i].name)
                                608                 :                :         {
 5282 tgl@sss.pgh.pa.us         609                 :UBC           0 :             errmsg = NULL;      /* means "out of memory", see below */
                                610                 :              0 :             goto advance_and_error;
                                611                 :                :         }
 8492 tgl@sss.pgh.pa.us         612                 :CBC      619084 :         result->attDescs[i].tableid = tableid;
                                613                 :         619084 :         result->attDescs[i].columnid = columnid;
                                614                 :         619084 :         result->attDescs[i].format = format;
 8505                           615                 :         619084 :         result->attDescs[i].typid = typid;
                                616                 :         619084 :         result->attDescs[i].typlen = typlen;
                                617                 :         619084 :         result->attDescs[i].atttypmod = atttypmod;
                                618                 :                : 
 8492                           619         [ +  + ]:         619084 :         if (format != 1)
                                620                 :         619033 :             result->binary = 0;
                                621                 :                :     }
                                622                 :                : 
                                623                 :                :     /* Success! */
 8505                           624                 :         203118 :     conn->result = result;
                                625                 :                : 
                                626                 :                :     /*
                                627                 :                :      * If we're doing a Describe, we're done, and ready to pass the result
                                628                 :                :      * back to the client.
                                629                 :                :      */
 2015 alvherre@alvh.no-ip.      630         [ +  - ]:         203118 :     if ((!conn->cmd_queue_head) ||
                                631         [ +  - ]:         203118 :         (conn->cmd_queue_head &&
                                632         [ +  + ]:         203118 :          conn->cmd_queue_head->queryclass == PGQUERY_DESCRIBE))
                                633                 :                :     {
 5282 tgl@sss.pgh.pa.us         634                 :             51 :         conn->asyncStatus = PGASYNC_READY;
                                635                 :             51 :         return 0;
                                636                 :                :     }
                                637                 :                : 
                                638                 :                :     /*
                                639                 :                :      * We could perform additional setup for the new result set here, but for
                                640                 :                :      * now there's nothing else to do.
                                641                 :                :      */
                                642                 :                : 
                                643                 :                :     /* And we're done. */
 5162                           644                 :         203067 :     return 0;
                                645                 :                : 
 5282 tgl@sss.pgh.pa.us         646                 :UBC           0 : advance_and_error:
                                647                 :                :     /* Discard unsaved result, if any */
                                648   [ #  #  #  # ]:              0 :     if (result && result != conn->result)
 7338                           649                 :              0 :         PQclear(result);
                                650                 :                : 
                                651                 :                :     /*
                                652                 :                :      * Replace partially constructed result with an error result. First
                                653                 :                :      * discard the old result to try to win back some memory.
                                654                 :                :      */
 5282                           655                 :              0 :     pqClearAsyncResult(conn);
                                656                 :                : 
                                657                 :                :     /*
                                658                 :                :      * If preceding code didn't provide an error message, assume "out of
                                659                 :                :      * memory" was meant.  The advantage of having this special case is that
                                660                 :                :      * freeing the old result first greatly improves the odds that gettext()
                                661                 :                :      * will succeed in providing a translation.
                                662                 :                :      */
                                663         [ #  # ]:              0 :     if (!errmsg)
                                664                 :              0 :         errmsg = libpq_gettext("out of memory for query result");
                                665                 :                : 
 2078                           666                 :              0 :     appendPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
 5282                           667                 :              0 :     pqSaveErrorResult(conn);
                                668                 :                : 
                                669                 :                :     /*
                                670                 :                :      * Show the message as fully consumed, else pqParseInput3 will overwrite
                                671                 :                :      * our error with a complaint about that.
                                672                 :                :      */
 2019                           673                 :              0 :     conn->inCursor = conn->inStart + 5 + msgLength;
                                674                 :                : 
                                675                 :                :     /*
                                676                 :                :      * Return zero to allow input parsing to continue.  Subsequent "D"
                                677                 :                :      * messages will be ignored until we get to end of data, since an error
                                678                 :                :      * result is already set up.
                                679                 :                :      */
 5282                           680                 :              0 :     return 0;
                                681                 :                : }
                                682                 :                : 
                                683                 :                : /*
                                684                 :                :  * parseInput subroutine to read a 't' (ParameterDescription) message.
                                685                 :                :  * We'll build a new PGresult structure containing the parameter data.
                                686                 :                :  * Returns: 0 if processed message successfully, EOF to suspend parsing
                                687                 :                :  * (the latter case is not actually used currently).
                                688                 :                :  */
                                689                 :                : static int
 3933 heikki.linnakangas@i      690                 :CBC          58 : getParamDescriptions(PGconn *conn, int msgLength)
                                691                 :                : {
                                692                 :                :     PGresult   *result;
 3824 tgl@sss.pgh.pa.us         693                 :             58 :     const char *errmsg = NULL;  /* means "out of memory", see below */
                                694                 :                :     int         nparams;
                                695                 :                :     int         i;
                                696                 :                : 
 7338                           697                 :             58 :     result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
                                698         [ -  + ]:             58 :     if (!result)
 3933 heikki.linnakangas@i      699                 :UBC           0 :         goto advance_and_error;
                                700                 :                : 
                                701                 :                :     /* parseInput already read the 't' label and message length. */
                                702                 :                :     /* the next two bytes are the number of parameters */
 7338 tgl@sss.pgh.pa.us         703         [ -  + ]:CBC          58 :     if (pqGetInt(&(result->numParameters), 2, conn))
 3933 heikki.linnakangas@i      704                 :UBC           0 :         goto not_enough_data;
 7338 tgl@sss.pgh.pa.us         705                 :CBC          58 :     nparams = result->numParameters;
                                706                 :                : 
                                707                 :                :     /* allocate space for the parameter descriptors */
                                708         [ +  + ]:             58 :     if (nparams > 0)
                                709                 :                :     {
                                710                 :              5 :         result->paramDescs = (PGresParamDesc *)
 3322 peter_e@gmx.net           711                 :              5 :             pqResultAlloc(result, nparams * sizeof(PGresParamDesc), true);
 7338 tgl@sss.pgh.pa.us         712         [ -  + ]:              5 :         if (!result->paramDescs)
 3933 heikki.linnakangas@i      713                 :UBC           0 :             goto advance_and_error;
 7338 tgl@sss.pgh.pa.us         714   [ +  -  +  +  :CBC           9 :         MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
                                     +  -  +  -  +  
                                                 + ]
                                715                 :                :     }
                                716                 :                : 
                                717                 :                :     /* get parameter info */
                                718         [ +  + ]:             67 :     for (i = 0; i < nparams; i++)
                                719                 :                :     {
                                720                 :                :         int         typid;
                                721                 :                : 
                                722         [ -  + ]:              9 :         if (pqGetInt(&typid, 4, conn))
 3933 heikki.linnakangas@i      723                 :UBC           0 :             goto not_enough_data;
 7338 tgl@sss.pgh.pa.us         724                 :CBC           9 :         result->paramDescs[i].typid = typid;
                                725                 :                :     }
                                726                 :                : 
                                727                 :                :     /* Success! */
                                728                 :             58 :     conn->result = result;
                                729                 :                : 
                                730                 :             58 :     return 0;
                                731                 :                : 
 3933 heikki.linnakangas@i      732                 :UBC           0 : not_enough_data:
 2019 tgl@sss.pgh.pa.us         733                 :              0 :     errmsg = libpq_gettext("insufficient data in \"t\" message");
                                734                 :                : 
 3933 heikki.linnakangas@i      735                 :              0 : advance_and_error:
                                736                 :                :     /* Discard unsaved result, if any */
                                737   [ #  #  #  # ]:              0 :     if (result && result != conn->result)
                                738                 :              0 :         PQclear(result);
                                739                 :                : 
                                740                 :                :     /*
                                741                 :                :      * Replace partially constructed result with an error result. First
                                742                 :                :      * discard the old result to try to win back some memory.
                                743                 :                :      */
                                744                 :              0 :     pqClearAsyncResult(conn);
                                745                 :                : 
                                746                 :                :     /*
                                747                 :                :      * If preceding code didn't provide an error message, assume "out of
                                748                 :                :      * memory" was meant.  The advantage of having this special case is that
                                749                 :                :      * freeing the old result first greatly improves the odds that gettext()
                                750                 :                :      * will succeed in providing a translation.
                                751                 :                :      */
                                752         [ #  # ]:              0 :     if (!errmsg)
                                753                 :              0 :         errmsg = libpq_gettext("out of memory");
 2078 tgl@sss.pgh.pa.us         754                 :              0 :     appendPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
 3933 heikki.linnakangas@i      755                 :              0 :     pqSaveErrorResult(conn);
                                756                 :                : 
                                757                 :                :     /*
                                758                 :                :      * Show the message as fully consumed, else pqParseInput3 will overwrite
                                759                 :                :      * our error with a complaint about that.
                                760                 :                :      */
 2019 tgl@sss.pgh.pa.us         761                 :              0 :     conn->inCursor = conn->inStart + 5 + msgLength;
                                762                 :                : 
                                763                 :                :     /*
                                764                 :                :      * Return zero to allow input parsing to continue.  Essentially, we've
                                765                 :                :      * replaced the COMMAND_OK result with an error result, but since this
                                766                 :                :      * doesn't affect the protocol state, it's fine.
                                767                 :                :      */
 3933 heikki.linnakangas@i      768                 :              0 :     return 0;
                                769                 :                : }
                                770                 :                : 
                                771                 :                : /*
                                772                 :                :  * parseInput subroutine to read a 'D' (row data) message.
                                773                 :                :  * We fill rowbuf with column pointers and then call the row processor.
                                774                 :                :  * Returns: 0 if processed message successfully, EOF to suspend parsing
                                775                 :                :  * (the latter case is not actually used currently).
                                776                 :                :  */
                                777                 :                : static int
 8505 tgl@sss.pgh.pa.us         778                 :CBC     3905895 : getAnotherTuple(PGconn *conn, int msgLength)
                                779                 :                : {
                                780                 :        3905895 :     PGresult   *result = conn->result;
                                781                 :        3905895 :     int         nfields = result->numAttributes;
                                782                 :                :     const char *errmsg;
                                783                 :                :     PGdataValue *rowbuf;
                                784                 :                :     int         tupnfields;     /* # fields from tuple */
                                785                 :                :     int         vlen;           /* length of the current field value */
                                786                 :                :     int         i;
                                787                 :                : 
                                788                 :                :     /* Get the field count and make sure it's what we expect */
                                789         [ -  + ]:        3905895 :     if (pqGetInt(&tupnfields, 2, conn))
                                790                 :                :     {
                                791                 :                :         /* We should not run out of data here, so complain */
 5282 tgl@sss.pgh.pa.us         792                 :UBC           0 :         errmsg = libpq_gettext("insufficient data in \"D\" message");
                                793                 :              0 :         goto advance_and_error;
                                794                 :                :     }
                                795                 :                : 
 8505 tgl@sss.pgh.pa.us         796         [ -  + ]:CBC     3905895 :     if (tupnfields != nfields)
                                797                 :                :     {
 5282 tgl@sss.pgh.pa.us         798                 :UBC           0 :         errmsg = libpq_gettext("unexpected field count in \"D\" message");
                                799                 :              0 :         goto advance_and_error;
                                800                 :                :     }
                                801                 :                : 
                                802                 :                :     /* Resize row buffer if needed */
 5282 tgl@sss.pgh.pa.us         803                 :CBC     3905895 :     rowbuf = conn->rowBuf;
                                804         [ +  + ]:        3905895 :     if (nfields > conn->rowBufLen)
                                805                 :                :     {
                                806                 :            215 :         rowbuf = (PGdataValue *) realloc(rowbuf,
                                807                 :                :                                          nfields * sizeof(PGdataValue));
                                808         [ -  + ]:            215 :         if (!rowbuf)
                                809                 :                :         {
 5282 tgl@sss.pgh.pa.us         810                 :UBC           0 :             errmsg = NULL;      /* means "out of memory", see below */
                                811                 :              0 :             goto advance_and_error;
                                812                 :                :         }
 5282 tgl@sss.pgh.pa.us         813                 :CBC         215 :         conn->rowBuf = rowbuf;
                                814                 :            215 :         conn->rowBufLen = nfields;
                                815                 :                :     }
                                816                 :                : 
                                817                 :                :     /* Scan the fields */
 8505                           818         [ +  + ]:       23592030 :     for (i = 0; i < nfields; i++)
                                819                 :                :     {
                                820                 :                :         /* get the value length */
                                821         [ -  + ]:       19686135 :         if (pqGetInt(&vlen, 4, conn))
                                822                 :                :         {
                                823                 :                :             /* We should not run out of data here, so complain */
 5282 tgl@sss.pgh.pa.us         824                 :UBC           0 :             errmsg = libpq_gettext("insufficient data in \"D\" message");
                                825                 :              0 :             goto advance_and_error;
                                826                 :                :         }
 5282 tgl@sss.pgh.pa.us         827                 :CBC    19686135 :         rowbuf[i].len = vlen;
                                828                 :                : 
                                829                 :                :         /*
                                830                 :                :          * rowbuf[i].value always points to the next address in the data
                                831                 :                :          * buffer even if the value is NULL.  This allows row processors to
                                832                 :                :          * estimate data sizes more easily.
                                833                 :                :          */
                                834                 :       19686135 :         rowbuf[i].value = conn->inBuffer + conn->inCursor;
                                835                 :                : 
                                836                 :                :         /* Skip over the data value */
 8505                           837         [ +  + ]:       19686135 :         if (vlen > 0)
                                838                 :                :         {
 5282                           839         [ -  + ]:       18393352 :             if (pqSkipnchar(vlen, conn))
                                840                 :                :             {
                                841                 :                :                 /* We should not run out of data here, so complain */
 5282 tgl@sss.pgh.pa.us         842                 :UBC           0 :                 errmsg = libpq_gettext("insufficient data in \"D\" message");
                                843                 :              0 :                 goto advance_and_error;
                                844                 :                :             }
                                845                 :                :         }
                                846                 :                :     }
                                847                 :                : 
                                848                 :                :     /* Process the collected row */
 5282 tgl@sss.pgh.pa.us         849                 :CBC     3905895 :     errmsg = NULL;
 5162                           850         [ +  - ]:        3905895 :     if (pqRowProcessor(conn, &errmsg))
                                851                 :        3905895 :         return 0;               /* normal, successful exit */
                                852                 :                : 
                                853                 :                :     /* pqRowProcessor failed, fall through to report it */
                                854                 :                : 
 5282 tgl@sss.pgh.pa.us         855                 :UBC           0 : advance_and_error:
                                856                 :                : 
                                857                 :                :     /*
                                858                 :                :      * Replace partially constructed result with an error result. First
                                859                 :                :      * discard the old result to try to win back some memory.
                                860                 :                :      */
 8505                           861                 :              0 :     pqClearAsyncResult(conn);
                                862                 :                : 
                                863                 :                :     /*
                                864                 :                :      * If preceding code didn't provide an error message, assume "out of
                                865                 :                :      * memory" was meant.  The advantage of having this special case is that
                                866                 :                :      * freeing the old result first greatly improves the odds that gettext()
                                867                 :                :      * will succeed in providing a translation.
                                868                 :                :      */
 5282                           869         [ #  # ]:              0 :     if (!errmsg)
                                870                 :              0 :         errmsg = libpq_gettext("out of memory for query result");
                                871                 :                : 
 2078                           872                 :              0 :     appendPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
 8505                           873                 :              0 :     pqSaveErrorResult(conn);
                                874                 :                : 
                                875                 :                :     /*
                                876                 :                :      * Show the message as fully consumed, else pqParseInput3 will overwrite
                                877                 :                :      * our error with a complaint about that.
                                878                 :                :      */
 2019                           879                 :              0 :     conn->inCursor = conn->inStart + 5 + msgLength;
                                880                 :                : 
                                881                 :                :     /*
                                882                 :                :      * Return zero to allow input parsing to continue.  Subsequent "D"
                                883                 :                :      * messages will be ignored until we get to end of data, since an error
                                884                 :                :      * result is already set up.
                                885                 :                :      */
 8505                           886                 :              0 :     return 0;
                                887                 :                : }
                                888                 :                : 
                                889                 :                : 
                                890                 :                : /*
                                891                 :                :  * Attempt to read an Error or Notice response message.
                                892                 :                :  * This is possible in several places, so we break it out as a subroutine.
                                893                 :                :  *
                                894                 :                :  * Entry: 'E' or 'N' message type and length have already been consumed.
                                895                 :                :  * Exit: returns 0 if successfully consumed message.
                                896                 :                :  *       returns EOF if not enough data.
                                897                 :                :  */
                                898                 :                : int
 8505 tgl@sss.pgh.pa.us         899                 :CBC       47644 : pqGetErrorNotice3(PGconn *conn, bool isError)
                                900                 :                : {
 7770 neilc@samurai.com         901                 :          47644 :     PGresult   *res = NULL;
 3822 tgl@sss.pgh.pa.us         902                 :          47644 :     bool        have_position = false;
                                903                 :                :     PQExpBufferData workBuf;
                                904                 :                :     char        id;
                                905                 :                : 
                                906                 :                :     /* If in pipeline mode, set error indicator for it */
 2015 alvherre@alvh.no-ip.      907   [ +  +  +  + ]:          47644 :     if (isError && conn->pipelineStatus != PQ_PIPELINE_OFF)
                                908                 :             98 :         conn->pipelineStatus = PQ_PIPELINE_ABORTED;
                                909                 :                : 
                                910                 :                :     /*
                                911                 :                :      * If this is an error message, pre-emptively clear any incomplete query
                                912                 :                :      * result we may have.  We'd just throw it away below anyway, and
                                913                 :                :      * releasing it before collecting the error might avoid out-of-memory.
                                914                 :                :      */
 3082 tgl@sss.pgh.pa.us         915         [ +  + ]:          47644 :     if (isError)
                                916                 :          31423 :         pqClearAsyncResult(conn);
                                917                 :                : 
                                918                 :                :     /*
                                919                 :                :      * Since the fields might be pretty long, we create a temporary
                                920                 :                :      * PQExpBuffer rather than using conn->workBuffer.  workBuffer is intended
                                921                 :                :      * for stuff that is expected to be short.  We shouldn't use
                                922                 :                :      * conn->errorMessage either, since this might be only a notice.
                                923                 :                :      */
 8505                           924                 :          47644 :     initPQExpBuffer(&workBuf);
                                925                 :                : 
                                926                 :                :     /*
                                927                 :                :      * Make a PGresult to hold the accumulated fields.  We temporarily lie
                                928                 :                :      * about the result status, so that PQmakeEmptyPGresult doesn't uselessly
                                929                 :                :      * copy conn->errorMessage.
                                930                 :                :      *
                                931                 :                :      * NB: This allocation can fail, if you run out of memory. The rest of the
                                932                 :                :      * function handles that gracefully, and we still try to set the error
                                933                 :                :      * message as the connection's error message.
                                934                 :                :      */
 7770 neilc@samurai.com         935                 :          47644 :     res = PQmakeEmptyPGresult(conn, PGRES_EMPTY_QUERY);
 4093 heikki.linnakangas@i      936         [ +  - ]:          47644 :     if (res)
                                937         [ +  + ]:          47644 :         res->resultStatus = isError ? PGRES_FATAL_ERROR : PGRES_NONFATAL_ERROR;
                                938                 :                : 
                                939                 :                :     /*
                                940                 :                :      * Read the fields and save into res.
                                941                 :                :      *
                                942                 :                :      * While at it, save the SQLSTATE in conn->last_sqlstate, and note whether
                                943                 :                :      * we saw a PG_DIAG_STATEMENT_POSITION field.
                                944                 :                :      */
                                945                 :                :     for (;;)
                                946                 :                :     {
 8505 tgl@sss.pgh.pa.us         947         [ -  + ]:         421082 :         if (pqGetc(&id, conn))
 8505 tgl@sss.pgh.pa.us         948                 :UBC           0 :             goto fail;
 8505 tgl@sss.pgh.pa.us         949         [ +  + ]:CBC      421082 :         if (id == '\0')
                                950                 :          47644 :             break;              /* terminator found */
                                951         [ -  + ]:         373438 :         if (pqGets(&workBuf, conn))
 8505 tgl@sss.pgh.pa.us         952                 :UBC           0 :             goto fail;
 8492 tgl@sss.pgh.pa.us         953                 :CBC      373438 :         pqSaveMessageField(res, id, workBuf.data);
 3822                           954         [ +  + ]:         373438 :         if (id == PG_DIAG_SQLSTATE)
                                955                 :          47644 :             strlcpy(conn->last_sqlstate, workBuf.data,
                                956                 :                :                     sizeof(conn->last_sqlstate));
                                957         [ +  + ]:         325794 :         else if (id == PG_DIAG_STATEMENT_POSITION)
                                958                 :           7803 :             have_position = true;
                                959                 :                :     }
                                960                 :                : 
                                961                 :                :     /*
                                962                 :                :      * Save the active query text, if any, into res as well; but only if we
                                963                 :                :      * might need it for an error cursor display, which is only true if there
                                964                 :                :      * is a PG_DIAG_STATEMENT_POSITION field.
                                965                 :                :      */
 2015 alvherre@alvh.no-ip.      966   [ +  +  +  -  :          47644 :     if (have_position && res && conn->cmd_queue_head && conn->cmd_queue_head->query)
                                        +  -  +  - ]
                                967                 :           7803 :         res->errQuery = pqResultStrdup(res, conn->cmd_queue_head->query);
                                968                 :                : 
                                969                 :                :     /*
                                970                 :                :      * Now build the "overall" error message for PQresultErrorMessage.
                                971                 :                :      */
 8505 tgl@sss.pgh.pa.us         972                 :          47644 :     resetPQExpBuffer(&workBuf);
 3822                           973                 :          47644 :     pqBuildErrorMessage3(&workBuf, res, conn->verbosity, conn->show_context);
                                974                 :                : 
                                975                 :                :     /*
                                976                 :                :      * Either save error as current async result, or just emit the notice.
                                977                 :                :      */
                                978         [ +  + ]:          47644 :     if (isError)
                                979                 :                :     {
 3082                           980                 :          31423 :         pqClearAsyncResult(conn);   /* redundant, but be safe */
 1675                           981         [ +  - ]:          31423 :         if (res)
                                982                 :                :         {
                                983                 :          31423 :             pqSetResultError(res, &workBuf, 0);
                                984                 :          31423 :             conn->result = res;
                                985                 :                :         }
                                986                 :                :         else
                                987                 :                :         {
                                988                 :                :             /* Fall back to using the internal-error processing paths */
 1675 tgl@sss.pgh.pa.us         989                 :UBC           0 :             conn->error_result = true;
                                990                 :                :         }
                                991                 :                : 
 3822 tgl@sss.pgh.pa.us         992         [ -  + ]:CBC       31423 :         if (PQExpBufferDataBroken(workBuf))
 1405 peter@eisentraut.org      993                 :UBC           0 :             libpq_append_conn_error(conn, "out of memory");
                                994                 :                :         else
 3822 tgl@sss.pgh.pa.us         995                 :CBC       31423 :             appendPQExpBufferStr(&conn->errorMessage, workBuf.data);
                                996                 :                :     }
                                997                 :                :     else
                                998                 :                :     {
                                999                 :                :         /* if we couldn't allocate the result set, just discard the NOTICE */
                               1000         [ +  - ]:          16221 :         if (res)
                               1001                 :                :         {
                               1002                 :                :             /*
                               1003                 :                :              * We can cheat a little here and not copy the message.  But if we
                               1004                 :                :              * were unlucky enough to run out of memory while filling workBuf,
                               1005                 :                :              * insert "out of memory", as in pqSetResultError.
                               1006                 :                :              */
 1879                          1007         [ -  + ]:          16221 :             if (PQExpBufferDataBroken(workBuf))
 1879 tgl@sss.pgh.pa.us        1008                 :UBC           0 :                 res->errMsg = libpq_gettext("out of memory\n");
                               1009                 :                :             else
 1879 tgl@sss.pgh.pa.us        1010                 :CBC       16221 :                 res->errMsg = workBuf.data;
 3822                          1011         [ +  - ]:          16221 :             if (res->noticeHooks.noticeRec != NULL)
 3300 peter_e@gmx.net          1012                 :          16221 :                 res->noticeHooks.noticeRec(res->noticeHooks.noticeRecArg, res);
 3822 tgl@sss.pgh.pa.us        1013                 :          16221 :             PQclear(res);
                               1014                 :                :         }
                               1015                 :                :     }
                               1016                 :                : 
                               1017                 :          47644 :     termPQExpBuffer(&workBuf);
                               1018                 :          47644 :     return 0;
                               1019                 :                : 
 3822 tgl@sss.pgh.pa.us        1020                 :UBC           0 : fail:
                               1021                 :              0 :     PQclear(res);
                               1022                 :              0 :     termPQExpBuffer(&workBuf);
                               1023                 :              0 :     return EOF;
                               1024                 :                : }
                               1025                 :                : 
                               1026                 :                : /*
                               1027                 :                :  * Construct an error message from the fields in the given PGresult,
                               1028                 :                :  * appending it to the contents of "msg".
                               1029                 :                :  */
                               1030                 :                : void
 3822 tgl@sss.pgh.pa.us        1031                 :CBC       47647 : pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res,
                               1032                 :                :                      PGVerbosity verbosity, PGContextVisibility show_context)
                               1033                 :                : {
                               1034                 :                :     const char *val;
                               1035                 :          47647 :     const char *querytext = NULL;
                               1036                 :          47647 :     int         querypos = 0;
                               1037                 :                : 
                               1038                 :                :     /* If we couldn't allocate a PGresult, just say "out of memory" */
                               1039         [ -  + ]:          47647 :     if (res == NULL)
                               1040                 :                :     {
 2635 drowley@postgresql.o     1041                 :UBC           0 :         appendPQExpBufferStr(msg, libpq_gettext("out of memory\n"));
 3822 tgl@sss.pgh.pa.us        1042                 :              0 :         return;
                               1043                 :                :     }
                               1044                 :                : 
                               1045                 :                :     /*
                               1046                 :                :      * If we don't have any broken-down fields, just return the base message.
                               1047                 :                :      * This mainly applies if we're given a libpq-generated error result.
                               1048                 :                :      */
 3822 tgl@sss.pgh.pa.us        1049         [ -  + ]:CBC       47647 :     if (res->errFields == NULL)
                               1050                 :                :     {
 3822 tgl@sss.pgh.pa.us        1051   [ #  #  #  # ]:UBC           0 :         if (res->errMsg && res->errMsg[0])
                               1052                 :              0 :             appendPQExpBufferStr(msg, res->errMsg);
                               1053                 :                :         else
 2635 drowley@postgresql.o     1054                 :              0 :             appendPQExpBufferStr(msg, libpq_gettext("no error message available\n"));
 3822 tgl@sss.pgh.pa.us        1055                 :              0 :         return;
                               1056                 :                :     }
                               1057                 :                : 
                               1058                 :                :     /* Else build error message from relevant fields */
 8425 peter_e@gmx.net          1059                 :CBC       47647 :     val = PQresultErrorField(res, PG_DIAG_SEVERITY);
 8492 tgl@sss.pgh.pa.us        1060         [ +  - ]:          47647 :     if (val)
 3822                          1061                 :          47647 :         appendPQExpBuffer(msg, "%s:  ", val);
                               1062                 :                : 
 2726                          1063         [ +  + ]:          47647 :     if (verbosity == PQERRORS_SQLSTATE)
                               1064                 :                :     {
                               1065                 :                :         /*
                               1066                 :                :          * If we have a SQLSTATE, print that and nothing else.  If not (which
                               1067                 :                :          * shouldn't happen for server-generated errors, but might possibly
                               1068                 :                :          * happen for libpq-generated ones), fall back to TERSE format, as
                               1069                 :                :          * that seems better than printing nothing at all.
                               1070                 :                :          */
                               1071                 :            115 :         val = PQresultErrorField(res, PG_DIAG_SQLSTATE);
                               1072         [ +  - ]:            115 :         if (val)
                               1073                 :                :         {
                               1074                 :            115 :             appendPQExpBuffer(msg, "%s\n", val);
                               1075                 :            115 :             return;
                               1076                 :                :         }
 2726 tgl@sss.pgh.pa.us        1077                 :UBC           0 :         verbosity = PQERRORS_TERSE;
                               1078                 :                :     }
                               1079                 :                : 
 3822 tgl@sss.pgh.pa.us        1080         [ +  + ]:CBC       47532 :     if (verbosity == PQERRORS_VERBOSE)
                               1081                 :                :     {
                               1082                 :              3 :         val = PQresultErrorField(res, PG_DIAG_SQLSTATE);
                               1083         [ +  - ]:              3 :         if (val)
                               1084                 :              3 :             appendPQExpBuffer(msg, "%s: ", val);
                               1085                 :                :     }
 8425 peter_e@gmx.net          1086                 :          47532 :     val = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
 8492 tgl@sss.pgh.pa.us        1087         [ +  - ]:          47532 :     if (val)
 3822                          1088                 :          47532 :         appendPQExpBufferStr(msg, val);
 8425 peter_e@gmx.net          1089                 :          47532 :     val = PQresultErrorField(res, PG_DIAG_STATEMENT_POSITION);
 8492 tgl@sss.pgh.pa.us        1090         [ +  + ]:          47532 :     if (val)
                               1091                 :                :     {
 3822                          1092   [ +  +  +  - ]:           7802 :         if (verbosity != PQERRORS_TERSE && res->errQuery != NULL)
                               1093                 :                :         {
                               1094                 :                :             /* emit position as a syntax cursor display */
                               1095                 :           7798 :             querytext = res->errQuery;
 7495                          1096                 :           7798 :             querypos = atoi(val);
                               1097                 :                :         }
                               1098                 :                :         else
                               1099                 :                :         {
                               1100                 :                :             /* emit position as text addition to primary message */
                               1101                 :                :             /* translator: %s represents a digit string */
 3822                          1102                 :              4 :             appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
                               1103                 :                :                               val);
                               1104                 :                :         }
                               1105                 :                :     }
                               1106                 :                :     else
                               1107                 :                :     {
 8218                          1108                 :          39730 :         val = PQresultErrorField(res, PG_DIAG_INTERNAL_POSITION);
                               1109         [ +  + ]:          39730 :         if (val)
                               1110                 :                :         {
 7495                          1111                 :             57 :             querytext = PQresultErrorField(res, PG_DIAG_INTERNAL_QUERY);
 3822                          1112   [ +  -  +  - ]:             57 :             if (verbosity != PQERRORS_TERSE && querytext != NULL)
                               1113                 :                :             {
                               1114                 :                :                 /* emit position as a syntax cursor display */
 7495                          1115                 :             57 :                 querypos = atoi(val);
                               1116                 :                :             }
                               1117                 :                :             else
                               1118                 :                :             {
                               1119                 :                :                 /* emit position as text addition to primary message */
                               1120                 :                :                 /* translator: %s represents a digit string */
 3822 tgl@sss.pgh.pa.us        1121                 :UBC           0 :                 appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
                               1122                 :                :                                   val);
                               1123                 :                :             }
                               1124                 :                :         }
                               1125                 :                :     }
 3822 tgl@sss.pgh.pa.us        1126                 :CBC       47532 :     appendPQExpBufferChar(msg, '\n');
                               1127         [ +  + ]:          47532 :     if (verbosity != PQERRORS_TERSE)
                               1128                 :                :     {
 7495                          1129   [ +  +  +  - ]:          47211 :         if (querytext && querypos > 0)
 3822                          1130                 :           7855 :             reportErrorPosition(msg, querytext, querypos,
                               1131                 :           7855 :                                 res->client_encoding);
 8425 peter_e@gmx.net          1132                 :          47211 :         val = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
 8492 tgl@sss.pgh.pa.us        1133         [ +  + ]:          47211 :         if (val)
 3822                          1134                 :           8240 :             appendPQExpBuffer(msg, libpq_gettext("DETAIL:  %s\n"), val);
 8425 peter_e@gmx.net          1135                 :          47211 :         val = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
 8492 tgl@sss.pgh.pa.us        1136         [ +  + ]:          47211 :         if (val)
 3822                          1137                 :           3124 :             appendPQExpBuffer(msg, libpq_gettext("HINT:  %s\n"), val);
 8218                          1138                 :          47211 :         val = PQresultErrorField(res, PG_DIAG_INTERNAL_QUERY);
                               1139         [ +  + ]:          47211 :         if (val)
 3822                          1140                 :             57 :             appendPQExpBuffer(msg, libpq_gettext("QUERY:  %s\n"), val);
                               1141   [ +  +  +  + ]:          47211 :         if (show_context == PQSHOW_CONTEXT_ALWAYS ||
                               1142                 :          46996 :             (show_context == PQSHOW_CONTEXT_ERRORS &&
                               1143         [ +  + ]:          46996 :              res->resultStatus == PGRES_FATAL_ERROR))
                               1144                 :                :         {
 4033                          1145                 :          31287 :             val = PQresultErrorField(res, PG_DIAG_CONTEXT);
                               1146         [ +  + ]:          31287 :             if (val)
 3822                          1147                 :           1617 :                 appendPQExpBuffer(msg, libpq_gettext("CONTEXT:  %s\n"),
                               1148                 :                :                                   val);
                               1149                 :                :         }
                               1150                 :                :     }
                               1151         [ +  + ]:          47532 :     if (verbosity == PQERRORS_VERBOSE)
                               1152                 :                :     {
 4982                          1153                 :              3 :         val = PQresultErrorField(res, PG_DIAG_SCHEMA_NAME);
                               1154         [ -  + ]:              3 :         if (val)
 3822 tgl@sss.pgh.pa.us        1155                 :UBC           0 :             appendPQExpBuffer(msg,
 4982                          1156                 :              0 :                               libpq_gettext("SCHEMA NAME:  %s\n"), val);
 4982 tgl@sss.pgh.pa.us        1157                 :CBC           3 :         val = PQresultErrorField(res, PG_DIAG_TABLE_NAME);
                               1158         [ -  + ]:              3 :         if (val)
 3822 tgl@sss.pgh.pa.us        1159                 :UBC           0 :             appendPQExpBuffer(msg,
 4982                          1160                 :              0 :                               libpq_gettext("TABLE NAME:  %s\n"), val);
 4982 tgl@sss.pgh.pa.us        1161                 :CBC           3 :         val = PQresultErrorField(res, PG_DIAG_COLUMN_NAME);
                               1162         [ -  + ]:              3 :         if (val)
 3822 tgl@sss.pgh.pa.us        1163                 :UBC           0 :             appendPQExpBuffer(msg,
 4982                          1164                 :              0 :                               libpq_gettext("COLUMN NAME:  %s\n"), val);
 4982 tgl@sss.pgh.pa.us        1165                 :CBC           3 :         val = PQresultErrorField(res, PG_DIAG_DATATYPE_NAME);
                               1166         [ -  + ]:              3 :         if (val)
 3822 tgl@sss.pgh.pa.us        1167                 :UBC           0 :             appendPQExpBuffer(msg,
 4982                          1168                 :              0 :                               libpq_gettext("DATATYPE NAME:  %s\n"), val);
 4982 tgl@sss.pgh.pa.us        1169                 :CBC           3 :         val = PQresultErrorField(res, PG_DIAG_CONSTRAINT_NAME);
                               1170         [ -  + ]:              3 :         if (val)
 3822 tgl@sss.pgh.pa.us        1171                 :UBC           0 :             appendPQExpBuffer(msg,
 4982                          1172                 :              0 :                               libpq_gettext("CONSTRAINT NAME:  %s\n"), val);
                               1173                 :                :     }
 3822 tgl@sss.pgh.pa.us        1174         [ +  + ]:CBC       47532 :     if (verbosity == PQERRORS_VERBOSE)
                               1175                 :                :     {
                               1176                 :                :         const char *valf;
                               1177                 :                :         const char *vall;
                               1178                 :                : 
 8425 peter_e@gmx.net          1179                 :              3 :         valf = PQresultErrorField(res, PG_DIAG_SOURCE_FILE);
                               1180                 :              3 :         vall = PQresultErrorField(res, PG_DIAG_SOURCE_LINE);
                               1181                 :              3 :         val = PQresultErrorField(res, PG_DIAG_SOURCE_FUNCTION);
 8492 tgl@sss.pgh.pa.us        1182   [ -  +  -  -  :              3 :         if (val || valf || vall)
                                              -  - ]
                               1183                 :                :         {
 3822                          1184                 :              3 :             appendPQExpBufferStr(msg, libpq_gettext("LOCATION:  "));
 8492                          1185         [ +  - ]:              3 :             if (val)
 3822                          1186                 :              3 :                 appendPQExpBuffer(msg, libpq_gettext("%s, "), val);
 8492                          1187   [ +  -  +  - ]:              3 :             if (valf && vall)   /* unlikely we'd have just one */
 3822                          1188                 :              3 :                 appendPQExpBuffer(msg, libpq_gettext("%s:%s"),
                               1189                 :                :                                   valf, vall);
                               1190                 :              3 :             appendPQExpBufferChar(msg, '\n');
                               1191                 :                :         }
                               1192                 :                :     }
                               1193                 :                : }
                               1194                 :                : 
                               1195                 :                : /*
                               1196                 :                :  * Add an error-location display to the error message under construction.
                               1197                 :                :  *
                               1198                 :                :  * The cursor location is measured in logical characters; the query string
                               1199                 :                :  * is presumed to be in the specified encoding.
                               1200                 :                :  */
                               1201                 :                : static void
 7495                          1202                 :           7855 : reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding)
                               1203                 :                : {
                               1204                 :                : #define DISPLAY_SIZE    60      /* screen width limit, in screen cols */
                               1205                 :                : #define MIN_RIGHT_CUT   10      /* try to keep this far away from EOL */
                               1206                 :                : 
                               1207                 :                :     char       *wquery;
                               1208                 :                :     int         slen,
                               1209                 :                :                 cno,
                               1210                 :                :                 i,
                               1211                 :                :                *qidx,
                               1212                 :                :                *scridx,
                               1213                 :                :                 qoffset,
                               1214                 :                :                 scroffset,
                               1215                 :                :                 ibeg,
                               1216                 :                :                 iend,
                               1217                 :                :                 loc_line;
                               1218                 :                :     bool        mb_encoding,
                               1219                 :                :                 beg_trunc,
                               1220                 :                :                 end_trunc;
                               1221                 :                : 
                               1222                 :                :     /* Convert loc from 1-based to 0-based; no-op if out of range */
 7294                          1223                 :           7855 :     loc--;
                               1224         [ -  + ]:           7855 :     if (loc < 0)
 7294 tgl@sss.pgh.pa.us        1225                 :UBC           0 :         return;
                               1226                 :                : 
                               1227                 :                :     /* Need a writable copy of the query */
 7495 tgl@sss.pgh.pa.us        1228                 :CBC        7855 :     wquery = strdup(query);
                               1229         [ -  + ]:           7855 :     if (wquery == NULL)
 7495 tgl@sss.pgh.pa.us        1230                 :UBC           0 :         return;                 /* fail silently if out of memory */
                               1231                 :                : 
                               1232                 :                :     /*
                               1233                 :                :      * Each character might occupy multiple physical bytes in the string, and
                               1234                 :                :      * in some Far Eastern character sets it might take more than one screen
                               1235                 :                :      * column as well.  We compute the starting byte offset and starting
                               1236                 :                :      * screen column of each logical character, and store these in qidx[] and
                               1237                 :                :      * scridx[] respectively.
                               1238                 :                :      */
                               1239                 :                : 
                               1240                 :                :     /*
                               1241                 :                :      * We need a safe allocation size.
                               1242                 :                :      *
                               1243                 :                :      * The only caller of reportErrorPosition() is pqBuildErrorMessage3(); it
                               1244                 :                :      * gets its query from either a PQresultErrorField() or a PGcmdQueueEntry,
                               1245                 :                :      * both of which must have fit into conn->inBuffer/outBuffer. So slen fits
                               1246                 :                :      * inside an int, but we can't assume that (slen * sizeof(int)) fits
                               1247                 :                :      * inside a size_t.
                               1248                 :                :      */
 7294 tgl@sss.pgh.pa.us        1249                 :CBC        7855 :     slen = strlen(wquery) + 1;
  314 jchampion@postgresql     1250         [ -  + ]:           7855 :     if (slen > SIZE_MAX / sizeof(int))
                               1251                 :                :     {
  314 jchampion@postgresql     1252                 :UBC           0 :         free(wquery);
                               1253                 :              0 :         return;
                               1254                 :                :     }
                               1255                 :                : 
 7495 tgl@sss.pgh.pa.us        1256                 :CBC        7855 :     qidx = (int *) malloc(slen * sizeof(int));
                               1257         [ -  + ]:           7855 :     if (qidx == NULL)
                               1258                 :                :     {
 7495 tgl@sss.pgh.pa.us        1259                 :UBC           0 :         free(wquery);
                               1260                 :              0 :         return;
                               1261                 :                :     }
 7495 tgl@sss.pgh.pa.us        1262                 :CBC        7855 :     scridx = (int *) malloc(slen * sizeof(int));
                               1263         [ -  + ]:           7855 :     if (scridx == NULL)
                               1264                 :                :     {
 7495 tgl@sss.pgh.pa.us        1265                 :UBC           0 :         free(qidx);
                               1266                 :              0 :         free(wquery);
                               1267                 :              0 :         return;
                               1268                 :                :     }
                               1269                 :                : 
                               1270                 :                :     /* We can optimize a bit if it's a single-byte encoding */
 7294 tgl@sss.pgh.pa.us        1271                 :CBC        7855 :     mb_encoding = (pg_encoding_max_length(encoding) != 1);
                               1272                 :                : 
                               1273                 :                :     /*
                               1274                 :                :      * Within the scanning loop, cno is the current character's logical
                               1275                 :                :      * number, qoffset is its offset in wquery, and scroffset is its starting
                               1276                 :                :      * logical screen column (all indexed from 0).  "loc" is the logical
                               1277                 :                :      * character number of the error location.  We scan to determine loc_line
                               1278                 :                :      * (the 1-based line number containing loc) and ibeg/iend (first character
                               1279                 :                :      * number and last+1 character number of the line containing loc). Note
                               1280                 :                :      * that qidx[] and scridx[] are filled only as far as iend.
                               1281                 :                :      */
 7495                          1282                 :           7855 :     qoffset = 0;
                               1283                 :           7855 :     scroffset = 0;
 7294                          1284                 :           7855 :     loc_line = 1;
                               1285                 :           7855 :     ibeg = 0;
                               1286                 :           7855 :     iend = -1;                  /* -1 means not set yet */
                               1287                 :                : 
                               1288         [ +  + ]:         448654 :     for (cno = 0; wquery[qoffset] != '\0'; cno++)
                               1289                 :                :     {
 7291 bruce@momjian.us         1290                 :         441645 :         char        ch = wquery[qoffset];
                               1291                 :                : 
 7294 tgl@sss.pgh.pa.us        1292                 :         441645 :         qidx[cno] = qoffset;
                               1293                 :         441645 :         scridx[cno] = scroffset;
                               1294                 :                : 
                               1295                 :                :         /*
                               1296                 :                :          * Replace tabs with spaces in the writable copy.  (Later we might
                               1297                 :                :          * want to think about coping with their variable screen width, but
                               1298                 :                :          * not today.)
                               1299                 :                :          */
                               1300         [ +  + ]:         441645 :         if (ch == '\t')
                               1301                 :            653 :             wquery[qoffset] = ' ';
                               1302                 :                : 
                               1303                 :                :         /*
                               1304                 :                :          * If end-of-line, count lines and mark positions. Each \r or \n
                               1305                 :                :          * counts as a line except when \r \n appear together.
                               1306                 :                :          */
                               1307   [ +  -  +  + ]:         440992 :         else if (ch == '\r' || ch == '\n')
                               1308                 :                :         {
                               1309         [ +  + ]:           2992 :             if (cno < loc)
                               1310                 :                :             {
                               1311   [ +  -  +  + ]:           2146 :                 if (ch == '\r' ||
                               1312                 :           2142 :                     cno == 0 ||
                               1313         [ +  - ]:           2142 :                     wquery[qidx[cno - 1]] != '\r')
                               1314                 :           2146 :                     loc_line++;
                               1315                 :                :                 /* extract beginning = last line start before loc. */
                               1316                 :           2146 :                 ibeg = cno + 1;
                               1317                 :                :             }
                               1318                 :                :             else
                               1319                 :                :             {
                               1320                 :                :                 /* set extract end. */
                               1321                 :            846 :                 iend = cno;
                               1322                 :                :                 /* done scanning. */
                               1323                 :            846 :                 break;
                               1324                 :                :             }
                               1325                 :                :         }
                               1326                 :                : 
                               1327                 :                :         /* Advance */
                               1328         [ +  + ]:         440799 :         if (mb_encoding)
                               1329                 :                :         {
                               1330                 :                :             int         w;
                               1331                 :                : 
                               1332                 :         440611 :             w = pg_encoding_dsplen(encoding, &wquery[qoffset]);
                               1333                 :                :             /* treat any non-tab control chars as width 1 */
                               1334         [ +  + ]:         440611 :             if (w <= 0)
                               1335                 :           2146 :                 w = 1;
                               1336                 :         440611 :             scroffset += w;
 1931                          1337                 :         440611 :             qoffset += PQmblenBounded(&wquery[qoffset], encoding);
                               1338                 :                :         }
                               1339                 :                :         else
                               1340                 :                :         {
                               1341                 :                :             /* We assume wide chars only exist in multibyte encodings */
 7294                          1342                 :            188 :             scroffset++;
                               1343                 :            188 :             qoffset++;
                               1344                 :                :         }
                               1345                 :                :     }
                               1346                 :                :     /* Fix up if we didn't find an end-of-line after loc */
                               1347         [ +  + ]:           7855 :     if (iend < 0)
                               1348                 :                :     {
                               1349                 :           7009 :         iend = cno;             /* query length in chars, +1 */
                               1350                 :           7009 :         qidx[iend] = qoffset;
                               1351                 :           7009 :         scridx[iend] = scroffset;
                               1352                 :                :     }
                               1353                 :                : 
                               1354                 :                :     /* Print only if loc is within computed query length */
                               1355         [ +  + ]:           7855 :     if (loc <= cno)
                               1356                 :                :     {
                               1357                 :                :         /* If the line extracted is too long, we truncate it. */
 7495                          1358                 :           7843 :         beg_trunc = false;
                               1359                 :           7843 :         end_trunc = false;
                               1360         [ +  + ]:           7843 :         if (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
                               1361                 :                :         {
                               1362                 :                :             /*
                               1363                 :                :              * We first truncate right if it is enough.  This code might be
                               1364                 :                :              * off a space or so on enforcing MIN_RIGHT_CUT if there's a wide
                               1365                 :                :              * character right there, but that should be okay.
                               1366                 :                :              */
                               1367         [ +  + ]:           2225 :             if (scridx[ibeg] + DISPLAY_SIZE >= scridx[loc] + MIN_RIGHT_CUT)
                               1368                 :                :             {
                               1369         [ +  + ]:          23111 :                 while (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
                               1370                 :          21744 :                     iend--;
                               1371                 :           1367 :                 end_trunc = true;
                               1372                 :                :             }
                               1373                 :                :             else
                               1374                 :                :             {
                               1375                 :                :                 /* Truncate right if not too close to loc. */
                               1376         [ +  + ]:          10190 :                 while (scridx[loc] + MIN_RIGHT_CUT < scridx[iend])
                               1377                 :                :                 {
                               1378                 :           9332 :                     iend--;
                               1379                 :           9332 :                     end_trunc = true;
                               1380                 :                :                 }
                               1381                 :                : 
                               1382                 :                :                 /* Truncate left if still too long. */
                               1383         [ +  + ]:          17439 :                 while (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
                               1384                 :                :                 {
                               1385                 :          16581 :                     ibeg++;
                               1386                 :          16581 :                     beg_trunc = true;
                               1387                 :                :                 }
                               1388                 :                :             }
                               1389                 :                :         }
                               1390                 :                : 
                               1391                 :                :         /* truncate working copy at desired endpoint */
                               1392                 :           7843 :         wquery[qidx[iend]] = '\0';
                               1393                 :                : 
                               1394                 :                :         /* Begin building the finished message. */
                               1395                 :           7843 :         i = msg->len;
                               1396                 :           7843 :         appendPQExpBuffer(msg, libpq_gettext("LINE %d: "), loc_line);
                               1397         [ +  + ]:           7843 :         if (beg_trunc)
                               1398                 :            858 :             appendPQExpBufferStr(msg, "...");
                               1399                 :                : 
                               1400                 :                :         /*
                               1401                 :                :          * While we have the prefix in the msg buffer, compute its screen
                               1402                 :                :          * width.
                               1403                 :                :          */
                               1404                 :           7843 :         scroffset = 0;
 1931                          1405         [ +  + ]:          73185 :         for (; i < msg->len; i += PQmblenBounded(&msg->data[i], encoding))
                               1406                 :                :         {
 7291 bruce@momjian.us         1407                 :          65342 :             int         w = pg_encoding_dsplen(encoding, &msg->data[i]);
                               1408                 :                : 
 7495 tgl@sss.pgh.pa.us        1409         [ -  + ]:          65342 :             if (w <= 0)
 7495 tgl@sss.pgh.pa.us        1410                 :UBC           0 :                 w = 1;
 7495 tgl@sss.pgh.pa.us        1411                 :CBC       65342 :             scroffset += w;
                               1412                 :                :         }
                               1413                 :                : 
                               1414                 :                :         /* Finish up the LINE message line. */
                               1415                 :           7843 :         appendPQExpBufferStr(msg, &wquery[qidx[ibeg]]);
                               1416         [ +  + ]:           7843 :         if (end_trunc)
                               1417                 :           1986 :             appendPQExpBufferStr(msg, "...");
                               1418                 :           7843 :         appendPQExpBufferChar(msg, '\n');
                               1419                 :                : 
                               1420                 :                :         /* Now emit the cursor marker line. */
                               1421                 :           7843 :         scroffset += scridx[loc] - scridx[ibeg];
                               1422         [ +  + ]:         249553 :         for (i = 0; i < scroffset; i++)
                               1423                 :         241710 :             appendPQExpBufferChar(msg, ' ');
                               1424                 :           7843 :         appendPQExpBufferChar(msg, '^');
                               1425                 :           7843 :         appendPQExpBufferChar(msg, '\n');
                               1426                 :                :     }
                               1427                 :                : 
                               1428                 :                :     /* Clean up. */
                               1429                 :           7855 :     free(scridx);
                               1430                 :           7855 :     free(qidx);
                               1431                 :           7855 :     free(wquery);
                               1432                 :                : }
                               1433                 :                : 
                               1434                 :                : 
                               1435                 :                : /*
                               1436                 :                :  * Attempt to read a NegotiateProtocolVersion message.  Sets conn->pversion
                               1437                 :                :  * to the version that's negotiated by the server.
                               1438                 :                :  *
                               1439                 :                :  * Entry: 'v' message type and length have already been consumed.
                               1440                 :                :  * Exit: returns 0 if successfully consumed message.
                               1441                 :                :  *       returns 1 on failure. The error message is filled in.
                               1442                 :                :  */
                               1443                 :                : int
 1403 peter@eisentraut.org     1444                 :UBC           0 : pqGetNegotiateProtocolVersion3(PGconn *conn)
                               1445                 :                : {
                               1446                 :                :     int         their_version;
                               1447                 :                :     int         num;
                               1448                 :                : 
  536 heikki.linnakangas@i     1449         [ #  # ]:              0 :     if (pqGetInt(&their_version, 4, conn) != 0)
                               1450                 :              0 :         goto eof;
                               1451                 :                : 
 1403 peter@eisentraut.org     1452         [ #  # ]:              0 :     if (pqGetInt(&num, 4, conn) != 0)
  536 heikki.linnakangas@i     1453                 :              0 :         goto eof;
                               1454                 :                : 
                               1455                 :                :     /*
                               1456                 :                :      * Check the protocol version.
                               1457                 :                :      *
                               1458                 :                :      * PG_PROTOCOL_GREASE is intentionally unsupported and reserved. It's
                               1459                 :                :      * higher than any real version, so check for that first, to get the most
                               1460                 :                :      * specific error message. Then check the upper and lower bounds.
                               1461                 :                :      */
  226 jchampion@postgresql     1462         [ #  # ]:              0 :     if (their_version == PG_PROTOCOL_GREASE)
                               1463                 :                :     {
                               1464                 :              0 :         libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requested \"grease\" protocol version 3.9999");
                               1465                 :              0 :         goto failure;
                               1466                 :                :     }
                               1467                 :                : 
  536 heikki.linnakangas@i     1468         [ #  # ]:              0 :     if (their_version > conn->pversion)
                               1469                 :                :     {
                               1470                 :              0 :         libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requested downgrade to a higher-numbered version");
                               1471                 :              0 :         goto failure;
                               1472                 :                :     }
                               1473                 :                : 
                               1474         [ #  # ]:              0 :     if (their_version < PG_PROTOCOL(3, 0))
                               1475                 :                :     {
                               1476                 :              0 :         libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requested downgrade to pre-3.0 protocol version");
                               1477                 :              0 :         goto failure;
                               1478                 :                :     }
                               1479                 :                : 
                               1480                 :                :     /* 3.1 never existed, we went straight from 3.0 to 3.2 */
  240 jchampion@postgresql     1481         [ #  # ]:              0 :     if (their_version == PG_PROTOCOL_RESERVED_31)
                               1482                 :                :     {
  451 peter@eisentraut.org     1483                 :              0 :         libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requested downgrade to non-existent 3.1 protocol version");
  536 heikki.linnakangas@i     1484                 :              0 :         goto failure;
                               1485                 :                :     }
                               1486                 :                : 
                               1487         [ #  # ]:              0 :     if (num < 0)
                               1488                 :                :     {
                               1489                 :              0 :         libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported negative number of unsupported parameters");
                               1490                 :              0 :         goto failure;
                               1491                 :                :     }
                               1492                 :                : 
                               1493   [ #  #  #  # ]:              0 :     if (their_version == conn->pversion && num == 0)
                               1494                 :                :     {
                               1495                 :              0 :         libpq_append_conn_error(conn, "received invalid protocol negotiation message: server negotiated but asks for no changes");
                               1496                 :              0 :         goto failure;
                               1497                 :                :     }
                               1498                 :                : 
                               1499         [ #  # ]:              0 :     if (their_version < conn->min_pversion)
                               1500                 :                :     {
  451 peter@eisentraut.org     1501                 :              0 :         libpq_append_conn_error(conn, "server only supports protocol version %d.%d, but \"%s\" was set to %d.%d",
                               1502                 :                :                                 PG_PROTOCOL_MAJOR(their_version),
                               1503                 :                :                                 PG_PROTOCOL_MINOR(their_version),
                               1504                 :                :                                 "min_protocol_version",
  536 heikki.linnakangas@i     1505                 :              0 :                                 PG_PROTOCOL_MAJOR(conn->min_pversion),
                               1506                 :              0 :                                 PG_PROTOCOL_MINOR(conn->min_pversion));
                               1507                 :                : 
                               1508                 :              0 :         goto failure;
                               1509                 :                :     }
                               1510                 :                : 
                               1511                 :                :     /* the version is acceptable */
                               1512                 :              0 :     conn->pversion = their_version;
                               1513                 :                : 
                               1514                 :                :     /*
                               1515                 :                :      * We don't currently request any protocol extensions, so we don't expect
                               1516                 :                :      * the server to reply with any either.
                               1517                 :                :      */
                               1518         [ #  # ]:              0 :     for (int i = 0; i < num; i++)
                               1519                 :                :     {
                               1520         [ #  # ]:              0 :         if (pqGets(&conn->workBuffer, conn))
                               1521                 :                :         {
                               1522                 :              0 :             goto eof;
                               1523                 :                :         }
                               1524         [ #  # ]:              0 :         if (strncmp(conn->workBuffer.data, "_pq_.", 5) != 0)
                               1525                 :                :         {
  451 peter@eisentraut.org     1526                 :              0 :             libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported unsupported parameter name without a \"%s\" prefix (\"%s\")", "_pq_.", conn->workBuffer.data);
  536 heikki.linnakangas@i     1527                 :              0 :             goto failure;
                               1528                 :                :         }
   19 jchampion@postgresql     1529                 :              0 :         libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported an unsupported parameter that was not requested (\"%s\")",
                               1530                 :                :                                 conn->workBuffer.data);
  536 heikki.linnakangas@i     1531                 :              0 :         goto failure;
                               1532                 :                :     }
                               1533                 :                : 
 1403 peter@eisentraut.org     1534                 :              0 :     return 0;
                               1535                 :                : 
  536 heikki.linnakangas@i     1536                 :              0 : eof:
  519 michael@paquier.xyz      1537                 :              0 :     libpq_append_conn_error(conn, "received invalid protocol negotiation message: message too short");
  536 heikki.linnakangas@i     1538                 :              0 : failure:
                               1539                 :              0 :     conn->asyncStatus = PGASYNC_READY;
                               1540                 :              0 :     pqSaveErrorResult(conn);
                               1541                 :              0 :     return 1;
                               1542                 :                : }
                               1543                 :                : 
                               1544                 :                : 
                               1545                 :                : /*
                               1546                 :                :  * Attempt to read a ParameterStatus message.
                               1547                 :                :  * This is possible in several places, so we break it out as a subroutine.
                               1548                 :                :  *
                               1549                 :                :  * Entry: 'S' message type and length have already been consumed.
                               1550                 :                :  * Exit: returns 0 if successfully consumed message.
                               1551                 :                :  *       returns EOF if not enough data.
                               1552                 :                :  */
                               1553                 :                : static int
 8505 tgl@sss.pgh.pa.us        1554                 :CBC      244613 : getParameterStatus(PGconn *conn)
                               1555                 :                : {
                               1556                 :                :     PQExpBufferData valueBuf;
                               1557                 :                : 
                               1558                 :                :     /* Get the parameter name */
                               1559         [ -  + ]:         244613 :     if (pqGets(&conn->workBuffer, conn))
 8505 tgl@sss.pgh.pa.us        1560                 :UBC           0 :         return EOF;
                               1561                 :                :     /* Get the parameter value (could be large) */
 8505 tgl@sss.pgh.pa.us        1562                 :CBC      244613 :     initPQExpBuffer(&valueBuf);
                               1563         [ -  + ]:         244613 :     if (pqGets(&valueBuf, conn))
                               1564                 :                :     {
 8505 tgl@sss.pgh.pa.us        1565                 :UBC           0 :         termPQExpBuffer(&valueBuf);
                               1566                 :              0 :         return EOF;
                               1567                 :                :     }
                               1568                 :                :     /* And save it */
  394 heikki.linnakangas@i     1569         [ -  + ]:CBC      244613 :     if (!pqSaveParameterStatus(conn, conn->workBuffer.data, valueBuf.data))
                               1570                 :                :     {
  394 heikki.linnakangas@i     1571                 :UBC           0 :         libpq_append_conn_error(conn, "out of memory");
                               1572                 :              0 :         handleFatalError(conn);
                               1573                 :                :     }
 8505 tgl@sss.pgh.pa.us        1574                 :CBC      244613 :     termPQExpBuffer(&valueBuf);
                               1575                 :         244613 :     return 0;
                               1576                 :                : }
                               1577                 :                : 
                               1578                 :                : /*
                               1579                 :                :  * parseInput subroutine to read a BackendKeyData message.
                               1580                 :                :  * Entry: 'K' message type and length have already been consumed.
                               1581                 :                :  * Exit: returns 0 if successfully consumed message.
                               1582                 :                :  *       returns EOF if not enough data.
                               1583                 :                :  */
                               1584                 :                : static int
  536 heikki.linnakangas@i     1585                 :          15707 : getBackendKeyData(PGconn *conn, int msgLength)
                               1586                 :                : {
                               1587                 :                :     int         cancel_key_len;
                               1588                 :                : 
                               1589         [ -  + ]:          15707 :     if (conn->be_cancel_key)
                               1590                 :                :     {
  536 heikki.linnakangas@i     1591                 :UBC           0 :         free(conn->be_cancel_key);
                               1592                 :              0 :         conn->be_cancel_key = NULL;
                               1593                 :              0 :         conn->be_cancel_key_len = 0;
                               1594                 :                :     }
                               1595                 :                : 
  536 heikki.linnakangas@i     1596         [ -  + ]:CBC       15707 :     if (pqGetInt(&(conn->be_pid), 4, conn))
  536 heikki.linnakangas@i     1597                 :UBC           0 :         return EOF;
                               1598                 :                : 
  536 heikki.linnakangas@i     1599                 :CBC       15707 :     cancel_key_len = 5 + msgLength - (conn->inCursor - conn->inStart);
                               1600                 :                : 
  394                          1601   [ +  +  -  + ]:          15707 :     if (cancel_key_len != 4 && conn->pversion == PG_PROTOCOL(3, 0))
                               1602                 :                :     {
  394 heikki.linnakangas@i     1603                 :UBC           0 :         libpq_append_conn_error(conn, "received invalid BackendKeyData message: cancel key with length %d not allowed in protocol version 3.0 (must be 4 bytes)", cancel_key_len);
                               1604                 :              0 :         handleFatalError(conn);
                               1605                 :              0 :         return 0;
                               1606                 :                :     }
                               1607                 :                : 
  394 heikki.linnakangas@i     1608         [ -  + ]:CBC       15707 :     if (cancel_key_len < 4)
                               1609                 :                :     {
  394 heikki.linnakangas@i     1610                 :UBC           0 :         libpq_append_conn_error(conn, "received invalid BackendKeyData message: cancel key with length %d is too short (minimum 4 bytes)", cancel_key_len);
                               1611                 :              0 :         handleFatalError(conn);
                               1612                 :              0 :         return 0;
                               1613                 :                :     }
                               1614                 :                : 
  394 heikki.linnakangas@i     1615         [ -  + ]:CBC       15707 :     if (cancel_key_len > 256)
                               1616                 :                :     {
  394 heikki.linnakangas@i     1617                 :UBC           0 :         libpq_append_conn_error(conn, "received invalid BackendKeyData message: cancel key with length %d is too long (maximum 256 bytes)", cancel_key_len);
                               1618                 :              0 :         handleFatalError(conn);
                               1619                 :              0 :         return 0;
                               1620                 :                :     }
                               1621                 :                : 
  536 heikki.linnakangas@i     1622                 :CBC       15707 :     conn->be_cancel_key = malloc(cancel_key_len);
                               1623         [ -  + ]:          15707 :     if (conn->be_cancel_key == NULL)
                               1624                 :                :     {
  536 heikki.linnakangas@i     1625                 :UBC           0 :         libpq_append_conn_error(conn, "out of memory");
  394                          1626                 :              0 :         handleFatalError(conn);
                               1627                 :              0 :         return 0;
                               1628                 :                :     }
  536 heikki.linnakangas@i     1629         [ -  + ]:CBC       15707 :     if (pqGetnchar(conn->be_cancel_key, cancel_key_len, conn))
                               1630                 :                :     {
  536 heikki.linnakangas@i     1631                 :UBC           0 :         free(conn->be_cancel_key);
                               1632                 :              0 :         conn->be_cancel_key = NULL;
                               1633                 :              0 :         return EOF;
                               1634                 :                :     }
  536 heikki.linnakangas@i     1635                 :CBC       15707 :     conn->be_cancel_key_len = cancel_key_len;
                               1636                 :          15707 :     return 0;
                               1637                 :                : }
                               1638                 :                : 
                               1639                 :                : 
                               1640                 :                : /*
                               1641                 :                :  * Attempt to read a Notify response message.
                               1642                 :                :  * This is possible in several places, so we break it out as a subroutine.
                               1643                 :                :  *
                               1644                 :                :  * Entry: 'A' message type and length have already been consumed.
                               1645                 :                :  * Exit: returns 0 if successfully consumed Notify message.
                               1646                 :                :  *       returns EOF if not enough data.
                               1647                 :                :  */
                               1648                 :                : static int
 8505 tgl@sss.pgh.pa.us        1649                 :             53 : getNotify(PGconn *conn)
                               1650                 :                : {
                               1651                 :                :     int         be_pid;
                               1652                 :                :     char       *svname;
                               1653                 :                :     int         nmlen;
                               1654                 :                :     int         extralen;
                               1655                 :                :     PGnotify   *newNotify;
                               1656                 :                : 
                               1657         [ -  + ]:             53 :     if (pqGetInt(&be_pid, 4, conn))
 8505 tgl@sss.pgh.pa.us        1658                 :UBC           0 :         return EOF;
 8505 tgl@sss.pgh.pa.us        1659         [ -  + ]:CBC          53 :     if (pqGets(&conn->workBuffer, conn))
 8505 tgl@sss.pgh.pa.us        1660                 :UBC           0 :         return EOF;
                               1661                 :                :     /* must save name while getting extra string */
 8492 tgl@sss.pgh.pa.us        1662                 :CBC          53 :     svname = strdup(conn->workBuffer.data);
                               1663         [ -  + ]:             53 :     if (!svname)
                               1664                 :                :     {
                               1665                 :                :         /*
                               1666                 :                :          * Notify messages can arrive at any state, so we cannot associate the
                               1667                 :                :          * error with any particular query.  There's no way to return back an
                               1668                 :                :          * "async error", so the best we can do is drop the connection.  That
                               1669                 :                :          * seems better than silently ignoring the notification.
                               1670                 :                :          */
  394 heikki.linnakangas@i     1671                 :UBC           0 :         libpq_append_conn_error(conn, "out of memory");
                               1672                 :              0 :         handleFatalError(conn);
                               1673                 :              0 :         return 0;
                               1674                 :                :     }
 8492 tgl@sss.pgh.pa.us        1675         [ -  + ]:CBC          53 :     if (pqGets(&conn->workBuffer, conn))
                               1676                 :                :     {
  394 heikki.linnakangas@i     1677                 :UBC           0 :         free(svname);
 8492 tgl@sss.pgh.pa.us        1678                 :              0 :         return EOF;
                               1679                 :                :     }
                               1680                 :                : 
                               1681                 :                :     /*
                               1682                 :                :      * Store the strings right after the PGnotify structure so it can all be
                               1683                 :                :      * freed at once.  We don't use NAMEDATALEN because we don't want to tie
                               1684                 :                :      * this interface to a specific server name length.
                               1685                 :                :      */
 8492 tgl@sss.pgh.pa.us        1686                 :CBC          53 :     nmlen = strlen(svname);
                               1687                 :             53 :     extralen = strlen(conn->workBuffer.data);
                               1688                 :             53 :     newNotify = (PGnotify *) malloc(sizeof(PGnotify) + nmlen + extralen + 2);
  394 heikki.linnakangas@i     1689         [ -  + ]:             53 :     if (!newNotify)
                               1690                 :                :     {
  394 heikki.linnakangas@i     1691                 :UBC           0 :         free(svname);
                               1692                 :              0 :         libpq_append_conn_error(conn, "out of memory");
                               1693                 :              0 :         handleFatalError(conn);
                               1694                 :              0 :         return 0;
                               1695                 :                :     }
                               1696                 :                : 
  394 heikki.linnakangas@i     1697                 :CBC          53 :     newNotify->relname = (char *) newNotify + sizeof(PGnotify);
                               1698                 :             53 :     strcpy(newNotify->relname, svname);
                               1699                 :             53 :     newNotify->extra = newNotify->relname + nmlen + 1;
                               1700                 :             53 :     strcpy(newNotify->extra, conn->workBuffer.data);
                               1701                 :             53 :     newNotify->be_pid = be_pid;
                               1702                 :             53 :     newNotify->next = NULL;
                               1703         [ +  + ]:             53 :     if (conn->notifyTail)
                               1704                 :             29 :         conn->notifyTail->next = newNotify;
                               1705                 :                :     else
                               1706                 :             24 :         conn->notifyHead = newNotify;
                               1707                 :             53 :     conn->notifyTail = newNotify;
                               1708                 :                : 
 8492 tgl@sss.pgh.pa.us        1709                 :             53 :     free(svname);
                               1710                 :             53 :     return 0;
                               1711                 :                : }
                               1712                 :                : 
                               1713                 :                : /*
                               1714                 :                :  * getCopyStart - process CopyInResponse, CopyOutResponse or
                               1715                 :                :  * CopyBothResponse message
                               1716                 :                :  *
                               1717                 :                :  * parseInput already read the message type and length.
                               1718                 :                :  */
                               1719                 :                : static int
                               1720                 :           6695 : getCopyStart(PGconn *conn, ExecStatusType copytype)
                               1721                 :                : {
                               1722                 :                :     PGresult   *result;
                               1723                 :                :     int         nfields;
                               1724                 :                :     int         i;
                               1725                 :                : 
                               1726                 :           6695 :     result = PQmakeEmptyPGresult(conn, copytype);
 7770 neilc@samurai.com        1727         [ -  + ]:           6695 :     if (!result)
 7770 neilc@samurai.com        1728                 :UBC           0 :         goto failure;
                               1729                 :                : 
 8492 tgl@sss.pgh.pa.us        1730         [ -  + ]:CBC        6695 :     if (pqGetc(&conn->copy_is_binary, conn))
 7770 neilc@samurai.com        1731                 :UBC           0 :         goto failure;
 8492 tgl@sss.pgh.pa.us        1732                 :CBC        6695 :     result->binary = conn->copy_is_binary;
                               1733                 :                :     /* the next two bytes are the number of fields  */
                               1734         [ -  + ]:           6695 :     if (pqGetInt(&(result->numAttributes), 2, conn))
 7770 neilc@samurai.com        1735                 :UBC           0 :         goto failure;
 8492 tgl@sss.pgh.pa.us        1736                 :CBC        6695 :     nfields = result->numAttributes;
                               1737                 :                : 
                               1738                 :                :     /* allocate space for the attribute descriptors */
                               1739         [ +  + ]:           6695 :     if (nfields > 0)
                               1740                 :                :     {
                               1741                 :           5519 :         result->attDescs = (PGresAttDesc *)
 3322 peter_e@gmx.net          1742                 :           5519 :             pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
 7770 neilc@samurai.com        1743         [ -  + ]:           5519 :         if (!result->attDescs)
 7770 neilc@samurai.com        1744                 :UBC           0 :             goto failure;
 7770 neilc@samurai.com        1745   [ +  -  +  -  :CBC       59743 :         MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
                                     +  -  +  +  +  
                                                 + ]
                               1746                 :                :     }
                               1747                 :                : 
 8492 tgl@sss.pgh.pa.us        1748         [ +  + ]:          25057 :     for (i = 0; i < nfields; i++)
                               1749                 :                :     {
                               1750                 :                :         int         format;
                               1751                 :                : 
                               1752         [ -  + ]:          18362 :         if (pqGetInt(&format, 2, conn))
 7770 neilc@samurai.com        1753                 :UBC           0 :             goto failure;
                               1754                 :                : 
                               1755                 :                :         /*
                               1756                 :                :          * Since pqGetInt treats 2-byte integers as unsigned, we need to
                               1757                 :                :          * coerce these results to signed form.
                               1758                 :                :          */
 8492 tgl@sss.pgh.pa.us        1759                 :CBC       18362 :         format = (int) ((int16) format);
                               1760                 :          18362 :         result->attDescs[i].format = format;
                               1761                 :                :     }
                               1762                 :                : 
                               1763                 :                :     /* Success! */
                               1764                 :           6695 :     conn->result = result;
 8505                          1765                 :           6695 :     return 0;
                               1766                 :                : 
 7770 neilc@samurai.com        1767                 :UBC           0 : failure:
                               1768                 :              0 :     PQclear(result);
                               1769                 :              0 :     return EOF;
                               1770                 :                : }
                               1771                 :                : 
                               1772                 :                : /*
                               1773                 :                :  * getReadyForQuery - process ReadyForQuery message
                               1774                 :                :  */
                               1775                 :                : static int
 8492 tgl@sss.pgh.pa.us        1776                 :CBC      420047 : getReadyForQuery(PGconn *conn)
                               1777                 :                : {
                               1778                 :                :     char        xact_status;
                               1779                 :                : 
                               1780         [ -  + ]:         420047 :     if (pqGetc(&xact_status, conn))
 8492 tgl@sss.pgh.pa.us        1781                 :UBC           0 :         return EOF;
 8492 tgl@sss.pgh.pa.us        1782   [ +  +  +  - ]:CBC      420047 :     switch (xact_status)
                               1783                 :                :     {
                               1784                 :         326390 :         case 'I':
                               1785                 :         326390 :             conn->xactStatus = PQTRANS_IDLE;
                               1786                 :         326390 :             break;
                               1787                 :          92482 :         case 'T':
                               1788                 :          92482 :             conn->xactStatus = PQTRANS_INTRANS;
                               1789                 :          92482 :             break;
                               1790                 :           1175 :         case 'E':
                               1791                 :           1175 :             conn->xactStatus = PQTRANS_INERROR;
                               1792                 :           1175 :             break;
 8492 tgl@sss.pgh.pa.us        1793                 :UBC           0 :         default:
                               1794                 :              0 :             conn->xactStatus = PQTRANS_UNKNOWN;
                               1795                 :              0 :             break;
                               1796                 :                :     }
                               1797                 :                : 
 8492 tgl@sss.pgh.pa.us        1798                 :CBC      420047 :     return 0;
                               1799                 :                : }
                               1800                 :                : 
                               1801                 :                : /*
                               1802                 :                :  * getCopyDataMessage - fetch next CopyData message, process async messages
                               1803                 :                :  *
                               1804                 :                :  * Returns length word of CopyData message (> 0), or 0 if no complete
                               1805                 :                :  * message available, -1 if end of copy, -2 if error.
                               1806                 :                :  */
                               1807                 :                : static int
 6824                          1808                 :        3101233 : getCopyDataMessage(PGconn *conn)
                               1809                 :                : {
                               1810                 :                :     char        id;
                               1811                 :                :     int         msgLength;
                               1812                 :                :     int         avail;
                               1813                 :                : 
                               1814                 :                :     for (;;)
                               1815                 :                :     {
                               1816                 :                :         /*
                               1817                 :                :          * Do we have the next input message?  To make life simpler for async
                               1818                 :                :          * callers, we keep returning 0 until the next message is fully
                               1819                 :                :          * available, even if it is not Copy Data.
                               1820                 :                :          */
 8492                          1821                 :        3101270 :         conn->inCursor = conn->inStart;
                               1822         [ +  + ]:        3101270 :         if (pqGetc(&id, conn))
 6824                          1823                 :         269575 :             return 0;
 8492                          1824         [ +  + ]:        2831695 :         if (pqGetInt(&msgLength, 4, conn))
 6824                          1825                 :            793 :             return 0;
                               1826         [ -  + ]:        2830902 :         if (msgLength < 4)
                               1827                 :                :         {
 6824 tgl@sss.pgh.pa.us        1828                 :UBC           0 :             handleSyncLoss(conn, id, msgLength);
                               1829                 :              0 :             return -2;
                               1830                 :                :         }
 8492 tgl@sss.pgh.pa.us        1831                 :CBC     2830902 :         avail = conn->inEnd - conn->inCursor;
                               1832         [ +  + ]:        2830902 :         if (avail < msgLength - 4)
                               1833                 :                :         {
                               1834                 :                :             /*
                               1835                 :                :              * Before returning, enlarge the input buffer if needed to hold
                               1836                 :                :              * the whole message.  See notes in parseInput.
                               1837                 :                :              */
 6688                          1838         [ -  + ]:         264545 :             if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength - 4,
                               1839                 :                :                                      conn))
                               1840                 :                :             {
                               1841                 :                :                 /*
                               1842                 :                :                  * Abandon the connection.  There's not much else we can
                               1843                 :                :                  * safely do; we can't just ignore the message or we could
                               1844                 :                :                  * miss important changes to the connection state.
                               1845                 :                :                  * pqCheckInBufferSpace() already reported the error.
                               1846                 :                :                  */
  394 heikki.linnakangas@i     1847                 :UBC           0 :                 handleFatalError(conn);
 6821 tgl@sss.pgh.pa.us        1848                 :              0 :                 return -2;
                               1849                 :                :             }
 6824 tgl@sss.pgh.pa.us        1850                 :CBC      264545 :             return 0;
                               1851                 :                :         }
                               1852                 :                : 
                               1853                 :                :         /*
                               1854                 :                :          * If it's a legitimate async message type, process it.  (NOTIFY
                               1855                 :                :          * messages are not currently possible here, but we handle them for
                               1856                 :                :          * completeness.)  Otherwise, if it's anything except Copy Data,
                               1857                 :                :          * report end-of-copy.
                               1858                 :                :          */
                               1859   [ -  +  -  +  :        2566357 :         switch (id)
                                              +  + ]
                               1860                 :                :         {
 1125 nathan@postgresql.or     1861                 :UBC           0 :             case PqMsg_NotificationResponse:
 6824 tgl@sss.pgh.pa.us        1862         [ #  # ]:              0 :                 if (getNotify(conn))
                               1863                 :              0 :                     return 0;
                               1864                 :              0 :                 break;
 1125 nathan@postgresql.or     1865                 :CBC          37 :             case PqMsg_NoticeResponse:
 6824 tgl@sss.pgh.pa.us        1866         [ -  + ]:             37 :                 if (pqGetErrorNotice3(conn, false))
 6824 tgl@sss.pgh.pa.us        1867                 :UBC           0 :                     return 0;
 6824 tgl@sss.pgh.pa.us        1868                 :CBC          37 :                 break;
 1125 nathan@postgresql.or     1869                 :UBC           0 :             case PqMsg_ParameterStatus:
 6824 tgl@sss.pgh.pa.us        1870         [ #  # ]:              0 :                 if (getParameterStatus(conn))
                               1871                 :              0 :                     return 0;
                               1872                 :              0 :                 break;
 1125 nathan@postgresql.or     1873                 :CBC     2560927 :             case PqMsg_CopyData:
 6824 tgl@sss.pgh.pa.us        1874                 :        2560927 :                 return msgLength;
 1125 nathan@postgresql.or     1875                 :           5328 :             case PqMsg_CopyDone:
                               1876                 :                : 
                               1877                 :                :                 /*
                               1878                 :                :                  * If this is a CopyDone message, exit COPY_OUT mode and let
                               1879                 :                :                  * caller read status with PQgetResult().  If we're in
                               1880                 :                :                  * COPY_BOTH mode, return to COPY_IN mode.
                               1881                 :                :                  */
 4892 rhaas@postgresql.org     1882         [ +  + ]:           5328 :                 if (conn->asyncStatus == PGASYNC_COPY_BOTH)
                               1883                 :             15 :                     conn->asyncStatus = PGASYNC_COPY_IN;
                               1884                 :                :                 else
                               1885                 :           5313 :                     conn->asyncStatus = PGASYNC_BUSY;
                               1886                 :           5328 :                 return -1;
 6824 tgl@sss.pgh.pa.us        1887                 :             65 :             default:            /* treat as end of copy */
                               1888                 :                : 
                               1889                 :                :                 /*
                               1890                 :                :                  * Any other message terminates either COPY_IN or COPY_BOTH
                               1891                 :                :                  * mode.
                               1892                 :                :                  */
 4892 rhaas@postgresql.org     1893                 :             65 :                 conn->asyncStatus = PGASYNC_BUSY;
 6824 tgl@sss.pgh.pa.us        1894                 :             65 :                 return -1;
                               1895                 :                :         }
                               1896                 :                : 
                               1897                 :                :         /*
                               1898                 :                :          * An error may have been triggered while processing the message,
                               1899                 :                :          * report it if it's the case
                               1900                 :                :          */
   47 fujii@postgresql.org     1901   [ -  +  -  - ]:             37 :         if (conn->error_result && conn->status == CONNECTION_BAD)
   47 fujii@postgresql.org     1902                 :UBC           0 :             return -2;
                               1903                 :                : 
                               1904                 :                :         /* Drop the processed message and loop around for another */
  765 alvherre@alvh.no-ip.     1905                 :CBC          37 :         pqParseDone(conn, conn->inCursor);
                               1906                 :                :     }
                               1907                 :                : }
                               1908                 :                : 
                               1909                 :                : /*
                               1910                 :                :  * PQgetCopyData - read a row of data from the backend during COPY OUT
                               1911                 :                :  * or COPY BOTH
                               1912                 :                :  *
                               1913                 :                :  * If successful, sets *buffer to point to a malloc'd row of data, and
                               1914                 :                :  * returns row length (always > 0) as result.
                               1915                 :                :  * Returns 0 if no row available yet (only possible if async is true),
                               1916                 :                :  * -1 if end of copy (consult PQgetResult), or -2 if error (consult
                               1917                 :                :  * PQerrorMessage).
                               1918                 :                :  */
                               1919                 :                : int
 6824 tgl@sss.pgh.pa.us        1920                 :        2914844 : pqGetCopyData3(PGconn *conn, char **buffer, int async)
                               1921                 :                : {
                               1922                 :                :     int         msgLength;
                               1923                 :                : 
                               1924                 :                :     for (;;)
                               1925                 :                :     {
                               1926                 :                :         /*
                               1927                 :                :          * Collect the next input message.  To make life simpler for async
                               1928                 :                :          * callers, we keep returning 0 until the next message is fully
                               1929                 :                :          * available, even if it is not Copy Data.
                               1930                 :                :          */
                               1931                 :        3101233 :         msgLength = getCopyDataMessage(conn);
                               1932         [ +  + ]:        3101233 :         if (msgLength < 0)
 6310 bruce@momjian.us         1933                 :           5393 :             return msgLength;   /* end-of-copy or error */
 6824 tgl@sss.pgh.pa.us        1934         [ +  + ]:        3095840 :         if (msgLength == 0)
                               1935                 :                :         {
                               1936                 :                :             /* Don't block if async read requested */
                               1937         [ +  + ]:         534913 :             if (async)
                               1938                 :         348524 :                 return 0;
                               1939                 :                :             /* Need to load more data */
 3322 peter_e@gmx.net          1940   [ +  -  -  + ]:         372778 :             if (pqWait(true, false, conn) ||
 6824 tgl@sss.pgh.pa.us        1941                 :         186389 :                 pqReadData(conn) < 0)
 6824 tgl@sss.pgh.pa.us        1942                 :UBC           0 :                 return -2;
 6824 tgl@sss.pgh.pa.us        1943                 :CBC      186389 :             continue;
                               1944                 :                :         }
                               1945                 :                : 
                               1946                 :                :         /*
                               1947                 :                :          * Drop zero-length messages (shouldn't happen anyway).  Otherwise
                               1948                 :                :          * pass the data back to the caller.
                               1949                 :                :          */
 8492                          1950                 :        2560927 :         msgLength -= 4;
                               1951         [ +  - ]:        2560927 :         if (msgLength > 0)
                               1952                 :                :         {
                               1953                 :        2560927 :             *buffer = (char *) malloc(msgLength + 1);
                               1954         [ -  + ]:        2560927 :             if (*buffer == NULL)
                               1955                 :                :             {
 1405 peter@eisentraut.org     1956                 :UBC           0 :                 libpq_append_conn_error(conn, "out of memory");
 8492 tgl@sss.pgh.pa.us        1957                 :              0 :                 return -2;
                               1958                 :                :             }
 8492 tgl@sss.pgh.pa.us        1959                 :CBC     2560927 :             memcpy(*buffer, &conn->inBuffer[conn->inCursor], msgLength);
 3378                          1960                 :        2560927 :             (*buffer)[msgLength] = '\0';    /* Add terminating null */
                               1961                 :                : 
                               1962                 :                :             /* Mark message consumed */
  765 alvherre@alvh.no-ip.     1963                 :        2560927 :             pqParseDone(conn, conn->inCursor + msgLength);
                               1964                 :                : 
 8492 tgl@sss.pgh.pa.us        1965                 :        2560927 :             return msgLength;
                               1966                 :                :         }
                               1967                 :                : 
                               1968                 :                :         /* Empty, so drop it and loop around for another */
  765 alvherre@alvh.no-ip.     1969                 :UBC           0 :         pqParseDone(conn, conn->inCursor);
                               1970                 :                :     }
                               1971                 :                : }
                               1972                 :                : 
                               1973                 :                : /*
                               1974                 :                :  * PQgetline - gets a newline-terminated string from the backend.
                               1975                 :                :  *
                               1976                 :                :  * See fe-exec.c for documentation.
                               1977                 :                :  */
                               1978                 :                : int
 8505 tgl@sss.pgh.pa.us        1979                 :              0 : pqGetline3(PGconn *conn, char *s, int maxlen)
                               1980                 :                : {
                               1981                 :                :     int         status;
                               1982                 :                : 
 4540 bruce@momjian.us         1983         [ #  # ]:              0 :     if (conn->sock == PGINVALID_SOCKET ||
 4895 rhaas@postgresql.org     1984         [ #  # ]:              0 :         (conn->asyncStatus != PGASYNC_COPY_OUT &&
                               1985         [ #  # ]:              0 :          conn->asyncStatus != PGASYNC_COPY_BOTH) ||
 8505 tgl@sss.pgh.pa.us        1986         [ #  # ]:              0 :         conn->copy_is_binary)
                               1987                 :                :     {
 1405 peter@eisentraut.org     1988                 :              0 :         libpq_append_conn_error(conn, "PQgetline: not doing text COPY OUT");
 8505 tgl@sss.pgh.pa.us        1989                 :              0 :         *s = '\0';
                               1990                 :              0 :         return EOF;
                               1991                 :                :     }
                               1992                 :                : 
 8448 bruce@momjian.us         1993         [ #  # ]:              0 :     while ((status = PQgetlineAsync(conn, s, maxlen - 1)) == 0)
                               1994                 :                :     {
                               1995                 :                :         /* need to load more data */
 3322 peter_e@gmx.net          1996   [ #  #  #  # ]:              0 :         if (pqWait(true, false, conn) ||
 8505 tgl@sss.pgh.pa.us        1997                 :              0 :             pqReadData(conn) < 0)
                               1998                 :                :         {
                               1999                 :              0 :             *s = '\0';
                               2000                 :              0 :             return EOF;
                               2001                 :                :         }
                               2002                 :                :     }
                               2003                 :                : 
                               2004         [ #  # ]:              0 :     if (status < 0)
                               2005                 :                :     {
                               2006                 :                :         /* End of copy detected; gin up old-style terminator */
                               2007                 :              0 :         strcpy(s, "\\.");
                               2008                 :              0 :         return 0;
                               2009                 :                :     }
                               2010                 :                : 
                               2011                 :                :     /* Add null terminator, and strip trailing \n if present */
 8448 bruce@momjian.us         2012         [ #  # ]:              0 :     if (s[status - 1] == '\n')
                               2013                 :                :     {
                               2014                 :              0 :         s[status - 1] = '\0';
 8505 tgl@sss.pgh.pa.us        2015                 :              0 :         return 0;
                               2016                 :                :     }
                               2017                 :                :     else
                               2018                 :                :     {
                               2019                 :              0 :         s[status] = '\0';
                               2020                 :              0 :         return 1;
                               2021                 :                :     }
                               2022                 :                : }
                               2023                 :                : 
                               2024                 :                : /*
                               2025                 :                :  * PQgetlineAsync - gets a COPY data row without blocking.
                               2026                 :                :  *
                               2027                 :                :  * See fe-exec.c for documentation.
                               2028                 :                :  */
                               2029                 :                : int
                               2030                 :              0 : pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)
                               2031                 :                : {
                               2032                 :                :     int         msgLength;
                               2033                 :                :     int         avail;
                               2034                 :                : 
 4895 rhaas@postgresql.org     2035         [ #  # ]:              0 :     if (conn->asyncStatus != PGASYNC_COPY_OUT
                               2036         [ #  # ]:              0 :         && conn->asyncStatus != PGASYNC_COPY_BOTH)
 8505 tgl@sss.pgh.pa.us        2037                 :              0 :         return -1;              /* we are not doing a copy... */
                               2038                 :                : 
                               2039                 :                :     /*
                               2040                 :                :      * Recognize the next input message.  To make life simpler for async
                               2041                 :                :      * callers, we keep returning 0 until the next message is fully available
                               2042                 :                :      * even if it is not Copy Data.  This should keep PQendcopy from blocking.
                               2043                 :                :      * (Note: unlike pqGetCopyData3, we do not change asyncStatus here.)
                               2044                 :                :      */
 6824                          2045                 :              0 :     msgLength = getCopyDataMessage(conn);
                               2046         [ #  # ]:              0 :     if (msgLength < 0)
                               2047                 :              0 :         return -1;              /* end-of-copy or error */
                               2048         [ #  # ]:              0 :     if (msgLength == 0)
                               2049                 :              0 :         return 0;               /* no data yet */
                               2050                 :                : 
                               2051                 :                :     /*
                               2052                 :                :      * Move data from libpq's buffer to the caller's.  In the case where a
                               2053                 :                :      * prior call found the caller's buffer too small, we use
                               2054                 :                :      * conn->copy_already_done to remember how much of the row was already
                               2055                 :                :      * returned to the caller.
                               2056                 :                :      */
 8505                          2057                 :              0 :     conn->inCursor += conn->copy_already_done;
                               2058                 :              0 :     avail = msgLength - 4 - conn->copy_already_done;
                               2059         [ #  # ]:              0 :     if (avail <= bufsize)
                               2060                 :                :     {
                               2061                 :                :         /* Able to consume the whole message */
                               2062                 :              0 :         memcpy(buffer, &conn->inBuffer[conn->inCursor], avail);
                               2063                 :                :         /* Mark message consumed */
                               2064                 :              0 :         conn->inStart = conn->inCursor + avail;
                               2065                 :                :         /* Reset state for next time */
                               2066                 :              0 :         conn->copy_already_done = 0;
                               2067                 :              0 :         return avail;
                               2068                 :                :     }
                               2069                 :                :     else
                               2070                 :                :     {
                               2071                 :                :         /* We must return a partial message */
                               2072                 :              0 :         memcpy(buffer, &conn->inBuffer[conn->inCursor], bufsize);
                               2073                 :                :         /* The message is NOT consumed from libpq's buffer */
                               2074                 :              0 :         conn->copy_already_done += bufsize;
                               2075                 :              0 :         return bufsize;
                               2076                 :                :     }
                               2077                 :                : }
                               2078                 :                : 
                               2079                 :                : /*
                               2080                 :                :  * PQendcopy
                               2081                 :                :  *
                               2082                 :                :  * See fe-exec.c for documentation.
                               2083                 :                :  */
                               2084                 :                : int
 8505 tgl@sss.pgh.pa.us        2085                 :CBC         210 : pqEndcopy3(PGconn *conn)
                               2086                 :                : {
                               2087                 :                :     PGresult   *result;
                               2088                 :                : 
                               2089         [ +  + ]:            210 :     if (conn->asyncStatus != PGASYNC_COPY_IN &&
 4895 rhaas@postgresql.org     2090         [ -  + ]:            203 :         conn->asyncStatus != PGASYNC_COPY_OUT &&
 4895 rhaas@postgresql.org     2091         [ #  # ]:UBC           0 :         conn->asyncStatus != PGASYNC_COPY_BOTH)
                               2092                 :                :     {
 1405 peter@eisentraut.org     2093                 :              0 :         libpq_append_conn_error(conn, "no COPY in progress");
 8505 tgl@sss.pgh.pa.us        2094                 :              0 :         return 1;
                               2095                 :                :     }
                               2096                 :                : 
                               2097                 :                :     /* Send the CopyDone message if needed */
 4895 rhaas@postgresql.org     2098         [ +  + ]:CBC         210 :     if (conn->asyncStatus == PGASYNC_COPY_IN ||
                               2099         [ -  + ]:            203 :         conn->asyncStatus == PGASYNC_COPY_BOTH)
                               2100                 :                :     {
 1125 nathan@postgresql.or     2101   [ +  -  -  + ]:             14 :         if (pqPutMsgStart(PqMsg_CopyDone, conn) < 0 ||
 8505 tgl@sss.pgh.pa.us        2102                 :              7 :             pqPutMsgEnd(conn) < 0)
 8505 tgl@sss.pgh.pa.us        2103                 :UBC           0 :             return 1;
                               2104                 :                : 
                               2105                 :                :         /*
                               2106                 :                :          * If we sent the COPY command in extended-query mode, we must issue a
                               2107                 :                :          * Sync as well.
                               2108                 :                :          */
 2015 alvherre@alvh.no-ip.     2109         [ +  - ]:CBC           7 :         if (conn->cmd_queue_head &&
                               2110         [ -  + ]:              7 :             conn->cmd_queue_head->queryclass != PGQUERY_SIMPLE)
                               2111                 :                :         {
 1125 nathan@postgresql.or     2112   [ #  #  #  # ]:UBC           0 :             if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
 8439 tgl@sss.pgh.pa.us        2113                 :              0 :                 pqPutMsgEnd(conn) < 0)
                               2114                 :              0 :                 return 1;
                               2115                 :                :         }
                               2116                 :                :     }
                               2117                 :                : 
                               2118                 :                :     /*
                               2119                 :                :      * make sure no data is waiting to be sent, abort if we are non-blocking
                               2120                 :                :      * and the flush fails
                               2121                 :                :      */
 8505 tgl@sss.pgh.pa.us        2122   [ -  +  -  - ]:CBC         210 :     if (pqFlush(conn) && pqIsnonblocking(conn))
 7557 neilc@samurai.com        2123                 :UBC           0 :         return 1;
                               2124                 :                : 
                               2125                 :                :     /* Return to active duty */
 8505 tgl@sss.pgh.pa.us        2126                 :CBC         210 :     conn->asyncStatus = PGASYNC_BUSY;
                               2127                 :                : 
                               2128                 :                :     /*
                               2129                 :                :      * Non blocking connections may have to abort at this point.  If everyone
                               2130                 :                :      * played the game there should be no problem, but in error scenarios the
                               2131                 :                :      * expected messages may not have arrived yet.  (We are assuming that the
                               2132                 :                :      * backend's packetizing will ensure that CommandComplete arrives along
                               2133                 :                :      * with the CopyDone; are there corner cases where that doesn't happen?)
                               2134                 :                :      */
                               2135   [ -  +  -  - ]:            210 :     if (pqIsnonblocking(conn) && PQisBusy(conn))
 7557 neilc@samurai.com        2136                 :UBC           0 :         return 1;
                               2137                 :                : 
                               2138                 :                :     /* Wait for the completion response */
 8505 tgl@sss.pgh.pa.us        2139                 :CBC         210 :     result = PQgetResult(conn);
                               2140                 :                : 
                               2141                 :                :     /* Expecting a successful result */
                               2142   [ +  -  +  - ]:            210 :     if (result && result->resultStatus == PGRES_COMMAND_OK)
                               2143                 :                :     {
                               2144                 :            210 :         PQclear(result);
                               2145                 :            210 :         return 0;
                               2146                 :                :     }
                               2147                 :                : 
                               2148                 :                :     /*
                               2149                 :                :      * Trouble. For backwards-compatibility reasons, we issue the error
                               2150                 :                :      * message as if it were a notice (would be nice to get rid of this
                               2151                 :                :      * silliness, but too many apps probably don't handle errors from
                               2152                 :                :      * PQendcopy reasonably).  Note that the app can still obtain the error
                               2153                 :                :      * status from the PGconn object.
                               2154                 :                :      */
 8505 tgl@sss.pgh.pa.us        2155         [ #  # ]:UBC           0 :     if (conn->errorMessage.len > 0)
                               2156                 :                :     {
                               2157                 :                :         /* We have to strip the trailing newline ... pain in neck... */
 8448 bruce@momjian.us         2158                 :              0 :         char        svLast = conn->errorMessage.data[conn->errorMessage.len - 1];
                               2159                 :                : 
 8492 tgl@sss.pgh.pa.us        2160         [ #  # ]:              0 :         if (svLast == '\n')
 8448 bruce@momjian.us         2161                 :              0 :             conn->errorMessage.data[conn->errorMessage.len - 1] = '\0';
 8490 tgl@sss.pgh.pa.us        2162                 :              0 :         pqInternalNotice(&conn->noticeHooks, "%s", conn->errorMessage.data);
 8448 bruce@momjian.us         2163                 :              0 :         conn->errorMessage.data[conn->errorMessage.len - 1] = svLast;
                               2164                 :                :     }
                               2165                 :                : 
 8505 tgl@sss.pgh.pa.us        2166                 :              0 :     PQclear(result);
                               2167                 :                : 
                               2168                 :              0 :     return 1;
                               2169                 :                : }
                               2170                 :                : 
                               2171                 :                : 
                               2172                 :                : /*
                               2173                 :                :  * PQnfn - Send a function call to the POSTGRES backend.
                               2174                 :                :  *
                               2175                 :                :  * See fe-exec.c for documentation.
                               2176                 :                :  */
                               2177                 :                : PGresult *
 8505 tgl@sss.pgh.pa.us        2178                 :CBC        1343 : pqFunctionCall3(PGconn *conn, Oid fnid,
                               2179                 :                :                 int *result_buf, int buf_size, int *actual_result_len,
                               2180                 :                :                 int result_is_int,
                               2181                 :                :                 const PQArgBlock *args, int nargs)
                               2182                 :                : {
                               2183                 :           1343 :     bool        needInput = false;
                               2184                 :           1343 :     ExecStatusType status = PGRES_FATAL_ERROR;
                               2185                 :                :     char        id;
                               2186                 :                :     int         msgLength;
                               2187                 :                :     int         avail;
                               2188                 :                :     int         i;
                               2189                 :                : 
                               2190                 :                :     /* already validated by PQnfn */
 2015 alvherre@alvh.no-ip.     2191         [ -  + ]:           1343 :     Assert(conn->pipelineStatus == PQ_PIPELINE_OFF);
                               2192                 :                : 
                               2193                 :                :     /* PQnfn already validated connection state */
                               2194                 :                : 
 1125 nathan@postgresql.or     2195   [ +  -  +  - ]:           2686 :     if (pqPutMsgStart(PqMsg_FunctionCall, conn) < 0 ||
 8448 bruce@momjian.us         2196         [ +  - ]:           2686 :         pqPutInt(fnid, 4, conn) < 0 ||   /* function id */
 3378 tgl@sss.pgh.pa.us        2197         [ +  - ]:           2686 :         pqPutInt(1, 2, conn) < 0 || /* # of format codes */
                               2198         [ -  + ]:           2686 :         pqPutInt(1, 2, conn) < 0 || /* format code: BINARY */
 8448 bruce@momjian.us         2199                 :           1343 :         pqPutInt(nargs, 2, conn) < 0)    /* # of args */
                               2200                 :                :     {
                               2201                 :                :         /* error message should be set up already */
 8505 tgl@sss.pgh.pa.us        2202                 :UBC           0 :         return NULL;
                               2203                 :                :     }
                               2204                 :                : 
 8505 tgl@sss.pgh.pa.us        2205         [ +  + ]:CBC        3906 :     for (i = 0; i < nargs; ++i)
                               2206                 :                :     {                           /* len.int4 + contents     */
                               2207         [ -  + ]:           2563 :         if (pqPutInt(args[i].len, 4, conn))
 8505 tgl@sss.pgh.pa.us        2208                 :UBC           0 :             return NULL;
 8505 tgl@sss.pgh.pa.us        2209         [ -  + ]:CBC        2563 :         if (args[i].len == -1)
 8505 tgl@sss.pgh.pa.us        2210                 :UBC           0 :             continue;           /* it's NULL */
                               2211                 :                : 
 8505 tgl@sss.pgh.pa.us        2212         [ +  + ]:CBC        2563 :         if (args[i].isint)
                               2213                 :                :         {
                               2214         [ -  + ]:           1906 :             if (pqPutInt(args[i].u.integer, args[i].len, conn))
 8505 tgl@sss.pgh.pa.us        2215                 :UBC           0 :                 return NULL;
                               2216                 :                :         }
                               2217                 :                :         else
                               2218                 :                :         {
  500 heikki.linnakangas@i     2219         [ -  + ]:CBC         657 :             if (pqPutnchar(args[i].u.ptr, args[i].len, conn))
 8505 tgl@sss.pgh.pa.us        2220                 :UBC           0 :                 return NULL;
                               2221                 :                :         }
                               2222                 :                :     }
                               2223                 :                : 
 3378 tgl@sss.pgh.pa.us        2224         [ -  + ]:CBC        1343 :     if (pqPutInt(1, 2, conn) < 0)    /* result format code: BINARY */
 8505 tgl@sss.pgh.pa.us        2225                 :UBC           0 :         return NULL;
                               2226                 :                : 
 8505 tgl@sss.pgh.pa.us        2227   [ +  -  +  - ]:CBC        2686 :     if (pqPutMsgEnd(conn) < 0 ||
                               2228                 :           1343 :         pqFlush(conn))
 8505 tgl@sss.pgh.pa.us        2229                 :UBC           0 :         return NULL;
                               2230                 :                : 
                               2231                 :                :     for (;;)
                               2232                 :                :     {
 8505 tgl@sss.pgh.pa.us        2233         [ +  + ]:CBC        4245 :         if (needInput)
                               2234                 :                :         {
                               2235                 :                :             /* Wait for some data to arrive (or for the channel to close) */
 3322 peter_e@gmx.net          2236   [ +  -  +  - ]:           3118 :             if (pqWait(true, false, conn) ||
 8505 tgl@sss.pgh.pa.us        2237                 :           1559 :                 pqReadData(conn) < 0)
                               2238                 :                :                 break;
                               2239                 :                :         }
                               2240                 :                : 
                               2241                 :                :         /*
                               2242                 :                :          * Scan the message. If we run out of data, loop around to try again.
                               2243                 :                :          */
                               2244                 :           4245 :         needInput = true;
                               2245                 :                : 
                               2246                 :           4245 :         conn->inCursor = conn->inStart;
                               2247         [ +  + ]:           4245 :         if (pqGetc(&id, conn))
                               2248                 :           1343 :             continue;
                               2249         [ -  + ]:           2902 :         if (pqGetInt(&msgLength, 4, conn))
 8505 tgl@sss.pgh.pa.us        2250                 :UBC           0 :             continue;
                               2251                 :                : 
                               2252                 :                :         /*
                               2253                 :                :          * Try to validate message type/length here.  A length less than 4 is
                               2254                 :                :          * definitely broken.  Large lengths should only be believed for a few
                               2255                 :                :          * message types.
                               2256                 :                :          */
 8505 tgl@sss.pgh.pa.us        2257         [ -  + ]:CBC        2902 :         if (msgLength < 4)
                               2258                 :                :         {
 8505 tgl@sss.pgh.pa.us        2259                 :UBC           0 :             handleSyncLoss(conn, id, msgLength);
                               2260                 :              0 :             break;
                               2261                 :                :         }
 8302 tgl@sss.pgh.pa.us        2262   [ -  +  -  -  :CBC        2902 :         if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
                                     -  -  -  -  -  
                                     -  -  -  -  -  
                                        -  -  -  - ]
                               2263                 :                :         {
 8505 tgl@sss.pgh.pa.us        2264                 :UBC           0 :             handleSyncLoss(conn, id, msgLength);
                               2265                 :              0 :             break;
                               2266                 :                :         }
                               2267                 :                : 
                               2268                 :                :         /*
                               2269                 :                :          * Can't process if message body isn't all here yet.
                               2270                 :                :          */
 8505 tgl@sss.pgh.pa.us        2271                 :CBC        2902 :         msgLength -= 4;
                               2272                 :           2902 :         avail = conn->inEnd - conn->inCursor;
                               2273         [ +  + ]:           2902 :         if (avail < msgLength)
                               2274                 :                :         {
                               2275                 :                :             /*
                               2276                 :                :              * Before looping, enlarge the input buffer if needed to hold the
                               2277                 :                :              * whole message.  See notes in parseInput.
                               2278                 :                :              */
 6688                          2279         [ -  + ]:            216 :             if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
                               2280                 :                :                                      conn))
                               2281                 :                :             {
                               2282                 :                :                 /*
                               2283                 :                :                  * Abandon the connection.  There's not much else we can
                               2284                 :                :                  * safely do; we can't just ignore the message or we could
                               2285                 :                :                  * miss important changes to the connection state.
                               2286                 :                :                  * pqCheckInBufferSpace() already reported the error.
                               2287                 :                :                  */
  394 heikki.linnakangas@i     2288                 :UBC           0 :                 handleFatalError(conn);
 8505 tgl@sss.pgh.pa.us        2289                 :              0 :                 break;
                               2290                 :                :             }
 8505 tgl@sss.pgh.pa.us        2291                 :CBC         216 :             continue;
                               2292                 :                :         }
                               2293                 :                : 
                               2294                 :                :         /*
                               2295                 :                :          * We should see V or E response to the command, but might get N
                               2296                 :                :          * and/or A notices first. We also need to swallow the final Z before
                               2297                 :                :          * returning.
                               2298                 :                :          */
                               2299   [ +  -  -  -  :           2686 :         switch (id)
                                           +  -  - ]
                               2300                 :                :         {
  391 nathan@postgresql.or     2301                 :           1343 :             case PqMsg_FunctionCallResponse:
 8505 tgl@sss.pgh.pa.us        2302         [ -  + ]:           1343 :                 if (pqGetInt(actual_result_len, 4, conn))
 8505 tgl@sss.pgh.pa.us        2303                 :UBC           0 :                     continue;
 8505 tgl@sss.pgh.pa.us        2304         [ +  - ]:CBC        1343 :                 if (*actual_result_len != -1)
                               2305                 :                :                 {
                               2306         [ +  + ]:           1343 :                     if (result_is_int)
                               2307                 :                :                     {
                               2308         [ -  + ]:            878 :                         if (pqGetInt(result_buf, *actual_result_len, conn))
 8505 tgl@sss.pgh.pa.us        2309                 :UBC           0 :                             continue;
                               2310                 :                :                     }
                               2311                 :                :                     else
                               2312                 :                :                     {
                               2313                 :                :                         /*
                               2314                 :                :                          * If the server returned too much data for the
                               2315                 :                :                          * buffer, something fishy is going on.  Abandon ship.
                               2316                 :                :                          */
  132 nathan@postgresql.or     2317   [ +  -  -  + ]:CBC         465 :                         if (buf_size != -1 && *actual_result_len > buf_size)
                               2318                 :                :                         {
  132 nathan@postgresql.or     2319                 :UBC           0 :                             libpq_append_conn_error(conn, "server returned too much data");
                               2320                 :              0 :                             handleFatalError(conn);
                               2321                 :              0 :                             return pqPrepareAsyncResult(conn);
                               2322                 :                :                         }
                               2323                 :                : 
  500 heikki.linnakangas@i     2324         [ -  + ]:CBC         465 :                         if (pqGetnchar(result_buf,
 8505 tgl@sss.pgh.pa.us        2325                 :            465 :                                        *actual_result_len,
                               2326                 :                :                                        conn))
 8505 tgl@sss.pgh.pa.us        2327                 :UBC           0 :                             continue;
                               2328                 :                :                     }
                               2329                 :                :                 }
                               2330                 :                :                 /* correctly finished function result message */
 8505 tgl@sss.pgh.pa.us        2331                 :CBC        1343 :                 status = PGRES_COMMAND_OK;
                               2332                 :           1343 :                 break;
  391 nathan@postgresql.or     2333                 :UBC           0 :             case PqMsg_ErrorResponse:
 8505 tgl@sss.pgh.pa.us        2334         [ #  # ]:              0 :                 if (pqGetErrorNotice3(conn, true))
                               2335                 :              0 :                     continue;
                               2336                 :              0 :                 status = PGRES_FATAL_ERROR;
                               2337                 :              0 :                 break;
  391 nathan@postgresql.or     2338                 :              0 :             case PqMsg_NotificationResponse:
                               2339                 :                :                 /* handle notify and go back to processing return values */
 8505 tgl@sss.pgh.pa.us        2340         [ #  # ]:              0 :                 if (getNotify(conn))
                               2341                 :              0 :                     continue;
                               2342                 :              0 :                 break;
  391 nathan@postgresql.or     2343                 :              0 :             case PqMsg_NoticeResponse:
                               2344                 :                :                 /* handle notice and go back to processing return values */
 8505 tgl@sss.pgh.pa.us        2345         [ #  # ]:              0 :                 if (pqGetErrorNotice3(conn, false))
                               2346                 :              0 :                     continue;
                               2347                 :              0 :                 break;
  391 nathan@postgresql.or     2348                 :CBC        1343 :             case PqMsg_ReadyForQuery:
 8492 tgl@sss.pgh.pa.us        2349         [ -  + ]:           1343 :                 if (getReadyForQuery(conn))
 8505 tgl@sss.pgh.pa.us        2350                 :UBC           0 :                     continue;
                               2351                 :                : 
                               2352                 :                :                 /* consume the message */
  765 alvherre@alvh.no-ip.     2353                 :CBC        1343 :                 pqParseDone(conn, conn->inStart + 5 + msgLength);
                               2354                 :                : 
                               2355                 :                :                 /*
                               2356                 :                :                  * If we already have a result object (probably an error), use
                               2357                 :                :                  * that.  Otherwise, if we saw a function result message,
                               2358                 :                :                  * report COMMAND_OK.  Otherwise, the backend violated the
                               2359                 :                :                  * protocol, so complain.
                               2360                 :                :                  */
 1613 tgl@sss.pgh.pa.us        2361   [ +  -  +  - ]:           1343 :                 if (!pgHavePendingResult(conn))
                               2362                 :                :                 {
 1675                          2363         [ +  - ]:           1343 :                     if (status == PGRES_COMMAND_OK)
                               2364                 :                :                     {
                               2365                 :           1343 :                         conn->result = PQmakeEmptyPGresult(conn, status);
                               2366         [ -  + ]:           1343 :                         if (!conn->result)
                               2367                 :                :                         {
 1405 peter@eisentraut.org     2368                 :UBC           0 :                             libpq_append_conn_error(conn, "out of memory");
 1675 tgl@sss.pgh.pa.us        2369                 :              0 :                             pqSaveErrorResult(conn);
                               2370                 :                :                         }
                               2371                 :                :                     }
                               2372                 :                :                     else
                               2373                 :                :                     {
 1405 peter@eisentraut.org     2374                 :              0 :                         libpq_append_conn_error(conn, "protocol error: no function result");
 1675 tgl@sss.pgh.pa.us        2375                 :              0 :                         pqSaveErrorResult(conn);
                               2376                 :                :                     }
                               2377                 :                :                 }
                               2378                 :                :                 /* and we're out */
 1675 tgl@sss.pgh.pa.us        2379                 :CBC        1343 :                 return pqPrepareAsyncResult(conn);
  391 nathan@postgresql.or     2380                 :UBC           0 :             case PqMsg_ParameterStatus:
 8505 tgl@sss.pgh.pa.us        2381         [ #  # ]:              0 :                 if (getParameterStatus(conn))
                               2382                 :              0 :                     continue;
                               2383                 :              0 :                 break;
                               2384                 :              0 :             default:
                               2385                 :                :                 /* The backend violates the protocol. */
 1405 peter@eisentraut.org     2386                 :              0 :                 libpq_append_conn_error(conn, "protocol error: id=0x%x", id);
 8505 tgl@sss.pgh.pa.us        2387                 :              0 :                 pqSaveErrorResult(conn);
                               2388                 :                : 
                               2389                 :                :                 /*
                               2390                 :                :                  * We can't call parsing done due to the protocol violation
                               2391                 :                :                  * (so message tracing wouldn't work), but trust the specified
                               2392                 :                :                  * message length as what to skip.
                               2393                 :                :                  */
                               2394                 :              0 :                 conn->inStart += 5 + msgLength;
                               2395                 :              0 :                 return pqPrepareAsyncResult(conn);
                               2396                 :                :         }
                               2397                 :                : 
                               2398                 :                :         /*
                               2399                 :                :          * An error may have been triggered while processing the message, bail
                               2400                 :                :          * out
                               2401                 :                :          */
   47 fujii@postgresql.org     2402   [ -  +  -  - ]:CBC        1343 :         if (conn->error_result && conn->status == CONNECTION_BAD)
   47 fujii@postgresql.org     2403                 :UBC           0 :             return pqPrepareAsyncResult(conn);
                               2404                 :                : 
                               2405                 :                :         /* Completed parsing this message, keep going */
  765 alvherre@alvh.no-ip.     2406                 :CBC        1343 :         pqParseDone(conn, conn->inStart + 5 + msgLength);
 8505 tgl@sss.pgh.pa.us        2407                 :           1343 :         needInput = false;
                               2408                 :                :     }
                               2409                 :                : 
                               2410                 :                :     /*
                               2411                 :                :      * We fall out of the loop only upon failing to read data.
                               2412                 :                :      * conn->errorMessage has been set by pqWait or pqReadData. We want to
                               2413                 :                :      * append it to any already-received error message.
                               2414                 :                :      */
 8505 tgl@sss.pgh.pa.us        2415                 :UBC           0 :     pqSaveErrorResult(conn);
                               2416                 :              0 :     return pqPrepareAsyncResult(conn);
                               2417                 :                : }
                               2418                 :                : 
                               2419                 :                : 
                               2420                 :                : /*
                               2421                 :                :  * Construct startup packet
                               2422                 :                :  *
                               2423                 :                :  * Returns a malloc'd packet buffer, or NULL if out of memory
                               2424                 :                :  */
                               2425                 :                : char *
 8505 tgl@sss.pgh.pa.us        2426                 :CBC       16077 : pqBuildStartupPacket3(PGconn *conn, int *packetlen,
                               2427                 :                :                       const PQEnvironmentOption *options)
                               2428                 :                : {
                               2429                 :                :     char       *startpacket;
                               2430                 :                :     size_t      len;
                               2431                 :                : 
  314 jchampion@postgresql     2432                 :          16077 :     len = build_startup_packet(conn, NULL, options);
                               2433   [ +  -  -  + ]:          16077 :     if (len == 0 || len > INT_MAX)
  314 jchampion@postgresql     2434                 :UBC           0 :         return NULL;
                               2435                 :                : 
  314 jchampion@postgresql     2436                 :CBC       16077 :     *packetlen = len;
 8505 tgl@sss.pgh.pa.us        2437                 :          16077 :     startpacket = (char *) malloc(*packetlen);
                               2438         [ -  + ]:          16077 :     if (!startpacket)
 8505 tgl@sss.pgh.pa.us        2439                 :UBC           0 :         return NULL;
                               2440                 :                : 
  314 jchampion@postgresql     2441                 :CBC       16077 :     len = build_startup_packet(conn, startpacket, options);
                               2442         [ -  + ]:          16077 :     Assert(*packetlen == len);
                               2443                 :                : 
 8505 tgl@sss.pgh.pa.us        2444                 :          16077 :     return startpacket;
                               2445                 :                : }
                               2446                 :                : 
                               2447                 :                : /*
                               2448                 :                :  * Build a startup packet given a filled-in PGconn structure.
                               2449                 :                :  *
                               2450                 :                :  * We need to figure out how much space is needed, then fill it in.
                               2451                 :                :  * To avoid duplicate logic, this routine is called twice: the first time
                               2452                 :                :  * (with packet == NULL) just counts the space needed, the second time
                               2453                 :                :  * (with packet == allocated space) fills it in.  Return value is the number
                               2454                 :                :  * of bytes used, or zero in the unlikely event of size_t overflow.
                               2455                 :                :  */
                               2456                 :                : static size_t
                               2457                 :          32154 : build_startup_packet(const PGconn *conn, char *packet,
                               2458                 :                :                      const PQEnvironmentOption *options)
                               2459                 :                : {
  314 jchampion@postgresql     2460                 :          32154 :     size_t      packet_len = 0;
                               2461                 :                :     const PQEnvironmentOption *next_eo;
                               2462                 :                :     const char *val;
                               2463                 :                : 
                               2464                 :                :     /* Protocol version comes first. */
 8505 tgl@sss.pgh.pa.us        2465         [ +  + ]:          32154 :     if (packet)
                               2466                 :                :     {
 3276 andres@anarazel.de       2467                 :          16077 :         ProtocolVersion pv = pg_hton32(conn->pversion);
                               2468                 :                : 
 8505 tgl@sss.pgh.pa.us        2469                 :          16077 :         memcpy(packet + packet_len, &pv, sizeof(ProtocolVersion));
                               2470                 :                :     }
                               2471                 :          32154 :     packet_len += sizeof(ProtocolVersion);
                               2472                 :                : 
                               2473                 :                :     /* Add user name, database name, options */
                               2474                 :                : 
                               2475                 :                : #define ADD_STARTUP_OPTION(optname, optval) \
                               2476                 :                :     do { \
                               2477                 :                :         if (packet) \
                               2478                 :                :             strcpy(packet + packet_len, optname); \
                               2479                 :                :         if (pg_add_size_overflow(packet_len, strlen(optname) + 1, &packet_len)) \
                               2480                 :                :             return 0; \
                               2481                 :                :         if (packet) \
                               2482                 :                :             strcpy(packet + packet_len, optval); \
                               2483                 :                :         if (pg_add_size_overflow(packet_len, strlen(optval) + 1, &packet_len)) \
                               2484                 :                :             return 0; \
                               2485                 :                :     } while(0)
                               2486                 :                : 
                               2487   [ +  -  +  - ]:          32154 :     if (conn->pguser && conn->pguser[0])
 6136                          2488   [ +  +  -  +  :          32154 :         ADD_STARTUP_OPTION("user", conn->pguser);
                                        +  +  -  + ]
 8505                          2489   [ +  -  +  - ]:          32154 :     if (conn->dbName && conn->dbName[0])
 6136                          2490   [ +  +  -  +  :          32154 :         ADD_STARTUP_OPTION("database", conn->dbName);
                                        +  +  -  + ]
 5989 magnus@hagander.net      2491   [ +  +  +  + ]:          32154 :     if (conn->replication && conn->replication[0])
 6092 heikki.linnakangas@i     2492   [ +  +  -  +  :           3576 :         ADD_STARTUP_OPTION("replication", conn->replication);
                                        +  +  -  + ]
 8505 tgl@sss.pgh.pa.us        2493   [ +  -  +  + ]:          32154 :     if (conn->pgoptions && conn->pgoptions[0])
 6136                          2494   [ +  +  -  +  :           9174 :         ADD_STARTUP_OPTION("options", conn->pgoptions);
                                        +  +  -  + ]
                               2495         [ +  - ]:          32154 :     if (conn->send_appname)
                               2496                 :                :     {
                               2497                 :                :         /* Use appname if present, otherwise use fallback */
                               2498         [ +  + ]:          32154 :         val = conn->appname ? conn->appname : conn->fbappname;
                               2499   [ +  +  +  - ]:          32154 :         if (val && val[0])
                               2500   [ +  +  -  +  :          32148 :             ADD_STARTUP_OPTION("application_name", val);
                                        +  +  -  + ]
                               2501                 :                :     }
                               2502                 :                : 
 5692 peter_e@gmx.net          2503   [ +  +  +  - ]:          32154 :     if (conn->client_encoding_initial && conn->client_encoding_initial[0])
                               2504   [ +  +  -  +  :           1906 :         ADD_STARTUP_OPTION("client_encoding", conn->client_encoding_initial);
                                        +  +  -  + ]
                               2505                 :                : 
                               2506                 :                :     /* Add any environment-driven GUC settings needed */
 8505 tgl@sss.pgh.pa.us        2507         [ +  + ]:         128616 :     for (next_eo = options; next_eo->envName; next_eo++)
                               2508                 :                :     {
                               2509         [ +  + ]:          96462 :         if ((val = getenv(next_eo->envName)) != NULL)
                               2510                 :                :         {
 8171                          2511         [ +  - ]:          10920 :             if (pg_strcasecmp(val, "default") != 0)
 6136                          2512   [ +  +  -  +  :          10920 :                 ADD_STARTUP_OPTION(next_eo->pgName, val);
                                        +  +  -  + ]
                               2513                 :                :         }
                               2514                 :                :     }
                               2515                 :                : 
                               2516                 :                :     /* Add trailing terminator */
 8505                          2517         [ +  + ]:          32154 :     if (packet)
                               2518                 :          16077 :         packet[packet_len] = '\0';
  300 jchampion@postgresql     2519         [ -  + ]:          32154 :     if (pg_add_size_overflow(packet_len, 1, &packet_len))
  314 jchampion@postgresql     2520                 :UBC           0 :         return 0;
                               2521                 :                : 
 8505 tgl@sss.pgh.pa.us        2522                 :CBC       32154 :     return packet_len;
                               2523                 :                : }
        

Generated by: LCOV version 2.0-1