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