]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-misc.c
Update copyright for 2014
[postgresql] / src / interfaces / libpq / fe-misc.c
1 /*-------------------------------------------------------------------------
2  *
3  *       FILE
4  *              fe-misc.c
5  *
6  *       DESCRIPTION
7  *               miscellaneous useful functions
8  *
9  * The communication routines here are analogous to the ones in
10  * backend/libpq/pqcomm.c and backend/libpq/pqcomprim.c, but operate
11  * in the considerably different environment of the frontend libpq.
12  * In particular, we work with a bare nonblock-mode socket, rather than
13  * a stdio stream, so that we can avoid unwanted blocking of the application.
14  *
15  * XXX: MOVE DEBUG PRINTOUT TO HIGHER LEVEL.  As is, block and restart
16  * will cause repeat printouts.
17  *
18  * We must speak the same transmitted data representations as the backend
19  * routines.
20  *
21  *
22  * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
23  * Portions Copyright (c) 1994, Regents of the University of California
24  *
25  * IDENTIFICATION
26  *        src/interfaces/libpq/fe-misc.c
27  *
28  *-------------------------------------------------------------------------
29  */
30
31 #include "postgres_fe.h"
32
33 #include <signal.h>
34 #include <time.h>
35
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
38
39 #ifdef WIN32
40 #include "win32.h"
41 #else
42 #include <unistd.h>
43 #include <sys/time.h>
44 #endif
45
46 #ifdef HAVE_POLL_H
47 #include <poll.h>
48 #endif
49 #ifdef HAVE_SYS_POLL_H
50 #include <sys/poll.h>
51 #endif
52 #ifdef HAVE_SYS_SELECT_H
53 #include <sys/select.h>
54 #endif
55
56 #include "libpq-fe.h"
57 #include "libpq-int.h"
58 #include "mb/pg_wchar.h"
59 #include "pg_config_paths.h"
60
61
62 static int      pqPutMsgBytes(const void *buf, size_t len, PGconn *conn);
63 static int      pqSendSome(PGconn *conn, int len);
64 static int pqSocketCheck(PGconn *conn, int forRead, int forWrite,
65                           time_t end_time);
66 static int      pqSocketPoll(int sock, int forRead, int forWrite, time_t end_time);
67
68 /*
69  * PQlibVersion: return the libpq version number
70  */
71 int
72 PQlibVersion(void)
73 {
74         return PG_VERSION_NUM;
75 }
76
77 /*
78  * fputnbytes: print exactly N bytes to a file
79  *
80  * We avoid using %.*s here because it can misbehave if the data
81  * is not valid in what libc thinks is the prevailing encoding.
82  */
83 static void
84 fputnbytes(FILE *f, const char *str, size_t n)
85 {
86         while (n-- > 0)
87                 fputc(*str++, f);
88 }
89
90
91 /*
92  * pqGetc: get 1 character from the connection
93  *
94  *      All these routines return 0 on success, EOF on error.
95  *      Note that for the Get routines, EOF only means there is not enough
96  *      data in the buffer, not that there is necessarily a hard error.
97  */
98 int
99 pqGetc(char *result, PGconn *conn)
100 {
101         if (conn->inCursor >= conn->inEnd)
102                 return EOF;
103
104         *result = conn->inBuffer[conn->inCursor++];
105
106         if (conn->Pfdebug)
107                 fprintf(conn->Pfdebug, "From backend> %c\n", *result);
108
109         return 0;
110 }
111
112
113 /*
114  * pqPutc: write 1 char to the current message
115  */
116 int
117 pqPutc(char c, PGconn *conn)
118 {
119         if (pqPutMsgBytes(&c, 1, conn))
120                 return EOF;
121
122         if (conn->Pfdebug)
123                 fprintf(conn->Pfdebug, "To backend> %c\n", c);
124
125         return 0;
126 }
127
128
129 /*
130  * pqGets[_append]:
131  * get a null-terminated string from the connection,
132  * and store it in an expansible PQExpBuffer.
133  * If we run out of memory, all of the string is still read,
134  * but the excess characters are silently discarded.
135  */
136 static int
137 pqGets_internal(PQExpBuffer buf, PGconn *conn, bool resetbuffer)
138 {
139         /* Copy conn data to locals for faster search loop */
140         char       *inBuffer = conn->inBuffer;
141         int                     inCursor = conn->inCursor;
142         int                     inEnd = conn->inEnd;
143         int                     slen;
144
145         while (inCursor < inEnd && inBuffer[inCursor])
146                 inCursor++;
147
148         if (inCursor >= inEnd)
149                 return EOF;
150
151         slen = inCursor - conn->inCursor;
152
153         if (resetbuffer)
154                 resetPQExpBuffer(buf);
155
156         appendBinaryPQExpBuffer(buf, inBuffer + conn->inCursor, slen);
157
158         conn->inCursor = ++inCursor;
159
160         if (conn->Pfdebug)
161                 fprintf(conn->Pfdebug, "From backend> \"%s\"\n",
162                                 buf->data);
163
164         return 0;
165 }
166
167 int
168 pqGets(PQExpBuffer buf, PGconn *conn)
169 {
170         return pqGets_internal(buf, conn, true);
171 }
172
173 int
174 pqGets_append(PQExpBuffer buf, PGconn *conn)
175 {
176         return pqGets_internal(buf, conn, false);
177 }
178
179
180 /*
181  * pqPuts: write a null-terminated string to the current message
182  */
183 int
184 pqPuts(const char *s, PGconn *conn)
185 {
186         if (pqPutMsgBytes(s, strlen(s) + 1, conn))
187                 return EOF;
188
189         if (conn->Pfdebug)
190                 fprintf(conn->Pfdebug, "To backend> \"%s\"\n", s);
191
192         return 0;
193 }
194
195 /*
196  * pqGetnchar:
197  *      get a string of exactly len bytes in buffer s, no null termination
198  */
199 int
200 pqGetnchar(char *s, size_t len, PGconn *conn)
201 {
202         if (len > (size_t) (conn->inEnd - conn->inCursor))
203                 return EOF;
204
205         memcpy(s, conn->inBuffer + conn->inCursor, len);
206         /* no terminating null */
207
208         conn->inCursor += len;
209
210         if (conn->Pfdebug)
211         {
212                 fprintf(conn->Pfdebug, "From backend (%lu)> ", (unsigned long) len);
213                 fputnbytes(conn->Pfdebug, s, len);
214                 fprintf(conn->Pfdebug, "\n");
215         }
216
217         return 0;
218 }
219
220 /*
221  * pqSkipnchar:
222  *      skip over len bytes in input buffer.
223  *
224  * Note: this is primarily useful for its debug output, which should
225  * be exactly the same as for pqGetnchar.  We assume the data in question
226  * will actually be used, but just isn't getting copied anywhere as yet.
227  */
228 int
229 pqSkipnchar(size_t len, PGconn *conn)
230 {
231         if (len > (size_t) (conn->inEnd - conn->inCursor))
232                 return EOF;
233
234         if (conn->Pfdebug)
235         {
236                 fprintf(conn->Pfdebug, "From backend (%lu)> ", (unsigned long) len);
237                 fputnbytes(conn->Pfdebug, conn->inBuffer + conn->inCursor, len);
238                 fprintf(conn->Pfdebug, "\n");
239         }
240
241         conn->inCursor += len;
242
243         return 0;
244 }
245
246 /*
247  * pqPutnchar:
248  *      write exactly len bytes to the current message
249  */
250 int
251 pqPutnchar(const char *s, size_t len, PGconn *conn)
252 {
253         if (pqPutMsgBytes(s, len, conn))
254                 return EOF;
255
256         if (conn->Pfdebug)
257         {
258                 fprintf(conn->Pfdebug, "To backend> ");
259                 fputnbytes(conn->Pfdebug, s, len);
260                 fprintf(conn->Pfdebug, "\n");
261         }
262
263         return 0;
264 }
265
266 /*
267  * pqGetInt
268  *      read a 2 or 4 byte integer and convert from network byte order
269  *      to local byte order
270  */
271 int
272 pqGetInt(int *result, size_t bytes, PGconn *conn)
273 {
274         uint16          tmp2;
275         uint32          tmp4;
276
277         switch (bytes)
278         {
279                 case 2:
280                         if (conn->inCursor + 2 > conn->inEnd)
281                                 return EOF;
282                         memcpy(&tmp2, conn->inBuffer + conn->inCursor, 2);
283                         conn->inCursor += 2;
284                         *result = (int) ntohs(tmp2);
285                         break;
286                 case 4:
287                         if (conn->inCursor + 4 > conn->inEnd)
288                                 return EOF;
289                         memcpy(&tmp4, conn->inBuffer + conn->inCursor, 4);
290                         conn->inCursor += 4;
291                         *result = (int) ntohl(tmp4);
292                         break;
293                 default:
294                         pqInternalNotice(&conn->noticeHooks,
295                                                          "integer of size %lu not supported by pqGetInt",
296                                                          (unsigned long) bytes);
297                         return EOF;
298         }
299
300         if (conn->Pfdebug)
301                 fprintf(conn->Pfdebug, "From backend (#%lu)> %d\n", (unsigned long) bytes, *result);
302
303         return 0;
304 }
305
306 /*
307  * pqPutInt
308  * write an integer of 2 or 4 bytes, converting from host byte order
309  * to network byte order.
310  */
311 int
312 pqPutInt(int value, size_t bytes, PGconn *conn)
313 {
314         uint16          tmp2;
315         uint32          tmp4;
316
317         switch (bytes)
318         {
319                 case 2:
320                         tmp2 = htons((uint16) value);
321                         if (pqPutMsgBytes((const char *) &tmp2, 2, conn))
322                                 return EOF;
323                         break;
324                 case 4:
325                         tmp4 = htonl((uint32) value);
326                         if (pqPutMsgBytes((const char *) &tmp4, 4, conn))
327                                 return EOF;
328                         break;
329                 default:
330                         pqInternalNotice(&conn->noticeHooks,
331                                                          "integer of size %lu not supported by pqPutInt",
332                                                          (unsigned long) bytes);
333                         return EOF;
334         }
335
336         if (conn->Pfdebug)
337                 fprintf(conn->Pfdebug, "To backend (%lu#)> %d\n", (unsigned long) bytes, value);
338
339         return 0;
340 }
341
342 /*
343  * Make sure conn's output buffer can hold bytes_needed bytes (caller must
344  * include already-stored data into the value!)
345  *
346  * Returns 0 on success, EOF if failed to enlarge buffer
347  */
348 int
349 pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
350 {
351         int                     newsize = conn->outBufSize;
352         char       *newbuf;
353
354         if (bytes_needed <= (size_t) newsize)
355                 return 0;
356
357         /*
358          * If we need to enlarge the buffer, we first try to double it in size; if
359          * that doesn't work, enlarge in multiples of 8K.  This avoids thrashing
360          * the malloc pool by repeated small enlargements.
361          *
362          * Note: tests for newsize > 0 are to catch integer overflow.
363          */
364         do
365         {
366                 newsize *= 2;
367         } while (newsize > 0 && bytes_needed > (size_t) newsize);
368
369         if (newsize > 0 && bytes_needed <= (size_t) newsize)
370         {
371                 newbuf = realloc(conn->outBuffer, newsize);
372                 if (newbuf)
373                 {
374                         /* realloc succeeded */
375                         conn->outBuffer = newbuf;
376                         conn->outBufSize = newsize;
377                         return 0;
378                 }
379         }
380
381         newsize = conn->outBufSize;
382         do
383         {
384                 newsize += 8192;
385         } while (newsize > 0 && bytes_needed > (size_t) newsize);
386
387         if (newsize > 0 && bytes_needed <= (size_t) newsize)
388         {
389                 newbuf = realloc(conn->outBuffer, newsize);
390                 if (newbuf)
391                 {
392                         /* realloc succeeded */
393                         conn->outBuffer = newbuf;
394                         conn->outBufSize = newsize;
395                         return 0;
396                 }
397         }
398
399         /* realloc failed. Probably out of memory */
400         printfPQExpBuffer(&conn->errorMessage,
401                                           "cannot allocate memory for output buffer\n");
402         return EOF;
403 }
404
405 /*
406  * Make sure conn's input buffer can hold bytes_needed bytes (caller must
407  * include already-stored data into the value!)
408  *
409  * Returns 0 on success, EOF if failed to enlarge buffer
410  */
411 int
412 pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
413 {
414         int                     newsize = conn->inBufSize;
415         char       *newbuf;
416
417         if (bytes_needed <= (size_t) newsize)
418                 return 0;
419
420         /*
421          * If we need to enlarge the buffer, we first try to double it in size; if
422          * that doesn't work, enlarge in multiples of 8K.  This avoids thrashing
423          * the malloc pool by repeated small enlargements.
424          *
425          * Note: tests for newsize > 0 are to catch integer overflow.
426          */
427         do
428         {
429                 newsize *= 2;
430         } while (newsize > 0 && bytes_needed > (size_t) newsize);
431
432         if (newsize > 0 && bytes_needed <= (size_t) newsize)
433         {
434                 newbuf = realloc(conn->inBuffer, newsize);
435                 if (newbuf)
436                 {
437                         /* realloc succeeded */
438                         conn->inBuffer = newbuf;
439                         conn->inBufSize = newsize;
440                         return 0;
441                 }
442         }
443
444         newsize = conn->inBufSize;
445         do
446         {
447                 newsize += 8192;
448         } while (newsize > 0 && bytes_needed > (size_t) newsize);
449
450         if (newsize > 0 && bytes_needed <= (size_t) newsize)
451         {
452                 newbuf = realloc(conn->inBuffer, newsize);
453                 if (newbuf)
454                 {
455                         /* realloc succeeded */
456                         conn->inBuffer = newbuf;
457                         conn->inBufSize = newsize;
458                         return 0;
459                 }
460         }
461
462         /* realloc failed. Probably out of memory */
463         printfPQExpBuffer(&conn->errorMessage,
464                                           "cannot allocate memory for input buffer\n");
465         return EOF;
466 }
467
468 /*
469  * pqPutMsgStart: begin construction of a message to the server
470  *
471  * msg_type is the message type byte, or 0 for a message without type byte
472  * (only startup messages have no type byte)
473  *
474  * force_len forces the message to have a length word; otherwise, we add
475  * a length word if protocol 3.
476  *
477  * Returns 0 on success, EOF on error
478  *
479  * The idea here is that we construct the message in conn->outBuffer,
480  * beginning just past any data already in outBuffer (ie, at
481  * outBuffer+outCount).  We enlarge the buffer as needed to hold the message.
482  * When the message is complete, we fill in the length word (if needed) and
483  * then advance outCount past the message, making it eligible to send.
484  *
485  * The state variable conn->outMsgStart points to the incomplete message's
486  * length word: it is either outCount or outCount+1 depending on whether
487  * there is a type byte.  If we are sending a message without length word
488  * (pre protocol 3.0 only), then outMsgStart is -1.  The state variable
489  * conn->outMsgEnd is the end of the data collected so far.
490  */
491 int
492 pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
493 {
494         int                     lenPos;
495         int                     endPos;
496
497         /* allow room for message type byte */
498         if (msg_type)
499                 endPos = conn->outCount + 1;
500         else
501                 endPos = conn->outCount;
502
503         /* do we want a length word? */
504         if (force_len || PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
505         {
506                 lenPos = endPos;
507                 /* allow room for message length */
508                 endPos += 4;
509         }
510         else
511                 lenPos = -1;
512
513         /* make sure there is room for message header */
514         if (pqCheckOutBufferSpace(endPos, conn))
515                 return EOF;
516         /* okay, save the message type byte if any */
517         if (msg_type)
518                 conn->outBuffer[conn->outCount] = msg_type;
519         /* set up the message pointers */
520         conn->outMsgStart = lenPos;
521         conn->outMsgEnd = endPos;
522         /* length word, if needed, will be filled in by pqPutMsgEnd */
523
524         if (conn->Pfdebug)
525                 fprintf(conn->Pfdebug, "To backend> Msg %c\n",
526                                 msg_type ? msg_type : ' ');
527
528         return 0;
529 }
530
531 /*
532  * pqPutMsgBytes: add bytes to a partially-constructed message
533  *
534  * Returns 0 on success, EOF on error
535  */
536 static int
537 pqPutMsgBytes(const void *buf, size_t len, PGconn *conn)
538 {
539         /* make sure there is room for it */
540         if (pqCheckOutBufferSpace(conn->outMsgEnd + len, conn))
541                 return EOF;
542         /* okay, save the data */
543         memcpy(conn->outBuffer + conn->outMsgEnd, buf, len);
544         conn->outMsgEnd += len;
545         /* no Pfdebug call here, caller should do it */
546         return 0;
547 }
548
549 /*
550  * pqPutMsgEnd: finish constructing a message and possibly send it
551  *
552  * Returns 0 on success, EOF on error
553  *
554  * We don't actually send anything here unless we've accumulated at least
555  * 8K worth of data (the typical size of a pipe buffer on Unix systems).
556  * This avoids sending small partial packets.  The caller must use pqFlush
557  * when it's important to flush all the data out to the server.
558  */
559 int
560 pqPutMsgEnd(PGconn *conn)
561 {
562         if (conn->Pfdebug)
563                 fprintf(conn->Pfdebug, "To backend> Msg complete, length %u\n",
564                                 conn->outMsgEnd - conn->outCount);
565
566         /* Fill in length word if needed */
567         if (conn->outMsgStart >= 0)
568         {
569                 uint32          msgLen = conn->outMsgEnd - conn->outMsgStart;
570
571                 msgLen = htonl(msgLen);
572                 memcpy(conn->outBuffer + conn->outMsgStart, &msgLen, 4);
573         }
574
575         /* Make message eligible to send */
576         conn->outCount = conn->outMsgEnd;
577
578         if (conn->outCount >= 8192)
579         {
580                 int                     toSend = conn->outCount - (conn->outCount % 8192);
581
582                 if (pqSendSome(conn, toSend) < 0)
583                         return EOF;
584                 /* in nonblock mode, don't complain if unable to send it all */
585         }
586
587         return 0;
588 }
589
590 /* ----------
591  * pqReadData: read more data, if any is available
592  * Possible return values:
593  *       1: successfully loaded at least one more byte
594  *       0: no data is presently available, but no error detected
595  *      -1: error detected (including EOF = connection closure);
596  *              conn->errorMessage set
597  * NOTE: callers must not assume that pointers or indexes into conn->inBuffer
598  * remain valid across this call!
599  * ----------
600  */
601 int
602 pqReadData(PGconn *conn)
603 {
604         int                     someread = 0;
605         int                     nread;
606
607         if (conn->sock < 0)
608         {
609                 printfPQExpBuffer(&conn->errorMessage,
610                                                   libpq_gettext("connection not open\n"));
611                 return -1;
612         }
613
614         /* Left-justify any data in the buffer to make room */
615         if (conn->inStart < conn->inEnd)
616         {
617                 if (conn->inStart > 0)
618                 {
619                         memmove(conn->inBuffer, conn->inBuffer + conn->inStart,
620                                         conn->inEnd - conn->inStart);
621                         conn->inEnd -= conn->inStart;
622                         conn->inCursor -= conn->inStart;
623                         conn->inStart = 0;
624                 }
625         }
626         else
627         {
628                 /* buffer is logically empty, reset it */
629                 conn->inStart = conn->inCursor = conn->inEnd = 0;
630         }
631
632         /*
633          * If the buffer is fairly full, enlarge it. We need to be able to enlarge
634          * the buffer in case a single message exceeds the initial buffer size. We
635          * enlarge before filling the buffer entirely so as to avoid asking the
636          * kernel for a partial packet. The magic constant here should be large
637          * enough for a TCP packet or Unix pipe bufferload.  8K is the usual pipe
638          * buffer size, so...
639          */
640         if (conn->inBufSize - conn->inEnd < 8192)
641         {
642                 if (pqCheckInBufferSpace(conn->inEnd + (size_t) 8192, conn))
643                 {
644                         /*
645                          * We don't insist that the enlarge worked, but we need some room
646                          */
647                         if (conn->inBufSize - conn->inEnd < 100)
648                                 return -1;              /* errorMessage already set */
649                 }
650         }
651
652         /* OK, try to read some data */
653 retry3:
654         nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
655                                                   conn->inBufSize - conn->inEnd);
656         if (nread < 0)
657         {
658                 if (SOCK_ERRNO == EINTR)
659                         goto retry3;
660                 /* Some systems return EAGAIN/EWOULDBLOCK for no data */
661 #ifdef EAGAIN
662                 if (SOCK_ERRNO == EAGAIN)
663                         return someread;
664 #endif
665 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
666                 if (SOCK_ERRNO == EWOULDBLOCK)
667                         return someread;
668 #endif
669                 /* We might get ECONNRESET here if using TCP and backend died */
670 #ifdef ECONNRESET
671                 if (SOCK_ERRNO == ECONNRESET)
672                         goto definitelyFailed;
673 #endif
674                 /* pqsecure_read set the error message for us */
675                 return -1;
676         }
677         if (nread > 0)
678         {
679                 conn->inEnd += nread;
680
681                 /*
682                  * Hack to deal with the fact that some kernels will only give us back
683                  * 1 packet per recv() call, even if we asked for more and there is
684                  * more available.      If it looks like we are reading a long message,
685                  * loop back to recv() again immediately, until we run out of data or
686                  * buffer space.  Without this, the block-and-restart behavior of
687                  * libpq's higher levels leads to O(N^2) performance on long messages.
688                  *
689                  * Since we left-justified the data above, conn->inEnd gives the
690                  * amount of data already read in the current message.  We consider
691                  * the message "long" once we have acquired 32k ...
692                  */
693                 if (conn->inEnd > 32768 &&
694                         (conn->inBufSize - conn->inEnd) >= 8192)
695                 {
696                         someread = 1;
697                         goto retry3;
698                 }
699                 return 1;
700         }
701
702         if (someread)
703                 return 1;                               /* got a zero read after successful tries */
704
705         /*
706          * A return value of 0 could mean just that no data is now available, or
707          * it could mean EOF --- that is, the server has closed the connection.
708          * Since we have the socket in nonblock mode, the only way to tell the
709          * difference is to see if select() is saying that the file is ready.
710          * Grumble.  Fortunately, we don't expect this path to be taken much,
711          * since in normal practice we should not be trying to read data unless
712          * the file selected for reading already.
713          *
714          * In SSL mode it's even worse: SSL_read() could say WANT_READ and then
715          * data could arrive before we make the pqReadReady() test.  So we must
716          * play dumb and assume there is more data, relying on the SSL layer to
717          * detect true EOF.
718          */
719
720 #ifdef USE_SSL
721         if (conn->ssl)
722                 return 0;
723 #endif
724
725         switch (pqReadReady(conn))
726         {
727                 case 0:
728                         /* definitely no data available */
729                         return 0;
730                 case 1:
731                         /* ready for read */
732                         break;
733                 default:
734                         printfPQExpBuffer(&conn->errorMessage,
735                                                           libpq_gettext(
736                                                                 "server closed the connection unexpectedly\n"
737                                    "\tThis probably means the server terminated abnormally\n"
738                                                          "\tbefore or while processing the request.\n"));
739                         goto definitelyFailed;
740         }
741
742         /*
743          * Still not sure that it's EOF, because some data could have just
744          * arrived.
745          */
746 retry4:
747         nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
748                                                   conn->inBufSize - conn->inEnd);
749         if (nread < 0)
750         {
751                 if (SOCK_ERRNO == EINTR)
752                         goto retry4;
753                 /* Some systems return EAGAIN/EWOULDBLOCK for no data */
754 #ifdef EAGAIN
755                 if (SOCK_ERRNO == EAGAIN)
756                         return 0;
757 #endif
758 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
759                 if (SOCK_ERRNO == EWOULDBLOCK)
760                         return 0;
761 #endif
762                 /* We might get ECONNRESET here if using TCP and backend died */
763 #ifdef ECONNRESET
764                 if (SOCK_ERRNO == ECONNRESET)
765                         goto definitelyFailed;
766 #endif
767                 /* pqsecure_read set the error message for us */
768                 return -1;
769         }
770         if (nread > 0)
771         {
772                 conn->inEnd += nread;
773                 return 1;
774         }
775
776         /*
777          * OK, we are getting a zero read even though select() says ready. This
778          * means the connection has been closed.  Cope.  Note that errorMessage
779          * has been set already.
780          */
781 definitelyFailed:
782         pqDropConnection(conn);
783         conn->status = CONNECTION_BAD;          /* No more connection to backend */
784         return -1;
785 }
786
787 /*
788  * pqSendSome: send data waiting in the output buffer.
789  *
790  * len is how much to try to send (typically equal to outCount, but may
791  * be less).
792  *
793  * Return 0 on success, -1 on failure and 1 when not all data could be sent
794  * because the socket would block and the connection is non-blocking.
795  */
796 static int
797 pqSendSome(PGconn *conn, int len)
798 {
799         char       *ptr = conn->outBuffer;
800         int                     remaining = conn->outCount;
801         int                     result = 0;
802
803         if (conn->sock < 0)
804         {
805                 printfPQExpBuffer(&conn->errorMessage,
806                                                   libpq_gettext("connection not open\n"));
807                 return -1;
808         }
809
810         /* while there's still data to send */
811         while (len > 0)
812         {
813                 int                     sent;
814
815 #ifndef WIN32
816                 sent = pqsecure_write(conn, ptr, len);
817 #else
818
819                 /*
820                  * Windows can fail on large sends, per KB article Q201213. The
821                  * failure-point appears to be different in different versions of
822                  * Windows, but 64k should always be safe.
823                  */
824                 sent = pqsecure_write(conn, ptr, Min(len, 65536));
825 #endif
826
827                 if (sent < 0)
828                 {
829                         /* Anything except EAGAIN/EWOULDBLOCK/EINTR is trouble */
830                         switch (SOCK_ERRNO)
831                         {
832 #ifdef EAGAIN
833                                 case EAGAIN:
834                                         break;
835 #endif
836 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
837                                 case EWOULDBLOCK:
838                                         break;
839 #endif
840                                 case EINTR:
841                                         continue;
842
843                                 default:
844                                         /* pqsecure_write set the error message for us */
845
846                                         /*
847                                          * We used to close the socket here, but that's a bad idea
848                                          * since there might be unread data waiting (typically, a
849                                          * NOTICE message from the backend telling us it's
850                                          * committing hara-kiri...).  Leave the socket open until
851                                          * pqReadData finds no more data can be read.  But abandon
852                                          * attempt to send data.
853                                          */
854                                         conn->outCount = 0;
855                                         return -1;
856                         }
857                 }
858                 else
859                 {
860                         ptr += sent;
861                         len -= sent;
862                         remaining -= sent;
863                 }
864
865                 if (len > 0)
866                 {
867                         /*
868                          * We didn't send it all, wait till we can send more.
869                          *
870                          * If the connection is in non-blocking mode we don't wait, but
871                          * return 1 to indicate that data is still pending.
872                          */
873                         if (pqIsnonblocking(conn))
874                         {
875                                 result = 1;
876                                 break;
877                         }
878
879                         /*
880                          * There are scenarios in which we can't send data because the
881                          * communications channel is full, but we cannot expect the server
882                          * to clear the channel eventually because it's blocked trying to
883                          * send data to us.  (This can happen when we are sending a large
884                          * amount of COPY data, and the server has generated lots of
885                          * NOTICE responses.)  To avoid a deadlock situation, we must be
886                          * prepared to accept and buffer incoming data before we try
887                          * again.  Furthermore, it is possible that such incoming data
888                          * might not arrive until after we've gone to sleep.  Therefore,
889                          * we wait for either read ready or write ready.
890                          */
891                         if (pqReadData(conn) < 0)
892                         {
893                                 result = -1;    /* error message already set up */
894                                 break;
895                         }
896                         if (pqWait(TRUE, TRUE, conn))
897                         {
898                                 result = -1;
899                                 break;
900                         }
901                 }
902         }
903
904         /* shift the remaining contents of the buffer */
905         if (remaining > 0)
906                 memmove(conn->outBuffer, ptr, remaining);
907         conn->outCount = remaining;
908
909         return result;
910 }
911
912
913 /*
914  * pqFlush: send any data waiting in the output buffer
915  *
916  * Return 0 on success, -1 on failure and 1 when not all data could be sent
917  * because the socket would block and the connection is non-blocking.
918  */
919 int
920 pqFlush(PGconn *conn)
921 {
922         if (conn->Pfdebug)
923                 fflush(conn->Pfdebug);
924
925         if (conn->outCount > 0)
926                 return pqSendSome(conn, conn->outCount);
927
928         return 0;
929 }
930
931
932 /*
933  * pqWait: wait until we can read or write the connection socket
934  *
935  * JAB: If SSL enabled and used and forRead, buffered bytes short-circuit the
936  * call to select().
937  *
938  * We also stop waiting and return if the kernel flags an exception condition
939  * on the socket.  The actual error condition will be detected and reported
940  * when the caller tries to read or write the socket.
941  */
942 int
943 pqWait(int forRead, int forWrite, PGconn *conn)
944 {
945         return pqWaitTimed(forRead, forWrite, conn, (time_t) -1);
946 }
947
948 /*
949  * pqWaitTimed: wait, but not past finish_time.
950  *
951  * If finish_time is exceeded then we return failure (EOF).  This is like
952  * the response for a kernel exception because we don't want the caller
953  * to try to read/write in that case.
954  *
955  * finish_time = ((time_t) -1) disables the wait limit.
956  */
957 int
958 pqWaitTimed(int forRead, int forWrite, PGconn *conn, time_t finish_time)
959 {
960         int                     result;
961
962         result = pqSocketCheck(conn, forRead, forWrite, finish_time);
963
964         if (result < 0)
965                 return EOF;                             /* errorMessage is already set */
966
967         if (result == 0)
968         {
969                 printfPQExpBuffer(&conn->errorMessage,
970                                                   libpq_gettext("timeout expired\n"));
971                 return EOF;
972         }
973
974         return 0;
975 }
976
977 /*
978  * pqReadReady: is select() saying the file is ready to read?
979  * Returns -1 on failure, 0 if not ready, 1 if ready.
980  */
981 int
982 pqReadReady(PGconn *conn)
983 {
984         return pqSocketCheck(conn, 1, 0, (time_t) 0);
985 }
986
987 /*
988  * pqWriteReady: is select() saying the file is ready to write?
989  * Returns -1 on failure, 0 if not ready, 1 if ready.
990  */
991 int
992 pqWriteReady(PGconn *conn)
993 {
994         return pqSocketCheck(conn, 0, 1, (time_t) 0);
995 }
996
997 /*
998  * Checks a socket, using poll or select, for data to be read, written,
999  * or both.  Returns >0 if one or more conditions are met, 0 if it timed
1000  * out, -1 if an error occurred.
1001  *
1002  * If SSL is in use, the SSL buffer is checked prior to checking the socket
1003  * for read data directly.
1004  */
1005 static int
1006 pqSocketCheck(PGconn *conn, int forRead, int forWrite, time_t end_time)
1007 {
1008         int                     result;
1009
1010         if (!conn)
1011                 return -1;
1012         if (conn->sock < 0)
1013         {
1014                 printfPQExpBuffer(&conn->errorMessage,
1015                                                   libpq_gettext("socket not open\n"));
1016                 return -1;
1017         }
1018
1019 #ifdef USE_SSL
1020         /* Check for SSL library buffering read bytes */
1021         if (forRead && conn->ssl && SSL_pending(conn->ssl) > 0)
1022         {
1023                 /* short-circuit the select */
1024                 return 1;
1025         }
1026 #endif
1027
1028         /* We will retry as long as we get EINTR */
1029         do
1030                 result = pqSocketPoll(conn->sock, forRead, forWrite, end_time);
1031         while (result < 0 && SOCK_ERRNO == EINTR);
1032
1033         if (result < 0)
1034         {
1035                 char            sebuf[256];
1036
1037                 printfPQExpBuffer(&conn->errorMessage,
1038                                                   libpq_gettext("select() failed: %s\n"),
1039                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1040         }
1041
1042         return result;
1043 }
1044
1045
1046 /*
1047  * Check a file descriptor for read and/or write data, possibly waiting.
1048  * If neither forRead nor forWrite are set, immediately return a timeout
1049  * condition (without waiting).  Return >0 if condition is met, 0
1050  * if a timeout occurred, -1 if an error or interrupt occurred.
1051  *
1052  * Timeout is infinite if end_time is -1.  Timeout is immediate (no blocking)
1053  * if end_time is 0 (or indeed, any time before now).
1054  */
1055 static int
1056 pqSocketPoll(int sock, int forRead, int forWrite, time_t end_time)
1057 {
1058         /* We use poll(2) if available, otherwise select(2) */
1059 #ifdef HAVE_POLL
1060         struct pollfd input_fd;
1061         int                     timeout_ms;
1062
1063         if (!forRead && !forWrite)
1064                 return 0;
1065
1066         input_fd.fd = sock;
1067         input_fd.events = POLLERR;
1068         input_fd.revents = 0;
1069
1070         if (forRead)
1071                 input_fd.events |= POLLIN;
1072         if (forWrite)
1073                 input_fd.events |= POLLOUT;
1074
1075         /* Compute appropriate timeout interval */
1076         if (end_time == ((time_t) -1))
1077                 timeout_ms = -1;
1078         else
1079         {
1080                 time_t          now = time(NULL);
1081
1082                 if (end_time > now)
1083                         timeout_ms = (end_time - now) * 1000;
1084                 else
1085                         timeout_ms = 0;
1086         }
1087
1088         return poll(&input_fd, 1, timeout_ms);
1089 #else                                                   /* !HAVE_POLL */
1090
1091         fd_set          input_mask;
1092         fd_set          output_mask;
1093         fd_set          except_mask;
1094         struct timeval timeout;
1095         struct timeval *ptr_timeout;
1096
1097         if (!forRead && !forWrite)
1098                 return 0;
1099
1100         FD_ZERO(&input_mask);
1101         FD_ZERO(&output_mask);
1102         FD_ZERO(&except_mask);
1103         if (forRead)
1104                 FD_SET(sock, &input_mask);
1105
1106         if (forWrite)
1107                 FD_SET(sock, &output_mask);
1108         FD_SET(sock, &except_mask);
1109
1110         /* Compute appropriate timeout interval */
1111         if (end_time == ((time_t) -1))
1112                 ptr_timeout = NULL;
1113         else
1114         {
1115                 time_t          now = time(NULL);
1116
1117                 if (end_time > now)
1118                         timeout.tv_sec = end_time - now;
1119                 else
1120                         timeout.tv_sec = 0;
1121                 timeout.tv_usec = 0;
1122                 ptr_timeout = &timeout;
1123         }
1124
1125         return select(sock + 1, &input_mask, &output_mask,
1126                                   &except_mask, ptr_timeout);
1127 #endif   /* HAVE_POLL */
1128 }
1129
1130
1131 /*
1132  * A couple of "miscellaneous" multibyte related functions. They used
1133  * to be in fe-print.c but that file is doomed.
1134  */
1135
1136 /*
1137  * returns the byte length of the word beginning s, using the
1138  * specified encoding.
1139  */
1140 int
1141 PQmblen(const char *s, int encoding)
1142 {
1143         return pg_encoding_mblen(encoding, s);
1144 }
1145
1146 /*
1147  * returns the display length of the word beginning s, using the
1148  * specified encoding.
1149  */
1150 int
1151 PQdsplen(const char *s, int encoding)
1152 {
1153         return pg_encoding_dsplen(encoding, s);
1154 }
1155
1156 /*
1157  * Get encoding id from environment variable PGCLIENTENCODING.
1158  */
1159 int
1160 PQenv2encoding(void)
1161 {
1162         char       *str;
1163         int                     encoding = PG_SQL_ASCII;
1164
1165         str = getenv("PGCLIENTENCODING");
1166         if (str && *str != '\0')
1167         {
1168                 encoding = pg_char_to_encoding(str);
1169                 if (encoding < 0)
1170                         encoding = PG_SQL_ASCII;
1171         }
1172         return encoding;
1173 }
1174
1175
1176 #ifdef ENABLE_NLS
1177
1178 char *
1179 libpq_gettext(const char *msgid)
1180 {
1181         static bool already_bound = false;
1182
1183         if (!already_bound)
1184         {
1185                 /* dgettext() preserves errno, but bindtextdomain() doesn't */
1186 #ifdef WIN32
1187                 int                     save_errno = GetLastError();
1188 #else
1189                 int                     save_errno = errno;
1190 #endif
1191                 const char *ldir;
1192
1193                 already_bound = true;
1194                 /* No relocatable lookup here because the binary could be anywhere */
1195                 ldir = getenv("PGLOCALEDIR");
1196                 if (!ldir)
1197                         ldir = LOCALEDIR;
1198                 bindtextdomain(PG_TEXTDOMAIN("libpq"), ldir);
1199 #ifdef WIN32
1200                 SetLastError(save_errno);
1201 #else
1202                 errno = save_errno;
1203 #endif
1204         }
1205
1206         return dgettext(PG_TEXTDOMAIN("libpq"), msgid);
1207 }
1208
1209 #endif   /* ENABLE_NLS */