iconv_prog.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. /* Convert text in given files from the specified from-set to the to-set.
  2. Copyright (C) 1998-2026 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  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
  6. by the Free Software Foundation; version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, see <https://www.gnu.org/licenses/>. */
  14. #include <argp.h>
  15. #include <assert.h>
  16. #include <ctype.h>
  17. #include <errno.h>
  18. #include <error.h>
  19. #include <fcntl.h>
  20. #include <iconv.h>
  21. #include <langinfo.h>
  22. #include <locale.h>
  23. #include <search.h>
  24. #include <stdbool.h>
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #include <unistd.h>
  29. #include <libintl.h>
  30. #include <charmap.h>
  31. #include <gconv_int.h>
  32. #include "iconv_prog.h"
  33. #include "iconvconfig.h"
  34. #include "gconv_charset.h"
  35. /* Get libc version number. */
  36. #include "../version.h"
  37. #define PACKAGE _libc_intl_domainname
  38. /* Name and version of program. */
  39. static void print_version (FILE *stream, struct argp_state *state);
  40. void (*argp_program_version_hook) (FILE *, struct argp_state *) = print_version;
  41. enum
  42. {
  43. OPT_VERBOSE = 1000,
  44. OPT_BUFFER_SIZE,
  45. };
  46. #define OPT_LIST 'l'
  47. /* Definitions of arguments for argp functions. */
  48. static const struct argp_option options[] =
  49. {
  50. { NULL, 0, NULL, 0, N_("Input/Output format specification:") },
  51. { "from-code", 'f', N_("NAME"), 0, N_("encoding of original text") },
  52. { "to-code", 't', N_("NAME"), 0, N_("encoding for output") },
  53. { NULL, 0, NULL, 0, N_("Information:") },
  54. { "list", 'l', NULL, 0, N_("list all known coded character sets") },
  55. { NULL, 0, NULL, 0, N_("Output control:") },
  56. { NULL, 'c', NULL, 0, N_("omit invalid characters from output") },
  57. { "output", 'o', N_("FILE"), 0, N_("output file") },
  58. { "silent", 's', NULL, 0, N_("suppress warnings") },
  59. { "verbose", OPT_VERBOSE, NULL, 0, N_("print progress information") },
  60. /* This is an internal option intended for testing only. Very small
  61. buffers do not work with all character sets. */
  62. { "buffer-size", OPT_BUFFER_SIZE, N_("BYTE-COUNT"), OPTION_HIDDEN,
  63. N_("size of in-memory scratch buffer") },
  64. { NULL, 0, NULL, 0, NULL }
  65. };
  66. /* Short description of program. */
  67. static const char doc[] = N_("\
  68. Convert encoding of given files from one encoding to another.");
  69. /* Strings for arguments in help texts. */
  70. static const char args_doc[] = N_("[FILE...]");
  71. /* Prototype for option handler. */
  72. static error_t parse_opt (int key, char *arg, struct argp_state *state);
  73. /* Function to print some extra text in the help message. */
  74. static char *more_help (int key, const char *text, void *input);
  75. /* Data structure to communicate with argp functions. */
  76. static struct argp argp =
  77. {
  78. options, parse_opt, args_doc, doc, NULL, more_help
  79. };
  80. /* Code sets to convert from and to respectively. An empty string as the
  81. default causes the 'iconv_open' function to look up the charset of the
  82. currently selected locale and use it. */
  83. static const char *from_code = "";
  84. static const char *to_code = "";
  85. /* File to write output to. If NULL write to stdout. */
  86. static const char *output_file;
  87. /* Nonzero if list of all coded character sets is wanted. */
  88. static int list;
  89. /* If nonzero omit invalid character from output. */
  90. int omit_invalid;
  91. /* Current index in argv (after command line processing) with the
  92. input file name. */
  93. static int current_input_file_index;
  94. /* Size of the temporary, in-memory buffer. Exceeding it needs
  95. spooling to disk in a temporary file. Controlled by --buffer_size. */
  96. static size_t output_buffer_size = 1024 * 1024;
  97. /* Prototypes for the functions doing the actual work. */
  98. static void prepare_output_file (char **argv);
  99. static void close_output_file (__gconv_t cd, int status);
  100. static int process_block (iconv_t cd, char **addr, size_t *len,
  101. off64_t file_offset, bool *incomplete);
  102. static int process_fd (iconv_t cd, int fd);
  103. static int process_file (iconv_t cd, FILE *input);
  104. static void print_known_names (void);
  105. int
  106. main (int argc, char *argv[])
  107. {
  108. int status = EXIT_SUCCESS;
  109. __gconv_t cd;
  110. struct charmap_t *from_charmap = NULL;
  111. struct charmap_t *to_charmap = NULL;
  112. /* Set locale via LC_ALL. */
  113. setlocale (LC_ALL, "");
  114. /* Set the text message domain. */
  115. textdomain (_libc_intl_domainname);
  116. /* Parse and process arguments. */
  117. argp_parse (&argp, argc, argv, 0, &current_input_file_index, NULL);
  118. /* List all coded character sets if wanted. */
  119. if (list)
  120. {
  121. print_known_names ();
  122. exit (EXIT_SUCCESS);
  123. }
  124. /* POSIX 1003.2b introduces a silly thing: the arguments to -t anf -f
  125. can be file names of charmaps. In this case iconv will have to read
  126. those charmaps and use them to do the conversion. But there are
  127. holes in the specification. There is nothing said that if -f is a
  128. charmap filename that -t must be, too. And vice versa. There is
  129. also no word about the symbolic names used. What if they don't
  130. match? */
  131. if (strchr (from_code, '/') != NULL)
  132. /* The from-name might be a charmap file name. Try reading the
  133. file. */
  134. from_charmap = charmap_read (from_code, /*0, 1*/1, 0, 0, 0);
  135. if (strchr (to_code, '/') != NULL)
  136. /* The to-name might be a charmap file name. Try reading the
  137. file. */
  138. to_charmap = charmap_read (to_code, /*0, 1,*/1, 0, 0, 0);
  139. /* At this point we have to handle two cases. The first one is
  140. where a charmap is used for the from- or to-charset, or both. We
  141. handle this special since it is very different from the sane way of
  142. doing things. The other case allows converting using the iconv()
  143. function. */
  144. if (from_charmap != NULL || to_charmap != NULL)
  145. /* Construct the conversion table and do the conversion. */
  146. status = charmap_conversion (from_code, from_charmap, to_code, to_charmap,
  147. argc, current_input_file_index, argv,
  148. output_file);
  149. else
  150. {
  151. struct gconv_spec conv_spec;
  152. int res;
  153. if (__gconv_create_spec (&conv_spec, from_code, to_code) == NULL)
  154. {
  155. error (EXIT_FAILURE, errno,
  156. _("failed to start conversion processing"));
  157. exit (1);
  158. }
  159. if (omit_invalid)
  160. conv_spec.ignore = true;
  161. /* Let's see whether we have these coded character sets. */
  162. res = __gconv_open (&conv_spec, &cd, 0);
  163. __gconv_destroy_spec (&conv_spec);
  164. if (res != __GCONV_OK)
  165. {
  166. if (res == __GCONV_NOCONV || res == __GCONV_NODB)
  167. {
  168. /* Try to be nice with the user and tell her which of the
  169. two encoding names is wrong. This is possible because
  170. all supported encodings can be converted from/to Unicode,
  171. in other words, because the graph of encodings is
  172. connected. */
  173. bool from_wrong =
  174. (iconv_open ("UTF-8", from_code) == (iconv_t) -1
  175. && errno == EINVAL);
  176. bool to_wrong =
  177. (iconv_open (to_code, "UTF-8") == (iconv_t) -1
  178. && errno == EINVAL);
  179. const char *from_pretty =
  180. (from_code[0] ? from_code : nl_langinfo (CODESET));
  181. const char *to_pretty =
  182. (to_code[0] ? to_code : nl_langinfo (CODESET));
  183. if (from_wrong)
  184. {
  185. if (to_wrong)
  186. error (0, 0,
  187. _("\
  188. conversions from `%s' and to `%s' are not supported"),
  189. from_pretty, to_pretty);
  190. else
  191. error (0, 0,
  192. _("conversion from `%s' is not supported"),
  193. from_pretty);
  194. }
  195. else
  196. {
  197. if (to_wrong)
  198. error (0, 0,
  199. _("conversion to `%s' is not supported"),
  200. to_pretty);
  201. else
  202. error (0, 0,
  203. _("conversion from `%s' to `%s' is not supported"),
  204. from_pretty, to_pretty);
  205. }
  206. argp_help (&argp, stderr, ARGP_HELP_SEE,
  207. program_invocation_short_name);
  208. exit (1);
  209. }
  210. else
  211. error (EXIT_FAILURE, errno,
  212. _("failed to start conversion processing"));
  213. }
  214. prepare_output_file (argv);
  215. /* Now process the remaining files. Write them to stdout or the file
  216. specified with the `-o' parameter. If we have no file given as
  217. the parameter process all from stdin. */
  218. if (current_input_file_index == argc)
  219. {
  220. if (process_file (cd, stdin) != 0)
  221. status = EXIT_FAILURE;
  222. }
  223. else
  224. do
  225. {
  226. int fd, ret;
  227. if (verbose)
  228. fprintf (stderr, "%s:\n", argv[current_input_file_index]);
  229. if (strcmp (argv[current_input_file_index], "-") == 0)
  230. fd = STDIN_FILENO;
  231. else
  232. {
  233. fd = open (argv[current_input_file_index], O_RDONLY);
  234. if (fd == -1)
  235. {
  236. error (0, errno, _("cannot open input file `%s'"),
  237. argv[current_input_file_index]);
  238. status = EXIT_FAILURE;
  239. continue;
  240. }
  241. }
  242. {
  243. /* Read the file in pieces. */
  244. ret = process_fd (cd, fd);
  245. /* Now close the file. */
  246. if (fd != STDIN_FILENO)
  247. close (fd);
  248. if (ret != 0)
  249. {
  250. /* Something went wrong. */
  251. status = EXIT_FAILURE;
  252. if (ret < 0)
  253. /* We cannot go on with producing output since it might
  254. lead to problem because the last output might leave
  255. the output stream in an undefined state. */
  256. break;
  257. }
  258. }
  259. }
  260. while (++current_input_file_index < argc);
  261. /* Ensure that iconv -c still exits with failure if iconv (the
  262. function) has failed with E2BIG instead of EILSEQ. */
  263. if (__gconv_has_illegal_input (cd))
  264. status = EXIT_FAILURE;
  265. /* Close the output file now. */
  266. close_output_file (cd, status);
  267. }
  268. return status;
  269. }
  270. /* Handle program arguments. */
  271. static error_t
  272. parse_opt (int key, char *arg, struct argp_state *state)
  273. {
  274. switch (key)
  275. {
  276. case 'f':
  277. from_code = arg;
  278. break;
  279. case 't':
  280. to_code = arg;
  281. break;
  282. case 'o':
  283. output_file = arg;
  284. break;
  285. case 's':
  286. /* Nothing, for now at least. We are not giving out any information
  287. about missing character or so. */
  288. break;
  289. case 'c':
  290. /* Omit invalid characters from output. */
  291. omit_invalid = 1;
  292. break;
  293. case OPT_BUFFER_SIZE:
  294. {
  295. int i = atoi (arg);
  296. if (i <= 0)
  297. error (EXIT_FAILURE, 0, _("invalid buffer size: %s"), arg);
  298. output_buffer_size = i;
  299. }
  300. break;
  301. case OPT_VERBOSE:
  302. verbose = 1;
  303. break;
  304. case OPT_LIST:
  305. list = 1;
  306. break;
  307. default:
  308. return ARGP_ERR_UNKNOWN;
  309. }
  310. return 0;
  311. }
  312. static char *
  313. more_help (int key, const char *text, void *input)
  314. {
  315. char *tp = NULL;
  316. switch (key)
  317. {
  318. case ARGP_KEY_HELP_EXTRA:
  319. /* We print some extra information. */
  320. if (asprintf (&tp, gettext ("\
  321. For bug reporting instructions, please see:\n\
  322. %s.\n"), REPORT_BUGS_TO) < 0)
  323. return NULL;
  324. return tp;
  325. default:
  326. break;
  327. }
  328. return (char *) text;
  329. }
  330. /* Print the version information. */
  331. static void
  332. print_version (FILE *stream, struct argp_state *state)
  333. {
  334. fprintf (stream, "iconv %s%s\n", PKGVERSION, VERSION);
  335. fprintf (stream, gettext ("\
  336. Copyright (C) %s Free Software Foundation, Inc.\n\
  337. This is free software; see the source for copying conditions. There is NO\n\
  338. warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
  339. "), "2024");
  340. fprintf (stream, gettext ("Written by %s.\n"), "Ulrich Drepper");
  341. }
  342. /* Command line index of the last input file that overlaps with the
  343. output file. Zero means no temporary file is ever required. */
  344. static int last_overlapping_file_index;
  345. /* This is set to true if the output is written to a temporary file. */
  346. static bool output_using_temporary_file;
  347. /* This is the file descriptor that will be used by write_output. */
  348. static int output_fd = -1;
  349. /* Pointers at the start and end of the fixed-size output buffer. */
  350. static char *output_buffer_start;
  351. /* Current write position in the output buffer. */
  352. static char *output_buffer_current;
  353. /* Remaining bytes after output_buffer_current in the output buffer. */
  354. static size_t output_buffer_remaining;
  355. /* Reduce the buffer size when writing directly to the output file, to
  356. reduce cache utilization. */
  357. static size_t copy_buffer_size = BUFSIZ;
  358. static void
  359. output_error (void)
  360. {
  361. error (EXIT_FAILURE, errno, _("cannot open output file"));
  362. }
  363. static void
  364. input_error (const char *path)
  365. {
  366. error (0, errno, _("cannot open input file `%s'"), path);
  367. }
  368. /* Opens output_file for writing, truncating it. */
  369. static void
  370. open_output_direct (void)
  371. {
  372. output_fd = open64 (output_file, O_WRONLY | O_CREAT | O_TRUNC, 0666);
  373. if (output_fd < 0)
  374. output_error ();
  375. }
  376. static void
  377. prepare_output_file (char **argv)
  378. {
  379. if (copy_buffer_size > output_buffer_size)
  380. copy_buffer_size = output_buffer_size;
  381. if (output_file == NULL || strcmp (output_file, "-") == 0)
  382. {
  383. /* No buffering is required when writing to standard output
  384. because input overlap is expected to be solved externally. */
  385. output_fd = STDOUT_FILENO;
  386. output_buffer_size = copy_buffer_size;
  387. }
  388. else
  389. {
  390. /* If iconv creates the output file, no overlap is possible. */
  391. output_fd = open64 (output_file, O_WRONLY | O_CREAT | O_EXCL, 0666);
  392. if (output_fd >= 0)
  393. output_buffer_size = copy_buffer_size;
  394. else
  395. {
  396. /* Otherwise, check if any of the input files overlap with the
  397. output file. */
  398. struct statx st;
  399. if (statx (AT_FDCWD, output_file, 0, STATX_INO | STATX_MODE, &st)
  400. != 0)
  401. output_error ();
  402. uint32_t out_dev_minor = st.stx_dev_minor;
  403. uint32_t out_dev_major = st.stx_dev_major;
  404. uint64_t out_ino = st.stx_ino;
  405. int idx = current_input_file_index;
  406. while (true)
  407. {
  408. /* Special case: no input files means standard input. */
  409. if (argv[idx] == NULL && idx != current_input_file_index)
  410. break;
  411. int ret;
  412. if (argv[idx] == NULL || strcmp (argv[idx], "-") == 0)
  413. ret = statx (STDIN_FILENO, "", AT_EMPTY_PATH, STATX_INO, &st);
  414. else
  415. ret = statx (AT_FDCWD, argv[idx], 0, STATX_INO, &st);
  416. if (ret != 0)
  417. {
  418. input_error (argv[idx]);
  419. exit (EXIT_FAILURE);
  420. }
  421. if (out_dev_minor == st.stx_dev_minor
  422. && out_dev_major == st.stx_dev_major
  423. && out_ino == st.stx_ino)
  424. {
  425. if (argv[idx] == NULL)
  426. /* Corner case: index of NULL would be larger than
  427. idx while converting, triggering a switch away
  428. from the temporary file. */
  429. last_overlapping_file_index = INT_MAX;
  430. else
  431. last_overlapping_file_index = idx;
  432. }
  433. if (argv[idx] == NULL)
  434. break;
  435. ++idx;
  436. }
  437. /* If there is no overlap, avoid using a temporary file. */
  438. if (last_overlapping_file_index == 0)
  439. {
  440. open_output_direct ();
  441. output_buffer_size = copy_buffer_size;
  442. }
  443. }
  444. }
  445. output_buffer_start = malloc (output_buffer_size);
  446. if (output_buffer_start == NULL)
  447. output_error ();
  448. output_buffer_current = output_buffer_start;
  449. output_buffer_remaining = output_buffer_size;
  450. }
  451. /* Write out the range [first, last), terminating the process on write
  452. error. */
  453. static void
  454. write_fully (int fd, const char *first, const char *last)
  455. {
  456. while (first < last)
  457. {
  458. ssize_t ret = write (fd, first, last - first);
  459. if (ret == 0)
  460. {
  461. errno = ENOSPC;
  462. output_error ();
  463. }
  464. if (ret < 0)
  465. error (EXIT_FAILURE, errno, _("\
  466. conversion stopped due to problem in writing the output"));
  467. first += ret;
  468. }
  469. }
  470. static void
  471. flush_output (void)
  472. {
  473. bool temporary_file_not_needed
  474. = current_input_file_index > last_overlapping_file_index;
  475. if (output_fd < 0)
  476. {
  477. if (temporary_file_not_needed)
  478. open_output_direct ();
  479. else
  480. {
  481. /* Create an anonymous temporary file. */
  482. FILE *fp = tmpfile ();
  483. if (fp == NULL)
  484. output_error ();
  485. output_fd = dup (fileno (fp));
  486. if (output_fd < 0)
  487. output_error ();
  488. fclose (fp);
  489. output_using_temporary_file = true;
  490. }
  491. /* Either way, no longer use a memory-only staging buffer. */
  492. output_buffer_size = copy_buffer_size;
  493. }
  494. else if (output_using_temporary_file && temporary_file_not_needed)
  495. {
  496. /* The temporary file is no longer needed. Switch to direct
  497. output, replacing output_fd. */
  498. int temp_fd = output_fd;
  499. open_output_direct ();
  500. /* Copy over the data spooled to the temporary file. */
  501. if (lseek (temp_fd, 0, SEEK_SET) < 0)
  502. output_error ();
  503. while (true)
  504. {
  505. char buf[BUFSIZ];
  506. ssize_t ret = read (temp_fd, buf, sizeof (buf));
  507. if (ret < 0)
  508. output_error ();
  509. if (ret == 0)
  510. break;
  511. write_fully (output_fd, buf, buf + ret);
  512. }
  513. close (temp_fd);
  514. /* No longer using a temporary file from now on. */
  515. output_using_temporary_file = false;
  516. output_buffer_size = copy_buffer_size;
  517. }
  518. write_fully (output_fd, output_buffer_start, output_buffer_current);
  519. output_buffer_current = output_buffer_start;
  520. output_buffer_remaining = output_buffer_size;
  521. }
  522. static void
  523. close_output_file (__gconv_t cd, int status)
  524. {
  525. /* Do not perform a flush if a temporary file or the in-memory
  526. buffer is in use and there was an error. It would clobber the
  527. overlapping input file. */
  528. if (status != EXIT_SUCCESS && !omit_invalid &&
  529. (output_using_temporary_file || output_fd < 0))
  530. return;
  531. /* All the input text is processed. For state-dependent character
  532. sets we have to flush the state now.
  533. The current_input_file_index variable is now larger than
  534. last_overlapping_file_index, so the flush_output calls switch
  535. away from the temporary file. */
  536. size_t n = iconv (cd, NULL, NULL,
  537. &output_buffer_current, &output_buffer_remaining);
  538. if (n == (size_t) -1 && errno == E2BIG)
  539. {
  540. /* Try again if the state flush exceeded the buffer space. */
  541. flush_output ();
  542. n = iconv (cd, NULL, NULL,
  543. &output_buffer_current, &output_buffer_remaining);
  544. }
  545. int saved_errno = errno;
  546. flush_output ();
  547. if (n == (size_t) -1 && !omit_invalid)
  548. {
  549. errno = saved_errno;
  550. output_error ();
  551. }
  552. if (output_fd == STDOUT_FILENO)
  553. {
  554. /* Close standard output in safe manner, to report certain
  555. ENOSPC errors. */
  556. output_fd = dup (output_fd);
  557. if (output_fd < 0)
  558. output_error ();
  559. }
  560. if (close (output_fd) < 0)
  561. output_error ();
  562. }
  563. /* CD is the iconv handle. Input processing starts at *ADDR, and
  564. consumes upto *LEN bytes. *ADDR and *LEN are updated. FILE_OFFSET
  565. is the file offset of the data initially at ADDR. *INCOMPLETE is
  566. set to true if conversion stops due to an incomplete input
  567. sequence. */
  568. static int
  569. process_block (iconv_t cd, char **addr, size_t *len, off64_t file_offset,
  570. bool *incomplete)
  571. {
  572. const char *start = *addr;
  573. size_t n;
  574. int ret = 0;
  575. while (*len > 0)
  576. {
  577. n = iconv (cd, addr, len,
  578. &output_buffer_current, &output_buffer_remaining);
  579. if (n == (size_t) -1 && omit_invalid && errno == EILSEQ)
  580. {
  581. ret = 1;
  582. if (*len == 0)
  583. n = 0;
  584. else
  585. errno = E2BIG;
  586. }
  587. if (n != (size_t) -1)
  588. break;
  589. if (errno == E2BIG)
  590. flush_output ();
  591. else
  592. {
  593. /* iconv() ran into a problem. */
  594. switch (errno)
  595. {
  596. case EILSEQ:
  597. if (! omit_invalid)
  598. error (0, 0, _("illegal input sequence at position %lld"),
  599. (long long int) (file_offset + (*addr - start)));
  600. break;
  601. case EINVAL:
  602. *incomplete = true;
  603. return ret;
  604. case EBADF:
  605. error (0, 0, _("internal error (illegal descriptor)"));
  606. break;
  607. default:
  608. error (0, 0, _("unknown iconv() error %d"), errno);
  609. break;
  610. }
  611. return -1;
  612. }
  613. }
  614. return ret;
  615. }
  616. static int
  617. process_fd (iconv_t cd, int fd)
  618. {
  619. char inbuf[BUFSIZ];
  620. char *inbuf_end = inbuf + sizeof (inbuf);
  621. size_t inbuf_used = 0;
  622. off64_t file_offset = 0;
  623. int status = 0;
  624. bool incomplete = false;
  625. while (true)
  626. {
  627. char *p = inbuf + inbuf_used;
  628. ssize_t read_ret = read (fd, p, inbuf_end - p);
  629. if (read_ret == 0)
  630. {
  631. /* On EOF, check if the previous iconv invocation saw an
  632. incomplete sequence. */
  633. if (incomplete)
  634. {
  635. error (0, 0, _("\
  636. incomplete character or shift sequence at end of buffer"));
  637. return 1;
  638. }
  639. return 0;
  640. }
  641. if (read_ret < 0)
  642. {
  643. error (0, errno, _("error while reading the input"));
  644. return -1;
  645. }
  646. inbuf_used += read_ret;
  647. incomplete = false;
  648. p = inbuf;
  649. int ret = process_block (cd, &p, &inbuf_used, file_offset, &incomplete);
  650. if (ret != 0)
  651. {
  652. status = ret;
  653. if (ret < 0)
  654. break;
  655. }
  656. /* The next loop iteration consumes the leftover bytes. */
  657. memmove (inbuf, p, inbuf_used);
  658. file_offset += read_ret - inbuf_used;
  659. }
  660. return status;
  661. }
  662. static int
  663. process_file (iconv_t cd, FILE *input)
  664. {
  665. /* This should be safe since we use this function only for `stdin' and
  666. we haven't read anything so far. */
  667. return process_fd (cd, fileno (input));
  668. }
  669. /* Print all known character sets/encodings. */
  670. static void *printlist;
  671. static size_t column;
  672. static int not_first;
  673. static void
  674. insert_print_list (const void *nodep, VISIT value, int level)
  675. {
  676. if (value == leaf || value == postorder)
  677. {
  678. const struct gconv_alias *s = *(const struct gconv_alias **) nodep;
  679. tsearch (s->fromname, &printlist, (__compar_fn_t) strverscmp);
  680. }
  681. }
  682. static void
  683. do_print_human (const void *nodep, VISIT value, int level)
  684. {
  685. if (value == leaf || value == postorder)
  686. {
  687. const char *s = *(const char **) nodep;
  688. size_t len = strlen (s);
  689. size_t cnt;
  690. while (len > 0 && s[len - 1] == '/')
  691. --len;
  692. for (cnt = 0; cnt < len; ++cnt)
  693. if (isalnum (s[cnt]))
  694. break;
  695. if (cnt == len)
  696. return;
  697. if (not_first)
  698. {
  699. putchar (',');
  700. ++column;
  701. if (column > 2 && column + len > 77)
  702. {
  703. fputs ("\n ", stdout);
  704. column = 2;
  705. }
  706. else
  707. {
  708. putchar (' ');
  709. ++column;
  710. }
  711. }
  712. else
  713. not_first = 1;
  714. fwrite (s, len, 1, stdout);
  715. column += len;
  716. }
  717. }
  718. static void
  719. do_print (const void *nodep, VISIT value, int level)
  720. {
  721. if (value == leaf || value == postorder)
  722. {
  723. const char *s = *(const char **) nodep;
  724. puts (s);
  725. }
  726. }
  727. static void
  728. add_known_names (struct gconv_module *node)
  729. {
  730. if (node->left != NULL)
  731. add_known_names (node->left);
  732. if (node->right != NULL)
  733. add_known_names (node->right);
  734. do
  735. {
  736. if (strcmp (node->from_string, "INTERNAL") != 0)
  737. tsearch (node->from_string, &printlist, (__compar_fn_t) strverscmp);
  738. if (strcmp (node->to_string, "INTERNAL") != 0)
  739. tsearch (node->to_string, &printlist, (__compar_fn_t) strverscmp);
  740. node = node->same;
  741. }
  742. while (node != NULL);
  743. }
  744. static void
  745. insert_cache (void)
  746. {
  747. const struct gconvcache_header *header;
  748. const char *strtab;
  749. const struct hash_entry *hashtab;
  750. size_t cnt;
  751. header = (const struct gconvcache_header *) __gconv_get_cache ();
  752. strtab = (char *) header + header->string_offset;
  753. hashtab = (struct hash_entry *) ((char *) header + header->hash_offset);
  754. for (cnt = 0; cnt < header->hash_size; ++cnt)
  755. if (hashtab[cnt].string_offset != 0)
  756. {
  757. const char *str = strtab + hashtab[cnt].string_offset;
  758. if (strcmp (str, "INTERNAL") != 0)
  759. tsearch (str, &printlist, (__compar_fn_t) strverscmp);
  760. }
  761. }
  762. static void
  763. print_known_names (void)
  764. {
  765. iconv_t h;
  766. void *cache;
  767. /* We must initialize the internal databases first. */
  768. h = iconv_open ("L1", "L1");
  769. iconv_close (h);
  770. /* See whether we have a cache. */
  771. cache = __gconv_get_cache ();
  772. if (cache != NULL)
  773. /* Yep, use only this information. */
  774. insert_cache ();
  775. else
  776. {
  777. struct gconv_module *modules;
  778. /* No, then use the information read from the gconv-modules file.
  779. First add the aliases. */
  780. twalk (__gconv_get_alias_db (), insert_print_list);
  781. /* Add the from- and to-names from the known modules. */
  782. modules = __gconv_get_modules_db ();
  783. if (modules != NULL)
  784. add_known_names (modules);
  785. }
  786. bool human_readable = isatty (fileno (stdout));
  787. if (human_readable)
  788. fputs (_("\
  789. The following list contains all the coded character sets known. This does\n\
  790. not necessarily mean that all combinations of these names can be used for\n\
  791. the FROM and TO command line parameters. One coded character set can be\n\
  792. listed with several different names (aliases).\n\n "), stdout);
  793. /* Now print the collected names. */
  794. column = 2;
  795. twalk (printlist, human_readable ? do_print_human : do_print);
  796. if (human_readable && column != 0)
  797. puts ("");
  798. }