xref: /freebsd/usr.bin/iconv/iconv.c (revision 7fdf597e96a02165cfe22ff357b857d5fa15ed8a)
1 /* $NetBSD: iconv.c,v 1.16 2009/02/20 15:28:21 yamt Exp $ */
2 
3 /*-
4  * SPDX-License-Identifier: BSD-2-Clause
5  *
6  * Copyright (c)2003 Citrus Project,
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #include <sys/capsicum.h>
32 
33 #include <capsicum_helpers.h>
34 #include <err.h>
35 #include <errno.h>
36 #include <getopt.h>
37 #include <iconv.h>
38 #include <limits.h>
39 #include <locale.h>
40 #include <stdbool.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45 
46 static int		do_conv(FILE *, iconv_t, bool, bool);
47 static int		do_list(unsigned int, const char * const *, void *);
48 static void		usage(void) __dead2;
49 
50 static const struct option long_options[] = {
51 	{"from-code",		required_argument,	NULL, 'f'},
52 	{"list",		no_argument,		NULL, 'l'},
53 	{"silent",		no_argument,		NULL, 's'},
54         {"to-code",		required_argument,	NULL, 't'},
55         {NULL,                  no_argument,            NULL, 0}
56 };
57 
58 static void
59 usage(void)
60 {
61 	(void)fprintf(stderr,
62 	    "Usage:\t%1$s [-cs] -f <from_code> -t <to_code> [file ...]\n"
63 	    "\t%1$s -f <from_code> [-cs] [-t <to_code>] [file ...]\n"
64 	    "\t%1$s -t <to_code> [-cs] [-f <from_code>] [file ...]\n"
65 	    "\t%1$s -l\n", getprogname());
66 	exit(1);
67 }
68 
69 #define INBUFSIZE 1024
70 #define OUTBUFSIZE (INBUFSIZE * 2)
71 static int
72 do_conv(FILE *fp, iconv_t cd, bool silent, bool hide_invalid)
73 {
74 	char inbuf[INBUFSIZE], outbuf[OUTBUFSIZE], *in, *out;
75 	unsigned long long invalids;
76 	size_t inbytes, outbytes, ret;
77 
78 	/*
79 	 * Don't touch ICONV_SET_DISCARD_ILSEQ if -c wasn't specified.  It may
80 	 * be that the user has specified //IGNORE in the -t specification, and
81 	 * we don't want to clobber that.
82 	 */
83 	if (hide_invalid) {
84 		int arg = (int)hide_invalid;
85 		if (iconvctl(cd, ICONV_SET_DISCARD_ILSEQ, (void *)&arg) == -1)
86 			err(EXIT_FAILURE, "iconvctl(DISCARD_ILSEQ, %d)", arg);
87 	}
88 
89 	invalids = 0;
90 	while ((inbytes = fread(inbuf, 1, INBUFSIZE, fp)) > 0) {
91 		in = inbuf;
92 		while (inbytes > 0) {
93 			size_t inval;
94 
95 			out = outbuf;
96 			outbytes = OUTBUFSIZE;
97 			ret = __iconv(cd, &in, &inbytes, &out, &outbytes,
98 			    0, &inval);
99 			invalids += inval;
100 			if (outbytes < OUTBUFSIZE)
101 				(void)fwrite(outbuf, 1, OUTBUFSIZE - outbytes,
102 				    stdout);
103 			if (ret == (size_t)-1 && errno != E2BIG) {
104 				if (errno != EINVAL || in == inbuf)
105 					err(EXIT_FAILURE, "iconv()");
106 
107 				/* incomplete input character */
108 				(void)memmove(inbuf, in, inbytes);
109 				ret = fread(inbuf + inbytes, 1,
110 				    INBUFSIZE - inbytes, fp);
111 				if (ret == 0) {
112 					fflush(stdout);
113 					if (feof(fp))
114 						errx(EXIT_FAILURE,
115 						    "unexpected end of file; "
116 						    "the last character is "
117 						    "incomplete.");
118 					else
119 						err(EXIT_FAILURE, "fread()");
120 				}
121 				in = inbuf;
122 				inbytes += ret;
123 			}
124 		}
125 	}
126 	/* reset the shift state of the output buffer */
127 	outbytes = OUTBUFSIZE;
128 	out = outbuf;
129 	ret = iconv(cd, NULL, NULL, &out, &outbytes);
130 	if (ret == (size_t)-1)
131 		err(EXIT_FAILURE, "iconv()");
132 	if (outbytes < OUTBUFSIZE)
133 		(void)fwrite(outbuf, 1, OUTBUFSIZE - outbytes, stdout);
134 
135 	if (invalids > 0 && !silent)
136 		warnx("warning: invalid characters: %llu", invalids);
137 
138 	return (invalids > 0);
139 }
140 
141 static int
142 do_list(unsigned int n, const char * const *list, void *data __unused)
143 {
144 	unsigned int i;
145 
146 	for(i = 0; i < n; i++) {
147 		printf("%s", list[i]);
148 		if (i < n - 1)
149 			printf(" ");
150 	}
151 	printf("\n");
152 
153 	return (1);
154 }
155 
156 int
157 main(int argc, char **argv)
158 {
159 	iconv_t cd;
160 	FILE *fp;
161 	const char *opt_f, *opt_t;
162 	int ch, i, res;
163 	bool opt_c = false, opt_s = false;
164 
165 	opt_f = opt_t = "";
166 
167 	setlocale(LC_ALL, "");
168 	setprogname(argv[0]);
169 
170 	while ((ch = getopt_long(argc, argv, "csLlf:t:",
171 	    long_options, NULL)) != -1) {
172 		switch (ch) {
173 		case 'c':
174 			opt_c = true;
175 			break;
176 		case 's':
177 			opt_s = true;
178 			break;
179 		case 'l':
180 			/* list */
181 			if (opt_s || opt_c || strcmp(opt_f, "") != 0 ||
182 			    strcmp(opt_t, "") != 0) {
183 				warnx("-l is not allowed with other flags.");
184 				usage();
185 			}
186 			iconvlist(do_list, NULL);
187 			return (EXIT_SUCCESS);
188 		case 'f':
189 			/* from */
190 			if (optarg != NULL)
191 				opt_f = optarg;
192 			break;
193 		case 't':
194 			/* to */
195 			if (optarg != NULL)
196 				opt_t = optarg;
197 			break;
198 		default:
199 			usage();
200 		}
201 	}
202 	argc -= optind;
203 	argv += optind;
204 	if ((strcmp(opt_f, "") == 0) && (strcmp(opt_t, "") == 0))
205 		usage();
206 
207 	if (caph_limit_stdio() < 0)
208 		err(EXIT_FAILURE, "capsicum");
209 
210 	/*
211 	 * Cache NLS data, for strerror, for err(3), before entering capability
212 	 * mode.
213 	 */
214 	caph_cache_catpages();
215 
216 	/*
217 	 * Cache iconv conversion handle before entering sandbox.
218 	 */
219 	cd = iconv_open(opt_t, opt_f);
220 	if (cd == (iconv_t)-1)
221 		err(EXIT_FAILURE, "iconv_open(%s, %s)", opt_t, opt_f);
222 
223 	if (argc == 0) {
224 		if (caph_enter() < 0)
225 			err(EXIT_FAILURE, "unable to enter capability mode");
226 		res = do_conv(stdin, cd, opt_s, opt_c);
227 	} else {
228 		res = 0;
229 		for (i = 0; i < argc; i++) {
230 			fp = (strcmp(argv[i], "-") != 0) ?
231 			    fopen(argv[i], "r") : stdin;
232 			if (fp == NULL)
233 				err(EXIT_FAILURE, "Cannot open `%s'",
234 				    argv[i]);
235 			/* Enter Capsicum sandbox for final input file. */
236 			if (i + 1 == argc && caph_enter() < 0)
237 				err(EXIT_FAILURE,
238 				    "unable to enter capability mode");
239 			res |= do_conv(fp, cd, opt_s, opt_c);
240 			(void)fclose(fp);
241 
242 			/* Reset iconv descriptor state. */
243 			(void)iconv(cd, NULL, NULL, NULL, NULL);
244 		}
245 	}
246 	iconv_close(cd);
247 	return (res == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
248 }
249