PostgreSQL Source Code git master
Loading...
Searching...
No Matches
fe-protocol3.c File Reference
#include "postgres_fe.h"
#include <ctype.h>
#include <fcntl.h>
#include <limits.h>
#include <unistd.h>
#include <netinet/tcp.h>
#include "common/int.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 handleFatalError (PGconn *conn)
 
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 getBackendKeyData (PGconn *conn, int msgLength)
 
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 size_t 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)
 
charpqBuildStartupPacket3 (PGconn *conn, int *packetlen, const PQEnvironmentOption *options)
 

Macro Definition Documentation

◆ ADD_STARTUP_OPTION

#define ADD_STARTUP_OPTION (   optname,
  optval 
)
Value:
do { \
strcpy(packet + packet_len, optname); \
return 0; \
return 0; \
} while(0)
static bool pg_add_size_overflow(size_t a, size_t b, size_t *result)
Definition int.h:608
static int fb(int x)

◆ 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) == PqMsg_CopyData || \
(id) == PqMsg_DataRow || \
(id) == PqMsg_ErrorResponse || \
(id) == PqMsg_NoticeResponse || \
#define PqMsg_NotificationResponse
Definition protocol.h:41
#define PqMsg_CopyData
Definition protocol.h:65
#define PqMsg_FunctionCallResponse
Definition protocol.h:53
#define PqMsg_RowDescription
Definition protocol.h:52
#define PqMsg_ErrorResponse
Definition protocol.h:44
#define PqMsg_DataRow
Definition protocol.h:43
#define PqMsg_NoticeResponse
Definition protocol.h:49

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

