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: c70b6db34ffeab48beef1fb4ce61bcad3772b8dd vs 06473f5a344df8c9594ead90a609b86f6724cff8 Lines: 62.3 % 981 611 4 366 2 609 4 2
Current Date: 2025-09-06 07:49:51 +0900 Functions: 78.3 % 23 18 5 1 17
Baseline: lcov-20250906-005545-baseline Branches: 57.0 % 798 455 343 455
Baseline Date: 2025-09-05 08:21:35 +0100 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 32.7 % 52 17 4 31 2 15
(30,360] days: 20.7 % 58 12 46 12
(360..) days: 66.8 % 871 582 289 582
Function coverage date bins:
(7,30] days: 0.0 % 2 0 2
(30,360] days: 100.0 % 1 1 1
(360..) days: 85.0 % 20 17 3 1 16
Branch coverage date bins:
(7,30] days: 50.0 % 18 9 9 9
(30,360] days: 19.4 % 36 7 29 7
(360..) days: 59.0 % 744 439 305 439

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

Generated by: LCOV version 2.4-beta