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 buf_size, 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 || \
(id) == PqMsg_RowDescription || \
#define PqMsg_NotificationResponse
Definition protocol.h:41
#define PqMsg_CopyData
Definition protocol.h:65
#define PqMsg_ParameterDescription
Definition protocol.h:58
#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.

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}
479
480/*
481 * handleFatalError: clean up after a nonrecoverable error
482 *
483 * This is for errors where we need to abandon the connection. The caller has
484 * already saved the error message in conn->errorMessage.
485 */
486static void
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}
496
497/*
498 * handleSyncLoss: clean up after loss of message-boundary sync
499 *
500 * There isn't really a lot we can do here except abandon the connection.
501 */
502static void
503handleSyncLoss(PGconn *conn, char id, int msgLength)
504{
505 libpq_append_conn_error(conn, "lost synchronization with server: got message type \"%c\", length %d",
506 id, msgLength);
508}
509
510/*
511 * parseInput subroutine to read a 'T' (row descriptions) message.
512 * We'll build a new PGresult structure (unless called for a Describe
513 * command for a prepared statement) containing the attribute data.
514 * Returns: 0 if processed message successfully, EOF to suspend parsing
515 * (the latter case is not actually used currently).
516 */
517static int
519{
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)
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}
681
682/*
683 * parseInput subroutine to read a 't' (ParameterDescription) message.
684 * We'll build a new PGresult structure containing the parameter data.
685 * Returns: 0 if processed message successfully, EOF to suspend parsing
686 * (the latter case is not actually used currently).
687 */
688static int
690{
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)
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}
769
770/*
771 * parseInput subroutine to read a 'D' (row data) message.
772 * We fill rowbuf with column pointers and then call the row processor.
773 * Returns: 0 if processed message successfully, EOF to suspend parsing
774 * (the latter case is not actually used currently).
775 */
776static int
778{
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}
887
888
889/*
890 * Attempt to read an Error or Notice response message.
891 * This is possible in several places, so we break it out as a subroutine.
892 *
893 * Entry: 'E' or 'N' message type and length have already been consumed.
894 * Exit: returns 0 if successfully consumed message.
895 * returns EOF if not enough data.
896 */
897int
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}
1024
1025/*
1026 * Construct an error message from the fields in the given PGresult,
1027 * appending it to the contents of "msg".
1028 */
1029void
1031 PGVerbosity verbosity, PGContextVisibility show_context)
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}
1193
1194/*
1195 * Add an error-location display to the error message under construction.
1196 *
1197 * The cursor location is measured in logical characters; the query string
1198 * is presumed to be in the specified encoding.
1199 */
1200static void
1201reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding)
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}
1432
1433
1434/*
1435 * Attempt to read a NegotiateProtocolVersion message. Sets conn->pversion
1436 * to the version that's negotiated by the server.
1437 *
1438 * Entry: 'v' message type and length have already been consumed.
1439 * Exit: returns 0 if successfully consumed message.
1440 * returns 1 on failure. The error message is filled in.
1441 */
1442int
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 \"%s\" parameter in its protocol negotiation message",
1564 "_pq_.test_protocol_negotiation");
1565 goto failure;
1566 }
1567
1568 return 0;
1569
1570eof:
1571 libpq_append_conn_error(conn, "received invalid protocol negotiation message: message too short");
1572failure:
1573 if (need_grease_info)
1577 return 1;
1578}
1579
1580
1581/*
1582 * Attempt to read a ParameterStatus message.
1583 * This is possible in several places, so we break it out as a subroutine.
1584 *
1585 * Entry: 'S' message type and length have already been consumed.
1586 * Exit: returns 0 if successfully consumed message.
1587 * returns EOF if not enough data.
1588 */
1589static int
1591{
1593
1594 /* Get the parameter name */
1595 if (pqGets(&conn->workBuffer, conn))
1596 return EOF;
1597 /* Get the parameter value (could be large) */
1599 if (pqGets(&valueBuf, conn))
1600 {
1602 return EOF;
1603 }
1604 /* And save it */
1606 {
1607 libpq_append_conn_error(conn, "out of memory");
1609 }
1611 return 0;
1612}
1613
1614/*
1615 * parseInput subroutine to read a BackendKeyData message.
1616 * Entry: 'K' message type and length have already been consumed.
1617 * Exit: returns 0 if successfully consumed message.
1618 * returns EOF if not enough data.
1619 */
1620static int
1622{
1623 int cancel_key_len;
1624
1625 if (conn->be_cancel_key)
1626 {
1630 }
1631
1632 if (pqGetInt(&(conn->be_pid), 4, conn))
1633 return EOF;
1634
1636
1637 if (cancel_key_len != 4 && conn->pversion == PG_PROTOCOL(3, 0))
1638 {
1639 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);
1641 return 0;
1642 }
1643
1644 if (cancel_key_len < 4)
1645 {
1646 libpq_append_conn_error(conn, "received invalid BackendKeyData message: cancel key with length %d is too short (minimum 4 bytes)", cancel_key_len);
1648 return 0;
1649 }
1650
1651 if (cancel_key_len > 256)
1652 {
1653 libpq_append_conn_error(conn, "received invalid BackendKeyData message: cancel key with length %d is too long (maximum 256 bytes)", cancel_key_len);
1655 return 0;
1656 }
1657
1659 if (conn->be_cancel_key == NULL)
1660 {
1661 libpq_append_conn_error(conn, "out of memory");
1663 return 0;
1664 }
1666 {
1669 return EOF;
1670 }
1672 return 0;
1673}
1674
1675
1676/*
1677 * Attempt to read a Notify response message.
1678 * This is possible in several places, so we break it out as a subroutine.
1679 *
1680 * Entry: 'A' message type and length have already been consumed.
1681 * Exit: returns 0 if successfully consumed Notify message.
1682 * returns EOF if not enough data.
1683 */
1684static int
1686{
1687 int be_pid;
1688 char *svname;
1689 int nmlen;
1690 int extralen;
1692
1693 if (pqGetInt(&be_pid, 4, conn))
1694 return EOF;
1695 if (pqGets(&conn->workBuffer, conn))
1696 return EOF;
1697 /* must save name while getting extra string */
1699 if (!svname)
1700 {
1701 /*
1702 * Notify messages can arrive at any state, so we cannot associate the
1703 * error with any particular query. There's no way to return back an
1704 * "async error", so the best we can do is drop the connection. That
1705 * seems better than silently ignoring the notification.
1706 */
1707 libpq_append_conn_error(conn, "out of memory");
1709 return 0;
1710 }
1711 if (pqGets(&conn->workBuffer, conn))
1712 {
1713 free(svname);
1714 return EOF;
1715 }
1716
1717 /*
1718 * Store the strings right after the PGnotify structure so it can all be
1719 * freed at once. We don't use NAMEDATALEN because we don't want to tie
1720 * this interface to a specific server name length.
1721 */
1722 nmlen = strlen(svname);
1724 newNotify = (PGnotify *) malloc(sizeof(PGnotify) + nmlen + extralen + 2);
1725 if (!newNotify)
1726 {
1727 free(svname);
1728 libpq_append_conn_error(conn, "out of memory");
1730 return 0;
1731 }
1732
1733 newNotify->relname = (char *) newNotify + sizeof(PGnotify);
1734 strcpy(newNotify->relname, svname);
1735 newNotify->extra = newNotify->relname + nmlen + 1;
1737 newNotify->be_pid = be_pid;
1738 newNotify->next = NULL;
1739 if (conn->notifyTail)
1741 else
1744
1745 free(svname);
1746 return 0;
1747}
1748
1749/*
1750 * getCopyStart - process CopyInResponse, CopyOutResponse or
1751 * CopyBothResponse message
1752 *
1753 * parseInput already read the message type and length.
1754 */
1755static int
1757{
1759 int nfields;
1760 int i;
1761
1763 if (!result)
1764 goto failure;
1765
1767 goto failure;
1768 result->binary = conn->copy_is_binary;
1769 /* the next two bytes are the number of fields */
1770 if (pqGetInt(&(result->numAttributes), 2, conn))
1771 goto failure;
1772 nfields = result->numAttributes;
1773
1774 /* allocate space for the attribute descriptors */
1775 if (nfields > 0)
1776 {
1777 result->attDescs = (PGresAttDesc *)
1778 pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
1779 if (!result->attDescs)
1780 goto failure;
1781 MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
1782 }
1783
1784 for (i = 0; i < nfields; i++)
1785 {
1786 int format;
1787
1788 if (pqGetInt(&format, 2, conn))
1789 goto failure;
1790
1791 /*
1792 * Since pqGetInt treats 2-byte integers as unsigned, we need to
1793 * coerce these results to signed form.
1794 */
1795 format = (int) ((int16) format);
1796 result->attDescs[i].format = format;
1797 }
1798
1799 /* Success! */
1800 conn->result = result;
1801 return 0;
1802
1803failure:
1804 PQclear(result);
1805 return EOF;
1806}
1807
1808/*
1809 * getReadyForQuery - process ReadyForQuery message
1810 */
1811static int
1813{
1814 char xact_status;
1815
1816 if (pqGetc(&xact_status, conn))
1817 return EOF;
1818 switch (xact_status)
1819 {
1820 case 'I':
1822 break;
1823 case 'T':
1825 break;
1826 case 'E':
1828 break;
1829 default:
1831 break;
1832 }
1833
1834 return 0;
1835}
1836
1837/*
1838 * getCopyDataMessage - fetch next CopyData message, process async messages
1839 *
1840 * Returns length word of CopyData message (> 0), or 0 if no complete
1841 * message available, -1 if end of copy, -2 if error.
1842 */
1843static int
1845{
1846 char id;
1847 int msgLength;
1848 int avail;
1849
1850 for (;;)
1851 {
1852 /*
1853 * Do we have the next input message? To make life simpler for async
1854 * callers, we keep returning 0 until the next message is fully
1855 * available, even if it is not Copy Data.
1856 */
1858 if (pqGetc(&id, conn))
1859 return 0;
1860 if (pqGetInt(&msgLength, 4, conn))
1861 return 0;
1862 if (msgLength < 4)
1863 {
1865 return -2;
1866 }
1867 avail = conn->inEnd - conn->inCursor;
1868 if (avail < msgLength - 4)
1869 {
1870 /*
1871 * Before returning, enlarge the input buffer if needed to hold
1872 * the whole message. See notes in parseInput.
1873 */
1874 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength - 4,
1875 conn))
1876 {
1877 /*
1878 * Abandon the connection. There's not much else we can
1879 * safely do; we can't just ignore the message or we could
1880 * miss important changes to the connection state.
1881 * pqCheckInBufferSpace() already reported the error.
1882 */
1884 return -2;
1885 }
1886 return 0;
1887 }
1888
1889 /*
1890 * If it's a legitimate async message type, process it. (NOTIFY
1891 * messages are not currently possible here, but we handle them for
1892 * completeness.) Otherwise, if it's anything except Copy Data,
1893 * report end-of-copy.
1894 */
1895 switch (id)
1896 {
1898 if (getNotify(conn))
1899 return 0;
1900 break;
1902 if (pqGetErrorNotice3(conn, false))
1903 return 0;
1904 break;
1907 return 0;
1908 break;
1909 case PqMsg_CopyData:
1910 return msgLength;
1911 case PqMsg_CopyDone:
1912
1913 /*
1914 * If this is a CopyDone message, exit COPY_OUT mode and let
1915 * caller read status with PQgetResult(). If we're in
1916 * COPY_BOTH mode, return to COPY_IN mode.
1917 */
1920 else
1922 return -1;
1923 default: /* treat as end of copy */
1924
1925 /*
1926 * Any other message terminates either COPY_IN or COPY_BOTH
1927 * mode.
1928 */
1930 return -1;
1931 }
1932
1933 /* Drop the processed message and loop around for another */
1935 }
1936}
1937
1938/*
1939 * PQgetCopyData - read a row of data from the backend during COPY OUT
1940 * or COPY BOTH
1941 *
1942 * If successful, sets *buffer to point to a malloc'd row of data, and
1943 * returns row length (always > 0) as result.
1944 * Returns 0 if no row available yet (only possible if async is true),
1945 * -1 if end of copy (consult PQgetResult), or -2 if error (consult
1946 * PQerrorMessage).
1947 */
1948int
1949pqGetCopyData3(PGconn *conn, char **buffer, int async)
1950{
1951 int msgLength;
1952
1953 for (;;)
1954 {
1955 /*
1956 * Collect the next input message. To make life simpler for async
1957 * callers, we keep returning 0 until the next message is fully
1958 * available, even if it is not Copy Data.
1959 */
1961 if (msgLength < 0)
1962 return msgLength; /* end-of-copy or error */
1963 if (msgLength == 0)
1964 {
1965 /* Don't block if async read requested */
1966 if (async)
1967 return 0;
1968 /* Need to load more data */
1969 if (pqWait(true, false, conn) ||
1970 pqReadData(conn) < 0)
1971 return -2;
1972 continue;
1973 }
1974
1975 /*
1976 * Drop zero-length messages (shouldn't happen anyway). Otherwise
1977 * pass the data back to the caller.
1978 */
1979 msgLength -= 4;
1980 if (msgLength > 0)
1981 {
1982 *buffer = (char *) malloc(msgLength + 1);
1983 if (*buffer == NULL)
1984 {
1985 libpq_append_conn_error(conn, "out of memory");
1986 return -2;
1987 }
1988 memcpy(*buffer, &conn->inBuffer[conn->inCursor], msgLength);
1989 (*buffer)[msgLength] = '\0'; /* Add terminating null */
1990
1991 /* Mark message consumed */
1993
1994 return msgLength;
1995 }
1996
1997 /* Empty, so drop it and loop around for another */
1999 }
2000}
2001
2002/*
2003 * PQgetline - gets a newline-terminated string from the backend.
2004 *
2005 * See fe-exec.c for documentation.
2006 */
2007int
2008pqGetline3(PGconn *conn, char *s, int maxlen)
2009{
2010 int status;
2011
2012 if (conn->sock == PGINVALID_SOCKET ||
2016 {
2017 libpq_append_conn_error(conn, "PQgetline: not doing text COPY OUT");
2018 *s = '\0';
2019 return EOF;
2020 }
2021
2022 while ((status = PQgetlineAsync(conn, s, maxlen - 1)) == 0)
2023 {
2024 /* need to load more data */
2025 if (pqWait(true, false, conn) ||
2026 pqReadData(conn) < 0)
2027 {
2028 *s = '\0';
2029 return EOF;
2030 }
2031 }
2032
2033 if (status < 0)
2034 {
2035 /* End of copy detected; gin up old-style terminator */
2036 strcpy(s, "\\.");
2037 return 0;
2038 }
2039
2040 /* Add null terminator, and strip trailing \n if present */
2041 if (s[status - 1] == '\n')
2042 {
2043 s[status - 1] = '\0';
2044 return 0;
2045 }
2046 else
2047 {
2048 s[status] = '\0';
2049 return 1;
2050 }
2051}
2052
2053/*
2054 * PQgetlineAsync - gets a COPY data row without blocking.
2055 *
2056 * See fe-exec.c for documentation.
2057 */
2058int
2059pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)
2060{
2061 int msgLength;
2062 int avail;
2063
2066 return -1; /* we are not doing a copy... */
2067
2068 /*
2069 * Recognize the next input message. To make life simpler for async
2070 * callers, we keep returning 0 until the next message is fully available
2071 * even if it is not Copy Data. This should keep PQendcopy from blocking.
2072 * (Note: unlike pqGetCopyData3, we do not change asyncStatus here.)
2073 */
2075 if (msgLength < 0)
2076 return -1; /* end-of-copy or error */
2077 if (msgLength == 0)
2078 return 0; /* no data yet */
2079
2080 /*
2081 * Move data from libpq's buffer to the caller's. In the case where a
2082 * prior call found the caller's buffer too small, we use
2083 * conn->copy_already_done to remember how much of the row was already
2084 * returned to the caller.
2085 */
2087 avail = msgLength - 4 - conn->copy_already_done;
2088 if (avail <= bufsize)
2089 {
2090 /* Able to consume the whole message */
2091 memcpy(buffer, &conn->inBuffer[conn->inCursor], avail);
2092 /* Mark message consumed */
2093 conn->inStart = conn->inCursor + avail;
2094 /* Reset state for next time */
2096 return avail;
2097 }
2098 else
2099 {
2100 /* We must return a partial message */
2101 memcpy(buffer, &conn->inBuffer[conn->inCursor], bufsize);
2102 /* The message is NOT consumed from libpq's buffer */
2104 return bufsize;
2105 }
2106}
2107
2108/*
2109 * PQendcopy
2110 *
2111 * See fe-exec.c for documentation.
2112 */
2113int
2115{
2117
2121 {
2122 libpq_append_conn_error(conn, "no COPY in progress");
2123 return 1;
2124 }
2125
2126 /* Send the CopyDone message if needed */
2129 {
2130 if (pqPutMsgStart(PqMsg_CopyDone, conn) < 0 ||
2131 pqPutMsgEnd(conn) < 0)
2132 return 1;
2133
2134 /*
2135 * If we sent the COPY command in extended-query mode, we must issue a
2136 * Sync as well.
2137 */
2138 if (conn->cmd_queue_head &&
2140 {
2141 if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
2142 pqPutMsgEnd(conn) < 0)
2143 return 1;
2144 }
2145 }
2146
2147 /*
2148 * make sure no data is waiting to be sent, abort if we are non-blocking
2149 * and the flush fails
2150 */
2152 return 1;
2153
2154 /* Return to active duty */
2156
2157 /*
2158 * Non blocking connections may have to abort at this point. If everyone
2159 * played the game there should be no problem, but in error scenarios the
2160 * expected messages may not have arrived yet. (We are assuming that the
2161 * backend's packetizing will ensure that CommandComplete arrives along
2162 * with the CopyDone; are there corner cases where that doesn't happen?)
2163 */
2165 return 1;
2166
2167 /* Wait for the completion response */
2169
2170 /* Expecting a successful result */
2171 if (result && result->resultStatus == PGRES_COMMAND_OK)
2172 {
2173 PQclear(result);
2174 return 0;
2175 }
2176
2177 /*
2178 * Trouble. For backwards-compatibility reasons, we issue the error
2179 * message as if it were a notice (would be nice to get rid of this
2180 * silliness, but too many apps probably don't handle errors from
2181 * PQendcopy reasonably). Note that the app can still obtain the error
2182 * status from the PGconn object.
2183 */
2184 if (conn->errorMessage.len > 0)
2185 {
2186 /* We have to strip the trailing newline ... pain in neck... */
2188
2189 if (svLast == '\n')
2190 conn->errorMessage.data[conn->errorMessage.len - 1] = '\0';
2193 }
2194
2195 PQclear(result);
2196
2197 return 1;
2198}
2199
2200
2201/*
2202 * PQfn - Send a function call to the POSTGRES backend.
2203 *
2204 * See fe-exec.c for documentation.
2205 */
2206PGresult *
2208 int *result_buf, int buf_size, int *actual_result_len,
2209 int result_is_int,
2210 const PQArgBlock *args, int nargs)
2211{
2212 bool needInput = false;
2214 char id;
2215 int msgLength;
2216 int avail;
2217 int i;
2218
2219 /* already validated by PQfn */
2221
2222 /* PQfn already validated connection state */
2223
2225 pqPutInt(fnid, 4, conn) < 0 || /* function id */
2226 pqPutInt(1, 2, conn) < 0 || /* # of format codes */
2227 pqPutInt(1, 2, conn) < 0 || /* format code: BINARY */
2228 pqPutInt(nargs, 2, conn) < 0) /* # of args */
2229 {
2230 /* error message should be set up already */
2231 return NULL;
2232 }
2233
2234 for (i = 0; i < nargs; ++i)
2235 { /* len.int4 + contents */
2236 if (pqPutInt(args[i].len, 4, conn))
2237 return NULL;
2238 if (args[i].len == -1)
2239 continue; /* it's NULL */
2240
2241 if (args[i].isint)
2242 {
2243 if (pqPutInt(args[i].u.integer, args[i].len, conn))
2244 return NULL;
2245 }
2246 else
2247 {
2248 if (pqPutnchar(args[i].u.ptr, args[i].len, conn))
2249 return NULL;
2250 }
2251 }
2252
2253 if (pqPutInt(1, 2, conn) < 0) /* result format code: BINARY */
2254 return NULL;
2255
2256 if (pqPutMsgEnd(conn) < 0 ||
2257 pqFlush(conn))
2258 return NULL;
2259
2260 for (;;)
2261 {
2262 if (needInput)
2263 {
2264 /* Wait for some data to arrive (or for the channel to close) */
2265 if (pqWait(true, false, conn) ||
2266 pqReadData(conn) < 0)
2267 break;
2268 }
2269
2270 /*
2271 * Scan the message. If we run out of data, loop around to try again.
2272 */
2273 needInput = true;
2274
2276 if (pqGetc(&id, conn))
2277 continue;
2278 if (pqGetInt(&msgLength, 4, conn))
2279 continue;
2280
2281 /*
2282 * Try to validate message type/length here. A length less than 4 is
2283 * definitely broken. Large lengths should only be believed for a few
2284 * message types.
2285 */
2286 if (msgLength < 4)
2287 {
2289 break;
2290 }
2291 if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
2292 {
2294 break;
2295 }
2296
2297 /*
2298 * Can't process if message body isn't all here yet.
2299 */
2300 msgLength -= 4;
2301 avail = conn->inEnd - conn->inCursor;
2302 if (avail < msgLength)
2303 {
2304 /*
2305 * Before looping, enlarge the input buffer if needed to hold the
2306 * whole message. See notes in parseInput.
2307 */
2309 conn))
2310 {
2311 /*
2312 * Abandon the connection. There's not much else we can
2313 * safely do; we can't just ignore the message or we could
2314 * miss important changes to the connection state.
2315 * pqCheckInBufferSpace() already reported the error.
2316 */
2318 break;
2319 }
2320 continue;
2321 }
2322
2323 /*
2324 * We should see V or E response to the command, but might get N
2325 * and/or A notices first. We also need to swallow the final Z before
2326 * returning.
2327 */
2328 switch (id)
2329 {
2332 continue;
2333 if (*actual_result_len != -1)
2334 {
2335 if (result_is_int)
2336 {
2338 continue;
2339 }
2340 else
2341 {
2342 /*
2343 * If the server returned too much data for the
2344 * buffer, something fishy is going on. Abandon ship.
2345 */
2346 if (buf_size != -1 && *actual_result_len > buf_size)
2347 {
2348 libpq_append_conn_error(conn, "server returned too much data");
2350 return pqPrepareAsyncResult(conn);
2351 }
2352
2355 conn))
2356 continue;
2357 }
2358 }
2359 /* correctly finished function result message */
2360 status = PGRES_COMMAND_OK;
2361 break;
2363 if (pqGetErrorNotice3(conn, true))
2364 continue;
2365 status = PGRES_FATAL_ERROR;
2366 break;
2368 /* handle notify and go back to processing return values */
2369 if (getNotify(conn))
2370 continue;
2371 break;
2373 /* handle notice and go back to processing return values */
2374 if (pqGetErrorNotice3(conn, false))
2375 continue;
2376 break;
2379 continue;
2380
2381 /* consume the message */
2383
2384 /*
2385 * If we already have a result object (probably an error), use
2386 * that. Otherwise, if we saw a function result message,
2387 * report COMMAND_OK. Otherwise, the backend violated the
2388 * protocol, so complain.
2389 */
2391 {
2392 if (status == PGRES_COMMAND_OK)
2393 {
2394 conn->result = PQmakeEmptyPGresult(conn, status);
2395 if (!conn->result)
2396 {
2397 libpq_append_conn_error(conn, "out of memory");
2399 }
2400 }
2401 else
2402 {
2403 libpq_append_conn_error(conn, "protocol error: no function result");
2405 }
2406 }
2407 /* and we're out */
2408 return pqPrepareAsyncResult(conn);
2411 continue;
2412 break;
2413 default:
2414 /* The backend violates the protocol. */
2415 libpq_append_conn_error(conn, "protocol error: id=0x%x", id);
2417
2418 /*
2419 * We can't call parsing done due to the protocol violation
2420 * (so message tracing wouldn't work), but trust the specified
2421 * message length as what to skip.
2422 */
2423 conn->inStart += 5 + msgLength;
2424 return pqPrepareAsyncResult(conn);
2425 }
2426
2427 /* Completed parsing this message, keep going */
2429 needInput = false;
2430 }
2431
2432 /*
2433 * We fall out of the loop only upon failing to read data.
2434 * conn->errorMessage has been set by pqWait or pqReadData. We want to
2435 * append it to any already-received error message.
2436 */
2438 return pqPrepareAsyncResult(conn);
2439}
2440
2441
2442/*
2443 * Construct startup packet
2444 *
2445 * Returns a malloc'd packet buffer, or NULL if out of memory
2446 */
2447char *
2450{
2451 char *startpacket;
2452 size_t len;
2453
2455 if (len == 0 || len > INT_MAX)
2456 return NULL;
2457
2458 *packetlen = len;
2459 startpacket = (char *) malloc(*packetlen);
2460 if (!startpacket)
2461 return NULL;
2462
2464 Assert(*packetlen == len);
2465
2466 return startpacket;
2467}
2468
2469/*
2470 * Build a startup packet given a filled-in PGconn structure.
2471 *
2472 * We need to figure out how much space is needed, then fill it in.
2473 * To avoid duplicate logic, this routine is called twice: the first time
2474 * (with packet == NULL) just counts the space needed, the second time
2475 * (with packet == allocated space) fills it in. Return value is the number
2476 * of bytes used, or zero in the unlikely event of size_t overflow.
2477 */
2478static size_t
2481{
2482 size_t packet_len = 0;
2484 const char *val;
2485
2486 /* Protocol version comes first. */
2487 if (packet)
2488 {
2490
2492 }
2493 packet_len += sizeof(ProtocolVersion);
2494
2495 /* Add user name, database name, options */
2496
2497#define ADD_STARTUP_OPTION(optname, optval) \
2498 do { \
2499 if (packet) \
2500 strcpy(packet + packet_len, optname); \
2501 if (pg_add_size_overflow(packet_len, strlen(optname) + 1, &packet_len)) \
2502 return 0; \
2503 if (packet) \
2504 strcpy(packet + packet_len, optval); \
2505 if (pg_add_size_overflow(packet_len, strlen(optval) + 1, &packet_len)) \
2506 return 0; \
2507 } while(0)
2508
2509 if (conn->pguser && conn->pguser[0])
2510 ADD_STARTUP_OPTION("user", conn->pguser);
2511 if (conn->dbName && conn->dbName[0])
2512 ADD_STARTUP_OPTION("database", conn->dbName);
2513 if (conn->replication && conn->replication[0])
2514 ADD_STARTUP_OPTION("replication", conn->replication);
2515 if (conn->pgoptions && conn->pgoptions[0])
2516 ADD_STARTUP_OPTION("options", conn->pgoptions);
2517 if (conn->send_appname)
2518 {
2519 /* Use appname if present, otherwise use fallback */
2521 if (val && val[0])
2522 ADD_STARTUP_OPTION("application_name", val);
2523 }
2524
2526 ADD_STARTUP_OPTION("client_encoding", conn->client_encoding_initial);
2527
2528 /*
2529 * Add the test_protocol_negotiation option when greasing, to test that
2530 * servers properly report unsupported protocol options in addition to
2531 * unsupported minor versions.
2532 */
2534 ADD_STARTUP_OPTION("_pq_.test_protocol_negotiation", "");
2535
2536 /* Add any environment-driven GUC settings needed */
2537 for (next_eo = options; next_eo->envName; next_eo++)
2538 {
2539 if ((val = getenv(next_eo->envName)) != NULL)
2540 {
2541 if (pg_strcasecmp(val, "default") != 0)
2542 ADD_STARTUP_OPTION(next_eo->pgName, val);
2543 }
2544 }
2545
2546 /* Add trailing terminator */
2547 if (packet)
2548 packet[packet_len] = '\0';
2550 return 0;
2551
2552 return packet_len;
2553}
#define Assert(condition)
Definition c.h:943
int16_t int16
Definition c.h:619
#define MemSet(start, val, len)
Definition c.h:1107
uint32 result
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
void pqDropConnection(PGconn *conn, bool flushInput)
Definition fe-connect.c:537
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:3173
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
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition fe-misc.c:1404
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)
#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)
PGresult * pqFunctionCall3(PGconn *conn, Oid fnid, int *result_buf, int buf_size, int *actual_result_len, int result_is_int, const PQArgBlock *args, int nargs)
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:91
ExecStatusType
Definition libpq-fe.h:129
@ PGRES_COPY_IN
Definition libpq-fe.h:138
@ PGRES_COPY_BOTH
Definition libpq-fe.h:143
@ PGRES_COMMAND_OK
Definition libpq-fe.h:131
@ PGRES_TUPLES_CHUNK
Definition libpq-fe.h:148
@ PGRES_FATAL_ERROR
Definition libpq-fe.h:142
@ PGRES_COPY_OUT
Definition libpq-fe.h:137
@ PGRES_EMPTY_QUERY
Definition libpq-fe.h:130
@ PGRES_PIPELINE_SYNC
Definition libpq-fe.h:145
@ PGRES_NONFATAL_ERROR
Definition libpq-fe.h:141
@ PGRES_TUPLES_OK
Definition libpq-fe.h:134
PGContextVisibility
Definition libpq-fe.h:169
@ PQSHOW_CONTEXT_ALWAYS
Definition libpq-fe.h:172
@ PQSHOW_CONTEXT_ERRORS
Definition libpq-fe.h:171
@ PQTRANS_INTRANS
Definition libpq-fe.h:155
@ PQTRANS_IDLE
Definition libpq-fe.h:153
@ PQTRANS_UNKNOWN
Definition libpq-fe.h:157
@ PQTRANS_INERROR
Definition libpq-fe.h:156
@ PQ_PIPELINE_OFF
Definition libpq-fe.h:193
@ PQ_PIPELINE_ABORTED
Definition libpq-fe.h:195
@ PQ_PIPELINE_ON
Definition libpq-fe.h:194
PGVerbosity
Definition libpq-fe.h:161
@ PQERRORS_VERBOSE
Definition libpq-fe.h:164
@ PQERRORS_TERSE
Definition libpq-fe.h:162
@ PQERRORS_SQLSTATE
Definition libpq-fe.h:165
@ PGASYNC_COPY_OUT
Definition libpq-int.h:224
@ PGASYNC_READY
Definition libpq-int.h:218
@ PGASYNC_COPY_BOTH
Definition libpq-int.h:225
@ PGASYNC_IDLE
Definition libpq-int.h:216
@ PGASYNC_COPY_IN
Definition libpq-int.h:223
@ PGASYNC_BUSY
Definition libpq-int.h:217
@ PGQUERY_SIMPLE
Definition libpq-int.h:322
@ PGQUERY_DESCRIBE
Definition libpq-int.h:325
@ PGQUERY_CLOSE
Definition libpq-int.h:327
@ PGQUERY_PREPARE
Definition libpq-int.h:324
#define CMDSTATUS_LEN
Definition libpq-int.h:83
#define pqIsnonblocking(conn)
Definition libpq-int.h:947
#define pgHavePendingResult(conn)
Definition libpq-int.h:940
#define libpq_gettext(x)
Definition oauth-utils.h:44
static char * errmsg
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_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:150
void * noticeRecArg
Definition libpq-int.h:151
PGQueryClass queryclass
Definition libpq-int.h:347
struct pgNotify * next
Definition libpq-fe.h:247
uint8 * be_cancel_key
Definition libpq-int.h:557
char * replication
Definition libpq-int.h:393
PGnotify * notifyHead
Definition libpq-int.h:479
PGdataValue * rowBuf
Definition libpq-int.h:596
pgsocket sock
Definition libpq-int.h:502
char * inBuffer
Definition libpq-int.h:579
ProtocolVersion pversion
Definition libpq-int.h:506
char * pgoptions
Definition libpq-int.h:389
bool send_appname
Definition libpq-int.h:546
PGTransactionStatusType xactStatus
Definition libpq-int.h:467
int inCursor
Definition libpq-int.h:582
int be_pid
Definition libpq-int.h:555
ProtocolVersion min_pversion
Definition libpq-int.h:551
char * dbName
Definition libpq-int.h:392
int inEnd
Definition libpq-int.h:583
char * fbappname
Definition libpq-int.h:391
PGnotify * notifyTail
Definition libpq-int.h:480
int copy_already_done
Definition libpq-int.h:478
PQExpBufferData workBuffer
Definition libpq-int.h:690
int inStart
Definition libpq-int.h:581
char * pguser
Definition libpq-int.h:397
PGresult * result
Definition libpq-int.h:609
PGVerbosity verbosity
Definition libpq-int.h:563
char * client_encoding_initial
Definition libpq-int.h:388
char * appname
Definition libpq-int.h:390
PQExpBufferData errorMessage
Definition libpq-int.h:686
bool error_result
Definition libpq-int.h:610
ProtocolVersion max_pversion
Definition libpq-int.h:552
int rowBufLen
Definition libpq-int.h:597
char last_sqlstate[6]
Definition libpq-int.h:468
PGAsyncStatusType asyncStatus
Definition libpq-int.h:466
PGpipelineStatus pipelineStatus
Definition libpq-int.h:472
char copy_is_binary
Definition libpq-int.h:477
PGNoticeHooks noticeHooks
Definition libpq-int.h:457
PGcmdQueueEntry * cmd_queue_head
Definition libpq-int.h:492
int be_cancel_key_len
Definition libpq-int.h:556
PGContextVisibility show_context
Definition libpq-int.h:564
ConnStatusType status
Definition libpq-int.h:465
PGNoticeHooks noticeHooks
Definition libpq-int.h:184
char * errMsg
Definition libpq-int.h:194
int numAttributes
Definition libpq-int.h:168
char cmdStatus[CMDSTATUS_LEN]
Definition libpq-int.h:176
PGMessageField * errFields
Definition libpq-int.h:195
ExecStatusType resultStatus
Definition libpq-int.h:175
char * errQuery
Definition libpq-int.h:196
int client_encoding
Definition libpq-int.h:187
int pg_encoding_dsplen(int encoding, const char *mbstr)
Definition wchar.c:1976
int pg_encoding_max_length(int encoding)
Definition wchar.c:2013