70{
71 char id;
72 int msgLength;
73 int avail;
74
75 /*
76 * Loop to parse successive complete messages available in the buffer.
77 */
78 for (;;)
79 {
80 /*
81 * Try to read a message. First get the type code and length. Return
82 * if not enough data.
83 */
85 if (pqGetc(&id, conn))
86 return;
87 if (pqGetInt(&msgLength, 4, conn))
88 return;
89
90 /*
91 * Try to validate message type/length here. A length less than 4 is
92 * definitely broken. Large lengths should only be believed for a few
93 * message types.
94 */
95 if (msgLength < 4)
96 {
98 return;
99 }
100 if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
101 {
103 return;
104 }
105
106 /*
107 * Can't process if message body isn't all here yet.
108 */
109 msgLength -= 4;
110 avail = conn->inEnd - conn->inCursor;
111 if (avail < msgLength)
112 {
113 /*
114 * Before returning, enlarge the input buffer if needed to hold
115 * the whole message. This is better than leaving it to
116 * pqReadData because we can avoid multiple cycles of realloc()
117 * when the message is large; also, we can implement a reasonable
118 * recovery strategy if we are unable to make the buffer big
119 * enough.
120 */
122 conn))
123 {
124 /*
125 * Abandon the connection. There's not much else we can
126 * safely do; we can't just ignore the message or we could
127 * miss important changes to the connection state.
128 * pqCheckInBufferSpace() already reported the error.
129 */
131 }
132 return;
133 }
134
135 /*
136 * NOTIFY and NOTICE messages can happen in any state; always process
137 * them right away.
138 *
139 * Most other messages should only be processed while in BUSY state.
140 * (In particular, in READY state we hold off further parsing until
141 * the application collects the current PGresult.)
142 *
143 * However, if the state is IDLE then we got trouble; we need to deal
144 * with the unexpected message somehow.
145 *
146 * ParameterStatus ('S') messages are a special case: in IDLE state we
147 * must process 'em (this case could happen if a new value was adopted
148 * from config file due to SIGHUP), but otherwise we hold off until
149 * BUSY state.
150 */
152 {
153 if (getNotify(conn))
154 return;
155 }
156 else if (id == PqMsg_NoticeResponse)
157 {
158 if (pqGetErrorNotice3(conn, false))
159 return;
160 }
161 else if (conn->asyncStatus != PGASYNC_BUSY)
162 {
163 /* If not IDLE state, just wait ... */
165 return;
166
167 /*
168 * Unexpected message in IDLE state; need to recover somehow.
169 * ERROR messages are handled using the notice processor;
170 * ParameterStatus is handled normally; anything else is just
171 * dropped on the floor after displaying a suitable warning
172 * notice. (An ERROR is very possibly the backend telling us why
173 * it is about to close the connection, so we don't want to just
174 * discard it...)
175 */
176 if (id == PqMsg_ErrorResponse)
177 {
178 if (pqGetErrorNotice3(conn, false /* treat as notice */ ))
179 return;
180 }
181 else if (id == PqMsg_ParameterStatus)
182 {
184 return;
185 }
186 else
187 {
188 /* Any other case is unexpected and we summarily skip it */
190 "message type 0x%02x arrived from server while idle",
191 id);
192 /* Discard the unexpected message */
194 }
195 }
196 else
197 {
198 /*
199 * In BUSY state, we can process everything.
200 */
201 switch (id)
202 {
204 if (pqGets(&conn->workBuffer, conn))
205 return;
207 {
210 if (!conn->result)
211 {
212 libpq_append_conn_error(conn, "out of memory");
214 }
215 }
216 if (conn->result)
220 break;
222 if (pqGetErrorNotice3(conn, true))
223 return;
225 break;
228 return;
230 {
233 if (!conn->result)
234 {
235 libpq_append_conn_error(conn, "out of memory");
237 }
238 else
239 {
242 }
243 }
244 else
245 {
246 /* Advance the command queue and set us idle */
247 pqCommandQueueAdvance(conn, true, false);
249 }
250 break;
253 {
256 if (!conn->result)
257 {
258 libpq_append_conn_error(conn, "out of memory");
260 }
261 }
263 break;
265 /* If we're doing PQprepare, we're done; else ignore */
266 if (conn->cmd_queue_head &&
268 {
270 {
273 if (!conn->result)
274 {
275 libpq_append_conn_error(conn, "out of memory");
277 }
278 }
280 }
281 break;
283 /* Nothing to do for this message type */
284 break;
286 /* If we're doing PQsendClose, we're done; else ignore */
287 if (conn->cmd_queue_head &&
289 {
291 {
294 if (!conn->result)
295 {
296 libpq_append_conn_error(conn, "out of memory");
298 }
299 }
301 }
302 break;
305 return;
306 break;
308
309 /*
310 * This is expected only during backend startup, but it's
311 * just as easy to handle it as part of the main loop.
312 * Save the data and continue processing.
313 */
315 return;
316 break;
318 if (conn->error_result ||
319 (conn->result != NULL &&
321 {
322 /*
323 * We've already choked for some reason. Just discard
324 * the data till we get to the end of the query.
325 */
327 }
328 else if (conn->result == NULL ||
331 {
332 /* First 'T' in a query sequence */
334 return;
335 }
336 else
337 {
338 /*
339 * A new 'T' message is treated as the start of
340 * another PGresult. (It is not clear that this is
341 * really possible with the current backend.) We stop
342 * parsing until the application accepts the current
343 * result.
344 */
346 return;
347 }
348 break;
349 case PqMsg_NoData:
350
351 /*
352 * NoData indicates that we will not be seeing a
353 * RowDescription message because the statement or portal
354 * inquired about doesn't return rows.
355 *
356 * If we're doing a Describe, we have to pass something
357 * back to the client, so set up a COMMAND_OK result,
358 * instead of PGRES_TUPLES_OK. Otherwise we can just
359 * ignore this message.
360 */
361 if (conn->cmd_queue_head &&
363 {
365 {
368 if (!conn->result)
369 {
370 libpq_append_conn_error(conn, "out of memory");
372 }
373 }
375 }
376 break;
379 return;
380 break;
381 case PqMsg_DataRow:
382 if (conn->result != NULL &&
385 {
386 /* Read another tuple of a normal query response */
388 return;
389 }
390 else if (conn->error_result ||
391 (conn->result != NULL &&
393 {
394 /*
395 * We've already choked for some reason. Just discard
396 * tuples till we get to the end of the query.
397 */
399 }
400 else
401 {
402 /* Set up to report error at end of query */
403 libpq_append_conn_error(conn, "server sent data (\"D\" message) without prior row description (\"T\" message)");
405 /* Discard the unexpected message */
407 }
408 break;
411 return;
413 break;
416 return;
419 break;
422 return;
425 break;
426 case PqMsg_CopyData:
427
428 /*
429 * If we see Copy Data, just silently drop it. This would
430 * only occur if application exits COPY OUT mode too
431 * early.
432 */
434 break;
435 case PqMsg_CopyDone:
436
437 /*
438 * If we see Copy Done, just silently drop it. This is
439 * the normal case during PQendcopy. We will keep
440 * swallowing data, expecting to see command-complete for
441 * the COPY command.
442 */
443 break;
444 default:
445 libpq_append_conn_error(conn, "unexpected response from server; first received character was \"%c\"", id);
446 /* build an error result holding the error message */
448 /* not sure if we will see more, so go to ready state */
450 /* Discard the unexpected message */
452 break;
453 } /* switch on protocol character */
454 }
455 /* Successfully consumed this message */
456 if (conn->inCursor == conn->inStart + 5 + msgLength)
457 {
458 /* Normal case: parsing agrees with specified length */
460 }
461 else if (conn->error_result && conn->status == CONNECTION_BAD)
462 {
463 /* The connection was abandoned and we already reported it */
464 return;
465 }
466 else
467 {
468 /* Trouble --- report it */
469 libpq_append_conn_error(conn, "message contents do not agree with length in message type \"%c\"", id);
470 /* build an error result holding the error message */
473 /* trust the specified message length as what to skip */
474 conn->inStart += 5 + msgLength;
475 }
476 }
477}
478
479/*
480 * handleFatalError: clean up after a nonrecoverable error
481 *
482 * This is for errors where we need to abandon the connection. The caller has
483 * already saved the error message in conn->errorMessage.
484 */
485static void
487{
488 /* build an error result holding the error message */
490 conn->asyncStatus = PGASYNC_READY; /* drop out of PQgetResult wait loop */
491 /* flush input data since we're giving up on processing it */
492 pqDropConnection(conn, true);
493 conn->status = CONNECTION_BAD; /* No more connection to backend */
494}
495
496/*
497 * handleSyncLoss: clean up after loss of message-boundary sync
498 *
499 * There isn't really a lot we can do here except abandon the connection.
500 */
501static void
502handleSyncLoss(PGconn *conn, char id, int msgLength)
503{
504 libpq_append_conn_error(conn, "lost synchronization with server: got message type \"%c\", length %d",
505 id, msgLength);
507}
508
509/*
510 * parseInput subroutine to read a 'T' (row descriptions) message.
511 * We'll build a new PGresult structure (unless called for a Describe
512 * command for a prepared statement) containing the attribute data.
513 * Returns: 0 if processed message successfully, EOF to suspend parsing
514 * (the latter case is not actually used currently).
515 */
516static int
518{
519 PGresult *result;
520 int nfields;
521 const char *errmsg;
522 int i;
523
524 /*
525 * When doing Describe for a prepared statement, there'll already be a
526 * PGresult created by getParamDescriptions, and we should fill data into
527 * that. Otherwise, create a new, empty PGresult.
528 */
529 if (!conn->cmd_queue_head ||
532 {
533 if (conn->result)
534 result = conn->result;
535 else
537 }
538 else
540 if (!result)
541 {
542 errmsg = NULL; /* means "out of memory", see below */
544 }
545
546 /* parseInput already read the 'T' label and message length. */
547 /* the next two bytes are the number of fields */
548 if (pqGetInt(&(result->numAttributes), 2, conn))
549 {
550 /* We should not run out of data here, so complain */
551 errmsg = libpq_gettext("insufficient data in \"T\" message");
553 }
554 nfields = result->numAttributes;
555
556 /* allocate space for the attribute descriptors */
557 if (nfields > 0)
558 {
559 result->attDescs = (PGresAttDesc *)
560 pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
561 if (!result->attDescs)
562 {
563 errmsg = NULL; /* means "out of memory", see below */
565 }
566 MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
567 }
568
569 /* result->binary is true only if ALL columns are binary */
570 result->binary = (nfields > 0) ? 1 : 0;
571
572 /* get type info */
573 for (i = 0; i < nfields; i++)
574 {
575 int tableid;
576 int columnid;
577 int typid;
578 int typlen;
579 int atttypmod;
580 int format;
581
582 if (pqGets(&conn->workBuffer, conn) ||
583 pqGetInt(&tableid, 4, conn) ||
584 pqGetInt(&columnid, 2, conn) ||
585 pqGetInt(&typid, 4, conn) ||
586 pqGetInt(&typlen, 2, conn) ||
587 pqGetInt(&atttypmod, 4, conn) ||
588 pqGetInt(&format, 2, conn))
589 {
590 /* We should not run out of data here, so complain */
591 errmsg = libpq_gettext("insufficient data in \"T\" message");
593 }
594
595 /*
596 * Since pqGetInt treats 2-byte integers as unsigned, we need to
597 * coerce these results to signed form.
598 */
599 columnid = (int) ((int16) columnid);
600 typlen = (int) ((int16) typlen);
601 format = (int) ((int16) format);
602
603 result->attDescs[i].name = pqResultStrdup(result,
605 if (!result->attDescs[i].name)
606 {
607 errmsg = NULL; /* means "out of memory", see below */
609 }
610 result->attDescs[i].tableid = tableid;
611 result->attDescs[i].columnid = columnid;
612 result->attDescs[i].format = format;
613 result->attDescs[i].typid = typid;
614 result->attDescs[i].typlen = typlen;
615 result->attDescs[i].atttypmod = atttypmod;
616
617 if (format != 1)
618 result->binary = 0;
619 }
620
621 /* Success! */
622 conn->result = result;
623
624 /*
625 * If we're doing a Describe, we're done, and ready to pass the result
626 * back to the client.
627 */
628 if ((!conn->cmd_queue_head) ||
631 {
633 return 0;
634 }
635
636 /*
637 * We could perform additional setup for the new result set here, but for
638 * now there's nothing else to do.
639 */
640
641 /* And we're done. */
642 return 0;
643
645 /* Discard unsaved result, if any */
646 if (result && result != conn->result)
647 PQclear(result);
648
649 /*
650 * Replace partially constructed result with an error result. First
651 * discard the old result to try to win back some memory.
652 */
654
655 /*
656 * If preceding code didn't provide an error message, assume "out of
657 * memory" was meant. The advantage of having this special case is that
658 * freeing the old result first greatly improves the odds that gettext()
659 * will succeed in providing a translation.
660 */
661 if (!errmsg)
662 errmsg = libpq_gettext("out of memory for query result");
663
666
667 /*
668 * Show the message as fully consumed, else pqParseInput3 will overwrite
669 * our error with a complaint about that.
670 */
672
673 /*
674 * Return zero to allow input parsing to continue. Subsequent "D"
675 * messages will be ignored until we get to end of data, since an error
676 * result is already set up.
677 */
678 return 0;
679}
680
681/*
682 * parseInput subroutine to read a 't' (ParameterDescription) message.
683 * We'll build a new PGresult structure containing the parameter data.
684 * Returns: 0 if processed message successfully, EOF to suspend parsing
685 * (the latter case is not actually used currently).
686 */
687static int
689{
690 PGresult *result;
691 const char *errmsg = NULL; /* means "out of memory", see below */
692 int nparams;
693 int i;
694
696 if (!result)
698
699 /* parseInput already read the 't' label and message length. */
700 /* the next two bytes are the number of parameters */
701 if (pqGetInt(&(result->numParameters), 2, conn))
702 goto not_enough_data;
703 nparams = result->numParameters;
704
705 /* allocate space for the parameter descriptors */
706 if (nparams > 0)
707 {
708 result->paramDescs = (PGresParamDesc *)
709 pqResultAlloc(result, nparams * sizeof(PGresParamDesc), true);
710 if (!result->paramDescs)
712 MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
713 }
714
715 /* get parameter info */
716 for (i = 0; i < nparams; i++)
717 {
718 int typid;
719
720 if (pqGetInt(&typid, 4, conn))
721 goto not_enough_data;
722 result->paramDescs[i].typid = typid;
723 }
724
725 /* Success! */
726 conn->result = result;
727
728 return 0;
729
731 errmsg = libpq_gettext("insufficient data in \"t\" message");
732
734 /* Discard unsaved result, if any */
735 if (result && result != conn->result)
736 PQclear(result);
737
738 /*
739 * Replace partially constructed result with an error result. First
740 * discard the old result to try to win back some memory.
741 */
743
744 /*
745 * If preceding code didn't provide an error message, assume "out of
746 * memory" was meant. The advantage of having this special case is that
747 * freeing the old result first greatly improves the odds that gettext()
748 * will succeed in providing a translation.
749 */
750 if (!errmsg)
751 errmsg = libpq_gettext("out of memory");
754
755 /*
756 * Show the message as fully consumed, else pqParseInput3 will overwrite
757 * our error with a complaint about that.
758 */
760
761 /*
762 * Return zero to allow input parsing to continue. Essentially, we've
763 * replaced the COMMAND_OK result with an error result, but since this
764 * doesn't affect the protocol state, it's fine.
765 */
766 return 0;
767}
768
769/*
770 * parseInput subroutine to read a 'D' (row data) message.
771 * We fill rowbuf with column pointers and then call the row processor.
772 * Returns: 0 if processed message successfully, EOF to suspend parsing
773 * (the latter case is not actually used currently).
774 */
775static int
777{
778 PGresult *result = conn->result;
779 int nfields = result->numAttributes;
780 const char *errmsg;
782 int tupnfields; /* # fields from tuple */
783 int vlen; /* length of the current field value */
784 int i;
785
786 /* Get the field count and make sure it's what we expect */
787 if (pqGetInt(&tupnfields, 2, conn))
788 {
789 /* We should not run out of data here, so complain */
790 errmsg = libpq_gettext("insufficient data in \"D\" message");
792 }
793
794 if (tupnfields != nfields)
795 {
796 errmsg = libpq_gettext("unexpected field count in \"D\" message");
798 }
799
800 /* Resize row buffer if needed */
801 rowbuf = conn->rowBuf;
802 if (nfields > conn->rowBufLen)
803 {
805 nfields * sizeof(PGdataValue));
806 if (!rowbuf)
807 {
808 errmsg = NULL; /* means "out of memory", see below */
810 }
811 conn->rowBuf = rowbuf;
812 conn->rowBufLen = nfields;
813 }
814
815 /* Scan the fields */
816 for (i = 0; i < nfields; i++)
817 {
818 /* get the value length */
819 if (pqGetInt(&vlen, 4, conn))
820 {
821 /* We should not run out of data here, so complain */
822 errmsg = libpq_gettext("insufficient data in \"D\" message");
824 }
825 rowbuf[i].len = vlen;
826
827 /*
828 * rowbuf[i].value always points to the next address in the data
829 * buffer even if the value is NULL. This allows row processors to
830 * estimate data sizes more easily.
831 */
832 rowbuf[i].value = conn->inBuffer + conn->inCursor;
833
834 /* Skip over the data value */
835 if (vlen > 0)
836 {
837 if (pqSkipnchar(vlen, conn))
838 {
839 /* We should not run out of data here, so complain */
840 errmsg = libpq_gettext("insufficient data in \"D\" message");
842 }
843 }
844 }
845
846 /* Process the collected row */
847 errmsg = NULL;
849 return 0; /* normal, successful exit */
850
851 /* pqRowProcessor failed, fall through to report it */
852
854
855 /*
856 * Replace partially constructed result with an error result. First
857 * discard the old result to try to win back some memory.
858 */
860
861 /*
862 * If preceding code didn't provide an error message, assume "out of
863 * memory" was meant. The advantage of having this special case is that
864 * freeing the old result first greatly improves the odds that gettext()
865 * will succeed in providing a translation.
866 */
867 if (!errmsg)
868 errmsg = libpq_gettext("out of memory for query result");
869
872
873 /*
874 * Show the message as fully consumed, else pqParseInput3 will overwrite
875 * our error with a complaint about that.
876 */
878
879 /*
880 * Return zero to allow input parsing to continue. Subsequent "D"
881 * messages will be ignored until we get to end of data, since an error
882 * result is already set up.
883 */
884 return 0;
885}
886
887
888/*
889 * Attempt to read an Error or Notice response message.
890 * This is possible in several places, so we break it out as a subroutine.
891 *
892 * Entry: 'E' or 'N' message type and length have already been consumed.
893 * Exit: returns 0 if successfully consumed message.
894 * returns EOF if not enough data.
895 */
896int
898{
899 PGresult *res = NULL;
900 bool have_position = false;
902 char id;
903
904 /* If in pipeline mode, set error indicator for it */
907
908 /*
909 * If this is an error message, pre-emptively clear any incomplete query
910 * result we may have. We'd just throw it away below anyway, and
911 * releasing it before collecting the error might avoid out-of-memory.
912 */
913 if (isError)
915
916 /*
917 * Since the fields might be pretty long, we create a temporary
918 * PQExpBuffer rather than using conn->workBuffer. workBuffer is intended
919 * for stuff that is expected to be short. We shouldn't use
920 * conn->errorMessage either, since this might be only a notice.
921 */
923
924 /*
925 * Make a PGresult to hold the accumulated fields. We temporarily lie
926 * about the result status, so that PQmakeEmptyPGresult doesn't uselessly
927 * copy conn->errorMessage.
928 *
929 * NB: This allocation can fail, if you run out of memory. The rest of the
930 * function handles that gracefully, and we still try to set the error
931 * message as the connection's error message.
932 */
934 if (res)
936
937 /*
938 * Read the fields and save into res.
939 *
940 * While at it, save the SQLSTATE in conn->last_sqlstate, and note whether
941 * we saw a PG_DIAG_STATEMENT_POSITION field.
942 */
943 for (;;)
944 {
945 if (pqGetc(&id, conn))
946 goto fail;
947 if (id == '\0')
948 break; /* terminator found */
949 if (pqGets(&workBuf, conn))
950 goto fail;
951 pqSaveMessageField(res, id, workBuf.data);
952 if (id == PG_DIAG_SQLSTATE)
954 sizeof(conn->last_sqlstate));
955 else if (id == PG_DIAG_STATEMENT_POSITION)
956 have_position = true;
957 }
958
959 /*
960 * Save the active query text, if any, into res as well; but only if we
961 * might need it for an error cursor display, which is only true if there
962 * is a PG_DIAG_STATEMENT_POSITION field.
963 */
966
967 /*
968 * Now build the "overall" error message for PQresultErrorMessage.
969 */
972
973 /*
974 * Either save error as current async result, or just emit the notice.
975 */
976 if (isError)
977 {
978 pqClearAsyncResult(conn); /* redundant, but be safe */
979 if (res)
980 {
981 pqSetResultError(res, &workBuf, 0);
982 conn->result = res;
983 }
984 else
985 {
986 /* Fall back to using the internal-error processing paths */
987 conn->error_result = true;
988 }
989
991 libpq_append_conn_error(conn, "out of memory");
992 else
994 }
995 else
996 {
997 /* if we couldn't allocate the result set, just discard the NOTICE */
998 if (res)
999 {
1000 /*
1001 * We can cheat a little here and not copy the message. But if we
1002 * were unlucky enough to run out of memory while filling workBuf,
1003 * insert "out of memory", as in pqSetResultError.
1004 */
1006 res->errMsg = libpq_gettext("out of memory\n");
1007 else
1008 res->errMsg = workBuf.data;
1009 if (res->noticeHooks.noticeRec != NULL)
1011 PQclear(res);
1012 }
1013 }
1014
1016 return 0;
1017
1018fail:
1019 PQclear(res);
1021 return EOF;
1022}
1023
1024/*
1025 * Construct an error message from the fields in the given PGresult,
1026 * appending it to the contents of "msg".
1027 */
1028void
1030 PGVerbosity verbosity, PGContextVisibility show_context)
1031{
1032 const char *val;
1033 const char *querytext = NULL;
1034 int querypos = 0;
1035
1036 /* If we couldn't allocate a PGresult, just say "out of memory" */
1037 if (res == NULL)
1038 {
1039 appendPQExpBufferStr(msg, libpq_gettext("out of memory\n"));
1040 return;
1041 }
1042
1043 /*
1044 * If we don't have any broken-down fields, just return the base message.
1045 * This mainly applies if we're given a libpq-generated error result.
1046 */
1047 if (res->errFields == NULL)
1048 {
1049 if (res->errMsg && res->errMsg[0])
1050 appendPQExpBufferStr(msg, res->errMsg);
1051 else
1052 appendPQExpBufferStr(msg, libpq_gettext("no error message available\n"));
1053 return;
1054 }
1055
1056 /* Else build error message from relevant fields */
1058 if (val)
1059 appendPQExpBuffer(msg, "%s: ", val);
1060
1061 if (verbosity == PQERRORS_SQLSTATE)
1062 {
1063 /*
1064 * If we have a SQLSTATE, print that and nothing else. If not (which
1065 * shouldn't happen for server-generated errors, but might possibly
1066 * happen for libpq-generated ones), fall back to TERSE format, as
1067 * that seems better than printing nothing at all.
1068 */
1070 if (val)
1071 {
1072 appendPQExpBuffer(msg, "%s\n", val);
1073 return;
1074 }
1075 verbosity = PQERRORS_TERSE;
1076 }
1077
1078 if (verbosity == PQERRORS_VERBOSE)
1079 {
1081 if (val)
1082 appendPQExpBuffer(msg, "%s: ", val);
1083 }
1085 if (val)
1088 if (val)
1089 {
1090 if (verbosity != PQERRORS_TERSE && res->errQuery != NULL)
1091 {
1092 /* emit position as a syntax cursor display */
1093 querytext = res->errQuery;
1094 querypos = atoi(val);
1095 }
1096 else
1097 {
1098 /* emit position as text addition to primary message */
1099 /* translator: %s represents a digit string */
1100 appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1101 val);
1102 }
1103 }
1104 else
1105 {
1107 if (val)
1108 {
1110 if (verbosity != PQERRORS_TERSE && querytext != NULL)
1111 {
1112 /* emit position as a syntax cursor display */
1113 querypos = atoi(val);
1114 }
1115 else
1116 {
1117 /* emit position as text addition to primary message */
1118 /* translator: %s represents a digit string */
1119 appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1120 val);
1121 }
1122 }
1123 }
1124 appendPQExpBufferChar(msg, '\n');
1125 if (verbosity != PQERRORS_TERSE)
1126 {
1127 if (querytext && querypos > 0)
1129 res->client_encoding);
1131 if (val)
1132 appendPQExpBuffer(msg, libpq_gettext("DETAIL: %s\n"), val);
1134 if (val)
1135 appendPQExpBuffer(msg, libpq_gettext("HINT: %s\n"), val);
1137 if (val)
1138 appendPQExpBuffer(msg, libpq_gettext("QUERY: %s\n"), val);
1139 if (show_context == PQSHOW_CONTEXT_ALWAYS ||
1140 (show_context == PQSHOW_CONTEXT_ERRORS &&
1142 {
1144 if (val)
1145 appendPQExpBuffer(msg, libpq_gettext("CONTEXT: %s\n"),
1146 val);
1147 }
1148 }
1149 if (verbosity == PQERRORS_VERBOSE)
1150 {
1152 if (val)
1154 libpq_gettext("SCHEMA NAME: %s\n"), val);
1156 if (val)
1158 libpq_gettext("TABLE NAME: %s\n"), val);
1160 if (val)
1162 libpq_gettext("COLUMN NAME: %s\n"), val);
1164 if (val)
1166 libpq_gettext("DATATYPE NAME: %s\n"), val);
1168 if (val)
1170 libpq_gettext("CONSTRAINT NAME: %s\n"), val);
1171 }
1172 if (verbosity == PQERRORS_VERBOSE)
1173 {
1174 const char *valf;
1175 const char *vall;
1176
1180 if (val || valf || vall)
1181 {
1182 appendPQExpBufferStr(msg, libpq_gettext("LOCATION: "));
1183 if (val)
1184 appendPQExpBuffer(msg, libpq_gettext("%s, "), val);
1185 if (valf && vall) /* unlikely we'd have just one */
1186 appendPQExpBuffer(msg, libpq_gettext("%s:%s"),
1187 valf, vall);
1188 appendPQExpBufferChar(msg, '\n');
1189 }
1190 }
1191}
1192
1193/*
1194 * Add an error-location display to the error message under construction.
1195 *
1196 * The cursor location is measured in logical characters; the query string
1197 * is presumed to be in the specified encoding.
1198 */
1199static void
1200reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding)
1201{
1202#define DISPLAY_SIZE 60 /* screen width limit, in screen cols */
1203#define MIN_RIGHT_CUT 10 /* try to keep this far away from EOL */
1204
1205 char *wquery;
1206 int slen,
1207 cno,
1208 i,
1209 *qidx,
1210 *scridx,
1211 qoffset,
1212 scroffset,
1213 ibeg,
1214 iend,
1215 loc_line;
1216 bool mb_encoding,
1217 beg_trunc,
1218 end_trunc;
1219
1220 /* Convert loc from 1-based to 0-based; no-op if out of range */
1221 loc--;
1222 if (loc < 0)
1223 return;
1224
1225 /* Need a writable copy of the query */
1226 wquery = strdup(query);
1227 if (wquery == NULL)
1228 return; /* fail silently if out of memory */
1229
1230 /*
1231 * Each character might occupy multiple physical bytes in the string, and
1232 * in some Far Eastern character sets it might take more than one screen
1233 * column as well. We compute the starting byte offset and starting
1234 * screen column of each logical character, and store these in qidx[] and
1235 * scridx[] respectively.
1236 */
1237
1238 /*
1239 * We need a safe allocation size.
1240 *
1241 * The only caller of reportErrorPosition() is pqBuildErrorMessage3(); it
1242 * gets its query from either a PQresultErrorField() or a PGcmdQueueEntry,
1243 * both of which must have fit into conn->inBuffer/outBuffer. So slen fits
1244 * inside an int, but we can't assume that (slen * sizeof(int)) fits
1245 * inside a size_t.
1246 */
1247 slen = strlen(wquery) + 1;
1248 if (slen > SIZE_MAX / sizeof(int))
1249 {
1250 free(wquery);
1251 return;
1252 }
1253
1254 qidx = (int *) malloc(slen * sizeof(int));
1255 if (qidx == NULL)
1256 {
1257 free(wquery);
1258 return;
1259 }
1260 scridx = (int *) malloc(slen * sizeof(int));
1261 if (scridx == NULL)
1262 {
1263 free(qidx);
1264 free(wquery);
1265 return;
1266 }
1267
1268 /* We can optimize a bit if it's a single-byte encoding */
1270
1271 /*
1272 * Within the scanning loop, cno is the current character's logical
1273 * number, qoffset is its offset in wquery, and scroffset is its starting
1274 * logical screen column (all indexed from 0). "loc" is the logical
1275 * character number of the error location. We scan to determine loc_line
1276 * (the 1-based line number containing loc) and ibeg/iend (first character
1277 * number and last+1 character number of the line containing loc). Note
1278 * that qidx[] and scridx[] are filled only as far as iend.
1279 */
1280 qoffset = 0;
1281 scroffset = 0;
1282 loc_line = 1;
1283 ibeg = 0;
1284 iend = -1; /* -1 means not set yet */
1285
1286 for (cno = 0; wquery[qoffset] != '\0'; cno++)
1287 {
1288 char ch = wquery[qoffset];
1289
1290 qidx[cno] = qoffset;
1291 scridx[cno] = scroffset;
1292
1293 /*
1294 * Replace tabs with spaces in the writable copy. (Later we might
1295 * want to think about coping with their variable screen width, but
1296 * not today.)
1297 */
1298 if (ch == '\t')
1299 wquery[qoffset] = ' ';
1300
1301 /*
1302 * If end-of-line, count lines and mark positions. Each \r or \n
1303 * counts as a line except when \r \n appear together.
1304 */
1305 else if (ch == '\r' || ch == '\n')
1306 {
1307 if (cno < loc)
1308 {
1309 if (ch == '\r' ||
1310 cno == 0 ||
1311 wquery[qidx[cno - 1]] != '\r')
1312 loc_line++;
1313 /* extract beginning = last line start before loc. */
1314 ibeg = cno + 1;
1315 }
1316 else
1317 {
1318 /* set extract end. */
1319 iend = cno;
1320 /* done scanning. */
1321 break;
1322 }
1323 }
1324
1325 /* Advance */
1326 if (mb_encoding)
1327 {
1328 int w;
1329
1331 /* treat any non-tab control chars as width 1 */
1332 if (w <= 0)
1333 w = 1;
1334 scroffset += w;
1336 }
1337 else
1338 {
1339 /* We assume wide chars only exist in multibyte encodings */
1340 scroffset++;
1341 qoffset++;
1342 }
1343 }
1344 /* Fix up if we didn't find an end-of-line after loc */
1345 if (iend < 0)
1346 {
1347 iend = cno; /* query length in chars, +1 */
1348 qidx[iend] = qoffset;
1350 }
1351
1352 /* Print only if loc is within computed query length */
1353 if (loc <= cno)
1354 {
1355 /* If the line extracted is too long, we truncate it. */
1356 beg_trunc = false;
1357 end_trunc = false;
1359 {
1360 /*
1361 * We first truncate right if it is enough. This code might be
1362 * off a space or so on enforcing MIN_RIGHT_CUT if there's a wide
1363 * character right there, but that should be okay.
1364 */
1365 if (scridx[ibeg] + DISPLAY_SIZE >= scridx[loc] + MIN_RIGHT_CUT)
1366 {
1367 while (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1368 iend--;
1369 end_trunc = true;
1370 }
1371 else
1372 {
1373 /* Truncate right if not too close to loc. */
1374 while (scridx[loc] + MIN_RIGHT_CUT < scridx[iend])
1375 {
1376 iend--;
1377 end_trunc = true;
1378 }
1379
1380 /* Truncate left if still too long. */
1381 while (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1382 {
1383 ibeg++;
1384 beg_trunc = true;
1385 }
1386 }
1387 }
1388
1389 /* truncate working copy at desired endpoint */
1390 wquery[qidx[iend]] = '\0';
1391
1392 /* Begin building the finished message. */
1393 i = msg->len;
1394 appendPQExpBuffer(msg, libpq_gettext("LINE %d: "), loc_line);
1395 if (beg_trunc)
1396 appendPQExpBufferStr(msg, "...");
1397
1398 /*
1399 * While we have the prefix in the msg buffer, compute its screen
1400 * width.
1401 */
1402 scroffset = 0;
1403 for (; i < msg->len; i += PQmblenBounded(&msg->data[i], encoding))
1404 {
1405 int w = pg_encoding_dsplen(encoding, &msg->data[i]);
1406
1407 if (w <= 0)
1408 w = 1;
1409 scroffset += w;
1410 }
1411
1412 /* Finish up the LINE message line. */
1414 if (end_trunc)
1415 appendPQExpBufferStr(msg, "...");
1416 appendPQExpBufferChar(msg, '\n');
1417
1418 /* Now emit the cursor marker line. */
1419 scroffset += scridx[loc] - scridx[ibeg];
1420 for (i = 0; i < scroffset; i++)
1421 appendPQExpBufferChar(msg, ' ');
1422 appendPQExpBufferChar(msg, '^');
1423 appendPQExpBufferChar(msg, '\n');
1424 }
1425
1426 /* Clean up. */
1427 free(scridx);
1428 free(qidx);
1429 free(wquery);
1430}
1431
1432
1433/*
1434 * Attempt to read a NegotiateProtocolVersion message. Sets conn->pversion
1435 * to the version that's negotiated by the server.
1436 *
1437 * Entry: 'v' message type and length have already been consumed.
1438 * Exit: returns 0 if successfully consumed message.
1439 * returns 1 on failure. The error message is filled in.
1440 */
1441int
1443{
1444 int their_version;
1445 int num;
1448
1449 /*
1450 * During 19beta only, if protocol grease is in use, assume that it's the
1451 * cause of any invalid messages encountered below. We'll print extra
1452 * information for the end user in that case.
1453 */
1455
1456 if (pqGetInt(&their_version, 4, conn) != 0)
1457 goto eof;
1458
1459 if (pqGetInt(&num, 4, conn) != 0)
1460 goto eof;
1461
1462 /*
1463 * Check the protocol version.
1464 *
1465 * PG_PROTOCOL_GREASE is intentionally unsupported and reserved. It's
1466 * higher than any real version, so check for that first, to get the most
1467 * specific error message. Then check the upper and lower bounds.
1468 */
1470 {
1471 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requested \"grease\" protocol version 3.9999");
1472 goto failure;
1473 }
1474
1476 {
1477 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requested downgrade to a higher-numbered version");
1478 goto failure;
1479 }
1480
1481 if (their_version < PG_PROTOCOL(3, 0))
1482 {
1483 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requested downgrade to pre-3.0 protocol version");
1484 goto failure;
1485 }
1486
1487 /* 3.1 never existed, we went straight from 3.0 to 3.2 */
1489 {
1490 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requested downgrade to non-existent 3.1 protocol version");
1491 goto failure;
1492 }
1493
1494 if (num < 0)
1495 {
1496 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported negative number of unsupported parameters");
1497 goto failure;
1498 }
1499
1500 if (their_version == conn->pversion && num == 0)
1501 {
1502 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server negotiated but asks for no changes");
1503 goto failure;
1504 }
1505
1506 if (their_version < conn->min_pversion)
1507 {
1508 libpq_append_conn_error(conn, "server only supports protocol version %d.%d, but \"%s\" was set to %d.%d",
1511 "min_protocol_version",
1514
1515 need_grease_info = false; /* this is valid server behavior */
1516 goto failure;
1517 }
1518
1519 /* the version is acceptable */
1521
1522 /*
1523 * Check that all expected unsupported parameters are reported by the
1524 * server.
1525 */
1528
1529 for (int i = 0; i < num; i++)
1530 {
1531 if (pqGets(&conn->workBuffer, conn))
1532 {
1533 goto eof;
1534 }
1535 if (strncmp(conn->workBuffer.data, "_pq_.", 5) != 0)
1536 {
1537 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported unsupported parameter name without a \"%s\" prefix (\"%s\")", "_pq_.", conn->workBuffer.data);
1538 goto failure;
1539 }
1540
1541 /* Check if this is the expected test parameter */
1543 strcmp(conn->workBuffer.data, "_pq_.test_protocol_negotiation") == 0)
1544 {
1546 }
1547 else
1548 {
1549 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported an unsupported parameter that was not requested (\"%s\")",
1551 goto failure;
1552 }
1553 }
1554
1555 /*
1556 * If we requested protocol grease, the server must report
1557 * _pq_.test_protocol_negotiation as unsupported. This ensures
1558 * comprehensive NegotiateProtocolVersion implementation.
1559 */
1561 {
1562 libpq_append_conn_error(conn, "server did not report the unsupported `_pq_.test_protocol_negotiation` parameter in its protocol negotiation message");
1563 goto failure;
1564 }
1565
1566 return 0;
1567
1568eof:
1569 libpq_append_conn_error(conn, "received invalid protocol negotiation message: message too short");
1570failure:
1571 if (need_grease_info)
1575 return 1;
1576}
1577
1578
1579/*
1580 * Attempt to read a ParameterStatus message.
1581 * This is possible in several places, so we break it out as a subroutine.
1582 *
1583 * Entry: 'S' message type and length have already been consumed.
1584 * Exit: returns 0 if successfully consumed message.
1585 * returns EOF if not enough data.
1586 */
1587static int
1589{
1591
1592 /* Get the parameter name */
1593 if (pqGets(&conn->workBuffer, conn))
1594 return EOF;
1595 /* Get the parameter value (could be large) */
1597 if (pqGets(&valueBuf, conn))
1598 {
1600 return EOF;
1601 }
1602 /* And save it */
1604 {
1605 libpq_append_conn_error(conn, "out of memory");
1607 }
1609 return 0;
1610}
1611
1612/*
1613 * parseInput subroutine to read a BackendKeyData message.
1614 * Entry: 'v' message type and length have already been consumed.
1615 * Exit: returns 0 if successfully consumed message.
1616 * returns EOF if not enough data.
1617 */
1618static int
1620{
1621 int cancel_key_len;
1622
1623 if (conn->be_cancel_key)
1624 {
1628 }
1629
1630 if (pqGetInt(&(conn->be_pid), 4, conn))
1631 return EOF;
1632
1634
1635 if (cancel_key_len != 4 && conn->pversion == PG_PROTOCOL(3, 0))
1636 {
1637 libpq_append_conn_error(conn, "received invalid BackendKeyData message: cancel key with length %d not allowed in protocol version 3.0 (must be 4 bytes)", cancel_key_len);
1639 return 0;
1640 }
1641
1642 if (cancel_key_len < 4)
1643 {
1644 libpq_append_conn_error(conn, "received invalid BackendKeyData message: cancel key with length %d is too short (minimum 4 bytes)", cancel_key_len);
1646 return 0;
1647 }
1648
1649 if (cancel_key_len > 256)
1650 {
1651 libpq_append_conn_error(conn, "received invalid BackendKeyData message: cancel key with length %d is too long (maximum 256 bytes)", cancel_key_len);
1653 return 0;
1654 }
1655
1657 if (conn->be_cancel_key == NULL)
1658 {
1659 libpq_append_conn_error(conn, "out of memory");
1661 return 0;
1662 }
1664 {
1667 return EOF;
1668 }
1670 return 0;
1671}
1672
1673
1674/*
1675 * Attempt to read a Notify response message.
1676 * This is possible in several places, so we break it out as a subroutine.
1677 *
1678 * Entry: 'A' message type and length have already been consumed.
1679 * Exit: returns 0 if successfully consumed Notify message.
1680 * returns EOF if not enough data.
1681 */
1682static int
1684{
1685 int be_pid;
1686 char *svname;
1687 int nmlen;
1688 int extralen;
1690
1691 if (pqGetInt(&be_pid, 4, conn))
1692 return EOF;
1693 if (pqGets(&conn->workBuffer, conn))
1694 return EOF;
1695 /* must save name while getting extra string */
1697 if (!svname)
1698 {
1699 /*
1700 * Notify messages can arrive at any state, so we cannot associate the
1701 * error with any particular query. There's no way to return back an
1702 * "async error", so the best we can do is drop the connection. That
1703 * seems better than silently ignoring the notification.
1704 */
1705 libpq_append_conn_error(conn, "out of memory");
1707 return 0;
1708 }
1709 if (pqGets(&conn->workBuffer, conn))
1710 {
1711 free(svname);
1712 return EOF;
1713 }
1714
1715 /*
1716 * Store the strings right after the PGnotify structure so it can all be
1717 * freed at once. We don't use NAMEDATALEN because we don't want to tie
1718 * this interface to a specific server name length.
1719 */
1720 nmlen = strlen(svname);
1722 newNotify = (PGnotify *) malloc(sizeof(PGnotify) + nmlen + extralen + 2);
1723 if (!newNotify)
1724 {
1725 free(svname);
1726 libpq_append_conn_error(conn, "out of memory");
1728 return 0;
1729 }
1730
1731 newNotify->relname = (char *) newNotify + sizeof(PGnotify);
1732 strcpy(newNotify->relname, svname);
1733 newNotify->extra = newNotify->relname + nmlen + 1;
1735 newNotify->be_pid = be_pid;
1736 newNotify->next = NULL;
1737 if (conn->notifyTail)
1739 else
1742
1743 free(svname);
1744 return 0;
1745}
1746
1747/*
1748 * getCopyStart - process CopyInResponse, CopyOutResponse or
1749 * CopyBothResponse message
1750 *
1751 * parseInput already read the message type and length.
1752 */
1753static int
1755{
1756 PGresult *result;
1757 int nfields;
1758 int i;
1759
1761 if (!result)
1762 goto failure;
1763
1765 goto failure;
1766 result->binary = conn->copy_is_binary;
1767 /* the next two bytes are the number of fields */
1768 if (pqGetInt(&(result->numAttributes), 2, conn))
1769 goto failure;
1770 nfields = result->numAttributes;
1771
1772 /* allocate space for the attribute descriptors */
1773 if (nfields > 0)
1774 {
1775 result->attDescs = (PGresAttDesc *)
1776 pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
1777 if (!result->attDescs)
1778 goto failure;
1779 MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
1780 }
1781
1782 for (i = 0; i < nfields; i++)
1783 {
1784 int format;
1785
1786 if (pqGetInt(&format, 2, conn))
1787 goto failure;
1788
1789 /*
1790 * Since pqGetInt treats 2-byte integers as unsigned, we need to
1791 * coerce these results to signed form.
1792 */
1793 format = (int) ((int16) format);
1794 result->attDescs[i].format = format;
1795 }
1796
1797 /* Success! */
1798 conn->result = result;
1799 return 0;
1800
1801failure:
1802 PQclear(result);
1803 return EOF;
1804}
1805
1806/*
1807 * getReadyForQuery - process ReadyForQuery message
1808 */
1809static int
1811{
1812 char xact_status;
1813
1814 if (pqGetc(&xact_status, conn))
1815 return EOF;
1816 switch (xact_status)
1817 {
1818 case 'I':
1820 break;
1821 case 'T':
1823 break;
1824 case 'E':
1826 break;
1827 default:
1829 break;
1830 }
1831
1832 return 0;
1833}
1834
1835/*
1836 * getCopyDataMessage - fetch next CopyData message, process async messages
1837 *
1838 * Returns length word of CopyData message (> 0), or 0 if no complete
1839 * message available, -1 if end of copy, -2 if error.
1840 */
1841static int
1843{
1844 char id;
1845 int msgLength;
1846 int avail;
1847
1848 for (;;)
1849 {
1850 /*
1851 * Do we have the next input message? To make life simpler for async
1852 * callers, we keep returning 0 until the next message is fully
1853 * available, even if it is not Copy Data.
1854 */
1856 if (pqGetc(&id, conn))
1857 return 0;
1858 if (pqGetInt(&msgLength, 4, conn))
1859 return 0;
1860 if (msgLength < 4)
1861 {
1863 return -2;
1864 }
1865 avail = conn->inEnd - conn->inCursor;
1866 if (avail < msgLength - 4)
1867 {
1868 /*
1869 * Before returning, enlarge the input buffer if needed to hold
1870 * the whole message. See notes in parseInput.
1871 */
1872 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength - 4,
1873 conn))
1874 {
1875 /*
1876 * Abandon the connection. There's not much else we can
1877 * safely do; we can't just ignore the message or we could
1878 * miss important changes to the connection state.
1879 * pqCheckInBufferSpace() already reported the error.
1880 */
1882 return -2;
1883 }
1884 return 0;
1885 }
1886
1887 /*
1888 * If it's a legitimate async message type, process it. (NOTIFY
1889 * messages are not currently possible here, but we handle them for
1890 * completeness.) Otherwise, if it's anything except Copy Data,
1891 * report end-of-copy.
1892 */
1893 switch (id)
1894 {
1896 if (getNotify(conn))
1897 return 0;
1898 break;
1900 if (pqGetErrorNotice3(conn, false))
1901 return 0;
1902 break;
1905 return 0;
1906 break;
1907 case PqMsg_CopyData:
1908 return msgLength;
1909 case PqMsg_CopyDone:
1910
1911 /*
1912 * If this is a CopyDone message, exit COPY_OUT mode and let
1913 * caller read status with PQgetResult(). If we're in
1914 * COPY_BOTH mode, return to COPY_IN mode.
1915 */
1918 else
1920 return -1;
1921 default: /* treat as end of copy */
1922
1923 /*
1924 * Any other message terminates either COPY_IN or COPY_BOTH
1925 * mode.
1926 */
1928 return -1;
1929 }
1930
1931 /* Drop the processed message and loop around for another */
1933 }
1934}
1935
1936/*
1937 * PQgetCopyData - read a row of data from the backend during COPY OUT
1938 * or COPY BOTH
1939 *
1940 * If successful, sets *buffer to point to a malloc'd row of data, and
1941 * returns row length (always > 0) as result.
1942 * Returns 0 if no row available yet (only possible if async is true),
1943 * -1 if end of copy (consult PQgetResult), or -2 if error (consult
1944 * PQerrorMessage).
1945 */
1946int
1947pqGetCopyData3(PGconn *conn, char **buffer, int async)
1948{
1949 int msgLength;
1950
1951 for (;;)
1952 {
1953 /*
1954 * Collect the next input message. To make life simpler for async
1955 * callers, we keep returning 0 until the next message is fully
1956 * available, even if it is not Copy Data.
1957 */
1959 if (msgLength < 0)
1960 return msgLength; /* end-of-copy or error */
1961 if (msgLength == 0)
1962 {
1963 /* Don't block if async read requested */
1964 if (async)
1965 return 0;
1966 /* Need to load more data */
1967 if (pqWait(true, false, conn) ||
1968 pqReadData(conn) < 0)
1969 return -2;
1970 continue;
1971 }
1972
1973 /*
1974 * Drop zero-length messages (shouldn't happen anyway). Otherwise
1975 * pass the data back to the caller.
1976 */
1977 msgLength -= 4;
1978 if (msgLength > 0)
1979 {
1980 *buffer = (char *) malloc(msgLength + 1);
1981 if (*buffer == NULL)
1982 {
1983 libpq_append_conn_error(conn, "out of memory");
1984 return -2;
1985 }
1986 memcpy(*buffer, &conn->inBuffer[conn->inCursor], msgLength);
1987 (*buffer)[msgLength] = '\0'; /* Add terminating null */
1988
1989 /* Mark message consumed */
1991
1992 return msgLength;
1993 }
1994
1995 /* Empty, so drop it and loop around for another */
1997 }
1998}
1999
2000/*
2001 * PQgetline - gets a newline-terminated string from the backend.
2002 *
2003 * See fe-exec.c for documentation.
2004 */
2005int
2006pqGetline3(PGconn *conn, char *s, int maxlen)
2007{
2008 int status;
2009
2010 if (conn->sock == PGINVALID_SOCKET ||
2014 {
2015 libpq_append_conn_error(conn, "PQgetline: not doing text COPY OUT");
2016 *s = '\0';
2017 return EOF;
2018 }
2019
2020 while ((status = PQgetlineAsync(conn, s, maxlen - 1)) == 0)
2021 {
2022 /* need to load more data */
2023 if (pqWait(true, false, conn) ||
2024 pqReadData(conn) < 0)
2025 {
2026 *s = '\0';
2027 return EOF;
2028 }
2029 }
2030
2031 if (status < 0)
2032 {
2033 /* End of copy detected; gin up old-style terminator */
2034 strcpy(s, "\\.");
2035 return 0;
2036 }
2037
2038 /* Add null terminator, and strip trailing \n if present */
2039 if (s[status - 1] == '\n')
2040 {
2041 s[status - 1] = '\0';
2042 return 0;
2043 }
2044 else
2045 {
2046 s[status] = '\0';
2047 return 1;
2048 }
2049}
2050
2051/*
2052 * PQgetlineAsync - gets a COPY data row without blocking.
2053 *
2054 * See fe-exec.c for documentation.
2055 */
2056int
2057pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)
2058{
2059 int msgLength;
2060 int avail;
2061
2064 return -1; /* we are not doing a copy... */
2065
2066 /*
2067 * Recognize the next input message. To make life simpler for async
2068 * callers, we keep returning 0 until the next message is fully available
2069 * even if it is not Copy Data. This should keep PQendcopy from blocking.
2070 * (Note: unlike pqGetCopyData3, we do not change asyncStatus here.)
2071 */
2073 if (msgLength < 0)
2074 return -1; /* end-of-copy or error */
2075 if (msgLength == 0)
2076 return 0; /* no data yet */
2077
2078 /*
2079 * Move data from libpq's buffer to the caller's. In the case where a
2080 * prior call found the caller's buffer too small, we use
2081 * conn->copy_already_done to remember how much of the row was already
2082 * returned to the caller.
2083 */
2085 avail = msgLength - 4 - conn->copy_already_done;
2086 if (avail <= bufsize)
2087 {
2088 /* Able to consume the whole message */
2089 memcpy(buffer, &conn->inBuffer[conn->inCursor], avail);
2090 /* Mark message consumed */
2091 conn->inStart = conn->inCursor + avail;
2092 /* Reset state for next time */
2094 return avail;
2095 }
2096 else
2097 {
2098 /* We must return a partial message */
2099 memcpy(buffer, &conn->inBuffer[conn->inCursor], bufsize);
2100 /* The message is NOT consumed from libpq's buffer */
2102 return bufsize;
2103 }
2104}
2105
2106/*
2107 * PQendcopy
2108 *
2109 * See fe-exec.c for documentation.
2110 */
2111int
2113{
2114 PGresult *result;
2115
2119 {
2120 libpq_append_conn_error(conn, "no COPY in progress");
2121 return 1;
2122 }
2123
2124 /* Send the CopyDone message if needed */
2127 {
2128 if (pqPutMsgStart(PqMsg_CopyDone, conn) < 0 ||
2129 pqPutMsgEnd(conn) < 0)
2130 return 1;
2131
2132 /*
2133 * If we sent the COPY command in extended-query mode, we must issue a
2134 * Sync as well.
2135 */
2136 if (conn->cmd_queue_head &&
2138 {
2139 if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
2140 pqPutMsgEnd(conn) < 0)
2141 return 1;
2142 }
2143 }
2144
2145 /*
2146 * make sure no data is waiting to be sent, abort if we are non-blocking
2147 * and the flush fails
2148 */
2150 return 1;
2151
2152 /* Return to active duty */
2154
2155 /*
2156 * Non blocking connections may have to abort at this point. If everyone
2157 * played the game there should be no problem, but in error scenarios the
2158 * expected messages may not have arrived yet. (We are assuming that the
2159 * backend's packetizing will ensure that CommandComplete arrives along
2160 * with the CopyDone; are there corner cases where that doesn't happen?)
2161 */
2163 return 1;
2164
2165 /* Wait for the completion response */
2166 result = PQgetResult(conn);
2167
2168 /* Expecting a successful result */
2169 if (result && result->resultStatus == PGRES_COMMAND_OK)
2170 {
2171 PQclear(result);
2172 return 0;
2173 }
2174
2175 /*
2176 * Trouble. For backwards-compatibility reasons, we issue the error
2177 * message as if it were a notice (would be nice to get rid of this
2178 * silliness, but too many apps probably don't handle errors from
2179 * PQendcopy reasonably). Note that the app can still obtain the error
2180 * status from the PGconn object.
2181 */
2182 if (conn->errorMessage.len > 0)
2183 {
2184 /* We have to strip the trailing newline ... pain in neck... */
2186
2187 if (svLast == '\n')
2188 conn->errorMessage.data[conn->errorMessage.len - 1] = '\0';
2191 }
2192
2193 PQclear(result);
2194
2195 return 1;
2196}
2197
2198
2199/*
2200 * PQfn - Send a function call to the POSTGRES backend.
2201 *
2202 * See fe-exec.c for documentation.
2203 */
2204PGresult *
2206 int *result_buf, int *actual_result_len,
2207 int result_is_int,
2208 const PQArgBlock *args, int nargs)
2209{
2210 bool needInput = false;
2212 char id;
2213 int msgLength;
2214 int avail;
2215 int i;
2216
2217 /* already validated by PQfn */
2219
2220 /* PQfn already validated connection state */
2221
2223 pqPutInt(fnid, 4, conn) < 0 || /* function id */
2224 pqPutInt(1, 2, conn) < 0 || /* # of format codes */
2225 pqPutInt(1, 2, conn) < 0 || /* format code: BINARY */
2226 pqPutInt(nargs, 2, conn) < 0) /* # of args */
2227 {
2228 /* error message should be set up already */
2229 return NULL;
2230 }
2231
2232 for (i = 0; i < nargs; ++i)
2233 { /* len.int4 + contents */
2234 if (pqPutInt(args[i].len, 4, conn))
2235 return NULL;
2236 if (args[i].len == -1)
2237 continue; /* it's NULL */
2238
2239 if (args[i].isint)
2240 {
2241 if (pqPutInt(args[i].u.integer, args[i].len, conn))
2242 return NULL;
2243 }
2244 else
2245 {
2246 if (pqPutnchar(args[i].u.ptr, args[i].len, conn))
2247 return NULL;
2248 }
2249 }
2250
2251 if (pqPutInt(1, 2, conn) < 0) /* result format code: BINARY */
2252 return NULL;
2253
2254 if (pqPutMsgEnd(conn) < 0 ||
2255 pqFlush(conn))
2256 return NULL;
2257
2258 for (;;)
2259 {
2260 if (needInput)
2261 {
2262 /* Wait for some data to arrive (or for the channel to close) */
2263 if (pqWait(true, false, conn) ||
2264 pqReadData(conn) < 0)
2265 break;
2266 }
2267
2268 /*
2269 * Scan the message. If we run out of data, loop around to try again.
2270 */
2271 needInput = true;
2272
2274 if (pqGetc(&id, conn))
2275 continue;
2276 if (pqGetInt(&msgLength, 4, conn))
2277 continue;
2278
2279 /*
2280 * Try to validate message type/length here. A length less than 4 is
2281 * definitely broken. Large lengths should only be believed for a few
2282 * message types.
2283 */
2284 if (msgLength < 4)
2285 {
2287 break;
2288 }
2289 if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
2290 {
2292 break;
2293 }
2294
2295 /*
2296 * Can't process if message body isn't all here yet.
2297 */
2298 msgLength -= 4;
2299 avail = conn->inEnd - conn->inCursor;
2300 if (avail < msgLength)
2301 {
2302 /*
2303 * Before looping, enlarge the input buffer if needed to hold the
2304 * whole message. See notes in parseInput.
2305 */
2307 conn))
2308 {
2309 /*
2310 * Abandon the connection. There's not much else we can
2311 * safely do; we can't just ignore the message or we could
2312 * miss important changes to the connection state.
2313 * pqCheckInBufferSpace() already reported the error.
2314 */
2316 break;
2317 }
2318 continue;
2319 }
2320
2321 /*
2322 * We should see V or E response to the command, but might get N
2323 * and/or A notices first. We also need to swallow the final Z before
2324 * returning.
2325 */
2326 switch (id)
2327 {
2330 continue;
2331 if (*actual_result_len != -1)
2332 {
2333 if (result_is_int)
2334 {
2336 continue;
2337 }
2338 else
2339 {
2342 conn))
2343 continue;
2344 }
2345 }
2346 /* correctly finished function result message */
2347 status = PGRES_COMMAND_OK;
2348 break;
2350 if (pqGetErrorNotice3(conn, true))
2351 continue;
2352 status = PGRES_FATAL_ERROR;
2353 break;
2355 /* handle notify and go back to processing return values */
2356 if (getNotify(conn))
2357 continue;
2358 break;
2360 /* handle notice and go back to processing return values */
2361 if (pqGetErrorNotice3(conn, false))
2362 continue;
2363 break;
2366 continue;
2367
2368 /* consume the message */
2370
2371 /*
2372 * If we already have a result object (probably an error), use
2373 * that. Otherwise, if we saw a function result message,
2374 * report COMMAND_OK. Otherwise, the backend violated the
2375 * protocol, so complain.
2376 */
2378 {
2379 if (status == PGRES_COMMAND_OK)
2380 {
2381 conn->result = PQmakeEmptyPGresult(conn, status);
2382 if (!conn->result)
2383 {
2384 libpq_append_conn_error(conn, "out of memory");
2386 }
2387 }
2388 else
2389 {
2390 libpq_append_conn_error(conn, "protocol error: no function result");
2392 }
2393 }
2394 /* and we're out */
2395 return pqPrepareAsyncResult(conn);
2398 continue;
2399 break;
2400 default:
2401 /* The backend violates the protocol. */
2402 libpq_append_conn_error(conn, "protocol error: id=0x%x", id);
2404
2405 /*
2406 * We can't call parsing done due to the protocol violation
2407 * (so message tracing wouldn't work), but trust the specified
2408 * message length as what to skip.
2409 */
2410 conn->inStart += 5 + msgLength;
2411 return pqPrepareAsyncResult(conn);
2412 }
2413
2414 /* Completed parsing this message, keep going */
2416 needInput = false;
2417 }
2418
2419 /*
2420 * We fall out of the loop only upon failing to read data.
2421 * conn->errorMessage has been set by pqWait or pqReadData. We want to
2422 * append it to any already-received error message.
2423 */
2425 return pqPrepareAsyncResult(conn);
2426}
2427
2428
2429/*
2430 * Construct startup packet
2431 *
2432 * Returns a malloc'd packet buffer, or NULL if out of memory
2433 */
2434char *
2437{
2438 char *startpacket;
2439 size_t len;
2440
2442 if (len == 0 || len > INT_MAX)
2443 return NULL;
2444
2445 *packetlen = len;
2446 startpacket = (char *) malloc(*packetlen);
2447 if (!startpacket)
2448 return NULL;
2449
2451 Assert(*packetlen == len);
2452
2453 return startpacket;
2454}
2455
2456/*
2457 * Build a startup packet given a filled-in PGconn structure.
2458 *
2459 * We need to figure out how much space is needed, then fill it in.
2460 * To avoid duplicate logic, this routine is called twice: the first time
2461 * (with packet == NULL) just counts the space needed, the second time
2462 * (with packet == allocated space) fills it in. Return value is the number
2463 * of bytes used, or zero in the unlikely event of size_t overflow.
2464 */
2465static size_t
2468{
2469 size_t packet_len = 0;
2471 const char *val;
2472
2473 /* Protocol version comes first. */
2474 if (packet)
2475 {
2477
2479 }
2480 packet_len += sizeof(ProtocolVersion);
2481
2482 /* Add user name, database name, options */
2483
2484#define ADD_STARTUP_OPTION(optname, optval) \
2485 do { \
2486 if (packet) \
2487 strcpy(packet + packet_len, optname); \
2488 if (pg_add_size_overflow(packet_len, strlen(optname) + 1, &packet_len)) \
2489 return 0; \
2490 if (packet) \
2491 strcpy(packet + packet_len, optval); \
2492 if (pg_add_size_overflow(packet_len, strlen(optval) + 1, &packet_len)) \
2493 return 0; \
2494 } while(0)
2495
2496 if (conn->pguser && conn->pguser[0])
2497 ADD_STARTUP_OPTION("user", conn->pguser);
2498 if (conn->dbName && conn->dbName[0])
2499 ADD_STARTUP_OPTION("database", conn->dbName);
2500 if (conn->replication && conn->replication[0])
2501 ADD_STARTUP_OPTION("replication", conn->replication);
2502 if (conn->pgoptions && conn->pgoptions[0])
2503 ADD_STARTUP_OPTION("options", conn->pgoptions);
2504 if (conn->send_appname)
2505 {
2506 /* Use appname if present, otherwise use fallback */
2508 if (val && val[0])
2509 ADD_STARTUP_OPTION("application_name", val);
2510 }
2511
2513 ADD_STARTUP_OPTION("client_encoding", conn->client_encoding_initial);
2514
2515 /*
2516 * Add the test_protocol_negotiation option when greasing, to test that
2517 * servers properly report unsupported protocol options in addition to
2518 * unsupported minor versions.
2519 */
2521 ADD_STARTUP_OPTION("_pq_.test_protocol_negotiation", "");
2522
2523 /* Add any environment-driven GUC settings needed */
2524 for (next_eo = options; next_eo->envName; next_eo++)
2525 {
2526 if ((val = getenv(next_eo->envName)) != NULL)
2527 {
2528 if (pg_strcasecmp(val, "default") != 0)
2529 ADD_STARTUP_OPTION(next_eo->pgName, val);
2530 }
2531 }
2532
2533 /* Add trailing terminator */
2534 if (packet)
2535 packet[packet_len] = '\0';
2537 return 0;
2538
2539 return packet_len;
2540}
#define Assert(condition)
Definition c.h:906
int16_t int16
Definition c.h:574
#define MemSet(start, val, len)
Definition c.h:1056
int errmsg(const char *fmt,...)
Definition elog.c:1093
void pqDropConnection(PGconn *conn, bool flushInput)
Definition fe-connect.c:533
void * pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
Definition fe-exec.c:564
void pqSaveMessageField(PGresult *res, char code, const char *value)
Definition fe-exec.c:1066
PGresult * pqPrepareAsyncResult(PGconn *conn)
Definition fe-exec.c:857
void pqCommandQueueAdvance(PGconn *conn, bool isReadyForQuery, bool gotSync)
Definition fe-exec.c:3159
void pqSetResultError(PGresult *res, PQExpBuffer errorMessage, int offset)
Definition fe-exec.c:698
void pqSaveErrorResult(PGconn *conn)
Definition fe-exec.c:809
int pqRowProcessor(PGconn *conn, const char **errmsgp)
Definition fe-exec.c:1223
int PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
Definition fe-exec.c:2918
PGresult * PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
Definition fe-exec.c:160
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition fe-exec.c:944
void pqClearAsyncResult(PGconn *conn)
Definition fe-exec.c:785
int PQisBusy(PGconn *conn)
Definition fe-exec.c:2048
int pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
Definition fe-exec.c:1091
char * pqResultStrdup(PGresult *res, const char *str)
Definition fe-exec.c:681
int pqReadData(PGconn *conn)
Definition fe-misc.c:606
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition fe-misc.c:253
int pqFlush(PGconn *conn)
Definition fe-misc.c:994
void pqParseDone(PGconn *conn, int newInStart)
Definition fe-misc.c:443
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition fe-misc.c:473
int pqSkipnchar(size_t len, PGconn *conn)
Definition fe-misc.c:187
int pqGetc(char *result, PGconn *conn)
Definition fe-misc.c:77
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition fe-misc.c:216
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition fe-misc.c:1019
void libpq_append_grease_info(PGconn *conn)
Definition fe-misc.c:1432
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition fe-misc.c:136
int pqPutnchar(const void *s, size_t len, PGconn *conn)
Definition fe-misc.c:202
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition fe-misc.c:351
int pqGetnchar(void *s, size_t len, PGconn *conn)
Definition fe-misc.c:165
int PQmblenBounded(const char *s, int encoding)
Definition fe-misc.c:1266
int pqPutMsgEnd(PGconn *conn)
Definition fe-misc.c:532
#define DISPLAY_SIZE
void pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res, PGVerbosity verbosity, PGContextVisibility show_context)
char * pqBuildStartupPacket3(PGconn *conn, int *packetlen, const PQEnvironmentOption *options)
int pqEndcopy3(PGconn *conn)
static int getNotify(PGconn *conn)
static int getAnotherTuple(PGconn *conn, int msgLength)
static int getRowDescriptions(PGconn *conn, int msgLength)
static void reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding)
PGresult * pqFunctionCall3(PGconn *conn, Oid fnid, int *result_buf, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
#define MIN_RIGHT_CUT
int pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)
int pqGetCopyData3(PGconn *conn, char **buffer, int async)
int pqGetNegotiateProtocolVersion3(PGconn *conn)
static int getParameterStatus(PGconn *conn)
static size_t build_startup_packet(const PGconn *conn, char *packet, const PQEnvironmentOption *options)
static void handleFatalError(PGconn *conn)
#define VALID_LONG_MESSAGE_TYPE(id)
static int getCopyStart(PGconn *conn, ExecStatusType copytype)
static void handleSyncLoss(PGconn *conn, char id, int msgLength)
static int getReadyForQuery(PGconn *conn)
#define ADD_STARTUP_OPTION(optname, optval)
static int getBackendKeyData(PGconn *conn, int msgLength)
static int getCopyDataMessage(PGconn *conn)
static int getParamDescriptions(PGconn *conn, int msgLength)
int pqGetline3(PGconn *conn, char *s, int maxlen)
int pqGetErrorNotice3(PGconn *conn, bool isError)
#define bufsize
long val
Definition informix.c:689
static char * encoding
Definition initdb.c:139
int i
Definition isn.c:77
#define PQgetResult
#define PQclear
#define PQresultErrorField
@ CONNECTION_BAD
Definition libpq-fe.h:85
ExecStatusType
Definition libpq-fe.h:123
@ PGRES_COPY_IN
Definition libpq-fe.h:132
@ PGRES_COPY_BOTH
Definition libpq-fe.h:137
@ PGRES_COMMAND_OK
Definition libpq-fe.h:125
@ PGRES_TUPLES_CHUNK
Definition libpq-fe.h:142
@ PGRES_FATAL_ERROR
Definition libpq-fe.h:136
@ PGRES_COPY_OUT
Definition libpq-fe.h:131
@ PGRES_EMPTY_QUERY
Definition libpq-fe.h:124
@ PGRES_PIPELINE_SYNC
Definition libpq-fe.h:139
@ PGRES_NONFATAL_ERROR
Definition libpq-fe.h:135
@ PGRES_TUPLES_OK
Definition libpq-fe.h:128
PGContextVisibility
Definition libpq-fe.h:163
@ PQSHOW_CONTEXT_ALWAYS
Definition libpq-fe.h:166
@ PQSHOW_CONTEXT_ERRORS
Definition libpq-fe.h:165
@ PQTRANS_INTRANS
Definition libpq-fe.h:149
@ PQTRANS_IDLE
Definition libpq-fe.h:147
@ PQTRANS_UNKNOWN
Definition libpq-fe.h:151
@ PQTRANS_INERROR
Definition libpq-fe.h:150
@ PQ_PIPELINE_OFF
Definition libpq-fe.h:187
@ PQ_PIPELINE_ABORTED
Definition libpq-fe.h:189
@ PQ_PIPELINE_ON
Definition libpq-fe.h:188
PGVerbosity
Definition libpq-fe.h:155
@ PQERRORS_VERBOSE
Definition libpq-fe.h:158
@ PQERRORS_TERSE
Definition libpq-fe.h:156
@ PQERRORS_SQLSTATE
Definition libpq-fe.h:159
@ PGASYNC_COPY_OUT
Definition libpq-int.h:223
@ PGASYNC_READY
Definition libpq-int.h:217
@ PGASYNC_COPY_BOTH
Definition libpq-int.h:224
@ PGASYNC_IDLE
Definition libpq-int.h:215
@ PGASYNC_COPY_IN
Definition libpq-int.h:222
@ PGASYNC_BUSY
Definition libpq-int.h:216
@ PGQUERY_SIMPLE
Definition libpq-int.h:320
@ PGQUERY_DESCRIBE
Definition libpq-int.h:323
@ PGQUERY_CLOSE
Definition libpq-int.h:325
@ PGQUERY_PREPARE
Definition libpq-int.h:322
#define CMDSTATUS_LEN
Definition libpq-int.h:83
#define pqIsnonblocking(conn)
Definition libpq-int.h:939
#define pgHavePendingResult(conn)
Definition libpq-int.h:932
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition oauth-utils.c:95
#define libpq_gettext(x)
Definition oauth-utils.h:86
static char format
#define pg_hton32(x)
Definition pg_bswap.h:121
const void size_t len
int pg_strcasecmp(const char *s1, const char *s2)
#define PGINVALID_SOCKET
Definition port.h:31
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition strlcpy.c:45
#define PG_DIAG_INTERNAL_QUERY
#define PG_DIAG_SCHEMA_NAME
#define PG_DIAG_CONSTRAINT_NAME
#define PG_DIAG_DATATYPE_NAME
unsigned int Oid
#define PG_DIAG_SOURCE_LINE
#define PG_DIAG_STATEMENT_POSITION
#define PG_DIAG_SOURCE_FILE
#define PG_DIAG_MESSAGE_HINT
#define PG_DIAG_SQLSTATE
#define PG_DIAG_TABLE_NAME
#define PG_DIAG_MESSAGE_PRIMARY
#define PG_DIAG_COLUMN_NAME
#define PG_DIAG_MESSAGE_DETAIL
#define PG_DIAG_CONTEXT
#define PG_DIAG_SEVERITY
#define PG_DIAG_SOURCE_FUNCTION
#define PG_DIAG_INTERNAL_POSITION
#define PG_PROTOCOL_MAJOR(v)
Definition pqcomm.h:86
uint32 ProtocolVersion
Definition pqcomm.h:132
#define PG_PROTOCOL_GREASE
Definition pqcomm.h:115
#define PG_PROTOCOL_RESERVED_31
Definition pqcomm.h:105
#define PG_PROTOCOL(m, n)
Definition pqcomm.h:89
#define PG_PROTOCOL_MINOR(v)
Definition pqcomm.h:87
void initPQExpBuffer(PQExpBuffer str)
Definition pqexpbuffer.c:90
void resetPQExpBuffer(PQExpBuffer str)
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
void appendPQExpBufferChar(PQExpBuffer str, char ch)
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
void termPQExpBuffer(PQExpBuffer str)
#define PQExpBufferDataBroken(buf)
Definition pqexpbuffer.h:67
#define PqMsg_CloseComplete
Definition protocol.h:40
#define PqMsg_CopyDone
Definition protocol.h:64
#define PqMsg_BindComplete
Definition protocol.h:39
#define PqMsg_ParameterDescription
Definition protocol.h:58
#define PqMsg_FunctionCall
Definition protocol.h:23
#define PqMsg_ReadyForQuery
Definition protocol.h:55
#define PqMsg_CopyInResponse
Definition protocol.h:45
#define PqMsg_EmptyQueryResponse
Definition protocol.h:47
#define PqMsg_CopyBothResponse
Definition protocol.h:54
#define PqMsg_ParameterStatus
Definition protocol.h:51
#define PqMsg_NoData
Definition protocol.h:56
#define PqMsg_Sync
Definition protocol.h:27
#define PqMsg_BackendKeyData
Definition protocol.h:48
#define PqMsg_CommandComplete
Definition protocol.h:42
#define PqMsg_CopyOutResponse
Definition protocol.h:46
#define PqMsg_ParseComplete
Definition protocol.h:38
#define realloc(a, b)
#define free(a)
#define malloc(a)
PGconn * conn
Definition streamutil.c:52
PQnoticeReceiver noticeRec
Definition libpq-int.h:149
void * noticeRecArg
Definition libpq-int.h:150
PGQueryClass queryclass
Definition libpq-int.h:345
struct pgNotify * next
Definition libpq-fe.h:234
uint8 * be_cancel_key
Definition libpq-int.h:554
char * replication
Definition libpq-int.h:391
PGnotify * notifyHead
Definition libpq-int.h:476
PGdataValue * rowBuf
Definition libpq-int.h:593
pgsocket sock
Definition libpq-int.h:499
char * inBuffer
Definition libpq-int.h:576
ProtocolVersion pversion
Definition libpq-int.h:503
char * pgoptions
Definition libpq-int.h:387
bool send_appname
Definition libpq-int.h:543
PGTransactionStatusType xactStatus
Definition libpq-int.h:464
int inCursor
Definition libpq-int.h:579
int be_pid
Definition libpq-int.h:552
ProtocolVersion min_pversion
Definition libpq-int.h:548
char * dbName
Definition libpq-int.h:390
int inEnd
Definition libpq-int.h:580
char * fbappname
Definition libpq-int.h:389
PGnotify * notifyTail
Definition libpq-int.h:477
int copy_already_done
Definition libpq-int.h:475
PQExpBufferData workBuffer
Definition libpq-int.h:687
int inStart
Definition libpq-int.h:578
char * pguser
Definition libpq-int.h:395
PGresult * result
Definition libpq-int.h:606
PGVerbosity verbosity
Definition libpq-int.h:560
char * client_encoding_initial
Definition libpq-int.h:386
char * appname
Definition libpq-int.h:388
PQExpBufferData errorMessage
Definition libpq-int.h:683
bool error_result
Definition libpq-int.h:607
ProtocolVersion max_pversion
Definition libpq-int.h:549
int rowBufLen
Definition libpq-int.h:594
char last_sqlstate[6]
Definition libpq-int.h:465
PGAsyncStatusType asyncStatus
Definition libpq-int.h:463
PGpipelineStatus pipelineStatus
Definition libpq-int.h:469
char copy_is_binary
Definition libpq-int.h:474
PGNoticeHooks noticeHooks
Definition libpq-int.h:454
PGcmdQueueEntry * cmd_queue_head
Definition libpq-int.h:489
int be_cancel_key_len
Definition libpq-int.h:553
PGContextVisibility show_context
Definition libpq-int.h:561
ConnStatusType status
Definition libpq-int.h:462
PGNoticeHooks noticeHooks
Definition libpq-int.h:183
char * errMsg
Definition libpq-int.h:193
int numParameters
Definition libpq-int.h:172
PGresAttDesc * attDescs
Definition libpq-int.h:168
int numAttributes
Definition libpq-int.h:167
char cmdStatus[CMDSTATUS_LEN]
Definition libpq-int.h:175
PGMessageField * errFields
Definition libpq-int.h:194
PGresParamDesc * paramDescs
Definition libpq-int.h:173
ExecStatusType resultStatus
Definition libpq-int.h:174
char * errQuery
Definition libpq-int.h:195
int client_encoding
Definition libpq-int.h:186
char * name
Definition libpq-fe.h:307
int pg_encoding_dsplen(int encoding, const char *mbstr)
Definition wchar.c:2198
int pg_encoding_max_length(int encoding)
Definition wchar.c:2235

