38.3. Клиентские интерфейсы #
- 38.3.1. Создание большого объекта
- 38.3.2. Импорт большого объекта
- 38.3.3. Экспорт большого объекта
- 38.3.4. Открытие существующего большого объекта
- 38.3.5. Запись данных в большой объект
- 38.3.6. Чтение данных из большого объекта
- 38.3.7. Перемещение в большом объекте
- 38.3.8. Получение текущего положения в большом объекте
- 38.3.9. Усечение большого объекта
- 38.3.10. Закрытие дескриптора большого объекта
- 38.3.11. Удаление большого объекта
В этом разделе описываются средства, которые предоставляет клиентская библиотека Postgres Pro libpq для обращения к большим объектам. Интерфейс работы с большими объектами Postgres Pro создан по подобию интерфейса файловых систем Unix, так что он включает аналоги функций open
, read
, write
, lseek
и т. д.
Все операции с большими объектами с применением этих функций должны иметь место в блоке транзакции SQL, так как дескрипторы больших объектов актуальны только во время транзакции. Операции записи, в том числе lo_open
в режиме INV_WRITE
, не допускаются в читающих транзакциях.
Если при выполнении одной из этих функций происходит ошибка, эта функция возвращает значение, иначе невозможное, обычно 0 или -1. Сообщение, описывающее ошибку, сохраняется в объекте соединения; получить его можно с помощью PQerrorMessage
.
Клиентские приложения, которые используют эти функции, должны включать заголовочный файл libpq/libpq-fs.h
и компоноваться с библиотекой libpq.
Клиентские приложения не могут использовать эти функции, когда соединение libpq находится в конвейерном режиме.
38.3.1. Создание большого объекта #
Oid lo_create(PGconn *conn, Oid lobjId);
создаёт новый большой объект. В lobjId
можно задать назначаемый ему OID; при этом произойдёт ошибка, если этот OID уже присвоен какому-либо большому объекту. Если в lobjId
передаётся InvalidOid
(ноль), lo_create
присваивает большому объекту свободный OID. Возвращаемым значением будет OID, назначенный новому большому объекту, либо InvalidOid
(ноль) в случае ошибки.
Пример:
inv_oid = lo_create(conn, desired_oid);
Oid lo_creat(PGconn *conn, int mode);
также создаёт новый большой объект, всегда присваивая ему неиспользуемый OID. Возвращаемое значение — это OID, присвоенный новому большому объекту, или InvalidOid
(ноль) в случае ошибки.
В PostgreSQL версии 8.1 и выше режим
игнорируется, так что вызов lo_creat
полностью равнозначен вызову lo_create
с нулевым вторым аргументом. Однако едва ли стоит использовать lo_creat
, если вам не нужно работать с серверами версии ниже 8.1. Чтобы работать с таким старым сервером, вы должны использовать lo_creat
, а не lo_create
, и передать в аргументе режим
значение INV_READ
, INV_WRITE
или INV_READ
|
INV_WRITE
. (Эти символические константы определены в заголовочном файле libpq/libpq-fs.h
.)
Пример:
inv_oid = lo_creat(conn, INV_READ|INV_WRITE);
38.3.2. Импорт большого объекта #
Чтобы импортировать в качестве большого объекта файл операционной системы, вызовите
Oid lo_import(PGconn *conn, const char *filename);
В filename
задаётся имя файла в операционной системе, который будет импортирован как большой объект. Возвращаемым значением будет OID, назначенный новому большому объекту, либо InvalidOid
(ноль) в случае ошибки. Заметьте, что этот файл читает библиотека клиентского интерфейса, а не сервер; таким образом, он должен существовать в файловой системе на стороне клиента и быть доступным для чтения клиентскому приложению.
Oid lo_import_with_oid(PGconn *conn, const char *filename, Oid lobjId);
также импортирует новый большой объект. В lobjId
можно задать назначаемый ему OID; при этом произойдёт ошибка, если этот OID уже присвоен какому-либо большому объекту. Если в lobjId
передаётся InvalidOid
(ноль), lo_import_with_oid
присваивает большому объекту свободный OID (так же, как и lo_import
). Возвращаемым значением будет OID, назначенный новому большому объекту, либо InvalidOid
(ноль) в случае ошибки.
Функция lo_import_with_oid
появилась в PostgreSQL 8.4 и вызывает внутри lo_create
, появившуюся в 8.1; если попытаться выполнить её с сервером версии 8.0 или ранней, она завершится ошибкой и возвратит InvalidOid
.
38.3.3. Экспорт большого объекта #
Чтобы экспортировать большой объект в файл операционной системы, вызовите
int lo_export(PGconn *conn, Oid lobjId, const char *filename);
В аргументе lobjId
задаётся OID экспортируемого большого объекта, а в аргументе filename
задаётся имя файла в операционной системе. Заметьте, что файл записывается библиотекой клиентского интерфейса, а не сервером. Возвращает 1 при успешном выполнении, -1 при ошибке.
38.3.4. Открытие существующего большого объекта #
Чтобы открыть существующий большой объект для чтения или записи, вызовите
int lo_open(PGconn *conn, Oid lobjId, int mode);
В аргументе lobjId
задаётся OID открываемого большого объекта. Биты в аргументе mode
определяют, открывается ли файл для чтения (INV_READ
), для записи (INV_WRITE
), либо для чтения/записи. (Эти константы определяются в заголовочном файле libpq/libpq-fs.h
.) Функция lo_open
возвращает дескриптор большого объекта (неотрицательный) для последующего использования в функциях lo_read
, lo_write
, lo_lseek
, lo_lseek64
, lo_tell
, lo_tell64
, lo_truncate
, lo_truncate64
и lo_close
. Этот дескриптор актуален только до завершения текущей транзакции. В случае ошибки возвращается -1.
В настоящее время сервер не различает режимы INV_WRITE
и INV_READ
|
INV_WRITE
: с таким дескриптором можно читать данные в любом случае. Однако есть значительное отличие этих режимов от одиночного INV_READ
: с дескриптором INV_READ
записывать данные нельзя, а данные, считываемые через него, будут отражать содержимое большого объекта в снимке транзакции, который был активен при выполнении lo_open
, то есть не будут включать изменения, произведённые позже этой или другими транзакциями. При чтении с дескриптором INV_WRITE
возвращаются данные, отражающие все изменения, произведённые другими зафиксированными транзакциями, а также текущей транзакцией. Это подобно различиям режимов REPEATABLE READ
и READ COMMITTED
для обычных команд SQL SELECT
.
Функция lo_open
завершится ошибкой, если пользователь не имеет права SELECT
для данного большого объекта или если указан флаг INV_WRITE
и отсутствует право UPDATE
. (До PostgreSQL 11 права проверялись при первом фактическом вызове функции чтения или записи с этим дескриптором.) Отключить новые проверки можно с помощью параметра времени выполнения lo_compat_privileges.
Пример:
inv_fd = lo_open(conn, inv_oid, INV_READ|INV_WRITE);
38.3.5. Запись данных в большой объект #
int lo_write(PGconn *conn, int fd, const char *buf, size_t len);
записывает len
байт из буфера buf
(который должен иметь размер len
) в дескриптор большого объекта fd
. В fd
должно передаваться значение, возвращённое предыдущим вызовом lo_open
. Возвращает эта функция число фактически записанных байт (в текущей реализации это всегда len
, если только не произошла ошибка). В случае ошибки возвращается значение -1.
Хотя параметр len
объявлен как size_t
, эта функция не принимает значение длины, превышающее INT_MAX
. На практике всё равно лучше передавать данные фрагментами не больше нескольких мегабайт.
38.3.6. Чтение данных из большого объекта #
int lo_read(PGconn *conn, int fd, char *buf, size_t len);
читает до len
байт из дескриптора большого объекта fd
в буфер buf
(который должен иметь размер len
). В fd
должно передаваться значение, возвращённое предыдущим вызовом lo_open
. Возвращает эта функция число фактически прочитанных байт; это число должно быть меньше len
, если при чтении был достигнут конец объекта. В случае ошибки возвращается -1.
Хотя параметр len
объявлен как size_t
, эта функция не принимает значение длины, превышающее INT_MAX
. На практике всё равно лучше передавать данные фрагментами не больше нескольких мегабайт.
38.3.7. Перемещение в большом объекте #
Чтобы изменить текущее положение чтения или записи, связанное с дескриптором большого объекта, вызовите
int lo_lseek(PGconn *conn, int fd, int offset, int whence);
Эта функция перемещает указатель текущего положения для дескриптора большого объекта fd
в новое положение, заданное аргументом offset
. Для аргумента whence
задаются значения SEEK_SET
(перемещение от начала объекта), SEEK_CUR
(перемещение от текущего положения) и SEEK_END
(перемещение от конца объекта). Возвращает эта функция новое положение указателя, либо -1 в случае ошибки.
Оперируя с большими объектами, размер которых превышает 2 ГБ, используйте
pg_int64 lo_lseek64(PGconn *conn, int fd, pg_int64 offset, int whence);
Эта функция действует так же, как и lo_lseek
, но может принять значение offset
, превышающее 2 ГБ, и/или вернуть результат, превышающий 2 ГБ. Заметьте, что если новое положение указателя оказывается за границей в 2ГБ, функция lo_lseek
выдаёт ошибку.
Функция lo_lseek64
появилась в PostgreSQL 9.3. Если попытаться выполнить её с сервером более старой версии, произойдёт ошибка и будет возвращено -1.
38.3.8. Получение текущего положения в большом объекте #
Чтобы получить текущее положение чтения или записи для дескриптора большого объекта, вызовите
int lo_tell(PGconn *conn, int fd);
Если возникает ошибка, возвращается -1.
Оперируя с большими объектами, размер которых может превышать 2 ГБ, используйте
pg_int64 lo_tell64(PGconn *conn, int fd);
Эта функция действует так же, как lo_tell
, но может выдавать результат, превышающий 2 ГБ. Заметьте, что lo_tell
выдаёт ошибку, если текущее положение чтения/записи оказывается за границей в 2 ГБ.
Функция lo_tell64
появилась в PostgreSQL 9.3. Если попытаться выполнить её с сервером более старой версии, произойдёт ошибка и будет возвращено -1.
38.3.9. Усечение большого объекта #
Чтобы усечь большой объект до требуемой длины, вызовите
int lo_truncate(PGconn *conn, int fd, size_t len);
Эта функция усекает большой объект с дескриптором fd
до длины len
. В fd
должно передаваться значение, возвращённое предыдущим вызовом lo_open
. Если len
превышает текущую длину большого объекта, большой объект расширяется до заданной длины нулевыми байтами ('\0'). В случае успеха lo_truncate
возвращает ноль, а при ошибке возвращается -1.
Положение чтения/записи, связанное с дескриптором fd
, при этом не меняется.
Хотя параметр len
объявлен как size_t
, lo_truncate
не принимает значение длины, превышающее INT_MAX
.
Оперируя с большими объектами, размер которых может превышать 2 ГБ, используйте
int lo_truncate64(PGconn *conn, int fd, pg_int64 len);
Эта функция действует так же, как lo_truncate
, но может принимать значения len
, превышающие 2 ГБ.
Функция lo_truncate
появилась в PostgreSQL 8.3; если попытаться выполнить её с сервером более старой версии, произойдёт ошибка и будет возвращено -1.
Функция lo_truncate64
появилась в PostgreSQL 9.3; если попытаться выполнить её с сервером более старой версии, произойдёт ошибка и будет возвращено -1.
38.3.10. Закрытие дескриптора большого объекта #
Дескриптор большого объекта можно закрыть, вызвав
int lo_close(PGconn *conn, int fd);
Здесь fd
— дескриптор большого объекта, возвращённый функцией lo_open
. В случае успеха lo_close
возвращает ноль. При ошибке возвращается -1.
Все дескрипторы больших объектов, остающиеся открытыми в конце транзакции, закрываются автоматически.
38.3.11. Удаление большого объекта #
Чтобы удалить большой объект из базы данных, вызовите
int lo_unlink(PGconn *conn, Oid lobjId);
В аргументе lobjId
задаётся OID большого объекта, который нужно удалить. В случае успеха возвращается 1, а в случае ошибки -1.
19.3. Connections and Authentication
19.3.1. Connection Settings
listen_addresses
(string
)Specifies the TCP/IP address(es) on which the server is to listen for connections from client applications. The value takes the form of a comma-separated list of host names and/or numeric IP addresses. The special entry
*
corresponds to all available IP interfaces. The entry0.0.0.0
allows listening for all IPv4 addresses and::
allows listening for all IPv6 addresses. If the list is empty, the server does not listen on any IP interface at all, in which case only Unix-domain sockets can be used to connect to it. If the list is not empty, the server will start if it can listen on at least one TCP/IP address. A warning will be emitted for any TCP/IP address which cannot be opened. The default value is localhost, which allows only local TCP/IP “loopback” connections to be made.While client authentication (Chapter 20) allows fine-grained control over who can access the server,
listen_addresses
controls which interfaces accept connection attempts, which can help prevent repeated malicious connection requests on insecure network interfaces. This parameter can only be set at server start.listen_rdma_addresses
(string
)Specifies the TCP/IP address(es) on which the server is to listen for new remote direct memory access (
RDMA
) connections viarsocket
from client applications. The value takes the form of a comma-separated list of host names and/or numeric IP addresses. The special entry*
corresponds to all available IP interfaces.port
(integer
)The TCP port the server listens on; 5432 by default. Note that the same port number is used for all IP addresses the server listens on. This parameter can only be set at server start.
max_connections
(integer
)Determines the maximum number of concurrent connections to the database server. The default is typically 100 connections, but might be less if your kernel settings will not support it (as determined during initdb). This parameter can only be set at server start.
When running a standby server, you must set this parameter to the same or higher value than on the master server. Otherwise, queries will not be allowed in the standby server.
superuser_reserved_connections
(integer
)Determines the number of connection “slots” that are reserved for connections by Postgres Pro superusers. At most max_connections connections can ever be active simultaneously. Whenever the number of active concurrent connections is at least
max_connections
minussuperuser_reserved_connections
, new connections will be accepted only for superusers, and no new replication connections will be accepted.The default value is three connections. The value must be less than
max_connections
minus max_wal_senders. This parameter can only be set at server start.max_sessions
(integer
)The maximum number of client sessions that can be handled by one backend when connection pooling is switched on. This parameter does not add any memory or CPU overhead, so specifying a large
max_sessions
value does not affect performance. If themax_sessions
limit is reached, the backend stops accepting connections. Until one of the connections is terminated, attempts to connect to this backend result in an error.The default value is 1000. This parameter can only be set at server start.
session_pool_size
(integer
)Enables connection pooling and defines the maximum number of backends that can be used by client sessions for each database.
The default value is zero, so connection pooling is disabled.
connection_pool_workers
(integer
)Number of connection listeners used to read client startup packages. If connection pooling is enabled, Postgres Pro Enterprise server redirects all client startup packages to a connection listener. The listener determines the database and user that the client needs to access and redirects the connection to an appropriate backend, which is selected from the pool in accordance with the session_schedule policy. This approach allows to avoid server slowdown if a client tries to connect via a slow or unreliable network.
The default value is 2.
dedicated_databases
(string
)Specifies the list of databases for which connection pooling is disabled, regardless of the
session_pool_size
value. For such databases, a separate backend is forked for each connection. By default, connection pooling is disabled fortemplate0
,template1
, andpostgres
databases.dedicated_users
(string
)Specifies the list of users for which connection pooling is disabled, regardless of the
session_pool_size
value. For such users, a separate backend is forked for each connection. By default, connection pooling is disabled for thepostgres
user.restart_pooler_on_reload
(boolean
)Restart connection pool workers once
pg_reload_conf()
is called. The default value isfalse
.hold_prepared_transactions
(boolean
)Do not reschedule the backend while the current session has unfinished prepared transactions. Scheduling several sessions with conflicting prepared transactions on the same backend can cause undetectable deadlocks.
The default value is
off
.session_schedule
(enum
)Specifies scheduling policy for assigning a session to a backend if connection pooling is enabled:
round-robin
— cyclically scatter sessions between pooled backends.random
— choose a backend in the pool at random.load-balancing
— choose the backend with the lowest load average. The backend load average is estimated by the number of ready events at each reschedule iteration.
The default policy is
round-robin
.idle_pool_worker_timeout
(integer
)Terminate an idle connection pool worker after the specified number of milliseconds. The default value is 0, so pool workers are never terminated.
unix_socket_directories
(string
)Specifies the directory of the Unix-domain socket(s) on which the server is to listen for connections from client applications. Multiple sockets can be created by listing multiple directories separated by commas. Whitespace between entries is ignored; surround a directory name with double quotes if you need to include whitespace or commas in the name. An empty value specifies not listening on any Unix-domain sockets, in which case only TCP/IP sockets can be used to connect to the server. The default value is normally
/tmp
, but that can be changed at build time. This parameter can only be set at server start.In addition to the socket file itself, which is named
.s.PGSQL.
wherennnn
nnnn
is the server's port number, an ordinary file named.s.PGSQL.
will be created in each of thennnn
.lockunix_socket_directories
directories. Neither file should ever be removed manually.This parameter is irrelevant on Windows, which does not have Unix-domain sockets.
unix_socket_group
(string
)Sets the owning group of the Unix-domain socket(s). (The owning user of the sockets is always the user that starts the server.) In combination with the parameter
unix_socket_permissions
this can be used as an additional access control mechanism for Unix-domain connections. By default this is the empty string, which uses the default group of the server user. This parameter can only be set at server start.This parameter is irrelevant on Windows, which does not have Unix-domain sockets.
unix_socket_permissions
(integer
)Sets the access permissions of the Unix-domain socket(s). Unix-domain sockets use the usual Unix file system permission set. The parameter value is expected to be a numeric mode specified in the format accepted by the
chmod
andumask
system calls. (To use the customary octal format the number must start with a0
(zero).)The default permissions are
0777
, meaning anyone can connect. Reasonable alternatives are0770
(only user and group, see alsounix_socket_group
) and0700
(only user). (Note that for a Unix-domain socket, only write permission matters, so there is no point in setting or revoking read or execute permissions.)This access control mechanism is independent of the one described in Chapter 20.
This parameter can only be set at server start.
This parameter is irrelevant on systems, notably Solaris as of Solaris 10, that ignore socket permissions entirely. There, one can achieve a similar effect by pointing
unix_socket_directories
to a directory having search permission limited to the desired audience. This parameter is also irrelevant on Windows, which does not have Unix-domain sockets.bonjour
(boolean
)Enables advertising the server's existence via Bonjour. The default is off. This parameter can only be set at server start.
bonjour_name
(string
)Specifies the Bonjour service name. The computer name is used if this parameter is set to the empty string
''
(which is the default). This parameter is ignored if the server was not compiled with Bonjour support. This parameter can only be set at server start.tcp_keepalives_idle
(integer
)Specifies the number of seconds of inactivity after which TCP should send a keepalive message to the client. A value of 0 uses the system default. This parameter is supported only on systems that support
TCP_KEEPIDLE
or an equivalent socket option, and on Windows; on other systems, it must be zero. In sessions connected via a Unix-domain socket, this parameter is ignored and always reads as zero.Note
On Windows, a value of 0 will set this parameter to 2 hours, since Windows does not provide a way to read the system default value.
tcp_keepalives_interval
(integer
)Specifies the number of seconds after which a TCP keepalive message that is not acknowledged by the client should be retransmitted. A value of 0 uses the system default. This parameter is supported only on systems that support
TCP_KEEPINTVL
or an equivalent socket option, and on Windows; on other systems, it must be zero. In sessions connected via a Unix-domain socket, this parameter is ignored and always reads as zero.Note
On Windows, a value of 0 will set this parameter to 1 second, since Windows does not provide a way to read the system default value.
tcp_keepalives_count
(integer
)Specifies the number of TCP keepalives that can be lost before the server's connection to the client is considered dead. A value of 0 uses the system default. This parameter is supported only on systems that support
TCP_KEEPCNT
or an equivalent socket option; on other systems, it must be zero. In sessions connected via a Unix-domain socket, this parameter is ignored and always reads as zero.Note
This parameter is not supported on Windows, and must be zero.
19.3.2. Authentication
authentication_timeout
(integer
)Maximum time to complete client authentication, in seconds. If a would-be client has not completed the authentication protocol in this much time, the server closes the connection. This prevents hung clients from occupying a connection indefinitely. The default is one minute (
1m
). This parameter can only be set in thepostgresql.conf
file or on the server command line.password_encryption
(enum
)When a password is specified in CREATE ROLE or ALTER ROLE, this parameter determines the algorithm to use to encrypt the password. The default value is
md5
, which stores the password as an MD5 hash (on
is also accepted, as alias formd5
). Setting this parameter toscram-sha-256
will encrypt the password with SCRAM-SHA-256.Note that older clients might lack support for the SCRAM authentication mechanism, and hence not work with passwords encrypted with SCRAM-SHA-256. See Section 20.5 for more details.
krb_server_keyfile
(string
)Sets the location of the Kerberos server key file. See Section 20.6 for details. This parameter can only be set in the
postgresql.conf
file or on the server command line.krb_caseins_users
(boolean
)Sets whether GSSAPI user names should be treated case-insensitively. The default is
off
(case sensitive). This parameter can only be set in thepostgresql.conf
file or on the server command line.db_user_namespace
(boolean
)This parameter enables per-database user names. It is off by default. This parameter can only be set in the
postgresql.conf
file or on the server command line.If this is on, you should create users as
username@dbname
. Whenusername
is passed by a connecting client,@
and the database name are appended to the user name and that database-specific user name is looked up by the server. Note that when you create users with names containing@
within the SQL environment, you will need to quote the user name.With this parameter enabled, you can still create ordinary global users. Simply append
@
when specifying the user name in the client, e.g.,joe@
. The@
will be stripped off before the user name is looked up by the server.db_user_namespace
causes the client's and server's user name representation to differ. Authentication checks are always done with the server's user name so authentication methods must be configured for the server's user name, not the client's. Becausemd5
uses the user name as salt on both the client and server,md5
cannot be used withdb_user_namespace
.Note
This feature is intended as a temporary measure until a complete solution is found. At that time, this option will be removed.
19.3.3. SSL
See Section 18.9 for more information about setting up SSL.
ssl
(boolean
)Enables SSL connections. This parameter can only be set in the
postgresql.conf
file or on the server command line. The default isoff
.ssl_ca_file
(string
)Specifies the name of the file containing the SSL server certificate authority (CA). Relative paths are relative to the data directory. This parameter can only be set in the
postgresql.conf
file or on the server command line. The default is empty, meaning no CA file is loaded, and client certificate verification is not performed.ssl_cert_file
(string
)Specifies the name of the file containing the SSL server certificate. Relative paths are relative to the data directory. This parameter can only be set in the
postgresql.conf
file or on the server command line. The default isserver.crt
.ssl_crl_file
(string
)Specifies the name of the file containing the SSL client certificate revocation list (CRL). Relative paths are relative to the data directory. This parameter can only be set in the
postgresql.conf
file or on the server command line. The default is empty, meaning no CRL file is loaded.ssl_key_file
(string
)Specifies the name of the file containing the SSL server private key. Relative paths are relative to the data directory. This parameter can only be set in the
postgresql.conf
file or on the server command line. The default isserver.key
.ssl_ciphers
(string
)Specifies a list of SSL cipher suites that are allowed to be used by SSL connections. See the ciphers manual page in the OpenSSL package for the syntax of this setting and a list of supported values. Only connections using TLS version 1.2 and lower are affected. There is currently no setting that controls the cipher choices used by TLS version 1.3 connections. The default value is
HIGH:MEDIUM:+3DES:!aNULL
. The default is usually a reasonable choice unless you have specific security requirements.This parameter can only be set in the
postgresql.conf
file or on the server command line.Explanation of the default value:
HIGH
Cipher suites that use ciphers from
HIGH
group (e.g., AES, Camellia, 3DES)MEDIUM
Cipher suites that use ciphers from
MEDIUM
group (e.g., RC4, SEED)+3DES
The OpenSSL default order for
HIGH
is problematic because it orders 3DES higher than AES128. This is wrong because 3DES offers less security than AES128, and it is also much slower.+3DES
reorders it after all otherHIGH
andMEDIUM
ciphers.!aNULL
Disables anonymous cipher suites that do no authentication. Such cipher suites are vulnerable to man-in-the-middle attacks and therefore should not be used.
Available cipher suite details will vary across OpenSSL versions. Use the command
openssl ciphers -v 'HIGH:MEDIUM:+3DES:!aNULL'
to see actual details for the currently installed OpenSSL version. Note that this list is filtered at run time based on the server key type.ssl_prefer_server_ciphers
(boolean
)Specifies whether to use the server's SSL cipher preferences, rather than the client's. This parameter can only be set in the
postgresql.conf
file or on the server command line. The default istrue
.Older Postgres Pro versions do not have this setting and always use the client's preferences. This setting is mainly for backward compatibility with those versions. Using the server's preferences is usually better because it is more likely that the server is appropriately configured.
ssl_ecdh_curve
(string
)Specifies the name of the curve to use in ECDH key exchange. It needs to be supported by all clients that connect. It does not need to be the same curve used by the server's Elliptic Curve key. This parameter can only be set in the
postgresql.conf
file or on the server command line. The default isprime256v1
.OpenSSL names for the most common curves are:
prime256v1
(NIST P-256),secp384r1
(NIST P-384),secp521r1
(NIST P-521). The full list of available curves can be shown with the commandopenssl ecparam -list_curves
. Not all of them are usable in TLS though.ssl_dh_params_file
(string
)Specifies the name of the file containing Diffie-Hellman parameters used for so-called ephemeral DH family of SSL ciphers. The default is empty, in which case compiled-in default DH parameters used. Using custom DH parameters reduces the exposure if an attacker manages to crack the well-known compiled-in DH parameters. You can create your own DH parameters file with the command
openssl dhparam -out dhparams.pem 2048
.This parameter can only be set in the
postgresql.conf
file or on the server command line.ssl_passphrase_command
(string
)Sets an external command to be invoked when a passphrase for decrypting an SSL file such as a private key needs to be obtained. By default, this parameter is empty, which means the built-in prompting mechanism is used.
The command must print the passphrase to the standard output and exit with code 0. In the parameter value,
%p
is replaced by a prompt string. (Write%%
for a literal%
.) Note that the prompt string will probably contain whitespace, so be sure to quote adequately. A single newline is stripped from the end of the output if present.The command does not actually have to prompt the user for a passphrase. It can read it from a file, obtain it from a keychain facility, or similar. It is up to the user to make sure the chosen mechanism is adequately secure.
This parameter can only be set in the
postgresql.conf
file or on the server command line.ssl_passphrase_command_supports_reload
(boolean
)This parameter determines whether the passphrase command set by
ssl_passphrase_command
will also be called during a configuration reload if a key file needs a passphrase. If this parameter is false (the default), thenssl_passphrase_command
will be ignored during a reload and the SSL configuration will not be reloaded if a passphrase is needed. That setting is appropriate for a command that requires a TTY for prompting, which might not be available when the server is running. Setting this parameter to true might be appropriate if the passphrase is obtained from a file, for example.This parameter can only be set in the
postgresql.conf
file or on the server command line.