Function Documentation

◆ build_startup_packet()

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

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

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

References ADD_STARTUP_OPTION, pg_conn::appname, pg_conn::client_encoding_initial, conn, pg_conn::dbName, fb(), pg_conn::fbappname, memcpy(), 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 778 of file fe-protocol3.c.

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

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, result, 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 1622 of file fe-protocol3.c.

1623{
1624 int cancel_key_len;
1625
1626 if (conn->be_cancel_key)
1627 {
1631 }
1632
1633 if (pqGetInt(&(conn->be_pid), 4, conn))
1634 return EOF;
1635
1637
1638 if (cancel_key_len != 4 && conn->pversion == PG_PROTOCOL(3, 0))
1639 {
1640 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);
1642 return 0;
1643 }
1644
1645 if (cancel_key_len < 4)
1646 {
1647 libpq_append_conn_error(conn, "received invalid BackendKeyData message: cancel key with length %d is too short (minimum 4 bytes)", cancel_key_len);
1649 return 0;
1650 }
1651
1652 if (cancel_key_len > 256)
1653 {
1654 libpq_append_conn_error(conn, "received invalid BackendKeyData message: cancel key with length %d is too long (maximum 256 bytes)", cancel_key_len);
1656 return 0;
1657 }
1658
1660 if (conn->be_cancel_key == NULL)
1661 {
1662 libpq_append_conn_error(conn, "out of memory");
1664 return 0;
1665 }
1667 {
1670 return EOF;
1671 }
1673 return 0;
1674}

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 1845 of file fe-protocol3.c.

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

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 1757 of file fe-protocol3.c.

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

