Update.
[glibc.git] / iconv / iconv_prog.c
bloba67c6ebad16d29454b2d3fc05fe193472f3b40ab
1 /* Convert text in given files from the specified from-set to the to-set.
2 Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Ulrich Drepper <drepper@cygnus.com>, 1998.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, write to the Free
18 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 02111-1307 USA. */
21 #include <argp.h>
22 #include <assert.h>
23 #include <ctype.h>
24 #include <errno.h>
25 #include <error.h>
26 #include <fcntl.h>
27 #include <iconv.h>
28 #include <langinfo.h>
29 #include <locale.h>
30 #include <search.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <libintl.h>
36 #ifdef _POSIX_MAPPED_FILES
37 # include <sys/mman.h>
38 #endif
39 #include <charmap.h>
40 #include <gconv_int.h>
41 #include "iconv_prog.h"
42 #include "iconvconfig.h"
44 /* Get libc version number. */
45 #include "../version.h"
47 #define PACKAGE _libc_intl_domainname
50 /* Name and version of program. */
51 static void print_version (FILE *stream, struct argp_state *state);
52 void (*argp_program_version_hook) (FILE *, struct argp_state *) = print_version;
54 #define OPT_VERBOSE 1000
55 #define OPT_LIST 'l'
57 /* Definitions of arguments for argp functions. */
58 static const struct argp_option options[] =
60 { NULL, 0, NULL, 0, N_("Input/Output format specification:") },
61 { "from-code", 'f', "NAME", 0, N_("encoding of original text") },
62 { "to-code", 't', "NAME", 0, N_("encoding for output") },
63 { NULL, 0, NULL, 0, N_("Information:") },
64 { "list", 'l', NULL, 0, N_("list all known coded character sets") },
65 { NULL, 0, NULL, 0, N_("Output control:") },
66 { NULL, 'c', NULL, 0, N_("omit invalid characters from output") },
67 { "output", 'o', "FILE", 0, N_("output file") },
68 { "silent", 's', NULL, 0, N_("suppress warnings") },
69 { "verbose", OPT_VERBOSE, NULL, 0, N_("print progress information") },
70 { NULL, 0, NULL, 0, NULL }
73 /* Short description of program. */
74 static const char doc[] = N_("\
75 Convert encoding of given files from one encoding to another.");
77 /* Strings for arguments in help texts. */
78 static const char args_doc[] = N_("[FILE...]");
80 /* Prototype for option handler. */
81 static error_t parse_opt (int key, char *arg, struct argp_state *state);
83 /* Function to print some extra text in the help message. */
84 static char *more_help (int key, const char *text, void *input);
86 /* Data structure to communicate with argp functions. */
87 static struct argp argp =
89 options, parse_opt, args_doc, doc, NULL, more_help
92 /* Code sets to convert from and to respectively. An empty string as the
93 default causes the 'iconv_open' function to look up the charset of the
94 currently selected locale and use it. */
95 static const char *from_code = "";
96 static const char *to_code = "";
98 /* File to write output to. If NULL write to stdout. */
99 static const char *output_file;
101 /* Nonzero if verbose ouput is wanted. */
102 int verbose;
104 /* Nonzero if list of all coded character sets is wanted. */
105 static int list;
107 /* If nonzero omit invalid character from output. */
108 int omit_invalid;
110 /* Prototypes for the functions doing the actual work. */
111 static int process_block (iconv_t cd, char *addr, size_t len, FILE *output);
112 static int process_fd (iconv_t cd, int fd, FILE *output);
113 static int process_file (iconv_t cd, FILE *input, FILE *output);
114 static void print_known_names (void) internal_function;
118 main (int argc, char *argv[])
120 int status = EXIT_SUCCESS;
121 int remaining;
122 FILE *output;
123 iconv_t cd;
124 const char *orig_to_code;
125 struct charmap_t *from_charmap = NULL;
126 struct charmap_t *to_charmap = NULL;
128 /* Set locale via LC_ALL. */
129 setlocale (LC_ALL, "");
131 /* Set the text message domain. */
132 textdomain (_libc_intl_domainname);
134 /* Parse and process arguments. */
135 argp_parse (&argp, argc, argv, 0, &remaining, NULL);
137 /* List all coded character sets if wanted. */
138 if (list)
140 print_known_names ();
141 exit (EXIT_SUCCESS);
144 /* If we have to ignore errors make sure we use the appropriate name for
145 the to-character-set. */
146 orig_to_code = to_code;
147 if (omit_invalid)
149 const char *errhand = strchrnul (to_code, '/');
150 int nslash = 2;
151 char *newp;
152 char *cp;
154 if (*errhand == '/')
156 --nslash;
157 errhand = strchrnul (errhand, '/');
159 if (*errhand == '/')
161 --nslash;
162 ++errhand;
166 newp = (char *) alloca (errhand - to_code + nslash + 6 + 1);
167 cp = mempcpy (newp, to_code, errhand - to_code);
168 while (nslash-- > 0)
169 *cp++ = '/';
170 memcpy (cp, "IGNORE", sizeof ("IGNORE"));
172 to_code = newp;
175 /* POSIX 1003.2b introduces a silly thing: the arguments to -t anf -f
176 can be file names of charmaps. In this case iconv will have to read
177 those charmaps and use them to do the conversion. But there are
178 holes in the specification. There is nothing said that if -f is a
179 charmap filename that -t must be, too. And vice versa. There is
180 also no word about the symbolic names used. What if they don't
181 match? */
182 if (strchr (from_code, '/') != NULL)
183 /* The from-name might be a charmap file name. Try reading the
184 file. */
185 from_charmap = charmap_read (from_code, /*0, 1*/1, 0, 0);
187 if (strchr (orig_to_code, '/') != NULL)
188 /* The to-name might be a charmap file name. Try reading the
189 file. */
190 to_charmap = charmap_read (orig_to_code, /*0, 1,*/1,0, 0);
193 /* Determine output file. */
194 if (output_file != NULL && strcmp (output_file, "-") != 0)
196 output = fopen (output_file, "w");
197 if (output == NULL)
198 error (EXIT_FAILURE, errno, _("cannot open output file"));
200 else
201 output = stdout;
203 /* At this point we have to handle two cases. The first one is
204 where a charmap is used for the from- or to-charset, or both. We
205 handle this special since it is very different from the sane way of
206 doing things. The other case allows converting using the iconv()
207 function. */
208 if (from_charmap != NULL || to_charmap != NULL)
209 /* Construct the conversion table and do the conversion. */
210 status = charmap_conversion (from_code, from_charmap, to_code, to_charmap,
211 argc, remaining, argv, output);
212 else
214 /* Let's see whether we have these coded character sets. */
215 cd = iconv_open (to_code, from_code);
216 if (cd == (iconv_t) -1)
218 if (errno == EINVAL)
219 error (EXIT_FAILURE, 0,
220 _("conversion from `%s' to `%s' not supported"),
221 from_code[0] ? from_code : nl_langinfo (CODESET),
222 orig_to_code[0] ? orig_to_code : nl_langinfo (CODESET));
223 else
224 error (EXIT_FAILURE, errno,
225 _("failed to start conversion processing"));
228 /* Now process the remaining files. Write them to stdout or the file
229 specified with the `-o' parameter. If we have no file given as
230 the parameter process all from stdin. */
231 if (remaining == argc)
233 if (process_file (cd, stdin, output) != 0)
234 status = EXIT_FAILURE;
236 else
239 #ifdef _POSIX_MAPPED_FILES
240 struct stat st;
241 char *addr;
242 #endif
243 int fd;
245 if (verbose)
246 printf ("%s:\n", argv[remaining]);
247 if (strcmp (argv[remaining], "-") == 0)
248 fd = 0;
249 else
251 fd = open (argv[remaining], O_RDONLY);
253 if (fd == -1)
255 error (0, errno, _("cannot open input file `%s'"),
256 argv[remaining]);
257 status = EXIT_FAILURE;
258 continue;
262 #ifdef _POSIX_MAPPED_FILES
263 /* We have possibilities for reading the input file. First try
264 to mmap() it since this will provide the fastest solution. */
265 if (fstat (fd, &st) == 0
266 && ((addr = mmap (NULL, st.st_size, PROT_READ, MAP_PRIVATE,
267 fd, 0)) != MAP_FAILED))
269 /* Yes, we can use mmap(). The descriptor is not needed
270 anymore. */
271 if (close (fd) != 0)
272 error (EXIT_FAILURE, errno,
273 _("error while closing input `%s'"),
274 argv[remaining]);
276 if (process_block (cd, addr, st.st_size, output) < 0)
278 /* Something went wrong. */
279 status = EXIT_FAILURE;
281 /* We don't need the input data anymore. */
282 munmap ((void *) addr, st.st_size);
284 /* We cannot go on with producing output since it might
285 lead to problem because the last output might leave
286 the output stream in an undefined state. */
287 break;
290 /* We don't need the input data anymore. */
291 munmap ((void *) addr, st.st_size);
293 else
294 #endif /* _POSIX_MAPPED_FILES */
296 /* Read the file in pieces. */
297 if (process_fd (cd, fd, output) != 0)
299 /* Something went wrong. */
300 status = EXIT_FAILURE;
302 /* We don't need the input file anymore. */
303 close (fd);
305 /* We cannot go on with producing output since it might
306 lead to problem because the last output might leave
307 the output stream in an undefined state. */
308 break;
311 /* Now close the file. */
312 close (fd);
315 while (++remaining < argc);
318 /* Close the output file now. */
319 if (fclose (output))
320 error (EXIT_FAILURE, errno, _("error while closing output file"));
322 return status;
326 /* Handle program arguments. */
327 static error_t
328 parse_opt (int key, char *arg, struct argp_state *state)
330 switch (key)
332 case 'f':
333 from_code = arg;
334 break;
335 case 't':
336 to_code = arg;
337 break;
338 case 'o':
339 output_file = arg;
340 break;
341 case 's':
342 /* Nothing, for now at least. We are not giving out any information
343 about missing character or so. */
344 break;
345 case 'c':
346 /* Omit invalid characters from output. */
347 omit_invalid = 1;
348 break;
349 case OPT_VERBOSE:
350 verbose = 1;
351 break;
352 case OPT_LIST:
353 list = 1;
354 break;
355 default:
356 return ARGP_ERR_UNKNOWN;
358 return 0;
362 static char *
363 more_help (int key, const char *text, void *input)
365 switch (key)
367 case ARGP_KEY_HELP_EXTRA:
368 /* We print some extra information. */
369 return strdup (gettext ("\
370 Report bugs using the `glibcbug' script to <bugs@gnu.org>.\n"));
371 default:
372 break;
374 return (char *) text;
378 /* Print the version information. */
379 static void
380 print_version (FILE *stream, struct argp_state *state)
382 fprintf (stream, "iconv (GNU %s) %s\n", PACKAGE, VERSION);
383 fprintf (stream, gettext ("\
384 Copyright (C) %s Free Software Foundation, Inc.\n\
385 This is free software; see the source for copying conditions. There is NO\n\
386 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
387 "), "2002");
388 fprintf (stream, gettext ("Written by %s.\n"), "Ulrich Drepper");
392 static int
393 process_block (iconv_t cd, char *addr, size_t len, FILE *output)
395 #define OUTBUF_SIZE 32768
396 const char *start = addr;
397 char outbuf[OUTBUF_SIZE];
398 char *outptr;
399 size_t outlen;
400 size_t n;
402 while (len > 0)
404 outptr = outbuf;
405 outlen = OUTBUF_SIZE;
406 n = iconv (cd, &addr, &len, &outptr, &outlen);
408 if (outptr != outbuf)
410 /* We have something to write out. */
411 int errno_save = errno;
413 if (fwrite (outbuf, 1, outptr - outbuf, output)
414 < (size_t) (outptr - outbuf)
415 || ferror (output))
417 /* Error occurred while printing the result. */
418 error (0, 0, _("\
419 conversion stopped due to problem in writing the output"));
420 return -1;
423 errno = errno_save;
426 if (n != (size_t) -1)
428 /* All the input test is processed. For state-dependent
429 character sets we have to flush the state now. */
430 outptr = outbuf;
431 outlen = OUTBUF_SIZE;
432 (void) iconv (cd, NULL, NULL, &outptr, &outlen);
434 if (outptr != outbuf)
436 /* We have something to write out. */
437 int errno_save = errno;
439 if (fwrite (outbuf, 1, outptr - outbuf, output)
440 < (size_t) (outptr - outbuf)
441 || ferror (output))
443 /* Error occurred while printing the result. */
444 error (0, 0, _("\
445 conversion stopped due to problem in writing the output"));
446 return -1;
449 errno = errno_save;
452 break;
455 if (errno != E2BIG)
457 /* iconv() ran into a problem. */
458 switch (errno)
460 case EILSEQ:
461 error (0, 0, _("illegal input sequence at position %ld"),
462 (long) (addr - start));
463 break;
464 case EINVAL:
465 error (0, 0, _("\
466 incomplete character or shift sequence at end of buffer"));
467 break;
468 case EBADF:
469 error (0, 0, _("internal error (illegal descriptor)"));
470 break;
471 default:
472 error (0, 0, _("unknown iconv() error %d"), errno);
473 break;
476 return -1;
480 return 0;
484 static int
485 process_fd (iconv_t cd, int fd, FILE *output)
487 /* we have a problem with reading from a desriptor since we must not
488 provide the iconv() function an incomplete character or shift
489 sequence at the end of the buffer. Since we have to deal with
490 arbitrary encodings we must read the whole text in a buffer and
491 process it in one step. */
492 static char *inbuf = NULL;
493 static size_t maxlen = 0;
494 char *inptr = NULL;
495 size_t actlen = 0;
497 while (actlen < maxlen)
499 ssize_t n = read (fd, inptr, maxlen - actlen);
501 if (n == 0)
502 /* No more text to read. */
503 break;
505 if (n == -1)
507 /* Error while reading. */
508 error (0, errno, _("error while reading the input"));
509 return -1;
512 inptr += n;
513 actlen += n;
516 if (actlen == maxlen)
517 while (1)
519 ssize_t n;
520 char *new_inbuf;
522 /* Increase the buffer. */
523 new_inbuf = (char *) realloc (inbuf, maxlen + 32768);
524 if (new_inbuf == NULL)
526 error (0, errno, _("unable to allocate buffer for input"));
527 return -1;
529 inbuf = new_inbuf;
530 maxlen += 32768;
531 inptr = inbuf + actlen;
535 n = read (fd, inptr, maxlen - actlen);
537 if (n == 0)
538 /* No more text to read. */
539 break;
541 if (n == -1)
543 /* Error while reading. */
544 error (0, errno, _("error while reading the input"));
545 return -1;
548 inptr += n;
549 actlen += n;
551 while (actlen < maxlen);
553 if (n == 0)
554 /* Break again so we leave both loops. */
555 break;
558 /* Now we have all the input in the buffer. Process it in one run. */
559 return process_block (cd, inbuf, actlen, output);
563 static int
564 process_file (iconv_t cd, FILE *input, FILE *output)
566 /* This should be safe since we use this function only for `stdin' and
567 we haven't read anything so far. */
568 return process_fd (cd, fileno (input), output);
572 /* Print all known character sets/encodings. */
573 static void *printlist;
574 static size_t column;
575 static int not_first;
577 static void
578 insert_print_list (const void *nodep, VISIT value, int level)
580 if (value == leaf || value == postorder)
582 const struct gconv_alias *s = *(const struct gconv_alias **) nodep;
583 tsearch (s->fromname, &printlist, (__compar_fn_t) strverscmp);
587 static void
588 do_print_human (const void *nodep, VISIT value, int level)
590 if (value == leaf || value == postorder)
592 const char *s = *(const char **) nodep;
593 size_t len = strlen (s);
594 size_t cnt;
596 while (len > 0 && s[len - 1] == '/')
597 --len;
599 for (cnt = 0; cnt < len; ++cnt)
600 if (isalnum (s[cnt]))
601 break;
602 if (cnt == len)
603 return;
605 if (not_first)
607 putchar (',');
608 ++column;
610 if (column > 2 && column + len > 77)
612 fputs ("\n ", stdout);
613 column = 2;
615 else
617 putchar (' ');
618 ++column;
621 else
622 not_first = 1;
624 fwrite (s, len, 1, stdout);
625 column += len;
629 static void
630 do_print (const void *nodep, VISIT value, int level)
632 if (value == leaf || value == postorder)
634 const char *s = *(const char **) nodep;
636 puts (s);
640 static void
641 internal_function
642 add_known_names (struct gconv_module *node)
644 if (node->left != NULL)
645 add_known_names (node->left);
646 if (node->right != NULL)
647 add_known_names (node->right);
650 if (strcmp (node->from_string, "INTERNAL"))
651 tsearch (node->from_string, &printlist,
652 (__compar_fn_t) strverscmp);
653 if (strcmp (node->to_string, "INTERNAL") != 0)
654 tsearch (node->to_string, &printlist, (__compar_fn_t) strverscmp);
656 node = node->same;
658 while (node != NULL);
662 static void
663 insert_cache (void)
665 const struct gconvcache_header *header;
666 const char *strtab;
667 const struct hash_entry *hashtab;
668 size_t cnt;
670 header = (const struct gconvcache_header *) __gconv_get_cache ();
671 strtab = (char *) header + header->string_offset;
672 hashtab = (struct hash_entry *) ((char *) header + header->hash_offset);
674 for (cnt = 0; cnt < header->hash_size; ++cnt)
675 if (hashtab[cnt].string_offset != 0)
677 const char *str = strtab + hashtab[cnt].string_offset;
679 if (strcmp (str, "INTERNAL") != 0)
680 tsearch (str, &printlist, (__compar_fn_t) strverscmp);
685 static void
686 internal_function
687 print_known_names (void)
689 iconv_t h;
690 void *cache;
692 /* We must initialize the internal databases first. */
693 h = iconv_open ("L1", "L1");
694 iconv_close (h);
696 /* See whether we have a cache. */
697 cache = __gconv_get_cache ();
698 if (cache != NULL)
699 /* Yep, use only this information. */
700 insert_cache ();
701 else
703 struct gconv_module *modules;
705 /* No, then use the information read from the gconv-modules file.
706 First add the aliases. */
707 twalk (__gconv_get_alias_db (), insert_print_list);
709 /* Add the from- and to-names from the known modules. */
710 modules = __gconv_get_modules_db ();
711 if (modules != NULL)
712 add_known_names (modules);
715 fputs (_("\
716 The following list contain all the coded character sets known. This does\n\
717 not necessarily mean that all combinations of these names can be used for\n\
718 the FROM and TO command line parameters. One coded character set can be\n\
719 listed with several different names (aliases).\n\n "), stdout);
721 /* Now print the collected names. */
722 column = 2;
723 if (isatty (fileno (stdout)))
725 twalk (printlist, do_print_human);
727 if (column != 0)
728 puts ("");
730 else
731 twalk (printlist, do_print);