summaryrefslogtreecommitdiff
path: root/tests/genfile.c
blob: 0cf6282b3ecd0a6775543fcede291dfe0d9e24cb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
/* Generate a file containing some preset patterns.
   Print statistics for existing files.

   Copyright (C) 1995, 1996, 1997, 2001, 2003, 2004, 2005 Free Software
   Foundation, Inc.

   François Pinard <pinard@iro.umontreal.ca>, 1995.
   Sergey Poznyakoff <gray@mirddin.farlep.net>, 2004, 2005.

   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 2, 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, write to the Free Software Foundation,
   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

#include <system.h>
#include <signal.h>
#include <stdarg.h>
#include <argmatch.h>
#include <argp.h>
#include <argcv.h>
#include <getdate.h>
#include <setenv.h>
#include <utimens.h>
#include <inttostr.h>

#ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
#endif
#ifndef EXIT_FAILURE
# define EXIT_FAILURE 1
#endif

#if ! defined SIGCHLD && defined SIGCLD
# define SIGCHLD SIGCLD
#endif

enum pattern
{
  DEFAULT_PATTERN,
  ZEROS_PATTERN
};

/* The name this program was run with. */
const char *program_name;

/* Name of file to generate */
static char *file_name;

/* Length of file to generate.  */
static off_t file_length = 0;

/* Pattern to generate.  */
static enum pattern pattern = DEFAULT_PATTERN;

/* Next checkpoint number */
size_t checkpoint;

enum genfile_mode
  {
    mode_generate,
    mode_sparse,
    mode_stat,
    mode_exec
  };

enum genfile_mode mode = mode_generate;

#define DEFAULT_STAT_FORMAT \
  "name,dev,ino,mode,nlink,uid,gid,size,blksize,blocks,atime,mtime,ctime"

/* Format for --stat option */
static char *stat_format = DEFAULT_STAT_FORMAT;

/* Size of a block for sparse file */
size_t block_size = 512;

/* Block buffer for sparse file */
char *buffer;

/* Number of arguments and argument vector for mode == mode_exec */
int exec_argc;
char **exec_argv;

/* Time for --touch option */
struct timespec touch_time;

/* Verbose mode */
int verbose;

const char *argp_program_version = "genfile (" PACKAGE ") " VERSION;
const char *argp_program_bug_address = "<" PACKAGE_BUGREPORT ">";
static char doc[] = N_("genfile manipulates data files for GNU paxutils test suite.\n"
"OPTIONS are:\n");

#define OPT_CHECKPOINT 256
#define OPT_TOUCH      257
#define OPT_APPEND     258
#define OPT_TRUNCATE   259
#define OPT_EXEC       260
#define OPT_DATE       261
#define OPT_VERBOSE    262

static struct argp_option options[] = {
#define GRP 0
  {NULL, 0, NULL, 0,
   N_("File creation options:"), GRP},
  {"length", 'l', N_("SIZE"), 0,
   N_("Create file of the given SIZE"), GRP+1 },
  {"file", 'f', N_("NAME"), 0,
   N_("Write to file NAME, instead of standard output"), GRP+1},
  {"pattern", 'p', N_("PATTERN"), 0,
   N_("Fill the file with the given PATTERN. PATTERN is 'default' or 'zeros'"),
   GRP+1 },
  {"block-size", 'b', N_("SIZE"), 0,
   N_("Size of a block for sparse file"), GRP+1},
  {"sparse", 's', NULL, 0,
   N_("Generate sparse file. Rest of the command line gives the file map."),
   GRP+1 },
#undef GRP
#define GRP 10
  {NULL, 0, NULL, 0,
   N_("File statistics options:"), GRP},

  {"stat", 'S', N_("FORMAT"), OPTION_ARG_OPTIONAL,
   N_("Print contents of struct stat for each given file. Default FORMAT is: ")
   DEFAULT_STAT_FORMAT,
   GRP+1 },
#undef GRP
#define GRP 20
  {NULL, 0, NULL, 0,
   N_("Synchronous execution options:"), GRP},

  {"run", 'r', N_("COMMAND"), 0,
   N_("Execute given COMMAND. Useful with --checkpoint and one of --cut, --append, --touch"),
   GRP+1 },
  {"checkpoint", OPT_CHECKPOINT, N_("NUMBER"), 0,
   N_("Perform given action (see below) upon reaching checkpoint NUMBER"),
   GRP+1 },
  {"date", OPT_DATE, N_("STRING"), 0,
   N_("Set date for next --touch option"),
   GRP+1 },
  {"verbose", OPT_VERBOSE, NULL, 0,
   N_("Display executed checkpoints and exit status of COMMAND"),
   GRP+1 },
#undef GRP
#define GRP 30
  {NULL, 0, NULL, 0,
   N_("Synchronous execution actions. These are executed when checkpoint number given by --checkpoint option is reached."), GRP},

