codekingpro/portable-devtools
115k
1<?xml version="1.0" encoding="UTF-8" standalone="no"?>2<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>55.2. Message Flow</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /><link rel="prev" href="protocol-overview.html" title="55.1. Overview" /><link rel="next" href="sasl-authentication.html" title="55.3. SASL Authentication" /></head><body id="docContent" class="container-fluid col-10"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">55.2. Message Flow</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="protocol-overview.html" title="55.1. Overview">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="protocol.html" title="Chapter 55. Frontend/Backend Protocol">Up</a></td><th width="60%" align="center">Chapter 55. Frontend/Backend Protocol</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 16.3 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="sasl-authentication.html" title="55.3. SASL Authentication">Next</a></td></tr></table><hr /></div><div class="sect1" id="PROTOCOL-FLOW"><div class="titlepage"><div><div><h2 class="title" style="clear: both">55.2. Message Flow <a href="#PROTOCOL-FLOW" class="id_link">#</a></h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-START-UP">55.2.1. Start-up</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-SIMPLE-QUERY">55.2.2. Simple Query</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY">55.2.3. Extended Query</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-PIPELINING">55.2.4. Pipelining</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-FUNCTION-CALL">55.2.5. Function Call</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-COPY">55.2.6. COPY Operations</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-ASYNC">55.2.7. Asynchronous Operations</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-CANCELING-REQUESTS">55.2.8. Canceling Requests in Progress</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-TERMINATION">55.2.9. Termination</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-SSL">55.2.10. <acronym class="acronym">SSL</acronym> Session Encryption</a></span></dt><dt><span class="sect2"><a href="protocol-flow.html#PROTOCOL-FLOW-GSSAPI">55.2.11. <acronym class="acronym">GSSAPI</acronym> Session Encryption</a></span></dt></dl></div><p>3 This section describes the message flow and the semantics of each4 message type. (Details of the exact representation of each message5 appear in <a class="xref" href="protocol-message-formats.html" title="55.7. Message Formats">Section 55.7</a>.) There are6 several different sub-protocols depending on the state of the7 connection: start-up, query, function call,8 <code class="command">COPY</code>, and termination. There are also special9 provisions for asynchronous operations (including notification10 responses and command cancellation), which can occur at any time11 after the start-up phase.12 </p><div class="sect2" id="PROTOCOL-FLOW-START-UP"><div class="titlepage"><div><div><h3 class="title">55.2.1. Start-up <a href="#PROTOCOL-FLOW-START-UP" class="id_link">#</a></h3></div></div></div><p>13 To begin a session, a frontend opens a connection to the server and sends14 a startup message. This message includes the names of the user and of the15 database the user wants to connect to; it also identifies the particular16 protocol version to be used. (Optionally, the startup message can include17 additional settings for run-time parameters.)18 The server then uses this information and19 the contents of its configuration files (such as20 <code class="filename">pg_hba.conf</code>) to determine21 whether the connection is provisionally acceptable, and what additional22 authentication is required (if any).23 </p><p>24 The server then sends an appropriate authentication request message,25 to which the frontend must reply with an appropriate authentication26 response message (such as a password).27 For all authentication methods except GSSAPI, SSPI and SASL, there is at28 most one request and one response. In some methods, no response29 at all is needed from the frontend, and so no authentication request30 occurs. For GSSAPI, SSPI and SASL, multiple exchanges of packets may be31 needed to complete the authentication.32 </p><p>33 The authentication cycle ends with the server either rejecting the34 connection attempt (ErrorResponse), or sending AuthenticationOk.35 </p><p>36 The possible messages from the server in this phase are:37 38 </p><div class="variablelist"><dl class="variablelist"><dt><span class="term">ErrorResponse</span></dt><dd><p>39 The connection attempt has been rejected.40 The server then immediately closes the connection.41 </p></dd><dt><span class="term">AuthenticationOk</span></dt><dd><p>42 The authentication exchange is successfully completed.43 </p></dd><dt><span class="term">AuthenticationKerberosV5</span></dt><dd><p>44 The frontend must now take part in a Kerberos V545 authentication dialog (not described here, part of the46 Kerberos specification) with the server. If this is47 successful, the server responds with an AuthenticationOk,48 otherwise it responds with an ErrorResponse. This is no49 longer supported.50 </p></dd><dt><span class="term">AuthenticationCleartextPassword</span></dt><dd><p>51 The frontend must now send a PasswordMessage containing the52 password in clear-text form. If53 this is the correct password, the server responds with an54 AuthenticationOk, otherwise it responds with an ErrorResponse.55 </p></dd><dt><span class="term">AuthenticationMD5Password</span></dt><dd><p>56 The frontend must now send a PasswordMessage containing the57 password (with user name) encrypted via MD5, then encrypted58 again using the 4-byte random salt specified in the59 AuthenticationMD5Password message. If this is the correct60 password, the server responds with an AuthenticationOk,61 otherwise it responds with an ErrorResponse. The actual62 PasswordMessage can be computed in SQL as <code class="literal">concat('md5',63 md5(concat(md5(concat(password, username)), random-salt)))</code>.64 (Keep in mind the <code class="function">md5()</code> function returns its65 result as a hex string.)66 </p></dd><dt><span class="term">AuthenticationGSS</span></dt><dd><p>67 The frontend must now initiate a GSSAPI negotiation. The frontend68 will send a GSSResponse message with the first part of the GSSAPI69 data stream in response to this. If further messages are needed,70 the server will respond with AuthenticationGSSContinue.71 </p></dd><dt><span class="term">AuthenticationSSPI</span></dt><dd><p>72 The frontend must now initiate an SSPI negotiation. The frontend73 will send a GSSResponse with the first part of the SSPI74 data stream in response to this. If further messages are needed,75 the server will respond with AuthenticationGSSContinue.76 </p></dd><dt><span class="term">AuthenticationGSSContinue</span></dt><dd><p>77 This message contains the response data from the previous step78 of GSSAPI or SSPI negotiation (AuthenticationGSS, AuthenticationSSPI79 or a previous AuthenticationGSSContinue). If the GSSAPI80 or SSPI data in this message81 indicates more data is needed to complete the authentication,82 the frontend must send that data as another GSSResponse message. If83 GSSAPI or SSPI authentication is completed by this message, the server84 will next send AuthenticationOk to indicate successful authentication85 or ErrorResponse to indicate failure.86 </p></dd><dt><span class="term">AuthenticationSASL</span></dt><dd><p>87 The frontend must now initiate a SASL negotiation, using one of the88 SASL mechanisms listed in the message. The frontend will send a89 SASLInitialResponse with the name of the selected mechanism, and the90 first part of the SASL data stream in response to this. If further91 messages are needed, the server will respond with92 AuthenticationSASLContinue. See <a class="xref" href="sasl-authentication.html" title="55.3. SASL Authentication">Section 55.3</a>93 for details.94 </p></dd><dt><span class="term">AuthenticationSASLContinue</span></dt><dd><p>95 This message contains challenge data from the previous step of SASL96 negotiation (AuthenticationSASL, or a previous97 AuthenticationSASLContinue). The frontend must respond with a98 SASLResponse message.99 </p></dd><dt><span class="term">AuthenticationSASLFinal</span></dt><dd><p>100 SASL authentication has completed with additional mechanism-specific101 data for the client. The server will next send AuthenticationOk to102 indicate successful authentication, or an ErrorResponse to indicate103 failure. This message is sent only if the SASL mechanism specifies104 additional data to be sent from server to client at completion.105 </p></dd><dt><span class="term">NegotiateProtocolVersion</span></dt><dd><p>106 The server does not support the minor protocol version requested107 by the client, but does support an earlier version of the protocol;108 this message indicates the highest supported minor version. This109 message will also be sent if the client requested unsupported protocol110 options (i.e., beginning with <code class="literal">_pq_.</code>) in the111 startup packet. This message will be followed by an ErrorResponse or112 a message indicating the success or failure of authentication.113 </p></dd></dl></div><p>114 </p><p>115 If the frontend does not support the authentication method116 requested by the server, then it should immediately close the117 connection.118 </p><p>119 After having received AuthenticationOk, the frontend must wait120 for further messages from the server. In this phase a backend process121 is being started, and the frontend is just an interested bystander.122 It is still possible for the startup attempt123 to fail (ErrorResponse) or the server to decline support for the requested124 minor protocol version (NegotiateProtocolVersion), but in the normal case125 the backend will send some ParameterStatus messages, BackendKeyData, and126 finally ReadyForQuery.127 </p><p>128 During this phase the backend will attempt to apply any additional129 run-time parameter settings that were given in the startup message.130 If successful, these values become session defaults. An error causes131 ErrorResponse and exit.132 </p><p>133 The possible messages from the backend in this phase are:134 135 </p><div class="variablelist"><dl class="variablelist"><dt><span class="term">BackendKeyData</span></dt><dd><p>136 This message provides secret-key data that the frontend must137 save if it wants to be able to issue cancel requests later.138 The frontend should not respond to this message, but should139 continue listening for a ReadyForQuery message.140 </p></dd><dt><span class="term">ParameterStatus</span></dt><dd><p>141 This message informs the frontend about the current (initial)142 setting of backend parameters, such as <a class="xref" href="runtime-config-client.html#GUC-CLIENT-ENCODING">client_encoding</a> or <a class="xref" href="runtime-config-client.html#GUC-DATESTYLE">DateStyle</a>.143 The frontend can ignore this message, or record the settings144 for its future use; see <a class="xref" href="protocol-flow.html#PROTOCOL-ASYNC" title="55.2.7. Asynchronous Operations">Section 55.2.7</a> for145 more details. The frontend should not respond to this146 message, but should continue listening for a ReadyForQuery147 message.148 </p></dd><dt><span class="term">ReadyForQuery</span></dt><dd><p>149 Start-up is completed. The frontend can now issue commands.150 </p></dd><dt><span class="term">ErrorResponse</span></dt><dd><p>151 Start-up failed. The connection is closed after sending this152 message.153 </p></dd><dt><span class="term">NoticeResponse</span></dt><dd><p>154 A warning message has been issued. The frontend should155 display the message but continue listening for ReadyForQuery156 or ErrorResponse.157 </p></dd></dl></div><p>158 </p><p>159 The ReadyForQuery message is the same one that the backend will160 issue after each command cycle. Depending on the coding needs of161 the frontend, it is reasonable to consider ReadyForQuery as162 starting a command cycle, or to consider ReadyForQuery as ending the163 start-up phase and each subsequent command cycle.164 </p></div><div class="sect2" id="PROTOCOL-FLOW-SIMPLE-QUERY"><div class="titlepage"><div><div><h3 class="title">55.2.2. Simple Query <a href="#PROTOCOL-FLOW-SIMPLE-QUERY" class="id_link">#</a></h3></div></div></div><p>165 A simple query cycle is initiated by the frontend sending a Query message166 to the backend. The message includes an SQL command (or commands)167 expressed as a text string.168 The backend then sends one or more response169 messages depending on the contents of the query command string,170 and finally a ReadyForQuery response message. ReadyForQuery171 informs the frontend that it can safely send a new command.172 (It is not actually necessary for the frontend to wait for173 ReadyForQuery before issuing another command, but the frontend must174 then take responsibility for figuring out what happens if the earlier175 command fails and already-issued later commands succeed.)176 </p><p>177 The possible response messages from the backend are:178 179 </p><div class="variablelist"><dl class="variablelist"><dt><span class="term">CommandComplete</span></dt><dd><p>180 An SQL command completed normally.181 </p></dd><dt><span class="term">CopyInResponse</span></dt><dd><p>182 The backend is ready to copy data from the frontend to a183 table; see <a class="xref" href="protocol-flow.html#PROTOCOL-COPY" title="55.2.6. COPY Operations">Section 55.2.6</a>.184 </p></dd><dt><span class="term">CopyOutResponse</span></dt><dd><p>185 The backend is ready to copy data from a table to the186 frontend; see <a class="xref" href="protocol-flow.html#PROTOCOL-COPY" title="55.2.6. COPY Operations">Section 55.2.6</a>.187 </p></dd><dt><span class="term">RowDescription</span></dt><dd><p>188 Indicates that rows are about to be returned in response to189 a <code class="command">SELECT</code>, <code class="command">FETCH</code>, etc. query.190 The contents of this message describe the column layout of the rows.191 This will be followed by a DataRow message for each row being returned192 to the frontend.193 </p></dd><dt><span class="term">DataRow</span></dt><dd><p>194 One of the set of rows returned by195 a <code class="command">SELECT</code>, <code class="command">FETCH</code>, etc. query.196 </p></dd><dt><span class="term">EmptyQueryResponse</span></dt><dd><p>197 An empty query string was recognized.198 </p></dd><dt><span class="term">ErrorResponse</span></dt><dd><p>199 An error has occurred.200 </p></dd><dt><span class="term">ReadyForQuery</span></dt><dd><p>201 Processing of the query string is complete. A separate202 message is sent to indicate this because the query string might203 contain multiple SQL commands. (CommandComplete marks the204 end of processing one SQL command, not the whole string.)205 ReadyForQuery will always be sent, whether processing206 terminates successfully or with an error.207 </p></dd><dt><span class="term">NoticeResponse</span></dt><dd><p>208 A warning message has been issued in relation to the query.209 Notices are in addition to other responses, i.e., the backend210 will continue processing the command.211 </p></dd></dl></div><p>212 </p><p>213 The response to a <code class="command">SELECT</code> query (or other queries that214 return row sets, such as <code class="command">EXPLAIN</code> or <code class="command">SHOW</code>)215 normally consists of RowDescription, zero or more216 DataRow messages, and then CommandComplete.217 <code class="command">COPY</code> to or from the frontend invokes special protocol218 as described in <a class="xref" href="protocol-flow.html#PROTOCOL-COPY" title="55.2.6. COPY Operations">Section 55.2.6</a>.219 All other query types normally produce only220 a CommandComplete message.221 </p><p>222 Since a query string could contain several queries (separated by223 semicolons), there might be several such response sequences before the224 backend finishes processing the query string. ReadyForQuery is issued225 when the entire string has been processed and the backend is ready to226 accept a new query string.227 </p><p>228 If a completely empty (no contents other than whitespace) query string229 is received, the response is EmptyQueryResponse followed by ReadyForQuery.230 </p><p>231 In the event of an error, ErrorResponse is issued followed by232 ReadyForQuery. All further processing of the query string is aborted by233 ErrorResponse (even if more queries remained in it). Note that this234 might occur partway through the sequence of messages generated by an235 individual query.236 </p><p>237 In simple Query mode, the format of retrieved values is always text,238 except when the given command is a <code class="command">FETCH</code> from a cursor239 declared with the <code class="literal">BINARY</code> option. In that case, the240 retrieved values are in binary format. The format codes given in241 the RowDescription message tell which format is being used.242 </p><p>243 A frontend must be prepared to accept ErrorResponse and244 NoticeResponse messages whenever it is expecting any other type of245 message. See also <a class="xref" href="protocol-flow.html#PROTOCOL-ASYNC" title="55.2.7. Asynchronous Operations">Section 55.2.7</a> concerning messages246 that the backend might generate due to outside events.247 </p><p>248 Recommended practice is to code frontends in a state-machine style249 that will accept any message type at any time that it could make sense,250 rather than wiring in assumptions about the exact sequence of messages.251 </p><div class="sect3" id="PROTOCOL-FLOW-MULTI-STATEMENT"><div class="titlepage"><div><div><h4 class="title">55.2.2.1. Multiple Statements in a Simple Query <a href="#PROTOCOL-FLOW-MULTI-STATEMENT" class="id_link">#</a></h4></div></div></div><p>252 When a simple Query message contains more than one SQL statement253 (separated by semicolons), those statements are executed as a single254 transaction, unless explicit transaction control commands are included255 to force a different behavior. For example, if the message contains256</p><pre class="programlisting">257INSERT INTO mytable VALUES(1);258SELECT 1/0;259INSERT INTO mytable VALUES(2);260</pre><p>261 then the divide-by-zero failure in the <code class="command">SELECT</code> will force262 rollback of the first <code class="command">INSERT</code>. Furthermore, because263 execution of the message is abandoned at the first error, the second264 <code class="command">INSERT</code> is never attempted at all.265 </p><p>266 If instead the message contains267</p><pre class="programlisting">268BEGIN;269INSERT INTO mytable VALUES(1);270COMMIT;271INSERT INTO mytable VALUES(2);272SELECT 1/0;273</pre><p>274 then the first <code class="command">INSERT</code> is committed by the275 explicit <code class="command">COMMIT</code> command. The second <code class="command">INSERT</code>276 and the <code class="command">SELECT</code> are still treated as a single transaction,277 so that the divide-by-zero failure will roll back the278 second <code class="command">INSERT</code>, but not the first one.279 </p><p>280 This behavior is implemented by running the statements in a281 multi-statement Query message in an <em class="firstterm">implicit transaction282 block</em> unless there is some explicit transaction block for them to283 run in. The main difference between an implicit transaction block and284 a regular one is that an implicit block is closed automatically at the285 end of the Query message, either by an implicit commit if there was no286 error, or an implicit rollback if there was an error. This is similar287 to the implicit commit or rollback that happens for a statement288 executed by itself (when not in a transaction block).289 </p><p>290 If the session is already in a transaction block, as a result of291 a <code class="command">BEGIN</code> in some previous message, then the Query message292 simply continues that transaction block, whether the message contains293 one statement or several. However, if the Query message contains294 a <code class="command">COMMIT</code> or <code class="command">ROLLBACK</code> closing the existing295 transaction block, then any following statements are executed in an296 implicit transaction block.297 Conversely, if a <code class="command">BEGIN</code> appears in a multi-statement Query298 message, then it starts a regular transaction block that will only be299 terminated by an explicit <code class="command">COMMIT</code> or <code class="command">ROLLBACK</code>,300 whether that appears in this Query message or a later one.301 If the <code class="command">BEGIN</code> follows some statements that were executed as302 an implicit transaction block, those statements are not immediately303 committed; in effect, they are retroactively included into the new304 regular transaction block.305 </p><p>306 A <code class="command">COMMIT</code> or <code class="command">ROLLBACK</code> appearing in an implicit307 transaction block is executed as normal, closing the implicit block;308 however, a warning will be issued since a <code class="command">COMMIT</code>309 or <code class="command">ROLLBACK</code> without a previous <code class="command">BEGIN</code> might310 represent a mistake. If more statements follow, a new implicit311 transaction block will be started for them.312 </p><p>313 Savepoints are not allowed in an implicit transaction block, since314 they would conflict with the behavior of automatically closing the315 block upon any error.316 </p><p>317 Remember that, regardless of any transaction control commands that may318 be present, execution of the Query message stops at the first error.319 Thus for example given320</p><pre class="programlisting">321BEGIN;322SELECT 1/0;323ROLLBACK;324</pre><p>325 in a single Query message, the session will be left inside a failed326 regular transaction block, since the <code class="command">ROLLBACK</code> is not327 reached after the divide-by-zero error. Another <code class="command">ROLLBACK</code>328 will be needed to restore the session to a usable state.329 </p><p>330 Another behavior of note is that initial lexical and syntactic331 analysis is done on the entire query string before any of it is332 executed. Thus simple errors (such as a misspelled keyword) in later333 statements can prevent execution of any of the statements. This334 is normally invisible to users since the statements would all roll335 back anyway when done as an implicit transaction block. However,336 it can be visible when attempting to do multiple transactions within a337 multi-statement Query. For instance, if a typo turned our previous338 example into339</p><pre class="programlisting">340BEGIN;341INSERT INTO mytable VALUES(1);342COMMIT;343INSERT INTO mytable VALUES(2);344SELCT 1/0;345</pre><p>346 then none of the statements would get run, resulting in the visible347 difference that the first <code class="command">INSERT</code> is not committed.348 Errors detected at semantic analysis or later, such as a misspelled349 table or column name, do not have this effect.350 </p></div></div><div class="sect2" id="PROTOCOL-FLOW-EXT-QUERY"><div class="titlepage"><div><div><h3 class="title">55.2.3. Extended Query <a href="#PROTOCOL-FLOW-EXT-QUERY" class="id_link">#</a></h3></div></div></div><p>351 The extended query protocol breaks down the above-described simple352 query protocol into multiple steps. The results of preparatory353 steps can be re-used multiple times for improved efficiency.354 Furthermore, additional features are available, such as the possibility355 of supplying data values as separate parameters instead of having to356 insert them directly into a query string.357 </p><p>358 In the extended protocol, the frontend first sends a Parse message,359 which contains a textual query string, optionally some information360 about data types of parameter placeholders, and the361 name of a destination prepared-statement object (an empty string362 selects the unnamed prepared statement). The response is363 either ParseComplete or ErrorResponse. Parameter data types can be364 specified by OID; if not given, the parser attempts to infer the365 data types in the same way as it would do for untyped literal string366 constants.367 </p><div class="note"><h3 class="title">Note</h3><p>368 A parameter data type can be left unspecified by setting it to zero,369 or by making the array of parameter type OIDs shorter than the370 number of parameter symbols (<code class="literal">$</code><em class="replaceable"><code>n</code></em>)371 used in the query string. Another special case is that a parameter's372 type can be specified as <code class="type">void</code> (that is, the OID of the373 <code class="type">void</code> pseudo-type). This is meant to allow parameter symbols374 to be used for function parameters that are actually OUT parameters.375 Ordinarily there is no context in which a <code class="type">void</code> parameter376 could be used, but if such a parameter symbol appears in a function's377 parameter list, it is effectively ignored. For example, a function378 call such as <code class="literal">foo($1,$2,$3,$4)</code> could match a function with379 two IN and two OUT arguments, if <code class="literal">$3</code> and <code class="literal">$4</code>380 are specified as having type <code class="type">void</code>.381 </p></div><div class="note"><h3 class="title">Note</h3><p>382 The query string contained in a Parse message cannot include more383 than one SQL statement; else a syntax error is reported. This384 restriction does not exist in the simple-query protocol, but it385 does exist in the extended protocol, because allowing prepared386 statements or portals to contain multiple commands would complicate387 the protocol unduly.388 </p></div><p>389 If successfully created, a named prepared-statement object lasts till390 the end of the current session, unless explicitly destroyed. An unnamed391 prepared statement lasts only until the next Parse statement specifying392 the unnamed statement as destination is issued. (Note that a simple393 Query message also destroys the unnamed statement.) Named prepared394 statements must be explicitly closed before they can be redefined by395 another Parse message, but this is not required for the unnamed statement.396 Named prepared statements can also be created and accessed at the SQL397 command level, using <code class="command">PREPARE</code> and <code class="command">EXECUTE</code>.398 </p><p>399 Once a prepared statement exists, it can be readied for execution using a400 Bind message. The Bind message gives the name of the source prepared401 statement (empty string denotes the unnamed prepared statement), the name402 of the destination portal (empty string denotes the unnamed portal), and403 the values to use for any parameter placeholders present in the prepared404 statement. The405 supplied parameter set must match those needed by the prepared statement.406 (If you declared any <code class="type">void</code> parameters in the Parse message,407 pass NULL values for them in the Bind message.)408 Bind also specifies the format to use for any data returned409 by the query; the format can be specified overall, or per-column.410 The response is either BindComplete or ErrorResponse.411 </p><div class="note"><h3 class="title">Note</h3><p>412 The choice between text and binary output is determined by the format413 codes given in Bind, regardless of the SQL command involved. The414 <code class="literal">BINARY</code> attribute in cursor declarations is irrelevant when415 using extended query protocol.416 </p></div><p>417 Query planning typically occurs when the Bind message is processed.418 If the prepared statement has no parameters, or is executed repeatedly,419 the server might save the created plan and re-use it during subsequent420 Bind messages for the same prepared statement. However, it will do so421 only if it finds that a generic plan can be created that is not much422 less efficient than a plan that depends on the specific parameter values423 supplied. This happens transparently so far as the protocol is concerned.424 </p><p>425 If successfully created, a named portal object lasts till the end of the426 current transaction, unless explicitly destroyed. An unnamed portal is427 destroyed at the end of the transaction, or as soon as the next Bind428 statement specifying the unnamed portal as destination is issued. (Note429 that a simple Query message also destroys the unnamed portal.) Named430 portals must be explicitly closed before they can be redefined by another431 Bind message, but this is not required for the unnamed portal.432 Named portals can also be created and accessed at the SQL433 command level, using <code class="command">DECLARE CURSOR</code> and <code class="command">FETCH</code>.434 </p><p>435 Once a portal exists, it can be executed using an Execute message.436 The Execute message specifies the portal name (empty string denotes the437 unnamed portal) and438 a maximum result-row count (zero meaning <span class="quote">“<span class="quote">fetch all rows</span>”</span>).439 The result-row count is only meaningful for portals440 containing commands that return row sets; in other cases the command is441 always executed to completion, and the row count is ignored.442 The possible443 responses to Execute are the same as those described above for queries444 issued via simple query protocol, except that Execute doesn't cause445 ReadyForQuery or RowDescription to be issued.446 </p><p>447 If Execute terminates before completing the execution of a portal448 (due to reaching a nonzero result-row count), it will send a449 PortalSuspended message; the appearance of this message tells the frontend450 that another Execute should be issued against the same portal to451 complete the operation. The CommandComplete message indicating452 completion of the source SQL command is not sent until453 the portal's execution is completed. Therefore, an Execute phase is454 always terminated by the appearance of exactly one of these messages:455 CommandComplete, EmptyQueryResponse (if the portal was created from456 an empty query string), ErrorResponse, or PortalSuspended.457 </p><p>458 At completion of each series of extended-query messages, the frontend459 should issue a Sync message. This parameterless message causes the460 backend to close the current transaction if it's not inside a461 <code class="command">BEGIN</code>/<code class="command">COMMIT</code> transaction block (<span class="quote">“<span class="quote">close</span>”</span>462 meaning to commit if no error, or roll back if error). Then a463 ReadyForQuery response is issued. The purpose of Sync is to provide464 a resynchronization point for error recovery. When an error is detected465 while processing any extended-query message, the backend issues466 ErrorResponse, then reads and discards messages until a Sync is reached,467 then issues ReadyForQuery and returns to normal message processing.468 (But note that no skipping occurs if an error is detected469 <span class="emphasis"><em>while</em></span> processing Sync — this ensures that there is one470 and only one ReadyForQuery sent for each Sync.)471 </p><div class="note"><h3 class="title">Note</h3><p>472 Sync does not cause a transaction block opened with <code class="command">BEGIN</code>473 to be closed. It is possible to detect this situation since the474 ReadyForQuery message includes transaction status information.475 </p></div><p>476 In addition to these fundamental, required operations, there are several477 optional operations that can be used with extended-query protocol.478 </p><p>479 The Describe message (portal variant) specifies the name of an existing480 portal (or an empty string for the unnamed portal). The response is a481 RowDescription message describing the rows that will be returned by482 executing the portal; or a NoData message if the portal does not contain a483 query that will return rows; or ErrorResponse if there is no such portal.484 </p><p>485 The Describe message (statement variant) specifies the name of an existing486 prepared statement (or an empty string for the unnamed prepared487 statement). The response is a ParameterDescription message describing the488 parameters needed by the statement, followed by a RowDescription message489 describing the rows that will be returned when the statement is eventually490 executed (or a NoData message if the statement will not return rows).491 ErrorResponse is issued if there is no such prepared statement. Note that492 since Bind has not yet been issued, the formats to be used for returned493 columns are not yet known to the backend; the format code fields in the494 RowDescription message will be zeroes in this case.495 </p><div class="tip"><h3 class="title">Tip</h3><p>496 In most scenarios the frontend should issue one or the other variant497 of Describe before issuing Execute, to ensure that it knows how to498 interpret the results it will get back.499 </p></div><p>500 The Close message closes an existing prepared statement or portal501 and releases resources. It is not an error to issue Close against502 a nonexistent statement or portal name. The response is normally503 CloseComplete, but could be ErrorResponse if some difficulty is504 encountered while releasing resources. Note that closing a prepared505 statement implicitly closes any open portals that were constructed506 from that statement.507 </p><p>508 The Flush message does not cause any specific output to be generated,509 but forces the backend to deliver any data pending in its output510 buffers. A Flush must be sent after any extended-query command except511 Sync, if the frontend wishes to examine the results of that command before512 issuing more commands. Without Flush, messages returned by the backend513 will be combined into the minimum possible number of packets to minimize514 network overhead.515 </p><div class="note"><h3 class="title">Note</h3><p>516 The simple Query message is approximately equivalent to the series Parse,517 Bind, portal Describe, Execute, Close, Sync, using the unnamed prepared518 statement and portal objects and no parameters. One difference is that519 it will accept multiple SQL statements in the query string, automatically520 performing the bind/describe/execute sequence for each one in succession.521 Another difference is that it will not return ParseComplete, BindComplete,522 CloseComplete, or NoData messages.523 </p></div></div><div class="sect2" id="PROTOCOL-FLOW-PIPELINING"><div class="titlepage"><div><div><h3 class="title">55.2.4. Pipelining <a href="#PROTOCOL-FLOW-PIPELINING" class="id_link">#</a></h3></div></div></div><a id="id-1.10.6.7.6.2" class="indexterm"></a><p>524 Use of the extended query protocol525 allows <em class="firstterm">pipelining</em>, which means sending a series526 of queries without waiting for earlier ones to complete. This reduces527 the number of network round trips needed to complete a given series of528 operations. However, the user must carefully consider the required529 behavior if one of the steps fails, since later queries will already530 be in flight to the server.531 </p><p>532 One way to deal with that is to make the whole query series be a533 single transaction, that is wrap it in <code class="command">BEGIN</code> ...534 <code class="command">COMMIT</code>. However, this does not help if one wishes535 for some of the commands to commit independently of others.536 </p><p>537 The extended query protocol provides another way to manage this538 concern, which is to omit sending Sync messages between steps that539 are dependent. Since, after an error, the backend will skip command540 messages until it finds Sync, this allows later commands in a pipeline541 to be skipped automatically when an earlier one fails, without the542 client having to manage that explicitly with <code class="command">BEGIN</code>543 and <code class="command">COMMIT</code>. Independently-committable segments544 of the pipeline can be separated by Sync messages.545 </p><p>546 If the client has not issued an explicit <code class="command">BEGIN</code>,547 then each Sync ordinarily causes an implicit <code class="command">COMMIT</code>548 if the preceding step(s) succeeded, or an549 implicit <code class="command">ROLLBACK</code> if they failed. However, there550 are a few DDL commands (such as <code class="command">CREATE DATABASE</code>)551 that cannot be executed inside a transaction block. If one of552 these is executed in a pipeline, it will fail unless it is the first553 command in the pipeline. Furthermore, upon success it will force an554 immediate commit to preserve database consistency. Thus a Sync555 immediately following one of these commands has no effect except to556 respond with ReadyForQuery.557 </p><p>558 When using this method, completion of the pipeline must be determined559 by counting ReadyForQuery messages and waiting for that to reach the560 number of Syncs sent. Counting command completion responses is561 unreliable, since some of the commands may be skipped and thus not562 produce a completion message.563 </p></div><div class="sect2" id="PROTOCOL-FLOW-FUNCTION-CALL"><div class="titlepage"><div><div><h3 class="title">55.2.5. Function Call <a href="#PROTOCOL-FLOW-FUNCTION-CALL" class="id_link">#</a></h3></div></div></div><p>564 The Function Call sub-protocol allows the client to request a direct565 call of any function that exists in the database's566 <code class="structname">pg_proc</code> system catalog. The client must have567 execute permission for the function.568 </p><div class="note"><h3 class="title">Note</h3><p>569 The Function Call sub-protocol is a legacy feature that is probably best570 avoided in new code. Similar results can be accomplished by setting up571 a prepared statement that does <code class="literal">SELECT function($1, ...)</code>.572 The Function Call cycle can then be replaced with Bind/Execute.573 </p></div><p>574 A Function Call cycle is initiated by the frontend sending a575 FunctionCall message to the backend. The backend then sends one576 or more response messages depending on the results of the function577 call, and finally a ReadyForQuery response message. ReadyForQuery578 informs the frontend that it can safely send a new query or579 function call.580 </p><p>581 The possible response messages from the backend are:582 583 </p><div class="variablelist"><dl class="variablelist"><dt><span class="term">ErrorResponse</span></dt><dd><p>584 An error has occurred.585 </p></dd><dt><span class="term">FunctionCallResponse</span></dt><dd><p>586 The function call was completed and returned the result given587 in the message.588 (Note that the Function Call protocol can only handle a single589 scalar result, not a row type or set of results.)590 </p></dd><dt><span class="term">ReadyForQuery</span></dt><dd><p>591 Processing of the function call is complete. ReadyForQuery592 will always be sent, whether processing terminates593 successfully or with an error.594 </p></dd><dt><span class="term">NoticeResponse</span></dt><dd><p>595 A warning message has been issued in relation to the function596 call. Notices are in addition to other responses, i.e., the597 backend will continue processing the command.598 </p></dd></dl></div><p>599 </p></div><div class="sect2" id="PROTOCOL-COPY"><div class="titlepage"><div><div><h3 class="title">55.2.6. COPY Operations <a href="#PROTOCOL-COPY" class="id_link">#</a></h3></div></div></div><p>600 The <code class="command">COPY</code> command allows high-speed bulk data transfer601 to or from the server. Copy-in and copy-out operations each switch602 the connection into a distinct sub-protocol, which lasts until the603 operation is completed.604 </p><p>605 Copy-in mode (data transfer to the server) is initiated when the606 backend executes a <code class="command">COPY FROM STDIN</code> SQL statement. The backend607 sends a CopyInResponse message to the frontend. The frontend should608 then send zero or more CopyData messages, forming a stream of input609 data. (The message boundaries are not required to have anything to do610 with row boundaries, although that is often a reasonable choice.)611 The frontend can terminate the copy-in mode by sending either a CopyDone612 message (allowing successful termination) or a CopyFail message (which613 will cause the <code class="command">COPY</code> SQL statement to fail with an614 error). The backend then reverts to the command-processing mode it was615 in before the <code class="command">COPY</code> started, which will be either simple or616 extended query protocol. It will next send either CommandComplete617 (if successful) or ErrorResponse (if not).618 </p><p>619 In the event of a backend-detected error during copy-in mode (including620 receipt of a CopyFail message), the backend will issue an ErrorResponse621 message. If the <code class="command">COPY</code> command was issued via an extended-query622 message, the backend will now discard frontend messages until a Sync623 message is received, then it will issue ReadyForQuery and return to normal624 processing. If the <code class="command">COPY</code> command was issued in a simple625 Query message, the rest of that message is discarded and ReadyForQuery626 is issued. In either case, any subsequent CopyData, CopyDone, or CopyFail627 messages issued by the frontend will simply be dropped.628 </p><p>629 The backend will ignore Flush and Sync messages received during copy-in630 mode. Receipt of any other non-copy message type constitutes an error631 that will abort the copy-in state as described above. (The exception for632 Flush and Sync is for the convenience of client libraries that always633 send Flush or Sync after an Execute message, without checking whether634 the command to be executed is a <code class="command">COPY FROM STDIN</code>.)635 </p><p>636 Copy-out mode (data transfer from the server) is initiated when the637 backend executes a <code class="command">COPY TO STDOUT</code> SQL statement. The backend638 sends a CopyOutResponse message to the frontend, followed by639 zero or more CopyData messages (always one per row), followed by CopyDone.640 The backend then reverts to the command-processing mode it was641 in before the <code class="command">COPY</code> started, and sends CommandComplete.642 The frontend cannot abort the transfer (except by closing the connection643 or issuing a Cancel request),644 but it can discard unwanted CopyData and CopyDone messages.645 </p><p>646 In the event of a backend-detected error during copy-out mode,647 the backend will issue an ErrorResponse message and revert to normal648 processing. The frontend should treat receipt of ErrorResponse as649 terminating the copy-out mode.650 </p><p>651 It is possible for NoticeResponse and ParameterStatus messages to be652 interspersed between CopyData messages; frontends must handle these cases,653 and should be prepared for other asynchronous message types as well (see654 <a class="xref" href="protocol-flow.html#PROTOCOL-ASYNC" title="55.2.7. Asynchronous Operations">Section 55.2.7</a>). Otherwise, any message type other than655 CopyData or CopyDone may be treated as terminating copy-out mode.656 </p><p>657 There is another Copy-related mode called copy-both, which allows658 high-speed bulk data transfer to <span class="emphasis"><em>and</em></span> from the server.659 Copy-both mode is initiated when a backend in walsender mode660 executes a <code class="command">START_REPLICATION</code> statement. The661 backend sends a CopyBothResponse message to the frontend. Both662 the backend and the frontend may then send CopyData messages663 until either end sends a CopyDone message. After the client664 sends a CopyDone message, the connection goes from copy-both mode to665 copy-out mode, and the client may not send any more CopyData messages.666 Similarly, when the server sends a CopyDone message, the connection667 goes into copy-in mode, and the server may not send any more CopyData668 messages. After both sides have sent a CopyDone message, the copy mode669 is terminated, and the backend reverts to the command-processing mode.670 In the event of a backend-detected error during copy-both mode,671 the backend will issue an ErrorResponse message, discard frontend messages672 until a Sync message is received, and then issue ReadyForQuery and return673 to normal processing. The frontend should treat receipt of ErrorResponse674 as terminating the copy in both directions; no CopyDone should be sent675 in this case. See <a class="xref" href="protocol-replication.html" title="55.4. Streaming Replication Protocol">Section 55.4</a> for more676 information on the subprotocol transmitted over copy-both mode.677 </p><p>678 The CopyInResponse, CopyOutResponse and CopyBothResponse messages679 include fields that inform the frontend of the number of columns680 per row and the format codes being used for each column. (As of681 the present implementation, all columns in a given <code class="command">COPY</code>682 operation will use the same format, but the message design does not683 assume this.)684 </p></div><div class="sect2" id="PROTOCOL-ASYNC"><div class="titlepage"><div><div><h3 class="title">55.2.7. Asynchronous Operations <a href="#PROTOCOL-ASYNC" class="id_link">#</a></h3></div></div></div><p>685 There are several cases in which the backend will send messages that686 are not specifically prompted by the frontend's command stream.687 Frontends must be prepared to deal with these messages at any time,688 even when not engaged in a query.689 At minimum, one should check for these cases before beginning to690 read a query response.691 </p><p>692 It is possible for NoticeResponse messages to be generated due to693 outside activity; for example, if the database administrator commands694 a <span class="quote">“<span class="quote">fast</span>”</span> database shutdown, the backend will send a NoticeResponse695 indicating this fact before closing the connection. Accordingly,696 frontends should always be prepared to accept and display NoticeResponse697 messages, even when the connection is nominally idle.698 </p><p>699 ParameterStatus messages will be generated whenever the active700 value changes for any of the parameters the backend believes the701 frontend should know about. Most commonly this occurs in response702 to a <code class="command">SET</code> SQL command executed by the frontend, and703 this case is effectively synchronous — but it is also possible704 for parameter status changes to occur because the administrator705 changed a configuration file and then sent the706 <span class="systemitem">SIGHUP</span> signal to the server. Also,707 if a <code class="command">SET</code> command is rolled back, an appropriate708 ParameterStatus message will be generated to report the current709 effective value.710 </p><p>711 At present there is a hard-wired set of parameters for which712 ParameterStatus will be generated. They are:713 </p><table border="0" summary="Simple list" class="simplelist"><tr><td><code class="varname">application_name</code></td><td><code class="varname">is_superuser</code></td></tr><tr><td><code class="varname">client_encoding</code></td><td><code class="varname">scram_iterations</code></td></tr><tr><td><code class="varname">DateStyle</code></td><td><code class="varname">server_encoding</code></td></tr><tr><td><code class="varname">default_transaction_read_only</code></td><td><code class="varname">server_version</code></td></tr><tr><td><code class="varname">in_hot_standby</code></td><td><code class="varname">session_authorization</code></td></tr><tr><td><code class="varname">integer_datetimes</code></td><td><code class="varname">standard_conforming_strings</code></td></tr><tr><td><code class="varname">IntervalStyle</code></td><td><code class="varname">TimeZone</code></td></tr></table><p>714 (<code class="varname">server_encoding</code>, <code class="varname">TimeZone</code>, and715 <code class="varname">integer_datetimes</code> were not reported by releases before 8.0;716 <code class="varname">standard_conforming_strings</code> was not reported by releases717 before 8.1;718 <code class="varname">IntervalStyle</code> was not reported by releases before 8.4;719 <code class="varname">application_name</code> was not reported by releases before720 9.0;721 <code class="varname">default_transaction_read_only</code> and722 <code class="varname">in_hot_standby</code> were not reported by releases before723 14; <code class="varname">scram_iterations</code> was not reported by releases724 before 16.)725 Note that726 <code class="varname">server_version</code>,727 <code class="varname">server_encoding</code> and728 <code class="varname">integer_datetimes</code>729 are pseudo-parameters that cannot change after startup.730 This set might change in the future, or even become configurable.731 Accordingly, a frontend should simply ignore ParameterStatus for732 parameters that it does not understand or care about.733 </p><p>734 If a frontend issues a <code class="command">LISTEN</code> command, then the735 backend will send a NotificationResponse message (not to be736 confused with NoticeResponse!) whenever a737 <code class="command">NOTIFY</code> command is executed for the same738 channel name.739 </p><div class="note"><h3 class="title">Note</h3><p>740 At present, NotificationResponse can only be sent outside a741 transaction, and thus it will not occur in the middle of a742 command-response series, though it might occur just before ReadyForQuery.743 It is unwise to design frontend logic that assumes that, however.744 Good practice is to be able to accept NotificationResponse at any745 point in the protocol.746 </p></div></div><div class="sect2" id="PROTOCOL-FLOW-CANCELING-REQUESTS"><div class="titlepage"><div><div><h3 class="title">55.2.8. Canceling Requests in Progress <a href="#PROTOCOL-FLOW-CANCELING-REQUESTS" class="id_link">#</a></h3></div></div></div><p>747 During the processing of a query, the frontend might request748 cancellation of the query. The cancel request is not sent749 directly on the open connection to the backend for reasons of750 implementation efficiency: we don't want to have the backend751 constantly checking for new input from the frontend during query752 processing. Cancel requests should be relatively infrequent, so753 we make them slightly cumbersome in order to avoid a penalty in754 the normal case.755 </p><p>756 To issue a cancel request, the frontend opens a new connection to757 the server and sends a CancelRequest message, rather than the758 StartupMessage message that would ordinarily be sent across a new759 connection. The server will process this request and then close760 the connection. For security reasons, no direct reply is made to761 the cancel request message.762 </p><p>763 A CancelRequest message will be ignored unless it contains the764 same key data (PID and secret key) passed to the frontend during765 connection start-up. If the request matches the PID and secret766 key for a currently executing backend, the processing of the767 current query is aborted. (In the existing implementation, this is768 done by sending a special signal to the backend process that is769 processing the query.)770 </p><p>771 The cancellation signal might or might not have any effect — for772 example, if it arrives after the backend has finished processing773 the query, then it will have no effect. If the cancellation is774 effective, it results in the current command being terminated775 early with an error message.776 </p><p>777 The upshot of all this is that for reasons of both security and778 efficiency, the frontend has no direct way to tell whether a779 cancel request has succeeded. It must continue to wait for the780 backend to respond to the query. Issuing a cancel simply improves781 the odds that the current query will finish soon, and improves the782 odds that it will fail with an error message instead of783 succeeding.784 </p><p>785 Since the cancel request is sent across a new connection to the786 server and not across the regular frontend/backend communication787 link, it is possible for the cancel request to be issued by any788 process, not just the frontend whose query is to be canceled.789 This might provide additional flexibility when building790 multiple-process applications. It also introduces a security791 risk, in that unauthorized persons might try to cancel queries.792 The security risk is addressed by requiring a dynamically793 generated secret key to be supplied in cancel requests.794 </p></div><div class="sect2" id="PROTOCOL-FLOW-TERMINATION"><div class="titlepage"><div><div><h3 class="title">55.2.9. Termination <a href="#PROTOCOL-FLOW-TERMINATION" class="id_link">#</a></h3></div></div></div><p>795 The normal, graceful termination procedure is that the frontend796 sends a Terminate message and immediately closes the connection.797 On receipt of this message, the backend closes the connection and798 terminates.799 </p><p>800 In rare cases (such as an administrator-commanded database shutdown)801 the backend might disconnect without any frontend request to do so.802 In such cases the backend will attempt to send an error or notice message803 giving the reason for the disconnection before it closes the connection.804 </p><p>805 Other termination scenarios arise from various failure cases, such as core806 dump at one end or the other, loss of the communications link, loss of807 message-boundary synchronization, etc. If either frontend or backend sees808 an unexpected closure of the connection, it should clean809 up and terminate. The frontend has the option of launching a new backend810 by recontacting the server if it doesn't want to terminate itself.811 Closing the connection is also advisable if an unrecognizable message type812 is received, since this probably indicates loss of message-boundary sync.813 </p><p>814 For either normal or abnormal termination, any open transaction is815 rolled back, not committed. One should note however that if a816 frontend disconnects while a non-<code class="command">SELECT</code> query817 is being processed, the backend will probably finish the query818 before noticing the disconnection. If the query is outside any819 transaction block (<code class="command">BEGIN</code> ... <code class="command">COMMIT</code>820 sequence) then its results might be committed before the821 disconnection is recognized.822 </p></div><div class="sect2" id="PROTOCOL-FLOW-SSL"><div class="titlepage"><div><div><h3 class="title">55.2.10. <acronym class="acronym">SSL</acronym> Session Encryption <a href="#PROTOCOL-FLOW-SSL" class="id_link">#</a></h3></div></div></div><p>823 If <span class="productname">PostgreSQL</span> was built with824 <acronym class="acronym">SSL</acronym> support, frontend/backend communications825 can be encrypted using <acronym class="acronym">SSL</acronym>. This provides826 communication security in environments where attackers might be827 able to capture the session traffic. For more information on828 encrypting <span class="productname">PostgreSQL</span> sessions with829 <acronym class="acronym">SSL</acronym>, see <a class="xref" href="ssl-tcp.html" title="19.9. Secure TCP/IP Connections with SSL">Section 19.9</a>.830 </p><p>831 To initiate an <acronym class="acronym">SSL</acronym>-encrypted connection, the832 frontend initially sends an SSLRequest message rather than a833 StartupMessage. The server then responds with a single byte834 containing <code class="literal">S</code> or <code class="literal">N</code>, indicating that it is835 willing or unwilling to perform <acronym class="acronym">SSL</acronym>,836 respectively. The frontend might close the connection at this point837 if it is dissatisfied with the response. To continue after838 <code class="literal">S</code>, perform an <acronym class="acronym">SSL</acronym> startup handshake839 (not described here, part of the <acronym class="acronym">SSL</acronym>840 specification) with the server. If this is successful, continue841 with sending the usual StartupMessage. In this case the842 StartupMessage and all subsequent data will be843 <acronym class="acronym">SSL</acronym>-encrypted. To continue after844 <code class="literal">N</code>, send the usual StartupMessage and proceed without845 encryption.846 (Alternatively, it is permissible to issue a GSSENCRequest message847 after an <code class="literal">N</code> response to try to848 use <acronym class="acronym">GSSAPI</acronym> encryption instead849 of <acronym class="acronym">SSL</acronym>.)850 </p><p>851 The frontend should also be prepared to handle an ErrorMessage852 response to SSLRequest from the server. This would only occur if853 the server predates the addition of <acronym class="acronym">SSL</acronym> support854 to <span class="productname">PostgreSQL</span>. (Such servers are now very ancient,855 and likely do not exist in the wild anymore.)856 In this case the connection must857 be closed, but the frontend might choose to open a fresh connection858 and proceed without requesting <acronym class="acronym">SSL</acronym>.859 </p><p>860 When <acronym class="acronym">SSL</acronym> encryption can be performed, the server861 is expected to send only the single <code class="literal">S</code> byte and then862 wait for the frontend to initiate an <acronym class="acronym">SSL</acronym> handshake.863 If additional bytes are available to read at this point, it likely864 means that a man-in-the-middle is attempting to perform a865 buffer-stuffing attack866 (<a class="ulink" href="https://www.postgresql.org/support/security/CVE-2021-23222/" target="_top">CVE-2021-23222</a>).867 Frontends should be coded either to read exactly one byte from the868 socket before turning the socket over to their SSL library, or to869 treat it as a protocol violation if they find they have read additional870 bytes.871 </p><p>872 An initial SSLRequest can also be used in a connection that is being873 opened to send a CancelRequest message.874 </p><p>875 While the protocol itself does not provide a way for the server to876 force <acronym class="acronym">SSL</acronym> encryption, the administrator can877 configure the server to reject unencrypted sessions as a byproduct878 of authentication checking.879 </p></div><div class="sect2" id="PROTOCOL-FLOW-GSSAPI"><div class="titlepage"><div><div><h3 class="title">55.2.11. <acronym class="acronym">GSSAPI</acronym> Session Encryption <a href="#PROTOCOL-FLOW-GSSAPI" class="id_link">#</a></h3></div></div></div><p>880 If <span class="productname">PostgreSQL</span> was built with881 <acronym class="acronym">GSSAPI</acronym> support, frontend/backend communications882 can be encrypted using <acronym class="acronym">GSSAPI</acronym>. This provides883 communication security in environments where attackers might be884 able to capture the session traffic. For more information on885 encrypting <span class="productname">PostgreSQL</span> sessions with886 <acronym class="acronym">GSSAPI</acronym>, see <a class="xref" href="gssapi-enc.html" title="19.10. Secure TCP/IP Connections with GSSAPI Encryption">Section 19.10</a>.887 </p><p>888 To initiate a <acronym class="acronym">GSSAPI</acronym>-encrypted connection, the889 frontend initially sends a GSSENCRequest message rather than a890 StartupMessage. The server then responds with a single byte891 containing <code class="literal">G</code> or <code class="literal">N</code>, indicating that it892 is willing or unwilling to perform <acronym class="acronym">GSSAPI</acronym> encryption,893 respectively. The frontend might close the connection at this point894 if it is dissatisfied with the response. To continue after895 <code class="literal">G</code>, using the GSSAPI C bindings as discussed in896 <a class="ulink" href="https://datatracker.ietf.org/doc/html/rfc2744" target="_top">RFC 2744</a>897 or equivalent, perform a <acronym class="acronym">GSSAPI</acronym> initialization by898 calling <code class="function">gss_init_sec_context()</code> in a loop and sending899 the result to the server, starting with an empty input and then with each900 result from the server, until it returns no output. When sending the901 results of <code class="function">gss_init_sec_context()</code> to the server,902 prepend the length of the message as a four byte integer in network byte903 order.904 To continue after905 <code class="literal">N</code>, send the usual StartupMessage and proceed without906 encryption.907 (Alternatively, it is permissible to issue an SSLRequest message908 after an <code class="literal">N</code> response to try to909 use <acronym class="acronym">SSL</acronym> encryption instead910 of <acronym class="acronym">GSSAPI</acronym>.)911 </p><p>912 The frontend should also be prepared to handle an ErrorMessage913 response to GSSENCRequest from the server. This would only occur if914 the server predates the addition of <acronym class="acronym">GSSAPI</acronym> encryption915 support to <span class="productname">PostgreSQL</span>. In this case the916 connection must be closed, but the frontend might choose to open a fresh917 connection and proceed without requesting <acronym class="acronym">GSSAPI</acronym>918 encryption.919 </p><p>920 When <acronym class="acronym">GSSAPI</acronym> encryption can be performed, the server921 is expected to send only the single <code class="literal">G</code> byte and then922 wait for the frontend to initiate a <acronym class="acronym">GSSAPI</acronym> handshake.923 If additional bytes are available to read at this point, it likely924 means that a man-in-the-middle is attempting to perform a925 buffer-stuffing attack926 (<a class="ulink" href="https://www.postgresql.org/support/security/CVE-2021-23222/" target="_top">CVE-2021-23222</a>).927 Frontends should be coded either to read exactly one byte from the928 socket before turning the socket over to their GSSAPI library, or to929 treat it as a protocol violation if they find they have read additional930 bytes.931 </p><p>932 An initial GSSENCRequest can also be used in a connection that is being933 opened to send a CancelRequest message.934 </p><p>935 Once <acronym class="acronym">GSSAPI</acronym> encryption has been successfully936 established, use <code class="function">gss_wrap()</code> to937 encrypt the usual StartupMessage and all subsequent data, prepending the938 length of the result from <code class="function">gss_wrap()</code> as a four byte939 integer in network byte order to the actual encrypted payload. Note that940 the server will only accept encrypted packets from the client which are less941 than 16kB; <code class="function">gss_wrap_size_limit()</code> should be used by the942 client to determine the size of the unencrypted message which will fit943 within this limit and larger messages should be broken up into multiple944 <code class="function">gss_wrap()</code> calls. Typical segments are 8kB of945 unencrypted data, resulting in encrypted packets of slightly larger than 8kB946 but well within the 16kB maximum. The server can be expected to not send947 encrypted packets of larger than 16kB to the client.948 </p><p>949 While the protocol itself does not provide a way for the server to950 force <acronym class="acronym">GSSAPI</acronym> encryption, the administrator can951 configure the server to reject unencrypted sessions as a byproduct952 of authentication checking.953 </p></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="protocol-overview.html" title="55.1. Overview">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="protocol.html" title="Chapter 55. Frontend/Backend Protocol">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="sasl-authentication.html" title="55.3. SASL Authentication">Next</a></td></tr><tr><td width="40%" align="left" valign="top">55.1. Overview </td><td width="20%" align="center"><a accesskey="h" href="index.html" title="PostgreSQL 16.3 Documentation">Home</a></td><td width="40%" align="right" valign="top"> 55.3. SASL Authentication</td></tr></table></div></body></html>