pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Make query cancellation keys longer
40+ messages / 10 participants
[nested] [flat]

Commits from this thread:
  2025-04-03 b82e7eddb0  Add missing declarations to pg_config.h.in
  2025-04-02 b05751220b  docs: Add a new section and a table listing protocol versions
  2025-04-02 a460251f0a  Make cancel request keys longer
  2025-04-02 09be391126 8e34acfda1 1604939b22 9dcfcb92ff b282280e9b  Add timingsafe_bcmp(), for constant-time memory comparison
  2025-04-02 85d799ba8a  docs: Update phrase on message lengths in the protocol
  2025-02-24 e87c14b19e  libpq: Trace all NegotiateProtocolVersion fields
  2025-02-24 c9d94ea215  libpq: Add PQfullProtocolVersion to exports.txt
  2024-07-29 9d9b9d46f3  Move cancel key generation to after forking the backend
* Make query cancellation keys longer
@ 2024-02-29 21:25  Heikki Linnakangas <hlinnaka@iki.fi>
  0 siblings, 2 replies; 40+ messages in thread

From: Heikki Linnakangas @ 2024-02-29 21:25 UTC (permalink / raw)
  To: pgsql-hackers

Currently, cancel request key is a 32-bit token, which isn't very much 
entropy. If you want to cancel another session's query, you can 
brute-force it. In most environments, an unauthorized cancellation of a 
query isn't very serious, but it nevertheless would be nice to have more 
protection from it. The attached patch makes it longer. It is an 
optional protocol feature, so it's fully backwards-compatible with 
clients that don't support longer keys.

If the client requests the "_pq_.extended_query_cancel" protocol 
feature, the server will generate a longer 256-bit cancellation key. 
However, the new longer key length is no longer hardcoded in the 
protocol. The client is expected to deal with variable length keys, up 
to some reasonable upper limit (TODO: document the maximum). This 
flexibility allows e.g. a connection pooler to add more information to 
the cancel key, which could be useful. If the client doesn't request the 
protocol feature, the server generates a 32-bit key like before.

One complication with this was that because we no longer know how long 
the key should be, 4-bytes or something longer, until the backend has 
performed the protocol negotiation, we cannot generate the key in the 
postmaster before forking the process anymore. The first patch here 
changes things so that the cancellation key is generated later, in the 
backend, and the backend advertises the key in the PMSignalState array. 
This is similar to how this has always worked in EXEC_BACKEND mode with 
the ShmemBackendArray, but instead of having a separate array, I added 
fields to the PMSignalState slots. This removes a bunch of 
EXEC_BACKEND-specific code, which is nice.

Any thoughts on this? Documentation is still missing, and there's one 
TODO on adding a portable time-constant memcmp() function; I'll add 
those if there's agreement on this otherwise.

-- 
Heikki Linnakangas
Neon (https://neon.tech)

Attachments: download all (2 files, .tar.gz)

0001-Move-cancel-key-generation-to-after-forking-the-back.patch (text/x-patch, 23.6K) download From f871e915fee08b3cc27e732646f3a62ec1c3024b Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas <heikki.linnakangas@iki.fi> Date: Thu, 29 Feb 2024 23:20:52 +0200 Subject: [PATCH 1/2] Move cancel key generation to after forking the backend Move responsibility of generating the cancel key to the backend process. The cancel key is now generated after forking, and the backend advertises it in the PMSignalState array. When a cancel request arrives, the backend handling it scans the PMSignalState array to find the target pid and cancel key. This is similar to how this previously worked in the EXEC_BACKEND case with the ShmemBackendArray, but instead of having the separate array, we store the cancel keys in PMSignalState array, and use it also in the !EXEC_BACKEND case. While we're at it, switch to using atomics in pmsignal.c for the state field. That feels easier to reason about than volatile pointers. (TODO: also switch to pg_atomic_flag for PMSignalFlags array. Weirdly we don't have "pg_atomic_test_clear_flag" nor "pg_atomic_set_flag". Those would be the natural opertions for PMSignalFlags. Maybe we should add those, but I didn't want to go that deep down the rabbit hole in this patch.) This is needed by the next patch, so that we can generate the cancel key later, after negotiating the protocol version with the client. --- src/backend/postmaster/postmaster.c | 185 +--------------------------- src/backend/storage/ipc/ipci.c | 11 -- src/backend/storage/ipc/pmsignal.c | 124 ++++++++++++++----- src/backend/storage/lmgr/proc.c | 16 ++- src/include/postmaster/postmaster.h | 3 - src/include/storage/pmsignal.h | 3 +- src/tools/pgindent/typedefs.list | 1 + 7 files changed, 116 insertions(+), 227 deletions(-) diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c index da0c627107e..408f8fb9b6d 100644 --- a/src/backend/postmaster/postmaster.c +++ b/src/backend/postmaster/postmaster.c @@ -177,7 +177,6 @@ typedef struct bkend { pid_t pid; /* process id of backend */ - int32 cancel_key; /* cancel key for cancels for this backend */ int child_slot; /* PMChildSlot for this backend, if any */ int bkend_type; /* child process flavor, see above */ bool dead_end; /* is it going to send an error and quit? */ @@ -187,10 +186,6 @@ typedef struct bkend static dlist_head BackendList = DLIST_STATIC_INIT(BackendList); -#ifdef EXEC_BACKEND -static Backend *ShmemBackendArray; -#endif - BackgroundWorker *MyBgworkerEntry = NULL; @@ -430,7 +425,6 @@ static void SendNegotiateProtocolVersion(List *unrecognized_protocol_options); static void processCancelRequest(Port *port, void *pkt); static void report_fork_failure_to_client(Port *port, int errnum); static CAC_state canAcceptConnections(int backend_type); -static bool RandomCancelKey(int32 *cancel_key); static void signal_child(pid_t pid, int signal); static void sigquit_child(pid_t pid); static bool SignalSomeChildren(int signal, int target); @@ -517,7 +511,6 @@ typedef struct #endif void *UsedShmemSegAddr; slock_t *ShmemLock; - Backend *ShmemBackendArray; #ifndef HAVE_SPINLOCKS PGSemaphore *SpinlockSemaArray; #endif @@ -559,9 +552,6 @@ static bool save_backend_variables(BackendParameters *param, Port *port, Backgro static bool save_backend_variables(BackendParameters *param, Port *port, BackgroundWorker *worker, HANDLE childProcess, pid_t childPid); #endif - -static void ShmemBackendArrayAdd(Backend *bn); -static void ShmemBackendArrayRemove(Backend *bn); #endif /* EXEC_BACKEND */ /* Macros to check exit status of a child process */ @@ -2334,58 +2324,11 @@ processCancelRequest(Port *port, void *pkt) CancelRequestPacket *canc = (CancelRequestPacket *) pkt; int backendPID; int32 cancelAuthCode; - Backend *bp; - -#ifndef EXEC_BACKEND - dlist_iter iter; -#else - int i; -#endif backendPID = (int) pg_ntoh32(canc->backendPID); cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode); - /* - * See if we have a matching backend. In the EXEC_BACKEND case, we can no - * longer access the postmaster's own backend list, and must rely on the - * duplicate array in shared memory. - */ -#ifndef EXEC_BACKEND - dlist_foreach(iter, &BackendList) - { - bp = dlist_container(Backend, elem, iter.cur); -#else - for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--) - { - bp = (Backend *) &ShmemBackendArray[i]; -#endif - if (bp->pid == backendPID) - { - if (bp->cancel_key == cancelAuthCode) - { - /* Found a match; signal that backend to cancel current op */ - ereport(DEBUG2, - (errmsg_internal("processing cancel request: sending SIGINT to process %d", - backendPID))); - signal_child(bp->pid, SIGINT); - } - else - /* Right PID, wrong key: no way, Jose */ - ereport(LOG, - (errmsg("wrong key in cancel request for process %d", - backendPID))); - return; - } -#ifndef EXEC_BACKEND /* make GNU Emacs 26.1 see brace balance */ - } -#else - } -#endif - - /* No matching backend */ - ereport(LOG, - (errmsg("PID %d in cancel request did not match any process", - backendPID))); + SendCancelRequest(backendPID, cancelAuthCode); } /* @@ -3296,9 +3239,6 @@ CleanupBackgroundWorker(int pid, /* Get it out of the BackendList and clear out remaining data */ dlist_delete(&rw->rw_backend->elem); -#ifdef EXEC_BACKEND - ShmemBackendArrayRemove(rw->rw_backend); -#endif /* * It's possible that this background worker started some OTHER @@ -3384,9 +3324,6 @@ CleanupBackend(int pid, HandleChildCrash(pid, exitstatus, _("server process")); return; } -#ifdef EXEC_BACKEND - ShmemBackendArrayRemove(bp); -#endif } if (bp->bgworker_notify) { @@ -3454,9 +3391,6 @@ HandleChildCrash(int pid, int exitstatus, const char *procname) */ (void) ReleasePostmasterChildSlot(rw->rw_child_slot); dlist_delete(&rw->rw_backend->elem); -#ifdef EXEC_BACKEND - ShmemBackendArrayRemove(rw->rw_backend); -#endif pfree(rw->rw_backend); rw->rw_backend = NULL; rw->rw_pid = 0; @@ -3489,9 +3423,6 @@ HandleChildCrash(int pid, int exitstatus, const char *procname) if (!bp->dead_end) { (void) ReleasePostmasterChildSlot(bp->child_slot); -#ifdef EXEC_BACKEND - ShmemBackendArrayRemove(bp); -#endif } dlist_delete(iter.cur); pfree(bp); @@ -4103,22 +4034,6 @@ BackendStartup(Port *port) return STATUS_ERROR; } - /* - * Compute the cancel key that will be assigned to this backend. The - * backend will have its own copy in the forked-off process' value of - * MyCancelKey, so that it can transmit the key to the frontend. - */ - if (!RandomCancelKey(&MyCancelKey)) - { - pfree(bn); - ereport(LOG, - (errcode(ERRCODE_INTERNAL_ERROR), - errmsg("could not generate random cancel key"))); - return STATUS_ERROR; - } - - bn->cancel_key = MyCancelKey; - /* Pass down canAcceptConnections state */ port->canAcceptConnections = canAcceptConnections(BACKEND_TYPE_NORMAL); bn->dead_end = (port->canAcceptConnections != CAC_OK); @@ -4182,11 +4097,6 @@ BackendStartup(Port *port) bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */ dlist_push_head(&BackendList, &bn->elem); -#ifdef EXEC_BACKEND - if (!bn->dead_end) - ShmemBackendArrayAdd(bn); -#endif - return STATUS_OK; } @@ -5252,16 +5162,6 @@ StartupPacketTimeoutHandler(void) _exit(1); } - -/* - * Generate a random cancel key. - */ -static bool -RandomCancelKey(int32 *cancel_key) -{ - return pg_strong_random(cancel_key, sizeof(int32)); -} - /* * Count up number of child processes of specified types (dead_end children * are always excluded). @@ -5437,25 +5337,9 @@ StartAutovacuumWorker(void) */ if (canAcceptConnections(BACKEND_TYPE_AUTOVAC) == CAC_OK) { - /* - * Compute the cancel key that will be assigned to this session. We - * probably don't need cancel keys for autovac workers, but we'd - * better have something random in the field to prevent unfriendly - * people from sending cancels to them. - */ - if (!RandomCancelKey(&MyCancelKey)) - { - ereport(LOG, - (errcode(ERRCODE_INTERNAL_ERROR), - errmsg("could not generate random cancel key"))); - return; - } - bn = (Backend *) palloc_extended(sizeof(Backend), MCXT_ALLOC_NO_OOM); if (bn) { - bn->cancel_key = MyCancelKey; - /* Autovac workers are not dead_end and need a child slot */ bn->dead_end = false; bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot(); @@ -5466,9 +5350,6 @@ StartAutovacuumWorker(void) { bn->bkend_type = BACKEND_TYPE_AUTOVAC; dlist_push_head(&BackendList, &bn->elem); -#ifdef EXEC_BACKEND - ShmemBackendArrayAdd(bn); -#endif /* all OK */ return; } @@ -5600,11 +5481,10 @@ CreateOptsFile(int argc, char *argv[], char *fullprogname) /* * MaxLivePostmasterChildren * - * This reports the number of entries needed in per-child-process arrays - * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray). - * These arrays include regular backends, autovac workers, walsenders + * This reports the number of entries needed in the per-child-process array. + * The array includes regular backends, autovac workers, walsenders * and background workers, but not special children nor dead_end children. - * This allows the arrays to have a fixed maximum size, to wit the same + * This allows the array to have a fixed maximum size, to wit the same * too-many-children limit enforced by canAcceptConnections(). The exact value * isn't too critical as long as it's more than MaxBackends. */ @@ -5804,9 +5684,6 @@ do_start_bgworker(RegisteredBgWorker *rw) ReportBackgroundWorkerPID(rw); /* add new worker to lists of backends */ dlist_push_head(&BackendList, &rw->rw_backend->elem); -#ifdef EXEC_BACKEND - ShmemBackendArrayAdd(rw->rw_backend); -#endif return true; } @@ -5877,20 +5754,6 @@ assign_backendlist_entry(RegisteredBgWorker *rw) return false; } - /* - * Compute the cancel key that will be assigned to this session. We - * probably don't need cancel keys for background workers, but we'd better - * have something random in the field to prevent unfriendly people from - * sending cancels to them. - */ - if (!RandomCancelKey(&MyCancelKey)) - { - ereport(LOG, - (errcode(ERRCODE_INTERNAL_ERROR), - errmsg("could not generate random cancel key"))); - return false; - } - bn = palloc_extended(sizeof(Backend), MCXT_ALLOC_NO_OOM); if (bn == NULL) { @@ -5900,7 +5763,6 @@ assign_backendlist_entry(RegisteredBgWorker *rw) return false; } - bn->cancel_key = MyCancelKey; bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot(); bn->bkend_type = BACKEND_TYPE_BGWORKER; bn->dead_end = false; @@ -6129,7 +5991,6 @@ save_backend_variables(BackendParameters *param, Port *port, BackgroundWorker *w param->UsedShmemSegAddr = UsedShmemSegAddr; param->ShmemLock = ShmemLock; - param->ShmemBackendArray = ShmemBackendArray; #ifndef HAVE_SPINLOCKS param->SpinlockSemaArray = SpinlockSemaArray; @@ -6374,7 +6235,6 @@ restore_backend_variables(BackendParameters *param, Port **port, BackgroundWorke UsedShmemSegAddr = param->UsedShmemSegAddr; ShmemLock = param->ShmemLock; - ShmemBackendArray = param->ShmemBackendArray; #ifndef HAVE_SPINLOCKS SpinlockSemaArray = param->SpinlockSemaArray; @@ -6426,43 +6286,6 @@ restore_backend_variables(BackendParameters *param, Port **port, BackgroundWorke ReserveExternalFD(); #endif } - - -Size -ShmemBackendArraySize(void) -{ - return mul_size(MaxLivePostmasterChildren(), sizeof(Backend)); -} - -void -ShmemBackendArrayAllocation(void) -{ - Size size = ShmemBackendArraySize(); - - ShmemBackendArray = (Backend *) ShmemAlloc(size); - /* Mark all slots as empty */ - memset(ShmemBackendArray, 0, size); -} - -static void -ShmemBackendArrayAdd(Backend *bn) -{ - /* The array slot corresponding to my PMChildSlot should be free */ - int i = bn->child_slot - 1; - - Assert(ShmemBackendArray[i].pid == 0); - ShmemBackendArray[i] = *bn; -} - -static void -ShmemBackendArrayRemove(Backend *bn) -{ - int i = bn->child_slot - 1; - - Assert(ShmemBackendArray[i].pid == bn->pid); - /* Mark the slot as empty */ - ShmemBackendArray[i].pid = 0; -} #endif /* EXEC_BACKEND */ diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c index 7e7941d6259..c2267b7b080 100644 --- a/src/backend/storage/ipc/ipci.c +++ b/src/backend/storage/ipc/ipci.c @@ -155,9 +155,6 @@ CalculateShmemSize(int *num_semaphores) size = add_size(size, WaitEventExtensionShmemSize()); size = add_size(size, InjectionPointShmemSize()); size = add_size(size, SlotSyncShmemSize()); -#ifdef EXEC_BACKEND - size = add_size(size, ShmemBackendArraySize()); -#endif /* include additional requested shmem from preload libraries */ size = add_size(size, total_addin_request); @@ -247,14 +244,6 @@ CreateSharedMemoryAndSemaphores(void) /* Initialize subsystems */ CreateOrAttachShmemStructs(); -#ifdef EXEC_BACKEND - - /* - * Alloc the win32 shared backend array - */ - ShmemBackendArrayAllocation(); -#endif - /* Initialize dynamic shared memory facilities. */ dsm_postmaster_startup(shim); diff --git a/src/backend/storage/ipc/pmsignal.c b/src/backend/storage/ipc/pmsignal.c index 27844b46a2b..9516b869cb2 100644 --- a/src/backend/storage/ipc/pmsignal.c +++ b/src/backend/storage/ipc/pmsignal.c @@ -22,6 +22,7 @@ #endif #include "miscadmin.h" +#include "port/atomics.h" #include "postmaster/postmaster.h" #include "replication/walsender.h" #include "storage/pmsignal.h" @@ -37,9 +38,8 @@ * if the same reason is signaled more than once simultaneously, the * postmaster will observe it only once.) * - * The flags are actually declared as "volatile sig_atomic_t" for maximum - * portability. This should ensure that loads and stores of the flag - * values are atomic, allowing us to dispense with any explicit locking. + * The flag fields use atomics, allowing us to dispense with any explicit + * locking. * * In addition to the per-reason flags, we store a set of per-child-process * flags that are currently used only for detecting whether a backend has @@ -67,20 +67,29 @@ #define PM_CHILD_ACTIVE 2 #define PM_CHILD_WALSENDER 3 +typedef struct ChildSlotData +{ + pg_atomic_uint32 state; + + int pid; + int32 cancel_key; +} ChildSlotData; + /* "typedef struct PMSignalData PMSignalData" appears in pmsignal.h */ struct PMSignalData { /* per-reason flags for signaling the postmaster */ - sig_atomic_t PMSignalFlags[NUM_PMSIGNALS]; + volatile sig_atomic_t PMSignalFlags[NUM_PMSIGNALS]; /* global flags for signals from postmaster to children */ QuitSignalReason sigquit_reason; /* why SIGQUIT was sent */ - /* per-child-process flags */ - int num_child_flags; /* # of entries in PMChildFlags[] */ - sig_atomic_t PMChildFlags[FLEXIBLE_ARRAY_MEMBER]; + + /* per-child-process slots */ + int num_child_slots; /* # of entries in child_slots[] */ + ChildSlotData child_slots[FLEXIBLE_ARRAY_MEMBER]; }; /* PMSignalState pointer is valid in both postmaster and child processes */ -NON_EXEC_STATIC volatile PMSignalData *PMSignalState = NULL; +NON_EXEC_STATIC PMSignalData *PMSignalState = NULL; /* * These static variables are valid only in the postmaster. We keep a @@ -130,9 +139,9 @@ PMSignalShmemSize(void) { Size size; - size = offsetof(PMSignalData, PMChildFlags); + size = offsetof(PMSignalData, child_slots); size = add_size(size, mul_size(MaxLivePostmasterChildren(), - sizeof(sig_atomic_t))); + sizeof(ChildSlotData))); return size; } @@ -151,9 +160,9 @@ PMSignalShmemInit(void) if (!found) { /* initialize all flags to zeroes */ - MemSet(unvolatize(PMSignalData *, PMSignalState), 0, PMSignalShmemSize()); + MemSet(PMSignalState, 0, PMSignalShmemSize()); num_child_inuse = MaxLivePostmasterChildren(); - PMSignalState->num_child_flags = num_child_inuse; + PMSignalState->num_child_slots = num_child_inuse; /* * Also allocate postmaster's private PMChildInUse[] array. We @@ -262,14 +271,14 @@ AssignPostmasterChildSlot(void) if (!PMChildInUse[slot]) { PMChildInUse[slot] = true; - PMSignalState->PMChildFlags[slot] = PM_CHILD_ASSIGNED; + pg_atomic_write_u32(&PMSignalState->child_slots[slot].state, PM_CHILD_ASSIGNED); next_child_inuse = slot; return slot + 1; } } /* Out of slots ... should never happen, else postmaster.c messed up */ - elog(FATAL, "no free slots in PMChildFlags array"); + elog(FATAL, "no free slots in postmaster child array"); return 0; /* keep compiler quiet */ } @@ -283,7 +292,7 @@ AssignPostmasterChildSlot(void) bool ReleasePostmasterChildSlot(int slot) { - bool result; + uint32 oldstate; Assert(slot > 0 && slot <= num_child_inuse); slot--; @@ -293,10 +302,9 @@ ReleasePostmasterChildSlot(int slot) * postmaster.c is such that this might get called twice when a child * crashes. So we don't try to Assert anything about the state. */ - result = (PMSignalState->PMChildFlags[slot] == PM_CHILD_ASSIGNED); - PMSignalState->PMChildFlags[slot] = PM_CHILD_UNUSED; + oldstate = pg_atomic_exchange_u32(&PMSignalState->child_slots[slot].state, PM_CHILD_UNUSED); PMChildInUse[slot] = false; - return result; + return oldstate == PM_CHILD_ASSIGNED; } /* @@ -309,7 +317,7 @@ IsPostmasterChildWalSender(int slot) Assert(slot > 0 && slot <= num_child_inuse); slot--; - if (PMSignalState->PMChildFlags[slot] == PM_CHILD_WALSENDER) + if (pg_atomic_read_u32(&PMSignalState->child_slots[slot].state) == PM_CHILD_WALSENDER) return true; else return false; @@ -320,14 +328,17 @@ IsPostmasterChildWalSender(int slot) * actively using shared memory. This is called in the child process. */ void -MarkPostmasterChildActive(void) +MarkPostmasterChildActive(int pid, int32 cancelAuthCode) { int slot = MyPMChildSlot; - Assert(slot > 0 && slot <= PMSignalState->num_child_flags); + Assert(slot > 0 && slot <= PMSignalState->num_child_slots); slot--; - Assert(PMSignalState->PMChildFlags[slot] == PM_CHILD_ASSIGNED); - PMSignalState->PMChildFlags[slot] = PM_CHILD_ACTIVE; + Assert(pg_atomic_read_u32(&PMSignalState->child_slots[slot].state) == PM_CHILD_ASSIGNED); + PMSignalState->child_slots[slot].pid = pid; + PMSignalState->child_slots[slot].cancel_key = cancelAuthCode; + pg_memory_barrier(); + pg_atomic_write_u32(&PMSignalState->child_slots[slot].state, PM_CHILD_ACTIVE); } /* @@ -342,10 +353,10 @@ MarkPostmasterChildWalSender(void) Assert(am_walsender); - Assert(slot > 0 && slot <= PMSignalState->num_child_flags); + Assert(slot > 0 && slot <= PMSignalState->num_child_slots); slot--; - Assert(PMSignalState->PMChildFlags[slot] == PM_CHILD_ACTIVE); - PMSignalState->PMChildFlags[slot] = PM_CHILD_WALSENDER; + Assert(pg_atomic_read_u32(&PMSignalState->child_slots[slot].state) == PM_CHILD_ACTIVE); + pg_atomic_write_u32(&PMSignalState->child_slots[slot].state, PM_CHILD_WALSENDER); } /* @@ -357,11 +368,17 @@ MarkPostmasterChildInactive(void) { int slot = MyPMChildSlot; - Assert(slot > 0 && slot <= PMSignalState->num_child_flags); + Assert(slot > 0 && slot <= PMSignalState->num_child_slots); slot--; - Assert(PMSignalState->PMChildFlags[slot] == PM_CHILD_ACTIVE || - PMSignalState->PMChildFlags[slot] == PM_CHILD_WALSENDER); - PMSignalState->PMChildFlags[slot] = PM_CHILD_ASSIGNED; +#ifdef USE_ASSERT_CHECKING + { + uint32 oldstate; + + oldstate = pg_atomic_read_u32(&PMSignalState->child_slots[slot].state); + Assert(oldstate == PM_CHILD_ACTIVE || oldstate == PM_CHILD_WALSENDER); + } +#endif + pg_atomic_write_u32(&PMSignalState->child_slots[slot].state, PM_CHILD_ASSIGNED); } @@ -460,3 +477,50 @@ PostmasterDeathSignalInit(void) postmaster_possibly_dead = true; #endif /* USE_POSTMASTER_DEATH_SIGNAL */ } + +void +SendCancelRequest(int backendPID, int32 cancelAuthCode) +{ + /* + * See if we have a matching backend. In the EXEC_BACKEND case, we can no + * longer access the postmaster's own backend list, and must rely on the + * duplicate array in shared memory. XXX + */ + for (int i = MaxLivePostmasterChildren() - 1; i >= 0; i--) + { + ChildSlotData *slot = &PMSignalState->child_slots[i]; + uint32 state = pg_atomic_read_u32(&slot->state); + + if (state != PM_CHILD_ACTIVE) + continue; + + pg_read_barrier(); + if (slot->pid == backendPID) + { + if (slot->cancel_key == cancelAuthCode) + { + /* Found a match; signal that backend to cancel current op */ + ereport(DEBUG2, + (errmsg_internal("processing cancel request: sending SIGINT to process %d", + backendPID))); + + /* + * FIXME: we used to use signal_child. I believe kill() is + * maybe even more correct, but verify that. + */ + kill(backendPID, SIGINT); + } + else + /* Right PID, wrong key: no way, Jose */ + ereport(LOG, + (errmsg("wrong key in cancel request for process %d", + backendPID))); + return; + } + } + + /* No matching backend */ + ereport(LOG, + (errmsg("PID %d in cancel request did not match any process", + backendPID))); +} diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 6e334971dc9..5984fe7d44c 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -310,6 +310,20 @@ InitProcess(void) if (MyProc != NULL) elog(ERROR, "you already exist"); + /* + * Generate a random cancel key. + * + * We probably don't need cancel keys for non-backend processes, but we'd + * better have something random in the field to prevent unfriendly people + * from sending cancels to them. + */ + if (!pg_strong_random(&MyCancelKey, sizeof(int32))) + { + ereport(ERROR, + (errcode(ERRCODE_INTERNAL_ERROR), + errmsg("could not generate random cancel key"))); + } + /* Decide which list should supply our PGPROC. */ if (IsAnyAutoVacuumProcess()) procgloballist = &ProcGlobal->autovacFreeProcs; @@ -373,7 +387,7 @@ InitProcess(void) */ if (IsUnderPostmaster && !IsAutoVacuumLauncherProcess() && !IsLogicalSlotSyncWorker()) - MarkPostmasterChildActive(); + MarkPostmasterChildActive(MyProcPid, MyCancelKey); /* * Initialize all fields of MyProc, except for those previously diff --git a/src/include/postmaster/postmaster.h b/src/include/postmaster/postmaster.h index 03f78b5b25f..7cfd07a2bda 100644 --- a/src/include/postmaster/postmaster.h +++ b/src/include/postmaster/postmaster.h @@ -61,9 +61,6 @@ extern bool PostmasterMarkPIDForWorkerNotify(int); #ifdef EXEC_BACKEND extern pid_t postmaster_forkexec(int argc, char *argv[]); extern void SubPostmasterMain(int argc, char *argv[]) pg_attribute_noreturn(); - -extern Size ShmemBackendArraySize(void); -extern void ShmemBackendArrayAllocation(void); #endif /* diff --git a/src/include/storage/pmsignal.h b/src/include/storage/pmsignal.h index 029b7201093..8dff47e86e4 100644 --- a/src/include/storage/pmsignal.h +++ b/src/include/storage/pmsignal.h @@ -69,11 +69,12 @@ extern QuitSignalReason GetQuitSignalReason(void); extern int AssignPostmasterChildSlot(void); extern bool ReleasePostmasterChildSlot(int slot); extern bool IsPostmasterChildWalSender(int slot); -extern void MarkPostmasterChildActive(void); +extern void MarkPostmasterChildActive(int pid, int32 cancelAuthCode); extern void MarkPostmasterChildInactive(void); extern void MarkPostmasterChildWalSender(void); extern bool PostmasterIsAliveInternal(void); extern void PostmasterDeathSignalInit(void); +extern void SendCancelRequest(int backendPID, int32 cancelAuthCode); /* diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index fc8b15d0cf2..ac0085a226f 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -375,6 +375,7 @@ CatalogId CatalogIdMapEntry CatalogIndexState ChangeVarNodes_context +ChildSlotData ReplaceVarnoContext CheckPoint CheckPointStmt -- 2.39.2
0002-Make-cancel-request-keys-longer-as-an-optional-proto.patch (text/x-patch, 22.7K) download From 32513dd0c5b48e4d6ac56f8a53085480c30a94bf Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas <heikki.linnakangas@iki.fi> Date: Thu, 29 Feb 2024 23:22:08 +0200 Subject: [PATCH 2/2] Make cancel request keys longer, as an optional protocol feature Currently, cancel request key is 32-bit token, which isn't very much entropy. If you want to cancel another session's query, you can brute-force it. In most environments, an unauthorized cancellation of a query isn't very serious, but it nevertheless would be nice to have more protection from it. To make it harder to guess the key, make it larger. But because the length is coded in the FE-BE protocol, make it an optional protocol feature. If the client requests the "_pq_.extended_query_cancel" protocol feature, the server will generate a longer 256-bit cancellation key. However, the new longer key length is not hardcoded in the protocol anymore, the client is expected to deal with variable length keys, up to some reasonable upper limit (TODO: document the maximum). This flexibility allows e.g. a connection pooler to add more information to the cancel key, which might be useful for finding the connection. If the client doesn't request the optional protocol feature, the server generates a 32-bit key like before. --- src/backend/access/transam/parallel.c | 6 +--- src/backend/postmaster/postmaster.c | 52 +++++++++++++++------------ src/backend/storage/ipc/pmsignal.c | 29 +++++++++++---- src/backend/storage/lmgr/proc.c | 9 +++-- src/backend/tcop/postgres.c | 2 +- src/backend/utils/init/globals.c | 1 - src/include/libpq/libpq-be.h | 5 +++ src/include/libpq/pqcomm.h | 5 +-- src/include/miscadmin.h | 3 +- src/include/storage/pmsignal.h | 6 ++-- src/interfaces/libpq/fe-cancel.c | 34 +++++++++--------- src/interfaces/libpq/fe-connect.c | 26 ++++++++++---- src/interfaces/libpq/fe-protocol3.c | 32 ++++++++++++++--- src/interfaces/libpq/libpq-int.h | 10 ++++-- 14 files changed, 148 insertions(+), 72 deletions(-) diff --git a/src/backend/access/transam/parallel.c b/src/backend/access/transam/parallel.c index 849a03e4b65..652b96225a4 100644 --- a/src/backend/access/transam/parallel.c +++ b/src/backend/access/transam/parallel.c @@ -1135,7 +1135,6 @@ HandleParallelMessage(ParallelContext *pcxt, int i, StringInfo msg) { int32 pid = pq_getmsgint(msg, 4); - (void) pq_getmsgint(msg, 4); /* discard cancel key */ (void) pq_getmsgend(msg); pcxt->worker[i].pid = pid; break; @@ -1372,13 +1371,10 @@ ParallelWorkerMain(Datum main_arg) /* * Send a BackendKeyData message to the process that initiated parallelism * so that it has access to our PID before it receives any other messages - * from us. Our cancel key is sent, too, since that's the way the - * protocol message is defined, but it won't actually be used for anything - * in this case. + * from us. */ pq_beginmessage(&msgbuf, PqMsg_BackendKeyData); pq_sendint32(&msgbuf, (int32) MyProcPid); - pq_sendint32(&msgbuf, (int32) MyCancelKey); pq_endmessage(&msgbuf); /* diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c index 408f8fb9b6d..47c29e8c10e 100644 --- a/src/backend/postmaster/postmaster.c +++ b/src/backend/postmaster/postmaster.c @@ -422,7 +422,7 @@ static int ServerLoop(void); static int BackendStartup(Port *port); static int ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done); static void SendNegotiateProtocolVersion(List *unrecognized_protocol_options); -static void processCancelRequest(Port *port, void *pkt); +static void processCancelRequest(Port *port, void *pkt, int pktlen); static void report_fork_failure_to_client(Port *port, int errnum); static CAC_state canAcceptConnections(int backend_type); static void signal_child(pid_t pid, int signal); @@ -501,7 +501,7 @@ typedef struct BackgroundWorker bgworker; char DataDir[MAXPGPATH]; - int32 MyCancelKey; + char MyCancelKey[CANCEL_KEY_LENGTH]; int MyPMChildSlot; #ifndef WIN32 unsigned long UsedShmemSegID; @@ -2008,16 +2008,9 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done) */ port->proto = proto = pg_ntoh32(*((ProtocolVersion *) buf)); - if (proto == CANCEL_REQUEST_CODE) + if (proto == EXTENDED_CANCEL_REQUEST_CODE || proto == CANCEL_REQUEST_CODE) { - if (len != sizeof(CancelRequestPacket)) - { - ereport(COMMERROR, - (errcode(ERRCODE_PROTOCOL_VIOLATION), - errmsg("invalid length of startup packet"))); - return STATUS_ERROR; - } - processCancelRequest(port, buf); + processCancelRequest(port, buf, len); /* Not really an error, but we don't want to proceed further */ return STATUS_ERROR; } @@ -2202,11 +2195,16 @@ retry1: { /* * Any option beginning with _pq_. is reserved for use as a - * protocol-level option, but at present no such options are - * defined. + * protocol-level option. At present, there is only this one. */ - unrecognized_protocol_options = - lappend(unrecognized_protocol_options, pstrdup(nameptr)); + if (strcmp(nameptr + 5, "extended_query_cancel") == 0) + { + /* the value is ignored */ + port->extended_query_cancel = true; + } + else + unrecognized_protocol_options = + lappend(unrecognized_protocol_options, pstrdup(nameptr)); } else { @@ -2319,16 +2317,27 @@ SendNegotiateProtocolVersion(List *unrecognized_protocol_options) * Nothing is sent back to the client. */ static void -processCancelRequest(Port *port, void *pkt) +processCancelRequest(Port *port, void *pkt, int pktlen) { CancelRequestPacket *canc = (CancelRequestPacket *) pkt; - int backendPID; - int32 cancelAuthCode; + int len; - backendPID = (int) pg_ntoh32(canc->backendPID); - cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode); + if (pktlen < offsetof(CancelRequestPacket, cancelAuthCode)) + { + ereport(COMMERROR, + (errcode(ERRCODE_PROTOCOL_VIOLATION), + errmsg("invalid length of extended quer cancel packet"))); + return; + } + canc = (CancelRequestPacket *) pkt; + len = pktlen - offsetof(CancelRequestPacket, cancelAuthCode); + + if (len != 4 && canc->cancelRequestCode == CANCEL_REQUEST_CODE) + ereport(COMMERROR, + (errcode(ERRCODE_PROTOCOL_VIOLATION), + errmsg("invalid length of cancel request packet"))); - SendCancelRequest(backendPID, cancelAuthCode); + SendCancelRequest(pg_ntoh32(canc->backendPID), canc->cancelAuthCode, len); } /* @@ -5981,7 +5990,6 @@ save_backend_variables(BackendParameters *param, Port *port, BackgroundWorker *w strlcpy(param->DataDir, DataDir, MAXPGPATH); - param->MyCancelKey = MyCancelKey; param->MyPMChildSlot = MyPMChildSlot; #ifdef WIN32 diff --git a/src/backend/storage/ipc/pmsignal.c b/src/backend/storage/ipc/pmsignal.c index 9516b869cb2..79751b513a0 100644 --- a/src/backend/storage/ipc/pmsignal.c +++ b/src/backend/storage/ipc/pmsignal.c @@ -72,7 +72,8 @@ typedef struct ChildSlotData pg_atomic_uint32 state; int pid; - int32 cancel_key; + int cancel_key_len; + char cancel_key[MAX_CANCEL_KEY_LENGTH]; } ChildSlotData; /* "typedef struct PMSignalData PMSignalData" appears in pmsignal.h */ @@ -328,16 +329,18 @@ IsPostmasterChildWalSender(int slot) * actively using shared memory. This is called in the child process. */ void -MarkPostmasterChildActive(int pid, int32 cancelAuthCode) +MarkPostmasterChildActive(int pid, char *cancelKey, int len) { int slot = MyPMChildSlot; + Assert(len <= MAX_CANCEL_KEY_LENGTH); Assert(slot > 0 && slot <= PMSignalState->num_child_slots); slot--; Assert(pg_atomic_read_u32(&PMSignalState->child_slots[slot].state) == PM_CHILD_ASSIGNED); PMSignalState->child_slots[slot].pid = pid; - PMSignalState->child_slots[slot].cancel_key = cancelAuthCode; - pg_memory_barrier(); + memcpy(PMSignalState->child_slots[slot].cancel_key, cancelKey, len); + PMSignalState->child_slots[slot].cancel_key_len = len; + pg_write_barrier(); pg_atomic_write_u32(&PMSignalState->child_slots[slot].state, PM_CHILD_ACTIVE); } @@ -478,8 +481,18 @@ PostmasterDeathSignalInit(void) #endif /* USE_POSTMASTER_DEATH_SIGNAL */ } +static int +pg_const_time_memcmp(const void *a, const void *b, size_t len) +{ + /* + * FIXME: need a constant time implementation. Implement one somewhere in + * src/port. + */ + return memcmp(a, b, len); +} + void -SendCancelRequest(int backendPID, int32 cancelAuthCode) +SendCancelRequest(int backendPID, char *cancelKey, int len) { /* * See if we have a matching backend. In the EXEC_BACKEND case, we can no @@ -497,7 +510,11 @@ SendCancelRequest(int backendPID, int32 cancelAuthCode) pg_read_barrier(); if (slot->pid == backendPID) { - if (slot->cancel_key == cancelAuthCode) + /* + * Use pg_const_time_memcmp() to prevent an attacker from using + * timing to reveal the cancel key. + */ + if (len == slot->cancel_key_len && pg_const_time_memcmp(slot->cancel_key, cancelKey, len) == 0) { /* Found a match; signal that backend to cancel current op */ ereport(DEBUG2, diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index 5984fe7d44c..7e4cce4c91f 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -36,6 +36,7 @@ #include "access/transam.h" #include "access/twophase.h" #include "access/xlogutils.h" +#include "libpq/libpq-be.h" #include "miscadmin.h" #include "pgstat.h" #include "postmaster/autovacuum.h" @@ -68,6 +69,9 @@ bool log_lock_waits = false; PGPROC *MyProc = NULL; int MyProcNumber = INVALID_PGPROCNO; +char MyCancelKey[MAX_CANCEL_KEY_LENGTH]; +int MyCancelKeyLength; + /* * This spinlock protects the freelist of recycled PGPROC structures. * We cannot use an LWLock because the LWLock manager depends on already @@ -317,7 +321,8 @@ InitProcess(void) * better have something random in the field to prevent unfriendly people * from sending cancels to them. */ - if (!pg_strong_random(&MyCancelKey, sizeof(int32))) + MyCancelKeyLength = (MyProcPort != NULL && MyProcPort->extended_query_cancel) ? MAX_CANCEL_KEY_LENGTH : 4; + if (!pg_strong_random(&MyCancelKey, MyCancelKeyLength)) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), @@ -387,7 +392,7 @@ InitProcess(void) */ if (IsUnderPostmaster && !IsAutoVacuumLauncherProcess() && !IsLogicalSlotSyncWorker()) - MarkPostmasterChildActive(MyProcPid, MyCancelKey); + MarkPostmasterChildActive(MyProcPid, MyCancelKey, MyCancelKeyLength); /* * Initialize all fields of MyProc, except for those previously diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c index 59ab812d2e8..7164aa31978 100644 --- a/src/backend/tcop/postgres.c +++ b/src/backend/tcop/postgres.c @@ -4274,7 +4274,7 @@ PostgresMain(const char *dbname, const char *username) pq_beginmessage(&buf, PqMsg_BackendKeyData); pq_sendint32(&buf, (int32) MyProcPid); - pq_sendint32(&buf, (int32) MyCancelKey); + pq_sendbytes(&buf, MyCancelKey, MyCancelKeyLength); pq_endmessage(&buf); /* Need not flush since ReadyForQuery will do it. */ } diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c index 5eaee88d969..7efcdae9657 100644 --- a/src/backend/utils/init/globals.c +++ b/src/backend/utils/init/globals.c @@ -46,7 +46,6 @@ int MyProcPid; pg_time_t MyStartTime; TimestampTz MyStartTimestamp; struct Port *MyProcPort; -int32 MyCancelKey; int MyPMChildSlot; /* diff --git a/src/include/libpq/libpq-be.h b/src/include/libpq/libpq-be.h index 47d66d55241..3aebf92a754 100644 --- a/src/include/libpq/libpq-be.h +++ b/src/include/libpq/libpq-be.h @@ -175,6 +175,11 @@ typedef struct Port */ char *application_name; + /* + * Protocol options supported by the client + */ + bool extended_query_cancel; + /* * Information that needs to be held during the authentication cycle. */ diff --git a/src/include/libpq/pqcomm.h b/src/include/libpq/pqcomm.h index 9ae469c86c4..9b5579a5386 100644 --- a/src/include/libpq/pqcomm.h +++ b/src/include/libpq/pqcomm.h @@ -129,6 +129,7 @@ typedef uint32 AuthRequest; * The cancel request code must not match any protocol version number * we're ever likely to use. This random choice should do. */ +#define EXTENDED_CANCEL_REQUEST_CODE PG_PROTOCOL(1234,5677) #define CANCEL_REQUEST_CODE PG_PROTOCOL(1234,5678) typedef struct CancelRequestPacket @@ -136,10 +137,10 @@ typedef struct CancelRequestPacket /* Note that each field is stored in network byte order! */ MsgType cancelRequestCode; /* code to identify a cancel request */ uint32 backendPID; /* PID of client's backend */ - uint32 cancelAuthCode; /* secret key to authorize cancel */ + char cancelAuthCode[FLEXIBLE_ARRAY_MEMBER]; /* secret key to + * authorize cancel */ } CancelRequestPacket; - /* * A client can also start by sending a SSL or GSSAPI negotiation request to * get a secure channel. diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h index 756d144c323..b70b412ea90 100644 --- a/src/include/miscadmin.h +++ b/src/include/miscadmin.h @@ -192,7 +192,8 @@ extern PGDLLIMPORT pg_time_t MyStartTime; extern PGDLLIMPORT TimestampTz MyStartTimestamp; extern PGDLLIMPORT struct Port *MyProcPort; extern PGDLLIMPORT struct Latch *MyLatch; -extern PGDLLIMPORT int32 MyCancelKey; +extern PGDLLIMPORT char MyCancelKey[]; +extern PGDLLIMPORT int MyCancelKeyLength; extern PGDLLIMPORT int MyPMChildSlot; extern PGDLLIMPORT char OutputFileName[]; diff --git a/src/include/storage/pmsignal.h b/src/include/storage/pmsignal.h index 8dff47e86e4..94420ecb0b5 100644 --- a/src/include/storage/pmsignal.h +++ b/src/include/storage/pmsignal.h @@ -57,6 +57,8 @@ typedef enum /* PMSignalData is an opaque struct, details known only within pmsignal.c */ typedef struct PMSignalData PMSignalData; +#define MAX_CANCEL_KEY_LENGTH 32 + /* * prototypes for functions in pmsignal.c */ @@ -69,12 +71,12 @@ extern QuitSignalReason GetQuitSignalReason(void); extern int AssignPostmasterChildSlot(void); extern bool ReleasePostmasterChildSlot(int slot); extern bool IsPostmasterChildWalSender(int slot); -extern void MarkPostmasterChildActive(int pid, int32 cancelAuthCode); +extern void MarkPostmasterChildActive(int pid, char *cancelKey, int len); extern void MarkPostmasterChildInactive(void); extern void MarkPostmasterChildWalSender(void); extern bool PostmasterIsAliveInternal(void); extern void PostmasterDeathSignalInit(void); -extern void SendCancelRequest(int backendPID, int32 cancelAuthCode); +extern void SendCancelRequest(int backendPID, char *cancelKey, int len); /* diff --git a/src/interfaces/libpq/fe-cancel.c b/src/interfaces/libpq/fe-cancel.c index 51f8d8a78c4..6c9bfeaa33f 100644 --- a/src/interfaces/libpq/fe-cancel.c +++ b/src/interfaces/libpq/fe-cancel.c @@ -34,6 +34,8 @@ PGcancel * PQgetCancel(PGconn *conn) { PGcancel *cancel; + int cancel_req_len; + CancelRequestPacket *req; if (!conn) return NULL; @@ -41,13 +43,13 @@ PQgetCancel(PGconn *conn) if (conn->sock == PGINVALID_SOCKET) return NULL; - cancel = malloc(sizeof(PGcancel)); + cancel_req_len = offsetof(CancelRequestPacket, cancelAuthCode) + conn->be_cancel_key_len; + cancel = malloc(offsetof(PGcancel, cancel_req) + cancel_req_len); if (cancel == NULL) return NULL; memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr)); - cancel->be_pid = conn->be_pid; - cancel->be_key = conn->be_key; + /* We use -1 to indicate an unset connection option */ cancel->pgtcp_user_timeout = -1; cancel->keepalives = -1; @@ -90,6 +92,13 @@ PQgetCancel(PGconn *conn) goto fail; } + req = (CancelRequestPacket *) &cancel->cancel_req; + req->cancelRequestCode = (MsgType) pg_hton32(conn->be_cancel_key_len == 4 ? CANCEL_REQUEST_CODE : EXTENDED_CANCEL_REQUEST_CODE); + req->backendPID = pg_hton32(conn->be_pid); + memcpy(req->cancelAuthCode, conn->be_cancel_key, conn->be_cancel_key_len); + /* include the length field itself in the length */ + cancel->cancel_pkt_len = pg_hton32(cancel_req_len + 4); + return cancel; fail: @@ -150,11 +159,8 @@ PQcancel(PGcancel *cancel, char *errbuf, int errbufsize) int save_errno = SOCK_ERRNO; pgsocket tmpsock = PGINVALID_SOCKET; int maxlen; - struct - { - uint32 packetlen; - CancelRequestPacket cp; - } crp; + char recvbuf; + int cancel_pkt_len; if (!cancel) { @@ -256,15 +262,11 @@ retry3: goto cancel_errReturn; } - /* Create and send the cancel request packet. */ - - crp.packetlen = pg_hton32((uint32) sizeof(crp)); - crp.cp.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE); - crp.cp.backendPID = pg_hton32(cancel->be_pid); - crp.cp.cancelAuthCode = pg_hton32(cancel->be_key); + /* Send the cancel request packet. */ + cancel_pkt_len = pg_ntoh32(cancel->cancel_pkt_len); retry4: - if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp)) + if (send(tmpsock, &cancel->cancel_pkt_len, cancel_pkt_len, 0) != cancel_pkt_len) { if (SOCK_ERRNO == EINTR) /* Interrupted system call - we'll just try again */ @@ -281,7 +283,7 @@ retry4: * read to obtain any data, we are just waiting for EOF to be signaled. */ retry5: - if (recv(tmpsock, (char *) &crp, 1, 0) < 0) + if (recv(tmpsock, &recvbuf, 1, 0) < 0) { if (SOCK_ERRNO == EINTR) /* Interrupted system call - we'll just try again */ diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index d4e10a0c4f3..5148b24ba34 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -617,7 +617,12 @@ pqDropServerData(PGconn *conn) free(conn->write_err_msg); conn->write_err_msg = NULL; conn->be_pid = 0; - conn->be_key = 0; + if (conn->be_cancel_key != NULL) + { + free(conn->be_cancel_key); + conn->be_cancel_key = NULL; + } + conn->be_cancel_key_len = 0; } @@ -3724,14 +3729,21 @@ keep_going: /* We will come back to here until there is } else if (beresp == PqMsg_NegotiateProtocolVersion) { - if (pqGetNegotiateProtocolVersion3(conn)) + switch (pqGetNegotiateProtocolVersion3(conn)) { - libpq_append_conn_error(conn, "received invalid protocol negotiation message"); - goto error_return; + case 0: + /* OK, we read the message; mark data consumed */ + conn->inStart = conn->inCursor; + /* Stay in the CONNECTION_AWAITING_RESPONSE state */ + goto keep_going; + case 1: + /* OK, we read the message; mark data consumed */ + conn->inStart = conn->inCursor; + goto error_return; + case EOF: + /* We'll come back when there is more data */ + return PGRES_POLLING_READING; } - /* OK, we read the message; mark data consumed */ - conn->inStart = conn->inCursor; - goto error_return; } /* It is an authentication request. */ diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c index 701d58e1087..c079297f736 100644 --- a/src/interfaces/libpq/fe-protocol3.c +++ b/src/interfaces/libpq/fe-protocol3.c @@ -310,8 +310,22 @@ pqParseInput3(PGconn *conn) */ if (pqGetInt(&(conn->be_pid), 4, conn)) return; - if (pqGetInt(&(conn->be_key), 4, conn)) - return; + + { + int cancel_key_len = 5 + msgLength - (conn->inCursor - conn->inStart); + + conn->be_cancel_key = malloc(cancel_key_len); + if (conn->be_cancel_key == NULL) + { + libpq_append_conn_error(conn, "out of memory"); + /* discard the message */ + conn->inCursor = conn->inStart + 5 + msgLength; + break; + } + if (pqGetnchar(conn->be_cancel_key, cancel_key_len, conn)) + return; + conn->be_cancel_key_len = cancel_key_len; + } break; case PqMsg_RowDescription: if (conn->error_result || @@ -1404,7 +1418,8 @@ reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding) /* * Attempt to read a NegotiateProtocolVersion message. * Entry: 'v' message type and length have already been consumed. - * Exit: returns 0 if successfully consumed message. + * Exit: returns 0 if successfully consumed message and the negotiation succeeded. + * returns 1 if successfully consumed message and the negotiation failed. * returns EOF if not enough data. */ int @@ -1413,6 +1428,7 @@ pqGetNegotiateProtocolVersion3(PGconn *conn) int tmp; ProtocolVersion their_version; int num; + int num_required_missing = 0; PQExpBufferData buf; if (pqGetInt(&tmp, 4, conn) != 0) @@ -1430,16 +1446,23 @@ pqGetNegotiateProtocolVersion3(PGconn *conn) termPQExpBuffer(&buf); return EOF; } + if (strcmp(conn->workBuffer.data, "_pq_.extended_query_cancel") == 0) + { + /* that's ok */ + continue; + } + if (buf.len > 0) appendPQExpBufferChar(&buf, ' '); appendPQExpBufferStr(&buf, conn->workBuffer.data); + num_required_missing++; } if (their_version < conn->pversion) libpq_append_conn_error(conn, "protocol version not supported by server: client uses %u.%u, server supports up to %u.%u", PG_PROTOCOL_MAJOR(conn->pversion), PG_PROTOCOL_MINOR(conn->pversion), PG_PROTOCOL_MAJOR(their_version), PG_PROTOCOL_MINOR(their_version)); - if (num > 0) + if (num_required_missing > 0) { appendPQExpBuffer(&conn->errorMessage, libpq_ngettext("protocol extension not supported by server: %s", @@ -2312,6 +2335,7 @@ build_startup_packet(const PGconn *conn, char *packet, ADD_STARTUP_OPTION(next_eo->pgName, val); } } + ADD_STARTUP_OPTION("_pq_.extended_query_cancel", ""); /* Add trailing terminator */ if (packet) diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 82c18f870d2..6187f282fb0 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -491,8 +491,9 @@ struct pg_conn bool send_appname; /* okay to send application_name? */ /* Miscellaneous stuff */ - int be_pid; /* PID of backend --- needed for cancels */ - int be_key; /* key of backend --- needed for cancels */ + int be_pid; /* PID of backend --- needed for XX cancels */ + char *be_cancel_key; + int be_cancel_key_len; pgParameterStatus *pstatus; /* ParameterStatus data */ int client_encoding; /* encoding id */ bool std_strings; /* standard_conforming_strings */ @@ -629,7 +630,6 @@ struct pg_cancel { SockAddr raddr; /* Remote address */ int be_pid; /* PID of backend --- needed for cancels */ - int be_key; /* key of backend --- needed for cancels */ int pgtcp_user_timeout; /* tcp user timeout */ int keepalives; /* use TCP keepalives? */ int keepalives_idle; /* time between TCP keepalives */ @@ -637,6 +637,10 @@ struct pg_cancel * retransmits */ int keepalives_count; /* maximum number of TCP keepalive * retransmits */ + + /* Pre-constructed cancel request packet starts here */ + int32 cancel_pkt_len; /* in network-byte-order */ + char cancel_req[FLEXIBLE_ARRAY_MEMBER]; /* CancelRequestPacket */ }; -- 2.39.2
^ permalink raw reply [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-03-01 05:19  Jelte Fennema-Nio <postgres@jeltef.nl>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  1 sibling, 1 reply; 40+ messages in thread

From: Jelte Fennema-Nio @ 2024-03-01 05:19 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: pgsql-hackers

This is a preliminary review. I'll look at this more closely soon.

On Thu, 29 Feb 2024 at 22:26, Heikki Linnakangas <hlinnaka@iki.fi> wrote:
> If the client requests the "_pq_.extended_query_cancel" protocol
> feature, the server will generate a longer 256-bit cancellation key.

Huge +1 for this general idea. This is a problem I ran into with
PgBouncer, and had to make some concessions when fitting the
information I wanted into the available bits. Also from a security
perspective I don't think the current amount of bits have stood the
test of time.

+ ADD_STARTUP_OPTION("_pq_.extended_query_cancel", "");

Since this parameter doesn't actually take a value (just empty
string). I think this behaviour makes more sense as a minor protocol
version bump instead of a parameter.

+ if (strcmp(conn->workBuffer.data, "_pq_.extended_query_cancel") == 0)
+ {
+ /* that's ok */
+ continue;
+ }

Please see this thread[1], which in the first few patches makes
pqGetNegotiateProtocolVersion3 actually usable for extending the
protocol. I started that, because very proposed protocol change that's
proposed on the list has similar changes to
pqGetNegotiateProtocolVersion3 and I think we shouldn't make these
changes ad-hoc hacked into the current code, but actually do them once
in a way that makes sense for all protocol changes.

> Documentation is still missing

I think at least protocol message type documentation would be very
helpful in reviewing, because that is really a core part of this
change. Based on the current code I think it should have a few
changes:

+ int cancel_key_len = 5 + msgLength - (conn->inCursor - conn->inStart);
+
+ conn->be_cancel_key = malloc(cancel_key_len);
+ if (conn->be_cancel_key == NULL)

This is using the message length to determine the length of the cancel
key in BackendKey. That is not something we generally do in the
protocol. It's even documented: "Notice that although each message
includes a byte count at the beginning, the message format is defined
so that the message end can be found without reference to the byte
count." So I think the patch should be changed to include the length
of the cancel key explicitly in the message.

[1]: https://www.postgresql.org/message-id/flat/CAGECzQSr2%3DJPJHNN06E_jTF2%2B0E60K%3DhotyBw5wY%3Dq9Wvmt7...





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-03-01 14:19  Peter Eisentraut <peter@eisentraut.org>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  1 sibling, 2 replies; 40+ messages in thread

From: Peter Eisentraut @ 2024-03-01 14:19 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; pgsql-hackers

On 29.02.24 22:25, Heikki Linnakangas wrote:
> Currently, cancel request key is a 32-bit token, which isn't very much 
> entropy. If you want to cancel another session's query, you can 
> brute-force it. In most environments, an unauthorized cancellation of a 
> query isn't very serious, but it nevertheless would be nice to have more 
> protection from it. The attached patch makes it longer. It is an 
> optional protocol feature, so it's fully backwards-compatible with 
> clients that don't support longer keys.

My intuition would be to make this a protocol version bump, not an 
optional feature.  I think this is something that everyone should 
eventually be using, not a niche feature that you explicitly want to 
opt-in for.

> One complication with this was that because we no longer know how long 
> the key should be, 4-bytes or something longer, until the backend has 
> performed the protocol negotiation, we cannot generate the key in the 
> postmaster before forking the process anymore.

Maybe this would be easier if it's a protocol version number change, 
since that is sent earlier than protocol extensions?






^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-03-03 06:59  Jelte Fennema-Nio <postgres@jeltef.nl>
  parent: Peter Eisentraut <peter@eisentraut.org>
  1 sibling, 0 replies; 40+ messages in thread

From: Jelte Fennema-Nio @ 2024-03-03 06:59 UTC (permalink / raw)
  To: Peter Eisentraut <peter@eisentraut.org>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; pgsql-hackers

On Fri, 1 Mar 2024 at 15:19, Peter Eisentraut <peter@eisentraut.org> wrote:
> > One complication with this was that because we no longer know how long
> > the key should be, 4-bytes or something longer, until the backend has
> > performed the protocol negotiation, we cannot generate the key in the
> > postmaster before forking the process anymore.
>
> Maybe this would be easier if it's a protocol version number change,
> since that is sent earlier than protocol extensions?

Protocol version and protocol extensions are both sent in the
StartupMessage, so the same complication applies. (But I do agree that
a protocol version bump is more appropriate for this type of change)





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-03-03 14:27  Jelte Fennema-Nio <postgres@jeltef.nl>
  parent: Jelte Fennema-Nio <postgres@jeltef.nl>
  0 siblings, 1 reply; 40+ messages in thread

From: Jelte Fennema-Nio @ 2024-03-03 14:27 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: pgsql-hackers

On Fri, 1 Mar 2024 at 06:19, Jelte Fennema-Nio <postgres@jeltef.nl> wrote:
> This is a preliminary review. I'll look at this more closely soon.

Some more thoughts after looking some more at the proposed changes

+#define EXTENDED_CANCEL_REQUEST_CODE PG_PROTOCOL(1234,5677)

nit: I think the code should be 1234,5679 because it's the newer
message type, so to me it makes more sense if the code is a larger
number.

+ * FIXME: we used to use signal_child. I believe kill() is
+ * maybe even more correct, but verify that.

signal_child seems to be the correct one, not kill. signal_child has
this relevant comment explaining why it's better than plain kill:

 * On systems that have setsid(), each child process sets itself up as a
 * process group leader.  For signals that are generally interpreted in the
 * appropriate fashion, we signal the entire process group not just the
 * direct child process.  This allows us to, for example, SIGQUIT a blocked
 * archive_recovery script, or SIGINT a script being run by a backend via
 * system().

+SendCancelRequest(int backendPID, int32 cancelAuthCode)

I think this name of the function is quite confusing, it's not sending
a cancel request, it is processing one. It sends a SIGINT.

> While we're at it, switch to using atomics in pmsignal.c for the state
> field. That feels easier to reason about than volatile
> pointers.

I feel like this refactor would benefit from being a separate commit.
That would make it easier to follow which change to pmsignal.c is
necessary for what.

+ MyCancelKeyLength = (MyProcPort != NULL &&
MyProcPort->extended_query_cancel) ? MAX_CANCEL_KEY_LENGTH : 4;

I think we should be doing this check the opposite way, i.e. only fall
back to the smaller key when explicitly requested:

+ MyCancelKeyLength = (MyProcPort != NULL &&
MyProcPort->old_query_cancel) ? 4 : MAX_CANCEL_KEY_LENGTH;

That way we'd get the more secure, longer key length for non-backend
processes such as background workers.

+ case EOF:
+ /* We'll come back when there is more data */
+ return PGRES_POLLING_READING;

Nice catch, I'll go steal this for my patchset which adds all the
necessary changes to be able to do a protocol bump[1].

+ int be_pid; /* PID of backend --- needed for XX cancels */

Seems like you accidentally added XX to the comment in this line.

[1]: https://www.postgresql.org/message-id/flat/CAGECzQSr2%3DJPJHNN06E_jTF2%2B0E60K%3DhotyBw5wY%3Dq9Wvmt7...





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-03-03 17:27  Jelte Fennema-Nio <postgres@jeltef.nl>
  parent: Jelte Fennema-Nio <postgres@jeltef.nl>
  0 siblings, 1 reply; 40+ messages in thread

From: Jelte Fennema-Nio @ 2024-03-03 17:27 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: pgsql-hackers

On Sun, 3 Mar 2024 at 15:27, Jelte Fennema-Nio <postgres@jeltef.nl> wrote:
> + case EOF:
> + /* We'll come back when there is more data */
> + return PGRES_POLLING_READING;
>
> Nice catch, I'll go steal this for my patchset which adds all the
> necessary changes to be able to do a protocol bump[1].

Actually, it turns out your change to return PGRES_POLLING_READING on
EOF is incorrect (afaict). A little bit above there is this code
comment above a check to see if the whole body was received:

 * Can't process if message body isn't all here yet.
 *
 * After this check passes, any further EOF during parsing
 * implies that the server sent a bad/truncated message.
 * Reading more bytes won't help in that case, so don't return
 * PGRES_POLLING_READING after this point.

So I'll leave my patchset as is.





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-03-06 01:12  Bruce Momjian <bruce@momjian.us>
  parent: Peter Eisentraut <peter@eisentraut.org>
  1 sibling, 0 replies; 40+ messages in thread

From: Bruce Momjian @ 2024-03-06 01:12 UTC (permalink / raw)
  To: Peter Eisentraut <peter@eisentraut.org>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; pgsql-hackers

On Fri, Mar  1, 2024 at 03:19:23PM +0100, Peter Eisentraut wrote:
> On 29.02.24 22:25, Heikki Linnakangas wrote:
> > Currently, cancel request key is a 32-bit token, which isn't very much
> > entropy. If you want to cancel another session's query, you can
> > brute-force it. In most environments, an unauthorized cancellation of a
> > query isn't very serious, but it nevertheless would be nice to have more
> > protection from it. The attached patch makes it longer. It is an
> > optional protocol feature, so it's fully backwards-compatible with
> > clients that don't support longer keys.
> 
> My intuition would be to make this a protocol version bump, not an optional
> feature.  I think this is something that everyone should eventually be
> using, not a niche feature that you explicitly want to opt-in for.

Agreed.

-- 
  Bruce Momjian  <bruce@momjian.us>        https://momjian.us
  EDB                                      https://enterprisedb.com

  Only you can decide what is important to you.





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-03-08 22:20  Heikki Linnakangas <hlinnaka@iki.fi>
  parent: Jelte Fennema-Nio <postgres@jeltef.nl>
  0 siblings, 2 replies; 40+ messages in thread

From: Heikki Linnakangas @ 2024-03-08 22:20 UTC (permalink / raw)
  To: Jelte Fennema-Nio <postgres@jeltef.nl>; +Cc: pgsql-hackers

On 01/03/2024 07:19, Jelte Fennema-Nio wrote:
> I think this behaviour makes more sense as a minor protocol version
> bump instead of a parameter.
Ok, the consensus is to bump the minor protocol version for this. Works 
for me.

> + if (strcmp(conn->workBuffer.data, "_pq_.extended_query_cancel") == 0)
> + {
> + /* that's ok */
> + continue;
> + }
> 
> Please see this thread[1], which in the first few patches makes
> pqGetNegotiateProtocolVersion3 actually usable for extending the
> protocol. I started that, because very proposed protocol change that's
> proposed on the list has similar changes to
> pqGetNegotiateProtocolVersion3 and I think we shouldn't make these
> changes ad-hoc hacked into the current code, but actually do them once
> in a way that makes sense for all protocol changes.

Thanks, I will take a look and respond on that thread.

>> Documentation is still missing
> 
> I think at least protocol message type documentation would be very
> helpful in reviewing, because that is really a core part of this
> change.

Added some documentation. There's more work to be done there, but at 
least the message type descriptions are now up-to-date.

> Based on the current code I think it should have a few changes:
> 
> + int cancel_key_len = 5 + msgLength - (conn->inCursor - conn->inStart);
> +
> + conn->be_cancel_key = malloc(cancel_key_len);
> + if (conn->be_cancel_key == NULL)
> 
> This is using the message length to determine the length of the cancel
> key in BackendKey. That is not something we generally do in the
> protocol. It's even documented: "Notice that although each message
> includes a byte count at the beginning, the message format is defined
> so that the message end can be found without reference to the byte
> count." So I think the patch should be changed to include the length
> of the cancel key explicitly in the message.

The nice thing about relying on the message length was that we could 
just redefine the CancelRequest message to have a variable length 
secret, and old CancelRequest with 4-byte secret was compatible with the 
new definition too. But it doesn't matter much, so added an explicit 
length field.

FWIW I don't think that restriction makes sense. Any code that parses 
the messages needs to have the message length available, and I don't 
think it helps with sanity checking that much. I think the documentation 
is a little anachronistic. The real reason that all the message types 
include enough information to find the message end is that in protocol 
version 2, there was no message length field. The only exception that 
doesn't have that property is CopyData, and it's no coincidence that it 
was added in protocol version 3.

On 03/03/2024 16:27, Jelte Fennema-Nio wrote:
> On Fri, 1 Mar 2024 at 06:19, Jelte Fennema-Nio <postgres@jeltef.nl> wrote:
>> This is a preliminary review. I'll look at this more closely soon.
> 
> Some more thoughts after looking some more at the proposed changes
> 
> +#define EXTENDED_CANCEL_REQUEST_CODE PG_PROTOCOL(1234,5677)
> 
> nit: I think the code should be 1234,5679 because it's the newer
> message type, so to me it makes more sense if the code is a larger
> number.

Unfortunately 1234,5679 already in use by NEGOTIATE_SSL_CODE. That's why 
I went the other direction. If we want to add this to "the end", it 
needs to be 1234,5681. But I wanted to keep the cancel requests together.

> + * FIXME: we used to use signal_child. I believe kill() is
> + * maybe even more correct, but verify that.
> 
> signal_child seems to be the correct one, not kill. signal_child has
> this relevant comment explaining why it's better than plain kill:
> 
>   * On systems that have setsid(), each child process sets itself up as a
>   * process group leader.  For signals that are generally interpreted in the
>   * appropriate fashion, we signal the entire process group not just the
>   * direct child process.  This allows us to, for example, SIGQUIT a blocked
>   * archive_recovery script, or SIGINT a script being run by a backend via
>   * system().

I changed it to signal the process group if HAVE_SETSID, like 
pg_signal_backend() does. We don't need to signal both the process group 
and the process itself like signal_child() does, because we don't have 
the race condition with recently-forked children that signal_child() 
talks about.

> +SendCancelRequest(int backendPID, int32 cancelAuthCode)
> 
> I think this name of the function is quite confusing, it's not sending
> a cancel request, it is processing one. It sends a SIGINT.

Heh, well, it's sending the cancel request signal to the right backend, 
but I see your point. Renamed to ProcessCancelRequest.

>> While we're at it, switch to using atomics in pmsignal.c for the state
>> field. That feels easier to reason about than volatile
>> pointers.
> 
> I feel like this refactor would benefit from being a separate commit.
> That would make it easier to follow which change to pmsignal.c is
> necessary for what.

Point taken. I didn't do that yet, but it makes sense.

> + MyCancelKeyLength = (MyProcPort != NULL &&
> MyProcPort->extended_query_cancel) ? MAX_CANCEL_KEY_LENGTH : 4;
> 
> I think we should be doing this check the opposite way, i.e. only fall
> back to the smaller key when explicitly requested:
> 
> + MyCancelKeyLength = (MyProcPort != NULL &&
> MyProcPort->old_query_cancel) ? 4 : MAX_CANCEL_KEY_LENGTH;
> 
> That way we'd get the more secure, longer key length for non-backend
> processes such as background workers.

+1, fixed.

On 03/03/2024 19:27, Jelte Fennema-Nio wrote:
> On Sun, 3 Mar 2024 at 15:27, Jelte Fennema-Nio <postgres@jeltef.nl> wrote:
>> + case EOF:
>> + /* We'll come back when there is more data */
>> + return PGRES_POLLING_READING;
>>
>> Nice catch, I'll go steal this for my patchset which adds all the
>> necessary changes to be able to do a protocol bump[1].
> 
> Actually, it turns out your change to return PGRES_POLLING_READING on
> EOF is incorrect (afaict). A little bit above there is this code
> comment above a check to see if the whole body was received:
> 
>   * Can't process if message body isn't all here yet.
>   *
>   * After this check passes, any further EOF during parsing
>   * implies that the server sent a bad/truncated message.
>   * Reading more bytes won't help in that case, so don't return
>   * PGRES_POLLING_READING after this point.
> 
> So I'll leave my patchset as is.

Yep, thanks.

One consequence of this patch that I didn't mention earlier is that it 
makes libpq incompatible with server version 9.2 and below, because the 
minor version negotiation was introduced in version 9.3. We could teach 
libpq to disconnect and reconnect with minor protocol version 3.0, if 
connecting with 3.1 fails, but IMHO it's better to not complicate this 
and accept the break in backwards-compatibility. 9.3 was released in 
2013. We dropped pg_dump support for versions older than 9.2 a few years 
ago, this raises the bar for pg_dump to 9.3 as well.

-- 
Heikki Linnakangas
Neon (https://neon.tech)

Attachments: download all (2 files, .tar.gz)

v2-0001-Move-cancel-key-generation-to-after-forking-the-b.patch (text/x-patch, 24.4K) download From a1ea2c805210fa22982b1f12ba7eb33549814441 Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas <heikki.linnakangas@iki.fi> Date: Thu, 7 Mar 2024 21:53:03 +0200 Subject: [PATCH v2 1/2] Move cancel key generation to after forking the backend Move responsibility of generating the cancel key to the backend process. The cancel key is now generated after forking, and the backend advertises it in the PMSignalState array. When a cancel request arrives, the backend handling it scans the PMSignalState array to find the target pid and cancel key. This is similar to how this previously worked in the EXEC_BACKEND case with the ShmemBackendArray, but instead of having the separate array, we store the cancel keys in PMSignalState array, and use it also in the !EXEC_BACKEND case. While we're at it, switch to using atomics in pmsignal.c for the state field. That feels easier to reason about than volatile pointers. (TODO: also switch to pg_atomic_flag for PMSignalFlags array. Weirdly we don't have "pg_atomic_test_clear_flag" nor "pg_atomic_set_flag". Those would be the natural opertions for PMSignalFlags. Maybe we should add those, but I didn't want to go that deep down the rabbit hole in this patch.) This is needed by the next patch, so that we can generate the cancel key later, after negotiating the protocol version with the client. Reviewed-by: Jelte Fennema-Nio Discussion: https://www.postgresql.org/message-id/508d0505-8b7a-4864-a681-e7e5edfe32aa@iki.fi --- src/backend/postmaster/postmaster.c | 188 +--------------------------- src/backend/storage/ipc/ipci.c | 11 -- src/backend/storage/ipc/pmsignal.c | 124 +++++++++++++----- src/backend/storage/lmgr/proc.c | 16 ++- src/include/postmaster/postmaster.h | 3 - src/include/storage/pmsignal.h | 3 +- src/tools/pgindent/typedefs.list | 1 + 7 files changed, 116 insertions(+), 230 deletions(-) diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c index f3c09e8dc0d..1eefe652e8e 100644 --- a/src/backend/postmaster/postmaster.c +++ b/src/backend/postmaster/postmaster.c @@ -175,7 +175,6 @@ typedef struct bkend { pid_t pid; /* process id of backend */ - int32 cancel_key; /* cancel key for cancels for this backend */ int child_slot; /* PMChildSlot for this backend, if any */ int bkend_type; /* child process flavor, see above */ bool dead_end; /* is it going to send an error and quit? */ @@ -185,10 +184,6 @@ typedef struct bkend static dlist_head BackendList = DLIST_STATIC_INIT(BackendList); -#ifdef EXEC_BACKEND -static Backend *ShmemBackendArray; -#endif - BackgroundWorker *MyBgworkerEntry = NULL; @@ -428,7 +423,6 @@ static void SendNegotiateProtocolVersion(List *unrecognized_protocol_options); static void processCancelRequest(Port *port, void *pkt); static void report_fork_failure_to_client(Port *port, int errnum); static CAC_state canAcceptConnections(int backend_type); -static bool RandomCancelKey(int32 *cancel_key); static void signal_child(pid_t pid, int signal); static void sigquit_child(pid_t pid); static bool SignalSomeChildren(int signal, int target); @@ -505,7 +499,6 @@ typedef struct BackgroundWorker bgworker; char DataDir[MAXPGPATH]; - int32 MyCancelKey; int MyPMChildSlot; #ifndef WIN32 unsigned long UsedShmemSegID; @@ -515,7 +508,6 @@ typedef struct #endif void *UsedShmemSegAddr; slock_t *ShmemLock; - Backend *ShmemBackendArray; #ifndef HAVE_SPINLOCKS PGSemaphore *SpinlockSemaArray; #endif @@ -557,9 +549,6 @@ static bool save_backend_variables(BackendParameters *param, Port *port, Backgro static bool save_backend_variables(BackendParameters *param, Port *port, BackgroundWorker *worker, HANDLE childProcess, pid_t childPid); #endif - -static void ShmemBackendArrayAdd(Backend *bn); -static void ShmemBackendArrayRemove(Backend *bn); #endif /* EXEC_BACKEND */ /* Macros to check exit status of a child process */ @@ -2332,58 +2321,11 @@ processCancelRequest(Port *port, void *pkt) CancelRequestPacket *canc = (CancelRequestPacket *) pkt; int backendPID; int32 cancelAuthCode; - Backend *bp; - -#ifndef EXEC_BACKEND - dlist_iter iter; -#else - int i; -#endif backendPID = (int) pg_ntoh32(canc->backendPID); cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode); - /* - * See if we have a matching backend. In the EXEC_BACKEND case, we can no - * longer access the postmaster's own backend list, and must rely on the - * duplicate array in shared memory. - */ -#ifndef EXEC_BACKEND - dlist_foreach(iter, &BackendList) - { - bp = dlist_container(Backend, elem, iter.cur); -#else - for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--) - { - bp = (Backend *) &ShmemBackendArray[i]; -#endif - if (bp->pid == backendPID) - { - if (bp->cancel_key == cancelAuthCode) - { - /* Found a match; signal that backend to cancel current op */ - ereport(DEBUG2, - (errmsg_internal("processing cancel request: sending SIGINT to process %d", - backendPID))); - signal_child(bp->pid, SIGINT); - } - else - /* Right PID, wrong key: no way, Jose */ - ereport(LOG, - (errmsg("wrong key in cancel request for process %d", - backendPID))); - return; - } -#ifndef EXEC_BACKEND /* make GNU Emacs 26.1 see brace balance */ - } -#else - } -#endif - - /* No matching backend */ - ereport(LOG, - (errmsg("PID %d in cancel request did not match any process", - backendPID))); + SendCancelRequest(backendPID, cancelAuthCode); } /* @@ -3294,9 +3236,6 @@ CleanupBackgroundWorker(int pid, /* Get it out of the BackendList and clear out remaining data */ dlist_delete(&rw->rw_backend->elem); -#ifdef EXEC_BACKEND - ShmemBackendArrayRemove(rw->rw_backend); -#endif /* * It's possible that this background worker started some OTHER @@ -3382,9 +3321,6 @@ CleanupBackend(int pid, HandleChildCrash(pid, exitstatus, _("server process")); return; } -#ifdef EXEC_BACKEND - ShmemBackendArrayRemove(bp); -#endif } if (bp->bgworker_notify) { @@ -3452,9 +3388,6 @@ HandleChildCrash(int pid, int exitstatus, const char *procname) */ (void) ReleasePostmasterChildSlot(rw->rw_child_slot); dlist_delete(&rw->rw_backend->elem); -#ifdef EXEC_BACKEND - ShmemBackendArrayRemove(rw->rw_backend); -#endif pfree(rw->rw_backend); rw->rw_backend = NULL; rw->rw_pid = 0; @@ -3487,9 +3420,6 @@ HandleChildCrash(int pid, int exitstatus, const char *procname) if (!bp->dead_end) { (void) ReleasePostmasterChildSlot(bp->child_slot); -#ifdef EXEC_BACKEND - ShmemBackendArrayRemove(bp); -#endif } dlist_delete(iter.cur); pfree(bp); @@ -4101,22 +4031,6 @@ BackendStartup(Port *port) return STATUS_ERROR; } - /* - * Compute the cancel key that will be assigned to this backend. The - * backend will have its own copy in the forked-off process' value of - * MyCancelKey, so that it can transmit the key to the frontend. - */ - if (!RandomCancelKey(&MyCancelKey)) - { - pfree(bn); - ereport(LOG, - (errcode(ERRCODE_INTERNAL_ERROR), - errmsg("could not generate random cancel key"))); - return STATUS_ERROR; - } - - bn->cancel_key = MyCancelKey; - /* Pass down canAcceptConnections state */ port->canAcceptConnections = canAcceptConnections(BACKEND_TYPE_NORMAL); bn->dead_end = (port->canAcceptConnections != CAC_OK); @@ -4180,11 +4094,6 @@ BackendStartup(Port *port) bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */ dlist_push_head(&BackendList, &bn->elem); -#ifdef EXEC_BACKEND - if (!bn->dead_end) - ShmemBackendArrayAdd(bn); -#endif - return STATUS_OK; } @@ -5247,16 +5156,6 @@ StartupPacketTimeoutHandler(void) _exit(1); } - -/* - * Generate a random cancel key. - */ -static bool -RandomCancelKey(int32 *cancel_key) -{ - return pg_strong_random(cancel_key, sizeof(int32)); -} - /* * Count up number of child processes of specified types (dead_end children * are always excluded). @@ -5432,25 +5331,9 @@ StartAutovacuumWorker(void) */ if (canAcceptConnections(BACKEND_TYPE_AUTOVAC) == CAC_OK) { - /* - * Compute the cancel key that will be assigned to this session. We - * probably don't need cancel keys for autovac workers, but we'd - * better have something random in the field to prevent unfriendly - * people from sending cancels to them. - */ - if (!RandomCancelKey(&MyCancelKey)) - { - ereport(LOG, - (errcode(ERRCODE_INTERNAL_ERROR), - errmsg("could not generate random cancel key"))); - return; - } - bn = (Backend *) palloc_extended(sizeof(Backend), MCXT_ALLOC_NO_OOM); if (bn) { - bn->cancel_key = MyCancelKey; - /* Autovac workers are not dead_end and need a child slot */ bn->dead_end = false; bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot(); @@ -5461,9 +5344,6 @@ StartAutovacuumWorker(void) { bn->bkend_type = BACKEND_TYPE_AUTOVAC; dlist_push_head(&BackendList, &bn->elem); -#ifdef EXEC_BACKEND - ShmemBackendArrayAdd(bn); -#endif /* all OK */ return; } @@ -5595,11 +5475,10 @@ CreateOptsFile(int argc, char *argv[], char *fullprogname) /* * MaxLivePostmasterChildren * - * This reports the number of entries needed in per-child-process arrays - * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray). - * These arrays include regular backends, autovac workers, walsenders + * This reports the number of entries needed in the per-child-process array. + * The array includes regular backends, autovac workers, walsenders * and background workers, but not special children nor dead_end children. - * This allows the arrays to have a fixed maximum size, to wit the same + * This allows the array to have a fixed maximum size, to wit the same * too-many-children limit enforced by canAcceptConnections(). The exact value * isn't too critical as long as it's more than MaxBackends. */ @@ -5799,9 +5678,6 @@ do_start_bgworker(RegisteredBgWorker *rw) ReportBackgroundWorkerPID(rw); /* add new worker to lists of backends */ dlist_push_head(&BackendList, &rw->rw_backend->elem); -#ifdef EXEC_BACKEND - ShmemBackendArrayAdd(rw->rw_backend); -#endif return true; } @@ -5872,20 +5748,6 @@ assign_backendlist_entry(RegisteredBgWorker *rw) return false; } - /* - * Compute the cancel key that will be assigned to this session. We - * probably don't need cancel keys for background workers, but we'd better - * have something random in the field to prevent unfriendly people from - * sending cancels to them. - */ - if (!RandomCancelKey(&MyCancelKey)) - { - ereport(LOG, - (errcode(ERRCODE_INTERNAL_ERROR), - errmsg("could not generate random cancel key"))); - return false; - } - bn = palloc_extended(sizeof(Backend), MCXT_ALLOC_NO_OOM); if (bn == NULL) { @@ -5895,7 +5757,6 @@ assign_backendlist_entry(RegisteredBgWorker *rw) return false; } - bn->cancel_key = MyCancelKey; bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot(); bn->bkend_type = BACKEND_TYPE_BGWORKER; bn->dead_end = false; @@ -6114,7 +5975,6 @@ save_backend_variables(BackendParameters *param, Port *port, BackgroundWorker *w strlcpy(param->DataDir, DataDir, MAXPGPATH); - param->MyCancelKey = MyCancelKey; param->MyPMChildSlot = MyPMChildSlot; #ifdef WIN32 @@ -6124,7 +5984,6 @@ save_backend_variables(BackendParameters *param, Port *port, BackgroundWorker *w param->UsedShmemSegAddr = UsedShmemSegAddr; param->ShmemLock = ShmemLock; - param->ShmemBackendArray = ShmemBackendArray; #ifndef HAVE_SPINLOCKS param->SpinlockSemaArray = SpinlockSemaArray; @@ -6359,7 +6218,6 @@ restore_backend_variables(BackendParameters *param, Port **port, BackgroundWorke SetDataDir(param->DataDir); - MyCancelKey = param->MyCancelKey; MyPMChildSlot = param->MyPMChildSlot; #ifdef WIN32 @@ -6369,7 +6227,6 @@ restore_backend_variables(BackendParameters *param, Port **port, BackgroundWorke UsedShmemSegAddr = param->UsedShmemSegAddr; ShmemLock = param->ShmemLock; - ShmemBackendArray = param->ShmemBackendArray; #ifndef HAVE_SPINLOCKS SpinlockSemaArray = param->SpinlockSemaArray; @@ -6421,43 +6278,6 @@ restore_backend_variables(BackendParameters *param, Port **port, BackgroundWorke ReserveExternalFD(); #endif } - - -Size -ShmemBackendArraySize(void) -{ - return mul_size(MaxLivePostmasterChildren(), sizeof(Backend)); -} - -void -ShmemBackendArrayAllocation(void) -{ - Size size = ShmemBackendArraySize(); - - ShmemBackendArray = (Backend *) ShmemAlloc(size); - /* Mark all slots as empty */ - memset(ShmemBackendArray, 0, size); -} - -static void -ShmemBackendArrayAdd(Backend *bn) -{ - /* The array slot corresponding to my PMChildSlot should be free */ - int i = bn->child_slot - 1; - - Assert(ShmemBackendArray[i].pid == 0); - ShmemBackendArray[i] = *bn; -} - -static void -ShmemBackendArrayRemove(Backend *bn) -{ - int i = bn->child_slot - 1; - - Assert(ShmemBackendArray[i].pid == bn->pid); - /* Mark the slot as empty */ - ShmemBackendArray[i].pid = 0; -} #endif /* EXEC_BACKEND */ diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c index 521ed5418cc..7cf7fe0549a 100644 --- a/src/backend/storage/ipc/ipci.c +++ b/src/backend/storage/ipc/ipci.c @@ -152,9 +152,6 @@ CalculateShmemSize(int *num_semaphores) size = add_size(size, WaitEventExtensionShmemSize()); size = add_size(size, InjectionPointShmemSize()); size = add_size(size, SlotSyncShmemSize()); -#ifdef EXEC_BACKEND - size = add_size(size, ShmemBackendArraySize()); -#endif /* include additional requested shmem from preload libraries */ size = add_size(size, total_addin_request); @@ -244,14 +241,6 @@ CreateSharedMemoryAndSemaphores(void) /* Initialize subsystems */ CreateOrAttachShmemStructs(); -#ifdef EXEC_BACKEND - - /* - * Alloc the win32 shared backend array - */ - ShmemBackendArrayAllocation(); -#endif - /* Initialize dynamic shared memory facilities. */ dsm_postmaster_startup(shim); diff --git a/src/backend/storage/ipc/pmsignal.c b/src/backend/storage/ipc/pmsignal.c index 27844b46a2b..9516b869cb2 100644 --- a/src/backend/storage/ipc/pmsignal.c +++ b/src/backend/storage/ipc/pmsignal.c @@ -22,6 +22,7 @@ #endif #include "miscadmin.h" +#include "port/atomics.h" #include "postmaster/postmaster.h" #include "replication/walsender.h" #include "storage/pmsignal.h" @@ -37,9 +38,8 @@ * if the same reason is signaled more than once simultaneously, the * postmaster will observe it only once.) * - * The flags are actually declared as "volatile sig_atomic_t" for maximum - * portability. This should ensure that loads and stores of the flag - * values are atomic, allowing us to dispense with any explicit locking. + * The flag fields use atomics, allowing us to dispense with any explicit + * locking. * * In addition to the per-reason flags, we store a set of per-child-process * flags that are currently used only for detecting whether a backend has @@ -67,20 +67,29 @@ #define PM_CHILD_ACTIVE 2 #define PM_CHILD_WALSENDER 3 +typedef struct ChildSlotData +{ + pg_atomic_uint32 state; + + int pid; + int32 cancel_key; +} ChildSlotData; + /* "typedef struct PMSignalData PMSignalData" appears in pmsignal.h */ struct PMSignalData { /* per-reason flags for signaling the postmaster */ - sig_atomic_t PMSignalFlags[NUM_PMSIGNALS]; + volatile sig_atomic_t PMSignalFlags[NUM_PMSIGNALS]; /* global flags for signals from postmaster to children */ QuitSignalReason sigquit_reason; /* why SIGQUIT was sent */ - /* per-child-process flags */ - int num_child_flags; /* # of entries in PMChildFlags[] */ - sig_atomic_t PMChildFlags[FLEXIBLE_ARRAY_MEMBER]; + + /* per-child-process slots */ + int num_child_slots; /* # of entries in child_slots[] */ + ChildSlotData child_slots[FLEXIBLE_ARRAY_MEMBER]; }; /* PMSignalState pointer is valid in both postmaster and child processes */ -NON_EXEC_STATIC volatile PMSignalData *PMSignalState = NULL; +NON_EXEC_STATIC PMSignalData *PMSignalState = NULL; /* * These static variables are valid only in the postmaster. We keep a @@ -130,9 +139,9 @@ PMSignalShmemSize(void) { Size size; - size = offsetof(PMSignalData, PMChildFlags); + size = offsetof(PMSignalData, child_slots); size = add_size(size, mul_size(MaxLivePostmasterChildren(), - sizeof(sig_atomic_t))); + sizeof(ChildSlotData))); return size; } @@ -151,9 +160,9 @@ PMSignalShmemInit(void) if (!found) { /* initialize all flags to zeroes */ - MemSet(unvolatize(PMSignalData *, PMSignalState), 0, PMSignalShmemSize()); + MemSet(PMSignalState, 0, PMSignalShmemSize()); num_child_inuse = MaxLivePostmasterChildren(); - PMSignalState->num_child_flags = num_child_inuse; + PMSignalState->num_child_slots = num_child_inuse; /* * Also allocate postmaster's private PMChildInUse[] array. We @@ -262,14 +271,14 @@ AssignPostmasterChildSlot(void) if (!PMChildInUse[slot]) { PMChildInUse[slot] = true; - PMSignalState->PMChildFlags[slot] = PM_CHILD_ASSIGNED; + pg_atomic_write_u32(&PMSignalState->child_slots[slot].state, PM_CHILD_ASSIGNED); next_child_inuse = slot; return slot + 1; } } /* Out of slots ... should never happen, else postmaster.c messed up */ - elog(FATAL, "no free slots in PMChildFlags array"); + elog(FATAL, "no free slots in postmaster child array"); return 0; /* keep compiler quiet */ } @@ -283,7 +292,7 @@ AssignPostmasterChildSlot(void) bool ReleasePostmasterChildSlot(int slot) { - bool result; + uint32 oldstate; Assert(slot > 0 && slot <= num_child_inuse); slot--; @@ -293,10 +302,9 @@ ReleasePostmasterChildSlot(int slot) * postmaster.c is such that this might get called twice when a child * crashes. So we don't try to Assert anything about the state. */ - result = (PMSignalState->PMChildFlags[slot] == PM_CHILD_ASSIGNED); - PMSignalState->PMChildFlags[slot] = PM_CHILD_UNUSED; + oldstate = pg_atomic_exchange_u32(&PMSignalState->child_slots[slot].state, PM_CHILD_UNUSED); PMChildInUse[slot] = false; - return result; + return oldstate == PM_CHILD_ASSIGNED; } /* @@ -309,7 +317,7 @@ IsPostmasterChildWalSender(int slot) Assert(slot > 0 && slot <= num_child_inuse); slot--; - if (PMSignalState->PMChildFlags[slot] == PM_CHILD_WALSENDER) + if (pg_atomic_read_u32(&PMSignalState->child_slots[slot].state) == PM_CHILD_WALSENDER) return true; else return false; @@ -320,14 +328,17 @@ IsPostmasterChildWalSender(int slot) * actively using shared memory. This is called in the child process. */ void -MarkPostmasterChildActive(void) +MarkPostmasterChildActive(int pid, int32 cancelAuthCode) { int slot = MyPMChildSlot; - Assert(slot > 0 && slot <= PMSignalState->num_child_flags); + Assert(slot > 0 && slot <= PMSignalState->num_child_slots); slot--; - Assert(PMSignalState->PMChildFlags[slot] == PM_CHILD_ASSIGNED); - PMSignalState->PMChildFlags[slot] = PM_CHILD_ACTIVE; + Assert(pg_atomic_read_u32(&PMSignalState->child_slots[slot].state) == PM_CHILD_ASSIGNED); + PMSignalState->child_slots[slot].pid = pid; + PMSignalState->child_slots[slot].cancel_key = cancelAuthCode; + pg_memory_barrier(); + pg_atomic_write_u32(&PMSignalState->child_slots[slot].state, PM_CHILD_ACTIVE); } /* @@ -342,10 +353,10 @@ MarkPostmasterChildWalSender(void) Assert(am_walsender); - Assert(slot > 0 && slot <= PMSignalState->num_child_flags); + Assert(slot > 0 && slot <= PMSignalState->num_child_slots); slot--; - Assert(PMSignalState->PMChildFlags[slot] == PM_CHILD_ACTIVE); - PMSignalState->PMChildFlags[slot] = PM_CHILD_WALSENDER; + Assert(pg_atomic_read_u32(&PMSignalState->child_slots[slot].state) == PM_CHILD_ACTIVE); + pg_atomic_write_u32(&PMSignalState->child_slots[slot].state, PM_CHILD_WALSENDER); } /* @@ -357,11 +368,17 @@ MarkPostmasterChildInactive(void) { int slot = MyPMChildSlot; - Assert(slot > 0 && slot <= PMSignalState->num_child_flags); + Assert(slot > 0 && slot <= PMSignalState->num_child_slots); slot--; - Assert(PMSignalState->PMChildFlags[slot] == PM_CHILD_ACTIVE || - PMSignalState->PMChildFlags[slot] == PM_CHILD_WALSENDER); - PMSignalState->PMChildFlags[slot] = PM_CHILD_ASSIGNED; +#ifdef USE_ASSERT_CHECKING + { + uint32 oldstate; + + oldstate = pg_atomic_read_u32(&PMSignalState->child_slots[slot].state); + Assert(oldstate == PM_CHILD_ACTIVE || oldstate == PM_CHILD_WALSENDER); + } +#endif + pg_atomic_write_u32(&PMSignalState->child_slots[slot].state, PM_CHILD_ASSIGNED); } @@ -460,3 +477,50 @@ PostmasterDeathSignalInit(void) postmaster_possibly_dead = true; #endif /* USE_POSTMASTER_DEATH_SIGNAL */ } + +void +SendCancelRequest(int backendPID, int32 cancelAuthCode) +{ + /* + * See if we have a matching backend. In the EXEC_BACKEND case, we can no + * longer access the postmaster's own backend list, and must rely on the + * duplicate array in shared memory. XXX + */ + for (int i = MaxLivePostmasterChildren() - 1; i >= 0; i--) + { + ChildSlotData *slot = &PMSignalState->child_slots[i]; + uint32 state = pg_atomic_read_u32(&slot->state); + + if (state != PM_CHILD_ACTIVE) + continue; + + pg_read_barrier(); + if (slot->pid == backendPID) + { + if (slot->cancel_key == cancelAuthCode) + { + /* Found a match; signal that backend to cancel current op */ + ereport(DEBUG2, + (errmsg_internal("processing cancel request: sending SIGINT to process %d", + backendPID))); + + /* + * FIXME: we used to use signal_child. I believe kill() is + * maybe even more correct, but verify that. + */ + kill(backendPID, SIGINT); + } + else + /* Right PID, wrong key: no way, Jose */ + ereport(LOG, + (errmsg("wrong key in cancel request for process %d", + backendPID))); + return; + } + } + + /* No matching backend */ + ereport(LOG, + (errmsg("PID %d in cancel request did not match any process", + backendPID))); +} diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index f3e20038f42..a30bba1499c 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -307,6 +307,20 @@ InitProcess(void) if (MyProc != NULL) elog(ERROR, "you already exist"); + /* + * Generate a random cancel key. + * + * We probably don't need cancel keys for non-backend processes, but we'd + * better have something random in the field to prevent unfriendly people + * from sending cancels to them. + */ + if (!pg_strong_random(&MyCancelKey, sizeof(int32))) + { + ereport(ERROR, + (errcode(ERRCODE_INTERNAL_ERROR), + errmsg("could not generate random cancel key"))); + } + /* Decide which list should supply our PGPROC. */ if (AmAutoVacuumLauncherProcess() || AmAutoVacuumWorkerProcess()) procgloballist = &ProcGlobal->autovacFreeProcs; @@ -370,7 +384,7 @@ InitProcess(void) */ if (IsUnderPostmaster && !AmAutoVacuumLauncherProcess() && !AmLogicalSlotSyncWorkerProcess()) - MarkPostmasterChildActive(); + MarkPostmasterChildActive(MyProcPid, MyCancelKey); /* * Initialize all fields of MyProc, except for those previously diff --git a/src/include/postmaster/postmaster.h b/src/include/postmaster/postmaster.h index 46f95f7c8a6..dc133afd815 100644 --- a/src/include/postmaster/postmaster.h +++ b/src/include/postmaster/postmaster.h @@ -61,9 +61,6 @@ extern bool PostmasterMarkPIDForWorkerNotify(int); #ifdef EXEC_BACKEND extern pid_t postmaster_forkexec(int argc, char *argv[]); extern void SubPostmasterMain(int argc, char *argv[]) pg_attribute_noreturn(); - -extern Size ShmemBackendArraySize(void); -extern void ShmemBackendArrayAllocation(void); #endif /* diff --git a/src/include/storage/pmsignal.h b/src/include/storage/pmsignal.h index 029b7201093..8dff47e86e4 100644 --- a/src/include/storage/pmsignal.h +++ b/src/include/storage/pmsignal.h @@ -69,11 +69,12 @@ extern QuitSignalReason GetQuitSignalReason(void); extern int AssignPostmasterChildSlot(void); extern bool ReleasePostmasterChildSlot(int slot); extern bool IsPostmasterChildWalSender(int slot); -extern void MarkPostmasterChildActive(void); +extern void MarkPostmasterChildActive(int pid, int32 cancelAuthCode); extern void MarkPostmasterChildInactive(void); extern void MarkPostmasterChildWalSender(void); extern bool PostmasterIsAliveInternal(void); extern void PostmasterDeathSignalInit(void); +extern void SendCancelRequest(int backendPID, int32 cancelAuthCode); /* diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index d3a7f75b080..e2233af884c 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -374,6 +374,7 @@ CatalogId CatalogIdMapEntry CatalogIndexState ChangeVarNodes_context +ChildSlotData ReplaceVarnoContext CheckPoint CheckPointStmt -- 2.39.2
v2-0002-Make-cancel-request-keys-longer-bump-minor-protoc.patch (text/x-patch, 32.3K) download From 419eadc67021fd98cc7f0a661e315eefd27f3789 Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas <heikki.linnakangas@iki.fi> Date: Sat, 9 Mar 2024 00:16:31 +0200 Subject: [PATCH v2 2/2] Make cancel request keys longer, bump minor protocol version Currently, cancel request key is 32-bit token, which isn't very much entropy. If you want to cancel another session's query, you can brute-force it. In most environments, an unauthorized cancellation of a query isn't very serious, but it nevertheless would be nice to have more protection from it. To make it harder to guess the key, make it larger. The new longer key length is not hardcoded in the protocol anymore, the client is expected to deal with variable length keys, up to some reasonable upper limit (TODO: document the maximum). This flexibility allows e.g. a connection pooler to add more information to the cancel key, which might be useful for finding the connection. This bumps the protocol version from 3.0 to 3.1. The server and libpq still both understand version 3.0, for interoperability with old client and server versions. If an old client connects to the server, the server falls back to generate a short 32-bit token like before. Note that the minor protocol version negotiation was added to the server in version 9.3. Connecting to PostgreSQL 9.2 with new libpq will fail with "unsupported frontend protocol" error. If we wanted to stay compatible, we could teach libpq to reconnect with protocol version 3.0, but I don't think that's necessary. Reviewed-by: Jelte Fennema-Nio Discussion: https://www.postgresql.org/message-id/508d0505-8b7a-4864-a681-e7e5edfe32aa@iki.fi --- doc/src/sgml/protocol.sgml | 120 +++++++++++++++++++++++++--- src/backend/postmaster/postmaster.c | 71 +++++++++++----- src/backend/storage/ipc/pmsignal.c | 42 +++++++--- src/backend/storage/lmgr/proc.c | 10 ++- src/backend/tcop/postgres.c | 12 ++- src/backend/utils/init/globals.c | 1 - src/include/libpq/pqcomm.h | 16 +++- src/include/miscadmin.h | 3 +- src/include/storage/pmsignal.h | 7 +- src/interfaces/libpq/fe-cancel.c | 59 ++++++++++---- src/interfaces/libpq/fe-connect.c | 32 ++++++-- src/interfaces/libpq/fe-protocol3.c | 66 +++++++++++++-- src/interfaces/libpq/libpq-int.h | 8 +- 13 files changed, 366 insertions(+), 81 deletions(-) diff --git a/doc/src/sgml/protocol.sgml b/doc/src/sgml/protocol.sgml index a5cb19357f5..357a7cb2fb0 100644 --- a/doc/src/sgml/protocol.sgml +++ b/doc/src/sgml/protocol.sgml @@ -18,9 +18,11 @@ </para> <para> - This document describes version 3.0 of the protocol, implemented in + This document describes version 3.1 of the protocol, introduces in + <productname>PostgreSQL</productname> 17. The server is compatible with + protocol version 3.0, implemented in <productname>PostgreSQL</productname> 7.4 and later. For descriptions - of the earlier protocol versions, see previous releases of the + of earlier protocol versions, see previous releases of the <productname>PostgreSQL</productname> documentation. A single server can support multiple protocol versions. The initial startup-request message tells the server which protocol version the client is attempting to @@ -34,6 +36,17 @@ minor protocol version which it supports. The client may then choose either to continue with the connection using the specified protocol version or to abort the connection. + + TODO: mention that the minor version negotiation was introduced PostgreSQL 9.3 + libpq can no longer connect to PostgreSQL 9.2. Maybe a support matrix? + </para> + + <para> + The difference between protocol version 3.0 and 3.1 is that the secret key + used query cancellation was enlarged from 4 bytes to a variable length + field. The BackendKeyData message was changed to accomodate that, and a new + CancelRequestExtended message with variable length secret was introduced to + replace the old CancelRequest message. </para> <para> @@ -405,8 +418,14 @@ this message indicates the highest supported minor version. This message will also be sent if the client requested unsupported protocol options (i.e., beginning with <literal>_pq_.</literal>) in the - startup packet. This message will be followed by an ErrorResponse or - a message indicating the success or failure of authentication. + startup packet. + </para> + <para> + After this message, the authentication will continue using the version + indicated by the server. If the client does not support the older + version, it should immediately close the connection. If the server + does not send this message, it supports the client's requested + protocol version and all the protocol options. </para> </listitem> </varlistentry> @@ -1381,7 +1400,7 @@ SELCT 1/0;<!-- this typo is intentional --> <para> To issue a cancel request, the frontend opens a new connection to - the server and sends a CancelRequest message, rather than the + the server and sends a cancel request message (CancelRequestExtended or CancelRequest), rather StartupMessage message that would ordinarily be sent across a new connection. The server will process this request and then close the connection. For security reasons, no direct reply is made to @@ -1389,7 +1408,7 @@ SELCT 1/0;<!-- this typo is intentional --> </para> <para> - A CancelRequest message will be ignored unless it contains the + A cancel request message will be ignored unless it contains the same key data (PID and secret key) passed to the frontend during connection start-up. If the request matches the PID and secret key for a currently executing backend, the processing of the @@ -1531,7 +1550,7 @@ SELCT 1/0;<!-- this typo is intentional --> <para> An initial SSLRequest can also be used in a connection that is being - opened to send a CancelRequest message. + opened to send a CancelRequest or CancelRequestExtended message. </para> <para> @@ -1607,7 +1626,7 @@ SELCT 1/0;<!-- this typo is intentional --> <para> An initial GSSENCRequest can also be used in a connection that is being - opened to send a CancelRequest message. + opened to send a CancelRequest or CancelRequestExtended message. </para> <para> @@ -3852,13 +3871,13 @@ psql "dbname=postgres replication=database" -c "IDENTIFY_SYSTEM;" <para> Identifies the message as cancellation key data. The frontend must save these values if it wishes to be - able to issue CancelRequest messages later. + able to issue cancel request messages later. </para> </listitem> </varlistentry> <varlistentry> - <term>Int32(12)</term> + <term>Int32</term> <listitem> <para> Length of message contents in bytes, including self. @@ -3876,7 +3895,21 @@ psql "dbname=postgres replication=database" -c "IDENTIFY_SYSTEM;" </varlistentry> <varlistentry> - <term>Int32</term> + <term>Int16</term> + <listitem> + <para> + Length of the secret key. + </para> + <para> + This field was added in minor protocol version 3.1. In protocol + version 3.0, it is omitted, and the secret key is always 4 bytes + long. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Byten</term> <listitem> <para> The secret key of this backend. @@ -4088,8 +4121,69 @@ psql "dbname=postgres replication=database" -c "IDENTIFY_SYSTEM;" </listitem> </varlistentry> + <varlistentry> + <term>Byte4</term> + <listitem> + <para> + The secret key for the target backend. + </para> + </listitem> + </varlistentry> + </variablelist> + <para> + This is for the older protocol version 3.0. Starting with protocol + version 3.1, the secret key is longer and the new CancelRequestExtended + message must be used instead. + </para> + </listitem> + </varlistentry> + + <varlistentry id="protocol-message-formats-CancelRequestExtended"> + <term>CancelRequestExtended (F)</term> + <listitem> + <variablelist> + <varlistentry> + <term>Int32(16)</term> + <listitem> + <para> + Length of message contents in bytes, including self. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Int32(80877101)</term> + <listitem> + <para> + The cancel request code. The value is chosen to contain + <literal>1234</literal> in the most significant 16 bits, + and <literal>5677</literal> in the least significant 16 bits. (To + avoid confusion, this code must not be the same as any protocol + version number.) + </para> + </listitem> + </varlistentry> + <varlistentry> <term>Int32</term> + <listitem> + <para> + The process ID of the target backend. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Int16</term> + <listitem> + <para> + Length of the secret key. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Byten</term> <listitem> <para> The secret key for the target backend. @@ -4097,6 +4191,10 @@ psql "dbname=postgres replication=database" -c "IDENTIFY_SYSTEM;" </listitem> </varlistentry> </variablelist> + <para> + This message was added in protocol version 3.1. In protocol version 3.0, + use the CancelRequest message instead. + </para> </listitem> </varlistentry> diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c index 1eefe652e8e..97f4372130e 100644 --- a/src/backend/postmaster/postmaster.c +++ b/src/backend/postmaster/postmaster.c @@ -420,7 +420,8 @@ static int ServerLoop(void); static int BackendStartup(Port *port); static int ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done); static void SendNegotiateProtocolVersion(List *unrecognized_protocol_options); -static void processCancelRequest(Port *port, void *pkt); +static void processExtendedCancelRequestPacket(Port *port, void *pkt, int pktlen); +static void processCancelRequestPacket(Port *port, void *pkt, int pktlen); static void report_fork_failure_to_client(Port *port, int errnum); static CAC_state canAcceptConnections(int backend_type); static void signal_child(pid_t pid, int signal); @@ -2005,16 +2006,15 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done) */ port->proto = proto = pg_ntoh32(*((ProtocolVersion *) buf)); + if (proto == EXTENDED_CANCEL_REQUEST_CODE) + { + processExtendedCancelRequestPacket(port, buf, len); + /* Not really an error, but we don't want to proceed further */ + return STATUS_ERROR; + } if (proto == CANCEL_REQUEST_CODE) { - if (len != sizeof(CancelRequestPacket)) - { - ereport(COMMERROR, - (errcode(ERRCODE_PROTOCOL_VIOLATION), - errmsg("invalid length of startup packet"))); - return STATUS_ERROR; - } - processCancelRequest(port, buf); + processCancelRequestPacket(port, buf, len); /* Not really an error, but we don't want to proceed further */ return STATUS_ERROR; } @@ -2311,21 +2311,54 @@ SendNegotiateProtocolVersion(List *unrecognized_protocol_options) } /* - * The client has sent a cancel request packet, not a normal - * start-a-new-connection packet. Perform the necessary processing. - * Nothing is sent back to the client. + * The client has sent an ExtendedCancelRequest cancel request packet, not a normal + * start-a-new-connection packet. Perform the necessary processing. Nothing + * is sent back to the client. */ static void -processCancelRequest(Port *port, void *pkt) +processExtendedCancelRequestPacket(Port *port, void *pkt, int pktlen) { - CancelRequestPacket *canc = (CancelRequestPacket *) pkt; - int backendPID; - int32 cancelAuthCode; + ExtendedCancelRequestPacket *canc; + int len; - backendPID = (int) pg_ntoh32(canc->backendPID); - cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode); + if (pktlen < offsetof(ExtendedCancelRequestPacket, cancelAuthCode)) + { + ereport(COMMERROR, + (errcode(ERRCODE_PROTOCOL_VIOLATION), + errmsg("invalid length of extended query cancel packet"))); + return; + } + canc = (ExtendedCancelRequestPacket *) pkt; + len = pg_ntoh16(canc->cancelAuthCodeLen); + if (pktlen != offsetof(ExtendedCancelRequestPacket, cancelAuthCode) + len) + { + ereport(COMMERROR, + (errcode(ERRCODE_PROTOCOL_VIOLATION), + errmsg("invalid length of extended cancel request packet"))); + return; + } + + ProcessCancelRequest(pg_ntoh32(canc->backendPID), canc->cancelAuthCode, len); +} - SendCancelRequest(backendPID, cancelAuthCode); +/* + * like processExtendedCancelRequestPacket, but for the old protocol version + * 3.0 CancelRequest message + */ +static void +processCancelRequestPacket(Port *port, void *pkt, int pktlen) +{ + CancelRequestPacket *canc; + + if (pktlen != sizeof(CancelRequestPacket)) + { + ereport(COMMERROR, + (errcode(ERRCODE_PROTOCOL_VIOLATION), + errmsg("invalid length of query cancel packet"))); + return; + } + canc = (CancelRequestPacket *) pkt; + ProcessCancelRequest(pg_ntoh32(canc->backendPID), canc->cancelAuthCode, 4); } /* diff --git a/src/backend/storage/ipc/pmsignal.c b/src/backend/storage/ipc/pmsignal.c index 9516b869cb2..cac4de5be06 100644 --- a/src/backend/storage/ipc/pmsignal.c +++ b/src/backend/storage/ipc/pmsignal.c @@ -72,7 +72,8 @@ typedef struct ChildSlotData pg_atomic_uint32 state; int pid; - int32 cancel_key; + int cancel_key_len; + char cancel_key[MAX_CANCEL_KEY_LENGTH]; } ChildSlotData; /* "typedef struct PMSignalData PMSignalData" appears in pmsignal.h */ @@ -328,16 +329,18 @@ IsPostmasterChildWalSender(int slot) * actively using shared memory. This is called in the child process. */ void -MarkPostmasterChildActive(int pid, int32 cancelAuthCode) +MarkPostmasterChildActive(int pid, char *cancelKey, int len) { int slot = MyPMChildSlot; + Assert(len <= MAX_CANCEL_KEY_LENGTH); Assert(slot > 0 && slot <= PMSignalState->num_child_slots); slot--; Assert(pg_atomic_read_u32(&PMSignalState->child_slots[slot].state) == PM_CHILD_ASSIGNED); PMSignalState->child_slots[slot].pid = pid; - PMSignalState->child_slots[slot].cancel_key = cancelAuthCode; - pg_memory_barrier(); + memcpy(PMSignalState->child_slots[slot].cancel_key, cancelKey, len); + PMSignalState->child_slots[slot].cancel_key_len = len; + pg_write_barrier(); pg_atomic_write_u32(&PMSignalState->child_slots[slot].state, PM_CHILD_ACTIVE); } @@ -478,8 +481,22 @@ PostmasterDeathSignalInit(void) #endif /* USE_POSTMASTER_DEATH_SIGNAL */ } +static int +pg_const_time_memcmp(const void *a, const void *b, size_t len) +{ + /* + * FIXME: need a constant time implementation. Implement one somewhere in + * src/port. + */ + return memcmp(a, b, len); +} + +/* + * Find the backend with given PID, and send SIGINT to it if the cancel key + * matches. + */ void -SendCancelRequest(int backendPID, int32 cancelAuthCode) +ProcessCancelRequest(int backendPID, char *cancelKey, int len) { /* * See if we have a matching backend. In the EXEC_BACKEND case, we can no @@ -497,18 +514,23 @@ SendCancelRequest(int backendPID, int32 cancelAuthCode) pg_read_barrier(); if (slot->pid == backendPID) { - if (slot->cancel_key == cancelAuthCode) + /* + * Use pg_const_time_memcmp() to prevent an attacker from using + * timing to reveal the cancel key. + */ + if (len == slot->cancel_key_len && pg_const_time_memcmp(slot->cancel_key, cancelKey, len) == 0) { /* Found a match; signal that backend to cancel current op */ ereport(DEBUG2, (errmsg_internal("processing cancel request: sending SIGINT to process %d", backendPID))); - /* - * FIXME: we used to use signal_child. I believe kill() is - * maybe even more correct, but verify that. - */ + /* If we have setsid(), signal the backend's whole process group */ +#ifdef HAVE_SETSID + kill(-backendPID, SIGINT); +#else kill(backendPID, SIGINT); +#endif } else /* Right PID, wrong key: no way, Jose */ diff --git a/src/backend/storage/lmgr/proc.c b/src/backend/storage/lmgr/proc.c index a30bba1499c..5ce86417216 100644 --- a/src/backend/storage/lmgr/proc.c +++ b/src/backend/storage/lmgr/proc.c @@ -36,6 +36,7 @@ #include "access/transam.h" #include "access/twophase.h" #include "access/xlogutils.h" +#include "libpq/libpq-be.h" #include "miscadmin.h" #include "pgstat.h" #include "postmaster/autovacuum.h" @@ -65,6 +66,9 @@ bool log_lock_waits = false; /* Pointer to this process's PGPROC struct, if any */ PGPROC *MyProc = NULL; +char MyCancelKey[MAX_CANCEL_KEY_LENGTH]; +int MyCancelKeyLength; + /* * This spinlock protects the freelist of recycled PGPROC structures. * We cannot use an LWLock because the LWLock manager depends on already @@ -314,7 +318,9 @@ InitProcess(void) * better have something random in the field to prevent unfriendly people * from sending cancels to them. */ - if (!pg_strong_random(&MyCancelKey, sizeof(int32))) + MyCancelKeyLength = (MyProcPort == NULL || MyProcPort->proto >= PG_PROTOCOL(3,1)) + ? MAX_CANCEL_KEY_LENGTH : 4; + if (!pg_strong_random(&MyCancelKey, MyCancelKeyLength)) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), @@ -384,7 +390,7 @@ InitProcess(void) */ if (IsUnderPostmaster && !AmAutoVacuumLauncherProcess() && !AmLogicalSlotSyncWorkerProcess()) - MarkPostmasterChildActive(MyProcPid, MyCancelKey); + MarkPostmasterChildActive(MyProcPid, MyCancelKey, MyCancelKeyLength); /* * Initialize all fields of MyProc, except for those previously diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c index aec1b194424..9c7b63ef4f8 100644 --- a/src/backend/tcop/postgres.c +++ b/src/backend/tcop/postgres.c @@ -4274,7 +4274,17 @@ PostgresMain(const char *dbname, const char *username) pq_beginmessage(&buf, PqMsg_BackendKeyData); pq_sendint32(&buf, (int32) MyProcPid); - pq_sendint32(&buf, (int32) MyCancelKey); + + if (MyProcPort->proto >= PG_PROTOCOL(3, 1)) + { + pq_sendint16(&buf, MyCancelKeyLength); + pq_sendbytes(&buf, MyCancelKey, MyCancelKeyLength); + } + else + { + Assert(MyCancelKeyLength == 4); + pq_sendbytes(&buf, MyCancelKey, 4); + } pq_endmessage(&buf); /* Need not flush since ReadyForQuery will do it. */ } diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c index 5b536ac50d1..fe702af4cfb 100644 --- a/src/backend/utils/init/globals.c +++ b/src/backend/utils/init/globals.c @@ -46,7 +46,6 @@ int MyProcPid; pg_time_t MyStartTime; TimestampTz MyStartTimestamp; struct Port *MyProcPort; -int32 MyCancelKey; int MyPMChildSlot; /* diff --git a/src/include/libpq/pqcomm.h b/src/include/libpq/pqcomm.h index 9ae469c86c4..d1cf43f12d0 100644 --- a/src/include/libpq/pqcomm.h +++ b/src/include/libpq/pqcomm.h @@ -94,7 +94,7 @@ is_unixsock_path(const char *path) */ #define PG_PROTOCOL_EARLIEST PG_PROTOCOL(3,0) -#define PG_PROTOCOL_LATEST PG_PROTOCOL(3,0) +#define PG_PROTOCOL_LATEST PG_PROTOCOL(3,1) typedef uint32 ProtocolVersion; /* FE/BE protocol version number */ @@ -129,6 +129,18 @@ typedef uint32 AuthRequest; * The cancel request code must not match any protocol version number * we're ever likely to use. This random choice should do. */ +#define EXTENDED_CANCEL_REQUEST_CODE PG_PROTOCOL(1234,5677) + +typedef struct ExtendedCancelRequestPacket +{ + /* Note that each field is stored in network byte order! */ + MsgType cancelRequestCode; /* code to identify a cancel request */ + uint32 backendPID; /* PID of client's backend */ + uint16 cancelAuthCodeLen; /* length of cancelAuthCode */ + char cancelAuthCode[FLEXIBLE_ARRAY_MEMBER]; /* secret key to + * authorize cancel */ +} ExtendedCancelRequestPacket; + #define CANCEL_REQUEST_CODE PG_PROTOCOL(1234,5678) typedef struct CancelRequestPacket @@ -136,7 +148,7 @@ typedef struct CancelRequestPacket /* Note that each field is stored in network byte order! */ MsgType cancelRequestCode; /* code to identify a cancel request */ uint32 backendPID; /* PID of client's backend */ - uint32 cancelAuthCode; /* secret key to authorize cancel */ + char cancelAuthCode[4]; /* secret key to authorize cancel */ } CancelRequestPacket; diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h index f900da61573..ae4abc0a43b 100644 --- a/src/include/miscadmin.h +++ b/src/include/miscadmin.h @@ -191,7 +191,8 @@ extern PGDLLIMPORT pg_time_t MyStartTime; extern PGDLLIMPORT TimestampTz MyStartTimestamp; extern PGDLLIMPORT struct Port *MyProcPort; extern PGDLLIMPORT struct Latch *MyLatch; -extern PGDLLIMPORT int32 MyCancelKey; +extern PGDLLIMPORT char MyCancelKey[]; +extern PGDLLIMPORT int MyCancelKeyLength; extern PGDLLIMPORT int MyPMChildSlot; extern PGDLLIMPORT char OutputFileName[]; diff --git a/src/include/storage/pmsignal.h b/src/include/storage/pmsignal.h index 8dff47e86e4..2573c051b0b 100644 --- a/src/include/storage/pmsignal.h +++ b/src/include/storage/pmsignal.h @@ -57,6 +57,9 @@ typedef enum /* PMSignalData is an opaque struct, details known only within pmsignal.c */ typedef struct PMSignalData PMSignalData; +/* Length of query cancel keys generated. */ +#define MAX_CANCEL_KEY_LENGTH 32 + /* * prototypes for functions in pmsignal.c */ @@ -69,12 +72,12 @@ extern QuitSignalReason GetQuitSignalReason(void); extern int AssignPostmasterChildSlot(void); extern bool ReleasePostmasterChildSlot(int slot); extern bool IsPostmasterChildWalSender(int slot); -extern void MarkPostmasterChildActive(int pid, int32 cancelAuthCode); +extern void MarkPostmasterChildActive(int pid, char *cancelKey, int len); extern void MarkPostmasterChildInactive(void); extern void MarkPostmasterChildWalSender(void); extern bool PostmasterIsAliveInternal(void); extern void PostmasterDeathSignalInit(void); -extern void SendCancelRequest(int backendPID, int32 cancelAuthCode); +extern void ProcessCancelRequest(int backendPID, char *cancelKey, int len); /* diff --git a/src/interfaces/libpq/fe-cancel.c b/src/interfaces/libpq/fe-cancel.c index 51f8d8a78c4..608038cf2be 100644 --- a/src/interfaces/libpq/fe-cancel.c +++ b/src/interfaces/libpq/fe-cancel.c @@ -34,6 +34,8 @@ PGcancel * PQgetCancel(PGconn *conn) { PGcancel *cancel; + int cancel_req_len; + bool use_extended; if (!conn) return NULL; @@ -41,13 +43,20 @@ PQgetCancel(PGconn *conn) if (conn->sock == PGINVALID_SOCKET) return NULL; - cancel = malloc(sizeof(PGcancel)); + use_extended = conn->pversion >= PG_PROTOCOL(3, 1); + if (use_extended) + cancel_req_len = offsetof(ExtendedCancelRequestPacket, cancelAuthCode) + conn->be_cancel_key_len; + else + { + Assert(conn->be_cancel_key_len == 4); + cancel_req_len = sizeof(CancelRequestPacket); + } + cancel = malloc(offsetof(PGcancel, cancel_req) + cancel_req_len); if (cancel == NULL) return NULL; memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr)); - cancel->be_pid = conn->be_pid; - cancel->be_key = conn->be_key; + /* We use -1 to indicate an unset connection option */ cancel->pgtcp_user_timeout = -1; cancel->keepalives = -1; @@ -90,6 +99,28 @@ PQgetCancel(PGconn *conn) goto fail; } + if (use_extended) + { + ExtendedCancelRequestPacket *req; + + req = (ExtendedCancelRequestPacket *) &cancel->cancel_req; + req->cancelRequestCode = (MsgType) pg_hton32(EXTENDED_CANCEL_REQUEST_CODE); + req->backendPID = pg_hton32(conn->be_pid); + req->cancelAuthCodeLen = pg_hton16(conn->be_cancel_key_len); + memcpy(req->cancelAuthCode, conn->be_cancel_key, conn->be_cancel_key_len); + } + else + { + CancelRequestPacket *req; + + req = (CancelRequestPacket *) &cancel->cancel_req; + req->cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE); + req->backendPID = pg_hton32(conn->be_pid); + memcpy(req->cancelAuthCode, conn->be_cancel_key, 4); + } + /* include the length field itself in the length */ + cancel->cancel_pkt_len = pg_hton32(cancel_req_len + 4); + return cancel; fail: @@ -150,11 +181,8 @@ PQcancel(PGcancel *cancel, char *errbuf, int errbufsize) int save_errno = SOCK_ERRNO; pgsocket tmpsock = PGINVALID_SOCKET; int maxlen; - struct - { - uint32 packetlen; - CancelRequestPacket cp; - } crp; + char recvbuf; + int cancel_pkt_len; if (!cancel) { @@ -256,15 +284,14 @@ retry3: goto cancel_errReturn; } - /* Create and send the cancel request packet. */ - - crp.packetlen = pg_hton32((uint32) sizeof(crp)); - crp.cp.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE); - crp.cp.backendPID = pg_hton32(cancel->be_pid); - crp.cp.cancelAuthCode = pg_hton32(cancel->be_key); + cancel_pkt_len = pg_ntoh32(cancel->cancel_pkt_len); retry4: - if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp)) + /* + * Send the cancel request packet. It starts with the message length at + * cancel_pkt_len, followed by the actual packet. + */ + if (send(tmpsock, (char *) &cancel->cancel_pkt_len, cancel_pkt_len, 0) != cancel_pkt_len) { if (SOCK_ERRNO == EINTR) /* Interrupted system call - we'll just try again */ @@ -281,7 +308,7 @@ retry4: * read to obtain any data, we are just waiting for EOF to be signaled. */ retry5: - if (recv(tmpsock, (char *) &crp, 1, 0) < 0) + if (recv(tmpsock, &recvbuf, 1, 0) < 0) { if (SOCK_ERRNO == EINTR) /* Interrupted system call - we'll just try again */ diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index d4e10a0c4f3..e47b933e27e 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -617,7 +617,12 @@ pqDropServerData(PGconn *conn) free(conn->write_err_msg); conn->write_err_msg = NULL; conn->be_pid = 0; - conn->be_key = 0; + if (conn->be_cancel_key != NULL) + { + free(conn->be_cancel_key); + conn->be_cancel_key = NULL; + } + conn->be_cancel_key_len = 0; } @@ -2724,7 +2729,7 @@ keep_going: /* We will come back to here until there is * must persist across individual connection attempts, but we must * reset them when we start to consider a new server. */ - conn->pversion = PG_PROTOCOL(3, 0); + conn->pversion = PG_PROTOCOL(3, 1); conn->send_appname = true; #ifdef USE_SSL /* initialize these values based on SSL mode */ @@ -3724,14 +3729,25 @@ keep_going: /* We will come back to here until there is } else if (beresp == PqMsg_NegotiateProtocolVersion) { - if (pqGetNegotiateProtocolVersion3(conn)) + switch (pqGetNegotiateProtocolVersion3(conn)) { - libpq_append_conn_error(conn, "received invalid protocol negotiation message"); - goto error_return; + case 0: + /* OK, we read the message; mark data consumed */ + conn->inStart = conn->inCursor; + /* Stay in the CONNECTION_AWAITING_RESPONSE state */ + goto keep_going; + case 1: + /* + * Negotiation failed. The error message was + * filled in already. + */ + conn->inStart = conn->inCursor; + goto error_return; + case EOF: + /* We'll come back when there is more data */ + libpq_append_conn_error(conn, "received invalid protocol negotiation message"); + goto error_return; } - /* OK, we read the message; mark data consumed */ - conn->inStart = conn->inCursor; - goto error_return; } /* It is an authentication request. */ diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c index 701d58e1087..877ba69c4a8 100644 --- a/src/interfaces/libpq/fe-protocol3.c +++ b/src/interfaces/libpq/fe-protocol3.c @@ -48,6 +48,7 @@ static int getRowDescriptions(PGconn *conn, int msgLength); static int getParamDescriptions(PGconn *conn, int msgLength); static int getAnotherTuple(PGconn *conn, int msgLength); static int getParameterStatus(PGconn *conn); +static int getBackendKeyData(PGconn *conn); static int getNotify(PGconn *conn); static int getCopyStart(PGconn *conn, ExecStatusType copytype); static int getReadyForQuery(PGconn *conn); @@ -308,9 +309,7 @@ pqParseInput3(PGconn *conn) * just as easy to handle it as part of the main loop. * Save the data and continue processing. */ - if (pqGetInt(&(conn->be_pid), 4, conn)) - return; - if (pqGetInt(&(conn->be_key), 4, conn)) + if (getBackendKeyData(conn)) return; break; case PqMsg_RowDescription: @@ -1404,7 +1403,8 @@ reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding) /* * Attempt to read a NegotiateProtocolVersion message. * Entry: 'v' message type and length have already been consumed. - * Exit: returns 0 if successfully consumed message. + * Exit: returns 0 if successfully consumed message and the negotiation succeeded. + * returns 1 if successfully consumed message and the negotiation failed. * returns EOF if not enough data. */ int @@ -1435,10 +1435,13 @@ pqGetNegotiateProtocolVersion3(PGconn *conn) appendPQExpBufferStr(&buf, conn->workBuffer.data); } - if (their_version < conn->pversion) - libpq_append_conn_error(conn, "protocol version not supported by server: client uses %u.%u, server supports up to %u.%u", + if (their_version < PG_PROTOCOL(3, 0)) + { + libpq_append_conn_error(conn, "protocol version not supported by server: client uses %u.%u, server supports up to %u.%u", /* XXX */ PG_PROTOCOL_MAJOR(conn->pversion), PG_PROTOCOL_MINOR(conn->pversion), PG_PROTOCOL_MAJOR(their_version), PG_PROTOCOL_MINOR(their_version)); + return 1; + } if (num > 0) { appendPQExpBuffer(&conn->errorMessage, @@ -1450,7 +1453,12 @@ pqGetNegotiateProtocolVersion3(PGconn *conn) /* neither -- server shouldn't have sent it */ if (!(their_version < conn->pversion) && !(num > 0)) + { libpq_append_conn_error(conn, "invalid %s message", "NegotiateProtocolVersion"); + return 1; + } + + conn->pversion = their_version; termPQExpBuffer(&buf); return 0; @@ -1485,6 +1493,52 @@ getParameterStatus(PGconn *conn) return 0; } +/* + * parseInput subroutine to read a BackendKeyData message. + * Entry: 'v' message type and length have already been consumed. + * Exit: returns 0 if successfully consumed message. + * returns EOF if not enough data. + */ +static int +getBackendKeyData(PGconn *conn) +{ + int cancel_key_len; + + if (conn->be_cancel_key) + { + free(conn->be_cancel_key); + conn->be_cancel_key = NULL; + conn->be_cancel_key_len = 0; + } + + if (pqGetInt(&(conn->be_pid), 4, conn)) + return EOF; + + if (conn->pversion >= PG_PROTOCOL(3, 1)) + { + if (pqGetInt(&cancel_key_len, 2, conn)) + return EOF; + } + else + cancel_key_len = 4; + + conn->be_cancel_key = malloc(cancel_key_len); + if (conn->be_cancel_key == NULL) + { + libpq_append_conn_error(conn, "out of memory"); + /* discard the message */ + return EOF; + } + if (pqGetnchar(conn->be_cancel_key, cancel_key_len, conn)) + { + free(conn->be_cancel_key); + conn->be_cancel_key = NULL; + return EOF; + } + conn->be_cancel_key_len = cancel_key_len; + return 0; +} + /* * Attempt to read a Notify response message. diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 82c18f870d2..3b46a760d23 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -492,7 +492,8 @@ struct pg_conn /* Miscellaneous stuff */ int be_pid; /* PID of backend --- needed for cancels */ - int be_key; /* key of backend --- needed for cancels */ + char *be_cancel_key; + uint16 be_cancel_key_len; pgParameterStatus *pstatus; /* ParameterStatus data */ int client_encoding; /* encoding id */ bool std_strings; /* standard_conforming_strings */ @@ -629,7 +630,6 @@ struct pg_cancel { SockAddr raddr; /* Remote address */ int be_pid; /* PID of backend --- needed for cancels */ - int be_key; /* key of backend --- needed for cancels */ int pgtcp_user_timeout; /* tcp user timeout */ int keepalives; /* use TCP keepalives? */ int keepalives_idle; /* time between TCP keepalives */ @@ -637,6 +637,10 @@ struct pg_cancel * retransmits */ int keepalives_count; /* maximum number of TCP keepalive * retransmits */ + + /* Pre-constructed cancel request packet starts here */ + int32 cancel_pkt_len; /* in network-byte-order */ + char cancel_req[FLEXIBLE_ARRAY_MEMBER]; /* CancelRequestPacket */ }; -- 2.39.2
^ permalink raw reply [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-03-09 12:32  Jelte Fennema-Nio <postgres@jeltef.nl>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  1 sibling, 0 replies; 40+ messages in thread

From: Jelte Fennema-Nio @ 2024-03-09 12:32 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: pgsql-hackers

On Fri, 8 Mar 2024 at 23:20, Heikki Linnakangas <hlinnaka@iki.fi> wrote:
> Added some documentation. There's more work to be done there, but at
> least the message type descriptions are now up-to-date.

Thanks, that's very helpful.

> The nice thing about relying on the message length was that we could
> just redefine the CancelRequest message to have a variable length
> secret, and old CancelRequest with 4-byte secret was compatible with the
> new definition too. But it doesn't matter much, so I added an explicit
> length field.
>
> FWIW I don't think that restriction makes sense. Any code that parses
> the messages needs to have the message length available, and I don't
> think it helps with sanity checking that much. I think the documentation
> is a little anachronistic. The real reason that all the message types
> include enough information to find the message end is that in protocol
> version 2, there was no message length field. The only exception that
> doesn't have that property is CopyData, and it's no coincidence that it
> was added in protocol version 3.

Hmm, looking at the current code, I do agree that not introducing a
new message would simplify both client and server implementation. Now
clients need to do different things depending on if the server
supports 3.1 or 3.0 (sending CancelRequestExtended instead of
CancelRequest and having to parse BackendKeyData differently). And I
also agree that the extra length field doesn't add much in regards to
sanity checking (for the CancelRequest and BackendKeyData message
types at least). So, sorry for the back and forth on this, but I now
agree with you that we should not add the length field. I think one
reason I didn't see the benefit before was because the initial patch
0002 was still introducing a CancelRequestExtended message type. If we
can get rid of this message type by not adding a length, then I think
that's worth losing the sanity checking.

> Unfortunately 1234,5679 already in use by NEGOTIATE_SSL_CODE. That's why
> I went the other direction. If we want to add this to "the end", it
> needs to be 1234,5681. But I wanted to keep the cancel requests together.

Fair enough, I didn't realise that. This whole point is moot anyway if
we're not introducing CancelRequestExtended

> We could teach
> libpq to disconnect and reconnect with minor protocol version 3.0, if
> connecting with 3.1 fails, but IMHO it's better to not complicate this
> and accept the break in backwards-compatibility.

Yeah, implementing automatic reconnection seems a bit overkill to me
too. But it might be nice to add a connection option that causes libpq
to use protocol 3.0. Having to install an old libpq to connect to an
old server seems quite annoying. Especially since I think that many
other types of servers that implement the postgres protocol have not
implemented the minor version negotiation.

I at least know PgBouncer[1] and pgcat[2] have not, but probably other
server implementations like CockroachDB and Google Spanner have this
problem too.

I'll try to add such a fallback connection option to my patchset soon.

[1]: https://github.com/pgbouncer/pgbouncer/pull/1007
[2]: https://github.com/postgresml/pgcat/issues/706





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-06-05 15:25  Robert Haas <robertmhaas@gmail.com>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  1 sibling, 1 reply; 40+ messages in thread

From: Robert Haas @ 2024-06-05 15:25 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Jelte Fennema-Nio <postgres@jeltef.nl>; pgsql-hackers

On Fri, Mar 8, 2024 at 5:20 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:
> The nice thing about relying on the message length was that we could
> just redefine the CancelRequest message to have a variable length
> secret, and old CancelRequest with 4-byte secret was compatible with the
> new definition too. But it doesn't matter much, so added an explicit
> length field.

I think I liked your original idea better than this one.

> One consequence of this patch that I didn't mention earlier is that it
> makes libpq incompatible with server version 9.2 and below, because the
> minor version negotiation was introduced in version 9.3. We could teach
> libpq to disconnect and reconnect with minor protocol version 3.0, if
> connecting with 3.1 fails, but IMHO it's better to not complicate this
> and accept the break in backwards-compatibility. 9.3 was released in
> 2013. We dropped pg_dump support for versions older than 9.2 a few years
> ago, this raises the bar for pg_dump to 9.3 as well.

I think we shouldn't underestimate the impact of bumping the minor
protocol version. Minor version negotiation is probably not supported
by all drivers and Jelte says that it's not supported by any poolers,
so for anybody but direct libpq users, there will be some breakage.
Now, on the one hand, as Jelte has said, there's little value in
having a protocol version if we're too afraid to make use of it. But
on the other hand, is this problem serious enough to justify the
breakage we'll cause? I'm not sure. It seems pretty silly to be using
a 32-bit value for this in 2024, but I'm sure some people aren't going
to like it, and they may not all have noticed this thread. On the
third hand, if we do this, it may help to unblock a bunch of other
pending patches that also want to do protocol-related things.

-- 
Robert Haas
EDB: http://www.enterprisedb.com





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-07-04 10:32  Heikki Linnakangas <hlinnaka@iki.fi>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 2 replies; 40+ messages in thread

From: Heikki Linnakangas @ 2024-07-04 10:32 UTC (permalink / raw)
  To: pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; +Cc: Jelte Fennema-Nio <postgres@jeltef.nl>; Robert Haas <robertmhaas@gmail.com>

Here's a new version of the first patch. In the previous version, I 
added the pid cancellation key to pmsignal.c, but on second thoughts, I 
think procsignal.c is a better place. The ProcSignal array already 
contains the pid, we just need to add the cancellation key there.

This first patch just refactors the current code, without changing the 
protocol or length of the cancellation key. I'd like to get this 
reviewed and committed first, and get back to the protocol changes after 
that.

We currently don't do any locking on the ProcSignal array. For query 
cancellations, that's good because a query cancel packet is processed 
without having a PGPROC entry, so we cannot take LWLocks. We could use 
spinlocks though. In this patch, I used memory barriers to ensure that 
we load/store the pid and the cancellation key in a sensible order, so 
that you cannot e.g. send a cancellation signal to a backend that's just 
starting up and hasn't advertised its cancellation key in ProcSignal 
yet. But I think this might be simpler and less error-prone by just 
adding a spinlock to each ProcSignal slot. That would also fix the 
existing race condition where we might set the pss_signalFlags flag for 
a slot, when the process concurrently terminates and the slot is reused 
for a different process. Because of that, we currently have this caveat: 
"... all the signals are such that no harm is done if they're mistakenly 
fired". With a spinlock, we could eliminate that race.

Thoughts?

-- 
Heikki Linnakangas
Neon (https://neon.tech)






^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-07-04 10:35  Heikki Linnakangas <hlinnaka@iki.fi>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  1 sibling, 1 reply; 40+ messages in thread

From: Heikki Linnakangas @ 2024-07-04 10:35 UTC (permalink / raw)
  To: pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; +Cc: Jelte Fennema-Nio <postgres@jeltef.nl>; Robert Haas <robertmhaas@gmail.com>

On 04/07/2024 13:32, Heikki Linnakangas wrote:
> Here's a new version of the first patch. 

Sorry, forgot attachment.

-- 
Heikki Linnakangas
Neon (https://neon.tech)

Attachments:

v3-0001-Move-cancel-key-generation-to-after-forking-the-b.patch (text/x-patch, 24.1K) download From e9fc1f4365077673c71ba138a0ae7fbcebe16a36 Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas <heikki.linnakangas@iki.fi> Date: Thu, 4 Jul 2024 01:03:15 +0300 Subject: [PATCH v3 1/1] Move cancel key generation to after forking the backend Move responsibility of generating the cancel key to the backend process. The cancel key is now generated after forking, and the backend advertises it in the ProcSignal array. When a cancel request arrives, the backend handling it scans the ProcSignal array to find the target pid and cancel key. This is similar to how this previously worked in the EXEC_BACKEND case with the ShmemBackendArray, just reusing the ProcSignal array. One notable change is that we no longer generate cancellation keys for non-backend processes. We generated them before just to prevent a malicious user from canceling them, the keys for non-backend processes were never actually given to anyone. There is now an explicit flag indicating whether a process has a valid key or not. I wrote this originally in preparation for supporting longer cancel keys, but it's a nice cleanup on its own. Reviewed-by: Jelte Fennema-Nio Discussion: https://www.postgresql.org/message-id/508d0505-8b7a-4864-a681-e7e5edfe32aa@iki.fi --- src/backend/postmaster/auxprocess.c | 2 +- src/backend/postmaster/launch_backend.c | 8 +- src/backend/postmaster/postmaster.c | 196 +----------------------- src/backend/storage/ipc/ipci.c | 11 -- src/backend/storage/ipc/procsignal.c | 77 +++++++++- src/backend/tcop/backend_startup.c | 9 +- src/backend/tcop/postgres.c | 21 +++ src/backend/utils/init/globals.c | 3 +- src/backend/utils/init/postinit.c | 2 +- src/include/miscadmin.h | 1 + src/include/postmaster/postmaster.h | 5 - src/include/storage/procsignal.h | 3 +- 12 files changed, 113 insertions(+), 225 deletions(-) diff --git a/src/backend/postmaster/auxprocess.c b/src/backend/postmaster/auxprocess.c index b21eae7136..74b8a00c94 100644 --- a/src/backend/postmaster/auxprocess.c +++ b/src/backend/postmaster/auxprocess.c @@ -71,7 +71,7 @@ AuxiliaryProcessMainCommon(void) BaseInit(); - ProcSignalInit(); + ProcSignalInit(false, 0); /* * Auxiliary processes don't run transactions, but they may need a diff --git a/src/backend/postmaster/launch_backend.c b/src/backend/postmaster/launch_backend.c index f9b24b7989..50a5a38526 100644 --- a/src/backend/postmaster/launch_backend.c +++ b/src/backend/postmaster/launch_backend.c @@ -93,7 +93,6 @@ typedef int InheritableSocket; typedef struct { char DataDir[MAXPGPATH]; - int32 MyCancelKey; int MyPMChildSlot; #ifndef WIN32 unsigned long UsedShmemSegID; @@ -103,7 +102,6 @@ typedef struct #endif void *UsedShmemSegAddr; slock_t *ShmemLock; - struct bkend *ShmemBackendArray; #ifndef HAVE_SPINLOCKS PGSemaphore *SpinlockSemaArray; #endif @@ -676,7 +674,7 @@ extern slock_t *ProcStructLock; extern PGPROC *AuxiliaryProcs; extern PMSignalData *PMSignalState; extern pg_time_t first_syslogger_file_time; -extern struct bkend *ShmemBackendArray; +extern bool redirection_done; #ifndef WIN32 #define write_inheritable_socket(dest, src, childpid) ((*(dest) = (src)), true) @@ -708,7 +706,6 @@ save_backend_variables(BackendParameters *param, ClientSocket *client_sock, strlcpy(param->DataDir, DataDir, MAXPGPATH); - param->MyCancelKey = MyCancelKey; param->MyPMChildSlot = MyPMChildSlot; #ifdef WIN32 @@ -718,7 +715,6 @@ save_backend_variables(BackendParameters *param, ClientSocket *client_sock, param->UsedShmemSegAddr = UsedShmemSegAddr; param->ShmemLock = ShmemLock; - param->ShmemBackendArray = ShmemBackendArray; #ifndef HAVE_SPINLOCKS param->SpinlockSemaArray = SpinlockSemaArray; @@ -967,7 +963,6 @@ restore_backend_variables(BackendParameters *param) SetDataDir(param->DataDir); - MyCancelKey = param->MyCancelKey; MyPMChildSlot = param->MyPMChildSlot; #ifdef WIN32 @@ -977,7 +972,6 @@ restore_backend_variables(BackendParameters *param) UsedShmemSegAddr = param->UsedShmemSegAddr; ShmemLock = param->ShmemLock; - ShmemBackendArray = param->ShmemBackendArray; #ifndef HAVE_SPINLOCKS SpinlockSemaArray = param->SpinlockSemaArray; diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c index 6f974a8d21..02442a4b85 100644 --- a/src/backend/postmaster/postmaster.c +++ b/src/backend/postmaster/postmaster.c @@ -168,7 +168,6 @@ typedef struct bkend { pid_t pid; /* process id of backend */ - int32 cancel_key; /* cancel key for cancels for this backend */ int child_slot; /* PMChildSlot for this backend, if any */ int bkend_type; /* child process flavor, see above */ bool dead_end; /* is it going to send an error and quit? */ @@ -178,10 +177,6 @@ typedef struct bkend static dlist_head BackendList = DLIST_STATIC_INIT(BackendList); -#ifdef EXEC_BACKEND -NON_EXEC_STATIC Backend *ShmemBackendArray; -#endif - BackgroundWorker *MyBgworkerEntry = NULL; @@ -413,7 +408,6 @@ static int ServerLoop(void); static int BackendStartup(ClientSocket *client_sock); static void report_fork_failure_to_client(ClientSocket *client_sock, int errnum); static CAC_state canAcceptConnections(int backend_type); -static bool RandomCancelKey(int32 *cancel_key); static void signal_child(pid_t pid, int signal); static void sigquit_child(pid_t pid); static bool SignalSomeChildren(int signal, int target); @@ -444,8 +438,6 @@ static void MaybeStartSlotSyncWorker(void); (pmState == PM_RECOVERY || pmState == PM_HOT_STANDBY))) && \ PgArchCanRestart()) -#ifdef EXEC_BACKEND - #ifdef WIN32 #define WNOHANG 0 /* ignored, so any integer value will do */ @@ -462,10 +454,6 @@ typedef struct } win32_deadchild_waitinfo; #endif /* WIN32 */ -static void ShmemBackendArrayAdd(Backend *bn); -static void ShmemBackendArrayRemove(Backend *bn); -#endif /* EXEC_BACKEND */ - /* Macros to check exit status of a child process */ #define EXIT_STATUS_0(st) ((st) == 0) #define EXIT_STATUS_1(st) (WIFEXITED(st) && WEXITSTATUS(st) == 1) @@ -1826,65 +1814,6 @@ ServerLoop(void) } } -/* - * The client has sent a cancel request packet, not a normal - * start-a-new-connection packet. Perform the necessary processing. - * Nothing is sent back to the client. - */ -void -processCancelRequest(int backendPID, int32 cancelAuthCode) -{ - Backend *bp; - -#ifndef EXEC_BACKEND - dlist_iter iter; -#else - int i; -#endif - - /* - * See if we have a matching backend. In the EXEC_BACKEND case, we can no - * longer access the postmaster's own backend list, and must rely on the - * duplicate array in shared memory. - */ -#ifndef EXEC_BACKEND - dlist_foreach(iter, &BackendList) - { - bp = dlist_container(Backend, elem, iter.cur); -#else - for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--) - { - bp = (Backend *) &ShmemBackendArray[i]; -#endif - if (bp->pid == backendPID) - { - if (bp->cancel_key == cancelAuthCode) - { - /* Found a match; signal that backend to cancel current op */ - ereport(DEBUG2, - (errmsg_internal("processing cancel request: sending SIGINT to process %d", - backendPID))); - signal_child(bp->pid, SIGINT); - } - else - /* Right PID, wrong key: no way, Jose */ - ereport(LOG, - (errmsg("wrong key in cancel request for process %d", - backendPID))); - return; - } -#ifndef EXEC_BACKEND /* make GNU Emacs 26.1 see brace balance */ - } -#else - } -#endif - - /* No matching backend */ - ereport(LOG, - (errmsg("PID %d in cancel request did not match any process", - backendPID))); -} - /* * canAcceptConnections --- check to see if database state allows connections * of the specified type. backend_type can be BACKEND_TYPE_NORMAL, @@ -2752,9 +2681,6 @@ CleanupBackgroundWorker(int pid, /* Get it out of the BackendList and clear out remaining data */ dlist_delete(&rw->rw_backend->elem); -#ifdef EXEC_BACKEND - ShmemBackendArrayRemove(rw->rw_backend); -#endif /* * It's possible that this background worker started some OTHER @@ -2840,9 +2766,6 @@ CleanupBackend(int pid, HandleChildCrash(pid, exitstatus, _("server process")); return; } -#ifdef EXEC_BACKEND - ShmemBackendArrayRemove(bp); -#endif } if (bp->bgworker_notify) { @@ -2910,9 +2833,6 @@ HandleChildCrash(int pid, int exitstatus, const char *procname) */ (void) ReleasePostmasterChildSlot(rw->rw_child_slot); dlist_delete(&rw->rw_backend->elem); -#ifdef EXEC_BACKEND - ShmemBackendArrayRemove(rw->rw_backend); -#endif pfree(rw->rw_backend); rw->rw_backend = NULL; rw->rw_pid = 0; @@ -2945,9 +2865,6 @@ HandleChildCrash(int pid, int exitstatus, const char *procname) if (!bp->dead_end) { (void) ReleasePostmasterChildSlot(bp->child_slot); -#ifdef EXEC_BACKEND - ShmemBackendArrayRemove(bp); -#endif } dlist_delete(iter.cur); pfree(bp); @@ -3560,24 +3477,9 @@ BackendStartup(ClientSocket *client_sock) return STATUS_ERROR; } - /* - * Compute the cancel key that will be assigned to this backend. The - * backend will have its own copy in the forked-off process' value of - * MyCancelKey, so that it can transmit the key to the frontend. - */ - if (!RandomCancelKey(&MyCancelKey)) - { - pfree(bn); - ereport(LOG, - (errcode(ERRCODE_INTERNAL_ERROR), - errmsg("could not generate random cancel key"))); - return STATUS_ERROR; - } - /* Pass down canAcceptConnections state */ startup_data.canAcceptConnections = canAcceptConnections(BACKEND_TYPE_NORMAL); bn->dead_end = (startup_data.canAcceptConnections != CAC_OK); - bn->cancel_key = MyCancelKey; /* * Unless it's a dead_end child, assign it a child slot number @@ -3621,11 +3523,6 @@ BackendStartup(ClientSocket *client_sock) bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */ dlist_push_head(&BackendList, &bn->elem); -#ifdef EXEC_BACKEND - if (!bn->dead_end) - ShmemBackendArrayAdd(bn); -#endif - return STATUS_OK; } @@ -3861,15 +3758,6 @@ dummy_handler(SIGNAL_ARGS) { } -/* - * Generate a random cancel key. - */ -static bool -RandomCancelKey(int32 *cancel_key) -{ - return pg_strong_random(cancel_key, sizeof(int32)); -} - /* * Count up number of child processes of specified types (dead_end children * are always excluded). @@ -3970,25 +3858,9 @@ StartAutovacuumWorker(void) */ if (canAcceptConnections(BACKEND_TYPE_AUTOVAC) == CAC_OK) { - /* - * Compute the cancel key that will be assigned to this session. We - * probably don't need cancel keys for autovac workers, but we'd - * better have something random in the field to prevent unfriendly - * people from sending cancels to them. - */ - if (!RandomCancelKey(&MyCancelKey)) - { - ereport(LOG, - (errcode(ERRCODE_INTERNAL_ERROR), - errmsg("could not generate random cancel key"))); - return; - } - bn = (Backend *) palloc_extended(sizeof(Backend), MCXT_ALLOC_NO_OOM); if (bn) { - bn->cancel_key = MyCancelKey; - /* Autovac workers are not dead_end and need a child slot */ bn->dead_end = false; bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot(); @@ -3999,9 +3871,6 @@ StartAutovacuumWorker(void) { bn->bkend_type = BACKEND_TYPE_AUTOVAC; dlist_push_head(&BackendList, &bn->elem); -#ifdef EXEC_BACKEND - ShmemBackendArrayAdd(bn); -#endif /* all OK */ return; } @@ -4133,11 +4002,10 @@ CreateOptsFile(int argc, char *argv[], char *fullprogname) /* * MaxLivePostmasterChildren * - * This reports the number of entries needed in per-child-process arrays - * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray). - * These arrays include regular backends, autovac workers, walsenders + * This reports the number of entries needed in the per-child-process array + * (PMChildFlags). It includes regular backends, autovac workers, walsenders * and background workers, but not special children nor dead_end children. - * This allows the arrays to have a fixed maximum size, to wit the same + * This allows the array to have a fixed maximum size, to wit the same * too-many-children limit enforced by canAcceptConnections(). The exact value * isn't too critical as long as it's more than MaxBackends. */ @@ -4206,9 +4074,6 @@ do_start_bgworker(RegisteredBgWorker *rw) ReportBackgroundWorkerPID(rw); /* add new worker to lists of backends */ dlist_push_head(&BackendList, &rw->rw_backend->elem); -#ifdef EXEC_BACKEND - ShmemBackendArrayAdd(rw->rw_backend); -#endif return true; } @@ -4276,20 +4141,6 @@ assign_backendlist_entry(RegisteredBgWorker *rw) return false; } - /* - * Compute the cancel key that will be assigned to this session. We - * probably don't need cancel keys for background workers, but we'd better - * have something random in the field to prevent unfriendly people from - * sending cancels to them. - */ - if (!RandomCancelKey(&MyCancelKey)) - { - ereport(LOG, - (errcode(ERRCODE_INTERNAL_ERROR), - errmsg("could not generate random cancel key"))); - return false; - } - bn = palloc_extended(sizeof(Backend), MCXT_ALLOC_NO_OOM); if (bn == NULL) { @@ -4299,7 +4150,6 @@ assign_backendlist_entry(RegisteredBgWorker *rw) return false; } - bn->cancel_key = MyCancelKey; bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot(); bn->bkend_type = BACKEND_TYPE_BGWORKER; bn->dead_end = false; @@ -4459,46 +4309,6 @@ PostmasterMarkPIDForWorkerNotify(int pid) return false; } -#ifdef EXEC_BACKEND - -Size -ShmemBackendArraySize(void) -{ - return mul_size(MaxLivePostmasterChildren(), sizeof(Backend)); -} - -void -ShmemBackendArrayAllocation(void) -{ - Size size = ShmemBackendArraySize(); - - ShmemBackendArray = (Backend *) ShmemAlloc(size); - /* Mark all slots as empty */ - memset(ShmemBackendArray, 0, size); -} - -static void -ShmemBackendArrayAdd(Backend *bn) -{ - /* The array slot corresponding to my PMChildSlot should be free */ - int i = bn->child_slot - 1; - - Assert(ShmemBackendArray[i].pid == 0); - ShmemBackendArray[i] = *bn; -} - -static void -ShmemBackendArrayRemove(Backend *bn) -{ - int i = bn->child_slot - 1; - - Assert(ShmemBackendArray[i].pid == bn->pid); - /* Mark the slot as empty */ - ShmemBackendArray[i].pid = 0; -} -#endif /* EXEC_BACKEND */ - - #ifdef WIN32 /* diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c index 2100150f01..c63384e7f3 100644 --- a/src/backend/storage/ipc/ipci.c +++ b/src/backend/storage/ipc/ipci.c @@ -152,9 +152,6 @@ CalculateShmemSize(int *num_semaphores) size = add_size(size, WaitEventCustomShmemSize()); size = add_size(size, InjectionPointShmemSize()); size = add_size(size, SlotSyncShmemSize()); -#ifdef EXEC_BACKEND - size = add_size(size, ShmemBackendArraySize()); -#endif /* include additional requested shmem from preload libraries */ size = add_size(size, total_addin_request); @@ -244,14 +241,6 @@ CreateSharedMemoryAndSemaphores(void) /* Initialize subsystems */ CreateOrAttachShmemStructs(); -#ifdef EXEC_BACKEND - - /* - * Alloc the win32 shared backend array - */ - ShmemBackendArrayAllocation(); -#endif - /* Initialize dynamic shared memory facilities. */ dsm_postmaster_startup(shim); diff --git a/src/backend/storage/ipc/procsignal.c b/src/backend/storage/ipc/procsignal.c index 4ed9cedcdd..2f35b39ae0 100644 --- a/src/backend/storage/ipc/procsignal.c +++ b/src/backend/storage/ipc/procsignal.c @@ -62,7 +62,10 @@ */ typedef struct { - volatile pid_t pss_pid; + pid_t pss_pid; + bool pss_cancel_key_valid; + int32 pss_cancel_key; + volatile sig_atomic_t pss_signalFlags[NUM_PROCSIGNALS]; pg_atomic_uint64 pss_barrierGeneration; pg_atomic_uint32 pss_barrierCheckMask; @@ -142,6 +145,8 @@ ProcSignalShmemInit(void) ProcSignalSlot *slot = &ProcSignal->psh_slot[i]; slot->pss_pid = 0; + slot->pss_cancel_key_valid = false; + slot->pss_cancel_key = 0; MemSet(slot->pss_signalFlags, 0, sizeof(slot->pss_signalFlags)); pg_atomic_init_u64(&slot->pss_barrierGeneration, PG_UINT64_MAX); pg_atomic_init_u32(&slot->pss_barrierCheckMask, 0); @@ -155,7 +160,7 @@ ProcSignalShmemInit(void) * Register the current process in the ProcSignal array */ void -ProcSignalInit(void) +ProcSignalInit(bool cancel_key_valid, int32 cancel_key) { ProcSignalSlot *slot; uint64 barrier_generation; @@ -189,9 +194,16 @@ ProcSignalInit(void) barrier_generation = pg_atomic_read_u64(&ProcSignal->psh_barrierGeneration); pg_atomic_write_u64(&slot->pss_barrierGeneration, barrier_generation); - pg_memory_barrier(); - /* Mark slot with my PID */ + slot->pss_cancel_key_valid = cancel_key_valid; + slot->pss_cancel_key = cancel_key; + + /* + * Mark slot with my PID. Issue a write barrier first, to make sure that any + * a concurrent reader cannot see the slot as used (= having a non-zero PID) + * before all the other fields have been initialized. + */ + pg_write_barrier(); slot->pss_pid = MyProcPid; /* Remember slot location for CheckProcSignal */ @@ -239,7 +251,14 @@ CleanupProcSignalState(int status, Datum arg) pg_atomic_write_u64(&slot->pss_barrierGeneration, PG_UINT64_MAX); ConditionVariableBroadcast(&slot->pss_barrierCV); + /* + * Mark the slot as unused. Use a memory barrier to ensure that the other fields + * are seen to have valid values for as long as the PID is valid. + */ slot->pss_pid = 0; + pg_write_barrier(); + slot->pss_cancel_key_valid = false; + slot->pss_cancel_key = 0; } /* @@ -678,3 +697,53 @@ procsignal_sigusr1_handler(SIGNAL_ARGS) SetLatch(MyLatch); } + +/* + * Send a query cancellation signal to backend. + * + * Note: This is called from a backend process before authentication. We + * cannot take LWLocks yet, but that's OK; we rely on atomic reads of the + * fields in the ProcSignal slots. + */ +void +SendCancelRequest(int backendPID, int32 cancelAuthCode) +{ + Assert(backendPID != 0); + + /* + * See if we have a matching backend. Reading the pss_pid and + * pss_cancel_key fields is racy, a backend might die and remove itself + * from the array at any time. The probability of the cancellation key + * matching wrong process is miniscule, however, so we can live with that. + * PIDs are reused too, so sending the signal based on PID is inherently + * racy anyway, although OS's avoid reusing PIDs too soon. + */ + for (int i = 0; i < NumProcSignalSlots; i++) + { + ProcSignalSlot *slot = &ProcSignal->psh_slot[i]; + + if (slot->pss_pid == backendPID) + { + pg_read_barrier(); + if (slot->pss_cancel_key_valid && slot->pss_cancel_key == cancelAuthCode) + { + /* Found a match; signal that backend to cancel current op */ + ereport(DEBUG2, + (errmsg_internal("processing cancel request: sending SIGINT to process %d", + backendPID))); + kill(backendPID, SIGINT); + } + else + /* Right PID, wrong key: no way, Jose */ + ereport(LOG, + (errmsg("wrong key in cancel request for process %d", + backendPID))); + return; + } + } + + /* No matching backend */ + ereport(LOG, + (errmsg("PID %d in cancel request did not match any process", + backendPID))); +} diff --git a/src/backend/tcop/backend_startup.c b/src/backend/tcop/backend_startup.c index a2f94b1050..57733185f8 100644 --- a/src/backend/tcop/backend_startup.c +++ b/src/backend/tcop/backend_startup.c @@ -29,6 +29,7 @@ #include "replication/walsender.h" #include "storage/fd.h" #include "storage/ipc.h" +#include "storage/procsignal.h" #include "storage/proc.h" #include "tcop/backend_startup.h" #include "tcop/tcopprot.h" @@ -525,6 +526,11 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done) if (proto == CANCEL_REQUEST_CODE) { + /* + * The client has sent a cancel request packet, not a normal + * start-a-new-connection packet. Perform the necessary processing. + * Nothing is sent back to the client. + */ CancelRequestPacket *canc; int backendPID; int32 cancelAuthCode; @@ -540,7 +546,8 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done) backendPID = (int) pg_ntoh32(canc->backendPID); cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode); - processCancelRequest(backendPID, cancelAuthCode); + if (backendPID != 0) + SendCancelRequest(backendPID, cancelAuthCode); /* Not really an error, but we don't want to proceed further */ return STATUS_ERROR; } diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c index e39c6804a7..3f9ed1ebf4 100644 --- a/src/backend/tcop/postgres.c +++ b/src/backend/tcop/postgres.c @@ -4225,6 +4225,26 @@ PostgresMain(const char *dbname, const char *username) /* We need to allow SIGINT, etc during the initial transaction */ sigprocmask(SIG_SETMASK, &UnBlockSig, NULL); + /* + * Generate a random cancel key, if this is a backend serving a + * connection. InitPostgres() advertised it in shared mmeory. + * + * We probably don't need cancel keys for non-backend processes, but we'd + * better have something random in the field to prevent unfriendly people + * from sending cancels to them. + */ + Assert(!MyCancelKeyValid); + if (whereToSendOutput == DestRemote) + { + if (!pg_strong_random(&MyCancelKey, sizeof(int32))) + { + ereport(ERROR, + (errcode(ERRCODE_INTERNAL_ERROR), + errmsg("could not generate random cancel key"))); + } + MyCancelKeyValid = true; + } + /* * General initialization. * @@ -4277,6 +4297,7 @@ PostgresMain(const char *dbname, const char *username) { StringInfoData buf; + Assert(MyCancelKeyValid); pq_beginmessage(&buf, PqMsg_BackendKeyData); pq_sendint32(&buf, (int32) MyProcPid); pq_sendint32(&buf, (int32) MyCancelKey); diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c index 927bccfbea..d8debd160e 100644 --- a/src/backend/utils/init/globals.c +++ b/src/backend/utils/init/globals.c @@ -48,7 +48,8 @@ pg_time_t MyStartTime; TimestampTz MyStartTimestamp; struct ClientSocket *MyClientSocket; struct Port *MyProcPort; -int32 MyCancelKey; +bool MyCancelKeyValid = false; +int32 MyCancelKey = 0; int MyPMChildSlot; /* diff --git a/src/backend/utils/init/postinit.c b/src/backend/utils/init/postinit.c index 0805398e24..1f2a16c96c 100644 --- a/src/backend/utils/init/postinit.c +++ b/src/backend/utils/init/postinit.c @@ -759,7 +759,7 @@ InitPostgres(const char *in_dbname, Oid dboid, */ SharedInvalBackendInit(false); - ProcSignalInit(); + ProcSignalInit(MyCancelKeyValid, MyCancelKey); /* * Also set up timeout handlers needed for backend operation. We need diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h index 90f9b21b25..ac16233b71 100644 --- a/src/include/miscadmin.h +++ b/src/include/miscadmin.h @@ -191,6 +191,7 @@ extern PGDLLIMPORT pg_time_t MyStartTime; extern PGDLLIMPORT TimestampTz MyStartTimestamp; extern PGDLLIMPORT struct Port *MyProcPort; extern PGDLLIMPORT struct Latch *MyLatch; +extern PGDLLIMPORT bool MyCancelKeyValid; extern PGDLLIMPORT int32 MyCancelKey; extern PGDLLIMPORT int MyPMChildSlot; diff --git a/src/include/postmaster/postmaster.h b/src/include/postmaster/postmaster.h index 9feb2e4de1..4cc59a662e 100644 --- a/src/include/postmaster/postmaster.h +++ b/src/include/postmaster/postmaster.h @@ -65,14 +65,9 @@ extern bool PostmasterMarkPIDForWorkerNotify(int); extern void processCancelRequest(int backendPID, int32 cancelAuthCode); -#ifdef EXEC_BACKEND -extern Size ShmemBackendArraySize(void); -extern void ShmemBackendArrayAllocation(void); - #ifdef WIN32 extern void pgwin32_register_deadchild_callback(HANDLE procHandle, DWORD procId); #endif -#endif /* defined in globals.c */ extern PGDLLIMPORT struct ClientSocket *MyClientSocket; diff --git a/src/include/storage/procsignal.h b/src/include/storage/procsignal.h index 7d290ea7d0..7b1fafe2c7 100644 --- a/src/include/storage/procsignal.h +++ b/src/include/storage/procsignal.h @@ -62,9 +62,10 @@ typedef enum extern Size ProcSignalShmemSize(void); extern void ProcSignalShmemInit(void); -extern void ProcSignalInit(void); +extern void ProcSignalInit(bool cancel_key_valid, int32 cancel_key); extern int SendProcSignal(pid_t pid, ProcSignalReason reason, ProcNumber procNumber); +extern void SendCancelRequest(int backendPID, int32 cancelAuthCode); extern uint64 EmitProcSignalBarrier(ProcSignalBarrierType type); extern void WaitForProcSignalBarrier(uint64 generation); -- 2.39.2
^ permalink raw reply [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-07-04 10:50  Jelte Fennema-Nio <postgres@jeltef.nl>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  0 siblings, 1 reply; 40+ messages in thread

From: Jelte Fennema-Nio @ 2024-07-04 10:50 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On Thu, 4 Jul 2024 at 12:35, Heikki Linnakangas <hlinnaka@iki.fi> wrote:
>
> On 04/07/2024 13:32, Heikki Linnakangas wrote:
> > Here's a new version of the first patch.
>
> Sorry, forgot attachment.

It seems you undid the following earlier change. Was that on purpose?
If not, did you undo any other earlier changes by accident?

> > +SendCancelRequest(int backendPID, int32 cancelAuthCode)
> >
> > I think this name of the function is quite confusing, it's not sending
> > a cancel request, it is processing one. It sends a SIGINT.
>
> Heh, well, it's sending the cancel request signal to the right backend,
> but I see your point. Renamed to ProcessCancelRequest.





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-07-04 11:35  Heikki Linnakangas <hlinnaka@iki.fi>
  parent: Jelte Fennema-Nio <postgres@jeltef.nl>
  0 siblings, 1 reply; 40+ messages in thread

From: Heikki Linnakangas @ 2024-07-04 11:35 UTC (permalink / raw)
  To: Jelte Fennema-Nio <postgres@jeltef.nl>; +Cc: pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On 04/07/2024 13:50, Jelte Fennema-Nio wrote:
> On Thu, 4 Jul 2024 at 12:35, Heikki Linnakangas <hlinnaka@iki.fi> wrote:
>>
>> On 04/07/2024 13:32, Heikki Linnakangas wrote:
>>> Here's a new version of the first patch.
>>
>> Sorry, forgot attachment.
> 
> It seems you undid the following earlier change. Was that on purpose?
> If not, did you undo any other earlier changes by accident?
> 
>>> +SendCancelRequest(int backendPID, int32 cancelAuthCode)
>>>
>>> I think this name of the function is quite confusing, it's not sending
>>> a cancel request, it is processing one. It sends a SIGINT.
>>
>> Heh, well, it's sending the cancel request signal to the right backend,
>> but I see your point. Renamed to ProcessCancelRequest.

Ah, I made that change as part of the second patch earlier, so I didn't 
consider it now.

I don't feel strongly about it, but I think SendCancelRequest() actually 
feels a little better, in procsignal.c. It's more consistent with the 
existing SendProcSignal() function.

There was indeed another change in the second patch that I missed:

> +				/* If we have setsid(), signal the backend's whole process group */
> +#ifdef HAVE_SETSID
> +				kill(-backendPID, SIGINT);
> +#else
>  				kill(backendPID, SIGINT);
> +#endif

I'm not sure that's really required, when sending SIGINT to a backend 
process. A backend process shouldn't have any child processes, and if it 
did, it's not clear what good SIGINT will do them. But I guess it makes 
sense to do it anyway, for consistency with pg_cancel_backend(), which 
also signals the whole process group.

-- 
Heikki Linnakangas
Neon (https://neon.tech)






^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-07-04 12:20  Jelte Fennema-Nio <postgres@jeltef.nl>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  1 sibling, 1 reply; 40+ messages in thread

From: Jelte Fennema-Nio @ 2024-07-04 12:20 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On Thu, 4 Jul 2024 at 12:32, Heikki Linnakangas <hlinnaka@iki.fi> wrote:
> We currently don't do any locking on the ProcSignal array. For query
> cancellations, that's good because a query cancel packet is processed
> without having a PGPROC entry, so we cannot take LWLocks. We could use
> spinlocks though. In this patch, I used memory barriers to ensure that
> we load/store the pid and the cancellation key in a sensible order, so
> that you cannot e.g. send a cancellation signal to a backend that's just
> starting up and hasn't advertised its cancellation key in ProcSignal
> yet. But I think this might be simpler and less error-prone by just
> adding a spinlock to each ProcSignal slot. That would also fix the
> existing race condition where we might set the pss_signalFlags flag for
> a slot, when the process concurrently terminates and the slot is reused
> for a different process. Because of that, we currently have this caveat:
> "... all the signals are such that no harm is done if they're mistakenly
> fired". With a spinlock, we could eliminate that race.

I think a spinlock would make this thing a whole concurrency stuff a
lot easier to reason about.

+   slot->pss_cancel_key_valid = false;
+   slot->pss_cancel_key = 0;

If no spinlock is added, I think these accesses should still be made
atomic writes. Otherwise data-races on those fields are still
possible, resulting in undefined behaviour. The memory barriers you
added don't prevent that afaict. With atomic operations there are
still race conditions, but no data-races.

Actually it seems like that same argument applies to the already
existing reading/writing of pss_pid: it's written/read using
non-atomic operations so data-races can occur and thus undefined
behaviour too.

-    volatile pid_t pss_pid;
+    pid_t        pss_pid;

Why remove the volatile modifier?





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-07-04 12:43  Tomas Vondra <tomas.vondra@enterprisedb.com>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  0 siblings, 1 reply; 40+ messages in thread

From: Tomas Vondra @ 2024-07-04 12:43 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; Jelte Fennema-Nio <postgres@jeltef.nl>; +Cc: pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Robert Haas <robertmhaas@gmail.com>

Hi,

I don't have any immediate feedback regarding this patch, but I'm
wondering about one thing related to cancellations - we talk cancelling
a query, but we really target a PID (or a particular backend, no matter
how we identify it).

I occasionally want to only cancel a particular query, but I don't think
that's really possible - the query may complete meanwhile, and the
backend may even get used for a different user connection (e.g. with a
connection pool)? Or am I missing something important?

Anyway, I wonder if making the cancellation key longer (or variable
length) might be useful for this too - it would allow including some
sort of optional "query ID" in the request, not just the PID. (Maybe
st_xact_start_timestamp would work?)

Obviously, that's not up to this patch, but it's somewhat related.



regards

-- 
Tomas Vondra
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-07-04 13:31  Jelte Fennema-Nio <postgres@jeltef.nl>
  parent: Tomas Vondra <tomas.vondra@enterprisedb.com>
  0 siblings, 0 replies; 40+ messages in thread

From: Jelte Fennema-Nio @ 2024-07-04 13:31 UTC (permalink / raw)
  To: Tomas Vondra <tomas.vondra@enterprisedb.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On Thu, 4 Jul 2024 at 14:43, Tomas Vondra <tomas.vondra@enterprisedb.com> wrote:
> I don't have any immediate feedback regarding this patch, but I'm
> wondering about one thing related to cancellations - we talk cancelling
> a query, but we really target a PID (or a particular backend, no matter
> how we identify it).
>
> I occasionally want to only cancel a particular query, but I don't think
> that's really possible - the query may complete meanwhile, and the
> backend may even get used for a different user connection (e.g. with a
> connection pool)? Or am I missing something important?

No, you're not missing anything. Having the target of the cancel
request be the backend instead of a specific query is really annoying
and can cause all kinds of race conditions. I had to redesign and
complicate the cancellation logic in PgBouncer significantly, to make
sure that one client could not cancel a connection from another client
anymore: https://github.com/pgbouncer/pgbouncer/pull/717

> Anyway, I wonder if making the cancellation key longer (or variable
> length) might be useful for this too - it would allow including some
> sort of optional "query ID" in the request, not just the PID. (Maybe
> st_xact_start_timestamp would work?)

Yeah, some query ID would be necessary. I think we'd want a dedicated
field for it though. Instead of encoding it in the secret. Getting the
xact_start_timestamp would require communication with the server to
get it, which you would like to avoid since the server might be
unresponsive. So I think a command counter that both sides keep track
of would be better. This counter could then be incremented after every
Query and Sync message.

> Obviously, that's not up to this patch, but it's somewhat related.

Yeah, let's postpone more discussion on this until we have the
currently proposed much simpler change in, which only changes the
secret length.





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-07-24 16:12  Heikki Linnakangas <hlinnaka@iki.fi>
  parent: Jelte Fennema-Nio <postgres@jeltef.nl>
  0 siblings, 1 reply; 40+ messages in thread

From: Heikki Linnakangas @ 2024-07-24 16:12 UTC (permalink / raw)
  To: Jelte Fennema-Nio <postgres@jeltef.nl>; +Cc: pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On 04/07/2024 15:20, Jelte Fennema-Nio wrote:
> On Thu, 4 Jul 2024 at 12:32, Heikki Linnakangas <hlinnaka@iki.fi> wrote:
>> We currently don't do any locking on the ProcSignal array. For query
>> cancellations, that's good because a query cancel packet is processed
>> without having a PGPROC entry, so we cannot take LWLocks. We could use
>> spinlocks though. In this patch, I used memory barriers to ensure that
>> we load/store the pid and the cancellation key in a sensible order, so
>> that you cannot e.g. send a cancellation signal to a backend that's just
>> starting up and hasn't advertised its cancellation key in ProcSignal
>> yet. But I think this might be simpler and less error-prone by just
>> adding a spinlock to each ProcSignal slot. That would also fix the
>> existing race condition where we might set the pss_signalFlags flag for
>> a slot, when the process concurrently terminates and the slot is reused
>> for a different process. Because of that, we currently have this caveat:
>> "... all the signals are such that no harm is done if they're mistakenly
>> fired". With a spinlock, we could eliminate that race.
> 
> I think a spinlock would make this thing a whole concurrency stuff a
> lot easier to reason about.
> 
> +   slot->pss_cancel_key_valid = false;
> +   slot->pss_cancel_key = 0;
> 
> If no spinlock is added, I think these accesses should still be made
> atomic writes. Otherwise data-races on those fields are still
> possible, resulting in undefined behaviour. The memory barriers you
> added don't prevent that afaict. With atomic operations there are
> still race conditions, but no data-races.
> 
> Actually it seems like that same argument applies to the already
> existing reading/writing of pss_pid: it's written/read using
> non-atomic operations so data-races can occur and thus undefined
> behaviour too.

Ok, here's a version with spinlocks.

I went back and forth on what exactly is protected by the spinlock. I 
kept the "volatile sig_atomic_t" type for pss_signalFlags, so that it 
can still be safely read without holding the spinlock in 
CheckProcSignal, but all the functions that set the flags now hold the 
spinlock. That removes the race condition that you might set the flag 
for wrong slot, if the target backend exits and the slot is recycled. 
The race condition was harmless and there were comments to note it, but 
it doesn't occur anymore with the spinlock.

(Note: Thomas's "Interrupts vs signals" patch will remove ps_signalFlags 
altogether. I'm looking forward to that.)

> -    volatile pid_t pss_pid;
> +    pid_t        pss_pid;
> 
> Why remove the volatile modifier?

Because I introduced a memory barrier to ensure the reads/writes of 
pss_pid become visible to other processes in right order. That makes the 
'volatile' unnecessary IIUC. With the spinlock, the point is moot however.

-- 
Heikki Linnakangas
Neon (https://neon.tech)

Attachments:

v4-0001-Move-cancel-key-generation-to-after-forking-the-b.patch (text/x-patch, 29.8K) download From 2e6035837c028abd3b645a8c038cac7179016eef Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas <heikki.linnakangas@iki.fi> Date: Wed, 24 Jul 2024 19:06:32 +0300 Subject: [PATCH v4 1/1] Move cancel key generation to after forking the backend Move responsibility of generating the cancel key to the backend process. The cancel key is now generated after forking, and the backend advertises it in the ProcSignal array. When a cancel request arrives, the backend handling it scans the ProcSignal array to find the target pid and cancel key. This is similar to how this previously worked in the EXEC_BACKEND case with the ShmemBackendArray, just reusing the ProcSignal array. One notable change is that we no longer generate cancellation keys for non-backend processes. We generated them before just to prevent a malicious user from canceling them, the keys for non-backend processes were never actually given to anyone. There is now an explicit flag indicating whether a process has a valid key or not. I wrote this originally in preparation for supporting longer cancel keys, but it's a nice cleanup on its own. Reviewed-by: Jelte Fennema-Nio Discussion: https://www.postgresql.org/message-id/508d0505-8b7a-4864-a681-e7e5edfe32aa@iki.fi --- src/backend/postmaster/auxprocess.c | 2 +- src/backend/postmaster/launch_backend.c | 6 - src/backend/postmaster/postmaster.c | 196 +----------------------- src/backend/storage/ipc/ipci.c | 11 -- src/backend/storage/ipc/procsignal.c | 172 ++++++++++++++++----- src/backend/tcop/backend_startup.c | 9 +- src/backend/tcop/postgres.c | 21 +++ src/backend/utils/init/globals.c | 3 +- src/backend/utils/init/postinit.c | 2 +- src/include/miscadmin.h | 1 + src/include/postmaster/postmaster.h | 9 -- src/include/storage/procsignal.h | 3 +- 12 files changed, 175 insertions(+), 260 deletions(-) diff --git a/src/backend/postmaster/auxprocess.c b/src/backend/postmaster/auxprocess.c index b21eae7136..74b8a00c94 100644 --- a/src/backend/postmaster/auxprocess.c +++ b/src/backend/postmaster/auxprocess.c @@ -71,7 +71,7 @@ AuxiliaryProcessMainCommon(void) BaseInit(); - ProcSignalInit(); + ProcSignalInit(false, 0); /* * Auxiliary processes don't run transactions, but they may need a diff --git a/src/backend/postmaster/launch_backend.c b/src/backend/postmaster/launch_backend.c index e9fc982787..f235248c54 100644 --- a/src/backend/postmaster/launch_backend.c +++ b/src/backend/postmaster/launch_backend.c @@ -93,7 +93,6 @@ typedef int InheritableSocket; typedef struct { char DataDir[MAXPGPATH]; - int32 MyCancelKey; int MyPMChildSlot; #ifndef WIN32 unsigned long UsedShmemSegID; @@ -103,7 +102,6 @@ typedef struct #endif void *UsedShmemSegAddr; slock_t *ShmemLock; - struct bkend *ShmemBackendArray; #ifndef HAVE_SPINLOCKS PGSemaphore *SpinlockSemaArray; #endif @@ -698,7 +696,6 @@ save_backend_variables(BackendParameters *param, ClientSocket *client_sock, strlcpy(param->DataDir, DataDir, MAXPGPATH); - param->MyCancelKey = MyCancelKey; param->MyPMChildSlot = MyPMChildSlot; #ifdef WIN32 @@ -708,7 +705,6 @@ save_backend_variables(BackendParameters *param, ClientSocket *client_sock, param->UsedShmemSegAddr = UsedShmemSegAddr; param->ShmemLock = ShmemLock; - param->ShmemBackendArray = ShmemBackendArray; #ifndef HAVE_SPINLOCKS param->SpinlockSemaArray = SpinlockSemaArray; @@ -957,7 +953,6 @@ restore_backend_variables(BackendParameters *param) SetDataDir(param->DataDir); - MyCancelKey = param->MyCancelKey; MyPMChildSlot = param->MyPMChildSlot; #ifdef WIN32 @@ -967,7 +962,6 @@ restore_backend_variables(BackendParameters *param) UsedShmemSegAddr = param->UsedShmemSegAddr; ShmemLock = param->ShmemLock; - ShmemBackendArray = param->ShmemBackendArray; #ifndef HAVE_SPINLOCKS SpinlockSemaArray = param->SpinlockSemaArray; diff --git a/src/backend/postmaster/postmaster.c b/src/backend/postmaster/postmaster.c index 6f974a8d21..02442a4b85 100644 --- a/src/backend/postmaster/postmaster.c +++ b/src/backend/postmaster/postmaster.c @@ -168,7 +168,6 @@ typedef struct bkend { pid_t pid; /* process id of backend */ - int32 cancel_key; /* cancel key for cancels for this backend */ int child_slot; /* PMChildSlot for this backend, if any */ int bkend_type; /* child process flavor, see above */ bool dead_end; /* is it going to send an error and quit? */ @@ -178,10 +177,6 @@ typedef struct bkend static dlist_head BackendList = DLIST_STATIC_INIT(BackendList); -#ifdef EXEC_BACKEND -NON_EXEC_STATIC Backend *ShmemBackendArray; -#endif - BackgroundWorker *MyBgworkerEntry = NULL; @@ -413,7 +408,6 @@ static int ServerLoop(void); static int BackendStartup(ClientSocket *client_sock); static void report_fork_failure_to_client(ClientSocket *client_sock, int errnum); static CAC_state canAcceptConnections(int backend_type); -static bool RandomCancelKey(int32 *cancel_key); static void signal_child(pid_t pid, int signal); static void sigquit_child(pid_t pid); static bool SignalSomeChildren(int signal, int target); @@ -444,8 +438,6 @@ static void MaybeStartSlotSyncWorker(void); (pmState == PM_RECOVERY || pmState == PM_HOT_STANDBY))) && \ PgArchCanRestart()) -#ifdef EXEC_BACKEND - #ifdef WIN32 #define WNOHANG 0 /* ignored, so any integer value will do */ @@ -462,10 +454,6 @@ typedef struct } win32_deadchild_waitinfo; #endif /* WIN32 */ -static void ShmemBackendArrayAdd(Backend *bn); -static void ShmemBackendArrayRemove(Backend *bn); -#endif /* EXEC_BACKEND */ - /* Macros to check exit status of a child process */ #define EXIT_STATUS_0(st) ((st) == 0) #define EXIT_STATUS_1(st) (WIFEXITED(st) && WEXITSTATUS(st) == 1) @@ -1826,65 +1814,6 @@ ServerLoop(void) } } -/* - * The client has sent a cancel request packet, not a normal - * start-a-new-connection packet. Perform the necessary processing. - * Nothing is sent back to the client. - */ -void -processCancelRequest(int backendPID, int32 cancelAuthCode) -{ - Backend *bp; - -#ifndef EXEC_BACKEND - dlist_iter iter; -#else - int i; -#endif - - /* - * See if we have a matching backend. In the EXEC_BACKEND case, we can no - * longer access the postmaster's own backend list, and must rely on the - * duplicate array in shared memory. - */ -#ifndef EXEC_BACKEND - dlist_foreach(iter, &BackendList) - { - bp = dlist_container(Backend, elem, iter.cur); -#else - for (i = MaxLivePostmasterChildren() - 1; i >= 0; i--) - { - bp = (Backend *) &ShmemBackendArray[i]; -#endif - if (bp->pid == backendPID) - { - if (bp->cancel_key == cancelAuthCode) - { - /* Found a match; signal that backend to cancel current op */ - ereport(DEBUG2, - (errmsg_internal("processing cancel request: sending SIGINT to process %d", - backendPID))); - signal_child(bp->pid, SIGINT); - } - else - /* Right PID, wrong key: no way, Jose */ - ereport(LOG, - (errmsg("wrong key in cancel request for process %d", - backendPID))); - return; - } -#ifndef EXEC_BACKEND /* make GNU Emacs 26.1 see brace balance */ - } -#else - } -#endif - - /* No matching backend */ - ereport(LOG, - (errmsg("PID %d in cancel request did not match any process", - backendPID))); -} - /* * canAcceptConnections --- check to see if database state allows connections * of the specified type. backend_type can be BACKEND_TYPE_NORMAL, @@ -2752,9 +2681,6 @@ CleanupBackgroundWorker(int pid, /* Get it out of the BackendList and clear out remaining data */ dlist_delete(&rw->rw_backend->elem); -#ifdef EXEC_BACKEND - ShmemBackendArrayRemove(rw->rw_backend); -#endif /* * It's possible that this background worker started some OTHER @@ -2840,9 +2766,6 @@ CleanupBackend(int pid, HandleChildCrash(pid, exitstatus, _("server process")); return; } -#ifdef EXEC_BACKEND - ShmemBackendArrayRemove(bp); -#endif } if (bp->bgworker_notify) { @@ -2910,9 +2833,6 @@ HandleChildCrash(int pid, int exitstatus, const char *procname) */ (void) ReleasePostmasterChildSlot(rw->rw_child_slot); dlist_delete(&rw->rw_backend->elem); -#ifdef EXEC_BACKEND - ShmemBackendArrayRemove(rw->rw_backend); -#endif pfree(rw->rw_backend); rw->rw_backend = NULL; rw->rw_pid = 0; @@ -2945,9 +2865,6 @@ HandleChildCrash(int pid, int exitstatus, const char *procname) if (!bp->dead_end) { (void) ReleasePostmasterChildSlot(bp->child_slot); -#ifdef EXEC_BACKEND - ShmemBackendArrayRemove(bp); -#endif } dlist_delete(iter.cur); pfree(bp); @@ -3560,24 +3477,9 @@ BackendStartup(ClientSocket *client_sock) return STATUS_ERROR; } - /* - * Compute the cancel key that will be assigned to this backend. The - * backend will have its own copy in the forked-off process' value of - * MyCancelKey, so that it can transmit the key to the frontend. - */ - if (!RandomCancelKey(&MyCancelKey)) - { - pfree(bn); - ereport(LOG, - (errcode(ERRCODE_INTERNAL_ERROR), - errmsg("could not generate random cancel key"))); - return STATUS_ERROR; - } - /* Pass down canAcceptConnections state */ startup_data.canAcceptConnections = canAcceptConnections(BACKEND_TYPE_NORMAL); bn->dead_end = (startup_data.canAcceptConnections != CAC_OK); - bn->cancel_key = MyCancelKey; /* * Unless it's a dead_end child, assign it a child slot number @@ -3621,11 +3523,6 @@ BackendStartup(ClientSocket *client_sock) bn->bkend_type = BACKEND_TYPE_NORMAL; /* Can change later to WALSND */ dlist_push_head(&BackendList, &bn->elem); -#ifdef EXEC_BACKEND - if (!bn->dead_end) - ShmemBackendArrayAdd(bn); -#endif - return STATUS_OK; } @@ -3861,15 +3758,6 @@ dummy_handler(SIGNAL_ARGS) { } -/* - * Generate a random cancel key. - */ -static bool -RandomCancelKey(int32 *cancel_key) -{ - return pg_strong_random(cancel_key, sizeof(int32)); -} - /* * Count up number of child processes of specified types (dead_end children * are always excluded). @@ -3970,25 +3858,9 @@ StartAutovacuumWorker(void) */ if (canAcceptConnections(BACKEND_TYPE_AUTOVAC) == CAC_OK) { - /* - * Compute the cancel key that will be assigned to this session. We - * probably don't need cancel keys for autovac workers, but we'd - * better have something random in the field to prevent unfriendly - * people from sending cancels to them. - */ - if (!RandomCancelKey(&MyCancelKey)) - { - ereport(LOG, - (errcode(ERRCODE_INTERNAL_ERROR), - errmsg("could not generate random cancel key"))); - return; - } - bn = (Backend *) palloc_extended(sizeof(Backend), MCXT_ALLOC_NO_OOM); if (bn) { - bn->cancel_key = MyCancelKey; - /* Autovac workers are not dead_end and need a child slot */ bn->dead_end = false; bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot(); @@ -3999,9 +3871,6 @@ StartAutovacuumWorker(void) { bn->bkend_type = BACKEND_TYPE_AUTOVAC; dlist_push_head(&BackendList, &bn->elem); -#ifdef EXEC_BACKEND - ShmemBackendArrayAdd(bn); -#endif /* all OK */ return; } @@ -4133,11 +4002,10 @@ CreateOptsFile(int argc, char *argv[], char *fullprogname) /* * MaxLivePostmasterChildren * - * This reports the number of entries needed in per-child-process arrays - * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray). - * These arrays include regular backends, autovac workers, walsenders + * This reports the number of entries needed in the per-child-process array + * (PMChildFlags). It includes regular backends, autovac workers, walsenders * and background workers, but not special children nor dead_end children. - * This allows the arrays to have a fixed maximum size, to wit the same + * This allows the array to have a fixed maximum size, to wit the same * too-many-children limit enforced by canAcceptConnections(). The exact value * isn't too critical as long as it's more than MaxBackends. */ @@ -4206,9 +4074,6 @@ do_start_bgworker(RegisteredBgWorker *rw) ReportBackgroundWorkerPID(rw); /* add new worker to lists of backends */ dlist_push_head(&BackendList, &rw->rw_backend->elem); -#ifdef EXEC_BACKEND - ShmemBackendArrayAdd(rw->rw_backend); -#endif return true; } @@ -4276,20 +4141,6 @@ assign_backendlist_entry(RegisteredBgWorker *rw) return false; } - /* - * Compute the cancel key that will be assigned to this session. We - * probably don't need cancel keys for background workers, but we'd better - * have something random in the field to prevent unfriendly people from - * sending cancels to them. - */ - if (!RandomCancelKey(&MyCancelKey)) - { - ereport(LOG, - (errcode(ERRCODE_INTERNAL_ERROR), - errmsg("could not generate random cancel key"))); - return false; - } - bn = palloc_extended(sizeof(Backend), MCXT_ALLOC_NO_OOM); if (bn == NULL) { @@ -4299,7 +4150,6 @@ assign_backendlist_entry(RegisteredBgWorker *rw) return false; } - bn->cancel_key = MyCancelKey; bn->child_slot = MyPMChildSlot = AssignPostmasterChildSlot(); bn->bkend_type = BACKEND_TYPE_BGWORKER; bn->dead_end = false; @@ -4459,46 +4309,6 @@ PostmasterMarkPIDForWorkerNotify(int pid) return false; } -#ifdef EXEC_BACKEND - -Size -ShmemBackendArraySize(void) -{ - return mul_size(MaxLivePostmasterChildren(), sizeof(Backend)); -} - -void -ShmemBackendArrayAllocation(void) -{ - Size size = ShmemBackendArraySize(); - - ShmemBackendArray = (Backend *) ShmemAlloc(size); - /* Mark all slots as empty */ - memset(ShmemBackendArray, 0, size); -} - -static void -ShmemBackendArrayAdd(Backend *bn) -{ - /* The array slot corresponding to my PMChildSlot should be free */ - int i = bn->child_slot - 1; - - Assert(ShmemBackendArray[i].pid == 0); - ShmemBackendArray[i] = *bn; -} - -static void -ShmemBackendArrayRemove(Backend *bn) -{ - int i = bn->child_slot - 1; - - Assert(ShmemBackendArray[i].pid == bn->pid); - /* Mark the slot as empty */ - ShmemBackendArray[i].pid = 0; -} -#endif /* EXEC_BACKEND */ - - #ifdef WIN32 /* diff --git a/src/backend/storage/ipc/ipci.c b/src/backend/storage/ipc/ipci.c index 2100150f01..c63384e7f3 100644 --- a/src/backend/storage/ipc/ipci.c +++ b/src/backend/storage/ipc/ipci.c @@ -152,9 +152,6 @@ CalculateShmemSize(int *num_semaphores) size = add_size(size, WaitEventCustomShmemSize()); size = add_size(size, InjectionPointShmemSize()); size = add_size(size, SlotSyncShmemSize()); -#ifdef EXEC_BACKEND - size = add_size(size, ShmemBackendArraySize()); -#endif /* include additional requested shmem from preload libraries */ size = add_size(size, total_addin_request); @@ -244,14 +241,6 @@ CreateSharedMemoryAndSemaphores(void) /* Initialize subsystems */ CreateOrAttachShmemStructs(); -#ifdef EXEC_BACKEND - - /* - * Alloc the win32 shared backend array - */ - ShmemBackendArrayAllocation(); -#endif - /* Initialize dynamic shared memory facilities. */ dsm_postmaster_startup(shim); diff --git a/src/backend/storage/ipc/procsignal.c b/src/backend/storage/ipc/procsignal.c index 4ed9cedcdd..1c346dcc8f 100644 --- a/src/backend/storage/ipc/procsignal.c +++ b/src/backend/storage/ipc/procsignal.c @@ -47,9 +47,9 @@ * know the ProcNumber of the process you're signaling. (We do support * signaling without ProcNumber, but it's a bit less efficient.) * - * The flags are actually declared as "volatile sig_atomic_t" for maximum - * portability. This should ensure that loads and stores of the flag - * values are atomic, allowing us to dispense with any explicit locking. + * The fields in each slot are protected by a spinlock, pss_mutex. pss_pid can + * also be read without holding the spinlock, as a quick preliminary check + * when searching for a particular PID in the array. * * pss_signalFlags are intended to be set in cases where we don't need to * keep track of whether or not the target process has handled the signal, @@ -62,8 +62,13 @@ */ typedef struct { - volatile pid_t pss_pid; + pg_atomic_uint32 pss_pid; + bool pss_cancel_key_valid; + int32 pss_cancel_key; volatile sig_atomic_t pss_signalFlags[NUM_PROCSIGNALS]; + slock_t pss_mutex; /* protects the above fields */ + + /* Barrier-related fields (not protected by pss_mutex) */ pg_atomic_uint64 pss_barrierGeneration; pg_atomic_uint32 pss_barrierCheckMask; ConditionVariable pss_barrierCV; @@ -141,7 +146,10 @@ ProcSignalShmemInit(void) { ProcSignalSlot *slot = &ProcSignal->psh_slot[i]; - slot->pss_pid = 0; + SpinLockInit(&slot->pss_mutex); + pg_atomic_init_u32(&slot->pss_pid, 0); + slot->pss_cancel_key_valid = false; + slot->pss_cancel_key = 0; MemSet(slot->pss_signalFlags, 0, sizeof(slot->pss_signalFlags)); pg_atomic_init_u64(&slot->pss_barrierGeneration, PG_UINT64_MAX); pg_atomic_init_u32(&slot->pss_barrierCheckMask, 0); @@ -155,7 +163,7 @@ ProcSignalShmemInit(void) * Register the current process in the ProcSignal array */ void -ProcSignalInit(void) +ProcSignalInit(bool cancel_key_valid, int32 cancel_key) { ProcSignalSlot *slot; uint64 barrier_generation; @@ -167,9 +175,13 @@ ProcSignalInit(void) slot = &ProcSignal->psh_slot[MyProcNumber]; /* sanity check */ - if (slot->pss_pid != 0) + SpinLockAcquire(&slot->pss_mutex); + if (pg_atomic_read_u32(&slot->pss_pid) != 0) + { + SpinLockRelease(&slot->pss_mutex); elog(LOG, "process %d taking over ProcSignal slot %d, but it's not empty", MyProcPid, MyProcNumber); + } /* Clear out any leftover signal reasons */ MemSet(slot->pss_signalFlags, 0, NUM_PROCSIGNALS * sizeof(sig_atomic_t)); @@ -189,10 +201,12 @@ ProcSignalInit(void) barrier_generation = pg_atomic_read_u64(&ProcSignal->psh_barrierGeneration); pg_atomic_write_u64(&slot->pss_barrierGeneration, barrier_generation); - pg_memory_barrier(); - /* Mark slot with my PID */ - slot->pss_pid = MyProcPid; + slot->pss_cancel_key_valid = cancel_key_valid; + slot->pss_cancel_key = cancel_key; + pg_atomic_write_u32(&slot->pss_pid, MyProcPid); + + SpinLockRelease(&slot->pss_mutex); /* Remember slot location for CheckProcSignal */ MyProcSignalSlot = slot; @@ -210,6 +224,7 @@ ProcSignalInit(void) static void CleanupProcSignalState(int status, Datum arg) { + pid_t old_pid; ProcSignalSlot *slot = MyProcSignalSlot; /* @@ -221,25 +236,34 @@ CleanupProcSignalState(int status, Datum arg) MyProcSignalSlot = NULL; /* sanity check */ - if (slot->pss_pid != MyProcPid) + SpinLockAcquire(&slot->pss_mutex); + old_pid = pg_atomic_read_u32(&slot->pss_pid); + if (old_pid != MyProcPid) { /* * don't ERROR here. We're exiting anyway, and don't want to get into * infinite loop trying to exit */ + SpinLockRelease(&slot->pss_mutex); elog(LOG, "process %d releasing ProcSignal slot %d, but it contains %d", - MyProcPid, (int) (slot - ProcSignal->psh_slot), (int) slot->pss_pid); + MyProcPid, (int) (slot - ProcSignal->psh_slot), (int) old_pid); return; /* XXX better to zero the slot anyway? */ } + /* Mark the slot as unused */ + pg_atomic_write_u32(&slot->pss_pid, 0); + slot->pss_cancel_key_valid = false; + slot->pss_cancel_key = 0; + /* * Make this slot look like it's absorbed all possible barriers, so that * no barrier waits block on it. */ pg_atomic_write_u64(&slot->pss_barrierGeneration, PG_UINT64_MAX); - ConditionVariableBroadcast(&slot->pss_barrierCV); - slot->pss_pid = 0; + SpinLockRelease(&slot->pss_mutex); + + ConditionVariableBroadcast(&slot->pss_barrierCV); } /* @@ -262,21 +286,16 @@ SendProcSignal(pid_t pid, ProcSignalReason reason, ProcNumber procNumber) { slot = &ProcSignal->psh_slot[procNumber]; - /* - * Note: Since there's no locking, it's possible that the target - * process detaches from shared memory and exits right after this - * test, before we set the flag and send signal. And the signal slot - * might even be recycled by a new process, so it's remotely possible - * that we set a flag for a wrong process. That's OK, all the signals - * are such that no harm is done if they're mistakenly fired. - */ - if (slot->pss_pid == pid) + SpinLockAcquire(&slot->pss_mutex); + if (pg_atomic_read_u32(&slot->pss_pid) == pid) { /* Atomically set the proper flag */ slot->pss_signalFlags[reason] = true; + SpinLockRelease(&slot->pss_mutex); /* Send signal */ return kill(pid, SIGUSR1); } + SpinLockRelease(&slot->pss_mutex); } else { @@ -293,14 +312,18 @@ SendProcSignal(pid_t pid, ProcSignalReason reason, ProcNumber procNumber) { slot = &ProcSignal->psh_slot[i]; - if (slot->pss_pid == pid) + if (pg_atomic_read_u32(&slot->pss_pid) == pid) { - /* the above note about race conditions applies here too */ - - /* Atomically set the proper flag */ - slot->pss_signalFlags[reason] = true; - /* Send signal */ - return kill(pid, SIGUSR1); + SpinLockAcquire(&slot->pss_mutex); + if (pg_atomic_read_u32(&slot->pss_pid) == pid) + { + /* Atomically set the proper flag */ + slot->pss_signalFlags[reason] = true; + SpinLockRelease(&slot->pss_mutex); + /* Send signal */ + return kill(pid, SIGUSR1); + } + SpinLockRelease(&slot->pss_mutex); } } } @@ -368,13 +391,20 @@ EmitProcSignalBarrier(ProcSignalBarrierType type) for (int i = NumProcSignalSlots - 1; i >= 0; i--) { volatile ProcSignalSlot *slot = &ProcSignal->psh_slot[i]; - pid_t pid = slot->pss_pid; + pid_t pid = pg_atomic_read_u32(&slot->pss_pid); if (pid != 0) { - /* see SendProcSignal for details */ - slot->pss_signalFlags[PROCSIG_BARRIER] = true; - kill(pid, SIGUSR1); + SpinLockAcquire(&slot->pss_mutex); + pid = pg_atomic_read_u32(&slot->pss_pid); + if (pid != 0) + { + /* see SendProcSignal for details */ + slot->pss_signalFlags[PROCSIG_BARRIER] = true; + SpinLockRelease(&slot->pss_mutex); + kill(pid, SIGUSR1); + } + SpinLockRelease(&slot->pss_mutex); } } @@ -414,7 +444,7 @@ WaitForProcSignalBarrier(uint64 generation) WAIT_EVENT_PROC_SIGNAL_BARRIER)) ereport(LOG, (errmsg("still waiting for backend with PID %d to accept ProcSignalBarrier", - (int) slot->pss_pid))); + (int) pg_atomic_read_u32(&slot->pss_pid)))); oldval = pg_atomic_read_u64(&slot->pss_barrierGeneration); } ConditionVariableCancelSleep(); @@ -617,7 +647,11 @@ CheckProcSignal(ProcSignalReason reason) if (slot != NULL) { - /* Careful here --- don't clear flag if we haven't seen it set */ + /* + * Careful here --- don't clear flag if we haven't seen it set. + * pss_signalFlags is of type "volatile sig_atomic_t" to allow us to + * read it here safely, without holding the spinlock. + */ if (slot->pss_signalFlags[reason]) { slot->pss_signalFlags[reason] = false; @@ -678,3 +712,69 @@ procsignal_sigusr1_handler(SIGNAL_ARGS) SetLatch(MyLatch); } + +/* + * Send a query cancellation signal to backend. + * + * Note: This is called from a backend process before authentication. We + * cannot take LWLocks yet, but that's OK; we rely on atomic reads of the + * fields in the ProcSignal slots. + */ +void +SendCancelRequest(int backendPID, int32 cancelAuthCode) +{ + Assert(backendPID != 0); + + /* + * See if we have a matching backend. Reading the pss_pid and + * pss_cancel_key fields is racy, a backend might die and remove itself + * from the array at any time. The probability of the cancellation key + * matching wrong process is miniscule, however, so we can live with that. + * PIDs are reused too, so sending the signal based on PID is inherently + * racy anyway, although OS's avoid reusing PIDs too soon. + */ + for (int i = 0; i < NumProcSignalSlots; i++) + { + ProcSignalSlot *slot = &ProcSignal->psh_slot[i]; + bool match; + + if (pg_atomic_read_u32(&slot->pss_pid) != backendPID) + continue; + + /* Acquire the spinlock and re-check */ + SpinLockAcquire(&slot->pss_mutex); + if (pg_atomic_read_u32(&slot->pss_pid) != backendPID) + { + SpinLockRelease(&slot->pss_mutex); + continue; + } + else + { + match = slot->pss_cancel_key_valid && slot->pss_cancel_key == cancelAuthCode; + + SpinLockRelease(&slot->pss_mutex); + + if (match) + { + /* Found a match; signal that backend to cancel current op */ + ereport(DEBUG2, + (errmsg_internal("processing cancel request: sending SIGINT to process %d", + backendPID))); + kill(backendPID, SIGINT); + } + else + { + /* Right PID, wrong key: no way, Jose */ + ereport(LOG, + (errmsg("wrong key in cancel request for process %d", + backendPID))); + } + return; + } + } + + /* No matching backend */ + ereport(LOG, + (errmsg("PID %d in cancel request did not match any process", + backendPID))); +} diff --git a/src/backend/tcop/backend_startup.c b/src/backend/tcop/backend_startup.c index a2f94b1050..57733185f8 100644 --- a/src/backend/tcop/backend_startup.c +++ b/src/backend/tcop/backend_startup.c @@ -29,6 +29,7 @@ #include "replication/walsender.h" #include "storage/fd.h" #include "storage/ipc.h" +#include "storage/procsignal.h" #include "storage/proc.h" #include "tcop/backend_startup.h" #include "tcop/tcopprot.h" @@ -525,6 +526,11 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done) if (proto == CANCEL_REQUEST_CODE) { + /* + * The client has sent a cancel request packet, not a normal + * start-a-new-connection packet. Perform the necessary processing. + * Nothing is sent back to the client. + */ CancelRequestPacket *canc; int backendPID; int32 cancelAuthCode; @@ -540,7 +546,8 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done) backendPID = (int) pg_ntoh32(canc->backendPID); cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode); - processCancelRequest(backendPID, cancelAuthCode); + if (backendPID != 0) + SendCancelRequest(backendPID, cancelAuthCode); /* Not really an error, but we don't want to proceed further */ return STATUS_ERROR; } diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c index ea517f4b9b..f4f5e56132 100644 --- a/src/backend/tcop/postgres.c +++ b/src/backend/tcop/postgres.c @@ -4224,6 +4224,26 @@ PostgresMain(const char *dbname, const char *username) /* We need to allow SIGINT, etc during the initial transaction */ sigprocmask(SIG_SETMASK, &UnBlockSig, NULL); + /* + * Generate a random cancel key, if this is a backend serving a + * connection. InitPostgres() will advertise it in shared memory. + * + * We probably don't need cancel keys for non-backend processes, but we'd + * better have something random in the field to prevent unfriendly people + * from sending cancels to them. + */ + Assert(!MyCancelKeyValid); + if (whereToSendOutput == DestRemote) + { + if (!pg_strong_random(&MyCancelKey, sizeof(int32))) + { + ereport(ERROR, + (errcode(ERRCODE_INTERNAL_ERROR), + errmsg("could not generate random cancel key"))); + } + MyCancelKeyValid = true; + } + /* * General initialization. * @@ -4276,6 +4296,7 @@ PostgresMain(const char *dbname, const char *username) { StringInfoData buf; + Assert(MyCancelKeyValid); pq_beginmessage(&buf, PqMsg_BackendKeyData); pq_sendint32(&buf, (int32) MyProcPid); pq_sendint32(&buf, (int32) MyCancelKey); diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c index 927bccfbea..d8debd160e 100644 --- a/src/backend/utils/init/globals.c +++ b/src/backend/utils/init/globals.c @@ -48,7 +48,8 @@ pg_time_t MyStartTime; TimestampTz MyStartTimestamp; struct ClientSocket *MyClientSocket; struct Port *MyProcPort; -int32 MyCancelKey; +bool MyCancelKeyValid = false; +int32 MyCancelKey = 0; int MyPMChildSlot; /* diff --git a/src/backend/utils/init/postinit.c b/src/backend/utils/init/postinit.c index 25867c8bd5..4d3fe43b08 100644 --- a/src/backend/utils/init/postinit.c +++ b/src/backend/utils/init/postinit.c @@ -716,7 +716,7 @@ InitPostgres(const char *in_dbname, Oid dboid, */ SharedInvalBackendInit(false); - ProcSignalInit(); + ProcSignalInit(MyCancelKeyValid, MyCancelKey); /* * Also set up timeout handlers needed for backend operation. We need diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h index 90f9b21b25..ac16233b71 100644 --- a/src/include/miscadmin.h +++ b/src/include/miscadmin.h @@ -191,6 +191,7 @@ extern PGDLLIMPORT pg_time_t MyStartTime; extern PGDLLIMPORT TimestampTz MyStartTimestamp; extern PGDLLIMPORT struct Port *MyProcPort; extern PGDLLIMPORT struct Latch *MyLatch; +extern PGDLLIMPORT bool MyCancelKeyValid; extern PGDLLIMPORT int32 MyCancelKey; extern PGDLLIMPORT int MyPMChildSlot; diff --git a/src/include/postmaster/postmaster.h b/src/include/postmaster/postmaster.h index d19e103937..4cc59a662e 100644 --- a/src/include/postmaster/postmaster.h +++ b/src/include/postmaster/postmaster.h @@ -36,10 +36,6 @@ extern PGDLLIMPORT bool remove_temp_files_after_crash; extern PGDLLIMPORT bool send_abort_for_crash; extern PGDLLIMPORT bool send_abort_for_kill; -#ifdef EXEC_BACKEND -extern struct bkend *ShmemBackendArray; -#endif - #ifdef WIN32 extern PGDLLIMPORT HANDLE PostmasterHandle; #else @@ -69,14 +65,9 @@ extern bool PostmasterMarkPIDForWorkerNotify(int); extern void processCancelRequest(int backendPID, int32 cancelAuthCode); -#ifdef EXEC_BACKEND -extern Size ShmemBackendArraySize(void); -extern void ShmemBackendArrayAllocation(void); - #ifdef WIN32 extern void pgwin32_register_deadchild_callback(HANDLE procHandle, DWORD procId); #endif -#endif /* defined in globals.c */ extern PGDLLIMPORT struct ClientSocket *MyClientSocket; diff --git a/src/include/storage/procsignal.h b/src/include/storage/procsignal.h index 7d290ea7d0..7b1fafe2c7 100644 --- a/src/include/storage/procsignal.h +++ b/src/include/storage/procsignal.h @@ -62,9 +62,10 @@ typedef enum extern Size ProcSignalShmemSize(void); extern void ProcSignalShmemInit(void); -extern void ProcSignalInit(void); +extern void ProcSignalInit(bool cancel_key_valid, int32 cancel_key); extern int SendProcSignal(pid_t pid, ProcSignalReason reason, ProcNumber procNumber); +extern void SendCancelRequest(int backendPID, int32 cancelAuthCode); extern uint64 EmitProcSignalBarrier(ProcSignalBarrierType type); extern void WaitForProcSignalBarrier(uint64 generation); -- 2.39.2
^ permalink raw reply [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-07-29 13:19  Heikki Linnakangas <hlinnaka@iki.fi>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  0 siblings, 2 replies; 40+ messages in thread

From: Heikki Linnakangas @ 2024-07-29 13:19 UTC (permalink / raw)
  To: Jelte Fennema-Nio <postgres@jeltef.nl>; +Cc: pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On 24/07/2024 19:12, Heikki Linnakangas wrote:
> On 04/07/2024 15:20, Jelte Fennema-Nio wrote:
>> On Thu, 4 Jul 2024 at 12:32, Heikki Linnakangas <hlinnaka@iki.fi> wrote:
>>> We currently don't do any locking on the ProcSignal array. For query
>>> cancellations, that's good because a query cancel packet is processed
>>> without having a PGPROC entry, so we cannot take LWLocks. We could use
>>> spinlocks though. In this patch, I used memory barriers to ensure that
>>> we load/store the pid and the cancellation key in a sensible order, so
>>> that you cannot e.g. send a cancellation signal to a backend that's just
>>> starting up and hasn't advertised its cancellation key in ProcSignal
>>> yet. But I think this might be simpler and less error-prone by just
>>> adding a spinlock to each ProcSignal slot. That would also fix the
>>> existing race condition where we might set the pss_signalFlags flag for
>>> a slot, when the process concurrently terminates and the slot is reused
>>> for a different process. Because of that, we currently have this caveat:
>>> "... all the signals are such that no harm is done if they're mistakenly
>>> fired". With a spinlock, we could eliminate that race.
>>
>> I think a spinlock would make this thing a whole concurrency stuff a
>> lot easier to reason about.
>>
>> +   slot->pss_cancel_key_valid = false;
>> +   slot->pss_cancel_key = 0;
>>
>> If no spinlock is added, I think these accesses should still be made
>> atomic writes. Otherwise data-races on those fields are still
>> possible, resulting in undefined behaviour. The memory barriers you
>> added don't prevent that afaict. With atomic operations there are
>> still race conditions, but no data-races.
>>
>> Actually it seems like that same argument applies to the already
>> existing reading/writing of pss_pid: it's written/read using
>> non-atomic operations so data-races can occur and thus undefined
>> behaviour too.
> 
> Ok, here's a version with spinlocks.
> 
> I went back and forth on what exactly is protected by the spinlock. I
> kept the "volatile sig_atomic_t" type for pss_signalFlags, so that it
> can still be safely read without holding the spinlock in
> CheckProcSignal, but all the functions that set the flags now hold the
> spinlock. That removes the race condition that you might set the flag
> for wrong slot, if the target backend exits and the slot is recycled.
> The race condition was harmless and there were comments to note it, but
> it doesn't occur anymore with the spinlock.
> 
> (Note: Thomas's "Interrupts vs signals" patch will remove ps_signalFlags
> altogether. I'm looking forward to that.)
> 
>> -    volatile pid_t pss_pid;
>> +    pid_t        pss_pid;
>>
>> Why remove the volatile modifier?
> 
> Because I introduced a memory barrier to ensure the reads/writes of
> pss_pid become visible to other processes in right order. That makes the
> 'volatile' unnecessary IIUC. With the spinlock, the point is moot however.

I:
- fixed a few comments,
- fixed a straightforward failure with EXEC_BACKEND (ProcSignal needs to 
be passed down in BackendParameters now),
- put back the snippet to signal the whole process group if supported, 
which you pointed out earlier

and committed this refactoring patch.

Thanks for the review!

-- 
Heikki Linnakangas
Neon (https://neon.tech)






^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-08-12 11:45  Thomas Munro <thomas.munro@gmail.com>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  1 sibling, 0 replies; 40+ messages in thread

From: Thomas Munro @ 2024-08-12 11:45 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Jelte Fennema-Nio <postgres@jeltef.nl>; pgsql-hackers; Robert Haas <robertmhaas@gmail.com>

+     * See if we have a matching backend. Reading the pss_pid and
+     * pss_cancel_key fields is racy, a backend might die and remove itself
+     * from the array at any time.  The probability of the cancellation key
+     * matching wrong process is miniscule, however, so we can live with that.
+     * PIDs are reused too, so sending the signal based on PID is inherently
+     * racy anyway, although OS's avoid reusing PIDs too soon.

Just BTW, we know that Windows sometimes recycles PIDs very soon,
sometimes even immediately, to the surprise of us Unix hackers.  It can
make for some very confusing build farm animal logs.  My patch will
propose to change that particular thing to proc numbers anyway so I'm
not asking for a change here, I just didn't want that assumption to go
un-footnoted.  I suppose that's actually (another) good reason to want
to widen the cancellation key, so that we don't have to worry about
proc number allocation order being less protective than traditional
Unix PID allocation...





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-08-15 17:13  Heikki Linnakangas <hlinnaka@iki.fi>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  1 sibling, 2 replies; 40+ messages in thread

From: Heikki Linnakangas @ 2024-08-15 17:13 UTC (permalink / raw)
  To: Jelte Fennema-Nio <postgres@jeltef.nl>; +Cc: pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Robert Haas <robertmhaas@gmail.com>

I'm back to working on the main patch here, to make cancellation keys 
longer. New rebased version attached, with all the FIXMEs and TODOs from 
the earlier version fixed. There was a lot of bitrot, too.

The first patch now introduces timingsafe_bcmp(), a function borrowed 
from OpenBSD to perform a constant-time comparison. There's a configure 
check to use the function from the OS if it's available, and includes a 
copy of OpenBSD's implementation otherwise. Similar functions exist with 
different names in OpenSSL (CRYPTO_memcmp) and NetBSD 
(consttime_memequal), but it's a pretty simple function so I don't think 
we need to work too hard to pick up those other native implementations.

I used it for checking if the cancellation key matches, now that it's 
not a single word anymore. It feels paranoid to worry about timing 
attacks here, a few instructions is unlikely to give enough signal to an 
attacker and query cancellation is not a very interesting target anyway. 
But better safe than sorry. You can still get information about whether 
a backend with the given PID exists at all, the constant-time comparison 
only applies to comparing the key. We probably should be using this in 
some other places in the backend, but I haven't gone around looking for 
them.

> Hmm, looking at the current code, I do agree that not introducing a
> new message would simplify both client and server implementation. Now
> clients need to do different things depending on if the server
> supports 3.1 or 3.0 (sending CancelRequestExtended instead of
> CancelRequest and having to parse BackendKeyData differently). And I
> also agree that the extra length field doesn't add much in regards to
> sanity checking (for the CancelRequest and BackendKeyData message
> types at least). So, sorry for the back and forth on this, but I now
> agree with you that we should not add the length field. I think one
> reason I didn't see the benefit before was because the initial patch
> 0002 was still introducing a CancelRequestExtended message type. If we
> can get rid of this message type by not adding a length, then I think
> that's worth losing the sanity checking.

Ok, I went back to the original scheme that just redefines the secret 
key in the CancelRequest message to be variable length, with the length 
deduced from the message length.

>> We could teach
>> libpq to disconnect and reconnect with minor protocol version 3.0, if
>> connecting with 3.1 fails, but IMHO it's better to not complicate this
>> and accept the break in backwards-compatibility.
> 
> Yeah, implementing automatic reconnection seems a bit overkill to me
> too. But it might be nice to add a connection option that causes libpq
> to use protocol 3.0. Having to install an old libpq to connect to an
> old server seems quite annoying.

Added a "protocol_version" libpq option for that. It defaults to "auto", 
but you can set it to "3.1" or "3.0" to force the version. It makes it 
easier to test that the backwards-compatibility works, too.

> Especially since I think that many other types of servers that
> implement the postgres protocol have not implemented the minor
> version negotiation.
> 
> I at least know PgBouncer[1] and pgcat[2] have not, but probably
> other server implementations like CockroachDB and Google Spanner have
> this problem too.
Good point.

-- 
Heikki Linnakangas
Neon (https://neon.tech)

Attachments: download all (2 files, .tar.gz)

v5-0001-Add-timingsafe_bcmp-for-constant-time-memory-comp.patch (text/x-patch, 5.1K) download From 5fb2a442efca75dbc384bafee486b090f91806ba Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas <heikki.linnakangas@iki.fi> Date: Thu, 15 Aug 2024 15:49:46 +0300 Subject: [PATCH v5 1/2] Add timingsafe_bcmp(), for constant-time memory comparison timingsafe_bcmp() should be used instead of memcmp() or a naive for-loop, when comparing passwords or secret tokens, to avoid leaking information about the secret token by timing. This commit just introduces the function but does not change any existing code to use it yet. --- configure | 23 +++++++++++++++++++++++ configure.ac | 3 ++- meson.build | 2 ++ src/include/port.h | 4 ++++ src/port/meson.build | 1 + src/port/timingsafe_bcmp.c | 35 +++++++++++++++++++++++++++++++++++ 6 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 src/port/timingsafe_bcmp.c diff --git a/configure b/configure index 2abbeb2794..1fd832bd5b 100755 --- a/configure +++ b/configure @@ -15758,6 +15758,16 @@ fi cat >>confdefs.h <<_ACEOF #define HAVE_DECL_STRSEP $ac_have_decl _ACEOF +ac_fn_c_check_decl "$LINENO" "timingsafe_bcmp" "ac_cv_have_decl_timingsafe_bcmp" "$ac_includes_default" +if test "x$ac_cv_have_decl_timingsafe_bcmp" = xyes; then : + ac_have_decl=1 +else + ac_have_decl=0 +fi + +cat >>confdefs.h <<_ACEOF +#define HAVE_DECL_TIMINGSAFE_BCMP $ac_have_decl +_ACEOF # We can't use AC_CHECK_FUNCS to detect these functions, because it @@ -15918,6 +15928,19 @@ esac fi +ac_fn_c_check_func "$LINENO" "timingsafe_bcmp" "ac_cv_func_timingsafe_bcmp" +if test "x$ac_cv_func_timingsafe_bcmp" = xyes; then : + $as_echo "#define HAVE_TIMINGSAFE_BCMP 1" >>confdefs.h + +else + case " $LIBOBJS " in + *" timingsafe_bcmp.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS timingsafe_bcmp.$ac_objext" + ;; +esac + +fi + ac_fn_c_check_func "$LINENO" "pthread_barrier_wait" "ac_cv_func_pthread_barrier_wait" diff --git a/configure.ac b/configure.ac index c46ed2c591..f9ddcb0ef0 100644 --- a/configure.ac +++ b/configure.ac @@ -1777,7 +1777,7 @@ AC_CHECK_DECLS(posix_fadvise, [], [], [#include <fcntl.h>]) ]) # fi AC_CHECK_DECLS(fdatasync, [], [], [#include <unistd.h>]) -AC_CHECK_DECLS([strlcat, strlcpy, strnlen, strsep]) +AC_CHECK_DECLS([strlcat, strlcpy, strnlen, strsep, timingsafe_bcmp]) # We can't use AC_CHECK_FUNCS to detect these functions, because it # won't handle deployment target restrictions on macOS @@ -1797,6 +1797,7 @@ AC_REPLACE_FUNCS(m4_normalize([ strlcpy strnlen strsep + timingsafe_bcmp ])) AC_REPLACE_FUNCS(pthread_barrier_wait) diff --git a/meson.build b/meson.build index cd711c6d01..f327424332 100644 --- a/meson.build +++ b/meson.build @@ -2427,6 +2427,7 @@ decl_checks = [ ['strlcpy', 'string.h'], ['strnlen', 'string.h'], ['strsep', 'string.h'], + ['timingsafe_bcmp', 'string.h'], ] # Need to check for function declarations for these functions, because @@ -2699,6 +2700,7 @@ func_checks = [ ['strsignal'], ['sync_file_range'], ['syncfs'], + ['timingsafe_bcmp'], ['uselocale'], ['wcstombs_l'], ] diff --git a/src/include/port.h b/src/include/port.h index c740005267..0b0f03afe2 100644 --- a/src/include/port.h +++ b/src/include/port.h @@ -436,6 +436,10 @@ extern size_t strnlen(const char *str, size_t maxlen); extern char *strsep(char **stringp, const char *delim); #endif +#if !HAVE_DECL_TIMINGSAFE_BCMP +extern int timingsafe_bcmp(const void *b1, const void *b2, size_t len); +#endif + /* port/user.c */ #ifndef WIN32 extern bool pg_get_user_name(uid_t user_id, char *buffer, size_t buflen); diff --git a/src/port/meson.build b/src/port/meson.build index ff54b7b53e..ecce6ab8ef 100644 --- a/src/port/meson.build +++ b/src/port/meson.build @@ -71,6 +71,7 @@ replace_funcs_neg = [ ['strlcpy'], ['strnlen'], ['strsep'], + ['timingsafe_bcmp'], ] if host_system != 'windows' diff --git a/src/port/timingsafe_bcmp.c b/src/port/timingsafe_bcmp.c new file mode 100644 index 0000000000..2d197481a7 --- /dev/null +++ b/src/port/timingsafe_bcmp.c @@ -0,0 +1,35 @@ +/* + * src/port/timingsafe_bcmp.c + * + * $OpenBSD: timingsafe_bcmp.c,v 1.3 2015/08/31 02:53:57 guenther Exp $ + */ + +/* + * Copyright (c) 2010 Damien Miller. All rights reserved. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include "c.h" + +int +timingsafe_bcmp(const void *b1, const void *b2, size_t n) +{ + const unsigned char *p1 = b1, + *p2 = b2; + int ret = 0; + + for (; n > 0; n--) + ret |= *p1++ ^ *p2++; + return (ret != 0); +} -- 2.39.2
v5-0002-Make-cancel-request-keys-longer-bump-minor-protoc.patch (text/x-patch, 35.8K) download From e313fe11d0b3253edbdc79212c4e055473ae0d39 Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas <heikki.linnakangas@iki.fi> Date: Thu, 15 Aug 2024 19:49:29 +0300 Subject: [PATCH v5 2/2] Make cancel request keys longer, bump minor protocol version Currently, cancel request key is 32-bit token, which isn't very much entropy. If you want to cancel another session's query, you can brute-force it. In most environments, an unauthorized cancellation of a query isn't very serious, but it nevertheless would be nice to have more protection from it. Hence make the key longer, to make it harder to guess. The new longer key length is not hardcoded in the protocol anymore, the client is expected to deal with variable length keys, up to some reasonable upper limit (TODO: document the maximum). This flexibility allows e.g. a connection pooler to add more information to the cancel key, which might be useful for finding the connection. This bumps the protocol version from 3.0 to 3.1. The server and libpq still both understand version 3.0, for interoperability with old client and server versions. If an old client connects to the server, the server falls back to generate a short 32-bit token like before. Note that the minor protocol version negotiation was added to the server in version 9.3. Connecting to PostgreSQL 9.2 with new libpq will fail with "unsupported frontend protocol" error, unless you force the old protocol to be used with "protocol_version=3.0". If we wanted to stay compatible, we could teach libpq to reconnect with protocol version 3.0 automatically, but I don't think that's necessary. Reviewed-by: Jelte Fennema-Nio Discussion: https://www.postgresql.org/message-id/508d0505-8b7a-4864-a681-e7e5edfe32aa@iki.fi --- doc/src/sgml/libpq.sgml | 12 +++ doc/src/sgml/protocol.sgml | 62 ++++++++++-- src/backend/storage/ipc/procsignal.c | 23 ++--- src/backend/tcop/backend_startup.c | 55 ++++++----- src/backend/tcop/postgres.c | 24 ++++- src/backend/utils/init/globals.c | 5 +- src/backend/utils/init/postinit.c | 2 +- src/include/libpq/pqcomm.h | 9 +- src/include/miscadmin.h | 4 +- src/include/storage/procsignal.h | 14 ++- src/interfaces/libpq/fe-cancel.c | 95 +++++++++++++++---- src/interfaces/libpq/fe-connect.c | 56 ++++++++--- src/interfaces/libpq/fe-protocol3.c | 91 ++++++++++++++++-- src/interfaces/libpq/libpq-int.h | 10 +- .../libpq_pipeline/t/001_libpq_pipeline.pl | 8 ++ src/tools/pgindent/typedefs.list | 1 + 16 files changed, 375 insertions(+), 96 deletions(-) diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 068ee60771..9b0a858282 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -2335,6 +2335,18 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> + <varlistentry id="libpq-connect-protocol-version" xreflabel="protocol_version"> + <term><literal>protocol_version</literal></term> + <listitem> + <para> + FE/BE protocol version to use. The default is "auto", to use the + highest version supported by both the client and the server. To + connect to old <productname>PostgreSQL</productname> servers versions + 9.2 and below, use "3.0". + </para> + </listitem> + </varlistentry> + </variablelist> </para> </sect2> diff --git a/doc/src/sgml/protocol.sgml b/doc/src/sgml/protocol.sgml index 79cd599692..aa8ddd0638 100644 --- a/doc/src/sgml/protocol.sgml +++ b/doc/src/sgml/protocol.sgml @@ -18,10 +18,16 @@ </para> <para> - This document describes version 3.0 of the protocol, implemented in + This document describes version 3.1 of the protocol, introduced in + <productname>PostgreSQL</productname> version 17. The server is compatible with + protocol version 3.0, implemented in <productname>PostgreSQL</productname> 7.4 and later. For descriptions - of the earlier protocol versions, see previous releases of the - <productname>PostgreSQL</productname> documentation. A single server + of earlier protocol versions, see previous releases of the + <productname>PostgreSQL</productname> documentation. + </para> + + <para> + A single server can support multiple protocol versions. The initial startup-request message tells the server which protocol version the client is attempting to use. If the major version requested by the client is not supported by @@ -36,6 +42,20 @@ to abort the connection. </para> + <para> + The protocol negotiation was introduced in + <productname>PostgreSQL</productname> version 9.3.21. Earlier versions would + reject the connection if the client requested a minor version that was not + supported by the server. + </para> + + <para> + The difference between protocol version 3.0 and 3.1 is that the secret key + used in query cancellation was enlarged from 4 bytes to a variable length + field. The BackendKeyData message was changed to accomodate that, and the + CancelRequest message was redefined to have a variable length payload. + </para> + <para> In order to serve multiple clients efficiently, the server launches a new <quote>backend</quote> process for each client. @@ -405,8 +425,14 @@ this message indicates the highest supported minor version. This message will also be sent if the client requested unsupported protocol options (i.e., beginning with <literal>_pq_.</literal>) in the - startup packet. This message will be followed by an ErrorResponse or - a message indicating the success or failure of authentication. + startup packet. + </para> + <para> + After this message, the authentication will continue using the version + indicated by the server. If the client does not support the older + version, it should immediately close the connection. If the server + does not send this message, it supports the client's requested + protocol version and all the protocol options. </para> </listitem> </varlistentry> @@ -3917,7 +3943,7 @@ psql "dbname=postgres replication=database" -c "IDENTIFY_SYSTEM;" </varlistentry> <varlistentry> - <term>Int32(12)</term> + <term>Int32</term> <listitem> <para> Length of message contents in bytes, including self. @@ -3935,7 +3961,21 @@ psql "dbname=postgres replication=database" -c "IDENTIFY_SYSTEM;" </varlistentry> <varlistentry> - <term>Int32</term> + <term>Int8</term> + <listitem> + <para> + Length of the secret key. + </para> + <para> + This field was added in minor protocol version 3.1. In protocol + version 3.0, it is omitted, and the secret key is always 4 bytes + long. + </para> + </listitem> + </varlistentry> + + <varlistentry> + <term>Byten</term> <listitem> <para> The secret key of this backend. @@ -4148,14 +4188,18 @@ psql "dbname=postgres replication=database" -c "IDENTIFY_SYSTEM;" </varlistentry> <varlistentry> - <term>Int32</term> + <term>Byte4</term> <listitem> <para> - The secret key for the target backend. + The secret key for the target backend. This field extends to the end of the + message, indicated by the length field. The maximum key length is 256 bytes. </para> </listitem> </varlistentry> </variablelist> + <para> + Before protocol version 3.1, the secret key was always 4 bytes long. + </para> </listitem> </varlistentry> diff --git a/src/backend/storage/ipc/procsignal.c b/src/backend/storage/ipc/procsignal.c index 87027f27eb..1b0e5e13b3 100644 --- a/src/backend/storage/ipc/procsignal.c +++ b/src/backend/storage/ipc/procsignal.c @@ -63,8 +63,8 @@ typedef struct { pg_atomic_uint32 pss_pid; - bool pss_cancel_key_valid; - int32 pss_cancel_key; + int pss_cancel_key_len; /* 0 means no cancellation is possible */ + char pss_cancel_key[MAX_CANCEL_KEY_LENGTH]; volatile sig_atomic_t pss_signalFlags[NUM_PROCSIGNALS]; slock_t pss_mutex; /* protects the above fields */ @@ -148,8 +148,7 @@ ProcSignalShmemInit(void) SpinLockInit(&slot->pss_mutex); pg_atomic_init_u32(&slot->pss_pid, 0); - slot->pss_cancel_key_valid = false; - slot->pss_cancel_key = 0; + slot->pss_cancel_key_len = 0; MemSet(slot->pss_signalFlags, 0, sizeof(slot->pss_signalFlags)); pg_atomic_init_u64(&slot->pss_barrierGeneration, PG_UINT64_MAX); pg_atomic_init_u32(&slot->pss_barrierCheckMask, 0); @@ -163,11 +162,12 @@ ProcSignalShmemInit(void) * Register the current process in the ProcSignal array */ void -ProcSignalInit(bool cancel_key_valid, int32 cancel_key) +ProcSignalInit(char *cancel_key, int cancel_key_len) { ProcSignalSlot *slot; uint64 barrier_generation; + Assert(cancel_key_len >= 0 && cancel_key_len <= MAX_CANCEL_KEY_LENGTH); if (MyProcNumber < 0) elog(ERROR, "MyProcNumber not set"); if (MyProcNumber >= NumProcSignalSlots) @@ -202,8 +202,9 @@ ProcSignalInit(bool cancel_key_valid, int32 cancel_key) pg_atomic_read_u64(&ProcSignal->psh_barrierGeneration); pg_atomic_write_u64(&slot->pss_barrierGeneration, barrier_generation); - slot->pss_cancel_key_valid = cancel_key_valid; - slot->pss_cancel_key = cancel_key; + if (cancel_key_len > 0) + memcpy(slot->pss_cancel_key, cancel_key, cancel_key_len); + slot->pss_cancel_key_len = cancel_key_len; pg_atomic_write_u32(&slot->pss_pid, MyProcPid); SpinLockRelease(&slot->pss_mutex); @@ -252,8 +253,7 @@ CleanupProcSignalState(int status, Datum arg) /* Mark the slot as unused */ pg_atomic_write_u32(&slot->pss_pid, 0); - slot->pss_cancel_key_valid = false; - slot->pss_cancel_key = 0; + slot->pss_cancel_key_len = 0; /* * Make this slot look like it's absorbed all possible barriers, so that @@ -723,7 +723,7 @@ procsignal_sigusr1_handler(SIGNAL_ARGS) * fields in the ProcSignal slots. */ void -SendCancelRequest(int backendPID, int32 cancelAuthCode) +SendCancelRequest(int backendPID, char *cancel_key, int cancel_key_len) { Assert(backendPID != 0); @@ -752,7 +752,8 @@ SendCancelRequest(int backendPID, int32 cancelAuthCode) } else { - match = slot->pss_cancel_key_valid && slot->pss_cancel_key == cancelAuthCode; + match = slot->pss_cancel_key_len == cancel_key_len && + timingsafe_bcmp(slot->pss_cancel_key, cancel_key, cancel_key_len) == 0; SpinLockRelease(&slot->pss_mutex); diff --git a/src/backend/tcop/backend_startup.c b/src/backend/tcop/backend_startup.c index 2a96c81f92..20fff425c0 100644 --- a/src/backend/tcop/backend_startup.c +++ b/src/backend/tcop/backend_startup.c @@ -45,6 +45,7 @@ bool Trace_connection_negotiation = false; static void BackendInitialize(ClientSocket *client_sock, CAC_state cac); static int ProcessSSLStartup(Port *port); static int ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done); +static void ProcessCancelRequestPacket(Port *port, void *pkt, int pktlen); static void SendNegotiateProtocolVersion(List *unrecognized_protocol_options); static void process_startup_packet_die(SIGNAL_ARGS); static void StartupPacketTimeoutHandler(void); @@ -542,28 +543,7 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done) if (proto == CANCEL_REQUEST_CODE) { - /* - * The client has sent a cancel request packet, not a normal - * start-a-new-connection packet. Perform the necessary processing. - * Nothing is sent back to the client. - */ - CancelRequestPacket *canc; - int backendPID; - int32 cancelAuthCode; - - if (len != sizeof(CancelRequestPacket)) - { - ereport(COMMERROR, - (errcode(ERRCODE_PROTOCOL_VIOLATION), - errmsg("invalid length of startup packet"))); - return STATUS_ERROR; - } - canc = (CancelRequestPacket *) buf; - backendPID = (int) pg_ntoh32(canc->backendPID); - cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode); - - if (backendPID != 0) - SendCancelRequest(backendPID, cancelAuthCode); + ProcessCancelRequestPacket(port, buf, len); /* Not really an error, but we don't want to proceed further */ return STATUS_ERROR; } @@ -854,6 +834,37 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done) return STATUS_OK; } +/* + * The client has sent a cancel request packet, not a normal + * start-a-new-connection packet. Perform the necessary processing. Nothing + * is sent back to the client. + */ +static void +ProcessCancelRequestPacket(Port *port, void *pkt, int pktlen) +{ + CancelRequestPacket *canc; + int len; + + if (pktlen < offsetof(CancelRequestPacket, cancelAuthCode)) + { + ereport(COMMERROR, + (errcode(ERRCODE_PROTOCOL_VIOLATION), + errmsg("invalid length of query cancel packet"))); + return; + } + len = pktlen - offsetof(CancelRequestPacket, cancelAuthCode); + if (len == 0 || len > 256) + { + ereport(COMMERROR, + (errcode(ERRCODE_PROTOCOL_VIOLATION), + errmsg("invalid length of query cancel key"))); + return; + } + + canc = (CancelRequestPacket *) pkt; + SendCancelRequest(pg_ntoh32(canc->backendPID), canc->cancelAuthCode, len); +} + /* * Send a NegotiateProtocolVersion to the client. This lets the client know * that they have either requested a newer minor protocol version than we are diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c index 8bc6bea113..c148167a62 100644 --- a/src/backend/tcop/postgres.c +++ b/src/backend/tcop/postgres.c @@ -4298,16 +4298,20 @@ PostgresMain(const char *dbname, const char *username) * Generate a random cancel key, if this is a backend serving a * connection. InitPostgres() will advertise it in shared memory. */ - Assert(!MyCancelKeyValid); + Assert(MyCancelKeyLength == 0); if (whereToSendOutput == DestRemote) { - if (!pg_strong_random(&MyCancelKey, sizeof(int32))) + int len; + + len = (MyProcPort == NULL || MyProcPort->proto >= PG_PROTOCOL(3, 1)) + ? MAX_CANCEL_KEY_LENGTH : 4; + if (!pg_strong_random(&MyCancelKey, len)) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("could not generate random cancel key"))); } - MyCancelKeyValid = true; + MyCancelKeyLength = len; } /* @@ -4362,10 +4366,20 @@ PostgresMain(const char *dbname, const char *username) { StringInfoData buf; - Assert(MyCancelKeyValid); + Assert(MyCancelKeyLength > 0); pq_beginmessage(&buf, PqMsg_BackendKeyData); pq_sendint32(&buf, (int32) MyProcPid); - pq_sendint32(&buf, (int32) MyCancelKey); + + if (MyProcPort->proto >= PG_PROTOCOL(3, 1)) + { + pq_sendint8(&buf, MyCancelKeyLength); + pq_sendbytes(&buf, MyCancelKey, MyCancelKeyLength); + } + else + { + Assert(MyCancelKeyLength == 4); + pq_sendbytes(&buf, MyCancelKey, 4); + } pq_endmessage(&buf); /* Need not flush since ReadyForQuery will do it. */ } diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c index 03a54451ac..7f3c838f83 100644 --- a/src/backend/utils/init/globals.c +++ b/src/backend/utils/init/globals.c @@ -24,6 +24,7 @@ #include "miscadmin.h" #include "postmaster/postmaster.h" #include "storage/procnumber.h" +#include "storage/procsignal.h" ProtocolVersion FrontendProtocol; @@ -48,8 +49,8 @@ pg_time_t MyStartTime; TimestampTz MyStartTimestamp; struct ClientSocket *MyClientSocket; struct Port *MyProcPort; -bool MyCancelKeyValid = false; -int32 MyCancelKey = 0; +char MyCancelKey[MAX_CANCEL_KEY_LENGTH]; +uint8 MyCancelKeyLength = 0; int MyPMChildSlot; /* diff --git a/src/backend/utils/init/postinit.c b/src/backend/utils/init/postinit.c index 13524ea488..c5d82f5ce4 100644 --- a/src/backend/utils/init/postinit.c +++ b/src/backend/utils/init/postinit.c @@ -683,7 +683,7 @@ InitPostgres(const char *in_dbname, Oid dboid, */ SharedInvalBackendInit(false); - ProcSignalInit(MyCancelKeyValid, MyCancelKey); + ProcSignalInit(MyCancelKey, MyCancelKeyLength); /* * Also set up timeout handlers needed for backend operation. We need diff --git a/src/include/libpq/pqcomm.h b/src/include/libpq/pqcomm.h index 527735e3db..20f6bad320 100644 --- a/src/include/libpq/pqcomm.h +++ b/src/include/libpq/pqcomm.h @@ -94,7 +94,7 @@ is_unixsock_path(const char *path) */ #define PG_PROTOCOL_EARLIEST PG_PROTOCOL(3,0) -#define PG_PROTOCOL_LATEST PG_PROTOCOL(3,0) +#define PG_PROTOCOL_LATEST PG_PROTOCOL(3,1) typedef uint32 ProtocolVersion; /* FE/BE protocol version number */ @@ -128,7 +128,11 @@ typedef uint32 AuthRequest; * * The cancel request code must not match any protocol version number * we're ever likely to use. This random choice should do. + * + * Before PostgreSQL v17 and the protocol version bump from 3.0 to 3.1, the + * cancel key was always 4 bytes. Starting with v17, it's variable length. */ + #define CANCEL_REQUEST_CODE PG_PROTOCOL(1234,5678) typedef struct CancelRequestPacket @@ -136,7 +140,8 @@ typedef struct CancelRequestPacket /* Note that each field is stored in network byte order! */ MsgType cancelRequestCode; /* code to identify a cancel request */ uint32 backendPID; /* PID of client's backend */ - uint32 cancelAuthCode; /* secret key to authorize cancel */ + char cancelAuthCode[FLEXIBLE_ARRAY_MEMBER]; /* secret key to + * authorize cancel */ } CancelRequestPacket; /* Application-Layer Protocol Negotiation is required for direct connections diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h index 25348e71eb..53b6f63aaa 100644 --- a/src/include/miscadmin.h +++ b/src/include/miscadmin.h @@ -191,8 +191,8 @@ extern PGDLLIMPORT pg_time_t MyStartTime; extern PGDLLIMPORT TimestampTz MyStartTimestamp; extern PGDLLIMPORT struct Port *MyProcPort; extern PGDLLIMPORT struct Latch *MyLatch; -extern PGDLLIMPORT bool MyCancelKeyValid; -extern PGDLLIMPORT int32 MyCancelKey; +extern PGDLLIMPORT char MyCancelKey[]; +extern PGDLLIMPORT uint8 MyCancelKeyLength; extern PGDLLIMPORT int MyPMChildSlot; extern PGDLLIMPORT char OutputFileName[]; diff --git a/src/include/storage/procsignal.h b/src/include/storage/procsignal.h index f94c11a9a8..071d302d63 100644 --- a/src/include/storage/procsignal.h +++ b/src/include/storage/procsignal.h @@ -56,16 +56,26 @@ typedef enum PROCSIGNAL_BARRIER_SMGRRELEASE, /* ask smgr to close files */ } ProcSignalBarrierType; +/* + * Length of query cancel keys generated. + * + * Note that the protocol allows for longer keys, or shorter, but this is the + * length we actually generate. Client code, and the server code that handles + * incoming cancellation packets from clients, cannot use this hardcoded + * length. + */ +#define MAX_CANCEL_KEY_LENGTH 32 + /* * prototypes for functions in procsignal.c */ extern Size ProcSignalShmemSize(void); extern void ProcSignalShmemInit(void); -extern void ProcSignalInit(bool cancel_key_valid, int32 cancel_key); +extern void ProcSignalInit(char *cancel_key, int cancel_key_len); extern int SendProcSignal(pid_t pid, ProcSignalReason reason, ProcNumber procNumber); -extern void SendCancelRequest(int backendPID, int32 cancelAuthCode); +extern void SendCancelRequest(int backendPID, char *cancel_key, int cancel_key_len); extern uint64 EmitProcSignalBarrier(ProcSignalBarrierType type); extern void WaitForProcSignalBarrier(uint64 generation); diff --git a/src/interfaces/libpq/fe-cancel.c b/src/interfaces/libpq/fe-cancel.c index 213a6f43c2..0a59c8904a 100644 --- a/src/interfaces/libpq/fe-cancel.c +++ b/src/interfaces/libpq/fe-cancel.c @@ -1,7 +1,7 @@ /*------------------------------------------------------------------------- * * fe-cancel.c - * functions related to setting up a connection to the backend + * functions related to query cancellation * * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California @@ -41,7 +41,6 @@ struct pg_cancel { SockAddr raddr; /* Remote address */ int be_pid; /* PID of to-be-canceled backend */ - int be_key; /* cancel key of to-be-canceled backend */ int pgtcp_user_timeout; /* tcp user timeout */ int keepalives; /* use TCP keepalives? */ int keepalives_idle; /* time between TCP keepalives */ @@ -49,6 +48,10 @@ struct pg_cancel * retransmits */ int keepalives_count; /* maximum number of TCP keepalive * retransmits */ + + /* Pre-constructed cancel request packet starts here */ + int32 cancel_pkt_len; /* in network-byte-order */ + char cancel_req[FLEXIBLE_ARRAY_MEMBER]; /* CancelRequestPacket */ }; @@ -83,6 +86,13 @@ PQcancelCreate(PGconn *conn) return (PGcancelConn *) cancelConn; } + /* Check that we have received a cancellation key */ + if (conn->be_cancel_key_len == 0) + { + libpq_append_conn_error(cancelConn, "no cancellation key received"); + return (PGcancelConn *) cancelConn; + } + /* * Indicate that this connection is used to send a cancellation */ @@ -101,7 +111,15 @@ PQcancelCreate(PGconn *conn) * Copy cancellation token data from the original connection */ cancelConn->be_pid = conn->be_pid; - cancelConn->be_key = conn->be_key; + if (conn->be_cancel_key != NULL) + { + cancelConn->be_cancel_key = malloc(conn->be_cancel_key_len); + if (!conn->be_cancel_key) + goto oom_error; + memcpy(cancelConn->be_cancel_key, conn->be_cancel_key, conn->be_cancel_key_len); + } + cancelConn->be_cancel_key_len = conn->be_cancel_key_len; + cancelConn->pversion = conn->pversion; /* * Cancel requests should not iterate over all possible hosts. The request @@ -349,6 +367,8 @@ PGcancel * PQgetCancel(PGconn *conn) { PGcancel *cancel; + int cancel_req_len; + CancelRequestPacket *req; if (!conn) return NULL; @@ -356,13 +376,17 @@ PQgetCancel(PGconn *conn) if (conn->sock == PGINVALID_SOCKET) return NULL; - cancel = malloc(sizeof(PGcancel)); + /* Check that we have received a cancellation key */ + if (conn->be_cancel_key_len == 0) + return NULL; + + cancel_req_len = offsetof(CancelRequestPacket, cancelAuthCode) + conn->be_cancel_key_len; + cancel = malloc(offsetof(PGcancel, cancel_req) + cancel_req_len); if (cancel == NULL) return NULL; memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr)); - cancel->be_pid = conn->be_pid; - cancel->be_key = conn->be_key; + /* We use -1 to indicate an unset connection option */ cancel->pgtcp_user_timeout = -1; cancel->keepalives = -1; @@ -405,6 +429,13 @@ PQgetCancel(PGconn *conn) goto fail; } + req = (CancelRequestPacket *) &cancel->cancel_req; + req->cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE); + req->backendPID = pg_hton32(conn->be_pid); + memcpy(req->cancelAuthCode, conn->be_cancel_key, conn->be_cancel_key_len); + /* include the length field itself in the length */ + cancel->cancel_pkt_len = pg_hton32(cancel_req_len + 4); + return cancel; fail: @@ -412,6 +443,35 @@ fail: return NULL; } +int +pqSendCancelRequest(PGconn *cancelConn) +{ + CancelRequestPacket req; + + /* Start the message. */ + if (pqPutMsgStart(0, cancelConn)) + return STATUS_ERROR; + + /* Send the message body. */ + memset(&req, 0, offsetof(CancelRequestPacket, cancelAuthCode)); + req.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE); + req.backendPID = pg_hton32(cancelConn->be_pid); + if (pqPutnchar((char *) &req, offsetof(CancelRequestPacket, cancelAuthCode), cancelConn)) + return STATUS_ERROR; + if (pqPutnchar(cancelConn->be_cancel_key, cancelConn->be_cancel_key_len, cancelConn)) + return STATUS_ERROR; + + /* Finish the message. */ + if (pqPutMsgEnd(cancelConn)) + return STATUS_ERROR; + + /* Flush to ensure backend gets it. */ + if (pqFlush(cancelConn)) + return STATUS_ERROR; + + return STATUS_OK; +} + /* PQfreeCancel: free a cancel structure */ void PQfreeCancel(PGcancel *cancel) @@ -465,11 +525,8 @@ PQcancel(PGcancel *cancel, char *errbuf, int errbufsize) int save_errno = SOCK_ERRNO; pgsocket tmpsock = PGINVALID_SOCKET; int maxlen; - struct - { - uint32 packetlen; - CancelRequestPacket cp; - } crp; + char recvbuf; + int cancel_pkt_len; if (!cancel) { @@ -571,15 +628,15 @@ retry3: goto cancel_errReturn; } - /* Create and send the cancel request packet. */ - - crp.packetlen = pg_hton32((uint32) sizeof(crp)); - crp.cp.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE); - crp.cp.backendPID = pg_hton32(cancel->be_pid); - crp.cp.cancelAuthCode = pg_hton32(cancel->be_key); + cancel_pkt_len = pg_ntoh32(cancel->cancel_pkt_len); retry4: - if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp)) + + /* + * Send the cancel request packet. It starts with the message length at + * cancel_pkt_len, followed by the actual packet. + */ + if (send(tmpsock, (char *) &cancel->cancel_pkt_len, cancel_pkt_len, 0) != cancel_pkt_len) { if (SOCK_ERRNO == EINTR) /* Interrupted system call - we'll just try again */ @@ -596,7 +653,7 @@ retry4: * read to obtain any data, we are just waiting for EOF to be signaled. */ retry5: - if (recv(tmpsock, (char *) &crp, 1, 0) < 0) + if (recv(tmpsock, &recvbuf, 1, 0) < 0) { if (SOCK_ERRNO == EINTR) /* Interrupted system call - we'll just try again */ diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index a5055271ae..d8aca4d973 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -243,6 +243,10 @@ static const internalPQconninfoOption PQconninfoOptions[] = { "Fallback-Application-Name", "", 64, offsetof(struct pg_conn, fbappname)}, + {"protocol_version", NULL, NULL, NULL, + "Protocol-Version", "", 5, + offsetof(struct pg_conn, protocol_version_str)}, + {"keepalives", NULL, NULL, NULL, "TCP-Keepalives", "", 1, /* should be just '0' or '1' */ offsetof(struct pg_conn, keepalives)}, @@ -636,7 +640,12 @@ pqDropServerData(PGconn *conn) if (!conn->cancelRequest) { conn->be_pid = 0; - conn->be_key = 0; + if (conn->be_cancel_key != NULL) + { + free(conn->be_cancel_key); + conn->be_cancel_key = NULL; + } + conn->be_cancel_key_len = 0; } } @@ -1762,6 +1771,29 @@ pqConnectOptions2(PGconn *conn) goto oom_error; } + /* + * Validate protocol_version + */ + if (conn->protocol_version_str) + { + if (strcmp(conn->protocol_version_str, "auto") == 0) + conn->requested_pversion = 0; + else if (strcmp(conn->protocol_version_str, "3.1") == 0) + conn->requested_pversion = PG_PROTOCOL(3, 1); + else if (strcmp(conn->protocol_version_str, "3.0") == 0) + conn->requested_pversion = PG_PROTOCOL(3, 0); + else + { + conn->status = CONNECTION_BAD; + libpq_append_conn_error(conn, "invalid %s value: \"%s\"", + "protocol_version", + conn->protocol_version_str); + return false; + } + } + else + conn->requested_pversion = 0; + /* * validate target_session_attrs option, and set target_server_type */ @@ -2836,7 +2868,10 @@ keep_going: /* We will come back to here until there is * must persist across individual connection attempts, but we must * reset them when we start to consider a new server. */ - conn->pversion = PG_PROTOCOL(3, 0); + if (conn->requested_pversion == 0) + conn->pversion = PG_PROTOCOL(3, 1); + else + conn->pversion = conn->requested_pversion; conn->send_appname = true; conn->failed_enc_methods = 0; conn->current_enc_method = 0; @@ -3401,13 +3436,7 @@ keep_going: /* We will come back to here until there is */ if (conn->cancelRequest) { - CancelRequestPacket cancelpacket; - - packetlen = sizeof(cancelpacket); - cancelpacket.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE); - cancelpacket.backendPID = pg_hton32(conn->be_pid); - cancelpacket.cancelAuthCode = pg_hton32(conn->be_key); - if (pqPacketSend(conn, 0, &cancelpacket, packetlen) != STATUS_OK) + if (pqSendCancelRequest(conn) != STATUS_OK) { libpq_append_conn_error(conn, "could not send cancel packet: %s", SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); @@ -3872,12 +3901,17 @@ keep_going: /* We will come back to here until there is { if (pqGetNegotiateProtocolVersion3(conn)) { - libpq_append_conn_error(conn, "received invalid protocol negotiation message"); + /* + * Negotiation failed. The error message was filled + * in already. + */ goto error_return; } /* OK, we read the message; mark data consumed */ + conn->inStart = conn->inCursor; - goto error_return; + /* Stay in the CONNECTION_AWAITING_RESPONSE state */ + goto keep_going; } /* It is an authentication request. */ diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c index 3170d484f0..50bec54068 100644 --- a/src/interfaces/libpq/fe-protocol3.c +++ b/src/interfaces/libpq/fe-protocol3.c @@ -48,6 +48,7 @@ static int getRowDescriptions(PGconn *conn, int msgLength); static int getParamDescriptions(PGconn *conn, int msgLength); static int getAnotherTuple(PGconn *conn, int msgLength); static int getParameterStatus(PGconn *conn); +static int getBackendKeyData(PGconn *conn); static int getNotify(PGconn *conn); static int getCopyStart(PGconn *conn, ExecStatusType copytype); static int getReadyForQuery(PGconn *conn); @@ -308,9 +309,7 @@ pqParseInput3(PGconn *conn) * just as easy to handle it as part of the main loop. * Save the data and continue processing. */ - if (pqGetInt(&(conn->be_pid), 4, conn)) - return; - if (pqGetInt(&(conn->be_key), 4, conn)) + if (getBackendKeyData(conn)) return; break; case PqMsg_RowDescription: @@ -1405,8 +1404,8 @@ reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding) /* * Attempt to read a NegotiateProtocolVersion message. * Entry: 'v' message type and length have already been consumed. - * Exit: returns 0 if successfully consumed message. - * returns EOF if not enough data. + * Exit: returns 0 if successfully consumed message and the negotiation succeeded. + * returns 1 on failure. The error message is filled in. */ int pqGetNegotiateProtocolVersion3(PGconn *conn) @@ -1417,11 +1416,11 @@ pqGetNegotiateProtocolVersion3(PGconn *conn) PQExpBufferData buf; if (pqGetInt(&tmp, 4, conn) != 0) - return EOF; + goto eof; their_version = tmp; if (pqGetInt(&num, 4, conn) != 0) - return EOF; + goto eof; initPQExpBuffer(&buf); for (int i = 0; i < num; i++) @@ -1429,17 +1428,36 @@ pqGetNegotiateProtocolVersion3(PGconn *conn) if (pqGets(&conn->workBuffer, conn)) { termPQExpBuffer(&buf); - return EOF; + goto eof; } if (buf.len > 0) appendPQExpBufferChar(&buf, ' '); appendPQExpBufferStr(&buf, conn->workBuffer.data); } - if (their_version < conn->pversion) + /* + * If a specific protocol version was requested by the user and the server + * does not support that exact version -> fail. + */ + if (conn->requested_pversion != 0 && their_version != conn->pversion) + { + libpq_append_conn_error(conn, "requested protocol version %u.%u not supported by server: server supports up to %u.%u", + PG_PROTOCOL_MAJOR(conn->pversion), PG_PROTOCOL_MINOR(conn->pversion), + PG_PROTOCOL_MAJOR(their_version), PG_PROTOCOL_MINOR(their_version)); + return 1; + } + + /* + * If we don't support any of the server's supported versions -> fail + */ + if (their_version < PG_PROTOCOL(3, 0)) + { libpq_append_conn_error(conn, "protocol version not supported by server: client uses %u.%u, server supports up to %u.%u", PG_PROTOCOL_MAJOR(conn->pversion), PG_PROTOCOL_MINOR(conn->pversion), PG_PROTOCOL_MAJOR(their_version), PG_PROTOCOL_MINOR(their_version)); + return 1; + } + if (num > 0) { appendPQExpBuffer(&conn->errorMessage, @@ -1451,10 +1469,19 @@ pqGetNegotiateProtocolVersion3(PGconn *conn) /* neither -- server shouldn't have sent it */ if (!(their_version < conn->pversion) && !(num > 0)) + { libpq_append_conn_error(conn, "invalid %s message", "NegotiateProtocolVersion"); + return 1; + } + + conn->pversion = their_version; termPQExpBuffer(&buf); return 0; + +eof: + libpq_append_conn_error(conn, "insufficient data in \"v\" (NegotiateProtocolVersion) message"); + return 1; } @@ -1486,6 +1513,52 @@ getParameterStatus(PGconn *conn) return 0; } +/* + * parseInput subroutine to read a BackendKeyData message. + * Entry: 'v' message type and length have already been consumed. + * Exit: returns 0 if successfully consumed message. + * returns EOF if not enough data. + */ +static int +getBackendKeyData(PGconn *conn) +{ + uint8 cancel_key_len; + + if (conn->be_cancel_key) + { + free(conn->be_cancel_key); + conn->be_cancel_key = NULL; + conn->be_cancel_key_len = 0; + } + + if (pqGetInt(&(conn->be_pid), 4, conn)) + return EOF; + + if (conn->pversion >= PG_PROTOCOL(3, 1)) + { + if (pqGetc((char *) &cancel_key_len, conn)) + return EOF; + } + else + cancel_key_len = 4; + + conn->be_cancel_key = malloc(cancel_key_len); + if (conn->be_cancel_key == NULL) + { + libpq_append_conn_error(conn, "out of memory"); + /* discard the message */ + return EOF; + } + if (pqGetnchar(conn->be_cancel_key, cancel_key_len, conn)) + { + free(conn->be_cancel_key); + conn->be_cancel_key = NULL; + return EOF; + } + conn->be_cancel_key_len = cancel_key_len; + return 0; +} + /* * Attempt to read a Notify response message. diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index d97b595c97..727110fb0f 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -397,6 +397,7 @@ struct pg_conn char *pguser; /* Postgres username and password, if any */ char *pgpass; char *pgpassfile; /* path to a file containing password(s) */ + char *protocol_version_str; /* protocol version to use */ char *channel_binding; /* channel binding mode * (require,prefer,disable) */ char *keepalives; /* use TCP keepalives? */ @@ -507,6 +508,8 @@ struct pg_conn * sending */ /* Transient state needed while establishing connection */ + ProtocolVersion requested_pversion; /* FE/BE protocol version requested, + * or 0 for "auto" */ PGTargetServerType target_server_type; /* desired session properties */ PGLoadBalanceType load_balance_type; /* desired load balancing * algorithm */ @@ -520,7 +523,8 @@ struct pg_conn /* Miscellaneous stuff */ int be_pid; /* PID of backend --- needed for cancels */ - int be_key; /* key of backend --- needed for cancels */ + char *be_cancel_key; /* query cancellation key and its length */ + uint16 be_cancel_key_len; pgParameterStatus *pstatus; /* ParameterStatus data */ int client_encoding; /* encoding id */ bool std_strings; /* standard_conforming_strings */ @@ -744,6 +748,10 @@ extern PGresult *pqFunctionCall3(PGconn *conn, Oid fnid, int result_is_int, const PQArgBlock *args, int nargs); +/* === in fe-cancel.c === */ + +extern int pqSendCancelRequest(PGconn *cancelConn); + /* === in fe-misc.c === */ /* diff --git a/src/test/modules/libpq_pipeline/t/001_libpq_pipeline.pl b/src/test/modules/libpq_pipeline/t/001_libpq_pipeline.pl index f9e6d07fc0..c543e366bb 100644 --- a/src/test/modules/libpq_pipeline/t/001_libpq_pipeline.pl +++ b/src/test/modules/libpq_pipeline/t/001_libpq_pipeline.pl @@ -72,6 +72,14 @@ for my $testname (@tests) } } +# There were changes to query cancellation in protocol version 3.1, so +# test separately that it still works the old protocol version too. +$node->command_ok( + [ + 'libpq_pipeline', 'cancel', $node->connstr('postgres') . " protocol_version=3.0" + ], + "libpq_pipeline cancel with protocol 3.0"); + $node->stop('fast'); done_testing(); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 547d14b3e7..c52e772442 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -375,6 +375,7 @@ CachedPlanSource CallContext CallStmt CancelRequestPacket +CancelRequestExtendedPacket Cardinality CaseExpr CaseKind -- 2.39.2
^ permalink raw reply [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-08-15 20:20  Robert Haas <robertmhaas@gmail.com>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  1 sibling, 1 reply; 40+ messages in thread

From: Robert Haas @ 2024-08-15 20:20 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Jelte Fennema-Nio <postgres@jeltef.nl>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>

On Thu, Aug 15, 2024 at 1:13 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:
> Added a "protocol_version" libpq option for that. It defaults to "auto",
> but you can set it to "3.1" or "3.0" to force the version. It makes it
> easier to test that the backwards-compatibility works, too.

Over on the "Add new protocol message to change GUCs for usage with
future protocol-only GUCs" there is a lot of relevant discussion about
how bumping the protocol version should work. This thread shouldn't
ignore all that discussion. Just to take one example, Jelte wants to
bump the protocol version to 3.2, not 3.1, for some reasons that are
in the commit message for the relevant patch over there.

-- 
Robert Haas
EDB: http://www.enterprisedb.com





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-08-15 22:07  Heikki Linnakangas <hlinnaka@iki.fi>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 40+ messages in thread

From: Heikki Linnakangas @ 2024-08-15 22:07 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Jelte Fennema-Nio <postgres@jeltef.nl>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>

On 15/08/2024 23:20, Robert Haas wrote:
> On Thu, Aug 15, 2024 at 1:13 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:
>> Added a "protocol_version" libpq option for that. It defaults to "auto",
>> but you can set it to "3.1" or "3.0" to force the version. It makes it
>> easier to test that the backwards-compatibility works, too.
> 
> Over on the "Add new protocol message to change GUCs for usage with
> future protocol-only GUCs" there is a lot of relevant discussion about
> how bumping the protocol version should work. This thread shouldn't
> ignore all that discussion. Just to take one example, Jelte wants to
> bump the protocol version to 3.2, not 3.1, for some reasons that are
> in the commit message for the relevant patch over there.

Ok, I've read through that thread now, and opined there too. One 
difference is with libpq option name: My patch adds "protocol_version", 
while Jelte proposes "max_protocol_version". I don't have strong 
opinions on that. I hope the ecosystem catches up to support 
NegotiateProtocolVersion quickly, so that only few people will need to 
set this option. In particular, I hope that there will never be need to 
use "max_protocol_version=3.2", because by the time we introduce version 
3.3, all the connection poolers that support 3.2 will also implement 
NegotiateProtocolVersion.

-- 
Heikki Linnakangas
Neon (https://neon.tech)






^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-08-16 12:31  Robert Haas <robertmhaas@gmail.com>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  0 siblings, 1 reply; 40+ messages in thread

From: Robert Haas @ 2024-08-16 12:31 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Jelte Fennema-Nio <postgres@jeltef.nl>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>

On Thu, Aug 15, 2024 at 6:07 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:
> Ok, I've read through that thread now, and opined there too. One
> difference is with libpq option name: My patch adds "protocol_version",
> while Jelte proposes "max_protocol_version". I don't have strong
> opinions on that. I hope the ecosystem catches up to support
> NegotiateProtocolVersion quickly, so that only few people will need to
> set this option. In particular, I hope that there will never be need to
> use "max_protocol_version=3.2", because by the time we introduce version
> 3.3, all the connection poolers that support 3.2 will also implement
> NegotiateProtocolVersion.

In Jelte's design, there end up being two connection parameters. We
tell the server we want max_protocol_version, but we accept that it
might give us something older. If, however, it tries to degrade us to
something lower than min_protocol_version, we bail out. I see you've
gone for a simpler design: you ask the server for protocol_version and
you get that or you die. To be honest, right up until exactly now, I
was assuming we wanted a two-parameter system like that, just because
being able to tolerate a range of protocol versions seems useful.
However, maybe we don't need it. Alternatively, we could do this for
now, and then later we could adjust the parameter so that you can say
protocol_version=3.2-3.7 and the client will ask for 3.7 but tolerate
anything >= 3.2. Hmm, I kind of like that idea.

I think it's likely that the ecosystem will catch up with
NegotiateProtocolVersion once things start breaking. However, I feel
pretty confident that there are going to be glitches. Clients are
going to want to force newer protocol versions to make sure they get
new features, or to make sure that security features that they want to
have (like this one) are enabled. Some users are going to be running
old poolers that can't handle 3.2, or there will be weirder things
where the pooler says it supports it but it doesn't actually work
properly in all cases. There are also non-PG servers that reimplement
the PG wire protocol. I can't really enumerate all the things that go
wrong, but I think there are a number of wire protocol changes that
various people have been wanting for a long while now, and when we
start to get the infrastructure in place to make that practical,
people are going to take advantage of it. So I think we can expect a
number of protocol enhancements and changes -- Peter's transparent
column encryption stuff is another example -- and there will be
mistakes by us and mistakes by others along the way. Allowing users to
specify what protocol version they want is probably an important part
of coping with that.

The documentation in the patch you attached still seems to think
there's an explicit length field for the cancel key. Also, I think it
would be good to split this into two patches, one to bump the protocol
version and a second to change the cancel key stuff. It would
facilitate review, and I also think that bumping the protocol version
is a big enough deal that it should have its own entry in the commit
log.

-- 
Robert Haas
EDB: http://www.enterprisedb.com





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-08-16 14:37  Heikki Linnakangas <hlinnaka@iki.fi>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 40+ messages in thread

From: Heikki Linnakangas @ 2024-08-16 14:37 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Jelte Fennema-Nio <postgres@jeltef.nl>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>

On 16/08/2024 15:31, Robert Haas wrote:
> On Thu, Aug 15, 2024 at 6:07 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:
>> Ok, I've read through that thread now, and opined there too. One
>> difference is with libpq option name: My patch adds "protocol_version",
>> while Jelte proposes "max_protocol_version". I don't have strong
>> opinions on that. I hope the ecosystem catches up to support
>> NegotiateProtocolVersion quickly, so that only few people will need to
>> set this option. In particular, I hope that there will never be need to
>> use "max_protocol_version=3.2", because by the time we introduce version
>> 3.3, all the connection poolers that support 3.2 will also implement
>> NegotiateProtocolVersion.
> 
> In Jelte's design, there end up being two connection parameters. We
> tell the server we want max_protocol_version, but we accept that it
> might give us something older. If, however, it tries to degrade us to
> something lower than min_protocol_version, we bail out. I see you've
> gone for a simpler design: you ask the server for protocol_version and
> you get that or you die. To be honest, right up until exactly now, I
> was assuming we wanted a two-parameter system like that, just because
> being able to tolerate a range of protocol versions seems useful.
> However, maybe we don't need it. Alternatively, we could do this for
> now, and then later we could adjust the parameter so that you can say
> protocol_version=3.2-3.7 and the client will ask for 3.7 but tolerate
> anything >= 3.2. Hmm, I kind of like that idea.

Works for me.

If we envision accepting ranges like that in the future, it would be 
good to do now rather than later. Otherwise, if someone wants to require 
features from protocol 3.2 today, they will have to put 
"protocol_version=3.2" in the connection string, and later when 3.3 
version is released, their connection string will continue to force the 
then-old 3.2 version.

> I think it's likely that the ecosystem will catch up with
> NegotiateProtocolVersion once things start breaking. However, I feel
> pretty confident that there are going to be glitches. Clients are
> going to want to force newer protocol versions to make sure they get
> new features, or to make sure that security features that they want to
> have (like this one) are enabled. Some users are going to be running
> old poolers that can't handle 3.2, or there will be weirder things
> where the pooler says it supports it but it doesn't actually work
> properly in all cases. There are also non-PG servers that reimplement
> the PG wire protocol. I can't really enumerate all the things that go
> wrong, but I think there are a number of wire protocol changes that
> various people have been wanting for a long while now, and when we
> start to get the infrastructure in place to make that practical,
> people are going to take advantage of it. So I think we can expect a
> number of protocol enhancements and changes -- Peter's transparent
> column encryption stuff is another example -- and there will be
> mistakes by us and mistakes by others along the way. Allowing users to
> specify what protocol version they want is probably an important part
> of coping with that.

Yes, it's a good escape hatch to have.

> The documentation in the patch you attached still seems to think
> there's an explicit length field for the cancel key.

ok thanks

> Also, I think it
> would be good to split this into two patches, one to bump the protocol
> version and a second to change the cancel key stuff. It would
> facilitate review, and I also think that bumping the protocol version
> is a big enough deal that it should have its own entry in the commit
> log.

Right. That's what Jelte's first patches did too. Those changes are more 
or less the same between this patch and his. These clearly need to be 
merged into one "introduce protocol version 3.2" patch.

I'll split this patch like that, to make it easier to compare and merge 
with Jelte's corresponding patches.

-- 
Heikki Linnakangas
Neon (https://neon.tech)






^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-08-16 15:29  Robert Haas <robertmhaas@gmail.com>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  0 siblings, 1 reply; 40+ messages in thread

From: Robert Haas @ 2024-08-16 15:29 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Jelte Fennema-Nio <postgres@jeltef.nl>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>

On Fri, Aug 16, 2024 at 10:37 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:
> If we envision accepting ranges like that in the future, it would be
> good to do now rather than later. Otherwise, if someone wants to require
> features from protocol 3.2 today, they will have to put
> "protocol_version=3.2" in the connection string, and later when 3.3
> version is released, their connection string will continue to force the
> then-old 3.2 version.

I'm totally cool with doing it now rather than later if you or someone
else is willing to do the work. But I don't see why we'd need a
protocol bump to change it later. If you write protocol_version=3.7 or
protocol_version=3.2-3.7 we send the same thing to the server either
way. It's only a difference in whether we slam the connection shut if
the server comes back and say it can only do 3.0.

> I'll split this patch like that, to make it easier to compare and merge
> with Jelte's corresponding patches.

That sounds great. IMHO, comparing and merging the patches is the next
step here and would be great to see.

-- 
Robert Haas
EDB: http://www.enterprisedb.com





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-09-05 15:43  Jacob Champion <jacob.champion@enterprisedb.com>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  1 sibling, 2 replies; 40+ messages in thread

From: Jacob Champion @ 2024-09-05 15:43 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Jelte Fennema-Nio <postgres@jeltef.nl>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On Thu, Aug 15, 2024 at 10:14 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:
> I'm back to working on the main patch here, to make cancellation keys
> longer. New rebased version attached, with all the FIXMEs and TODOs from
> the earlier version fixed. There was a lot of bitrot, too.

I have a couple of questions/comments separate from the protocol changes:

Has there been any work/discussion around not sending the cancel key
in plaintext from psql? It's not a prerequisite or anything (the
longer length is a clear improvement either way), but it seems odd
that this longer "secret" is still just going to be exposed on the
wire when you press Ctrl+C.

> The first patch now introduces timingsafe_bcmp(), a function borrowed
> from OpenBSD to perform a constant-time comparison. There's a configure
> check to use the function from the OS if it's available, and includes a
> copy of OpenBSD's implementation otherwise. Similar functions exist with
> different names in OpenSSL (CRYPTO_memcmp) and NetBSD
> (consttime_memequal), but it's a pretty simple function so I don't think
> we need to work too hard to pick up those other native implementations.

One advantage to using other implementations is that _they're_ on the
hook for keeping constant-time guarantees, which is getting trickier
due to weird architectural optimizations [1]. CRYPTO_memcmp() has
almost the same implementation as 0001 here, except they made the
decision to mark the pointers volatile, and they also provide
hand-crafted assembly versions. This patch has OpenBSD's version, but
they've also turned on data-independent timing by default across their
ARM64 processors [2]. And Intel may require the same tweak, but it
doesn't look like userspace has access to that setting yet, and the
kernel thread [3] appears to have just withered...

For the cancel key implementation in particular, I agree with you that
it's probably not a serious problem. But if other security code starts
using timingsafe_bcmp() then it might be something to be concerned
about. Are there any platform/architecture combos that don't provide a
native timingsafe_bcmp() *and* need a DIT bit for safety?

Thanks,
--Jacob

[1] https://github.com/golang/go/issues/66450
[2] https://github.com/openbsd/src/commit/cf1440f11c
[3] https://lore.kernel.org/lkml/851920c5-31c9-ddd9-3e2d-57d379aa0671@intel.com/





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-09-05 16:21  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Jacob Champion <jacob.champion@enterprisedb.com>
  1 sibling, 1 reply; 40+ messages in thread

From: Tom Lane @ 2024-09-05 16:21 UTC (permalink / raw)
  To: Jacob Champion <jacob.champion@enterprisedb.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Jelte Fennema-Nio <postgres@jeltef.nl>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Robert Haas <robertmhaas@gmail.com>

Jacob Champion <jacob.champion@enterprisedb.com> writes:
> Has there been any work/discussion around not sending the cancel key
> in plaintext from psql? It's not a prerequisite or anything (the
> longer length is a clear improvement either way), but it seems odd
> that this longer "secret" is still just going to be exposed on the
> wire when you press Ctrl+C.

Wasn't this already addressed in v17, by

Author: Alvaro Herrera <alvherre@alvh.no-ip.org>
2024-03-12 [61461a300] libpq: Add encrypted and non-blocking query cancellation

?  Perhaps we need to run around and make sure none of our standard
clients use the old API anymore, but the libpq infrastructure is
there already.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-09-05 16:33  Jacob Champion <jacob.champion@enterprisedb.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 0 replies; 40+ messages in thread

From: Jacob Champion @ 2024-09-05 16:33 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; Jelte Fennema-Nio <postgres@jeltef.nl>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On Thu, Sep 5, 2024 at 9:21 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Wasn't this already addressed in v17, by
>
> Author: Alvaro Herrera <alvherre@alvh.no-ip.org>
> 2024-03-12 [61461a300] libpq: Add encrypted and non-blocking query cancellation
>
> ?  Perhaps we need to run around and make sure none of our standard
> clients use the old API anymore, but the libpq infrastructure is
> there already.

Right. From a quick grep, it looks like we have seven binaries using
the signal-based cancel handler.

(For programs that only send a cancel request right before they break
the connection, it's probably not worth a huge amount of effort to
change it right away, but for psql in particular I think the status
quo is a little weird.)

Thanks,
--Jacob





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-09-05 16:36  Jelte Fennema-Nio <postgres@jeltef.nl>
  parent: Jacob Champion <jacob.champion@enterprisedb.com>
  1 sibling, 1 reply; 40+ messages in thread

From: Jelte Fennema-Nio @ 2024-09-05 16:36 UTC (permalink / raw)
  To: Jacob Champion <jacob.champion@enterprisedb.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On Thu, 5 Sept 2024 at 17:43, Jacob Champion
<jacob.champion@enterprisedb.com> wrote:
> Has there been any work/discussion around not sending the cancel key
> in plaintext from psql? It's not a prerequisite or anything (the
> longer length is a clear improvement either way), but it seems odd
> that this longer "secret" is still just going to be exposed on the
> wire when you press Ctrl+C.

Totally agreed that it would be good to update psql to use the new
much more secure libpq function introduced in PG17[1]. This is not a
trivial change though because it requires refactoring the way we
handle signals (which is why I didn't do it as part of introducing
these new APIs). I had hoped that the work in [2] would either do that
or at least make it a lot easier, but that thread seems to have
stalled. So +1 for doing this, but I think it's a totally separate
change and so should be discussed on a separate thread.

[1]: https://www.postgresql.org/docs/17/libpq-cancel.html#LIBPQ-CANCEL-FUNCTIONS
[2]: https://www.postgresql.org/message-id/flat/20240331222502.03b5354bc6356bc5c388919d%40sraoss.co.jp#14...

> For the cancel key implementation in particular, I agree with you that
> it's probably not a serious problem. But if other security code starts
> using timingsafe_bcmp() then it might be something to be concerned
> about. Are there any platform/architecture combos that don't provide a
> native timingsafe_bcmp() *and* need a DIT bit for safety?

It sounds to me like we should at least use OpenSSL's CRYPTO_memcmp if
we linked against it and the OS doesn't provide a timingsafe_bcmp.
Would that remove your concerns? I expect anyone that cares about
security to link against some TLS library. That way our "fallback"
implementation is only used on the rare systems where that's not the
case.





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-09-05 17:08  Jacob Champion <jacob.champion@enterprisedb.com>
  parent: Jelte Fennema-Nio <postgres@jeltef.nl>
  0 siblings, 0 replies; 40+ messages in thread

From: Jacob Champion @ 2024-09-05 17:08 UTC (permalink / raw)
  To: Jelte Fennema-Nio <postgres@jeltef.nl>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>; Robert Haas <robertmhaas@gmail.com>

On Thu, Sep 5, 2024 at 9:36 AM Jelte Fennema-Nio <postgres@jeltef.nl> wrote:
> Totally agreed that it would be good to update psql to use the new
> much more secure libpq function introduced in PG17[1]. This is not a
> trivial change though because it requires refactoring the way we
> handle signals (which is why I didn't do it as part of introducing
> these new APIs).

Yeah, I figured it wasn't a quick fix.

> I had hoped that the work in [2] would either do that
> or at least make it a lot easier, but that thread seems to have
> stalled. So +1 for doing this, but I think it's a totally separate
> change and so should be discussed on a separate thread.

As long as the new thread doesn't also stall out/get forgotten, I'm happy.

> It sounds to me like we should at least use OpenSSL's CRYPTO_memcmp if
> we linked against it and the OS doesn't provide a timingsafe_bcmp.
> Would that remove your concerns?

If we go that direction, I'd still like to know which platforms we
expect to have a suboptimal port, if for no other reason than
documenting that those users should try to get OpenSSL into their
builds. (I agree that they probably will already, if they care.)

And if I'm being really picky, I'm not sure we should call our port
"timingsafe_bcmp" (vs. pg_secure_bcmp or something) if we know it's
not actually timing-safe for some. But I won't die on that hill.

Thanks,
--Jacob





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2024-09-09 15:58  Robert Haas <robertmhaas@gmail.com>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 40+ messages in thread

From: Robert Haas @ 2024-09-09 15:58 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Jelte Fennema-Nio <postgres@jeltef.nl>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>

On Fri, Aug 16, 2024 at 11:29 AM Robert Haas <robertmhaas@gmail.com> wrote:
> > I'll split this patch like that, to make it easier to compare and merge
> > with Jelte's corresponding patches.
>
> That sounds great. IMHO, comparing and merging the patches is the next
> step here and would be great to see.

Heikki, do you have any update on this work?

-- 
Robert Haas
EDB: http://www.enterprisedb.com





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2025-02-22 14:58  Jelte Fennema-Nio <postgres@jeltef.nl>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 2 replies; 40+ messages in thread

From: Jelte Fennema-Nio @ 2025-02-22 14:58 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>

On Mon, 9 Sept 2024 at 17:58, Robert Haas <robertmhaas@gmail.com> wrote:
>
> On Fri, Aug 16, 2024 at 11:29 AM Robert Haas <robertmhaas@gmail.com> wrote:
> > > I'll split this patch like that, to make it easier to compare and merge
> > > with Jelte's corresponding patches.
> >
> > That sounds great. IMHO, comparing and merging the patches is the next
> > step here and would be great to see.
>
> Heikki, do you have any update on this work?

My patchset in the other protocol thread needed a rebase. So I took
that as an opportunity to rebase this patchset on top of it, because
this seems to be the protocol change that we can most easily push over
the finish line.

1. I changed the last patch from Heikki to only contain the changes
for the cancel lengthening. The general protocol change related things
I merged with mine (I only kept some error handling and docs).
2. I also removed the length field in the new BackendKey definition,
eventhough I asked for that addition previously. I agree with Heikki
that it's actually easier to parse and create without, because you can
use the same code for both versions.
3. I made our timingsafe_bcmp implementation call into OpenSSL's CRYPTO_memcmp.

One open question on the last patch is: Document what the maximum size
of the cancel key is that the client can expect? I think Jacob might
have some ideas on that.

Attachments: download all (7 files, .tar.gz)

v4-0001-libpq-Add-PQfullProtocolVersion-to-exports.txt.patch (text/x-patch, 812B) download From 0168dd6d463eb989d2e944c8acccf7cc620f5db1 Mon Sep 17 00:00:00 2001 From: Jelte Fennema-Nio <postgres@jeltef.nl> Date: Mon, 23 Dec 2024 16:49:10 +0100 Subject: [PATCH v4 1/7] libpq: Add PQfullProtocolVersion to exports.txt This is necessary to be able to actually use the function on Windows. --- src/interfaces/libpq/exports.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/src/interfaces/libpq/exports.txt b/src/interfaces/libpq/exports.txt index 9b789cbec0b..d5143766858 100644 --- a/src/interfaces/libpq/exports.txt +++ b/src/interfaces/libpq/exports.txt @@ -209,3 +209,4 @@ PQservice 206 PQsetAuthDataHook 207 PQgetAuthDataHook 208 PQdefaultAuthDataHook 209 +PQfullProtocolVersion 210 base-commit: bba2fbc6238b2a0a7f348fbbb5c31ffa7623bc39 -- 2.43.0
v4-0002-libpq-Trace-NegotiateProtocolVersion-correctly.patch (text/x-patch, 1.4K) download From 804da9044f08c62db598b42296b973284ca5b32b Mon Sep 17 00:00:00 2001 From: Jelte Fennema-Nio <jelte.fennema@microsoft.com> Date: Wed, 5 Jun 2024 11:40:04 +0200 Subject: [PATCH v4 2/7] libpq: Trace NegotiateProtocolVersion correctly This changes the libpq tracing code to correctly trace the NegotiateProtocolVersion message. Previously it wasn't important that tracing of the NegotiateProtocolVersion message worked correctly, because in practice libpq never received it. Now that we are planning to introduce protocol changes in future commits it starts to become more useful for testing/debugging. --- src/interfaces/libpq/fe-trace.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/interfaces/libpq/fe-trace.c b/src/interfaces/libpq/fe-trace.c index 641e70f321c..a45f0d85587 100644 --- a/src/interfaces/libpq/fe-trace.c +++ b/src/interfaces/libpq/fe-trace.c @@ -578,9 +578,15 @@ pqTraceOutput_RowDescription(FILE *f, const char *message, int *cursor, bool reg static void pqTraceOutput_NegotiateProtocolVersion(FILE *f, const char *message, int *cursor) { + int nparams; + fprintf(f, "NegotiateProtocolVersion\t"); pqTraceOutputInt32(f, message, cursor, false); - pqTraceOutputInt32(f, message, cursor, false); + nparams = pqTraceOutputInt32(f, message, cursor, false); + for (int i = 0; i < nparams; i++) + { + pqTraceOutputString(f, message, cursor, false); + } } static void -- 2.43.0
v4-0003-libpq-Handle-NegotiateProtocolVersion-message-dif.patch (text/x-patch, 5.9K) download From d4264c2487cb7c84efeaee09cbe52685487c0b88 Mon Sep 17 00:00:00 2001 From: Jelte Fennema-Nio <postgres@jeltef.nl> Date: Wed, 14 Aug 2024 18:25:16 +0200 Subject: [PATCH v4 3/7] libpq: Handle NegotiateProtocolVersion message differently Previously libpq would always error when the server returns a NegotiateProtocolVersion message. This was fine because libpq only supported a single protocol version and did not support any protocol parameters. But we now that we're discussing protocol changes we need to change this behaviour, and introduce a fallback mechanism when connecting to an older server. This patch modifies the client side checks to allow a range of supported protocol versions, instead of only allowing the exact version that was requested. Currently this "range" only contains the 3.0 version, but in a future commit we'll change this. In addition it changes the errors for protocol to say that they error because we did not request any parameters, not because the server did not support some of them. In a future commit more infrastructure for protocol parameters will be added, so that these checks can also succeed when receiving unsupported parameters back. Note that at the moment this change does not have any behavioural effect, because libpq will only request version 3.0 and will never send protocol parameters. Which means that the client never receives a NegotiateProtocolVersion message from the server. --- src/interfaces/libpq/fe-connect.c | 3 +- src/interfaces/libpq/fe-protocol3.c | 80 +++++++++++++++++------------ 2 files changed, 49 insertions(+), 34 deletions(-) diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index d5051f5e820..281710b0616 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -4091,9 +4091,10 @@ keep_going: /* We will come back to here until there is libpq_append_conn_error(conn, "received invalid protocol negotiation message"); goto error_return; } + /* OK, we read the message; mark data consumed */ pqParseDone(conn, conn->inCursor); - goto error_return; + goto keep_going; } /* It is an authentication request. */ diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c index 95dd456f076..68a94281eb4 100644 --- a/src/interfaces/libpq/fe-protocol3.c +++ b/src/interfaces/libpq/fe-protocol3.c @@ -1399,58 +1399,72 @@ reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding) /* - * Attempt to read a NegotiateProtocolVersion message. + * Attempt to read a NegotiateProtocolVersion message. Sets conn->pversion + * to the version that's negotiated by the server. * Entry: 'v' message type and length have already been consumed. * Exit: returns 0 if successfully consumed message. - * returns EOF if not enough data. + * returns 1 on failure. The error message is filled in. */ int pqGetNegotiateProtocolVersion3(PGconn *conn) { - int tmp; - ProtocolVersion their_version; + int their_version; int num; - PQExpBufferData buf; - if (pqGetInt(&tmp, 4, conn) != 0) - return EOF; - their_version = tmp; + if (pqGetInt(&their_version, 4, conn) != 0) + goto eof; if (pqGetInt(&num, 4, conn) != 0) - return EOF; + goto eof; - initPQExpBuffer(&buf); - for (int i = 0; i < num; i++) + if (their_version > conn->pversion) { - if (pqGets(&conn->workBuffer, conn)) - { - termPQExpBuffer(&buf); - return EOF; - } - if (buf.len > 0) - appendPQExpBufferChar(&buf, ' '); - appendPQExpBufferStr(&buf, conn->workBuffer.data); + libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requests downgrade to higher-numbered version"); + goto failure; } - if (their_version < conn->pversion) - libpq_append_conn_error(conn, "protocol version not supported by server: client uses %u.%u, server supports up to %u.%u", - PG_PROTOCOL_MAJOR(conn->pversion), PG_PROTOCOL_MINOR(conn->pversion), - PG_PROTOCOL_MAJOR(their_version), PG_PROTOCOL_MINOR(their_version)); - if (num > 0) + if (their_version < PG_PROTOCOL(3, 0)) + { + libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requests downgrade to pre-3.0 protocol version"); + goto failure; + } + + if (num < 0) { - appendPQExpBuffer(&conn->errorMessage, - libpq_ngettext("protocol extension not supported by server: %s", - "protocol extensions not supported by server: %s", num), - buf.data); - appendPQExpBufferChar(&conn->errorMessage, '\n'); + libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported negative number of unsupported parameters"); + goto failure; } - /* neither -- server shouldn't have sent it */ - if (!(their_version < conn->pversion) && !(num > 0)) - libpq_append_conn_error(conn, "invalid %s message", "NegotiateProtocolVersion"); + if (their_version == conn->pversion && num == 0) + { + libpq_append_conn_error(conn, "received invalid protocol negotiation message: server negotiated but asks for no changes"); + goto failure; + } + + conn->pversion = their_version; + for (int i = 0; i < num; i++) + { + if (pqGets(&conn->workBuffer, conn)) + { + goto eof; + } + if (strncmp(conn->workBuffer.data, "_pq_.", 5) != 0) + { + libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported unsupported parameter name without a _pq_. prefix (\"%s\")", conn->workBuffer.data); + goto failure; + } + libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported an unsupported parameter that was not requested (\"%s\")", conn->workBuffer.data); + goto failure; + } - termPQExpBuffer(&buf); return 0; + +eof: + libpq_append_conn_error(conn, "received invalid protocol negotation message: message too short"); +failure: + conn->asyncStatus = PGASYNC_READY; + pqSaveErrorResult(conn); + return 1; } -- 2.43.0
v4-0004-libpq-Add-min-max_protocol_version-connection-opt.patch (text/x-patch, 11.8K) download From 007e89278b3a5ab4c407c86363210205e0eb2b40 Mon Sep 17 00:00:00 2001 From: Jelte Fennema-Nio <postgres@jeltef.nl> Date: Wed, 14 Aug 2024 18:25:16 +0200 Subject: [PATCH v4 4/7] libpq: Add min/max_protocol_version connection options All officially supported version of the PostgreSQL server send the NegotiateProtocolVersion message when an unsupported minor protocol version is requested by a client. But many other applications that implement the PostgreSQL protocol (connection poolers, or other databases) do not, and the same is true for many unspported PostgreSQL server versions. Connecting to such other applications thus fails if a client requests a protocol version different than 3.0. This patch adds a max_protocol_version connection option to libpq that specifies the protocol version that libpq should request from the server. Currently all allowed values result in the use of 3.0, but that will be changed in a future commit that bumps the protocol version. Even after that version bump the default will likely stay 3.0 for the time being. Once more of the ecosystem supports the NegotiateProtocolVersion message we might want to change the default to the latest minor version. We also add the similar min_protocol_version connection option, to allow a client to specify that connecting should fail if a lower protocol version is attempted by the server. This can be used to ensure certain protocol features are in used, which can be particularly useful if those features impact security. --- doc/src/sgml/libpq.sgml | 71 ++++++++++++++++++- src/interfaces/libpq/fe-connect.c | 104 +++++++++++++++++++++++++++- src/interfaces/libpq/fe-protocol3.c | 12 ++++ src/interfaces/libpq/libpq-int.h | 4 ++ 4 files changed, 189 insertions(+), 2 deletions(-) diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index ddb3596df83..f249bbd9263 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -2144,6 +2144,56 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </listitem> </varlistentry> + <varlistentry id="libpq-connect-min-protocol-version" xreflabel="min_protocol_version"> + <term><literal>min_protocol_version</literal></term> + <listitem> + <para> + Specifies the minimum protocol version to allow for the connection. + The default is to allow any version of the + <productname>PostgreSQL</productname> protocol supported by libpq, + which currently means <literal>3.0</literal>. If the server + does not support at least this protocol version the connection will be + closed. + </para> + + <para> + The current supported values are + <literal>3.0</literal> + and <literal>latest</literal>. The <literal>latest</literal> value is + equivalent to the latest protocol version that is supported by the used + libpq version, which currently is <literal>3.2</literal>, but this will + change in future libpq releases. + </para> + </listitem> + </varlistentry> + + <varlistentry id="libpq-connect-max-protocol-version" xreflabel="max_protocol_version"> + <term><literal>max_protocol_version</literal></term> + <listitem> + <para> + Specifies the protocol version to request from the server. + The default is to use version <literal>3.0</literal> of the + <productname>PostgreSQL</productname> protocol, unless the connection + string specifies a feature that relies on a higher protocol version, in + that case the latest version supported by libpq is used. If the server + does not support the requested protocol version of the client the + connection will be automatically downgraded to a lower minor protocol + version, which the server does support. After the connection attempt has + completed you can use <xref linkend="libpq-PQprotocolVersion"/> to find + out which exact protocol version was negotiated. + </para> + + <para> + The current supported values are + <literal>3.0</literal> + and <literal>latest</literal>. The <literal>latest</literal> value is + equivalent to the latest protocol version that is supported by the used + libpq version, which currently is <literal>3.0</literal>, but this will + change in future libpq releases. + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-connect-ssl-max-protocol-version" xreflabel="ssl_max_protocol_version"> <term><literal>ssl_max_protocol_version</literal></term> <listitem> @@ -2482,7 +2532,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - </variablelist> </para> </sect2> @@ -9329,6 +9378,26 @@ myEventProc(PGEventId evtId, void *evtInfo, void *passThrough) linkend="libpq-connect-load-balance-hosts"/> connection parameter. </para> </listitem> + + <listitem> + <para> + <indexterm> + <primary><envar>PGMINPROTOCOLVERSION</envar></primary> + </indexterm> + <envar>PGMINPROTOCOLVERSION</envar> behaves the same as the <xref + linkend="libpq-connect-min-protocol-version"/> connection parameter. + </para> + </listitem> + + <listitem> + <para> + <indexterm> + <primary><envar>PGMAXPROTOCOLVERSION</envar></primary> + </indexterm> + <envar>PGMAXPROTOCOLVERSION</envar> behaves the same as the <xref + linkend="libpq-connect-max-protocol-version"/> connection parameter. + </para> + </listitem> </itemizedlist> </para> diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index 281710b0616..7f08b143fa7 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -325,6 +325,16 @@ static const internalPQconninfoOption PQconninfoOptions[] = { "Require-Auth", "", 14, /* sizeof("scram-sha-256") == 14 */ offsetof(struct pg_conn, require_auth)}, + {"min_protocol_version", "PGMINPROTOCOLVERSION", + NULL, NULL, + "Min-Protocol-Version", "", 6, /* sizeof("latest") = 6 */ + offsetof(struct pg_conn, min_protocol_version)}, + + {"max_protocol_version", "PGMAXPROTOCOLVERSION", + NULL, NULL, + "Max-Protocol-Version", "", 6, /* sizeof("latest") = 6 */ + offsetof(struct pg_conn, max_protocol_version)}, + {"ssl_min_protocol_version", "PGSSLMINPROTOCOLVERSION", "TLSv1.2", NULL, "SSL-Minimum-Protocol-Version", "", 8, /* sizeof("TLSv1.x") == 8 */ offsetof(struct pg_conn, ssl_min_protocol_version)}, @@ -483,6 +493,7 @@ static void pgpassfileWarning(PGconn *conn); static void default_threadlock(int acquire); static bool sslVerifyProtocolVersion(const char *version); static bool sslVerifyProtocolRange(const char *min, const char *max); +static bool pqParseProtocolVersion(const char *value, ProtocolVersion *result, PGconn *conn, const char *context); /* global variable because fe-auth.c needs to access it */ @@ -2080,6 +2091,42 @@ pqConnectOptions2(PGconn *conn) } } + if (conn->min_protocol_version) + { + if (!pqParseProtocolVersion(conn->min_protocol_version, &conn->min_pversion, conn, "min_protocol_version")) + return false; + } + else + { + conn->min_pversion = PG_PROTOCOL_EARLIEST; + } + + if (conn->max_protocol_version) + { + if (!pqParseProtocolVersion(conn->max_protocol_version, &conn->max_pversion, conn, "max_protocol_version")) + return false; + } + else + { + /* + * To not break connecting to older servers/poolers that do not yet + * support NegotiateProtocolVersion, default to the 3.0 protocol at + * least for a while longer. Except when min_protocol_version is set + * to something larger, then we might as well default to the latest. + */ + if (conn->min_pversion > PG_PROTOCOL(3, 0)) + conn->max_pversion = PG_PROTOCOL_LATEST; + else + conn->max_pversion = PG_PROTOCOL(3, 0); + } + + if (conn->min_pversion > conn->max_pversion) + { + conn->status = CONNECTION_BAD; + libpq_append_conn_error(conn, "min_protocol_version is greater than max_protocol_version"); + return false; + } + /* * Resolve special "auto" client_encoding from the locale */ @@ -3083,7 +3130,7 @@ keep_going: /* We will come back to here until there is * must persist across individual connection attempts, but we must * reset them when we start to consider a new server. */ - conn->pversion = PG_PROTOCOL(3, 0); + conn->pversion = conn->max_pversion; conn->send_appname = true; conn->failed_enc_methods = 0; conn->current_enc_method = 0; @@ -4094,6 +4141,7 @@ keep_going: /* We will come back to here until there is /* OK, we read the message; mark data consumed */ pqParseDone(conn, conn->inCursor); + goto keep_going; } @@ -8149,6 +8197,60 @@ error: return false; } +/* + * Parse and try to interpret "value" as a ProtocolVersion value, and if successful, + * store it in *result. + */ +static bool +pqParseProtocolVersion(const char *value, ProtocolVersion *result, PGconn *conn, + const char *context) +{ + char *end; + int major; + int minor; + ProtocolVersion version; + + if (strcmp(value, "latest") == 0) + { + *result = PG_PROTOCOL_LATEST; + return true; + } + + major = strtol(value, &end, 10); + if (*end != '.') + { + conn->status = CONNECTION_BAD; + libpq_append_conn_error(conn, "invalid %s value: \"%s\"", + context, + value); + return false; + } + + minor = strtol(&end[1], &end, 10); + if (*end != '\0') + { + conn->status = CONNECTION_BAD; + libpq_append_conn_error(conn, "invalid %s value: \"%s\"", + context, + value); + return false; + } + + version = PG_PROTOCOL(major, minor); + if (version > PG_PROTOCOL_LATEST || + version < PG_PROTOCOL_EARLIEST) + { + conn->status = CONNECTION_BAD; + libpq_append_conn_error(conn, "invalid %s value: \"%s\"", + context, + value); + return false; + } + + *result = version; + return true; +} + /* * To keep the API consistent, the locking stubs are always provided, even * if they are not required. diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c index 68a94281eb4..221627bdea6 100644 --- a/src/interfaces/libpq/fe-protocol3.c +++ b/src/interfaces/libpq/fe-protocol3.c @@ -1441,6 +1441,18 @@ pqGetNegotiateProtocolVersion3(PGconn *conn) goto failure; } + if (their_version < conn->min_pversion) + { + libpq_append_conn_error(conn, "server only supports protocol version %d.%d, but min_protocol_version was set to %d.%d", + PG_PROTOCOL_MAJOR(conn->pversion), + PG_PROTOCOL_MINOR(conn->pversion), + PG_PROTOCOL_MAJOR(conn->min_pversion), + PG_PROTOCOL_MINOR(conn->min_pversion)); + + goto failure; + } + + conn->pversion = their_version; for (int i = 0; i < num; i++) { diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index f36f7f19d58..c016408338a 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -425,6 +425,8 @@ struct pg_conn char *gsslib; /* What GSS library to use ("gssapi" or * "sspi") */ char *gssdelegation; /* Try to delegate GSS credentials? (0 or 1) */ + char *min_protocol_version; /* minimum used protocol version */ + char *max_protocol_version; /* maximum used protocol version */ char *ssl_min_protocol_version; /* minimum TLS protocol version */ char *ssl_max_protocol_version; /* maximum TLS protocol version */ char *target_session_attrs; /* desired session properties */ @@ -545,6 +547,8 @@ struct pg_conn void *scram_client_key_binary; /* binary SCRAM client key */ size_t scram_server_key_len; void *scram_server_key_binary; /* binary SCRAM server key */ + ProtocolVersion min_pversion; /* protocol version to request */ + ProtocolVersion max_pversion; /* protocol version to request */ /* Miscellaneous stuff */ int be_pid; /* PID of backend --- needed for cancels */ -- 2.43.0
v4-0005-Bump-protocol-version-to-3.2.patch (text/x-patch, 12.5K) download From fd49b5ec9bad0e50ebea84b48a6d7eadacabe450 Mon Sep 17 00:00:00 2001 From: Jelte Fennema-Nio <postgres@jeltef.nl> Date: Wed, 14 Aug 2024 18:25:16 +0200 Subject: [PATCH v4 5/7] Bump protocol version to 3.2 In preparation of new additions to the protocol in a follow up commit this bumps the minor protocol version number. Instead of bumping the version number to 3.1, which would be the next minor version, we skip that one and bump straight to 3.2. The reason for this is that many PgBouncer releases have, due to an off-by-one bug, reported 3.1 as supported[1]. These versions would interpret 3.1 as equivalent to 3.0. So if we would now add extra messages to the 3.1 protocol, clients would succeed to connect to PgBouncer, but would then cause connection failures when sending such new messages. So instead of bumping to 3.1, we bump the protocol version to 3.2, for which these buggy PgBouncer releases will correctly close the connection at the startup packet. It's a bit strange to skip a version number due to a bug in a third-party application, but PgBouncer is used widely enough that it seems worth it to not cause user confusion when connecting to recent versions of it. Especially since skipping a single minor version number in the protocol versioning doesn't really cost us anything. So, while this is not the most theoretically sound decission, it is the most pragmatic one. [1]: https://github.com/pgbouncer/pgbouncer/pull/1007 --- doc/src/sgml/libpq.sgml | 8 +- doc/src/sgml/protocol.sgml | 31 ++++- src/include/libpq/pqcomm.h | 3 +- src/interfaces/libpq/fe-connect.c | 9 ++ src/interfaces/libpq/fe-protocol3.c | 8 +- .../modules/libpq_pipeline/libpq_pipeline.c | 110 +++++++++++++++--- 6 files changed, 142 insertions(+), 27 deletions(-) diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index f249bbd9263..ed099598c38 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -2158,7 +2158,8 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname <para> The current supported values are - <literal>3.0</literal> + <literal>3.0</literal>, + <literal>3.2</literal>, and <literal>latest</literal>. The <literal>latest</literal> value is equivalent to the latest protocol version that is supported by the used libpq version, which currently is <literal>3.2</literal>, but this will @@ -2185,10 +2186,11 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname <para> The current supported values are - <literal>3.0</literal> + <literal>3.0</literal>, + <literal>3.2</literal>, and <literal>latest</literal>. The <literal>latest</literal> value is equivalent to the latest protocol version that is supported by the used - libpq version, which currently is <literal>3.0</literal>, but this will + libpq version, which currently is <literal>3.2</literal>, but this will change in future libpq releases. </para> </listitem> diff --git a/doc/src/sgml/protocol.sgml b/doc/src/sgml/protocol.sgml index 3bd9e68e6ce..6bb97dbba55 100644 --- a/doc/src/sgml/protocol.sgml +++ b/doc/src/sgml/protocol.sgml @@ -18,17 +18,23 @@ </para> <para> - This document describes version 3.0 of the protocol, implemented in + This document describes version 3.2 of the protocol, introduced in + <productname>PostgreSQL</productname> version 17. The server is compatible with + protocol version 3.0, implemented in <productname>PostgreSQL</productname> 7.4 and later. For descriptions - of the earlier protocol versions, see previous releases of the - <productname>PostgreSQL</productname> documentation. A single server + of earlier protocol versions, see previous releases of the + <productname>PostgreSQL</productname> documentation. + </para> + + <para> + A single server can support multiple protocol versions. The initial startup-request message tells the server which protocol version the client is attempting to use. If the major version requested by the client is not supported by the server, the connection will be rejected (for example, this would occur if the client requested protocol version 4.0, which does not exist as of this writing). If the minor version requested by the client is not - supported by the server (e.g., the client requests version 3.1, but the + supported by the server (e.g., the client requests version 3.2, but the server supports only 3.0), the server may either reject the connection or may respond with a NegotiateProtocolVersion message containing the highest minor protocol version which it supports. The client may then choose either @@ -36,6 +42,13 @@ to abort the connection. </para> + <para> + The protocol negotiation was introduced in + <productname>PostgreSQL</productname> version 9.3.21. Earlier versions would + reject the connection if the client requested a minor version that was not + supported by the server. + </para> + <para> In order to serve multiple clients efficiently, the server launches a new <quote>backend</quote> process for each client. @@ -413,8 +426,14 @@ this message indicates the highest supported minor version. This message will also be sent if the client requested unsupported protocol options (i.e., beginning with <literal>_pq_.</literal>) in the - startup packet. This message will be followed by an ErrorResponse or - a message indicating the success or failure of authentication. + startup packet. + </para> + <para> + After this message, the authentication will continue using the version + indicated by the server. If the client does not support the older + version, it should immediately close the connection. If the server + does not send this message, it supports the client's requested + protocol version and all the protocol options. </para> </listitem> </varlistentry> diff --git a/src/include/libpq/pqcomm.h b/src/include/libpq/pqcomm.h index 46b37e0e4eb..0aceb7147c7 100644 --- a/src/include/libpq/pqcomm.h +++ b/src/include/libpq/pqcomm.h @@ -91,11 +91,10 @@ is_unixsock_path(const char *path) /* * The earliest and latest frontend/backend protocol version supported. - * (Only protocol version 3 is currently supported) */ #define PG_PROTOCOL_EARLIEST PG_PROTOCOL(3,0) -#define PG_PROTOCOL_LATEST PG_PROTOCOL(3,0) +#define PG_PROTOCOL_LATEST PG_PROTOCOL(3,2) typedef uint32 ProtocolVersion; /* FE/BE protocol version number */ diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index 7f08b143fa7..559964a6a25 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -8216,6 +8216,15 @@ pqParseProtocolVersion(const char *value, ProtocolVersion *result, PGconn *conn, return true; } + if (strcmp(value, "3.1") == 0) + { + conn->status = CONNECTION_BAD; + libpq_append_conn_error(conn, "invalid %s value: \"%s\"", + context, + value); + return false; + } + major = strtol(value, &end, 10); if (*end != '.') { diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c index 221627bdea6..f33766c7df4 100644 --- a/src/interfaces/libpq/fe-protocol3.c +++ b/src/interfaces/libpq/fe-protocol3.c @@ -1428,7 +1428,13 @@ pqGetNegotiateProtocolVersion3(PGconn *conn) libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requests downgrade to pre-3.0 protocol version"); goto failure; } - + + if (their_version == PG_PROTOCOL(3, 1)) + { + libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requests downgrade to 3.1 protocol version"); + goto failure; + } + if (num < 0) { libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported negative number of unsupported parameters"); diff --git a/src/test/modules/libpq_pipeline/libpq_pipeline.c b/src/test/modules/libpq_pipeline/libpq_pipeline.c index 7ff18e91e66..656f437826e 100644 --- a/src/test/modules/libpq_pipeline/libpq_pipeline.c +++ b/src/test/modules/libpq_pipeline/libpq_pipeline.c @@ -198,24 +198,15 @@ send_cancellable_query_impl(int line, PGconn *conn, PGconn *monitorConn) } /* - * Create a new connection with the same conninfo as the given one. + * Fills keywords and vals, with the same options as the ones in the opts + * linked-list. Returns the length of the filled in list. */ -static PGconn * -copy_connection(PGconn *conn) +static +int +copy_connection_options(PQconninfoOption *opts, const char **keywords, const char **vals) { - PGconn *copyConn; - PQconninfoOption *opts = PQconninfo(conn); - const char **keywords; - const char **vals; - int nopts = 1; int i = 0; - for (PQconninfoOption *opt = opts; opt->keyword != NULL; ++opt) - nopts++; - - keywords = pg_malloc(sizeof(char *) * nopts); - vals = pg_malloc(sizeof(char *) * nopts); - for (PQconninfoOption *opt = opts; opt->keyword != NULL; ++opt) { if (opt->val) @@ -225,8 +216,28 @@ copy_connection(PGconn *conn) i++; } } - keywords[i] = vals[i] = NULL; + return i; +} + +/* + * Create a new connection with the same conninfo as the given one. + */ +static PGconn * +copy_connection(PGconn *conn) +{ + const char **keywords; + const char **vals; + PGconn *copyConn; + PQconninfoOption *opts = PQconninfo(conn); + int nopts = 1; /* 1 for the NULL terminator */ + for (PQconninfoOption *opt = opts; opt->keyword != NULL; ++opt) + nopts++; + + keywords = pg_malloc0(sizeof(char *) * nopts); + vals = pg_malloc0(sizeof(char *) * nopts); + + copy_connection_options(opts, keywords, vals); copyConn = PQconnectdbParams(keywords, vals, false); if (PQstatus(copyConn) != CONNECTION_OK) @@ -1406,6 +1417,72 @@ test_prepared(PGconn *conn) fprintf(stderr, "ok\n"); } +static void +test_protocol_version(PGconn *conn) +{ + const char **keywords; + const char **vals; + int nopts = 2; /* NULL terminator + max_protocol_version */ + PQconninfoOption *opts = PQconninfo(conn); + int protocol_version; + int max_protocol_version_index; + + for (PQconninfoOption *opt = opts; opt->keyword != NULL; ++opt) + nopts++; + + keywords = pg_malloc0(sizeof(char *) * nopts); + vals = pg_malloc0(sizeof(char *) * nopts); + + max_protocol_version_index = copy_connection_options(opts, keywords, vals); + + keywords[max_protocol_version_index] = "max_protocol_version"; + vals[max_protocol_version_index] = "3.0"; + + conn = PQconnectdbParams(keywords, vals, false); + + if (PQstatus(conn) != CONNECTION_OK) + pg_fatal("Connection to database failed: %s", + PQerrorMessage(conn)); + + protocol_version = PQfullProtocolVersion(conn); + if (protocol_version != 30000) + pg_fatal("expected 30000, got %d", protocol_version); + + PQfinish(conn); + + vals[max_protocol_version_index] = "3.1"; + conn = PQconnectdbParams(keywords, vals, false); + + if (PQstatus(conn) != CONNECTION_BAD) + pg_fatal("Connecting with max_protocol_version 3.1 should have failed."); + + PQfinish(conn); + + vals[max_protocol_version_index] = "3.2"; + conn = PQconnectdbParams(keywords, vals, false); + + if (PQstatus(conn) != CONNECTION_OK) + pg_fatal("Connection to database failed: %s", + PQerrorMessage(conn)); + + protocol_version = PQfullProtocolVersion(conn); + if (protocol_version != 30002) + pg_fatal("expected 30002, got %d", protocol_version); + PQfinish(conn); + + vals[max_protocol_version_index] = "latest"; + conn = PQconnectdbParams(keywords, vals, false); + + if (PQstatus(conn) != CONNECTION_OK) + pg_fatal("Connection to database failed: %s", + PQerrorMessage(conn)); + + protocol_version = PQfullProtocolVersion(conn); + if (protocol_version != 30002) + pg_fatal("expected 30002, got %d", protocol_version); + PQfinish(conn); +} + /* Notice processor: print notices, and count how many we got */ static void notice_processor(void *arg, const char *message) @@ -2154,6 +2231,7 @@ print_test_list(void) printf("pipeline_idle\n"); printf("pipelined_insert\n"); printf("prepared\n"); + printf("protocol_version\n"); printf("simple_pipeline\n"); printf("singlerow\n"); printf("transaction\n"); @@ -2264,6 +2342,8 @@ main(int argc, char **argv) test_pipelined_insert(conn, numrows); else if (strcmp(testname, "prepared") == 0) test_prepared(conn); + else if (strcmp(testname, "protocol_version") == 0) + test_protocol_version(conn); else if (strcmp(testname, "simple_pipeline") == 0) test_simple_pipeline(conn); else if (strcmp(testname, "singlerow") == 0) -- 2.43.0
v4-0006-Add-timingsafe_bcmp-for-constant-time-memory-comp.patch (text/x-patch, 5.3K) download From 86e307c7534dfdd2b25afac273211e2c63de737c Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas <heikki.linnakangas@iki.fi> Date: Thu, 15 Aug 2024 15:49:46 +0300 Subject: [PATCH v4 6/7] Add timingsafe_bcmp(), for constant-time memory comparison timingsafe_bcmp() should be used instead of memcmp() or a naive for-loop, when comparing passwords or secret tokens, to avoid leaking information about the secret token by timing. This commit just introduces the function but does not change any existing code to use it yet. --- configure | 23 ++++++++++++++++++++ configure.ac | 3 ++- meson.build | 2 ++ src/include/port.h | 4 ++++ src/port/meson.build | 1 + src/port/timingsafe_bcmp.c | 43 ++++++++++++++++++++++++++++++++++++++ 6 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 src/port/timingsafe_bcmp.c diff --git a/configure b/configure index 93fddd69981..73648354a65 100755 --- a/configure +++ b/configure @@ -15792,6 +15792,16 @@ fi cat >>confdefs.h <<_ACEOF #define HAVE_DECL_STRSEP $ac_have_decl _ACEOF +ac_fn_c_check_decl "$LINENO" "timingsafe_bcmp" "ac_cv_have_decl_timingsafe_bcmp" "$ac_includes_default" +if test "x$ac_cv_have_decl_timingsafe_bcmp" = xyes; then : + ac_have_decl=1 +else + ac_have_decl=0 +fi + +cat >>confdefs.h <<_ACEOF +#define HAVE_DECL_TIMINGSAFE_BCMP $ac_have_decl +_ACEOF # We can't use AC_CHECK_FUNCS to detect these functions, because it @@ -15952,6 +15962,19 @@ esac fi +ac_fn_c_check_func "$LINENO" "timingsafe_bcmp" "ac_cv_func_timingsafe_bcmp" +if test "x$ac_cv_func_timingsafe_bcmp" = xyes; then : + $as_echo "#define HAVE_TIMINGSAFE_BCMP 1" >>confdefs.h + +else + case " $LIBOBJS " in + *" timingsafe_bcmp.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS timingsafe_bcmp.$ac_objext" + ;; +esac + +fi + ac_fn_c_check_func "$LINENO" "pthread_barrier_wait" "ac_cv_func_pthread_barrier_wait" diff --git a/configure.ac b/configure.ac index b6d02f5ecc7..af6e237b26d 100644 --- a/configure.ac +++ b/configure.ac @@ -1793,7 +1793,7 @@ AC_CHECK_DECLS(posix_fadvise, [], [], [#include <fcntl.h>]) ]) # fi AC_CHECK_DECLS(fdatasync, [], [], [#include <unistd.h>]) -AC_CHECK_DECLS([strlcat, strlcpy, strnlen, strsep]) +AC_CHECK_DECLS([strlcat, strlcpy, strnlen, strsep, timingsafe_bcmp]) # We can't use AC_CHECK_FUNCS to detect these functions, because it # won't handle deployment target restrictions on macOS @@ -1813,6 +1813,7 @@ AC_REPLACE_FUNCS(m4_normalize([ strlcpy strnlen strsep + timingsafe_bcmp ])) AC_REPLACE_FUNCS(pthread_barrier_wait) diff --git a/meson.build b/meson.build index 13c13748e5d..5a7e77ddbe6 100644 --- a/meson.build +++ b/meson.build @@ -2513,6 +2513,7 @@ decl_checks = [ ['strlcpy', 'string.h'], ['strnlen', 'string.h'], ['strsep', 'string.h'], + ['timingsafe_bcmp', 'string.h'], ] # Need to check for function declarations for these functions, because @@ -2754,6 +2755,7 @@ func_checks = [ ['strsignal'], ['sync_file_range'], ['syncfs'], + ['timingsafe_bcmp'], ['uselocale'], ['wcstombs_l'], ] diff --git a/src/include/port.h b/src/include/port.h index 703cad868ba..8db8b9f2a6f 100644 --- a/src/include/port.h +++ b/src/include/port.h @@ -464,6 +464,10 @@ extern size_t strnlen(const char *str, size_t maxlen); extern char *strsep(char **stringp, const char *delim); #endif +#if !HAVE_DECL_TIMINGSAFE_BCMP +extern int timingsafe_bcmp(const void *b1, const void *b2, size_t len); +#endif + /* * Callers should use the qsort() macro defined below instead of calling * pg_qsort() directly. diff --git a/src/port/meson.build b/src/port/meson.build index 7fcfa728d43..16134bb6065 100644 --- a/src/port/meson.build +++ b/src/port/meson.build @@ -71,6 +71,7 @@ replace_funcs_neg = [ ['strlcpy'], ['strnlen'], ['strsep'], + ['timingsafe_bcmp'], ] if host_system != 'windows' diff --git a/src/port/timingsafe_bcmp.c b/src/port/timingsafe_bcmp.c new file mode 100644 index 00000000000..288865f50d1 --- /dev/null +++ b/src/port/timingsafe_bcmp.c @@ -0,0 +1,43 @@ +/* + * src/port/timingsafe_bcmp.c + * + * $OpenBSD: timingsafe_bcmp.c,v 1.3 2015/08/31 02:53:57 guenther Exp $ + */ + +/* + * Copyright (c) 2010 Damien Miller. All rights reserved. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include "c.h" + +#ifdef USE_SSL +#include <openssl/crypto.h> +#endif + +int +timingsafe_bcmp(const void *b1, const void *b2, size_t n) +{ +#ifdef USE_SSL + return CRYPTO_memcmp(b1, b2, n); +#else + const unsigned char *p1 = b1, + *p2 = b2; + int ret = 0; + + for (; n > 0; n--) + ret |= *p1++ ^ *p2++; + return (ret != 0); +#endif +} -- 2.43.0
v4-0007-Make-cancel-request-keys-longer.patch (text/x-patch, 26.7K) download From 6d5332914bfd0562708151fc0b4033dfd6bb356a Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas <heikki.linnakangas@iki.fi> Date: Thu, 15 Aug 2024 19:49:29 +0300 Subject: [PATCH v4 7/7] Make cancel request keys longer Currently, cancel request key is 32-bit token, which isn't very much entropy. If you want to cancel another session's query, you can brute-force it. In most environments, an unauthorized cancellation of a query isn't very serious, but it nevertheless would be nice to have more protection from it. Hence make the key longer, to make it harder to guess. The new longer key length is not hardcoded in the protocol anymore, the client is expected to deal with variable length keys, up to some reasonable upper limit (TODO: document the maximum). This flexibility allows e.g. a connection pooler to add more information to the cancel key, which might be useful for finding the connection. Reviewed-by: Jelte Fennema-Nio Discussion: https://www.postgresql.org/message-id/508d0505-8b7a-4864-a681-e7e5edfe32aa@iki.fi --- doc/src/sgml/protocol.sgml | 19 +++- src/backend/storage/ipc/procsignal.c | 23 ++-- src/backend/tcop/backend_startup.c | 55 ++++++---- src/backend/tcop/postgres.c | 15 ++- src/backend/utils/init/globals.c | 5 +- src/backend/utils/init/postinit.c | 2 +- src/include/libpq/pqcomm.h | 7 +- src/include/miscadmin.h | 4 +- src/include/storage/procsignal.h | 14 ++- src/interfaces/libpq/fe-cancel.c | 102 ++++++++++++++---- src/interfaces/libpq/fe-connect.c | 20 ++-- src/interfaces/libpq/fe-protocol3.c | 45 +++++++- src/interfaces/libpq/libpq-int.h | 7 +- .../libpq_pipeline/t/001_libpq_pipeline.pl | 12 ++- src/tools/pgindent/typedefs.list | 1 + 15 files changed, 247 insertions(+), 84 deletions(-) diff --git a/doc/src/sgml/protocol.sgml b/doc/src/sgml/protocol.sgml index 6bb97dbba55..a5dc8721bc3 100644 --- a/doc/src/sgml/protocol.sgml +++ b/doc/src/sgml/protocol.sgml @@ -49,6 +49,13 @@ supported by the server. </para> + <para> + The difference between protocol version 3.0 and 3.2 is that the secret key + used in query cancellation was enlarged from 4 bytes to a variable length + field. The BackendKeyData message was changed to accomodate that, and the + CancelRequest message was redefined to have a variable length payload. + </para> + <para> In order to serve multiple clients efficiently, the server launches a new <quote>backend</quote> process for each client. @@ -4064,7 +4071,7 @@ psql "dbname=postgres replication=database" -c "IDENTIFY_SYSTEM;" </varlistentry> <varlistentry> - <term>Int32(12)</term> + <term>Int32</term> <listitem> <para> Length of message contents in bytes, including self. @@ -4082,7 +4089,7 @@ psql "dbname=postgres replication=database" -c "IDENTIFY_SYSTEM;" </varlistentry> <varlistentry> - <term>Int32</term> + <term>Byten</term> <listitem> <para> The secret key of this backend. @@ -4295,14 +4302,18 @@ psql "dbname=postgres replication=database" -c "IDENTIFY_SYSTEM;" </varlistentry> <varlistentry> - <term>Int32</term> + <term>Byte4</term> <listitem> <para> - The secret key for the target backend. + The secret key for the target backend. This field extends to the end of the + message, indicated by the length field. The maximum key length is 256 bytes. </para> </listitem> </varlistentry> </variablelist> + <para> + Before protocol version 3.2, the secret key was always 4 bytes long. + </para> </listitem> </varlistentry> diff --git a/src/backend/storage/ipc/procsignal.c b/src/backend/storage/ipc/procsignal.c index 7401b6e625e..6ad800c717e 100644 --- a/src/backend/storage/ipc/procsignal.c +++ b/src/backend/storage/ipc/procsignal.c @@ -63,8 +63,8 @@ typedef struct { pg_atomic_uint32 pss_pid; - bool pss_cancel_key_valid; - int32 pss_cancel_key; + int pss_cancel_key_len; /* 0 means no cancellation is possible */ + char pss_cancel_key[MAX_CANCEL_KEY_LENGTH]; volatile sig_atomic_t pss_signalFlags[NUM_PROCSIGNALS]; slock_t pss_mutex; /* protects the above fields */ @@ -148,8 +148,7 @@ ProcSignalShmemInit(void) SpinLockInit(&slot->pss_mutex); pg_atomic_init_u32(&slot->pss_pid, 0); - slot->pss_cancel_key_valid = false; - slot->pss_cancel_key = 0; + slot->pss_cancel_key_len = 0; MemSet(slot->pss_signalFlags, 0, sizeof(slot->pss_signalFlags)); pg_atomic_init_u64(&slot->pss_barrierGeneration, PG_UINT64_MAX); pg_atomic_init_u32(&slot->pss_barrierCheckMask, 0); @@ -163,11 +162,12 @@ ProcSignalShmemInit(void) * Register the current process in the ProcSignal array */ void -ProcSignalInit(bool cancel_key_valid, int32 cancel_key) +ProcSignalInit(char *cancel_key, int cancel_key_len) { ProcSignalSlot *slot; uint64 barrier_generation; + Assert(cancel_key_len >= 0 && cancel_key_len <= MAX_CANCEL_KEY_LENGTH); if (MyProcNumber < 0) elog(ERROR, "MyProcNumber not set"); if (MyProcNumber >= NumProcSignalSlots) @@ -202,8 +202,9 @@ ProcSignalInit(bool cancel_key_valid, int32 cancel_key) pg_atomic_read_u64(&ProcSignal->psh_barrierGeneration); pg_atomic_write_u64(&slot->pss_barrierGeneration, barrier_generation); - slot->pss_cancel_key_valid = cancel_key_valid; - slot->pss_cancel_key = cancel_key; + if (cancel_key_len > 0) + memcpy(slot->pss_cancel_key, cancel_key, cancel_key_len); + slot->pss_cancel_key_len = cancel_key_len; pg_atomic_write_u32(&slot->pss_pid, MyProcPid); SpinLockRelease(&slot->pss_mutex); @@ -252,8 +253,7 @@ CleanupProcSignalState(int status, Datum arg) /* Mark the slot as unused */ pg_atomic_write_u32(&slot->pss_pid, 0); - slot->pss_cancel_key_valid = false; - slot->pss_cancel_key = 0; + slot->pss_cancel_key_len = 0; /* * Make this slot look like it's absorbed all possible barriers, so that @@ -723,7 +723,7 @@ procsignal_sigusr1_handler(SIGNAL_ARGS) * fields in the ProcSignal slots. */ void -SendCancelRequest(int backendPID, int32 cancelAuthCode) +SendCancelRequest(int backendPID, char *cancel_key, int cancel_key_len) { Assert(backendPID != 0); @@ -752,7 +752,8 @@ SendCancelRequest(int backendPID, int32 cancelAuthCode) } else { - match = slot->pss_cancel_key_valid && slot->pss_cancel_key == cancelAuthCode; + match = slot->pss_cancel_key_len == cancel_key_len && + timingsafe_bcmp(slot->pss_cancel_key, cancel_key, cancel_key_len) == 0; SpinLockRelease(&slot->pss_mutex); diff --git a/src/backend/tcop/backend_startup.c b/src/backend/tcop/backend_startup.c index 9ee738eb1e0..b73cec88721 100644 --- a/src/backend/tcop/backend_startup.c +++ b/src/backend/tcop/backend_startup.c @@ -45,6 +45,7 @@ bool Trace_connection_negotiation = false; static void BackendInitialize(ClientSocket *client_sock, CAC_state cac); static int ProcessSSLStartup(Port *port); static int ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done); +static void ProcessCancelRequestPacket(Port *port, void *pkt, int pktlen); static void SendNegotiateProtocolVersion(List *unrecognized_protocol_options); static void process_startup_packet_die(SIGNAL_ARGS); static void StartupPacketTimeoutHandler(void); @@ -542,28 +543,7 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done) if (proto == CANCEL_REQUEST_CODE) { - /* - * The client has sent a cancel request packet, not a normal - * start-a-new-connection packet. Perform the necessary processing. - * Nothing is sent back to the client. - */ - CancelRequestPacket *canc; - int backendPID; - int32 cancelAuthCode; - - if (len != sizeof(CancelRequestPacket)) - { - ereport(COMMERROR, - (errcode(ERRCODE_PROTOCOL_VIOLATION), - errmsg("invalid length of startup packet"))); - return STATUS_ERROR; - } - canc = (CancelRequestPacket *) buf; - backendPID = (int) pg_ntoh32(canc->backendPID); - cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode); - - if (backendPID != 0) - SendCancelRequest(backendPID, cancelAuthCode); + ProcessCancelRequestPacket(port, buf, len); /* Not really an error, but we don't want to proceed further */ return STATUS_ERROR; } @@ -863,6 +843,37 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done) return STATUS_OK; } +/* + * The client has sent a cancel request packet, not a normal + * start-a-new-connection packet. Perform the necessary processing. Nothing + * is sent back to the client. + */ +static void +ProcessCancelRequestPacket(Port *port, void *pkt, int pktlen) +{ + CancelRequestPacket *canc; + int len; + + if (pktlen < offsetof(CancelRequestPacket, cancelAuthCode)) + { + ereport(COMMERROR, + (errcode(ERRCODE_PROTOCOL_VIOLATION), + errmsg("invalid length of query cancel packet"))); + return; + } + len = pktlen - offsetof(CancelRequestPacket, cancelAuthCode); + if (len == 0 || len > 256) + { + ereport(COMMERROR, + (errcode(ERRCODE_PROTOCOL_VIOLATION), + errmsg("invalid length of query cancel key"))); + return; + } + + canc = (CancelRequestPacket *) pkt; + SendCancelRequest(pg_ntoh32(canc->backendPID), canc->cancelAuthCode, len); +} + /* * Send a NegotiateProtocolVersion to the client. This lets the client know * that they have either requested a newer minor protocol version than we are diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c index f2f75aa0f88..ef413b33227 100644 --- a/src/backend/tcop/postgres.c +++ b/src/backend/tcop/postgres.c @@ -4225,16 +4225,20 @@ PostgresMain(const char *dbname, const char *username) * Generate a random cancel key, if this is a backend serving a * connection. InitPostgres() will advertise it in shared memory. */ - Assert(!MyCancelKeyValid); + Assert(MyCancelKeyLength == 0); if (whereToSendOutput == DestRemote) { - if (!pg_strong_random(&MyCancelKey, sizeof(int32))) + int len; + + len = (MyProcPort == NULL || MyProcPort->proto >= PG_PROTOCOL(3, 1)) + ? MAX_CANCEL_KEY_LENGTH : 4; + if (!pg_strong_random(&MyCancelKey, len)) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("could not generate random cancel key"))); } - MyCancelKeyValid = true; + MyCancelKeyLength = len; } /* @@ -4289,10 +4293,11 @@ PostgresMain(const char *dbname, const char *username) { StringInfoData buf; - Assert(MyCancelKeyValid); + Assert(MyCancelKeyLength > 0); pq_beginmessage(&buf, PqMsg_BackendKeyData); pq_sendint32(&buf, (int32) MyProcPid); - pq_sendint32(&buf, (int32) MyCancelKey); + + pq_sendbytes(&buf, MyCancelKey, MyCancelKeyLength); pq_endmessage(&buf); /* Need not flush since ReadyForQuery will do it. */ } diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c index b844f9fdaef..2152aad97d9 100644 --- a/src/backend/utils/init/globals.c +++ b/src/backend/utils/init/globals.c @@ -24,6 +24,7 @@ #include "miscadmin.h" #include "postmaster/postmaster.h" #include "storage/procnumber.h" +#include "storage/procsignal.h" ProtocolVersion FrontendProtocol; @@ -48,8 +49,8 @@ pg_time_t MyStartTime; TimestampTz MyStartTimestamp; struct ClientSocket *MyClientSocket; struct Port *MyProcPort; -bool MyCancelKeyValid = false; -int32 MyCancelKey = 0; +char MyCancelKey[MAX_CANCEL_KEY_LENGTH]; +uint8 MyCancelKeyLength = 0; int MyPMChildSlot; /* diff --git a/src/backend/utils/init/postinit.c b/src/backend/utils/init/postinit.c index 01bb6a410cb..a59871422cb 100644 --- a/src/backend/utils/init/postinit.c +++ b/src/backend/utils/init/postinit.c @@ -723,7 +723,7 @@ InitPostgres(const char *in_dbname, Oid dboid, */ SharedInvalBackendInit(false); - ProcSignalInit(MyCancelKeyValid, MyCancelKey); + ProcSignalInit(MyCancelKey, MyCancelKeyLength); /* * Also set up timeout handlers needed for backend operation. We need diff --git a/src/include/libpq/pqcomm.h b/src/include/libpq/pqcomm.h index 0aceb7147c7..d0f2c1fb03a 100644 --- a/src/include/libpq/pqcomm.h +++ b/src/include/libpq/pqcomm.h @@ -128,7 +128,11 @@ typedef uint32 AuthRequest; * * The cancel request code must not match any protocol version number * we're ever likely to use. This random choice should do. + * + * Before PostgreSQL v17 and the protocol version bump from 3.0 to 3.1, the + * cancel key was always 4 bytes. Starting with v17, it's variable length. */ + #define CANCEL_REQUEST_CODE PG_PROTOCOL(1234,5678) typedef struct CancelRequestPacket @@ -136,7 +140,8 @@ typedef struct CancelRequestPacket /* Note that each field is stored in network byte order! */ MsgType cancelRequestCode; /* code to identify a cancel request */ uint32 backendPID; /* PID of client's backend */ - uint32 cancelAuthCode; /* secret key to authorize cancel */ + char cancelAuthCode[FLEXIBLE_ARRAY_MEMBER]; /* secret key to + * authorize cancel */ } CancelRequestPacket; /* Application-Layer Protocol Negotiation is required for direct connections diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h index a2b63495eec..2eda5b0bd4d 100644 --- a/src/include/miscadmin.h +++ b/src/include/miscadmin.h @@ -191,8 +191,8 @@ extern PGDLLIMPORT pg_time_t MyStartTime; extern PGDLLIMPORT TimestampTz MyStartTimestamp; extern PGDLLIMPORT struct Port *MyProcPort; extern PGDLLIMPORT struct Latch *MyLatch; -extern PGDLLIMPORT bool MyCancelKeyValid; -extern PGDLLIMPORT int32 MyCancelKey; +extern PGDLLIMPORT char MyCancelKey[]; +extern PGDLLIMPORT uint8 MyCancelKeyLength; extern PGDLLIMPORT int MyPMChildSlot; extern PGDLLIMPORT char OutputFileName[]; diff --git a/src/include/storage/procsignal.h b/src/include/storage/procsignal.h index 022fd8ed933..b14c9252582 100644 --- a/src/include/storage/procsignal.h +++ b/src/include/storage/procsignal.h @@ -56,16 +56,26 @@ typedef enum PROCSIGNAL_BARRIER_SMGRRELEASE, /* ask smgr to close files */ } ProcSignalBarrierType; +/* + * Length of query cancel keys generated. + * + * Note that the protocol allows for longer keys, or shorter, but this is the + * length we actually generate. Client code, and the server code that handles + * incoming cancellation packets from clients, cannot use this hardcoded + * length. + */ +#define MAX_CANCEL_KEY_LENGTH 32 + /* * prototypes for functions in procsignal.c */ extern Size ProcSignalShmemSize(void); extern void ProcSignalShmemInit(void); -extern void ProcSignalInit(bool cancel_key_valid, int32 cancel_key); +extern void ProcSignalInit(char *cancel_key, int cancel_key_len); extern int SendProcSignal(pid_t pid, ProcSignalReason reason, ProcNumber procNumber); -extern void SendCancelRequest(int backendPID, int32 cancelAuthCode); +extern void SendCancelRequest(int backendPID, char *cancel_key, int cancel_key_len); extern uint64 EmitProcSignalBarrier(ProcSignalBarrierType type); extern void WaitForProcSignalBarrier(uint64 generation); diff --git a/src/interfaces/libpq/fe-cancel.c b/src/interfaces/libpq/fe-cancel.c index 7ebaa335bba..e84e64bf2a7 100644 --- a/src/interfaces/libpq/fe-cancel.c +++ b/src/interfaces/libpq/fe-cancel.c @@ -1,7 +1,7 @@ /*------------------------------------------------------------------------- * * fe-cancel.c - * functions related to setting up a connection to the backend + * functions related to query cancellation * * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California @@ -41,7 +41,6 @@ struct pg_cancel { SockAddr raddr; /* Remote address */ int be_pid; /* PID of to-be-canceled backend */ - int be_key; /* cancel key of to-be-canceled backend */ int pgtcp_user_timeout; /* tcp user timeout */ int keepalives; /* use TCP keepalives? */ int keepalives_idle; /* time between TCP keepalives */ @@ -49,6 +48,10 @@ struct pg_cancel * retransmits */ int keepalives_count; /* maximum number of TCP keepalive * retransmits */ + + /* Pre-constructed cancel request packet starts here */ + int32 cancel_pkt_len; /* in network-byte-order */ + char cancel_req[FLEXIBLE_ARRAY_MEMBER]; /* CancelRequestPacket */ }; @@ -83,6 +86,13 @@ PQcancelCreate(PGconn *conn) return (PGcancelConn *) cancelConn; } + /* Check that we have received a cancellation key */ + if (conn->be_cancel_key_len == 0) + { + libpq_append_conn_error(cancelConn, "no cancellation key received"); + return (PGcancelConn *) cancelConn; + } + /* * Indicate that this connection is used to send a cancellation */ @@ -101,7 +111,15 @@ PQcancelCreate(PGconn *conn) * Copy cancellation token data from the original connection */ cancelConn->be_pid = conn->be_pid; - cancelConn->be_key = conn->be_key; + if (conn->be_cancel_key != NULL) + { + cancelConn->be_cancel_key = malloc(conn->be_cancel_key_len); + if (!conn->be_cancel_key) + goto oom_error; + memcpy(cancelConn->be_cancel_key, conn->be_cancel_key, conn->be_cancel_key_len); + } + cancelConn->be_cancel_key_len = conn->be_cancel_key_len; + cancelConn->pversion = conn->pversion; /* * Cancel requests should not iterate over all possible hosts. The request @@ -349,6 +367,8 @@ PGcancel * PQgetCancel(PGconn *conn) { PGcancel *cancel; + int cancel_req_len; + CancelRequestPacket *req; if (!conn) return NULL; @@ -356,13 +376,17 @@ PQgetCancel(PGconn *conn) if (conn->sock == PGINVALID_SOCKET) return NULL; - cancel = malloc(sizeof(PGcancel)); + /* Check that we have received a cancellation key */ + if (conn->be_cancel_key_len == 0) + return NULL; + + cancel_req_len = offsetof(CancelRequestPacket, cancelAuthCode) + conn->be_cancel_key_len; + cancel = malloc(offsetof(PGcancel, cancel_req) + cancel_req_len); if (cancel == NULL) return NULL; memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr)); - cancel->be_pid = conn->be_pid; - cancel->be_key = conn->be_key; + /* We use -1 to indicate an unset connection option */ cancel->pgtcp_user_timeout = -1; cancel->keepalives = -1; @@ -405,6 +429,13 @@ PQgetCancel(PGconn *conn) goto fail; } + req = (CancelRequestPacket *) &cancel->cancel_req; + req->cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE); + req->backendPID = pg_hton32(conn->be_pid); + memcpy(req->cancelAuthCode, conn->be_cancel_key, conn->be_cancel_key_len); + /* include the length field itself in the length */ + cancel->cancel_pkt_len = pg_hton32(cancel_req_len + 4); + return cancel; fail: @@ -412,6 +443,42 @@ fail: return NULL; } +/* + * PQsendCancelRequest + * Submit a CancelRequest message, but don't wait for it to finish + * + * Returns: 1 if successfully submitted + * 0 if error (conn->errorMessage is set) + */ +int +PQsendCancelRequest(PGconn *cancelConn) +{ + CancelRequestPacket req; + + /* Start the message. */ + if (pqPutMsgStart(0, cancelConn)) + return STATUS_ERROR; + + /* Send the message body. */ + memset(&req, 0, offsetof(CancelRequestPacket, cancelAuthCode)); + req.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE); + req.backendPID = pg_hton32(cancelConn->be_pid); + if (pqPutnchar((char *) &req, offsetof(CancelRequestPacket, cancelAuthCode), cancelConn)) + return STATUS_ERROR; + if (pqPutnchar(cancelConn->be_cancel_key, cancelConn->be_cancel_key_len, cancelConn)) + return STATUS_ERROR; + + /* Finish the message. */ + if (pqPutMsgEnd(cancelConn)) + return STATUS_ERROR; + + /* Flush to ensure backend gets it. */ + if (pqFlush(cancelConn)) + return STATUS_ERROR; + + return STATUS_OK; +} + /* PQfreeCancel: free a cancel structure */ void PQfreeCancel(PGcancel *cancel) @@ -465,11 +532,8 @@ PQcancel(PGcancel *cancel, char *errbuf, int errbufsize) int save_errno = SOCK_ERRNO; pgsocket tmpsock = PGINVALID_SOCKET; int maxlen; - struct - { - uint32 packetlen; - CancelRequestPacket cp; - } crp; + char recvbuf; + int cancel_pkt_len; if (!cancel) { @@ -571,15 +635,15 @@ retry3: goto cancel_errReturn; } - /* Create and send the cancel request packet. */ - - crp.packetlen = pg_hton32((uint32) sizeof(crp)); - crp.cp.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE); - crp.cp.backendPID = pg_hton32(cancel->be_pid); - crp.cp.cancelAuthCode = pg_hton32(cancel->be_key); + cancel_pkt_len = pg_ntoh32(cancel->cancel_pkt_len); retry4: - if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp)) + + /* + * Send the cancel request packet. It starts with the message length at + * cancel_pkt_len, followed by the actual packet. + */ + if (send(tmpsock, (char *) &cancel->cancel_pkt_len, cancel_pkt_len, 0) != cancel_pkt_len) { if (SOCK_ERRNO == EINTR) /* Interrupted system call - we'll just try again */ @@ -596,7 +660,7 @@ retry4: * read to obtain any data, we are just waiting for EOF to be signaled. */ retry5: - if (recv(tmpsock, (char *) &crp, 1, 0) < 0) + if (recv(tmpsock, &recvbuf, 1, 0) < 0) { if (SOCK_ERRNO == EINTR) /* Interrupted system call - we'll just try again */ diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index 559964a6a25..1423311b1ee 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -695,7 +695,12 @@ pqDropServerData(PGconn *conn) if (!conn->cancelRequest) { conn->be_pid = 0; - conn->be_key = 0; + if (conn->be_cancel_key != NULL) + { + free(conn->be_cancel_key); + conn->be_cancel_key = NULL; + } + conn->be_cancel_key_len = 0; } } @@ -3685,13 +3690,7 @@ keep_going: /* We will come back to here until there is */ if (conn->cancelRequest) { - CancelRequestPacket cancelpacket; - - packetlen = sizeof(cancelpacket); - cancelpacket.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE); - cancelpacket.backendPID = pg_hton32(conn->be_pid); - cancelpacket.cancelAuthCode = pg_hton32(conn->be_key); - if (pqPacketSend(conn, 0, &cancelpacket, packetlen) != STATUS_OK) + if (PQsendCancelRequest(conn) != STATUS_OK) { libpq_append_conn_error(conn, "could not send cancel packet: %s", SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); @@ -4135,7 +4134,10 @@ keep_going: /* We will come back to here until there is { if (pqGetNegotiateProtocolVersion3(conn)) { - libpq_append_conn_error(conn, "received invalid protocol negotiation message"); + /* + * Negotiation failed. The error message was filled + * in already. + */ goto error_return; } diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c index f33766c7df4..d7570705bc4 100644 --- a/src/interfaces/libpq/fe-protocol3.c +++ b/src/interfaces/libpq/fe-protocol3.c @@ -48,6 +48,7 @@ static int getRowDescriptions(PGconn *conn, int msgLength); static int getParamDescriptions(PGconn *conn, int msgLength); static int getAnotherTuple(PGconn *conn, int msgLength); static int getParameterStatus(PGconn *conn); +static int getBackendKeyData(PGconn *conn, int msgLength); static int getNotify(PGconn *conn); static int getCopyStart(PGconn *conn, ExecStatusType copytype); static int getReadyForQuery(PGconn *conn); @@ -308,9 +309,7 @@ pqParseInput3(PGconn *conn) * just as easy to handle it as part of the main loop. * Save the data and continue processing. */ - if (pqGetInt(&(conn->be_pid), 4, conn)) - return; - if (pqGetInt(&(conn->be_key), 4, conn)) + if (getBackendKeyData(conn, msgLength)) return; break; case PqMsg_RowDescription: @@ -1514,6 +1513,46 @@ getParameterStatus(PGconn *conn) return 0; } +/* + * parseInput subroutine to read a BackendKeyData message. + * Entry: 'v' message type and length have already been consumed. + * Exit: returns 0 if successfully consumed message. + * returns EOF if not enough data. + */ +static int +getBackendKeyData(PGconn *conn, int msgLength) +{ + uint8 cancel_key_len; + + if (conn->be_cancel_key) + { + free(conn->be_cancel_key); + conn->be_cancel_key = NULL; + conn->be_cancel_key_len = 0; + } + + if (pqGetInt(&(conn->be_pid), 4, conn)) + return EOF; + + cancel_key_len = 5 + msgLength - (conn->inCursor - conn->inStart); + + conn->be_cancel_key = malloc(cancel_key_len); + if (conn->be_cancel_key == NULL) + { + libpq_append_conn_error(conn, "out of memory"); + /* discard the message */ + return EOF; + } + if (pqGetnchar(conn->be_cancel_key, cancel_key_len, conn)) + { + free(conn->be_cancel_key); + conn->be_cancel_key = NULL; + return EOF; + } + conn->be_cancel_key_len = cancel_key_len; + return 0; +} + /* * Attempt to read a Notify response message. diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index c016408338a..587315ad890 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -552,7 +552,8 @@ struct pg_conn /* Miscellaneous stuff */ int be_pid; /* PID of backend --- needed for cancels */ - int be_key; /* key of backend --- needed for cancels */ + char *be_cancel_key; /* query cancellation key and its length */ + uint16 be_cancel_key_len; pgParameterStatus *pstatus; /* ParameterStatus data */ int client_encoding; /* encoding id */ bool std_strings; /* standard_conforming_strings */ @@ -772,6 +773,10 @@ extern PGresult *pqFunctionCall3(PGconn *conn, Oid fnid, int result_is_int, const PQArgBlock *args, int nargs); +/* === in fe-cancel.c === */ + +extern int PQsendCancelRequest(PGconn *cancelConn); + /* === in fe-misc.c === */ /* diff --git a/src/test/modules/libpq_pipeline/t/001_libpq_pipeline.pl b/src/test/modules/libpq_pipeline/t/001_libpq_pipeline.pl index e301c378264..d900355c5cf 100644 --- a/src/test/modules/libpq_pipeline/t/001_libpq_pipeline.pl +++ b/src/test/modules/libpq_pipeline/t/001_libpq_pipeline.pl @@ -49,11 +49,11 @@ for my $testname (@tests) push @extraargs, "-t", $traceout; } - # Execute the test + # Execute the test using the latest protocol version. $node->command_ok( [ 'libpq_pipeline', @extraargs, - $testname, $node->connstr('postgres') + $testname, $node->connstr('postgres') . " max_protocol_version=latest" ], "libpq_pipeline $testname"); @@ -72,6 +72,14 @@ for my $testname (@tests) } } +# There were changes to query cancellation in protocol version 3.2, so +# test separately that it still works the old protocol version too. +$node->command_ok( + [ + 'libpq_pipeline', 'cancel', $node->connstr('postgres') . " max_protocol_version=3.0" + ], + "libpq_pipeline cancel with protocol 3.0"); + $node->stop('fast'); done_testing(); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b09d8af7183..cdf0d5dff2b 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -382,6 +382,7 @@ CachedPlanSource CallContext CallStmt CancelRequestPacket +CancelRequestExtendedPacket Cardinality CaseExpr CaseKind -- 2.43.0
^ permalink raw reply [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2025-02-24 17:24  Robert Haas <robertmhaas@gmail.com>
  parent: Jelte Fennema-Nio <postgres@jeltef.nl>
  1 sibling, 1 reply; 40+ messages in thread

From: Robert Haas @ 2025-02-24 17:24 UTC (permalink / raw)
  To: Jelte Fennema-Nio <postgres@jeltef.nl>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>

On Sat, Feb 22, 2025 at 9:58 AM Jelte Fennema-Nio <postgres@jeltef.nl> wrote:
> My patchset in the other protocol thread needed a rebase. So I took
> that as an opportunity to rebase this patchset on top of it, because
> this seems to be the protocol change that we can most easily push over
> the finish line.

I'm still not really convinced about that -- see comments upthread --
but I committed 0001 and 0002, which appear to be straightforward bug
fixes.

-- 
Robert Haas
EDB: http://www.enterprisedb.com





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2025-02-25 14:28  Jelte Fennema-Nio <postgres@jeltef.nl>
  parent: Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 40+ messages in thread

From: Jelte Fennema-Nio @ 2025-02-25 14:28 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>

On Mon, 24 Feb 2025 at 18:24, Robert Haas <robertmhaas@gmail.com> wrote:
>
> On Sat, Feb 22, 2025 at 9:58 AM Jelte Fennema-Nio <postgres@jeltef.nl> wrote:
> > My patchset in the other protocol thread needed a rebase. So I took
> > that as an opportunity to rebase this patchset on top of it, because
> > this seems to be the protocol change that we can most easily push over
> > the finish line.
>
> I'm still not really convinced about that -- see comments upthread --

You've said quite a few things upthread, so I'm going to assume you
are referring to the following. If that's not the case could you
please quote the part of the thread that you think is important:

On Wed, 5 Jun 2024 at 17:26, Robert Haas <robertmhaas@gmail.com> wrote:
> I think we shouldn't underestimate the impact of bumping the minor
> protocol version. Minor version negotiation is probably not supported
> by all drivers and Jelte says that it's not supported by any poolers,
> so for anybody but direct libpq users, there will be some breakage.
> Now, on the one hand, as Jelte has said, there's little value in
> having a protocol version if we're too afraid to make use of it. But
> on the other hand, is this problem serious enough to justify the
> breakage we'll cause? I'm not sure. It seems pretty silly to be using
> a 32-bit value for this in 2024, but I'm sure some people aren't going
> to like it, and they may not all have noticed this thread. On the
> third hand, if we do this, it may help to unblock a bunch of other
> pending patches that also want to do protocol-related things.

So to be clear: the current patchset *does not* change any client
defaults. libpq will still connect to a server using the protocol
version 3.0 by default. It will only connect with 3.2 unless
instructed explicitly in the connection string using
min/max_protocol_version. So no breakage by default is going to
happen, and very few users will hit any breakage at all, because they
won't change the default.

The reason I think that this longer cancel key change is the easiest
protocol change to get through, is precisely because it's a really
minor change that almost no-one actually cares about. Don't get me
wrong, it's useful feature from a security perspective, and for people
implementing poolers, but for both of those it's a relatively minor
benefit.

To me the main feature of doing this change, is to nudge poolers and
other servers to implement the NegotiateProtocolVersion feature. I
think there are two reasons why no server except Postgres has
implemented it:
1. There was no immediate usecase, because there was no new protocol
version in sight that would be useful to them.
2. There was no easy way to test this. They would need to recompile
libpq/psql to be able to send a different protocol version.

Both of those would be addressed by getting this really minor change
in. 1 would be addressed, because this change is a signal that we
intend to do more useful protocol changes in the somewhat near future.
And 2 is addressed because you can now send 2 different protocol
versions with a single psql binary. So by releasing this the ecosystem
is able to catch up to Postgres its NegotiateProtocolVersion support,
which will mean much less breakage in the future when we make a
protocol change that users will actively want to use (e.g. because
it's a feature they care about or makes their queries faster).

> but I committed 0001 and 0002, which appear to be straightforward bug
> fixes.

Nice.





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2025-02-26 20:18  Robert Haas <robertmhaas@gmail.com>
  parent: Jelte Fennema-Nio <postgres@jeltef.nl>
  0 siblings, 0 replies; 40+ messages in thread

From: Robert Haas @ 2025-02-26 20:18 UTC (permalink / raw)
  To: Jelte Fennema-Nio <postgres@jeltef.nl>; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>

On Tue, Feb 25, 2025 at 9:28 AM Jelte Fennema-Nio <postgres@jeltef.nl> wrote:
> So to be clear: the current patchset *does not* change any client
> defaults. libpq will still connect to a server using the protocol
> version 3.0 by default. It will only connect with 3.2 unless
> instructed explicitly in the connection string using
> min/max_protocol_version. So no breakage by default is going to
> happen, and very few users will hit any breakage at all, because they
> won't change the default.

Ah, interesting. I didn't realize that you had done this in a way
where it wasn't enabled by default. I think that's different from what
was proposed before, but maybe I'm not remembering correctly.

-- 
Robert Haas
EDB: http://www.enterprisedb.com





^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2025-04-01 14:08  Heikki Linnakangas <hlinnaka@iki.fi>
  parent: Jelte Fennema-Nio <postgres@jeltef.nl>
  1 sibling, 1 reply; 40+ messages in thread

From: Heikki Linnakangas @ 2025-04-01 14:08 UTC (permalink / raw)
  To: Jelte Fennema-Nio <postgres@jeltef.nl>; Robert Haas <robertmhaas@gmail.com>; +Cc: pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>

On 22/02/2025 16:58, Jelte Fennema-Nio wrote:
> On Mon, 9 Sept 2024 at 17:58, Robert Haas <robertmhaas@gmail.com> wrote:
>>
>> On Fri, Aug 16, 2024 at 11:29 AM Robert Haas <robertmhaas@gmail.com> wrote:
>>>> I'll split this patch like that, to make it easier to compare and merge
>>>> with Jelte's corresponding patches.
>>>
>>> That sounds great. IMHO, comparing and merging the patches is the next
>>> step here and would be great to see.
>>
>> Heikki, do you have any update on this work?
> 
> My patchset in the other protocol thread needed a rebase. So I took
> that as an opportunity to rebase this patchset on top of it, because
> this seems to be the protocol change that we can most easily push over
> the finish line.
> 
> 1. I changed the last patch from Heikki to only contain the changes
> for the cancel lengthening. The general protocol change related things
> I merged with mine (I only kept some error handling and docs).
> 2. I also removed the length field in the new BackendKey definition,
> eventhough I asked for that addition previously. I agree with Heikki
> that it's actually easier to parse and create without, because you can
> use the same code for both versions.
> 3. I made our timingsafe_bcmp implementation call into OpenSSL's CRYPTO_memcmp.

Great, thanks!

I spent some time going over this again, making tiny fixes here and 
there. A couple of somewhat notable fixes:

- fixed the "server only supports protocol version %d.%d, but 
min_protocol_version was set to %d.%d" message to print the server's 
protocol version correctly
- error out if the server sends two NegotiateProtocolVersion messages 
for some reason
- added a new "protocol versions" subsection to the docs, moving the 
existing paragraphs related to version negotiation there. I also added a 
table to list the different protocol versions. See the last patch in the 
series.

I'm a bit disappointed that we're not changing the default protocol 
version to 3.2 yet. It will receive very little usage in practice until 
we do. But that seems to be the least objectionable path forward.

I think this is pretty much ready for commit. I will go over it one more 
time, and plan to push tomorrow.

> One open question on the last patch is: Document what the maximum size
> of the cancel key is that the client can expect? I think Jacob might
> have some ideas on that.

It's documented as 256 bytes now. But that still leaves one remaining 
question: the idea is that the maximum size is long enough that 
middleware can add their data to it, and still include the original 
server's key. As the patch stands, the server creates 32 byte keys, 
leaving 224 for middleware. But that's not documented anywhere. I'm 
inclined to document that the server only uses up to 32 bytes, and 
middleware should likewise try to "add" only 32 bytes or so to the key, 
so that you can stack multiple such middleware without exceeding the 
total length. And perhaps 256 bytes is still too small, if you consider 
such stacking.

-- 
Heikki Linnakangas
Neon (https://neon.tech)

Attachments: download all (7 files, .tar.gz)

0001-Add-timingsafe_bcmp-for-constant-time-memory-compari.patch (text/x-patch, 5.4K) download From 2efd6b839fb00e260d40da9b4e272db1e67685f7 Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas <heikki.linnakangas@iki.fi> Date: Tue, 1 Apr 2025 16:28:11 +0300 Subject: [PATCH 1/7] Add timingsafe_bcmp(), for constant-time memory comparison timingsafe_bcmp() should be used instead of memcmp() or a naive for-loop, when comparing passwords or secret tokens, to avoid leaking information about the secret token by timing. This commit just introduces the function but does not change any existing code to use it yet. Co-authored-by: Jelte Fennema-Nio <github-tech@jeltef.nl> Discussion: https://www.postgresql.org/message-id/7b86da3b-9356-4e50-aa1b-56570825e234@iki.fi --- configure | 23 ++++++++++++++++++++ configure.ac | 3 ++- meson.build | 2 ++ src/include/port.h | 4 ++++ src/port/meson.build | 1 + src/port/timingsafe_bcmp.c | 43 ++++++++++++++++++++++++++++++++++++++ 6 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 src/port/timingsafe_bcmp.c diff --git a/configure b/configure index 30d949c3c46..1e18a5a22b0 100755 --- a/configure +++ b/configure @@ -15927,6 +15927,16 @@ fi cat >>confdefs.h <<_ACEOF #define HAVE_DECL_STRSEP $ac_have_decl _ACEOF +ac_fn_c_check_decl "$LINENO" "timingsafe_bcmp" "ac_cv_have_decl_timingsafe_bcmp" "$ac_includes_default" +if test "x$ac_cv_have_decl_timingsafe_bcmp" = xyes; then : + ac_have_decl=1 +else + ac_have_decl=0 +fi + +cat >>confdefs.h <<_ACEOF +#define HAVE_DECL_TIMINGSAFE_BCMP $ac_have_decl +_ACEOF # We can't use AC_CHECK_FUNCS to detect these functions, because it @@ -16087,6 +16097,19 @@ esac fi +ac_fn_c_check_func "$LINENO" "timingsafe_bcmp" "ac_cv_func_timingsafe_bcmp" +if test "x$ac_cv_func_timingsafe_bcmp" = xyes; then : + $as_echo "#define HAVE_TIMINGSAFE_BCMP 1" >>confdefs.h + +else + case " $LIBOBJS " in + *" timingsafe_bcmp.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS timingsafe_bcmp.$ac_objext" + ;; +esac + +fi + ac_fn_c_check_func "$LINENO" "pthread_barrier_wait" "ac_cv_func_pthread_barrier_wait" diff --git a/configure.ac b/configure.ac index 25cdfcf65af..440640febcc 100644 --- a/configure.ac +++ b/configure.ac @@ -1806,7 +1806,7 @@ AC_CHECK_DECLS(posix_fadvise, [], [], [#include <fcntl.h>]) ]) # fi AC_CHECK_DECLS(fdatasync, [], [], [#include <unistd.h>]) -AC_CHECK_DECLS([strlcat, strlcpy, strnlen, strsep]) +AC_CHECK_DECLS([strlcat, strlcpy, strnlen, strsep, timingsafe_bcmp]) # We can't use AC_CHECK_FUNCS to detect these functions, because it # won't handle deployment target restrictions on macOS @@ -1826,6 +1826,7 @@ AC_REPLACE_FUNCS(m4_normalize([ strlcpy strnlen strsep + timingsafe_bcmp ])) AC_REPLACE_FUNCS(pthread_barrier_wait) diff --git a/meson.build b/meson.build index b8da4966297..eee744b3abe 100644 --- a/meson.build +++ b/meson.build @@ -2569,6 +2569,7 @@ decl_checks = [ ['strlcpy', 'string.h'], ['strnlen', 'string.h'], ['strsep', 'string.h'], + ['timingsafe_bcmp', 'string.h'], ] # Need to check for function declarations for these functions, because @@ -2811,6 +2812,7 @@ func_checks = [ ['strsignal'], ['sync_file_range'], ['syncfs'], + ['timingsafe_bcmp'], ['uselocale'], ['wcstombs_l'], ] diff --git a/src/include/port.h b/src/include/port.h index 3faae03d246..3964d3b1293 100644 --- a/src/include/port.h +++ b/src/include/port.h @@ -464,6 +464,10 @@ extern size_t strnlen(const char *str, size_t maxlen); extern char *strsep(char **stringp, const char *delim); #endif +#if !HAVE_DECL_TIMINGSAFE_BCMP +extern int timingsafe_bcmp(const void *b1, const void *b2, size_t len); +#endif + /* * Callers should use the qsort() macro defined below instead of calling * pg_qsort() directly. diff --git a/src/port/meson.build b/src/port/meson.build index cf7f07644b9..51041e75609 100644 --- a/src/port/meson.build +++ b/src/port/meson.build @@ -73,6 +73,7 @@ replace_funcs_neg = [ ['strlcpy'], ['strnlen'], ['strsep'], + ['timingsafe_bcmp'], ] if host_system != 'windows' diff --git a/src/port/timingsafe_bcmp.c b/src/port/timingsafe_bcmp.c new file mode 100644 index 00000000000..288865f50d1 --- /dev/null +++ b/src/port/timingsafe_bcmp.c @@ -0,0 +1,43 @@ +/* + * src/port/timingsafe_bcmp.c + * + * $OpenBSD: timingsafe_bcmp.c,v 1.3 2015/08/31 02:53:57 guenther Exp $ + */ + +/* + * Copyright (c) 2010 Damien Miller. All rights reserved. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include "c.h" + +#ifdef USE_SSL +#include <openssl/crypto.h> +#endif + +int +timingsafe_bcmp(const void *b1, const void *b2, size_t n) +{ +#ifdef USE_SSL + return CRYPTO_memcmp(b1, b2, n); +#else + const unsigned char *p1 = b1, + *p2 = b2; + int ret = 0; + + for (; n > 0; n--) + ret |= *p1++ ^ *p2++; + return (ret != 0); +#endif +} -- 2.39.5
0002-libpq-Handle-NegotiateProtocolVersion-message-differ.patch (text/x-patch, 8.7K) download From 855048b6a8452973be2afdc2b9b0bbf9ca3d324b Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas <heikki.linnakangas@iki.fi> Date: Tue, 1 Apr 2025 16:02:27 +0300 Subject: [PATCH 2/7] libpq: Handle NegotiateProtocolVersion message differently Previously libpq would always error when the server returns a NegotiateProtocolVersion message. This was fine because libpq only supported a single protocol version and did not support any protocol parameters. But we now that we're discussing protocol changes we need to change this behaviour, and introduce a fallback mechanism when connecting to an older server. This patch modifies the client side checks to allow a range of supported protocol versions, instead of only allowing the exact version that was requested. Currently this "range" only contains the 3.0 version, but in a future commit we'll change this. In addition it changes the errors for protocol to say that they error because we did not request any parameters, not because the server did not support some of them. In a future commit more infrastructure for protocol parameters will be added, so that these checks can also succeed when receiving unsupported parameters back. Note that at the moment this change does not have any behavioural effect, because libpq will only request version 3.0 and will never send protocol parameters. Which means that the client never receives a NegotiateProtocolVersion message from the server. Author: Jelte Fennema-Nio <postgres@jeltef.nl> Discussion: https://www.postgresql.org/message-id/CAGECzQTfc_O%2BHXqAo5_-xG4r3EFVsTefUeQzSvhEyyLDba-O9w@mail.gmail.com Discussion: https://www.postgresql.org/message-id/CAGECzQRbAGqJnnJJxTdKewTsNOovUt4bsx3NFfofz3m2j-t7tA@mail.gmail.com --- src/interfaces/libpq/fe-connect.c | 12 +++- src/interfaces/libpq/fe-protocol3.c | 91 ++++++++++++++++++----------- src/interfaces/libpq/libpq-int.h | 1 + 3 files changed, 70 insertions(+), 34 deletions(-) diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index d5051f5e820..a1e462f2e2f 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -667,6 +667,7 @@ pqDropServerData(PGconn *conn) /* Reset assorted other per-connection state */ conn->last_sqlstate[0] = '\0'; + conn->negotiate_pversion_received = false; conn->auth_req_received = false; conn->client_finished_auth = false; conn->password_needed = false; @@ -4084,16 +4085,25 @@ keep_going: /* We will come back to here until there is CONNECTION_FAILED(); } + /* Handle NegotiateProtocolVersion */ else if (beresp == PqMsg_NegotiateProtocolVersion) { + if (conn->negotiate_pversion_received) + { + libpq_append_conn_error(conn, "received duplicate protocol negotiation message"); + goto error_return; + } + conn->negotiate_pversion_received = true; + if (pqGetNegotiateProtocolVersion3(conn)) { libpq_append_conn_error(conn, "received invalid protocol negotiation message"); goto error_return; } + /* OK, we read the message; mark data consumed */ pqParseDone(conn, conn->inCursor); - goto error_return; + goto keep_going; } /* It is an authentication request. */ diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c index 95dd456f076..43e3519e4bd 100644 --- a/src/interfaces/libpq/fe-protocol3.c +++ b/src/interfaces/libpq/fe-protocol3.c @@ -870,6 +870,7 @@ advance_and_error: /* * Attempt to read an Error or Notice response message. * This is possible in several places, so we break it out as a subroutine. + * * Entry: 'E' or 'N' message type and length have already been consumed. * Exit: returns 0 if successfully consumed message. * returns EOF if not enough data. @@ -1399,64 +1400,87 @@ reportErrorPosition(PQExpBuffer msg, const char *query, int loc, int encoding) /* - * Attempt to read a NegotiateProtocolVersion message. + * Attempt to read a NegotiateProtocolVersion message. Sets conn->pversion + * to the version that's negotiated by the server. + * * Entry: 'v' message type and length have already been consumed. * Exit: returns 0 if successfully consumed message. - * returns EOF if not enough data. + * returns 1 on failure. The error message is filled in. */ int pqGetNegotiateProtocolVersion3(PGconn *conn) { - int tmp; - ProtocolVersion their_version; + int their_version; int num; - PQExpBufferData buf; - if (pqGetInt(&tmp, 4, conn) != 0) - return EOF; - their_version = tmp; + if (pqGetInt(&their_version, 4, conn) != 0) + goto eof; if (pqGetInt(&num, 4, conn) != 0) - return EOF; + goto eof; - initPQExpBuffer(&buf); - for (int i = 0; i < num; i++) + /* Check the protocol version */ + if (their_version > conn->pversion) { - if (pqGets(&conn->workBuffer, conn)) - { - termPQExpBuffer(&buf); - return EOF; - } - if (buf.len > 0) - appendPQExpBufferChar(&buf, ' '); - appendPQExpBufferStr(&buf, conn->workBuffer.data); + libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requested downgrade to a higher-numbered version"); + goto failure; + } + + if (their_version < PG_PROTOCOL(3, 0)) + { + libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requested downgrade to pre-3.0 protocol version"); + goto failure; } - if (their_version < conn->pversion) - libpq_append_conn_error(conn, "protocol version not supported by server: client uses %u.%u, server supports up to %u.%u", - PG_PROTOCOL_MAJOR(conn->pversion), PG_PROTOCOL_MINOR(conn->pversion), - PG_PROTOCOL_MAJOR(their_version), PG_PROTOCOL_MINOR(their_version)); - if (num > 0) + if (num < 0) { - appendPQExpBuffer(&conn->errorMessage, - libpq_ngettext("protocol extension not supported by server: %s", - "protocol extensions not supported by server: %s", num), - buf.data); - appendPQExpBufferChar(&conn->errorMessage, '\n'); + libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported negative number of unsupported parameters"); + goto failure; + } + + if (their_version == conn->pversion && num == 0) + { + libpq_append_conn_error(conn, "received invalid protocol negotiation message: server negotiated but asks for no changes"); + goto failure; } - /* neither -- server shouldn't have sent it */ - if (!(their_version < conn->pversion) && !(num > 0)) - libpq_append_conn_error(conn, "invalid %s message", "NegotiateProtocolVersion"); + /* the version is acceptable */ + conn->pversion = their_version; + + /* + * We don't currently request any protocol extensions, so we don't expect + * the server to reply with any either. + */ + for (int i = 0; i < num; i++) + { + if (pqGets(&conn->workBuffer, conn)) + { + goto eof; + } + if (strncmp(conn->workBuffer.data, "_pq_.", 5) != 0) + { + libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported unsupported parameter name without a _pq_. prefix (\"%s\")", conn->workBuffer.data); + goto failure; + } + libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported an unsupported parameter that was not requested (\"%s\")", conn->workBuffer.data); + goto failure; + } - termPQExpBuffer(&buf); return 0; + +eof: + libpq_append_conn_error(conn, "received invalid protocol negotation message: message too short"); +failure: + conn->asyncStatus = PGASYNC_READY; + pqSaveErrorResult(conn); + return 1; } /* * Attempt to read a ParameterStatus message. * This is possible in several places, so we break it out as a subroutine. + * * Entry: 'S' message type and length have already been consumed. * Exit: returns 0 if successfully consumed message. * returns EOF if not enough data. @@ -1486,6 +1510,7 @@ getParameterStatus(PGconn *conn) /* * Attempt to read a Notify response message. * This is possible in several places, so we break it out as a subroutine. + * * Entry: 'A' message type and length have already been consumed. * Exit: returns 0 if successfully consumed Notify message. * returns EOF if not enough data. diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index ade5ad82f07..bf31e660477 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -496,6 +496,7 @@ struct pg_conn SockAddr raddr; /* Remote address */ ProtocolVersion pversion; /* FE/BE protocol version in use */ int sversion; /* server version, e.g. 70401 for 7.4.1 */ + bool negotiate_pversion_received; /* true if NegotiateProtocolVersion received */ bool auth_req_received; /* true if any type of auth req received */ bool password_needed; /* true if server demanded a password */ bool gssapi_used; /* true if authenticated via gssapi */ -- 2.39.5
0003-libpq-Add-min-max_protocol_version-connection-option.patch (text/x-patch, 12.0K) download From 23483d723fda9160f106cbd0dc89e25fcf8e1f33 Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas <heikki.linnakangas@iki.fi> Date: Tue, 1 Apr 2025 16:10:31 +0300 Subject: [PATCH 3/7] libpq: Add min/max_protocol_version connection options All supported version of the PostgreSQL server send the NegotiateProtocolVersion message when an unsupported minor protocol version is requested by a client. But many other applications that implement the PostgreSQL protocol (connection poolers, or other databases) do not, and the same is true for PostgreSQL server versions older than 9.2. Connecting to such other applications thus fails if a client requests a protocol version different than 3.0. This patch adds a max_protocol_version connection option to libpq that specifies the protocol version that libpq should request from the server. Currently all allowed values result in the use of 3.0, but that will be changed in a future commit that bumps the protocol version. Even after that version bump the default will likely stay 3.0 for the time being. Once more of the ecosystem supports the NegotiateProtocolVersion message we might want to change the default to the latest minor version. We also add the similar min_protocol_version connection option, to allow a client to specify that connecting should fail if a lower protocol version is attempted by the server. This can be used to ensure certain protocol features are in used, which can be particularly useful if those features impact security. Author: Jelte Fennema-Nio <postgres@jeltef.nl> Reviewed-by: Robert Haas <robertmhaas@gmail.com> (earlier versions) Discussion: https://www.postgresql.org/message-id/CAGECzQTfc_O%2BHXqAo5_-xG4r3EFVsTefUeQzSvhEyyLDba-O9w@mail.gmail.com Discussion: https://www.postgresql.org/message-id/CAGECzQRbAGqJnnJJxTdKewTsNOovUt4bsx3NFfofz3m2j-t7tA@mail.gmail.com --- doc/src/sgml/libpq.sgml | 69 +++++++++++++++++- src/interfaces/libpq/fe-connect.c | 104 +++++++++++++++++++++++++++- src/interfaces/libpq/fe-protocol3.c | 11 +++ src/interfaces/libpq/libpq-int.h | 4 ++ 4 files changed, 186 insertions(+), 2 deletions(-) diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index b359fbff295..a880e3acf0a 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -2144,6 +2144,54 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </listitem> </varlistentry> + <varlistentry id="libpq-connect-min-protocol-version" xreflabel="min_protocol_version"> + <term><literal>min_protocol_version</literal></term> + <listitem> + <para> + Specifies the minimum protocol version to allow for the connection. + The default is to allow any version of the + <productname>PostgreSQL</productname> protocol supported by libpq, + which currently means <literal>3.0</literal>. If the server + does not support at least this protocol version the connection will be + closed. + </para> + + <para> + The current supported values are + <literal>3.0</literal> + and <literal>latest</literal>. The <literal>latest</literal> value is + equivalent to the latest protocol version that is supported by the used + libpq version, which currently is <literal>3.0</literal>. + </para> + </listitem> + </varlistentry> + + <varlistentry id="libpq-connect-max-protocol-version" xreflabel="max_protocol_version"> + <term><literal>max_protocol_version</literal></term> + <listitem> + <para> + Specifies the protocol version to request from the server. + The default is to use version <literal>3.0</literal> of the + <productname>PostgreSQL</productname> protocol, unless the connection + string specifies a feature that relies on a higher protocol version, + in which case the latest version supported by libpq is used. If the + server does not support the protocol version requested by the client, + the connection is automatically downgraded to a lower minor protocol + version that the server supports. After the connection attempt has + completed you can use <xref linkend="libpq-PQprotocolVersion"/> to + find out which exact protocol version was negotiated. + </para> + + <para> + The current supported values are + <literal>3.0</literal> + and <literal>latest</literal>. The <literal>latest</literal> value is + equivalent to the latest protocol version that is supported by the + libpq version used, which is currently <literal>3.0</literal>. + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-connect-ssl-max-protocol-version" xreflabel="ssl_max_protocol_version"> <term><literal>ssl_max_protocol_version</literal></term> <listitem> @@ -2482,7 +2530,6 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </para> </listitem> </varlistentry> - </variablelist> </para> </sect2> @@ -9329,6 +9376,26 @@ myEventProc(PGEventId evtId, void *evtInfo, void *passThrough) linkend="libpq-connect-load-balance-hosts"/> connection parameter. </para> </listitem> + + <listitem> + <para> + <indexterm> + <primary><envar>PGMINPROTOCOLVERSION</envar></primary> + </indexterm> + <envar>PGMINPROTOCOLVERSION</envar> behaves the same as the <xref + linkend="libpq-connect-min-protocol-version"/> connection parameter. + </para> + </listitem> + + <listitem> + <para> + <indexterm> + <primary><envar>PGMAXPROTOCOLVERSION</envar></primary> + </indexterm> + <envar>PGMAXPROTOCOLVERSION</envar> behaves the same as the <xref + linkend="libpq-connect-max-protocol-version"/> connection parameter. + </para> + </listitem> </itemizedlist> </para> diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index a1e462f2e2f..8f95f47216c 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -325,6 +325,16 @@ static const internalPQconninfoOption PQconninfoOptions[] = { "Require-Auth", "", 14, /* sizeof("scram-sha-256") == 14 */ offsetof(struct pg_conn, require_auth)}, + {"min_protocol_version", "PGMINPROTOCOLVERSION", + NULL, NULL, + "Min-Protocol-Version", "", 6, /* sizeof("latest") = 6 */ + offsetof(struct pg_conn, min_protocol_version)}, + + {"max_protocol_version", "PGMAXPROTOCOLVERSION", + NULL, NULL, + "Max-Protocol-Version", "", 6, /* sizeof("latest") = 6 */ + offsetof(struct pg_conn, max_protocol_version)}, + {"ssl_min_protocol_version", "PGSSLMINPROTOCOLVERSION", "TLSv1.2", NULL, "SSL-Minimum-Protocol-Version", "", 8, /* sizeof("TLSv1.x") == 8 */ offsetof(struct pg_conn, ssl_min_protocol_version)}, @@ -483,6 +493,7 @@ static void pgpassfileWarning(PGconn *conn); static void default_threadlock(int acquire); static bool sslVerifyProtocolVersion(const char *version); static bool sslVerifyProtocolRange(const char *min, const char *max); +static bool pqParseProtocolVersion(const char *value, ProtocolVersion *result, PGconn *conn, const char *context); /* global variable because fe-auth.c needs to access it */ @@ -2081,6 +2092,42 @@ pqConnectOptions2(PGconn *conn) } } + if (conn->min_protocol_version) + { + if (!pqParseProtocolVersion(conn->min_protocol_version, &conn->min_pversion, conn, "min_protocol_version")) + return false; + } + else + { + conn->min_pversion = PG_PROTOCOL_EARLIEST; + } + + if (conn->max_protocol_version) + { + if (!pqParseProtocolVersion(conn->max_protocol_version, &conn->max_pversion, conn, "max_protocol_version")) + return false; + } + else + { + /* + * To not break connecting to older servers/poolers that do not yet + * support NegotiateProtocolVersion, default to the 3.0 protocol at + * least for a while longer. Except when min_protocol_version is set + * to something larger, then we might as well default to the latest. + */ + if (conn->min_pversion > PG_PROTOCOL(3, 0)) + conn->max_pversion = PG_PROTOCOL_LATEST; + else + conn->max_pversion = PG_PROTOCOL(3, 0); + } + + if (conn->min_pversion > conn->max_pversion) + { + conn->status = CONNECTION_BAD; + libpq_append_conn_error(conn, "min_protocol_version is greater than max_protocol_version"); + return false; + } + /* * Resolve special "auto" client_encoding from the locale */ @@ -3084,7 +3131,7 @@ keep_going: /* We will come back to here until there is * must persist across individual connection attempts, but we must * reset them when we start to consider a new server. */ - conn->pversion = PG_PROTOCOL(3, 0); + conn->pversion = conn->max_pversion; conn->send_appname = true; conn->failed_enc_methods = 0; conn->current_enc_method = 0; @@ -4103,6 +4150,7 @@ keep_going: /* We will come back to here until there is /* OK, we read the message; mark data consumed */ pqParseDone(conn, conn->inCursor); + goto keep_going; } @@ -8158,6 +8206,60 @@ error: return false; } +/* + * Parse and try to interpret "value" as a ProtocolVersion value, and if successful, + * store it in *result. + */ +static bool +pqParseProtocolVersion(const char *value, ProtocolVersion *result, PGconn *conn, + const char *context) +{ + char *end; + int major; + int minor; + ProtocolVersion version; + + if (strcmp(value, "latest") == 0) + { + *result = PG_PROTOCOL_LATEST; + return true; + } + + major = strtol(value, &end, 10); + if (*end != '.') + { + conn->status = CONNECTION_BAD; + libpq_append_conn_error(conn, "invalid %s value: \"%s\"", + context, + value); + return false; + } + + minor = strtol(&end[1], &end, 10); + if (*end != '\0') + { + conn->status = CONNECTION_BAD; + libpq_append_conn_error(conn, "invalid %s value: \"%s\"", + context, + value); + return false; + } + + version = PG_PROTOCOL(major, minor); + if (version > PG_PROTOCOL_LATEST || + version < PG_PROTOCOL_EARLIEST) + { + conn->status = CONNECTION_BAD; + libpq_append_conn_error(conn, "invalid %s value: \"%s\"", + context, + value); + return false; + } + + *result = version; + return true; +} + /* * To keep the API consistent, the locking stubs are always provided, even * if they are not required. diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c index 43e3519e4bd..5015debca77 100644 --- a/src/interfaces/libpq/fe-protocol3.c +++ b/src/interfaces/libpq/fe-protocol3.c @@ -1444,6 +1444,17 @@ pqGetNegotiateProtocolVersion3(PGconn *conn) goto failure; } + if (their_version < conn->min_pversion) + { + libpq_append_conn_error(conn, "server only supports protocol version %d.%d, but min_protocol_version was set to %d.%d", + PG_PROTOCOL_MAJOR(their_version), + PG_PROTOCOL_MINOR(their_version), + PG_PROTOCOL_MAJOR(conn->min_pversion), + PG_PROTOCOL_MINOR(conn->min_pversion)); + + goto failure; + } + /* the version is acceptable */ conn->pversion = their_version; diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index bf31e660477..68c8cd81d72 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -417,6 +417,8 @@ struct pg_conn char *gsslib; /* What GSS library to use ("gssapi" or * "sspi") */ char *gssdelegation; /* Try to delegate GSS credentials? (0 or 1) */ + char *min_protocol_version; /* minimum used protocol version */ + char *max_protocol_version; /* maximum used protocol version */ char *ssl_min_protocol_version; /* minimum TLS protocol version */ char *ssl_max_protocol_version; /* maximum TLS protocol version */ char *target_session_attrs; /* desired session properties */ @@ -538,6 +540,8 @@ struct pg_conn void *scram_client_key_binary; /* binary SCRAM client key */ size_t scram_server_key_len; void *scram_server_key_binary; /* binary SCRAM server key */ + ProtocolVersion min_pversion; /* protocol version to request */ + ProtocolVersion max_pversion; /* protocol version to request */ /* Miscellaneous stuff */ int be_pid; /* PID of backend --- needed for cancels */ -- 2.39.5
0004-Bump-protocol-version-to-3.2.patch (text/x-patch, 12.9K) download From 019c03e1c218e85b42656e881d3fd904c327e413 Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas <heikki.linnakangas@iki.fi> Date: Tue, 1 Apr 2025 16:24:41 +0300 Subject: [PATCH 4/7] Bump protocol version to 3.2 In preparation of new additions to the protocol in the next commit, this bumps the minor protocol version number. Instead of bumping the version number to 3.1, which would be the next minor version, we skip that one and bump straight to 3.2. The reason for this is that many PgBouncer releases have, due to an off-by-one bug, reported 3.1 as supported. These versions would interpret 3.1 as equivalent to 3.0. So if we would now add extra messages to the 3.1 protocol, clients would succeed to connect to PgBouncer, but would then cause connection failures when sending such new messages. So instead of bumping to 3.1, we bump the protocol version to 3.2, for which these buggy PgBouncer releases will correctly close the connection at the startup packet. It's a bit strange to skip a version number due to a bug in a third-party application, but PgBouncer is used widely enough that it seems worth it to not cause user confusion when connecting to recent versions of it. Especially since skipping a single minor version number in the protocol versioning doesn't really cost us anything. So, while this is not the most theoretically sound decission, it is the most pragmatic one. Author: Jelte Fennema-Nio <postgres@jeltef.nl> Discussion: https://www.postgresql.org/message-id/CAGECzQTfc_O%2BHXqAo5_-xG4r3EFVsTefUeQzSvhEyyLDba-O9w%40mail.gmail.com Discussion: https://www.postgresql.org/message-id/CAGECzQRbAGqJnnJJxTdKewTsNOovUt4bsx3NFfofz3m2j-t7tA@mail.gmail.com Discussion: https://github.com/pgbouncer/pgbouncer/pull/1007 --- doc/src/sgml/libpq.sgml | 12 +- doc/src/sgml/protocol.sgml | 31 ++++- src/include/libpq/pqcomm.h | 3 +- src/interfaces/libpq/fe-connect.c | 10 ++ src/interfaces/libpq/fe-protocol3.c | 7 ++ .../modules/libpq_pipeline/libpq_pipeline.c | 110 +++++++++++++++--- 6 files changed, 145 insertions(+), 28 deletions(-) diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index a880e3acf0a..41e898e7a38 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -2158,10 +2158,11 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname <para> The current supported values are - <literal>3.0</literal> + <literal>3.0</literal>, + <literal>3.2</literal>, and <literal>latest</literal>. The <literal>latest</literal> value is equivalent to the latest protocol version that is supported by the used - libpq version, which currently is <literal>3.0</literal>. + libpq version, which currently is <literal>3.2</literal>. </para> </listitem> </varlistentry> @@ -2184,10 +2185,11 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname <para> The current supported values are - <literal>3.0</literal> + <literal>3.0</literal>, + <literal>3.2</literal>, and <literal>latest</literal>. The <literal>latest</literal> value is - equivalent to the latest protocol version that is supported by the - libpq version used, which is currently <literal>3.0</literal>. + equivalent to the latest protocol version that is supported by the used + libpq version, which currently is <literal>3.2</literal>. </para> </listitem> </varlistentry> diff --git a/doc/src/sgml/protocol.sgml b/doc/src/sgml/protocol.sgml index 04d8e7d21af..0a60c2e7647 100644 --- a/doc/src/sgml/protocol.sgml +++ b/doc/src/sgml/protocol.sgml @@ -18,17 +18,23 @@ </para> <para> - This document describes version 3.0 of the protocol, implemented in + This document describes version 3.2 of the protocol, introduced in + <productname>PostgreSQL</productname> version 17. The server is compatible with + protocol version 3.0, implemented in <productname>PostgreSQL</productname> 7.4 and later. For descriptions - of the earlier protocol versions, see previous releases of the - <productname>PostgreSQL</productname> documentation. A single server + of earlier protocol versions, see previous releases of the + <productname>PostgreSQL</productname> documentation. + </para> + + <para> + A single server can support multiple protocol versions. The initial startup-request message tells the server which protocol version the client is attempting to use. If the major version requested by the client is not supported by the server, the connection will be rejected (for example, this would occur if the client requested protocol version 4.0, which does not exist as of this writing). If the minor version requested by the client is not - supported by the server (e.g., the client requests version 3.1, but the + supported by the server (e.g., the client requests version 3.2, but the server supports only 3.0), the server may either reject the connection or may respond with a NegotiateProtocolVersion message containing the highest minor protocol version which it supports. The client may then choose either @@ -36,6 +42,13 @@ to abort the connection. </para> + <para> + The protocol negotiation was introduced in + <productname>PostgreSQL</productname> version 9.3.21. Earlier versions would + reject the connection if the client requested a minor version that was not + supported by the server. + </para> + <para> In order to serve multiple clients efficiently, the server launches a new <quote>backend</quote> process for each client. @@ -413,8 +426,14 @@ this message indicates the highest supported minor version. This message will also be sent if the client requested unsupported protocol options (i.e., beginning with <literal>_pq_.</literal>) in the - startup packet. This message will be followed by an ErrorResponse or - a message indicating the success or failure of authentication. + startup packet. + </para> + <para> + After this message, the authentication will continue using the version + indicated by the server. If the client does not support the older + version, it should immediately close the connection. If the server + does not send this message, it supports the client's requested + protocol version and all the protocol options. </para> </listitem> </varlistentry> diff --git a/src/include/libpq/pqcomm.h b/src/include/libpq/pqcomm.h index 46b37e0e4eb..0aceb7147c7 100644 --- a/src/include/libpq/pqcomm.h +++ b/src/include/libpq/pqcomm.h @@ -91,11 +91,10 @@ is_unixsock_path(const char *path) /* * The earliest and latest frontend/backend protocol version supported. - * (Only protocol version 3 is currently supported) */ #define PG_PROTOCOL_EARLIEST PG_PROTOCOL(3,0) -#define PG_PROTOCOL_LATEST PG_PROTOCOL(3,0) +#define PG_PROTOCOL_LATEST PG_PROTOCOL(3,2) typedef uint32 ProtocolVersion; /* FE/BE protocol version number */ diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index 8f95f47216c..455a29c6720 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -8225,6 +8225,16 @@ pqParseProtocolVersion(const char *value, ProtocolVersion *result, PGconn *conn, return true; } + /* 3.1 never existed, we went straight from 3.0 to 3.2 */ + if (strcmp(value, "3.1") == 0) + { + conn->status = CONNECTION_BAD; + libpq_append_conn_error(conn, "invalid %s value: \"%s\"", + context, + value); + return false; + } + major = strtol(value, &end, 10); if (*end != '.') { diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c index 5015debca77..7ba49ea4592 100644 --- a/src/interfaces/libpq/fe-protocol3.c +++ b/src/interfaces/libpq/fe-protocol3.c @@ -1432,6 +1432,13 @@ pqGetNegotiateProtocolVersion3(PGconn *conn) goto failure; } + /* 3.1 never existed, we went straight from 3.0 to 3.2 */ + if (their_version == PG_PROTOCOL(3, 1)) + { + libpq_append_conn_error(conn, "received invalid protocol negotiation message: server requests downgrade to non-existent 3.1 protocol version"); + goto failure; + } + if (num < 0) { libpq_append_conn_error(conn, "received invalid protocol negotiation message: server reported negative number of unsupported parameters"); diff --git a/src/test/modules/libpq_pipeline/libpq_pipeline.c b/src/test/modules/libpq_pipeline/libpq_pipeline.c index ac9ac95135f..92c54758196 100644 --- a/src/test/modules/libpq_pipeline/libpq_pipeline.c +++ b/src/test/modules/libpq_pipeline/libpq_pipeline.c @@ -197,24 +197,15 @@ send_cancellable_query_impl(int line, PGconn *conn, PGconn *monitorConn) } /* - * Create a new connection with the same conninfo as the given one. + * Fills keywords and vals, with the same options as the ones in the opts + * linked-list. Returns the length of the filled in list. */ -static PGconn * -copy_connection(PGconn *conn) +static +int +copy_connection_options(PQconninfoOption *opts, const char **keywords, const char **vals) { - PGconn *copyConn; - PQconninfoOption *opts = PQconninfo(conn); - const char **keywords; - const char **vals; - int nopts = 1; int i = 0; - for (PQconninfoOption *opt = opts; opt->keyword != NULL; ++opt) - nopts++; - - keywords = pg_malloc(sizeof(char *) * nopts); - vals = pg_malloc(sizeof(char *) * nopts); - for (PQconninfoOption *opt = opts; opt->keyword != NULL; ++opt) { if (opt->val) @@ -224,8 +215,28 @@ copy_connection(PGconn *conn) i++; } } - keywords[i] = vals[i] = NULL; + return i; +} + +/* + * Create a new connection with the same conninfo as the given one. + */ +static PGconn * +copy_connection(PGconn *conn) +{ + const char **keywords; + const char **vals; + PGconn *copyConn; + PQconninfoOption *opts = PQconninfo(conn); + int nopts = 1; /* 1 for the NULL terminator */ + for (PQconninfoOption *opt = opts; opt->keyword != NULL; ++opt) + nopts++; + + keywords = pg_malloc0(sizeof(char *) * nopts); + vals = pg_malloc0(sizeof(char *) * nopts); + + copy_connection_options(opts, keywords, vals); copyConn = PQconnectdbParams(keywords, vals, false); if (PQstatus(copyConn) != CONNECTION_OK) @@ -1405,6 +1416,72 @@ test_prepared(PGconn *conn) fprintf(stderr, "ok\n"); } +static void +test_protocol_version(PGconn *conn) +{ + const char **keywords; + const char **vals; + int nopts = 2; /* NULL terminator + max_protocol_version */ + PQconninfoOption *opts = PQconninfo(conn); + int protocol_version; + int max_protocol_version_index; + + for (PQconninfoOption *opt = opts; opt->keyword != NULL; ++opt) + nopts++; + + keywords = pg_malloc0(sizeof(char *) * nopts); + vals = pg_malloc0(sizeof(char *) * nopts); + + max_protocol_version_index = copy_connection_options(opts, keywords, vals); + + keywords[max_protocol_version_index] = "max_protocol_version"; + vals[max_protocol_version_index] = "3.0"; + + conn = PQconnectdbParams(keywords, vals, false); + + if (PQstatus(conn) != CONNECTION_OK) + pg_fatal("Connection to database failed: %s", + PQerrorMessage(conn)); + + protocol_version = PQfullProtocolVersion(conn); + if (protocol_version != 30000) + pg_fatal("expected 30000, got %d", protocol_version); + + PQfinish(conn); + + vals[max_protocol_version_index] = "3.1"; + conn = PQconnectdbParams(keywords, vals, false); + + if (PQstatus(conn) != CONNECTION_BAD) + pg_fatal("Connecting with max_protocol_version 3.1 should have failed."); + + PQfinish(conn); + + vals[max_protocol_version_index] = "3.2"; + conn = PQconnectdbParams(keywords, vals, false); + + if (PQstatus(conn) != CONNECTION_OK) + pg_fatal("Connection to database failed: %s", + PQerrorMessage(conn)); + + protocol_version = PQfullProtocolVersion(conn); + if (protocol_version != 30002) + pg_fatal("expected 30002, got %d", protocol_version); + PQfinish(conn); + + vals[max_protocol_version_index] = "latest"; + conn = PQconnectdbParams(keywords, vals, false); + + if (PQstatus(conn) != CONNECTION_OK) + pg_fatal("Connection to database failed: %s", + PQerrorMessage(conn)); + + protocol_version = PQfullProtocolVersion(conn); + if (protocol_version != 30002) + pg_fatal("expected 30002, got %d", protocol_version); + PQfinish(conn); +} + /* Notice processor: print notices, and count how many we got */ static void notice_processor(void *arg, const char *message) @@ -2153,6 +2230,7 @@ print_test_list(void) printf("pipeline_idle\n"); printf("pipelined_insert\n"); printf("prepared\n"); + printf("protocol_version\n"); printf("simple_pipeline\n"); printf("singlerow\n"); printf("transaction\n"); @@ -2263,6 +2341,8 @@ main(int argc, char **argv) test_pipelined_insert(conn, numrows); else if (strcmp(testname, "prepared") == 0) test_prepared(conn); + else if (strcmp(testname, "protocol_version") == 0) + test_protocol_version(conn); else if (strcmp(testname, "simple_pipeline") == 0) test_simple_pipeline(conn); else if (strcmp(testname, "singlerow") == 0) -- 2.39.5
0005-Make-cancel-request-keys-longer.patch (text/x-patch, 27.3K) download From 187d597edb8081ab044ff1240cb0466faa6de192 Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas <heikki.linnakangas@iki.fi> Date: Tue, 1 Apr 2025 15:50:52 +0300 Subject: [PATCH 5/7] Make cancel request keys longer Currently, cancel request key is 32-bit token, which isn't very much entropy. If you want to cancel another session's query, you can brute-force it. In most environments, an unauthorized cancellation of a query isn't very serious, but it nevertheless would be nice to have more protection from it. Hence make the key longer, to make it harder to guess. The longer cancellation keys are generated when using the new protocol version 3.2. For connections using version 3.0, short 4-bytes keys are still used. The new longer key length is not hardcoded in the protocol anymore, the client is expected to deal with variable length keys, up to 256 bytes. This flexibility allows e.g. a connection pooler to add more information to the cancel key, which might be useful for finding the connection. Reviewed-by: Jelte Fennema-Nio <postgres@jeltef.nl> Reviewed-by: Robert Haas <robertmhaas@gmail.com> (earlier versions) Discussion: https://www.postgresql.org/message-id/508d0505-8b7a-4864-a681-e7e5edfe32aa@iki.fi --- doc/src/sgml/protocol.sgml | 25 ++++- src/backend/storage/ipc/procsignal.c | 23 ++-- src/backend/tcop/backend_startup.c | 55 ++++++---- src/backend/tcop/postgres.c | 15 ++- src/backend/utils/init/globals.c | 5 +- src/backend/utils/init/postinit.c | 2 +- src/include/libpq/pqcomm.h | 7 +- src/include/miscadmin.h | 4 +- src/include/storage/procsignal.h | 14 ++- src/interfaces/libpq/fe-cancel.c | 102 ++++++++++++++---- src/interfaces/libpq/fe-connect.c | 20 ++-- src/interfaces/libpq/fe-protocol3.c | 45 +++++++- src/interfaces/libpq/libpq-int.h | 7 +- .../libpq_pipeline/t/001_libpq_pipeline.pl | 12 ++- src/tools/pgindent/typedefs.list | 1 + 15 files changed, 252 insertions(+), 85 deletions(-) diff --git a/doc/src/sgml/protocol.sgml b/doc/src/sgml/protocol.sgml index 0a60c2e7647..1410b4984f2 100644 --- a/doc/src/sgml/protocol.sgml +++ b/doc/src/sgml/protocol.sgml @@ -49,6 +49,13 @@ supported by the server. </para> + <para> + The difference between protocol version 3.0 and 3.2 is that the secret key + used in query cancellation was enlarged from 4 bytes to a variable length + field. The BackendKeyData message was changed to accomodate that, and the + CancelRequest message was redefined to have a variable length payload. + </para> + <para> In order to serve multiple clients efficiently, the server launches a new <quote>backend</quote> process for each client. @@ -4062,7 +4069,7 @@ psql "dbname=postgres replication=database" -c "IDENTIFY_SYSTEM;" </varlistentry> <varlistentry> - <term>Int32(12)</term> + <term>Int32</term> <listitem> <para> Length of message contents in bytes, including self. @@ -4080,14 +4087,18 @@ psql "dbname=postgres replication=database" -c "IDENTIFY_SYSTEM;" </varlistentry> <varlistentry> - <term>Int32</term> + <term>Byte<replaceable>n</replaceable></term> <listitem> <para> - The secret key of this backend. + The secret key of this backend. This field extends to the end of the + message, indicated by the length field. The maximum key length is 256 bytes. </para> </listitem> </varlistentry> </variablelist> + <para> + Before protocol version 3.2, the secret key was always 4 bytes long. + </para> </listitem> </varlistentry> @@ -4293,14 +4304,18 @@ psql "dbname=postgres replication=database" -c "IDENTIFY_SYSTEM;" </varlistentry> <varlistentry> - <term>Int32</term> + <term>Byte<replaceable>n</replaceable></term> <listitem> <para> - The secret key for the target backend. + The secret key for the target backend. This field extends to the end of the + message, indicated by the length field. The maximum key length is 256 bytes. </para> </listitem> </varlistentry> </variablelist> + <para> + Before protocol version 3.2, the secret key was always 4 bytes long. + </para> </listitem> </varlistentry> diff --git a/src/backend/storage/ipc/procsignal.c b/src/backend/storage/ipc/procsignal.c index 7d201965503..b7c39a4c5f0 100644 --- a/src/backend/storage/ipc/procsignal.c +++ b/src/backend/storage/ipc/procsignal.c @@ -63,8 +63,8 @@ typedef struct { pg_atomic_uint32 pss_pid; - bool pss_cancel_key_valid; - int32 pss_cancel_key; + int pss_cancel_key_len; /* 0 means no cancellation is possible */ + char pss_cancel_key[MAX_CANCEL_KEY_LENGTH]; volatile sig_atomic_t pss_signalFlags[NUM_PROCSIGNALS]; slock_t pss_mutex; /* protects the above fields */ @@ -148,8 +148,7 @@ ProcSignalShmemInit(void) SpinLockInit(&slot->pss_mutex); pg_atomic_init_u32(&slot->pss_pid, 0); - slot->pss_cancel_key_valid = false; - slot->pss_cancel_key = 0; + slot->pss_cancel_key_len = 0; MemSet(slot->pss_signalFlags, 0, sizeof(slot->pss_signalFlags)); pg_atomic_init_u64(&slot->pss_barrierGeneration, PG_UINT64_MAX); pg_atomic_init_u32(&slot->pss_barrierCheckMask, 0); @@ -163,12 +162,13 @@ ProcSignalShmemInit(void) * Register the current process in the ProcSignal array */ void -ProcSignalInit(bool cancel_key_valid, int32 cancel_key) +ProcSignalInit(char *cancel_key, int cancel_key_len) { ProcSignalSlot *slot; uint64 barrier_generation; uint32 old_pss_pid; + Assert(cancel_key_len >= 0 && cancel_key_len <= MAX_CANCEL_KEY_LENGTH); if (MyProcNumber < 0) elog(ERROR, "MyProcNumber not set"); if (MyProcNumber >= NumProcSignalSlots) @@ -199,8 +199,9 @@ ProcSignalInit(bool cancel_key_valid, int32 cancel_key) pg_atomic_read_u64(&ProcSignal->psh_barrierGeneration); pg_atomic_write_u64(&slot->pss_barrierGeneration, barrier_generation); - slot->pss_cancel_key_valid = cancel_key_valid; - slot->pss_cancel_key = cancel_key; + if (cancel_key_len > 0) + memcpy(slot->pss_cancel_key, cancel_key, cancel_key_len); + slot->pss_cancel_key_len = cancel_key_len; pg_atomic_write_u32(&slot->pss_pid, MyProcPid); SpinLockRelease(&slot->pss_mutex); @@ -254,8 +255,7 @@ CleanupProcSignalState(int status, Datum arg) /* Mark the slot as unused */ pg_atomic_write_u32(&slot->pss_pid, 0); - slot->pss_cancel_key_valid = false; - slot->pss_cancel_key = 0; + slot->pss_cancel_key_len = 0; /* * Make this slot look like it's absorbed all possible barriers, so that @@ -725,7 +725,7 @@ procsignal_sigusr1_handler(SIGNAL_ARGS) * fields in the ProcSignal slots. */ void -SendCancelRequest(int backendPID, int32 cancelAuthCode) +SendCancelRequest(int backendPID, char *cancel_key, int cancel_key_len) { Assert(backendPID != 0); @@ -754,7 +754,8 @@ SendCancelRequest(int backendPID, int32 cancelAuthCode) } else { - match = slot->pss_cancel_key_valid && slot->pss_cancel_key == cancelAuthCode; + match = slot->pss_cancel_key_len == cancel_key_len && + timingsafe_bcmp(slot->pss_cancel_key, cancel_key, cancel_key_len) == 0; SpinLockRelease(&slot->pss_mutex); diff --git a/src/backend/tcop/backend_startup.c b/src/backend/tcop/backend_startup.c index a07c59ece01..cbdc903b456 100644 --- a/src/backend/tcop/backend_startup.c +++ b/src/backend/tcop/backend_startup.c @@ -59,6 +59,7 @@ ConnectionTiming conn_timing = {.ready_for_use = TIMESTAMP_MINUS_INFINITY}; static void BackendInitialize(ClientSocket *client_sock, CAC_state cac); static int ProcessSSLStartup(Port *port); static int ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done); +static void ProcessCancelRequestPacket(Port *port, void *pkt, int pktlen); static void SendNegotiateProtocolVersion(List *unrecognized_protocol_options); static void process_startup_packet_die(SIGNAL_ARGS); static void StartupPacketTimeoutHandler(void); @@ -557,28 +558,7 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done) if (proto == CANCEL_REQUEST_CODE) { - /* - * The client has sent a cancel request packet, not a normal - * start-a-new-connection packet. Perform the necessary processing. - * Nothing is sent back to the client. - */ - CancelRequestPacket *canc; - int backendPID; - int32 cancelAuthCode; - - if (len != sizeof(CancelRequestPacket)) - { - ereport(COMMERROR, - (errcode(ERRCODE_PROTOCOL_VIOLATION), - errmsg("invalid length of startup packet"))); - return STATUS_ERROR; - } - canc = (CancelRequestPacket *) buf; - backendPID = (int) pg_ntoh32(canc->backendPID); - cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode); - - if (backendPID != 0) - SendCancelRequest(backendPID, cancelAuthCode); + ProcessCancelRequestPacket(port, buf, len); /* Not really an error, but we don't want to proceed further */ return STATUS_ERROR; } @@ -878,6 +858,37 @@ ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done) return STATUS_OK; } +/* + * The client has sent a cancel request packet, not a normal + * start-a-new-connection packet. Perform the necessary processing. Nothing + * is sent back to the client. + */ +static void +ProcessCancelRequestPacket(Port *port, void *pkt, int pktlen) +{ + CancelRequestPacket *canc; + int len; + + if (pktlen < offsetof(CancelRequestPacket, cancelAuthCode)) + { + ereport(COMMERROR, + (errcode(ERRCODE_PROTOCOL_VIOLATION), + errmsg("invalid length of query cancel packet"))); + return; + } + len = pktlen - offsetof(CancelRequestPacket, cancelAuthCode); + if (len == 0 || len > 256) + { + ereport(COMMERROR, + (errcode(ERRCODE_PROTOCOL_VIOLATION), + errmsg("invalid length of query cancel key"))); + return; + } + + canc = (CancelRequestPacket *) pkt; + SendCancelRequest(pg_ntoh32(canc->backendPID), canc->cancelAuthCode, len); +} + /* * Send a NegotiateProtocolVersion to the client. This lets the client know * that they have either requested a newer minor protocol version than we are diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c index aec65007bb6..c26a0511989 100644 --- a/src/backend/tcop/postgres.c +++ b/src/backend/tcop/postgres.c @@ -4259,16 +4259,20 @@ PostgresMain(const char *dbname, const char *username) * Generate a random cancel key, if this is a backend serving a * connection. InitPostgres() will advertise it in shared memory. */ - Assert(!MyCancelKeyValid); + Assert(MyCancelKeyLength == 0); if (whereToSendOutput == DestRemote) { - if (!pg_strong_random(&MyCancelKey, sizeof(int32))) + int len; + + len = (MyProcPort == NULL || MyProcPort->proto >= PG_PROTOCOL(3, 1)) + ? MAX_CANCEL_KEY_LENGTH : 4; + if (!pg_strong_random(&MyCancelKey, len)) { ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR), errmsg("could not generate random cancel key"))); } - MyCancelKeyValid = true; + MyCancelKeyLength = len; } /* @@ -4323,10 +4327,11 @@ PostgresMain(const char *dbname, const char *username) { StringInfoData buf; - Assert(MyCancelKeyValid); + Assert(MyCancelKeyLength > 0); pq_beginmessage(&buf, PqMsg_BackendKeyData); pq_sendint32(&buf, (int32) MyProcPid); - pq_sendint32(&buf, (int32) MyCancelKey); + + pq_sendbytes(&buf, MyCancelKey, MyCancelKeyLength); pq_endmessage(&buf); /* Need not flush since ReadyForQuery will do it. */ } diff --git a/src/backend/utils/init/globals.c b/src/backend/utils/init/globals.c index b844f9fdaef..2152aad97d9 100644 --- a/src/backend/utils/init/globals.c +++ b/src/backend/utils/init/globals.c @@ -24,6 +24,7 @@ #include "miscadmin.h" #include "postmaster/postmaster.h" #include "storage/procnumber.h" +#include "storage/procsignal.h" ProtocolVersion FrontendProtocol; @@ -48,8 +49,8 @@ pg_time_t MyStartTime; TimestampTz MyStartTimestamp; struct ClientSocket *MyClientSocket; struct Port *MyProcPort; -bool MyCancelKeyValid = false; -int32 MyCancelKey = 0; +char MyCancelKey[MAX_CANCEL_KEY_LENGTH]; +uint8 MyCancelKeyLength = 0; int MyPMChildSlot; /* diff --git a/src/backend/utils/init/postinit.c b/src/backend/utils/init/postinit.c index 7958ea11b73..c09c4d404ba 100644 --- a/src/backend/utils/init/postinit.c +++ b/src/backend/utils/init/postinit.c @@ -753,7 +753,7 @@ InitPostgres(const char *in_dbname, Oid dboid, */ SharedInvalBackendInit(false); - ProcSignalInit(MyCancelKeyValid, MyCancelKey); + ProcSignalInit(MyCancelKey, MyCancelKeyLength); /* * Also set up timeout handlers needed for backend operation. We need diff --git a/src/include/libpq/pqcomm.h b/src/include/libpq/pqcomm.h index 0aceb7147c7..d0f2c1fb03a 100644 --- a/src/include/libpq/pqcomm.h +++ b/src/include/libpq/pqcomm.h @@ -128,7 +128,11 @@ typedef uint32 AuthRequest; * * The cancel request code must not match any protocol version number * we're ever likely to use. This random choice should do. + * + * Before PostgreSQL v17 and the protocol version bump from 3.0 to 3.1, the + * cancel key was always 4 bytes. Starting with v17, it's variable length. */ + #define CANCEL_REQUEST_CODE PG_PROTOCOL(1234,5678) typedef struct CancelRequestPacket @@ -136,7 +140,8 @@ typedef struct CancelRequestPacket /* Note that each field is stored in network byte order! */ MsgType cancelRequestCode; /* code to identify a cancel request */ uint32 backendPID; /* PID of client's backend */ - uint32 cancelAuthCode; /* secret key to authorize cancel */ + char cancelAuthCode[FLEXIBLE_ARRAY_MEMBER]; /* secret key to + * authorize cancel */ } CancelRequestPacket; /* Application-Layer Protocol Negotiation is required for direct connections diff --git a/src/include/miscadmin.h b/src/include/miscadmin.h index 603d0424354..0d8528b2875 100644 --- a/src/include/miscadmin.h +++ b/src/include/miscadmin.h @@ -191,8 +191,8 @@ extern PGDLLIMPORT pg_time_t MyStartTime; extern PGDLLIMPORT TimestampTz MyStartTimestamp; extern PGDLLIMPORT struct Port *MyProcPort; extern PGDLLIMPORT struct Latch *MyLatch; -extern PGDLLIMPORT bool MyCancelKeyValid; -extern PGDLLIMPORT int32 MyCancelKey; +extern PGDLLIMPORT char MyCancelKey[]; +extern PGDLLIMPORT uint8 MyCancelKeyLength; extern PGDLLIMPORT int MyPMChildSlot; extern PGDLLIMPORT char OutputFileName[]; diff --git a/src/include/storage/procsignal.h b/src/include/storage/procsignal.h index 022fd8ed933..b14c9252582 100644 --- a/src/include/storage/procsignal.h +++ b/src/include/storage/procsignal.h @@ -56,16 +56,26 @@ typedef enum PROCSIGNAL_BARRIER_SMGRRELEASE, /* ask smgr to close files */ } ProcSignalBarrierType; +/* + * Length of query cancel keys generated. + * + * Note that the protocol allows for longer keys, or shorter, but this is the + * length we actually generate. Client code, and the server code that handles + * incoming cancellation packets from clients, cannot use this hardcoded + * length. + */ +#define MAX_CANCEL_KEY_LENGTH 32 + /* * prototypes for functions in procsignal.c */ extern Size ProcSignalShmemSize(void); extern void ProcSignalShmemInit(void); -extern void ProcSignalInit(bool cancel_key_valid, int32 cancel_key); +extern void ProcSignalInit(char *cancel_key, int cancel_key_len); extern int SendProcSignal(pid_t pid, ProcSignalReason reason, ProcNumber procNumber); -extern void SendCancelRequest(int backendPID, int32 cancelAuthCode); +extern void SendCancelRequest(int backendPID, char *cancel_key, int cancel_key_len); extern uint64 EmitProcSignalBarrier(ProcSignalBarrierType type); extern void WaitForProcSignalBarrier(uint64 generation); diff --git a/src/interfaces/libpq/fe-cancel.c b/src/interfaces/libpq/fe-cancel.c index 7ebaa335bba..e84e64bf2a7 100644 --- a/src/interfaces/libpq/fe-cancel.c +++ b/src/interfaces/libpq/fe-cancel.c @@ -1,7 +1,7 @@ /*------------------------------------------------------------------------- * * fe-cancel.c - * functions related to setting up a connection to the backend + * functions related to query cancellation * * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California @@ -41,7 +41,6 @@ struct pg_cancel { SockAddr raddr; /* Remote address */ int be_pid; /* PID of to-be-canceled backend */ - int be_key; /* cancel key of to-be-canceled backend */ int pgtcp_user_timeout; /* tcp user timeout */ int keepalives; /* use TCP keepalives? */ int keepalives_idle; /* time between TCP keepalives */ @@ -49,6 +48,10 @@ struct pg_cancel * retransmits */ int keepalives_count; /* maximum number of TCP keepalive * retransmits */ + + /* Pre-constructed cancel request packet starts here */ + int32 cancel_pkt_len; /* in network-byte-order */ + char cancel_req[FLEXIBLE_ARRAY_MEMBER]; /* CancelRequestPacket */ }; @@ -83,6 +86,13 @@ PQcancelCreate(PGconn *conn) return (PGcancelConn *) cancelConn; } + /* Check that we have received a cancellation key */ + if (conn->be_cancel_key_len == 0) + { + libpq_append_conn_error(cancelConn, "no cancellation key received"); + return (PGcancelConn *) cancelConn; + } + /* * Indicate that this connection is used to send a cancellation */ @@ -101,7 +111,15 @@ PQcancelCreate(PGconn *conn) * Copy cancellation token data from the original connection */ cancelConn->be_pid = conn->be_pid; - cancelConn->be_key = conn->be_key; + if (conn->be_cancel_key != NULL) + { + cancelConn->be_cancel_key = malloc(conn->be_cancel_key_len); + if (!conn->be_cancel_key) + goto oom_error; + memcpy(cancelConn->be_cancel_key, conn->be_cancel_key, conn->be_cancel_key_len); + } + cancelConn->be_cancel_key_len = conn->be_cancel_key_len; + cancelConn->pversion = conn->pversion; /* * Cancel requests should not iterate over all possible hosts. The request @@ -349,6 +367,8 @@ PGcancel * PQgetCancel(PGconn *conn) { PGcancel *cancel; + int cancel_req_len; + CancelRequestPacket *req; if (!conn) return NULL; @@ -356,13 +376,17 @@ PQgetCancel(PGconn *conn) if (conn->sock == PGINVALID_SOCKET) return NULL; - cancel = malloc(sizeof(PGcancel)); + /* Check that we have received a cancellation key */ + if (conn->be_cancel_key_len == 0) + return NULL; + + cancel_req_len = offsetof(CancelRequestPacket, cancelAuthCode) + conn->be_cancel_key_len; + cancel = malloc(offsetof(PGcancel, cancel_req) + cancel_req_len); if (cancel == NULL) return NULL; memcpy(&cancel->raddr, &conn->raddr, sizeof(SockAddr)); - cancel->be_pid = conn->be_pid; - cancel->be_key = conn->be_key; + /* We use -1 to indicate an unset connection option */ cancel->pgtcp_user_timeout = -1; cancel->keepalives = -1; @@ -405,6 +429,13 @@ PQgetCancel(PGconn *conn) goto fail; } + req = (CancelRequestPacket *) &cancel->cancel_req; + req->cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE); + req->backendPID = pg_hton32(conn->be_pid); + memcpy(req->cancelAuthCode, conn->be_cancel_key, conn->be_cancel_key_len); + /* include the length field itself in the length */ + cancel->cancel_pkt_len = pg_hton32(cancel_req_len + 4); + return cancel; fail: @@ -412,6 +443,42 @@ fail: return NULL; } +/* + * PQsendCancelRequest + * Submit a CancelRequest message, but don't wait for it to finish + * + * Returns: 1 if successfully submitted + * 0 if error (conn->errorMessage is set) + */ +int +PQsendCancelRequest(PGconn *cancelConn) +{ + CancelRequestPacket req; + + /* Start the message. */ + if (pqPutMsgStart(0, cancelConn)) + return STATUS_ERROR; + + /* Send the message body. */ + memset(&req, 0, offsetof(CancelRequestPacket, cancelAuthCode)); + req.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE); + req.backendPID = pg_hton32(cancelConn->be_pid); + if (pqPutnchar((char *) &req, offsetof(CancelRequestPacket, cancelAuthCode), cancelConn)) + return STATUS_ERROR; + if (pqPutnchar(cancelConn->be_cancel_key, cancelConn->be_cancel_key_len, cancelConn)) + return STATUS_ERROR; + + /* Finish the message. */ + if (pqPutMsgEnd(cancelConn)) + return STATUS_ERROR; + + /* Flush to ensure backend gets it. */ + if (pqFlush(cancelConn)) + return STATUS_ERROR; + + return STATUS_OK; +} + /* PQfreeCancel: free a cancel structure */ void PQfreeCancel(PGcancel *cancel) @@ -465,11 +532,8 @@ PQcancel(PGcancel *cancel, char *errbuf, int errbufsize) int save_errno = SOCK_ERRNO; pgsocket tmpsock = PGINVALID_SOCKET; int maxlen; - struct - { - uint32 packetlen; - CancelRequestPacket cp; - } crp; + char recvbuf; + int cancel_pkt_len; if (!cancel) { @@ -571,15 +635,15 @@ retry3: goto cancel_errReturn; } - /* Create and send the cancel request packet. */ - - crp.packetlen = pg_hton32((uint32) sizeof(crp)); - crp.cp.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE); - crp.cp.backendPID = pg_hton32(cancel->be_pid); - crp.cp.cancelAuthCode = pg_hton32(cancel->be_key); + cancel_pkt_len = pg_ntoh32(cancel->cancel_pkt_len); retry4: - if (send(tmpsock, (char *) &crp, sizeof(crp), 0) != (int) sizeof(crp)) + + /* + * Send the cancel request packet. It starts with the message length at + * cancel_pkt_len, followed by the actual packet. + */ + if (send(tmpsock, (char *) &cancel->cancel_pkt_len, cancel_pkt_len, 0) != cancel_pkt_len) { if (SOCK_ERRNO == EINTR) /* Interrupted system call - we'll just try again */ @@ -596,7 +660,7 @@ retry4: * read to obtain any data, we are just waiting for EOF to be signaled. */ retry5: - if (recv(tmpsock, (char *) &crp, 1, 0) < 0) + if (recv(tmpsock, &recvbuf, 1, 0) < 0) { if (SOCK_ERRNO == EINTR) /* Interrupted system call - we'll just try again */ diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index 455a29c6720..58328e829af 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -696,7 +696,12 @@ pqDropServerData(PGconn *conn) if (!conn->cancelRequest) { conn->be_pid = 0; - conn->be_key = 0; + if (conn->be_cancel_key != NULL) + { + free(conn->be_cancel_key); + conn->be_cancel_key = NULL; + } + conn->be_cancel_key_len = 0; } } @@ -3686,13 +3691,7 @@ keep_going: /* We will come back to here until there is */ if (conn->cancelRequest) { - CancelRequestPacket cancelpacket; - - packetlen = sizeof(cancelpacket); - cancelpacket.cancelRequestCode = (MsgType) pg_hton32(CANCEL_REQUEST_CODE); - cancelpacket.backendPID = pg_hton32(conn->be_pid); - cancelpacket.cancelAuthCode = pg_hton32(conn->be_key); - if (pqPacketSend(conn, 0, &cancelpacket, packetlen) != STATUS_OK) + if (PQsendCancelRequest(conn) != STATUS_OK) { libpq_append_conn_error(conn, "could not send cancel packet: %s", SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf))); @@ -4144,7 +4143,10 @@ keep_going: /* We will come back to here until there is if (pqGetNegotiateProtocolVersion3(conn)) { - libpq_append_conn_error(conn, "received invalid protocol negotiation message"); + /* + * Negotiation failed. The error message was filled + * in already. + */ goto error_return; } diff --git a/src/interfaces/libpq/fe-protocol3.c b/src/interfaces/libpq/fe-protocol3.c index 7ba49ea4592..d85910f41fc 100644 --- a/src/interfaces/libpq/fe-protocol3.c +++ b/src/interfaces/libpq/fe-protocol3.c @@ -48,6 +48,7 @@ static int getRowDescriptions(PGconn *conn, int msgLength); static int getParamDescriptions(PGconn *conn, int msgLength); static int getAnotherTuple(PGconn *conn, int msgLength); static int getParameterStatus(PGconn *conn); +static int getBackendKeyData(PGconn *conn, int msgLength); static int getNotify(PGconn *conn); static int getCopyStart(PGconn *conn, ExecStatusType copytype); static int getReadyForQuery(PGconn *conn); @@ -308,9 +309,7 @@ pqParseInput3(PGconn *conn) * just as easy to handle it as part of the main loop. * Save the data and continue processing. */ - if (pqGetInt(&(conn->be_pid), 4, conn)) - return; - if (pqGetInt(&(conn->be_key), 4, conn)) + if (getBackendKeyData(conn, msgLength)) return; break; case PqMsg_RowDescription: @@ -1524,6 +1523,46 @@ getParameterStatus(PGconn *conn) return 0; } +/* + * parseInput subroutine to read a BackendKeyData message. + * Entry: 'v' message type and length have already been consumed. + * Exit: returns 0 if successfully consumed message. + * returns EOF if not enough data. + */ +static int +getBackendKeyData(PGconn *conn, int msgLength) +{ + uint8 cancel_key_len; + + if (conn->be_cancel_key) + { + free(conn->be_cancel_key); + conn->be_cancel_key = NULL; + conn->be_cancel_key_len = 0; + } + + if (pqGetInt(&(conn->be_pid), 4, conn)) + return EOF; + + cancel_key_len = 5 + msgLength - (conn->inCursor - conn->inStart); + + conn->be_cancel_key = malloc(cancel_key_len); + if (conn->be_cancel_key == NULL) + { + libpq_append_conn_error(conn, "out of memory"); + /* discard the message */ + return EOF; + } + if (pqGetnchar(conn->be_cancel_key, cancel_key_len, conn)) + { + free(conn->be_cancel_key); + conn->be_cancel_key = NULL; + return EOF; + } + conn->be_cancel_key_len = cancel_key_len; + return 0; +} + /* * Attempt to read a Notify response message. diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 68c8cd81d72..16b6d96df33 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -545,7 +545,8 @@ struct pg_conn /* Miscellaneous stuff */ int be_pid; /* PID of backend --- needed for cancels */ - int be_key; /* key of backend --- needed for cancels */ + char *be_cancel_key; /* query cancellation key and its length */ + uint16 be_cancel_key_len; pgParameterStatus *pstatus; /* ParameterStatus data */ int client_encoding; /* encoding id */ bool std_strings; /* standard_conforming_strings */ @@ -765,6 +766,10 @@ extern PGresult *pqFunctionCall3(PGconn *conn, Oid fnid, int result_is_int, const PQArgBlock *args, int nargs); +/* === in fe-cancel.c === */ + +extern int PQsendCancelRequest(PGconn *cancelConn); + /* === in fe-misc.c === */ /* diff --git a/src/test/modules/libpq_pipeline/t/001_libpq_pipeline.pl b/src/test/modules/libpq_pipeline/t/001_libpq_pipeline.pl index 9691b850418..61524bdbd8f 100644 --- a/src/test/modules/libpq_pipeline/t/001_libpq_pipeline.pl +++ b/src/test/modules/libpq_pipeline/t/001_libpq_pipeline.pl @@ -49,11 +49,11 @@ for my $testname (@tests) push @extraargs, "-t" => $traceout; } - # Execute the test + # Execute the test using the latest protocol version. $node->command_ok( [ 'libpq_pipeline', @extraargs, - $testname, $node->connstr('postgres') + $testname, $node->connstr('postgres') . " max_protocol_version=latest" ], "libpq_pipeline $testname"); @@ -72,6 +72,14 @@ for my $testname (@tests) } } +# There were changes to query cancellation in protocol version 3.2, so +# test separately that it still works the old protocol version too. +$node->command_ok( + [ + 'libpq_pipeline', 'cancel', $node->connstr('postgres') . " max_protocol_version=3.0" + ], + "libpq_pipeline cancel with protocol 3.0"); + $node->stop('fast'); done_testing(); diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index b66cecd8799..aa01983337e 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -386,6 +386,7 @@ CachedPlanSource CallContext CallStmt CancelRequestPacket +CancelRequestExtendedPacket Cardinality CaseExpr CaseKind -- 2.39.5
0006-docs-Update-phrase-that-talks-about-message-lengths-.patch (text/x-patch, 1.8K) download From 6060971265adccdb61b0c2b693f977cc404e93c8 Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas <heikki.linnakangas@iki.fi> Date: Tue, 1 Apr 2025 14:47:55 +0300 Subject: [PATCH 6/7] docs: Update phrase that talks about message lengths in the protocol The reasoning for why all the message formats are parseable without the explicit message length field is anachronistic; the real reason is that protocol version 2 did not have a message length field. There's nothing wrong with relying on the message length, like we do in the new variable-length definitions of CancelRequest and BackendKeyData., even though it often still makes sense to have length fields for individual parts in messages. --- doc/src/sgml/protocol.sgml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/src/sgml/protocol.sgml b/doc/src/sgml/protocol.sgml index 1410b4984f2..8074085eec5 100644 --- a/doc/src/sgml/protocol.sgml +++ b/doc/src/sgml/protocol.sgml @@ -3650,10 +3650,10 @@ psql "dbname=postgres replication=database" -c "IDENTIFY_SYSTEM;" indicate that it can be sent by a frontend (F), a backend (B), or both (F &amp; B). Notice that although each message includes a byte count at the beginning, - the message format is defined so that the message end can be found without - reference to the byte count. This aids validity checking. (The CopyData - message is an exception, because it forms part of a data stream; the contents - of any individual CopyData message cannot be interpretable on their own.) + most messages are defined so that the message end can be found without + reference to the byte count. This is mostly for historical reasons, as + the original, now-obsolete protocol version 2 did not have an explicit length + field, but it also aids validity checking. </para> <variablelist> -- 2.39.5
0007-docs-Add-a-new-section-and-table-listing-protocol-ve.patch (text/x-patch, 5.9K) download From 06d53688510d31e141cda5a64111a751775ac0be Mon Sep 17 00:00:00 2001 From: Heikki Linnakangas <heikki.linnakangas@iki.fi> Date: Tue, 1 Apr 2025 16:44:27 +0300 Subject: [PATCH 7/7] docs: Add a new section and table listing protocol versions Move the discussion on protocol versions and version negotiation to a new "Protocol versions" section. Add a table listing all the different protocol versions, starting from the obsolete protocol version 2, and the PostgreSQL versions that support each. --- doc/src/sgml/protocol.sgml | 117 ++++++++++++++++++++++++++----------- 1 file changed, 82 insertions(+), 35 deletions(-) diff --git a/doc/src/sgml/protocol.sgml b/doc/src/sgml/protocol.sgml index 8074085eec5..4c80c456e41 100644 --- a/doc/src/sgml/protocol.sgml +++ b/doc/src/sgml/protocol.sgml @@ -19,41 +19,9 @@ <para> This document describes version 3.2 of the protocol, introduced in - <productname>PostgreSQL</productname> version 17. The server is compatible with - protocol version 3.0, implemented in - <productname>PostgreSQL</productname> 7.4 and later. For descriptions - of earlier protocol versions, see previous releases of the - <productname>PostgreSQL</productname> documentation. - </para> - - <para> - A single server - can support multiple protocol versions. The initial startup-request - message tells the server which protocol version the client is attempting to - use. If the major version requested by the client is not supported by - the server, the connection will be rejected (for example, this would occur - if the client requested protocol version 4.0, which does not exist as of - this writing). If the minor version requested by the client is not - supported by the server (e.g., the client requests version 3.2, but the - server supports only 3.0), the server may either reject the connection or - may respond with a NegotiateProtocolVersion message containing the highest - minor protocol version which it supports. The client may then choose either - to continue with the connection using the specified protocol version or - to abort the connection. - </para> - - <para> - The protocol negotiation was introduced in - <productname>PostgreSQL</productname> version 9.3.21. Earlier versions would - reject the connection if the client requested a minor version that was not - supported by the server. - </para> - - <para> - The difference between protocol version 3.0 and 3.2 is that the secret key - used in query cancellation was enlarged from 4 bytes to a variable length - field. The BackendKeyData message was changed to accomodate that, and the - CancelRequest message was redefined to have a variable length payload. + <productname>PostgreSQL</productname> version 17. The server and the libpq + client library is compatible with protocol version 3.0, implemented in + <productname>PostgreSQL</productname> 7.4 and later. </para> <para> @@ -219,6 +187,85 @@ server versions; the text format is usually the more portable choice. </para> </sect2> + + <sect2 id="protocol-versions"> + <title>Protocol versions</title> + + <para> + The current, latest version of the protocol is version 3.2. For backwards + compatibility with old server versions and middleware that don't support + the version negotiation yet, the libpq library still uses protocol version + 3.0 by default however. + </para> + + <para> + A single server can support multiple protocol versions. The initial + startup-request message tells the server which protocol version the client + is attempting to use. If the major version requested by the client is not + supported by the server, the connection will be rejected (for example, + this would occur if the client requested protocol version 4.0, which does + not exist as of this writing). If the minor version requested by the + client is not supported by the server (e.g., the client requests version + 3.2, but the server supports only 3.0), the server may either reject the + connection or may respond with a NegotiateProtocolVersion message + containing the highest minor protocol version which it supports. The + client may then choose either to continue with the connection using the + specified protocol version or to abort the connection. + </para> + + <para> + The protocol negotiation was introduced in + <productname>PostgreSQL</productname> version 9.3.21. Earlier versions + would reject the connection if the client requested a minor version that + was not supported by the server. + </para> + + <table> + <title>Protocol versions</title> + + <tgroup cols="2"> + <thead> + <row> + <entry>Version</entry> + <entry>Supported by</entry> + <entry>Description</entry> + </row> + </thead> + + <tbody> + <row> + <entry>3.2</entry> + <entry>PostgreSQL 18 and later</entry> + <entry>Current latest version. The secret key used in query + cancellation was enlarged from 4 bytes to a variable length field. The + BackendKeyData message was changed to accomodate that, and the CancelRequest + message was redefined to have a variable length payload. + </entry> + </row> + <row> + <entry>3.1</entry> + <entry>-</entry> + <entry>Reserved. Version 3.1 has not been used by any PostgreSQL + version, but it was skipped because old versions of the popular + pgbouncer application had a bug in the protocol negotiation which made + it incorrectly claim that it supported version 3.1. + </entry> + </row> + <row> + <entry>3.0</entry> + <entry>PostgreSQL 7.4 and later</entry> + </row> + <row> + <entry>2.0</entry> + <entry>up to PostgreSQL 13</entry> + <entry>See previous releases of + the <productname>PostgreSQL</productname> documentation for + details</entry> + </row> + </tbody> + </tgroup> + </table> + </sect2> </sect1> <sect1 id="protocol-flow"> -- 2.39.5
^ permalink raw reply [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2025-04-02 13:48  Heikki Linnakangas <hlinnaka@iki.fi>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  0 siblings, 1 reply; 40+ messages in thread

From: Heikki Linnakangas @ 2025-04-02 13:48 UTC (permalink / raw)
  To: Jelte Fennema-Nio <postgres@jeltef.nl>; Robert Haas <robertmhaas@gmail.com>; Jacob Champion <jacob.champion@enterprisedb.com>; +Cc: pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>

On 01/04/2025 17:08, Heikki Linnakangas wrote:
> I think this is pretty much ready for commit. I will go over it one more 
> time, and plan to push tomorrow.

And committed, with minor a bunch more little cleanups.

Thank you to everyone involved, in particular Jelte, Robert and Jacob! I 
read through all the discussions on this and the other thread again last 
night to make sure I didn't miss anything. And what a long thread that 
was! But full of good, genuine discussions on pros and cons of various 
details. Changing the protocol is permanent in a way many other changes 
are not. I feel good about where we arrived in the end.

-- 
Heikki Linnakangas
Neon (https://neon.tech)






^ permalink  raw  reply  [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2025-04-03 11:29  Daniel Gustafsson <daniel@yesql.se>
  parent: Heikki Linnakangas <hlinnaka@iki.fi>
  0 siblings, 1 reply; 40+ messages in thread

From: Daniel Gustafsson @ 2025-04-03 11:29 UTC (permalink / raw)
  To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Jelte Fennema-Nio <postgres@jeltef.nl>; Robert Haas <robertmhaas@gmail.com>; Jacob Champion <jacob.champion@enterprisedb.com>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>

> On 2 Apr 2025, at 15:48, Heikki Linnakangas <hlinnaka@iki.fi> wrote:

> And committed, with minor a bunch more little cleanups.

0001 in commit 09be39112654 seems to have missed (omitted?) adding the HAVE_
macros to pg_config.h.in, which doesn't matter as of now since they're not used
but it will be in the way for anyone running autoheader.  Any objection to me
pushing the attached?

--
Daniel Gustafsson

Attachments:

timingsafe.diff (application/octet-stream, 794B) download diff --git a/src/include/pg_config.h.in b/src/include/pg_config.h.in index 2428e4f854f..c2f1241b234 100644 --- a/src/include/pg_config.h.in +++ b/src/include/pg_config.h.in @@ -123,6 +123,10 @@ */ #undef HAVE_DECL_STRSEP +/* Define to 1 if you have the declaration of `timingsafe_bcmp', and to 0 if + you don't. */ +#undef HAVE_DECL_TIMINGSAFE_BCMP + /* Define to 1 if you have the <editline/history.h> header file. */ #undef HAVE_EDITLINE_HISTORY_H @@ -455,6 +459,9 @@ /* Define to 1 if curl_global_init() is guaranteed to be thread-safe. */ #undef HAVE_THREADSAFE_CURL_GLOBAL_INIT +/* Define to 1 if you have the `timingsafe_bcmp' function. */ +#undef HAVE_TIMINGSAFE_BCMP + /* Define to 1 if your compiler understands `typeof' or something similar. */ #undef HAVE_TYPEOF
^ permalink raw reply [nested|flat] 40+ messages in thread

* Re: Make query cancellation keys longer
@ 2025-04-03 11:33  Heikki Linnakangas <hlinnaka@iki.fi>
  parent: Daniel Gustafsson <daniel@yesql.se>
  0 siblings, 0 replies; 40+ messages in thread

From: Heikki Linnakangas @ 2025-04-03 11:33 UTC (permalink / raw)
  To: Daniel Gustafsson <daniel@yesql.se>; +Cc: Jelte Fennema-Nio <postgres@jeltef.nl>; Robert Haas <robertmhaas@gmail.com>; Jacob Champion <jacob.champion@enterprisedb.com>; pgsql-hackers; Thomas Munro <thomas.munro@gmail.com>

On 03/04/2025 14:29, Daniel Gustafsson wrote:
>> On 2 Apr 2025, at 15:48, Heikki Linnakangas <hlinnaka@iki.fi> wrote:
> 
>> And committed, with minor a bunch more little cleanups.
> 
> 0001 in commit 09be39112654 seems to have missed (omitted?) adding the HAVE_
> macros to pg_config.h.in, which doesn't matter as of now since they're not used
> but it will be in the way for anyone running autoheader.  Any objection to me
> pushing the attached?

Sounds good, thanks!

-- 
Heikki Linnakangas
Neon (https://neon.tech)





^ permalink  raw  reply  [nested|flat] 40+ messages in thread


end of thread, other threads:[~2025-04-03 11:33 UTC | newest]

Thread overview: 40+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2024-02-29 21:25 Make query cancellation keys longer Heikki Linnakangas <hlinnaka@iki.fi>
2024-03-01 05:19 ` Jelte Fennema-Nio <postgres@jeltef.nl>
2024-03-03 14:27   ` Jelte Fennema-Nio <postgres@jeltef.nl>
2024-03-03 17:27     ` Jelte Fennema-Nio <postgres@jeltef.nl>
2024-03-08 22:20       ` Heikki Linnakangas <hlinnaka@iki.fi>
2024-03-09 12:32         ` Jelte Fennema-Nio <postgres@jeltef.nl>
2024-06-05 15:25         ` Robert Haas <robertmhaas@gmail.com>
2024-07-04 10:32           ` Heikki Linnakangas <hlinnaka@iki.fi>
2024-07-04 10:35             ` Heikki Linnakangas <hlinnaka@iki.fi>
2024-07-04 10:50               ` Jelte Fennema-Nio <postgres@jeltef.nl>
2024-07-04 11:35                 ` Heikki Linnakangas <hlinnaka@iki.fi>
2024-07-04 12:43                   ` Tomas Vondra <tomas.vondra@enterprisedb.com>
2024-07-04 13:31                     ` Jelte Fennema-Nio <postgres@jeltef.nl>
2024-07-04 12:20             ` Jelte Fennema-Nio <postgres@jeltef.nl>
2024-07-24 16:12               ` Heikki Linnakangas <hlinnaka@iki.fi>
2024-07-29 13:19                 ` Heikki Linnakangas <hlinnaka@iki.fi>
2024-08-12 11:45                   ` Thomas Munro <thomas.munro@gmail.com>
2024-08-15 17:13                   ` Heikki Linnakangas <hlinnaka@iki.fi>
2024-08-15 20:20                     ` Robert Haas <robertmhaas@gmail.com>
2024-08-15 22:07                       ` Heikki Linnakangas <hlinnaka@iki.fi>
2024-08-16 12:31                         ` Robert Haas <robertmhaas@gmail.com>
2024-08-16 14:37                           ` Heikki Linnakangas <hlinnaka@iki.fi>
2024-08-16 15:29                             ` Robert Haas <robertmhaas@gmail.com>
2024-09-09 15:58                               ` Robert Haas <robertmhaas@gmail.com>
2025-02-22 14:58                                 ` Jelte Fennema-Nio <postgres@jeltef.nl>
2025-02-24 17:24                                   ` Robert Haas <robertmhaas@gmail.com>
2025-02-25 14:28                                     ` Jelte Fennema-Nio <postgres@jeltef.nl>
2025-02-26 20:18                                       ` Robert Haas <robertmhaas@gmail.com>
2025-04-01 14:08                                   ` Heikki Linnakangas <hlinnaka@iki.fi>
2025-04-02 13:48                                     ` Heikki Linnakangas <hlinnaka@iki.fi>
2025-04-03 11:29                                       ` Daniel Gustafsson <daniel@yesql.se>
2025-04-03 11:33                                         ` Heikki Linnakangas <hlinnaka@iki.fi>
2024-09-05 15:43                     ` Jacob Champion <jacob.champion@enterprisedb.com>
2024-09-05 16:21                       ` Tom Lane <tgl@sss.pgh.pa.us>
2024-09-05 16:33                         ` Jacob Champion <jacob.champion@enterprisedb.com>
2024-09-05 16:36                       ` Jelte Fennema-Nio <postgres@jeltef.nl>
2024-09-05 17:08                         ` Jacob Champion <jacob.champion@enterprisedb.com>
2024-03-01 14:19 ` Peter Eisentraut <peter@eisentraut.org>
2024-03-03 06:59   ` Jelte Fennema-Nio <postgres@jeltef.nl>
2024-03-06 01:12   ` Bruce Momjian <bruce@momjian.us>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox