PostgreSQL Source Code  git master
fe-misc.c File Reference
#include "postgres_fe.h"
#include <signal.h>
#include <time.h>
#include <unistd.h>
#include "libpq-fe.h"
#include "libpq-int.h"
#include "mb/pg_wchar.h"
#include "pg_config_paths.h"
#include "port/pg_bswap.h"
Include dependency graph for fe-misc.c:

Go to the source code of this file.

Functions

static int pqPutMsgBytes (const void *buf, size_t len, PGconn *conn)
 
static int pqSendSome (PGconn *conn, int len)
 
static int pqSocketCheck (PGconn *conn, int forRead, int forWrite, time_t end_time)
 
static int pqSocketPoll (int sock, int forRead, int forWrite, time_t end_time)
 
int PQlibVersion (void)
 
int pqGetc (char *result, PGconn *conn)
 
int pqPutc (char c, PGconn *conn)
 
static int pqGets_internal (PQExpBuffer buf, PGconn *conn, bool resetbuffer)
 
int pqGets (PQExpBuffer buf, PGconn *conn)
 
int pqGets_append (PQExpBuffer buf, PGconn *conn)
 
int pqPuts (const char *s, PGconn *conn)
 
int pqGetnchar (char *s, size_t len, PGconn *conn)
 
int pqSkipnchar (size_t len, PGconn *conn)
 
int pqPutnchar (const char *s, size_t len, PGconn *conn)
 
int pqGetInt (int *result, size_t bytes, PGconn *conn)
 
int pqPutInt (int value, size_t bytes, PGconn *conn)
 
int pqCheckOutBufferSpace (size_t bytes_needed, PGconn *conn)
 
int pqCheckInBufferSpace (size_t bytes_needed, PGconn *conn)
 
int pqPutMsgStart (char msg_type, PGconn *conn)
 
int pqPutMsgEnd (PGconn *conn)
 
int pqReadData (PGconn *conn)
 
int pqFlush (PGconn *conn)
 
int pqWait (int forRead, int forWrite, PGconn *conn)
 
int pqWaitTimed (int forRead, int forWrite, PGconn *conn, time_t finish_time)
 
int pqReadReady (PGconn *conn)
 
int pqWriteReady (PGconn *conn)
 
int PQmblen (const char *s, int encoding)
 
int PQmblenBounded (const char *s, int encoding)
 
int PQdsplen (const char *s, int encoding)
 
int PQenv2encoding (void)
 

Function Documentation

◆ pqCheckInBufferSpace()

int pqCheckInBufferSpace ( size_t  bytes_needed,
PGconn conn 
)

Definition at line 354 of file fe-misc.c.

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 }
#define realloc(a, b)
Definition: header.h:60
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
PGconn * conn
Definition: streamutil.c:54
char * inBuffer
Definition: libpq-int.h:479
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

References appendPQExpBufferStr(), conn, pg_conn::errorMessage, pg_conn::inBuffer, pg_conn::inBufSize, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, and realloc.

Referenced by getCopyDataMessage(), PQconnectPoll(), pqFunctionCall3(), pqParseInput3(), and pqReadData().

◆ pqCheckOutBufferSpace()

int pqCheckOutBufferSpace ( size_t  bytes_needed,
PGconn conn 
)

Definition at line 290 of file fe-misc.c.

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 }
int outBufSize
Definition: libpq-int.h:487
char * outBuffer
Definition: libpq-int.h:486

References appendPQExpBufferStr(), conn, pg_conn::errorMessage, pg_conn::outBuffer, pg_conn::outBufSize, and realloc.

Referenced by PQputCopyData(), pqPutMsgBytes(), and pqPutMsgStart().

◆ PQdsplen()

int PQdsplen ( const char *  s,
int  encoding 
)

Definition at line 1205 of file fe-misc.c.

1206 {
1207  return pg_encoding_dsplen(encoding, s);
1208 }
int32 encoding
Definition: pg_database.h:41
int pg_encoding_dsplen(int encoding, const char *mbstr)
Definition: wchar.c:2150

References encoding, and pg_encoding_dsplen().

Referenced by get_prompt(), pg_wcsformat(), pg_wcssize(), pg_wcswidth(), and strlen_max_width().

