LCOV - code coverage report
Current view: top level - src/interfaces/libpq - fe-protocol3.c (source / functions) Hit Total Coverage
Test: PostgreSQL 17devel Lines: 602 927 64.9 %
Date: 2024-04-19 03:11:37 Functions: 17 21 81.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14