Always calls SetMenu in MDISetMenu.
[wine.git] / files / dos_fs.c
blobe6575854f349feb284ad9f5225522e2b73457038
1 /*
2 * DOS file system functions
4 * Copyright 1993 Erik Bos
5 * Copyright 1996 Alexandre Julliard
6 */
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>
24 #include "windef.h"
25 #include "wingdi.h"
26 #include "winuser.h"
27 #include "wine/winbase16.h"
28 #include "winerror.h"
29 #include "drive.h"
30 #include "file.h"
31 #include "heap.h"
32 #include "msdos.h"
33 #include "syslevel.h"
34 #include "server.h"
35 #include "process.h"
36 #include "options.h"
37 #include "debugtools.h"
39 DEFAULT_DEBUG_CHANNEL(dosfs)
40 DECLARE_DEBUG_CHANNEL(file)
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
48 long d_ino;
49 long d_off;
50 unsigned short d_reclen;
51 char d_name[256];
52 } KERNEL_DIRENT;
54 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
56 #else /* linux */
57 #undef VFAT_IOCTL_READDIR_BOTH /* just in case... */
58 #endif /* linux */
60 /* Chars we don't want to see in DOS file names */
61 #define INVALID_DOS_CHARS "*?<>|\"+=,;[] \345"
63 static const DOS_DEVICE DOSFS_Devices[] =
64 /* name, device flags (see Int 21/AX=0x4400) */
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 }
82 #define GET_DRIVE(path) \
83 (((path)[1] == ':') ? toupper((path)[0]) - 'A' : DOSFS_CurDrive)
85 /* Directory info for DOSFS_ReadDir */
86 typedef struct
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;
96 /* Info structure for FindFirstFile handle */
97 typedef struct
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;
110 /***********************************************************************
111 * DOSFS_ValidDOSName
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 '/'.
117 static int DOSFS_ValidDOSName( const char *name, int ignore_case )
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;
124 if (*p == '.')
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));
132 while (!IS_END_OF_NAME(*p))
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++;
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))
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++;
150 return 1;
154 /***********************************************************************
155 * DOSFS_ToDosFCBFormat
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.
163 BOOL DOSFS_ToDosFCBFormat( LPCSTR name, LPSTR buffer )
165 static const char invalid_chars[] = INVALID_DOS_CHARS;
166 const char *p = name;
167 int i;
169 /* Check for "." and ".." */
170 if (*p == '.')
172 p++;
173 strcpy( buffer, ". " );
174 if (*p == '.')
176 buffer[1] = '.';
177 p++;
179 return (!*p || (*p == '/') || (*p == '\\'));
182 for (i = 0; i < 8; i++)
184 switch(*p)
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;
206 if (*p == '*')
208 /* Skip all chars after wildcard up to first dot */
209 while (*p && (*p != '/') && (*p != '\\') && (*p != '.')) p++;
211 else
213 /* Check if name too long */
214 if (*p && (*p != '/') && (*p != '\\') && (*p != '.')) return FALSE;
216 if (*p == '.') p++; /* Skip dot */
218 for (i = 8; i < 11; i++)
220 switch(*p)
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;
242 buffer[11] = '\0';
244 /* at most 3 character of the extension are processed
245 * is something behind this ?
247 while (*p == '*' || *p == ' ') p++; /* skip wildcards and spaces */
248 return IS_END_OF_NAME(*p);
252 /***********************************************************************
253 * DOSFS_ToDosDTAFormat
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.
260 static void DOSFS_ToDosDTAFormat( LPCSTR name, LPSTR buffer )
262 char *p;
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';
274 /***********************************************************************
275 * DOSFS_MatchShort
277 * Check a DOS file name against a mask (both in FCB format).
279 static int DOSFS_MatchShort( const char *mask, const char *name )
281 int i;
282 for (i = 11; i > 0; i--, mask++, name++)
283 if ((*mask != '?') && (*mask != *name)) return 0;
284 return 1;
288 /***********************************************************************
289 * DOSFS_MatchLong
291 * Check a long file name against a mask.
293 static int DOSFS_MatchLong( const char *mask, const char *name,
294 int case_sensitive )
296 if (!strcmp( mask, "*.*" )) return 1;
297 while (*name && *mask)
299 if (*mask == '*')
301 mask++;
302 while (*mask == '*') mask++; /* Skip consecutive '*' */
303 if (!*mask) return 1;
304 if (case_sensitive) while (*name && (*name != *mask)) name++;
305 else while (*name && (toupper(*name) != toupper(*mask))) name++;
306 if (!*name) break;
308 else if (*mask != '?')
310 if (case_sensitive)
312 if (*mask != *name) return 0;
314 else if (toupper(*mask) != toupper(*name)) return 0;
316 mask++;
317 name++;
319 if (*mask == '.') mask++; /* Ignore trailing '.' in mask */
320 return (!*name && !*mask);
324 /***********************************************************************
325 * DOSFS_OpenDir
327 static DOS_DIR *DOSFS_OpenDir( LPCSTR path )
329 DOS_DIR *dir = HeapAlloc( GetProcessHeap(), 0, sizeof(*dir) );
330 if (!dir)
332 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
333 return NULL;
336 /* Treat empty path as root directory. This simplifies path split into
337 directory and mask in several other places */
338 if (!*path) path = "/";
340 #ifdef VFAT_IOCTL_READDIR_BOTH
342 /* Check if the VFAT ioctl is supported on this directory */
344 if ((dir->fd = open( path, O_RDONLY )) != -1)
346 if (ioctl( dir->fd, VFAT_IOCTL_READDIR_BOTH, (long)dir->dirent ) == -1)
348 close( dir->fd );
349 dir->fd = -1;
351 else
353 /* Set the file pointer back at the start of the directory */
354 lseek( dir->fd, 0, SEEK_SET );
355 dir->dir = NULL;
356 return dir;
359 #endif /* VFAT_IOCTL_READDIR_BOTH */
361 /* Now use the standard opendir/readdir interface */
363 if (!(dir->dir = opendir( path )))
365 HeapFree( GetProcessHeap(), 0, dir );
366 return NULL;
368 return dir;
372 /***********************************************************************
373 * DOSFS_CloseDir
375 static void DOSFS_CloseDir( DOS_DIR *dir )
377 #ifdef VFAT_IOCTL_READDIR_BOTH
378 if (dir->fd != -1) close( dir->fd );
379 #endif /* VFAT_IOCTL_READDIR_BOTH */
380 if (dir->dir) closedir( dir->dir );
381 HeapFree( GetProcessHeap(), 0, dir );
385 /***********************************************************************
386 * DOSFS_ReadDir
388 static BOOL DOSFS_ReadDir( DOS_DIR *dir, LPCSTR *long_name,
389 LPCSTR *short_name )
391 struct dirent *dirent;
393 #ifdef VFAT_IOCTL_READDIR_BOTH
394 if (dir->fd != -1)
396 if (ioctl( dir->fd, VFAT_IOCTL_READDIR_BOTH, (long)dir->dirent ) != -1) {
397 if (!dir->dirent[0].d_reclen) return FALSE;
398 if (!DOSFS_ToDosFCBFormat( dir->dirent[0].d_name, dir->short_name ))
399 dir->short_name[0] = '\0';
400 *short_name = dir->short_name;
401 if (dir->dirent[1].d_name[0]) *long_name = dir->dirent[1].d_name;
402 else *long_name = dir->dirent[0].d_name;
403 return TRUE;
406 #endif /* VFAT_IOCTL_READDIR_BOTH */
408 if (!(dirent = readdir( dir->dir ))) return FALSE;
409 *long_name = dirent->d_name;
410 *short_name = NULL;
411 return TRUE;
415 /***********************************************************************
416 * DOSFS_Hash
418 * Transform a Unix file name into a hashed DOS name. If the name is a valid
419 * DOS name, it is converted to upper-case; otherwise it is replaced by a
420 * hashed version that fits in 8.3 format.
421 * File name can be terminated by '\0', '\\' or '/'.
422 * 'buffer' must be at least 13 characters long.
424 static void DOSFS_Hash( LPCSTR name, LPSTR buffer, BOOL dir_format,
425 BOOL ignore_case )
427 static const char invalid_chars[] = INVALID_DOS_CHARS "~.";
428 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
430 const char *p, *ext;
431 char *dst;
432 unsigned short hash;
433 int i;
435 if (dir_format) strcpy( buffer, " " );
437 if (DOSFS_ValidDOSName( name, ignore_case ))
439 /* Check for '.' and '..' */
440 if (*name == '.')
442 buffer[0] = '.';
443 if (!dir_format) buffer[1] = buffer[2] = '\0';
444 if (name[1] == '.') buffer[1] = '.';
445 return;
448 /* Simply copy the name, converting to uppercase */
450 for (dst = buffer; !IS_END_OF_NAME(*name) && (*name != '.'); name++)
451 *dst++ = toupper(*name);
452 if (*name == '.')
454 if (dir_format) dst = buffer + 8;
455 else *dst++ = '.';
456 for (name++; !IS_END_OF_NAME(*name); name++)
457 *dst++ = toupper(*name);
459 if (!dir_format) *dst = '\0';
460 return;
463 /* Compute the hash code of the file name */
464 /* If you know something about hash functions, feel free to */
465 /* insert a better algorithm here... */
466 if (ignore_case)
468 for (p = name, hash = 0xbeef; !IS_END_OF_NAME(p[1]); p++)
469 hash = (hash<<3) ^ (hash>>5) ^ tolower(*p) ^ (tolower(p[1]) << 8);
470 hash = (hash<<3) ^ (hash>>5) ^ tolower(*p); /* Last character*/
472 else
474 for (p = name, hash = 0xbeef; !IS_END_OF_NAME(p[1]); p++)
475 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
476 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
479 /* Find last dot for start of the extension */
480 for (p = name+1, ext = NULL; !IS_END_OF_NAME(*p); p++)
481 if (*p == '.') ext = p;
482 if (ext && IS_END_OF_NAME(ext[1]))
483 ext = NULL; /* Empty extension ignored */
485 /* Copy first 4 chars, replacing invalid chars with '_' */
486 for (i = 4, p = name, dst = buffer; i > 0; i--, p++)
488 if (IS_END_OF_NAME(*p) || (p == ext)) break;
489 *dst++ = strchr( invalid_chars, *p ) ? '_' : toupper(*p);
491 /* Pad to 5 chars with '~' */
492 while (i-- >= 0) *dst++ = '~';
494 /* Insert hash code converted to 3 ASCII chars */
495 *dst++ = hash_chars[(hash >> 10) & 0x1f];
496 *dst++ = hash_chars[(hash >> 5) & 0x1f];
497 *dst++ = hash_chars[hash & 0x1f];
499 /* Copy the first 3 chars of the extension (if any) */
500 if (ext)
502 if (!dir_format) *dst++ = '.';
503 for (i = 3, ext++; (i > 0) && !IS_END_OF_NAME(*ext); i--, ext++)
504 *dst++ = strchr( invalid_chars, *ext ) ? '_' : toupper(*ext);
506 if (!dir_format) *dst = '\0';
510 /***********************************************************************
511 * DOSFS_FindUnixName
513 * Find the Unix file name in a given directory that corresponds to
514 * a file name (either in Unix or DOS format).
515 * File name can be terminated by '\0', '\\' or '/'.
516 * Return TRUE if OK, FALSE if no file name matches.
518 * 'long_buf' must be at least 'long_len' characters long. If the long name
519 * turns out to be larger than that, the function returns FALSE.
520 * 'short_buf' must be at least 13 characters long.
522 BOOL DOSFS_FindUnixName( LPCSTR path, LPCSTR name, LPSTR long_buf,
523 INT long_len, LPSTR short_buf, BOOL ignore_case)
525 DOS_DIR *dir;
526 LPCSTR long_name, short_name;
527 char dos_name[12], tmp_buf[13];
528 BOOL ret;
530 const char *p = strchr( name, '/' );
531 int len = p ? (int)(p - name) : strlen(name);
532 if ((p = strchr( name, '\\' ))) len = min( (int)(p - name), len );
533 /* Ignore trailing dots */
534 while (len > 1 && name[len-1] == '.') len--;
535 if (long_len < len + 1) return FALSE;
537 TRACE("%s,%s\n", path, name );
539 if (!DOSFS_ToDosFCBFormat( name, dos_name )) dos_name[0] = '\0';
541 if (!(dir = DOSFS_OpenDir( path )))
543 WARN("(%s,%s): can't open dir: %s\n",
544 path, name, strerror(errno) );
545 return FALSE;
548 while ((ret = DOSFS_ReadDir( dir, &long_name, &short_name )))
550 /* Check against Unix name */
551 if (len == strlen(long_name))
553 if (!ignore_case)
555 if (!strncmp( long_name, name, len )) break;
557 else
559 if (!lstrncmpiA( long_name, name, len )) break;
562 if (dos_name[0])
564 /* Check against hashed DOS name */
565 if (!short_name)
567 DOSFS_Hash( long_name, tmp_buf, TRUE, ignore_case );
568 short_name = tmp_buf;
570 if (!strcmp( dos_name, short_name )) break;
573 if (ret)
575 if (long_buf) strcpy( long_buf, long_name );
576 if (short_buf)
578 if (short_name)
579 DOSFS_ToDosDTAFormat( short_name, short_buf );
580 else
581 DOSFS_Hash( long_name, short_buf, FALSE, ignore_case );
583 TRACE("(%s,%s) -> %s (%s)\n",
584 path, name, long_name, short_buf ? short_buf : "***");
586 else
587 WARN("'%s' not found in '%s'\n", name, path);
588 DOSFS_CloseDir( dir );
589 return ret;
593 /***********************************************************************
594 * DOSFS_GetDevice
596 * Check if a DOS file name represents a DOS device and return the device.
598 const DOS_DEVICE *DOSFS_GetDevice( const char *name )
600 int i;
601 const char *p;
603 if (!name) return NULL; /* if FILE_DupUnixHandle was used */
604 if (name[0] && (name[1] == ':')) name += 2;
605 if ((p = strrchr( name, '/' ))) name = p + 1;
606 if ((p = strrchr( name, '\\' ))) name = p + 1;
607 for (i = 0; i < sizeof(DOSFS_Devices)/sizeof(DOSFS_Devices[0]); i++)
609 const char *dev = DOSFS_Devices[i].name;
610 if (!lstrncmpiA( dev, name, strlen(dev) ))
612 p = name + strlen( dev );
613 if (!*p || (*p == '.')) return &DOSFS_Devices[i];
616 return NULL;
620 /***********************************************************************
621 * DOSFS_GetDeviceByHandle
623 const DOS_DEVICE *DOSFS_GetDeviceByHandle( HFILE hFile )
625 struct get_file_info_request *req = get_req_buffer();
627 req->handle = hFile;
628 if (!server_call( REQ_GET_FILE_INFO ) && (req->type == FILE_TYPE_UNKNOWN))
630 if ((req->attr >= 0) &&
631 (req->attr < sizeof(DOSFS_Devices)/sizeof(DOSFS_Devices[0])))
632 return &DOSFS_Devices[req->attr];
634 return NULL;
638 /***********************************************************************
639 * DOSFS_OpenDevice
641 * Open a DOS device. This might not map 1:1 into the UNIX device concept.
643 HFILE DOSFS_OpenDevice( const char *name, DWORD access )
645 int i;
646 const char *p;
648 if (!name) return (HFILE)NULL; /* if FILE_DupUnixHandle was used */
649 if (name[0] && (name[1] == ':')) name += 2;
650 if ((p = strrchr( name, '/' ))) name = p + 1;
651 if ((p = strrchr( name, '\\' ))) name = p + 1;
652 for (i = 0; i < sizeof(DOSFS_Devices)/sizeof(DOSFS_Devices[0]); i++)
654 const char *dev = DOSFS_Devices[i].name;
655 if (!lstrncmpiA( dev, name, strlen(dev) ))
657 p = name + strlen( dev );
658 if (!*p || (*p == '.')) {
659 /* got it */
660 if (!strcmp(DOSFS_Devices[i].name,"NUL"))
661 return FILE_CreateFile( "/dev/null", access,
662 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
663 OPEN_EXISTING, 0, -1, TRUE );
664 if (!strcmp(DOSFS_Devices[i].name,"CON")) {
665 HFILE to_dup;
666 HFILE handle;
667 switch (access & (GENERIC_READ|GENERIC_WRITE)) {
668 case GENERIC_READ:
669 to_dup = GetStdHandle( STD_INPUT_HANDLE );
670 break;
671 case GENERIC_WRITE:
672 to_dup = GetStdHandle( STD_OUTPUT_HANDLE );
673 break;
674 default:
675 FIXME("can't open CON read/write\n");
676 return HFILE_ERROR;
677 break;
679 if (!DuplicateHandle( GetCurrentProcess(), to_dup, GetCurrentProcess(),
680 &handle, 0, FALSE, DUPLICATE_SAME_ACCESS ))
681 handle = HFILE_ERROR;
682 return handle;
684 if (!strcmp(DOSFS_Devices[i].name,"SCSIMGR$") ||
685 !strcmp(DOSFS_Devices[i].name,"HPSCAN"))
687 return FILE_CreateDevice( i, access, NULL );
690 HFILE r;
691 char devname[40];
692 PROFILE_GetWineIniString("serialports",name,"",devname,sizeof devname);
694 if(devname[0])
696 TRACE_(file)("DOSFS_OpenDevice %s is %s\n",
697 DOSFS_Devices[i].name,devname);
698 r = FILE_CreateFile( devname, access,
699 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
700 OPEN_EXISTING, 0, -1, TRUE );
701 TRACE_(file)("Create_File return %08X\n",r);
702 return r;
706 FIXME("device open %s not supported (yet)\n",DOSFS_Devices[i].name);
707 return HFILE_ERROR;
711 return HFILE_ERROR;
715 /***********************************************************************
716 * DOSFS_GetPathDrive
718 * Get the drive specified by a given path name (DOS or Unix format).
720 static int DOSFS_GetPathDrive( const char **name )
722 int drive;
723 const char *p = *name;
725 if (*p && (p[1] == ':'))
727 drive = toupper(*p) - 'A';
728 *name += 2;
730 else if (*p == '/') /* Absolute Unix path? */
732 if ((drive = DRIVE_FindDriveRoot( name )) == -1)
734 MESSAGE("Warning: %s not accessible from a DOS drive\n", *name );
735 /* Assume it really was a DOS name */
736 drive = DRIVE_GetCurrentDrive();
739 else drive = DRIVE_GetCurrentDrive();
741 if (!DRIVE_IsValid(drive))
743 SetLastError( ERROR_INVALID_DRIVE );
744 return -1;
746 return drive;
750 /***********************************************************************
751 * DOSFS_GetFullName
753 * Convert a file name (DOS or mixed DOS/Unix format) to a valid
754 * Unix name / short DOS name pair.
755 * Return FALSE if one of the path components does not exist. The last path
756 * component is only checked if 'check_last' is non-zero.
757 * The buffers pointed to by 'long_buf' and 'short_buf' must be
758 * at least MAX_PATHNAME_LEN long.
760 BOOL DOSFS_GetFullName( LPCSTR name, BOOL check_last, DOS_FULL_NAME *full )
762 BOOL found;
763 UINT flags;
764 char *p_l, *p_s, *root;
766 TRACE("%s (last=%d)\n", name, check_last );
768 if ((full->drive = DOSFS_GetPathDrive( &name )) == -1) return FALSE;
769 flags = DRIVE_GetFlags( full->drive );
771 lstrcpynA( full->long_name, DRIVE_GetRoot( full->drive ),
772 sizeof(full->long_name) );
773 if (full->long_name[1]) root = full->long_name + strlen(full->long_name);
774 else root = full->long_name; /* root directory */
776 strcpy( full->short_name, "A:\\" );
777 full->short_name[0] += full->drive;
779 if ((*name == '\\') || (*name == '/')) /* Absolute path */
781 while ((*name == '\\') || (*name == '/')) name++;
783 else /* Relative path */
785 lstrcpynA( root + 1, DRIVE_GetUnixCwd( full->drive ),
786 sizeof(full->long_name) - (root - full->long_name) - 1 );
787 if (root[1]) *root = '/';
788 lstrcpynA( full->short_name + 3, DRIVE_GetDosCwd( full->drive ),
789 sizeof(full->short_name) - 3 );
792 p_l = full->long_name[1] ? full->long_name + strlen(full->long_name)
793 : full->long_name;
794 p_s = full->short_name[3] ? full->short_name + strlen(full->short_name)
795 : full->short_name + 2;
796 found = TRUE;
798 while (*name && found)
800 /* Check for '.' and '..' */
802 if (*name == '.')
804 if (IS_END_OF_NAME(name[1]))
806 name++;
807 while ((*name == '\\') || (*name == '/')) name++;
808 continue;
810 else if ((name[1] == '.') && IS_END_OF_NAME(name[2]))
812 name += 2;
813 while ((*name == '\\') || (*name == '/')) name++;
814 while ((p_l > root) && (*p_l != '/')) p_l--;
815 while ((p_s > full->short_name + 2) && (*p_s != '\\')) p_s--;
816 *p_l = *p_s = '\0'; /* Remove trailing separator */
817 continue;
821 /* Make sure buffers are large enough */
823 if ((p_s >= full->short_name + sizeof(full->short_name) - 14) ||
824 (p_l >= full->long_name + sizeof(full->long_name) - 1))
826 SetLastError( ERROR_PATH_NOT_FOUND );
827 return FALSE;
830 /* Get the long and short name matching the file name */
832 if ((found = DOSFS_FindUnixName( full->long_name, name, p_l + 1,
833 sizeof(full->long_name) - (p_l - full->long_name) - 1,
834 p_s + 1, !(flags & DRIVE_CASE_SENSITIVE) )))
836 *p_l++ = '/';
837 p_l += strlen(p_l);
838 *p_s++ = '\\';
839 p_s += strlen(p_s);
840 while (!IS_END_OF_NAME(*name)) name++;
842 else if (!check_last)
844 *p_l++ = '/';
845 *p_s++ = '\\';
846 while (!IS_END_OF_NAME(*name) &&
847 (p_s < full->short_name + sizeof(full->short_name) - 1) &&
848 (p_l < full->long_name + sizeof(full->long_name) - 1))
850 *p_s++ = tolower(*name);
851 /* If the drive is case-sensitive we want to create new */
852 /* files in lower-case otherwise we can't reopen them */
853 /* under the same short name. */
854 if (flags & DRIVE_CASE_SENSITIVE) *p_l++ = tolower(*name);
855 else *p_l++ = *name;
856 name++;
858 *p_l = *p_s = '\0';
860 while ((*name == '\\') || (*name == '/')) name++;
863 if (!found)
865 if (check_last)
867 SetLastError( ERROR_FILE_NOT_FOUND );
868 return FALSE;
870 if (*name) /* Not last */
872 SetLastError( ERROR_PATH_NOT_FOUND );
873 return FALSE;
876 if (!full->long_name[0]) strcpy( full->long_name, "/" );
877 if (!full->short_name[2]) strcpy( full->short_name + 2, "\\" );
878 TRACE("returning %s = %s\n", full->long_name, full->short_name );
879 return TRUE;
883 /***********************************************************************
884 * GetShortPathNameA (KERNEL32.271)
886 * NOTES
887 * observed:
888 * longpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
889 * *longpath="" or invalid: LastError=ERROR_BAD_PATHNAME, ret=0
891 * more observations ( with NT 3.51 (WinDD) ):
892 * longpath <= 8.3 -> just copy longpath to shortpath
893 * longpath > 8.3 ->
894 * a) file does not exist -> return 0, LastError = ERROR_FILE_NOT_FOUND
895 * b) file does exist -> set the short filename.
896 * - trailing slashes are reproduced in the short name, even if the
897 * file is not a directory
898 * - the absolute/relative path of the short name is reproduced like found
899 * in the long name
900 * - longpath and shortpath may have the same adress
901 * Peter Ganten, 1999
903 DWORD WINAPI GetShortPathNameA( LPCSTR longpath, LPSTR shortpath,
904 DWORD shortlen )
906 DOS_FULL_NAME full_name;
907 LPSTR tmpshortpath;
908 DWORD sp = 0, lp = 0;
909 int tmplen, drive;
910 UINT flags;
912 TRACE("%s\n", debugstr_a(longpath));
914 if (!longpath) {
915 SetLastError(ERROR_INVALID_PARAMETER);
916 return 0;
918 if (!longpath[0]) {
919 SetLastError(ERROR_BAD_PATHNAME);
920 return 0;
923 if ( ( tmpshortpath = HeapAlloc ( GetProcessHeap(), 0, MAX_PATHNAME_LEN ) ) == NULL ) {
924 SetLastError ( ERROR_NOT_ENOUGH_MEMORY );
925 return 0;
928 /* check for drive letter */
929 if ( longpath[1] == ':' ) {
930 tmpshortpath[0] = longpath[0];
931 tmpshortpath[1] = ':';
932 sp = 2;
935 if ( ( drive = DOSFS_GetPathDrive ( &longpath )) == -1 ) return 0;
936 flags = DRIVE_GetFlags ( drive );
938 while ( longpath[lp] ) {
940 /* check for path delimiters and reproduce them */
941 if ( longpath[lp] == '\\' || longpath[lp] == '/' ) {
942 if (!sp || tmpshortpath[sp-1]!= '\\')
944 /* strip double "\\" */
945 tmpshortpath[sp] = '\\';
946 sp++;
948 lp++;
949 continue;
952 tmplen = strcspn ( longpath + lp, "\\/" );
953 lstrcpynA ( tmpshortpath+sp, longpath + lp, tmplen+1 );
955 /* Check, if the current element is a valid dos name */
956 if ( DOSFS_ValidDOSName ( longpath + lp, !(flags & DRIVE_CASE_SENSITIVE) ) ) {
957 sp += tmplen;
958 lp += tmplen;
959 continue;
962 /* Check if the file exists and use the existing file name */
963 if ( DOSFS_GetFullName ( tmpshortpath, TRUE, &full_name ) ) {
964 lstrcpyA ( tmpshortpath+sp, strrchr ( full_name.short_name, '\\' ) + 1 );
965 sp += lstrlenA ( tmpshortpath+sp );
966 lp += tmplen;
967 continue;
970 TRACE("not found!\n" );
971 SetLastError ( ERROR_FILE_NOT_FOUND );
972 return 0;
974 tmpshortpath[sp] = 0;
976 lstrcpynA ( shortpath, tmpshortpath, shortlen );
977 TRACE("returning %s\n", debugstr_a(shortpath) );
978 tmplen = lstrlenA ( tmpshortpath );
979 HeapFree ( GetProcessHeap(), 0, tmpshortpath );
981 return tmplen;
985 /***********************************************************************
986 * GetShortPathNameW (KERNEL32.272)
988 DWORD WINAPI GetShortPathNameW( LPCWSTR longpath, LPWSTR shortpath,
989 DWORD shortlen )
991 LPSTR longpathA, shortpathA;
992 DWORD ret = 0;
994 longpathA = HEAP_strdupWtoA( GetProcessHeap(), 0, longpath );
995 shortpathA = HeapAlloc ( GetProcessHeap(), 0, shortlen );
997 ret = GetShortPathNameA ( longpathA, shortpathA, shortlen );
998 lstrcpynAtoW ( shortpath, shortpathA, shortlen );
1000 HeapFree( GetProcessHeap(), 0, longpathA );
1001 HeapFree( GetProcessHeap(), 0, shortpathA );
1003 return ret;
1007 /***********************************************************************
1008 * GetLongPathNameA (KERNEL32.xxx)
1010 DWORD WINAPI GetLongPathNameA( LPCSTR shortpath, LPSTR longpath,
1011 DWORD longlen )
1013 DOS_FULL_NAME full_name;
1014 char *p, *r, *ll, *ss;
1016 if (!DOSFS_GetFullName( shortpath, TRUE, &full_name )) return 0;
1017 lstrcpynA( longpath, full_name.short_name, longlen );
1019 /* Do some hackery to get the long filename. */
1021 if (longpath) {
1022 ss=longpath+strlen(longpath);
1023 ll=full_name.long_name+strlen(full_name.long_name);
1024 p=NULL;
1025 while (ss>=longpath)
1027 /* FIXME: aren't we more paranoid, than needed? */
1028 while ((ss[0]=='\\') && (ss>=longpath)) ss--;
1029 p=ss;
1030 while ((ss[0]!='\\') && (ss>=longpath)) ss--;
1031 if (ss>=longpath)
1033 /* FIXME: aren't we more paranoid, than needed? */
1034 while ((ll[0]=='/') && (ll>=full_name.long_name)) ll--;
1035 while ((ll[0]!='/') && (ll>=full_name.long_name)) ll--;
1036 if (ll<full_name.long_name)
1038 ERR("Bad longname! (ss=%s ll=%s)\n This should never happen !\n"
1039 ,ss ,ll );
1040 return 0;
1045 /* FIXME: fix for names like "C:\\" (ie. with more '\'s) */
1046 if (p && p[2])
1048 p+=1;
1049 if ((p-longpath)>0) longlen -= (p-longpath);
1050 lstrcpynA( p, ll , longlen);
1052 /* Now, change all '/' to '\' */
1053 for (r=p; r<(p+longlen); r++ )
1054 if (r[0]=='/') r[0]='\\';
1055 return strlen(longpath) - strlen(p) + longlen;
1059 return strlen(longpath);
1063 /***********************************************************************
1064 * GetLongPathNameW (KERNEL32.269)
1066 DWORD WINAPI GetLongPathNameW( LPCWSTR shortpath, LPWSTR longpath,
1067 DWORD longlen )
1069 DOS_FULL_NAME full_name;
1070 DWORD ret = 0;
1071 LPSTR shortpathA = HEAP_strdupWtoA( GetProcessHeap(), 0, shortpath );
1073 /* FIXME: is it correct to always return a fully qualified short path? */
1074 if (DOSFS_GetFullName( shortpathA, TRUE, &full_name ))
1076 ret = strlen( full_name.short_name );
1077 lstrcpynAtoW( longpath, full_name.long_name, longlen );
1079 HeapFree( GetProcessHeap(), 0, shortpathA );
1080 return ret;
1084 /***********************************************************************
1085 * DOSFS_DoGetFullPathName
1087 * Implementation of GetFullPathNameA/W.
1089 * bon@elektron 000331:
1090 * A test for GetFullPathName with many patholotical case
1091 * gives now identical output for Wine and OSR2
1093 static DWORD DOSFS_DoGetFullPathName( LPCSTR name, DWORD len, LPSTR result,
1094 BOOL unicode )
1096 DWORD ret;
1097 DOS_FULL_NAME full_name;
1098 char *p,*q;
1099 const char * root;
1100 char drivecur[]="c:.";
1101 char driveletter=0;
1102 int namelen,drive=0;
1104 if ((strlen(name) >1)&& (name[1]==':'))
1105 /*drive letter given */
1107 driveletter = name[0];
1109 if ((strlen(name) >2)&& (name[1]==':') &&
1110 ((name[2]=='\\') || (name[2]=='/')))
1111 /*absolue path given */
1113 lstrcpynA(full_name.short_name,name,MAX_PATHNAME_LEN);
1115 else
1117 if (driveletter)
1118 drivecur[0]=driveletter;
1119 else
1120 strcpy(drivecur,".");
1121 if (!DOSFS_GetFullName( drivecur, FALSE, &full_name ))
1123 FIXME("internal: error getting drive/path\n");
1124 return 0;
1126 /* find path that drive letter substitutes*/
1127 drive = (int)toupper(full_name.short_name[0]) -0x41;
1128 root= DRIVE_GetRoot(drive);
1129 p= full_name.long_name +strlen(root);
1130 /* append long name (= unix name) to drive */
1131 lstrcpynA(full_name.short_name+2,p,MAX_PATHNAME_LEN-3);
1132 /* append name to treat */
1133 namelen= strlen(full_name.short_name);
1134 p = (char*)name;
1135 if (driveletter)
1136 p += +2; /* skip drive name when appending */
1137 if (namelen +2 + strlen(p) > MAX_PATHNAME_LEN)
1139 FIXME("internal error: buffer too small\n");
1140 return 0;
1142 full_name.short_name[namelen++] ='\\';
1143 full_name.short_name[namelen] = 0;
1144 lstrcpynA(full_name.short_name +namelen,p,MAX_PATHNAME_LEN-namelen);
1146 /* reverse all slashes */
1147 for (p=full_name.short_name;
1148 p < full_name.short_name+strlen(full_name.short_name);
1149 p++)
1151 if ( *p == '/' )
1152 *p = '\\';
1154 /* Use memmove, as areas overlap*/
1155 /* Delete .. */
1156 while ((p = strstr(full_name.short_name,"\\..\\")))
1158 if (p > full_name.short_name+2)
1160 *p = 0;
1161 q = strrchr(full_name.short_name,'\\');
1162 memmove(q+1,p+4,strlen(p+4)+1);
1164 else
1166 memmove(full_name.short_name+3,p+4,strlen(p+4)+1);
1169 if ((full_name.short_name[2]=='.')&&(full_name.short_name[3]=='.'))
1171 /* This case istn't treated yet : c:..\test */
1172 memmove(full_name.short_name+2,full_name.short_name+4,
1173 strlen(full_name.short_name+4)+1);
1175 /* Delete . */
1176 while ((p = strstr(full_name.short_name,"\\.\\")))
1178 *(p+1) = 0;
1179 memmove(p+1,p+3,strlen(p+3));
1181 if (!(DRIVE_GetFlags(drive) & DRIVE_CASE_PRESERVING))
1182 CharUpperA( full_name.short_name );
1183 namelen=strlen(full_name.short_name);
1184 if (!strcmp(full_name.short_name+namelen-3,"\\.."))
1186 /* one more starnge case: "c:\test\test1\.."
1187 return "c:\test"*/
1188 *(full_name.short_name+namelen-3)=0;
1189 q = strrchr(full_name.short_name,'\\');
1190 *q =0;
1192 if (full_name.short_name[namelen-1]=='.')
1193 full_name.short_name[(namelen--)-1] =0;
1194 if (!driveletter)
1195 if (full_name.short_name[namelen-1]=='\\')
1196 full_name.short_name[(namelen--)-1] =0;
1197 TRACE("got %s\n",full_name.short_name);
1199 /* If the lpBuffer buffer is too small, the return value is the
1200 size of the buffer, in characters, required to hold the path
1201 plus the terminating \0 (tested against win95osr, bon 001118)
1202 . */
1203 ret = strlen(full_name.short_name);
1204 if (ret >= len )
1206 /* don't touch anything when the buffer is not large enough */
1207 SetLastError( ERROR_INSUFFICIENT_BUFFER );
1208 return ret+1;
1210 if (result)
1212 if (unicode)
1213 lstrcpynAtoW( (LPWSTR)result, full_name.short_name, len );
1214 else
1215 lstrcpynA( result, full_name.short_name, len );
1218 TRACE("returning '%s'\n", full_name.short_name );
1219 return ret;
1223 /***********************************************************************
1224 * GetFullPathNameA (KERNEL32.272)
1225 * NOTES
1226 * if the path closed with '\', *lastpart is 0
1228 DWORD WINAPI GetFullPathNameA( LPCSTR name, DWORD len, LPSTR buffer,
1229 LPSTR *lastpart )
1231 DWORD ret = DOSFS_DoGetFullPathName( name, len, buffer, FALSE );
1232 if (ret && (ret<=len) && buffer && lastpart)
1234 LPSTR p = buffer + strlen(buffer);
1236 if (*p != '\\')
1238 while ((p > buffer + 2) && (*p != '\\')) p--;
1239 *lastpart = p + 1;
1241 else *lastpart = NULL;
1243 return ret;
1247 /***********************************************************************
1248 * GetFullPathNameW (KERNEL32.273)
1250 DWORD WINAPI GetFullPathNameW( LPCWSTR name, DWORD len, LPWSTR buffer,
1251 LPWSTR *lastpart )
1253 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
1254 DWORD ret = DOSFS_DoGetFullPathName( nameA, len, (LPSTR)buffer, TRUE );
1255 HeapFree( GetProcessHeap(), 0, nameA );
1256 if (ret && (ret<=len) && buffer && lastpart)
1258 LPWSTR p = buffer + lstrlenW(buffer);
1259 if (*p != (WCHAR)'\\')
1261 while ((p > buffer + 2) && (*p != (WCHAR)'\\')) p--;
1262 *lastpart = p + 1;
1264 else *lastpart = NULL;
1266 return ret;
1269 /***********************************************************************
1270 * DOSFS_FindNextEx
1272 static int DOSFS_FindNextEx( FIND_FIRST_INFO *info, WIN32_FIND_DATAA *entry )
1274 BYTE attr = info->attr | FA_UNUSED | FA_ARCHIVE | FA_RDONLY;
1275 UINT flags = DRIVE_GetFlags( info->drive );
1276 char *p, buffer[MAX_PATHNAME_LEN];
1277 const char *drive_path;
1278 int drive_root;
1279 LPCSTR long_name, short_name;
1280 BY_HANDLE_FILE_INFORMATION fileinfo;
1281 char dos_name[13];
1283 if ((info->attr & ~(FA_UNUSED | FA_ARCHIVE | FA_RDONLY)) == FA_LABEL)
1285 if (info->cur_pos) return 0;
1286 entry->dwFileAttributes = FILE_ATTRIBUTE_LABEL;
1287 DOSFS_UnixTimeToFileTime( (time_t)0, &entry->ftCreationTime, 0 );
1288 DOSFS_UnixTimeToFileTime( (time_t)0, &entry->ftLastAccessTime, 0 );
1289 DOSFS_UnixTimeToFileTime( (time_t)0, &entry->ftLastWriteTime, 0 );
1290 entry->nFileSizeHigh = 0;
1291 entry->nFileSizeLow = 0;
1292 entry->dwReserved0 = 0;
1293 entry->dwReserved1 = 0;
1294 DOSFS_ToDosDTAFormat( DRIVE_GetLabel( info->drive ), entry->cFileName );
1295 strcpy( entry->cAlternateFileName, entry->cFileName );
1296 info->cur_pos++;
1297 return 1;
1300 drive_path = info->path + strlen(DRIVE_GetRoot( info->drive ));
1301 while ((*drive_path == '/') || (*drive_path == '\\')) drive_path++;
1302 drive_root = !*drive_path;
1304 lstrcpynA( buffer, info->path, sizeof(buffer) - 1 );
1305 strcat( buffer, "/" );
1306 p = buffer + strlen(buffer);
1308 while (DOSFS_ReadDir( info->dir, &long_name, &short_name ))
1310 info->cur_pos++;
1312 /* Don't return '.' and '..' in the root of the drive */
1313 if (drive_root && (long_name[0] == '.') &&
1314 (!long_name[1] || ((long_name[1] == '.') && !long_name[2])))
1315 continue;
1317 /* Check the long mask */
1319 if (info->long_mask)
1321 if (!DOSFS_MatchLong( info->long_mask, long_name,
1322 flags & DRIVE_CASE_SENSITIVE )) continue;
1325 /* Check the short mask */
1327 if (info->short_mask)
1329 if (!short_name)
1331 DOSFS_Hash( long_name, dos_name, TRUE,
1332 !(flags & DRIVE_CASE_SENSITIVE) );
1333 short_name = dos_name;
1335 if (!DOSFS_MatchShort( info->short_mask, short_name )) continue;
1338 /* Check the file attributes */
1340 lstrcpynA( p, long_name, sizeof(buffer) - (int)(p - buffer) );
1341 if (!FILE_Stat( buffer, &fileinfo ))
1343 WARN("can't stat %s\n", buffer);
1344 continue;
1346 if (fileinfo.dwFileAttributes & ~attr) continue;
1348 /* We now have a matching entry; fill the result and return */
1350 entry->dwFileAttributes = fileinfo.dwFileAttributes;
1351 entry->ftCreationTime = fileinfo.ftCreationTime;
1352 entry->ftLastAccessTime = fileinfo.ftLastAccessTime;
1353 entry->ftLastWriteTime = fileinfo.ftLastWriteTime;
1354 entry->nFileSizeHigh = fileinfo.nFileSizeHigh;
1355 entry->nFileSizeLow = fileinfo.nFileSizeLow;
1357 if (short_name)
1358 DOSFS_ToDosDTAFormat( short_name, entry->cAlternateFileName );
1359 else
1360 DOSFS_Hash( long_name, entry->cAlternateFileName, FALSE,
1361 !(flags & DRIVE_CASE_SENSITIVE) );
1363 lstrcpynA( entry->cFileName, long_name, sizeof(entry->cFileName) );
1364 if (!(flags & DRIVE_CASE_PRESERVING)) CharLowerA( entry->cFileName );
1365 TRACE("returning %s (%s) %02lx %ld\n",
1366 entry->cFileName, entry->cAlternateFileName,
1367 entry->dwFileAttributes, entry->nFileSizeLow );
1368 return 1;
1370 return 0; /* End of directory */
1373 /***********************************************************************
1374 * DOSFS_FindNext
1376 * Find the next matching file. Return the number of entries read to find
1377 * the matching one, or 0 if no more entries.
1378 * 'short_mask' is the 8.3 mask (in FCB format), 'long_mask' is the long
1379 * file name mask. Either or both can be NULL.
1381 * NOTE: This is supposed to be only called by the int21 emulation
1382 * routines. Thus, we should own the Win16Mutex anyway.
1383 * Nevertheless, we explicitly enter it to ensure the static
1384 * directory cache is protected.
1386 int DOSFS_FindNext( const char *path, const char *short_mask,
1387 const char *long_mask, int drive, BYTE attr,
1388 int skip, WIN32_FIND_DATAA *entry )
1390 static FIND_FIRST_INFO info = { NULL };
1391 LPCSTR short_name, long_name;
1392 int count;
1394 SYSLEVEL_EnterWin16Lock();
1396 /* Check the cached directory */
1397 if (!(info.dir && info.path == path && info.short_mask == short_mask
1398 && info.long_mask == long_mask && info.drive == drive
1399 && info.attr == attr && info.cur_pos <= skip))
1401 /* Not in the cache, open it anew */
1402 if (info.dir) DOSFS_CloseDir( info.dir );
1404 info.path = (LPSTR)path;
1405 info.long_mask = (LPSTR)long_mask;
1406 info.short_mask = (LPSTR)short_mask;
1407 info.attr = attr;
1408 info.drive = drive;
1409 info.cur_pos = 0;
1410 info.dir = DOSFS_OpenDir( info.path );
1413 /* Skip to desired position */
1414 while (info.cur_pos < skip)
1415 if (info.dir && DOSFS_ReadDir( info.dir, &long_name, &short_name ))
1416 info.cur_pos++;
1417 else
1418 break;
1420 if (info.dir && info.cur_pos == skip && DOSFS_FindNextEx( &info, entry ))
1421 count = info.cur_pos - skip;
1422 else
1423 count = 0;
1425 if (!count)
1427 if (info.dir) DOSFS_CloseDir( info.dir );
1428 memset( &info, '\0', sizeof(info) );
1431 SYSLEVEL_LeaveWin16Lock();
1433 return count;
1438 /*************************************************************************
1439 * FindFirstFile16 (KERNEL.413)
1441 HANDLE16 WINAPI FindFirstFile16( LPCSTR path, WIN32_FIND_DATAA *data )
1443 DOS_FULL_NAME full_name;
1444 HGLOBAL16 handle;
1445 FIND_FIRST_INFO *info;
1447 data->dwReserved0 = data->dwReserved1 = 0x0;
1448 if (!path) return 0;
1449 if (!DOSFS_GetFullName( path, FALSE, &full_name ))
1450 return INVALID_HANDLE_VALUE16;
1451 if (!(handle = GlobalAlloc16( GMEM_MOVEABLE, sizeof(FIND_FIRST_INFO) )))
1452 return INVALID_HANDLE_VALUE16;
1453 info = (FIND_FIRST_INFO *)GlobalLock16( handle );
1454 info->path = HEAP_strdupA( GetProcessHeap(), 0, full_name.long_name );
1455 info->long_mask = strrchr( info->path, '/' );
1456 *(info->long_mask++) = '\0';
1457 info->short_mask = NULL;
1458 info->attr = 0xff;
1459 if (path[0] && (path[1] == ':')) info->drive = toupper(*path) - 'A';
1460 else info->drive = DRIVE_GetCurrentDrive();
1461 info->cur_pos = 0;
1463 info->dir = DOSFS_OpenDir( info->path );
1465 GlobalUnlock16( handle );
1466 if (!FindNextFile16( handle, data ))
1468 FindClose16( handle );
1469 SetLastError( ERROR_NO_MORE_FILES );
1470 return INVALID_HANDLE_VALUE16;
1472 return handle;
1476 /*************************************************************************
1477 * FindFirstFileA (KERNEL32.123)
1479 HANDLE WINAPI FindFirstFileA( LPCSTR path, WIN32_FIND_DATAA *data )
1481 HANDLE handle = FindFirstFile16( path, data );
1482 if (handle == INVALID_HANDLE_VALUE16) return INVALID_HANDLE_VALUE;
1483 return handle;
1487 /*************************************************************************
1488 * FindFirstFileW (KERNEL32.124)
1490 HANDLE WINAPI FindFirstFileW( LPCWSTR path, WIN32_FIND_DATAW *data )
1492 WIN32_FIND_DATAA dataA;
1493 LPSTR pathA = HEAP_strdupWtoA( GetProcessHeap(), 0, path );
1494 HANDLE handle = FindFirstFileA( pathA, &dataA );
1495 HeapFree( GetProcessHeap(), 0, pathA );
1496 if (handle != INVALID_HANDLE_VALUE)
1498 data->dwFileAttributes = dataA.dwFileAttributes;
1499 data->ftCreationTime = dataA.ftCreationTime;
1500 data->ftLastAccessTime = dataA.ftLastAccessTime;
1501 data->ftLastWriteTime = dataA.ftLastWriteTime;
1502 data->nFileSizeHigh = dataA.nFileSizeHigh;
1503 data->nFileSizeLow = dataA.nFileSizeLow;
1504 lstrcpyAtoW( data->cFileName, dataA.cFileName );
1505 lstrcpyAtoW( data->cAlternateFileName, dataA.cAlternateFileName );
1507 return handle;
1511 /*************************************************************************
1512 * FindNextFile16 (KERNEL.414)
1514 BOOL16 WINAPI FindNextFile16( HANDLE16 handle, WIN32_FIND_DATAA *data )
1516 FIND_FIRST_INFO *info;
1518 if (!(info = (FIND_FIRST_INFO *)GlobalLock16( handle )))
1520 SetLastError( ERROR_INVALID_HANDLE );
1521 return FALSE;
1523 GlobalUnlock16( handle );
1524 if (!info->path || !info->dir)
1526 SetLastError( ERROR_NO_MORE_FILES );
1527 return FALSE;
1529 if (!DOSFS_FindNextEx( info, data ))
1531 DOSFS_CloseDir( info->dir ); info->dir = NULL;
1532 HeapFree( GetProcessHeap(), 0, info->path );
1533 info->path = info->long_mask = NULL;
1534 SetLastError( ERROR_NO_MORE_FILES );
1535 return FALSE;
1537 return TRUE;
1541 /*************************************************************************
1542 * FindNextFileA (KERNEL32.126)
1544 BOOL WINAPI FindNextFileA( HANDLE handle, WIN32_FIND_DATAA *data )
1546 return FindNextFile16( handle, data );
1550 /*************************************************************************
1551 * FindNextFileW (KERNEL32.127)
1553 BOOL WINAPI FindNextFileW( HANDLE handle, WIN32_FIND_DATAW *data )
1555 WIN32_FIND_DATAA dataA;
1556 if (!FindNextFileA( handle, &dataA )) return FALSE;
1557 data->dwFileAttributes = dataA.dwFileAttributes;
1558 data->ftCreationTime = dataA.ftCreationTime;
1559 data->ftLastAccessTime = dataA.ftLastAccessTime;
1560 data->ftLastWriteTime = dataA.ftLastWriteTime;
1561 data->nFileSizeHigh = dataA.nFileSizeHigh;
1562 data->nFileSizeLow = dataA.nFileSizeLow;
1563 lstrcpyAtoW( data->cFileName, dataA.cFileName );
1564 lstrcpyAtoW( data->cAlternateFileName, dataA.cAlternateFileName );
1565 return TRUE;
1569 /*************************************************************************
1570 * FindClose16 (KERNEL.415)
1572 BOOL16 WINAPI FindClose16( HANDLE16 handle )
1574 FIND_FIRST_INFO *info;
1576 if ((handle == INVALID_HANDLE_VALUE16) ||
1577 !(info = (FIND_FIRST_INFO *)GlobalLock16( handle )))
1579 SetLastError( ERROR_INVALID_HANDLE );
1580 return FALSE;
1582 if (info->dir) DOSFS_CloseDir( info->dir );
1583 if (info->path) HeapFree( GetProcessHeap(), 0, info->path );
1584 GlobalUnlock16( handle );
1585 GlobalFree16( handle );
1586 return TRUE;
1590 /*************************************************************************
1591 * FindClose (KERNEL32.119)
1593 BOOL WINAPI FindClose( HANDLE handle )
1595 return FindClose16( (HANDLE16)handle );
1599 /***********************************************************************
1600 * DOSFS_UnixTimeToFileTime
1602 * Convert a Unix time to FILETIME format.
1603 * The FILETIME structure is a 64-bit value representing the number of
1604 * 100-nanosecond intervals since January 1, 1601, 0:00.
1605 * 'remainder' is the nonnegative number of 100-ns intervals
1606 * corresponding to the time fraction smaller than 1 second that
1607 * couldn't be stored in the time_t value.
1609 void DOSFS_UnixTimeToFileTime( time_t unix_time, FILETIME *filetime,
1610 DWORD remainder )
1612 /* NOTES:
1614 CONSTANTS:
1615 The time difference between 1 January 1601, 00:00:00 and
1616 1 January 1970, 00:00:00 is 369 years, plus the leap years
1617 from 1604 to 1968, excluding 1700, 1800, 1900.
1618 This makes (1968 - 1600) / 4 - 3 = 89 leap days, and a total
1619 of 134774 days.
1621 Any day in that period had 24 * 60 * 60 = 86400 seconds.
1623 The time difference is 134774 * 86400 * 10000000, which can be written
1624 116444736000000000
1625 27111902 * 2^32 + 3577643008
1626 413 * 2^48 + 45534 * 2^32 + 54590 * 2^16 + 32768
1628 If you find that these constants are buggy, please change them in all
1629 instances in both conversion functions.
1631 VERSIONS:
1632 There are two versions, one of them uses long long variables and
1633 is presumably faster but not ISO C. The other one uses standard C
1634 data types and operations but relies on the assumption that negative
1635 numbers are stored as 2's complement (-1 is 0xffff....). If this
1636 assumption is violated, dates before 1970 will not convert correctly.
1637 This should however work on any reasonable architecture where WINE
1638 will run.
1640 DETAILS:
1642 Take care not to remove the casts. I have tested these functions
1643 (in both versions) for a lot of numbers. I would be interested in
1644 results on other compilers than GCC.
1646 The operations have been designed to account for the possibility
1647 of 64-bit time_t in future UNICES. Even the versions without
1648 internal long long numbers will work if time_t only is 64 bit.
1649 A 32-bit shift, which was necessary for that operation, turned out
1650 not to work correctly in GCC, besides giving the warning. So I
1651 used a double 16-bit shift instead. Numbers are in the ISO version
1652 represented by three limbs, the most significant with 32 bit, the
1653 other two with 16 bit each.
1655 As the modulo-operator % is not well-defined for negative numbers,
1656 negative divisors have been avoided in DOSFS_FileTimeToUnixTime.
1658 There might be quicker ways to do this in C. Certainly so in
1659 assembler.
1661 Claus Fischer, fischer@iue.tuwien.ac.at
1664 #if SIZEOF_LONG_LONG >= 8
1665 # define USE_LONG_LONG 1
1666 #else
1667 # define USE_LONG_LONG 0
1668 #endif
1670 #if USE_LONG_LONG /* gcc supports long long type */
1672 long long int t = unix_time;
1673 t *= 10000000;
1674 t += 116444736000000000LL;
1675 t += remainder;
1676 filetime->dwLowDateTime = (UINT)t;
1677 filetime->dwHighDateTime = (UINT)(t >> 32);
1679 #else /* ISO version */
1681 UINT a0; /* 16 bit, low bits */
1682 UINT a1; /* 16 bit, medium bits */
1683 UINT a2; /* 32 bit, high bits */
1685 /* Copy the unix time to a2/a1/a0 */
1686 a0 = unix_time & 0xffff;
1687 a1 = (unix_time >> 16) & 0xffff;
1688 /* This is obsolete if unix_time is only 32 bits, but it does not hurt.
1689 Do not replace this by >> 32, it gives a compiler warning and it does
1690 not work. */
1691 a2 = (unix_time >= 0 ? (unix_time >> 16) >> 16 :
1692 ~((~unix_time >> 16) >> 16));
1694 /* Multiply a by 10000000 (a = a2/a1/a0)
1695 Split the factor into 10000 * 1000 which are both less than 0xffff. */
1696 a0 *= 10000;
1697 a1 = a1 * 10000 + (a0 >> 16);
1698 a2 = a2 * 10000 + (a1 >> 16);
1699 a0 &= 0xffff;
1700 a1 &= 0xffff;
1702 a0 *= 1000;
1703 a1 = a1 * 1000 + (a0 >> 16);
1704 a2 = a2 * 1000 + (a1 >> 16);
1705 a0 &= 0xffff;
1706 a1 &= 0xffff;
1708 /* Add the time difference and the remainder */
1709 a0 += 32768 + (remainder & 0xffff);
1710 a1 += 54590 + (remainder >> 16 ) + (a0 >> 16);
1711 a2 += 27111902 + (a1 >> 16);
1712 a0 &= 0xffff;
1713 a1 &= 0xffff;
1715 /* Set filetime */
1716 filetime->dwLowDateTime = (a1 << 16) + a0;
1717 filetime->dwHighDateTime = a2;
1718 #endif
1722 /***********************************************************************
1723 * DOSFS_FileTimeToUnixTime
1725 * Convert a FILETIME format to Unix time.
1726 * If not NULL, 'remainder' contains the fractional part of the filetime,
1727 * in the range of [0..9999999] (even if time_t is negative).
1729 time_t DOSFS_FileTimeToUnixTime( const FILETIME *filetime, DWORD *remainder )
1731 /* Read the comment in the function DOSFS_UnixTimeToFileTime. */
1732 #if USE_LONG_LONG
1734 long long int t = filetime->dwHighDateTime;
1735 t <<= 32;
1736 t += (UINT)filetime->dwLowDateTime;
1737 t -= 116444736000000000LL;
1738 if (t < 0)
1740 if (remainder) *remainder = 9999999 - (-t - 1) % 10000000;
1741 return -1 - ((-t - 1) / 10000000);
1743 else
1745 if (remainder) *remainder = t % 10000000;
1746 return t / 10000000;
1749 #else /* ISO version */
1751 UINT a0; /* 16 bit, low bits */
1752 UINT a1; /* 16 bit, medium bits */
1753 UINT a2; /* 32 bit, high bits */
1754 UINT r; /* remainder of division */
1755 unsigned int carry; /* carry bit for subtraction */
1756 int negative; /* whether a represents a negative value */
1758 /* Copy the time values to a2/a1/a0 */
1759 a2 = (UINT)filetime->dwHighDateTime;
1760 a1 = ((UINT)filetime->dwLowDateTime ) >> 16;
1761 a0 = ((UINT)filetime->dwLowDateTime ) & 0xffff;
1763 /* Subtract the time difference */
1764 if (a0 >= 32768 ) a0 -= 32768 , carry = 0;
1765 else a0 += (1 << 16) - 32768 , carry = 1;
1767 if (a1 >= 54590 + carry) a1 -= 54590 + carry, carry = 0;
1768 else a1 += (1 << 16) - 54590 - carry, carry = 1;
1770 a2 -= 27111902 + carry;
1772 /* If a is negative, replace a by (-1-a) */
1773 negative = (a2 >= ((UINT)1) << 31);
1774 if (negative)
1776 /* Set a to -a - 1 (a is a2/a1/a0) */
1777 a0 = 0xffff - a0;
1778 a1 = 0xffff - a1;
1779 a2 = ~a2;
1782 /* Divide a by 10000000 (a = a2/a1/a0), put the rest into r.
1783 Split the divisor into 10000 * 1000 which are both less than 0xffff. */
1784 a1 += (a2 % 10000) << 16;
1785 a2 /= 10000;
1786 a0 += (a1 % 10000) << 16;
1787 a1 /= 10000;
1788 r = a0 % 10000;
1789 a0 /= 10000;
1791 a1 += (a2 % 1000) << 16;
1792 a2 /= 1000;
1793 a0 += (a1 % 1000) << 16;
1794 a1 /= 1000;
1795 r += (a0 % 1000) * 10000;
1796 a0 /= 1000;
1798 /* If a was negative, replace a by (-1-a) and r by (9999999 - r) */
1799 if (negative)
1801 /* Set a to -a - 1 (a is a2/a1/a0) */
1802 a0 = 0xffff - a0;
1803 a1 = 0xffff - a1;
1804 a2 = ~a2;
1806 r = 9999999 - r;
1809 if (remainder) *remainder = r;
1811 /* Do not replace this by << 32, it gives a compiler warning and it does
1812 not work. */
1813 return ((((time_t)a2) << 16) << 16) + (a1 << 16) + a0;
1814 #endif
1818 /***********************************************************************
1819 * DosDateTimeToFileTime (KERNEL32.76)
1821 BOOL WINAPI DosDateTimeToFileTime( WORD fatdate, WORD fattime, LPFILETIME ft)
1823 struct tm newtm;
1825 newtm.tm_sec = (fattime & 0x1f) * 2;
1826 newtm.tm_min = (fattime >> 5) & 0x3f;
1827 newtm.tm_hour = (fattime >> 11);
1828 newtm.tm_mday = (fatdate & 0x1f);
1829 newtm.tm_mon = ((fatdate >> 5) & 0x0f) - 1;
1830 newtm.tm_year = (fatdate >> 9) + 80;
1831 DOSFS_UnixTimeToFileTime( mktime( &newtm ), ft, 0 );
1832 return TRUE;
1836 /***********************************************************************
1837 * FileTimeToDosDateTime (KERNEL32.111)
1839 BOOL WINAPI FileTimeToDosDateTime( const FILETIME *ft, LPWORD fatdate,
1840 LPWORD fattime )
1842 time_t unixtime = DOSFS_FileTimeToUnixTime( ft, NULL );
1843 struct tm *tm = localtime( &unixtime );
1844 if (fattime)
1845 *fattime = (tm->tm_hour << 11) + (tm->tm_min << 5) + (tm->tm_sec / 2);
1846 if (fatdate)
1847 *fatdate = ((tm->tm_year - 80) << 9) + ((tm->tm_mon + 1) << 5)
1848 + tm->tm_mday;
1849 return TRUE;
1853 /***********************************************************************
1854 * LocalFileTimeToFileTime (KERNEL32.373)
1856 BOOL WINAPI LocalFileTimeToFileTime( const FILETIME *localft,
1857 LPFILETIME utcft )
1859 struct tm *xtm;
1860 DWORD remainder;
1862 /* convert from local to UTC. Perhaps not correct. FIXME */
1863 time_t unixtime = DOSFS_FileTimeToUnixTime( localft, &remainder );
1864 xtm = gmtime( &unixtime );
1865 DOSFS_UnixTimeToFileTime( mktime(xtm), utcft, remainder );
1866 return TRUE;
1870 /***********************************************************************
1871 * FileTimeToLocalFileTime (KERNEL32.112)
1873 BOOL WINAPI FileTimeToLocalFileTime( const FILETIME *utcft,
1874 LPFILETIME localft )
1876 DWORD remainder;
1877 /* convert from UTC to local. Perhaps not correct. FIXME */
1878 time_t unixtime = DOSFS_FileTimeToUnixTime( utcft, &remainder );
1879 #ifdef HAVE_TIMEGM
1880 struct tm *xtm = localtime( &unixtime );
1881 time_t localtime;
1883 localtime = timegm(xtm);
1884 DOSFS_UnixTimeToFileTime( localtime, localft, remainder );
1886 #else
1887 struct tm *xtm,*gtm;
1888 time_t time1,time2;
1890 xtm = localtime( &unixtime );
1891 gtm = gmtime( &unixtime );
1892 time1 = mktime(xtm);
1893 time2 = mktime(gtm);
1894 DOSFS_UnixTimeToFileTime( 2*time1-time2, localft, remainder );
1895 #endif
1896 return TRUE;
1900 /***********************************************************************
1901 * FileTimeToSystemTime (KERNEL32.113)
1903 BOOL WINAPI FileTimeToSystemTime( const FILETIME *ft, LPSYSTEMTIME syst )
1905 struct tm *xtm;
1906 DWORD remainder;
1907 time_t xtime = DOSFS_FileTimeToUnixTime( ft, &remainder );
1908 xtm = gmtime(&xtime);
1909 syst->wYear = xtm->tm_year+1900;
1910 syst->wMonth = xtm->tm_mon + 1;
1911 syst->wDayOfWeek = xtm->tm_wday;
1912 syst->wDay = xtm->tm_mday;
1913 syst->wHour = xtm->tm_hour;
1914 syst->wMinute = xtm->tm_min;
1915 syst->wSecond = xtm->tm_sec;
1916 syst->wMilliseconds = remainder / 10000;
1917 return TRUE;
1920 /***********************************************************************
1921 * QueryDosDeviceA (KERNEL32.413)
1923 * returns array of strings terminated by \0, terminated by \0
1925 DWORD WINAPI QueryDosDeviceA(LPCSTR devname,LPSTR target,DWORD bufsize)
1927 LPSTR s;
1928 char buffer[200];
1930 TRACE("(%s,...)\n", devname ? devname : "<null>");
1931 if (!devname) {
1932 /* return known MSDOS devices */
1933 strcpy(buffer,"CON COM1 COM2 LPT1 NUL ");
1934 while ((s=strchr(buffer,' ')))
1935 *s='\0';
1937 lstrcpynA(target,buffer,bufsize);
1938 return strlen(buffer);
1940 strcpy(buffer,"\\DEV\\");
1941 strcat(buffer,devname);
1942 if ((s=strchr(buffer,':'))) *s='\0';
1943 lstrcpynA(target,buffer,bufsize);
1944 return strlen(buffer);
1948 /***********************************************************************
1949 * QueryDosDeviceW (KERNEL32.414)
1951 * returns array of strings terminated by \0, terminated by \0
1953 DWORD WINAPI QueryDosDeviceW(LPCWSTR devname,LPWSTR target,DWORD bufsize)
1955 LPSTR devnameA = devname?HEAP_strdupWtoA(GetProcessHeap(),0,devname):NULL;
1956 LPSTR targetA = (LPSTR)HeapAlloc(GetProcessHeap(),0,bufsize);
1957 DWORD ret = QueryDosDeviceA(devnameA,targetA,bufsize);
1959 lstrcpynAtoW(target,targetA,bufsize);
1960 if (devnameA) HeapFree(GetProcessHeap(),0,devnameA);
1961 if (targetA) HeapFree(GetProcessHeap(),0,targetA);
1962 return ret;
1966 /***********************************************************************
1967 * SystemTimeToFileTime (KERNEL32.526)
1969 BOOL WINAPI SystemTimeToFileTime( const SYSTEMTIME *syst, LPFILETIME ft )
1971 #ifdef HAVE_TIMEGM
1972 struct tm xtm;
1973 time_t utctime;
1974 #else
1975 struct tm xtm,*local_tm,*utc_tm;
1976 time_t localtim,utctime;
1977 #endif
1979 xtm.tm_year = syst->wYear-1900;
1980 xtm.tm_mon = syst->wMonth - 1;
1981 xtm.tm_wday = syst->wDayOfWeek;
1982 xtm.tm_mday = syst->wDay;
1983 xtm.tm_hour = syst->wHour;
1984 xtm.tm_min = syst->wMinute;
1985 xtm.tm_sec = syst->wSecond; /* this is UTC */
1986 xtm.tm_isdst = -1;
1987 #ifdef HAVE_TIMEGM
1988 utctime = timegm(&xtm);
1989 DOSFS_UnixTimeToFileTime( utctime, ft,
1990 syst->wMilliseconds * 10000 );
1991 #else
1992 localtim = mktime(&xtm); /* now we've got local time */
1993 local_tm = localtime(&localtim);
1994 utc_tm = gmtime(&localtim);
1995 utctime = mktime(utc_tm);
1996 DOSFS_UnixTimeToFileTime( 2*localtim -utctime, ft,
1997 syst->wMilliseconds * 10000 );
1998 #endif
1999 return TRUE;
2002 /***********************************************************************
2003 * DefineDosDeviceA (KERNEL32.182)
2005 BOOL WINAPI DefineDosDeviceA(DWORD flags,LPCSTR devname,LPCSTR targetpath) {
2006 FIXME("(0x%08lx,%s,%s),stub!\n",flags,devname,targetpath);
2007 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2008 return FALSE;