]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-connect.c
Update copyrights for 2013
[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-2013, 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", "", 8,              /* sizeof("disable") == 8 */
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(KRB5) || 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 >= 0)
402                 closesocket(conn->sock);
403         conn->sock = -1;
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                 if (!conninfo_add_defaults(connOptions, &errorBuf))
879                 {
880                         PQconninfoFree(connOptions);
881                         connOptions = NULL;
882                 }
883         }
884
885         termPQExpBuffer(&errorBuf);
886         return connOptions;
887 }
888
889 /* ----------------
890  *              PQsetdbLogin
891  *
892  * establishes a connection to a postgres backend through the postmaster
893  * at the specified host and port.
894  *
895  * returns a PGconn* which is needed for all subsequent libpq calls
896  *
897  * if the status field of the connection returned is CONNECTION_BAD,
898  * then only the errorMessage is likely to be useful.
899  * ----------------
900  */
901 PGconn *
902 PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
903                          const char *pgtty, const char *dbName, const char *login,
904                          const char *pwd)
905 {
906         PGconn     *conn;
907
908         /*
909          * Allocate memory for the conn structure
910          */
911         conn = makeEmptyPGconn();
912         if (conn == NULL)
913                 return NULL;
914
915         /*
916          * If the dbName parameter contains what looks like a connection string,
917          * parse it into conn struct using connectOptions1.
918          */
919         if (dbName && recognized_connection_string(dbName))
920         {
921                 if (!connectOptions1(conn, dbName))
922                         return conn;
923         }
924         else
925         {
926                 /*
927                  * Old-style path: first, parse an empty conninfo string in order to
928                  * set up the same defaults that PQconnectdb() would use.
929                  */
930                 if (!connectOptions1(conn, ""))
931                         return conn;
932
933                 /* Insert dbName parameter value into struct */
934                 if (dbName && dbName[0] != '\0')
935                 {
936                         if (conn->dbName)
937                                 free(conn->dbName);
938                         conn->dbName = strdup(dbName);
939                 }
940         }
941
942         /*
943          * Insert remaining parameters into struct, overriding defaults (as well
944          * as any conflicting data from dbName taken as a conninfo).
945          */
946         if (pghost && pghost[0] != '\0')
947         {
948                 if (conn->pghost)
949                         free(conn->pghost);
950                 conn->pghost = strdup(pghost);
951         }
952
953         if (pgport && pgport[0] != '\0')
954         {
955                 if (conn->pgport)
956                         free(conn->pgport);
957                 conn->pgport = strdup(pgport);
958         }
959
960         if (pgoptions && pgoptions[0] != '\0')
961         {
962                 if (conn->pgoptions)
963                         free(conn->pgoptions);
964                 conn->pgoptions = strdup(pgoptions);
965         }
966
967         if (pgtty && pgtty[0] != '\0')
968         {
969                 if (conn->pgtty)
970                         free(conn->pgtty);
971                 conn->pgtty = strdup(pgtty);
972         }
973
974         if (login && login[0] != '\0')
975         {
976                 if (conn->pguser)
977                         free(conn->pguser);
978                 conn->pguser = strdup(login);
979         }
980
981         if (pwd && pwd[0] != '\0')
982         {
983                 if (conn->pgpass)
984                         free(conn->pgpass);
985                 conn->pgpass = strdup(pwd);
986         }
987
988         /*
989          * Compute derived options
990          */
991         if (!connectOptions2(conn))
992                 return conn;
993
994         /*
995          * Connect to the database
996          */
997         if (connectDBStart(conn))
998                 (void) connectDBComplete(conn);
999
1000         return conn;
1001 }
1002
1003
1004 /* ----------
1005  * connectNoDelay -
1006  * Sets the TCP_NODELAY socket option.
1007  * Returns 1 if successful, 0 if not.
1008  * ----------
1009  */
1010 static int
1011 connectNoDelay(PGconn *conn)
1012 {
1013 #ifdef  TCP_NODELAY
1014         int                     on = 1;
1015
1016         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_NODELAY,
1017                                    (char *) &on,
1018                                    sizeof(on)) < 0)
1019         {
1020                 char            sebuf[256];
1021
1022                 appendPQExpBuffer(&conn->errorMessage,
1023                         libpq_gettext("could not set socket to TCP no delay mode: %s\n"),
1024                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1025                 return 0;
1026         }
1027 #endif
1028
1029         return 1;
1030 }
1031
1032
1033 /* ----------
1034  * connectFailureMessage -
1035  * create a friendly error message on connection failure.
1036  * ----------
1037  */
1038 static void
1039 connectFailureMessage(PGconn *conn, int errorno)
1040 {
1041         char            sebuf[256];
1042
1043 #ifdef HAVE_UNIX_SOCKETS
1044         if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1045         {
1046                 char            service[NI_MAXHOST];
1047
1048                 pg_getnameinfo_all(&conn->raddr.addr, conn->raddr.salen,
1049                                                    NULL, 0,
1050                                                    service, sizeof(service),
1051                                                    NI_NUMERICSERV);
1052                 appendPQExpBuffer(&conn->errorMessage,
1053                                                   libpq_gettext("could not connect to server: %s\n"
1054                                                         "\tIs the server running locally and accepting\n"
1055                                                         "\tconnections on Unix domain socket \"%s\"?\n"),
1056                                                   SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1057                                                   service);
1058         }
1059         else
1060 #endif   /* HAVE_UNIX_SOCKETS */
1061         {
1062                 char            host_addr[NI_MAXHOST];
1063                 const char *displayed_host;
1064                 struct sockaddr_storage *addr = &conn->raddr.addr;
1065
1066                 /*
1067                  * Optionally display the network address with the hostname. This is
1068                  * useful to distinguish between IPv4 and IPv6 connections.
1069                  */
1070                 if (conn->pghostaddr != NULL)
1071                         strlcpy(host_addr, conn->pghostaddr, NI_MAXHOST);
1072                 else if (addr->ss_family == AF_INET)
1073                 {
1074                         if (inet_net_ntop(AF_INET,
1075                                                           &((struct sockaddr_in *) addr)->sin_addr.s_addr,
1076                                                           32,
1077                                                           host_addr, sizeof(host_addr)) == NULL)
1078                                 strcpy(host_addr, "???");
1079                 }
1080 #ifdef HAVE_IPV6
1081                 else if (addr->ss_family == AF_INET6)
1082                 {
1083                         if (inet_net_ntop(AF_INET6,
1084                                                   &((struct sockaddr_in6 *) addr)->sin6_addr.s6_addr,
1085                                                           128,
1086                                                           host_addr, sizeof(host_addr)) == NULL)
1087                                 strcpy(host_addr, "???");
1088                 }
1089 #endif
1090                 else
1091                         strcpy(host_addr, "???");
1092
1093                 if (conn->pghostaddr && conn->pghostaddr[0] != '\0')
1094                         displayed_host = conn->pghostaddr;
1095                 else if (conn->pghost && conn->pghost[0] != '\0')
1096                         displayed_host = conn->pghost;
1097                 else
1098                         displayed_host = DefaultHost;
1099
1100                 /*
1101                  * If the user did not supply an IP address using 'hostaddr', and
1102                  * 'host' was missing or does not match our lookup, display the
1103                  * looked-up IP address.
1104                  */
1105                 if ((conn->pghostaddr == NULL) &&
1106                         (conn->pghost == NULL || strcmp(conn->pghost, host_addr) != 0))
1107                         appendPQExpBuffer(&conn->errorMessage,
1108                                                         libpq_gettext("could not connect to server: %s\n"
1109                                 "\tIs the server running on host \"%s\" (%s) and accepting\n"
1110                                                                            "\tTCP/IP connections on port %s?\n"),
1111                                                           SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1112                                                           displayed_host,
1113                                                           host_addr,
1114                                                           conn->pgport);
1115                 else
1116                         appendPQExpBuffer(&conn->errorMessage,
1117                                                         libpq_gettext("could not connect to server: %s\n"
1118                                          "\tIs the server running on host \"%s\" and accepting\n"
1119                                                                            "\tTCP/IP connections on port %s?\n"),
1120                                                           SOCK_STRERROR(errorno, sebuf, sizeof(sebuf)),
1121                                                           displayed_host,
1122                                                           conn->pgport);
1123         }
1124 }
1125
1126 /*
1127  * Should we use keepalives?  Returns 1 if yes, 0 if no, and -1 if
1128  * conn->keepalives is set to a value which is not parseable as an
1129  * integer.
1130  */
1131 static int
1132 useKeepalives(PGconn *conn)
1133 {
1134         char       *ep;
1135         int                     val;
1136
1137         if (conn->keepalives == NULL)
1138                 return 1;
1139         val = strtol(conn->keepalives, &ep, 10);
1140         if (*ep)
1141                 return -1;
1142         return val != 0 ? 1 : 0;
1143 }
1144
1145 #ifndef WIN32
1146 /*
1147  * Set the keepalive idle timer.
1148  */
1149 static int
1150 setKeepalivesIdle(PGconn *conn)
1151 {
1152         int                     idle;
1153
1154         if (conn->keepalives_idle == NULL)
1155                 return 1;
1156
1157         idle = atoi(conn->keepalives_idle);
1158         if (idle < 0)
1159                 idle = 0;
1160
1161 #ifdef TCP_KEEPIDLE
1162         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPIDLE,
1163                                    (char *) &idle, sizeof(idle)) < 0)
1164         {
1165                 char            sebuf[256];
1166
1167                 appendPQExpBuffer(&conn->errorMessage,
1168                                           libpq_gettext("setsockopt(TCP_KEEPIDLE) failed: %s\n"),
1169                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1170                 return 0;
1171         }
1172 #else
1173 #ifdef TCP_KEEPALIVE
1174         /* Darwin uses TCP_KEEPALIVE rather than TCP_KEEPIDLE */
1175         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPALIVE,
1176                                    (char *) &idle, sizeof(idle)) < 0)
1177         {
1178                 char            sebuf[256];
1179
1180                 appendPQExpBuffer(&conn->errorMessage,
1181                                          libpq_gettext("setsockopt(TCP_KEEPALIVE) failed: %s\n"),
1182                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1183                 return 0;
1184         }
1185 #endif
1186 #endif
1187
1188         return 1;
1189 }
1190
1191 /*
1192  * Set the keepalive interval.
1193  */
1194 static int
1195 setKeepalivesInterval(PGconn *conn)
1196 {
1197         int                     interval;
1198
1199         if (conn->keepalives_interval == NULL)
1200                 return 1;
1201
1202         interval = atoi(conn->keepalives_interval);
1203         if (interval < 0)
1204                 interval = 0;
1205
1206 #ifdef TCP_KEEPINTVL
1207         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPINTVL,
1208                                    (char *) &interval, sizeof(interval)) < 0)
1209         {
1210                 char            sebuf[256];
1211
1212                 appendPQExpBuffer(&conn->errorMessage,
1213                                          libpq_gettext("setsockopt(TCP_KEEPINTVL) failed: %s\n"),
1214                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1215                 return 0;
1216         }
1217 #endif
1218
1219         return 1;
1220 }
1221
1222 /*
1223  * Set the count of lost keepalive packets that will trigger a connection
1224  * break.
1225  */
1226 static int
1227 setKeepalivesCount(PGconn *conn)
1228 {
1229         int                     count;
1230
1231         if (conn->keepalives_count == NULL)
1232                 return 1;
1233
1234         count = atoi(conn->keepalives_count);
1235         if (count < 0)
1236                 count = 0;
1237
1238 #ifdef TCP_KEEPCNT
1239         if (setsockopt(conn->sock, IPPROTO_TCP, TCP_KEEPCNT,
1240                                    (char *) &count, sizeof(count)) < 0)
1241         {
1242                 char            sebuf[256];
1243
1244                 appendPQExpBuffer(&conn->errorMessage,
1245                                            libpq_gettext("setsockopt(TCP_KEEPCNT) failed: %s\n"),
1246                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1247                 return 0;
1248         }
1249 #endif
1250
1251         return 1;
1252 }
1253 #else                                                   /* Win32 */
1254 #ifdef SIO_KEEPALIVE_VALS
1255 /*
1256  * Enable keepalives and set the keepalive values on Win32,
1257  * where they are always set in one batch.
1258  */
1259 static int
1260 setKeepalivesWin32(PGconn *conn)
1261 {
1262         struct tcp_keepalive ka;
1263         DWORD           retsize;
1264         int                     idle = 0;
1265         int                     interval = 0;
1266
1267         if (conn->keepalives_idle)
1268                 idle = atoi(conn->keepalives_idle);
1269         if (idle <= 0)
1270                 idle = 2 * 60 * 60;             /* 2 hours = default */
1271
1272         if (conn->keepalives_interval)
1273                 interval = atoi(conn->keepalives_interval);
1274         if (interval <= 0)
1275                 interval = 1;                   /* 1 second = default */
1276
1277         ka.onoff = 1;
1278         ka.keepalivetime = idle * 1000;
1279         ka.keepaliveinterval = interval * 1000;
1280
1281         if (WSAIoctl(conn->sock,
1282                                  SIO_KEEPALIVE_VALS,
1283                                  (LPVOID) &ka,
1284                                  sizeof(ka),
1285                                  NULL,
1286                                  0,
1287                                  &retsize,
1288                                  NULL,
1289                                  NULL)
1290                 != 0)
1291         {
1292                 appendPQExpBuffer(&conn->errorMessage,
1293                                  libpq_gettext("WSAIoctl(SIO_KEEPALIVE_VALS) failed: %ui\n"),
1294                                                   WSAGetLastError());
1295                 return 0;
1296         }
1297         return 1;
1298 }
1299 #endif   /* SIO_KEEPALIVE_VALS */
1300 #endif   /* WIN32 */
1301
1302 /* ----------
1303  * connectDBStart -
1304  *              Begin the process of making a connection to the backend.
1305  *
1306  * Returns 1 if successful, 0 if not.
1307  * ----------
1308  */
1309 static int
1310 connectDBStart(PGconn *conn)
1311 {
1312         int                     portnum;
1313         char            portstr[MAXPGPATH];
1314         struct addrinfo *addrs = NULL;
1315         struct addrinfo hint;
1316         const char *node;
1317         int                     ret;
1318
1319         if (!conn)
1320                 return 0;
1321
1322         if (!conn->options_valid)
1323                 goto connect_errReturn;
1324
1325         /* Ensure our buffers are empty */
1326         conn->inStart = conn->inCursor = conn->inEnd = 0;
1327         conn->outCount = 0;
1328
1329         /*
1330          * Determine the parameters to pass to pg_getaddrinfo_all.
1331          */
1332
1333         /* Initialize hint structure */
1334         MemSet(&hint, 0, sizeof(hint));
1335         hint.ai_socktype = SOCK_STREAM;
1336         hint.ai_family = AF_UNSPEC;
1337
1338         /* Set up port number as a string */
1339         if (conn->pgport != NULL && conn->pgport[0] != '\0')
1340         {
1341                 portnum = atoi(conn->pgport);
1342                 if (portnum < 1 || portnum > 65535)
1343                 {
1344                         appendPQExpBuffer(&conn->errorMessage,
1345                                                           libpq_gettext("invalid port number: \"%s\"\n"),
1346                                                           conn->pgport);
1347                         conn->options_valid = false;
1348                         goto connect_errReturn;
1349                 }
1350         }
1351         else
1352                 portnum = DEF_PGPORT;
1353         snprintf(portstr, sizeof(portstr), "%d", portnum);
1354
1355         if (conn->pghostaddr != NULL && conn->pghostaddr[0] != '\0')
1356         {
1357                 /* Using pghostaddr avoids a hostname lookup */
1358                 node = conn->pghostaddr;
1359                 hint.ai_family = AF_UNSPEC;
1360                 hint.ai_flags = AI_NUMERICHOST;
1361         }
1362         else if (conn->pghost != NULL && conn->pghost[0] != '\0')
1363         {
1364                 /* Using pghost, so we have to look-up the hostname */
1365                 node = conn->pghost;
1366                 hint.ai_family = AF_UNSPEC;
1367         }
1368         else
1369         {
1370 #ifdef HAVE_UNIX_SOCKETS
1371                 /* pghostaddr and pghost are NULL, so use Unix domain socket */
1372                 node = NULL;
1373                 hint.ai_family = AF_UNIX;
1374                 UNIXSOCK_PATH(portstr, portnum, conn->pgunixsocket);
1375                 if (strlen(portstr) >= UNIXSOCK_PATH_BUFLEN)
1376                 {
1377                         appendPQExpBuffer(&conn->errorMessage,
1378                                                           libpq_gettext("Unix-domain socket path \"%s\" is too long (maximum %d bytes)\n"),
1379                                                                                         portstr,
1380                                                                                         (int) (UNIXSOCK_PATH_BUFLEN - 1));
1381                         conn->options_valid = false;
1382                         goto connect_errReturn;
1383                 }
1384 #else
1385                 /* Without Unix sockets, default to localhost instead */
1386                 node = DefaultHost;
1387                 hint.ai_family = AF_UNSPEC;
1388 #endif   /* HAVE_UNIX_SOCKETS */
1389         }
1390
1391         /* Use pg_getaddrinfo_all() to resolve the address */
1392         ret = pg_getaddrinfo_all(node, portstr, &hint, &addrs);
1393         if (ret || !addrs)
1394         {
1395                 if (node)
1396                         appendPQExpBuffer(&conn->errorMessage,
1397                                                           libpq_gettext("could not translate host name \"%s\" to address: %s\n"),
1398                                                           node, gai_strerror(ret));
1399                 else
1400                         appendPQExpBuffer(&conn->errorMessage,
1401                                                           libpq_gettext("could not translate Unix-domain socket path \"%s\" to address: %s\n"),
1402                                                           portstr, gai_strerror(ret));
1403                 if (addrs)
1404                         pg_freeaddrinfo_all(hint.ai_family, addrs);
1405                 conn->options_valid = false;
1406                 goto connect_errReturn;
1407         }
1408
1409 #ifdef USE_SSL
1410         /* setup values based on SSL mode */
1411         if (conn->sslmode[0] == 'd')    /* "disable" */
1412                 conn->allow_ssl_try = false;
1413         else if (conn->sslmode[0] == 'a')       /* "allow" */
1414                 conn->wait_ssl_try = true;
1415 #endif
1416
1417         /*
1418          * Set up to try to connect, with protocol 3.0 as the first attempt.
1419          */
1420         conn->addrlist = addrs;
1421         conn->addr_cur = addrs;
1422         conn->addrlist_family = hint.ai_family;
1423         conn->pversion = PG_PROTOCOL(3, 0);
1424         conn->send_appname = true;
1425         conn->status = CONNECTION_NEEDED;
1426
1427         /*
1428          * The code for processing CONNECTION_NEEDED state is in PQconnectPoll(),
1429          * so that it can easily be re-executed if needed again during the
1430          * asynchronous startup process.  However, we must run it once here,
1431          * because callers expect a success return from this routine to mean that
1432          * we are in PGRES_POLLING_WRITING connection state.
1433          */
1434         if (PQconnectPoll(conn) == PGRES_POLLING_WRITING)
1435                 return 1;
1436
1437 connect_errReturn:
1438         pqDropConnection(conn);
1439         conn->status = CONNECTION_BAD;
1440         return 0;
1441 }
1442
1443
1444 /*
1445  *              connectDBComplete
1446  *
1447  * Block and complete a connection.
1448  *
1449  * Returns 1 on success, 0 on failure.
1450  */
1451 static int
1452 connectDBComplete(PGconn *conn)
1453 {
1454         PostgresPollingStatusType flag = PGRES_POLLING_WRITING;
1455         time_t          finish_time = ((time_t) -1);
1456
1457         if (conn == NULL || conn->status == CONNECTION_BAD)
1458                 return 0;
1459
1460         /*
1461          * Set up a time limit, if connect_timeout isn't zero.
1462          */
1463         if (conn->connect_timeout != NULL)
1464         {
1465                 int                     timeout = atoi(conn->connect_timeout);
1466
1467                 if (timeout > 0)
1468                 {
1469                         /*
1470                          * Rounding could cause connection to fail; need at least 2 secs
1471                          */
1472                         if (timeout < 2)
1473                                 timeout = 2;
1474                         /* calculate the finish time based on start + timeout */
1475                         finish_time = time(NULL) + timeout;
1476                 }
1477         }
1478
1479         for (;;)
1480         {
1481                 /*
1482                  * Wait, if necessary.  Note that the initial state (just after
1483                  * PQconnectStart) is to wait for the socket to select for writing.
1484                  */
1485                 switch (flag)
1486                 {
1487                         case PGRES_POLLING_OK:
1488
1489                                 /*
1490                                  * Reset stored error messages since we now have a working
1491                                  * connection
1492                                  */
1493                                 resetPQExpBuffer(&conn->errorMessage);
1494                                 return 1;               /* success! */
1495
1496                         case PGRES_POLLING_READING:
1497                                 if (pqWaitTimed(1, 0, conn, finish_time))
1498                                 {
1499                                         conn->status = CONNECTION_BAD;
1500                                         return 0;
1501                                 }
1502                                 break;
1503
1504                         case PGRES_POLLING_WRITING:
1505                                 if (pqWaitTimed(0, 1, conn, finish_time))
1506                                 {
1507                                         conn->status = CONNECTION_BAD;
1508                                         return 0;
1509                                 }
1510                                 break;
1511
1512                         default:
1513                                 /* Just in case we failed to set it in PQconnectPoll */
1514                                 conn->status = CONNECTION_BAD;
1515                                 return 0;
1516                 }
1517
1518                 /*
1519                  * Now try to advance the state machine.
1520                  */
1521                 flag = PQconnectPoll(conn);
1522         }
1523 }
1524
1525 /* ----------------
1526  *              PQconnectPoll
1527  *
1528  * Poll an asynchronous connection.
1529  *
1530  * Returns a PostgresPollingStatusType.
1531  * Before calling this function, use select(2) to determine when data
1532  * has arrived..
1533  *
1534  * You must call PQfinish whether or not this fails.
1535  *
1536  * This function and PQconnectStart are intended to allow connections to be
1537  * made without blocking the execution of your program on remote I/O. However,
1538  * there are a number of caveats:
1539  *
1540  *       o      If you call PQtrace, ensure that the stream object into which you trace
1541  *              will not block.
1542  *       o      If you do not supply an IP address for the remote host (i.e. you
1543  *              supply a host name instead) then PQconnectStart will block on
1544  *              gethostbyname.  You will be fine if using Unix sockets (i.e. by
1545  *              supplying neither a host name nor a host address).
1546  *       o      If your backend wants to use Kerberos authentication then you must
1547  *              supply both a host name and a host address, otherwise this function
1548  *              may block on gethostname.
1549  *
1550  * ----------------
1551  */
1552 PostgresPollingStatusType
1553 PQconnectPoll(PGconn *conn)
1554 {
1555         PGresult   *res;
1556         char            sebuf[256];
1557         int                     optval;
1558
1559         if (conn == NULL)
1560                 return PGRES_POLLING_FAILED;
1561
1562         /* Get the new data */
1563         switch (conn->status)
1564         {
1565                         /*
1566                          * We really shouldn't have been polled in these two cases, but we
1567                          * can handle it.
1568                          */
1569                 case CONNECTION_BAD:
1570                         return PGRES_POLLING_FAILED;
1571                 case CONNECTION_OK:
1572                         return PGRES_POLLING_OK;
1573
1574                         /* These are reading states */
1575                 case CONNECTION_AWAITING_RESPONSE:
1576                 case CONNECTION_AUTH_OK:
1577                         {
1578                                 /* Load waiting data */
1579                                 int                     n = pqReadData(conn);
1580
1581                                 if (n < 0)
1582                                         goto error_return;
1583                                 if (n == 0)
1584                                         return PGRES_POLLING_READING;
1585
1586                                 break;
1587                         }
1588
1589                         /* These are writing states, so we just proceed. */
1590                 case CONNECTION_STARTED:
1591                 case CONNECTION_MADE:
1592                         break;
1593
1594                         /* We allow pqSetenvPoll to decide whether to proceed. */
1595                 case CONNECTION_SETENV:
1596                         break;
1597
1598                         /* Special cases: proceed without waiting. */
1599                 case CONNECTION_SSL_STARTUP:
1600                 case CONNECTION_NEEDED:
1601                         break;
1602
1603                 default:
1604                         appendPQExpBuffer(&conn->errorMessage,
1605                                                           libpq_gettext(
1606                                                                                         "invalid connection state, "
1607                                                                  "probably indicative of memory corruption\n"
1608                                                                                         ));
1609                         goto error_return;
1610         }
1611
1612
1613 keep_going:                                             /* We will come back to here until there is
1614                                                                  * nothing left to do. */
1615         switch (conn->status)
1616         {
1617                 case CONNECTION_NEEDED:
1618                         {
1619                                 /*
1620                                  * Try to initiate a connection to one of the addresses
1621                                  * returned by pg_getaddrinfo_all().  conn->addr_cur is the
1622                                  * next one to try. We fail when we run out of addresses.
1623                                  */
1624                                 while (conn->addr_cur != NULL)
1625                                 {
1626                                         struct addrinfo *addr_cur = conn->addr_cur;
1627
1628                                         /* Remember current address for possible error msg */
1629                                         memcpy(&conn->raddr.addr, addr_cur->ai_addr,
1630                                                    addr_cur->ai_addrlen);
1631                                         conn->raddr.salen = addr_cur->ai_addrlen;
1632
1633                                         /* Open a socket */
1634                                         conn->sock = socket(addr_cur->ai_family, SOCK_STREAM, 0);
1635                                         if (conn->sock < 0)
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 non-blocking 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                                                         appendPQExpBuffer(&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                                                         SOCK_ERRNO == EWOULDBLOCK ||
1784                                                         SOCK_ERRNO == EINTR ||
1785                                                         SOCK_ERRNO == 0)
1786                                                 {
1787                                                         /*
1788                                                          * This is fine - we're in non-blocking mode, and
1789                                                          * the connection is in progress.  Tell caller to
1790                                                          * wait for write-ready on socket.
1791                                                          */
1792                                                         conn->status = CONNECTION_STARTED;
1793                                                         return PGRES_POLLING_WRITING;
1794                                                 }
1795                                                 /* otherwise, trouble */
1796                                         }
1797                                         else
1798                                         {
1799                                                 /*
1800                                                  * Hm, we're connected already --- seems the "nonblock
1801                                                  * connection" wasn't.  Advance the state machine and
1802                                                  * go do the next stuff.
1803                                                  */
1804                                                 conn->status = CONNECTION_STARTED;
1805                                                 goto keep_going;
1806                                         }
1807
1808                                         /*
1809                                          * This connection failed --- set up error report, then
1810                                          * close socket (do it this way in case close() affects
1811                                          * the value of errno...).      We will ignore the connect()
1812                                          * failure and keep going if there are more addresses.
1813                                          */
1814                                         connectFailureMessage(conn, SOCK_ERRNO);
1815                                         pqDropConnection(conn);
1816
1817                                         /*
1818                                          * Try the next address, if any.
1819                                          */
1820                                         conn->addr_cur = addr_cur->ai_next;
1821                                 }                               /* loop over addresses */
1822
1823                                 /*
1824                                  * Ooops, no more addresses.  An appropriate error message is
1825                                  * already set up, so just set the right status.
1826                                  */
1827                                 goto error_return;
1828                         }
1829
1830                 case CONNECTION_STARTED:
1831                         {
1832                                 ACCEPT_TYPE_ARG3 optlen = sizeof(optval);
1833
1834                                 /*
1835                                  * Write ready, since we've made it here, so the connection
1836                                  * has been made ... or has failed.
1837                                  */
1838
1839                                 /*
1840                                  * Now check (using getsockopt) that there is not an error
1841                                  * state waiting for us on the socket.
1842                                  */
1843
1844                                 if (getsockopt(conn->sock, SOL_SOCKET, SO_ERROR,
1845                                                            (char *) &optval, &optlen) == -1)
1846                                 {
1847                                         appendPQExpBuffer(&conn->errorMessage,
1848                                         libpq_gettext("could not get socket error status: %s\n"),
1849                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1850                                         goto error_return;
1851                                 }
1852                                 else if (optval != 0)
1853                                 {
1854                                         /*
1855                                          * When using a nonblocking connect, we will typically see
1856                                          * connect failures at this point, so provide a friendly
1857                                          * error message.
1858                                          */
1859                                         connectFailureMessage(conn, optval);
1860                                         pqDropConnection(conn);
1861
1862                                         /*
1863                                          * If more addresses remain, keep trying, just as in the
1864                                          * case where connect() returned failure immediately.
1865                                          */
1866                                         if (conn->addr_cur->ai_next != NULL)
1867                                         {
1868                                                 conn->addr_cur = conn->addr_cur->ai_next;
1869                                                 conn->status = CONNECTION_NEEDED;
1870                                                 goto keep_going;
1871                                         }
1872                                         goto error_return;
1873                                 }
1874
1875                                 /* Fill in the client address */
1876                                 conn->laddr.salen = sizeof(conn->laddr.addr);
1877                                 if (getsockname(conn->sock,
1878                                                                 (struct sockaddr *) & conn->laddr.addr,
1879                                                                 &conn->laddr.salen) < 0)
1880                                 {
1881                                         appendPQExpBuffer(&conn->errorMessage,
1882                                                                           libpq_gettext("could not get client address from socket: %s\n"),
1883                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1884                                         goto error_return;
1885                                 }
1886
1887                                 /*
1888                                  * Make sure we can write before advancing to next step.
1889                                  */
1890                                 conn->status = CONNECTION_MADE;
1891                                 return PGRES_POLLING_WRITING;
1892                         }
1893
1894                 case CONNECTION_MADE:
1895                         {
1896                                 char       *startpacket;
1897                                 int                     packetlen;
1898
1899 #ifdef HAVE_UNIX_SOCKETS
1900
1901                                 /*
1902                                  * Implement requirepeer check, if requested and it's a
1903                                  * Unix-domain socket.
1904                                  */
1905                                 if (conn->requirepeer && conn->requirepeer[0] &&
1906                                         IS_AF_UNIX(conn->raddr.addr.ss_family))
1907                                 {
1908                                         char            pwdbuf[BUFSIZ];
1909                                         struct passwd pass_buf;
1910                                         struct passwd *pass;
1911                                         uid_t           uid;
1912                                         gid_t           gid;
1913
1914                                         errno = 0;
1915                                         if (getpeereid(conn->sock, &uid, &gid) != 0)
1916                                         {
1917                                                 /*
1918                                                  * Provide special error message if getpeereid is a
1919                                                  * stub
1920                                                  */
1921                                                 if (errno == ENOSYS)
1922                                                         appendPQExpBuffer(&conn->errorMessage,
1923                                                                                           libpq_gettext("requirepeer parameter is not supported on this platform\n"));
1924                                                 else
1925                                                         appendPQExpBuffer(&conn->errorMessage,
1926                                                                                           libpq_gettext("could not get peer credentials: %s\n"),
1927                                                                         pqStrerror(errno, sebuf, sizeof(sebuf)));
1928                                                 goto error_return;
1929                                         }
1930
1931                                         pqGetpwuid(uid, &pass_buf, pwdbuf, sizeof(pwdbuf), &pass);
1932
1933                                         if (pass == NULL)
1934                                         {
1935                                                 appendPQExpBuffer(&conn->errorMessage,
1936                                                                                   libpq_gettext("local user with ID %d does not exist\n"),
1937                                                                                   (int) uid);
1938                                                 goto error_return;
1939                                         }
1940
1941                                         if (strcmp(pass->pw_name, conn->requirepeer) != 0)
1942                                         {
1943                                                 appendPQExpBuffer(&conn->errorMessage,
1944                                                                                   libpq_gettext("requirepeer specifies \"%s\", but actual peer user name is \"%s\"\n"),
1945                                                                                   conn->requirepeer, pass->pw_name);
1946                                                 goto error_return;
1947                                         }
1948                                 }
1949 #endif   /* HAVE_UNIX_SOCKETS */
1950
1951 #ifdef USE_SSL
1952
1953                                 /*
1954                                  * If SSL is enabled and we haven't already got it running,
1955                                  * request it instead of sending the startup message.
1956                                  */
1957                                 if (IS_AF_UNIX(conn->raddr.addr.ss_family))
1958                                 {
1959                                         /* Don't bother requesting SSL over a Unix socket */
1960                                         conn->allow_ssl_try = false;
1961                                 }
1962                                 if (conn->allow_ssl_try && !conn->wait_ssl_try &&
1963                                         conn->ssl == NULL)
1964                                 {
1965                                         ProtocolVersion pv;
1966
1967                                         /*
1968                                          * Send the SSL request packet.
1969                                          *
1970                                          * Theoretically, this could block, but it really
1971                                          * shouldn't since we only got here if the socket is
1972                                          * write-ready.
1973                                          */
1974                                         pv = htonl(NEGOTIATE_SSL_CODE);
1975                                         if (pqPacketSend(conn, 0, &pv, sizeof(pv)) != STATUS_OK)
1976                                         {
1977                                                 appendPQExpBuffer(&conn->errorMessage,
1978                                                                                   libpq_gettext("could not send SSL negotiation packet: %s\n"),
1979                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1980                                                 goto error_return;
1981                                         }
1982                                         /* Ok, wait for response */
1983                                         conn->status = CONNECTION_SSL_STARTUP;
1984                                         return PGRES_POLLING_READING;
1985                                 }
1986 #endif   /* USE_SSL */
1987
1988                                 /*
1989                                  * Build the startup packet.
1990                                  */
1991                                 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
1992                                         startpacket = pqBuildStartupPacket3(conn, &packetlen,
1993                                                                                                                 EnvironmentOptions);
1994                                 else
1995                                         startpacket = pqBuildStartupPacket2(conn, &packetlen,
1996                                                                                                                 EnvironmentOptions);
1997                                 if (!startpacket)
1998                                 {
1999                                         /*
2000                                          * will not appendbuffer here, since it's likely to also
2001                                          * run out of memory
2002                                          */
2003                                         printfPQExpBuffer(&conn->errorMessage,
2004                                                                           libpq_gettext("out of memory\n"));
2005                                         goto error_return;
2006                                 }
2007
2008                                 /*
2009                                  * Send the startup packet.
2010                                  *
2011                                  * Theoretically, this could block, but it really shouldn't
2012                                  * since we only got here if the socket is write-ready.
2013                                  */
2014                                 if (pqPacketSend(conn, 0, startpacket, packetlen) != STATUS_OK)
2015                                 {
2016                                         appendPQExpBuffer(&conn->errorMessage,
2017                                                 libpq_gettext("could not send startup packet: %s\n"),
2018                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
2019                                         free(startpacket);
2020                                         goto error_return;
2021                                 }
2022
2023                                 free(startpacket);
2024
2025                                 conn->status = CONNECTION_AWAITING_RESPONSE;
2026                                 return PGRES_POLLING_READING;
2027                         }
2028
2029                         /*
2030                          * Handle SSL negotiation: wait for postmaster messages and
2031                          * respond as necessary.
2032                          */
2033                 case CONNECTION_SSL_STARTUP:
2034                         {
2035 #ifdef USE_SSL
2036                                 PostgresPollingStatusType pollres;
2037
2038                                 /*
2039                                  * On first time through, get the postmaster's response to our
2040                                  * SSL negotiation packet.
2041                                  */
2042                                 if (conn->ssl == NULL)
2043                                 {
2044                                         /*
2045                                          * We use pqReadData here since it has the logic to
2046                                          * distinguish no-data-yet from connection closure. Since
2047                                          * conn->ssl isn't set, a plain recv() will occur.
2048                                          */
2049                                         char            SSLok;
2050                                         int                     rdresult;
2051
2052                                         rdresult = pqReadData(conn);
2053                                         if (rdresult < 0)
2054                                         {
2055                                                 /* errorMessage is already filled in */
2056                                                 goto error_return;
2057                                         }
2058                                         if (rdresult == 0)
2059                                         {
2060                                                 /* caller failed to wait for data */
2061                                                 return PGRES_POLLING_READING;
2062                                         }
2063                                         if (pqGetc(&SSLok, conn) < 0)
2064                                         {
2065                                                 /* should not happen really */
2066                                                 return PGRES_POLLING_READING;
2067                                         }
2068                                         if (SSLok == 'S')
2069                                         {
2070                                                 /* mark byte consumed */
2071                                                 conn->inStart = conn->inCursor;
2072                                                 /* Set up global SSL state if required */
2073                                                 if (pqsecure_initialize(conn) != 0)
2074                                                         goto error_return;
2075                                         }
2076                                         else if (SSLok == 'N')
2077                                         {
2078                                                 /* mark byte consumed */
2079                                                 conn->inStart = conn->inCursor;
2080                                                 /* OK to do without SSL? */
2081                                                 if (conn->sslmode[0] == 'r' ||  /* "require" */
2082                                                         conn->sslmode[0] == 'v')        /* "verify-ca" or
2083                                                                                                                  * "verify-full" */
2084                                                 {
2085                                                         /* Require SSL, but server does not want it */
2086                                                         appendPQExpBuffer(&conn->errorMessage,
2087                                                                                           libpq_gettext("server does not support SSL, but SSL was required\n"));
2088                                                         goto error_return;
2089                                                 }
2090                                                 /* Otherwise, proceed with normal startup */
2091                                                 conn->allow_ssl_try = false;
2092                                                 conn->status = CONNECTION_MADE;
2093                                                 return PGRES_POLLING_WRITING;
2094                                         }
2095                                         else if (SSLok == 'E')
2096                                         {
2097                                                 /*
2098                                                  * Server failure of some sort, such as failure to
2099                                                  * fork a backend process.      We need to process and
2100                                                  * report the error message, which might be formatted
2101                                                  * according to either protocol 2 or protocol 3.
2102                                                  * Rather than duplicate the code for that, we flip
2103                                                  * into AWAITING_RESPONSE state and let the code there
2104                                                  * deal with it.  Note we have *not* consumed the "E"
2105                                                  * byte here.
2106                                                  */
2107                                                 conn->status = CONNECTION_AWAITING_RESPONSE;
2108                                                 goto keep_going;
2109                                         }
2110                                         else
2111                                         {
2112                                                 appendPQExpBuffer(&conn->errorMessage,
2113                                                                                   libpq_gettext("received invalid response to SSL negotiation: %c\n"),
2114                                                                                   SSLok);
2115                                                 goto error_return;
2116                                         }
2117                                 }
2118
2119                                 /*
2120                                  * Begin or continue the SSL negotiation process.
2121                                  */
2122                                 pollres = pqsecure_open_client(conn);
2123                                 if (pollres == PGRES_POLLING_OK)
2124                                 {
2125                                         /* SSL handshake done, ready to send startup packet */
2126                                         conn->status = CONNECTION_MADE;
2127                                         return PGRES_POLLING_WRITING;
2128                                 }
2129                                 if (pollres == PGRES_POLLING_FAILED)
2130                                 {
2131                                         /*
2132                                          * Failed ... if sslmode is "prefer" then do a non-SSL
2133                                          * retry
2134                                          */
2135                                         if (conn->sslmode[0] == 'p' /* "prefer" */
2136                                                 && conn->allow_ssl_try  /* redundant? */
2137                                                 && !conn->wait_ssl_try) /* redundant? */
2138                                         {
2139                                                 /* only retry once */
2140                                                 conn->allow_ssl_try = false;
2141                                                 /* Must drop the old connection */
2142                                                 pqDropConnection(conn);
2143                                                 conn->status = CONNECTION_NEEDED;
2144                                                 goto keep_going;
2145                                         }
2146                                 }
2147                                 return pollres;
2148 #else                                                   /* !USE_SSL */
2149                                 /* can't get here */
2150                                 goto error_return;
2151 #endif   /* USE_SSL */
2152                         }
2153
2154                         /*
2155                          * Handle authentication exchange: wait for postmaster messages
2156                          * and respond as necessary.
2157                          */
2158                 case CONNECTION_AWAITING_RESPONSE:
2159                         {
2160                                 char            beresp;
2161                                 int                     msgLength;
2162                                 int                     avail;
2163                                 AuthRequest areq;
2164
2165                                 /*
2166                                  * Scan the message from current point (note that if we find
2167                                  * the message is incomplete, we will return without advancing
2168                                  * inStart, and resume here next time).
2169                                  */
2170                                 conn->inCursor = conn->inStart;
2171
2172                                 /* Read type byte */
2173                                 if (pqGetc(&beresp, conn))
2174                                 {
2175                                         /* We'll come back when there is more data */
2176                                         return PGRES_POLLING_READING;
2177                                 }
2178
2179                                 /*
2180                                  * Validate message type: we expect only an authentication
2181                                  * request or an error here.  Anything else probably means
2182                                  * it's not Postgres on the other end at all.
2183                                  */
2184                                 if (!(beresp == 'R' || beresp == 'E'))
2185                                 {
2186                                         appendPQExpBuffer(&conn->errorMessage,
2187                                                                           libpq_gettext(
2188                                                                           "expected authentication request from "
2189                                                                                                 "server, but received %c\n"),
2190                                                                           beresp);
2191                                         goto error_return;
2192                                 }
2193
2194                                 if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2195                                 {
2196                                         /* Read message length word */
2197                                         if (pqGetInt(&msgLength, 4, conn))
2198                                         {
2199                                                 /* We'll come back when there is more data */
2200                                                 return PGRES_POLLING_READING;
2201                                         }
2202                                 }
2203                                 else
2204                                 {
2205                                         /* Set phony message length to disable checks below */
2206                                         msgLength = 8;
2207                                 }
2208
2209                                 /*
2210                                  * Try to validate message length before using it.
2211                                  * Authentication requests can't be very large, although GSS
2212                                  * auth requests may not be that small.  Errors can be a
2213                                  * little larger, but not huge.  If we see a large apparent
2214                                  * length in an error, it means we're really talking to a
2215                                  * pre-3.0-protocol server; cope.
2216                                  */
2217                                 if (beresp == 'R' && (msgLength < 8 || msgLength > 2000))
2218                                 {
2219                                         appendPQExpBuffer(&conn->errorMessage,
2220                                                                           libpq_gettext(
2221                                                                           "expected authentication request from "
2222                                                                                                 "server, but received %c\n"),
2223                                                                           beresp);
2224                                         goto error_return;
2225                                 }
2226
2227                                 if (beresp == 'E' && (msgLength < 8 || msgLength > 30000))
2228                                 {
2229                                         /* Handle error from a pre-3.0 server */
2230                                         conn->inCursor = conn->inStart + 1; /* reread data */
2231                                         if (pqGets_append(&conn->errorMessage, conn))
2232                                         {
2233                                                 /* We'll come back when there is more data */
2234                                                 return PGRES_POLLING_READING;
2235                                         }
2236                                         /* OK, we read the message; mark data consumed */
2237                                         conn->inStart = conn->inCursor;
2238
2239                                         /*
2240                                          * The postmaster typically won't end its message with a
2241                                          * newline, so add one to conform to libpq conventions.
2242                                          */
2243                                         appendPQExpBufferChar(&conn->errorMessage, '\n');
2244
2245                                         /*
2246                                          * If we tried to open the connection in 3.0 protocol,
2247                                          * fall back to 2.0 protocol.
2248                                          */
2249                                         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2250                                         {
2251                                                 conn->pversion = PG_PROTOCOL(2, 0);
2252                                                 /* Must drop the old connection */
2253                                                 pqDropConnection(conn);
2254                                                 conn->status = CONNECTION_NEEDED;
2255                                                 goto keep_going;
2256                                         }
2257
2258                                         goto error_return;
2259                                 }
2260
2261                                 /*
2262                                  * Can't process if message body isn't all here yet.
2263                                  *
2264                                  * (In protocol 2.0 case, we are assuming messages carry at
2265                                  * least 4 bytes of data.)
2266                                  */
2267                                 msgLength -= 4;
2268                                 avail = conn->inEnd - conn->inCursor;
2269                                 if (avail < msgLength)
2270                                 {
2271                                         /*
2272                                          * Before returning, try to enlarge the input buffer if
2273                                          * needed to hold the whole message; see notes in
2274                                          * pqParseInput3.
2275                                          */
2276                                         if (pqCheckInBufferSpace(conn->inCursor + (size_t) msgLength,
2277                                                                                          conn))
2278                                                 goto error_return;
2279                                         /* We'll come back when there is more data */
2280                                         return PGRES_POLLING_READING;
2281                                 }
2282
2283                                 /* Handle errors. */
2284                                 if (beresp == 'E')
2285                                 {
2286                                         if (PG_PROTOCOL_MAJOR(conn->pversion) >= 3)
2287                                         {
2288                                                 if (pqGetErrorNotice3(conn, true))
2289                                                 {
2290                                                         /* We'll come back when there is more data */
2291                                                         return PGRES_POLLING_READING;
2292                                                 }
2293                                         }
2294                                         else
2295                                         {
2296                                                 if (pqGets_append(&conn->errorMessage, conn))
2297                                                 {
2298                                                         /* We'll come back when there is more data */
2299                                                         return PGRES_POLLING_READING;
2300                                                 }
2301                                         }
2302                                         /* OK, we read the message; mark data consumed */
2303                                         conn->inStart = conn->inCursor;
2304
2305 #ifdef USE_SSL
2306
2307                                         /*
2308                                          * if sslmode is "allow" and we haven't tried an SSL
2309                                          * connection already, then retry with an SSL connection
2310                                          */
2311                                         if (conn->sslmode[0] == 'a' /* "allow" */
2312                                                 && conn->ssl == NULL
2313                                                 && conn->allow_ssl_try
2314                                                 && conn->wait_ssl_try)
2315                                         {
2316                                                 /* only retry once */
2317                                                 conn->wait_ssl_try = false;
2318                                                 /* Must drop the old connection */
2319                                                 pqDropConnection(conn);
2320                                                 conn->status = CONNECTION_NEEDED;
2321                                                 goto keep_going;
2322                                         }
2323
2324                                         /*
2325                                          * if sslmode is "prefer" and we're in an SSL connection,
2326                                          * then do a non-SSL retry
2327                                          */
2328                                         if (conn->sslmode[0] == 'p' /* "prefer" */
2329                                                 && conn->allow_ssl_try
2330                                                 && !conn->wait_ssl_try) /* redundant? */
2331                                         {
2332                                                 /* only retry once */
2333                                                 conn->allow_ssl_try = false;
2334                                                 /* Must drop the old connection */
2335                                                 pqDropConnection(conn);
2336                                                 conn->status = CONNECTION_NEEDED;
2337                                                 goto keep_going;
2338                                         }
2339 #endif
2340
2341                                         goto error_return;
2342                                 }
2343
2344                                 /* It is an authentication request. */
2345                                 conn->auth_req_received = true;
2346
2347                                 /* Get the type of request. */
2348                                 if (pqGetInt((int *) &areq, 4, conn))
2349                                 {
2350                                         /* We'll come back when there are more data */
2351                                         return PGRES_POLLING_READING;
2352                                 }
2353
2354                                 /* Get the password salt if there is one. */
2355                                 if (areq == AUTH_REQ_MD5)
2356                                 {
2357                                         if (pqGetnchar(conn->md5Salt,
2358                                                                    sizeof(conn->md5Salt), conn))
2359                                         {
2360                                                 /* We'll come back when there are more data */
2361                                                 return PGRES_POLLING_READING;
2362                                         }
2363                                 }
2364 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
2365
2366                                 /*
2367                                  * Continue GSSAPI/SSPI authentication
2368                                  */
2369                                 if (areq == AUTH_REQ_GSS_CONT)
2370                                 {
2371                                         int                     llen = msgLength - 4;
2372
2373                                         /*
2374                                          * We can be called repeatedly for the same buffer. Avoid
2375                                          * re-allocating the buffer in this case - just re-use the
2376                                          * old buffer.
2377                                          */
2378                                         if (llen != conn->ginbuf.length)
2379                                         {
2380                                                 if (conn->ginbuf.value)
2381                                                         free(conn->ginbuf.value);
2382
2383                                                 conn->ginbuf.length = llen;
2384                                                 conn->ginbuf.value = malloc(llen);
2385                                                 if (!conn->ginbuf.value)
2386                                                 {
2387                                                         printfPQExpBuffer(&conn->errorMessage,
2388                                                                                           libpq_gettext("out of memory allocating GSSAPI buffer (%d)"),
2389                                                                                           llen);
2390                                                         goto error_return;
2391                                                 }
2392                                         }
2393
2394                                         if (pqGetnchar(conn->ginbuf.value, llen, conn))
2395                                         {
2396                                                 /* We'll come back when there is more data. */
2397                                                 return PGRES_POLLING_READING;
2398                                         }
2399                                 }
2400 #endif
2401
2402                                 /*
2403                                  * OK, we successfully read the message; mark data consumed
2404                                  */
2405                                 conn->inStart = conn->inCursor;
2406
2407                                 /* Respond to the request if necessary. */
2408
2409                                 /*
2410                                  * Note that conn->pghost must be non-NULL if we are going to
2411                                  * avoid the Kerberos code doing a hostname look-up.
2412                                  */
2413
2414                                 if (pg_fe_sendauth(areq, conn) != STATUS_OK)
2415                                 {
2416                                         conn->errorMessage.len = strlen(conn->errorMessage.data);
2417                                         goto error_return;
2418                                 }
2419                                 conn->errorMessage.len = strlen(conn->errorMessage.data);
2420
2421                                 /*
2422                                  * Just make sure that any data sent by pg_fe_sendauth is
2423                                  * flushed out.  Although this theoretically could block, it
2424                                  * really shouldn't since we don't send large auth responses.
2425                                  */
2426                                 if (pqFlush(conn))
2427                                         goto error_return;
2428
2429                                 if (areq == AUTH_REQ_OK)
2430                                 {
2431                                         /* We are done with authentication exchange */
2432                                         conn->status = CONNECTION_AUTH_OK;
2433
2434                                         /*
2435                                          * Set asyncStatus so that PQgetResult will think that
2436                                          * what comes back next is the result of a query.  See
2437                                          * below.
2438                                          */
2439                                         conn->asyncStatus = PGASYNC_BUSY;
2440                                 }
2441
2442                                 /* Look to see if we have more data yet. */
2443                                 goto keep_going;
2444                         }
2445
2446                 case CONNECTION_AUTH_OK:
2447                         {
2448                                 /*
2449                                  * Now we expect to hear from the backend. A ReadyForQuery
2450                                  * message indicates that startup is successful, but we might
2451                                  * also get an Error message indicating failure. (Notice
2452                                  * messages indicating nonfatal warnings are also allowed by
2453                                  * the protocol, as are ParameterStatus and BackendKeyData
2454                                  * messages.) Easiest way to handle this is to let
2455                                  * PQgetResult() read the messages. We just have to fake it
2456                                  * out about the state of the connection, by setting
2457                                  * asyncStatus = PGASYNC_BUSY (done above).
2458                                  */
2459
2460                                 if (PQisBusy(conn))
2461                                         return PGRES_POLLING_READING;
2462
2463                                 res = PQgetResult(conn);
2464
2465                                 /*
2466                                  * NULL return indicating we have gone to IDLE state is
2467                                  * expected
2468                                  */
2469                                 if (res)
2470                                 {
2471                                         if (res->resultStatus != PGRES_FATAL_ERROR)
2472                                                 appendPQExpBuffer(&conn->errorMessage,
2473                                                                                   libpq_gettext("unexpected message from server during startup\n"));
2474                                         else if (conn->send_appname &&
2475                                                          (conn->appname || conn->fbappname))
2476                                         {
2477                                                 /*
2478                                                  * If we tried to send application_name, check to see
2479                                                  * if the error is about that --- pre-9.0 servers will
2480                                                  * reject it at this stage of the process.      If so,
2481                                                  * close the connection and retry without sending
2482                                                  * application_name.  We could possibly get a false
2483                                                  * SQLSTATE match here and retry uselessly, but there
2484                                                  * seems no great harm in that; we'll just get the
2485                                                  * same error again if it's unrelated.
2486                                                  */
2487                                                 const char *sqlstate;
2488
2489                                                 sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2490                                                 if (sqlstate &&
2491                                                         strcmp(sqlstate, ERRCODE_APPNAME_UNKNOWN) == 0)
2492                                                 {
2493                                                         PQclear(res);
2494                                                         conn->send_appname = false;
2495                                                         /* Must drop the old connection */
2496                                                         pqDropConnection(conn);
2497                                                         conn->status = CONNECTION_NEEDED;
2498                                                         goto keep_going;
2499                                                 }
2500                                         }
2501
2502                                         /*
2503                                          * if the resultStatus is FATAL, then conn->errorMessage
2504                                          * already has a copy of the error; needn't copy it back.
2505                                          * But add a newline if it's not there already, since
2506                                          * postmaster error messages may not have one.
2507                                          */
2508                                         if (conn->errorMessage.len <= 0 ||
2509                                                 conn->errorMessage.data[conn->errorMessage.len - 1] != '\n')
2510                                                 appendPQExpBufferChar(&conn->errorMessage, '\n');
2511                                         PQclear(res);
2512                                         goto error_return;
2513                                 }
2514
2515                                 /* We can release the address list now. */
2516                                 pg_freeaddrinfo_all(conn->addrlist_family, conn->addrlist);
2517                                 conn->addrlist = NULL;
2518                                 conn->addr_cur = NULL;
2519
2520                                 /* Fire up post-connection housekeeping if needed */
2521                                 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
2522                                 {
2523                                         conn->status = CONNECTION_SETENV;
2524                                         conn->setenv_state = SETENV_STATE_CLIENT_ENCODING_SEND;
2525                                         conn->next_eo = EnvironmentOptions;
2526                                         return PGRES_POLLING_WRITING;
2527                                 }
2528
2529                                 /* Otherwise, we are open for business! */
2530                                 conn->status = CONNECTION_OK;
2531                                 return PGRES_POLLING_OK;
2532                         }
2533
2534                 case CONNECTION_SETENV:
2535
2536                         /*
2537                          * Do post-connection housekeeping (only needed in protocol 2.0).
2538                          *
2539                          * We pretend that the connection is OK for the duration of these
2540                          * queries.
2541                          */
2542                         conn->status = CONNECTION_OK;
2543
2544                         switch (pqSetenvPoll(conn))
2545                         {
2546                                 case PGRES_POLLING_OK:  /* Success */
2547                                         break;
2548
2549                                 case PGRES_POLLING_READING:             /* Still going */
2550                                         conn->status = CONNECTION_SETENV;
2551                                         return PGRES_POLLING_READING;
2552
2553                                 case PGRES_POLLING_WRITING:             /* Still going */
2554                                         conn->status = CONNECTION_SETENV;
2555                                         return PGRES_POLLING_WRITING;
2556
2557                                 default:
2558                                         goto error_return;
2559                         }
2560
2561                         /* We are open for business! */
2562                         conn->status = CONNECTION_OK;
2563                         return PGRES_POLLING_OK;
2564
2565                 default:
2566                         appendPQExpBuffer(&conn->errorMessage,
2567                                                           libpq_gettext("invalid connection state %d, "
2568                                                            "probably indicative of memory corruption\n"),
2569                                                           conn->status);
2570                         goto error_return;
2571         }
2572
2573         /* Unreachable */
2574
2575 error_return:
2576
2577         dot_pg_pass_warning(conn);
2578
2579         /*
2580          * We used to close the socket at this point, but that makes it awkward
2581          * for those above us if they wish to remove this socket from their own
2582          * records (an fd_set for example).  We'll just have this socket closed
2583          * when PQfinish is called (which is compulsory even after an error, since
2584          * the connection structure must be freed).
2585          */
2586         conn->status = CONNECTION_BAD;
2587         return PGRES_POLLING_FAILED;
2588 }
2589
2590
2591 /*
2592  * internal_ping
2593  *              Determine if a server is running and if we can connect to it.
2594  *
2595  * The argument is a connection that's been started, but not completed.
2596  */
2597 static PGPing
2598 internal_ping(PGconn *conn)
2599 {
2600         /* Say "no attempt" if we never got to PQconnectPoll */
2601         if (!conn || !conn->options_valid)
2602                 return PQPING_NO_ATTEMPT;
2603
2604         /* Attempt to complete the connection */
2605         if (conn->status != CONNECTION_BAD)
2606                 (void) connectDBComplete(conn);
2607
2608         /* Definitely OK if we succeeded */
2609         if (conn->status != CONNECTION_BAD)
2610                 return PQPING_OK;
2611
2612         /*
2613          * Here begins the interesting part of "ping": determine the cause of the
2614          * failure in sufficient detail to decide what to return.  We do not want
2615          * to report that the server is not up just because we didn't have a valid
2616          * password, for example.  In fact, any sort of authentication request
2617          * implies the server is up.  (We need this check since the libpq side of
2618          * things might have pulled the plug on the connection before getting an
2619          * error as such from the postmaster.)
2620          */
2621         if (conn->auth_req_received)
2622                 return PQPING_OK;
2623
2624         /*
2625          * If we failed to get any ERROR response from the postmaster, report
2626          * PQPING_NO_RESPONSE.  This result could be somewhat misleading for a
2627          * pre-7.4 server, since it won't send back a SQLSTATE, but those are long
2628          * out of support.      Another corner case where the server could return a
2629          * failure without a SQLSTATE is fork failure, but NO_RESPONSE isn't
2630          * totally unreasonable for that anyway.  We expect that every other
2631          * failure case in a modern server will produce a report with a SQLSTATE.
2632          *
2633          * NOTE: whenever we get around to making libpq generate SQLSTATEs for
2634          * client-side errors, we should either not store those into
2635          * last_sqlstate, or add an extra flag so we can tell client-side errors
2636          * apart from server-side ones.
2637          */
2638         if (strlen(conn->last_sqlstate) != 5)
2639                 return PQPING_NO_RESPONSE;
2640
2641         /*
2642          * Report PQPING_REJECT if server says it's not accepting connections. (We
2643          * distinguish this case mainly for the convenience of pg_ctl.)
2644          */
2645         if (strcmp(conn->last_sqlstate, ERRCODE_CANNOT_CONNECT_NOW) == 0)
2646                 return PQPING_REJECT;
2647
2648         /*
2649          * Any other SQLSTATE can be taken to indicate that the server is up.
2650          * Presumably it didn't like our username, password, or database name; or
2651          * perhaps it had some transient failure, but that should not be taken as
2652          * meaning "it's down".
2653          */
2654         return PQPING_OK;
2655 }
2656
2657
2658 /*
2659  * makeEmptyPGconn
2660  *       - create a PGconn data structure with (as yet) no interesting data
2661  */
2662 static PGconn *
2663 makeEmptyPGconn(void)
2664 {
2665         PGconn     *conn;
2666
2667 #ifdef WIN32
2668
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 = -1;
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(KRB5) || 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 >= 0 && 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                 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 < 0)
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         int                     tmpsock = -1;
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)) < 0)
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 >= 0)
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 < 0)
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                                 msgid,
3366                                 size,
3367                                 state,
3368                                 oldstate,
3369                                 i;
3370         bool            found_keyword;
3371         char       *url,
3372                            *hostname,
3373                            *portstr,
3374                            *endptr,
3375                            *dn,
3376                            *scopestr,
3377                            *filter,
3378                            *result,
3379                            *p,
3380                            *p1 = NULL,
3381                            *optname = NULL,
3382                            *optval = NULL;
3383         char       *attrs[2] = {NULL, NULL};
3384         LDAP       *ld = NULL;
3385         LDAPMessage *res,
3386                            *entry;
3387         struct berval **values;
3388         LDAP_TIMEVAL time = {PGLDAP_TIMEOUT, 0};
3389
3390         if ((url = strdup(purl)) == NULL)
3391         {
3392                 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
3393                 return 3;
3394         }
3395
3396         /*
3397          * Parse URL components, check for correctness.  Basically, url has '\0'
3398          * placed at component boundaries and variables are pointed at each
3399          * component.
3400          */
3401
3402         if (pg_strncasecmp(url, LDAP_URL, strlen(LDAP_URL)) != 0)
3403         {
3404                 printfPQExpBuffer(errorMessage,
3405                                                   libpq_gettext("invalid LDAP URL \"%s\": scheme must be ldap://\n"), purl);
3406                 free(url);
3407                 return 3;
3408         }
3409
3410         /* hostname */
3411         hostname = url + strlen(LDAP_URL);
3412         if (*hostname == '/')           /* no hostname? */
3413                 hostname = DefaultHost; /* the default */
3414
3415         /* dn, "distinguished name" */
3416         p = strchr(url + strlen(LDAP_URL), '/');
3417         if (p == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3418         {
3419                 printfPQExpBuffer(errorMessage, libpq_gettext(
3420                          "invalid LDAP URL \"%s\": missing distinguished name\n"), purl);
3421                 free(url);
3422                 return 3;
3423         }
3424         *p = '\0';                                      /* terminate hostname */
3425         dn = p + 1;
3426
3427         /* attribute */
3428         if ((p = strchr(dn, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3429         {
3430                 printfPQExpBuffer(errorMessage, libpq_gettext(
3431                 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
3432                 free(url);
3433                 return 3;
3434         }
3435         *p = '\0';
3436         attrs[0] = p + 1;
3437
3438         /* scope */
3439         if ((p = strchr(attrs[0], '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3440         {
3441                 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
3442                 free(url);
3443                 return 3;
3444         }
3445         *p = '\0';
3446         scopestr = p + 1;
3447
3448         /* filter */
3449         if ((p = strchr(scopestr, '?')) == NULL || *(p + 1) == '\0' || *(p + 1) == '?')
3450         {
3451                 printfPQExpBuffer(errorMessage,
3452                                 libpq_gettext("invalid LDAP URL \"%s\": no filter\n"), purl);
3453                 free(url);
3454                 return 3;
3455         }
3456         *p = '\0';
3457         filter = p + 1;
3458         if ((p = strchr(filter, '?')) != NULL)
3459                 *p = '\0';
3460
3461         /* port number? */
3462         if ((p1 = strchr(hostname, ':')) != NULL)
3463         {
3464                 long            lport;
3465
3466                 *p1 = '\0';
3467                 portstr = p1 + 1;
3468                 errno = 0;
3469                 lport = strtol(portstr, &endptr, 10);
3470                 if (*portstr == '\0' || *endptr != '\0' || errno || lport < 0 || lport > 65535)
3471                 {
3472                         printfPQExpBuffer(errorMessage, libpq_gettext(
3473                                         "invalid LDAP URL \"%s\": invalid port number\n"), purl);
3474                         free(url);
3475                         return 3;
3476                 }
3477                 port = (int) lport;
3478         }
3479
3480         /* Allow only one attribute */
3481         if (strchr(attrs[0], ',') != NULL)
3482         {
3483                 printfPQExpBuffer(errorMessage, libpq_gettext(
3484                 "invalid LDAP URL \"%s\": must have exactly one attribute\n"), purl);
3485                 free(url);
3486                 return 3;
3487         }
3488
3489         /* set scope */
3490         if (pg_strcasecmp(scopestr, "base") == 0)
3491                 scope = LDAP_SCOPE_BASE;
3492         else if (pg_strcasecmp(scopestr, "one") == 0)
3493                 scope = LDAP_SCOPE_ONELEVEL;
3494         else if (pg_strcasecmp(scopestr, "sub") == 0)
3495                 scope = LDAP_SCOPE_SUBTREE;
3496         else
3497         {
3498                 printfPQExpBuffer(errorMessage, libpq_gettext("invalid LDAP URL \"%s\": must have search scope (base/one/sub)\n"), purl);
3499                 free(url);
3500                 return 3;
3501         }
3502
3503         /* initialize LDAP structure */
3504         if ((ld = ldap_init(hostname, port)) == NULL)
3505         {
3506                 printfPQExpBuffer(errorMessage,
3507                                                   libpq_gettext("could not create LDAP structure\n"));
3508                 free(url);
3509                 return 3;
3510         }
3511
3512         /*
3513          * Initialize connection to the server.  We do an explicit bind because we
3514          * want to return 2 if the bind fails.
3515          */
3516         if ((msgid = ldap_simple_bind(ld, NULL, NULL)) == -1)
3517         {
3518                 /* error in ldap_simple_bind() */
3519                 free(url);
3520                 ldap_unbind(ld);
3521                 return 2;
3522         }
3523
3524         /* wait some time for the connection to succeed */
3525         res = NULL;
3526         if ((rc = ldap_result(ld, msgid, LDAP_MSG_ALL, &time, &res)) == -1 ||
3527                 res == NULL)
3528         {
3529                 if (res != NULL)
3530                 {
3531                         /* timeout */
3532                         ldap_msgfree(res);
3533                 }
3534                 /* error in ldap_result() */
3535                 free(url);
3536                 ldap_unbind(ld);
3537                 return 2;
3538         }
3539         ldap_msgfree(res);
3540
3541         /* search */
3542         res = NULL;
3543         if ((rc = ldap_search_st(ld, dn, scope, filter, attrs, 0, &time, &res))
3544                 != LDAP_SUCCESS)
3545         {
3546                 if (res != NULL)
3547                         ldap_msgfree(res);
3548                 printfPQExpBuffer(errorMessage,
3549                                                   libpq_gettext("lookup on LDAP server failed: %s\n"),
3550                                                   ldap_err2string(rc));
3551                 ldap_unbind(ld);
3552                 free(url);
3553                 return 1;
3554         }
3555
3556         /* complain if there was not exactly one result */
3557         if ((rc = ldap_count_entries(ld, res)) != 1)
3558         {
3559                 printfPQExpBuffer(errorMessage,
3560                          rc ? libpq_gettext("more than one entry found on LDAP lookup\n")
3561                                                   : libpq_gettext("no entry found on LDAP lookup\n"));
3562                 ldap_msgfree(res);
3563                 ldap_unbind(ld);
3564                 free(url);
3565                 return 1;
3566         }
3567
3568         /* get entry */
3569         if ((entry = ldap_first_entry(ld, res)) == NULL)
3570         {
3571                 /* should never happen */
3572                 printfPQExpBuffer(errorMessage,
3573                                                   libpq_gettext("no entry found on LDAP lookup\n"));
3574                 ldap_msgfree(res);
3575                 ldap_unbind(ld);
3576                 free(url);
3577                 return 1;
3578         }
3579
3580         /* get values */
3581         if ((values = ldap_get_values_len(ld, entry, attrs[0])) == NULL)
3582         {
3583                 printfPQExpBuffer(errorMessage,
3584                                   libpq_gettext("attribute has no values on LDAP lookup\n"));
3585                 ldap_msgfree(res);
3586                 ldap_unbind(ld);
3587                 free(url);
3588                 return 1;
3589         }
3590
3591         ldap_msgfree(res);
3592         free(url);
3593
3594         if (values[0] == NULL)
3595         {
3596                 printfPQExpBuffer(errorMessage,
3597                                   libpq_gettext("attribute has no values on LDAP lookup\n"));
3598                 ldap_value_free_len(values);
3599                 ldap_unbind(ld);
3600                 return 1;
3601         }
3602
3603         /* concatenate values into a single string with newline terminators */
3604         size = 1;                                       /* for the trailing null */
3605         for (i = 0; values[i] != NULL; i++)
3606                 size += values[i]->bv_len + 1;
3607         if ((result = malloc(size)) == NULL)
3608         {
3609                 printfPQExpBuffer(errorMessage,
3610                                                   libpq_gettext("out of memory\n"));
3611                 ldap_value_free_len(values);
3612                 ldap_unbind(ld);
3613                 return 3;
3614         }
3615         p = result;
3616         for (i = 0; values[i] != NULL; i++)
3617         {
3618                 memcpy(p, values[i]->bv_val, values[i]->bv_len);
3619                 p += values[i]->bv_len;
3620                 *(p++) = '\n';
3621         }
3622         *p = '\0';
3623
3624         ldap_value_free_len(values);
3625         ldap_unbind(ld);
3626
3627         /* parse result string */
3628         oldstate = state = 0;
3629         for (p = result; *p != '\0'; ++p)
3630         {
3631                 switch (state)
3632                 {
3633                         case 0:                         /* between entries */
3634                                 if (!ld_is_sp_tab(*p) && !ld_is_nl_cr(*p))
3635                                 {
3636                                         optname = p;
3637                                         state = 1;
3638                                 }
3639                                 break;
3640                         case 1:                         /* in option name */
3641                                 if (ld_is_sp_tab(*p))
3642                                 {
3643                                         *p = '\0';
3644                                         state = 2;
3645                                 }
3646                                 else if (ld_is_nl_cr(*p))
3647                                 {
3648                                         printfPQExpBuffer(errorMessage, libpq_gettext(
3649                                         "missing \"=\" after \"%s\" in connection info string\n"),
3650                                                                           optname);
3651                                         free(result);
3652                                         return 3;
3653                                 }
3654                                 else if (*p == '=')
3655                                 {
3656                                         *p = '\0';
3657                                         state = 3;
3658                                 }
3659                                 break;
3660                         case 2:                         /* after option name */
3661                                 if (*p == '=')
3662                                 {
3663                                         state = 3;
3664                                 }
3665                                 else if (!ld_is_sp_tab(*p))
3666                                 {
3667                                         printfPQExpBuffer(errorMessage, libpq_gettext(
3668                                         "missing \"=\" after \"%s\" in connection info string\n"),
3669                                                                           optname);
3670                                         free(result);
3671                                         return 3;
3672                                 }
3673                                 break;
3674                         case 3:                         /* before option value */
3675                                 if (*p == '\'')
3676                                 {
3677                                         optval = p + 1;
3678                                         p1 = p + 1;
3679                                         state = 5;
3680                                 }
3681                                 else if (ld_is_nl_cr(*p))
3682                                 {
3683                                         optval = optname + strlen(optname); /* empty */
3684                                         state = 0;
3685                                 }
3686                                 else if (!ld_is_sp_tab(*p))
3687                                 {
3688                                         optval = p;
3689                                         state = 4;
3690                                 }
3691                                 break;
3692                         case 4:                         /* in unquoted option value */
3693                                 if (ld_is_sp_tab(*p) || ld_is_nl_cr(*p))
3694                                 {
3695                                         *p = '\0';
3696                                         state = 0;
3697                                 }
3698                                 break;
3699                         case 5:                         /* in quoted option value */
3700                                 if (*p == '\'')
3701                                 {
3702                                         *p1 = '\0';
3703                                         state = 0;
3704                                 }
3705                                 else if (*p == '\\')
3706                                         state = 6;
3707                                 else
3708                                         *(p1++) = *p;
3709                                 break;
3710                         case 6:                         /* in quoted option value after escape */
3711                                 *(p1++) = *p;
3712                                 state = 5;
3713                                 break;
3714                 }
3715
3716                 if (state == 0 && oldstate != 0)
3717                 {
3718                         found_keyword = false;
3719                         for (i = 0; options[i].keyword; i++)
3720                         {
3721                                 if (strcmp(options[i].keyword, optname) == 0)
3722                                 {
3723                                         if (options[i].val == NULL)
3724                                                 options[i].val = strdup(optval);
3725                                         found_keyword = true;
3726                                         break;
3727                                 }
3728                         }
3729                         if (!found_keyword)
3730                         {
3731                                 printfPQExpBuffer(errorMessage,
3732                                                  libpq_gettext("invalid connection option \"%s\"\n"),
3733                                                                   optname);
3734                                 free(result);
3735                                 return 1;
3736                         }
3737                         optname = NULL;
3738                         optval = NULL;
3739                 }
3740                 oldstate = state;
3741         }
3742
3743         free(result);
3744
3745         if (state == 5 || state == 6)
3746         {
3747                 printfPQExpBuffer(errorMessage, libpq_gettext(
3748                                   "unterminated quoted string in connection info string\n"));
3749                 return 3;
3750         }
3751
3752         return 0;
3753 }
3754 #endif
3755
3756 #define MAXBUFSIZE 256
3757
3758 static int
3759 parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
3760 {
3761         const char *service = conninfo_getval(options, "service");
3762         char            serviceFile[MAXPGPATH];
3763         char       *env;
3764         bool            group_found = false;
3765         int                     status;
3766         struct stat stat_buf;
3767
3768         /*
3769          * We have to special-case the environment variable PGSERVICE here, since
3770          * this is and should be called before inserting environment defaults for
3771          * other connection options.
3772          */
3773         if (service == NULL)
3774                 service = getenv("PGSERVICE");
3775
3776         if (service == NULL)
3777                 return 0;
3778
3779         if ((env = getenv("PGSERVICEFILE")) != NULL)
3780                 strlcpy(serviceFile, env, sizeof(serviceFile));
3781         else
3782         {
3783                 char            homedir[MAXPGPATH];
3784
3785                 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
3786                 {
3787                         printfPQExpBuffer(errorMessage, libpq_gettext("could not get home directory to locate service definition file"));
3788                         return 1;
3789                 }
3790                 snprintf(serviceFile, MAXPGPATH, "%s/%s", homedir, ".pg_service.conf");
3791                 errno = 0;
3792                 if (stat(serviceFile, &stat_buf) != 0 && errno == ENOENT)
3793                         goto next_file;
3794         }
3795
3796         status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
3797         if (group_found || status != 0)
3798                 return status;
3799
3800 next_file:
3801
3802         /*
3803          * This could be used by any application so we can't use the binary
3804          * location to find our config files.
3805          */
3806         snprintf(serviceFile, MAXPGPATH, "%s/pg_service.conf",
3807                          getenv("PGSYSCONFDIR") ? getenv("PGSYSCONFDIR") : SYSCONFDIR);
3808         errno = 0;
3809         if (stat(serviceFile, &stat_buf) != 0 && errno == ENOENT)
3810                 goto last_file;
3811
3812         status = parseServiceFile(serviceFile, service, options, errorMessage, &group_found);
3813         if (status != 0)
3814                 return status;
3815
3816 last_file:
3817         if (!group_found)
3818         {
3819                 printfPQExpBuffer(errorMessage,
3820                  libpq_gettext("definition of service \"%s\" not found\n"), service);
3821                 return 3;
3822         }
3823
3824         return 0;
3825 }
3826
3827 static int
3828 parseServiceFile(const char *serviceFile,
3829                                  const char *service,
3830                                  PQconninfoOption *options,
3831                                  PQExpBuffer errorMessage,
3832                                  bool *group_found)
3833 {
3834         int                     linenr = 0,
3835                                 i;
3836         FILE       *f;
3837         char            buf[MAXBUFSIZE],
3838                            *line;
3839
3840         f = fopen(serviceFile, "r");
3841         if (f == NULL)
3842         {
3843                 printfPQExpBuffer(errorMessage, libpq_gettext("service file \"%s\" not found\n"),
3844                                                   serviceFile);
3845                 return 1;
3846         }
3847
3848         while ((line = fgets(buf, sizeof(buf), f)) != NULL)
3849         {
3850                 linenr++;
3851
3852                 if (strlen(line) >= sizeof(buf) - 1)
3853                 {
3854                         fclose(f);
3855                         printfPQExpBuffer(errorMessage,
3856                                   libpq_gettext("line %d too long in service file \"%s\"\n"),
3857                                                           linenr,
3858                                                           serviceFile);
3859                         return 2;
3860                 }
3861
3862                 /* ignore EOL at end of line */
3863                 if (strlen(line) && line[strlen(line) - 1] == '\n')
3864                         line[strlen(line) - 1] = 0;
3865
3866                 /* ignore leading blanks */
3867                 while (*line && isspace((unsigned char) line[0]))
3868                         line++;
3869
3870                 /* ignore comments and empty lines */
3871                 if (strlen(line) == 0 || line[0] == '#')
3872                         continue;
3873
3874                 /* Check for right groupname */
3875                 if (line[0] == '[')
3876                 {
3877                         if (*group_found)
3878                         {
3879                                 /* group info already read */
3880                                 fclose(f);
3881                                 return 0;
3882                         }
3883
3884                         if (strncmp(line + 1, service, strlen(service)) == 0 &&
3885                                 line[strlen(service) + 1] == ']')
3886                                 *group_found = true;
3887                         else
3888                                 *group_found = false;
3889                 }
3890                 else
3891                 {
3892                         if (*group_found)
3893                         {
3894                                 /*
3895                                  * Finally, we are in the right group and can parse the line
3896                                  */
3897                                 char       *key,
3898                                                    *val;
3899                                 bool            found_keyword;
3900
3901 #ifdef USE_LDAP
3902                                 if (strncmp(line, "ldap", 4) == 0)
3903                                 {
3904                                         int                     rc = ldapServiceLookup(line, options, errorMessage);
3905
3906                                         /* if rc = 2, go on reading for fallback */
3907                                         switch (rc)
3908                                         {
3909                                                 case 0:
3910                                                         fclose(f);
3911                                                         return 0;
3912                                                 case 1:
3913                                                 case 3:
3914                                                         fclose(f);
3915                                                         return 3;
3916                                                 case 2:
3917                                                         continue;
3918                                         }
3919                                 }
3920 #endif
3921
3922                                 key = line;
3923                                 val = strchr(line, '=');
3924                                 if (val == NULL)
3925                                 {
3926                                         printfPQExpBuffer(errorMessage,
3927                                                                           libpq_gettext("syntax error in service file \"%s\", line %d\n"),
3928                                                                           serviceFile,
3929                                                                           linenr);
3930                                         fclose(f);
3931                                         return 3;
3932                                 }
3933                                 *val++ = '\0';
3934
3935                                 /*
3936                                  * Set the parameter --- but don't override any previous
3937                                  * explicit setting.
3938                                  */
3939                                 found_keyword = false;
3940                                 for (i = 0; options[i].keyword; i++)
3941                                 {
3942                                         if (strcmp(options[i].keyword, key) == 0)
3943                                         {
3944                                                 if (options[i].val == NULL)
3945                                                         options[i].val = strdup(val);
3946                                                 found_keyword = true;
3947                                                 break;
3948                                         }
3949                                 }
3950
3951                                 if (!found_keyword)
3952                                 {
3953                                         printfPQExpBuffer(errorMessage,
3954                                                                           libpq_gettext("syntax error in service file \"%s\", line %d\n"),
3955                                                                           serviceFile,
3956                                                                           linenr);
3957                                         fclose(f);
3958                                         return 3;
3959                                 }
3960                         }
3961                 }
3962         }
3963
3964         fclose(f);
3965
3966         return 0;
3967 }
3968
3969
3970 /*
3971  *              PQconninfoParse
3972  *
3973  * Parse a string like PQconnectdb() would do and return the
3974  * resulting connection options array.  NULL is returned on failure.
3975  * The result contains only options specified directly in the string,
3976  * not any possible default values.
3977  *
3978  * If errmsg isn't NULL, *errmsg is set to NULL on success, or a malloc'd
3979  * string on failure (use PQfreemem to free it).  In out-of-memory conditions
3980  * both *errmsg and the result could be NULL.
3981  *
3982  * NOTE: the returned array is dynamically allocated and should
3983  * be freed when no longer needed via PQconninfoFree().
3984  */
3985 PQconninfoOption *
3986 PQconninfoParse(const char *conninfo, char **errmsg)
3987 {
3988         PQExpBufferData errorBuf;
3989         PQconninfoOption *connOptions;
3990
3991         if (errmsg)
3992                 *errmsg = NULL;                 /* default */
3993         initPQExpBuffer(&errorBuf);
3994         if (PQExpBufferDataBroken(errorBuf))
3995                 return NULL;                    /* out of memory already :-( */
3996         connOptions = parse_connection_string(conninfo, &errorBuf, false);
3997         if (connOptions == NULL && errmsg)
3998                 *errmsg = errorBuf.data;
3999         else
4000                 termPQExpBuffer(&errorBuf);
4001         return connOptions;
4002 }
4003
4004 /*
4005  * Build a working copy of the constant PQconninfoOptions array.
4006  */
4007 static PQconninfoOption *
4008 conninfo_init(PQExpBuffer errorMessage)
4009 {
4010         PQconninfoOption *options;
4011         PQconninfoOption *opt_dest;
4012         const internalPQconninfoOption *cur_opt;
4013
4014         /*
4015          * Get enough memory for all options in PQconninfoOptions, even if some
4016          * end up being filtered out.
4017          */
4018         options = (PQconninfoOption *) malloc(sizeof(PQconninfoOption) * sizeof(PQconninfoOptions) / sizeof(PQconninfoOptions[0]));
4019         if (options == NULL)
4020         {
4021                 printfPQExpBuffer(errorMessage,
4022                                                   libpq_gettext("out of memory\n"));
4023                 return NULL;
4024         }
4025         opt_dest = options;
4026
4027         for (cur_opt = PQconninfoOptions; cur_opt->keyword; cur_opt++)
4028         {
4029                 /* Only copy the public part of the struct, not the full internal */
4030                 memcpy(opt_dest, cur_opt, sizeof(PQconninfoOption));
4031                 opt_dest++;
4032         }
4033         MemSet(opt_dest, 0, sizeof(PQconninfoOption));
4034
4035         return options;
4036 }
4037
4038 /*
4039  * Connection string parser
4040  *
4041  * Returns a malloc'd PQconninfoOption array, if parsing is successful.
4042  * Otherwise, NULL is returned and an error message is left in errorMessage.
4043  *
4044  * If use_defaults is TRUE, default values are filled in (from a service file,
4045  * environment variables, etc).
4046  */
4047 static PQconninfoOption *
4048 parse_connection_string(const char *connstr, PQExpBuffer errorMessage,
4049                                                 bool use_defaults)
4050 {
4051         /* Parse as URI if connection string matches URI prefix */
4052         if (uri_prefix_length(connstr) != 0)
4053                 return conninfo_uri_parse(connstr, errorMessage, use_defaults);
4054
4055         /* Parse as default otherwise */
4056         return conninfo_parse(connstr, errorMessage, use_defaults);
4057 }
4058
4059 /*
4060  * Checks if connection string starts with either of the valid URI prefix
4061  * designators.
4062  *
4063  * Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
4064  */
4065 static int
4066 uri_prefix_length(const char *connstr)
4067 {
4068         if (strncmp(connstr, uri_designator,
4069                                 sizeof(uri_designator) - 1) == 0)
4070                 return sizeof(uri_designator) - 1;
4071
4072         if (strncmp(connstr, short_uri_designator,
4073                                 sizeof(short_uri_designator) - 1) == 0)
4074                 return sizeof(short_uri_designator) - 1;
4075
4076         return 0;
4077 }
4078
4079 /*
4080  * Recognized connection string either starts with a valid URI prefix or
4081  * contains a "=" in it.
4082  *
4083  * Must be consistent with parse_connection_string: anything for which this
4084  * returns true should at least look like it's parseable by that routine.
4085  */
4086 static bool
4087 recognized_connection_string(const char *connstr)
4088 {
4089         return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
4090 }
4091
4092 /*
4093  * Subroutine for parse_connection_string
4094  *
4095  * Deal with a string containing key=value pairs.
4096  */
4097 static PQconninfoOption *
4098 conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
4099                            bool use_defaults)
4100 {
4101         char       *pname;
4102         char       *pval;
4103         char       *buf;
4104         char       *cp;
4105         char       *cp2;
4106         PQconninfoOption *options;
4107
4108         /* Make a working copy of PQconninfoOptions */
4109         options = conninfo_init(errorMessage);
4110         if (options == NULL)
4111                 return NULL;
4112
4113         /* Need a modifiable copy of the input string */
4114         if ((buf = strdup(conninfo)) == NULL)
4115         {
4116                 printfPQExpBuffer(errorMessage,
4117                                                   libpq_gettext("out of memory\n"));
4118                 PQconninfoFree(options);
4119                 return NULL;
4120         }
4121         cp = buf;
4122
4123         while (*cp)
4124         {
4125                 /* Skip blanks before the parameter name */
4126                 if (isspace((unsigned char) *cp))
4127                 {
4128                         cp++;
4129                         continue;
4130                 }
4131
4132                 /* Get the parameter name */
4133                 pname = cp;
4134                 while (*cp)
4135                 {
4136                         if (*cp == '=')
4137                                 break;
4138                         if (isspace((unsigned char) *cp))
4139                         {
4140                                 *cp++ = '\0';
4141                                 while (*cp)
4142                                 {
4143                                         if (!isspace((unsigned char) *cp))
4144                                                 break;
4145                                         cp++;
4146                                 }
4147                                 break;
4148                         }
4149                         cp++;
4150                 }
4151
4152                 /* Check that there is a following '=' */
4153                 if (*cp != '=')
4154                 {
4155                         printfPQExpBuffer(errorMessage,
4156                                                           libpq_gettext("missing \"=\" after \"%s\" in connection info string\n"),
4157                                                           pname);
4158                         PQconninfoFree(options);
4159                         free(buf);
4160                         return NULL;
4161                 }
4162                 *cp++ = '\0';
4163
4164                 /* Skip blanks after the '=' */
4165                 while (*cp)
4166                 {
4167                         if (!isspace((unsigned char) *cp))
4168                                 break;
4169                         cp++;
4170                 }
4171
4172                 /* Get the parameter value */
4173                 pval = cp;
4174
4175                 if (*cp != '\'')
4176                 {
4177                         cp2 = pval;
4178                         while (*cp)
4179                         {
4180                                 if (isspace((unsigned char) *cp))
4181                                 {
4182                                         *cp++ = '\0';
4183                                         break;
4184                                 }
4185                                 if (*cp == '\\')
4186                                 {
4187                                         cp++;
4188                                         if (*cp != '\0')
4189                                                 *cp2++ = *cp++;
4190                                 }
4191                                 else
4192                                         *cp2++ = *cp++;
4193                         }
4194                         *cp2 = '\0';
4195                 }
4196                 else
4197                 {
4198                         cp2 = pval;
4199                         cp++;
4200                         for (;;)
4201                         {
4202                                 if (*cp == '\0')
4203                                 {
4204                                         printfPQExpBuffer(errorMessage,
4205                                                                           libpq_gettext("unterminated quoted string in connection info string\n"));
4206                                         PQconninfoFree(options);
4207                                         free(buf);
4208                                         return NULL;
4209                                 }
4210                                 if (*cp == '\\')
4211                                 {
4212                                         cp++;
4213                                         if (*cp != '\0')
4214                                                 *cp2++ = *cp++;
4215                                         continue;
4216                                 }
4217                                 if (*cp == '\'')
4218                                 {
4219                                         *cp2 = '\0';
4220                                         cp++;
4221                                         break;
4222                                 }
4223                                 *cp2++ = *cp++;
4224                         }
4225                 }
4226
4227                 /*
4228                  * Now that we have the name and the value, store the record.
4229                  */
4230                 if (!conninfo_storeval(options, pname, pval, errorMessage, false, false))
4231                 {
4232                         PQconninfoFree(options);
4233                         free(buf);
4234                         return NULL;
4235                 }
4236         }
4237
4238         /* Done with the modifiable input string */
4239         free(buf);
4240
4241         /*
4242          * Add in defaults if the caller wants that.
4243          */
4244         if (use_defaults)
4245         {
4246                 if (!conninfo_add_defaults(options, errorMessage))
4247                 {
4248                         PQconninfoFree(options);
4249                         return NULL;
4250                 }
4251         }
4252
4253         return options;
4254 }
4255
4256 /*
4257  * Conninfo array parser routine
4258  *
4259  * If successful, a malloc'd PQconninfoOption array is returned.
4260  * If not successful, NULL is returned and an error message is
4261  * left in errorMessage.
4262  * Defaults are supplied (from a service file, environment variables, etc)
4263  * for unspecified options, but only if use_defaults is TRUE.
4264  *
4265  * If expand_dbname is non-zero, and the value passed for keyword "dbname" is a
4266  * connection string (as indicated by recognized_connection_string) then parse
4267  * and process it, overriding any previously processed conflicting
4268  * keywords. Subsequent keywords will take precedence, however.
4269  */
4270 static PQconninfoOption *
4271 conninfo_array_parse(const char *const * keywords, const char *const * values,
4272                                          PQExpBuffer errorMessage, bool use_defaults,
4273                                          int expand_dbname)
4274 {
4275         PQconninfoOption *options;
4276         PQconninfoOption *dbname_options = NULL;
4277         PQconninfoOption *option;
4278         int                     i = 0;
4279
4280         /*
4281          * If expand_dbname is non-zero, check keyword "dbname" to see if val is
4282          * actually a recognized connection string.
4283          */
4284         while (expand_dbname && keywords[i])
4285         {
4286                 const char *pname = keywords[i];
4287                 const char *pvalue = values[i];
4288
4289                 /* first find "dbname" if any */
4290                 if (strcmp(pname, "dbname") == 0 && pvalue)
4291                 {
4292                         /*
4293                          * If value is a connection string, parse it, but do not use
4294                          * defaults here -- those get picked up later. We only want to
4295                          * override for those parameters actually passed.
4296                          */
4297                         if (recognized_connection_string(pvalue))
4298                         {
4299                                 dbname_options = parse_connection_string(pvalue, errorMessage, false);
4300                                 if (dbname_options == NULL)
4301                                         return NULL;
4302                         }
4303                         break;
4304                 }
4305                 ++i;
4306         }
4307
4308         /* Make a working copy of PQconninfoOptions */
4309         options = conninfo_init(errorMessage);
4310         if (options == NULL)
4311         {
4312                 PQconninfoFree(dbname_options);
4313                 return NULL;
4314         }
4315
4316         /* Parse the keywords/values arrays */
4317         i = 0;
4318         while (keywords[i])
4319         {
4320                 const char *pname = keywords[i];
4321                 const char *pvalue = values[i];
4322
4323                 if (pvalue != NULL)
4324                 {
4325                         /* Search for the param record */
4326                         for (option = options; option->keyword != NULL; option++)
4327                         {
4328                                 if (strcmp(option->keyword, pname) == 0)
4329                                         break;
4330                         }
4331
4332                         /* Check for invalid connection option */
4333                         if (option->keyword == NULL)
4334                         {
4335                                 printfPQExpBuffer(errorMessage,
4336                                                  libpq_gettext("invalid connection option \"%s\"\n"),
4337                                                                   pname);
4338                                 PQconninfoFree(options);
4339                                 PQconninfoFree(dbname_options);
4340                                 return NULL;
4341                         }
4342
4343                         /*
4344                          * If we are on the dbname parameter, and we have a parsed
4345                          * connection string, copy those parameters across, overriding any
4346                          * existing previous settings.
4347                          */
4348                         if (strcmp(pname, "dbname") == 0 && dbname_options)
4349                         {
4350                                 PQconninfoOption *str_option;
4351
4352                                 for (str_option = dbname_options; str_option->keyword != NULL; str_option++)
4353                                 {
4354                                         if (str_option->val != NULL)
4355                                         {
4356                                                 int                     k;
4357
4358                                                 for (k = 0; options[k].keyword; k++)
4359                                                 {
4360                                                         if (strcmp(options[k].keyword, str_option->keyword) == 0)
4361                                                         {
4362                                                                 if (options[k].val)
4363                                                                         free(options[k].val);
4364                                                                 options[k].val = strdup(str_option->val);
4365                                                                 break;
4366                                                         }
4367                                                 }
4368                                         }
4369                                 }
4370                         }
4371                         else
4372                         {
4373                                 /*
4374                                  * Store the value, overriding previous settings
4375                                  */
4376                                 if (option->val)
4377                                         free(option->val);
4378                                 option->val = strdup(pvalue);
4379                                 if (!option->val)
4380                                 {
4381                                         printfPQExpBuffer(errorMessage,
4382                                                                           libpq_gettext("out of memory\n"));
4383                                         PQconninfoFree(options);
4384                                         PQconninfoFree(dbname_options);
4385                                         return NULL;
4386                                 }
4387                         }
4388                 }
4389                 ++i;
4390         }
4391         PQconninfoFree(dbname_options);
4392
4393         /*
4394          * Add in defaults if the caller wants that.
4395          */
4396         if (use_defaults)
4397         {
4398                 if (!conninfo_add_defaults(options, errorMessage))
4399                 {
4400                         PQconninfoFree(options);
4401                         return NULL;
4402                 }
4403         }
4404
4405         return options;
4406 }
4407
4408 /*
4409  * Add the default values for any unspecified options to the connection
4410  * options array.
4411  *
4412  * Defaults are obtained from a service file, environment variables, etc.
4413  *
4414  * Returns TRUE if successful, otherwise FALSE; errorMessage is filled in
4415  * upon failure.  Note that failure to locate a default value is not an
4416  * error condition here --- we just leave the option's value as NULL.
4417  */
4418 static bool
4419 conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
4420 {
4421         PQconninfoOption *option;
4422         char       *tmp;
4423
4424         /*
4425          * If there's a service spec, use it to obtain any not-explicitly-given
4426          * parameters.
4427          */
4428         if (parseServiceInfo(options, errorMessage) != 0)
4429                 return false;
4430
4431         /*
4432          * Get the fallback resources for parameters not specified in the conninfo
4433          * string nor the service.
4434          */
4435         for (option = options; option->keyword != NULL; option++)
4436         {
4437                 if (option->val != NULL)
4438                         continue;                       /* Value was in conninfo or service */
4439
4440                 /*
4441                  * Try to get the environment variable fallback
4442                  */
4443                 if (option->envvar != NULL)
4444                 {
4445                         if ((tmp = getenv(option->envvar)) != NULL)
4446                         {
4447                                 option->val = strdup(tmp);
4448                                 if (!option->val)
4449                                 {
4450                                         printfPQExpBuffer(errorMessage,
4451                                                                           libpq_gettext("out of memory\n"));
4452                                         return false;
4453                                 }
4454                                 continue;
4455                         }
4456                 }
4457
4458                 /*
4459                  * No environment variable specified or the variable isn't set - try
4460                  * compiled-in default
4461                  */
4462                 if (option->compiled != NULL)
4463                 {
4464                         option->val = strdup(option->compiled);
4465                         if (!option->val)
4466                         {
4467                                 printfPQExpBuffer(errorMessage,
4468                                                                   libpq_gettext("out of memory\n"));
4469                                 return false;
4470                         }
4471                         continue;
4472                 }
4473
4474                 /*
4475                  * Special handling for "user" option
4476                  */
4477                 if (strcmp(option->keyword, "user") == 0)
4478                 {
4479                         option->val = pg_fe_getauthname(errorMessage);
4480                         continue;
4481                 }
4482         }
4483
4484         return true;
4485 }
4486
4487 /*
4488  * Subroutine for parse_connection_string
4489  *
4490  * Deal with a URI connection string.
4491  */
4492 static PQconninfoOption *
4493 conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage,
4494                                    bool use_defaults)
4495 {
4496         PQconninfoOption *options;
4497
4498         /* Make a working copy of PQconninfoOptions */
4499         options = conninfo_init(errorMessage);
4500         if (options == NULL)
4501                 return NULL;
4502
4503         if (!conninfo_uri_parse_options(options, uri, errorMessage))
4504         {
4505                 PQconninfoFree(options);
4506                 return NULL;
4507         }
4508
4509         /*
4510          * Add in defaults if the caller wants that.
4511          */
4512         if (use_defaults)
4513         {
4514                 if (!conninfo_add_defaults(options, errorMessage))
4515                 {
4516                         PQconninfoFree(options);
4517                         return NULL;
4518                 }
4519         }
4520
4521         return options;
4522 }
4523
4524 /*
4525  * conninfo_uri_parse_options
4526  *              Actual URI parser.
4527  *
4528  * If successful, returns true while the options array is filled with parsed
4529  * options from the URI.
4530  * If not successful, returns false and fills errorMessage accordingly.
4531  *
4532  * Parses the connection URI string in 'uri' according to the URI syntax (RFC
4533  * 3986):
4534  *
4535  * postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
4536  *
4537  * where "netloc" is a hostname, an IPv4 address, or an IPv6 address surrounded
4538  * by literal square brackets.
4539  *
4540  * Any of the URI parts might use percent-encoding (%xy).
4541  */
4542 static bool
4543 conninfo_uri_parse_options(PQconninfoOption *options, const char *uri,
4544                                                    PQExpBuffer errorMessage)
4545 {
4546         int                     prefix_len;
4547         char       *p;
4548         char       *buf = strdup(uri);          /* need a modifiable copy of the input
4549                                                                                  * URI */
4550         char       *start = buf;
4551         char            prevchar = '\0';
4552         char       *user = NULL;
4553         char       *host = NULL;
4554         bool            retval = false;
4555
4556         if (buf == NULL)
4557         {
4558                 printfPQExpBuffer(errorMessage,
4559                                                   libpq_gettext("out of memory\n"));
4560                 return false;
4561         }
4562
4563         /* Skip the URI prefix */
4564         prefix_len = uri_prefix_length(uri);
4565         if (prefix_len == 0)
4566         {
4567                 /* Should never happen */
4568                 printfPQExpBuffer(errorMessage,
4569                                                   libpq_gettext("invalid URI propagated to internal parser routine: \"%s\"\n"),
4570                                                   uri);
4571                 goto cleanup;
4572         }
4573         start += prefix_len;
4574         p = start;
4575
4576         /* Look ahead for possible user credentials designator */
4577         while (*p && *p != '@' && *p != '/')
4578                 ++p;
4579         if (*p == '@')
4580         {
4581                 /*
4582                  * Found username/password designator, so URI should be of the form
4583                  * "scheme://user[:password]@[netloc]".
4584                  */
4585                 user = start;
4586
4587                 p = user;
4588                 while (*p != ':' && *p != '@')
4589                         ++p;
4590
4591                 /* Save last char and cut off at end of user name */
4592                 prevchar = *p;
4593                 *p = '\0';
4594
4595                 if (*user &&
4596                         !conninfo_storeval(options, "user", user,
4597                                                            errorMessage, false, true))
4598                         goto cleanup;
4599
4600                 if (prevchar == ':')
4601                 {
4602                         const char *password = p + 1;
4603
4604                         while (*p != '@')
4605                                 ++p;
4606                         *p = '\0';
4607
4608                         if (*password &&
4609                                 !conninfo_storeval(options, "password", password,
4610                                                                    errorMessage, false, true))
4611                                 goto cleanup;
4612                 }
4613
4614                 /* Advance past end of parsed user name or password token */
4615                 ++p;
4616         }
4617         else
4618         {
4619                 /*
4620                  * No username/password designator found.  Reset to start of URI.
4621                  */
4622                 p = start;
4623         }
4624
4625         /*
4626          * "p" has been incremented past optional URI credential information at
4627          * this point and now points at the "netloc" part of the URI.
4628          *
4629          * Look for IPv6 address.
4630          */
4631         if (*p == '[')
4632         {
4633                 host = ++p;
4634                 while (*p && *p != ']')
4635                         ++p;
4636                 if (!*p)
4637                 {
4638                         printfPQExpBuffer(errorMessage,
4639                                                           libpq_gettext("end of string reached when looking for matching \"]\" in IPv6 host address in URI: \"%s\"\n"),
4640                                                           uri);
4641                         goto cleanup;
4642                 }
4643                 if (p == host)
4644                 {
4645                         printfPQExpBuffer(errorMessage,
4646                                                           libpq_gettext("IPv6 host address may not be empty in URI: \"%s\"\n"),
4647                                                           uri);
4648                         goto cleanup;
4649                 }
4650
4651                 /* Cut off the bracket and advance */
4652                 *(p++) = '\0';
4653
4654                 /*
4655                  * The address may be followed by a port specifier or a slash or a
4656                  * query.
4657                  */
4658                 if (*p && *p != ':' && *p != '/' && *p != '?')
4659                 {
4660                         printfPQExpBuffer(errorMessage,
4661                                                           libpq_gettext("unexpected character \"%c\" at position %d in URI (expected \":\" or \"/\"): \"%s\"\n"),
4662                                                           *p, (int) (p - buf + 1), uri);
4663                         goto cleanup;
4664                 }
4665         }
4666         else
4667         {
4668                 /* not an IPv6 address: DNS-named or IPv4 netloc */
4669                 host = p;
4670
4671                 /*
4672                  * Look for port specifier (colon) or end of host specifier (slash),
4673                  * or query (question mark).
4674                  */
4675                 while (*p && *p != ':' && *p != '/' && *p != '?')
4676                         ++p;
4677         }
4678
4679         /* Save the hostname terminator before we null it */
4680         prevchar = *p;
4681         *p = '\0';
4682
4683         if (*host &&
4684                 !conninfo_storeval(options, "host", host,
4685                                                    errorMessage, false, true))
4686                 goto cleanup;
4687
4688
4689         if (prevchar == ':')
4690         {
4691                 const char *port = ++p; /* advance past host terminator */
4692
4693                 while (*p && *p != '/' && *p != '?')
4694                         ++p;
4695
4696                 prevchar = *p;
4697                 *p = '\0';
4698
4699                 if (*port &&
4700                         !conninfo_storeval(options, "port", port,
4701                                                            errorMessage, false, true))
4702                         goto cleanup;
4703         }
4704
4705         if (prevchar && prevchar != '?')
4706         {
4707                 const char *dbname = ++p;               /* advance past host terminator */
4708
4709                 /* Look for query parameters */
4710                 while (*p && *p != '?')
4711                         ++p;
4712
4713                 prevchar = *p;
4714                 *p = '\0';
4715
4716                 /*
4717                  * Avoid setting dbname to an empty string, as it forces the default
4718                  * value (username) and ignores $PGDATABASE, as opposed to not setting
4719                  * it at all.
4720                  */
4721                 if (*dbname &&
4722                         !conninfo_storeval(options, "dbname", dbname,
4723                                                            errorMessage, false, true))
4724                         goto cleanup;
4725         }
4726
4727         if (prevchar)
4728         {
4729                 ++p;                                    /* advance past terminator */
4730
4731                 if (!conninfo_uri_parse_params(p, options, errorMessage))
4732                         goto cleanup;
4733         }
4734
4735         /* everything parsed okay */
4736         retval = true;
4737
4738 cleanup:
4739         free(buf);
4740         return retval;
4741 }
4742
4743 /*
4744  * Connection URI parameters parser routine
4745  *
4746  * If successful, returns true while connOptions is filled with parsed
4747  * parameters.  Otherwise, returns false and fills errorMessage appropriately.
4748  *
4749  * Destructively modifies 'params' buffer.
4750  */
4751 static bool
4752 conninfo_uri_parse_params(char *params,
4753                                                   PQconninfoOption *connOptions,
4754                                                   PQExpBuffer errorMessage)
4755 {
4756         while (*params)
4757         {
4758                 char       *keyword = params;
4759                 char       *value = NULL;
4760                 char       *p = params;
4761                 bool            malloced = false;
4762
4763                 /*
4764                  * Scan the params string for '=' and '&', marking the end of keyword
4765                  * and value respectively.
4766                  */
4767                 for (;;)
4768                 {
4769                         if (*p == '=')
4770                         {
4771                                 /* Was there '=' already? */
4772                                 if (value != NULL)
4773                                 {
4774                                         printfPQExpBuffer(errorMessage,
4775                                                                           libpq_gettext("extra key/value separator \"=\" in URI query parameter: \"%s\"\n"),
4776                                                                           params);
4777                                         return false;
4778                                 }
4779                                 /* Cut off keyword, advance to value */
4780                                 *p = '\0';
4781                                 value = ++p;
4782                         }
4783                         else if (*p == '&' || *p == '\0')
4784                         {
4785                                 char            prevchar;
4786
4787                                 /* Cut off value, remember old value */
4788                                 prevchar = *p;
4789                                 *p = '\0';
4790
4791                                 /* Was there '=' at all? */
4792                                 if (value == NULL)
4793                                 {
4794                                         printfPQExpBuffer(errorMessage,
4795                                                                           libpq_gettext("missing key/value separator \"=\" in URI query parameter: \"%s\"\n"),
4796                                                                           params);
4797                                         return false;
4798                                 }
4799
4800                                 /*
4801                                  * If not at the end, advance; now pointing to start of the
4802                                  * next parameter, if any.
4803                                  */
4804                                 if (prevchar != '\0')
4805                                         ++p;
4806                                 break;
4807                         }
4808
4809                         /* Advance, NUL is checked in the 'if' above */
4810                         ++p;
4811                 }
4812
4813                 keyword = conninfo_uri_decode(keyword, errorMessage);
4814                 if (keyword == NULL)
4815                 {
4816                         /* conninfo_uri_decode already set an error message */
4817                         return false;
4818                 }
4819                 value = conninfo_uri_decode(value, errorMessage);
4820                 if (value == NULL)
4821                 {
4822                         /* conninfo_uri_decode already set an error message */
4823                         free(keyword);
4824                         return false;
4825                 }
4826                 malloced = true;
4827
4828                 /*
4829                  * Special keyword handling for improved JDBC compatibility.
4830                  */
4831                 if (strcmp(keyword, "ssl") == 0 &&
4832                         strcmp(value, "true") == 0)
4833                 {
4834                         free(keyword);
4835                         free(value);
4836                         malloced = false;
4837
4838                         keyword = "sslmode";
4839                         value = "require";
4840                 }
4841
4842                 /*
4843                  * Store the value if the corresponding option exists; ignore
4844                  * otherwise.  At this point both keyword and value are not
4845                  * URI-encoded.
4846                  */
4847                 if (!conninfo_storeval(connOptions, keyword, value,
4848                                                            errorMessage, true, false))
4849                 {
4850                         /*
4851                          * Check if there was a hard error when decoding or storing the
4852                          * option.
4853                          */
4854                         if (errorMessage->len != 0)
4855                         {
4856                                 if (malloced)
4857                                 {
4858                                         free(keyword);
4859                                         free(value);
4860                                 }
4861                                 return false;
4862                         }
4863
4864                         printfPQExpBuffer(errorMessage,
4865                                                           libpq_gettext(
4866                                                                         "invalid URI query parameter: \"%s\"\n"),
4867                                                           keyword);
4868                         if (malloced)
4869                         {
4870                                 free(keyword);
4871                                 free(value);
4872                         }
4873                         return false;
4874                 }
4875                 if (malloced)
4876                 {
4877                         free(keyword);
4878                         free(value);
4879                 }
4880
4881                 /* Proceed to next key=value pair */
4882                 params = p;
4883         }
4884
4885         return true;
4886 }
4887
4888 /*
4889  * Connection URI decoder routine
4890  *
4891  * If successful, returns the malloc'd decoded string.
4892  * If not successful, returns NULL and fills errorMessage accordingly.
4893  *
4894  * The string is decoded by replacing any percent-encoded tokens with
4895  * corresponding characters, while preserving any non-encoded characters.  A
4896  * percent-encoded token is a character triplet: a percent sign, followed by a
4897  * pair of hexadecimal digits (0-9A-F), where lower- and upper-case letters are
4898  * treated identically.
4899  */
4900 static char *
4901 conninfo_uri_decode(const char *str, PQExpBuffer errorMessage)
4902 {
4903         char       *buf = malloc(strlen(str) + 1);
4904         char       *p = buf;
4905         const char *q = str;
4906
4907         if (buf == NULL)
4908         {
4909                 printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
4910                 return NULL;
4911         }
4912
4913         for (;;)
4914         {
4915                 if (*q != '%')
4916                 {
4917                         /* copy and check for NUL terminator */
4918                         if (!(*(p++) = *(q++)))
4919                                 break;
4920                 }
4921                 else
4922                 {
4923                         int                     hi;
4924                         int                     lo;
4925                         int                     c;
4926
4927                         ++q;                            /* skip the percent sign itself */
4928
4929                         /*
4930                          * Possible EOL will be caught by the first call to
4931                          * get_hexdigit(), so we never dereference an invalid q pointer.
4932                          */
4933                         if (!(get_hexdigit(*q++, &hi) && get_hexdigit(*q++, &lo)))
4934                         {
4935                                 printfPQExpBuffer(errorMessage,
4936                                         libpq_gettext("invalid percent-encoded token: \"%s\"\n"),
4937                                                                   str);
4938                                 free(buf);
4939                                 return NULL;
4940                         }
4941
4942                         c = (hi << 4) | lo;
4943                         if (c == 0)
4944                         {
4945                                 printfPQExpBuffer(errorMessage,
4946                                                                   libpq_gettext("forbidden value %%00 in percent-encoded value: \"%s\"\n"),
4947                                                                   str);
4948                                 free(buf);
4949                                 return NULL;
4950                         }
4951                         *(p++) = c;
4952                 }
4953         }
4954
4955         return buf;
4956 }
4957
4958 /*
4959  * Convert hexadecimal digit character to its integer value.
4960  *
4961  * If successful, returns true and value is filled with digit's base 16 value.
4962  * If not successful, returns false.
4963  *
4964  * Lower- and upper-case letters in the range A-F are treated identically.
4965  */
4966 static bool
4967 get_hexdigit(char digit, int *value)
4968 {
4969         if ('0' <= digit && digit <= '9')
4970                 *value = digit - '0';
4971         else if ('A' <= digit && digit <= 'F')
4972                 *value = digit - 'A' + 10;
4973         else if ('a' <= digit && digit <= 'f')
4974                 *value = digit - 'a' + 10;
4975         else
4976                 return false;
4977
4978         return true;
4979 }
4980
4981 /*
4982  * Find an option value corresponding to the keyword in the connOptions array.
4983  *
4984  * If successful, returns a pointer to the corresponding option's value.
4985  * If not successful, returns NULL.
4986  */
4987 static const char *
4988 conninfo_getval(PQconninfoOption *connOptions,
4989                                 const char *keyword)
4990 {
4991         PQconninfoOption *option;
4992
4993         option = conninfo_find(connOptions, keyword);
4994
4995         return option ? option->val : NULL;
4996 }
4997
4998 /*
4999  * Store a (new) value for an option corresponding to the keyword in
5000  * connOptions array.
5001  *
5002  * If uri_decode is true, the value is URI-decoded.  The keyword is always
5003  * assumed to be non URI-encoded.
5004  *
5005  * If successful, returns a pointer to the corresponding PQconninfoOption,
5006  * which value is replaced with a strdup'd copy of the passed value string.
5007  * The existing value for the option is free'd before replacing, if any.
5008  *
5009  * If not successful, returns NULL and fills errorMessage accordingly.
5010  * However, if the reason of failure is an invalid keyword being passed and
5011  * ignoreMissing is TRUE, errorMessage will be left untouched.
5012  */
5013 static PQconninfoOption *
5014 conninfo_storeval(PQconninfoOption *connOptions,
5015                                   const char *keyword, const char *value,
5016                                   PQExpBuffer errorMessage, bool ignoreMissing,
5017                                   bool uri_decode)
5018 {
5019         PQconninfoOption *option;
5020         char       *value_copy;
5021
5022         /*
5023          * For backwards compatibility, requiressl=1 gets translated to
5024          * sslmode=require, and requiressl=0 gets translated to sslmode=prefer
5025          * (which is the default for sslmode).
5026          */
5027         if (strcmp(keyword, "requiressl") == 0)
5028         {
5029                 keyword = "sslmode";
5030                 if (value[0] == '1')
5031                         value = "require";
5032                 else
5033                         value = "prefer";
5034         }
5035
5036         option = conninfo_find(connOptions, keyword);
5037         if (option == NULL)
5038         {
5039                 if (!ignoreMissing)
5040                         printfPQExpBuffer(errorMessage,
5041                                                  libpq_gettext("invalid connection option \"%s\"\n"),
5042                                                           keyword);
5043                 return NULL;
5044         }
5045
5046         if (uri_decode)
5047         {
5048                 value_copy = conninfo_uri_decode(value, errorMessage);
5049                 if (value_copy == NULL)
5050                         /* conninfo_uri_decode already set an error message */
5051                         return NULL;
5052         }
5053         else
5054         {
5055                 value_copy = strdup(value);
5056
5057                 if (value_copy == NULL)
5058                 {
5059                         printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
5060                         return NULL;
5061                 }
5062         }
5063
5064         if (option->val)
5065                 free(option->val);
5066         option->val = value_copy;
5067
5068         return option;
5069 }
5070
5071 /*
5072  * Find a PQconninfoOption option corresponding to the keyword in the
5073  * connOptions array.
5074  *
5075  * If successful, returns a pointer to the corresponding PQconninfoOption
5076  * structure.
5077  * If not successful, returns NULL.
5078  */
5079 static PQconninfoOption *
5080 conninfo_find(PQconninfoOption *connOptions, const char *keyword)
5081 {
5082         PQconninfoOption *option;
5083
5084         for (option = connOptions; option->keyword != NULL; option++)
5085         {
5086                 if (strcmp(option->keyword, keyword) == 0)
5087                         return option;
5088         }
5089
5090         return NULL;
5091 }
5092
5093
5094 /*
5095  * Return the connection options used for the connection
5096  */
5097 PQconninfoOption *
5098 PQconninfo(PGconn *conn)
5099 {
5100         PQExpBufferData errorBuf;
5101         PQconninfoOption *connOptions;
5102
5103         if (conn == NULL)
5104                 return NULL;
5105
5106         /* We don't actually report any errors here, but callees want a buffer */
5107         initPQExpBuffer(&errorBuf);
5108         if (PQExpBufferDataBroken(errorBuf))
5109                 return NULL;                    /* out of memory already :-( */
5110
5111         connOptions = conninfo_init(&errorBuf);
5112
5113         if (connOptions != NULL)
5114         {
5115                 const internalPQconninfoOption *option;
5116
5117                 for (option = PQconninfoOptions; option->keyword; option++)
5118                 {
5119                         char      **connmember;
5120
5121                         if (option->connofs < 0)
5122                                 continue;
5123
5124                         connmember = (char **) ((char *) conn + option->connofs);
5125
5126                         if (*connmember)
5127                                 conninfo_storeval(connOptions, option->keyword, *connmember,
5128                                                                   &errorBuf, true, false);
5129                 }
5130         }
5131
5132         termPQExpBuffer(&errorBuf);
5133
5134         return connOptions;
5135 }
5136
5137
5138 void
5139 PQconninfoFree(PQconninfoOption *connOptions)
5140 {
5141         PQconninfoOption *option;
5142
5143         if (connOptions == NULL)
5144                 return;
5145
5146         for (option = connOptions; option->keyword != NULL; option++)
5147         {
5148                 if (option->val != NULL)
5149                         free(option->val);
5150         }
5151         free(connOptions);
5152 }
5153
5154
5155 /* =========== accessor functions for PGconn ========= */
5156 char *
5157 PQdb(const PGconn *conn)
5158 {
5159         if (!conn)
5160                 return NULL;
5161         return conn->dbName;
5162 }
5163
5164 char *
5165 PQuser(const PGconn *conn)
5166 {
5167         if (!conn)
5168                 return NULL;
5169         return conn->pguser;
5170 }
5171
5172 char *
5173 PQpass(const PGconn *conn)
5174 {
5175         if (!conn)
5176                 return NULL;
5177         return conn->pgpass;
5178 }
5179
5180 char *
5181 PQhost(const PGconn *conn)
5182 {
5183         if (!conn)
5184                 return NULL;
5185         return conn->pghost ? conn->pghost : conn->pgunixsocket;
5186 }
5187
5188 char *
5189 PQport(const PGconn *conn)
5190 {
5191         if (!conn)
5192                 return NULL;
5193         return conn->pgport;
5194 }
5195
5196 char *
5197 PQtty(const PGconn *conn)
5198 {
5199         if (!conn)
5200                 return NULL;
5201         return conn->pgtty;
5202 }
5203
5204 char *
5205 PQoptions(const PGconn *conn)
5206 {
5207         if (!conn)
5208                 return NULL;
5209         return conn->pgoptions;
5210 }
5211
5212 ConnStatusType
5213 PQstatus(const PGconn *conn)
5214 {
5215         if (!conn)
5216                 return CONNECTION_BAD;
5217         return conn->status;
5218 }
5219
5220 PGTransactionStatusType
5221 PQtransactionStatus(const PGconn *conn)
5222 {
5223         if (!conn || conn->status != CONNECTION_OK)
5224                 return PQTRANS_UNKNOWN;
5225         if (conn->asyncStatus != PGASYNC_IDLE)
5226                 return PQTRANS_ACTIVE;
5227         return conn->xactStatus;
5228 }
5229
5230 const char *
5231 PQparameterStatus(const PGconn *conn, const char *paramName)
5232 {
5233         const pgParameterStatus *pstatus;
5234
5235         if (!conn || !paramName)
5236                 return NULL;
5237         for (pstatus = conn->pstatus; pstatus != NULL; pstatus = pstatus->next)
5238         {
5239                 if (strcmp(pstatus->name, paramName) == 0)
5240                         return pstatus->value;
5241         }
5242         return NULL;
5243 }
5244
5245 int
5246 PQprotocolVersion(const PGconn *conn)
5247 {
5248         if (!conn)
5249                 return 0;
5250         if (conn->status == CONNECTION_BAD)
5251                 return 0;
5252         return PG_PROTOCOL_MAJOR(conn->pversion);
5253 }
5254
5255 int
5256 PQserverVersion(const PGconn *conn)
5257 {
5258         if (!conn)
5259                 return 0;
5260         if (conn->status == CONNECTION_BAD)
5261                 return 0;
5262         return conn->sversion;
5263 }
5264
5265 char *
5266 PQerrorMessage(const PGconn *conn)
5267 {
5268         if (!conn)
5269                 return libpq_gettext("connection pointer is NULL\n");
5270
5271         return conn->errorMessage.data;
5272 }
5273
5274 int
5275 PQsocket(const PGconn *conn)
5276 {
5277         if (!conn)
5278                 return -1;
5279         return conn->sock;
5280 }
5281
5282 int
5283 PQbackendPID(const PGconn *conn)
5284 {
5285         if (!conn || conn->status != CONNECTION_OK)
5286                 return 0;
5287         return conn->be_pid;
5288 }
5289
5290 int
5291 PQconnectionNeedsPassword(const PGconn *conn)
5292 {
5293         if (!conn)
5294                 return false;
5295         if (conn->password_needed &&
5296                 (conn->pgpass == NULL || conn->pgpass[0] == '\0'))
5297                 return true;
5298         else
5299                 return false;
5300 }
5301
5302 int
5303 PQconnectionUsedPassword(const PGconn *conn)
5304 {
5305         if (!conn)
5306                 return false;
5307         if (conn->password_needed)
5308                 return true;
5309         else
5310                 return false;
5311 }
5312
5313 int
5314 PQclientEncoding(const PGconn *conn)
5315 {
5316         if (!conn || conn->status != CONNECTION_OK)
5317                 return -1;
5318         return conn->client_encoding;
5319 }
5320
5321 int
5322 PQsetClientEncoding(PGconn *conn, const char *encoding)
5323 {
5324         char            qbuf[128];
5325         static const char query[] = "set client_encoding to '%s'";
5326         PGresult   *res;
5327         int                     status;
5328
5329         if (!conn || conn->status != CONNECTION_OK)
5330                 return -1;
5331
5332         if (!encoding)
5333                 return -1;
5334
5335         /* Resolve special "auto" value from the locale */
5336         if (strcmp(encoding, "auto") == 0)
5337                 encoding = pg_encoding_to_char(pg_get_encoding_from_locale(NULL, true));
5338
5339         /* check query buffer overflow */
5340         if (sizeof(qbuf) < (sizeof(query) + strlen(encoding)))
5341                 return -1;
5342
5343         /* ok, now send a query */
5344         sprintf(qbuf, query, encoding);
5345         res = PQexec(conn, qbuf);
5346
5347         if (res == NULL)
5348                 return -1;
5349         if (res->resultStatus != PGRES_COMMAND_OK)
5350                 status = -1;
5351         else
5352         {
5353                 /*
5354                  * In protocol 2 we have to assume the setting will stick, and adjust
5355                  * our state immediately.  In protocol 3 and up we can rely on the
5356                  * backend to report the parameter value, and we'll change state at
5357                  * that time.
5358                  */
5359                 if (PG_PROTOCOL_MAJOR(conn->pversion) < 3)
5360                         pqSaveParameterStatus(conn, "client_encoding", encoding);
5361                 status = 0;                             /* everything is ok */
5362         }
5363         PQclear(res);
5364         return status;
5365 }
5366
5367 PGVerbosity
5368 PQsetErrorVerbosity(PGconn *conn, PGVerbosity verbosity)
5369 {
5370         PGVerbosity old;
5371
5372         if (!conn)
5373                 return PQERRORS_DEFAULT;
5374         old = conn->verbosity;
5375         conn->verbosity = verbosity;
5376         return old;
5377 }
5378
5379 void
5380 PQtrace(PGconn *conn, FILE *debug_port)
5381 {
5382         if (conn == NULL)
5383                 return;
5384         PQuntrace(conn);
5385         conn->Pfdebug = debug_port;
5386 }
5387
5388 void
5389 PQuntrace(PGconn *conn)
5390 {
5391         if (conn == NULL)
5392                 return;
5393         if (conn->Pfdebug)
5394         {
5395                 fflush(conn->Pfdebug);
5396                 conn->Pfdebug = NULL;
5397         }
5398 }
5399
5400 PQnoticeReceiver
5401 PQsetNoticeReceiver(PGconn *conn, PQnoticeReceiver proc, void *arg)
5402 {
5403         PQnoticeReceiver old;
5404
5405         if (conn == NULL)
5406                 return NULL;
5407
5408         old = conn->noticeHooks.noticeRec;
5409         if (proc)
5410         {
5411                 conn->noticeHooks.noticeRec = proc;
5412                 conn->noticeHooks.noticeRecArg = arg;
5413         }
5414         return old;
5415 }
5416
5417 PQnoticeProcessor
5418 PQsetNoticeProcessor(PGconn *conn, PQnoticeProcessor proc, void *arg)
5419 {
5420         PQnoticeProcessor old;
5421
5422         if (conn == NULL)
5423                 return NULL;
5424
5425         old = conn->noticeHooks.noticeProc;
5426         if (proc)
5427         {
5428                 conn->noticeHooks.noticeProc = proc;
5429                 conn->noticeHooks.noticeProcArg = arg;
5430         }
5431         return old;
5432 }
5433
5434 /*
5435  * The default notice message receiver just gets the standard notice text
5436  * and sends it to the notice processor.  This two-level setup exists
5437  * mostly for backwards compatibility; perhaps we should deprecate use of
5438  * PQsetNoticeProcessor?
5439  */
5440 static void
5441 defaultNoticeReceiver(void *arg, const PGresult *res)
5442 {
5443         (void) arg;                                     /* not used */
5444         if (res->noticeHooks.noticeProc != NULL)
5445                 (*res->noticeHooks.noticeProc) (res->noticeHooks.noticeProcArg,
5446                                                                                 PQresultErrorMessage(res));
5447 }
5448
5449 /*
5450  * The default notice message processor just prints the
5451  * message on stderr.  Applications can override this if they
5452  * want the messages to go elsewhere (a window, for example).
5453  * Note that simply discarding notices is probably a bad idea.
5454  */
5455 static void
5456 defaultNoticeProcessor(void *arg, const char *message)
5457 {
5458         (void) arg;                                     /* not used */
5459         /* Note: we expect the supplied string to end with a newline already. */
5460         fprintf(stderr, "%s", message);
5461 }
5462
5463 /*
5464  * returns a pointer to the next token or NULL if the current
5465  * token doesn't match
5466  */
5467 static char *
5468 pwdfMatchesString(char *buf, char *token)
5469 {
5470         char       *tbuf,
5471                            *ttok;
5472         bool            bslash = false;
5473
5474         if (buf == NULL || token == NULL)
5475                 return NULL;
5476         tbuf = buf;
5477         ttok = token;
5478         if (tbuf[0] == '*' && tbuf[1] == ':')
5479                 return tbuf + 2;
5480         while (*tbuf != 0)
5481         {
5482                 if (*tbuf == '\\' && !bslash)
5483                 {
5484                         tbuf++;
5485                         bslash = true;
5486                 }
5487                 if (*tbuf == ':' && *ttok == 0 && !bslash)
5488                         return tbuf + 1;
5489                 bslash = false;
5490                 if (*ttok == 0)
5491                         return NULL;
5492                 if (*tbuf == *ttok)
5493                 {
5494                         tbuf++;
5495                         ttok++;
5496                 }
5497                 else
5498                         return NULL;
5499         }
5500         return NULL;
5501 }
5502
5503 /* Get a password from the password file. Return value is malloc'd. */
5504 static char *
5505 PasswordFromFile(char *hostname, char *port, char *dbname, char *username)
5506 {
5507         FILE       *fp;
5508         char            pgpassfile[MAXPGPATH];
5509         struct stat stat_buf;
5510
5511 #define LINELEN NAMEDATALEN*5
5512         char            buf[LINELEN];
5513
5514         if (dbname == NULL || strlen(dbname) == 0)
5515                 return NULL;
5516
5517         if (username == NULL || strlen(username) == 0)
5518                 return NULL;
5519
5520         /* 'localhost' matches pghost of '' or the default socket directory */
5521         if (hostname == NULL)
5522                 hostname = DefaultHost;
5523         else if (is_absolute_path(hostname))
5524
5525                 /*
5526                  * We should probably use canonicalize_path(), but then we have to
5527                  * bring path.c into libpq, and it doesn't seem worth it.
5528                  */
5529                 if (strcmp(hostname, DEFAULT_PGSOCKET_DIR) == 0)
5530                         hostname = DefaultHost;
5531
5532         if (port == NULL)
5533                 port = DEF_PGPORT_STR;
5534
5535         if (!getPgPassFilename(pgpassfile))
5536                 return NULL;
5537
5538         /* If password file cannot be opened, ignore it. */
5539         if (stat(pgpassfile, &stat_buf) != 0)
5540                 return NULL;
5541
5542 #ifndef WIN32
5543         if (!S_ISREG(stat_buf.st_mode))
5544         {
5545                 fprintf(stderr,
5546                 libpq_gettext("WARNING: password file \"%s\" is not a plain file\n"),
5547                                 pgpassfile);
5548                 return NULL;
5549         }
5550
5551         /* If password file is insecure, alert the user and ignore it. */
5552         if (stat_buf.st_mode & (S_IRWXG | S_IRWXO))
5553         {
5554                 fprintf(stderr,
5555                                 libpq_gettext("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
5556                                 pgpassfile);
5557                 return NULL;
5558         }
5559 #else
5560
5561         /*
5562          * On Win32, the directory is protected, so we don't have to check the
5563          * file.
5564          */
5565 #endif
5566
5567         fp = fopen(pgpassfile, "r");
5568         if (fp == NULL)
5569                 return NULL;
5570
5571         while (!feof(fp) && !ferror(fp))
5572         {
5573                 char       *t = buf,
5574                                    *ret,
5575                                    *p1,
5576                                    *p2;
5577                 int                     len;
5578
5579                 if (fgets(buf, sizeof(buf), fp) == NULL)
5580                         break;
5581
5582                 len = strlen(buf);
5583                 if (len == 0)
5584                         continue;
5585
5586                 /* Remove trailing newline */
5587                 if (buf[len - 1] == '\n')
5588                         buf[len - 1] = 0;
5589
5590                 if ((t = pwdfMatchesString(t, hostname)) == NULL ||
5591                         (t = pwdfMatchesString(t, port)) == NULL ||
5592                         (t = pwdfMatchesString(t, dbname)) == NULL ||
5593                         (t = pwdfMatchesString(t, username)) == NULL)
5594                         continue;
5595                 ret = strdup(t);
5596                 fclose(fp);
5597
5598                 /* De-escape password. */
5599                 for (p1 = p2 = ret; *p1 != ':' && *p1 != '\0'; ++p1, ++p2)
5600                 {
5601                         if (*p1 == '\\' && p1[1] != '\0')
5602                                 ++p1;
5603                         *p2 = *p1;
5604                 }
5605                 *p2 = '\0';
5606
5607                 return ret;
5608         }
5609
5610         fclose(fp);
5611         return NULL;
5612
5613 #undef LINELEN
5614 }
5615
5616
5617 static bool
5618 getPgPassFilename(char *pgpassfile)
5619 {
5620         char       *passfile_env;
5621
5622         if ((passfile_env = getenv("PGPASSFILE")) != NULL)
5623                 /* use the literal path from the environment, if set */
5624                 strlcpy(pgpassfile, passfile_env, MAXPGPATH);
5625         else
5626         {
5627                 char            homedir[MAXPGPATH];
5628
5629                 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
5630                         return false;
5631                 snprintf(pgpassfile, MAXPGPATH, "%s/%s", homedir, PGPASSFILE);
5632         }
5633         return true;
5634 }
5635
5636 /*
5637  *      If the connection failed, we should mention if
5638  *      we got the password from .pgpass in case that
5639  *      password is wrong.
5640  */
5641 static void
5642 dot_pg_pass_warning(PGconn *conn)
5643 {
5644         /* If it was 'invalid authorization', add .pgpass mention */
5645         /* only works with >= 9.0 servers */
5646         if (conn->dot_pgpass_used && conn->password_needed && conn->result &&
5647                 strcmp(PQresultErrorField(conn->result, PG_DIAG_SQLSTATE),
5648                            ERRCODE_INVALID_PASSWORD) == 0)
5649         {
5650                 char            pgpassfile[MAXPGPATH];
5651
5652                 if (!getPgPassFilename(pgpassfile))
5653                         return;
5654                 appendPQExpBuffer(&conn->errorMessage,
5655                                           libpq_gettext("password retrieved from file \"%s\"\n"),
5656                                                   pgpassfile);
5657         }
5658 }
5659
5660
5661 /*
5662  * Obtain user's home directory, return in given buffer
5663  *
5664  * On Unix, this actually returns the user's home directory.  On Windows
5665  * it returns the PostgreSQL-specific application data folder.
5666  *
5667  * This is essentially the same as get_home_path(), but we don't use that
5668  * because we don't want to pull path.c into libpq (it pollutes application
5669  * namespace)
5670  */
5671 bool
5672 pqGetHomeDirectory(char *buf, int bufsize)
5673 {
5674 #ifndef WIN32
5675         char            pwdbuf[BUFSIZ];
5676         struct passwd pwdstr;
5677         struct passwd *pwd = NULL;
5678
5679         if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
5680                 return false;
5681         strlcpy(buf, pwd->pw_dir, bufsize);
5682         return true;
5683 #else
5684         char            tmppath[MAX_PATH];
5685
5686         ZeroMemory(tmppath, sizeof(tmppath));
5687         if (SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, tmppath) != S_OK)
5688                 return false;
5689         snprintf(buf, bufsize, "%s/postgresql", tmppath);
5690         return true;
5691 #endif
5692 }
5693
5694 /*
5695  * To keep the API consistent, the locking stubs are always provided, even
5696  * if they are not required.
5697  */
5698
5699 static void
5700 default_threadlock(int acquire)
5701 {
5702 #ifdef ENABLE_THREAD_SAFETY
5703 #ifndef WIN32
5704         static pthread_mutex_t singlethread_lock = PTHREAD_MUTEX_INITIALIZER;
5705 #else
5706         static pthread_mutex_t singlethread_lock = NULL;
5707         static long mutex_initlock = 0;
5708
5709         if (singlethread_lock == NULL)
5710         {
5711                 while (InterlockedExchange(&mutex_initlock, 1) == 1)
5712                          /* loop, another thread own the lock */ ;
5713                 if (singlethread_lock == NULL)
5714                 {
5715                         if (pthread_mutex_init(&singlethread_lock, NULL))
5716                                 PGTHREAD_ERROR("failed to initialize mutex");
5717                 }
5718                 InterlockedExchange(&mutex_initlock, 0);
5719         }
5720 #endif
5721         if (acquire)
5722         {
5723                 if (pthread_mutex_lock(&singlethread_lock))
5724                         PGTHREAD_ERROR("failed to lock mutex");
5725         }
5726         else
5727         {
5728                 if (pthread_mutex_unlock(&singlethread_lock))
5729                         PGTHREAD_ERROR("failed to unlock mutex");
5730         }
5731 #endif
5732 }
5733
5734 pgthreadlock_t
5735 PQregisterThreadLock(pgthreadlock_t newhandler)
5736 {
5737         pgthreadlock_t prev = pg_g_threadlock;
5738
5739         if (newhandler)
5740                 pg_g_threadlock = newhandler;
5741         else
5742                 pg_g_threadlock = default_threadlock;
5743
5744         return prev;
5745 }