Branch data Line data Source code
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-2026, 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/select.h>
41 : : #include <sys/time.h>
42 : : #endif
43 : :
44 : : #ifdef HAVE_POLL_H
45 : : #include <poll.h>
46 : : #endif
47 : :
48 : : #include "libpq-fe.h"
49 : : #include "libpq-int.h"
50 : : #include "mb/pg_wchar.h"
51 : : #include "pg_config_paths.h"
52 : : #include "port/pg_bswap.h"
53 : :
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);
58 : : static int pqReadData_internal(PGconn *conn);
59 : : static int pqDrainPending(PGconn *conn);
60 : :
61 : : /*
62 : : * PQlibVersion: return the libpq version number
63 : : */
64 : : int
65 : 0 : PQlibVersion(void)
66 : : {
67 : 0 : return PG_VERSION_NUM;
68 : : }
69 : :
70 : :
71 : : /*
72 : : * pqGetc: read 1 character from the connection
73 : : *
74 : : * All these routines return 0 on success, EOF on error.
75 : : * Note that for the Get routines, EOF only means there is not enough
76 : : * data in the buffer, not that there is necessarily a hard error.
77 : : */
78 : : int
79 : 13342281 : pqGetc(char *result, PGconn *conn)
80 : : {
81 [ + + ]: 13342281 : if (conn->inCursor >= conn->inEnd)
82 : 1919385 : return EOF;
83 : :
84 : 11422896 : *result = conn->inBuffer[conn->inCursor++];
85 : :
86 : 11422896 : return 0;
87 : : }
88 : :
89 : :
90 : : /*
91 : : * pqPutc: write 1 char to the current message
92 : : */
93 : : int
94 : 11656 : pqPutc(char c, PGconn *conn)
95 : : {
96 [ - + ]: 11656 : if (pqPutMsgBytes(&c, 1, conn))
97 : 0 : return EOF;
98 : :
99 : 11656 : return 0;
100 : : }
101 : :
102 : :
103 : : /*
104 : : * pqGets[_append]:
105 : : * read a null-terminated string from the connection,
106 : : * and store it in an expansible PQExpBuffer.
107 : : * If we run out of memory, all of the string is still read,
108 : : * but the excess characters are silently discarded.
109 : : */
110 : : static int
111 : 3429045 : pqGets_internal(PQExpBuffer buf, PGconn *conn, bool resetbuffer)
112 : : {
113 : : /* Copy conn data to locals for faster search loop */
114 : 3429045 : char *inBuffer = conn->inBuffer;
115 : 3429045 : int inCursor = conn->inCursor;
116 : 3429045 : int inEnd = conn->inEnd;
117 : : int slen;
118 : :
119 [ + - + + ]: 87874407 : while (inCursor < inEnd && inBuffer[inCursor])
120 : 84445362 : inCursor++;
121 : :
122 [ - + ]: 3429045 : if (inCursor >= inEnd)
123 : 0 : return EOF;
124 : :
125 : 3429045 : slen = inCursor - conn->inCursor;
126 : :
127 [ + - ]: 3429045 : if (resetbuffer)
128 : 3429045 : resetPQExpBuffer(buf);
129 : :
130 : 3429045 : appendBinaryPQExpBuffer(buf, inBuffer + conn->inCursor, slen);
131 : :
132 : 3429045 : conn->inCursor = ++inCursor;
133 : :
134 : 3429045 : return 0;
135 : : }
136 : :
137 : : int
138 : 3429045 : pqGets(PQExpBuffer buf, PGconn *conn)
139 : : {
140 : 3429045 : return pqGets_internal(buf, conn, true);
141 : : }
142 : :
143 : : int
144 : 0 : pqGets_append(PQExpBuffer buf, PGconn *conn)
145 : : {
146 : 0 : return pqGets_internal(buf, conn, false);
147 : : }
148 : :
149 : :
150 : : /*
151 : : * pqPuts: write a null-terminated string to the current message
152 : : */
153 : : int
154 : 459948 : pqPuts(const char *s, PGconn *conn)
155 : : {
156 [ - + ]: 459948 : if (pqPutMsgBytes(s, strlen(s) + 1, conn))
157 : 0 : return EOF;
158 : :
159 : 459948 : return 0;
160 : : }
161 : :
162 : : /*
163 : : * pqGetnchar:
164 : : * read exactly len bytes in buffer s, no null termination
165 : : */
166 : : int
167 : 15895 : pqGetnchar(void *s, size_t len, PGconn *conn)
168 : : {
169 [ - + ]: 15895 : if (len > (size_t) (conn->inEnd - conn->inCursor))
170 : 0 : return EOF;
171 : :
172 : 15895 : memcpy(s, conn->inBuffer + conn->inCursor, len);
173 : : /* no terminating null */
174 : :
175 : 15895 : conn->inCursor += len;
176 : :
177 : 15895 : return 0;
178 : : }
179 : :
180 : : /*
181 : : * pqSkipnchar:
182 : : * skip over len bytes in input buffer.
183 : : *
184 : : * Note: this is primarily useful for its debug output, which should
185 : : * be exactly the same as for pqGetnchar. We assume the data in question
186 : : * will actually be used, but just isn't getting copied anywhere as yet.
187 : : */
188 : : int
189 : 18694712 : pqSkipnchar(size_t len, PGconn *conn)
190 : : {
191 [ - + ]: 18694712 : if (len > (size_t) (conn->inEnd - conn->inCursor))
192 : 0 : return EOF;
193 : :
194 : 18694712 : conn->inCursor += len;
195 : :
196 : 18694712 : return 0;
197 : : }
198 : :
199 : : /*
200 : : * pqPutnchar:
201 : : * write exactly len bytes to the current message
202 : : */
203 : : int
204 : 357832 : pqPutnchar(const void *s, size_t len, PGconn *conn)
205 : : {
206 [ - + ]: 357832 : if (pqPutMsgBytes(s, len, conn))
207 : 0 : return EOF;
208 : :
209 : 357832 : return 0;
210 : : }
211 : :
212 : : /*
213 : : * pqGetInt
214 : : * read a 2 or 4 byte integer and convert from network byte order
215 : : * to local byte order
216 : : */
217 : : int
218 : 36855501 : pqGetInt(int *result, size_t bytes, PGconn *conn)
219 : : {
220 : : uint16 tmp2;
221 : : uint32 tmp4;
222 : :
223 [ + + - ]: 36855501 : switch (bytes)
224 : : {
225 : 6038869 : case 2:
226 [ - + ]: 6038869 : if (conn->inCursor + 2 > conn->inEnd)
227 : 0 : return EOF;
228 : 6038869 : memcpy(&tmp2, conn->inBuffer + conn->inCursor, 2);
229 : 6038869 : conn->inCursor += 2;
230 : 6038869 : *result = (int) pg_ntoh16(tmp2);
231 : 6038869 : break;
232 : 30816632 : case 4:
233 [ + + ]: 30816632 : if (conn->inCursor + 4 > conn->inEnd)
234 : 1256 : return EOF;
235 : 30815376 : memcpy(&tmp4, conn->inBuffer + conn->inCursor, 4);
236 : 30815376 : conn->inCursor += 4;
237 : 30815376 : *result = (int) pg_ntoh32(tmp4);
238 : 30815376 : break;
239 : 0 : default:
240 : 0 : pqInternalNotice(&conn->noticeHooks,
241 : : "integer of size %zu not supported by pqGetInt",
242 : : bytes);
243 : 0 : return EOF;
244 : : }
245 : :
246 : 36854245 : return 0;
247 : : }
248 : :
249 : : /*
250 : : * pqPutInt
251 : : * write an integer of 2 or 4 bytes, converting from host byte order
252 : : * to network byte order.
253 : : */
254 : : int
255 : 93545 : pqPutInt(int value, size_t bytes, PGconn *conn)
256 : : {
257 : : uint16 tmp2;
258 : : uint32 tmp4;
259 : :
260 [ + + - ]: 93545 : switch (bytes)
261 : : {
262 : 60982 : case 2:
263 : 60982 : tmp2 = pg_hton16((uint16) value);
264 [ - + ]: 60982 : if (pqPutMsgBytes((const char *) &tmp2, 2, conn))
265 : 0 : return EOF;
266 : 60982 : break;
267 : 32563 : case 4:
268 : 32563 : tmp4 = pg_hton32((uint32) value);
269 [ - + ]: 32563 : if (pqPutMsgBytes((const char *) &tmp4, 4, conn))
270 : 0 : return EOF;
271 : 32563 : break;
272 : 0 : default:
273 : 0 : pqInternalNotice(&conn->noticeHooks,
274 : : "integer of size %zu not supported by pqPutInt",
275 : : bytes);
276 : 0 : return EOF;
277 : : }
278 : :
279 : 93545 : return 0;
280 : : }
281 : :
282 : : /*
283 : : * Make sure conn's output buffer can hold bytes_needed bytes (caller must
284 : : * include already-stored data into the value!)
285 : : *
286 : : * Returns 0 on success, EOF if failed to enlarge buffer
287 : : */
288 : : int
289 : 1737444 : pqCheckOutBufferSpace(size_t bytes_needed, PGconn *conn)
290 : : {
291 : 1737444 : int newsize = conn->outBufSize;
292 : : char *newbuf;
293 : :
294 : : /* Quick exit if we have enough space */
295 [ + + ]: 1737444 : if (bytes_needed <= (size_t) newsize)
296 : 1737405 : return 0;
297 : :
298 : : /*
299 : : * If we need to enlarge the buffer, we first try to double it in size; if
300 : : * that doesn't work, enlarge in multiples of 8K. This avoids thrashing
301 : : * the malloc pool by repeated small enlargements.
302 : : *
303 : : * Note: tests for newsize > 0 are to catch integer overflow.
304 : : */
305 : : do
306 : : {
307 : 94 : newsize *= 2;
308 [ + - + + ]: 94 : } while (newsize > 0 && bytes_needed > (size_t) newsize);
309 : :
310 [ + - + - ]: 39 : if (newsize > 0 && bytes_needed <= (size_t) newsize)
311 : : {
312 : 39 : newbuf = realloc(conn->outBuffer, newsize);
313 [ + - ]: 39 : if (newbuf)
314 : : {
315 : : /* realloc succeeded */
316 : 39 : conn->outBuffer = newbuf;
317 : 39 : conn->outBufSize = newsize;
318 : 39 : return 0;
319 : : }
320 : : }
321 : :
322 : 0 : newsize = conn->outBufSize;
323 : : do
324 : : {
325 : 0 : newsize += 8192;
326 [ # # # # ]: 0 : } while (newsize > 0 && bytes_needed > (size_t) newsize);
327 : :
328 [ # # # # ]: 0 : if (newsize > 0 && bytes_needed <= (size_t) newsize)
329 : : {
330 : 0 : newbuf = realloc(conn->outBuffer, newsize);
331 [ # # ]: 0 : if (newbuf)
332 : : {
333 : : /* realloc succeeded */
334 : 0 : conn->outBuffer = newbuf;
335 : 0 : conn->outBufSize = newsize;
336 : 0 : return 0;
337 : : }
338 : : }
339 : :
340 : : /* realloc failed. Probably out of memory */
341 : 0 : appendPQExpBufferStr(&conn->errorMessage,
342 : : "cannot allocate memory for output buffer\n");
343 : 0 : return EOF;
344 : : }
345 : :
346 : : /*
347 : : * Make sure conn's input buffer can hold bytes_needed bytes (caller must
348 : : * include already-stored data into the value!)
349 : : *
350 : : * Returns 0 on success, EOF if failed to enlarge buffer
351 : : */
352 : : int
353 : 265078 : pqCheckInBufferSpace(size_t bytes_needed, PGconn *conn)
354 : : {
355 : 265078 : int newsize = conn->inBufSize;
356 : : char *newbuf;
357 : :
358 : : /* Quick exit if we have enough space */
359 [ + + ]: 265078 : if (bytes_needed <= (size_t) newsize)
360 : 97934 : return 0;
361 : :
362 : : /*
363 : : * Before concluding that we need to enlarge the buffer, left-justify
364 : : * whatever is in it and recheck. The caller's value of bytes_needed
365 : : * includes any data to the left of inStart, but we can delete that in
366 : : * preference to enlarging the buffer. It's slightly ugly to have this
367 : : * function do this, but it's better than making callers worry about it.
368 : : */
369 : 167144 : bytes_needed -= conn->inStart;
370 : :
371 [ + - ]: 167144 : if (conn->inStart < conn->inEnd)
372 : : {
373 [ + + ]: 167144 : if (conn->inStart > 0)
374 : : {
375 : 166908 : memmove(conn->inBuffer, conn->inBuffer + conn->inStart,
376 : 166908 : conn->inEnd - conn->inStart);
377 : 166908 : conn->inEnd -= conn->inStart;
378 : 166908 : conn->inCursor -= conn->inStart;
379 : 166908 : conn->inStart = 0;
380 : : }
381 : : }
382 : : else
383 : : {
384 : : /* buffer is logically empty, reset it */
385 : 0 : conn->inStart = conn->inCursor = conn->inEnd = 0;
386 : : }
387 : :
388 : : /* Recheck whether we have enough space */
389 [ + + ]: 167144 : if (bytes_needed <= (size_t) newsize)
390 : 166479 : return 0;
391 : :
392 : : /*
393 : : * If we need to enlarge the buffer, we first try to double it in size; if
394 : : * that doesn't work, enlarge in multiples of 8K. This avoids thrashing
395 : : * the malloc pool by repeated small enlargements.
396 : : *
397 : : * Note: tests for newsize > 0 are to catch integer overflow.
398 : : */
399 : : do
400 : : {
401 : 1480 : newsize *= 2;
402 [ + - + + ]: 1480 : } while (newsize > 0 && bytes_needed > (size_t) newsize);
403 : :
404 [ + - + - ]: 665 : if (newsize > 0 && bytes_needed <= (size_t) newsize)
405 : : {
406 : 665 : newbuf = realloc(conn->inBuffer, newsize);
407 [ + - ]: 665 : if (newbuf)
408 : : {
409 : : /* realloc succeeded */
410 : 665 : conn->inBuffer = newbuf;
411 : 665 : conn->inBufSize = newsize;
412 : 665 : return 0;
413 : : }
414 : : }
415 : :
416 : 0 : newsize = conn->inBufSize;
417 : : do
418 : : {
419 : 0 : newsize += 8192;
420 [ # # # # ]: 0 : } while (newsize > 0 && bytes_needed > (size_t) newsize);
421 : :
422 [ # # # # ]: 0 : if (newsize > 0 && bytes_needed <= (size_t) newsize)
423 : : {
424 : 0 : newbuf = realloc(conn->inBuffer, newsize);
425 [ # # ]: 0 : if (newbuf)
426 : : {
427 : : /* realloc succeeded */
428 : 0 : conn->inBuffer = newbuf;
429 : 0 : conn->inBufSize = newsize;
430 : 0 : return 0;
431 : : }
432 : : }
433 : :
434 : : /* realloc failed. Probably out of memory */
435 : 0 : appendPQExpBufferStr(&conn->errorMessage,
436 : : "cannot allocate memory for input buffer\n");
437 : 0 : return EOF;
438 : : }
439 : :
440 : : /*
441 : : * pqParseDone: after a server-to-client message has successfully
442 : : * been parsed, advance conn->inStart to account for it.
443 : : */
444 : : void
445 : 8075204 : pqParseDone(PGconn *conn, int newInStart)
446 : : {
447 : : /* trace server-to-client message */
448 [ + + ]: 8075204 : if (conn->Pfdebug)
449 : 217 : pqTraceOutputMessage(conn, conn->inBuffer + conn->inStart, false);
450 : :
451 : : /* Mark message as done */
452 : 8075204 : conn->inStart = newInStart;
453 : 8075204 : }
454 : :
455 : : /*
456 : : * pqPutMsgStart: begin construction of a message to the server
457 : : *
458 : : * msg_type is the message type byte, or 0 for a message without type byte
459 : : * (only startup messages have no type byte)
460 : : *
461 : : * Returns 0 on success, EOF on error
462 : : *
463 : : * The idea here is that we construct the message in conn->outBuffer,
464 : : * beginning just past any data already in outBuffer (ie, at
465 : : * outBuffer+outCount). We enlarge the buffer as needed to hold the message.
466 : : * When the message is complete, we fill in the length word (if needed) and
467 : : * then advance outCount past the message, making it eligible to send.
468 : : *
469 : : * The state variable conn->outMsgStart points to the incomplete message's
470 : : * length word: it is either outCount or outCount+1 depending on whether
471 : : * there is a type byte. The state variable conn->outMsgEnd is the end of
472 : : * the data collected so far.
473 : : */
474 : : int
475 : 814438 : pqPutMsgStart(char msg_type, PGconn *conn)
476 : : {
477 : : int lenPos;
478 : : int endPos;
479 : :
480 : : /* allow room for message type byte */
481 [ + + ]: 814438 : if (msg_type)
482 : 798451 : endPos = conn->outCount + 1;
483 : : else
484 : 15987 : endPos = conn->outCount;
485 : :
486 : : /* do we want a length word? */
487 : 814438 : lenPos = endPos;
488 : : /* allow room for message length */
489 : 814438 : endPos += 4;
490 : :
491 : : /* make sure there is room for message header */
492 [ - + ]: 814438 : if (pqCheckOutBufferSpace(endPos, conn))
493 : 0 : return EOF;
494 : : /* okay, save the message type byte if any */
495 [ + + ]: 814438 : if (msg_type)
496 : 798451 : conn->outBuffer[conn->outCount] = msg_type;
497 : : /* set up the message pointers */
498 : 814438 : conn->outMsgStart = lenPos;
499 : 814438 : conn->outMsgEnd = endPos;
500 : : /* length word, if needed, will be filled in by pqPutMsgEnd */
501 : :
502 : 814438 : return 0;
503 : : }
504 : :
505 : : /*
506 : : * pqPutMsgBytes: add bytes to a partially-constructed message
507 : : *
508 : : * Returns 0 on success, EOF on error
509 : : */
510 : : static int
511 : 922981 : pqPutMsgBytes(const void *buf, size_t len, PGconn *conn)
512 : : {
513 : : /* make sure there is room for it */
514 [ - + ]: 922981 : if (pqCheckOutBufferSpace(conn->outMsgEnd + len, conn))
515 : 0 : return EOF;
516 : : /* okay, save the data */
517 : 922981 : memcpy(conn->outBuffer + conn->outMsgEnd, buf, len);
518 : 922981 : conn->outMsgEnd += len;
519 : : /* no Pfdebug call here, caller should do it */
520 : 922981 : return 0;
521 : : }
522 : :
523 : : /*
524 : : * pqPutMsgEnd: finish constructing a message and possibly send it
525 : : *
526 : : * Returns 0 on success, EOF on error
527 : : *
528 : : * We don't actually send anything here unless we've accumulated at least
529 : : * 8K worth of data (the typical size of a pipe buffer on Unix systems).
530 : : * This avoids sending small partial packets. The caller must use pqFlush
531 : : * when it's important to flush all the data out to the server.
532 : : */
533 : : int
534 : 814438 : pqPutMsgEnd(PGconn *conn)
535 : : {
536 : : /* Fill in length word if needed */
537 [ + - ]: 814438 : if (conn->outMsgStart >= 0)
538 : : {
539 : 814438 : uint32 msgLen = conn->outMsgEnd - conn->outMsgStart;
540 : :
541 : 814438 : msgLen = pg_hton32(msgLen);
542 : 814438 : memcpy(conn->outBuffer + conn->outMsgStart, &msgLen, 4);
543 : : }
544 : :
545 : : /* trace client-to-server message */
546 [ + + ]: 814438 : if (conn->Pfdebug)
547 : : {
548 [ + - ]: 197 : if (conn->outCount < conn->outMsgStart)
549 : 197 : pqTraceOutputMessage(conn, conn->outBuffer + conn->outCount, true);
550 : : else
551 : 0 : pqTraceOutputNoTypeByteMessage(conn,
552 : 0 : conn->outBuffer + conn->outMsgStart);
553 : : }
554 : :
555 : : /* Make message eligible to send */
556 : 814438 : conn->outCount = conn->outMsgEnd;
557 : :
558 : : /* If appropriate, try to push out some data */
559 [ + + ]: 814438 : if (conn->outCount >= 8192)
560 : : {
561 : 1223 : int toSend = conn->outCount;
562 : :
563 : : /*
564 : : * On Unix-pipe connections, it seems profitable to prefer sending
565 : : * pipe-buffer-sized packets not randomly-sized ones, so retain the
566 : : * last partial-8K chunk in our buffer for now. On TCP connections,
567 : : * the advantage of that is far less clear. Moreover, it flat out
568 : : * isn't safe when using SSL or GSSAPI, because those code paths have
569 : : * API stipulations that if they fail to send all the data that was
570 : : * offered in the previous write attempt, we mustn't offer less data
571 : : * in this write attempt. The previous write attempt might've been
572 : : * pqFlush attempting to send everything in the buffer, so we mustn't
573 : : * offer less now. (Presently, we won't try to use SSL or GSSAPI on
574 : : * Unix connections, so those checks are just Asserts. They'll have
575 : : * to become part of the regular if-test if we ever change that.)
576 : : */
577 [ + - ]: 1223 : if (conn->raddr.addr.ss_family == AF_UNIX)
578 : : {
579 : : #ifdef USE_SSL
580 : : Assert(!conn->ssl_in_use);
581 : : #endif
582 : : #ifdef ENABLE_GSS
583 : : Assert(!conn->gssenc);
584 : : #endif
585 : 1223 : toSend -= toSend % 8192;
586 : : }
587 : :
588 [ - + ]: 1223 : if (pqSendSome(conn, toSend) < 0)
589 : 0 : return EOF;
590 : : /* in nonblock mode, don't complain if unable to send it all */
591 : : }
592 : :
593 : 814438 : return 0;
594 : : }
595 : :
596 : : /* ----------
597 : : * pqReadData: read more data, if any is available
598 : : *
599 : : * Upon a successful return, callers may assume that either 1) all available
600 : : * bytes have been consumed from the socket, or 2) the socket is still marked
601 : : * readable by the OS. (In other words: after a successful pqReadData, it's
602 : : * safe to tell a client to poll for readable bytes on the socket without any
603 : : * further draining of the SSL/GSS transport buffers.)
604 : : *
605 : : * Possible return values:
606 : : * 1: successfully loaded at least one more byte
607 : : * 0: no data is presently available, but no error detected
608 : : * -1: error detected (including EOF = connection closure);
609 : : * conn->errorMessage set
610 : : * NOTE: callers must not assume that pointers or indexes into conn->inBuffer
611 : : * remain valid across this call!
612 : : * ----------
613 : : */
614 : : int
615 : 1203294 : pqReadData(PGconn *conn)
616 : : {
617 : : int available;
618 : :
619 [ + + ]: 1203294 : if (conn->sock == PGINVALID_SOCKET)
620 : : {
621 : 2 : libpq_append_conn_error(conn, "connection not open");
622 : 2 : return -1;
623 : : }
624 : :
625 : 1203292 : available = pqReadData_internal(conn);
626 [ + + ]: 1203292 : if (available < 0)
627 : 137 : return -1;
628 [ + + ]: 1203155 : else if (available > 0)
629 : : {
630 : : /*
631 : : * Make sure there are no bytes stuck in layers between conn->inBuffer
632 : : * and the socket, to make it safe for clients to poll on PQsocket().
633 : : */
634 [ - + ]: 832719 : if (pqDrainPending(conn))
635 : 0 : return -1;
636 : : }
637 : : else
638 : : {
639 : : /*
640 : : * If we're not returning any bytes from the underlying transport,
641 : : * that must imply there aren't any in the transport buffer...
642 : : */
643 : : Assert(pqsecure_bytes_pending(conn) == 0);
644 : : }
645 : :
646 : 1203155 : return available;
647 : : }
648 : :
649 : : /*
650 : : * Workhorse for pqReadData(). It's kept separate from the pqDrainPending()
651 : : * logic to avoid adding to this function's goto complexity.
652 : : */
653 : : static int
654 : 1203292 : pqReadData_internal(PGconn *conn)
655 : : {
656 : 1203292 : int someread = 0;
657 : : ssize_t nread;
658 : :
659 : : /* Left-justify any data in the buffer to make room */
660 [ + + ]: 1203292 : if (conn->inStart < conn->inEnd)
661 : : {
662 [ + + ]: 207883 : if (conn->inStart > 0)
663 : : {
664 : 17100 : memmove(conn->inBuffer, conn->inBuffer + conn->inStart,
665 : 17100 : conn->inEnd - conn->inStart);
666 : 17100 : conn->inEnd -= conn->inStart;
667 : 17100 : conn->inCursor -= conn->inStart;
668 : 17100 : conn->inStart = 0;
669 : : }
670 : : }
671 : : else
672 : : {
673 : : /* buffer is logically empty, reset it */
674 : 995409 : conn->inStart = conn->inCursor = conn->inEnd = 0;
675 : : }
676 : :
677 : : /*
678 : : * If the buffer is fairly full, enlarge it. We need to be able to enlarge
679 : : * the buffer in case a single message exceeds the initial buffer size. We
680 : : * enlarge before filling the buffer entirely so as to avoid asking the
681 : : * kernel for a partial packet. The magic constant here should be large
682 : : * enough for a TCP packet or Unix pipe bufferload. 8K is the usual pipe
683 : : * buffer size, so...
684 : : */
685 [ + + ]: 1203292 : if (conn->inBufSize - conn->inEnd < 8192)
686 : : {
687 [ + - ]: 4 : if (pqCheckInBufferSpace(conn->inEnd + (size_t) 8192, conn))
688 : : {
689 : : /*
690 : : * We don't insist that the enlarge worked, but we need some room
691 : : */
692 [ # # ]: 0 : if (conn->inBufSize - conn->inEnd < 100)
693 : 0 : return -1; /* errorMessage already set */
694 : : }
695 : : }
696 : :
697 : : /* OK, try to read some data */
698 : 1274984 : retry3:
699 : 1274984 : nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
700 : 1274984 : conn->inBufSize - conn->inEnd);
701 [ + + ]: 1274984 : if (nread < 0)
702 : : {
703 [ - + + - ]: 430248 : switch (SOCK_ERRNO)
704 : : {
705 : 0 : case EINTR:
706 : 0 : goto retry3;
707 : :
708 : : /* Some systems return EAGAIN/EWOULDBLOCK for no data */
709 : : #ifdef EAGAIN
710 : 430230 : case EAGAIN:
711 : 430230 : return someread;
712 : : #endif
713 : : #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
714 : : case EWOULDBLOCK:
715 : : return someread;
716 : : #endif
717 : :
718 : : /* We might get ECONNRESET etc here if connection failed */
719 : 18 : case ALL_CONNECTION_FAILURE_ERRNOS:
720 : 18 : goto definitelyFailed;
721 : :
722 : 0 : default:
723 : : /* pqsecure_read set the error message for us */
724 : 0 : return -1;
725 : : }
726 : : }
727 [ + + ]: 844736 : if (nread > 0)
728 : : {
729 : 844508 : conn->inEnd += nread;
730 : :
731 : : /*
732 : : * Hack to deal with the fact that some kernels will only give us back
733 : : * 1 packet per recv() call, even if we asked for more and there is
734 : : * more available. If it looks like we are reading a long message,
735 : : * loop back to recv() again immediately, until we run out of data or
736 : : * buffer space. Without this, the block-and-restart behavior of
737 : : * libpq's higher levels leads to O(N^2) performance on long messages.
738 : : *
739 : : * Since we left-justified the data above, conn->inEnd gives the
740 : : * amount of data already read in the current message. We consider
741 : : * the message "long" once we have acquired 32k ...
742 : : */
743 [ + + ]: 844508 : if (conn->inEnd > 32768 &&
744 [ + + ]: 213394 : (conn->inBufSize - conn->inEnd) >= 8192)
745 : : {
746 : 71692 : someread = 1;
747 : 71692 : goto retry3;
748 : : }
749 : 772816 : return 1;
750 : : }
751 : :
752 [ - + ]: 228 : if (someread)
753 : 0 : return 1; /* got a zero read after successful tries */
754 : :
755 : : /*
756 : : * A return value of 0 could mean just that no data is now available, or
757 : : * it could mean EOF --- that is, the server has closed the connection.
758 : : * Since we have the socket in nonblock mode, the only way to tell the
759 : : * difference is to see if select() is saying that the file is ready.
760 : : * Grumble. Fortunately, we don't expect this path to be taken much,
761 : : * since in normal practice we should not be trying to read data unless
762 : : * the file selected for reading already.
763 : : *
764 : : * In SSL mode it's even worse: SSL_read() could say WANT_READ and then
765 : : * data could arrive before we make the pqReadReady() test, but the second
766 : : * SSL_read() could still say WANT_READ because the data received was not
767 : : * a complete SSL record. So we must play dumb and assume there is more
768 : : * data, relying on the SSL layer to detect true EOF.
769 : : */
770 : :
771 : : #ifdef USE_SSL
772 [ + + ]: 228 : if (conn->ssl_in_use)
773 : 109 : return 0;
774 : : #endif
775 : :
776 [ - + - ]: 119 : switch (pqReadReady(conn))
777 : : {
778 : 0 : case 0:
779 : : /* definitely no data available */
780 : 0 : return 0;
781 : 119 : case 1:
782 : : /* ready for read */
783 : 119 : break;
784 : 0 : default:
785 : : /* we override pqReadReady's message with something more useful */
786 : 0 : goto definitelyEOF;
787 : : }
788 : :
789 : : /*
790 : : * Still not sure that it's EOF, because some data could have just
791 : : * arrived.
792 : : */
793 : 119 : retry4:
794 : 119 : nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
795 : 119 : conn->inBufSize - conn->inEnd);
796 [ - + ]: 119 : if (nread < 0)
797 : : {
798 [ # # # # ]: 0 : switch (SOCK_ERRNO)
799 : : {
800 : 0 : case EINTR:
801 : 0 : goto retry4;
802 : :
803 : : /* Some systems return EAGAIN/EWOULDBLOCK for no data */
804 : : #ifdef EAGAIN
805 : 0 : case EAGAIN:
806 : 0 : return 0;
807 : : #endif
808 : : #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
809 : : case EWOULDBLOCK:
810 : : return 0;
811 : : #endif
812 : :
813 : : /* We might get ECONNRESET etc here if connection failed */
814 : 0 : case ALL_CONNECTION_FAILURE_ERRNOS:
815 : 0 : goto definitelyFailed;
816 : :
817 : 0 : default:
818 : : /* pqsecure_read set the error message for us */
819 : 0 : return -1;
820 : : }
821 : : }
822 [ - + ]: 119 : if (nread > 0)
823 : : {
824 : 0 : conn->inEnd += nread;
825 : 0 : return 1;
826 : : }
827 : :
828 : : /*
829 : : * OK, we are getting a zero read even though select() says ready. This
830 : : * means the connection has been closed. Cope.
831 : : */
832 : 119 : definitelyEOF:
833 : 119 : libpq_append_conn_error(conn, "server closed the connection unexpectedly\n"
834 : : "\tThis probably means the server terminated abnormally\n"
835 : : "\tbefore or while processing the request.");
836 : :
837 : : /* Come here if lower-level code already set a suitable errorMessage */
838 : 137 : definitelyFailed:
839 : : /* Do *not* drop any already-read data; caller still wants it */
840 : 137 : pqDropConnection(conn, false);
841 : 137 : conn->status = CONNECTION_BAD; /* No more connection to backend */
842 : 137 : return -1;
843 : : }
844 : :
845 : : /*---
846 : : * Drain any transport data that is already buffered in userspace and add it
847 : : * to conn->inBuffer, enlarging inBuffer if necessary. The drain fails if
848 : : * inBuffer cannot be made to hold all available transport data.
849 : : *
850 : : * We assume that the underlying secure transport implementation does not
851 : : * attempt to read any more data from the socket while draining the transport
852 : : * buffer. After a successful return, pqsecure_bytes_pending() must be zero.
853 : : *
854 : : * This operation is necessary to prevent deadlock, due to a layering
855 : : * violation designed into our asynchronous client API: pqReadData() and all
856 : : * the parsing routines above it receive data from the SSL/GSS transport
857 : : * buffer, but clients poll on the raw PQsocket() handle. So data can be
858 : : * "lost" in the intermediate layer if we don't take it out here.
859 : : *
860 : : * To illustrate what we're trying to prevent, say that the server is sending
861 : : * two messages at once in response to a query (Aaaa and Bb), the libpq buffer
862 : : * is five characters in size, and TLS records max out at three-character
863 : : * payloads. Here's what would happen if pqReadData() didn't call
864 : : * pqDrainPending():
865 : : *
866 : : * Client libpq SSL Socket
867 : : * | | | |
868 : : * | [ ] [ ] [ ] [1] Buffers are empty, client is
869 : : * x --------------------------> | polling on socket
870 : : * | | | |
871 : : * | [ ] [ ] [xxx] [2] First record is received; poll
872 : : * | <-------------------------- | signals read-ready
873 : : * | | | |
874 : : * x ---> [ ] [ ] [xxx] [3] Client calls PQconsumeInput()
875 : : * | | | |
876 : : * | [ ] -> [ ] [xxx] [4] libpq calls pqReadData() to fill
877 : : * | | | | the receive buffer
878 : : * | [ ] [Aaa] <-- [ ] [5] SSL pulls payload off the wire
879 : : * | | | | and decrypts it
880 : : * | [Aaa ] <- [ ] [ ] [6] pqsecure_read() takes all data
881 : : * | | | |
882 : : * | <--- [Aaa ] [ ] [ ] [7] PQconsumeInput() returns with a
883 : : * x --------------------------> | partial message, PQisBusy() is
884 : : * | | | | still true, client polls again
885 : : * | [Aaa ] [ ] [xxx] [8] Second record is received; poll
886 : : * | <-------------------------- | signals read-ready
887 : : * | | | |
888 : : * x ---> [Aaa ] [ ] [xxx] [9] Client calls PQconsumeInput()
889 : : * | | | |
890 : : * | [Aaa ] -> [ ] [xxx] [10] libpq calls pqReadData() to fill
891 : : * | | | | the receive buffer
892 : : * | [Aaa ] [aBb] <-- [ ] [11] SSL decrypts
893 : : * | | | |
894 : : * | [AaaaB] <- [b ] [ ] [12] pqsecure_read() fills its
895 : : * | | | | buffer, taking only two bytes
896 : : * | <--- [AaaaB] [b ] [ ] [13] PQconsumeInput() returns with a
897 : : * | | | | complete message buffered;
898 : : * | | | | PQisBusy() is false
899 : : * x ---> [AaaaB] [b ] [ ] [14] Client calls PQgetResult()
900 : : * | | | |
901 : : * | <--- [B ] [b ] [ ] [15] Aaaa is returned; PQisBusy() is
902 : : * x --------------------------> | true and client polls again
903 : : * . | | .
904 : : * . [B ] [b ] . [16] No packets, and client hangs.
905 : : * . | | .
906 : : *
907 : : * The pqDrainPending() call fixes the above scenario at step [13]. Before
908 : : * returning to the Client, it first expands the libpq buffer and moves the
909 : : * remaining data from the SSL buffer to the libpq buffer.
910 : : *
911 : : * The function returns 0 on success and -1 on error. Success means that
912 : : * there was no data pending or it was successfully drained to conn->inBuffer.
913 : : * On error, conn->errorMessage is set.
914 : : */
915 : : static int
916 : 832719 : pqDrainPending(PGconn *conn)
917 : : {
918 : : ssize_t bytes_pending;
919 : : ssize_t nread;
920 : :
921 : 832719 : bytes_pending = pqsecure_bytes_pending(conn);
922 [ + - ]: 832719 : if (bytes_pending <= 0)
923 : 832719 : return bytes_pending;
924 : :
925 : : /* Expand the input buffer if necessary. */
926 [ # # ]: 0 : if (pqCheckInBufferSpace(conn->inEnd + (size_t) bytes_pending, conn))
927 : 0 : return -1; /* errorMessage already set */
928 : :
929 : 0 : nread = pqsecure_read(conn, conn->inBuffer + conn->inEnd,
930 : : bytes_pending);
931 : :
932 : : /*
933 : : * When there are bytes pending, pqsecure_read() is not supposed to fail
934 : : * or do a short read, but let's check anyway to be safe.
935 : : */
936 [ # # ]: 0 : if (nread < 0)
937 : 0 : return -1;
938 : 0 : conn->inEnd += nread;
939 [ # # ]: 0 : if (nread != bytes_pending)
940 : : {
941 : 0 : libpq_append_conn_error(conn,
942 : : "drained only %zd of %zd pending bytes in transport buffer",
943 : : nread, bytes_pending);
944 : 0 : return -1;
945 : : }
946 : 0 : return 0;
947 : : }
948 : :
949 : : /*
950 : : * pqSendSome: send data waiting in the output buffer.
951 : : *
952 : : * len is how much to try to send (typically equal to outCount, but may
953 : : * be less).
954 : : *
955 : : * Return 0 on success, -1 on failure and 1 when not all data could be sent
956 : : * because the socket would block and the connection is non-blocking.
957 : : *
958 : : * Note that this is also responsible for consuming data from the socket
959 : : * (putting it in conn->inBuffer) in any situation where we can't send
960 : : * all the specified data immediately.
961 : : *
962 : : * If a socket-level write failure occurs, conn->write_failed is set and the
963 : : * error message is saved in conn->write_err_msg, but we clear the output
964 : : * buffer and return zero anyway; this is because callers should soldier on
965 : : * until we have read what we can from the server and checked for an error
966 : : * message. write_err_msg should be reported only when we are unable to
967 : : * obtain a server error first. Much of that behavior is implemented at
968 : : * lower levels, but this function deals with some edge cases.
969 : : */
970 : : static int
971 : 575392 : pqSendSome(PGconn *conn, int len)
972 : : {
973 : 575392 : char *ptr = conn->outBuffer;
974 : 575392 : int remaining = conn->outCount;
975 : 575392 : int result = 0;
976 : :
977 : : /*
978 : : * If we already had a write failure, we will never again try to send data
979 : : * on that connection. Even if the kernel would let us, we've probably
980 : : * lost message boundary sync with the server. conn->write_failed
981 : : * therefore persists until the connection is reset, and we just discard
982 : : * all data presented to be written. However, as long as we still have a
983 : : * valid socket, we should continue to absorb data from the backend, so
984 : : * that we can collect any final error messages.
985 : : */
986 [ + + ]: 575392 : if (conn->write_failed)
987 : : {
988 : : /* conn->write_err_msg should be set up already */
989 : 3 : conn->outCount = 0;
990 : : /* Absorb input data if any, and detect socket closure */
991 [ + - ]: 3 : if (conn->sock != PGINVALID_SOCKET)
992 : : {
993 [ + - ]: 3 : if (pqReadData(conn) < 0)
994 : 3 : return -1;
995 : : }
996 : 0 : return 0;
997 : : }
998 : :
999 [ - + ]: 575389 : if (conn->sock == PGINVALID_SOCKET)
1000 : : {
1001 : 0 : conn->write_failed = true;
1002 : : /* Store error message in conn->write_err_msg, if possible */
1003 : : /* (strdup failure is OK, we'll cope later) */
1004 : 0 : conn->write_err_msg = strdup(libpq_gettext("connection not open\n"));
1005 : : /* Discard queued data; no chance it'll ever be sent */
1006 : 0 : conn->outCount = 0;
1007 : 0 : return 0;
1008 : : }
1009 : :
1010 : : /* while there's still data to send */
1011 [ + + ]: 1150784 : while (len > 0)
1012 : : {
1013 : : ssize_t sent;
1014 : :
1015 : : #ifndef WIN32
1016 : 575398 : sent = pqsecure_write(conn, ptr, len);
1017 : : #else
1018 : :
1019 : : /*
1020 : : * Windows can fail on large sends, per KB article Q201213. The
1021 : : * failure-point appears to be different in different versions of
1022 : : * Windows, but 64k should always be safe.
1023 : : */
1024 : : sent = pqsecure_write(conn, ptr, Min(len, 65536));
1025 : : #endif
1026 : :
1027 [ + + ]: 575398 : if (sent < 0)
1028 : : {
1029 : : /* Anything except EAGAIN/EWOULDBLOCK/EINTR is trouble */
1030 [ + - - ]: 12 : switch (SOCK_ERRNO)
1031 : : {
1032 : : #ifdef EAGAIN
1033 : 12 : case EAGAIN:
1034 : 12 : break;
1035 : : #endif
1036 : : #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1037 : : case EWOULDBLOCK:
1038 : : break;
1039 : : #endif
1040 : 0 : case EINTR:
1041 : 0 : continue;
1042 : :
1043 : 0 : default:
1044 : : /* Discard queued data; no chance it'll ever be sent */
1045 : 0 : conn->outCount = 0;
1046 : :
1047 : : /* Absorb input data if any, and detect socket closure */
1048 [ # # ]: 0 : if (conn->sock != PGINVALID_SOCKET)
1049 : : {
1050 [ # # ]: 0 : if (pqReadData(conn) < 0)
1051 : 0 : return -1;
1052 : : }
1053 : :
1054 : : /*
1055 : : * Lower-level code should already have filled
1056 : : * conn->write_err_msg (and set conn->write_failed) or
1057 : : * conn->errorMessage. In the former case, we pretend
1058 : : * there's no problem; the write_failed condition will be
1059 : : * dealt with later. Otherwise, report the error now.
1060 : : */
1061 [ # # ]: 0 : if (conn->write_failed)
1062 : 0 : return 0;
1063 : : else
1064 : 0 : return -1;
1065 : : }
1066 : : }
1067 : : else
1068 : : {
1069 : 575386 : ptr += sent;
1070 : 575386 : len -= sent;
1071 : 575386 : remaining -= sent;
1072 : : }
1073 : :
1074 [ + + ]: 575398 : if (len > 0)
1075 : : {
1076 : : /*
1077 : : * We didn't send it all, wait till we can send more.
1078 : : *
1079 : : * There are scenarios in which we can't send data because the
1080 : : * communications channel is full, but we cannot expect the server
1081 : : * to clear the channel eventually because it's blocked trying to
1082 : : * send data to us. (This can happen when we are sending a large
1083 : : * amount of COPY data, and the server has generated lots of
1084 : : * NOTICE responses.) To avoid a deadlock situation, we must be
1085 : : * prepared to accept and buffer incoming data before we try
1086 : : * again. Furthermore, it is possible that such incoming data
1087 : : * might not arrive until after we've gone to sleep. Therefore,
1088 : : * we wait for either read ready or write ready.
1089 : : *
1090 : : * In non-blocking mode, we don't wait here directly, but return 1
1091 : : * to indicate that data is still pending. The caller should wait
1092 : : * for both read and write ready conditions, and call
1093 : : * PQconsumeInput() on read ready, but just in case it doesn't, we
1094 : : * call pqReadData() ourselves before returning. That's not
1095 : : * enough if the data has not arrived yet, but it's the best we
1096 : : * can do, and works pretty well in practice. (The documentation
1097 : : * used to say that you only need to wait for write-ready, so
1098 : : * there are still plenty of applications like that out there.)
1099 : : *
1100 : : * Note that errors here don't result in write_failed becoming
1101 : : * set.
1102 : : */
1103 [ - + ]: 12 : if (pqReadData(conn) < 0)
1104 : : {
1105 : 0 : result = -1; /* error message already set up */
1106 : 0 : break;
1107 : : }
1108 : :
1109 [ + + ]: 12 : if (pqIsnonblocking(conn))
1110 : : {
1111 : 3 : result = 1;
1112 : 3 : break;
1113 : : }
1114 : :
1115 [ - + ]: 9 : if (pqWait(true, true, conn))
1116 : : {
1117 : 0 : result = -1;
1118 : 0 : break;
1119 : : }
1120 : : }
1121 : : }
1122 : :
1123 : : /* shift the remaining contents of the buffer */
1124 [ + + ]: 575389 : if (remaining > 0)
1125 : 1223 : memmove(conn->outBuffer, ptr, remaining);
1126 : 575389 : conn->outCount = remaining;
1127 : :
1128 : 575389 : return result;
1129 : : }
1130 : :
1131 : :
1132 : : /*
1133 : : * pqFlush: send any data waiting in the output buffer
1134 : : *
1135 : : * Return 0 on success, -1 on failure and 1 when not all data could be sent
1136 : : * because the socket would block and the connection is non-blocking.
1137 : : * (See pqSendSome comments about how failure should be handled.)
1138 : : */
1139 : : int
1140 : 1103204 : pqFlush(PGconn *conn)
1141 : : {
1142 [ + + ]: 1103204 : if (conn->outCount > 0)
1143 : : {
1144 [ + + ]: 574169 : if (conn->Pfdebug)
1145 : 54 : fflush(conn->Pfdebug);
1146 : :
1147 : 574169 : return pqSendSome(conn, conn->outCount);
1148 : : }
1149 : :
1150 : 529035 : return 0;
1151 : : }
1152 : :
1153 : :
1154 : : /*
1155 : : * pqWait: wait until we can read or write the connection socket
1156 : : *
1157 : : * JAB: If SSL enabled and used and forRead, buffered bytes short-circuit the
1158 : : * call to select().
1159 : : *
1160 : : * We also stop waiting and return if the kernel flags an exception condition
1161 : : * on the socket. The actual error condition will be detected and reported
1162 : : * when the caller tries to read or write the socket.
1163 : : */
1164 : : int
1165 : 616626 : pqWait(int forRead, int forWrite, PGconn *conn)
1166 : : {
1167 : 616626 : return pqWaitTimed(forRead, forWrite, conn, -1);
1168 : : }
1169 : :
1170 : : /*
1171 : : * pqWaitTimed: wait, but not past end_time.
1172 : : *
1173 : : * Returns -1 on failure, 0 if the socket is readable/writable, 1 if it timed out.
1174 : : *
1175 : : * The timeout is specified by end_time, which is the int64 number of
1176 : : * microseconds since the Unix epoch (that is, time_t times 1 million).
1177 : : * Timeout is infinite if end_time is -1. Timeout is immediate (no blocking)
1178 : : * if end_time is 0 (or indeed, any time before now).
1179 : : */
1180 : : int
1181 : 646010 : pqWaitTimed(int forRead, int forWrite, PGconn *conn, pg_usec_time_t end_time)
1182 : : {
1183 : : int result;
1184 : :
1185 : 646010 : result = pqSocketCheck(conn, forRead, forWrite, end_time);
1186 : :
1187 [ + + ]: 646010 : if (result < 0)
1188 : 49 : return -1; /* errorMessage is already set */
1189 : :
1190 [ - + ]: 645961 : if (result == 0)
1191 : : {
1192 : 0 : libpq_append_conn_error(conn, "timeout expired");
1193 : 0 : return 1;
1194 : : }
1195 : :
1196 : 645961 : return 0;
1197 : : }
1198 : :
1199 : : /*
1200 : : * pqReadReady: is select() saying the file is ready to read?
1201 : : * Returns -1 on failure, 0 if not ready, 1 if ready.
1202 : : */
1203 : : int
1204 : 119 : pqReadReady(PGconn *conn)
1205 : : {
1206 : 119 : return pqSocketCheck(conn, 1, 0, 0);
1207 : : }
1208 : :
1209 : : /*
1210 : : * pqWriteReady: is select() saying the file is ready to write?
1211 : : * Returns -1 on failure, 0 if not ready, 1 if ready.
1212 : : */
1213 : : int
1214 : 0 : pqWriteReady(PGconn *conn)
1215 : : {
1216 : 0 : return pqSocketCheck(conn, 0, 1, 0);
1217 : : }
1218 : :
1219 : : /*
1220 : : * Checks a socket, using poll or select, for data to be read, written,
1221 : : * or both. Returns >0 if one or more conditions are met, 0 if it timed
1222 : : * out, -1 if an error occurred.
1223 : : *
1224 : : * If an altsock is set for asynchronous authentication, that will be used in
1225 : : * preference to the "server" socket. Otherwise, if SSL is in use, the SSL
1226 : : * buffer is checked prior to checking the socket for read data directly.
1227 : : */
1228 : : static int
1229 : 646129 : pqSocketCheck(PGconn *conn, int forRead, int forWrite, pg_usec_time_t end_time)
1230 : : {
1231 : : int result;
1232 : : pgsocket sock;
1233 : :
1234 [ - + ]: 646129 : if (!conn)
1235 : 0 : return -1;
1236 : :
1237 [ - + ]: 646129 : if (conn->altsock != PGINVALID_SOCKET)
1238 : 0 : sock = conn->altsock;
1239 : : else
1240 : : {
1241 : 646129 : sock = conn->sock;
1242 [ + + ]: 646129 : if (sock == PGINVALID_SOCKET)
1243 : : {
1244 : 49 : libpq_append_conn_error(conn, "invalid socket");
1245 : 49 : return -1;
1246 : : }
1247 : :
1248 : : /* Check for SSL/GSS library buffering read bytes */
1249 [ + + - + ]: 646080 : if (forRead && pqsecure_bytes_pending(conn) != 0)
1250 : : {
1251 : : /* short-circuit the select */
1252 : 0 : return 1;
1253 : : }
1254 : : }
1255 : :
1256 : : /* We will retry as long as we get EINTR */
1257 : : do
1258 : 646082 : result = PQsocketPoll(sock, forRead, forWrite, end_time);
1259 [ + + + - ]: 646082 : while (result < 0 && SOCK_ERRNO == EINTR);
1260 : :
1261 [ - + ]: 646080 : if (result < 0)
1262 : : {
1263 : : char sebuf[PG_STRERROR_R_BUFLEN];
1264 : :
1265 : 0 : libpq_append_conn_error(conn, "%s() failed: %s", "select",
1266 : 0 : SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1267 : : }
1268 : :
1269 : 646080 : return result;
1270 : : }
1271 : :
1272 : :
1273 : : /*
1274 : : * Check a file descriptor for read and/or write data, possibly waiting.
1275 : : * If neither forRead nor forWrite are set, immediately return a timeout
1276 : : * condition (without waiting). Return >0 if condition is met, 0
1277 : : * if a timeout occurred, -1 if an error or interrupt occurred.
1278 : : *
1279 : : * The timeout is specified by end_time, which is the int64 number of
1280 : : * microseconds since the Unix epoch (that is, time_t times 1 million).
1281 : : * Timeout is infinite if end_time is -1. Timeout is immediate (no blocking)
1282 : : * if end_time is 0 (or indeed, any time before now).
1283 : : */
1284 : : int
1285 : 646521 : PQsocketPoll(int sock, int forRead, int forWrite, pg_usec_time_t end_time)
1286 : : {
1287 : : /* We use poll(2) if available, otherwise select(2) */
1288 : : #ifdef HAVE_POLL
1289 : : struct pollfd input_fd;
1290 : : int timeout_ms;
1291 : :
1292 [ + + - + ]: 646521 : if (!forRead && !forWrite)
1293 : 0 : return 0;
1294 : :
1295 : 646521 : input_fd.fd = sock;
1296 : 646521 : input_fd.events = POLLERR;
1297 : 646521 : input_fd.revents = 0;
1298 : :
1299 [ + + ]: 646521 : if (forRead)
1300 : 631588 : input_fd.events |= POLLIN;
1301 [ + + ]: 646521 : if (forWrite)
1302 : 14942 : input_fd.events |= POLLOUT;
1303 : :
1304 : : /* Compute appropriate timeout interval */
1305 [ + + ]: 646521 : if (end_time == -1)
1306 : 645943 : timeout_ms = -1;
1307 [ + + ]: 578 : else if (end_time == 0)
1308 : 119 : timeout_ms = 0;
1309 : : else
1310 : : {
1311 : 459 : pg_usec_time_t now = PQgetCurrentTimeUSec();
1312 : :
1313 [ + - ]: 459 : if (end_time > now)
1314 : 459 : timeout_ms = (end_time - now) / 1000;
1315 : : else
1316 : 0 : timeout_ms = 0;
1317 : : }
1318 : :
1319 : 646521 : return poll(&input_fd, 1, timeout_ms);
1320 : : #else /* !HAVE_POLL */
1321 : :
1322 : : fd_set input_mask;
1323 : : fd_set output_mask;
1324 : : fd_set except_mask;
1325 : : struct timeval timeout;
1326 : : struct timeval *ptr_timeout;
1327 : :
1328 : : if (!forRead && !forWrite)
1329 : : return 0;
1330 : :
1331 : : FD_ZERO(&input_mask);
1332 : : FD_ZERO(&output_mask);
1333 : : FD_ZERO(&except_mask);
1334 : : if (forRead)
1335 : : FD_SET(sock, &input_mask);
1336 : :
1337 : : if (forWrite)
1338 : : FD_SET(sock, &output_mask);
1339 : : FD_SET(sock, &except_mask);
1340 : :
1341 : : /* Compute appropriate timeout interval */
1342 : : if (end_time == -1)
1343 : : ptr_timeout = NULL;
1344 : : else if (end_time == 0)
1345 : : {
1346 : : timeout.tv_sec = 0;
1347 : : timeout.tv_usec = 0;
1348 : : ptr_timeout = &timeout;
1349 : : }
1350 : : else
1351 : : {
1352 : : pg_usec_time_t now = PQgetCurrentTimeUSec();
1353 : :
1354 : : if (end_time > now)
1355 : : {
1356 : : timeout.tv_sec = (end_time - now) / 1000000;
1357 : : timeout.tv_usec = (end_time - now) % 1000000;
1358 : : }
1359 : : else
1360 : : {
1361 : : timeout.tv_sec = 0;
1362 : : timeout.tv_usec = 0;
1363 : : }
1364 : : ptr_timeout = &timeout;
1365 : : }
1366 : :
1367 : : return select(sock + 1, &input_mask, &output_mask,
1368 : : &except_mask, ptr_timeout);
1369 : : #endif /* HAVE_POLL */
1370 : : }
1371 : :
1372 : : /*
1373 : : * PQgetCurrentTimeUSec: get current time with microsecond precision
1374 : : *
1375 : : * This provides a platform-independent way of producing a reference
1376 : : * value for PQsocketPoll's timeout parameter.
1377 : : */
1378 : : pg_usec_time_t
1379 : 905 : PQgetCurrentTimeUSec(void)
1380 : : {
1381 : : struct timeval tval;
1382 : :
1383 : 905 : gettimeofday(&tval, NULL);
1384 : 905 : return (pg_usec_time_t) tval.tv_sec * 1000000 + tval.tv_usec;
1385 : : }
1386 : :
1387 : :
1388 : : /*
1389 : : * A couple of "miscellaneous" multibyte related functions. They used
1390 : : * to be in fe-print.c but that file is doomed.
1391 : : */
1392 : :
1393 : : /*
1394 : : * Like pg_encoding_mblen(). Use this in callers that want the
1395 : : * dynamically-linked libpq's stance on encodings, even if that means
1396 : : * different behavior in different startups of the executable.
1397 : : */
1398 : : int
1399 : 29737402 : PQmblen(const char *s, int encoding)
1400 : : {
1401 : 29737402 : return pg_encoding_mblen(encoding, s);
1402 : : }
1403 : :
1404 : : /*
1405 : : * Like pg_encoding_mblen_bounded(). Use this in callers that want the
1406 : : * dynamically-linked libpq's stance on encodings, even if that means
1407 : : * different behavior in different startups of the executable.
1408 : : */
1409 : : int
1410 : 651076 : PQmblenBounded(const char *s, int encoding)
1411 : : {
1412 : 651076 : return strnlen(s, pg_encoding_mblen(encoding, s));
1413 : : }
1414 : :
1415 : : /*
1416 : : * Returns the display length of the character beginning at s, using the
1417 : : * specified encoding.
1418 : : */
1419 : : int
1420 : 29737711 : PQdsplen(const char *s, int encoding)
1421 : : {
1422 : 29737711 : return pg_encoding_dsplen(encoding, s);
1423 : : }
1424 : :
1425 : : /*
1426 : : * Get encoding id from environment variable PGCLIENTENCODING.
1427 : : */
1428 : : int
1429 : 10677 : PQenv2encoding(void)
1430 : : {
1431 : : char *str;
1432 : 10677 : int encoding = PG_SQL_ASCII;
1433 : :
1434 : 10677 : str = getenv("PGCLIENTENCODING");
1435 [ + + + - ]: 10677 : if (str && *str != '\0')
1436 : : {
1437 : 6 : encoding = pg_char_to_encoding(str);
1438 [ - + ]: 6 : if (encoding < 0)
1439 : 0 : encoding = PG_SQL_ASCII;
1440 : : }
1441 : 10677 : return encoding;
1442 : : }
1443 : :
1444 : :
1445 : : #ifdef ENABLE_NLS
1446 : :
1447 : : static void
1448 : 374263 : libpq_binddomain(void)
1449 : : {
1450 : : /*
1451 : : * At least on Windows, there are gettext implementations that fail if
1452 : : * multiple threads call bindtextdomain() concurrently. Use a mutex and
1453 : : * flag variable to ensure that we call it just once per process. It is
1454 : : * not known that similar bugs exist on non-Windows platforms, but we
1455 : : * might as well do it the same way everywhere.
1456 : : */
1457 : : static volatile bool already_bound = false;
1458 : : static pthread_mutex_t binddomain_mutex = PTHREAD_MUTEX_INITIALIZER;
1459 : :
1460 [ + + ]: 374263 : if (!already_bound)
1461 : : {
1462 : : /* bindtextdomain() does not preserve errno */
1463 : : #ifdef WIN32
1464 : : int save_errno = GetLastError();
1465 : : #else
1466 : 13285 : int save_errno = errno;
1467 : : #endif
1468 : :
1469 : 13285 : (void) pthread_mutex_lock(&binddomain_mutex);
1470 : :
1471 [ + - ]: 13285 : if (!already_bound)
1472 : : {
1473 : : const char *ldir;
1474 : :
1475 : : /*
1476 : : * No relocatable lookup here because the calling executable could
1477 : : * be anywhere
1478 : : */
1479 : 13285 : ldir = getenv("PGLOCALEDIR");
1480 [ + + ]: 13285 : if (!ldir)
1481 : 124 : ldir = LOCALEDIR;
1482 : 13285 : bindtextdomain(PG_TEXTDOMAIN("libpq"), ldir);
1483 : 13285 : already_bound = true;
1484 : : }
1485 : :
1486 : 13285 : (void) pthread_mutex_unlock(&binddomain_mutex);
1487 : :
1488 : : #ifdef WIN32
1489 : : SetLastError(save_errno);
1490 : : #else
1491 : 13285 : errno = save_errno;
1492 : : #endif
1493 : : }
1494 : 374263 : }
1495 : :
1496 : : char *
1497 : 374256 : libpq_gettext(const char *msgid)
1498 : : {
1499 : 374256 : libpq_binddomain();
1500 : 374256 : return dgettext(PG_TEXTDOMAIN("libpq"), msgid);
1501 : : }
1502 : :
1503 : : char *
1504 : 7 : libpq_ngettext(const char *msgid, const char *msgid_plural, unsigned long n)
1505 : : {
1506 : 7 : libpq_binddomain();
1507 : 7 : return dngettext(PG_TEXTDOMAIN("libpq"), msgid, msgid_plural, n);
1508 : : }
1509 : :
1510 : : #endif /* ENABLE_NLS */
1511 : :
1512 : :
1513 : : /*
1514 : : * Append a formatted string to the given buffer, after translating it. A
1515 : : * newline is automatically appended; the format should not end with a
1516 : : * newline.
1517 : : */
1518 : : void
1519 : 43 : libpq_append_error(PQExpBuffer errorMessage, const char *fmt, ...)
1520 : : {
1521 : 43 : int save_errno = errno;
1522 : : bool done;
1523 : : va_list args;
1524 : :
1525 : : Assert(fmt[strlen(fmt) - 1] != '\n');
1526 : :
1527 [ + - - + ]: 43 : if (PQExpBufferBroken(errorMessage))
1528 : 0 : return; /* already failed */
1529 : :
1530 : : /* Loop in case we have to retry after enlarging the buffer. */
1531 : : do
1532 : : {
1533 : 43 : errno = save_errno;
1534 : 43 : va_start(args, fmt);
1535 : 43 : done = appendPQExpBufferVA(errorMessage, libpq_gettext(fmt), args);
1536 : 43 : va_end(args);
1537 [ - + ]: 43 : } while (!done);
1538 : :
1539 : 43 : appendPQExpBufferChar(errorMessage, '\n');
1540 : : }
1541 : :
1542 : : /*
1543 : : * Append a formatted string to the error message buffer of the given
1544 : : * connection, after translating it. A newline is automatically appended; the
1545 : : * format should not end with a newline.
1546 : : */
1547 : : void
1548 : 894 : libpq_append_conn_error(PGconn *conn, const char *fmt, ...)
1549 : : {
1550 : 894 : int save_errno = errno;
1551 : : bool done;
1552 : : va_list args;
1553 : :
1554 : : Assert(fmt[strlen(fmt) - 1] != '\n');
1555 : :
1556 [ + - - + ]: 894 : if (PQExpBufferBroken(&conn->errorMessage))
1557 : 0 : return; /* already failed */
1558 : :
1559 : : /* Loop in case we have to retry after enlarging the buffer. */
1560 : : do
1561 : : {
1562 : 900 : errno = save_errno;
1563 : 900 : va_start(args, fmt);
1564 : 900 : done = appendPQExpBufferVA(&conn->errorMessage, libpq_gettext(fmt), args);
1565 : 900 : va_end(args);
1566 [ + + ]: 900 : } while (!done);
1567 : :
1568 : 894 : appendPQExpBufferChar(&conn->errorMessage, '\n');
1569 : : }
1570 : :
1571 : : /*
1572 : : * For 19beta only, some protocol errors will have additional information
1573 : : * appended to help with the "grease" campaign.
1574 : : */
1575 : : void
1576 : 0 : libpq_append_grease_info(PGconn *conn)
1577 : : {
1578 : : /* translator: %s is a URL */
1579 : 0 : libpq_append_conn_error(conn,
1580 : : "\tThis indicates a bug in either the server being contacted\n"
1581 : : "\tor a proxy handling the connection. Please consider\n"
1582 : : "\treporting this to the maintainers of that software.\n"
1583 : : "\tFor more information, including instructions on how to\n"
1584 : : "\twork around this issue for now, visit\n"
1585 : : "\t\t%s",
1586 : : "https://wiki.postgresql.org/wiki/Grease");
1587 : 0 : }
|