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