Function Documentation

◆ build_startup_packet()

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

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

2469{
2470 size_t packet_len = 0;
2472 const char *val;
2473
2474 /* Protocol version comes first. */
2475 if (packet)
2476 {
2478
2480 }
2481 packet_len += sizeof(ProtocolVersion);
2482
2483 /* Add user name, database name, options */
2484
2485#define ADD_STARTUP_OPTION(optname, optval) \
2486 do { \
2487 if (packet) \
2488 strcpy(packet + packet_len, optname); \
2489 if (pg_add_size_overflow(packet_len, strlen(optname) + 1, &packet_len)) \
2490 return 0; \
2491 if (packet) \
2492 strcpy(packet + packet_len, optval); \
2493 if (pg_add_size_overflow(packet_len, strlen(optval) + 1, &packet_len)) \
2494 return 0; \
2495 } while(0)
2496
2497 if (conn->pguser && conn->pguser[0])
2498 ADD_STARTUP_OPTION("user", conn->pguser);
2499 if (conn->dbName && conn->dbName[0])
2500 ADD_STARTUP_OPTION("database", conn->dbName);
2501 if (conn->replication && conn->replication[0])
2502 ADD_STARTUP_OPTION("replication", conn->replication);
2503 if (conn->pgoptions && conn->pgoptions[0])
2504 ADD_STARTUP_OPTION("options", conn->pgoptions);
2505 if (conn->send_appname)
2506 {
2507 /* Use appname if present, otherwise use fallback */
2509 if (val && val[0])
2510 ADD_STARTUP_OPTION("application_name", val);
2511 }
2512
2514 ADD_STARTUP_OPTION("client_encoding", conn->client_encoding_initial);
2515
2516 /*
2517 * Add the test_protocol_negotiation option when greasing, to test that
2518 * servers properly report unsupported protocol options in addition to
2519 * unsupported minor versions.
2520 */
2522 ADD_STARTUP_OPTION("_pq_.test_protocol_negotiation", "");
2523
2524 /* Add any environment-driven GUC settings needed */
2525 for (next_eo = options; next_eo->envName; next_eo++)
2526 {
2527 if ((val = getenv(next_eo->envName)) != NULL)
2528 {
2529 if (pg_strcasecmp(val, "default") != 0)
2530 ADD_STARTUP_OPTION(next_eo->pgName, val);
2531 }
2532 }
2533
2534 /* Add trailing terminator */
2535 if (packet)
2536 packet[packet_len] = '\0';
2538 return 0;
2539
2540 return packet_len;
2541}

