xref: /haiku/src/add-ons/kernel/file_systems/ntfs/libntfs/unistr.c (revision be3db2942c0e8dda63cdd226ec3c99309d3eab0c)
1 /**
2  * unistr.c - Unicode string handling. Originated from the Linux-NTFS project.
3  *
4  * Copyright (c) 2000-2004 Anton Altaparmakov
5  * Copyright (c) 2002-2006 Szabolcs Szakacsits
6  *
7  * This program/include file is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License as published
9  * by the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program/include file is distributed in the hope that it will be
13  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program (in the main directory of the NTFS-3G
19  * distribution in the file COPYING); if not, write to the Free Software
20  * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22 
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26 
27 #ifdef HAVE_STDIO_H
28 #include <stdio.h>
29 #endif
30 #ifdef HAVE_STDLIB_H
31 #include <stdlib.h>
32 #endif
33 #ifdef HAVE_WCHAR_H
34 #include <wchar.h>
35 #endif
36 #ifdef HAVE_STRING_H
37 #include <string.h>
38 #endif
39 #ifdef HAVE_ERRNO_H
40 #include <errno.h>
41 #endif
42 
43 #include "attrib.h"
44 #include "types.h"
45 #include "unistr.h"
46 #include "debug.h"
47 #include "logging.h"
48 #include "misc.h"
49 
50 /*
51  * IMPORTANT
52  * =========
53  *
54  * All these routines assume that the Unicode characters are in little endian
55  * encoding inside the strings!!!
56  */
57 
58 /*
59  * This is used by the name collation functions to quickly determine what
60  * characters are (in)valid.
61  */
62 #if 0
63 static const u8 legal_ansi_char_array[0x40] = {
64 	0x00, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
65 	0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
66 
67 	0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
68 	0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
69 
70 	0x17, 0x07, 0x18, 0x17, 0x17, 0x17, 0x17, 0x17,
71 	0x17, 0x17, 0x18, 0x16, 0x16, 0x17, 0x07, 0x00,
72 
73 	0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
74 	0x17, 0x17, 0x04, 0x16, 0x18, 0x16, 0x18, 0x18,
75 };
76 #endif
77 
78 /**
79  * ntfs_names_are_equal - compare two Unicode names for equality
80  * @s1:			name to compare to @s2
81  * @s1_len:		length in Unicode characters of @s1
82  * @s2:			name to compare to @s1
83  * @s2_len:		length in Unicode characters of @s2
84  * @ic:			ignore case bool
85  * @upcase:		upcase table (only if @ic == IGNORE_CASE)
86  * @upcase_size:	length in Unicode characters of @upcase (if present)
87  *
88  * Compare the names @s1 and @s2 and return TRUE (1) if the names are
89  * identical, or FALSE (0) if they are not identical. If @ic is IGNORE_CASE,
90  * the @upcase table is used to perform a case insensitive comparison.
91  */
92 BOOL ntfs_names_are_equal(const ntfschar *s1, size_t s1_len,
93 		const ntfschar *s2, size_t s2_len,
94 		const IGNORE_CASE_BOOL ic,
95 		const ntfschar *upcase, const u32 upcase_size)
96 {
97 	if (s1_len != s2_len)
98 		return FALSE;
99 	if (!s1_len)
100 		return TRUE;
101 	if (ic == CASE_SENSITIVE)
102 		return ntfs_ucsncmp(s1, s2, s1_len) ? FALSE: TRUE;
103 	return ntfs_ucsncasecmp(s1, s2, s1_len, upcase, upcase_size) ? FALSE:
104 								       TRUE;
105 }
106 
107 /**
108  * ntfs_names_collate - collate two Unicode names
109  * @name1:	first Unicode name to compare
110  * @name1_len:	length of first Unicode name to compare
111  * @name2:	second Unicode name to compare
112  * @name2_len:	length of second Unicode name to compare
113  * @err_val:	if @name1 contains an invalid character return this value
114  * @ic:		either CASE_SENSITIVE or IGNORE_CASE
115  * @upcase:	upcase table (ignored if @ic is CASE_SENSITIVE)
116  * @upcase_len:	upcase table size (ignored if @ic is CASE_SENSITIVE)
117  *
118  * ntfs_names_collate() collates two Unicode names and returns:
119  *
120  *  -1 if the first name collates before the second one,
121  *   0 if the names match,
122  *   1 if the second name collates before the first one, or
123  * @err_val if an invalid character is found in @name1 during the comparison.
124  *
125  * The following characters are considered invalid: '"', '*', '<', '>' and '?'.
126  */
127 int ntfs_names_collate(const ntfschar *name1, const u32 name1_len,
128 		const ntfschar *name2, const u32 name2_len,
129 		const int err_val __attribute__((unused)),
130 		const IGNORE_CASE_BOOL ic, const ntfschar *upcase,
131 		const u32 upcase_len)
132 {
133 	u32 cnt;
134 	ntfschar c1, c2;
135 
136 #ifdef DEBUG
137 	if (!name1 || !name2 || (ic && (!upcase || !upcase_len))) {
138 		ntfs_log_debug("ntfs_names_collate received NULL pointer!\n");
139 		exit(1);
140 	}
141 #endif
142 	for (cnt = 0; cnt < min(name1_len, name2_len); ++cnt) {
143 		c1 = le16_to_cpu(*name1);
144 		name1++;
145 		c2 = le16_to_cpu(*name2);
146 		name2++;
147 		if (ic) {
148 			if (c1 < upcase_len)
149 				c1 = le16_to_cpu(upcase[c1]);
150 			if (c2 < upcase_len)
151 				c2 = le16_to_cpu(upcase[c2]);
152 		}
153 #if 0
154 		if (c1 < 64 && legal_ansi_char_array[c1] & 8)
155 			return err_val;
156 #endif
157 		if (c1 < c2)
158 			return -1;
159 		if (c1 > c2)
160 			return 1;
161 	}
162 	if (name1_len < name2_len)
163 		return -1;
164 	if (name1_len == name2_len)
165 		return 0;
166 	/* name1_len > name2_len */
167 #if 0
168 	c1 = le16_to_cpu(*name1);
169 	if (c1 < 64 && legal_ansi_char_array[c1] & 8)
170 		return err_val;
171 #endif
172 	return 1;
173 }
174 
175 /**
176  * ntfs_ucsncmp - compare two little endian Unicode strings
177  * @s1:		first string
178  * @s2:		second string
179  * @n:		maximum unicode characters to compare
180  *
181  * Compare the first @n characters of the Unicode strings @s1 and @s2,
182  * The strings in little endian format and appropriate le16_to_cpu()
183  * conversion is performed on non-little endian machines.
184  *
185  * The function returns an integer less than, equal to, or greater than zero
186  * if @s1 (or the first @n Unicode characters thereof) is found, respectively,
187  * to be less than, to match, or be greater than @s2.
188  */
189 int ntfs_ucsncmp(const ntfschar *s1, const ntfschar *s2, size_t n)
190 {
191 	ntfschar c1, c2;
192 	size_t i;
193 
194 #ifdef DEBUG
195 	if (!s1 || !s2) {
196 		ntfs_log_debug("ntfs_wcsncmp() received NULL pointer!\n");
197 		exit(1);
198 	}
199 #endif
200 	for (i = 0; i < n; ++i) {
201 		c1 = le16_to_cpu(s1[i]);
202 		c2 = le16_to_cpu(s2[i]);
203 		if (c1 < c2)
204 			return -1;
205 		if (c1 > c2)
206 			return 1;
207 		if (!c1)
208 			break;
209 	}
210 	return 0;
211 }
212 
213 /**
214  * ntfs_ucsncasecmp - compare two little endian Unicode strings, ignoring case
215  * @s1:			first string
216  * @s2:			second string
217  * @n:			maximum unicode characters to compare
218  * @upcase:		upcase table
219  * @upcase_size:	upcase table size in Unicode characters
220  *
221  * Compare the first @n characters of the Unicode strings @s1 and @s2,
222  * ignoring case. The strings in little endian format and appropriate
223  * le16_to_cpu() conversion is performed on non-little endian machines.
224  *
225  * Each character is uppercased using the @upcase table before the comparison.
226  *
227  * The function returns an integer less than, equal to, or greater than zero
228  * if @s1 (or the first @n Unicode characters thereof) is found, respectively,
229  * to be less than, to match, or be greater than @s2.
230  */
231 int ntfs_ucsncasecmp(const ntfschar *s1, const ntfschar *s2, size_t n,
232 		const ntfschar *upcase, const u32 upcase_size)
233 {
234 	ntfschar c1, c2;
235 	size_t i;
236 
237 #ifdef DEBUG
238 	if (!s1 || !s2 || !upcase) {
239 		ntfs_log_debug("ntfs_wcsncasecmp() received NULL pointer!\n");
240 		exit(1);
241 	}
242 #endif
243 	for (i = 0; i < n; ++i) {
244 		if ((c1 = le16_to_cpu(s1[i])) < upcase_size)
245 			c1 = le16_to_cpu(upcase[c1]);
246 		if ((c2 = le16_to_cpu(s2[i])) < upcase_size)
247 			c2 = le16_to_cpu(upcase[c2]);
248 		if (c1 < c2)
249 			return -1;
250 		if (c1 > c2)
251 			return 1;
252 		if (!c1)
253 			break;
254 	}
255 	return 0;
256 }
257 
258 /**
259  * ntfs_ucsnlen - determine the length of a little endian Unicode string
260  * @s:		pointer to Unicode string
261  * @maxlen:	maximum length of string @s
262  *
263  * Return the number of Unicode characters in the little endian Unicode
264  * string @s up to a maximum of maxlen Unicode characters, not including
265  * the terminating (ntfschar)'\0'. If there is no (ntfschar)'\0' between @s
266  * and @s + @maxlen, @maxlen is returned.
267  *
268  * This function never looks beyond @s + @maxlen.
269  */
270 u32 ntfs_ucsnlen(const ntfschar *s, u32 maxlen)
271 {
272 	u32 i;
273 
274 	for (i = 0; i < maxlen; i++) {
275 		if (!le16_to_cpu(s[i]))
276 			break;
277 	}
278 	return i;
279 }
280 
281 /**
282  * ntfs_ucsndup - duplicate little endian Unicode string
283  * @s:		pointer to Unicode string
284  * @maxlen:	maximum length of string @s
285  *
286  * Return a pointer to a new little endian Unicode string which is a duplicate
287  * of the string s.  Memory for the new string is obtained with ntfs_malloc(3),
288  * and can be freed with free(3).
289  *
290  * A maximum of @maxlen Unicode characters are copied and a terminating
291  * (ntfschar)'\0' little endian Unicode character is added.
292  *
293  * This function never looks beyond @s + @maxlen.
294  *
295  * Return a pointer to the new little endian Unicode string on success and NULL
296  * on failure with errno set to the error code.
297  */
298 ntfschar *ntfs_ucsndup(const ntfschar *s, u32 maxlen)
299 {
300 	ntfschar *dst;
301 	u32 len;
302 
303 	len = ntfs_ucsnlen(s, maxlen);
304 	dst = ntfs_malloc((len + 1) * sizeof(ntfschar));
305 	if (dst) {
306 		memcpy(dst, s, len * sizeof(ntfschar));
307 		dst[len] = cpu_to_le16(L'\0');
308 	}
309 	return dst;
310 }
311 
312 /**
313  * ntfs_name_upcase - Map an Unicode name to its uppercase equivalent
314  * @name:
315  * @name_len:
316  * @upcase:
317  * @upcase_len:
318  *
319  * Description...
320  *
321  * Returns:
322  */
323 void ntfs_name_upcase(ntfschar *name, u32 name_len, const ntfschar *upcase,
324 		const u32 upcase_len)
325 {
326 	u32 i;
327 	ntfschar u;
328 
329 	for (i = 0; i < name_len; i++)
330 		if ((u = le16_to_cpu(name[i])) < upcase_len)
331 			name[i] = upcase[u];
332 }
333 
334 /**
335  * ntfs_file_value_upcase - Convert a filename to upper case
336  * @file_name_attr:
337  * @upcase:
338  * @upcase_len:
339  *
340  * Description...
341  *
342  * Returns:
343  */
344 void ntfs_file_value_upcase(FILE_NAME_ATTR *file_name_attr,
345 		const ntfschar *upcase, const u32 upcase_len)
346 {
347 	ntfs_name_upcase((ntfschar*)&file_name_attr->file_name,
348 			file_name_attr->file_name_length, upcase, upcase_len);
349 }
350 
351 /**
352  * ntfs_file_values_compare - Which of two filenames should be listed first
353  * @file_name_attr1:
354  * @file_name_attr2:
355  * @err_val:
356  * @ic:
357  * @upcase:
358  * @upcase_len:
359  *
360  * Description...
361  *
362  * Returns:
363  */
364 int ntfs_file_values_compare(const FILE_NAME_ATTR *file_name_attr1,
365 		const FILE_NAME_ATTR *file_name_attr2,
366 		const int err_val, const IGNORE_CASE_BOOL ic,
367 		const ntfschar *upcase, const u32 upcase_len)
368 {
369 	return ntfs_names_collate((ntfschar*)&file_name_attr1->file_name,
370 			file_name_attr1->file_name_length,
371 			(ntfschar*)&file_name_attr2->file_name,
372 			file_name_attr2->file_name_length,
373 			err_val, ic, upcase, upcase_len);
374 }
375 
376 #ifdef _BEOS_
377 
378 
379 static int
380 to_utf8(wchar_t c,unsigned char* buf)
381 {
382 	if(c==0)
383 		return 0; /* No support for embedded 0 runes */
384 	if(c<0x80){
385 		if(buf)buf[0]=(unsigned char)c;
386 		return 1;
387 	}
388 	if(c<0x800){
389 		if(buf){
390 			buf[0] = 0xc0 | (c>>6);
391 			buf[1] = 0x80 | (c & 0x3f);
392 		}
393 		return 2;
394 	}
395 	if(c<0x10000){
396 		if(buf){
397 			buf[0] = 0xe0 | (c>>12);
398 			buf[1] = 0x80 | ((c>>6) & 0x3f);
399 			buf[2] = 0x80 | (c & 0x3f);
400 		}
401 		return 3;
402 	}
403 	/* We don't support characters above 0xFFFF in NTFS */
404 	return 0;
405 }
406 
407 
408 /* Decodes a sequence of utf8 bytes into a single wide character.
409  * The character is returned in host byte order.
410  * Returns the number of bytes consumed, or 0 on error.
411  */
412 static int
413 from_utf8(const unsigned char* str,wchar_t *c)
414 {
415 	int l=0,i;
416 
417 	if(*str<0x80){
418 		*c = *str;
419 		return 1;
420 	}
421 	if(*str<0xc0) /* lead byte must not be 10xxxxxx */
422 		return 0;   /* is c0 a possible lead byte? */
423 	if(*str<0xe0){         /* 110xxxxx */
424 		*c = *str & 0x1f;
425 		l=2;
426 	}else if(*str<0xf0){   /* 1110xxxx */
427 		*c = *str & 0xf;
428 		l=3;
429 	}else if(*str<0xf8){   /* 11110xxx */
430 		*c = *str & 7;
431 		l=4;
432 	}else /* We don't support characters above 0xFFFF in NTFS */
433 		return 0;
434 
435 
436 	for(i=1;i<l;i++){
437 		/* all other bytes must be 10xxxxxx */
438 		if((str[i] & 0xc0) != 0x80)
439 			return 0;
440 		*c <<= 6;
441 		*c |= str[i] & 0x3f;
442 	}
443 	return l;
444 }
445 
446 
447 /* Converts wide string to UTF-8. Expects two in- and two out-parameters.
448  * Returns 0 on success, or error code.
449  * The caller has to free the result string.
450  * There is no support for UTF-16, yet
451  */
452 static int ntfs_dupuni2utf8(wchar_t* in, int in_len,char **out,int *out_len)
453 {
454 	int i,tmp;
455 	int len8;
456 	unsigned char *result;
457 
458 	/* count the length of the resulting UTF-8 */
459 	for(i=len8=0;i<in_len;i++){
460 		tmp=to_utf8(le16_to_cpu( *(in+i) ),0);
461 		if(!tmp)
462 			/* invalid character */
463 			return EILSEQ;
464 		len8+=tmp;
465 	}
466 	*out=result=ntfs_malloc(len8+1); /* allow for zero-termination */
467 
468 	if(!result)
469 		return ENOMEM;
470 	result[len8]='\0';
471 	*out_len=len8;
472 	for(i=len8=0;i<in_len;i++)
473 		len8+=to_utf8(le16_to_cpu( *(in+i) ),result+len8);
474 	return 0;
475 }
476 
477 /* Converts an UTF-8 sequence to a wide string. Same conventions as the
478  * previous function
479  */
480 static int ntfs_duputf82uni(unsigned char* in, int in_len,wchar_t** out,int *out_len)
481 {
482 	int i,tmp;
483 	int len16;
484 
485 	wchar_t* result;
486 	wchar_t wtmp;
487 	for(i=len16=0;i<in_len;i+=tmp,len16++){
488 		tmp=from_utf8(in+i,&wtmp);
489 		if(!tmp)
490 			return EILSEQ;
491 	}
492 	*out=result=ntfs_malloc(2*(len16+1));
493 	if(!result)
494 		return ENOMEM;
495 	result[len16]=0;
496 	*out_len=len16;
497 	for(i=len16=0;i<in_len;i+=tmp,len16++)
498 	{
499 		tmp=from_utf8(in+i, &wtmp);
500 		*(result+len16) = cpu_to_le16(wtmp);
501 	}
502 	return 0;
503 }
504 
505 
506 /**
507  * ntfs_ucstombs - convert a little endian Unicode string to a multibyte string
508  * @ins:	input Unicode string buffer
509  * @ins_len:	length of input string in Unicode characters
510  * @outs:	on return contains the (allocated) output multibyte string
511  * @outs_len:	length of output buffer in bytes
512  *
513  * Convert the input little endian, 2-byte Unicode string @ins, of length
514  * @ins_len into the multibyte string format dictated by the current locale.
515  *
516  * If *@outs is NULL, the function allocates the string and the caller is
517  * responsible for calling free(*@outs); when finished with it.
518  *
519  * On success the function returns the number of bytes written to the output
520  * string *@outs (>= 0), not counting the terminating NULL byte. If the output
521  * string buffer was allocated, *@outs is set to it.
522  *
523  * On error, -1 is returned, and errno is set to the error code. The following
524  * error codes can be expected:
525  *	EINVAL		Invalid arguments (e.g. @ins or @outs is NULL).
526  *	EILSEQ		The input string cannot be represented as a multibyte
527  *			sequence according to the current locale.
528  *	ENAMETOOLONG	Destination buffer is too small for input string.
529  *	ENOMEM		Not enough memory to allocate destination buffer.
530  */
531 int ntfs_ucstombs(const ntfschar *ins, const int ins_len, char **outs,	int outs_len)
532 {
533 	int out_len = outs_len;
534 	if(ntfs_dupuni2utf8(ins,ins_len,outs,&out_len)==0)
535 	  	return out_len;
536 	else
537 		return EINVAL;
538 }
539 
540 /**
541  * ntfs_mbstoucs - convert a multibyte string to a little endian Unicode string
542  * @ins:	input multibyte string buffer
543  * @outs:	on return contains the (allocated) output Unicode string
544  * @outs_len:	length of output buffer in Unicode characters
545  *
546  * Convert the input multibyte string @ins, from the current locale into the
547  * corresponding little endian, 2-byte Unicode string.
548  *
549  * If *@outs is NULL, the function allocates the string and the caller is
550  * responsible for calling free(*@outs); when finished with it.
551  *
552  * On success the function returns the number of Unicode characters written to
553  * the output string *@outs (>= 0), not counting the terminating Unicode NULL
554  * character. If the output string buffer was allocated, *@outs is set to it.
555  *
556  * On error, -1 is returned, and errno is set to the error code. The following
557  * error codes can be expected:
558  *	EINVAL		Invalid arguments (e.g. @ins or @outs is NULL).
559  *	EILSEQ		The input string cannot be represented as a Unicode
560  *			string according to the current locale.
561  *	ENAMETOOLONG	Destination buffer is too small for input string.
562  *	ENOMEM		Not enough memory to allocate destination buffer.
563  */
564 int ntfs_mbstoucs(const char *ins, ntfschar **outs, int outs_len)
565 {
566 	int in_len = strlen(ins);
567 	int out_len = outs_len;
568 	if(ntfs_duputf82uni(ins,in_len,outs,&out_len)==0)
569 		return out_len;
570 	else
571 		return EILSEQ;
572 }
573 
574 #else
575 
576 /**
577  * ntfs_ucstombs - convert a little endian Unicode string to a multibyte string
578  * @ins:	input Unicode string buffer
579  * @ins_len:	length of input string in Unicode characters
580  * @outs:	on return contains the (allocated) output multibyte string
581  * @outs_len:	length of output buffer in bytes
582  *
583  * Convert the input little endian, 2-byte Unicode string @ins, of length
584  * @ins_len into the multibyte string format dictated by the current locale.
585  *
586  * If *@outs is NULL, the function allocates the string and the caller is
587  * responsible for calling free(*@outs); when finished with it.
588  *
589  * On success the function returns the number of bytes written to the output
590  * string *@outs (>= 0), not counting the terminating NULL byte. If the output
591  * string buffer was allocated, *@outs is set to it.
592  *
593  * On error, -1 is returned, and errno is set to the error code. The following
594  * error codes can be expected:
595  *	EINVAL		Invalid arguments (e.g. @ins or @outs is NULL).
596  *	EILSEQ		The input string cannot be represented as a multibyte
597  *			sequence according to the current locale.
598  *	ENAMETOOLONG	Destination buffer is too small for input string.
599  *	ENOMEM		Not enough memory to allocate destination buffer.
600  */
601 int ntfs_ucstombs(const ntfschar *ins, const int ins_len, char **outs,
602 		int outs_len)
603 {
604 	char *mbs;
605 	wchar_t wc;
606 	int i, o, mbs_len;
607 	int cnt = 0;
608 #ifdef HAVE_MBSINIT
609 	mbstate_t mbstate;
610 #endif
611 
612 	if (!ins || !outs) {
613 		errno = EINVAL;
614 		return -1;
615 	}
616 	mbs = *outs;
617 	mbs_len = outs_len;
618 	if (mbs && !mbs_len) {
619 		errno = ENAMETOOLONG;
620 		return -1;
621 	}
622 	if (!mbs) {
623 		mbs_len = (ins_len + 1) * MB_CUR_MAX;
624 		mbs = ntfs_malloc(mbs_len);
625 		if (!mbs)
626 			return -1;
627 	}
628 #ifdef HAVE_MBSINIT
629 	memset(&mbstate, 0, sizeof(mbstate));
630 #else
631 	wctomb(NULL, 0);
632 #endif
633 	for (i = o = 0; i < ins_len; i++) {
634 		/* Reallocate memory if necessary or abort. */
635 		if ((int)(o + MB_CUR_MAX) > mbs_len) {
636 			char *tc;
637 			if (mbs == *outs) {
638 				errno = ENAMETOOLONG;
639 				return -1;
640 			}
641 			tc = ntfs_malloc((mbs_len + 64) & ~63);
642 			if (!tc)
643 				goto err_out;
644 			memcpy(tc, mbs, mbs_len);
645 			mbs_len = (mbs_len + 64) & ~63;
646 			free(mbs);
647 			mbs = tc;
648 		}
649 		/* Convert the LE Unicode character to a CPU wide character. */
650 		wc = (wchar_t)le16_to_cpu(ins[i]);
651 		if (!wc)
652 			break;
653 		/* Convert the CPU endian wide character to multibyte. */
654 #ifdef HAVE_MBSINIT
655 		cnt = wcrtomb(mbs + o, wc, &mbstate);
656 #else
657 		cnt = wctomb(mbs + o, wc);
658 #endif
659 		if (cnt == -1)
660 			goto err_out;
661 		if (cnt <= 0) {
662 			ntfs_log_debug("Eeek. cnt <= 0, cnt = %i\n", cnt);
663 			errno = EINVAL;
664 			goto err_out;
665 		}
666 		o += cnt;
667 	}
668 #ifdef HAVE_MBSINIT
669 	/* Make sure we are back in the initial state. */
670 	if (!mbsinit(&mbstate)) {
671 		ntfs_log_debug("Eeek. mbstate not in initial state!\n");
672 		errno = EILSEQ;
673 		goto err_out;
674 	}
675 #endif
676 	/* Now write the NULL character. */
677 	mbs[o] = '\0';
678 	if (*outs != mbs)
679 		*outs = mbs;
680 	return o;
681 err_out:
682 	if (mbs != *outs) {
683 		int eo = errno;
684 		free(mbs);
685 		errno = eo;
686 	}
687 	return -1;
688 }
689 
690 /**
691  * ntfs_mbstoucs - convert a multibyte string to a little endian Unicode string
692  * @ins:	input multibyte string buffer
693  * @outs:	on return contains the (allocated) output Unicode string
694  * @outs_len:	length of output buffer in Unicode characters
695  *
696  * Convert the input multibyte string @ins, from the current locale into the
697  * corresponding little endian, 2-byte Unicode string.
698  *
699  * If *@outs is NULL, the function allocates the string and the caller is
700  * responsible for calling free(*@outs); when finished with it.
701  *
702  * On success the function returns the number of Unicode characters written to
703  * the output string *@outs (>= 0), not counting the terminating Unicode NULL
704  * character. If the output string buffer was allocated, *@outs is set to it.
705  *
706  * On error, -1 is returned, and errno is set to the error code. The following
707  * error codes can be expected:
708  *	EINVAL		Invalid arguments (e.g. @ins or @outs is NULL).
709  *	EILSEQ		The input string cannot be represented as a Unicode
710  *			string according to the current locale.
711  *	ENAMETOOLONG	Destination buffer is too small for input string.
712  *	ENOMEM		Not enough memory to allocate destination buffer.
713  */
714 int ntfs_mbstoucs(const char *ins, ntfschar **outs, int outs_len)
715 {
716 	ntfschar *ucs;
717 	const char *s;
718 	wchar_t wc;
719 	int i, o, cnt, ins_len, ucs_len, ins_size;
720 #ifdef HAVE_MBSINIT
721 	mbstate_t mbstate;
722 #endif
723 
724 	if (!ins || !outs) {
725 		errno = EINVAL;
726 		return -1;
727 	}
728 	ucs = *outs;
729 	ucs_len = outs_len;
730 	if (ucs && !ucs_len) {
731 		errno = ENAMETOOLONG;
732 		return -1;
733 	}
734 	/* Determine the size of the multi-byte string in bytes. */
735 	ins_size = strlen(ins);
736 	/* Determine the length of the multi-byte string. */
737 	s = ins;
738 #if defined(HAVE_MBSINIT)
739 	memset(&mbstate, 0, sizeof(mbstate));
740 	ins_len = mbsrtowcs(NULL, (const char **)&s, 0, &mbstate);
741 #ifdef __CYGWIN32__
742 	if (!ins_len && *ins) {
743 		/* Older Cygwin had broken mbsrtowcs() implementation. */
744 		ins_len = strlen(ins);
745 	}
746 #endif
747 #elif !defined(DJGPP)
748 	ins_len = mbstowcs(NULL, s, 0);
749 #else
750 	/* Eeek!!! DJGPP has broken mbstowcs() implementation!!! */
751 	ins_len = strlen(ins);
752 #endif
753 	if (ins_len == -1)
754 		return ins_len;
755 #ifdef HAVE_MBSINIT
756 	if ((s != ins) || !mbsinit(&mbstate)) {
757 #else
758 	if (s != ins) {
759 #endif
760 		errno = EILSEQ;
761 		return -1;
762 	}
763 	/* Add the NULL terminator. */
764 	ins_len++;
765 	if (!ucs) {
766 		ucs_len = ins_len;
767 		ucs = ntfs_malloc(ucs_len * sizeof(ntfschar));
768 		if (!ucs)
769 			return -1;
770 	}
771 #ifdef HAVE_MBSINIT
772 	memset(&mbstate, 0, sizeof(mbstate));
773 #else
774 	mbtowc(NULL, NULL, 0);
775 #endif
776 	for (i = o = cnt = 0; i < ins_size; i += cnt, o++) {
777 		/* Reallocate memory if necessary or abort. */
778 		if (o >= ucs_len) {
779 			ntfschar *tc;
780 			if (ucs == *outs) {
781 				errno = ENAMETOOLONG;
782 				return -1;
783 			}
784 			/*
785 			 * We will never get here but hey, it's only a bit of
786 			 * extra code...
787 			 */
788 			ucs_len = (ucs_len * sizeof(ntfschar) + 64) & ~63;
789 			tc = (ntfschar*)realloc(ucs, ucs_len);
790 			if (!tc)
791 				goto err_out;
792 			ucs = tc;
793 			ucs_len /= sizeof(ntfschar);
794 		}
795 		/* Convert the multibyte character to a wide character. */
796 #ifdef HAVE_MBSINIT
797 		cnt = mbrtowc(&wc, ins + i, ins_size - i, &mbstate);
798 #else
799 		cnt = mbtowc(&wc, ins + i, ins_size - i);
800 #endif
801 		if (!cnt)
802 			break;
803 		if (cnt == -1)
804 			goto err_out;
805 		if (cnt < -1) {
806 			ntfs_log_trace("Eeek. cnt = %i\n", cnt);
807 			errno = EINVAL;
808 			goto err_out;
809 		}
810 		/* Make sure we are not overflowing the NTFS Unicode set. */
811 		if ((unsigned long)wc >= (unsigned long)(1 <<
812 				(8 * sizeof(ntfschar)))) {
813 			errno = EILSEQ;
814 			goto err_out;
815 		}
816 		/* Convert the CPU wide character to a LE Unicode character. */
817 		ucs[o] = cpu_to_le16(wc);
818 	}
819 #ifdef HAVE_MBSINIT
820 	/* Make sure we are back in the initial state. */
821 	if (!mbsinit(&mbstate)) {
822 		ntfs_log_trace("Eeek. mbstate not in initial state!\n");
823 		errno = EILSEQ;
824 		goto err_out;
825 	}
826 #endif
827 	/* Now write the NULL character. */
828 	ucs[o] = cpu_to_le16(L'\0');
829 	if (*outs != ucs)
830 		*outs = ucs;
831 	return o;
832 err_out:
833 	if (ucs != *outs) {
834 		int eo = errno;
835 		free(ucs);
836 		errno = eo;
837 	}
838 	return -1;
839 }
840 
841 #endif
842 
843 /**
844  * ntfs_upcase_table_build - build the default upcase table for NTFS
845  * @uc:		destination buffer where to store the built table
846  * @uc_len:	size of destination buffer in bytes
847  *
848  * ntfs_upcase_table_build() builds the default upcase table for NTFS and
849  * stores it in the caller supplied buffer @uc of size @uc_len.
850  *
851  * Note, @uc_len must be at least 128kiB in size or bad things will happen!
852  */
853 void ntfs_upcase_table_build(ntfschar *uc, u32 uc_len)
854 {
855 	static int uc_run_table[][3] = { /* Start, End, Add */
856 	{0x0061, 0x007B,  -32}, {0x0451, 0x045D, -80}, {0x1F70, 0x1F72,  74},
857 	{0x00E0, 0x00F7,  -32}, {0x045E, 0x0460, -80}, {0x1F72, 0x1F76,  86},
858 	{0x00F8, 0x00FF,  -32}, {0x0561, 0x0587, -48}, {0x1F76, 0x1F78, 100},
859 	{0x0256, 0x0258, -205}, {0x1F00, 0x1F08,   8}, {0x1F78, 0x1F7A, 128},
860 	{0x028A, 0x028C, -217}, {0x1F10, 0x1F16,   8}, {0x1F7A, 0x1F7C, 112},
861 	{0x03AC, 0x03AD,  -38}, {0x1F20, 0x1F28,   8}, {0x1F7C, 0x1F7E, 126},
862 	{0x03AD, 0x03B0,  -37}, {0x1F30, 0x1F38,   8}, {0x1FB0, 0x1FB2,   8},
863 	{0x03B1, 0x03C2,  -32}, {0x1F40, 0x1F46,   8}, {0x1FD0, 0x1FD2,   8},
864 	{0x03C2, 0x03C3,  -31}, {0x1F51, 0x1F52,   8}, {0x1FE0, 0x1FE2,   8},
865 	{0x03C3, 0x03CC,  -32}, {0x1F53, 0x1F54,   8}, {0x1FE5, 0x1FE6,   7},
866 	{0x03CC, 0x03CD,  -64}, {0x1F55, 0x1F56,   8}, {0x2170, 0x2180, -16},
867 	{0x03CD, 0x03CF,  -63}, {0x1F57, 0x1F58,   8}, {0x24D0, 0x24EA, -26},
868 	{0x0430, 0x0450,  -32}, {0x1F60, 0x1F68,   8}, {0xFF41, 0xFF5B, -32},
869 	{0}
870 	};
871 	static int uc_dup_table[][2] = { /* Start, End */
872 	{0x0100, 0x012F}, {0x01A0, 0x01A6}, {0x03E2, 0x03EF}, {0x04CB, 0x04CC},
873 	{0x0132, 0x0137}, {0x01B3, 0x01B7}, {0x0460, 0x0481}, {0x04D0, 0x04EB},
874 	{0x0139, 0x0149}, {0x01CD, 0x01DD}, {0x0490, 0x04BF}, {0x04EE, 0x04F5},
875 	{0x014A, 0x0178}, {0x01DE, 0x01EF}, {0x04BF, 0x04BF}, {0x04F8, 0x04F9},
876 	{0x0179, 0x017E}, {0x01F4, 0x01F5}, {0x04C1, 0x04C4}, {0x1E00, 0x1E95},
877 	{0x018B, 0x018B}, {0x01FA, 0x0218}, {0x04C7, 0x04C8}, {0x1EA0, 0x1EF9},
878 	{0}
879 	};
880 	static int uc_byte_table[][2] = { /* Offset, Value */
881 	{0x00FF, 0x0178}, {0x01AD, 0x01AC}, {0x01F3, 0x01F1}, {0x0269, 0x0196},
882 	{0x0183, 0x0182}, {0x01B0, 0x01AF}, {0x0253, 0x0181}, {0x026F, 0x019C},
883 	{0x0185, 0x0184}, {0x01B9, 0x01B8}, {0x0254, 0x0186}, {0x0272, 0x019D},
884 	{0x0188, 0x0187}, {0x01BD, 0x01BC}, {0x0259, 0x018F}, {0x0275, 0x019F},
885 	{0x018C, 0x018B}, {0x01C6, 0x01C4}, {0x025B, 0x0190}, {0x0283, 0x01A9},
886 	{0x0192, 0x0191}, {0x01C9, 0x01C7}, {0x0260, 0x0193}, {0x0288, 0x01AE},
887 	{0x0199, 0x0198}, {0x01CC, 0x01CA}, {0x0263, 0x0194}, {0x0292, 0x01B7},
888 	{0x01A8, 0x01A7}, {0x01DD, 0x018E}, {0x0268, 0x0197},
889 	{0}
890 	};
891 	int i, r;
892 
893 	memset((char*)uc, 0, uc_len);
894 	uc_len >>= 1;
895 	if (uc_len > 65536)
896 		uc_len = 65536;
897 	for (i = 0; (u32)i < uc_len; i++)
898 		uc[i] = i;
899 	for (r = 0; uc_run_table[r][0]; r++)
900 		for (i = uc_run_table[r][0]; i < uc_run_table[r][1]; i++)
901 			uc[i] += uc_run_table[r][2];
902 	for (r = 0; uc_dup_table[r][0]; r++)
903 		for (i = uc_dup_table[r][0]; i < uc_dup_table[r][1]; i += 2)
904 			uc[i + 1]--;
905 	for (r = 0; uc_byte_table[r][0]; r++)
906 		uc[uc_byte_table[r][0]] = uc_byte_table[r][1];
907 }
908 
909 /**
910  * ntfs_str2ucs - convert a string to a valid NTFS file name
911  * @s:		input string
912  * @len:	length of output buffer in Unicode characters
913  *
914  * Convert the input @s string into the corresponding little endian,
915  * 2-byte Unicode string. The length of the converted string is less
916  * or equal to the maximum length allowed by the NTFS format (255).
917  *
918  * If @s is NULL then return AT_UNNAMED.
919  *
920  * On success the function returns the Unicode string in an allocated
921  * buffer and the caller is responsible to free it when it's not needed
922  * anymore.
923  *
924  * On error NULL is returned and errno is set to the error code.
925  */
926 ntfschar *ntfs_str2ucs(const char *s, int *len)
927 {
928 	ntfschar *ucs = NULL;
929 
930 	if (s && ((*len = ntfs_mbstoucs(s, &ucs, 0)) == -1)) {
931 		ntfs_log_perror("Couldn't convert '%s' to Unicode", s);
932 		return NULL;
933 	}
934 	if (*len > NTFS_MAX_NAME_LEN) {
935 		free(ucs);
936 		errno = ENAMETOOLONG;
937 		return NULL;
938 	}
939 	if (!ucs || !*len) {
940 		ucs  = AT_UNNAMED;
941 		*len = 0;
942 	}
943 	return ucs;
944 }
945 
946 /**
947  * ntfs_ucsfree - free memory allocated by ntfs_str2ucs()
948  * @ucs		input string to be freed
949  *
950  * Free memory at @ucs and which was allocated by ntfs_str2ucs.
951  *
952  * Return value: none.
953  */
954 void ntfs_ucsfree(ntfschar *ucs)
955 {
956 	if (ucs && (ucs != AT_UNNAMED))
957 		free(ucs);
958 }
959 
960