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-2014, 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 if (bytes_needed <= (size_t) newsize)
358 * If we need to enlarge the buffer, we first try to double it in size; if
359 * that doesn't work, enlarge in multiples of 8K. This avoids thrashing
360 * the malloc pool by repeated small enlargements.
362 * Note: tests for newsize > 0 are to catch integer overflow.
367 } while (newsize > 0 && bytes_needed > (size_t) newsize);
369 if (newsize > 0 && bytes_needed <= (size_t) newsize)
371 newbuf = realloc(conn->outBuffer, newsize);
374 /* realloc succeeded */
375 conn->outBuffer = newbuf;
376 conn->outBufSize = newsize;
381 newsize = conn->outBufSize;
385 } while (newsize > 0 && bytes_needed > (size_t) newsize);
387 if (newsize > 0 && bytes_needed <= (size_t) newsize)
389 newbuf = realloc(conn->outBuffer, newsize);
392 /* realloc succeeded */
393 conn->outBuffer = newbuf;
394 conn->outBufSize = newsize;
399 /* realloc failed. Probably out of memory */
400 printfPQExpBuffer(&conn->errorMessage,
401 "cannot allocate memory for output buffer\n");
406 * Make sure conn's input buffer can hold bytes_needed bytes (caller must
407 * include already-stored data into the value!)
409 * Returns 0 on success, EOF if failed to enlarge buffer
412 pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
414 int newsize = conn->inBufSize;
417 if (bytes_needed <= (size_t) newsize)
421 * If we need to enlarge the buffer, we first try to double it in size; if
422 * that doesn't work, enlarge in multiples of 8K. This avoids thrashing
423 * the malloc pool by repeated small enlargements.
425 * Note: tests for newsize > 0 are to catch integer overflow.
430 } while (newsize > 0 && bytes_needed > (size_t) newsize);
432 if (newsize > 0 && bytes_needed <= (size_t) newsize)
434 newbuf = realloc(conn->inBuffer, newsize);
437 /* realloc succeeded */
438 conn->inBuffer = newbuf;
439 conn->inBufSize = newsize;
444 newsize = conn->inBufSize;
448 } while (newsize > 0 && bytes_needed > (size_t) newsize);
450 if (newsize > 0 && bytes_needed <= (size_t) newsize)
452 newbuf = realloc(conn->inBuffer, newsize);
455 /* realloc succeeded */
456 conn->inBuffer = newbuf;
457 conn->inBufSize = newsize;
462 /* realloc failed. Probably out of memory */
463 printfPQExpBuffer(&conn->errorMessage,
464 "cannot allocate memory for input buffer\n");
469 * pqPutMsgStart: begin construction of a message to the server
471 * msg_type is the message type byte, or 0 for a message without type byte
472 * (only startup messages have no type byte)
474 * force_len forces the message to have a length word; otherwise, we add
475 * a length word if protocol 3.
477 * Returns 0 on success, EOF on error
479 * The idea here is that we construct the message in conn->outBuffer,
480 * beginning just past any data already in outBuffer (ie, at
481 * outBuffer+outCount). We enlarge the buffer as needed to hold the message.
482 * When the message is complete, we fill in the length word (if needed) and
483 * then advance outCount past the message, making it eligible to send.
485 * The state variable conn->outMsgStart points to the incomplete message's
486 * length word: it is either outCount or outCount+1 depending on whether
487 * there is a type byte. If we are sending a message without length word
488 * (pre protocol 3.0 only), then outMsgStart is -1. The state variable
489 * conn->outMsgEnd is the end of the data collected so far.
492 pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
497 /* allow room for message type byte */
499 endPos = conn->outCount + 1;
501 endPos = conn->outCount;
503 /* do we want a length word? */
504 if (force_len || PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
507 /* allow room for message length */
513 /* make sure there is room for message header */
514 if (pqCheckOutBufferSpace(endPos, conn))
516 /* okay, save the message type byte if any */
518 conn->outBuffer[conn->outCount] = msg_type;
519 /* set up the message pointers */
520 conn->outMsgStart = lenPos;
521 conn->outMsgEnd = endPos;
522 /* length word, if needed, will be filled in by pqPutMsgEnd */
525 fprintf(conn->Pfdebug, "To backend> Msg %c\n",
526 msg_type ? msg_type : ' ');
532 * pqPutMsgBytes: add bytes to a partially-constructed message
534 * Returns 0 on success, EOF on error
537 pqPutMsgBytes(const void *buf, size_t len, PGconn *conn)
539 /* make sure there is room for it */
540 if (pqCheckOutBufferSpace(conn->outMsgEnd + len, conn))
542 /* okay, save the data */
543 memcpy(conn->outBuffer + conn->outMsgEnd, buf, len);
544 conn->outMsgEnd += len;
545 /* no Pfdebug call here, caller should do it */
550 * pqPutMsgEnd: finish constructing a message and possibly send it
552 * Returns 0 on success, EOF on error
554 * We don't actually send anything here unless we've accumulated at least
555 * 8K worth of data (the typical size of a pipe buffer on Unix systems).
556 * This avoids sending small partial packets. The caller must use pqFlush
557 * when it's important to flush all the data out to the server.
560 pqPutMsgEnd(PGconn *conn)
563 fprintf(conn->Pfdebug, "To backend> Msg complete, length %u\n",
564 conn->outMsgEnd - conn->outCount);
566 /* Fill in length word if needed */
567 if (conn->outMsgStart >= 0)
569 uint32 msgLen = conn->outMsgEnd - conn->outMsgStart;
571 msgLen = htonl(msgLen);
572 memcpy(conn->outBuffer + conn->outMsgStart, &msgLen, 4);
575 /* Make message eligible to send */
576 conn->outCount = conn->outMsgEnd;
578 if (conn->outCount >= 8192)
580 int toSend = conn->outCount - (conn->outCount % 8192);
582 if (pqSendSome(conn, toSend) < 0)
584 /* in nonblock mode, don't complain if unable to send it all */
591 * pqReadData: read more data, if any is available
592 * Possible return values:
593 * 1: successfully loaded at least one more byte
594 * 0: no data is presently available, but no error detected
595 * -1: error detected (including EOF = connection closure);
596 * conn->errorMessage set
597 * NOTE: callers must not assume that pointers or indexes into conn->inBuffer
598 * remain valid across this call!
602 pqReadData(PGconn *conn)
609 printfPQExpBuffer(&conn->errorMessage,
610 libpq_gettext("connection not open\n"));
614 /* Left-justify any data in the buffer to make room */
615 if (conn->inStart < conn->inEnd)
617 if (conn->inStart > 0)
619 memmove(conn->inBuffer, conn->inBuffer + conn->inStart,
620 conn->inEnd - conn->inStart);
621 conn->inEnd -= conn->inStart;
622 conn->inCursor -= conn->inStart;
628 /* buffer is logically empty, reset it */
629 conn->inStart = conn->inCursor = conn->inEnd = 0;
633 * If the buffer is fairly full, enlarge it. We need to be able to enlarge
634 * the buffer in case a single message exceeds the initial buffer size. We
635 * enlarge before filling the buffer entirely so as to avoid asking the
636 * kernel for a partial packet. The magic constant here should be large
637 * enough for a TCP packet or Unix pipe bufferload. 8K is the usual pipe
640 if (conn->inBufSize - conn->inEnd < 8192)
642 if (pqCheckInBufferSpace(conn->inEnd + (size_t) 8192, conn))
645 * We don't insist that the enlarge worked, but we need some room
647 if (conn->inBufSize - conn->inEnd < 100)
648 return -1; /* errorMessage already set */
652 /* OK, try to read some data */
654 nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
655 conn->inBufSize - conn->inEnd);
658 if (SOCK_ERRNO == EINTR)
660 /* Some systems return EAGAIN/EWOULDBLOCK for no data */
662 if (SOCK_ERRNO == EAGAIN)
665 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
666 if (SOCK_ERRNO == EWOULDBLOCK)
669 /* We might get ECONNRESET here if using TCP and backend died */
671 if (SOCK_ERRNO == ECONNRESET)
672 goto definitelyFailed;
674 /* pqsecure_read set the error message for us */
679 conn->inEnd += nread;
682 * Hack to deal with the fact that some kernels will only give us back
683 * 1 packet per recv() call, even if we asked for more and there is
684 * more available. If it looks like we are reading a long message,
685 * loop back to recv() again immediately, until we run out of data or
686 * buffer space. Without this, the block-and-restart behavior of
687 * libpq's higher levels leads to O(N^2) performance on long messages.
689 * Since we left-justified the data above, conn->inEnd gives the
690 * amount of data already read in the current message. We consider
691 * the message "long" once we have acquired 32k ...
693 if (conn->inEnd > 32768 &&
694 (conn->inBufSize - conn->inEnd) >= 8192)
703 return 1; /* got a zero read after successful tries */
706 * A return value of 0 could mean just that no data is now available, or
707 * it could mean EOF --- that is, the server has closed the connection.
708 * Since we have the socket in nonblock mode, the only way to tell the
709 * difference is to see if select() is saying that the file is ready.
710 * Grumble. Fortunately, we don't expect this path to be taken much,
711 * since in normal practice we should not be trying to read data unless
712 * the file selected for reading already.
714 * In SSL mode it's even worse: SSL_read() could say WANT_READ and then
715 * data could arrive before we make the pqReadReady() test. So we must
716 * play dumb and assume there is more data, relying on the SSL layer to
725 switch (pqReadReady(conn))
728 /* definitely no data available */
734 printfPQExpBuffer(&conn->errorMessage,
736 "server closed the connection unexpectedly\n"
737 "\tThis probably means the server terminated abnormally\n"
738 "\tbefore or while processing the request.\n"));
739 goto definitelyFailed;
743 * Still not sure that it's EOF, because some data could have just
747 nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
748 conn->inBufSize - conn->inEnd);
751 if (SOCK_ERRNO == EINTR)
753 /* Some systems return EAGAIN/EWOULDBLOCK for no data */
755 if (SOCK_ERRNO == EAGAIN)
758 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
759 if (SOCK_ERRNO == EWOULDBLOCK)
762 /* We might get ECONNRESET here if using TCP and backend died */
764 if (SOCK_ERRNO == ECONNRESET)
765 goto definitelyFailed;
767 /* pqsecure_read set the error message for us */
772 conn->inEnd += nread;
777 * OK, we are getting a zero read even though select() says ready. This
778 * means the connection has been closed. Cope. Note that errorMessage
779 * has been set already.
782 pqDropConnection(conn);
783 conn->status = CONNECTION_BAD; /* No more connection to backend */
788 * pqSendSome: send data waiting in the output buffer.
790 * len is how much to try to send (typically equal to outCount, but may
793 * Return 0 on success, -1 on failure and 1 when not all data could be sent
794 * because the socket would block and the connection is non-blocking.
797 pqSendSome(PGconn *conn, int len)
799 char *ptr = conn->outBuffer;
800 int remaining = conn->outCount;
805 printfPQExpBuffer(&conn->errorMessage,
806 libpq_gettext("connection not open\n"));
810 /* while there's still data to send */
816 sent = pqsecure_write(conn, ptr, len);
820 * Windows can fail on large sends, per KB article Q201213. The
821 * failure-point appears to be different in different versions of
822 * Windows, but 64k should always be safe.
824 sent = pqsecure_write(conn, ptr, Min(len, 65536));
829 /* Anything except EAGAIN/EWOULDBLOCK/EINTR is trouble */
836 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
844 /* pqsecure_write set the error message for us */
847 * We used to close the socket here, but that's a bad idea
848 * since there might be unread data waiting (typically, a
849 * NOTICE message from the backend telling us it's
850 * committing hara-kiri...). Leave the socket open until
851 * pqReadData finds no more data can be read. But abandon
852 * attempt to send data.
868 * We didn't send it all, wait till we can send more.
870 * If the connection is in non-blocking mode we don't wait, but
871 * return 1 to indicate that data is still pending.
873 if (pqIsnonblocking(conn))
880 * There are scenarios in which we can't send data because the
881 * communications channel is full, but we cannot expect the server
882 * to clear the channel eventually because it's blocked trying to
883 * send data to us. (This can happen when we are sending a large
884 * amount of COPY data, and the server has generated lots of
885 * NOTICE responses.) To avoid a deadlock situation, we must be
886 * prepared to accept and buffer incoming data before we try
887 * again. Furthermore, it is possible that such incoming data
888 * might not arrive until after we've gone to sleep. Therefore,
889 * we wait for either read ready or write ready.
891 if (pqReadData(conn) < 0)
893 result = -1; /* error message already set up */
896 if (pqWait(TRUE, TRUE, conn))
904 /* shift the remaining contents of the buffer */
906 memmove(conn->outBuffer, ptr, remaining);
907 conn->outCount = remaining;
914 * pqFlush: send any data waiting in the output buffer
916 * Return 0 on success, -1 on failure and 1 when not all data could be sent
917 * because the socket would block and the connection is non-blocking.
920 pqFlush(PGconn *conn)
923 fflush(conn->Pfdebug);
925 if (conn->outCount > 0)
926 return pqSendSome(conn, conn->outCount);
933 * pqWait: wait until we can read or write the connection socket
935 * JAB: If SSL enabled and used and forRead, buffered bytes short-circuit the
938 * We also stop waiting and return if the kernel flags an exception condition
939 * on the socket. The actual error condition will be detected and reported
940 * when the caller tries to read or write the socket.
943 pqWait(int forRead, int forWrite, PGconn *conn)
945 return pqWaitTimed(forRead, forWrite, conn, (time_t) -1);
949 * pqWaitTimed: wait, but not past finish_time.
951 * If finish_time is exceeded then we return failure (EOF). This is like
952 * the response for a kernel exception because we don't want the caller
953 * to try to read/write in that case.
955 * finish_time = ((time_t) -1) disables the wait limit.
958 pqWaitTimed(int forRead, int forWrite, PGconn *conn, time_t finish_time)
962 result = pqSocketCheck(conn, forRead, forWrite, finish_time);
965 return EOF; /* errorMessage is already set */
969 printfPQExpBuffer(&conn->errorMessage,
970 libpq_gettext("timeout expired\n"));
978 * pqReadReady: is select() saying the file is ready to read?
979 * Returns -1 on failure, 0 if not ready, 1 if ready.
982 pqReadReady(PGconn *conn)
984 return pqSocketCheck(conn, 1, 0, (time_t) 0);
988 * pqWriteReady: is select() saying the file is ready to write?
989 * Returns -1 on failure, 0 if not ready, 1 if ready.
992 pqWriteReady(PGconn *conn)
994 return pqSocketCheck(conn, 0, 1, (time_t) 0);
998 * Checks a socket, using poll or select, for data to be read, written,
999 * or both. Returns >0 if one or more conditions are met, 0 if it timed
1000 * out, -1 if an error occurred.
1002 * If SSL is in use, the SSL buffer is checked prior to checking the socket
1003 * for read data directly.
1006 pqSocketCheck(PGconn *conn, int forRead, int forWrite, time_t end_time)
1014 printfPQExpBuffer(&conn->errorMessage,
1015 libpq_gettext("socket not open\n"));
1020 /* Check for SSL library buffering read bytes */
1021 if (forRead && conn->ssl && SSL_pending(conn->ssl) > 0)
1023 /* short-circuit the select */
1028 /* We will retry as long as we get EINTR */
1030 result = pqSocketPoll(conn->sock, forRead, forWrite, end_time);
1031 while (result < 0 && SOCK_ERRNO == EINTR);
1037 printfPQExpBuffer(&conn->errorMessage,
1038 libpq_gettext("select() failed: %s\n"),
1039 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1047 * Check a file descriptor for read and/or write data, possibly waiting.
1048 * If neither forRead nor forWrite are set, immediately return a timeout
1049 * condition (without waiting). Return >0 if condition is met, 0
1050 * if a timeout occurred, -1 if an error or interrupt occurred.
1052 * Timeout is infinite if end_time is -1. Timeout is immediate (no blocking)
1053 * if end_time is 0 (or indeed, any time before now).
1056 pqSocketPoll(int sock, int forRead, int forWrite, time_t end_time)
1058 /* We use poll(2) if available, otherwise select(2) */
1060 struct pollfd input_fd;
1063 if (!forRead && !forWrite)
1067 input_fd.events = POLLERR;
1068 input_fd.revents = 0;
1071 input_fd.events |= POLLIN;
1073 input_fd.events |= POLLOUT;
1075 /* Compute appropriate timeout interval */
1076 if (end_time == ((time_t) -1))
1080 time_t now = time(NULL);
1083 timeout_ms = (end_time - now) * 1000;
1088 return poll(&input_fd, 1, timeout_ms);
1089 #else /* !HAVE_POLL */
1094 struct timeval timeout;
1095 struct timeval *ptr_timeout;
1097 if (!forRead && !forWrite)
1100 FD_ZERO(&input_mask);
1101 FD_ZERO(&output_mask);
1102 FD_ZERO(&except_mask);
1104 FD_SET(sock, &input_mask);
1107 FD_SET(sock, &output_mask);
1108 FD_SET(sock, &except_mask);
1110 /* Compute appropriate timeout interval */
1111 if (end_time == ((time_t) -1))
1115 time_t now = time(NULL);
1118 timeout.tv_sec = end_time - now;
1121 timeout.tv_usec = 0;
1122 ptr_timeout = &timeout;
1125 return select(sock + 1, &input_mask, &output_mask,
1126 &except_mask, ptr_timeout);
1127 #endif /* HAVE_POLL */
1132 * A couple of "miscellaneous" multibyte related functions. They used
1133 * to be in fe-print.c but that file is doomed.
1137 * returns the byte length of the word beginning s, using the
1138 * specified encoding.
1141 PQmblen(const char *s, int encoding)
1143 return pg_encoding_mblen(encoding, s);
1147 * returns the display length of the word beginning s, using the
1148 * specified encoding.
1151 PQdsplen(const char *s, int encoding)
1153 return pg_encoding_dsplen(encoding, s);
1157 * Get encoding id from environment variable PGCLIENTENCODING.
1160 PQenv2encoding(void)
1163 int encoding = PG_SQL_ASCII;
1165 str = getenv("PGCLIENTENCODING");
1166 if (str && *str != '\0')
1168 encoding = pg_char_to_encoding(str);
1170 encoding = PG_SQL_ASCII;
1179 libpq_gettext(const char *msgid)
1181 static bool already_bound = false;
1185 /* dgettext() preserves errno, but bindtextdomain() doesn't */
1187 int save_errno = GetLastError();
1189 int save_errno = errno;
1193 already_bound = true;
1194 /* No relocatable lookup here because the binary could be anywhere */
1195 ldir = getenv("PGLOCALEDIR");
1198 bindtextdomain(PG_TEXTDOMAIN("libpq"), ldir);
1200 SetLastError(save_errno);
1206 return dgettext(PG_TEXTDOMAIN("libpq"), msgid);
1209 #endif /* ENABLE_NLS */