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