PostgreSQL Source Code  git master
fe-protocol3.c File Reference
#include "postgres_fe.h"
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
#include <netinet/tcp.h>
#include "libpq-fe.h"
#include "libpq-int.h"
#include "mb/pg_wchar.h"
#include "port/pg_bswap.h"
Include dependency graph for fe-protocol3.c:

Go to the source code of this file.

Macros

#define VALID_LONG_MESSAGE_TYPE(id)
 
#define DISPLAY_SIZE   60 /* screen width limit, in screen cols */
 
#define MIN_RIGHT_CUT   10 /* try to keep this far away from EOL */
 
#define ADD_STARTUP_OPTION(optname, optval)
 

Functions

static void handleSyncLoss (PGconn *conn, char id, int msgLength)
 
static int getRowDescriptions (PGconn *conn, int msgLength)
 
static int getParamDescriptions (PGconn *conn, int msgLength)
 
static int getAnotherTuple (PGconn *conn, int msgLength)
 
static int getParameterStatus (PGconn *conn)
 
static int getNotify (PGconn *conn)
 
static int getCopyStart (PGconn *conn, ExecStatusType copytype)
 
static int getReadyForQuery (PGconn *conn)
 
static void reportErrorPosition (PQExpBuffer msg, const char *query, int loc, int encoding)
 
static int build_startup_packet (const PGconn *conn, char *packet, const PQEnvironmentOption *options)
 
void pqParseInput3 (PGconn *conn)
 
int pqGetErrorNotice3 (PGconn *conn, bool isError)
 
void pqBuildErrorMessage3 (PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
 
int pqGetNegotiateProtocolVersion3 (PGconn *conn)
 
static int getCopyDataMessage (PGconn *conn)
 
int pqGetCopyData3 (PGconn *conn, char **buffer, int async)
 
int pqGetline3 (PGconn *conn, char *s, int maxlen)
 
int pqGetlineAsync3 (PGconn *conn, char *buffer, int bufsize)
 
int pqEndcopy3 (PGconn *conn)
 
PGresultpqFunctionCall3 (PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
 
char * pqBuildStartupPacket3 (PGconn *conn, int *packetlen, const PQEnvironmentOption *options)
 

Macro Definition Documentation

◆ ADD_STARTUP_OPTION

#define ADD_STARTUP_OPTION (   optname,
  optval 
)
Value:
do { \
if (packet) \
strcpy(packet + packet_len, optname); \
packet_len += strlen(optname) + 1; \
if (packet) \
strcpy(packet + packet_len, optval); \
packet_len += strlen(optval) + 1; \
} while(0)

◆ DISPLAY_SIZE

#define DISPLAY_SIZE   60 /* screen width limit, in screen cols */

◆ MIN_RIGHT_CUT

#define MIN_RIGHT_CUT   10 /* try to keep this far away from EOL */

◆ VALID_LONG_MESSAGE_TYPE

#define VALID_LONG_MESSAGE_TYPE (   id)
Value:
((id) == 'T' || (id) == 'D' || (id) == 'd' || (id) == 'V' || \
(id) == 'E' || (id) == 'N' || (id) == 'A')

Definition at line 36 of file fe-protocol3.c.

Function Documentation

◆ build_startup_packet()

static int build_startup_packet ( const PGconn conn,
char *  packet,
const PQEnvironmentOption options 
)
static

Definition at line 2242 of file fe-protocol3.c.

2244 {
2245  int packet_len = 0;
2246  const PQEnvironmentOption *next_eo;
2247  const char *val;
2248 
2249  /* Protocol version comes first. */
2250  if (packet)
2251  {
2253 
2254  memcpy(packet + packet_len, &pv, sizeof(ProtocolVersion));
2255  }
2256  packet_len += sizeof(ProtocolVersion);
2257 
2258  /* Add user name, database name, options */
2259 
2260 #define ADD_STARTUP_OPTION(optname, optval) \
2261  do { \
2262  if (packet) \
2263  strcpy(packet + packet_len, optname); \
2264  packet_len += strlen(optname) + 1; \
2265  if (packet) \
2266  strcpy(packet + packet_len, optval); \
2267  packet_len += strlen(optval) + 1; \
2268  } while(0)
2269 
2270  if (conn->pguser && conn->pguser[0])
2271  ADD_STARTUP_OPTION("user", conn->pguser);
2272  if (conn->dbName && conn->dbName[0])
2273  ADD_STARTUP_OPTION("database", conn->dbName);
2274  if (conn->replication && conn->replication[0])
2275  ADD_STARTUP_OPTION("replication", conn->replication);
2276  if (conn->pgoptions && conn->pgoptions[0])
2277  ADD_STARTUP_OPTION("options", conn->pgoptions);
2278  if (conn->send_appname)
2279  {
2280  /* Use appname if present, otherwise use fallback */
2282  if (val && val[0])
2283  ADD_STARTUP_OPTION("application_name", val);
2284  }
2285 
2287  ADD_STARTUP_OPTION("client_encoding", conn->client_encoding_initial);
2288 
2289  /* Add any environment-driven GUC settings needed */
2290  for (next_eo = options; next_eo->envName; next_eo++)
2291  {
2292  if ((val = getenv(next_eo->envName)) != NULL)
2293  {
2294  if (pg_strcasecmp(val, "default") != 0)
2295  ADD_STARTUP_OPTION(next_eo->pgName, val);
2296  }
2297  }
2298 
2299  /* Add trailing terminator */
2300  if (packet)
2301  packet[packet_len] = '\0';
2302  packet_len++;
2303 
2304  return packet_len;
2305 }
#define ADD_STARTUP_OPTION(optname, optval)
long val
Definition: informix.c:664
#define pg_hton32(x)
Definition: pg_bswap.h:121
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
uint32 ProtocolVersion
Definition: pqcomm.h:87
PGconn * conn
Definition: streamutil.c:54
const char * pgName
Definition: libpq-int.h:257
const char * envName
Definition: libpq-int.h:256
char * replication
Definition: libpq-int.h:370
ProtocolVersion pversion
Definition: libpq-int.h:453
char * pgoptions
Definition: libpq-int.h:366
bool send_appname
Definition: libpq-int.h:477
char * dbName
Definition: libpq-int.h:369
char * fbappname
Definition: libpq-int.h:368
char * pguser
Definition: libpq-int.h:371
char * client_encoding_initial
Definition: libpq-int.h:365
char * appname
Definition: libpq-int.h:367

References ADD_STARTUP_OPTION, pg_conn::appname, pg_conn::client_encoding_initial, conn, pg_conn::dbName, PQEnvironmentOption::envName, pg_conn::fbappname, pg_hton32, pg_strcasecmp(), PQEnvironmentOption::pgName, pg_conn::pgoptions, pg_conn::pguser, pg_conn::pversion, pg_conn::replication, pg_conn::send_appname, and val.

Referenced by pqBuildStartupPacket3().

◆ getAnotherTuple()

static int getAnotherTuple ( PGconn conn,
int  msgLength 
)
static

Definition at line 745 of file fe-protocol3.c.

746 {
747  PGresult *result = conn->result;
748  int nfields = result->numAttributes;
749  const char *errmsg;
750  PGdataValue *rowbuf;
751  int tupnfields; /* # fields from tuple */
752  int vlen; /* length of the current field value */
753  int i;
754 
755  /* Get the field count and make sure it's what we expect */
756  if (pqGetInt(&tupnfields, 2, conn))
757  {
758  /* We should not run out of data here, so complain */
759  errmsg = libpq_gettext("insufficient data in \"D\" message");
760  goto advance_and_error;
761  }
762 
763  if (tupnfields != nfields)
764  {
765  errmsg = libpq_gettext("unexpected field count in \"D\" message");
766  goto advance_and_error;
767  }
768 
769  /* Resize row buffer if needed */
770  rowbuf = conn->rowBuf;
771  if (nfields > conn->rowBufLen)
772  {
773  rowbuf = (PGdataValue *) realloc(rowbuf,
774  nfields * sizeof(PGdataValue));
775  if (!rowbuf)
776  {
777  errmsg = NULL; /* means "out of memory", see below */
778  goto advance_and_error;
779  }
780  conn->rowBuf = rowbuf;
781  conn->rowBufLen = nfields;
782  }
783 
784  /* Scan the fields */
785  for (i = 0; i < nfields; i++)
786  {
787  /* get the value length */
788  if (pqGetInt(&vlen, 4, conn))
789  {
790  /* We should not run out of data here, so complain */
791  errmsg = libpq_gettext("insufficient data in \"D\" message");
792  goto advance_and_error;
793  }
794  rowbuf[i].len = vlen;
795 
796  /*
797  * rowbuf[i].value always points to the next address in the data
798  * buffer even if the value is NULL. This allows row processors to
799  * estimate data sizes more easily.
800  */
801  rowbuf[i].value = conn->inBuffer + conn->inCursor;
802 
803  /* Skip over the data value */
804  if (vlen > 0)
805  {
806  if (pqSkipnchar(vlen, conn))
807  {
808  /* We should not run out of data here, so complain */
809  errmsg = libpq_gettext("insufficient data in \"D\" message");
810  goto advance_and_error;
811  }
812  }
813  }
814 
815  /* Process the collected row */
816  errmsg = NULL;
817  if (pqRowProcessor(conn, &errmsg))
818  return 0; /* normal, successful exit */
819 
820  /* pqRowProcessor failed, fall through to report it */
821 
822 advance_and_error:
823 
824  /*
825  * Replace partially constructed result with an error result. First
826  * discard the old result to try to win back some memory.
827  */
829 
830  /*
831  * If preceding code didn't provide an error message, assume "out of
832  * memory" was meant. The advantage of having this special case is that
833  * freeing the old result first greatly improves the odds that gettext()
834  * will succeed in providing a translation.
835  */
836  if (!errmsg)
837  errmsg = libpq_gettext("out of memory for query result");
838 
841 
842  /*
843  * Show the message as fully consumed, else pqParseInput3 will overwrite
844  * our error with a complaint about that.
845  */
846  conn->inCursor = conn->inStart + 5 + msgLength;
847 
848  /*
849  * Return zero to allow input parsing to continue. Subsequent "D"
850  * messages will be ignored until we get to end of data, since an error
851  * result is already set up.
852  */
853  return 0;
854 }
int errmsg(const char *fmt,...)
Definition: elog.c:1069
void pqSaveErrorResult(PGconn *conn)
Definition: fe-exec.c:800
int pqRowProcessor(PGconn *conn, const char **errmsgp)
Definition: fe-exec.c:1202
void pqClearAsyncResult(PGconn *conn)
Definition: fe-exec.c:776
int pqSkipnchar(size_t len, PGconn *conn)
Definition: fe-misc.c:188
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:217
#define realloc(a, b)
Definition: header.h:60
int i
Definition: isn.c:73
#define libpq_gettext(x)
Definition: libpq-int.h:894
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
const char * value
Definition: libpq-int.h:295
PGdataValue * rowBuf
Definition: libpq-int.h:509
char * inBuffer
Definition: libpq-int.h:492
int inCursor
Definition: libpq-int.h:495
int inStart
Definition: libpq-int.h:494
PGresult * result
Definition: libpq-int.h:521
PQExpBufferData errorMessage
Definition: libpq-int.h:600
int rowBufLen
Definition: libpq-int.h:510
int numAttributes
Definition: libpq-int.h:172

References appendPQExpBuffer(), conn, errmsg(), pg_conn::errorMessage, i, pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inStart, pgDataValue::len, libpq_gettext, pg_result::numAttributes, pqClearAsyncResult(), pqGetInt(), pqRowProcessor(), pqSaveErrorResult(), pqSkipnchar(), realloc, pg_conn::result, pg_conn::rowBuf, pg_conn::rowBufLen, and pgDataValue::value.

Referenced by pqParseInput3().

◆ getCopyDataMessage()

static int getCopyDataMessage ( PGconn conn)
static

Definition at line 1624 of file fe-protocol3.c.

1625 {
1626  char id;
1627  int msgLength;
1628  int avail;
1629 
1630  for (;;)
1631  {
1632  /*
1633  * Do we have the next input message? To make life simpler for async
1634  * callers, we keep returning 0 until the next message is fully
1635  * available, even if it is not Copy Data.
1636  */
1637  conn->inCursor = conn->inStart;
1638  if (pqGetc(&id, conn))
1639  return 0;
1640  if (pqGetInt(&msgLength, 4, conn))
1641  return 0;
1642  if (msgLength < 4)
1643  {
1644  handleSyncLoss(conn, id, msgLength);
1645  return -2;
1646  }
1647  avail = conn->inEnd - conn->inCursor;
1648  if (avail < msgLength - 4)
1649  {
1650  /*
1651  * Before returning, enlarge the input buffer if needed to hold
1652  * the whole message. See notes in parseInput.
1653  */
1654  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength - 4,
1655  conn))
1656  {
1657  /*
1658  * XXX add some better recovery code... plan is to skip over
1659  * the message using its length, then report an error. For the
1660  * moment, just treat this like loss of sync (which indeed it
1661  * might be!)
1662  */
1663  handleSyncLoss(conn, id, msgLength);
1664  return -2;
1665  }
1666  return 0;
1667  }
1668 
1669  /*
1670  * If it's a legitimate async message type, process it. (NOTIFY
1671  * messages are not currently possible here, but we handle them for
1672  * completeness.) Otherwise, if it's anything except Copy Data,
1673  * report end-of-copy.
1674  */
1675  switch (id)
1676  {
1677  case 'A': /* NOTIFY */
1678  if (getNotify(conn))
1679  return 0;
1680  break;
1681  case 'N': /* NOTICE */
1682  if (pqGetErrorNotice3(conn, false))
1683  return 0;
1684  break;
1685  case 'S': /* ParameterStatus */
1686  if (getParameterStatus(conn))
1687  return 0;
1688  break;
1689  case 'd': /* Copy Data, pass it back to caller */
1690  return msgLength;
1691  case 'c':
1692 
1693  /*
1694  * If this is a CopyDone message, exit COPY_OUT mode and let
1695  * caller read status with PQgetResult(). If we're in
1696  * COPY_BOTH mode, return to COPY_IN mode.
1697  */
1700  else
1702  return -1;
1703  default: /* treat as end of copy */
1704 
1705  /*
1706  * Any other message terminates either COPY_IN or COPY_BOTH
1707  * mode.
1708  */
1710  return -1;
1711  }
1712 
1713  /* trace server-to-client message */
1714  if (conn->Pfdebug)
1716 
1717  /* Drop the processed message and loop around for another */
1718  conn->inStart = conn->inCursor;
1719  }
1720 }
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:78
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:352
static int getNotify(PGconn *conn)
static int getParameterStatus(PGconn *conn)
static void handleSyncLoss(PGconn *conn, char id, int msgLength)
Definition: fe-protocol3.c:466
int pqGetErrorNotice3(PGconn *conn, bool isError)
Definition: fe-protocol3.c:865
void pqTraceOutputMessage(PGconn *conn, const char *message, bool toServer)
Definition: fe-trace.c:529
@ PGASYNC_COPY_BOTH
Definition: libpq-int.h:229
@ PGASYNC_COPY_IN
Definition: libpq-int.h:227
@ PGASYNC_BUSY
Definition: libpq-int.h:221
int inEnd
Definition: libpq-int.h:496
PGAsyncStatusType asyncStatus
Definition: libpq-int.h:416
FILE * Pfdebug
Definition: libpq-int.h:403

References pg_conn::asyncStatus, conn, getNotify(), getParameterStatus(), handleSyncLoss(), pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, pg_conn::Pfdebug, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, pqCheckInBufferSpace(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), and pqTraceOutputMessage().

Referenced by pqGetCopyData3(), and pqGetlineAsync3().

◆ getCopyStart()

static int getCopyStart ( PGconn conn,
ExecStatusType  copytype 
)
static

Definition at line 1536 of file fe-protocol3.c.

1537 {
1538  PGresult *result;
1539  int nfields;
1540  int i;
1541 
1542  result = PQmakeEmptyPGresult(conn, copytype);
1543  if (!result)
1544  goto failure;
1545 
1546  if (pqGetc(&conn->copy_is_binary, conn))
1547  goto failure;
1548  result->binary = conn->copy_is_binary;
1549  /* the next two bytes are the number of fields */
1550  if (pqGetInt(&(result->numAttributes), 2, conn))
1551  goto failure;
1552  nfields = result->numAttributes;
1553 
1554  /* allocate space for the attribute descriptors */
1555  if (nfields > 0)
1556  {
1557  result->attDescs = (PGresAttDesc *)
1558  pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
1559  if (!result->attDescs)
1560  goto failure;
1561  MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
1562  }
1563 
1564  for (i = 0; i < nfields; i++)
1565  {
1566  int format;
1567 
1568  if (pqGetInt(&format, 2, conn))
1569  goto failure;
1570 
1571  /*
1572  * Since pqGetInt treats 2-byte integers as unsigned, we need to
1573  * coerce these results to signed form.
1574  */
1575  format = (int) ((int16) format);
1576  result->attDescs[i].format = format;
1577  }
1578 
1579  /* Success! */
1580  conn->result = result;
1581  return 0;
1582 
1583 failure:
1584  PQclear(result);
1585  return EOF;
1586 }
signed short int16
Definition: c.h:477
#define MemSet(start, val, len)
Definition: c.h:1004
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition: fe-exec.c:157
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition: fe-exec.c:560
static char format
char copy_is_binary
Definition: libpq-int.h:424
int binary
Definition: libpq-int.h:181
PGresAttDesc * attDescs
Definition: libpq-int.h:173

References pg_result::attDescs, pg_result::binary, conn, pg_conn::copy_is_binary, format, pgresAttDesc::format, i, MemSet, pg_result::numAttributes, PQclear(), pqGetc(), pqGetInt(), PQmakeEmptyPGresult(), pqResultAlloc(), and pg_conn::result.

Referenced by pqParseInput3().

◆ getNotify()

static int getNotify ( PGconn conn)
static

Definition at line 1480 of file fe-protocol3.c.

1481 {
1482  int be_pid;
1483  char *svname;
1484  int nmlen;
1485  int extralen;
1486  PGnotify *newNotify;
1487 
1488  if (pqGetInt(&be_pid, 4, conn))
1489  return EOF;
1490  if (pqGets(&conn->workBuffer, conn))
1491  return EOF;
1492  /* must save name while getting extra string */
1493  svname = strdup(conn->workBuffer.data);
1494  if (!svname)
1495  return EOF;
1496  if (pqGets(&conn->workBuffer, conn))
1497  {
1498  free(svname);
1499  return EOF;
1500  }
1501 
1502  /*
1503  * Store the strings right after the PQnotify structure so it can all be
1504  * freed at once. We don't use NAMEDATALEN because we don't want to tie
1505  * this interface to a specific server name length.
1506  */
1507  nmlen = strlen(svname);
1508  extralen = strlen(conn->workBuffer.data);
1509  newNotify = (PGnotify *) malloc(sizeof(PGnotify) + nmlen + extralen + 2);
1510  if (newNotify)
1511  {
1512  newNotify->relname = (char *) newNotify + sizeof(PGnotify);
1513  strcpy(newNotify->relname, svname);
1514  newNotify->extra = newNotify->relname + nmlen + 1;
1515  strcpy(newNotify->extra, conn->workBuffer.data);
1516  newNotify->be_pid = be_pid;
1517  newNotify->next = NULL;
1518  if (conn->notifyTail)
1519  conn->notifyTail->next = newNotify;
1520  else
1521  conn->notifyHead = newNotify;
1522  conn->notifyTail = newNotify;
1523  }
1524 
1525  free(svname);
1526  return 0;
1527 }
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:137
#define free(a)
Definition: header.h:65
#define malloc(a)
Definition: header.h:50
struct pgNotify * next
Definition: libpq-fe.h:193
int be_pid
Definition: libpq-fe.h:190
char * relname
Definition: libpq-fe.h:189
char * extra
Definition: libpq-fe.h:191
PGnotify * notifyHead
Definition: libpq-int.h:426
PGnotify * notifyTail
Definition: libpq-int.h:427
PQExpBufferData workBuffer
Definition: libpq-int.h:604

References pgNotify::be_pid, conn, PQExpBufferData::data, pgNotify::extra, free, malloc, pgNotify::next, pg_conn::notifyHead, pg_conn::notifyTail, pqGetInt(), pqGets(), pgNotify::relname, and pg_conn::workBuffer.

Referenced by getCopyDataMessage(), pqFunctionCall3(), and pqParseInput3().

◆ getParamDescriptions()

static int getParamDescriptions ( PGconn conn,
int  msgLength 
)
static

Definition at line 657 of file fe-protocol3.c.

658 {
659  PGresult *result;
660  const char *errmsg = NULL; /* means "out of memory", see below */
661  int nparams;
662  int i;
663 
665  if (!result)
666  goto advance_and_error;
667 
668  /* parseInput already read the 't' label and message length. */
669  /* the next two bytes are the number of parameters */
670  if (pqGetInt(&(result->numParameters), 2, conn))
671  goto not_enough_data;
672  nparams = result->numParameters;
673 
674  /* allocate space for the parameter descriptors */
675  if (nparams > 0)
676  {
677  result->paramDescs = (PGresParamDesc *)
678  pqResultAlloc(result, nparams * sizeof(PGresParamDesc), true);
679  if (!result->paramDescs)
680  goto advance_and_error;
681  MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
682  }
683 
684  /* get parameter info */
685  for (i = 0; i < nparams; i++)
686  {
687  int typid;
688 
689  if (pqGetInt(&typid, 4, conn))
690  goto not_enough_data;
691  result->paramDescs[i].typid = typid;
692  }
693 
694  /* Success! */
695  conn->result = result;
696 
697  return 0;
698 
699 not_enough_data:
700  errmsg = libpq_gettext("insufficient data in \"t\" message");
701 
702 advance_and_error:
703  /* Discard unsaved result, if any */
704  if (result && result != conn->result)
705  PQclear(result);
706 
707  /*
708  * Replace partially constructed result with an error result. First
709  * discard the old result to try to win back some memory.
710  */
712 
713  /*
714  * If preceding code didn't provide an error message, assume "out of
715  * memory" was meant. The advantage of having this special case is that
716  * freeing the old result first greatly improves the odds that gettext()
717  * will succeed in providing a translation.
718  */
719  if (!errmsg)
720  errmsg = libpq_gettext("out of memory");
723 
724  /*
725  * Show the message as fully consumed, else pqParseInput3 will overwrite
726  * our error with a complaint about that.
727  */
728  conn->inCursor = conn->inStart + 5 + msgLength;
729 
730  /*
731  * Return zero to allow input parsing to continue. Essentially, we've
732  * replaced the COMMAND_OK result with an error result, but since this
733  * doesn't affect the protocol state, it's fine.
734  */
735  return 0;
736 }
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:97
int numParameters
Definition: libpq-int.h:177
PGresParamDesc * paramDescs
Definition: libpq-int.h:178

