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

Generated by: LCOV version 1.14