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