Whamcloud - gitweb
util: allow subst to build on systems that do not have utimes()
[tools/e2fsprogs.git] / util / subst.c
1 /*
2  * subst.c --- substitution program
3  *
4  * Subst is used as a quicky program to do @ substitutions
5  *
6  */
7
8 #ifdef HAVE_CONFIG_H
9 #include "config.h"
10 #else
11 #define HAVE_SYS_TIME_H
12 #endif
13 #include <stdio.h>
14 #include <errno.h>
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include <string.h>
18 #include <ctype.h>
19 #ifdef HAVE_SYS_TIME_H
20 #include <sys/time.h>
21 #endif
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <fcntl.h>
25 #include <time.h>
26 #include <utime.h>
27
28 #ifdef HAVE_GETOPT_H
29 #include <getopt.h>
30 #else
31 extern char *optarg;
32 extern int optind;
33 #endif
34
35
36 struct subst_entry {
37         char *name;
38         char *value;
39         struct subst_entry *next;
40 };
41
42 static struct subst_entry *subst_table = 0;
43
44 static int add_subst(char *name, char *value)
45 {
46         struct subst_entry      *ent = 0;
47
48         ent = (struct subst_entry *) malloc(sizeof(struct subst_entry));
49         if (!ent)
50                 goto fail;
51         ent->name = (char *) malloc(strlen(name)+1);
52         if (!ent->name)
53                 goto fail;
54         ent->value = (char *) malloc(strlen(value)+1);
55         if (!ent->value)
56                 goto fail;
57         strcpy(ent->name, name);
58         strcpy(ent->value, value);
59         ent->next = subst_table;
60         subst_table = ent;
61         return 0;
62 fail:
63         if (ent) {
64                 free(ent->name);
65                 free(ent);
66         }
67         return ENOMEM;
68 }
69
70 static struct subst_entry *fetch_subst_entry(char *name)
71 {
72         struct subst_entry *ent;
73
74         for (ent = subst_table; ent; ent = ent->next) {
75                 if (strcmp(name, ent->name) == 0)
76                         break;
77         }
78         return ent;
79 }
80
81 /*
82  * Given the starting and ending position of the replacement name,
83  * check to see if it is valid, and pull it out if it is.
84  */
85 static char *get_subst_symbol(const char *begin, size_t len, char prefix)
86 {
87         static char replace_name[128];
88         char *cp, *start;
89
90         start = replace_name;
91         if (prefix)
92                 *start++ = prefix;
93
94         if (len > sizeof(replace_name)-2)
95                 return NULL;
96         memcpy(start, begin, len);
97         start[len] = 0;
98
99         /*
100          * The substitution variable must all be in the of [0-9A-Za-z_].
101          * If it isn't, this must be an invalid symbol name.
102          */
103         for (cp = start; *cp; cp++) {
104                 if (!(*cp >= 'a' && *cp <= 'z') &&
105                     !(*cp >= 'A' && *cp <= 'Z') &&
106                     !(*cp >= '0' && *cp <= '9') &&
107                     !(*cp == '_'))
108                         return NULL;
109         }
110         return (replace_name);
111 }
112
113 static void replace_string(char *begin, char *end, char *newstr)
114 {
115         int     replace_len, len;
116
117         replace_len = strlen(newstr);
118         len = end - begin;
119         if (replace_len == 0)
120                 memmove(begin, end+1, strlen(end)+1);
121         else if (replace_len != len+1)
122                 memmove(end+(replace_len-len-1), end,
123                         strlen(end)+1);
124         memcpy(begin, newstr, replace_len);
125 }
126
127 static void substitute_line(char *line)
128 {
129         char    *ptr, *name_ptr, *end_ptr;
130         struct subst_entry *ent;
131         char    *replace_name;
132         size_t  len;
133
134         /*
135          * Expand all @FOO@ substitutions
136          */
137         ptr = line;
138         while (ptr) {
139                 name_ptr = strchr(ptr, '@');
140                 if (!name_ptr)
141                         break;  /* No more */
142                 if (*(++name_ptr) == '@') {
143                         /*
144                          * Handle tytso@@mit.edu --> tytso@mit.edu
145                          */
146                         memmove(name_ptr-1, name_ptr, strlen(name_ptr)+1);
147                         ptr = name_ptr+1;
148                         continue;
149                 }
150                 end_ptr = strchr(name_ptr, '@');
151                 if (!end_ptr)
152                         break;
153                 len = end_ptr - name_ptr;
154                 replace_name = get_subst_symbol(name_ptr, len, 0);
155                 if (!replace_name) {
156                         ptr = name_ptr;
157                         continue;
158                 }
159                 ent = fetch_subst_entry(replace_name);
160                 if (!ent) {
161                         fprintf(stderr, "Unfound expansion: '%s'\n",
162                                 replace_name);
163                         ptr = end_ptr + 1;
164                         continue;
165                 }
166 #if 0
167                 fprintf(stderr, "Replace name = '%s' with '%s'\n",
168                        replace_name, ent->value);
169 #endif
170                 ptr = name_ptr-1;
171                 replace_string(ptr, end_ptr, ent->value);
172                 if ((ent->value[0] == '@') &&
173                     (strlen(replace_name) == strlen(ent->value)-2) &&
174                     !strncmp(replace_name, ent->value+1,
175                              strlen(ent->value)-2))
176                         /* avoid an infinite loop */
177                         ptr += strlen(ent->value);
178         }
179         /*
180          * Now do a second pass to expand ${FOO}
181          */
182         ptr = line;
183         while (ptr) {
184                 name_ptr = strchr(ptr, '$');
185                 if (!name_ptr)
186                         break;  /* No more */
187                 if (*(++name_ptr) != '{') {
188                         ptr = name_ptr;
189                         continue;
190                 }
191                 name_ptr++;
192                 end_ptr = strchr(name_ptr, '}');
193                 if (!end_ptr)
194                         break;
195                 len = end_ptr - name_ptr;
196                 replace_name = get_subst_symbol(name_ptr, len, '$');
197                 if (!replace_name) {
198                         ptr = name_ptr;
199                         continue;
200                 }
201                 ent = fetch_subst_entry(replace_name);
202                 if (!ent) {
203                         ptr = end_ptr + 1;
204                         continue;
205                 }
206 #if 0
207                 fprintf(stderr, "Replace name = '%s' with '%s'\n",
208                        replace_name, ent->value);
209 #endif
210                 ptr = name_ptr-2;
211                 replace_string(ptr, end_ptr, ent->value);
212         }
213 }
214
215 static void parse_config_file(FILE *f)
216 {
217         char    line[2048];
218         char    *cp, *ptr;
219
220         while (!feof(f)) {
221                 memset(line, 0, sizeof(line));
222                 if (fgets(line, sizeof(line), f) == NULL)
223                         break;
224                 /*
225                  * Strip newlines and comments.
226                  */
227                 cp = strchr(line, '\n');
228                 if (cp)
229                         *cp = 0;
230                 cp = strchr(line, '#');
231                 if (cp)
232                         *cp = 0;
233                 /*
234                  * Skip trailing and leading whitespace
235                  */
236                 for (cp = line + strlen(line) - 1; cp >= line; cp--) {
237                         if (*cp == ' ' || *cp == '\t')
238                                 *cp = 0;
239                         else
240                                 break;
241                 }
242                 cp = line;
243                 while (*cp && isspace(*cp))
244                         cp++;
245                 ptr = cp;
246                 /*
247                  * Skip empty lines
248                  */
249                 if (*ptr == 0)
250                         continue;
251                 /*
252                  * Ignore future extensions
253                  */
254                 if (*ptr == '@')
255                         continue;
256                 /*
257                  * Parse substitutions
258                  */
259                 for (cp = ptr; *cp; cp++)
260                         if (isspace(*cp))
261                                 break;
262                 *cp = 0;
263                 for (cp++; *cp; cp++)
264                         if (!isspace(*cp))
265                                 break;
266 #if 0
267                 printf("Substitute: '%s' for '%s'\n", ptr, cp ? cp : "<NULL>");
268 #endif
269                 add_subst(ptr, cp);
270         }
271 }
272
273 /*
274  * Return 0 if the files are different, 1 if the files are the same.
275  */
276 static int compare_file(FILE *old_f, FILE *new_f)
277 {
278         char    oldbuf[2048], newbuf[2048], *oldcp, *newcp;
279         int     retval;
280
281         while (1) {
282                 oldcp = fgets(oldbuf, sizeof(oldbuf), old_f);
283                 newcp = fgets(newbuf, sizeof(newbuf), new_f);
284                 if (!oldcp && !newcp) {
285                         retval = 1;
286                         break;
287                 }
288                 if (!oldcp || !newcp || strcmp(oldbuf, newbuf)) {
289                         retval = 0;
290                         break;
291                 }
292         }
293         return retval;
294 }
295
296 void set_utimes(const char *filename, int fd, const struct timeval times[2])
297 {
298 #ifdef HAVE_FUTIMES
299         if (futimes(fd, times) < 0)
300                 perror("futimes");
301 #elif HAVE_UTIMES
302         if (utimes(filename, times) < 0)
303                 perror("utimes");
304 #else
305         struct utimbuf ut;
306
307         ut.actime = times[0].tv_sec;
308         ut.modtime = times[1].tv_sec;
309         if (utime(filename, &ut) < 0)
310                 perror("utime");
311 #endif
312 }
313
314
315 int main(int argc, char **argv)
316 {
317         char    line[2048];
318         int     c;
319         int     fd;
320         FILE    *in, *out, *old = NULL;
321         char    *outfn = NULL, *newfn = NULL;
322         int     verbose = 0;
323         int     adjust_timestamp = 0;
324         int     got_atime = 0;
325         struct stat stbuf;
326         struct timeval tv[2];
327
328         while ((c = getopt (argc, argv, "f:tv")) != EOF) {
329                 switch (c) {
330                 case 'f':
331                         in = fopen(optarg, "r");
332                         if (!in) {
333                                 perror(optarg);
334                                 exit(1);
335                         }
336                         parse_config_file(in);
337                         fclose(in);
338                         break;
339                 case 't':
340                         adjust_timestamp++;
341                         break;
342                 case 'v':
343                         verbose++;
344                         break;
345                 default:
346                         fprintf(stderr, "%s: [-f config-file] [file]\n",
347                                 argv[0]);
348                         break;
349                 }
350         }
351         if (optind < argc) {
352                 in = fopen(argv[optind], "r");
353                 if (!in) {
354                         perror(argv[optind]);
355                         exit(1);
356                 }
357                 optind++;
358         } else
359                 in = stdin;
360
361         if (optind < argc) {
362                 outfn = argv[optind];
363                 newfn = (char *) malloc(strlen(outfn)+20);
364                 if (!newfn) {
365                         fprintf(stderr, "Memory error!  Exiting.\n");
366                         exit(1);
367                 }
368                 strcpy(newfn, outfn);
369                 strcat(newfn, ".new");
370                 fd = open(newfn, O_CREAT|O_TRUNC|O_RDWR, 0444);
371                 if (fd < 0) {
372                         perror(newfn);
373                         exit(1);
374                 }
375                 out = fdopen(fd, "w+");
376                 if (!out) {
377                         perror("fdopen");
378                         exit(1);
379                 }
380
381                 fd = open(outfn, O_RDONLY);
382                 if (fd > 0) {
383                         /* save the original atime, if possible */
384                         if (fstat(fd, &stbuf) == 0) {
385 #if HAVE_STRUCT_STAT_ST_ATIM
386                                 tv[0].tv_sec = stbuf.st_atim.tv_sec;
387                                 tv[0].tv_usec = stbuf.st_atim.tv_nsec / 1000;
388 #else
389                                 tv[0].tv_sec = stbuf.st_atime;
390                                 tv[0].tv_usec = 0;
391 #endif
392                                 got_atime = 1;
393                         }
394                         old = fdopen(fd, "r");
395                         if (!old)
396                                 close(fd);
397                 }
398         } else {
399                 out = stdout;
400                 outfn = 0;
401         }
402
403         while (!feof(in)) {
404                 if (fgets(line, sizeof(line), in) == NULL)
405                         break;
406                 substitute_line(line);
407                 fputs(line, out);
408         }
409         fclose(in);
410         if (outfn) {
411                 fflush(out);
412                 rewind(out);
413                 if (old && compare_file(old, out)) {
414                         if (verbose)
415                                 printf("No change, keeping %s.\n", outfn);
416                         if (adjust_timestamp) {
417                                 if (verbose)
418                                         printf("Updating modtime for %s\n", outfn);
419                                 if (gettimeofday(&tv[1], NULL) < 0) {
420                                         perror("gettimeofday");
421                                         exit(1);
422                                 }
423                                 if (got_atime == 0)
424                                         tv[0] = tv[1];
425                                 else if (verbose)
426                                         printf("Using original atime\n");
427                                 set_utimes(outfn, fileno(old), tv);
428                         }
429                         fclose(out);
430                         if (unlink(newfn) < 0)
431                                 perror("unlink");
432                 } else {
433                         if (verbose)
434                                 printf("Creating or replacing %s.\n", outfn);
435                         fclose(out);
436                         if (old)
437                                 fclose(old);
438                         old = NULL;
439                         if (rename(newfn, outfn) < 0) {
440                                 perror("rename");
441                                 exit(1);
442                         }
443                 }
444         }
445         if (old)
446                 fclose(old);
447         return (0);
448 }
449
450