Commit b035cb9d authored by Alvaro Herrera's avatar Alvaro Herrera

Accept postgres:// URIs in libpq connection functions

postgres:// URIs are an attempt to "stop the bleeding" in this general
area that has been said to occur due to external projects adopting their
own syntaxes.  The syntaxes supported by this patch:

 postgres://[user[:pwd]@][unix-socket][:port[/dbname]][?param1=value1&...]
 postgres://[user[:pwd]@][net-location][:port][/dbname][?param1=value1&...]

should be enough to cover most interesting cases without having to
resort to "param=value" pairs, but those are provided for the cases that
need them regardless.

libpq documentation has been shuffled around a bit, to avoid stuffing
all the format details into the PQconnectdbParams description, which was
already a bit overwhelming.  The list of keywords has moved to its own
subsection, and the details on the URI format live in another subsection.

This includes a simple test program, as requested in discussion, to
ensure that interesting corner cases continue to work appropriately in
the future.

Author: Alexander Shulgin
Some tweaking by Álvaro Herrera, Greg Smith, Daniel Farina, Peter Eisentraut
Reviewed by Robert Haas, Alexey Klyukin (offlist), Heikki Linnakangas,
Marko Kreen, and others

Oh, it also supports postgresql:// but that's probably just an accident.
parent 3769fa5f
...@@ -116,10 +116,16 @@ PGconn *PQconnectdbParams(const char * const *keywords, ...@@ -116,10 +116,16 @@ PGconn *PQconnectdbParams(const char * const *keywords,
programming. programming.
</para> </para>
<para>
The currently recognized parameter key words are listed in
<xref linkend="libpq-paramkeywords">.
</para>
<para> <para>
When <literal>expand_dbname</literal> is non-zero, the When <literal>expand_dbname</literal> is non-zero, the
<parameter>dbname</parameter> key word value is allowed to be recognized <parameter>dbname</parameter> key word value is allowed to be recognized
as a <parameter>conninfo</parameter> string. See below for details. as a connection string. More details on the possible formats appear in
<xref linkend="libpq-connstring">.
</para> </para>
<para> <para>
...@@ -130,1095 +136,1191 @@ PGconn *PQconnectdbParams(const char * const *keywords, ...@@ -130,1095 +136,1191 @@ PGconn *PQconnectdbParams(const char * const *keywords,
</para> </para>
<para> <para>
The currently recognized parameter key words are: If any parameter is unspecified, then the corresponding
environment variable (see <xref linkend="libpq-envars">)
is checked. If the environment variable is not set either,
then the indicated built-in defaults are used.
</para>
<variablelist>
<varlistentry id="libpq-connect-host" xreflabel="host">
<term><literal>host</literal></term>
<listitem>
<para> <para>
Name of host to connect to.<indexterm><primary>host name</></> In general key words are processed from the beginning of these arrays in index
If this begins with a slash, it specifies Unix-domain order. The effect of this is that when key words are repeated, the last processed
communication rather than TCP/IP communication; the value is the value is retained. Therefore, through careful placement of the
name of the directory in which the socket file is stored. The <parameter>dbname</parameter> key word, it is possible to determine what may
default behavior when <literal>host</literal> is not specified be overridden by a <parameter>conninfo</parameter> string, and what may not.
is to connect to a Unix-domain
socket<indexterm><primary>Unix domain socket</></> in
<filename>/tmp</filename> (or whatever socket directory was specified
when <productname>PostgreSQL</> was built). On machines without
Unix-domain sockets, the default is to connect to <literal>localhost</>.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-connect-hostaddr" xreflabel="hostaddr"> <varlistentry id="libpq-pqconnectdb">
<term><literal>hostaddr</literal></term> <term><function>PQconnectdb</function><indexterm><primary>PQconnectdb</></></term>
<listitem> <listitem>
<para> <para>
Numeric IP address of host to connect to. This should be in the Makes a new connection to the database server.
standard IPv4 address format, e.g., <literal>172.28.40.9</>. If
your machine supports IPv6, you can also use those addresses. <synopsis>
TCP/IP communication is PGconn *PQconnectdb(const char *conninfo);
always used when a nonempty string is specified for this parameter. </synopsis>
</para> </para>
<para> <para>
Using <literal>hostaddr</> instead of <literal>host</> allows the This function opens a new database connection using the parameters taken
application to avoid a host name look-up, which might be important from the string <literal>conninfo</literal>.
in applications with time constraints. However, a host name is
required for Kerberos, GSSAPI, or SSPI authentication
methods, as well as for <literal>verify-full</> SSL
certificate verification. The following rules are used:
<itemizedlist>
<listitem>
<para>
If <literal>host</> is specified without <literal>hostaddr</>,
a host name lookup occurs.
</para> </para>
</listitem>
<listitem>
<para> <para>
If <literal>hostaddr</> is specified without <literal>host</>, The passed string can be empty to use all default parameters, or it can
the value for <literal>hostaddr</> gives the server network address. contain one or more parameter settings separated by whitespace,
The connection attempt will fail if the authentication or it can contain a <acronym>URI</acronym>.
method requires a host name. See <xref linkend="libpq-connstring"> for details.
</para> </para>
</listitem> </listitem>
</varlistentry>
<varlistentry id="libpq-pqsetdblogin">
<term><function>PQsetdbLogin</function><indexterm><primary>PQsetdbLogin</></></term>
<listitem> <listitem>
<para> <para>
If both <literal>host</> and <literal>hostaddr</> are specified, Makes a new connection to the database server.
the value for <literal>hostaddr</> gives the server network address. <synopsis>
The value for <literal>host</> is ignored unless the PGconn *PQsetdbLogin(const char *pghost,
authentication method requires it, in which case it will be const char *pgport,
used as the host name. const char *pgoptions,
</para> const char *pgtty,
</listitem> const char *dbName,
</itemizedlist> const char *login,
Note that authentication is likely to fail if <literal>host</> const char *pwd);
is not the name of the server at network address <literal>hostaddr</>. </synopsis>
Also, note that <literal>host</> rather than <literal>hostaddr</>
is used to identify the connection in <filename>~/.pgpass</> (see
<xref linkend="libpq-pgpass">).
</para> </para>
<para> <para>
Without either a host name or host address, This is the predecessor of <function>PQconnectdb</function> with a fixed
<application>libpq</application> will connect using a set of parameters. It has the same functionality except that the
local Unix-domain socket; or on machines without Unix-domain missing parameters will always take on default values. Write <symbol>NULL</symbol> or an
sockets, it will attempt to connect to <literal>localhost</>. empty string for any one of the fixed parameters that is to be defaulted.
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-port" xreflabel="port">
<term><literal>port</literal></term>
<listitem>
<para> <para>
Port number to connect to at the server host, or socket file If the <parameter>dbName</parameter> contains
name extension for Unix-domain an <symbol>=</symbol> sign or has a valid connection <acronym>URI</acronym> prefix, it
connections.<indexterm><primary>port</></> is taken as a <parameter>conninfo</parameter> string in exactly the same way as
if it had been passed to <function>PQconnectdb</function>, and the remaining
parameters are then applied as specified for <function>PQconnectdbParams</>.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-connect-dbname" xreflabel="dbname"> <varlistentry id="libpq-pqsetdb">
<term><literal>dbname</literal></term> <term><function>PQsetdb</function><indexterm><primary>PQsetdb</></></term>
<listitem> <listitem>
<para> <para>
The database name. Defaults to be the same as the user name. Makes a new connection to the database server.
<synopsis>
PGconn *PQsetdb(char *pghost,
char *pgport,
char *pgoptions,
char *pgtty,
char *dbName);
</synopsis>
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-user" xreflabel="user">
<term><literal>user</literal></term>
<listitem>
<para> <para>
<productname>PostgreSQL</productname> user name to connect as. This is a macro that calls <function>PQsetdbLogin</function> with null pointers
Defaults to be the same as the operating system name of the user for the <parameter>login</> and <parameter>pwd</> parameters. It is provided
running the application. for backward compatibility with very old programs.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-connect-password" xreflabel="password"> <varlistentry id="libpq-pqconnectstartparams">
<term><literal>password</literal></term> <term><function>PQconnectStartParams</function><indexterm><primary>PQconnectStartParams</></></term>
<term><function>PQconnectStart</function><indexterm><primary>PQconnectStart</></></term>
<term><function>PQconnectPoll</function><indexterm><primary>PQconnectPoll</></></term>
<listitem> <listitem>
<para> <para>
Password to be used if the server demands password authentication. <indexterm><primary>nonblocking connection</primary></indexterm>
Make a connection to the database server in a nonblocking manner.
<synopsis>
PGconn *PQconnectStartParams(const char * const *keywords,
const char * const *values,
int expand_dbname);
PGconn *PQconnectStart(const char *conninfo);
PostgresPollingStatusType PQconnectPoll(PGconn *conn);
</synopsis>
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout">
<term><literal>connect_timeout</literal></term>
<listitem>
<para> <para>
Maximum wait for connection, in seconds (write as a decimal integer These three functions are used to open a connection to a database server such
string). Zero or not specified means wait indefinitely. It is not that your application's thread of execution is not blocked on remote I/O
recommended to use a timeout of less than 2 seconds. whilst doing so. The point of this approach is that the waits for I/O to
complete can occur in the application's main loop, rather than down inside
<function>PQconnectdbParams</> or <function>PQconnectdb</>, and so the
application can manage this operation in parallel with other activities.
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding">
<term><literal>client_encoding</literal></term>
<listitem>
<para> <para>
This sets the <varname>client_encoding</varname> With <function>PQconnectStartParams</function>, the database connection is made
configuration parameter for this connection. In addition to using the parameters taken from the <literal>keywords</literal> and
the values accepted by the corresponding server option, you <literal>values</literal> arrays, and controlled by <literal>expand_dbname</literal>,
can use <literal>auto</literal> to determine the right as described above for <function>PQconnectdbParams</function>.
encoding from the current locale in the client
(<envar>LC_CTYPE</envar> environment variable on Unix
systems).
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-options" xreflabel="options">
<term><literal>options</literal></term>
<listitem>
<para> <para>
Adds command-line options to send to the server at run-time. With <function>PQconnectStart</function>, the database connection is made
For example, setting this to <literal>-c geqo=off</> sets the using the parameters taken from the string <literal>conninfo</literal> as
session's value of the <varname>geqo</> parameter to described above for <function>PQconnectdb</function>.
<literal>off</>. For a detailed discussion of the available
options, consult <xref linkend="runtime-config">.
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-application-name" xreflabel="application_name"> <para>
<term><literal>application_name</literal></term> Neither <function>PQconnectStartParams</function> nor <function>PQconnectStart</function>
nor <function>PQconnectPoll</function> will block, so long as a number of
restrictions are met:
<itemizedlist>
<listitem> <listitem>
<para> <para>
Specifies a value for the <xref linkend="guc-application-name"> The <literal>hostaddr</> and <literal>host</> parameters are used appropriately to ensure that
configuration parameter. name and reverse name queries are not made. See the documentation of
these parameters in <xref linkend="libpq-paramkeywords"> for details.
</para> </para>
</listitem> </listitem>
</varlistentry>
<varlistentry id="libpq-connect-fallback-application-name" xreflabel="fallback_application_name">
<term><literal>fallback_application_name</literal></term>
<listitem> <listitem>
<para> <para>
Specifies a fallback value for the <xref If you call <function>PQtrace</function>, ensure that the stream object
linkend="guc-application-name"> configuration parameter. into which you trace will not block.
This value will be used if no value has been given for
<literal>application_name</> via a connection parameter or the
<envar>PGAPPNAME</envar> environment variable. Specifying
a fallback name is useful in generic utility programs that
wish to set a default application name but allow it to be
overridden by the user.
</para> </para>
</listitem> </listitem>
</varlistentry>
<varlistentry id="libpq-keepalives" xreflabel="keepalives">
<term><literal>keepalives</literal></term>
<listitem> <listitem>
<para> <para>
Controls whether client-side TCP keepalives are used. The default You ensure that the socket is in the appropriate state
value is 1, meaning on, but you can change this to 0, meaning off, before calling <function>PQconnectPoll</function>, as described below.
if keepalives are not wanted. This parameter is ignored for
connections made via a Unix-domain socket.
</para> </para>
</listitem> </listitem>
</varlistentry> </itemizedlist>
</para>
<varlistentry id="libpq-keepalives-idle" xreflabel="keepalives_idle">
<term><literal>keepalives_idle</literal></term>
<listitem>
<para> <para>
Controls the number of seconds of inactivity after which TCP should Note: use of <function>PQconnectStartParams</> is analogous to
send a keepalive message to the server. A value of zero uses the <function>PQconnectStart</> shown below.
system default. This parameter is ignored for connections made via a
Unix-domain socket, or if keepalives are disabled. It is only supported
on systems where the <symbol>TCP_KEEPIDLE</> or <symbol>TCP_KEEPALIVE</>
socket option is available, and on Windows; on other systems, it has no
effect.
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-keepalives-interval" xreflabel="keepalives_interval">
<term><literal>keepalives_interval</literal></term>
<listitem>
<para> <para>
Controls the number of seconds after which a TCP keepalive message To begin a nonblocking connection request, call <literal>conn = PQconnectStart("<replaceable>connection_info_string</>")</literal>.
that is not acknowledged by the server should be retransmitted. A If <varname>conn</varname> is null, then <application>libpq</> has been unable to allocate a new <structname>PGconn</>
value of zero uses the system default. This parameter is ignored for structure. Otherwise, a valid <structname>PGconn</> pointer is returned (though not yet
connections made via a Unix-domain socket, or if keepalives are disabled. representing a valid connection to the database). On return from
It is only supported on systems where the <symbol>TCP_KEEPINTVL</> <function>PQconnectStart</function>, call <literal>status = PQstatus(conn)</literal>. If <varname>status</varname> equals
socket option is available, and on Windows; on other systems, it has no <symbol>CONNECTION_BAD</symbol>, <function>PQconnectStart</function> has failed.
effect.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-keepalives-count" xreflabel="keepalives_count">
<term><literal>keepalives_count</literal></term>
<listitem>
<para>
Controls the number of TCP keepalives that can be lost before the
client's connection to the server is considered dead. A value of
zero uses the system default. This parameter is ignored for
connections made via a Unix-domain socket, or if keepalives are disabled.
It is only supported on systems where the <symbol>TCP_KEEPCNT</>
socket option is available; on other systems, it has no effect.
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-tty" xreflabel="tty">
<term><literal>tty</literal></term>
<listitem>
<para> <para>
Ignored (formerly, this specified where to send server debug output). If <function>PQconnectStart</> succeeds, the next stage is to poll
<application>libpq</> so that it can proceed with the connection sequence.
Use <function>PQsocket(conn)</function> to obtain the descriptor of the
socket underlying the database connection.
Loop thus: If <function>PQconnectPoll(conn)</function> last returned
<symbol>PGRES_POLLING_READING</symbol>, wait until the socket is ready to
read (as indicated by <function>select()</>, <function>poll()</>, or
similar system function).
Then call <function>PQconnectPoll(conn)</function> again.
Conversely, if <function>PQconnectPoll(conn)</function> last returned
<symbol>PGRES_POLLING_WRITING</symbol>, wait until the socket is ready
to write, then call <function>PQconnectPoll(conn)</function> again.
If you have yet to call
<function>PQconnectPoll</function>, i.e., just after the call to
<function>PQconnectStart</function>, behave as if it last returned
<symbol>PGRES_POLLING_WRITING</symbol>. Continue this loop until
<function>PQconnectPoll(conn)</function> returns
<symbol>PGRES_POLLING_FAILED</symbol>, indicating the connection procedure
has failed, or <symbol>PGRES_POLLING_OK</symbol>, indicating the connection
has been successfully made.
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-sslmode" xreflabel="sslmode">
<term><literal>sslmode</literal></term>
<listitem>
<para> <para>
This option determines whether or with what priority a secure At any time during connection, the status of the connection can be
<acronym>SSL</> TCP/IP connection will be negotiated with the checked by calling <function>PQstatus</>. If this call returns <symbol>CONNECTION_BAD</>, then the
server. There are six modes: connection procedure has failed; if the call returns <function>CONNECTION_OK</>, then the
connection is ready. Both of these states are equally detectable
from the return value of <function>PQconnectPoll</>, described above. Other states might also occur
during (and only during) an asynchronous connection procedure. These
indicate the current stage of the connection procedure and might be useful
to provide feedback to the user for example. These statuses are:
<variablelist> <variablelist>
<varlistentry> <varlistentry id="libpq-connection-started">
<term><literal>disable</literal></term> <term><symbol>CONNECTION_STARTED</symbol></term>
<listitem> <listitem>
<para> <para>
only try a non-<acronym>SSL</> connection Waiting for connection to be made.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry> <varlistentry id="libpq-connection-made">
<term><literal>allow</literal></term> <term><symbol>CONNECTION_MADE</symbol></term>
<listitem> <listitem>
<para> <para>
first try a non-<acronym>SSL</> connection; if that Connection OK; waiting to send.
fails, try an <acronym>SSL</> connection
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry> <varlistentry id="libpq-connection-awaiting-response">
<term><literal>prefer</literal> (default)</term> <term><symbol>CONNECTION_AWAITING_RESPONSE</symbol></term>
<listitem> <listitem>
<para> <para>
first try an <acronym>SSL</> connection; if that fails, Waiting for a response from the server.
try a non-<acronym>SSL</> connection
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry> <varlistentry id="libpq-connection-auth-ok">
<term><literal>require</literal></term> <term><symbol>CONNECTION_AUTH_OK</symbol></term>
<listitem> <listitem>
<para> <para>
only try an <acronym>SSL</> connection. If a root CA Received authentication; waiting for backend start-up to finish.
file is present, verify the certificate in the same way as
if <literal>verify-ca</literal> was specified
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry> <varlistentry id="libpq-connection-ssl-startup">
<term><literal>verify-ca</literal></term> <term><symbol>CONNECTION_SSL_STARTUP</symbol></term>
<listitem> <listitem>
<para> <para>
only try an <acronym>SSL</> connection, and verify that Negotiating SSL encryption.
the server certificate is issued by a trusted
certificate authority (<acronym>CA</>)
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry> <varlistentry id="libpq-connection-setenv">
<term><literal>verify-full</literal></term> <term><symbol>CONNECTION_SETENV</symbol></term>
<listitem> <listitem>
<para> <para>
only try an <acronym>SSL</> connection, verify that the Negotiating environment-driven parameter settings.
server certificate is issued by a
trusted <acronym>CA</> and that the server host name
matches that in the certificate
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
</variablelist> </variablelist>
See <xref linkend="libpq-ssl"> for a detailed description of how Note that, although these constants will remain (in order to maintain
these options work. compatibility), an application should never rely upon these occurring in a
particular order, or at all, or on the status always being one of these
documented values. An application might do something like this:
<programlisting>
switch(PQstatus(conn))
{
case CONNECTION_STARTED:
feedback = "Connecting...";
break;
case CONNECTION_MADE:
feedback = "Connected to server...";
break;
.
.
.
default:
feedback = "Connecting...";
}
</programlisting>
</para> </para>
<para> <para>
<literal>sslmode</> is ignored for Unix domain socket The <literal>connect_timeout</literal> connection parameter is ignored
communication. when using <function>PQconnectPoll</function>; it is the application's
If <productname>PostgreSQL</> is compiled without SSL support, responsibility to decide whether an excessive amount of time has elapsed.
using options <literal>require</>, <literal>verify-ca</>, or Otherwise, <function>PQconnectStart</function> followed by a
<literal>verify-full</> will cause an error, while <function>PQconnectPoll</function> loop is equivalent to
options <literal>allow</> and <literal>prefer</> will be <function>PQconnectdb</function>.
accepted but <application>libpq</> will not actually attempt </para>
an <acronym>SSL</>
connection.<indexterm><primary>SSL</><secondary <para>
sortas="libpq">with libpq</></indexterm> Note that if <function>PQconnectStart</function> returns a non-null pointer, you must call
<function>PQfinish</function> when you are finished with it, in order to dispose of
the structure and any associated memory blocks. This must be done even if
the connection attempt fails or is abandoned.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-connect-requiressl" xreflabel="requiressl"> <varlistentry id="libpq-pqconndefaults">
<term><literal>requiressl</literal></term> <term><function>PQconndefaults</function><indexterm><primary>PQconndefaults</></></term>
<listitem> <listitem>
<para> <para>
This option is deprecated in favor of the <literal>sslmode</> Returns the default connection options.
setting. <synopsis>
PQconninfoOption *PQconndefaults(void);
typedef struct
{
char *keyword; /* The keyword of the option */
char *envvar; /* Fallback environment variable name */
char *compiled; /* Fallback compiled in default value */
char *val; /* Option's current value, or NULL */
char *label; /* Label for field in connect dialog */
char *dispchar; /* Indicates how to display this field
in a connect dialog. Values are:
"" Display entered value as is
"*" Password field - hide value
"D" Debug option - don't show by default */
int dispsize; /* Field size in characters for dialog */
} PQconninfoOption;
</synopsis>
</para> </para>
<para> <para>
If set to 1, an <acronym>SSL</acronym> connection to the server Returns a connection options array. This can be used to determine
is required (this is equivalent to <literal>sslmode</> all possible <function>PQconnectdb</function> options and their
<literal>require</>). <application>libpq</> will then refuse current default values. The return value points to an array of
to connect if the server does not accept an <structname>PQconninfoOption</structname> structures, which ends
<acronym>SSL</acronym> connection. If set to 0 (default), with an entry having a null <structfield>keyword</> pointer. The
<application>libpq</> will negotiate the connection type with null pointer is returned if memory could not be allocated. Note that
the server (equivalent to <literal>sslmode</> the current default values (<structfield>val</structfield> fields)
<literal>prefer</>). This option is only available if will depend on environment variables and other context. Callers
<productname>PostgreSQL</> is compiled with SSL support. must treat the connection options data as read-only.
</para> </para>
<para>
After processing the options array, free it by passing it to
<function>PQconninfoFree</function>. If this is not done, a small amount of memory
is leaked for each call to <function>PQconndefaults</function>.
</para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-connect-sslcompression" xreflabel="sslcompression"> <varlistentry id="libpq-pqconninfoparse">
<term><literal>sslcompression</literal></term> <term><function>PQconninfoParse</function><indexterm><primary>PQconninfoParse</></></term>
<listitem> <listitem>
<para> <para>
If set to 1 (default), data sent over SSL connections will be Returns parsed connection options from the provided connection string.
compressed (this requires <productname>OpenSSL</> version
0.9.8 or later). <synopsis>
If set to 0, compression will be disabled (this requires PQconninfoOption *PQconninfoParse(const char *conninfo, char **errmsg);
<productname>OpenSSL</> 1.0.0 or later). </synopsis>
This parameter is ignored if a connection without SSL is made,
or if the version of <productname>OpenSSL</> used does not support
it.
</para> </para>
<para> <para>
Compression uses CPU time, but can improve throughput if Parses a connection string and returns the resulting options as an
the network is the bottleneck. array; or returns <symbol>NULL</> if there is a problem with the connection
Disabling compression can improve response time and throughput string. This function can be used to extract
if CPU performance is the limiting factor. the <function>PQconnectdb</function> options in the provided
connection string. The return value points to an array of
<structname>PQconninfoOption</structname> structures, which ends
with an entry having a null <structfield>keyword</> pointer.
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-sslcert" xreflabel="sslcert">
<term><literal>sslcert</literal></term>
<listitem>
<para> <para>
This parameter specifies the file name of the client SSL All legal options will be present in the result array, but the
certificate, replacing the default <literal>PQconninfoOption</literal> for any option not present
<filename>~/.postgresql/postgresql.crt</>. in the connection string will have <literal>val</literal> set to
This parameter is ignored if an SSL connection is not made. <literal>NULL</literal>; default values are not inserted.
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-sslkey" xreflabel="sslkey">
<term><literal>sslkey</literal></term>
<listitem>
<para> <para>
This parameter specifies the location for the secret key used for If <literal>errmsg</> is not <symbol>NULL</>, then <literal>*errmsg</> is set
the client certificate. It can either specify a file name that will to <symbol>NULL</> on success, else to a <function>malloc</>'d error string explaining
be used instead of the default the problem. (It is also possible for <literal>*errmsg</> to be
<filename>~/.postgresql/postgresql.key</>, or it can specify a key set to <symbol>NULL</> and the function to return <symbol>NULL</>;
obtained from an external <quote>engine</> (engines are this indicates an out-of-memory condition.)
<productname>OpenSSL</> loadable modules). An external engine
specification should consist of a colon-separated engine name and
an engine-specific key identifier. This parameter is ignored if an
SSL connection is not made.
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-sslrootcert" xreflabel="sslrootcert">
<term><literal>sslrootcert</literal></term>
<listitem>
<para> <para>
This parameter specifies the name of a file containing SSL After processing the options array, free it by passing it to
certificate authority (<acronym>CA</>) certificate(s). <function>PQconninfoFree</function>. If this is not done, some memory
If the file exists, the server's certificate will be verified is leaked for each call to <function>PQconninfoParse</function>.
to be signed by one of these authorities. The default is Conversely, if an error occurs and <literal>errmsg</> is not <symbol>NULL</>,
<filename>~/.postgresql/root.crt</>. be sure to free the error string using <function>PQfreemem</>.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-connect-sslcrl" xreflabel="sslcrl"> <varlistentry id="libpq-pqfinish">
<term><literal>sslcrl</literal></term> <term><function>PQfinish</function><indexterm><primary>PQfinish</></></term>
<listitem> <listitem>
<para> <para>
This parameter specifies the file name of the SSL certificate Closes the connection to the server. Also frees
revocation list (CRL). Certificates listed in this file, if it memory used by the <structname>PGconn</structname> object.
exists, will be rejected while attempting to authenticate the <synopsis>
server's certificate. The default is void PQfinish(PGconn *conn);
<filename>~/.postgresql/root.crl</>. </synopsis>
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-requirepeer" xreflabel="requirepeer">
<term><literal>requirepeer</literal></term>
<listitem>
<para> <para>
This parameter specifies the operating-system user name of the Note that even if the server connection attempt fails (as
server, for example <literal>requirepeer=postgres</literal>. indicated by <function>PQstatus</function>), the application should call <function>PQfinish</function>
When making a Unix-domain socket connection, if this to free the memory used by the <structname>PGconn</structname> object.
parameter is set, the client checks at the beginning of the The <structname>PGconn</> pointer must not be used again after
connection that the server process is running under the specified <function>PQfinish</function> has been called.
user name; if it is not, the connection is aborted with an error.
This parameter can be used to provide server authentication similar
to that available with SSL certificates on TCP/IP connections.
(Note that if the Unix-domain socket is in
<filename>/tmp</filename> or another publicly writable location,
any user could start a server listening there. Use this parameter
to ensure that you are connected to a server run by a trusted user.)
This option is only supported on platforms for which the
<literal>peer</> authentication method is implemented; see
<xref linkend="auth-peer">.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-connect-krbsrvname" xreflabel="krbsrvname"> <varlistentry id="libpq-pqreset">
<term><literal>krbsrvname</literal></term> <term><function>PQreset</function><indexterm><primary>PQreset</></></term>
<listitem> <listitem>
<para> <para>
Kerberos service name to use when authenticating with Kerberos 5 Resets the communication channel to the server.
or GSSAPI. <synopsis>
This must match the service name specified in the server void PQreset(PGconn *conn);
configuration for Kerberos authentication to succeed. (See also </synopsis>
<xref linkend="kerberos-auth"> and <xref linkend="gssapi-auth">.)
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-gsslib" xreflabel="gsslib">
<term><literal>gsslib</literal></term>
<listitem>
<para> <para>
GSS library to use for GSSAPI authentication. Only used on Windows. This function will close the connection
Set to <literal>gssapi</literal> to force libpq to use the GSSAPI to the server and attempt to reestablish a new
library for authentication instead of the default SSPI. connection to the same server, using all the same
parameters previously used. This might be useful for
error recovery if a working connection is lost.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-connect-service" xreflabel="service"> <varlistentry id="libpq-pqresetstart">
<term><literal>service</literal></term> <term><function>PQresetStart</function><indexterm><primary>PQresetStart</></></term>
<term><function>PQresetPoll</function><indexterm><primary>PQresetPoll</></></term>
<listitem> <listitem>
<para> <para>
Service name to use for additional parameters. It specifies a service Reset the communication channel to the server, in a nonblocking manner.
name in <filename>pg_service.conf</filename> that holds additional connection parameters.
This allows applications to specify only a service name so connection parameters
can be centrally maintained. See <xref linkend="libpq-pgservice">.
</para>
</listitem>
</varlistentry>
</variablelist>
If any parameter is unspecified, then the corresponding <synopsis>
environment variable (see <xref linkend="libpq-envars">) int PQresetStart(PGconn *conn);
is checked. If the environment variable is not set either,
then the indicated built-in defaults are used. PostgresPollingStatusType PQresetPoll(PGconn *conn);
</synopsis>
</para> </para>
<para> <para>
If <literal>expand_dbname</literal> is non-zero and These functions will close the connection to the server and attempt to
<parameter>dbname</parameter> contains an <symbol>=</symbol> sign, it reestablish a new connection to the same server, using all the same
is taken as a <parameter>conninfo</parameter> string in exactly the same way as parameters previously used. This can be useful for error recovery if a
if it had been passed to <function>PQconnectdb</function>(see below). Previously working connection is lost. They differ from <function>PQreset</function> (above) in that they
processed key words will be overridden by key words in the act in a nonblocking manner. These functions suffer from the same
<parameter>conninfo</parameter> string. restrictions as <function>PQconnectStartParams</>, <function>PQconnectStart</>
and <function>PQconnectPoll</>.
</para> </para>
<para> <para>
In general key words are processed from the beginning of these arrays in index To initiate a connection reset, call
order. The effect of this is that when key words are repeated, the last processed <function>PQresetStart</function>. If it returns 0, the reset has
value is retained. Therefore, through careful placement of the failed. If it returns 1, poll the reset using
<parameter>dbname</parameter> key word, it is possible to determine what may <function>PQresetPoll</function> in exactly the same way as you
be overridden by a <parameter>conninfo</parameter> string, and what may not. would create the connection using <function>PQconnectPoll</function>.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-pqconnectdb"> <varlistentry id="libpq-pqpingparams">
<term><function>PQconnectdb</function><indexterm><primary>PQconnectdb</></></term> <term><function>PQpingParams</function><indexterm><primary>PQpingParams</></></term>
<listitem> <listitem>
<para> <para>
Makes a new connection to the database server. <function>PQpingParams</function> reports the status of the
server. It accepts connection parameters identical to those of
<function>PQconnectdbParams</>, described above. It is not, however,
necessary to supply correct user name, password, or database name
values to obtain the server status.
<synopsis> <synopsis>
PGconn *PQconnectdb(const char *conninfo); PGPing PQpingParams(const char * const *keywords,
const char * const *values,
int expand_dbname);
</synopsis> </synopsis>
</para>
<para> The function returns one of the following values:
This function opens a new database connection using the parameters taken
from the string <literal>conninfo</literal>.
</para>
<variablelist>
<varlistentry id="libpq-pqpingparams-pqping-ok">
<term><literal>PQPING_OK</literal></term>
<listitem>
<para> <para>
The passed string can be empty to use all default parameters, or it can The server is running and appears to be accepting connections.
contain one or more parameter settings separated by whitespace.
Each parameter setting is in the form <literal>keyword = value</literal>.
Spaces around the equal sign are optional. To write an empty value,
or a value containing spaces, surround it with single quotes, e.g.,
<literal>keyword = 'a value'</literal>. Single quotes and backslashes
within the value must be escaped with a backslash, i.e.,
<literal>\'</literal> and <literal>\\</literal>.
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-pqpingparams-pqping-reject">
<term><literal>PQPING_REJECT</literal></term>
<listitem>
<para> <para>
The currently recognized parameter key words are the same as above. The server is running but is in a state that disallows connections
(startup, shutdown, or crash recovery).
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-pqsetdblogin"> <varlistentry id="libpq-pqpingparams-pqping-no-response">
<term><function>PQsetdbLogin</function><indexterm><primary>PQsetdbLogin</></></term> <term><literal>PQPING_NO_RESPONSE</literal></term>
<listitem> <listitem>
<para> <para>
Makes a new connection to the database server. The server could not be contacted. This might indicate that the
<synopsis> server is not running, or that there is something wrong with the
PGconn *PQsetdbLogin(const char *pghost, given connection parameters (for example, wrong port number), or
const char *pgport, that there is a network connectivity problem (for example, a
const char *pgoptions, firewall blocking the connection request).
const char *pgtty,
const char *dbName,
const char *login,
const char *pwd);
</synopsis>
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-pqpingparams-pqping-no-attempt">
<term><literal>PQPING_NO_ATTEMPT</literal></term>
<listitem>
<para> <para>
This is the predecessor of <function>PQconnectdb</function> with a fixed No attempt was made to contact the server, because the supplied
set of parameters. It has the same functionality except that the parameters were obviously incorrect or there was some client-side
missing parameters will always take on default values. Write <symbol>NULL</symbol> or an problem (for example, out of memory).
empty string for any one of the fixed parameters that is to be defaulted.
</para> </para>
</listitem>
</varlistentry>
</variablelist>
<para>
If the <parameter>dbName</parameter> contains an <symbol>=</symbol> sign, it
is taken as a <parameter>conninfo</parameter> string in exactly the same way as
if it had been passed to <function>PQconnectdb</function>, and the remaining
parameters are then applied as above.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-pqsetdb"> <varlistentry id="libpq-pqping">
<term><function>PQsetdb</function><indexterm><primary>PQsetdb</></></term> <term><function>PQping</function><indexterm><primary>PQping</></></term>
<listitem> <listitem>
<para> <para>
Makes a new connection to the database server. <function>PQping</function> reports the status of the
server. It accepts connection parameters identical to those of
<function>PQconnectdb</>, described above. It is not, however,
necessary to supply correct user name, password, or database name
values to obtain the server status.
<synopsis> <synopsis>
PGconn *PQsetdb(char *pghost, PGPing PQping(const char *conninfo);
char *pgport,
char *pgoptions,
char *pgtty,
char *dbName);
</synopsis> </synopsis>
</para> </para>
<para> <para>
This is a macro that calls <function>PQsetdbLogin</function> with null pointers The return values are the same as for <function>PQpingParams</>.
for the <parameter>login</> and <parameter>pwd</> parameters. It is provided
for backward compatibility with very old programs.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-pqconnectstartparams"> </variablelist>
<term><function>PQconnectStartParams</function><indexterm><primary>PQconnectStartParams</></></term>
<term><function>PQconnectStart</function><indexterm><primary>PQconnectStart</></></term>
<term><function>PQconnectPoll</function><indexterm><primary>PQconnectPoll</></></term>
<listitem>
<para>
<indexterm><primary>nonblocking connection</primary></indexterm>
Make a connection to the database server in a nonblocking manner.
<synopsis>
PGconn *PQconnectStartParams(const char * const *keywords,
const char * const *values,
int expand_dbname);
PGconn *PQconnectStart(const char *conninfo);
PostgresPollingStatusType PQconnectPoll(PGconn *conn);
</synopsis>
</para> </para>
<sect2 id="libpq-paramkeywords">
<title>Parameter Key Words</title>
<para> <para>
These three functions are used to open a connection to a database server such The currently recognized parameter key words are:
that your application's thread of execution is not blocked on remote I/O
whilst doing so. The point of this approach is that the waits for I/O to
complete can occur in the application's main loop, rather than down inside
<function>PQconnectdbParams</> or <function>PQconnectdb</>, and so the
application can manage this operation in parallel with other activities.
</para>
<variablelist>
<varlistentry id="libpq-connect-host" xreflabel="host">
<term><literal>host</literal></term>
<listitem>
<para> <para>
With <function>PQconnectStartParams</function>, the database connection is made Name of host to connect to.<indexterm><primary>host name</></>
using the parameters taken from the <literal>keywords</literal> and If this begins with a slash, it specifies Unix-domain
<literal>values</literal> arrays, and controlled by <literal>expand_dbname</literal>, communication rather than TCP/IP communication; the value is the
as described above for <function>PQconnectdbParams</function>. name of the directory in which the socket file is stored. The
default behavior when <literal>host</literal> is not specified
is to connect to a Unix-domain
socket<indexterm><primary>Unix domain socket</></> in
<filename>/tmp</filename> (or whatever socket directory was specified
when <productname>PostgreSQL</> was built). On machines without
Unix-domain sockets, the default is to connect to <literal>localhost</>.
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-hostaddr" xreflabel="hostaddr">
<term><literal>hostaddr</literal></term>
<listitem>
<para> <para>
With <function>PQconnectStart</function>, the database connection is made Numeric IP address of host to connect to. This should be in the
using the parameters taken from the string <literal>conninfo</literal> as standard IPv4 address format, e.g., <literal>172.28.40.9</>. If
described above for <function>PQconnectdb</function>. your machine supports IPv6, you can also use those addresses.
TCP/IP communication is
always used when a nonempty string is specified for this parameter.
</para> </para>
<para> <para>
Neither <function>PQconnectStartParams</function> nor <function>PQconnectStart</function> Using <literal>hostaddr</> instead of <literal>host</> allows the
nor <function>PQconnectPoll</function> will block, so long as a number of application to avoid a host name look-up, which might be important
restrictions are met: in applications with time constraints. However, a host name is
required for Kerberos, GSSAPI, or SSPI authentication
methods, as well as for <literal>verify-full</> SSL
certificate verification. The following rules are used:
<itemizedlist> <itemizedlist>
<listitem> <listitem>
<para> <para>
The <literal>hostaddr</> and <literal>host</> parameters are used appropriately to ensure that If <literal>host</> is specified without <literal>hostaddr</>,
name and reverse name queries are not made. See the documentation of a host name lookup occurs.
these parameters under <function>PQconnectdbParams</function> above for details.
</para> </para>
</listitem> </listitem>
<listitem> <listitem>
<para> <para>
If you call <function>PQtrace</function>, ensure that the stream object If <literal>hostaddr</> is specified without <literal>host</>,
into which you trace will not block. the value for <literal>hostaddr</> gives the server network address.
The connection attempt will fail if the authentication
method requires a host name.
</para> </para>
</listitem> </listitem>
<listitem> <listitem>
<para> <para>
You ensure that the socket is in the appropriate state If both <literal>host</> and <literal>hostaddr</> are specified,
before calling <function>PQconnectPoll</function>, as described below. the value for <literal>hostaddr</> gives the server network address.
The value for <literal>host</> is ignored unless the
authentication method requires it, in which case it will be
used as the host name.
</para> </para>
</listitem> </listitem>
</itemizedlist> </itemizedlist>
Note that authentication is likely to fail if <literal>host</>
is not the name of the server at network address <literal>hostaddr</>.
Also, note that <literal>host</> rather than <literal>hostaddr</>
is used to identify the connection in <filename>~/.pgpass</> (see
<xref linkend="libpq-pgpass">).
</para> </para>
<para> <para>
Note: use of <function>PQconnectStartParams</> is analogous to Without either a host name or host address,
<function>PQconnectStart</> shown below. <application>libpq</application> will connect using a
local Unix-domain socket; or on machines without Unix-domain
sockets, it will attempt to connect to <literal>localhost</>.
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-port" xreflabel="port">
<term><literal>port</literal></term>
<listitem>
<para> <para>
To begin a nonblocking connection request, call <literal>conn = PQconnectStart("<replaceable>connection_info_string</>")</literal>. Port number to connect to at the server host, or socket file
If <varname>conn</varname> is null, then <application>libpq</> has been unable to allocate a new <structname>PGconn</> name extension for Unix-domain
structure. Otherwise, a valid <structname>PGconn</> pointer is returned (though not yet connections.<indexterm><primary>port</></>
representing a valid connection to the database). On return from
<function>PQconnectStart</function>, call <literal>status = PQstatus(conn)</literal>. If <varname>status</varname> equals
<symbol>CONNECTION_BAD</symbol>, <function>PQconnectStart</function> has failed.
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-dbname" xreflabel="dbname">
<term><literal>dbname</literal></term>
<listitem>
<para> <para>
If <function>PQconnectStart</> succeeds, the next stage is to poll The database name. Defaults to be the same as the user name.
<application>libpq</> so that it can proceed with the connection sequence. In certain contexts, the value is checked for extended
Use <function>PQsocket(conn)</function> to obtain the descriptor of the formats; see <xref linkend="libpq-connstring"> for more details on
socket underlying the database connection. those.
Loop thus: If <function>PQconnectPoll(conn)</function> last returned </para>
<symbol>PGRES_POLLING_READING</symbol>, wait until the socket is ready to </listitem>
read (as indicated by <function>select()</>, <function>poll()</>, or </varlistentry>
similar system function).
Then call <function>PQconnectPoll(conn)</function> again. <varlistentry id="libpq-connect-user" xreflabel="user">
Conversely, if <function>PQconnectPoll(conn)</function> last returned <term><literal>user</literal></term>
<symbol>PGRES_POLLING_WRITING</symbol>, wait until the socket is ready <listitem>
to write, then call <function>PQconnectPoll(conn)</function> again. <para>
If you have yet to call <productname>PostgreSQL</productname> user name to connect as.
<function>PQconnectPoll</function>, i.e., just after the call to Defaults to be the same as the operating system name of the user
<function>PQconnectStart</function>, behave as if it last returned running the application.
<symbol>PGRES_POLLING_WRITING</symbol>. Continue this loop until
<function>PQconnectPoll(conn)</function> returns
<symbol>PGRES_POLLING_FAILED</symbol>, indicating the connection procedure
has failed, or <symbol>PGRES_POLLING_OK</symbol>, indicating the connection
has been successfully made.
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-password" xreflabel="password">
<term><literal>password</literal></term>
<listitem>
<para> <para>
At any time during connection, the status of the connection can be Password to be used if the server demands password authentication.
checked by calling <function>PQstatus</>. If this call returns <symbol>CONNECTION_BAD</>, then the </para>
connection procedure has failed; if the call returns <function>CONNECTION_OK</>, then the </listitem>
connection is ready. Both of these states are equally detectable </varlistentry>
from the return value of <function>PQconnectPoll</>, described above. Other states might also occur
during (and only during) an asynchronous connection procedure. These
indicate the current stage of the connection procedure and might be useful
to provide feedback to the user for example. These statuses are:
<variablelist> <varlistentry id="libpq-connect-connect-timeout" xreflabel="connect_timeout">
<varlistentry id="libpq-connection-started"> <term><literal>connect_timeout</literal></term>
<term><symbol>CONNECTION_STARTED</symbol></term>
<listitem> <listitem>
<para> <para>
Waiting for connection to be made. Maximum wait for connection, in seconds (write as a decimal integer
string). Zero or not specified means wait indefinitely. It is not
recommended to use a timeout of less than 2 seconds.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-connection-made"> <varlistentry id="libpq-connect-client-encoding" xreflabel="client_encoding">
<term><symbol>CONNECTION_MADE</symbol></term> <term><literal>client_encoding</literal></term>
<listitem> <listitem>
<para> <para>
Connection OK; waiting to send. This sets the <varname>client_encoding</varname>
configuration parameter for this connection. In addition to
the values accepted by the corresponding server option, you
can use <literal>auto</literal> to determine the right
encoding from the current locale in the client
(<envar>LC_CTYPE</envar> environment variable on Unix
systems).
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-connection-awaiting-response"> <varlistentry id="libpq-connect-options" xreflabel="options">
<term><symbol>CONNECTION_AWAITING_RESPONSE</symbol></term> <term><literal>options</literal></term>
<listitem> <listitem>
<para> <para>
Waiting for a response from the server. Adds command-line options to send to the server at run-time.
For example, setting this to <literal>-c geqo=off</> sets the
session's value of the <varname>geqo</> parameter to
<literal>off</>. For a detailed discussion of the available
options, consult <xref linkend="runtime-config">.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-connection-auth-ok"> <varlistentry id="libpq-connect-application-name" xreflabel="application_name">
<term><symbol>CONNECTION_AUTH_OK</symbol></term> <term><literal>application_name</literal></term>
<listitem> <listitem>
<para> <para>
Received authentication; waiting for backend start-up to finish. Specifies a value for the <xref linkend="guc-application-name">
configuration parameter.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-connection-ssl-startup"> <varlistentry id="libpq-connect-fallback-application-name" xreflabel="fallback_application_name">
<term><symbol>CONNECTION_SSL_STARTUP</symbol></term> <term><literal>fallback_application_name</literal></term>
<listitem> <listitem>
<para> <para>
Negotiating SSL encryption. Specifies a fallback value for the <xref
linkend="guc-application-name"> configuration parameter.
This value will be used if no value has been given for
<literal>application_name</> via a connection parameter or the
<envar>PGAPPNAME</envar> environment variable. Specifying
a fallback name is useful in generic utility programs that
wish to set a default application name but allow it to be
overridden by the user.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-connection-setenv"> <varlistentry id="libpq-keepalives" xreflabel="keepalives">
<term><symbol>CONNECTION_SETENV</symbol></term> <term><literal>keepalives</literal></term>
<listitem> <listitem>
<para> <para>
Negotiating environment-driven parameter settings. Controls whether client-side TCP keepalives are used. The default
value is 1, meaning on, but you can change this to 0, meaning off,
if keepalives are not wanted. This parameter is ignored for
connections made via a Unix-domain socket.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
</variablelist>
Note that, although these constants will remain (in order to maintain <varlistentry id="libpq-keepalives-idle" xreflabel="keepalives_idle">
compatibility), an application should never rely upon these occurring in a <term><literal>keepalives_idle</literal></term>
particular order, or at all, or on the status always being one of these <listitem>
documented values. An application might do something like this: <para>
<programlisting> Controls the number of seconds of inactivity after which TCP should
switch(PQstatus(conn)) send a keepalive message to the server. A value of zero uses the
{ system default. This parameter is ignored for connections made via a
case CONNECTION_STARTED: Unix-domain socket, or if keepalives are disabled. It is only supported
feedback = "Connecting..."; on systems where the <symbol>TCP_KEEPIDLE</> or <symbol>TCP_KEEPALIVE</>
break; socket option is available, and on Windows; on other systems, it has no
effect.
</para>
</listitem>
</varlistentry>
case CONNECTION_MADE: <varlistentry id="libpq-keepalives-interval" xreflabel="keepalives_interval">
feedback = "Connected to server..."; <term><literal>keepalives_interval</literal></term>
break; <listitem>
. <para>
. Controls the number of seconds after which a TCP keepalive message
. that is not acknowledged by the server should be retransmitted. A
default: value of zero uses the system default. This parameter is ignored for
feedback = "Connecting..."; connections made via a Unix-domain socket, or if keepalives are disabled.
} It is only supported on systems where the <symbol>TCP_KEEPINTVL</>
</programlisting> socket option is available, and on Windows; on other systems, it has no
effect.
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-keepalives-count" xreflabel="keepalives_count">
<term><literal>keepalives_count</literal></term>
<listitem>
<para> <para>
The <literal>connect_timeout</literal> connection parameter is ignored Controls the number of TCP keepalives that can be lost before the
when using <function>PQconnectPoll</function>; it is the application's client's connection to the server is considered dead. A value of
responsibility to decide whether an excessive amount of time has elapsed. zero uses the system default. This parameter is ignored for
Otherwise, <function>PQconnectStart</function> followed by a connections made via a Unix-domain socket, or if keepalives are disabled.
<function>PQconnectPoll</function> loop is equivalent to It is only supported on systems where the <symbol>TCP_KEEPCNT</>
<function>PQconnectdb</function>. socket option is available; on other systems, it has no effect.
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-tty" xreflabel="tty">
<term><literal>tty</literal></term>
<listitem>
<para> <para>
Note that if <function>PQconnectStart</function> returns a non-null pointer, you must call Ignored (formerly, this specified where to send server debug output).
<function>PQfinish</function> when you are finished with it, in order to dispose of
the structure and any associated memory blocks. This must be done even if
the connection attempt fails or is abandoned.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-pqconndefaults"> <varlistentry id="libpq-connect-sslmode" xreflabel="sslmode">
<term><function>PQconndefaults</function><indexterm><primary>PQconndefaults</></></term> <term><literal>sslmode</literal></term>
<listitem> <listitem>
<para> <para>
Returns the default connection options. This option determines whether or with what priority a secure
<synopsis> <acronym>SSL</> TCP/IP connection will be negotiated with the
PQconninfoOption *PQconndefaults(void); server. There are six modes:
typedef struct <variablelist>
{ <varlistentry>
char *keyword; /* The keyword of the option */ <term><literal>disable</literal></term>
char *envvar; /* Fallback environment variable name */ <listitem>
char *compiled; /* Fallback compiled in default value */ <para>
char *val; /* Option's current value, or NULL */ only try a non-<acronym>SSL</> connection
char *label; /* Label for field in connect dialog */
char *dispchar; /* Indicates how to display this field
in a connect dialog. Values are:
"" Display entered value as is
"*" Password field - hide value
"D" Debug option - don't show by default */
int dispsize; /* Field size in characters for dialog */
} PQconninfoOption;
</synopsis>
</para> </para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>allow</literal></term>
<listitem>
<para> <para>
Returns a connection options array. This can be used to determine first try a non-<acronym>SSL</> connection; if that
all possible <function>PQconnectdb</function> options and their fails, try an <acronym>SSL</> connection
current default values. The return value points to an array of
<structname>PQconninfoOption</structname> structures, which ends
with an entry having a null <structfield>keyword</> pointer. The
null pointer is returned if memory could not be allocated. Note that
the current default values (<structfield>val</structfield> fields)
will depend on environment variables and other context. Callers
must treat the connection options data as read-only.
</para> </para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>prefer</literal> (default)</term>
<listitem>
<para> <para>
After processing the options array, free it by passing it to first try an <acronym>SSL</> connection; if that fails,
<function>PQconninfoFree</function>. If this is not done, a small amount of memory try a non-<acronym>SSL</> connection
is leaked for each call to <function>PQconndefaults</function>.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-pqconninfoparse"> <varlistentry>
<term><function>PQconninfoParse</function><indexterm><primary>PQconninfoParse</></></term> <term><literal>require</literal></term>
<listitem> <listitem>
<para> <para>
Returns parsed connection options from the provided connection string. only try an <acronym>SSL</> connection. If a root CA
file is present, verify the certificate in the same way as
<synopsis> if <literal>verify-ca</literal> was specified
PQconninfoOption *PQconninfoParse(const char *conninfo, char **errmsg);
</synopsis>
</para> </para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>verify-ca</literal></term>
<listitem>
<para> <para>
Parses a connection string and returns the resulting options as an only try an <acronym>SSL</> connection, and verify that
array; or returns <symbol>NULL</> if there is a problem with the connection the server certificate is issued by a trusted
string. This function can be used to extract certificate authority (<acronym>CA</>)
the <function>PQconnectdb</function> options in the provided
connection string. The return value points to an array of
<structname>PQconninfoOption</structname> structures, which ends
with an entry having a null <structfield>keyword</> pointer.
</para> </para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>verify-full</literal></term>
<listitem>
<para> <para>
All legal options will be present in the result array, but the only try an <acronym>SSL</> connection, verify that the
<literal>PQconninfoOption</literal> for any option not present server certificate is issued by a
in the connection string will have <literal>val</literal> set to trusted <acronym>CA</> and that the server host name
<literal>NULL</literal>; default values are not inserted. matches that in the certificate
</para> </para>
</listitem>
</varlistentry>
</variablelist>
<para> See <xref linkend="libpq-ssl"> for a detailed description of how
If <literal>errmsg</> is not <symbol>NULL</>, then <literal>*errmsg</> is set these options work.
to <symbol>NULL</> on success, else to a <function>malloc</>'d error string explaining
the problem. (It is also possible for <literal>*errmsg</> to be
set to <symbol>NULL</> and the function to return <symbol>NULL</>;
this indicates an out-of-memory condition.)
</para> </para>
<para> <para>
After processing the options array, free it by passing it to <literal>sslmode</> is ignored for Unix domain socket
<function>PQconninfoFree</function>. If this is not done, some memory communication.
is leaked for each call to <function>PQconninfoParse</function>. If <productname>PostgreSQL</> is compiled without SSL support,
Conversely, if an error occurs and <literal>errmsg</> is not <symbol>NULL</>, using options <literal>require</>, <literal>verify-ca</>, or
be sure to free the error string using <function>PQfreemem</>. <literal>verify-full</> will cause an error, while
options <literal>allow</> and <literal>prefer</> will be
accepted but <application>libpq</> will not actually attempt
an <acronym>SSL</>
connection.<indexterm><primary>SSL</><secondary
sortas="libpq">with libpq</></indexterm>
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-pqfinish"> <varlistentry id="libpq-connect-requiressl" xreflabel="requiressl">
<term><function>PQfinish</function><indexterm><primary>PQfinish</></></term> <term><literal>requiressl</literal></term>
<listitem> <listitem>
<para> <para>
Closes the connection to the server. Also frees This option is deprecated in favor of the <literal>sslmode</>
memory used by the <structname>PGconn</structname> object. setting.
<synopsis>
void PQfinish(PGconn *conn);
</synopsis>
</para> </para>
<para> <para>
Note that even if the server connection attempt fails (as If set to 1, an <acronym>SSL</acronym> connection to the server
indicated by <function>PQstatus</function>), the application should call <function>PQfinish</function> is required (this is equivalent to <literal>sslmode</>
to free the memory used by the <structname>PGconn</structname> object. <literal>require</>). <application>libpq</> will then refuse
The <structname>PGconn</> pointer must not be used again after to connect if the server does not accept an
<function>PQfinish</function> has been called. <acronym>SSL</acronym> connection. If set to 0 (default),
<application>libpq</> will negotiate the connection type with
the server (equivalent to <literal>sslmode</>
<literal>prefer</>). This option is only available if
<productname>PostgreSQL</> is compiled with SSL support.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-pqreset"> <varlistentry id="libpq-connect-sslcompression" xreflabel="sslcompression">
<term><function>PQreset</function><indexterm><primary>PQreset</></></term> <term><literal>sslcompression</literal></term>
<listitem> <listitem>
<para> <para>
Resets the communication channel to the server. If set to 1 (default), data sent over SSL connections will be
<synopsis> compressed (this requires <productname>OpenSSL</> version
void PQreset(PGconn *conn); 0.9.8 or later).
</synopsis> If set to 0, compression will be disabled (this requires
<productname>OpenSSL</> 1.0.0 or later).
This parameter is ignored if a connection without SSL is made,
or if the version of <productname>OpenSSL</> used does not support
it.
</para> </para>
<para> <para>
This function will close the connection Compression uses CPU time, but can improve throughput if
to the server and attempt to reestablish a new the network is the bottleneck.
connection to the same server, using all the same Disabling compression can improve response time and throughput
parameters previously used. This might be useful for if CPU performance is the limiting factor.
error recovery if a working connection is lost.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-pqresetstart"> <varlistentry id="libpq-connect-sslcert" xreflabel="sslcert">
<term><function>PQresetStart</function><indexterm><primary>PQresetStart</></></term> <term><literal>sslcert</literal></term>
<term><function>PQresetPoll</function><indexterm><primary>PQresetPoll</></></term>
<listitem> <listitem>
<para> <para>
Reset the communication channel to the server, in a nonblocking manner. This parameter specifies the file name of the client SSL
certificate, replacing the default
<synopsis> <filename>~/.postgresql/postgresql.crt</>.
int PQresetStart(PGconn *conn); This parameter is ignored if an SSL connection is not made.
PostgresPollingStatusType PQresetPoll(PGconn *conn);
</synopsis>
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-sslkey" xreflabel="sslkey">
<term><literal>sslkey</literal></term>
<listitem>
<para> <para>
These functions will close the connection to the server and attempt to This parameter specifies the location for the secret key used for
reestablish a new connection to the same server, using all the same the client certificate. It can either specify a file name that will
parameters previously used. This can be useful for error recovery if a be used instead of the default
working connection is lost. They differ from <function>PQreset</function> (above) in that they <filename>~/.postgresql/postgresql.key</>, or it can specify a key
act in a nonblocking manner. These functions suffer from the same obtained from an external <quote>engine</> (engines are
restrictions as <function>PQconnectStartParams</>, <function>PQconnectStart</> <productname>OpenSSL</> loadable modules). An external engine
and <function>PQconnectPoll</>. specification should consist of a colon-separated engine name and
an engine-specific key identifier. This parameter is ignored if an
SSL connection is not made.
</para> </para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connect-sslrootcert" xreflabel="sslrootcert">
<term><literal>sslrootcert</literal></term>
<listitem>
<para> <para>
To initiate a connection reset, call This parameter specifies the name of a file containing SSL
<function>PQresetStart</function>. If it returns 0, the reset has certificate authority (<acronym>CA</>) certificate(s).
failed. If it returns 1, poll the reset using If the file exists, the server's certificate will be verified
<function>PQresetPoll</function> in exactly the same way as you to be signed by one of these authorities. The default is
would create the connection using <function>PQconnectPoll</function>. <filename>~/.postgresql/root.crt</>.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-pqpingparams"> <varlistentry id="libpq-connect-sslcrl" xreflabel="sslcrl">
<term><function>PQpingParams</function><indexterm><primary>PQpingParams</></></term> <term><literal>sslcrl</literal></term>
<listitem> <listitem>
<para> <para>
<function>PQpingParams</function> reports the status of the This parameter specifies the file name of the SSL certificate
server. It accepts connection parameters identical to those of revocation list (CRL). Certificates listed in this file, if it
<function>PQconnectdbParams</>, described above. It is not, however, exists, will be rejected while attempting to authenticate the
necessary to supply correct user name, password, or database name server's certificate. The default is
values to obtain the server status. <filename>~/.postgresql/root.crl</>.
</para>
<synopsis> </listitem>
PGPing PQpingParams(const char * const *keywords, </varlistentry>
const char * const *values,
int expand_dbname);
</synopsis>
The function returns one of the following values:
<variablelist> <varlistentry id="libpq-connect-requirepeer" xreflabel="requirepeer">
<varlistentry id="libpq-pqpingparams-pqping-ok"> <term><literal>requirepeer</literal></term>
<term><literal>PQPING_OK</literal></term>
<listitem> <listitem>
<para> <para>
The server is running and appears to be accepting connections. This parameter specifies the operating-system user name of the
server, for example <literal>requirepeer=postgres</literal>.
When making a Unix-domain socket connection, if this
parameter is set, the client checks at the beginning of the
connection that the server process is running under the specified
user name; if it is not, the connection is aborted with an error.
This parameter can be used to provide server authentication similar
to that available with SSL certificates on TCP/IP connections.
(Note that if the Unix-domain socket is in
<filename>/tmp</filename> or another publicly writable location,
any user could start a server listening there. Use this parameter
to ensure that you are connected to a server run by a trusted user.)
This option is only supported on platforms for which the
<literal>peer</> authentication method is implemented; see
<xref linkend="auth-peer">.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-pqpingparams-pqping-reject"> <varlistentry id="libpq-connect-krbsrvname" xreflabel="krbsrvname">
<term><literal>PQPING_REJECT</literal></term> <term><literal>krbsrvname</literal></term>
<listitem> <listitem>
<para> <para>
The server is running but is in a state that disallows connections Kerberos service name to use when authenticating with Kerberos 5
(startup, shutdown, or crash recovery). or GSSAPI.
This must match the service name specified in the server
configuration for Kerberos authentication to succeed. (See also
<xref linkend="kerberos-auth"> and <xref linkend="gssapi-auth">.)
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-pqpingparams-pqping-no-response"> <varlistentry id="libpq-connect-gsslib" xreflabel="gsslib">
<term><literal>PQPING_NO_RESPONSE</literal></term> <term><literal>gsslib</literal></term>
<listitem> <listitem>
<para> <para>
The server could not be contacted. This might indicate that the GSS library to use for GSSAPI authentication. Only used on Windows.
server is not running, or that there is something wrong with the Set to <literal>gssapi</literal> to force libpq to use the GSSAPI
given connection parameters (for example, wrong port number), or library for authentication instead of the default SSPI.
that there is a network connectivity problem (for example, a
firewall blocking the connection request).
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry id="libpq-pqpingparams-pqping-no-attempt"> <varlistentry id="libpq-connect-service" xreflabel="service">
<term><literal>PQPING_NO_ATTEMPT</literal></term> <term><literal>service</literal></term>
<listitem> <listitem>
<para> <para>
No attempt was made to contact the server, because the supplied Service name to use for additional parameters. It specifies a service
parameters were obviously incorrect or there was some client-side name in <filename>pg_service.conf</filename> that holds additional connection parameters.
problem (for example, out of memory). This allows applications to specify only a service name so connection parameters
can be centrally maintained. See <xref linkend="libpq-pgservice">.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
</variablelist> </variablelist>
</para>
</sect2>
<sect2 id="libpq-connstring">
<title>Connection Strings</title>
<indexterm zone="libpq-connstring">
<primary><literal>conninfo</literal></primary>
</indexterm>
<indexterm zone="libpq-connstring">
<primary><literal>URI</literal></primary>
</indexterm>
<para>
Several <application>libpq</> functions parse a user-specified string to obtain
connection parameters. There are two accepted formats for these strings:
plain <literal>keyword = value</literal> strings, and URIs.
</para> </para>
</listitem> <para>
</varlistentry> In the first format, each parameter setting is in the form
<literal>keyword = value</literal>. Spaces around the equal sign are
optional. To write an empty value, or a value containing spaces, surround it
with single quotes, e.g., <literal>keyword = 'a value'</literal>. Single
quotes and backslashes within
the value must be escaped with a backslash, i.e., <literal>\'</literal> and
<literal>\\</literal>.
</para>
<varlistentry id="libpq-pqping">
<term><function>PQping</function><indexterm><primary>PQping</></></term>
<listitem>
<para> <para>
<function>PQping</function> reports the status of the The currently recognized parameter key words are listed in
server. It accepts connection parameters identical to those of <xref linkend="libpq-paramkeywords">.
<function>PQconnectdb</>, described above. It is not, however, </para>
necessary to supply correct user name, password, or database name
values to obtain the server status.
<para>
The general form for connection <acronym>URI</acronym> is the
following:
<synopsis> <synopsis>
PGPing PQping(const char *conninfo); postgresql://[user[:password]@][unix-socket][:port[/dbname]][?param1=value1&amp;...]
postgresql://[user[:password]@][net-location][:port][/dbname][?param1=value1&amp;...]
</synopsis> </synopsis>
</para> </para>
<para> <para>
The return values are the same as for <function>PQpingParams</>. The <acronym>URI</acronym> designator can be either
<literal>postgresql://</literal> or <literal>postgres://</literal> and
each of the <acronym>URI</acronym> parts is optional. The following
examples illustrate valid <acronym>URI</acronym> syntax uses:
<synopsis>
postgresql://
postgresql://localhost
postgresql://localhost:5433
postgresql://localhost/mydb
postgresql://user@localhost
postgresql://user:secret@localhost
postgresql://other@localhost/otherdb
</synopsis>
</para> </para>
</listitem> <para>
</varlistentry> Percent-encoding may be used to include a symbol with special meaning in
any of the <acronym>URI</acronym> parts.
</para>
</variablelist> <para>
Additional connection parameters may optionally follow the base <acronym>URI</acronym>.
Any connection parameters not corresponding to key words listed
in <xref linkend="libpq-paramkeywords"> are ignored and a warning message
about them is sent to <filename>stderr</filename>.
</para>
<para>
For improved compatibility with JDBC connection <acronym>URI</acronym>
syntax, instances of parameter <literal>ssl=true</literal> are translated
into <literal>sslmode=require</literal> (see above.)
</para>
<para>
The host part may be either hostname or an IP address. To specify an
IPv6 host address, enclose it in square brackets:
<synopsis>
postgresql://[2001:db8::1234]/database
</synopsis>
As a special case, a host part which starts with <symbol>/</symbol> is
treated as a local Unix socket directory to look for the connection
socket special file:
<synopsis>
postgresql:///path/to/pgsql/socket/dir
</synopsis>
The whole connection string up to the extra parameters designator
(<symbol>?</symbol>) or the port designator (<symbol>:</symbol>) is treated
as the absolute path to the socket directory
(<literal>/path/to/pgsql/socket/dir</literal> in this example.) To specify
a non-default database name in this case you can use either of the following
syntaxes:
<synopsis>
postgresql:///path/to/pgsql/socket/dir?dbname=otherdb
postgresql:///path/to/pgsql/socket/dir:5432/otherdb
</synopsis>
</para> </para>
</sect2>
</sect1> </sect1>
<sect1 id="libpq-status"> <sect1 id="libpq-status">
......
...@@ -115,7 +115,10 @@ PostgreSQL documentation ...@@ -115,7 +115,10 @@ PostgreSQL documentation
argument on the command line. argument on the command line.
</para> </para>
<para> <para>
If this parameter contains an <symbol>=</symbol> sign, it is treated as a If this parameter contains an <symbol>=</symbol> sign or starts
with a valid <acronym>URI</acronym> prefix
(<literal>postgresql://</literal>
or <literal>postgres://</literal>), it is treated as a
<parameter>conninfo</parameter> string. See <xref linkend="libpq-connect"> for more information. <parameter>conninfo</parameter> string. See <xref linkend="libpq-connect"> for more information.
</para> </para>
</listitem> </listitem>
...@@ -596,11 +599,13 @@ PostgreSQL documentation ...@@ -596,11 +599,13 @@ PostgreSQL documentation
<para> <para>
An alternative way to specify connection parameters is in a An alternative way to specify connection parameters is in a
<parameter>conninfo</parameter> string, which is used instead of a <parameter>conninfo</parameter> string or
database name. This mechanism give you very wide control over the a <acronym>URI</acronym>, which is used instead of a database
name. This mechanism give you very wide control over the
connection. For example: connection. For example:
<programlisting> <programlisting>
$ <userinput>psql "service=myservice sslmode=require"</userinput> $ <userinput>psql "service=myservice sslmode=require"</userinput>
$ <userinput>psql postgresql://dbmaster:5433/mydb?sslmode=require</userinput>
</programlisting> </programlisting>
This way you can also use LDAP for connection parameter lookup as This way you can also use LDAP for connection parameter lookup as
described in <xref linkend="libpq-ldap">. described in <xref linkend="libpq-ldap">.
......
...@@ -121,6 +121,9 @@ install: all installdirs install-lib ...@@ -121,6 +121,9 @@ install: all installdirs install-lib
$(INSTALL_DATA) $(srcdir)/pqexpbuffer.h '$(DESTDIR)$(includedir_internal)' $(INSTALL_DATA) $(srcdir)/pqexpbuffer.h '$(DESTDIR)$(includedir_internal)'
$(INSTALL_DATA) $(srcdir)/pg_service.conf.sample '$(DESTDIR)$(datadir)/pg_service.conf.sample' $(INSTALL_DATA) $(srcdir)/pg_service.conf.sample '$(DESTDIR)$(datadir)/pg_service.conf.sample'
installcheck:
$(MAKE) -C test $@
installdirs: installdirs-lib installdirs: installdirs-lib
$(MKDIR_P) '$(DESTDIR)$(includedir)' '$(DESTDIR)$(includedir_internal)' $(MKDIR_P) '$(DESTDIR)$(includedir)' '$(DESTDIR)$(includedir_internal)'
...@@ -132,6 +135,7 @@ uninstall: uninstall-lib ...@@ -132,6 +135,7 @@ uninstall: uninstall-lib
rm -f '$(DESTDIR)$(datadir)/pg_service.conf.sample' rm -f '$(DESTDIR)$(datadir)/pg_service.conf.sample'
clean distclean: clean-lib clean distclean: clean-lib
$(MAKE) -C test $@
rm -f $(OBJS) pthread.h libpq.rc rm -f $(OBJS) pthread.h libpq.rc
# Might be left over from a Win32 client-only build # Might be left over from a Win32 client-only build
rm -f pg_config_paths.h rm -f pg_config_paths.h
...@@ -142,4 +146,5 @@ clean distclean: clean-lib ...@@ -142,4 +146,5 @@ clean distclean: clean-lib
rm -f encnames.c wchar.c rm -f encnames.c wchar.c
maintainer-clean: distclean maintainer-clean-lib maintainer-clean: distclean maintainer-clean-lib
$(MAKE) -C test $@
rm -f libpq-dist.rc rm -f libpq-dist.rc
...@@ -282,6 +282,9 @@ static const PQEnvironmentOption EnvironmentOptions[] = ...@@ -282,6 +282,9 @@ static const PQEnvironmentOption EnvironmentOptions[] =
} }
}; };
/* The connection URI must start with either of the following designators: */
static const char uri_designator[] = "postgresql://";
static const char short_uri_designator[] = "postgres://";
static bool connectOptions1(PGconn *conn, const char *conninfo); static bool connectOptions1(PGconn *conn, const char *conninfo);
static bool connectOptions2(PGconn *conn); static bool connectOptions2(PGconn *conn);
...@@ -293,6 +296,10 @@ static void fillPGconn(PGconn *conn, PQconninfoOption *connOptions); ...@@ -293,6 +296,10 @@ static void fillPGconn(PGconn *conn, PQconninfoOption *connOptions);
static void freePGconn(PGconn *conn); static void freePGconn(PGconn *conn);
static void closePGconn(PGconn *conn); static void closePGconn(PGconn *conn);
static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage); static PQconninfoOption *conninfo_init(PQExpBuffer errorMessage);
static PQconninfoOption *parse_connection_string(const char *conninfo,
PQExpBuffer errorMessage, bool use_defaults);
static int uri_prefix_length(const char *connstr);
static bool recognized_connection_string(const char *connstr);
static PQconninfoOption *conninfo_parse(const char *conninfo, static PQconninfoOption *conninfo_parse(const char *conninfo,
PQExpBuffer errorMessage, bool use_defaults); PQExpBuffer errorMessage, bool use_defaults);
static PQconninfoOption *conninfo_array_parse(const char *const * keywords, static PQconninfoOption *conninfo_array_parse(const char *const * keywords,
...@@ -300,7 +307,21 @@ static PQconninfoOption *conninfo_array_parse(const char *const * keywords, ...@@ -300,7 +307,21 @@ static PQconninfoOption *conninfo_array_parse(const char *const * keywords,
bool use_defaults, int expand_dbname); bool use_defaults, int expand_dbname);
static bool conninfo_add_defaults(PQconninfoOption *options, static bool conninfo_add_defaults(PQconninfoOption *options,
PQExpBuffer errorMessage); PQExpBuffer errorMessage);
static char *conninfo_getval(PQconninfoOption *connOptions, static PQconninfoOption *conninfo_uri_parse(const char *uri,
PQExpBuffer errorMessage, bool use_defaults);
static bool conninfo_uri_parse_options(PQconninfoOption *options,
const char *uri, PQExpBuffer errorMessage);
static bool conninfo_uri_parse_params(char *params,
PQconninfoOption *connOptions,
PQExpBuffer errorMessage);
static char *conninfo_uri_decode(const char *str, PQExpBuffer errorMessage);
static bool get_hexdigit(char digit, int *value);
static const char *conninfo_getval(PQconninfoOption *connOptions,
const char *keyword);
static PQconninfoOption *conninfo_storeval(PQconninfoOption *connOptions,
const char *keyword, const char *value,
PQExpBuffer errorMessage, bool ignoreMissing, bool uri_decode);
static PQconninfoOption *conninfo_find(PQconninfoOption *connOptions,
const char *keyword); const char *keyword);
static void defaultNoticeReceiver(void *arg, const PGresult *res); static void defaultNoticeReceiver(void *arg, const PGresult *res);
static void defaultNoticeProcessor(void *arg, const char *message); static void defaultNoticeProcessor(void *arg, const char *message);
...@@ -333,9 +354,9 @@ pgthreadlock_t pg_g_threadlock = default_threadlock; ...@@ -333,9 +354,9 @@ pgthreadlock_t pg_g_threadlock = default_threadlock;
* to the latter). * to the latter).
* *
* If it is desired to connect in a synchronous (blocking) manner, use the * If it is desired to connect in a synchronous (blocking) manner, use the
* function PQconnectdb or PQconnectdbParams. The former accepts a string * function PQconnectdb or PQconnectdbParams. The former accepts a string of
* of option = value pairs which must be parsed; the latter takes two NULL * option = value pairs (or a URI) which must be parsed; the latter takes two
* terminated arrays instead. * NULL terminated arrays instead.
* *
* To connect in an asynchronous (non-blocking) manner, use the functions * To connect in an asynchronous (non-blocking) manner, use the functions
* PQconnectStart or PQconnectStartParams (which differ in the same way as * PQconnectStart or PQconnectStartParams (which differ in the same way as
...@@ -406,13 +427,14 @@ PQpingParams(const char *const * keywords, ...@@ -406,13 +427,14 @@ PQpingParams(const char *const * keywords,
* establishes a connection to a postgres backend through the postmaster * establishes a connection to a postgres backend through the postmaster
* using connection information in a string. * using connection information in a string.
* *
* The conninfo string is a white-separated list of * The conninfo string is either a whitespace-separated list of
* *
* option = value * option = value
* *
* definitions. Value might be a single value containing no whitespaces or * definitions or a URI (refer to the documentation for details.) Value
* a single quoted string. If a single quote should appear anywhere in * might be a single value containing no whitespaces or a single quoted
* the value, it must be escaped with a backslash like \' * string. If a single quote should appear anywhere in the value, it must be
* escaped with a backslash like \'
* *
* Returns a PGconn* which is needed for all subsequent libpq calls, or NULL * Returns a PGconn* which is needed for all subsequent libpq calls, or NULL
* if a memory allocation failed. * if a memory allocation failed.
...@@ -583,7 +605,7 @@ PQconnectStart(const char *conninfo) ...@@ -583,7 +605,7 @@ PQconnectStart(const char *conninfo)
static void static void
fillPGconn(PGconn *conn, PQconninfoOption *connOptions) fillPGconn(PGconn *conn, PQconninfoOption *connOptions)
{ {
char *tmp; const char *tmp;
/* /*
* Move option values into conn structure * Move option values into conn structure
...@@ -680,7 +702,7 @@ connectOptions1(PGconn *conn, const char *conninfo) ...@@ -680,7 +702,7 @@ connectOptions1(PGconn *conn, const char *conninfo)
/* /*
* Parse the conninfo string * Parse the conninfo string
*/ */
connOptions = conninfo_parse(conninfo, &conn->errorMessage, true); connOptions = parse_connection_string(conninfo, &conn->errorMessage, true);
if (connOptions == NULL) if (connOptions == NULL)
{ {
conn->status = CONNECTION_BAD; conn->status = CONNECTION_BAD;
...@@ -881,9 +903,10 @@ PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions, ...@@ -881,9 +903,10 @@ PQsetdbLogin(const char *pghost, const char *pgport, const char *pgoptions,
return NULL; return NULL;
/* /*
* If the dbName parameter contains '=', assume it's a conninfo string. * If the dbName parameter contains what looks like a connection
* string, parse it into conn struct using connectOptions1.
*/ */
if (dbName && strchr(dbName, '=')) if (dbName && recognized_connection_string(dbName))
{ {
if (!connectOptions1(conn, dbName)) if (!connectOptions1(conn, dbName))
return conn; return conn;
...@@ -3764,7 +3787,7 @@ ldapServiceLookup(const char *purl, PQconninfoOption *options, ...@@ -3764,7 +3787,7 @@ ldapServiceLookup(const char *purl, PQconninfoOption *options,
static int static int
parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage) parseServiceInfo(PQconninfoOption *options, PQExpBuffer errorMessage)
{ {
char *service = conninfo_getval(options, "service"); const char *service = conninfo_getval(options, "service");
char serviceFile[MAXPGPATH]; char serviceFile[MAXPGPATH];
char *env; char *env;
bool group_found = false; bool group_found = false;
...@@ -3999,7 +4022,7 @@ PQconninfoParse(const char *conninfo, char **errmsg) ...@@ -3999,7 +4022,7 @@ PQconninfoParse(const char *conninfo, char **errmsg)
initPQExpBuffer(&errorBuf); initPQExpBuffer(&errorBuf);
if (PQExpBufferDataBroken(errorBuf)) if (PQExpBufferDataBroken(errorBuf))
return NULL; /* out of memory already :-( */ return NULL; /* out of memory already :-( */
connOptions = conninfo_parse(conninfo, &errorBuf, false); connOptions = parse_connection_string(conninfo, &errorBuf, false);
if (connOptions == NULL && errmsg) if (connOptions == NULL && errmsg)
*errmsg = errorBuf.data; *errmsg = errorBuf.data;
else else
...@@ -4023,17 +4046,68 @@ conninfo_init(PQExpBuffer errorMessage) ...@@ -4023,17 +4046,68 @@ conninfo_init(PQExpBuffer errorMessage)
return NULL; return NULL;
} }
memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions)); memcpy(options, PQconninfoOptions, sizeof(PQconninfoOptions));
return options; return options;
} }
/* /*
* Conninfo parser routine * Connection string parser
* *
* If successful, a malloc'd PQconninfoOption array is returned. * Returns a malloc'd PQconninfoOption array, if parsing is successful.
* If not successful, NULL is returned and an error message is * Otherwise, NULL is returned and an error message is left in errorMessage.
* left in errorMessage. *
* Defaults are supplied (from a service file, environment variables, etc) * If use_defaults is TRUE, default values are filled in (from a service file,
* for unspecified options, but only if use_defaults is TRUE. * environment variables, etc).
*/
static PQconninfoOption *
parse_connection_string(const char *connstr, PQExpBuffer errorMessage,
bool use_defaults)
{
/* Parse as URI if connection string matches URI prefix */
if (uri_prefix_length(connstr) != 0)
return conninfo_uri_parse(connstr, errorMessage, use_defaults);
/* Parse as default otherwise */
return conninfo_parse(connstr, errorMessage, use_defaults);
}
/*
* Checks if connection string starts with either of the valid URI prefix
* designators.
*
* Returns the URI prefix length, 0 if the string doesn't contain a URI prefix.
*/
static int
uri_prefix_length(const char *connstr)
{
if (strncmp(connstr, uri_designator,
sizeof(uri_designator) - 1) == 0)
return sizeof(uri_designator) - 1;
if (strncmp(connstr, short_uri_designator,
sizeof(short_uri_designator) - 1) == 0)
return sizeof(short_uri_designator) - 1;
return 0;
}
/*
* Recognized connection string either starts with a valid URI prefix or
* contains a "=" in it.
*
* Must be consistent with parse_connection_string: anything for which this
* returns true should at least look like it's parseable by that routine.
*/
static bool
recognized_connection_string(const char *connstr)
{
return uri_prefix_length(connstr) != 0 || strchr(connstr, '=') != NULL;
}
/*
* Subroutine for parse_connection_string
*
* Deal with a string containing key=value pairs.
*/ */
static PQconninfoOption * static PQconninfoOption *
conninfo_parse(const char *conninfo, PQExpBuffer errorMessage, conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
...@@ -4045,7 +4119,6 @@ conninfo_parse(const char *conninfo, PQExpBuffer errorMessage, ...@@ -4045,7 +4119,6 @@ conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
char *cp; char *cp;
char *cp2; char *cp2;
PQconninfoOption *options; PQconninfoOption *options;
PQconninfoOption *option;
/* Make a working copy of PQconninfoOptions */ /* Make a working copy of PQconninfoOptions */
options = conninfo_init(errorMessage); options = conninfo_init(errorMessage);
...@@ -4167,33 +4240,10 @@ conninfo_parse(const char *conninfo, PQExpBuffer errorMessage, ...@@ -4167,33 +4240,10 @@ conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
} }
/* /*
* Now we have the name and the value. Search for the param record. * Now that we have the name and the value, store the record.
*/
for (option = options; option->keyword != NULL; option++)
{
if (strcmp(option->keyword, pname) == 0)
break;
}
if (option->keyword == NULL)
{
printfPQExpBuffer(errorMessage,
libpq_gettext("invalid connection option \"%s\"\n"),
pname);
PQconninfoFree(options);
free(buf);
return NULL;
}
/*
* Store the value
*/ */
if (option->val) if (!conninfo_storeval(options, pname, pval, errorMessage, false, false))
free(option->val);
option->val = strdup(pval);
if (!option->val)
{ {
printfPQExpBuffer(errorMessage,
libpq_gettext("out of memory\n"));
PQconninfoFree(options); PQconninfoFree(options);
free(buf); free(buf);
return NULL; return NULL;
...@@ -4227,10 +4277,10 @@ conninfo_parse(const char *conninfo, PQExpBuffer errorMessage, ...@@ -4227,10 +4277,10 @@ conninfo_parse(const char *conninfo, PQExpBuffer errorMessage,
* Defaults are supplied (from a service file, environment variables, etc) * Defaults are supplied (from a service file, environment variables, etc)
* for unspecified options, but only if use_defaults is TRUE. * for unspecified options, but only if use_defaults is TRUE.
* *
* If expand_dbname is non-zero, and the value passed for keyword "dbname" * If expand_dbname is non-zero, and the value passed for keyword "dbname" is a
* contains an "=", assume it is a conninfo string and process it, * connection string (as indicated by recognized_connection_string) then parse
* overriding any previously processed conflicting keywords. Subsequent * and process it, overriding any previously processed conflicting
* keywords will take precedence, however. * keywords. Subsequent keywords will take precedence, however.
*/ */
static PQconninfoOption * static PQconninfoOption *
conninfo_array_parse(const char *const * keywords, const char *const * values, conninfo_array_parse(const char *const * keywords, const char *const * values,
...@@ -4238,13 +4288,13 @@ conninfo_array_parse(const char *const * keywords, const char *const * values, ...@@ -4238,13 +4288,13 @@ conninfo_array_parse(const char *const * keywords, const char *const * values,
int expand_dbname) int expand_dbname)
{ {
PQconninfoOption *options; PQconninfoOption *options;
PQconninfoOption *str_options = NULL; PQconninfoOption *dbname_options = NULL;
PQconninfoOption *option; PQconninfoOption *option;
int i = 0; int i = 0;
/* /*
* If expand_dbname is non-zero, check keyword "dbname" to see if val is * If expand_dbname is non-zero, check keyword "dbname" to see if val is
* actually a conninfo string * actually a recognized connection string.
*/ */
while (expand_dbname && keywords[i]) while (expand_dbname && keywords[i])
{ {
...@@ -4252,18 +4302,17 @@ conninfo_array_parse(const char *const * keywords, const char *const * values, ...@@ -4252,18 +4302,17 @@ conninfo_array_parse(const char *const * keywords, const char *const * values,
const char *pvalue = values[i]; const char *pvalue = values[i];
/* first find "dbname" if any */ /* first find "dbname" if any */
if (strcmp(pname, "dbname") == 0) if (strcmp(pname, "dbname") == 0 && pvalue)
{
/* next look for "=" in the value */
if (pvalue && strchr(pvalue, '='))
{ {
/* /*
* Must be a conninfo string, so parse it, but do not use * If value is a connection string, parse it, but do not use defaults
* defaults here -- those get picked up later. We only want to * here -- those get picked up later. We only want to override for
* override for those parameters actually passed. * those parameters actually passed.
*/ */
str_options = conninfo_parse(pvalue, errorMessage, false); if (recognized_connection_string(pvalue))
if (str_options == NULL) {
dbname_options = parse_connection_string(pvalue, errorMessage, false);
if (dbname_options == NULL)
return NULL; return NULL;
} }
break; break;
...@@ -4275,7 +4324,7 @@ conninfo_array_parse(const char *const * keywords, const char *const * values, ...@@ -4275,7 +4324,7 @@ conninfo_array_parse(const char *const * keywords, const char *const * values,
options = conninfo_init(errorMessage); options = conninfo_init(errorMessage);
if (options == NULL) if (options == NULL)
{ {
PQconninfoFree(str_options); PQconninfoFree(dbname_options);
return NULL; return NULL;
} }
...@@ -4302,20 +4351,20 @@ conninfo_array_parse(const char *const * keywords, const char *const * values, ...@@ -4302,20 +4351,20 @@ conninfo_array_parse(const char *const * keywords, const char *const * values,
libpq_gettext("invalid connection option \"%s\"\n"), libpq_gettext("invalid connection option \"%s\"\n"),
pname); pname);
PQconninfoFree(options); PQconninfoFree(options);
PQconninfoFree(str_options); PQconninfoFree(dbname_options);
return NULL; return NULL;
} }
/* /*
* If we are on the dbname parameter, and we have a parsed * If we are on the dbname parameter, and we have a parsed
* conninfo string, copy those parameters across, overriding any * connection string, copy those parameters across, overriding any
* existing previous settings * existing previous settings.
*/ */
if (strcmp(pname, "dbname") == 0 && str_options) if (strcmp(pname, "dbname") == 0 && dbname_options)
{ {
PQconninfoOption *str_option; PQconninfoOption *str_option;
for (str_option = str_options; str_option->keyword != NULL; str_option++) for (str_option = dbname_options; str_option->keyword != NULL; str_option++)
{ {
if (str_option->val != NULL) if (str_option->val != NULL)
{ {
...@@ -4347,14 +4396,14 @@ conninfo_array_parse(const char *const * keywords, const char *const * values, ...@@ -4347,14 +4396,14 @@ conninfo_array_parse(const char *const * keywords, const char *const * values,
printfPQExpBuffer(errorMessage, printfPQExpBuffer(errorMessage,
libpq_gettext("out of memory\n")); libpq_gettext("out of memory\n"));
PQconninfoFree(options); PQconninfoFree(options);
PQconninfoFree(str_options); PQconninfoFree(dbname_options);
return NULL; return NULL;
} }
} }
} }
++i; ++i;
} }
PQconninfoFree(str_options); PQconninfoFree(dbname_options);
/* /*
* Add in defaults if the caller wants that. * Add in defaults if the caller wants that.
...@@ -4450,16 +4499,618 @@ conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage) ...@@ -4450,16 +4499,618 @@ conninfo_add_defaults(PQconninfoOption *options, PQExpBuffer errorMessage)
return true; return true;
} }
/*
* Subroutine for parse_connection_string
*
* Deal with a URI connection string.
*/
static PQconninfoOption *
conninfo_uri_parse(const char *uri, PQExpBuffer errorMessage,
bool use_defaults)
{
PQconninfoOption *options;
/* Make a working copy of PQconninfoOptions */
options = conninfo_init(errorMessage);
if (options == NULL)
return NULL;
if (!conninfo_uri_parse_options(options, uri, errorMessage))
{
PQconninfoFree(options);
return NULL;
}
/*
* Add in defaults if the caller wants that.
*/
if (use_defaults)
{
if (!conninfo_add_defaults(options, errorMessage))
{
PQconninfoFree(options);
return NULL;
}
}
return options;
}
/*
* conninfo_uri_parse_options
* Actual URI parser.
*
* If successful, returns true while the options array is filled with parsed
* options from the URI.
* If not successful, returns false and fills errorMessage accordingly.
*
* Parses the connection URI string in 'uri' according to the URI syntax:
*
* postgresql://[user[:pwd]@][unix-socket][:port[/dbname]][?param1=value1&...]
* postgresql://[user[:pwd]@][net-location][:port][/dbname][?param1=value1&...]
*
* "net-location" is a hostname, an IPv4 address, or an IPv6 address surrounded
* by literal square brackets. To be recognized as a unix-domain socket, the
* value must start with a slash '/'. Note slight inconsistency in that dbname
* can always be specified after net-location, but after unix-socket it can only
* be specified if there is a port specification.
*
* Any of those elements might be percent-encoded (%xy).
*/
static bool
conninfo_uri_parse_options(PQconninfoOption *options, const char *uri,
PQExpBuffer errorMessage)
{
int prefix_len;
char *p;
char *buf = strdup(uri); /* need a modifiable copy of the input URI */
char *start = buf;
char prevchar = '\0';
bool retval = false;
if (buf == NULL)
{
printfPQExpBuffer(errorMessage,
libpq_gettext("out of memory\n"));
return false;
}
/* Skip the URI prefix */
prefix_len = uri_prefix_length(uri);
if (prefix_len == 0)
{
/* Should never happen */
printfPQExpBuffer(errorMessage,
libpq_gettext("invalid URI propagated to internal parser routine: \"%s\"\n"),
uri);
goto cleanup;
}
start += prefix_len;
p = start;
/* Look ahead for possible user credentials designator */
while (*p && *p != '@' && *p != '/')
++p;
if (*p == '@')
{
char *user;
/*
* Found username/password designator, so URI should be of the form
* "scheme://user[:password]@[netloc]".
*/
user = start;
p = user;
while (*p != ':' && *p != '@')
++p;
/* Save last char and cut off at end of user name */
prevchar = *p;
*p = '\0';
if (!*user)
{
printfPQExpBuffer(errorMessage,
libpq_gettext("invalid empty username specifier in URI: %s\n"),
uri);
goto cleanup;
}
if (!conninfo_storeval(options, "user", user,
errorMessage, false, true))
goto cleanup;
if (prevchar == ':')
{
const char *password = p + 1;
while (*p != '@')
++p;
*p = '\0';
if (!*password)
{
printfPQExpBuffer(errorMessage,
libpq_gettext("invalid empty password specifier in URI: %s\n"),
uri);
goto cleanup;
}
if (!conninfo_storeval(options, "password", password,
errorMessage, false, true))
goto cleanup;
}
/* Advance past end of parsed user name or password token */
++p;
}
else
{
/*
* No username/password designator found. Reset to start of URI.
*/
p = start;
}
/*
* "p" has been incremented past optional URI credential information at
* this point and now points at the "netloc" part of the URI.
*
* Check for local unix socket dir.
*/
if (*p == '/')
{
const char *socket = p;
/* Look for possible port specifier or query parameters */
while (*p && *p != ':' && *p != '?')
++p;
prevchar = *p;
*p = '\0';
if (!conninfo_storeval(options, "host", socket,
errorMessage, false, true))
goto cleanup;
}
else
{
/* Not a unix socket dir: parse as host name or address */
const char *host;
/*
*
* Look for IPv6 address
*/
if (*p == '[')
{
host = ++p;
while (*p && *p != ']')
++p;
if (!*p)
{
printfPQExpBuffer(errorMessage,
libpq_gettext("end of string reached when looking for matching ']' in IPv6 host address in URI: %s\n"),
uri);
goto cleanup;
}
if (p == host)
{
printfPQExpBuffer(errorMessage,
libpq_gettext("IPv6 host address may not be empty in URI: %s\n"),
uri);
goto cleanup;
}
/* Cut off the bracket and advance */
*(p++) = '\0';
/*
* The address may be followed by a port specifier or a slash or a
* query.
*/
if (*p && *p != ':' && *p != '/' && *p != '?')
{
printfPQExpBuffer(errorMessage,
libpq_gettext("unexpected '%c' at position %d in URI (expecting ':' or '/'): %s\n"),
*p, (int) (p - buf + 1), uri);
goto cleanup;
}
}
else
{
/* not an IPv6 address: DNS-named or IPv4 netloc */
host = p;
/*
* Look for port specifier (colon) or end of host specifier
* (slash), or query (question mark).
*/
while (*p && *p != ':' && *p != '/' && *p != '?')
++p;
}
/* Save the hostname terminator before we null it */
prevchar = *p;
*p = '\0';
if (!conninfo_storeval(options, "host", host,
errorMessage, false, true))
goto cleanup;
}
if (prevchar == ':')
{
const char *port = ++p; /* advance past host terminator */
while (*p && *p != '/' && *p != '?')
++p;
prevchar = *p;
*p = '\0';
if (!*port)
{
printfPQExpBuffer(errorMessage,
libpq_gettext("missing port specifier in URI: %s\n"),
uri);
goto cleanup;
}
if (!conninfo_storeval(options, "port", port,
errorMessage, false, true))
goto cleanup;
}
if (prevchar && prevchar != '?')
{
const char *dbname = ++p; /* advance past host terminator */
/* Look for query parameters */
while (*p && *p != '?')
++p;
prevchar = *p;
*p = '\0';
/*
* Avoid setting dbname to an empty string, as it forces the default
* value (username) and ignores $PGDATABASE, as opposed to not setting
* it at all.
*/
if (*dbname &&
!conninfo_storeval(options, "dbname", dbname,
errorMessage, false, true))
goto cleanup;
}
if (prevchar)
{
++p; /* advance past terminator */
if (!conninfo_uri_parse_params(p, options, errorMessage))
goto cleanup;
}
/* everything parsed okay */
retval = true;
cleanup:
free(buf);
return retval;
}
/*
* Connection URI parameters parser routine
*
* If successful, returns true while connOptions is filled with parsed
* parameters. Otherwise, returns false and fills errorMessage appropriately.
*
* Destructively modifies 'params' buffer.
*/
static bool
conninfo_uri_parse_params(char *params,
PQconninfoOption *connOptions,
PQExpBuffer errorMessage)
{
while (*params)
{
const char *keyword = params;
const char *value = NULL;
char *p = params;
/*
* Scan the params string for '=' and '&', marking the end of keyword
* and value respectively.
*/
for (;;)
{
if (*p == '=')
{
/* Was there '=' already? */
if (value != NULL)
{
printfPQExpBuffer(errorMessage,
libpq_gettext("extra key/value separator '=' in URI query parameter: %s\n"),
params);
return false;
}
/* Cut off keyword, advance to value */
*p = '\0';
value = ++p;
}
else if (*p == '&' || *p == '\0')
{
char prevchar;
/* Cut off value, remember old value */
prevchar = *p;
*p = '\0';
/* Was there '=' at all? */
if (value == NULL)
{
printfPQExpBuffer(errorMessage,
libpq_gettext("missing key/value separator '=' in URI query parameter: %s\n"),
params);
return false;
}
/*
* If not at the end, advance; now pointing to start of the
* next parameter, if any.
*/
if (prevchar != '\0')
++p;
break;
}
/* Advance, NUL is checked in the 'if' above */
++p;
}
/*
* Special keyword handling for improved JDBC compatibility. Note
* we fail to detect URI-encoded values here, but we don't care.
*/
if (strcmp(keyword, "ssl") == 0 &&
strcmp(value, "true") == 0)
{
keyword = "sslmode";
value = "require";
}
/*
* Store the value if the corresponding option exists; ignore
* otherwise.
*/
if (!conninfo_storeval(connOptions, keyword, value,
errorMessage, true, true))
{
/*
* Check if there was a hard error when decoding or storing the
* option.
*/
if (errorMessage->len != 0)
return false;
fprintf(stderr,
libpq_gettext("WARNING: ignoring unrecognized URI query parameter: %s\n"),
keyword);
}
/* Proceed to next key=value pair */
params = p;
}
return true;
}
/*
* Connection URI decoder routine
*
* If successful, returns the malloc'd decoded string.
* If not successful, returns NULL and fills errorMessage accordingly.
*
* The string is decoded by replacing any percent-encoded tokens with
* corresponding characters, while preserving any non-encoded characters. A
* percent-encoded token is a character triplet: a percent sign, followed by a
* pair of hexadecimal digits (0-9A-F), where lower- and upper-case letters are
* treated identically.
*/
static char * static char *
conninfo_uri_decode(const char *str, PQExpBuffer errorMessage)
{
char *buf = malloc(strlen(str) + 1);
char *p = buf;
const char *q = str;
if (buf == NULL)
{
printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
return NULL;
}
for (;;)
{
if (*q != '%')
{
/* copy and check for NUL terminator */
if (!(*(p++) = *(q++)))
break;
}
else
{
int hi;
int lo;
int c;
++q; /* skip the percent sign itself */
/*
* Possible EOL will be caught by the first call to get_hexdigit(),
* so we never dereference an invalid q pointer.
*/
if (!(get_hexdigit(*q++, &hi) && get_hexdigit(*q++, &lo)))
{
printfPQExpBuffer(errorMessage,
libpq_gettext("invalid percent-encoded token: %s\n"),
str);
free(buf);
return NULL;
}
c = (hi << 4) | lo;
if (c == 0)
{
printfPQExpBuffer(errorMessage,
libpq_gettext("forbidden value %%00 in percent-encoded value: %s\n"),
str);
free(buf);
return NULL;
}
*(p++) = c;
}
}
return buf;
}
/*
* Convert hexadecimal digit character to its integer value.
*
* If successful, returns true and value is filled with digit's base 16 value.
* If not successful, returns false.
*
* Lower- and upper-case letters in the range A-F are treated identically.
*/
static bool
get_hexdigit(char digit, int *value)
{
if ('0' <= digit && digit <= '9')
*value = digit - '0';
else if ('A' <= digit && digit <= 'F')
*value = digit - 'A' + 10;
else if ('a' <= digit && digit <= 'f')
*value = digit - 'a' + 10;
else
return false;
return true;
}
/*
* Find an option value corresponding to the keyword in the connOptions array.
*
* If successful, returns a pointer to the corresponding option's value.
* If not successful, returns NULL.
*/
static const char *
conninfo_getval(PQconninfoOption *connOptions, conninfo_getval(PQconninfoOption *connOptions,
const char *keyword) const char *keyword)
{ {
PQconninfoOption *option; PQconninfoOption *option;
option = conninfo_find(connOptions, keyword);
return option ? option->val : NULL;
}
/*
* Store a (new) value for an option corresponding to the keyword in
* connOptions array.
*
* If uri_decode is true, keyword and value are URI-decoded.
*
* If successful, returns a pointer to the corresponding PQconninfoOption,
* which value is replaced with a strdup'd copy of the passed value string.
* The existing value for the option is free'd before replacing, if any.
*
* If not successful, returns NULL and fills errorMessage accordingly.
* However, if the reason of failure is an invalid keyword being passed and
* ignoreMissing is TRUE, errorMessage will be left untouched.
*/
static PQconninfoOption *
conninfo_storeval(PQconninfoOption *connOptions,
const char *keyword, const char *value,
PQExpBuffer errorMessage, bool ignoreMissing,
bool uri_decode)
{
PQconninfoOption *option;
char *value_copy;
char *keyword_copy = NULL;
/*
* Decode the keyword. XXX this is seldom necessary as keywords do not
* normally need URI-escaping. It'd be good to do away with the
* malloc/free overhead and the general ugliness, but I don't see a
* better way to handle it.
*/
if (uri_decode)
{
keyword_copy = conninfo_uri_decode(keyword, errorMessage);
if (keyword_copy == NULL)
/* conninfo_uri_decode already set an error message */
goto failed;
}
option = conninfo_find(connOptions,
keyword_copy != NULL ? keyword_copy : keyword);
if (option == NULL)
{
if (!ignoreMissing)
printfPQExpBuffer(errorMessage,
libpq_gettext("invalid connection option \"%s\"\n"),
keyword);
goto failed;
}
if (uri_decode)
{
value_copy = conninfo_uri_decode(value, errorMessage);
if (value_copy == NULL)
/* conninfo_uri_decode already set an error message */
goto failed;
}
else
{
value_copy = strdup(value);
if (value_copy == NULL)
{
printfPQExpBuffer(errorMessage, libpq_gettext("out of memory\n"));
goto failed;
}
}
if (option->val)
free(option->val);
option->val = value_copy;
if (keyword_copy != NULL)
free(keyword_copy);
return option;
failed:
if (keyword_copy != NULL)
free(keyword_copy);
return NULL;
}
/*
* Find a PQconninfoOption option corresponding to the keyword in the
* connOptions array.
*
* If successful, returns a pointer to the corresponding PQconninfoOption
* structure.
* If not successful, returns NULL.
*/
static PQconninfoOption *
conninfo_find(PQconninfoOption *connOptions, const char *keyword)
{
PQconninfoOption *option;
for (option = connOptions; option->keyword != NULL; option++) for (option = connOptions; option->keyword != NULL; option++)
{ {
if (strcmp(option->keyword, keyword) == 0) if (strcmp(option->keyword, keyword) == 0)
return option->val; return option;
} }
return NULL; return NULL;
......
subdir = src/interfaces/libpq/test
top_builddir = ../../../..
include $(top_builddir)/src/Makefile.global
ifeq ($(PORTNAME), win32)
LDLIBS += -lws2_32
endif
override CPPFLAGS := -I$(libpq_srcdir) $(CPPFLAGS)
override LDLIBS := $(libpq_pgport) $(LDLIBS)
PROGS = uri-regress
all: $(PROGS)
installcheck: all
SRCDIR='$(top_srcdir)' SUBDIR='$(subdir)' \
$(SHELL) $(top_srcdir)/$(subdir)/regress.sh
clean distclean maintainer-clean:
rm -f $(PROGS)
rm -f regress.out regress.diff
This is a testsuite for testing libpq URI connection string syntax.
To run the suite, use 'make installcheck' command. It works by
running 'regress.sh' from this directory with appropriate environment
set up, which in turn feeds up lines from 'regress.in' to
'uri-regress' test program and compares the output against the correct
one in 'expected.out' file.
trying postgresql://uri-user:secret@host:12345/db
user='uri-user' password='secret' dbname='db' host='host' port='12345' (inet)
trying postgresql://uri-user@host:12345/db
user='uri-user' dbname='db' host='host' port='12345' (inet)
trying postgresql://uri-user@host/db
user='uri-user' dbname='db' host='host' (inet)
trying postgresql://host:12345/db
dbname='db' host='host' port='12345' (inet)
trying postgresql://host/db
dbname='db' host='host' (inet)
trying postgresql://uri-user@host:12345/
user='uri-user' host='host' port='12345' (inet)
trying postgresql://uri-user@host/
user='uri-user' host='host' (inet)
trying postgresql://uri-user@
user='uri-user' host='' (local)
trying postgresql://host:12345/
host='host' port='12345' (inet)
trying postgresql://host:12345
host='host' port='12345' (inet)
trying postgresql://host/db
dbname='db' host='host' (inet)
trying postgresql://host/
host='host' (inet)
trying postgresql://host
host='host' (inet)
trying postgresql://
host='' (local)
trying postgresql://?hostaddr=127.0.0.1
host='' hostaddr='127.0.0.1' (inet)
trying postgresql://example.com?hostaddr=63.1.2.4
host='example.com' hostaddr='63.1.2.4' (inet)
trying postgresql://%68ost/
host='host' (inet)
trying postgresql://host/db?user=uri-user
user='uri-user' dbname='db' host='host' (inet)
trying postgresql://host/db?user=uri-user&port=12345
user='uri-user' dbname='db' host='host' port='12345' (inet)
trying postgresql://host/db?u%73er=someotheruser&port=12345
user='someotheruser' dbname='db' host='host' port='12345' (inet)
trying postgresql://host/db?u%7aer=someotheruser&port=12345
WARNING: ignoring unrecognized URI query parameter: u%7aer
dbname='db' host='host' port='12345' (inet)
trying postgresql://host:12345?user=uri-user
user='uri-user' host='host' port='12345' (inet)
trying postgresql://host?user=uri-user
user='uri-user' host='host' (inet)
trying postgresql://host?
host='host' (inet)
trying postgresql://[::1]:12345/db
dbname='db' host='::1' port='12345' (inet)
trying postgresql://[::1]/db
dbname='db' host='::1' (inet)
trying postgresql://[2001:db8::1234]/
host='2001:db8::1234' (inet)
trying postgresql://[200z:db8::1234]/
host='200z:db8::1234' (inet)
trying postgresql://[::1]
host='::1' (inet)
trying postgres://
host='' (local)
trying postgres:///tmp
host='/tmp' (local)
trying postgresql://host?uzer=
WARNING: ignoring unrecognized URI query parameter: uzer
host='host' (inet)
trying postgre://
uri-regress: missing "=" after "postgre://" in connection info string
trying postgres://[::1
uri-regress: end of string reached when looking for matching ']' in IPv6 host address in URI: postgres://[::1
trying postgres://[]
uri-regress: IPv6 host address may not be empty in URI: postgres://[]
trying postgres://[::1]z
uri-regress: unexpected 'z' at position 17 in URI (expecting ':' or '/'): postgres://[::1]z
trying postgresql://host?zzz
uri-regress: missing key/value separator '=' in URI query parameter: zzz
trying postgresql://host?value1&value2
uri-regress: missing key/value separator '=' in URI query parameter: value1
trying postgresql://host?key=key=value
uri-regress: extra key/value separator '=' in URI query parameter: key
trying postgres://host?dbname=%XXfoo
uri-regress: invalid percent-encoded token: %XXfoo
trying postgresql://a%00b
uri-regress: forbidden value %00 in percent-encoded value: a%00b
trying postgresql://%zz
uri-regress: invalid percent-encoded token: %zz
trying postgresql://%1
uri-regress: invalid percent-encoded token: %1
trying postgresql://%
uri-regress: invalid percent-encoded token: %
trying postgres://@host
uri-regress: invalid empty username specifier in URI: postgres://@host
trying postgres://host:/
uri-regress: missing port specifier in URI: postgres://host:/
trying postgres://otheruser@/no/such/directory
user='otheruser' host='/no/such/directory' (local)
trying postgres://otheruser@/no/such/socket/path:12345
user='otheruser' host='/no/such/socket/path' port='12345' (local)
trying postgres://otheruser@/path/to/socket:12345/db
user='otheruser' dbname='db' host='/path/to/socket' port='12345' (local)
postgresql://uri-user:secret@host:12345/db
postgresql://uri-user@host:12345/db
postgresql://uri-user@host/db
postgresql://host:12345/db
postgresql://host/db
postgresql://uri-user@host:12345/
postgresql://uri-user@host/
postgresql://uri-user@
postgresql://host:12345/
postgresql://host:12345
postgresql://host/db
postgresql://host/
postgresql://host
postgresql://
postgresql://?hostaddr=127.0.0.1
postgresql://example.com?hostaddr=63.1.2.4
postgresql://%68ost/
postgresql://host/db?user=uri-user
postgresql://host/db?user=uri-user&port=12345
postgresql://host/db?u%73er=someotheruser&port=12345
postgresql://host/db?u%7aer=someotheruser&port=12345
postgresql://host:12345?user=uri-user
postgresql://host?user=uri-user
postgresql://host?
postgresql://[::1]:12345/db
postgresql://[::1]/db
postgresql://[2001:db8::1234]/
postgresql://[200z:db8::1234]/
postgresql://[::1]
postgres://
postgres:///tmp
postgresql://host?uzer=
postgre://
postgres://[::1
postgres://[]
postgres://[::1]z
postgresql://host?zzz
postgresql://host?value1&value2
postgresql://host?key=key=value
postgres://host?dbname=%XXfoo
postgresql://a%00b
postgresql://%zz
postgresql://%1
postgresql://%
postgres://@host
postgres://host:/
postgres://otheruser@/no/such/directory
postgres://otheruser@/no/such/socket/path:12345
postgres://otheruser@/path/to/socket:12345/db
#!/bin/sh
while read line
do
echo "trying $line"
./uri-regress "$line"
echo ""
done < "${SRCDIR}/${SUBDIR}"/regress.in >regress.out 2>&1
if diff -c "${SRCDIR}/${SUBDIR}/"expected.out regress.out >regress.diff; then
echo "========================================"
echo "All tests passed"
exit 0
else
echo "========================================"
echo "FAILED: the test result differs from the expected output"
echo
echo "Review the difference in ${SUBDIR}/regress.diff"
echo "========================================"
exit 1
fi
/*
* uri-regress.c
* A test program for libpq URI format
*
* This is a helper for libpq conninfo regression testing. It takes a single
* conninfo string as a parameter, parses it using PQconninfoParse, and then
* prints out the values from the parsed PQconninfoOption struct that differ
* from the defaults (obtained from PQconndefaults).
*
* Portions Copyright (c) 2012, PostgreSQL Global Development Group
*
* IDENTIFICATION
* src/interfaces/libpq/test/uri-regress.c
*/
#include "postgres_fe.h"
#include "libpq-fe.h"
int
main(int argc, char *argv[])
{
PQconninfoOption *opts;
PQconninfoOption *defs;
PQconninfoOption *opt;
PQconninfoOption *def;
char *errmsg = NULL;
bool local = true;
if (argc != 2)
return 1;
opts = PQconninfoParse(argv[1], &errmsg);
if (opts == NULL)
{
fprintf(stderr, "uri-regress: %s\n", errmsg);
return 1;
}
defs = PQconndefaults();
if (defs == NULL)
{
fprintf(stderr, "uri-regress: cannot fetch default options\n");
return 1;
}
/*
* Loop on the options, and print the value of each if not the default.
*
* XXX this coding assumes that PQconninfoOption structs always have the
* keywords in the same order.
*/
for (opt = opts, def = defs; opt->keyword; ++opt, ++def)
{
if (opt->val != NULL)
{
if (def->val == NULL || strcmp(opt->val, def->val) != 0)
printf("%s='%s' ", opt->keyword, opt->val);
/*
* Try to detect if this is a Unix-domain socket or inet. This is
* a bit grotty but it's the same thing that libpq itself does.
*
* Note that we directly test for '/' instead of using
* is_absolute_path, as that would be considerably more messy.
* This would fail on Windows, but that platform doesn't have
* Unix-domain sockets anyway.
*/
if (*opt->val &&
(strcmp(opt->keyword, "hostaddr") == 0 ||
(strcmp(opt->keyword, "host") == 0 && *opt->val != '/')))
{
local = false;
}
}
}
if (local)
printf("(local)\n");
else
printf("(inet)\n");
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment