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

Generated by: LCOV version 1.13