References conn, pg_conn::copy_is_binary, fb(), format, i, MemSet, PQclear, pqGetc(), pqGetInt(), PQmakeEmptyPGresult(), pqResultAlloc(), result, and pg_conn::result.

Referenced by pqParseInput3().

◆ getNotify()

static int getNotify ( PGconn conn)
static

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

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

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 690 of file fe-protocol3.c.

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

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

Referenced by pqParseInput3().

◆ getParameterStatus()

static int getParameterStatus ( PGconn conn)
static

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

1592{
1594
1595 /* Get the parameter name */
1596 if (pqGets(&conn->workBuffer, conn))
1597 return EOF;
1598 /* Get the parameter value (could be large) */
1600 if (pqGets(&valueBuf, conn))
1601 {
1603 return EOF;
1604 }
1605 /* And save it */
1607 {
1608 libpq_append_conn_error(conn, "out of memory");
1610 }
1612 return 0;
1613}

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 1813 of file fe-protocol3.c.

1814{
1815 char xact_status;
1816
1817 if (pqGetc(&xact_status, conn))
1818 return EOF;
1819 switch (xact_status)
1820 {
1821 case 'I':
1823 break;
1824 case 'T':
1826 break;
1827 case 'E':
1829 break;
1830 default:
1832 break;
1833 }
1834
1835 return 0;
1836}

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 519 of file fe-protocol3.c.

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

