LCOV - code coverage report
Current view: top level - src/backend/backup - basebackup.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 83.4 % 670 559
Test Date: 2026-07-15 15:16:33 Functions: 93.3 % 15 14
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 60.0 % 608 365

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * basebackup.c
       4                 :             :  *    code for taking a base backup and streaming it to a standby
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 2010-2026, PostgreSQL Global Development Group
       7                 :             :  *
       8                 :             :  * IDENTIFICATION
       9                 :             :  *    src/backend/backup/basebackup.c
      10                 :             :  *
      11                 :             :  *-------------------------------------------------------------------------
      12                 :             :  */
      13                 :             : #include "postgres.h"
      14                 :             : 
      15                 :             : #include <sys/stat.h>
      16                 :             : #include <unistd.h>
      17                 :             : #include <time.h>
      18                 :             : 
      19                 :             : #include "access/xlog_internal.h"
      20                 :             : #include "access/xlogbackup.h"
      21                 :             : #include "backup/backup_manifest.h"
      22                 :             : #include "backup/basebackup.h"
      23                 :             : #include "backup/basebackup_incremental.h"
      24                 :             : #include "backup/basebackup_sink.h"
      25                 :             : #include "backup/basebackup_target.h"
      26                 :             : #include "catalog/pg_tablespace_d.h"
      27                 :             : #include "commands/defrem.h"
      28                 :             : #include "common/compression.h"
      29                 :             : #include "common/file_perm.h"
      30                 :             : #include "common/file_utils.h"
      31                 :             : #include "lib/stringinfo.h"
      32                 :             : #include "miscadmin.h"
      33                 :             : #include "nodes/pg_list.h"
      34                 :             : #include "pgstat.h"
      35                 :             : #include "pgtar.h"
      36                 :             : #include "postmaster/syslogger.h"
      37                 :             : #include "postmaster/walsummarizer.h"
      38                 :             : #include "replication/slot.h"
      39                 :             : #include "replication/walsender.h"
      40                 :             : #include "replication/walsender_private.h"
      41                 :             : #include "storage/bufpage.h"
      42                 :             : #include "storage/checksum.h"
      43                 :             : #include "storage/dsm_impl.h"
      44                 :             : #include "storage/ipc.h"
      45                 :             : #include "storage/reinit.h"
      46                 :             : #include "utils/builtins.h"
      47                 :             : #include "utils/guc.h"
      48                 :             : #include "utils/ps_status.h"
      49                 :             : #include "utils/relcache.h"
      50                 :             : #include "utils/resowner.h"
      51                 :             : #include "utils/wait_event.h"
      52                 :             : 
      53                 :             : /*
      54                 :             :  * How much data do we want to send in one CopyData message? Note that
      55                 :             :  * this may also result in reading the underlying files in chunks of this
      56                 :             :  * size.
      57                 :             :  *
      58                 :             :  * NB: The buffer size is required to be a multiple of the system block
      59                 :             :  * size, so use that value instead if it's bigger than our preference.
      60                 :             :  */
      61                 :             : #define SINK_BUFFER_LENGTH          Max(32768, BLCKSZ)
      62                 :             : 
      63                 :             : typedef struct
      64                 :             : {
      65                 :             :     const char *label;
      66                 :             :     bool        progress;
      67                 :             :     bool        fastcheckpoint;
      68                 :             :     bool        nowait;
      69                 :             :     bool        includewal;
      70                 :             :     bool        incremental;
      71                 :             :     uint32      maxrate;
      72                 :             :     bool        sendtblspcmapfile;
      73                 :             :     bool        send_to_client;
      74                 :             :     bool        use_copytblspc;
      75                 :             :     BaseBackupTargetHandle *target_handle;
      76                 :             :     backup_manifest_option manifest;
      77                 :             :     pg_compress_algorithm compression;
      78                 :             :     pg_compress_specification compression_specification;
      79                 :             :     pg_checksum_type manifest_checksum_type;
      80                 :             : } basebackup_options;
      81                 :             : 
      82                 :             : #define TAR_NUM_TERMINATION_BLOCKS 2
      83                 :             : 
      84                 :             : StaticAssertDecl(TAR_NUM_TERMINATION_BLOCKS * TAR_BLOCK_SIZE <= BLCKSZ,
      85                 :             :                  "BLCKSZ too small for " CppAsString2(TAR_NUM_TERMINATION_BLOCKS) " tar termination blocks");
      86                 :             : 
      87                 :             : static int64 sendTablespace(bbsink *sink, char *path, Oid spcoid, bool sizeonly,
      88                 :             :                             struct backup_manifest_info *manifest,
      89                 :             :                             IncrementalBackupInfo *ib);
      90                 :             : static int64 sendDir(bbsink *sink, const char *path, int basepathlen, bool sizeonly,
      91                 :             :                      List *tablespaces, bool sendtblspclinks,
      92                 :             :                      backup_manifest_info *manifest, Oid spcoid,
      93                 :             :                      IncrementalBackupInfo *ib);
      94                 :             : static bool sendFile(bbsink *sink, const char *readfilename, const char *tarfilename,
      95                 :             :                      struct stat *statbuf, bool missing_ok,
      96                 :             :                      Oid dboid, Oid spcoid, RelFileNumber relfilenumber,
      97                 :             :                      unsigned segno,
      98                 :             :                      backup_manifest_info *manifest,
      99                 :             :                      unsigned num_incremental_blocks,
     100                 :             :                      BlockNumber *incremental_blocks,
     101                 :             :                      unsigned truncation_block_length);
     102                 :             : static off_t read_file_data_into_buffer(bbsink *sink,
     103                 :             :                                         const char *readfilename, int fd,
     104                 :             :                                         off_t offset, size_t length,
     105                 :             :                                         BlockNumber blkno,
     106                 :             :                                         bool verify_checksum,
     107                 :             :                                         int *checksum_failures);
     108                 :             : static void push_to_sink(bbsink *sink, pg_checksum_context *checksum_ctx,
     109                 :             :                          size_t *bytes_done, void *data, size_t length);
     110                 :             : static bool verify_page_checksum(Page page, XLogRecPtr start_lsn,
     111                 :             :                                  BlockNumber blkno,
     112                 :             :                                  uint16 *expected_checksum);
     113                 :             : static void sendFileWithContent(bbsink *sink, const char *filename,
     114                 :             :                                 const char *content, int len,
     115                 :             :                                 backup_manifest_info *manifest);
     116                 :             : static int64 _tarWriteHeader(bbsink *sink, const char *filename,
     117                 :             :                              const char *linktarget, struct stat *statbuf,
     118                 :             :                              bool sizeonly);
     119                 :             : static void _tarWritePadding(bbsink *sink, int len);
     120                 :             : static void convert_link_to_directory(const char *pathbuf, struct stat *statbuf);
     121                 :             : static void perform_base_backup(basebackup_options *opt, bbsink *sink,
     122                 :             :                                 IncrementalBackupInfo *ib);
     123                 :             : static void parse_basebackup_options(List *options, basebackup_options *opt);
     124                 :             : static int  compareWalFileNames(const ListCell *a, const ListCell *b);
     125                 :             : static ssize_t basebackup_read_file(int fd, char *buf, size_t nbytes, off_t offset,
     126                 :             :                                     const char *filename, bool partial_read_ok);
     127                 :             : 
     128                 :             : /* Was the backup currently in-progress initiated in recovery mode? */
     129                 :             : static bool backup_started_in_recovery = false;
     130                 :             : 
     131                 :             : /* Total number of checksum failures during base backup. */
     132                 :             : static long long int total_checksum_failures;
     133                 :             : 
     134                 :             : /* Do not verify checksums. */
     135                 :             : static bool noverify_checksums = false;
     136                 :             : 
     137                 :             : /*
     138                 :             :  * Definition of one element part of an exclusion list, used for paths part
     139                 :             :  * of checksum validation or base backups.  "name" is the name of the file
     140                 :             :  * or path to check for exclusion.  If "match_prefix" is true, any items
     141                 :             :  * matching the name as prefix are excluded.
     142                 :             :  */
     143                 :             : struct exclude_list_item
     144                 :             : {
     145                 :             :     const char *name;
     146                 :             :     bool        match_prefix;
     147                 :             : };
     148                 :             : 
     149                 :             : /*
     150                 :             :  * The contents of these directories are removed or recreated during server
     151                 :             :  * start so they are not included in backups.  The directories themselves are
     152                 :             :  * kept and included as empty to preserve access permissions.
     153                 :             :  *
     154                 :             :  * Note: this list should be kept in sync with the filter lists in pg_rewind's
     155                 :             :  * filemap.c.
     156                 :             :  */
     157                 :             : static const char *const excludeDirContents[] =
     158                 :             : {
     159                 :             :     /*
     160                 :             :      * Skip temporary statistics files. PG_STAT_TMP_DIR must be skipped
     161                 :             :      * because extensions like pg_stat_statements store data there.
     162                 :             :      */
     163                 :             :     PG_STAT_TMP_DIR,
     164                 :             : 
     165                 :             :     /*
     166                 :             :      * It is generally not useful to backup the contents of this directory
     167                 :             :      * even if the intention is to restore to another primary. See backup.sgml
     168                 :             :      * for a more detailed description.
     169                 :             :      */
     170                 :             :     PG_REPLSLOT_DIR,
     171                 :             : 
     172                 :             :     /* Contents removed on startup, see dsm_cleanup_for_mmap(). */
     173                 :             :     PG_DYNSHMEM_DIR,
     174                 :             : 
     175                 :             :     /* Contents removed on startup, see AsyncShmemInit(). */
     176                 :             :     "pg_notify",
     177                 :             : 
     178                 :             :     /*
     179                 :             :      * Old contents are loaded for possible debugging but are not required for
     180                 :             :      * normal operation, see SerialInit().
     181                 :             :      */
     182                 :             :     "pg_serial",
     183                 :             : 
     184                 :             :     /* Contents removed on startup, see DeleteAllExportedSnapshotFiles(). */
     185                 :             :     "pg_snapshots",
     186                 :             : 
     187                 :             :     /* Contents zeroed on startup, see StartupSUBTRANS(). */
     188                 :             :     "pg_subtrans",
     189                 :             : 
     190                 :             :     /* end of list */
     191                 :             :     NULL
     192                 :             : };
     193                 :             : 
     194                 :             : /*
     195                 :             :  * List of files excluded from backups.
     196                 :             :  */
     197                 :             : static const struct exclude_list_item excludeFiles[] =
     198                 :             : {
     199                 :             :     /* Skip auto conf temporary file. */
     200                 :             :     {PG_AUTOCONF_FILENAME ".tmp", false},
     201                 :             : 
     202                 :             :     /* Skip current log file temporary file */
     203                 :             :     {LOG_METAINFO_DATAFILE_TMP, false},
     204                 :             : 
     205                 :             :     /*
     206                 :             :      * Skip relation cache because it is rebuilt on startup.  This includes
     207                 :             :      * temporary files.
     208                 :             :      */
     209                 :             :     {RELCACHE_INIT_FILENAME, true},
     210                 :             : 
     211                 :             :     /*
     212                 :             :      * backup_label and tablespace_map should not exist in a running cluster
     213                 :             :      * capable of doing an online backup, but exclude them just in case.
     214                 :             :      */
     215                 :             :     {BACKUP_LABEL_FILE, false},
     216                 :             :     {TABLESPACE_MAP, false},
     217                 :             : 
     218                 :             :     /*
     219                 :             :      * If there's a backup_manifest, it belongs to a backup that was used to
     220                 :             :      * start this server. It is *not* correct for this backup. Our
     221                 :             :      * backup_manifest is injected into the backup separately if users want
     222                 :             :      * it.
     223                 :             :      */
     224                 :             :     {"backup_manifest", false},
     225                 :             : 
     226                 :             :     {"postmaster.pid", false},
     227                 :             :     {"postmaster.opts", false},
     228                 :             : 
     229                 :             :     /* end of list */
     230                 :             :     {NULL, false}
     231                 :             : };
     232                 :             : 
     233                 :             : /*
     234                 :             :  * Actually do a base backup for the specified tablespaces.
     235                 :             :  *
     236                 :             :  * This is split out mainly to avoid complaints about "variable might be
     237                 :             :  * clobbered by longjmp" from stupider versions of gcc.
     238                 :             :  */
     239                 :             : static void
     240                 :         180 : perform_base_backup(basebackup_options *opt, bbsink *sink,
     241                 :             :                     IncrementalBackupInfo *ib)
     242                 :             : {
     243                 :             :     bbsink_state state;
     244                 :             :     XLogRecPtr  endptr;
     245                 :             :     TimeLineID  endtli;
     246                 :             :     backup_manifest_info manifest;
     247                 :             :     BackupState *backup_state;
     248                 :             :     StringInfoData tablespace_map;
     249                 :             : 
     250                 :             :     /* Initial backup state, insofar as we know it now. */
     251                 :         180 :     state.tablespaces = NIL;
     252                 :         180 :     state.tablespace_num = 0;
     253                 :         180 :     state.bytes_done = 0;
     254                 :         180 :     state.bytes_total = 0;
     255                 :         180 :     state.bytes_total_is_valid = false;
     256                 :             : 
     257                 :             :     /* we're going to use a BufFile, so we need a ResourceOwner */
     258                 :             :     Assert(AuxProcessResourceOwner != NULL);
     259                 :             :     Assert(CurrentResourceOwner == AuxProcessResourceOwner ||
     260                 :             :            CurrentResourceOwner == NULL);
     261                 :         180 :     CurrentResourceOwner = AuxProcessResourceOwner;
     262                 :             : 
     263                 :         180 :     backup_started_in_recovery = RecoveryInProgress();
     264                 :             : 
     265                 :         180 :     InitializeBackupManifest(&manifest, opt->manifest,
     266                 :             :                              opt->manifest_checksum_type);
     267                 :             : 
     268                 :         180 :     total_checksum_failures = 0;
     269                 :             : 
     270                 :             :     /* Allocate backup related variables. */
     271                 :         180 :     backup_state = palloc0_object(BackupState);
     272                 :         180 :     initStringInfo(&tablespace_map);
     273                 :             : 
     274                 :         180 :     basebackup_progress_wait_checkpoint();
     275                 :         180 :     do_pg_backup_start(opt->label, opt->fastcheckpoint, &state.tablespaces,
     276                 :             :                        backup_state, &tablespace_map);
     277                 :             : 
     278                 :         180 :     state.startptr = backup_state->startpoint;
     279                 :         180 :     state.starttli = backup_state->starttli;
     280                 :             : 
     281                 :             :     /*
     282                 :             :      * Once do_pg_backup_start has been called, ensure that any failure causes
     283                 :             :      * us to abort the backup so we don't "leak" a backup counter. For this
     284                 :             :      * reason, *all* functionality between do_pg_backup_start() and the end of
     285                 :             :      * do_pg_backup_stop() should be inside the error cleanup block!
     286                 :             :      */
     287                 :             : 
     288         [ +  + ]:         180 :     PG_ENSURE_ERROR_CLEANUP(do_pg_abort_backup, BoolGetDatum(false));
     289                 :             :     {
     290                 :             :         ListCell   *lc;
     291                 :             :         tablespaceinfo *newti;
     292                 :             : 
     293                 :             :         /* If this is an incremental backup, execute preparatory steps. */
     294         [ +  + ]:         180 :         if (ib != NULL)
     295                 :          12 :             PrepareForIncrementalBackup(ib, backup_state);
     296                 :             : 
     297                 :             :         /* Add a node for the base directory at the end */
     298                 :         179 :         newti = palloc0_object(tablespaceinfo);
     299                 :         179 :         newti->size = -1;
     300                 :         179 :         state.tablespaces = lappend(state.tablespaces, newti);
     301                 :             : 
     302                 :             :         /*
     303                 :             :          * Calculate the total backup size by summing up the size of each
     304                 :             :          * tablespace
     305                 :             :          */
     306         [ +  - ]:         179 :         if (opt->progress)
     307                 :             :         {
     308                 :         179 :             basebackup_progress_estimate_backup_size();
     309                 :             : 
     310   [ +  -  +  +  :         395 :             foreach(lc, state.tablespaces)
                   +  + ]
     311                 :             :             {
     312                 :         216 :                 tablespaceinfo *tmp = (tablespaceinfo *) lfirst(lc);
     313                 :             : 
     314         [ +  + ]:         216 :                 if (tmp->path == NULL)
     315                 :         179 :                     tmp->size = sendDir(sink, ".", 1, true, state.tablespaces,
     316                 :             :                                         true, NULL, InvalidOid, NULL);
     317                 :             :                 else
     318                 :          37 :                     tmp->size = sendTablespace(sink, tmp->path, tmp->oid, true,
     319                 :             :                                                NULL, NULL);
     320                 :         216 :                 state.bytes_total += tmp->size;
     321                 :             :             }
     322                 :         179 :             state.bytes_total_is_valid = true;
     323                 :             :         }
     324                 :             : 
     325                 :             :         /* notify basebackup sink about start of backup */
     326                 :         179 :         bbsink_begin_backup(sink, &state, SINK_BUFFER_LENGTH);
     327                 :             : 
     328                 :             :         /* Send off our tablespaces one by one */
     329   [ +  -  +  +  :         390 :         foreach(lc, state.tablespaces)
                   +  + ]
     330                 :             :         {
     331                 :         216 :             tablespaceinfo *ti = (tablespaceinfo *) lfirst(lc);
     332                 :             : 
     333         [ +  + ]:         216 :             if (ti->path == NULL)
     334                 :             :             {
     335                 :             :                 struct stat statbuf;
     336                 :         179 :                 bool        sendtblspclinks = true;
     337                 :             :                 char       *backup_label;
     338                 :             : 
     339                 :         179 :                 bbsink_begin_archive(sink, "base.tar");
     340                 :             : 
     341                 :             :                 /* In the main tar, include the backup_label first... */
     342                 :         179 :                 backup_label = build_backup_content(backup_state, false);
     343                 :         179 :                 sendFileWithContent(sink, BACKUP_LABEL_FILE,
     344                 :             :                                     backup_label, -1, &manifest);
     345                 :         179 :                 pfree(backup_label);
     346                 :             : 
     347                 :             :                 /* Then the tablespace_map file, if required... */
     348         [ +  + ]:         179 :                 if (opt->sendtblspcmapfile)
     349                 :             :                 {
     350                 :          28 :                     sendFileWithContent(sink, TABLESPACE_MAP,
     351                 :          28 :                                         tablespace_map.data, -1, &manifest);
     352                 :          28 :                     sendtblspclinks = false;
     353                 :             :                 }
     354                 :             : 
     355                 :             :                 /* Then the bulk of the files... */
     356                 :         179 :                 sendDir(sink, ".", 1, false, state.tablespaces,
     357                 :             :                         sendtblspclinks, &manifest, InvalidOid, ib);
     358                 :             : 
     359                 :             :                 /* ... and pg_control after everything else. */
     360         [ -  + ]:         174 :                 if (lstat(XLOG_CONTROL_FILE, &statbuf) != 0)
     361         [ #  # ]:           0 :                     ereport(ERROR,
     362                 :             :                             (errcode_for_file_access(),
     363                 :             :                              errmsg("could not stat file \"%s\": %m",
     364                 :             :                                     XLOG_CONTROL_FILE)));
     365                 :         174 :                 sendFile(sink, XLOG_CONTROL_FILE, XLOG_CONTROL_FILE, &statbuf,
     366                 :             :                          false, InvalidOid, InvalidOid,
     367                 :             :                          InvalidRelFileNumber, 0, &manifest, 0, NULL, 0);
     368                 :             :             }
     369                 :             :             else
     370                 :             :             {
     371                 :          37 :                 char       *archive_name = psprintf("%u.tar", ti->oid);
     372                 :             : 
     373                 :          37 :                 bbsink_begin_archive(sink, archive_name);
     374                 :             : 
     375                 :          37 :                 sendTablespace(sink, ti->path, ti->oid, false, &manifest, ib);
     376                 :             :             }
     377                 :             : 
     378                 :             :             /*
     379                 :             :              * If we're including WAL, and this is the main data directory we
     380                 :             :              * don't treat this as the end of the tablespace. Instead, we will
     381                 :             :              * include the xlog files below and stop afterwards. This is safe
     382                 :             :              * since the main data directory is always sent *last*.
     383                 :             :              */
     384   [ +  +  +  + ]:         211 :             if (opt->includewal && ti->path == NULL)
     385                 :             :             {
     386                 :             :                 Assert(lnext(state.tablespaces, lc) == NULL);
     387                 :             :             }
     388                 :             :             else
     389                 :             :             {
     390                 :             :                 /* Properly terminate the tarfile. */
     391                 :         196 :                 memset(sink->bbs_buffer, 0, TAR_NUM_TERMINATION_BLOCKS * TAR_BLOCK_SIZE);
     392                 :         196 :                 bbsink_archive_contents(sink, TAR_NUM_TERMINATION_BLOCKS * TAR_BLOCK_SIZE);
     393                 :             : 
     394                 :             :                 /* OK, that's the end of the archive. */
     395                 :         196 :                 bbsink_end_archive(sink);
     396                 :             :             }
     397                 :             :         }
     398                 :             : 
     399                 :         174 :         basebackup_progress_wait_wal_archive(&state);
     400                 :         174 :         do_pg_backup_stop(backup_state, !opt->nowait);
     401                 :             : 
     402                 :         174 :         endptr = backup_state->stoppoint;
     403                 :         174 :         endtli = backup_state->stoptli;
     404                 :             : 
     405                 :             :         /* Deallocate backup-related variables. */
     406                 :         174 :         pfree(tablespace_map.data);
     407                 :         174 :         pfree(backup_state);
     408                 :             :     }
     409         [ -  + ]:         176 :     PG_END_ENSURE_ERROR_CLEANUP(do_pg_abort_backup, BoolGetDatum(false));
     410                 :             : 
     411                 :             : 
     412         [ +  + ]:         174 :     if (opt->includewal)
     413                 :             :     {
     414                 :             :         /*
     415                 :             :          * We've left the last tar file "open", so we can now append the
     416                 :             :          * required WAL files to it.
     417                 :             :          */
     418                 :             :         char        pathbuf[MAXPGPATH];
     419                 :             :         XLogSegNo   segno;
     420                 :             :         XLogSegNo   startsegno;
     421                 :             :         XLogSegNo   endsegno;
     422                 :             :         struct stat statbuf;
     423                 :          15 :         List       *historyFileList = NIL;
     424                 :          15 :         List       *walFileList = NIL;
     425                 :             :         char        firstoff[MAXFNAMELEN];
     426                 :             :         char        lastoff[MAXFNAMELEN];
     427                 :             :         DIR        *dir;
     428                 :             :         struct dirent *de;
     429                 :             :         ListCell   *lc;
     430                 :             :         TimeLineID  tli;
     431                 :             : 
     432                 :          15 :         basebackup_progress_transfer_wal();
     433                 :             : 
     434                 :             :         /*
     435                 :             :          * I'd rather not worry about timelines here, so scan pg_wal and
     436                 :             :          * include all WAL files in the range between 'startptr' and 'endptr',
     437                 :             :          * regardless of the timeline the file is stamped with. If there are
     438                 :             :          * some spurious WAL files belonging to timelines that don't belong in
     439                 :             :          * this server's history, they will be included too. Normally there
     440                 :             :          * shouldn't be such files, but if there are, there's little harm in
     441                 :             :          * including them.
     442                 :             :          */
     443                 :          15 :         XLByteToSeg(state.startptr, startsegno, wal_segment_size);
     444                 :          15 :         XLogFileName(firstoff, state.starttli, startsegno, wal_segment_size);
     445                 :          15 :         XLByteToPrevSeg(endptr, endsegno, wal_segment_size);
     446                 :          15 :         XLogFileName(lastoff, endtli, endsegno, wal_segment_size);
     447                 :             : 
     448                 :          15 :         dir = AllocateDir("pg_wal");
     449         [ +  + ]:         108 :         while ((de = ReadDir(dir, "pg_wal")) != NULL)
     450                 :             :         {
     451                 :             :             /* Does it look like a WAL segment, and is it in the range? */
     452         [ +  + ]:          93 :             if (IsXLogFileName(de->d_name) &&
     453         [ +  - ]:          33 :                 strcmp(de->d_name + 8, firstoff + 8) >= 0 &&
     454         [ +  + ]:          33 :                 strcmp(de->d_name + 8, lastoff + 8) <= 0)
     455                 :             :             {
     456                 :          15 :                 walFileList = lappend(walFileList, pstrdup(de->d_name));
     457                 :             :             }
     458                 :             :             /* Does it look like a timeline history file? */
     459         [ -  + ]:          78 :             else if (IsTLHistoryFileName(de->d_name))
     460                 :             :             {
     461                 :           0 :                 historyFileList = lappend(historyFileList, pstrdup(de->d_name));
     462                 :             :             }
     463                 :             :         }
     464                 :          15 :         FreeDir(dir);
     465                 :             : 
     466                 :             :         /*
     467                 :             :          * Before we go any further, check that none of the WAL segments we
     468                 :             :          * need were removed.
     469                 :             :          */
     470                 :          15 :         CheckXLogRemoved(startsegno, state.starttli);
     471                 :             : 
     472                 :             :         /*
     473                 :             :          * Sort the WAL filenames.  We want to send the files in order from
     474                 :             :          * oldest to newest, to reduce the chance that a file is recycled
     475                 :             :          * before we get a chance to send it over.
     476                 :             :          */
     477                 :          15 :         list_sort(walFileList, compareWalFileNames);
     478                 :             : 
     479                 :             :         /*
     480                 :             :          * There must be at least one xlog file in the pg_wal directory, since
     481                 :             :          * we are doing backup-including-xlog.
     482                 :             :          */
     483         [ -  + ]:          15 :         if (walFileList == NIL)
     484         [ #  # ]:           0 :             ereport(ERROR,
     485                 :             :                     (errmsg("could not find any WAL files")));
     486                 :             : 
     487                 :             :         /*
     488                 :             :          * Sanity check: the first and last segment should cover startptr and
     489                 :             :          * endptr, with no gaps in between.
     490                 :             :          */
     491                 :          15 :         XLogFromFileName((char *) linitial(walFileList),
     492                 :             :                          &tli, &segno, wal_segment_size);
     493         [ -  + ]:          15 :         if (segno != startsegno)
     494                 :             :         {
     495                 :             :             char        startfname[MAXFNAMELEN];
     496                 :             : 
     497                 :           0 :             XLogFileName(startfname, state.starttli, startsegno,
     498                 :             :                          wal_segment_size);
     499         [ #  # ]:           0 :             ereport(ERROR,
     500                 :             :                     (errmsg("could not find WAL file \"%s\"", startfname)));
     501                 :             :         }
     502   [ +  -  +  +  :          30 :         foreach(lc, walFileList)
                   +  + ]
     503                 :             :         {
     504                 :          15 :             char       *walFileName = (char *) lfirst(lc);
     505                 :          15 :             XLogSegNo   currsegno = segno;
     506                 :          15 :             XLogSegNo   nextsegno = segno + 1;
     507                 :             : 
     508                 :          15 :             XLogFromFileName(walFileName, &tli, &segno, wal_segment_size);
     509   [ +  -  -  + ]:          15 :             if (!(nextsegno == segno || currsegno == segno))
     510                 :             :             {
     511                 :             :                 char        nextfname[MAXFNAMELEN];
     512                 :             : 
     513                 :           0 :                 XLogFileName(nextfname, tli, nextsegno, wal_segment_size);
     514         [ #  # ]:           0 :                 ereport(ERROR,
     515                 :             :                         (errmsg("could not find WAL file \"%s\"", nextfname)));
     516                 :             :             }
     517                 :             :         }
     518         [ -  + ]:          15 :         if (segno != endsegno)
     519                 :             :         {
     520                 :             :             char        endfname[MAXFNAMELEN];
     521                 :             : 
     522                 :           0 :             XLogFileName(endfname, endtli, endsegno, wal_segment_size);
     523         [ #  # ]:           0 :             ereport(ERROR,
     524                 :             :                     (errmsg("could not find WAL file \"%s\"", endfname)));
     525                 :             :         }
     526                 :             : 
     527                 :             :         /* Ok, we have everything we need. Send the WAL files. */
     528   [ +  -  +  +  :          30 :         foreach(lc, walFileList)
                   +  + ]
     529                 :             :         {
     530                 :          15 :             char       *walFileName = (char *) lfirst(lc);
     531                 :             :             int         fd;
     532                 :             :             ssize_t     cnt;
     533                 :          15 :             pgoff_t     len = 0;
     534                 :             : 
     535                 :          15 :             snprintf(pathbuf, MAXPGPATH, XLOGDIR "/%s", walFileName);
     536                 :          15 :             XLogFromFileName(walFileName, &tli, &segno, wal_segment_size);
     537                 :             : 
     538                 :          15 :             fd = OpenTransientFile(pathbuf, O_RDONLY | PG_BINARY);
     539         [ -  + ]:          15 :             if (fd < 0)
     540                 :             :             {
     541                 :           0 :                 int         save_errno = errno;
     542                 :             : 
     543                 :             :                 /*
     544                 :             :                  * Most likely reason for this is that the file was already
     545                 :             :                  * removed by a checkpoint, so check for that to get a better
     546                 :             :                  * error message.
     547                 :             :                  */
     548                 :           0 :                 CheckXLogRemoved(segno, tli);
     549                 :             : 
     550                 :           0 :                 errno = save_errno;
     551         [ #  # ]:           0 :                 ereport(ERROR,
     552                 :             :                         (errcode_for_file_access(),
     553                 :             :                          errmsg("could not open file \"%s\": %m", pathbuf)));
     554                 :             :             }
     555                 :             : 
     556         [ -  + ]:          15 :             if (fstat(fd, &statbuf) != 0)
     557         [ #  # ]:           0 :                 ereport(ERROR,
     558                 :             :                         (errcode_for_file_access(),
     559                 :             :                          errmsg("could not stat file \"%s\": %m",
     560                 :             :                                 pathbuf)));
     561         [ -  + ]:          15 :             if (statbuf.st_size != wal_segment_size)
     562                 :             :             {
     563                 :           0 :                 CheckXLogRemoved(segno, tli);
     564         [ #  # ]:           0 :                 ereport(ERROR,
     565                 :             :                         (errcode_for_file_access(),
     566                 :             :                          errmsg("unexpected WAL file size \"%s\"", walFileName)));
     567                 :             :             }
     568                 :             : 
     569                 :             :             /* send the WAL file itself */
     570                 :          15 :             _tarWriteHeader(sink, pathbuf, NULL, &statbuf, false);
     571                 :             : 
     572                 :          15 :             while ((cnt = basebackup_read_file(fd, sink->bbs_buffer,
     573                 :        7680 :                                                Min(sink->bbs_buffer_length,
     574                 :             :                                                    wal_segment_size - len),
     575         [ +  - ]:        7680 :                                                len, pathbuf, true)) > 0)
     576                 :             :             {
     577                 :        7680 :                 CheckXLogRemoved(segno, tli);
     578                 :        7680 :                 bbsink_archive_contents(sink, cnt);
     579                 :             : 
     580                 :        7680 :                 len += cnt;
     581                 :             : 
     582         [ +  + ]:        7680 :                 if (len == wal_segment_size)
     583                 :          15 :                     break;
     584                 :             :             }
     585                 :             : 
     586         [ -  + ]:          15 :             if (len != wal_segment_size)
     587                 :             :             {
     588                 :           0 :                 CheckXLogRemoved(segno, tli);
     589         [ #  # ]:           0 :                 ereport(ERROR,
     590                 :             :                         (errcode_for_file_access(),
     591                 :             :                          errmsg("unexpected WAL file size \"%s\"", walFileName)));
     592                 :             :             }
     593                 :             : 
     594                 :             :             /*
     595                 :             :              * wal_segment_size is a multiple of TAR_BLOCK_SIZE, so no need
     596                 :             :              * for padding.
     597                 :             :              */
     598                 :             :             Assert(wal_segment_size % TAR_BLOCK_SIZE == 0);
     599                 :             : 
     600                 :          15 :             CloseTransientFile(fd);
     601                 :             : 
     602                 :             :             /*
     603                 :             :              * Mark file as archived, otherwise files can get archived again
     604                 :             :              * after promotion of a new node. This is in line with
     605                 :             :              * walreceiver.c always doing an XLogArchiveForceDone() after a
     606                 :             :              * complete segment.
     607                 :             :              */
     608                 :          15 :             StatusFilePath(pathbuf, walFileName, ".done");
     609                 :          15 :             sendFileWithContent(sink, pathbuf, "", -1, &manifest);
     610                 :             :         }
     611                 :             : 
     612                 :             :         /*
     613                 :             :          * Send timeline history files too. Only the latest timeline history
     614                 :             :          * file is required for recovery, and even that only if there happens
     615                 :             :          * to be a timeline switch in the first WAL segment that contains the
     616                 :             :          * checkpoint record, or if we're taking a base backup from a standby
     617                 :             :          * server and the target timeline changes while the backup is taken.
     618                 :             :          * But they are small and highly useful for debugging purposes, so
     619                 :             :          * better include them all, always.
     620                 :             :          */
     621   [ -  +  -  -  :          15 :         foreach(lc, historyFileList)
                   -  + ]
     622                 :             :         {
     623                 :           0 :             char       *fname = lfirst(lc);
     624                 :             : 
     625                 :           0 :             snprintf(pathbuf, MAXPGPATH, XLOGDIR "/%s", fname);
     626                 :             : 
     627         [ #  # ]:           0 :             if (lstat(pathbuf, &statbuf) != 0)
     628         [ #  # ]:           0 :                 ereport(ERROR,
     629                 :             :                         (errcode_for_file_access(),
     630                 :             :                          errmsg("could not stat file \"%s\": %m", pathbuf)));
     631                 :             : 
     632                 :           0 :             sendFile(sink, pathbuf, pathbuf, &statbuf, false,
     633                 :             :                      InvalidOid, InvalidOid, InvalidRelFileNumber, 0,
     634                 :             :                      &manifest, 0, NULL, 0);
     635                 :             : 
     636                 :             :             /* unconditionally mark file as archived */
     637                 :           0 :             StatusFilePath(pathbuf, fname, ".done");
     638                 :           0 :             sendFileWithContent(sink, pathbuf, "", -1, &manifest);
     639                 :             :         }
     640                 :             : 
     641                 :             :         /* Properly terminate the tar file. */
     642                 :          15 :         memset(sink->bbs_buffer, 0, TAR_NUM_TERMINATION_BLOCKS * TAR_BLOCK_SIZE);
     643                 :          15 :         bbsink_archive_contents(sink, TAR_NUM_TERMINATION_BLOCKS * TAR_BLOCK_SIZE);
     644                 :             : 
     645                 :             :         /* OK, that's the end of the archive. */
     646                 :          15 :         bbsink_end_archive(sink);
     647                 :             :     }
     648                 :             : 
     649                 :         174 :     AddWALInfoToBackupManifest(&manifest, state.startptr, state.starttli,
     650                 :             :                                endptr, endtli);
     651                 :             : 
     652                 :         174 :     SendBackupManifest(&manifest, sink);
     653                 :             : 
     654                 :         174 :     bbsink_end_backup(sink, endptr, endtli);
     655                 :             : 
     656         [ +  + ]:         174 :     if (total_checksum_failures)
     657                 :             :     {
     658         [ +  + ]:           3 :         if (total_checksum_failures > 1)
     659         [ +  - ]:           2 :             ereport(WARNING,
     660                 :             :                     (errmsg_plural("%lld total checksum verification failure",
     661                 :             :                                    "%lld total checksum verification failures",
     662                 :             :                                    total_checksum_failures,
     663                 :             :                                    total_checksum_failures)));
     664                 :             : 
     665         [ +  - ]:           3 :         ereport(ERROR,
     666                 :             :                 (errcode(ERRCODE_DATA_CORRUPTED),
     667                 :             :                  errmsg("checksum verification failure during base backup")));
     668                 :             :     }
     669                 :             : 
     670                 :             :     /*
     671                 :             :      * Make sure to free the manifest before the resource owners as manifests
     672                 :             :      * use cryptohash contexts that may depend on resource owners (like
     673                 :             :      * OpenSSL).
     674                 :             :      */
     675                 :         171 :     FreeBackupManifest(&manifest);
     676                 :             : 
     677                 :             :     /* clean up the resource owner we created */
     678                 :         171 :     ReleaseAuxProcessResources(true);
     679                 :         171 : }
     680                 :             : 
     681                 :             : /*
     682                 :             :  * list_sort comparison function, to compare log/seg portion of WAL segment
     683                 :             :  * filenames, ignoring the timeline portion.
     684                 :             :  */
     685                 :             : static int
     686                 :           0 : compareWalFileNames(const ListCell *a, const ListCell *b)
     687                 :             : {
     688                 :           0 :     char       *fna = (char *) lfirst(a);
     689                 :           0 :     char       *fnb = (char *) lfirst(b);
     690                 :             : 
     691                 :           0 :     return strcmp(fna + 8, fnb + 8);
     692                 :             : }
     693                 :             : 
     694                 :             : /*
     695                 :             :  * Parse the base backup options passed down by the parser
     696                 :             :  */
     697                 :             : static void
     698                 :         197 : parse_basebackup_options(List *options, basebackup_options *opt)
     699                 :             : {
     700                 :             :     ListCell   *lopt;
     701                 :         197 :     bool        o_label = false;
     702                 :         197 :     bool        o_progress = false;
     703                 :         197 :     bool        o_checkpoint = false;
     704                 :         197 :     bool        o_nowait = false;
     705                 :         197 :     bool        o_wal = false;
     706                 :         197 :     bool        o_incremental = false;
     707                 :         197 :     bool        o_maxrate = false;
     708                 :         197 :     bool        o_tablespace_map = false;
     709                 :         197 :     bool        o_noverify_checksums = false;
     710                 :         197 :     bool        o_manifest = false;
     711                 :         197 :     bool        o_manifest_checksums = false;
     712                 :         197 :     bool        o_target = false;
     713                 :         197 :     bool        o_target_detail = false;
     714                 :         197 :     char       *target_str = NULL;
     715                 :         197 :     char       *target_detail_str = NULL;
     716                 :         197 :     bool        o_compression = false;
     717                 :         197 :     bool        o_compression_detail = false;
     718                 :         197 :     char       *compression_detail_str = NULL;
     719                 :             : 
     720   [ +  -  +  -  :        2167 :     MemSet(opt, 0, sizeof(*opt));
          +  -  +  -  +  
                      + ]
     721                 :         197 :     opt->manifest = MANIFEST_OPTION_NO;
     722                 :         197 :     opt->manifest_checksum_type = CHECKSUM_TYPE_CRC32C;
     723                 :         197 :     opt->compression = PG_COMPRESSION_NONE;
     724                 :         197 :     opt->compression_specification.algorithm = PG_COMPRESSION_NONE;
     725                 :             : 
     726   [ +  -  +  +  :        1481 :     foreach(lopt, options)
                   +  + ]
     727                 :             :     {
     728                 :        1287 :         DefElem    *defel = (DefElem *) lfirst(lopt);
     729                 :             : 
     730         [ +  + ]:        1287 :         if (strcmp(defel->defname, "label") == 0)
     731                 :             :         {
     732         [ -  + ]:         197 :             if (o_label)
     733         [ #  # ]:           0 :                 ereport(ERROR,
     734                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     735                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     736                 :         197 :             opt->label = defGetString(defel);
     737                 :         197 :             o_label = true;
     738                 :             :         }
     739         [ +  + ]:        1090 :         else if (strcmp(defel->defname, "progress") == 0)
     740                 :             :         {
     741         [ -  + ]:         197 :             if (o_progress)
     742         [ #  # ]:           0 :                 ereport(ERROR,
     743                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     744                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     745                 :         197 :             opt->progress = defGetBoolean(defel);
     746                 :         197 :             o_progress = true;
     747                 :             :         }
     748         [ +  + ]:         893 :         else if (strcmp(defel->defname, "checkpoint") == 0)
     749                 :             :         {
     750                 :         187 :             char       *optval = defGetString(defel);
     751                 :             : 
     752         [ -  + ]:         187 :             if (o_checkpoint)
     753         [ #  # ]:           0 :                 ereport(ERROR,
     754                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     755                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     756         [ +  - ]:         187 :             if (pg_strcasecmp(optval, "fast") == 0)
     757                 :         187 :                 opt->fastcheckpoint = true;
     758         [ #  # ]:           0 :             else if (pg_strcasecmp(optval, "spread") == 0)
     759                 :           0 :                 opt->fastcheckpoint = false;
     760                 :             :             else
     761         [ #  # ]:           0 :                 ereport(ERROR,
     762                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     763                 :             :                          errmsg("unrecognized checkpoint type: \"%s\"",
     764                 :             :                                 optval)));
     765                 :         187 :             o_checkpoint = true;
     766                 :             :         }
     767         [ +  + ]:         706 :         else if (strcmp(defel->defname, "wait") == 0)
     768                 :             :         {
     769         [ -  + ]:         188 :             if (o_nowait)
     770         [ #  # ]:           0 :                 ereport(ERROR,
     771                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     772                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     773                 :         188 :             opt->nowait = !defGetBoolean(defel);
     774                 :         188 :             o_nowait = true;
     775                 :             :         }
     776         [ +  + ]:         518 :         else if (strcmp(defel->defname, "wal") == 0)
     777                 :             :         {
     778         [ -  + ]:          19 :             if (o_wal)
     779         [ #  # ]:           0 :                 ereport(ERROR,
     780                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     781                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     782                 :          19 :             opt->includewal = defGetBoolean(defel);
     783                 :          19 :             o_wal = true;
     784                 :             :         }
     785         [ +  + ]:         499 :         else if (strcmp(defel->defname, "incremental") == 0)
     786                 :             :         {
     787         [ -  + ]:          12 :             if (o_incremental)
     788         [ #  # ]:           0 :                 ereport(ERROR,
     789                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     790                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     791                 :          12 :             opt->incremental = defGetBoolean(defel);
     792   [ +  -  -  + ]:          12 :             if (opt->incremental && !summarize_wal)
     793         [ #  # ]:           0 :                 ereport(ERROR,
     794                 :             :                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     795                 :             :                          errmsg("incremental backups cannot be taken unless WAL summarization is enabled")));
     796                 :          12 :             o_incremental = true;
     797                 :             :         }
     798         [ +  + ]:         487 :         else if (strcmp(defel->defname, "max_rate") == 0)
     799                 :             :         {
     800                 :             :             int64       maxrate;
     801                 :             : 
     802         [ -  + ]:           1 :             if (o_maxrate)
     803         [ #  # ]:           0 :                 ereport(ERROR,
     804                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     805                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     806                 :             : 
     807                 :           1 :             maxrate = defGetInt64(defel);
     808   [ +  -  -  + ]:           1 :             if (maxrate < MAX_RATE_LOWER || maxrate > MAX_RATE_UPPER)
     809         [ #  # ]:           0 :                 ereport(ERROR,
     810                 :             :                         (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
     811                 :             :                          errmsg("%" PRId64 " is outside the valid range for parameter \"%s\" (%d .. %d)",
     812                 :             :                                 maxrate, "MAX_RATE", MAX_RATE_LOWER, MAX_RATE_UPPER)));
     813                 :             : 
     814                 :           1 :             opt->maxrate = (uint32) maxrate;
     815                 :           1 :             o_maxrate = true;
     816                 :             :         }
     817         [ +  + ]:         486 :         else if (strcmp(defel->defname, "tablespace_map") == 0)
     818                 :             :         {
     819         [ -  + ]:          34 :             if (o_tablespace_map)
     820         [ #  # ]:           0 :                 ereport(ERROR,
     821                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     822                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     823                 :          34 :             opt->sendtblspcmapfile = defGetBoolean(defel);
     824                 :          34 :             o_tablespace_map = true;
     825                 :             :         }
     826         [ +  + ]:         452 :         else if (strcmp(defel->defname, "verify_checksums") == 0)
     827                 :             :         {
     828         [ -  + ]:           1 :             if (o_noverify_checksums)
     829         [ #  # ]:           0 :                 ereport(ERROR,
     830                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     831                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     832                 :           1 :             noverify_checksums = !defGetBoolean(defel);
     833                 :           1 :             o_noverify_checksums = true;
     834                 :             :         }
     835         [ +  + ]:         451 :         else if (strcmp(defel->defname, "manifest") == 0)
     836                 :             :         {
     837                 :         196 :             char       *optval = defGetString(defel);
     838                 :             :             bool        manifest_bool;
     839                 :             : 
     840         [ -  + ]:         196 :             if (o_manifest)
     841         [ #  # ]:           0 :                 ereport(ERROR,
     842                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     843                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     844         [ +  + ]:         196 :             if (parse_bool(optval, &manifest_bool))
     845                 :             :             {
     846         [ +  - ]:         195 :                 if (manifest_bool)
     847                 :         195 :                     opt->manifest = MANIFEST_OPTION_YES;
     848                 :             :                 else
     849                 :           0 :                     opt->manifest = MANIFEST_OPTION_NO;
     850                 :             :             }
     851         [ +  - ]:           1 :             else if (pg_strcasecmp(optval, "force-encode") == 0)
     852                 :           1 :                 opt->manifest = MANIFEST_OPTION_FORCE_ENCODE;
     853                 :             :             else
     854         [ #  # ]:           0 :                 ereport(ERROR,
     855                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     856                 :             :                          errmsg("unrecognized manifest option: \"%s\"",
     857                 :             :                                 optval)));
     858                 :         196 :             o_manifest = true;
     859                 :             :         }
     860         [ +  + ]:         255 :         else if (strcmp(defel->defname, "manifest_checksums") == 0)
     861                 :             :         {
     862                 :          14 :             char       *optval = defGetString(defel);
     863                 :             : 
     864         [ -  + ]:          14 :             if (o_manifest_checksums)
     865         [ #  # ]:           0 :                 ereport(ERROR,
     866                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     867                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     868         [ +  + ]:          14 :             if (!pg_checksum_parse_type(optval,
     869                 :             :                                         &opt->manifest_checksum_type))
     870         [ +  - ]:           2 :                 ereport(ERROR,
     871                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     872                 :             :                          errmsg("unrecognized checksum algorithm: \"%s\"",
     873                 :             :                                 optval)));
     874                 :          12 :             o_manifest_checksums = true;
     875                 :             :         }
     876         [ +  + ]:         241 :         else if (strcmp(defel->defname, "target") == 0)
     877                 :             :         {
     878         [ -  + ]:         195 :             if (o_target)
     879         [ #  # ]:           0 :                 ereport(ERROR,
     880                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     881                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     882                 :         195 :             target_str = defGetString(defel);
     883                 :         195 :             o_target = true;
     884                 :             :         }
     885         [ +  + ]:          46 :         else if (strcmp(defel->defname, "target_detail") == 0)
     886                 :             :         {
     887                 :           8 :             char       *optval = defGetString(defel);
     888                 :             : 
     889         [ -  + ]:           8 :             if (o_target_detail)
     890         [ #  # ]:           0 :                 ereport(ERROR,
     891                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     892                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     893                 :           8 :             target_detail_str = optval;
     894                 :           8 :             o_target_detail = true;
     895                 :             :         }
     896         [ +  + ]:          38 :         else if (strcmp(defel->defname, "compression") == 0)
     897                 :             :         {
     898                 :          26 :             char       *optval = defGetString(defel);
     899                 :             : 
     900         [ -  + ]:          26 :             if (o_compression)
     901         [ #  # ]:           0 :                 ereport(ERROR,
     902                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     903                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     904         [ +  + ]:          26 :             if (!parse_compress_algorithm(optval, &opt->compression))
     905         [ +  - ]:           1 :                 ereport(ERROR,
     906                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     907                 :             :                          errmsg("unrecognized compression algorithm: \"%s\"",
     908                 :             :                                 optval)));
     909                 :          25 :             o_compression = true;
     910                 :             :         }
     911         [ +  - ]:          12 :         else if (strcmp(defel->defname, "compression_detail") == 0)
     912                 :             :         {
     913         [ -  + ]:          12 :             if (o_compression_detail)
     914         [ #  # ]:           0 :                 ereport(ERROR,
     915                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     916                 :             :                          errmsg("duplicate option \"%s\"", defel->defname)));
     917                 :          12 :             compression_detail_str = defGetString(defel);
     918                 :          12 :             o_compression_detail = true;
     919                 :             :         }
     920                 :             :         else
     921         [ #  # ]:           0 :             ereport(ERROR,
     922                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     923                 :             :                      errmsg("unrecognized base backup option: \"%s\"",
     924                 :             :                             defel->defname)));
     925                 :             :     }
     926                 :             : 
     927         [ -  + ]:         194 :     if (opt->label == NULL)
     928                 :           0 :         opt->label = "base backup";
     929         [ +  + ]:         194 :     if (opt->manifest == MANIFEST_OPTION_NO)
     930                 :             :     {
     931         [ -  + ]:           1 :         if (o_manifest_checksums)
     932         [ #  # ]:           0 :             ereport(ERROR,
     933                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     934                 :             :                      errmsg("manifest checksums require a backup manifest")));
     935                 :           1 :         opt->manifest_checksum_type = CHECKSUM_TYPE_NONE;
     936                 :             :     }
     937                 :             : 
     938         [ -  + ]:         194 :     if (target_str == NULL)
     939                 :             :     {
     940         [ #  # ]:           0 :         if (target_detail_str != NULL)
     941         [ #  # ]:           0 :             ereport(ERROR,
     942                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     943                 :             :                      errmsg("target detail cannot be used without target")));
     944                 :           0 :         opt->use_copytblspc = true;
     945                 :           0 :         opt->send_to_client = true;
     946                 :             :     }
     947         [ +  + ]:         194 :     else if (strcmp(target_str, "client") == 0)
     948                 :             :     {
     949         [ -  + ]:         180 :         if (target_detail_str != NULL)
     950         [ #  # ]:           0 :             ereport(ERROR,
     951                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     952                 :             :                      errmsg("target \"%s\" does not accept a target detail",
     953                 :             :                             target_str)));
     954                 :         180 :         opt->send_to_client = true;
     955                 :             :     }
     956                 :             :     else
     957                 :          12 :         opt->target_handle =
     958                 :          14 :             BaseBackupGetTargetHandle(target_str, target_detail_str);
     959                 :             : 
     960   [ +  +  -  + ]:         192 :     if (o_compression_detail && !o_compression)
     961         [ #  # ]:           0 :         ereport(ERROR,
     962                 :             :                 (errcode(ERRCODE_SYNTAX_ERROR),
     963                 :             :                  errmsg("compression detail cannot be specified unless compression is enabled")));
     964                 :             : 
     965         [ +  + ]:         192 :     if (o_compression)
     966                 :             :     {
     967                 :             :         char       *error_detail;
     968                 :             : 
     969                 :          23 :         parse_compress_specification(opt->compression, compression_detail_str,
     970                 :             :                                      &opt->compression_specification);
     971                 :             :         error_detail =
     972                 :          23 :             validate_compress_specification(&opt->compression_specification);
     973         [ +  + ]:          23 :         if (error_detail != NULL)
     974         [ +  - ]:           9 :             ereport(ERROR,
     975                 :             :                     errcode(ERRCODE_SYNTAX_ERROR),
     976                 :             :                     errmsg("invalid compression specification: %s",
     977                 :             :                            error_detail));
     978                 :             :     }
     979                 :         183 : }
     980                 :             : 
     981                 :             : 
     982                 :             : /*
     983                 :             :  * SendBaseBackup() - send a complete base backup.
     984                 :             :  *
     985                 :             :  * The function will put the system into backup mode like pg_backup_start()
     986                 :             :  * does, so that the backup is consistent even though we read directly from
     987                 :             :  * the filesystem, bypassing the buffer cache.
     988                 :             :  */
     989                 :             : void
     990                 :         198 : SendBaseBackup(BaseBackupCmd *cmd, IncrementalBackupInfo *ib)
     991                 :             : {
     992                 :             :     basebackup_options opt;
     993                 :             :     bbsink     *sink;
     994                 :         198 :     SessionBackupState status = get_backup_status();
     995                 :             : 
     996         [ +  + ]:         198 :     if (status == SESSION_BACKUP_RUNNING)
     997         [ +  - ]:           1 :         ereport(ERROR,
     998                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     999                 :             :                  errmsg("a backup is already in progress in this session")));
    1000                 :             : 
    1001                 :         197 :     parse_basebackup_options(cmd->options, &opt);
    1002                 :             : 
    1003                 :         183 :     WalSndSetState(WALSNDSTATE_BACKUP);
    1004                 :             : 
    1005         [ +  - ]:         183 :     if (update_process_title)
    1006                 :             :     {
    1007                 :             :         char        activitymsg[50];
    1008                 :             : 
    1009                 :         183 :         snprintf(activitymsg, sizeof(activitymsg), "sending backup \"%s\"",
    1010                 :             :                  opt.label);
    1011                 :         183 :         set_ps_display(activitymsg);
    1012                 :             :     }
    1013                 :             : 
    1014                 :             :     /*
    1015                 :             :      * If we're asked to perform an incremental backup and the user has not
    1016                 :             :      * supplied a manifest, that's an ERROR.
    1017                 :             :      *
    1018                 :             :      * If we're asked to perform a full backup and the user did supply a
    1019                 :             :      * manifest, just ignore it.
    1020                 :             :      */
    1021         [ +  + ]:         183 :     if (!opt.incremental)
    1022                 :         171 :         ib = NULL;
    1023         [ -  + ]:          12 :     else if (ib == NULL)
    1024         [ #  # ]:           0 :         ereport(ERROR,
    1025                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1026                 :             :                  errmsg("must UPLOAD_MANIFEST before performing an incremental BASE_BACKUP")));
    1027                 :             : 
    1028                 :             :     /*
    1029                 :             :      * If the target is specifically 'client' then set up to stream the backup
    1030                 :             :      * to the client; otherwise, it's being sent someplace else and should not
    1031                 :             :      * be sent to the client. BaseBackupGetSink has the job of setting up a
    1032                 :             :      * sink to send the backup data wherever it needs to go.
    1033                 :             :      */
    1034                 :         183 :     sink = bbsink_copystream_new(opt.send_to_client);
    1035         [ +  + ]:         183 :     if (opt.target_handle != NULL)
    1036                 :          12 :         sink = BaseBackupGetSink(opt.target_handle, sink);
    1037                 :             : 
    1038                 :             :     /* Set up network throttling, if client requested it */
    1039         [ +  + ]:         180 :     if (opt.maxrate > 0)
    1040                 :           1 :         sink = bbsink_throttle_new(sink, opt.maxrate);
    1041                 :             : 
    1042                 :             :     /* Set up server-side compression, if client requested it */
    1043         [ +  + ]:         180 :     if (opt.compression == PG_COMPRESSION_GZIP)
    1044                 :           2 :         sink = bbsink_gzip_new(sink, &opt.compression_specification);
    1045         [ +  + ]:         178 :     else if (opt.compression == PG_COMPRESSION_LZ4)
    1046                 :           3 :         sink = bbsink_lz4_new(sink, &opt.compression_specification);
    1047         [ -  + ]:         175 :     else if (opt.compression == PG_COMPRESSION_ZSTD)
    1048                 :           0 :         sink = bbsink_zstd_new(sink, &opt.compression_specification);
    1049                 :             : 
    1050                 :             :     /* Set up progress reporting. */
    1051                 :         180 :     sink = bbsink_progress_new(sink, opt.progress, opt.incremental);
    1052                 :             : 
    1053                 :             :     /*
    1054                 :             :      * Perform the base backup, but make sure we clean up the bbsink even if
    1055                 :             :      * an error occurs.
    1056                 :             :      */
    1057         [ +  + ]:         180 :     PG_TRY();
    1058                 :             :     {
    1059                 :         180 :         perform_base_backup(&opt, sink, ib);
    1060                 :             :     }
    1061                 :           5 :     PG_FINALLY();
    1062                 :             :     {
    1063                 :         176 :         bbsink_cleanup(sink);
    1064                 :             :     }
    1065         [ +  + ]:         176 :     PG_END_TRY();
    1066                 :         171 : }
    1067                 :             : 
    1068                 :             : /*
    1069                 :             :  * Inject a file with given name and content in the output tar stream.
    1070                 :             :  *
    1071                 :             :  * "len" can optionally be set to an arbitrary length of data sent.  If set
    1072                 :             :  * to -1, the content sent is treated as a string with strlen() as length.
    1073                 :             :  */
    1074                 :             : static void
    1075                 :         222 : sendFileWithContent(bbsink *sink, const char *filename, const char *content,
    1076                 :             :                     int len, backup_manifest_info *manifest)
    1077                 :             : {
    1078                 :             :     struct stat statbuf;
    1079                 :         222 :     int         bytes_done = 0;
    1080                 :             :     pg_checksum_context checksum_ctx;
    1081                 :             : 
    1082         [ -  + ]:         222 :     if (pg_checksum_init(&checksum_ctx, manifest->checksum_type) < 0)
    1083         [ #  # ]:           0 :         elog(ERROR, "could not initialize checksum of file \"%s\"",
    1084                 :             :              filename);
    1085                 :             : 
    1086         [ +  - ]:         222 :     if (len < 0)
    1087                 :         222 :         len = strlen(content);
    1088                 :             : 
    1089                 :             :     /*
    1090                 :             :      * Construct a stat struct for the file we're injecting in the tar.
    1091                 :             :      */
    1092                 :             : 
    1093                 :             :     /* Windows doesn't have the concept of uid and gid */
    1094                 :             : #ifdef WIN32
    1095                 :             :     statbuf.st_uid = 0;
    1096                 :             :     statbuf.st_gid = 0;
    1097                 :             : #else
    1098                 :         222 :     statbuf.st_uid = geteuid();
    1099                 :         222 :     statbuf.st_gid = getegid();
    1100                 :             : #endif
    1101                 :         222 :     statbuf.st_mtime = time(NULL);
    1102                 :         222 :     statbuf.st_mode = pg_file_create_mode;
    1103                 :         222 :     statbuf.st_size = len;
    1104                 :             : 
    1105                 :         222 :     _tarWriteHeader(sink, filename, NULL, &statbuf, false);
    1106                 :             : 
    1107         [ -  + ]:         222 :     if (pg_checksum_update(&checksum_ctx, (const uint8 *) content, len) < 0)
    1108         [ #  # ]:           0 :         elog(ERROR, "could not update checksum of file \"%s\"",
    1109                 :             :              filename);
    1110                 :             : 
    1111         [ +  + ]:         407 :     while (bytes_done < len)
    1112                 :             :     {
    1113                 :         185 :         size_t      remaining = len - bytes_done;
    1114                 :         185 :         size_t      nbytes = Min(sink->bbs_buffer_length, remaining);
    1115                 :             : 
    1116                 :         185 :         memcpy(sink->bbs_buffer, content, nbytes);
    1117                 :         185 :         bbsink_archive_contents(sink, nbytes);
    1118                 :         185 :         bytes_done += nbytes;
    1119                 :         185 :         content += nbytes;
    1120                 :             :     }
    1121                 :             : 
    1122                 :         222 :     _tarWritePadding(sink, len);
    1123                 :             : 
    1124                 :         222 :     AddFileToBackupManifest(manifest, InvalidOid, filename, len,
    1125                 :         222 :                             (pg_time_t) statbuf.st_mtime, &checksum_ctx);
    1126                 :         222 : }
    1127                 :             : 
    1128                 :             : /*
    1129                 :             :  * Include the tablespace directory pointed to by 'path' in the output tar
    1130                 :             :  * stream.  If 'sizeonly' is true, we just calculate a total length and return
    1131                 :             :  * it, without actually sending anything.
    1132                 :             :  *
    1133                 :             :  * Only used to send auxiliary tablespaces, not PGDATA.
    1134                 :             :  */
    1135                 :             : static int64
    1136                 :          74 : sendTablespace(bbsink *sink, char *path, Oid spcoid, bool sizeonly,
    1137                 :             :                backup_manifest_info *manifest, IncrementalBackupInfo *ib)
    1138                 :             : {
    1139                 :             :     int64       size;
    1140                 :             :     char        pathbuf[MAXPGPATH];
    1141                 :             :     struct stat statbuf;
    1142                 :             : 
    1143                 :             :     /*
    1144                 :             :      * 'path' points to the tablespace location, but we only want to include
    1145                 :             :      * the version directory in it that belongs to us.
    1146                 :             :      */
    1147                 :          74 :     snprintf(pathbuf, sizeof(pathbuf), "%s/%s", path,
    1148                 :             :              TABLESPACE_VERSION_DIRECTORY);
    1149                 :             : 
    1150                 :             :     /*
    1151                 :             :      * Store a directory entry in the tar file so we get the permissions
    1152                 :             :      * right.
    1153                 :             :      */
    1154         [ -  + ]:          74 :     if (lstat(pathbuf, &statbuf) != 0)
    1155                 :             :     {
    1156         [ #  # ]:           0 :         if (errno != ENOENT)
    1157         [ #  # ]:           0 :             ereport(ERROR,
    1158                 :             :                     (errcode_for_file_access(),
    1159                 :             :                      errmsg("could not stat file or directory \"%s\": %m",
    1160                 :             :                             pathbuf)));
    1161                 :             : 
    1162                 :             :         /* If the tablespace went away while scanning, it's no error. */
    1163                 :           0 :         return 0;
    1164                 :             :     }
    1165                 :             : 
    1166                 :          74 :     size = _tarWriteHeader(sink, TABLESPACE_VERSION_DIRECTORY, NULL, &statbuf,
    1167                 :             :                            sizeonly);
    1168                 :             : 
    1169                 :             :     /* Send all the files in the tablespace version directory */
    1170                 :          74 :     size += sendDir(sink, pathbuf, strlen(path), sizeonly, NIL, true, manifest,
    1171                 :             :                     spcoid, ib);
    1172                 :             : 
    1173                 :          74 :     return size;
    1174                 :             : }
    1175                 :             : 
    1176                 :             : /*
    1177                 :             :  * Include all files from the given directory in the output tar stream. If
    1178                 :             :  * 'sizeonly' is true, we just calculate a total length and return it, without
    1179                 :             :  * actually sending anything.
    1180                 :             :  *
    1181                 :             :  * Omit any directory in the tablespaces list, to avoid backing up
    1182                 :             :  * tablespaces twice when they were created inside PGDATA.
    1183                 :             :  *
    1184                 :             :  * If sendtblspclinks is true, we need to include symlink
    1185                 :             :  * information in the tar file. If not, we can skip that
    1186                 :             :  * as it will be sent separately in the tablespace_map file.
    1187                 :             :  */
    1188                 :             : static int64
    1189                 :        6194 : sendDir(bbsink *sink, const char *path, int basepathlen, bool sizeonly,
    1190                 :             :         List *tablespaces, bool sendtblspclinks, backup_manifest_info *manifest,
    1191                 :             :         Oid spcoid, IncrementalBackupInfo *ib)
    1192                 :             : {
    1193                 :             :     DIR        *dir;
    1194                 :             :     struct dirent *de;
    1195                 :             :     char        pathbuf[MAXPGPATH * 2];
    1196                 :             :     struct stat statbuf;
    1197                 :        6194 :     int64       size = 0;
    1198                 :             :     const char *lastDir;        /* Split last dir from parent path. */
    1199                 :        6194 :     bool        isRelationDir = false;  /* Does directory contain relations? */
    1200                 :        6194 :     bool        isGlobalDir = false;
    1201                 :        6194 :     Oid         dboid = InvalidOid;
    1202                 :        6194 :     BlockNumber *relative_block_numbers = NULL;
    1203                 :             : 
    1204                 :             :     /*
    1205                 :             :      * Since this array is relatively large, avoid putting it on the stack.
    1206                 :             :      * But we don't need it at all if this is not an incremental backup.
    1207                 :             :      */
    1208         [ +  + ]:        6194 :     if (ib != NULL)
    1209                 :         191 :         relative_block_numbers = palloc_array(BlockNumber, RELSEG_SIZE);
    1210                 :             : 
    1211                 :             :     /*
    1212                 :             :      * Determine if the current path is a database directory that can contain
    1213                 :             :      * relations.
    1214                 :             :      *
    1215                 :             :      * Start by finding the location of the delimiter between the parent path
    1216                 :             :      * and the current path.
    1217                 :             :      */
    1218                 :        6194 :     lastDir = last_dir_separator(path);
    1219                 :             : 
    1220                 :             :     /* Does this path look like a database path (i.e. all digits)? */
    1221         [ +  + ]:        6194 :     if (lastDir != NULL &&
    1222         [ +  + ]:        5836 :         strspn(lastDir + 1, "0123456789") == strlen(lastDir + 1))
    1223                 :        1146 :     {
    1224                 :             :         /* Part of path that contains the parent directory. */
    1225                 :        1146 :         int         parentPathLen = lastDir - path;
    1226                 :             : 
    1227                 :             :         /*
    1228                 :             :          * Mark path as a database directory if the parent path is either
    1229                 :             :          * $PGDATA/base or a tablespace version path.
    1230                 :             :          */
    1231         [ +  + ]:        1146 :         if (strncmp(path, "./base", parentPathLen) == 0 ||
    1232         [ +  - ]:          52 :             (parentPathLen >= (sizeof(TABLESPACE_VERSION_DIRECTORY) - 1) &&
    1233         [ +  - ]:          52 :              strncmp(lastDir - (sizeof(TABLESPACE_VERSION_DIRECTORY) - 1),
    1234                 :             :                      TABLESPACE_VERSION_DIRECTORY,
    1235                 :             :                      sizeof(TABLESPACE_VERSION_DIRECTORY) - 1) == 0))
    1236                 :             :         {
    1237                 :        1146 :             isRelationDir = true;
    1238                 :        1146 :             dboid = atooid(lastDir + 1);
    1239                 :             :         }
    1240                 :             :     }
    1241         [ +  + ]:        5048 :     else if (strcmp(path, "./global") == 0)
    1242                 :             :     {
    1243                 :         356 :         isRelationDir = true;
    1244                 :         356 :         isGlobalDir = true;
    1245                 :             :     }
    1246                 :             : 
    1247                 :        6194 :     dir = AllocateDir(path);
    1248         [ +  + ]:      404482 :     while ((de = ReadDir(dir, path)) != NULL)
    1249                 :             :     {
    1250                 :             :         int         excludeIdx;
    1251                 :             :         bool        excludeFound;
    1252                 :      398297 :         RelFileNumber relfilenumber = InvalidRelFileNumber;
    1253                 :      398297 :         ForkNumber  relForkNum = InvalidForkNumber;
    1254                 :      398297 :         unsigned    segno = 0;
    1255                 :      398297 :         bool        isRelationFile = false;
    1256                 :             : 
    1257                 :             :         /* Skip special stuff */
    1258   [ +  +  +  + ]:      398297 :         if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
    1259                 :       17507 :             continue;
    1260                 :             : 
    1261                 :             :         /* Skip temporary files */
    1262         [ +  + ]:      385923 :         if (strncmp(de->d_name,
    1263                 :             :                     PG_TEMP_FILE_PREFIX,
    1264                 :             :                     strlen(PG_TEMP_FILE_PREFIX)) == 0)
    1265                 :         353 :             continue;
    1266                 :             : 
    1267                 :             :         /* Skip macOS system files */
    1268         [ +  + ]:      385570 :         if (strcmp(de->d_name, ".DS_Store") == 0)
    1269                 :          69 :             continue;
    1270                 :             : 
    1271                 :             :         /*
    1272                 :             :          * Check if the postmaster has signaled us to exit, and abort with an
    1273                 :             :          * error in that case. The error handler further up will call
    1274                 :             :          * do_pg_abort_backup() for us. Also check that if the backup was
    1275                 :             :          * started while still in recovery, the server wasn't promoted.
    1276                 :             :          * do_pg_backup_stop() will check that too, but it's better to stop
    1277                 :             :          * the backup early than continue to the end and fail there.
    1278                 :             :          */
    1279         [ +  + ]:      385501 :         CHECK_FOR_INTERRUPTS();
    1280         [ -  + ]:      385497 :         if (RecoveryInProgress() != backup_started_in_recovery)
    1281         [ #  # ]:           0 :             ereport(ERROR,
    1282                 :             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1283                 :             :                      errmsg("the standby was promoted during online backup"),
    1284                 :             :                      errhint("This means that the backup being taken is corrupt "
    1285                 :             :                              "and should not be used. "
    1286                 :             :                              "Try taking another online backup.")));
    1287                 :             : 
    1288                 :             :         /* Scan for files that should be excluded */
    1289                 :      385497 :         excludeFound = false;
    1290         [ +  + ]:     3464149 :         for (excludeIdx = 0; excludeFiles[excludeIdx].name != NULL; excludeIdx++)
    1291                 :             :         {
    1292                 :     3080052 :             int         cmplen = strlen(excludeFiles[excludeIdx].name);
    1293                 :             : 
    1294         [ +  + ]:     3080052 :             if (!excludeFiles[excludeIdx].match_prefix)
    1295                 :     2694687 :                 cmplen++;
    1296         [ +  + ]:     3080052 :             if (strncmp(de->d_name, excludeFiles[excludeIdx].name, cmplen) == 0)
    1297                 :             :             {
    1298         [ +  + ]:        1400 :                 elog(DEBUG1, "file \"%s\" excluded from backup", de->d_name);
    1299                 :        1400 :                 excludeFound = true;
    1300                 :        1400 :                 break;
    1301                 :             :             }
    1302                 :             :         }
    1303                 :             : 
    1304         [ +  + ]:      385497 :         if (excludeFound)
    1305                 :        1400 :             continue;
    1306                 :             : 
    1307                 :             :         /*
    1308                 :             :          * If there could be non-temporary relation files in this directory,
    1309                 :             :          * try to parse the filename.
    1310                 :             :          */
    1311         [ +  + ]:      384097 :         if (isRelationDir)
    1312                 :             :             isRelationFile =
    1313                 :      371672 :                 parse_filename_for_nontemp_relation(de->d_name,
    1314                 :             :                                                     &relfilenumber,
    1315                 :             :                                                     &relForkNum, &segno);
    1316                 :             : 
    1317                 :             :         /* Exclude all forks for unlogged tables except the init fork */
    1318   [ +  +  +  + ]:      384097 :         if (isRelationFile && relForkNum != INIT_FORKNUM)
    1319                 :             :         {
    1320                 :             :             char        initForkFile[MAXPGPATH];
    1321                 :             : 
    1322                 :             :             /*
    1323                 :             :              * If any other type of fork, check if there is an init fork with
    1324                 :             :              * the same RelFileNumber. If so, the file can be excluded.
    1325                 :             :              */
    1326                 :      368659 :             snprintf(initForkFile, sizeof(initForkFile), "%s/%u_init",
    1327                 :             :                      path, relfilenumber);
    1328                 :             : 
    1329         [ +  + ]:      368659 :             if (lstat(initForkFile, &statbuf) == 0)
    1330                 :             :             {
    1331         [ -  + ]:          81 :                 elog(DEBUG2,
    1332                 :             :                      "unlogged relation file \"%s\" excluded from backup",
    1333                 :             :                      de->d_name);
    1334                 :             : 
    1335                 :          81 :                 continue;
    1336                 :             :             }
    1337                 :             :         }
    1338                 :             : 
    1339                 :             :         /* Exclude temporary relations */
    1340   [ +  +  +  + ]:      384016 :         if (OidIsValid(dboid) && looks_like_temp_rel_name(de->d_name))
    1341                 :             :         {
    1342         [ -  + ]:          36 :             elog(DEBUG2,
    1343                 :             :                  "temporary relation file \"%s\" excluded from backup",
    1344                 :             :                  de->d_name);
    1345                 :             : 
    1346                 :          36 :             continue;
    1347                 :             :         }
    1348                 :             : 
    1349                 :      383980 :         snprintf(pathbuf, sizeof(pathbuf), "%s/%s", path, de->d_name);
    1350                 :             : 
    1351                 :             :         /* Skip pg_control here to back up it last */
    1352         [ +  + ]:      383980 :         if (strcmp(pathbuf, "./" XLOG_CONTROL_FILE) == 0)
    1353                 :         354 :             continue;
    1354                 :             : 
    1355         [ -  + ]:      383626 :         if (lstat(pathbuf, &statbuf) != 0)
    1356                 :             :         {
    1357         [ #  # ]:           0 :             if (errno != ENOENT)
    1358         [ #  # ]:           0 :                 ereport(ERROR,
    1359                 :             :                         (errcode_for_file_access(),
    1360                 :             :                          errmsg("could not stat file or directory \"%s\": %m",
    1361                 :             :                                 pathbuf)));
    1362                 :             : 
    1363                 :             :             /* If the file went away while scanning, it's not an error. */
    1364                 :           0 :             continue;
    1365                 :             :         }
    1366                 :             : 
    1367                 :             :         /* Scan for directories whose contents should be excluded */
    1368                 :      383626 :         excludeFound = false;
    1369         [ +  + ]:     3059052 :         for (excludeIdx = 0; excludeDirContents[excludeIdx] != NULL; excludeIdx++)
    1370                 :             :         {
    1371         [ +  + ]:     2677912 :             if (strcmp(de->d_name, excludeDirContents[excludeIdx]) == 0)
    1372                 :             :             {
    1373         [ +  + ]:        2486 :                 elog(DEBUG1, "contents of directory \"%s\" excluded from backup", de->d_name);
    1374                 :        2486 :                 convert_link_to_directory(pathbuf, &statbuf);
    1375                 :        2486 :                 size += _tarWriteHeader(sink, pathbuf + basepathlen + 1, NULL,
    1376                 :             :                                         &statbuf, sizeonly);
    1377                 :        2486 :                 excludeFound = true;
    1378                 :        2486 :                 break;
    1379                 :             :             }
    1380                 :             :         }
    1381                 :             : 
    1382         [ +  + ]:      383626 :         if (excludeFound)
    1383                 :        2486 :             continue;
    1384                 :             : 
    1385                 :             :         /*
    1386                 :             :          * We can skip pg_wal, the WAL segments need to be fetched from the
    1387                 :             :          * WAL archive anyway. But include it as an empty directory anyway, so
    1388                 :             :          * we get permissions right.
    1389                 :             :          */
    1390         [ +  + ]:      381140 :         if (strcmp(pathbuf, "./pg_wal") == 0)
    1391                 :             :         {
    1392                 :             :             /* If pg_wal is a symlink, write it as a directory anyway */
    1393                 :         354 :             convert_link_to_directory(pathbuf, &statbuf);
    1394                 :         354 :             size += _tarWriteHeader(sink, pathbuf + basepathlen + 1, NULL,
    1395                 :             :                                     &statbuf, sizeonly);
    1396                 :             : 
    1397                 :             :             /*
    1398                 :             :              * Also send archive_status and summaries directories (by
    1399                 :             :              * hackishly reusing statbuf from above ...).
    1400                 :             :              */
    1401                 :         354 :             size += _tarWriteHeader(sink, "./pg_wal/archive_status", NULL,
    1402                 :             :                                     &statbuf, sizeonly);
    1403                 :         354 :             size += _tarWriteHeader(sink, "./pg_wal/summaries", NULL,
    1404                 :             :                                     &statbuf, sizeonly);
    1405                 :             : 
    1406                 :         354 :             continue;           /* don't recurse into pg_wal */
    1407                 :             :         }
    1408                 :             : 
    1409                 :             :         /* Allow symbolic links in pg_tblspc only */
    1410   [ +  +  +  + ]:      380786 :         if (strcmp(path, "./pg_tblspc") == 0 && S_ISLNK(statbuf.st_mode))
    1411                 :          39 :         {
    1412                 :             :             char        linkpath[MAXPGPATH];
    1413                 :             :             ssize_t     rllen;
    1414                 :             : 
    1415                 :          39 :             rllen = readlink(pathbuf, linkpath, sizeof(linkpath));
    1416         [ -  + ]:          39 :             if (rllen < 0)
    1417         [ #  # ]:           0 :                 ereport(ERROR,
    1418                 :             :                         (errcode_for_file_access(),
    1419                 :             :                          errmsg("could not read symbolic link \"%s\": %m",
    1420                 :             :                                 pathbuf)));
    1421         [ -  + ]:          39 :             if (rllen >= sizeof(linkpath))
    1422         [ #  # ]:           0 :                 ereport(ERROR,
    1423                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    1424                 :             :                          errmsg("symbolic link \"%s\" target is too long",
    1425                 :             :                                 pathbuf)));
    1426                 :          39 :             linkpath[rllen] = '\0';
    1427                 :             : 
    1428                 :          39 :             size += _tarWriteHeader(sink, pathbuf + basepathlen + 1, linkpath,
    1429                 :             :                                     &statbuf, sizeonly);
    1430                 :             :         }
    1431         [ +  + ]:      380747 :         else if (S_ISDIR(statbuf.st_mode))
    1432                 :             :         {
    1433                 :        5817 :             bool        skip_this_dir = false;
    1434                 :             :             ListCell   *lc;
    1435                 :             : 
    1436                 :             :             /*
    1437                 :             :              * Store a directory entry in the tar file so we can get the
    1438                 :             :              * permissions right.
    1439                 :             :              */
    1440                 :        5817 :             size += _tarWriteHeader(sink, pathbuf + basepathlen + 1, NULL, &statbuf,
    1441                 :             :                                     sizeonly);
    1442                 :             : 
    1443                 :             :             /*
    1444                 :             :              * Call ourselves recursively for a directory, unless it happens
    1445                 :             :              * to be a separate tablespace located within PGDATA.
    1446                 :             :              */
    1447   [ +  +  +  +  :       12776 :             foreach(lc, tablespaces)
                   +  + ]
    1448                 :             :             {
    1449                 :        6987 :                 tablespaceinfo *ti = (tablespaceinfo *) lfirst(lc);
    1450                 :             : 
    1451                 :             :                 /*
    1452                 :             :                  * ti->rpath is the tablespace relative path within PGDATA, or
    1453                 :             :                  * NULL if the tablespace has been properly located somewhere
    1454                 :             :                  * else.
    1455                 :             :                  *
    1456                 :             :                  * Skip past the leading "./" in pathbuf when comparing.
    1457                 :             :                  */
    1458   [ +  +  +  + ]:        6987 :                 if (ti->rpath && strcmp(ti->rpath, pathbuf + 2) == 0)
    1459                 :             :                 {
    1460                 :          28 :                     skip_this_dir = true;
    1461                 :          28 :                     break;
    1462                 :             :                 }
    1463                 :             :             }
    1464                 :             : 
    1465                 :             :             /*
    1466                 :             :              * skip sending directories inside pg_tblspc, if not required.
    1467                 :             :              */
    1468   [ +  +  +  + ]:        5817 :             if (strcmp(pathbuf, "./pg_tblspc") == 0 && !sendtblspclinks)
    1469                 :          27 :                 skip_this_dir = true;
    1470                 :             : 
    1471         [ +  + ]:        5817 :             if (!skip_this_dir)
    1472                 :        5762 :                 size += sendDir(sink, pathbuf, basepathlen, sizeonly, tablespaces,
    1473                 :             :                                 sendtblspclinks, manifest, spcoid, ib);
    1474                 :             :         }
    1475         [ +  - ]:      374930 :         else if (S_ISREG(statbuf.st_mode))
    1476                 :             :         {
    1477                 :      374930 :             bool        sent = false;
    1478                 :      374930 :             unsigned    num_blocks_required = 0;
    1479                 :      374930 :             unsigned    truncation_block_length = 0;
    1480                 :             :             char        tarfilenamebuf[MAXPGPATH * 2];
    1481                 :      374930 :             char       *tarfilename = pathbuf + basepathlen + 1;
    1482                 :      374930 :             FileBackupMethod method = BACK_UP_FILE_FULLY;
    1483                 :             : 
    1484   [ +  +  +  + ]:      374930 :             if (ib != NULL && isRelationFile)
    1485                 :             :             {
    1486                 :             :                 Oid         relspcoid;
    1487                 :             :                 char       *lookup_path;
    1488                 :             : 
    1489         [ +  + ]:       11795 :                 if (OidIsValid(spcoid))
    1490                 :             :                 {
    1491                 :           9 :                     relspcoid = spcoid;
    1492                 :           9 :                     lookup_path = psprintf("%s/%u/%s", PG_TBLSPC_DIR, spcoid,
    1493                 :             :                                            tarfilename);
    1494                 :             :                 }
    1495                 :             :                 else
    1496                 :             :                 {
    1497         [ +  + ]:       11786 :                     if (isGlobalDir)
    1498                 :         616 :                         relspcoid = GLOBALTABLESPACE_OID;
    1499                 :             :                     else
    1500                 :       11170 :                         relspcoid = DEFAULTTABLESPACE_OID;
    1501                 :       11786 :                     lookup_path = pstrdup(tarfilename);
    1502                 :             :                 }
    1503                 :             : 
    1504                 :       11795 :                 method = GetFileBackupMethod(ib, lookup_path, dboid, relspcoid,
    1505                 :             :                                              relfilenumber, relForkNum,
    1506                 :       11795 :                                              segno, statbuf.st_size,
    1507                 :             :                                              &num_blocks_required,
    1508                 :             :                                              relative_block_numbers,
    1509                 :             :                                              &truncation_block_length);
    1510         [ +  + ]:       11795 :                 if (method == BACK_UP_FILE_INCREMENTALLY)
    1511                 :             :                 {
    1512                 :        7756 :                     statbuf.st_size =
    1513                 :        7756 :                         GetIncrementalFileSize(num_blocks_required);
    1514                 :        7756 :                     snprintf(tarfilenamebuf, sizeof(tarfilenamebuf),
    1515                 :             :                              "%s/INCREMENTAL.%s",
    1516                 :        7756 :                              path + basepathlen + 1,
    1517                 :        7756 :                              de->d_name);
    1518                 :        7756 :                     tarfilename = tarfilenamebuf;
    1519                 :             :                 }
    1520                 :             : 
    1521                 :       11795 :                 pfree(lookup_path);
    1522                 :             :             }
    1523                 :             : 
    1524         [ +  + ]:      374930 :             if (!sizeonly)
    1525         [ +  + ]:      184956 :                 sent = sendFile(sink, pathbuf, tarfilename, &statbuf,
    1526                 :             :                                 true, dboid, spcoid,
    1527                 :             :                                 relfilenumber, segno, manifest,
    1528                 :             :                                 num_blocks_required,
    1529                 :             :                                 method == BACK_UP_FILE_INCREMENTALLY ? relative_block_numbers : NULL,
    1530                 :             :                                 truncation_block_length);
    1531                 :             : 
    1532   [ +  +  +  - ]:      374929 :             if (sent || sizeonly)
    1533                 :             :             {
    1534                 :             :                 /* Add size. */
    1535                 :      374929 :                 size += statbuf.st_size;
    1536                 :             : 
    1537                 :             :                 /* Pad to a multiple of the tar block size. */
    1538                 :      374929 :                 size += tarPaddingBytesRequired(statbuf.st_size);
    1539                 :             : 
    1540                 :             :                 /* Size of the header for the file. */
    1541                 :      374929 :                 size += TAR_BLOCK_SIZE;
    1542                 :             :             }
    1543                 :             :         }
    1544                 :             :         else
    1545         [ #  # ]:           0 :             ereport(WARNING,
    1546                 :             :                     (errmsg("skipping special file \"%s\"", pathbuf)));
    1547                 :             :     }
    1548                 :             : 
    1549         [ +  + ]:        6185 :     if (relative_block_numbers != NULL)
    1550                 :         191 :         pfree(relative_block_numbers);
    1551                 :             : 
    1552                 :        6185 :     FreeDir(dir);
    1553                 :        6185 :     return size;
    1554                 :             : }
    1555                 :             : 
    1556                 :             : /*
    1557                 :             :  * Given the member, write the TAR header & send the file.
    1558                 :             :  *
    1559                 :             :  * If 'missing_ok' is true, will not throw an error if the file is not found.
    1560                 :             :  *
    1561                 :             :  * If dboid is anything other than InvalidOid then any checksum failures
    1562                 :             :  * detected will get reported to the cumulative stats system.
    1563                 :             :  *
    1564                 :             :  * If the file is to be sent incrementally, then num_incremental_blocks
    1565                 :             :  * should be the number of blocks to be sent, and incremental_blocks
    1566                 :             :  * an array of block numbers relative to the start of the current segment.
    1567                 :             :  * If the whole file is to be sent, then incremental_blocks should be NULL,
    1568                 :             :  * and num_incremental_blocks can have any value, as it will be ignored.
    1569                 :             :  *
    1570                 :             :  * Returns true if the file was successfully sent, false if 'missing_ok',
    1571                 :             :  * and the file did not exist.
    1572                 :             :  */
    1573                 :             : static bool
    1574                 :      185130 : sendFile(bbsink *sink, const char *readfilename, const char *tarfilename,
    1575                 :             :          struct stat *statbuf, bool missing_ok, Oid dboid, Oid spcoid,
    1576                 :             :          RelFileNumber relfilenumber, unsigned segno,
    1577                 :             :          backup_manifest_info *manifest, unsigned num_incremental_blocks,
    1578                 :             :          BlockNumber *incremental_blocks, unsigned truncation_block_length)
    1579                 :             : {
    1580                 :             :     int         fd;
    1581                 :      185130 :     BlockNumber blkno = 0;
    1582                 :      185130 :     int         checksum_failures = 0;
    1583                 :             :     off_t       cnt;
    1584                 :      185130 :     pgoff_t     bytes_done = 0;
    1585                 :      185130 :     bool        verify_checksum = false;
    1586                 :             :     pg_checksum_context checksum_ctx;
    1587                 :      185130 :     int         ibindex = 0;
    1588                 :             : 
    1589         [ -  + ]:      185130 :     if (pg_checksum_init(&checksum_ctx, manifest->checksum_type) < 0)
    1590         [ #  # ]:           0 :         elog(ERROR, "could not initialize checksum of file \"%s\"",
    1591                 :             :              readfilename);
    1592                 :             : 
    1593                 :      185130 :     fd = OpenTransientFile(readfilename, O_RDONLY | PG_BINARY);
    1594         [ -  + ]:      185130 :     if (fd < 0)
    1595                 :             :     {
    1596   [ #  #  #  # ]:           0 :         if (errno == ENOENT && missing_ok)
    1597                 :           0 :             return false;
    1598         [ #  # ]:           0 :         ereport(ERROR,
    1599                 :             :                 (errcode_for_file_access(),
    1600                 :             :                  errmsg("could not open file \"%s\": %m", readfilename)));
    1601                 :             :     }
    1602                 :             : 
    1603                 :      185130 :     _tarWriteHeader(sink, tarfilename, NULL, statbuf, false);
    1604                 :             : 
    1605                 :             :     /*
    1606                 :             :      * Checksums are verified in multiples of BLCKSZ, so the buffer length
    1607                 :             :      * should be a multiple of the block size as well.
    1608                 :             :      */
    1609                 :             :     Assert((sink->bbs_buffer_length % BLCKSZ) == 0);
    1610                 :             : 
    1611                 :             :     /*
    1612                 :             :      * If we weren't told not to verify checksums, and if checksums are
    1613                 :             :      * enabled for this cluster, and if this is a relation file, then verify
    1614                 :             :      * the checksum.  We cannot at this point check if checksums are enabled
    1615                 :             :      * or disabled as that might change, thus we check at each point where we
    1616                 :             :      * could be validating a checksum.
    1617                 :             :      */
    1618   [ +  +  +  + ]:      185129 :     if (!noverify_checksums && RelFileNumberIsValid(relfilenumber))
    1619                 :      180832 :         verify_checksum = true;
    1620                 :             : 
    1621                 :             :     /*
    1622                 :             :      * If we're sending an incremental file, write the file header.
    1623                 :             :      */
    1624         [ +  + ]:      185129 :     if (incremental_blocks != NULL)
    1625                 :             :     {
    1626                 :        7756 :         unsigned    magic = INCREMENTAL_MAGIC;
    1627                 :        7756 :         size_t      header_bytes_done = 0;
    1628                 :             :         char        padding[BLCKSZ];
    1629                 :             :         size_t      paddinglen;
    1630                 :             : 
    1631                 :             :         /* Emit header data. */
    1632                 :        7756 :         push_to_sink(sink, &checksum_ctx, &header_bytes_done,
    1633                 :             :                      &magic, sizeof(magic));
    1634                 :        7756 :         push_to_sink(sink, &checksum_ctx, &header_bytes_done,
    1635                 :             :                      &num_incremental_blocks, sizeof(num_incremental_blocks));
    1636                 :        7756 :         push_to_sink(sink, &checksum_ctx, &header_bytes_done,
    1637                 :             :                      &truncation_block_length, sizeof(truncation_block_length));
    1638                 :        7756 :         push_to_sink(sink, &checksum_ctx, &header_bytes_done,
    1639                 :             :                      incremental_blocks,
    1640                 :             :                      sizeof(BlockNumber) * num_incremental_blocks);
    1641                 :             : 
    1642                 :             :         /*
    1643                 :             :          * Add padding to align header to a multiple of BLCKSZ, but only if
    1644                 :             :          * the incremental file has some blocks, and the alignment is actually
    1645                 :             :          * needed (i.e. header is not already a multiple of BLCKSZ). If there
    1646                 :             :          * are no blocks we don't want to make the file unnecessarily large,
    1647                 :             :          * as that might make some filesystem optimizations impossible.
    1648                 :             :          */
    1649   [ +  +  +  - ]:        7756 :         if ((num_incremental_blocks > 0) && (header_bytes_done % BLCKSZ != 0))
    1650                 :             :         {
    1651                 :          25 :             paddinglen = (BLCKSZ - (header_bytes_done % BLCKSZ));
    1652                 :             : 
    1653                 :          25 :             memset(padding, 0, paddinglen);
    1654                 :          25 :             bytes_done += paddinglen;
    1655                 :             : 
    1656                 :          25 :             push_to_sink(sink, &checksum_ctx, &header_bytes_done,
    1657                 :             :                          padding, paddinglen);
    1658                 :             :         }
    1659                 :             : 
    1660                 :             :         /* Flush out any data still in the buffer so it's again empty. */
    1661         [ +  - ]:        7756 :         if (header_bytes_done > 0)
    1662                 :             :         {
    1663                 :        7756 :             bbsink_archive_contents(sink, header_bytes_done);
    1664         [ -  + ]:        7756 :             if (pg_checksum_update(&checksum_ctx,
    1665                 :        7756 :                                    (uint8 *) sink->bbs_buffer,
    1666                 :             :                                    header_bytes_done) < 0)
    1667         [ #  # ]:           0 :                 elog(ERROR, "could not update checksum of base backup");
    1668                 :             :         }
    1669                 :             : 
    1670                 :             :         /* Update our notion of file position. */
    1671                 :        7756 :         bytes_done += sizeof(magic);
    1672                 :        7756 :         bytes_done += sizeof(num_incremental_blocks);
    1673                 :        7756 :         bytes_done += sizeof(truncation_block_length);
    1674                 :        7756 :         bytes_done += sizeof(BlockNumber) * num_incremental_blocks;
    1675                 :             :     }
    1676                 :             : 
    1677                 :             :     /*
    1678                 :             :      * Loop until we read the amount of data the caller told us to expect. The
    1679                 :             :      * file could be longer, if it was extended while we were sending it, but
    1680                 :             :      * for a base backup we can ignore such extended data. It will be restored
    1681                 :             :      * from WAL.
    1682                 :             :      */
    1683                 :             :     while (1)
    1684                 :             :     {
    1685                 :             :         /*
    1686                 :             :          * Determine whether we've read all the data that we need, and if not,
    1687                 :             :          * read some more.
    1688                 :             :          */
    1689         [ +  + ]:      395226 :         if (incremental_blocks == NULL)
    1690                 :             :         {
    1691                 :      387434 :             size_t      remaining = statbuf->st_size - bytes_done;
    1692                 :             : 
    1693                 :             :             /*
    1694                 :             :              * If we've read the required number of bytes, then it's time to
    1695                 :             :              * stop.
    1696                 :             :              */
    1697         [ +  + ]:      387434 :             if (bytes_done >= statbuf->st_size)
    1698                 :      177373 :                 break;
    1699                 :             : 
    1700                 :             :             /*
    1701                 :             :              * Read as many bytes as will fit in the buffer, or however many
    1702                 :             :              * are left to read, whichever is less.
    1703                 :             :              */
    1704                 :      210061 :             cnt = read_file_data_into_buffer(sink, readfilename, fd,
    1705                 :             :                                              bytes_done, remaining,
    1706                 :      210061 :                                              blkno + segno * RELSEG_SIZE,
    1707                 :             :                                              verify_checksum,
    1708                 :             :                                              &checksum_failures);
    1709                 :             :         }
    1710                 :             :         else
    1711                 :             :         {
    1712                 :             :             BlockNumber relative_blkno;
    1713                 :             : 
    1714                 :             :             /*
    1715                 :             :              * If we've read all the blocks, then it's time to stop.
    1716                 :             :              */
    1717         [ +  + ]:        7792 :             if (ibindex >= num_incremental_blocks)
    1718                 :        7756 :                 break;
    1719                 :             : 
    1720                 :             :             /*
    1721                 :             :              * Read just one block, whichever one is the next that we're
    1722                 :             :              * supposed to include.
    1723                 :             :              */
    1724                 :          36 :             relative_blkno = incremental_blocks[ibindex++];
    1725                 :          36 :             cnt = read_file_data_into_buffer(sink, readfilename, fd,
    1726                 :          36 :                                              relative_blkno * BLCKSZ,
    1727                 :             :                                              BLCKSZ,
    1728                 :          36 :                                              relative_blkno + segno * RELSEG_SIZE,
    1729                 :             :                                              verify_checksum,
    1730                 :             :                                              &checksum_failures);
    1731                 :             : 
    1732                 :             :             /*
    1733                 :             :              * If we get a partial read, that must mean that the relation is
    1734                 :             :              * being truncated. Ultimately, it should be truncated to a
    1735                 :             :              * multiple of BLCKSZ, since this path should only be reached for
    1736                 :             :              * relation files, but we might transiently observe an
    1737                 :             :              * intermediate value.
    1738                 :             :              *
    1739                 :             :              * It should be fine to treat this just as if the entire block had
    1740                 :             :              * been truncated away - i.e. fill this and all later blocks with
    1741                 :             :              * zeroes. WAL replay will fix things up.
    1742                 :             :              */
    1743         [ -  + ]:          36 :             if (cnt < BLCKSZ)
    1744                 :           0 :                 break;
    1745                 :             :         }
    1746                 :             : 
    1747                 :             :         /*
    1748                 :             :          * If the amount of data we were able to read was not a multiple of
    1749                 :             :          * BLCKSZ, we cannot verify checksums, which are block-level.
    1750                 :             :          */
    1751   [ +  +  +  +  :      210097 :         if (verify_checksum && DataChecksumsNeedVerify() && (cnt % BLCKSZ != 0))
                   -  + ]
    1752                 :             :         {
    1753         [ #  # ]:           0 :             ereport(WARNING,
    1754                 :             :                     (errmsg("could not verify checksum in file \"%s\", block "
    1755                 :             :                             "%u: read buffer size %d and page size %d "
    1756                 :             :                             "differ",
    1757                 :             :                             readfilename, blkno, (int) cnt, BLCKSZ)));
    1758                 :           0 :             verify_checksum = false;
    1759                 :             :         }
    1760                 :             : 
    1761                 :             :         /*
    1762                 :             :          * If we hit end-of-file, a concurrent truncation must have occurred.
    1763                 :             :          * That's not an error condition, because WAL replay will fix things
    1764                 :             :          * up.
    1765                 :             :          */
    1766         [ -  + ]:      210097 :         if (cnt == 0)
    1767                 :           0 :             break;
    1768                 :             : 
    1769                 :             :         /* Update block number and # of bytes done for next loop iteration. */
    1770                 :      210097 :         blkno += cnt / BLCKSZ;
    1771                 :      210097 :         bytes_done += cnt;
    1772                 :             : 
    1773                 :             :         /*
    1774                 :             :          * Make sure incremental files with block data are properly aligned
    1775                 :             :          * (header is a multiple of BLCKSZ, blocks are BLCKSZ too).
    1776                 :             :          */
    1777                 :             :         Assert(!((incremental_blocks != NULL && num_incremental_blocks > 0) &&
    1778                 :             :                  (bytes_done % BLCKSZ != 0)));
    1779                 :             : 
    1780                 :             :         /* Archive the data we just read. */
    1781                 :      210097 :         bbsink_archive_contents(sink, cnt);
    1782                 :             : 
    1783                 :             :         /* Also feed it to the checksum machinery. */
    1784         [ -  + ]:      210097 :         if (pg_checksum_update(&checksum_ctx,
    1785                 :      210097 :                                (uint8 *) sink->bbs_buffer, cnt) < 0)
    1786         [ #  # ]:           0 :             elog(ERROR, "could not update checksum of base backup");
    1787                 :             :     }
    1788                 :             : 
    1789                 :             :     /* If the file was truncated while we were sending it, pad it with zeros */
    1790         [ -  + ]:      185129 :     while (bytes_done < statbuf->st_size)
    1791                 :             :     {
    1792                 :           0 :         size_t      remaining = statbuf->st_size - bytes_done;
    1793                 :           0 :         size_t      nbytes = Min(sink->bbs_buffer_length, remaining);
    1794                 :             : 
    1795   [ #  #  #  #  :           0 :         MemSet(sink->bbs_buffer, 0, nbytes);
          #  #  #  #  #  
                      # ]
    1796         [ #  # ]:           0 :         if (pg_checksum_update(&checksum_ctx,
    1797                 :           0 :                                (uint8 *) sink->bbs_buffer,
    1798                 :             :                                nbytes) < 0)
    1799         [ #  # ]:           0 :             elog(ERROR, "could not update checksum of base backup");
    1800                 :           0 :         bbsink_archive_contents(sink, nbytes);
    1801                 :           0 :         bytes_done += nbytes;
    1802                 :             :     }
    1803                 :             : 
    1804                 :             :     /*
    1805                 :             :      * Pad to a block boundary, per tar format requirements. (This small piece
    1806                 :             :      * of data is probably not worth throttling, and is not checksummed
    1807                 :             :      * because it's not actually part of the file.)
    1808                 :             :      */
    1809                 :      185129 :     _tarWritePadding(sink, bytes_done);
    1810                 :             : 
    1811                 :      185129 :     CloseTransientFile(fd);
    1812                 :             : 
    1813         [ +  + ]:      185129 :     if (checksum_failures > 1)
    1814                 :             :     {
    1815         [ +  - ]:           2 :         ereport(WARNING,
    1816                 :             :                 (errmsg_plural("file \"%s\" has a total of %d checksum verification failure",
    1817                 :             :                                "file \"%s\" has a total of %d checksum verification failures",
    1818                 :             :                                checksum_failures,
    1819                 :             :                                readfilename, checksum_failures)));
    1820                 :             : 
    1821                 :           2 :         pgstat_prepare_report_checksum_failure(dboid);
    1822                 :           2 :         pgstat_report_checksum_failures_in_db(dboid, checksum_failures);
    1823                 :             :     }
    1824                 :             : 
    1825                 :      185129 :     total_checksum_failures += checksum_failures;
    1826                 :             : 
    1827                 :      185129 :     AddFileToBackupManifest(manifest, spcoid, tarfilename, statbuf->st_size,
    1828                 :      185129 :                             (pg_time_t) statbuf->st_mtime, &checksum_ctx);
    1829                 :             : 
    1830                 :      185129 :     return true;
    1831                 :             : }
    1832                 :             : 
    1833                 :             : /*
    1834                 :             :  * Read some more data from the file into the bbsink's buffer, verifying
    1835                 :             :  * checksums as required.
    1836                 :             :  *
    1837                 :             :  * 'offset' is the file offset from which we should begin to read, and
    1838                 :             :  * 'length' is the amount of data that should be read. The actual amount
    1839                 :             :  * of data read will be less than the requested amount if the bbsink's
    1840                 :             :  * buffer isn't big enough to hold it all, or if the underlying file has
    1841                 :             :  * been truncated. The return value is the number of bytes actually read.
    1842                 :             :  *
    1843                 :             :  * 'blkno' is the block number of the first page in the bbsink's buffer
    1844                 :             :  * relative to the start of the relation.
    1845                 :             :  *
    1846                 :             :  * 'verify_checksum' determines if the user has asked to verify checksums, but
    1847                 :             :  * since data checksums can be disabled, or become disabled, we need to check
    1848                 :             :  * state before verifying individual pages.  If we do this, we'll update
    1849                 :             :  * *checksum_failures and issue warnings as appropriate.
    1850                 :             :  */
    1851                 :             : static off_t
    1852                 :      210097 : read_file_data_into_buffer(bbsink *sink, const char *readfilename, int fd,
    1853                 :             :                            off_t offset, size_t length, BlockNumber blkno,
    1854                 :             :                            bool verify_checksum, int *checksum_failures)
    1855                 :             : {
    1856                 :             :     off_t       cnt;
    1857                 :             :     int         i;
    1858                 :             :     char       *page;
    1859                 :             : 
    1860                 :             :     /* Try to read some more data. */
    1861                 :      210097 :     cnt = basebackup_read_file(fd, sink->bbs_buffer,
    1862                 :      210097 :                                Min(sink->bbs_buffer_length, length),
    1863                 :             :                                offset, readfilename, true);
    1864                 :             : 
    1865                 :             :     /* Can't verify checksums if read length is not a multiple of BLCKSZ. */
    1866   [ +  +  -  + ]:      210097 :     if (!verify_checksum || (cnt % BLCKSZ) != 0)
    1867                 :        4841 :         return cnt;
    1868                 :             : 
    1869                 :             :     /* Verify checksum for each block. */
    1870         [ +  + ]:      701855 :     for (i = 0; i < cnt / BLCKSZ; i++)
    1871                 :             :     {
    1872                 :             :         int         reread_cnt;
    1873                 :             :         uint16      expected_checksum;
    1874                 :             : 
    1875                 :             :         /*
    1876                 :             :          * The data checksum state can change at any point, so we need to
    1877                 :             :          * re-check before each page.
    1878                 :             :          */
    1879         [ +  + ]:      499057 :         if (!DataChecksumsNeedVerify())
    1880                 :        2458 :             return cnt;
    1881                 :             : 
    1882                 :      496599 :         page = sink->bbs_buffer + BLCKSZ * i;
    1883                 :             : 
    1884                 :             :         /* If the page is OK, go on to the next one. */
    1885         [ +  + ]:      496599 :         if (verify_page_checksum(page, sink->bbs_state->startptr, blkno + i,
    1886                 :             :                                  &expected_checksum))
    1887                 :      496585 :             continue;
    1888                 :             : 
    1889                 :             :         /*
    1890                 :             :          * Retry the block on the first failure.  It's possible that we read
    1891                 :             :          * the first 4K page of the block just before postgres updated the
    1892                 :             :          * entire block so it ends up looking torn to us. If, before we retry
    1893                 :             :          * the read, the concurrent write of the block finishes, the page LSN
    1894                 :             :          * will be updated and we'll realize that we should ignore this block.
    1895                 :             :          *
    1896                 :             :          * There's no guarantee that this will actually happen, though: the
    1897                 :             :          * torn write could take an arbitrarily long time to complete.
    1898                 :             :          * Retrying multiple times wouldn't fix this problem, either, though
    1899                 :             :          * it would reduce the chances of it happening in practice. The only
    1900                 :             :          * real fix here seems to be to have some kind of interlock that
    1901                 :             :          * allows us to wait until we can be certain that no write to the
    1902                 :             :          * block is in progress. Since we don't have any such thing right now,
    1903                 :             :          * we just do this and hope for the best.
    1904                 :             :          *
    1905                 :             :          * The data checksum state may also have changed concurrently so check
    1906                 :             :          * again.
    1907                 :             :          */
    1908         [ -  + ]:          14 :         if (!DataChecksumsNeedVerify())
    1909                 :           0 :             return cnt;
    1910                 :          14 :         reread_cnt =
    1911                 :          14 :             basebackup_read_file(fd, sink->bbs_buffer + BLCKSZ * i,
    1912                 :          14 :                                  BLCKSZ, offset + BLCKSZ * i,
    1913                 :             :                                  readfilename, false);
    1914         [ -  + ]:          14 :         if (reread_cnt == 0)
    1915                 :             :         {
    1916                 :             :             /*
    1917                 :             :              * If we hit end-of-file, a concurrent truncation must have
    1918                 :             :              * occurred, so reduce cnt to reflect only the blocks already
    1919                 :             :              * processed and break out of this loop.
    1920                 :             :              */
    1921                 :           0 :             cnt = BLCKSZ * i;
    1922                 :           0 :             break;
    1923                 :             :         }
    1924                 :             : 
    1925                 :             :         /* If the page now looks OK, go on to the next one. */
    1926         [ -  + ]:          14 :         if (verify_page_checksum(page, sink->bbs_state->startptr, blkno + i,
    1927                 :             :                                  &expected_checksum))
    1928                 :           0 :             continue;
    1929                 :             : 
    1930                 :             :         /* Handle checksum failure. */
    1931                 :          14 :         (*checksum_failures)++;
    1932         [ +  + ]:          14 :         if (*checksum_failures <= 5)
    1933         [ +  - ]:          12 :             ereport(WARNING,
    1934                 :             :                     (errmsg("checksum verification failed in "
    1935                 :             :                             "file \"%s\", block %u: calculated "
    1936                 :             :                             "%X but expected %X",
    1937                 :             :                             readfilename, blkno + i, expected_checksum,
    1938                 :             :                             ((PageHeader) page)->pd_checksum)));
    1939         [ +  + ]:          14 :         if (*checksum_failures == 5)
    1940         [ +  - ]:           2 :             ereport(WARNING,
    1941                 :             :                     (errmsg("further checksum verification "
    1942                 :             :                             "failures in file \"%s\" will not "
    1943                 :             :                             "be reported", readfilename)));
    1944                 :             :     }
    1945                 :             : 
    1946                 :      202798 :     return cnt;
    1947                 :             : }
    1948                 :             : 
    1949                 :             : /*
    1950                 :             :  * Push data into a bbsink.
    1951                 :             :  *
    1952                 :             :  * It's better, when possible, to read data directly into the bbsink's buffer,
    1953                 :             :  * rather than using this function to copy it into the buffer; this function is
    1954                 :             :  * for cases where that approach is not practical.
    1955                 :             :  *
    1956                 :             :  * bytes_done should point to a count of the number of bytes that are
    1957                 :             :  * currently used in the bbsink's buffer. Upon return, the bytes identified by
    1958                 :             :  * data and length will have been copied into the bbsink's buffer, flushing
    1959                 :             :  * as required, and *bytes_done will have been updated accordingly. If the
    1960                 :             :  * buffer was flushed, the previous contents will also have been fed to
    1961                 :             :  * checksum_ctx.
    1962                 :             :  *
    1963                 :             :  * Note that after one or more calls to this function it is the caller's
    1964                 :             :  * responsibility to perform any required final flush.
    1965                 :             :  */
    1966                 :             : static void
    1967                 :       31049 : push_to_sink(bbsink *sink, pg_checksum_context *checksum_ctx,
    1968                 :             :              size_t *bytes_done, void *data, size_t length)
    1969                 :             : {
    1970         [ +  + ]:       31049 :     while (length > 0)
    1971                 :             :     {
    1972                 :             :         size_t      bytes_to_copy;
    1973                 :             : 
    1974                 :             :         /*
    1975                 :             :          * We use < here rather than <= so that if the data exactly fills the
    1976                 :             :          * remaining buffer space, we trigger a flush now.
    1977                 :             :          */
    1978         [ +  - ]:       23318 :         if (length < sink->bbs_buffer_length - *bytes_done)
    1979                 :             :         {
    1980                 :             :             /* Append remaining data to buffer. */
    1981                 :       23318 :             memcpy(sink->bbs_buffer + *bytes_done, data, length);
    1982                 :       23318 :             *bytes_done += length;
    1983                 :       23318 :             return;
    1984                 :             :         }
    1985                 :             : 
    1986                 :             :         /* Copy until buffer is full and flush it. */
    1987                 :           0 :         bytes_to_copy = sink->bbs_buffer_length - *bytes_done;
    1988                 :           0 :         memcpy(sink->bbs_buffer + *bytes_done, data, bytes_to_copy);
    1989                 :           0 :         data = ((char *) data) + bytes_to_copy;
    1990                 :           0 :         length -= bytes_to_copy;
    1991                 :           0 :         bbsink_archive_contents(sink, sink->bbs_buffer_length);
    1992         [ #  # ]:           0 :         if (pg_checksum_update(checksum_ctx, (uint8 *) sink->bbs_buffer,
    1993                 :             :                                sink->bbs_buffer_length) < 0)
    1994         [ #  # ]:           0 :             elog(ERROR, "could not update checksum");
    1995                 :           0 :         *bytes_done = 0;
    1996                 :             :     }
    1997                 :             : }
    1998                 :             : 
    1999                 :             : /*
    2000                 :             :  * Try to verify the checksum for the provided page, if it seems appropriate
    2001                 :             :  * to do so.
    2002                 :             :  *
    2003                 :             :  * Returns true if verification succeeds or if we decide not to check it,
    2004                 :             :  * and false if verification fails. When return false, it also sets
    2005                 :             :  * *expected_checksum to the computed value.
    2006                 :             :  */
    2007                 :             : static bool
    2008                 :      496613 : verify_page_checksum(Page page, XLogRecPtr start_lsn, BlockNumber blkno,
    2009                 :             :                      uint16 *expected_checksum)
    2010                 :             : {
    2011                 :             :     PageHeader  phdr;
    2012                 :             :     uint16      checksum;
    2013                 :             : 
    2014                 :             :     /*
    2015                 :             :      * Only check pages which have not been modified since the start of the
    2016                 :             :      * base backup. Otherwise, they might have been written only halfway and
    2017                 :             :      * the checksum would not be valid.  However, replaying WAL would
    2018                 :             :      * reinstate the correct page in this case. We also skip completely new
    2019                 :             :      * pages, since they don't have a checksum yet.
    2020                 :             :      */
    2021   [ +  +  +  + ]:      496613 :     if (PageIsNew(page) || PageGetLSN(page) >= start_lsn)
    2022                 :        1055 :         return true;
    2023                 :             : 
    2024         [ -  + ]:      495558 :     if (!DataChecksumsNeedVerify())
    2025                 :           0 :         return true;
    2026                 :             : 
    2027                 :             :     /* Perform the actual checksum calculation. */
    2028                 :      495558 :     checksum = pg_checksum_page(page, blkno);
    2029                 :             : 
    2030                 :             :     /* See whether it matches the value from the page. */
    2031                 :      495558 :     phdr = (PageHeader) page;
    2032         [ +  + ]:      495558 :     if (phdr->pd_checksum == checksum)
    2033                 :      495530 :         return true;
    2034                 :          28 :     *expected_checksum = checksum;
    2035                 :          28 :     return false;
    2036                 :             : }
    2037                 :             : 
    2038                 :             : static int64
    2039                 :      194845 : _tarWriteHeader(bbsink *sink, const char *filename, const char *linktarget,
    2040                 :             :                 struct stat *statbuf, bool sizeonly)
    2041                 :             : {
    2042                 :             :     enum tarError rc;
    2043                 :             : 
    2044         [ +  + ]:      194845 :     if (!sizeonly)
    2045                 :             :     {
    2046                 :             :         /*
    2047                 :             :          * As of this writing, the smallest supported block size is 1kB, which
    2048                 :             :          * is twice TAR_BLOCK_SIZE. Since the buffer size is required to be a
    2049                 :             :          * multiple of BLCKSZ, it should be safe to assume that the buffer is
    2050                 :             :          * large enough to fit an entire tar block. We double-check by means
    2051                 :             :          * of these assertions.
    2052                 :             :          */
    2053                 :             :         StaticAssertDecl(TAR_BLOCK_SIZE <= BLCKSZ,
    2054                 :             :                          "BLCKSZ too small for tar block");
    2055                 :             :         Assert(sink->bbs_buffer_length >= TAR_BLOCK_SIZE);
    2056                 :             : 
    2057                 :      190070 :         rc = tarCreateHeader(sink->bbs_buffer, filename, linktarget,
    2058                 :             :                              statbuf->st_size, statbuf->st_mode,
    2059                 :             :                              statbuf->st_uid, statbuf->st_gid,
    2060                 :             :                              statbuf->st_mtime);
    2061                 :             : 
    2062   [ +  +  -  - ]:      190070 :         switch (rc)
    2063                 :             :         {
    2064                 :      190069 :             case TAR_OK:
    2065                 :      190069 :                 break;
    2066                 :           1 :             case TAR_NAME_TOO_LONG:
    2067         [ +  - ]:           1 :                 ereport(ERROR,
    2068                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2069                 :             :                          errmsg("file name too long for tar format: \"%s\"",
    2070                 :             :                                 filename)));
    2071                 :             :                 break;
    2072                 :           0 :             case TAR_SYMLINK_TOO_LONG:
    2073         [ #  # ]:           0 :                 ereport(ERROR,
    2074                 :             :                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
    2075                 :             :                          errmsg("symbolic link target too long for tar format: "
    2076                 :             :                                 "file name \"%s\", target \"%s\"",
    2077                 :             :                                 filename, linktarget)));
    2078                 :             :                 break;
    2079                 :           0 :             default:
    2080         [ #  # ]:           0 :                 elog(ERROR, "unrecognized tar error: %d", rc);
    2081                 :             :         }
    2082                 :             : 
    2083                 :      190069 :         bbsink_archive_contents(sink, TAR_BLOCK_SIZE);
    2084                 :             :     }
    2085                 :             : 
    2086                 :      194844 :     return TAR_BLOCK_SIZE;
    2087                 :             : }
    2088                 :             : 
    2089                 :             : /*
    2090                 :             :  * Pad with zero bytes out to a multiple of TAR_BLOCK_SIZE.
    2091                 :             :  */
    2092                 :             : static void
    2093                 :      185351 : _tarWritePadding(bbsink *sink, int len)
    2094                 :             : {
    2095                 :      185351 :     int         pad = tarPaddingBytesRequired(len);
    2096                 :             : 
    2097                 :             :     /*
    2098                 :             :      * As in _tarWriteHeader, it should be safe to assume that the buffer is
    2099                 :             :      * large enough that we don't need to do this in multiple chunks.
    2100                 :             :      */
    2101                 :             :     Assert(sink->bbs_buffer_length >= TAR_BLOCK_SIZE);
    2102                 :             :     Assert(pad <= TAR_BLOCK_SIZE);
    2103                 :             : 
    2104         [ +  + ]:      185351 :     if (pad > 0)
    2105                 :             :     {
    2106   [ +  -  +  +  :       32062 :         MemSet(sink->bbs_buffer, 0, pad);
          +  -  +  -  +  
                      + ]
    2107                 :       10477 :         bbsink_archive_contents(sink, pad);
    2108                 :             :     }
    2109                 :      185351 : }
    2110                 :             : 
    2111                 :             : /*
    2112                 :             :  * If the entry in statbuf is a link, then adjust statbuf to make it look like a
    2113                 :             :  * directory, so that it will be written that way.
    2114                 :             :  */
    2115                 :             : static void
    2116                 :        2840 : convert_link_to_directory(const char *pathbuf, struct stat *statbuf)
    2117                 :             : {
    2118                 :             :     /* If symlink, write it as a directory anyway */
    2119         [ +  + ]:        2840 :     if (S_ISLNK(statbuf->st_mode))
    2120                 :          66 :         statbuf->st_mode = S_IFDIR | pg_dir_create_mode;
    2121                 :        2840 : }
    2122                 :             : 
    2123                 :             : /*
    2124                 :             :  * Read some data from a file, setting a wait event and reporting any error
    2125                 :             :  * encountered.
    2126                 :             :  *
    2127                 :             :  * If partial_read_ok is false, also report an error if the number of bytes
    2128                 :             :  * read is not equal to the number of bytes requested.
    2129                 :             :  *
    2130                 :             :  * Returns the number of bytes read.
    2131                 :             :  */
    2132                 :             : static ssize_t
    2133                 :      217791 : basebackup_read_file(int fd, char *buf, size_t nbytes, off_t offset,
    2134                 :             :                      const char *filename, bool partial_read_ok)
    2135                 :             : {
    2136                 :             :     ssize_t     rc;
    2137                 :             : 
    2138                 :      217791 :     pgstat_report_wait_start(WAIT_EVENT_BASEBACKUP_READ);
    2139                 :      217791 :     rc = pg_pread(fd, buf, nbytes, offset);
    2140                 :      217791 :     pgstat_report_wait_end();
    2141                 :             : 
    2142         [ -  + ]:      217791 :     if (rc < 0)
    2143         [ #  # ]:           0 :         ereport(ERROR,
    2144                 :             :                 (errcode_for_file_access(),
    2145                 :             :                  errmsg("could not read file \"%s\": %m", filename)));
    2146   [ +  +  +  -  :      217791 :     if (!partial_read_ok && rc > 0 && rc != nbytes)
                   -  + ]
    2147         [ #  # ]:           0 :         ereport(ERROR,
    2148                 :             :                 (errcode_for_file_access(),
    2149                 :             :                  errmsg("could not read file \"%s\": read %zd of %zu",
    2150                 :             :                         filename, rc, nbytes)));
    2151                 :             : 
    2152                 :      217791 :     return rc;
    2153                 :             : }
        

Generated by: LCOV version 2.0-1