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