Debian Codegraph @

src/interfaces/libpq/fe-protocol3.c

raw
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 "common/int.h"
29 #include "libpq-fe.h"
30 #include "libpq-int.h"
31 #include "mb/pg_wchar.h"
32 #include "port/pg_bswap.h"
33
34 /*
35 * This macro lists the backend message types that could be "long" (more
36 * than a couple of kilobytes).
37 */
38 #define VALID_LONG_MESSAGE_TYPE(id) \
39 ((id) == PqMsg_CopyData || \
40 (id) == PqMsg_DataRow || \
41 (id) == PqMsg_ErrorResponse || \
42 (id) == PqMsg_FunctionCallResponse || \
43 (id) == PqMsg_NoticeResponse || \
44 (id) == PqMsg_NotificationResponse || \
45 (id) == PqMsg_RowDescription || \
46 (id) == PqMsg_ParameterDescription)
47
48
49 static void handleFatalError(PGconn *conn);
50 static void handleSyncLoss(PGconn *conn, char id, int msgLength);
51 static int getRowDescriptions(PGconn *conn, int msgLength);
52 static int getParamDescriptions(PGconn *conn, int msgLength);
53 static int getAnotherTuple(PGconn *conn, int msgLength);
54 static int getParameterStatus(PGconn *conn);
55 static int getBackendKeyData(PGconn *conn, int msgLength);
56 static int getNotify(PGconn *conn);
57 static int getCopyStart(PGconn *conn, ExecStatusType copytype);
58 static int getReadyForQuery(PGconn *conn);
59 static void reportErrorPosition(PQExpBuffer msg, const char *query,
60 int loc, int encoding);
61 static size_t build_startup_packet(const PGconn *conn, char *packet,
62 const PQEnvironmentOption *options);
63
64
65 /*
66 * parseInput: if appropriate, parse input data from backend
67 * until input is exhausted or a stopping state is reached.
68 * Note that this function will NOT attempt to read more data from the backend.
69 */
70 void
71 pqParseInput3(PGconn *conn)
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 */
86 conn->inCursor = conn->inStart;
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 {
99 handleSyncLoss(conn, id, msgLength);
100 return;
101 }
102 if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
103 {
104 handleSyncLoss(conn, id, msgLength);
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 */
123 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
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 */
132 handleFatalError(conn);
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 */
153 if (id == PqMsg_NotificationResponse)
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 ... */
166 if (conn->asyncStatus != PGASYNC_IDLE)
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 {
185 if (getParameterStatus(conn))
186 return;
187 }
188 else
189 {
190 /* Any other case is unexpected and we summarily skip it */
191 pqInternalNotice(&conn->noticeHooks,
192 "message type 0x%02x arrived from server while idle",
193 id);
194 /* Discard the unexpected message */
195 conn->inCursor += msgLength;
196 }
197 }
198 else
199 {
200 /*
201 * In BUSY state, we can process everything.
202 */
203 switch (id)
204 {
205 case PqMsg_CommandComplete:
206 if (pqGets(&conn->workBuffer, conn))
207 return;
208 if (!pgHavePendingResult(conn))
209 {
210 conn->result = PQmakeEmptyPGresult(conn,
211 PGRES_COMMAND_OK);
212 if (!conn->result)
213 {
214 libpq_append_conn_error(conn, "out of memory");
215 pqSaveErrorResult(conn);
216 }
217 }
218 if (conn->result)
219 strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
220 CMDSTATUS_LEN);
221 conn->asyncStatus = PGASYNC_READY;
222 break;
223 case PqMsg_ErrorResponse:
224 if (pqGetErrorNotice3(conn, true))
225 return;
226 conn->asyncStatus = PGASYNC_READY;
227 break;
228 case PqMsg_ReadyForQuery:
229 if (getReadyForQuery(conn))
230 return;
231 if (conn->pipelineStatus != PQ_PIPELINE_OFF)
232 {
233 conn->result = PQmakeEmptyPGresult(conn,
234 PGRES_PIPELINE_SYNC);
235 if (!conn->result)
236 {
237 libpq_append_conn_error(conn, "out of memory");
238 pqSaveErrorResult(conn);
239 }
240 else
241 {
242 conn->pipelineStatus = PQ_PIPELINE_ON;
243 conn->asyncStatus = PGASYNC_READY;
244 }
245 }
246 else
247 {
248 /* Advance the command queue and set us idle */
249 pqCommandQueueAdvance(conn, true, false);
250 conn->asyncStatus = PGASYNC_IDLE;
251 }
252 break;
253 case PqMsg_EmptyQueryResponse:
254 if (!pgHavePendingResult(conn))
255 {
256 conn->result = PQmakeEmptyPGresult(conn,
257 PGRES_EMPTY_QUERY);
258 if (!conn->result)
259 {
260 libpq_append_conn_error(conn, "out of memory");
261 pqSaveErrorResult(conn);
262 }
263 }
264 conn->asyncStatus = PGASYNC_READY;
265 break;
266 case PqMsg_ParseComplete:
267 /* If we're doing PQprepare, we're done; else ignore */
268 if (conn->cmd_queue_head &&
269 conn->cmd_queue_head->queryclass == PGQUERY_PREPARE)
270 {
271 if (!pgHavePendingResult(conn))
272 {
273 conn->result = PQmakeEmptyPGresult(conn,
274 PGRES_COMMAND_OK);
275 if (!conn->result)
276 {
277 libpq_append_conn_error(conn, "out of memory");
278 pqSaveErrorResult(conn);
279 }
280 }
281 conn->asyncStatus = PGASYNC_READY;
282 }
283 break;
284 case PqMsg_BindComplete:
285 /* Nothing to do for this message type */
286 break;
287 case PqMsg_CloseComplete:
288 /* If we're doing PQsendClose, we're done; else ignore */
289 if (conn->cmd_queue_head &&
290 conn->cmd_queue_head->queryclass == PGQUERY_CLOSE)
291 {
292 if (!pgHavePendingResult(conn))
293 {
294 conn->result = PQmakeEmptyPGresult(conn,
295 PGRES_COMMAND_OK);
296 if (!conn->result)
297 {
298 libpq_append_conn_error(conn, "out of memory");
299 pqSaveErrorResult(conn);
300 }
301 }
302 conn->asyncStatus = PGASYNC_READY;
303 }
304 break;
305 case PqMsg_ParameterStatus:
306 if (getParameterStatus(conn))
307 return;
308 break;
309 case PqMsg_BackendKeyData:
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 */
316 if (getBackendKeyData(conn, msgLength))
317 return;
318 break;
319 case PqMsg_RowDescription:
320 if (conn->error_result ||
321 (conn->result != NULL &&
322 conn->result->resultStatus == PGRES_FATAL_ERROR))
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 */
328 conn->inCursor += msgLength;
329 }
330 else if (conn->result == NULL ||
331 (conn->cmd_queue_head &&
332 conn->cmd_queue_head->queryclass == PGQUERY_DESCRIBE))
333 {
334 /* First 'T' in a query sequence */
335 if (getRowDescriptions(conn, msgLength))
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 */
347 conn->asyncStatus = PGASYNC_READY;
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 &&
364 conn->cmd_queue_head->queryclass == PGQUERY_DESCRIBE)
365 {
366 if (!pgHavePendingResult(conn))
367 {
368 conn->result = PQmakeEmptyPGresult(conn,
369 PGRES_COMMAND_OK);
370 if (!conn->result)
371 {
372 libpq_append_conn_error(conn, "out of memory");
373 pqSaveErrorResult(conn);
374 }
375 }
376 conn->asyncStatus = PGASYNC_READY;
377 }
378 break;
379 case PqMsg_ParameterDescription:
380 if (getParamDescriptions(conn, msgLength))
381 return;
382 break;
383 case PqMsg_DataRow:
384 if (conn->result != NULL &&
385 (conn->result->resultStatus == PGRES_TUPLES_OK ||
386 conn->result->resultStatus == PGRES_TUPLES_CHUNK))
387 {
388 /* Read another tuple of a normal query response */
389 if (getAnotherTuple(conn, msgLength))
390 return;
391 }
392 else if (conn->error_result ||
393 (conn->result != NULL &&
394 conn->result->resultStatus == PGRES_FATAL_ERROR))
395 {
396 /*
397 * We've already choked for some reason. Just discard
398 * tuples till we get to the end of the query.
399 */
400 conn->inCursor += msgLength;
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)");
406 pqSaveErrorResult(conn);
407 /* Discard the unexpected message */
408 conn->inCursor += msgLength;
409 }
410 break;
411 case PqMsg_CopyInResponse:
412 if (getCopyStart(conn, PGRES_COPY_IN))
413 return;
414 conn->asyncStatus = PGASYNC_COPY_IN;
415 break;
416 case PqMsg_CopyOutResponse:
417 if (getCopyStart(conn, PGRES_COPY_OUT))
418 return;
419 conn->asyncStatus = PGASYNC_COPY_OUT;
420 conn->copy_already_done = 0;
421 break;
422 case PqMsg_CopyBothResponse:
423 if (getCopyStart(conn, PGRES_COPY_BOTH))
424 return;
425 conn->asyncStatus = PGASYNC_COPY_BOTH;
426 conn->copy_already_done = 0;
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 */
435 conn->inCursor += msgLength;
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 */
449 pqSaveErrorResult(conn);
450 /* not sure if we will see more, so go to ready state */
451 conn->asyncStatus = PGASYNC_READY;
452 /* Discard the unexpected message */
453 conn->inCursor += msgLength;
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 */
461 pqParseDone(conn, conn->inCursor);
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 */
473 pqSaveErrorResult(conn);
474 conn->asyncStatus = PGASYNC_READY;
475 /* trust the specified message length as what to skip */
476 conn->inStart += 5 + msgLength;
477 }
478 }
479 }
480
481 /*
482 * handleFatalError: clean up after a nonrecoverable error
483 *
484 * This is for errors where we need to abandon the connection. The caller has
485 * already saved the error message in conn->errorMessage.
486 */
487 static void
488 handleFatalError(PGconn *conn)
489 {
490 /* build an error result holding the error message */
491 pqSaveErrorResult(conn);
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 }
497
498 /*
499 * handleSyncLoss: clean up after loss of message-boundary sync
500 *
501 * There isn't really a lot we can do here except abandon the connection.
502 */
503 static void
504 handleSyncLoss(PGconn *conn, char id, int msgLength)
505 {
506 libpq_append_conn_error(conn, "lost synchronization with server: got message type \"%c\", length %d",
507 id, msgLength);
508 handleFatalError(conn);
509 }
510
511 /*
512 * parseInput subroutine to read a 'T' (row descriptions) message.
513 * We'll build a new PGresult structure (unless called for a Describe
514 * command for a prepared statement) containing the attribute data.
515 * Returns: 0 if processed message successfully, EOF to suspend parsing
516 * (the latter case is not actually used currently).
517 */
518 static int
519 getRowDescriptions(PGconn *conn, int msgLength)
520 {
521 PGresult *result;
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 ||
532 (conn->cmd_queue_head &&
533 conn->cmd_queue_head->queryclass == PGQUERY_DESCRIBE))
534 {
535 if (conn->result)
536 result = conn->result;
537 else
538 result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
539 }
540 else
541 result = PQmakeEmptyPGresult(conn, PGRES_TUPLES_OK);
542 if (!result)
543 {
544 errmsg = NULL; /* means "out of memory", see below */
545 goto advance_and_error;
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");
554 goto advance_and_error;
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 */
566 goto advance_and_error;
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");
594 goto advance_and_error;
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,
606 conn->workBuffer.data);
607 if (!result->attDescs[i].name)
608 {
609 errmsg = NULL; /* means "out of memory", see below */
610 goto advance_and_error;
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) ||
631 (conn->cmd_queue_head &&
632 conn->cmd_queue_head->queryclass == PGQUERY_DESCRIBE))
633 {
634 conn->asyncStatus = PGASYNC_READY;
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
646 advance_and_error:
647 /* Discard unsaved result, if any */
648 if (result && result != conn->result)
649 PQclear(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 */
655 pqClearAsyncResult(conn);
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
666 appendPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
667 pqSaveErrorResult(conn);
668
669 /*
670 * Show the message as fully consumed, else pqParseInput3 will overwrite
671 * our error with a complaint about that.
672 */
673 conn->inCursor = conn->inStart + 5 + msgLength;
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 }
682
683 /*
684 * parseInput subroutine to read a 't' (ParameterDescription) message.
685 * We'll build a new PGresult structure containing the parameter data.
686 * Returns: 0 if processed message successfully, EOF to suspend parsing
687 * (the latter case is not actually used currently).
688 */
689 static int
690 getParamDescriptions(PGconn *conn, int msgLength)
691 {
692 PGresult *result;
693 const char *errmsg = NULL; /* means "out of memory", see below */
694 int nparams;
695 int i;
696
697 result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
698 if (!result)
699 goto advance_and_error;
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)
713 goto advance_and_error;
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
732 not_enough_data:
733 errmsg = libpq_gettext("insufficient data in \"t\" message");
734
735 advance_and_error:
736 /* Discard unsaved result, if any */
737 if (result && result != conn->result)
738 PQclear(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 */
744 pqClearAsyncResult(conn);
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");
754 appendPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
755 pqSaveErrorResult(conn);
756
757 /*
758 * Show the message as fully consumed, else pqParseInput3 will overwrite
759 * our error with a complaint about that.
760 */
761 conn->inCursor = conn->inStart + 5 + msgLength;
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 }
770
771 /*
772 * parseInput subroutine to read a 'D' (row data) message.
773 * We fill rowbuf with column pointers and then call the row processor.
774 * Returns: 0 if processed message successfully, EOF to suspend parsing
775 * (the latter case is not actually used currently).
776 */
777 static int
778 getAnotherTuple(PGconn *conn, int msgLength)
779 {
780 PGresult *result = conn->result;
781 int nfields = result->numAttributes;
782 const char *errmsg;
783 PGdataValue *rowbuf;
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");
793 goto advance_and_error;
794 }
795
796 if (tupnfields != nfields)
797 {
798 errmsg = libpq_gettext("unexpected field count in \"D\" message");
799 goto advance_and_error;
800 }
801
802 /* Resize row buffer if needed */
803 rowbuf = conn->rowBuf;
804 if (nfields > conn->rowBufLen)
805 {
806 rowbuf = (PGdataValue *) realloc(rowbuf,
807 nfields * sizeof(PGdataValue));
808 if (!rowbuf)
809 {
810 errmsg = NULL; /* means "out of memory", see below */
811 goto advance_and_error;
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");
825 goto advance_and_error;
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");
843 goto advance_and_error;
844 }
845 }
846 }
847
848 /* Process the collected row */
849 errmsg = NULL;
850 if (pqRowProcessor(conn, &errmsg))
851 return 0; /* normal, successful exit */
852
853 /* pqRowProcessor failed, fall through to report it */
854
855 advance_and_error:
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 */
861 pqClearAsyncResult(conn);
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
872 appendPQExpBuffer(&conn->errorMessage, "%s\n", errmsg);
873 pqSaveErrorResult(conn);
874
875 /*
876 * Show the message as fully consumed, else pqParseInput3 will overwrite
877 * our error with a complaint about that.
878 */
879 conn->inCursor = conn->inStart + 5 + msgLength;
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 }
888
889
890 /*
891 * Attempt to read an Error or Notice response message.
892 * This is possible in several places, so we break it out as a subroutine.
893 *
894 * Entry: 'E' or 'N' message type and length have already been consumed.
895 * Exit: returns 0 if successfully consumed message.
896 * returns EOF if not enough data.
897 */
898 int
899 pqGetErrorNotice3(PGconn *conn, bool isError)
900 {
901 PGresult *res = NULL;
902 bool have_position = false;
903 PQExpBufferData workBuf;
904 char id;
905
906 /* If in pipeline mode, set error indicator for it */
907 if (isError && conn->pipelineStatus != PQ_PIPELINE_OFF)
908 conn->pipelineStatus = PQ_PIPELINE_ABORTED;
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)
916 pqClearAsyncResult(conn);
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 */
924 initPQExpBuffer(&workBuf);
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 */
935 res = PQmakeEmptyPGresult(conn, PGRES_EMPTY_QUERY);
936 if (res)
937 res->resultStatus = isError ? PGRES_FATAL_ERROR : PGRES_NONFATAL_ERROR;
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)
955 strlcpy(conn->last_sqlstate, workBuf.data,
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 */
966 if (have_position && res && conn->cmd_queue_head && conn->cmd_queue_head->query)
967 res->errQuery = pqResultStrdup(res, conn->cmd_queue_head->query);
968
969 /*
970 * Now build the "overall" error message for PQresultErrorMessage.
971 */
972 resetPQExpBuffer(&workBuf);
973 pqBuildErrorMessage3(&workBuf, res, conn->verbosity, conn->show_context);
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
992 if (PQExpBufferDataBroken(workBuf))
993 libpq_append_conn_error(conn, "out of memory");
994 else
995 appendPQExpBufferStr(&conn->errorMessage, workBuf.data);
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 */
1007 if (PQExpBufferDataBroken(workBuf))
1008 res->errMsg = libpq_gettext("out of memory\n");
1009 else
1010 res->errMsg = workBuf.data;
1011 if (res->noticeHooks.noticeRec != NULL)
1012 res->noticeHooks.noticeRec(res->noticeHooks.noticeRecArg, res);
1013 PQclear(res);
1014 }
1015 }
1016
1017 termPQExpBuffer(&workBuf);
1018 return 0;
1019
1020 fail:
1021 PQclear(res);
1022 termPQExpBuffer(&workBuf);
1023 return EOF;
1024 }
1025
1026 /*
1027 * Construct an error message from the fields in the given PGresult,
1028 * appending it to the contents of "msg".
1029 */
1030 void
1031 pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res,
1032 PGVerbosity verbosity, PGContextVisibility show_context)
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 */
1059 val = PQresultErrorField(res, PG_DIAG_SEVERITY);
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 */
1071 val = PQresultErrorField(res, PG_DIAG_SQLSTATE);
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 {
1082 val = PQresultErrorField(res, PG_DIAG_SQLSTATE);
1083 if (val)
1084 appendPQExpBuffer(msg, "%s: ", val);
1085 }
1086 val = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
1087 if (val)
1088 appendPQExpBufferStr(msg, val);
1089 val = PQresultErrorField(res, PG_DIAG_STATEMENT_POSITION);
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 {
1108 val = PQresultErrorField(res, PG_DIAG_INTERNAL_POSITION);
1109 if (val)
1110 {
1111 querytext = PQresultErrorField(res, PG_DIAG_INTERNAL_QUERY);
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)
1130 reportErrorPosition(msg, querytext, querypos,
1131 res->client_encoding);
1132 val = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
1133 if (val)
1134 appendPQExpBuffer(msg, libpq_gettext("DETAIL: %s\n"), val);
1135 val = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
1136 if (val)
1137 appendPQExpBuffer(msg, libpq_gettext("HINT: %s\n"), val);
1138 val = PQresultErrorField(res, PG_DIAG_INTERNAL_QUERY);
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 &&
1143 res->resultStatus == PGRES_FATAL_ERROR))
1144 {
1145 val = PQresultErrorField(res, PG_DIAG_CONTEXT);
1146 if (val)
1147 appendPQExpBuffer(msg, libpq_gettext("CONTEXT: %s\n"),
1148 val);
1149 }
1150 }
1151 if (verbosity == PQERRORS_VERBOSE)
1152 {
1153 val = PQresultErrorField(res, PG_DIAG_SCHEMA_NAME);
1154 if (val)
1155 appendPQExpBuffer(msg,
1156 libpq_gettext("SCHEMA NAME: %s\n"), val);
1157 val = PQresultErrorField(res, PG_DIAG_TABLE_NAME);
1158 if (val)
1159 appendPQExpBuffer(msg,
1160 libpq_gettext("TABLE NAME: %s\n"), val);
1161 val = PQresultErrorField(res, PG_DIAG_COLUMN_NAME);
1162 if (val)
1163 appendPQExpBuffer(msg,
1164 libpq_gettext("COLUMN NAME: %s\n"), val);
1165 val = PQresultErrorField(res, PG_DIAG_DATATYPE_NAME);
1166 if (val)
1167 appendPQExpBuffer(msg,
1168 libpq_gettext("DATATYPE NAME: %s\n"), val);
1169 val = PQresultErrorField(res, PG_DIAG_CONSTRAINT_NAME);
1170 if (val)
1171 appendPQExpBuffer(msg,
1172 libpq_gettext("CONSTRAINT NAME: %s\n"), val);
1173 }
1174 if (verbosity == PQERRORS_VERBOSE)
1175 {
1176 const char *valf;
1177 const char *vall;
1178
1179 valf = PQresultErrorField(res, PG_DIAG_SOURCE_FILE);
1180 vall = PQresultErrorField(res, PG_DIAG_SOURCE_LINE);
1181 val = PQresultErrorField(res, PG_DIAG_SOURCE_FUNCTION);
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 }
1194
1195 /*
1196 * Add an error-location display to the error message under construction.
1197 *
1198 * The cursor location is measured in logical characters; the query string
1199 * is presumed to be in the specified encoding.
1200 */
1201 static void
1202 reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding)
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 */
1271 mb_encoding = (pg_encoding_max_length(encoding) != 1);
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
1332 w = pg_encoding_dsplen(encoding, &wquery[qoffset]);
1333 /* treat any non-tab control chars as width 1 */
1334 if (w <= 0)
1335 w = 1;
1336 scroffset += w;
1337 qoffset += PQmblenBounded(&wquery[qoffset], encoding);
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;
1351 scridx[iend] = scroffset;
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;
1360 if (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
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. */
1415 appendPQExpBufferStr(msg, &wquery[qidx[ibeg]]);
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 }
1433
1434
1435 /*
1436 * Attempt to read a NegotiateProtocolVersion message. Sets conn->pversion
1437 * to the version that's negotiated by the server.
1438 *
1439 * Entry: 'v' message type and length have already been consumed.
1440 * Exit: returns 0 if successfully consumed message.
1441 * returns 1 on failure. The error message is filled in.
1442 */
1443 int
1444 pqGetNegotiateProtocolVersion3(PGconn *conn)
1445 {
1446 int their_version;
1447 int num;
1448
1449 if (pqGetInt(&their_version, 4, conn) != 0)
1450 goto eof;
1451
1452 if (pqGetInt(&num, 4, conn) != 0)
1453 goto eof;
1454
1455 /* Check the protocol version */
1456 if (their_version > conn->pversion)
1457 {
1458 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requested downgrade to a higher-numbered version");
1459 goto failure;
1460 }
1461
1462 if (their_version < PG_PROTOCOL(3, 0))
1463 {
1464 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requested downgrade to pre-3.0 protocol version");
1465 goto failure;
1466 }
1467
1468 /* 3.1 never existed, we went straight from 3.0 to 3.2 */
1469 if (their_version == PG_PROTOCOL(3, 1))
1470 {
1471 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requested downgrade to non-existent 3.1 protocol version");
1472 goto failure;
1473 }
1474
1475 if (num < 0)
1476 {
1477 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported negative number of unsupported parameters");
1478 goto failure;
1479 }
1480
1481 if (their_version == conn->pversion && num == 0)
1482 {
1483 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server negotiated but asks for no changes");
1484 goto failure;
1485 }
1486
1487 if (their_version < conn->min_pversion)
1488 {
1489 libpq_append_conn_error(conn, "server only supports protocol version %d.%d, but \"%s\" was set to %d.%d",
1490 PG_PROTOCOL_MAJOR(their_version),
1491 PG_PROTOCOL_MINOR(their_version),
1492 "min_protocol_version",
1493 PG_PROTOCOL_MAJOR(conn->min_pversion),
1494 PG_PROTOCOL_MINOR(conn->min_pversion));
1495
1496 goto failure;
1497 }
1498
1499 /* the version is acceptable */
1500 conn->pversion = their_version;
1501
1502 /*
1503 * We don't currently request any protocol extensions, so we don't expect
1504 * the server to reply with any either.
1505 */
1506 for (int i = 0; i < num; i++)
1507 {
1508 if (pqGets(&conn->workBuffer, conn))
1509 {
1510 goto eof;
1511 }
1512 if (strncmp(conn->workBuffer.data, "_pq_.", 5) != 0)
1513 {
1514 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported unsupported parameter name without a \"%s\" prefix (\"%s\")", "_pq_.", conn->workBuffer.data);
1515 goto failure;
1516 }
1517 libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported an unsupported parameter that was not requested (\"%s\")", conn->workBuffer.data);
1518 goto failure;
1519 }
1520
1521 return 0;
1522
1523 eof:
1524 libpq_append_conn_error(conn, "received invalid protocol negotiation message: message too short");
1525 failure:
1526 conn->asyncStatus = PGASYNC_READY;
1527 pqSaveErrorResult(conn);
1528 return 1;
1529 }
1530
1531
1532 /*
1533 * Attempt to read a ParameterStatus message.
1534 * This is possible in several places, so we break it out as a subroutine.
1535 *
1536 * Entry: 'S' message type and length have already been consumed.
1537 * Exit: returns 0 if successfully consumed message.
1538 * returns EOF if not enough data.
1539 */
1540 static int
1541 getParameterStatus(PGconn *conn)
1542 {
1543 PQExpBufferData valueBuf;
1544
1545 /* Get the parameter name */
1546 if (pqGets(&conn->workBuffer, conn))
1547 return EOF;
1548 /* Get the parameter value (could be large) */
1549 initPQExpBuffer(&valueBuf);
1550 if (pqGets(&valueBuf, conn))
1551 {
1552 termPQExpBuffer(&valueBuf);
1553 return EOF;
1554 }
1555 /* And save it */
1556 if (!pqSaveParameterStatus(conn, conn->workBuffer.data, valueBuf.data))
1557 {
1558 libpq_append_conn_error(conn, "out of memory");
1559 handleFatalError(conn);
1560 }
1561 termPQExpBuffer(&valueBuf);
1562 return 0;
1563 }
1564
1565 /*
1566 * parseInput subroutine to read a BackendKeyData message.
1567 * Entry: 'v' message type and length have already been consumed.
1568 * Exit: returns 0 if successfully consumed message.
1569 * returns EOF if not enough data.
1570 */
1571 static int
1572 getBackendKeyData(PGconn *conn, int msgLength)
1573 {
1574 int cancel_key_len;
1575
1576 if (conn->be_cancel_key)
1577 {
1578 free(conn->be_cancel_key);
1579 conn->be_cancel_key = NULL;
1580 conn->be_cancel_key_len = 0;
1581 }
1582
1583 if (pqGetInt(&(conn->be_pid), 4, conn))
1584 return EOF;
1585
1586 cancel_key_len = 5 + msgLength - (conn->inCursor - conn->inStart);
1587
1588 if (cancel_key_len != 4 && conn->pversion == PG_PROTOCOL(3, 0))
1589 {
1590 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);
1591 handleFatalError(conn);
1592 return 0;
1593 }
1594
1595 if (cancel_key_len < 4)
1596 {
1597 libpq_append_conn_error(conn, "received invalid BackendKeyData message: cancel key with length %d is too short (minimum 4 bytes)", cancel_key_len);
1598 handleFatalError(conn);
1599 return 0;
1600 }
1601
1602 if (cancel_key_len > 256)
1603 {
1604 libpq_append_conn_error(conn, "received invalid BackendKeyData message: cancel key with length %d is too long (maximum 256 bytes)", cancel_key_len);
1605 handleFatalError(conn);
1606 return 0;
1607 }
1608
1609 conn->be_cancel_key = malloc(cancel_key_len);
1610 if (conn->be_cancel_key == NULL)
1611 {
1612 libpq_append_conn_error(conn, "out of memory");
1613 handleFatalError(conn);
1614 return 0;
1615 }
1616 if (pqGetnchar(conn->be_cancel_key, cancel_key_len, conn))
1617 {
1618 free(conn->be_cancel_key);
1619 conn->be_cancel_key = NULL;
1620 return EOF;
1621 }
1622 conn->be_cancel_key_len = cancel_key_len;
1623 return 0;
1624 }
1625
1626
1627 /*
1628 * Attempt to read a Notify response message.
1629 * This is possible in several places, so we break it out as a subroutine.
1630 *
1631 * Entry: 'A' message type and length have already been consumed.
1632 * Exit: returns 0 if successfully consumed Notify message.
1633 * returns EOF if not enough data.
1634 */
1635 static int
1636 getNotify(PGconn *conn)
1637 {
1638 int be_pid;
1639 char *svname;
1640 int nmlen;
1641 int extralen;
1642 PGnotify *newNotify;
1643
1644 if (pqGetInt(&be_pid, 4, conn))
1645 return EOF;
1646 if (pqGets(&conn->workBuffer, conn))
1647 return EOF;
1648 /* must save name while getting extra string */
1649 svname = strdup(conn->workBuffer.data);
1650 if (!svname)
1651 {
1652 /*
1653 * Notify messages can arrive at any state, so we cannot associate the
1654 * error with any particular query. There's no way to return back an
1655 * "async error", so the best we can do is drop the connection. That
1656 * seems better than silently ignoring the notification.
1657 */
1658 libpq_append_conn_error(conn, "out of memory");
1659 handleFatalError(conn);
1660 return 0;
1661 }
1662 if (pqGets(&conn->workBuffer, conn))
1663 {
1664 free(svname);
1665 return EOF;
1666 }
1667
1668 /*
1669 * Store the strings right after the PGnotify structure so it can all be
1670 * freed at once. We don't use NAMEDATALEN because we don't want to tie
1671 * this interface to a specific server name length.
1672 */
1673 nmlen = strlen(svname);
1674 extralen = strlen(conn->workBuffer.data);
1675 newNotify = (PGnotify *) malloc(sizeof(PGnotify) + nmlen + extralen + 2);
1676 if (!newNotify)
1677 {
1678 free(svname);
1679 libpq_append_conn_error(conn, "out of memory");
1680 handleFatalError(conn);
1681 return 0;
1682 }
1683
1684 newNotify->relname = (char *) newNotify + sizeof(PGnotify);
1685 strcpy(newNotify->relname, svname);
1686 newNotify->extra = newNotify->relname + nmlen + 1;
1687 strcpy(newNotify->extra, conn->workBuffer.data);
1688 newNotify->be_pid = be_pid;
1689 newNotify->next = NULL;
1690 if (conn->notifyTail)
1691 conn->notifyTail->next = newNotify;
1692 else
1693 conn->notifyHead = newNotify;
1694 conn->notifyTail = newNotify;
1695
1696 free(svname);
1697 return 0;
1698 }
1699
1700 /*
1701 * getCopyStart - process CopyInResponse, CopyOutResponse or
1702 * CopyBothResponse message
1703 *
1704 * parseInput already read the message type and length.
1705 */
1706 static int
1707 getCopyStart(PGconn *conn, ExecStatusType copytype)
1708 {
1709 PGresult *result;
1710 int nfields;
1711 int i;
1712
1713 result = PQmakeEmptyPGresult(conn, copytype);
1714 if (!result)
1715 goto failure;
1716
1717 if (pqGetc(&conn->copy_is_binary, conn))
1718 goto failure;
1719 result->binary = conn->copy_is_binary;
1720 /* the next two bytes are the number of fields */
1721 if (pqGetInt(&(result->numAttributes), 2, conn))
1722 goto failure;
1723 nfields = result->numAttributes;
1724
1725 /* allocate space for the attribute descriptors */
1726 if (nfields > 0)
1727 {
1728 result->attDescs = (PGresAttDesc *)
1729 pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
1730 if (!result->attDescs)
1731 goto failure;
1732 MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
1733 }
1734
1735 for (i = 0; i < nfields; i++)
1736 {
1737 int format;
1738
1739 if (pqGetInt(&format, 2, conn))
1740 goto failure;
1741
1742 /*
1743 * Since pqGetInt treats 2-byte integers as unsigned, we need to
1744 * coerce these results to signed form.
1745 */
1746 format = (int) ((int16) format);
1747 result->attDescs[i].format = format;
1748 }
1749
1750 /* Success! */
1751 conn->result = result;
1752 return 0;
1753
1754 failure:
1755 PQclear(result);
1756 return EOF;
1757 }
1758
1759 /*
1760 * getReadyForQuery - process ReadyForQuery message
1761 */
1762 static int
1763 getReadyForQuery(PGconn *conn)
1764 {
1765 char xact_status;
1766
1767 if (pqGetc(&xact_status, conn))
1768 return EOF;
1769 switch (xact_status)
1770 {
1771 case 'I':
1772 conn->xactStatus = PQTRANS_IDLE;
1773 break;
1774 case 'T':
1775 conn->xactStatus = PQTRANS_INTRANS;
1776 break;
1777 case 'E':
1778 conn->xactStatus = PQTRANS_INERROR;
1779 break;
1780 default:
1781 conn->xactStatus = PQTRANS_UNKNOWN;
1782 break;
1783 }
1784
1785 return 0;
1786 }
1787
1788 /*
1789 * getCopyDataMessage - fetch next CopyData message, process async messages
1790 *
1791 * Returns length word of CopyData message (> 0), or 0 if no complete
1792 * message available, -1 if end of copy, -2 if error.
1793 */
1794 static int
1795 getCopyDataMessage(PGconn *conn)
1796 {
1797 char id;
1798 int msgLength;
1799 int avail;
1800
1801 for (;;)
1802 {
1803 /*
1804 * Do we have the next input message? To make life simpler for async
1805 * callers, we keep returning 0 until the next message is fully
1806 * available, even if it is not Copy Data.
1807 */
1808 conn->inCursor = conn->inStart;
1809 if (pqGetc(&id, conn))
1810 return 0;
1811 if (pqGetInt(&msgLength, 4, conn))
1812 return 0;
1813 if (msgLength < 4)
1814 {
1815 handleSyncLoss(conn, id, msgLength);
1816 return -2;
1817 }
1818 avail = conn->inEnd - conn->inCursor;
1819 if (avail < msgLength - 4)
1820 {
1821 /*
1822 * Before returning, enlarge the input buffer if needed to hold
1823 * the whole message. See notes in parseInput.
1824 */
1825 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength - 4,
1826 conn))
1827 {
1828 /*
1829 * Abandon the connection. There's not much else we can
1830 * safely do; we can't just ignore the message or we could
1831 * miss important changes to the connection state.
1832 * pqCheckInBufferSpace() already reported the error.
1833 */
1834 handleFatalError(conn);
1835 return -2;
1836 }
1837 return 0;
1838 }
1839
1840 /*
1841 * If it's a legitimate async message type, process it. (NOTIFY
1842 * messages are not currently possible here, but we handle them for
1843 * completeness.) Otherwise, if it's anything except Copy Data,
1844 * report end-of-copy.
1845 */
1846 switch (id)
1847 {
1848 case PqMsg_NotificationResponse:
1849 if (getNotify(conn))
1850 return 0;
1851 break;
1852 case PqMsg_NoticeResponse:
1853 if (pqGetErrorNotice3(conn, false))
1854 return 0;
1855 break;
1856 case PqMsg_ParameterStatus:
1857 if (getParameterStatus(conn))
1858 return 0;
1859 break;
1860 case PqMsg_CopyData:
1861 return msgLength;
1862 case PqMsg_CopyDone:
1863
1864 /*
1865 * If this is a CopyDone message, exit COPY_OUT mode and let
1866 * caller read status with PQgetResult(). If we're in
1867 * COPY_BOTH mode, return to COPY_IN mode.
1868 */
1869 if (conn->asyncStatus == PGASYNC_COPY_BOTH)
1870 conn->asyncStatus = PGASYNC_COPY_IN;
1871 else
1872 conn->asyncStatus = PGASYNC_BUSY;
1873 return -1;
1874 default: /* treat as end of copy */
1875
1876 /*
1877 * Any other message terminates either COPY_IN or COPY_BOTH
1878 * mode.
1879 */
1880 conn->asyncStatus = PGASYNC_BUSY;
1881 return -1;
1882 }
1883
1884 /*
1885 * An error may have been triggered while processing the message,
1886 * report it if it's the case
1887 */
1888 if (conn->error_result && conn->status == CONNECTION_BAD)
1889 return -2;
1890
1891 /* Drop the processed message and loop around for another */
1892 pqParseDone(conn, conn->inCursor);
1893 }
1894 }
1895
1896 /*
1897 * PQgetCopyData - read a row of data from the backend during COPY OUT
1898 * or COPY BOTH
1899 *
1900 * If successful, sets *buffer to point to a malloc'd row of data, and
1901 * returns row length (always > 0) as result.
1902 * Returns 0 if no row available yet (only possible if async is true),
1903 * -1 if end of copy (consult PQgetResult), or -2 if error (consult
1904 * PQerrorMessage).
1905 */
1906 int
1907 pqGetCopyData3(PGconn *conn, char **buffer, int async)
1908 {
1909 int msgLength;
1910
1911 for (;;)
1912 {
1913 /*
1914 * Collect the next input message. To make life simpler for async
1915 * callers, we keep returning 0 until the next message is fully
1916 * available, even if it is not Copy Data.
1917 */
1918 msgLength = getCopyDataMessage(conn);
1919 if (msgLength < 0)
1920 return msgLength; /* end-of-copy or error */
1921 if (msgLength == 0)
1922 {
1923 /* Don't block if async read requested */
1924 if (async)
1925 return 0;
1926 /* Need to load more data */
1927 if (pqWait(true, false, conn) ||
1928 pqReadData(conn) < 0)
1929 return -2;
1930 continue;
1931 }
1932
1933 /*
1934 * Drop zero-length messages (shouldn't happen anyway). Otherwise
1935 * pass the data back to the caller.
1936 */
1937 msgLength -= 4;
1938 if (msgLength > 0)
1939 {
1940 *buffer = (char *) malloc(msgLength + 1);
1941 if (*buffer == NULL)
1942 {
1943 libpq_append_conn_error(conn, "out of memory");
1944 return -2;
1945 }
1946 memcpy(*buffer, &conn->inBuffer[conn->inCursor], msgLength);
1947 (*buffer)[msgLength] = '\0'; /* Add terminating null */
1948
1949 /* Mark message consumed */
1950 pqParseDone(conn, conn->inCursor + msgLength);
1951
1952 return msgLength;
1953 }
1954
1955 /* Empty, so drop it and loop around for another */
1956 pqParseDone(conn, conn->inCursor);
1957 }
1958 }
1959
1960 /*
1961 * PQgetline - gets a newline-terminated string from the backend.
1962 *
1963 * See fe-exec.c for documentation.
1964 */
1965 int
1966 pqGetline3(PGconn *conn, char *s, int maxlen)
1967 {
1968 int status;
1969
1970 if (conn->sock == PGINVALID_SOCKET ||
1971 (conn->asyncStatus != PGASYNC_COPY_OUT &&
1972 conn->asyncStatus != PGASYNC_COPY_BOTH) ||
1973 conn->copy_is_binary)
1974 {
1975 libpq_append_conn_error(conn, "PQgetline: not doing text COPY OUT");
1976 *s = '\0';
1977 return EOF;
1978 }
1979
1980 while ((status = PQgetlineAsync(conn, s, maxlen - 1)) == 0)
1981 {
1982 /* need to load more data */
1983 if (pqWait(true, false, conn) ||
1984 pqReadData(conn) < 0)
1985 {
1986 *s = '\0';
1987 return EOF;
1988 }
1989 }
1990
1991 if (status < 0)
1992 {
1993 /* End of copy detected; gin up old-style terminator */
1994 strcpy(s, "\\.");
1995 return 0;
1996 }
1997
1998 /* Add null terminator, and strip trailing \n if present */
1999 if (s[status - 1] == '\n')
2000 {
2001 s[status - 1] = '\0';
2002 return 0;
2003 }
2004 else
2005 {
2006 s[status] = '\0';
2007 return 1;
2008 }
2009 }
2010
2011 /*
2012 * PQgetlineAsync - gets a COPY data row without blocking.
2013 *
2014 * See fe-exec.c for documentation.
2015 */
2016 int
2017 pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)
2018 {
2019 int msgLength;
2020 int avail;
2021
2022 if (conn->asyncStatus != PGASYNC_COPY_OUT
2023 && conn->asyncStatus != PGASYNC_COPY_BOTH)
2024 return -1; /* we are not doing a copy... */
2025
2026 /*
2027 * Recognize the next input message. To make life simpler for async
2028 * callers, we keep returning 0 until the next message is fully available
2029 * even if it is not Copy Data. This should keep PQendcopy from blocking.
2030 * (Note: unlike pqGetCopyData3, we do not change asyncStatus here.)
2031 */
2032 msgLength = getCopyDataMessage(conn);
2033 if (msgLength < 0)
2034 return -1; /* end-of-copy or error */
2035 if (msgLength == 0)
2036 return 0; /* no data yet */
2037
2038 /*
2039 * Move data from libpq's buffer to the caller's. In the case where a
2040 * prior call found the caller's buffer too small, we use
2041 * conn->copy_already_done to remember how much of the row was already
2042 * returned to the caller.
2043 */
2044 conn->inCursor += conn->copy_already_done;
2045 avail = msgLength - 4 - conn->copy_already_done;
2046 if (avail <= bufsize)
2047 {
2048 /* Able to consume the whole message */
2049 memcpy(buffer, &conn->inBuffer[conn->inCursor], avail);
2050 /* Mark message consumed */
2051 conn->inStart = conn->inCursor + avail;
2052 /* Reset state for next time */
2053 conn->copy_already_done = 0;
2054 return avail;
2055 }
2056 else
2057 {
2058 /* We must return a partial message */
2059 memcpy(buffer, &conn->inBuffer[conn->inCursor], bufsize);
2060 /* The message is NOT consumed from libpq's buffer */
2061 conn->copy_already_done += bufsize;
2062 return bufsize;
2063 }
2064 }
2065
2066 /*
2067 * PQendcopy
2068 *
2069 * See fe-exec.c for documentation.
2070 */
2071 int
2072 pqEndcopy3(PGconn *conn)
2073 {
2074 PGresult *result;
2075
2076 if (conn->asyncStatus != PGASYNC_COPY_IN &&
2077 conn->asyncStatus != PGASYNC_COPY_OUT &&
2078 conn->asyncStatus != PGASYNC_COPY_BOTH)
2079 {
2080 libpq_append_conn_error(conn, "no COPY in progress");
2081 return 1;
2082 }
2083
2084 /* Send the CopyDone message if needed */
2085 if (conn->asyncStatus == PGASYNC_COPY_IN ||
2086 conn->asyncStatus == PGASYNC_COPY_BOTH)
2087 {
2088 if (pqPutMsgStart(PqMsg_CopyDone, conn) < 0 ||
2089 pqPutMsgEnd(conn) < 0)
2090 return 1;
2091
2092 /*
2093 * If we sent the COPY command in extended-query mode, we must issue a
2094 * Sync as well.
2095 */
2096 if (conn->cmd_queue_head &&
2097 conn->cmd_queue_head->queryclass != PGQUERY_SIMPLE)
2098 {
2099 if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
2100 pqPutMsgEnd(conn) < 0)
2101 return 1;
2102 }
2103 }
2104
2105 /*
2106 * make sure no data is waiting to be sent, abort if we are non-blocking
2107 * and the flush fails
2108 */
2109 if (pqFlush(conn) && pqIsnonblocking(conn))
2110 return 1;
2111
2112 /* Return to active duty */
2113 conn->asyncStatus = PGASYNC_BUSY;
2114
2115 /*
2116 * Non blocking connections may have to abort at this point. If everyone
2117 * played the game there should be no problem, but in error scenarios the
2118 * expected messages may not have arrived yet. (We are assuming that the
2119 * backend's packetizing will ensure that CommandComplete arrives along
2120 * with the CopyDone; are there corner cases where that doesn't happen?)
2121 */
2122 if (pqIsnonblocking(conn) && PQisBusy(conn))
2123 return 1;
2124
2125 /* Wait for the completion response */
2126 result = PQgetResult(conn);
2127
2128 /* Expecting a successful result */
2129 if (result && result->resultStatus == PGRES_COMMAND_OK)
2130 {
2131 PQclear(result);
2132 return 0;
2133 }
2134
2135 /*
2136 * Trouble. For backwards-compatibility reasons, we issue the error
2137 * message as if it were a notice (would be nice to get rid of this
2138 * silliness, but too many apps probably don't handle errors from
2139 * PQendcopy reasonably). Note that the app can still obtain the error
2140 * status from the PGconn object.
2141 */
2142 if (conn->errorMessage.len > 0)
2143 {
2144 /* We have to strip the trailing newline ... pain in neck... */
2145 char svLast = conn->errorMessage.data[conn->errorMessage.len - 1];
2146
2147 if (svLast == '\n')
2148 conn->errorMessage.data[conn->errorMessage.len - 1] = '\0';
2149 pqInternalNotice(&conn->noticeHooks, "%s", conn->errorMessage.data);
2150 conn->errorMessage.data[conn->errorMessage.len - 1] = svLast;
2151 }
2152
2153 PQclear(result);
2154
2155 return 1;
2156 }
2157
2158
2159 /*
2160 * PQfn - Send a function call to the POSTGRES backend.
2161 *
2162 * See fe-exec.c for documentation.
2163 */
2164 PGresult *
2165 pqFunctionCall3(PGconn *conn, Oid fnid,
2166 int *result_buf, int buf_size, int *actual_result_len,
2167 int result_is_int,
2168 const PQArgBlock *args, int nargs)
2169 {
2170 bool needInput = false;
2171 ExecStatusType status = PGRES_FATAL_ERROR;
2172 char id;
2173 int msgLength;
2174 int avail;
2175 int i;
2176
2177 /* already validated by PQfn */
2178 Assert(conn->pipelineStatus == PQ_PIPELINE_OFF);
2179
2180 /* PQfn already validated connection state */
2181
2182 if (pqPutMsgStart(PqMsg_FunctionCall, conn) < 0 ||
2183 pqPutInt(fnid, 4, conn) < 0 || /* function id */
2184 pqPutInt(1, 2, conn) < 0 || /* # of format codes */
2185 pqPutInt(1, 2, conn) < 0 || /* format code: BINARY */
2186 pqPutInt(nargs, 2, conn) < 0) /* # of args */
2187 {
2188 /* error message should be set up already */
2189 return NULL;
2190 }
2191
2192 for (i = 0; i < nargs; ++i)
2193 { /* len.int4 + contents */
2194 if (pqPutInt(args[i].len, 4, conn))
2195 return NULL;
2196 if (args[i].len == -1)
2197 continue; /* it's NULL */
2198
2199 if (args[i].isint)
2200 {
2201 if (pqPutInt(args[i].u.integer, args[i].len, conn))
2202 return NULL;
2203 }
2204 else
2205 {
2206 if (pqPutnchar(args[i].u.ptr, args[i].len, conn))
2207 return NULL;
2208 }
2209 }
2210
2211 if (pqPutInt(1, 2, conn) < 0) /* result format code: BINARY */
2212 return NULL;
2213
2214 if (pqPutMsgEnd(conn) < 0 ||
2215 pqFlush(conn))
2216 return NULL;
2217
2218 for (;;)
2219 {
2220 if (needInput)
2221 {
2222 /* Wait for some data to arrive (or for the channel to close) */
2223 if (pqWait(true, false, conn) ||
2224 pqReadData(conn) < 0)
2225 break;
2226 }
2227
2228 /*
2229 * Scan the message. If we run out of data, loop around to try again.
2230 */
2231 needInput = true;
2232
2233 conn->inCursor = conn->inStart;
2234 if (pqGetc(&id, conn))
2235 continue;
2236 if (pqGetInt(&msgLength, 4, conn))
2237 continue;
2238
2239 /*
2240 * Try to validate message type/length here. A length less than 4 is
2241 * definitely broken. Large lengths should only be believed for a few
2242 * message types.
2243 */
2244 if (msgLength < 4)
2245 {
2246 handleSyncLoss(conn, id, msgLength);
2247 break;
2248 }
2249 if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
2250 {
2251 handleSyncLoss(conn, id, msgLength);
2252 break;
2253 }
2254
2255 /*
2256 * Can't process if message body isn't all here yet.
2257 */
2258 msgLength -= 4;
2259 avail = conn->inEnd - conn->inCursor;
2260 if (avail < msgLength)
2261 {
2262 /*
2263 * Before looping, enlarge the input buffer if needed to hold the
2264 * whole message. See notes in parseInput.
2265 */
2266 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
2267 conn))
2268 {
2269 /*
2270 * Abandon the connection. There's not much else we can
2271 * safely do; we can't just ignore the message or we could
2272 * miss important changes to the connection state.
2273 * pqCheckInBufferSpace() already reported the error.
2274 */
2275 handleFatalError(conn);
2276 break;
2277 }
2278 continue;
2279 }
2280
2281 /*
2282 * We should see V or E response to the command, but might get N
2283 * and/or A notices first. We also need to swallow the final Z before
2284 * returning.
2285 */
2286 switch (id)
2287 {
2288 case 'V': /* function result */
2289 if (pqGetInt(actual_result_len, 4, conn))
2290 continue;
2291 if (*actual_result_len != -1)
2292 {
2293 if (result_is_int)
2294 {
2295 if (pqGetInt(result_buf, *actual_result_len, conn))
2296 continue;
2297 }
2298 else
2299 {
2300 /*
2301 * If the server returned too much data for the
2302 * buffer, something fishy is going on. Abandon ship.
2303 */
2304 if (buf_size != -1 && *actual_result_len > buf_size)
2305 {
2306 libpq_append_conn_error(conn, "server returned too much data");
2307 handleFatalError(conn);
2308 return pqPrepareAsyncResult(conn);
2309 }
2310
2311 if (pqGetnchar(result_buf,
2312 *actual_result_len,
2313 conn))
2314 continue;
2315 }
2316 }
2317 /* correctly finished function result message */
2318 status = PGRES_COMMAND_OK;
2319 break;
2320 case 'E': /* error return */
2321 if (pqGetErrorNotice3(conn, true))
2322 continue;
2323 status = PGRES_FATAL_ERROR;
2324 break;
2325 case 'A': /* notify message */
2326 /* handle notify and go back to processing return values */
2327 if (getNotify(conn))
2328 continue;
2329 break;
2330 case 'N': /* notice */
2331 /* handle notice and go back to processing return values */
2332 if (pqGetErrorNotice3(conn, false))
2333 continue;
2334 break;
2335 case 'Z': /* backend is ready for new query */
2336 if (getReadyForQuery(conn))
2337 continue;
2338
2339 /* consume the message */
2340 pqParseDone(conn, conn->inStart + 5 + msgLength);
2341
2342 /*
2343 * If we already have a result object (probably an error), use
2344 * that. Otherwise, if we saw a function result message,
2345 * report COMMAND_OK. Otherwise, the backend violated the
2346 * protocol, so complain.
2347 */
2348 if (!pgHavePendingResult(conn))
2349 {
2350 if (status == PGRES_COMMAND_OK)
2351 {
2352 conn->result = PQmakeEmptyPGresult(conn, status);
2353 if (!conn->result)
2354 {
2355 libpq_append_conn_error(conn, "out of memory");
2356 pqSaveErrorResult(conn);
2357 }
2358 }
2359 else
2360 {
2361 libpq_append_conn_error(conn, "protocol error: no function result");
2362 pqSaveErrorResult(conn);
2363 }
2364 }
2365 /* and we're out */
2366 return pqPrepareAsyncResult(conn);
2367 case 'S': /* parameter status */
2368 if (getParameterStatus(conn))
2369 continue;
2370 break;
2371 default:
2372 /* The backend violates the protocol. */
2373 libpq_append_conn_error(conn, "protocol error: id=0x%x", id);
2374 pqSaveErrorResult(conn);
2375
2376 /*
2377 * We can't call parsing done due to the protocol violation
2378 * (so message tracing wouldn't work), but trust the specified
2379 * message length as what to skip.
2380 */
2381 conn->inStart += 5 + msgLength;
2382 return pqPrepareAsyncResult(conn);
2383 }
2384
2385 /*
2386 * An error may have been triggered while processing the message, bail
2387 * out
2388 */
2389 if (conn->error_result && conn->status == CONNECTION_BAD)
2390 return pqPrepareAsyncResult(conn);
2391
2392 /* Completed parsing this message, keep going */
2393 pqParseDone(conn, conn->inStart + 5 + msgLength);
2394 needInput = false;
2395 }
2396
2397 /*
2398 * We fall out of the loop only upon failing to read data.
2399 * conn->errorMessage has been set by pqWait or pqReadData. We want to
2400 * append it to any already-received error message.
2401 */
2402 pqSaveErrorResult(conn);
2403 return pqPrepareAsyncResult(conn);
2404 }
2405
2406
2407 /*
2408 * Construct startup packet
2409 *
2410 * Returns a malloc'd packet buffer, or NULL if out of memory
2411 */
2412 char *
2413 pqBuildStartupPacket3(PGconn *conn, int *packetlen,
2414 const PQEnvironmentOption *options)
2415 {
2416 char *startpacket;
2417 size_t len;
2418
2419 len = build_startup_packet(conn, NULL, options);
2420 if (len == 0 || len > INT_MAX)
2421 return NULL;
2422
2423 *packetlen = len;
2424 startpacket = (char *) malloc(*packetlen);
2425 if (!startpacket)
2426 return NULL;
2427
2428 len = build_startup_packet(conn, startpacket, options);
2429 Assert(*packetlen == len);
2430
2431 return startpacket;
2432 }
2433
2434 /*
2435 * Build a startup packet given a filled-in PGconn structure.
2436 *
2437 * We need to figure out how much space is needed, then fill it in.
2438 * To avoid duplicate logic, this routine is called twice: the first time
2439 * (with packet == NULL) just counts the space needed, the second time
2440 * (with packet == allocated space) fills it in. Return value is the number
2441 * of bytes used, or zero in the unlikely event of size_t overflow.
2442 */
2443 static size_t
2444 build_startup_packet(const PGconn *conn, char *packet,
2445 const PQEnvironmentOption *options)
2446 {
2447 size_t packet_len = 0;
2448 const PQEnvironmentOption *next_eo;
2449 const char *val;
2450
2451 /* Protocol version comes first. */
2452 if (packet)
2453 {
2454 ProtocolVersion pv = pg_hton32(conn->pversion);
2455
2456 memcpy(packet + packet_len, &pv, sizeof(ProtocolVersion));
2457 }
2458 packet_len += sizeof(ProtocolVersion);
2459
2460 /* Add user name, database name, options */
2461
2462 #define ADD_STARTUP_OPTION(optname, optval) \
2463 do { \
2464 if (packet) \
2465 strcpy(packet + packet_len, optname); \
2466 if (pg_add_size_overflow(packet_len, strlen(optname) + 1, &packet_len)) \
2467 return 0; \
2468 if (packet) \
2469 strcpy(packet + packet_len, optval); \
2470 if (pg_add_size_overflow(packet_len, strlen(optval) + 1, &packet_len)) \
2471 return 0; \
2472 } while(0)
2473
2474 if (conn->pguser && conn->pguser[0])
2475 ADD_STARTUP_OPTION("user", conn->pguser);
2476 if (conn->dbName && conn->dbName[0])
2477 ADD_STARTUP_OPTION("database", conn->dbName);
2478 if (conn->replication && conn->replication[0])
2479 ADD_STARTUP_OPTION("replication", conn->replication);
2480 if (conn->pgoptions && conn->pgoptions[0])
2481 ADD_STARTUP_OPTION("options", conn->pgoptions);
2482 if (conn->send_appname)
2483 {
2484 /* Use appname if present, otherwise use fallback */
2485 val = conn->appname ? conn->appname : conn->fbappname;
2486 if (val && val[0])
2487 ADD_STARTUP_OPTION("application_name", val);
2488 }
2489
2490 if (conn->client_encoding_initial && conn->client_encoding_initial[0])
2491 ADD_STARTUP_OPTION("client_encoding", conn->client_encoding_initial);
2492
2493 /* Add any environment-driven GUC settings needed */
2494 for (next_eo = options; next_eo->envName; next_eo++)
2495 {
2496 if ((val = getenv(next_eo->envName)) != NULL)
2497 {
2498 if (pg_strcasecmp(val, "default") != 0)
2499 ADD_STARTUP_OPTION(next_eo->pgName, val);
2500 }
2501 }
2502
2503 /* Add trailing terminator */
2504 if (packet)
2505 packet[packet_len] = '\0';
2506 if (pg_add_size_overflow(packet_len, 1, &packet_len))
2507 return 0;
2508
2509 return packet_len;
2510 }