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