]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-misc.c
Avoid duplicate definition of LOCALEDIR in pg_config.h, already defined
[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-2006, PostgreSQL Global Development Group
23  * Portions Copyright (c) 1994, Regents of the University of California
24  *
25  * IDENTIFICATION
26  *        $PostgreSQL: pgsql/src/interfaces/libpq/fe-misc.c,v 1.127 2006/05/23 19:28:45 momjian 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 #ifndef WIN32_CLIENT_ONLY
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 #include "pg_config_paths.h"
64
65
66 static int      pqPutMsgBytes(const void *buf, size_t len, PGconn *conn);
67 static int      pqSendSome(PGconn *conn, int len);
68 static int      pqSocketCheck(PGconn *conn, int forRead, int forWrite,
69                           time_t end_time);
70 static int      pqSocketPoll(int sock, int forRead, int forWrite, time_t end_time);
71
72
73 /*
74  * pqGetc: get 1 character from the connection
75  *
76  *      All these routines return 0 on success, EOF on error.
77  *      Note that for the Get routines, EOF only means there is not enough
78  *      data in the buffer, not that there is necessarily a hard error.
79  */
80 int
81 pqGetc(char *result, PGconn *conn)
82 {
83         if (conn->inCursor >= conn->inEnd)
84                 return EOF;
85
86         *result = conn->inBuffer[conn->inCursor++];
87
88         if (conn->Pfdebug)
89                 fprintf(conn->Pfdebug, "From backend> %c\n", *result);
90
91         return 0;
92 }
93
94
95 /*
96  * pqPutc: write 1 char to the current message
97  */
98 int
99 pqPutc(char c, PGconn *conn)
100 {
101         if (pqPutMsgBytes(&c, 1, conn))
102                 return EOF;
103
104         if (conn->Pfdebug)
105                 fprintf(conn->Pfdebug, "To backend> %c\n", c);
106
107         return 0;
108 }
109
110
111 /*
112  * pqGets:
113  * get a null-terminated string from the connection,
114  * and store it in an expansible PQExpBuffer.
115  * If we run out of memory, all of the string is still read,
116  * but the excess characters are silently discarded.
117  */
118 int
119 pqGets(PQExpBuffer buf, PGconn *conn)
120 {
121         /* Copy conn data to locals for faster search loop */
122         char       *inBuffer = conn->inBuffer;
123         int                     inCursor = conn->inCursor;
124         int                     inEnd = conn->inEnd;
125         int                     slen;
126
127         while (inCursor < inEnd && inBuffer[inCursor])
128                 inCursor++;
129
130         if (inCursor >= inEnd)
131                 return EOF;
132
133         slen = inCursor - conn->inCursor;
134
135         resetPQExpBuffer(buf);
136         appendBinaryPQExpBuffer(buf, inBuffer + conn->inCursor, slen);
137
138         conn->inCursor = ++inCursor;
139
140         if (conn->Pfdebug)
141                 fprintf(conn->Pfdebug, "From backend> \"%s\"\n",
142                                 buf->data);
143
144         return 0;
145 }
146
147
148 /*
149  * pqPuts: write a null-terminated string to the current message
150  */
151 int
152 pqPuts(const char *s, PGconn *conn)
153 {
154         if (pqPutMsgBytes(s, strlen(s) + 1, conn))
155                 return EOF;
156
157         if (conn->Pfdebug)
158                 fprintf(conn->Pfdebug, "To backend> \"%s\"\n", s);
159
160         return 0;
161 }
162
163 /*
164  * pqGetnchar:
165  *      get a string of exactly len bytes in buffer s, no null termination
166  */
167 int
168 pqGetnchar(char *s, size_t len, PGconn *conn)
169 {
170         if (len < 0 || len > (size_t) (conn->inEnd - conn->inCursor))
171                 return EOF;
172
173         memcpy(s, conn->inBuffer + conn->inCursor, len);
174         /* no terminating null */
175
176         conn->inCursor += len;
177
178         if (conn->Pfdebug)
179                 fprintf(conn->Pfdebug, "From backend (%lu)> %.*s\n",
180                                 (unsigned long) len, (int) len, s);
181
182         return 0;
183 }
184
185 /*
186  * pqPutnchar:
187  *      write exactly len bytes to the current message
188  */
189 int
190 pqPutnchar(const char *s, size_t len, PGconn *conn)
191 {
192         if (pqPutMsgBytes(s, len, conn))
193                 return EOF;
194
195         if (conn->Pfdebug)
196                 fprintf(conn->Pfdebug, "To backend> %.*s\n", (int) len, s);
197
198         return 0;
199 }
200
201 /*
202  * pqGetInt
203  *      read a 2 or 4 byte integer and convert from network byte order
204  *      to local byte order
205  */
206 int
207 pqGetInt(int *result, size_t bytes, PGconn *conn)
208 {
209         uint16          tmp2;
210         uint32          tmp4;
211
212         switch (bytes)
213         {
214                 case 2:
215                         if (conn->inCursor + 2 > conn->inEnd)
216                                 return EOF;
217                         memcpy(&tmp2, conn->inBuffer + conn->inCursor, 2);
218                         conn->inCursor += 2;
219                         *result = (int) ntohs(tmp2);
220                         break;
221                 case 4:
222                         if (conn->inCursor + 4 > conn->inEnd)
223                                 return EOF;
224                         memcpy(&tmp4, conn->inBuffer + conn->inCursor, 4);
225                         conn->inCursor += 4;
226                         *result = (int) ntohl(tmp4);
227                         break;
228                 default:
229                         pqInternalNotice(&conn->noticeHooks,
230                                                          "integer of size %lu not supported by pqGetInt",
231                                                          (unsigned long) bytes);
232                         return EOF;
233         }
234
235         if (conn->Pfdebug)
236                 fprintf(conn->Pfdebug, "From backend (#%lu)> %d\n", (unsigned long) bytes, *result);
237
238         return 0;
239 }
240
241 /*
242  * pqPutInt
243  * write an integer of 2 or 4 bytes, converting from host byte order
244  * to network byte order.
245  */
246 int
247 pqPutInt(int value, size_t bytes, PGconn *conn)
248 {
249         uint16          tmp2;
250         uint32          tmp4;
251
252         switch (bytes)
253         {
254                 case 2:
255                         tmp2 = htons((uint16) value);
256                         if (pqPutMsgBytes((const char *) &tmp2, 2, conn))
257                                 return EOF;
258                         break;
259                 case 4:
260                         tmp4 = htonl((uint32) value);
261                         if (pqPutMsgBytes((const char *) &tmp4, 4, conn))
262                                 return EOF;
263                         break;
264                 default:
265                         pqInternalNotice(&conn->noticeHooks,
266                                                          "integer of size %lu not supported by pqPutInt",
267                                                          (unsigned long) bytes);
268                         return EOF;
269         }
270
271         if (conn->Pfdebug)
272                 fprintf(conn->Pfdebug, "To backend (%lu#)> %d\n", (unsigned long) bytes, value);
273
274         return 0;
275 }
276
277 /*
278  * Make sure conn's output buffer can hold bytes_needed bytes (caller must
279  * include already-stored data into the value!)
280  *
281  * Returns 0 on success, EOF if failed to enlarge buffer
282  */
283 int
284 pqCheckOutBufferSpace(int bytes_needed, PGconn *conn)
285 {
286         int                     newsize = conn->outBufSize;
287         char       *newbuf;
288
289         if (bytes_needed <= newsize)
290                 return 0;
291
292         /*
293          * If we need to enlarge the buffer, we first try to double it in size; if
294          * that doesn't work, enlarge in multiples of 8K.  This avoids thrashing
295          * the malloc pool by repeated small enlargements.
296          *
297          * Note: tests for newsize > 0 are to catch integer overflow.
298          */
299         do
300         {
301                 newsize *= 2;
302         } while (bytes_needed > newsize && newsize > 0);
303
304         if (bytes_needed <= newsize)
305         {
306                 newbuf = realloc(conn->outBuffer, newsize);
307                 if (newbuf)
308                 {
309                         /* realloc succeeded */
310                         conn->outBuffer = newbuf;
311                         conn->outBufSize = newsize;
312                         return 0;
313                 }
314         }
315
316         newsize = conn->outBufSize;
317         do
318         {
319                 newsize += 8192;
320         } while (bytes_needed > newsize && newsize > 0);
321
322         if (bytes_needed <= newsize)
323         {
324                 newbuf = realloc(conn->outBuffer, newsize);
325                 if (newbuf)
326                 {
327                         /* realloc succeeded */
328                         conn->outBuffer = newbuf;
329                         conn->outBufSize = newsize;
330                         return 0;
331                 }
332         }
333
334         /* realloc failed. Probably out of memory */
335         printfPQExpBuffer(&conn->errorMessage,
336                                           "cannot allocate memory for output buffer\n");
337         return EOF;
338 }
339
340 /*
341  * Make sure conn's input buffer can hold bytes_needed bytes (caller must
342  * include already-stored data into the value!)
343  *
344  * Returns 0 on success, EOF if failed to enlarge buffer
345  */
346 int
347 pqCheckInBufferSpace(int bytes_needed, PGconn *conn)
348 {
349         int                     newsize = conn->inBufSize;
350         char       *newbuf;
351
352         if (bytes_needed <= newsize)
353                 return 0;
354
355         /*
356          * If we need to enlarge the buffer, we first try to double it in size; if
357          * that doesn't work, enlarge in multiples of 8K.  This avoids thrashing
358          * the malloc pool by repeated small enlargements.
359          *
360          * Note: tests for newsize > 0 are to catch integer overflow.
361          */
362         do
363         {
364                 newsize *= 2;
365         } while (bytes_needed > newsize && newsize > 0);
366
367         if (bytes_needed <= newsize)
368         {
369                 newbuf = realloc(conn->inBuffer, newsize);
370                 if (newbuf)
371                 {
372                         /* realloc succeeded */
373                         conn->inBuffer = newbuf;
374                         conn->inBufSize = newsize;
375                         return 0;
376                 }
377         }
378
379         newsize = conn->inBufSize;
380         do
381         {
382                 newsize += 8192;
383         } while (bytes_needed > newsize && newsize > 0);
384
385         if (bytes_needed <= newsize)
386         {
387                 newbuf = realloc(conn->inBuffer, newsize);
388                 if (newbuf)
389                 {
390                         /* realloc succeeded */
391                         conn->inBuffer = newbuf;
392                         conn->inBufSize = newsize;
393                         return 0;
394                 }
395         }
396
397         /* realloc failed. Probably out of memory */
398         printfPQExpBuffer(&conn->errorMessage,
399                                           "cannot allocate memory for input buffer\n");
400         return EOF;
401 }
402
403 /*
404  * pqPutMsgStart: begin construction of a message to the server
405  *
406  * msg_type is the message type byte, or 0 for a message without type byte
407  * (only startup messages have no type byte)
408  *
409  * force_len forces the message to have a length word; otherwise, we add
410  * a length word if protocol 3.
411  *
412  * Returns 0 on success, EOF on error
413  *
414  * The idea here is that we construct the message in conn->outBuffer,
415  * beginning just past any data already in outBuffer (ie, at
416  * outBuffer+outCount).  We enlarge the buffer as needed to hold the message.
417  * When the message is complete, we fill in the length word (if needed) and
418  * then advance outCount past the message, making it eligible to send.
419  *
420  * The state variable conn->outMsgStart points to the incomplete message's
421  * length word: it is either outCount or outCount+1 depending on whether
422  * there is a type byte.  If we are sending a message without length word
423  * (pre protocol 3.0 only), then outMsgStart is -1.  The state variable
424  * conn->outMsgEnd is the end of the data collected so far.
425  */
426 int
427 pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
428 {
429         int                     lenPos;
430         int                     endPos;
431
432         /* allow room for message type byte */
433         if (msg_type)
434                 endPos = conn->outCount + 1;
435         else
436                 endPos = conn->outCount;
437
438         /* do we want a length word? */
439         if (force_len || PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
440         {
441                 lenPos = endPos;
442                 /* allow room for message length */
443                 endPos += 4;
444         }
445         else
446                 lenPos = -1;
447
448         /* make sure there is room for message header */
449         if (pqCheckOutBufferSpace(endPos, conn))
450                 return EOF;
451         /* okay, save the message type byte if any */
452         if (msg_type)
453                 conn->outBuffer[conn->outCount] = msg_type;
454         /* set up the message pointers */
455         conn->outMsgStart = lenPos;
456         conn->outMsgEnd = endPos;
457         /* length word, if needed, will be filled in by pqPutMsgEnd */
458
459         if (conn->Pfdebug)
460                 fprintf(conn->Pfdebug, "To backend> Msg %c\n",
461                                 msg_type ? msg_type : ' ');
462
463         return 0;
464 }
465
466 /*
467  * pqPutMsgBytes: add bytes to a partially-constructed message
468  *
469  * Returns 0 on success, EOF on error
470  */
471 static int
472 pqPutMsgBytes(const void *buf, size_t len, PGconn *conn)
473 {
474         /* make sure there is room for it */
475         if (pqCheckOutBufferSpace(conn->outMsgEnd + len, conn))
476                 return EOF;
477         /* okay, save the data */
478         memcpy(conn->outBuffer + conn->outMsgEnd, buf, len);
479         conn->outMsgEnd += len;
480         /* no Pfdebug call here, caller should do it */
481         return 0;
482 }
483
484 /*
485  * pqPutMsgEnd: finish constructing a message and possibly send it
486  *
487  * Returns 0 on success, EOF on error
488  *
489  * We don't actually send anything here unless we've accumulated at least
490  * 8K worth of data (the typical size of a pipe buffer on Unix systems).
491  * This avoids sending small partial packets.  The caller must use pqFlush
492  * when it's important to flush all the data out to the server.
493  */
494 int
495 pqPutMsgEnd(PGconn *conn)
496 {
497         if (conn->Pfdebug)
498                 fprintf(conn->Pfdebug, "To backend> Msg complete, length %u\n",
499                                 conn->outMsgEnd - conn->outCount);
500
501         /* Fill in length word if needed */
502         if (conn->outMsgStart >= 0)
503         {
504                 uint32          msgLen = conn->outMsgEnd - conn->outMsgStart;
505
506                 msgLen = htonl(msgLen);
507                 memcpy(conn->outBuffer + conn->outMsgStart, &msgLen, 4);
508         }
509
510         /* Make message eligible to send */
511         conn->outCount = conn->outMsgEnd;
512
513         if (conn->outCount >= 8192)
514         {
515                 int                     toSend = conn->outCount - (conn->outCount % 8192);
516
517                 if (pqSendSome(conn, toSend) < 0)
518                         return EOF;
519                 /* in nonblock mode, don't complain if unable to send it all */
520         }
521
522         return 0;
523 }
524
525 /* ----------
526  * pqReadData: read more data, if any is available
527  * Possible return values:
528  *       1: successfully loaded at least one more byte
529  *       0: no data is presently available, but no error detected
530  *      -1: error detected (including EOF = connection closure);
531  *              conn->errorMessage set
532  * NOTE: callers must not assume that pointers or indexes into conn->inBuffer
533  * remain valid across this call!
534  * ----------
535  */
536 int
537 pqReadData(PGconn *conn)
538 {
539         int                     someread = 0;
540         int                     nread;
541         char            sebuf[256];
542
543         if (conn->sock < 0)
544         {
545                 printfPQExpBuffer(&conn->errorMessage,
546                                                   libpq_gettext("connection not open\n"));
547                 return -1;
548         }
549
550         /* Left-justify any data in the buffer to make room */
551         if (conn->inStart < conn->inEnd)
552         {
553                 if (conn->inStart > 0)
554                 {
555                         memmove(conn->inBuffer, conn->inBuffer + conn->inStart,
556                                         conn->inEnd - conn->inStart);
557                         conn->inEnd -= conn->inStart;
558                         conn->inCursor -= conn->inStart;
559                         conn->inStart = 0;
560                 }
561         }
562         else
563         {
564                 /* buffer is logically empty, reset it */
565                 conn->inStart = conn->inCursor = conn->inEnd = 0;
566         }
567
568         /*
569          * If the buffer is fairly full, enlarge it. We need to be able to enlarge
570          * the buffer in case a single message exceeds the initial buffer size. We
571          * enlarge before filling the buffer entirely so as to avoid asking the
572          * kernel for a partial packet. The magic constant here should be large
573          * enough for a TCP packet or Unix pipe bufferload.  8K is the usual pipe
574          * buffer size, so...
575          */
576         if (conn->inBufSize - conn->inEnd < 8192)
577         {
578                 if (pqCheckInBufferSpace(conn->inEnd + 8192, conn))
579                 {
580                         /*
581                          * We don't insist that the enlarge worked, but we need some room
582                          */
583                         if (conn->inBufSize - conn->inEnd < 100)
584                                 return -1;              /* errorMessage already set */
585                 }
586         }
587
588         /* OK, try to read some data */
589 retry3:
590         nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
591                                                   conn->inBufSize - conn->inEnd);
592         if (nread < 0)
593         {
594                 if (SOCK_ERRNO == EINTR)
595                         goto retry3;
596                 /* Some systems return EAGAIN/EWOULDBLOCK for no data */
597 #ifdef EAGAIN
598                 if (SOCK_ERRNO == EAGAIN)
599                         return someread;
600 #endif
601 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
602                 if (SOCK_ERRNO == EWOULDBLOCK)
603                         return someread;
604 #endif
605                 /* We might get ECONNRESET here if using TCP and backend died */
606 #ifdef ECONNRESET
607                 if (SOCK_ERRNO == ECONNRESET)
608                         goto definitelyFailed;
609 #endif
610                 printfPQExpBuffer(&conn->errorMessage,
611                                    libpq_gettext("could not receive data from server: %s\n"),
612                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
613                 return -1;
614         }
615         if (nread > 0)
616         {
617                 conn->inEnd += nread;
618
619                 /*
620                  * Hack to deal with the fact that some kernels will only give us back
621                  * 1 packet per recv() call, even if we asked for more and there is
622                  * more available.      If it looks like we are reading a long message,
623                  * loop back to recv() again immediately, until we run out of data or
624                  * buffer space.  Without this, the block-and-restart behavior of
625                  * libpq's higher levels leads to 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 consider
629                  * 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, or
645          * it could mean EOF --- that is, the server has closed the connection.
646          * Since we have the socket in nonblock mode, the only way to tell the
647          * difference is to see if select() is saying that the file is ready.
648          * Grumble.  Fortunately, we don't expect this path to be taken much,
649          * since in normal practice we should not be trying to read data unless
650          * 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 must
654          * play dumb and assume there is more data, relying on the SSL layer to
655          * 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. This
713          * 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 it's
764                          * EPIPE or ECONNRESET, assume we've lost the backend connection
765                          * 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 idea
792                                          * since there might be unread data waiting (typically, a
793                                          * NOTICE message from the backend telling us it's
794                                          * committing hara-kiri...).  Leave the socket open until
795                                          * pqReadData finds no more data can be read.  But abandon
796                                          * 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 #else                                                   /* !HAVE_POLL */
1042
1043         fd_set          input_mask;
1044         fd_set          output_mask;
1045         fd_set          except_mask;
1046         struct timeval timeout;
1047         struct timeval *ptr_timeout;
1048
1049         if (!forRead && !forWrite)
1050                 return 0;
1051
1052         FD_ZERO(&input_mask);
1053         FD_ZERO(&output_mask);
1054         FD_ZERO(&except_mask);
1055         if (forRead)
1056                 FD_SET(sock, &input_mask);
1057         if (forWrite)
1058                 FD_SET(sock, &output_mask);
1059         FD_SET(sock, &except_mask);
1060
1061         /* Compute appropriate timeout interval */
1062         if (end_time == ((time_t) -1))
1063                 ptr_timeout = NULL;
1064         else
1065         {
1066                 time_t          now = time(NULL);
1067
1068                 if (end_time > now)
1069                         timeout.tv_sec = end_time - now;
1070                 else
1071                         timeout.tv_sec = 0;
1072                 timeout.tv_usec = 0;
1073                 ptr_timeout = &timeout;
1074         }
1075
1076         return select(sock + 1, &input_mask, &output_mask,
1077                                   &except_mask, ptr_timeout);
1078 #endif   /* HAVE_POLL */
1079 }
1080
1081
1082 /*
1083  * A couple of "miscellaneous" multibyte related functions. They used
1084  * to be in fe-print.c but that file is doomed.
1085  */
1086
1087 /*
1088  * returns the byte length of the word beginning s, using the
1089  * specified encoding.
1090  */
1091 int
1092 PQmblen(const char *s, int encoding)
1093 {
1094         return pg_encoding_mblen(encoding, s);
1095 }
1096
1097 /*
1098  * returns the display length of the word beginning s, using the
1099  * specified encoding.
1100  */
1101 int
1102 PQdsplen(const char *s, int encoding)
1103 {
1104         return pg_encoding_dsplen(encoding, s);
1105 }
1106
1107 /*
1108  * Get encoding id from environment variable PGCLIENTENCODING.
1109  */
1110 int
1111 PQenv2encoding(void)
1112 {
1113         char       *str;
1114         int                     encoding = PG_SQL_ASCII;
1115
1116         str = getenv("PGCLIENTENCODING");
1117         if (str && *str != '\0')
1118                 encoding = pg_char_to_encoding(str);
1119         return encoding;
1120 }
1121
1122
1123 #ifdef ENABLE_NLS
1124
1125 char *
1126 libpq_gettext(const char *msgid)
1127 {
1128         static bool already_bound = false;
1129
1130         if (!already_bound)
1131         {
1132                 /* dgettext() preserves errno, but bindtextdomain() doesn't */
1133 #ifdef WIN32
1134                 int                     save_errno = GetLastError();
1135 #else
1136                 int                     save_errno = errno;
1137 #endif
1138                 const char *ldir;
1139
1140                 already_bound = true;
1141                 /* No relocatable lookup here because the binary could be anywhere */
1142                 ldir = getenv("PGLOCALEDIR");
1143                 if (!ldir)
1144                         ldir = LOCALEDIR;
1145                 bindtextdomain("libpq", ldir);
1146 #ifdef WIN32
1147                 SetLastError(save_errno);
1148 #else
1149                 errno = save_errno;
1150 #endif
1151         }
1152
1153         return dgettext("libpq", msgid);
1154 }
1155
1156 #endif   /* ENABLE_NLS */