1 /*-------------------------------------------------------------------------
4 * functions that are specific to frontend/backend protocol version 3
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/interfaces/libpq/fe-protocol3.c
13 *-------------------------------------------------------------------------
15 #include "postgres_fe.h"
21 #include "libpq-int.h"
23 #include "mb/pg_wchar.h"
29 #include <netinet/in.h>
30 #ifdef HAVE_NETINET_TCP_H
31 #include <netinet/tcp.h>
33 #include <arpa/inet.h>
38 * This macro lists the backend message types that could be "long" (more
39 * than a couple of kilobytes).
41 #define VALID_LONG_MESSAGE_TYPE(id) \
42 ((id) == 'T' || (id) == 'D' || (id) == 'd' || (id) == 'V' || \
43 (id) == 'E' || (id) == 'N' || (id) == 'A')
46 static void handleSyncLoss(PGconn *conn, char id, int msgLength);
47 static int getRowDescriptions(PGconn *conn);
48 static int getParamDescriptions(PGconn *conn);
49 static int getAnotherTuple(PGconn *conn, int msgLength);
50 static int getParameterStatus(PGconn *conn);
51 static int getNotify(PGconn *conn);
52 static int getCopyStart(PGconn *conn, ExecStatusType copytype);
53 static int getReadyForQuery(PGconn *conn);
54 static void reportErrorPosition(PQExpBuffer msg, const char *query,
55 int loc, int encoding);
56 static int build_startup_packet(const PGconn *conn, char *packet,
57 const PQEnvironmentOption *options);
61 * parseInput: if appropriate, parse input data from backend
62 * until input is exhausted or a stopping state is reached.
63 * Note that this function will NOT attempt to read more data from the backend.
66 pqParseInput3(PGconn *conn)
73 * Loop to parse successive complete messages available in the buffer.
78 * Try to read a message. First get the type code and length. Return
81 conn->inCursor = conn->inStart;
82 if (pqGetc(&id, conn))
84 if (pqGetInt(&msgLength, 4, conn))
88 * Try to validate message type/length here. A length less than 4 is
89 * definitely broken. Large lengths should only be believed for a few
94 handleSyncLoss(conn, id, msgLength);
97 if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
99 handleSyncLoss(conn, id, msgLength);
104 * Can't process if message body isn't all here yet.
107 avail = conn->inEnd - conn->inCursor;
108 if (avail < msgLength)
111 * Before returning, enlarge the input buffer if needed to hold
112 * the whole message. This is better than leaving it to
113 * pqReadData because we can avoid multiple cycles of realloc()
114 * when the message is large; also, we can implement a reasonable
115 * recovery strategy if we are unable to make the buffer big
118 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
122 * XXX add some better recovery code... plan is to skip over
123 * the message using its length, then report an error. For the
124 * moment, just treat this like loss of sync (which indeed it
127 handleSyncLoss(conn, id, msgLength);
133 * NOTIFY and NOTICE messages can happen in any state; always process
136 * Most other messages should only be processed while in BUSY state.
137 * (In particular, in READY state we hold off further parsing until
138 * the application collects the current PGresult.)
140 * However, if the state is IDLE then we got trouble; we need to deal
141 * with the unexpected message somehow.
143 * ParameterStatus ('S') messages are a special case: in IDLE state we
144 * must process 'em (this case could happen if a new value was adopted
145 * from config file due to SIGHUP), but otherwise we hold off until
155 if (pqGetErrorNotice3(conn, false))
158 else if (conn->asyncStatus != PGASYNC_BUSY)
160 /* If not IDLE state, just wait ... */
161 if (conn->asyncStatus != PGASYNC_IDLE)
165 * Unexpected message in IDLE state; need to recover somehow.
166 * ERROR messages are displayed using the notice processor;
167 * ParameterStatus is handled normally; anything else is just
168 * dropped on the floor after displaying a suitable warning
169 * notice. (An ERROR is very possibly the backend telling us why
170 * it is about to close the connection, so we don't want to just
175 if (pqGetErrorNotice3(conn, false /* treat as notice */ ))
180 if (getParameterStatus(conn))
185 pqInternalNotice(&conn->noticeHooks,
186 "message type 0x%02x arrived from server while idle",
188 /* Discard the unexpected message */
189 conn->inCursor += msgLength;
195 * In BUSY state, we can process everything.
199 case 'C': /* command complete */
200 if (pqGets(&conn->workBuffer, conn))
202 if (conn->result == NULL)
204 conn->result = PQmakeEmptyPGresult(conn,
209 strncpy(conn->result->cmdStatus, conn->workBuffer.data,
211 conn->asyncStatus = PGASYNC_READY;
213 case 'E': /* error return */
214 if (pqGetErrorNotice3(conn, true))
216 conn->asyncStatus = PGASYNC_READY;
218 case 'Z': /* backend is ready for new query */
219 if (getReadyForQuery(conn))
221 conn->asyncStatus = PGASYNC_IDLE;
223 case 'I': /* empty query */
224 if (conn->result == NULL)
226 conn->result = PQmakeEmptyPGresult(conn,
231 conn->asyncStatus = PGASYNC_READY;
233 case '1': /* Parse Complete */
234 /* If we're doing PQprepare, we're done; else ignore */
235 if (conn->queryclass == PGQUERY_PREPARE)
237 if (conn->result == NULL)
239 conn->result = PQmakeEmptyPGresult(conn,
244 conn->asyncStatus = PGASYNC_READY;
247 case '2': /* Bind Complete */
248 case '3': /* Close Complete */
249 /* Nothing to do for these message types */
251 case 'S': /* parameter status */
252 if (getParameterStatus(conn))
255 case 'K': /* secret key data from the backend */
258 * This is expected only during backend startup, but it's
259 * just as easy to handle it as part of the main loop.
260 * Save the data and continue processing.
262 if (pqGetInt(&(conn->be_pid), 4, conn))
264 if (pqGetInt(&(conn->be_key), 4, conn))
267 case 'T': /* Row Description */
268 if (conn->result == NULL ||
269 conn->queryclass == PGQUERY_DESCRIBE)
271 /* First 'T' in a query sequence */
272 if (getRowDescriptions(conn))
276 * If we're doing a Describe, we're ready to pass the
277 * result back to the client.
279 if (conn->queryclass == PGQUERY_DESCRIBE)
280 conn->asyncStatus = PGASYNC_READY;
285 * A new 'T' message is treated as the start of
286 * another PGresult. (It is not clear that this is
287 * really possible with the current backend.) We stop
288 * parsing until the application accepts the current
291 conn->asyncStatus = PGASYNC_READY;
295 case 'n': /* No Data */
298 * NoData indicates that we will not be seeing a
299 * RowDescription message because the statement or portal
300 * inquired about doesn't return rows.
302 * If we're doing a Describe, we have to pass something
303 * back to the client, so set up a COMMAND_OK result,
304 * instead of TUPLES_OK. Otherwise we can just ignore
307 if (conn->queryclass == PGQUERY_DESCRIBE)
309 if (conn->result == NULL)
311 conn->result = PQmakeEmptyPGresult(conn,
316 conn->asyncStatus = PGASYNC_READY;
319 case 't': /* Parameter Description */
320 if (getParamDescriptions(conn))
323 case 'D': /* Data Row */
324 if (conn->result != NULL &&
325 conn->result->resultStatus == PGRES_TUPLES_OK)
327 /* Read another tuple of a normal query response */
328 if (getAnotherTuple(conn, msgLength))
331 else if (conn->result != NULL &&
332 conn->result->resultStatus == PGRES_FATAL_ERROR)
335 * We've already choked for some reason. Just discard
336 * tuples till we get to the end of the query.
338 conn->inCursor += msgLength;
342 /* Set up to report error at end of query */
343 printfPQExpBuffer(&conn->errorMessage,
344 libpq_gettext("server sent data (\"D\" message) without prior row description (\"T\" message)\n"));
345 pqSaveErrorResult(conn);
346 /* Discard the unexpected message */
347 conn->inCursor += msgLength;
350 case 'G': /* Start Copy In */
351 if (getCopyStart(conn, PGRES_COPY_IN))
353 conn->asyncStatus = PGASYNC_COPY_IN;
355 case 'H': /* Start Copy Out */
356 if (getCopyStart(conn, PGRES_COPY_OUT))
358 conn->asyncStatus = PGASYNC_COPY_OUT;
359 conn->copy_already_done = 0;
361 case 'W': /* Start Copy Both */
362 if (getCopyStart(conn, PGRES_COPY_BOTH))
364 conn->asyncStatus = PGASYNC_COPY_BOTH;
365 conn->copy_already_done = 0;
367 case 'd': /* Copy Data */
370 * If we see Copy Data, just silently drop it. This would
371 * only occur if application exits COPY OUT mode too
374 conn->inCursor += msgLength;
376 case 'c': /* Copy Done */
379 * If we see Copy Done, just silently drop it. This is
380 * the normal case during PQendcopy. We will keep
381 * swallowing data, expecting to see command-complete for
386 printfPQExpBuffer(&conn->errorMessage,
388 "unexpected response from server; first received character was \"%c\"\n"),
390 /* build an error result holding the error message */
391 pqSaveErrorResult(conn);
392 /* not sure if we will see more, so go to ready state */
393 conn->asyncStatus = PGASYNC_READY;
394 /* Discard the unexpected message */
395 conn->inCursor += msgLength;
397 } /* switch on protocol character */
399 /* Successfully consumed this message */
400 if (conn->inCursor == conn->inStart + 5 + msgLength)
402 /* Normal case: parsing agrees with specified length */
403 conn->inStart = conn->inCursor;
407 /* Trouble --- report it */
408 printfPQExpBuffer(&conn->errorMessage,
409 libpq_gettext("message contents do not agree with length in message type \"%c\"\n"),
411 /* build an error result holding the error message */
412 pqSaveErrorResult(conn);
413 conn->asyncStatus = PGASYNC_READY;
414 /* trust the specified message length as what to skip */
415 conn->inStart += 5 + msgLength;
421 * handleSyncLoss: clean up after loss of message-boundary sync
423 * There isn't really a lot we can do here except abandon the connection.
426 handleSyncLoss(PGconn *conn, char id, int msgLength)
428 printfPQExpBuffer(&conn->errorMessage,
430 "lost synchronization with server: got message type \"%c\", length %d\n"),
432 /* build an error result holding the error message */
433 pqSaveErrorResult(conn);
434 conn->asyncStatus = PGASYNC_READY; /* drop out of GetResult wait loop */
436 pqsecure_close(conn);
437 closesocket(conn->sock);
439 conn->status = CONNECTION_BAD; /* No more connection to backend */
443 * parseInput subroutine to read a 'T' (row descriptions) message.
444 * We'll build a new PGresult structure (unless called for a Describe
445 * command for a prepared statement) containing the attribute data.
446 * Returns: 0 if completed message, EOF if not enough data yet.
448 * Note that if we run out of data, we have to release the partially
449 * constructed PGresult, and rebuild it again next time. Fortunately,
450 * that shouldn't happen often, since 'T' messages usually fit in a packet.
453 getRowDescriptions(PGconn *conn)
460 * When doing Describe for a prepared statement, there'll already be a
461 * PGresult created by getParamDescriptions, and we should fill data into
462 * that. Otherwise, create a new, empty PGresult.
464 if (conn->queryclass == PGQUERY_DESCRIBE)
467 result = conn->result;
469 result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
472 result = PQmakeEmptyPGresult(conn, PGRES_TUPLES_OK);
476 /* parseInput already read the 'T' label and message length. */
477 /* the next two bytes are the number of fields */
478 if (pqGetInt(&(result->numAttributes), 2, conn))
480 nfields = result->numAttributes;
482 /* allocate space for the attribute descriptors */
485 result->attDescs = (PGresAttDesc *)
486 pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
487 if (!result->attDescs)
489 MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
492 /* result->binary is true only if ALL columns are binary */
493 result->binary = (nfields > 0) ? 1 : 0;
496 for (i = 0; i < nfields; i++)
505 if (pqGets(&conn->workBuffer, conn) ||
506 pqGetInt(&tableid, 4, conn) ||
507 pqGetInt(&columnid, 2, conn) ||
508 pqGetInt(&typid, 4, conn) ||
509 pqGetInt(&typlen, 2, conn) ||
510 pqGetInt(&atttypmod, 4, conn) ||
511 pqGetInt(&format, 2, conn))
517 * Since pqGetInt treats 2-byte integers as unsigned, we need to
518 * coerce these results to signed form.
520 columnid = (int) ((int16) columnid);
521 typlen = (int) ((int16) typlen);
522 format = (int) ((int16) format);
524 result->attDescs[i].name = pqResultStrdup(result,
525 conn->workBuffer.data);
526 if (!result->attDescs[i].name)
528 result->attDescs[i].tableid = tableid;
529 result->attDescs[i].columnid = columnid;
530 result->attDescs[i].format = format;
531 result->attDescs[i].typid = typid;
532 result->attDescs[i].typlen = typlen;
533 result->attDescs[i].atttypmod = atttypmod;
540 conn->result = result;
546 * Discard incomplete result, unless it's from getParamDescriptions.
548 * Note that if we hit a bufferload boundary while handling the
549 * describe-statement case, we'll forget any PGresult space we just
550 * allocated, and then reallocate it on next try. This will bloat the
551 * PGresult a little bit but the space will be freed at PQclear, so it
552 * doesn't seem worth trying to be smarter.
554 if (result != conn->result)
560 * parseInput subroutine to read a 't' (ParameterDescription) message.
561 * We'll build a new PGresult structure containing the parameter data.
562 * Returns: 0 if completed message, EOF if not enough data yet.
564 * Note that if we run out of data, we have to release the partially
565 * constructed PGresult, and rebuild it again next time. Fortunately,
566 * that shouldn't happen often, since 't' messages usually fit in a packet.
569 getParamDescriptions(PGconn *conn)
575 result = PQmakeEmptyPGresult(conn, PGRES_COMMAND_OK);
579 /* parseInput already read the 't' label and message length. */
580 /* the next two bytes are the number of parameters */
581 if (pqGetInt(&(result->numParameters), 2, conn))
583 nparams = result->numParameters;
585 /* allocate space for the parameter descriptors */
588 result->paramDescs = (PGresParamDesc *)
589 pqResultAlloc(result, nparams * sizeof(PGresParamDesc), TRUE);
590 if (!result->paramDescs)
592 MemSet(result->paramDescs, 0, nparams * sizeof(PGresParamDesc));
595 /* get parameter info */
596 for (i = 0; i < nparams; i++)
600 if (pqGetInt(&typid, 4, conn))
602 result->paramDescs[i].typid = typid;
606 conn->result = result;
615 * parseInput subroutine to read a 'D' (row data) message.
616 * We add another tuple to the existing PGresult structure.
617 * Returns: 0 if completed message, EOF if error or not enough data yet.
619 * Note that if we run out of data, we have to suspend and reprocess
620 * the message after more data is received. We keep a partially constructed
621 * tuple in conn->curTuple, and avoid reallocating already-allocated storage.
624 getAnotherTuple(PGconn *conn, int msgLength)
626 PGresult *result = conn->result;
627 int nfields = result->numAttributes;
629 int tupnfields; /* # fields from tuple */
630 int vlen; /* length of the current field value */
633 /* Allocate tuple space if first time for this data message */
634 if (conn->curTuple == NULL)
636 conn->curTuple = (PGresAttValue *)
637 pqResultAlloc(result, nfields * sizeof(PGresAttValue), TRUE);
638 if (conn->curTuple == NULL)
640 MemSet(conn->curTuple, 0, nfields * sizeof(PGresAttValue));
642 tup = conn->curTuple;
644 /* Get the field count and make sure it's what we expect */
645 if (pqGetInt(&tupnfields, 2, conn))
648 if (tupnfields != nfields)
650 /* Replace partially constructed result with an error result */
651 printfPQExpBuffer(&conn->errorMessage,
652 libpq_gettext("unexpected field count in \"D\" message\n"));
653 pqSaveErrorResult(conn);
654 /* Discard the failed message by pretending we read it */
655 conn->inCursor = conn->inStart + 5 + msgLength;
659 /* Scan the fields */
660 for (i = 0; i < nfields; i++)
662 /* get the value length */
663 if (pqGetInt(&vlen, 4, conn))
668 tup[i].value = result->null_field;
669 tup[i].len = NULL_LEN;
674 if (tup[i].value == NULL)
676 bool isbinary = (result->attDescs[i].format != 0);
678 tup[i].value = (char *) pqResultAlloc(result, vlen + 1, isbinary);
679 if (tup[i].value == NULL)
683 /* read in the value */
685 if (pqGetnchar((char *) (tup[i].value), vlen, conn))
687 /* we have to terminate this ourselves */
688 tup[i].value[vlen] = '\0';
691 /* Success! Store the completed tuple in the result */
692 if (!pqAddTuple(result, tup))
694 /* and reset for a new message */
695 conn->curTuple = NULL;
702 * Replace partially constructed result with an error result. First
703 * discard the old result to try to win back some memory.
705 pqClearAsyncResult(conn);
706 printfPQExpBuffer(&conn->errorMessage,
707 libpq_gettext("out of memory for query result\n"));
708 pqSaveErrorResult(conn);
710 /* Discard the failed message by pretending we read it */
711 conn->inCursor = conn->inStart + 5 + msgLength;
717 * Attempt to read an Error or Notice response message.
718 * This is possible in several places, so we break it out as a subroutine.
719 * Entry: 'E' or 'N' message type and length have already been consumed.
720 * Exit: returns 0 if successfully consumed message.
721 * returns EOF if not enough data.
724 pqGetErrorNotice3(PGconn *conn, bool isError)
726 PGresult *res = NULL;
727 PQExpBufferData workBuf;
730 const char *querytext = NULL;
734 * Since the fields might be pretty long, we create a temporary
735 * PQExpBuffer rather than using conn->workBuffer. workBuffer is intended
736 * for stuff that is expected to be short. We shouldn't use
737 * conn->errorMessage either, since this might be only a notice.
739 initPQExpBuffer(&workBuf);
742 * Make a PGresult to hold the accumulated fields. We temporarily lie
743 * about the result status, so that PQmakeEmptyPGresult doesn't uselessly
744 * copy conn->errorMessage.
746 res = PQmakeEmptyPGresult(conn, PGRES_EMPTY_QUERY);
749 res->resultStatus = isError ? PGRES_FATAL_ERROR : PGRES_NONFATAL_ERROR;
752 * Read the fields and save into res.
756 if (pqGetc(&id, conn))
759 break; /* terminator found */
760 if (pqGets(&workBuf, conn))
762 pqSaveMessageField(res, id, workBuf.data);
766 * Now build the "overall" error message for PQresultErrorMessage.
768 * Also, save the SQLSTATE in conn->last_sqlstate.
770 resetPQExpBuffer(&workBuf);
771 val = PQresultErrorField(res, PG_DIAG_SEVERITY);
773 appendPQExpBuffer(&workBuf, "%s: ", val);
774 val = PQresultErrorField(res, PG_DIAG_SQLSTATE);
777 if (strlen(val) < sizeof(conn->last_sqlstate))
778 strcpy(conn->last_sqlstate, val);
779 if (conn->verbosity == PQERRORS_VERBOSE)
780 appendPQExpBuffer(&workBuf, "%s: ", val);
782 val = PQresultErrorField(res, PG_DIAG_MESSAGE_PRIMARY);
784 appendPQExpBufferStr(&workBuf, val);
785 val = PQresultErrorField(res, PG_DIAG_STATEMENT_POSITION);
788 if (conn->verbosity != PQERRORS_TERSE && conn->last_query != NULL)
790 /* emit position as a syntax cursor display */
791 querytext = conn->last_query;
792 querypos = atoi(val);
796 /* emit position as text addition to primary message */
797 /* translator: %s represents a digit string */
798 appendPQExpBuffer(&workBuf, libpq_gettext(" at character %s"),
804 val = PQresultErrorField(res, PG_DIAG_INTERNAL_POSITION);
807 querytext = PQresultErrorField(res, PG_DIAG_INTERNAL_QUERY);
808 if (conn->verbosity != PQERRORS_TERSE && querytext != NULL)
810 /* emit position as a syntax cursor display */
811 querypos = atoi(val);
815 /* emit position as text addition to primary message */
816 /* translator: %s represents a digit string */
817 appendPQExpBuffer(&workBuf, libpq_gettext(" at character %s"),
822 appendPQExpBufferChar(&workBuf, '\n');
823 if (conn->verbosity != PQERRORS_TERSE)
825 if (querytext && querypos > 0)
826 reportErrorPosition(&workBuf, querytext, querypos,
827 conn->client_encoding);
828 val = PQresultErrorField(res, PG_DIAG_MESSAGE_DETAIL);
830 appendPQExpBuffer(&workBuf, libpq_gettext("DETAIL: %s\n"), val);
831 val = PQresultErrorField(res, PG_DIAG_MESSAGE_HINT);
833 appendPQExpBuffer(&workBuf, libpq_gettext("HINT: %s\n"), val);
834 val = PQresultErrorField(res, PG_DIAG_INTERNAL_QUERY);
836 appendPQExpBuffer(&workBuf, libpq_gettext("QUERY: %s\n"), val);
837 val = PQresultErrorField(res, PG_DIAG_CONTEXT);
839 appendPQExpBuffer(&workBuf, libpq_gettext("CONTEXT: %s\n"), val);
841 if (conn->verbosity == PQERRORS_VERBOSE)
846 valf = PQresultErrorField(res, PG_DIAG_SOURCE_FILE);
847 vall = PQresultErrorField(res, PG_DIAG_SOURCE_LINE);
848 val = PQresultErrorField(res, PG_DIAG_SOURCE_FUNCTION);
849 if (val || valf || vall)
851 appendPQExpBufferStr(&workBuf, libpq_gettext("LOCATION: "));
853 appendPQExpBuffer(&workBuf, libpq_gettext("%s, "), val);
854 if (valf && vall) /* unlikely we'd have just one */
855 appendPQExpBuffer(&workBuf, libpq_gettext("%s:%s"),
857 appendPQExpBufferChar(&workBuf, '\n');
862 * Either save error as current async result, or just emit the notice.
866 res->errMsg = pqResultStrdup(res, workBuf.data);
869 pqClearAsyncResult(conn);
871 appendPQExpBufferStr(&conn->errorMessage, workBuf.data);
875 /* We can cheat a little here and not copy the message. */
876 res->errMsg = workBuf.data;
877 if (res->noticeHooks.noticeRec != NULL)
878 (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
882 termPQExpBuffer(&workBuf);
887 termPQExpBuffer(&workBuf);
892 * Add an error-location display to the error message under construction.
894 * The cursor location is measured in logical characters; the query string
895 * is presumed to be in the specified encoding.
898 reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding)
900 #define DISPLAY_SIZE 60 /* screen width limit, in screen cols */
901 #define MIN_RIGHT_CUT 10 /* try to keep this far away from EOL */
918 /* Convert loc from 1-based to 0-based; no-op if out of range */
923 /* Need a writable copy of the query */
924 wquery = strdup(query);
926 return; /* fail silently if out of memory */
929 * Each character might occupy multiple physical bytes in the string, and
930 * in some Far Eastern character sets it might take more than one screen
931 * column as well. We compute the starting byte offset and starting
932 * screen column of each logical character, and store these in qidx[] and
933 * scridx[] respectively.
936 /* we need a safe allocation size... */
937 slen = strlen(wquery) + 1;
939 qidx = (int *) malloc(slen * sizeof(int));
945 scridx = (int *) malloc(slen * sizeof(int));
953 /* We can optimize a bit if it's a single-byte encoding */
954 mb_encoding = (pg_encoding_max_length(encoding) != 1);
957 * Within the scanning loop, cno is the current character's logical
958 * number, qoffset is its offset in wquery, and scroffset is its starting
959 * logical screen column (all indexed from 0). "loc" is the logical
960 * character number of the error location. We scan to determine loc_line
961 * (the 1-based line number containing loc) and ibeg/iend (first character
962 * number and last+1 character number of the line containing loc). Note
963 * that qidx[] and scridx[] are filled only as far as iend.
969 iend = -1; /* -1 means not set yet */
971 for (cno = 0; wquery[qoffset] != '\0'; cno++)
973 char ch = wquery[qoffset];
976 scridx[cno] = scroffset;
979 * Replace tabs with spaces in the writable copy. (Later we might
980 * want to think about coping with their variable screen width, but
984 wquery[qoffset] = ' ';
987 * If end-of-line, count lines and mark positions. Each \r or \n
988 * counts as a line except when \r \n appear together.
990 else if (ch == '\r' || ch == '\n')
996 wquery[qidx[cno - 1]] != '\r')
998 /* extract beginning = last line start before loc. */
1003 /* set extract end. */
1005 /* done scanning. */
1015 w = pg_encoding_dsplen(encoding, &wquery[qoffset]);
1016 /* treat any non-tab control chars as width 1 */
1020 qoffset += pg_encoding_mblen(encoding, &wquery[qoffset]);
1024 /* We assume wide chars only exist in multibyte encodings */
1029 /* Fix up if we didn't find an end-of-line after loc */
1032 iend = cno; /* query length in chars, +1 */
1033 qidx[iend] = qoffset;
1034 scridx[iend] = scroffset;
1037 /* Print only if loc is within computed query length */
1040 /* If the line extracted is too long, we truncate it. */
1043 if (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1046 * We first truncate right if it is enough. This code might be
1047 * off a space or so on enforcing MIN_RIGHT_CUT if there's a wide
1048 * character right there, but that should be okay.
1050 if (scridx[ibeg] + DISPLAY_SIZE >= scridx[loc] + MIN_RIGHT_CUT)
1052 while (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1058 /* Truncate right if not too close to loc. */
1059 while (scridx[loc] + MIN_RIGHT_CUT < scridx[iend])
1065 /* Truncate left if still too long. */
1066 while (scridx[iend] - scridx[ibeg] > DISPLAY_SIZE)
1074 /* truncate working copy at desired endpoint */
1075 wquery[qidx[iend]] = '\0';
1077 /* Begin building the finished message. */
1079 appendPQExpBuffer(msg, libpq_gettext("LINE %d: "), loc_line);
1081 appendPQExpBufferStr(msg, "...");
1084 * While we have the prefix in the msg buffer, compute its screen
1088 for (; i < msg->len; i += pg_encoding_mblen(encoding, &msg->data[i]))
1090 int w = pg_encoding_dsplen(encoding, &msg->data[i]);
1097 /* Finish up the LINE message line. */
1098 appendPQExpBufferStr(msg, &wquery[qidx[ibeg]]);
1100 appendPQExpBufferStr(msg, "...");
1101 appendPQExpBufferChar(msg, '\n');
1103 /* Now emit the cursor marker line. */
1104 scroffset += scridx[loc] - scridx[ibeg];
1105 for (i = 0; i < scroffset; i++)
1106 appendPQExpBufferChar(msg, ' ');
1107 appendPQExpBufferChar(msg, '^');
1108 appendPQExpBufferChar(msg, '\n');
1119 * Attempt to read a ParameterStatus message.
1120 * This is possible in several places, so we break it out as a subroutine.
1121 * Entry: 'S' message type and length have already been consumed.
1122 * Exit: returns 0 if successfully consumed message.
1123 * returns EOF if not enough data.
1126 getParameterStatus(PGconn *conn)
1128 PQExpBufferData valueBuf;
1130 /* Get the parameter name */
1131 if (pqGets(&conn->workBuffer, conn))
1133 /* Get the parameter value (could be large) */
1134 initPQExpBuffer(&valueBuf);
1135 if (pqGets(&valueBuf, conn))
1137 termPQExpBuffer(&valueBuf);
1141 pqSaveParameterStatus(conn, conn->workBuffer.data, valueBuf.data);
1142 termPQExpBuffer(&valueBuf);
1148 * Attempt to read a Notify response message.
1149 * This is possible in several places, so we break it out as a subroutine.
1150 * Entry: 'A' message type and length have already been consumed.
1151 * Exit: returns 0 if successfully consumed Notify message.
1152 * returns EOF if not enough data.
1155 getNotify(PGconn *conn)
1161 PGnotify *newNotify;
1163 if (pqGetInt(&be_pid, 4, conn))
1165 if (pqGets(&conn->workBuffer, conn))
1167 /* must save name while getting extra string */
1168 svname = strdup(conn->workBuffer.data);
1171 if (pqGets(&conn->workBuffer, conn))
1178 * Store the strings right after the PQnotify structure so it can all be
1179 * freed at once. We don't use NAMEDATALEN because we don't want to tie
1180 * this interface to a specific server name length.
1182 nmlen = strlen(svname);
1183 extralen = strlen(conn->workBuffer.data);
1184 newNotify = (PGnotify *) malloc(sizeof(PGnotify) + nmlen + extralen + 2);
1187 newNotify->relname = (char *) newNotify + sizeof(PGnotify);
1188 strcpy(newNotify->relname, svname);
1189 newNotify->extra = newNotify->relname + nmlen + 1;
1190 strcpy(newNotify->extra, conn->workBuffer.data);
1191 newNotify->be_pid = be_pid;
1192 newNotify->next = NULL;
1193 if (conn->notifyTail)
1194 conn->notifyTail->next = newNotify;
1196 conn->notifyHead = newNotify;
1197 conn->notifyTail = newNotify;
1205 * getCopyStart - process CopyInResponse, CopyOutResponse or
1206 * CopyBothResponse message
1208 * parseInput already read the message type and length.
1211 getCopyStart(PGconn *conn, ExecStatusType copytype)
1217 result = PQmakeEmptyPGresult(conn, copytype);
1221 if (pqGetc(&conn->copy_is_binary, conn))
1223 result->binary = conn->copy_is_binary;
1224 /* the next two bytes are the number of fields */
1225 if (pqGetInt(&(result->numAttributes), 2, conn))
1227 nfields = result->numAttributes;
1229 /* allocate space for the attribute descriptors */
1232 result->attDescs = (PGresAttDesc *)
1233 pqResultAlloc(result, nfields * sizeof(PGresAttDesc), TRUE);
1234 if (!result->attDescs)
1236 MemSet(result->attDescs, 0, nfields * sizeof(PGresAttDesc));
1239 for (i = 0; i < nfields; i++)
1243 if (pqGetInt(&format, 2, conn))
1247 * Since pqGetInt treats 2-byte integers as unsigned, we need to
1248 * coerce these results to signed form.
1250 format = (int) ((int16) format);
1251 result->attDescs[i].format = format;
1255 conn->result = result;
1264 * getReadyForQuery - process ReadyForQuery message
1267 getReadyForQuery(PGconn *conn)
1271 if (pqGetc(&xact_status, conn))
1273 switch (xact_status)
1276 conn->xactStatus = PQTRANS_IDLE;
1279 conn->xactStatus = PQTRANS_INTRANS;
1282 conn->xactStatus = PQTRANS_INERROR;
1285 conn->xactStatus = PQTRANS_UNKNOWN;
1293 * getCopyDataMessage - fetch next CopyData message, process async messages
1295 * Returns length word of CopyData message (> 0), or 0 if no complete
1296 * message available, -1 if end of copy, -2 if error.
1299 getCopyDataMessage(PGconn *conn)
1308 * Do we have the next input message? To make life simpler for async
1309 * callers, we keep returning 0 until the next message is fully
1310 * available, even if it is not Copy Data.
1312 conn->inCursor = conn->inStart;
1313 if (pqGetc(&id, conn))
1315 if (pqGetInt(&msgLength, 4, conn))
1319 handleSyncLoss(conn, id, msgLength);
1322 avail = conn->inEnd - conn->inCursor;
1323 if (avail < msgLength - 4)
1326 * Before returning, enlarge the input buffer if needed to hold
1327 * the whole message. See notes in parseInput.
1329 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength - 4,
1333 * XXX add some better recovery code... plan is to skip over
1334 * the message using its length, then report an error. For the
1335 * moment, just treat this like loss of sync (which indeed it
1338 handleSyncLoss(conn, id, msgLength);
1345 * If it's a legitimate async message type, process it. (NOTIFY
1346 * messages are not currently possible here, but we handle them for
1347 * completeness.) Otherwise, if it's anything except Copy Data,
1348 * report end-of-copy.
1352 case 'A': /* NOTIFY */
1353 if (getNotify(conn))
1356 case 'N': /* NOTICE */
1357 if (pqGetErrorNotice3(conn, false))
1360 case 'S': /* ParameterStatus */
1361 if (getParameterStatus(conn))
1364 case 'd': /* Copy Data, pass it back to caller */
1366 default: /* treat as end of copy */
1370 /* Drop the processed message and loop around for another */
1371 conn->inStart = conn->inCursor;
1376 * PQgetCopyData - read a row of data from the backend during COPY OUT
1379 * If successful, sets *buffer to point to a malloc'd row of data, and
1380 * returns row length (always > 0) as result.
1381 * Returns 0 if no row available yet (only possible if async is true),
1382 * -1 if end of copy (consult PQgetResult), or -2 if error (consult
1386 pqGetCopyData3(PGconn *conn, char **buffer, int async)
1393 * Collect the next input message. To make life simpler for async
1394 * callers, we keep returning 0 until the next message is fully
1395 * available, even if it is not Copy Data.
1397 msgLength = getCopyDataMessage(conn);
1401 * On end-of-copy, exit COPY_OUT or COPY_BOTH mode and let caller
1402 * read status with PQgetResult(). The normal case is that it's
1403 * Copy Done, but we let parseInput read that. If error, we expect
1404 * the state was already changed.
1406 if (msgLength == -1)
1407 conn->asyncStatus = PGASYNC_BUSY;
1408 return msgLength; /* end-of-copy or error */
1412 /* Don't block if async read requested */
1415 /* Need to load more data */
1416 if (pqWait(TRUE, FALSE, conn) ||
1417 pqReadData(conn) < 0)
1423 * Drop zero-length messages (shouldn't happen anyway). Otherwise
1424 * pass the data back to the caller.
1429 *buffer = (char *) malloc(msgLength + 1);
1430 if (*buffer == NULL)
1432 printfPQExpBuffer(&conn->errorMessage,
1433 libpq_gettext("out of memory\n"));
1436 memcpy(*buffer, &conn->inBuffer[conn->inCursor], msgLength);
1437 (*buffer)[msgLength] = '\0'; /* Add terminating null */
1439 /* Mark message consumed */
1440 conn->inStart = conn->inCursor + msgLength;
1445 /* Empty, so drop it and loop around for another */
1446 conn->inStart = conn->inCursor;
1451 * PQgetline - gets a newline-terminated string from the backend.
1453 * See fe-exec.c for documentation.
1456 pqGetline3(PGconn *conn, char *s, int maxlen)
1460 if (conn->sock < 0 ||
1461 conn->asyncStatus != PGASYNC_COPY_OUT ||
1462 conn->copy_is_binary)
1464 printfPQExpBuffer(&conn->errorMessage,
1465 libpq_gettext("PQgetline: not doing text COPY OUT\n"));
1470 while ((status = PQgetlineAsync(conn, s, maxlen - 1)) == 0)
1472 /* need to load more data */
1473 if (pqWait(TRUE, FALSE, conn) ||
1474 pqReadData(conn) < 0)
1483 /* End of copy detected; gin up old-style terminator */
1488 /* Add null terminator, and strip trailing \n if present */
1489 if (s[status - 1] == '\n')
1491 s[status - 1] = '\0';
1502 * PQgetlineAsync - gets a COPY data row without blocking.
1504 * See fe-exec.c for documentation.
1507 pqGetlineAsync3(PGconn *conn, char *buffer, int bufsize)
1512 if (conn->asyncStatus != PGASYNC_COPY_OUT)
1513 return -1; /* we are not doing a copy... */
1516 * Recognize the next input message. To make life simpler for async
1517 * callers, we keep returning 0 until the next message is fully available
1518 * even if it is not Copy Data. This should keep PQendcopy from blocking.
1519 * (Note: unlike pqGetCopyData3, we do not change asyncStatus here.)
1521 msgLength = getCopyDataMessage(conn);
1523 return -1; /* end-of-copy or error */
1525 return 0; /* no data yet */
1528 * Move data from libpq's buffer to the caller's. In the case where a
1529 * prior call found the caller's buffer too small, we use
1530 * conn->copy_already_done to remember how much of the row was already
1531 * returned to the caller.
1533 conn->inCursor += conn->copy_already_done;
1534 avail = msgLength - 4 - conn->copy_already_done;
1535 if (avail <= bufsize)
1537 /* Able to consume the whole message */
1538 memcpy(buffer, &conn->inBuffer[conn->inCursor], avail);
1539 /* Mark message consumed */
1540 conn->inStart = conn->inCursor + avail;
1541 /* Reset state for next time */
1542 conn->copy_already_done = 0;
1547 /* We must return a partial message */
1548 memcpy(buffer, &conn->inBuffer[conn->inCursor], bufsize);
1549 /* The message is NOT consumed from libpq's buffer */
1550 conn->copy_already_done += bufsize;
1558 * See fe-exec.c for documentation.
1561 pqEndcopy3(PGconn *conn)
1565 if (conn->asyncStatus != PGASYNC_COPY_IN &&
1566 conn->asyncStatus != PGASYNC_COPY_OUT)
1568 printfPQExpBuffer(&conn->errorMessage,
1569 libpq_gettext("no COPY in progress\n"));
1573 /* Send the CopyDone message if needed */
1574 if (conn->asyncStatus == PGASYNC_COPY_IN)
1576 if (pqPutMsgStart('c', false, conn) < 0 ||
1577 pqPutMsgEnd(conn) < 0)
1581 * If we sent the COPY command in extended-query mode, we must issue a
1584 if (conn->queryclass != PGQUERY_SIMPLE)
1586 if (pqPutMsgStart('S', false, conn) < 0 ||
1587 pqPutMsgEnd(conn) < 0)
1593 * make sure no data is waiting to be sent, abort if we are non-blocking
1594 * and the flush fails
1596 if (pqFlush(conn) && pqIsnonblocking(conn))
1599 /* Return to active duty */
1600 conn->asyncStatus = PGASYNC_BUSY;
1601 resetPQExpBuffer(&conn->errorMessage);
1604 * Non blocking connections may have to abort at this point. If everyone
1605 * played the game there should be no problem, but in error scenarios the
1606 * expected messages may not have arrived yet. (We are assuming that the
1607 * backend's packetizing will ensure that CommandComplete arrives along
1608 * with the CopyDone; are there corner cases where that doesn't happen?)
1610 if (pqIsnonblocking(conn) && PQisBusy(conn))
1613 /* Wait for the completion response */
1614 result = PQgetResult(conn);
1616 /* Expecting a successful result */
1617 if (result && result->resultStatus == PGRES_COMMAND_OK)
1624 * Trouble. For backwards-compatibility reasons, we issue the error
1625 * message as if it were a notice (would be nice to get rid of this
1626 * silliness, but too many apps probably don't handle errors from
1627 * PQendcopy reasonably). Note that the app can still obtain the error
1628 * status from the PGconn object.
1630 if (conn->errorMessage.len > 0)
1632 /* We have to strip the trailing newline ... pain in neck... */
1633 char svLast = conn->errorMessage.data[conn->errorMessage.len - 1];
1636 conn->errorMessage.data[conn->errorMessage.len - 1] = '\0';
1637 pqInternalNotice(&conn->noticeHooks, "%s", conn->errorMessage.data);
1638 conn->errorMessage.data[conn->errorMessage.len - 1] = svLast;
1648 * PQfn - Send a function call to the POSTGRES backend.
1650 * See fe-exec.c for documentation.
1653 pqFunctionCall3(PGconn *conn, Oid fnid,
1654 int *result_buf, int *actual_result_len,
1656 const PQArgBlock *args, int nargs)
1658 bool needInput = false;
1659 ExecStatusType status = PGRES_FATAL_ERROR;
1665 /* PQfn already validated connection state */
1667 if (pqPutMsgStart('F', false, conn) < 0 || /* function call msg */
1668 pqPutInt(fnid, 4, conn) < 0 || /* function id */
1669 pqPutInt(1, 2, conn) < 0 || /* # of format codes */
1670 pqPutInt(1, 2, conn) < 0 || /* format code: BINARY */
1671 pqPutInt(nargs, 2, conn) < 0) /* # of args */
1673 pqHandleSendFailure(conn);
1677 for (i = 0; i < nargs; ++i)
1678 { /* len.int4 + contents */
1679 if (pqPutInt(args[i].len, 4, conn))
1681 pqHandleSendFailure(conn);
1684 if (args[i].len == -1)
1685 continue; /* it's NULL */
1689 if (pqPutInt(args[i].u.integer, args[i].len, conn))
1691 pqHandleSendFailure(conn);
1697 if (pqPutnchar((char *) args[i].u.ptr, args[i].len, conn))
1699 pqHandleSendFailure(conn);
1705 if (pqPutInt(1, 2, conn) < 0) /* result format code: BINARY */
1707 pqHandleSendFailure(conn);
1711 if (pqPutMsgEnd(conn) < 0 ||
1714 pqHandleSendFailure(conn);
1722 /* Wait for some data to arrive (or for the channel to close) */
1723 if (pqWait(TRUE, FALSE, conn) ||
1724 pqReadData(conn) < 0)
1729 * Scan the message. If we run out of data, loop around to try again.
1733 conn->inCursor = conn->inStart;
1734 if (pqGetc(&id, conn))
1736 if (pqGetInt(&msgLength, 4, conn))
1740 * Try to validate message type/length here. A length less than 4 is
1741 * definitely broken. Large lengths should only be believed for a few
1746 handleSyncLoss(conn, id, msgLength);
1749 if (msgLength > 30000 && !VALID_LONG_MESSAGE_TYPE(id))
1751 handleSyncLoss(conn, id, msgLength);
1756 * Can't process if message body isn't all here yet.
1759 avail = conn->inEnd - conn->inCursor;
1760 if (avail < msgLength)
1763 * Before looping, enlarge the input buffer if needed to hold the
1764 * whole message. See notes in parseInput.
1766 if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
1770 * XXX add some better recovery code... plan is to skip over
1771 * the message using its length, then report an error. For the
1772 * moment, just treat this like loss of sync (which indeed it
1775 handleSyncLoss(conn, id, msgLength);
1782 * We should see V or E response to the command, but might get N
1783 * and/or A notices first. We also need to swallow the final Z before
1788 case 'V': /* function result */
1789 if (pqGetInt(actual_result_len, 4, conn))
1791 if (*actual_result_len != -1)
1795 if (pqGetInt(result_buf, *actual_result_len, conn))
1800 if (pqGetnchar((char *) result_buf,
1806 /* correctly finished function result message */
1807 status = PGRES_COMMAND_OK;
1809 case 'E': /* error return */
1810 if (pqGetErrorNotice3(conn, true))
1812 status = PGRES_FATAL_ERROR;
1814 case 'A': /* notify message */
1815 /* handle notify and go back to processing return values */
1816 if (getNotify(conn))
1819 case 'N': /* notice */
1820 /* handle notice and go back to processing return values */
1821 if (pqGetErrorNotice3(conn, false))
1824 case 'Z': /* backend is ready for new query */
1825 if (getReadyForQuery(conn))
1827 /* consume the message and exit */
1828 conn->inStart += 5 + msgLength;
1829 /* if we saved a result object (probably an error), use it */
1831 return pqPrepareAsyncResult(conn);
1832 return PQmakeEmptyPGresult(conn, status);
1833 case 'S': /* parameter status */
1834 if (getParameterStatus(conn))
1838 /* The backend violates the protocol. */
1839 printfPQExpBuffer(&conn->errorMessage,
1840 libpq_gettext("protocol error: id=0x%x\n"),
1842 pqSaveErrorResult(conn);
1843 /* trust the specified message length as what to skip */
1844 conn->inStart += 5 + msgLength;
1845 return pqPrepareAsyncResult(conn);
1847 /* Completed this message, keep going */
1848 /* trust the specified message length as what to skip */
1849 conn->inStart += 5 + msgLength;
1854 * We fall out of the loop only upon failing to read data.
1855 * conn->errorMessage has been set by pqWait or pqReadData. We want to
1856 * append it to any already-received error message.
1858 pqSaveErrorResult(conn);
1859 return pqPrepareAsyncResult(conn);
1864 * Construct startup packet
1866 * Returns a malloc'd packet buffer, or NULL if out of memory
1869 pqBuildStartupPacket3(PGconn *conn, int *packetlen,
1870 const PQEnvironmentOption *options)
1874 *packetlen = build_startup_packet(conn, NULL, options);
1875 startpacket = (char *) malloc(*packetlen);
1878 *packetlen = build_startup_packet(conn, startpacket, options);
1883 * Build a startup packet given a filled-in PGconn structure.
1885 * We need to figure out how much space is needed, then fill it in.
1886 * To avoid duplicate logic, this routine is called twice: the first time
1887 * (with packet == NULL) just counts the space needed, the second time
1888 * (with packet == allocated space) fills it in. Return value is the number
1892 build_startup_packet(const PGconn *conn, char *packet,
1893 const PQEnvironmentOption *options)
1896 const PQEnvironmentOption *next_eo;
1899 /* Protocol version comes first. */
1902 ProtocolVersion pv = htonl(conn->pversion);
1904 memcpy(packet + packet_len, &pv, sizeof(ProtocolVersion));
1906 packet_len += sizeof(ProtocolVersion);
1908 /* Add user name, database name, options */
1910 #define ADD_STARTUP_OPTION(optname, optval) \
1913 strcpy(packet + packet_len, optname); \
1914 packet_len += strlen(optname) + 1; \
1916 strcpy(packet + packet_len, optval); \
1917 packet_len += strlen(optval) + 1; \
1920 if (conn->pguser && conn->pguser[0])
1921 ADD_STARTUP_OPTION("user", conn->pguser);
1922 if (conn->dbName && conn->dbName[0])
1923 ADD_STARTUP_OPTION("database", conn->dbName);
1924 if (conn->replication && conn->replication[0])
1925 ADD_STARTUP_OPTION("replication", conn->replication);
1926 if (conn->pgoptions && conn->pgoptions[0])
1927 ADD_STARTUP_OPTION("options", conn->pgoptions);
1928 if (conn->send_appname)
1930 /* Use appname if present, otherwise use fallback */
1931 val = conn->appname ? conn->appname : conn->fbappname;
1933 ADD_STARTUP_OPTION("application_name", val);
1936 if (conn->client_encoding_initial && conn->client_encoding_initial[0])
1937 ADD_STARTUP_OPTION("client_encoding", conn->client_encoding_initial);
1939 /* Add any environment-driven GUC settings needed */
1940 for (next_eo = options; next_eo->envName; next_eo++)
1942 if ((val = getenv(next_eo->envName)) != NULL)
1944 if (pg_strcasecmp(val, "default") != 0)
1945 ADD_STARTUP_OPTION(next_eo->pgName, val);
1949 /* Add trailing terminator */
1951 packet[packet_len] = '\0';