References ADD_STARTUP_OPTION, pg_conn::appname, pg_conn::client_encoding_initial, conn, pg_conn::dbName, fb(), pg_conn::fbappname, pg_add_size_overflow(), pg_hton32, PG_PROTOCOL_GREASE, pg_strcasecmp(), 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 777 of file fe-protocol3.c.

778{
779 PGresult *result = conn->result;
780 int nfields = result->numAttributes;
781 const char *errmsg;
783 int tupnfields; /* # fields from tuple */
784 int vlen; /* length of the current field value */
785 int i;
786
787 /* Get the field count and make sure it's what we expect */
788 if (pqGetInt(&tupnfields, 2, conn))
789 {
790 /* We should not run out of data here, so complain */
791 errmsg = libpq_gettext("insufficient data in \"D\" message");
793 }
794
795 if (tupnfields != nfields)
796 {
797 errmsg = libpq_gettext("unexpected field count in \"D\" message");
799 }
800
801 /* Resize row buffer if needed */
802 rowbuf = conn->rowBuf;
803 if (nfields > conn->rowBufLen)
804 {
806 nfields * sizeof(PGdataValue));
807 if (!rowbuf)
808 {
809 errmsg = NULL; /* means "out of memory", see below */
811 }
812 conn->rowBuf = rowbuf;
813 conn->rowBufLen = nfields;
814 }
815
816 /* Scan the fields */
817 for (i = 0; i < nfields; i++)
818 {
819 /* get the value length */
820 if (pqGetInt(&vlen, 4, conn))
821 {
822 /* We should not run out of data here, so complain */
823 errmsg = libpq_gettext("insufficient data in \"D\" message");
825 }
826 rowbuf[i].len = vlen;
827
828 /*
829 * rowbuf[i].value always points to the next address in the data
830 * buffer even if the value is NULL. This allows row processors to
831 * estimate data sizes more easily.
832 */
833 rowbuf[i].value = conn->inBuffer + conn->inCursor;
834
835 /* Skip over the data value */
836 if (vlen > 0)
837 {
838 if (pqSkipnchar(vlen, conn))
839 {
840 /* We should not run out of data here, so complain */
841 errmsg = libpq_gettext("insufficient data in \"D\" message");
843 }
844 }
845 }
846
847 /* Process the collected row */
848 errmsg = NULL;
850 return 0; /* normal, successful exit */
851
852 /* pqRowProcessor failed, fall through to report it */
853
855
856 /*
857 * Replace partially constructed result with an error result. First
858 * discard the old result to try to win back some memory.
859 */
861
862 /*
863 * If preceding code didn't provide an error message, assume "out of
864 * memory" was meant. The advantage of having this special case is that
865 * freeing the old result first greatly improves the odds that gettext()
866 * will succeed in providing a translation.
867 */
868 if (!errmsg)
869 errmsg = libpq_gettext("out of memory for query result");
870
873
874 /*
875 * Show the message as fully consumed, else pqParseInput3 will overwrite
876 * our error with a complaint about that.
877 */
879
880 /*
881 * Return zero to allow input parsing to continue. Subsequent "D"
882 * messages will be ignored until we get to end of data, since an error
883 * result is already set up.
884 */
885 return 0;
886}

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

Referenced by pqParseInput3().

◆ getBackendKeyData()

static int getBackendKeyData ( PGconn conn,
int  msgLength 
)
static

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

1621{
1622 int cancel_key_len;
1623
1624 if (conn->be_cancel_key)
1625 {
1629 }
1630
1631 if (pqGetInt(&(conn->be_pid), 4, conn))
1632 return EOF;
1633
1635
1636 if (cancel_key_len != 4 && conn->pversion == PG_PROTOCOL(3, 0))
1637 {
1638 libpq_append_conn_error(conn, "received invalid BackendKeyData message: cancel key with length %d not allowed in protocol version 3.0 (must be 4 bytes)", cancel_key_len);
1640 return 0;
1641 }
1642
1643 if (cancel_key_len < 4)
1644 {
1645 libpq_append_conn_error(conn, "received invalid BackendKeyData message: cancel key with length %d is too short (minimum 4 bytes)", cancel_key_len);
1647 return 0;
1648 }
1649
1650 if (cancel_key_len > 256)
1651 {
1652 libpq_append_conn_error(conn, "received invalid BackendKeyData message: cancel key with length %d is too long (maximum 256 bytes)", cancel_key_len);
1654 return 0;
1655 }
1656
1658 if (conn->be_cancel_key == NULL)
1659 {
1660 libpq_append_conn_error(conn, "out of memory");
1662 return 0;
1663 }
1665 {
1668 return EOF;
1669 }
1671 return 0;
1672}

References pg_conn::be_cancel_key, pg_conn::be_cancel_key_len, pg_conn::be_pid, conn, fb(), free, handleFatalError(), pg_conn::inCursor, pg_conn::inStart, libpq_append_conn_error(), malloc, PG_PROTOCOL, pqGetInt(), pqGetnchar(), and pg_conn::pversion.

Referenced by pqParseInput3().

◆ getCopyDataMessage()

static int getCopyDataMessage ( PGconn conn)
static

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

1844{
1845 char id;
1846 int msgLength;
1847 int avail;
1848
1849 for (;;)
1850 {
1851 /*
1852 * Do we have the next input message? To make life simpler for async
1853 * callers, we keep returning 0 until the next message is fully
1854 * available, even if it is not Copy Data.
1855 */
1857 if (pqGetc(&id, conn))
1858 return 0;
1859 if (pqGetInt(&msgLength, 4, conn))
1860 return 0;
1861 if (msgLength < 4)
1862 {
1864 return -2;
1865 }
1866 avail = conn->inEnd - conn->inCursor;
1867 if (avail < msgLength - 4)
1868 {
1869 /*
1870 * Before returning, enlarge the input buffer if needed to hold
1871 * the whole message. See notes in parseInput.
1872 */
1873 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength - 4,
1874 conn))
1875 {
1876 /*
1877 * Abandon the connection. There's not much else we can
1878 * safely do; we can't just ignore the message or we could
1879 * miss important changes to the connection state.
1880 * pqCheckInBufferSpace() already reported the error.
1881 */
1883 return -2;
1884 }
1885 return 0;
1886 }
1887
1888 /*
1889 * If it's a legitimate async message type, process it. (NOTIFY
1890 * messages are not currently possible here, but we handle them for
1891 * completeness.) Otherwise, if it's anything except Copy Data,
1892 * report end-of-copy.
1893 */
1894 switch (id)
1895 {
1897 if (getNotify(conn))
1898 return 0;
1899 break;
1901 if (pqGetErrorNotice3(conn, false))
1902 return 0;
1903 break;
1906 return 0;
1907 break;
1908 case PqMsg_CopyData:
1909 return msgLength;
1910 case PqMsg_CopyDone:
1911
1912 /*
1913 * If this is a CopyDone message, exit COPY_OUT mode and let
1914 * caller read status with PQgetResult(). If we're in
1915 * COPY_BOTH mode, return to COPY_IN mode.
1916 */
1919 else
1921 return -1;
1922 default: /* treat as end of copy */
1923
1924 /*
1925 * Any other message terminates either COPY_IN or COPY_BOTH
1926 * mode.
1927 */
1929 return -1;
1930 }
1931
1932 /* Drop the processed message and loop around for another */
1934 }
1935}

References pg_conn::asyncStatus, conn, fb(), getNotify(), getParameterStatus(), handleFatalError(), handleSyncLoss(), pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, pqCheckInBufferSpace(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), PqMsg_CopyData, PqMsg_CopyDone, PqMsg_NoticeResponse, PqMsg_NotificationResponse, PqMsg_ParameterStatus, and pqParseDone().

Referenced by pqGetCopyData3(), and pqGetlineAsync3().

◆ getCopyStart()

static int getCopyStart ( PGconn conn,
ExecStatusType  copytype 
)
static

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

1756{
1757 PGresult *result;
1758 int nfields;
1759 int i;
1760
1762 if (!result)
1763 goto failure;
1764
1766 goto failure;
1767 result->binary = conn->copy_is_binary;
1768 /* the next two bytes are the number of fields */
1769 if (pqGetInt(&(result->numAttributes), 2, conn))
1770 goto failure;
1771 nfields = result->numAttributes;
1772
1773 /* allocate space for the attribute descriptors */
1774 if (nfields > 0)
1775 {
1776 result->attDescs = (PGresAttDesc *)
1777 pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
1778 if (!result->attDescs)
1779 goto failure;
1780 MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
1781 }
1782
1783 for (i = 0; i < nfields; i++)
1784 {
1785 int format;
1786
1787 if (pqGetInt(&format, 2, conn))
1788 goto failure;
1789
1790 /*
1791 * Since pqGetInt treats 2-byte integers as unsigned, we need to
1792 * coerce these results to signed form.
1793 */
1794 format = (int) ((int16) format);
1795 result->attDescs[i].format = format;
1796 }
1797
1798 /* Success! */
1799 conn->result = result;
1800 return 0;
1801
1802failure:
1803 PQclear(result);
1804 return EOF;
1805}