◆ PQenv2encoding()

int PQenv2encoding ( void  )

Definition at line 1214 of file fe-misc.c.

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 }
int pg_char_to_encoding(const char *name)
Definition: encnames.c:550
@ PG_SQL_ASCII
Definition: pg_wchar.h:224

References encoding, pg_char_to_encoding(), PG_SQL_ASCII, and generate_unaccent_rules::str.

Referenced by main().

◆ pqFlush()

int pqFlush ( PGconn conn)

Definition at line 958 of file fe-misc.c.

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 }
static int pqSendSome(PGconn *conn, int len)
Definition: fe-misc.c:789
static void const char fflush(stdout)
FILE * Pfdebug
Definition: libpq-int.h:398
int outCount
Definition: libpq-int.h:488

References conn, fflush(), pg_conn::outCount, pg_conn::Pfdebug, and pqSendSome().

Referenced by pg_SASL_init(), PQconnectPoll(), PQconsumeInput(), pqEndcopy3(), PQexitPipelineMode(), PQflush(), pqFunctionCall3(), PQgetResult(), pqPacketSend(), pqPipelineFlush(), PQputCopyData(), PQputCopyEnd(), PQsetnonblocking(), and sendTerminateConn().

◆ pqGetc()

int pqGetc ( char *  result,
PGconn conn 
)

Definition at line 80 of file fe-misc.c.

81 {
82  if (conn->inCursor >= conn->inEnd)
83  return EOF;
84 
85  *result = conn->inBuffer[conn->inCursor++];
86 
87  return 0;
88 }

References conn, pg_conn::inBuffer, pg_conn::inCursor, and pg_conn::inEnd.

Referenced by getCopyDataMessage(), getCopyStart(), getReadyForQuery(), PQconnectPoll(), pqFunctionCall3(), pqGetErrorNotice3(), and pqParseInput3().

◆ pqGetInt()

int pqGetInt ( int *  result,
size_t  bytes,
PGconn conn 
)

Definition at line 219 of file fe-misc.c.

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 }
unsigned short uint16
Definition: c.h:440
unsigned int uint32
Definition: c.h:441
void pqInternalNotice(const PGNoticeHooks *hooks, const char *fmt,...)
Definition: fe-exec.c:939
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
#define pg_ntoh16(x)
Definition: pg_bswap.h:124
PGNoticeHooks noticeHooks
Definition: libpq-int.h:402

References conn, pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inEnd, pg_conn::noticeHooks, pg_ntoh16, pg_ntoh32, and pqInternalNotice().

Referenced by getAnotherTuple(), getCopyDataMessage(), getCopyStart(), getNotify(), getParamDescriptions(), getRowDescriptions(), PQconnectPoll(), pqFunctionCall3(), and pqParseInput3().

◆ pqGetnchar()

int pqGetnchar ( char *  s,
size_t  len,
PGconn conn 
)

Definition at line 168 of file fe-misc.c.

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 }
const void size_t len

References conn, pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inEnd, and len.

Referenced by pg_password_sendauth(), pg_SASL_continue(), and pqFunctionCall3().

◆ pqGets()

int pqGets ( PQExpBuffer  buf,
PGconn conn 
)

Definition at line 139 of file fe-misc.c.

140 {
141  return pqGets_internal(buf, conn, true);
142 }
static int pqGets_internal(PQExpBuffer buf, PGconn *conn, bool resetbuffer)
Definition: fe-misc.c:112
static char * buf
Definition: pg_test_fsync.c:67

References buf, conn, and pqGets_internal().

Referenced by getNotify(), getParameterStatus(), getRowDescriptions(), pg_SASL_init(), pqGetErrorNotice3(), and pqParseInput3().

◆ pqGets_append()

int pqGets_append ( PQExpBuffer  buf,
PGconn conn 
)

Definition at line 145 of file fe-misc.c.

146 {
147  return pqGets_internal(buf, conn, false);
148 }

References buf, conn, and pqGets_internal().

Referenced by PQconnectPoll().

◆ pqGets_internal()

static int pqGets_internal ( PQExpBuffer  buf,
PGconn conn,
bool  resetbuffer 
)
static

