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