Release 960131
[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 <ctype.h>
9 #include <dirent.h>
10 #include <string.h>
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <sys/stat.h>
14 #include <time.h>
15 #ifdef __svr4__
16 #include <sys/statfs.h>
17 #endif
18
19 #include "windows.h"
20 #include "dos_fs.h"
21 #include "drive.h"
22 #include "file.h"
23 #include "msdos.h"
24 #include "stddebug.h"
25 #include "debug.h"
26
27 /* Chars we don't want to see in DOS file names */
28 #define INVALID_DOS_CHARS  "*?<>|\"+=,;[] \345"
29
30 static const char *DOSFS_Devices[][2] =
31 {
32     { "CON",  "" },
33     { "PRN",  "" },
34     { "NUL",  "/dev/null" },
35     { "AUX",  "" },
36     { "LPT1", "" },
37     { "LPT2", "" },
38     { "LPT3", "" },
39     { "LPT4", "" },
40     { "COM1", "" },
41     { "COM2", "" },
42     { "COM3", "" },
43     { "COM4", "" }
44 };
45
46 #define GET_DRIVE(path) \
47     (((path)[1] == ':') ? toupper((path)[0]) - 'A' : DOSFS_CurDrive)
48
49     /* DOS extended error status */
50 WORD DOS_ExtendedError;
51 BYTE DOS_ErrorClass;
52 BYTE DOS_ErrorAction;
53 BYTE DOS_ErrorLocus;
54
55
56 /***********************************************************************
57  *           DOSFS_ValidDOSName
58  *
59  * Return 1 if Unix file 'name' is also a valid MS-DOS name
60  * (i.e. contains only valid DOS chars, lower-case only, fits in 8.3 format).
61  * File name can be terminated by '\0', '\\' or '/'.
62  */
63 static int DOSFS_ValidDOSName( const char *name )
64 {
65     static const char invalid_chars[] = INVALID_DOS_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
66     const char *p = name;
67     int len = 0;
68
69     if (*p == '.')
70     {
71         /* Check for "." and ".." */
72         p++;
73         if (*p == '.') p++;
74         /* All other names beginning with '.' are invalid */
75         return (IS_END_OF_NAME(*p));
76     }
77     while (!IS_END_OF_NAME(*p))
78     {
79         if (strchr( invalid_chars, *p )) return 0;  /* Invalid char */
80         if (*p == '.') break;  /* Start of the extension */
81         if (++len > 8) return 0;  /* Name too long */
82         p++;
83     }
84     if (*p != '.') return 1;  /* End of name */
85     p++;
86     if (IS_END_OF_NAME(*p)) return 0;  /* Empty extension not allowed */
87     len = 0;
88     while (!IS_END_OF_NAME(*p))
89     {
90         if (strchr( invalid_chars, *p )) return 0;  /* Invalid char */
91         if (*p == '.') return 0;  /* Second extension not allowed */
92         if (++len > 3) return 0;  /* Extension too long */
93         p++;
94     }
95     return 1;
96 }
97
98
99 /***********************************************************************
100  *           DOSFS_CheckDotDot
101  *
102  * Remove all '.' and '..' at the beginning of 'name'.
103  */
104 static const char * DOSFS_CheckDotDot( const char *name, char *buffer,
105                                        char sep , int *len )
106 {
107     char *p = buffer + strlen(buffer);
108
109     while (*name == '.')
110     {
111         if (IS_END_OF_NAME(name[1]))
112         {
113             name++;
114             while ((*name == '\\') || (*name == '/')) name++;
115         }
116         else if ((name[1] == '.') && IS_END_OF_NAME(name[2]))
117         {
118             name += 2;
119             while ((*name == '\\') || (*name == '/')) name++;
120             while ((p > buffer) && (*p != sep)) { p--; (*len)++; }
121             *p = '\0';  /* Remove trailing separator */
122         }
123         else break;
124     }
125     return name;
126 }
127
128
129 /***********************************************************************
130  *           DOSFS_ToDosFCBFormat
131  *
132  * Convert a file name to DOS FCB format (8+3 chars, padded with blanks),
133  * expanding wild cards and converting to upper-case in the process.
134  * File name can be terminated by '\0', '\\' or '/'.
135  * Return NULL if the name is not a valid DOS name.
136  */
137 const char *DOSFS_ToDosFCBFormat( const char *name )
138 {
139     static const char invalid_chars[] = INVALID_DOS_CHARS;
140     static char buffer[12];
141     const char *p = name;
142     int i;
143
144     /* Check for "." and ".." */
145     if (*p == '.')
146     {
147         p++;
148         strcpy( buffer, ".          " );
149         if (*p == '.') p++;
150         return (!*p || (*p == '/') || (*p == '\\')) ? buffer : NULL;
151     }
152
153     for (i = 0; i < 8; i++)
154     {
155         switch(*p)
156         {
157         case '\0':
158         case '\\':
159         case '/':
160         case '.':
161             buffer[i] = ' ';
162             break;
163         case '?':
164             p++;
165             /* fall through */
166         case '*':
167             buffer[i] = '?';
168             break;
169         default:
170             if (strchr( invalid_chars, *p )) return NULL;
171             buffer[i] = toupper(*p);
172             p++;
173             break;
174         }
175     }
176
177     if (*p == '*')
178     {
179         /* Skip all chars after wildcard up to first dot */
180         while (*p && (*p != '/') && (*p != '\\') && (*p != '.')) p++;
181     }
182     else
183     {
184         /* Check if name too long */
185         if (*p && (*p != '/') && (*p != '\\') && (*p != '.')) return NULL;
186     }
187     if (*p == '.') p++;  /* Skip dot */
188
189     for (i = 8; i < 11; i++)
190     {
191         switch(*p)
192         {
193         case '\0':
194         case '\\':
195         case '/':
196             buffer[i] = ' ';
197             break;
198         case '.':
199             return NULL;  /* Second extension not allowed */
200         case '?':
201             p++;
202             /* fall through */
203         case '*':
204             buffer[i] = '?';
205             break;
206         default:
207             if (strchr( invalid_chars, *p )) return NULL;
208             buffer[i] = toupper(*p);
209             p++;
210             break;
211         }
212     }
213     buffer[11] = '\0';
214     return buffer;
215 }
216
217
218 /***********************************************************************
219  *           DOSFS_ToDosDTAFormat
220  *
221  * Convert a file name from FCB to DTA format (name.ext, null-terminated)
222  * converting to upper-case in the process.
223  * File name can be terminated by '\0', '\\' or '/'.
224  * Return NULL if the name is not a valid DOS name.
225  */
226 const char *DOSFS_ToDosDTAFormat( const char *name )
227 {
228     static char buffer[13];
229     char *p;
230
231     memcpy( buffer, name, 8 );
232     for (p = buffer + 8; (p > buffer) && (p[-1] == ' '); p--);
233     *p++ = '.';
234     memcpy( p, name + 8, 3 );
235     for (p += 3; p[-1] == ' '; p--);
236     if (p[-1] == '.') p--;
237     *p = '\0';
238     return buffer;
239 }
240
241
242 /***********************************************************************
243  *           DOSFS_Match
244  *
245  * Check a DOS file name against a mask (both in FCB format).
246  */
247 static int DOSFS_Match( const char *mask, const char *name )
248 {
249     int i;
250     for (i = 11; i > 0; i--, mask++, name++)
251         if ((*mask != '?') && (*mask != *name)) return 0;
252     return 1;
253 }
254
255
256 /***********************************************************************
257  *           DOSFS_ToDosDateTime
258  *
259  * Convert a Unix time in the DOS date/time format.
260  */
261 void DOSFS_ToDosDateTime( time_t *unixtime, WORD *pDate, WORD *pTime )
262 {
263     struct tm *tm = localtime( unixtime );
264     if (pTime)
265         *pTime = (tm->tm_hour << 11) + (tm->tm_min << 5) + (tm->tm_sec / 2);
266     if (pDate)
267         *pDate = ((tm->tm_year - 80) << 9) + ((tm->tm_mon + 1) << 5)
268                  + tm->tm_mday;
269 }
270
271
272 /***********************************************************************
273  *           DOSFS_Hash
274  *
275  * Transform a Unix file name into a hashed DOS name. If the name is a valid
276  * DOS name, it is converted to upper-case; otherwise it is replaced by a
277  * hashed version that fits in 8.3 format.
278  * File name can be terminated by '\0', '\\' or '/'.
279  */
280 static const char *DOSFS_Hash( const char *name, int dir_format )
281 {
282     static const char invalid_chars[] = INVALID_DOS_CHARS "~.";
283     static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
284
285     static char buffer[13];
286     const char *p, *ext;
287     char *dst;
288     unsigned short hash;
289     int i;
290
291     if (dir_format) strcpy( buffer, "           " );
292
293     if (DOSFS_ValidDOSName( name ))
294     {
295         /* Check for '.' and '..' */
296         if (*name == '.')
297         {
298             buffer[0] = '.';
299             if (!dir_format) buffer[1] = buffer[2] = '\0';
300             if (name[1] == '.') buffer[1] = '.';
301             return buffer;
302         }
303
304         /* Simply copy the name, converting to uppercase */
305
306         for (dst = buffer; !IS_END_OF_NAME(*name) && (*name != '.'); name++)
307             *dst++ = toupper(*name);
308         if (*name == '.')
309         {
310             if (dir_format) dst = buffer + 8;
311             else *dst++ = '.';
312             for (name++; !IS_END_OF_NAME(*name); name++)
313                 *dst++ = toupper(*name);
314         }
315         if (!dir_format) *dst = '\0';
316     }
317     else
318     {
319         /* Compute the hash code of the file name */
320         /* If you know something about hash functions, feel free to */
321         /* insert a better algorithm here... */
322         for (p = name, hash = 0xbeef; !IS_END_OF_NAME(p[1]); p++)
323             hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
324         hash = (hash << 3) ^ (hash >> 5) ^ *p;  /* Last character */
325         
326         /* Find last dot for start of the extension */
327         for (p = name+1, ext = NULL; !IS_END_OF_NAME(*p); p++)
328             if (*p == '.') ext = p;
329         if (ext && IS_END_OF_NAME(ext[1]))
330             ext = NULL;  /* Empty extension ignored */
331
332         /* Copy first 4 chars, replacing invalid chars with '_' */
333         for (i = 4, p = name, dst = buffer; i > 0; i--, p++)
334         {
335             if (IS_END_OF_NAME(*p) || (p == ext)) break;
336             *dst++ = strchr( invalid_chars, *p ) ? '_' : toupper(*p);
337         }
338         /* Pad to 5 chars with '~' */
339         while (i-- >= 0) *dst++ = '~';
340
341         /* Insert hash code converted to 3 ASCII chars */
342         *dst++ = hash_chars[(hash >> 10) & 0x1f];
343         *dst++ = hash_chars[(hash >> 5) & 0x1f];
344         *dst++ = hash_chars[hash & 0x1f];
345
346         /* Copy the first 3 chars of the extension (if any) */
347         if (ext)
348         {
349             if (!dir_format) *dst++ = '.';
350             for (i = 3, ext++; (i > 0) && !IS_END_OF_NAME(*ext); i--, ext++)
351                 *dst++ = toupper(*ext);
352         }
353         if (!dir_format) *dst = '\0';
354     }
355     return buffer;
356 }
357
358
359 /***********************************************************************
360  *           DOSFS_FindUnixName
361  *
362  * Find the Unix file name in a given directory that corresponds to
363  * a file name (either in Unix or DOS format).
364  * File name can be terminated by '\0', '\\' or '/'.
365  * Return 1 if OK, 0 if no file name matches.
366  */
367 static int DOSFS_FindUnixName( const char *path, const char *name,
368                                char *buffer, int maxlen )
369 {
370     DIR *dir;
371     struct dirent *dirent;
372
373     const char *dos_name = DOSFS_ToDosFCBFormat( name );
374     const char *p = strchr( name, '/' );
375     int len = p ? (int)(p - name) : strlen(name);
376
377     dprintf_dosfs( stddeb, "DOSFS_FindUnixName: %s %s\n", path, name );
378
379     if ((p = strchr( name, '\\' ))) len = MIN( (int)(p - name), len );
380
381     if (!(dir = opendir( path )))
382     {
383         dprintf_dosfs( stddeb, "DOSFS_FindUnixName(%s,%s): can't open dir\n",
384                        path, name );
385         return 0;
386     }
387     while ((dirent = readdir( dir )) != NULL)
388     {
389         /* Check against Unix name */
390         if ((len == strlen(dirent->d_name) &&
391              !memcmp( dirent->d_name, name, len ))) break;
392         if (dos_name)
393         {
394             /* Check against hashed DOS name */
395             const char *hash_name = DOSFS_Hash( dirent->d_name, TRUE );
396             if (!strcmp( dos_name, hash_name )) break;
397         }
398     }
399     if (dirent) lstrcpyn( buffer, dirent->d_name, maxlen );
400     closedir( dir );
401     dprintf_dosfs( stddeb, "DOSFS_FindUnixName(%s,%s) -> %s\n",
402                    path, name, dirent ? buffer : "** Not found **" );
403     return (dirent != NULL);
404 }
405
406
407 /***********************************************************************
408  *           DOSFS_IsDevice
409  *
410  * Check if a DOS file name represents a DOS device. Returns the name
411  * of the associated Unix device, or NULL if not found.
412  */
413 const char *DOSFS_IsDevice( const char *name )
414 {
415     int i;
416     const char *p;
417
418     if (name[1] == ':') name += 2;
419     if ((p = strrchr( name, '/' ))) name = p + 1;
420     if ((p = strrchr( name, '\\' ))) name = p + 1;
421     for (i = 0; i < sizeof(DOSFS_Devices)/sizeof(DOSFS_Devices[0]); i++)
422     {
423         const char *dev = DOSFS_Devices[i][0];
424         if (!lstrncmpi( dev, name, strlen(dev) ))
425         {
426             p = name + strlen( dev );
427             if (*p == ':') p++;
428             if (!*p || (*p == '.')) return DOSFS_Devices[i][1];
429         }
430     }
431     return NULL;
432 }
433
434
435 /***********************************************************************
436  *           DOSFS_GetUnixFileName
437  *
438  * Convert a file name (DOS or mixed DOS/Unix format) to a valid Unix name.
439  * Return NULL if one of the path components does not exist. The last path
440  * component is only checked if 'check_last' is non-zero.
441  */
442 const char * DOSFS_GetUnixFileName( const char * name, int check_last )
443 {
444     static char buffer[MAX_PATHNAME_LEN];
445     int drive, len, found;
446     char *p, *root;
447
448     dprintf_dosfs( stddeb, "DOSFS_GetUnixFileName: %s\n", name );
449     if (name[1] == ':')
450     {
451         drive = toupper(name[0]) - 'A';
452         name += 2;
453     }
454     else if (name[0] == '/') /* Absolute Unix path? */
455     {
456         if ((drive = DRIVE_FindDriveRoot( &name )) == -1)
457         {
458             fprintf( stderr, "Warning: %s not accessible from a DOS drive\n",
459                      name );
460             /* Assume it really was a DOS name */
461             drive = DRIVE_GetCurrentDrive();            
462         }
463     }
464     else drive = DRIVE_GetCurrentDrive();
465
466     if (!DRIVE_IsValid(drive))
467     {
468         DOS_ERROR( ER_InvalidDrive, EC_MediaError, SA_Abort, EL_Disk );
469         return NULL;
470     }
471     lstrcpyn( buffer, DRIVE_GetRoot(drive), MAX_PATHNAME_LEN );
472     if (buffer[1]) root = buffer + strlen(buffer);
473     else root = buffer;  /* root directory */
474
475     if ((*name == '\\') || (*name == '/'))
476     {
477         while ((*name == '\\') || (*name == '/')) name++;
478     }
479     else
480     {
481         lstrcpyn( root + 1, DRIVE_GetUnixCwd(drive),
482                   MAX_PATHNAME_LEN - (int)(root - buffer) - 1 );
483         if (root[1]) *root = '/';
484     }
485
486     p = buffer[1] ? buffer + strlen(buffer) : buffer;
487     len = MAX_PATHNAME_LEN - strlen(buffer);
488     found = 1;
489     while (*name && found)
490     {
491         const char *newname = DOSFS_CheckDotDot( name, root, '/', &len );
492         if (newname != name)
493         {
494             p = root + strlen(root);
495             name = newname;
496             continue;
497         }
498         if (len <= 1)
499         {
500             DOS_ERROR( ER_PathNotFound, EC_NotFound, SA_Abort, EL_Disk );
501             return NULL;
502         }
503         if ((found = DOSFS_FindUnixName( buffer, name, p+1, len-1 )))
504         {
505             *p = '/';
506             len -= strlen(p);
507             p += strlen(p);
508             while (!IS_END_OF_NAME(*name)) name++;
509         }
510         else if (!check_last)
511         {
512             *p++ = '/';
513             for (len--; !IS_END_OF_NAME(*name) && (len > 1); name++, len--)
514                 *p++ = tolower(*name);
515             *p = '\0';
516         }
517         while ((*name == '\\') || (*name == '/')) name++;
518     }
519     if (!found)
520     {
521         if (check_last)
522         {
523             DOS_ERROR( ER_FileNotFound, EC_NotFound, SA_Abort, EL_Disk );
524             return NULL;
525         }
526         if (*name)  /* Not last */
527         {
528             DOS_ERROR( ER_PathNotFound, EC_NotFound, SA_Abort, EL_Disk );
529             return NULL;
530         }
531     }
532     if (!buffer[0]) strcpy( buffer, "/" );
533     dprintf_dosfs( stddeb, "DOSFS_GetUnixFileName: returning %s\n", buffer );
534     return buffer;
535 }
536
537
538 /***********************************************************************
539  *           DOSFS_GetDosTrueName
540  *
541  * Convert a file name (DOS or Unix format) to a complete DOS name.
542  * Return NULL if the path name is invalid or too long.
543  * The unix_format flag is a hint that the file name is in Unix format.
544  */
545 const char * DOSFS_GetDosTrueName( const char *name, int unix_format )
546 {
547     static char buffer[MAX_PATHNAME_LEN];
548     int drive, len;
549     char *p;
550
551     dprintf_dosfs( stddeb, "DOSFS_GetDosTrueName(%s,%d)\n", name, unix_format);
552     if (name[1] == ':')
553     {
554         drive = toupper(name[0]) - 'A';
555         name += 2;
556     }
557     else if (name[0] == '/') /* Absolute Unix path? */
558     {
559         if ((drive = DRIVE_FindDriveRoot( &name )) == -1)
560         {
561             fprintf( stderr, "Warning: %s not accessible from a DOS drive\n",
562                      name );
563             /* Assume it really was a DOS name */
564             drive = DRIVE_GetCurrentDrive();            
565         }
566     }
567     else drive = DRIVE_GetCurrentDrive();
568
569     if (!DRIVE_IsValid(drive))
570     {
571         DOS_ERROR( ER_InvalidDrive, EC_MediaError, SA_Abort, EL_Disk );
572         return NULL;
573     }
574
575     p = buffer;
576     *p++ = 'A' + drive;
577     *p++ = ':';
578     if (IS_END_OF_NAME(*name))
579     {
580         while ((*name == '\\') || (*name == '/')) name++;
581     }
582     else
583     {
584         *p++ = '\\';
585         lstrcpyn( p, DRIVE_GetDosCwd(drive), sizeof(buffer) - 3 );
586         if (*p) p += strlen(p); else p--;
587     }
588     *p = '\0';
589     len = MAX_PATHNAME_LEN - (int)(p - buffer);
590
591     while (*name)
592     {
593         const char *newname = DOSFS_CheckDotDot( name, buffer+2, '\\', &len );
594         if (newname != name)
595         {
596             p = buffer + strlen(buffer);
597             name = newname;
598             continue;
599         }
600         if (len <= 1)
601         {
602             DOS_ERROR( ER_PathNotFound, EC_NotFound, SA_Abort, EL_Disk );
603             return NULL;
604         }
605         *p++ = '\\';
606         if (unix_format)  /* Hash it into a DOS name */
607         {
608             lstrcpyn( p, DOSFS_Hash( name, FALSE ), len );
609             len -= strlen(p);
610             p += strlen(p);
611             while (!IS_END_OF_NAME(*name)) name++;
612         }
613         else  /* Already DOS format, simply upper-case it */
614         {
615             while (!IS_END_OF_NAME(*name) && (len > 1))
616             {
617                 *p++ = toupper(*name);
618                 name++;
619                 len--;
620             }
621             *p = '\0';
622         }
623         while ((*name == '\\') || (*name == '/')) name++;
624     }
625     if (!buffer[2])
626     {
627         buffer[2] = '\\';
628         buffer[3] = '\0';
629     }
630     dprintf_dosfs( stddeb, "DOSFS_GetDosTrueName: returning %s\n", buffer );
631     return buffer;
632 }
633
634
635 /***********************************************************************
636  *           DOSFS_FindNext
637  *
638  * Find the next matching file. Return the number of entries read to find
639  * the matching one, or 0 if no more entries.
640  */
641 int DOSFS_FindNext( const char *path, const char *mask, int drive,
642                     BYTE attr, int skip, DOS_DIRENT *entry )
643 {
644     static DIR *dir = NULL;
645     struct dirent *dirent;
646     int count = 0;
647     static char buffer[MAX_PATHNAME_LEN];
648     static int cur_pos = 0;
649     char *p;
650     const char *hash_name;
651     
652     if ((attr & ~(FA_UNUSED | FA_ARCHIVE | FA_RDONLY)) == FA_LABEL)
653     {
654         time_t now = time(NULL);
655         if (skip) return 0;
656         strcpy( entry->name, DRIVE_GetLabel( drive ) );
657         entry->attr = FA_LABEL;
658         entry->size = 0;
659         DOSFS_ToDosDateTime( &now, &entry->date, &entry->time );
660         return 1;
661     }
662
663     /* Check the cached directory */
664     if (dir && !strcmp( buffer, path ) && (cur_pos <= skip)) skip -= cur_pos;
665     else  /* Not in the cache, open it anew */
666     {
667         dprintf_dosfs( stddeb, "DOSFS_FindNext: cache miss, path=%s skip=%d buf=%s cur=%d\n",
668                        path, skip, buffer, cur_pos );
669         cur_pos = skip;
670         if (dir) closedir(dir);
671         if (!(dir = opendir( path ))) return 0;
672         lstrcpyn( buffer, path, sizeof(buffer) - 1 );
673     }
674     strcat( buffer, "/" );
675     p = buffer + strlen(buffer);
676     attr |= FA_UNUSED | FA_ARCHIVE | FA_RDONLY;
677
678     while ((dirent = readdir( dir )) != NULL)
679     {
680         if (skip-- > 0) continue;
681         count++;
682         hash_name = DOSFS_Hash( dirent->d_name, TRUE );
683         if (!DOSFS_Match( mask, hash_name )) continue;
684         lstrcpyn( p, dirent->d_name, sizeof(buffer) - (int)(p - buffer) );
685
686         if (!FILE_Stat( buffer, &entry->attr, &entry->size,
687                         &entry->date, &entry->time ))
688         {
689             fprintf( stderr, "DOSFS_FindNext: can't stat %s\n", buffer );
690             continue;
691         }
692         if (entry->attr & ~attr) continue;
693         strcpy( entry->name, hash_name );
694         lstrcpyn( entry->unixname, dirent->d_name, sizeof(entry->unixname) );
695         dprintf_dosfs( stddeb, "DOSFS_FindNext: returning %s %02x %ld\n",
696                        entry->name, entry->attr, entry->size );
697         cur_pos += count;
698         p[-1] = '\0';  /* Remove trailing slash in buffer */
699         return count;
700     }
701     closedir( dir );
702     dir = NULL;
703     return 0;  /* End of directory */
704 }