Debian Codegraph @

terps/tads/glk/osportable.cc

raw symbols SCIP
1 /* Adapted from src/osportable.cc from FrobTADS 1.2.3.
2 * FrobTADS copyright (C) 2009 Nikos Chantziaras.
3 */
4
5 /* This file implements some of the functions described in
6 * tads2/osifc.h. We don't need to implement them all, as most of them
7 * are provided by tads2/osnoui.c and tads2/osgen3.c.
8 *
9 * This file implements the "portable" subset of these functions;
10 * functions that depend upon curses/ncurses are defined in oscurses.cc.
11 */
12 #if 0
13 #include "common.h"
14 #include "osstzprs.h"
15 #endif
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <ctype.h>
20 #include <string.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <fcntl.h>
24 #include <unistd.h>
25 #if 0
26 #include <sys/param.h>
27 #ifdef HAVE_LANGINFO_CODESET
28 #include <langinfo.h>
29 #endif
30 #ifdef HAVE_GLOB_H
31 #include <glob.h>
32 #endif
33
34
35 #include "os.h"
36 #ifdef RUNTIME
37 // We utilize the Tads 3 Unicode character mapping facility even for
38 // Tads 2 (only in the interpreter).
39 #include "charmap.h"
40 // Need access to command line options: globalApp->options. Only at
41 // runtime - compiler uses different mechanism for command line
42 // options.
43 #include "frobtadsapp.h"
44 #endif // RUNTIME
45 #endif
46
47 #ifdef GLK
48 #include "osextra.h"
49 #include "charmap.h"
50 #include <time.h>
51 #ifndef _WIN32
52 #include <dirent.h>
53 #endif
54 #include <limits.h>
55
56 #if defined(_WIN32)
57 #include <windows.h>
58 #ifndef PATH_MAX
59 #define PATH_MAX MAX_PATH
60 #endif
61 #define MKDIR_TAKES_ONE_ARG 1
62 #define lstat stat
63 #elif defined(__APPLE__)
64 #define HAVE_GETTIMEOFDAY
65 #include <sys/time.h>
66 #else
67 #define HAVE_CLOCK_GETTIME
68 #endif
69 #define HAVE_MKDIR 1
70 #define T3_RES_DIR 0
71 #define T3_INC_DIR 0
72 #define T3_LIB_DIR 0
73 #define T3_LOG_FILE 0
74
75 #ifdef EMGLKEN
76 #include "glk.h"
77 #include "glkstart.h"
78 #include "emglken.h"
79 #include "osemglken.h"
80
81 #define getcwd emglken_getcwd
82 #define realpath(path, resolved_path) (0)
83 #endif/* EMGLKEN */
84
85 #endif /* GLK */
86
87
88 /* Safe strcpy.
89 * (Copied from tads2/msdos/osdos.c)
90 */
91 static void
92 safe_strcpy(char *dst, size_t dstlen, const char *src)
93 {
94 size_t copylen;
95
96 /* do nothing if there's no output buffer */
97 if (dst == 0 || dstlen == 0)
98 return;
99
100 /* do nothing if the source and destination buffers are the same */
101 if (dst == src)
102 return;
103
104 /* use an empty string if given a null string */
105 if (src == 0)
106 src = "";
107
108 /*
109 * figure the copy length - use the smaller of the actual string size
110 * or the available buffer size, minus one for the null terminator
111 */
112 copylen = strlen(src);
113 if (copylen > dstlen - 1)
114 copylen = dstlen - 1;
115
116 /* copy the string (or as much as we can) */
117 memcpy(dst, src, copylen);
118
119 /* null-terminate it */
120 dst[copylen] = '\0';
121 }
122
123 #if 0
124 /* Service routine.
125 * Try to bring returned by system charset name to a name of one of
126 * the encodings in cmaplib.t3r. The proper way to do it is to
127 * maintain an external database of charset aliases, which user can
128 * edit. But this adds unnecessary complexity, which we really don't
129 * need. So, the "database" is internal.
130 *
131 * TODO: Restore previous bahavior when we fix out curses interface.
132 * For now, we always return "us-ascii".
133 */
134 static const char*
135 get_charset_alias( const char* charset )
136 {
137 const char* p;
138 const char* c;
139
140 // Special case.
141 if (!stricmp(charset, "ANSI_X3.4-1968")) return "us-ascii";
142
143 // If it's in ru_RU.KOI8-R form, try to extract charset part
144 // (everything after last point).
145
146 // Find the last point in the charset name.
147 for (p = charset, c = charset ; *p != '\0' ; ++p) {
148 if (*p == '.') c = p + 1;
149 }
150
151 // '.' was the last symbol in charset name?
152 if (*c == '\0') c = charset;
153
154 if (!stricmp(c, "KOI8-R")) return "koi8-r";
155
156 if (!stricmp(c, "ISO-8859-1")) return "iso1";
157 if (!stricmp(c, "ISO-8859-2")) return "iso2";
158 if (!stricmp(c, "ISO-8859-3")) return "iso3";
159 if (!stricmp(c, "ISO-8859-4")) return "iso4";
160 if (!stricmp(c, "ISO-8859-5")) return "iso5";
161 if (!stricmp(c, "ISO-8859-6")) return "iso6";
162 if (!stricmp(c, "ISO-8859-7")) return "iso7";
163 if (!stricmp(c, "ISO-8859-8")) return "iso8";
164 if (!stricmp(c, "ISO-8859-9")) return "iso9";
165 if (!stricmp(c, "ISO-8859-10")) return "iso10";
166 if (!stricmp(c, "8859-1")) return "iso1";
167 if (!stricmp(c, "8859-2")) return "iso2";
168 if (!stricmp(c, "8859-3")) return "iso3";
169 if (!stricmp(c, "8859-4")) return "iso4";
170 if (!stricmp(c, "8859-5")) return "iso5";
171 if (!stricmp(c, "8859-6")) return "iso6";
172 if (!stricmp(c, "8859-7")) return "iso7";
173 if (!stricmp(c, "8859-8")) return "iso8";
174 if (!stricmp(c, "8859-9")) return "iso9";
175 if (!stricmp(c, "8859-10")) return "iso10";
176
177 if (!stricmp(c, "CP1250")) return "cp1250";
178 if (!stricmp(c, "CP-1250")) return "cp1250";
179 if (!stricmp(c, "CP_1250")) return "cp1250";
180 if (!stricmp(c, "CP1251")) return "cp1251";
181 if (!stricmp(c, "CP-1251")) return "cp1251";
182 if (!stricmp(c, "CP_1251")) return "cp1251";
183 if (!stricmp(c, "CP1252")) return "cp1252";
184 if (!stricmp(c, "CP-1252")) return "cp1252";
185 if (!stricmp(c, "CP_1252")) return "cp1252";
186 if (!stricmp(c, "CP1253")) return "cp1253";
187 if (!stricmp(c, "CP-1253")) return "cp1253";
188 if (!stricmp(c, "CP_1253")) return "cp1253";
189 if (!stricmp(c, "CP1254")) return "cp1254";
190 if (!stricmp(c, "CP-1254")) return "cp1254";
191 if (!stricmp(c, "CP_1254")) return "cp1254";
192 if (!stricmp(c, "CP1255")) return "cp1255";
193 if (!stricmp(c, "CP-1255")) return "cp1255";
194 if (!stricmp(c, "CP_1255")) return "cp1255";
195 if (!stricmp(c, "CP1256")) return "cp1256";
196 if (!stricmp(c, "CP-1256")) return "cp1256";
197 if (!stricmp(c, "CP_1256")) return "cp1256";
198 if (!stricmp(c, "CP1257")) return "cp1257";
199 if (!stricmp(c, "CP-1257")) return "cp1257";
200 if (!stricmp(c, "CP_1257")) return "cp1257";
201 if (!stricmp(c, "CP1258")) return "cp1258";
202 if (!stricmp(c, "CP-1258")) return "cp1258";
203 if (!stricmp(c, "CP_1258")) return "cp1258";
204
205 if (!stricmp(c, "CP437")) return "cp437";
206 if (!stricmp(c, "CP-437")) return "cp437";
207 if (!stricmp(c, "CP_437")) return "cp437";
208 if (!stricmp(c, "PC437")) return "cp437";
209 if (!stricmp(c, "PC-437")) return "cp437";
210 if (!stricmp(c, "PC_437")) return "cp437";
211 if (!stricmp(c, "CP737")) return "cp737";
212 if (!stricmp(c, "CP-737")) return "cp737";
213 if (!stricmp(c, "CP_737")) return "cp737";
214 if (!stricmp(c, "PC737")) return "cp737";
215 if (!stricmp(c, "PC-737")) return "cp737";
216 if (!stricmp(c, "PC_737")) return "cp737";
217 if (!stricmp(c, "CP775")) return "cp775";
218 if (!stricmp(c, "CP-775")) return "cp775";
219 if (!stricmp(c, "CP_775")) return "cp775";
220 if (!stricmp(c, "PC775")) return "cp775";
221 if (!stricmp(c, "PC-775")) return "cp775";
222 if (!stricmp(c, "PC_775")) return "cp775";
223 if (!stricmp(c, "CP850")) return "cp850";
224 if (!stricmp(c, "CP-850")) return "cp850";
225 if (!stricmp(c, "CP_850")) return "cp850";
226 if (!stricmp(c, "PC850")) return "cp850";
227 if (!stricmp(c, "PC-850")) return "cp850";
228 if (!stricmp(c, "PC_850")) return "cp850";
229 if (!stricmp(c, "CP852")) return "cp852";
230 if (!stricmp(c, "CP-852")) return "cp852";
231 if (!stricmp(c, "CP_852")) return "cp852";
232 if (!stricmp(c, "PC852")) return "cp852";
233 if (!stricmp(c, "PC-852")) return "cp852";
234 if (!stricmp(c, "PC_852")) return "cp852";
235 if (!stricmp(c, "CP855")) return "cp855";
236 if (!stricmp(c, "CP-855")) return "cp855";
237 if (!stricmp(c, "CP_855")) return "cp855";
238 if (!stricmp(c, "PC855")) return "cp855";
239 if (!stricmp(c, "PC-855")) return "cp855";
240 if (!stricmp(c, "PC_855")) return "cp855";
241 if (!stricmp(c, "CP857")) return "cp857";
242 if (!stricmp(c, "CP-857")) return "cp857";
243 if (!stricmp(c, "CP_857")) return "cp857";
244 if (!stricmp(c, "PC857")) return "cp857";
245 if (!stricmp(c, "PC-857")) return "cp857";
246 if (!stricmp(c, "PC_857")) return "cp857";
247 if (!stricmp(c, "CP860")) return "cp860";
248 if (!stricmp(c, "CP-860")) return "cp860";
249 if (!stricmp(c, "CP_860")) return "cp860";
250 if (!stricmp(c, "PC860")) return "cp860";
251 if (!stricmp(c, "PC-860")) return "cp860";
252 if (!stricmp(c, "PC_860")) return "cp860";
253 if (!stricmp(c, "CP861")) return "cp861";
254 if (!stricmp(c, "CP-861")) return "cp861";
255 if (!stricmp(c, "CP_861")) return "cp861";
256 if (!stricmp(c, "PC861")) return "cp861";
257 if (!stricmp(c, "PC-861")) return "cp861";
258 if (!stricmp(c, "PC_861")) return "cp861";
259 if (!stricmp(c, "CP862")) return "cp862";
260 if (!stricmp(c, "CP-862")) return "cp862";
261 if (!stricmp(c, "CP_862")) return "cp862";
262 if (!stricmp(c, "PC862")) return "cp862";
263 if (!stricmp(c, "PC-862")) return "cp862";
264 if (!stricmp(c, "PC_862")) return "cp862";
265 if (!stricmp(c, "CP863")) return "cp863";
266 if (!stricmp(c, "CP-863")) return "cp863";
267 if (!stricmp(c, "CP_863")) return "cp863";
268 if (!stricmp(c, "PC863")) return "cp863";
269 if (!stricmp(c, "PC-863")) return "cp863";
270 if (!stricmp(c, "PC_863")) return "cp863";
271 if (!stricmp(c, "CP864")) return "cp864";
272 if (!stricmp(c, "CP-864")) return "cp864";
273 if (!stricmp(c, "CP_864")) return "cp864";
274 if (!stricmp(c, "PC864")) return "cp864";
275 if (!stricmp(c, "PC-864")) return "cp864";
276 if (!stricmp(c, "PC_864")) return "cp864";
277 if (!stricmp(c, "CP865")) return "cp865";
278 if (!stricmp(c, "CP-865")) return "cp865";
279 if (!stricmp(c, "CP_865")) return "cp865";
280 if (!stricmp(c, "PC865")) return "cp865";
281 if (!stricmp(c, "PC-865")) return "cp865";
282 if (!stricmp(c, "PC_865")) return "cp865";
283 if (!stricmp(c, "CP866")) return "cp866";
284 if (!stricmp(c, "CP-866")) return "cp866";
285 if (!stricmp(c, "CP_866")) return "cp866";
286 if (!stricmp(c, "PC866")) return "cp866";
287 if (!stricmp(c, "PC-866")) return "cp866";
288 if (!stricmp(c, "PC_866")) return "cp866";
289 if (!stricmp(c, "CP869")) return "cp869";
290 if (!stricmp(c, "CP-869")) return "cp869";
291 if (!stricmp(c, "CP_869")) return "cp869";
292 if (!stricmp(c, "PC869")) return "cp869";
293 if (!stricmp(c, "PC-869")) return "cp869";
294 if (!stricmp(c, "PC_869")) return "cp869";
295 if (!stricmp(c, "CP874")) return "cp874";
296 if (!stricmp(c, "CP-874")) return "cp874";
297 if (!stricmp(c, "CP_874")) return "cp874";
298 if (!stricmp(c, "PC874")) return "cp874";
299 if (!stricmp(c, "PC-874")) return "cp874";
300 if (!stricmp(c, "PC_874")) return "cp874";
301
302 // There are Mac OS Roman, Central European, Cyrillic, Greek,
303 // Icelandic and Turkish charmaps in cmaplib.t3r. But what codes
304 // system supposed to return?
305
306 // Unrecognized.
307 return charset;
308 }
309 #endif
310
311 /* Open text file for reading and writing.
312 */
313 osfildef*
314 osfoprwt( const char* fname, os_filetype_t )
315 {
316 #ifdef EMGLKEN
317 frefid_t fref = glkunix_fileref_create_by_name_uncleaned(fileusage_TextMode, fname, 0);
318 if (fref) {
319 osfildef *result = glk_stream_open_file(fref, filemode_ReadWrite, 0);
320 glk_fileref_destroy(fref);
321 return result;
322 }
323 return NULL;
324 #else /* EMGLKEN */
325 // assert(fname != 0);
326 // Try opening the file in read/write mode.
327 osfildef* fp = fopen(fname, "r+");
328 // If opening the file failed, it probably means that it doesn't
329 // exist. In that case, create a new file in read/write mode.
330 if (fp == 0) fp = fopen(fname, "w+");
331 return fp;
332 #endif /* EMGLKEN */
333 }
334
335
336 /* Open binary file for reading/writing.
337 */
338 osfildef*
339 osfoprwb( const char* fname, os_filetype_t )
340 {
341 #ifdef EMGLKEN
342 frefid_t fref = glkunix_fileref_create_by_name_uncleaned(fileusage_BinaryMode, fname, 0);
343 if (fref) {
344 osfildef *result = glk_stream_open_file(fref, filemode_ReadWrite, 0);
345 glk_fileref_destroy(fref);
346 return result;
347 }
348 return NULL;
349 #else /* EMGLKEN */
350 // assert(fname != 0);
351 osfildef* fp = fopen(fname, "r+b");
352 if (fp == 0) fp = fopen(fname, "w+b");
353 return fp;
354 #endif /* EMGLKEN */
355 }
356
357 /* Duplicate a file hand.e
358 */
359 osfildef*
360 osfdup(osfildef *orig, const char *mode)
361 {
362 const char *m;
363
364 /* verify that there aren't any unrecognized mode flags */
365 for (m = mode ; *m != '\0' ; ++m)
366 {
367 if (strchr("rw+bst", *m) == 0)
368 return 0;
369 }
370
371 #ifdef EMGLKEN
372 const char *filename = glkunix_stream_get_filename(orig);
373 glui32 fmode = filemode_Read;
374 glui32 usage = fileusage_TextMode;
375
376 if (mode[0] == 'r') {
377 if (mode[1] == '+') {
378 fmode = filemode_ReadWrite;
379 }
380 }
381 else if (mode[0] == 'w') {
382 // I'm not sure this is right, but the description in osifc.h really isn't specific enough
383 fmode = filemode_WriteAppend;
384 }
385 else {
386 return 0;
387 }
388 if (strchr(mode, 'b') != NULL) {
389 usage = fileusage_BinaryMode;
390 }
391
392 frefid_t fref = glkunix_fileref_create_by_name_uncleaned(usage, filename, 0);
393 if (fref) {
394 osfildef *result = glk_stream_open_file(fref, fmode, 0);
395 glk_fileref_destroy(fref);
396 return result;
397 }
398 return NULL;
399 #else /* EMGLKEN */
400 char realmode[5];
401 char *p = realmode;
402
403 /* figure the read/write mode - translate r+ and w+ to r+ */
404 if ((mode[0] == 'r' || mode[0] == 'w') && mode[1] == '+')
405 *p++ = 'r', *p++ = '+';
406 else if (mode[0] == 'r')
407 *p++ = 'r';
408 else if (mode[0] == 'w')
409 *p++ = 'w';
410 else
411 return 0;
412
413 /* end the mode string */
414 *p = '\0';
415
416 /* duplicate the handle in the given mode */
417 // Shouldn't this be realmode?
418 return fdopen(dup(fileno(orig)), mode);
419 #endif /* EMGLKEN */
420 }
421
422
423 /* Convert string to all-lowercase.
424 */
425 char*
426 os_strlwr( char* s )
427 {
428 // assert(s != 0);
429 for (int i = 0; s[i] != '\0'; ++i) {
430 #if 0
431 s[i] = tolower(s[i]);
432 #endif
433 s[i] = tolower((unsigned char)s[i]);
434 }
435 return s;
436 }
437
438
439 /* Seek to the resource file embedded in the current executable file.
440 *
441 * We don't support this (and probably never will).
442 */
443 osfildef*
444 os_exeseek( const char*, const char* )
445 {
446 #if 0
447 return static_cast(osfildef*)(0);
448 #endif
449 return static_cast<osfildef*>(0);
450 }
451
452
453 #if 0
454 /* Create and open a temporary file.
455 */
456 osfildef*
457 os_create_tempfile( const char* fname, char* buf )
458 {
459 if (fname != 0 and fname[0] != '\0') {
460 // A filename has been specified; use it.
461 return fopen(fname, "w+b");
462 }
463
464 //ASSERT(buf != 0);
465
466 // No filename needed; create a nameless tempfile.
467 buf[0] = '\0';
468 return tmpfile();
469 }
470
471
472 /* Delete a temporary file created with os_create_tempfile().
473 */
474 int
475 osfdel_temp( const char* fname )
476 {
477 //ASSERT(fname != 0);
478
479 if (fname[0] == '\0' or remove(fname) == 0) {
480 // Either it was a nameless temp-file and has been
481 // already deleted by the system, or deleting it
482 // succeeded. In either case, the operation was
483 // successful.
484 return 0;
485 }
486 // It was not a nameless tempfile and remove() failed.
487 return 1;
488 }
489
490
491 /* Generate a temporary filename.
492 */
493 int
494 os_gen_temp_filename( char* buf, size_t buflen )
495 {
496 // Get the temporary directory: use the environment variable TMPDIR
497 // if it's defined, otherwise use P_tmpdir; if even that's not
498 // defined, return failure.
499 const char* tmp = getenv("TMPDIR");
500 if (tmp == 0)
501 tmp = P_tmpdir;
502 if (tmp == 0)
503 return false;
504
505 // Build a template filename for mkstemp.
506 snprintf(buf, buflen, "%s/tads-XXXXXX", tmp);
507
508 // Generate a unique name and open the file.
509 int fd = mkstemp(buf);
510 if (fd >= 0) {
511 // Got it - close the placeholder file and return success.
512 close(fd);
513 return true;
514 }
515 // Failed.
516 return false;
517 }
518 #endif
519
520 /* tads2/osnoui.c defines DOS versions of those routine when MSDOS is defined.
521 */
522 #ifndef MSDOS
523
524 /* Get the temporary file path.
525 */
526 void
527 os_get_tmp_path( char* buf )
528 {
529 #ifdef _WIN32
530 GetTempPath(OSFNMAX, buf);
531 #else
532 // Try the usual env. variable first.
533 const char* tmpDir = getenv("TMPDIR");
534
535 // If no such variable exists, try P_tmpdir (if defined in
536 // <stdio.h>).
537 #ifdef P_tmpdir
538 if (tmpDir == 0 or tmpDir[0] == '\0') {
539 tmpDir = P_tmpdir;
540 }
541 #endif
542
543 // If we still lack a path, use "/tmp".
544 if (tmpDir == 0 or tmpDir[0] == '\0') {
545 tmpDir = "/tmp";
546 }
547
548 // If the directory doesn't exist or is not a directory, don't
549 // provide anything at all (which means that the current
550 // directory will be used).
551 struct stat inf;
552 int statRet = stat(tmpDir, &inf);
553 if (statRet != 0 or (inf.st_mode & S_IFMT) != S_IFDIR) {
554 buf[0] = '\0';
555 return;
556 }
557
558 strcpy(buf, tmpDir);
559
560 // Append a slash if necessary.
561 size_t len = strlen(buf);
562 if (buf[len - 1] != '/') {
563 buf[len] = '/';
564 buf[len + 1] = '\0';
565 }
566 #endif
567 }
568
569 /* Create a directory.
570 */
571 int
572 os_mkdir( const char* dir, int create_parents )
573 {
574 //assert(dir != 0);
575
576 if (dir[0] == '\0')
577 return true;
578
579 // Copy the directory name to a new string so we can strip any trailing
580 // path seperators.
581 size_t len = strlen(dir);
582 char* tmp = new char[len + 1];
583 strncpy(tmp, dir, len);
584 while (tmp[len - 1] == OSPATHCHAR)
585 --len;
586 tmp[len] = '\0';
587
588 // If we're creating intermediate diretories, and the path contains
589 // multiple elements, recursively create the parent directories first.
590 if (create_parents and strchr(tmp, OSPATHCHAR) != 0) {
591 char par[OSFNMAX];
592
593 // Extract the parent path.
594 os_get_path_name(par, sizeof(par), tmp);
595
596 // If the parent doesn't already exist, create it recursively.
597 if (osfacc(par) != 0 and not os_mkdir(par, true)) {
598 delete[] tmp;
599 return false;
600 }
601 }
602
603 // Create the directory.
604 int ret =
605 #if HAVE_MKDIR
606 # if MKDIR_TAKES_ONE_ARG
607 mkdir(tmp);
608 # else
609 mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO);
610 # endif
611 #elif HAVE__MKDIR
612 _mkdir(tmp);
613 #else
614 # error "Neither mkdir() nor _mkdir() is available on this system."
615 #endif
616 delete[] tmp;
617 return ret == 0;
618 }
619
620 /* Remove a directory.
621 */
622 int
623 os_rmdir( const char *dir )
624 {
625 return rmdir(dir) == 0;
626 }
627
628 #endif // not MSDOS
629
630 /* Get a file's mode/type. This returns the same information as
631 * the 'mode' member of os_file_stat_t from os_file_stat(), so we
632 * simply call that routine and return the value.
633 */
634 int
635 osfmode( const char *fname, int follow_links, unsigned long *mode,
636 unsigned long* attr )
637 {
638 // TODO: Emglken
639 os_file_stat_t s;
640 int ok;
641 if ((ok = os_file_stat(fname, follow_links, &s)) != false) {
642 if (mode != NULL)
643 *mode = s.mode;
644 if (attr != NULL)
645 *attr = s.attrs;
646 }
647 return ok;
648 }
649
650 /* Get full stat() information on a file.
651 */
652 int
653 os_file_stat( const char *fname, int follow_links, os_file_stat_t *s )
654 {
655 // TODO: Emglken
656 struct stat buf;
657 if ((follow_links ? stat(fname, &buf) : lstat(fname, &buf)) != 0)
658 return false;
659
660 s->sizelo = (uint32_t)(buf.st_size & 0xFFFFFFFF);
661 s->sizehi = sizeof(buf.st_size) > 4
662 ? (uint32_t)((buf.st_size >> 32) & 0xFFFFFFFF)
663 : 0;
664 s->cre_time = buf.st_ctime;
665 s->mod_time = buf.st_mtime;
666 s->acc_time = buf.st_atime;
667 s->mode = buf.st_mode;
668 s->attrs = 0;
669
670 #ifdef _WIN32
671 s->attrs = oss_get_file_attrs(fname);
672 #else
673 if (os_get_root_name(fname)[0] == '.') {
674 s->attrs |= OSFATTR_HIDDEN;
675 }
676
677 // If we're the owner, check if we have read/write access.
678 if (geteuid() == buf.st_uid) {
679 if (buf.st_mode & S_IRUSR)
680 s->attrs |= OSFATTR_READ;
681 if (buf.st_mode & S_IWUSR)
682 s->attrs |= OSFATTR_WRITE;
683 return true;
684 }
685
686 // Check if one of our groups matches the file's group and if so, check
687 // for read/write access.
688
689 // Also reserve a spot for the effective group ID, which might
690 // not be included in the list in our next call.
691 int grpSize = getgroups(0, NULL) + 1;
692 // Paranoia.
693 if (grpSize > NGROUPS_MAX or grpSize < 0)
694 return false;
695 gid_t* groups = new gid_t[grpSize];
696 if (getgroups(grpSize - 1, groups + 1) < 0) {
697 delete[] groups;
698 return false;
699 }
700 groups[0] = getegid();
701 int i;
702 for (i = 0; i < grpSize and buf.st_gid != groups[i]; ++i)
703 ;
704 delete[] groups;
705 if (i < grpSize) {
706 if (buf.st_mode & S_IRGRP)
707 s->attrs |= OSFATTR_READ;
708 if (buf.st_mode & S_IWGRP)
709 s->attrs |= OSFATTR_WRITE;
710 return true;
711 }
712
713 // We're neither the owner of the file nor do we belong to its
714 // group. Check whether the file is world readable/writable.
715 if (buf.st_mode & S_IROTH)
716 s->attrs |= OSFATTR_READ;
717 if (buf.st_mode & S_IWOTH)
718 s->attrs |= OSFATTR_WRITE;
719 #endif
720 return true;
721 }
722
723 /* Manually resolve a symbolic link.
724 */
725 int
726 os_resolve_symlink( const char *fname, char *target, size_t target_size )
727 {
728 // TODO: Emglken
729 #ifdef _WIN32
730 return false;
731 #else
732 // get the stat() information for the *undereferenced* link; if
733 // it's not actually a link, there's nothing to resolve
734 struct stat buf;
735 if (lstat(fname, &buf) != 0 or (buf.st_mode & S_IFLNK) == 0)
736 return false;
737
738 // read the link contents (maxing out at the buffer size)
739 size_t copylen = (size_t)buf.st_size;
740 if (copylen > target_size - 1)
741 copylen = target_size - 1;
742 if (readlink(fname, target, copylen) < 0)
743 return false;
744
745 // null-terminate the result and return success
746 target[copylen] = '\0';
747 return true;
748 #endif
749 }
750
751 #if 0
752 /* Get a suitable seed for a random number generator.
753 *
754 * We don't just use the system-clock, but build a number as random as
755 * the mechanisms of the standard C-library allow. This is somewhat of
756 * an overkill, but it's simple enough so here goes. Someone has to
757 * write a nuclear war simulator in TADS to test this thoroughly.
758 */
759 void
760 os_rand( long* val )
761 {
762 //assert(val != 0);
763 // Use the current time as the first seed.
764 srand(static_cast(unsigned int)(time(0)));
765
766 // Create the final seed by generating a random number using
767 // high-order bits, because on some systems the low-order bits
768 // aren't very random.
769 *val = 1 + static_cast(long)(static_cast(long double)(65535) * rand() / (RAND_MAX + 1.0));
770 }
771
772
773 /* Generate random bytes for use in seeding a PRNG (pseudo-random number
774 * generator). This is an extended version of os_rand() for PRNGs that use
775 * large seed vectors containing many bytes, rather than the simple 32-bit
776 * seed that os_rand() assumes.
777 */
778 void os_gen_rand_bytes( unsigned char* buf, size_t len )
779 {
780 // Read bytes from /dev/urandom to fill the buffer (use /dev/urandom
781 // rather than /dev/random, so that we don't block for long periods -
782 // /dev/random can be quite slow because it's designed not to return
783 // any bits until a fairly high threshold of entropy has been reached).
784 int f = open("/dev/urandom", O_RDONLY);
785 read(f, (void*)buf, len);
786 close(f);
787 }
788 #endif
789
790 /* Get the current system high-precision timer.
791 *
792 * We provide four (4) implementations of this function:
793 *
794 * 1. clock_gettime() is available
795 * 2. gettimeofday() is available
796 * 3. ftime() is available
797 * 4. Neither is available - fall back to time()
798 *
799 * Note that HAVE_CLOCK_GETTIME, HAVE_GETTIMEOFDAY and HAVE_FTIME are
800 * mutually exclusive; if one of them is defined, the others aren't. No
801 * need for #else here.
802 *
803 * Although not required by the TADS VM, these implementations will
804 * always return 0 on the first call.
805 */
806 #ifdef HAVE_CLOCK_GETTIME
807 // The system has the clock_gettime() function.
808 long
809 os_get_sys_clock_ms( void )
810 {
811 // We need to remember the exact time this function has been
812 // called for the first time, and use that time as our
813 // zero-point. On each call, we simply return the difference
814 // in milliseconds between the current time and our zero point.
815 static struct timespec zeroPoint;
816
817 // Did we get the zero point yet?
818 static bool initialized = false;
819
820 // Not all systems provide a monotonic clock; check if it's
821 // available before falling back to the global system-clock. A
822 // monotonic clock is guaranteed not to change while the system
823 // is running, so we prefer it over the global clock.
824 static const clockid_t clockType =
825 #ifdef HAVE_CLOCK_MONOTONIC
826 CLOCK_MONOTONIC;
827 #else
828 CLOCK_REALTIME;
829 #endif
830 // We must get the current time in each call.
831 struct timespec currTime;
832
833 // Initialize our zero-point, if not already done so.
834 if (not initialized) {
835 clock_gettime(clockType, &zeroPoint);
836 initialized = true;
837 }
838
839 // Get the current time.
840 clock_gettime(clockType, &currTime);
841
842 // Note that tv_nsec contains *nano*seconds, not milliseconds,
843 // so we need to convert it; a millisec is 1.000.000 nanosecs.
844 return (currTime.tv_sec - zeroPoint.tv_sec) * 1000
845 + (currTime.tv_nsec - zeroPoint.tv_nsec) / 1000000;
846 }
847
848 /* Get the time since the Unix Epoch in seconds and nanoseconds.
849 */
850 void
851 os_time_ns( os_time_t *seconds, long *nanoseconds )
852 {
853 // Get the current time.
854 static const clockid_t clockType = CLOCK_REALTIME;
855 struct timespec currTime;
856 clock_gettime(clockType, &currTime);
857
858 // return the data
859 *seconds = currTime.tv_sec;
860 *nanoseconds = currTime.tv_nsec;
861 }
862 #endif // HAVE_CLOCK_GETTIME
863
864 #ifdef HAVE_GETTIMEOFDAY
865 // The system has the gettimeofday() function.
866 long
867 os_get_sys_clock_ms( void )
868 {
869 static struct timeval zeroPoint;
870 static bool initialized = false;
871 // gettimeofday() needs the timezone as a second argument. This
872 // is obsolete today, but we don't care anyway; we just pass
873 // something.
874 #if 0
875 struct timezone bogus = {0, 0};
876 #endif
877 struct timeval currTime;
878
879 if (not initialized) {
880 #if 0
881 gettimeofday(&zeroPoint, &bogus);
882 #endif
883 gettimeofday(&zeroPoint, NULL);
884 initialized = true;
885 }
886
887 #if 0
888 gettimeofday(&currTime, &bogus);
889 #endif
890 gettimeofday(&currTime, NULL);
891
892 // 'tv_usec' contains *micro*seconds, not milliseconds. A
893 // millisec is 1.000 microsecs.
894 return (currTime.tv_sec - zeroPoint.tv_sec) * 1000 + (currTime.tv_usec - zeroPoint.tv_usec) / 1000;
895 }
896
897 /* Get the time since the Unix Epoch in seconds and nanoseconds.
898 */
899 void
900 os_time_ns( os_time_t *seconds, long *nanoseconds )
901 {
902 // get the time
903 #if 0
904 struct timezone bogus = {0, 0};
905 #endif
906 struct timeval currTime;
907 #if 0
908 gettimeofday(&currTime, &bogus);
909 #endif
910 gettimeofday(&currTime, NULL);
911
912 // return the data, converting milliseconds to nanoseconds
913 *seconds = currTime.tv_sec;
914 *nanoseconds = currTime.tv_usec * 1000;
915 }
916 #endif // HAVE_GETTIMEOFDAY
917
918
919 #ifdef HAVE_FTIME
920 // The system has the ftime() function. ftime() is in <sys/timeb.h>.
921 #include <sys/timeb.h>
922 long
923 os_get_sys_clock_ms( void )
924 {
925 static timeb zeroPoint;
926 static bool initialized = false;
927 struct timeb currTime;
928
929 if (not initialized) {
930 ftime(&zeroPoint);
931 initialized = true;
932 }
933
934 ftime(&currTime);
935 return (currTime.time - zeroPoint.time) * 1000 + (currTime.millitm - zeroPoint.millitm);
936 }
937
938 /* Get the time since the Unix Epoch in seconds and nanoseconds.
939 */
940 void
941 os_time_ns( os_time_t *seconds, long *nanoseconds )
942 {
943 // get the time
944 struct timeb currTime;
945 ftime(&currTime);
946
947 // return the data, converting milliseconds to nanoseconds
948 *seconds = currTime.time;
949 *nanoseconds = (long)currTime.millitm * 1000000;
950 }
951 #endif // HAVE_FTIME
952
953
954 #ifndef HAVE_CLOCK_GETTIME
955 #ifndef HAVE_GETTIMEOFDAY
956 #ifndef HAVE_FTIME
957 // Use the standard time() function from the C library. We lose
958 // millisecond-precision, but that's the best we can do with time().
959 long
960 os_get_sys_clock_ms( void )
961 {
962 static time_t zeroPoint = time(0);
963 return (time(0) - zeroPoint) * 1000;
964 }
965
966 void
967 os_time_ns( os_time_t *seconds, long *nanoseconds )
968 {
969 // get the regular time() value in seconds; we have no
970 // higher precision element to return, so return zero
971 #if 0
972 *seconds = time();
973 #endif
974 *seconds = time(0);
975 *nanoseconds = 0;
976 }
977 #endif
978 #endif
979 #endif
980
981
982 /* Get filename from startup parameter, if possible.
983 *
984 * TODO: Find out what this is supposed to do.
985 */
986 int
987 os_paramfile( char* )
988 {
989 return 0;
990 }
991
992
993 /* Open a directory search.
994 */
995 int os_open_dir(const char *dirname, osdirhdl_t *hdl)
996 {
997 #ifdef _WIN32
998 auto attrs = GetFileAttributesA(dirname);
999 if (attrs == INVALID_FILE_ATTRIBUTES || (attrs & FILE_ATTRIBUTE_DIRECTORY) == 0)
1000 return false;
1001
1002 // a directory, proceed
1003 Win32Dir *dirp = (Win32Dir *) malloc(sizeof(Win32Dir));
1004 if (!dirp) return false;
1005 size_t dirlen = strlen(dirname);
1006 dirp->dirname = (char *) malloc(dirlen + 4);
1007 if (!dirp->dirname) return false;
1008 // Adjust dirname for Windows FindFile conventions
1009 if (dirp->dirname[dirlen - 1] == '\\' || dirp->dirname[dirlen - 1] == '/') {
1010 dirp->dirname[dirlen] = '*';
1011 dirp->dirname[dirlen + 1] = 0;
1012 } else {
1013 dirp->dirname[dirlen] = '\\';
1014 dirp->dirname[dirlen + 1] = '*';
1015 dirp->dirname[dirlen + 2] = 0;
1016 }
1017 *hdl = dirp;
1018 return true;
1019 #else
1020 // TODO: Emglken
1021 return (*hdl = opendir(dirname)) != NULL;
1022 #endif
1023 }
1024
1025 /* Read the next result in a directory search.
1026 */
1027 int os_read_dir(osdirhdl_t hdl, char *buf, size_t buflen)
1028 {
1029 #ifdef _WIN32
1030 struct Win32Dir *dirp = (struct Win32Dir *) hdl;
1031 if (dirp->hFindFile == NULL) { // first call, begin enumeration
1032 dirp->hFindFile = FindFirstFileA(dirp->dirname, &(dirp->findFileData));
1033 if (dirp->hFindFile == INVALID_HANDLE_VALUE) // nothing found, return failure
1034 return false;
1035 } else { // continue
1036 // if we've exhausted the search, return failure
1037 if (FindNextFileA(dirp->hFindFile, &(dirp->findFileData)) == 0)
1038 return false;
1039 }
1040 safe_strcpy(buf, buflen, dirp->findFileData.cFileName);
1041 return true;
1042 #else
1043 // TODO: Emglken
1044 // Read the next directory entry - if we've exhausted the search,
1045 // return failure.
1046 struct dirent *d = readdir(hdl);
1047 if (d == 0)
1048 return false;
1049
1050 // return this entry
1051 safe_strcpy(buf, buflen, d->d_name);
1052 return true;
1053 #endif
1054 }
1055
1056 /* Close a directory search.
1057 */
1058 void os_close_dir(osdirhdl_t hdl)
1059 {
1060 #ifdef _WIN32
1061 if (hdl->hFindFile)
1062 FindClose(hdl->hFindFile);
1063 free(hdl->dirname);
1064 free(hdl);
1065 #else
1066 // TODO: Emglken
1067 closedir(hdl);
1068 #endif
1069 }
1070
1071
1072 /* Determine if the given filename refers to a special file.
1073 *
1074 * tads2/osnoui.c defines its own version when MSDOS is defined.
1075 */
1076 #ifndef MSDOS
1077 os_specfile_t
1078 os_is_special_file( const char* fname )
1079 {
1080 // We also check for "./" and "../" instead of just "." and
1081 // "..". (We use OSPATHCHAR instead of '/' though.)
1082 const char selfWithSep[3] = {'.', OSPATHCHAR, '\0'};
1083 const char parentWithSep[4] = {'.', '.', OSPATHCHAR, '\0'};
1084 if ((strcmp(fname, ".") == 0) or (strcmp(fname, selfWithSep) == 0)) return OS_SPECFILE_SELF;
1085 if ((strcmp(fname, "..") == 0) or (strcmp(fname, parentWithSep) == 0)) return OS_SPECFILE_PARENT;
1086 return OS_SPECFILE_NONE;
1087 }
1088 #endif
1089
1090
1091 #if 1
1092 extern "C" void canonicalize_path(char *path);
1093 #else
1094 /* Canonicalize a path: remove ".." and "." relative elements.
1095 * (Copied from tads2/osnoui.c)
1096 */
1097 static void
1098 canonicalize_path(char *path)
1099 {
1100 char *p;
1101 char *start;
1102
1103 /* keep going until we're done */
1104 for (start = p = path ; ; ++p)
1105 {
1106 /* if it's a separator, note it and process the path element */
1107 if (*p == '\\' || *p == '/' || *p == '\0')
1108 {
1109 /*
1110 * check the path element that's ending here to see if it's a
1111 * relative item - either "." or ".."
1112 */
1113 if (p - start == 1 && *start == '.')
1114 {
1115 /*
1116 * we have a '.' element - simply remove it along with the
1117 * path separator that follows
1118 */
1119 if (*p == '\\' || *p == '/')
1120 memmove(start, p + 1, strlen(p+1) + 1);
1121 else if (start > path)
1122 *(start - 1) = '\0';
1123 else
1124 *start = '\0';
1125 }
1126 else if (p - start == 2 && *start == '.' && *(start+1) == '.')
1127 {
1128 char *prv;
1129
1130 /*
1131 * we have a '..' element - find the previous path element,
1132 * if any, and remove it, along with the '..' and the
1133 * subsequent separator
1134 */
1135 for (prv = start ;
1136 prv > path && (*(prv-1) != '\\' || *(prv-1) == '/') ;
1137 --prv) ;
1138
1139 /* if we found a separator, remove the previous element */
1140 if (prv > start)
1141 {
1142 if (*p == '\\' || *p == '/')
1143 memmove(prv, p + 1, strlen(p+1) + 1);
1144 else if (start > path)
1145 *(start - 1) = '\0';
1146 else
1147 *start = '\0';
1148 }
1149 }
1150
1151 /* note the start of the next element */
1152 start = p + 1;
1153 }
1154
1155 /* stop at the end of the string */
1156 if (*p == '\0')
1157 break;
1158 }
1159 }
1160 #endif
1161
1162 #ifdef _WIN32
1163 /* This file only ever calls realpath() with resolved_name as NULL. */
1164 static char *realpath(const char *file_name, char *resolved_name)
1165 {
1166 resolved_name = (char *)malloc(PATH_MAX + 1);
1167 if (resolved_name == NULL)
1168 return NULL;
1169
1170 DWORD len = GetFullPathName(file_name, PATH_MAX + 1, resolved_name, NULL);
1171 if (!len || len > PATH_MAX)
1172 return NULL;
1173
1174 return resolved_name;
1175 }
1176 #endif
1177
1178
1179 /* Resolve symbolic links in a path. It's okay for 'buf' and 'path'
1180 * to point to the same buffer if you wish to resolve a path in place.
1181 */
1182 static void
1183 resolve_path( char *buf, size_t buflen, const char *path )
1184 {
1185 // Starting with the full path string, try resolving the path with
1186 // realpath(). The tricky bit is that realpath() will fail if any
1187 // component of the path doesn't exist, but we need to resolve paths
1188 // for prospective filenames, such as files or directories we're
1189 // about to create. So if realpath() fails, remove the last path
1190 // component and try again with the remainder. Repeat until we
1191 // can resolve a real path, or run out of components to remove.
1192 // The point of this algorithm is that it will resolve as much of
1193 // the path as actually exists in the file system, ensuring that
1194 // we resolve any links that affect the path. Any portion of the
1195 // path that doesn't exist obviously can't refer to a link, so it
1196 // will be taken literally. Once we've resolved the longest prefix,
1197 // tack the stripped portion back on to form the fully resolved
1198 // path.
1199
1200 // make a writable copy of the path to work with
1201 size_t pathl = strlen(path);
1202 char *mypath = new char[pathl + 1];
1203 memcpy(mypath, path, pathl + 1);
1204
1205 // start at the very end of the path, with no stripped suffix yet
1206 char *suffix = mypath + pathl;
1207 char sl = '\0';
1208
1209 // keep going until we resolve something or run out of path
1210 for (;;)
1211 {
1212 // resolve the current prefix, allocating the result
1213 char *rpath = realpath(mypath, 0);
1214
1215 // un-split the path
1216 *suffix = sl;
1217
1218 // if we resolved the prefix, return the result
1219 if (rpath != 0)
1220 {
1221 // success - if we separated a suffix, reattach it
1222 if (*suffix != '\0')
1223 {
1224 // reattach the suffix (the part after the '/')
1225 for ( ; *suffix == '/' ; ++suffix) ;
1226 os_build_full_path(buf, buflen, rpath, suffix);
1227 }
1228 else
1229 {
1230 // no suffix, so we resolved the entire path
1231 safe_strcpy(buf, buflen, rpath);
1232 }
1233
1234 // done with the resolved path
1235 free(rpath);
1236
1237 // ...and done searching
1238 break;
1239 }
1240
1241 // no luck with realpath(); search for the '/' at the end of the
1242 // previous component in the path
1243 for ( ; suffix > mypath && *(suffix-1) != '/' ; --suffix) ;
1244
1245 // skip any redundant slashes
1246 for ( ; suffix > mypath && *(suffix-1) == '/' ; --suffix) ;
1247
1248 // if we're at the root element, we're out of path elements
1249 if (suffix == mypath)
1250 {
1251 // we can't resolve any part of the path, so just return the
1252 // original path unchanged
1253 safe_strcpy(buf, buflen, mypath);
1254 break;
1255 }
1256
1257 // split the path here into prefix and suffix, and try again
1258 sl = *suffix;
1259 *suffix = '\0';
1260 }
1261
1262 // done with our writable copy of the path
1263 delete [] mypath;
1264 }
1265
1266 /* Is the given file in the given directory?
1267 */
1268 int
1269 os_is_file_in_dir( const char* filename, const char* path,
1270 int allow_subdirs, int match_self )
1271 {
1272 char filename_buf[OSFNMAX], path_buf[OSFNMAX];
1273 size_t flen, plen;
1274
1275 // Absolute-ize the filename, if necessary.
1276 if (not os_is_file_absolute(filename)) {
1277 os_get_abs_filename(filename_buf, sizeof(filename_buf), filename);
1278 filename = filename_buf;
1279 }
1280
1281 // Absolute-ize the path, if necessary.
1282 if (not os_is_file_absolute(path)) {
1283 os_get_abs_filename(path_buf, sizeof(path_buf), path);
1284 path = path_buf;
1285 }
1286
1287 // Canonicalize the paths, to remove .. and . elements - this will make
1288 // it possible to directly compare the path strings. Also resolve it
1289 // to the extent possible, to make sure we're not fooled by symbolic
1290 // links.
1291 safe_strcpy(filename_buf, sizeof(filename_buf), filename);
1292 canonicalize_path(filename_buf);
1293 resolve_path(filename_buf, sizeof(filename_buf), filename_buf);
1294 filename = filename_buf;
1295
1296 safe_strcpy(path_buf, sizeof(path_buf), path);
1297 canonicalize_path(path_buf);
1298 resolve_path(path_buf, sizeof(path_buf), path_buf);
1299 path = path_buf;
1300
1301 // Get the length of the filename and the length of the path.
1302 flen = strlen(filename);
1303 plen = strlen(path);
1304
1305 // If the path ends in a separator character, ignore that.
1306 if (plen > 0 and path[plen-1] == OSPATHCHAR)
1307 --plen;
1308
1309 // if the names match, return true if and only if we're matching the
1310 // directory to itself
1311 if (plen == flen && memcmp(filename, path, flen) == 0)
1312 return match_self;
1313
1314 // Check that the filename has 'path' as its path prefix. First, check
1315 // that the leading substring of the filename matches 'path', ignoring
1316 // case. Note that we need the filename to be at least two characters
1317 // longer than the path: it must have a path separator after the path
1318 // name, and at least one character for a filename past that.
1319 if (flen < plen + 2 or memcmp(filename, path, plen) != 0)
1320 return false;
1321
1322 // Okay, 'path' is the leading substring of 'filename'; next make sure
1323 // that this prefix actually ends at a path separator character in the
1324 // filename. (This is necessary so that we don't confuse "c:\a\b.txt"
1325 // as matching "c:\abc\d.txt" - if we only matched the "c:\a" prefix,
1326 // we'd miss the fact that the file is actually in directory "c:\abc",
1327 // not "c:\a".)
1328 if (filename[plen] != OSPATHCHAR)
1329 return false;
1330
1331 // We're good on the path prefix - we definitely have a file that's
1332 // within the 'path' directory or one of its subdirectories. If we're
1333 // allowed to match on subdirectories, we already have our answer
1334 // (true). If we're not allowed to match subdirectories, we still have
1335 // one more check, which is that the rest of the filename is free of
1336 // path separator charactres. If it is, we have a file that's directly
1337 // in the 'path' directory; otherwise it's in a subdirectory of 'path'
1338 // and thus isn't a match.
1339 if (allow_subdirs) {
1340 // Filename is in the 'path' directory or one of its
1341 // subdirectories, and we're allowed to match on subdirectories, so
1342 // we have a match.
1343 return true;
1344 }
1345
1346 // We're not allowed to match subdirectories, so scan the rest of
1347 // the filename for path separators. If we find any, the file is
1348 // in a subdirectory of 'path' rather than directly in 'path'
1349 // itself, so it's not a match. If we don't find any separators,
1350 // we have a file directly in 'path', so it's a match.
1351 const char* p;
1352 for (p = filename; *p != '\0' and *p != OSPATHCHAR ; ++p)
1353 ;
1354
1355 // If we reached the end of the string without finding a path
1356 // separator character, it's a match .
1357 return *p == '\0';
1358 }
1359
1360
1361 /* Get the absolute path for a given filename.
1362 */
1363 int
1364 os_get_abs_filename( char* buf, size_t buflen, const char* filename )
1365 {
1366 // If the filename is already absolute, copy it; otherwise combine
1367 // it with the working directory.
1368 if (os_is_file_absolute(filename))
1369 {
1370 // absolute - copy it as-is
1371 safe_strcpy(buf, buflen, filename);
1372 }
1373 else
1374 {
1375 // combine it with the working directory to get the path
1376 char pwd[OSFNMAX];
1377 if (getcwd(pwd, sizeof(pwd)) != 0)
1378 os_build_full_path(buf, buflen, pwd, filename);
1379 else
1380 safe_strcpy(buf, buflen, filename);
1381 }
1382
1383 // canonicalize the result
1384 canonicalize_path(buf);
1385
1386 // Try getting the canonical path from the OS (allocating the
1387 // result buffer).
1388 char* newpath = realpath(filename, 0);
1389 if (newpath != 0) {
1390 // Copy the output (truncating if it's too long).
1391 safe_strcpy(buf, buflen, newpath);
1392 free(newpath);
1393 return true;
1394 }
1395
1396 // realpath() failed, but that's okay - realpath() only works if the
1397 // path refers to an existing file, but it's valid for callers to
1398 // pass non-existent filenames, such as names of files they're about
1399 // to create, or hypothetical paths being used for comparison
1400 // purposes or for future use. Simply return the canonical path
1401 // name we generated above.
1402 return true;
1403 }
1404
1405
1406 /* ------------------------------------------------------------------------ */
1407 /*
1408 * Get the file system roots. Unix has the lovely unified namespace with
1409 * just the one root, /, so this is quite simple.
1410 */
1411 size_t os_get_root_dirs(char *buf, size_t buflen)
1412 {
1413 // TODO: Emglken
1414 static const char ret[] = { '/', 0, 0 };
1415
1416 // if there's room, copy the root string "/" and an extra null
1417 // terminator for the overall list
1418 if (buflen >= sizeof(ret))
1419 memcpy(buf, ret, sizeof(ret));
1420
1421 // return the required size
1422 return sizeof(ret);
1423 }
1424
1425
1426 /* ------------------------------------------------------------------------ */
1427 /* Get a special directory path.
1428 *
1429 * If env. variables exist, they always override the compile-time
1430 * defaults.
1431 *
1432 * We ignore the argv parameter, since on Unix binaries aren't stored
1433 * together with data on disk.
1434 */
1435 void
1436 os_get_special_path( char* buf, size_t buflen, const char* argv0, int id )
1437 {
1438 const char* res;
1439
1440 switch (id) {
1441 case OS_GSP_T3_RES:
1442 res = getenv("T3_RESDIR");
1443 if (res == 0 or res[0] == '\0') {
1444 res = T3_RES_DIR;
1445 }
1446 break;
1447
1448 case OS_GSP_T3_INC:
1449 res = getenv("T3_INCDIR");
1450 if (res == 0 or res[0] == '\0') {
1451 res = T3_INC_DIR;
1452 }
1453 break;
1454
1455 case OS_GSP_T3_LIB:
1456 res = getenv("T3_LIBDIR");
1457 if (res == 0 or res[0] == '\0') {
1458 res = T3_LIB_DIR;
1459 }
1460 break;
1461
1462 case OS_GSP_T3_USER_LIBS:
1463 // There's no compile-time default for user libs.
1464 res = getenv("T3_USERLIBDIR");
1465 break;
1466
1467 case OS_GSP_T3_SYSCONFIG:
1468 res = getenv("T3_CONFIG");
1469 if (res == 0 and argv0 != 0) {
1470 os_get_path_name(buf, buflen, argv0);
1471 return;
1472 }
1473 break;
1474
1475 case OS_GSP_LOGFILE:
1476 res = getenv("T3_LOGDIR");
1477 if (res == 0 or res[0] == '\0') {
1478 res = T3_LOG_FILE;
1479 }
1480 break;
1481
1482 default:
1483 // TODO: We could print a warning here to inform the
1484 // user that we're outdated.
1485 res = 0;
1486 }
1487
1488 if (res != 0) {
1489 // Only use the detected path if it exists and is a
1490 // directory.
1491 struct stat inf;
1492 int statRet = stat(res, &inf);
1493 if (statRet == 0 and (inf.st_mode & S_IFMT) == S_IFDIR) {
1494 strncpy(buf, res, buflen - 1);
1495 return;
1496 }
1497 }
1498 // Indicate failure.
1499 buf[0] = '\0';
1500 }
1501
1502
1503 #if 0
1504 /* Generate a filename for a character-set mapping file.
1505 *
1506 * Follow DOS convention: start with the current local charset
1507 * identifier, then the internal ID, and the suffix ".tcp". No path
1508 * prefix, which means look in current directory. This is what we
1509 * want, because mapping files are supposed to be distributed with a
1510 * game, not with the interpreter.
1511 */
1512 void
1513 os_gen_charmap_filename( char* filename, char* internal_id, char* /*argv0*/ )
1514 {
1515 char mapname[32];
1516
1517 os_get_charmap(mapname, OS_CHARMAP_DISPLAY);
1518
1519 // Theoretically, we can get mapname so long that with 4-letter
1520 // internal id and 4-letter extension '.tcp' it will be longer
1521 // than OSFNMAX. Highly unlikely, but...
1522 size_t len = strlen(mapname);
1523 if (len > OSFNMAX - 9) len = OSFNMAX - 9;
1524
1525 memcpy(filename, mapname, len);
1526 strcat(filename, internal_id);
1527 strcat(filename, ".tcp");
1528 }
1529
1530 #endif
1531
1532 /* Receive notification that a character mapping file has been loaded.
1533 */
1534 void
1535 os_advise_load_charmap( char* /*id*/, char* /*ldesc*/, char* /*sysinfo*/ )
1536 {
1537 }
1538
1539
1540 /* T3 post-load UI initialization. This is a hook provided by the T3
1541 * VM to allow the UI layer to do any extra initialization that depends
1542 * upon the contents of the loaded game file. We don't currently need
1543 * any extra initialization here.
1544 */
1545 #ifdef RUNTIME
1546 void
1547 os_init_ui_after_load( class CVmBifTable*, class CVmMetaTable* )
1548 {
1549 // No extra initialization required.
1550 }
1551 #endif
1552
1553
1554 /* Get the full filename (including directory path) to the executable
1555 * file, given the argv[0] parameter passed into the main program.
1556 *
1557 * On Unix, you can't tell what the executable's name is by just looking
1558 * at argv, so we always indicate failure. No big deal though; this
1559 * information is only used when the interpreter's executable is bundled
1560 * with a game, and we don't support this at all.
1561 */
1562 int
1563 os_get_exe_filename( char*, size_t, const char* )
1564 {
1565 return false;
1566 }
1567
1568
1569 #if 0
1570 /* Generate the name of the character set mapping table for Unicode
1571 * characters to and from the given local character set.
1572 */
1573 void
1574 os_get_charmap( char* mapname, int charmap_id )
1575 {
1576 const char* charset = 0; // Character set name.
1577
1578 #ifdef RUNTIME
1579 // If there was a command line option, it takes precedence.
1580 // User knows better, so do not try to modify his setting.
1581 if (globalApp->options.characterSet[0] != '\0') {
1582 // One charset for all.
1583 strncpy(mapname, globalApp->options.characterSet, 32);
1584 return;
1585 }
1586 #endif
1587
1588 // There is absolutely no robust way to determine the local
1589 // character set. Roughly speaking, we have three options:
1590 //
1591 // Use nl_langinfo() function. Not always available.
1592 //
1593 // Use setlocale(LC_CTYPE, NULL). This only works if user set
1594 // locale which is actually installed on the machine, or else
1595 // it will return NULL. But we don't need locale, we just need
1596 // to know what the user wants.
1597 //
1598 // Manually look up environment variables LC_ALL, LC_CTYPE and
1599 // LANG.
1600 //
1601 // However, not a single one will provide us with a reliable
1602 // name of local character set. There is no standard way to
1603 // name charsets. For a single set we can get almost anything:
1604 // Windows-1251, Win-1251, CP1251, CP-1251, ru_RU.CP1251,
1605 // ru_RU.CP-1251, ru_RU.CP_1251... And the only way is to
1606 // maintain a database of aliases.
1607
1608 #if HAVE_LANGINFO_CODESET
1609 charset = nl_langinfo(CODESET);
1610 #else
1611 charset = getenv("LC_CTYPE");
1612 if (charset == 0 or charset[0] == '\0') {
1613 charset = getenv("LC_ALL");
1614 if (charset == 0 or charset[0] == '\0') {
1615 charset = getenv("LANG");
1616 }
1617 }
1618 #endif
1619
1620 if (charset == 0) {
1621 strcpy(mapname, "us-ascii");
1622 } else {
1623 strcpy(mapname, get_charset_alias(charset));
1624 }
1625 return;
1626 }
1627
1628 #endif
1629
1630 /* Translate a character from the HTML 4 Unicode character set to the
1631 * current character set used for display.
1632 *
1633 * Note that this function is used only by Tads 2. Tads 3 does mappings
1634 * automatically.
1635 *
1636 * We omit this implementation when not compiling the interpreter (in
1637 * which case os_xlat_html4 will have been defined as an empty macro in
1638 * osfrobtads.h). We do this because we don't want to introduce any
1639 * TADS 3 dependencies upon the TADS 2 compiler, which should compile
1640 * regardless of whether the TADS 3 sources are available or not.
1641 */
1642 #ifndef os_xlat_html4
1643 void
1644 os_xlat_html4( unsigned int html4_char, char* result, size_t result_buf_len )
1645 {
1646 // HTML 4 characters are Unicode. Tads 3 provides just the
1647 // right mapper: Unicode to ASCII. We make it static in order
1648 // not to create a mapper on each call and save CPU cycles.
1649 static CCharmapToLocalASCII mapper;
1650 result[mapper.map_char(html4_char, result, result_buf_len)] = '\0';
1651 }
1652 #endif
1653
1654 #if 0
1655 /* =====================================================================
1656 *
1657 * The functions defined below are not needed by the interpreter, or
1658 * have a curses-specific implementation and are therefore only used
1659 * when building the compiler (the compiler doesn't use curses, just
1660 * plain stdio).
1661 */
1662 #ifndef RUNTIME
1663
1664 /* Wait for a character to become available from the keyboard.
1665 */
1666 void
1667 os_waitc( void )
1668 {
1669 getchar();
1670 }
1671
1672
1673 /* Read a character from the keyboard.
1674 */
1675 int
1676 os_getc( void )
1677 {
1678 return getchar();
1679 }
1680
1681
1682 /* Read a character from the keyboard and return the low-level,
1683 * untranslated key code whenever possible.
1684 */
1685 int
1686 os_getc_raw( void )
1687 {
1688 return getchar();
1689 }
1690
1691
1692 /* Check for user break.
1693 *
1694 * We only provide a dummy here; we might do something more useful in
1695 * the future though.
1696 */
1697 int
1698 os_break( void )
1699 {
1700 return false;
1701 }
1702
1703
1704 /* Yield CPU.
1705 *
1706 * We don't need this. It's only useful for Windows 3.x and maybe pre-X Mac OS
1707 * and other systems with brain damaged multitasking.
1708 */
1709 int
1710 os_yield( void )
1711 {
1712 return false;
1713 }
1714
1715
1716 /* Sleep for a while.
1717 *
1718 * The compiler doesn't need this.
1719 */
1720 void
1721 os_sleep_ms( long )
1722 {
1723 }
1724
1725 #endif /* ! RUNTIME */
1726 #endif