Debian Codegraph @

src/main.c

raw symbols SCIP
1 /* Conversion of files between different charsets and surfaces.
2 Copyright © 1990-2023 Free Software Foundation, Inc.
3 François Pinard <[email protected]>, 1990.
4
5 This program is free software; you can redistribute it and/or modify it
6 under the terms of the GNU General Public License as published by the
7 Free Software Foundation; either version 3, or (at your option) any later
8 version.
9
10 This program is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
13 Public License for more details.
14
15 You should have received a copy of the GNU General Public License along
16 along with this program; if not, see <https://www.gnu.org/licenses/>.
17 */
18
19 #include "config.h"
20 #include "common.h"
21
22 #include <ctype.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <unistd.h>
26 #include <libgen.h>
27 #include <utime.h>
28 #include <setjmp.h>
29 #include <locale.h>
30
31 #include "getopt.h"
32 #include "xbinary-io.h"
33
34 /* Variables. */
35
36 /* The name this program was run with. */
37 const char *program_name;
38
39 /* If nonzero, display usage information and exit. */
40 static int show_help = 0;
41
42 /* If nonzero, print the version on standard output and exit. */
43 static int show_version = 0;
44
45 /* If true, show a list of one or all known charsets, then exit. */
46 static bool show_symbols = false;
47
48 /* If true, check all charsets for subsets, then exit. */
49 static bool find_subsets = false;
50
51 /* User provided list of charset restrictions (option -k). */
52 static const char *charset_restrictions = NULL;
53
54 /* Indicates the format for showing only one charset. */
55 enum recode_list_format list_format = RECODE_NO_FORMAT;
56
57 /* Table name in generated language code. */
58 static const char *header_name;
59
60 /* Language to use for generated code. */
61 static enum recode_programming_language header_language;
62
63 /* This option asks recode to report the progress while recoding many files
64 in a single call. */
65 static bool verbose_flag = false;
66
67 /* This option merely inhibits messages about non-reversible recodings, but
68 it does not prevent recodings to be aborted or exit status to be set. */
69 static bool quiet_flag = false;
70
71 /* If the recoding yields some problems in recode_reversibility in some file, this
72 file replacement is denied and it is left unrecoded or, if recode is used
73 as a mere filter, the recoding is aborted. The following flag forces
74 the recoding to run to completion and the replacement to be done even if
75 the recoding is not reversible. */
76 static bool force_flag = false;
77
78 /* When a file is recoded over itself, precautions are taken to move the
79 timestamps of the original file into the recoded file, so to make the
80 recoding the most transparent possible to make, and other tools.
81 However, selecting the following option inhibit the timestamps handling,
82 thus effectively `touching' the file. */
83 static bool touch_option = false;
84
85 /* With strict mapping, all recode_reversibility fallbacks get defeated. */
86 static bool strict_mapping = false;
87
88 /* Use iconv if possible. */
89 static bool prefer_iconv = false;
90
91 /* The following charset name will be ignored, if given. */
92 static const char *ignored_name = NULL;
93
94 /* Ordinals of list, BEFORE and AFTER charset. */
95 static RECODE_SYMBOL list_charset;
96
97 /* Flag telling usage that we are decoding charsets. */
98 bool decoding_charset_flag = false;
99
100 /* Error handling. */
101
102 /*-------------------------------------------------.
103 | Produce a message explaining the error in TASK. |
104 `-------------------------------------------------*/
105
106 static const char *
107 task_perror (RECODE_CONST_TASK task)
108 {
109 switch (task->error_so_far)
110 {
111 case RECODE_NO_ERROR:
112 return _("No error");
113
114 case RECODE_NOT_CANONICAL:
115 return _("Non canonical input");
116
117 case RECODE_AMBIGUOUS_OUTPUT:
118 return _("Ambiguous output");
119
120 case RECODE_UNTRANSLATABLE:
121 return _("Untranslatable input");
122
123 case RECODE_INVALID_INPUT:
124 return _("Invalid input");
125
126 case RECODE_SYSTEM_ERROR:
127 return _("System detected problem");
128
129 case RECODE_USER_ERROR:
130 return _("Misuse of recoding library");
131
132 default:
133 return _("Internal recoding bug");
134 }
135 }
136
137 /*-----------------.
138 | Signal handler. |
139 `-----------------*/
140
141 #ifdef HAVE_PIPE
142 static void
143 sig_catch(int sig, void (*handler) (int))
144 {
145 struct sigaction sa;
146 sa.sa_handler = handler;
147 sa.sa_flags = 0;
148 sigemptyset (&sa.sa_mask);
149 sigaction (sig, &sa, NULL); /* ignore error: none possible */
150 }
151
152 static void
153 signal_handler (int number)
154 {
155 recode_interrupted = 1;
156 sig_catch (number, signal_handler);
157 }
158
159 static void
160 setup_signals (void)
161 {
162 sig_catch (SIGPIPE, signal_handler);
163 }
164 #endif
165
166 /* Main control. */
167
168 /*-----------------------------------.
169 | Prints a more detailed Copyright. |
170 `-----------------------------------*/
171
172 static void
173 print_copyright (void)
174 {
175 fputs (_("\
176 This program is free software; you can redistribute it and/or modify\n\
177 it under the terms of the GNU General Public License as published by\n\
178 the Free Software Foundation; either version 3, or (at your option)\n\
179 any later version.\n\
180 \n\
181 This program is distributed in the hope that it will be useful,\n\
182 but WITHOUT ANY WARRANTY; without even the implied warranty of\n\
183 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\
184 GNU General Public License for more details.\n\
185 \n\
186 You should have received a copy of the GNU General Public License\n\
187 along with this program; if not, see <https://www.gnu.org/licenses/>.\n"),
188 stdout);
189 }
190
191 /*-----------------------------------------------.
192 | Explain how to use the program, then get out. |
193 `-----------------------------------------------*/
194
195 static void
196 usage (int status, bool list)
197 {
198 if (status != EXIT_SUCCESS)
199 fprintf (stderr, _("Try `%s %s' for more information.\n"), program_name,
200 list ? "--list" : "--help");
201 else
202 {
203 fputs (_("\
204 Recode converts files between various character sets and surfaces.\n\
205 "),
206 stdout);
207 printf (_("\
208 \n\
209 Usage: %s [OPTION]... [ [CHARSET] | REQUEST [FILE]... ]\n"), program_name);
210 fputs (_("\
211 \n\
212 If a long option shows an argument as mandatory, then it is mandatory\n\
213 for the equivalent short option also. Similarly for optional arguments.\n\
214 "),
215 stdout);
216 fputs (_("\
217 \n\
218 Listings:\n\
219 -l, --list[=FORMAT] list one or all known charsets and aliases\n\
220 -k, --known=PAIRS restrict charsets according to known PAIRS list\n\
221 -h, --header[=[LN/]NAME] write table NAME on stdout using LN, then exit\n\
222 -T, --find-subsets report all charsets being subset of others\n\
223 -C, --copyright display copyright and copying conditions\n\
224 --help display this help and exit\n\
225 --version output version information and exit\n\
226 "),
227 stdout);
228 fputs (_("\
229 \n\
230 Operation modes:\n\
231 -v, --verbose explain sequence of steps and report progress\n\
232 -q, --quiet, --silent inhibit messages about irreversible recodings\n\
233 -f, --force force recodings even when not reversible\n\
234 -t, --touch touch the recoded files after replacement\n\
235 -i, -p, --sequence=STRATEGY ignored for backwards compatibility\n\
236 "),
237 stdout);
238 fputs (_("\
239 \n\
240 Fine tuning:\n\
241 -s, --strict use strict mappings; discard untranslatable characters\n\
242 -d, --diacritics convert only diacritics and special characters for\n\
243 HTML/LaTeX/BibTeX\n\
244 -S, --source[=LN] limit recoding to strings and comments as for LN\n\
245 -c, --colons use colons instead of double quotes for diaeresis\n\
246 -g, --graphics approximate IBMPC rulers by ASCII graphics\n\
247 -x, --ignore=CHARSET ignore CHARSET while choosing a recoding path\n\
248 -I, --prefer-iconv use iconv if possible\n\
249 "),
250 stdout);
251 fputs (_("\
252 \n\
253 Option -l with no FORMAT nor CHARSET list available charsets and surfaces.\n\
254 FORMAT is `decimal', `octal', `hexadecimal' or `full' (or one of `dohf').\n\
255 "),
256 stdout);
257 fputs (_("\
258 Unless DEFAULT_CHARSET is set in environment, CHARSET defaults to the locale\n\
259 dependent encoding, determined by LC_ALL, LC_CTYPE, LANG.\n\
260 "),
261 stdout);
262 fputs (_("\
263 With -k, possible before charsets are listed for the given after CHARSET,\n\
264 both being tabular charsets, with PAIRS of the form `BEF1:AFT1,BEF2:AFT2,...'\n\
265 and BEFs and AFTs being codes are given as decimal numbers.\n"),
266 stdout);
267 fputs (_("\
268 LN is some language, it may be `c', `perl' or `po'; `c' is the default.\n"),
269 stdout);
270 fputs (_("\
271 \n\
272 REQUEST is SUBREQUEST[,SUBREQUEST]...; SUBREQUEST is ENCODING[..ENCODING]...\n\
273 ENCODING is [CHARSET][/[SURFACE]]...; REQUEST often looks like BEFORE..AFTER,\n\
274 with BEFORE and AFTER being charsets. An omitted CHARSET implies the usual\n\
275 charset; an omitted [/SURFACE]... means the implied surfaces for CHARSET; a /\n\
276 with an empty surface name means no surfaces at all. See the manual.\n"),
277 stdout);
278 fputs (_("\
279 \n\
280 Each FILE is recoded over itself, destroying the original. If no\n\
281 FILE is specified, then act as a filter and recode stdin to stdout.\n"),
282 stdout);
283 fputs (_("\
284 \n\
285 Report bugs at https://github.com/rrthomas/recode\n"),
286 stdout);
287 }
288 exit (status);
289 }
290
291 /*----------------------------------------------------------------------.
292 | Main program. Decode ARGC arguments passed through the ARGV array of |
293 | strings, then launch execution. |
294 `----------------------------------------------------------------------*/
295
296 /* Long options equivalences. */
297 static const struct option long_options[] =
298 {
299 {"colons", no_argument, NULL, 'c'},
300 {"copyright", no_argument, NULL, 'C'},
301 {"diacritics", no_argument, NULL, 'd'},
302 {"find-subsets", no_argument, NULL, 'T'},
303 {"force", no_argument, NULL, 'f'},
304 {"header", optional_argument, NULL, 'h'},
305 {"help", no_argument, &show_help, 1},
306 {"ignore", required_argument, NULL, 'x'},
307 {"known", required_argument, NULL, 'k'},
308 {"list", optional_argument, NULL, 'l'},
309 {"prefer-iconv", no_argument, NULL, 'I'},
310 {"quiet", no_argument, NULL, 'q'},
311 {"sequence", required_argument, NULL, '\n'},
312 {"source", optional_argument, NULL, 'S'},
313 {"silent", no_argument, NULL, 'q'},
314 {"strict", no_argument, NULL, 's'},
315 {"touch", no_argument, NULL, 't'},
316 {"verbose", no_argument, NULL, 'v'},
317 {"version", no_argument, &show_version, 1},
318 {0, 0, 0, 0},
319 };
320
321 static const char *const format_strings[]
322 = { "decimal", "octal", "hexadecimal", "full", NULL };
323
324 static const char *const language_strings[]
325 = { "c", "perl", "po", NULL };
326
327 static const char *const sequence_strings[]
328 = { "memory", "files", "pipe", NULL };
329
330
331 static RECODE_OUTER
332 new_outer(unsigned flags)
333 {
334 /* Register all modules and build internal tables. */
335
336 RECODE_OUTER outer =
337 recode_new_outer (flags | RECODE_AUTO_ABORT_FLAG);
338 if (!outer)
339 abort ();
340
341 /* If using strict mapping, remove fallbacks. */
342
343 if (outer->strict_mapping)
344 for (RECODE_SINGLE single = outer->single_list;
345 single;
346 single = single->next)
347 single->fallback_routine = NULL;
348
349 /* Set the ignored charset. */
350
351 if (ignored_name)
352 {
353 RECODE_ALIAS alias
354 = recode_find_alias (outer, ignored_name, ALIAS_FIND_AS_CHARSET);
355
356 if (!alias)
357 {
358 error (0, 0, _("Symbol `%s' is unknown"), ignored_name);
359 usage (EXIT_FAILURE, 1);
360 }
361
362 alias->symbol->ignore = true;
363 }
364
365 return outer;
366 }
367
368 static RECODE_REQUEST
369 new_request(RECODE_OUTER outer, struct recode_request *request_option)
370 {
371 RECODE_REQUEST request = recode_new_request (outer);
372 request->ascii_graphics = request_option->ascii_graphics;
373 request->diacritics_only = request_option->diacritics_only;
374 request->diaeresis_char = request_option->diaeresis_char;
375 request->make_header_flag = request_option->make_header_flag;
376 return request;
377 }
378
379 int
380 main (int argc, char *const *argv)
381 {
382 int option_char; /* option character */
383 bool success = true; /* recode_reversibility of all recodings */
384
385 static bool (*processor) (RECODE_TASK);
386 struct recode_outer outer_option;
387 struct recode_request request_option;
388 struct recode_task task_option;
389
390 program_name = argv[0];
391 /* libtool creates a temporary executable whose names is prefixed with
392 "lt-". Remove this prefix here. */
393 if (strncmp (program_name, "lt-", 3) == 0)
394 program_name += 3;
395
396 setlocale (LC_ALL, "");
397 textdomain (PACKAGE);
398
399 /* Decode command options. */
400
401 if (argc == 1)
402 usage (EXIT_SUCCESS, 0);
403
404 processor = recode_perform_task;
405 memset (&outer_option, 0, sizeof (struct recode_outer));
406 memset (&request_option, 0, sizeof (struct recode_request));
407 memset (&task_option, 0, sizeof (struct recode_task));
408
409 request_option.diaeresis_char = '"';
410 task_option.fail_level = RECODE_AMBIGUOUS_OUTPUT;
411 task_option.abort_level = RECODE_AMBIGUOUS_OUTPUT;
412
413 while (option_char = getopt_long (argc, argv, "CIFS::Tcdfgh::ik:l::pqstvx:",
414 long_options, NULL),
415 option_char != -1)
416 switch (option_char)
417 {
418 default:
419 usage (EXIT_FAILURE, 0);
420
421 case NUL:
422 break;
423
424 case '\n':
425 switch (argmatch (optarg, sequence_strings, NULL, 0))
426 {
427 case -2:
428 error (0, 0, _("Sequence `%s' is ambiguous"), optarg);
429 usage (EXIT_FAILURE, 0);
430 break;
431
432 case -1:
433 error (0, 0, _("Sequence `%s' is unknown"), optarg);
434 usage (EXIT_FAILURE, 0);
435 break;
436
437 /* Ignore for backwards compatibility with version 3.6. */
438 case 0:
439 case 1:
440 case 2:
441 break;
442
443 default:
444 break;
445 }
446 break;
447
448 case 'C':
449 print_copyright ();
450 exit (EXIT_SUCCESS);
451
452 case 'I':
453 prefer_iconv = true;
454 break;
455
456 case 'S':
457 if (optarg)
458 switch (argmatch (optarg, language_strings, NULL, 0))
459 {
460 case -2:
461 error (0, 0, _("Language `%s' is ambiguous"), optarg);
462 usage (EXIT_FAILURE, 0);
463 break;
464
465 default: /* -1 */
466 error (0, 0, _("Language `%s' is unknown"), optarg);
467 usage (EXIT_FAILURE, 0);
468 break;
469
470 case 0:
471 processor = recode_transform_c_source;
472 break;
473
474 case 2:
475 processor = recode_transform_po_source;
476 break;
477 }
478 else
479 processor = recode_transform_c_source;
480 break;
481
482 case 'T':
483 find_subsets = true;
484 break;
485
486 case 'c':
487 request_option.diaeresis_char = ':';
488 break;
489
490 case 'd':
491 request_option.diacritics_only = true;
492 break;
493
494 case 'f':
495 task_option.fail_level = RECODE_SYSTEM_ERROR;
496 task_option.abort_level = RECODE_USER_ERROR;
497 force_flag = true;
498 break;
499
500 case 'g':
501 request_option.ascii_graphics = true;
502 break;
503
504 case 'h':
505 request_option.make_header_flag = true;
506 header_name = optarg ? strrchr (optarg, '/') : NULL;
507 if (header_name)
508 {
509 char *buffer;
510 unsigned counter;
511
512 header_name++;
513 buffer = (char *) xmalloc ((size_t) (header_name - optarg));
514 if (*header_name == NUL)
515 header_name = NULL;
516 for (counter = 0; optarg[counter] != '/'; counter++)
517 buffer[counter] = tolower (optarg[counter]);
518 buffer[counter] = NUL;
519 switch (argmatch (buffer, language_strings, NULL, 0))
520 {
521 case -2:
522 error (0, 0, _("Language `%s' is ambiguous"), buffer);
523 usage (EXIT_FAILURE, 0);
524 break;
525
526 default: /* -1 */
527 error (0, 0, _("Language `%s' is unknown"), buffer);
528 usage (EXIT_FAILURE, 0);
529 break;
530
531 case 0:
532 header_language = RECODE_LANGUAGE_C;
533 break;
534
535 case 1:
536 header_language = RECODE_LANGUAGE_PERL;
537 break;
538 }
539 free (buffer);
540 }
541 else
542 {
543 header_name = optarg;
544 header_language = RECODE_LANGUAGE_C;
545 }
546 break;
547
548 case 'i':
549 /* Ignore for backwards compatibility with version 3.6. */
550 break;
551
552 case 'k':
553 charset_restrictions = optarg;
554 break;
555
556 case 'l':
557 show_symbols = true;
558 if (optarg)
559 switch (argmatch (optarg, format_strings, NULL, 0))
560 {
561 case -2:
562 error (0, 0, _("Format `%s' is ambiguous"), optarg);
563 usage (EXIT_FAILURE, 0);
564 break;
565
566 case -1:
567 error (0, 0, _("Format `%s' is unknown"), optarg);
568 usage (EXIT_FAILURE, 0);
569 break;
570
571 case 0:
572 list_format = RECODE_DECIMAL_FORMAT;
573 break;
574
575 case 1:
576 list_format = RECODE_OCTAL_FORMAT;
577 break;
578
579 case 2:
580 list_format = RECODE_HEXADECIMAL_FORMAT;
581 break;
582
583 case 3:
584 list_format = RECODE_FULL_FORMAT;
585 break;
586
587 default:
588 break;
589 }
590 break;
591
592 case 'p':
593 /* Ignore for backwards compatibility with version 3.6. */
594 break;
595
596 case 'q':
597 quiet_flag = true;
598 break;
599
600 case 's':
601 strict_mapping = true;
602 task_option.fail_level = RECODE_NOT_CANONICAL;
603 task_option.abort_level = RECODE_NOT_CANONICAL;
604 break;
605
606 case 't':
607 touch_option = true;
608 break;
609
610 case 'v':
611 verbose_flag = true;
612 break;
613
614 case 'x':
615 ignored_name = optarg;
616 break;
617 }
618
619 if (request_option.ascii_graphics)
620 force_flag = true;
621
622 /* Process trivial options. */
623
624 if (show_version)
625 {
626 printf ("%s %s\n", PACKAGE, VERSION);
627 fputs (_("\
628 Written by François Pinard <[email protected]>.\n"),
629 stdout);
630 fputs (_("\
631 \n\
632 Copyright (C) 1990-2023 Free Software Foundation, Inc.\n"),
633 stdout);
634 fputs (_("\
635 This is free software; see the source for copying conditions. There is NO\n\
636 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"),
637 stdout);
638 exit (EXIT_SUCCESS);
639 }
640
641 if (show_help)
642 usage (EXIT_SUCCESS, 0);
643
644 /* Set up the outer level. */
645
646 unsigned flags = 0;
647 if ((ignored_name && *ignored_name == ':')
648 || request_option.make_header_flag)
649 flags |= RECODE_NO_ICONV_FLAG;
650 if (strict_mapping)
651 flags |= RECODE_STRICT_MAPPING_FLAG;
652 if (force_flag)
653 flags |= RECODE_FORCE_FLAG;
654 RECODE_OUTER outer = new_outer (flags);
655
656 /* Process charset listing options. */
657
658 if (find_subsets)
659 {
660 recode_find_and_report_subsets (outer);
661 exit (EXIT_SUCCESS);
662 }
663
664 if (show_symbols || charset_restrictions)
665 {
666 if (charset_restrictions)
667 if (!recode_decode_known_pairs (outer, charset_restrictions))
668 {
669 error (0, 0, "Could not understand `%s'", charset_restrictions);
670 usage (EXIT_FAILURE, 0);
671
672 }
673 if (optind + 1 < argc)
674 {
675 error (0, 0, "Argument `%s' is extraneous", argv[optind]);
676 usage (EXIT_FAILURE, 0);
677 }
678
679 /* Select a possible charset and a default format. */
680
681 if (optind < argc)
682 {
683 RECODE_ALIAS alias
684 = recode_find_alias (outer, argv[optind], ALIAS_FIND_AS_CHARSET);
685
686 if (!alias)
687 {
688 error (0, 0, _("Charset `%s' is unknown or ambiguous"),
689 argv[optind]);
690 usage (EXIT_FAILURE, 1);
691 }
692
693 list_charset = alias->symbol;
694 }
695 else if (list_format != RECODE_NO_FORMAT || charset_restrictions)
696 {
697 RECODE_ALIAS alias
698 = recode_find_alias (outer, NULL, ALIAS_FIND_AS_CHARSET);
699
700 if (!alias)
701 {
702 error (0, 0, _("Charset `%s' is unknown or ambiguous"),
703 argv[optind]);
704 usage (EXIT_FAILURE, 1);
705 }
706
707 list_charset = alias->symbol;
708 }
709 else
710 list_charset = NULL;
711
712 /* List the charset(s) appropriately. */
713
714 if (charset_restrictions)
715 recode_list_all_symbols (outer, list_charset);
716 else if (list_charset)
717 if (list_format == RECODE_FULL_FORMAT)
718 recode_list_full_charset (outer, list_charset);
719 else
720 recode_list_concise_charset (outer, list_charset, list_format);
721 else
722 recode_list_all_symbols (outer, NULL);
723
724 /* Then get out. */
725
726 exit (EXIT_SUCCESS);
727 }
728
729 /* Decode the REQUEST argument. */
730
731 if (optind + 1 > argc)
732 {
733 error (0, 0, _("Required argument is missing"));
734 usage (EXIT_FAILURE, 0);
735 }
736
737 RECODE_REQUEST request = new_request (outer, &request_option);
738
739 const char *user_request = argv[optind];
740
741 if (!recode_scan_request (request, user_request))
742 error (EXIT_FAILURE, 0, _("Request `%s' is erroneous"), user_request);
743
744 /* If we merely want source code, do it and get out. */
745
746 if (request_option.make_header_flag)
747 {
748 recode_format_table (request, header_language, header_name);
749 exit (EXIT_SUCCESS);
750 }
751
752 /* If we are recoding, and we are allowed to use iconv, and --prefer-iconv
753 was not used, see if we can do it without iconv. */
754
755 if ((flags & RECODE_NO_ICONV_FLAG) == 0 && !prefer_iconv)
756 {
757 RECODE_OUTER no_iconv_outer = new_outer (RECODE_NO_ICONV_FLAG);
758 RECODE_REQUEST no_iconv_request =
759 new_request (no_iconv_outer, &request_option);
760
761 if (recode_scan_request (no_iconv_request, user_request))
762 {
763 recode_delete_request (request);
764 recode_delete_outer (outer);
765 outer = no_iconv_outer;
766 request = no_iconv_request;
767 }
768 }
769
770 /* Scan the request once more to get output if in verbose mode. */
771 if (verbose_flag)
772 {
773 request->verbose_flag = true;
774 recode_scan_request (request, user_request);
775 }
776
777 /* Discard the request argument. */
778 optind++;
779
780 #if HAVE_PIPE
781 setup_signals ();
782 #endif
783
784 {
785 RECODE_TASK task;
786
787 task = recode_new_task (request);
788 task->fail_level = task_option.fail_level;
789 task->abort_level = task_option.fail_level;
790
791 /* If there is no input file, act as a filter. Else, recode all files
792 over themselves. */
793
794 if (optind < argc)
795 {
796 /* In case files are recoded over themselves and there is no
797 recoding step at all, do not even try to touch the files. */
798
799 if (request->sequence_length > 0)
800
801 /* Process files, one at a time. */
802
803 for (; optind < argc; optind++)
804 {
805 const char *input_name;
806 FILE *file;
807 struct stat file_stat;
808 struct utimbuf file_utime;
809
810 input_name = realpath (argv[optind], NULL);
811 if (input_name == NULL)
812 error (EXIT_FAILURE, errno, "realpath (%s)", argv[optind]);
813
814 /* Check if the file can be read and rewritten. */
815
816 if (file = fopen (input_name, "r+"), file == NULL)
817 error (EXIT_FAILURE, errno, "fopen (%s)", input_name);
818
819 /* Save the input file attributes. */
820
821 fstat (fileno (file), &file_stat);
822 fclose (file);
823
824 /* Choose an output file in the same directory. */
825
826 char *input_name_copy = xstrdup (input_name);
827 char *output_dir = dirname (input_name_copy);
828 char *output_name;
829 if (asprintf (&output_name, "%s/recode-XXXXXX.tmp", output_dir) == -1)
830 error (EXIT_FAILURE, errno, "asprintf");
831 int fd = mkstemps (output_name, 4);
832 if (fd == -1)
833 error (EXIT_FAILURE, errno, "mkstemps (%s)", output_name);
834 xset_binary_mode (fd, O_BINARY);
835
836 /* Recode the file. */
837
838 task->input.name = input_name;
839 task->output.name = NULL;
840 task->output.file = fdopen (fd, "w+");
841 if (task->output.file == NULL)
842 error (EXIT_FAILURE, errno, "fdopen ()");
843
844 if (verbose_flag)
845 {
846 fprintf (stderr, _("Recoding %s..."), task->input.name);
847 fflush (stderr);
848 }
849
850 if ((*processor) (task))
851 {
852 /* Recoding was successful. */
853
854 if (verbose_flag)
855 {
856 fprintf (stderr, _(" done\n"));
857 fflush (stderr);
858 }
859
860 /* Close the file. */
861
862 if (fclose (task->output.file) == EOF)
863 error (EXIT_FAILURE, errno, "close ()");
864
865 /* Move the new file over the original. */
866
867 if (unlink (input_name) < 0)
868 error (EXIT_FAILURE, errno, "unlink (%s)", input_name);
869
870 /* Preserve the file permissions if possible. */
871
872 chmod (output_name, file_stat.st_mode & 07777);
873
874 if (rename (output_name, input_name) < 0)
875 error (EXIT_FAILURE, errno, "rename (%s, %s)",
876 output_name, input_name);
877
878 /* Adjust the time stamp for the new file. */
879
880 if (!touch_option)
881 {
882 file_utime.actime = file_stat.st_atime;
883 file_utime.modtime = file_stat.st_mtime;
884 utime (input_name, &file_utime);
885 }
886 }
887 else
888 {
889 /* Recoding failed, discard output. */
890
891 success = false;
892 if (verbose_flag)
893 {
894 fprintf (stderr, _(" failed: %s%s%s%s%s%s\n"),
895 task_perror (task),
896 task->error_at_step ? _(" in step `") : "",
897 task->error_at_step ? task->error_at_step->before->name : "",
898 task->error_at_step ? _("..") : "",
899 task->error_at_step ? task->error_at_step->after->name : "",
900 task->error_at_step ? _("'") : "");
901 fflush (stderr);
902 }
903 else if (!quiet_flag)
904 error (0, 0, _("%s failed: %s%s%s%s%s%s"),
905 input_name, task_perror (task),
906 task->error_at_step ? _(" in step `") : "",
907 task->error_at_step ? task->error_at_step->before->name : "",
908 task->error_at_step ? _("..") : "",
909 task->error_at_step ? task->error_at_step->after->name : "",
910 task->error_at_step ? _("'") : "");
911
912 unlink (output_name);
913 }
914 free (output_name);
915 free (input_name_copy);
916 }
917 }
918 else
919 {
920 task->input.name = "";
921 task->output.name = "";
922 if (!(*processor) (task))
923 {
924 success = false;
925 if (!quiet_flag)
926 error (0, 0, _("%s%s%s%s%s%s"),
927 task_perror (task),
928 task->error_at_step ? _(" in step `") : "",
929 task->error_at_step ? task->error_at_step->before->name : "",
930 task->error_at_step ? _("..") : "",
931 task->error_at_step ? task->error_at_step->after->name : "",
932 task->error_at_step ? _("'") : "");
933 }
934 }
935 }
936
937 /* Exit with an appropriate status. */
938
939 exit (success ? EXIT_SUCCESS : EXIT_FAILURE);
940 }