(batch_convert): Free `initial_TZ' only if it was set.
[platform/upstream/coreutils.git] / src / date.c
1 /* date - print or set the system date and time
2    Copyright (C) 1989-2000 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17
18    David MacKenzie <djm@gnu.ai.mit.edu> */
19
20 #include <config.h>
21 #include <stdio.h>
22 #include <getopt.h>
23 #include <sys/types.h>
24 #if HAVE_LANGINFO_H
25 # include <langinfo.h>
26 #endif
27
28 #include "system.h"
29 #include "argmatch.h"
30 #include "closeout.h"
31 #include "error.h"
32 #include "getdate.h"
33 #include "getline.h"
34 #include "posixtm.h"
35
36 /* The official name of this program (e.g., no `g' prefix).  */
37 #define PROGRAM_NAME "date"
38
39 #define AUTHORS "David MacKenzie"
40
41 #ifndef STDC_HEADERS
42 size_t strftime ();
43 time_t time ();
44 #endif
45
46 int putenv ();
47 int stime ();
48
49 static void show_date PARAMS ((const char *format, time_t when));
50
51 enum Time_spec
52 {
53   /* display only the date: 1999-03-25 */
54   TIME_SPEC_DATE=1,
55   /* display date and hour: 1999-03-25T03-0500 */
56   TIME_SPEC_HOURS,
57   /* display date, hours, and minutes: 1999-03-25T03:23-0500 */
58   TIME_SPEC_MINUTES,
59   /* display date, hours, minutes, and seconds: 1999-03-25T03:23:14-0500 */
60   TIME_SPEC_SECONDS
61 };
62
63 static char const *const time_spec_string[] =
64 {
65   "date", "hours", "minutes", "seconds", 0
66 };
67
68 static enum Time_spec const time_spec[] =
69 {
70   TIME_SPEC_DATE, TIME_SPEC_HOURS, TIME_SPEC_MINUTES, TIME_SPEC_SECONDS
71 };
72
73 /* The name this program was run with, for error messages. */
74 char *program_name;
75
76 /* If nonzero, display an ISO 8601 format date/time string */
77 static int iso_8601_format = 0;
78
79 /* If non-zero, display time in RFC-822 format for mail or news. */
80 static int rfc_format = 0;
81
82 /* If nonzero, print or set Coordinated Universal Time.  */
83 static int universal_time = 0;
84
85 static struct option const long_options[] =
86 {
87   {"date", required_argument, NULL, 'd'},
88   {"file", required_argument, NULL, 'f'},
89   {"iso-8601", optional_argument, NULL, 'I'},
90   {"reference", required_argument, NULL, 'r'},
91   {"rfc-822", no_argument, NULL, 'R'},
92   {"set", required_argument, NULL, 's'},
93   {"uct", no_argument, NULL, 'u'},
94   {"utc", no_argument, NULL, 'u'},
95   {"universal", no_argument, NULL, 'u'},
96   {GETOPT_HELP_OPTION_DECL},
97   {GETOPT_VERSION_OPTION_DECL},
98   {NULL, 0, NULL, 0}
99 };
100
101 #define TZ_UTC0 "TZ=UTC0"
102
103 #if LOCALTIME_CACHE
104 # define TZSET tzset ()
105 #else
106 # define TZSET /* empty */
107 #endif
108
109 #define MAYBE_SET_TZ_UTC0 \
110   do { if (universal_time) set_tz (TZ_UTC0); } while (0)
111
112 #ifdef _DATE_FMT
113 # define DATE_FMT_LANGINFO() nl_langinfo (_DATE_FMT)
114 #else
115 # define DATE_FMT_LANGINFO() ""
116 #endif
117
118 void
119 usage (int status)
120 {
121   if (status != 0)
122     fprintf (stderr, _("Try `%s --help' for more information.\n"),
123              program_name);
124   else
125     {
126       printf (_("\
127 Usage: %s [OPTION]... [+FORMAT]\n\
128   or:  %s [OPTION] [MMDDhhmm[[CC]YY][.ss]]\n\
129 "),
130               program_name, program_name);
131       printf (_("\
132 Display the current time in the given FORMAT, or set the system date.\n\
133 \n\
134   -d, --date=STRING         display time described by STRING, not `now'\n\
135   -f, --file=DATEFILE       like --date once for each line of DATEFILE\n\
136   -I, --iso-8601[=TIMESPEC] output an ISO-8601 compliant date/time string.\n\
137                             TIMESPEC=`date' (or missing) for date only,\n\
138                             `hours', `minutes', or `seconds' for date and\n\
139                             time to the indicated precision.\n\
140   -r, --reference=FILE      display the last modification time of FILE\n\
141   -R, --rfc-822             output RFC-822 compliant date string\n\
142   -s, --set=STRING          set time described by STRING\n\
143   -u, --utc, --universal    print or set Coordinated Universal Time\n\
144       --help                display this help and exit\n\
145       --version             output version information and exit\n\
146 "));
147       printf (_("\
148 \n\
149 FORMAT controls the output.  The only valid option for the second form\n\
150 specifies Coordinated Universal Time.  Interpreted sequences are:\n\
151 \n\
152   %%%%   a literal %%\n\
153   %%a   locale's abbreviated weekday name (Sun..Sat)\n\
154   %%A   locale's full weekday name, variable length (Sunday..Saturday)\n\
155   %%b   locale's abbreviated month name (Jan..Dec)\n\
156   %%B   locale's full month name, variable length (January..December)\n\
157   %%c   locale's date and time (Sat Nov 04 12:02:33 EST 1989)\n\
158   %%d   day of month (01..31)\n\
159   %%D   date (mm/dd/yy)\n\
160   %%e   day of month, blank padded ( 1..31)\n\
161   %%h   same as %%b\n\
162   %%H   hour (00..23)\n\
163   %%I   hour (01..12)\n\
164   %%j   day of year (001..366)\n\
165   %%k   hour ( 0..23)\n\
166   %%l   hour ( 1..12)\n\
167   %%m   month (01..12)\n\
168   %%M   minute (00..59)\n\
169   %%n   a newline\n\
170   %%p   locale's AM or PM\n\
171   %%r   time, 12-hour (hh:mm:ss [AP]M)\n\
172   %%s   seconds since 00:00:00, Jan 1, 1970 (a GNU extension)\n\
173   %%S   second (00..60)\n\
174   %%t   a horizontal tab\n\
175   %%T   time, 24-hour (hh:mm:ss)\n\
176   %%U   week number of year with Sunday as first day of week (00..53)\n\
177   %%V   week number of year with Monday as first day of week (01..53)\n\
178   %%w   day of week (0..6);  0 represents Sunday\n\
179   %%W   week number of year with Monday as first day of week (00..53)\n\
180   %%x   locale's date representation (mm/dd/yy)\n\
181   %%X   locale's time representation (%%H:%%M:%%S)\n\
182   %%y   last two digits of year (00..99)\n\
183   %%Y   year (1970...)\n\
184   %%z   RFC-822 style numeric timezone (-0500) (a nonstandard extension)\n\
185   %%Z   time zone (e.g., EDT), or nothing if no time zone is determinable\n\
186 \n\
187 By default, date pads numeric fields with zeroes.  GNU date recognizes\n\
188 the following modifiers between `%%' and a numeric directive.\n\
189 \n\
190   `-' (hyphen) do not pad the field\n\
191   `_' (underscore) pad the field with spaces\n\
192 "));
193       puts (_("\nReport bugs to <bug-sh-utils@gnu.org>."));
194     }
195   exit (status);
196 }
197
198 /* Set the TZ environment variable.  */
199
200 static void
201 set_tz (const char *tz_eq_zone)
202 {
203   if (putenv (tz_eq_zone) != 0)
204     error (1, 0, "memory exhausted");
205   TZSET;
206 }
207
208 /* Parse each line in INPUT_FILENAME as with --date and display each
209    resulting time and date.  If the file cannot be opened, tell why
210    then exit.  Issue a diagnostic for any lines that cannot be parsed.
211    If any line cannot be parsed, return nonzero;  otherwise return zero.  */
212
213 static int
214 batch_convert (const char *input_filename, const char *format)
215 {
216   int status;
217   FILE *in_stream;
218   char *line;
219   int line_length;
220   size_t buflen;
221   time_t when;
222   char *initial_TZ IF_LINT (= NULL);
223
224   if (strcmp (input_filename, "-") == 0)
225     {
226       input_filename = _("standard input");
227       in_stream = stdin;
228     }
229   else
230     {
231       in_stream = fopen (input_filename, "r");
232       if (in_stream == NULL)
233         {
234           error (1, errno, "`%s'", input_filename);
235         }
236     }
237
238   line = NULL;
239   buflen = 0;
240
241   if (universal_time)
242     {
243       initial_TZ = getenv ("TZ");
244       if (initial_TZ == NULL)
245         {
246           initial_TZ = xstrdup ("TZ=");
247         }
248       else
249         {
250           size_t tz_len = strlen (initial_TZ);
251           char *buf = xmalloc (3 + tz_len + 1);
252           memcpy (mempcpy (buf, "TZ=", 3), initial_TZ, tz_len + 1);
253           initial_TZ = buf;
254         }
255     }
256
257   status = 0;
258   while (1)
259     {
260       line_length = getline (&line, &buflen, in_stream);
261       if (line_length < 0)
262         {
263           /* FIXME: detect/handle error here.  */
264           break;
265         }
266
267       if (universal_time)
268         {
269           /* When given a universal time option, restore the initial
270              value of TZ before parsing each string.  */
271           set_tz (initial_TZ);
272         }
273
274       when = get_date (line, NULL);
275
276       if (when == -1)
277         {
278           if (line[line_length - 1] == '\n')
279             line[line_length - 1] = '\0';
280           error (0, 0, _("invalid date `%s'"), line);
281           status = 1;
282         }
283       else
284         {
285           MAYBE_SET_TZ_UTC0;
286           show_date (format, when);
287         }
288     }
289
290   if (universal_time)
291     free (initial_TZ);
292
293   if (fclose (in_stream) == EOF)
294     error (2, errno, "`%s'", input_filename);
295
296   if (line != NULL)
297     free (line);
298
299   return status;
300 }
301
302 int
303 main (int argc, char **argv)
304 {
305   int optc;
306   const char *datestr = NULL;
307   const char *set_datestr = NULL;
308   time_t when;
309   int set_date = 0;
310   char *format;
311   char *batch_file = NULL;
312   char *reference = NULL;
313   struct stat refstats;
314   int n_args;
315   int status;
316   int option_specified_date;
317
318   program_name = argv[0];
319   setlocale (LC_ALL, "");
320   bindtextdomain (PACKAGE, LOCALEDIR);
321   textdomain (PACKAGE);
322
323   close_stdout_set_status (2);
324   atexit (close_stdout);
325
326   while ((optc = getopt_long (argc, argv, "d:f:I::r:Rs:u", long_options, NULL))
327          != -1)
328     switch (optc)
329       {
330       case 0:
331         break;
332       case 'd':
333         datestr = optarg;
334         break;
335       case 'f':
336         batch_file = optarg;
337         break;
338       case 'I':
339         iso_8601_format = (optarg
340                            ? XARGMATCH ("--iso-8601", optarg,
341                                         time_spec_string, time_spec)
342                            : TIME_SPEC_DATE);
343         break;
344       case 'r':
345         reference = optarg;
346         break;
347       case 'R':
348         rfc_format = 1;
349         break;
350       case 's':
351         set_datestr = optarg;
352         set_date = 1;
353         break;
354       case 'u':
355         universal_time = 1;
356         break;
357       case_GETOPT_HELP_CHAR;
358       case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
359       default:
360         usage (1);
361       }
362
363   n_args = argc - optind;
364
365   option_specified_date = ((datestr ? 1 : 0)
366                            + (batch_file ? 1 : 0)
367                            + (reference ? 1 : 0));
368
369   if (option_specified_date > 1)
370     {
371       error (0, 0,
372         _("the options to specify dates for printing are mutually exclusive"));
373       usage (1);
374     }
375
376   if (set_date && option_specified_date)
377     {
378       error (0, 0,
379           _("the options to print and set the time may not be used together"));
380       usage (1);
381     }
382
383   if (n_args > 1)
384     {
385       error (0, 0, _("too many non-option arguments"));
386       usage (1);
387     }
388
389   if ((set_date || option_specified_date)
390       && n_args == 1 && argv[optind][0] != '+')
391     {
392       error (0, 0, _("\
393 the argument `%s' lacks a leading `+';\n\
394 When using an option to specify date(s), any non-option\n\
395 argument must be a format string beginning with `+'."),
396              argv[optind]);
397       usage (1);
398     }
399
400   if (set_date)
401     datestr = set_datestr;
402
403   if (batch_file != NULL)
404     {
405       status = batch_convert (batch_file,
406                               (n_args == 1 ? argv[optind] + 1 : NULL));
407     }
408   else
409     {
410       status = 0;
411
412       if (!option_specified_date && !set_date)
413         {
414           if (n_args == 1 && argv[optind][0] != '+')
415             {
416               /* Prepare to set system clock to the specified date/time
417                  given in the POSIX-format.  */
418               set_date = 1;
419               datestr = argv[optind];
420               when = posixtime (datestr,
421                                 PDS_TRAILING_YEAR | PDS_CENTURY | PDS_SECONDS);
422               format = NULL;
423             }
424           else
425             {
426               /* Prepare to print the current date/time.  */
427               datestr = _("undefined");
428               time (&when);
429               format = (n_args == 1 ? argv[optind] + 1 : NULL);
430             }
431         }
432       else
433         {
434           /* (option_specified_date || set_date) */
435           if (reference != NULL)
436             {
437               if (stat (reference, &refstats))
438                 error (1, errno, "%s", reference);
439               when = refstats.st_mtime;
440             }
441           else
442             {
443               when = get_date (datestr, NULL);
444             }
445
446           format = (n_args == 1 ? argv[optind] + 1 : NULL);
447         }
448
449       if (when == -1)
450         error (1, 0, _("invalid date `%s'"), datestr);
451
452       if (set_date)
453         {
454           /* Set the system clock to the specified date, then regardless of
455              the success of that operation, format and print that date.  */
456           if (stime (&when) == -1)
457             {
458               error (0, errno, _("cannot set date"));
459               status = 1;
460             }
461         }
462
463       /* When given a universal time option, set TZ to UTC0 after
464          parsing the specified date, but before printing it.  */
465       MAYBE_SET_TZ_UTC0;
466
467       show_date (format, when);
468     }
469
470   exit (status);
471 }
472
473 /* Display the date and/or time in WHEN according to the format specified
474    in FORMAT, followed by a newline.  If FORMAT is NULL, use the
475    standard output format (ctime style but with a timezone inserted). */
476
477 static void
478 show_date (const char *format, time_t when)
479 {
480   struct tm *tm;
481   char *out = NULL;
482   size_t out_length = 0;
483   /* ISO 8601 formats, in local and UTC.  See below regarding %z */
484   static char *iso_format_string[5][2] =
485   {
486     {"", ""},
487     {"%Y-%m-%d", "%Y-%m-%d"},
488     {"%Y-%m-%dT%H%z", "%Y-%m-%dT%HZ"},
489     {"%Y-%m-%dT%H:%M%z", "%Y-%m-%dT%H:%MZ"},
490     {"%Y-%m-%dT%H:%M:%S%z", "%Y-%m-%dT%H:%M:%SZ"}
491   };
492
493   tm = localtime (&when);
494
495   if (format == NULL)
496     {
497       /* Print the date in the default format.  Vanilla ANSI C strftime
498          doesn't support %e, but POSIX requires it.  If you don't use
499          a GNU strftime, make sure yours supports %e.
500          If you are not using GNU strftime, you want to change %z
501          in the RFC format to %Z; this gives, however, an invalid
502          RFC time format outside the continental United States and GMT. */
503
504       if (rfc_format)
505         format = (universal_time
506                   ? "%a, %_d %b %Y %H:%M:%S GMT"
507                   : "%a, %_d %b %Y %H:%M:%S %z");
508       else if (iso_8601_format)
509         format = iso_format_string[iso_8601_format][universal_time];
510       else
511         {
512           char *date_fmt = DATE_FMT_LANGINFO ();
513           format = *date_fmt ? date_fmt : "%a %b %e %H:%M:%S %Z %Y";
514         }
515     }
516   else if (*format == '\0')
517     {
518       printf ("\n");
519       return;
520     }
521
522   if (rfc_format)
523     setlocale (LC_ALL, "C");
524
525   do
526     {
527       out_length += 200;
528       out = (char *) xrealloc (out, out_length);
529
530       /* Mark the first byte of the buffer so we can detect the case
531          of strftime producing an empty string.  Otherwise, this loop
532          would not terminate when date was invoked like this
533          `LANG=de date +%p' on a system with good language support.  */
534       out[0] = '\1';
535     }
536   while (strftime (out, out_length, format, tm) == 0 && out[0] != '\0');
537
538   printf ("%s\n", out);
539   free (out);
540 }