References pg_result::attDescs, pg_result::binary, conn, pg_conn::copy_is_binary, fb(), 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 1684 of file fe-protocol3.c.

1685{
1686 int be_pid;
1687 char *svname;
1688 int nmlen;
1689 int extralen;
1691
1692 if (pqGetInt(&be_pid, 4, conn))
1693 return EOF;
1694 if (pqGets(&conn->workBuffer, conn))
1695 return EOF;
1696 /* must save name while getting extra string */
1698 if (!svname)
1699 {
1700 /*
1701 * Notify messages can arrive at any state, so we cannot associate the
1702 * error with any particular query. There's no way to return back an
1703 * "async error", so the best we can do is drop the connection. That
1704 * seems better than silently ignoring the notification.
1705 */
1706 libpq_append_conn_error(conn, "out of memory");
1708 return 0;
1709 }
1710 if (pqGets(&conn->workBuffer, conn))
1711 {
1712 free(svname);
1713 return EOF;
1714 }
1715
1716 /*
1717 * Store the strings right after the PGnotify structure so it can all be
1718 * freed at once. We don't use NAMEDATALEN because we don't want to tie
1719 * this interface to a specific server name length.
1720 */
1721 nmlen = strlen(svname);
1723 newNotify = (PGnotify *) malloc(sizeof(PGnotify) + nmlen + extralen + 2);
1724 if (!newNotify)
1725 {
1726 free(svname);
1727 libpq_append_conn_error(conn, "out of memory");
1729 return 0;
1730 }
1731
1732 newNotify->relname = (char *) newNotify + sizeof(PGnotify);
1733 strcpy(newNotify->relname, svname);
1734 newNotify->extra = newNotify->relname + nmlen + 1;
1736 newNotify->be_pid = be_pid;
1737 newNotify->next = NULL;
1738 if (conn->notifyTail)
1740 else
1743
1744 free(svname);
1745 return 0;
1746}

References conn, PQExpBufferData::data, fb(), free, handleFatalError(), libpq_append_conn_error(), malloc, pgNotify::next, pg_conn::notifyHead, pg_conn::notifyTail, pqGetInt(), pqGets(), and pg_conn::workBuffer.

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

◆ getParamDescriptions()

static int getParamDescriptions ( PGconn conn,
int  msgLength 
)
static

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

690{
691 PGresult *result;
692 const char *errmsg = NULL; /* means "out of memory", see below */
693 int nparams;
694 int i;
695
697 if (!result)
699
700 /* parseInput already read the 't' label and message length. */
701 /* the next two bytes are the number of parameters */
702 if (pqGetInt(&(result->numParameters), 2, conn))
703 goto not_enough_data;
704 nparams = result->numParameters;
705
706 /* allocate space for the parameter descriptors */
707 if (nparams > 0)
708 {
709 result->paramDescs = (PGresParamDesc *)
710 pqResultAlloc(result, nparams * sizeof(PGresParamDesc), true);
711 if (!result->paramDescs)
713 MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
714 }
715
716 /* get parameter info */
717 for (i = 0; i < nparams; i++)
718 {
719 int typid;
720
721 if (pqGetInt(&typid, 4, conn))
722 goto not_enough_data;
723 result->paramDescs[i].typid = typid;
724 }
725
726 /* Success! */
727 conn->result = result;
728
729 return 0;
730
732 errmsg = libpq_gettext("insufficient data in \"t\" message");
733
735 /* Discard unsaved result, if any */
736 if (result && result != conn->result)
737 PQclear(result);
738
739 /*
740 * Replace partially constructed result with an error result. First
741 * discard the old result to try to win back some memory.
742 */
744
745 /*
746 * If preceding code didn't provide an error message, assume "out of
747 * memory" was meant. The advantage of having this special case is that
748 * freeing the old result first greatly improves the odds that gettext()
749 * will succeed in providing a translation.
750 */
751 if (!errmsg)
752 errmsg = libpq_gettext("out of memory");
755
756 /*
757 * Show the message as fully consumed, else pqParseInput3 will overwrite
758 * our error with a complaint about that.
759 */
761
762 /*
763 * Return zero to allow input parsing to continue. Essentially, we've
764 * replaced the COMMAND_OK result with an error result, but since this
765 * doesn't affect the protocol state, it's fine.
766 */
767 return 0;
768}

References appendPQExpBuffer(), conn, errmsg(), pg_conn::errorMessage, fb(), 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 1589 of file fe-protocol3.c.

1590{
1592
1593 /* Get the parameter name */
1594 if (pqGets(&conn->workBuffer, conn))
1595 return EOF;
1596 /* Get the parameter value (could be large) */
1598 if (pqGets(&valueBuf, conn))
1599 {
1601 return EOF;
1602 }
1603 /* And save it */
1605 {
1606 libpq_append_conn_error(conn, "out of memory");
1608 }
1610 return 0;
1611}

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

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

◆ getReadyForQuery()

static int getReadyForQuery ( PGconn conn)
static

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

1812{
1813 char xact_status;
1814
1815 if (pqGetc(&xact_status, conn))
1816 return EOF;
1817 switch (xact_status)
1818 {
1819 case 'I':
1821 break;
1822 case 'T':
1824 break;
1825 case 'E':
1827 break;
1828 default:
1830 break;
1831 }
1832
1833 return 0;
1834}

References conn, fb(), 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 518 of file fe-protocol3.c.

519{
520 PGresult *result;
521 int nfields;
522 const char *errmsg;
523 int i;
524
525 /*
526 * When doing Describe for a prepared statement, there'll already be a
527 * PGresult created by getParamDescriptions, and we should fill data into
528 * that. Otherwise, create a new, empty PGresult.
529 */
530 if (!conn->cmd_queue_head ||
533 {
534 if (conn->result)
535 result = conn->result;
536 else
538 }
539 else
541 if (!result)
542 {
543 errmsg = NULL; /* means "out of memory", see below */
545 }
546
547 /* parseInput already read the 'T' label and message length. */
548 /* the next two bytes are the number of fields */
549 if (pqGetInt(&(result->numAttributes), 2, conn))
550 {
551 /* We should not run out of data here, so complain */
552 errmsg = libpq_gettext("insufficient data in \"T\" message");
554 }
555 nfields = result->numAttributes;
556
557 /* allocate space for the attribute descriptors */
558 if (nfields > 0)
559 {
560 result->attDescs = (PGresAttDesc *)
561 pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
562 if (!result->attDescs)
563 {
564 errmsg = NULL; /* means "out of memory", see below */
566 }
567 MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
568 }
569
570 /* result->binary is true only if ALL columns are binary */
571 result->binary = (nfields > 0) ? 1 : 0;
572
573 /* get type info */
574 for (i = 0; i < nfields; i++)
575 {
576 int tableid;
577 int columnid;
578 int typid;
579 int typlen;
580 int atttypmod;
581 int format;
582
583 if (pqGets(&conn->workBuffer, conn) ||
584 pqGetInt(&tableid, 4, conn) ||
585 pqGetInt(&columnid, 2, conn) ||
586 pqGetInt(&typid, 4, conn) ||
587 pqGetInt(&typlen, 2, conn) ||
588 pqGetInt(&atttypmod, 4, conn) ||
589 pqGetInt(&format, 2, conn))
590 {
591 /* We should not run out of data here, so complain */
592 errmsg = libpq_gettext("insufficient data in \"T\" message");
594 }
595
596 /*
597 * Since pqGetInt treats 2-byte integers as unsigned, we need to
598 * coerce these results to signed form.
599 */
600 columnid = (int) ((int16) columnid);
601 typlen = (int) ((int16) typlen);
602 format = (int) ((int16) format);
603
604 result->attDescs[i].name = pqResultStrdup(result,
606 if (!result->attDescs[i].name)
607 {
608 errmsg = NULL; /* means "out of memory", see below */
610 }
611 result->attDescs[i].tableid = tableid;
612 result->attDescs[i].columnid = columnid;
613 result->attDescs[i].format = format;
614 result->attDescs[i].typid = typid;
615 result->attDescs[i].typlen = typlen;
616 result->attDescs[i].atttypmod = atttypmod;
617
618 if (format != 1)
619 result->binary = 0;
620 }
621
622 /* Success! */
623 conn->result = result;
624
625 /*
626 * If we're doing a Describe, we're done, and ready to pass the result
627 * back to the client.
628 */
629 if ((!conn->cmd_queue_head) ||
632 {
634 return 0;
635 }
636
637 /*
638 * We could perform additional setup for the new result set here, but for
639 * now there's nothing else to do.
640 */
641
642 /* And we're done. */
643 return 0;
644
646 /* Discard unsaved result, if any */
647 if (result && result != conn->result)
648 PQclear(result);
649
650 /*
651 * Replace partially constructed result with an error result. First
652 * discard the old result to try to win back some memory.
653 */
655
656 /*
657 * If preceding code didn't provide an error message, assume "out of
658 * memory" was meant. The advantage of having this special case is that
659 * freeing the old result first greatly improves the odds that gettext()
660 * will succeed in providing a translation.
661 */
662 if (!errmsg)
663 errmsg = libpq_gettext("out of memory for query result");
664
667
668 /*
669 * Show the message as fully consumed, else pqParseInput3 will overwrite
670 * our error with a complaint about that.
671 */
673
674 /*
675 * Return zero to allow input parsing to continue. Subsequent "D"
676 * messages will be ignored until we get to end of data, since an error
677 * result is already set up.
678 */
679 return 0;
680}

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, fb(), 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().

◆ handleFatalError()

static void handleFatalError ( PGconn conn)
static

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

488{
489 /* build an error result holding the error message */
491 conn->asyncStatus = PGASYNC_READY; /* drop out of PQgetResult wait loop */
492 /* flush input data since we're giving up on processing it */
493 pqDropConnection(conn, true);
494 conn->status = CONNECTION_BAD; /* No more connection to backend */
495}

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

Referenced by getBackendKeyData(), getCopyDataMessage(), getNotify(), getParameterStatus(), handleSyncLoss(), pqFunctionCall3(), and pqParseInput3().

◆ handleSyncLoss()

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

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

504{
505 libpq_append_conn_error(conn, "lost synchronization with server: got message type \"%c\", length %d",
506 id, msgLength);
508}

References conn, fb(), handleFatalError(), and libpq_append_conn_error().

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

◆ pqBuildErrorMessage3()

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

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

1032{
1033 const char *val;
1034 const char *querytext = NULL;
1035 int querypos = 0;
1036
1037 /* If we couldn't allocate a PGresult, just say "out of memory" */
1038 if (res == NULL)
1039 {
1040 appendPQExpBufferStr(msg, libpq_gettext("out of memory\n"));
1041 return;
1042 }
1043
1044 /*
1045 * If we don't have any broken-down fields, just return the base message.
1046 * This mainly applies if we're given a libpq-generated error result.
1047 */
1048 if (res->errFields == NULL)
1049 {
1050 if (res->errMsg && res->errMsg[0])
1051 appendPQExpBufferStr(msg, res->errMsg);
1052 else
1053 appendPQExpBufferStr(msg, libpq_gettext("no error message available\n"));
1054 return;
1055 }
1056
1057 /* Else build error message from relevant fields */
1059 if (val)
1060 appendPQExpBuffer(msg, "%s: ", val);
1061
1062 if (verbosity == PQERRORS_SQLSTATE)
1063 {
1064 /*
1065 * If we have a SQLSTATE, print that and nothing else. If not (which
1066 * shouldn't happen for server-generated errors, but might possibly
1067 * happen for libpq-generated ones), fall back to TERSE format, as
1068 * that seems better than printing nothing at all.
1069 */
1071 if (val)
1072 {
1073 appendPQExpBuffer(msg, "%s\n", val);
1074 return;
1075 }
1076 verbosity = PQERRORS_TERSE;
1077 }
1078
1079 if (verbosity == PQERRORS_VERBOSE)
1080 {
1082 if (val)
1083 appendPQExpBuffer(msg, "%s: ", val);
1084 }
1086 if (val)
1089 if (val)
1090 {
1091 if (verbosity != PQERRORS_TERSE && res->errQuery != NULL)
1092 {
1093 /* emit position as a syntax cursor display */
1094 querytext = res->errQuery;
1095 querypos = atoi(val);
1096 }
1097 else
1098 {
1099 /* emit position as text addition to primary message */
1100 /* translator: %s represents a digit string */
1101 appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1102 val);
1103 }
1104 }
1105 else
1106 {
1108 if (val)
1109 {
1111 if (verbosity != PQERRORS_TERSE && querytext != NULL)
1112 {
1113 /* emit position as a syntax cursor display */
1114 querypos = atoi(val);
1115 }
1116 else
1117 {
1118 /* emit position as text addition to primary message */
1119 /* translator: %s represents a digit string */
1120 appendPQExpBuffer(msg, libpq_gettext(" at character %s"),
1121 val);
1122 }
1123 }
1124 }
1125 appendPQExpBufferChar(msg, '\n');
1126 if (verbosity != PQERRORS_TERSE)
1127 {
1128 if (querytext && querypos > 0)
1130 res->client_encoding);
1132 if (val)
1133 appendPQExpBuffer(msg, libpq_gettext("DETAIL: %s\n"), val);
1135 if (val)
1136 appendPQExpBuffer(msg, libpq_gettext("HINT: %s\n"), val);
1138 if (val)
1139 appendPQExpBuffer(msg, libpq_gettext("QUERY: %s\n"), val);
1140 if (show_context == PQSHOW_CONTEXT_ALWAYS ||
1141 (show_context == PQSHOW_CONTEXT_ERRORS &&
1143 {
1145 if (val)
1146 appendPQExpBuffer(msg, libpq_gettext("CONTEXT: %s\n"),
1147 val);
1148 }
1149 }
1150 if (verbosity == PQERRORS_VERBOSE)
1151 {
1153 if (val)
1155 libpq_gettext("SCHEMA NAME: %s\n"), val);
1157 if (val)
1159 libpq_gettext("TABLE NAME: %s\n"), val);
1161 if (val)
1163 libpq_gettext("COLUMN NAME: %s\n"), val);
1165 if (val)
1167 libpq_gettext("DATATYPE NAME: %s\n"), val);
1169 if (val)
1171 libpq_gettext("CONSTRAINT NAME: %s\n"), val);
1172 }
1173 if (verbosity == PQERRORS_VERBOSE)
1174 {
1175 const char *valf;
1176 const char *vall;
1177
1181 if (val || valf || vall)
1182 {
1183 appendPQExpBufferStr(msg, libpq_gettext("LOCATION: "));
1184 if (val)
1185 appendPQExpBuffer(msg, libpq_gettext("%s, "), val);
1186 if (valf && vall) /* unlikely we'd have just one */
1187 appendPQExpBuffer(msg, libpq_gettext("%s:%s"),
1188 valf, vall);
1189 appendPQExpBufferChar(msg, '\n');
1190 }
1191 }
1192}

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), pg_result::client_encoding, pg_result::errFields, pg_result::errMsg, pg_result::errQuery, fb(), 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(), pg_result::resultStatus, and val.

Referenced by pqGetErrorNotice3(), and PQresultVerboseErrorMessage().

◆ pqBuildStartupPacket3()

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

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

2438{
2439 char *startpacket;
2440 size_t len;
2441
2443 if (len == 0 || len > INT_MAX)
2444 return NULL;
2445
2446 *packetlen = len;
2447 startpacket = (char *) malloc(*packetlen);
2448 if (!startpacket)
2449 return NULL;
2450
2452 Assert(*packetlen == len);
2453
2454 return startpacket;
2455}

References Assert, build_startup_packet(), conn, fb(), len, and malloc.

Referenced by PQconnectPoll().

◆ pqEndcopy3()

int pqEndcopy3 ( PGconn conn)

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

2114{
2115 PGresult *result;
2116
2120 {
2121 libpq_append_conn_error(conn, "no COPY in progress");
2122 return 1;
2123 }
2124
2125 /* Send the CopyDone message if needed */
2128 {
2129 if (pqPutMsgStart(PqMsg_CopyDone, conn) < 0 ||
2130 pqPutMsgEnd(conn) < 0)
2131 return 1;
2132
2133 /*
2134 * If we sent the COPY command in extended-query mode, we must issue a
2135 * Sync as well.
2136 */
2137 if (conn->cmd_queue_head &&
2139 {
2140 if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
2141 pqPutMsgEnd(conn) < 0)
2142 return 1;
2143 }
2144 }
2145
2146 /*
2147 * make sure no data is waiting to be sent, abort if we are non-blocking
2148 * and the flush fails
2149 */
2151 return 1;
2152
2153 /* Return to active duty */
2155
2156 /*
2157 * Non blocking connections may have to abort at this point. If everyone
2158 * played the game there should be no problem, but in error scenarios the
2159 * expected messages may not have arrived yet. (We are assuming that the
2160 * backend's packetizing will ensure that CommandComplete arrives along
2161 * with the CopyDone; are there corner cases where that doesn't happen?)
2162 */
2164 return 1;
2165
2166 /* Wait for the completion response */
2167 result = PQgetResult(conn);
2168
2169 /* Expecting a successful result */
2170 if (result && result->resultStatus == PGRES_COMMAND_OK)
2171 {
2172 PQclear(result);
2173 return 0;
2174 }
2175
2176 /*
2177 * Trouble. For backwards-compatibility reasons, we issue the error
2178 * message as if it were a notice (would be nice to get rid of this
2179 * silliness, but too many apps probably don't handle errors from
2180 * PQendcopy reasonably). Note that the app can still obtain the error
2181 * status from the PGconn object.
2182 */
2183 if (conn->errorMessage.len > 0)
2184 {
2185 /* We have to strip the trailing newline ... pain in neck... */
2187
2188 if (svLast == '\n')
2189 conn->errorMessage.data[conn->errorMessage.len - 1] = '\0';
2192 }
2193
2194 PQclear(result);
2195
2196 return 1;
2197}

References pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, PQExpBufferData::data, pg_conn::errorMessage, fb(), 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, PqMsg_CopyDone, PqMsg_Sync, 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 2206 of file fe-protocol3.c.

2210{
2211 bool needInput = false;
2213 char id;
2214 int msgLength;
2215 int avail;
2216 int i;
2217
2218 /* already validated by PQfn */
2220
2221 /* PQfn already validated connection state */
2222
2224 pqPutInt(fnid, 4, conn) < 0 || /* function id */
2225 pqPutInt(1, 2, conn) < 0 || /* # of format codes */
2226 pqPutInt(1, 2, conn) < 0 || /* format code: BINARY */
2227 pqPutInt(nargs, 2, conn) < 0) /* # of args */
2228 {
2229 /* error message should be set up already */
2230 return NULL;
2231 }
2232
2233 for (i = 0; i < nargs; ++i)
2234 { /* len.int4 + contents */
2235 if (pqPutInt(args[i].len, 4, conn))
2236 return NULL;
2237 if (args[i].len == -1)
2238 continue; /* it's NULL */
2239
2240 if (args[i].isint)
2241 {
2242 if (pqPutInt(args[i].u.integer, args[i].len, conn))
2243 return NULL;
2244 }
2245 else
2246 {
2247 if (pqPutnchar(args[i].u.ptr, args[i].len, conn))
2248 return NULL;
2249 }
2250 }
2251
2252 if (pqPutInt(1, 2, conn) < 0) /* result format code: BINARY */
2253 return NULL;
2254
2255 if (pqPutMsgEnd(conn) < 0 ||
2256 pqFlush(conn))
2257 return NULL;
2258
2259 for (;;)
2260 {
2261 if (needInput)
2262 {
2263 /* Wait for some data to arrive (or for the channel to close) */
2264 if (pqWait(true, false, conn) ||
2265 pqReadData(conn) < 0)
2266 break;
2267 }
2268
2269 /*
2270 * Scan the message. If we run out of data, loop around to try again.
2271 */
2272 needInput = true;
2273
2275 if (pqGetc(&id, conn))
2276 continue;
2277 if (pqGetInt(&msgLength, 4, conn))
2278 continue;
2279
2280 /*
2281 * Try to validate message type/length here. A length less than 4 is
2282 * definitely broken. Large lengths should only be believed for a few
2283 * message types.
2284 */
2285 if (msgLength < 4)
2286 {
2288 break;
2289 }
2290 if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
2291 {
2293 break;
2294 }
2295
2296 /*
2297 * Can't process if message body isn't all here yet.
2298 */
2299 msgLength -= 4;
2300 avail = conn->inEnd - conn->inCursor;
2301 if (avail < msgLength)
2302 {
2303 /*
2304 * Before looping, enlarge the input buffer if needed to hold the
2305 * whole message. See notes in parseInput.
2306 */
2308 conn))
2309 {
2310 /*
2311 * Abandon the connection. There's not much else we can
2312 * safely do; we can't just ignore the message or we could
2313 * miss important changes to the connection state.
2314 * pqCheckInBufferSpace() already reported the error.
2315 */
2317 break;
2318 }
2319 continue;
2320 }
2321
2322 /*
2323 * We should see V or E response to the command, but might get N
2324 * and/or A notices first. We also need to swallow the final Z before
2325 * returning.
2326 */
2327 switch (id)
2328 {
2331 continue;
2332 if (*actual_result_len != -1)
2333 {
2334 if (result_is_int)
2335 {
2337 continue;
2338 }
2339 else
2340 {
2343 conn))
2344 continue;
2345 }
2346 }
2347 /* correctly finished function result message */
2348 status = PGRES_COMMAND_OK;
2349 break;
2351 if (pqGetErrorNotice3(conn, true))
2352 continue;
2353 status = PGRES_FATAL_ERROR;
2354 break;
2356 /* handle notify and go back to processing return values */
2357 if (getNotify(conn))
2358 continue;
2359 break;
2361 /* handle notice and go back to processing return values */
2362 if (pqGetErrorNotice3(conn, false))
2363 continue;
2364 break;
2367 continue;
2368
2369 /* consume the message */
2371
2372 /*
2373 * If we already have a result object (probably an error), use
2374 * that. Otherwise, if we saw a function result message,
2375 * report COMMAND_OK. Otherwise, the backend violated the
2376 * protocol, so complain.
2377 */
2379 {
2380 if (status == PGRES_COMMAND_OK)
2381 {
2382 conn->result = PQmakeEmptyPGresult(conn, status);
2383 if (!conn->result)
2384 {
2385 libpq_append_conn_error(conn, "out of memory");
2387 }
2388 }
2389 else
2390 {
2391 libpq_append_conn_error(conn, "protocol error: no function result");
2393 }
2394 }
2395 /* and we're out */
2396 return pqPrepareAsyncResult(conn);
2399 continue;
2400 break;
2401 default:
2402 /* The backend violates the protocol. */
2403 libpq_append_conn_error(conn, "protocol error: id=0x%x", id);
2405
2406 /*
2407 * We can't call parsing done due to the protocol violation
2408 * (so message tracing wouldn't work), but trust the specified
2409 * message length as what to skip.
2410 */
2411 conn->inStart += 5 + msgLength;
2412 return pqPrepareAsyncResult(conn);
2413 }
2414
2415 /* Completed parsing this message, keep going */
2417 needInput = false;
2418 }
2419
2420 /*
2421 * We fall out of the loop only upon failing to read data.
2422 * conn->errorMessage has been set by pqWait or pqReadData. We want to
2423 * append it to any already-received error message.
2424 */
2426 return pqPrepareAsyncResult(conn);
2427}

References Assert, conn, fb(), getNotify(), getParameterStatus(), getReadyForQuery(), handleFatalError(), handleSyncLoss(), i, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, len, libpq_append_conn_error(), pgHavePendingResult, PGRES_COMMAND_OK, PGRES_FATAL_ERROR, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, pqCheckInBufferSpace(), pqFlush(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGetnchar(), PQmakeEmptyPGresult(), PqMsg_ErrorResponse, PqMsg_FunctionCall, PqMsg_FunctionCallResponse, PqMsg_NoticeResponse, PqMsg_NotificationResponse, PqMsg_ParameterStatus, PqMsg_ReadyForQuery, pqParseDone(), pqPrepareAsyncResult(), pqPutInt(), pqPutMsgEnd(), pqPutMsgStart(), pqPutnchar(), pqReadData(), pqSaveErrorResult(), pqWait(), pg_conn::result, and VALID_LONG_MESSAGE_TYPE.

Referenced by PQfn().

◆ pqGetCopyData3()

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

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

1949{
1950 int msgLength;
1951
1952 for (;;)
1953 {
1954 /*
1955 * Collect the next input message. To make life simpler for async
1956 * callers, we keep returning 0 until the next message is fully
1957 * available, even if it is not Copy Data.
1958 */
1960 if (msgLength < 0)
1961 return msgLength; /* end-of-copy or error */
1962 if (msgLength == 0)
1963 {
1964 /* Don't block if async read requested */
1965 if (async)
1966 return 0;
1967 /* Need to load more data */
1968 if (pqWait(true, false, conn) ||
1969 pqReadData(conn) < 0)
1970 return -2;
1971 continue;
1972 }
1973
1974 /*
1975 * Drop zero-length messages (shouldn't happen anyway). Otherwise
1976 * pass the data back to the caller.
1977 */
1978 msgLength -= 4;
1979 if (msgLength > 0)
1980 {
1981 *buffer = (char *) malloc(msgLength + 1);
1982 if (*buffer == NULL)
1983 {
1984 libpq_append_conn_error(conn, "out of memory");
1985 return -2;
1986 }
1987 memcpy(*buffer, &conn->inBuffer[conn->inCursor], msgLength);
1988 (*buffer)[msgLength] = '\0'; /* Add terminating null */
1989
1990 /* Mark message consumed */
1992
1993 return msgLength;
1994 }
1995
1996 /* Empty, so drop it and loop around for another */
1998 }
1999}

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

Referenced by PQgetCopyData().

◆ pqGetErrorNotice3()

int pqGetErrorNotice3 ( PGconn conn,
bool  isError 
)

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

899{
900 PGresult *res = NULL;
901 bool have_position = false;
903 char id;
904
905 /* If in pipeline mode, set error indicator for it */
908
909 /*
910 * If this is an error message, pre-emptively clear any incomplete query
911 * result we may have. We'd just throw it away below anyway, and
912 * releasing it before collecting the error might avoid out-of-memory.
913 */
914 if (isError)
916
917 /*
918 * Since the fields might be pretty long, we create a temporary
919 * PQExpBuffer rather than using conn->workBuffer. workBuffer is intended
920 * for stuff that is expected to be short. We shouldn't use
921 * conn->errorMessage either, since this might be only a notice.
922 */
924
925 /*
926 * Make a PGresult to hold the accumulated fields. We temporarily lie
927 * about the result status, so that PQmakeEmptyPGresult doesn't uselessly
928 * copy conn->errorMessage.
929 *
930 * NB: This allocation can fail, if you run out of memory. The rest of the
931 * function handles that gracefully, and we still try to set the error
932 * message as the connection's error message.
933 */
935 if (res)
937
938 /*
939 * Read the fields and save into res.
940 *
941 * While at it, save the SQLSTATE in conn->last_sqlstate, and note whether
942 * we saw a PG_DIAG_STATEMENT_POSITION field.
943 */
944 for (;;)
945 {
946 if (pqGetc(&id, conn))
947 goto fail;
948 if (id == '\0')
949 break; /* terminator found */
950 if (pqGets(&workBuf, conn))
951 goto fail;
952 pqSaveMessageField(res, id, workBuf.data);
953 if (id == PG_DIAG_SQLSTATE)
955 sizeof(conn->last_sqlstate));
956 else if (id == PG_DIAG_STATEMENT_POSITION)
957 have_position = true;
958 }
959
960 /*
961 * Save the active query text, if any, into res as well; but only if we
962 * might need it for an error cursor display, which is only true if there
963 * is a PG_DIAG_STATEMENT_POSITION field.
964 */
967
968 /*
969 * Now build the "overall" error message for PQresultErrorMessage.
970 */
973
974 /*
975 * Either save error as current async result, or just emit the notice.
976 */
977 if (isError)
978 {
979 pqClearAsyncResult(conn); /* redundant, but be safe */
980 if (res)
981 {
982 pqSetResultError(res, &workBuf, 0);
983 conn->result = res;
984 }
985 else
986 {
987 /* Fall back to using the internal-error processing paths */
988 conn->error_result = true;
989 }
990
992 libpq_append_conn_error(conn, "out of memory");
993 else
995 }
996 else
997 {
998 /* if we couldn't allocate the result set, just discard the NOTICE */
999 if (res)
1000 {
1001 /*
1002 * We can cheat a little here and not copy the message. But if we
1003 * were unlucky enough to run out of memory while filling workBuf,
1004 * insert "out of memory", as in pqSetResultError.
1005 */
1007 res->errMsg = libpq_gettext("out of memory\n");
1008 else
1009 res->errMsg = workBuf.data;
1010 if (res->noticeHooks.noticeRec != NULL)
1012 PQclear(res);
1013 }
1014 }
1015
1017 return 0;
1018
1019fail:
1020 PQclear(res);
1022 return EOF;
1023}

References appendPQExpBufferStr(), pg_conn::cmd_queue_head, conn, PQExpBufferData::data, pg_result::errMsg, pg_conn::error_result, pg_conn::errorMessage, pg_result::errQuery, fb(), 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, 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 2007 of file fe-protocol3.c.

2008{
2009 int status;
2010
2011 if (conn->sock == PGINVALID_SOCKET ||
2015 {
2016 libpq_append_conn_error(conn, "PQgetline: not doing text COPY OUT");
2017 *s = '\0';
2018 return EOF;
2019 }
2020
2021 while ((status = PQgetlineAsync(conn, s, maxlen - 1)) == 0)
2022 {
2023 /* need to load more data */
2024 if (pqWait(true, false, conn) ||
2025 pqReadData(conn) < 0)
2026 {
2027 *s = '\0';
2028 return EOF;
2029 }
2030 }
2031
2032 if (status < 0)
2033 {
2034 /* End of copy detected; gin up old-style terminator */
2035 strcpy(s, "\\.");
2036 return 0;
2037 }
2038
2039 /* Add null terminator, and strip trailing \n if present */
2040 if (s[status - 1] == '\n')
2041 {
2042 s[status - 1] = '\0';
2043 return 0;
2044 }
2045 else
2046 {
2047 s[status] = '\0';
2048 return 1;
2049 }
2050}

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

Referenced by PQgetline().

◆ pqGetlineAsync3()

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

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

2059{
2060 int msgLength;
2061 int avail;
2062
2065 return -1; /* we are not doing a copy... */
2066
2067 /*
2068 * Recognize the next input message. To make life simpler for async
2069 * callers, we keep returning 0 until the next message is fully available
2070 * even if it is not Copy Data. This should keep PQendcopy from blocking.
2071 * (Note: unlike pqGetCopyData3, we do not change asyncStatus here.)
2072 */
2074 if (msgLength < 0)
2075 return -1; /* end-of-copy or error */
2076 if (msgLength == 0)
2077 return 0; /* no data yet */
2078
2079 /*
2080 * Move data from libpq's buffer to the caller's. In the case where a
2081 * prior call found the caller's buffer too small, we use
2082 * conn->copy_already_done to remember how much of the row was already
2083 * returned to the caller.
2084 */
2086 avail = msgLength - 4 - conn->copy_already_done;
2087 if (avail <= bufsize)
2088 {
2089 /* Able to consume the whole message */
2090 memcpy(buffer, &conn->inBuffer[conn->inCursor], avail);
2091 /* Mark message consumed */
2092 conn->inStart = conn->inCursor + avail;
2093 /* Reset state for next time */
2095 return avail;
2096 }
2097 else
2098 {
2099 /* We must return a partial message */
2100 memcpy(buffer, &conn->inBuffer[conn->inCursor], bufsize);
2101 /* The message is NOT consumed from libpq's buffer */
2103 return bufsize;
2104 }
2105}

References pg_conn::asyncStatus, bufsize, conn, pg_conn::copy_already_done, fb(), 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 1443 of file fe-protocol3.c.

1444{
1445 int their_version;
1446 int num;
1449
1450 /*
1451 * During 19beta only, if protocol grease is in use, assume that it's the
1452 * cause of any invalid messages encountered below. We'll print extra
1453 * information for the end user in that case.
1454 */
1456
1457 if (pqGetInt(&their_version, 4, conn) != 0)
1458 goto eof;
1459
1460 if (pqGetInt(&num, 4, conn) != 0)
1461 goto eof;
1462
1463 /*
1464 * Check the protocol version.
1465 *
1466 * PG_PROTOCOL_GREASE is intentionally unsupported and reserved. It's
1467 * higher than any real version, so check for that first, to get the most
1468 * specific error message. Then check the upper and lower bounds.
1469 */
1471 {
1472 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requested \"grease\" protocol version 3.9999");
1473 goto failure;
1474 }
1475
1477 {
1478 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requested downgrade to a higher-numbered version");
1479 goto failure;
1480 }
1481
1482 if (their_version < PG_PROTOCOL(3, 0))
1483 {
1484 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requested downgrade to pre-3.0 protocol version");
1485 goto failure;
1486 }
1487
1488 /* 3.1 never existed, we went straight from 3.0 to 3.2 */
1490 {
1491 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requested downgrade to non-existent 3.1 protocol version");
1492 goto failure;
1493 }
1494
1495 if (num < 0)
1496 {
1497 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported negative number of unsupported parameters");
1498 goto failure;
1499 }
1500
1501 if (their_version == conn->pversion && num == 0)
1502 {
1503 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server negotiated but asks for no changes");
1504 goto failure;
1505 }
1506
1507 if (their_version < conn->min_pversion)
1508 {
1509 libpq_append_conn_error(conn, "server only supports protocol version %d.%d, but \"%s\" was set to %d.%d",
1512 "min_protocol_version",
1515
1516 need_grease_info = false; /* this is valid server behavior */
1517 goto failure;
1518 }
1519
1520 /* the version is acceptable */
1522
1523 /*
1524 * Check that all expected unsupported parameters are reported by the
1525 * server.
1526 */
1529
1530 for (int i = 0; i < num; i++)
1531 {
1532 if (pqGets(&conn->workBuffer, conn))
1533 {
1534 goto eof;
1535 }
1536 if (strncmp(conn->workBuffer.data, "_pq_.", 5) != 0)
1537 {
1538 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported unsupported parameter name without a \"%s\" prefix (\"%s\")", "_pq_.", conn->workBuffer.data);
1539 goto failure;
1540 }
1541
1542 /* Check if this is the expected test parameter */
1544 strcmp(conn->workBuffer.data, "_pq_.test_protocol_negotiation") == 0)
1545 {
1547 }
1548 else
1549 {
1550 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported an unsupported parameter that was not requested (\"%s\")",
1552 goto failure;
1553 }
1554 }
1555
1556 /*
1557 * If we requested protocol grease, the server must report
1558 * _pq_.test_protocol_negotiation as unsupported. This ensures
1559 * comprehensive NegotiateProtocolVersion implementation.
1560 */
1562 {
1563 libpq_append_conn_error(conn, "server did not report the unsupported `_pq_.test_protocol_negotiation` parameter in its protocol negotiation message");
1564 goto failure;
1565 }
1566
1567 return 0;
1568
1569eof:
1570 libpq_append_conn_error(conn, "received invalid protocol negotiation message: message too short");
1571failure:
1572 if (need_grease_info)
1576 return 1;
1577}

