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