Fix CVE-2018-20482
[tar.git] / src / utf8.c
blobabf26bc2f23d3a121de7e907df9dee4ad9135a50
1 /* Charset handling for GNU tar.
3 Copyright 2004, 2006-2007, 2013-2014, 2016-2017 Free Software
4 Foundation, Inc.
6 This file is part of GNU tar.
8 GNU tar is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or
11 (at your option) any later version.
13 GNU tar is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21 #include <system.h>
22 #include <quotearg.h>
23 #include <localcharset.h>
24 #include "common.h"
25 #ifdef HAVE_ICONV_H
26 # include <iconv.h>
27 #endif
29 #ifndef ICONV_CONST
30 # define ICONV_CONST
31 #endif
33 #ifndef HAVE_ICONV
35 # undef iconv_open
36 # define iconv_open(tocode, fromcode) ((iconv_t) -1)
38 # undef iconv
39 # define iconv(cd, inbuf, inbytesleft, outbuf, outbytesleft) ((size_t) 0)
41 # undef iconv_close
42 # define iconv_close(cd) 0
44 #endif
49 static iconv_t conv_desc[2] = { (iconv_t) -1, (iconv_t) -1 };
51 static iconv_t
52 utf8_init (bool to_utf)
54 if (conv_desc[(int) to_utf] == (iconv_t) -1)
56 if (to_utf)
57 conv_desc[(int) to_utf] = iconv_open ("UTF-8", locale_charset ());
58 else
59 conv_desc[(int) to_utf] = iconv_open (locale_charset (), "UTF-8");
61 return conv_desc[(int) to_utf];
64 bool
65 utf8_convert (bool to_utf, char const *input, char **output)
67 char ICONV_CONST *ib;
68 char *ob, *ret;
69 size_t inlen;
70 size_t outlen;
71 iconv_t cd = utf8_init (to_utf);
73 if (cd == 0)
75 *output = xstrdup (input);
76 return true;
78 else if (cd == (iconv_t)-1)
79 return false;
81 inlen = strlen (input) + 1;
82 outlen = inlen * MB_LEN_MAX + 1;
83 ob = ret = xmalloc (outlen);
84 ib = (char ICONV_CONST *) input;
85 if (iconv (cd, &ib, &inlen, &ob, &outlen) == -1)
87 free (ret);
88 return false;
90 *ob = 0;
91 *output = ret;
92 return true;
96 bool
97 string_ascii_p (char const *p)
99 for (; *p; p++)
100 if (*p & ~0x7f)
101 return false;
102 return true;