LCOV - differential code coverage report
Current view: top level - src/interfaces/libpq - fe-protocol3.c (source / functions) Coverage Total Hit UNC UBC GNC CBC DUB DCB
Current: 7a15cff1f11193467898da1c1fabf06fd2caee04 vs 84a3778c79c2d28b4dc281d03ef2ab019b16483b Lines: 62.2 % 989 615 4 370 3 612 5 8
Current Date: 2025-12-15 18:36:29 -0500 Functions: 78.3 % 23 18 5 2 16 1
Baseline: lcov-20251216-010103-baseline Branches: 56.7 % 836 474 1 361 1 473
Baseline Date: 2025-12-15 13:30:48 -0800 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 1 1 1
(30,360] days: 29.8 % 121 36 4 81 2 34
(360..) days: 66.7 % 867 578 289 578
Function coverage date bins:
(30,360] days: 33.3 % 3 1 2 1
(360..) days: 85.0 % 20 17 3 2 15
Branch coverage date bins:
(7,30] days: 50.0 % 2 1 1 1
(30,360] days: 32.3 % 62 20 42 20
(360..) days: 58.7 % 772 453 319 453

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

Generated by: LCOV version 2.4-beta