Definition at line 112 of file fe-misc.c.

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 }
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:148
void appendBinaryPQExpBuffer(PQExpBuffer str, const char *data, size_t datalen)
Definition: pqexpbuffer.c:399

References appendBinaryPQExpBuffer(), buf, conn, pg_conn::inBuffer, pg_conn::inCursor, pg_conn::inEnd, and resetPQExpBuffer().

Referenced by pqGets(), and pqGets_append().

◆ PQlibVersion()

int PQlibVersion ( void  )

Definition at line 66 of file fe-misc.c.

67 {
68  return PG_VERSION_NUM;
69 }

◆ PQmblen()

int PQmblen ( const char *  s,
int  encoding 
)

Definition at line 1185 of file fe-misc.c.

1186 {
1187  return pg_encoding_mblen(encoding, s);
1188 }
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:2129

References encoding, and pg_encoding_mblen().

Referenced by appendStringLiteral(), get_prompt(), pg_wcsformat(), pg_wcssize(), pg_wcswidth(), and strlen_max_width().

◆ PQmblenBounded()

int PQmblenBounded ( const char *  s,
int  encoding 
)

Definition at line 1195 of file fe-misc.c.

1196 {
1197  return strnlen(s, pg_encoding_mblen(encoding, s));
1198 }
size_t strnlen(const char *str, size_t maxlen)
Definition: strnlen.c:26

References encoding, pg_encoding_mblen(), and strnlen().

Referenced by command_no_begin(), do_field(), is_select_command(), patternToSQLRegex(), quote_if_needed(), reportErrorPosition(), skip_white_space(), splitTableColumnsSpec(), strip_quotes(), and strtokx().

◆ pqPutc()

int pqPutc ( char  c,
PGconn conn 
)

Definition at line 95 of file fe-misc.c.

96 {
97  if (pqPutMsgBytes(&c, 1, conn))
98  return EOF;
99 
100  return 0;
101 }
static int pqPutMsgBytes(const void *buf, size_t len, PGconn *conn)
Definition: fe-misc.c:497
char * c

References conn, and pqPutMsgBytes().

Referenced by PQsendDescribe(), PQsendQueryGuts(), and PQsendQueryInternal().

◆ pqPutInt()

int pqPutInt ( int  value,
size_t  bytes,
PGconn conn 
)

Definition at line 256 of file fe-misc.c.

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 }
static struct @151 value
#define pg_hton32(x)
Definition: pg_bswap.h:121
#define pg_hton16(x)
Definition: pg_bswap.h:120

References conn, pg_conn::noticeHooks, pg_hton16, pg_hton32, pqInternalNotice(), pqPutMsgBytes(), and value.

Referenced by pg_SASL_init(), pqFunctionCall3(), PQsendPrepare(), PQsendQueryGuts(), and PQsendQueryInternal().

◆ pqPutMsgBytes()

static int pqPutMsgBytes ( const void *  buf,
size_t  len,
PGconn conn 
)
static

Definition at line 497 of file fe-misc.c.

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 }
int pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:290
int outMsgEnd
Definition: libpq-int.h:493

References buf, conn, len, pg_conn::outBuffer, pg_conn::outMsgEnd, and pqCheckOutBufferSpace().

Referenced by pqPutc(), pqPutInt(), pqPutnchar(), and pqPuts().

◆ pqPutMsgEnd()

int pqPutMsgEnd ( PGconn conn)

Definition at line 520 of file fe-misc.c.

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 }
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
int outMsgStart
Definition: libpq-int.h:491

References conn, pg_conn::outBuffer, pg_conn::outCount, pg_conn::outMsgEnd, pg_conn::outMsgStart, pg_conn::Pfdebug, pg_hton32, pqSendSome(), pqTraceOutputMessage(), and pqTraceOutputNoTypeByteMessage().

Referenced by pg_SASL_init(), pqEndcopy3(), pqFunctionCall3(), pqPacketSend(), PQpipelineSync(), PQputCopyData(), PQputCopyEnd(), PQsendDescribe(), PQsendFlushRequest(), PQsendPrepare(), PQsendQueryGuts(), PQsendQueryInternal(), and sendTerminateConn().

◆ pqPutMsgStart()

int pqPutMsgStart ( char  msg_type,
PGconn conn 
)

Definition at line 461 of file fe-misc.c.

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 }

References conn, pg_conn::outBuffer, pg_conn::outCount, pg_conn::outMsgEnd, pg_conn::outMsgStart, and pqCheckOutBufferSpace().

Referenced by pg_SASL_init(), pqEndcopy3(), pqFunctionCall3(), pqPacketSend(), PQpipelineSync(), PQputCopyData(), PQputCopyEnd(), PQsendDescribe(), PQsendFlushRequest(), PQsendPrepare(), PQsendQueryGuts(), PQsendQueryInternal(), and sendTerminateConn().

◆ pqPutnchar()

int pqPutnchar ( const char *  s,
size_t  len,
PGconn conn 
)

Definition at line 205 of file fe-misc.c.

206 {
207  if (pqPutMsgBytes(s, len, conn))
208  return EOF;
209 
210  return 0;
211 }

References conn, len, and pqPutMsgBytes().

Referenced by pg_SASL_init(), pqFunctionCall3(), pqPacketSend(), PQputCopyData(), and PQsendQueryGuts().

◆ pqPuts()

int pqPuts ( const char *  s,
PGconn conn 
)

Definition at line 155 of file fe-misc.c.

156 {
157  if (pqPutMsgBytes(s, strlen(s) + 1, conn))
158  return EOF;
159 
160  return 0;
161 }

References conn, and pqPutMsgBytes().

Referenced by pg_SASL_init(), PQputCopyEnd(), PQsendDescribe(), PQsendPrepare(), PQsendQueryGuts(), and PQsendQueryInternal().

◆ pqReadData()

int pqReadData ( PGconn conn)

Definition at line 568 of file fe-misc.c.

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 }
void pqDropConnection(PGconn *conn, bool flushInput)
Definition: fe-connect.c:449
int pqReadReady(PGconn *conn)
Definition: fe-misc.c:1020
int pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
Definition: fe-misc.c:354
ssize_t pqsecure_read(PGconn *conn, void *ptr, size_t len)
Definition: fe-secure.c:206
@ CONNECTION_BAD
Definition: libpq-fe.h:61
#define libpq_gettext(x)
Definition: libpq-int.h:878
#define SOCK_ERRNO
Definition: libpq-int.h:891
#define ALL_CONNECTION_FAILURE_ERRNOS
Definition: port.h:117
#define PGINVALID_SOCKET
Definition: port.h:31
pgsocket sock
Definition: libpq-int.h:444
bool ssl_in_use
Definition: libpq-int.h:517
ConnStatusType status
Definition: libpq-int.h:410
#define EINTR
Definition: win32_port.h:351
#define EWOULDBLOCK
Definition: win32_port.h:357
#define EAGAIN
Definition: win32_port.h:349

References ALL_CONNECTION_FAILURE_ERRNOS, appendPQExpBufferStr(), conn, CONNECTION_BAD, EAGAIN, EINTR, pg_conn::errorMessage, EWOULDBLOCK, pg_conn::inBuffer, pg_conn::inBufSize, pg_conn::inCursor, pg_conn::inEnd, pg_conn::inStart, libpq_gettext, PGINVALID_SOCKET, pqCheckInBufferSpace(), pqDropConnection(), pqReadReady(), pqsecure_read(), pg_conn::sock, SOCK_ERRNO, pg_conn::ssl_in_use, and pg_conn::status.

Referenced by PQconnectPoll(), PQconsumeInput(), pqFunctionCall3(), pqGetCopyData3(), pqGetline3(), PQgetResult(), and pqSendSome().

◆ pqReadReady()

int pqReadReady ( PGconn conn)

Definition at line 1020 of file fe-misc.c.

1021 {
1022  return pqSocketCheck(conn, 1, 0, (time_t) 0);
1023 }
static int pqSocketCheck(PGconn *conn, int forRead, int forWrite, time_t end_time)
Definition: fe-misc.c:1044

References conn, and pqSocketCheck().

Referenced by gss_read(), and pqReadData().

◆ pqSendSome()

static int pqSendSome ( PGconn conn,
int  len 
)
static

Definition at line 789 of file fe-misc.c.

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 }
#define Min(x, y)
Definition: c.h:986
int pqReadData(PGconn *conn)
Definition: fe-misc.c:568
int pqWait(int forRead, int forWrite, PGconn *conn)
Definition: fe-misc.c:983
ssize_t pqsecure_write(PGconn *conn, const void *ptr, size_t len)
Definition: fe-secure.c:301
int remaining
Definition: informix.c:667
#define pqIsnonblocking(conn)
Definition: libpq-int.h:867
char * write_err_msg
Definition: libpq-int.h:455
bool write_failed
Definition: libpq-int.h:454

References conn, EAGAIN, EINTR, EWOULDBLOCK, len, libpq_gettext, Min, pg_conn::outBuffer, pg_conn::outCount, PGINVALID_SOCKET, pqIsnonblocking, pqReadData(), pqsecure_write(), pqWait(), remaining, pg_conn::sock, SOCK_ERRNO, pg_conn::write_err_msg, and pg_conn::write_failed.

Referenced by pqFlush(), and pqPutMsgEnd().

◆ pqSkipnchar()

int pqSkipnchar ( size_t  len,
PGconn conn 
)

Definition at line 190 of file fe-misc.c.

191 {
192  if (len > (size_t) (conn->inEnd - conn->inCursor))
193  return EOF;
194 
195  conn->inCursor += len;
196 
197  return 0;
198 }

References conn, pg_conn::inCursor, pg_conn::inEnd, and len.

Referenced by getAnotherTuple().

◆ pqSocketCheck()

static int pqSocketCheck ( PGconn conn,
int  forRead,
int  forWrite,
time_t  end_time 
)
static

Definition at line 1044 of file fe-misc.c.

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 }
static int pqSocketPoll(int sock, int forRead, int forWrite, time_t end_time)
Definition: fe-misc.c:1095
bool pgtls_read_pending(PGconn *conn)
#define SOCK_STRERROR
Definition: libpq-int.h:892
int64 end_time
Definition: pgbench.c:188
#define PG_STRERROR_R_BUFLEN
Definition: port.h:243
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267

References appendPQExpBuffer(), appendPQExpBufferStr(), conn, EINTR, end_time, pg_conn::errorMessage, libpq_gettext, PG_STRERROR_R_BUFLEN, PGINVALID_SOCKET, pgtls_read_pending(), pqSocketPoll(), pg_conn::sock, SOCK_ERRNO, SOCK_STRERROR, and pg_conn::ssl_in_use.

Referenced by pqReadReady(), pqWaitTimed(), and pqWriteReady().

◆ pqSocketPoll()

static int pqSocketPoll ( int  sock,
int  forRead,
int  forWrite,
time_t  end_time 
)
static

Definition at line 1095 of file fe-misc.c.

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 }
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538
#define select(n, r, w, e, timeout)
Definition: win32_port.h:474

References end_time, now(), and select.

Referenced by pqSocketCheck().

◆ pqWait()

int pqWait ( int  forRead,
int  forWrite,
PGconn conn 
)

Definition at line 983 of file fe-misc.c.

984 {
985  return pqWaitTimed(forRead, forWrite, conn, (time_t) -1);
986 }
int pqWaitTimed(int forRead, int forWrite, PGconn *conn, time_t finish_time)
Definition: fe-misc.c:996

References conn, and pqWaitTimed().

Referenced by pqFunctionCall3(), pqGetCopyData3(), pqGetline3(), PQgetResult(), and pqSendSome().

◆ pqWaitTimed()

int pqWaitTimed ( int  forRead,
int  forWrite,
PGconn conn,
time_t  finish_time 
)

Definition at line 996 of file fe-misc.c.

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 }

References appendPQExpBufferStr(), conn, pg_conn::errorMessage, libpq_gettext, and pqSocketCheck().

Referenced by connectDBComplete(), and pqWait().

◆ pqWriteReady()

int pqWriteReady ( PGconn conn)

Definition at line 1030 of file fe-misc.c.

1031 {
1032  return pqSocketCheck(conn, 0, 1, (time_t) 0);
1033 }

References conn, and pqSocketCheck().