1 /*-------------------------------------------------------------------------
7 * miscellaneous useful functions
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.
15 * XXX: MOVE DEBUG PRINTOUT TO HIGHER LEVEL. As is, block and restart
16 * will cause repeat printouts.
18 * We must speak the same transmitted data representations as the backend
22 * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
23 * Portions Copyright (c) 1994, Regents of the University of California
26 * src/interfaces/libpq/fe-misc.c
28 *-------------------------------------------------------------------------
31 #include "postgres_fe.h"
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
49 #ifdef HAVE_SYS_POLL_H
52 #ifdef HAVE_SYS_SELECT_H
53 #include <sys/select.h>
57 #include "libpq-int.h"
58 #include "mb/pg_wchar.h"
59 #include "pg_config_paths.h"
62 static int pqPutMsgBytes(const void *buf, size_t len, PGconn *conn);
63 static int pqSendSome(PGconn *conn, int len);
64 static int pqSocketCheck(PGconn *conn, int forRead, int forWrite,
66 static int pqSocketPoll(int sock, int forRead, int forWrite, time_t end_time);
69 * PQlibVersion: return the libpq version number
74 return PG_VERSION_NUM;
78 * fputnbytes: print exactly N bytes to a file
80 * We avoid using %.*s here because it can misbehave if the data
81 * is not valid in what libc thinks is the prevailing encoding.
84 fputnbytes(FILE *f, const char *str, size_t n)
92 * pqGetc: get 1 character from the connection
94 * All these routines return 0 on success, EOF on error.
95 * Note that for the Get routines, EOF only means there is not enough
96 * data in the buffer, not that there is necessarily a hard error.
99 pqGetc(char *result, PGconn *conn)
101 if (conn->inCursor >= conn->inEnd)
104 *result = conn->inBuffer[conn->inCursor++];
107 fprintf(conn->Pfdebug, "From backend> %c\n", *result);
114 * pqPutc: write 1 char to the current message
117 pqPutc(char c, PGconn *conn)
119 if (pqPutMsgBytes(&c, 1, conn))
123 fprintf(conn->Pfdebug, "To backend> %c\n", c);
131 * get a null-terminated string from the connection,
132 * and store it in an expansible PQExpBuffer.
133 * If we run out of memory, all of the string is still read,
134 * but the excess characters are silently discarded.
137 pqGets_internal(PQExpBuffer buf, PGconn *conn, bool resetbuffer)
139 /* Copy conn data to locals for faster search loop */
140 char *inBuffer = conn->inBuffer;
141 int inCursor = conn->inCursor;
142 int inEnd = conn->inEnd;
145 while (inCursor < inEnd && inBuffer[inCursor])
148 if (inCursor >= inEnd)
151 slen = inCursor - conn->inCursor;
154 resetPQExpBuffer(buf);
156 appendBinaryPQExpBuffer(buf, inBuffer + conn->inCursor, slen);
158 conn->inCursor = ++inCursor;
161 fprintf(conn->Pfdebug, "From backend> \"%s\"\n",
168 pqGets(PQExpBuffer buf, PGconn *conn)
170 return pqGets_internal(buf, conn, true);
174 pqGets_append(PQExpBuffer buf, PGconn *conn)
176 return pqGets_internal(buf, conn, false);
181 * pqPuts: write a null-terminated string to the current message
184 pqPuts(const char *s, PGconn *conn)
186 if (pqPutMsgBytes(s, strlen(s) + 1, conn))
190 fprintf(conn->Pfdebug, "To backend> \"%s\"\n", s);
197 * get a string of exactly len bytes in buffer s, no null termination
200 pqGetnchar(char *s, size_t len, PGconn *conn)
202 if (len > (size_t) (conn->inEnd - conn->inCursor))
205 memcpy(s, conn->inBuffer + conn->inCursor, len);
206 /* no terminating null */
208 conn->inCursor += len;
212 fprintf(conn->Pfdebug, "From backend (%lu)> ", (unsigned long) len);
213 fputnbytes(conn->Pfdebug, s, len);
214 fprintf(conn->Pfdebug, "\n");
222 * skip over len bytes in input buffer.
224 * Note: this is primarily useful for its debug output, which should
225 * be exactly the same as for pqGetnchar. We assume the data in question
226 * will actually be used, but just isn't getting copied anywhere as yet.
229 pqSkipnchar(size_t len, PGconn *conn)
231 if (len > (size_t) (conn->inEnd - conn->inCursor))
236 fprintf(conn->Pfdebug, "From backend (%lu)> ", (unsigned long) len);
237 fputnbytes(conn->Pfdebug, conn->inBuffer + conn->inCursor, len);
238 fprintf(conn->Pfdebug, "\n");
241 conn->inCursor += len;
248 * write exactly len bytes to the current message
251 pqPutnchar(const char *s, size_t len, PGconn *conn)
253 if (pqPutMsgBytes(s, len, conn))
258 fprintf(conn->Pfdebug, "To backend> ");
259 fputnbytes(conn->Pfdebug, s, len);
260 fprintf(conn->Pfdebug, "\n");
268 * read a 2 or 4 byte integer and convert from network byte order
269 * to local byte order
272 pqGetInt(int *result, size_t bytes, PGconn *conn)
280 if (conn->inCursor + 2 > conn->inEnd)
282 memcpy(&tmp2, conn->inBuffer + conn->inCursor, 2);
284 *result = (int) ntohs(tmp2);
287 if (conn->inCursor + 4 > conn->inEnd)
289 memcpy(&tmp4, conn->inBuffer + conn->inCursor, 4);
291 *result = (int) ntohl(tmp4);
294 pqInternalNotice(&conn->noticeHooks,
295 "integer of size %lu not supported by pqGetInt",
296 (unsigned long) bytes);
301 fprintf(conn->Pfdebug, "From backend (#%lu)> %d\n", (unsigned long) bytes, *result);
308 * write an integer of 2 or 4 bytes, converting from host byte order
309 * to network byte order.
312 pqPutInt(int value, size_t bytes, PGconn *conn)
320 tmp2 = htons((uint16) value);
321 if (pqPutMsgBytes((const char *) &tmp2, 2, conn))
325 tmp4 = htonl((uint32) value);
326 if (pqPutMsgBytes((const char *) &tmp4, 4, conn))
330 pqInternalNotice(&conn->noticeHooks,
331 "integer of size %lu not supported by pqPutInt",
332 (unsigned long) bytes);
337 fprintf(conn->Pfdebug, "To backend (%lu#)> %d\n", (unsigned long) bytes, value);
343 * Make sure conn's output buffer can hold bytes_needed bytes (caller must
344 * include already-stored data into the value!)
346 * Returns 0 on success, EOF if failed to enlarge buffer
349 pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
351 int newsize = conn->outBufSize;
354 /* Quick exit if we have enough space */
355 if (bytes_needed <= (size_t) newsize)
359 * If we need to enlarge the buffer, we first try to double it in size; if
360 * that doesn't work, enlarge in multiples of 8K. This avoids thrashing
361 * the malloc pool by repeated small enlargements.
363 * Note: tests for newsize > 0 are to catch integer overflow.
368 } while (newsize > 0 && bytes_needed > (size_t) newsize);
370 if (newsize > 0 && bytes_needed <= (size_t) newsize)
372 newbuf = realloc(conn->outBuffer, newsize);
375 /* realloc succeeded */
376 conn->outBuffer = newbuf;
377 conn->outBufSize = newsize;
382 newsize = conn->outBufSize;
386 } while (newsize > 0 && bytes_needed > (size_t) newsize);
388 if (newsize > 0 && bytes_needed <= (size_t) newsize)
390 newbuf = realloc(conn->outBuffer, newsize);
393 /* realloc succeeded */
394 conn->outBuffer = newbuf;
395 conn->outBufSize = newsize;
400 /* realloc failed. Probably out of memory */
401 printfPQExpBuffer(&conn->errorMessage,
402 "cannot allocate memory for output buffer\n");
407 * Make sure conn's input buffer can hold bytes_needed bytes (caller must
408 * include already-stored data into the value!)
410 * Returns 0 on success, EOF if failed to enlarge buffer
413 pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
415 int newsize = conn->inBufSize;
418 /* Quick exit if we have enough space */
419 if (bytes_needed <= (size_t) newsize)
423 * Before concluding that we need to enlarge the buffer, left-justify
424 * whatever is in it and recheck. The caller's value of bytes_needed
425 * includes any data to the left of inStart, but we can delete that in
426 * preference to enlarging the buffer. It's slightly ugly to have this
427 * function do this, but it's better than making callers worry about it.
429 bytes_needed -= conn->inStart;
431 if (conn->inStart < conn->inEnd)
433 if (conn->inStart > 0)
435 memmove(conn->inBuffer, conn->inBuffer + conn->inStart,
436 conn->inEnd - conn->inStart);
437 conn->inEnd -= conn->inStart;
438 conn->inCursor -= conn->inStart;
444 /* buffer is logically empty, reset it */
445 conn->inStart = conn->inCursor = conn->inEnd = 0;
448 /* Recheck whether we have enough space */
449 if (bytes_needed <= (size_t) newsize)
453 * If we need to enlarge the buffer, we first try to double it in size; if
454 * that doesn't work, enlarge in multiples of 8K. This avoids thrashing
455 * the malloc pool by repeated small enlargements.
457 * Note: tests for newsize > 0 are to catch integer overflow.
462 } while (newsize > 0 && bytes_needed > (size_t) newsize);
464 if (newsize > 0 && bytes_needed <= (size_t) newsize)
466 newbuf = realloc(conn->inBuffer, newsize);
469 /* realloc succeeded */
470 conn->inBuffer = newbuf;
471 conn->inBufSize = newsize;
476 newsize = conn->inBufSize;
480 } while (newsize > 0 && bytes_needed > (size_t) newsize);
482 if (newsize > 0 && bytes_needed <= (size_t) newsize)
484 newbuf = realloc(conn->inBuffer, newsize);
487 /* realloc succeeded */
488 conn->inBuffer = newbuf;
489 conn->inBufSize = newsize;
494 /* realloc failed. Probably out of memory */
495 printfPQExpBuffer(&conn->errorMessage,
496 "cannot allocate memory for input buffer\n");
501 * pqPutMsgStart: begin construction of a message to the server
503 * msg_type is the message type byte, or 0 for a message without type byte
504 * (only startup messages have no type byte)
506 * force_len forces the message to have a length word; otherwise, we add
507 * a length word if protocol 3.
509 * Returns 0 on success, EOF on error
511 * The idea here is that we construct the message in conn->outBuffer,
512 * beginning just past any data already in outBuffer (ie, at
513 * outBuffer+outCount). We enlarge the buffer as needed to hold the message.
514 * When the message is complete, we fill in the length word (if needed) and
515 * then advance outCount past the message, making it eligible to send.
517 * The state variable conn->outMsgStart points to the incomplete message's
518 * length word: it is either outCount or outCount+1 depending on whether
519 * there is a type byte. If we are sending a message without length word
520 * (pre protocol 3.0 only), then outMsgStart is -1. The state variable
521 * conn->outMsgEnd is the end of the data collected so far.
524 pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
529 /* allow room for message type byte */
531 endPos = conn->outCount + 1;
533 endPos = conn->outCount;
535 /* do we want a length word? */
536 if (force_len || PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
539 /* allow room for message length */
545 /* make sure there is room for message header */
546 if (pqCheckOutBufferSpace(endPos, conn))
548 /* okay, save the message type byte if any */
550 conn->outBuffer[conn->outCount] = msg_type;
551 /* set up the message pointers */
552 conn->outMsgStart = lenPos;
553 conn->outMsgEnd = endPos;
554 /* length word, if needed, will be filled in by pqPutMsgEnd */
557 fprintf(conn->Pfdebug, "To backend> Msg %c\n",
558 msg_type ? msg_type : ' ');
564 * pqPutMsgBytes: add bytes to a partially-constructed message
566 * Returns 0 on success, EOF on error
569 pqPutMsgBytes(const void *buf, size_t len, PGconn *conn)
571 /* make sure there is room for it */
572 if (pqCheckOutBufferSpace(conn->outMsgEnd + len, conn))
574 /* okay, save the data */
575 memcpy(conn->outBuffer + conn->outMsgEnd, buf, len);
576 conn->outMsgEnd += len;
577 /* no Pfdebug call here, caller should do it */
582 * pqPutMsgEnd: finish constructing a message and possibly send it
584 * Returns 0 on success, EOF on error
586 * We don't actually send anything here unless we've accumulated at least
587 * 8K worth of data (the typical size of a pipe buffer on Unix systems).
588 * This avoids sending small partial packets. The caller must use pqFlush
589 * when it's important to flush all the data out to the server.
592 pqPutMsgEnd(PGconn *conn)
595 fprintf(conn->Pfdebug, "To backend> Msg complete, length %u\n",
596 conn->outMsgEnd - conn->outCount);
598 /* Fill in length word if needed */
599 if (conn->outMsgStart >= 0)
601 uint32 msgLen = conn->outMsgEnd - conn->outMsgStart;
603 msgLen = htonl(msgLen);
604 memcpy(conn->outBuffer + conn->outMsgStart, &msgLen, 4);
607 /* Make message eligible to send */
608 conn->outCount = conn->outMsgEnd;
610 if (conn->outCount >= 8192)
612 int toSend = conn->outCount - (conn->outCount % 8192);
614 if (pqSendSome(conn, toSend) < 0)
616 /* in nonblock mode, don't complain if unable to send it all */
623 * pqReadData: read more data, if any is available
624 * Possible return values:
625 * 1: successfully loaded at least one more byte
626 * 0: no data is presently available, but no error detected
627 * -1: error detected (including EOF = connection closure);
628 * conn->errorMessage set
629 * NOTE: callers must not assume that pointers or indexes into conn->inBuffer
630 * remain valid across this call!
634 pqReadData(PGconn *conn)
639 if (conn->sock == PGINVALID_SOCKET)
641 printfPQExpBuffer(&conn->errorMessage,
642 libpq_gettext("connection not open\n"));
646 /* Left-justify any data in the buffer to make room */
647 if (conn->inStart < conn->inEnd)
649 if (conn->inStart > 0)
651 memmove(conn->inBuffer, conn->inBuffer + conn->inStart,
652 conn->inEnd - conn->inStart);
653 conn->inEnd -= conn->inStart;
654 conn->inCursor -= conn->inStart;
660 /* buffer is logically empty, reset it */
661 conn->inStart = conn->inCursor = conn->inEnd = 0;
665 * If the buffer is fairly full, enlarge it. We need to be able to enlarge
666 * the buffer in case a single message exceeds the initial buffer size. We
667 * enlarge before filling the buffer entirely so as to avoid asking the
668 * kernel for a partial packet. The magic constant here should be large
669 * enough for a TCP packet or Unix pipe bufferload. 8K is the usual pipe
672 if (conn->inBufSize - conn->inEnd < 8192)
674 if (pqCheckInBufferSpace(conn->inEnd + (size_t) 8192, conn))
677 * We don't insist that the enlarge worked, but we need some room
679 if (conn->inBufSize - conn->inEnd < 100)
680 return -1; /* errorMessage already set */
684 /* OK, try to read some data */
686 nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
687 conn->inBufSize - conn->inEnd);
690 if (SOCK_ERRNO == EINTR)
692 /* Some systems return EAGAIN/EWOULDBLOCK for no data */
694 if (SOCK_ERRNO == EAGAIN)
697 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
698 if (SOCK_ERRNO == EWOULDBLOCK)
701 /* We might get ECONNRESET here if using TCP and backend died */
703 if (SOCK_ERRNO == ECONNRESET)
704 goto definitelyFailed;
706 /* pqsecure_read set the error message for us */
711 conn->inEnd += nread;
714 * Hack to deal with the fact that some kernels will only give us back
715 * 1 packet per recv() call, even if we asked for more and there is
716 * more available. If it looks like we are reading a long message,
717 * loop back to recv() again immediately, until we run out of data or
718 * buffer space. Without this, the block-and-restart behavior of
719 * libpq's higher levels leads to O(N^2) performance on long messages.
721 * Since we left-justified the data above, conn->inEnd gives the
722 * amount of data already read in the current message. We consider
723 * the message "long" once we have acquired 32k ...
725 if (conn->inEnd > 32768 &&
726 (conn->inBufSize - conn->inEnd) >= 8192)
735 return 1; /* got a zero read after successful tries */
738 * A return value of 0 could mean just that no data is now available, or
739 * it could mean EOF --- that is, the server has closed the connection.
740 * Since we have the socket in nonblock mode, the only way to tell the
741 * difference is to see if select() is saying that the file is ready.
742 * Grumble. Fortunately, we don't expect this path to be taken much,
743 * since in normal practice we should not be trying to read data unless
744 * the file selected for reading already.
746 * In SSL mode it's even worse: SSL_read() could say WANT_READ and then
747 * data could arrive before we make the pqReadReady() test, but the second
748 * SSL_read() could still say WANT_READ because the data received was not
749 * a complete SSL record. So we must play dumb and assume there is more
750 * data, relying on the SSL layer to detect true EOF.
754 if (conn->ssl_in_use)
758 switch (pqReadReady(conn))
761 /* definitely no data available */
767 /* we override pqReadReady's message with something more useful */
772 * Still not sure that it's EOF, because some data could have just
776 nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
777 conn->inBufSize - conn->inEnd);
780 if (SOCK_ERRNO == EINTR)
782 /* Some systems return EAGAIN/EWOULDBLOCK for no data */
784 if (SOCK_ERRNO == EAGAIN)
787 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
788 if (SOCK_ERRNO == EWOULDBLOCK)
791 /* We might get ECONNRESET here if using TCP and backend died */
793 if (SOCK_ERRNO == ECONNRESET)
794 goto definitelyFailed;
796 /* pqsecure_read set the error message for us */
801 conn->inEnd += nread;
806 * OK, we are getting a zero read even though select() says ready. This
807 * means the connection has been closed. Cope.
810 printfPQExpBuffer(&conn->errorMessage,
812 "server closed the connection unexpectedly\n"
813 "\tThis probably means the server terminated abnormally\n"
814 "\tbefore or while processing the request.\n"));
816 /* Come here if lower-level code already set a suitable errorMessage */
818 /* Do *not* drop any already-read data; caller still wants it */
819 pqDropConnection(conn, false);
820 conn->status = CONNECTION_BAD; /* No more connection to backend */
825 * pqSendSome: send data waiting in the output buffer.
827 * len is how much to try to send (typically equal to outCount, but may
830 * Return 0 on success, -1 on failure and 1 when not all data could be sent
831 * because the socket would block and the connection is non-blocking.
834 pqSendSome(PGconn *conn, int len)
836 char *ptr = conn->outBuffer;
837 int remaining = conn->outCount;
840 if (conn->sock == PGINVALID_SOCKET)
842 printfPQExpBuffer(&conn->errorMessage,
843 libpq_gettext("connection not open\n"));
844 /* Discard queued data; no chance it'll ever be sent */
849 /* while there's still data to send */
855 sent = pqsecure_write(conn, ptr, len);
859 * Windows can fail on large sends, per KB article Q201213. The
860 * failure-point appears to be different in different versions of
861 * Windows, but 64k should always be safe.
863 sent = pqsecure_write(conn, ptr, Min(len, 65536));
868 /* Anything except EAGAIN/EWOULDBLOCK/EINTR is trouble */
875 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
883 /* pqsecure_write set the error message for us */
886 * We used to close the socket here, but that's a bad idea
887 * since there might be unread data waiting (typically, a
888 * NOTICE message from the backend telling us it's
889 * committing hara-kiri...). Leave the socket open until
890 * pqReadData finds no more data can be read. But abandon
891 * attempt to send data.
907 * We didn't send it all, wait till we can send more.
909 * There are scenarios in which we can't send data because the
910 * communications channel is full, but we cannot expect the server
911 * to clear the channel eventually because it's blocked trying to
912 * send data to us. (This can happen when we are sending a large
913 * amount of COPY data, and the server has generated lots of
914 * NOTICE responses.) To avoid a deadlock situation, we must be
915 * prepared to accept and buffer incoming data before we try
916 * again. Furthermore, it is possible that such incoming data
917 * might not arrive until after we've gone to sleep. Therefore,
918 * we wait for either read ready or write ready.
920 * In non-blocking mode, we don't wait here directly, but return 1
921 * to indicate that data is still pending. The caller should wait
922 * for both read and write ready conditions, and call
923 * PQconsumeInput() on read ready, but just in case it doesn't, we
924 * call pqReadData() ourselves before returning. That's not
925 * enough if the data has not arrived yet, but it's the best we
926 * can do, and works pretty well in practice. (The documentation
927 * used to say that you only need to wait for write-ready, so
928 * there are still plenty of applications like that out there.)
930 if (pqReadData(conn) < 0)
932 result = -1; /* error message already set up */
936 if (pqIsnonblocking(conn))
942 if (pqWait(TRUE, TRUE, conn))
950 /* shift the remaining contents of the buffer */
952 memmove(conn->outBuffer, ptr, remaining);
953 conn->outCount = remaining;
960 * pqFlush: send any data waiting in the output buffer
962 * Return 0 on success, -1 on failure and 1 when not all data could be sent
963 * because the socket would block and the connection is non-blocking.
966 pqFlush(PGconn *conn)
969 fflush(conn->Pfdebug);
971 if (conn->outCount > 0)
972 return pqSendSome(conn, conn->outCount);
979 * pqWait: wait until we can read or write the connection socket
981 * JAB: If SSL enabled and used and forRead, buffered bytes short-circuit the
984 * We also stop waiting and return if the kernel flags an exception condition
985 * on the socket. The actual error condition will be detected and reported
986 * when the caller tries to read or write the socket.
989 pqWait(int forRead, int forWrite, PGconn *conn)
991 return pqWaitTimed(forRead, forWrite, conn, (time_t) -1);
995 * pqWaitTimed: wait, but not past finish_time.
997 * If finish_time is exceeded then we return failure (EOF). This is like
998 * the response for a kernel exception because we don't want the caller
999 * to try to read/write in that case.
1001 * finish_time = ((time_t) -1) disables the wait limit.
1004 pqWaitTimed(int forRead, int forWrite, PGconn *conn, time_t finish_time)
1008 result = pqSocketCheck(conn, forRead, forWrite, finish_time);
1011 return EOF; /* errorMessage is already set */
1015 printfPQExpBuffer(&conn->errorMessage,
1016 libpq_gettext("timeout expired\n"));
1024 * pqReadReady: is select() saying the file is ready to read?
1025 * Returns -1 on failure, 0 if not ready, 1 if ready.
1028 pqReadReady(PGconn *conn)
1030 return pqSocketCheck(conn, 1, 0, (time_t) 0);
1034 * pqWriteReady: is select() saying the file is ready to write?
1035 * Returns -1 on failure, 0 if not ready, 1 if ready.
1038 pqWriteReady(PGconn *conn)
1040 return pqSocketCheck(conn, 0, 1, (time_t) 0);
1044 * Checks a socket, using poll or select, for data to be read, written,
1045 * or both. Returns >0 if one or more conditions are met, 0 if it timed
1046 * out, -1 if an error occurred.
1048 * If SSL is in use, the SSL buffer is checked prior to checking the socket
1049 * for read data directly.
1052 pqSocketCheck(PGconn *conn, int forRead, int forWrite, time_t end_time)
1058 if (conn->sock == PGINVALID_SOCKET)
1060 printfPQExpBuffer(&conn->errorMessage,
1061 libpq_gettext("socket not open\n"));
1066 /* Check for SSL library buffering read bytes */
1067 if (forRead && conn->ssl_in_use && pgtls_read_pending(conn) > 0)
1069 /* short-circuit the select */
1074 /* We will retry as long as we get EINTR */
1076 result = pqSocketPoll(conn->sock, forRead, forWrite, end_time);
1077 while (result < 0 && SOCK_ERRNO == EINTR);
1083 printfPQExpBuffer(&conn->errorMessage,
1084 libpq_gettext("select() failed: %s\n"),
1085 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1093 * Check a file descriptor for read and/or write data, possibly waiting.
1094 * If neither forRead nor forWrite are set, immediately return a timeout
1095 * condition (without waiting). Return >0 if condition is met, 0
1096 * if a timeout occurred, -1 if an error or interrupt occurred.
1098 * Timeout is infinite if end_time is -1. Timeout is immediate (no blocking)
1099 * if end_time is 0 (or indeed, any time before now).
1102 pqSocketPoll(int sock, int forRead, int forWrite, time_t end_time)
1104 /* We use poll(2) if available, otherwise select(2) */
1106 struct pollfd input_fd;
1109 if (!forRead && !forWrite)
1113 input_fd.events = POLLERR;
1114 input_fd.revents = 0;
1117 input_fd.events |= POLLIN;
1119 input_fd.events |= POLLOUT;
1121 /* Compute appropriate timeout interval */
1122 if (end_time == ((time_t) -1))
1126 time_t now = time(NULL);
1129 timeout_ms = (end_time - now) * 1000;
1134 return poll(&input_fd, 1, timeout_ms);
1135 #else /* !HAVE_POLL */
1140 struct timeval timeout;
1141 struct timeval *ptr_timeout;
1143 if (!forRead && !forWrite)
1146 FD_ZERO(&input_mask);
1147 FD_ZERO(&output_mask);
1148 FD_ZERO(&except_mask);
1150 FD_SET(sock, &input_mask);
1153 FD_SET(sock, &output_mask);
1154 FD_SET(sock, &except_mask);
1156 /* Compute appropriate timeout interval */
1157 if (end_time == ((time_t) -1))
1161 time_t now = time(NULL);
1164 timeout.tv_sec = end_time - now;
1167 timeout.tv_usec = 0;
1168 ptr_timeout = &timeout;
1171 return select(sock + 1, &input_mask, &output_mask,
1172 &except_mask, ptr_timeout);
1173 #endif /* HAVE_POLL */
1178 * A couple of "miscellaneous" multibyte related functions. They used
1179 * to be in fe-print.c but that file is doomed.
1183 * returns the byte length of the word beginning s, using the
1184 * specified encoding.
1187 PQmblen(const char *s, int encoding)
1189 return pg_encoding_mblen(encoding, s);
1193 * returns the display length of the word beginning s, using the
1194 * specified encoding.
1197 PQdsplen(const char *s, int encoding)
1199 return pg_encoding_dsplen(encoding, s);
1203 * Get encoding id from environment variable PGCLIENTENCODING.
1206 PQenv2encoding(void)
1209 int encoding = PG_SQL_ASCII;
1211 str = getenv("PGCLIENTENCODING");
1212 if (str && *str != '\0')
1214 encoding = pg_char_to_encoding(str);
1216 encoding = PG_SQL_ASCII;
1227 static bool already_bound = false;
1231 /* bindtextdomain() does not preserve errno */
1233 int save_errno = GetLastError();
1235 int save_errno = errno;
1239 already_bound = true;
1240 /* No relocatable lookup here because the binary could be anywhere */
1241 ldir = getenv("PGLOCALEDIR");
1244 bindtextdomain(PG_TEXTDOMAIN("libpq"), ldir);
1246 SetLastError(save_errno);
1254 libpq_gettext(const char *msgid)
1257 return dgettext(PG_TEXTDOMAIN("libpq"), msgid);
1261 libpq_ngettext(const char *msgid, const char *msgid_plural, unsigned long n)
1264 return dngettext(PG_TEXTDOMAIN("libpq"), msgid, msgid_plural, n);
1267 #endif /* ENABLE_NLS */