]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-exec.c
Revert "psql: fix \connect with URIs and conninfo strings"
[postgresql] / src / interfaces / libpq / fe-exec.c
1 /*-------------------------------------------------------------------------
2  *
3  * fe-exec.c
4  *        functions related to sending a query down to the backend
5  *
6  * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/interfaces/libpq/fe-exec.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres_fe.h"
16
17 #include <ctype.h>
18 #include <fcntl.h>
19
20 #include "libpq-fe.h"
21 #include "libpq-int.h"
22
23 #include "mb/pg_wchar.h"
24
25 #ifdef WIN32
26 #include "win32.h"
27 #else
28 #include <unistd.h>
29 #endif
30
31 /* keep this in same order as ExecStatusType in libpq-fe.h */
32 char       *const pgresStatus[] = {
33         "PGRES_EMPTY_QUERY",
34         "PGRES_COMMAND_OK",
35         "PGRES_TUPLES_OK",
36         "PGRES_COPY_OUT",
37         "PGRES_COPY_IN",
38         "PGRES_BAD_RESPONSE",
39         "PGRES_NONFATAL_ERROR",
40         "PGRES_FATAL_ERROR",
41         "PGRES_COPY_BOTH",
42         "PGRES_SINGLE_TUPLE"
43 };
44
45 /*
46  * static state needed by PQescapeString and PQescapeBytea; initialize to
47  * values that result in backward-compatible behavior
48  */
49 static int      static_client_encoding = PG_SQL_ASCII;
50 static bool static_std_strings = false;
51
52
53 static PGEvent *dupEvents(PGEvent *events, int count);
54 static bool pqAddTuple(PGresult *res, PGresAttValue *tup);
55 static bool PQsendQueryStart(PGconn *conn);
56 static int PQsendQueryGuts(PGconn *conn,
57                                 const char *command,
58                                 const char *stmtName,
59                                 int nParams,
60                                 const Oid *paramTypes,
61                                 const char *const * paramValues,
62                                 const int *paramLengths,
63                                 const int *paramFormats,
64                                 int resultFormat);
65 static void parseInput(PGconn *conn);
66 static PGresult *getCopyResult(PGconn *conn, ExecStatusType copytype);
67 static bool PQexecStart(PGconn *conn);
68 static PGresult *PQexecFinish(PGconn *conn);
69 static int PQsendDescribe(PGconn *conn, char desc_type,
70                            const char *desc_target);
71 static int      check_field_number(const PGresult *res, int field_num);
72
73
74 /* ----------------
75  * Space management for PGresult.
76  *
77  * Formerly, libpq did a separate malloc() for each field of each tuple
78  * returned by a query.  This was remarkably expensive --- malloc/free
79  * consumed a sizable part of the application's runtime.  And there is
80  * no real need to keep track of the fields separately, since they will
81  * all be freed together when the PGresult is released.  So now, we grab
82  * large blocks of storage from malloc and allocate space for query data
83  * within these blocks, using a trivially simple allocator.  This reduces
84  * the number of malloc/free calls dramatically, and it also avoids
85  * fragmentation of the malloc storage arena.
86  * The PGresult structure itself is still malloc'd separately.  We could
87  * combine it with the first allocation block, but that would waste space
88  * for the common case that no extra storage is actually needed (that is,
89  * the SQL command did not return tuples).
90  *
91  * We also malloc the top-level array of tuple pointers separately, because
92  * we need to be able to enlarge it via realloc, and our trivial space
93  * allocator doesn't handle that effectively.  (Too bad the FE/BE protocol
94  * doesn't tell us up front how many tuples will be returned.)
95  * All other subsidiary storage for a PGresult is kept in PGresult_data blocks
96  * of size PGRESULT_DATA_BLOCKSIZE.  The overhead at the start of each block
97  * is just a link to the next one, if any.  Free-space management info is
98  * kept in the owning PGresult.
99  * A query returning a small amount of data will thus require three malloc
100  * calls: one for the PGresult, one for the tuples pointer array, and one
101  * PGresult_data block.
102  *
103  * Only the most recently allocated PGresult_data block is a candidate to
104  * have more stuff added to it --- any extra space left over in older blocks
105  * is wasted.  We could be smarter and search the whole chain, but the point
106  * here is to be simple and fast.  Typical applications do not keep a PGresult
107  * around very long anyway, so some wasted space within one is not a problem.
108  *
109  * Tuning constants for the space allocator are:
110  * PGRESULT_DATA_BLOCKSIZE: size of a standard allocation block, in bytes
111  * PGRESULT_ALIGN_BOUNDARY: assumed alignment requirement for binary data
112  * PGRESULT_SEP_ALLOC_THRESHOLD: objects bigger than this are given separate
113  *       blocks, instead of being crammed into a regular allocation block.
114  * Requirements for correct function are:
115  * PGRESULT_ALIGN_BOUNDARY must be a multiple of the alignment requirements
116  *              of all machine data types.  (Currently this is set from configure
117  *              tests, so it should be OK automatically.)
118  * PGRESULT_SEP_ALLOC_THRESHOLD + PGRESULT_BLOCK_OVERHEAD <=
119  *                      PGRESULT_DATA_BLOCKSIZE
120  *              pqResultAlloc assumes an object smaller than the threshold will fit
121  *              in a new block.
122  * The amount of space wasted at the end of a block could be as much as
123  * PGRESULT_SEP_ALLOC_THRESHOLD, so it doesn't pay to make that too large.
124  * ----------------
125  */
126
127 #define PGRESULT_DATA_BLOCKSIZE         2048
128 #define PGRESULT_ALIGN_BOUNDARY         MAXIMUM_ALIGNOF         /* from configure */
129 #define PGRESULT_BLOCK_OVERHEAD         Max(sizeof(PGresult_data), PGRESULT_ALIGN_BOUNDARY)
130 #define PGRESULT_SEP_ALLOC_THRESHOLD    (PGRESULT_DATA_BLOCKSIZE / 2)
131
132
133 /*
134  * PQmakeEmptyPGresult
135  *       returns a newly allocated, initialized PGresult with given status.
136  *       If conn is not NULL and status indicates an error, the conn's
137  *       errorMessage is copied.  Also, any PGEvents are copied from the conn.
138  */
139 PGresult *
140 PQmakeEmptyPGresult(PGconn *conn, ExecStatusType status)
141 {
142         PGresult   *result;
143
144         result = (PGresult *) malloc(sizeof(PGresult));
145         if (!result)
146                 return NULL;
147
148         result->ntups = 0;
149         result->numAttributes = 0;
150         result->attDescs = NULL;
151         result->tuples = NULL;
152         result->tupArrSize = 0;
153         result->numParameters = 0;
154         result->paramDescs = NULL;
155         result->resultStatus = status;
156         result->cmdStatus[0] = '\0';
157         result->binary = 0;
158         result->events = NULL;
159         result->nEvents = 0;
160         result->errMsg = NULL;
161         result->errFields = NULL;
162         result->null_field[0] = '\0';
163         result->curBlock = NULL;
164         result->curOffset = 0;
165         result->spaceLeft = 0;
166
167         if (conn)
168         {
169                 /* copy connection data we might need for operations on PGresult */
170                 result->noticeHooks = conn->noticeHooks;
171                 result->client_encoding = conn->client_encoding;
172
173                 /* consider copying conn's errorMessage */
174                 switch (status)
175                 {
176                         case PGRES_EMPTY_QUERY:
177                         case PGRES_COMMAND_OK:
178                         case PGRES_TUPLES_OK:
179                         case PGRES_COPY_OUT:
180                         case PGRES_COPY_IN:
181                         case PGRES_COPY_BOTH:
182                         case PGRES_SINGLE_TUPLE:
183                                 /* non-error cases */
184                                 break;
185                         default:
186                                 pqSetResultError(result, conn->errorMessage.data);
187                                 break;
188                 }
189
190                 /* copy events last; result must be valid if we need to PQclear */
191                 if (conn->nEvents > 0)
192                 {
193                         result->events = dupEvents(conn->events, conn->nEvents);
194                         if (!result->events)
195                         {
196                                 PQclear(result);
197                                 return NULL;
198                         }
199                         result->nEvents = conn->nEvents;
200                 }
201         }
202         else
203         {
204                 /* defaults... */
205                 result->noticeHooks.noticeRec = NULL;
206                 result->noticeHooks.noticeRecArg = NULL;
207                 result->noticeHooks.noticeProc = NULL;
208                 result->noticeHooks.noticeProcArg = NULL;
209                 result->client_encoding = PG_SQL_ASCII;
210         }
211
212         return result;
213 }
214
215 /*
216  * PQsetResultAttrs
217  *
218  * Set the attributes for a given result.  This function fails if there are
219  * already attributes contained in the provided result.  The call is
220  * ignored if numAttributes is zero or attDescs is NULL.  If the
221  * function fails, it returns zero.  If the function succeeds, it
222  * returns a non-zero value.
223  */
224 int
225 PQsetResultAttrs(PGresult *res, int numAttributes, PGresAttDesc *attDescs)
226 {
227         int                     i;
228
229         /* If attrs already exist, they cannot be overwritten. */
230         if (!res || res->numAttributes > 0)
231                 return FALSE;
232
233         /* ignore no-op request */
234         if (numAttributes <= 0 || !attDescs)
235                 return TRUE;
236
237         res->attDescs = (PGresAttDesc *)
238                 PQresultAlloc(res, numAttributes * sizeof(PGresAttDesc));
239
240         if (!res->attDescs)
241                 return FALSE;
242
243         res->numAttributes = numAttributes;
244         memcpy(res->attDescs, attDescs, numAttributes * sizeof(PGresAttDesc));
245
246         /* deep-copy the attribute names, and determine format */
247         res->binary = 1;
248         for (i = 0; i < res->numAttributes; i++)
249         {
250                 if (res->attDescs[i].name)
251                         res->attDescs[i].name = pqResultStrdup(res, res->attDescs[i].name);
252                 else
253                         res->attDescs[i].name = res->null_field;
254
255                 if (!res->attDescs[i].name)
256                         return FALSE;
257
258                 if (res->attDescs[i].format == 0)
259                         res->binary = 0;
260         }
261
262         return TRUE;
263 }
264
265 /*
266  * PQcopyResult
267  *
268  * Returns a deep copy of the provided 'src' PGresult, which cannot be NULL.
269  * The 'flags' argument controls which portions of the result will or will
270  * NOT be copied.  The created result is always put into the
271  * PGRES_TUPLES_OK status.  The source result error message is not copied,
272  * although cmdStatus is.
273  *
274  * To set custom attributes, use PQsetResultAttrs.  That function requires
275  * that there are no attrs contained in the result, so to use that
276  * function you cannot use the PG_COPYRES_ATTRS or PG_COPYRES_TUPLES
277  * options with this function.
278  *
279  * Options:
280  *       PG_COPYRES_ATTRS - Copy the source result's attributes
281  *
282  *       PG_COPYRES_TUPLES - Copy the source result's tuples.  This implies
283  *       copying the attrs, seeing how the attrs are needed by the tuples.
284  *
285  *       PG_COPYRES_EVENTS - Copy the source result's events.
286  *
287  *       PG_COPYRES_NOTICEHOOKS - Copy the source result's notice hooks.
288  */
289 PGresult *
290 PQcopyResult(const PGresult *src, int flags)
291 {
292         PGresult   *dest;
293         int                     i;
294
295         if (!src)
296                 return NULL;
297
298         dest = PQmakeEmptyPGresult(NULL, PGRES_TUPLES_OK);
299         if (!dest)
300                 return NULL;
301
302         /* Always copy these over.  Is cmdStatus really useful here? */
303         dest->client_encoding = src->client_encoding;
304         strcpy(dest->cmdStatus, src->cmdStatus);
305
306         /* Wants attrs? */
307         if (flags & (PG_COPYRES_ATTRS | PG_COPYRES_TUPLES))
308         {
309                 if (!PQsetResultAttrs(dest, src->numAttributes, src->attDescs))
310                 {
311                         PQclear(dest);
312                         return NULL;
313                 }
314         }
315
316         /* Wants to copy tuples? */
317         if (flags & PG_COPYRES_TUPLES)
318         {
319                 int                     tup,
320                                         field;
321
322                 for (tup = 0; tup < src->ntups; tup++)
323                 {
324                         for (field = 0; field < src->numAttributes; field++)
325                         {
326                                 if (!PQsetvalue(dest, tup, field,
327                                                                 src->tuples[tup][field].value,
328                                                                 src->tuples[tup][field].len))
329                                 {
330                                         PQclear(dest);
331                                         return NULL;
332                                 }
333                         }
334                 }
335         }
336
337         /* Wants to copy notice hooks? */
338         if (flags & PG_COPYRES_NOTICEHOOKS)
339                 dest->noticeHooks = src->noticeHooks;
340
341         /* Wants to copy PGEvents? */
342         if ((flags & PG_COPYRES_EVENTS) && src->nEvents > 0)
343         {
344                 dest->events = dupEvents(src->events, src->nEvents);
345                 if (!dest->events)
346                 {
347                         PQclear(dest);
348                         return NULL;
349                 }
350                 dest->nEvents = src->nEvents;
351         }
352
353         /* Okay, trigger PGEVT_RESULTCOPY event */
354         for (i = 0; i < dest->nEvents; i++)
355         {
356                 if (src->events[i].resultInitialized)
357                 {
358                         PGEventResultCopy evt;
359
360                         evt.src = src;
361                         evt.dest = dest;
362                         if (!dest->events[i].proc(PGEVT_RESULTCOPY, &evt,
363                                                                           dest->events[i].passThrough))
364                         {
365                                 PQclear(dest);
366                                 return NULL;
367                         }
368                         dest->events[i].resultInitialized = TRUE;
369                 }
370         }
371
372         return dest;
373 }
374
375 /*
376  * Copy an array of PGEvents (with no extra space for more).
377  * Does not duplicate the event instance data, sets this to NULL.
378  * Also, the resultInitialized flags are all cleared.
379  */
380 static PGEvent *
381 dupEvents(PGEvent *events, int count)
382 {
383         PGEvent    *newEvents;
384         int                     i;
385
386         if (!events || count <= 0)
387                 return NULL;
388
389         newEvents = (PGEvent *) malloc(count * sizeof(PGEvent));
390         if (!newEvents)
391                 return NULL;
392
393         for (i = 0; i < count; i++)
394         {
395                 newEvents[i].proc = events[i].proc;
396                 newEvents[i].passThrough = events[i].passThrough;
397                 newEvents[i].data = NULL;
398                 newEvents[i].resultInitialized = FALSE;
399                 newEvents[i].name = strdup(events[i].name);
400                 if (!newEvents[i].name)
401                 {
402                         while (--i >= 0)
403                                 free(newEvents[i].name);
404                         free(newEvents);
405                         return NULL;
406                 }
407         }
408
409         return newEvents;
410 }
411
412
413 /*
414  * Sets the value for a tuple field.  The tup_num must be less than or
415  * equal to PQntuples(res).  If it is equal, a new tuple is created and
416  * added to the result.
417  * Returns a non-zero value for success and zero for failure.
418  */
419 int
420 PQsetvalue(PGresult *res, int tup_num, int field_num, char *value, int len)
421 {
422         PGresAttValue *attval;
423
424         if (!check_field_number(res, field_num))
425                 return FALSE;
426
427         /* Invalid tup_num, must be <= ntups */
428         if (tup_num < 0 || tup_num > res->ntups)
429                 return FALSE;
430
431         /* need to allocate a new tuple? */
432         if (tup_num == res->ntups)
433         {
434                 PGresAttValue *tup;
435                 int                     i;
436
437                 tup = (PGresAttValue *)
438                         pqResultAlloc(res, res->numAttributes * sizeof(PGresAttValue),
439                                                   TRUE);
440
441                 if (!tup)
442                         return FALSE;
443
444                 /* initialize each column to NULL */
445                 for (i = 0; i < res->numAttributes; i++)
446                 {
447                         tup[i].len = NULL_LEN;
448                         tup[i].value = res->null_field;
449                 }
450
451                 /* add it to the array */
452                 if (!pqAddTuple(res, tup))
453                         return FALSE;
454         }
455
456         attval = &res->tuples[tup_num][field_num];
457
458         /* treat either NULL_LEN or NULL value pointer as a NULL field */
459         if (len == NULL_LEN || value == NULL)
460         {
461                 attval->len = NULL_LEN;
462                 attval->value = res->null_field;
463         }
464         else if (len <= 0)
465         {
466                 attval->len = 0;
467                 attval->value = res->null_field;
468         }
469         else
470         {
471                 attval->value = (char *) pqResultAlloc(res, len + 1, TRUE);
472                 if (!attval->value)
473                         return FALSE;
474                 attval->len = len;
475                 memcpy(attval->value, value, len);
476                 attval->value[len] = '\0';
477         }
478
479         return TRUE;
480 }
481
482 /*
483  * pqResultAlloc - exported routine to allocate local storage in a PGresult.
484  *
485  * We force all such allocations to be maxaligned, since we don't know
486  * whether the value might be binary.
487  */
488 void *
489 PQresultAlloc(PGresult *res, size_t nBytes)
490 {
491         return pqResultAlloc(res, nBytes, TRUE);
492 }
493
494 /*
495  * pqResultAlloc -
496  *              Allocate subsidiary storage for a PGresult.
497  *
498  * nBytes is the amount of space needed for the object.
499  * If isBinary is true, we assume that we need to align the object on
500  * a machine allocation boundary.
501  * If isBinary is false, we assume the object is a char string and can
502  * be allocated on any byte boundary.
503  */
504 void *
505 pqResultAlloc(PGresult *res, size_t nBytes, bool isBinary)
506 {
507         char       *space;
508         PGresult_data *block;
509
510         if (!res)
511                 return NULL;
512
513         if (nBytes <= 0)
514                 return res->null_field;
515
516         /*
517          * If alignment is needed, round up the current position to an alignment
518          * boundary.
519          */
520         if (isBinary)
521         {
522                 int                     offset = res->curOffset % PGRESULT_ALIGN_BOUNDARY;
523
524                 if (offset)
525                 {
526                         res->curOffset += PGRESULT_ALIGN_BOUNDARY - offset;
527                         res->spaceLeft -= PGRESULT_ALIGN_BOUNDARY - offset;
528                 }
529         }
530
531         /* If there's enough space in the current block, no problem. */
532         if (nBytes <= (size_t) res->spaceLeft)
533         {
534                 space = res->curBlock->space + res->curOffset;
535                 res->curOffset += nBytes;
536                 res->spaceLeft -= nBytes;
537                 return space;
538         }
539
540         /*
541          * If the requested object is very large, give it its own block; this
542          * avoids wasting what might be most of the current block to start a new
543          * block.  (We'd have to special-case requests bigger than the block size
544          * anyway.)  The object is always given binary alignment in this case.
545          */
546         if (nBytes >= PGRESULT_SEP_ALLOC_THRESHOLD)
547         {
548                 block = (PGresult_data *) malloc(nBytes + PGRESULT_BLOCK_OVERHEAD);
549                 if (!block)
550                         return NULL;
551                 space = block->space + PGRESULT_BLOCK_OVERHEAD;
552                 if (res->curBlock)
553                 {
554                         /*
555                          * Tuck special block below the active block, so that we don't
556                          * have to waste the free space in the active block.
557                          */
558                         block->next = res->curBlock->next;
559                         res->curBlock->next = block;
560                 }
561                 else
562                 {
563                         /* Must set up the new block as the first active block. */
564                         block->next = NULL;
565                         res->curBlock = block;
566                         res->spaceLeft = 0; /* be sure it's marked full */
567                 }
568                 return space;
569         }
570
571         /* Otherwise, start a new block. */
572         block = (PGresult_data *) malloc(PGRESULT_DATA_BLOCKSIZE);
573         if (!block)
574                 return NULL;
575         block->next = res->curBlock;
576         res->curBlock = block;
577         if (isBinary)
578         {
579                 /* object needs full alignment */
580                 res->curOffset = PGRESULT_BLOCK_OVERHEAD;
581                 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - PGRESULT_BLOCK_OVERHEAD;
582         }
583         else
584         {
585                 /* we can cram it right after the overhead pointer */
586                 res->curOffset = sizeof(PGresult_data);
587                 res->spaceLeft = PGRESULT_DATA_BLOCKSIZE - sizeof(PGresult_data);
588         }
589
590         space = block->space + res->curOffset;
591         res->curOffset += nBytes;
592         res->spaceLeft -= nBytes;
593         return space;
594 }
595
596 /*
597  * pqResultStrdup -
598  *              Like strdup, but the space is subsidiary PGresult space.
599  */
600 char *
601 pqResultStrdup(PGresult *res, const char *str)
602 {
603         char       *space = (char *) pqResultAlloc(res, strlen(str) + 1, FALSE);
604
605         if (space)
606                 strcpy(space, str);
607         return space;
608 }
609
610 /*
611  * pqSetResultError -
612  *              assign a new error message to a PGresult
613  */
614 void
615 pqSetResultError(PGresult *res, const char *msg)
616 {
617         if (!res)
618                 return;
619         if (msg && *msg)
620                 res->errMsg = pqResultStrdup(res, msg);
621         else
622                 res->errMsg = NULL;
623 }
624
625 /*
626  * pqCatenateResultError -
627  *              concatenate a new error message to the one already in a PGresult
628  */
629 void
630 pqCatenateResultError(PGresult *res, const char *msg)
631 {
632         PQExpBufferData errorBuf;
633
634         if (!res || !msg)
635                 return;
636         initPQExpBuffer(&errorBuf);
637         if (res->errMsg)
638                 appendPQExpBufferStr(&errorBuf, res->errMsg);
639         appendPQExpBufferStr(&errorBuf, msg);
640         pqSetResultError(res, errorBuf.data);
641         termPQExpBuffer(&errorBuf);
642 }
643
644 /*
645  * PQclear -
646  *        free's the memory associated with a PGresult
647  */
648 void
649 PQclear(PGresult *res)
650 {
651         PGresult_data *block;
652         int                     i;
653
654         if (!res)
655                 return;
656
657         for (i = 0; i < res->nEvents; i++)
658         {
659                 /* only send DESTROY to successfully-initialized event procs */
660                 if (res->events[i].resultInitialized)
661                 {
662                         PGEventResultDestroy evt;
663
664                         evt.result = res;
665                         (void) res->events[i].proc(PGEVT_RESULTDESTROY, &evt,
666                                                                            res->events[i].passThrough);
667                 }
668                 free(res->events[i].name);
669         }
670
671         if (res->events)
672                 free(res->events);
673
674         /* Free all the subsidiary blocks */
675         while ((block = res->curBlock) != NULL)
676         {
677                 res->curBlock = block->next;
678                 free(block);
679         }
680
681         /* Free the top-level tuple pointer array */
682         if (res->tuples)
683                 free(res->tuples);
684
685         /* zero out the pointer fields to catch programming errors */
686         res->attDescs = NULL;
687         res->tuples = NULL;
688         res->paramDescs = NULL;
689         res->errFields = NULL;
690         res->events = NULL;
691         res->nEvents = 0;
692         /* res->curBlock was zeroed out earlier */
693
694         /* Free the PGresult structure itself */
695         free(res);
696 }
697
698 /*
699  * Handy subroutine to deallocate any partially constructed async result.
700  *
701  * Any "next" result gets cleared too.
702  */
703 void
704 pqClearAsyncResult(PGconn *conn)
705 {
706         if (conn->result)
707                 PQclear(conn->result);
708         conn->result = NULL;
709         if (conn->next_result)
710                 PQclear(conn->next_result);
711         conn->next_result = NULL;
712 }
713
714 /*
715  * This subroutine deletes any existing async result, sets conn->result
716  * to a PGresult with status PGRES_FATAL_ERROR, and stores the current
717  * contents of conn->errorMessage into that result.  It differs from a
718  * plain call on PQmakeEmptyPGresult() in that if there is already an
719  * async result with status PGRES_FATAL_ERROR, the current error message
720  * is APPENDED to the old error message instead of replacing it.  This
721  * behavior lets us report multiple error conditions properly, if necessary.
722  * (An example where this is needed is when the backend sends an 'E' message
723  * and immediately closes the connection --- we want to report both the
724  * backend error and the connection closure error.)
725  */
726 void
727 pqSaveErrorResult(PGconn *conn)
728 {
729         /*
730          * If no old async result, just let PQmakeEmptyPGresult make one. Likewise
731          * if old result is not an error message.
732          */
733         if (conn->result == NULL ||
734                 conn->result->resultStatus != PGRES_FATAL_ERROR ||
735                 conn->result->errMsg == NULL)
736         {
737                 pqClearAsyncResult(conn);
738                 conn->result = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
739         }
740         else
741         {
742                 /* Else, concatenate error message to existing async result. */
743                 pqCatenateResultError(conn->result, conn->errorMessage.data);
744         }
745 }
746
747 /*
748  * This subroutine prepares an async result object for return to the caller.
749  * If there is not already an async result object, build an error object
750  * using whatever is in conn->errorMessage.  In any case, clear the async
751  * result storage and make sure PQerrorMessage will agree with the result's
752  * error string.
753  */
754 PGresult *
755 pqPrepareAsyncResult(PGconn *conn)
756 {
757         PGresult   *res;
758
759         /*
760          * conn->result is the PGresult to return.  If it is NULL (which probably
761          * shouldn't happen) we assume there is an appropriate error message in
762          * conn->errorMessage.
763          */
764         res = conn->result;
765         if (!res)
766                 res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
767         else
768         {
769                 /*
770                  * Make sure PQerrorMessage agrees with result; it could be different
771                  * if we have concatenated messages.
772                  */
773                 resetPQExpBuffer(&conn->errorMessage);
774                 appendPQExpBufferStr(&conn->errorMessage,
775                                                          PQresultErrorMessage(res));
776         }
777
778         /*
779          * Replace conn->result with next_result, if any.  In the normal case
780          * there isn't a next result and we're just dropping ownership of the
781          * current result.  In single-row mode this restores the situation to what
782          * it was before we created the current single-row result.
783          */
784         conn->result = conn->next_result;
785         conn->next_result = NULL;
786
787         return res;
788 }
789
790 /*
791  * pqInternalNotice - produce an internally-generated notice message
792  *
793  * A format string and optional arguments can be passed.  Note that we do
794  * libpq_gettext() here, so callers need not.
795  *
796  * The supplied text is taken as primary message (ie., it should not include
797  * a trailing newline, and should not be more than one line).
798  */
799 void
800 pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
801 {
802         char            msgBuf[1024];
803         va_list         args;
804         PGresult   *res;
805
806         if (hooks->noticeRec == NULL)
807                 return;                                 /* nobody home to receive notice? */
808
809         /* Format the message */
810         va_start(args, fmt);
811         vsnprintf(msgBuf, sizeof(msgBuf), libpq_gettext(fmt), args);
812         va_end(args);
813         msgBuf[sizeof(msgBuf) - 1] = '\0';      /* make real sure it's terminated */
814
815         /* Make a PGresult to pass to the notice receiver */
816         res = PQmakeEmptyPGresult(NULL, PGRES_NONFATAL_ERROR);
817         if (!res)
818                 return;
819         res->noticeHooks = *hooks;
820
821         /*
822          * Set up fields of notice.
823          */
824         pqSaveMessageField(res, PG_DIAG_MESSAGE_PRIMARY, msgBuf);
825         pqSaveMessageField(res, PG_DIAG_SEVERITY, libpq_gettext("NOTICE"));
826         /* XXX should provide a SQLSTATE too? */
827
828         /*
829          * Result text is always just the primary message + newline. If we can't
830          * allocate it, don't bother invoking the receiver.
831          */
832         res->errMsg = (char *) pqResultAlloc(res, strlen(msgBuf) + 2, FALSE);
833         if (res->errMsg)
834         {
835                 sprintf(res->errMsg, "%s\n", msgBuf);
836
837                 /*
838                  * Pass to receiver, then free it.
839                  */
840                 (*res->noticeHooks.noticeRec) (res->noticeHooks.noticeRecArg, res);
841         }
842         PQclear(res);
843 }
844
845 /*
846  * pqAddTuple
847  *        add a row pointer to the PGresult structure, growing it if necessary
848  *        Returns TRUE if OK, FALSE if not enough memory to add the row
849  */
850 static bool
851 pqAddTuple(PGresult *res, PGresAttValue *tup)
852 {
853         if (res->ntups >= res->tupArrSize)
854         {
855                 /*
856                  * Try to grow the array.
857                  *
858                  * We can use realloc because shallow copying of the structure is
859                  * okay. Note that the first time through, res->tuples is NULL. While
860                  * ANSI says that realloc() should act like malloc() in that case,
861                  * some old C libraries (like SunOS 4.1.x) coredump instead. On
862                  * failure realloc is supposed to return NULL without damaging the
863                  * existing allocation. Note that the positions beyond res->ntups are
864                  * garbage, not necessarily NULL.
865                  */
866                 int                     newSize = (res->tupArrSize > 0) ? res->tupArrSize * 2 : 128;
867                 PGresAttValue **newTuples;
868
869                 if (res->tuples == NULL)
870                         newTuples = (PGresAttValue **)
871                                 malloc(newSize * sizeof(PGresAttValue *));
872                 else
873                         newTuples = (PGresAttValue **)
874                                 realloc(res->tuples, newSize * sizeof(PGresAttValue *));
875                 if (!newTuples)
876                         return FALSE;           /* malloc or realloc failed */
877                 res->tupArrSize = newSize;
878                 res->tuples = newTuples;
879         }
880         res->tuples[res->ntups] = tup;
881         res->ntups++;
882         return TRUE;
883 }
884
885 /*
886  * pqSaveMessageField - save one field of an error or notice message
887  */
888 void
889 pqSaveMessageField(PGresult *res, char code, const char *value)
890 {
891         PGMessageField *pfield;
892
893         pfield = (PGMessageField *)
894                 pqResultAlloc(res,
895                                           offsetof(PGMessageField, contents) +
896                                           strlen(value) + 1,
897                                           TRUE);
898         if (!pfield)
899                 return;                                 /* out of memory? */
900         pfield->code = code;
901         strcpy(pfield->contents, value);
902         pfield->next = res->errFields;
903         res->errFields = pfield;
904 }
905
906 /*
907  * pqSaveParameterStatus - remember parameter status sent by backend
908  */
909 void
910 pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
911 {
912         pgParameterStatus *pstatus;
913         pgParameterStatus *prev;
914
915         if (conn->Pfdebug)
916                 fprintf(conn->Pfdebug, "pqSaveParameterStatus: '%s' = '%s'\n",
917                                 name, value);
918
919         /*
920          * Forget any old information about the parameter
921          */
922         for (pstatus = conn->pstatus, prev = NULL;
923                  pstatus != NULL;
924                  prev = pstatus, pstatus = pstatus->next)
925         {
926                 if (strcmp(pstatus->name, name) == 0)
927                 {
928                         if (prev)
929                                 prev->next = pstatus->next;
930                         else
931                                 conn->pstatus = pstatus->next;
932                         free(pstatus);          /* frees name and value strings too */
933                         break;
934                 }
935         }
936
937         /*
938          * Store new info as a single malloc block
939          */
940         pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
941                                                                                    strlen(name) +strlen(value) + 2);
942         if (pstatus)
943         {
944                 char       *ptr;
945
946                 ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
947                 pstatus->name = ptr;
948                 strcpy(ptr, name);
949                 ptr += strlen(name) + 1;
950                 pstatus->value = ptr;
951                 strcpy(ptr, value);
952                 pstatus->next = conn->pstatus;
953                 conn->pstatus = pstatus;
954         }
955
956         /*
957          * Special hacks: remember client_encoding and
958          * standard_conforming_strings, and convert server version to a numeric
959          * form.  We keep the first two of these in static variables as well, so
960          * that PQescapeString and PQescapeBytea can behave somewhat sanely (at
961          * least in single-connection-using programs).
962          */
963         if (strcmp(name, "client_encoding") == 0)
964         {
965                 conn->client_encoding = pg_char_to_encoding(value);
966                 /* if we don't recognize the encoding name, fall back to SQL_ASCII */
967                 if (conn->client_encoding < 0)
968                         conn->client_encoding = PG_SQL_ASCII;
969                 static_client_encoding = conn->client_encoding;
970         }
971         else if (strcmp(name, "standard_conforming_strings") == 0)
972         {
973                 conn->std_strings = (strcmp(value, "on") == 0);
974                 static_std_strings = conn->std_strings;
975         }
976         else if (strcmp(name, "server_version") == 0)
977         {
978                 int                     cnt;
979                 int                     vmaj,
980                                         vmin,
981                                         vrev;
982
983                 cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
984
985                 if (cnt < 2)
986                         conn->sversion = 0; /* unknown */
987                 else
988                 {
989                         if (cnt == 2)
990                                 vrev = 0;
991                         conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
992                 }
993         }
994 }
995
996
997 /*
998  * pqRowProcessor
999  *        Add the received row to the current async result (conn->result).
1000  *        Returns 1 if OK, 0 if error occurred.
1001  *
1002  * On error, *errmsgp can be set to an error string to be returned.
1003  * If it is left NULL, the error is presumed to be "out of memory".
1004  *
1005  * In single-row mode, we create a new result holding just the current row,
1006  * stashing the previous result in conn->next_result so that it becomes
1007  * active again after pqPrepareAsyncResult().  This allows the result metadata
1008  * (column descriptions) to be carried forward to each result row.
1009  */
1010 int
1011 pqRowProcessor(PGconn *conn, const char **errmsgp)
1012 {
1013         PGresult   *res = conn->result;
1014         int                     nfields = res->numAttributes;
1015         const PGdataValue *columns = conn->rowBuf;
1016         PGresAttValue *tup;
1017         int                     i;
1018
1019         /*
1020          * In single-row mode, make a new PGresult that will hold just this one
1021          * row; the original conn->result is left unchanged so that it can be used
1022          * again as the template for future rows.
1023          */
1024         if (conn->singleRowMode)
1025         {
1026                 /* Copy everything that should be in the result at this point */
1027                 res = PQcopyResult(res,
1028                                                    PG_COPYRES_ATTRS | PG_COPYRES_EVENTS |
1029                                                    PG_COPYRES_NOTICEHOOKS);
1030                 if (!res)
1031                         return 0;
1032         }
1033
1034         /*
1035          * Basically we just allocate space in the PGresult for each field and
1036          * copy the data over.
1037          *
1038          * Note: on malloc failure, we return 0 leaving *errmsgp still NULL, which
1039          * caller will take to mean "out of memory".  This is preferable to trying
1040          * to set up such a message here, because evidently there's not enough
1041          * memory for gettext() to do anything.
1042          */
1043         tup = (PGresAttValue *)
1044                 pqResultAlloc(res, nfields * sizeof(PGresAttValue), TRUE);
1045         if (tup == NULL)
1046                 goto fail;
1047
1048         for (i = 0; i < nfields; i++)
1049         {
1050                 int                     clen = columns[i].len;
1051
1052                 if (clen < 0)
1053                 {
1054                         /* null field */
1055                         tup[i].len = NULL_LEN;
1056                         tup[i].value = res->null_field;
1057                 }
1058                 else
1059                 {
1060                         bool            isbinary = (res->attDescs[i].format != 0);
1061                         char       *val;
1062
1063                         val = (char *) pqResultAlloc(res, clen + 1, isbinary);
1064                         if (val == NULL)
1065                                 goto fail;
1066
1067                         /* copy and zero-terminate the data (even if it's binary) */
1068                         memcpy(val, columns[i].value, clen);
1069                         val[clen] = '\0';
1070
1071                         tup[i].len = clen;
1072                         tup[i].value = val;
1073                 }
1074         }
1075
1076         /* And add the tuple to the PGresult's tuple array */
1077         if (!pqAddTuple(res, tup))
1078                 goto fail;
1079
1080         /*
1081          * Success.  In single-row mode, make the result available to the client
1082          * immediately.
1083          */
1084         if (conn->singleRowMode)
1085         {
1086                 /* Change result status to special single-row value */
1087                 res->resultStatus = PGRES_SINGLE_TUPLE;
1088                 /* Stash old result for re-use later */
1089                 conn->next_result = conn->result;
1090                 conn->result = res;
1091                 /* And mark the result ready to return */
1092                 conn->asyncStatus = PGASYNC_READY;
1093         }
1094
1095         return 1;
1096
1097 fail:
1098         /* release locally allocated PGresult, if we made one */
1099         if (res != conn->result)
1100                 PQclear(res);
1101         return 0;
1102 }
1103
1104
1105 /*
1106  * PQsendQuery
1107  *       Submit a query, but don't wait for it to finish
1108  *
1109  * Returns: 1 if successfully submitted
1110  *                      0 if error (conn->errorMessage is set)
1111  */
1112 int
1113 PQsendQuery(PGconn *conn, const char *query)
1114 {
1115         if (!PQsendQueryStart(conn))
1116                 return 0;
1117
1118         /* check the argument */
1119         if (!query)
1120         {
1121                 printfPQExpBuffer(&conn->errorMessage,
1122                                                 libpq_gettext("command string is a null pointer\n"));
1123                 return 0;
1124         }
1125
1126         /* construct the outgoing Query message */
1127         if (pqPutMsgStart('Q', false, conn) < 0 ||
1128                 pqPuts(query, conn) < 0 ||
1129                 pqPutMsgEnd(conn) < 0)
1130         {
1131                 pqHandleSendFailure(conn);
1132                 return 0;
1133         }
1134
1135         /* remember we are using simple query protocol */
1136         conn->queryclass = PGQUERY_SIMPLE;
1137
1138         /* and remember the query text too, if possible */
1139         /* if insufficient memory, last_query just winds up NULL */
1140         if (conn->last_query)
1141                 free(conn->last_query);
1142         conn->last_query = strdup(query);
1143
1144         /*
1145          * Give the data a push.  In nonblock mode, don't complain if we're unable
1146          * to send it all; PQgetResult() will do any additional flushing needed.
1147          */
1148         if (pqFlush(conn) < 0)
1149         {
1150                 pqHandleSendFailure(conn);
1151                 return 0;
1152         }
1153
1154         /* OK, it's launched! */
1155         conn->asyncStatus = PGASYNC_BUSY;
1156         return 1;
1157 }
1158
1159 /*
1160  * PQsendQueryParams
1161  *              Like PQsendQuery, but use protocol 3.0 so we can pass parameters
1162  */
1163 int
1164 PQsendQueryParams(PGconn *conn,
1165                                   const char *command,
1166                                   int nParams,
1167                                   const Oid *paramTypes,
1168                                   const char *const * paramValues,
1169                                   const int *paramLengths,
1170                                   const int *paramFormats,
1171                                   int resultFormat)
1172 {
1173         if (!PQsendQueryStart(conn))
1174                 return 0;
1175
1176         /* check the arguments */
1177         if (!command)
1178         {
1179                 printfPQExpBuffer(&conn->errorMessage,
1180                                                 libpq_gettext("command string is a null pointer\n"));
1181                 return 0;
1182         }
1183         if (nParams < 0 || nParams > 65535)
1184         {
1185                 printfPQExpBuffer(&conn->errorMessage,
1186                 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1187                 return 0;
1188         }
1189
1190         return PQsendQueryGuts(conn,
1191                                                    command,
1192                                                    "",  /* use unnamed statement */
1193                                                    nParams,
1194                                                    paramTypes,
1195                                                    paramValues,
1196                                                    paramLengths,
1197                                                    paramFormats,
1198                                                    resultFormat);
1199 }
1200
1201 /*
1202  * PQsendPrepare
1203  *       Submit a Parse message, but don't wait for it to finish
1204  *
1205  * Returns: 1 if successfully submitted
1206  *                      0 if error (conn->errorMessage is set)
1207  */
1208 int
1209 PQsendPrepare(PGconn *conn,
1210                           const char *stmtName, const char *query,
1211                           int nParams, const Oid *paramTypes)
1212 {
1213         if (!PQsendQueryStart(conn))
1214                 return 0;
1215
1216         /* check the arguments */
1217         if (!stmtName)
1218         {
1219                 printfPQExpBuffer(&conn->errorMessage,
1220                                                 libpq_gettext("statement name is a null pointer\n"));
1221                 return 0;
1222         }
1223         if (!query)
1224         {
1225                 printfPQExpBuffer(&conn->errorMessage,
1226                                                 libpq_gettext("command string is a null pointer\n"));
1227                 return 0;
1228         }
1229         if (nParams < 0 || nParams > 65535)
1230         {
1231                 printfPQExpBuffer(&conn->errorMessage,
1232                 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1233                 return 0;
1234         }
1235
1236         /* This isn't gonna work on a 2.0 server */
1237         if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1238         {
1239                 printfPQExpBuffer(&conn->errorMessage,
1240                  libpq_gettext("function requires at least protocol version 3.0\n"));
1241                 return 0;
1242         }
1243
1244         /* construct the Parse message */
1245         if (pqPutMsgStart('P', false, conn) < 0 ||
1246                 pqPuts(stmtName, conn) < 0 ||
1247                 pqPuts(query, conn) < 0)
1248                 goto sendFailed;
1249
1250         if (nParams > 0 && paramTypes)
1251         {
1252                 int                     i;
1253
1254                 if (pqPutInt(nParams, 2, conn) < 0)
1255                         goto sendFailed;
1256                 for (i = 0; i < nParams; i++)
1257                 {
1258                         if (pqPutInt(paramTypes[i], 4, conn) < 0)
1259                                 goto sendFailed;
1260                 }
1261         }
1262         else
1263         {
1264                 if (pqPutInt(0, 2, conn) < 0)
1265                         goto sendFailed;
1266         }
1267         if (pqPutMsgEnd(conn) < 0)
1268                 goto sendFailed;
1269
1270         /* construct the Sync message */
1271         if (pqPutMsgStart('S', false, conn) < 0 ||
1272                 pqPutMsgEnd(conn) < 0)
1273                 goto sendFailed;
1274
1275         /* remember we are doing just a Parse */
1276         conn->queryclass = PGQUERY_PREPARE;
1277
1278         /* and remember the query text too, if possible */
1279         /* if insufficient memory, last_query just winds up NULL */
1280         if (conn->last_query)
1281                 free(conn->last_query);
1282         conn->last_query = strdup(query);
1283
1284         /*
1285          * Give the data a push.  In nonblock mode, don't complain if we're unable
1286          * to send it all; PQgetResult() will do any additional flushing needed.
1287          */
1288         if (pqFlush(conn) < 0)
1289                 goto sendFailed;
1290
1291         /* OK, it's launched! */
1292         conn->asyncStatus = PGASYNC_BUSY;
1293         return 1;
1294
1295 sendFailed:
1296         pqHandleSendFailure(conn);
1297         return 0;
1298 }
1299
1300 /*
1301  * PQsendQueryPrepared
1302  *              Like PQsendQuery, but execute a previously prepared statement,
1303  *              using protocol 3.0 so we can pass parameters
1304  */
1305 int
1306 PQsendQueryPrepared(PGconn *conn,
1307                                         const char *stmtName,
1308                                         int nParams,
1309                                         const char *const * paramValues,
1310                                         const int *paramLengths,
1311                                         const int *paramFormats,
1312                                         int resultFormat)
1313 {
1314         if (!PQsendQueryStart(conn))
1315                 return 0;
1316
1317         /* check the arguments */
1318         if (!stmtName)
1319         {
1320                 printfPQExpBuffer(&conn->errorMessage,
1321                                                 libpq_gettext("statement name is a null pointer\n"));
1322                 return 0;
1323         }
1324         if (nParams < 0 || nParams > 65535)
1325         {
1326                 printfPQExpBuffer(&conn->errorMessage,
1327                 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1328                 return 0;
1329         }
1330
1331         return PQsendQueryGuts(conn,
1332                                                    NULL,        /* no command to parse */
1333                                                    stmtName,
1334                                                    nParams,
1335                                                    NULL,        /* no param types */
1336                                                    paramValues,
1337                                                    paramLengths,
1338                                                    paramFormats,
1339                                                    resultFormat);
1340 }
1341
1342 /*
1343  * Common startup code for PQsendQuery and sibling routines
1344  */
1345 static bool
1346 PQsendQueryStart(PGconn *conn)
1347 {
1348         if (!conn)
1349                 return false;
1350
1351         /* clear the error string */
1352         resetPQExpBuffer(&conn->errorMessage);
1353
1354         /* Don't try to send if we know there's no live connection. */
1355         if (conn->status != CONNECTION_OK)
1356         {
1357                 printfPQExpBuffer(&conn->errorMessage,
1358                                                   libpq_gettext("no connection to the server\n"));
1359                 return false;
1360         }
1361         /* Can't send while already busy, either. */
1362         if (conn->asyncStatus != PGASYNC_IDLE)
1363         {
1364                 printfPQExpBuffer(&conn->errorMessage,
1365                                   libpq_gettext("another command is already in progress\n"));
1366                 return false;
1367         }
1368
1369         /* initialize async result-accumulation state */
1370         conn->result = NULL;
1371         conn->next_result = NULL;
1372
1373         /* reset single-row processing mode */
1374         conn->singleRowMode = false;
1375
1376         /* ready to send command message */
1377         return true;
1378 }
1379
1380 /*
1381  * PQsendQueryGuts
1382  *              Common code for protocol-3.0 query sending
1383  *              PQsendQueryStart should be done already
1384  *
1385  * command may be NULL to indicate we use an already-prepared statement
1386  */
1387 static int
1388 PQsendQueryGuts(PGconn *conn,
1389                                 const char *command,
1390                                 const char *stmtName,
1391                                 int nParams,
1392                                 const Oid *paramTypes,
1393                                 const char *const * paramValues,
1394                                 const int *paramLengths,
1395                                 const int *paramFormats,
1396                                 int resultFormat)
1397 {
1398         int                     i;
1399
1400         /* This isn't gonna work on a 2.0 server */
1401         if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1402         {
1403                 printfPQExpBuffer(&conn->errorMessage,
1404                  libpq_gettext("function requires at least protocol version 3.0\n"));
1405                 return 0;
1406         }
1407
1408         /*
1409          * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync,
1410          * using specified statement name and the unnamed portal.
1411          */
1412
1413         if (command)
1414         {
1415                 /* construct the Parse message */
1416                 if (pqPutMsgStart('P', false, conn) < 0 ||
1417                         pqPuts(stmtName, conn) < 0 ||
1418                         pqPuts(command, conn) < 0)
1419                         goto sendFailed;
1420                 if (nParams > 0 && paramTypes)
1421                 {
1422                         if (pqPutInt(nParams, 2, conn) < 0)
1423                                 goto sendFailed;
1424                         for (i = 0; i < nParams; i++)
1425                         {
1426                                 if (pqPutInt(paramTypes[i], 4, conn) < 0)
1427                                         goto sendFailed;
1428                         }
1429                 }
1430                 else
1431                 {
1432                         if (pqPutInt(0, 2, conn) < 0)
1433                                 goto sendFailed;
1434                 }
1435                 if (pqPutMsgEnd(conn) < 0)
1436                         goto sendFailed;
1437         }
1438
1439         /* Construct the Bind message */
1440         if (pqPutMsgStart('B', false, conn) < 0 ||
1441                 pqPuts("", conn) < 0 ||
1442                 pqPuts(stmtName, conn) < 0)
1443                 goto sendFailed;
1444
1445         /* Send parameter formats */
1446         if (nParams > 0 && paramFormats)
1447         {
1448                 if (pqPutInt(nParams, 2, conn) < 0)
1449                         goto sendFailed;
1450                 for (i = 0; i < nParams; i++)
1451                 {
1452                         if (pqPutInt(paramFormats[i], 2, conn) < 0)
1453                                 goto sendFailed;
1454                 }
1455         }
1456         else
1457         {
1458                 if (pqPutInt(0, 2, conn) < 0)
1459                         goto sendFailed;
1460         }
1461
1462         if (pqPutInt(nParams, 2, conn) < 0)
1463                 goto sendFailed;
1464
1465         /* Send parameters */
1466         for (i = 0; i < nParams; i++)
1467         {
1468                 if (paramValues && paramValues[i])
1469                 {
1470                         int                     nbytes;
1471
1472                         if (paramFormats && paramFormats[i] != 0)
1473                         {
1474                                 /* binary parameter */
1475                                 if (paramLengths)
1476                                         nbytes = paramLengths[i];
1477                                 else
1478                                 {
1479                                         printfPQExpBuffer(&conn->errorMessage,
1480                                                                           libpq_gettext("length must be given for binary parameter\n"));
1481                                         goto sendFailed;
1482                                 }
1483                         }
1484                         else
1485                         {
1486                                 /* text parameter, do not use paramLengths */
1487                                 nbytes = strlen(paramValues[i]);
1488                         }
1489                         if (pqPutInt(nbytes, 4, conn) < 0 ||
1490                                 pqPutnchar(paramValues[i], nbytes, conn) < 0)
1491                                 goto sendFailed;
1492                 }
1493                 else
1494                 {
1495                         /* take the param as NULL */
1496                         if (pqPutInt(-1, 4, conn) < 0)
1497                                 goto sendFailed;
1498                 }
1499         }
1500         if (pqPutInt(1, 2, conn) < 0 ||
1501                 pqPutInt(resultFormat, 2, conn))
1502                 goto sendFailed;
1503         if (pqPutMsgEnd(conn) < 0)
1504                 goto sendFailed;
1505
1506         /* construct the Describe Portal message */
1507         if (pqPutMsgStart('D', false, conn) < 0 ||
1508                 pqPutc('P', conn) < 0 ||
1509                 pqPuts("", conn) < 0 ||
1510                 pqPutMsgEnd(conn) < 0)
1511                 goto sendFailed;
1512
1513         /* construct the Execute message */
1514         if (pqPutMsgStart('E', false, conn) < 0 ||
1515                 pqPuts("", conn) < 0 ||
1516                 pqPutInt(0, 4, conn) < 0 ||
1517                 pqPutMsgEnd(conn) < 0)
1518                 goto sendFailed;
1519
1520         /* construct the Sync message */
1521         if (pqPutMsgStart('S', false, conn) < 0 ||
1522                 pqPutMsgEnd(conn) < 0)
1523                 goto sendFailed;
1524
1525         /* remember we are using extended query protocol */
1526         conn->queryclass = PGQUERY_EXTENDED;
1527
1528         /* and remember the query text too, if possible */
1529         /* if insufficient memory, last_query just winds up NULL */
1530         if (conn->last_query)
1531                 free(conn->last_query);
1532         if (command)
1533                 conn->last_query = strdup(command);
1534         else
1535                 conn->last_query = NULL;
1536
1537         /*
1538          * Give the data a push.  In nonblock mode, don't complain if we're unable
1539          * to send it all; PQgetResult() will do any additional flushing needed.
1540          */
1541         if (pqFlush(conn) < 0)
1542                 goto sendFailed;
1543
1544         /* OK, it's launched! */
1545         conn->asyncStatus = PGASYNC_BUSY;
1546         return 1;
1547
1548 sendFailed:
1549         pqHandleSendFailure(conn);
1550         return 0;
1551 }
1552
1553 /*
1554  * pqHandleSendFailure: try to clean up after failure to send command.
1555  *
1556  * Primarily, what we want to accomplish here is to process an async
1557  * NOTICE message that the backend might have sent just before it died.
1558  *
1559  * NOTE: this routine should only be called in PGASYNC_IDLE state.
1560  */
1561 void
1562 pqHandleSendFailure(PGconn *conn)
1563 {
1564         /*
1565          * Accept any available input data, ignoring errors.  Note that if
1566          * pqReadData decides the backend has closed the channel, it will close
1567          * our side of the socket --- that's just what we want here.
1568          */
1569         while (pqReadData(conn) > 0)
1570                  /* loop until no more data readable */ ;
1571
1572         /*
1573          * Parse any available input messages.  Since we are in PGASYNC_IDLE
1574          * state, only NOTICE and NOTIFY messages will be eaten.
1575          */
1576         parseInput(conn);
1577 }
1578
1579 /*
1580  * Select row-by-row processing mode
1581  */
1582 int
1583 PQsetSingleRowMode(PGconn *conn)
1584 {
1585         /*
1586          * Only allow setting the flag when we have launched a query and not yet
1587          * received any results.
1588          */
1589         if (!conn)
1590                 return 0;
1591         if (conn->asyncStatus != PGASYNC_BUSY)
1592                 return 0;
1593         if (conn->queryclass != PGQUERY_SIMPLE &&
1594                 conn->queryclass != PGQUERY_EXTENDED)
1595                 return 0;
1596         if (conn->result)
1597                 return 0;
1598
1599         /* OK, set flag */
1600         conn->singleRowMode = true;
1601         return 1;
1602 }
1603
1604 /*
1605  * Consume any available input from the backend
1606  * 0 return: some kind of trouble
1607  * 1 return: no problem
1608  */
1609 int
1610 PQconsumeInput(PGconn *conn)
1611 {
1612         if (!conn)
1613                 return 0;
1614
1615         /*
1616          * for non-blocking connections try to flush the send-queue, otherwise we
1617          * may never get a response for something that may not have already been
1618          * sent because it's in our write buffer!
1619          */
1620         if (pqIsnonblocking(conn))
1621         {
1622                 if (pqFlush(conn) < 0)
1623                         return 0;
1624         }
1625
1626         /*
1627          * Load more data, if available. We do this no matter what state we are
1628          * in, since we are probably getting called because the application wants
1629          * to get rid of a read-select condition. Note that we will NOT block
1630          * waiting for more input.
1631          */
1632         if (pqReadData(conn) < 0)
1633                 return 0;
1634
1635         /* Parsing of the data waits till later. */
1636         return 1;
1637 }
1638
1639
1640 /*
1641  * parseInput: if appropriate, parse input data from backend
1642  * until input is exhausted or a stopping state is reached.
1643  * Note that this function will NOT attempt to read more data from the backend.
1644  */
1645 static void
1646 parseInput(PGconn *conn)
1647 {
1648         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1649                 pqParseInput3(conn);
1650         else
1651                 pqParseInput2(conn);
1652 }
1653
1654 /*
1655  * PQisBusy
1656  *       Return TRUE if PQgetResult would block waiting for input.
1657  */
1658
1659 int
1660 PQisBusy(PGconn *conn)
1661 {
1662         if (!conn)
1663                 return FALSE;
1664
1665         /* Parse any available data, if our state permits. */
1666         parseInput(conn);
1667
1668         /* PQgetResult will return immediately in all states except BUSY. */
1669         return conn->asyncStatus == PGASYNC_BUSY;
1670 }
1671
1672
1673 /*
1674  * PQgetResult
1675  *        Get the next PGresult produced by a query.  Returns NULL if no
1676  *        query work remains or an error has occurred (e.g. out of
1677  *        memory).
1678  */
1679
1680 PGresult *
1681 PQgetResult(PGconn *conn)
1682 {
1683         PGresult   *res;
1684
1685         if (!conn)
1686                 return NULL;
1687
1688         /* Parse any available data, if our state permits. */
1689         parseInput(conn);
1690
1691         /* If not ready to return something, block until we are. */
1692         while (conn->asyncStatus == PGASYNC_BUSY)
1693         {
1694                 int                     flushResult;
1695
1696                 /*
1697                  * If data remains unsent, send it.  Else we might be waiting for the
1698                  * result of a command the backend hasn't even got yet.
1699                  */
1700                 while ((flushResult = pqFlush(conn)) > 0)
1701                 {
1702                         if (pqWait(FALSE, TRUE, conn))
1703                         {
1704                                 flushResult = -1;
1705                                 break;
1706                         }
1707                 }
1708
1709                 /* Wait for some more data, and load it. */
1710                 if (flushResult ||
1711                         pqWait(TRUE, FALSE, conn) ||
1712                         pqReadData(conn) < 0)
1713                 {
1714                         /*
1715                          * conn->errorMessage has been set by pqWait or pqReadData. We
1716                          * want to append it to any already-received error message.
1717                          */
1718                         pqSaveErrorResult(conn);
1719                         conn->asyncStatus = PGASYNC_IDLE;
1720                         return pqPrepareAsyncResult(conn);
1721                 }
1722
1723                 /* Parse it. */
1724                 parseInput(conn);
1725         }
1726
1727         /* Return the appropriate thing. */
1728         switch (conn->asyncStatus)
1729         {
1730                 case PGASYNC_IDLE:
1731                         res = NULL;                     /* query is complete */
1732                         break;
1733                 case PGASYNC_READY:
1734                         res = pqPrepareAsyncResult(conn);
1735                         /* Set the state back to BUSY, allowing parsing to proceed. */
1736                         conn->asyncStatus = PGASYNC_BUSY;
1737                         break;
1738                 case PGASYNC_COPY_IN:
1739                         res = getCopyResult(conn, PGRES_COPY_IN);
1740                         break;
1741                 case PGASYNC_COPY_OUT:
1742                         res = getCopyResult(conn, PGRES_COPY_OUT);
1743                         break;
1744                 case PGASYNC_COPY_BOTH:
1745                         res = getCopyResult(conn, PGRES_COPY_BOTH);
1746                         break;
1747                 default:
1748                         printfPQExpBuffer(&conn->errorMessage,
1749                                                           libpq_gettext("unexpected asyncStatus: %d\n"),
1750                                                           (int) conn->asyncStatus);
1751                         res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1752                         break;
1753         }
1754
1755         if (res)
1756         {
1757                 int                     i;
1758
1759                 for (i = 0; i < res->nEvents; i++)
1760                 {
1761                         PGEventResultCreate evt;
1762
1763                         evt.conn = conn;
1764                         evt.result = res;
1765                         if (!res->events[i].proc(PGEVT_RESULTCREATE, &evt,
1766                                                                          res->events[i].passThrough))
1767                         {
1768                                 printfPQExpBuffer(&conn->errorMessage,
1769                                                                   libpq_gettext("PGEventProc \"%s\" failed during PGEVT_RESULTCREATE event\n"),
1770                                                                   res->events[i].name);
1771                                 pqSetResultError(res, conn->errorMessage.data);
1772                                 res->resultStatus = PGRES_FATAL_ERROR;
1773                                 break;
1774                         }
1775                         res->events[i].resultInitialized = TRUE;
1776                 }
1777         }
1778
1779         return res;
1780 }
1781
1782 /*
1783  * getCopyResult
1784  *        Helper for PQgetResult: generate result for COPY-in-progress cases
1785  */
1786 static PGresult *
1787 getCopyResult(PGconn *conn, ExecStatusType copytype)
1788 {
1789         /*
1790          * If the server connection has been lost, don't pretend everything is
1791          * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
1792          * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
1793          * error in the earlier steps in PQgetResult).  The text returned in the
1794          * result is whatever is in conn->errorMessage; we hope that was filled
1795          * with something relevant when the lost connection was detected.
1796          */
1797         if (conn->status != CONNECTION_OK)
1798         {
1799                 pqSaveErrorResult(conn);
1800                 conn->asyncStatus = PGASYNC_IDLE;
1801                 return pqPrepareAsyncResult(conn);
1802         }
1803
1804         /* If we have an async result for the COPY, return that */
1805         if (conn->result && conn->result->resultStatus == copytype)
1806                 return pqPrepareAsyncResult(conn);
1807
1808         /* Otherwise, invent a suitable PGresult */
1809         return PQmakeEmptyPGresult(conn, copytype);
1810 }
1811
1812
1813 /*
1814  * PQexec
1815  *        send a query to the backend and package up the result in a PGresult
1816  *
1817  * If the query was not even sent, return NULL; conn->errorMessage is set to
1818  * a relevant message.
1819  * If the query was sent, a new PGresult is returned (which could indicate
1820  * either success or failure).
1821  * The user is responsible for freeing the PGresult via PQclear()
1822  * when done with it.
1823  */
1824 PGresult *
1825 PQexec(PGconn *conn, const char *query)
1826 {
1827         if (!PQexecStart(conn))
1828                 return NULL;
1829         if (!PQsendQuery(conn, query))
1830                 return NULL;
1831         return PQexecFinish(conn);
1832 }
1833
1834 /*
1835  * PQexecParams
1836  *              Like PQexec, but use protocol 3.0 so we can pass parameters
1837  */
1838 PGresult *
1839 PQexecParams(PGconn *conn,
1840                          const char *command,
1841                          int nParams,
1842                          const Oid *paramTypes,
1843                          const char *const * paramValues,
1844                          const int *paramLengths,
1845                          const int *paramFormats,
1846                          int resultFormat)
1847 {
1848         if (!PQexecStart(conn))
1849                 return NULL;
1850         if (!PQsendQueryParams(conn, command,
1851                                                    nParams, paramTypes, paramValues, paramLengths,
1852                                                    paramFormats, resultFormat))
1853                 return NULL;
1854         return PQexecFinish(conn);
1855 }
1856
1857 /*
1858  * PQprepare
1859  *        Creates a prepared statement by issuing a v3.0 parse message.
1860  *
1861  * If the query was not even sent, return NULL; conn->errorMessage is set to
1862  * a relevant message.
1863  * If the query was sent, a new PGresult is returned (which could indicate
1864  * either success or failure).
1865  * The user is responsible for freeing the PGresult via PQclear()
1866  * when done with it.
1867  */
1868 PGresult *
1869 PQprepare(PGconn *conn,
1870                   const char *stmtName, const char *query,
1871                   int nParams, const Oid *paramTypes)
1872 {
1873         if (!PQexecStart(conn))
1874                 return NULL;
1875         if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
1876                 return NULL;
1877         return PQexecFinish(conn);
1878 }
1879
1880 /*
1881  * PQexecPrepared
1882  *              Like PQexec, but execute a previously prepared statement,
1883  *              using protocol 3.0 so we can pass parameters
1884  */
1885 PGresult *
1886 PQexecPrepared(PGconn *conn,
1887                            const char *stmtName,
1888                            int nParams,
1889                            const char *const * paramValues,
1890                            const int *paramLengths,
1891                            const int *paramFormats,
1892                            int resultFormat)
1893 {
1894         if (!PQexecStart(conn))
1895                 return NULL;
1896         if (!PQsendQueryPrepared(conn, stmtName,
1897                                                          nParams, paramValues, paramLengths,
1898                                                          paramFormats, resultFormat))
1899                 return NULL;
1900         return PQexecFinish(conn);
1901 }
1902
1903 /*
1904  * Common code for PQexec and sibling routines: prepare to send command
1905  */
1906 static bool
1907 PQexecStart(PGconn *conn)
1908 {
1909         PGresult   *result;
1910
1911         if (!conn)
1912                 return false;
1913
1914         /*
1915          * Silently discard any prior query result that application didn't eat.
1916          * This is probably poor design, but it's here for backward compatibility.
1917          */
1918         while ((result = PQgetResult(conn)) != NULL)
1919         {
1920                 ExecStatusType resultStatus = result->resultStatus;
1921
1922                 PQclear(result);                /* only need its status */
1923                 if (resultStatus == PGRES_COPY_IN)
1924                 {
1925                         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1926                         {
1927                                 /* In protocol 3, we can get out of a COPY IN state */
1928                                 if (PQputCopyEnd(conn,
1929                                                  libpq_gettext("COPY terminated by new PQexec")) < 0)
1930                                         return false;
1931                                 /* keep waiting to swallow the copy's failure message */
1932                         }
1933                         else
1934                         {
1935                                 /* In older protocols we have to punt */
1936                                 printfPQExpBuffer(&conn->errorMessage,
1937                                   libpq_gettext("COPY IN state must be terminated first\n"));
1938                                 return false;
1939                         }
1940                 }
1941                 else if (resultStatus == PGRES_COPY_OUT)
1942                 {
1943                         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1944                         {
1945                                 /*
1946                                  * In protocol 3, we can get out of a COPY OUT state: we just
1947                                  * switch back to BUSY and allow the remaining COPY data to be
1948                                  * dropped on the floor.
1949                                  */
1950                                 conn->asyncStatus = PGASYNC_BUSY;
1951                                 /* keep waiting to swallow the copy's completion message */
1952                         }
1953                         else
1954                         {
1955                                 /* In older protocols we have to punt */
1956                                 printfPQExpBuffer(&conn->errorMessage,
1957                                  libpq_gettext("COPY OUT state must be terminated first\n"));
1958                                 return false;
1959                         }
1960                 }
1961                 else if (resultStatus == PGRES_COPY_BOTH)
1962                 {
1963                         /* We don't allow PQexec during COPY BOTH */
1964                         printfPQExpBuffer(&conn->errorMessage,
1965                                          libpq_gettext("PQexec not allowed during COPY BOTH\n"));
1966                         return false;
1967                 }
1968                 /* check for loss of connection, too */
1969                 if (conn->status == CONNECTION_BAD)
1970                         return false;
1971         }
1972
1973         /* OK to send a command */
1974         return true;
1975 }
1976
1977 /*
1978  * Common code for PQexec and sibling routines: wait for command result
1979  */
1980 static PGresult *
1981 PQexecFinish(PGconn *conn)
1982 {
1983         PGresult   *result;
1984         PGresult   *lastResult;
1985
1986         /*
1987          * For backwards compatibility, return the last result if there are more
1988          * than one --- but merge error messages if we get more than one error
1989          * result.
1990          *
1991          * We have to stop if we see copy in/out/both, however. We will resume
1992          * parsing after application performs the data transfer.
1993          *
1994          * Also stop if the connection is lost (else we'll loop infinitely).
1995          */
1996         lastResult = NULL;
1997         while ((result = PQgetResult(conn)) != NULL)
1998         {
1999                 if (lastResult)
2000                 {
2001                         if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
2002                                 result->resultStatus == PGRES_FATAL_ERROR)
2003                         {
2004                                 pqCatenateResultError(lastResult, result->errMsg);
2005                                 PQclear(result);
2006                                 result = lastResult;
2007
2008                                 /*
2009                                  * Make sure PQerrorMessage agrees with concatenated result
2010                                  */
2011                                 resetPQExpBuffer(&conn->errorMessage);
2012                                 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
2013                         }
2014                         else
2015                                 PQclear(lastResult);
2016                 }
2017                 lastResult = result;
2018                 if (result->resultStatus == PGRES_COPY_IN ||
2019                         result->resultStatus == PGRES_COPY_OUT ||
2020                         result->resultStatus == PGRES_COPY_BOTH ||
2021                         conn->status == CONNECTION_BAD)
2022                         break;
2023         }
2024
2025         return lastResult;
2026 }
2027
2028 /*
2029  * PQdescribePrepared
2030  *        Obtain information about a previously prepared statement
2031  *
2032  * If the query was not even sent, return NULL; conn->errorMessage is set to
2033  * a relevant message.
2034  * If the query was sent, a new PGresult is returned (which could indicate
2035  * either success or failure).  On success, the PGresult contains status
2036  * PGRES_COMMAND_OK, and its parameter and column-heading fields describe
2037  * the statement's inputs and outputs respectively.
2038  * The user is responsible for freeing the PGresult via PQclear()
2039  * when done with it.
2040  */
2041 PGresult *
2042 PQdescribePrepared(PGconn *conn, const char *stmt)
2043 {
2044         if (!PQexecStart(conn))
2045                 return NULL;
2046         if (!PQsendDescribe(conn, 'S', stmt))
2047                 return NULL;
2048         return PQexecFinish(conn);
2049 }
2050
2051 /*
2052  * PQdescribePortal
2053  *        Obtain information about a previously created portal
2054  *
2055  * This is much like PQdescribePrepared, except that no parameter info is
2056  * returned.  Note that at the moment, libpq doesn't really expose portals
2057  * to the client; but this can be used with a portal created by a SQL
2058  * DECLARE CURSOR command.
2059  */
2060 PGresult *
2061 PQdescribePortal(PGconn *conn, const char *portal)
2062 {
2063         if (!PQexecStart(conn))
2064                 return NULL;
2065         if (!PQsendDescribe(conn, 'P', portal))
2066                 return NULL;
2067         return PQexecFinish(conn);
2068 }
2069
2070 /*
2071  * PQsendDescribePrepared
2072  *       Submit a Describe Statement command, but don't wait for it to finish
2073  *
2074  * Returns: 1 if successfully submitted
2075  *                      0 if error (conn->errorMessage is set)
2076  */
2077 int
2078 PQsendDescribePrepared(PGconn *conn, const char *stmt)
2079 {
2080         return PQsendDescribe(conn, 'S', stmt);
2081 }
2082
2083 /*
2084  * PQsendDescribePortal
2085  *       Submit a Describe Portal command, but don't wait for it to finish
2086  *
2087  * Returns: 1 if successfully submitted
2088  *                      0 if error (conn->errorMessage is set)
2089  */
2090 int
2091 PQsendDescribePortal(PGconn *conn, const char *portal)
2092 {
2093         return PQsendDescribe(conn, 'P', portal);
2094 }
2095
2096 /*
2097  * PQsendDescribe
2098  *       Common code to send a Describe command
2099  *
2100  * Available options for desc_type are
2101  *       'S' to describe a prepared statement; or
2102  *       'P' to describe a portal.
2103  * Returns 1 on success and 0 on failure.
2104  */
2105 static int
2106 PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
2107 {
2108         /* Treat null desc_target as empty string */
2109         if (!desc_target)
2110                 desc_target = "";
2111
2112         if (!PQsendQueryStart(conn))
2113                 return 0;
2114
2115         /* This isn't gonna work on a 2.0 server */
2116         if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2117         {
2118                 printfPQExpBuffer(&conn->errorMessage,
2119                  libpq_gettext("function requires at least protocol version 3.0\n"));
2120                 return 0;
2121         }
2122
2123         /* construct the Describe message */
2124         if (pqPutMsgStart('D', false, conn) < 0 ||
2125                 pqPutc(desc_type, conn) < 0 ||
2126                 pqPuts(desc_target, conn) < 0 ||
2127                 pqPutMsgEnd(conn) < 0)
2128                 goto sendFailed;
2129
2130         /* construct the Sync message */
2131         if (pqPutMsgStart('S', false, conn) < 0 ||
2132                 pqPutMsgEnd(conn) < 0)
2133                 goto sendFailed;
2134
2135         /* remember we are doing a Describe */
2136         conn->queryclass = PGQUERY_DESCRIBE;
2137
2138         /* reset last-query string (not relevant now) */
2139         if (conn->last_query)
2140         {
2141                 free(conn->last_query);
2142                 conn->last_query = NULL;
2143         }
2144
2145         /*
2146          * Give the data a push.  In nonblock mode, don't complain if we're unable
2147          * to send it all; PQgetResult() will do any additional flushing needed.
2148          */
2149         if (pqFlush(conn) < 0)
2150                 goto sendFailed;
2151
2152         /* OK, it's launched! */
2153         conn->asyncStatus = PGASYNC_BUSY;
2154         return 1;
2155
2156 sendFailed:
2157         pqHandleSendFailure(conn);
2158         return 0;
2159 }
2160
2161 /*
2162  * PQnotifies
2163  *        returns a PGnotify* structure of the latest async notification
2164  * that has not yet been handled
2165  *
2166  * returns NULL, if there is currently
2167  * no unhandled async notification from the backend
2168  *
2169  * the CALLER is responsible for FREE'ing the structure returned
2170  */
2171 PGnotify *
2172 PQnotifies(PGconn *conn)
2173 {
2174         PGnotify   *event;
2175
2176         if (!conn)
2177                 return NULL;
2178
2179         /* Parse any available data to see if we can extract NOTIFY messages. */
2180         parseInput(conn);
2181
2182         event = conn->notifyHead;
2183         if (event)
2184         {
2185                 conn->notifyHead = event->next;
2186                 if (!conn->notifyHead)
2187                         conn->notifyTail = NULL;
2188                 event->next = NULL;             /* don't let app see the internal state */
2189         }
2190         return event;
2191 }
2192
2193 /*
2194  * PQputCopyData - send some data to the backend during COPY IN or COPY BOTH
2195  *
2196  * Returns 1 if successful, 0 if data could not be sent (only possible
2197  * in nonblock mode), or -1 if an error occurs.
2198  */
2199 int
2200 PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
2201 {
2202         if (!conn)
2203                 return -1;
2204         if (conn->asyncStatus != PGASYNC_COPY_IN &&
2205                 conn->asyncStatus != PGASYNC_COPY_BOTH)
2206         {
2207                 printfPQExpBuffer(&conn->errorMessage,
2208                                                   libpq_gettext("no COPY in progress\n"));
2209                 return -1;
2210         }
2211
2212         /*
2213          * Process any NOTICE or NOTIFY messages that might be pending in the
2214          * input buffer.  Since the server might generate many notices during the
2215          * COPY, we want to clean those out reasonably promptly to prevent
2216          * indefinite expansion of the input buffer.  (Note: the actual read of
2217          * input data into the input buffer happens down inside pqSendSome, but
2218          * it's not authorized to get rid of the data again.)
2219          */
2220         parseInput(conn);
2221
2222         if (nbytes > 0)
2223         {
2224                 /*
2225                  * Try to flush any previously sent data in preference to growing the
2226                  * output buffer.  If we can't enlarge the buffer enough to hold the
2227                  * data, return 0 in the nonblock case, else hard error. (For
2228                  * simplicity, always assume 5 bytes of overhead even in protocol 2.0
2229                  * case.)
2230                  */
2231                 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2232                 {
2233                         if (pqFlush(conn) < 0)
2234                                 return -1;
2235                         if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2236                                                                           conn))
2237                                 return pqIsnonblocking(conn) ? 0 : -1;
2238                 }
2239                 /* Send the data (too simple to delegate to fe-protocol files) */
2240                 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2241                 {
2242                         if (pqPutMsgStart('d', false, conn) < 0 ||
2243                                 pqPutnchar(buffer, nbytes, conn) < 0 ||
2244                                 pqPutMsgEnd(conn) < 0)
2245                                 return -1;
2246                 }
2247                 else
2248                 {
2249                         if (pqPutMsgStart(0, false, conn) < 0 ||
2250                                 pqPutnchar(buffer, nbytes, conn) < 0 ||
2251                                 pqPutMsgEnd(conn) < 0)
2252                                 return -1;
2253                 }
2254         }
2255         return 1;
2256 }
2257
2258 /*
2259  * PQputCopyEnd - send EOF indication to the backend during COPY IN
2260  *
2261  * After calling this, use PQgetResult() to check command completion status.
2262  *
2263  * Returns 1 if successful, 0 if data could not be sent (only possible
2264  * in nonblock mode), or -1 if an error occurs.
2265  */
2266 int
2267 PQputCopyEnd(PGconn *conn, const char *errormsg)
2268 {
2269         if (!conn)
2270                 return -1;
2271         if (conn->asyncStatus != PGASYNC_COPY_IN &&
2272                 conn->asyncStatus != PGASYNC_COPY_BOTH)
2273         {
2274                 printfPQExpBuffer(&conn->errorMessage,
2275                                                   libpq_gettext("no COPY in progress\n"));
2276                 return -1;
2277         }
2278
2279         /*
2280          * Send the COPY END indicator.  This is simple enough that we don't
2281          * bother delegating it to the fe-protocol files.
2282          */
2283         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2284         {
2285                 if (errormsg)
2286                 {
2287                         /* Send COPY FAIL */
2288                         if (pqPutMsgStart('f', false, conn) < 0 ||
2289                                 pqPuts(errormsg, conn) < 0 ||
2290                                 pqPutMsgEnd(conn) < 0)
2291                                 return -1;
2292                 }
2293                 else
2294                 {
2295                         /* Send COPY DONE */
2296                         if (pqPutMsgStart('c', false, conn) < 0 ||
2297                                 pqPutMsgEnd(conn) < 0)
2298                                 return -1;
2299                 }
2300
2301                 /*
2302                  * If we sent the COPY command in extended-query mode, we must issue a
2303                  * Sync as well.
2304                  */
2305                 if (conn->queryclass != PGQUERY_SIMPLE)
2306                 {
2307                         if (pqPutMsgStart('S', false, conn) < 0 ||
2308                                 pqPutMsgEnd(conn) < 0)
2309                                 return -1;
2310                 }
2311         }
2312         else
2313         {
2314                 if (errormsg)
2315                 {
2316                         /* Ooops, no way to do this in 2.0 */
2317                         printfPQExpBuffer(&conn->errorMessage,
2318                                                           libpq_gettext("function requires at least protocol version 3.0\n"));
2319                         return -1;
2320                 }
2321                 else
2322                 {
2323                         /* Send old-style end-of-data marker */
2324                         if (pqPutMsgStart(0, false, conn) < 0 ||
2325                                 pqPutnchar("\\.\n", 3, conn) < 0 ||
2326                                 pqPutMsgEnd(conn) < 0)
2327                                 return -1;
2328                 }
2329         }
2330
2331         /* Return to active duty */
2332         if (conn->asyncStatus == PGASYNC_COPY_BOTH)
2333                 conn->asyncStatus = PGASYNC_COPY_OUT;
2334         else
2335                 conn->asyncStatus = PGASYNC_BUSY;
2336         resetPQExpBuffer(&conn->errorMessage);
2337
2338         /* Try to flush data */
2339         if (pqFlush(conn) < 0)
2340                 return -1;
2341
2342         return 1;
2343 }
2344
2345 /*
2346  * PQgetCopyData - read a row of data from the backend during COPY OUT
2347  * or COPY BOTH
2348  *
2349  * If successful, sets *buffer to point to a malloc'd row of data, and
2350  * returns row length (always > 0) as result.
2351  * Returns 0 if no row available yet (only possible if async is true),
2352  * -1 if end of copy (consult PQgetResult), or -2 if error (consult
2353  * PQerrorMessage).
2354  */
2355 int
2356 PQgetCopyData(PGconn *conn, char **buffer, int async)
2357 {
2358         *buffer = NULL;                         /* for all failure cases */
2359         if (!conn)
2360                 return -2;
2361         if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2362                 conn->asyncStatus != PGASYNC_COPY_BOTH)
2363         {
2364                 printfPQExpBuffer(&conn->errorMessage,
2365                                                   libpq_gettext("no COPY in progress\n"));
2366                 return -2;
2367         }
2368         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2369                 return pqGetCopyData3(conn, buffer, async);
2370         else
2371                 return pqGetCopyData2(conn, buffer, async);
2372 }
2373
2374 /*
2375  * PQgetline - gets a newline-terminated string from the backend.
2376  *
2377  * Chiefly here so that applications can use "COPY <rel> to stdout"
2378  * and read the output string.  Returns a null-terminated string in s.
2379  *
2380  * XXX this routine is now deprecated, because it can't handle binary data.
2381  * If called during a COPY BINARY we return EOF.
2382  *
2383  * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
2384  * the terminating \n (like gets(3)).
2385  *
2386  * CAUTION: the caller is responsible for detecting the end-of-copy signal
2387  * (a line containing just "\.") when using this routine.
2388  *
2389  * RETURNS:
2390  *              EOF if error (eg, invalid arguments are given)
2391  *              0 if EOL is reached (i.e., \n has been read)
2392  *                              (this is required for backward-compatibility -- this
2393  *                               routine used to always return EOF or 0, assuming that
2394  *                               the line ended within maxlen bytes.)
2395  *              1 in other cases (i.e., the buffer was filled before \n is reached)
2396  */
2397 int
2398 PQgetline(PGconn *conn, char *s, int maxlen)
2399 {
2400         if (!s || maxlen <= 0)
2401                 return EOF;
2402         *s = '\0';
2403         /* maxlen must be at least 3 to hold the \. terminator! */
2404         if (maxlen < 3)
2405                 return EOF;
2406
2407         if (!conn)
2408                 return EOF;
2409
2410         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2411                 return pqGetline3(conn, s, maxlen);
2412         else
2413                 return pqGetline2(conn, s, maxlen);
2414 }
2415
2416 /*
2417  * PQgetlineAsync - gets a COPY data row without blocking.
2418  *
2419  * This routine is for applications that want to do "COPY <rel> to stdout"
2420  * asynchronously, that is without blocking.  Having issued the COPY command
2421  * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
2422  * and this routine until the end-of-data signal is detected.  Unlike
2423  * PQgetline, this routine takes responsibility for detecting end-of-data.
2424  *
2425  * On each call, PQgetlineAsync will return data if a complete data row
2426  * is available in libpq's input buffer.  Otherwise, no data is returned
2427  * until the rest of the row arrives.
2428  *
2429  * If -1 is returned, the end-of-data signal has been recognized (and removed
2430  * from libpq's input buffer).  The caller *must* next call PQendcopy and
2431  * then return to normal processing.
2432  *
2433  * RETURNS:
2434  *       -1    if the end-of-copy-data marker has been recognized
2435  *       0         if no data is available
2436  *       >0    the number of bytes returned.
2437  *
2438  * The data returned will not extend beyond a data-row boundary.  If possible
2439  * a whole row will be returned at one time.  But if the buffer offered by
2440  * the caller is too small to hold a row sent by the backend, then a partial
2441  * data row will be returned.  In text mode this can be detected by testing
2442  * whether the last returned byte is '\n' or not.
2443  *
2444  * The returned data is *not* null-terminated.
2445  */
2446
2447 int
2448 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
2449 {
2450         if (!conn)
2451                 return -1;
2452
2453         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2454                 return pqGetlineAsync3(conn, buffer, bufsize);
2455         else
2456                 return pqGetlineAsync2(conn, buffer, bufsize);
2457 }
2458
2459 /*
2460  * PQputline -- sends a string to the backend during COPY IN.
2461  * Returns 0 if OK, EOF if not.
2462  *
2463  * This is deprecated primarily because the return convention doesn't allow
2464  * caller to tell the difference between a hard error and a nonblock-mode
2465  * send failure.
2466  */
2467 int
2468 PQputline(PGconn *conn, const char *s)
2469 {
2470         return PQputnbytes(conn, s, strlen(s));
2471 }
2472
2473 /*
2474  * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
2475  * Returns 0 if OK, EOF if not.
2476  */
2477 int
2478 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
2479 {
2480         if (PQputCopyData(conn, buffer, nbytes) > 0)
2481                 return 0;
2482         else
2483                 return EOF;
2484 }
2485
2486 /*
2487  * PQendcopy
2488  *              After completing the data transfer portion of a copy in/out,
2489  *              the application must call this routine to finish the command protocol.
2490  *
2491  * When using protocol 3.0 this is deprecated; it's cleaner to use PQgetResult
2492  * to get the transfer status.  Note however that when using 2.0 protocol,
2493  * recovering from a copy failure often requires a PQreset.  PQendcopy will
2494  * take care of that, PQgetResult won't.
2495  *
2496  * RETURNS:
2497  *              0 on success
2498  *              1 on failure
2499  */
2500 int
2501 PQendcopy(PGconn *conn)
2502 {
2503         if (!conn)
2504                 return 0;
2505
2506         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2507                 return pqEndcopy3(conn);
2508         else
2509                 return pqEndcopy2(conn);
2510 }
2511
2512
2513 /* ----------------
2514  *              PQfn -  Send a function call to the POSTGRES backend.
2515  *
2516  *              conn                    : backend connection
2517  *              fnid                    : OID of function to be called
2518  *              result_buf              : pointer to result buffer
2519  *              result_len              : actual length of result is returned here
2520  *              result_is_int   : If the result is an integer, this must be 1,
2521  *                                                otherwise this should be 0
2522  *              args                    : pointer to an array of function arguments
2523  *                                                (each has length, if integer, and value/pointer)
2524  *              nargs                   : # of arguments in args array.
2525  *
2526  * RETURNS
2527  *              PGresult with status = PGRES_COMMAND_OK if successful.
2528  *                      *result_len is > 0 if there is a return value, 0 if not.
2529  *              PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
2530  *              NULL on communications failure.  conn->errorMessage will be set.
2531  * ----------------
2532  */
2533
2534 PGresult *
2535 PQfn(PGconn *conn,
2536          int fnid,
2537          int *result_buf,
2538          int *result_len,
2539          int result_is_int,
2540          const PQArgBlock *args,
2541          int nargs)
2542 {
2543         *result_len = 0;
2544
2545         if (!conn)
2546                 return NULL;
2547
2548         /* clear the error string */
2549         resetPQExpBuffer(&conn->errorMessage);
2550
2551         if (conn->sock == PGINVALID_SOCKET || conn->asyncStatus != PGASYNC_IDLE ||
2552                 conn->result != NULL)
2553         {
2554                 printfPQExpBuffer(&conn->errorMessage,
2555                                                   libpq_gettext("connection in wrong state\n"));
2556                 return NULL;
2557         }
2558
2559         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2560                 return pqFunctionCall3(conn, fnid,
2561                                                            result_buf, result_len,
2562                                                            result_is_int,
2563                                                            args, nargs);
2564         else
2565                 return pqFunctionCall2(conn, fnid,
2566                                                            result_buf, result_len,
2567                                                            result_is_int,
2568                                                            args, nargs);
2569 }
2570
2571
2572 /* ====== accessor funcs for PGresult ======== */
2573
2574 ExecStatusType
2575 PQresultStatus(const PGresult *res)
2576 {
2577         if (!res)
2578                 return PGRES_FATAL_ERROR;
2579         return res->resultStatus;
2580 }
2581
2582 char *
2583 PQresStatus(ExecStatusType status)
2584 {
2585         if ((unsigned int) status >= sizeof pgresStatus / sizeof pgresStatus[0])
2586                 return libpq_gettext("invalid ExecStatusType code");
2587         return pgresStatus[status];
2588 }
2589
2590 char *
2591 PQresultErrorMessage(const PGresult *res)
2592 {
2593         if (!res || !res->errMsg)
2594                 return "";
2595         return res->errMsg;
2596 }
2597
2598 char *
2599 PQresultErrorField(const PGresult *res, int fieldcode)
2600 {
2601         PGMessageField *pfield;
2602
2603         if (!res)
2604                 return NULL;
2605         for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
2606         {
2607                 if (pfield->code == fieldcode)
2608                         return pfield->contents;
2609         }
2610         return NULL;
2611 }
2612
2613 int
2614 PQntuples(const PGresult *res)
2615 {
2616         if (!res)
2617                 return 0;
2618         return res->ntups;
2619 }
2620
2621 int
2622 PQnfields(const PGresult *res)
2623 {
2624         if (!res)
2625                 return 0;
2626         return res->numAttributes;
2627 }
2628
2629 int
2630 PQbinaryTuples(const PGresult *res)
2631 {
2632         if (!res)
2633                 return 0;
2634         return res->binary;
2635 }
2636
2637 /*
2638  * Helper routines to range-check field numbers and tuple numbers.
2639  * Return TRUE if OK, FALSE if not
2640  */
2641
2642 static int
2643 check_field_number(const PGresult *res, int field_num)
2644 {
2645         if (!res)
2646                 return FALSE;                   /* no way to display error message... */
2647         if (field_num < 0 || field_num >= res->numAttributes)
2648         {
2649                 pqInternalNotice(&res->noticeHooks,
2650                                                  "column number %d is out of range 0..%d",
2651                                                  field_num, res->numAttributes - 1);
2652                 return FALSE;
2653         }
2654         return TRUE;
2655 }
2656
2657 static int
2658 check_tuple_field_number(const PGresult *res,
2659                                                  int tup_num, int field_num)
2660 {
2661         if (!res)
2662                 return FALSE;                   /* no way to display error message... */
2663         if (tup_num < 0 || tup_num >= res->ntups)
2664         {
2665                 pqInternalNotice(&res->noticeHooks,
2666                                                  "row number %d is out of range 0..%d",
2667                                                  tup_num, res->ntups - 1);
2668                 return FALSE;
2669         }
2670         if (field_num < 0 || field_num >= res->numAttributes)
2671         {
2672                 pqInternalNotice(&res->noticeHooks,
2673                                                  "column number %d is out of range 0..%d",
2674                                                  field_num, res->numAttributes - 1);
2675                 return FALSE;
2676         }
2677         return TRUE;
2678 }
2679
2680 static int
2681 check_param_number(const PGresult *res, int param_num)
2682 {
2683         if (!res)
2684                 return FALSE;                   /* no way to display error message... */
2685         if (param_num < 0 || param_num >= res->numParameters)
2686         {
2687                 pqInternalNotice(&res->noticeHooks,
2688                                                  "parameter number %d is out of range 0..%d",
2689                                                  param_num, res->numParameters - 1);
2690                 return FALSE;
2691         }
2692
2693         return TRUE;
2694 }
2695
2696 /*
2697  * returns NULL if the field_num is invalid
2698  */
2699 char *
2700 PQfname(const PGresult *res, int field_num)
2701 {
2702         if (!check_field_number(res, field_num))
2703                 return NULL;
2704         if (res->attDescs)
2705                 return res->attDescs[field_num].name;
2706         else
2707                 return NULL;
2708 }
2709
2710 /*
2711  * PQfnumber: find column number given column name
2712  *
2713  * The column name is parsed as if it were in a SQL statement, including
2714  * case-folding and double-quote processing.  But note a possible gotcha:
2715  * downcasing in the frontend might follow different locale rules than
2716  * downcasing in the backend...
2717  *
2718  * Returns -1 if no match.  In the present backend it is also possible
2719  * to have multiple matches, in which case the first one is found.
2720  */
2721 int
2722 PQfnumber(const PGresult *res, const char *field_name)
2723 {
2724         char       *field_case;
2725         bool            in_quotes;
2726         bool            all_lower = true;
2727         const char *iptr;
2728         char       *optr;
2729         int                     i;
2730
2731         if (!res)
2732                 return -1;
2733
2734         /*
2735          * Note: it is correct to reject a zero-length input string; the proper
2736          * input to match a zero-length field name would be "".
2737          */
2738         if (field_name == NULL ||
2739                 field_name[0] == '\0' ||
2740                 res->attDescs == NULL)
2741                 return -1;
2742
2743         /*
2744          * Check if we can avoid the strdup() and related work because the
2745          * passed-in string wouldn't be changed before we do the check anyway.
2746          */
2747         for (iptr = field_name; *iptr; iptr++)
2748         {
2749                 char            c = *iptr;
2750
2751                 if (c == '"' || c != pg_tolower((unsigned char) c))
2752                 {
2753                         all_lower = false;
2754                         break;
2755                 }
2756         }
2757
2758         if (all_lower)
2759                 for (i = 0; i < res->numAttributes; i++)
2760                         if (strcmp(field_name, res->attDescs[i].name) == 0)
2761                                 return i;
2762
2763         /* Fall through to the normal check if that didn't work out. */
2764
2765         /*
2766          * Note: this code will not reject partially quoted strings, eg
2767          * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
2768          * condition.
2769          */
2770         field_case = strdup(field_name);
2771         if (field_case == NULL)
2772                 return -1;                              /* grotty */
2773
2774         in_quotes = false;
2775         optr = field_case;
2776         for (iptr = field_case; *iptr; iptr++)
2777         {
2778                 char            c = *iptr;
2779
2780                 if (in_quotes)
2781                 {
2782                         if (c == '"')
2783                         {
2784                                 if (iptr[1] == '"')
2785                                 {
2786                                         /* doubled quotes become a single quote */
2787                                         *optr++ = '"';
2788                                         iptr++;
2789                                 }
2790                                 else
2791                                         in_quotes = false;
2792                         }
2793                         else
2794                                 *optr++ = c;
2795                 }
2796                 else if (c == '"')
2797                         in_quotes = true;
2798                 else
2799                 {
2800                         c = pg_tolower((unsigned char) c);
2801                         *optr++ = c;
2802                 }
2803         }
2804         *optr = '\0';
2805
2806         for (i = 0; i < res->numAttributes; i++)
2807         {
2808                 if (strcmp(field_case, res->attDescs[i].name) == 0)
2809                 {
2810                         free(field_case);
2811                         return i;
2812                 }
2813         }
2814         free(field_case);
2815         return -1;
2816 }
2817
2818 Oid
2819 PQftable(const PGresult *res, int field_num)
2820 {
2821         if (!check_field_number(res, field_num))
2822                 return InvalidOid;
2823         if (res->attDescs)
2824                 return res->attDescs[field_num].tableid;
2825         else
2826                 return InvalidOid;
2827 }
2828
2829 int
2830 PQftablecol(const PGresult *res, int field_num)
2831 {
2832         if (!check_field_number(res, field_num))
2833                 return 0;
2834         if (res->attDescs)
2835                 return res->attDescs[field_num].columnid;
2836         else
2837                 return 0;
2838 }
2839
2840 int
2841 PQfformat(const PGresult *res, int field_num)
2842 {
2843         if (!check_field_number(res, field_num))
2844                 return 0;
2845         if (res->attDescs)
2846                 return res->attDescs[field_num].format;
2847         else
2848                 return 0;
2849 }
2850
2851 Oid
2852 PQftype(const PGresult *res, int field_num)
2853 {
2854         if (!check_field_number(res, field_num))
2855                 return InvalidOid;
2856         if (res->attDescs)
2857                 return res->attDescs[field_num].typid;
2858         else
2859                 return InvalidOid;
2860 }
2861
2862 int
2863 PQfsize(const PGresult *res, int field_num)
2864 {
2865         if (!check_field_number(res, field_num))
2866                 return 0;
2867         if (res->attDescs)
2868                 return res->attDescs[field_num].typlen;
2869         else
2870                 return 0;
2871 }
2872
2873 int
2874 PQfmod(const PGresult *res, int field_num)
2875 {
2876         if (!check_field_number(res, field_num))
2877                 return 0;
2878         if (res->attDescs)
2879                 return res->attDescs[field_num].atttypmod;
2880         else
2881                 return 0;
2882 }
2883
2884 char *
2885 PQcmdStatus(PGresult *res)
2886 {
2887         if (!res)
2888                 return NULL;
2889         return res->cmdStatus;
2890 }
2891
2892 /*
2893  * PQoidStatus -
2894  *      if the last command was an INSERT, return the oid string
2895  *      if not, return ""
2896  */
2897 char *
2898 PQoidStatus(const PGresult *res)
2899 {
2900         /*
2901          * This must be enough to hold the result. Don't laugh, this is better
2902          * than what this function used to do.
2903          */
2904         static char buf[24];
2905
2906         size_t          len;
2907
2908         if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2909                 return "";
2910
2911         len = strspn(res->cmdStatus + 7, "0123456789");
2912         if (len > sizeof(buf) - 1)
2913                 len = sizeof(buf) - 1;
2914         memcpy(buf, res->cmdStatus + 7, len);
2915         buf[len] = '\0';
2916
2917         return buf;
2918 }
2919
2920 /*
2921  * PQoidValue -
2922  *      a perhaps preferable form of the above which just returns
2923  *      an Oid type
2924  */
2925 Oid
2926 PQoidValue(const PGresult *res)
2927 {
2928         char       *endptr = NULL;
2929         unsigned long result;
2930
2931         if (!res ||
2932                 strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
2933                 res->cmdStatus[7] < '0' ||
2934                 res->cmdStatus[7] > '9')
2935                 return InvalidOid;
2936
2937         result = strtoul(res->cmdStatus + 7, &endptr, 10);
2938
2939         if (!endptr || (*endptr != ' ' && *endptr != '\0'))
2940                 return InvalidOid;
2941         else
2942                 return (Oid) result;
2943 }
2944
2945
2946 /*
2947  * PQcmdTuples -
2948  *      If the last command was INSERT/UPDATE/DELETE/MOVE/FETCH/COPY, return
2949  *      a string containing the number of inserted/affected tuples. If not,
2950  *      return "".
2951  *
2952  *      XXX: this should probably return an int
2953  */
2954 char *
2955 PQcmdTuples(PGresult *res)
2956 {
2957         char       *p,
2958                            *c;
2959
2960         if (!res)
2961                 return "";
2962
2963         if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
2964         {
2965                 p = res->cmdStatus + 7;
2966                 /* INSERT: skip oid and space */
2967                 while (*p && *p != ' ')
2968                         p++;
2969                 if (*p == 0)
2970                         goto interpret_error;           /* no space? */
2971                 p++;
2972         }
2973         else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
2974                          strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
2975                          strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
2976                 p = res->cmdStatus + 7;
2977         else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
2978                 p = res->cmdStatus + 6;
2979         else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
2980                          strncmp(res->cmdStatus, "COPY ", 5) == 0)
2981                 p = res->cmdStatus + 5;
2982         else
2983                 return "";
2984
2985         /* check that we have an integer (at least one digit, nothing else) */
2986         for (c = p; *c; c++)
2987         {
2988                 if (!isdigit((unsigned char) *c))
2989                         goto interpret_error;
2990         }
2991         if (c == p)
2992                 goto interpret_error;
2993
2994         return p;
2995
2996 interpret_error:
2997         pqInternalNotice(&res->noticeHooks,
2998                                          "could not interpret result from server: %s",
2999                                          res->cmdStatus);
3000         return "";
3001 }
3002
3003 /*
3004  * PQgetvalue:
3005  *      return the value of field 'field_num' of row 'tup_num'
3006  */
3007 char *
3008 PQgetvalue(const PGresult *res, int tup_num, int field_num)
3009 {
3010         if (!check_tuple_field_number(res, tup_num, field_num))
3011                 return NULL;
3012         return res->tuples[tup_num][field_num].value;
3013 }
3014
3015 /* PQgetlength:
3016  *      returns the actual length of a field value in bytes.
3017  */
3018 int
3019 PQgetlength(const PGresult *res, int tup_num, int field_num)
3020 {
3021         if (!check_tuple_field_number(res, tup_num, field_num))
3022                 return 0;
3023         if (res->tuples[tup_num][field_num].len != NULL_LEN)
3024                 return res->tuples[tup_num][field_num].len;
3025         else
3026                 return 0;
3027 }
3028
3029 /* PQgetisnull:
3030  *      returns the null status of a field value.
3031  */
3032 int
3033 PQgetisnull(const PGresult *res, int tup_num, int field_num)
3034 {
3035         if (!check_tuple_field_number(res, tup_num, field_num))
3036                 return 1;                               /* pretend it is null */
3037         if (res->tuples[tup_num][field_num].len == NULL_LEN)
3038                 return 1;
3039         else
3040                 return 0;
3041 }
3042
3043 /* PQnparams:
3044  *      returns the number of input parameters of a prepared statement.
3045  */
3046 int
3047 PQnparams(const PGresult *res)
3048 {
3049         if (!res)
3050                 return 0;
3051         return res->numParameters;
3052 }
3053
3054 /* PQparamtype:
3055  *      returns type Oid of the specified statement parameter.
3056  */
3057 Oid
3058 PQparamtype(const PGresult *res, int param_num)
3059 {
3060         if (!check_param_number(res, param_num))
3061                 return InvalidOid;
3062         if (res->paramDescs)
3063                 return res->paramDescs[param_num].typid;
3064         else
3065                 return InvalidOid;
3066 }
3067
3068
3069 /* PQsetnonblocking:
3070  *      sets the PGconn's database connection non-blocking if the arg is TRUE
3071  *      or makes it blocking if the arg is FALSE, this will not protect
3072  *      you from PQexec(), you'll only be safe when using the non-blocking API.
3073  *      Needs to be called only on a connected database connection.
3074  */
3075 int
3076 PQsetnonblocking(PGconn *conn, int arg)
3077 {
3078         bool            barg;
3079
3080         if (!conn || conn->status == CONNECTION_BAD)
3081                 return -1;
3082
3083         barg = (arg ? TRUE : FALSE);
3084
3085         /* early out if the socket is already in the state requested */
3086         if (barg == conn->nonblocking)
3087                 return 0;
3088
3089         /*
3090          * to guarantee constancy for flushing/query/result-polling behavior we
3091          * need to flush the send queue at this point in order to guarantee proper
3092          * behavior. this is ok because either they are making a transition _from_
3093          * or _to_ blocking mode, either way we can block them.
3094          */
3095         /* if we are going from blocking to non-blocking flush here */
3096         if (pqFlush(conn))
3097                 return -1;
3098
3099         conn->nonblocking = barg;
3100
3101         return 0;
3102 }
3103
3104 /*
3105  * return the blocking status of the database connection
3106  *              TRUE == nonblocking, FALSE == blocking
3107  */
3108 int
3109 PQisnonblocking(const PGconn *conn)
3110 {
3111         return pqIsnonblocking(conn);
3112 }
3113
3114 /* libpq is thread-safe? */
3115 int
3116 PQisthreadsafe(void)
3117 {
3118 #ifdef ENABLE_THREAD_SAFETY
3119         return true;
3120 #else
3121         return false;
3122 #endif
3123 }
3124
3125
3126 /* try to force data out, really only useful for non-blocking users */
3127 int
3128 PQflush(PGconn *conn)
3129 {
3130         return pqFlush(conn);
3131 }
3132
3133
3134 /*
3135  *              PQfreemem - safely frees memory allocated
3136  *
3137  * Needed mostly by Win32, unless multithreaded DLL (/MD in VC6)
3138  * Used for freeing memory from PQescapeByte()a/PQunescapeBytea()
3139  */
3140 void
3141 PQfreemem(void *ptr)
3142 {
3143         free(ptr);
3144 }
3145
3146 /*
3147  * PQfreeNotify - free's the memory associated with a PGnotify
3148  *
3149  * This function is here only for binary backward compatibility.
3150  * New code should use PQfreemem().  A macro will automatically map
3151  * calls to PQfreemem.  It should be removed in the future.  bjm 2003-03-24
3152  */
3153
3154 #undef PQfreeNotify
3155 void            PQfreeNotify(PGnotify *notify);
3156
3157 void
3158 PQfreeNotify(PGnotify *notify)
3159 {
3160         PQfreemem(notify);
3161 }
3162
3163
3164 /*
3165  * Escaping arbitrary strings to get valid SQL literal strings.
3166  *
3167  * Replaces "'" with "''", and if not std_strings, replaces "\" with "\\".
3168  *
3169  * length is the length of the source string.  (Note: if a terminating NUL
3170  * is encountered sooner, PQescapeString stops short of "length"; the behavior
3171  * is thus rather like strncpy.)
3172  *
3173  * For safety the buffer at "to" must be at least 2*length + 1 bytes long.
3174  * A terminating NUL character is added to the output string, whether the
3175  * input is NUL-terminated or not.
3176  *
3177  * Returns the actual length of the output (not counting the terminating NUL).
3178  */
3179 static size_t
3180 PQescapeStringInternal(PGconn *conn,
3181                                            char *to, const char *from, size_t length,
3182                                            int *error,
3183                                            int encoding, bool std_strings)
3184 {
3185         const char *source = from;
3186         char       *target = to;
3187         size_t          remaining = length;
3188
3189         if (error)
3190                 *error = 0;
3191
3192         while (remaining > 0 && *source != '\0')
3193         {
3194                 char            c = *source;
3195                 int                     len;
3196                 int                     i;
3197
3198                 /* Fast path for plain ASCII */
3199                 if (!IS_HIGHBIT_SET(c))
3200                 {
3201                         /* Apply quoting if needed */
3202                         if (SQL_STR_DOUBLE(c, !std_strings))
3203                                 *target++ = c;
3204                         /* Copy the character */
3205                         *target++ = c;
3206                         source++;
3207                         remaining--;
3208                         continue;
3209                 }
3210
3211                 /* Slow path for possible multibyte characters */
3212                 len = pg_encoding_mblen(encoding, source);
3213
3214                 /* Copy the character */
3215                 for (i = 0; i < len; i++)
3216                 {
3217                         if (remaining == 0 || *source == '\0')
3218                                 break;
3219                         *target++ = *source++;
3220                         remaining--;
3221                 }
3222
3223                 /*
3224                  * If we hit premature end of string (ie, incomplete multibyte
3225                  * character), try to pad out to the correct length with spaces. We
3226                  * may not be able to pad completely, but we will always be able to
3227                  * insert at least one pad space (since we'd not have quoted a
3228                  * multibyte character).  This should be enough to make a string that
3229                  * the server will error out on.
3230                  */
3231                 if (i < len)
3232                 {
3233                         if (error)
3234                                 *error = 1;
3235                         if (conn)
3236                                 printfPQExpBuffer(&conn->errorMessage,
3237                                                   libpq_gettext("incomplete multibyte character\n"));
3238                         for (; i < len; i++)
3239                         {
3240                                 if (((size_t) (target - to)) / 2 >= length)
3241                                         break;
3242                                 *target++ = ' ';
3243                         }
3244                         break;
3245                 }
3246         }
3247
3248         /* Write the terminating NUL character. */
3249         *target = '\0';
3250
3251         return target - to;
3252 }
3253
3254 size_t
3255 PQescapeStringConn(PGconn *conn,
3256                                    char *to, const char *from, size_t length,
3257                                    int *error)
3258 {
3259         if (!conn)
3260         {
3261                 /* force empty-string result */
3262                 *to = '\0';
3263                 if (error)
3264                         *error = 1;
3265                 return 0;
3266         }
3267         return PQescapeStringInternal(conn, to, from, length, error,
3268                                                                   conn->client_encoding,
3269                                                                   conn->std_strings);
3270 }
3271
3272 size_t
3273 PQescapeString(char *to, const char *from, size_t length)
3274 {
3275         return PQescapeStringInternal(NULL, to, from, length, NULL,
3276                                                                   static_client_encoding,
3277                                                                   static_std_strings);
3278 }
3279
3280
3281 /*
3282  * Escape arbitrary strings.  If as_ident is true, we escape the result
3283  * as an identifier; if false, as a literal.  The result is returned in
3284  * a newly allocated buffer.  If we fail due to an encoding violation or out
3285  * of memory condition, we return NULL, storing an error message into conn.
3286  */
3287 static char *
3288 PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
3289 {
3290         const char *s;
3291         char       *result;
3292         char       *rp;
3293         int                     num_quotes = 0; /* single or double, depending on as_ident */
3294         int                     num_backslashes = 0;
3295         int                     input_len;
3296         int                     result_size;
3297         char            quote_char = as_ident ? '"' : '\'';
3298
3299         /* We must have a connection, else fail immediately. */
3300         if (!conn)
3301                 return NULL;
3302
3303         /* Scan the string for characters that must be escaped. */
3304         for (s = str; (s - str) < len && *s != '\0'; ++s)
3305         {
3306                 if (*s == quote_char)
3307                         ++num_quotes;
3308                 else if (*s == '\\')
3309                         ++num_backslashes;
3310                 else if (IS_HIGHBIT_SET(*s))
3311                 {
3312                         int                     charlen;
3313
3314                         /* Slow path for possible multibyte characters */
3315                         charlen = pg_encoding_mblen(conn->client_encoding, s);
3316
3317                         /* Multibyte character overruns allowable length. */
3318                         if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
3319                         {
3320                                 printfPQExpBuffer(&conn->errorMessage,
3321                                                   libpq_gettext("incomplete multibyte character\n"));
3322                                 return NULL;
3323                         }
3324
3325                         /* Adjust s, bearing in mind that for loop will increment it. */
3326                         s += charlen - 1;
3327                 }
3328         }
3329
3330         /* Allocate output buffer. */
3331         input_len = s - str;
3332         result_size = input_len + num_quotes + 3;       /* two quotes, plus a NUL */
3333         if (!as_ident && num_backslashes > 0)
3334                 result_size += num_backslashes + 2;
3335         result = rp = (char *) malloc(result_size);
3336         if (rp == NULL)
3337         {
3338                 printfPQExpBuffer(&conn->errorMessage,
3339                                                   libpq_gettext("out of memory\n"));
3340                 return NULL;
3341         }
3342
3343         /*
3344          * If we are escaping a literal that contains backslashes, we use the
3345          * escape string syntax so that the result is correct under either value
3346          * of standard_conforming_strings.  We also emit a leading space in this
3347          * case, to guard against the possibility that the result might be
3348          * interpolated immediately following an identifier.
3349          */
3350         if (!as_ident && num_backslashes > 0)
3351         {
3352                 *rp++ = ' ';
3353                 *rp++ = 'E';
3354         }
3355
3356         /* Opening quote. */
3357         *rp++ = quote_char;
3358
3359         /*
3360          * Use fast path if possible.
3361          *
3362          * We've already verified that the input string is well-formed in the
3363          * current encoding.  If it contains no quotes and, in the case of
3364          * literal-escaping, no backslashes, then we can just copy it directly to
3365          * the output buffer, adding the necessary quotes.
3366          *
3367          * If not, we must rescan the input and process each character
3368          * individually.
3369          */
3370         if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
3371         {
3372                 memcpy(rp, str, input_len);
3373                 rp += input_len;
3374         }
3375         else
3376         {
3377                 for (s = str; s - str < input_len; ++s)
3378                 {
3379                         if (*s == quote_char || (!as_ident && *s == '\\'))
3380                         {
3381                                 *rp++ = *s;
3382                                 *rp++ = *s;
3383                         }
3384                         else if (!IS_HIGHBIT_SET(*s))
3385                                 *rp++ = *s;
3386                         else
3387                         {
3388                                 int                     i = pg_encoding_mblen(conn->client_encoding, s);
3389
3390                                 while (1)
3391                                 {
3392                                         *rp++ = *s;
3393                                         if (--i == 0)
3394                                                 break;
3395                                         ++s;            /* for loop will provide the final increment */
3396                                 }
3397                         }
3398                 }
3399         }
3400
3401         /* Closing quote and terminating NUL. */
3402         *rp++ = quote_char;
3403         *rp = '\0';
3404
3405         return result;
3406 }
3407
3408 char *
3409 PQescapeLiteral(PGconn *conn, const char *str, size_t len)
3410 {
3411         return PQescapeInternal(conn, str, len, false);
3412 }
3413
3414 char *
3415 PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
3416 {
3417         return PQescapeInternal(conn, str, len, true);
3418 }
3419
3420 /* HEX encoding support for bytea */
3421 static const char hextbl[] = "0123456789abcdef";
3422
3423 static const int8 hexlookup[128] = {
3424         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3425         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3426         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3427         0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
3428         -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3429         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3430         -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3431         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3432 };
3433
3434 static inline char
3435 get_hex(char c)
3436 {
3437         int                     res = -1;
3438
3439         if (c > 0 && c < 127)
3440                 res = hexlookup[(unsigned char) c];
3441
3442         return (char) res;
3443 }
3444
3445
3446 /*
3447  *              PQescapeBytea   - converts from binary string to the
3448  *              minimal encoding necessary to include the string in an SQL
3449  *              INSERT statement with a bytea type column as the target.
3450  *
3451  *              We can use either hex or escape (traditional) encoding.
3452  *              In escape mode, the following transformations are applied:
3453  *              '\0' == ASCII  0 == \000
3454  *              '\'' == ASCII 39 == ''
3455  *              '\\' == ASCII 92 == \\
3456  *              anything < 0x20, or > 0x7e ---> \ooo
3457  *                                                                              (where ooo is an octal expression)
3458  *
3459  *              If not std_strings, all backslashes sent to the output are doubled.
3460  */
3461 static unsigned char *
3462 PQescapeByteaInternal(PGconn *conn,
3463                                           const unsigned char *from, size_t from_length,
3464                                           size_t *to_length, bool std_strings, bool use_hex)
3465 {
3466         const unsigned char *vp;
3467         unsigned char *rp;
3468         unsigned char *result;
3469         size_t          i;
3470         size_t          len;
3471         size_t          bslash_len = (std_strings ? 1 : 2);
3472
3473         /*
3474          * empty string has 1 char ('\0')
3475          */
3476         len = 1;
3477
3478         if (use_hex)
3479         {
3480                 len += bslash_len + 1 + 2 * from_length;
3481         }
3482         else
3483         {
3484                 vp = from;
3485                 for (i = from_length; i > 0; i--, vp++)
3486                 {
3487                         if (*vp < 0x20 || *vp > 0x7e)
3488                                 len += bslash_len + 3;
3489                         else if (*vp == '\'')
3490                                 len += 2;
3491                         else if (*vp == '\\')
3492                                 len += bslash_len + bslash_len;
3493                         else
3494                                 len++;
3495                 }
3496         }
3497
3498         *to_length = len;
3499         rp = result = (unsigned char *) malloc(len);
3500         if (rp == NULL)
3501         {
3502                 if (conn)
3503                         printfPQExpBuffer(&conn->errorMessage,
3504                                                           libpq_gettext("out of memory\n"));
3505                 return NULL;
3506         }
3507
3508         if (use_hex)
3509         {
3510                 if (!std_strings)
3511                         *rp++ = '\\';
3512                 *rp++ = '\\';
3513                 *rp++ = 'x';
3514         }
3515
3516         vp = from;
3517         for (i = from_length; i > 0; i--, vp++)
3518         {
3519                 unsigned char c = *vp;
3520
3521                 if (use_hex)
3522                 {
3523                         *rp++ = hextbl[(c >> 4) & 0xF];
3524                         *rp++ = hextbl[c & 0xF];
3525                 }
3526                 else if (c < 0x20 || c > 0x7e)
3527                 {
3528                         if (!std_strings)
3529                                 *rp++ = '\\';
3530                         *rp++ = '\\';
3531                         *rp++ = (c >> 6) + '0';
3532                         *rp++ = ((c >> 3) & 07) + '0';
3533                         *rp++ = (c & 07) + '0';
3534                 }
3535                 else if (c == '\'')
3536                 {
3537                         *rp++ = '\'';
3538                         *rp++ = '\'';
3539                 }
3540                 else if (c == '\\')
3541                 {
3542                         if (!std_strings)
3543                         {
3544                                 *rp++ = '\\';
3545                                 *rp++ = '\\';
3546                         }
3547                         *rp++ = '\\';
3548                         *rp++ = '\\';
3549                 }
3550                 else
3551                         *rp++ = c;
3552         }
3553         *rp = '\0';
3554
3555         return result;
3556 }
3557
3558 unsigned char *
3559 PQescapeByteaConn(PGconn *conn,
3560                                   const unsigned char *from, size_t from_length,
3561                                   size_t *to_length)
3562 {
3563         if (!conn)
3564                 return NULL;
3565         return PQescapeByteaInternal(conn, from, from_length, to_length,
3566                                                                  conn->std_strings,
3567                                                                  (conn->sversion >= 90000));
3568 }
3569
3570 unsigned char *
3571 PQescapeBytea(const unsigned char *from, size_t from_length, size_t *to_length)
3572 {
3573         return PQescapeByteaInternal(NULL, from, from_length, to_length,
3574                                                                  static_std_strings,
3575                                                                  false /* can't use hex */ );
3576 }
3577
3578
3579 #define ISFIRSTOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '3')
3580 #define ISOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '7')
3581 #define OCTVAL(CH) ((CH) - '0')
3582
3583 /*
3584  *              PQunescapeBytea - converts the null terminated string representation
3585  *              of a bytea, strtext, into binary, filling a buffer. It returns a
3586  *              pointer to the buffer (or NULL on error), and the size of the
3587  *              buffer in retbuflen. The pointer may subsequently be used as an
3588  *              argument to the function PQfreemem.
3589  *
3590  *              The following transformations are made:
3591  *              \\       == ASCII 92 == \
3592  *              \ooo == a byte whose value = ooo (ooo is an octal number)
3593  *              \x       == x (x is any character not matched by the above transformations)
3594  */
3595 unsigned char *
3596 PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
3597 {
3598         size_t          strtextlen,
3599                                 buflen;
3600         unsigned char *buffer,
3601                            *tmpbuf;
3602         size_t          i,
3603                                 j;
3604
3605         if (strtext == NULL)
3606                 return NULL;
3607
3608         strtextlen = strlen((const char *) strtext);
3609
3610         if (strtext[0] == '\\' && strtext[1] == 'x')
3611         {
3612                 const unsigned char *s;
3613                 unsigned char *p;
3614
3615                 buflen = (strtextlen - 2) / 2;
3616                 /* Avoid unportable malloc(0) */
3617                 buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
3618                 if (buffer == NULL)
3619                         return NULL;
3620
3621                 s = strtext + 2;
3622                 p = buffer;
3623                 while (*s)
3624                 {
3625                         char            v1,
3626                                                 v2;
3627
3628                         /*
3629                          * Bad input is silently ignored.  Note that this includes
3630                          * whitespace between hex pairs, which is allowed by byteain.
3631                          */
3632                         v1 = get_hex(*s++);
3633                         if (!*s || v1 == (char) -1)
3634                                 continue;
3635                         v2 = get_hex(*s++);
3636                         if (v2 != (char) -1)
3637                                 *p++ = (v1 << 4) | v2;
3638                 }
3639
3640                 buflen = p - buffer;
3641         }
3642         else
3643         {
3644                 /*
3645                  * Length of input is max length of output, but add one to avoid
3646                  * unportable malloc(0) if input is zero-length.
3647                  */
3648                 buffer = (unsigned char *) malloc(strtextlen + 1);
3649                 if (buffer == NULL)
3650                         return NULL;
3651
3652                 for (i = j = 0; i < strtextlen;)
3653                 {
3654                         switch (strtext[i])
3655                         {
3656                                 case '\\':
3657                                         i++;
3658                                         if (strtext[i] == '\\')
3659                                                 buffer[j++] = strtext[i++];
3660                                         else
3661                                         {
3662                                                 if ((ISFIRSTOCTDIGIT(strtext[i])) &&
3663                                                         (ISOCTDIGIT(strtext[i + 1])) &&
3664                                                         (ISOCTDIGIT(strtext[i + 2])))
3665                                                 {
3666                                                         int                     byte;
3667
3668                                                         byte = OCTVAL(strtext[i++]);
3669                                                         byte = (byte << 3) + OCTVAL(strtext[i++]);
3670                                                         byte = (byte << 3) + OCTVAL(strtext[i++]);
3671                                                         buffer[j++] = byte;
3672                                                 }
3673                                         }
3674
3675                                         /*
3676                                          * Note: if we see '\' followed by something that isn't a
3677                                          * recognized escape sequence, we loop around having done
3678                                          * nothing except advance i.  Therefore the something will
3679                                          * be emitted as ordinary data on the next cycle. Corner
3680                                          * case: '\' at end of string will just be discarded.
3681                                          */
3682                                         break;
3683
3684                                 default:
3685                                         buffer[j++] = strtext[i++];
3686                                         break;
3687                         }
3688                 }
3689                 buflen = j;                             /* buflen is the length of the dequoted data */
3690         }
3691
3692         /* Shrink the buffer to be no larger than necessary */
3693         /* +1 avoids unportable behavior when buflen==0 */
3694         tmpbuf = realloc(buffer, buflen + 1);
3695
3696         /* It would only be a very brain-dead realloc that could fail, but... */
3697         if (!tmpbuf)
3698         {
3699                 free(buffer);
3700                 return NULL;
3701         }
3702
3703         *retbuflen = buflen;
3704         return tmpbuf;
3705 }