References pg_conn::asyncStatus, conn, PQExpBufferData::data, fb(), i, libpq_append_conn_error(), libpq_append_grease_info(), pg_conn::max_pversion, pg_conn::min_pversion, PG_PROTOCOL, PG_PROTOCOL_GREASE, PG_PROTOCOL_MAJOR, PG_PROTOCOL_MINOR, PG_PROTOCOL_RESERVED_31, PGASYNC_READY, pqGetInt(), pqGets(), pqSaveErrorResult(), pg_conn::pversion, and pg_conn::workBuffer.

Referenced by PQconnectPoll().

◆ pqParseInput3()

void pqParseInput3 ( PGconn conn)

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

71{
72 char id;
73 int msgLength;
74 int avail;
75
76 /*
77 * Loop to parse successive complete messages available in the buffer.
78 */
79 for (;;)
80 {
81 /*
82 * Try to read a message. First get the type code and length. Return
83 * if not enough data.
84 */
86 if (pqGetc(&id, conn))
87 return;
88 if (pqGetInt(&msgLength, 4, conn))
89 return;
90
91 /*
92 * Try to validate message type/length here. A length less than 4 is
93 * definitely broken. Large lengths should only be believed for a few
94 * message types.
95 */
96 if (msgLength < 4)
97 {
99 return;
100 }
101 if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
102 {
104 return;
105 }
106
107 /*
108 * Can't process if message body isn't all here yet.
109 */
110 msgLength -= 4;
111 avail = conn->inEnd - conn->inCursor;
112 if (avail < msgLength)
113 {
114 /*
115 * Before returning, enlarge the input buffer if needed to hold
116 * the whole message. This is better than leaving it to
117 * pqReadData because we can avoid multiple cycles of realloc()
118 * when the message is large; also, we can implement a reasonable
119 * recovery strategy if we are unable to make the buffer big
120 * enough.
121 */
123 conn))
124 {
125 /*
126 * Abandon the connection. There's not much else we can
127 * safely do; we can't just ignore the message or we could
128 * miss important changes to the connection state.
129 * pqCheckInBufferSpace() already reported the error.
130 */
132 }
133 return;
134 }
135
136 /*
137 * NOTIFY and NOTICE messages can happen in any state; always process
138 * them right away.
139 *
140 * Most other messages should only be processed while in BUSY state.
141 * (In particular, in READY state we hold off further parsing until
142 * the application collects the current PGresult.)
143 *
144 * However, if the state is IDLE then we got trouble; we need to deal
145 * with the unexpected message somehow.
146 *
147 * ParameterStatus ('S') messages are a special case: in IDLE state we
148 * must process 'em (this case could happen if a new value was adopted
149 * from config file due to SIGHUP), but otherwise we hold off until
150 * BUSY state.
151 */
153 {
154 if (getNotify(conn))
155 return;
156 }
157 else if (id == PqMsg_NoticeResponse)
158 {
159 if (pqGetErrorNotice3(conn, false))
160 return;
161 }
162 else if (conn->asyncStatus != PGASYNC_BUSY)
163 {
164 /* If not IDLE state, just wait ... */
166 return;
167
168 /*
169 * Unexpected message in IDLE state; need to recover somehow.
170 * ERROR messages are handled using the notice processor;
171 * ParameterStatus is handled normally; anything else is just
172 * dropped on the floor after displaying a suitable warning
173 * notice. (An ERROR is very possibly the backend telling us why
174 * it is about to close the connection, so we don't want to just
175 * discard it...)
176 */
177 if (id == PqMsg_ErrorResponse)
178 {
179 if (pqGetErrorNotice3(conn, false /* treat as notice */ ))
180 return;
181 }
182 else if (id == PqMsg_ParameterStatus)
183 {
185 return;
186 }
187 else
188 {
189 /* Any other case is unexpected and we summarily skip it */
191 "message type 0x%02x arrived from server while idle",
192 id);
193 /* Discard the unexpected message */
195 }
196 }
197 else
198 {
199 /*
200 * In BUSY state, we can process everything.
201 */
202 switch (id)
203 {
205 if (pqGets(&conn->workBuffer, conn))
206 return;
208 {
211 if (!conn->result)
212 {
213 libpq_append_conn_error(conn, "out of memory");
215 }
216 }
217 if (conn->result)
221 break;
223 if (pqGetErrorNotice3(conn, true))
224 return;
226 break;
229 return;
231 {
234 if (!conn->result)
235 {
236 libpq_append_conn_error(conn, "out of memory");
238 }
239 else
240 {
243 }
244 }
245 else
246 {
247 /* Advance the command queue and set us idle */
248 pqCommandQueueAdvance(conn, true, false);
250 }
251 break;
254 {
257 if (!conn->result)
258 {
259 libpq_append_conn_error(conn, "out of memory");
261 }
262 }
264 break;
266 /* If we're doing PQprepare, we're done; else ignore */
267 if (conn->cmd_queue_head &&
269 {
271 {
274 if (!conn->result)
275 {
276 libpq_append_conn_error(conn, "out of memory");
278 }
279 }
281 }
282 break;
284 /* Nothing to do for this message type */
285 break;
287 /* If we're doing PQsendClose, we're done; else ignore */
288 if (conn->cmd_queue_head &&
290 {
292 {
295 if (!conn->result)
296 {
297 libpq_append_conn_error(conn, "out of memory");
299 }
300 }
302 }
303 break;
306 return;
307 break;
309
310 /*
311 * This is expected only during backend startup, but it's
312 * just as easy to handle it as part of the main loop.
313 * Save the data and continue processing.
314 */
316 return;
317 break;
319 if (conn->error_result ||
320 (conn->result != NULL &&
322 {
323 /*
324 * We've already choked for some reason. Just discard
325 * the data till we get to the end of the query.
326 */
328 }
329 else if (conn->result == NULL ||
332 {
333 /* First 'T' in a query sequence */
335 return;
336 }
337 else
338 {
339 /*
340 * A new 'T' message is treated as the start of
341 * another PGresult. (It is not clear that this is
342 * really possible with the current backend.) We stop
343 * parsing until the application accepts the current
344 * result.
345 */
347 return;
348 }
349 break;
350 case PqMsg_NoData:
351
352 /*
353 * NoData indicates that we will not be seeing a
354 * RowDescription message because the statement or portal
355 * inquired about doesn't return rows.
356 *
357 * If we're doing a Describe, we have to pass something
358 * back to the client, so set up a COMMAND_OK result,
359 * instead of PGRES_TUPLES_OK. Otherwise we can just
360 * ignore this message.
361 */
362 if (conn->cmd_queue_head &&
364 {
366 {
369 if (!conn->result)
370 {
371 libpq_append_conn_error(conn, "out of memory");
373 }
374 }
376 }
377 break;
380 return;
381 break;
382 case PqMsg_DataRow:
383 if (conn->result != NULL &&
386 {
387 /* Read another tuple of a normal query response */
389 return;
390 }
391 else if (conn->error_result ||
392 (conn->result != NULL &&
394 {
395 /*
396 * We've already choked for some reason. Just discard
397 * tuples till we get to the end of the query.
398 */
400 }
401 else
402 {
403 /* Set up to report error at end of query */
404 libpq_append_conn_error(conn, "server sent data (\"D\" message) without prior row description (\"T\" message)");
406 /* Discard the unexpected message */
408 }
409 break;
412 return;
414 break;
417 return;
420 break;
423 return;
426 break;
427 case PqMsg_CopyData:
428
429 /*
430 * If we see Copy Data, just silently drop it. This would
431 * only occur if application exits COPY OUT mode too
432 * early.
433 */
435 break;
436 case PqMsg_CopyDone:
437
438 /*
439 * If we see Copy Done, just silently drop it. This is
440 * the normal case during PQendcopy. We will keep
441 * swallowing data, expecting to see command-complete for
442 * the COPY command.
443 */
444 break;
445 default:
446 libpq_append_conn_error(conn, "unexpected response from server; first received character was \"%c\"", id);
447 /* build an error result holding the error message */
449 /* not sure if we will see more, so go to ready state */
451 /* Discard the unexpected message */
453 break;
454 } /* switch on protocol character */
455 }
456 /* Successfully consumed this message */
457 if (conn->inCursor == conn->inStart + 5 + msgLength)
458 {
459 /* Normal case: parsing agrees with specified length */
461 }
462 else if (conn->error_result && conn->status == CONNECTION_BAD)
463 {
464 /* The connection was abandoned and we already reported it */
465 return;
466 }
467 else
468 {
469 /* Trouble --- report it */
470 libpq_append_conn_error(conn, "message contents do not agree with length in message type \"%c\"", id);
471 /* build an error result holding the error message */
474 /* trust the specified message length as what to skip */
475 conn->inStart += 5 + msgLength;
476 }
477 }
478}

References pg_conn::asyncStatus, pg_conn::cmd_queue_head, pg_result::cmdStatus, CMDSTATUS_LEN, conn, CONNECTION_BAD, pg_conn::copy_already_done, PQExpBufferData::data, pg_conn::error_result, fb(), getAnotherTuple(), getBackendKeyData(), getCopyStart(), getNotify(), getParamDescriptions(), getParameterStatus(), getReadyForQuery(), getRowDescriptions(), handleFatalError(), handleSyncLoss(), pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, libpq_append_conn_error(), pg_conn::noticeHooks, PGASYNC_BUSY, PGASYNC_COPY_BOTH, PGASYNC_COPY_IN, PGASYNC_COPY_OUT, PGASYNC_IDLE, PGASYNC_READY, pgHavePendingResult, PGQUERY_CLOSE, PGQUERY_DESCRIBE, PGQUERY_PREPARE, PGRES_COMMAND_OK, PGRES_COPY_BOTH, PGRES_COPY_IN, PGRES_COPY_OUT, PGRES_EMPTY_QUERY, PGRES_FATAL_ERROR, PGRES_PIPELINE_SYNC, PGRES_TUPLES_CHUNK, PGRES_TUPLES_OK, pg_conn::pipelineStatus, PQ_PIPELINE_OFF, PQ_PIPELINE_ON, pqCheckInBufferSpace(), pqCommandQueueAdvance(), pqGetc(), pqGetErrorNotice3(), pqGetInt(), pqGets(), pqInternalNotice(), PQmakeEmptyPGresult(), PqMsg_BackendKeyData, PqMsg_BindComplete, PqMsg_CloseComplete, PqMsg_CommandComplete, PqMsg_CopyBothResponse, PqMsg_CopyData, PqMsg_CopyDone, PqMsg_CopyInResponse, PqMsg_CopyOutResponse, PqMsg_DataRow, PqMsg_EmptyQueryResponse, PqMsg_ErrorResponse, PqMsg_NoData, PqMsg_NoticeResponse, PqMsg_NotificationResponse, PqMsg_ParameterDescription, PqMsg_ParameterStatus, PqMsg_ParseComplete, PqMsg_ReadyForQuery, PqMsg_RowDescription, pqParseDone(), pqSaveErrorResult(), PGcmdQueueEntry::queryclass, pg_conn::result, pg_result::resultStatus, pg_conn::status, 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 1201 of file fe-protocol3.c.

1202{
1203#define DISPLAY_SIZE 60 /* screen width limit, in screen cols */
1204#define MIN_RIGHT_CUT 10 /* try to keep this far away from EOL */
1205
1206 char *wquery;
1207 int slen,
1208 cno,
1209 i,
1210 *qidx,
1211 *scridx,
1212 qoffset,
1213 scroffset,
1214 ibeg,
1215 iend,
1216 loc_line;
1217 bool mb_encoding,
1218 beg_trunc,
1219 end_trunc;
1220
1221 /* Convert loc from 1-based to 0-based; no-op if out of range */
1222 loc--;
1223 if (loc < 0)
1224 return;
1225
1226 /* Need a writable copy of the query */
1227 wquery = strdup(query);
1228 if (wquery == NULL)
1229 return; /* fail silently if out of memory */
1230
1231 /*
1232 * Each character might occupy multiple physical bytes in the string, and
1233 * in some Far Eastern character sets it might take more than one screen
1234 * column as well. We compute the starting byte offset and starting
1235 * screen column of each logical character, and store these in qidx[] and
1236 * scridx[] respectively.
1237 */
1238
1239 /*
1240 * We need a safe allocation size.
1241 *
1242 * The only caller of reportErrorPosition() is pqBuildErrorMessage3(); it
1243 * gets its query from either a PQresultErrorField() or a PGcmdQueueEntry,
1244 * both of which must have fit into conn->inBuffer/outBuffer. So slen fits
1245 * inside an int, but we can't assume that (slen * sizeof(int)) fits
1246 * inside a size_t.
1247 */
1248 slen = strlen(wquery) + 1;
1249 if (slen > SIZE_MAX / sizeof(int))
1250 {
1251 free(wquery);
1252 return;
1253 }
1254
1255 qidx = (int *) malloc(slen * sizeof(int));
1256 if (qidx == NULL)
1257 {
1258 free(wquery);
1259 return;
1260 }
1261 scridx = (int *) malloc(slen * sizeof(int));
1262 if (scridx == NULL)
1263 {
1264 free(qidx);
1265 free(wquery);
1266 return;
1267 }
1268
1269 /* We can optimize a bit if it's a single-byte encoding */
1271
1272 /*
1273 * Within the scanning loop, cno is the current character's logical
1274 * number, qoffset is its offset in wquery, and scroffset is its starting
1275 * logical screen column (all indexed from 0). "loc" is the logical
1276 * character number of the error location. We scan to determine loc_line
1277 * (the 1-based line number containing loc) and ibeg/iend (first character
1278 * number and last+1 character number of the line containing loc). Note
1279 * that qidx[] and scridx[] are filled only as far as iend.
1280 */
1281 qoffset = 0;
1282 scroffset = 0;
1283 loc_line = 1;
1284 ibeg = 0;
1285 iend = -1; /* -1 means not set yet */
1286
1287 for (cno = 0; wquery[qoffset] != '\0'; cno++)
1288 {
1289 char ch = wquery[qoffset];
1290
1291 qidx[cno] = qoffset;
1292 scridx[cno] = scroffset;
1293
1294 /*
1295 * Replace tabs with spaces in the writable copy. (Later we might
1296 * want to think about coping with their variable screen width, but
1297 * not today.)
1298 */
1299 if (ch == '\t')
1300 wquery[qoffset] = ' ';
1301
1302 /*
1303 * If end-of-line, count lines and mark positions. Each \r or \n
1304 * counts as a line except when \r \n appear together.
1305 */
1306 else if (ch == '\r' || ch == '\n')
1307 {
1308 if (cno < loc)
1309 {
1310 if (ch == '\r' ||
1311 cno == 0 ||
1312 wquery[qidx[cno - 1]] != '\r')
1313 loc_line++;
1314 /* extract beginning = last line start before loc. */
1315 ibeg = cno + 1;
1316 }
1317 else
1318 {
1319 /* set extract end. */
1320 iend = cno;
1321 /* done scanning. */
1322 break;
1323 }
1324 }
1325
1326 /* Advance */
1327 if (mb_encoding)
1328 {
1329 int w;
1330
1332 /* treat any non-tab control chars as width 1 */
1333 if (w <= 0)
1334 w = 1;
1335 scroffset += w;
1337 }
1338 else
1339 {
1340 /* We assume wide chars only exist in multibyte encodings */
1341 scroffset++;
1342 qoffset++;
1343 }
1344 }
1345 /* Fix up if we didn't find an end-of-line after loc */
1346 if (iend < 0)
1347 {
1348 iend = cno; /* query length in chars, +1 */
1349 qidx[iend] = qoffset;
1351 }
1352
1353 /* Print only if loc is within computed query length */
1354 if (loc <= cno)
1355 {
1356 /* If the line extracted is too long, we truncate it. */
1357 beg_trunc = false;
1358 end_trunc = false;
1360 {
1361 /*
1362 * We first truncate right if it is enough. This code might be
1363 * off a space or so on enforcing MIN_RIGHT_CUT if there's a wide
1364 * character right there, but that should be okay.
1365 */
1366 if (scridx[ibeg] + DISPLAY_SIZE >= scridx[loc] + MIN_RIGHT_CUT)
1367 {
1368 while (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1369 iend--;
1370 end_trunc = true;
1371 }
1372 else
1373 {
1374 /* Truncate right if not too close to loc. */
1375 while (scridx[loc] + MIN_RIGHT_CUT < scridx[iend])
1376 {
1377 iend--;
1378 end_trunc = true;
1379 }
1380
1381 /* Truncate left if still too long. */
1382 while (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1383 {
1384 ibeg++;
1385 beg_trunc = true;
1386 }
1387 }
1388 }
1389
1390 /* truncate working copy at desired endpoint */
1391 wquery[qidx[iend]] = '\0';
1392
1393 /* Begin building the finished message. */
1394 i = msg->len;
1395 appendPQExpBuffer(msg, libpq_gettext("LINE %d: "), loc_line);
1396 if (beg_trunc)
1397 appendPQExpBufferStr(msg, "...");
1398
1399 /*
1400 * While we have the prefix in the msg buffer, compute its screen
1401 * width.
1402 */
1403 scroffset = 0;
1404 for (; i < msg->len; i += PQmblenBounded(&msg->data[i], encoding))
1405 {
1406 int w = pg_encoding_dsplen(encoding, &msg->data[i]);
1407
1408 if (w <= 0)
1409 w = 1;
1410 scroffset += w;
1411 }
1412
1413 /* Finish up the LINE message line. */
1415 if (end_trunc)
1416 appendPQExpBufferStr(msg, "...");
1417 appendPQExpBufferChar(msg, '\n');
1418
1419 /* Now emit the cursor marker line. */
1420 scroffset += scridx[loc] - scridx[ibeg];
1421 for (i = 0; i < scroffset; i++)
1422 appendPQExpBufferChar(msg, ' ');
1423 appendPQExpBufferChar(msg, '^');
1424 appendPQExpBufferChar(msg, '\n');
1425 }
1426
1427 /* Clean up. */
1428 free(scridx);
1429 free(qidx);
1430 free(wquery);
1431}

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

Referenced by pqBuildErrorMessage3().