]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-exec.c
Support Subject Alternative Names in SSL server certificates.
[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-2014, 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                                           sizeof(PGMessageField) + strlen(value),
896                                           TRUE);
897         if (!pfield)
898                 return;                                 /* out of memory? */
899         pfield->code = code;
900         strcpy(pfield->contents, value);
901         pfield->next = res->errFields;
902         res->errFields = pfield;
903 }
904
905 /*
906  * pqSaveParameterStatus - remember parameter status sent by backend
907  */
908 void
909 pqSaveParameterStatus(PGconn *conn, const char *name, const char *value)
910 {
911         pgParameterStatus *pstatus;
912         pgParameterStatus *prev;
913
914         if (conn->Pfdebug)
915                 fprintf(conn->Pfdebug, "pqSaveParameterStatus: '%s' = '%s'\n",
916                                 name, value);
917
918         /*
919          * Forget any old information about the parameter
920          */
921         for (pstatus = conn->pstatus, prev = NULL;
922                  pstatus != NULL;
923                  prev = pstatus, pstatus = pstatus->next)
924         {
925                 if (strcmp(pstatus->name, name) == 0)
926                 {
927                         if (prev)
928                                 prev->next = pstatus->next;
929                         else
930                                 conn->pstatus = pstatus->next;
931                         free(pstatus);          /* frees name and value strings too */
932                         break;
933                 }
934         }
935
936         /*
937          * Store new info as a single malloc block
938          */
939         pstatus = (pgParameterStatus *) malloc(sizeof(pgParameterStatus) +
940                                                                                    strlen(name) +strlen(value) + 2);
941         if (pstatus)
942         {
943                 char       *ptr;
944
945                 ptr = ((char *) pstatus) + sizeof(pgParameterStatus);
946                 pstatus->name = ptr;
947                 strcpy(ptr, name);
948                 ptr += strlen(name) + 1;
949                 pstatus->value = ptr;
950                 strcpy(ptr, value);
951                 pstatus->next = conn->pstatus;
952                 conn->pstatus = pstatus;
953         }
954
955         /*
956          * Special hacks: remember client_encoding and
957          * standard_conforming_strings, and convert server version to a numeric
958          * form.  We keep the first two of these in static variables as well, so
959          * that PQescapeString and PQescapeBytea can behave somewhat sanely (at
960          * least in single-connection-using programs).
961          */
962         if (strcmp(name, "client_encoding") == 0)
963         {
964                 conn->client_encoding = pg_char_to_encoding(value);
965                 /* if we don't recognize the encoding name, fall back to SQL_ASCII */
966                 if (conn->client_encoding < 0)
967                         conn->client_encoding = PG_SQL_ASCII;
968                 static_client_encoding = conn->client_encoding;
969         }
970         else if (strcmp(name, "standard_conforming_strings") == 0)
971         {
972                 conn->std_strings = (strcmp(value, "on") == 0);
973                 static_std_strings = conn->std_strings;
974         }
975         else if (strcmp(name, "server_version") == 0)
976         {
977                 int                     cnt;
978                 int                     vmaj,
979                                         vmin,
980                                         vrev;
981
982                 cnt = sscanf(value, "%d.%d.%d", &vmaj, &vmin, &vrev);
983
984                 if (cnt < 2)
985                         conn->sversion = 0; /* unknown */
986                 else
987                 {
988                         if (cnt == 2)
989                                 vrev = 0;
990                         conn->sversion = (100 * vmaj + vmin) * 100 + vrev;
991                 }
992         }
993 }
994
995
996 /*
997  * pqRowProcessor
998  *        Add the received row to the current async result (conn->result).
999  *        Returns 1 if OK, 0 if error occurred.
1000  *
1001  * On error, *errmsgp can be set to an error string to be returned.
1002  * If it is left NULL, the error is presumed to be "out of memory".
1003  *
1004  * In single-row mode, we create a new result holding just the current row,
1005  * stashing the previous result in conn->next_result so that it becomes
1006  * active again after pqPrepareAsyncResult().  This allows the result metadata
1007  * (column descriptions) to be carried forward to each result row.
1008  */
1009 int
1010 pqRowProcessor(PGconn *conn, const char **errmsgp)
1011 {
1012         PGresult   *res = conn->result;
1013         int                     nfields = res->numAttributes;
1014         const PGdataValue *columns = conn->rowBuf;
1015         PGresAttValue *tup;
1016         int                     i;
1017
1018         /*
1019          * In single-row mode, make a new PGresult that will hold just this one
1020          * row; the original conn->result is left unchanged so that it can be used
1021          * again as the template for future rows.
1022          */
1023         if (conn->singleRowMode)
1024         {
1025                 /* Copy everything that should be in the result at this point */
1026                 res = PQcopyResult(res,
1027                                                    PG_COPYRES_ATTRS | PG_COPYRES_EVENTS |
1028                                                    PG_COPYRES_NOTICEHOOKS);
1029                 if (!res)
1030                         return 0;
1031         }
1032
1033         /*
1034          * Basically we just allocate space in the PGresult for each field and
1035          * copy the data over.
1036          *
1037          * Note: on malloc failure, we return 0 leaving *errmsgp still NULL, which
1038          * caller will take to mean "out of memory".  This is preferable to trying
1039          * to set up such a message here, because evidently there's not enough
1040          * memory for gettext() to do anything.
1041          */
1042         tup = (PGresAttValue *)
1043                 pqResultAlloc(res, nfields * sizeof(PGresAttValue), TRUE);
1044         if (tup == NULL)
1045                 goto fail;
1046
1047         for (i = 0; i < nfields; i++)
1048         {
1049                 int                     clen = columns[i].len;
1050
1051                 if (clen < 0)
1052                 {
1053                         /* null field */
1054                         tup[i].len = NULL_LEN;
1055                         tup[i].value = res->null_field;
1056                 }
1057                 else
1058                 {
1059                         bool            isbinary = (res->attDescs[i].format != 0);
1060                         char       *val;
1061
1062                         val = (char *) pqResultAlloc(res, clen + 1, isbinary);
1063                         if (val == NULL)
1064                                 goto fail;
1065
1066                         /* copy and zero-terminate the data (even if it's binary) */
1067                         memcpy(val, columns[i].value, clen);
1068                         val[clen] = '\0';
1069
1070                         tup[i].len = clen;
1071                         tup[i].value = val;
1072                 }
1073         }
1074
1075         /* And add the tuple to the PGresult's tuple array */
1076         if (!pqAddTuple(res, tup))
1077                 goto fail;
1078
1079         /*
1080          * Success.  In single-row mode, make the result available to the client
1081          * immediately.
1082          */
1083         if (conn->singleRowMode)
1084         {
1085                 /* Change result status to special single-row value */
1086                 res->resultStatus = PGRES_SINGLE_TUPLE;
1087                 /* Stash old result for re-use later */
1088                 conn->next_result = conn->result;
1089                 conn->result = res;
1090                 /* And mark the result ready to return */
1091                 conn->asyncStatus = PGASYNC_READY;
1092         }
1093
1094         return 1;
1095
1096 fail:
1097         /* release locally allocated PGresult, if we made one */
1098         if (res != conn->result)
1099                 PQclear(res);
1100         return 0;
1101 }
1102
1103
1104 /*
1105  * PQsendQuery
1106  *       Submit a query, but don't wait for it to finish
1107  *
1108  * Returns: 1 if successfully submitted
1109  *                      0 if error (conn->errorMessage is set)
1110  */
1111 int
1112 PQsendQuery(PGconn *conn, const char *query)
1113 {
1114         if (!PQsendQueryStart(conn))
1115                 return 0;
1116
1117         /* check the argument */
1118         if (!query)
1119         {
1120                 printfPQExpBuffer(&conn->errorMessage,
1121                                                 libpq_gettext("command string is a null pointer\n"));
1122                 return 0;
1123         }
1124
1125         /* construct the outgoing Query message */
1126         if (pqPutMsgStart('Q', false, conn) < 0 ||
1127                 pqPuts(query, conn) < 0 ||
1128                 pqPutMsgEnd(conn) < 0)
1129         {
1130                 pqHandleSendFailure(conn);
1131                 return 0;
1132         }
1133
1134         /* remember we are using simple query protocol */
1135         conn->queryclass = PGQUERY_SIMPLE;
1136
1137         /* and remember the query text too, if possible */
1138         /* if insufficient memory, last_query just winds up NULL */
1139         if (conn->last_query)
1140                 free(conn->last_query);
1141         conn->last_query = strdup(query);
1142
1143         /*
1144          * Give the data a push.  In nonblock mode, don't complain if we're unable
1145          * to send it all; PQgetResult() will do any additional flushing needed.
1146          */
1147         if (pqFlush(conn) < 0)
1148         {
1149                 pqHandleSendFailure(conn);
1150                 return 0;
1151         }
1152
1153         /* OK, it's launched! */
1154         conn->asyncStatus = PGASYNC_BUSY;
1155         return 1;
1156 }
1157
1158 /*
1159  * PQsendQueryParams
1160  *              Like PQsendQuery, but use protocol 3.0 so we can pass parameters
1161  */
1162 int
1163 PQsendQueryParams(PGconn *conn,
1164                                   const char *command,
1165                                   int nParams,
1166                                   const Oid *paramTypes,
1167                                   const char *const * paramValues,
1168                                   const int *paramLengths,
1169                                   const int *paramFormats,
1170                                   int resultFormat)
1171 {
1172         if (!PQsendQueryStart(conn))
1173                 return 0;
1174
1175         /* check the arguments */
1176         if (!command)
1177         {
1178                 printfPQExpBuffer(&conn->errorMessage,
1179                                                 libpq_gettext("command string is a null pointer\n"));
1180                 return 0;
1181         }
1182         if (nParams < 0 || nParams > 65535)
1183         {
1184                 printfPQExpBuffer(&conn->errorMessage,
1185                 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1186                 return 0;
1187         }
1188
1189         return PQsendQueryGuts(conn,
1190                                                    command,
1191                                                    "",  /* use unnamed statement */
1192                                                    nParams,
1193                                                    paramTypes,
1194                                                    paramValues,
1195                                                    paramLengths,
1196                                                    paramFormats,
1197                                                    resultFormat);
1198 }
1199
1200 /*
1201  * PQsendPrepare
1202  *       Submit a Parse message, but don't wait for it to finish
1203  *
1204  * Returns: 1 if successfully submitted
1205  *                      0 if error (conn->errorMessage is set)
1206  */
1207 int
1208 PQsendPrepare(PGconn *conn,
1209                           const char *stmtName, const char *query,
1210                           int nParams, const Oid *paramTypes)
1211 {
1212         if (!PQsendQueryStart(conn))
1213                 return 0;
1214
1215         /* check the arguments */
1216         if (!stmtName)
1217         {
1218                 printfPQExpBuffer(&conn->errorMessage,
1219                                                 libpq_gettext("statement name is a null pointer\n"));
1220                 return 0;
1221         }
1222         if (!query)
1223         {
1224                 printfPQExpBuffer(&conn->errorMessage,
1225                                                 libpq_gettext("command string is a null pointer\n"));
1226                 return 0;
1227         }
1228         if (nParams < 0 || nParams > 65535)
1229         {
1230                 printfPQExpBuffer(&conn->errorMessage,
1231                 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1232                 return 0;
1233         }
1234
1235         /* This isn't gonna work on a 2.0 server */
1236         if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1237         {
1238                 printfPQExpBuffer(&conn->errorMessage,
1239                  libpq_gettext("function requires at least protocol version 3.0\n"));
1240                 return 0;
1241         }
1242
1243         /* construct the Parse message */
1244         if (pqPutMsgStart('P', false, conn) < 0 ||
1245                 pqPuts(stmtName, conn) < 0 ||
1246                 pqPuts(query, conn) < 0)
1247                 goto sendFailed;
1248
1249         if (nParams > 0 && paramTypes)
1250         {
1251                 int                     i;
1252
1253                 if (pqPutInt(nParams, 2, conn) < 0)
1254                         goto sendFailed;
1255                 for (i = 0; i < nParams; i++)
1256                 {
1257                         if (pqPutInt(paramTypes[i], 4, conn) < 0)
1258                                 goto sendFailed;
1259                 }
1260         }
1261         else
1262         {
1263                 if (pqPutInt(0, 2, conn) < 0)
1264                         goto sendFailed;
1265         }
1266         if (pqPutMsgEnd(conn) < 0)
1267                 goto sendFailed;
1268
1269         /* construct the Sync message */
1270         if (pqPutMsgStart('S', false, conn) < 0 ||
1271                 pqPutMsgEnd(conn) < 0)
1272                 goto sendFailed;
1273
1274         /* remember we are doing just a Parse */
1275         conn->queryclass = PGQUERY_PREPARE;
1276
1277         /* and remember the query text too, if possible */
1278         /* if insufficient memory, last_query just winds up NULL */
1279         if (conn->last_query)
1280                 free(conn->last_query);
1281         conn->last_query = strdup(query);
1282
1283         /*
1284          * Give the data a push.  In nonblock mode, don't complain if we're unable
1285          * to send it all; PQgetResult() will do any additional flushing needed.
1286          */
1287         if (pqFlush(conn) < 0)
1288                 goto sendFailed;
1289
1290         /* OK, it's launched! */
1291         conn->asyncStatus = PGASYNC_BUSY;
1292         return 1;
1293
1294 sendFailed:
1295         pqHandleSendFailure(conn);
1296         return 0;
1297 }
1298
1299 /*
1300  * PQsendQueryPrepared
1301  *              Like PQsendQuery, but execute a previously prepared statement,
1302  *              using protocol 3.0 so we can pass parameters
1303  */
1304 int
1305 PQsendQueryPrepared(PGconn *conn,
1306                                         const char *stmtName,
1307                                         int nParams,
1308                                         const char *const * paramValues,
1309                                         const int *paramLengths,
1310                                         const int *paramFormats,
1311                                         int resultFormat)
1312 {
1313         if (!PQsendQueryStart(conn))
1314                 return 0;
1315
1316         /* check the arguments */
1317         if (!stmtName)
1318         {
1319                 printfPQExpBuffer(&conn->errorMessage,
1320                                                 libpq_gettext("statement name is a null pointer\n"));
1321                 return 0;
1322         }
1323         if (nParams < 0 || nParams > 65535)
1324         {
1325                 printfPQExpBuffer(&conn->errorMessage,
1326                 libpq_gettext("number of parameters must be between 0 and 65535\n"));
1327                 return 0;
1328         }
1329
1330         return PQsendQueryGuts(conn,
1331                                                    NULL,        /* no command to parse */
1332                                                    stmtName,
1333                                                    nParams,
1334                                                    NULL,        /* no param types */
1335                                                    paramValues,
1336                                                    paramLengths,
1337                                                    paramFormats,
1338                                                    resultFormat);
1339 }
1340
1341 /*
1342  * Common startup code for PQsendQuery and sibling routines
1343  */
1344 static bool
1345 PQsendQueryStart(PGconn *conn)
1346 {
1347         if (!conn)
1348                 return false;
1349
1350         /* clear the error string */
1351         resetPQExpBuffer(&conn->errorMessage);
1352
1353         /* Don't try to send if we know there's no live connection. */
1354         if (conn->status != CONNECTION_OK)
1355         {
1356                 printfPQExpBuffer(&conn->errorMessage,
1357                                                   libpq_gettext("no connection to the server\n"));
1358                 return false;
1359         }
1360         /* Can't send while already busy, either. */
1361         if (conn->asyncStatus != PGASYNC_IDLE)
1362         {
1363                 printfPQExpBuffer(&conn->errorMessage,
1364                                   libpq_gettext("another command is already in progress\n"));
1365                 return false;
1366         }
1367
1368         /* initialize async result-accumulation state */
1369         conn->result = NULL;
1370         conn->next_result = NULL;
1371
1372         /* reset single-row processing mode */
1373         conn->singleRowMode = false;
1374
1375         /* ready to send command message */
1376         return true;
1377 }
1378
1379 /*
1380  * PQsendQueryGuts
1381  *              Common code for protocol-3.0 query sending
1382  *              PQsendQueryStart should be done already
1383  *
1384  * command may be NULL to indicate we use an already-prepared statement
1385  */
1386 static int
1387 PQsendQueryGuts(PGconn *conn,
1388                                 const char *command,
1389                                 const char *stmtName,
1390                                 int nParams,
1391                                 const Oid *paramTypes,
1392                                 const char *const * paramValues,
1393                                 const int *paramLengths,
1394                                 const int *paramFormats,
1395                                 int resultFormat)
1396 {
1397         int                     i;
1398
1399         /* This isn't gonna work on a 2.0 server */
1400         if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
1401         {
1402                 printfPQExpBuffer(&conn->errorMessage,
1403                  libpq_gettext("function requires at least protocol version 3.0\n"));
1404                 return 0;
1405         }
1406
1407         /*
1408          * We will send Parse (if needed), Bind, Describe Portal, Execute, Sync,
1409          * using specified statement name and the unnamed portal.
1410          */
1411
1412         if (command)
1413         {
1414                 /* construct the Parse message */
1415                 if (pqPutMsgStart('P', false, conn) < 0 ||
1416                         pqPuts(stmtName, conn) < 0 ||
1417                         pqPuts(command, conn) < 0)
1418                         goto sendFailed;
1419                 if (nParams > 0 && paramTypes)
1420                 {
1421                         if (pqPutInt(nParams, 2, conn) < 0)
1422                                 goto sendFailed;
1423                         for (i = 0; i < nParams; i++)
1424                         {
1425                                 if (pqPutInt(paramTypes[i], 4, conn) < 0)
1426                                         goto sendFailed;
1427                         }
1428                 }
1429                 else
1430                 {
1431                         if (pqPutInt(0, 2, conn) < 0)
1432                                 goto sendFailed;
1433                 }
1434                 if (pqPutMsgEnd(conn) < 0)
1435                         goto sendFailed;
1436         }
1437
1438         /* Construct the Bind message */
1439         if (pqPutMsgStart('B', false, conn) < 0 ||
1440                 pqPuts("", conn) < 0 ||
1441                 pqPuts(stmtName, conn) < 0)
1442                 goto sendFailed;
1443
1444         /* Send parameter formats */
1445         if (nParams > 0 && paramFormats)
1446         {
1447                 if (pqPutInt(nParams, 2, conn) < 0)
1448                         goto sendFailed;
1449                 for (i = 0; i < nParams; i++)
1450                 {
1451                         if (pqPutInt(paramFormats[i], 2, conn) < 0)
1452                                 goto sendFailed;
1453                 }
1454         }
1455         else
1456         {
1457                 if (pqPutInt(0, 2, conn) < 0)
1458                         goto sendFailed;
1459         }
1460
1461         if (pqPutInt(nParams, 2, conn) < 0)
1462                 goto sendFailed;
1463
1464         /* Send parameters */
1465         for (i = 0; i < nParams; i++)
1466         {
1467                 if (paramValues && paramValues[i])
1468                 {
1469                         int                     nbytes;
1470
1471                         if (paramFormats && paramFormats[i] != 0)
1472                         {
1473                                 /* binary parameter */
1474                                 if (paramLengths)
1475                                         nbytes = paramLengths[i];
1476                                 else
1477                                 {
1478                                         printfPQExpBuffer(&conn->errorMessage,
1479                                                                           libpq_gettext("length must be given for binary parameter\n"));
1480                                         goto sendFailed;
1481                                 }
1482                         }
1483                         else
1484                         {
1485                                 /* text parameter, do not use paramLengths */
1486                                 nbytes = strlen(paramValues[i]);
1487                         }
1488                         if (pqPutInt(nbytes, 4, conn) < 0 ||
1489                                 pqPutnchar(paramValues[i], nbytes, conn) < 0)
1490                                 goto sendFailed;
1491                 }
1492                 else
1493                 {
1494                         /* take the param as NULL */
1495                         if (pqPutInt(-1, 4, conn) < 0)
1496                                 goto sendFailed;
1497                 }
1498         }
1499         if (pqPutInt(1, 2, conn) < 0 ||
1500                 pqPutInt(resultFormat, 2, conn))
1501                 goto sendFailed;
1502         if (pqPutMsgEnd(conn) < 0)
1503                 goto sendFailed;
1504
1505         /* construct the Describe Portal message */
1506         if (pqPutMsgStart('D', false, conn) < 0 ||
1507                 pqPutc('P', conn) < 0 ||
1508                 pqPuts("", conn) < 0 ||
1509                 pqPutMsgEnd(conn) < 0)
1510                 goto sendFailed;
1511
1512         /* construct the Execute message */
1513         if (pqPutMsgStart('E', false, conn) < 0 ||
1514                 pqPuts("", conn) < 0 ||
1515                 pqPutInt(0, 4, conn) < 0 ||
1516                 pqPutMsgEnd(conn) < 0)
1517                 goto sendFailed;
1518
1519         /* construct the Sync message */
1520         if (pqPutMsgStart('S', false, conn) < 0 ||
1521                 pqPutMsgEnd(conn) < 0)
1522                 goto sendFailed;
1523
1524         /* remember we are using extended query protocol */
1525         conn->queryclass = PGQUERY_EXTENDED;
1526
1527         /* and remember the query text too, if possible */
1528         /* if insufficient memory, last_query just winds up NULL */
1529         if (conn->last_query)
1530                 free(conn->last_query);
1531         if (command)
1532                 conn->last_query = strdup(command);
1533         else
1534                 conn->last_query = NULL;
1535
1536         /*
1537          * Give the data a push.  In nonblock mode, don't complain if we're unable
1538          * to send it all; PQgetResult() will do any additional flushing needed.
1539          */
1540         if (pqFlush(conn) < 0)
1541                 goto sendFailed;
1542
1543         /* OK, it's launched! */
1544         conn->asyncStatus = PGASYNC_BUSY;
1545         return 1;
1546
1547 sendFailed:
1548         pqHandleSendFailure(conn);
1549         return 0;
1550 }
1551
1552 /*
1553  * pqHandleSendFailure: try to clean up after failure to send command.
1554  *
1555  * Primarily, what we want to accomplish here is to process an async
1556  * NOTICE message that the backend might have sent just before it died.
1557  *
1558  * NOTE: this routine should only be called in PGASYNC_IDLE state.
1559  */
1560 void
1561 pqHandleSendFailure(PGconn *conn)
1562 {
1563         /*
1564          * Accept any available input data, ignoring errors.  Note that if
1565          * pqReadData decides the backend has closed the channel, it will close
1566          * our side of the socket --- that's just what we want here.
1567          */
1568         while (pqReadData(conn) > 0)
1569                  /* loop until no more data readable */ ;
1570
1571         /*
1572          * Parse any available input messages.  Since we are in PGASYNC_IDLE
1573          * state, only NOTICE and NOTIFY messages will be eaten.
1574          */
1575         parseInput(conn);
1576 }
1577
1578 /*
1579  * Select row-by-row processing mode
1580  */
1581 int
1582 PQsetSingleRowMode(PGconn *conn)
1583 {
1584         /*
1585          * Only allow setting the flag when we have launched a query and not yet
1586          * received any results.
1587          */
1588         if (!conn)
1589                 return 0;
1590         if (conn->asyncStatus != PGASYNC_BUSY)
1591                 return 0;
1592         if (conn->queryclass != PGQUERY_SIMPLE &&
1593                 conn->queryclass != PGQUERY_EXTENDED)
1594                 return 0;
1595         if (conn->result)
1596                 return 0;
1597
1598         /* OK, set flag */
1599         conn->singleRowMode = true;
1600         return 1;
1601 }
1602
1603 /*
1604  * Consume any available input from the backend
1605  * 0 return: some kind of trouble
1606  * 1 return: no problem
1607  */
1608 int
1609 PQconsumeInput(PGconn *conn)
1610 {
1611         if (!conn)
1612                 return 0;
1613
1614         /*
1615          * for non-blocking connections try to flush the send-queue, otherwise we
1616          * may never get a response for something that may not have already been
1617          * sent because it's in our write buffer!
1618          */
1619         if (pqIsnonblocking(conn))
1620         {
1621                 if (pqFlush(conn) < 0)
1622                         return 0;
1623         }
1624
1625         /*
1626          * Load more data, if available. We do this no matter what state we are
1627          * in, since we are probably getting called because the application wants
1628          * to get rid of a read-select condition. Note that we will NOT block
1629          * waiting for more input.
1630          */
1631         if (pqReadData(conn) < 0)
1632                 return 0;
1633
1634         /* Parsing of the data waits till later. */
1635         return 1;
1636 }
1637
1638
1639 /*
1640  * parseInput: if appropriate, parse input data from backend
1641  * until input is exhausted or a stopping state is reached.
1642  * Note that this function will NOT attempt to read more data from the backend.
1643  */
1644 static void
1645 parseInput(PGconn *conn)
1646 {
1647         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1648                 pqParseInput3(conn);
1649         else
1650                 pqParseInput2(conn);
1651 }
1652
1653 /*
1654  * PQisBusy
1655  *       Return TRUE if PQgetResult would block waiting for input.
1656  */
1657
1658 int
1659 PQisBusy(PGconn *conn)
1660 {
1661         if (!conn)
1662                 return FALSE;
1663
1664         /* Parse any available data, if our state permits. */
1665         parseInput(conn);
1666
1667         /* PQgetResult will return immediately in all states except BUSY. */
1668         return conn->asyncStatus == PGASYNC_BUSY;
1669 }
1670
1671
1672 /*
1673  * PQgetResult
1674  *        Get the next PGresult produced by a query.  Returns NULL if no
1675  *        query work remains or an error has occurred (e.g. out of
1676  *        memory).
1677  */
1678
1679 PGresult *
1680 PQgetResult(PGconn *conn)
1681 {
1682         PGresult   *res;
1683
1684         if (!conn)
1685                 return NULL;
1686
1687         /* Parse any available data, if our state permits. */
1688         parseInput(conn);
1689
1690         /* If not ready to return something, block until we are. */
1691         while (conn->asyncStatus == PGASYNC_BUSY)
1692         {
1693                 int                     flushResult;
1694
1695                 /*
1696                  * If data remains unsent, send it.  Else we might be waiting for the
1697                  * result of a command the backend hasn't even got yet.
1698                  */
1699                 while ((flushResult = pqFlush(conn)) > 0)
1700                 {
1701                         if (pqWait(FALSE, TRUE, conn))
1702                         {
1703                                 flushResult = -1;
1704                                 break;
1705                         }
1706                 }
1707
1708                 /* Wait for some more data, and load it. */
1709                 if (flushResult ||
1710                         pqWait(TRUE, FALSE, conn) ||
1711                         pqReadData(conn) < 0)
1712                 {
1713                         /*
1714                          * conn->errorMessage has been set by pqWait or pqReadData. We
1715                          * want to append it to any already-received error message.
1716                          */
1717                         pqSaveErrorResult(conn);
1718                         conn->asyncStatus = PGASYNC_IDLE;
1719                         return pqPrepareAsyncResult(conn);
1720                 }
1721
1722                 /* Parse it. */
1723                 parseInput(conn);
1724         }
1725
1726         /* Return the appropriate thing. */
1727         switch (conn->asyncStatus)
1728         {
1729                 case PGASYNC_IDLE:
1730                         res = NULL;                     /* query is complete */
1731                         break;
1732                 case PGASYNC_READY:
1733                         res = pqPrepareAsyncResult(conn);
1734                         /* Set the state back to BUSY, allowing parsing to proceed. */
1735                         conn->asyncStatus = PGASYNC_BUSY;
1736                         break;
1737                 case PGASYNC_COPY_IN:
1738                         res = getCopyResult(conn, PGRES_COPY_IN);
1739                         break;
1740                 case PGASYNC_COPY_OUT:
1741                         res = getCopyResult(conn, PGRES_COPY_OUT);
1742                         break;
1743                 case PGASYNC_COPY_BOTH:
1744                         res = getCopyResult(conn, PGRES_COPY_BOTH);
1745                         break;
1746                 default:
1747                         printfPQExpBuffer(&conn->errorMessage,
1748                                                           libpq_gettext("unexpected asyncStatus: %d\n"),
1749                                                           (int) conn->asyncStatus);
1750                         res = PQmakeEmptyPGresult(conn, PGRES_FATAL_ERROR);
1751                         break;
1752         }
1753
1754         if (res)
1755         {
1756                 int                     i;
1757
1758                 for (i = 0; i < res->nEvents; i++)
1759                 {
1760                         PGEventResultCreate evt;
1761
1762                         evt.conn = conn;
1763                         evt.result = res;
1764                         if (!res->events[i].proc(PGEVT_RESULTCREATE, &evt,
1765                                                                          res->events[i].passThrough))
1766                         {
1767                                 printfPQExpBuffer(&conn->errorMessage,
1768                                                                   libpq_gettext("PGEventProc \"%s\" failed during PGEVT_RESULTCREATE event\n"),
1769                                                                   res->events[i].name);
1770                                 pqSetResultError(res, conn->errorMessage.data);
1771                                 res->resultStatus = PGRES_FATAL_ERROR;
1772                                 break;
1773                         }
1774                         res->events[i].resultInitialized = TRUE;
1775                 }
1776         }
1777
1778         return res;
1779 }
1780
1781 /*
1782  * getCopyResult
1783  *        Helper for PQgetResult: generate result for COPY-in-progress cases
1784  */
1785 static PGresult *
1786 getCopyResult(PGconn *conn, ExecStatusType copytype)
1787 {
1788         /*
1789          * If the server connection has been lost, don't pretend everything is
1790          * hunky-dory; instead return a PGRES_FATAL_ERROR result, and reset the
1791          * asyncStatus to idle (corresponding to what we'd do if we'd detected I/O
1792          * error in the earlier steps in PQgetResult).  The text returned in the
1793          * result is whatever is in conn->errorMessage; we hope that was filled
1794          * with something relevant when the lost connection was detected.
1795          */
1796         if (conn->status != CONNECTION_OK)
1797         {
1798                 pqSaveErrorResult(conn);
1799                 conn->asyncStatus = PGASYNC_IDLE;
1800                 return pqPrepareAsyncResult(conn);
1801         }
1802
1803         /* If we have an async result for the COPY, return that */
1804         if (conn->result && conn->result->resultStatus == copytype)
1805                 return pqPrepareAsyncResult(conn);
1806
1807         /* Otherwise, invent a suitable PGresult */
1808         return PQmakeEmptyPGresult(conn, copytype);
1809 }
1810
1811
1812 /*
1813  * PQexec
1814  *        send a query to the backend and package up the result in a PGresult
1815  *
1816  * If the query was not even sent, return NULL; conn->errorMessage is set to
1817  * a relevant message.
1818  * If the query was sent, a new PGresult is returned (which could indicate
1819  * either success or failure).
1820  * The user is responsible for freeing the PGresult via PQclear()
1821  * when done with it.
1822  */
1823 PGresult *
1824 PQexec(PGconn *conn, const char *query)
1825 {
1826         if (!PQexecStart(conn))
1827                 return NULL;
1828         if (!PQsendQuery(conn, query))
1829                 return NULL;
1830         return PQexecFinish(conn);
1831 }
1832
1833 /*
1834  * PQexecParams
1835  *              Like PQexec, but use protocol 3.0 so we can pass parameters
1836  */
1837 PGresult *
1838 PQexecParams(PGconn *conn,
1839                          const char *command,
1840                          int nParams,
1841                          const Oid *paramTypes,
1842                          const char *const * paramValues,
1843                          const int *paramLengths,
1844                          const int *paramFormats,
1845                          int resultFormat)
1846 {
1847         if (!PQexecStart(conn))
1848                 return NULL;
1849         if (!PQsendQueryParams(conn, command,
1850                                                    nParams, paramTypes, paramValues, paramLengths,
1851                                                    paramFormats, resultFormat))
1852                 return NULL;
1853         return PQexecFinish(conn);
1854 }
1855
1856 /*
1857  * PQprepare
1858  *        Creates a prepared statement by issuing a v3.0 parse message.
1859  *
1860  * If the query was not even sent, return NULL; conn->errorMessage is set to
1861  * a relevant message.
1862  * If the query was sent, a new PGresult is returned (which could indicate
1863  * either success or failure).
1864  * The user is responsible for freeing the PGresult via PQclear()
1865  * when done with it.
1866  */
1867 PGresult *
1868 PQprepare(PGconn *conn,
1869                   const char *stmtName, const char *query,
1870                   int nParams, const Oid *paramTypes)
1871 {
1872         if (!PQexecStart(conn))
1873                 return NULL;
1874         if (!PQsendPrepare(conn, stmtName, query, nParams, paramTypes))
1875                 return NULL;
1876         return PQexecFinish(conn);
1877 }
1878
1879 /*
1880  * PQexecPrepared
1881  *              Like PQexec, but execute a previously prepared statement,
1882  *              using protocol 3.0 so we can pass parameters
1883  */
1884 PGresult *
1885 PQexecPrepared(PGconn *conn,
1886                            const char *stmtName,
1887                            int nParams,
1888                            const char *const * paramValues,
1889                            const int *paramLengths,
1890                            const int *paramFormats,
1891                            int resultFormat)
1892 {
1893         if (!PQexecStart(conn))
1894                 return NULL;
1895         if (!PQsendQueryPrepared(conn, stmtName,
1896                                                          nParams, paramValues, paramLengths,
1897                                                          paramFormats, resultFormat))
1898                 return NULL;
1899         return PQexecFinish(conn);
1900 }
1901
1902 /*
1903  * Common code for PQexec and sibling routines: prepare to send command
1904  */
1905 static bool
1906 PQexecStart(PGconn *conn)
1907 {
1908         PGresult   *result;
1909
1910         if (!conn)
1911                 return false;
1912
1913         /*
1914          * Silently discard any prior query result that application didn't eat.
1915          * This is probably poor design, but it's here for backward compatibility.
1916          */
1917         while ((result = PQgetResult(conn)) != NULL)
1918         {
1919                 ExecStatusType resultStatus = result->resultStatus;
1920
1921                 PQclear(result);                /* only need its status */
1922                 if (resultStatus == PGRES_COPY_IN)
1923                 {
1924                         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1925                         {
1926                                 /* In protocol 3, we can get out of a COPY IN state */
1927                                 if (PQputCopyEnd(conn,
1928                                                  libpq_gettext("COPY terminated by new PQexec")) < 0)
1929                                         return false;
1930                                 /* keep waiting to swallow the copy's failure message */
1931                         }
1932                         else
1933                         {
1934                                 /* In older protocols we have to punt */
1935                                 printfPQExpBuffer(&conn->errorMessage,
1936                                   libpq_gettext("COPY IN state must be terminated first\n"));
1937                                 return false;
1938                         }
1939                 }
1940                 else if (resultStatus == PGRES_COPY_OUT)
1941                 {
1942                         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1943                         {
1944                                 /*
1945                                  * In protocol 3, we can get out of a COPY OUT state: we just
1946                                  * switch back to BUSY and allow the remaining COPY data to be
1947                                  * dropped on the floor.
1948                                  */
1949                                 conn->asyncStatus = PGASYNC_BUSY;
1950                                 /* keep waiting to swallow the copy's completion message */
1951                         }
1952                         else
1953                         {
1954                                 /* In older protocols we have to punt */
1955                                 printfPQExpBuffer(&conn->errorMessage,
1956                                  libpq_gettext("COPY OUT state must be terminated first\n"));
1957                                 return false;
1958                         }
1959                 }
1960                 else if (resultStatus == PGRES_COPY_BOTH)
1961                 {
1962                         /* We don't allow PQexec during COPY BOTH */
1963                         printfPQExpBuffer(&conn->errorMessage,
1964                                          libpq_gettext("PQexec not allowed during COPY BOTH\n"));
1965                         return false;
1966                 }
1967                 /* check for loss of connection, too */
1968                 if (conn->status == CONNECTION_BAD)
1969                         return false;
1970         }
1971
1972         /* OK to send a command */
1973         return true;
1974 }
1975
1976 /*
1977  * Common code for PQexec and sibling routines: wait for command result
1978  */
1979 static PGresult *
1980 PQexecFinish(PGconn *conn)
1981 {
1982         PGresult   *result;
1983         PGresult   *lastResult;
1984
1985         /*
1986          * For backwards compatibility, return the last result if there are more
1987          * than one --- but merge error messages if we get more than one error
1988          * result.
1989          *
1990          * We have to stop if we see copy in/out/both, however. We will resume
1991          * parsing after application performs the data transfer.
1992          *
1993          * Also stop if the connection is lost (else we'll loop infinitely).
1994          */
1995         lastResult = NULL;
1996         while ((result = PQgetResult(conn)) != NULL)
1997         {
1998                 if (lastResult)
1999                 {
2000                         if (lastResult->resultStatus == PGRES_FATAL_ERROR &&
2001                                 result->resultStatus == PGRES_FATAL_ERROR)
2002                         {
2003                                 pqCatenateResultError(lastResult, result->errMsg);
2004                                 PQclear(result);
2005                                 result = lastResult;
2006
2007                                 /*
2008                                  * Make sure PQerrorMessage agrees with concatenated result
2009                                  */
2010                                 resetPQExpBuffer(&conn->errorMessage);
2011                                 appendPQExpBufferStr(&conn->errorMessage, result->errMsg);
2012                         }
2013                         else
2014                                 PQclear(lastResult);
2015                 }
2016                 lastResult = result;
2017                 if (result->resultStatus == PGRES_COPY_IN ||
2018                         result->resultStatus == PGRES_COPY_OUT ||
2019                         result->resultStatus == PGRES_COPY_BOTH ||
2020                         conn->status == CONNECTION_BAD)
2021                         break;
2022         }
2023
2024         return lastResult;
2025 }
2026
2027 /*
2028  * PQdescribePrepared
2029  *        Obtain information about a previously prepared statement
2030  *
2031  * If the query was not even sent, return NULL; conn->errorMessage is set to
2032  * a relevant message.
2033  * If the query was sent, a new PGresult is returned (which could indicate
2034  * either success or failure).  On success, the PGresult contains status
2035  * PGRES_COMMAND_OK, and its parameter and column-heading fields describe
2036  * the statement's inputs and outputs respectively.
2037  * The user is responsible for freeing the PGresult via PQclear()
2038  * when done with it.
2039  */
2040 PGresult *
2041 PQdescribePrepared(PGconn *conn, const char *stmt)
2042 {
2043         if (!PQexecStart(conn))
2044                 return NULL;
2045         if (!PQsendDescribe(conn, 'S', stmt))
2046                 return NULL;
2047         return PQexecFinish(conn);
2048 }
2049
2050 /*
2051  * PQdescribePortal
2052  *        Obtain information about a previously created portal
2053  *
2054  * This is much like PQdescribePrepared, except that no parameter info is
2055  * returned.  Note that at the moment, libpq doesn't really expose portals
2056  * to the client; but this can be used with a portal created by a SQL
2057  * DECLARE CURSOR command.
2058  */
2059 PGresult *
2060 PQdescribePortal(PGconn *conn, const char *portal)
2061 {
2062         if (!PQexecStart(conn))
2063                 return NULL;
2064         if (!PQsendDescribe(conn, 'P', portal))
2065                 return NULL;
2066         return PQexecFinish(conn);
2067 }
2068
2069 /*
2070  * PQsendDescribePrepared
2071  *       Submit a Describe Statement command, but don't wait for it to finish
2072  *
2073  * Returns: 1 if successfully submitted
2074  *                      0 if error (conn->errorMessage is set)
2075  */
2076 int
2077 PQsendDescribePrepared(PGconn *conn, const char *stmt)
2078 {
2079         return PQsendDescribe(conn, 'S', stmt);
2080 }
2081
2082 /*
2083  * PQsendDescribePortal
2084  *       Submit a Describe Portal command, but don't wait for it to finish
2085  *
2086  * Returns: 1 if successfully submitted
2087  *                      0 if error (conn->errorMessage is set)
2088  */
2089 int
2090 PQsendDescribePortal(PGconn *conn, const char *portal)
2091 {
2092         return PQsendDescribe(conn, 'P', portal);
2093 }
2094
2095 /*
2096  * PQsendDescribe
2097  *       Common code to send a Describe command
2098  *
2099  * Available options for desc_type are
2100  *       'S' to describe a prepared statement; or
2101  *       'P' to describe a portal.
2102  * Returns 1 on success and 0 on failure.
2103  */
2104 static int
2105 PQsendDescribe(PGconn *conn, char desc_type, const char *desc_target)
2106 {
2107         /* Treat null desc_target as empty string */
2108         if (!desc_target)
2109                 desc_target = "";
2110
2111         if (!PQsendQueryStart(conn))
2112                 return 0;
2113
2114         /* This isn't gonna work on a 2.0 server */
2115         if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2116         {
2117                 printfPQExpBuffer(&conn->errorMessage,
2118                  libpq_gettext("function requires at least protocol version 3.0\n"));
2119                 return 0;
2120         }
2121
2122         /* construct the Describe message */
2123         if (pqPutMsgStart('D', false, conn) < 0 ||
2124                 pqPutc(desc_type, conn) < 0 ||
2125                 pqPuts(desc_target, conn) < 0 ||
2126                 pqPutMsgEnd(conn) < 0)
2127                 goto sendFailed;
2128
2129         /* construct the Sync message */
2130         if (pqPutMsgStart('S', false, conn) < 0 ||
2131                 pqPutMsgEnd(conn) < 0)
2132                 goto sendFailed;
2133
2134         /* remember we are doing a Describe */
2135         conn->queryclass = PGQUERY_DESCRIBE;
2136
2137         /* reset last-query string (not relevant now) */
2138         if (conn->last_query)
2139         {
2140                 free(conn->last_query);
2141                 conn->last_query = NULL;
2142         }
2143
2144         /*
2145          * Give the data a push.  In nonblock mode, don't complain if we're unable
2146          * to send it all; PQgetResult() will do any additional flushing needed.
2147          */
2148         if (pqFlush(conn) < 0)
2149                 goto sendFailed;
2150
2151         /* OK, it's launched! */
2152         conn->asyncStatus = PGASYNC_BUSY;
2153         return 1;
2154
2155 sendFailed:
2156         pqHandleSendFailure(conn);
2157         return 0;
2158 }
2159
2160 /*
2161  * PQnotifies
2162  *        returns a PGnotify* structure of the latest async notification
2163  * that has not yet been handled
2164  *
2165  * returns NULL, if there is currently
2166  * no unhandled async notification from the backend
2167  *
2168  * the CALLER is responsible for FREE'ing the structure returned
2169  */
2170 PGnotify *
2171 PQnotifies(PGconn *conn)
2172 {
2173         PGnotify   *event;
2174
2175         if (!conn)
2176                 return NULL;
2177
2178         /* Parse any available data to see if we can extract NOTIFY messages. */
2179         parseInput(conn);
2180
2181         event = conn->notifyHead;
2182         if (event)
2183         {
2184                 conn->notifyHead = event->next;
2185                 if (!conn->notifyHead)
2186                         conn->notifyTail = NULL;
2187                 event->next = NULL;             /* don't let app see the internal state */
2188         }
2189         return event;
2190 }
2191
2192 /*
2193  * PQputCopyData - send some data to the backend during COPY IN or COPY BOTH
2194  *
2195  * Returns 1 if successful, 0 if data could not be sent (only possible
2196  * in nonblock mode), or -1 if an error occurs.
2197  */
2198 int
2199 PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
2200 {
2201         if (!conn)
2202                 return -1;
2203         if (conn->asyncStatus != PGASYNC_COPY_IN &&
2204                 conn->asyncStatus != PGASYNC_COPY_BOTH)
2205         {
2206                 printfPQExpBuffer(&conn->errorMessage,
2207                                                   libpq_gettext("no COPY in progress\n"));
2208                 return -1;
2209         }
2210
2211         /*
2212          * Process any NOTICE or NOTIFY messages that might be pending in the
2213          * input buffer.  Since the server might generate many notices during the
2214          * COPY, we want to clean those out reasonably promptly to prevent
2215          * indefinite expansion of the input buffer.  (Note: the actual read of
2216          * input data into the input buffer happens down inside pqSendSome, but
2217          * it's not authorized to get rid of the data again.)
2218          */
2219         parseInput(conn);
2220
2221         if (nbytes > 0)
2222         {
2223                 /*
2224                  * Try to flush any previously sent data in preference to growing the
2225                  * output buffer.  If we can't enlarge the buffer enough to hold the
2226                  * data, return 0 in the nonblock case, else hard error. (For
2227                  * simplicity, always assume 5 bytes of overhead even in protocol 2.0
2228                  * case.)
2229                  */
2230                 if ((conn->outBufSize - conn->outCount - 5) < nbytes)
2231                 {
2232                         if (pqFlush(conn) < 0)
2233                                 return -1;
2234                         if (pqCheckOutBufferSpace(conn->outCount + 5 + (size_t) nbytes,
2235                                                                           conn))
2236                                 return pqIsnonblocking(conn) ? 0 : -1;
2237                 }
2238                 /* Send the data (too simple to delegate to fe-protocol files) */
2239                 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2240                 {
2241                         if (pqPutMsgStart('d', false, conn) < 0 ||
2242                                 pqPutnchar(buffer, nbytes, conn) < 0 ||
2243                                 pqPutMsgEnd(conn) < 0)
2244                                 return -1;
2245                 }
2246                 else
2247                 {
2248                         if (pqPutMsgStart(0, false, conn) < 0 ||
2249                                 pqPutnchar(buffer, nbytes, conn) < 0 ||
2250                                 pqPutMsgEnd(conn) < 0)
2251                                 return -1;
2252                 }
2253         }
2254         return 1;
2255 }
2256
2257 /*
2258  * PQputCopyEnd - send EOF indication to the backend during COPY IN
2259  *
2260  * After calling this, use PQgetResult() to check command completion status.
2261  *
2262  * Returns 1 if successful, 0 if data could not be sent (only possible
2263  * in nonblock mode), or -1 if an error occurs.
2264  */
2265 int
2266 PQputCopyEnd(PGconn *conn, const char *errormsg)
2267 {
2268         if (!conn)
2269                 return -1;
2270         if (conn->asyncStatus != PGASYNC_COPY_IN &&
2271                 conn->asyncStatus != PGASYNC_COPY_BOTH)
2272         {
2273                 printfPQExpBuffer(&conn->errorMessage,
2274                                                   libpq_gettext("no COPY in progress\n"));
2275                 return -1;
2276         }
2277
2278         /*
2279          * Send the COPY END indicator.  This is simple enough that we don't
2280          * bother delegating it to the fe-protocol files.
2281          */
2282         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2283         {
2284                 if (errormsg)
2285                 {
2286                         /* Send COPY FAIL */
2287                         if (pqPutMsgStart('f', false, conn) < 0 ||
2288                                 pqPuts(errormsg, conn) < 0 ||
2289                                 pqPutMsgEnd(conn) < 0)
2290                                 return -1;
2291                 }
2292                 else
2293                 {
2294                         /* Send COPY DONE */
2295                         if (pqPutMsgStart('c', false, conn) < 0 ||
2296                                 pqPutMsgEnd(conn) < 0)
2297                                 return -1;
2298                 }
2299
2300                 /*
2301                  * If we sent the COPY command in extended-query mode, we must issue a
2302                  * Sync as well.
2303                  */
2304                 if (conn->queryclass != PGQUERY_SIMPLE)
2305                 {
2306                         if (pqPutMsgStart('S', false, conn) < 0 ||
2307                                 pqPutMsgEnd(conn) < 0)
2308                                 return -1;
2309                 }
2310         }
2311         else
2312         {
2313                 if (errormsg)
2314                 {
2315                         /* Ooops, no way to do this in 2.0 */
2316                         printfPQExpBuffer(&conn->errorMessage,
2317                                                           libpq_gettext("function requires at least protocol version 3.0\n"));
2318                         return -1;
2319                 }
2320                 else
2321                 {
2322                         /* Send old-style end-of-data marker */
2323                         if (pqPutMsgStart(0, false, conn) < 0 ||
2324                                 pqPutnchar("\\.\n", 3, conn) < 0 ||
2325                                 pqPutMsgEnd(conn) < 0)
2326                                 return -1;
2327                 }
2328         }
2329
2330         /* Return to active duty */
2331         if (conn->asyncStatus == PGASYNC_COPY_BOTH)
2332                 conn->asyncStatus = PGASYNC_COPY_OUT;
2333         else
2334                 conn->asyncStatus = PGASYNC_BUSY;
2335         resetPQExpBuffer(&conn->errorMessage);
2336
2337         /* Try to flush data */
2338         if (pqFlush(conn) < 0)
2339                 return -1;
2340
2341         return 1;
2342 }
2343
2344 /*
2345  * PQgetCopyData - read a row of data from the backend during COPY OUT
2346  * or COPY BOTH
2347  *
2348  * If successful, sets *buffer to point to a malloc'd row of data, and
2349  * returns row length (always > 0) as result.
2350  * Returns 0 if no row available yet (only possible if async is true),
2351  * -1 if end of copy (consult PQgetResult), or -2 if error (consult
2352  * PQerrorMessage).
2353  */
2354 int
2355 PQgetCopyData(PGconn *conn, char **buffer, int async)
2356 {
2357         *buffer = NULL;                         /* for all failure cases */
2358         if (!conn)
2359                 return -2;
2360         if (conn->asyncStatus != PGASYNC_COPY_OUT &&
2361                 conn->asyncStatus != PGASYNC_COPY_BOTH)
2362         {
2363                 printfPQExpBuffer(&conn->errorMessage,
2364                                                   libpq_gettext("no COPY in progress\n"));
2365                 return -2;
2366         }
2367         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2368                 return pqGetCopyData3(conn, buffer, async);
2369         else
2370                 return pqGetCopyData2(conn, buffer, async);
2371 }
2372
2373 /*
2374  * PQgetline - gets a newline-terminated string from the backend.
2375  *
2376  * Chiefly here so that applications can use "COPY <rel> to stdout"
2377  * and read the output string.  Returns a null-terminated string in s.
2378  *
2379  * XXX this routine is now deprecated, because it can't handle binary data.
2380  * If called during a COPY BINARY we return EOF.
2381  *
2382  * PQgetline reads up to maxlen-1 characters (like fgets(3)) but strips
2383  * the terminating \n (like gets(3)).
2384  *
2385  * CAUTION: the caller is responsible for detecting the end-of-copy signal
2386  * (a line containing just "\.") when using this routine.
2387  *
2388  * RETURNS:
2389  *              EOF if error (eg, invalid arguments are given)
2390  *              0 if EOL is reached (i.e., \n has been read)
2391  *                              (this is required for backward-compatibility -- this
2392  *                               routine used to always return EOF or 0, assuming that
2393  *                               the line ended within maxlen bytes.)
2394  *              1 in other cases (i.e., the buffer was filled before \n is reached)
2395  */
2396 int
2397 PQgetline(PGconn *conn, char *s, int maxlen)
2398 {
2399         if (!s || maxlen <= 0)
2400                 return EOF;
2401         *s = '\0';
2402         /* maxlen must be at least 3 to hold the \. terminator! */
2403         if (maxlen < 3)
2404                 return EOF;
2405
2406         if (!conn)
2407                 return EOF;
2408
2409         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2410                 return pqGetline3(conn, s, maxlen);
2411         else
2412                 return pqGetline2(conn, s, maxlen);
2413 }
2414
2415 /*
2416  * PQgetlineAsync - gets a COPY data row without blocking.
2417  *
2418  * This routine is for applications that want to do "COPY <rel> to stdout"
2419  * asynchronously, that is without blocking.  Having issued the COPY command
2420  * and gotten a PGRES_COPY_OUT response, the app should call PQconsumeInput
2421  * and this routine until the end-of-data signal is detected.  Unlike
2422  * PQgetline, this routine takes responsibility for detecting end-of-data.
2423  *
2424  * On each call, PQgetlineAsync will return data if a complete data row
2425  * is available in libpq's input buffer.  Otherwise, no data is returned
2426  * until the rest of the row arrives.
2427  *
2428  * If -1 is returned, the end-of-data signal has been recognized (and removed
2429  * from libpq's input buffer).  The caller *must* next call PQendcopy and
2430  * then return to normal processing.
2431  *
2432  * RETURNS:
2433  *       -1    if the end-of-copy-data marker has been recognized
2434  *       0         if no data is available
2435  *       >0    the number of bytes returned.
2436  *
2437  * The data returned will not extend beyond a data-row boundary.  If possible
2438  * a whole row will be returned at one time.  But if the buffer offered by
2439  * the caller is too small to hold a row sent by the backend, then a partial
2440  * data row will be returned.  In text mode this can be detected by testing
2441  * whether the last returned byte is '\n' or not.
2442  *
2443  * The returned data is *not* null-terminated.
2444  */
2445
2446 int
2447 PQgetlineAsync(PGconn *conn, char *buffer, int bufsize)
2448 {
2449         if (!conn)
2450                 return -1;
2451
2452         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2453                 return pqGetlineAsync3(conn, buffer, bufsize);
2454         else
2455                 return pqGetlineAsync2(conn, buffer, bufsize);
2456 }
2457
2458 /*
2459  * PQputline -- sends a string to the backend during COPY IN.
2460  * Returns 0 if OK, EOF if not.
2461  *
2462  * This is deprecated primarily because the return convention doesn't allow
2463  * caller to tell the difference between a hard error and a nonblock-mode
2464  * send failure.
2465  */
2466 int
2467 PQputline(PGconn *conn, const char *s)
2468 {
2469         return PQputnbytes(conn, s, strlen(s));
2470 }
2471
2472 /*
2473  * PQputnbytes -- like PQputline, but buffer need not be null-terminated.
2474  * Returns 0 if OK, EOF if not.
2475  */
2476 int
2477 PQputnbytes(PGconn *conn, const char *buffer, int nbytes)
2478 {
2479         if (PQputCopyData(conn, buffer, nbytes) > 0)
2480                 return 0;
2481         else
2482                 return EOF;
2483 }
2484
2485 /*
2486  * PQendcopy
2487  *              After completing the data transfer portion of a copy in/out,
2488  *              the application must call this routine to finish the command protocol.
2489  *
2490  * When using protocol 3.0 this is deprecated; it's cleaner to use PQgetResult
2491  * to get the transfer status.  Note however that when using 2.0 protocol,
2492  * recovering from a copy failure often requires a PQreset.  PQendcopy will
2493  * take care of that, PQgetResult won't.
2494  *
2495  * RETURNS:
2496  *              0 on success
2497  *              1 on failure
2498  */
2499 int
2500 PQendcopy(PGconn *conn)
2501 {
2502         if (!conn)
2503                 return 0;
2504
2505         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2506                 return pqEndcopy3(conn);
2507         else
2508                 return pqEndcopy2(conn);
2509 }
2510
2511
2512 /* ----------------
2513  *              PQfn -  Send a function call to the POSTGRES backend.
2514  *
2515  *              conn                    : backend connection
2516  *              fnid                    : function id
2517  *              result_buf              : pointer to result buffer (&int if integer)
2518  *              result_len              : length of return value.
2519  *              actual_result_len: actual length returned. (differs from result_len
2520  *                                                for varlena structures.)
2521  *              result_type             : If the result is an integer, this must be 1,
2522  *                                                otherwise this should be 0
2523  *              args                    : pointer to an array of function arguments.
2524  *                                                (each has length, if integer, and value/pointer)
2525  *              nargs                   : # of arguments in args array.
2526  *
2527  * RETURNS
2528  *              PGresult with status = PGRES_COMMAND_OK if successful.
2529  *                      *actual_result_len is > 0 if there is a return value, 0 if not.
2530  *              PGresult with status = PGRES_FATAL_ERROR if backend returns an error.
2531  *              NULL on communications failure.  conn->errorMessage will be set.
2532  * ----------------
2533  */
2534
2535 PGresult *
2536 PQfn(PGconn *conn,
2537          int fnid,
2538          int *result_buf,
2539          int *actual_result_len,
2540          int result_is_int,
2541          const PQArgBlock *args,
2542          int nargs)
2543 {
2544         *actual_result_len = 0;
2545
2546         if (!conn)
2547                 return NULL;
2548
2549         /* clear the error string */
2550         resetPQExpBuffer(&conn->errorMessage);
2551
2552         if (conn->sock == PGINVALID_SOCKET || conn->asyncStatus != PGASYNC_IDLE ||
2553                 conn->result != NULL)
2554         {
2555                 printfPQExpBuffer(&conn->errorMessage,
2556                                                   libpq_gettext("connection in wrong state\n"));
2557                 return NULL;
2558         }
2559
2560         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2561                 return pqFunctionCall3(conn, fnid,
2562                                                            result_buf, actual_result_len,
2563                                                            result_is_int,
2564                                                            args, nargs);
2565         else
2566                 return pqFunctionCall2(conn, fnid,
2567                                                            result_buf, actual_result_len,
2568                                                            result_is_int,
2569                                                            args, nargs);
2570 }
2571
2572
2573 /* ====== accessor funcs for PGresult ======== */
2574
2575 ExecStatusType
2576 PQresultStatus(const PGresult *res)
2577 {
2578         if (!res)
2579                 return PGRES_FATAL_ERROR;
2580         return res->resultStatus;
2581 }
2582
2583 char *
2584 PQresStatus(ExecStatusType status)
2585 {
2586         if ((unsigned int) status >= sizeof pgresStatus / sizeof pgresStatus[0])
2587                 return libpq_gettext("invalid ExecStatusType code");
2588         return pgresStatus[status];
2589 }
2590
2591 char *
2592 PQresultErrorMessage(const PGresult *res)
2593 {
2594         if (!res || !res->errMsg)
2595                 return "";
2596         return res->errMsg;
2597 }
2598
2599 char *
2600 PQresultErrorField(const PGresult *res, int fieldcode)
2601 {
2602         PGMessageField *pfield;
2603
2604         if (!res)
2605                 return NULL;
2606         for (pfield = res->errFields; pfield != NULL; pfield = pfield->next)
2607         {
2608                 if (pfield->code == fieldcode)
2609                         return pfield->contents;
2610         }
2611         return NULL;
2612 }
2613
2614 int
2615 PQntuples(const PGresult *res)
2616 {
2617         if (!res)
2618                 return 0;
2619         return res->ntups;
2620 }
2621
2622 int
2623 PQnfields(const PGresult *res)
2624 {
2625         if (!res)
2626                 return 0;
2627         return res->numAttributes;
2628 }
2629
2630 int
2631 PQbinaryTuples(const PGresult *res)
2632 {
2633         if (!res)
2634                 return 0;
2635         return res->binary;
2636 }
2637
2638 /*
2639  * Helper routines to range-check field numbers and tuple numbers.
2640  * Return TRUE if OK, FALSE if not
2641  */
2642
2643 static int
2644 check_field_number(const PGresult *res, int field_num)
2645 {
2646         if (!res)
2647                 return FALSE;                   /* no way to display error message... */
2648         if (field_num < 0 || field_num >= res->numAttributes)
2649         {
2650                 pqInternalNotice(&res->noticeHooks,
2651                                                  "column number %d is out of range 0..%d",
2652                                                  field_num, res->numAttributes - 1);
2653                 return FALSE;
2654         }
2655         return TRUE;
2656 }
2657
2658 static int
2659 check_tuple_field_number(const PGresult *res,
2660                                                  int tup_num, int field_num)
2661 {
2662         if (!res)
2663                 return FALSE;                   /* no way to display error message... */
2664         if (tup_num < 0 || tup_num >= res->ntups)
2665         {
2666                 pqInternalNotice(&res->noticeHooks,
2667                                                  "row number %d is out of range 0..%d",
2668                                                  tup_num, res->ntups - 1);
2669                 return FALSE;
2670         }
2671         if (field_num < 0 || field_num >= res->numAttributes)
2672         {
2673                 pqInternalNotice(&res->noticeHooks,
2674                                                  "column number %d is out of range 0..%d",
2675                                                  field_num, res->numAttributes - 1);
2676                 return FALSE;
2677         }
2678         return TRUE;
2679 }
2680
2681 static int
2682 check_param_number(const PGresult *res, int param_num)
2683 {
2684         if (!res)
2685                 return FALSE;                   /* no way to display error message... */
2686         if (param_num < 0 || param_num >= res->numParameters)
2687         {
2688                 pqInternalNotice(&res->noticeHooks,
2689                                                  "parameter number %d is out of range 0..%d",
2690                                                  param_num, res->numParameters - 1);
2691                 return FALSE;
2692         }
2693
2694         return TRUE;
2695 }
2696
2697 /*
2698  * returns NULL if the field_num is invalid
2699  */
2700 char *
2701 PQfname(const PGresult *res, int field_num)
2702 {
2703         if (!check_field_number(res, field_num))
2704                 return NULL;
2705         if (res->attDescs)
2706                 return res->attDescs[field_num].name;
2707         else
2708                 return NULL;
2709 }
2710
2711 /*
2712  * PQfnumber: find column number given column name
2713  *
2714  * The column name is parsed as if it were in a SQL statement, including
2715  * case-folding and double-quote processing.  But note a possible gotcha:
2716  * downcasing in the frontend might follow different locale rules than
2717  * downcasing in the backend...
2718  *
2719  * Returns -1 if no match.  In the present backend it is also possible
2720  * to have multiple matches, in which case the first one is found.
2721  */
2722 int
2723 PQfnumber(const PGresult *res, const char *field_name)
2724 {
2725         char       *field_case;
2726         bool            in_quotes;
2727         bool            all_lower = true;
2728         const char *iptr;
2729         char       *optr;
2730         int                     i;
2731
2732         if (!res)
2733                 return -1;
2734
2735         /*
2736          * Note: it is correct to reject a zero-length input string; the proper
2737          * input to match a zero-length field name would be "".
2738          */
2739         if (field_name == NULL ||
2740                 field_name[0] == '\0' ||
2741                 res->attDescs == NULL)
2742                 return -1;
2743
2744         /*
2745          * Check if we can avoid the strdup() and related work because the
2746          * passed-in string wouldn't be changed before we do the check anyway.
2747          */
2748         for (iptr = field_name; *iptr; iptr++)
2749         {
2750                 char            c = *iptr;
2751
2752                 if (c == '"' || c != pg_tolower((unsigned char) c))
2753                 {
2754                         all_lower = false;
2755                         break;
2756                 }
2757         }
2758
2759         if (all_lower)
2760                 for (i = 0; i < res->numAttributes; i++)
2761                         if (strcmp(field_name, res->attDescs[i].name) == 0)
2762                                 return i;
2763
2764         /* Fall through to the normal check if that didn't work out. */
2765
2766         /*
2767          * Note: this code will not reject partially quoted strings, eg
2768          * foo"BAR"foo will become fooBARfoo when it probably ought to be an error
2769          * condition.
2770          */
2771         field_case = strdup(field_name);
2772         if (field_case == NULL)
2773                 return -1;                              /* grotty */
2774
2775         in_quotes = false;
2776         optr = field_case;
2777         for (iptr = field_case; *iptr; iptr++)
2778         {
2779                 char            c = *iptr;
2780
2781                 if (in_quotes)
2782                 {
2783                         if (c == '"')
2784                         {
2785                                 if (iptr[1] == '"')
2786                                 {
2787                                         /* doubled quotes become a single quote */
2788                                         *optr++ = '"';
2789                                         iptr++;
2790                                 }
2791                                 else
2792                                         in_quotes = false;
2793                         }
2794                         else
2795                                 *optr++ = c;
2796                 }
2797                 else if (c == '"')
2798                         in_quotes = true;
2799                 else
2800                 {
2801                         c = pg_tolower((unsigned char) c);
2802                         *optr++ = c;
2803                 }
2804         }
2805         *optr = '\0';
2806
2807         for (i = 0; i < res->numAttributes; i++)
2808         {
2809                 if (strcmp(field_case, res->attDescs[i].name) == 0)
2810                 {
2811                         free(field_case);
2812                         return i;
2813                 }
2814         }
2815         free(field_case);
2816         return -1;
2817 }
2818
2819 Oid
2820 PQftable(const PGresult *res, int field_num)
2821 {
2822         if (!check_field_number(res, field_num))
2823                 return InvalidOid;
2824         if (res->attDescs)
2825                 return res->attDescs[field_num].tableid;
2826         else
2827                 return InvalidOid;
2828 }
2829
2830 int
2831 PQftablecol(const PGresult *res, int field_num)
2832 {
2833         if (!check_field_number(res, field_num))
2834                 return 0;
2835         if (res->attDescs)
2836                 return res->attDescs[field_num].columnid;
2837         else
2838                 return 0;
2839 }
2840
2841 int
2842 PQfformat(const PGresult *res, int field_num)
2843 {
2844         if (!check_field_number(res, field_num))
2845                 return 0;
2846         if (res->attDescs)
2847                 return res->attDescs[field_num].format;
2848         else
2849                 return 0;
2850 }
2851
2852 Oid
2853 PQftype(const PGresult *res, int field_num)
2854 {
2855         if (!check_field_number(res, field_num))
2856                 return InvalidOid;
2857         if (res->attDescs)
2858                 return res->attDescs[field_num].typid;
2859         else
2860                 return InvalidOid;
2861 }
2862
2863 int
2864 PQfsize(const PGresult *res, int field_num)
2865 {
2866         if (!check_field_number(res, field_num))
2867                 return 0;
2868         if (res->attDescs)
2869                 return res->attDescs[field_num].typlen;
2870         else
2871                 return 0;
2872 }
2873
2874 int
2875 PQfmod(const PGresult *res, int field_num)
2876 {
2877         if (!check_field_number(res, field_num))
2878                 return 0;
2879         if (res->attDescs)
2880                 return res->attDescs[field_num].atttypmod;
2881         else
2882                 return 0;
2883 }
2884
2885 char *
2886 PQcmdStatus(PGresult *res)
2887 {
2888         if (!res)
2889                 return NULL;
2890         return res->cmdStatus;
2891 }
2892
2893 /*
2894  * PQoidStatus -
2895  *      if the last command was an INSERT, return the oid string
2896  *      if not, return ""
2897  */
2898 char *
2899 PQoidStatus(const PGresult *res)
2900 {
2901         /*
2902          * This must be enough to hold the result. Don't laugh, this is better
2903          * than what this function used to do.
2904          */
2905         static char buf[24];
2906
2907         size_t          len;
2908
2909         if (!res || strncmp(res->cmdStatus, "INSERT ", 7) != 0)
2910                 return "";
2911
2912         len = strspn(res->cmdStatus + 7, "0123456789");
2913         if (len > 23)
2914                 len = 23;
2915         strncpy(buf, res->cmdStatus + 7, len);
2916         buf[len] = '\0';
2917
2918         return buf;
2919 }
2920
2921 /*
2922  * PQoidValue -
2923  *      a perhaps preferable form of the above which just returns
2924  *      an Oid type
2925  */
2926 Oid
2927 PQoidValue(const PGresult *res)
2928 {
2929         char       *endptr = NULL;
2930         unsigned long result;
2931
2932         if (!res ||
2933                 strncmp(res->cmdStatus, "INSERT ", 7) != 0 ||
2934                 res->cmdStatus[7] < '0' ||
2935                 res->cmdStatus[7] > '9')
2936                 return InvalidOid;
2937
2938         result = strtoul(res->cmdStatus + 7, &endptr, 10);
2939
2940         if (!endptr || (*endptr != ' ' && *endptr != '\0'))
2941                 return InvalidOid;
2942         else
2943                 return (Oid) result;
2944 }
2945
2946
2947 /*
2948  * PQcmdTuples -
2949  *      If the last command was INSERT/UPDATE/DELETE/MOVE/FETCH/COPY, return
2950  *      a string containing the number of inserted/affected tuples. If not,
2951  *      return "".
2952  *
2953  *      XXX: this should probably return an int
2954  */
2955 char *
2956 PQcmdTuples(PGresult *res)
2957 {
2958         char       *p,
2959                            *c;
2960
2961         if (!res)
2962                 return "";
2963
2964         if (strncmp(res->cmdStatus, "INSERT ", 7) == 0)
2965         {
2966                 p = res->cmdStatus + 7;
2967                 /* INSERT: skip oid and space */
2968                 while (*p && *p != ' ')
2969                         p++;
2970                 if (*p == 0)
2971                         goto interpret_error;           /* no space? */
2972                 p++;
2973         }
2974         else if (strncmp(res->cmdStatus, "SELECT ", 7) == 0 ||
2975                          strncmp(res->cmdStatus, "DELETE ", 7) == 0 ||
2976                          strncmp(res->cmdStatus, "UPDATE ", 7) == 0)
2977                 p = res->cmdStatus + 7;
2978         else if (strncmp(res->cmdStatus, "FETCH ", 6) == 0)
2979                 p = res->cmdStatus + 6;
2980         else if (strncmp(res->cmdStatus, "MOVE ", 5) == 0 ||
2981                          strncmp(res->cmdStatus, "COPY ", 5) == 0)
2982                 p = res->cmdStatus + 5;
2983         else
2984                 return "";
2985
2986         /* check that we have an integer (at least one digit, nothing else) */
2987         for (c = p; *c; c++)
2988         {
2989                 if (!isdigit((unsigned char) *c))
2990                         goto interpret_error;
2991         }
2992         if (c == p)
2993                 goto interpret_error;
2994
2995         return p;
2996
2997 interpret_error:
2998         pqInternalNotice(&res->noticeHooks,
2999                                          "could not interpret result from server: %s",
3000                                          res->cmdStatus);
3001         return "";
3002 }
3003
3004 /*
3005  * PQgetvalue:
3006  *      return the value of field 'field_num' of row 'tup_num'
3007  */
3008 char *
3009 PQgetvalue(const PGresult *res, int tup_num, int field_num)
3010 {
3011         if (!check_tuple_field_number(res, tup_num, field_num))
3012                 return NULL;
3013         return res->tuples[tup_num][field_num].value;
3014 }
3015
3016 /* PQgetlength:
3017  *      returns the actual length of a field value in bytes.
3018  */
3019 int
3020 PQgetlength(const PGresult *res, int tup_num, int field_num)
3021 {
3022         if (!check_tuple_field_number(res, tup_num, field_num))
3023                 return 0;
3024         if (res->tuples[tup_num][field_num].len != NULL_LEN)
3025                 return res->tuples[tup_num][field_num].len;
3026         else
3027                 return 0;
3028 }
3029
3030 /* PQgetisnull:
3031  *      returns the null status of a field value.
3032  */
3033 int
3034 PQgetisnull(const PGresult *res, int tup_num, int field_num)
3035 {
3036         if (!check_tuple_field_number(res, tup_num, field_num))
3037                 return 1;                               /* pretend it is null */
3038         if (res->tuples[tup_num][field_num].len == NULL_LEN)
3039                 return 1;
3040         else
3041                 return 0;
3042 }
3043
3044 /* PQnparams:
3045  *      returns the number of input parameters of a prepared statement.
3046  */
3047 int
3048 PQnparams(const PGresult *res)
3049 {
3050         if (!res)
3051                 return 0;
3052         return res->numParameters;
3053 }
3054
3055 /* PQparamtype:
3056  *      returns type Oid of the specified statement parameter.
3057  */
3058 Oid
3059 PQparamtype(const PGresult *res, int param_num)
3060 {
3061         if (!check_param_number(res, param_num))
3062                 return InvalidOid;
3063         if (res->paramDescs)
3064                 return res->paramDescs[param_num].typid;
3065         else
3066                 return InvalidOid;
3067 }
3068
3069
3070 /* PQsetnonblocking:
3071  *      sets the PGconn's database connection non-blocking if the arg is TRUE
3072  *      or makes it blocking if the arg is FALSE, this will not protect
3073  *      you from PQexec(), you'll only be safe when using the non-blocking API.
3074  *      Needs to be called only on a connected database connection.
3075  */
3076 int
3077 PQsetnonblocking(PGconn *conn, int arg)
3078 {
3079         bool            barg;
3080
3081         if (!conn || conn->status == CONNECTION_BAD)
3082                 return -1;
3083
3084         barg = (arg ? TRUE : FALSE);
3085
3086         /* early out if the socket is already in the state requested */
3087         if (barg == conn->nonblocking)
3088                 return 0;
3089
3090         /*
3091          * to guarantee constancy for flushing/query/result-polling behavior we
3092          * need to flush the send queue at this point in order to guarantee proper
3093          * behavior. this is ok because either they are making a transition _from_
3094          * or _to_ blocking mode, either way we can block them.
3095          */
3096         /* if we are going from blocking to non-blocking flush here */
3097         if (pqFlush(conn))
3098                 return -1;
3099
3100         conn->nonblocking = barg;
3101
3102         return 0;
3103 }
3104
3105 /*
3106  * return the blocking status of the database connection
3107  *              TRUE == nonblocking, FALSE == blocking
3108  */
3109 int
3110 PQisnonblocking(const PGconn *conn)
3111 {
3112         return pqIsnonblocking(conn);
3113 }
3114
3115 /* libpq is thread-safe? */
3116 int
3117 PQisthreadsafe(void)
3118 {
3119 #ifdef ENABLE_THREAD_SAFETY
3120         return true;
3121 #else
3122         return false;
3123 #endif
3124 }
3125
3126
3127 /* try to force data out, really only useful for non-blocking users */
3128 int
3129 PQflush(PGconn *conn)
3130 {
3131         return pqFlush(conn);
3132 }
3133
3134
3135 /*
3136  *              PQfreemem - safely frees memory allocated
3137  *
3138  * Needed mostly by Win32, unless multithreaded DLL (/MD in VC6)
3139  * Used for freeing memory from PQescapeByte()a/PQunescapeBytea()
3140  */
3141 void
3142 PQfreemem(void *ptr)
3143 {
3144         free(ptr);
3145 }
3146
3147 /*
3148  * PQfreeNotify - free's the memory associated with a PGnotify
3149  *
3150  * This function is here only for binary backward compatibility.
3151  * New code should use PQfreemem().  A macro will automatically map
3152  * calls to PQfreemem.  It should be removed in the future.  bjm 2003-03-24
3153  */
3154
3155 #undef PQfreeNotify
3156 void            PQfreeNotify(PGnotify *notify);
3157
3158 void
3159 PQfreeNotify(PGnotify *notify)
3160 {
3161         PQfreemem(notify);
3162 }
3163
3164
3165 /*
3166  * Escaping arbitrary strings to get valid SQL literal strings.
3167  *
3168  * Replaces "'" with "''", and if not std_strings, replaces "\" with "\\".
3169  *
3170  * length is the length of the source string.  (Note: if a terminating NUL
3171  * is encountered sooner, PQescapeString stops short of "length"; the behavior
3172  * is thus rather like strncpy.)
3173  *
3174  * For safety the buffer at "to" must be at least 2*length + 1 bytes long.
3175  * A terminating NUL character is added to the output string, whether the
3176  * input is NUL-terminated or not.
3177  *
3178  * Returns the actual length of the output (not counting the terminating NUL).
3179  */
3180 static size_t
3181 PQescapeStringInternal(PGconn *conn,
3182                                            char *to, const char *from, size_t length,
3183                                            int *error,
3184                                            int encoding, bool std_strings)
3185 {
3186         const char *source = from;
3187         char       *target = to;
3188         size_t          remaining = length;
3189
3190         if (error)
3191                 *error = 0;
3192
3193         while (remaining > 0 && *source != '\0')
3194         {
3195                 char            c = *source;
3196                 int                     len;
3197                 int                     i;
3198
3199                 /* Fast path for plain ASCII */
3200                 if (!IS_HIGHBIT_SET(c))
3201                 {
3202                         /* Apply quoting if needed */
3203                         if (SQL_STR_DOUBLE(c, !std_strings))
3204                                 *target++ = c;
3205                         /* Copy the character */
3206                         *target++ = c;
3207                         source++;
3208                         remaining--;
3209                         continue;
3210                 }
3211
3212                 /* Slow path for possible multibyte characters */
3213                 len = pg_encoding_mblen(encoding, source);
3214
3215                 /* Copy the character */
3216                 for (i = 0; i < len; i++)
3217                 {
3218                         if (remaining == 0 || *source == '\0')
3219                                 break;
3220                         *target++ = *source++;
3221                         remaining--;
3222                 }
3223
3224                 /*
3225                  * If we hit premature end of string (ie, incomplete multibyte
3226                  * character), try to pad out to the correct length with spaces. We
3227                  * may not be able to pad completely, but we will always be able to
3228                  * insert at least one pad space (since we'd not have quoted a
3229                  * multibyte character).  This should be enough to make a string that
3230                  * the server will error out on.
3231                  */
3232                 if (i < len)
3233                 {
3234                         if (error)
3235                                 *error = 1;
3236                         if (conn)
3237                                 printfPQExpBuffer(&conn->errorMessage,
3238                                                   libpq_gettext("incomplete multibyte character\n"));
3239                         for (; i < len; i++)
3240                         {
3241                                 if (((size_t) (target - to)) / 2 >= length)
3242                                         break;
3243                                 *target++ = ' ';
3244                         }
3245                         break;
3246                 }
3247         }
3248
3249         /* Write the terminating NUL character. */
3250         *target = '\0';
3251
3252         return target - to;
3253 }
3254
3255 size_t
3256 PQescapeStringConn(PGconn *conn,
3257                                    char *to, const char *from, size_t length,
3258                                    int *error)
3259 {
3260         if (!conn)
3261         {
3262                 /* force empty-string result */
3263                 *to = '\0';
3264                 if (error)
3265                         *error = 1;
3266                 return 0;
3267         }
3268         return PQescapeStringInternal(conn, to, from, length, error,
3269                                                                   conn->client_encoding,
3270                                                                   conn->std_strings);
3271 }
3272
3273 size_t
3274 PQescapeString(char *to, const char *from, size_t length)
3275 {
3276         return PQescapeStringInternal(NULL, to, from, length, NULL,
3277                                                                   static_client_encoding,
3278                                                                   static_std_strings);
3279 }
3280
3281
3282 /*
3283  * Escape arbitrary strings.  If as_ident is true, we escape the result
3284  * as an identifier; if false, as a literal.  The result is returned in
3285  * a newly allocated buffer.  If we fail due to an encoding violation or out
3286  * of memory condition, we return NULL, storing an error message into conn.
3287  */
3288 static char *
3289 PQescapeInternal(PGconn *conn, const char *str, size_t len, bool as_ident)
3290 {
3291         const char *s;
3292         char       *result;
3293         char       *rp;
3294         int                     num_quotes = 0; /* single or double, depending on as_ident */
3295         int                     num_backslashes = 0;
3296         int                     input_len;
3297         int                     result_size;
3298         char            quote_char = as_ident ? '"' : '\'';
3299
3300         /* We must have a connection, else fail immediately. */
3301         if (!conn)
3302                 return NULL;
3303
3304         /* Scan the string for characters that must be escaped. */
3305         for (s = str; (s - str) < len && *s != '\0'; ++s)
3306         {
3307                 if (*s == quote_char)
3308                         ++num_quotes;
3309                 else if (*s == '\\')
3310                         ++num_backslashes;
3311                 else if (IS_HIGHBIT_SET(*s))
3312                 {
3313                         int                     charlen;
3314
3315                         /* Slow path for possible multibyte characters */
3316                         charlen = pg_encoding_mblen(conn->client_encoding, s);
3317
3318                         /* Multibyte character overruns allowable length. */
3319                         if ((s - str) + charlen > len || memchr(s, 0, charlen) != NULL)
3320                         {
3321                                 printfPQExpBuffer(&conn->errorMessage,
3322                                                   libpq_gettext("incomplete multibyte character\n"));
3323                                 return NULL;
3324                         }
3325
3326                         /* Adjust s, bearing in mind that for loop will increment it. */
3327                         s += charlen - 1;
3328                 }
3329         }
3330
3331         /* Allocate output buffer. */
3332         input_len = s - str;
3333         result_size = input_len + num_quotes + 3;       /* two quotes, plus a NUL */
3334         if (!as_ident && num_backslashes > 0)
3335                 result_size += num_backslashes + 2;
3336         result = rp = (char *) malloc(result_size);
3337         if (rp == NULL)
3338         {
3339                 printfPQExpBuffer(&conn->errorMessage,
3340                                                   libpq_gettext("out of memory\n"));
3341                 return NULL;
3342         }
3343
3344         /*
3345          * If we are escaping a literal that contains backslashes, we use the
3346          * escape string syntax so that the result is correct under either value
3347          * of standard_conforming_strings.  We also emit a leading space in this
3348          * case, to guard against the possibility that the result might be
3349          * interpolated immediately following an identifier.
3350          */
3351         if (!as_ident && num_backslashes > 0)
3352         {
3353                 *rp++ = ' ';
3354                 *rp++ = 'E';
3355         }
3356
3357         /* Opening quote. */
3358         *rp++ = quote_char;
3359
3360         /*
3361          * Use fast path if possible.
3362          *
3363          * We've already verified that the input string is well-formed in the
3364          * current encoding.  If it contains no quotes and, in the case of
3365          * literal-escaping, no backslashes, then we can just copy it directly to
3366          * the output buffer, adding the necessary quotes.
3367          *
3368          * If not, we must rescan the input and process each character
3369          * individually.
3370          */
3371         if (num_quotes == 0 && (num_backslashes == 0 || as_ident))
3372         {
3373                 memcpy(rp, str, input_len);
3374                 rp += input_len;
3375         }
3376         else
3377         {
3378                 for (s = str; s - str < input_len; ++s)
3379                 {
3380                         if (*s == quote_char || (!as_ident && *s == '\\'))
3381                         {
3382                                 *rp++ = *s;
3383                                 *rp++ = *s;
3384                         }
3385                         else if (!IS_HIGHBIT_SET(*s))
3386                                 *rp++ = *s;
3387                         else
3388                         {
3389                                 int                     i = pg_encoding_mblen(conn->client_encoding, s);
3390
3391                                 while (1)
3392                                 {
3393                                         *rp++ = *s;
3394                                         if (--i == 0)
3395                                                 break;
3396                                         ++s;            /* for loop will provide the final increment */
3397                                 }
3398                         }
3399                 }
3400         }
3401
3402         /* Closing quote and terminating NUL. */
3403         *rp++ = quote_char;
3404         *rp = '\0';
3405
3406         return result;
3407 }
3408
3409 char *
3410 PQescapeLiteral(PGconn *conn, const char *str, size_t len)
3411 {
3412         return PQescapeInternal(conn, str, len, false);
3413 }
3414
3415 char *
3416 PQescapeIdentifier(PGconn *conn, const char *str, size_t len)
3417 {
3418         return PQescapeInternal(conn, str, len, true);
3419 }
3420
3421 /* HEX encoding support for bytea */
3422 static const char hextbl[] = "0123456789abcdef";
3423
3424 static const int8 hexlookup[128] = {
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         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3428         0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
3429         -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3430         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3431         -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3432         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
3433 };
3434
3435 static inline char
3436 get_hex(char c)
3437 {
3438         int                     res = -1;
3439
3440         if (c > 0 && c < 127)
3441                 res = hexlookup[(unsigned char) c];
3442
3443         return (char) res;
3444 }
3445
3446
3447 /*
3448  *              PQescapeBytea   - converts from binary string to the
3449  *              minimal encoding necessary to include the string in an SQL
3450  *              INSERT statement with a bytea type column as the target.
3451  *
3452  *              We can use either hex or escape (traditional) encoding.
3453  *              In escape mode, the following transformations are applied:
3454  *              '\0' == ASCII  0 == \000
3455  *              '\'' == ASCII 39 == ''
3456  *              '\\' == ASCII 92 == \\
3457  *              anything < 0x20, or > 0x7e ---> \ooo
3458  *                                                                              (where ooo is an octal expression)
3459  *
3460  *              If not std_strings, all backslashes sent to the output are doubled.
3461  */
3462 static unsigned char *
3463 PQescapeByteaInternal(PGconn *conn,
3464                                           const unsigned char *from, size_t from_length,
3465                                           size_t *to_length, bool std_strings, bool use_hex)
3466 {
3467         const unsigned char *vp;
3468         unsigned char *rp;
3469         unsigned char *result;
3470         size_t          i;
3471         size_t          len;
3472         size_t          bslash_len = (std_strings ? 1 : 2);
3473
3474         /*
3475          * empty string has 1 char ('\0')
3476          */
3477         len = 1;
3478
3479         if (use_hex)
3480         {
3481                 len += bslash_len + 1 + 2 * from_length;
3482         }
3483         else
3484         {
3485                 vp = from;
3486                 for (i = from_length; i > 0; i--, vp++)
3487                 {
3488                         if (*vp < 0x20 || *vp > 0x7e)
3489                                 len += bslash_len + 3;
3490                         else if (*vp == '\'')
3491                                 len += 2;
3492                         else if (*vp == '\\')
3493                                 len += bslash_len + bslash_len;
3494                         else
3495                                 len++;
3496                 }
3497         }
3498
3499         *to_length = len;
3500         rp = result = (unsigned char *) malloc(len);
3501         if (rp == NULL)
3502         {
3503                 if (conn)
3504                         printfPQExpBuffer(&conn->errorMessage,
3505                                                           libpq_gettext("out of memory\n"));
3506                 return NULL;
3507         }
3508
3509         if (use_hex)
3510         {
3511                 if (!std_strings)
3512                         *rp++ = '\\';
3513                 *rp++ = '\\';
3514                 *rp++ = 'x';
3515         }
3516
3517         vp = from;
3518         for (i = from_length; i > 0; i--, vp++)
3519         {
3520                 unsigned char c = *vp;
3521
3522                 if (use_hex)
3523                 {
3524                         *rp++ = hextbl[(c >> 4) & 0xF];
3525                         *rp++ = hextbl[c & 0xF];
3526                 }
3527                 else if (c < 0x20 || c > 0x7e)
3528                 {
3529                         if (!std_strings)
3530                                 *rp++ = '\\';
3531                         *rp++ = '\\';
3532                         *rp++ = (c >> 6) + '0';
3533                         *rp++ = ((c >> 3) & 07) + '0';
3534                         *rp++ = (c & 07) + '0';
3535                 }
3536                 else if (c == '\'')
3537                 {
3538                         *rp++ = '\'';
3539                         *rp++ = '\'';
3540                 }
3541                 else if (c == '\\')
3542                 {
3543                         if (!std_strings)
3544                         {
3545                                 *rp++ = '\\';
3546                                 *rp++ = '\\';
3547                         }
3548                         *rp++ = '\\';
3549                         *rp++ = '\\';
3550                 }
3551                 else
3552                         *rp++ = c;
3553         }
3554         *rp = '\0';
3555
3556         return result;
3557 }
3558
3559 unsigned char *
3560 PQescapeByteaConn(PGconn *conn,
3561                                   const unsigned char *from, size_t from_length,
3562                                   size_t *to_length)
3563 {
3564         if (!conn)
3565                 return NULL;
3566         return PQescapeByteaInternal(conn, from, from_length, to_length,
3567                                                                  conn->std_strings,
3568                                                                  (conn->sversion >= 90000));
3569 }
3570
3571 unsigned char *
3572 PQescapeBytea(const unsigned char *from, size_t from_length, size_t *to_length)
3573 {
3574         return PQescapeByteaInternal(NULL, from, from_length, to_length,
3575                                                                  static_std_strings,
3576                                                                  false /* can't use hex */ );
3577 }
3578
3579
3580 #define ISFIRSTOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '3')
3581 #define ISOCTDIGIT(CH) ((CH) >= '0' && (CH) <= '7')
3582 #define OCTVAL(CH) ((CH) - '0')
3583
3584 /*
3585  *              PQunescapeBytea - converts the null terminated string representation
3586  *              of a bytea, strtext, into binary, filling a buffer. It returns a
3587  *              pointer to the buffer (or NULL on error), and the size of the
3588  *              buffer in retbuflen. The pointer may subsequently be used as an
3589  *              argument to the function PQfreemem.
3590  *
3591  *              The following transformations are made:
3592  *              \\       == ASCII 92 == \
3593  *              \ooo == a byte whose value = ooo (ooo is an octal number)
3594  *              \x       == x (x is any character not matched by the above transformations)
3595  */
3596 unsigned char *
3597 PQunescapeBytea(const unsigned char *strtext, size_t *retbuflen)
3598 {
3599         size_t          strtextlen,
3600                                 buflen;
3601         unsigned char *buffer,
3602                            *tmpbuf;
3603         size_t          i,
3604                                 j;
3605
3606         if (strtext == NULL)
3607                 return NULL;
3608
3609         strtextlen = strlen((const char *) strtext);
3610
3611         if (strtext[0] == '\\' && strtext[1] == 'x')
3612         {
3613                 const unsigned char *s;
3614                 unsigned char *p;
3615
3616                 buflen = (strtextlen - 2) / 2;
3617                 /* Avoid unportable malloc(0) */
3618                 buffer = (unsigned char *) malloc(buflen > 0 ? buflen : 1);
3619                 if (buffer == NULL)
3620                         return NULL;
3621
3622                 s = strtext + 2;
3623                 p = buffer;
3624                 while (*s)
3625                 {
3626                         char            v1,
3627                                                 v2;
3628
3629                         /*
3630                          * Bad input is silently ignored.  Note that this includes
3631                          * whitespace between hex pairs, which is allowed by byteain.
3632                          */
3633                         v1 = get_hex(*s++);
3634                         if (!*s || v1 == (char) -1)
3635                                 continue;
3636                         v2 = get_hex(*s++);
3637                         if (v2 != (char) -1)
3638                                 *p++ = (v1 << 4) | v2;
3639                 }
3640
3641                 buflen = p - buffer;
3642         }
3643         else
3644         {
3645                 /*
3646                  * Length of input is max length of output, but add one to avoid
3647                  * unportable malloc(0) if input is zero-length.
3648                  */
3649                 buffer = (unsigned char *) malloc(strtextlen + 1);
3650                 if (buffer == NULL)
3651                         return NULL;
3652
3653                 for (i = j = 0; i < strtextlen;)
3654                 {
3655                         switch (strtext[i])
3656                         {
3657                                 case '\\':
3658                                         i++;
3659                                         if (strtext[i] == '\\')
3660                                                 buffer[j++] = strtext[i++];
3661                                         else
3662                                         {
3663                                                 if ((ISFIRSTOCTDIGIT(strtext[i])) &&
3664                                                         (ISOCTDIGIT(strtext[i + 1])) &&
3665                                                         (ISOCTDIGIT(strtext[i + 2])))
3666                                                 {
3667                                                         int                     byte;
3668
3669                                                         byte = OCTVAL(strtext[i++]);
3670                                                         byte = (byte << 3) + OCTVAL(strtext[i++]);
3671                                                         byte = (byte << 3) + OCTVAL(strtext[i++]);
3672                                                         buffer[j++] = byte;
3673                                                 }
3674                                         }
3675
3676                                         /*
3677                                          * Note: if we see '\' followed by something that isn't a
3678                                          * recognized escape sequence, we loop around having done
3679                                          * nothing except advance i.  Therefore the something will
3680                                          * be emitted as ordinary data on the next cycle. Corner
3681                                          * case: '\' at end of string will just be discarded.
3682                                          */
3683                                         break;
3684
3685                                 default:
3686                                         buffer[j++] = strtext[i++];
3687                                         break;
3688                         }
3689                 }
3690                 buflen = j;                             /* buflen is the length of the dequoted data */
3691         }
3692
3693         /* Shrink the buffer to be no larger than necessary */
3694         /* +1 avoids unportable behavior when buflen==0 */
3695         tmpbuf = realloc(buffer, buflen + 1);
3696
3697         /* It would only be a very brain-dead realloc that could fail, but... */
3698         if (!tmpbuf)
3699         {
3700                 free(buffer);
3701                 return NULL;
3702         }
3703
3704         *retbuflen = buflen;
3705         return tmpbuf;
3706 }