PostgreSQL Source Code  git master
backend_startup.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * backend_startup.c
4  * Backend startup code
5  *
6  * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/tcop/backend_startup.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 
16 #include "postgres.h"
17 
18 #include <unistd.h>
19 
20 #include "access/xlog.h"
21 #include "common/ip.h"
22 #include "common/string.h"
23 #include "libpq/libpq.h"
24 #include "libpq/libpq-be.h"
25 #include "libpq/pqformat.h"
26 #include "libpq/pqsignal.h"
27 #include "miscadmin.h"
28 #include "postmaster/postmaster.h"
29 #include "replication/walsender.h"
30 #include "storage/fd.h"
31 #include "storage/ipc.h"
32 #include "storage/proc.h"
33 #include "tcop/backend_startup.h"
34 #include "tcop/tcopprot.h"
35 #include "utils/builtins.h"
36 #include "utils/injection_point.h"
37 #include "utils/memutils.h"
38 #include "utils/ps_status.h"
39 #include "utils/timeout.h"
40 
41 /* GUCs */
43 
44 static void BackendInitialize(ClientSocket *client_sock, CAC_state cac);
45 static int ProcessSSLStartup(Port *port);
46 static int ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done);
47 static void SendNegotiateProtocolVersion(List *unrecognized_protocol_options);
49 static void StartupPacketTimeoutHandler(void);
50 
51 /*
52  * Entry point for a new backend process.
53  *
54  * Initialize the connection, read the startup packet, authenticate the
55  * client, and start the main processing loop.
56  */
57 void
58 BackendMain(char *startup_data, size_t startup_data_len)
59 {
60  BackendStartupData *bsdata = (BackendStartupData *) startup_data;
61 
62  Assert(startup_data_len == sizeof(BackendStartupData));
63  Assert(MyClientSocket != NULL);
64 
65 #ifdef EXEC_BACKEND
66 
67  /*
68  * Need to reinitialize the SSL library in the backend, since the context
69  * structures contain function pointers and cannot be passed through the
70  * parameter file.
71  *
72  * If for some reason reload fails (maybe the user installed broken key
73  * files), soldier on without SSL; that's better than all connections
74  * becoming impossible.
75  *
76  * XXX should we do this in all child processes? For the moment it's
77  * enough to do it in backend children.
78  */
79 #ifdef USE_SSL
80  if (EnableSSL)
81  {
82  if (secure_initialize(false) == 0)
83  LoadedSSL = true;
84  else
85  ereport(LOG,
86  (errmsg("SSL configuration could not be loaded in child process")));
87  }
88 #endif
89 #endif
90 
91  /* Perform additional initialization and collect startup packet */
93 
94  /*
95  * Create a per-backend PGPROC struct in shared memory. We must do this
96  * before we can use LWLocks or access any shared memory.
97  */
98  InitProcess();
99 
100  /*
101  * Make sure we aren't in PostmasterContext anymore. (We can't delete it
102  * just yet, though, because InitPostgres will need the HBA data.)
103  */
105 
107 }
108 
109 
110 /*
111  * BackendInitialize -- initialize an interactive (postmaster-child)
112  * backend process, and collect the client's startup packet.
113  *
114  * returns: nothing. Will not return at all if there's any failure.
115  *
116  * Note: this code does not depend on having any access to shared memory.
117  * Indeed, our approach to SIGTERM/timeout handling *requires* that
118  * shared memory not have been touched yet; see comments within.
119  * In the EXEC_BACKEND case, we are physically attached to shared memory
120  * but have not yet set up most of our local pointers to shmem structures.
121  */
122 static void
124 {
125  int status;
126  int ret;
127  Port *port;
128  char remote_host[NI_MAXHOST];
129  char remote_port[NI_MAXSERV];
130  StringInfoData ps_data;
131  MemoryContext oldcontext;
132 
133  /* Tell fd.c about the long-lived FD associated with the client_sock */
135 
136  /*
137  * PreAuthDelay is a debugging aid for investigating problems in the
138  * authentication cycle: it can be set in postgresql.conf to allow time to
139  * attach to the newly-forked backend with a debugger. (See also
140  * PostAuthDelay, which we allow clients to pass through PGOPTIONS, but it
141  * is not honored until after authentication.)
142  */
143  if (PreAuthDelay > 0)
144  pg_usleep(PreAuthDelay * 1000000L);
145 
146  /* This flag will remain set until InitPostgres finishes authentication */
147  ClientAuthInProgress = true; /* limit visibility of log messages */
148 
149  /*
150  * Initialize libpq and enable reporting of ereport errors to the client.
151  * Must do this now because authentication uses libpq to send messages.
152  *
153  * The Port structure and all data structures attached to it are allocated
154  * in TopMemoryContext, so that they survive into PostgresMain execution.
155  * We need not worry about leaking this storage on failure, since we
156  * aren't in the postmaster process anymore.
157  */
159  port = MyProcPort = pq_init(client_sock);
160  MemoryContextSwitchTo(oldcontext);
161 
162  whereToSendOutput = DestRemote; /* now safe to ereport to client */
163 
164  /* set these to empty in case they are needed before we set them up */
165  port->remote_host = "";
166  port->remote_port = "";
167 
168  /*
169  * We arrange to do _exit(1) if we receive SIGTERM or timeout while trying
170  * to collect the startup packet; while SIGQUIT results in _exit(2).
171  * Otherwise the postmaster cannot shutdown the database FAST or IMMED
172  * cleanly if a buggy client fails to send the packet promptly.
173  *
174  * Exiting with _exit(1) is only possible because we have not yet touched
175  * shared memory; therefore no outside-the-process state needs to get
176  * cleaned up.
177  */
179  /* SIGQUIT handler was already set up by InitPostmasterChild */
180  InitializeTimeouts(); /* establishes SIGALRM handler */
181  sigprocmask(SIG_SETMASK, &StartupBlockSig, NULL);
182 
183  /*
184  * Get the remote host name and port for logging and status display.
185  */
186  remote_host[0] = '\0';
187  remote_port[0] = '\0';
188  if ((ret = pg_getnameinfo_all(&port->raddr.addr, port->raddr.salen,
189  remote_host, sizeof(remote_host),
190  remote_port, sizeof(remote_port),
191  (log_hostname ? 0 : NI_NUMERICHOST) | NI_NUMERICSERV)) != 0)
193  (errmsg_internal("pg_getnameinfo_all() failed: %s",
194  gai_strerror(ret))));
195 
196  /*
197  * Save remote_host and remote_port in port structure (after this, they
198  * will appear in log_line_prefix data for log messages).
199  */
200  port->remote_host = MemoryContextStrdup(TopMemoryContext, remote_host);
201  port->remote_port = MemoryContextStrdup(TopMemoryContext, remote_port);
202 
203  /* And now we can issue the Log_connections message, if wanted */
204  if (Log_connections)
205  {
206  if (remote_port[0])
207  ereport(LOG,
208  (errmsg("connection received: host=%s port=%s",
209  remote_host,
210  remote_port)));
211  else
212  ereport(LOG,
213  (errmsg("connection received: host=%s",
214  remote_host)));
215  }
216 
217  /* For testing client error handling */
218 #ifdef USE_INJECTION_POINTS
219  INJECTION_POINT("backend-initialize");
220  if (IS_INJECTION_POINT_ATTACHED("backend-initialize-v2-error"))
221  {
222  /*
223  * This simulates an early error from a pre-v14 server, which used the
224  * version 2 protocol for any errors that occurred before processing
225  * the startup packet.
226  */
228  elog(FATAL, "protocol version 2 error triggered");
229  }
230 #endif
231 
232  /*
233  * If we did a reverse lookup to name, we might as well save the results
234  * rather than possibly repeating the lookup during authentication.
235  *
236  * Note that we don't want to specify NI_NAMEREQD above, because then we'd
237  * get nothing useful for a client without an rDNS entry. Therefore, we
238  * must check whether we got a numeric IPv4 or IPv6 address, and not save
239  * it into remote_hostname if so. (This test is conservative and might
240  * sometimes classify a hostname as numeric, but an error in that
241  * direction is safe; it only results in a possible extra lookup.)
242  */
243  if (log_hostname &&
244  ret == 0 &&
245  strspn(remote_host, "0123456789.") < strlen(remote_host) &&
246  strspn(remote_host, "0123456789ABCDEFabcdef:") < strlen(remote_host))
247  {
248  port->remote_hostname = MemoryContextStrdup(TopMemoryContext, remote_host);
249  }
250 
251  /*
252  * Ready to begin client interaction. We will give up and _exit(1) after
253  * a time delay, so that a broken client can't hog a connection
254  * indefinitely. PreAuthDelay and any DNS interactions above don't count
255  * against the time limit.
256  *
257  * Note: AuthenticationTimeout is applied here while waiting for the
258  * startup packet, and then again in InitPostgres for the duration of any
259  * authentication operations. So a hostile client could tie up the
260  * process for nearly twice AuthenticationTimeout before we kick him off.
261  *
262  * Note: because PostgresMain will call InitializeTimeouts again, the
263  * registration of STARTUP_PACKET_TIMEOUT will be lost. This is okay
264  * since we never use it again after this function.
265  */
268 
269  /* Handle direct SSL handshake */
270  status = ProcessSSLStartup(port);
271 
272  /*
273  * Receive the startup packet (which might turn out to be a cancel request
274  * packet).
275  */
276  if (status == STATUS_OK)
277  status = ProcessStartupPacket(port, false, false);
278 
279  /*
280  * If we're going to reject the connection due to database state, say so
281  * now instead of wasting cycles on an authentication exchange. (This also
282  * allows a pg_ping utility to be written.)
283  */
284  if (status == STATUS_OK)
285  {
286  switch (cac)
287  {
288  case CAC_STARTUP:
289  ereport(FATAL,
291  errmsg("the database system is starting up")));
292  break;
293  case CAC_NOTCONSISTENT:
294  if (EnableHotStandby)
295  ereport(FATAL,
297  errmsg("the database system is not yet accepting connections"),
298  errdetail("Consistent recovery state has not been yet reached.")));
299  else
300  ereport(FATAL,
302  errmsg("the database system is not accepting connections"),
303  errdetail("Hot standby mode is disabled.")));
304  break;
305  case CAC_SHUTDOWN:
306  ereport(FATAL,
308  errmsg("the database system is shutting down")));
309  break;
310  case CAC_RECOVERY:
311  ereport(FATAL,
313  errmsg("the database system is in recovery mode")));
314  break;
315  case CAC_TOOMANY:
316  ereport(FATAL,
317  (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
318  errmsg("sorry, too many clients already")));
319  break;
320  case CAC_OK:
321  break;
322  }
323  }
324 
325  /*
326  * Disable the timeout, and prevent SIGTERM again.
327  */
329  sigprocmask(SIG_SETMASK, &BlockSig, NULL);
330 
331  /*
332  * As a safety check that nothing in startup has yet performed
333  * shared-memory modifications that would need to be undone if we had
334  * exited through SIGTERM or timeout above, check that no on_shmem_exit
335  * handlers have been registered yet. (This isn't terribly bulletproof,
336  * since someone might misuse an on_proc_exit handler for shmem cleanup,
337  * but it's a cheap and helpful check. We cannot disallow on_proc_exit
338  * handlers unfortunately, since pq_init() already registered one.)
339  */
341 
342  /*
343  * Stop here if it was bad or a cancel packet. ProcessStartupPacket
344  * already did any appropriate error reporting.
345  */
346  if (status != STATUS_OK)
347  proc_exit(0);
348 
349  /*
350  * Now that we have the user and database name, we can set the process
351  * title for ps. It's good to do this as early as possible in startup.
352  */
353  initStringInfo(&ps_data);
354  if (am_walsender)
356  appendStringInfo(&ps_data, "%s ", port->user_name);
357  if (port->database_name[0] != '\0')
358  appendStringInfo(&ps_data, "%s ", port->database_name);
359  appendStringInfoString(&ps_data, port->remote_host);
360  if (port->remote_port[0] != '\0')
361  appendStringInfo(&ps_data, "(%s)", port->remote_port);
362 
363  init_ps_display(ps_data.data);
364  pfree(ps_data.data);
365 
366  set_ps_display("initializing");
367 }
368 
369 /*
370  * Check for a direct SSL connection.
371  *
372  * This happens before the startup packet so we are careful not to actually
373  * read any bytes from the stream if it's not a direct SSL connection.
374  */
375 static int
377 {
378  int firstbyte;
379 
380  Assert(!port->ssl_in_use);
381 
382  pq_startmsgread();
383  firstbyte = pq_peekbyte();
384  pq_endmsgread();
385  if (firstbyte == EOF)
386  {
387  /*
388  * Like in ProcessStartupPacket, if we get no data at all, don't
389  * clutter the log with a complaint.
390  */
391  return STATUS_ERROR;
392  }
393 
394  if (firstbyte != 0x16)
395  {
396  /* Not an SSL handshake message */
397  return STATUS_OK;
398  }
399 
400  /*
401  * First byte indicates standard SSL handshake message
402  *
403  * (It can't be a Postgres startup length because in network byte order
404  * that would be a startup packet hundreds of megabytes long)
405  */
406 
407 #ifdef USE_SSL
408  if (!LoadedSSL || port->laddr.addr.ss_family == AF_UNIX)
409  {
410  /* SSL not supported */
411  goto reject;
412  }
413 
414  if (secure_open_server(port) == -1)
415  {
416  /*
417  * we assume secure_open_server() sent an appropriate TLS alert
418  * already
419  */
420  goto reject;
421  }
422  Assert(port->ssl_in_use);
423 
424  if (!port->alpn_used)
425  {
427  (errcode(ERRCODE_PROTOCOL_VIOLATION),
428  errmsg("received direct SSL connection request without ALPN protocol negotiation extension")));
429  goto reject;
430  }
431 
433  ereport(LOG,
434  (errmsg("direct SSL connection accepted")));
435  return STATUS_OK;
436 #else
437  /* SSL not supported by this build */
438  goto reject;
439 #endif
440 
441 reject:
443  ereport(LOG,
444  (errmsg("direct SSL connection rejected")));
445  return STATUS_ERROR;
446 }
447 
448 /*
449  * Read a client's startup packet and do something according to it.
450  *
451  * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
452  * not return at all.
453  *
454  * (Note that ereport(FATAL) stuff is sent to the client, so only use it
455  * if that's what you want. Return STATUS_ERROR if you don't want to
456  * send anything to the client, which would typically be appropriate
457  * if we detect a communications failure.)
458  *
459  * Set ssl_done and/or gss_done when negotiation of an encrypted layer
460  * (currently, TLS or GSSAPI) is completed. A successful negotiation of either
461  * encryption layer sets both flags, but a rejected negotiation sets only the
462  * flag for that layer, since the client may wish to try the other one. We
463  * should make no assumption here about the order in which the client may make
464  * requests.
465  */
466 static int
467 ProcessStartupPacket(Port *port, bool ssl_done, bool gss_done)
468 {
469  int32 len;
470  char *buf;
471  ProtocolVersion proto;
472  MemoryContext oldcontext;
473 
474  pq_startmsgread();
475 
476  /*
477  * Grab the first byte of the length word separately, so that we can tell
478  * whether we have no data at all or an incomplete packet. (This might
479  * sound inefficient, but it's not really, because of buffering in
480  * pqcomm.c.)
481  */
482  if (pq_getbytes((char *) &len, 1) == EOF)
483  {
484  /*
485  * If we get no data at all, don't clutter the log with a complaint;
486  * such cases often occur for legitimate reasons. An example is that
487  * we might be here after responding to NEGOTIATE_SSL_CODE, and if the
488  * client didn't like our response, it'll probably just drop the
489  * connection. Service-monitoring software also often just opens and
490  * closes a connection without sending anything. (So do port
491  * scanners, which may be less benign, but it's not really our job to
492  * notice those.)
493  */
494  return STATUS_ERROR;
495  }
496 
497  if (pq_getbytes(((char *) &len) + 1, 3) == EOF)
498  {
499  /* Got a partial length word, so bleat about that */
500  if (!ssl_done && !gss_done)
502  (errcode(ERRCODE_PROTOCOL_VIOLATION),
503  errmsg("incomplete startup packet")));
504  return STATUS_ERROR;
505  }
506 
507  len = pg_ntoh32(len);
508  len -= 4;
509 
510  if (len < (int32) sizeof(ProtocolVersion) ||
512  {
514  (errcode(ERRCODE_PROTOCOL_VIOLATION),
515  errmsg("invalid length of startup packet")));
516  return STATUS_ERROR;
517  }
518 
519  /*
520  * Allocate space to hold the startup packet, plus one extra byte that's
521  * initialized to be zero. This ensures we will have null termination of
522  * all strings inside the packet.
523  */
524  buf = palloc(len + 1);
525  buf[len] = '\0';
526 
527  if (pq_getbytes(buf, len) == EOF)
528  {
530  (errcode(ERRCODE_PROTOCOL_VIOLATION),
531  errmsg("incomplete startup packet")));
532  return STATUS_ERROR;
533  }
534  pq_endmsgread();
535 
536  /*
537  * The first field is either a protocol version number or a special
538  * request code.
539  */
540  port->proto = proto = pg_ntoh32(*((ProtocolVersion *) buf));
541 
542  if (proto == CANCEL_REQUEST_CODE)
543  {
544  CancelRequestPacket *canc;
545  int backendPID;
546  int32 cancelAuthCode;
547 
548  if (len != sizeof(CancelRequestPacket))
549  {
551  (errcode(ERRCODE_PROTOCOL_VIOLATION),
552  errmsg("invalid length of startup packet")));
553  return STATUS_ERROR;
554  }
555  canc = (CancelRequestPacket *) buf;
556  backendPID = (int) pg_ntoh32(canc->backendPID);
557  cancelAuthCode = (int32) pg_ntoh32(canc->cancelAuthCode);
558 
559  processCancelRequest(backendPID, cancelAuthCode);
560  /* Not really an error, but we don't want to proceed further */
561  return STATUS_ERROR;
562  }
563 
564  if (proto == NEGOTIATE_SSL_CODE && !ssl_done)
565  {
566  char SSLok;
567 
568 #ifdef USE_SSL
569 
570  /*
571  * No SSL when disabled or on Unix sockets.
572  *
573  * Also no SSL negotiation if we already have a direct SSL connection
574  */
575  if (!LoadedSSL || port->laddr.addr.ss_family == AF_UNIX || port->ssl_in_use)
576  SSLok = 'N';
577  else
578  SSLok = 'S'; /* Support for SSL */
579 #else
580  SSLok = 'N'; /* No support for SSL */
581 #endif
582 
584  {
585  if (SSLok == 'S')
586  ereport(LOG,
587  (errmsg("SSLRequest accepted")));
588  else
589  ereport(LOG,
590  (errmsg("SSLRequest rejected")));
591  }
592 
593  while (secure_write(port, &SSLok, 1) != 1)
594  {
595  if (errno == EINTR)
596  continue; /* if interrupted, just retry */
599  errmsg("failed to send SSL negotiation response: %m")));
600  return STATUS_ERROR; /* close the connection */
601  }
602 
603 #ifdef USE_SSL
604  if (SSLok == 'S' && secure_open_server(port) == -1)
605  return STATUS_ERROR;
606 #endif
607 
608  /*
609  * At this point we should have no data already buffered. If we do,
610  * it was received before we performed the SSL handshake, so it wasn't
611  * encrypted and indeed may have been injected by a man-in-the-middle.
612  * We report this case to the client.
613  */
614  if (pq_buffer_remaining_data() > 0)
615  ereport(FATAL,
616  (errcode(ERRCODE_PROTOCOL_VIOLATION),
617  errmsg("received unencrypted data after SSL request"),
618  errdetail("This could be either a client-software bug or evidence of an attempted man-in-the-middle attack.")));
619 
620  /*
621  * regular startup packet, cancel, etc packet should follow, but not
622  * another SSL negotiation request, and a GSS request should only
623  * follow if SSL was rejected (client may negotiate in either order)
624  */
625  return ProcessStartupPacket(port, true, SSLok == 'S');
626  }
627  else if (proto == NEGOTIATE_GSS_CODE && !gss_done)
628  {
629  char GSSok = 'N';
630 
631 #ifdef ENABLE_GSS
632  /* No GSSAPI encryption when on Unix socket */
633  if (port->laddr.addr.ss_family != AF_UNIX)
634  GSSok = 'G';
635 #endif
636 
638  {
639  if (GSSok == 'G')
640  ereport(LOG,
641  (errmsg("GSSENCRequest accepted")));
642  else
643  ereport(LOG,
644  (errmsg("GSSENCRequest rejected")));
645  }
646 
647  while (secure_write(port, &GSSok, 1) != 1)
648  {
649  if (errno == EINTR)
650  continue;
653  errmsg("failed to send GSSAPI negotiation response: %m")));
654  return STATUS_ERROR; /* close the connection */
655  }
656 
657 #ifdef ENABLE_GSS
658  if (GSSok == 'G' && secure_open_gssapi(port) == -1)
659  return STATUS_ERROR;
660 #endif
661 
662  /*
663  * At this point we should have no data already buffered. If we do,
664  * it was received before we performed the GSS handshake, so it wasn't
665  * encrypted and indeed may have been injected by a man-in-the-middle.
666  * We report this case to the client.
667  */
668  if (pq_buffer_remaining_data() > 0)
669  ereport(FATAL,
670  (errcode(ERRCODE_PROTOCOL_VIOLATION),
671  errmsg("received unencrypted data after GSSAPI encryption request"),
672  errdetail("This could be either a client-software bug or evidence of an attempted man-in-the-middle attack.")));
673 
674  /*
675  * regular startup packet, cancel, etc packet should follow, but not
676  * another GSS negotiation request, and an SSL request should only
677  * follow if GSS was rejected (client may negotiate in either order)
678  */
679  return ProcessStartupPacket(port, GSSok == 'G', true);
680  }
681 
682  /* Could add additional special packet types here */
683 
684  /*
685  * Set FrontendProtocol now so that ereport() knows what format to send if
686  * we fail during startup.
687  */
688  FrontendProtocol = proto;
689 
690  /* Check that the major protocol version is in range. */
693  ereport(FATAL,
694  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
695  errmsg("unsupported frontend protocol %u.%u: server supports %u.0 to %u.%u",
696  PG_PROTOCOL_MAJOR(proto), PG_PROTOCOL_MINOR(proto),
700 
701  /*
702  * Now fetch parameters out of startup packet and save them into the Port
703  * structure.
704  */
706 
707  /* Handle protocol version 3 startup packet */
708  {
709  int32 offset = sizeof(ProtocolVersion);
710  List *unrecognized_protocol_options = NIL;
711 
712  /*
713  * Scan packet body for name/option pairs. We can assume any string
714  * beginning within the packet body is null-terminated, thanks to
715  * zeroing extra byte above.
716  */
717  port->guc_options = NIL;
718 
719  while (offset < len)
720  {
721  char *nameptr = buf + offset;
722  int32 valoffset;
723  char *valptr;
724 
725  if (*nameptr == '\0')
726  break; /* found packet terminator */
727  valoffset = offset + strlen(nameptr) + 1;
728  if (valoffset >= len)
729  break; /* missing value, will complain below */
730  valptr = buf + valoffset;
731 
732  if (strcmp(nameptr, "database") == 0)
733  port->database_name = pstrdup(valptr);
734  else if (strcmp(nameptr, "user") == 0)
735  port->user_name = pstrdup(valptr);
736  else if (strcmp(nameptr, "options") == 0)
737  port->cmdline_options = pstrdup(valptr);
738  else if (strcmp(nameptr, "replication") == 0)
739  {
740  /*
741  * Due to backward compatibility concerns the replication
742  * parameter is a hybrid beast which allows the value to be
743  * either boolean or the string 'database'. The latter
744  * connects to a specific database which is e.g. required for
745  * logical decoding while.
746  */
747  if (strcmp(valptr, "database") == 0)
748  {
749  am_walsender = true;
750  am_db_walsender = true;
751  }
752  else if (!parse_bool(valptr, &am_walsender))
753  ereport(FATAL,
754  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
755  errmsg("invalid value for parameter \"%s\": \"%s\"",
756  "replication",
757  valptr),
758  errhint("Valid values are: \"false\", 0, \"true\", 1, \"database\".")));
759  }
760  else if (strncmp(nameptr, "_pq_.", 5) == 0)
761  {
762  /*
763  * Any option beginning with _pq_. is reserved for use as a
764  * protocol-level option, but at present no such options are
765  * defined.
766  */
767  unrecognized_protocol_options =
768  lappend(unrecognized_protocol_options, pstrdup(nameptr));
769  }
770  else
771  {
772  /* Assume it's a generic GUC option */
773  port->guc_options = lappend(port->guc_options,
774  pstrdup(nameptr));
775  port->guc_options = lappend(port->guc_options,
776  pstrdup(valptr));
777 
778  /*
779  * Copy application_name to port if we come across it. This
780  * is done so we can log the application_name in the
781  * connection authorization message. Note that the GUC would
782  * be used but we haven't gone through GUC setup yet.
783  */
784  if (strcmp(nameptr, "application_name") == 0)
785  {
786  port->application_name = pg_clean_ascii(valptr, 0);
787  }
788  }
789  offset = valoffset + strlen(valptr) + 1;
790  }
791 
792  /*
793  * If we didn't find a packet terminator exactly at the end of the
794  * given packet length, complain.
795  */
796  if (offset != len - 1)
797  ereport(FATAL,
798  (errcode(ERRCODE_PROTOCOL_VIOLATION),
799  errmsg("invalid startup packet layout: expected terminator as last byte")));
800 
801  /*
802  * If the client requested a newer protocol version or if the client
803  * requested any protocol options we didn't recognize, let them know
804  * the newest minor protocol version we do support and the names of
805  * any unrecognized options.
806  */
808  unrecognized_protocol_options != NIL)
809  SendNegotiateProtocolVersion(unrecognized_protocol_options);
810  }
811 
812  /* Check a user name was given. */
813  if (port->user_name == NULL || port->user_name[0] == '\0')
814  ereport(FATAL,
815  (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
816  errmsg("no PostgreSQL user name specified in startup packet")));
817 
818  /* The database defaults to the user name. */
819  if (port->database_name == NULL || port->database_name[0] == '\0')
820  port->database_name = pstrdup(port->user_name);
821 
822  if (am_walsender)
824  else
826 
827  /*
828  * Normal walsender backends, e.g. for streaming replication, are not
829  * connected to a particular database. But walsenders used for logical
830  * replication need to connect to a specific database. We allow streaming
831  * replication commands to be issued even if connected to a database as it
832  * can make sense to first make a basebackup and then stream changes
833  * starting from that.
834  */
836  port->database_name[0] = '\0';
837 
838  /*
839  * Done filling the Port structure
840  */
841  MemoryContextSwitchTo(oldcontext);
842 
843  return STATUS_OK;
844 }
845 
846 /*
847  * Send a NegotiateProtocolVersion to the client. This lets the client know
848  * that they have requested a newer minor protocol version than we are able
849  * to speak. We'll speak the highest version we know about; the client can,
850  * of course, abandon the connection if that's a problem.
851  *
852  * We also include in the response a list of protocol options we didn't
853  * understand. This allows clients to include optional parameters that might
854  * be present either in newer protocol versions or third-party protocol
855  * extensions without fear of having to reconnect if those options are not
856  * understood, while at the same time making certain that the client is aware
857  * of which options were actually accepted.
858  */
859 static void
860 SendNegotiateProtocolVersion(List *unrecognized_protocol_options)
861 {
863  ListCell *lc;
864 
867  pq_sendint32(&buf, list_length(unrecognized_protocol_options));
868  foreach(lc, unrecognized_protocol_options)
869  pq_sendstring(&buf, lfirst(lc));
870  pq_endmessage(&buf);
871 
872  /* no need to flush, some other message will follow */
873 }
874 
875 
876 /*
877  * SIGTERM while processing startup packet.
878  *
879  * Running proc_exit() from a signal handler would be quite unsafe.
880  * However, since we have not yet touched shared memory, we can just
881  * pull the plug and exit without running any atexit handlers.
882  *
883  * One might be tempted to try to send a message, or log one, indicating
884  * why we are disconnecting. However, that would be quite unsafe in itself.
885  * Also, it seems undesirable to provide clues about the database's state
886  * to a client that has not yet completed authentication, or even sent us
887  * a startup packet.
888  */
889 static void
891 {
892  _exit(1);
893 }
894 
895 /*
896  * Timeout while processing startup packet.
897  * As for process_startup_packet_die(), we exit via _exit(1).
898  */
899 static void
901 {
902  _exit(1);
903 }
sigset_t StartupBlockSig
Definition: pqsignal.c:24
sigset_t BlockSig
Definition: pqsignal.c:23
bool Trace_connection_negotiation
static void SendNegotiateProtocolVersion(List *unrecognized_protocol_options)
void BackendMain(char *startup_data, size_t startup_data_len)
static void process_startup_packet_die(SIGNAL_ARGS)
static void StartupPacketTimeoutHandler(void)
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)
CAC_state
@ CAC_TOOMANY
@ CAC_OK
@ CAC_RECOVERY
@ CAC_NOTCONSISTENT
@ CAC_STARTUP
@ CAC_SHUTDOWN
ssize_t secure_open_gssapi(Port *port)
int secure_initialize(bool isServerStart)
Definition: be-secure.c:74
ssize_t secure_write(Port *port, void *ptr, size_t len)
Definition: be-secure.c:304
int secure_open_server(Port *port)
Definition: be-secure.c:111
bool parse_bool(const char *value, bool *result)
Definition: bool.c:30
#define STATUS_OK
Definition: c.h:1169
signed int int32
Definition: c.h:494
#define SIGNAL_ARGS
Definition: c.h:1345
#define Assert(condition)
Definition: c.h:858
#define STATUS_ERROR
Definition: c.h:1170
@ DestRemote
Definition: dest.h:89
int errcode_for_socket_access(void)
Definition: elog.c:953
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1157
int errdetail(const char *fmt,...)
Definition: elog.c:1203
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define LOG
Definition: elog.h:31
#define COMMERROR
Definition: elog.h:33
#define FATAL
Definition: elog.h:41
#define WARNING
Definition: elog.h:36
#define elog(elevel,...)
Definition: elog.h:224
#define ereport(elevel,...)
Definition: elog.h:149
void ReserveExternalFD(void)
Definition: fd.c:1221
#define ERRCODE_CANNOT_CONNECT_NOW
Definition: fe-connect.c:91
struct ClientSocket * MyClientSocket
Definition: globals.c:49
ProtocolVersion FrontendProtocol
Definition: globals.c:29
struct Port * MyProcPort
Definition: globals.c:50
#define INJECTION_POINT(name)
#define IS_INJECTION_POINT_ATTACHED(name)
int pg_getnameinfo_all(const struct sockaddr_storage *addr, int salen, char *node, int nodelen, char *service, int servicelen, int flags)
Definition: ip.c:114
void check_on_shmem_exit_lists_are_empty(void)
Definition: ipc.c:432
void proc_exit(int code)
Definition: ipc.c:104
List * lappend(List *list, void *datum)
Definition: list.c:339
char * pstrdup(const char *in)
Definition: mcxt.c:1696
void pfree(void *pointer)
Definition: mcxt.c:1521
MemoryContext TopMemoryContext
Definition: mcxt.c:149
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1683
void * palloc(Size size)
Definition: mcxt.c:1317
@ B_WAL_SENDER
Definition: miscadmin.h:342
@ B_BACKEND
Definition: miscadmin.h:338
const char * GetBackendTypeDesc(BackendType backendType)
Definition: miscinit.c:263
BackendType MyBackendType
Definition: miscinit.c:63
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
const void size_t len
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
static int port
Definition: pg_regress.c:116
static char * buf
Definition: pg_test_fsync.c:73
pqsigfunc pqsignal(int signo, pqsigfunc func)
CommandDest whereToSendOutput
Definition: postgres.c:90
void PostgresMain(const char *dbname, const char *username)
Definition: postgres.c:4151
int PreAuthDelay
Definition: postmaster.c:227
bool log_hostname
Definition: postmaster.c:230
bool Log_connections
Definition: postmaster.c:231
bool ClientAuthInProgress
Definition: postmaster.c:350
void processCancelRequest(int backendPID, int32 cancelAuthCode)
Definition: postmaster.c:1835
int AuthenticationTimeout
Definition: postmaster.c:228
bool EnableSSL
Definition: postmaster.c:225
PGDLLIMPORT bool LoadedSSL
int pq_peekbyte(void)
Definition: pqcomm.c:983
int pq_getbytes(char *s, size_t len)
Definition: pqcomm.c:1063
Port * pq_init(ClientSocket *client_sock)
Definition: pqcomm.c:174
ssize_t pq_buffer_remaining_data(void)
Definition: pqcomm.c:1127
void pq_endmsgread(void)
Definition: pqcomm.c:1165
void pq_startmsgread(void)
Definition: pqcomm.c:1141
#define PG_PROTOCOL_MAJOR(v)
Definition: pqcomm.h:87
#define PG_PROTOCOL_EARLIEST
Definition: pqcomm.h:96
#define CANCEL_REQUEST_CODE
Definition: pqcomm.h:132
#define MAX_STARTUP_PACKET_LENGTH
Definition: pqcomm.h:118
#define PG_PROTOCOL_LATEST
Definition: pqcomm.h:97
#define NEGOTIATE_GSS_CODE
Definition: pqcomm.h:167
#define NEGOTIATE_SSL_CODE
Definition: pqcomm.h:166
uint32 ProtocolVersion
Definition: pqcomm.h:99
#define PG_PROTOCOL(m, n)
Definition: pqcomm.h:89
#define PG_PROTOCOL_MINOR(v)
Definition: pqcomm.h:88
void pq_sendstring(StringInfo buf, const char *str)
Definition: pqformat.c:195
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:296
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:88
static void pq_sendint32(StringInfo buf, uint32 i)
Definition: pqformat.h:144
#define PqMsg_NegotiateProtocolVersion
Definition: protocol.h:59
void init_ps_display(const char *fixed_part)
Definition: ps_status.c:267
static void set_ps_display(const char *activity)
Definition: ps_status.h:40
MemoryContextSwitchTo(old_ctx)
void pg_usleep(long microsec)
Definition: signal.c:53
const char * gai_strerror(int ecode)
void InitProcess(void)
Definition: proc.c:296
char * pg_clean_ascii(const char *str, int alloc_flags)
Definition: string.c:86
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:97
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:182
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
CAC_state canAcceptConnections
uint32 backendPID
Definition: pqcomm.h:138
uint32 cancelAuthCode
Definition: pqcomm.h:139
Definition: pg_list.h:54
Definition: libpq-be.h:133
char * user_name
Definition: libpq-be.h:152
char * database_name
Definition: libpq-be.h:151
void enable_timeout_after(TimeoutId id, int delay_ms)
Definition: timeout.c:560
void InitializeTimeouts(void)
Definition: timeout.c:470
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:685
TimeoutId RegisterTimeout(TimeoutId id, timeout_handler_proc handler)
Definition: timeout.c:505
@ STARTUP_PACKET_TIMEOUT
Definition: timeout.h:26
bool am_walsender
Definition: walsender.c:115
bool am_db_walsender
Definition: walsender.c:118
#define EINTR
Definition: win32_port.h:374
bool EnableHotStandby
Definition: xlog.c:119