References appendPQExpBuffer(), conn, errmsg(), pg_conn::errorMessage, i, pg_conn::inCursor, pg_conn::inStart, libpq_gettext, MemSet, pg_result::numParameters, pg_result::paramDescs, PGRES_COMMAND_OK, PQclear(), pqClearAsyncResult(), pqGetInt(), PQmakeEmptyPGresult(), pqResultAlloc(), pqSaveErrorResult(), pg_conn::result, and pgresParamDesc::typid.

Referenced by pqParseInput3().

◆ getParameterStatus()

static int getParameterStatus ( PGconn conn)
static

Definition at line 1451 of file fe-protocol3.c.

1452 {
1453  PQExpBufferData valueBuf;
1454 
1455  /* Get the parameter name */
1456  if (pqGets(&conn->workBuffer, conn))
1457  return EOF;
1458  /* Get the parameter value (could be large) */
1459  initPQExpBuffer(&valueBuf);
1460  if (pqGets(&valueBuf, conn))
1461  {
1462  termPQExpBuffer(&valueBuf);
1463  return EOF;
1464  }
1465  /* And save it */
1467  termPQExpBuffer(&valueBuf);
1468  return 0;
1469 }
void pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
Definition: fe-exec.c:1076
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129

References conn, PQExpBufferData::data, initPQExpBuffer(), pqGets(), pqSaveParameterStatus(), termPQExpBuffer(), and pg_conn::workBuffer.

Referenced by getCopyDataMessage(), pqFunctionCall3(), and pqParseInput3().

◆ getReadyForQuery()

static int getReadyForQuery ( PGconn conn)
static

Definition at line 1592 of file fe-protocol3.c.

1593 {
1594  char xact_status;
1595 
1596  if (pqGetc(&xact_status, conn))
1597  return EOF;
1598  switch (xact_status)
1599  {
1600  case 'I':
1602  break;
1603  case 'T':
1605  break;
1606  case 'E':
1608  break;
1609  default:
1611  break;
1612  }
1613 
1614  return 0;
1615 }
@ PQTRANS_INTRANS
Definition: libpq-fe.h:120
@ PQTRANS_IDLE
Definition: libpq-fe.h:118
@ PQTRANS_UNKNOWN
Definition: libpq-fe.h:122
@ PQTRANS_INERROR
Definition: libpq-fe.h:121
PGTransactionStatusType xactStatus
Definition: libpq-int.h:417

References conn, pqGetc(), PQTRANS_IDLE, PQTRANS_INERROR, PQTRANS_INTRANS, PQTRANS_UNKNOWN, and pg_conn::xactStatus.

Referenced by pqFunctionCall3(), and pqParseInput3().

◆ getRowDescriptions()

static int getRowDescriptions ( PGconn conn,
int  msgLength 
)
static

Definition at line 486 of file fe-protocol3.c.

