PostgreSQL Source Code  git master
fe-misc.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * FILE
4  * fe-misc.c
5  *
6  * DESCRIPTION
7  * miscellaneous useful functions
8  *
9  * The communication routines here are analogous to the ones in
10  * backend/libpq/pqcomm.c and backend/libpq/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.
14  *
15  * XXX: MOVE DEBUG PRINTOUT TO HIGHER LEVEL. As is, block and restart
16  * will cause repeat printouts.
17  *
18  * We must speak the same transmitted data representations as the backend
19  * routines.
20  *
21  *
22  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
23  * Portions Copyright (c) 1994, Regents of the University of California
24  *
25  * IDENTIFICATION
26  * src/interfaces/libpq/fe-misc.c
27  *
28  *-------------------------------------------------------------------------
29  */
30 
31 #include "postgres_fe.h"
32 
33 #include <signal.h>
34 #include <time.h>
35 
36 #ifdef WIN32
37 #include "win32.h"
38 #else
39 #include <unistd.h>
40 #include <sys/time.h>
41 #endif
42 
43 #ifdef HAVE_POLL_H
44 #include <poll.h>
45 #endif
46 #ifdef HAVE_SYS_SELECT_H
47 #include <sys/select.h>
48 #endif
49 
50 #include "libpq-fe.h"
51 #include "libpq-int.h"
52 #include "mb/pg_wchar.h"
53 #include "pg_config_paths.h"
54 #include "port/pg_bswap.h"
55 
56 static int pqPutMsgBytes(const void *buf, size_t len, PGconn *conn);
57 static int pqSendSome(PGconn *conn, int len);
58 static int pqSocketCheck(PGconn *conn, int forRead, int forWrite,
59  time_t end_time);
60 static int pqSocketPoll(int sock, int forRead, int forWrite, time_t end_time);
61 
62 /*
63  * PQlibVersion: return the libpq version number
64  */
65 int
67 {
68  return PG_VERSION_NUM;
69 }
70 
71 
72 /*
73  * pqGetc: get 1 character from the connection
74  *
75  * All these routines return 0 on success, EOF on error.
76  * Note that for the Get routines, EOF only means there is not enough
77  * data in the buffer, not that there is necessarily a hard error.
78  */
79 int
80 pqGetc(char *result, PGconn *conn)
81 {
82  if (conn->inCursor >= conn->inEnd)
83  return EOF;
84 
85  *result = conn->inBuffer[conn->inCursor++];
86 
87  return 0;
88 }
89 
90 
91 /*
92  * pqPutc: write 1 char to the current message
93  */
94 int
96 {
97  if (pqPutMsgBytes(&c, 1, conn))
98  return EOF;
99 
100  return 0;
101 }
102 
103 
104 /*
105  * pqGets[_append]:
106  * get a null-terminated string from the connection,
107  * and store it in an expansible PQExpBuffer.
108  * If we run out of memory, all of the string is still read,
109  * but the excess characters are silently discarded.
110  */
111 static int
113 {
114  /* Copy conn data to locals for faster search loop */
115  char *inBuffer = conn->inBuffer;
116  int inCursor = conn->inCursor;
117  int inEnd = conn->inEnd;
118  int slen;
119 
120  while (inCursor < inEnd && inBuffer[inCursor])
121  inCursor++;
122 
123  if (inCursor >= inEnd)
124  return EOF;
125 
126  slen = inCursor - conn->inCursor;
127 
128  if (resetbuffer)
130 
131  appendBinaryPQExpBuffer(buf, inBuffer + conn->inCursor, slen);
132 
133  conn->inCursor = ++inCursor;
134 
135  return 0;
136 }
137 
138 int
140 {
141  return pqGets_internal(buf, conn, true);
142 }
143 
144 int
146 {
147  return pqGets_internal(buf, conn, false);
148 }
149 
150 
151 /*
152  * pqPuts: write a null-terminated string to the current message
153  */
154 int
155 pqPuts(const char *s, PGconn *conn)
156 {
157  if (pqPutMsgBytes(s, strlen(s) + 1, conn))
158  return EOF;
159 
160  return 0;
161 }
162 
163 /*
164  * pqGetnchar:
165  * get a string of exactly len bytes in buffer s, no null termination
166  */
167 int
168 pqGetnchar(char *s, size_t len, PGconn *conn)
169 {
170  if (len > (size_t) (conn->inEnd - conn->inCursor))
171  return EOF;
172 
173  memcpy(s, conn->inBuffer + conn->inCursor, len);
174  /* no terminating null */
175 
176  conn->inCursor += len;
177 
178  return 0;
179 }
180 
181 /*
182  * pqSkipnchar:
183  * skip over len bytes in input buffer.
184  *
185  * Note: this is primarily useful for its debug output, which should
186  * be exactly the same as for pqGetnchar. We assume the data in question
187  * will actually be used, but just isn't getting copied anywhere as yet.
188  */
189 int
191 {
192  if (len > (size_t) (conn->inEnd - conn->inCursor))
193  return EOF;
194 
195  conn->inCursor += len;
196 
197  return 0;
198 }
199 
200 /*
201  * pqPutnchar:
202  * write exactly len bytes to the current message
203  */
204 int
205 pqPutnchar(const char *s, size_t len, PGconn *conn)
206 {
207  if (pqPutMsgBytes(s, len, conn))
208  return EOF;
209 
210  return 0;
211 }
212 
213 /*
214  * pqGetInt
215  * read a 2 or 4 byte integer and convert from network byte order
216  * to local byte order
217  */
218 int
219 pqGetInt(int *result, size_t bytes, PGconn *conn)
220 {
221  uint16 tmp2;
222  uint32 tmp4;
223 
224  switch (bytes)
225  {
226  case 2:
227  if (conn->inCursor + 2 > conn->inEnd)
228  return EOF;
229  memcpy(&tmp2, conn->inBuffer + conn->inCursor, 2);
230  conn->inCursor += 2;
231  *result = (int) pg_ntoh16(tmp2);
232  break;
233  case 4:
234  if (conn->inCursor + 4 > conn->inEnd)
235  return EOF;
236  memcpy(&tmp4, conn->inBuffer + conn->inCursor, 4);
237  conn->inCursor += 4;
238  *result = (int) pg_ntoh32(tmp4);
239  break;
240  default:
242  "integer of size %lu not supported by pqGetInt",
243  (unsigned long) bytes);
244  return EOF;
245  }
246 
247  return 0;
248 }
249 
250 /*
251  * pqPutInt
252  * write an integer of 2 or 4 bytes, converting from host byte order
253  * to network byte order.
254  */
255 int
256 pqPutInt(int value, size_t bytes, PGconn *conn)
257 {
258  uint16 tmp2;
259  uint32 tmp4;
260 
261  switch (bytes)
262  {
263  case 2:
264  tmp2 = pg_hton16((uint16) value);
265  if (pqPutMsgBytes((const char *) &tmp2, 2, conn))
266  return EOF;
267  break;
268  case 4:
269  tmp4 = pg_hton32((uint32) value);
270  if (pqPutMsgBytes((const char *) &tmp4, 4, conn))
271  return EOF;
272  break;
273  default:
275  "integer of size %lu not supported by pqPutInt",
276  (unsigned long) bytes);
277  return EOF;
278  }
279 
280  return 0;
281 }
282 
283 /*
284  * Make sure conn's output buffer can hold bytes_needed bytes (caller must
285  * include already-stored data into the value!)
286  *
287  * Returns 0 on success, EOF if failed to enlarge buffer
288  */
289 int
290 pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
291 {
292  int newsize = conn->outBufSize;
293  char *newbuf;
294 
295  /* Quick exit if we have enough space */
296  if (bytes_needed <= (size_t) newsize)
297  return 0;
298 
299  /*
300  * If we need to enlarge the buffer, we first try to double it in size; if
301  * that doesn't work, enlarge in multiples of 8K. This avoids thrashing
302  * the malloc pool by repeated small enlargements.
303  *
304  * Note: tests for newsize > 0 are to catch integer overflow.
305  */
306  do
307  {
308  newsize *= 2;
309  } while (newsize > 0 && bytes_needed > (size_t) newsize);
310 
311  if (newsize > 0 && bytes_needed <= (size_t) newsize)
312  {
313  newbuf = realloc(conn->outBuffer, newsize);
314  if (newbuf)
315  {
316  /* realloc succeeded */
317  conn->outBuffer = newbuf;
318  conn->outBufSize = newsize;
319  return 0;
320  }
321  }
322 
323  newsize = conn->outBufSize;
324  do
325  {
326  newsize += 8192;
327  } while (newsize > 0 && bytes_needed > (size_t) newsize);
328 
329  if (newsize > 0 && bytes_needed <= (size_t) newsize)
330  {
331  newbuf = realloc(conn->outBuffer, newsize);
332  if (newbuf)
333  {
334  /* realloc succeeded */
335  conn->outBuffer = newbuf;
336  conn->outBufSize = newsize;
337  return 0;
338  }
339  }
340 
341  /* realloc failed. Probably out of memory */
343  "cannot allocate memory for output buffer\n");
344  return EOF;
345 }
346 
347 /*
348  * Make sure conn's input buffer can hold bytes_needed bytes (caller must
349  * include already-stored data into the value!)
350  *
351  * Returns 0 on success, EOF if failed to enlarge buffer
352  */
353 int
354 pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
355 {
356  int newsize = conn->inBufSize;
357  char *newbuf;
358 
359  /* Quick exit if we have enough space */
360  if (bytes_needed <= (size_t) newsize)
361  return 0;
362 
363  /*
364  * Before concluding that we need to enlarge the buffer, left-justify
365  * whatever is in it and recheck. The caller's value of bytes_needed
366  * includes any data to the left of inStart, but we can delete that in
367  * preference to enlarging the buffer. It's slightly ugly to have this
368  * function do this, but it's better than making callers worry about it.
369  */
370  bytes_needed -= conn->inStart;
371 
372  if (conn->inStart < conn->inEnd)
373  {
374  if (conn->inStart > 0)
375  {
376  memmove(conn->inBuffer, conn->inBuffer + conn->inStart,
377  conn->inEnd - conn->inStart);
378  conn->inEnd -= conn->inStart;
379  conn->inCursor -= conn->inStart;
380  conn->inStart = 0;
381  }
382  }
383  else
384  {
385  /* buffer is logically empty, reset it */
386  conn->inStart = conn->inCursor = conn->inEnd = 0;
387  }
388 
389  /* Recheck whether we have enough space */
390  if (bytes_needed <= (size_t) newsize)
391  return 0;
392 
393  /*
394  * If we need to enlarge the buffer, we first try to double it in size; if
395  * that doesn't work, enlarge in multiples of 8K. This avoids thrashing
396  * the malloc pool by repeated small enlargements.
397  *
398  * Note: tests for newsize > 0 are to catch integer overflow.
399  */
400  do
401  {
402  newsize *= 2;
403  } while (newsize > 0 && bytes_needed > (size_t) newsize);
404 
405  if (newsize > 0 && bytes_needed <= (size_t) newsize)
406  {
407  newbuf = realloc(conn->inBuffer, newsize);
408  if (newbuf)
409  {
410  /* realloc succeeded */
411  conn->inBuffer = newbuf;
412  conn->inBufSize = newsize;
413  return 0;
414  }
415  }
416 
417  newsize = conn->inBufSize;
418  do
419  {
420  newsize += 8192;
421  } while (newsize > 0 && bytes_needed > (size_t) newsize);
422 
423  if (newsize > 0 && bytes_needed <= (size_t) newsize)
424  {
425  newbuf = realloc(conn->inBuffer, newsize);
426  if (newbuf)
427  {
428  /* realloc succeeded */
429  conn->inBuffer = newbuf;
430  conn->inBufSize = newsize;
431  return 0;
432  }
433  }
434 
435  /* realloc failed. Probably out of memory */
437  "cannot allocate memory for input buffer\n");
438  return EOF;
439 }
440 
441 /*
442  * pqPutMsgStart: begin construction of a message to the server
443  *
444  * msg_type is the message type byte, or 0 for a message without type byte
445  * (only startup messages have no type byte)
446  *
447  * Returns 0 on success, EOF on error
448  *
449  * The idea here is that we construct the message in conn->outBuffer,
450  * beginning just past any data already in outBuffer (ie, at
451  * outBuffer+outCount). We enlarge the buffer as needed to hold the message.
452  * When the message is complete, we fill in the length word (if needed) and
453  * then advance outCount past the message, making it eligible to send.
454  *
455  * The state variable conn->outMsgStart points to the incomplete message's
456  * length word: it is either outCount or outCount+1 depending on whether
457  * there is a type byte. The state variable conn->outMsgEnd is the end of
458  * the data collected so far.
459  */
460 int
461 pqPutMsgStart(char msg_type, PGconn *conn)
462 {
463  int lenPos;
464  int endPos;
465 
466  /* allow room for message type byte */
467  if (msg_type)
468  endPos = conn->outCount + 1;
469  else
470  endPos = conn->outCount;
471 
472  /* do we want a length word? */
473  lenPos = endPos;
474  /* allow room for message length */
475  endPos += 4;
476 
477  /* make sure there is room for message header */
478  if (pqCheckOutBufferSpace(endPos, conn))
479  return EOF;
480  /* okay, save the message type byte if any */
481  if (msg_type)
482  conn->outBuffer[conn->outCount] = msg_type;
483  /* set up the message pointers */
484  conn->outMsgStart = lenPos;
485  conn->outMsgEnd = endPos;
486  /* length word, if needed, will be filled in by pqPutMsgEnd */
487 
488  return 0;
489 }
490 
491 /*
492  * pqPutMsgBytes: add bytes to a partially-constructed message
493  *
494  * Returns 0 on success, EOF on error
495  */
496 static int
497 pqPutMsgBytes(const void *buf, size_t len, PGconn *conn)
498 {
499  /* make sure there is room for it */
501  return EOF;
502  /* okay, save the data */
503  memcpy(conn->outBuffer + conn->outMsgEnd, buf, len);
504  conn->outMsgEnd += len;
505  /* no Pfdebug call here, caller should do it */
506  return 0;
507 }
508 
509 /*
510  * pqPutMsgEnd: finish constructing a message and possibly send it
511  *
512  * Returns 0 on success, EOF on error
513  *
514  * We don't actually send anything here unless we've accumulated at least
515  * 8K worth of data (the typical size of a pipe buffer on Unix systems).
516  * This avoids sending small partial packets. The caller must use pqFlush
517  * when it's important to flush all the data out to the server.
518  */
519 int
521 {
522  /* Fill in length word if needed */
523  if (conn->outMsgStart >= 0)
524  {
525  uint32 msgLen = conn->outMsgEnd - conn->outMsgStart;
526 
527  msgLen = pg_hton32(msgLen);
528  memcpy(conn->outBuffer + conn->outMsgStart, &msgLen, 4);
529  }
530 
531  /* trace client-to-server message */
532  if (conn->Pfdebug)
533  {
534  if (conn->outCount < conn->outMsgStart)
536  else
539  }
540 
541  /* Make message eligible to send */
543 
544  if (conn->outCount >= 8192)
545  {
546  int toSend = conn->outCount - (conn->outCount % 8192);
547 
548  if (pqSendSome(conn, toSend) < 0)
549  return EOF;
550  /* in nonblock mode, don't complain if unable to send it all */
551  }
552 
553  return 0;
554 }
555 
556 /* ----------
557  * pqReadData: read more data, if any is available
558  * Possible return values:
559  * 1: successfully loaded at least one more byte
560  * 0: no data is presently available, but no error detected
561  * -1: error detected (including EOF = connection closure);
562  * conn->errorMessage set
563  * NOTE: callers must not assume that pointers or indexes into conn->inBuffer
564  * remain valid across this call!
565  * ----------
566  */
567 int
569 {
570  int someread = 0;
571  int nread;
572 
573  if (conn->sock == PGINVALID_SOCKET)
574  {
576  libpq_gettext("connection not open\n"));
577  return -1;
578  }
579 
580  /* Left-justify any data in the buffer to make room */
581  if (conn->inStart < conn->inEnd)
582  {
583  if (conn->inStart > 0)
584  {
585  memmove(conn->inBuffer, conn->inBuffer + conn->inStart,
586  conn->inEnd - conn->inStart);
587  conn->inEnd -= conn->inStart;
588  conn->inCursor -= conn->inStart;
589  conn->inStart = 0;
590  }
591  }
592  else
593  {
594  /* buffer is logically empty, reset it */
595  conn->inStart = conn->inCursor = conn->inEnd = 0;
596  }
597 
598  /*
599  * If the buffer is fairly full, enlarge it. We need to be able to enlarge
600  * the buffer in case a single message exceeds the initial buffer size. We
601  * enlarge before filling the buffer entirely so as to avoid asking the
602  * kernel for a partial packet. The magic constant here should be large
603  * enough for a TCP packet or Unix pipe bufferload. 8K is the usual pipe
604  * buffer size, so...
605  */
606  if (conn->inBufSize - conn->inEnd < 8192)
607  {
608  if (pqCheckInBufferSpace(conn->inEnd + (size_t) 8192, conn))
609  {
610  /*
611  * We don't insist that the enlarge worked, but we need some room
612  */
613  if (conn->inBufSize - conn->inEnd < 100)
614  return -1; /* errorMessage already set */
615  }
616  }
617 
618  /* OK, try to read some data */
619 retry3:
620  nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
621  conn->inBufSize - conn->inEnd);
622  if (nread < 0)
623  {
624  switch (SOCK_ERRNO)
625  {
626  case EINTR:
627  goto retry3;
628 
629  /* Some systems return EAGAIN/EWOULDBLOCK for no data */
630 #ifdef EAGAIN
631  case EAGAIN:
632  return someread;
633 #endif
634 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
635  case EWOULDBLOCK:
636  return someread;
637 #endif
638 
639  /* We might get ECONNRESET etc here if connection failed */
641  goto definitelyFailed;
642 
643  default:
644  /* pqsecure_read set the error message for us */
645  return -1;
646  }
647  }
648  if (nread > 0)
649  {
650  conn->inEnd += nread;
651 
652  /*
653  * Hack to deal with the fact that some kernels will only give us back
654  * 1 packet per recv() call, even if we asked for more and there is
655  * more available. If it looks like we are reading a long message,
656  * loop back to recv() again immediately, until we run out of data or
657  * buffer space. Without this, the block-and-restart behavior of
658  * libpq's higher levels leads to O(N^2) performance on long messages.
659  *
660  * Since we left-justified the data above, conn->inEnd gives the
661  * amount of data already read in the current message. We consider
662  * the message "long" once we have acquired 32k ...
663  */
664  if (conn->inEnd > 32768 &&
665  (conn->inBufSize - conn->inEnd) >= 8192)
666  {
667  someread = 1;
668  goto retry3;
669  }
670  return 1;
671  }
672 
673  if (someread)
674  return 1; /* got a zero read after successful tries */
675 
676  /*
677  * A return value of 0 could mean just that no data is now available, or
678  * it could mean EOF --- that is, the server has closed the connection.
679  * Since we have the socket in nonblock mode, the only way to tell the
680  * difference is to see if select() is saying that the file is ready.
681  * Grumble. Fortunately, we don't expect this path to be taken much,
682  * since in normal practice we should not be trying to read data unless
683  * the file selected for reading already.
684  *
685  * In SSL mode it's even worse: SSL_read() could say WANT_READ and then
686  * data could arrive before we make the pqReadReady() test, but the second
687  * SSL_read() could still say WANT_READ because the data received was not
688  * a complete SSL record. So we must play dumb and assume there is more
689  * data, relying on the SSL layer to detect true EOF.
690  */
691 
692 #ifdef USE_SSL
693  if (conn->ssl_in_use)
694  return 0;
695 #endif
696 
697  switch (pqReadReady(conn))
698  {
699  case 0:
700  /* definitely no data available */
701  return 0;
702  case 1:
703  /* ready for read */
704  break;
705  default:
706  /* we override pqReadReady's message with something more useful */
707  goto definitelyEOF;
708  }
709 
710  /*
711  * Still not sure that it's EOF, because some data could have just
712  * arrived.
713  */
714 retry4:
715  nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
716  conn->inBufSize - conn->inEnd);
717  if (nread < 0)
718  {
719  switch (SOCK_ERRNO)
720  {
721  case EINTR:
722  goto retry4;
723 
724  /* Some systems return EAGAIN/EWOULDBLOCK for no data */
725 #ifdef EAGAIN
726  case EAGAIN:
727  return 0;
728 #endif
729 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
730  case EWOULDBLOCK:
731  return 0;
732 #endif
733 
734  /* We might get ECONNRESET etc here if connection failed */
736  goto definitelyFailed;
737 
738  default:
739  /* pqsecure_read set the error message for us */
740  return -1;
741  }
742  }
743  if (nread > 0)
744  {
745  conn->inEnd += nread;
746  return 1;
747  }
748 
749  /*
750  * OK, we are getting a zero read even though select() says ready. This
751  * means the connection has been closed. Cope.
752  */
753 definitelyEOF:
755  libpq_gettext("server closed the connection unexpectedly\n"
756  "\tThis probably means the server terminated abnormally\n"
757  "\tbefore or while processing the request.\n"));
758 
759  /* Come here if lower-level code already set a suitable errorMessage */
760 definitelyFailed:
761  /* Do *not* drop any already-read data; caller still wants it */
762  pqDropConnection(conn, false);
763  conn->status = CONNECTION_BAD; /* No more connection to backend */
764  return -1;
765 }
766 
767 /*
768  * pqSendSome: send data waiting in the output buffer.
769  *
770  * len is how much to try to send (typically equal to outCount, but may
771  * be less).
772  *
773  * Return 0 on success, -1 on failure and 1 when not all data could be sent
774  * because the socket would block and the connection is non-blocking.
775  *
776  * Note that this is also responsible for consuming data from the socket
777  * (putting it in conn->inBuffer) in any situation where we can't send
778  * all the specified data immediately.
779  *
780  * If a socket-level write failure occurs, conn->write_failed is set and the
781  * error message is saved in conn->write_err_msg, but we clear the output
782  * buffer and return zero anyway; this is because callers should soldier on
783  * until we have read what we can from the server and checked for an error
784  * message. write_err_msg should be reported only when we are unable to
785  * obtain a server error first. Much of that behavior is implemented at
786  * lower levels, but this function deals with some edge cases.
787  */
788 static int
790 {
791  char *ptr = conn->outBuffer;
792  int remaining = conn->outCount;
793  int result = 0;
794 
795  /*
796  * If we already had a write failure, we will never again try to send data
797  * on that connection. Even if the kernel would let us, we've probably
798  * lost message boundary sync with the server. conn->write_failed
799  * therefore persists until the connection is reset, and we just discard
800  * all data presented to be written. However, as long as we still have a
801  * valid socket, we should continue to absorb data from the backend, so
802  * that we can collect any final error messages.
803  */
804  if (conn->write_failed)
805  {
806  /* conn->write_err_msg should be set up already */
807  conn->outCount = 0;
808  /* Absorb input data if any, and detect socket closure */
809  if (conn->sock != PGINVALID_SOCKET)
810  {
811  if (pqReadData(conn) < 0)
812  return -1;
813  }
814  return 0;
815  }
816 
817  if (conn->sock == PGINVALID_SOCKET)
818  {
819  conn->write_failed = true;
820  /* Store error message in conn->write_err_msg, if possible */
821  /* (strdup failure is OK, we'll cope later) */
822  conn->write_err_msg = strdup(libpq_gettext("connection not open\n"));
823  /* Discard queued data; no chance it'll ever be sent */
824  conn->outCount = 0;
825  return 0;
826  }
827 
828  /* while there's still data to send */
829  while (len > 0)
830  {
831  int sent;
832 
833 #ifndef WIN32
834  sent = pqsecure_write(conn, ptr, len);
835 #else
836 
837  /*
838  * Windows can fail on large sends, per KB article Q201213. The
839  * failure-point appears to be different in different versions of
840  * Windows, but 64k should always be safe.
841  */
842  sent = pqsecure_write(conn, ptr, Min(len, 65536));
843 #endif
844 
845  if (sent < 0)
846  {
847  /* Anything except EAGAIN/EWOULDBLOCK/EINTR is trouble */
848  switch (SOCK_ERRNO)
849  {
850 #ifdef EAGAIN
851  case EAGAIN:
852  break;
853 #endif
854 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
855  case EWOULDBLOCK:
856  break;
857 #endif
858  case EINTR:
859  continue;
860 
861  default:
862  /* Discard queued data; no chance it'll ever be sent */
863  conn->outCount = 0;
864 
865  /* Absorb input data if any, and detect socket closure */
866  if (conn->sock != PGINVALID_SOCKET)
867  {
868  if (pqReadData(conn) < 0)
869  return -1;
870  }
871 
872  /*
873  * Lower-level code should already have filled
874  * conn->write_err_msg (and set conn->write_failed) or
875  * conn->errorMessage. In the former case, we pretend
876  * there's no problem; the write_failed condition will be
877  * dealt with later. Otherwise, report the error now.
878  */
879  if (conn->write_failed)
880  return 0;
881  else
882  return -1;
883  }
884  }
885  else
886  {
887  ptr += sent;
888  len -= sent;
889  remaining -= sent;
890  }
891 
892  if (len > 0)
893  {
894  /*
895  * We didn't send it all, wait till we can send more.
896  *
897  * There are scenarios in which we can't send data because the
898  * communications channel is full, but we cannot expect the server
899  * to clear the channel eventually because it's blocked trying to
900  * send data to us. (This can happen when we are sending a large
901  * amount of COPY data, and the server has generated lots of
902  * NOTICE responses.) To avoid a deadlock situation, we must be
903  * prepared to accept and buffer incoming data before we try
904  * again. Furthermore, it is possible that such incoming data
905  * might not arrive until after we've gone to sleep. Therefore,
906  * we wait for either read ready or write ready.
907  *
908  * In non-blocking mode, we don't wait here directly, but return 1
909  * to indicate that data is still pending. The caller should wait
910  * for both read and write ready conditions, and call
911  * PQconsumeInput() on read ready, but just in case it doesn't, we
912  * call pqReadData() ourselves before returning. That's not
913  * enough if the data has not arrived yet, but it's the best we
914  * can do, and works pretty well in practice. (The documentation
915  * used to say that you only need to wait for write-ready, so
916  * there are still plenty of applications like that out there.)
917  *
918  * Note that errors here don't result in write_failed becoming
919  * set.
920  */
921  if (pqReadData(conn) < 0)
922  {
923  result = -1; /* error message already set up */
924  break;
925  }
926 
927  if (pqIsnonblocking(conn))
928  {
929  result = 1;
930  break;
931  }
932 
933  if (pqWait(true, true, conn))
934  {
935  result = -1;
936  break;
937  }
938  }
939  }
940 
941  /* shift the remaining contents of the buffer */
942  if (remaining > 0)
943  memmove(conn->outBuffer, ptr, remaining);
945 
946  return result;
947 }
948 
949 
950 /*
951  * pqFlush: send any data waiting in the output buffer
952  *
953  * Return 0 on success, -1 on failure and 1 when not all data could be sent
954  * because the socket would block and the connection is non-blocking.
955  * (See pqSendSome comments about how failure should be handled.)
956  */
957 int
959 {
960  if (conn->outCount > 0)
961  {
962  if (conn->Pfdebug)
963  fflush(conn->Pfdebug);
964 
965  return pqSendSome(conn, conn->outCount);
966  }
967 
968  return 0;
969 }
970 
971 
972 /*
973  * pqWait: wait until we can read or write the connection socket
974  *
975  * JAB: If SSL enabled and used and forRead, buffered bytes short-circuit the
976  * call to select().
977  *
978  * We also stop waiting and return if the kernel flags an exception condition
979  * on the socket. The actual error condition will be detected and reported
980  * when the caller tries to read or write the socket.
981  */
982 int
983 pqWait(int forRead, int forWrite, PGconn *conn)
984 {
985  return pqWaitTimed(forRead, forWrite, conn, (time_t) -1);
986 }
987 
988 /*
989  * pqWaitTimed: wait, but not past finish_time.
990  *
991  * finish_time = ((time_t) -1) disables the wait limit.
992  *
993  * Returns -1 on failure, 0 if the socket is readable/writable, 1 if it timed out.
994  */
995 int
996 pqWaitTimed(int forRead, int forWrite, PGconn *conn, time_t finish_time)
997 {
998  int result;
999 
1000  result = pqSocketCheck(conn, forRead, forWrite, finish_time);
1001 
1002  if (result < 0)
1003  return -1; /* errorMessage is already set */
1004 
1005  if (result == 0)
1006  {
1008  libpq_gettext("timeout expired\n"));
1009  return 1;
1010  }
1011 
1012  return 0;
1013 }
1014 
1015 /*
1016  * pqReadReady: is select() saying the file is ready to read?
1017  * Returns -1 on failure, 0 if not ready, 1 if ready.
1018  */
1019 int
1021 {
1022  return pqSocketCheck(conn, 1, 0, (time_t) 0);
1023 }
1024 
1025 /*
1026  * pqWriteReady: is select() saying the file is ready to write?
1027  * Returns -1 on failure, 0 if not ready, 1 if ready.
1028  */
1029 int
1031 {
1032  return pqSocketCheck(conn, 0, 1, (time_t) 0);
1033 }
1034 
1035 /*
1036  * Checks a socket, using poll or select, for data to be read, written,
1037  * or both. Returns >0 if one or more conditions are met, 0 if it timed
1038  * out, -1 if an error occurred.
1039  *
1040  * If SSL is in use, the SSL buffer is checked prior to checking the socket
1041  * for read data directly.
1042  */
1043 static int
1044 pqSocketCheck(PGconn *conn, int forRead, int forWrite, time_t end_time)
1045 {
1046  int result;
1047 
1048  if (!conn)
1049  return -1;
1050  if (conn->sock == PGINVALID_SOCKET)
1051  {
1053  libpq_gettext("invalid socket\n"));
1054  return -1;
1055  }
1056 
1057 #ifdef USE_SSL
1058  /* Check for SSL library buffering read bytes */
1059  if (forRead && conn->ssl_in_use && pgtls_read_pending(conn))
1060  {
1061  /* short-circuit the select */
1062  return 1;
1063  }
1064 #endif
1065 
1066  /* We will retry as long as we get EINTR */
1067  do
1068  result = pqSocketPoll(conn->sock, forRead, forWrite, end_time);
1069  while (result < 0 && SOCK_ERRNO == EINTR);
1070 
1071  if (result < 0)
1072  {
1073  char sebuf[PG_STRERROR_R_BUFLEN];
1074 
1076  libpq_gettext("%s() failed: %s\n"),
1077  "select",
1078  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1079  }
1080 
1081  return result;
1082 }
1083 
1084 
1085 /*
1086  * Check a file descriptor for read and/or write data, possibly waiting.
1087  * If neither forRead nor forWrite are set, immediately return a timeout
1088  * condition (without waiting). Return >0 if condition is met, 0
1089  * if a timeout occurred, -1 if an error or interrupt occurred.
1090  *
1091  * Timeout is infinite if end_time is -1. Timeout is immediate (no blocking)
1092  * if end_time is 0 (or indeed, any time before now).
1093  */
1094 static int
1095 pqSocketPoll(int sock, int forRead, int forWrite, time_t end_time)
1096 {
1097  /* We use poll(2) if available, otherwise select(2) */
1098 #ifdef HAVE_POLL
1099  struct pollfd input_fd;
1100  int timeout_ms;
1101 
1102  if (!forRead && !forWrite)
1103  return 0;
1104 
1105  input_fd.fd = sock;
1106  input_fd.events = POLLERR;
1107  input_fd.revents = 0;
1108 
1109  if (forRead)
1110  input_fd.events |= POLLIN;
1111  if (forWrite)
1112  input_fd.events |= POLLOUT;
1113 
1114  /* Compute appropriate timeout interval */
1115  if (end_time == ((time_t) -1))
1116  timeout_ms = -1;
1117  else
1118  {
1119  time_t now = time(NULL);
1120 
1121  if (end_time > now)
1122  timeout_ms = (end_time - now) * 1000;
1123  else
1124  timeout_ms = 0;
1125  }
1126 
1127  return poll(&input_fd, 1, timeout_ms);
1128 #else /* !HAVE_POLL */
1129 
1130  fd_set input_mask;
1131  fd_set output_mask;
1132  fd_set except_mask;
1133  struct timeval timeout;
1134  struct timeval *ptr_timeout;
1135 
1136  if (!forRead && !forWrite)
1137  return 0;
1138 
1139  FD_ZERO(&input_mask);
1140  FD_ZERO(&output_mask);
1141  FD_ZERO(&except_mask);
1142  if (forRead)
1143  FD_SET(sock, &input_mask);
1144 
1145  if (forWrite)
1146  FD_SET(sock, &output_mask);
1147  FD_SET(sock, &except_mask);
1148 
1149  /* Compute appropriate timeout interval */
1150  if (end_time == ((time_t) -1))
1151  ptr_timeout = NULL;
1152  else
1153  {
1154  time_t now = time(NULL);
1155 
1156  if (end_time > now)
1157  timeout.tv_sec = end_time - now;
1158  else
1159  timeout.tv_sec = 0;
1160  timeout.tv_usec = 0;
1161  ptr_timeout = &timeout;
1162  }
1163 
1164  return select(sock + 1, &input_mask, &output_mask,
1165  &except_mask, ptr_timeout);
1166 #endif /* HAVE_POLL */
1167 }
1168 
1169 
1170 /*
1171  * A couple of "miscellaneous" multibyte related functions. They used
1172  * to be in fe-print.c but that file is doomed.
1173  */
1174 
1175 /*
1176  * Returns the byte length of the character beginning at s, using the
1177  * specified encoding.
1178  *
1179  * Caution: when dealing with text that is not certainly valid in the
1180  * specified encoding, the result may exceed the actual remaining
1181  * string length. Callers that are not prepared to deal with that
1182  * should use PQmblenBounded() instead.
1183  */
1184 int
1185 PQmblen(const char *s, int encoding)
1186 {
1187  return pg_encoding_mblen(encoding, s);
1188 }
1189 
1190 /*
1191  * Returns the byte length of the character beginning at s, using the
1192  * specified encoding; but not more than the distance to end of string.
1193  */
1194 int
1195 PQmblenBounded(const char *s, int encoding)
1196 {
1197  return strnlen(s, pg_encoding_mblen(encoding, s));
1198 }
1199 
1200 /*
1201  * Returns the display length of the character beginning at s, using the
1202  * specified encoding.
1203  */
1204 int
1205 PQdsplen(const char *s, int encoding)
1206 {
1207  return pg_encoding_dsplen(encoding, s);
1208 }
1209 
1210 /*
1211  * Get encoding id from environment variable PGCLIENTENCODING.
1212  */
1213 int
1215 {
1216  char *str;
1217  int encoding = PG_SQL_ASCII;
1218 
1219  str = getenv("PGCLIENTENCODING");
1220  if (str && *str != '\0')
1221  {
1223  if (encoding < 0)
1225  }
1226  return encoding;
1227 }
1228 
1229 
1230 #ifdef ENABLE_NLS
1231 
1232 static void
1233 libpq_binddomain(void)
1234 {
1235  /*
1236  * If multiple threads come through here at about the same time, it's okay
1237  * for more than one of them to call bindtextdomain(). But it's not okay
1238  * for any of them to return to caller before bindtextdomain() is
1239  * complete, so don't set the flag till that's done. Use "volatile" just
1240  * to be sure the compiler doesn't try to get cute.
1241  */
1242  static volatile bool already_bound = false;
1243 
1244  if (!already_bound)
1245  {
1246  /* bindtextdomain() does not preserve errno */
1247 #ifdef WIN32
1248  int save_errno = GetLastError();
1249 #else
1250  int save_errno = errno;
1251 #endif
1252  const char *ldir;
1253 
1254  /* No relocatable lookup here because the binary could be anywhere */
1255  ldir = getenv("PGLOCALEDIR");
1256  if (!ldir)
1257  ldir = LOCALEDIR;
1258  bindtextdomain(PG_TEXTDOMAIN("libpq"), ldir);
1259  already_bound = true;
1260 #ifdef WIN32
1261  SetLastError(save_errno);
1262 #else
1263  errno = save_errno;
1264 #endif
1265  }
1266 }
1267 
1268 char *
1269 libpq_gettext(const char *msgid)
1270 {
1271  libpq_binddomain();
1272  return dgettext(PG_TEXTDOMAIN("libpq"), msgid);
1273 }
1274 
1275 char *
1276 libpq_ngettext(const char *msgid, const char *msgid_plural, unsigned long n)
1277 {
1278  libpq_binddomain();
1279  return dngettext(PG_TEXTDOMAIN("libpq"), msgid, msgid_plural, n);
1280 }
1281 
1282 #endif /* ENABLE_NLS */
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538
unsigned short uint16
Definition: c.h:451
unsigned int uint32
Definition: c.h:452
#define Min(x, y)
Definition: c.h:997
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1223
#define dngettext(d, s, p, n)
Definition: c.h:1191
#define dgettext(d, x)
Definition: c.h:1189
int pg_char_to_encoding(const char *name)
Definition: encnames.c:550
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:449
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:939
int pqPutc(char c, PGconn *conn)
Definition: fe-misc.c:95
int pqReadData(PGconn *conn)
Definition: fe-misc.c:568
int pqPutInt(int value, size_t bytes, PGconn *conn)
Definition: fe-misc.c:256
int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:290
int pqFlush(PGconn *conn)
Definition: fe-misc.c:958
int pqReadReady(PGconn *conn)
Definition: fe-misc.c:1020
int PQenv2encoding(void)
Definition: fe-misc.c:1214
int pqPutMsgStart(char msg_type, PGconn *conn)
Definition: fe-misc.c:461
int pqSkipnchar(size_t len, PGconn *conn)
Definition: fe-misc.c:190
int pqGetc(char *result, PGconn *conn)
Definition: fe-misc.c:80
int PQlibVersion(void)
Definition: fe-misc.c:66
int pqGetInt(int *result, size_t bytes, PGconn *conn)
Definition: fe-misc.c:219
int pqGetnchar(char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:168
int PQmblen(const char *s, int encoding)
Definition: fe-misc.c:1185
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:983
int pqGets(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:139
int PQdsplen(const char *s, int encoding)
Definition: fe-misc.c:1205
static int pqSocketPoll(int sock, int forRead, int forWrite, time_t end_time)
Definition: fe-misc.c:1095
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:354
static int pqPutMsgBytes(const void *buf, size_t len, PGconn *conn)
Definition: fe-misc.c:497
int pqPutnchar(const char *s, size_t len, PGconn *conn)
Definition: fe-misc.c:205
static int pqSendSome(PGconn *conn, int len)
Definition: fe-misc.c:789
static int pqGets_internal(PQExpBuffer buf, PGconn *conn, bool resetbuffer)
Definition: fe-misc.c:112
int pqPuts(const char *s, PGconn *conn)
Definition: fe-misc.c:155
static int pqSocketCheck(PGconn *conn, int forRead, int forWrite, time_t end_time)
Definition: fe-misc.c:1044
int pqWaitTimed(int forRead, int forWrite, PGconn *conn, time_t finish_time)
Definition: fe-misc.c:996
int PQmblenBounded(const char *s, int encoding)
Definition: fe-misc.c:1195
int pqGets_append(PQExpBuffer buf, PGconn *conn)
Definition: fe-misc.c:145
int pqWriteReady(PGconn *conn)
Definition: fe-misc.c:1030
int pqPutMsgEnd(PGconn *conn)
Definition: fe-misc.c:520
bool pgtls_read_pending(PGconn *conn)
ssize_t pqsecure_write(PGconn *conn, const void *ptr, size_t len)
Definition: fe-secure.c:301
ssize_t pqsecure_read(PGconn *conn, void *ptr, size_t len)
Definition: fe-secure.c:206
void pqTraceOutputMessage(PGconn *conn, const char *message, bool toServer)
Definition: fe-trace.c:529
void pqTraceOutputNoTypeByteMessage(PGconn *conn, const char *message)
Definition: fe-trace.c:694
#define realloc(a, b)
Definition: header.h:60
static struct @151 value
int remaining
Definition: informix.c:667
@ CONNECTION_BAD
Definition: libpq-fe.h:61
#define libpq_gettext(x)
Definition: libpq-int.h:878
#define SOCK_STRERROR
Definition: libpq-int.h:892
#define SOCK_ERRNO
Definition: libpq-int.h:891
#define libpq_ngettext(s, p, n)
Definition: libpq-int.h:879
#define pqIsnonblocking(conn)
Definition: libpq-int.h:867
static void const char fflush(stdout)
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
#define pg_hton32(x)
Definition: pg_bswap.h:121
#define pg_hton16(x)
Definition: pg_bswap.h:120
#define pg_ntoh16(x)
Definition: pg_bswap.h:124
const void size_t len
int32 encoding
Definition: pg_database.h:41
static char * buf
Definition: pg_test_fsync.c:67
@ PG_SQL_ASCII
Definition: pg_wchar.h:224
int64 end_time
Definition: pgbench.c:188
#define PG_STRERROR_R_BUFLEN
Definition: port.h:243
#define ALL_CONNECTION_FAILURE_ERRNOS
Definition: port.h:117
#define PGINVALID_SOCKET
Definition: port.h:31
size_t strnlen(const char *str, size_t maxlen)
Definition: strnlen.c:26
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
void appendBinaryPQExpBuffer(PQExpBuffer str, const char *data, size_t datalen)
Definition: pqexpbuffer.c:399
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
char * c
PGconn * conn
Definition: streamutil.c:54
char * write_err_msg
Definition: libpq-int.h:455
pgsocket sock
Definition: libpq-int.h:444
char * inBuffer
Definition: libpq-int.h:479
bool write_failed
Definition: libpq-int.h:454
int inCursor
Definition: libpq-int.h:482
int inEnd
Definition: libpq-int.h:483
int inBufSize
Definition: libpq-int.h:480
int inStart
Definition: libpq-int.h:481
PQExpBufferData errorMessage
Definition: libpq-int.h:585
int outBufSize
Definition: libpq-int.h:487
PGNoticeHooks noticeHooks
Definition: libpq-int.h:402
FILE * Pfdebug
Definition: libpq-int.h:398
int outMsgStart
Definition: libpq-int.h:491
int outCount
Definition: libpq-int.h:488
int outMsgEnd
Definition: libpq-int.h:493
bool ssl_in_use
Definition: libpq-int.h:517
char * outBuffer
Definition: libpq-int.h:486
ConnStatusType status
Definition: libpq-int.h:410
int pg_encoding_dsplen(int encoding, const char *mbstr)
Definition: wchar.c:2150
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:2129
#define EINTR
Definition: win32_port.h:351
#define EWOULDBLOCK
Definition: win32_port.h:357
#define EAGAIN
Definition: win32_port.h:349
#define select(n, r, w, e, timeout)
Definition: win32_port.h:474