1 /*-------------------------------------------------------------------------
7 * miscellaneous useful functions
9 * The communication routines here are analogous to the ones in
10 * backend/libpq/pqcomm.c and backend/libpq/pqformat.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-2025, 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"
40 #include <sys/select.h>
49 #include "libpq-int.h"
50 #include "mb/pg_wchar.h"
51 #include "pg_config_paths.h"
52 #include "port/pg_bswap.h"
54 static int pqPutMsgBytes(const void *buf
, size_t len
, PGconn
*conn
);
55 static int pqSendSome(PGconn
*conn
, int len
);
56 static int pqSocketCheck(PGconn
*conn
, int forRead
, int forWrite
,
57 pg_usec_time_t end_time
);
60 * PQlibVersion: return the libpq version number
65 return PG_VERSION_NUM
;
70 * pqGetc: get 1 character from the connection
72 * All these routines return 0 on success, EOF on error.
73 * Note that for the Get routines, EOF only means there is not enough
74 * data in the buffer, not that there is necessarily a hard error.
77 pqGetc(char *result
, PGconn
*conn
)
79 if (conn
->inCursor
>= conn
->inEnd
)
82 *result
= conn
->inBuffer
[conn
->inCursor
++];
89 * pqPutc: write 1 char to the current message
92 pqPutc(char c
, PGconn
*conn
)
94 if (pqPutMsgBytes(&c
, 1, conn
))
103 * get a null-terminated string from the connection,
104 * and store it in an expansible PQExpBuffer.
105 * If we run out of memory, all of the string is still read,
106 * but the excess characters are silently discarded.
109 pqGets_internal(PQExpBuffer buf
, PGconn
*conn
, bool resetbuffer
)
111 /* Copy conn data to locals for faster search loop */
112 char *inBuffer
= conn
->inBuffer
;
113 int inCursor
= conn
->inCursor
;
114 int inEnd
= conn
->inEnd
;
117 while (inCursor
< inEnd
&& inBuffer
[inCursor
])
120 if (inCursor
>= inEnd
)
123 slen
= inCursor
- conn
->inCursor
;
126 resetPQExpBuffer(buf
);
128 appendBinaryPQExpBuffer(buf
, inBuffer
+ conn
->inCursor
, slen
);
130 conn
->inCursor
= ++inCursor
;
136 pqGets(PQExpBuffer buf
, PGconn
*conn
)
138 return pqGets_internal(buf
, conn
, true);
142 pqGets_append(PQExpBuffer buf
, PGconn
*conn
)
144 return pqGets_internal(buf
, conn
, false);
149 * pqPuts: write a null-terminated string to the current message
152 pqPuts(const char *s
, PGconn
*conn
)
154 if (pqPutMsgBytes(s
, strlen(s
) + 1, conn
))
162 * get a string of exactly len bytes in buffer s, no null termination
165 pqGetnchar(char *s
, size_t len
, PGconn
*conn
)
167 if (len
> (size_t) (conn
->inEnd
- conn
->inCursor
))
170 memcpy(s
, conn
->inBuffer
+ conn
->inCursor
, len
);
171 /* no terminating null */
173 conn
->inCursor
+= len
;
180 * skip over len bytes in input buffer.
182 * Note: this is primarily useful for its debug output, which should
183 * be exactly the same as for pqGetnchar. We assume the data in question
184 * will actually be used, but just isn't getting copied anywhere as yet.
187 pqSkipnchar(size_t len
, PGconn
*conn
)
189 if (len
> (size_t) (conn
->inEnd
- conn
->inCursor
))
192 conn
->inCursor
+= len
;
199 * write exactly len bytes to the current message
202 pqPutnchar(const char *s
, size_t len
, PGconn
*conn
)
204 if (pqPutMsgBytes(s
, len
, conn
))
212 * read a 2 or 4 byte integer and convert from network byte order
213 * to local byte order
216 pqGetInt(int *result
, size_t bytes
, PGconn
*conn
)
224 if (conn
->inCursor
+ 2 > conn
->inEnd
)
226 memcpy(&tmp2
, conn
->inBuffer
+ conn
->inCursor
, 2);
228 *result
= (int) pg_ntoh16(tmp2
);
231 if (conn
->inCursor
+ 4 > conn
->inEnd
)
233 memcpy(&tmp4
, conn
->inBuffer
+ conn
->inCursor
, 4);
235 *result
= (int) pg_ntoh32(tmp4
);
238 pqInternalNotice(&conn
->noticeHooks
,
239 "integer of size %lu not supported by pqGetInt",
240 (unsigned long) bytes
);
249 * write an integer of 2 or 4 bytes, converting from host byte order
250 * to network byte order.
253 pqPutInt(int value
, size_t bytes
, PGconn
*conn
)
261 tmp2
= pg_hton16((uint16
) value
);
262 if (pqPutMsgBytes((const char *) &tmp2
, 2, conn
))
266 tmp4
= pg_hton32((uint32
) value
);
267 if (pqPutMsgBytes((const char *) &tmp4
, 4, conn
))
271 pqInternalNotice(&conn
->noticeHooks
,
272 "integer of size %lu not supported by pqPutInt",
273 (unsigned long) bytes
);
281 * Make sure conn's output buffer can hold bytes_needed bytes (caller must
282 * include already-stored data into the value!)
284 * Returns 0 on success, EOF if failed to enlarge buffer
287 pqCheckOutBufferSpace(size_t bytes_needed
, PGconn
*conn
)
289 int newsize
= conn
->outBufSize
;
292 /* Quick exit if we have enough space */
293 if (bytes_needed
<= (size_t) newsize
)
297 * If we need to enlarge the buffer, we first try to double it in size; if
298 * that doesn't work, enlarge in multiples of 8K. This avoids thrashing
299 * the malloc pool by repeated small enlargements.
301 * Note: tests for newsize > 0 are to catch integer overflow.
306 } while (newsize
> 0 && bytes_needed
> (size_t) newsize
);
308 if (newsize
> 0 && bytes_needed
<= (size_t) newsize
)
310 newbuf
= realloc(conn
->outBuffer
, newsize
);
313 /* realloc succeeded */
314 conn
->outBuffer
= newbuf
;
315 conn
->outBufSize
= newsize
;
320 newsize
= conn
->outBufSize
;
324 } while (newsize
> 0 && bytes_needed
> (size_t) newsize
);
326 if (newsize
> 0 && bytes_needed
<= (size_t) newsize
)
328 newbuf
= realloc(conn
->outBuffer
, newsize
);
331 /* realloc succeeded */
332 conn
->outBuffer
= newbuf
;
333 conn
->outBufSize
= newsize
;
338 /* realloc failed. Probably out of memory */
339 appendPQExpBufferStr(&conn
->errorMessage
,
340 "cannot allocate memory for output buffer\n");
345 * Make sure conn's input buffer can hold bytes_needed bytes (caller must
346 * include already-stored data into the value!)
348 * Returns 0 on success, EOF if failed to enlarge buffer
351 pqCheckInBufferSpace(size_t bytes_needed
, PGconn
*conn
)
353 int newsize
= conn
->inBufSize
;
356 /* Quick exit if we have enough space */
357 if (bytes_needed
<= (size_t) newsize
)
361 * Before concluding that we need to enlarge the buffer, left-justify
362 * whatever is in it and recheck. The caller's value of bytes_needed
363 * includes any data to the left of inStart, but we can delete that in
364 * preference to enlarging the buffer. It's slightly ugly to have this
365 * function do this, but it's better than making callers worry about it.
367 bytes_needed
-= conn
->inStart
;
369 if (conn
->inStart
< conn
->inEnd
)
371 if (conn
->inStart
> 0)
373 memmove(conn
->inBuffer
, conn
->inBuffer
+ conn
->inStart
,
374 conn
->inEnd
- conn
->inStart
);
375 conn
->inEnd
-= conn
->inStart
;
376 conn
->inCursor
-= conn
->inStart
;
382 /* buffer is logically empty, reset it */
383 conn
->inStart
= conn
->inCursor
= conn
->inEnd
= 0;
386 /* Recheck whether we have enough space */
387 if (bytes_needed
<= (size_t) newsize
)
391 * If we need to enlarge the buffer, we first try to double it in size; if
392 * that doesn't work, enlarge in multiples of 8K. This avoids thrashing
393 * the malloc pool by repeated small enlargements.
395 * Note: tests for newsize > 0 are to catch integer overflow.
400 } while (newsize
> 0 && bytes_needed
> (size_t) newsize
);
402 if (newsize
> 0 && bytes_needed
<= (size_t) newsize
)
404 newbuf
= realloc(conn
->inBuffer
, newsize
);
407 /* realloc succeeded */
408 conn
->inBuffer
= newbuf
;
409 conn
->inBufSize
= newsize
;
414 newsize
= conn
->inBufSize
;
418 } while (newsize
> 0 && bytes_needed
> (size_t) newsize
);
420 if (newsize
> 0 && bytes_needed
<= (size_t) newsize
)
422 newbuf
= realloc(conn
->inBuffer
, newsize
);
425 /* realloc succeeded */
426 conn
->inBuffer
= newbuf
;
427 conn
->inBufSize
= newsize
;
432 /* realloc failed. Probably out of memory */
433 appendPQExpBufferStr(&conn
->errorMessage
,
434 "cannot allocate memory for input buffer\n");
439 * pqParseDone: after a server-to-client message has successfully
440 * been parsed, advance conn->inStart to account for it.
443 pqParseDone(PGconn
*conn
, int newInStart
)
445 /* trace server-to-client message */
447 pqTraceOutputMessage(conn
, conn
->inBuffer
+ conn
->inStart
, false);
449 /* Mark message as done */
450 conn
->inStart
= newInStart
;
454 * pqPutMsgStart: begin construction of a message to the server
456 * msg_type is the message type byte, or 0 for a message without type byte
457 * (only startup messages have no type byte)
459 * Returns 0 on success, EOF on error
461 * The idea here is that we construct the message in conn->outBuffer,
462 * beginning just past any data already in outBuffer (ie, at
463 * outBuffer+outCount). We enlarge the buffer as needed to hold the message.
464 * When the message is complete, we fill in the length word (if needed) and
465 * then advance outCount past the message, making it eligible to send.
467 * The state variable conn->outMsgStart points to the incomplete message's
468 * length word: it is either outCount or outCount+1 depending on whether
469 * there is a type byte. The state variable conn->outMsgEnd is the end of
470 * the data collected so far.
473 pqPutMsgStart(char msg_type
, PGconn
*conn
)
478 /* allow room for message type byte */
480 endPos
= conn
->outCount
+ 1;
482 endPos
= conn
->outCount
;
484 /* do we want a length word? */
486 /* allow room for message length */
489 /* make sure there is room for message header */
490 if (pqCheckOutBufferSpace(endPos
, conn
))
492 /* okay, save the message type byte if any */
494 conn
->outBuffer
[conn
->outCount
] = msg_type
;
495 /* set up the message pointers */
496 conn
->outMsgStart
= lenPos
;
497 conn
->outMsgEnd
= endPos
;
498 /* length word, if needed, will be filled in by pqPutMsgEnd */
504 * pqPutMsgBytes: add bytes to a partially-constructed message
506 * Returns 0 on success, EOF on error
509 pqPutMsgBytes(const void *buf
, size_t len
, PGconn
*conn
)
511 /* make sure there is room for it */
512 if (pqCheckOutBufferSpace(conn
->outMsgEnd
+ len
, conn
))
514 /* okay, save the data */
515 memcpy(conn
->outBuffer
+ conn
->outMsgEnd
, buf
, len
);
516 conn
->outMsgEnd
+= len
;
517 /* no Pfdebug call here, caller should do it */
522 * pqPutMsgEnd: finish constructing a message and possibly send it
524 * Returns 0 on success, EOF on error
526 * We don't actually send anything here unless we've accumulated at least
527 * 8K worth of data (the typical size of a pipe buffer on Unix systems).
528 * This avoids sending small partial packets. The caller must use pqFlush
529 * when it's important to flush all the data out to the server.
532 pqPutMsgEnd(PGconn
*conn
)
534 /* Fill in length word if needed */
535 if (conn
->outMsgStart
>= 0)
537 uint32 msgLen
= conn
->outMsgEnd
- conn
->outMsgStart
;
539 msgLen
= pg_hton32(msgLen
);
540 memcpy(conn
->outBuffer
+ conn
->outMsgStart
, &msgLen
, 4);
543 /* trace client-to-server message */
546 if (conn
->outCount
< conn
->outMsgStart
)
547 pqTraceOutputMessage(conn
, conn
->outBuffer
+ conn
->outCount
, true);
549 pqTraceOutputNoTypeByteMessage(conn
,
550 conn
->outBuffer
+ conn
->outMsgStart
);
553 /* Make message eligible to send */
554 conn
->outCount
= conn
->outMsgEnd
;
556 if (conn
->outCount
>= 8192)
558 int toSend
= conn
->outCount
- (conn
->outCount
% 8192);
560 if (pqSendSome(conn
, toSend
) < 0)
562 /* in nonblock mode, don't complain if unable to send it all */
569 * pqReadData: read more data, if any is available
570 * Possible return values:
571 * 1: successfully loaded at least one more byte
572 * 0: no data is presently available, but no error detected
573 * -1: error detected (including EOF = connection closure);
574 * conn->errorMessage set
575 * NOTE: callers must not assume that pointers or indexes into conn->inBuffer
576 * remain valid across this call!
580 pqReadData(PGconn
*conn
)
585 if (conn
->sock
== PGINVALID_SOCKET
)
587 libpq_append_conn_error(conn
, "connection not open");
591 /* Left-justify any data in the buffer to make room */
592 if (conn
->inStart
< conn
->inEnd
)
594 if (conn
->inStart
> 0)
596 memmove(conn
->inBuffer
, conn
->inBuffer
+ conn
->inStart
,
597 conn
->inEnd
- conn
->inStart
);
598 conn
->inEnd
-= conn
->inStart
;
599 conn
->inCursor
-= conn
->inStart
;
605 /* buffer is logically empty, reset it */
606 conn
->inStart
= conn
->inCursor
= conn
->inEnd
= 0;
610 * If the buffer is fairly full, enlarge it. We need to be able to enlarge
611 * the buffer in case a single message exceeds the initial buffer size. We
612 * enlarge before filling the buffer entirely so as to avoid asking the
613 * kernel for a partial packet. The magic constant here should be large
614 * enough for a TCP packet or Unix pipe bufferload. 8K is the usual pipe
617 if (conn
->inBufSize
- conn
->inEnd
< 8192)
619 if (pqCheckInBufferSpace(conn
->inEnd
+ (size_t) 8192, conn
))
622 * We don't insist that the enlarge worked, but we need some room
624 if (conn
->inBufSize
- conn
->inEnd
< 100)
625 return -1; /* errorMessage already set */
629 /* OK, try to read some data */
631 nread
= pqsecure_read(conn
, conn
->inBuffer
+ conn
->inEnd
,
632 conn
->inBufSize
- conn
->inEnd
);
640 /* Some systems return EAGAIN/EWOULDBLOCK for no data */
645 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
650 /* We might get ECONNRESET etc here if connection failed */
651 case ALL_CONNECTION_FAILURE_ERRNOS
:
652 goto definitelyFailed
;
655 /* pqsecure_read set the error message for us */
661 conn
->inEnd
+= nread
;
664 * Hack to deal with the fact that some kernels will only give us back
665 * 1 packet per recv() call, even if we asked for more and there is
666 * more available. If it looks like we are reading a long message,
667 * loop back to recv() again immediately, until we run out of data or
668 * buffer space. Without this, the block-and-restart behavior of
669 * libpq's higher levels leads to O(N^2) performance on long messages.
671 * Since we left-justified the data above, conn->inEnd gives the
672 * amount of data already read in the current message. We consider
673 * the message "long" once we have acquired 32k ...
675 if (conn
->inEnd
> 32768 &&
676 (conn
->inBufSize
- conn
->inEnd
) >= 8192)
685 return 1; /* got a zero read after successful tries */
688 * A return value of 0 could mean just that no data is now available, or
689 * it could mean EOF --- that is, the server has closed the connection.
690 * Since we have the socket in nonblock mode, the only way to tell the
691 * difference is to see if select() is saying that the file is ready.
692 * Grumble. Fortunately, we don't expect this path to be taken much,
693 * since in normal practice we should not be trying to read data unless
694 * the file selected for reading already.
696 * In SSL mode it's even worse: SSL_read() could say WANT_READ and then
697 * data could arrive before we make the pqReadReady() test, but the second
698 * SSL_read() could still say WANT_READ because the data received was not
699 * a complete SSL record. So we must play dumb and assume there is more
700 * data, relying on the SSL layer to detect true EOF.
704 if (conn
->ssl_in_use
)
708 switch (pqReadReady(conn
))
711 /* definitely no data available */
717 /* we override pqReadReady's message with something more useful */
722 * Still not sure that it's EOF, because some data could have just
726 nread
= pqsecure_read(conn
, conn
->inBuffer
+ conn
->inEnd
,
727 conn
->inBufSize
- conn
->inEnd
);
735 /* Some systems return EAGAIN/EWOULDBLOCK for no data */
740 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
745 /* We might get ECONNRESET etc here if connection failed */
746 case ALL_CONNECTION_FAILURE_ERRNOS
:
747 goto definitelyFailed
;
750 /* pqsecure_read set the error message for us */
756 conn
->inEnd
+= nread
;
761 * OK, we are getting a zero read even though select() says ready. This
762 * means the connection has been closed. Cope.
765 libpq_append_conn_error(conn
, "server closed the connection unexpectedly\n"
766 "\tThis probably means the server terminated abnormally\n"
767 "\tbefore or while processing the request.");
769 /* Come here if lower-level code already set a suitable errorMessage */
771 /* Do *not* drop any already-read data; caller still wants it */
772 pqDropConnection(conn
, false);
773 conn
->status
= CONNECTION_BAD
; /* No more connection to backend */
778 * pqSendSome: send data waiting in the output buffer.
780 * len is how much to try to send (typically equal to outCount, but may
783 * Return 0 on success, -1 on failure and 1 when not all data could be sent
784 * because the socket would block and the connection is non-blocking.
786 * Note that this is also responsible for consuming data from the socket
787 * (putting it in conn->inBuffer) in any situation where we can't send
788 * all the specified data immediately.
790 * If a socket-level write failure occurs, conn->write_failed is set and the
791 * error message is saved in conn->write_err_msg, but we clear the output
792 * buffer and return zero anyway; this is because callers should soldier on
793 * until we have read what we can from the server and checked for an error
794 * message. write_err_msg should be reported only when we are unable to
795 * obtain a server error first. Much of that behavior is implemented at
796 * lower levels, but this function deals with some edge cases.
799 pqSendSome(PGconn
*conn
, int len
)
801 char *ptr
= conn
->outBuffer
;
802 int remaining
= conn
->outCount
;
806 * If we already had a write failure, we will never again try to send data
807 * on that connection. Even if the kernel would let us, we've probably
808 * lost message boundary sync with the server. conn->write_failed
809 * therefore persists until the connection is reset, and we just discard
810 * all data presented to be written. However, as long as we still have a
811 * valid socket, we should continue to absorb data from the backend, so
812 * that we can collect any final error messages.
814 if (conn
->write_failed
)
816 /* conn->write_err_msg should be set up already */
818 /* Absorb input data if any, and detect socket closure */
819 if (conn
->sock
!= PGINVALID_SOCKET
)
821 if (pqReadData(conn
) < 0)
827 if (conn
->sock
== PGINVALID_SOCKET
)
829 conn
->write_failed
= true;
830 /* Store error message in conn->write_err_msg, if possible */
831 /* (strdup failure is OK, we'll cope later) */
832 conn
->write_err_msg
= strdup(libpq_gettext("connection not open\n"));
833 /* Discard queued data; no chance it'll ever be sent */
838 /* while there's still data to send */
844 sent
= pqsecure_write(conn
, ptr
, len
);
848 * Windows can fail on large sends, per KB article Q201213. The
849 * failure-point appears to be different in different versions of
850 * Windows, but 64k should always be safe.
852 sent
= pqsecure_write(conn
, ptr
, Min(len
, 65536));
857 /* Anything except EAGAIN/EWOULDBLOCK/EINTR is trouble */
864 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
872 /* Discard queued data; no chance it'll ever be sent */
875 /* Absorb input data if any, and detect socket closure */
876 if (conn
->sock
!= PGINVALID_SOCKET
)
878 if (pqReadData(conn
) < 0)
883 * Lower-level code should already have filled
884 * conn->write_err_msg (and set conn->write_failed) or
885 * conn->errorMessage. In the former case, we pretend
886 * there's no problem; the write_failed condition will be
887 * dealt with later. Otherwise, report the error now.
889 if (conn
->write_failed
)
905 * We didn't send it all, wait till we can send more.
907 * There are scenarios in which we can't send data because the
908 * communications channel is full, but we cannot expect the server
909 * to clear the channel eventually because it's blocked trying to
910 * send data to us. (This can happen when we are sending a large
911 * amount of COPY data, and the server has generated lots of
912 * NOTICE responses.) To avoid a deadlock situation, we must be
913 * prepared to accept and buffer incoming data before we try
914 * again. Furthermore, it is possible that such incoming data
915 * might not arrive until after we've gone to sleep. Therefore,
916 * we wait for either read ready or write ready.
918 * In non-blocking mode, we don't wait here directly, but return 1
919 * to indicate that data is still pending. The caller should wait
920 * for both read and write ready conditions, and call
921 * PQconsumeInput() on read ready, but just in case it doesn't, we
922 * call pqReadData() ourselves before returning. That's not
923 * enough if the data has not arrived yet, but it's the best we
924 * can do, and works pretty well in practice. (The documentation
925 * used to say that you only need to wait for write-ready, so
926 * there are still plenty of applications like that out there.)
928 * Note that errors here don't result in write_failed becoming
931 if (pqReadData(conn
) < 0)
933 result
= -1; /* error message already set up */
937 if (pqIsnonblocking(conn
))
943 if (pqWait(true, true, conn
))
951 /* shift the remaining contents of the buffer */
953 memmove(conn
->outBuffer
, ptr
, remaining
);
954 conn
->outCount
= remaining
;
961 * pqFlush: send any data waiting in the output buffer
963 * Return 0 on success, -1 on failure and 1 when not all data could be sent
964 * because the socket would block and the connection is non-blocking.
965 * (See pqSendSome comments about how failure should be handled.)
968 pqFlush(PGconn
*conn
)
970 if (conn
->outCount
> 0)
973 fflush(conn
->Pfdebug
);
975 return pqSendSome(conn
, conn
->outCount
);
983 * pqWait: wait until we can read or write the connection socket
985 * JAB: If SSL enabled and used and forRead, buffered bytes short-circuit the
988 * We also stop waiting and return if the kernel flags an exception condition
989 * on the socket. The actual error condition will be detected and reported
990 * when the caller tries to read or write the socket.
993 pqWait(int forRead
, int forWrite
, PGconn
*conn
)
995 return pqWaitTimed(forRead
, forWrite
, conn
, -1);
999 * pqWaitTimed: wait, but not past end_time.
1001 * Returns -1 on failure, 0 if the socket is readable/writable, 1 if it timed out.
1003 * The timeout is specified by end_time, which is the int64 number of
1004 * microseconds since the Unix epoch (that is, time_t times 1 million).
1005 * Timeout is infinite if end_time is -1. Timeout is immediate (no blocking)
1006 * if end_time is 0 (or indeed, any time before now).
1009 pqWaitTimed(int forRead
, int forWrite
, PGconn
*conn
, pg_usec_time_t end_time
)
1013 result
= pqSocketCheck(conn
, forRead
, forWrite
, end_time
);
1016 return -1; /* errorMessage is already set */
1020 libpq_append_conn_error(conn
, "timeout expired");
1028 * pqReadReady: is select() saying the file is ready to read?
1029 * Returns -1 on failure, 0 if not ready, 1 if ready.
1032 pqReadReady(PGconn
*conn
)
1034 return pqSocketCheck(conn
, 1, 0, 0);
1038 * pqWriteReady: is select() saying the file is ready to write?
1039 * Returns -1 on failure, 0 if not ready, 1 if ready.
1042 pqWriteReady(PGconn
*conn
)
1044 return pqSocketCheck(conn
, 0, 1, 0);
1048 * Checks a socket, using poll or select, for data to be read, written,
1049 * or both. Returns >0 if one or more conditions are met, 0 if it timed
1050 * out, -1 if an error occurred.
1052 * If SSL is in use, the SSL buffer is checked prior to checking the socket
1053 * for read data directly.
1056 pqSocketCheck(PGconn
*conn
, int forRead
, int forWrite
, pg_usec_time_t end_time
)
1062 if (conn
->sock
== PGINVALID_SOCKET
)
1064 libpq_append_conn_error(conn
, "invalid socket");
1069 /* Check for SSL library buffering read bytes */
1070 if (forRead
&& conn
->ssl_in_use
&& pgtls_read_pending(conn
))
1072 /* short-circuit the select */
1077 /* We will retry as long as we get EINTR */
1079 result
= PQsocketPoll(conn
->sock
, forRead
, forWrite
, end_time
);
1080 while (result
< 0 && SOCK_ERRNO
== EINTR
);
1084 char sebuf
[PG_STRERROR_R_BUFLEN
];
1086 libpq_append_conn_error(conn
, "%s() failed: %s", "select",
1087 SOCK_STRERROR(SOCK_ERRNO
, sebuf
, sizeof(sebuf
)));
1095 * Check a file descriptor for read and/or write data, possibly waiting.
1096 * If neither forRead nor forWrite are set, immediately return a timeout
1097 * condition (without waiting). Return >0 if condition is met, 0
1098 * if a timeout occurred, -1 if an error or interrupt occurred.
1100 * The timeout is specified by end_time, which is the int64 number of
1101 * microseconds since the Unix epoch (that is, time_t times 1 million).
1102 * Timeout is infinite if end_time is -1. Timeout is immediate (no blocking)
1103 * if end_time is 0 (or indeed, any time before now).
1106 PQsocketPoll(int sock
, int forRead
, int forWrite
, pg_usec_time_t end_time
)
1108 /* We use poll(2) if available, otherwise select(2) */
1110 struct pollfd input_fd
;
1113 if (!forRead
&& !forWrite
)
1117 input_fd
.events
= POLLERR
;
1118 input_fd
.revents
= 0;
1121 input_fd
.events
|= POLLIN
;
1123 input_fd
.events
|= POLLOUT
;
1125 /* Compute appropriate timeout interval */
1128 else if (end_time
== 0)
1132 pg_usec_time_t now
= PQgetCurrentTimeUSec();
1135 timeout_ms
= (end_time
- now
) / 1000;
1140 return poll(&input_fd
, 1, timeout_ms
);
1141 #else /* !HAVE_POLL */
1146 struct timeval timeout
;
1147 struct timeval
*ptr_timeout
;
1149 if (!forRead
&& !forWrite
)
1152 FD_ZERO(&input_mask
);
1153 FD_ZERO(&output_mask
);
1154 FD_ZERO(&except_mask
);
1156 FD_SET(sock
, &input_mask
);
1159 FD_SET(sock
, &output_mask
);
1160 FD_SET(sock
, &except_mask
);
1162 /* Compute appropriate timeout interval */
1165 else if (end_time
== 0)
1168 timeout
.tv_usec
= 0;
1169 ptr_timeout
= &timeout
;
1173 pg_usec_time_t now
= PQgetCurrentTimeUSec();
1177 timeout
.tv_sec
= (end_time
- now
) / 1000000;
1178 timeout
.tv_usec
= (end_time
- now
) % 1000000;
1183 timeout
.tv_usec
= 0;
1185 ptr_timeout
= &timeout
;
1188 return select(sock
+ 1, &input_mask
, &output_mask
,
1189 &except_mask
, ptr_timeout
);
1190 #endif /* HAVE_POLL */
1194 * PQgetCurrentTimeUSec: get current time with microsecond precision
1196 * This provides a platform-independent way of producing a reference
1197 * value for PQsocketPoll's timeout parameter.
1200 PQgetCurrentTimeUSec(void)
1202 struct timeval tval
;
1204 gettimeofday(&tval
, NULL
);
1205 return (pg_usec_time_t
) tval
.tv_sec
* 1000000 + tval
.tv_usec
;
1210 * A couple of "miscellaneous" multibyte related functions. They used
1211 * to be in fe-print.c but that file is doomed.
1215 * Returns the byte length of the character beginning at s, using the
1216 * specified encoding.
1218 * Caution: when dealing with text that is not certainly valid in the
1219 * specified encoding, the result may exceed the actual remaining
1220 * string length. Callers that are not prepared to deal with that
1221 * should use PQmblenBounded() instead.
1224 PQmblen(const char *s
, int encoding
)
1226 return pg_encoding_mblen(encoding
, s
);
1230 * Returns the byte length of the character beginning at s, using the
1231 * specified encoding; but not more than the distance to end of string.
1234 PQmblenBounded(const char *s
, int encoding
)
1236 return strnlen(s
, pg_encoding_mblen(encoding
, s
));
1240 * Returns the display length of the character beginning at s, using the
1241 * specified encoding.
1244 PQdsplen(const char *s
, int encoding
)
1246 return pg_encoding_dsplen(encoding
, s
);
1250 * Get encoding id from environment variable PGCLIENTENCODING.
1253 PQenv2encoding(void)
1256 int encoding
= PG_SQL_ASCII
;
1258 str
= getenv("PGCLIENTENCODING");
1259 if (str
&& *str
!= '\0')
1261 encoding
= pg_char_to_encoding(str
);
1263 encoding
= PG_SQL_ASCII
;
1272 libpq_binddomain(void)
1275 * At least on Windows, there are gettext implementations that fail if
1276 * multiple threads call bindtextdomain() concurrently. Use a mutex and
1277 * flag variable to ensure that we call it just once per process. It is
1278 * not known that similar bugs exist on non-Windows platforms, but we
1279 * might as well do it the same way everywhere.
1281 static volatile bool already_bound
= false;
1282 static pthread_mutex_t binddomain_mutex
= PTHREAD_MUTEX_INITIALIZER
;
1286 /* bindtextdomain() does not preserve errno */
1288 int save_errno
= GetLastError();
1290 int save_errno
= errno
;
1293 (void) pthread_mutex_lock(&binddomain_mutex
);
1300 * No relocatable lookup here because the calling executable could
1303 ldir
= getenv("PGLOCALEDIR");
1306 bindtextdomain(PG_TEXTDOMAIN("libpq"), ldir
);
1307 already_bound
= true;
1310 (void) pthread_mutex_unlock(&binddomain_mutex
);
1313 SetLastError(save_errno
);
1321 libpq_gettext(const char *msgid
)
1324 return dgettext(PG_TEXTDOMAIN("libpq"), msgid
);
1328 libpq_ngettext(const char *msgid
, const char *msgid_plural
, unsigned long n
)
1331 return dngettext(PG_TEXTDOMAIN("libpq"), msgid
, msgid_plural
, n
);
1334 #endif /* ENABLE_NLS */
1338 * Append a formatted string to the given buffer, after translating it. A
1339 * newline is automatically appended; the format should not end with a
1343 libpq_append_error(PQExpBuffer errorMessage
, const char *fmt
,...)
1345 int save_errno
= errno
;
1349 Assert(fmt
[strlen(fmt
) - 1] != '\n');
1351 if (PQExpBufferBroken(errorMessage
))
1352 return; /* already failed */
1354 /* Loop in case we have to retry after enlarging the buffer. */
1358 va_start(args
, fmt
);
1359 done
= appendPQExpBufferVA(errorMessage
, libpq_gettext(fmt
), args
);
1363 appendPQExpBufferChar(errorMessage
, '\n');
1367 * Append a formatted string to the error message buffer of the given
1368 * connection, after translating it. A newline is automatically appended; the
1369 * format should not end with a newline.
1372 libpq_append_conn_error(PGconn
*conn
, const char *fmt
,...)
1374 int save_errno
= errno
;
1378 Assert(fmt
[strlen(fmt
) - 1] != '\n');
1380 if (PQExpBufferBroken(&conn
->errorMessage
))
1381 return; /* already failed */
1383 /* Loop in case we have to retry after enlarging the buffer. */
1387 va_start(args
, fmt
);
1388 done
= appendPQExpBufferVA(&conn
->errorMessage
, libpq_gettext(fmt
), args
);
1392 appendPQExpBufferChar(&conn
->errorMessage
, '\n');