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 3693788 : 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 14578048 : conn->inCursor = conn->inStart;
83 14578048 : if (pqGetc(&id, conn))
84 2806388 : return;
85 11771660 : if (pqGetInt(&msgLength, 4, conn))
86 3176 : 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 11768484 : if (msgLength < 4)
94 : {
95 0 : handleSyncLoss(conn, id, msgLength);
96 0 : return;
97 : }
98 11768484 : 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 11768484 : msgLength -= 4;
108 11768484 : avail = conn->inEnd - conn->inCursor;
109 11768484 : 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 101700 : 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 101700 : 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 11666784 : if (id == PqMsg_NotificationResponse)
150 : {
151 62 : if (getNotify(conn))
152 0 : return;
153 : }
154 11666722 : else if (id == PqMsg_NoticeResponse)
155 : {
156 156322 : if (pqGetErrorNotice3(conn, false))
157 0 : return;
158 : }
159 11510400 : else if (conn->asyncStatus != PGASYNC_BUSY)
160 : {
161 : /* If not IDLE state, just wait ... */
162 782524 : if (conn->asyncStatus != PGASYNC_IDLE)
163 782524 : 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 0 : if (id == PqMsg_ErrorResponse)
175 : {
176 0 : if (pqGetErrorNotice3(conn, false /* treat as notice */ ))
177 0 : return;
178 : }
179 0 : 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 0 : pqInternalNotice(&conn->noticeHooks,
188 : "message type 0x%02x arrived from server while idle",
189 : id);
190 : /* Discard the unexpected message */
191 0 : conn->inCursor += msgLength;
192 : }
193 : }
194 : else
195 : {
196 : /*
197 : * In BUSY state, we can process everything.
198 : */
199 10727876 : switch (id)
200 : {
201 655162 : case PqMsg_CommandComplete:
202 655162 : if (pqGets(&conn->workBuffer, conn))
203 0 : return;
204 655162 : if (!pgHavePendingResult(conn))
205 : {
206 333490 : conn->result = PQmakeEmptyPGresult(conn,
207 : PGRES_COMMAND_OK);
208 333490 : if (!conn->result)
209 : {
210 0 : libpq_append_conn_error(conn, "out of memory");
211 0 : pqSaveErrorResult(conn);
212 : }
213 : }
214 655162 : if (conn->result)
215 655162 : strlcpy(conn->result->cmdStatus, conn->workBuffer.data,
216 : CMDSTATUS_LEN);
217 655162 : conn->asyncStatus = PGASYNC_READY;
218 655162 : break;
219 43280 : case PqMsg_ErrorResponse:
220 43280 : if (pqGetErrorNotice3(conn, true))
221 0 : return;
222 43280 : conn->asyncStatus = PGASYNC_READY;
223 43280 : break;
224 687860 : case PqMsg_ReadyForQuery:
225 687860 : if (getReadyForQuery(conn))
226 0 : return;
227 687860 : if (conn->pipelineStatus != PQ_PIPELINE_OFF)
228 : {
229 526 : conn->result = PQmakeEmptyPGresult(conn,
230 : PGRES_PIPELINE_SYNC);
231 526 : if (!conn->result)
232 : {
233 0 : libpq_append_conn_error(conn, "out of memory");
234 0 : pqSaveErrorResult(conn);
235 : }
236 : else
237 : {
238 526 : conn->pipelineStatus = PQ_PIPELINE_ON;
239 526 : conn->asyncStatus = PGASYNC_READY;
240 : }
241 : }
242 : else
243 : {
244 : /* Advance the command queue and set us idle */
245 687334 : pqCommandQueueAdvance(conn, true, false);
246 687334 : conn->asyncStatus = PGASYNC_IDLE;
247 : }
248 687860 : break;
249 1386 : case PqMsg_EmptyQueryResponse:
250 1386 : if (!pgHavePendingResult(conn))
251 : {
252 1386 : conn->result = PQmakeEmptyPGresult(conn,
253 : PGRES_EMPTY_QUERY);
254 1386 : if (!conn->result)
255 : {
256 0 : libpq_append_conn_error(conn, "out of memory");
257 0 : pqSaveErrorResult(conn);
258 : }
259 : }
260 1386 : conn->asyncStatus = PGASYNC_READY;
261 1386 : break;
262 10968 : case PqMsg_ParseComplete:
263 : /* If we're doing PQprepare, we're done; else ignore */
264 10968 : if (conn->cmd_queue_head &&
265 10968 : 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 10968 : break;
280 21502 : case PqMsg_BindComplete:
281 : /* Nothing to do for this message type */
282 21502 : 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 403290 : case PqMsg_ParameterStatus:
302 403290 : if (getParameterStatus(conn))
303 0 : return;
304 403290 : break;
305 25972 : 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 25972 : if (getBackendKeyData(conn, msgLength))
313 0 : return;
314 25972 : break;
315 329014 : case PqMsg_RowDescription:
316 329014 : if (conn->error_result ||
317 329014 : (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 329014 : 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 329014 : 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 329014 : break;
347 12492 : 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 12492 : if (conn->cmd_queue_head &&
360 12492 : 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 12492 : break;
375 140 : case PqMsg_ParameterDescription:
376 140 : if (getParamDescriptions(conn, msgLength))
377 0 : return;
378 140 : break;
379 8505870 : case PqMsg_DataRow:
380 8505870 : if (conn->result != NULL &&
381 8505870 : (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 8505870 : 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 8505870 : break;
407 2254 : case PqMsg_CopyInResponse:
408 2254 : if (getCopyStart(conn, PGRES_COPY_IN))
409 0 : return;
410 2254 : conn->asyncStatus = PGASYNC_COPY_IN;
411 2254 : break;
412 13336 : case PqMsg_CopyOutResponse:
413 13336 : if (getCopyStart(conn, PGRES_COPY_OUT))
414 0 : return;
415 13336 : conn->asyncStatus = PGASYNC_COPY_OUT;
416 13336 : conn->copy_already_done = 0;
417 13336 : break;
418 1316 : case PqMsg_CopyBothResponse:
419 1316 : if (getCopyStart(conn, PGRES_COPY_BOTH))
420 0 : return;
421 1316 : conn->asyncStatus = PGASYNC_COPY_BOTH;
422 1316 : conn->copy_already_done = 0;
423 1316 : break;
424 2 : 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 2 : conn->inCursor += msgLength;
432 2 : break;
433 14000 : 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 14000 : 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 10884260 : if (conn->inCursor == conn->inStart + 5 + msgLength)
455 : {
456 : /* Normal case: parsing agrees with specified length */
457 10884260 : 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 329014 : 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 329014 : if (!conn->cmd_queue_head ||
511 329014 : (conn->cmd_queue_head &&
512 329014 : 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 328884 : result = PQmakeEmptyPGresult(conn, PGRES_TUPLES_OK);
521 329014 : 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 329014 : 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 329014 : nfields = result->numAttributes;
536 :
537 : /* allocate space for the attribute descriptors */
538 329014 : if (nfields > 0)
539 : {
540 328740 : result->attDescs = (PGresAttDesc *)
541 328740 : pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
542 328740 : if (!result->attDescs)
543 : {
544 0 : errmsg = NULL; /* means "out of memory", see below */
545 0 : goto advance_and_error;
546 : }
547 4782180 : MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
548 : }
549 :
550 : /* result->binary is true only if ALL columns are binary */
551 329014 : result->binary = (nfields > 0) ? 1 : 0;
552 :
553 : /* get type info */
554 1462954 : 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 2267880 : if (pqGets(&conn->workBuffer, conn) ||
564 2267880 : pqGetInt(&tableid, 4, conn) ||
565 2267880 : pqGetInt(&columnid, 2, conn) ||
566 2267880 : pqGetInt(&typid, 4, conn) ||
567 2267880 : pqGetInt(&typlen, 2, conn) ||
568 2267880 : pqGetInt(&atttypmod, 4, conn) ||
569 1133940 : 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 1133940 : columnid = (int) ((int16) columnid);
581 1133940 : typlen = (int) ((int16) typlen);
582 1133940 : format = (int) ((int16) format);
583 :
584 2267880 : result->attDescs[i].name = pqResultStrdup(result,
585 1133940 : conn->workBuffer.data);
586 1133940 : if (!result->attDescs[i].name)
587 : {
588 0 : errmsg = NULL; /* means "out of memory", see below */
589 0 : goto advance_and_error;
590 : }
591 1133940 : result->attDescs[i].tableid = tableid;
592 1133940 : result->attDescs[i].columnid = columnid;
593 1133940 : result->attDescs[i].format = format;
594 1133940 : result->attDescs[i].typid = typid;
595 1133940 : result->attDescs[i].typlen = typlen;
596 1133940 : result->attDescs[i].atttypmod = atttypmod;
597 :
598 1133940 : if (format != 1)
599 1133854 : result->binary = 0;
600 : }
601 :
602 : /* Success! */
603 329014 : 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 329014 : if ((!conn->cmd_queue_head) ||
610 329014 : (conn->cmd_queue_head &&
611 329014 : 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 328884 : 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 8505870 : getAnotherTuple(PGconn *conn, int msgLength)
758 : {
759 8505870 : PGresult *result = conn->result;
760 8505870 : 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 8505870 : 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 8505870 : 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 8505870 : rowbuf = conn->rowBuf;
783 8505870 : 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 52549312 : for (i = 0; i < nfields; i++)
798 : {
799 : /* get the value length */
800 44043442 : 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 44043442 : 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 44043442 : rowbuf[i].value = conn->inBuffer + conn->inCursor;
814 :
815 : /* Skip over the data value */
816 44043442 : if (vlen > 0)
817 : {
818 40911696 : 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 8505870 : errmsg = NULL;
829 8505870 : if (pqRowProcessor(conn, &errmsg))
830 8505870 : 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 200286 : pqGetErrorNotice3(PGconn *conn, bool isError)
879 : {
880 200286 : PGresult *res = NULL;
881 200286 : bool have_position = false;
882 : PQExpBufferData workBuf;
883 : char id;
884 :
885 : /* If in pipeline mode, set error indicator for it */
886 200286 : if (isError && conn->pipelineStatus != PQ_PIPELINE_OFF)
887 98 : 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 200286 : if (isError)
895 43902 : 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 200286 : 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 200286 : res = PQmakeEmptyPGresult(conn, PGRES_EMPTY_QUERY);
915 200286 : if (res)
916 200286 : 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 1787720 : if (pqGetc(&id, conn))
927 0 : goto fail;
928 1787720 : if (id == '\0')
929 200286 : break; /* terminator found */
930 1587434 : if (pqGets(&workBuf, conn))
931 0 : goto fail;
932 1587434 : pqSaveMessageField(res, id, workBuf.data);
933 1587434 : if (id == PG_DIAG_SQLSTATE)
934 200286 : strlcpy(conn->last_sqlstate, workBuf.data,
935 : sizeof(conn->last_sqlstate));
936 1387148 : else if (id == PG_DIAG_STATEMENT_POSITION)
937 10314 : 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 200286 : if (have_position && res && conn->cmd_queue_head && conn->cmd_queue_head->query)
946 10314 : res->errQuery = pqResultStrdup(res, conn->cmd_queue_head->query);
947 :
948 : /*
949 : * Now build the "overall" error message for PQresultErrorMessage.
950 : */
951 200286 : resetPQExpBuffer(&workBuf);
952 200286 : 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 200286 : if (isError)
958 : {
959 43902 : pqClearAsyncResult(conn); /* redundant, but be safe */
960 43902 : if (res)
961 : {
962 43902 : pqSetResultError(res, &workBuf, 0);
963 43902 : 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 43902 : if (PQExpBufferDataBroken(workBuf))
972 0 : libpq_append_conn_error(conn, "out of memory");
973 : else
974 43902 : appendPQExpBufferStr(&conn->errorMessage, workBuf.data);
975 : }
976 : else
977 : {
978 : /* if we couldn't allocate the result set, just discard the NOTICE */
979 156384 : 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 156384 : if (PQExpBufferDataBroken(workBuf))
987 0 : res->errMsg = libpq_gettext("out of memory\n");
988 : else
989 156384 : res->errMsg = workBuf.data;
990 156384 : if (res->noticeHooks.noticeRec != NULL)
991 156384 : res->noticeHooks.noticeRec(res->noticeHooks.noticeRecArg, res);
992 156384 : PQclear(res);
993 : }
994 : }
995 :
996 200286 : termPQExpBuffer(&workBuf);
997 200286 : 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 200292 : pqBuildErrorMessage3(PQExpBuffer msg, const PGresult *res,
1011 : PGVerbosity verbosity, PGContextVisibility show_context)
1012 : {
1013 : const char *val;
1014 200292 : const char *querytext = NULL;
1015 200292 : int querypos = 0;
1016 :
1017 : /* If we couldn't allocate a PGresult, just say "out of memory" */
1018 200292 : 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 200292 : 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 200292 : val = PQresultErrorField(res, PG_DIAG_SEVERITY);
1039 200292 : if (val)
1040 200292 : appendPQExpBuffer(msg, "%s: ", val);
1041 :
1042 200292 : 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 200226 : 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 200226 : val = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
1066 200226 : if (val)
1067 200226 : appendPQExpBufferStr(msg, val);
1068 200226 : val = PQresultErrorField(res, PG_DIAG_STATEMENT_POSITION);
1069 200226 : if (val)
1070 : {
1071 10314 : if (verbosity != PQERRORS_TERSE && res->errQuery != NULL)
1072 : {
1073 : /* emit position as a syntax cursor display */
1074 10308 : querytext = res->errQuery;
1075 10308 : 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 189912 : val = PQresultErrorField(res, PG_DIAG_INTERNAL_POSITION);
1088 189912 : 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 200226 : appendPQExpBufferChar(msg, '\n');
1106 200226 : if (verbosity != PQERRORS_TERSE)
1107 : {
1108 199630 : if (querytext && querypos > 0)
1109 10406 : reportErrorPosition(msg, querytext, querypos,
1110 10406 : res->client_encoding);
1111 199630 : val = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
1112 199630 : if (val)
1113 10804 : appendPQExpBuffer(msg, libpq_gettext("DETAIL: %s\n"), val);
1114 199630 : val = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
1115 199630 : if (val)
1116 134688 : appendPQExpBuffer(msg, libpq_gettext("HINT: %s\n"), val);
1117 199630 : val = PQresultErrorField(res, PG_DIAG_INTERNAL_QUERY);
1118 199630 : if (val)
1119 98 : appendPQExpBuffer(msg, libpq_gettext("QUERY: %s\n"), val);
1120 199630 : if (show_context == PQSHOW_CONTEXT_ALWAYS ||
1121 199360 : (show_context == PQSHOW_CONTEXT_ERRORS &&
1122 199360 : res->resultStatus == PGRES_FATAL_ERROR))
1123 : {
1124 43766 : val = PQresultErrorField(res, PG_DIAG_CONTEXT);
1125 43766 : if (val)
1126 2416 : appendPQExpBuffer(msg, libpq_gettext("CONTEXT: %s\n"),
1127 : val);
1128 : }
1129 : }
1130 200226 : 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 200226 : 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 10406 : 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 10406 : loc--;
1203 10406 : if (loc < 0)
1204 0 : return;
1205 :
1206 : /* Need a writable copy of the query */
1207 10406 : wquery = strdup(query);
1208 10406 : 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 10406 : slen = strlen(wquery) + 1;
1221 :
1222 10406 : qidx = (int *) malloc(slen * sizeof(int));
1223 10406 : if (qidx == NULL)
1224 : {
1225 0 : free(wquery);
1226 0 : return;
1227 : }
1228 10406 : scridx = (int *) malloc(slen * sizeof(int));
1229 10406 : 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 10406 : 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 10406 : qoffset = 0;
1249 10406 : scroffset = 0;
1250 10406 : loc_line = 1;
1251 10406 : ibeg = 0;
1252 10406 : iend = -1; /* -1 means not set yet */
1253 :
1254 556790 : for (cno = 0; wquery[qoffset] != '\0'; cno++)
1255 : {
1256 547530 : char ch = wquery[qoffset];
1257 :
1258 547530 : qidx[cno] = qoffset;
1259 547530 : 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 547530 : 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 546552 : 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 546384 : if (mb_encoding)
1295 : {
1296 : int w;
1297 :
1298 546008 : w = pg_encoding_dsplen(encoding, &wquery[qoffset]);
1299 : /* treat any non-tab control chars as width 1 */
1300 546008 : if (w <= 0)
1301 2688 : w = 1;
1302 546008 : scroffset += w;
1303 546008 : 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 10406 : if (iend < 0)
1314 : {
1315 9260 : iend = cno; /* query length in chars, +1 */
1316 9260 : qidx[iend] = qoffset;
1317 9260 : scridx[iend] = scroffset;
1318 : }
1319 :
1320 : /* Print only if loc is within computed query length */
1321 10406 : if (loc <= cno)
1322 : {
1323 : /* If the line extracted is too long, we truncate it. */
1324 10388 : beg_trunc = false;
1325 10388 : end_trunc = false;
1326 10388 : 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 2488 : if (scridx[ibeg] + DISPLAY_SIZE >= scridx[loc] + MIN_RIGHT_CUT)
1334 : {
1335 19458 : while (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1336 18160 : iend--;
1337 1298 : end_trunc = true;
1338 : }
1339 : else
1340 : {
1341 : /* Truncate right if not too close to loc. */
1342 14118 : while (scridx[loc] + MIN_RIGHT_CUT < scridx[iend])
1343 : {
1344 12928 : iend--;
1345 12928 : end_trunc = true;
1346 : }
1347 :
1348 : /* Truncate left if still too long. */
1349 22908 : while (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1350 : {
1351 21718 : ibeg++;
1352 21718 : beg_trunc = true;
1353 : }
1354 : }
1355 : }
1356 :
1357 : /* truncate working copy at desired endpoint */
1358 10388 : wquery[qidx[iend]] = '\0';
1359 :
1360 : /* Begin building the finished message. */
1361 10388 : i = msg->len;
1362 10388 : appendPQExpBuffer(msg, libpq_gettext("LINE %d: "), loc_line);
1363 10388 : if (beg_trunc)
1364 1190 : appendPQExpBufferStr(msg, "...");
1365 :
1366 : /*
1367 : * While we have the prefix in the msg buffer, compute its screen
1368 : * width.
1369 : */
1370 10388 : scroffset = 0;
1371 97074 : for (; i < msg->len; i += PQmblenBounded(&msg->data[i], encoding))
1372 : {
1373 86686 : int w = pg_encoding_dsplen(encoding, &msg->data[i]);
1374 :
1375 86686 : if (w <= 0)
1376 0 : w = 1;
1377 86686 : scroffset += w;
1378 : }
1379 :
1380 : /* Finish up the LINE message line. */
1381 10388 : appendPQExpBufferStr(msg, &wquery[qidx[ibeg]]);
1382 10388 : if (end_trunc)
1383 2148 : appendPQExpBufferStr(msg, "...");
1384 10388 : appendPQExpBufferChar(msg, '\n');
1385 :
1386 : /* Now emit the cursor marker line. */
1387 10388 : scroffset += scridx[loc] - scridx[ibeg];
1388 332912 : for (i = 0; i < scroffset; i++)
1389 322524 : appendPQExpBufferChar(msg, ' ');
1390 10388 : appendPQExpBufferChar(msg, '^');
1391 10388 : appendPQExpBufferChar(msg, '\n');
1392 : }
1393 :
1394 : /* Clean up. */
1395 10406 : free(scridx);
1396 10406 : free(qidx);
1397 10406 : 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 requested 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 \"%s\" was set to %d.%d",
1456 : PG_PROTOCOL_MAJOR(their_version),
1457 : PG_PROTOCOL_MINOR(their_version),
1458 : "min_protocol_version",
1459 0 : PG_PROTOCOL_MAJOR(conn->min_pversion),
1460 0 : PG_PROTOCOL_MINOR(conn->min_pversion));
1461 :
1462 0 : goto failure;
1463 : }
1464 :
1465 : /* the version is acceptable */
1466 0 : conn->pversion = their_version;
1467 :
1468 : /*
1469 : * We don't currently request any protocol extensions, so we don't expect
1470 : * the server to reply with any either.
1471 : */
1472 0 : for (int i = 0; i < num; i++)
1473 : {
1474 0 : if (pqGets(&conn->workBuffer, conn))
1475 : {
1476 0 : goto eof;
1477 : }
1478 0 : if (strncmp(conn->workBuffer.data, "_pq_.", 5) != 0)
1479 : {
1480 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);
1481 0 : goto failure;
1482 : }
1483 0 : libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported an unsupported parameter that was not requested (\"%s\")", conn->workBuffer.data);
1484 0 : goto failure;
1485 : }
1486 :
1487 0 : return 0;
1488 :
1489 0 : eof:
1490 0 : libpq_append_conn_error(conn, "received invalid protocol negotiation message: message too short");
1491 0 : failure:
1492 0 : conn->asyncStatus = PGASYNC_READY;
1493 0 : pqSaveErrorResult(conn);
1494 0 : return 1;
1495 : }
1496 :
1497 :
1498 : /*
1499 : * Attempt to read a ParameterStatus message.
1500 : * This is possible in several places, so we break it out as a subroutine.
1501 : *
1502 : * Entry: 'S' message type and length have already been consumed.
1503 : * Exit: returns 0 if successfully consumed message.
1504 : * returns EOF if not enough data.
1505 : */
1506 : static int
1507 403290 : getParameterStatus(PGconn *conn)
1508 : {
1509 : PQExpBufferData valueBuf;
1510 :
1511 : /* Get the parameter name */
1512 403290 : if (pqGets(&conn->workBuffer, conn))
1513 0 : return EOF;
1514 : /* Get the parameter value (could be large) */
1515 403290 : initPQExpBuffer(&valueBuf);
1516 403290 : if (pqGets(&valueBuf, conn))
1517 : {
1518 0 : termPQExpBuffer(&valueBuf);
1519 0 : return EOF;
1520 : }
1521 : /* And save it */
1522 403290 : pqSaveParameterStatus(conn, conn->workBuffer.data, valueBuf.data);
1523 403290 : termPQExpBuffer(&valueBuf);
1524 403290 : return 0;
1525 : }
1526 :
1527 : /*
1528 : * parseInput subroutine to read a BackendKeyData message.
1529 : * Entry: 'v' message type and length have already been consumed.
1530 : * Exit: returns 0 if successfully consumed message.
1531 : * returns EOF if not enough data.
1532 : */
1533 : static int
1534 25972 : getBackendKeyData(PGconn *conn, int msgLength)
1535 : {
1536 : int cancel_key_len;
1537 :
1538 25972 : if (conn->be_cancel_key)
1539 : {
1540 0 : free(conn->be_cancel_key);
1541 0 : conn->be_cancel_key = NULL;
1542 0 : conn->be_cancel_key_len = 0;
1543 : }
1544 :
1545 25972 : if (pqGetInt(&(conn->be_pid), 4, conn))
1546 0 : return EOF;
1547 :
1548 25972 : cancel_key_len = 5 + msgLength - (conn->inCursor - conn->inStart);
1549 :
1550 25972 : conn->be_cancel_key = malloc(cancel_key_len);
1551 25972 : if (conn->be_cancel_key == NULL)
1552 : {
1553 0 : libpq_append_conn_error(conn, "out of memory");
1554 : /* discard the message */
1555 0 : return EOF;
1556 : }
1557 25972 : if (pqGetnchar(conn->be_cancel_key, cancel_key_len, conn))
1558 : {
1559 0 : free(conn->be_cancel_key);
1560 0 : conn->be_cancel_key = NULL;
1561 0 : return EOF;
1562 : }
1563 25972 : conn->be_cancel_key_len = cancel_key_len;
1564 25972 : return 0;
1565 : }
1566 :
1567 :
1568 : /*
1569 : * Attempt to read a Notify response message.
1570 : * This is possible in several places, so we break it out as a subroutine.
1571 : *
1572 : * Entry: 'A' message type and length have already been consumed.
1573 : * Exit: returns 0 if successfully consumed Notify message.
1574 : * returns EOF if not enough data.
1575 : */
1576 : static int
1577 62 : getNotify(PGconn *conn)
1578 : {
1579 : int be_pid;
1580 : char *svname;
1581 : int nmlen;
1582 : int extralen;
1583 : PGnotify *newNotify;
1584 :
1585 62 : if (pqGetInt(&be_pid, 4, conn))
1586 0 : return EOF;
1587 62 : if (pqGets(&conn->workBuffer, conn))
1588 0 : return EOF;
1589 : /* must save name while getting extra string */
1590 62 : svname = strdup(conn->workBuffer.data);
1591 62 : if (!svname)
1592 0 : return EOF;
1593 62 : if (pqGets(&conn->workBuffer, conn))
1594 : {
1595 0 : free(svname);
1596 0 : return EOF;
1597 : }
1598 :
1599 : /*
1600 : * Store the strings right after the PGnotify structure so it can all be
1601 : * freed at once. We don't use NAMEDATALEN because we don't want to tie
1602 : * this interface to a specific server name length.
1603 : */
1604 62 : nmlen = strlen(svname);
1605 62 : extralen = strlen(conn->workBuffer.data);
1606 62 : newNotify = (PGnotify *) malloc(sizeof(PGnotify) + nmlen + extralen + 2);
1607 62 : if (newNotify)
1608 : {
1609 62 : newNotify->relname = (char *) newNotify + sizeof(PGnotify);
1610 62 : strcpy(newNotify->relname, svname);
1611 62 : newNotify->extra = newNotify->relname + nmlen + 1;
1612 62 : strcpy(newNotify->extra, conn->workBuffer.data);
1613 62 : newNotify->be_pid = be_pid;
1614 62 : newNotify->next = NULL;
1615 62 : if (conn->notifyTail)
1616 24 : conn->notifyTail->next = newNotify;
1617 : else
1618 38 : conn->notifyHead = newNotify;
1619 62 : conn->notifyTail = newNotify;
1620 : }
1621 :
1622 62 : free(svname);
1623 62 : return 0;
1624 : }
1625 :
1626 : /*
1627 : * getCopyStart - process CopyInResponse, CopyOutResponse or
1628 : * CopyBothResponse message
1629 : *
1630 : * parseInput already read the message type and length.
1631 : */
1632 : static int
1633 16906 : getCopyStart(PGconn *conn, ExecStatusType copytype)
1634 : {
1635 : PGresult *result;
1636 : int nfields;
1637 : int i;
1638 :
1639 16906 : result = PQmakeEmptyPGresult(conn, copytype);
1640 16906 : if (!result)
1641 0 : goto failure;
1642 :
1643 16906 : if (pqGetc(&conn->copy_is_binary, conn))
1644 0 : goto failure;
1645 16906 : result->binary = conn->copy_is_binary;
1646 : /* the next two bytes are the number of fields */
1647 16906 : if (pqGetInt(&(result->numAttributes), 2, conn))
1648 0 : goto failure;
1649 16906 : nfields = result->numAttributes;
1650 :
1651 : /* allocate space for the attribute descriptors */
1652 16906 : if (nfields > 0)
1653 : {
1654 14936 : result->attDescs = (PGresAttDesc *)
1655 14936 : pqResultAlloc(result, nfields * sizeof(PGresAttDesc), true);
1656 14936 : if (!result->attDescs)
1657 0 : goto failure;
1658 157736 : MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
1659 : }
1660 :
1661 71594 : for (i = 0; i < nfields; i++)
1662 : {
1663 : int format;
1664 :
1665 54688 : if (pqGetInt(&format, 2, conn))
1666 0 : goto failure;
1667 :
1668 : /*
1669 : * Since pqGetInt treats 2-byte integers as unsigned, we need to
1670 : * coerce these results to signed form.
1671 : */
1672 54688 : format = (int) ((int16) format);
1673 54688 : result->attDescs[i].format = format;
1674 : }
1675 :
1676 : /* Success! */
1677 16906 : conn->result = result;
1678 16906 : return 0;
1679 :
1680 0 : failure:
1681 0 : PQclear(result);
1682 0 : return EOF;
1683 : }
1684 :
1685 : /*
1686 : * getReadyForQuery - process ReadyForQuery message
1687 : */
1688 : static int
1689 690068 : getReadyForQuery(PGconn *conn)
1690 : {
1691 : char xact_status;
1692 :
1693 690068 : if (pqGetc(&xact_status, conn))
1694 0 : return EOF;
1695 690068 : switch (xact_status)
1696 : {
1697 509108 : case 'I':
1698 509108 : conn->xactStatus = PQTRANS_IDLE;
1699 509108 : break;
1700 179168 : case 'T':
1701 179168 : conn->xactStatus = PQTRANS_INTRANS;
1702 179168 : break;
1703 1792 : case 'E':
1704 1792 : conn->xactStatus = PQTRANS_INERROR;
1705 1792 : break;
1706 0 : default:
1707 0 : conn->xactStatus = PQTRANS_UNKNOWN;
1708 0 : break;
1709 : }
1710 :
1711 690068 : return 0;
1712 : }
1713 :
1714 : /*
1715 : * getCopyDataMessage - fetch next CopyData message, process async messages
1716 : *
1717 : * Returns length word of CopyData message (> 0), or 0 if no complete
1718 : * message available, -1 if end of copy, -2 if error.
1719 : */
1720 : static int
1721 8475090 : getCopyDataMessage(PGconn *conn)
1722 : {
1723 : char id;
1724 : int msgLength;
1725 : int avail;
1726 :
1727 : for (;;)
1728 : {
1729 : /*
1730 : * Do we have the next input message? To make life simpler for async
1731 : * callers, we keep returning 0 until the next message is fully
1732 : * available, even if it is not Copy Data.
1733 : */
1734 8475152 : conn->inCursor = conn->inStart;
1735 8475152 : if (pqGetc(&id, conn))
1736 632286 : return 0;
1737 7842866 : if (pqGetInt(&msgLength, 4, conn))
1738 2692 : return 0;
1739 7840174 : if (msgLength < 4)
1740 : {
1741 0 : handleSyncLoss(conn, id, msgLength);
1742 0 : return -2;
1743 : }
1744 7840174 : avail = conn->inEnd - conn->inCursor;
1745 7840174 : if (avail < msgLength - 4)
1746 : {
1747 : /*
1748 : * Before returning, enlarge the input buffer if needed to hold
1749 : * the whole message. See notes in parseInput.
1750 : */
1751 412600 : if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength - 4,
1752 : conn))
1753 : {
1754 : /*
1755 : * XXX add some better recovery code... plan is to skip over
1756 : * the message using its length, then report an error. For the
1757 : * moment, just treat this like loss of sync (which indeed it
1758 : * might be!)
1759 : */
1760 0 : handleSyncLoss(conn, id, msgLength);
1761 0 : return -2;
1762 : }
1763 412600 : return 0;
1764 : }
1765 :
1766 : /*
1767 : * If it's a legitimate async message type, process it. (NOTIFY
1768 : * messages are not currently possible here, but we handle them for
1769 : * completeness.) Otherwise, if it's anything except Copy Data,
1770 : * report end-of-copy.
1771 : */
1772 7427574 : switch (id)
1773 : {
1774 0 : case PqMsg_NotificationResponse:
1775 0 : if (getNotify(conn))
1776 0 : return 0;
1777 0 : break;
1778 62 : case PqMsg_NoticeResponse:
1779 62 : if (pqGetErrorNotice3(conn, false))
1780 0 : return 0;
1781 62 : break;
1782 0 : case PqMsg_ParameterStatus:
1783 0 : if (getParameterStatus(conn))
1784 0 : return 0;
1785 0 : break;
1786 7413780 : case PqMsg_CopyData:
1787 7413780 : return msgLength;
1788 13636 : case PqMsg_CopyDone:
1789 :
1790 : /*
1791 : * If this is a CopyDone message, exit COPY_OUT mode and let
1792 : * caller read status with PQgetResult(). If we're in
1793 : * COPY_BOTH mode, return to COPY_IN mode.
1794 : */
1795 13636 : if (conn->asyncStatus == PGASYNC_COPY_BOTH)
1796 26 : conn->asyncStatus = PGASYNC_COPY_IN;
1797 : else
1798 13610 : conn->asyncStatus = PGASYNC_BUSY;
1799 13636 : return -1;
1800 96 : default: /* treat as end of copy */
1801 :
1802 : /*
1803 : * Any other message terminates either COPY_IN or COPY_BOTH
1804 : * mode.
1805 : */
1806 96 : conn->asyncStatus = PGASYNC_BUSY;
1807 96 : return -1;
1808 : }
1809 :
1810 : /* Drop the processed message and loop around for another */
1811 62 : pqParseDone(conn, conn->inCursor);
1812 : }
1813 : }
1814 :
1815 : /*
1816 : * PQgetCopyData - read a row of data from the backend during COPY OUT
1817 : * or COPY BOTH
1818 : *
1819 : * If successful, sets *buffer to point to a malloc'd row of data, and
1820 : * returns row length (always > 0) as result.
1821 : * Returns 0 if no row available yet (only possible if async is true),
1822 : * -1 if end of copy (consult PQgetResult), or -2 if error (consult
1823 : * PQerrorMessage).
1824 : */
1825 : int
1826 8178436 : pqGetCopyData3(PGconn *conn, char **buffer, int async)
1827 : {
1828 : int msgLength;
1829 :
1830 : for (;;)
1831 : {
1832 : /*
1833 : * Collect the next input message. To make life simpler for async
1834 : * callers, we keep returning 0 until the next message is fully
1835 : * available, even if it is not Copy Data.
1836 : */
1837 8475090 : msgLength = getCopyDataMessage(conn);
1838 8475090 : if (msgLength < 0)
1839 13732 : return msgLength; /* end-of-copy or error */
1840 8461358 : if (msgLength == 0)
1841 : {
1842 : /* Don't block if async read requested */
1843 1047578 : if (async)
1844 750924 : return 0;
1845 : /* Need to load more data */
1846 593308 : if (pqWait(true, false, conn) ||
1847 296654 : pqReadData(conn) < 0)
1848 0 : return -2;
1849 296654 : continue;
1850 : }
1851 :
1852 : /*
1853 : * Drop zero-length messages (shouldn't happen anyway). Otherwise
1854 : * pass the data back to the caller.
1855 : */
1856 7413780 : msgLength -= 4;
1857 7413780 : if (msgLength > 0)
1858 : {
1859 7413780 : *buffer = (char *) malloc(msgLength + 1);
1860 7413780 : if (*buffer == NULL)
1861 : {
1862 0 : libpq_append_conn_error(conn, "out of memory");
1863 0 : return -2;
1864 : }
1865 7413780 : memcpy(*buffer, &conn->inBuffer[conn->inCursor], msgLength);
1866 7413780 : (*buffer)[msgLength] = '\0'; /* Add terminating null */
1867 :
1868 : /* Mark message consumed */
1869 7413780 : pqParseDone(conn, conn->inCursor + msgLength);
1870 :
1871 7413780 : return msgLength;
1872 : }
1873 :
1874 : /* Empty, so drop it and loop around for another */
1875 0 : pqParseDone(conn, conn->inCursor);
1876 : }
1877 : }
1878 :
1879 : /*
1880 : * PQgetline - gets a newline-terminated string from the backend.
1881 : *
1882 : * See fe-exec.c for documentation.
1883 : */
1884 : int
1885 0 : pqGetline3(PGconn *conn, char *s, int maxlen)
1886 : {
1887 : int status;
1888 :
1889 0 : if (conn->sock == PGINVALID_SOCKET ||
1890 0 : (conn->asyncStatus != PGASYNC_COPY_OUT &&
1891 0 : conn->asyncStatus != PGASYNC_COPY_BOTH) ||
1892 0 : conn->copy_is_binary)
1893 : {
1894 0 : libpq_append_conn_error(conn, "PQgetline: not doing text COPY OUT");
1895 0 : *s = '\0';
1896 0 : return EOF;
1897 : }
1898 :
1899 0 : while ((status = PQgetlineAsync(conn, s, maxlen - 1)) == 0)
1900 : {
1901 : /* need to load more data */
1902 0 : if (pqWait(true, false, conn) ||
1903 0 : pqReadData(conn) < 0)
1904 : {
1905 0 : *s = '\0';
1906 0 : return EOF;
1907 : }
1908 : }
1909 :
1910 0 : if (status < 0)
1911 : {
1912 : /* End of copy detected; gin up old-style terminator */
1913 0 : strcpy(s, "\\.");
1914 0 : return 0;
1915 : }
1916 :
1917 : /* Add null terminator, and strip trailing \n if present */
1918 0 : if (s[status - 1] == '\n')
1919 : {
1920 0 : s[status - 1] = '\0';
1921 0 : return 0;
1922 : }
1923 : else
1924 : {
1925 0 : s[status] = '\0';
1926 0 : return 1;
1927 : }
1928 : }
1929 :
1930 : /*
1931 : * PQgetlineAsync - gets a COPY data row without blocking.
1932 : *
1933 : * See fe-exec.c for documentation.
1934 : */
1935 : int
1936 0 : pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)
1937 : {
1938 : int msgLength;
1939 : int avail;
1940 :
1941 0 : if (conn->asyncStatus != PGASYNC_COPY_OUT
1942 0 : && conn->asyncStatus != PGASYNC_COPY_BOTH)
1943 0 : return -1; /* we are not doing a copy... */
1944 :
1945 : /*
1946 : * Recognize the next input message. To make life simpler for async
1947 : * callers, we keep returning 0 until the next message is fully available
1948 : * even if it is not Copy Data. This should keep PQendcopy from blocking.
1949 : * (Note: unlike pqGetCopyData3, we do not change asyncStatus here.)
1950 : */
1951 0 : msgLength = getCopyDataMessage(conn);
1952 0 : if (msgLength < 0)
1953 0 : return -1; /* end-of-copy or error */
1954 0 : if (msgLength == 0)
1955 0 : return 0; /* no data yet */
1956 :
1957 : /*
1958 : * Move data from libpq's buffer to the caller's. In the case where a
1959 : * prior call found the caller's buffer too small, we use
1960 : * conn->copy_already_done to remember how much of the row was already
1961 : * returned to the caller.
1962 : */
1963 0 : conn->inCursor += conn->copy_already_done;
1964 0 : avail = msgLength - 4 - conn->copy_already_done;
1965 0 : if (avail <= bufsize)
1966 : {
1967 : /* Able to consume the whole message */
1968 0 : memcpy(buffer, &conn->inBuffer[conn->inCursor], avail);
1969 : /* Mark message consumed */
1970 0 : conn->inStart = conn->inCursor + avail;
1971 : /* Reset state for next time */
1972 0 : conn->copy_already_done = 0;
1973 0 : return avail;
1974 : }
1975 : else
1976 : {
1977 : /* We must return a partial message */
1978 0 : memcpy(buffer, &conn->inBuffer[conn->inCursor], bufsize);
1979 : /* The message is NOT consumed from libpq's buffer */
1980 0 : conn->copy_already_done += bufsize;
1981 0 : return bufsize;
1982 : }
1983 : }
1984 :
1985 : /*
1986 : * PQendcopy
1987 : *
1988 : * See fe-exec.c for documentation.
1989 : */
1990 : int
1991 376 : pqEndcopy3(PGconn *conn)
1992 : {
1993 : PGresult *result;
1994 :
1995 376 : if (conn->asyncStatus != PGASYNC_COPY_IN &&
1996 364 : conn->asyncStatus != PGASYNC_COPY_OUT &&
1997 0 : conn->asyncStatus != PGASYNC_COPY_BOTH)
1998 : {
1999 0 : libpq_append_conn_error(conn, "no COPY in progress");
2000 0 : return 1;
2001 : }
2002 :
2003 : /* Send the CopyDone message if needed */
2004 376 : if (conn->asyncStatus == PGASYNC_COPY_IN ||
2005 364 : conn->asyncStatus == PGASYNC_COPY_BOTH)
2006 : {
2007 24 : if (pqPutMsgStart(PqMsg_CopyDone, conn) < 0 ||
2008 12 : pqPutMsgEnd(conn) < 0)
2009 0 : return 1;
2010 :
2011 : /*
2012 : * If we sent the COPY command in extended-query mode, we must issue a
2013 : * Sync as well.
2014 : */
2015 12 : if (conn->cmd_queue_head &&
2016 12 : conn->cmd_queue_head->queryclass != PGQUERY_SIMPLE)
2017 : {
2018 0 : if (pqPutMsgStart(PqMsg_Sync, conn) < 0 ||
2019 0 : pqPutMsgEnd(conn) < 0)
2020 0 : return 1;
2021 : }
2022 : }
2023 :
2024 : /*
2025 : * make sure no data is waiting to be sent, abort if we are non-blocking
2026 : * and the flush fails
2027 : */
2028 376 : if (pqFlush(conn) && pqIsnonblocking(conn))
2029 0 : return 1;
2030 :
2031 : /* Return to active duty */
2032 376 : conn->asyncStatus = PGASYNC_BUSY;
2033 :
2034 : /*
2035 : * Non blocking connections may have to abort at this point. If everyone
2036 : * played the game there should be no problem, but in error scenarios the
2037 : * expected messages may not have arrived yet. (We are assuming that the
2038 : * backend's packetizing will ensure that CommandComplete arrives along
2039 : * with the CopyDone; are there corner cases where that doesn't happen?)
2040 : */
2041 376 : if (pqIsnonblocking(conn) && PQisBusy(conn))
2042 0 : return 1;
2043 :
2044 : /* Wait for the completion response */
2045 376 : result = PQgetResult(conn);
2046 :
2047 : /* Expecting a successful result */
2048 376 : if (result && result->resultStatus == PGRES_COMMAND_OK)
2049 : {
2050 376 : PQclear(result);
2051 376 : return 0;
2052 : }
2053 :
2054 : /*
2055 : * Trouble. For backwards-compatibility reasons, we issue the error
2056 : * message as if it were a notice (would be nice to get rid of this
2057 : * silliness, but too many apps probably don't handle errors from
2058 : * PQendcopy reasonably). Note that the app can still obtain the error
2059 : * status from the PGconn object.
2060 : */
2061 0 : if (conn->errorMessage.len > 0)
2062 : {
2063 : /* We have to strip the trailing newline ... pain in neck... */
2064 0 : char svLast = conn->errorMessage.data[conn->errorMessage.len - 1];
2065 :
2066 0 : if (svLast == '\n')
2067 0 : conn->errorMessage.data[conn->errorMessage.len - 1] = '\0';
2068 0 : pqInternalNotice(&conn->noticeHooks, "%s", conn->errorMessage.data);
2069 0 : conn->errorMessage.data[conn->errorMessage.len - 1] = svLast;
2070 : }
2071 :
2072 0 : PQclear(result);
2073 :
2074 0 : return 1;
2075 : }
2076 :
2077 :
2078 : /*
2079 : * PQfn - Send a function call to the POSTGRES backend.
2080 : *
2081 : * See fe-exec.c for documentation.
2082 : */
2083 : PGresult *
2084 2208 : pqFunctionCall3(PGconn *conn, Oid fnid,
2085 : int *result_buf, int *actual_result_len,
2086 : int result_is_int,
2087 : const PQArgBlock *args, int nargs)
2088 : {
2089 2208 : bool needInput = false;
2090 2208 : ExecStatusType status = PGRES_FATAL_ERROR;
2091 : char id;
2092 : int msgLength;
2093 : int avail;
2094 : int i;
2095 :
2096 : /* already validated by PQfn */
2097 : Assert(conn->pipelineStatus == PQ_PIPELINE_OFF);
2098 :
2099 : /* PQfn already validated connection state */
2100 :
2101 4416 : if (pqPutMsgStart(PqMsg_FunctionCall, conn) < 0 ||
2102 4416 : pqPutInt(fnid, 4, conn) < 0 || /* function id */
2103 4416 : pqPutInt(1, 2, conn) < 0 || /* # of format codes */
2104 4416 : pqPutInt(1, 2, conn) < 0 || /* format code: BINARY */
2105 2208 : pqPutInt(nargs, 2, conn) < 0) /* # of args */
2106 : {
2107 : /* error message should be set up already */
2108 0 : return NULL;
2109 : }
2110 :
2111 6382 : for (i = 0; i < nargs; ++i)
2112 : { /* len.int4 + contents */
2113 4174 : if (pqPutInt(args[i].len, 4, conn))
2114 0 : return NULL;
2115 4174 : if (args[i].len == -1)
2116 0 : continue; /* it's NULL */
2117 :
2118 4174 : if (args[i].isint)
2119 : {
2120 3184 : if (pqPutInt(args[i].u.integer, args[i].len, conn))
2121 0 : return NULL;
2122 : }
2123 : else
2124 : {
2125 990 : if (pqPutnchar(args[i].u.ptr, args[i].len, conn))
2126 0 : return NULL;
2127 : }
2128 : }
2129 :
2130 2208 : if (pqPutInt(1, 2, conn) < 0) /* result format code: BINARY */
2131 0 : return NULL;
2132 :
2133 4416 : if (pqPutMsgEnd(conn) < 0 ||
2134 2208 : pqFlush(conn))
2135 0 : return NULL;
2136 :
2137 : for (;;)
2138 : {
2139 7100 : if (needInput)
2140 : {
2141 : /* Wait for some data to arrive (or for the channel to close) */
2142 5368 : if (pqWait(true, false, conn) ||
2143 2684 : pqReadData(conn) < 0)
2144 : break;
2145 : }
2146 :
2147 : /*
2148 : * Scan the message. If we run out of data, loop around to try again.
2149 : */
2150 7100 : needInput = true;
2151 :
2152 7100 : conn->inCursor = conn->inStart;
2153 7100 : if (pqGetc(&id, conn))
2154 2208 : continue;
2155 4892 : if (pqGetInt(&msgLength, 4, conn))
2156 0 : continue;
2157 :
2158 : /*
2159 : * Try to validate message type/length here. A length less than 4 is
2160 : * definitely broken. Large lengths should only be believed for a few
2161 : * message types.
2162 : */
2163 4892 : if (msgLength < 4)
2164 : {
2165 0 : handleSyncLoss(conn, id, msgLength);
2166 0 : break;
2167 : }
2168 4892 : if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
2169 : {
2170 0 : handleSyncLoss(conn, id, msgLength);
2171 0 : break;
2172 : }
2173 :
2174 : /*
2175 : * Can't process if message body isn't all here yet.
2176 : */
2177 4892 : msgLength -= 4;
2178 4892 : avail = conn->inEnd - conn->inCursor;
2179 4892 : if (avail < msgLength)
2180 : {
2181 : /*
2182 : * Before looping, enlarge the input buffer if needed to hold the
2183 : * whole message. See notes in parseInput.
2184 : */
2185 476 : if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
2186 : conn))
2187 : {
2188 : /*
2189 : * XXX add some better recovery code... plan is to skip over
2190 : * the message using its length, then report an error. For the
2191 : * moment, just treat this like loss of sync (which indeed it
2192 : * might be!)
2193 : */
2194 0 : handleSyncLoss(conn, id, msgLength);
2195 0 : break;
2196 : }
2197 476 : continue;
2198 : }
2199 :
2200 : /*
2201 : * We should see V or E response to the command, but might get N
2202 : * and/or A notices first. We also need to swallow the final Z before
2203 : * returning.
2204 : */
2205 4416 : switch (id)
2206 : {
2207 2208 : case 'V': /* function result */
2208 2208 : if (pqGetInt(actual_result_len, 4, conn))
2209 0 : continue;
2210 2208 : if (*actual_result_len != -1)
2211 : {
2212 2208 : if (result_is_int)
2213 : {
2214 1436 : if (pqGetInt(result_buf, *actual_result_len, conn))
2215 0 : continue;
2216 : }
2217 : else
2218 : {
2219 772 : if (pqGetnchar(result_buf,
2220 772 : *actual_result_len,
2221 : conn))
2222 0 : continue;
2223 : }
2224 : }
2225 : /* correctly finished function result message */
2226 2208 : status = PGRES_COMMAND_OK;
2227 2208 : break;
2228 0 : case 'E': /* error return */
2229 0 : if (pqGetErrorNotice3(conn, true))
2230 0 : continue;
2231 0 : status = PGRES_FATAL_ERROR;
2232 0 : break;
2233 0 : case 'A': /* notify message */
2234 : /* handle notify and go back to processing return values */
2235 0 : if (getNotify(conn))
2236 0 : continue;
2237 0 : break;
2238 0 : case 'N': /* notice */
2239 : /* handle notice and go back to processing return values */
2240 0 : if (pqGetErrorNotice3(conn, false))
2241 0 : continue;
2242 0 : break;
2243 2208 : case 'Z': /* backend is ready for new query */
2244 2208 : if (getReadyForQuery(conn))
2245 0 : continue;
2246 :
2247 : /* consume the message */
2248 2208 : pqParseDone(conn, conn->inStart + 5 + msgLength);
2249 :
2250 : /*
2251 : * If we already have a result object (probably an error), use
2252 : * that. Otherwise, if we saw a function result message,
2253 : * report COMMAND_OK. Otherwise, the backend violated the
2254 : * protocol, so complain.
2255 : */
2256 2208 : if (!pgHavePendingResult(conn))
2257 : {
2258 2208 : if (status == PGRES_COMMAND_OK)
2259 : {
2260 2208 : conn->result = PQmakeEmptyPGresult(conn, status);
2261 2208 : if (!conn->result)
2262 : {
2263 0 : libpq_append_conn_error(conn, "out of memory");
2264 0 : pqSaveErrorResult(conn);
2265 : }
2266 : }
2267 : else
2268 : {
2269 0 : libpq_append_conn_error(conn, "protocol error: no function result");
2270 0 : pqSaveErrorResult(conn);
2271 : }
2272 : }
2273 : /* and we're out */
2274 2208 : return pqPrepareAsyncResult(conn);
2275 0 : case 'S': /* parameter status */
2276 0 : if (getParameterStatus(conn))
2277 0 : continue;
2278 0 : break;
2279 0 : default:
2280 : /* The backend violates the protocol. */
2281 0 : libpq_append_conn_error(conn, "protocol error: id=0x%x", id);
2282 0 : pqSaveErrorResult(conn);
2283 :
2284 : /*
2285 : * We can't call parsing done due to the protocol violation
2286 : * (so message tracing wouldn't work), but trust the specified
2287 : * message length as what to skip.
2288 : */
2289 0 : conn->inStart += 5 + msgLength;
2290 0 : return pqPrepareAsyncResult(conn);
2291 : }
2292 :
2293 : /* Completed parsing this message, keep going */
2294 2208 : pqParseDone(conn, conn->inStart + 5 + msgLength);
2295 2208 : needInput = false;
2296 : }
2297 :
2298 : /*
2299 : * We fall out of the loop only upon failing to read data.
2300 : * conn->errorMessage has been set by pqWait or pqReadData. We want to
2301 : * append it to any already-received error message.
2302 : */
2303 0 : pqSaveErrorResult(conn);
2304 0 : return pqPrepareAsyncResult(conn);
2305 : }
2306 :
2307 :
2308 : /*
2309 : * Construct startup packet
2310 : *
2311 : * Returns a malloc'd packet buffer, or NULL if out of memory
2312 : */
2313 : char *
2314 26712 : pqBuildStartupPacket3(PGconn *conn, int *packetlen,
2315 : const PQEnvironmentOption *options)
2316 : {
2317 : char *startpacket;
2318 :
2319 26712 : *packetlen = build_startup_packet(conn, NULL, options);
2320 26712 : startpacket = (char *) malloc(*packetlen);
2321 26712 : if (!startpacket)
2322 0 : return NULL;
2323 26712 : *packetlen = build_startup_packet(conn, startpacket, options);
2324 26712 : return startpacket;
2325 : }
2326 :
2327 : /*
2328 : * Build a startup packet given a filled-in PGconn structure.
2329 : *
2330 : * We need to figure out how much space is needed, then fill it in.
2331 : * To avoid duplicate logic, this routine is called twice: the first time
2332 : * (with packet == NULL) just counts the space needed, the second time
2333 : * (with packet == allocated space) fills it in. Return value is the number
2334 : * of bytes used.
2335 : */
2336 : static int
2337 53424 : build_startup_packet(const PGconn *conn, char *packet,
2338 : const PQEnvironmentOption *options)
2339 : {
2340 53424 : int packet_len = 0;
2341 : const PQEnvironmentOption *next_eo;
2342 : const char *val;
2343 :
2344 : /* Protocol version comes first. */
2345 53424 : if (packet)
2346 : {
2347 26712 : ProtocolVersion pv = pg_hton32(conn->pversion);
2348 :
2349 26712 : memcpy(packet + packet_len, &pv, sizeof(ProtocolVersion));
2350 : }
2351 53424 : packet_len += sizeof(ProtocolVersion);
2352 :
2353 : /* Add user name, database name, options */
2354 :
2355 : #define ADD_STARTUP_OPTION(optname, optval) \
2356 : do { \
2357 : if (packet) \
2358 : strcpy(packet + packet_len, optname); \
2359 : packet_len += strlen(optname) + 1; \
2360 : if (packet) \
2361 : strcpy(packet + packet_len, optval); \
2362 : packet_len += strlen(optval) + 1; \
2363 : } while(0)
2364 :
2365 53424 : if (conn->pguser && conn->pguser[0])
2366 53424 : ADD_STARTUP_OPTION("user", conn->pguser);
2367 53424 : if (conn->dbName && conn->dbName[0])
2368 53424 : ADD_STARTUP_OPTION("database", conn->dbName);
2369 53424 : if (conn->replication && conn->replication[0])
2370 5792 : ADD_STARTUP_OPTION("replication", conn->replication);
2371 53424 : if (conn->pgoptions && conn->pgoptions[0])
2372 15132 : ADD_STARTUP_OPTION("options", conn->pgoptions);
2373 53424 : if (conn->send_appname)
2374 : {
2375 : /* Use appname if present, otherwise use fallback */
2376 53424 : val = conn->appname ? conn->appname : conn->fbappname;
2377 53424 : if (val && val[0])
2378 53412 : ADD_STARTUP_OPTION("application_name", val);
2379 : }
2380 :
2381 53424 : if (conn->client_encoding_initial && conn->client_encoding_initial[0])
2382 3120 : ADD_STARTUP_OPTION("client_encoding", conn->client_encoding_initial);
2383 :
2384 : /* Add any environment-driven GUC settings needed */
2385 213696 : for (next_eo = options; next_eo->envName; next_eo++)
2386 : {
2387 160272 : if ((val = getenv(next_eo->envName)) != NULL)
2388 : {
2389 19144 : if (pg_strcasecmp(val, "default") != 0)
2390 19144 : ADD_STARTUP_OPTION(next_eo->pgName, val);
2391 : }
2392 : }
2393 :
2394 : /* Add trailing terminator */
2395 53424 : if (packet)
2396 26712 : packet[packet_len] = '\0';
2397 53424 : packet_len++;
2398 :
2399 53424 : return packet_len;
2400 : }
|