summaryrefslogtreecommitdiff
path: root/src/touch.c
blob: 89595bb5a48286ce433abc3aade3b6edb63deb51 (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
/* touch -- change modification and access times of files
   Copyright (C) 87, 1989-1991, 1995-1999 Free Software Foundation, Inc.

   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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */

/* Written by Paul Rubin, Arnold Robbins, Jim Kingdon, David MacKenzie,
   and Randy Smith. */

#include <config.h>
#include <stdio.h>
#include <getopt.h>
#include <sys/types.h>

#include "system.h"
#include "argmatch.h"
#include "error.h"
#include "getdate.h"
#include "posixtm.h"
#include "safe-read.h"

/* The official name of this program (e.g., no `g' prefix).  */
#define PROGRAM_NAME "touch"

#define AUTHORS \
  "Paul Rubin, Arnold Robbins, Jim Kingdon, David MacKenzie, and Randy Smith"

#ifndef STDC_HEADERS
time_t time ();
#endif

int full_write ();

/* Bitmasks for `change_times'. */
#define CH_ATIME 1
#define CH_MTIME 2

/* The name by which this program was run. */
char *program_name;

/* Which timestamps to change. */
static int change_times;

/* (-c) If nonzero, don't create if not already there. */
static int no_create;

/* (-d) If nonzero, date supplied on command line in get_date formats. */
static int flexible_date;

/* (-r) If nonzero, use times from a reference file. */
static int use_ref;

/* (-t) If nonzero, date supplied on command line in POSIX format. */
static int posix_date;

/* If nonzero, the only thing we have to do is change both the
   modification and access time to the current time, so we don't
   have to own the file, just be able to read and write it.  */
static int amtime_now;

/* New time to use when setting time. */
static time_t newtime;

/* File to use for -r. */
static char *ref_file;

/* Info about the reference file. */
static struct stat ref_stats;

static struct option const longopts[] =
{
  {"time", required_argument, 0, CHAR_MAX + 1},
  {"no-create", no_argument, 0, 'c'},
  {"date", required_argument, 0, 'd'},
  {"file", required_argument, 0, 'r'}, /* FIXME: phase out --file */
  {"reference", required_argument, 0, 'r'},
  {GETOPT_HELP_OPTION_DECL},
  {GETOPT_VERSION_OPTION_DECL},
  {0, 0, 0, 0}
};

/* Valid arguments to the `--time' option. */
static char const* const time_args[] =
{
  "atime", "access", "use", "mtime", "modify", 0
};

/* The bits in `change_times' that those arguments set. */
static int const time_masks[] =
{
  CH_ATIME, CH_ATIME, CH_ATIME, CH_MTIME, CH_MTIME
};

/* Open FILE, possibly creating it.  Set *FILE_CREATED to nonzero if the
   open creates it, or to zero if the open call opened an existing file.
   Return the result of the open call.  Be careful to avoid race conditions.  */

static int
open_maybe_create (const char *file, int *file_created)
{
  int fd;

  *file_created = 0;
  while (1)
    {
      /* First, see if we can create a new FILE.  */
      fd = open (file, O_WRONLY | O_CREAT | O_EXCL,
		 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
      if (fd != -1)
	*file_created = 1;

      /* If the open succeeded or if it failed for any reason other
	 than the existence of FILE, then we're done.  Some systems
         (solaris) set errno to EINVAL when FILE is a directory.  */
      if (fd != -1 || (errno != EEXIST && errno != EINVAL))
	break;

      /* The first open failed because FILE already exists.
	 Now try to open it for writing.  */
      fd = open (file, O_WRONLY);

      /* If the open succeeded or if it failed for any reason other
	 than the absence of FILE, then we're done.  */
      /* The 2nd open can fail if FILE was unlinked between the two
	 open calls.  When that happens, just iterate.  */
      if (fd != -1 || errno != ENOENT)
	break;
    }

  return fd;
}

/* Update the time of file FILE according to the options given.
   Return 0 if successful, 1 if an error occurs. */

static int
touch (const char *file)
{
  int status;
  struct stat sbuf;
  int fd;
  int file_created;

  if (no_create)
    {
      /* Try to open an existing FILE.  */
      fd = open (file, O_WRONLY);
      if (fd == -1 && errno == ENOENT)
	{
	  /* FILE doesn't exist.  So we're done.  */
	  return 0;
	}
      file_created = 0;
    }
  else
    {
      /* Try to open FILE, creating it if necessary.  */
      fd = open_maybe_create (file, &file_created);
    }

  /* Don't fail if the open failed because FILE is a directory.  */
  if (fd == -1
      /* As usual, using E* macros like this is risky...
         So heads up.  */
      && errno != EISDIR)
    {
      error (0, errno, "%s", file);
      return 1;
    }

  if (amtime_now)
    {
      if (file_created)
	{
	  if (close (fd) < 0)
	    {
	      error (0, errno, "%s", file);
	      return 1;
	    }

	  /* We've just created the file with the current times.  */
	  return 0;
	}
    }
  else
    {
      /* We're setting only one of the time values.  stat the target to get
	 the other one.  If we have the file descriptor already, use fstat,
	 otherwise, FILE is a directory, so we have to use stat.  */
      if (fd == -1 ? stat (file, &sbuf) : fstat (fd, &sbuf))
	{
	  error (0, errno, "%s", file);
	  close (fd);
	  return 1;
	}
    }

  if (fd != -1 && close (fd) < 0)
    {
      error (0, errno, "%s", file);
      return 1;
    }

  if (amtime_now)
    {
      /* Pass NULL to utime so it will not fail if we just have
	 write access to the file, but don't own it.  */
      status = utime (file, NULL);
    }
  else
    {
      struct utimbuf utb;

      /* There's currently no interface to set file timestamps with
	 better than 1-second resolution, so discard any fractional
	 part of the source timestamp.  */

      if (use_ref)
	{
	  utb.actime = ref_stats.st_atime;
	  utb.modtime = ref_stats.st_mtime;
	}
      else
	utb.actime = utb.modtime = newtime;

      if (!(change_times & CH_ATIME))
	utb.actime = sbuf.st_atime;

      if (!(change_times & CH_MTIME))
	utb.modtime = sbuf.st_mtime;

      status = utime (file, &utb);
    }

  if (status)
    {
      error (0, errno, "%s", file);
      return 1;
    }

  return 0;
}

void
usage (int status)
{
  if (status != 0)
    fprintf (stderr, _("Try `%s --help' for more information.\n"),
	     program_name);
  else
    {
      printf (_("Usage: %s [OPTION]... FILE...\n"), program_name);
      printf (_("  or : %s [-acm] MMDDhhmm[YY] FILE... (obsolescent)\n"),
	      program_name);
      printf (_("\
Update the access and modification times of each FILE to the current time.\n\
\n\
  -a                     change only the access time\n\
  -c, --no-create        do not create any files\n\
  -d, --date=STRING      parse STRING and use it instead of current time\n\
  -f                     (ignored)\n\
  -m                     change only the modification time\n\
  -r, --reference=FILE   use this file's times instead of current time\n\
  -t STAMP               use [[CC]YY]MMDDhhmm[.ss] instead of current time\n\
  --time=WORD            set time given by WORD: access atime use (same as -a)\n\
                           modify mtime (same as -m)\n\
      --help             display this help and exit\n\
      --version          output version information and exit\n\
\n\
STAMP may be used without -t if none of -drt, nor --, are used.\n\
Note that the three time-date formats recognized for the -d and -t options\n\
and for the obsolescent argument are all different.\n\
"));
      puts (_("\nReport bugs to <bug-fileutils@gnu.org>."));
      close_stdout ();
    }
  exit (status);
}

int
main (int argc, char **argv)
{
  int c;
  int date_set = 0;
  int err = 0;

  program_name = argv[0];
  setlocale (LC_ALL, "");
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);

  change_times = no_create = use_ref = posix_date = flexible_date = 0;
  newtime = (time_t) -1;

  while ((c = getopt_long (argc, argv, "acd:fmr:t:", longopts, NULL)) != -1)
    {
      switch (c)
	{
	case 0:
	  break;

	case 'a':
	  change_times |= CH_ATIME;
	  break;

	case 'c':
	  no_create++;
	  break;

	case 'd':
	  flexible_date++;
	  newtime = get_date (optarg, NULL);
	  if (newtime == (time_t) -1)
	    error (1, 0, _("invalid date format `%s'"), optarg);
	  date_set++;
	  break;

	case 'f':
	  break;

	case 'm':
	  change_times |= CH_MTIME;
	  break;

	case 'r':
	  use_ref++;
	  ref_file = optarg;
	  break;

	case 't':
	  posix_date++;
	  newtime = posixtime (optarg,
			       PDS_LEADING_YEAR | PDS_CENTURY | PDS_SECONDS);
	  if (newtime == (time_t) -1)
	    error (1, 0, _("invalid date format `%s'"), optarg);
	  date_set++;
	  break;

	case CHAR_MAX + 1:	/* --time */
	  change_times |= XARGMATCH ("--time", optarg,
				     time_args, time_masks);
	  break;

	case_GETOPT_HELP_CHAR;

	case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);

	default:
	  usage (1);
	}
    }

  if (change_times == 0)
    change_times = CH_ATIME | CH_MTIME;

  if ((use_ref && (posix_date || flexible_date))
      || (posix_date && flexible_date))
    {
      error (0, 0, _("cannot specify times from more than one source"));
      usage (1);
    }

  if (use_ref)
    {
      if (stat (ref_file, &ref_stats))
	error (1, errno, "%s", ref_file);
      date_set++;
    }

  if (!date_set && optind < argc && !STREQ (argv[optind - 1], "--"))
    {
      newtime = posixtime (argv[optind], PDS_TRAILING_YEAR);
      if (newtime != (time_t) -1)
	{
	  optind++;
	  date_set++;
	}
    }
  if (!date_set)
    {
      if ((change_times & (CH_ATIME | CH_MTIME)) == (CH_ATIME | CH_MTIME))
	amtime_now = 1;
      else
	time (&newtime);
    }

  if (optind == argc)
    {
      error (0, 0, _("file arguments missing"));
      usage (1);
    }

  for (; optind < argc; ++optind)
    err += touch (argv[optind]);

  exit (err != 0);
}