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

Generated by: LCOV version 1.14