xref: /netbsd-src/sys/fs/msdosfs/msdosfs_conv.c (revision 181254a7b1bdde6873432bffef2d2decc4b5c22f)
1 /*	$NetBSD: msdosfs_conv.c,v 1.17 2016/06/30 09:34:01 nonaka Exp $	*/
2 
3 /*-
4  * Copyright (C) 1995, 1997 Wolfgang Solfrank.
5  * Copyright (C) 1995, 1997 TooLs GmbH.
6  * All rights reserved.
7  * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below).
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  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *	This product includes software developed by TooLs GmbH.
20  * 4. The name of TooLs GmbH may not be used to endorse or promote products
21  *    derived from this software without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
29  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
30  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
31  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
32  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 /*
35  * Written by Paul Popelka (paulp@uts.amdahl.com)
36  *
37  * You can do anything you want with this software, just don't say you wrote
38  * it, and don't remove this notice.
39  *
40  * This software is provided "as is".
41  *
42  * The author supplies this software to be publicly redistributed on the
43  * understanding that the author is not responsible for the correct
44  * functioning of this software in any circumstances and is not liable for
45  * any damages caused by this software.
46  *
47  * October 1992
48  *
49  */
50 
51 #if HAVE_NBTOOL_CONFIG_H
52 #include "nbtool_config.h"
53 #endif
54 
55 #ifndef _KERNEL
56 #include <assert.h>
57 #define KASSERT(x)     assert(x)
58 #endif
59 
60 #include <sys/cdefs.h>
61 __KERNEL_RCSID(0, "$NetBSD: msdosfs_conv.c,v 1.17 2016/06/30 09:34:01 nonaka Exp $");
62 
63 /*
64  * System include files.
65  */
66 #include <sys/param.h>
67 #include <sys/time.h>
68 #include <sys/endian.h>
69 #ifdef _KERNEL
70 #include <sys/dirent.h>
71 #include <sys/systm.h>
72 #include <sys/kernel.h>
73 #include <sys/vnode.h>
74 #else
75 #include <stdio.h>
76 #include <string.h>
77 #include <dirent.h>
78 #include <sys/queue.h>
79 #endif
80 #include <dev/clock_subr.h>
81 
82 /*
83  * MSDOSFS include files.
84  */
85 #include <fs/msdosfs/direntry.h>
86 #include <fs/msdosfs/denode.h>
87 
88 static int invalidname(const u_int16_t *, int);
89 
90 static int ucs2utf8(const u_int16_t *, u_int8_t *, int);
91 static int utf8ucs2(const u_int8_t *, int, u_int16_t *);
92 
93 static int ucs2utf8str(const u_int16_t *, int, u_int8_t *, int);
94 static int utf8ucs2str(const u_int8_t *, int, u_int16_t *, int);
95 static int ucs2char8str(const u_int16_t *, int, u_int8_t *, int);
96 static int char8ucs2str(const u_int8_t *, int, u_int16_t *, int);
97 
98 static void ucs2pad(u_int16_t *, int, int);
99 
100 static u_int16_t ucs2fold(u_int16_t);
101 static int ucs2match(u_int16_t *, u_int16_t *, int n);
102 static int char8match(u_int16_t *, u_int16_t *, int n);
103 
104 /*
105  * The number of seconds between Jan 1, 1970 and Jan 1, 1980. In that
106  * interval there were 8 regular years and 2 leap years.
107  */
108 #define	DOSBIASYEAR	1980
109 #define	SECONDSTO1980	(((8 * 365) + (2 * 366)) * (24 * 60 * 60))
110 /*
111  * msdos fs can not store dates beyound the year 2234
112  */
113 #define DOSMAXYEAR	((DD_YEAR_MASK >> DD_YEAR_SHIFT) + DOSBIASYEAR)
114 
115 /*
116  * Convert the unix version of time to dos's idea of time to be used in
117  * file timestamps. The passed in unix time is assumed to be in GMT.
118  */
119 void
120 unix2dostime(const struct timespec *tsp, int gmtoff, u_int16_t *ddp, u_int16_t *dtp, u_int8_t *dhp)
121 {
122 	u_long t;
123 	struct clock_ymdhms ymd;
124 
125 	t = tsp->tv_sec + gmtoff; /* time zone correction */
126 
127 	/*
128 	 * DOS timestamps can not represent dates before 1980.
129 	 */
130 	if (t < SECONDSTO1980)
131 		goto invalid_dos_date;
132 
133 	/*
134 	 * DOS granularity is 2 seconds
135 	 */
136 	t &= ~1;
137 
138 	/*
139 	 * Convert to year/month/day/.. format
140 	 */
141 	clock_secs_to_ymdhms(t, &ymd);
142 	if (ymd.dt_year > DOSMAXYEAR)
143 		goto invalid_dos_date;
144 
145 	/*
146 	 * Now transform to DOS format
147 	 */
148 	*ddp = (ymd.dt_day << DD_DAY_SHIFT)
149 	    + (ymd.dt_mon << DD_MONTH_SHIFT)
150 	    + ((ymd.dt_year - DOSBIASYEAR) << DD_YEAR_SHIFT);
151 	if (dhp)
152 		*dhp = (tsp->tv_sec & 1) * 100 + tsp->tv_nsec / 10000000;
153 	if (dtp)
154 		*dtp = (((t / 2) % 30) << DT_2SECONDS_SHIFT)
155 		    + (((t / 60) % 60) << DT_MINUTES_SHIFT)
156 		    + (((t / 3600) % 24) << DT_HOURS_SHIFT);
157 	return;
158 
159 invalid_dos_date:
160 	*ddp = 0;
161 	if (dtp)
162 		*dtp = 0;
163 	if (dhp)
164 		*dhp = 0;
165 }
166 
167 /*
168  * Convert from dos' idea of time to unix'. This will probably only be
169  * called from the stat(), and fstat() system calls and so probably need
170  * not be too efficient.
171  */
172 void
173 dos2unixtime(u_int dd, u_int dt, u_int dh, int gmtoff, struct timespec *tsp)
174 {
175 	time_t seconds;
176 	struct clock_ymdhms ymd;
177 
178 	if (dd == 0) {
179 		/*
180 		 * Uninitialized field, return the epoch.
181 		 */
182 		tsp->tv_sec = 0;
183 		tsp->tv_nsec = 0;
184 		return;
185 	}
186 
187 	memset(&ymd, 0, sizeof(ymd));
188 	ymd.dt_year = ((dd & DD_YEAR_MASK) >> DD_YEAR_SHIFT) + 1980 ;
189 	ymd.dt_mon = ((dd & DD_MONTH_MASK) >> DD_MONTH_SHIFT);
190 	ymd.dt_day = ((dd & DD_DAY_MASK) >> DD_DAY_SHIFT);
191 	ymd.dt_hour = (dt & DT_HOURS_MASK) >> DT_HOURS_SHIFT;
192 	ymd.dt_min = (dt & DT_MINUTES_MASK) >> DT_MINUTES_SHIFT;
193 	ymd.dt_sec = ((dt & DT_2SECONDS_MASK) >> DT_2SECONDS_SHIFT) * 2;
194 
195 	seconds = clock_ymdhms_to_secs(&ymd);
196 
197 	tsp->tv_sec = seconds;
198 	tsp->tv_sec -= gmtoff;	/* time zone correction */
199 	tsp->tv_nsec = (dh % 100) * 10000000;
200 }
201 
202 static const u_char
203 unix2dos[256] = {
204 	0,    0,    0,    0,    0,    0,    0,    0,	/* 00-07 */
205 	0,    0,    0,    0,    0,    0,    0,    0,	/* 08-0f */
206 	0,    0,    0,    0,    0,    0,    0,    0,	/* 10-17 */
207 	0,    0,    0,    0,    0,    0,    0,    0,	/* 18-1f */
208 	0,    '!',  0,    '#',  '$',  '%',  '&',  '\'',	/* 20-27 */
209 	'(',  ')',  0,    '+',  0,    '-',  0,    0,	/* 28-2f */
210 	'0',  '1',  '2',  '3',  '4',  '5',  '6',  '7',	/* 30-37 */
211 	'8',  '9',  0,    0,    0,    0,    0,    0,	/* 38-3f */
212 	'@',  'A',  'B',  'C',  'D',  'E',  'F',  'G',	/* 40-47 */
213 	'H',  'I',  'J',  'K',  'L',  'M',  'N',  'O',	/* 48-4f */
214 	'P',  'Q',  'R',  'S',  'T',  'U',  'V',  'W',	/* 50-57 */
215 	'X',  'Y',  'Z',  0,    0,    0,    '^',  '_',	/* 58-5f */
216 	'`',  'A',  'B',  'C',  'D',  'E',  'F',  'G',	/* 60-67 */
217 	'H',  'I',  'J',  'K',  'L',  'M',  'N',  'O',	/* 68-6f */
218 	'P',  'Q',  'R',  'S',  'T',  'U',  'V',  'W',	/* 70-77 */
219 	'X',  'Y',  'Z',  '{',  0,    '}',  '~',  0,	/* 78-7f */
220 	0,    0,    0,    0,    0,    0,    0,    0,	/* 80-87 */
221 	0,    0,    0,    0,    0,    0,    0,    0,	/* 88-8f */
222 	0,    0,    0,    0,    0,    0,    0,    0,	/* 90-97 */
223 	0,    0,    0,    0,    0,    0,    0,    0,	/* 98-9f */
224 	0,    0xad, 0xbd, 0x9c, 0xcf, 0xbe, 0xdd, 0xf5,	/* a0-a7 */
225 	0xf9, 0xb8, 0xa6, 0xae, 0xaa, 0xf0, 0xa9, 0xee,	/* a8-af */
226 	0xf8, 0xf1, 0xfd, 0xfc, 0xef, 0xe6, 0xf4, 0xfa,	/* b0-b7 */
227 	0xf7, 0xfb, 0xa7, 0xaf, 0xac, 0xab, 0xf3, 0xa8,	/* b8-bf */
228 	0xb7, 0xb5, 0xb6, 0xc7, 0x8e, 0x8f, 0x92, 0x80,	/* c0-c7 */
229 	0xd4, 0x90, 0xd2, 0xd3, 0xde, 0xd6, 0xd7, 0xd8,	/* c8-cf */
230 	0xd1, 0xa5, 0xe3, 0xe0, 0xe2, 0xe5, 0x99, 0x9e,	/* d0-d7 */
231 	0x9d, 0xeb, 0xe9, 0xea, 0x9a, 0xed, 0xe8, 0xe1,	/* d8-df */
232 	0xb7, 0xb5, 0xb6, 0xc7, 0x8e, 0x8f, 0x92, 0x80,	/* e0-e7 */
233 	0xd4, 0x90, 0xd2, 0xd3, 0xde, 0xd6, 0xd7, 0xd8,	/* e8-ef */
234 	0xd1, 0xa5, 0xe3, 0xe0, 0xe2, 0xe5, 0x99, 0xf6,	/* f0-f7 */
235 	0x9d, 0xeb, 0xe9, 0xea, 0x9a, 0xed, 0xe8, 0x98,	/* f8-ff */
236 };
237 
238 static const u_char
239 dos2unix[256] = {
240 	 '?',  '?',  '?',  '?',  '?',  '?',  '?',  '?',	/* 00-07 */
241 	 '?',  '?',  '?',  '?',  '?',  '?',  '?',  '?',	/* 08-0f */
242 	 '?',  '?',  '?',  '?',  '?',  '?',  '?',  '?',	/* 10-17 */
243 	 '?',  '?',  '?',  '?',  '?',  '?',  '?',  '?',	/* 18-1f */
244 	 ' ',  '!',  '"',  '#',  '$',  '%',  '&', '\'',	/* 20-27 */
245 	 '(',  ')',  '*',  '+',  ',',  '-',  '.',  '/',	/* 28-2f */
246 	 '0',  '1',  '2',  '3',  '4',  '5',  '6',  '7',	/* 30-37 */
247 	 '8',  '9',  ':',  ';',  '<',  '=',  '>',  '?',	/* 38-3f */
248 	 '@',  'A',  'B',  'C',  'D',  'E',  'F',  'G',	/* 40-47 */
249 	 'H',  'I',  'J',  'K',  'L',  'M',  'N',  'O',	/* 48-4f */
250 	 'P',  'Q',  'R',  'S',  'T',  'U',  'V',  'W',	/* 50-57 */
251 	 'X',  'Y',  'Z',  '[', '\\',  ']',  '^',  '_',	/* 58-5f */
252 	 '`',  'a',  'b',  'c',  'd',  'e',  'f',  'g',	/* 60-67 */
253 	 'h',  'i',  'j',  'k',  'l',  'm',  'n',  'o',	/* 68-6f */
254 	 'p',  'q',  'r',  's',  't',  'u',  'v',  'w',	/* 70-77 */
255 	 'x',  'y',  'z',  '{',  '|',  '}',  '~', 0x7f,	/* 78-7f */
256 	0xc7, 0xfc, 0xe9, 0xe2, 0xe4, 0xe0, 0xe5, 0xe7,	/* 80-87 */
257 	0xea, 0xeb, 0xe8, 0xef, 0xee, 0xec, 0xc4, 0xc5,	/* 88-8f */
258 	0xc9, 0xe6, 0xc6, 0xf4, 0xf6, 0xf2, 0xfb, 0xf9,	/* 90-97 */
259 	0xff, 0xd6, 0xdc, 0xf8, 0xa3, 0xd8, 0xd7,  '?',	/* 98-9f */
260 	0xe1, 0xed, 0xf3, 0xfa, 0xf1, 0xd1, 0xaa, 0xba,	/* a0-a7 */
261 	0xbf, 0xae, 0xac, 0xbd, 0xbc, 0xa1, 0xab, 0xbb,	/* a8-af */
262 	 '?',  '?',  '?',  '?',  '?', 0xc1, 0xc2, 0xc0,	/* b0-b7 */
263 	0xa9,  '?',  '?',  '?',  '?', 0xa2, 0xa5,  '?',	/* b8-bf */
264 	 '?',  '?',  '?',  '?',  '?',  '?', 0xe3, 0xc3,	/* c0-c7 */
265 	 '?',  '?',  '?',  '?',  '?',  '?',  '?', 0xa4,	/* c8-cf */
266 	0xf0, 0xd0, 0xca, 0xcb, 0xc8,  '?', 0xcd, 0xce,	/* d0-d7 */
267 	0xcf,  '?',  '?',  '?',  '?', 0xa6, 0xcc,  '?',	/* d8-df */
268 	0xd3, 0xdf, 0xd4, 0xd2, 0xf5, 0xd5, 0xb5, 0xfe,	/* e0-e7 */
269 	0xde, 0xda, 0xdb, 0xd9, 0xfd, 0xdd, 0xaf, 0x3f,	/* e8-ef */
270 	0xad, 0xb1,  '?', 0xbe, 0xb6, 0xa7, 0xf7, 0xb8,	/* f0-f7 */
271 	0xb0, 0xa8, 0xb7, 0xb9, 0xb3, 0xb2,  '?',  '?',	/* f8-ff */
272 };
273 
274 static const u_char
275 u2l[256] = {
276 	0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* 00-07 */
277 	0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /* 08-0f */
278 	0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, /* 10-17 */
279 	0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, /* 18-1f */
280 	 ' ',  '!',  '"',  '#',  '$',  '%',  '&', '\'', /* 20-27 */
281 	 '(',  ')',  '*',  '+',  ',',  '-',  '.',  '/', /* 28-2f */
282 	 '0',  '1',  '2',  '3',  '4',  '5',  '6',  '7', /* 30-37 */
283 	 '8',  '9',  ':',  ';',  '<',  '=',  '>',  '?', /* 38-3f */
284 	 '@',  'a',  'b',  'c',  'd',  'e',  'f',  'g', /* 40-47 */
285 	 'h',  'i',  'j',  'k',  'l',  'm',  'n',  'o', /* 48-4f */
286 	 'p',  'q',  'r',  's',  't',  'u',  'v',  'w', /* 50-57 */
287 	 'x',  'y',  'z',  '[', '\\',  ']',  '^',  '_', /* 58-5f */
288 	 '`',  'a',  'b',  'c',  'd',  'e',  'f',  'g', /* 60-67 */
289 	 'h',  'i',  'j',  'k',  'l',  'm',  'n',  'o', /* 68-6f */
290 	 'p',  'q',  'r',  's',  't',  'u',  'v',  'w', /* 70-77 */
291 	 'x',  'y',  'z',  '{',  '|',  '}',  '~', 0x7f, /* 78-7f */
292 	0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /* 80-87 */
293 	0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 88-8f */
294 	0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, /* 90-97 */
295 	0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 98-9f */
296 	0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, /* a0-a7 */
297 	0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, /* a8-af */
298 	0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, /* b0-b7 */
299 	0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, /* b8-bf */
300 	0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* c0-c7 */
301 	0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* c8-cf */
302 	0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xd7, /* d0-d7 */
303 	0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xdf, /* d8-df */
304 	0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, /* e0-e7 */
305 	0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, /* e8-ef */
306 	0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, /* f0-f7 */
307 	0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, /* f8-ff */
308 };
309 
310 /*
311  * DOS filenames are made of 2 parts, the name part and the extension part.
312  * The name part is 8 characters long and the extension part is 3
313  * characters long.  They may contain trailing blanks if the name or
314  * extension are not long enough to fill their respective fields.
315  */
316 
317 /*
318  * Convert a DOS filename to a unix filename. And, return the number of
319  * characters in the resulting unix filename excluding the terminating
320  * null.
321  */
322 int
323 dos2unixfn(u_char dn[11], u_char *un, int lower)
324 {
325 	int i, j;
326 	int thislong = 1;
327 	u_char c;
328 
329 	/*
330 	 * If first char of the filename is SLOT_E5 (0x05), then the real
331 	 * first char of the filename should be 0xe5. But, they couldn't
332 	 * just have a 0xe5 mean 0xe5 because that is used to mean a freed
333 	 * directory slot. Another dos quirk.
334 	 */
335 	if (*dn == SLOT_E5)
336 		c = dos2unix[0xe5];
337 	else
338 		c = dos2unix[*dn];
339 	*un++ = lower ? u2l[c] : c;
340 
341 	/*
342 	 * Copy the rest into the unix filename string, ignoring
343 	 * trailing blanks.
344 	 */
345 
346 	for (j=7; (j >= 0) && (dn[j] == ' '); j--)
347 		;
348 
349 	for (i = 1; i <= j; i++) {
350 		c = dos2unix[dn[i]];
351 		*un++ = lower ? u2l[c] : c;
352 		thislong++;
353 	}
354 	dn += 8;
355 
356 	/*
357 	 * Now, if there is an extension then put in a period and copy in
358 	 * the extension.
359 	 */
360 	if (*dn != ' ') {
361 		*un++ = '.';
362 		thislong++;
363 		for (i = 0; i < 3 && *dn != ' '; i++) {
364 			c = dos2unix[*dn++];
365 			*un++ = lower ? u2l[c] : c;
366 			thislong++;
367 		}
368 	}
369 	*un++ = 0;
370 
371 	return (thislong);
372 }
373 
374 /*
375  * Convert a unix filename to a DOS filename according to Win95 rules.
376  * If applicable and gen is not 0, it is inserted into the converted
377  * filename as a generation number.
378  * Returns
379  *	0 if name couldn't be converted
380  *	1 if the converted name is the same as the original
381  *	  (no long filename entry necessary for Win95)
382  *	2 if conversion was successful
383  *	3 if conversion was successful and generation number was inserted
384  */
385 int
386 unix2dosfn(const u_char *un, u_char dn[12], int unlen, u_int gen)
387 {
388 	int i, j, l;
389 	int conv = 1;
390 	const u_char *cp, *dp, *dp1;
391 	u_char gentext[6], *wcp;
392 	int shortlen;
393 
394 	/*
395 	 * Fill the dos filename string with blanks. These are DOS's pad
396 	 * characters.
397 	 */
398 	for (i = 0; i < 11; i++)
399 		dn[i] = ' ';
400 	dn[11] = 0;
401 
402 	/*
403 	 * The filenames "." and ".." are handled specially, since they
404 	 * don't follow dos filename rules.
405 	 */
406 	if (un[0] == '.' && unlen == 1) {
407 		dn[0] = '.';
408 		return gen <= 1;
409 	}
410 	if (un[0] == '.' && un[1] == '.' && unlen == 2) {
411 		dn[0] = '.';
412 		dn[1] = '.';
413 		return gen <= 1;
414 	}
415 
416 	/*
417 	 * Filenames with only blanks and dots are not allowed!
418 	 */
419 	for (cp = un, i = unlen; --i >= 0; cp++)
420 		if (*cp != ' ' && *cp != '.')
421 			break;
422 	if (i < 0)
423 		return 0;
424 
425 	/*
426 	 * Now find the extension
427 	 * Note: dot as first char doesn't start extension
428 	 *	 and trailing dots and blanks are ignored
429 	 */
430 	dp = dp1 = 0;
431 	for (cp = un + 1, i = unlen - 1; --i >= 0;) {
432 		switch (*cp++) {
433 		case '.':
434 			if (!dp1)
435 				dp1 = cp;
436 			break;
437 		case ' ':
438 			break;
439 		default:
440 			if (dp1)
441 				dp = dp1;
442 			dp1 = 0;
443 			break;
444 		}
445 	}
446 
447 	/*
448 	 * Now convert it
449 	 */
450 	if (dp) {
451 		if (dp1)
452 			l = dp1 - dp;
453 		else
454 			l = unlen - (dp - un);
455 		for (i = 0, j = 8; i < l && j < 11; i++, j++) {
456 			if (dp[i] != (dn[j] = unix2dos[dp[i]])
457 			    && conv != 3)
458 				conv = 2;
459 			if (!dn[j]) {
460 				conv = 3;
461 				dn[j--] = ' ';
462 			}
463 		}
464 		if (i < l)
465 			conv = 3;
466 		dp--;
467 	} else {
468 		for (dp = cp; *--dp == ' ' || *dp == '.';);
469 		dp++;
470 	}
471 
472 	shortlen = (dp - un) <= 8;
473 
474 	/*
475 	 * Now convert the rest of the name
476 	 */
477 	for (i = j = 0; un < dp && j < 8; i++, j++, un++) {
478 		if ((*un == ' ') && shortlen)
479 			dn[j] = ' ';
480 		else
481 			dn[j] = unix2dos[*un];
482 		if ((*un != dn[j])
483 		    && conv != 3)
484 			conv = 2;
485 		if (!dn[j]) {
486 			conv = 3;
487 			dn[j--] = ' ';
488 		}
489 	}
490 	if (un < dp)
491 		conv = 3;
492 	/*
493 	 * If we didn't have any chars in filename,
494 	 * generate a default
495 	 */
496 	if (!j)
497 		dn[0] = '_';
498 
499 	/*
500 	 * The first character cannot be E5,
501 	 * because that means a deleted entry
502 	 */
503 	if (dn[0] == 0xe5)
504 		dn[0] = SLOT_E5;
505 
506 	/*
507 	 * If there wasn't any char dropped,
508 	 * there is no place for generation numbers
509 	 */
510 	if (conv != 3) {
511 		if (gen > 1)
512 			return 0;
513 		return conv;
514 	}
515 
516 	/*
517 	 * Now insert the generation number into the filename part
518 	 */
519 	for (wcp = gentext + sizeof(gentext); wcp > gentext && gen; gen /= 10)
520 		*--wcp = gen % 10 + '0';
521 	if (gen)
522 		return 0;
523 	for (i = 8; dn[--i] == ' ';);
524 	i++;
525 	if (gentext + sizeof(gentext) - wcp + 1 > 8 - i)
526 		i = 8 - (gentext + sizeof(gentext) - wcp + 1);
527 	dn[i++] = '~';
528 	while (wcp < gentext + sizeof(gentext))
529 		dn[i++] = *wcp++;
530 	return 3;
531 }
532 
533 /*
534  * Create a Win95 long name directory entry
535  * Note: assumes that the filename is valid,
536  *	 i.e. doesn't consist solely of blanks and dots
537  */
538 int
539 unix2winfn(const u_char *un, int unlen, struct winentry *wep, int cnt, int chksum, int utf8)
540 {
541 	u_int16_t wn[WIN_MAXLEN], *p;
542 	int i, len;
543 	const u_char *cp;
544 
545 	/*
546 	 * Drop trailing blanks and dots
547 	 */
548 	for (cp = un + unlen; unlen > 0; unlen--)
549 		if (*--cp != ' ' && *cp != '.')
550 			break;
551 
552 	/*
553 	 * Offset of this entry
554 	 */
555 	i = (cnt - 1) * WIN_CHARS;
556 
557 	/*
558 	 * Translate UNIX name to ucs-2
559 	 */
560 	len = utf8 ? utf8ucs2str(un, unlen, wn, WIN_MAXLEN) : char8ucs2str(un, unlen, wn, WIN_MAXLEN);
561 	ucs2pad(wn, len, WIN_MAXLEN);
562 
563 	/*
564 	 * Initialize winentry to some useful default
565 	 */
566 	memset(wep, 0xff, sizeof(*wep));
567 	wep->weCnt = cnt;
568 	wep->weAttributes = ATTR_WIN95;
569 	wep->weReserved1 = 0;
570 	wep->weChksum = chksum;
571 	wep->weReserved2 = 0;
572 
573 	/*
574 	 * Store name segment into directory entry
575 	 */
576 	p = &wn[i];
577 	memcpy(wep->wePart1, p, sizeof(wep->wePart1));
578 	p += sizeof(wep->wePart1) / sizeof(*p);
579 	memcpy(wep->wePart2, p, sizeof(wep->wePart2));
580 	p += sizeof(wep->wePart2) / sizeof(*p);
581 	memcpy(wep->wePart3, p, sizeof(wep->wePart3));
582 
583 	if (len > i + WIN_CHARS)
584 		return 1;
585 
586 	wep->weCnt |= WIN_LAST;
587 	return 0;
588 }
589 
590 /*
591  * Compare our filename to the one in the Win95 entry
592  * Returns the checksum or -1 if no match
593  */
594 int
595 winChkName(const u_char *un, int unlen, struct winentry *wep, int chksum, int utf8)
596 {
597 	u_int16_t wn[WIN_MAXLEN], *p;
598 	u_int16_t buf[WIN_CHARS];
599 	int i, len;
600 
601 	/*
602 	 * First compare checksums
603 	 */
604 	if (wep->weCnt & WIN_LAST)
605 		chksum = wep->weChksum;
606 	else if (chksum != wep->weChksum)
607 		chksum = -1;
608 	if (chksum == -1)
609 		return -1;
610 
611 	/*
612 	 * Offset of this entry
613 	 */
614 	i = ((wep->weCnt & WIN_CNT) - 1) * WIN_CHARS;
615 
616 	/*
617 	 * Translate UNIX name to ucs-2
618 	 */
619 	len = utf8 ? utf8ucs2str(un, unlen, wn, WIN_MAXLEN) : char8ucs2str(un, unlen, wn, WIN_MAXLEN);
620 	ucs2pad(wn, len, WIN_MAXLEN);
621 
622 	if (i >= len + 1)
623 		return -1;
624 	if ((wep->weCnt & WIN_LAST) && (len - i > WIN_CHARS))
625 		return -1;
626 
627 	/*
628 	 * Fetch name segment from directory entry
629 	 */
630 	p = &buf[0];
631 	memcpy(p, wep->wePart1, sizeof(wep->wePart1));
632 	p += sizeof(wep->wePart1) / sizeof(*p);
633 	memcpy(p, wep->wePart2, sizeof(wep->wePart2));
634 	p += sizeof(wep->wePart2) / sizeof(*p);
635 	memcpy(p, wep->wePart3, sizeof(wep->wePart3));
636 
637 	/*
638 	 * And compare name segment
639 	 */
640 	if (! (utf8 ? ucs2match(&wn[i], buf, WIN_CHARS) : char8match(&wn[i], buf, WIN_CHARS)))
641 		return -1;
642 
643 	return chksum;
644 }
645 
646 /*
647  * Convert Win95 filename to dirbuf.
648  * Returns the checksum or -1 if impossible
649  */
650 int
651 win2unixfn(struct winentry *wep, struct dirent *dp, int chksum,
652     uint16_t *namlen, int utf8)
653 {
654 	u_int16_t wn[WIN_CHARS], *p;
655 	u_int8_t buf[WIN_CHARS*3];
656 	int len;
657 
658 	if ((wep->weCnt & WIN_CNT) > howmany(WIN_MAXLEN, WIN_CHARS)
659 	    || !(wep->weCnt & WIN_CNT))
660 		return -1;
661 
662 	/*
663 	 * First compare checksums
664 	 */
665 	if (wep->weCnt & WIN_LAST) {
666 		chksum = wep->weChksum;
667 		*namlen = 0;
668 	} else if (chksum != wep->weChksum)
669 		chksum = -1;
670 	if (chksum == -1)
671 		return -1;
672 
673 	/*
674 	 * Fetch name segment from directory entry
675 	 */
676 	p = &wn[0];
677 	memcpy(p, wep->wePart1, sizeof(wep->wePart1));
678 	p += sizeof(wep->wePart1) / sizeof(*p);
679 	memcpy(p, wep->wePart2, sizeof(wep->wePart2));
680 	p += sizeof(wep->wePart2) / sizeof(*p);
681 	memcpy(p, wep->wePart3, sizeof(wep->wePart3));
682 
683 	/*
684 	 * Don't allow slashes in UNIX names. Discard that entry.
685 	 */
686 	if (invalidname(wn, WIN_CHARS))
687 		return -1;
688 
689 	/*
690 	 * Translate ucs-2 to UNIX name
691 	 */
692 	len = utf8 ? ucs2utf8str(wn, WIN_CHARS, buf, sizeof(buf))
693 	    : ucs2char8str(wn, WIN_CHARS, buf, sizeof(buf));
694 
695 	KASSERT(len >= 0);
696 	KASSERT((size_t)len <= MIN(sizeof(buf), sizeof(dp->d_name)-1));
697 
698 	/*
699 	 * Prepend name segment to directory entry
700 	 *
701 	 * This ignores the slot number from the windows entry but
702 	 * assumes that segments are read in reverse order.
703 	 *
704 	 * The UCS-2 name (up to 255 chars) can overflow the UNIX
705 	 * directory entry (up to 511 bytes). Trailing characters
706 	 * are silently discarded. This could also end in multiple
707 	 * files using the same (truncated) name.
708 	 */
709 	*namlen += len;
710 	if (*namlen > sizeof(dp->d_name) - 1)
711 		*namlen = sizeof(dp->d_name) - 1;
712 
713 	KASSERT(*namlen >= len);
714 
715 	memmove(&dp->d_name[len], &dp->d_name[0], *namlen - len);
716 	memcpy(dp->d_name, buf, len);
717 
718 	return chksum;
719 }
720 
721 /*
722  * Compute the checksum of a DOS filename for Win95 use
723  */
724 u_int8_t
725 winChksum(u_int8_t *name)
726 {
727 	int i;
728 	u_int8_t s;
729 
730 	for (s = 0, i = 11; --i >= 0; s += *name++)
731 		s = (s << 7) | (s >> 1);
732 	return s;
733 }
734 
735 /*
736  * Determine the number of slots necessary for Win95 names
737  */
738 int
739 winSlotCnt(const u_char *un, int unlen, int utf8)
740 {
741 	const u_char *cp;
742 	int len;
743 
744 	/*
745 	 * Drop trailing blanks and dots
746 	 */
747 	for (cp = un + unlen; unlen > 0; unlen--)
748 		if (*--cp != ' ' && *cp != '.')
749 			break;
750 
751 	len = utf8 ? utf8ucs2str(un, unlen, NULL, WIN_MAXLEN) : unlen;
752 
753 	return howmany(len, WIN_CHARS);
754 }
755 
756 /*
757  * Scan windows name for characters that must not
758  * appear in a UNIX filename
759  */
760 static int
761 invalidname(const u_int16_t *in, int n)
762 {
763 	while (n-- > 0) {
764 		if (*in++ == '/')
765 			return 1;
766 	}
767 
768 	return 0;
769 }
770 
771 /*
772  * Convert UCS-2 character into UTF-8
773  * return number of output bytes or 0 if output
774  * buffer is too short
775  */
776 static int
777 ucs2utf8(const u_int16_t *in, u_int8_t *out, int n)
778 {
779 	uint16_t inch = le16toh(in[0]);
780 
781 	if (inch <= 0x007f) {
782 		if (n < 1) return 0;
783 		if (out)
784 			*out++ = inch;
785 		return 1;
786 	} else if (inch <= 0x07ff) {
787 		if (n < 2) return 0;
788 		if (out) {
789 			*out++ = 0xc0 | (inch >> 6);
790 			*out++ = 0x80 | (inch & 0x3f);
791 		}
792 		return 2;
793 	} else {
794 		if (n < 3) return 0;
795 		if (out) {
796 			*out++ = 0xe0 | (inch >> 12);
797 			*out++ = 0x80 | ((inch >> 6) & 0x3f);
798 			*out++ = 0x80 | (inch & 0x3f);
799 		}
800 		return 3;
801 	}
802 }
803 
804 
805 /*
806  * Convert UTF-8 bytes into UCS-2 character
807  * return number of input bytes, 0 if input
808  * is too short and -1 if input is invalid
809  */
810 static int
811 utf8ucs2(const u_int8_t *in, int n, u_int16_t *out)
812 {
813 	uint16_t outch;
814 
815 	if (n < 1) return 0;
816 
817 	if (in[0] <= 0x7f) {
818 		outch = in[0];
819 		if (out)
820 			*out = htole16(outch);
821 		return 1;
822 	} else if (in[0] <= 0xdf) {
823 		if (n < 2) return 0;
824 		outch = (in[0] & 0x1f) << 6 | (in[1] & 0x3f);
825 		if (out)
826 			*out = htole16(outch);
827 		return 2;
828 	} else if (in[0] <= 0xef) {
829 		if (n < 3) return 0;
830 		outch = (in[0] & 0x1f) << 12 | (in[1] & 0x3f) << 6 | (in[2] & 0x3f);
831 		if (out)
832 			*out = htole16(outch);
833 		return 3;
834 	}
835 
836 	return -1;
837 }
838 
839 /*
840  * Convert UCS-2 string into UTF-8 string
841  * return total number of output bytes
842  */
843 static int
844 ucs2utf8str(const u_int16_t *in, int n, u_int8_t *out, int m)
845 {
846 	u_int8_t *p;
847 	int outlen;
848 
849 	p = out;
850 	while (n > 0 && *in != 0) {
851 		outlen = ucs2utf8(in, out ? p : out, m);
852 		if (outlen == 0)
853 			break;
854 		p += outlen;
855 		m -= outlen;
856 		in += 1;
857 		n -= 1;
858 	}
859 
860 	return p - out;
861 }
862 
863 /*
864  * Convert UTF8 string into UCS-2 string
865  * return total number of output chacters
866  */
867 static int
868 utf8ucs2str(const u_int8_t *in, int n, u_int16_t *out, int m)
869 {
870 	u_int16_t *p;
871 	int inlen;
872 
873 	p = out;
874 	while (n > 0 && *in != 0) {
875 		if (m < 1)
876 			break;
877 		inlen = utf8ucs2(in, n, out ? p : out);
878 		if (inlen <= 0)
879 			break;
880 		in += inlen;
881 		n -= inlen;
882 		p += 1;
883 		m -= 1;
884 	}
885 
886 	return p - out;
887 }
888 
889 /*
890  * Convert UCS-2 string into 8bit character string
891  * return total number of output bytes
892  */
893 static int
894 ucs2char8str(const u_int16_t *in, int n, u_int8_t *out, int m)
895 {
896 	u_int8_t *p;
897 	u_int16_t inch;
898 
899 	p = out;
900 	while (n > 0 && in[0] != 0) {
901 		if (m < 1)
902 			break;
903 		inch = le16toh(in[0]);
904 		if (inch > 255)
905 			break;
906 		if (p)
907 			p[0] = inch;
908 		p += 1;
909 		m -= 1;
910 		in += 1;
911 		n -= 1;
912 	}
913 
914 	return p - out;
915 }
916 
917 /*
918  * Convert 8bit character string into UCS-2 string
919  * return total number of output chacters
920  */
921 static int
922 char8ucs2str(const u_int8_t *in, int n, u_int16_t *out, int m)
923 {
924 	u_int16_t *p;
925 
926 	p = out;
927 	while (n > 0 && in[0] != 0) {
928 		if (m < 1)
929 			break;
930 		if (p)
931 			p[0] = htole16(in[0]);
932 		p += 1;
933 		m -= 1;
934 		in += 1;
935 		n -= 1;
936 	}
937 
938 	return p - out;
939 }
940 
941 static void
942 ucs2pad(u_int16_t *buf, int len, int size)
943 {
944 
945 	if (len < size-1)
946 		buf[len++] = 0x0000;
947 	while (len < size)
948 		buf[len++] = 0xffff;
949 }
950 
951 /*
952  * Fold UCS-2 character to uppercase
953  */
954 static u_int16_t
955 ucs2fold(u_int16_t w)
956 {
957 	int low,high,mid;
958 	u_int16_t check;
959 	extern const u_int16_t msdosfs_unicode_foldmap[];
960 	extern size_t msdosfs_unicode_foldmap_entries;
961 
962 	w = le16toh(w);
963 
964 	low = 0;
965 	high = msdosfs_unicode_foldmap_entries / 2;
966 	while (low < high) {
967 		mid = (low + high)/2;
968 		check = msdosfs_unicode_foldmap[2*mid+0];
969 
970 		if (w == check) {
971 			w = msdosfs_unicode_foldmap[2*mid+1];
972 			break;
973 		}
974 
975 		if (w < check)
976 			high = mid;
977 		else
978 			low = mid+1;
979 	}
980 
981 	w = le16toh(w);
982 
983 	return w;
984 }
985 
986 /*
987  * Compare two UCS-2 strings case-insensitive
988  *
989  * uses the Unicode case folding table
990  */
991 static int
992 ucs2match(u_int16_t *w1, u_int16_t *w2, int n)
993 {
994 	u_int16_t u1, u2;
995 
996 	while (n > 0) {
997 		if (*w1 == 0 || *w2 == 0)
998 			return *w1 == *w2;
999 		u1 = ucs2fold(*w1);
1000 		u2 = ucs2fold(*w2);
1001 		if (u1 != u2)
1002 			return 0;
1003 		++w1;
1004 		++w2;
1005 		--n;
1006 	}
1007 
1008 	return 1;
1009 }
1010 
1011 /*
1012  * Compare two 8bit char conversions case-insensitive
1013  *
1014  * uses the DOS case folding table
1015  */
1016 static int
1017 char8match(u_int16_t *w1, u_int16_t *w2, int n)
1018 {
1019 	u_int16_t u1, u2;
1020 
1021 	while (n > 0) {
1022 		u1 = le16toh(*w1);
1023 		u2 = le16toh(*w2);
1024 		if (u1 == 0 || u2 == 0)
1025 			return u1 == u2;
1026 		if (u1 > 255 || u2 > 255)
1027 			return 0;
1028 		u1 = u2l[u1 & 0xff];
1029 		u2 = u2l[u2 & 0xff];
1030 		if (u1 != u2)
1031 			return 0;
1032 		++w1;
1033 		++w2;
1034 		--n;
1035 	}
1036 
1037 	return 1;
1038 }
1039 
1040