  {"cut", OPT_TRUNCATE, N_("FILE"), 0,
   N_("Truncate FILE to the size specified by previous --length option (or 0, if it is not given)"),
   GRP+1 },
  {"truncate", 0, NULL, OPTION_ALIAS, NULL, GRP+1 },
  {"append", OPT_APPEND, N_("FILE"), 0,
   N_("Append SIZE bytes to FILE. SIZE is given by previous --length option."),
   GRP+1 },
  {"touch", OPT_TOUCH, N_("FILE"), 0,
   N_("Update the access and modification times of FILE"),
   GRP+1 },
  {"exec", OPT_EXEC, N_("COMMAND"), 0,
   N_("Execute COMMAND"),
   GRP+1 },
#undef GRP
  { NULL, }
};

static char const * const pattern_args[] = { "default", "zeros", 0 };
static enum pattern const pattern_types[] = {DEFAULT_PATTERN, ZEROS_PATTERN};

static int
xlat_suffix (off_t *vp, char *p)
{
  if (p[1])
    return 1;
  switch (p[0])
    {
    case 'g':
    case 'G':
      *vp *= 1024;

    case 'm':
    case 'M':
      *vp *= 1024;

    case 'k':
    case 'K':
      *vp *= 1024;
      break;

    default:
      return 1;
    }
  return 0;
}

static off_t
get_size (const char *str, int allow_zero)
{
  char *p;
  off_t n;

  n = strtoul (str, &p, 0);
  if (n < 0 || (!allow_zero && n == 0) || (*p && xlat_suffix (&n, p)))
    error (EXIT_FAILURE, 0, _("Invalid size: %s"), str);
  return n;
}

struct action
{
  struct action *next;
  size_t checkpoint;
  int action;
  char *name;
  off_t size;
  enum pattern pattern;
  struct timespec ts;
};

static struct action *action_list;

int
reg_action (int action, char *arg)
{
  struct action *act = xmalloc (sizeof (*act));
  act->checkpoint = checkpoint;
  act->action = action;
  act->pattern = pattern;
  act->ts = touch_time;
  act->size = file_length;
  act->name = arg;
  act->next = action_list;
  action_list = act;
}

static error_t
parse_opt (int key, char *arg, struct argp_state *state)
{
  switch (key)
    {
    case 'f':
      file_name = arg;
      break;

    case 'l':
      file_length = get_size (arg, 1);
      break;

    case 'p':
      pattern = XARGMATCH ("--pattern", arg, pattern_args, pattern_types);
      break;

    case 'b':
      block_size = get_size (arg, 0);
      break;

    case 's':
      mode = mode_sparse;
      break;

    case 'S':
      mode = mode_stat;
      if (arg)
	stat_format = arg;
      break;

    case 'r':
      mode = mode_exec;
      argcv_get (arg, "", NULL, &exec_argc, &exec_argv);
      break;

    case OPT_CHECKPOINT:
      {
	char *p;

	checkpoint = strtoul (arg, &p, 0);
	if (*p)
	  argp_error (state, _("Error parsing number near `%s'"), p);
      }
      break;

    case OPT_DATE:
      if (!get_date (&touch_time, arg, NULL))
	argp_error (state, _("Unknown date format"));
      break;

    case OPT_APPEND:
    case OPT_TRUNCATE:
    case OPT_TOUCH:
    case OPT_EXEC:
      reg_action (key, arg);
      break;

    case OPT_VERBOSE:
      verbose++;
      break;

    default:
      return ARGP_ERR_UNKNOWN;
    }
  return 0;
}

static struct argp argp = {
  options,
  parse_opt,
  N_("[ARGS...]"),
  doc,
  NULL,
  NULL,
  NULL
};


void
fill (FILE *fp, off_t length, enum pattern pattern)
{
  off_t i;

  switch (pattern)
    {
    case DEFAULT_PATTERN:
      for (i = 0; i < length; i++)
	fputc (i & 255, fp);
      break;

    case ZEROS_PATTERN:
      for (i = 0; i < length; i++)
	fputc (0, fp);
      break;
    }
}

/* Generate Mode: usual files */
static void
generate_simple_file (int argc, char **argv)
{
  int i;
  FILE *fp;

  if (argc)
    error (EXIT_FAILURE, 0, _("too many arguments"));

  if (file_name)
    {
      fp = fopen (file_name, "w");
      if (!fp)
	error (EXIT_FAILURE, 0, _("cannot open `%s'"), file_name);
    }
  else
    fp = stdout;

  fill (fp, file_length, pattern);

  fclose (fp);
}


/* Generate Mode: sparse files */

static void
mkhole (int fd, off_t displ)
{
  if (lseek (fd, displ, SEEK_CUR) == -1)
    error (EXIT_FAILURE, errno, "lseek");
  ftruncate (fd, lseek (fd, 0, SEEK_CUR));
}

static void
mksparse (int fd, off_t displ, char *marks)
{
  for (; *marks; marks++)
    {
      memset (buffer, *marks, block_size);
      if (write (fd, buffer, block_size) != block_size)
	error (EXIT_FAILURE, errno, "write");

      if (lseek (fd, displ, SEEK_CUR) == -1)
	error (EXIT_FAILURE, errno, "lseek");
    }
}

static void
generate_sparse_file (int argc, char **argv)
{
  int i;
  int fd;

  if (!file_name)
    error (EXIT_FAILURE, 0,
	   _("cannot generate sparse files on standard output, use --file option"));
  fd = open (file_name, O_CREAT|O_TRUNC|O_RDWR, 0644);
  if (fd < 0)
    error (EXIT_FAILURE, 0, _("cannot open `%s'"), file_name);

  buffer = xmalloc (block_size);

  for (i = 0; i < argc; i += 2)
    {
      off_t displ = get_size (argv[i], 1);

      if (i == argc-1)
	{
	  mkhole (fd, displ);
	  break;
	}
      else
	mksparse (fd, displ, argv[i+1]);
    }

  close (fd);
}


/* Status Mode */

void
print_time (time_t t)
{
  char buf[20]; /* ccyy-mm-dd HH:MM:SS\0 */
  strftime (buf, sizeof buf, "%Y-%m-%d %H:%M:%S", gmtime (&t));
  printf ("%s ", buf);
}

void
print_stat (const char *name)
{
  char *fmt, *p;
  struct stat st;
  char buf[UINTMAX_STRSIZE_BOUND];

  if (stat (name, &st))
    {
      error (0, errno, _("stat(%s) failed"), name);
      return;
    }

  fmt = strdup (stat_format);
  for (p = strtok (fmt, ","); p; p = strtok (NULL, ","))
    {
      if (memcmp (p, "st_", 3) == 0)
	p += 3;
      if (strcmp (p, "name") == 0)
	printf ("%s", name);
      else if (strcmp (p, "dev") == 0)
	printf ("%lu", (unsigned long) st.st_dev);
      else if (strcmp (p, "ino") == 0)
	printf ("%lu", (unsigned long) st.st_ino);
      else if (strcmp (p, "mode") == 0)
	printf ("%0o", st.st_mode);
      else if (strcmp (p, "nlink") == 0)
	printf ("%lu", (unsigned long) st.st_nlink);
      else if (strcmp (p, "uid") == 0)
	printf ("%ld", (long unsigned) st.st_uid);
      else if (strcmp (p, "gid") == 0)
	printf ("%lu", (unsigned long) st.st_gid);
      else if (strcmp (p, "size") == 0)
	printf ("%s", umaxtostr (st.st_size, buf));
      else if (strcmp (p, "blksize") == 0)
	printf ("%s", umaxtostr (st.st_blksize, buf));
      else if (strcmp (p, "blocks") == 0)
	printf ("%s", umaxtostr (st.st_blocks, buf));
      else if (strcmp (p, "atime") == 0)
	printf ("%lu", (unsigned long) st.st_atime);
      else if (strcmp (p, "atimeH") == 0)
	print_time (st.st_atime);
      else if (strcmp (p, "mtime") == 0)
	printf ("%lu", (unsigned long) st.st_mtime);
      else if (strcmp (p, "mtimeH") == 0)
	print_time (st.st_mtime);
      else if (strcmp (p, "ctime") == 0)
	printf ("%lu", (unsigned long) st.st_ctime);
      else if (strcmp (p, "ctimeH") == 0)
	print_time (st.st_ctime);
      else
	{
	  printf ("\n");
	  error (EXIT_FAILURE, 0, _("Unknown field `%s'"), p);
	}
      printf (" ");
    }
  printf ("\n");
  free (fmt);
}


/* Exec Mode */

void
exec_checkpoint (struct action *p)
{
  if (verbose)
    printf ("processing checkpoint %lu\n", (unsigned long) p->checkpoint);
  switch (p->action)
    {
    case OPT_TOUCH:
      {
	struct timespec ts[2];

	ts[0] = ts[1] = p->ts;
	if (utimens (p->name, ts) != 0)
	  {
	    error (0, errno, _("cannot set time on `%s'"), p->name);
	    break;
	  }
      }
      break;

    case OPT_APPEND:
      {
	FILE *fp = fopen (p->name, "a");
	if (!fp)
	  {
	    error (0, errno, _("cannot open `%s'"), p->name);
	    break;
	  }

	fill (fp, p->size, p->pattern);
	fclose (fp);
      }
      break;

    case OPT_TRUNCATE:
      {
	int fd = open (p->name, O_RDWR);
	if (fd == -1)
	  {
	    error (0, errno, _("cannot open `%s'"), p->name);
	    break;
	  }
	ftruncate (fd, p->size);
	close (fd);
      }
      break;

    case OPT_EXEC:
      system (p->name);
      break;

    default:
      abort ();
    }
}

