Debian Codegraph @

terps/tads/tads2/osnoui.c

raw symbols SCIP
1 #ifdef RCSID
2 static char RCSid[] =
3 "$Header: d:/cvsroot/tads/TADS2/OSNOUI.C,v 1.3 1999/07/11 00:46:30 MJRoberts Exp $";
4 #endif
5
6 /*
7 * Copyright (c) 1997, 2002 Michael J. Roberts. All Rights Reserved.
8 *
9 * Please see the accompanying license file, LICENSE.TXT, for information
10 * on using and copying this software.
11 */
12 /*
13 Name
14 osnoui.c - general-purpose implementations of OS routines with no UI
15 Function
16 This file provides implementations for certain OS routines that have
17 no UI component and can be implemented in general for a range of
18 operating systems.
19 Notes
20
21 Modified
22 04/11/99 CNebel - Improve const-ness; fix C++ errors.
23 11/02/97 MJRoberts - Creation
24 */
25
26 #include <stdio.h>
27 #ifdef MSDOS
28 #include <io.h>
29 #endif
30 #include <stdlib.h>
31 #include <string.h>
32 #include <stdarg.h>
33 #include <ctype.h>
34 #include <time.h>
35 #include <sys/stat.h>
36
37 #ifdef T_WIN32
38 #include <windows.h>
39 #include <direct.h>
40 #endif
41
42 #include "os.h"
43 #include "run.h"
44
45 /* ------------------------------------------------------------------------ */
46 /*
47 * Safe strcpy
48 */
49 void safe_strcpyl(char *dst, size_t dstlen,
50 const char *src, size_t srclen)
51 {
52 size_t copylen;
53
54 /* do nothing if there's no output buffer */
55 if (dst == 0 || dstlen == 0)
56 return;
57
58 /* do nothing if the source and destination buffers are the same */
59 if (dst == src)
60 return;
61
62 /* use an empty string if given a null string */
63 if (src == 0)
64 src = "";
65
66 /*
67 * figure the copy length - use the smaller of the actual string size
68 * or the available buffer size, minus one for the null terminator
69 */
70 copylen = srclen;
71 if (copylen > dstlen - 1)
72 copylen = dstlen - 1;
73
74 /* copy the string (or as much as we can) */
75 memcpy(dst, src, copylen);
76
77 /* null-terminate it */
78 dst[copylen] = '\0';
79 }
80
81 void safe_strcpy(char *dst, size_t dstlen, const char *src)
82 {
83 safe_strcpyl(dst, dstlen, src, src != 0 ? strlen(src) : 0);
84 }
85
86
87
88 /* ------------------------------------------------------------------------ */
89 #define ispathchar(c) \
90 ((c) == OSPATHCHAR || ((c) != 0 && strchr(OSPATHALT, c) != 0))
91
92 /*
93 * Ports with MS-DOS-like file systems (Atari ST, OS/2, Macintosh, and,
94 * of course, MS-DOS itself) can use the os_defext and os_remext
95 * routines below by defining USE_DOSEXT. Unix and VMS filenames will
96 * also be parsed correctly by these implementations, but untranslated
97 * VMS logical names may not be.
98 */
99
100 #ifdef USE_DOSEXT
101 /*
102 * os_defext(fn, ext) should append the default extension ext to the
103 * filename in fn. It is assumed that the buffer at fn is big enough to
104 * hold the added characters in the extension. The result should be
105 * null-terminated. When an extension is already present in the
106 * filename at fn, no action should be taken. On systems without an
107 * analogue of extensions, this routine should do nothing.
108 */
109 #ifndef OSNOUI_OMIT_OS_DEFEXT
110 void os_defext(char *fn, const char *ext)
111 {
112 char *p;
113
114 /*
115 * Scan backwards from the end of the string, looking for the last
116 * dot ('.') in the filename. Stop if we encounter a path separator
117 * character of some kind, because that means we reached the start
118 * of the filename without encountering a period.
119 */
120 p = fn + strlen(fn);
121 while (p > fn)
122 {
123 /* on to the previous character */
124 p--;
125
126 /*
127 * if it's a period, return without doing anything - this
128 * filename already has an extension, so don't apply a default
129 */
130 if (*p == '.')
131 return;
132
133 /*
134 * if this is a path separator character, we're no longer in the
135 * filename, so stop looking for a period
136 */
137 if (ispathchar(*p))
138 break;
139 }
140
141 /* we didn't find an extension - add the dot and the extension */
142 strcat(fn, ".");
143 strcat(fn, ext);
144 }
145 #endif
146
147 /*
148 * Add an extension, even if the filename currently has one
149 */
150 #ifndef OSNOUI_OMIT_OS_ADDEXT
151 void os_addext(char *fn, const char *ext)
152 {
153 if (strlen(fn) + 1 + strlen(ext) + 1 < OSFNMAX)
154 {
155 strcat(fn, ".");
156 strcat(fn, ext);
157 }
158 }
159 #endif
160
161 /*
162 * os_remext(fn) removes the extension from fn, if present. The buffer
163 * at fn should be modified in place. If no extension is present, no
164 * action should be taken. For systems without an analogue of
165 * extensions, this routine should do nothing.
166 */
167 #ifndef OSNOUI_OMIT_OS_REMEXT
168 void os_remext(char *fn)
169 {
170 char *p;
171
172 /* scan backwards from the end of the string, looking for a dot */
173 p = fn + strlen(fn);
174 while ( p>fn )
175 {
176 /* move to the previous character */
177 p--;
178
179 /* if it's a period, we've found the extension */
180 if ( *p=='.' )
181 {
182 /* terminate the string here to remove the extension */
183 *p = '\0';
184
185 /* we're done */
186 return;
187 }
188
189 /*
190 * if this is a path separator, there's no extension, so we can
191 * stop looking
192 */
193 if (ispathchar(*p))
194 return;
195 }
196 }
197 #endif
198
199 /*
200 * Get a pointer to the root name portion of a filename. Note that this
201 * implementation is included in the ifdef USE_DOSEXT section, since it
202 * seems safe to assume that if a platform has filenames that are
203 * sufficiently DOS-like for the extension parsing routines, the same
204 * will be true of path parsing.
205 */
206 #ifndef OSNOUI_OMIT_OS_GET_ROOTNAME
207 char *os_get_root_name(const char *buf)
208 {
209 const char *rootname;
210 #ifdef MSDOS
211 const char *orig = buf;
212 #endif
213
214 /* scan the name for path separators */
215 for (rootname = buf ; *buf != '\0' ; ++buf)
216 {
217 /* if this is a path separator, remember it */
218 if (ispathchar(*buf))
219 {
220 #ifdef MSDOS
221 /*
222 * if this is the last character in the name, and it's beyond
223 * the second character, assume it's a device name colon rather
224 * than a path separator colon
225 */
226 if (*buf == ':' && buf > orig + 1 && buf[1] == '\0')
227 continue;
228 #endif
229
230 /*
231 * It's a path separators - for now, assume the root will
232 * start at the next character after this separator. If we
233 * find another separator later, we'll forget about this one
234 * and use the later one instead.
235 */
236 rootname = buf + 1;
237 }
238 }
239
240 /*
241 * Return the last root name candidate that we found. (Cast it to
242 * non-const for the caller's convenience: *we're* not allowed to
243 * modify this buffer, but the caller is certainly free to pass in a
244 * writable buffer, and they're free to write to it after we return.)
245 */
246 return (char *)rootname;
247 }
248 #endif
249
250 /*
251 * Extract the path from a filename
252 */
253 #ifndef OSNOUI_OMIT_OS_GET_PATH_NAME
254 void os_get_path_name(char *pathbuf, size_t pathbuflen, const char *fname)
255 {
256 const char *lastsep;
257 const char *p;
258 size_t len;
259 int root_path;
260
261 #ifdef MSDOS
262 /*
263 * Special case for DOS/Windows: If we have a bare drive letter, or an
264 * explicit current directory path on a drive letter (X:.), there is no
265 * parent directory. Our normal algorithm won't catch this because of
266 * our special handling that adds the working directory to a bare drive
267 * letter (turning "X:" into "X:.").
268 */
269 if (isalpha(fname[0]) && fname[1] == ':'
270 && (fname[2] == '\0' || (fname[2] == '.' && fname[3] == '\0')))
271 {
272 if (pathbuflen > 0)
273 pathbuf[0] = '\0';
274 return;
275 }
276 #endif
277
278 /* find the last separator in the filename */
279 for (p = fname, lastsep = fname ; *p != '\0' ; ++p)
280 {
281 /*
282 * If it's a path separator character, remember it as the last one
283 * we've found so far. However, don't count it if it's the last
284 * separator - i.e., if only more path separators follow.
285 */
286 if (ispathchar(*p))
287 {
288 const char *q;
289
290 /* skip any immediately adjacent path separators */
291 for (q = p + 1 ; *q != '\0' && ispathchar(*q) ; ++q) ;
292
293 /* if we found more following, *p is the last separator */
294 if (*q != '\0')
295 lastsep = p;
296 }
297 }
298
299 /* get the length of the prefix, not including the separator */
300 len = lastsep - fname;
301
302 /*
303 * Normally, we don't include the last path separator in the path; for
304 * example, on Unix, the path of "/a/b/c" is "/a/b", not "/a/b/".
305 * However, on Unix/DOS-like file systems, a root path *does* require
306 * the last path separator: the path of "/a" is "/", not an empty
307 * string. So, we need to check to see if the file is in a root path,
308 * and if so, include the final path separator character in the path.
309 */
310 for (p = fname, root_path = TRUE ; p != lastsep ; ++p)
311 {
312 /*
313 * if this is NOT a path separator character, we don't have all
314 * path separator characters before the filename, so we don't have
315 * a root path
316 */
317 if (!ispathchar(*p))
318 {
319 /* note that we don't have a root path */
320 root_path = FALSE;
321
322 /* no need to look any further */
323 break;
324 }
325 }
326
327 /* if we have a root path, keep the final path separator in the path */
328 if (root_path && ispathchar(fname[len]))
329 ++len;
330
331 #ifdef MSDOS
332 /*
333 * On DOS, we have a special case: if the path is of the form "x:\",
334 * where "x" is any letter, then we have a root filename and we want to
335 * include the backslash.
336 */
337 if (lastsep == fname + 2
338 && isalpha(fname[0]) && fname[1] == ':' && fname[2] == '\\')
339 {
340 /* we have an absolute path - use the full "x:\" sequence */
341 len = 3;
342
343 /* if this was the entire path name, we have no parent */
344 if (fname[3] == '\0')
345 len = 0;
346 }
347
348 /* if the path is of the form X:, keep the trailing colon */
349 if (len == 1 && *lastsep == ':')
350 len = 2;
351 #endif
352
353 /* make sure it fits in our buffer (with a null terminator) */
354 if (len > pathbuflen - 1)
355 len = pathbuflen - 1;
356
357 /* copy it and null-terminate it */
358 memcpy(pathbuf, fname, len);
359 pathbuf[len] = '\0';
360
361 #ifdef MSDOS
362 /*
363 * Another DOS special case: if the path is of the form "X:", with no
364 * directory element, it refers to the current working directory on
365 * drive X: (DOS/Win keep a working directory per drive letter). To
366 * make this more explicit, change it to "X:.", so that we actually
367 * have the name of a directory.
368 */
369 if (lastsep == fname + 1 && pathbuf[1] == ':' && pathbuflen >= 4)
370 {
371 pathbuf[2] = '.';
372 pathbuf[3] = '\0';
373 }
374 #endif
375 }
376 #endif
377
378 /*
379 * Canonicalize a path: remove ".." and "." relative elements
380 */
381 #if !defined(OSNOUI_OMIT_OS_BUILD_FULL_PATH) && !defined(OSNOUI_OMIT_OS_COMBINE_PATHS)
382 void canonicalize_path(char *path)
383 {
384 char *orig = path;
385 char *p;
386 char *ele, *prvele;
387 char *trimpt = 0;
388 int dotcnt = 0;
389
390 /*
391 * First, skip the root element. This is unremovable. For Unix, the
392 * root element is simply a leading slash (or series of slashes). For
393 * DOS/Win, we can also have drive letters and UNC paths (as in
394 * \\MACHINE\ROOT).
395 */
396 #ifdef MSDOS
397 /* check for a UNC path or drive letter */
398 if (path[0] == '\\' && path[1] == '\\')
399 {
400 /* skip to the \ after the machine name */
401 for (path += 2 ; *path != '\0' && *path != '\\' && *path != '/' ;
402 ++path) ;
403
404 /*
405 * further skip to the slash after that, as the drive name is part
406 * of the root as well
407 */
408 if (*path != '\0')
409 {
410 /* find the slash */
411 for (++path ; *path != '\0' && *path != '\\' && *path != '/' ;
412 ++path) ;
413
414 /* we can trim this slash if the path ends here */
415 trimpt = path;
416 }
417 }
418 else if (path[1] == ':' && isalpha(path[0]))
419 {
420 /* skip the drive letter */
421 path += 2;
422 }
423 #endif
424
425 /* skip leading slashes */
426 for ( ; ispathchar(*path) ; ++path) ;
427
428 /*
429 * if we didn't choose a different trim starting point, trim from after
430 * the root slashes
431 */
432 if (trimpt == 0)
433 trimpt = path;
434
435 /* scan elements */
436 for (p = ele = path, prvele = 0 ; *ele != '\0' ; )
437 {
438 size_t ele_len;
439
440 /* find the end of the current element */
441 for ( ; *p != '\0' && !ispathchar(*p) ; ++p) ;
442 ele_len = p - ele;
443
444 /* skip adjacent path separators */
445 for ( ; ispathchar(*p) ; ++p) ;
446
447 /* check for special elements */
448 if (ele_len == 1 && ele[0] == '.')
449 {
450 /* '.' -> current directory; simply remove this element */
451 ++dotcnt;
452 memmove(ele, p, strlen(p) + 1);
453
454 /* revisit this element */
455 p = ele;
456 }
457 else if (ele_len == 2 && ele[0] == '.' && ele[1] == '.')
458 {
459 /*
460 * '..' -> parent directory; remove this element and the
461 * previous element. If there is no previous element, or the
462 * previous element is a DOS drive letter or root path slash,
463 * we can't remove it. Leaving a '..' at the root level will
464 * result in an invalid path, but it would change the meaning
465 * to remove it, so leave it intact.
466 *
467 * There's also a special case if the previous element is
468 * another '..'. If so, it means this was an unremovable '..',
469 * so we can't do any combining - we need to keep this '..'
470 * AND the previous '..' to retain the meaning.
471 */
472 ++dotcnt;
473 if (prvele == 0
474 || ispathchar(*prvele)
475 || (prvele[0] == '.' && prvele[1] == '.'
476 && ispathchar(prvele[2]))
477 #ifdef MSDOS
478 || (prvele == path && path[1] == ':' && isalpha(path[0]))
479 #endif
480 )
481 prvele = 0;
482
483 /* remove the previous element */
484 if (prvele != 0)
485 {
486 /* remove the element */
487 memmove(prvele, p, strlen(p) + 1);
488
489 /*
490 * start the scan over from the beginning; this is a little
491 * inefficient, but it's the easiest way to ensure
492 * accuracy, since we'd otherwise have to back up to find
493 * the previous element, which can be tricky
494 */
495 p = ele = path;
496 prvele = 0;
497 }
498 else
499 {
500 /*
501 * no previous element, so keep the .. as it is and move on
502 * to the next element
503 */
504 prvele = ele;
505 ele = p;
506 }
507 }
508 else
509 {
510 /* ordinary element - move on to the next element */
511 prvele = ele;
512 ele = p;
513 }
514 }
515
516 /* if we left any trailing slashes, remove them */
517 for (p = trimpt + strlen(trimpt) ;
518 p > trimpt && ispathchar(*(p-1)) ;
519 *--p = '\0') ;
520
521 /*
522 * If that left us with an empty string, and we had one or more "." or
523 * ".." elements, the "." and ".." elements must have canceled out the
524 * other elements. In this case return "." as the result.
525 */
526 if (orig[0] == '\0' && dotcnt != 0)
527 {
528 orig[0] = '.';
529 orig[1] = '\0';
530 }
531 }
532 #endif
533
534 /*
535 * General path builder for os_build_full_path() and os_combine_paths().
536 * The two versions do the same work, except that the former canonicalizes
537 * the result (resolving "." and ".." in the last element, for example),
538 * while the latter just builds the combined path literally.
539 */
540 #if !defined(OSNOUI_OMIT_OS_BUILD_FULL_PATH) && !defined(OSNOUI_OMIT_OS_COMBINE_PATHS)
541 static void build_path(char *fullpathbuf, size_t fullpathbuflen,
542 const char *path, const char *filename, int canon)
543 {
544 size_t plen, flen;
545 int add_sep;
546
547 /* presume we'll copy the entire path */
548 plen = strlen(path);
549
550 #ifdef MSDOS
551 /*
552 * On DOS, there's a special case involving root paths without drive
553 * letters. If the filename starts with a slash, but doesn't look like
554 * a UNC-style name (\\MACHINE\NAME), it's an absolute path on a
555 * relative drive. This means that we need to copy the drive letter or
556 * UNC prefix from 'path' and add the root path from 'filename'.
557 */
558 if ((filename[0] == '\\' || filename[0] == '/')
559 && !(filename[1] == '\\' && filename[1] == '/'))
560 {
561 const char *p;
562
563 /*
564 * 'filename' is a root path without a drive letter. Determine if
565 * 'path' starts with a drive letter or a UNC path.
566 */
567 if (isalpha(path[0]) && path[1] == ':')
568 {
569 /* drive letter */
570 plen = 2;
571 }
572 else if ((path[0] == '\\' || path[0] == '/')
573 && (path[1] == '\\' || path[1] == '/'))
574 {
575 /*
576 * UNC-style name - copy the whole \\MACHINE\PATH part. Look
577 * for the first path separator after the machine name...
578 */
579 for (p = path + 2 ; *p != '\0' && *p != '\\' && *p != '/' ; ++p) ;
580
581 /* ...now look for the next path separator after that */
582 if (*p != '\0')
583 for (++p ; *p != '\0' && *p != '\\' && *p != '/' ; ++p) ;
584
585 /* copy everything up to but not including the second separator */
586 plen = p - path;
587 }
588 else
589 {
590 /*
591 * we have a root path on the filename side, but no drive
592 * letter or UNC prefix on the path side, so there's nothing to
593 * add to the filename
594 */
595 plen = 0;
596 }
597 }
598
599 /*
600 * There's a second special case for DOS. If the filename has a drive
601 * letter with a relative path (e.g., "d:asdf" - no leading backslash),
602 * we can't apply any of the path. This sort of path isn't absolute,
603 * in that it depends upon the working directory on the drive, but it's
604 * also not relative, in that it does specify a full directory rather
605 * than a path fragment to add to a root path.
606 */
607 if (isalpha(filename[0]) && filename[1] == ':'
608 && filename[2] != '\\' && filename[2] != '/')
609 {
610 /* the file has a drive letter - we can't combine it with the path */
611 plen = 0;
612 }
613 #endif
614
615 /* if the filename is an absolute path already, leave it as is */
616 if (os_is_file_absolute(filename))
617 plen = 0;
618
619 /*
620 * Note whether we need to add a separator. If the path prefix ends in
621 * a separator, don't add another; otherwise, add the standard system
622 * separator character.
623 *
624 * Don't add a separator if the path is completely empty, since this
625 * simply means that we want to use the current directory.
626 */
627 add_sep = (plen != 0 && path[plen] == '\0' && !ispathchar(path[plen-1]));
628
629 /* copy the path to the full path buffer, limiting to the buffer length */
630 if (plen > fullpathbuflen - 1)
631 plen = fullpathbuflen - 1;
632 memcpy(fullpathbuf, path, plen);
633
634 /* add the path separator if necessary (and if there's room) */
635 if (add_sep && plen + 2 < fullpathbuflen)
636 fullpathbuf[plen++] = OSPATHCHAR;
637
638 /* add the filename after the path, if there's room */
639 flen = strlen(filename);
640 if (flen > fullpathbuflen - plen - 1)
641 flen = fullpathbuflen - plen - 1;
642 memcpy(fullpathbuf + plen, filename, flen);
643
644 /* add a null terminator */
645 fullpathbuf[plen + flen] = '\0';
646
647 /* if desired, canonicalize the result */
648 if (canon)
649 canonicalize_path(fullpathbuf);
650 }
651 #endif
652
653 /*
654 * Build a full path out of path and filename components, returning the
655 * result in canonical form (e.g., with '.' and '..' resolved).
656 */
657 #ifndef OSNOUI_OMIT_OS_BUILD_FULL_PATH
658 void os_build_full_path(char *fullpathbuf, size_t fullpathbuflen,
659 const char *path, const char *filename)
660 {
661 /* build the combined path, and canonicalize the result */
662 build_path(fullpathbuf, fullpathbuflen, path, filename, TRUE);
663 }
664 #endif
665
666 /*
667 * Build a combined path, returning the literal combination without
668 * resolving any relative links.
669 */
670 #ifndef OSNOUI_OMIT_OS_COMBINE_PATHS
671 void os_combine_paths(char *fullpathbuf, size_t fullpathbuflen,
672 const char *path, const char *filename)
673 {
674 /* build the path, without any canonicalization */
675 build_path(fullpathbuf, fullpathbuflen, path, filename, FALSE);
676 }
677 #endif
678
679 /*
680 * Determine if a path is absolute or relative. If the path starts with
681 * a path separator character, we consider it absolute, otherwise we
682 * consider it relative.
683 *
684 * Note that, on DOS, an absolute path can also follow a drive letter.
685 * So, if the path contains a letter followed by a colon, we'll consider
686 * the path to be absolute.
687 */
688 #ifndef OSNOUI_OMIT_IS_FILE_ABSOLUTE
689 int os_is_file_absolute(const char *fname)
690 {
691 #ifdef MSDOS
692 /*
693 * on DOS, a file is absolute if it starts with a drive letter followed
694 * by a path separator
695 */
696 if (isalpha(fname[0]) && fname[1] == ':'
697 && (fname[2] == '/' || fname[2] == '\\'))
698 return TRUE;
699
700 /*
701 * it's also absolute if it starts with a UNC-style path
702 * (\\MACHINE\DRIVE)
703 */
704 if ((fname[0] == '\\' || fname[0] == '/')
705 && (fname[1] == '\\' || fname[1] == '/'))
706 {
707 const char *p;
708
709 /* make sure we have another \ sometime later */
710 for (p = fname + 2 ; *p != '\0' && *p != '/' && *p != '\\' ; ++p) ;
711 if (*p != '\0')
712 return TRUE;
713 }
714
715 #else /* MSDOS */
716
717 /* if the name starts with a path separator, it's absolute */
718 if (ispathchar(fname[0]))
719 return TRUE;
720
721 #endif
722
723 /* the path is relative */
724 return FALSE;
725 }
726 #endif
727
728
729 /*
730 * path letter/substring comparison; define this according to whether the
731 * local file system is case-sensitive (e.g., Unix) or not (DOS, Windows)
732 */
733 #if defined(MSDOS)
734 # define pathmemcmp(a, b, len) memicmp(a, b, len)
735 # define pathchareq(a, b) (toupper(a) == toupper(b))
736 #endif
737 #ifndef pathchareq
738 # define pathmemcmp(a, b, len) memcmp(a, b, len)
739 # define pathchareq(a, b) ((a) == (b))
740 #endif
741
742
743 #ifdef MSDOS
744 /*
745 * Parse a volume name in an absolute path. DOS/Windows volume names are
746 * simply one-letter drive names - A:, C:, etc. If there's a drive letter
747 * name, returns the next character after the ':'; if there's not a drive
748 * letter, returns null.
749 */
750 static const char *oss_parse_volume(const char *path)
751 {
752 if (isalpha(path[0]) && path[1] == ':')
753 return path + 2;
754 else
755 return 0;
756 }
757 #endif
758
759 /*
760 * Get the relative form of a path name. Given a base path and a filename,
761 * get the name of the file with its path expressed relative to the base
762 * path, if possible. Both paths must be in absolute format.
763 *
764 * For DOS-like systems with drive letters, if the filename and base path
765 * are on different drives, there's no way to express the filename in
766 * relative terms, so we'll return it unchanged.
767 */
768 #ifndef OSNOUI_OMIT_OS_GET_REL_PATH
769 int os_get_rel_path(char *result, size_t result_len,
770 const char *basepath, const char *filename)
771 {
772 const char *fp;
773 const char *bp;
774 const char *fsep;
775 const char *bsep;
776 size_t rem;
777 char *rp;
778
779 #if defined(MSDOS)
780 /*
781 * DOS and some other systems (e.g., VMS) use drive letter, volume, or
782 * device prefixes, and each drive/volume/device is effectively its own
783 * separate namespace with its own root directory. There's typically
784 * no syntax on these systems to refer to a container entity above the
785 * volume level, or the parent of a volume root, which means there's no
786 * way to write a filename in relative terms when it's on a different
787 * volume from the base path.
788 *
789 * So: start by checking for a drive/volume prefix. If both paths have
790 * one (and they both should if the system uses them at all, as both
791 * paths are supposed to be handed to us in absolute format), make sure
792 * they match; if not, we can't form a relative name.
793 */
794 bp = oss_parse_volume(basepath);
795 fp = oss_parse_volume(filename);
796 if (bp != 0 && fp != 0
797 && (bp - basepath != fp - filename
798 || pathmemcmp(basepath, filename, bp - basepath) != 0))
799 {
800 /* we have volumes, and they don't match - we can't relativize it */
801 strncpy(result, filename, result_len - 1);
802 result[result_len - 1] = '\0';
803 return FALSE;
804 }
805 #endif
806
807 /*
808 * Find the common path prefix. We can lop off any leading elements
809 * that the two paths have in common.
810 */
811 for (fp = filename, bp = basepath, fsep = 0, bsep = 0 ;
812 pathchareq(*fp, *bp) || (ispathchar(*fp) && ispathchar(*bp)) ;
813 ++fp, ++bp)
814 {
815 /*
816 * if this is a separator character, note it - we want to keep
817 * track of the last separator in the common portion, since this is
818 * the end of the common path prefix
819 */
820 if (ispathchar(*fp) || *fp == '\0')
821 {
822 fsep = fp;
823 bsep = bp;
824 }
825
826 /* stop at the end of the strings */
827 if (*fp == '\0' || *bp == '\0')
828 break;
829 }
830
831 /* if we didn't find any separators, we can't relativize the paths */
832 if (bsep == 0 || fsep == 0)
833 {
834 /* nothing in common - return the filename unchanged */
835 strncpy(result, filename, result_len - 1);
836 result[result_len - 1] = '\0';
837 return FALSE;
838 }
839
840 /*
841 * If we reached the end of the base path string, and we're at a path
842 * separator in the filename string, then the entire base path prefix
843 * is in common to both names.
844 */
845 if (*bp == '\0' && (ispathchar(*fp) || *fp == '\0'))
846 {
847 fsep = fp;
848 bsep = bp;
849 }
850
851 /* if we're at a path separator in the base path, skip it */
852 if (*bsep != '\0')
853 ++bsep;
854
855 /* if we're at a path separator in the filename, skip it */
856 if (*fsep != '\0')
857 ++fsep;
858
859 /*
860 * Everything up to fsep and bsep can be dropped, because it's a common
861 * directory path prefix. We must now add the relative adjustment
862 * portion: add a ".." directory for each remaining directory in the
863 * base path, since we must move from the base path up to the common
864 * ancestor; then add the rest of the filename path.
865 */
866
867 /*
868 * first, set up to copy into the result buffer - leave space for null
869 * termination
870 */
871 rp = result;
872 rem = result_len - 1;
873
874 /* add a ".." for each remaining directory in the base path string */
875 while (*bsep != '\0')
876 {
877 /* add ".." and a path separator */
878 if (rem > 3)
879 {
880 *rp++ = '.';
881 *rp++ = '.';
882 *rp++ = OSPATHCHAR;
883 rem -= 3;
884 }
885 else
886 {
887 /* no more room - give up */
888 rem = 0;
889 break;
890 }
891
892 /* scan to the next path separator */
893 for ( ; *bsep != '\0' && !ispathchar(*bsep) ; ++bsep) ;
894
895 /* if this is a path separator, skip it */
896 if (*bsep != '\0')
897 ++bsep;
898 }
899
900 /*
901 * Copy the remainder of the filename, or as much as will fit, and
902 * ensure that the result is properly null-terminated
903 */
904 strncpy(rp, fsep, rem);
905 rp[rem] = '\0';
906
907 /* if the result is empty, return "." to represent the current dir */
908 if (result[0] == '\0')
909 strcpy(rp, ".");
910
911 /* success */
912 return TRUE;
913 }
914 #endif
915
916
917 #endif /* USE_DOSEXT */
918
919 /* ------------------------------------------------------------------------ */
920
921 /*
922 * A port can define USE_TIMERAND if it wishes to randomize from the
923 * system clock. This should be usable by most ports.
924 */
925 #ifdef USE_TIMERAND
926 # include <time.h>
927
928 void os_rand(long *seed)
929 {
930 time_t t;
931
932 time( &t );
933 *seed = (long)t;
934 }
935 #endif /* USE_TIMERAND */
936
937 #ifdef USE_PATHSEARCH
938 /* search a path specified in the environment for a tads file */
939 static int pathfind(const char *fname, int flen, const char *pathvar,
940 char *buf, size_t bufsiz)
941 {
942 char *e;
943
944 if ( (e = getenv(pathvar)) == 0 )
945 return(0);
946 for ( ;; )
947 {
948 char *sep;
949 size_t len;
950
951 if ( (sep = strchr(e, OSPATHSEP)) != 0 )
952 {
953 len = (size_t)(sep-e);
954 if (!len) continue;
955 }
956 else
957 {
958 len = strlen(e);
959 if (!len) break;
960 }
961 memcpy(buf, e, len);
962 if (!ispathchar(buf[len-1]))
963 buf[len++] = OSPATHCHAR;
964 memcpy(buf+len, fname, flen);
965 buf[len+flen] = 0;
966 if (osfacc(buf) == 0) return(1);
967 if (!sep) break;
968 e = sep+1;
969 }
970 return(0);
971 }
972 #endif /* USE_PATHSEARCH */
973
974 /*
975 * Look for a tads-related file in the standard locations and, if the
976 * search is successful, store the result file name in the given buffer.
977 * Return 1 if the file was located, 0 if not.
978 *
979 * Search the following areas for the file: current directory, program
980 * directory (as derived from argv[0]), and the TADS path.
981 */
982 int os_locate(const char *fname, int flen, const char *arg0,
983 char *buf, size_t bufsiz)
984 {
985 /* Check the current directory */
986 if (osfacc(fname) == 0)
987 {
988 memcpy(buf, fname, flen);
989 buf[flen] = 0;
990 return(1);
991 }
992
993 /* Check the program directory */
994 if (arg0 && *arg0)
995 {
996 const char *p;
997
998 /* find the end of the directory name of argv[0] */
999 for (p = arg0 + strlen(arg0); p > arg0 && !ispathchar(*(p-1)); --p) ;
1000
1001 /* don't bother if there's no directory on argv[0] */
1002 if (p > arg0)
1003 {
1004 size_t len = (size_t)(p - arg0);
1005
1006 memcpy(buf, arg0, len);
1007 memcpy(buf+len, fname, flen);
1008 buf[len+flen] = 0;
1009 if (osfacc(buf) == 0) return(1);
1010 }
1011 }
1012
1013 #ifdef USE_PATHSEARCH
1014 /* Check TADS path */
1015 if ( pathfind(fname, flen, "TADS", buf, bufsiz) )
1016 return(1);
1017 #endif /* USE_PATHSEARCH */
1018
1019 return(0);
1020 }
1021
1022
1023 /* ------------------------------------------------------------------------ */
1024 /*
1025 * Define the version of memcmp to use for comparing filename path elements
1026 * for equality. For case-sensitive file systems, use memcmp(); for
1027 * systems that ignore case, use memicmp().
1028 */
1029 #if defined(MSDOS) || defined(T_WIN32) || defined(DJGPP) || defined(MSOS2)
1030 # define fname_memcmp memicmp
1031 #endif
1032 #if defined(UNIX)
1033 # define fname_memcmp memcmp
1034 #endif
1035
1036 #if defined(GLK) && !defined(fname_memcmp)
1037 # define fname_memcmp memcmp
1038 #endif
1039
1040
1041 /*
1042 * Get the next earlier element of a path
1043 */
1044 static const char *prev_path_ele(const char *start, const char *p,
1045 size_t *ele_len)
1046 {
1047 int cancel = 0;
1048 const char *dotdot = 0;
1049
1050 /* if we're at the start of the string, there are no more elements */
1051 if (p == start)
1052 return 0;
1053
1054 /* keep going until we find a suitable element */
1055 for (;;)
1056 {
1057 const char *endp;
1058
1059 /*
1060 * If we've reached the start of the string, it means that we have
1061 * ".."'s that canceled out every earlier element of the string.
1062 * If the cancel count is non-zero, it means that we have one or
1063 * more ".."'s that are significant (in that they cancel out
1064 * relative elements before the start of the string). If the
1065 * cancel count is zero, it means that we've exactly canceled out
1066 * all remaining elements in the string.
1067 */
1068 if (p == start)
1069 {
1070 *ele_len = (dotdot != 0 ? 2 : 0);
1071 return dotdot;
1072 }
1073
1074 /*
1075 * back up through any adjacent path separators before the current
1076 * element, so that we're pointing to the first separator after the
1077 * previous element
1078 */
1079 for ( ; p != start && ispathchar(*(p-1)) ; --p) ;
1080
1081 /*
1082 * If we're at the start of the string, this is an absolute path.
1083 * Treat it specially by returning a zero-length initial element.
1084 */
1085 if (p == start)
1086 {
1087 *ele_len = 0;
1088 return p;
1089 }
1090
1091 /* note where the current element ends */
1092 endp = p;
1093
1094 /* now back up to the path separator before this element */
1095 for ( ; p != start && !ispathchar(*(p-1)) ; --p) ;
1096
1097 /*
1098 * if this is ".", skip it, since this simply means that this
1099 * element matches the same folder as the previous element
1100 */
1101 if (endp - p == 1 && p[0] == '.')
1102 continue;
1103
1104 /*
1105 * if this is "..", it cancels out the preceding non-relative
1106 * element; up the cancel count and keep searching
1107 */
1108 if (endp - p == 2 && p[0] == '.' && p[1] == '.')
1109 {
1110 /* up the cancel count */
1111 ++cancel;
1112
1113 /* if this is the first ".." we've encountered, note it */
1114 if (dotdot == 0)
1115 dotdot = p;
1116
1117 /* keep searching */
1118 continue;
1119 }
1120
1121 /*
1122 * This is an ordinary path element, not a relative "." or ".."
1123 * link. If we have a non-zero cancel count, we're still working
1124 * on canceling out elements from ".."'s we found later in the
1125 * string.
1126 */
1127 if (cancel != 0)
1128 {
1129 /* this absorbs one level of cancellation */
1130 --cancel;
1131
1132 /*
1133 * if that's the last cancellation, we've absorbed all ".."
1134 * effects, so the last ".." we found is no longer significant
1135 */
1136 if (cancel == 0)
1137 dotdot = 0;
1138
1139 /* keep searching */
1140 continue;
1141 }
1142
1143 /* this item isn't canceled out by a "..", so it's our winner */
1144 *ele_len = endp - p;
1145 return p;
1146 }
1147 }
1148
1149
1150 /*
1151 * Compare two paths for equality
1152 */
1153 int os_file_names_equal(const char *a, const char *b)
1154 {
1155 /* start at the end of each name and work backwards */
1156 const char *pa = a + strlen(a), *pb = b + strlen(b);
1157
1158 /* keep going until we reach the start of one or the other path */
1159 for (;;)
1160 {
1161 size_t lena, lenb;
1162
1163 /* get the next earlier element of each path */
1164 pa = prev_path_ele(a, pa, &lena);
1165 pb = prev_path_ele(b, pb, &lenb);
1166
1167 /* if one or the other ran out, we're done */
1168 if (pa == 0 || pb == 0)
1169 {
1170 /* the paths match if they ran out at the same time */
1171 return pa == pb;
1172 }
1173
1174 /* if the two elements don't match, return unequal */
1175 if (lena != lenb || fname_memcmp(pa, pb, lena) != 0)
1176 return FALSE;
1177 }
1178 }
1179
1180
1181 /* ------------------------------------------------------------------------ */
1182 /*
1183 * ISAAC random number generator. This is a small, fast, cryptographic
1184 * quality random number generator that we use internally for some generic
1185 * purposes:
1186 *
1187 * - for os_gen_temp_filename(), we use it to generate a GUID-style random
1188 * filename
1189 *
1190 * - for our generic implementation of os_gen_rand_bytes(), we use it as
1191 * the source of the random bytes
1192 */
1193
1194 /*
1195 * include ISAAC if we're using our generic temporary filename generator
1196 * with long filenames, or we're using our generic os_gen_rand_bytes()
1197 */
1198 #if !defined(OSNOUI_OMIT_TEMPFILE) && (defined(T_WIN32) || !defined(MSDOS))
1199 #define INCLUDE_ISAAC
1200 #endif
1201 #ifdef USE_GENRAND
1202 #define INCLUDE_ISAAC
1203 #endif
1204
1205 #ifdef INCLUDE_ISAAC
1206 /*
1207 * ISAAC random number generator implementation, for generating
1208 * GUID-strength random temporary filenames
1209 */
1210 #define ISAAC_RANDSIZL (8)
1211 #define ISAAC_RANDSIZ (1<<ISAAC_RANDSIZL)
1212 static struct isaacctx
1213 {
1214 /* RNG context */
1215 unsigned long cnt;
1216 unsigned long rsl[ISAAC_RANDSIZ];
1217 unsigned long mem[ISAAC_RANDSIZ];
1218 unsigned long a;
1219 unsigned long b;
1220 unsigned long c;
1221 } *S_isaacctx;
1222
1223 #define _isaac_rand(r) \
1224 ((r)->cnt-- == 0 ? \
1225 (isaac_gen_group(r), (r)->cnt=ISAAC_RANDSIZ-1, (r)->rsl[(r)->cnt]) : \
1226 (r)->rsl[(r)->cnt])
1227 #define isaac_rand() _isaac_rand(S_isaacctx)
1228
1229 #define isaac_ind(mm,x) ((mm)[(x>>2)&(ISAAC_RANDSIZ-1)])
1230 #define isaac_step(mix,a,b,mm,m,m2,r,x) \
1231 { \
1232 x = *m; \
1233 a = ((a^(mix)) + *(m2++)) & 0xffffffff; \
1234 *(m++) = y = (isaac_ind(mm,x) + a + b) & 0xffffffff; \
1235 *(r++) = b = (isaac_ind(mm,y>>ISAAC_RANDSIZL) + x) & 0xffffffff; \
1236 }
1237
1238 #define isaac_mix(a,b,c,d,e,f,g,h) \
1239 { \
1240 a^=b<<11; d+=a; b+=c; \
1241 b^=c>>2; e+=b; c+=d; \
1242 c^=d<<8; f+=c; d+=e; \
1243 d^=e>>16; g+=d; e+=f; \
1244 e^=f<<10; h+=e; f+=g; \
1245 f^=g>>4; a+=f; g+=h; \
1246 g^=h<<8; b+=g; h+=a; \
1247 h^=a>>9; c+=h; a+=b; \
1248 }
1249
1250 /* generate the group of numbers */
1251 static void isaac_gen_group(struct isaacctx *ctx)
1252 {
1253 unsigned long a;
1254 unsigned long b;
1255 unsigned long x;
1256 unsigned long y;
1257 unsigned long *m;
1258 unsigned long *mm;
1259 unsigned long *m2;
1260 unsigned long *r;
1261 unsigned long *mend;
1262
1263 mm = ctx->mem;
1264 r = ctx->rsl;
1265 a = ctx->a;
1266 b = (ctx->b + (++ctx->c)) & 0xffffffff;
1267 for (m = mm, mend = m2 = m + (ISAAC_RANDSIZ/2) ; m<mend ; )
1268 {
1269 isaac_step(a<<13, a, b, mm, m, m2, r, x);
1270 isaac_step(a>>6, a, b, mm, m, m2, r, x);
1271 isaac_step(a<<2, a, b, mm, m, m2, r, x);
1272 isaac_step(a>>16, a, b, mm, m, m2, r, x);
1273 }
1274 for (m2 = mm; m2<mend; )
1275 {
1276 isaac_step(a<<13, a, b, mm, m, m2, r, x);
1277 isaac_step(a>>6, a, b, mm, m, m2, r, x);
1278 isaac_step(a<<2, a, b, mm, m, m2, r, x);
1279 isaac_step(a>>16, a, b, mm, m, m2, r, x);
1280 }
1281 ctx->b = b;
1282 ctx->a = a;
1283 }
1284
1285 static void isaac_init(unsigned long *rsl)
1286 {
1287 static int inited = FALSE;
1288 int i;
1289 unsigned long a;
1290 unsigned long b;
1291 unsigned long c;
1292 unsigned long d;
1293 unsigned long e;
1294 unsigned long f;
1295 unsigned long g;
1296 unsigned long h;
1297 unsigned long *m;
1298 unsigned long *r;
1299 struct isaacctx *ctx;
1300
1301 /* allocate the context if we don't already have it set up */
1302 if ((ctx = S_isaacctx) == 0)
1303 ctx = S_isaacctx = (struct isaacctx *)malloc(sizeof(struct isaacctx));
1304
1305 /*
1306 * If we're already initialized, AND the caller isn't re-seeding with
1307 * explicit data, we're done.
1308 */
1309 if (inited && rsl == 0)
1310 return;
1311 inited = TRUE;
1312
1313 ctx->a = ctx->b = ctx->c = 0;
1314 m = ctx->mem;
1315 r = ctx->rsl;
1316 a = b = c = d = e = f = g = h = 0x9e3779b9; /* the golden ratio */
1317
1318 /* scramble the initial settings */
1319 for (i = 0 ; i < 4 ; ++i)
1320 {
1321 isaac_mix(a, b, c, d, e, f, g, h);
1322 }
1323
1324 /*
1325 * if they sent in explicit initialization bytes, use them; otherwise
1326 * seed the generator with truly random bytes from the system
1327 */
1328 if (rsl != 0)
1329 memcpy(ctx->rsl, rsl, sizeof(ctx->rsl));
1330 else
1331 os_gen_rand_bytes((unsigned char *)ctx->rsl, sizeof(ctx->rsl));
1332
1333 /* initialize using the contents of ctx->rsl[] as the seed */
1334 for (i = 0 ; i < ISAAC_RANDSIZ ; i += 8)
1335 {
1336 a += r[i]; b += r[i+1]; c += r[i+2]; d += r[i+3];
1337 e += r[i+4]; f += r[i+5]; g += r[i+6]; h += r[i+7];
1338 isaac_mix(a, b, c, d, e, f, g, h);
1339 m[i] = a; m[i+1] = b; m[i+2] = c; m[i+3] = d;
1340 m[i+4] = e; m[i+5] = f; m[i+6] = g; m[i+7] = h;
1341 }
1342
1343 /* do a second pass to make all of the seed affect all of m */
1344 for (i = 0 ; i < ISAAC_RANDSIZ ; i += 8)
1345 {
1346 a += m[i]; b += m[i+1]; c += m[i+2]; d += m[i+3];
1347 e += m[i+4]; f += m[i+5]; g += m[i+6]; h += m[i+7];
1348 isaac_mix(a, b, c, d, e, f, g, h);
1349 m[i] = a; m[i+1] = b; m[i+2] = c; m[i+3] = d;
1350 m[i+4] = e; m[i+5] = f; m[i+6] = g; m[i+7] = h;
1351 }
1352
1353 /* fill in the first set of results */
1354 isaac_gen_group(ctx);
1355
1356 /* prepare to use the first set of results */
1357 ctx->cnt = ISAAC_RANDSIZ;
1358 }
1359 #endif /* INCLUDE_ISAAC */
1360
1361
1362 /* ------------------------------------------------------------------------ */
1363 /*
1364 * Generic implementation of os_gen_rand_bytes(). This can be used when
1365 * the operating system doesn't have a native source of true randomness,
1366 * but prefereably only as a last resort - see below for why.
1367 *
1368 * This generator uses ISAAC to generate the bytes, seeded by the system
1369 * time. This algorithm isn't nearly as good as using a native OS-level
1370 * randomness source, since any decent OS API will have access to
1371 * considerably more sources of true entropy. In a portable setting, we
1372 * have very little in the way of true randomness available. The most
1373 * reliable portable source of randomness is the system clock; if it has
1374 * resolution in the millisecond range, this gives us roughly 10-12 bits of
1375 * real entropy if we assume that the user is running the program manually,
1376 * in that there should be no pattern to the exact program start time -
1377 * even a series of back-to-back runs would be pretty random in the part of
1378 * the time below about 1 second. We *might* also be able to get a little
1379 * randomness from the memory environment, such as the current stack
1380 * pointer, the state of the malloc() allocator as revealed by the address
1381 * of a newly allocated block, the contents of uninitialized stack
1382 * variables and uninitialized malloc blocks, and the contents of the
1383 * system registers as saved by setjmp. These memory settings are not
1384 * entirely likely to vary much from one run to the next: most modern OSes
1385 * virtualize the process environment to such an extent that each fresh run
1386 * will start with exactly the same initial memory environment, including
1387 * the stack address and malloc heap configuration.
1388 *
1389 * We make the most of these limited entropy sources by using them to seed
1390 * an ISAAC RNG, then generating the returned random bytes via ISAAC.
1391 * ISAAC's design as a cryptographic RNG means that it thoroughly mixes up
1392 * the meager set of random bits we hand it, so the bytes returned will
1393 * statistically look nice and random. However, don't be fooled into
1394 * thinking that this magnifies the basic entropy we have as inputs - it
1395 * doesn't. If we only have 10-12 bits of entropy from the timer, and
1396 * everything else is static, our byte sequence will represent 10-12 bits
1397 * of entropy scattered around through a large set of mathematically (and
1398 * deterministically) derived bits. The danger is that the "birthday
1399 * problem" dictates that with 12 bits of variation from one run to the
1400 * next, we'd have a good chance of seeing a repeat of the *exact same byte
1401 * sequence* within about 100 runs. This is why it's so much better to
1402 * customize this routine using a native OS mechanism whenever possible.
1403 */
1404 #ifdef USE_GENRAND
1405
1406 void os_gen_rand_bytes(unsigned char *buf, size_t buflen)
1407 {
1408 union
1409 {
1410 unsigned long r[ISAAC_RANDSIZ];
1411 struct
1412 {
1413 unsigned long r1[15];
1414 jmp_buf env;
1415 } o;
1416 } r;
1417 void *p, *q;
1418
1419 /*
1420 * Seed ISAAC with what little entropy we have access to in a generic
1421 * cross-platform implementation:
1422 *
1423 * - the current wall-clock time
1424 *. - the high-precision (millisecond) system timer
1425 *. - the current stack pointer
1426 *. - an arbitrary heap pointer obtained from malloc()
1427 *. - whatever garbage is in the random heap pointer from malloc()
1428 *. - whatever random garbage is in the rest of our stack buffer 'r'
1429 *. - the contents of system registers from 'setjmp'
1430 *
1431 * The millisecond timer is by far the most reliable source of real
1432 * entropy we have available. The wall clock time doesn't vary quickly
1433 * enough to produce more than a few bits of entropy from run to run;
1434 * all of the memory factors could be absolutely deterministic from run
1435 * to run, depending on how thoroughly the OS virtualizes the process
1436 * environment at the start of a run. For example, some systems clear
1437 * memory pages allocated to a process, as a security measure to
1438 * prevent old data from one process from becoming readable by another
1439 * process. Some systems virtualize the memory space such that the
1440 * program is always loaded at the same virtual address, always has its
1441 * stack at the same virtual address, etc.
1442 *
1443 * Note that we try to add some variability to our malloc heap probing,
1444 * first by making the allocation size vary according to the low bits
1445 * of the system millisecond timer, then by doing a second allocation
1446 * to take into account the effect of the randomized size of the first
1447 * allocation. This should avoid getting the exact same results every
1448 * time we run, even if the OS arranges for the heap to have exactly
1449 * the same initial layout with every run, since our second malloc will
1450 * have initial conditions that vary according to the size our first
1451 * malloc. This arguably doesn't introduce a lot of additional real
1452 * entropy, since we're already using the system timer directly in the
1453 * calculation anyway: in a sufficiently predictable enough heap
1454 * environment, our two malloc() calls will yield the same results for
1455 * a given timer value, so we're effectively adding f(timer) for some
1456 * deterministic function f(), which is the same in terms of additional
1457 * real entropy as just adding the timer again, which is the same as
1458 * adding nothing.
1459 */
1460 r.r[0] = (unsigned long)time(0);
1461 r.r[1] = (unsigned long)os_get_sys_clock_ms();
1462 r.r[2] = (unsigned long)buf;
1463 r.r[3] = (unsigned long)&buf;
1464 p = malloc((size_t)(os_get_sys_clock_ms() & 1023) + 17);
1465 r.r[4] = (unsigned long)p;
1466 r.r[5] = *(unsigned long *)p;
1467 r.r[6] = *((unsigned long *)p + 10);
1468 q = malloc(((size_t)p & 1023) + 19);
1469 r.r[7] = (unsigned long)p;
1470 r.r[8] = *(unsigned long *)p;
1471 r.r[9] = *((unsigned long *)p + 10);
1472 setjmp(r.o.env);
1473
1474 free(p);
1475 free(q);
1476
1477 /* initialize isaac with our seed data */
1478 isaac_init(r.r);
1479
1480 /* generate random bytes from isaac to fill the buffer */
1481 while (buflen > 0)
1482 {
1483 unsigned long n;
1484 size_t copylen;
1485
1486 /* generate a number */
1487 n = isaac_rand();
1488
1489 /* copy it into the buffer */
1490 copylen = buflen < sizeof(n) ? buflen : sizeof(n);
1491 memcpy(buf, &n, copylen);
1492
1493 /* advance our buffer pointer */
1494 buf += copylen;
1495 buflen -= copylen;
1496 }
1497 }
1498
1499 #endif /* USE_GENRAND */
1500
1501 /* ------------------------------------------------------------------------ */
1502 /*
1503 * Temporary files
1504 *
1505 * This default implementation is layered on the normal osifc file APIs, so
1506 * our temp files are nothing special: they're just ordinary files that we
1507 * put in a special directory (the temp path), and which we count on our
1508 * caller to delete before the app terminates (which assumes that the app
1509 * terminates normally, AND that our portable caller correctly keeps track
1510 * of every temp file it creates and explicitly deletes it).
1511 *
1512 * On systems that have native temp file support, you might want to use the
1513 * native API instead, since native temp file APIs often have the useful
1514 * distinction that they'll automatically delete any outstanding temp files
1515 * on application termination, even on crashy exits. To remove these
1516 * default implementations from the build, #define OSNOUI_OMIT_TEMPFILE
1517 * in your makefile.
1518 */
1519 #ifndef OSNOUI_OMIT_TEMPFILE
1520
1521 /*
1522 * Create and open a temporary file
1523 */
1524 osfildef *os_create_tempfile(const char *swapname, char *buf)
1525 {
1526 osfildef *fp;
1527 const char *fname;
1528
1529 /* if a name wasn't provided, generate a name */
1530 if (swapname == 0)
1531 {
1532 /* generate a name for the file */
1533 os_gen_temp_filename(buf, OSFNMAX);
1534
1535 /* use the generated name */
1536 fname = buf;
1537 }
1538 else
1539 {
1540 /* use the name they passed in */
1541 fname = swapname;
1542 }
1543
1544 /* open the file in binary write/truncate mode */
1545 fp = osfoprwtb(fname, OSFTSWAP);
1546
1547 /* set the file's type in the OS, if necessary */
1548 os_settype(fname, OSFTSWAP);
1549
1550 /* return the file pointer */
1551 return fp;
1552 }
1553
1554 /*
1555 * Delete a temporary file. Since our generic implementation of
1556 * os_create_tempfile() simply uses osfoprwtb() to open the file, a
1557 * temporary file's handle is not any different from any other file
1558 * handle - in particular, the OS doesn't automatically delete the file
1559 * when closed. Hence, we need to delete the file explicitly here.
1560 */
1561 int osfdel_temp(const char *fname)
1562 {
1563 /* delete the file using the normal mechanism */
1564 return osfdel(fname);
1565 }
1566
1567 #if defined(MSDOS) && !defined(T_WIN32)
1568 #define SHORT_FILENAMES
1569 #endif
1570
1571 #ifndef SHORT_FILENAMES
1572 /*
1573 * Generate a name for a temporary file. This is the long filename
1574 * version, suitable only for platforms that can handle filenames of at
1575 * least 45 characters in just the root name portion. For systems with
1576 * short filenames (e.g., MS-DOS, this must use a different algorithm - see
1577 * the MSDOS section below for a fairly portable "8.3" implementation.
1578 */
1579 int os_gen_temp_filename(char *buf, size_t buflen)
1580 {
1581 char tmpdir[OSFNMAX], fname[50];
1582
1583 /* get the system temporary directory */
1584 os_get_tmp_path(tmpdir);
1585
1586 /* seed ISAAC with random data from the system */
1587 isaac_init(0);
1588
1589 /*
1590 * Generate a GUID-strength random filename. ISAAC is a cryptographic
1591 * quality RNG, so the chances of collisions with other filenames
1592 * should be effectively zero.
1593 */
1594 sprintf(fname, "TADS-%08lx-%08lx-%08lx-%08lx.tmp",
1595 isaac_rand(), isaac_rand(), isaac_rand(), isaac_rand());
1596
1597 /* build the full path */
1598 os_build_full_path(buf, buflen, tmpdir, fname);
1599
1600 /* success */
1601 return TRUE;
1602 }
1603
1604 #endif
1605 #endif /* OSNOUI_OMIT_TEMPFILE */
1606
1607 /* ------------------------------------------------------------------------ */
1608
1609 /*
1610 * print a null-terminated string to osfildef* file
1611 */
1612 #ifndef OSNOUI_OMIT_OS_FPRINTZ
1613 void os_fprintz(osfildef *fp, const char *str)
1614 {
1615 fprintf(fp, "%s", str);
1616 }
1617 #endif
1618
1619 /*
1620 * print a counted-length string (which might not be null-terminated) to a
1621 * file
1622 */
1623 #ifndef OSNOUI_OMIT_OS_FPRINT
1624 void os_fprint(osfildef *fp, const char *str, size_t len)
1625 {
1626 fprintf(fp, "%.*s", (int)len, str);
1627 }
1628 #endif
1629
1630 /* ------------------------------------------------------------------------ */
1631
1632 #ifdef T_WIN32
1633 /*
1634 * Windows implementation - get the temporary file path.
1635 */
1636 void os_get_tmp_path(char *buf)
1637 {
1638 GetTempPath(OSFNMAX, buf);
1639 }
1640 #endif
1641
1642 #if defined(MSDOS) && !defined(T_WIN32)
1643 /*
1644 * MS-DOS implementation - Get the temporary file path. Tries getting
1645 * the values of various environment variables that are typically used
1646 * to define the location for temporary files.
1647 */
1648 void os_get_tmp_path(char *buf)
1649 {
1650 static char *vars[] =
1651 {
1652 "TEMPDIR",
1653 "TMPDIR",
1654 "TEMP",
1655 "TMP",
1656 0
1657 };
1658 char **varp;
1659
1660 /* look for an environment variable from our list */
1661 for (varp = vars ; *varp ; ++varp)
1662 {
1663 char *val;
1664
1665 /* get this variable's value */
1666 val = getenv(*varp);
1667 if (val)
1668 {
1669 size_t len;
1670
1671 /* use this value */
1672 strcpy(buf, val);
1673
1674 /* add a backslash if necessary */
1675 if ((len = strlen(buf)) != 0
1676 && buf[len-1] != '/' && buf[len-1] != '\\')
1677 {
1678 buf[len] = '\\';
1679 buf[len+1] = '\0';
1680 }
1681
1682 /* use this value */
1683 return;
1684 }
1685 }
1686
1687 /* didn't find anything - leave the prefix empty */
1688 buf[0] = '\0';
1689 }
1690
1691 /*
1692 * Generate a name for a temporary file. This implementation is suitable
1693 * for MS-DOS and other platforms with short filenames - for the simpler
1694 * and more generic long-filename version, see above. On systems where
1695 * filenames are limited to short names, we can't pack enough randomness
1696 * into a filename to guarantee uniqueness by virtue of randomness alone,
1697 * so we cope by actually checking for an existing file for each random
1698 * name we roll up, trying again if our selected name is in use.
1699 */
1700 int os_gen_temp_filename(char *buf, size_t buflen)
1701 {
1702 osfildef *fp;
1703 int attempt;
1704 size_t len;
1705 time_t timer;
1706 int pass;
1707
1708 /*
1709 * Fail if our buffer is smaller than OSFNMAX. os_get_tmp_path()
1710 * assumes an OSFNMAX-sized buffer, so we'll have problems if the
1711 * passed-in buffer is shorter than that.
1712 */
1713 if (buflen < OSFNMAX)
1714 return FALSE;
1715
1716 /*
1717 * Try a few times with the temporary file path; if we can't find an
1718 * available filename there, try again with the working directory.
1719 */
1720 for (pass = 1 ; pass <= 2 ; ++pass)
1721 {
1722 /* get the directory path */
1723 if (pass == 1)
1724 {
1725 /* first pass - use the system temp directory */
1726 os_get_tmp_path(buf);
1727 len = strlen(buf);
1728 }
1729 else
1730 {
1731 /*
1732 * second pass - we couldn't find any free names in the system
1733 * temp directory, so try the working directory
1734 */
1735 buf[0] = '\0';
1736 len = 0;
1737 }
1738
1739 /* get the current time, as a basis for a unique identifier */
1740 time(&timer);
1741
1742 /* try until we find a non-existent filename */
1743 for (attempt = 0 ; attempt < 100 ; ++attempt)
1744 {
1745 /* generate a name based on time and try number */
1746 sprintf(buf + len, "SW%06ld.%03d",
1747 (long)timer % 999999, attempt);
1748
1749 /* check to see if a file by this name already exists */
1750 if (osfacc(buf))
1751 {
1752 /* the file doesn't exist - try creating it */
1753 fp = osfoprwtb(buf, OSFTSWAP);
1754
1755 /* if that succeeded, return this file */
1756 if (fp != 0)
1757 {
1758 /* set the file's type in the OS, if necessary */
1759 os_settype(buf, OSFTSWAP);
1760
1761 /* close the file - it's just an empty placeholder */
1762 osfcls(fp);
1763
1764 /* return success */
1765 return TRUE;
1766 }
1767 }
1768 }
1769 }
1770
1771 /* we couldn't find a free filename - return failure */
1772 return FALSE;
1773 }
1774
1775 #endif /* MSDOS */
1776
1777 #ifdef USE_NULLSTYPE
1778 void os_settype(const char *f, os_filetype_t t)
1779 {
1780 /* nothing needs to be done on this system */
1781 }
1782 #endif /* USE_NULLSTYPE */
1783
1784 /* ------------------------------------------------------------------------ */
1785 /*
1786 * URL/local path conversion
1787 */
1788
1789 #if defined(TURBO) || defined(DJGPP) || defined(MICROSOFT) || defined(MSOS2)
1790 /* length-protected character adder for os_cvt_xxx */
1791 static void cvtaddchar(char **dst, size_t *rem, char c)
1792 {
1793 if (*rem > 1)
1794 {
1795 **dst = c;
1796 *dst += 1;
1797 *rem -= 1;
1798 }
1799 }
1800 static void cvtaddchars(char **dst, size_t *rem, const char *src, size_t len)
1801 {
1802 for ( ; len > 0 ; --len)
1803 cvtaddchar(dst, rem, *src++);
1804 }
1805 #endif
1806
1807 /*
1808 * Convert an OS filename path to a relative URL
1809 */
1810 void os_cvt_dir_url(char *result_buf, size_t result_buf_size,
1811 const char *src_path)
1812 {
1813 char *dst = result_buf;
1814 const char *src = src_path;
1815 size_t rem = result_buf_size;
1816
1817 #if defined(TURBO) || defined(DJGPP) || defined(MICROSOFT) || defined(MSOS2)
1818 /*
1819 * If there's a DOS/Windows drive letter, start with the drive letter
1820 * and leading '\', if present, as a separate path element. If it's a
1821 * UNC-style path, add the UNC \\MACHINE\SHARE as the first element.
1822 *
1823 * In either case, we'll leave the source pointer positioned at the
1824 * rest of the path after the drive root or UNC share, which means
1825 * we're pointing to the relative portion of the path that follows.
1826 * The normal algorithm will simply convert this to a relative URL that
1827 * will be tacked on to the absolute root URL portion that we generate
1828 * here, so we'll have the correct overall format.
1829 */
1830 if (isalpha(src[0]) && src[1] == ':')
1831 {
1832 /* start with /X: */
1833 cvtaddchar(&dst, &rem, '/');
1834 cvtaddchars(&dst, &rem, src, 2);
1835 src += 2;
1836
1837 /*
1838 * if it's just "X:" and not "X:\", translate it to "X:." to make
1839 * it explicit that we're talking about the working directory on X:
1840 */
1841 if (*src != '\\' && *src != '/')
1842 cvtaddchars(&dst, &rem, "./", 2);
1843 }
1844 else if ((src[0] == '\\' || src[0] == '/')
1845 && (src[1] == '\\' || src[1] == '/'))
1846 {
1847 const char *p;
1848
1849 /*
1850 * UNC-style path. Find the next separator to get the end of the
1851 * machine name.
1852 */
1853 for (p = src + 2 ; *p != '\0' && *p != '/' && *p != '\\' ; ++p) ;
1854
1855 /* start with /\\MACHINE */
1856 cvtaddchar(&dst, &rem, '/');
1857 cvtaddchars(&dst, &rem, src, p - src);
1858
1859 /* skip to the path separator */
1860 src = p;
1861 }
1862 #endif /* DOS */
1863
1864 /*
1865 * Run through the source buffer, copying characters to the output
1866 * buffer. If we encounter a path separator character, replace it with
1867 * a forward slash.
1868 */
1869 for ( ; *src != '\0' && rem > 1 ; ++dst, ++src, --rem)
1870 {
1871 /*
1872 * If this is a local path separator character, replace it with the
1873 * URL-style path separator character. Otherwise, copy it
1874 * unchanged.
1875 */
1876 if (strchr(OSPATHURL, *src) != 0)
1877 {
1878 /* add the URL-style path separator instead of the local one */
1879 *dst = '/';
1880 }
1881 else
1882 {
1883 /* add the character unchanged */
1884 *dst = *src;
1885 }
1886 }
1887
1888 /* remove any trailing separators (unless the whole path is "/") */
1889 while (dst > result_buf + 1 && *(dst-1) == '/')
1890 --dst;
1891
1892 /* add a null terminator */
1893 *dst = '\0';
1894 }
1895
1896 /*
1897 * Convert a relative URL to a relative file system path name
1898 */
1899 #ifndef OSNOUI_OMIT_OS_CVT_URL_DIR
1900 void os_cvt_url_dir(char *result_buf, size_t result_buf_size,
1901 const char *src_url)
1902 {
1903 char *dst = result_buf;
1904 const char *src = src_url;
1905 size_t rem = result_buf_size;
1906
1907 /*
1908 * check for an absolute path
1909 */
1910 #if defined(TURBO) || defined(DJGPP) || defined(MICROSOFT) || defined(MSOS2)
1911 if (*src == '/')
1912 {
1913 const char *p;
1914 int is_drive, is_unc = FALSE;
1915
1916 /* we have an absolute path - find the end of the first element */
1917 for (p = ++src ; *p != '\0' && *p != '/' ; ++p) ;
1918
1919 /* check to see if it looks like a drive letter */
1920 is_drive = (isalpha(src[0]) && src[1] == ':'
1921 && (p - src == 2
1922 || (p - src == 3 && src[2] == '.')));
1923
1924 /* check to see if it looks like a UNC-style path */
1925 is_unc = (src[0] == '\\' && src[1] == '\\');
1926
1927 /*
1928 * if it's a drive letter or UNC path, it's a valid Windows root
1929 * path element - copy it exactly, then decode the rest of the path
1930 * as a simple relative path relative to this root
1931 */
1932 if (is_drive || is_unc)
1933 {
1934 /* it's a drive letter or drive root path - copy it exactly */
1935 cvtaddchars(&dst, &rem, src, p - src);
1936
1937 /*
1938 * if it's an X:. path, remove the . and the following path
1939 * separator
1940 */
1941 if (is_drive && p - src == 3 && src[2] == '.')
1942 {
1943 /* undo the '.' */
1944 --dst;
1945 ++rem;
1946
1947 /* skip the '/' if present */
1948 if (*p == '/')
1949 ++p;
1950 }
1951
1952 /* skip to the '/' */
1953 src = p;
1954 }
1955 else
1956 {
1957 /*
1958 * It's not a valid DOS root element, so make this a
1959 * non-drive-letter root path, converting the first element as
1960 * a directory name.
1961 */
1962 cvtaddchar(&dst, &rem, '\\');
1963 }
1964 }
1965 else if (isalpha(src[0]) && src[1] == ':')
1966 {
1967 /*
1968 * As a special case, assume that a path starting with "X:" (where
1969 * X is any letter) is a Windows/DOS drive letter prefix. This
1970 * doesn't fit our new (as of Jan 2012) rules for converting paths
1971 * to URLs, but it's what older versions did, so it provides
1972 * compatibility. There's a small price for this compatibility,
1973 * which is that it's possible in principle for a Unix relative
1974 * path to look the same way - you could have a Unix directory
1975 * called "c:", so "c:/dir" would be a valid relative path. But
1976 * it's extremely uncommon for Unix users to use colons in
1977 * directory names for a couple of reasons; one is that it creates
1978 * interop problems because practically every other file system
1979 * treats ':' as a special syntax element, and the other is that
1980 * ':' is conventionally used on Unix itself as a delimiter in path
1981 * lists, so while it isn't formally a special character in file
1982 * names, it's effectively a special character.
1983 */
1984 cvtaddchars(&dst, &rem, src, 2);
1985 src += 2;
1986 }
1987 #endif
1988
1989 /*
1990 * Run through the source buffer, copying characters to the output
1991 * buffer. If we encounter a '/', convert it to a path separator
1992 * character.
1993 */
1994 for ( ; *src != '\0' && rem > 1 ; ++src, ++dst, --rem)
1995 {
1996 /*
1997 * replace slashes with path separators; expand '%' sequences; copy
1998 * all other characters unchanged
1999 */
2000 if (*src == '/')
2001 {
2002 /* change '/' to the local path separator */
2003 *dst = OSPATHCHAR;
2004 }
2005 else if ((unsigned char)*src < 32
2006 #if defined(TURBO) || defined(DJGPP) || defined(MICROSOFT) || defined(MSOS2)
2007 || strchr("*+?=[]\\&|\":<>", *src) != 0
2008 #endif
2009 )
2010 {
2011 *dst = '_';
2012 }
2013 else
2014 {
2015 /* copy this character unchanged */
2016 *dst = *src;
2017 }
2018 }
2019
2020 /* add a null terminator and we're done */
2021 *dst = '\0';
2022 }
2023 #endif
2024
2025
2026 /* ------------------------------------------------------------------------ */
2027 /*
2028 * Service routine for searching - build the full output path name. (This
2029 * is used in the various DOS/Windows builds.)
2030 */
2031 #if defined(TURBO) || defined(DJGPP) || defined(MICROSOFT) || defined(MSOS2)
2032
2033 static void oss_build_outpathbuf(char *outpathbuf, size_t outpathbufsiz,
2034 const char *path, const char *fname)
2035 {
2036 /* if there's a full path buffer, build the full path */
2037 if (outpathbuf != 0)
2038 {
2039 size_t lp;
2040 size_t lf;
2041
2042 /* copy the path prefix */
2043 lp = strlen(path);
2044 if (lp > outpathbufsiz - 1)
2045 lp = outpathbufsiz - 1;
2046 memcpy(outpathbuf, path, lp);
2047
2048 /* add the filename if there's any room */
2049 lf = strlen(fname);
2050 if (lf > outpathbufsiz - lp - 1)
2051 lf = outpathbufsiz - lp - 1;
2052 memcpy(outpathbuf + lp, fname, lf);
2053
2054 /* null-terminate the result */
2055 outpathbuf[lp + lf] = '\0';
2056 }
2057 }
2058
2059 #endif /* TURBO || DJGPP || MICROSOFT || MSOS2 */
2060
2061 /* ------------------------------------------------------------------------ */
2062 /*
2063 * Borland C implementation of directory functions
2064 */
2065 #if defined(TURBO) || defined(DJGPP)
2066
2067 #include <dir.h>
2068 #include <dos.h>
2069
2070 struct oss_find_ctx_t
2071 {
2072 struct ffblk ff;
2073 int found;
2074 };
2075
2076 int os_open_dir(const char *dir, osdirhdl_t *hdl)
2077 {
2078 char *pat;
2079 size_t patsiz;
2080 struct oss_find_ctx_t *ctx;
2081
2082 /* create a copy of the string with "\*.*" appended */
2083 patsiz = strlen(dir) + 32;
2084 pat = (char *)malloc(patsiz);
2085 os_build_full_path(pat, patsiz, dir, "*.*");
2086 if (pat == 0)
2087 return FALSE;
2088
2089 /* allocate a search block structure */
2090 ctx = (struct oss_find_ctx_t *)malloc(sizeof(struct oss_find_ctx_t));
2091 if (ctx == 0)
2092 {
2093 free(pat);
2094 return FALSE;
2095 }
2096
2097 /* begin the search */
2098 ctx->found = (findfirst(pat, &ctx->ff, FA_DIREC) == 0);
2099
2100 /* done with the pattern buffer */
2101 free(pat);
2102
2103 /* return the context as the search handle and indicate success */
2104 *hdl = ctx;
2105 return TRUE;
2106 }
2107
2108 int os_read_dir(osdirhdl_t hdl, char *buf, size_t buflen)
2109 {
2110 /* cast the handle to our private structure */
2111 struct oss_find_ctx_t *ctx = (struct oss_find_ctx_t *)hdl;
2112
2113 /* if we're out of files, return failure */
2114 if (!ctx->found)
2115 return FALSE;
2116
2117 /* return the current file */
2118 safe_strcpy(buf, buflen, ctx->ff.ff_name);
2119
2120 /* move on to the next file */
2121 ctx->found = (findnext(&ctx->ff) == 0);
2122
2123 /* success */
2124 return TRUE;
2125 }
2126
2127 void os_close_dir(osdirhdl_t hdl)
2128 {
2129 /* free the context structure */
2130 free(hdl);
2131 }
2132
2133 #if 0 // the os_find_xxx family of functions has been DEPRECATED
2134 /*
2135 * search context structure - DEPRECATED
2136 */
2137 struct oss_find_ctx_t
2138 {
2139 /* C library find-file block */
2140 struct ffblk ff;
2141
2142 /* original search path prefix (we'll allocate more to fit the string) */
2143 char path[1];
2144 };
2145
2146 /*
2147 * find first matching file - DEPRECATED
2148 */
2149 void *os_find_first_file(const char *dir, const char *pattern, char *outbuf,
2150 size_t outbufsiz, int *isdir,
2151 char *outpathbuf, size_t outpathbufsiz)
2152 {
2153 struct oss_find_ctx_t *ctx;
2154 char realpat[OSFNMAX];
2155 size_t l;
2156 size_t path_len;
2157 const char *lastsep;
2158 const char *p;
2159
2160 /*
2161 * construct the filename pattern from the directory and pattern
2162 * segments, using "*" as the default wildcard pattern if no
2163 * explicit pattern was provided
2164 */
2165 strcpy(realpat, dir);
2166 if ((l = strlen(realpat)) != 0 && realpat[l - 1] != '\\')
2167 realpat[l++] = '\\';
2168 if (pattern == 0)
2169 strcpy(realpat + l, "*.*");
2170 else
2171 strcpy(realpat + l, pattern);
2172
2173 /* find the last separator in the original path */
2174 for (p = realpat, lastsep = 0 ; *p != '\0' ; ++p)
2175 {
2176 /* if this is a separator, remember it */
2177 if (*p == '\\' || *p == '/' || *p == ':')
2178 lastsep = p;
2179 }
2180
2181 /*
2182 * if we found a separator, the path prefix is everything up to and
2183 * including the separator; otherwise, there's no path prefix
2184 */
2185 if (lastsep != 0)
2186 {
2187 /* the length of the path includes the separator */
2188 path_len = lastsep + 1 - realpat;
2189 }
2190 else
2191 {
2192 /* there's no path prefix - everything is in the current directory */
2193 path_len = 0;
2194 }
2195
2196 /* allocate a context */
2197 ctx = (struct oss_find_ctx_t *)malloc(sizeof(struct oss_find_ctx_t)
2198 + path_len);
2199
2200 /* copy the path to the context */
2201 memcpy(ctx->path, realpat, path_len);
2202 ctx->path[path_len] = '\0';
2203
2204 /* call DOS to search for a matching file */
2205 if (findfirst(realpat, &ctx->ff, FA_DIREC))
2206 {
2207 /* no dice - delete the context and return failure */
2208 free(ctx);
2209 return 0;
2210 }
2211
2212 /* skip files with the HIDDEN or SYSTEM attributes */
2213 while ((ctx->ff.ff_attrib & (FA_HIDDEN | FA_SYSTEM)) != 0)
2214 {
2215 /* skip to the next file */
2216 if (findnext(&ctx->ff))
2217 {
2218 /* no more files - delete the context and give up */
2219 free(ctx);
2220 return 0;
2221 }
2222 }
2223
2224 /* copy the filename into the caller's buffer */
2225 l = strlen(ctx->ff.ff_name);
2226 if (l > outbufsiz - 1)
2227 l = outbufsiz - 1;
2228 memcpy(outbuf, ctx->ff.ff_name, l);
2229 outbuf[l] = '\0';
2230
2231 /* build the full path, if desired */
2232 oss_build_outpathbuf(outpathbuf, outpathbufsiz,
2233 ctx->path, ctx->ff.ff_name);
2234
2235 /* return the directory indication */
2236 *isdir = (ctx->ff.ff_attrib & FA_DIREC) != 0;
2237
2238 /*
2239 * return the context - it will be freed later when find-next
2240 * reaches the last file or find-close is called to cancel the
2241 * search
2242 */
2243 return ctx;
2244 }
2245
2246 /* find the next file - DEPRECATED */
2247 void *os_find_next_file(void *ctx0, char *outbuf, size_t outbufsiz,
2248 int *isdir, char *outpathbuf, size_t outpathbufsiz)
2249 {
2250 struct oss_find_ctx_t *ctx = (struct oss_find_ctx_t *)ctx0;
2251 size_t l;
2252
2253 /* if the search has already ended, do nothing */
2254 if (ctx == 0)
2255 return 0;
2256
2257 /* keep going until we find a non-hidden, non-system file */
2258 do
2259 {
2260 /* try searching for the next file */
2261 if (findnext(&ctx->ff))
2262 {
2263 /* no more files - delete the context and give up */
2264 free(ctx);
2265
2266 /* return null to indicate that the search is finished */
2267 return 0;
2268 }
2269 } while ((ctx->ff.ff_attrib & (FA_HIDDEN | FA_SYSTEM)) != 0);
2270
2271 /* return the name */
2272 l = strlen(ctx->ff.ff_name);
2273 if (l > outbufsiz - 1) l = outbufsiz - 1;
2274 memcpy(outbuf, ctx->ff.ff_name, l);
2275 outbuf[l] = '\0';
2276
2277 /* return the directory indication */
2278 *isdir = (ctx->ff.ff_attrib & FA_DIREC) != 0;
2279
2280 /* build the full path, if desired */
2281 oss_build_outpathbuf(outpathbuf, outpathbufsiz,
2282 ctx->path, ctx->ff.ff_name);
2283
2284 /*
2285 * indicate that the search was successful by returning the non-null
2286 * context pointer -- the context has been updated for the new
2287 * position in the search, so we just return the same context
2288 * structure that we've been using all along
2289 */
2290 return ctx;
2291 }
2292
2293 /* cancel a search - DEPRECATED */
2294 void os_find_close(void *ctx0)
2295 {
2296 struct oss_find_ctx_t *ctx = (struct oss_find_ctx_t *)ctx0;
2297
2298 /* if the search was already cancelled, do nothing */
2299 if (ctx == 0)
2300 return;
2301
2302 /* delete the search context */
2303 free(ctx);
2304 }
2305 #endif /* DEPRECATED */
2306
2307 /*
2308 * Time-zone initialization
2309 */
2310 void os_tzset()
2311 {
2312 /* let the run-time library initialize the time zone */
2313 tzset();
2314 }
2315
2316 /* ------------------------------------------------------------------------ */
2317 /*
2318 * Get file attributes
2319 */
2320 unsigned long oss_get_file_attrs(const char *fname)
2321 {
2322 struct ffblk ff;
2323 unsigned long attrs = 0;
2324
2325 /* look up the file */
2326 if (!findfirst(fname, &ff, FA_DIREC))
2327 {
2328 /* translate the HIDDEN and SYSTEM bits */
2329 if ((ff.ff_attrib & FA_HIDDEN) != 0)
2330 attrs |= OSFATTR_HIDDEN;
2331 if ((ff.ff_attrib & FA_SYSTEM) != 0)
2332 attrs |= OSFATTR_SYSTEM;
2333
2334 /* if the RDONLY bit is set, it's readable, otherwise read/write */
2335 attrs |= OSFATTR_READ;
2336 if ((ff.ff_attrib & FA_RDONLY) == 0)
2337 attrs |= OSFATTR_WRITE;
2338 }
2339
2340 /* return the attributes */
2341 return attrs;
2342 }
2343
2344 /*
2345 * Get file status information
2346 */
2347 int os_file_stat(const char *fname, int follow_links, os_file_stat_t *s)
2348 {
2349 struct stat info;
2350 struct ffblk ff;
2351
2352 /* get the file information */
2353 if (stat(fname, &info))
2354 {
2355 /*
2356 * stat() doesn't work for devices; try running through osfmode(),
2357 * which does special checks for reserved device names
2358 */
2359 if (osfmode(fname, follow_links, &s->mode, &s->attrs))
2360 {
2361 /* devices have no sizes or timestamps */
2362 s->sizehi = 0;
2363 s->sizelo = 0;
2364 s->cre_time = 0;
2365 s->mod_time = 0;
2366 s->acc_time = 0;
2367
2368 /* success */
2369 return TRUE;
2370 }
2371
2372 /* failed */
2373 return FALSE;
2374 }
2375
2376 /* translate the status fields */
2377 if (sizeof(info.st_size) <= 4)
2378 {
2379 s->sizelo = info.st_size;
2380 s->sizehi = 0;
2381 }
2382 else
2383 {
2384 s->sizelo = (uint32_t)(info.st_size & 0xFFFFFFFF);
2385 s->sizehi = (uint32_t)(info.st_size >> 32);
2386 }
2387 s->cre_time = info.st_ctime;
2388 s->mod_time = info.st_mtime;
2389 s->acc_time = info.st_atime;
2390 s->mode = info.st_mode;
2391
2392 /* get the DOS mode information */
2393 s->attrs = oss_get_file_attrs(fname);
2394
2395 /* success */
2396 return TRUE;
2397 }
2398
2399 /*
2400 * Resolve a symbolic link
2401 */
2402 int os_resolve_symlink(const char *fname, char *target, size_t target_size)
2403 {
2404 /* DOS doesn't support symbolic links */
2405 return FALSE;
2406 }
2407
2408
2409 #endif /* TURBO || DJGPP */
2410
2411 /* ------------------------------------------------------------------------ */
2412 /*
2413 * Microsoft C implementation of directory functions
2414 */
2415 #ifdef MICROSOFT
2416
2417 struct oss_find_ctx_t
2418 {
2419 /* _findfirst/_findnext search handle */
2420 long handle;
2421
2422 /* return data from _findfirst/_findnext */
2423 struct _finddata_t data;
2424
2425 /* does 'data' contain a valid file description? */
2426 int found;
2427 };
2428
2429 int os_open_dir(const char *dir, osdirhdl_t *hdl)
2430 {
2431 char *pat;
2432 size_t patsiz;
2433 struct oss_find_ctx_t *ctx;
2434
2435 /* create a copy of the string with "\*" appended */
2436 patsiz = strlen(dir) + 32;
2437 pat = (char *)malloc(patsiz);
2438 os_build_full_path(pat, patsiz, dir, "*");
2439 if (pat == 0)
2440 return FALSE;
2441
2442 /* allocate a search block structure */
2443 ctx = (struct oss_find_ctx_t *)malloc(sizeof(struct oss_find_ctx_t));
2444 if (ctx == 0)
2445 {
2446 free(pat);
2447 return FALSE;
2448 }
2449
2450 /* begin the search */
2451 ctx->handle = _findfirst(pat, &ctx->data);
2452
2453 /* done with the pattern string */
2454 free(pat);
2455
2456 /* if the search failed, free resources and return failure */
2457 if (ctx->handle == -1L)
2458 {
2459 free(ctx);
2460 return FALSE;
2461 }
2462
2463 /* return the context as the search handle and indicate success */
2464 ctx->found = TRUE;
2465 *hdl = ctx;
2466 return TRUE;
2467 }
2468
2469 int os_read_dir(osdirhdl_t hdl, char *buf, size_t buflen)
2470 {
2471 /* cast the handle to our private structure */
2472 struct oss_find_ctx_t *ctx = (struct oss_find_ctx_t *)hdl;
2473
2474 /* if we're out of files, return failure */
2475 if (!ctx->found)
2476 return FALSE;
2477
2478 /* return the current file */
2479 safe_strcpy(buf, buflen, ctx->data.name);
2480
2481 /* move on to the next file */
2482 ctx->found = (_findnext(ctx->handle, &ctx->data) == 0);
2483
2484 /* success */
2485 return TRUE;
2486 }
2487
2488 void os_close_dir(osdirhdl_t hdl)
2489 {
2490 /* cast the handle to our private structure */
2491 struct oss_find_ctx_t *ctx = (struct oss_find_ctx_t *)hdl;
2492
2493 /* close the system search handle */
2494 _findclose(ctx->handle);
2495
2496 /* free the context structure */
2497 free(hdl);
2498 }
2499
2500
2501 #if 0 // the os_find_xxx family of functions has been DEPRECATED
2502 typedef struct
2503 {
2504 /* search handle */
2505 long handle;
2506
2507 /* found data structure */
2508 struct _finddata_t data;
2509
2510 /* full original search path */
2511 char path[1];
2512 } ossfcx;
2513
2514 /*
2515 * find first matching file
2516 */
2517 void *os_find_first_file(const char *dir, const char *pattern, char *outbuf,
2518 size_t outbufsiz, int *isdir,
2519 char *outpathbuf, size_t outpathbufsiz)
2520 {
2521 ossfcx *ctx;
2522 char realpat[OSFNMAX];
2523 size_t l;
2524 size_t path_len;
2525 const char *lastsep;
2526 const char *p;
2527
2528 /*
2529 * construct the filename pattern from the directory and pattern
2530 * segments, using "*" as the default wildcard pattern if no
2531 * explicit pattern was provided
2532 */
2533 strcpy(realpat, dir);
2534 if ((l = strlen(realpat)) != 0 && realpat[l - 1] != '\\')
2535 realpat[l++] = '\\';
2536 if (pattern == 0)
2537 strcpy(realpat + l, "*");
2538 else
2539 strcpy(realpat + l, pattern);
2540
2541 /* find the last separator in the original path */
2542 for (p = realpat, lastsep = 0 ; *p != '\0' ; ++p)
2543 {
2544 /* if this is a separator, remember it */
2545 if (*p == '\\' || *p == '/' || *p == ':')
2546 lastsep = p;
2547 }
2548
2549 /*
2550 * if we found a separator, the path prefix is everything up to and
2551 * including the separator; otherwise, there's no path prefix
2552 */
2553 if (lastsep != 0)
2554 {
2555 /* the length of the path includes the separator */
2556 path_len = lastsep + 1 - realpat;
2557 }
2558 else
2559 {
2560 /* there's no path prefix - everything is in the current directory */
2561 path_len = 0;
2562 }
2563
2564 /* allocate a context */
2565 ctx = (ossfcx *)malloc(sizeof(ossfcx) + path_len);
2566
2567 /* copy the path to the context */
2568 memcpy(ctx->path, realpat, path_len);
2569 ctx->path[path_len] = '\0';
2570
2571 /* call DOS to search for a matching file */
2572 ctx->handle = _findfirst(realpat, &ctx->data);
2573 if (ctx->handle == -1L)
2574 {
2575 /* no dice - delete the context and return failure */
2576 free(ctx);
2577 return 0;
2578 }
2579
2580 /* skip files with HIDDEN or SYSTEM attributes */
2581 while ((ctx->data.attrib & (_A_HIDDEN | _A_SYSTEM)) != 0)
2582 {
2583 /* skip this file */
2584 if (_findnext(ctx->handle, &ctx->data) != 0)
2585 {
2586 /* no more files - close up shop and return failure */
2587 _findclose(ctx->handle);
2588 free(ctx);
2589 return 0;
2590 }
2591 }
2592
2593 /* return the name */
2594 l = strlen(ctx->data.name);
2595 if (l > outbufsiz - 1) l = outbufsiz - 1;
2596 memcpy(outbuf, ctx->data.name, l);
2597 outbuf[l] = '\0';
2598
2599 /* return the directory indication */
2600 *isdir = (ctx->data.attrib & _A_SUBDIR) != 0;
2601
2602 /* build the full path, if desired */
2603 oss_build_outpathbuf(outpathbuf, outpathbufsiz,
2604 ctx->path, ctx->data.name);
2605
2606 /*
2607 * return the context - it will be freed later when find-next
2608 * reaches the last file or find-close is called to cancel the
2609 * search
2610 */
2611 return ctx;
2612 }
2613
2614 /* find the next file */
2615 void *os_find_next_file(void *ctx0, char *outbuf, size_t outbufsiz,
2616 int *isdir, char *outpathbuf, size_t outpathbufsiz)
2617 {
2618 ossfcx *ctx = (ossfcx *)ctx0;
2619 size_t l;
2620
2621 /* if the search has already ended, do nothing */
2622 if (ctx == 0)
2623 return 0;
2624
2625 /* keep going until we find a non-system, non-hidden file */
2626 do
2627 {
2628 /* try searching for the next file */
2629 if (_findnext(ctx->handle, &ctx->data) != 0)
2630 {
2631 /* no more files - close the search and delete the context */
2632 _findclose(ctx->handle);
2633 free(ctx);
2634
2635 /* return null to indicate that the search is finished */
2636 return 0;
2637 }
2638 } while ((ctx->data.attrib & (_A_HIDDEN | _A_SYSTEM)) != 0);
2639
2640 /* return the name */
2641 l = strlen(ctx->data.name);
2642 if (l > outbufsiz - 1) l = outbufsiz - 1;
2643 memcpy(outbuf, ctx->data.name, l);
2644 outbuf[l] = '\0';
2645
2646 /* return the directory indication */
2647 *isdir = (ctx->data.attrib & _A_SUBDIR) != 0;
2648
2649 /* build the full path, if desired */
2650 oss_build_outpathbuf(outpathbuf, outpathbufsiz,
2651 ctx->path, ctx->data.name);
2652
2653 /*
2654 * indicate that the search was successful by returning the non-null
2655 * context pointer -- the context has been updated for the new
2656 * position in the search, so we just return the same context
2657 * structure that we've been using all along
2658 */
2659 return ctx;
2660 }
2661
2662 /* cancel a search */
2663 void os_find_close(void *ctx0)
2664 {
2665 ossfcx *ctx = (ossfcx *)ctx0;
2666
2667 /* if the search was already cancelled, do nothing */
2668 if (ctx == 0)
2669 return;
2670
2671 /* close the search and delete the context structure */
2672 _findclose(ctx->handle);
2673 free(ctx);
2674 }
2675 #endif /* DEPCRECATED */
2676
2677 /*
2678 * Time-zone initialization
2679 */
2680 void os_tzset()
2681 {
2682 /* let the run-time library initialize the time zone */
2683 tzset();
2684 }
2685
2686 /* ------------------------------------------------------------------------ */
2687 /*
2688 * Get the DOS attributes for a file
2689 */
2690 unsigned long oss_get_file_attrs(const char *fname)
2691 {
2692 unsigned long attrs = 0;
2693 struct _finddata_t ff;
2694
2695 /* get the DOS attribute flags */
2696 ff.attrib = 0;
2697 #ifdef T_WIN32
2698 ff.attrib = GetFileAttributes(fname);
2699 #else
2700 {
2701 long h = _findfirst(fname, &ff);
2702 if (h != -1L)
2703 _findclose(h);
2704 }
2705 #endif
2706
2707 /* translate the HIDDEN and SYSTEM bits */
2708 if ((ff.attrib & _A_HIDDEN) != 0)
2709 attrs |= OSFATTR_HIDDEN;
2710 if ((ff.attrib & _A_SYSTEM) != 0)
2711 attrs |= OSFATTR_SYSTEM;
2712
2713 /* if the RDONLY bit is set, it's readable, otherwise read/write */
2714 attrs |= OSFATTR_READ;
2715 if ((ff.attrib & _A_RDONLY) == 0)
2716 attrs |= OSFATTR_WRITE;
2717
2718 #ifdef T_WIN32
2719 /*
2720 * On Windows, attempt to do a full security manager check to determine
2721 * our actual access rights to the file. If we fail to get the
2722 * security info, we'll give up and return the simple RDONLY
2723 * determination we just made above. In most cases, failure to check
2724 * the security information will simply be because the file has no ACL,
2725 * which means that anyone can access it, hence our tentative result
2726 * from the RDONLY attribute is correct after all.
2727 */
2728 {
2729 /*
2730 * get the file's DACL and owner/group security info; first, ask
2731 * how much space we need to allocate for the returned information
2732 */
2733 DWORD len = 0;
2734 SECURITY_INFORMATION info = (SECURITY_INFORMATION)(
2735 OWNER_SECURITY_INFORMATION
2736 | GROUP_SECURITY_INFORMATION
2737 | DACL_SECURITY_INFORMATION);
2738 GetFileSecurity(fname, info, 0, 0, &len);
2739 if (len != 0)
2740 {
2741 /* allocate a buffer for the security info */
2742 SECURITY_DESCRIPTOR *sd = (SECURITY_DESCRIPTOR *)malloc(len);
2743 if (sd != 0)
2744 {
2745 /* now actually retrieve the security info into our buffer */
2746 if (GetFileSecurity(fname, info, sd, len, &len))
2747 {
2748 HANDLE ttok;
2749
2750 /* impersonate myself for security purposes */
2751 ImpersonateSelf(SecurityImpersonation);
2752
2753 /*
2754 * get the security token for the current thread, which
2755 * is the context in which the caller will presumably
2756 * eventually attempt to access the file
2757 */
2758 if (OpenThreadToken(
2759 GetCurrentThread(), TOKEN_ALL_ACCESS, TRUE, &ttok))
2760 {
2761 GENERIC_MAPPING genmap = {
2762 FILE_GENERIC_READ,
2763 FILE_GENERIC_WRITE,
2764 FILE_GENERIC_EXECUTE,
2765 FILE_ALL_ACCESS
2766 };
2767 PRIVILEGE_SET privs;
2768 DWORD privlen = sizeof(privs);
2769 BOOL granted = FALSE;
2770 DWORD desired;
2771 DWORD allowed;
2772
2773 /* test read access */
2774 desired = GENERIC_READ;
2775 MapGenericMask(&desired, &genmap);
2776 if (AccessCheck(sd, ttok, desired, &genmap,
2777 &privs, &privlen, &allowed, &granted))
2778 {
2779 /* clear the read bit if reading isn't allowed */
2780 if (allowed == 0)
2781 attrs &= ~OSFATTR_READ;
2782 }
2783
2784 /* test write access */
2785 desired = GENERIC_WRITE;
2786 MapGenericMask(&desired, &genmap);
2787 if (AccessCheck(sd, ttok, desired, &genmap,
2788 &privs, &privlen, &allowed, &granted))
2789 {
2790 /* clear the read bit if reading isn't allowed */
2791 if (allowed == 0)
2792 attrs &= ~OSFATTR_WRITE;
2793 }
2794
2795 /* done with the thread token */
2796 CloseHandle(ttok);
2797 }
2798
2799 /* terminate our security self-impersonation */
2800 RevertToSelf();
2801 }
2802
2803 /* free the allocated security info buffer */
2804 free(sd);
2805 }
2806 }
2807 }
2808 #endif /* T_WIN32 */
2809
2810 /* return the attributes */
2811 return attrs;
2812 }
2813
2814
2815 /*
2816 * Get file status information
2817 */
2818 int os_file_stat(const char *fname, int follow_links, os_file_stat_t *s)
2819 {
2820 struct __stat64 info;
2821
2822 // $$$ we should support Windows symlinks and junction points
2823
2824 /* get the file information */
2825 if (_stat64(fname, &info))
2826 return FALSE;
2827
2828 /* translate the status fields */
2829 s->sizelo = (uint32_t)(info.st_size & 0xFFFFFFFF);
2830 s->sizehi = (uint32_t)(info.st_size >> 32);
2831 s->cre_time = (os_time_t)info.st_ctime;
2832 s->mod_time = (os_time_t)info.st_mtime;
2833 s->acc_time = (os_time_t)info.st_atime;
2834 s->mode = info.st_mode;
2835
2836 /* get the attributes */
2837 s->attrs = oss_get_file_attrs(fname);
2838
2839 /* success */
2840 return TRUE;
2841 }
2842
2843 /*
2844 * Resolve a symbolic link
2845 */
2846 int os_resolve_symlink(const char *fname, char *target, size_t target_size)
2847 {
2848 /*
2849 * We don't currently support symbolic links. (We should change this
2850 * to support Windows symlinks and junction points.
2851 */
2852 //$$$
2853 return FALSE;
2854 }
2855
2856
2857 #endif /* MICROSOFT */
2858
2859
2860 /* ------------------------------------------------------------------------ */
2861 /*
2862 * Create a directory
2863 */
2864 #ifdef MSDOS
2865
2866 #ifdef TURBO
2867 #define _mkdir(dir) mkdir(dir)
2868 #endif
2869 #ifdef DJGPP
2870 #define _mkdir(dir) mkdir(dir, S_IWUSR)
2871 #endif
2872
2873 int os_mkdir(const char *dir, int create_parents)
2874 {
2875 /*
2876 * if we're to create the intermediate parent folders, and the path
2877 * contains multiple elements, recursively create the parent
2878 * directories first
2879 */
2880 if (create_parents
2881 && (strchr(dir, ':') != 0
2882 || strchr(dir, '/') != 0
2883 || strchr(dir, '\\') != 0))
2884 {
2885 char par[OSFNMAX];
2886
2887 /* extract the parent path */
2888 os_get_path_name(par, sizeof(par), dir);
2889
2890 /* if the parent doesn't already exist, create it recursively */
2891 if (par[0] != '\0' && osfacc(par) && !os_mkdir(par, TRUE))
2892 return FALSE;
2893 }
2894
2895 /* create the directory */
2896 return _mkdir(dir) == 0;
2897 }
2898 #endif
2899
2900 /* ------------------------------------------------------------------------ */
2901 /*
2902 * Remove a directory
2903 */
2904 #ifdef MSDOS
2905
2906 #ifdef TURBO
2907 #define _rmdir(dir) rmdir(dir)
2908 #endif
2909 #ifdef DJGPP
2910 #define _rmdir(dir) rmdir(dir)
2911 #endif
2912
2913 int os_rmdir(const char *dir)
2914 {
2915 return _rmdir(dir) == 0;
2916 }
2917 #endif
2918
2919
2920 /* ------------------------------------------------------------------------ */
2921 /*
2922 * OS/2 implementation of directory functions
2923 */
2924 #ifdef MSOS2
2925
2926 /* C library context structure used for file searches */
2927 #ifdef __32BIT__
2928 # define DosFindFirst(a,b,c,d,e,f) DosFindFirst(a,b,c,d,e,f,FIL_STANDARD)
2929 typedef FILEFINDBUF3 oss_c_ffcx;
2930 typedef ULONG count_t;
2931 #else /* !__32BIT__ */
2932 # define DosFindFirst(a,b,c,d,e,f) DosFindFirst(a,b,c,d,e,f,0L)
2933 typedef FILEFINDBUF oss_c_ffcx;
2934 typedef USHORT count_t;
2935 #endif /* __32BIT__ */
2936
2937 struct oss_find_ctx_t
2938 {
2939 oss_c_ffcx ff;
2940 int found;
2941 };
2942
2943 int os_open_dir(const char *dir, osdirhdl_t *hdl)
2944 {
2945 char *pat;
2946 size_t patsiz;
2947 struct oss_find_ctx_t *ctx;
2948 HDIR hdir = HDIR_SYSTEM;
2949 count_t scnt = 1;
2950
2951 /* create a copy of the string with "\*.*" appended */
2952 patsiz = strlen(dir) + 32;
2953 pat = (char *)malloc(patsiz);
2954 os_build_full_path(pat, patsiz, dir, "*.*");
2955 if (pat == 0)
2956 return FALSE;
2957
2958 /* allocate a search block structure */
2959 ctx = (struct oss_find_ctx_t *)malloc(sizeof(struct oss_find_ctx_t));
2960 if (ctx == 0)
2961 {
2962 free(pat);
2963 return FALSE;
2964 }
2965
2966 /* begin the search */
2967 ctx->found = (DosFindFirst(pat, &hdir, FILE_DIRECTORY | FILE_NORMAL,
2968 &ctx->ff, sizeof(ctx->ff), &scnt) == 0);
2969
2970 /* done with the pattern buffer */
2971 free(pat);
2972
2973 /* return the context as the search handle, and indicate success */
2974 *hdl = ctx;
2975 return TRUE;
2976 }
2977
2978 int os_read_dir(osdirhdl_t hdl, char *buf, size_t buflen)
2979 {
2980 count_t scnt = 1;
2981
2982 /* cast the handle to our private structure */
2983 struct oss_find_ctx_t *ctx = (oss_find_ctx_t *)hdl;
2984
2985 /* if we're out of files, return failure */
2986 if (!ctx->found)
2987 return FALSE;
2988
2989 /* return the current file */
2990 safe_strcpyl(buf, buflen, ctx->ff.achName, ctx->ff.cchName);
2991
2992 /* move on to the next file */
2993 ctx->found = (DosFindNext(
2994 HDIR_SYSTEM, &ctx->ff, sizeof(ctx->ff), &scnt) == 0);
2995
2996 /* success */
2997 return TRUE;
2998 }
2999
3000 void os_close_dir(osdirhdl_t hdl)
3001 {
3002 /* free the context structure */
3003 free(hdl);
3004 }
3005
3006 #if 0 // the os_find_xxx family of functions has been DEPRECATED
3007 typedef struct
3008 {
3009 /* C library context structure */
3010 oss_c_ffcx ff;
3011
3012 /* original search path */
3013 char path[1];
3014 } ossfcx;
3015
3016 void *os_find_first_file(const char *dir, const char *pattern, char *outbuf,
3017 size_t outbufsiz, int *isdir,
3018 char *outpathbuf, size_t outpathbufsiz)
3019 {
3020 ossfcx *ctx;
3021 char realpat[OSFNMAX];
3022 size_t l;
3023 HDIR hdir = HDIR_SYSTEM;
3024 count_t scnt = 1;
3025 size_t path_len;
3026 const char *lastsep;
3027 const char *p;
3028
3029 /*
3030 * construct the filename pattern from the directory and pattern
3031 * segments, using "*" as the default wildcard pattern if no
3032 * explicit pattern was provided
3033 */
3034 strcpy(realpat, dir);
3035 if ((l = strlen(realpat)) != 0 && realpat[l - 1] != '\\')
3036 realpat[l++] = '\\';
3037 if (pattern == 0)
3038 strcpy(realpat + l, "*");
3039 else
3040 strcpy(realpat + l, pattern);
3041
3042 /* find the last separator in the original path */
3043 for (p = realpat, lastsep = 0 ; *p != '\0' ; ++p)
3044 {
3045 /* if this is a separator, remember it */
3046 if (*p == '\\' || *p == '/' || *p == ':')
3047 lastsep = p;
3048 }
3049
3050 /*
3051 * if we found a separator, the path prefix is everything up to and
3052 * including the separator; otherwise, there's no path prefix
3053 */
3054 if (lastsep != 0)
3055 {
3056 /* the length of the path includes the separator */
3057 path_len = lastsep + 1 - realpat;
3058 }
3059 else
3060 {
3061 /* there's no path prefix - everything is in the current directory */
3062 path_len = 0;
3063 }
3064
3065 /* allocate a context */
3066 ctx = (ossfcx *)malloc(sizeof(ossfcx) + path_len);
3067
3068 /* call DOS to search for a matching file */
3069 if (DosFindFirst(realpat, &hdir, FILE_DIRECTORY | FILE_NORMAL,
3070 &ctx->ff, sizeof(ctx->ff), &scnt))
3071 {
3072 /* no dice - delete the context and return failure */
3073 free(ctx);
3074 return 0;
3075 }
3076
3077 /* if it's a HIDDEN or SYSTEM file, skip it */
3078 while ((ctx->ff.attrFile & (FILE_HIDDEN | FILE_SYSTEM)) != 0)
3079 {
3080 /* skip to the next file */
3081 if (DosFindNext(HDIR_SYSTEM, &ctx->ff, sizeof(ctx->ff), &scnt))
3082 {
3083 /* no more files - delete the context and give up */
3084 free(ctx);
3085 return 0;
3086 }
3087 }
3088
3089 /* copy the path to the context */
3090 memcpy(ctx->path, realpat, path_len);
3091 ctx->path[path_len] = '\0';
3092
3093 /* return the name */
3094 l = ctx->ff.cchName;
3095 if (l > outbufsiz - 1) l = outbufsiz - 1;
3096 memcpy(outbuf, ctx->ff.achName, l);
3097 outbuf[l] = '\0';
3098
3099 /* return the directory indication */
3100 *isdir = (ctx->ff.attrFile & FILE_DIRECTORY) != 0;
3101
3102 /* build the full path, if desired */
3103 oss_build_outpathbuf(outpathbuf, outpathbufsiz,
3104 ctx->path, ctx->ff.data.name);
3105
3106 /*
3107 * return the context - it will be freed later when find-next
3108 * reaches the last file or find-close is called to cancel the
3109 * search
3110 */
3111 return ctx;
3112 }
3113
3114 /* find the next file */
3115 void *os_find_next_file(void *ctx0, char *outbuf, size_t outbufsiz,
3116 int *isdir, char *outpathbuf, size_t outpathbufsiz)
3117 {
3118 ossfcx *ctx = (ossfcx *)ctx0;
3119 size_t l;
3120
3121 /* if the search has already ended, do nothing */
3122 if (ctx == 0)
3123 return 0;
3124
3125 /* keep going until we find a non-system, non-hidden file */
3126 do
3127 {
3128 /* try searching for the next file */
3129 if (DosFindNext(HDIR_SYSTEM, &ctx->ff, sizeof(ctx->ff), &scnt))
3130 {
3131 /* no more files - delete the context and give up */
3132 free(ctx);
3133
3134 /* return null to indicate that the search is finished */
3135 return 0;
3136 }
3137 } while ((ctx->ff.attrFile & (FILE_HIDDEN | FILE_SYSTEM)) != 0);
3138
3139 /* return the name */
3140 l = ctx->ff.cchName;
3141 if (l > outbufsiz - 1) l = outbufsiz - 1;
3142 memcpy(outbuf, ctx->ff.achName, l);
3143 outbuf[l] = '\0';
3144
3145 /* return the directory indication */
3146 *isdir = (ctx->ff.attrFile & FILE_DIRECTORY) != 0;
3147
3148 /* build the full path, if desired */
3149 oss_build_outpathbuf(outpathbuf, outpathbufsiz,
3150 ctx->ff.path, ctx->ff.data.name);
3151
3152 /*
3153 * indicate that the search was successful by returning the non-null
3154 * context pointer -- the context has been updated for the new
3155 * position in the search, so we just return the same context
3156 * structure that we've been using all along
3157 */
3158 return ctx;
3159 }
3160
3161 /* cancel a search */
3162 void os_find_close(void *ctx0)
3163 {
3164 ossfcx *ctx = (ossfcx *)ctx0;
3165
3166 /* if the search was already cancelled, do nothing */
3167 if (ctx == 0)
3168 return;
3169
3170 /* delete the context structure */
3171 free(ctx);
3172 }
3173 #endif /* DEPRECATED */
3174
3175 #endif /* MSOS2 */
3176
3177 #ifdef MSDOS
3178 /*
3179 * Check for a special filename
3180 */
3181 enum os_specfile_t os_is_special_file(const char *fname)
3182 {
3183 /* check for '.' */
3184 if (strcmp(fname, ".") == 0)
3185 return OS_SPECFILE_SELF;
3186
3187 /* check for '..' */
3188 if (strcmp(fname, "..") == 0)
3189 return OS_SPECFILE_PARENT;
3190
3191 /* not a special file */
3192 return OS_SPECFILE_NONE;
3193 }
3194
3195 #endif /* MSDOS */
3196