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