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