/* shred.c - overwrite files and devices to make it harder to recover data      This is the shred utility
                                                                                
   Copyright (C) 1999-2018 Free Software Foundation, Inc.                       
   Copyright (C) 1997, 1998, 1999 Colin Plumb.                                  
                                                                                
   This program is free software: you can redistribute it and/or modify         
   it under the terms of the GNU General Public License as published by         
   the Free Software Foundation, either version 3 of the License, or            
   (at your option) any later version.                                          
                                                                                
   This program is distributed in the hope that it will be useful,              
   but WITHOUT ANY WARRANTY; without even the implied warranty of               
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                
   GNU General Public License for more details.                                 
                                                                                
   You should have received a copy of the GNU General Public License            
   along with this program.  If not, see <https://www.gnu.org/licenses/>.       
                                                                                
   Written by Colin Plumb.  */                                                  The GNUv3 license
                                                                                
/*                                                                              
 * Do a more secure overwrite of given files or devices, to make it harder      
 * for even very expensive hardware probing to recover the data.                
 *                                                                              
 * Although this process is also known as "wiping", I prefer the longer         
 * name both because I think it is more evocative of what is happening and      
 * because a longer name conveys a more appropriate sense of deliberateness.    
 *                                                                              
 * For the theory behind this, see "Secure Deletion of Data from Magnetic       
 * and Solid-State Memory", on line at                                          
 * https://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.html                  
 *                                                                              
 * Just for the record, reversing one or two passes of disk overwrite           
 * is not terribly difficult with hardware help.  Hook up a good-quality        
 * digitizing oscilloscope to the output of the head preamplifier and copy      
 * the high-res digitized data to a computer for some off-line analysis.        
 * Read the "current" data and average all the pulses together to get an        
 * "average" pulse on the disk.  Subtract this average pulse from all of        
 * the actual pulses and you can clearly see the "echo" of the previous         
 * data on the disk.                                                            
 *                                                                              
 * Real hard drives have to balance the cost of the media, the head,            
 * and the read circuitry.  They use better-quality media than absolutely       
 * necessary to limit the cost of the read circuitry.  By throwing that         
 * assumption out, and the assumption that you want the data processed          
 * as fast as the hard drive can spin, you can do better.                       
 *                                                                              
 * If asked to wipe a file, this also unlinks it, renaming it in a              
 * clever way to try to leave no trace of the original filename.                
 *                                                                              
 * This was inspired by a desire to improve on some code titled:                
 * Wipe V1.0-- Overwrite and delete files.  S. 2/3/96                           
 * but I've rewritten everything here so completely that no trace of            
 * the original remains.                                                        
 *                                                                              
 * Thanks to:                                                                   
 * Bob Jenkins, for his good RNG work and patience with the FSF copyright       
 * paperwork.                                                                   
 * Jim Meyering, for his work merging this into the GNU fileutils while         
 * still letting me feel a sense of ownership and pride.  Getting me to         
 * tolerate the GNU brace style was quite a feat of diplomacy.                  
 * Paul Eggert, for lots of useful discussion and code.  I disagree with        
 * an awful lot of his suggestions, but they're disagreements worth having.     
 *                                                                              
 * Things to think about:                                                       
 * - Security: Is there any risk to the race                                    
 *   between overwriting and unlinking a file?  Will it do anything             
 *   drastically bad if told to attack a named pipe or socket?                  
 */                                                                             
                                                                                
/* The official name of this program (e.g., no 'g' prefix).  */                 
#define PROGRAM_NAME "shred"                                                    Line 72
                                                                                
#define AUTHORS proper_name ("Colin Plumb")                                     Line 74
                                                                                
#include <config.h>                                                             Provides system specific information
                                                                                
#include <getopt.h>                                                             ...!includes auto-comment...
#include <stdio.h>                                                              Provides standard I/O capability
#include <assert.h>                                                             ...!includes auto-comment...
#include <setjmp.h>                                                             ...!includes auto-comment...
#include <sys/types.h>                                                          Provides system data types
#if defined __linux__ && HAVE_SYS_MTIO_H                                        Line 83
# include <sys/mtio.h>                                                          Line 84
#endif                                                                          Line 85
                                                                                
#include "system.h"                                                             ...!includes auto-comment...
#include "argmatch.h"                                                           ...!includes auto-comment...
#include "xdectoint.h"                                                          ...!includes auto-comment...
#include "die.h"                                                                ...!includes auto-comment...
#include "error.h"                                                              ...!includes auto-comment...
#include "fcntl--.h"                                                            ...!includes auto-comment...
#include "human.h"                                                              ...!includes auto-comment...
#include "randint.h"                                                            ...!includes auto-comment...
#include "randread.h"                                                           ...!includes auto-comment...
#include "renameatu.h"                                                          ...!includes auto-comment...
#include "stat-size.h"                                                          ...!includes auto-comment...
                                                                                
/* Default number of times to overwrite.  */                                    
enum { DEFAULT_PASSES = 3 };                                                    Line 100
                                                                                
/* How many seconds to wait before checking whether to output another           
   verbose output line.  */                                                     
enum { VERBOSE_UPDATE = 5 };                                                    Line 104
                                                                                
/* Sector size and corresponding mask, for recovering after write failures.     
   The size must be a power of 2.  */                                           
enum { SECTOR_SIZE = 512 };                                                     Line 108Block 3
enum { SECTOR_MASK = SECTOR_SIZE - 1 };                                         Line 109Block 4
verify (0 < SECTOR_SIZE && (SECTOR_SIZE & SECTOR_MASK) == 0);                   Line 110
                                                                                
enum remove_method                                                              Line 112
{                                                                               
  remove_none = 0,      /* the default: only wipe data.  */                     Line 114
  remove_unlink,        /* don't obfuscate name, just unlink.  */               Line 115
  remove_wipe,          /* obfuscate name before unlink.  */                    Line 116
  remove_wipesync       /* obfuscate name, syncing each byte, before unlink.  */Line 117
};                                                                              Block 5
                                                                                
static char const *const remove_args[] =                                        Line 120
{                                                                               
  "unlink", "wipe", "wipesync", NULL                                            Line 122
};                                                                              Block 6
                                                                                
static enum remove_method const remove_methods[] =                              Line 125
{                                                                               
  remove_unlink, remove_wipe, remove_wipesync                                   Line 127
};                                                                              Block 7
                                                                                
struct Options                                                                  Line 130
{                                                                               
  bool force;  /* -f flag: chmod files if necessary */                          Line 132
  size_t n_iterations; /* -n flag: Number of iterations */                      Line 133
  off_t size;  /* -s flag: size of file */                                      Line 134
  enum remove_method remove_file; /* -u flag: remove file after shredding */    Line 135
  bool verbose;  /* -v flag: Print progress */                                  Line 136
  bool exact;  /* -x flag: Do not round up file size */                         Line 137
  bool zero_fill; /* -z flag: Add a final zero pass */                          Line 138
};                                                                              Block 8
                                                                                
/* For long options that have no equivalent short option, use a                 
   non-character as a pseudo short option, starting with CHAR_MAX + 1.  */      
enum                                                                            Line 143
{                                                                               
  RANDOM_SOURCE_OPTION = CHAR_MAX + 1                                           Line 145
};                                                                              Block 9
                                                                                
static struct option const long_opts[] =                                        Line 148
{                                                                               
  {"exact", no_argument, NULL, 'x'},                                            Line 150
  {"force", no_argument, NULL, 'f'},                                            Line 151
  {"iterations", required_argument, NULL, 'n'},                                 Line 152
  {"size", required_argument, NULL, 's'},                                       Line 153
  {"random-source", required_argument, NULL, RANDOM_SOURCE_OPTION},             Line 154
  {"remove", optional_argument, NULL, 'u'},                                     Line 155
  {"verbose", no_argument, NULL, 'v'},                                          Line 156
  {"zero", no_argument, NULL, 'z'},                                             Line 157
  {GETOPT_HELP_OPTION_DECL},                                                    Line 158
  {GETOPT_VERSION_OPTION_DECL},                                                 Line 159
  {NULL, 0, NULL, 0}                                                            Line 160
};                                                                              Block 10
                                                                                
void                                                                            Line 163
usage (int status)                                                              Line 164
{                                                                               
  if (status != EXIT_SUCCESS)                                                   Line 166
    emit_try_help ();                                                           ...!common auto-comment...
  else                                                                          Line 168
    {                                                                           
      printf (_("Usage: %s [OPTION]... FILE...\n"), program_name);              Line 170
      fputs (_("\                                                               Line 171
Overwrite the specified FILE(s) repeatedly, in order to make it harder\n\       Line 172
for even very expensive hardware probing to recover the data.\n\                Line 173
"), stdout);                                                                    Line 174
      fputs (_("\                                                               Line 175
\n\                                                                             
If FILE is -, shred standard output.\n\                                         Line 177
"), stdout);                                                                    Line 178
                                                                                
      emit_mandatory_arg_note ();                                               ...!common auto-comment...
                                                                                
      printf (_("\                                                              Line 182
  -f, --force    change permissions to allow writing if necessary\n\            Line 183
  -n, --iterations=N  overwrite N times instead of the default (%d)\n\          Line 184
      --random-source=FILE  get random bytes from FILE\n\                       Line 185
  -s, --size=N   shred this many bytes (suffixes like K, M, G accepted)\n\      Line 186
"), DEFAULT_PASSES);                                                            Line 187
      fputs (_("\                                                               Line 188
  -u             deallocate and remove file after overwriting\n\                Line 189
      --remove[=HOW]  like -u but give control on HOW to delete;  See below\n\  Line 190
  -v, --verbose  show progress\n\                                               Line 191
  -x, --exact    do not round file sizes up to the next full block;\n\          Line 192
                   this is the default for non-regular files\n\                 Line 193
  -z, --zero     add a final overwrite with zeros to hide shredding\n\          Line 194
"), stdout);                                                                    Line 195
      fputs (HELP_OPTION_DESCRIPTION, stdout);                                  Line 196
      fputs (VERSION_OPTION_DESCRIPTION, stdout);                               Line 197
      fputs (_("\                                                               Line 198
\n\                                                                             
Delete FILE(s) if --remove (-u) is specified.  The default is not to remove\n\  Line 200
the files because it is common to operate on device files like /dev/hda,\n\     Line 201
and those files usually should not be removed.\n\                               Line 202
The optional HOW parameter indicates how to remove a directory entry:\n\        Line 203
'unlink' => use a standard unlink call.\n\                                      Line 204
'wipe' => also first obfuscate bytes in the name.\n\                            Line 205
'wipesync' => also sync each obfuscated byte to disk.\n\                        Line 206
The default mode is 'wipesync', but note it can be expensive.\n\                Line 207
\n\                                                                             
"), stdout);                                                                    Line 209
      fputs (_("\                                                               Line 210
CAUTION: Note that shred relies on a very important assumption:\n\              Line 211
that the file system overwrites data in place.  This is the traditional\n\      Line 212
way to do things, but many modern file system designs do not satisfy this\n\    Line 213
assumption.  The following are examples of file systems on which shred is\n\    Line 214
not effective, or is not guaranteed to be effective in all file system modes:\n\Line 215
\n\                                                                             
"), stdout);                                                                    Line 217
      fputs (_("\                                                               Line 218
* log-structured or journaled file systems, such as those supplied with\n\      Line 219
AIX and Solaris (and JFS, ReiserFS, XFS, Ext3, etc.)\n\                         Line 220
\n\                                                                             
* file systems that write redundant data and carry on even if some writes\n\    Line 222
fail, such as RAID-based file systems\n\                                        Line 223
\n\                                                                             
* file systems that make snapshots, such as Network Appliance's NFS server\n\   Line 225
\n\                                                                             
"), stdout);                                                                    Line 227
      fputs (_("\                                                               Line 228
* file systems that cache in temporary locations, such as NFS\n\                Line 229
version 3 clients\n\                                                            Line 230
\n\                                                                             
* compressed file systems\n\                                                    Line 232
\n\                                                                             
"), stdout);                                                                    Line 234
      fputs (_("\                                                               Line 235
In the case of ext3 file systems, the above disclaimer applies\n\               Line 236
(and shred is thus of limited effectiveness) only in data=journal mode,\n\      Line 237
which journals file data in addition to just metadata.  In both the\n\          Line 238
data=ordered (default) and data=writeback modes, shred works as usual.\n\       Line 239
Ext3 journaling modes can be changed by adding the data=something option\n\     Line 240
to the mount options for a particular file system in the /etc/fstab file,\n\    Line 241
as documented in the mount man page (man mount).\n\                             Line 242
\n\                                                                             
"), stdout);                                                                    Line 244
      fputs (_("\                                                               Line 245
In addition, file system backups and remote mirrors may contain copies\n\       Line 246
of the file that cannot be removed, and that will allow a shredded file\n\      Line 247
to be recovered later.\n\                                                       Line 248
"), stdout);                                                                    Line 249
      emit_ancillary_info (PROGRAM_NAME);                                       Line 250
    }                                                                           
  exit (status);                                                                Line 252
}                                                                               Block 11
                                                                                
/*                                                                              
 * Determine if pattern type is periodic or not.                                
 */                                                                             
static bool                                                                     Line 258
periodic_pattern (int type)                                                     Line 259
{                                                                               
  if (type <= 0)                                                                Line 261
    return false;                                                               Line 262
                                                                                
  unsigned char r[3];                                                           Line 264
  unsigned int bits = type & 0xfff;                                             Line 265
                                                                                
  bits |= bits << 12;                                                           Line 267
  r[0] = (bits >> 4) & 255;                                                     Line 268
  r[1] = (bits >> 8) & 255;                                                     Line 269
  r[2] = bits & 255;                                                            Line 270
                                                                                
  return (r[0] != r[1]) || (r[0] != r[2]);                                      Line 272
}                                                                               Block 12
                                                                                
/*                                                                              
 * Fill a buffer with a fixed pattern.                                          
 *                                                                              
 * The buffer must be at least 3 bytes long, even if                            
 * size is less.  Larger sizes are filled exactly.                              
 */                                                                             
static void                                                                     Line 281
fillpattern (int type, unsigned char *r, size_t size)                           Line 282
{                                                                               
  size_t i;                                                                     Line 284
  unsigned int bits = type & 0xfff;                                             Line 285
                                                                                
  bits |= bits << 12;                                                           Line 287
  r[0] = (bits >> 4) & 255;                                                     Line 288
  r[1] = (bits >> 8) & 255;                                                     Line 289
  r[2] = bits & 255;                                                            Line 290
  for (i = 3; i <= size / 2; i *= 2)                                            Line 291
    memcpy (r + i, r, i);                                                       Line 292
  if (i < size)                                                                 Line 293
    memcpy (r + i, r, size - i);                                                Line 294
                                                                                
  /* Invert the first bit of every sector. */                                   
  if (type & 0x1000)                                                            Line 297
    for (i = 0; i < size; i += SECTOR_SIZE)                                     Line 298
      r[i] ^= 0x80;                                                             Line 299
}                                                                               Block 13
                                                                                
/*                                                                              
 * Generate a 6-character (+ nul) pass name string                              
 * FIXME: allow translation of "random".                                        
 */                                                                             
#define PASS_NAME_SIZE 7                                                        Line 306
static void                                                                     Line 307
passname (unsigned char const *data, char name[PASS_NAME_SIZE])                 Line 308
{                                                                               
  if (data)                                                                     Line 310
    sprintf (name, "%02x%02x%02x", data[0], data[1], data[2]);                  Line 311
  else                                                                          Line 312
    memcpy (name, "random", PASS_NAME_SIZE);                                    Line 313
}                                                                               Block 14
                                                                                
/* Return true when it's ok to ignore an fsync or fdatasync                     
   failure that set errno to ERRNO_VAL.  */                                     
static bool                                                                     Line 318
ignorable_sync_errno (int errno_val)                                            Line 319
{                                                                               
  return (errno_val == EINVAL                                                   Line 321
          || errno_val == EBADF                                                 Line 322
          /* HP-UX does this */                                                 
          || errno_val == EISDIR);                                              Line 324
}                                                                               Block 15
                                                                                
/* Request that all data for FD be transferred to the corresponding             
   storage device.  QNAME is the file name (quoted for colons).                 
   Report any errors found.  Return 0 on success, -1                            
   (setting errno) on failure.  It is not an error if fdatasync and/or          
   fsync is not supported for this file, or if the file is not a                
   writable file descriptor.  */                                                
static int                                                                      Line 333
dosync (int fd, char const *qname)                                              Line 334...!syscalls auto-comment...
{                                                                               
  int err;                                                                      Line 336
                                                                                
#if HAVE_FDATASYNC                                                              Line 338
  if (fdatasync (fd) == 0)                                                      Line 339...!syscalls auto-comment...
    return 0;                                                                   Line 340
  err = errno;                                                                  Line 341
  if ( ! ignorable_sync_errno (err))                                            Line 342
    {                                                                           
      error (0, err, _("%s: fdatasync failed"), qname);                         Line 344
      errno = err;                                                              Line 345
      return -1;                                                                Line 346
    }                                                                           
#endif                                                                          Line 348
                                                                                
  if (fsync (fd) == 0)                                                          Line 350...!syscalls auto-comment...
    return 0;                                                                   Line 351
  err = errno;                                                                  Line 352
  if ( ! ignorable_sync_errno (err))                                            Line 353
    {                                                                           
      error (0, err, _("%s: fsync failed"), qname);                             Line 355
      errno = err;                                                              Line 356
      return -1;                                                                Line 357
    }                                                                           
                                                                                
  sync ();                                                                      Line 360...!syscalls auto-comment...
  return 0;                                                                     Line 361
}                                                                               Block 16
                                                                                
/* Turn on or off direct I/O mode for file descriptor FD, if possible.          
   Try to turn it on if ENABLE is true.  Otherwise, try to turn it off.  */     
static void                                                                     Line 366
direct_mode (int fd, bool enable)                                               Line 367
{                                                                               
  if (O_DIRECT)                                                                 Line 369
    {                                                                           
      int fd_flags = fcntl (fd, F_GETFL);                                       Line 371...!syscalls auto-comment...
      if (0 < fd_flags)                                                         Line 372
        {                                                                       
          int new_flags = (enable                                               Line 374
                           ? (fd_flags | O_DIRECT)                              Line 375
                           : (fd_flags & ~O_DIRECT));                           Line 376
          if (new_flags != fd_flags)                                            Line 377
            fcntl (fd, F_SETFL, new_flags);                                     Line 378...!syscalls auto-comment...
        }                                                                       
    }                                                                           
                                                                                
#if HAVE_DIRECTIO && defined DIRECTIO_ON && defined DIRECTIO_OFF                Line 382
  /* This is Solaris-specific.  */                                              
  directio (fd, enable ? DIRECTIO_ON : DIRECTIO_OFF);                           Line 384
#endif                                                                          Line 385
}                                                                               Block 17
                                                                                
/* Rewind FD; its status is ST.  */                                             
static bool                                                                     Line 389
dorewind (int fd, struct stat const *st)                                        Line 390
{                                                                               
  if (S_ISCHR (st->st_mode))                                                    Line 392
    {                                                                           
#if defined __linux__ && HAVE_SYS_MTIO_H                                        Line 394
      /* In the Linux kernel, lseek does not work on tape devices; it           
         returns a randomish value instead.  Try the low-level tape             
         rewind operation first.  */                                            
      struct mtop op;                                                           Line 398
      op.mt_op = MTREW;                                                         Line 399
      op.mt_count = 1;                                                          Line 400
      if (ioctl (fd, MTIOCTOP, &op) == 0)                                       Line 401...!syscalls auto-comment...
        return true;                                                            Line 402
#endif                                                                          Line 403
    }                                                                           
  off_t offset = lseek (fd, 0, SEEK_SET);                                       Line 405
  if (0 < offset)                                                               Line 406
    errno = EINVAL;                                                             Line 407
  return offset == 0;                                                           Line 408
}                                                                               Block 18
                                                                                
/* By convention, negative sizes represent unknown values.  */                  
                                                                                
static bool                                                                     Line 413
known (off_t size)                                                              Line 414
{                                                                               
  return 0 <= size;                                                             Line 416
}                                                                               Block 19
                                                                                
/*                                                                              
 * Do pass number K of N, writing *SIZEP bytes of the given pattern TYPE        
 * to the file descriptor FD.  K and N are passed in only for verbose           
 * progress message purposes.  If N == 0, no progress messages are printed.     
 *                                                                              
 * If *SIZEP == -1, the size is unknown, and it will be filled in as soon       
 * as writing fails with ENOSPC.                                                
 *                                                                              
 * Return 1 on write error, -1 on other error, 0 on success.                    
 */                                                                             
static int                                                                      Line 429
dopass (int fd, struct stat const *st, char const *qname, off_t *sizep,         Line 430
        int type, struct randread_source *s,                                    Line 431
        unsigned long int k, unsigned long int n)                               Line 432
{                                                                               
  off_t size = *sizep;                                                          Line 434
  off_t offset;   /* Current file position */                                   Line 435
  time_t thresh IF_LINT ( = 0); /* Time to maybe print next status update */    Line 436
  time_t now = 0;  /* Current time */                                           Line 437
  size_t lim;   /* Amount of data to try writing */                             Line 438
  size_t soff;   /* Offset into buffer for next write */                        Line 439
  ssize_t ssize;  /* Return value from write */                                 Line 440
                                                                                
  /* Fill pattern buffer.  Aligning it to a page so we can do direct I/O.  */   
  size_t page_size = getpagesize ();                                            Line 443
#define PERIODIC_OUTPUT_SIZE (60 * 1024)                                        Line 444
#define NONPERIODIC_OUTPUT_SIZE (64 * 1024)                                     Line 445
  verify (PERIODIC_OUTPUT_SIZE % 3 == 0);                                       Line 446
  size_t output_size = periodic_pattern (type)                                  Line 447
                       ? PERIODIC_OUTPUT_SIZE : NONPERIODIC_OUTPUT_SIZE;        Line 448
#define PAGE_ALIGN_SLOP (page_size - 1)                /* So directio works */  Line 449
#define FILLPATTERN_SIZE (((output_size + 2) / 3) * 3) /* Multiple of 3 */      Line 450
#define PATTERNBUF_SIZE (PAGE_ALIGN_SLOP + FILLPATTERN_SIZE)                    Line 451
  void *fill_pattern_mem = xmalloc (PATTERNBUF_SIZE);                           Line 452
  unsigned char *pbuf = ptr_align (fill_pattern_mem, page_size);                Line 453
                                                                                
  char pass_string[PASS_NAME_SIZE]; /* Name of current pass */                  Line 455
  bool write_error = false;                                                     Line 456
  bool other_error = false;                                                     Line 457
                                                                                
  /* Printable previous offset into the file */                                 
  char previous_offset_buf[LONGEST_HUMAN_READABLE + 1];                         Line 460
  char const *previous_human_offset IF_LINT ( = 0);                             Line 461
                                                                                
  /* As a performance tweak, avoid direct I/O for small sizes,                  
     as it's just a performance rather then security consideration,             
     and direct I/O can often be unsupported for small non aligned sizes.  */   
  bool try_without_directio = 0 < size && size < output_size;                   Line 466
  if (! try_without_directio)                                                   Line 467
    direct_mode (fd, true);                                                     Line 468
                                                                                
  if (! dorewind (fd, st))                                                      Line 470
    {                                                                           
      error (0, errno, _("%s: cannot rewind"), qname);                          Line 472
      other_error = true;                                                       Line 473
      goto free_pattern_mem;                                                    Line 474
    }                                                                           
                                                                                
  /* Constant fill patterns need only be set up once. */                        
  if (type >= 0)                                                                Line 478
    {                                                                           
      lim = known (size) && size < FILLPATTERN_SIZE ? size : FILLPATTERN_SIZE;  Line 480
      fillpattern (type, pbuf, lim);                                            Line 481
      passname (pbuf, pass_string);                                             Line 482
    }                                                                           
  else                                                                          Line 484
    {                                                                           
      passname (0, pass_string);                                                Line 486
    }                                                                           
                                                                                
  /* Set position if first status update */                                     
  if (n)                                                                        Line 490
    {                                                                           
      error (0, 0, _("%s: pass %lu/%lu (%s)..."), qname, k, n, pass_string);    Line 492
      thresh = time (NULL) + VERBOSE_UPDATE;                                    Line 493
      previous_human_offset = "";                                               Line 494
    }                                                                           
                                                                                
  offset = 0;                                                                   Line 497
  while (true)                                                                  Line 498
    {                                                                           
      /* How much to write this time? */                                        
      lim = output_size;                                                        Line 501
      if (known (size) && size - offset < output_size)                          Line 502
        {                                                                       
          if (size < offset)                                                    Line 504
            break;                                                              Line 505
          lim = size - offset;                                                  Line 506
          if (!lim)                                                             Line 507
            break;                                                              Line 508
        }                                                                       
      if (type < 0)                                                             Line 510
        randread (s, pbuf, lim);                                                Line 511...!syscalls auto-comment...
      /* Loop to retry partial writes. */                                       
      for (soff = 0; soff < lim; soff += ssize)                                 Line 513
        {                                                                       
          ssize = write (fd, pbuf + soff, lim - soff);                          Line 515...!syscalls auto-comment...
          if (0 < ssize)                                                        Line 516
            assume (ssize <= lim - soff);                                       Line 517
          else                                                                  Line 518
            {                                                                   
              if (! known (size) && (ssize == 0 || errno == ENOSPC))            Line 520
                {                                                               
                  /* We have found the end of the file.  */                     
                  if (soff <= OFF_T_MAX - offset)                               Line 523
                    *sizep = size = offset + soff;                              Line 524
                  break;                                                        Line 525
                }                                                               
              else                                                              Line 527
                {                                                               
                  int errnum = errno;                                           Line 529
                  char buf[INT_BUFSIZE_BOUND (uintmax_t)];                      Line 530
                                                                                
                  /* Retry without direct I/O since this may not be supported   
                     at all on some (file) systems, or with the current size.   
                     I.e., a specified --size that is not aligned, or when      
                     dealing with slop at the end of a file with --exact.  */   
                  if (! try_without_directio && errno == EINVAL)                Line 536
                    {                                                           
                      direct_mode (fd, false);                                  Line 538
                      ssize = 0;                                                Line 539
                      try_without_directio = true;                              Line 540
                      continue;                                                 Line 541
                    }                                                           
                  error (0, errnum, _("%s: error writing at offset %s"),        Line 543
                         qname, umaxtostr (offset + soff, buf));                Line 544
                                                                                
                  /* 'shred' is often used on bad media, before throwing it     
                     out.  Thus, it shouldn't give up on bad blocks.  This      
                     code works because lim is always a multiple of             
                     SECTOR_SIZE, except at the end.  This size constraint      
                     also enables direct I/O on some (file) systems.  */        
                  verify (PERIODIC_OUTPUT_SIZE % SECTOR_SIZE == 0);             Line 551
                  verify (NONPERIODIC_OUTPUT_SIZE % SECTOR_SIZE == 0);          Line 552
                  if (errnum == EIO && known (size)                             Line 553
                      && (soff | SECTOR_MASK) < lim)                            Line 554
                    {                                                           
                      size_t soff1 = (soff | SECTOR_MASK) + 1;                  Line 556
                      if (lseek (fd, offset + soff1, SEEK_SET) != -1)           Line 557
                        {                                                       
                          /* Arrange to skip this block. */                     
                          ssize = soff1 - soff;                                 Line 560
                          write_error = true;                                   Line 561
                          continue;                                             Line 562
                        }                                                       
                      error (0, errno, _("%s: lseek failed"), qname);           Line 564
                    }                                                           
                  other_error = true;                                           Line 566
                  goto free_pattern_mem;                                        Line 567
                }                                                               
            }                                                                   
        }                                                                       
                                                                                
      /* Okay, we have written "soff" bytes. */                                 
                                                                                
      if (OFF_T_MAX - offset < soff)                                            Line 574
        {                                                                       
          error (0, 0, _("%s: file too large"), qname);                         Line 576
          other_error = true;                                                   Line 577
          goto free_pattern_mem;                                                Line 578
        }                                                                       
                                                                                
      offset += soff;                                                           Line 581
                                                                                
      bool done = offset == size;                                               Line 583
                                                                                
      /* Time to print progress? */                                             
      if (n && ((done && *previous_human_offset)                                Line 586
                || thresh <= (now = time (NULL))))                              Line 587
        {                                                                       
          char offset_buf[LONGEST_HUMAN_READABLE + 1];                          Line 589
          char size_buf[LONGEST_HUMAN_READABLE + 1];                            Line 590
          int human_progress_opts = (human_autoscale | human_SI                 Line 591
                                     | human_base_1024 | human_B);              Line 592
          char const *human_offset                                              Line 593
            = human_readable (offset, offset_buf,                               Line 594
                              human_floor | human_progress_opts, 1, 1);         Line 595
                                                                                
          if (done || !STREQ (previous_human_offset, human_offset))             Line 597
            {                                                                   
              if (! known (size))                                               Line 599
                error (0, 0, _("%s: pass %lu/%lu (%s)...%s"),                   Line 600
                       qname, k, n, pass_string, human_offset);                 Line 601
              else                                                              Line 602
                {                                                               
                  uintmax_t off = offset;                                       Line 604
                  int percent = (size == 0                                      Line 605
                                 ? 100                                          Line 606
                                 : (off <= TYPE_MAXIMUM (uintmax_t) / 100       Line 607
                                    ? off * 100 / size                          Line 608
                                    : off / (size / 100)));                     Line 609
                  char const *human_size                                        Line 610
                    = human_readable (size, size_buf,                           Line 611
                                      human_ceiling | human_progress_opts,      Line 612
                                      1, 1);                                    Line 613
                  if (done)                                                     Line 614
                    human_offset = human_size;                                  Line 615
                  error (0, 0, _("%s: pass %lu/%lu (%s)...%s/%s %d%%"),         Line 616
                         qname, k, n, pass_string, human_offset, human_size,    Line 617
                         percent);                                              Line 618
                }                                                               
                                                                                
              strcpy (previous_offset_buf, human_offset);                       Line 621
              previous_human_offset = previous_offset_buf;                      Line 622
              thresh = now + VERBOSE_UPDATE;                                    Line 623
                                                                                
              /*                                                                
               * Force periodic syncs to keep displayed progress accurate       
               * FIXME: Should these be present even if -v is not enabled,      
               * to keep the buffer cache from filling with dirty pages?        
               * It's a common problem with programs that do lots of writes,    
               * like mkfs.                                                     
               */                                                               
              if (dosync (fd, qname) != 0)                                      Line 632...!syscalls auto-comment...
                {                                                               
                  if (errno != EIO)                                             Line 634
                    {                                                           
                      other_error = true;                                       Line 636
                      goto free_pattern_mem;                                    Line 637
                    }                                                           
                  write_error = true;                                           Line 639
                }                                                               
            }                                                                   
        }                                                                       
    }                                                                           
                                                                                
  /* Force what we just wrote to hit the media. */                              
  if (dosync (fd, qname) != 0)                                                  Line 646...!syscalls auto-comment...
    {                                                                           
      if (errno != EIO)                                                         Line 648
        {                                                                       
          other_error = true;                                                   Line 650
          goto free_pattern_mem;                                                Line 651
        }                                                                       
      write_error = true;                                                       Line 653
    }                                                                           
                                                                                
free_pattern_mem:                                                               Line 656
  free (fill_pattern_mem);                                                      Line 657
                                                                                
  return other_error ? -1 : write_error;                                        Line 659
}                                                                               Block 20
                                                                                
/*                                                                              
 * The passes start and end with a random pass, and the passes in between       
 * are done in random order.  The idea is to deprive someone trying to          
 * reverse the process of knowledge of the overwrite patterns, so they          
 * have the additional step of figuring out what was done to the disk           
 * before they can try to reverse or cancel it.                                 
 *                                                                              
 * First, all possible 1-bit patterns.  There are two of them.                  
 * Then, all possible 2-bit patterns.  There are four, but the two              
 * which are also 1-bit patterns can be omitted.                                
 * Then, all possible 3-bit patterns.  Likewise, 8-2 = 6.                       
 * Then, all possible 4-bit patterns.  16-4 = 12.                               
 *                                                                              
 * The basic passes are:                                                        
 * 1-bit: 0x000, 0xFFF                                                          
 * 2-bit: 0x555, 0xAAA                                                          
 * 3-bit: 0x249, 0x492, 0x924, 0x6DB, 0xB6D, 0xDB6 (+ 1-bit)                    
 *        100100100100         110110110110                                     
 *           9   2   4            D   B   6                                     
 * 4-bit: 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,                             
 *        0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE (+ 1-bit, 2-bit)             
 * Adding three random passes at the beginning, middle and end                  
 * produces the default 25-pass structure.                                      
 *                                                                              
 * The next extension would be to 5-bit and 6-bit patterns.                     
 * There are 30 uncovered 5-bit patterns and 64-8-2 = 46 uncovered              
 * 6-bit patterns, so they would increase the time required                     
 * significantly.  4-bit patterns are enough for most purposes.                 
 *                                                                              
 * The main gotcha is that this would require a trickier encoding,              
 * since lcm(2,3,4) = 12 bits is easy to fit into an int, but                   
 * lcm(2,3,4,5) = 60 bits is not.                                               
 *                                                                              
 * One extension that is included is to complement the first bit in each        
 * 512-byte block, to alter the phase of the encoded data in the more           
 * complex encodings.  This doesn't apply to MFM, so the 1-bit patterns         
 * are considered part of the 3-bit ones and the 2-bit patterns are             
 * considered part of the 4-bit patterns.                                       
 *                                                                              
 *                                                                              
 * How does the generalization to variable numbers of passes work?              
 *                                                                              
 * Here's how...                                                                
 * Have an ordered list of groups of passes.  Each group is a set.              
 * Take as many groups as will fit, plus a random subset of the                 
 * last partial group, and place them into the passes list.                     
 * Then shuffle the passes list into random order and use that.                 
 *                                                                              
 * One extra detail: if we can't include a large enough fraction of the         
 * last group to be interesting, then just substitute random passes.            
 *                                                                              
 * If you want more passes than the entire list of groups can                   
 * provide, just start repeating from the beginning of the list.                
 */                                                                             
static int const                                                                Line 716
  patterns[] =                                                                  Line 717
{                                                                               
  -2,    /* 2 random passes */                                                  Line 719
  2, 0x000, 0xFFF,  /* 1-bit */                                                 Line 720
  2, 0x555, 0xAAA,  /* 2-bit */                                                 Line 721
  -1,    /* 1 random pass */                                                    Line 722
  6, 0x249, 0x492, 0x6DB, 0x924, 0xB6D, 0xDB6, /* 3-bit */                      Line 723
  12, 0x111, 0x222, 0x333, 0x444, 0x666, 0x777,                                 Line 724
  0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE, /* 4-bit */                         Line 725
  -1,    /* 1 random pass */                                                    Line 726
        /* The following patterns have the first bit per block flipped */       
  8, 0x1000, 0x1249, 0x1492, 0x16DB, 0x1924, 0x1B6D, 0x1DB6, 0x1FFF,            Line 728
  14, 0x1111, 0x1222, 0x1333, 0x1444, 0x1555, 0x1666, 0x1777,                   Line 729
  0x1888, 0x1999, 0x1AAA, 0x1BBB, 0x1CCC, 0x1DDD, 0x1EEE,                       Line 730
  -1,    /* 1 random pass */                                                    Line 731
  0    /* End */                                                                Line 732
};                                                                              Block 21
                                                                                
/*                                                                              
 * Generate a random wiping pass pattern with num passes.                       
 * This is a two-stage process.  First, the passes to include                   
 * are chosen, and then they are shuffled into the desired                      
 * order.                                                                       
 */                                                                             
static void                                                                     Line 741
genpattern (int *dest, size_t num, struct randint_source *s)                    Line 742
{                                                                               
  size_t randpasses;                                                            Line 744
  int const *p;                                                                 Line 745
  int *d;                                                                       Line 746
  size_t n;                                                                     Line 747
  size_t accum, top, swap;                                                      Line 748
  int k;                                                                        Line 749
                                                                                
  if (!num)                                                                     Line 751
    return;                                                                     Line 752
                                                                                
  /* Stage 1: choose the passes to use */                                       
  p = patterns;                                                                 Line 755
  randpasses = 0;                                                               Line 756
  d = dest;   /* Destination for generated pass list */                         Line 757
  n = num;   /* Passes remaining to fill */                                     Line 758
                                                                                
  while (true)                                                                  Line 760
    {                                                                           
      k = *p++;   /* Block descriptor word */                                   Line 762
      if (!k)                                                                   Line 763
        {   /* Loop back to the beginning */                                    Line 764
          p = patterns;                                                         Line 765
        }                                                                       
      else if (k < 0)                                                           Line 767
        {   /* -k random passes */                                              Line 768
          k = -k;                                                               Line 769
          if ((size_t) k >= n)                                                  Line 770
            {                                                                   
              randpasses += n;                                                  Line 772
              break;                                                            Line 773
            }                                                                   
          randpasses += k;                                                      Line 775
          n -= k;                                                               Line 776
        }                                                                       
      else if ((size_t) k <= n)                                                 Line 778
        {   /* Full block of patterns */                                        Line 779
          memcpy (d, p, k * sizeof (int));                                      Line 780
          p += k;                                                               Line 781
          d += k;                                                               Line 782
          n -= k;                                                               Line 783
        }                                                                       
      else if (n < 2 || 3 * n < (size_t) k)                                     Line 785
        {   /* Finish with random */                                            Line 786
          randpasses += n;                                                      Line 787
          break;                                                                Line 788
        }                                                                       
      else                                                                      Line 790
        {   /* Pad out with n of the k available */                             Line 791
          do                                                                    
            {                                                                   
              if (n == (size_t) k || randint_choose (s, k) < n)                 Line 794
                {                                                               
                  *d++ = *p;                                                    Line 796
                  n--;                                                          Line 797
                }                                                               
              p++;                                                              Line 799
              k--;                                                              Line 800
            }                                                                   
          while (n);                                                            Line 802
          break;                                                                Line 803
        }                                                                       
    }                                                                           
  top = num - randpasses; /* Top of initialized data */                         Line 806
  /* assert (d == dest+top); */                                                 
                                                                                
  /*                                                                            
   * We now have fixed patterns in the dest buffer up to                        
   * "top", and we need to scramble them, with "randpasses"                     
   * random passes evenly spaced among them.                                    
   *                                                                            
   * We want one at the beginning, one at the end, and                          
   * evenly spaced in between.  To do this, we basically                        
   * use Bresenham's line draw (a.k.a DDA) algorithm                            
   * to draw a line with slope (randpasses-1)/(num-1).                          
   * (We use a positive accumulator and count down to                           
   * do this.)                                                                  
   *                                                                            
   * So for each desired output value, we do the following:                     
   * - If it should be a random pass, copy the pass type                        
   *   to top++, out of the way of the other passes, and                        
   *   set the current pass to -1 (random).                                     
   * - If it should be a normal pattern pass, choose an                         
   *   entry at random between here and top-1 (inclusive)                       
   *   and swap the current entry with that one.                                
   */                                                                           
  randpasses--;   /* To speed up later math */                                  Line 829
  accum = randpasses;  /* Bresenham DDA accumulator */                          Line 830
  for (n = 0; n < num; n++)                                                     Line 831
    {                                                                           
      if (accum <= randpasses)                                                  Line 833
        {                                                                       
          accum += num - 1;                                                     Line 835
          dest[top++] = dest[n];                                                Line 836
          dest[n] = -1;                                                         Line 837
        }                                                                       
      else                                                                      Line 839
        {                                                                       
          swap = n + randint_choose (s, top - n);                               Line 841
          k = dest[n];                                                          Line 842
          dest[n] = dest[swap];                                                 Line 843
          dest[swap] = k;                                                       Line 844
        }                                                                       
      accum -= randpasses;                                                      Line 846
    }                                                                           
  /* assert (top == num); */                                                    
}                                                                               Block 22
                                                                                
/*                                                                              
 * The core routine to actually do the work.  This overwrites the first         
 * size bytes of the given fd.  Return true if successful.                      
 */                                                                             
static bool                                                                     Line 855
do_wipefd (int fd, char const *qname, struct randint_source *s,                 Line 856
           struct Options const *flags)                                         Line 857
{                                                                               
  size_t i;                                                                     Line 859
  struct stat st;                                                               Line 860
  off_t size;  /* Size to write, size to read */                                Line 861
  off_t i_size = 0; /* For small files, initial size to overwrite inode */      Line 862
  unsigned long int n; /* Number of passes for printing purposes */             Line 863
  int *passarray;                                                               Line 864
  bool ok = true;                                                               Line 865
  struct randread_source *rs;                                                   Line 866
                                                                                
  n = 0;  /* dopass takes n == 0 to mean "don't print progress" */              Line 868
  if (flags->verbose)                                                           Line 869
    n = flags->n_iterations + flags->zero_fill;                                 Line 870
                                                                                
  if (fstat (fd, &st))                                                          Line 872...!syscalls auto-comment......!syscalls auto-comment...
    {                                                                           
      error (0, errno, _("%s: fstat failed"), qname);                           Line 874
      return false;                                                             Line 875
    }                                                                           
                                                                                
  /* If we know that we can't possibly shred the file, give up now.             
     Otherwise, we may go into an infinite loop writing data before we          
     find that we can't rewind the device.  */                                  
  if ((S_ISCHR (st.st_mode) && isatty (fd))                                     Line 881
      || S_ISFIFO (st.st_mode)                                                  Line 882
      || S_ISSOCK (st.st_mode))                                                 Line 883
    {                                                                           
      error (0, 0, _("%s: invalid file type"), qname);                          Line 885
      return false;                                                             Line 886
    }                                                                           
  else if (S_ISREG (st.st_mode) && st.st_size < 0)                              Line 888
    {                                                                           
      error (0, 0, _("%s: file has negative size"), qname);                     Line 890
      return false;                                                             Line 891
    }                                                                           
                                                                                
  /* Allocate pass array */                                                     
  passarray = xnmalloc (flags->n_iterations, sizeof *passarray);                Line 895
                                                                                
  size = flags->size;                                                           Line 897
  if (size == -1)                                                               Line 898
    {                                                                           
      if (S_ISREG (st.st_mode))                                                 Line 900
        {                                                                       
          size = st.st_size;                                                    Line 902
                                                                                
          if (! flags->exact)                                                   Line 904
            {                                                                   
              /* Round up to the nearest block size to clear slack space.  */   
              off_t remainder = size % ST_BLKSIZE (st);                         Line 907
              if (size && size < ST_BLKSIZE (st))                               Line 908
                i_size = size;                                                  Line 909
              if (remainder != 0)                                               Line 910
                {                                                               
                  off_t size_incr = ST_BLKSIZE (st) - remainder;                Line 912
                  size += MIN (size_incr, OFF_T_MAX - size);                    Line 913
                }                                                               
            }                                                                   
        }                                                                       
      else                                                                      Line 917
        {                                                                       
          /* The behavior of lseek is unspecified, but in practice if           
             it returns a positive number that's the size of this               
             device.  */                                                        
          size = lseek (fd, 0, SEEK_END);                                       Line 922
          if (size <= 0)                                                        Line 923
            {                                                                   
              /* We are unable to determine the length, up front.               
                 Let dopass do that as part of its first iteration.  */         
              size = -1;                                                        Line 927
            }                                                                   
        }                                                                       
    }                                                                           
  else if (S_ISREG (st.st_mode)                                                 Line 931
           && st.st_size < MIN (ST_BLKSIZE (st), size))                         Line 932
    i_size = st.st_size;                                                        Line 933
                                                                                
  /* Schedule the passes in random order. */                                    
  genpattern (passarray, flags->n_iterations, s);                               Line 936
                                                                                
  rs = randint_get_source (s);                                                  Line 938
                                                                                
  while (true)                                                                  Line 940
    {                                                                           
      off_t pass_size;                                                          Line 942
      unsigned long int pn = n;                                                 Line 943
                                                                                
      if (i_size)                                                               Line 945
        {                                                                       
          pass_size = i_size;                                                   Line 947
          i_size = 0;                                                           Line 948
          pn = 0;                                                               Line 949
        }                                                                       
      else if (size)                                                            Line 951
        {                                                                       
          pass_size = size;                                                     Line 953
          size = 0;                                                             Line 954
        }                                                                       
      /* TODO: consider handling tail packing by                                
         writing the tail padding as a separate pass,                           
         (that would not rewind).  */                                           
      else                                                                      Line 959
        break;                                                                  Line 960
                                                                                
      for (i = 0; i < flags->n_iterations + flags->zero_fill; i++)              Line 962
        {                                                                       
          int err = 0;                                                          Line 964
          int type = i < flags->n_iterations ? passarray[i] : 0;                Line 965
                                                                                
          err = dopass (fd, &st, qname, &pass_size, type, rs, i + 1, pn);       Line 967
                                                                                
          if (err)                                                              Line 969
            {                                                                   
              ok = false;                                                       Line 971
              if (err < 0)                                                      Line 972
                goto wipefd_out;                                                Line 973
            }                                                                   
        }                                                                       
    }                                                                           
                                                                                
  /* Now deallocate the data.  The effect of ftruncate on                       
     non-regular files is unspecified, so don't worry about any                 
     errors reported for them.  */                                              
  if (flags->remove_file && ftruncate (fd, 0) != 0                              Line 981...!syscalls auto-comment...
      && S_ISREG (st.st_mode))                                                  Line 982
    {                                                                           
      error (0, errno, _("%s: error truncating"), qname);                       Line 984
      ok = false;                                                               Line 985
      goto wipefd_out;                                                          Line 986
    }                                                                           
                                                                                
wipefd_out:                                                                     Line 989
  free (passarray);                                                             Line 990
  return ok;                                                                    Line 991
}                                                                               Block 23
                                                                                
/* A wrapper with a little more checking for fds on the command line */         
static bool                                                                     Line 995
wipefd (int fd, char const *qname, struct randint_source *s,                    Line 996
        struct Options const *flags)                                            Line 997
{                                                                               
  int fd_flags = fcntl (fd, F_GETFL);                                           Line 999...!syscalls auto-comment...
                                                                                
  if (fd_flags < 0)                                                             Line 1001
    {                                                                           
      error (0, errno, _("%s: fcntl failed"), qname);                           Line 1003
      return false;                                                             Line 1004
    }                                                                           
  if (fd_flags & O_APPEND)                                                      Line 1006
    {                                                                           
      error (0, 0, _("%s: cannot shred append-only file descriptor"), qname);   Line 1008
      return false;                                                             Line 1009
    }                                                                           
  return do_wipefd (fd, qname, s, flags);                                       Line 1011
}                                                                               Block 24
                                                                                
/* --- Name-wiping code --- */                                                  
                                                                                
/* Characters allowed in a file name - a safe universal set.  */                
static char const nameset[] =                                                   Line 1017
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_.";             Line 1018
                                                                                
/* Increment NAME (with LEN bytes).  NAME must be a big-endian base N           
   number with the digits taken from nameset.  Return true if successful.       
   Otherwise, (because NAME already has the greatest possible value)            
   return false.  */                                                            
                                                                                
static bool                                                                     Line 1025
incname (char *name, size_t len)                                                Line 1026
{                                                                               
  while (len--)                                                                 Line 1028
    {                                                                           
      char const *p = strchr (nameset, name[len]);                              Line 1030
                                                                                
      /* Given that NAME is composed of bytes from NAMESET,                     
         P will never be NULL here.  */                                         
      assert (p);                                                               Line 1034
                                                                                
      /* If this character has a successor, use it.  */                         
      if (p[1])                                                                 Line 1037
        {                                                                       
          name[len] = p[1];                                                     Line 1039
          return true;                                                          Line 1040
        }                                                                       
                                                                                
      /* Otherwise, set this digit to 0 and increment the prefix.  */           
      name[len] = nameset[0];                                                   Line 1044
    }                                                                           
                                                                                
  return false;                                                                 Line 1047
}                                                                               Block 25
                                                                                
/*                                                                              
 * Repeatedly rename a file with shorter and shorter names,                     
 * to obliterate all traces of the file name (and length) on any system         
 * that adds a trailing delimiter to on-disk file names and reuses              
 * the same directory slot.  Finally, unlink it.                                
 * The passed-in filename is modified in place to the new filename.             
 * (Which is unlinked if this function succeeds, but is still present if        
 * it fails for some reason.)                                                   
 *                                                                              
 * The main loop is written carefully to not get stuck if all possible          
 * names of a given length are occupied.  It counts down the length from        
 * the original to 0.  While the length is non-zero, it tries to find an        
 * unused file name of the given length.  It continues until either the         
 * name is available and the rename succeeds, or it runs out of names           
 * to try (incname wraps and returns 1).  Finally, it unlinks the file.         
 *                                                                              
 * The unlink is Unix-specific, as ANSI-standard remove has more                
 * portability problems with C libraries making it "safe".  rename              
 * is ANSI-standard.                                                            
 *                                                                              
 * To force the directory data out, we try to open the directory and            
 * invoke fdatasync and/or fsync on it.  This is non-standard, so don't         
 * insist that it works: just fall back to a global sync in that case.          
 * This is fairly significantly Unix-specific.  Of course, on any               
 * file system with synchronous metadata updates, this is unnecessary.          
 */                                                                             
static bool                                                                     Line 1076
wipename (char *oldname, char const *qoldname, struct Options const *flags)     Line 1077
{                                                                               
  char *newname = xstrdup (oldname);                                            Line 1079
  char *base = last_component (newname);                                        Line 1080
  char *dir = dir_name (newname);                                               Line 1081
  char *qdir = xstrdup (quotef (dir));                                          Line 1082
  bool first = true;                                                            Line 1083
  bool ok = true;                                                               Line 1084
  int dir_fd = -1;                                                              Line 1085
                                                                                
  if (flags->remove_file == remove_wipesync)                                    Line 1087
    dir_fd = open (dir, O_RDONLY | O_DIRECTORY | O_NOCTTY | O_NONBLOCK);        Line 1088...!syscalls auto-comment...
                                                                                
  if (flags->verbose)                                                           Line 1090
    error (0, 0, _("%s: removing"), qoldname);                                  Line 1091
                                                                                
  if (flags->remove_file != remove_unlink)                                      Line 1093
    for (size_t len = base_len (base); len != 0; len--)                         Line 1094
      {                                                                         
        memset (base, nameset[0], len);                                         Line 1096
        base[len] = 0;                                                          Line 1097
        bool rename_ok;                                                         Line 1098
        while (! (rename_ok = (renameatu (AT_FDCWD, oldname, AT_FDCWD, newname, Line 1099
                                          RENAME_NOREPLACE)                     Line 1100
                               == 0))                                           Line 1101
               && errno == EEXIST && incname (base, len))                       Line 1102
          continue;                                                             Line 1103
        if (rename_ok)                                                          Line 1104
          {                                                                     
            if (0 <= dir_fd && dosync (dir_fd, qdir) != 0)                      Line 1106...!syscalls auto-comment...
              ok = false;                                                       Line 1107
            if (flags->verbose)                                                 Line 1108
              {                                                                 
                /* People seem to understand this better than talking           
                   about renaming OLDNAME.  NEWNAME doesn't need                
                   quoting because we picked it.  OLDNAME needs to be           
                   quoted only the first time.  */                              
                char const *old = first ? qoldname : oldname;                   Line 1114
                error (0, 0,                                                    Line 1115
                       _("%s: renamed to %s"), old, newname);                   Line 1116
                first = false;                                                  Line 1117
              }                                                                 
            memcpy (oldname + (base - newname), base, len + 1);                 Line 1119
          }                                                                     
      }                                                                         
                                                                                
  if (unlink (oldname) != 0)                                                    Line 1123...!syscalls auto-comment......!syscalls auto-comment...
    {                                                                           
      error (0, errno, _("%s: failed to remove"), qoldname);                    Line 1125
      ok = false;                                                               Line 1126
    }                                                                           
  else if (flags->verbose)                                                      Line 1128
    error (0, 0, _("%s: removed"), qoldname);                                   Line 1129
  if (0 <= dir_fd)                                                              Line 1130
    {                                                                           
      if (dosync (dir_fd, qdir) != 0)                                           Line 1132...!syscalls auto-comment...
        ok = false;                                                             Line 1133
      if (close (dir_fd) != 0)                                                  Line 1134...!syscalls auto-comment...
        {                                                                       
          error (0, errno, _("%s: failed to close"), qdir);                     Line 1136
          ok = false;                                                           Line 1137
        }                                                                       
    }                                                                           
  free (newname);                                                               Line 1140
  free (dir);                                                                   Line 1141
  free (qdir);                                                                  Line 1142
  return ok;                                                                    Line 1143
}                                                                               Block 26
                                                                                
/*                                                                              
 * Finally, the function that actually takes a filename and grinds              
 * it into hamburger.                                                           
 *                                                                              
 * FIXME                                                                        
 * Detail to note: since we do not restore errno to EACCES after                
 * a failed chmod, we end up printing the error code from the chmod.            
 * This is actually the error that stopped us from proceeding, so               
 * it's arguably the right one, and in practice it'll be either EACCES          
 * again or EPERM, which both give similar error messages.                      
 * Does anyone disagree?                                                        
 */                                                                             
static bool                                                                     Line 1158
wipefile (char *name, char const *qname,                                        Line 1159
          struct randint_source *s, struct Options const *flags)                Line 1160
{                                                                               
  bool ok;                                                                      Line 1162
  int fd;                                                                       Line 1163
                                                                                
  fd = open (name, O_WRONLY | O_NOCTTY | O_BINARY);                             Line 1165...!syscalls auto-comment...
  if (fd < 0                                                                    Line 1166
      && (errno == EACCES && flags->force)                                      Line 1167
      && chmod (name, S_IWUSR) == 0)                                            Line 1168
    fd = open (name, O_WRONLY | O_NOCTTY | O_BINARY);                           Line 1169...!syscalls auto-comment...
  if (fd < 0)                                                                   Line 1170
    {                                                                           
      error (0, errno, _("%s: failed to open for writing"), qname);             Line 1172
      return false;                                                             Line 1173
    }                                                                           
                                                                                
  ok = do_wipefd (fd, qname, s, flags);                                         Line 1176
  if (close (fd) != 0)                                                          Line 1177...!syscalls auto-comment...
    {                                                                           
      error (0, errno, _("%s: failed to close"), qname);                        Line 1179
      ok = false;                                                               Line 1180
    }                                                                           
  if (ok && flags->remove_file)                                                 Line 1182
    ok = wipename (name, qname, flags);                                         Line 1183
  return ok;                                                                    Line 1184
}                                                                               Block 27
                                                                                
                                                                                
/* Buffers for random data.  */                                                 
static struct randint_source *randint_source;                                   Line 1189
                                                                                
/* Just on general principles, wipe buffers containing information              
   that may be related to the possibly-pseudorandom values used during          
   shredding.  */                                                               
static void                                                                     Line 1194
clear_random_data (void)                                                        Line 1195
{                                                                               
  randint_all_free (randint_source);                                            Line 1197
}                                                                               Block 28
                                                                                
                                                                                
int                                                                             
main (int argc, char **argv)                                                    Line 1202
{                                                                               
  bool ok = true;                                                               Line 1204
  struct Options flags = { 0, };                                                Line 1205
  char **file;                                                                  Line 1206
  int n_files;                                                                  Line 1207
  int c;                                                                        Line 1208
  int i;                                                                        Line 1209
  char const *random_source = NULL;                                             Line 1210
                                                                                
  initialize_main (&argc, &argv);                                               VMS-specific entry point handling wildcard expansion
  set_program_name (argv[0]);                                                   Retains program name and discards path
  setlocale (LC_ALL, "");                                                       Sets up internationalization (i18n)
  bindtextdomain (PACKAGE, LOCALEDIR);                                          Assigns i18n directorySets text domain for _() [gettext()] function
  textdomain (PACKAGE);                                                         Sets text domain for _() [gettext()] function
                                                                                
  atexit (close_stdout);                                                        Close stdout on exit (see gnulib)
                                                                                
  flags.n_iterations = DEFAULT_PASSES;                                          Line 1220
  flags.size = -1;                                                              Line 1221
                                                                                
  while ((c = getopt_long (argc, argv, "fn:s:uvxz", long_opts, NULL)) != -1)    Line 1223
    {                                                                           
      switch (c)                                                                Line 1225
        {                                                                       
        case 'f':                                                               Line 1227
          flags.force = true;                                                   Line 1228
          break;                                                                Line 1229
                                                                                
        case 'n':                                                               Line 1231
          flags.n_iterations = xdectoumax (optarg, 0,                           Line 1232
                                           MIN (ULONG_MAX,                      Line 1233
                                                SIZE_MAX / sizeof (int)), "",   Line 1234
                                           _("invalid number of passes"), 0);   Line 1235
          break;                                                                Line 1236
                                                                                
        case RANDOM_SOURCE_OPTION:                                              Line 1238
          if (random_source && !STREQ (random_source, optarg))                  Line 1239
            die (EXIT_FAILURE, 0, _("multiple random sources specified"));      Line 1240
          random_source = optarg;                                               Line 1241
          break;                                                                Line 1242
                                                                                
        case 'u':                                                               Line 1244
          if (optarg == NULL)                                                   Line 1245
            flags.remove_file = remove_wipesync;                                Line 1246
          else                                                                  Line 1247
            flags.remove_file = XARGMATCH ("--remove", optarg,                  Line 1248
                                           remove_args, remove_methods);        Line 1249
          break;                                                                Line 1250
                                                                                
        case 's':                                                               Line 1252
          flags.size = xnumtoumax (optarg, 0, 0, OFF_T_MAX, "cbBkKMGTPEZY0",    Line 1253
                                   _("invalid file size"), 0);                  Line 1254
          break;                                                                Line 1255
                                                                                
        case 'v':                                                               Line 1257
          flags.verbose = true;                                                 Line 1258
          break;                                                                Line 1259
                                                                                
        case 'x':                                                               Line 1261
          flags.exact = true;                                                   Line 1262
          break;                                                                Line 1263
                                                                                
        case 'z':                                                               Line 1265
          flags.zero_fill = true;                                               Line 1266
          break;                                                                Line 1267
                                                                                
        case_GETOPT_HELP_CHAR;                                                  Line 1269
                                                                                
        case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);                       Line 1271
                                                                                
        default:                                                                Line 1273
          usage (EXIT_FAILURE);                                                 Line 1274
        }                                                                       
    }                                                                           
                                                                                
  file = argv + optind;                                                         Line 1278
  n_files = argc - optind;                                                      Line 1279
                                                                                
  if (n_files == 0)                                                             Line 1281
    {                                                                           
      error (0, 0, _("missing file operand"));                                  Line 1283
      usage (EXIT_FAILURE);                                                     Line 1284
    }                                                                           
                                                                                
  randint_source = randint_all_new (random_source, SIZE_MAX);                   Line 1287
  if (! randint_source)                                                         Line 1288
    die (EXIT_FAILURE, errno, "%s", quotef (random_source));                    Line 1289
  atexit (clear_random_data);                                                   Close stdout on exit (see gnulib)
                                                                                
  for (i = 0; i < n_files; i++)                                                 Line 1292
    {                                                                           
      char *qname = xstrdup (quotef (file[i]));                                 Line 1294
      if (STREQ (file[i], "-"))                                                 Line 1295
        {                                                                       
          ok &= wipefd (STDOUT_FILENO, qname, randint_source, &flags);          Line 1297
        }                                                                       
      else                                                                      Line 1299
        {                                                                       
          /* Plain filename - Note that this overwrites *argv! */               
          ok &= wipefile (file[i], qname, randint_source, &flags);              Line 1302
        }                                                                       
      free (qname);                                                             Line 1304
    }                                                                           
                                                                                
  return ok ? EXIT_SUCCESS : EXIT_FAILURE;                                      Line 1307
}                                                                               Block 29
/*                                                                              
 * vim:sw=2:sts=2:                                                              
 */