]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-connect.c
libpq: have PQconnectdbParams() and PQpingParams accept "" as default
[postgresql] / src / interfaces / libpq / fe-connect.c
1 /*-------------------------------------------------------------------------
2  *
3  * fe-connect.c
4  *        functions related to setting up a connection to the backend
5  *
6  * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/interfaces/libpq/fe-connect.c
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres_fe.h"
17
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <fcntl.h>
21 #include <ctype.h>
22 #include <time.h>
23 #include <unistd.h>
24
25 #include "libpq-fe.h"
26 #include "libpq-int.h"
27 #include "fe-auth.h"
28 #include "pg_config_paths.h"
29
30 #ifdef WIN32
31 #include "win32.h"
32 #ifdef _WIN32_IE
33 #undef _WIN32_IE
34 #endif
35 #define _WIN32_IE 0x0500
36 #ifdef near
37 #undef near
38 #endif
39 #define near
40 #include <shlobj.h>
41 #ifdef WIN32_ONLY_COMPILER              /* mstcpip.h is missing on mingw */
42 #include <mstcpip.h>
43 #endif
44 #else
45 #include <sys/socket.h>
46 #include <netdb.h>
47 #include <netinet/in.h>
48 #ifdef HAVE_NETINET_TCP_H
49 #include <netinet/tcp.h>
50 #endif
51 #include <arpa/inet.h>
52 #endif
53
54 #ifdef ENABLE_THREAD_SAFETY
55 #ifdef WIN32
56 #include "pthread-win32.h"
57 #else
58 #include <pthread.h>
59 #endif
60 #endif
61
62 #ifdef USE_LDAP
63 #ifdef WIN32
64 #include <winldap.h>
65 #else
66 /* OpenLDAP deprecates RFC 1823, but we want standard conformance */
67 #define LDAP_DEPRECATED 1
68 #include <ldap.h>
69 typedef struct timeval LDAP_TIMEVAL;
70 #endif
71 static int ldapServiceLookup(const char *purl, PQconninfoOption *options,
72                                   PQExpBuffer errorMessage);
73 #endif
74
75 #include "libpq/ip.h"
76 #include "mb/pg_wchar.h"
77
78 #ifndef FD_CLOEXEC
79 #define FD_CLOEXEC 1
80 #endif
81
82
83 #ifndef WIN32
84 #define PGPASSFILE ".pgpass"
85 #else
86 #define PGPASSFILE "pgpass.conf"
87 #endif
88
89 /*
90  * Pre-9.0 servers will return this SQLSTATE if asked to set
91  * application_name in a startup packet.  We hard-wire the value rather
92  * than looking into errcodes.h since it reflects historical behavior
93  * rather than that of the current code.
94  */
95 #define ERRCODE_APPNAME_UNKNOWN "42704"
96
97 /* This is part of the protocol so just define it */
98 #define ERRCODE_INVALID_PASSWORD "28P01"
99 /* This too */
100 #define ERRCODE_CANNOT_CONNECT_NOW "57P03"
101
102 /*
103  * fall back options if they are not specified by arguments or defined
104  * by environment variables
105  */
106 #define DefaultHost             "localhost"
107 #define DefaultTty              ""
108 #define DefaultOption   ""
109 #define DefaultAuthtype           ""
110 #define DefaultPassword           ""
111 #ifdef USE_SSL
112 #define DefaultSSLMode "prefer"
113 #else
114 #define DefaultSSLMode  "disable"
115 #endif
116
117 /* ----------
118  * Definition of the conninfo parameters and their fallback resources.
119  *
120  * If Environment-Var and Compiled-in are specified as NULL, no
121  * fallback is available. If after all no value can be determined
122  * for an option, an error is returned.
123  *
124  * The value for the username is treated specially in conninfo_add_defaults.
125  * If the value is not obtained any other way, the username is determined
126  * by pg_fe_getauthname().
127  *
128  * The Label and Disp-Char entries are provided for applications that
129  * want to use PQconndefaults() to create a generic database connection
130  * dialog. Disp-Char is defined as follows:
131  *              ""              Normal input field
132  *              "*"             Password field - hide value
133  *              "D"             Debug option - don't show by default
134  *
135  * PQconninfoOptions[] is a constant static array that we use to initialize
136  * a dynamically allocated working copy.  All the "val" fields in
137  * PQconninfoOptions[] *must* be NULL.  In a working copy, non-null "val"
138  * fields point to malloc'd strings that should be freed when the working
139  * array is freed (see PQconninfoFree).
140  *
141  * The first part of each struct is identical to the one in libpq-fe.h,
142  * which is required since we memcpy() data between the two!
143  * ----------
144  */
145 typedef struct _internalPQconninfoOption
146 {
147         char       *keyword;            /* The keyword of the option                    */
148         char       *envvar;                     /* Fallback environment variable name   */
149         char       *compiled;           /* Fallback compiled in default value   */
150         char       *val;                        /* Option's current value, or NULL               */
151         char       *label;                      /* Label for field in connect dialog    */
152         char       *dispchar;           /* Indicates how to display this field in a
153                                                                  * connect dialog. Values are: "" Display
154                                                                  * entered value as is "*" Password field -
155                                                                  * hide value "D"  Debug option - don't show
156                                                                  * by default */
157         int                     dispsize;               /* Field size in characters for dialog  */
158         /* ---
159          * Anything above this comment must be synchronized with
160          * PQconninfoOption in libpq-fe.h, since we memcpy() data
161          * between them!
162          * ---
163          */
164         off_t           connofs;                /* Offset into PGconn struct, -1 if not there */
165 } internalPQconninfoOption;
166
167 static const internalPQconninfoOption PQconninfoOptions[] = {
168         /*
169          * "authtype" is no longer used, so mark it "don't show".  We keep it in
170          * the array so as not to reject conninfo strings from old apps that might
171          * still try to set it.
172          */
173         {"authtype", "PGAUTHTYPE", DefaultAuthtype, NULL,
174         "Database-Authtype", "D", 20, -1},
175
176         {"service", "PGSERVICE", NULL, NULL,
177         "Database-Service", "", 20, -1},
178
179         {"user", "PGUSER", NULL, NULL,
180                 "Database-User", "", 20,
181         offsetof(struct pg_conn, pguser)},
182
183         {"password", "PGPASSWORD", NULL, NULL,
184                 "Database-Password", "*", 20,
185         offsetof(struct pg_conn, pgpass)},
186
187         {"connect_timeout", "PGCONNECT_TIMEOUT", NULL, NULL,
188                 "Connect-timeout", "", 10,              /* strlen(INT32_MAX) == 10 */
189         offsetof(struct pg_conn, connect_timeout)},
190
191         {"dbname", "PGDATABASE", NULL, NULL,
192                 "Database-Name", "", 20,
193         offsetof(struct pg_conn, dbName)},
194
195         {"host", "PGHOST", NULL, NULL,
196                 "Database-Host", "", 40,
197         offsetof(struct pg_conn, pghost)},
198
199         {"hostaddr", "PGHOSTADDR", NULL, NULL,
200                 "Database-Host-IP-Address", "", 45,
201         offsetof(struct pg_conn, pghostaddr)},
202
203         {"port", "PGPORT", DEF_PGPORT_STR, NULL,
204                 "Database-Port", "", 6,
205         offsetof(struct pg_conn, pgport)},
206
207         {"client_encoding", "PGCLIENTENCODING", NULL, NULL,
208                 "Client-Encoding", "", 10,
209         offsetof(struct pg_conn, client_encoding_initial)},
210
211         /*
212          * "tty" is no longer used either, but keep it present for backwards
213          * compatibility.
214          */
215         {"tty", "PGTTY", DefaultTty, NULL,
216                 "Backend-Debug-TTY", "D", 40,
217         offsetof(struct pg_conn, pgtty)},
218
219         {"options", "PGOPTIONS", DefaultOption, NULL,
220                 "Backend-Debug-Options", "D", 40,
221         offsetof(struct pg_conn, pgoptions)},
222
223         {"application_name", "PGAPPNAME", NULL, NULL,
224                 "Application-Name", "", 64,
225         offsetof(struct pg_conn, appname)},
226
227         {"fallback_application_name", NULL, NULL, NULL,
228                 "Fallback-Application-Name", "", 64,
229         offsetof(struct pg_conn, fbappname)},
230
231         {"keepalives", NULL, NULL, NULL,
232                 "TCP-Keepalives", "", 1,        /* should be just '0' or '1' */
233         offsetof(struct pg_conn, keepalives)},
234
235         {"keepalives_idle", NULL, NULL, NULL,
236                 "TCP-Keepalives-Idle", "", 10,  /* strlen(INT32_MAX) == 10 */
237         offsetof(struct pg_conn, keepalives_idle)},
238
239         {"keepalives_interval", NULL, NULL, NULL,
240                 "TCP-Keepalives-Interval", "", 10,              /* strlen(INT32_MAX) == 10 */
241         offsetof(struct pg_conn, keepalives_interval)},
242
243         {"keepalives_count", NULL, NULL, NULL,
244                 "TCP-Keepalives-Count", "", 10, /* strlen(INT32_MAX) == 10 */
245         offsetof(struct pg_conn, keepalives_count)},
246
247         /*
248          * ssl options are allowed even without client SSL support because the
249          * client can still handle SSL modes "disable" and "allow". Other
250          * parameters have no effect on non-SSL connections, so there is no reason
251          * to exclude them since none of them are mandatory.
252          */
253         {"sslmode", "PGSSLMODE", DefaultSSLMode, NULL,
254                 "SSL-Mode", "", 12,             /* sizeof("verify-full") == 12 */
255         offsetof(struct pg_conn, sslmode)},
256
257         {"sslcompression", "PGSSLCOMPRESSION", "1", NULL,
258                 "SSL-Compression", "", 1,
259         offsetof(struct pg_conn, sslcompression)},
260
261         {"sslcert", "PGSSLCERT", NULL, NULL,
262                 "SSL-Client-Cert", "", 64,
263         offsetof(struct pg_conn, sslcert)},
264
265         {"sslkey", "PGSSLKEY", NULL, NULL,
266                 "SSL-Client-Key", "", 64,
267         offsetof(struct pg_conn, sslkey)},
268
269         {"sslrootcert", "PGSSLROOTCERT", NULL, NULL,
270                 "SSL-Root-Certificate", "", 64,
271         offsetof(struct pg_conn, sslrootcert)},
272
273         {"sslcrl", "PGSSLCRL", NULL, NULL,
274                 "SSL-Revocation-List", "", 64,
275         offsetof(struct pg_conn, sslcrl)},
276
277         {"requirepeer", "PGREQUIREPEER", NULL, NULL,
278                 "Require-Peer", "", 10,
279         offsetof(struct pg_conn, requirepeer)},
280
281 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
282         /* Kerberos and GSSAPI authentication support specifying the service name */
283         {"krbsrvname", "PGKRBSRVNAME", PG_KRB_SRVNAM, NULL,
284                 "Kerberos-service-name", "", 20,
285         offsetof(struct pg_conn, krbsrvname)},
286 #endif
287
288 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
289
290         /*
291          * GSSAPI and SSPI both enabled, give a way to override which is used by
292          * default
293          */
294         {"gsslib", "PGGSSLIB", NULL, NULL,
295                 "GSS-library", "", 7,   /* sizeof("gssapi") = 7 */
296         offsetof(struct pg_conn, gsslib)},
297 #endif
298
299         {"replication", NULL, NULL, NULL,
300                 "Replication", "D", 5,
301         offsetof(struct pg_conn, replication)},
302
303         /* Terminating entry --- MUST BE LAST */
304         {NULL, NULL, NULL, NULL,
305         NULL, NULL, 0}
306 };
307
308 static const PQEnvironmentOption EnvironmentOptions[] =
309 {
310         /* common user-interface settings */
311         {
312                 "PGDATESTYLE", "datestyle"
313         },
314         {
315                 "PGTZ", "timezone"
316         },
317         /* internal performance-related settings */
318         {
319                 "PGGEQO", "geqo"
320         },
321         {
322                 NULL, NULL
323         }
324 };
325
326 /* The connection URI must start with either of the following designators: */
327 static const char uri_designator[] = "postgresql://";
328 static const char short_uri_designator[] = "postgres://";
329
330 static bool connectOptions1(PGconn *conn, const char *conninfo);
331 static bool connectOptions2(PGconn *conn);
332 static int      connectDBStart(PGconn *conn);
333 static int      connectDBComplete(PGconn *conn);
334 static PGPing internal_ping(PGconn *conn);
335 static PGconn *makeEmptyPGconn(void);
336 static void fillPGconn(PGconn *conn, PQconninfoOption *connOptions);
337 static void freePGconn(PGconn *conn);
338 static void closePGconn(PGconn *conn);
339 static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage);
340 static PQconninfoOption *parse_connection_string(const char *conninfo,
341                                                 PQExpBuffer errorMessage, bool use_defaults);
342 static int      uri_prefix_length(const char *connstr);
343 static bool recognized_connection_string(const char *connstr);
344 static PQconninfoOption *conninfo_parse(const char *conninfo,
345                            PQExpBuffer errorMessage, bool use_defaults);
346 static PQconninfoOption *conninfo_array_parse(const char *const * keywords,
347                                          const char *const * values, PQExpBuffer errorMessage,
348                                          bool use_defaults, int expand_dbname);
349 static bool conninfo_add_defaults(PQconninfoOption *options,
350                                           PQExpBuffer errorMessage);
351 static PQconninfoOption *conninfo_uri_parse(const char *uri,
352                                    PQExpBuffer errorMessage, bool use_defaults);
353 static bool conninfo_uri_parse_options(PQconninfoOption *options,
354                                                    const char *uri, PQExpBuffer errorMessage);
355 static bool conninfo_uri_parse_params(char *params,
356                                                   PQconninfoOption *connOptions,
357                                                   PQExpBuffer errorMessage);
358 static char *conninfo_uri_decode(const char *str, PQExpBuffer errorMessage);
359 static bool get_hexdigit(char digit, int *value);
360 static const char *conninfo_getval(PQconninfoOption *connOptions,
361                                 const char *keyword);
362 static PQconninfoOption *conninfo_storeval(PQconninfoOption *connOptions,
363                                   const char *keyword, const char *value,
364                           PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode);
365 static PQconninfoOption *conninfo_find(PQconninfoOption *connOptions,
366                           const char *keyword);
367 static void defaultNoticeReceiver(void *arg, const PGresult *res);
368 static void defaultNoticeProcessor(void *arg, const char *message);
369 static int parseServiceInfo(PQconninfoOption *options,
370                                  PQExpBuffer errorMessage);
371 static int parseServiceFile(const char *serviceFile,
372                                  const char *service,
373                                  PQconninfoOption *options,
374                                  PQExpBuffer errorMessage,
375                                  bool *group_found);
376 static char *pwdfMatchesString(char *buf, char *token);
377 static char *PasswordFromFile(char *hostname, char *port, char *dbname,
378                                  char *username);
379 static bool getPgPassFilename(char *pgpassfile);
380 static void dot_pg_pass_warning(PGconn *conn);
381 static void default_threadlock(int acquire);
382
383
384 /* global variable because fe-auth.c needs to access it */
385 pgthreadlock_t pg_g_threadlock = default_threadlock;
386
387
388 /*
389  *              pqDropConnection
390  *
391  * Close any physical connection to the server, and reset associated
392  * state inside the connection object.  We don't release state that
393  * would be needed to reconnect, though.
394  */
395 void
396 pqDropConnection(PGconn *conn)
397 {
398         /* Drop any SSL state */
399         pqsecure_close(conn);
400         /* Close the socket itself */
401         if (conn->sock != PGINVALID_SOCKET)
402                 closesocket(conn->sock);
403         conn->sock = PGINVALID_SOCKET;
404         /* Discard any unread/unsent data */
405         conn->inStart = conn->inCursor = conn->inEnd = 0;
406         conn->outCount = 0;
407 }
408
409
410 /*
411  *              Connecting to a Database
412  *
413  * There are now six different ways a user of this API can connect to the
414  * database.  Two are not recommended for use in new code, because of their
415  * lack of extensibility with respect to the passing of options to the
416  * backend.  These are PQsetdb and PQsetdbLogin (the former now being a macro
417  * to the latter).
418  *
419  * If it is desired to connect in a synchronous (blocking) manner, use the
420  * function PQconnectdb or PQconnectdbParams. The former accepts a string of
421  * option = value pairs (or a URI) which must be parsed; the latter takes two
422  * NULL terminated arrays instead.
423  *
424  * To connect in an asynchronous (non-blocking) manner, use the functions
425  * PQconnectStart or PQconnectStartParams (which differ in the same way as
426  * PQconnectdb and PQconnectdbParams) and PQconnectPoll.
427  *
428  * Internally, the static functions connectDBStart, connectDBComplete
429  * are part of the connection procedure.
430  */
431
432 /*
433  *              PQconnectdbParams
434  *
435  * establishes a connection to a postgres backend through the postmaster
436  * using connection information in two arrays.
437  *
438  * The keywords array is defined as
439  *
440  *         const char *params[] = {"option1", "option2", NULL}
441  *
442  * The values array is defined as
443  *
444  *         const char *values[] = {"value1", "value2", NULL}
445  *
446  * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
447  * if a memory allocation failed.
448  * If the status field of the connection returned is CONNECTION_BAD,
449  * then some fields may be null'ed out instead of having valid values.
450  *
451  * You should call PQfinish (if conn is not NULL) regardless of whether this
452  * call succeeded.
453  */
454 PGconn *
455 PQconnectdbParams(const char *const * keywords,
456                                   const char *const * values,
457                                   int expand_dbname)
458 {
459         PGconn     *conn = PQconnectStartParams(keywords, values, expand_dbname);
460
461         if (conn && conn->status != CONNECTION_BAD)
462                 (void) connectDBComplete(conn);
463
464         return conn;
465
466 }
467
468 /*
469  *              PQpingParams
470  *
471  * check server status, accepting parameters identical to PQconnectdbParams
472  */
473 PGPing
474 PQpingParams(const char *const * keywords,
475                          const char *const * values,
476                          int expand_dbname)
477 {
478         PGconn     *conn = PQconnectStartParams(keywords, values, expand_dbname);
479         PGPing          ret;
480
481         ret = internal_ping(conn);
482         PQfinish(conn);
483
484         return ret;
485 }
486
487 /*
488  *              PQconnectdb
489  *
490  * establishes a connection to a postgres backend through the postmaster
491  * using connection information in a string.
492  *
493  * The conninfo string is either a whitespace-separated list of
494  *
495  *         option = value
496  *
497  * definitions or a URI (refer to the documentation for details.) Value
498  * might be a single value containing no whitespaces or a single quoted
499  * string. If a single quote should appear anywhere in the value, it must be
500  * escaped with a backslash like \'
501  *
502  * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
503  * if a memory allocation failed.
504  * If the status field of the connection returned is CONNECTION_BAD,
505  * then some fields may be null'ed out instead of having valid values.
506  *
507  * You should call PQfinish (if conn is not NULL) regardless of whether this
508  * call succeeded.
509  */
510 PGconn *
511 PQconnectdb(const char *conninfo)
512 {
513         PGconn     *conn = PQconnectStart(conninfo);
514
515         if (conn && conn->status != CONNECTION_BAD)
516                 (void) connectDBComplete(conn);
517
518         return conn;
519 }
520
521 /*
522  *              PQping
523  *
524  * check server status, accepting parameters identical to PQconnectdb
525  */
526 PGPing
527 PQping(const char *conninfo)
528 {
529         PGconn     *conn = PQconnectStart(conninfo);
530         PGPing          ret;
531
532         ret = internal_ping(conn);
533         PQfinish(conn);
534
535         return ret;
536 }
537
538 /*
539  *              PQconnectStartParams
540  *
541  * Begins the establishment of a connection to a postgres backend through the
542  * postmaster using connection information in a struct.
543  *
544  * See comment for PQconnectdbParams for the definition of the string format.
545  *
546  * Returns a PGconn*.  If NULL is returned, a malloc error has occurred, and
547  * you should not attempt to proceed with this connection.      If the status
548  * field of the connection returned is CONNECTION_BAD, an error has
549  * occurred. In this case you should call PQfinish on the result, (perhaps
550  * inspecting the error message first).  Other fields of the structure may not
551  * be valid if that occurs.  If the status field is not CONNECTION_BAD, then
552  * this stage has succeeded - call PQconnectPoll, using select(2) to see when
553  * this is necessary.
554  *
555  * See PQconnectPoll for more info.
556  */
557 PGconn *
558 PQconnectStartParams(const char *const * keywords,
559                                          const char *const * values,
560                                          int expand_dbname)
561 {
562         PGconn     *conn;
563         PQconninfoOption *connOptions;
564
565         /*
566          * Allocate memory for the conn structure
567          */
568         conn = makeEmptyPGconn();
569         if (conn == NULL)
570                 return NULL;
571
572         /*
573          * Parse the conninfo arrays
574          */
575         connOptions = conninfo_array_parse(keywords, values,
576                                                                            &conn->errorMessage,
577                                                                            true, expand_dbname);
578         if (connOptions == NULL)
579         {
580                 conn->status = CONNECTION_BAD;
581                 /* errorMessage is already set */
582                 return conn;
583         }
584
585         /*
586          * Move option values into conn structure
587          */
588         fillPGconn(conn, connOptions);
589
590         /*
591          * Free the option info - all is in conn now
592          */
593         PQconninfoFree(connOptions);
594
595         /*
596          * Compute derived options
597          */
598         if (!connectOptions2(conn))
599                 return conn;
600
601         /*
602          * Connect to the database
603          */
604         if (!connectDBStart(conn))
605         {
606                 /* Just in case we failed to set it in connectDBStart */
607                 conn->status = CONNECTION_BAD;
608         }
609
610         return conn;
611 }
612
613 /*
614  *              PQconnectStart
615  *
616  * Begins the establishment of a connection to a postgres backend through the
617  * postmaster using connection information in a string.
618  *
619  * See comment for PQconnectdb for the definition of the string format.
620  *
621  * Returns a PGconn*.  If NULL is returned, a malloc error has occurred, and
622  * you should not attempt to proceed with this connection.      If the status
623  * field of the connection returned is CONNECTION_BAD, an error has
624  * occurred. In this case you should call PQfinish on the result, (perhaps
625  * inspecting the error message first).  Other fields of the structure may not
626  * be valid if that occurs.  If the status field is not CONNECTION_BAD, then
627  * this stage has succeeded - call PQconnectPoll, using select(2) to see when
628  * this is necessary.
629  *
630  * See PQconnectPoll for more info.
631  */
632 PGconn *
633 PQconnectStart(const char *conninfo)
634 {
635         PGconn     *conn;
636
637         /*
638          * Allocate memory for the conn structure
639          */
640         conn = makeEmptyPGconn();
641         if (conn == NULL)
642                 return NULL;
643
644         /*
645          * Parse the conninfo string
646          */
647         if (!connectOptions1(conn, conninfo))
648                 return conn;
649
650         /*
651          * Compute derived options
652          */
653         if (!connectOptions2(conn))
654                 return conn;
655
656         /*
657          * Connect to the database
658          */
659         if (!connectDBStart(conn))
660         {
661                 /* Just in case we failed to set it in connectDBStart */
662                 conn->status = CONNECTION_BAD;
663         }
664
665         return conn;
666 }
667
668 static void
669 fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
670 {
671         const internalPQconninfoOption *option;
672
673         /*
674          * Move option values into conn structure
675          *
676          * Don't put anything cute here --- intelligence should be in
677          * connectOptions2 ...
678          *
679          * XXX: probably worth checking strdup() return value here...
680          */
681         for (option = PQconninfoOptions; option->keyword; option++)
682         {
683                 const char *tmp = conninfo_getval(connOptions, option->keyword);
684
685                 if (tmp && option->connofs >= 0)
686                 {
687                         char      **connmember = (char **) ((char *) conn + option->connofs);
688
689                         if (*connmember)
690                                 free(*connmember);
691                         *connmember = tmp ? strdup(tmp) : NULL;
692                 }
693         }
694 }
695
696 /*
697  *              connectOptions1
698  *
699  * Internal subroutine to set up connection parameters given an already-
700  * created PGconn and a conninfo string.  Derived settings should be
701  * processed by calling connectOptions2 next.  (We split them because
702  * PQsetdbLogin overrides defaults in between.)
703  *
704  * Returns true if OK, false if trouble (in which case errorMessage is set
705  * and so is conn->status).
706  */
707 static bool
708 connectOptions1(PGconn *conn, const char *conninfo)
709 {
710         PQconninfoOption *connOptions;
711
712         /*
713          * Parse the conninfo string
714          */
715         connOptions = parse_connection_string(conninfo, &conn->errorMessage, true);
716         if (connOptions == NULL)
717         {
718                 conn->status = CONNECTION_BAD;
719                 /* errorMessage is already set */
720                 return false;
721         }
722
723         /*
724          * Move option values into conn structure
725          */
726         fillPGconn(conn, connOptions);
727
728         /*
729          * Free the option info - all is in conn now
730          */
731         PQconninfoFree(connOptions);
732
733         return true;
734 }
735
736 /*
737  *              connectOptions2
738  *
739  * Compute derived connection options after absorbing all user-supplied info.
740  *
741  * Returns true if OK, false if trouble (in which case errorMessage is set
742  * and so is conn->status).
743  */
744 static bool
745 connectOptions2(PGconn *conn)
746 {
747         /*
748          * If database name was not given, default it to equal user name
749          */
750         if ((conn->dbName == NULL || conn->dbName[0] == '\0')
751                 && conn->pguser != NULL)
752         {
753                 if (conn->dbName)
754                         free(conn->dbName);
755                 conn->dbName = strdup(conn->pguser);
756         }
757
758         /*
759          * Supply default password if none given
760          */
761         if (conn->pgpass == NULL || conn->pgpass[0] == '\0')
762         {
763                 if (conn->pgpass)
764                         free(conn->pgpass);
765                 conn->pgpass = PasswordFromFile(conn->pghost, conn->pgport,
766                                                                                 conn->dbName, conn->pguser);
767                 if (conn->pgpass == NULL)
768                         conn->pgpass = strdup(DefaultPassword);
769                 else
770                         conn->dot_pgpass_used = true;
771         }
772
773         /*
774          * Allow unix socket specification in the host name
775          */
776         if (conn->pghost && is_absolute_path(conn->pghost))
777         {
778                 if (conn->pgunixsocket)
779                         free(conn->pgunixsocket);
780                 conn->pgunixsocket = conn->pghost;
781                 conn->pghost = NULL;
782         }
783
784         /*
785          * validate sslmode option
786          */
787         if (conn->sslmode)
788         {
789                 if (strcmp(conn->sslmode, "disable") != 0
790                         && strcmp(conn->sslmode, "allow") != 0
791                         && strcmp(conn->sslmode, "prefer") != 0
792                         && strcmp(conn->sslmode, "require") != 0
793                         && strcmp(conn->sslmode, "verify-ca") != 0
794                         && strcmp(conn->sslmode, "verify-full") != 0)
795                 {
796                         conn->status = CONNECTION_BAD;
797                         printfPQExpBuffer(&conn->errorMessage,
798                                                         libpq_gettext("invalid sslmode value: \"%s\"\n"),
799                                                           conn->sslmode);
800                         return false;
801                 }
802
803 #ifndef USE_SSL
804                 switch (conn->sslmode[0])
805                 {
806                         case 'a':                       /* "allow" */
807                         case 'p':                       /* "prefer" */
808
809                                 /*
810                                  * warn user that an SSL connection will never be negotiated
811                                  * since SSL was not compiled in?
812                                  */
813                                 break;
814
815                         case 'r':                       /* "require" */
816                         case 'v':                       /* "verify-ca" or "verify-full" */
817                                 conn->status = CONNECTION_BAD;
818                                 printfPQExpBuffer(&conn->errorMessage,
819                                                                   libpq_gettext("sslmode value \"%s\" invalid when SSL support is not compiled in\n"),
820                                                                   conn->sslmode);
821                                 return false;
822                 }
823 #endif
824         }
825         else
826                 conn->sslmode = strdup(DefaultSSLMode);
827
828         /*
829          * Resolve special "auto" client_encoding from the locale
830          */
831         if (conn->client_encoding_initial &&
832                 strcmp(conn->client_encoding_initial, "auto") == 0)
833         {
834                 free(conn->client_encoding_initial);
835                 conn->client_encoding_initial = strdup(pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true)));
836         }
837
838         /*
839          * Only if we get this far is it appropriate to try to connect. (We need a
840          * state flag, rather than just the boolean result of this function, in
841          * case someone tries to PQreset() the PGconn.)
842          */
843         conn->options_valid = true;
844
845         return true;
846 }
847
848 /*
849  *              PQconndefaults
850  *
851  * Construct a default connection options array, which identifies all the
852  * available options and shows any default values that are available from the
853  * environment etc.  On error (eg out of memory), NULL is returned.
854  *
855  * Using this function, an application may determine all possible options
856  * and their current default values.
857  *
858  * NOTE: as of PostgreSQL 7.0, the returned array is dynamically allocated
859  * and should be freed when no longer needed via PQconninfoFree().      (In prior
860  * versions, the returned array was static, but that's not thread-safe.)
861  * Pre-7.0 applications that use this function will see a small memory leak
862  * until they are updated to call PQconninfoFree.
863  */
864 PQconninfoOption *
865 PQconndefaults(void)
866 {
867         PQExpBufferData errorBuf;
868         PQconninfoOption *connOptions;
869
870         /* We don't actually report any errors here, but callees want a buffer */
871         initPQExpBuffer(&errorBuf);
872         if (PQExpBufferDataBroken(errorBuf))
873                 return NULL;                    /* out of memory already :-( */
874
875         connOptions = conninfo_init(&errorBuf);
876         if (connOptions != NULL)
877         {
878                 /* pass NULL errorBuf to ignore errors */
879                 if (!conninfo_add_defaults(connOptions, NULL))
880                 {
881                         PQconninfoFree(connOptions);
882                         connOptions = NULL;
883                 }
884         }
885
886         termPQExpBuffer(&errorBuf);
887         return connOptions;
888 }
889
890 /* ----------------
891  *              PQsetdbLogin
892  *
893  * establishes a connection to a postgres backend through the postmaster
894  * at the specified host and port.
895  *
896  * returns a PGconn* which is needed for all subsequent libpq calls
897  *
898  * if the status field of the connection returned is CONNECTION_BAD,
899  * then only the errorMessage is likely to be useful.
900  * ----------------
901  */
902 PGconn *
903 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
904                          const char *pgtty, const char *dbName, const char *login,
905                          const char *pwd)
906 {
907         PGconn     *conn;
908
909         /*
910          * Allocate memory for the conn structure
911          */
912         conn = makeEmptyPGconn();
913         if (conn == NULL)
914                 return NULL;
915
916         /*
917          * If the dbName parameter contains what looks like a connection string,
918          * parse it into conn struct using connectOptions1.
919          */
920         if (dbName && recognized_connection_string(dbName))
921         {
922                 if (!connectOptions1(conn, dbName))
923                         return conn;
924         }
925         else
926         {
927                 /*
928                  * Old-style path: first, parse an empty conninfo string in order to
929                  * set up the same defaults that PQconnectdb() would use.
930                  */
931                 if (!connectOptions1(conn, ""))
932                         return conn;
933
934                 /* Insert dbName parameter value into struct */
935                 if (dbName && dbName[0] != '\0')
936                 {
937                         if (conn->dbName)
938                                 free(conn->dbName);
939                         conn->dbName = strdup(dbName);
940                 }
941         }
942
943         /*
944          * Insert remaining parameters into struct, overriding defaults (as well
945          * as any conflicting data from dbName taken as a conninfo).
946          */
947         if (pghost && pghost[0] != '\0')
948         {
949                 if (conn->pghost)
950                         free(conn->pghost);
951                 conn->pghost = strdup(pghost);
952         }
953
954         if (pgport && pgport[0] != '\0')
955         {
956                 if (conn->pgport)
957                         free(conn->pgport);
958                 conn->pgport = strdup(pgport);
959         }
960
961         if (pgoptions && pgoptions[0] != '\0')
962         {
963                 if (conn->pgoptions)
964                         free(conn->pgoptions);
965                 conn->pgoptions = strdup(pgoptions);
966         }
967
968         if (pgtty && pgtty[0] != '\0')
969         {
970                 if (conn->pgtty)
971                         free(conn->pgtty);
972                 conn->pgtty = strdup(pgtty);
973         }
974
975         if (login && login[0] != '\0')
976         {
977                 if (conn->pguser)
978                         free(conn->pguser);
979                 conn->pguser = strdup(login);
980         }
981
982         if (pwd && pwd[0] != '\0')
983         {
984                 if (conn->pgpass)
985                         free(conn->pgpass);
986                 conn->pgpass = strdup(pwd);
987         }
988
989         /*
990          * Compute derived options
991          */
992         if (!connectOptions2(conn))
993                 return conn;
994
995         /*
996          * Connect to the database
997          */
998         if (connectDBStart(conn))
999                 (void) connectDBComplete(conn);
1000
1001         return conn;
1002 }
1003
1004
1005 /* ----------
1006  * connectNoDelay -
1007  * Sets the TCP_NODELAY socket option.
1008  * Returns 1 if successful, 0 if not.
1009  * ----------
1010  */
1011 static int
1012 connectNoDelay(PGconn *conn)
1013 {
1014 #ifdef  TCP_NODELAY
1015         int                     on = 1;
1016
1017         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
1018                                    (char *) &on,
1019                                    sizeof(on)) < 0)
1020         {
1021                 char            sebuf[256];
1022
1023                 appendPQExpBuffer(&conn->errorMessage,
1024                         libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
1025                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1026                 return 0;
1027         }
1028 #endif
1029
1030         return 1;
1031 }
1032
1033
1034 /* ----------
1035  * connectFailureMessage -
1036  * create a friendly error message on connection failure.
1037  * ----------
1038  */
1039 static void
1040 connectFailureMessage(PGconn *conn, int errorno)
1041 {
1042         char            sebuf[256];
1043
1044 #ifdef HAVE_UNIX_SOCKETS
1045         if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1046         {
1047                 char            service[NI_MAXHOST];
1048
1049                 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
1050                                                    NULL, 0,
1051                                                    service, sizeof(service),
1052                                                    NI_NUMERICSERV);
1053                 appendPQExpBuffer(&conn->errorMessage,
1054                                                   libpq_gettext("could not connect to server: %s\n"
1055                                                         "\tIs the server running locally and accepting\n"
1056                                                         "\tconnections on Unix domain socket \"%s\"?\n"),
1057                                                   SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1058                                                   service);
1059         }
1060         else
1061 #endif   /* HAVE_UNIX_SOCKETS */
1062         {
1063                 char            host_addr[NI_MAXHOST];
1064                 const char *displayed_host;
1065                 struct sockaddr_storage *addr = &conn->raddr.addr;
1066
1067                 /*
1068                  * Optionally display the network address with the hostname. This is
1069                  * useful to distinguish between IPv4 and IPv6 connections.
1070                  */
1071                 if (conn->pghostaddr != NULL)
1072                         strlcpy(host_addr, conn->pghostaddr, NI_MAXHOST);
1073                 else if (addr->ss_family == AF_INET)
1074                 {
1075                         if (inet_net_ntop(AF_INET,
1076                                                           &((struct sockaddr_in *) addr)->sin_addr.s_addr,
1077                                                           32,
1078                                                           host_addr, sizeof(host_addr)) == NULL)
1079                                 strcpy(host_addr, "???");
1080                 }
1081 #ifdef HAVE_IPV6
1082                 else if (addr->ss_family == AF_INET6)
1083                 {
1084                         if (inet_net_ntop(AF_INET6,
1085                                                   &((struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
1086                                                           128,
1087                                                           host_addr, sizeof(host_addr)) == NULL)
1088                                 strcpy(host_addr, "???");
1089                 }
1090 #endif
1091                 else
1092                         strcpy(host_addr, "???");
1093
1094                 if (conn->pghostaddr && conn->pghostaddr[0] != '\0')
1095                         displayed_host = conn->pghostaddr;
1096                 else if (conn->pghost && conn->pghost[0] != '\0')
1097                         displayed_host = conn->pghost;
1098                 else
1099                         displayed_host = DefaultHost;
1100
1101                 /*
1102                  * If the user did not supply an IP address using 'hostaddr', and
1103                  * 'host' was missing or does not match our lookup, display the
1104                  * looked-up IP address.
1105                  */
1106                 if ((conn->pghostaddr == NULL) &&
1107                         (conn->pghost == NULL || strcmp(conn->pghost, host_addr) != 0))
1108                         appendPQExpBuffer(&conn->errorMessage,
1109                                                         libpq_gettext("could not connect to server: %s\n"
1110                                 "\tIs the server running on host \"%s\" (%s) and accepting\n"
1111                                                                            "\tTCP/IP connections on port %s?\n"),
1112                                                           SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1113                                                           displayed_host,
1114                                                           host_addr,
1115                                                           conn->pgport);
1116                 else
1117                         appendPQExpBuffer(&conn->errorMessage,
1118                                                         libpq_gettext("could not connect to server: %s\n"
1119                                          "\tIs the server running on host \"%s\" and accepting\n"
1120                                                                            "\tTCP/IP connections on port %s?\n"),
1121                                                           SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1122                                                           displayed_host,
1123                                                           conn->pgport);
1124         }
1125 }
1126
1127 /*
1128  * Should we use keepalives?  Returns 1 if yes, 0 if no, and -1 if
1129  * conn->keepalives is set to a value which is not parseable as an
1130  * integer.
1131  */
1132 static int
1133 useKeepalives(PGconn *conn)
1134 {
1135         char       *ep;
1136         int                     val;
1137
1138         if (conn->keepalives == NULL)
1139                 return 1;
1140         val = strtol(conn->keepalives, &ep, 10);
1141         if (*ep)
1142                 return -1;
1143         return val != 0 ? 1 : 0;
1144 }
1145
1146 #ifndef WIN32
1147 /*
1148  * Set the keepalive idle timer.
1149  */
1150 static int
1151 setKeepalivesIdle(PGconn *conn)
1152 {
1153         int                     idle;
1154
1155         if (conn->keepalives_idle == NULL)
1156                 return 1;
1157
1158         idle = atoi(conn->keepalives_idle);
1159         if (idle < 0)
1160                 idle = 0;
1161
1162 #ifdef TCP_KEEPIDLE
1163         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPIDLE,
1164                                    (char *) &idle, sizeof(idle)) < 0)
1165         {
1166                 char            sebuf[256];
1167
1168                 appendPQExpBuffer(&conn->errorMessage,
1169                                           libpq_gettext("setsockopt(TCP_KEEPIDLE) failed: %s\n"),
1170                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1171                 return 0;
1172         }
1173 #else
1174 #ifdef TCP_KEEPALIVE
1175         /* Darwin uses TCP_KEEPALIVE rather than TCP_KEEPIDLE */
1176         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPALIVE,
1177                                    (char *) &idle, sizeof(idle)) < 0)
1178         {
1179                 char            sebuf[256];
1180
1181                 appendPQExpBuffer(&conn->errorMessage,
1182                                          libpq_gettext("setsockopt(TCP_KEEPALIVE) failed: %s\n"),
1183                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1184                 return 0;
1185         }
1186 #endif
1187 #endif
1188
1189         return 1;
1190 }
1191
1192 /*
1193  * Set the keepalive interval.
1194  */
1195 static int
1196 setKeepalivesInterval(PGconn *conn)
1197 {
1198         int                     interval;
1199
1200         if (conn->keepalives_interval == NULL)
1201                 return 1;
1202
1203         interval = atoi(conn->keepalives_interval);
1204         if (interval < 0)
1205                 interval = 0;
1206
1207 #ifdef TCP_KEEPINTVL
1208         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1209                                    (char *) &interval, sizeof(interval)) < 0)
1210         {
1211                 char            sebuf[256];
1212
1213                 appendPQExpBuffer(&conn->errorMessage,
1214                                          libpq_gettext("setsockopt(TCP_KEEPINTVL) failed: %s\n"),
1215                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1216                 return 0;
1217         }
1218 #endif
1219
1220         return 1;
1221 }
1222
1223 /*
1224  * Set the count of lost keepalive packets that will trigger a connection
1225  * break.
1226  */
1227 static int
1228 setKeepalivesCount(PGconn *conn)
1229 {
1230         int                     count;
1231
1232         if (conn->keepalives_count == NULL)
1233                 return 1;
1234
1235         count = atoi(conn->keepalives_count);
1236         if (count < 0)
1237                 count = 0;
1238
1239 #ifdef TCP_KEEPCNT
1240         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPCNT,
1241                                    (char *) &count, sizeof(count)) < 0)
1242         {
1243                 char            sebuf[256];
1244
1245                 appendPQExpBuffer(&conn->errorMessage,
1246                                            libpq_gettext("setsockopt(TCP_KEEPCNT) failed: %s\n"),
1247                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1248                 return 0;
1249         }
1250 #endif
1251
1252         return 1;
1253 }
1254 #else                                                   /* Win32 */
1255 #ifdef SIO_KEEPALIVE_VALS
1256 /*
1257  * Enable keepalives and set the keepalive values on Win32,
1258  * where they are always set in one batch.
1259  */
1260 static int
1261 setKeepalivesWin32(PGconn *conn)
1262 {
1263         struct tcp_keepalive ka;
1264         DWORD           retsize;
1265         int                     idle = 0;
1266         int                     interval = 0;
1267
1268         if (conn->keepalives_idle)
1269                 idle = atoi(conn->keepalives_idle);
1270         if (idle <= 0)
1271                 idle = 2 * 60 * 60;             /* 2 hours = default */
1272
1273         if (conn->keepalives_interval)
1274                 interval = atoi(conn->keepalives_interval);
1275         if (interval <= 0)
1276                 interval = 1;                   /* 1 second = default */
1277
1278         ka.onoff = 1;
1279         ka.keepalivetime = idle * 1000;
1280         ka.keepaliveinterval = interval * 1000;
1281
1282         if (WSAIoctl(conn->sock,
1283                                  SIO_KEEPALIVE_VALS,
1284                                  (LPVOID) &ka,
1285                                  sizeof(ka),
1286                                  NULL,
1287                                  0,
1288                                  &retsize,
1289                                  NULL,
1290                                  NULL)
1291                 != 0)
1292         {
1293                 appendPQExpBuffer(&conn->errorMessage,
1294                                  libpq_gettext("WSAIoctl(SIO_KEEPALIVE_VALS) failed: %ui\n"),
1295                                                   WSAGetLastError());
1296                 return 0;
1297         }
1298         return 1;
1299 }
1300 #endif   /* SIO_KEEPALIVE_VALS */
1301 #endif   /* WIN32 */
1302
1303 /* ----------
1304  * connectDBStart -
1305  *              Begin the process of making a connection to the backend.
1306  *
1307  * Returns 1 if successful, 0 if not.
1308  * ----------
1309  */
1310 static int
1311 connectDBStart(PGconn *conn)
1312 {
1313         int                     portnum;
1314         char            portstr[MAXPGPATH];
1315         struct addrinfo *addrs = NULL;
1316         struct addrinfo hint;
1317         const char *node;
1318         int                     ret;
1319
1320         if (!conn)
1321                 return 0;
1322
1323         if (!conn->options_valid)
1324                 goto connect_errReturn;
1325
1326         /* Ensure our buffers are empty */
1327         conn->inStart = conn->inCursor = conn->inEnd = 0;
1328         conn->outCount = 0;
1329
1330         /*
1331          * Determine the parameters to pass to pg_getaddrinfo_all.
1332          */
1333
1334         /* Initialize hint structure */
1335         MemSet(&hint, 0, sizeof(hint));
1336         hint.ai_socktype = SOCK_STREAM;
1337         hint.ai_family = AF_UNSPEC;
1338
1339         /* Set up port number as a string */
1340         if (conn->pgport != NULL && conn->pgport[0] != '\0')
1341         {
1342                 portnum = atoi(conn->pgport);
1343                 if (portnum < 1 || portnum > 65535)
1344                 {
1345                         appendPQExpBuffer(&conn->errorMessage,
1346                                                           libpq_gettext("invalid port number: \"%s\"\n"),
1347                                                           conn->pgport);
1348                         conn->options_valid = false;
1349                         goto connect_errReturn;
1350                 }
1351         }
1352         else
1353                 portnum = DEF_PGPORT;
1354         snprintf(portstr, sizeof(portstr), "%d", portnum);
1355
1356         if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
1357         {
1358                 /* Using pghostaddr avoids a hostname lookup */
1359                 node = conn->pghostaddr;
1360                 hint.ai_family = AF_UNSPEC;
1361                 hint.ai_flags = AI_NUMERICHOST;
1362         }
1363         else if (conn->pghost != NULL && conn->pghost[0] != '\0')
1364         {
1365                 /* Using pghost, so we have to look-up the hostname */
1366                 node = conn->pghost;
1367                 hint.ai_family = AF_UNSPEC;
1368         }
1369         else
1370         {
1371 #ifdef HAVE_UNIX_SOCKETS
1372                 /* pghostaddr and pghost are NULL, so use Unix domain socket */
1373                 node = NULL;
1374                 hint.ai_family = AF_UNIX;
1375                 UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
1376                 if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
1377                 {
1378                         appendPQExpBuffer(&conn->errorMessage,
1379                                                           libpq_gettext("Unix-domain socket path \"%s\" is too long (maximum %d bytes)\n"),
1380                                                           portstr,
1381                                                           (int) (UNIXSOCK_PATH_BUFLEN - 1));
1382                         conn->options_valid = false;
1383                         goto connect_errReturn;
1384                 }
1385 #else
1386                 /* Without Unix sockets, default to localhost instead */
1387                 node = DefaultHost;
1388                 hint.ai_family = AF_UNSPEC;
1389 #endif   /* HAVE_UNIX_SOCKETS */
1390         }
1391
1392         /* Use pg_getaddrinfo_all() to resolve the address */
1393         ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs);
1394         if (ret || !addrs)
1395         {
1396                 if (node)
1397                         appendPQExpBuffer(&conn->errorMessage,
1398                                                           libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
1399                                                           node, gai_strerror(ret));
1400                 else
1401                         appendPQExpBuffer(&conn->errorMessage,
1402                                                           libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
1403                                                           portstr, gai_strerror(ret));
1404                 if (addrs)
1405                         pg_freeaddrinfo_all(hint.ai_family, addrs);
1406                 conn->options_valid = false;
1407                 goto connect_errReturn;
1408         }
1409
1410 #ifdef USE_SSL
1411         /* setup values based on SSL mode */
1412         if (conn->sslmode[0] == 'd')    /* "disable" */
1413                 conn->allow_ssl_try = false;
1414         else if (conn->sslmode[0] == 'a')       /* "allow" */
1415                 conn->wait_ssl_try = true;
1416 #endif
1417
1418         /*
1419          * Set up to try to connect, with protocol 3.0 as the first attempt.
1420          */
1421         conn->addrlist = addrs;
1422         conn->addr_cur = addrs;
1423         conn->addrlist_family = hint.ai_family;
1424         conn->pversion = PG_PROTOCOL(3, 0);
1425         conn->send_appname = true;
1426         conn->status = CONNECTION_NEEDED;
1427
1428         /*
1429          * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
1430          * so that it can easily be re-executed if needed again during the
1431          * asynchronous startup process.  However, we must run it once here,
1432          * because callers expect a success return from this routine to mean that
1433          * we are in PGRES_POLLING_WRITING connection state.
1434          */
1435         if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
1436                 return 1;
1437
1438 connect_errReturn:
1439         pqDropConnection(conn);
1440         conn->status = CONNECTION_BAD;
1441         return 0;
1442 }
1443
1444
1445 /*
1446  *              connectDBComplete
1447  *
1448  * Block and complete a connection.
1449  *
1450  * Returns 1 on success, 0 on failure.
1451  */
1452 static int
1453 connectDBComplete(PGconn *conn)
1454 {
1455         PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
1456         time_t          finish_time = ((time_t) -1);
1457
1458         if (conn == NULL || conn->status == CONNECTION_BAD)
1459                 return 0;
1460
1461         /*
1462          * Set up a time limit, if connect_timeout isn't zero.
1463          */
1464         if (conn->connect_timeout != NULL)
1465         {
1466                 int                     timeout = atoi(conn->connect_timeout);
1467
1468                 if (timeout > 0)
1469                 {
1470                         /*
1471                          * Rounding could cause connection to fail; need at least 2 secs
1472                          */
1473                         if (timeout < 2)
1474                                 timeout = 2;
1475                         /* calculate the finish time based on start + timeout */
1476                         finish_time = time(NULL) + timeout;
1477                 }
1478         }
1479
1480         for (;;)
1481         {
1482                 /*
1483                  * Wait, if necessary.  Note that the initial state (just after
1484                  * PQconnectStart) is to wait for the socket to select for writing.
1485                  */
1486                 switch (flag)
1487                 {
1488                         case PGRES_POLLING_OK:
1489
1490                                 /*
1491                                  * Reset stored error messages since we now have a working
1492                                  * connection
1493                                  */
1494                                 resetPQExpBuffer(&conn->errorMessage);
1495                                 return 1;               /* success! */
1496
1497                         case PGRES_POLLING_READING:
1498                                 if (pqWaitTimed(1, 0, conn, finish_time))
1499                                 {
1500                                         conn->status = CONNECTION_BAD;
1501                                         return 0;
1502                                 }
1503                                 break;
1504
1505                         case PGRES_POLLING_WRITING:
1506                                 if (pqWaitTimed(0, 1, conn, finish_time))
1507                                 {
1508                                         conn->status = CONNECTION_BAD;
1509                                         return 0;
1510                                 }
1511                                 break;
1512
1513                         default:
1514                                 /* Just in case we failed to set it in PQconnectPoll */
1515                                 conn->status = CONNECTION_BAD;
1516                                 return 0;
1517                 }
1518
1519                 /*
1520                  * Now try to advance the state machine.
1521                  */
1522                 flag = PQconnectPoll(conn);
1523         }
1524 }
1525
1526 /* ----------------
1527  *              PQconnectPoll
1528  *
1529  * Poll an asynchronous connection.
1530  *
1531  * Returns a PostgresPollingStatusType.
1532  * Before calling this function, use select(2) to determine when data
1533  * has arrived..
1534  *
1535  * You must call PQfinish whether or not this fails.
1536  *
1537  * This function and PQconnectStart are intended to allow connections to be
1538  * made without blocking the execution of your program on remote I/O. However,
1539  * there are a number of caveats:
1540  *
1541  *       o      If you call PQtrace, ensure that the stream object into which you trace
1542  *              will not block.
1543  *       o      If you do not supply an IP address for the remote host (i.e. you
1544  *              supply a host name instead) then PQconnectStart will block on
1545  *              gethostbyname.  You will be fine if using Unix sockets (i.e. by
1546  *              supplying neither a host name nor a host address).
1547  *       o      If your backend wants to use Kerberos authentication then you must
1548  *              supply both a host name and a host address, otherwise this function
1549  *              may block on gethostname.
1550  *
1551  * ----------------
1552  */
1553 PostgresPollingStatusType
1554 PQconnectPoll(PGconn *conn)
1555 {
1556         PGresult   *res;
1557         char            sebuf[256];
1558         int                     optval;
1559
1560         if (conn == NULL)
1561                 return PGRES_POLLING_FAILED;
1562
1563         /* Get the new data */
1564         switch (conn->status)
1565         {
1566                         /*
1567                          * We really shouldn't have been polled in these two cases, but we
1568                          * can handle it.
1569                          */
1570                 case CONNECTION_BAD:
1571                         return PGRES_POLLING_FAILED;
1572                 case CONNECTION_OK:
1573                         return PGRES_POLLING_OK;
1574
1575                         /* These are reading states */
1576                 case CONNECTION_AWAITING_RESPONSE:
1577                 case CONNECTION_AUTH_OK:
1578                         {
1579                                 /* Load waiting data */
1580                                 int                     n = pqReadData(conn);
1581
1582                                 if (n < 0)
1583                                         goto error_return;
1584                                 if (n == 0)
1585                                         return PGRES_POLLING_READING;
1586
1587                                 break;
1588                         }
1589
1590                         /* These are writing states, so we just proceed. */
1591                 case CONNECTION_STARTED:
1592                 case CONNECTION_MADE:
1593                         break;
1594
1595                         /* We allow pqSetenvPoll to decide whether to proceed. */
1596                 case CONNECTION_SETENV:
1597                         break;
1598
1599                         /* Special cases: proceed without waiting. */
1600                 case CONNECTION_SSL_STARTUP:
1601                 case CONNECTION_NEEDED:
1602                         break;
1603
1604                 default:
1605                         appendPQExpBufferStr(&conn->errorMessage,
1606                                                                  libpq_gettext(
1607                                                                                            "invalid connection state, "
1608                                                                  "probably indicative of memory corruption\n"
1609                                                                                         ));
1610                         goto error_return;
1611         }
1612
1613
1614 keep_going:                                             /* We will come back to here until there is
1615                                                                  * nothing left to do. */
1616         switch (conn->status)
1617         {
1618                 case CONNECTION_NEEDED:
1619                         {
1620                                 /*
1621                                  * Try to initiate a connection to one of the addresses
1622                                  * returned by pg_getaddrinfo_all().  conn->addr_cur is the
1623                                  * next one to try. We fail when we run out of addresses.
1624                                  */
1625                                 while (conn->addr_cur != NULL)
1626                                 {
1627                                         struct addrinfo *addr_cur = conn->addr_cur;
1628
1629                                         /* Remember current address for possible error msg */
1630                                         memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1631                                                    addr_cur->ai_addrlen);
1632                                         conn->raddr.salen = addr_cur->ai_addrlen;
1633
1634                                         conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1635                                         if (conn->sock == PGINVALID_SOCKET)
1636                                         {
1637                                                 /*
1638                                                  * ignore socket() failure if we have more addresses
1639                                                  * to try
1640                                                  */
1641                                                 if (addr_cur->ai_next != NULL)
1642                                                 {
1643                                                         conn->addr_cur = addr_cur->ai_next;
1644                                                         continue;
1645                                                 }
1646                                                 appendPQExpBuffer(&conn->errorMessage,
1647                                                           libpq_gettext("could not create socket: %s\n"),
1648                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1649                                                 break;
1650                                         }
1651
1652                                         /*
1653                                          * Select socket options: no delay of outgoing data for
1654                                          * TCP sockets, nonblock mode, close-on-exec. Fail if any
1655                                          * of this fails.
1656                                          */
1657                                         if (!IS_AF_UNIX(addr_cur->ai_family))
1658                                         {
1659                                                 if (!connectNoDelay(conn))
1660                                                 {
1661                                                         pqDropConnection(conn);
1662                                                         conn->addr_cur = addr_cur->ai_next;
1663                                                         continue;
1664                                                 }
1665                                         }
1666                                         if (!pg_set_noblock(conn->sock))
1667                                         {
1668                                                 appendPQExpBuffer(&conn->errorMessage,
1669                                                                                   libpq_gettext("could not set socket to nonblocking mode: %s\n"),
1670                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1671                                                 pqDropConnection(conn);
1672                                                 conn->addr_cur = addr_cur->ai_next;
1673                                                 continue;
1674                                         }
1675
1676 #ifdef F_SETFD
1677                                         if (fcntl(conn->sock, F_SETFD, FD_CLOEXEC) == -1)
1678                                         {
1679                                                 appendPQExpBuffer(&conn->errorMessage,
1680                                                                                   libpq_gettext("could not set socket to close-on-exec mode: %s\n"),
1681                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1682                                                 pqDropConnection(conn);
1683                                                 conn->addr_cur = addr_cur->ai_next;
1684                                                 continue;
1685                                         }
1686 #endif   /* F_SETFD */
1687
1688                                         if (!IS_AF_UNIX(addr_cur->ai_family))
1689                                         {
1690 #ifndef WIN32
1691                                                 int                     on = 1;
1692 #endif
1693                                                 int                     usekeepalives = useKeepalives(conn);
1694                                                 int                     err = 0;
1695
1696                                                 if (usekeepalives < 0)
1697                                                 {
1698                                                         appendPQExpBufferStr(&conn->errorMessage,
1699                                                                                                  libpq_gettext("keepalives parameter must be an integer\n"));
1700                                                         err = 1;
1701                                                 }
1702                                                 else if (usekeepalives == 0)
1703                                                 {
1704                                                         /* Do nothing */
1705                                                 }
1706 #ifndef WIN32
1707                                                 else if (setsockopt(conn->sock,
1708                                                                                         SOL_SOCKET, SO_KEEPALIVE,
1709                                                                                         (char *) &on, sizeof(on)) < 0)
1710                                                 {
1711                                                         appendPQExpBuffer(&conn->errorMessage,
1712                                                                                           libpq_gettext("setsockopt(SO_KEEPALIVE) failed: %s\n"),
1713                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1714                                                         err = 1;
1715                                                 }
1716                                                 else if (!setKeepalivesIdle(conn)
1717                                                                  || !setKeepalivesInterval(conn)
1718                                                                  || !setKeepalivesCount(conn))
1719                                                         err = 1;
1720 #else                                                   /* WIN32 */
1721 #ifdef SIO_KEEPALIVE_VALS
1722                                                 else if (!setKeepalivesWin32(conn))
1723                                                         err = 1;
1724 #endif   /* SIO_KEEPALIVE_VALS */
1725 #endif   /* WIN32 */
1726
1727                                                 if (err)
1728                                                 {
1729                                                         pqDropConnection(conn);
1730                                                         conn->addr_cur = addr_cur->ai_next;
1731                                                         continue;
1732                                                 }
1733                                         }
1734
1735                                         /*----------
1736                                          * We have three methods of blocking SIGPIPE during
1737                                          * send() calls to this socket:
1738                                          *
1739                                          *      - setsockopt(sock, SO_NOSIGPIPE)
1740                                          *      - send(sock, ..., MSG_NOSIGNAL)
1741                                          *      - setting the signal mask to SIG_IGN during send()
1742                                          *
1743                                          * The third method requires three syscalls per send,
1744                                          * so we prefer either of the first two, but they are
1745                                          * less portable.  The state is tracked in the following
1746                                          * members of PGconn:
1747                                          *
1748                                          * conn->sigpipe_so             - we have set up SO_NOSIGPIPE
1749                                          * conn->sigpipe_flag   - we're specifying MSG_NOSIGNAL
1750                                          *
1751                                          * If we can use SO_NOSIGPIPE, then set sigpipe_so here
1752                                          * and we're done.  Otherwise, set sigpipe_flag so that
1753                                          * we will try MSG_NOSIGNAL on sends.  If we get an error
1754                                          * with MSG_NOSIGNAL, we'll clear that flag and revert to
1755                                          * signal masking.
1756                                          *----------
1757                                          */
1758                                         conn->sigpipe_so = false;
1759 #ifdef MSG_NOSIGNAL
1760                                         conn->sigpipe_flag = true;
1761 #else
1762                                         conn->sigpipe_flag = false;
1763 #endif   /* MSG_NOSIGNAL */
1764
1765 #ifdef SO_NOSIGPIPE
1766                                         optval = 1;
1767                                         if (setsockopt(conn->sock, SOL_SOCKET, SO_NOSIGPIPE,
1768                                                                    (char *) &optval, sizeof(optval)) == 0)
1769                                         {
1770                                                 conn->sigpipe_so = true;
1771                                                 conn->sigpipe_flag = false;
1772                                         }
1773 #endif   /* SO_NOSIGPIPE */
1774
1775                                         /*
1776                                          * Start/make connection.  This should not block, since we
1777                                          * are in nonblock mode.  If it does, well, too bad.
1778                                          */
1779                                         if (connect(conn->sock, addr_cur->ai_addr,
1780                                                                 addr_cur->ai_addrlen) < 0)
1781                                         {
1782                                                 if (SOCK_ERRNO == EINPROGRESS ||
1783 #ifdef WIN32
1784                                                         SOCK_ERRNO == EWOULDBLOCK ||
1785 #endif
1786                                                         SOCK_ERRNO == EINTR)
1787                                                 {
1788                                                         /*
1789                                                          * This is fine - we're in non-blocking mode, and
1790                                                          * the connection is in progress.  Tell caller to
1791                                                          * wait for write-ready on socket.
1792                                                          */
1793                                                         conn->status = CONNECTION_STARTED;
1794                                                         return PGRES_POLLING_WRITING;
1795                                                 }
1796                                                 /* otherwise, trouble */
1797                                         }
1798                                         else
1799                                         {
1800                                                 /*
1801                                                  * Hm, we're connected already --- seems the "nonblock
1802                                                  * connection" wasn't.  Advance the state machine and
1803                                                  * go do the next stuff.
1804                                                  */
1805                                                 conn->status = CONNECTION_STARTED;
1806                                                 goto keep_going;
1807                                         }
1808
1809                                         /*
1810                                          * This connection failed --- set up error report, then
1811                                          * close socket (do it this way in case close() affects
1812                                          * the value of errno...).      We will ignore the connect()
1813                                          * failure and keep going if there are more addresses.
1814                                          */
1815                                         connectFailureMessage(conn, SOCK_ERRNO);
1816                                         pqDropConnection(conn);
1817
1818                                         /*
1819                                          * Try the next address, if any.
1820                                          */
1821                                         conn->addr_cur = addr_cur->ai_next;
1822                                 }                               /* loop over addresses */
1823
1824                                 /*
1825                                  * Ooops, no more addresses.  An appropriate error message is
1826                                  * already set up, so just set the right status.
1827                                  */
1828                                 goto error_return;
1829                         }
1830
1831                 case CONNECTION_STARTED:
1832                         {
1833                                 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1834
1835                                 /*
1836                                  * Write ready, since we've made it here, so the connection
1837                                  * has been made ... or has failed.
1838                                  */
1839
1840                                 /*
1841                                  * Now check (using getsockopt) that there is not an error
1842                                  * state waiting for us on the socket.
1843                                  */
1844
1845                                 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1846                                                            (char *) &optval, &optlen) == -1)
1847                                 {
1848                                         appendPQExpBuffer(&conn->errorMessage,
1849                                         libpq_gettext("could not get socket error status: %s\n"),
1850                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1851                                         goto error_return;
1852                                 }
1853                                 else if (optval != 0)
1854                                 {
1855                                         /*
1856                                          * When using a nonblocking connect, we will typically see
1857                                          * connect failures at this point, so provide a friendly
1858                                          * error message.
1859                                          */
1860                                         connectFailureMessage(conn, optval);
1861                                         pqDropConnection(conn);
1862
1863                                         /*
1864                                          * If more addresses remain, keep trying, just as in the
1865                                          * case where connect() returned failure immediately.
1866                                          */
1867                                         if (conn->addr_cur->ai_next != NULL)
1868                                         {
1869                                                 conn->addr_cur = conn->addr_cur->ai_next;
1870                                                 conn->status = CONNECTION_NEEDED;
1871                                                 goto keep_going;
1872                                         }
1873                                         goto error_return;
1874                                 }
1875
1876                                 /* Fill in the client address */
1877                                 conn->laddr.salen = sizeof(conn->laddr.addr);
1878                                 if (getsockname(conn->sock,
1879                                                                 (struct sockaddr *) & conn->laddr.addr,
1880                                                                 &conn->laddr.salen) < 0)
1881                                 {
1882                                         appendPQExpBuffer(&conn->errorMessage,
1883                                                                           libpq_gettext("could not get client address from socket: %s\n"),
1884                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1885                                         goto error_return;
1886                                 }
1887
1888                                 /*
1889                                  * Make sure we can write before advancing to next step.
1890                                  */
1891                                 conn->status = CONNECTION_MADE;
1892                                 return PGRES_POLLING_WRITING;
1893                         }
1894
1895                 case CONNECTION_MADE:
1896                         {
1897                                 char       *startpacket;
1898                                 int                     packetlen;
1899
1900 #ifdef HAVE_UNIX_SOCKETS
1901
1902                                 /*
1903                                  * Implement requirepeer check, if requested and it's a
1904                                  * Unix-domain socket.
1905                                  */
1906                                 if (conn->requirepeer && conn->requirepeer[0] &&
1907                                         IS_AF_UNIX(conn->raddr.addr.ss_family))
1908                                 {
1909                                         char            pwdbuf[BUFSIZ];
1910                                         struct passwd pass_buf;
1911                                         struct passwd *pass;
1912                                         uid_t           uid;
1913                                         gid_t           gid;
1914
1915                                         errno = 0;
1916                                         if (getpeereid(conn->sock, &uid, &gid) != 0)
1917                                         {
1918                                                 /*
1919                                                  * Provide special error message if getpeereid is a
1920                                                  * stub
1921                                                  */
1922                                                 if (errno == ENOSYS)
1923                                                         appendPQExpBufferStr(&conn->errorMessage,
1924                                                                                                  libpq_gettext("requirepeer parameter is not supported on this platform\n"));
1925                                                 else
1926                                                         appendPQExpBuffer(&conn->errorMessage,
1927                                                                                           libpq_gettext("could not get peer credentials: %s\n"),
1928                                                                         pqStrerror(errno, sebuf, sizeof(sebuf)));
1929                                                 goto error_return;
1930                                         }
1931
1932                                         pqGetpwuid(uid, &pass_buf, pwdbuf, sizeof(pwdbuf), &pass);
1933
1934                                         if (pass == NULL)
1935                                         {
1936                                                 appendPQExpBuffer(&conn->errorMessage,
1937                                                                                   libpq_gettext("local user with ID %d does not exist\n"),
1938                                                                                   (int) uid);
1939                                                 goto error_return;
1940                                         }
1941
1942                                         if (strcmp(pass->pw_name, conn->requirepeer) != 0)
1943                                         {
1944                                                 appendPQExpBuffer(&conn->errorMessage,
1945                                                                                   libpq_gettext("requirepeer specifies \"%s\", but actual peer user name is \"%s\"\n"),
1946                                                                                   conn->requirepeer, pass->pw_name);
1947                                                 goto error_return;
1948                                         }
1949                                 }
1950 #endif   /* HAVE_UNIX_SOCKETS */
1951
1952 #ifdef USE_SSL
1953
1954                                 /*
1955                                  * If SSL is enabled and we haven't already got it running,
1956                                  * request it instead of sending the startup message.
1957                                  */
1958                                 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1959                                 {
1960                                         /* Don't bother requesting SSL over a Unix socket */
1961                                         conn->allow_ssl_try = false;
1962                                 }
1963                                 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
1964                                         conn->ssl == NULL)
1965                                 {
1966                                         ProtocolVersion pv;
1967
1968                                         /*
1969                                          * Send the SSL request packet.
1970                                          *
1971                                          * Theoretically, this could block, but it really
1972                                          * shouldn't since we only got here if the socket is
1973                                          * write-ready.
1974                                          */
1975                                         pv = htonl(NEGOTIATE_SSL_CODE);
1976                                         if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1977                                         {
1978                                                 appendPQExpBuffer(&conn->errorMessage,
1979                                                                                   libpq_gettext("could not send SSL negotiation packet: %s\n"),
1980                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1981                                                 goto error_return;
1982                                         }
1983                                         /* Ok, wait for response */
1984                                         conn->status = CONNECTION_SSL_STARTUP;
1985                                         return PGRES_POLLING_READING;
1986                                 }
1987 #endif   /* USE_SSL */
1988
1989                                 /*
1990                                  * Build the startup packet.
1991                                  */
1992                                 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1993                                         startpacket = pqBuildStartupPacket3(conn, &packetlen,
1994                                                                                                                 EnvironmentOptions);
1995                                 else
1996                                         startpacket = pqBuildStartupPacket2(conn, &packetlen,
1997                                                                                                                 EnvironmentOptions);
1998                                 if (!startpacket)
1999                                 {
2000                                         /*
2001                                          * will not appendbuffer here, since it's likely to also
2002                                          * run out of memory
2003                                          */
2004                                         printfPQExpBuffer(&conn->errorMessage,
2005                                                                           libpq_gettext("out of memory\n"));
2006                                         goto error_return;
2007                                 }
2008
2009                                 /*
2010                                  * Send the startup packet.
2011                                  *
2012                                  * Theoretically, this could block, but it really shouldn't
2013                                  * since we only got here if the socket is write-ready.
2014                                  */
2015                                 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
2016                                 {
2017                                         appendPQExpBuffer(&conn->errorMessage,
2018                                                 libpq_gettext("could not send startup packet: %s\n"),
2019                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2020                                         free(startpacket);
2021                                         goto error_return;
2022                                 }
2023
2024                                 free(startpacket);
2025
2026                                 conn->status = CONNECTION_AWAITING_RESPONSE;
2027                                 return PGRES_POLLING_READING;
2028                         }
2029
2030                         /*
2031                          * Handle SSL negotiation: wait for postmaster messages and
2032                          * respond as necessary.
2033                          */
2034                 case CONNECTION_SSL_STARTUP:
2035                         {
2036 #ifdef USE_SSL
2037                                 PostgresPollingStatusType pollres;
2038
2039                                 /*
2040                                  * On first time through, get the postmaster's response to our
2041                                  * SSL negotiation packet.
2042                                  */
2043                                 if (conn->ssl == NULL)
2044                                 {
2045                                         /*
2046                                          * We use pqReadData here since it has the logic to
2047                                          * distinguish no-data-yet from connection closure. Since
2048                                          * conn->ssl isn't set, a plain recv() will occur.
2049                                          */
2050                                         char            SSLok;
2051                                         int                     rdresult;
2052
2053                                         rdresult = pqReadData(conn);
2054                                         if (rdresult < 0)
2055                                         {
2056                                                 /* errorMessage is already filled in */
2057                                                 goto error_return;
2058                                         }
2059                                         if (rdresult == 0)
2060                                         {
2061                                                 /* caller failed to wait for data */
2062                                                 return PGRES_POLLING_READING;
2063                                         }
2064                                         if (pqGetc(&SSLok, conn) < 0)
2065                                         {
2066                                                 /* should not happen really */
2067                                                 return PGRES_POLLING_READING;
2068                                         }
2069                                         if (SSLok == 'S')
2070                                         {
2071                                                 /* mark byte consumed */
2072                                                 conn->inStart = conn->inCursor;
2073                                                 /* Set up global SSL state if required */
2074                                                 if (pqsecure_initialize(conn) != 0)
2075                                                         goto error_return;
2076                                         }
2077                                         else if (SSLok == 'N')
2078                                         {
2079                                                 /* mark byte consumed */
2080                                                 conn->inStart = conn->inCursor;
2081                                                 /* OK to do without SSL? */
2082                                                 if (conn->sslmode[0] == 'r' ||  /* "require" */
2083                                                         conn->sslmode[0] == 'v')        /* "verify-ca" or
2084                                                                                                                  * "verify-full" */
2085                                                 {
2086                                                         /* Require SSL, but server does not want it */
2087                                                         appendPQExpBufferStr(&conn->errorMessage,
2088                                                                                                  libpq_gettext("server does not support SSL, but SSL was required\n"));
2089                                                         goto error_return;
2090                                                 }
2091                                                 /* Otherwise, proceed with normal startup */
2092                                                 conn->allow_ssl_try = false;
2093                                                 conn->status = CONNECTION_MADE;
2094                                                 return PGRES_POLLING_WRITING;
2095                                         }
2096                                         else if (SSLok == 'E')
2097                                         {
2098                                                 /*
2099                                                  * Server failure of some sort, such as failure to
2100                                                  * fork a backend process.      We need to process and
2101                                                  * report the error message, which might be formatted
2102                                                  * according to either protocol 2 or protocol 3.
2103                                                  * Rather than duplicate the code for that, we flip
2104                                                  * into AWAITING_RESPONSE state and let the code there
2105                                                  * deal with it.  Note we have *not* consumed the "E"
2106                                                  * byte here.
2107                                                  */
2108                                                 conn->status = CONNECTION_AWAITING_RESPONSE;
2109                                                 goto keep_going;
2110                                         }
2111                                         else
2112                                         {
2113                                                 appendPQExpBuffer(&conn->errorMessage,
2114                                                                                   libpq_gettext("received invalid response to SSL negotiation: %c\n"),
2115                                                                                   SSLok);
2116                                                 goto error_return;
2117                                         }
2118                                 }
2119
2120                                 /*
2121                                  * Begin or continue the SSL negotiation process.
2122                                  */
2123                                 pollres = pqsecure_open_client(conn);
2124                                 if (pollres == PGRES_POLLING_OK)
2125                                 {
2126                                         /* SSL handshake done, ready to send startup packet */
2127                                         conn->status = CONNECTION_MADE;
2128                                         return PGRES_POLLING_WRITING;
2129                                 }
2130                                 if (pollres == PGRES_POLLING_FAILED)
2131                                 {
2132                                         /*
2133                                          * Failed ... if sslmode is "prefer" then do a non-SSL
2134                                          * retry
2135                                          */
2136                                         if (conn->sslmode[0] == 'p' /* "prefer" */
2137                                                 && conn->allow_ssl_try  /* redundant? */
2138                                                 && !conn->wait_ssl_try) /* redundant? */
2139                                         {
2140                                                 /* only retry once */
2141                                                 conn->allow_ssl_try = false;
2142                                                 /* Must drop the old connection */
2143                                                 pqDropConnection(conn);
2144                                                 conn->status = CONNECTION_NEEDED;
2145                                                 goto keep_going;
2146                                         }
2147                                 }
2148                                 return pollres;
2149 #else                                                   /* !USE_SSL */
2150                                 /* can't get here */
2151                                 goto error_return;
2152 #endif   /* USE_SSL */
2153                         }
2154
2155                         /*
2156                          * Handle authentication exchange: wait for postmaster messages
2157                          * and respond as necessary.
2158                          */
2159                 case CONNECTION_AWAITING_RESPONSE:
2160                         {
2161                                 char            beresp;
2162                                 int                     msgLength;
2163                                 int                     avail;
2164                                 AuthRequest areq;
2165
2166                                 /*
2167                                  * Scan the message from current point (note that if we find
2168                                  * the message is incomplete, we will return without advancing
2169                                  * inStart, and resume here next time).
2170                                  */
2171                                 conn->inCursor = conn->inStart;
2172
2173                                 /* Read type byte */
2174                                 if (pqGetc(&beresp, conn))
2175                                 {
2176                                         /* We'll come back when there is more data */
2177                                         return PGRES_POLLING_READING;
2178                                 }
2179
2180                                 /*
2181                                  * Validate message type: we expect only an authentication
2182                                  * request or an error here.  Anything else probably means
2183                                  * it's not Postgres on the other end at all.
2184                                  */
2185                                 if (!(beresp == 'R' || beresp == 'E'))
2186                                 {
2187                                         appendPQExpBuffer(&conn->errorMessage,
2188                                                                           libpq_gettext(
2189                                                                           "expected authentication request from "
2190                                                                                                 "server, but received %c\n"),
2191                                                                           beresp);
2192                                         goto error_return;
2193                                 }
2194
2195                                 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2196                                 {
2197                                         /* Read message length word */
2198                                         if (pqGetInt(&msgLength, 4, conn))
2199                                         {
2200                                                 /* We'll come back when there is more data */
2201                                                 return PGRES_POLLING_READING;
2202                                         }
2203                                 }
2204                                 else
2205                                 {
2206                                         /* Set phony message length to disable checks below */
2207                                         msgLength = 8;
2208                                 }
2209
2210                                 /*
2211                                  * Try to validate message length before using it.
2212                                  * Authentication requests can't be very large, although GSS
2213                                  * auth requests may not be that small.  Errors can be a
2214                                  * little larger, but not huge.  If we see a large apparent
2215                                  * length in an error, it means we're really talking to a
2216                                  * pre-3.0-protocol server; cope.
2217                                  */
2218                                 if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
2219                                 {
2220                                         appendPQExpBuffer(&conn->errorMessage,
2221                                                                           libpq_gettext(
2222                                                                           "expected authentication request from "
2223                                                                                                 "server, but received %c\n"),
2224                                                                           beresp);
2225                                         goto error_return;
2226                                 }
2227
2228                                 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
2229                                 {
2230                                         /* Handle error from a pre-3.0 server */
2231                                         conn->inCursor = conn->inStart + 1; /* reread data */
2232                                         if (pqGets_append(&conn->errorMessage, conn))
2233                                         {
2234                                                 /* We'll come back when there is more data */
2235                                                 return PGRES_POLLING_READING;
2236                                         }
2237                                         /* OK, we read the message; mark data consumed */
2238                                         conn->inStart = conn->inCursor;
2239
2240                                         /*
2241                                          * The postmaster typically won't end its message with a
2242                                          * newline, so add one to conform to libpq conventions.
2243                                          */
2244                                         appendPQExpBufferChar(&conn->errorMessage, '\n');
2245
2246                                         /*
2247                                          * If we tried to open the connection in 3.0 protocol,
2248                                          * fall back to 2.0 protocol.
2249                                          */
2250                                         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2251                                         {
2252                                                 conn->pversion = PG_PROTOCOL(2, 0);
2253                                                 /* Must drop the old connection */
2254                                                 pqDropConnection(conn);
2255                                                 conn->status = CONNECTION_NEEDED;
2256                                                 goto keep_going;
2257                                         }
2258
2259                                         goto error_return;
2260                                 }
2261
2262                                 /*
2263                                  * Can't process if message body isn't all here yet.
2264                                  *
2265                                  * (In protocol 2.0 case, we are assuming messages carry at
2266                                  * least 4 bytes of data.)
2267                                  */
2268                                 msgLength -= 4;
2269                                 avail = conn->inEnd - conn->inCursor;
2270                                 if (avail < msgLength)
2271                                 {
2272                                         /*
2273                                          * Before returning, try to enlarge the input buffer if
2274                                          * needed to hold the whole message; see notes in
2275                                          * pqParseInput3.
2276                                          */
2277                                         if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
2278                                                                                          conn))
2279                                                 goto error_return;
2280                                         /* We'll come back when there is more data */
2281                                         return PGRES_POLLING_READING;
2282                                 }
2283
2284                                 /* Handle errors. */
2285                                 if (beresp == 'E')
2286                                 {
2287                                         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2288                                         {
2289                                                 if (pqGetErrorNotice3(conn, true))
2290                                                 {
2291                                                         /* We'll come back when there is more data */
2292                                                         return PGRES_POLLING_READING;
2293                                                 }
2294                                         }
2295                                         else
2296                                         {
2297                                                 if (pqGets_append(&conn->errorMessage, conn))
2298                                                 {
2299                                                         /* We'll come back when there is more data */
2300                                                         return PGRES_POLLING_READING;
2301                                                 }
2302                                         }
2303                                         /* OK, we read the message; mark data consumed */
2304                                         conn->inStart = conn->inCursor;
2305
2306 #ifdef USE_SSL
2307
2308                                         /*
2309                                          * if sslmode is "allow" and we haven't tried an SSL
2310                                          * connection already, then retry with an SSL connection
2311                                          */
2312                                         if (conn->sslmode[0] == 'a' /* "allow" */
2313                                                 && conn->ssl == NULL
2314                                                 && conn->allow_ssl_try
2315                                                 && conn->wait_ssl_try)
2316                                         {
2317                                                 /* only retry once */
2318                                                 conn->wait_ssl_try = false;
2319                                                 /* Must drop the old connection */
2320                                                 pqDropConnection(conn);
2321                                                 conn->status = CONNECTION_NEEDED;
2322                                                 goto keep_going;
2323                                         }
2324
2325                                         /*
2326                                          * if sslmode is "prefer" and we're in an SSL connection,
2327                                          * then do a non-SSL retry
2328                                          */
2329                                         if (conn->sslmode[0] == 'p' /* "prefer" */
2330                                                 && conn->allow_ssl_try
2331                                                 && !conn->wait_ssl_try) /* redundant? */
2332                                         {
2333                                                 /* only retry once */
2334                                                 conn->allow_ssl_try = false;
2335                                                 /* Must drop the old connection */
2336                                                 pqDropConnection(conn);
2337                                                 conn->status = CONNECTION_NEEDED;
2338                                                 goto keep_going;
2339                                         }
2340 #endif
2341
2342                                         goto error_return;
2343                                 }
2344
2345                                 /* It is an authentication request. */
2346                                 conn->auth_req_received = true;
2347
2348                                 /* Get the type of request. */
2349                                 if (pqGetInt((int *) &areq, 4, conn))
2350                                 {
2351                                         /* We'll come back when there are more data */
2352                                         return PGRES_POLLING_READING;
2353                                 }
2354
2355                                 /* Get the password salt if there is one. */
2356                                 if (areq == AUTH_REQ_MD5)
2357                                 {
2358                                         if (pqGetnchar(conn->md5Salt,
2359                                                                    sizeof(conn->md5Salt), conn))
2360                                         {
2361                                                 /* We'll come back when there are more data */
2362                                                 return PGRES_POLLING_READING;
2363                                         }
2364                                 }
2365 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2366
2367                                 /*
2368                                  * Continue GSSAPI/SSPI authentication
2369                                  */
2370                                 if (areq == AUTH_REQ_GSS_CONT)
2371                                 {
2372                                         int                     llen = msgLength - 4;
2373
2374                                         /*
2375                                          * We can be called repeatedly for the same buffer. Avoid
2376                                          * re-allocating the buffer in this case - just re-use the
2377                                          * old buffer.
2378                                          */
2379                                         if (llen != conn->ginbuf.length)
2380                                         {
2381                                                 if (conn->ginbuf.value)
2382                                                         free(conn->ginbuf.value);
2383
2384                                                 conn->ginbuf.length = llen;
2385                                                 conn->ginbuf.value = malloc(llen);
2386                                                 if (!conn->ginbuf.value)
2387                                                 {
2388                                                         printfPQExpBuffer(&conn->errorMessage,
2389                                                                                           libpq_gettext("out of memory allocating GSSAPI buffer (%d)"),
2390                                                                                           llen);
2391                                                         goto error_return;
2392                                                 }
2393                                         }
2394
2395                                         if (pqGetnchar(conn->ginbuf.value, llen, conn))
2396                                         {
2397                                                 /* We'll come back when there is more data. */
2398                                                 return PGRES_POLLING_READING;
2399                                         }
2400                                 }
2401 #endif
2402
2403                                 /*
2404                                  * OK, we successfully read the message; mark data consumed
2405                                  */
2406                                 conn->inStart = conn->inCursor;
2407
2408                                 /* Respond to the request if necessary. */
2409
2410                                 /*
2411                                  * Note that conn->pghost must be non-NULL if we are going to
2412                                  * avoid the Kerberos code doing a hostname look-up.
2413                                  */
2414
2415                                 if (pg_fe_sendauth(areq, conn) != STATUS_OK)
2416                                 {
2417                                         conn->errorMessage.len = strlen(conn->errorMessage.data);
2418                                         goto error_return;
2419                                 }
2420                                 conn->errorMessage.len = strlen(conn->errorMessage.data);
2421
2422                                 /*
2423                                  * Just make sure that any data sent by pg_fe_sendauth is
2424                                  * flushed out.  Although this theoretically could block, it
2425                                  * really shouldn't since we don't send large auth responses.
2426                                  */
2427                                 if (pqFlush(conn))
2428                                         goto error_return;
2429
2430                                 if (areq == AUTH_REQ_OK)
2431                                 {
2432                                         /* We are done with authentication exchange */
2433                                         conn->status = CONNECTION_AUTH_OK;
2434
2435                                         /*
2436                                          * Set asyncStatus so that PQgetResult will think that
2437                                          * what comes back next is the result of a query.  See
2438                                          * below.
2439                                          */
2440                                         conn->asyncStatus = PGASYNC_BUSY;
2441                                 }
2442
2443                                 /* Look to see if we have more data yet. */
2444                                 goto keep_going;
2445                         }
2446
2447                 case CONNECTION_AUTH_OK:
2448                         {
2449                                 /*
2450                                  * Now we expect to hear from the backend. A ReadyForQuery
2451                                  * message indicates that startup is successful, but we might
2452                                  * also get an Error message indicating failure. (Notice
2453                                  * messages indicating nonfatal warnings are also allowed by
2454                                  * the protocol, as are ParameterStatus and BackendKeyData
2455                                  * messages.) Easiest way to handle this is to let
2456                                  * PQgetResult() read the messages. We just have to fake it
2457                                  * out about the state of the connection, by setting
2458                                  * asyncStatus = PGASYNC_BUSY (done above).
2459                                  */
2460
2461                                 if (PQisBusy(conn))
2462                                         return PGRES_POLLING_READING;
2463
2464                                 res = PQgetResult(conn);
2465
2466                                 /*
2467                                  * NULL return indicating we have gone to IDLE state is
2468                                  * expected
2469                                  */
2470                                 if (res)
2471                                 {
2472                                         if (res->resultStatus != PGRES_FATAL_ERROR)
2473                                                 appendPQExpBufferStr(&conn->errorMessage,
2474                                                                                          libpq_gettext("unexpected message from server during startup\n"));
2475                                         else if (conn->send_appname &&
2476                                                          (conn->appname || conn->fbappname))
2477                                         {
2478                                                 /*
2479                                                  * If we tried to send application_name, check to see
2480                                                  * if the error is about that --- pre-9.0 servers will
2481                                                  * reject it at this stage of the process.      If so,
2482                                                  * close the connection and retry without sending
2483                                                  * application_name.  We could possibly get a false
2484                                                  * SQLSTATE match here and retry uselessly, but there
2485                                                  * seems no great harm in that; we'll just get the
2486                                                  * same error again if it's unrelated.
2487                                                  */
2488                                                 const char *sqlstate;
2489
2490                                                 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2491                                                 if (sqlstate &&
2492                                                         strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
2493                                                 {
2494                                                         PQclear(res);
2495                                                         conn->send_appname = false;
2496                                                         /* Must drop the old connection */
2497                                                         pqDropConnection(conn);
2498                                                         conn->status = CONNECTION_NEEDED;
2499                                                         goto keep_going;
2500                                                 }
2501                                         }
2502
2503                                         /*
2504                                          * if the resultStatus is FATAL, then conn->errorMessage
2505                                          * already has a copy of the error; needn't copy it back.
2506                                          * But add a newline if it's not there already, since
2507                                          * postmaster error messages may not have one.
2508                                          */
2509                                         if (conn->errorMessage.len <= 0 ||
2510                                                 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
2511                                                 appendPQExpBufferChar(&conn->errorMessage, '\n');
2512                                         PQclear(res);
2513                                         goto error_return;
2514                                 }
2515
2516                                 /* We can release the address list now. */
2517                                 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2518                                 conn->addrlist = NULL;
2519                                 conn->addr_cur = NULL;
2520
2521                                 /* Fire up post-connection housekeeping if needed */
2522                                 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2523                                 {
2524                                         conn->status = CONNECTION_SETENV;
2525                                         conn->setenv_state = SETENV_STATE_CLIENT_ENCODING_SEND;
2526                                         conn->next_eo = EnvironmentOptions;
2527                                         return PGRES_POLLING_WRITING;
2528                                 }
2529
2530                                 /* Otherwise, we are open for business! */
2531                                 conn->status = CONNECTION_OK;
2532                                 return PGRES_POLLING_OK;
2533                         }
2534
2535                 case CONNECTION_SETENV:
2536
2537                         /*
2538                          * Do post-connection housekeeping (only needed in protocol 2.0).
2539                          *
2540                          * We pretend that the connection is OK for the duration of these
2541                          * queries.
2542                          */
2543                         conn->status = CONNECTION_OK;
2544
2545                         switch (pqSetenvPoll(conn))
2546                         {
2547                                 case PGRES_POLLING_OK:  /* Success */
2548                                         break;
2549
2550                                 case PGRES_POLLING_READING:             /* Still going */
2551                                         conn->status = CONNECTION_SETENV;
2552                                         return PGRES_POLLING_READING;
2553
2554                                 case PGRES_POLLING_WRITING:             /* Still going */
2555                                         conn->status = CONNECTION_SETENV;
2556                                         return PGRES_POLLING_WRITING;
2557
2558                                 default:
2559                                         goto error_return;
2560                         }
2561
2562                         /* We are open for business! */
2563                         conn->status = CONNECTION_OK;
2564                         return PGRES_POLLING_OK;
2565
2566                 default:
2567                         appendPQExpBuffer(&conn->errorMessage,
2568                                                           libpq_gettext("invalid connection state %d, "
2569                                                            "probably indicative of memory corruption\n"),
2570                                                           conn->status);
2571                         goto error_return;
2572         }
2573
2574         /* Unreachable */
2575
2576 error_return:
2577
2578         dot_pg_pass_warning(conn);
2579
2580         /*
2581          * We used to close the socket at this point, but that makes it awkward
2582          * for those above us if they wish to remove this socket from their own
2583          * records (an fd_set for example).  We'll just have this socket closed
2584          * when PQfinish is called (which is compulsory even after an error, since
2585          * the connection structure must be freed).
2586          */
2587         conn->status = CONNECTION_BAD;
2588         return PGRES_POLLING_FAILED;
2589 }
2590
2591
2592 /*
2593  * internal_ping
2594  *              Determine if a server is running and if we can connect to it.
2595  *
2596  * The argument is a connection that's been started, but not completed.
2597  */
2598 static PGPing
2599 internal_ping(PGconn *conn)
2600 {
2601         /* Say "no attempt" if we never got to PQconnectPoll */
2602         if (!conn || !conn->options_valid)
2603                 return PQPING_NO_ATTEMPT;
2604
2605         /* Attempt to complete the connection */
2606         if (conn->status != CONNECTION_BAD)
2607                 (void) connectDBComplete(conn);
2608
2609         /* Definitely OK if we succeeded */
2610         if (conn->status != CONNECTION_BAD)
2611                 return PQPING_OK;
2612
2613         /*
2614          * Here begins the interesting part of "ping": determine the cause of the
2615          * failure in sufficient detail to decide what to return.  We do not want
2616          * to report that the server is not up just because we didn't have a valid
2617          * password, for example.  In fact, any sort of authentication request
2618          * implies the server is up.  (We need this check since the libpq side of
2619          * things might have pulled the plug on the connection before getting an
2620          * error as such from the postmaster.)
2621          */
2622         if (conn->auth_req_received)
2623                 return PQPING_OK;
2624
2625         /*
2626          * If we failed to get any ERROR response from the postmaster, report
2627          * PQPING_NO_RESPONSE.  This result could be somewhat misleading for a
2628          * pre-7.4 server, since it won't send back a SQLSTATE, but those are long
2629          * out of support.      Another corner case where the server could return a
2630          * failure without a SQLSTATE is fork failure, but NO_RESPONSE isn't
2631          * totally unreasonable for that anyway.  We expect that every other
2632          * failure case in a modern server will produce a report with a SQLSTATE.
2633          *
2634          * NOTE: whenever we get around to making libpq generate SQLSTATEs for
2635          * client-side errors, we should either not store those into
2636          * last_sqlstate, or add an extra flag so we can tell client-side errors
2637          * apart from server-side ones.
2638          */
2639         if (strlen(conn->last_sqlstate) != 5)
2640                 return PQPING_NO_RESPONSE;
2641
2642         /*
2643          * Report PQPING_REJECT if server says it's not accepting connections. (We
2644          * distinguish this case mainly for the convenience of pg_ctl.)
2645          */
2646         if (strcmp(conn->last_sqlstate, ERRCODE_CANNOT_CONNECT_NOW) == 0)
2647                 return PQPING_REJECT;
2648
2649         /*
2650          * Any other SQLSTATE can be taken to indicate that the server is up.
2651          * Presumably it didn't like our username, password, or database name; or
2652          * perhaps it had some transient failure, but that should not be taken as
2653          * meaning "it's down".
2654          */
2655         return PQPING_OK;
2656 }
2657
2658
2659 /*
2660  * makeEmptyPGconn
2661  *       - create a PGconn data structure with (as yet) no interesting data
2662  */
2663 static PGconn *
2664 makeEmptyPGconn(void)
2665 {
2666         PGconn     *conn;
2667
2668 #ifdef WIN32
2669         /*
2670          * Make sure socket support is up and running.
2671          */
2672         WSADATA         wsaData;
2673
2674         if (WSAStartup(MAKEWORD(1, 1), &wsaData))
2675                 return NULL;
2676         WSASetLastError(0);
2677 #endif
2678
2679         conn = (PGconn *) malloc(sizeof(PGconn));
2680         if (conn == NULL)
2681         {
2682 #ifdef WIN32
2683                 WSACleanup();
2684 #endif
2685                 return conn;
2686         }
2687
2688         /* Zero all pointers and booleans */
2689         MemSet(conn, 0, sizeof(PGconn));
2690
2691         /* install default notice hooks */
2692         conn->noticeHooks.noticeRec = defaultNoticeReceiver;
2693         conn->noticeHooks.noticeProc = defaultNoticeProcessor;
2694
2695         conn->status = CONNECTION_BAD;
2696         conn->asyncStatus = PGASYNC_IDLE;
2697         conn->xactStatus = PQTRANS_IDLE;
2698         conn->options_valid = false;
2699         conn->nonblocking = false;
2700         conn->setenv_state = SETENV_STATE_IDLE;
2701         conn->client_encoding = PG_SQL_ASCII;
2702         conn->std_strings = false;      /* unless server says differently */
2703         conn->verbosity = PQERRORS_DEFAULT;
2704         conn->sock = PGINVALID_SOCKET;
2705         conn->auth_req_received = false;
2706         conn->password_needed = false;
2707         conn->dot_pgpass_used = false;
2708 #ifdef USE_SSL
2709         conn->allow_ssl_try = true;
2710         conn->wait_ssl_try = false;
2711 #endif
2712
2713         /*
2714          * We try to send at least 8K at a time, which is the usual size of pipe
2715          * buffers on Unix systems.  That way, when we are sending a large amount
2716          * of data, we avoid incurring extra kernel context swaps for partial
2717          * bufferloads.  The output buffer is initially made 16K in size, and we
2718          * try to dump it after accumulating 8K.
2719          *
2720          * With the same goal of minimizing context swaps, the input buffer will
2721          * be enlarged anytime it has less than 8K free, so we initially allocate
2722          * twice that.
2723          */
2724         conn->inBufSize = 16 * 1024;
2725         conn->inBuffer = (char *) malloc(conn->inBufSize);
2726         conn->outBufSize = 16 * 1024;
2727         conn->outBuffer = (char *) malloc(conn->outBufSize);
2728         conn->rowBufLen = 32;
2729         conn->rowBuf = (PGdataValue *) malloc(conn->rowBufLen * sizeof(PGdataValue));
2730         initPQExpBuffer(&conn->errorMessage);
2731         initPQExpBuffer(&conn->workBuffer);
2732
2733         if (conn->inBuffer == NULL ||
2734                 conn->outBuffer == NULL ||
2735                 conn->rowBuf == NULL ||
2736                 PQExpBufferBroken(&conn->errorMessage) ||
2737                 PQExpBufferBroken(&conn->workBuffer))
2738         {
2739                 /* out of memory already :-( */
2740                 freePGconn(conn);
2741                 conn = NULL;
2742         }
2743
2744         return conn;
2745 }
2746
2747 /*
2748  * freePGconn
2749  *       - free an idle (closed) PGconn data structure
2750  *
2751  * NOTE: this should not overlap any functionality with closePGconn().
2752  * Clearing/resetting of transient state belongs there; what we do here is
2753  * release data that is to be held for the life of the PGconn structure.
2754  * If a value ought to be cleared/freed during PQreset(), do it there not here.
2755  */
2756 static void
2757 freePGconn(PGconn *conn)
2758 {
2759         int                     i;
2760
2761         /* let any event procs clean up their state data */
2762         for (i = 0; i < conn->nEvents; i++)
2763         {
2764                 PGEventConnDestroy evt;
2765
2766                 evt.conn = conn;
2767                 (void) conn->events[i].proc(PGEVT_CONNDESTROY, &evt,
2768                                                                         conn->events[i].passThrough);
2769                 free(conn->events[i].name);
2770         }
2771
2772         if (conn->client_encoding_initial)
2773                 free(conn->client_encoding_initial);
2774         if (conn->events)
2775                 free(conn->events);
2776         if (conn->pghost)
2777                 free(conn->pghost);
2778         if (conn->pghostaddr)
2779                 free(conn->pghostaddr);
2780         if (conn->pgport)
2781                 free(conn->pgport);
2782         if (conn->pgunixsocket)
2783                 free(conn->pgunixsocket);
2784         if (conn->pgtty)
2785                 free(conn->pgtty);
2786         if (conn->connect_timeout)
2787                 free(conn->connect_timeout);
2788         if (conn->pgoptions)
2789                 free(conn->pgoptions);
2790         if (conn->appname)
2791                 free(conn->appname);
2792         if (conn->fbappname)
2793                 free(conn->fbappname);
2794         if (conn->dbName)
2795                 free(conn->dbName);
2796         if (conn->replication)
2797                 free(conn->replication);
2798         if (conn->pguser)
2799                 free(conn->pguser);
2800         if (conn->pgpass)
2801                 free(conn->pgpass);
2802         if (conn->keepalives)
2803                 free(conn->keepalives);
2804         if (conn->keepalives_idle)
2805                 free(conn->keepalives_idle);
2806         if (conn->keepalives_interval)
2807                 free(conn->keepalives_interval);
2808         if (conn->keepalives_count)
2809                 free(conn->keepalives_count);
2810         if (conn->sslmode)
2811                 free(conn->sslmode);
2812         if (conn->sslcert)
2813                 free(conn->sslcert);
2814         if (conn->sslkey)
2815                 free(conn->sslkey);
2816         if (conn->sslrootcert)
2817                 free(conn->sslrootcert);
2818         if (conn->sslcrl)
2819                 free(conn->sslcrl);
2820         if (conn->sslcompression)
2821                 free(conn->sslcompression);
2822         if (conn->requirepeer)
2823                 free(conn->requirepeer);
2824 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2825         if (conn->krbsrvname)
2826                 free(conn->krbsrvname);
2827 #endif
2828 #if defined(ENABLE_GSS) && defined(ENABLE_SSPI)
2829         if (conn->gsslib)
2830                 free(conn->gsslib);
2831 #endif
2832         /* Note that conn->Pfdebug is not ours to close or free */
2833         if (conn->last_query)
2834                 free(conn->last_query);
2835         if (conn->inBuffer)
2836                 free(conn->inBuffer);
2837         if (conn->outBuffer)
2838                 free(conn->outBuffer);
2839         if (conn->rowBuf)
2840                 free(conn->rowBuf);
2841         termPQExpBuffer(&conn->errorMessage);
2842         termPQExpBuffer(&conn->workBuffer);
2843
2844         free(conn);
2845
2846 #ifdef WIN32
2847         WSACleanup();
2848 #endif
2849 }
2850
2851 /*
2852  * closePGconn
2853  *       - properly close a connection to the backend
2854  *
2855  * This should reset or release all transient state, but NOT the connection
2856  * parameters.  On exit, the PGconn should be in condition to start a fresh
2857  * connection with the same parameters (see PQreset()).
2858  */
2859 static void
2860 closePGconn(PGconn *conn)
2861 {
2862         PGnotify   *notify;
2863         pgParameterStatus *pstatus;
2864
2865         /*
2866          * Note that the protocol doesn't allow us to send Terminate messages
2867          * during the startup phase.
2868          */
2869         if (conn->sock != PGINVALID_SOCKET && conn->status == CONNECTION_OK)
2870         {
2871                 /*
2872                  * Try to send "close connection" message to backend. Ignore any
2873                  * error.
2874                  */
2875                 pqPutMsgStart('X', false, conn);
2876                 pqPutMsgEnd(conn);
2877                 (void) pqFlush(conn);
2878         }
2879
2880         /*
2881          * Must reset the blocking status so a possible reconnect will work.
2882          *
2883          * Don't call PQsetnonblocking() because it will fail if it's unable to
2884          * flush the connection.
2885          */
2886         conn->nonblocking = FALSE;
2887
2888         /*
2889          * Close the connection, reset all transient state, flush I/O buffers.
2890          */
2891         pqDropConnection(conn);
2892         conn->status = CONNECTION_BAD;          /* Well, not really _bad_ - just
2893                                                                                  * absent */
2894         conn->asyncStatus = PGASYNC_IDLE;
2895         pqClearAsyncResult(conn);       /* deallocate result */
2896         pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2897         conn->addrlist = NULL;
2898         conn->addr_cur = NULL;
2899         notify = conn->notifyHead;
2900         while (notify != NULL)
2901         {
2902                 PGnotify   *prev = notify;
2903
2904                 notify = notify->next;
2905                 free(prev);
2906         }
2907         conn->notifyHead = conn->notifyTail = NULL;
2908         pstatus = conn->pstatus;
2909         while (pstatus != NULL)
2910         {
2911                 pgParameterStatus *prev = pstatus;
2912
2913                 pstatus = pstatus->next;
2914                 free(prev);
2915         }
2916         conn->pstatus = NULL;
2917         if (conn->lobjfuncs)
2918                 free(conn->lobjfuncs);
2919         conn->lobjfuncs = NULL;
2920 #ifdef ENABLE_GSS
2921         {
2922                 OM_uint32       min_s;
2923
2924                 if (conn->gctx)
2925                         gss_delete_sec_context(&min_s, &conn->gctx, GSS_C_NO_BUFFER);
2926                 if (conn->gtarg_nam)
2927                         gss_release_name(&min_s, &conn->gtarg_nam);
2928                 if (conn->ginbuf.length)
2929                         gss_release_buffer(&min_s, &conn->ginbuf);
2930                 if (conn->goutbuf.length)
2931                         gss_release_buffer(&min_s, &conn->goutbuf);
2932         }
2933 #endif
2934 #ifdef ENABLE_SSPI
2935         if (conn->ginbuf.length)
2936                 free(conn->ginbuf.value);
2937         conn->ginbuf.length = 0;
2938         conn->ginbuf.value = NULL;
2939         if (conn->sspitarget)
2940                 free(conn->sspitarget);
2941         conn->sspitarget = NULL;
2942         if (conn->sspicred)
2943         {
2944                 FreeCredentialsHandle(conn->sspicred);
2945                 free(conn->sspicred);
2946                 conn->sspicred = NULL;
2947         }
2948         if (conn->sspictx)
2949         {
2950                 DeleteSecurityContext(conn->sspictx);
2951                 free(conn->sspictx);
2952                 conn->sspictx = NULL;
2953         }
2954 #endif
2955 }
2956
2957 /*
2958  * PQfinish: properly close a connection to the backend. Also frees
2959  * the PGconn data structure so it shouldn't be re-used after this.
2960  */
2961 void
2962 PQfinish(PGconn *conn)
2963 {
2964         if (conn)
2965         {
2966                 closePGconn(conn);
2967                 freePGconn(conn);
2968         }
2969 }
2970
2971 /*
2972  * PQreset: resets the connection to the backend by closing the
2973  * existing connection and creating a new one.
2974  */
2975 void
2976 PQreset(PGconn *conn)
2977 {
2978         if (conn)
2979         {
2980                 closePGconn(conn);
2981
2982                 if (connectDBStart(conn) && connectDBComplete(conn))
2983                 {
2984                         /*
2985                          * Notify event procs of successful reset.      We treat an event proc
2986                          * failure as disabling the connection ... good idea?
2987                          */
2988                         int                     i;
2989
2990                         for (i = 0; i < conn->nEvents; i++)
2991                         {
2992                                 PGEventConnReset evt;
2993
2994                                 evt.conn = conn;
2995                                 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
2996                                                                                   conn->events[i].passThrough))
2997                                 {
2998                                         conn->status = CONNECTION_BAD;
2999                                         printfPQExpBuffer(&conn->errorMessage,
3000                                                                           libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
3001                                                                           conn->events[i].name);
3002                                         break;
3003                                 }
3004                         }
3005                 }
3006         }
3007 }
3008
3009
3010 /*
3011  * PQresetStart:
3012  * resets the connection to the backend
3013  * closes the existing connection and makes a new one
3014  * Returns 1 on success, 0 on failure.
3015  */
3016 int
3017 PQresetStart(PGconn *conn)
3018 {
3019         if (conn)
3020         {
3021                 closePGconn(conn);
3022
3023                 return connectDBStart(conn);
3024         }
3025
3026         return 0;
3027 }
3028
3029
3030 /*
3031  * PQresetPoll:
3032  * resets the connection to the backend
3033  * closes the existing connection and makes a new one
3034  */
3035 PostgresPollingStatusType
3036 PQresetPoll(PGconn *conn)
3037 {
3038         if (conn)
3039         {
3040                 PostgresPollingStatusType status = PQconnectPoll(conn);
3041
3042                 if (status == PGRES_POLLING_OK)
3043                 {
3044                         /*
3045                          * Notify event procs of successful reset.      We treat an event proc
3046                          * failure as disabling the connection ... good idea?
3047                          */
3048                         int                     i;
3049
3050                         for (i = 0; i < conn->nEvents; i++)
3051                         {
3052                                 PGEventConnReset evt;
3053
3054                                 evt.conn = conn;
3055                                 if (!conn->events[i].proc(PGEVT_CONNRESET, &evt,
3056                                                                                   conn->events[i].passThrough))
3057                                 {
3058                                         conn->status = CONNECTION_BAD;
3059                                         printfPQExpBuffer(&conn->errorMessage,
3060                                                                           libpq_gettext("PGEventProc \"%s\" failed during PGEVT_CONNRESET event\n"),
3061                                                                           conn->events[i].name);
3062                                         return PGRES_POLLING_FAILED;
3063                                 }
3064                         }
3065                 }
3066
3067                 return status;
3068         }
3069
3070         return PGRES_POLLING_FAILED;
3071 }
3072
3073 /*
3074  * PQcancelGet: get a PGcancel structure corresponding to a connection.
3075  *
3076  * A copy is needed to be able to cancel a running query from a different
3077  * thread. If the same structure is used all structure members would have
3078  * to be individually locked (if the entire structure was locked, it would
3079  * be impossible to cancel a synchronous query because the structure would
3080  * have to stay locked for the duration of the query).
3081  */
3082 PGcancel *
3083 PQgetCancel(PGconn *conn)
3084 {
3085         PGcancel   *cancel;
3086
3087         if (!conn)
3088                 return NULL;
3089
3090         if (conn->sock == PGINVALID_SOCKET)
3091                 return NULL;
3092
3093         cancel = malloc(sizeof(PGcancel));
3094         if (cancel == NULL)
3095                 return NULL;
3096
3097         memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr));
3098         cancel->be_pid = conn->be_pid;
3099         cancel->be_key = conn->be_key;
3100
3101         return cancel;
3102 }
3103
3104 /* PQfreeCancel: free a cancel structure */
3105 void
3106 PQfreeCancel(PGcancel *cancel)
3107 {
3108         if (cancel)
3109                 free(cancel);
3110 }
3111
3112
3113 /*
3114  * PQcancel and PQrequestCancel: attempt to request cancellation of the
3115  * current operation.
3116  *
3117  * The return value is TRUE if the cancel request was successfully
3118  * dispatched, FALSE if not (in which case an error message is available).
3119  * Note: successful dispatch is no guarantee that there will be any effect at
3120  * the backend.  The application must read the operation result as usual.
3121  *
3122  * CAUTION: we want this routine to be safely callable from a signal handler
3123  * (for example, an application might want to call it in a SIGINT handler).
3124  * This means we cannot use any C library routine that might be non-reentrant.
3125  * malloc/free are often non-reentrant, and anything that might call them is
3126  * just as dangerous.  We avoid sprintf here for that reason.  Building up
3127  * error messages with strcpy/strcat is tedious but should be quite safe.
3128  * We also save/restore errno in case the signal handler support doesn't.
3129  *
3130  * internal_cancel() is an internal helper function to make code-sharing
3131  * between the two versions of the cancel function possible.
3132  */
3133 static int
3134 internal_cancel(SockAddr *raddr, int be_pid, int be_key,
3135                                 char *errbuf, int errbufsize)
3136 {
3137         int                     save_errno = SOCK_ERRNO;
3138         pgsocket        tmpsock = PGINVALID_SOCKET;
3139         char            sebuf[256];
3140         int                     maxlen;
3141         struct
3142         {
3143                 uint32          packetlen;
3144                 CancelRequestPacket cp;
3145         }                       crp;
3146
3147         /*
3148          * We need to open a temporary connection to the postmaster. Do this with
3149          * only kernel calls.
3150          */
3151         if ((tmpsock = socket(raddr->addr.ss_family, SOCK_STREAM, 0)) == PGINVALID_SOCKET)
3152         {
3153                 strlcpy(errbuf, "PQcancel() -- socket() failed: ", errbufsize);
3154                 goto cancel_errReturn;
3155         }
3156 retry3:
3157         if (connect(tmpsock, (struct sockaddr *) & raddr->addr,
3158                                 raddr->salen) < 0)
3159         {
3160                 if (SOCK_ERRNO == EINTR)
3161                         /* Interrupted system call - we'll just try again */
3162                         goto retry3;
3163                 strlcpy(errbuf, "PQcancel() -- connect() failed: ", errbufsize);
3164                 goto cancel_errReturn;
3165         }
3166
3167         /*
3168          * We needn't set nonblocking I/O or NODELAY options here.
3169          */
3170
3171         /* Create and send the cancel request packet. */
3172
3173         crp.packetlen = htonl((uint32) sizeof(crp));
3174         crp.cp.cancelRequestCode = (MsgType) htonl(CANCEL_REQUEST_CODE);
3175         crp.cp.backendPID = htonl(be_pid);
3176         crp.cp.cancelAuthCode = htonl(be_key);
3177
3178 retry4:
3179         if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp))
3180         {
3181                 if (SOCK_ERRNO == EINTR)
3182                         /* Interrupted system call - we'll just try again */
3183                         goto retry4;
3184                 strlcpy(errbuf, "PQcancel() -- send() failed: ", errbufsize);
3185                 goto cancel_errReturn;
3186         }
3187
3188         /*
3189          * Wait for the postmaster to close the connection, which indicates that
3190          * it's processed the request.  Without this delay, we might issue another
3191          * command only to find that our cancel zaps that command instead of the
3192          * one we thought we were canceling.  Note we don't actually expect this
3193          * read to obtain any data, we are just waiting for EOF to be signaled.
3194          */
3195 retry5:
3196         if (recv(tmpsock, (char *) &crp, 1, 0) < 0)
3197         {
3198                 if (SOCK_ERRNO == EINTR)
3199                         /* Interrupted system call - we'll just try again */
3200                         goto retry5;
3201                 /* we ignore other error conditions */
3202         }
3203
3204         /* All done */
3205         closesocket(tmpsock);
3206         SOCK_ERRNO_SET(save_errno);
3207         return TRUE;
3208
3209 cancel_errReturn:
3210
3211         /*
3212          * Make sure we don't overflow the error buffer. Leave space for the \n at
3213          * the end, and for the terminating zero.
3214          */
3215         maxlen = errbufsize - strlen(errbuf) - 2;
3216         if (maxlen >= 0)
3217         {
3218                 strncat(errbuf, SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)),
3219                                 maxlen);
3220                 strcat(errbuf, "\n");
3221         }
3222         if (tmpsock != PGINVALID_SOCKET)
3223                 closesocket(tmpsock);
3224         SOCK_ERRNO_SET(save_errno);
3225         return FALSE;
3226 }
3227
3228 /*
3229  * PQcancel: request query cancel
3230  *
3231  * Returns TRUE if able to send the cancel request, FALSE if not.
3232  *
3233  * On failure, an error message is stored in *errbuf, which must be of size
3234  * errbufsize (recommended size is 256 bytes).  *errbuf is not changed on
3235  * success return.
3236  */
3237 int
3238 PQcancel(PGcancel *cancel, char *errbuf, int errbufsize)
3239 {
3240         if (!cancel)
3241         {
3242                 strlcpy(errbuf, "PQcancel() -- no cancel object supplied", errbufsize);
3243                 return FALSE;
3244         }
3245
3246         return internal_cancel(&cancel->raddr, cancel->be_pid, cancel->be_key,
3247                                                    errbuf, errbufsize);
3248 }
3249
3250 /*
3251  * PQrequestCancel: old, not thread-safe function for requesting query cancel
3252  *
3253  * Returns TRUE if able to send the cancel request, FALSE if not.
3254  *
3255  * On failure, the error message is saved in conn->errorMessage; this means
3256  * that this can't be used when there might be other active operations on
3257  * the connection object.
3258  *
3259  * NOTE: error messages will be cut off at the current size of the
3260  * error message buffer, since we dare not try to expand conn->errorMessage!
3261  */
3262 int
3263 PQrequestCancel(PGconn *conn)
3264 {
3265         int                     r;
3266
3267         /* Check we have an open connection */
3268         if (!conn)
3269                 return FALSE;
3270
3271         if (conn->sock == PGINVALID_SOCKET)
3272         {
3273                 strlcpy(conn->errorMessage.data,
3274                                 "PQrequestCancel() -- connection is not open\n",
3275                                 conn->errorMessage.maxlen);
3276                 conn->errorMessage.len = strlen(conn->errorMessage.data);
3277
3278                 return FALSE;
3279         }
3280
3281         r = internal_cancel(&conn->raddr, conn->be_pid, conn->be_key,
3282                                                 conn->errorMessage.data, conn->errorMessage.maxlen);
3283
3284         if (!r)
3285                 conn->errorMessage.len = strlen(conn->errorMessage.data);
3286
3287         return r;
3288 }
3289
3290
3291 /*
3292  * pqPacketSend() -- convenience routine to send a message to server.
3293  *
3294  * pack_type: the single-byte message type code.  (Pass zero for startup
3295  * packets, which have no message type code.)
3296  *
3297  * buf, buf_len: contents of message.  The given length includes only what
3298  * is in buf; the message type and message length fields are added here.
3299  *
3300  * RETURNS: STATUS_ERROR if the write fails, STATUS_OK otherwise.
3301  * SIDE_EFFECTS: may block.
3302  *
3303  * Note: all messages sent with this routine have a length word, whether
3304  * it's protocol 2.0 or 3.0.
3305  */
3306 int
3307 pqPacketSend(PGconn *conn, char pack_type,
3308                          const void *buf, size_t buf_len)
3309 {
3310         /* Start the message. */
3311         if (pqPutMsgStart(pack_type, true, conn))
3312                 return STATUS_ERROR;
3313
3314         /* Send the message body. */
3315         if (pqPutnchar(buf, buf_len, conn))
3316                 return STATUS_ERROR;
3317
3318         /* Finish the message. */
3319         if (pqPutMsgEnd(conn))
3320                 return STATUS_ERROR;
3321
3322         /* Flush to ensure backend gets it. */
3323         if (pqFlush(conn))
3324                 return STATUS_ERROR;
3325
3326         return STATUS_OK;
3327 }
3328
3329 #ifdef USE_LDAP
3330
3331 #define LDAP_URL        "ldap://"
3332 #define LDAP_DEF_PORT   389
3333 #define PGLDAP_TIMEOUT 2
3334
3335 #define ld_is_sp_tab(x) ((x) == ' ' || (x) == '\t')
3336 #define ld_is_nl_cr(x) ((x) == '\r' || (x) == '\n')
3337
3338
3339 /*
3340  *              ldapServiceLookup
3341  *
3342  * Search the LDAP URL passed as first argument, treat the result as a
3343  * string of connection options that are parsed and added to the array of
3344  * options passed as second argument.
3345  *
3346  * LDAP URLs must conform to RFC 1959 without escape sequences.
3347  *      ldap://host:port/dn?attributes?scope?filter?extensions
3348  *
3349  * Returns
3350  *      0 if the lookup was successful,
3351  *      1 if the connection to the LDAP server could be established but
3352  *        the search was unsuccessful,
3353  *      2 if a connection could not be established, and
3354  *      3 if a fatal error occurred.
3355  *
3356  * An error message is returned in the third argument for return codes 1 and 3.
3357  */
3358 static int
3359 ldapServiceLookup(const char *purl, PQconninfoOption *options,
3360                                   PQExpBuffer errorMessage)
3361 {
3362         int                     port = LDAP_DEF_PORT,
3363                                 scope,
3364                                 rc,
3365                                 size,
3366                                 state,
3367                                 oldstate,
3368                                 i;
3369 #ifndef WIN32
3370         int                     msgid;
3371 #endif
3372         bool            found_keyword;
3373         char       *url,
3374                            *hostname,
3375                            *portstr,
3376                            *endptr,
3377                            *dn,
3378                            *scopestr,
3379                            *filter,
3380                            *result,
3381                            *p,
3382                            *p1 = NULL,
3383                            *optname = NULL,
3384                            *optval = NULL;
3385         char       *attrs[2] = {NULL, NULL};
3386         LDAP       *ld = NULL;
3387         LDAPMessage *res,
3388                            *entry;
3389         struct berval **values;
3390         LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
3391
3392         if ((url = strdup(purl)) == NULL)
3393         {
3394                 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
3395                 return 3;
3396         }
3397
3398         /*
3399          * Parse URL components, check for correctness.  Basically, url has '\0'
3400          * placed at component boundaries and variables are pointed at each
3401          * component.
3402          */
3403
3404         if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
3405         {
3406                 printfPQExpBuffer(errorMessage,
3407                                                   libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
3408                 free(url);
3409                 return 3;
3410         }
3411
3412         /* hostname */
3413         hostname = url + strlen(LDAP_URL);
3414         if (*hostname == '/')           /* no hostname? */
3415                 hostname = DefaultHost; /* the default */
3416
3417         /* dn, "distinguished name" */
3418         p = strchr(url + strlen(LDAP_URL), '/');
3419         if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3420         {
3421                 printfPQExpBuffer(errorMessage, libpq_gettext(
3422                          "invalid LDAP URL \"%s\": missing distinguished name\n"), purl);
3423                 free(url);
3424                 return 3;
3425         }
3426         *p = '\0';                                      /* terminate hostname */
3427         dn = p + 1;
3428
3429         /* attribute */
3430         if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3431         {
3432                 printfPQExpBuffer(errorMessage, libpq_gettext(
3433                 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
3434                 free(url);
3435                 return 3;
3436         }
3437         *p = '\0';
3438         attrs[0] = p + 1;
3439
3440         /* scope */
3441         if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3442         {
3443                 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
3444                 free(url);
3445                 return 3;
3446         }
3447         *p = '\0';
3448         scopestr = p + 1;
3449
3450         /* filter */
3451         if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3452         {
3453                 printfPQExpBuffer(errorMessage,
3454                                 libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
3455                 free(url);
3456                 return 3;
3457         }
3458         *p = '\0';
3459         filter = p + 1;
3460         if ((p = strchr(filter, '?')) != NULL)
3461                 *p = '\0';
3462
3463         /* port number? */
3464         if ((p1 = strchr(hostname, ':')) != NULL)
3465         {
3466                 long            lport;
3467
3468                 *p1 = '\0';
3469                 portstr = p1 + 1;
3470                 errno = 0;
3471                 lport = strtol(portstr, &endptr, 10);
3472                 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
3473                 {
3474                         printfPQExpBuffer(errorMessage, libpq_gettext(
3475                                         "invalid LDAP URL \"%s\": invalid port number\n"), purl);
3476                         free(url);
3477                         return 3;
3478                 }
3479                 port = (int) lport;
3480         }
3481
3482         /* Allow only one attribute */
3483         if (strchr(attrs[0], ',') != NULL)
3484         {
3485                 printfPQExpBuffer(errorMessage, libpq_gettext(
3486                 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
3487                 free(url);
3488                 return 3;
3489         }
3490
3491         /* set scope */
3492         if (pg_strcasecmp(scopestr, "base") == 0)
3493                 scope = LDAP_SCOPE_BASE;
3494         else if (pg_strcasecmp(scopestr, "one") == 0)
3495                 scope = LDAP_SCOPE_ONELEVEL;
3496         else if (pg_strcasecmp(scopestr, "sub") == 0)
3497                 scope = LDAP_SCOPE_SUBTREE;
3498         else
3499         {
3500                 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
3501                 free(url);
3502                 return 3;
3503         }
3504
3505         /* initialize LDAP structure */
3506         if ((ld = ldap_init(hostname, port)) == NULL)
3507         {
3508                 printfPQExpBuffer(errorMessage,
3509                                                   libpq_gettext("could not create LDAP structure\n"));
3510                 free(url);
3511                 return 3;
3512         }
3513
3514         /*
3515          * Perform an explicit anonymous bind.
3516          *
3517          * LDAP does not require that an anonymous bind is performed explicitly,
3518          * but we want to distinguish between the case where LDAP bind does not
3519          * succeed within PGLDAP_TIMEOUT seconds (return 2 to continue parsing
3520          * the service control file) and the case where querying the LDAP server
3521          * fails (return 1 to end parsing).
3522          *
3523          * Unfortunately there is no way of setting a timeout that works for
3524          * both Windows and OpenLDAP.
3525          */
3526 #ifdef WIN32
3527         /* the nonstandard ldap_connect function performs an anonymous bind */
3528         if (ldap_connect(ld, &time) != LDAP_SUCCESS)
3529         {
3530                 /* error or timeout in ldap_connect */
3531                 free(url);
3532                 ldap_unbind(ld);
3533                 return 2;
3534         }
3535 #else /* !WIN32 */
3536         /* in OpenLDAP, use the LDAP_OPT_NETWORK_TIMEOUT option */
3537         if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
3538         {
3539                 free(url);
3540                 ldap_unbind(ld);
3541                 return 3;
3542         }
3543
3544         /* anonymous bind */
3545         if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
3546         {
3547                 /* error or network timeout */
3548                 free(url);
3549                 ldap_unbind(ld);
3550                 return 2;
3551         }
3552
3553         /* wait some time for the connection to succeed */
3554         res = NULL;
3555         if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
3556                 res == NULL)
3557         {
3558                 /* error or timeout */
3559                 if (res != NULL)
3560                         ldap_msgfree(res);
3561                 free(url);
3562                 ldap_unbind(ld);
3563                 return 2;
3564         }
3565         ldap_msgfree(res);
3566
3567         /* reset timeout */
3568         time.tv_sec = -1;
3569         if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, &time) != LDAP_SUCCESS)
3570         {
3571                 free(url);
3572                 ldap_unbind(ld);
3573                 return 3;
3574         }
3575 #endif /* WIN32 */
3576
3577         /* search */
3578         res = NULL;
3579         if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
3580                 != LDAP_SUCCESS)
3581         {
3582                 if (res != NULL)
3583                         ldap_msgfree(res);
3584                 printfPQExpBuffer(errorMessage,
3585                                                   libpq_gettext("lookup on LDAP server failed: %s\n"),
3586                                                   ldap_err2string(rc));
3587                 ldap_unbind(ld);
3588                 free(url);
3589                 return 1;
3590         }
3591
3592         /* complain if there was not exactly one result */
3593         if ((rc = ldap_count_entries(ld, res)) != 1)
3594         {
3595                 printfPQExpBuffer(errorMessage,
3596                          rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
3597                                                   : libpq_gettext("no entry found on LDAP lookup\n"));
3598                 ldap_msgfree(res);
3599                 ldap_unbind(ld);
3600                 free(url);
3601                 return 1;
3602         }
3603
3604         /* get entry */
3605         if ((entry = ldap_first_entry(ld, res)) == NULL)
3606         {
3607                 /* should never happen */
3608                 printfPQExpBuffer(errorMessage,
3609                                                   libpq_gettext("no entry found on LDAP lookup\n"));
3610                 ldap_msgfree(res);
3611                 ldap_unbind(ld);
3612                 free(url);
3613                 return 1;
3614         }
3615
3616         /* get values */
3617         if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
3618         {
3619                 printfPQExpBuffer(errorMessage,
3620                                   libpq_gettext("attribute has no values on LDAP lookup\n"));
3621                 ldap_msgfree(res);
3622                 ldap_unbind(ld);
3623                 free(url);
3624                 return 1;
3625         }
3626
3627         ldap_msgfree(res);
3628         free(url);
3629
3630         if (values[0] == NULL)
3631         {
3632                 printfPQExpBuffer(errorMessage,
3633                                   libpq_gettext("attribute has no values on LDAP lookup\n"));
3634                 ldap_value_free_len(values);
3635                 ldap_unbind(ld);
3636                 return 1;
3637         }
3638
3639         /* concatenate values into a single string with newline terminators */
3640         size = 1;                                       /* for the trailing null */
3641         for (i = 0; values[i] != NULL; i++)
3642                 size += values[i]->bv_len + 1;
3643         if ((result = malloc(size)) == NULL)
3644         {
3645                 printfPQExpBuffer(errorMessage,
3646                                                   libpq_gettext("out of memory\n"));
3647                 ldap_value_free_len(values);
3648                 ldap_unbind(ld);
3649                 return 3;
3650         }
3651         p = result;
3652         for (i = 0; values[i] != NULL; i++)
3653         {
3654                 memcpy(p, values[i]->bv_val, values[i]->bv_len);
3655                 p += values[i]->bv_len;
3656                 *(p++) = '\n';
3657         }
3658         *p = '\0';
3659
3660         ldap_value_free_len(values);
3661         ldap_unbind(ld);
3662
3663         /* parse result string */
3664         oldstate = state = 0;
3665         for (p = result; *p != '\0'; ++p)
3666         {
3667                 switch (state)
3668                 {
3669                         case 0:                         /* between entries */
3670                                 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
3671                                 {
3672                                         optname = p;
3673                                         state = 1;
3674                                 }
3675                                 break;
3676                         case 1:                         /* in option name */
3677                                 if (ld_is_sp_tab(*p))
3678                                 {
3679                                         *p = '\0';
3680                                         state = 2;
3681                                 }
3682                                 else if (ld_is_nl_cr(*p))
3683                                 {
3684                                         printfPQExpBuffer(errorMessage, libpq_gettext(
3685                                         "missing \"=\" after \"%s\" in connection info string\n"),
3686                                                                           optname);
3687                                         free(result);
3688                                         return 3;
3689                                 }
3690                                 else if (*p == '=')
3691                                 {
3692                                         *p = '\0';
3693                                         state = 3;
3694                                 }
3695                                 break;
3696                         case 2:                         /* after option name */
3697                                 if (*p == '=')
3698                                 {
3699                                         state = 3;
3700                                 }
3701                                 else if (!ld_is_sp_tab(*p))
3702                                 {
3703                                         printfPQExpBuffer(errorMessage, libpq_gettext(
3704                                         "missing \"=\" after \"%s\" in connection info string\n"),
3705                                                                           optname);
3706                                         free(result);
3707                                         return 3;
3708                                 }
3709                                 break;
3710                         case 3:                         /* before option value */
3711                                 if (*p == '\'')
3712                                 {
3713                                         optval = p + 1;
3714                                         p1 = p + 1;
3715                                         state = 5;
3716                                 }
3717                                 else if (ld_is_nl_cr(*p))
3718                                 {
3719                                         optval = optname + strlen(optname); /* empty */
3720                                         state = 0;
3721                                 }
3722                                 else if (!ld_is_sp_tab(*p))
3723                                 {
3724                                         optval = p;
3725                                         state = 4;
3726                                 }
3727                                 break;
3728                         case 4:                         /* in unquoted option value */
3729                                 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
3730                                 {
3731                                         *p = '\0';
3732                                         state = 0;
3733                                 }
3734                                 break;
3735                         case 5:                         /* in quoted option value */
3736                                 if (*p == '\'')
3737                                 {
3738                                         *p1 = '\0';
3739                                         state = 0;
3740                                 }
3741                                 else if (*p == '\\')
3742                                         state = 6;
3743                                 else
3744                                         *(p1++) = *p;
3745                                 break;
3746                         case 6:                         /* in quoted option value after escape */
3747                                 *(p1++) = *p;
3748                                 state = 5;
3749                                 break;
3750                 }
3751
3752                 if (state == 0 && oldstate != 0)
3753                 {
3754                         found_keyword = false;
3755                         for (i = 0; options[i].keyword; i++)
3756                         {
3757                                 if (strcmp(options[i].keyword, optname) == 0)
3758                                 {
3759                                         if (options[i].val == NULL)
3760                                                 options[i].val = strdup(optval);
3761                                         found_keyword = true;
3762                                         break;
3763                                 }
3764                         }
3765                         if (!found_keyword)
3766                         {
3767                                 printfPQExpBuffer(errorMessage,
3768                                                  libpq_gettext("invalid connection option \"%s\"\n"),
3769                                                                   optname);
3770                                 free(result);
3771                                 return 1;
3772                         }
3773                         optname = NULL;
3774                         optval = NULL;
3775                 }
3776                 oldstate = state;
3777         }
3778
3779         free(result);
3780
3781         if (state == 5 || state == 6)
3782         {
3783                 printfPQExpBuffer(errorMessage, libpq_gettext(
3784                                   "unterminated quoted string in connection info string\n"));
3785                 return 3;
3786         }
3787
3788         return 0;
3789 }
3790
3791 #endif  /* USE_LDAP */
3792
3793 #define MAXBUFSIZE 256
3794
3795 static int
3796 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
3797 {
3798         const char *service = conninfo_getval(options, "service");
3799         char            serviceFile[MAXPGPATH];
3800         char       *env;
3801         bool            group_found = false;
3802         int                     status;
3803         struct stat stat_buf;
3804
3805         /*
3806          * We have to special-case the environment variable PGSERVICE here, since
3807          * this is and should be called before inserting environment defaults for
3808          * other connection options.
3809          */
3810         if (service == NULL)
3811                 service = getenv("PGSERVICE");
3812
3813         if (service == NULL)
3814                 return 0;
3815
3816         if ((env = getenv("PGSERVICEFILE")) != NULL)
3817                 strlcpy(serviceFile, env, sizeof(serviceFile));
3818         else
3819         {
3820                 char            homedir[MAXPGPATH];
3821
3822                 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
3823                 {
3824                         printfPQExpBuffer(errorMessage, libpq_gettext("could not get home directory to locate service definition file"));
3825                         return 1;
3826                 }
3827                 snprintf(serviceFile, MAXPGPATH, "%s/%s", homedir, ".pg_service.conf");
3828                 errno = 0;
3829                 if (stat(serviceFile, &stat_buf) != 0 && errno == ENOENT)
3830                         goto next_file;
3831         }
3832
3833         status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
3834         if (group_found || status != 0)
3835                 return status;
3836
3837 next_file:
3838
3839         /*
3840          * This could be used by any application so we can't use the binary
3841          * location to find our config files.
3842          */
3843         snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
3844                          getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
3845         errno = 0;
3846         if (stat(serviceFile, &stat_buf) != 0 && errno == ENOENT)
3847                 goto last_file;
3848
3849         status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
3850         if (status != 0)
3851                 return status;
3852
3853 last_file:
3854         if (!group_found)
3855         {
3856                 printfPQExpBuffer(errorMessage,
3857                  libpq_gettext("definition of service \"%s\" not found\n"), service);
3858                 return 3;
3859         }
3860
3861         return 0;
3862 }
3863
3864 static int
3865 parseServiceFile(const char *serviceFile,
3866                                  const char *service,
3867                                  PQconninfoOption *options,
3868                                  PQExpBuffer errorMessage,
3869                                  bool *group_found)
3870 {
3871         int                     linenr = 0,
3872                                 i;
3873         FILE       *f;
3874         char            buf[MAXBUFSIZE],
3875                            *line;
3876
3877         f = fopen(serviceFile, "r");
3878         if (f == NULL)
3879         {
3880                 printfPQExpBuffer(errorMessage, libpq_gettext("service file \"%s\" not found\n"),
3881                                                   serviceFile);
3882                 return 1;
3883         }
3884
3885         while ((line = fgets(buf, sizeof(buf), f)) != NULL)
3886         {
3887                 linenr++;
3888
3889                 if (strlen(line) >= sizeof(buf) - 1)
3890                 {
3891                         fclose(f);
3892                         printfPQExpBuffer(errorMessage,
3893                                   libpq_gettext("line %d too long in service file \"%s\"\n"),
3894                                                           linenr,
3895                                                           serviceFile);
3896                         return 2;
3897                 }
3898
3899                 /* ignore EOL at end of line */
3900                 if (strlen(line) && line[strlen(line) - 1] == '\n')
3901                         line[strlen(line) - 1] = 0;
3902
3903                 /* ignore leading blanks */
3904                 while (*line && isspace((unsigned char) line[0]))
3905                         line++;
3906
3907                 /* ignore comments and empty lines */
3908                 if (strlen(line) == 0 || line[0] == '#')
3909                         continue;
3910
3911                 /* Check for right groupname */
3912                 if (line[0] == '[')
3913                 {
3914                         if (*group_found)
3915                         {
3916                                 /* group info already read */
3917                                 fclose(f);
3918                                 return 0;
3919                         }
3920
3921                         if (strncmp(line + 1, service, strlen(service)) == 0 &&
3922                                 line[strlen(service) + 1] == ']')
3923                                 *group_found = true;
3924                         else
3925                                 *group_found = false;
3926                 }
3927                 else
3928                 {
3929                         if (*group_found)
3930                         {
3931                                 /*
3932                                  * Finally, we are in the right group and can parse the line
3933                                  */
3934                                 char       *key,
3935                                                    *val;
3936                                 bool            found_keyword;
3937
3938 #ifdef USE_LDAP
3939                                 if (strncmp(line, "ldap", 4) == 0)
3940                                 {
3941                                         int                     rc = ldapServiceLookup(line, options, errorMessage);
3942
3943                                         /* if rc = 2, go on reading for fallback */
3944                                         switch (rc)
3945                                         {
3946                                                 case 0:
3947                                                         fclose(f);
3948                                                         return 0;
3949                                                 case 1:
3950                                                 case 3:
3951                                                         fclose(f);
3952                                                         return 3;
3953                                                 case 2:
3954                                                         continue;
3955                                         }
3956                                 }
3957 #endif
3958
3959                                 key = line;
3960                                 val = strchr(line, '=');
3961                                 if (val == NULL)
3962                                 {
3963                                         printfPQExpBuffer(errorMessage,
3964                                                                           libpq_gettext("syntax error in service file \"%s\", line %d\n"),
3965                                                                           serviceFile,
3966                                                                           linenr);
3967                                         fclose(f);
3968                                         return 3;
3969                                 }
3970                                 *val++ = '\0';
3971
3972                                 /*
3973                                  * Set the parameter --- but don't override any previous
3974                                  * explicit setting.
3975                                  */
3976                                 found_keyword = false;
3977                                 for (i = 0; options[i].keyword; i++)
3978                                 {
3979                                         if (strcmp(options[i].keyword, key) == 0)
3980                                         {
3981                                                 if (options[i].val == NULL)
3982                                                         options[i].val = strdup(val);
3983                                                 found_keyword = true;
3984                                                 break;
3985                                         }
3986                                 }
3987
3988                                 if (!found_keyword)
3989                                 {
3990                                         printfPQExpBuffer(errorMessage,
3991                                                                           libpq_gettext("syntax error in service file \"%s\", line %d\n"),
3992                                                                           serviceFile,
3993                                                                           linenr);
3994                                         fclose(f);
3995                                         return 3;
3996                                 }
3997                         }
3998                 }
3999         }
4000
4001         fclose(f);
4002
4003         return 0;
4004 }
4005
4006
4007 /*
4008  *              PQconninfoParse
4009  *
4010  * Parse a string like PQconnectdb() would do and return the
4011  * resulting connection options array.  NULL is returned on failure.
4012  * The result contains only options specified directly in the string,
4013  * not any possible default values.
4014  *
4015  * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
4016  * string on failure (use PQfreemem to free it).  In out-of-memory conditions
4017  * both *errmsg and the result could be NULL.
4018  *
4019  * NOTE: the returned array is dynamically allocated and should
4020  * be freed when no longer needed via PQconninfoFree().
4021  */
4022 PQconninfoOption *
4023 PQconninfoParse(const char *conninfo, char **errmsg)
4024 {
4025         PQExpBufferData errorBuf;
4026         PQconninfoOption *connOptions;
4027
4028         if (errmsg)
4029                 *errmsg = NULL;                 /* default */
4030         initPQExpBuffer(&errorBuf);
4031         if (PQExpBufferDataBroken(errorBuf))
4032                 return NULL;                    /* out of memory already :-( */
4033         connOptions = parse_connection_string(conninfo, &errorBuf, false);
4034         if (connOptions == NULL && errmsg)
4035                 *errmsg = errorBuf.data;
4036         else
4037                 termPQExpBuffer(&errorBuf);
4038         return connOptions;
4039 }
4040
4041 /*
4042  * Build a working copy of the constant PQconninfoOptions array.
4043  */
4044 static PQconninfoOption *
4045 conninfo_init(PQExpBuffer errorMessage)
4046 {
4047         PQconninfoOption *options;
4048         PQconninfoOption *opt_dest;
4049         const internalPQconninfoOption *cur_opt;
4050
4051         /*
4052          * Get enough memory for all options in PQconninfoOptions, even if some
4053          * end up being filtered out.
4054          */
4055         options = (PQconninfoOption *) malloc(sizeof(PQconninfoOption) * sizeof(PQconninfoOptions) / sizeof(PQconninfoOptions[0]));
4056         if (options == NULL)
4057         {
4058                 printfPQExpBuffer(errorMessage,
4059                                                   libpq_gettext("out of memory\n"));
4060                 return NULL;
4061         }
4062         opt_dest = options;
4063
4064         for (cur_opt = PQconninfoOptions; cur_opt->keyword; cur_opt++)
4065         {
4066                 /* Only copy the public part of the struct, not the full internal */
4067                 memcpy(opt_dest, cur_opt, sizeof(PQconninfoOption));
4068                 opt_dest++;
4069         }
4070         MemSet(opt_dest, 0, sizeof(PQconninfoOption));
4071
4072         return options;
4073 }
4074
4075 /*
4076  * Connection string parser
4077  *
4078  * Returns a malloc'd PQconninfoOption array, if parsing is successful.
4079  * Otherwise, NULL is returned and an error message is left in errorMessage.
4080  *
4081  * If use_defaults is TRUE, default values are filled in (from a service file,
4082  * environment variables, etc).
4083  */
4084 static PQconninfoOption *
4085 parse_connection_string(const char *connstr, PQExpBuffer errorMessage,
4086                                                 bool use_defaults)
4087 {
4088         /* Parse as URI if connection string matches URI prefix */
4089         if (uri_prefix_length(connstr) != 0)
4090                 return conninfo_uri_parse(connstr, errorMessage, use_defaults);
4091
4092         /* Parse as default otherwise */
4093         return conninfo_parse(connstr, errorMessage, use_defaults);
4094 }
4095
4096 /*
4097  * Checks if connection string starts with either of the valid URI prefix
4098  * designators.
4099  *
4100  * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
4101  */
4102 static int
4103 uri_prefix_length(const char *connstr)
4104 {
4105         if (strncmp(connstr, uri_designator,
4106                                 sizeof(uri_designator) - 1) == 0)
4107                 return sizeof(uri_designator) - 1;
4108
4109         if (strncmp(connstr, short_uri_designator,
4110                                 sizeof(short_uri_designator) - 1) == 0)
4111                 return sizeof(short_uri_designator) - 1;
4112
4113         return 0;
4114 }
4115
4116 /*
4117  * Recognized connection string either starts with a valid URI prefix or
4118  * contains a "=" in it.
4119  *
4120  * Must be consistent with parse_connection_string: anything for which this
4121  * returns true should at least look like it's parseable by that routine.
4122  */
4123 static bool
4124 recognized_connection_string(const char *connstr)
4125 {
4126         return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
4127 }
4128
4129 /*
4130  * Subroutine for parse_connection_string
4131  *
4132  * Deal with a string containing key=value pairs.
4133  */
4134 static PQconninfoOption *
4135 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
4136                            bool use_defaults)
4137 {
4138         char       *pname;
4139         char       *pval;
4140         char       *buf;
4141         char       *cp;
4142         char       *cp2;
4143         PQconninfoOption *options;
4144
4145         /* Make a working copy of PQconninfoOptions */
4146         options = conninfo_init(errorMessage);
4147         if (options == NULL)
4148                 return NULL;
4149
4150         /* Need a modifiable copy of the input string */
4151         if ((buf = strdup(conninfo)) == NULL)
4152         {
4153                 printfPQExpBuffer(errorMessage,
4154                                                   libpq_gettext("out of memory\n"));
4155                 PQconninfoFree(options);
4156                 return NULL;
4157         }
4158         cp = buf;
4159
4160         while (*cp)
4161         {
4162                 /* Skip blanks before the parameter name */
4163                 if (isspace((unsigned char) *cp))
4164                 {
4165                         cp++;
4166                         continue;
4167                 }
4168
4169                 /* Get the parameter name */
4170                 pname = cp;
4171                 while (*cp)
4172                 {
4173                         if (*cp == '=')
4174                                 break;
4175                         if (isspace((unsigned char) *cp))
4176                         {
4177                                 *cp++ = '\0';
4178                                 while (*cp)
4179                                 {
4180                                         if (!isspace((unsigned char) *cp))
4181                                                 break;
4182                                         cp++;
4183                                 }
4184                                 break;
4185                         }
4186                         cp++;
4187                 }
4188
4189                 /* Check that there is a following '=' */
4190                 if (*cp != '=')
4191                 {
4192                         printfPQExpBuffer(errorMessage,
4193                                                           libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
4194                                                           pname);
4195                         PQconninfoFree(options);
4196                         free(buf);
4197                         return NULL;
4198                 }
4199                 *cp++ = '\0';
4200
4201                 /* Skip blanks after the '=' */
4202                 while (*cp)
4203                 {
4204                         if (!isspace((unsigned char) *cp))
4205                                 break;
4206                         cp++;
4207                 }
4208
4209                 /* Get the parameter value */
4210                 pval = cp;
4211
4212                 if (*cp != '\'')
4213                 {
4214                         cp2 = pval;
4215                         while (*cp)
4216                         {
4217                                 if (isspace((unsigned char) *cp))
4218                                 {
4219                                         *cp++ = '\0';
4220                                         break;
4221                                 }
4222                                 if (*cp == '\\')
4223                                 {
4224                                         cp++;
4225                                         if (*cp != '\0')
4226                                                 *cp2++ = *cp++;
4227                                 }
4228                                 else
4229                                         *cp2++ = *cp++;
4230                         }
4231                         *cp2 = '\0';
4232                 }
4233                 else
4234                 {
4235                         cp2 = pval;
4236                         cp++;
4237                         for (;;)
4238                         {
4239                                 if (*cp == '\0')
4240                                 {
4241                                         printfPQExpBuffer(errorMessage,
4242                                                                           libpq_gettext("unterminated quoted string in connection info string\n"));
4243                                         PQconninfoFree(options);
4244                                         free(buf);
4245                                         return NULL;
4246                                 }
4247                                 if (*cp == '\\')
4248                                 {
4249                                         cp++;
4250                                         if (*cp != '\0')
4251                                                 *cp2++ = *cp++;
4252                                         continue;
4253                                 }
4254                                 if (*cp == '\'')
4255                                 {
4256                                         *cp2 = '\0';
4257                                         cp++;
4258                                         break;
4259                                 }
4260                                 *cp2++ = *cp++;
4261                         }
4262                 }
4263
4264                 /*
4265                  * Now that we have the name and the value, store the record.
4266                  */
4267                 if (!conninfo_storeval(options, pname, pval, errorMessage, false, false))
4268                 {
4269                         PQconninfoFree(options);
4270                         free(buf);
4271                         return NULL;
4272                 }
4273         }
4274
4275         /* Done with the modifiable input string */
4276         free(buf);
4277
4278         /*
4279          * Add in defaults if the caller wants that.
4280          */
4281         if (use_defaults)
4282         {
4283                 if (!conninfo_add_defaults(options, errorMessage))
4284                 {
4285                         PQconninfoFree(options);
4286                         return NULL;
4287                 }
4288         }
4289
4290         return options;
4291 }
4292
4293 /*
4294  * Conninfo array parser routine
4295  *
4296  * If successful, a malloc'd PQconninfoOption array is returned.
4297  * If not successful, NULL is returned and an error message is
4298  * left in errorMessage.
4299  * Defaults are supplied (from a service file, environment variables, etc)
4300  * for unspecified options, but only if use_defaults is TRUE.
4301  *
4302  * If expand_dbname is non-zero, and the value passed for keyword "dbname" is a
4303  * connection string (as indicated by recognized_connection_string) then parse
4304  * and process it, overriding any previously processed conflicting
4305  * keywords. Subsequent keywords will take precedence, however.
4306  */
4307 static PQconninfoOption *
4308 conninfo_array_parse(const char *const * keywords, const char *const * values,
4309                                          PQExpBuffer errorMessage, bool use_defaults,
4310                                          int expand_dbname)
4311 {
4312         PQconninfoOption *options;
4313         PQconninfoOption *dbname_options = NULL;
4314         PQconninfoOption *option;
4315         int                     i = 0;
4316
4317         /*
4318          * If expand_dbname is non-zero, check keyword "dbname" to see if val is
4319          * actually a recognized connection string.
4320          */
4321         while (expand_dbname && keywords[i])
4322         {
4323                 const char *pname = keywords[i];
4324                 const char *pvalue = values[i];
4325
4326                 /* first find "dbname" if any */
4327                 if (strcmp(pname, "dbname") == 0 && pvalue)
4328                 {
4329                         /*
4330                          * If value is a connection string, parse it, but do not use
4331                          * defaults here -- those get picked up later. We only want to
4332                          * override for those parameters actually passed.
4333                          */
4334                         if (recognized_connection_string(pvalue))
4335                         {
4336                                 dbname_options = parse_connection_string(pvalue, errorMessage, false);
4337                                 if (dbname_options == NULL)
4338                                         return NULL;
4339                         }
4340                         break;
4341                 }
4342                 ++i;
4343         }
4344
4345         /* Make a working copy of PQconninfoOptions */
4346         options = conninfo_init(errorMessage);
4347         if (options == NULL)
4348         {
4349                 PQconninfoFree(dbname_options);
4350                 return NULL;
4351         }
4352
4353         /* Parse the keywords/values arrays */
4354         i = 0;
4355         while (keywords[i])
4356         {
4357                 const char *pname = keywords[i];
4358                 const char *pvalue = values[i];
4359
4360                 if (pvalue != NULL && pvalue[0] != '\0')
4361                 {
4362                         /* Search for the param record */
4363                         for (option = options; option->keyword != NULL; option++)
4364                         {
4365                                 if (strcmp(option->keyword, pname) == 0)
4366                                         break;
4367                         }
4368
4369                         /* Check for invalid connection option */
4370                         if (option->keyword == NULL)
4371                         {
4372                                 printfPQExpBuffer(errorMessage,
4373                                                  libpq_gettext("invalid connection option \"%s\"\n"),
4374                                                                   pname);
4375                                 PQconninfoFree(options);
4376                                 PQconninfoFree(dbname_options);
4377                                 return NULL;
4378                         }
4379
4380                         /*
4381                          * If we are on the dbname parameter, and we have a parsed
4382                          * connection string, copy those parameters across, overriding any
4383                          * existing previous settings.
4384                          */
4385                         if (strcmp(pname, "dbname") == 0 && dbname_options)
4386                         {
4387                                 PQconninfoOption *str_option;
4388
4389                                 for (str_option = dbname_options; str_option->keyword != NULL; str_option++)
4390                                 {
4391                                         if (str_option->val != NULL)
4392                                         {
4393                                                 int                     k;
4394
4395                                                 for (k = 0; options[k].keyword; k++)
4396                                                 {
4397                                                         if (strcmp(options[k].keyword, str_option->keyword) == 0)
4398                                                         {
4399                                                                 if (options[k].val)
4400                                                                         free(options[k].val);
4401                                                                 options[k].val = strdup(str_option->val);
4402                                                                 break;
4403                                                         }
4404                                                 }
4405                                         }
4406                                 }
4407                         }
4408                         else
4409                         {
4410                                 /*
4411                                  * Store the value, overriding previous settings
4412                                  */
4413                                 if (option->val)
4414                                         free(option->val);
4415                                 option->val = strdup(pvalue);
4416                                 if (!option->val)
4417                                 {
4418                                         printfPQExpBuffer(errorMessage,
4419                                                                           libpq_gettext("out of memory\n"));
4420                                         PQconninfoFree(options);
4421                                         PQconninfoFree(dbname_options);
4422                                         return NULL;
4423                                 }
4424                         }
4425                 }
4426                 ++i;
4427         }
4428         PQconninfoFree(dbname_options);
4429
4430         /*
4431          * Add in defaults if the caller wants that.
4432          */
4433         if (use_defaults)
4434         {
4435                 if (!conninfo_add_defaults(options, errorMessage))
4436                 {
4437                         PQconninfoFree(options);
4438                         return NULL;
4439                 }
4440         }
4441
4442         return options;
4443 }
4444
4445 /*
4446  * Add the default values for any unspecified options to the connection
4447  * options array.
4448  *
4449  * Defaults are obtained from a service file, environment variables, etc.
4450  *
4451  * Returns TRUE if successful, otherwise FALSE; errorMessage, if supplied,
4452  * is filled in upon failure.  Note that failure to locate a default value
4453  * is not an error condition here --- we just leave the option's value as
4454  * NULL.
4455  */
4456 static bool
4457 conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
4458 {
4459         PQconninfoOption *option;
4460         char       *tmp;
4461
4462         /*
4463          * If there's a service spec, use it to obtain any not-explicitly-given
4464          * parameters.  Ignore error if no error message buffer is passed
4465          * because there is no way to pass back the failure message.
4466          */
4467         if (parseServiceInfo(options, errorMessage) != 0 && errorMessage)
4468                 return false;
4469
4470         /*
4471          * Get the fallback resources for parameters not specified in the conninfo
4472          * string nor the service.
4473          */
4474         for (option = options; option->keyword != NULL; option++)
4475         {
4476                 if (option->val != NULL)
4477                         continue;                       /* Value was in conninfo or service */
4478
4479                 /*
4480                  * Try to get the environment variable fallback
4481                  */
4482                 if (option->envvar != NULL)
4483                 {
4484                         if ((tmp = getenv(option->envvar)) != NULL)
4485                         {
4486                                 option->val = strdup(tmp);
4487                                 if (!option->val)
4488                                 {
4489                                         if (errorMessage)
4490                                                 printfPQExpBuffer(errorMessage,
4491                                                                                   libpq_gettext("out of memory\n"));
4492                                         return false;
4493                                 }
4494                                 continue;
4495                         }
4496                 }
4497
4498                 /*
4499                  * No environment variable specified or the variable isn't set - try
4500                  * compiled-in default
4501                  */
4502                 if (option->compiled != NULL)
4503                 {
4504                         option->val = strdup(option->compiled);
4505                         if (!option->val)
4506                         {
4507                                 if (errorMessage)
4508                                         printfPQExpBuffer(errorMessage,
4509                                                                           libpq_gettext("out of memory\n"));
4510                                 return false;
4511                         }
4512                         continue;
4513                 }
4514
4515                 /*
4516                  * Special handling for "user" option
4517                  */
4518                 if (strcmp(option->keyword, "user") == 0)
4519                 {
4520                         option->val = pg_fe_getauthname();
4521                         if (!option->val)
4522                         {
4523                                 if (errorMessage)
4524                                         printfPQExpBuffer(errorMessage,
4525                                                                           libpq_gettext("out of memory\n"));
4526                                 return false;
4527                         }
4528                         continue;
4529                 }
4530         }
4531
4532         return true;
4533 }
4534
4535 /*
4536  * Subroutine for parse_connection_string
4537  *
4538  * Deal with a URI connection string.
4539  */
4540 static PQconninfoOption *
4541 conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage,
4542                                    bool use_defaults)
4543 {
4544         PQconninfoOption *options;
4545
4546         /* Make a working copy of PQconninfoOptions */
4547         options = conninfo_init(errorMessage);
4548         if (options == NULL)
4549                 return NULL;
4550
4551         if (!conninfo_uri_parse_options(options, uri, errorMessage))
4552         {
4553                 PQconninfoFree(options);
4554                 return NULL;
4555         }
4556
4557         /*
4558          * Add in defaults if the caller wants that.
4559          */
4560         if (use_defaults)
4561         {
4562                 if (!conninfo_add_defaults(options, errorMessage))
4563                 {
4564                         PQconninfoFree(options);
4565                         return NULL;
4566                 }
4567         }
4568
4569         return options;
4570 }
4571
4572 /*
4573  * conninfo_uri_parse_options
4574  *              Actual URI parser.
4575  *
4576  * If successful, returns true while the options array is filled with parsed
4577  * options from the URI.
4578  * If not successful, returns false and fills errorMessage accordingly.
4579  *
4580  * Parses the connection URI string in 'uri' according to the URI syntax (RFC
4581  * 3986):
4582  *
4583  * postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
4584  *
4585  * where "netloc" is a hostname, an IPv4 address, or an IPv6 address surrounded
4586  * by literal square brackets.
4587  *
4588  * Any of the URI parts might use percent-encoding (%xy).
4589  */
4590 static bool
4591 conninfo_uri_parse_options(PQconninfoOption *options, const char *uri,
4592                                                    PQExpBuffer errorMessage)
4593 {
4594         int                     prefix_len;
4595         char       *p;
4596         char       *buf = strdup(uri);          /* need a modifiable copy of the input
4597                                                                                  * URI */
4598         char       *start = buf;
4599         char            prevchar = '\0';
4600         char       *user = NULL;
4601         char       *host = NULL;
4602         bool            retval = false;
4603
4604         if (buf == NULL)
4605         {
4606                 printfPQExpBuffer(errorMessage,
4607                                                   libpq_gettext("out of memory\n"));
4608                 return false;
4609         }
4610
4611         /* Skip the URI prefix */
4612         prefix_len = uri_prefix_length(uri);
4613         if (prefix_len == 0)
4614         {
4615                 /* Should never happen */
4616                 printfPQExpBuffer(errorMessage,
4617                                                   libpq_gettext("invalid URI propagated to internal parser routine: \"%s\"\n"),
4618                                                   uri);
4619                 goto cleanup;
4620         }
4621         start += prefix_len;
4622         p = start;
4623
4624         /* Look ahead for possible user credentials designator */
4625         while (*p && *p != '@' && *p != '/')
4626                 ++p;
4627         if (*p == '@')
4628         {
4629                 /*
4630                  * Found username/password designator, so URI should be of the form
4631                  * "scheme://user[:password]@[netloc]".
4632                  */
4633                 user = start;
4634
4635                 p = user;
4636                 while (*p != ':' && *p != '@')
4637                         ++p;
4638
4639                 /* Save last char and cut off at end of user name */
4640                 prevchar = *p;
4641                 *p = '\0';
4642
4643                 if (*user &&
4644                         !conninfo_storeval(options, "user", user,
4645                                                            errorMessage, false, true))
4646                         goto cleanup;
4647
4648                 if (prevchar == ':')
4649                 {
4650                         const char *password = p + 1;
4651
4652                         while (*p != '@')
4653                                 ++p;
4654                         *p = '\0';
4655
4656                         if (*password &&
4657                                 !conninfo_storeval(options, "password", password,
4658                                                                    errorMessage, false, true))
4659                                 goto cleanup;
4660                 }
4661
4662                 /* Advance past end of parsed user name or password token */
4663                 ++p;
4664         }
4665         else
4666         {
4667                 /*
4668                  * No username/password designator found.  Reset to start of URI.
4669                  */
4670                 p = start;
4671         }
4672
4673         /*
4674          * "p" has been incremented past optional URI credential information at
4675          * this point and now points at the "netloc" part of the URI.
4676          *
4677          * Look for IPv6 address.
4678          */
4679         if (*p == '[')
4680         {
4681                 host = ++p;
4682                 while (*p && *p != ']')
4683                         ++p;
4684                 if (!*p)
4685                 {
4686                         printfPQExpBuffer(errorMessage,
4687                                                           libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"),
4688                                                           uri);
4689                         goto cleanup;
4690                 }
4691                 if (p == host)
4692                 {
4693                         printfPQExpBuffer(errorMessage,
4694                                                           libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"),
4695                                                           uri);
4696                         goto cleanup;
4697                 }
4698
4699                 /* Cut off the bracket and advance */
4700                 *(p++) = '\0';
4701
4702                 /*
4703                  * The address may be followed by a port specifier or a slash or a
4704                  * query.
4705                  */
4706                 if (*p && *p != ':' && *p != '/' && *p != '?')
4707                 {
4708                         printfPQExpBuffer(errorMessage,
4709                                                           libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"),
4710                                                           *p, (int) (p - buf + 1), uri);
4711                         goto cleanup;
4712                 }
4713         }
4714         else
4715         {
4716                 /* not an IPv6 address: DNS-named or IPv4 netloc */
4717                 host = p;
4718
4719                 /*
4720                  * Look for port specifier (colon) or end of host specifier (slash),
4721                  * or query (question mark).
4722                  */
4723                 while (*p && *p != ':' && *p != '/' && *p != '?')
4724                         ++p;
4725         }
4726
4727         /* Save the hostname terminator before we null it */
4728         prevchar = *p;
4729         *p = '\0';
4730
4731         if (*host &&
4732                 !conninfo_storeval(options, "host", host,
4733                                                    errorMessage, false, true))
4734                 goto cleanup;
4735
4736
4737         if (prevchar == ':')
4738         {
4739                 const char *port = ++p; /* advance past host terminator */
4740
4741                 while (*p && *p != '/' && *p != '?')
4742                         ++p;
4743
4744                 prevchar = *p;
4745                 *p = '\0';
4746
4747                 if (*port &&
4748                         !conninfo_storeval(options, "port", port,
4749                                                            errorMessage, false, true))
4750                         goto cleanup;
4751         }
4752
4753         if (prevchar && prevchar != '?')
4754         {
4755                 const char *dbname = ++p;               /* advance past host terminator */
4756
4757                 /* Look for query parameters */
4758                 while (*p && *p != '?')
4759                         ++p;
4760
4761                 prevchar = *p;
4762                 *p = '\0';
4763
4764                 /*
4765                  * Avoid setting dbname to an empty string, as it forces the default
4766                  * value (username) and ignores $PGDATABASE, as opposed to not setting
4767                  * it at all.
4768                  */
4769                 if (*dbname &&
4770                         !conninfo_storeval(options, "dbname", dbname,
4771                                                            errorMessage, false, true))
4772                         goto cleanup;
4773         }
4774
4775         if (prevchar)
4776         {
4777                 ++p;                                    /* advance past terminator */
4778
4779                 if (!conninfo_uri_parse_params(p, options, errorMessage))
4780                         goto cleanup;
4781         }
4782
4783         /* everything parsed okay */
4784         retval = true;
4785
4786 cleanup:
4787         free(buf);
4788         return retval;
4789 }
4790
4791 /*
4792  * Connection URI parameters parser routine
4793  *
4794  * If successful, returns true while connOptions is filled with parsed
4795  * parameters.  Otherwise, returns false and fills errorMessage appropriately.
4796  *
4797  * Destructively modifies 'params' buffer.
4798  */
4799 static bool
4800 conninfo_uri_parse_params(char *params,
4801                                                   PQconninfoOption *connOptions,
4802                                                   PQExpBuffer errorMessage)
4803 {
4804         while (*params)
4805         {
4806                 char       *keyword = params;
4807                 char       *value = NULL;
4808                 char       *p = params;
4809                 bool            malloced = false;
4810
4811                 /*
4812                  * Scan the params string for '=' and '&', marking the end of keyword
4813                  * and value respectively.
4814                  */
4815                 for (;;)
4816                 {
4817                         if (*p == '=')
4818                         {
4819                                 /* Was there '=' already? */
4820                                 if (value != NULL)
4821                                 {
4822                                         printfPQExpBuffer(errorMessage,
4823                                                                           libpq_gettext("extra key/value separator \"=\" in URI query parameter: \"%s\"\n"),
4824                                                                           params);
4825                                         return false;
4826                                 }
4827                                 /* Cut off keyword, advance to value */
4828                                 *p = '\0';
4829                                 value = ++p;
4830                         }
4831                         else if (*p == '&' || *p == '\0')
4832                         {
4833                                 char            prevchar;
4834
4835                                 /* Cut off value, remember old value */
4836                                 prevchar = *p;
4837                                 *p = '\0';
4838
4839                                 /* Was there '=' at all? */
4840                                 if (value == NULL)
4841                                 {
4842                                         printfPQExpBuffer(errorMessage,
4843                                                                           libpq_gettext("missing key/value separator \"=\" in URI query parameter: \"%s\"\n"),
4844                                                                           params);
4845                                         return false;
4846                                 }
4847
4848                                 /*
4849                                  * If not at the end, advance; now pointing to start of the
4850                                  * next parameter, if any.
4851                                  */
4852                                 if (prevchar != '\0')
4853                                         ++p;
4854                                 break;
4855                         }
4856
4857                         /* Advance, NUL is checked in the 'if' above */
4858                         ++p;
4859                 }
4860
4861                 keyword = conninfo_uri_decode(keyword, errorMessage);
4862                 if (keyword == NULL)
4863                 {
4864                         /* conninfo_uri_decode already set an error message */
4865                         return false;
4866                 }
4867                 value = conninfo_uri_decode(value, errorMessage);
4868                 if (value == NULL)
4869                 {
4870                         /* conninfo_uri_decode already set an error message */
4871                         free(keyword);
4872                         return false;
4873                 }
4874                 malloced = true;
4875
4876                 /*
4877                  * Special keyword handling for improved JDBC compatibility.
4878                  */
4879                 if (strcmp(keyword, "ssl") == 0 &&
4880                         strcmp(value, "true") == 0)
4881                 {
4882                         free(keyword);
4883                         free(value);
4884                         malloced = false;
4885
4886                         keyword = "sslmode";
4887                         value = "require";
4888                 }
4889
4890                 /*
4891                  * Store the value if the corresponding option exists; ignore
4892                  * otherwise.  At this point both keyword and value are not
4893                  * URI-encoded.
4894                  */
4895                 if (!conninfo_storeval(connOptions, keyword, value,
4896                                                            errorMessage, true, false))
4897                 {
4898                         /*
4899                          * Check if there was a hard error when decoding or storing the
4900                          * option.
4901                          */
4902                         if (errorMessage->len != 0)
4903                         {
4904                                 if (malloced)
4905                                 {
4906                                         free(keyword);
4907                                         free(value);
4908                                 }
4909                                 return false;
4910                         }
4911
4912                         printfPQExpBuffer(errorMessage,
4913                                                           libpq_gettext(
4914                                                                         "invalid URI query parameter: \"%s\"\n"),
4915                                                           keyword);
4916                         if (malloced)
4917                         {
4918                                 free(keyword);
4919                                 free(value);
4920                         }
4921                         return false;
4922                 }
4923                 if (malloced)
4924                 {
4925                         free(keyword);
4926                         free(value);
4927                 }
4928
4929                 /* Proceed to next key=value pair */
4930                 params = p;
4931         }
4932
4933         return true;
4934 }
4935
4936 /*
4937  * Connection URI decoder routine
4938  *
4939  * If successful, returns the malloc'd decoded string.
4940  * If not successful, returns NULL and fills errorMessage accordingly.
4941  *
4942  * The string is decoded by replacing any percent-encoded tokens with
4943  * corresponding characters, while preserving any non-encoded characters.  A
4944  * percent-encoded token is a character triplet: a percent sign, followed by a
4945  * pair of hexadecimal digits (0-9A-F), where lower- and upper-case letters are
4946  * treated identically.
4947  */
4948 static char *
4949 conninfo_uri_decode(const char *str, PQExpBuffer errorMessage)
4950 {
4951         char       *buf = malloc(strlen(str) + 1);
4952         char       *p = buf;
4953         const char *q = str;
4954
4955         if (buf == NULL)
4956         {
4957                 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
4958                 return NULL;
4959         }
4960
4961         for (;;)
4962         {
4963                 if (*q != '%')
4964                 {
4965                         /* copy and check for NUL terminator */
4966                         if (!(*(p++) = *(q++)))
4967                                 break;
4968                 }
4969                 else
4970                 {
4971                         int                     hi;
4972                         int                     lo;
4973                         int                     c;
4974
4975                         ++q;                            /* skip the percent sign itself */
4976
4977                         /*
4978                          * Possible EOL will be caught by the first call to
4979                          * get_hexdigit(), so we never dereference an invalid q pointer.
4980                          */
4981                         if (!(get_hexdigit(*q++, &hi) && get_hexdigit(*q++, &lo)))
4982                         {
4983                                 printfPQExpBuffer(errorMessage,
4984                                         libpq_gettext("invalid percent-encoded token: \"%s\"\n"),
4985                                                                   str);
4986                                 free(buf);
4987                                 return NULL;
4988                         }
4989
4990                         c = (hi << 4) | lo;
4991                         if (c == 0)
4992                         {
4993                                 printfPQExpBuffer(errorMessage,
4994                                                                   libpq_gettext("forbidden value %%00 in percent-encoded value: \"%s\"\n"),
4995                                                                   str);
4996                                 free(buf);
4997                                 return NULL;
4998                         }
4999                         *(p++) = c;
5000                 }
5001         }
5002
5003         return buf;
5004 }
5005
5006 /*
5007  * Convert hexadecimal digit character to its integer value.
5008  *
5009  * If successful, returns true and value is filled with digit's base 16 value.
5010  * If not successful, returns false.
5011  *
5012  * Lower- and upper-case letters in the range A-F are treated identically.
5013  */
5014 static bool
5015 get_hexdigit(char digit, int *value)
5016 {
5017         if ('0' <= digit && digit <= '9')
5018                 *value = digit - '0';
5019         else if ('A' <= digit && digit <= 'F')
5020                 *value = digit - 'A' + 10;
5021         else if ('a' <= digit && digit <= 'f')
5022                 *value = digit - 'a' + 10;
5023         else
5024                 return false;
5025
5026         return true;
5027 }
5028
5029 /*
5030  * Find an option value corresponding to the keyword in the connOptions array.
5031  *
5032  * If successful, returns a pointer to the corresponding option's value.
5033  * If not successful, returns NULL.
5034  */
5035 static const char *
5036 conninfo_getval(PQconninfoOption *connOptions,
5037                                 const char *keyword)
5038 {
5039         PQconninfoOption *option;
5040
5041         option = conninfo_find(connOptions, keyword);
5042
5043         return option ? option->val : NULL;
5044 }
5045
5046 /*
5047  * Store a (new) value for an option corresponding to the keyword in
5048  * connOptions array.
5049  *
5050  * If uri_decode is true, the value is URI-decoded.  The keyword is always
5051  * assumed to be non URI-encoded.
5052  *
5053  * If successful, returns a pointer to the corresponding PQconninfoOption,
5054  * which value is replaced with a strdup'd copy of the passed value string.
5055  * The existing value for the option is free'd before replacing, if any.
5056  *
5057  * If not successful, returns NULL and fills errorMessage accordingly.
5058  * However, if the reason of failure is an invalid keyword being passed and
5059  * ignoreMissing is TRUE, errorMessage will be left untouched.
5060  */
5061 static PQconninfoOption *
5062 conninfo_storeval(PQconninfoOption *connOptions,
5063                                   const char *keyword, const char *value,
5064                                   PQExpBuffer errorMessage, bool ignoreMissing,
5065                                   bool uri_decode)
5066 {
5067         PQconninfoOption *option;
5068         char       *value_copy;
5069
5070         /*
5071          * For backwards compatibility, requiressl=1 gets translated to
5072          * sslmode=require, and requiressl=0 gets translated to sslmode=prefer
5073          * (which is the default for sslmode).
5074          */
5075         if (strcmp(keyword, "requiressl") == 0)
5076         {
5077                 keyword = "sslmode";
5078                 if (value[0] == '1')
5079                         value = "require";
5080                 else
5081                         value = "prefer";
5082         }
5083
5084         option = conninfo_find(connOptions, keyword);
5085         if (option == NULL)
5086         {
5087                 if (!ignoreMissing)
5088                         printfPQExpBuffer(errorMessage,
5089                                                  libpq_gettext("invalid connection option \"%s\"\n"),
5090                                                           keyword);
5091                 return NULL;
5092         }
5093
5094         if (uri_decode)
5095         {
5096                 value_copy = conninfo_uri_decode(value, errorMessage);
5097                 if (value_copy == NULL)
5098                         /* conninfo_uri_decode already set an error message */
5099                         return NULL;
5100         }
5101         else
5102         {
5103                 value_copy = strdup(value);
5104
5105                 if (value_copy == NULL)
5106                 {
5107                         printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
5108                         return NULL;
5109                 }
5110         }
5111
5112         if (option->val)
5113                 free(option->val);
5114         option->val = value_copy;
5115
5116         return option;
5117 }
5118
5119 /*
5120  * Find a PQconninfoOption option corresponding to the keyword in the
5121  * connOptions array.
5122  *
5123  * If successful, returns a pointer to the corresponding PQconninfoOption
5124  * structure.
5125  * If not successful, returns NULL.
5126  */
5127 static PQconninfoOption *
5128 conninfo_find(PQconninfoOption *connOptions, const char *keyword)
5129 {
5130         PQconninfoOption *option;
5131
5132         for (option = connOptions; option->keyword != NULL; option++)
5133         {
5134                 if (strcmp(option->keyword, keyword) == 0)
5135                         return option;
5136         }
5137
5138         return NULL;
5139 }
5140
5141
5142 /*
5143  * Return the connection options used for the connection
5144  */
5145 PQconninfoOption *
5146 PQconninfo(PGconn *conn)
5147 {
5148         PQExpBufferData errorBuf;
5149         PQconninfoOption *connOptions;
5150
5151         if (conn == NULL)
5152                 return NULL;
5153
5154         /* We don't actually report any errors here, but callees want a buffer */
5155         initPQExpBuffer(&errorBuf);
5156         if (PQExpBufferDataBroken(errorBuf))
5157                 return NULL;                    /* out of memory already :-( */
5158
5159         connOptions = conninfo_init(&errorBuf);
5160
5161         if (connOptions != NULL)
5162         {
5163                 const internalPQconninfoOption *option;
5164
5165                 for (option = PQconninfoOptions; option->keyword; option++)
5166                 {
5167                         char      **connmember;
5168
5169                         if (option->connofs < 0)
5170                                 continue;
5171
5172                         connmember = (char **) ((char *) conn + option->connofs);
5173
5174                         if (*connmember)
5175                                 conninfo_storeval(connOptions, option->keyword, *connmember,
5176                                                                   &errorBuf, true, false);
5177                 }
5178         }
5179
5180         termPQExpBuffer(&errorBuf);
5181
5182         return connOptions;
5183 }
5184
5185
5186 void
5187 PQconninfoFree(PQconninfoOption *connOptions)
5188 {
5189         PQconninfoOption *option;
5190
5191         if (connOptions == NULL)
5192                 return;
5193
5194         for (option = connOptions; option->keyword != NULL; option++)
5195         {
5196                 if (option->val != NULL)
5197                         free(option->val);
5198         }
5199         free(connOptions);
5200 }
5201
5202
5203 /* =========== accessor functions for PGconn ========= */
5204 char *
5205 PQdb(const PGconn *conn)
5206 {
5207         if (!conn)
5208                 return NULL;
5209         return conn->dbName;
5210 }
5211
5212 char *
5213 PQuser(const PGconn *conn)
5214 {
5215         if (!conn)
5216                 return NULL;
5217         return conn->pguser;
5218 }
5219
5220 char *
5221 PQpass(const PGconn *conn)
5222 {
5223         if (!conn)
5224                 return NULL;
5225         return conn->pgpass;
5226 }
5227
5228 char *
5229 PQhost(const PGconn *conn)
5230 {
5231         if (!conn)
5232                 return NULL;
5233         if (conn->pghost != NULL && conn->pghost[0] != '\0')
5234                 return conn->pghost;
5235         else
5236         {
5237 #ifdef HAVE_UNIX_SOCKETS
5238                 return conn->pgunixsocket;
5239 #else
5240                 return DefaultHost;
5241 #endif
5242         }
5243 }
5244
5245 char *
5246 PQhostaddr(const PGconn *conn)
5247 {
5248         if (!conn)
5249                 return NULL;
5250         return conn->pghostaddr;
5251 }
5252
5253 char *
5254 PQport(const PGconn *conn)
5255 {
5256         if (!conn)
5257                 return NULL;
5258         return conn->pgport;
5259 }
5260
5261 char *
5262 PQtty(const PGconn *conn)
5263 {
5264         if (!conn)
5265                 return NULL;
5266         return conn->pgtty;
5267 }
5268
5269 char *
5270 PQoptions(const PGconn *conn)
5271 {
5272         if (!conn)
5273                 return NULL;
5274         return conn->pgoptions;
5275 }
5276
5277 ConnStatusType
5278 PQstatus(const PGconn *conn)
5279 {
5280         if (!conn)
5281                 return CONNECTION_BAD;
5282         return conn->status;
5283 }
5284
5285 PGTransactionStatusType
5286 PQtransactionStatus(const PGconn *conn)
5287 {
5288         if (!conn || conn->status != CONNECTION_OK)
5289                 return PQTRANS_UNKNOWN;
5290         if (conn->asyncStatus != PGASYNC_IDLE)
5291                 return PQTRANS_ACTIVE;
5292         return conn->xactStatus;
5293 }
5294
5295 const char *
5296 PQparameterStatus(const PGconn *conn, const char *paramName)
5297 {
5298         const pgParameterStatus *pstatus;
5299
5300         if (!conn || !paramName)
5301                 return NULL;
5302         for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
5303         {
5304                 if (strcmp(pstatus->name, paramName) == 0)
5305                         return pstatus->value;
5306         }
5307         return NULL;
5308 }
5309
5310 int
5311 PQprotocolVersion(const PGconn *conn)
5312 {
5313         if (!conn)
5314                 return 0;
5315         if (conn->status == CONNECTION_BAD)
5316                 return 0;
5317         return PG_PROTOCOL_MAJOR(conn->pversion);
5318 }
5319
5320 int
5321 PQserverVersion(const PGconn *conn)
5322 {
5323         if (!conn)
5324                 return 0;
5325         if (conn->status == CONNECTION_BAD)
5326                 return 0;
5327         return conn->sversion;
5328 }
5329
5330 char *
5331 PQerrorMessage(const PGconn *conn)
5332 {
5333         if (!conn)
5334                 return libpq_gettext("connection pointer is NULL\n");
5335
5336         return conn->errorMessage.data;
5337 }
5338
5339 /*
5340  * In Windows, socket values are unsigned, and an invalid socket value
5341  * (INVALID_SOCKET) is ~0, which equals -1 in comparisons (with no compiler
5342  * warning). Ideally we would return an unsigned value for PQsocket() on
5343  * Windows, but that would cause the function's return value to differ from
5344  * Unix, so we just return -1 for invalid sockets.
5345  * http://msdn.microsoft.com/en-us/library/windows/desktop/cc507522%28v=vs.85%29.aspx
5346  * http://stackoverflow.com/questions/10817252/why-is-invalid-socket-defined-as-0-in-winsock2-h-c
5347  */
5348 int
5349 PQsocket(const PGconn *conn)
5350 {
5351         if (!conn)
5352                 return -1;
5353         return (conn->sock != PGINVALID_SOCKET) ? conn->sock : -1;
5354 }
5355
5356 int
5357 PQbackendPID(const PGconn *conn)
5358 {
5359         if (!conn || conn->status != CONNECTION_OK)
5360                 return 0;
5361         return conn->be_pid;
5362 }
5363
5364 int
5365 PQconnectionNeedsPassword(const PGconn *conn)
5366 {
5367         if (!conn)
5368                 return false;
5369         if (conn->password_needed &&
5370                 (conn->pgpass == NULL || conn->pgpass[0] == '\0'))
5371                 return true;
5372         else
5373                 return false;
5374 }
5375
5376 int
5377 PQconnectionUsedPassword(const PGconn *conn)
5378 {
5379         if (!conn)
5380                 return false;
5381         if (conn->password_needed)
5382                 return true;
5383         else
5384                 return false;
5385 }
5386
5387 int
5388 PQclientEncoding(const PGconn *conn)
5389 {
5390         if (!conn || conn->status != CONNECTION_OK)
5391                 return -1;
5392         return conn->client_encoding;
5393 }
5394
5395 int
5396 PQsetClientEncoding(PGconn *conn, const char *encoding)
5397 {
5398         char            qbuf[128];
5399         static const char query[] = "set client_encoding to '%s'";
5400         PGresult   *res;
5401         int                     status;
5402
5403         if (!conn || conn->status != CONNECTION_OK)
5404                 return -1;
5405
5406         if (!encoding)
5407                 return -1;
5408
5409         /* Resolve special "auto" value from the locale */
5410         if (strcmp(encoding, "auto") == 0)
5411                 encoding = pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true));
5412
5413         /* check query buffer overflow */
5414         if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
5415                 return -1;
5416
5417         /* ok, now send a query */
5418         sprintf(qbuf, query, encoding);
5419         res = PQexec(conn, qbuf);
5420
5421         if (res == NULL)
5422                 return -1;
5423         if (res->resultStatus != PGRES_COMMAND_OK)
5424                 status = -1;
5425         else
5426         {
5427                 /*
5428                  * In protocol 2 we have to assume the setting will stick, and adjust
5429                  * our state immediately.  In protocol 3 and up we can rely on the
5430                  * backend to report the parameter value, and we'll change state at
5431                  * that time.
5432                  */
5433                 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
5434                         pqSaveParameterStatus(conn, "client_encoding", encoding);
5435                 status = 0;                             /* everything is ok */
5436         }
5437         PQclear(res);
5438         return status;
5439 }
5440
5441 PGVerbosity
5442 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
5443 {
5444         PGVerbosity old;
5445
5446         if (!conn)
5447                 return PQERRORS_DEFAULT;
5448         old = conn->verbosity;
5449         conn->verbosity = verbosity;
5450         return old;
5451 }
5452
5453 void
5454 PQtrace(PGconn *conn, FILE *debug_port)
5455 {
5456         if (conn == NULL)
5457                 return;
5458         PQuntrace(conn);
5459         conn->Pfdebug = debug_port;
5460 }
5461
5462 void
5463 PQuntrace(PGconn *conn)
5464 {
5465         if (conn == NULL)
5466                 return;
5467         if (conn->Pfdebug)
5468         {
5469                 fflush(conn->Pfdebug);
5470                 conn->Pfdebug = NULL;
5471         }
5472 }
5473
5474 PQnoticeReceiver
5475 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
5476 {
5477         PQnoticeReceiver old;
5478
5479         if (conn == NULL)
5480                 return NULL;
5481
5482         old = conn->noticeHooks.noticeRec;
5483         if (proc)
5484         {
5485                 conn->noticeHooks.noticeRec = proc;
5486                 conn->noticeHooks.noticeRecArg = arg;
5487         }
5488         return old;
5489 }
5490
5491 PQnoticeProcessor
5492 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
5493 {
5494         PQnoticeProcessor old;
5495
5496         if (conn == NULL)
5497                 return NULL;
5498
5499         old = conn->noticeHooks.noticeProc;
5500         if (proc)
5501         {
5502                 conn->noticeHooks.noticeProc = proc;
5503                 conn->noticeHooks.noticeProcArg = arg;
5504         }
5505         return old;
5506 }
5507
5508 /*
5509  * The default notice message receiver just gets the standard notice text
5510  * and sends it to the notice processor.  This two-level setup exists
5511  * mostly for backwards compatibility; perhaps we should deprecate use of
5512  * PQsetNoticeProcessor?
5513  */
5514 static void
5515 defaultNoticeReceiver(void *arg, const PGresult *res)
5516 {
5517         (void) arg;                                     /* not used */
5518         if (res->noticeHooks.noticeProc != NULL)
5519                 (*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
5520                                                                                 PQresultErrorMessage(res));
5521 }
5522
5523 /*
5524  * The default notice message processor just prints the
5525  * message on stderr.  Applications can override this if they
5526  * want the messages to go elsewhere (a window, for example).
5527  * Note that simply discarding notices is probably a bad idea.
5528  */
5529 static void
5530 defaultNoticeProcessor(void *arg, const char *message)
5531 {
5532         (void) arg;                                     /* not used */
5533         /* Note: we expect the supplied string to end with a newline already. */
5534         fprintf(stderr, "%s", message);
5535 }
5536
5537 /*
5538  * returns a pointer to the next token or NULL if the current
5539  * token doesn't match
5540  */
5541 static char *
5542 pwdfMatchesString(char *buf, char *token)
5543 {
5544         char       *tbuf,
5545                            *ttok;
5546         bool            bslash = false;
5547
5548         if (buf == NULL || token == NULL)
5549                 return NULL;
5550         tbuf = buf;
5551         ttok = token;
5552         if (tbuf[0] == '*' && tbuf[1] == ':')
5553                 return tbuf + 2;
5554         while (*tbuf != 0)
5555         {
5556                 if (*tbuf == '\\' && !bslash)
5557                 {
5558                         tbuf++;
5559                         bslash = true;
5560                 }
5561                 if (*tbuf == ':' && *ttok == 0 && !bslash)
5562                         return tbuf + 1;
5563                 bslash = false;
5564                 if (*ttok == 0)
5565                         return NULL;
5566                 if (*tbuf == *ttok)
5567                 {
5568                         tbuf++;
5569                         ttok++;
5570                 }
5571                 else
5572                         return NULL;
5573         }
5574         return NULL;
5575 }
5576
5577 /* Get a password from the password file. Return value is malloc'd. */
5578 static char *
5579 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
5580 {
5581         FILE       *fp;
5582         char            pgpassfile[MAXPGPATH];
5583         struct stat stat_buf;
5584
5585 #define LINELEN NAMEDATALEN*5
5586         char            buf[LINELEN];
5587
5588         if (dbname == NULL || strlen(dbname) == 0)
5589                 return NULL;
5590
5591         if (username == NULL || strlen(username) == 0)
5592                 return NULL;
5593
5594         /* 'localhost' matches pghost of '' or the default socket directory */
5595         if (hostname == NULL)
5596                 hostname = DefaultHost;
5597         else if (is_absolute_path(hostname))
5598
5599                 /*
5600                  * We should probably use canonicalize_path(), but then we have to
5601                  * bring path.c into libpq, and it doesn't seem worth it.
5602                  */
5603                 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
5604                         hostname = DefaultHost;
5605
5606         if (port == NULL)
5607                 port = DEF_PGPORT_STR;
5608
5609         if (!getPgPassFilename(pgpassfile))
5610                 return NULL;
5611
5612         /* If password file cannot be opened, ignore it. */
5613         if (stat(pgpassfile, &stat_buf) != 0)
5614                 return NULL;
5615
5616 #ifndef WIN32
5617         if (!S_ISREG(stat_buf.st_mode))
5618         {
5619                 fprintf(stderr,
5620                 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
5621                                 pgpassfile);
5622                 return NULL;
5623         }
5624
5625         /* If password file is insecure, alert the user and ignore it. */
5626         if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
5627         {
5628                 fprintf(stderr,
5629                                 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
5630                                 pgpassfile);
5631                 return NULL;
5632         }
5633 #else
5634
5635         /*
5636          * On Win32, the directory is protected, so we don't have to check the
5637          * file.
5638          */
5639 #endif
5640
5641         fp = fopen(pgpassfile, "r");
5642         if (fp == NULL)
5643                 return NULL;
5644
5645         while (!feof(fp) && !ferror(fp))
5646         {
5647                 char       *t = buf,
5648                                    *ret,
5649                                    *p1,
5650                                    *p2;
5651                 int                     len;
5652
5653                 if (fgets(buf, sizeof(buf), fp) == NULL)
5654                         break;
5655
5656                 len = strlen(buf);
5657                 if (len == 0)
5658                         continue;
5659
5660                 /* Remove trailing newline */
5661                 if (buf[len - 1] == '\n')
5662                         buf[len - 1] = 0;
5663
5664                 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
5665                         (t = pwdfMatchesString(t, port)) == NULL ||
5666                         (t = pwdfMatchesString(t, dbname)) == NULL ||
5667                         (t = pwdfMatchesString(t, username)) == NULL)
5668                         continue;
5669                 ret = strdup(t);
5670                 fclose(fp);
5671
5672                 /* De-escape password. */
5673                 for (p1 = p2 = ret; *p1 != ':' && *p1 != '\0'; ++p1, ++p2)
5674                 {
5675                         if (*p1 == '\\' && p1[1] != '\0')
5676                                 ++p1;
5677                         *p2 = *p1;
5678                 }
5679                 *p2 = '\0';
5680
5681                 return ret;
5682         }
5683
5684         fclose(fp);
5685         return NULL;
5686
5687 #undef LINELEN
5688 }
5689
5690
5691 static bool
5692 getPgPassFilename(char *pgpassfile)
5693 {
5694         char       *passfile_env;
5695
5696         if ((passfile_env = getenv("PGPASSFILE")) != NULL)
5697                 /* use the literal path from the environment, if set */
5698                 strlcpy(pgpassfile, passfile_env, MAXPGPATH);
5699         else
5700         {
5701                 char            homedir[MAXPGPATH];
5702
5703                 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
5704                         return false;
5705                 snprintf(pgpassfile, MAXPGPATH, "%s/%s", homedir, PGPASSFILE);
5706         }
5707         return true;
5708 }
5709
5710 /*
5711  *      If the connection failed, we should mention if
5712  *      we got the password from .pgpass in case that
5713  *      password is wrong.
5714  */
5715 static void
5716 dot_pg_pass_warning(PGconn *conn)
5717 {
5718         /* If it was 'invalid authorization', add .pgpass mention */
5719         /* only works with >= 9.0 servers */
5720         if (conn->dot_pgpass_used && conn->password_needed && conn->result &&
5721                 strcmp(PQresultErrorField(conn->result, PG_DIAG_SQLSTATE),
5722                            ERRCODE_INVALID_PASSWORD) == 0)
5723         {
5724                 char            pgpassfile[MAXPGPATH];
5725
5726                 if (!getPgPassFilename(pgpassfile))
5727                         return;
5728                 appendPQExpBuffer(&conn->errorMessage,
5729                                           libpq_gettext("password retrieved from file \"%s\"\n"),
5730                                                   pgpassfile);
5731         }
5732 }
5733
5734
5735 /*
5736  * Obtain user's home directory, return in given buffer
5737  *
5738  * On Unix, this actually returns the user's home directory.  On Windows
5739  * it returns the PostgreSQL-specific application data folder.
5740  *
5741  * This is essentially the same as get_home_path(), but we don't use that
5742  * because we don't want to pull path.c into libpq (it pollutes application
5743  * namespace)
5744  */
5745 bool
5746 pqGetHomeDirectory(char *buf, int bufsize)
5747 {
5748 #ifndef WIN32
5749         char            pwdbuf[BUFSIZ];
5750         struct passwd pwdstr;
5751         struct passwd *pwd = NULL;
5752
5753         if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
5754                 return false;
5755         strlcpy(buf, pwd->pw_dir, bufsize);
5756         return true;
5757 #else
5758         char            tmppath[MAX_PATH];
5759
5760         ZeroMemory(tmppath, sizeof(tmppath));
5761         if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
5762                 return false;
5763         snprintf(buf, bufsize, "%s/postgresql", tmppath);
5764         return true;
5765 #endif
5766 }
5767
5768 /*
5769  * To keep the API consistent, the locking stubs are always provided, even
5770  * if they are not required.
5771  */
5772
5773 static void
5774 default_threadlock(int acquire)
5775 {
5776 #ifdef ENABLE_THREAD_SAFETY
5777 #ifndef WIN32
5778         static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
5779 #else
5780         static pthread_mutex_t singlethread_lock = NULL;
5781         static long mutex_initlock = 0;
5782
5783         if (singlethread_lock == NULL)
5784         {
5785                 while (InterlockedExchange(&mutex_initlock, 1) == 1)
5786                          /* loop, another thread own the lock */ ;
5787                 if (singlethread_lock == NULL)
5788                 {
5789                         if (pthread_mutex_init(&singlethread_lock, NULL))
5790                                 PGTHREAD_ERROR("failed to initialize mutex");
5791                 }
5792                 InterlockedExchange(&mutex_initlock, 0);
5793         }
5794 #endif
5795         if (acquire)
5796         {
5797                 if (pthread_mutex_lock(&singlethread_lock))
5798                         PGTHREAD_ERROR("failed to lock mutex");
5799         }
5800         else
5801         {
5802                 if (pthread_mutex_unlock(&singlethread_lock))
5803                         PGTHREAD_ERROR("failed to unlock mutex");
5804         }
5805 #endif
5806 }
5807
5808 pgthreadlock_t
5809 PQregisterThreadLock(pgthreadlock_t newhandler)
5810 {
5811         pgthreadlock_t prev = pg_g_threadlock;
5812
5813         if (newhandler)
5814                 pg_g_threadlock = newhandler;
5815         else
5816                 pg_g_threadlock = default_threadlock;
5817
5818         return prev;
5819 }