487 {
488  PGresult *result;
489  int nfields;
490  const char *errmsg;
491  int i;
492 
493  /*
494  * When doing Describe for a prepared statement, there'll already be a
495  * PGresult created by getParamDescriptions, and we should fill data into
496  * that. Otherwise, create a new, empty PGresult.
497  */
498  if (!conn->cmd_queue_head ||
499  (conn->cmd_queue_head &&
501  {
502  if (conn->result)
503  result = conn->result;
504  else
506  }
507  else
509  if (!result)
510  {
511  errmsg = NULL; /* means "out of memory", see below */
512  goto advance_and_error;
513  }
514 
515  /* parseInput already read the 'T' label and message length. */
516  /* the next two bytes are the number of fields */
517  if (pqGetInt(&(result->numAttributes), 2, conn))
518  {
519  /* We should not run out of data here, so complain */
520  errmsg = libpq_gettext("insufficient data in \"T\" message");
521  goto advance_and_error;
522  }
523  nfields = result->numAttributes;
524 
525  /* allocate space for the attribute descriptors */
526  if (nfields > 0)
527  {
528  result->attDescs = (PGresAttDesc *)
529  pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
530  if (!result->attDescs)
531  {
532  errmsg = NULL; /* means "out of memory", see below */
533  goto advance_and_error;
534  }
535  MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
536  }
537 
538  /* result->binary is true only if ALL columns are binary */
539  result->binary = (nfields > 0) ? 1 : 0;
540 
541  /* get type info */
542  for (i = 0; i < nfields; i++)
543  {
544  int tableid;
545  int columnid;
546  int typid;
547  int typlen;
548  int atttypmod;
549  int format;
550 
551  if (pqGets(&conn->workBuffer, conn) ||
552  pqGetInt(&tableid, 4, conn) ||
553  pqGetInt(&columnid, 2, conn) ||
554  pqGetInt(&typid, 4, conn) ||
555  pqGetInt(&typlen, 2, conn) ||
556  pqGetInt(&atttypmod, 4, conn) ||
557  pqGetInt(&format, 2, conn))
558  {
559  /* We should not run out of data here, so complain */
560  errmsg = libpq_gettext("insufficient data in \"T\" message");
561  goto advance_and_error;
562  }
563 
564  /*
565  * Since pqGetInt treats 2-byte integers as unsigned, we need to
566  * coerce these results to signed form.
567  */
568  columnid = (int) ((int16) columnid);
569  typlen = (int) ((int16) typlen);
570  format = (int) ((int16) format);
571 
572  result->attDescs[i].name = pqResultStrdup(result,
573  conn->workBuffer.data);
574  if (!result->attDescs[i].name)
575  {
576  errmsg = NULL; /* means "out of memory", see below */
577  goto advance_and_error;
578  }
579  result->attDescs[i].tableid = tableid;
580  result->attDescs[i].columnid = columnid;
581  result->attDescs[i].format = format;
582  result->attDescs[i].typid = typid;
583  result->attDescs[i].typlen = typlen;
584  result->attDescs[i].atttypmod = atttypmod;
585 
586  if (format != 1)
587  result->binary = 0;
588  }
589 
590  /* Success! */
591  conn->result = result;
592 
593  /*
594  * If we're doing a Describe, we're done, and ready to pass the result
595  * back to the client.
596  */
597  if ((!conn->cmd_queue_head) ||
598  (conn->cmd_queue_head &&
600  {
602  return 0;
603  }
604 
605  /*
606  * We could perform additional setup for the new result set here, but for
607  * now there's nothing else to do.
608  */
609 
610  /* And we're done. */
611  return 0;
612 
613 advance_and_error:
614  /* Discard unsaved result, if any */
615  if (result && result != conn->result)
616  PQclear(result);
617 
618  /*
619  * Replace partially constructed result with an error result. First
620  * discard the old result to try to win back some memory.
621  */
623 
624  /*
625  * If preceding code didn't provide an error message, assume "out of
626  * memory" was meant. The advantage of having this special case is that
627  * freeing the old result first greatly improves the odds that gettext()
628  * will succeed in providing a translation.
629  */
630  if (!errmsg)
631  errmsg = libpq_gettext("out of memory for query result");
632 
635 
636  /*
637  * Show the message as fully consumed, else pqParseInput3 will overwrite
638  * our error with a complaint about that.
639  */
640  conn->inCursor = conn->inStart + 5 + msgLength;
641 
642  /*
643  * Return zero to allow input parsing to continue. Subsequent "D"
644  * messages will be ignored until we get to end of data, since an error
645  * result is already set up.
646  */
647  return 0;
648 }
char * pqResultStrdup(PGresult *res, const char *str)
Definition: fe-exec.c:672
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:100
@ PGASYNC_READY
Definition: libpq-int.h:222
@ PGQUERY_DESCRIBE
Definition: libpq-int.h:315
PGQueryClass queryclass
Definition: libpq-int.h:325
PGcmdQueueEntry * cmd_queue_head
Definition: libpq-int.h:439
char * name
Definition: libpq-fe.h:263
int columnid
Definition: libpq-fe.h:265
int atttypmod
Definition: libpq-fe.h:269

References appendPQExpBuffer(), pg_conn::asyncStatus, pg_result::attDescs, pgresAttDesc::atttypmod, pg_result::binary, pg_conn::cmd_queue_head, pgresAttDesc::columnid, conn, PQExpBufferData::data, errmsg(), pg_conn::errorMessage, format, pgresAttDesc::format, i, pg_conn::inCursor, pg_conn::inStart, libpq_gettext, MemSet, pgresAttDesc::name, pg_result::numAttributes, PGASYNC_READY, PGQUERY_DESCRIBE, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear(), pqClearAsyncResult(), pqGetInt(), pqGets(), PQmakeEmptyPGresult(), pqResultAlloc(), pqResultStrdup(), pqSaveErrorResult(), PGcmdQueueEntry::queryclass, pg_conn::result, pgresAttDesc::tableid, pgresAttDesc::typid, pgresAttDesc::typlen, and pg_conn::workBuffer.

Referenced by pqParseInput3().

◆ handleSyncLoss()

static void handleSyncLoss ( PGconn conn,
char  id,
int  msgLength 
)
static

Definition at line 466 of file fe-protocol3.c.

467 {
468  libpq_append_conn_error(conn, "lost synchronization with server: got message type \"%c\", length %d",
469  id, msgLength);
470  /* build an error result holding the error message */
472  conn->asyncStatus = PGASYNC_READY; /* drop out of PQgetResult wait loop */
473  /* flush input data since we're giving up on processing it */
474  pqDropConnection(conn, true);
475  conn->status = CONNECTION_BAD; /* No more connection to backend */
476 }
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:456
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition: fe-misc.c:1312
@ CONNECTION_BAD
Definition: libpq-fe.h:61
ConnStatusType status
Definition: libpq-int.h:415

References pg_conn::asyncStatus, conn, CONNECTION_BAD, libpq_append_conn_error(), PGASYNC_READY, pqDropConnection(), pqSaveErrorResult(), and pg_conn::status.

Referenced by getCopyDataMessage(), pqFunctionCall3(), and pqParseInput3().

◆ pqBuildErrorMessage3()

void pqBuildErrorMessage3 ( PQExpBuffer  msg,
const PGresult res,
PGVerbosity  verbosity,
PGContextVisibility  show_context 
)

Definition at line 997 of file fe-protocol3.c.

999 {
1000  const char *val;
1001  const char *querytext = NULL;
1002  int querypos = 0;
1003 
1004  /* If we couldn't allocate a PGresult, just say "out of memory" */
1005  if (res == NULL)
1006  {
1007  appendPQExpBufferStr(msg, libpq_gettext("out of memory\n"));
1008  return;
1009  }
1010 
1011  /*
1012  * If we don't have any broken-down fields, just return the base message.
1013  * This mainly applies if we're given a libpq-generated error result.
1014  */
1015  if (res->errFields == NULL)
1016  {
1017  if (res->errMsg && res->errMsg[0])
1019  else
1020  appendPQExpBufferStr(msg, libpq_gettext("no error message available\n"));
1021  return;
1022  }
1023 
1024  /* Else build error message from relevant fields */
1026  if (val)
1027  appendPQExpBuffer(msg, "%s: ", val);
1028 
1029  if (verbosity == PQERRORS_SQLSTATE)
1030  {
1031  /*
1032  * If we have a SQLSTATE, print that and nothing else. If not (which
1033  * shouldn't happen for server-generated errors, but might possibly
1034  * happen for libpq-generated ones), fall back to TERSE format, as
1035  * that seems better than printing nothing at all.
1036  */
1038  if (val)
1039  {
1040  appendPQExpBuffer(msg, "%s\n", val);
1041  return;
1042  }
1043  verbosity = PQERRORS_TERSE;
1044  }
1045 
1046  if (verbosity == PQERRORS_VERBOSE)
1047  {
1049  if (val)
1050  appendPQExpBuffer(msg, "%s: ", val);
1051  }
1053  if (val)
1054  appendPQExpBufferStr(msg, val);
1056  if (val)
1057  {
1058  if (verbosity != PQERRORS_TERSE && res->errQuery != NULL)
1059  {
1060  /* emit position as a syntax cursor display */
1061  querytext = res->errQuery;
1062  querypos = atoi(val);
1063  }
1064  else
1065  {
1066  /* emit position as text addition to primary message */
1067  /* translator: %s represents a digit string */
1068  appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1069  val);
1070  }
1071  }
1072  else
1073  {
1075  if (val)
1076  {
1078  if (verbosity != PQERRORS_TERSE && querytext != NULL)
1079  {
1080  /* emit position as a syntax cursor display */
1081  querypos = atoi(val);
1082  }
1083  else
1084  {
1085  /* emit position as text addition to primary message */
1086  /* translator: %s represents a digit string */
1087  appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1088  val);
1089  }
1090  }
1091  }
1092  appendPQExpBufferChar(msg, '\n');
1093  if (verbosity != PQERRORS_TERSE)
1094  {
1095  if (querytext && querypos > 0)
1096  reportErrorPosition(msg, querytext, querypos,
1097  res->client_encoding);
1099  if (val)
1100  appendPQExpBuffer(msg, libpq_gettext("DETAIL: %s\n"), val);
1102  if (val)
1103  appendPQExpBuffer(msg, libpq_gettext("HINT: %s\n"), val);
1105  if (val)
1106  appendPQExpBuffer(msg, libpq_gettext("QUERY: %s\n"), val);
1107  if (show_context == PQSHOW_CONTEXT_ALWAYS ||
1108  (show_context == PQSHOW_CONTEXT_ERRORS &&
1110  {
1112  if (val)
1113  appendPQExpBuffer(msg, libpq_gettext("CONTEXT: %s\n"),
1114  val);
1115  }
1116  }
1117  if (verbosity == PQERRORS_VERBOSE)
1118  {
1120  if (val)
1121  appendPQExpBuffer(msg,
1122  libpq_gettext("SCHEMA NAME: %s\n"), val);
1124  if (val)
1125  appendPQExpBuffer(msg,
1126  libpq_gettext("TABLE NAME: %s\n"), val);
1128  if (val)
1129  appendPQExpBuffer(msg,
1130  libpq_gettext("COLUMN NAME: %s\n"), val);
1132  if (val)
1133  appendPQExpBuffer(msg,
1134  libpq_gettext("DATATYPE NAME: %s\n"), val);
1136  if (val)
1137  appendPQExpBuffer(msg,
1138  libpq_gettext("CONSTRAINT NAME: %s\n"), val);
1139  }
1140  if (verbosity == PQERRORS_VERBOSE)
1141  {
1142  const char *valf;
1143  const char *vall;
1144 
1148  if (val || valf || vall)
1149  {
1150  appendPQExpBufferStr(msg, libpq_gettext("LOCATION: "));
1151  if (val)
1152  appendPQExpBuffer(msg, libpq_gettext("%s, "), val);
1153  if (valf && vall) /* unlikely we'd have just one */
1154  appendPQExpBuffer(msg, libpq_gettext("%s:%s"),
1155  valf, vall);
1156  appendPQExpBufferChar(msg, '\n');
1157  }
1158  }
1159 }
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3295
static void reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding)
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:108
@ PQSHOW_CONTEXT_ALWAYS
Definition: libpq-fe.h:137
@ PQSHOW_CONTEXT_ERRORS
Definition: libpq-fe.h:136
@ PQERRORS_VERBOSE
Definition: libpq-fe.h:129
@ PQERRORS_TERSE
Definition: libpq-fe.h:127
@ PQERRORS_SQLSTATE
Definition: libpq-fe.h:130
#define PG_DIAG_INTERNAL_QUERY
Definition: postgres_ext.h:62
#define PG_DIAG_SCHEMA_NAME
Definition: postgres_ext.h:64
#define PG_DIAG_CONSTRAINT_NAME
Definition: postgres_ext.h:68
#define PG_DIAG_DATATYPE_NAME
Definition: postgres_ext.h:67
#define PG_DIAG_SOURCE_LINE
Definition: postgres_ext.h:70
#define PG_DIAG_STATEMENT_POSITION
Definition: postgres_ext.h:60
#define PG_DIAG_SOURCE_FILE
Definition: postgres_ext.h:69
#define PG_DIAG_MESSAGE_HINT
Definition: postgres_ext.h:59
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:56
#define PG_DIAG_TABLE_NAME
Definition: postgres_ext.h:65
#define PG_DIAG_MESSAGE_PRIMARY
Definition: postgres_ext.h:57
#define PG_DIAG_COLUMN_NAME
Definition: postgres_ext.h:66
#define PG_DIAG_MESSAGE_DETAIL
Definition: postgres_ext.h:58
#define PG_DIAG_CONTEXT
Definition: postgres_ext.h:63
#define PG_DIAG_SEVERITY
Definition: postgres_ext.h:54
#define PG_DIAG_SOURCE_FUNCTION
Definition: postgres_ext.h:71
#define PG_DIAG_INTERNAL_POSITION
Definition: postgres_ext.h:61
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:378
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
char * errMsg
Definition: libpq-int.h:198
PGMessageField * errFields
Definition: libpq-int.h:199
ExecStatusType resultStatus
Definition: libpq-int.h:179
char * errQuery
Definition: libpq-int.h:200
int client_encoding
Definition: libpq-int.h:191

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), pg_result::client_encoding, pg_result::errFields, pg_result::errMsg, pg_result::errQuery, libpq_gettext, PG_DIAG_COLUMN_NAME, PG_DIAG_CONSTRAINT_NAME, PG_DIAG_CONTEXT, PG_DIAG_DATATYPE_NAME, PG_DIAG_INTERNAL_POSITION, PG_DIAG_INTERNAL_QUERY, PG_DIAG_MESSAGE_DETAIL, PG_DIAG_MESSAGE_HINT, PG_DIAG_MESSAGE_PRIMARY, PG_DIAG_SCHEMA_NAME, PG_DIAG_SEVERITY, PG_DIAG_SOURCE_FILE, PG_DIAG_SOURCE_FUNCTION, PG_DIAG_SOURCE_LINE, PG_DIAG_SQLSTATE, PG_DIAG_STATEMENT_POSITION, PG_DIAG_TABLE_NAME, PGRES_FATAL_ERROR, PQERRORS_SQLSTATE, PQERRORS_TERSE, PQERRORS_VERBOSE, PQresultErrorField(), PQSHOW_CONTEXT_ALWAYS, PQSHOW_CONTEXT_ERRORS, reportErrorPosition(), res, pg_result::resultStatus, and val.

Referenced by pqGetErrorNotice3(), and PQresultVerboseErrorMessage().

◆ pqBuildStartupPacket3()

char* pqBuildStartupPacket3 ( PGconn conn,
int *  packetlen,
const PQEnvironmentOption options 
)

Definition at line 2219 of file fe-protocol3.c.

2221 {
2222  char *startpacket;
2223 
2224  *packetlen = build_startup_packet(conn, NULL, options);
2225  startpacket = (char *) malloc(*packetlen);
2226  if (!startpacket)
2227  return NULL;
2228  *packetlen = build_startup_packet(conn, startpacket, options);
2229  return startpacket;
2230 }
static int build_startup_packet(const PGconn *conn, char *packet, const PQEnvironmentOption *options)

References build_startup_packet(), conn, and malloc.

Referenced by PQconnectPoll().

◆ pqEndcopy3()

int pqEndcopy3 ( PGconn conn)

Definition at line 1898 of file fe-protocol3.c.

1899 {
1900  PGresult *result;
1901 
1902  if (conn->asyncStatus != PGASYNC_COPY_IN &&
1905  {
1906  libpq_append_conn_error(conn, "no COPY in progress");
1907  return 1;
1908  }
1909 
1910  /* Send the CopyDone message if needed */
1911  if (conn->asyncStatus == PGASYNC_COPY_IN ||
1913  {
1914  if (pqPutMsgStart('c', conn) < 0 ||
1915  pqPutMsgEnd(conn) < 0)
1916  return 1;
1917 
1918  /*
1919  * If we sent the COPY command in extended-query mode, we must issue a
1920  * Sync as well.
1921  */
1922  if (conn->cmd_queue_head &&
1924  {
1925  if (pqPutMsgStart('S', conn) < 0 ||
1926  pqPutMsgEnd(conn) < 0)
1927  return 1;
1928  }
1929  }
1930 
1931  /*
1932  * make sure no data is waiting to be sent, abort if we are non-blocking
1933  * and the flush fails
1934  */
1935  if (pqFlush(conn) && pqIsnonblocking(conn))
1936  return 1;
1937 
1938  /* Return to active duty */
1940 
1941  /*
1942  * Non blocking connections may have to abort at this point. If everyone
1943  * played the game there should be no problem, but in error scenarios the
1944  * expected messages may not have arrived yet. (We are assuming that the
1945  * backend's packetizing will ensure that CommandComplete arrives along
1946  * with the CopyDone; are there corner cases where that doesn't happen?)
1947  */
1948  if (pqIsnonblocking(conn) && PQisBusy(conn))
1949  return 1;
1950 
1951  /* Wait for the completion response */
1952  result = PQgetResult(conn);
1953 
1954  /* Expecting a successful result */
1955  if (result && result->resultStatus == PGRES_COMMAND_OK)
1956  {
1957  PQclear(result);
1958  return 0;
1959  }
1960 
1961  /*
1962  * Trouble. For backwards-compatibility reasons, we issue the error
1963  * message as if it were a notice (would be nice to get rid of this
1964  * silliness, but too many apps probably don't handle errors from
1965  * PQendcopy reasonably). Note that the app can still obtain the error
1966  * status from the PGconn object.
1967  */
1968  if (conn->errorMessage.len > 0)
1969  {
1970  /* We have to strip the trailing newline ... pain in neck... */
1971  char svLast = conn->errorMessage.data[conn->errorMessage.len - 1];
1972 
1973  if (svLast == '\n')
1974  conn->errorMessage.data[conn->errorMessage.len - 1] = '\0';
1976  conn->errorMessage.data[conn->errorMessage.len - 1] = svLast;
1977  }
1978 
1979  PQclear(result);
1980 
1981  return 1;
1982 }
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:933
int PQisBusy(PGconn *conn)
Definition: fe-exec.c:2000
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2031
int pqFlush(PGconn *conn)
Definition: fe-misc.c:954
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:459
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:518
@ PGASYNC_COPY_OUT
Definition: libpq-int.h:228
@ PGQUERY_SIMPLE
Definition: libpq-int.h:312
#define pqIsnonblocking(conn)
Definition: libpq-int.h:883
PGNoticeHooks noticeHooks
Definition: libpq-int.h:407

References pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, PQExpBufferData::data, pg_conn::errorMessage, PQExpBufferData::len, libpq_append_conn_error(), pg_conn::noticeHooks, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGQUERY_SIMPLE, PGRES_COMMAND_OK, PQclear(), pqFlush(), PQgetResult(), pqInternalNotice(), PQisBusy(), pqIsnonblocking, pqPutMsgEnd(), pqPutMsgStart(), PGcmdQueueEntry::queryclass, and pg_result::resultStatus.

Referenced by PQendcopy().

◆ pqFunctionCall3()

PGresult* pqFunctionCall3 ( PGconn conn,
Oid  fnid,
int *  result_buf,
int *  actual_result_len,
int  result_is_int,
const PQArgBlock args,
int  nargs 
)

Definition at line 1991 of file fe-protocol3.c.

1995 {
1996  bool needInput = false;
1998  char id;
1999  int msgLength;
2000  int avail;
2001  int i;
2002 
2003  /* already validated by PQfn */
2005 
2006  /* PQfn already validated connection state */
2007 
2008  if (pqPutMsgStart('F', conn) < 0 || /* function call msg */
2009  pqPutInt(fnid, 4, conn) < 0 || /* function id */
2010  pqPutInt(1, 2, conn) < 0 || /* # of format codes */
2011  pqPutInt(1, 2, conn) < 0 || /* format code: BINARY */
2012  pqPutInt(nargs, 2, conn) < 0) /* # of args */
2013  {
2014  /* error message should be set up already */
2015  return NULL;
2016  }
2017 
2018  for (i = 0; i < nargs; ++i)
2019  { /* len.int4 + contents */
2020  if (pqPutInt(args[i].len, 4, conn))
2021  return NULL;
2022  if (args[i].len == -1)
2023  continue; /* it's NULL */
2024 
2025  if (args[i].isint)
2026  {
2027  if (pqPutInt(args[i].u.integer, args[i].len, conn))
2028  return NULL;
2029  }
2030  else
2031  {
2032  if (pqPutnchar((char *) args[i].u.ptr, args[i].len, conn))
2033  return NULL;
2034  }
2035  }
2036 
2037  if (pqPutInt(1, 2, conn) < 0) /* result format code: BINARY */
2038  return NULL;
2039 
2040  if (pqPutMsgEnd(conn) < 0 ||
2041  pqFlush(conn))
2042  return NULL;
2043 
2044  for (;;)
2045  {
2046  if (needInput)
2047  {
2048  /* Wait for some data to arrive (or for the channel to close) */
2049  if (pqWait(true, false, conn) ||
2050  pqReadData(conn) < 0)
2051  break;
2052  }
2053 
2054  /*
2055  * Scan the message. If we run out of data, loop around to try again.
2056  */
2057  needInput = true;
2058 
2059  conn->inCursor = conn->inStart;
2060  if (pqGetc(&id, conn))
2061  continue;
2062  if (pqGetInt(&msgLength, 4, conn))
2063  continue;
2064 
2065  /*
2066  * Try to validate message type/length here. A length less than 4 is
2067  * definitely broken. Large lengths should only be believed for a few
2068  * message types.
2069  */
2070  if (msgLength < 4)
2071  {
2072  handleSyncLoss(conn, id, msgLength);
2073  break;
2074  }
2075  if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
2076  {
2077  handleSyncLoss(conn, id, msgLength);
2078  break;
2079  }
2080 
2081  /*
2082  * Can't process if message body isn't all here yet.
2083  */
2084  msgLength -= 4;
2085  avail = conn->inEnd - conn->inCursor;
2086  if (avail < msgLength)
2087  {
2088  /*
2089  * Before looping, enlarge the input buffer if needed to hold the
2090  * whole message. See notes in parseInput.
2091  */
2092  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
2093  conn))
2094  {
2095  /*
2096  * XXX add some better recovery code... plan is to skip over
2097  * the message using its length, then report an error. For the
2098  * moment, just treat this like loss of sync (which indeed it
2099  * might be!)
2100  */
2101  handleSyncLoss(conn, id, msgLength);
2102  break;
2103  }
2104  continue;
2105  }
2106 
2107  /*
2108  * We should see V or E response to the command, but might get N
2109  * and/or A notices first. We also need to swallow the final Z before
2110  * returning.
2111  */
2112  switch (id)
2113  {
2114  case 'V': /* function result */
2115  if (pqGetInt(actual_result_len, 4, conn))
2116  continue;
2117  if (*actual_result_len != -1)
2118  {
2119  if (result_is_int)
2120  {
2121  if (pqGetInt(result_buf, *actual_result_len, conn))
2122  continue;
2123  }
2124  else
2125  {
2126  if (pqGetnchar((char *) result_buf,
2127  *actual_result_len,
2128  conn))
2129  continue;
2130  }
2131  }
2132  /* correctly finished function result message */
2134  break;
2135  case 'E': /* error return */
2136  if (pqGetErrorNotice3(conn, true))
2137  continue;
2139  break;
2140  case 'A': /* notify message */
2141  /* handle notify and go back to processing return values */
2142  if (getNotify(conn))
2143  continue;
2144  break;
2145  case 'N': /* notice */
2146  /* handle notice and go back to processing return values */
2147  if (pqGetErrorNotice3(conn, false))
2148  continue;
2149  break;
2150  case 'Z': /* backend is ready for new query */
2151  if (getReadyForQuery(conn))
2152  continue;
2153  /* consume the message and exit */
2154  conn->inStart += 5 + msgLength;
2155 
2156  /*
2157  * If we already have a result object (probably an error), use
2158  * that. Otherwise, if we saw a function result message,
2159  * report COMMAND_OK. Otherwise, the backend violated the
2160  * protocol, so complain.
2161  */
2162  if (!pgHavePendingResult(conn))
2163  {
2164  if (status == PGRES_COMMAND_OK)
2165  {
2167  if (!conn->result)
2168  {
2169  libpq_append_conn_error(conn, "out of memory");
2171  }
2172  }
2173  else
2174  {
2175  libpq_append_conn_error(conn, "protocol error: no function result");
2177  }
2178  }
2179  return pqPrepareAsyncResult(conn);
2180  case 'S': /* parameter status */
2181  if (getParameterStatus(conn))
2182  continue;
2183  break;
2184  default:
2185  /* The backend violates the protocol. */
2186  libpq_append_conn_error(conn, "protocol error: id=0x%x", id);
2188  /* trust the specified message length as what to skip */
2189  conn->inStart += 5 + msgLength;
2190  return pqPrepareAsyncResult(conn);
2191  }
2192 
2193  /* trace server-to-client message */
2194  if (conn->Pfdebug)
2196 
2197  /* Completed this message, keep going */
2198  /* trust the specified message length as what to skip */
2199  conn->inStart += 5 + msgLength;
2200  needInput = false;
2201  }
2202 
2203  /*
2204  * We fall out of the loop only upon failing to read data.
2205  * conn->errorMessage has been set by pqWait or pqReadData. We want to
2206  * append it to any already-received error message.
2207  */
2209  return pqPrepareAsyncResult(conn);
2210 }
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition: fe-exec.c:846
int pqReadData(PGconn *conn)
Definition: fe-misc.c:566
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:254
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:166
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:979
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:203
#define VALID_LONG_MESSAGE_TYPE(id)
Definition: fe-protocol3.c:36
static int getReadyForQuery(PGconn *conn)
ExecStatusType
Definition: libpq-fe.h:95
@ PQ_PIPELINE_OFF
Definition: libpq-fe.h:158
#define pgHavePendingResult(conn)
Definition: libpq-int.h:876
Assert(fmt[strlen(fmt) - 1] !='\n')
const void size_t len
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:224
PGpipelineStatus pipelineStatus
Definition: libpq-int.h:422

References generate_unaccent_rules::args, Assert(), conn, getNotify(), getParameterStatus(), getReadyForQuery(), handleSyncLoss(), i, pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, len, libpq_append_conn_error(), pg_conn::Pfdebug, pgHavePendingResult, PGRES_COMMAND_OK, PGRES_FATAL_ERROR, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqCheckInBufferSpace(), pqFlush(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGetnchar(), PQmakeEmptyPGresult(), pqPrepareAsyncResult(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), pqReadData(), pqSaveErrorResult(), pqTraceOutputMessage(), pqWait(), pg_conn::result, status(), and VALID_LONG_MESSAGE_TYPE.

Referenced by PQfn().

◆ pqGetCopyData3()

int pqGetCopyData3 ( PGconn conn,
char **  buffer,
int  async 
)

Definition at line 1733 of file fe-protocol3.c.

1734 {
1735  int msgLength;
1736 
1737  for (;;)
1738  {
1739  /*
1740  * Collect the next input message. To make life simpler for async
1741  * callers, we keep returning 0 until the next message is fully
1742  * available, even if it is not Copy Data.
1743  */
1744  msgLength = getCopyDataMessage(conn);
1745  if (msgLength < 0)
1746  return msgLength; /* end-of-copy or error */
1747  if (msgLength == 0)
1748  {
1749  /* Don't block if async read requested */
1750  if (async)
1751  return 0;
1752  /* Need to load more data */
1753  if (pqWait(true, false, conn) ||
1754  pqReadData(conn) < 0)
1755  return -2;
1756  continue;
1757  }
1758 
1759  /*
1760  * Drop zero-length messages (shouldn't happen anyway). Otherwise
1761  * pass the data back to the caller.
1762  */
1763  msgLength -= 4;
1764  if (msgLength > 0)
1765  {
1766  *buffer = (char *) malloc(msgLength + 1);
1767  if (*buffer == NULL)
1768  {
1769  libpq_append_conn_error(conn, "out of memory");
1770  return -2;
1771  }
1772  memcpy(*buffer, &conn->inBuffer[conn->inCursor], msgLength);
1773  (*buffer)[msgLength] = '\0'; /* Add terminating null */
1774 
1775  /* Mark message consumed */
1776  conn->inStart = conn->inCursor + msgLength;
1777 
1778  return msgLength;
1779  }
1780 
1781  /* Empty, so drop it and loop around for another */
1782  conn->inStart = conn->inCursor;
1783  }
1784 }
static int getCopyDataMessage(PGconn *conn)

References conn, getCopyDataMessage(), pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inStart, libpq_append_conn_error(), malloc, pqReadData(), and pqWait().

Referenced by PQgetCopyData().

◆ pqGetErrorNotice3()

int pqGetErrorNotice3 ( PGconn conn,
bool  isError 
)

Definition at line 865 of file fe-protocol3.c.

866 {
867  PGresult *res = NULL;
868  bool have_position = false;
869  PQExpBufferData workBuf;
870  char id;
871 
872  /* If in pipeline mode, set error indicator for it */
873  if (isError && conn->pipelineStatus != PQ_PIPELINE_OFF)
875 
876  /*
877  * If this is an error message, pre-emptively clear any incomplete query
878  * result we may have. We'd just throw it away below anyway, and
879  * releasing it before collecting the error might avoid out-of-memory.
880  */
881  if (isError)
883 
884  /*
885  * Since the fields might be pretty long, we create a temporary
886  * PQExpBuffer rather than using conn->workBuffer. workBuffer is intended
887  * for stuff that is expected to be short. We shouldn't use
888  * conn->errorMessage either, since this might be only a notice.
889  */
890  initPQExpBuffer(&workBuf);
891 
892  /*
893  * Make a PGresult to hold the accumulated fields. We temporarily lie
894  * about the result status, so that PQmakeEmptyPGresult doesn't uselessly
895  * copy conn->errorMessage.
896  *
897  * NB: This allocation can fail, if you run out of memory. The rest of the
898  * function handles that gracefully, and we still try to set the error
899  * message as the connection's error message.
900  */
902  if (res)
904 
905  /*
906  * Read the fields and save into res.
907  *
908  * While at it, save the SQLSTATE in conn->last_sqlstate, and note whether
909  * we saw a PG_DIAG_STATEMENT_POSITION field.
910  */
911  for (;;)
912  {
913  if (pqGetc(&id, conn))
914  goto fail;
915  if (id == '\0')
916  break; /* terminator found */
917  if (pqGets(&workBuf, conn))
918  goto fail;
919  pqSaveMessageField(res, id, workBuf.data);
920  if (id == PG_DIAG_SQLSTATE)
921  strlcpy(conn->last_sqlstate, workBuf.data,
922  sizeof(conn->last_sqlstate));
923  else if (id == PG_DIAG_STATEMENT_POSITION)
924  have_position = true;
925  }
926 
927  /*
928  * Save the active query text, if any, into res as well; but only if we
929  * might need it for an error cursor display, which is only true if there
930  * is a PG_DIAG_STATEMENT_POSITION field.
931  */
932  if (have_position && res && conn->cmd_queue_head && conn->cmd_queue_head->query)
934 
935  /*
936  * Now build the "overall" error message for PQresultErrorMessage.
937  */
938  resetPQExpBuffer(&workBuf);
940 
941  /*
942  * Either save error as current async result, or just emit the notice.
943  */
944  if (isError)
945  {
946  pqClearAsyncResult(conn); /* redundant, but be safe */
947  if (res)
948  {
949  pqSetResultError(res, &workBuf, 0);
950  conn->result = res;
951  }
952  else
953  {
954  /* Fall back to using the internal-error processing paths */
955  conn->error_result = true;
956  }
957 
958  if (PQExpBufferDataBroken(workBuf))
959  libpq_append_conn_error(conn, "out of memory");
960  else
962  }
963  else
964  {
965  /* if we couldn't allocate the result set, just discard the NOTICE */
966  if (res)
967  {
968  /*
969  * We can cheat a little here and not copy the message. But if we
970  * were unlucky enough to run out of memory while filling workBuf,
971  * insert "out of memory", as in pqSetResultError.
972  */
973  if (PQExpBufferDataBroken(workBuf))
974  res->errMsg = libpq_gettext("out of memory\n");
975  else
976  res->errMsg = workBuf.data;
977  if (res->noticeHooks.noticeRec != NULL)
979  PQclear(res);
980  }
981  }
982 
983  termPQExpBuffer(&workBuf);
984  return 0;
985 
986 fail:
987  PQclear(res);
988  termPQExpBuffer(&workBuf);
989  return EOF;
990 }
void pqSaveMessageField(PGresult *res, char code, const char *value)
Definition: fe-exec.c:1055
void pqSetResultError(PGresult *res, PQExpBuffer errorMessage, int offset)
Definition: fe-exec.c:689
void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
Definition: fe-protocol3.c:997
@ PGRES_EMPTY_QUERY
Definition: libpq-fe.h:96
@ PGRES_NONFATAL_ERROR
Definition: libpq-fe.h:107
@ PQ_PIPELINE_ABORTED
Definition: libpq-fe.h:160
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:146
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
PQnoticeReceiver noticeRec
Definition: libpq-int.h:154
void * noticeRecArg
Definition: libpq-int.h:155
PGVerbosity verbosity
Definition: libpq-int.h:487
bool error_result
Definition: libpq-int.h:522
char last_sqlstate[6]
Definition: libpq-int.h:418
PGContextVisibility show_context
Definition: libpq-int.h:488
PGNoticeHooks noticeHooks
Definition: libpq-int.h:188

References appendPQExpBufferStr(), pg_conn::cmd_queue_head, conn, PQExpBufferData::data, pg_result::errMsg, pg_conn::error_result, pg_conn::errorMessage, pg_result::errQuery, initPQExpBuffer(), pg_conn::last_sqlstate, libpq_append_conn_error(), libpq_gettext, pg_result::noticeHooks, PGNoticeHooks::noticeRec, PGNoticeHooks::noticeRecArg, PG_DIAG_SQLSTATE, PG_DIAG_STATEMENT_POSITION, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PGRES_NONFATAL_ERROR, pg_conn::pipelineStatus, PQ_PIPELINE_ABORTED, PQ_PIPELINE_OFF, pqBuildErrorMessage3(), PQclear(), pqClearAsyncResult(), PQExpBufferDataBroken, pqGetc(), pqGets(), PQmakeEmptyPGresult(), pqResultStrdup(), pqSaveMessageField(), pqSetResultError(), PGcmdQueueEntry::query, res, resetPQExpBuffer(), pg_conn::result, pg_result::resultStatus, pg_conn::show_context, strlcpy(), termPQExpBuffer(), and pg_conn::verbosity.

Referenced by getCopyDataMessage(), PQconnectPoll(), pqFunctionCall3(), and pqParseInput3().

◆ pqGetline3()

int pqGetline3 ( PGconn conn,
char *  s,
int  maxlen 
)

Definition at line 1792 of file fe-protocol3.c.

1793 {
1794  int status;
1795 
1796  if (conn->sock == PGINVALID_SOCKET ||
1800  {
1801  libpq_append_conn_error(conn, "PQgetline: not doing text COPY OUT");
1802  *s = '\0';
1803  return EOF;
1804  }
1805 
1806  while ((status = PQgetlineAsync(conn, s, maxlen - 1)) == 0)
1807  {
1808  /* need to load more data */
1809  if (pqWait(true, false, conn) ||
1810  pqReadData(conn) < 0)
1811  {
1812  *s = '\0';
1813  return EOF;
1814  }
1815  }
1816 
1817  if (status < 0)
1818  {
1819  /* End of copy detected; gin up old-style terminator */
1820  strcpy(s, "\\.");
1821  return 0;
1822  }
1823 
1824  /* Add null terminator, and strip trailing \n if present */
1825  if (s[status - 1] == '\n')
1826  {
1827  s[status - 1] = '\0';
1828  return 0;
1829  }
1830  else
1831  {
1832  s[status] = '\0';
1833  return 1;
1834  }
1835 }
int PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
Definition: fe-exec.c:2783
#define PGINVALID_SOCKET
Definition: port.h:31
pgsocket sock
Definition: libpq-int.h:449

References pg_conn::asyncStatus, conn, pg_conn::copy_is_binary, libpq_append_conn_error(), PGASYNC_COPY_BOTH, PGASYNC_COPY_OUT, PGINVALID_SOCKET, PQgetlineAsync(), pqReadData(), pqWait(), pg_conn::sock, and status().

Referenced by PQgetline().

◆ pqGetlineAsync3()

int pqGetlineAsync3 ( PGconn conn,
char *  buffer,
int  bufsize 
)

Definition at line 1843 of file fe-protocol3.c.

1844 {
1845  int msgLength;
1846  int avail;
1847 
1850  return -1; /* we are not doing a copy... */
1851 
1852  /*
1853  * Recognize the next input message. To make life simpler for async
1854  * callers, we keep returning 0 until the next message is fully available
1855  * even if it is not Copy Data. This should keep PQendcopy from blocking.
1856  * (Note: unlike pqGetCopyData3, we do not change asyncStatus here.)
1857  */
1858  msgLength = getCopyDataMessage(conn);
1859  if (msgLength < 0)
1860  return -1; /* end-of-copy or error */
1861  if (msgLength == 0)
1862  return 0; /* no data yet */
1863 
1864  /*
1865  * Move data from libpq's buffer to the caller's. In the case where a
1866  * prior call found the caller's buffer too small, we use
1867  * conn->copy_already_done to remember how much of the row was already
1868  * returned to the caller.
1869  */
1871  avail = msgLength - 4 - conn->copy_already_done;
1872  if (avail <= bufsize)
1873  {
1874  /* Able to consume the whole message */
1875  memcpy(buffer, &conn->inBuffer[conn->inCursor], avail);
1876  /* Mark message consumed */
1877  conn->inStart = conn->inCursor + avail;
1878  /* Reset state for next time */
1879  conn->copy_already_done = 0;
1880  return avail;
1881  }
1882  else
1883  {
1884  /* We must return a partial message */
1885  memcpy(buffer, &conn->inBuffer[conn->inCursor], bufsize);
1886  /* The message is NOT consumed from libpq's buffer */
1888  return bufsize;
1889  }
1890 }
#define bufsize
Definition: indent_globs.h:36
int copy_already_done
Definition: libpq-int.h:425

References pg_conn::asyncStatus, bufsize, conn, pg_conn::copy_already_done, getCopyDataMessage(), pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inStart, PGASYNC_COPY_BOTH, and PGASYNC_COPY_OUT.

Referenced by PQgetlineAsync().

◆ pqGetNegotiateProtocolVersion3()

int pqGetNegotiateProtocolVersion3 ( PGconn conn)

Definition at line 1395 of file fe-protocol3.c.

1396 {
1397  int tmp;
1398  ProtocolVersion their_version;
1399  int num;
1401 
1402  if (pqGetInt(&tmp, 4, conn) != 0)
1403  return EOF;
1404  their_version = tmp;
1405 
1406  if (pqGetInt(&num, 4, conn) != 0)
1407  return EOF;
1408 
1409  initPQExpBuffer(&buf);
1410  for (int i = 0; i < num; i++)
1411  {
1412  if (pqGets(&conn->workBuffer, conn))
1413  {
1414  termPQExpBuffer(&buf);
1415  return EOF;
1416  }
1417  if (buf.len > 0)
1418  appendPQExpBufferChar(&buf, ' ');
1420  }
1421 
1422  if (their_version < conn->pversion)
1424  libpq_gettext("protocol version not supported by server: client uses %u.%u, server supports up to %u.%u\n"),
1426  PG_PROTOCOL_MAJOR(their_version), PG_PROTOCOL_MINOR(their_version));
1427  if (num > 0)
1429  libpq_ngettext("protocol extension not supported by server: %s\n",
1430  "protocol extensions not supported by server: %s\n", num),
1431  buf.data);
1432 
1433  /* neither -- server shouldn't have sent it */
1434  if (!(their_version < conn->pversion) && !(num > 0))
1436  libpq_gettext("invalid %s message"), "NegotiateProtocolVersion");
1437 
1438  termPQExpBuffer(&buf);
1439  return 0;
1440 }
#define libpq_ngettext(s, p, n)
Definition: libpq-int.h:895
static char * buf
Definition: pg_test_fsync.c:67
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:75
#define PG_PROTOCOL_MINOR(v)
Definition: pqcomm.h:76

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), buf, conn, PQExpBufferData::data, pg_conn::errorMessage, i, initPQExpBuffer(), libpq_gettext, libpq_ngettext, PG_PROTOCOL_MAJOR, PG_PROTOCOL_MINOR, pqGetInt(), pqGets(), pg_conn::pversion, termPQExpBuffer(), and pg_conn::workBuffer.

Referenced by PQconnectPoll().

◆ pqParseInput3()

void pqParseInput3 ( PGconn conn)

Definition at line 61 of file fe-protocol3.c.

62 {
63  char id;
64  int msgLength;
65  int avail;
66 
67  /*
68  * Loop to parse successive complete messages available in the buffer.
69  */
70  for (;;)
71  {
72  /*
73  * Try to read a message. First get the type code and length. Return
74  * if not enough data.
75  */
77  if (pqGetc(&id, conn))
78  return;
79  if (pqGetInt(&msgLength, 4, conn))
80  return;
81 
82  /*
83  * Try to validate message type/length here. A length less than 4 is
84  * definitely broken. Large lengths should only be believed for a few
85  * message types.
86  */
87  if (msgLength < 4)
88  {
89  handleSyncLoss(conn, id, msgLength);
90  return;
91  }
92  if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
93  {
94  handleSyncLoss(conn, id, msgLength);
95  return;
96  }
97 
98  /*
99  * Can't process if message body isn't all here yet.
100  */
101  msgLength -= 4;
102  avail = conn->inEnd - conn->inCursor;
103  if (avail < msgLength)
104  {
105  /*
106  * Before returning, enlarge the input buffer if needed to hold
107  * the whole message. This is better than leaving it to
108  * pqReadData because we can avoid multiple cycles of realloc()
109  * when the message is large; also, we can implement a reasonable
110  * recovery strategy if we are unable to make the buffer big
111  * enough.
112  */
113  if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
114  conn))
115  {
116  /*
117  * XXX add some better recovery code... plan is to skip over
118  * the message using its length, then report an error. For the
119  * moment, just treat this like loss of sync (which indeed it
120  * might be!)
121  */
122  handleSyncLoss(conn, id, msgLength);
123  }
124  return;
125  }
126 
127  /*
128  * NOTIFY and NOTICE messages can happen in any state; always process
129  * them right away.
130  *
131  * Most other messages should only be processed while in BUSY state.
132  * (In particular, in READY state we hold off further parsing until
133  * the application collects the current PGresult.)
134  *
135  * However, if the state is IDLE then we got trouble; we need to deal
136  * with the unexpected message somehow.
137  *
138  * ParameterStatus ('S') messages are a special case: in IDLE state we
139  * must process 'em (this case could happen if a new value was adopted
140  * from config file due to SIGHUP), but otherwise we hold off until
141  * BUSY state.
142  */
143  if (id == 'A')
144  {
145  if (getNotify(conn))
146  return;
147  }
148  else if (id == 'N')
149  {
150  if (pqGetErrorNotice3(conn, false))
151  return;
152  }
153  else if (conn->asyncStatus != PGASYNC_BUSY)
154  {
155  /* If not IDLE state, just wait ... */
156  if (conn->asyncStatus != PGASYNC_IDLE)
157  return;
158 
159  /*
160  * Unexpected message in IDLE state; need to recover somehow.
161  * ERROR messages are handled using the notice processor;
162  * ParameterStatus is handled normally; anything else is just
163  * dropped on the floor after displaying a suitable warning
164  * notice. (An ERROR is very possibly the backend telling us why
165  * it is about to close the connection, so we don't want to just
166  * discard it...)
167  */
168  if (id == 'E')
169  {
170  if (pqGetErrorNotice3(conn, false /* treat as notice */ ))
171  return;
172  }
173  else if (id == 'S')
174  {
176  return;
177  }
178  else
179  {
180  /* Any other case is unexpected and we summarily skip it */
182  "message type 0x%02x arrived from server while idle",
183  id);
184  /* Discard the unexpected message */
185  conn->inCursor += msgLength;
186  }
187  }
188  else
189  {
190  /*
191  * In BUSY state, we can process everything.
192  */
193  switch (id)
194  {
195  case 'C': /* command complete */
196  if (pqGets(&conn->workBuffer, conn))
197  return;
199  {
202  if (!conn->result)
203  {
204  libpq_append_conn_error(conn, "out of memory");
206  }
207  }
208  if (conn->result)
210  CMDSTATUS_LEN);
212  break;
213  case 'E': /* error return */
214  if (pqGetErrorNotice3(conn, true))
215  return;
217  break;
218  case 'Z': /* sync response, backend is ready for new
219  * query */
220  if (getReadyForQuery(conn))
221  return;
223  {
226  if (!conn->result)
227  {
228  libpq_append_conn_error(conn, "out of memory");
230  }
231  else
232  {
235  }
236  }
237  else
238  {
239  /*
240  * In simple query protocol, advance the command queue
241  * (see PQgetResult).
242  */
243  if (conn->cmd_queue_head &&
247  }
248  break;
249  case 'I': /* empty query */
251  {
254  if (!conn->result)
255  {
256  libpq_append_conn_error(conn, "out of memory");
258  }
259  }
261  break;
262  case '1': /* Parse Complete */
263  /* If we're doing PQprepare, we're done; else ignore */
264  if (conn->cmd_queue_head &&
266  {
268  {
271  if (!conn->result)
272  {
273  libpq_append_conn_error(conn, "out of memory");
275  }
276  }
278  }
279  break;
280  case '2': /* Bind Complete */
281  case '3': /* Close Complete */
282  /* Nothing to do for these message types */
283  break;
284  case 'S': /* parameter status */
286  return;
287  break;
288  case 'K': /* secret key data from the backend */
289 
290  /*
291  * This is expected only during backend startup, but it's
292  * just as easy to handle it as part of the main loop.
293  * Save the data and continue processing.
294  */
295  if (pqGetInt(&(conn->be_pid), 4, conn))
296  return;
297  if (pqGetInt(&(conn->be_key), 4, conn))
298  return;
299  break;
300  case 'T': /* Row Description */
301  if (conn->error_result ||
302  (conn->result != NULL &&
304  {
305  /*
306  * We've already choked for some reason. Just discard
307  * the data till we get to the end of the query.
308  */
309  conn->inCursor += msgLength;
310  }
311  else if (conn->result == NULL ||
312  (conn->cmd_queue_head &&
314  {
315  /* First 'T' in a query sequence */
316  if (getRowDescriptions(conn, msgLength))
317  return;
318  }
319  else
320  {
321  /*
322  * A new 'T' message is treated as the start of
323  * another PGresult. (It is not clear that this is
324  * really possible with the current backend.) We stop
325  * parsing until the application accepts the current
326  * result.
327  */
329  return;
330  }
331  break;
332  case 'n': /* No Data */
333 
334  /*
335  * NoData indicates that we will not be seeing a
336  * RowDescription message because the statement or portal
337  * inquired about doesn't return rows.
338  *
339  * If we're doing a Describe, we have to pass something
340  * back to the client, so set up a COMMAND_OK result,
341  * instead of PGRES_TUPLES_OK. Otherwise we can just
342  * ignore this message.
343  */
344  if (conn->cmd_queue_head &&
346  {
348  {
351  if (!conn->result)
352  {
353  libpq_append_conn_error(conn, "out of memory");
355  }
356  }
358  }
359  break;
360  case 't': /* Parameter Description */
361  if (getParamDescriptions(conn, msgLength))
362  return;
363  break;
364  case 'D': /* Data Row */
365  if (conn->result != NULL &&
367  {
368  /* Read another tuple of a normal query response */
369  if (getAnotherTuple(conn, msgLength))
370  return;
371  }
372  else if (conn->error_result ||
373  (conn->result != NULL &&
375  {
376  /*
377  * We've already choked for some reason. Just discard
378  * tuples till we get to the end of the query.
379  */
380  conn->inCursor += msgLength;
381  }
382  else
383  {
384  /* Set up to report error at end of query */
385  libpq_append_conn_error(conn, "server sent data (\"D\" message) without prior row description (\"T\" message)");
387  /* Discard the unexpected message */
388  conn->inCursor += msgLength;
389  }
390  break;
391  case 'G': /* Start Copy In */
393  return;
395  break;
396  case 'H': /* Start Copy Out */
398  return;
400  conn->copy_already_done = 0;
401  break;
402  case 'W': /* Start Copy Both */
404  return;
406  conn->copy_already_done = 0;
407  break;
408  case 'd': /* Copy Data */
409 
410  /*
411  * If we see Copy Data, just silently drop it. This would
412  * only occur if application exits COPY OUT mode too
413  * early.
414  */
415  conn->inCursor += msgLength;
416  break;
417  case 'c': /* Copy Done */
418 
419  /*
420  * If we see Copy Done, just silently drop it. This is
421  * the normal case during PQendcopy. We will keep
422  * swallowing data, expecting to see command-complete for
423  * the COPY command.
424  */
425  break;
426  default:
427  libpq_append_conn_error(conn, "unexpected response from server; first received character was \"%c\"", id);
428  /* build an error result holding the error message */
430  /* not sure if we will see more, so go to ready state */
432  /* Discard the unexpected message */
433  conn->inCursor += msgLength;
434  break;
435  } /* switch on protocol character */
436  }
437  /* Successfully consumed this message */
438  if (conn->inCursor == conn->inStart + 5 + msgLength)
439  {
440  /* trace server-to-client message */
441  if (conn->Pfdebug)
443 
444  /* Normal case: parsing agrees with specified length */
446  }
447  else
448  {
449  /* Trouble --- report it */
450  libpq_append_conn_error(conn, "message contents do not agree with length in message type \"%c\"", id);
451  /* build an error result holding the error message */
454  /* trust the specified message length as what to skip */
455  conn->inStart += 5 + msgLength;
456  }
457  }
458 }
void pqCommandQueueAdvance(PGconn *conn)
Definition: fe-exec.c:3011
static int getAnotherTuple(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:745
static int getRowDescriptions(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:486
static int getCopyStart(PGconn *conn, ExecStatusType copytype)
static int getParamDescriptions(PGconn *conn, int msgLength)
Definition: fe-protocol3.c:657
@ PGRES_COPY_IN
Definition: libpq-fe.h:104
@ PGRES_COPY_BOTH
Definition: libpq-fe.h:109
@ PGRES_COPY_OUT
Definition: libpq-fe.h:103
@ PGRES_PIPELINE_SYNC
Definition: libpq-fe.h:111
@ PQ_PIPELINE_ON
Definition: libpq-fe.h:159
@ PGASYNC_IDLE
Definition: libpq-int.h:220
@ PGQUERY_PREPARE
Definition: libpq-int.h:314
#define CMDSTATUS_LEN
Definition: libpq-int.h:88
int be_pid
Definition: libpq-int.h:480
int be_key
Definition: libpq-int.h:481
char cmdStatus[CMDSTATUS_LEN]
Definition: libpq-int.h:180

References pg_conn::asyncStatus, pg_conn::be_key, pg_conn::be_pid, pg_conn::cmd_queue_head, pg_result::cmdStatus, CMDSTATUS_LEN, conn, pg_conn::copy_already_done, PQExpBufferData::data, pg_conn::error_result, getAnotherTuple(), getCopyStart(), getNotify(), getParamDescriptions(), getParameterStatus(), getReadyForQuery(), getRowDescriptions(), handleSyncLoss(), pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, libpq_append_conn_error(), pg_conn::noticeHooks, pg_conn::Pfdebug, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_READY, pgHavePendingResult, PGQUERY_DESCRIBE, PGQUERY_PREPARE, PGQUERY_SIMPLE, PGRES_COMMAND_OK, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PGRES_PIPELINE_SYNC, PGRES_TUPLES_OK, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, PQ_PIPELINE_ON, pqCheckInBufferSpace(), pqCommandQueueAdvance(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGets(), pqInternalNotice(), PQmakeEmptyPGresult(), pqSaveErrorResult(), pqTraceOutputMessage(), PGcmdQueueEntry::queryclass, pg_conn::result, pg_result::resultStatus, strlcpy(), VALID_LONG_MESSAGE_TYPE, and pg_conn::workBuffer.

Referenced by parseInput().

◆ reportErrorPosition()

static void reportErrorPosition ( PQExpBuffer  msg,
const char *  query,
int  loc,
int  encoding 
)
static

Definition at line 1168 of file fe-protocol3.c.

1169 {
1170 #define DISPLAY_SIZE 60 /* screen width limit, in screen cols */
1171 #define MIN_RIGHT_CUT 10 /* try to keep this far away from EOL */
1172 
1173  char *wquery;
1174  int slen,
1175  cno,
1176  i,
1177  *qidx,
1178  *scridx,
1179  qoffset,
1180  scroffset,
1181  ibeg,
1182  iend,
1183  loc_line;
1184  bool mb_encoding,
1185  beg_trunc,
1186  end_trunc;
1187 
1188  /* Convert loc from 1-based to 0-based; no-op if out of range */
1189  loc--;
1190  if (loc < 0)
1191  return;
1192 
1193  /* Need a writable copy of the query */
1194  wquery = strdup(query);
1195  if (wquery == NULL)
1196  return; /* fail silently if out of memory */
1197 
1198  /*
1199  * Each character might occupy multiple physical bytes in the string, and
1200  * in some Far Eastern character sets it might take more than one screen
1201  * column as well. We compute the starting byte offset and starting
1202  * screen column of each logical character, and store these in qidx[] and
1203  * scridx[] respectively.
1204  */
1205 
1206  /* we need a safe allocation size... */
1207  slen = strlen(wquery) + 1;
1208 
1209  qidx = (int *) malloc(slen * sizeof(int));
1210  if (qidx == NULL)
1211  {
1212  free(wquery);
1213  return;
1214  }
1215  scridx = (int *) malloc(slen * sizeof(int));
1216  if (scridx == NULL)
1217  {
1218  free(qidx);
1219  free(wquery);
1220  return;
1221  }
1222 
1223  /* We can optimize a bit if it's a single-byte encoding */
1224  mb_encoding = (pg_encoding_max_length(encoding) != 1);
1225 
1226  /*
1227  * Within the scanning loop, cno is the current character's logical
1228  * number, qoffset is its offset in wquery, and scroffset is its starting
1229  * logical screen column (all indexed from 0). "loc" is the logical
1230  * character number of the error location. We scan to determine loc_line
1231  * (the 1-based line number containing loc) and ibeg/iend (first character
1232  * number and last+1 character number of the line containing loc). Note
1233  * that qidx[] and scridx[] are filled only as far as iend.
1234  */
1235  qoffset = 0;
1236  scroffset = 0;
1237  loc_line = 1;
1238  ibeg = 0;
1239  iend = -1; /* -1 means not set yet */
1240 
1241  for (cno = 0; wquery[qoffset] != '\0'; cno++)
1242  {
1243  char ch = wquery[qoffset];
1244 
1245  qidx[cno] = qoffset;
1246  scridx[cno] = scroffset;
1247 
1248  /*
1249  * Replace tabs with spaces in the writable copy. (Later we might
1250  * want to think about coping with their variable screen width, but
1251  * not today.)
1252  */
1253  if (ch == '\t')
1254  wquery[qoffset] = ' ';
1255 
1256  /*
1257  * If end-of-line, count lines and mark positions. Each \r or \n
1258  * counts as a line except when \r \n appear together.
1259  */
1260  else if (ch == '\r' || ch == '\n')
1261  {
1262  if (cno < loc)
1263  {
1264  if (ch == '\r' ||
1265  cno == 0 ||
1266  wquery[qidx[cno - 1]] != '\r')
1267  loc_line++;
1268  /* extract beginning = last line start before loc. */
1269  ibeg = cno + 1;
1270  }
1271  else
1272  {
1273  /* set extract end. */
1274  iend = cno;
1275  /* done scanning. */
1276  break;
1277  }
1278  }
1279 
1280  /* Advance */
1281  if (mb_encoding)
1282  {
1283  int w;
1284 
1285  w = pg_encoding_dsplen(encoding, &wquery[qoffset]);
1286  /* treat any non-tab control chars as width 1 */
1287  if (w <= 0)
1288  w = 1;
1289  scroffset += w;
1290  qoffset += PQmblenBounded(&wquery[qoffset], encoding);
1291  }
1292  else
1293  {
1294  /* We assume wide chars only exist in multibyte encodings */
1295  scroffset++;
1296  qoffset++;
1297  }
1298  }
1299  /* Fix up if we didn't find an end-of-line after loc */
1300  if (iend < 0)
1301  {
1302  iend = cno; /* query length in chars, +1 */
1303  qidx[iend] = qoffset;
1304  scridx[iend] = scroffset;
1305  }
1306 
1307  /* Print only if loc is within computed query length */
1308  if (loc <= cno)
1309  {
1310  /* If the line extracted is too long, we truncate it. */
1311  beg_trunc = false;
1312  end_trunc = false;
1313  if (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1314  {
1315  /*
1316  * We first truncate right if it is enough. This code might be
1317  * off a space or so on enforcing MIN_RIGHT_CUT if there's a wide
1318  * character right there, but that should be okay.
1319  */
1320  if (scridx[ibeg] + DISPLAY_SIZE >= scridx[loc] + MIN_RIGHT_CUT)
1321  {
1322  while (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1323  iend--;
1324  end_trunc = true;
1325  }
1326  else
1327  {
1328  /* Truncate right if not too close to loc. */
1329  while (scridx[loc] + MIN_RIGHT_CUT < scridx[iend])
1330  {
1331  iend--;
1332  end_trunc = true;
1333  }
1334 
1335  /* Truncate left if still too long. */
1336  while (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1337  {
1338  ibeg++;
1339  beg_trunc = true;
1340  }
1341  }
1342  }
1343 
1344  /* truncate working copy at desired endpoint */
1345  wquery[qidx[iend]] = '\0';
1346 
1347  /* Begin building the finished message. */
1348  i = msg->len;
1349  appendPQExpBuffer(msg, libpq_gettext("LINE %d: "), loc_line);
1350  if (beg_trunc)
1351  appendPQExpBufferStr(msg, "...");
1352 
1353  /*
1354  * While we have the prefix in the msg buffer, compute its screen
1355  * width.
1356  */
1357  scroffset = 0;
1358  for (; i < msg->len; i += PQmblenBounded(&msg->data[i], encoding))
1359  {
1360  int w = pg_encoding_dsplen(encoding, &msg->data[i]);
1361 
1362  if (w <= 0)
1363  w = 1;
1364  scroffset += w;
1365  }
1366 
1367  /* Finish up the LINE message line. */
1368  appendPQExpBufferStr(msg, &wquery[qidx[ibeg]]);
1369  if (end_trunc)
1370  appendPQExpBufferStr(msg, "...");
1371  appendPQExpBufferChar(msg, '\n');
1372 
1373  /* Now emit the cursor marker line. */
1374  scroffset += scridx[loc] - scridx[ibeg];
1375  for (i = 0; i < scroffset; i++)
1376  appendPQExpBufferChar(msg, ' ');
1377  appendPQExpBufferChar(msg, '^');
1378  appendPQExpBufferChar(msg, '\n');
1379  }
1380 
1381  /* Clean up. */
1382  free(scridx);
1383  free(qidx);
1384  free(wquery);
1385 }
int PQmblenBounded(const char *s, int encoding)
Definition: fe-misc.c:1187
#define DISPLAY_SIZE
#define MIN_RIGHT_CUT
int32 encoding
Definition: pg_database.h:41
int pg_encoding_dsplen(int encoding, const char *mbstr)
Definition: wchar.c:2151
int pg_encoding_max_length(int encoding)
Definition: wchar.c:2188

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), PQExpBufferData::data, DISPLAY_SIZE, encoding, free, i, PQExpBufferData::len, libpq_gettext, malloc, MIN_RIGHT_CUT, pg_encoding_dsplen(), pg_encoding_max_length(), and PQmblenBounded().

Referenced by pqBuildErrorMessage3().