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