References appendPQExpBuffer(), pg_conn::asyncStatus, pg_conn::cmd_queue_head, conn, PQExpBufferData::data, errmsg, pg_conn::errorMessage, fb(), format, i, pg_conn::inCursor, pg_conn::inStart, libpq_gettext, MemSet, PGASYNC_READY, PGQUERY_DESCRIBE, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear, pqClearAsyncResult(), pqGetInt(), pqGets(), PQmakeEmptyPGresult(), pqResultAlloc(), pqResultStrdup(), pqSaveErrorResult(), PGcmdQueueEntry::queryclass, result, pg_conn::result, and pg_conn::workBuffer.

Referenced by pqParseInput3().

◆ handleFatalError()

static void handleFatalError ( PGconn conn)
static

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

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

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 504 of file fe-protocol3.c.

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

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 1031 of file fe-protocol3.c.

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

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 2449 of file fe-protocol3.c.

2451{
2452 char *startpacket;
2453 size_t len;
2454
2456 if (len == 0 || len > INT_MAX)
2457 return NULL;
2458
2459 *packetlen = len;
2460 startpacket = (char *) malloc(*packetlen);
2461 if (!startpacket)
2462 return NULL;
2463
2465 Assert(*packetlen == len);
2466
2467 return startpacket;
2468}

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

Referenced by PQconnectPoll().

◆ pqEndcopy3()

int pqEndcopy3 ( PGconn conn)

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

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

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 result.

Referenced by PQendcopy().

◆ pqFunctionCall3()

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

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

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

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 PQnfn().

◆ pqGetCopyData3()

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

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

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

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

Referenced by PQgetCopyData().

◆ pqGetErrorNotice3()

int pqGetErrorNotice3 ( PGconn conn,
bool  isError 
)

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

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

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 2009 of file fe-protocol3.c.

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

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 2060 of file fe-protocol3.c.

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

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

Referenced by PQgetlineAsync().

◆ pqGetNegotiateProtocolVersion3()

int pqGetNegotiateProtocolVersion3 ( PGconn conn)

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

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

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 71 of file fe-protocol3.c.

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

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 1202 of file fe-protocol3.c.

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

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