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