DOSFS_MatchLong ignored several things about file mask matching for
[wine] / files / dos_fs.c
1 /*
2  * DOS file system functions
3  *
4  * Copyright 1993 Erik Bos
5  * Copyright 1996 Alexandre Julliard
6  */
7
8 #include "config.h"
9 #include <sys/types.h>
10 #include <ctype.h>
11 #include <dirent.h>
12 #include <errno.h>
13 #ifdef HAVE_SYS_ERRNO_H
14 #include <sys/errno.h>
15 #endif
16 #include <fcntl.h>
17 #include <string.h>
18 #include <stdlib.h>
19 #include <sys/stat.h>
20 #include <sys/ioctl.h>
21 #include <time.h>
22 #include <unistd.h>
23
24 #include "windef.h"
25 #include "ntddk.h"
26 #include "wine/winbase16.h"
27 #include "wine/unicode.h"
28 #include "winerror.h"
29 #include "drive.h"
30 #include "file.h"
31 #include "comm.h"
32 #include "heap.h"
33 #include "msdos.h"
34 #include "syslevel.h"
35 #include "server.h"
36 #include "options.h"
37 #include "debugtools.h"
38
39 DEFAULT_DEBUG_CHANNEL(dosfs);
40 DECLARE_DEBUG_CHANNEL(file);
41
42 /* Define the VFAT ioctl to get both short and long file names */
43 /* FIXME: is it possible to get this to work on other systems? */
44 #ifdef linux
45 /* We want the real kernel dirent structure, not the libc one */
46 typedef struct
47 {
48     long d_ino;
49     long d_off;
50     unsigned short d_reclen;
51     char d_name[256];
52 } KERNEL_DIRENT;
53
54 #define VFAT_IOCTL_READDIR_BOTH  _IOR('r', 1, KERNEL_DIRENT [2] )
55
56 #else   /* linux */
57 #undef VFAT_IOCTL_READDIR_BOTH  /* just in case... */
58 #endif  /* linux */
59
60 /* Chars we don't want to see in DOS file names */
61 #define INVALID_DOS_CHARS  "*?<>|\"+=,;[] \345"
62
63 static const DOS_DEVICE DOSFS_Devices[] =
64 /* name, device flags (see Int 21/AX=0x4400) */
65 {
66     { "CON",            0xc0d3 },
67     { "PRN",            0xa0c0 },
68     { "NUL",            0x80c4 },
69     { "AUX",            0x80c0 },
70     { "LPT1",           0xa0c0 },
71     { "LPT2",           0xa0c0 },
72     { "LPT3",           0xa0c0 },
73     { "LPT4",           0xc0d3 },
74     { "COM1",           0x80c0 },
75     { "COM2",           0x80c0 },
76     { "COM3",           0x80c0 },
77     { "COM4",           0x80c0 },
78     { "SCSIMGR$",       0xc0c0 },
79     { "HPSCAN",         0xc0c0 }
80 };
81
82 #define GET_DRIVE(path) \
83     (((path)[1] == ':') ? toupper((path)[0]) - 'A' : DOSFS_CurDrive)
84
85 /* Directory info for DOSFS_ReadDir */
86 typedef struct
87 {
88     DIR           *dir;
89 #ifdef VFAT_IOCTL_READDIR_BOTH
90     int            fd;
91     char           short_name[12];
92     KERNEL_DIRENT  dirent[2];
93 #endif
94 } DOS_DIR;
95
96 /* Info structure for FindFirstFile handle */
97 typedef struct
98 {
99     LPSTR path;
100     LPSTR long_mask;
101     LPSTR short_mask;
102     BYTE  attr;
103     int   drive;
104     int   cur_pos;
105     DOS_DIR *dir;
106 } FIND_FIRST_INFO;
107
108
109
110 /***********************************************************************
111  *           DOSFS_ValidDOSName
112  *
113  * Return 1 if Unix file 'name' is also a valid MS-DOS name
114  * (i.e. contains only valid DOS chars, lower-case only, fits in 8.3 format).
115  * File name can be terminated by '\0', '\\' or '/'.
116  */
117 static int DOSFS_ValidDOSName( const char *name, int ignore_case )
118 {
119     static const char invalid_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" INVALID_DOS_CHARS;
120     const char *p = name;
121     const char *invalid = ignore_case ? (invalid_chars + 26) : invalid_chars;
122     int len = 0;
123
124     if (*p == '.')
125     {
126         /* Check for "." and ".." */
127         p++;
128         if (*p == '.') p++;
129         /* All other names beginning with '.' are invalid */
130         return (IS_END_OF_NAME(*p));
131     }
132     while (!IS_END_OF_NAME(*p))
133     {
134         if (strchr( invalid, *p )) return 0;  /* Invalid char */
135         if (*p == '.') break;  /* Start of the extension */
136         if (++len > 8) return 0;  /* Name too long */
137         p++;
138     }
139     if (*p != '.') return 1;  /* End of name */
140     p++;
141     if (IS_END_OF_NAME(*p)) return 0;  /* Empty extension not allowed */
142     len = 0;
143     while (!IS_END_OF_NAME(*p))
144     {
145         if (strchr( invalid, *p )) return 0;  /* Invalid char */
146         if (*p == '.') return 0;  /* Second extension not allowed */
147         if (++len > 3) return 0;  /* Extension too long */
148         p++;
149     }
150     return 1;
151 }
152
153
154 /***********************************************************************
155  *           DOSFS_ToDosFCBFormat
156  *
157  * Convert a file name to DOS FCB format (8+3 chars, padded with blanks),
158  * expanding wild cards and converting to upper-case in the process.
159  * File name can be terminated by '\0', '\\' or '/'.
160  * Return FALSE if the name is not a valid DOS name.
161  * 'buffer' must be at least 12 characters long.
162  */
163 BOOL DOSFS_ToDosFCBFormat( LPCSTR name, LPSTR buffer )
164 {
165     static const char invalid_chars[] = INVALID_DOS_CHARS;
166     const char *p = name;
167     int i;
168
169     /* Check for "." and ".." */
170     if (*p == '.')
171     {
172         p++;
173         strcpy( buffer, ".          " );
174         if (*p == '.')
175         {
176             buffer[1] = '.';
177             p++;
178         }
179         return (!*p || (*p == '/') || (*p == '\\'));
180     }
181
182     for (i = 0; i < 8; i++)
183     {
184         switch(*p)
185         {
186         case '\0':
187         case '\\':
188         case '/':
189         case '.':
190             buffer[i] = ' ';
191             break;
192         case '?':
193             p++;
194             /* fall through */
195         case '*':
196             buffer[i] = '?';
197             break;
198         default:
199             if (strchr( invalid_chars, *p )) return FALSE;
200             buffer[i] = toupper(*p);
201             p++;
202             break;
203         }
204     }
205
206     if (*p == '*')
207     {
208         /* Skip all chars after wildcard up to first dot */
209         while (*p && (*p != '/') && (*p != '\\') && (*p != '.')) p++;
210     }
211     else
212     {
213         /* Check if name too long */
214         if (*p && (*p != '/') && (*p != '\\') && (*p != '.')) return FALSE;
215     }
216     if (*p == '.') p++;  /* Skip dot */
217
218     for (i = 8; i < 11; i++)
219     {
220         switch(*p)
221         {
222         case '\0':
223         case '\\':
224         case '/':
225             buffer[i] = ' ';
226             break;
227         case '.':
228             return FALSE;  /* Second extension not allowed */
229         case '?':
230             p++;
231             /* fall through */
232         case '*':
233             buffer[i] = '?';
234             break;
235         default:
236             if (strchr( invalid_chars, *p )) return FALSE;
237             buffer[i] = toupper(*p);
238             p++;
239             break;
240         }
241     }
242     buffer[11] = '\0';
243
244     /* at most 3 character of the extension are processed
245      * is something behind this ? 
246      */
247     while (*p == '*' || *p == ' ') p++; /* skip wildcards and spaces */
248     return IS_END_OF_NAME(*p);
249 }
250
251
252 /***********************************************************************
253  *           DOSFS_ToDosDTAFormat
254  *
255  * Convert a file name from FCB to DTA format (name.ext, null-terminated)
256  * converting to upper-case in the process.
257  * File name can be terminated by '\0', '\\' or '/'.
258  * 'buffer' must be at least 13 characters long.
259  */
260 static void DOSFS_ToDosDTAFormat( LPCSTR name, LPSTR buffer )
261 {
262     char *p;
263
264     memcpy( buffer, name, 8 );
265     for (p = buffer + 8; (p > buffer) && (p[-1] == ' '); p--);
266     *p++ = '.';
267     memcpy( p, name + 8, 3 );
268     for (p += 3; p[-1] == ' '; p--);
269     if (p[-1] == '.') p--;
270     *p = '\0';
271 }
272
273
274 /***********************************************************************
275  *           DOSFS_MatchShort
276  *
277  * Check a DOS file name against a mask (both in FCB format).
278  */
279 static int DOSFS_MatchShort( const char *mask, const char *name )
280 {
281     int i;
282     for (i = 11; i > 0; i--, mask++, name++)
283         if ((*mask != '?') && (*mask != *name)) return 0;
284     return 1;
285 }
286
287
288 /***********************************************************************
289  *           DOSFS_MatchLong
290  *
291  * Check a long file name against a mask.
292  *
293  * Tests (done in W95 DOS shell - case insensitive):
294  * *.txt                        test1.test.txt                          *
295  * *st1*                        test1.txt                               *
296  * *.t??????.t*                 test1.ta.tornado.txt                    *
297  * *tornado*                    test1.ta.tornado.txt                    *
298  * t*t                          test1.ta.tornado.txt                    *
299  * ?est*                        test1.txt                               *
300  * ?est???                      test1.txt                               -
301  * *test1.txt*                  test1.txt                               * 
302  * h?l?o*t.dat                  hellothisisatest.dat                    *
303  */
304 static int DOSFS_MatchLong( const char *mask, const char *name,
305                             int case_sensitive )
306 {
307     const char *lastjoker = NULL;
308     const char *next_to_retry = NULL;
309
310     if (!strcmp( mask, "*.*" )) return 1;
311     while (*name && *mask)
312     {
313         if (*mask == '*')
314         {
315             mask++;
316             while (*mask == '*') mask++;  /* Skip consecutive '*' */
317             lastjoker = mask;
318             if (!*mask) return 1; /* end of mask is all '*', so match */
319
320             /* skip to the next match after the joker(s) */
321             if (case_sensitive) while (*name && (*name != *mask)) name++;
322             else while (*name && (toupper(*name) != toupper(*mask))) name++;
323
324             if (!*name) break;
325             next_to_retry = name;
326         }
327         else if (*mask != '?')
328         {
329             int mismatch = 0;
330             if (case_sensitive)
331             {
332                 if (*mask != *name) mismatch = 1;
333             }
334             else
335             {
336                 if (toupper(*mask) != toupper(*name)) mismatch = 1;
337             }
338             if (!mismatch)
339             {
340                 mask++;
341                 name++;
342                 if (*mask == '\0')
343                 {
344                     if (*name == '\0')
345                         return 1;
346                     if (lastjoker)
347                         mask = lastjoker;
348                 }
349             }
350             else /* mismatch ! */
351             {
352                 if (lastjoker) /* we had an '*', so we can try unlimitedly */
353                 {
354                     mask = lastjoker;
355
356                     /* this scan sequence was a mismatch, so restart
357                      * 1 char after the first char we checked last time */
358                     next_to_retry++;
359                     name = next_to_retry;
360                 }
361                 else
362                     return 0; /* bad luck */
363             }
364         }
365         else /* '?' */
366         {
367             mask++;
368             name++;
369         }
370     }
371     while ((*mask == '.') || (*mask == '*'))
372         mask++;  /* Ignore trailing '.' or '*' in mask */
373     return (!*name && !*mask);
374 }
375
376
377 /***********************************************************************
378  *           DOSFS_OpenDir
379  */
380 static DOS_DIR *DOSFS_OpenDir( LPCSTR path )
381 {
382     DOS_DIR *dir = HeapAlloc( GetProcessHeap(), 0, sizeof(*dir) );
383     if (!dir)
384     {
385         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
386         return NULL;
387     }
388
389     /* Treat empty path as root directory. This simplifies path split into
390        directory and mask in several other places */
391     if (!*path) path = "/";
392
393 #ifdef VFAT_IOCTL_READDIR_BOTH
394
395     /* Check if the VFAT ioctl is supported on this directory */
396
397     if ((dir->fd = open( path, O_RDONLY )) != -1)
398     {
399         if (ioctl( dir->fd, VFAT_IOCTL_READDIR_BOTH, (long)dir->dirent ) == -1)
400         {
401             close( dir->fd );
402             dir->fd = -1;
403         }
404         else
405         {
406             /* Set the file pointer back at the start of the directory */
407             lseek( dir->fd, 0, SEEK_SET );
408             dir->dir = NULL;
409             return dir;
410         }
411     }
412 #endif  /* VFAT_IOCTL_READDIR_BOTH */
413
414     /* Now use the standard opendir/readdir interface */
415
416     if (!(dir->dir = opendir( path )))
417     {
418         HeapFree( GetProcessHeap(), 0, dir );
419         return NULL;
420     }
421     return dir;
422 }
423
424
425 /***********************************************************************
426  *           DOSFS_CloseDir
427  */
428 static void DOSFS_CloseDir( DOS_DIR *dir )
429 {
430 #ifdef VFAT_IOCTL_READDIR_BOTH
431     if (dir->fd != -1) close( dir->fd );
432 #endif  /* VFAT_IOCTL_READDIR_BOTH */
433     if (dir->dir) closedir( dir->dir );
434     HeapFree( GetProcessHeap(), 0, dir );
435 }
436
437
438 /***********************************************************************
439  *           DOSFS_ReadDir
440  */
441 static BOOL DOSFS_ReadDir( DOS_DIR *dir, LPCSTR *long_name,
442                              LPCSTR *short_name )
443 {
444     struct dirent *dirent;
445
446 #ifdef VFAT_IOCTL_READDIR_BOTH
447     if (dir->fd != -1)
448     {
449         if (ioctl( dir->fd, VFAT_IOCTL_READDIR_BOTH, (long)dir->dirent ) != -1) {
450             if (!dir->dirent[0].d_reclen) return FALSE;
451             if (!DOSFS_ToDosFCBFormat( dir->dirent[0].d_name, dir->short_name ))
452                 dir->short_name[0] = '\0';
453             *short_name = dir->short_name;
454             if (dir->dirent[1].d_name[0]) *long_name = dir->dirent[1].d_name;
455             else *long_name = dir->dirent[0].d_name;
456             return TRUE;
457         }
458     }
459 #endif  /* VFAT_IOCTL_READDIR_BOTH */
460
461     if (!(dirent = readdir( dir->dir ))) return FALSE;
462     *long_name  = dirent->d_name;
463     *short_name = NULL;
464     return TRUE;
465 }
466
467
468 /***********************************************************************
469  *           DOSFS_Hash
470  *
471  * Transform a Unix file name into a hashed DOS name. If the name is a valid
472  * DOS name, it is converted to upper-case; otherwise it is replaced by a
473  * hashed version that fits in 8.3 format.
474  * File name can be terminated by '\0', '\\' or '/'.
475  * 'buffer' must be at least 13 characters long.
476  */
477 static void DOSFS_Hash( LPCSTR name, LPSTR buffer, BOOL dir_format,
478                         BOOL ignore_case )
479 {
480     static const char invalid_chars[] = INVALID_DOS_CHARS "~.";
481     static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
482
483     const char *p, *ext;
484     char *dst;
485     unsigned short hash;
486     int i;
487
488     if (dir_format) strcpy( buffer, "           " );
489
490     if (DOSFS_ValidDOSName( name, ignore_case ))
491     {
492         /* Check for '.' and '..' */
493         if (*name == '.')
494         {
495             buffer[0] = '.';
496             if (!dir_format) buffer[1] = buffer[2] = '\0';
497             if (name[1] == '.') buffer[1] = '.';
498             return;
499         }
500
501         /* Simply copy the name, converting to uppercase */
502
503         for (dst = buffer; !IS_END_OF_NAME(*name) && (*name != '.'); name++)
504             *dst++ = toupper(*name);
505         if (*name == '.')
506         {
507             if (dir_format) dst = buffer + 8;
508             else *dst++ = '.';
509             for (name++; !IS_END_OF_NAME(*name); name++)
510                 *dst++ = toupper(*name);
511         }
512         if (!dir_format) *dst = '\0';
513         return;
514     }
515
516     /* Compute the hash code of the file name */
517     /* If you know something about hash functions, feel free to */
518     /* insert a better algorithm here... */
519     if (ignore_case)
520     {
521         for (p = name, hash = 0xbeef; !IS_END_OF_NAME(p[1]); p++)
522             hash = (hash<<3) ^ (hash>>5) ^ tolower(*p) ^ (tolower(p[1]) << 8);
523         hash = (hash<<3) ^ (hash>>5) ^ tolower(*p); /* Last character*/
524     }
525     else
526     {
527         for (p = name, hash = 0xbeef; !IS_END_OF_NAME(p[1]); p++)
528             hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
529         hash = (hash << 3) ^ (hash >> 5) ^ *p;  /* Last character */
530     }
531
532     /* Find last dot for start of the extension */
533     for (p = name+1, ext = NULL; !IS_END_OF_NAME(*p); p++)
534         if (*p == '.') ext = p;
535     if (ext && IS_END_OF_NAME(ext[1]))
536         ext = NULL;  /* Empty extension ignored */
537
538     /* Copy first 4 chars, replacing invalid chars with '_' */
539     for (i = 4, p = name, dst = buffer; i > 0; i--, p++)
540     {
541         if (IS_END_OF_NAME(*p) || (p == ext)) break;
542         *dst++ = strchr( invalid_chars, *p ) ? '_' : toupper(*p);
543     }
544     /* Pad to 5 chars with '~' */
545     while (i-- >= 0) *dst++ = '~';
546
547     /* Insert hash code converted to 3 ASCII chars */
548     *dst++ = hash_chars[(hash >> 10) & 0x1f];
549     *dst++ = hash_chars[(hash >> 5) & 0x1f];
550     *dst++ = hash_chars[hash & 0x1f];
551
552     /* Copy the first 3 chars of the extension (if any) */
553     if (ext)
554     {
555         if (!dir_format) *dst++ = '.';
556         for (i = 3, ext++; (i > 0) && !IS_END_OF_NAME(*ext); i--, ext++)
557             *dst++ = strchr( invalid_chars, *ext ) ? '_' : toupper(*ext);
558     }
559     if (!dir_format) *dst = '\0';
560 }
561
562
563 /***********************************************************************
564  *           DOSFS_FindUnixName
565  *
566  * Find the Unix file name in a given directory that corresponds to
567  * a file name (either in Unix or DOS format).
568  * File name can be terminated by '\0', '\\' or '/'.
569  * Return TRUE if OK, FALSE if no file name matches.
570  *
571  * 'long_buf' must be at least 'long_len' characters long. If the long name
572  * turns out to be larger than that, the function returns FALSE.
573  * 'short_buf' must be at least 13 characters long.
574  */
575 BOOL DOSFS_FindUnixName( LPCSTR path, LPCSTR name, LPSTR long_buf,
576                            INT long_len, LPSTR short_buf, BOOL ignore_case)
577 {
578     DOS_DIR *dir;
579     LPCSTR long_name, short_name;
580     char dos_name[12], tmp_buf[13];
581     BOOL ret;
582
583     const char *p = strchr( name, '/' );
584     int len = p ? (int)(p - name) : strlen(name);
585     if ((p = strchr( name, '\\' ))) len = min( (int)(p - name), len );
586     /* Ignore trailing dots and spaces */
587     while (len > 1 && (name[len-1] == '.' || name[len-1] == ' ')) len--;
588     if (long_len < len + 1) return FALSE;
589
590     TRACE("%s,%s\n", path, name );
591
592     if (!DOSFS_ToDosFCBFormat( name, dos_name )) dos_name[0] = '\0';
593
594     if (!(dir = DOSFS_OpenDir( path )))
595     {
596         WARN("(%s,%s): can't open dir: %s\n",
597                        path, name, strerror(errno) );
598         return FALSE;
599     }
600
601     while ((ret = DOSFS_ReadDir( dir, &long_name, &short_name )))
602     {
603         /* Check against Unix name */
604         if (len == strlen(long_name))
605         {
606             if (!ignore_case)
607             {
608                 if (!strncmp( long_name, name, len )) break;
609             }
610             else
611             {
612                 if (!lstrncmpiA( long_name, name, len )) break;
613             }
614         }
615         if (dos_name[0])
616         {
617             /* Check against hashed DOS name */
618             if (!short_name)
619             {
620                 DOSFS_Hash( long_name, tmp_buf, TRUE, ignore_case );
621                 short_name = tmp_buf;
622             }
623             if (!strcmp( dos_name, short_name )) break;
624         }
625     }
626     if (ret)
627     {
628         if (long_buf) strcpy( long_buf, long_name );
629         if (short_buf)
630         {
631             if (short_name)
632                 DOSFS_ToDosDTAFormat( short_name, short_buf );
633             else
634                 DOSFS_Hash( long_name, short_buf, FALSE, ignore_case );
635         }
636         TRACE("(%s,%s) -> %s (%s)\n",
637               path, name, long_name, short_buf ? short_buf : "***");
638     }
639     else
640         WARN("'%s' not found in '%s'\n", name, path);
641     DOSFS_CloseDir( dir );
642     return ret;
643 }
644
645
646 /***********************************************************************
647  *           DOSFS_GetDevice
648  *
649  * Check if a DOS file name represents a DOS device and return the device.
650  */
651 const DOS_DEVICE *DOSFS_GetDevice( const char *name )
652 {
653     int i;
654     const char *p;
655
656     if (!name) return NULL; /* if FILE_DupUnixHandle was used */
657     if (name[0] && (name[1] == ':')) name += 2;
658     if ((p = strrchr( name, '/' ))) name = p + 1;
659     if ((p = strrchr( name, '\\' ))) name = p + 1;
660     for (i = 0; i < sizeof(DOSFS_Devices)/sizeof(DOSFS_Devices[0]); i++)
661     {
662         const char *dev = DOSFS_Devices[i].name;
663         if (!lstrncmpiA( dev, name, strlen(dev) ))
664         {
665             p = name + strlen( dev );
666             if (!*p || (*p == '.')) return &DOSFS_Devices[i];
667         }
668     }
669     return NULL;
670 }
671
672
673 /***********************************************************************
674  *           DOSFS_GetDeviceByHandle
675  */
676 const DOS_DEVICE *DOSFS_GetDeviceByHandle( HFILE hFile )
677 {
678     const DOS_DEVICE *ret = NULL;
679     SERVER_START_REQ
680     {
681         struct get_file_info_request *req = server_alloc_req( sizeof(*req), 0 );
682
683         req->handle = hFile;
684         if (!server_call( REQ_GET_FILE_INFO ) && (req->type == FILE_TYPE_UNKNOWN))
685         {
686             if ((req->attr >= 0) &&
687                 (req->attr < sizeof(DOSFS_Devices)/sizeof(DOSFS_Devices[0])))
688                 ret = &DOSFS_Devices[req->attr];
689         }
690     }
691     SERVER_END_REQ;
692     return ret;
693 }
694
695
696 /***********************************************************************
697  *           DOSFS_OpenDevice
698  *
699  * Open a DOS device. This might not map 1:1 into the UNIX device concept.
700  */
701 HFILE DOSFS_OpenDevice( const char *name, DWORD access )
702 {
703     int i;
704     const char *p;
705     HFILE handle;
706
707     if (!name) return (HFILE)NULL; /* if FILE_DupUnixHandle was used */
708     if (name[0] && (name[1] == ':')) name += 2;
709     if ((p = strrchr( name, '/' ))) name = p + 1;
710     if ((p = strrchr( name, '\\' ))) name = p + 1;
711     for (i = 0; i < sizeof(DOSFS_Devices)/sizeof(DOSFS_Devices[0]); i++)
712     {
713         const char *dev = DOSFS_Devices[i].name;
714         if (!lstrncmpiA( dev, name, strlen(dev) ))
715         {
716             p = name + strlen( dev );
717             if (!*p || (*p == '.')) {
718                 /* got it */
719                 if (!strcmp(DOSFS_Devices[i].name,"NUL"))
720                     return FILE_CreateFile( "/dev/null", access,
721                                             FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
722                                             OPEN_EXISTING, 0, -1, TRUE );
723                 if (!strcmp(DOSFS_Devices[i].name,"CON")) {
724                         HFILE to_dup;
725                         switch (access & (GENERIC_READ|GENERIC_WRITE)) {
726                         case GENERIC_READ:
727                                 to_dup = GetStdHandle( STD_INPUT_HANDLE );
728                                 break;
729                         case GENERIC_WRITE:
730                                 to_dup = GetStdHandle( STD_OUTPUT_HANDLE );
731                                 break;
732                         default:
733                                 FIXME("can't open CON read/write\n");
734                                 return HFILE_ERROR;
735                                 break;
736                         }
737                         if (!DuplicateHandle( GetCurrentProcess(), to_dup, GetCurrentProcess(),
738                                               &handle, 0, FALSE, DUPLICATE_SAME_ACCESS ))
739                             handle = HFILE_ERROR;
740                         return handle;
741                 }
742                 if (!strcmp(DOSFS_Devices[i].name,"SCSIMGR$") ||
743                     !strcmp(DOSFS_Devices[i].name,"HPSCAN"))
744                 {
745                     return FILE_CreateDevice( i, access, NULL );
746                 }
747
748                 if( (handle=COMM_CreatePort(name,access)) )
749                     return handle;
750
751                 FIXME("device open %s not supported (yet)\n",DOSFS_Devices[i].name);
752                 return HFILE_ERROR;
753             }
754         }
755     }
756     return HFILE_ERROR;
757 }
758
759
760 /***********************************************************************
761  *           DOSFS_GetPathDrive
762  *
763  * Get the drive specified by a given path name (DOS or Unix format).
764  */
765 static int DOSFS_GetPathDrive( const char **name )
766 {
767     int drive;
768     const char *p = *name;
769
770     if (*p && (p[1] == ':'))
771     {
772         drive = toupper(*p) - 'A';
773         *name += 2;
774     }
775     else if (*p == '/') /* Absolute Unix path? */
776     {
777         if ((drive = DRIVE_FindDriveRoot( name )) == -1)
778         {
779             MESSAGE("Warning: %s not accessible from a DOS drive\n", *name );
780             /* Assume it really was a DOS name */
781             drive = DRIVE_GetCurrentDrive();            
782         }
783     }
784     else drive = DRIVE_GetCurrentDrive();
785
786     if (!DRIVE_IsValid(drive))
787     {
788         SetLastError( ERROR_INVALID_DRIVE );
789         return -1;
790     }
791     return drive;
792 }
793
794
795 /***********************************************************************
796  *           DOSFS_GetFullName
797  *
798  * Convert a file name (DOS or mixed DOS/Unix format) to a valid
799  * Unix name / short DOS name pair.
800  * Return FALSE if one of the path components does not exist. The last path
801  * component is only checked if 'check_last' is non-zero.
802  * The buffers pointed to by 'long_buf' and 'short_buf' must be
803  * at least MAX_PATHNAME_LEN long.
804  */
805 BOOL DOSFS_GetFullName( LPCSTR name, BOOL check_last, DOS_FULL_NAME *full )
806 {
807     BOOL found;
808     UINT flags;
809     char *p_l, *p_s, *root;
810
811     TRACE("%s (last=%d)\n", name, check_last );
812
813     if ((full->drive = DOSFS_GetPathDrive( &name )) == -1) return FALSE;
814     flags = DRIVE_GetFlags( full->drive );
815
816     lstrcpynA( full->long_name, DRIVE_GetRoot( full->drive ),
817                  sizeof(full->long_name) );
818     if (full->long_name[1]) root = full->long_name + strlen(full->long_name);
819     else root = full->long_name;  /* root directory */
820
821     strcpy( full->short_name, "A:\\" );
822     full->short_name[0] += full->drive;
823
824     if ((*name == '\\') || (*name == '/'))  /* Absolute path */
825     {
826         while ((*name == '\\') || (*name == '/')) name++;
827     }
828     else  /* Relative path */
829     {
830         lstrcpynA( root + 1, DRIVE_GetUnixCwd( full->drive ),
831                      sizeof(full->long_name) - (root - full->long_name) - 1 );
832         if (root[1]) *root = '/';
833         lstrcpynA( full->short_name + 3, DRIVE_GetDosCwd( full->drive ),
834                      sizeof(full->short_name) - 3 );
835     }
836
837     p_l = full->long_name[1] ? full->long_name + strlen(full->long_name)
838                              : full->long_name;
839     p_s = full->short_name[3] ? full->short_name + strlen(full->short_name)
840                               : full->short_name + 2;
841     found = TRUE;
842
843     while (*name && found)
844     {
845         /* Check for '.' and '..' */
846
847         if (*name == '.')
848         {
849             if (IS_END_OF_NAME(name[1]))
850             {
851                 name++;
852                 while ((*name == '\\') || (*name == '/')) name++;
853                 continue;
854             }
855             else if ((name[1] == '.') && IS_END_OF_NAME(name[2]))
856             {
857                 name += 2;
858                 while ((*name == '\\') || (*name == '/')) name++;
859                 while ((p_l > root) && (*p_l != '/')) p_l--;
860                 while ((p_s > full->short_name + 2) && (*p_s != '\\')) p_s--;
861                 *p_l = *p_s = '\0';  /* Remove trailing separator */
862                 continue;
863             }
864         }
865
866         /* Make sure buffers are large enough */
867
868         if ((p_s >= full->short_name + sizeof(full->short_name) - 14) ||
869             (p_l >= full->long_name + sizeof(full->long_name) - 1))
870         {
871             SetLastError( ERROR_PATH_NOT_FOUND );
872             return FALSE;
873         }
874
875         /* Get the long and short name matching the file name */
876
877         if ((found = DOSFS_FindUnixName( full->long_name, name, p_l + 1,
878                          sizeof(full->long_name) - (p_l - full->long_name) - 1,
879                          p_s + 1, !(flags & DRIVE_CASE_SENSITIVE) )))
880         {
881             *p_l++ = '/';
882             p_l   += strlen(p_l);
883             *p_s++ = '\\';
884             p_s   += strlen(p_s);
885             while (!IS_END_OF_NAME(*name)) name++;
886         }
887         else if (!check_last)
888         {
889             *p_l++ = '/';
890             *p_s++ = '\\';
891             while (!IS_END_OF_NAME(*name) &&
892                    (p_s < full->short_name + sizeof(full->short_name) - 1) &&
893                    (p_l < full->long_name + sizeof(full->long_name) - 1))
894             {
895                 *p_s++ = tolower(*name);
896                 /* If the drive is case-sensitive we want to create new */
897                 /* files in lower-case otherwise we can't reopen them   */
898                 /* under the same short name. */
899                 if (flags & DRIVE_CASE_SENSITIVE) *p_l++ = tolower(*name);
900                 else *p_l++ = *name;
901                 name++;
902             }
903             /* Ignore trailing dots and spaces */
904             while(p_l[-1] == '.' || p_l[-1] == ' ') {
905                 --p_l;
906                 --p_s;
907             }
908             *p_l = *p_s = '\0';
909         }
910         while ((*name == '\\') || (*name == '/')) name++;
911     }
912
913     if (!found)
914     {
915         if (check_last)
916         {
917             SetLastError( ERROR_FILE_NOT_FOUND );
918             return FALSE;
919         }
920         if (*name)  /* Not last */
921         {
922             SetLastError( ERROR_PATH_NOT_FOUND );
923             return FALSE;
924         }
925     }
926     if (!full->long_name[0]) strcpy( full->long_name, "/" );
927     if (!full->short_name[2]) strcpy( full->short_name + 2, "\\" );
928     TRACE("returning %s = %s\n", full->long_name, full->short_name );
929     return TRUE;
930 }
931
932
933 /***********************************************************************
934  *           GetShortPathNameA   (KERNEL32.271)
935  *
936  * NOTES
937  *  observed:
938  *  longpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
939  *  *longpath="" or invalid: LastError=ERROR_BAD_PATHNAME, ret=0
940  * 
941  * more observations ( with NT 3.51 (WinDD) ):
942  * longpath <= 8.3 -> just copy longpath to shortpath
943  * longpath > 8.3  -> 
944  *             a) file does not exist -> return 0, LastError = ERROR_FILE_NOT_FOUND
945  *             b) file does exist     -> set the short filename.
946  * - trailing slashes are reproduced in the short name, even if the
947  *   file is not a directory
948  * - the absolute/relative path of the short name is reproduced like found
949  *   in the long name
950  * - longpath and shortpath may have the same adress
951  * Peter Ganten, 1999
952  */
953 DWORD WINAPI GetShortPathNameA( LPCSTR longpath, LPSTR shortpath,
954                                   DWORD shortlen )
955 {
956     DOS_FULL_NAME full_name;
957     LPSTR tmpshortpath;
958     DWORD sp = 0, lp = 0;
959     int tmplen, drive;
960     UINT flags;
961
962     TRACE("%s\n", debugstr_a(longpath));
963
964     if (!longpath) {
965       SetLastError(ERROR_INVALID_PARAMETER);
966       return 0;
967     }
968     if (!longpath[0]) {
969       SetLastError(ERROR_BAD_PATHNAME);
970       return 0;
971     }
972
973     if ( ( tmpshortpath = HeapAlloc ( GetProcessHeap(), 0, MAX_PATHNAME_LEN ) ) == NULL ) {
974       SetLastError ( ERROR_NOT_ENOUGH_MEMORY );
975       return 0;
976     }
977
978     /* check for drive letter */
979     if ( longpath[1] == ':' ) {
980       tmpshortpath[0] = longpath[0];
981       tmpshortpath[1] = ':';
982       sp = 2;
983     }
984
985     if ( ( drive = DOSFS_GetPathDrive ( &longpath )) == -1 ) return 0;
986     flags = DRIVE_GetFlags ( drive );
987
988     while ( longpath[lp] ) {
989
990       /* check for path delimiters and reproduce them */
991       if ( longpath[lp] == '\\' || longpath[lp] == '/' ) {
992         if (!sp || tmpshortpath[sp-1]!= '\\') 
993         {
994             /* strip double "\\" */
995             tmpshortpath[sp] = '\\';
996             sp++;
997         }
998         tmpshortpath[sp]=0;/*terminate string*/
999         lp++;
1000         continue;
1001       }
1002
1003       tmplen = strcspn ( longpath + lp, "\\/" ); 
1004       lstrcpynA ( tmpshortpath+sp, longpath + lp, tmplen+1 );
1005       
1006       /* Check, if the current element is a valid dos name */
1007       if ( DOSFS_ValidDOSName ( longpath + lp, !(flags & DRIVE_CASE_SENSITIVE) ) ) {
1008         sp += tmplen;
1009         lp += tmplen;
1010         continue;
1011       }
1012
1013       /* Check if the file exists and use the existing file name */
1014       if ( DOSFS_GetFullName ( tmpshortpath, TRUE, &full_name ) ) {
1015         strcpy( tmpshortpath+sp, strrchr ( full_name.short_name, '\\' ) + 1 );
1016         sp += strlen ( tmpshortpath+sp );
1017         lp += tmplen;
1018         continue;
1019       }
1020
1021       TRACE("not found!\n" );
1022       SetLastError ( ERROR_FILE_NOT_FOUND );
1023       return 0;
1024     }
1025     tmpshortpath[sp] = 0;
1026
1027     lstrcpynA ( shortpath, tmpshortpath, shortlen );
1028     TRACE("returning %s\n", debugstr_a(shortpath) );
1029     tmplen = strlen ( tmpshortpath );
1030     HeapFree ( GetProcessHeap(), 0, tmpshortpath );
1031     
1032     return tmplen;
1033 }
1034
1035
1036 /***********************************************************************
1037  *           GetShortPathNameW   (KERNEL32.272)
1038  */
1039 DWORD WINAPI GetShortPathNameW( LPCWSTR longpath, LPWSTR shortpath,
1040                                   DWORD shortlen )
1041 {
1042     LPSTR longpathA, shortpathA;
1043     DWORD ret = 0;
1044
1045     longpathA = HEAP_strdupWtoA( GetProcessHeap(), 0, longpath );
1046     shortpathA = HeapAlloc ( GetProcessHeap(), 0, shortlen );
1047
1048     ret = GetShortPathNameA ( longpathA, shortpathA, shortlen );
1049     lstrcpynAtoW ( shortpath, shortpathA, shortlen );
1050
1051     HeapFree( GetProcessHeap(), 0, longpathA );
1052     HeapFree( GetProcessHeap(), 0, shortpathA );
1053
1054     return ret;
1055 }
1056
1057
1058 /***********************************************************************
1059  *           GetLongPathNameA   (KERNEL32.xxx)
1060  */
1061 DWORD WINAPI GetLongPathNameA( LPCSTR shortpath, LPSTR longpath,
1062                                   DWORD longlen )
1063 {
1064     DOS_FULL_NAME full_name;
1065     char *p, *r, *ll, *ss;
1066     
1067     if (!DOSFS_GetFullName( shortpath, TRUE, &full_name )) return 0;
1068     lstrcpynA( longpath, full_name.short_name, longlen );
1069
1070     /* Do some hackery to get the long filename. */
1071
1072     if (longpath) {
1073      ss=longpath+strlen(longpath);
1074      ll=full_name.long_name+strlen(full_name.long_name);
1075      p=NULL;
1076      while (ss>=longpath)
1077      {
1078        /* FIXME: aren't we more paranoid, than needed? */
1079        while ((ss[0]=='\\') && (ss>=longpath)) ss--;
1080        p=ss;
1081        while ((ss[0]!='\\') && (ss>=longpath)) ss--;
1082        if (ss>=longpath) 
1083          {
1084          /* FIXME: aren't we more paranoid, than needed? */
1085          while ((ll[0]=='/') && (ll>=full_name.long_name)) ll--;
1086          while ((ll[0]!='/') && (ll>=full_name.long_name)) ll--;
1087          if (ll<full_name.long_name) 
1088               { 
1089               ERR("Bad longname! (ss=%s ll=%s)\n This should never happen !\n"
1090                   ,ss ,ll ); 
1091               return 0;
1092               }
1093          }
1094      }
1095
1096    /* FIXME: fix for names like "C:\\" (ie. with more '\'s) */
1097       if (p && p[2]) 
1098         {
1099         p+=1;
1100         if ((p-longpath)>0) longlen -= (p-longpath);
1101         lstrcpynA( p, ll , longlen);
1102
1103         /* Now, change all '/' to '\' */
1104         for (r=p; r<(p+longlen); r++ ) 
1105           if (r[0]=='/') r[0]='\\';
1106         return strlen(longpath) - strlen(p) + longlen;
1107         }
1108     }
1109
1110     return strlen(longpath);
1111 }
1112
1113
1114 /***********************************************************************
1115  *           GetLongPathNameW   (KERNEL32.269)
1116  */
1117 DWORD WINAPI GetLongPathNameW( LPCWSTR shortpath, LPWSTR longpath,
1118                                   DWORD longlen )
1119 {
1120     DOS_FULL_NAME full_name;
1121     DWORD ret = 0;
1122     LPSTR shortpathA = HEAP_strdupWtoA( GetProcessHeap(), 0, shortpath );
1123
1124     /* FIXME: is it correct to always return a fully qualified short path? */
1125     if (DOSFS_GetFullName( shortpathA, TRUE, &full_name ))
1126     {
1127         ret = strlen( full_name.short_name );
1128         lstrcpynAtoW( longpath, full_name.long_name, longlen );
1129     }
1130     HeapFree( GetProcessHeap(), 0, shortpathA );
1131     return ret;
1132 }
1133
1134
1135 /***********************************************************************
1136  *           DOSFS_DoGetFullPathName
1137  *
1138  * Implementation of GetFullPathNameA/W.
1139  *
1140  * bon@elektron 000331:
1141  * A test for GetFullPathName with many patholotical case 
1142  * gives now identical output for Wine and OSR2
1143  */
1144 static DWORD DOSFS_DoGetFullPathName( LPCSTR name, DWORD len, LPSTR result,
1145                                       BOOL unicode )
1146 {
1147     DWORD ret;
1148     DOS_FULL_NAME full_name;
1149     char *p,*q;
1150     const char * root;
1151     char drivecur[]="c:.";
1152     char driveletter=0;
1153     int namelen,drive=0;
1154
1155     if ((strlen(name) >1)&& (name[1]==':'))
1156       /*drive letter given */
1157       {
1158         driveletter = name[0];
1159       }
1160     if ((strlen(name) >2)&& (name[1]==':') &&
1161              ((name[2]=='\\') || (name[2]=='/')))
1162       /*absolute path given */
1163       {
1164         lstrcpynA(full_name.short_name,name,MAX_PATHNAME_LEN);
1165         drive = (int)toupper(name[0]) - 'A';
1166       }
1167     else
1168       {
1169         if (driveletter)
1170           drivecur[0]=driveletter;
1171         else
1172           strcpy(drivecur,".");
1173         if (!DOSFS_GetFullName( drivecur, FALSE, &full_name ))
1174           {
1175             FIXME("internal: error getting drive/path\n");
1176             return 0;
1177           }
1178         /* find path that drive letter substitutes*/
1179         drive = (int)toupper(full_name.short_name[0]) -0x41;
1180         root= DRIVE_GetRoot(drive);
1181         if (!root)
1182           {
1183             FIXME("internal: error getting DOS Drive Root\n");
1184             return 0;
1185           }
1186         p= full_name.long_name +strlen(root);
1187         /* append long name (= unix name) to drive */
1188         lstrcpynA(full_name.short_name+2,p,MAX_PATHNAME_LEN-3);
1189         /* append name to treat */
1190         namelen= strlen(full_name.short_name);
1191         p = (char*)name;
1192         if (driveletter)
1193           p += +2; /* skip drive name when appending */
1194         if (namelen +2  + strlen(p) > MAX_PATHNAME_LEN)
1195           {
1196             FIXME("internal error: buffer too small\n");
1197              return 0;
1198           }
1199         full_name.short_name[namelen++] ='\\';
1200         full_name.short_name[namelen] = 0;
1201         lstrcpynA(full_name.short_name +namelen,p,MAX_PATHNAME_LEN-namelen);
1202       }
1203     /* reverse all slashes */
1204     for (p=full_name.short_name;
1205          p < full_name.short_name+strlen(full_name.short_name);
1206          p++)
1207       {
1208         if ( *p == '/' )
1209           *p = '\\';
1210       }
1211      /* Use memmove, as areas overlap*/
1212      /* Delete .. */
1213     while ((p = strstr(full_name.short_name,"\\..\\")))
1214       {
1215         if (p > full_name.short_name+2)
1216           {
1217             *p = 0;
1218             q = strrchr(full_name.short_name,'\\');
1219             memmove(q+1,p+4,strlen(p+4)+1);
1220           }
1221         else
1222           {
1223             memmove(full_name.short_name+3,p+4,strlen(p+4)+1);
1224           }
1225       }
1226     if ((full_name.short_name[2]=='.')&&(full_name.short_name[3]=='.'))
1227         {
1228           /* This case istn't treated yet : c:..\test */
1229           memmove(full_name.short_name+2,full_name.short_name+4,
1230                   strlen(full_name.short_name+4)+1);
1231         }
1232      /* Delete . */
1233     while ((p = strstr(full_name.short_name,"\\.\\")))
1234       {
1235         *(p+1) = 0;
1236         memmove(p+1,p+3,strlen(p+3)+1);
1237       }
1238     if (!(DRIVE_GetFlags(drive) & DRIVE_CASE_PRESERVING))
1239       _strupr( full_name.short_name );
1240     namelen=strlen(full_name.short_name);
1241     if (!strcmp(full_name.short_name+namelen-3,"\\.."))
1242         {
1243           /* one more starnge case: "c:\test\test1\.." 
1244            return "c:\test"*/
1245           *(full_name.short_name+namelen-3)=0;
1246           q = strrchr(full_name.short_name,'\\');
1247           *q =0;
1248         }
1249     if (full_name.short_name[namelen-1]=='.')
1250         full_name.short_name[(namelen--)-1] =0;
1251     if (!driveletter)
1252       if (full_name.short_name[namelen-1]=='\\')
1253         full_name.short_name[(namelen--)-1] =0;
1254     TRACE("got %s\n",full_name.short_name);
1255
1256     /* If the lpBuffer buffer is too small, the return value is the 
1257     size of the buffer, in characters, required to hold the path 
1258     plus the terminating \0 (tested against win95osr, bon 001118)
1259     . */
1260     ret = strlen(full_name.short_name);
1261     if (ret >= len )
1262       {
1263         /* don't touch anything when the buffer is not large enough */
1264         SetLastError( ERROR_INSUFFICIENT_BUFFER );
1265         return ret+1;
1266       }
1267     if (result)
1268     {
1269         if (unicode)
1270             lstrcpynAtoW( (LPWSTR)result, full_name.short_name, len );
1271         else
1272             lstrcpynA( result, full_name.short_name, len );
1273     }
1274
1275     TRACE("returning '%s'\n", full_name.short_name );
1276     return ret;
1277 }
1278
1279
1280 /***********************************************************************
1281  *           GetFullPathNameA   (KERNEL32.272)
1282  * NOTES
1283  *   if the path closed with '\', *lastpart is 0 
1284  */
1285 DWORD WINAPI GetFullPathNameA( LPCSTR name, DWORD len, LPSTR buffer,
1286                                  LPSTR *lastpart )
1287 {
1288     DWORD ret = DOSFS_DoGetFullPathName( name, len, buffer, FALSE );
1289     if (ret && (ret<=len) && buffer && lastpart)
1290     {
1291         LPSTR p = buffer + strlen(buffer);
1292
1293         if (*p != '\\')
1294         {
1295           while ((p > buffer + 2) && (*p != '\\')) p--;
1296           *lastpart = p + 1;
1297         }
1298         else *lastpart = NULL;
1299     }
1300     return ret;
1301 }
1302
1303
1304 /***********************************************************************
1305  *           GetFullPathNameW   (KERNEL32.273)
1306  */
1307 DWORD WINAPI GetFullPathNameW( LPCWSTR name, DWORD len, LPWSTR buffer,
1308                                  LPWSTR *lastpart )
1309 {
1310     LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
1311     DWORD ret = DOSFS_DoGetFullPathName( nameA, len, (LPSTR)buffer, TRUE );
1312     HeapFree( GetProcessHeap(), 0, nameA );
1313     if (ret && (ret<=len) && buffer && lastpart)
1314     {
1315         LPWSTR p = buffer + strlenW(buffer);
1316         if (*p != (WCHAR)'\\')
1317         {
1318             while ((p > buffer + 2) && (*p != (WCHAR)'\\')) p--;
1319             *lastpart = p + 1;
1320         }
1321         else *lastpart = NULL;  
1322     }
1323     return ret;
1324 }
1325
1326 /***********************************************************************
1327  *           DOSFS_FindNextEx
1328  */
1329 static int DOSFS_FindNextEx( FIND_FIRST_INFO *info, WIN32_FIND_DATAA *entry )
1330 {
1331     BYTE attr = info->attr | FA_UNUSED | FA_ARCHIVE | FA_RDONLY;
1332     UINT flags = DRIVE_GetFlags( info->drive );
1333     char *p, buffer[MAX_PATHNAME_LEN];
1334     const char *drive_path;
1335     int drive_root;
1336     LPCSTR long_name, short_name;
1337     BY_HANDLE_FILE_INFORMATION fileinfo;
1338     char dos_name[13];
1339
1340     if ((info->attr & ~(FA_UNUSED | FA_ARCHIVE | FA_RDONLY)) == FA_LABEL)
1341     {
1342         if (info->cur_pos) return 0;
1343         entry->dwFileAttributes  = FILE_ATTRIBUTE_LABEL;
1344         RtlSecondsSince1970ToTime( (time_t)0, &entry->ftCreationTime );
1345         RtlSecondsSince1970ToTime( (time_t)0, &entry->ftLastAccessTime );
1346         RtlSecondsSince1970ToTime( (time_t)0, &entry->ftLastWriteTime );
1347         entry->nFileSizeHigh     = 0;
1348         entry->nFileSizeLow      = 0;
1349         entry->dwReserved0       = 0;
1350         entry->dwReserved1       = 0;
1351         DOSFS_ToDosDTAFormat( DRIVE_GetLabel( info->drive ), entry->cFileName );
1352         strcpy( entry->cAlternateFileName, entry->cFileName ); 
1353         info->cur_pos++;
1354         TRACE("returning %s (%s) as label\n",
1355                entry->cFileName, entry->cAlternateFileName);
1356         return 1;
1357     }
1358
1359     drive_path = info->path + strlen(DRIVE_GetRoot( info->drive ));
1360     while ((*drive_path == '/') || (*drive_path == '\\')) drive_path++;
1361     drive_root = !*drive_path;
1362
1363     lstrcpynA( buffer, info->path, sizeof(buffer) - 1 );
1364     strcat( buffer, "/" );
1365     p = buffer + strlen(buffer);
1366
1367     while (DOSFS_ReadDir( info->dir, &long_name, &short_name ))
1368     {
1369         info->cur_pos++;
1370
1371         /* Don't return '.' and '..' in the root of the drive */
1372         if (drive_root && (long_name[0] == '.') &&
1373             (!long_name[1] || ((long_name[1] == '.') && !long_name[2])))
1374             continue;
1375
1376         /* Check the long mask */
1377
1378         if (info->long_mask)
1379         {
1380             if (!DOSFS_MatchLong( info->long_mask, long_name,
1381                                   flags & DRIVE_CASE_SENSITIVE )) continue;
1382         }
1383
1384         /* Check the short mask */
1385
1386         if (info->short_mask)
1387         {
1388             if (!short_name)
1389             {
1390                 DOSFS_Hash( long_name, dos_name, TRUE,
1391                             !(flags & DRIVE_CASE_SENSITIVE) );
1392                 short_name = dos_name;
1393             }
1394             if (!DOSFS_MatchShort( info->short_mask, short_name )) continue;
1395         }
1396
1397         /* Check the file attributes */
1398
1399         lstrcpynA( p, long_name, sizeof(buffer) - (int)(p - buffer) );
1400         if (!FILE_Stat( buffer, &fileinfo ))
1401         {
1402             WARN("can't stat %s\n", buffer);
1403             continue;
1404         }
1405         if (fileinfo.dwFileAttributes & ~attr) continue;
1406
1407         /* We now have a matching entry; fill the result and return */
1408
1409         entry->dwFileAttributes = fileinfo.dwFileAttributes;
1410         entry->ftCreationTime   = fileinfo.ftCreationTime;
1411         entry->ftLastAccessTime = fileinfo.ftLastAccessTime;
1412         entry->ftLastWriteTime  = fileinfo.ftLastWriteTime;
1413         entry->nFileSizeHigh    = fileinfo.nFileSizeHigh;
1414         entry->nFileSizeLow     = fileinfo.nFileSizeLow;
1415
1416         if (short_name)
1417             DOSFS_ToDosDTAFormat( short_name, entry->cAlternateFileName );
1418         else
1419             DOSFS_Hash( long_name, entry->cAlternateFileName, FALSE,
1420                         !(flags & DRIVE_CASE_SENSITIVE) );
1421
1422         lstrcpynA( entry->cFileName, long_name, sizeof(entry->cFileName) );
1423         if (!(flags & DRIVE_CASE_PRESERVING)) _strlwr( entry->cFileName );
1424         TRACE("returning %s (%s) %02lx %ld\n",
1425               entry->cFileName, entry->cAlternateFileName,
1426               entry->dwFileAttributes, entry->nFileSizeLow );
1427         return 1;
1428     }
1429     return 0;  /* End of directory */
1430 }
1431
1432 /***********************************************************************
1433  *           DOSFS_FindNext
1434  *
1435  * Find the next matching file. Return the number of entries read to find
1436  * the matching one, or 0 if no more entries.
1437  * 'short_mask' is the 8.3 mask (in FCB format), 'long_mask' is the long
1438  * file name mask. Either or both can be NULL.
1439  *
1440  * NOTE: This is supposed to be only called by the int21 emulation
1441  *       routines. Thus, we should own the Win16Mutex anyway.
1442  *       Nevertheless, we explicitly enter it to ensure the static
1443  *       directory cache is protected.
1444  */
1445 int DOSFS_FindNext( const char *path, const char *short_mask,
1446                     const char *long_mask, int drive, BYTE attr,
1447                     int skip, WIN32_FIND_DATAA *entry )
1448 {
1449     static FIND_FIRST_INFO info = { NULL };
1450     LPCSTR short_name, long_name;
1451     int count;
1452
1453     SYSLEVEL_EnterWin16Lock();
1454
1455     /* Check the cached directory */
1456     if (!(info.dir && info.path == path && info.short_mask == short_mask
1457                    && info.long_mask == long_mask && info.drive == drive
1458                    && info.attr == attr && info.cur_pos <= skip))
1459     {  
1460         /* Not in the cache, open it anew */
1461         if (info.dir) DOSFS_CloseDir( info.dir );
1462
1463         info.path = (LPSTR)path;
1464         info.long_mask = (LPSTR)long_mask;
1465         info.short_mask = (LPSTR)short_mask;
1466         info.attr = attr;
1467         info.drive = drive;
1468         info.cur_pos = 0;
1469         info.dir = DOSFS_OpenDir( info.path );
1470     }
1471
1472     /* Skip to desired position */
1473     while (info.cur_pos < skip)
1474         if (info.dir && DOSFS_ReadDir( info.dir, &long_name, &short_name ))
1475             info.cur_pos++;
1476         else
1477             break;
1478
1479     if (info.dir && info.cur_pos == skip && DOSFS_FindNextEx( &info, entry ))
1480         count = info.cur_pos - skip;
1481     else
1482         count = 0;
1483
1484     if (!count)
1485     {
1486         if (info.dir) DOSFS_CloseDir( info.dir );
1487         memset( &info, '\0', sizeof(info) );
1488     }
1489
1490     SYSLEVEL_LeaveWin16Lock();
1491
1492     return count;
1493 }
1494
1495 /*************************************************************************
1496  *           FindFirstFileExA  (KERNEL32)
1497  */
1498 HANDLE WINAPI FindFirstFileExA(
1499         LPCSTR lpFileName,
1500         FINDEX_INFO_LEVELS fInfoLevelId,
1501         LPVOID lpFindFileData,
1502         FINDEX_SEARCH_OPS fSearchOp,
1503         LPVOID lpSearchFilter,
1504         DWORD dwAdditionalFlags)
1505 {
1506     DOS_FULL_NAME full_name;
1507     HGLOBAL handle;
1508     FIND_FIRST_INFO *info;
1509     
1510     if ((fSearchOp != FindExSearchNameMatch) || (dwAdditionalFlags != 0))
1511     {
1512         FIXME("options not implemented 0x%08x 0x%08lx\n", fSearchOp, dwAdditionalFlags );
1513         return INVALID_HANDLE_VALUE;
1514     }
1515
1516     switch(fInfoLevelId)
1517     {
1518       case FindExInfoStandard:
1519         {
1520           WIN32_FIND_DATAA * data = (WIN32_FIND_DATAA *) lpFindFileData;
1521           data->dwReserved0 = data->dwReserved1 = 0x0;
1522           if (!lpFileName) return 0;
1523           if (!DOSFS_GetFullName( lpFileName, FALSE, &full_name )) break;
1524           if (!(handle = GlobalAlloc(GMEM_MOVEABLE, sizeof(FIND_FIRST_INFO)))) break;
1525           info = (FIND_FIRST_INFO *)GlobalLock( handle );
1526           info->path = HEAP_strdupA( GetProcessHeap(), 0, full_name.long_name );
1527           info->long_mask = strrchr( info->path, '/' );
1528           *(info->long_mask++) = '\0';
1529           info->short_mask = NULL;
1530           info->attr = 0xff;
1531           if (lpFileName[0] && (lpFileName[1] == ':'))
1532               info->drive = toupper(*lpFileName) - 'A';
1533           else info->drive = DRIVE_GetCurrentDrive();
1534           info->cur_pos = 0;
1535
1536           info->dir = DOSFS_OpenDir( info->path );
1537
1538           GlobalUnlock( handle );
1539           if (!FindNextFileA( handle, data ))
1540           {
1541               FindClose( handle );
1542               SetLastError( ERROR_NO_MORE_FILES );
1543               break;
1544           }
1545           return handle;
1546         }
1547         break;
1548       default:
1549         FIXME("fInfoLevelId 0x%08x not implemented\n", fInfoLevelId );
1550     }
1551     return INVALID_HANDLE_VALUE;
1552 }
1553
1554 /*************************************************************************
1555  *           FindFirstFileA   (KERNEL32.123)
1556  */
1557 HANDLE WINAPI FindFirstFileA(
1558         LPCSTR lpFileName,
1559         WIN32_FIND_DATAA *lpFindData )
1560 {
1561     return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
1562                             FindExSearchNameMatch, NULL, 0);
1563 }
1564
1565 /*************************************************************************
1566  *           FindFirstFileExW   (KERNEL32)
1567  */
1568 HANDLE WINAPI FindFirstFileExW(
1569         LPCWSTR lpFileName,
1570         FINDEX_INFO_LEVELS fInfoLevelId,
1571         LPVOID lpFindFileData,
1572         FINDEX_SEARCH_OPS fSearchOp,
1573         LPVOID lpSearchFilter,
1574         DWORD dwAdditionalFlags)
1575 {
1576     HANDLE handle;
1577     WIN32_FIND_DATAA dataA;
1578     LPVOID _lpFindFileData;
1579     LPSTR pathA;
1580
1581     switch(fInfoLevelId)
1582     {
1583       case FindExInfoStandard:
1584         {
1585           _lpFindFileData = &dataA;
1586         }
1587         break;
1588       default:
1589         FIXME("fInfoLevelId 0x%08x not implemented\n", fInfoLevelId );
1590         return INVALID_HANDLE_VALUE;
1591     }
1592
1593     pathA = HEAP_strdupWtoA( GetProcessHeap(), 0, lpFileName );
1594     handle = FindFirstFileExA(pathA, fInfoLevelId, _lpFindFileData, fSearchOp, lpSearchFilter, dwAdditionalFlags);
1595     HeapFree( GetProcessHeap(), 0, pathA );
1596     if (handle == INVALID_HANDLE_VALUE) return handle;
1597     
1598     switch(fInfoLevelId)
1599     {
1600       case FindExInfoStandard:
1601         {
1602           WIN32_FIND_DATAW *dataW = (WIN32_FIND_DATAW*) lpFindFileData;
1603           dataW->dwFileAttributes = dataA.dwFileAttributes;
1604           dataW->ftCreationTime   = dataA.ftCreationTime;
1605           dataW->ftLastAccessTime = dataA.ftLastAccessTime;
1606           dataW->ftLastWriteTime  = dataA.ftLastWriteTime;
1607           dataW->nFileSizeHigh    = dataA.nFileSizeHigh;
1608           dataW->nFileSizeLow     = dataA.nFileSizeLow;
1609           lstrcpyAtoW( dataW->cFileName, dataA.cFileName );
1610           lstrcpyAtoW( dataW->cAlternateFileName, dataA.cAlternateFileName );
1611         }
1612         break;
1613       default:
1614         FIXME("fInfoLevelId 0x%08x not implemented\n", fInfoLevelId );
1615         return INVALID_HANDLE_VALUE;
1616     }
1617     return handle;
1618 }
1619
1620 /*************************************************************************
1621  *           FindFirstFileW   (KERNEL32.124)
1622  */
1623 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
1624 {
1625     return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
1626                             FindExSearchNameMatch, NULL, 0);
1627 }
1628
1629 /*************************************************************************
1630  *           FindNextFileA   (KERNEL32.126)
1631  */
1632 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
1633 {
1634     FIND_FIRST_INFO *info;
1635
1636     if ((handle == INVALID_HANDLE_VALUE) || 
1637        !(info = (FIND_FIRST_INFO *)GlobalLock( handle )))
1638     {
1639         SetLastError( ERROR_INVALID_HANDLE );
1640         return FALSE;
1641     }
1642     GlobalUnlock( handle );
1643     if (!info->path || !info->dir)
1644     {
1645         SetLastError( ERROR_NO_MORE_FILES );
1646         return FALSE;
1647     }
1648     if (!DOSFS_FindNextEx( info, data ))
1649     {
1650         DOSFS_CloseDir( info->dir ); info->dir = NULL;
1651         HeapFree( GetProcessHeap(), 0, info->path );
1652         info->path = info->long_mask = NULL;
1653         SetLastError( ERROR_NO_MORE_FILES );
1654         return FALSE;
1655     }
1656     return TRUE;
1657 }
1658
1659
1660 /*************************************************************************
1661  *           FindNextFileW   (KERNEL32.127)
1662  */
1663 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1664 {
1665     WIN32_FIND_DATAA dataA;
1666     if (!FindNextFileA( handle, &dataA )) return FALSE;
1667     data->dwFileAttributes = dataA.dwFileAttributes;
1668     data->ftCreationTime   = dataA.ftCreationTime;
1669     data->ftLastAccessTime = dataA.ftLastAccessTime;
1670     data->ftLastWriteTime  = dataA.ftLastWriteTime;
1671     data->nFileSizeHigh    = dataA.nFileSizeHigh;
1672     data->nFileSizeLow     = dataA.nFileSizeLow;
1673     lstrcpyAtoW( data->cFileName, dataA.cFileName );
1674     lstrcpyAtoW( data->cAlternateFileName, dataA.cAlternateFileName );
1675     return TRUE;
1676 }
1677
1678 /*************************************************************************
1679  *           FindClose   (KERNEL32.119)
1680  */
1681 BOOL WINAPI FindClose( HANDLE handle )
1682 {
1683     FIND_FIRST_INFO *info;
1684
1685     if ((handle == INVALID_HANDLE_VALUE) ||
1686         !(info = (FIND_FIRST_INFO *)GlobalLock( handle )))
1687     {
1688         SetLastError( ERROR_INVALID_HANDLE );
1689         return FALSE;
1690     }
1691     if (info->dir) DOSFS_CloseDir( info->dir );
1692     if (info->path) HeapFree( GetProcessHeap(), 0, info->path );
1693     GlobalUnlock( handle );
1694     GlobalFree( handle );
1695     return TRUE;
1696 }
1697
1698 /***********************************************************************
1699  *           DOSFS_UnixTimeToFileTime
1700  *
1701  * Convert a Unix time to FILETIME format.
1702  * The FILETIME structure is a 64-bit value representing the number of
1703  * 100-nanosecond intervals since January 1, 1601, 0:00.
1704  * 'remainder' is the nonnegative number of 100-ns intervals
1705  * corresponding to the time fraction smaller than 1 second that
1706  * couldn't be stored in the time_t value.
1707  */
1708 void DOSFS_UnixTimeToFileTime( time_t unix_time, FILETIME *filetime,
1709                                DWORD remainder )
1710 {
1711     /* NOTES:
1712
1713        CONSTANTS: 
1714        The time difference between 1 January 1601, 00:00:00 and
1715        1 January 1970, 00:00:00 is 369 years, plus the leap years
1716        from 1604 to 1968, excluding 1700, 1800, 1900.
1717        This makes (1968 - 1600) / 4 - 3 = 89 leap days, and a total
1718        of 134774 days.
1719
1720        Any day in that period had 24 * 60 * 60 = 86400 seconds.
1721
1722        The time difference is 134774 * 86400 * 10000000, which can be written
1723        116444736000000000
1724        27111902 * 2^32 + 3577643008
1725        413 * 2^48 + 45534 * 2^32 + 54590 * 2^16 + 32768
1726
1727        If you find that these constants are buggy, please change them in all
1728        instances in both conversion functions.
1729
1730        VERSIONS:
1731        There are two versions, one of them uses long long variables and
1732        is presumably faster but not ISO C. The other one uses standard C
1733        data types and operations but relies on the assumption that negative
1734        numbers are stored as 2's complement (-1 is 0xffff....). If this
1735        assumption is violated, dates before 1970 will not convert correctly.
1736        This should however work on any reasonable architecture where WINE
1737        will run.
1738
1739        DETAILS:
1740        
1741        Take care not to remove the casts. I have tested these functions
1742        (in both versions) for a lot of numbers. I would be interested in
1743        results on other compilers than GCC.
1744
1745        The operations have been designed to account for the possibility
1746        of 64-bit time_t in future UNICES. Even the versions without
1747        internal long long numbers will work if time_t only is 64 bit.
1748        A 32-bit shift, which was necessary for that operation, turned out
1749        not to work correctly in GCC, besides giving the warning. So I
1750        used a double 16-bit shift instead. Numbers are in the ISO version
1751        represented by three limbs, the most significant with 32 bit, the
1752        other two with 16 bit each.
1753
1754        As the modulo-operator % is not well-defined for negative numbers,
1755        negative divisors have been avoided in DOSFS_FileTimeToUnixTime.
1756
1757        There might be quicker ways to do this in C. Certainly so in
1758        assembler.
1759
1760        Claus Fischer, fischer@iue.tuwien.ac.at
1761        */
1762
1763 #if SIZEOF_LONG_LONG >= 8
1764 #  define USE_LONG_LONG 1
1765 #else
1766 #  define USE_LONG_LONG 0
1767 #endif
1768
1769 #if USE_LONG_LONG               /* gcc supports long long type */
1770
1771     long long int t = unix_time;
1772     t *= 10000000;
1773     t += 116444736000000000LL;
1774     t += remainder;
1775     filetime->dwLowDateTime  = (UINT)t;
1776     filetime->dwHighDateTime = (UINT)(t >> 32);
1777
1778 #else  /* ISO version */
1779
1780     UINT a0;                    /* 16 bit, low    bits */
1781     UINT a1;                    /* 16 bit, medium bits */
1782     UINT a2;                    /* 32 bit, high   bits */
1783
1784     /* Copy the unix time to a2/a1/a0 */
1785     a0 =  unix_time & 0xffff;
1786     a1 = (unix_time >> 16) & 0xffff;
1787     /* This is obsolete if unix_time is only 32 bits, but it does not hurt.
1788        Do not replace this by >> 32, it gives a compiler warning and it does
1789        not work. */
1790     a2 = (unix_time >= 0 ? (unix_time >> 16) >> 16 :
1791           ~((~unix_time >> 16) >> 16));
1792
1793     /* Multiply a by 10000000 (a = a2/a1/a0)
1794        Split the factor into 10000 * 1000 which are both less than 0xffff. */
1795     a0 *= 10000;
1796     a1 = a1 * 10000 + (a0 >> 16);
1797     a2 = a2 * 10000 + (a1 >> 16);
1798     a0 &= 0xffff;
1799     a1 &= 0xffff;
1800
1801     a0 *= 1000;
1802     a1 = a1 * 1000 + (a0 >> 16);
1803     a2 = a2 * 1000 + (a1 >> 16);
1804     a0 &= 0xffff;
1805     a1 &= 0xffff;
1806
1807     /* Add the time difference and the remainder */
1808     a0 += 32768 + (remainder & 0xffff);
1809     a1 += 54590 + (remainder >> 16   ) + (a0 >> 16);
1810     a2 += 27111902                     + (a1 >> 16);
1811     a0 &= 0xffff;
1812     a1 &= 0xffff;
1813
1814     /* Set filetime */
1815     filetime->dwLowDateTime  = (a1 << 16) + a0;
1816     filetime->dwHighDateTime = a2;
1817 #endif
1818 }
1819
1820
1821 /***********************************************************************
1822  *           DOSFS_FileTimeToUnixTime
1823  *
1824  * Convert a FILETIME format to Unix time.
1825  * If not NULL, 'remainder' contains the fractional part of the filetime,
1826  * in the range of [0..9999999] (even if time_t is negative).
1827  */
1828 time_t DOSFS_FileTimeToUnixTime( const FILETIME *filetime, DWORD *remainder )
1829 {
1830     /* Read the comment in the function DOSFS_UnixTimeToFileTime. */
1831 #if USE_LONG_LONG
1832
1833     long long int t = filetime->dwHighDateTime;
1834     t <<= 32;
1835     t += (UINT)filetime->dwLowDateTime;
1836     t -= 116444736000000000LL;
1837     if (t < 0)
1838     {
1839         if (remainder) *remainder = 9999999 - (-t - 1) % 10000000;
1840         return -1 - ((-t - 1) / 10000000);
1841     }
1842     else
1843     {
1844         if (remainder) *remainder = t % 10000000;
1845         return t / 10000000;
1846     }
1847
1848 #else  /* ISO version */
1849
1850     UINT a0;                    /* 16 bit, low    bits */
1851     UINT a1;                    /* 16 bit, medium bits */
1852     UINT a2;                    /* 32 bit, high   bits */
1853     UINT r;                     /* remainder of division */
1854     unsigned int carry;         /* carry bit for subtraction */
1855     int negative;               /* whether a represents a negative value */
1856
1857     /* Copy the time values to a2/a1/a0 */
1858     a2 =  (UINT)filetime->dwHighDateTime;
1859     a1 = ((UINT)filetime->dwLowDateTime ) >> 16;
1860     a0 = ((UINT)filetime->dwLowDateTime ) & 0xffff;
1861
1862     /* Subtract the time difference */
1863     if (a0 >= 32768           ) a0 -=             32768        , carry = 0;
1864     else                        a0 += (1 << 16) - 32768        , carry = 1;
1865
1866     if (a1 >= 54590    + carry) a1 -=             54590 + carry, carry = 0;
1867     else                        a1 += (1 << 16) - 54590 - carry, carry = 1;
1868
1869     a2 -= 27111902 + carry;
1870     
1871     /* If a is negative, replace a by (-1-a) */
1872     negative = (a2 >= ((UINT)1) << 31);
1873     if (negative)
1874     {
1875         /* Set a to -a - 1 (a is a2/a1/a0) */
1876         a0 = 0xffff - a0;
1877         a1 = 0xffff - a1;
1878         a2 = ~a2;
1879     }
1880
1881     /* Divide a by 10000000 (a = a2/a1/a0), put the rest into r.
1882        Split the divisor into 10000 * 1000 which are both less than 0xffff. */
1883     a1 += (a2 % 10000) << 16;
1884     a2 /=       10000;
1885     a0 += (a1 % 10000) << 16;
1886     a1 /=       10000;
1887     r   =  a0 % 10000;
1888     a0 /=       10000;
1889
1890     a1 += (a2 % 1000) << 16;
1891     a2 /=       1000;
1892     a0 += (a1 % 1000) << 16;
1893     a1 /=       1000;
1894     r  += (a0 % 1000) * 10000;
1895     a0 /=       1000;
1896
1897     /* If a was negative, replace a by (-1-a) and r by (9999999 - r) */
1898     if (negative)
1899     {
1900         /* Set a to -a - 1 (a is a2/a1/a0) */
1901         a0 = 0xffff - a0;
1902         a1 = 0xffff - a1;
1903         a2 = ~a2;
1904
1905         r  = 9999999 - r;
1906     }
1907
1908     if (remainder) *remainder = r;
1909
1910     /* Do not replace this by << 32, it gives a compiler warning and it does
1911        not work. */
1912     return ((((time_t)a2) << 16) << 16) + (a1 << 16) + a0;
1913 #endif
1914 }
1915
1916
1917 /***********************************************************************
1918  *           MulDiv   (KERNEL32.391)
1919  * RETURNS
1920  *      Result of multiplication and division
1921  *      -1: Overflow occurred or Divisor was 0
1922  */
1923 INT WINAPI MulDiv(
1924              INT nMultiplicand, 
1925              INT nMultiplier,
1926              INT nDivisor)
1927 {
1928 #if SIZEOF_LONG_LONG >= 8
1929     long long ret;
1930
1931     if (!nDivisor) return -1;
1932
1933     /* We want to deal with a positive divisor to simplify the logic. */
1934     if (nDivisor < 0)
1935     {
1936       nMultiplicand = - nMultiplicand;
1937       nDivisor = -nDivisor;
1938     }
1939
1940     /* If the result is positive, we "add" to round. else, we subtract to round. */
1941     if ( ( (nMultiplicand <  0) && (nMultiplier <  0) ) ||
1942          ( (nMultiplicand >= 0) && (nMultiplier >= 0) ) )
1943       ret = (((long long)nMultiplicand * nMultiplier) + (nDivisor/2)) / nDivisor;
1944     else
1945       ret = (((long long)nMultiplicand * nMultiplier) - (nDivisor/2)) / nDivisor;
1946
1947     if ((ret > 2147483647) || (ret < -2147483647)) return -1;
1948     return ret;
1949 #else
1950     if (!nDivisor) return -1;
1951
1952     /* We want to deal with a positive divisor to simplify the logic. */
1953     if (nDivisor < 0)
1954     {
1955       nMultiplicand = - nMultiplicand;
1956       nDivisor = -nDivisor;
1957     }
1958
1959     /* If the result is positive, we "add" to round. else, we subtract to round. */
1960     if ( ( (nMultiplicand <  0) && (nMultiplier <  0) ) ||
1961          ( (nMultiplicand >= 0) && (nMultiplier >= 0) ) )
1962       return ((nMultiplicand * nMultiplier) + (nDivisor/2)) / nDivisor;
1963  
1964     return ((nMultiplicand * nMultiplier) - (nDivisor/2)) / nDivisor;
1965     
1966 #endif
1967 }
1968
1969
1970 /***********************************************************************
1971  *           DosDateTimeToFileTime   (KERNEL32.76)
1972  */
1973 BOOL WINAPI DosDateTimeToFileTime( WORD fatdate, WORD fattime, LPFILETIME ft)
1974 {
1975     struct tm newtm;
1976
1977     newtm.tm_sec  = (fattime & 0x1f) * 2;
1978     newtm.tm_min  = (fattime >> 5) & 0x3f;
1979     newtm.tm_hour = (fattime >> 11);
1980     newtm.tm_mday = (fatdate & 0x1f);
1981     newtm.tm_mon  = ((fatdate >> 5) & 0x0f) - 1;
1982     newtm.tm_year = (fatdate >> 9) + 80;
1983     RtlSecondsSince1970ToTime( mktime( &newtm ), ft );
1984     return TRUE;
1985 }
1986
1987
1988 /***********************************************************************
1989  *           FileTimeToDosDateTime   (KERNEL32.111)
1990  */
1991 BOOL WINAPI FileTimeToDosDateTime( const FILETIME *ft, LPWORD fatdate,
1992                                      LPWORD fattime )
1993 {
1994     time_t unixtime = DOSFS_FileTimeToUnixTime( ft, NULL );
1995     struct tm *tm = localtime( &unixtime );
1996     if (fattime)
1997         *fattime = (tm->tm_hour << 11) + (tm->tm_min << 5) + (tm->tm_sec / 2);
1998     if (fatdate)
1999         *fatdate = ((tm->tm_year - 80) << 9) + ((tm->tm_mon + 1) << 5)
2000                    + tm->tm_mday;
2001     return TRUE;
2002 }
2003
2004
2005 /***********************************************************************
2006  *           LocalFileTimeToFileTime   (KERNEL32.373)
2007  */
2008 BOOL WINAPI LocalFileTimeToFileTime( const FILETIME *localft,
2009                                        LPFILETIME utcft )
2010 {
2011     struct tm *xtm;
2012     DWORD remainder;
2013
2014     /* convert from local to UTC. Perhaps not correct. FIXME */
2015     time_t unixtime = DOSFS_FileTimeToUnixTime( localft, &remainder );
2016     xtm = gmtime( &unixtime );
2017     DOSFS_UnixTimeToFileTime( mktime(xtm), utcft, remainder );
2018     return TRUE; 
2019 }
2020
2021
2022 /***********************************************************************
2023  *           FileTimeToLocalFileTime   (KERNEL32.112)
2024  */
2025 BOOL WINAPI FileTimeToLocalFileTime( const FILETIME *utcft,
2026                                        LPFILETIME localft )
2027 {
2028     DWORD remainder;
2029     /* convert from UTC to local. Perhaps not correct. FIXME */
2030     time_t unixtime = DOSFS_FileTimeToUnixTime( utcft, &remainder );
2031 #ifdef HAVE_TIMEGM
2032     struct tm *xtm = localtime( &unixtime );
2033     time_t localtime;
2034
2035     localtime = timegm(xtm);
2036     DOSFS_UnixTimeToFileTime( localtime, localft, remainder );
2037
2038 #else
2039     struct tm *xtm,*gtm;
2040     time_t time1,time2;
2041
2042     xtm = localtime( &unixtime );
2043     gtm = gmtime( &unixtime );
2044     time1 = mktime(xtm);
2045     time2 = mktime(gtm);
2046     DOSFS_UnixTimeToFileTime( 2*time1-time2, localft, remainder );
2047 #endif
2048     return TRUE; 
2049 }
2050
2051
2052 /***********************************************************************
2053  *           FileTimeToSystemTime   (KERNEL32.113)
2054  */
2055 BOOL WINAPI FileTimeToSystemTime( const FILETIME *ft, LPSYSTEMTIME syst )
2056 {
2057     struct tm *xtm;
2058     DWORD remainder;
2059     time_t xtime = DOSFS_FileTimeToUnixTime( ft, &remainder );
2060     xtm = gmtime(&xtime);
2061     syst->wYear         = xtm->tm_year+1900;
2062     syst->wMonth        = xtm->tm_mon + 1;
2063     syst->wDayOfWeek    = xtm->tm_wday;
2064     syst->wDay          = xtm->tm_mday;
2065     syst->wHour         = xtm->tm_hour;
2066     syst->wMinute       = xtm->tm_min;
2067     syst->wSecond       = xtm->tm_sec;
2068     syst->wMilliseconds = remainder / 10000;
2069     return TRUE; 
2070 }
2071
2072 /***********************************************************************
2073  *           QueryDosDeviceA   (KERNEL32.413)
2074  *
2075  * returns array of strings terminated by \0, terminated by \0
2076  */
2077 DWORD WINAPI QueryDosDeviceA(LPCSTR devname,LPSTR target,DWORD bufsize)
2078 {
2079     LPSTR s;
2080     char  buffer[200];
2081
2082     TRACE("(%s,...)\n", devname ? devname : "<null>");
2083     if (!devname) {
2084         /* return known MSDOS devices */
2085         strcpy(buffer,"CON COM1 COM2 LPT1 NUL ");
2086         while ((s=strchr(buffer,' ')))
2087                 *s='\0';
2088
2089         lstrcpynA(target,buffer,bufsize);
2090         return strlen(buffer);
2091     }
2092     strcpy(buffer,"\\DEV\\");
2093     strcat(buffer,devname);
2094     if ((s=strchr(buffer,':'))) *s='\0';
2095     lstrcpynA(target,buffer,bufsize);
2096     return strlen(buffer);
2097 }
2098
2099
2100 /***********************************************************************
2101  *           QueryDosDeviceW   (KERNEL32.414)
2102  *
2103  * returns array of strings terminated by \0, terminated by \0
2104  */
2105 DWORD WINAPI QueryDosDeviceW(LPCWSTR devname,LPWSTR target,DWORD bufsize)
2106 {
2107     LPSTR devnameA = devname?HEAP_strdupWtoA(GetProcessHeap(),0,devname):NULL;
2108     LPSTR targetA = (LPSTR)HeapAlloc(GetProcessHeap(),0,bufsize);
2109     DWORD ret = QueryDosDeviceA(devnameA,targetA,bufsize);
2110
2111     lstrcpynAtoW(target,targetA,bufsize);
2112     if (devnameA) HeapFree(GetProcessHeap(),0,devnameA);
2113     if (targetA) HeapFree(GetProcessHeap(),0,targetA);
2114     return ret;
2115 }
2116
2117
2118 /***********************************************************************
2119  *           SystemTimeToFileTime   (KERNEL32.526)
2120  */
2121 BOOL WINAPI SystemTimeToFileTime( const SYSTEMTIME *syst, LPFILETIME ft )
2122 {
2123 #ifdef HAVE_TIMEGM
2124     struct tm xtm;
2125     time_t utctime;
2126 #else
2127     struct tm xtm,*local_tm,*utc_tm;
2128     time_t localtim,utctime;
2129 #endif
2130
2131     xtm.tm_year = syst->wYear-1900;
2132     xtm.tm_mon  = syst->wMonth - 1;
2133     xtm.tm_wday = syst->wDayOfWeek;
2134     xtm.tm_mday = syst->wDay;
2135     xtm.tm_hour = syst->wHour;
2136     xtm.tm_min  = syst->wMinute;
2137     xtm.tm_sec  = syst->wSecond; /* this is UTC */
2138     xtm.tm_isdst = -1;
2139 #ifdef HAVE_TIMEGM
2140     utctime = timegm(&xtm);
2141     DOSFS_UnixTimeToFileTime( utctime, ft, 
2142                               syst->wMilliseconds * 10000 );
2143 #else
2144     localtim = mktime(&xtm);    /* now we've got local time */
2145     local_tm = localtime(&localtim);
2146     utc_tm = gmtime(&localtim);
2147     utctime = mktime(utc_tm);
2148     DOSFS_UnixTimeToFileTime( 2*localtim -utctime, ft, 
2149                               syst->wMilliseconds * 10000 );
2150 #endif
2151     return TRUE; 
2152 }
2153
2154 /***********************************************************************
2155  *           DefineDosDeviceA       (KERNEL32.182)
2156  */
2157 BOOL WINAPI DefineDosDeviceA(DWORD flags,LPCSTR devname,LPCSTR targetpath) {
2158         FIXME("(0x%08lx,%s,%s),stub!\n",flags,devname,targetpath);
2159         SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2160         return FALSE;
2161 }
2162
2163 /*
2164    --- 16 bit functions ---
2165 */
2166
2167 /*************************************************************************
2168  *           FindFirstFile16   (KERNEL.413)
2169  */
2170 HANDLE16 WINAPI FindFirstFile16( LPCSTR path, WIN32_FIND_DATAA *data )
2171 {
2172     DOS_FULL_NAME full_name;
2173     HGLOBAL16 handle;
2174     FIND_FIRST_INFO *info;
2175
2176     data->dwReserved0 = data->dwReserved1 = 0x0;
2177     if (!path) return 0;
2178     if (!DOSFS_GetFullName( path, FALSE, &full_name ))
2179         return INVALID_HANDLE_VALUE16;
2180     if (!(handle = GlobalAlloc16( GMEM_MOVEABLE, sizeof(FIND_FIRST_INFO) )))
2181         return INVALID_HANDLE_VALUE16;
2182     info = (FIND_FIRST_INFO *)GlobalLock16( handle );
2183     info->path = HEAP_strdupA( SystemHeap, 0, full_name.long_name );
2184     info->long_mask = strrchr( info->path, '/' );
2185     if (info->long_mask )
2186         *(info->long_mask++) = '\0';
2187     info->short_mask = NULL;
2188     info->attr = 0xff;
2189     if (path[0] && (path[1] == ':')) info->drive = toupper(*path) - 'A';
2190     else info->drive = DRIVE_GetCurrentDrive();
2191     info->cur_pos = 0;
2192
2193     info->dir = DOSFS_OpenDir( info->path );
2194
2195     GlobalUnlock16( handle );
2196     if (!FindNextFile16( handle, data ))
2197     {
2198         FindClose16( handle );
2199         SetLastError( ERROR_NO_MORE_FILES );
2200         return INVALID_HANDLE_VALUE16;
2201     }
2202     return handle;
2203 }
2204
2205 /*************************************************************************
2206  *           FindNextFile16   (KERNEL.414)
2207  */
2208 BOOL16 WINAPI FindNextFile16( HANDLE16 handle, WIN32_FIND_DATAA *data )
2209 {
2210     FIND_FIRST_INFO *info;
2211
2212     if ((handle == INVALID_HANDLE_VALUE16) ||
2213        !(info = (FIND_FIRST_INFO *)GlobalLock16( handle )))
2214     {
2215         SetLastError( ERROR_INVALID_HANDLE );
2216         return FALSE;
2217     }
2218     GlobalUnlock16( handle );
2219     if (!info->path || !info->dir)
2220     {
2221         SetLastError( ERROR_NO_MORE_FILES );
2222         return FALSE;
2223     }
2224     if (!DOSFS_FindNextEx( info, data ))
2225     {
2226         DOSFS_CloseDir( info->dir ); info->dir = NULL;
2227         HeapFree( SystemHeap, 0, info->path );
2228         info->path = info->long_mask = NULL;
2229         SetLastError( ERROR_NO_MORE_FILES );
2230         return FALSE;
2231     }
2232     return TRUE;
2233 }
2234
2235 /*************************************************************************
2236  *           FindClose16   (KERNEL.415)
2237  */
2238 BOOL16 WINAPI FindClose16( HANDLE16 handle )
2239 {
2240     FIND_FIRST_INFO *info;
2241
2242     if ((handle == INVALID_HANDLE_VALUE16) ||
2243         !(info = (FIND_FIRST_INFO *)GlobalLock16( handle )))
2244     {
2245         SetLastError( ERROR_INVALID_HANDLE );
2246         return FALSE;
2247     }
2248     if (info->dir) DOSFS_CloseDir( info->dir );
2249     if (info->path) HeapFree( SystemHeap, 0, info->path );
2250     GlobalUnlock16( handle );
2251     GlobalFree16( handle );
2252     return TRUE;
2253 }
2254