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-2011, 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"
59 #include "mb/pg_wchar.h"
60 #include "pg_config_paths.h"
63 static int pqPutMsgBytes(const void *buf, size_t len, PGconn *conn);
64 static int pqSendSome(PGconn *conn, int len);
65 static int pqSocketCheck(PGconn *conn, int forRead, int forWrite,
67 static int pqSocketPoll(int sock, int forRead, int forWrite, time_t end_time);
70 * PQlibVersion: return the libpq version number
75 return PG_VERSION_NUM;
79 * fputnbytes: print exactly N bytes to a file
81 * We avoid using %.*s here because it can misbehave if the data
82 * is not valid in what libc thinks is the prevailing encoding.
85 fputnbytes(FILE *f, const char *str, size_t n)
93 * pqGetc: get 1 character from the connection
95 * All these routines return 0 on success, EOF on error.
96 * Note that for the Get routines, EOF only means there is not enough
97 * data in the buffer, not that there is necessarily a hard error.
100 pqGetc(char *result, PGconn *conn)
102 if (conn->inCursor >= conn->inEnd)
105 *result = conn->inBuffer[conn->inCursor++];
108 fprintf(conn->Pfdebug, "From backend> %c\n", *result);
115 * pqPutc: write 1 char to the current message
118 pqPutc(char c, PGconn *conn)
120 if (pqPutMsgBytes(&c, 1, conn))
124 fprintf(conn->Pfdebug, "To backend> %c\n", c);
132 * get a null-terminated string from the connection,
133 * and store it in an expansible PQExpBuffer.
134 * If we run out of memory, all of the string is still read,
135 * but the excess characters are silently discarded.
138 pqGets_internal(PQExpBuffer buf, PGconn *conn, bool resetbuffer)
140 /* Copy conn data to locals for faster search loop */
141 char *inBuffer = conn->inBuffer;
142 int inCursor = conn->inCursor;
143 int inEnd = conn->inEnd;
146 while (inCursor < inEnd && inBuffer[inCursor])
149 if (inCursor >= inEnd)
152 slen = inCursor - conn->inCursor;
155 resetPQExpBuffer(buf);
157 appendBinaryPQExpBuffer(buf, inBuffer + conn->inCursor, slen);
159 conn->inCursor = ++inCursor;
162 fprintf(conn->Pfdebug, "From backend> \"%s\"\n",
169 pqGets(PQExpBuffer buf, PGconn *conn)
171 return pqGets_internal(buf, conn, true);
175 pqGets_append(PQExpBuffer buf, PGconn *conn)
177 return pqGets_internal(buf, conn, false);
182 * pqPuts: write a null-terminated string to the current message
185 pqPuts(const char *s, PGconn *conn)
187 if (pqPutMsgBytes(s, strlen(s) + 1, conn))
191 fprintf(conn->Pfdebug, "To backend> \"%s\"\n", s);
198 * get a string of exactly len bytes in buffer s, no null termination
201 pqGetnchar(char *s, size_t len, PGconn *conn)
203 if (len > (size_t) (conn->inEnd - conn->inCursor))
206 memcpy(s, conn->inBuffer + conn->inCursor, len);
207 /* no terminating null */
209 conn->inCursor += len;
213 fprintf(conn->Pfdebug, "From backend (%lu)> ", (unsigned long) len);
214 fputnbytes(conn->Pfdebug, s, len);
215 fprintf(conn->Pfdebug, "\n");
223 * write exactly len bytes to the current message
226 pqPutnchar(const char *s, size_t len, PGconn *conn)
228 if (pqPutMsgBytes(s, len, conn))
233 fprintf(conn->Pfdebug, "To backend> ");
234 fputnbytes(conn->Pfdebug, s, len);
235 fprintf(conn->Pfdebug, "\n");
243 * read a 2 or 4 byte integer and convert from network byte order
244 * to local byte order
247 pqGetInt(int *result, size_t bytes, PGconn *conn)
255 if (conn->inCursor + 2 > conn->inEnd)
257 memcpy(&tmp2, conn->inBuffer + conn->inCursor, 2);
259 *result = (int) ntohs(tmp2);
262 if (conn->inCursor + 4 > conn->inEnd)
264 memcpy(&tmp4, conn->inBuffer + conn->inCursor, 4);
266 *result = (int) ntohl(tmp4);
269 pqInternalNotice(&conn->noticeHooks,
270 "integer of size %lu not supported by pqGetInt",
271 (unsigned long) bytes);
276 fprintf(conn->Pfdebug, "From backend (#%lu)> %d\n", (unsigned long) bytes, *result);
283 * write an integer of 2 or 4 bytes, converting from host byte order
284 * to network byte order.
287 pqPutInt(int value, size_t bytes, PGconn *conn)
295 tmp2 = htons((uint16) value);
296 if (pqPutMsgBytes((const char *) &tmp2, 2, conn))
300 tmp4 = htonl((uint32) value);
301 if (pqPutMsgBytes((const char *) &tmp4, 4, conn))
305 pqInternalNotice(&conn->noticeHooks,
306 "integer of size %lu not supported by pqPutInt",
307 (unsigned long) bytes);
312 fprintf(conn->Pfdebug, "To backend (%lu#)> %d\n", (unsigned long) bytes, value);
318 * Make sure conn's output buffer can hold bytes_needed bytes (caller must
319 * include already-stored data into the value!)
321 * Returns 0 on success, EOF if failed to enlarge buffer
324 pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
326 int newsize = conn->outBufSize;
329 if (bytes_needed <= (size_t) newsize)
333 * If we need to enlarge the buffer, we first try to double it in size; if
334 * that doesn't work, enlarge in multiples of 8K. This avoids thrashing
335 * the malloc pool by repeated small enlargements.
337 * Note: tests for newsize > 0 are to catch integer overflow.
342 } while (newsize > 0 && bytes_needed > (size_t) newsize);
344 if (newsize > 0 && bytes_needed <= (size_t) newsize)
346 newbuf = realloc(conn->outBuffer, newsize);
349 /* realloc succeeded */
350 conn->outBuffer = newbuf;
351 conn->outBufSize = newsize;
356 newsize = conn->outBufSize;
360 } while (newsize > 0 && bytes_needed > (size_t) newsize);
362 if (newsize > 0 && bytes_needed <= (size_t) newsize)
364 newbuf = realloc(conn->outBuffer, newsize);
367 /* realloc succeeded */
368 conn->outBuffer = newbuf;
369 conn->outBufSize = newsize;
374 /* realloc failed. Probably out of memory */
375 printfPQExpBuffer(&conn->errorMessage,
376 "cannot allocate memory for output buffer\n");
381 * Make sure conn's input buffer can hold bytes_needed bytes (caller must
382 * include already-stored data into the value!)
384 * Returns 0 on success, EOF if failed to enlarge buffer
387 pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
389 int newsize = conn->inBufSize;
392 if (bytes_needed <= (size_t) newsize)
396 * If we need to enlarge the buffer, we first try to double it in size; if
397 * that doesn't work, enlarge in multiples of 8K. This avoids thrashing
398 * the malloc pool by repeated small enlargements.
400 * Note: tests for newsize > 0 are to catch integer overflow.
405 } while (newsize > 0 && bytes_needed > (size_t) newsize);
407 if (newsize > 0 && bytes_needed <= (size_t) newsize)
409 newbuf = realloc(conn->inBuffer, newsize);
412 /* realloc succeeded */
413 conn->inBuffer = newbuf;
414 conn->inBufSize = newsize;
419 newsize = conn->inBufSize;
423 } while (newsize > 0 && bytes_needed > (size_t) newsize);
425 if (newsize > 0 && bytes_needed <= (size_t) newsize)
427 newbuf = realloc(conn->inBuffer, newsize);
430 /* realloc succeeded */
431 conn->inBuffer = newbuf;
432 conn->inBufSize = newsize;
437 /* realloc failed. Probably out of memory */
438 printfPQExpBuffer(&conn->errorMessage,
439 "cannot allocate memory for input buffer\n");
444 * pqPutMsgStart: begin construction of a message to the server
446 * msg_type is the message type byte, or 0 for a message without type byte
447 * (only startup messages have no type byte)
449 * force_len forces the message to have a length word; otherwise, we add
450 * a length word if protocol 3.
452 * Returns 0 on success, EOF on error
454 * The idea here is that we construct the message in conn->outBuffer,
455 * beginning just past any data already in outBuffer (ie, at
456 * outBuffer+outCount). We enlarge the buffer as needed to hold the message.
457 * When the message is complete, we fill in the length word (if needed) and
458 * then advance outCount past the message, making it eligible to send.
460 * The state variable conn->outMsgStart points to the incomplete message's
461 * length word: it is either outCount or outCount+1 depending on whether
462 * there is a type byte. If we are sending a message without length word
463 * (pre protocol 3.0 only), then outMsgStart is -1. The state variable
464 * conn->outMsgEnd is the end of the data collected so far.
467 pqPutMsgStart(char msg_type, bool force_len, PGconn *conn)
472 /* allow room for message type byte */
474 endPos = conn->outCount + 1;
476 endPos = conn->outCount;
478 /* do we want a length word? */
479 if (force_len || PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
482 /* allow room for message length */
488 /* make sure there is room for message header */
489 if (pqCheckOutBufferSpace(endPos, conn))
491 /* okay, save the message type byte if any */
493 conn->outBuffer[conn->outCount] = msg_type;
494 /* set up the message pointers */
495 conn->outMsgStart = lenPos;
496 conn->outMsgEnd = endPos;
497 /* length word, if needed, will be filled in by pqPutMsgEnd */
500 fprintf(conn->Pfdebug, "To backend> Msg %c\n",
501 msg_type ? msg_type : ' ');
507 * pqPutMsgBytes: add bytes to a partially-constructed message
509 * Returns 0 on success, EOF on error
512 pqPutMsgBytes(const void *buf, size_t len, PGconn *conn)
514 /* make sure there is room for it */
515 if (pqCheckOutBufferSpace(conn->outMsgEnd + len, conn))
517 /* okay, save the data */
518 memcpy(conn->outBuffer + conn->outMsgEnd, buf, len);
519 conn->outMsgEnd += len;
520 /* no Pfdebug call here, caller should do it */
525 * pqPutMsgEnd: finish constructing a message and possibly send it
527 * Returns 0 on success, EOF on error
529 * We don't actually send anything here unless we've accumulated at least
530 * 8K worth of data (the typical size of a pipe buffer on Unix systems).
531 * This avoids sending small partial packets. The caller must use pqFlush
532 * when it's important to flush all the data out to the server.
535 pqPutMsgEnd(PGconn *conn)
538 fprintf(conn->Pfdebug, "To backend> Msg complete, length %u\n",
539 conn->outMsgEnd - conn->outCount);
541 /* Fill in length word if needed */
542 if (conn->outMsgStart >= 0)
544 uint32 msgLen = conn->outMsgEnd - conn->outMsgStart;
546 msgLen = htonl(msgLen);
547 memcpy(conn->outBuffer + conn->outMsgStart, &msgLen, 4);
550 /* Make message eligible to send */
551 conn->outCount = conn->outMsgEnd;
553 if (conn->outCount >= 8192)
555 int toSend = conn->outCount - (conn->outCount % 8192);
557 if (pqSendSome(conn, toSend) < 0)
559 /* in nonblock mode, don't complain if unable to send it all */
566 * pqReadData: read more data, if any is available
567 * Possible return values:
568 * 1: successfully loaded at least one more byte
569 * 0: no data is presently available, but no error detected
570 * -1: error detected (including EOF = connection closure);
571 * conn->errorMessage set
572 * NOTE: callers must not assume that pointers or indexes into conn->inBuffer
573 * remain valid across this call!
577 pqReadData(PGconn *conn)
585 printfPQExpBuffer(&conn->errorMessage,
586 libpq_gettext("connection not open\n"));
590 /* Left-justify any data in the buffer to make room */
591 if (conn->inStart < conn->inEnd)
593 if (conn->inStart > 0)
595 memmove(conn->inBuffer, conn->inBuffer + conn->inStart,
596 conn->inEnd - conn->inStart);
597 conn->inEnd -= conn->inStart;
598 conn->inCursor -= conn->inStart;
604 /* buffer is logically empty, reset it */
605 conn->inStart = conn->inCursor = conn->inEnd = 0;
609 * If the buffer is fairly full, enlarge it. We need to be able to enlarge
610 * the buffer in case a single message exceeds the initial buffer size. We
611 * enlarge before filling the buffer entirely so as to avoid asking the
612 * kernel for a partial packet. The magic constant here should be large
613 * enough for a TCP packet or Unix pipe bufferload. 8K is the usual pipe
616 if (conn->inBufSize - conn->inEnd < 8192)
618 if (pqCheckInBufferSpace(conn->inEnd + (size_t) 8192, conn))
621 * We don't insist that the enlarge worked, but we need some room
623 if (conn->inBufSize - conn->inEnd < 100)
624 return -1; /* errorMessage already set */
628 /* OK, try to read some data */
630 nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
631 conn->inBufSize - conn->inEnd);
634 if (SOCK_ERRNO == EINTR)
636 /* Some systems return EAGAIN/EWOULDBLOCK for no data */
638 if (SOCK_ERRNO == EAGAIN)
641 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
642 if (SOCK_ERRNO == EWOULDBLOCK)
645 /* We might get ECONNRESET here if using TCP and backend died */
647 if (SOCK_ERRNO == ECONNRESET)
648 goto definitelyFailed;
650 printfPQExpBuffer(&conn->errorMessage,
651 libpq_gettext("could not receive data from server: %s\n"),
652 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
657 conn->inEnd += nread;
660 * Hack to deal with the fact that some kernels will only give us back
661 * 1 packet per recv() call, even if we asked for more and there is
662 * more available. If it looks like we are reading a long message,
663 * loop back to recv() again immediately, until we run out of data or
664 * buffer space. Without this, the block-and-restart behavior of
665 * libpq's higher levels leads to O(N^2) performance on long messages.
667 * Since we left-justified the data above, conn->inEnd gives the
668 * amount of data already read in the current message. We consider
669 * the message "long" once we have acquired 32k ...
671 if (conn->inEnd > 32768 &&
672 (conn->inBufSize - conn->inEnd) >= 8192)
681 return 1; /* got a zero read after successful tries */
684 * A return value of 0 could mean just that no data is now available, or
685 * it could mean EOF --- that is, the server has closed the connection.
686 * Since we have the socket in nonblock mode, the only way to tell the
687 * difference is to see if select() is saying that the file is ready.
688 * Grumble. Fortunately, we don't expect this path to be taken much,
689 * since in normal practice we should not be trying to read data unless
690 * the file selected for reading already.
692 * In SSL mode it's even worse: SSL_read() could say WANT_READ and then
693 * data could arrive before we make the pqReadReady() test. So we must
694 * play dumb and assume there is more data, relying on the SSL layer to
703 switch (pqReadReady(conn))
706 /* definitely no data available */
712 goto definitelyFailed;
716 * Still not sure that it's EOF, because some data could have just
720 nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
721 conn->inBufSize - conn->inEnd);
724 if (SOCK_ERRNO == EINTR)
726 /* Some systems return EAGAIN/EWOULDBLOCK for no data */
728 if (SOCK_ERRNO == EAGAIN)
731 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
732 if (SOCK_ERRNO == EWOULDBLOCK)
735 /* We might get ECONNRESET here if using TCP and backend died */
737 if (SOCK_ERRNO == ECONNRESET)
738 goto definitelyFailed;
740 printfPQExpBuffer(&conn->errorMessage,
741 libpq_gettext("could not receive data from server: %s\n"),
742 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
747 conn->inEnd += nread;
752 * OK, we are getting a zero read even though select() says ready. This
753 * means the connection has been closed. Cope.
756 printfPQExpBuffer(&conn->errorMessage,
758 "server closed the connection unexpectedly\n"
759 "\tThis probably means the server terminated abnormally\n"
760 "\tbefore or while processing the request.\n"));
761 conn->status = CONNECTION_BAD; /* No more connection to backend */
762 pqsecure_close(conn);
763 closesocket(conn->sock);
770 * pqSendSome: send data waiting in the output buffer.
772 * len is how much to try to send (typically equal to outCount, but may
775 * Return 0 on success, -1 on failure and 1 when not all data could be sent
776 * because the socket would block and the connection is non-blocking.
779 pqSendSome(PGconn *conn, int len)
781 char *ptr = conn->outBuffer;
782 int remaining = conn->outCount;
787 printfPQExpBuffer(&conn->errorMessage,
788 libpq_gettext("connection not open\n"));
792 /* while there's still data to send */
799 sent = pqsecure_write(conn, ptr, len);
803 * Windows can fail on large sends, per KB article Q201213. The
804 * failure-point appears to be different in different versions of
805 * Windows, but 64k should always be safe.
807 sent = pqsecure_write(conn, ptr, Min(len, 65536));
813 * Anything except EAGAIN/EWOULDBLOCK/EINTR is trouble. If it's
814 * EPIPE or ECONNRESET, assume we've lost the backend connection
823 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
834 printfPQExpBuffer(&conn->errorMessage,
836 "server closed the connection unexpectedly\n"
837 "\tThis probably means the server terminated abnormally\n"
838 "\tbefore or while processing the request.\n"));
841 * We used to close the socket here, but that's a bad idea
842 * since there might be unread data waiting (typically, a
843 * NOTICE message from the backend telling us it's
844 * committing hara-kiri...). Leave the socket open until
845 * pqReadData finds no more data can be read. But abandon
846 * attempt to send data.
852 printfPQExpBuffer(&conn->errorMessage,
853 libpq_gettext("could not send data to server: %s\n"),
854 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
855 /* We don't assume it's a fatal error... */
870 * We didn't send it all, wait till we can send more.
872 * If the connection is in non-blocking mode we don't wait, but
873 * return 1 to indicate that data is still pending.
875 if (pqIsnonblocking(conn))
882 * There are scenarios in which we can't send data because the
883 * communications channel is full, but we cannot expect the server
884 * to clear the channel eventually because it's blocked trying to
885 * send data to us. (This can happen when we are sending a large
886 * amount of COPY data, and the server has generated lots of
887 * NOTICE responses.) To avoid a deadlock situation, we must be
888 * prepared to accept and buffer incoming data before we try
889 * again. Furthermore, it is possible that such incoming data
890 * might not arrive until after we've gone to sleep. Therefore,
891 * we wait for either read ready or write ready.
893 if (pqReadData(conn) < 0)
895 result = -1; /* error message already set up */
898 if (pqWait(TRUE, TRUE, conn))
906 /* shift the remaining contents of the buffer */
908 memmove(conn->outBuffer, ptr, remaining);
909 conn->outCount = remaining;
916 * pqFlush: send any data waiting in the output buffer
918 * Return 0 on success, -1 on failure and 1 when not all data could be sent
919 * because the socket would block and the connection is non-blocking.
922 pqFlush(PGconn *conn)
925 fflush(conn->Pfdebug);
927 if (conn->outCount > 0)
928 return pqSendSome(conn, conn->outCount);
935 * pqWait: wait until we can read or write the connection socket
937 * JAB: If SSL enabled and used and forRead, buffered bytes short-circuit the
940 * We also stop waiting and return if the kernel flags an exception condition
941 * on the socket. The actual error condition will be detected and reported
942 * when the caller tries to read or write the socket.
945 pqWait(int forRead, int forWrite, PGconn *conn)
947 return pqWaitTimed(forRead, forWrite, conn, (time_t) -1);
951 * pqWaitTimed: wait, but not past finish_time.
953 * If finish_time is exceeded then we return failure (EOF). This is like
954 * the response for a kernel exception because we don't want the caller
955 * to try to read/write in that case.
957 * finish_time = ((time_t) -1) disables the wait limit.
960 pqWaitTimed(int forRead, int forWrite, PGconn *conn, time_t finish_time)
964 result = pqSocketCheck(conn, forRead, forWrite, finish_time);
967 return EOF; /* errorMessage is already set */
971 printfPQExpBuffer(&conn->errorMessage,
972 libpq_gettext("timeout expired\n"));
980 * pqReadReady: is select() saying the file is ready to read?
981 * Returns -1 on failure, 0 if not ready, 1 if ready.
984 pqReadReady(PGconn *conn)
986 return pqSocketCheck(conn, 1, 0, (time_t) 0);
990 * pqWriteReady: is select() saying the file is ready to write?
991 * Returns -1 on failure, 0 if not ready, 1 if ready.
994 pqWriteReady(PGconn *conn)
996 return pqSocketCheck(conn, 0, 1, (time_t) 0);
1000 * Checks a socket, using poll or select, for data to be read, written,
1001 * or both. Returns >0 if one or more conditions are met, 0 if it timed
1002 * out, -1 if an error occurred.
1004 * If SSL is in use, the SSL buffer is checked prior to checking the socket
1005 * for read data directly.
1008 pqSocketCheck(PGconn *conn, int forRead, int forWrite, time_t end_time)
1016 printfPQExpBuffer(&conn->errorMessage,
1017 libpq_gettext("socket not open\n"));
1022 /* Check for SSL library buffering read bytes */
1023 if (forRead && conn->ssl && SSL_pending(conn->ssl) > 0)
1025 /* short-circuit the select */
1030 /* We will retry as long as we get EINTR */
1032 result = pqSocketPoll(conn->sock, forRead, forWrite, end_time);
1033 while (result < 0 && SOCK_ERRNO == EINTR);
1039 printfPQExpBuffer(&conn->errorMessage,
1040 libpq_gettext("select() failed: %s\n"),
1041 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1049 * Check a file descriptor for read and/or write data, possibly waiting.
1050 * If neither forRead nor forWrite are set, immediately return a timeout
1051 * condition (without waiting). Return >0 if condition is met, 0
1052 * if a timeout occurred, -1 if an error or interrupt occurred.
1054 * Timeout is infinite if end_time is -1. Timeout is immediate (no blocking)
1055 * if end_time is 0 (or indeed, any time before now).
1058 pqSocketPoll(int sock, int forRead, int forWrite, time_t end_time)
1060 /* We use poll(2) if available, otherwise select(2) */
1062 struct pollfd input_fd;
1065 if (!forRead && !forWrite)
1069 input_fd.events = POLLERR;
1070 input_fd.revents = 0;
1073 input_fd.events |= POLLIN;
1075 input_fd.events |= POLLOUT;
1077 /* Compute appropriate timeout interval */
1078 if (end_time == ((time_t) -1))
1082 time_t now = time(NULL);
1085 timeout_ms = (end_time - now) * 1000;
1090 return poll(&input_fd, 1, timeout_ms);
1091 #else /* !HAVE_POLL */
1096 struct timeval timeout;
1097 struct timeval *ptr_timeout;
1099 if (!forRead && !forWrite)
1102 FD_ZERO(&input_mask);
1103 FD_ZERO(&output_mask);
1104 FD_ZERO(&except_mask);
1106 FD_SET(sock, &input_mask);
1109 FD_SET(sock, &output_mask);
1110 FD_SET(sock, &except_mask);
1112 /* Compute appropriate timeout interval */
1113 if (end_time == ((time_t) -1))
1117 time_t now = time(NULL);
1120 timeout.tv_sec = end_time - now;
1123 timeout.tv_usec = 0;
1124 ptr_timeout = &timeout;
1127 return select(sock + 1, &input_mask, &output_mask,
1128 &except_mask, ptr_timeout);
1129 #endif /* HAVE_POLL */
1134 * A couple of "miscellaneous" multibyte related functions. They used
1135 * to be in fe-print.c but that file is doomed.
1139 * returns the byte length of the word beginning s, using the
1140 * specified encoding.
1143 PQmblen(const char *s, int encoding)
1145 return pg_encoding_mblen(encoding, s);
1149 * returns the display length of the word beginning s, using the
1150 * specified encoding.
1153 PQdsplen(const char *s, int encoding)
1155 return pg_encoding_dsplen(encoding, s);
1159 * Get encoding id from environment variable PGCLIENTENCODING.
1162 PQenv2encoding(void)
1165 int encoding = PG_SQL_ASCII;
1167 str = getenv("PGCLIENTENCODING");
1168 if (str && *str != '\0')
1170 encoding = pg_char_to_encoding(str);
1172 encoding = PG_SQL_ASCII;
1181 libpq_gettext(const char *msgid)
1183 static bool already_bound = false;
1187 /* dgettext() preserves errno, but bindtextdomain() doesn't */
1189 int save_errno = GetLastError();
1191 int save_errno = errno;
1195 already_bound = true;
1196 /* No relocatable lookup here because the binary could be anywhere */
1197 ldir = getenv("PGLOCALEDIR");
1200 bindtextdomain(PG_TEXTDOMAIN("libpq"), ldir);
1202 SetLastError(save_errno);
1208 return dgettext(PG_TEXTDOMAIN("libpq"), msgid);
1211 #endif /* ENABLE_NLS */