void
process_checkpoint (size_t n)
{
  struct action *p, *prev = NULL;

  for (p = action_list; p; )
    {
      struct action *next = p->next;

      if (p->checkpoint <= n)
	{
	  exec_checkpoint (p);
	  /* Remove the item from the list */
	  if (prev)
	    prev->next = next;
	  else
	    action_list = next;
	  free (p);
	}
      else
	prev = p;

      p = next;
    }
}

#define CHECKPOINT_TEXT "Write checkpoint"

void
exec_command (void)
{
  int i, status;
  pid_t pid;
  int fd[2];
  char *p;
  FILE *fp;
  char buf[128];

  /* Insert --checkpoint option.
     FIXME: This assumes that exec_argv does not use traditional tar options
     (without dash) */
  exec_argc++;
  exec_argv = xrealloc (exec_argv, exec_argc * sizeof (*exec_argv));
  memmove (exec_argv+2, exec_argv+1, (exec_argc-1)*sizeof (*exec_argv));
  exec_argv[1] = "--checkpoint";

#ifdef SIGCHLD
  /* System V fork+wait does not work if SIGCHLD is ignored.  */
  signal (SIGCHLD, SIG_DFL);
#endif

  pipe (fd);

  pid = fork ();
  if (pid == -1)
    error (EXIT_FAILURE, errno, "fork");

  if (pid == 0)
    {
      /* Child */

      /* Pipe stderr */
      if (fd[1] != 2)
	dup2 (fd[1], 2);
      close (fd[0]);

      /* Make sure POSIX locale is used */
      setenv ("LC_ALL", "POSIX", 1);

      execvp (exec_argv[0], exec_argv);
      error (EXIT_FAILURE, errno, "execvp");
    }

  /* Master */
  close (fd[1]);
  fp = fdopen (fd[0], "r");
  if (fp == NULL)
    error (EXIT_FAILURE, errno, "fdopen");

  while ((p = fgets (buf, sizeof buf, fp)))
    {
      while (*p && !isspace (*p) && *p != ':')
	p++;

      if (*p == ':')
	{
	  for (p++; *p && isspace (*p); p++)
	    ;

	  if (*p
	      && memcmp (p, CHECKPOINT_TEXT, sizeof CHECKPOINT_TEXT - 1) == 0)
	    {
	      char *end;
	      size_t n = strtoul (p + sizeof CHECKPOINT_TEXT - 1, &end, 10);
	      if (!(*end && !isspace (*end)))
		{
		  process_checkpoint (n);
		  continue;
		}
	    }
	}
      fprintf (stderr, "%s", buf);
    }

  /* Collect exit status */
  waitpid (pid, &status, 0);

  if (verbose)
    {
      if (WIFEXITED (status))
	{
	  if (WEXITSTATUS (status) == 0)
	    printf (_("Command exited successfully\n"));
	  else
	    printf (_("Command failed with status %d\n"),
		    WEXITSTATUS (status));
	}
      else if (WIFSIGNALED (status))
	printf (_("Command terminated on signal %d\n"), WTERMSIG (status));
      else if (WIFSTOPPED (status))
	printf (_("Command stopped on signal %d\n"), WSTOPSIG (status));
#ifdef WCOREDUMP
      else if (WCOREDUMP (status))
	printf (_("Command dumped core\n"));
#endif
      else
	printf(_("Command terminated\n"));
    }

  if (WIFEXITED (status))
    exit (WEXITSTATUS (status));
  exit (EXIT_FAILURE);
}

int
main (int argc, char **argv)
{
  int index;

  program_name = argv[0];
  setlocale (LC_ALL, "");
  get_date (&touch_time, "now", NULL);

  /* Decode command options.  */

  if (argp_parse (&argp, argc, argv, 0, &index, NULL))
    exit (EXIT_FAILURE);

  argc -= index;
  argv += index;

  switch (mode)
    {
    case mode_stat:
      if (argc == 0)
	error (EXIT_FAILURE, 0, _("--stat requires file names"));

      while (argc--)
	print_stat (*argv++);
      break;

    case mode_sparse:
      generate_sparse_file (argc, argv);
      break;

    case mode_generate:
      generate_simple_file (argc, argv);
      break;

    case mode_exec:
      exec_command ();
      break;

    default:
      /* Just in case */
      abort ();
    }
  exit (EXIT_SUCCESS);
}