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