If we have a drive pointing to /, we must not remove the final / or we
[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 "wine/winestring.h"
29 #include "winerror.h"
30 #include "drive.h"
31 #include "file.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 (!strncasecmp( 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 (!strncasecmp( 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_CreateCommPort
698  */
699 static HANDLE DOSFS_CreateCommPort(LPCSTR name, DWORD access)
700 {
701     HANDLE ret = INVALID_HANDLE_VALUE;
702     char devname[40];
703
704     TRACE("%s %lx\n", name, access);
705
706     PROFILE_GetWineIniString("serialports",name,"",devname,sizeof devname);
707     if(!devname[0])
708         return 0;
709
710     TRACE("opening %s as %s\n", devname, name);
711
712     SERVER_START_REQ
713     {
714         size_t len = strlen(devname);
715         struct create_serial_request *req = server_alloc_req( sizeof(*req), len );
716
717         req->access  = access;
718         req->inherit = 0;  /*FIXME*/
719         req->sharing = FILE_SHARE_READ|FILE_SHARE_WRITE;
720         memcpy( server_data_ptr(req), devname, len );
721         SetLastError(0);
722         if (!(server_call( REQ_CREATE_SERIAL ))) ret = req->handle;
723     }
724     SERVER_END_REQ;
725
726     TRACE("return %08X\n", ret );
727     return ret;
728 }
729
730 /***********************************************************************
731  *           DOSFS_OpenDevice
732  *
733  * Open a DOS device. This might not map 1:1 into the UNIX device concept.
734  */
735 HFILE DOSFS_OpenDevice( const char *name, DWORD access )
736 {
737     int i;
738     const char *p;
739     HFILE handle;
740
741     if (!name) return (HFILE)NULL; /* if FILE_DupUnixHandle was used */
742     if (name[0] && (name[1] == ':')) name += 2;
743     if ((p = strrchr( name, '/' ))) name = p + 1;
744     if ((p = strrchr( name, '\\' ))) name = p + 1;
745     for (i = 0; i < sizeof(DOSFS_Devices)/sizeof(DOSFS_Devices[0]); i++)
746     {
747         const char *dev = DOSFS_Devices[i].name;
748         if (!strncasecmp( dev, name, strlen(dev) ))
749         {
750             p = name + strlen( dev );
751             if (!*p || (*p == '.')) {
752                 /* got it */
753                 if (!strcmp(DOSFS_Devices[i].name,"NUL"))
754                     return FILE_CreateFile( "/dev/null", access,
755                                             FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
756                                             OPEN_EXISTING, 0, -1, TRUE );
757                 if (!strcmp(DOSFS_Devices[i].name,"CON")) {
758                         HFILE to_dup;
759                         switch (access & (GENERIC_READ|GENERIC_WRITE)) {
760                         case GENERIC_READ:
761                                 to_dup = GetStdHandle( STD_INPUT_HANDLE );
762                                 break;
763                         case GENERIC_WRITE:
764                                 to_dup = GetStdHandle( STD_OUTPUT_HANDLE );
765                                 break;
766                         default:
767                                 FIXME("can't open CON read/write\n");
768                                 return HFILE_ERROR;
769                                 break;
770                         }
771                         if (!DuplicateHandle( GetCurrentProcess(), to_dup, GetCurrentProcess(),
772                                               &handle, 0, FALSE, DUPLICATE_SAME_ACCESS ))
773                             handle = HFILE_ERROR;
774                         return handle;
775                 }
776                 if (!strcmp(DOSFS_Devices[i].name,"SCSIMGR$") ||
777                     !strcmp(DOSFS_Devices[i].name,"HPSCAN"))
778                 {
779                     return FILE_CreateDevice( i, access, NULL );
780                 }
781
782                 if( (handle=DOSFS_CreateCommPort(name,access)) )
783                     return handle;
784
785                 FIXME("device open %s not supported (yet)\n",DOSFS_Devices[i].name);
786                 return HFILE_ERROR;
787             }
788         }
789     }
790     return HFILE_ERROR;
791 }
792
793
794 /***********************************************************************
795  *           DOSFS_GetPathDrive
796  *
797  * Get the drive specified by a given path name (DOS or Unix format).
798  */
799 static int DOSFS_GetPathDrive( const char **name )
800 {
801     int drive;
802     const char *p = *name;
803
804     if (*p && (p[1] == ':'))
805     {
806         drive = toupper(*p) - 'A';
807         *name += 2;
808     }
809     else if (*p == '/') /* Absolute Unix path? */
810     {
811         if ((drive = DRIVE_FindDriveRoot( name )) == -1)
812         {
813             MESSAGE("Warning: %s not accessible from a DOS drive\n", *name );
814             /* Assume it really was a DOS name */
815             drive = DRIVE_GetCurrentDrive();            
816         }
817     }
818     else drive = DRIVE_GetCurrentDrive();
819
820     if (!DRIVE_IsValid(drive))
821     {
822         SetLastError( ERROR_INVALID_DRIVE );
823         return -1;
824     }
825     return drive;
826 }
827
828
829 /***********************************************************************
830  *           DOSFS_GetFullName
831  *
832  * Convert a file name (DOS or mixed DOS/Unix format) to a valid
833  * Unix name / short DOS name pair.
834  * Return FALSE if one of the path components does not exist. The last path
835  * component is only checked if 'check_last' is non-zero.
836  * The buffers pointed to by 'long_buf' and 'short_buf' must be
837  * at least MAX_PATHNAME_LEN long.
838  */
839 BOOL DOSFS_GetFullName( LPCSTR name, BOOL check_last, DOS_FULL_NAME *full )
840 {
841     BOOL found;
842     UINT flags;
843     char *p_l, *p_s, *root;
844
845     TRACE("%s (last=%d)\n", name, check_last );
846
847     if ((full->drive = DOSFS_GetPathDrive( &name )) == -1) return FALSE;
848     flags = DRIVE_GetFlags( full->drive );
849
850     lstrcpynA( full->long_name, DRIVE_GetRoot( full->drive ),
851                  sizeof(full->long_name) );
852     if (full->long_name[1]) root = full->long_name + strlen(full->long_name);
853     else root = full->long_name;  /* root directory */
854
855     strcpy( full->short_name, "A:\\" );
856     full->short_name[0] += full->drive;
857
858     if ((*name == '\\') || (*name == '/'))  /* Absolute path */
859     {
860         while ((*name == '\\') || (*name == '/')) name++;
861     }
862     else  /* Relative path */
863     {
864         lstrcpynA( root + 1, DRIVE_GetUnixCwd( full->drive ),
865                      sizeof(full->long_name) - (root - full->long_name) - 1 );
866         if (root[1]) *root = '/';
867         lstrcpynA( full->short_name + 3, DRIVE_GetDosCwd( full->drive ),
868                      sizeof(full->short_name) - 3 );
869     }
870
871     p_l = full->long_name[1] ? full->long_name + strlen(full->long_name)
872                              : full->long_name;
873     p_s = full->short_name[3] ? full->short_name + strlen(full->short_name)
874                               : full->short_name + 2;
875     found = TRUE;
876
877     while (*name && found)
878     {
879         /* Check for '.' and '..' */
880
881         if (*name == '.')
882         {
883             if (IS_END_OF_NAME(name[1]))
884             {
885                 name++;
886                 while ((*name == '\\') || (*name == '/')) name++;
887                 continue;
888             }
889             else if ((name[1] == '.') && IS_END_OF_NAME(name[2]))
890             {
891                 name += 2;
892                 while ((*name == '\\') || (*name == '/')) name++;
893                 while ((p_l > root) && (*p_l != '/')) p_l--;
894                 while ((p_s > full->short_name + 2) && (*p_s != '\\')) p_s--;
895                 *p_l = *p_s = '\0';  /* Remove trailing separator */
896                 continue;
897             }
898         }
899
900         /* Make sure buffers are large enough */
901
902         if ((p_s >= full->short_name + sizeof(full->short_name) - 14) ||
903             (p_l >= full->long_name + sizeof(full->long_name) - 1))
904         {
905             SetLastError( ERROR_PATH_NOT_FOUND );
906             return FALSE;
907         }
908
909         /* Get the long and short name matching the file name */
910
911         if ((found = DOSFS_FindUnixName( full->long_name, name, p_l + 1,
912                          sizeof(full->long_name) - (p_l - full->long_name) - 1,
913                          p_s + 1, !(flags & DRIVE_CASE_SENSITIVE) )))
914         {
915             *p_l++ = '/';
916             p_l   += strlen(p_l);
917             *p_s++ = '\\';
918             p_s   += strlen(p_s);
919             while (!IS_END_OF_NAME(*name)) name++;
920         }
921         else if (!check_last)
922         {
923             *p_l++ = '/';
924             *p_s++ = '\\';
925             while (!IS_END_OF_NAME(*name) &&
926                    (p_s < full->short_name + sizeof(full->short_name) - 1) &&
927                    (p_l < full->long_name + sizeof(full->long_name) - 1))
928             {
929                 *p_s++ = tolower(*name);
930                 /* If the drive is case-sensitive we want to create new */
931                 /* files in lower-case otherwise we can't reopen them   */
932                 /* under the same short name. */
933                 if (flags & DRIVE_CASE_SENSITIVE) *p_l++ = tolower(*name);
934                 else *p_l++ = *name;
935                 name++;
936             }
937             /* Ignore trailing dots and spaces */
938             while(p_l[-1] == '.' || p_l[-1] == ' ') {
939                 --p_l;
940                 --p_s;
941             }
942             *p_l = *p_s = '\0';
943         }
944         while ((*name == '\\') || (*name == '/')) name++;
945     }
946
947     if (!found)
948     {
949         if (check_last)
950         {
951             SetLastError( ERROR_FILE_NOT_FOUND );
952             return FALSE;
953         }
954         if (*name)  /* Not last */
955         {
956             SetLastError( ERROR_PATH_NOT_FOUND );
957             return FALSE;
958         }
959     }
960     if (!full->long_name[0]) strcpy( full->long_name, "/" );
961     if (!full->short_name[2]) strcpy( full->short_name + 2, "\\" );
962     TRACE("returning %s = %s\n", full->long_name, full->short_name );
963     return TRUE;
964 }
965
966
967 /***********************************************************************
968  *           GetShortPathNameA   (KERNEL32.271)
969  *
970  * NOTES
971  *  observed:
972  *  longpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
973  *  *longpath="" or invalid: LastError=ERROR_BAD_PATHNAME, ret=0
974  * 
975  * more observations ( with NT 3.51 (WinDD) ):
976  * longpath <= 8.3 -> just copy longpath to shortpath
977  * longpath > 8.3  -> 
978  *             a) file does not exist -> return 0, LastError = ERROR_FILE_NOT_FOUND
979  *             b) file does exist     -> set the short filename.
980  * - trailing slashes are reproduced in the short name, even if the
981  *   file is not a directory
982  * - the absolute/relative path of the short name is reproduced like found
983  *   in the long name
984  * - longpath and shortpath may have the same adress
985  * Peter Ganten, 1999
986  */
987 DWORD WINAPI GetShortPathNameA( LPCSTR longpath, LPSTR shortpath,
988                                   DWORD shortlen )
989 {
990     DOS_FULL_NAME full_name;
991     LPSTR tmpshortpath;
992     DWORD sp = 0, lp = 0;
993     int tmplen, drive;
994     UINT flags;
995
996     TRACE("%s\n", debugstr_a(longpath));
997
998     if (!longpath) {
999       SetLastError(ERROR_INVALID_PARAMETER);
1000       return 0;
1001     }
1002     if (!longpath[0]) {
1003       SetLastError(ERROR_BAD_PATHNAME);
1004       return 0;
1005     }
1006
1007     if ( ( tmpshortpath = HeapAlloc ( GetProcessHeap(), 0, MAX_PATHNAME_LEN ) ) == NULL ) {
1008       SetLastError ( ERROR_NOT_ENOUGH_MEMORY );
1009       return 0;
1010     }
1011
1012     /* check for drive letter */
1013     if ( longpath[1] == ':' ) {
1014       tmpshortpath[0] = longpath[0];
1015       tmpshortpath[1] = ':';
1016       sp = 2;
1017     }
1018
1019     if ( ( drive = DOSFS_GetPathDrive ( &longpath )) == -1 ) return 0;
1020     flags = DRIVE_GetFlags ( drive );
1021
1022     while ( longpath[lp] ) {
1023
1024       /* check for path delimiters and reproduce them */
1025       if ( longpath[lp] == '\\' || longpath[lp] == '/' ) {
1026         if (!sp || tmpshortpath[sp-1]!= '\\') 
1027         {
1028             /* strip double "\\" */
1029             tmpshortpath[sp] = '\\';
1030             sp++;
1031         }
1032         tmpshortpath[sp]=0;/*terminate string*/
1033         lp++;
1034         continue;
1035       }
1036
1037       tmplen = strcspn ( longpath + lp, "\\/" ); 
1038       lstrcpynA ( tmpshortpath+sp, longpath + lp, tmplen+1 );
1039       
1040       /* Check, if the current element is a valid dos name */
1041       if ( DOSFS_ValidDOSName ( longpath + lp, !(flags & DRIVE_CASE_SENSITIVE) ) ) {
1042         sp += tmplen;
1043         lp += tmplen;
1044         continue;
1045       }
1046
1047       /* Check if the file exists and use the existing file name */
1048       if ( DOSFS_GetFullName ( tmpshortpath, TRUE, &full_name ) ) {
1049         strcpy( tmpshortpath+sp, strrchr ( full_name.short_name, '\\' ) + 1 );
1050         sp += strlen ( tmpshortpath+sp );
1051         lp += tmplen;
1052         continue;
1053       }
1054
1055       TRACE("not found!\n" );
1056       SetLastError ( ERROR_FILE_NOT_FOUND );
1057       return 0;
1058     }
1059     tmpshortpath[sp] = 0;
1060
1061     lstrcpynA ( shortpath, tmpshortpath, shortlen );
1062     TRACE("returning %s\n", debugstr_a(shortpath) );
1063     tmplen = strlen ( tmpshortpath );
1064     HeapFree ( GetProcessHeap(), 0, tmpshortpath );
1065     
1066     return tmplen;
1067 }
1068
1069
1070 /***********************************************************************
1071  *           GetShortPathNameW   (KERNEL32.272)
1072  */
1073 DWORD WINAPI GetShortPathNameW( LPCWSTR longpath, LPWSTR shortpath,
1074                                   DWORD shortlen )
1075 {
1076     LPSTR longpathA, shortpathA;
1077     DWORD ret = 0;
1078
1079     longpathA = HEAP_strdupWtoA( GetProcessHeap(), 0, longpath );
1080     shortpathA = HeapAlloc ( GetProcessHeap(), 0, shortlen );
1081
1082     ret = GetShortPathNameA ( longpathA, shortpathA, shortlen );
1083     lstrcpynAtoW ( shortpath, shortpathA, shortlen );
1084
1085     HeapFree( GetProcessHeap(), 0, longpathA );
1086     HeapFree( GetProcessHeap(), 0, shortpathA );
1087
1088     return ret;
1089 }
1090
1091
1092 /***********************************************************************
1093  *           GetLongPathNameA   (KERNEL32.xxx)
1094  */
1095 DWORD WINAPI GetLongPathNameA( LPCSTR shortpath, LPSTR longpath,
1096                                   DWORD longlen )
1097 {
1098     DOS_FULL_NAME full_name;
1099     char *p, *r, *ll, *ss;
1100     
1101     if (!DOSFS_GetFullName( shortpath, TRUE, &full_name )) return 0;
1102     lstrcpynA( longpath, full_name.short_name, longlen );
1103
1104     /* Do some hackery to get the long filename. */
1105
1106     if (longpath) {
1107      ss=longpath+strlen(longpath);
1108      ll=full_name.long_name+strlen(full_name.long_name);
1109      p=NULL;
1110      while (ss>=longpath)
1111      {
1112        /* FIXME: aren't we more paranoid, than needed? */
1113        while ((ss[0]=='\\') && (ss>=longpath)) ss--;
1114        p=ss;
1115        while ((ss[0]!='\\') && (ss>=longpath)) ss--;
1116        if (ss>=longpath) 
1117          {
1118          /* FIXME: aren't we more paranoid, than needed? */
1119          while ((ll[0]=='/') && (ll>=full_name.long_name)) ll--;
1120          while ((ll[0]!='/') && (ll>=full_name.long_name)) ll--;
1121          if (ll<full_name.long_name) 
1122               { 
1123               ERR("Bad longname! (ss=%s ll=%s)\n This should never happen !\n"
1124                   ,ss ,ll ); 
1125               return 0;
1126               }
1127          }
1128      }
1129
1130    /* FIXME: fix for names like "C:\\" (ie. with more '\'s) */
1131       if (p && p[2]) 
1132         {
1133         p+=1;
1134         if ((p-longpath)>0) longlen -= (p-longpath);
1135         lstrcpynA( p, ll , longlen);
1136
1137         /* Now, change all '/' to '\' */
1138         for (r=p; r<(p+longlen); r++ ) 
1139           if (r[0]=='/') r[0]='\\';
1140         return strlen(longpath) - strlen(p) + longlen;
1141         }
1142     }
1143
1144     return strlen(longpath);
1145 }
1146
1147
1148 /***********************************************************************
1149  *           GetLongPathNameW   (KERNEL32.269)
1150  */
1151 DWORD WINAPI GetLongPathNameW( LPCWSTR shortpath, LPWSTR longpath,
1152                                   DWORD longlen )
1153 {
1154     DOS_FULL_NAME full_name;
1155     DWORD ret = 0;
1156     LPSTR shortpathA = HEAP_strdupWtoA( GetProcessHeap(), 0, shortpath );
1157
1158     /* FIXME: is it correct to always return a fully qualified short path? */
1159     if (DOSFS_GetFullName( shortpathA, TRUE, &full_name ))
1160     {
1161         ret = strlen( full_name.short_name );
1162         lstrcpynAtoW( longpath, full_name.long_name, longlen );
1163     }
1164     HeapFree( GetProcessHeap(), 0, shortpathA );
1165     return ret;
1166 }
1167
1168
1169 /***********************************************************************
1170  *           DOSFS_DoGetFullPathName
1171  *
1172  * Implementation of GetFullPathNameA/W.
1173  *
1174  * bon@elektron 000331:
1175  * A test for GetFullPathName with many patholotical case 
1176  * gives now identical output for Wine and OSR2
1177  */
1178 static DWORD DOSFS_DoGetFullPathName( LPCSTR name, DWORD len, LPSTR result,
1179                                       BOOL unicode )
1180 {
1181     DWORD ret;
1182     DOS_FULL_NAME full_name;
1183     char *p,*q;
1184     const char * root;
1185     char drivecur[]="c:.";
1186     char driveletter=0;
1187     int namelen,drive=0;
1188
1189     if ((strlen(name) >1)&& (name[1]==':'))
1190       /*drive letter given */
1191       {
1192         driveletter = name[0];
1193       }
1194     if ((strlen(name) >2)&& (name[1]==':') &&
1195              ((name[2]=='\\') || (name[2]=='/')))
1196       /*absolute path given */
1197       {
1198         lstrcpynA(full_name.short_name,name,MAX_PATHNAME_LEN);
1199         drive = (int)toupper(name[0]) - 'A';
1200       }
1201     else
1202       {
1203         if (driveletter)
1204           drivecur[0]=driveletter;
1205         else
1206           strcpy(drivecur,".");
1207         if (!DOSFS_GetFullName( drivecur, FALSE, &full_name ))
1208           {
1209             FIXME("internal: error getting drive/path\n");
1210             return 0;
1211           }
1212         /* find path that drive letter substitutes*/
1213         drive = (int)toupper(full_name.short_name[0]) -0x41;
1214         root= DRIVE_GetRoot(drive);
1215         if (!root)
1216           {
1217             FIXME("internal: error getting DOS Drive Root\n");
1218             return 0;
1219           }
1220         if (!strcmp(root,"/"))
1221           {
1222             /* we have just the last / and we need it. */
1223             p= full_name.long_name;
1224           }
1225         else
1226           {
1227             p= full_name.long_name +strlen(root);
1228           }
1229         /* append long name (= unix name) to drive */
1230         lstrcpynA(full_name.short_name+2,p,MAX_PATHNAME_LEN-3);
1231         /* append name to treat */
1232         namelen= strlen(full_name.short_name);
1233         p = (char*)name;
1234         if (driveletter)
1235           p += +2; /* skip drive name when appending */
1236         if (namelen +2  + strlen(p) > MAX_PATHNAME_LEN)
1237           {
1238             FIXME("internal error: buffer too small\n");
1239              return 0;
1240           }
1241         full_name.short_name[namelen++] ='\\';
1242         full_name.short_name[namelen] = 0;
1243         lstrcpynA(full_name.short_name +namelen,p,MAX_PATHNAME_LEN-namelen);
1244       }
1245     /* reverse all slashes */
1246     for (p=full_name.short_name;
1247          p < full_name.short_name+strlen(full_name.short_name);
1248          p++)
1249       {
1250         if ( *p == '/' )
1251           *p = '\\';
1252       }
1253      /* Use memmove, as areas overlap*/
1254      /* Delete .. */
1255     while ((p = strstr(full_name.short_name,"\\..\\")))
1256       {
1257         if (p > full_name.short_name+2)
1258           {
1259             *p = 0;
1260             q = strrchr(full_name.short_name,'\\');
1261             memmove(q+1,p+4,strlen(p+4)+1);
1262           }
1263         else
1264           {
1265             memmove(full_name.short_name+3,p+4,strlen(p+4)+1);
1266           }
1267       }
1268     if ((full_name.short_name[2]=='.')&&(full_name.short_name[3]=='.'))
1269         {
1270           /* This case istn't treated yet : c:..\test */
1271           memmove(full_name.short_name+2,full_name.short_name+4,
1272                   strlen(full_name.short_name+4)+1);
1273         }
1274      /* Delete . */
1275     while ((p = strstr(full_name.short_name,"\\.\\")))
1276       {
1277         *(p+1) = 0;
1278         memmove(p+1,p+3,strlen(p+3)+1);
1279       }
1280     if (!(DRIVE_GetFlags(drive) & DRIVE_CASE_PRESERVING))
1281       _strupr( full_name.short_name );
1282     namelen=strlen(full_name.short_name);
1283     if (!strcmp(full_name.short_name+namelen-3,"\\.."))
1284         {
1285           /* one more starnge case: "c:\test\test1\.." 
1286            return "c:\test"*/
1287           *(full_name.short_name+namelen-3)=0;
1288           q = strrchr(full_name.short_name,'\\');
1289           *q =0;
1290         }
1291     if (full_name.short_name[namelen-1]=='.')
1292         full_name.short_name[(namelen--)-1] =0;
1293     if (!driveletter)
1294       if (full_name.short_name[namelen-1]=='\\')
1295         full_name.short_name[(namelen--)-1] =0;
1296     TRACE("got %s\n",full_name.short_name);
1297
1298     /* If the lpBuffer buffer is too small, the return value is the 
1299     size of the buffer, in characters, required to hold the path 
1300     plus the terminating \0 (tested against win95osr, bon 001118)
1301     . */
1302     ret = strlen(full_name.short_name);
1303     if (ret >= len )
1304       {
1305         /* don't touch anything when the buffer is not large enough */
1306         SetLastError( ERROR_INSUFFICIENT_BUFFER );
1307         return ret+1;
1308       }
1309     if (result)
1310     {
1311         if (unicode)
1312             lstrcpynAtoW( (LPWSTR)result, full_name.short_name, len );
1313         else
1314             lstrcpynA( result, full_name.short_name, len );
1315     }
1316
1317     TRACE("returning '%s'\n", full_name.short_name );
1318     return ret;
1319 }
1320
1321
1322 /***********************************************************************
1323  *           GetFullPathNameA   (KERNEL32.272)
1324  * NOTES
1325  *   if the path closed with '\', *lastpart is 0 
1326  */
1327 DWORD WINAPI GetFullPathNameA( LPCSTR name, DWORD len, LPSTR buffer,
1328                                  LPSTR *lastpart )
1329 {
1330     DWORD ret = DOSFS_DoGetFullPathName( name, len, buffer, FALSE );
1331     if (ret && (ret<=len) && buffer && lastpart)
1332     {
1333         LPSTR p = buffer + strlen(buffer);
1334
1335         if (*p != '\\')
1336         {
1337           while ((p > buffer + 2) && (*p != '\\')) p--;
1338           *lastpart = p + 1;
1339         }
1340         else *lastpart = NULL;
1341     }
1342     return ret;
1343 }
1344
1345
1346 /***********************************************************************
1347  *           GetFullPathNameW   (KERNEL32.273)
1348  */
1349 DWORD WINAPI GetFullPathNameW( LPCWSTR name, DWORD len, LPWSTR buffer,
1350                                  LPWSTR *lastpart )
1351 {
1352     LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
1353     DWORD ret = DOSFS_DoGetFullPathName( nameA, len, (LPSTR)buffer, TRUE );
1354     HeapFree( GetProcessHeap(), 0, nameA );
1355     if (ret && (ret<=len) && buffer && lastpart)
1356     {
1357         LPWSTR p = buffer + strlenW(buffer);
1358         if (*p != (WCHAR)'\\')
1359         {
1360             while ((p > buffer + 2) && (*p != (WCHAR)'\\')) p--;
1361             *lastpart = p + 1;
1362         }
1363         else *lastpart = NULL;  
1364     }
1365     return ret;
1366 }
1367
1368 /***********************************************************************
1369  *           DOSFS_FindNextEx
1370  */
1371 static int DOSFS_FindNextEx( FIND_FIRST_INFO *info, WIN32_FIND_DATAA *entry )
1372 {
1373     DWORD attr = info->attr | FA_UNUSED | FA_ARCHIVE | FA_RDONLY | FILE_ATTRIBUTE_SYMLINK;
1374     UINT flags = DRIVE_GetFlags( info->drive );
1375     char *p, buffer[MAX_PATHNAME_LEN];
1376     const char *drive_path;
1377     int drive_root;
1378     LPCSTR long_name, short_name;
1379     BY_HANDLE_FILE_INFORMATION fileinfo;
1380     char dos_name[13];
1381
1382     if ((info->attr & ~(FA_UNUSED | FA_ARCHIVE | FA_RDONLY)) == FA_LABEL)
1383     {
1384         if (info->cur_pos) return 0;
1385         entry->dwFileAttributes  = FILE_ATTRIBUTE_LABEL;
1386         RtlSecondsSince1970ToTime( (time_t)0, &entry->ftCreationTime );
1387         RtlSecondsSince1970ToTime( (time_t)0, &entry->ftLastAccessTime );
1388         RtlSecondsSince1970ToTime( (time_t)0, &entry->ftLastWriteTime );
1389         entry->nFileSizeHigh     = 0;
1390         entry->nFileSizeLow      = 0;
1391         entry->dwReserved0       = 0;
1392         entry->dwReserved1       = 0;
1393         DOSFS_ToDosDTAFormat( DRIVE_GetLabel( info->drive ), entry->cFileName );
1394         strcpy( entry->cAlternateFileName, entry->cFileName ); 
1395         info->cur_pos++;
1396         TRACE("returning %s (%s) as label\n",
1397                entry->cFileName, entry->cAlternateFileName);
1398         return 1;
1399     }
1400
1401     drive_path = info->path + strlen(DRIVE_GetRoot( info->drive ));
1402     while ((*drive_path == '/') || (*drive_path == '\\')) drive_path++;
1403     drive_root = !*drive_path;
1404
1405     lstrcpynA( buffer, info->path, sizeof(buffer) - 1 );
1406     strcat( buffer, "/" );
1407     p = buffer + strlen(buffer);
1408
1409     while (DOSFS_ReadDir( info->dir, &long_name, &short_name ))
1410     {
1411         info->cur_pos++;
1412
1413         /* Don't return '.' and '..' in the root of the drive */
1414         if (drive_root && (long_name[0] == '.') &&
1415             (!long_name[1] || ((long_name[1] == '.') && !long_name[2])))
1416             continue;
1417
1418         /* Check the long mask */
1419
1420         if (info->long_mask)
1421         {
1422             if (!DOSFS_MatchLong( info->long_mask, long_name,
1423                                   flags & DRIVE_CASE_SENSITIVE )) continue;
1424         }
1425
1426         /* Check the short mask */
1427
1428         if (info->short_mask)
1429         {
1430             if (!short_name)
1431             {
1432                 DOSFS_Hash( long_name, dos_name, TRUE,
1433                             !(flags & DRIVE_CASE_SENSITIVE) );
1434                 short_name = dos_name;
1435             }
1436             if (!DOSFS_MatchShort( info->short_mask, short_name )) continue;
1437         }
1438
1439         /* Check the file attributes */
1440
1441         lstrcpynA( p, long_name, sizeof(buffer) - (int)(p - buffer) );
1442         if (!FILE_Stat( buffer, &fileinfo ))
1443         {
1444             WARN("can't stat %s\n", buffer);
1445             continue;
1446         }
1447         if ((fileinfo.dwFileAttributes & FILE_ATTRIBUTE_SYMLINK) &&
1448             (fileinfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
1449         {
1450             static int show_dir_symlinks = -1;
1451             if (show_dir_symlinks == -1)
1452                 show_dir_symlinks = PROFILE_GetWineIniBool("wine", "ShowDirSymlinks", 0);
1453             if (!show_dir_symlinks) continue;
1454         }
1455
1456         if (fileinfo.dwFileAttributes & ~attr) continue;
1457
1458         /* We now have a matching entry; fill the result and return */
1459
1460         entry->dwFileAttributes = fileinfo.dwFileAttributes;
1461         entry->ftCreationTime   = fileinfo.ftCreationTime;
1462         entry->ftLastAccessTime = fileinfo.ftLastAccessTime;
1463         entry->ftLastWriteTime  = fileinfo.ftLastWriteTime;
1464         entry->nFileSizeHigh    = fileinfo.nFileSizeHigh;
1465         entry->nFileSizeLow     = fileinfo.nFileSizeLow;
1466
1467         if (short_name)
1468             DOSFS_ToDosDTAFormat( short_name, entry->cAlternateFileName );
1469         else
1470             DOSFS_Hash( long_name, entry->cAlternateFileName, FALSE,
1471                         !(flags & DRIVE_CASE_SENSITIVE) );
1472
1473         lstrcpynA( entry->cFileName, long_name, sizeof(entry->cFileName) );
1474         if (!(flags & DRIVE_CASE_PRESERVING)) _strlwr( entry->cFileName );
1475         TRACE("returning %s (%s) %02lx %ld\n",
1476               entry->cFileName, entry->cAlternateFileName,
1477               entry->dwFileAttributes, entry->nFileSizeLow );
1478         return 1;
1479     }
1480     return 0;  /* End of directory */
1481 }
1482
1483 /***********************************************************************
1484  *           DOSFS_FindNext
1485  *
1486  * Find the next matching file. Return the number of entries read to find
1487  * the matching one, or 0 if no more entries.
1488  * 'short_mask' is the 8.3 mask (in FCB format), 'long_mask' is the long
1489  * file name mask. Either or both can be NULL.
1490  *
1491  * NOTE: This is supposed to be only called by the int21 emulation
1492  *       routines. Thus, we should own the Win16Mutex anyway.
1493  *       Nevertheless, we explicitly enter it to ensure the static
1494  *       directory cache is protected.
1495  */
1496 int DOSFS_FindNext( const char *path, const char *short_mask,
1497                     const char *long_mask, int drive, BYTE attr,
1498                     int skip, WIN32_FIND_DATAA *entry )
1499 {
1500     static FIND_FIRST_INFO info;
1501     LPCSTR short_name, long_name;
1502     int count;
1503
1504     SYSLEVEL_EnterWin16Lock();
1505
1506     /* Check the cached directory */
1507     if (!(info.dir && info.path == path && info.short_mask == short_mask
1508                    && info.long_mask == long_mask && info.drive == drive
1509                    && info.attr == attr && info.cur_pos <= skip))
1510     {  
1511         /* Not in the cache, open it anew */
1512         if (info.dir) DOSFS_CloseDir( info.dir );
1513
1514         info.path = (LPSTR)path;
1515         info.long_mask = (LPSTR)long_mask;
1516         info.short_mask = (LPSTR)short_mask;
1517         info.attr = attr;
1518         info.drive = drive;
1519         info.cur_pos = 0;
1520         info.dir = DOSFS_OpenDir( info.path );
1521     }
1522
1523     /* Skip to desired position */
1524     while (info.cur_pos < skip)
1525         if (info.dir && DOSFS_ReadDir( info.dir, &long_name, &short_name ))
1526             info.cur_pos++;
1527         else
1528             break;
1529
1530     if (info.dir && info.cur_pos == skip && DOSFS_FindNextEx( &info, entry ))
1531         count = info.cur_pos - skip;
1532     else
1533         count = 0;
1534
1535     if (!count)
1536     {
1537         if (info.dir) DOSFS_CloseDir( info.dir );
1538         memset( &info, '\0', sizeof(info) );
1539     }
1540
1541     SYSLEVEL_LeaveWin16Lock();
1542
1543     return count;
1544 }
1545
1546 /*************************************************************************
1547  *           FindFirstFileExA  (KERNEL32)
1548  */
1549 HANDLE WINAPI FindFirstFileExA(
1550         LPCSTR lpFileName,
1551         FINDEX_INFO_LEVELS fInfoLevelId,
1552         LPVOID lpFindFileData,
1553         FINDEX_SEARCH_OPS fSearchOp,
1554         LPVOID lpSearchFilter,
1555         DWORD dwAdditionalFlags)
1556 {
1557     DOS_FULL_NAME full_name;
1558     HGLOBAL handle;
1559     FIND_FIRST_INFO *info;
1560     
1561     if ((fSearchOp != FindExSearchNameMatch) || (dwAdditionalFlags != 0))
1562     {
1563         FIXME("options not implemented 0x%08x 0x%08lx\n", fSearchOp, dwAdditionalFlags );
1564         return INVALID_HANDLE_VALUE;
1565     }
1566
1567     switch(fInfoLevelId)
1568     {
1569       case FindExInfoStandard:
1570         {
1571           WIN32_FIND_DATAA * data = (WIN32_FIND_DATAA *) lpFindFileData;
1572           data->dwReserved0 = data->dwReserved1 = 0x0;
1573           if (!lpFileName) return 0;
1574           if (!DOSFS_GetFullName( lpFileName, FALSE, &full_name )) break;
1575           if (!(handle = GlobalAlloc(GMEM_MOVEABLE, sizeof(FIND_FIRST_INFO)))) break;
1576           info = (FIND_FIRST_INFO *)GlobalLock( handle );
1577           info->path = HEAP_strdupA( GetProcessHeap(), 0, full_name.long_name );
1578           info->long_mask = strrchr( info->path, '/' );
1579           *(info->long_mask++) = '\0';
1580           info->short_mask = NULL;
1581           info->attr = 0xff;
1582           if (lpFileName[0] && (lpFileName[1] == ':'))
1583               info->drive = toupper(*lpFileName) - 'A';
1584           else info->drive = DRIVE_GetCurrentDrive();
1585           info->cur_pos = 0;
1586
1587           info->dir = DOSFS_OpenDir( info->path );
1588
1589           GlobalUnlock( handle );
1590           if (!FindNextFileA( handle, data ))
1591           {
1592               FindClose( handle );
1593               SetLastError( ERROR_NO_MORE_FILES );
1594               break;
1595           }
1596           return handle;
1597         }
1598         break;
1599       default:
1600         FIXME("fInfoLevelId 0x%08x not implemented\n", fInfoLevelId );
1601     }
1602     return INVALID_HANDLE_VALUE;
1603 }
1604
1605 /*************************************************************************
1606  *           FindFirstFileA   (KERNEL32.123)
1607  */
1608 HANDLE WINAPI FindFirstFileA(
1609         LPCSTR lpFileName,
1610         WIN32_FIND_DATAA *lpFindData )
1611 {
1612     return FindFirstFileExA(lpFileName, FindExInfoStandard, lpFindData,
1613                             FindExSearchNameMatch, NULL, 0);
1614 }
1615
1616 /*************************************************************************
1617  *           FindFirstFileExW   (KERNEL32)
1618  */
1619 HANDLE WINAPI FindFirstFileExW(
1620         LPCWSTR lpFileName,
1621         FINDEX_INFO_LEVELS fInfoLevelId,
1622         LPVOID lpFindFileData,
1623         FINDEX_SEARCH_OPS fSearchOp,
1624         LPVOID lpSearchFilter,
1625         DWORD dwAdditionalFlags)
1626 {
1627     HANDLE handle;
1628     WIN32_FIND_DATAA dataA;
1629     LPVOID _lpFindFileData;
1630     LPSTR pathA;
1631
1632     switch(fInfoLevelId)
1633     {
1634       case FindExInfoStandard:
1635         {
1636           _lpFindFileData = &dataA;
1637         }
1638         break;
1639       default:
1640         FIXME("fInfoLevelId 0x%08x not implemented\n", fInfoLevelId );
1641         return INVALID_HANDLE_VALUE;
1642     }
1643
1644     pathA = HEAP_strdupWtoA( GetProcessHeap(), 0, lpFileName );
1645     handle = FindFirstFileExA(pathA, fInfoLevelId, _lpFindFileData, fSearchOp, lpSearchFilter, dwAdditionalFlags);
1646     HeapFree( GetProcessHeap(), 0, pathA );
1647     if (handle == INVALID_HANDLE_VALUE) return handle;
1648     
1649     switch(fInfoLevelId)
1650     {
1651       case FindExInfoStandard:
1652         {
1653           WIN32_FIND_DATAW *dataW = (WIN32_FIND_DATAW*) lpFindFileData;
1654           dataW->dwFileAttributes = dataA.dwFileAttributes;
1655           dataW->ftCreationTime   = dataA.ftCreationTime;
1656           dataW->ftLastAccessTime = dataA.ftLastAccessTime;
1657           dataW->ftLastWriteTime  = dataA.ftLastWriteTime;
1658           dataW->nFileSizeHigh    = dataA.nFileSizeHigh;
1659           dataW->nFileSizeLow     = dataA.nFileSizeLow;
1660           MultiByteToWideChar( CP_ACP, 0, dataA.cFileName, -1,
1661                                dataW->cFileName, sizeof(dataW->cFileName)/sizeof(WCHAR) );
1662           MultiByteToWideChar( CP_ACP, 0, dataA.cAlternateFileName, -1,
1663                                dataW->cAlternateFileName,
1664                                sizeof(dataW->cAlternateFileName)/sizeof(WCHAR) );
1665         }
1666         break;
1667       default:
1668         FIXME("fInfoLevelId 0x%08x not implemented\n", fInfoLevelId );
1669         return INVALID_HANDLE_VALUE;
1670     }
1671     return handle;
1672 }
1673
1674 /*************************************************************************
1675  *           FindFirstFileW   (KERNEL32.124)
1676  */
1677 HANDLE WINAPI FindFirstFileW( LPCWSTR lpFileName, WIN32_FIND_DATAW *lpFindData )
1678 {
1679     return FindFirstFileExW(lpFileName, FindExInfoStandard, lpFindData,
1680                             FindExSearchNameMatch, NULL, 0);
1681 }
1682
1683 /*************************************************************************
1684  *           FindNextFileA   (KERNEL32.126)
1685  */
1686 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
1687 {
1688     FIND_FIRST_INFO *info;
1689
1690     if ((handle == INVALID_HANDLE_VALUE) || 
1691        !(info = (FIND_FIRST_INFO *)GlobalLock( handle )))
1692     {
1693         SetLastError( ERROR_INVALID_HANDLE );
1694         return FALSE;
1695     }
1696     GlobalUnlock( handle );
1697     if (!info->path || !info->dir)
1698     {
1699         SetLastError( ERROR_NO_MORE_FILES );
1700         return FALSE;
1701     }
1702     if (!DOSFS_FindNextEx( info, data ))
1703     {
1704         DOSFS_CloseDir( info->dir ); info->dir = NULL;
1705         HeapFree( GetProcessHeap(), 0, info->path );
1706         info->path = info->long_mask = NULL;
1707         SetLastError( ERROR_NO_MORE_FILES );
1708         return FALSE;
1709     }
1710     return TRUE;
1711 }
1712
1713
1714 /*************************************************************************
1715  *           FindNextFileW   (KERNEL32.127)
1716  */
1717 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1718 {
1719     WIN32_FIND_DATAA dataA;
1720     if (!FindNextFileA( handle, &dataA )) return FALSE;
1721     data->dwFileAttributes = dataA.dwFileAttributes;
1722     data->ftCreationTime   = dataA.ftCreationTime;
1723     data->ftLastAccessTime = dataA.ftLastAccessTime;
1724     data->ftLastWriteTime  = dataA.ftLastWriteTime;
1725     data->nFileSizeHigh    = dataA.nFileSizeHigh;
1726     data->nFileSizeLow     = dataA.nFileSizeLow;
1727     MultiByteToWideChar( CP_ACP, 0, dataA.cFileName, -1,
1728                          data->cFileName, sizeof(data->cFileName)/sizeof(WCHAR) );
1729     MultiByteToWideChar( CP_ACP, 0, dataA.cAlternateFileName, -1,
1730                          data->cAlternateFileName,
1731                          sizeof(data->cAlternateFileName)/sizeof(WCHAR) );
1732     return TRUE;
1733 }
1734
1735 /*************************************************************************
1736  *           FindClose   (KERNEL32.119)
1737  */
1738 BOOL WINAPI FindClose( HANDLE handle )
1739 {
1740     FIND_FIRST_INFO *info;
1741
1742     if ((handle == INVALID_HANDLE_VALUE) ||
1743         !(info = (FIND_FIRST_INFO *)GlobalLock( handle )))
1744     {
1745         SetLastError( ERROR_INVALID_HANDLE );
1746         return FALSE;
1747     }
1748     if (info->dir) DOSFS_CloseDir( info->dir );
1749     if (info->path) HeapFree( GetProcessHeap(), 0, info->path );
1750     GlobalUnlock( handle );
1751     GlobalFree( handle );
1752     return TRUE;
1753 }
1754
1755 /***********************************************************************
1756  *           DOSFS_UnixTimeToFileTime
1757  *
1758  * Convert a Unix time to FILETIME format.
1759  * The FILETIME structure is a 64-bit value representing the number of
1760  * 100-nanosecond intervals since January 1, 1601, 0:00.
1761  * 'remainder' is the nonnegative number of 100-ns intervals
1762  * corresponding to the time fraction smaller than 1 second that
1763  * couldn't be stored in the time_t value.
1764  */
1765 void DOSFS_UnixTimeToFileTime( time_t unix_time, FILETIME *filetime,
1766                                DWORD remainder )
1767 {
1768     /* NOTES:
1769
1770        CONSTANTS: 
1771        The time difference between 1 January 1601, 00:00:00 and
1772        1 January 1970, 00:00:00 is 369 years, plus the leap years
1773        from 1604 to 1968, excluding 1700, 1800, 1900.
1774        This makes (1968 - 1600) / 4 - 3 = 89 leap days, and a total
1775        of 134774 days.
1776
1777        Any day in that period had 24 * 60 * 60 = 86400 seconds.
1778
1779        The time difference is 134774 * 86400 * 10000000, which can be written
1780        116444736000000000
1781        27111902 * 2^32 + 3577643008
1782        413 * 2^48 + 45534 * 2^32 + 54590 * 2^16 + 32768
1783
1784        If you find that these constants are buggy, please change them in all
1785        instances in both conversion functions.
1786
1787        VERSIONS:
1788        There are two versions, one of them uses long long variables and
1789        is presumably faster but not ISO C. The other one uses standard C
1790        data types and operations but relies on the assumption that negative
1791        numbers are stored as 2's complement (-1 is 0xffff....). If this
1792        assumption is violated, dates before 1970 will not convert correctly.
1793        This should however work on any reasonable architecture where WINE
1794        will run.
1795
1796        DETAILS:
1797        
1798        Take care not to remove the casts. I have tested these functions
1799        (in both versions) for a lot of numbers. I would be interested in
1800        results on other compilers than GCC.
1801
1802        The operations have been designed to account for the possibility
1803        of 64-bit time_t in future UNICES. Even the versions without
1804        internal long long numbers will work if time_t only is 64 bit.
1805        A 32-bit shift, which was necessary for that operation, turned out
1806        not to work correctly in GCC, besides giving the warning. So I
1807        used a double 16-bit shift instead. Numbers are in the ISO version
1808        represented by three limbs, the most significant with 32 bit, the
1809        other two with 16 bit each.
1810
1811        As the modulo-operator % is not well-defined for negative numbers,
1812        negative divisors have been avoided in DOSFS_FileTimeToUnixTime.
1813
1814        There might be quicker ways to do this in C. Certainly so in
1815        assembler.
1816
1817        Claus Fischer, fischer@iue.tuwien.ac.at
1818        */
1819
1820 #if SIZEOF_LONG_LONG >= 8
1821 #  define USE_LONG_LONG 1
1822 #else
1823 #  define USE_LONG_LONG 0
1824 #endif
1825
1826 #if USE_LONG_LONG               /* gcc supports long long type */
1827
1828     long long int t = unix_time;
1829     t *= 10000000;
1830     t += 116444736000000000LL;
1831     t += remainder;
1832     filetime->dwLowDateTime  = (UINT)t;
1833     filetime->dwHighDateTime = (UINT)(t >> 32);
1834
1835 #else  /* ISO version */
1836
1837     UINT a0;                    /* 16 bit, low    bits */
1838     UINT a1;                    /* 16 bit, medium bits */
1839     UINT a2;                    /* 32 bit, high   bits */
1840
1841     /* Copy the unix time to a2/a1/a0 */
1842     a0 =  unix_time & 0xffff;
1843     a1 = (unix_time >> 16) & 0xffff;
1844     /* This is obsolete if unix_time is only 32 bits, but it does not hurt.
1845        Do not replace this by >> 32, it gives a compiler warning and it does
1846        not work. */
1847     a2 = (unix_time >= 0 ? (unix_time >> 16) >> 16 :
1848           ~((~unix_time >> 16) >> 16));
1849
1850     /* Multiply a by 10000000 (a = a2/a1/a0)
1851        Split the factor into 10000 * 1000 which are both less than 0xffff. */
1852     a0 *= 10000;
1853     a1 = a1 * 10000 + (a0 >> 16);
1854     a2 = a2 * 10000 + (a1 >> 16);
1855     a0 &= 0xffff;
1856     a1 &= 0xffff;
1857
1858     a0 *= 1000;
1859     a1 = a1 * 1000 + (a0 >> 16);
1860     a2 = a2 * 1000 + (a1 >> 16);
1861     a0 &= 0xffff;
1862     a1 &= 0xffff;
1863
1864     /* Add the time difference and the remainder */
1865     a0 += 32768 + (remainder & 0xffff);
1866     a1 += 54590 + (remainder >> 16   ) + (a0 >> 16);
1867     a2 += 27111902                     + (a1 >> 16);
1868     a0 &= 0xffff;
1869     a1 &= 0xffff;
1870
1871     /* Set filetime */
1872     filetime->dwLowDateTime  = (a1 << 16) + a0;
1873     filetime->dwHighDateTime = a2;
1874 #endif
1875 }
1876
1877
1878 /***********************************************************************
1879  *           DOSFS_FileTimeToUnixTime
1880  *
1881  * Convert a FILETIME format to Unix time.
1882  * If not NULL, 'remainder' contains the fractional part of the filetime,
1883  * in the range of [0..9999999] (even if time_t is negative).
1884  */
1885 time_t DOSFS_FileTimeToUnixTime( const FILETIME *filetime, DWORD *remainder )
1886 {
1887     /* Read the comment in the function DOSFS_UnixTimeToFileTime. */
1888 #if USE_LONG_LONG
1889
1890     long long int t = filetime->dwHighDateTime;
1891     t <<= 32;
1892     t += (UINT)filetime->dwLowDateTime;
1893     t -= 116444736000000000LL;
1894     if (t < 0)
1895     {
1896         if (remainder) *remainder = 9999999 - (-t - 1) % 10000000;
1897         return -1 - ((-t - 1) / 10000000);
1898     }
1899     else
1900     {
1901         if (remainder) *remainder = t % 10000000;
1902         return t / 10000000;
1903     }
1904
1905 #else  /* ISO version */
1906
1907     UINT a0;                    /* 16 bit, low    bits */
1908     UINT a1;                    /* 16 bit, medium bits */
1909     UINT a2;                    /* 32 bit, high   bits */
1910     UINT r;                     /* remainder of division */
1911     unsigned int carry;         /* carry bit for subtraction */
1912     int negative;               /* whether a represents a negative value */
1913
1914     /* Copy the time values to a2/a1/a0 */
1915     a2 =  (UINT)filetime->dwHighDateTime;
1916     a1 = ((UINT)filetime->dwLowDateTime ) >> 16;
1917     a0 = ((UINT)filetime->dwLowDateTime ) & 0xffff;
1918
1919     /* Subtract the time difference */
1920     if (a0 >= 32768           ) a0 -=             32768        , carry = 0;
1921     else                        a0 += (1 << 16) - 32768        , carry = 1;
1922
1923     if (a1 >= 54590    + carry) a1 -=             54590 + carry, carry = 0;
1924     else                        a1 += (1 << 16) - 54590 - carry, carry = 1;
1925
1926     a2 -= 27111902 + carry;
1927     
1928     /* If a is negative, replace a by (-1-a) */
1929     negative = (a2 >= ((UINT)1) << 31);
1930     if (negative)
1931     {
1932         /* Set a to -a - 1 (a is a2/a1/a0) */
1933         a0 = 0xffff - a0;
1934         a1 = 0xffff - a1;
1935         a2 = ~a2;
1936     }
1937
1938     /* Divide a by 10000000 (a = a2/a1/a0), put the rest into r.
1939        Split the divisor into 10000 * 1000 which are both less than 0xffff. */
1940     a1 += (a2 % 10000) << 16;
1941     a2 /=       10000;
1942     a0 += (a1 % 10000) << 16;
1943     a1 /=       10000;
1944     r   =  a0 % 10000;
1945     a0 /=       10000;
1946
1947     a1 += (a2 % 1000) << 16;
1948     a2 /=       1000;
1949     a0 += (a1 % 1000) << 16;
1950     a1 /=       1000;
1951     r  += (a0 % 1000) * 10000;
1952     a0 /=       1000;
1953
1954     /* If a was negative, replace a by (-1-a) and r by (9999999 - r) */
1955     if (negative)
1956     {
1957         /* Set a to -a - 1 (a is a2/a1/a0) */
1958         a0 = 0xffff - a0;
1959         a1 = 0xffff - a1;
1960         a2 = ~a2;
1961
1962         r  = 9999999 - r;
1963     }
1964
1965     if (remainder) *remainder = r;
1966
1967     /* Do not replace this by << 32, it gives a compiler warning and it does
1968        not work. */
1969     return ((((time_t)a2) << 16) << 16) + (a1 << 16) + a0;
1970 #endif
1971 }
1972
1973
1974 /***********************************************************************
1975  *           MulDiv   (KERNEL32.391)
1976  * RETURNS
1977  *      Result of multiplication and division
1978  *      -1: Overflow occurred or Divisor was 0
1979  */
1980 INT WINAPI MulDiv(
1981              INT nMultiplicand, 
1982              INT nMultiplier,
1983              INT nDivisor)
1984 {
1985 #if SIZEOF_LONG_LONG >= 8
1986     long long ret;
1987
1988     if (!nDivisor) return -1;
1989
1990     /* We want to deal with a positive divisor to simplify the logic. */
1991     if (nDivisor < 0)
1992     {
1993       nMultiplicand = - nMultiplicand;
1994       nDivisor = -nDivisor;
1995     }
1996
1997     /* If the result is positive, we "add" to round. else, we subtract to round. */
1998     if ( ( (nMultiplicand <  0) && (nMultiplier <  0) ) ||
1999          ( (nMultiplicand >= 0) && (nMultiplier >= 0) ) )
2000       ret = (((long long)nMultiplicand * nMultiplier) + (nDivisor/2)) / nDivisor;
2001     else
2002       ret = (((long long)nMultiplicand * nMultiplier) - (nDivisor/2)) / nDivisor;
2003
2004     if ((ret > 2147483647) || (ret < -2147483647)) return -1;
2005     return ret;
2006 #else
2007     if (!nDivisor) return -1;
2008
2009     /* We want to deal with a positive divisor to simplify the logic. */
2010     if (nDivisor < 0)
2011     {
2012       nMultiplicand = - nMultiplicand;
2013       nDivisor = -nDivisor;
2014     }
2015
2016     /* If the result is positive, we "add" to round. else, we subtract to round. */
2017     if ( ( (nMultiplicand <  0) && (nMultiplier <  0) ) ||
2018          ( (nMultiplicand >= 0) && (nMultiplier >= 0) ) )
2019       return ((nMultiplicand * nMultiplier) + (nDivisor/2)) / nDivisor;
2020  
2021     return ((nMultiplicand * nMultiplier) - (nDivisor/2)) / nDivisor;
2022     
2023 #endif
2024 }
2025
2026
2027 /***********************************************************************
2028  *           DosDateTimeToFileTime   (KERNEL32.76)
2029  */
2030 BOOL WINAPI DosDateTimeToFileTime( WORD fatdate, WORD fattime, LPFILETIME ft)
2031 {
2032     struct tm newtm;
2033
2034     newtm.tm_sec  = (fattime & 0x1f) * 2;
2035     newtm.tm_min  = (fattime >> 5) & 0x3f;
2036     newtm.tm_hour = (fattime >> 11);
2037     newtm.tm_mday = (fatdate & 0x1f);
2038     newtm.tm_mon  = ((fatdate >> 5) & 0x0f) - 1;
2039     newtm.tm_year = (fatdate >> 9) + 80;
2040     RtlSecondsSince1970ToTime( mktime( &newtm ), ft );
2041     return TRUE;
2042 }
2043
2044
2045 /***********************************************************************
2046  *           FileTimeToDosDateTime   (KERNEL32.111)
2047  */
2048 BOOL WINAPI FileTimeToDosDateTime( const FILETIME *ft, LPWORD fatdate,
2049                                      LPWORD fattime )
2050 {
2051     time_t unixtime = DOSFS_FileTimeToUnixTime( ft, NULL );
2052     struct tm *tm = localtime( &unixtime );
2053     if (fattime)
2054         *fattime = (tm->tm_hour << 11) + (tm->tm_min << 5) + (tm->tm_sec / 2);
2055     if (fatdate)
2056         *fatdate = ((tm->tm_year - 80) << 9) + ((tm->tm_mon + 1) << 5)
2057                    + tm->tm_mday;
2058     return TRUE;
2059 }
2060
2061
2062 /***********************************************************************
2063  *           LocalFileTimeToFileTime   (KERNEL32.373)
2064  */
2065 BOOL WINAPI LocalFileTimeToFileTime( const FILETIME *localft,
2066                                        LPFILETIME utcft )
2067 {
2068     struct tm *xtm;
2069     DWORD remainder;
2070
2071     /* convert from local to UTC. Perhaps not correct. FIXME */
2072     time_t unixtime = DOSFS_FileTimeToUnixTime( localft, &remainder );
2073     xtm = gmtime( &unixtime );
2074     DOSFS_UnixTimeToFileTime( mktime(xtm), utcft, remainder );
2075     return TRUE; 
2076 }
2077
2078
2079 /***********************************************************************
2080  *           FileTimeToLocalFileTime   (KERNEL32.112)
2081  */
2082 BOOL WINAPI FileTimeToLocalFileTime( const FILETIME *utcft,
2083                                        LPFILETIME localft )
2084 {
2085     DWORD remainder;
2086     /* convert from UTC to local. Perhaps not correct. FIXME */
2087     time_t unixtime = DOSFS_FileTimeToUnixTime( utcft, &remainder );
2088 #ifdef HAVE_TIMEGM
2089     struct tm *xtm = localtime( &unixtime );
2090     time_t localtime;
2091
2092     localtime = timegm(xtm);
2093     DOSFS_UnixTimeToFileTime( localtime, localft, remainder );
2094
2095 #else
2096     struct tm *xtm,*gtm;
2097     time_t time1,time2;
2098
2099     xtm = localtime( &unixtime );
2100     gtm = gmtime( &unixtime );
2101     time1 = mktime(xtm);
2102     time2 = mktime(gtm);
2103     DOSFS_UnixTimeToFileTime( 2*time1-time2, localft, remainder );
2104 #endif
2105     return TRUE; 
2106 }
2107
2108
2109 /***********************************************************************
2110  *           FileTimeToSystemTime   (KERNEL32.113)
2111  */
2112 BOOL WINAPI FileTimeToSystemTime( const FILETIME *ft, LPSYSTEMTIME syst )
2113 {
2114     struct tm *xtm;
2115     DWORD remainder;
2116     time_t xtime = DOSFS_FileTimeToUnixTime( ft, &remainder );
2117     xtm = gmtime(&xtime);
2118     syst->wYear         = xtm->tm_year+1900;
2119     syst->wMonth        = xtm->tm_mon + 1;
2120     syst->wDayOfWeek    = xtm->tm_wday;
2121     syst->wDay          = xtm->tm_mday;
2122     syst->wHour         = xtm->tm_hour;
2123     syst->wMinute       = xtm->tm_min;
2124     syst->wSecond       = xtm->tm_sec;
2125     syst->wMilliseconds = remainder / 10000;
2126     return TRUE; 
2127 }
2128
2129 /***********************************************************************
2130  *           QueryDosDeviceA   (KERNEL32.413)
2131  *
2132  * returns array of strings terminated by \0, terminated by \0
2133  */
2134 DWORD WINAPI QueryDosDeviceA(LPCSTR devname,LPSTR target,DWORD bufsize)
2135 {
2136     LPSTR s;
2137     char  buffer[200];
2138
2139     TRACE("(%s,...)\n", devname ? devname : "<null>");
2140     if (!devname) {
2141         /* return known MSDOS devices */
2142         strcpy(buffer,"CON COM1 COM2 LPT1 NUL ");
2143         while ((s=strchr(buffer,' ')))
2144                 *s='\0';
2145
2146         lstrcpynA(target,buffer,bufsize);
2147         return strlen(buffer);
2148     }
2149     strcpy(buffer,"\\DEV\\");
2150     strcat(buffer,devname);
2151     if ((s=strchr(buffer,':'))) *s='\0';
2152     lstrcpynA(target,buffer,bufsize);
2153     return strlen(buffer);
2154 }
2155
2156
2157 /***********************************************************************
2158  *           QueryDosDeviceW   (KERNEL32.414)
2159  *
2160  * returns array of strings terminated by \0, terminated by \0
2161  */
2162 DWORD WINAPI QueryDosDeviceW(LPCWSTR devname,LPWSTR target,DWORD bufsize)
2163 {
2164     LPSTR devnameA = devname?HEAP_strdupWtoA(GetProcessHeap(),0,devname):NULL;
2165     LPSTR targetA = (LPSTR)HeapAlloc(GetProcessHeap(),0,bufsize);
2166     DWORD ret = QueryDosDeviceA(devnameA,targetA,bufsize);
2167
2168     lstrcpynAtoW(target,targetA,bufsize);
2169     if (devnameA) HeapFree(GetProcessHeap(),0,devnameA);
2170     if (targetA) HeapFree(GetProcessHeap(),0,targetA);
2171     return ret;
2172 }
2173
2174
2175 /***********************************************************************
2176  *           SystemTimeToFileTime   (KERNEL32.526)
2177  */
2178 BOOL WINAPI SystemTimeToFileTime( const SYSTEMTIME *syst, LPFILETIME ft )
2179 {
2180 #ifdef HAVE_TIMEGM
2181     struct tm xtm;
2182     time_t utctime;
2183 #else
2184     struct tm xtm,*local_tm,*utc_tm;
2185     time_t localtim,utctime;
2186 #endif
2187
2188     xtm.tm_year = syst->wYear-1900;
2189     xtm.tm_mon  = syst->wMonth - 1;
2190     xtm.tm_wday = syst->wDayOfWeek;
2191     xtm.tm_mday = syst->wDay;
2192     xtm.tm_hour = syst->wHour;
2193     xtm.tm_min  = syst->wMinute;
2194     xtm.tm_sec  = syst->wSecond; /* this is UTC */
2195     xtm.tm_isdst = -1;
2196 #ifdef HAVE_TIMEGM
2197     utctime = timegm(&xtm);
2198     DOSFS_UnixTimeToFileTime( utctime, ft, 
2199                               syst->wMilliseconds * 10000 );
2200 #else
2201     localtim = mktime(&xtm);    /* now we've got local time */
2202     local_tm = localtime(&localtim);
2203     utc_tm = gmtime(&localtim);
2204     utctime = mktime(utc_tm);
2205     DOSFS_UnixTimeToFileTime( 2*localtim -utctime, ft, 
2206                               syst->wMilliseconds * 10000 );
2207 #endif
2208     return TRUE; 
2209 }
2210
2211 /***********************************************************************
2212  *           DefineDosDeviceA       (KERNEL32.182)
2213  */
2214 BOOL WINAPI DefineDosDeviceA(DWORD flags,LPCSTR devname,LPCSTR targetpath) {
2215         FIXME("(0x%08lx,%s,%s),stub!\n",flags,devname,targetpath);
2216         SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2217         return FALSE;
2218 }
2219
2220 /*
2221    --- 16 bit functions ---
2222 */
2223
2224 /*************************************************************************
2225  *           FindFirstFile16   (KERNEL.413)
2226  */
2227 HANDLE16 WINAPI FindFirstFile16( LPCSTR path, WIN32_FIND_DATAA *data )
2228 {
2229     DOS_FULL_NAME full_name;
2230     HGLOBAL16 handle;
2231     FIND_FIRST_INFO *info;
2232
2233     data->dwReserved0 = data->dwReserved1 = 0x0;
2234     if (!path) return 0;
2235     if (!DOSFS_GetFullName( path, FALSE, &full_name ))
2236         return INVALID_HANDLE_VALUE16;
2237     if (!(handle = GlobalAlloc16( GMEM_MOVEABLE, sizeof(FIND_FIRST_INFO) )))
2238         return INVALID_HANDLE_VALUE16;
2239     info = (FIND_FIRST_INFO *)GlobalLock16( handle );
2240     info->path = HEAP_strdupA( SystemHeap, 0, full_name.long_name );
2241     info->long_mask = strrchr( info->path, '/' );
2242     if (info->long_mask )
2243         *(info->long_mask++) = '\0';
2244     info->short_mask = NULL;
2245     info->attr = 0xff;
2246     if (path[0] && (path[1] == ':')) info->drive = toupper(*path) - 'A';
2247     else info->drive = DRIVE_GetCurrentDrive();
2248     info->cur_pos = 0;
2249
2250     info->dir = DOSFS_OpenDir( info->path );
2251
2252     GlobalUnlock16( handle );
2253     if (!FindNextFile16( handle, data ))
2254     {
2255         FindClose16( handle );
2256         SetLastError( ERROR_NO_MORE_FILES );
2257         return INVALID_HANDLE_VALUE16;
2258     }
2259     return handle;
2260 }
2261
2262 /*************************************************************************
2263  *           FindNextFile16   (KERNEL.414)
2264  */
2265 BOOL16 WINAPI FindNextFile16( HANDLE16 handle, WIN32_FIND_DATAA *data )
2266 {
2267     FIND_FIRST_INFO *info;
2268
2269     if ((handle == INVALID_HANDLE_VALUE16) ||
2270        !(info = (FIND_FIRST_INFO *)GlobalLock16( handle )))
2271     {
2272         SetLastError( ERROR_INVALID_HANDLE );
2273         return FALSE;
2274     }
2275     GlobalUnlock16( handle );
2276     if (!info->path || !info->dir)
2277     {
2278         SetLastError( ERROR_NO_MORE_FILES );
2279         return FALSE;
2280     }
2281     if (!DOSFS_FindNextEx( info, data ))
2282     {
2283         DOSFS_CloseDir( info->dir ); info->dir = NULL;
2284         HeapFree( SystemHeap, 0, info->path );
2285         info->path = info->long_mask = NULL;
2286         SetLastError( ERROR_NO_MORE_FILES );
2287         return FALSE;
2288     }
2289     return TRUE;
2290 }
2291
2292 /*************************************************************************
2293  *           FindClose16   (KERNEL.415)
2294  */
2295 BOOL16 WINAPI FindClose16( HANDLE16 handle )
2296 {
2297     FIND_FIRST_INFO *info;
2298
2299     if ((handle == INVALID_HANDLE_VALUE16) ||
2300         !(info = (FIND_FIRST_INFO *)GlobalLock16( handle )))
2301     {
2302         SetLastError( ERROR_INVALID_HANDLE );
2303         return FALSE;
2304     }
2305     if (info->dir) DOSFS_CloseDir( info->dir );
2306     if (info->path) HeapFree( SystemHeap, 0, info->path );
2307     GlobalUnlock16( handle );
2308     GlobalFree16( handle );
2309     return TRUE;
2310 }
2311