Source:NetHack 3.6.4/src/files.c

From NetHackWiki
Jump to navigation Jump to search

Below is the full text to files.c from the source code of NetHack 3.6.4. To link to a particular line, write [[Source:NetHack 3.6.4/src/files.c#line12]], for example.

The NetHack General Public License applies to screenshots, source code and other content from NetHack.

This content was modified from the original NetHack source code distribution (by splitting up NetHack content between wiki pages, and possibly further editing). See the page history for a list of who changed it, and on what dates.

1. /* NetHack 3.6	files.c	$NHDT-Date: 1576626110 2019/12/17 23:41:50 $  $NHDT-Branch: NetHack-3.6 $:$NHDT-Revision: 1.276 $ */
2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3. /*-Copyright (c) Derek S. Ray, 2015. */
4. /* NetHack may be freely redistributed.  See license for details. */
5. 
6. #define NEED_VARARGS
7. 
8. #include "hack.h"
9. #include "dlb.h"
10. 
11. #ifdef TTY_GRAPHICS
12. #include "wintty.h" /* more() */
13. #endif
14. 
15. #if (!defined(MAC) && !defined(O_WRONLY) && !defined(AZTEC_C)) \
16.     || defined(USE_FCNTL)
17. #include <fcntl.h>
18. #endif
19. 
20. #include <errno.h>
21. #ifdef _MSC_VER /* MSC 6.0 defines errno quite differently */
22. #if (_MSC_VER >= 600)
23. #define SKIP_ERRNO
24. #endif
25. #else
26. #ifdef NHSTDC
27. #define SKIP_ERRNO
28. #endif
29. #endif
30. #ifndef SKIP_ERRNO
31. #ifdef _DCC
32. const
33. #endif
34.     extern int errno;
35. #endif
36. 
37. #ifdef ZLIB_COMP /* RLC 09 Mar 1999: Support internal ZLIB */
38. #include "zlib.h"
39. #ifndef COMPRESS_EXTENSION
40. #define COMPRESS_EXTENSION ".gz"
41. #endif
42. #endif
43. 
44. #if defined(UNIX) && defined(QT_GRAPHICS)
45. #include <sys/types.h>
46. #include <dirent.h>
47. #include <stdlib.h>
48. #endif
49. 
50. #if defined(UNIX) || defined(VMS) || !defined(NO_SIGNAL)
51. #include <signal.h>
52. #endif
53. 
54. #if defined(MSDOS) || defined(OS2) || defined(TOS) || defined(WIN32)
55. #ifndef __DJGPP__
56. #include <sys\stat.h>
57. #else
58. #include <sys/stat.h>
59. #endif
60. #endif
61. #ifndef O_BINARY /* used for micros, no-op for others */
62. #define O_BINARY 0
63. #endif
64. 
65. #ifdef PREFIXES_IN_USE
66. #define FQN_NUMBUF 4
67. static char fqn_filename_buffer[FQN_NUMBUF][FQN_MAX_FILENAME];
68. #endif
69. 
70. #if !defined(MFLOPPY) && !defined(VMS) && !defined(WIN32)
71. char bones[] = "bonesnn.xxx";
72. char lock[PL_NSIZ + 14] = "1lock"; /* long enough for uid+name+.99 */
73. #else
74. #if defined(MFLOPPY)
75. char bones[FILENAME]; /* pathname of bones files */
76. char lock[FILENAME];  /* pathname of level files */
77. #endif
78. #if defined(VMS)
79. char bones[] = "bonesnn.xxx;1";
80. char lock[PL_NSIZ + 17] = "1lock"; /* long enough for _uid+name+.99;1 */
81. #endif
82. #if defined(WIN32)
83. char bones[] = "bonesnn.xxx";
84. char lock[PL_NSIZ + 25]; /* long enough for username+-+name+.99 */
85. #endif
86. #endif
87. 
88. #if defined(UNIX) || defined(__BEOS__)
89. #define SAVESIZE (PL_NSIZ + 13) /* save/99999player.e */
90. #else
91. #ifdef VMS
92. #define SAVESIZE (PL_NSIZ + 22) /* [.save]<uid>player.e;1 */
93. #else
94. #if defined(WIN32)
95. #define SAVESIZE (PL_NSIZ + 40) /* username-player.NetHack-saved-game */
96. #else
97. #define SAVESIZE FILENAME /* from macconf.h or pcconf.h */
98. #endif
99. #endif
100. #endif
101. 
102. #if !defined(SAVE_EXTENSION)
103. #ifdef MICRO
104. #define SAVE_EXTENSION ".sav"
105. #endif
106. #ifdef WIN32
107. #define SAVE_EXTENSION ".NetHack-saved-game"
108. #endif
109. #endif
110. 
111. char SAVEF[SAVESIZE]; /* holds relative path of save file from playground */
112. #ifdef MICRO
113. char SAVEP[SAVESIZE]; /* holds path of directory for save file */
114. #endif
115. 
116. #ifdef HOLD_LOCKFILE_OPEN
117. struct level_ftrack {
118.     int init;
119.     int fd;    /* file descriptor for level file     */
120.     int oflag; /* open flags                         */
121.     boolean nethack_thinks_it_is_open; /* Does NetHack think it's open? */
122. } lftrack;
123. #if defined(WIN32)
124. #include <share.h>
125. #endif
126. #endif /*HOLD_LOCKFILE_OPEN*/
127. 
128. #define WIZKIT_MAX 128
129. static char wizkit[WIZKIT_MAX];
130. STATIC_DCL FILE *NDECL(fopen_wizkit_file);
131. STATIC_DCL void FDECL(wizkit_addinv, (struct obj *));
132. 
133. #ifdef AMIGA
134. extern char PATH[]; /* see sys/amiga/amidos.c */
135. extern char bbs_id[];
136. static int lockptr;
137. #ifdef __SASC_60
138. #include <proto/dos.h>
139. #endif
140. 
141. #include <libraries/dos.h>
142. extern void FDECL(amii_set_text_font, (char *, int));
143. #endif
144. 
145. #if defined(WIN32) || defined(MSDOS)
146. static int lockptr;
147. #ifdef MSDOS
148. #define Delay(a) msleep(a)
149. #endif
150. #define Close close
151. #ifndef WIN_CE
152. #define DeleteFile unlink
153. #endif
154. #ifdef WIN32
155. /*from windmain.c */
156. extern char *FDECL(translate_path_variables, (const char *, char *));
157. #endif
158. #endif
159. 
160. #ifdef MAC
161. #undef unlink
162. #define unlink macunlink
163. #endif
164. 
165. #if (defined(macintosh) && (defined(__SC__) || defined(__MRC__))) \
166.     || defined(__MWERKS__)
167. #define PRAGMA_UNUSED
168. #endif
169. 
170. #ifdef USER_SOUNDS
171. extern char *sounddir;
172. #endif
173. 
174. extern int n_dgns; /* from dungeon.c */
175. 
176. #if defined(UNIX) && defined(QT_GRAPHICS)
177. #define SELECTSAVED
178. #endif
179. 
180. #ifdef SELECTSAVED
181. STATIC_PTR int FDECL(CFDECLSPEC strcmp_wrap, (const void *, const void *));
182. #endif
183. STATIC_DCL char *FDECL(set_bonesfile_name, (char *, d_level *));
184. STATIC_DCL char *NDECL(set_bonestemp_name);
185. #ifdef COMPRESS
186. STATIC_DCL void FDECL(redirect, (const char *, const char *, FILE *,
187.                                  BOOLEAN_P));
188. #endif
189. #if defined(COMPRESS) || defined(ZLIB_COMP)
190. STATIC_DCL void FDECL(docompress_file, (const char *, BOOLEAN_P));
191. #endif
192. #if defined(ZLIB_COMP)
193. STATIC_DCL boolean FDECL(make_compressed_name, (const char *, char *));
194. #endif
195. #ifndef USE_FCNTL
196. STATIC_DCL char *FDECL(make_lockname, (const char *, char *));
197. #endif
198. STATIC_DCL void FDECL(set_configfile_name, (const char *));
199. STATIC_DCL FILE *FDECL(fopen_config_file, (const char *, int));
200. STATIC_DCL int FDECL(get_uchars, (char *, uchar *, BOOLEAN_P,
201.                                   int, const char *));
202. boolean FDECL(proc_wizkit_line, (char *));
203. boolean FDECL(parse_config_line, (char *));
204. STATIC_DCL boolean FDECL(parse_conf_file, (FILE *, boolean (*proc)(char *)));
205. STATIC_DCL FILE *NDECL(fopen_sym_file);
206. boolean FDECL(proc_symset_line, (char *));
207. STATIC_DCL void FDECL(set_symhandling, (char *, int));
208. #ifdef NOCWD_ASSUMPTIONS
209. STATIC_DCL void FDECL(adjust_prefix, (char *, int));
210. #endif
211. STATIC_DCL boolean FDECL(config_error_nextline, (const char *));
212. STATIC_DCL void NDECL(free_config_sections);
213. STATIC_DCL char *FDECL(choose_random_part, (char *, CHAR_P));
214. STATIC_DCL boolean FDECL(is_config_section, (const char *));
215. STATIC_DCL boolean FDECL(handle_config_section, (char *));
216. #ifdef SELF_RECOVER
217. STATIC_DCL boolean FDECL(copy_bytes, (int, int));
218. #endif
219. #ifdef HOLD_LOCKFILE_OPEN
220. STATIC_DCL int FDECL(open_levelfile_exclusively, (const char *, int, int));
221. #endif
222. 
223. 
224. static char *config_section_chosen = (char *) 0;
225. static char *config_section_current = (char *) 0;
226. 
227. /*
228.  * fname_encode()
229.  *
230.  *   Args:
231.  *      legal       zero-terminated list of acceptable file name characters
232.  *      quotechar   lead-in character used to quote illegal characters as
233.  *                  hex digits
234.  *      s           string to encode
235.  *      callerbuf   buffer to house result
236.  *      bufsz       size of callerbuf
237.  *
238.  *   Notes:
239.  *      The hex digits 0-9 and A-F are always part of the legal set due to
240.  *      their use in the encoding scheme, even if not explicitly included in
241.  *      'legal'.
242.  *
243.  *   Sample:
244.  *      The following call:
245.  *  (void)fname_encode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
246.  *                     '%', "This is a % test!", buf, 512);
247.  *      results in this encoding:
248.  *          "This%20is%20a%20%25%20test%21"
249.  */
250. char *
251. fname_encode(legal, quotechar, s, callerbuf, bufsz)
252. const char *legal;
253. char quotechar;
254. char *s, *callerbuf;
255. int bufsz;
256. {
257.     char *sp, *op;
258.     int cnt = 0;
259.     static char hexdigits[] = "0123456789ABCDEF";
260. 
261.     sp = s;
262.     op = callerbuf;
263.     *op = '\0';
264. 
265.     while (*sp) {
266.         /* Do we have room for one more character or encoding? */
267.         if ((bufsz - cnt) <= 4)
268.             return callerbuf;
269. 
270.         if (*sp == quotechar) {
271.             (void) sprintf(op, "%c%02X", quotechar, *sp);
272.             op += 3;
273.             cnt += 3;
274.         } else if ((index(legal, *sp) != 0) || (index(hexdigits, *sp) != 0)) {
275.             *op++ = *sp;
276.             *op = '\0';
277.             cnt++;
278.         } else {
279.             (void) sprintf(op, "%c%02X", quotechar, *sp);
280.             op += 3;
281.             cnt += 3;
282.         }
283.         sp++;
284.     }
285.     return callerbuf;
286. }
287. 
288. /*
289.  * fname_decode()
290.  *
291.  *   Args:
292.  *      quotechar   lead-in character used to quote illegal characters as
293.  *                  hex digits
294.  *      s           string to decode
295.  *      callerbuf   buffer to house result
296.  *      bufsz       size of callerbuf
297.  */
298. char *
299. fname_decode(quotechar, s, callerbuf, bufsz)
300. char quotechar;
301. char *s, *callerbuf;
302. int bufsz;
303. {
304.     char *sp, *op;
305.     int k, calc, cnt = 0;
306.     static char hexdigits[] = "0123456789ABCDEF";
307. 
308.     sp = s;
309.     op = callerbuf;
310.     *op = '\0';
311.     calc = 0;
312. 
313.     while (*sp) {
314.         /* Do we have room for one more character? */
315.         if ((bufsz - cnt) <= 2)
316.             return callerbuf;
317.         if (*sp == quotechar) {
318.             sp++;
319.             for (k = 0; k < 16; ++k)
320.                 if (*sp == hexdigits[k])
321.                     break;
322.             if (k >= 16)
323.                 return callerbuf; /* impossible, so bail */
324.             calc = k << 4;
325.             sp++;
326.             for (k = 0; k < 16; ++k)
327.                 if (*sp == hexdigits[k])
328.                     break;
329.             if (k >= 16)
330.                 return callerbuf; /* impossible, so bail */
331.             calc += k;
332.             sp++;
333.             *op++ = calc;
334.             *op = '\0';
335.         } else {
336.             *op++ = *sp++;
337.             *op = '\0';
338.         }
339.         cnt++;
340.     }
341.     return callerbuf;
342. }
343. 
344. #ifdef PREFIXES_IN_USE
345. #define UNUSED_if_not_PREFIXES_IN_USE /*empty*/
346. #else
347. #define UNUSED_if_not_PREFIXES_IN_USE UNUSED
348. #endif
349. 
350. /*ARGSUSED*/
351. const char *
352. fqname(basenam, whichprefix, buffnum)
353. const char *basenam;
354. int whichprefix UNUSED_if_not_PREFIXES_IN_USE;
355. int buffnum UNUSED_if_not_PREFIXES_IN_USE;
356. {
357. #ifdef PREFIXES_IN_USE
358.     char *bufptr;
359. #endif
360. #ifdef WIN32
361.     char tmpbuf[BUFSZ];
362. #endif
363. 
364. #ifndef PREFIXES_IN_USE
365.     return basenam;
366. #else
367.     if (!basenam || whichprefix < 0 || whichprefix >= PREFIX_COUNT)
368.         return basenam;
369.     if (!fqn_prefix[whichprefix])
370.         return basenam;
371.     if (buffnum < 0 || buffnum >= FQN_NUMBUF) {
372.         impossible("Invalid fqn_filename_buffer specified: %d", buffnum);
373.         buffnum = 0;
374.     }
375.     bufptr = fqn_prefix[whichprefix];
376. #ifdef WIN32
377.     if (strchr(fqn_prefix[whichprefix], '%')
378.         || strchr(fqn_prefix[whichprefix], '~'))
379.         bufptr = translate_path_variables(fqn_prefix[whichprefix], tmpbuf);
380. #endif
381.     if (strlen(bufptr) + strlen(basenam) >= FQN_MAX_FILENAME) {
382.         impossible("fqname too long: %s + %s", bufptr, basenam);
383.         return basenam; /* XXX */
384.     }
385.     Strcpy(fqn_filename_buffer[buffnum], bufptr);
386.     return strcat(fqn_filename_buffer[buffnum], basenam);
387. #endif /* !PREFIXES_IN_USE */
388. }
389. 
390. int
391. validate_prefix_locations(reasonbuf)
392. char *reasonbuf; /* reasonbuf must be at least BUFSZ, supplied by caller */
393. {
394. #if defined(NOCWD_ASSUMPTIONS)
395.     FILE *fp;
396.     const char *filename;
397.     int prefcnt, failcount = 0;
398.     char panicbuf1[BUFSZ], panicbuf2[BUFSZ];
399.     const char *details;
400. #endif
401. 
402.     if (reasonbuf)
403.         reasonbuf[0] = '\0';
404. #if defined(NOCWD_ASSUMPTIONS)
405.     for (prefcnt = 1; prefcnt < PREFIX_COUNT; prefcnt++) {
406.         /* don't test writing to configdir or datadir; they're readonly */
407.         if (prefcnt == SYSCONFPREFIX || prefcnt == CONFIGPREFIX
408.             || prefcnt == DATAPREFIX)
409.             continue;
410.         filename = fqname("validate", prefcnt, 3);
411.         if ((fp = fopen(filename, "w"))) {
412.             fclose(fp);
413.             (void) unlink(filename);
414.         } else {
415.             if (reasonbuf) {
416.                 if (failcount)
417.                     Strcat(reasonbuf, ", ");
418.                 Strcat(reasonbuf, fqn_prefix_names[prefcnt]);
419.             }
420.             /* the paniclog entry gets the value of errno as well */
421.             Sprintf(panicbuf1, "Invalid %s", fqn_prefix_names[prefcnt]);
422. #if defined(NHSTDC) && !defined(NOTSTDC)
423.             if (!(details = strerror(errno)))
424. #endif
425.                 details = "";
426.             Sprintf(panicbuf2, "\"%s\", (%d) %s", fqn_prefix[prefcnt], errno,
427.                     details);
428.             paniclog(panicbuf1, panicbuf2);
429.             failcount++;
430.         }
431.     }
432.     if (failcount)
433.         return 0;
434.     else
435. #endif
436.         return 1;
437. }
438. 
439. /* fopen a file, with OS-dependent bells and whistles */
440. /* NOTE: a simpler version of this routine also exists in util/dlb_main.c */
441. FILE *
442. fopen_datafile(filename, mode, prefix)
443. const char *filename, *mode;
444. int prefix;
445. {
446.     FILE *fp;
447. 
448.     filename = fqname(filename, prefix, prefix == TROUBLEPREFIX ? 3 : 0);
449.     fp = fopen(filename, mode);
450.     return fp;
451. }
452. 
453. /* ----------  BEGIN LEVEL FILE HANDLING ----------- */
454. 
455. #ifdef MFLOPPY
456. /* Set names for bones[] and lock[] */
457. void
458. set_lock_and_bones()
459. {
460.     if (!ramdisk) {
461.         Strcpy(levels, permbones);
462.         Strcpy(bones, permbones);
463.     }
464.     append_slash(permbones);
465.     append_slash(levels);
466. #ifdef AMIGA
467.     strncat(levels, bbs_id, PATHLEN);
468. #endif
469.     append_slash(bones);
470.     Strcat(bones, "bonesnn.*");
471.     Strcpy(lock, levels);
472. #ifndef AMIGA
473.     Strcat(lock, alllevels);
474. #endif
475.     return;
476. }
477. #endif /* MFLOPPY */
478. 
479. /* Construct a file name for a level-type file, which is of the form
480.  * something.level (with any old level stripped off).
481.  * This assumes there is space on the end of 'file' to append
482.  * a two digit number.  This is true for 'level'
483.  * but be careful if you use it for other things -dgk
484.  */
485. void
486. set_levelfile_name(file, lev)
487. char *file;
488. int lev;
489. {
490.     char *tf;
491. 
492.     tf = rindex(file, '.');
493.     if (!tf)
494.         tf = eos(file);
495.     Sprintf(tf, ".%d", lev);
496. #ifdef VMS
497.     Strcat(tf, ";1");
498. #endif
499.     return;
500. }
501. 
502. int
503. create_levelfile(lev, errbuf)
504. int lev;
505. char errbuf[];
506. {
507.     int fd;
508.     const char *fq_lock;
509. 
510.     if (errbuf)
511.         *errbuf = '\0';
512.     set_levelfile_name(lock, lev);
513.     fq_lock = fqname(lock, LEVELPREFIX, 0);
514. 
515. #if defined(MICRO) || defined(WIN32)
516. /* Use O_TRUNC to force the file to be shortened if it already
517.  * exists and is currently longer.
518.  */
519. #ifdef HOLD_LOCKFILE_OPEN
520.     if (lev == 0)
521.         fd = open_levelfile_exclusively(
522.             fq_lock, lev, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY);
523.     else
524. #endif
525.         fd = open(fq_lock, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, FCMASK);
526. #else
527. #ifdef MAC
528.     fd = maccreat(fq_lock, LEVL_TYPE);
529. #else
530.     fd = creat(fq_lock, FCMASK);
531. #endif
532. #endif /* MICRO || WIN32 */
533. 
534.     if (fd >= 0)
535.         level_info[lev].flags |= LFILE_EXISTS;
536.     else if (errbuf) /* failure explanation */
537.         Sprintf(errbuf, "Cannot create file \"%s\" for level %d (errno %d).",
538.                 lock, lev, errno);
539. 
540.     return fd;
541. }
542. 
543. int
544. open_levelfile(lev, errbuf)
545. int lev;
546. char errbuf[];
547. {
548.     int fd;
549.     const char *fq_lock;
550. 
551.     if (errbuf)
552.         *errbuf = '\0';
553.     set_levelfile_name(lock, lev);
554.     fq_lock = fqname(lock, LEVELPREFIX, 0);
555. #ifdef MFLOPPY
556.     /* If not currently accessible, swap it in. */
557.     if (level_info[lev].where != ACTIVE)
558.         swapin_file(lev);
559. #endif
560. #ifdef MAC
561.     fd = macopen(fq_lock, O_RDONLY | O_BINARY, LEVL_TYPE);
562. #else
563. #ifdef HOLD_LOCKFILE_OPEN
564.     if (lev == 0)
565.         fd = open_levelfile_exclusively(fq_lock, lev, O_RDONLY | O_BINARY);
566.     else
567. #endif
568.         fd = open(fq_lock, O_RDONLY | O_BINARY, 0);
569. #endif
570. 
571.     /* for failure, return an explanation that our caller can use;
572.        settle for `lock' instead of `fq_lock' because the latter
573.        might end up being too big for nethack's BUFSZ */
574.     if (fd < 0 && errbuf)
575.         Sprintf(errbuf, "Cannot open file \"%s\" for level %d (errno %d).",
576.                 lock, lev, errno);
577. 
578.     return fd;
579. }
580. 
581. void
582. delete_levelfile(lev)
583. int lev;
584. {
585.     /*
586.      * Level 0 might be created by port specific code that doesn't
587.      * call create_levfile(), so always assume that it exists.
588.      */
589.     if (lev == 0 || (level_info[lev].flags & LFILE_EXISTS)) {
590.         set_levelfile_name(lock, lev);
591. #ifdef HOLD_LOCKFILE_OPEN
592.         if (lev == 0)
593.             really_close();
594. #endif
595.         (void) unlink(fqname(lock, LEVELPREFIX, 0));
596.         level_info[lev].flags &= ~LFILE_EXISTS;
597.     }
598. }
599. 
600. void
601. clearlocks()
602. {
603. #ifdef HANGUPHANDLING
604.     if (program_state.preserve_locks)
605.         return;
606. #endif
607. #if !defined(PC_LOCKING) && defined(MFLOPPY) && !defined(AMIGA)
608.     eraseall(levels, alllevels);
609.     if (ramdisk)
610.         eraseall(permbones, alllevels);
611. #else
612.     {
613.         register int x;
614. 
615. #ifndef NO_SIGNAL
616.         (void) signal(SIGINT, SIG_IGN);
617. #endif
618. #if defined(UNIX) || defined(VMS)
619.         sethanguphandler((void FDECL((*), (int) )) SIG_IGN);
620. #endif
621.         /* can't access maxledgerno() before dungeons are created -dlc */
622.         for (x = (n_dgns ? maxledgerno() : 0); x >= 0; x--)
623.             delete_levelfile(x); /* not all levels need be present */
624.     }
625. #endif /* ?PC_LOCKING,&c */
626. }
627. 
628. #if defined(SELECTSAVED)
629. /* qsort comparison routine */
630. STATIC_OVL int CFDECLSPEC
631. strcmp_wrap(p, q)
632. const void *p;
633. const void *q;
634. {
635. #if defined(UNIX) && defined(QT_GRAPHICS)
636.     return strncasecmp(*(char **) p, *(char **) q, 16);
637. #else
638.     return strncmpi(*(char **) p, *(char **) q, 16);
639. #endif
640. }
641. #endif
642. 
643. #ifdef HOLD_LOCKFILE_OPEN
644. STATIC_OVL int
645. open_levelfile_exclusively(name, lev, oflag)
646. const char *name;
647. int lev, oflag;
648. {
649.     int reslt, fd;
650. 
651.     if (!lftrack.init) {
652.         lftrack.init = 1;
653.         lftrack.fd = -1;
654.     }
655.     if (lftrack.fd >= 0) {
656.         /* check for compatible access */
657.         if (lftrack.oflag == oflag) {
658.             fd = lftrack.fd;
659.             reslt = lseek(fd, 0L, SEEK_SET);
660.             if (reslt == -1L)
661.                 panic("open_levelfile_exclusively: lseek failed %d", errno);
662.             lftrack.nethack_thinks_it_is_open = TRUE;
663.         } else {
664.             really_close();
665.             fd = sopen(name, oflag, SH_DENYRW, FCMASK);
666.             lftrack.fd = fd;
667.             lftrack.oflag = oflag;
668.             lftrack.nethack_thinks_it_is_open = TRUE;
669.         }
670.     } else {
671.         fd = sopen(name, oflag, SH_DENYRW, FCMASK);
672.         lftrack.fd = fd;
673.         lftrack.oflag = oflag;
674.         if (fd >= 0)
675.             lftrack.nethack_thinks_it_is_open = TRUE;
676.     }
677.     return fd;
678. }
679. 
680. void
681. really_close()
682. {
683.     int fd;
684. 
685.     if (lftrack.init) {
686.         fd = lftrack.fd;
687. 
688.         lftrack.nethack_thinks_it_is_open = FALSE;
689.         lftrack.fd = -1;
690.         lftrack.oflag = 0;
691.         if (fd != -1)
692.             (void) close(fd);
693.     }
694.     return;
695. }
696. 
697. int
698. nhclose(fd)
699. int fd;
700. {
701.     if (lftrack.fd == fd) {
702.         really_close(); /* close it, but reopen it to hold it */
703.         fd = open_levelfile(0, (char *) 0);
704.         lftrack.nethack_thinks_it_is_open = FALSE;
705.         return 0;
706.     }
707.     return close(fd);
708. }
709. #else /* !HOLD_LOCKFILE_OPEN */
710. 
711. int
712. nhclose(fd)
713. int fd;
714. {
715.     return close(fd);
716. }
717. #endif /* ?HOLD_LOCKFILE_OPEN */
718. 
719. /* ----------  END LEVEL FILE HANDLING ----------- */
720. 
721. /* ----------  BEGIN BONES FILE HANDLING ----------- */
722. 
723. /* set up "file" to be file name for retrieving bones, and return a
724.  * bonesid to be read/written in the bones file.
725.  */
726. STATIC_OVL char *
727. set_bonesfile_name(file, lev)
728. char *file;
729. d_level *lev;
730. {
731.     s_level *sptr;
732.     char *dptr;
733. 
734.     /*
735.      * "bonD0.nn"   = bones for level nn in the main dungeon;
736.      * "bonM0.T"    = bones for Minetown;
737.      * "bonQBar.n"  = bones for level n in the Barbarian quest;
738.      * "bon3D0.nn"  = \
739.      * "bon3M0.T"   =  > same as above, but for bones pool #3.
740.      * "bon3QBar.n" = /
741.      *
742.      * Return value for content validation skips "bon" and the
743.      * pool number (if present), making it feasible for the admin
744.      * to manually move a bones file from one pool to another by
745.      * renaming it.
746.      */
747.     Strcpy(file, "bon");
748. #ifdef SYSCF
749.     if (sysopt.bones_pools > 1) {
750.         unsigned poolnum = min((unsigned) sysopt.bones_pools, 10);
751. 
752.         poolnum = (unsigned) ubirthday % poolnum; /* 0..9 */
753.         Sprintf(eos(file), "%u", poolnum);
754.     }
755. #endif
756.     dptr = eos(file); /* this used to be after the following Sprintf()
757.                          and the return value was (dptr - 2) */
758.     /* when this naming scheme was adopted, 'filecode' was one letter;
759.        3.3.0 turned it into a three letter string (via roles[] in role.c);
760.        from that version through 3.6.0, 'dptr' pointed past the filecode
761.        and the return value of (dptr - 2)  was wrong for bones produced
762.        in the quest branch, skipping the boneid character 'Q' and the
763.        first letter of the role's filecode; bones loading still worked
764.        because the bonesid used for validation had the same error */
765.     Sprintf(dptr, "%c%s", dungeons[lev->dnum].boneid,
766.             In_quest(lev) ? urole.filecode : "0");
767.     if ((sptr = Is_special(lev)) != 0)
768.         Sprintf(eos(dptr), ".%c", sptr->boneid);
769.     else
770.         Sprintf(eos(dptr), ".%d", lev->dlevel);
771. #ifdef VMS
772.     Strcat(dptr, ";1");
773. #endif
774.     return dptr;
775. }
776. 
777. /* set up temporary file name for writing bones, to avoid another game's
778.  * trying to read from an uncompleted bones file.  we want an uncontentious
779.  * name, so use one in the namespace reserved for this game's level files.
780.  * (we are not reading or writing level files while writing bones files, so
781.  * the same array may be used instead of copying.)
782.  */
783. STATIC_OVL char *
784. set_bonestemp_name()
785. {
786.     char *tf;
787. 
788.     tf = rindex(lock, '.');
789.     if (!tf)
790.         tf = eos(lock);
791.     Sprintf(tf, ".bn");
792. #ifdef VMS
793.     Strcat(tf, ";1");
794. #endif
795.     return lock;
796. }
797. 
798. int
799. create_bonesfile(lev, bonesid, errbuf)
800. d_level *lev;
801. char **bonesid;
802. char errbuf[];
803. {
804.     const char *file;
805.     int fd;
806. 
807.     if (errbuf)
808.         *errbuf = '\0';
809.     *bonesid = set_bonesfile_name(bones, lev);
810.     file = set_bonestemp_name();
811.     file = fqname(file, BONESPREFIX, 0);
812. 
813. #if defined(MICRO) || defined(WIN32)
814.     /* Use O_TRUNC to force the file to be shortened if it already
815.      * exists and is currently longer.
816.      */
817.     fd = open(file, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, FCMASK);
818. #else
819. #ifdef MAC
820.     fd = maccreat(file, BONE_TYPE);
821. #else
822.     fd = creat(file, FCMASK);
823. #endif
824. #endif
825.     if (fd < 0 && errbuf) /* failure explanation */
826.         Sprintf(errbuf, "Cannot create bones \"%s\", id %s (errno %d).", lock,
827.                 *bonesid, errno);
828. 
829. #if defined(VMS) && !defined(SECURE)
830.     /*
831.        Re-protect bones file with world:read+write+execute+delete access.
832.        umask() doesn't seem very reliable; also, vaxcrtl won't let us set
833.        delete access without write access, which is what's really wanted.
834.        Can't simply create it with the desired protection because creat
835.        ANDs the mask with the user's default protection, which usually
836.        denies some or all access to world.
837.      */
838.     (void) chmod(file, FCMASK | 007); /* allow other users full access */
839. #endif /* VMS && !SECURE */
840. 
841.     return fd;
842. }
843. 
844. #ifdef MFLOPPY
845. /* remove partial bonesfile in process of creation */
846. void
847. cancel_bonesfile()
848. {
849.     const char *tempname;
850. 
851.     tempname = set_bonestemp_name();
852.     tempname = fqname(tempname, BONESPREFIX, 0);
853.     (void) unlink(tempname);
854. }
855. #endif /* MFLOPPY */
856. 
857. /* move completed bones file to proper name */
858. void
859. commit_bonesfile(lev)
860. d_level *lev;
861. {
862.     const char *fq_bones, *tempname;
863.     int ret;
864. 
865.     (void) set_bonesfile_name(bones, lev);
866.     fq_bones = fqname(bones, BONESPREFIX, 0);
867.     tempname = set_bonestemp_name();
868.     tempname = fqname(tempname, BONESPREFIX, 1);
869. 
870. #if (defined(SYSV) && !defined(SVR4)) || defined(GENIX)
871.     /* old SYSVs don't have rename.  Some SVR3's may, but since they
872.      * also have link/unlink, it doesn't matter. :-)
873.      */
874.     (void) unlink(fq_bones);
875.     ret = link(tempname, fq_bones);
876.     ret += unlink(tempname);
877. #else
878.     ret = rename(tempname, fq_bones);
879. #endif
880.     if (wizard && ret != 0)
881.         pline("couldn't rename %s to %s.", tempname, fq_bones);
882. }
883. 
884. int
885. open_bonesfile(lev, bonesid)
886. d_level *lev;
887. char **bonesid;
888. {
889.     const char *fq_bones;
890.     int fd;
891. 
892.     *bonesid = set_bonesfile_name(bones, lev);
893.     fq_bones = fqname(bones, BONESPREFIX, 0);
894.     nh_uncompress(fq_bones); /* no effect if nonexistent */
895. #ifdef MAC
896.     fd = macopen(fq_bones, O_RDONLY | O_BINARY, BONE_TYPE);
897. #else
898.     fd = open(fq_bones, O_RDONLY | O_BINARY, 0);
899. #endif
900.     return fd;
901. }
902. 
903. int
904. delete_bonesfile(lev)
905. d_level *lev;
906. {
907.     (void) set_bonesfile_name(bones, lev);
908.     return !(unlink(fqname(bones, BONESPREFIX, 0)) < 0);
909. }
910. 
911. /* assume we're compressing the recently read or created bonesfile, so the
912.  * file name is already set properly */
913. void
914. compress_bonesfile()
915. {
916.     nh_compress(fqname(bones, BONESPREFIX, 0));
917. }
918. 
919. /* ----------  END BONES FILE HANDLING ----------- */
920. 
921. /* ----------  BEGIN SAVE FILE HANDLING ----------- */
922. 
923. /* set savefile name in OS-dependent manner from pre-existing plname,
924.  * avoiding troublesome characters */
925. void
926. set_savefile_name(regularize_it)
927. boolean regularize_it;
928. {
929. #ifdef VMS
930.     Sprintf(SAVEF, "[.save]%d%s", getuid(), plname);
931.     if (regularize_it)
932.         regularize(SAVEF + 7);
933.     Strcat(SAVEF, ";1");
934. #else
935. #if defined(MICRO)
936.     Strcpy(SAVEF, SAVEP);
937. #ifdef AMIGA
938.     strncat(SAVEF, bbs_id, PATHLEN);
939. #endif
940.     {
941.         int i = strlen(SAVEP);
942. #ifdef AMIGA
943.         /* plname has to share space with SAVEP and ".sav" */
944.         (void) strncat(SAVEF, plname, FILENAME - i - 4);
945. #else
946.         (void) strncat(SAVEF, plname, 8);
947. #endif
948.         if (regularize_it)
949.             regularize(SAVEF + i);
950.     }
951.     Strcat(SAVEF, SAVE_EXTENSION);
952. #else
953. #if defined(WIN32)
954.     {
955.         static const char okchars[] =
956.             "*ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-.";
957.         const char *legal = okchars;
958.         char fnamebuf[BUFSZ], encodedfnamebuf[BUFSZ];
959. 
960.         /* Obtain the name of the logged on user and incorporate
961.          * it into the name. */
962.         Sprintf(fnamebuf, "%s", plname);
963.         if (regularize_it)
964.             ++legal; /* skip '*' wildcard character */
965.         (void) fname_encode(legal, '%', fnamebuf, encodedfnamebuf, BUFSZ);
966.         Sprintf(SAVEF, "%s%s", encodedfnamebuf, SAVE_EXTENSION);
967.     }
968. #else  /* not VMS or MICRO or WIN32 */
969.     Sprintf(SAVEF, "save/%d%s", (int) getuid(), plname);
970.     if (regularize_it)
971.         regularize(SAVEF + 5); /* avoid . or / in name */
972. #endif /* WIN32 */
973. #endif /* MICRO */
974. #endif /* VMS   */
975. }
976. 
977. #ifdef INSURANCE
978. void
979. save_savefile_name(fd)
980. int fd;
981. {
982.     (void) write(fd, (genericptr_t) SAVEF, sizeof(SAVEF));
983. }
984. #endif
985. 
986. #ifndef MICRO
987. /* change pre-existing savefile name to indicate an error savefile */
988. void
989. set_error_savefile()
990. {
991. #ifdef VMS
992.     {
993.         char *semi_colon = rindex(SAVEF, ';');
994. 
995.         if (semi_colon)
996.             *semi_colon = '\0';
997.     }
998.     Strcat(SAVEF, ".e;1");
999. #else
1000. #ifdef MAC
1001.     Strcat(SAVEF, "-e");
1002. #else
1003.     Strcat(SAVEF, ".e");
1004. #endif
1005. #endif
1006. }
1007. #endif
1008. 
1009. /* create save file, overwriting one if it already exists */
1010. int
1011. create_savefile()
1012. {
1013.     const char *fq_save;
1014.     int fd;
1015. 
1016.     fq_save = fqname(SAVEF, SAVEPREFIX, 0);
1017. #if defined(MICRO) || defined(WIN32)
1018.     fd = open(fq_save, O_WRONLY | O_BINARY | O_CREAT | O_TRUNC, FCMASK);
1019. #else
1020. #ifdef MAC
1021.     fd = maccreat(fq_save, SAVE_TYPE);
1022. #else
1023.     fd = creat(fq_save, FCMASK);
1024. #endif
1025. #if defined(VMS) && !defined(SECURE)
1026.     /*
1027.        Make sure the save file is owned by the current process.  That's
1028.        the default for non-privileged users, but for priv'd users the
1029.        file will be owned by the directory's owner instead of the user.
1030.     */
1031. #undef getuid
1032.     (void) chown(fq_save, getuid(), getgid());
1033. #define getuid() vms_getuid()
1034. #endif /* VMS && !SECURE */
1035. #endif /* MICRO */
1036. 
1037.     return fd;
1038. }
1039. 
1040. /* open savefile for reading */
1041. int
1042. open_savefile()
1043. {
1044.     const char *fq_save;
1045.     int fd;
1046. 
1047.     fq_save = fqname(SAVEF, SAVEPREFIX, 0);
1048. #ifdef MAC
1049.     fd = macopen(fq_save, O_RDONLY | O_BINARY, SAVE_TYPE);
1050. #else
1051.     fd = open(fq_save, O_RDONLY | O_BINARY, 0);
1052. #endif
1053.     return fd;
1054. }
1055. 
1056. /* delete savefile */
1057. int
1058. delete_savefile()
1059. {
1060.     (void) unlink(fqname(SAVEF, SAVEPREFIX, 0));
1061.     return 0; /* for restore_saved_game() (ex-xxxmain.c) test */
1062. }
1063. 
1064. /* try to open up a save file and prepare to restore it */
1065. int
1066. restore_saved_game()
1067. {
1068.     const char *fq_save;
1069.     int fd;
1070. 
1071.     reset_restpref();
1072.     set_savefile_name(TRUE);
1073. #ifdef MFLOPPY
1074.     if (!saveDiskPrompt(1))
1075.         return -1;
1076. #endif /* MFLOPPY */
1077.     fq_save = fqname(SAVEF, SAVEPREFIX, 0);
1078. 
1079.     nh_uncompress(fq_save);
1080.     if ((fd = open_savefile()) < 0)
1081.         return fd;
1082. 
1083.     if (validate(fd, fq_save) != 0) {
1084.         (void) nhclose(fd), fd = -1;
1085.         (void) delete_savefile();
1086.     }
1087.     return fd;
1088. }
1089. 
1090. #if defined(SELECTSAVED)
1091. char *
1092. plname_from_file(filename)
1093. const char *filename;
1094. {
1095.     int fd;
1096.     char *result = 0;
1097. 
1098.     Strcpy(SAVEF, filename);
1099. #ifdef COMPRESS_EXTENSION
1100.     SAVEF[strlen(SAVEF) - strlen(COMPRESS_EXTENSION)] = '\0';
1101. #endif
1102.     nh_uncompress(SAVEF);
1103.     if ((fd = open_savefile()) >= 0) {
1104.         if (validate(fd, filename) == 0) {
1105.             char tplname[PL_NSIZ];
1106.             get_plname_from_file(fd, tplname);
1107.             result = dupstr(tplname);
1108.         }
1109.         (void) nhclose(fd);
1110.     }
1111.     nh_compress(SAVEF);
1112. 
1113.     return result;
1114. #if 0
1115. /* --------- obsolete - used to be ifndef STORE_PLNAME_IN_FILE ----*/
1116. #if defined(UNIX) && defined(QT_GRAPHICS)
1117.     /* Name not stored in save file, so we have to extract it from
1118.        the filename, which loses information
1119.        (eg. "/", "_", and "." characters are lost. */
1120.     int k;
1121.     int uid;
1122.     char name[64]; /* more than PL_NSIZ */
1123. #ifdef COMPRESS_EXTENSION
1124. #define EXTSTR COMPRESS_EXTENSION
1125. #else
1126. #define EXTSTR ""
1127. #endif
1128. 
1129.     if ( sscanf( filename, "%*[^/]/%d%63[^.]" EXTSTR, &uid, name ) == 2 ) {
1130. #undef EXTSTR
1131.         /* "_" most likely means " ", which certainly looks nicer */
1132.         for (k=0; name[k]; k++)
1133.             if ( name[k] == '_' )
1134.                 name[k] = ' ';
1135.         return dupstr(name);
1136.     } else
1137. #endif /* UNIX && QT_GRAPHICS */
1138.     {
1139.         return 0;
1140.     }
1141. /* --------- end of obsolete code ----*/
1142. #endif /* 0 - WAS STORE_PLNAME_IN_FILE*/
1143. }
1144. #endif /* defined(SELECTSAVED) */
1145. 
1146. char **
1147. get_saved_games()
1148. {
1149. #if defined(SELECTSAVED)
1150.     int n, j = 0;
1151.     char **result = 0;
1152. #ifdef WIN32
1153.     {
1154.         char *foundfile;
1155.         const char *fq_save;
1156.         const char *fq_new_save;
1157.         const char *fq_old_save;
1158.         char **files = 0;
1159.         int i;
1160. 
1161.         Strcpy(plname, "*");
1162.         set_savefile_name(FALSE);
1163. #if defined(ZLIB_COMP)
1164.         Strcat(SAVEF, COMPRESS_EXTENSION);
1165. #endif
1166.         fq_save = fqname(SAVEF, SAVEPREFIX, 0);
1167. 
1168.         n = 0;
1169.         foundfile = foundfile_buffer();
1170.         if (findfirst((char *) fq_save)) {
1171.             do {
1172.                 ++n;
1173.             } while (findnext());
1174.         }
1175. 
1176.         if (n > 0) {
1177.             files = (char **) alloc((n + 1) * sizeof(char *)); /* at most */
1178.             (void) memset((genericptr_t) files, 0, (n + 1) * sizeof(char *));
1179.             if (findfirst((char *) fq_save)) {
1180.                 i = 0;
1181.                 do {
1182.                     files[i++] = strdup(foundfile);
1183.                 } while (findnext());
1184.             }
1185.         }
1186. 
1187.         if (n > 0) {
1188.             result = (char **) alloc((n + 1) * sizeof(char *)); /* at most */
1189.             (void) memset((genericptr_t) result, 0, (n + 1) * sizeof(char *));
1190.             for(i = 0; i < n; i++) {
1191.                 char *r;
1192.                 r = plname_from_file(files[i]);
1193. 
1194.                 if (r) {
1195. 
1196.                     /* rename file if it is not named as expected */
1197.                     Strcpy(plname, r);
1198.                     set_savefile_name(FALSE);
1199.                     fq_new_save = fqname(SAVEF, SAVEPREFIX, 0);
1200.                     fq_old_save = fqname(files[i], SAVEPREFIX, 1);
1201. 
1202.                     if(strcmp(fq_old_save, fq_new_save) != 0 &&
1203.                         !file_exists(fq_new_save))
1204.                         rename(fq_old_save, fq_new_save);
1205. 
1206.                     result[j++] = r;
1207.                 }
1208.             }
1209.         }
1210. 
1211.         free_saved_games(files);
1212. 
1213.     }
1214. #endif
1215. #if defined(UNIX) && defined(QT_GRAPHICS)
1216.     /* posixly correct version */
1217.     int myuid = getuid();
1218.     DIR *dir;
1219. 
1220.     if ((dir = opendir(fqname("save", SAVEPREFIX, 0)))) {
1221.         for (n = 0; readdir(dir); n++)
1222.             ;
1223.         closedir(dir);
1224.         if (n > 0) {
1225.             int i;
1226. 
1227.             if (!(dir = opendir(fqname("save", SAVEPREFIX, 0))))
1228.                 return 0;
1229.             result = (char **) alloc((n + 1) * sizeof(char *)); /* at most */
1230.             (void) memset((genericptr_t) result, 0, (n + 1) * sizeof(char *));
1231.             for (i = 0, j = 0; i < n; i++) {
1232.                 int uid;
1233.                 char name[64]; /* more than PL_NSIZ */
1234.                 struct dirent *entry = readdir(dir);
1235. 
1236.                 if (!entry)
1237.                     break;
1238.                 if (sscanf(entry->d_name, "%d%63s", &uid, name) == 2) {
1239.                     if (uid == myuid) {
1240.                         char filename[BUFSZ];
1241.                         char *r;
1242. 
1243.                         Sprintf(filename, "save/%d%s", uid, name);
1244.                         r = plname_from_file(filename);
1245.                         if (r)
1246.                             result[j++] = r;
1247.                     }
1248.                 }
1249.             }
1250.             closedir(dir);
1251.         }
1252.     }
1253. #endif
1254. #ifdef VMS
1255.     Strcpy(plname, "*");
1256.     set_savefile_name(FALSE);
1257.     j = vms_get_saved_games(SAVEF, &result);
1258. #endif /* VMS */
1259. 
1260.     if (j > 0) {
1261.         if (j > 1)
1262.             qsort(result, j, sizeof (char *), strcmp_wrap);
1263.         result[j] = 0;
1264.         return result;
1265.     } else if (result) { /* could happen if save files are obsolete */
1266.         free_saved_games(result);
1267.     }
1268. #endif /* SELECTSAVED */
1269.     return 0;
1270. }
1271. 
1272. void
1273. free_saved_games(saved)
1274. char **saved;
1275. {
1276.     if (saved) {
1277.         int i = 0;
1278. 
1279.         while (saved[i])
1280.             free((genericptr_t) saved[i++]);
1281.         free((genericptr_t) saved);
1282.     }
1283. }
1284. 
1285. /* ----------  END SAVE FILE HANDLING ----------- */
1286. 
1287. /* ----------  BEGIN FILE COMPRESSION HANDLING ----------- */
1288. 
1289. #ifdef COMPRESS
1290. 
1291. STATIC_OVL void
1292. redirect(filename, mode, stream, uncomp)
1293. const char *filename, *mode;
1294. FILE *stream;
1295. boolean uncomp;
1296. {
1297.     if (freopen(filename, mode, stream) == (FILE *) 0) {
1298.         (void) fprintf(stderr, "freopen of %s for %scompress failed\n",
1299.                        filename, uncomp ? "un" : "");
1300.         nh_terminate(EXIT_FAILURE);
1301.     }
1302. }
1303. 
1304. /*
1305.  * using system() is simpler, but opens up security holes and causes
1306.  * problems on at least Interactive UNIX 3.0.1 (SVR3.2), where any
1307.  * setuid is renounced by /bin/sh, so the files cannot be accessed.
1308.  *
1309.  * cf. child() in unixunix.c.
1310.  */
1311. STATIC_OVL void
1312. docompress_file(filename, uncomp)
1313. const char *filename;
1314. boolean uncomp;
1315. {
1316.     char cfn[80];
1317.     FILE *cf;
1318.     const char *args[10];
1319. #ifdef COMPRESS_OPTIONS
1320.     char opts[80];
1321. #endif
1322.     int i = 0;
1323.     int f;
1324. #ifdef TTY_GRAPHICS
1325.     boolean istty = WINDOWPORT("tty");
1326. #endif
1327. 
1328.     Strcpy(cfn, filename);
1329. #ifdef COMPRESS_EXTENSION
1330.     Strcat(cfn, COMPRESS_EXTENSION);
1331. #endif
1332.     /* when compressing, we know the file exists */
1333.     if (uncomp) {
1334.         if ((cf = fopen(cfn, RDBMODE)) == (FILE *) 0)
1335.             return;
1336.         (void) fclose(cf);
1337.     }
1338. 
1339.     args[0] = COMPRESS;
1340.     if (uncomp)
1341.         args[++i] = "-d"; /* uncompress */
1342. #ifdef COMPRESS_OPTIONS
1343.     {
1344.         /* we can't guarantee there's only one additional option, sigh */
1345.         char *opt;
1346.         boolean inword = FALSE;
1347. 
1348.         Strcpy(opts, COMPRESS_OPTIONS);
1349.         opt = opts;
1350.         while (*opt) {
1351.             if ((*opt == ' ') || (*opt == '\t')) {
1352.                 if (inword) {
1353.                     *opt = '\0';
1354.                     inword = FALSE;
1355.                 }
1356.             } else if (!inword) {
1357.                 args[++i] = opt;
1358.                 inword = TRUE;
1359.             }
1360.             opt++;
1361.         }
1362.     }
1363. #endif
1364.     args[++i] = (char *) 0;
1365. 
1366. #ifdef TTY_GRAPHICS
1367.     /* If we don't do this and we are right after a y/n question *and*
1368.      * there is an error message from the compression, the 'y' or 'n' can
1369.      * end up being displayed after the error message.
1370.      */
1371.     if (istty)
1372.         mark_synch();
1373. #endif
1374.     f = fork();
1375.     if (f == 0) { /* child */
1376. #ifdef TTY_GRAPHICS
1377.         /* any error messages from the compression must come out after
1378.          * the first line, because the more() to let the user read
1379.          * them will have to clear the first line.  This should be
1380.          * invisible if there are no error messages.
1381.          */
1382.         if (istty)
1383.             raw_print("");
1384. #endif
1385.         /* run compressor without privileges, in case other programs
1386.          * have surprises along the line of gzip once taking filenames
1387.          * in GZIP.
1388.          */
1389.         /* assume all compressors will compress stdin to stdout
1390.          * without explicit filenames.  this is true of at least
1391.          * compress and gzip, those mentioned in config.h.
1392.          */
1393.         if (uncomp) {
1394.             redirect(cfn, RDBMODE, stdin, uncomp);
1395.             redirect(filename, WRBMODE, stdout, uncomp);
1396.         } else {
1397.             redirect(filename, RDBMODE, stdin, uncomp);
1398.             redirect(cfn, WRBMODE, stdout, uncomp);
1399.         }
1400.         (void) setgid(getgid());
1401.         (void) setuid(getuid());
1402.         (void) execv(args[0], (char *const *) args);
1403.         perror((char *) 0);
1404.         (void) fprintf(stderr, "Exec to %scompress %s failed.\n",
1405.                        uncomp ? "un" : "", filename);
1406.         nh_terminate(EXIT_FAILURE);
1407.     } else if (f == -1) {
1408.         perror((char *) 0);
1409.         pline("Fork to %scompress %s failed.", uncomp ? "un" : "", filename);
1410.         return;
1411.     }
1412. #ifndef NO_SIGNAL
1413.     (void) signal(SIGINT, SIG_IGN);
1414.     (void) signal(SIGQUIT, SIG_IGN);
1415.     (void) wait((int *) &i);
1416.     (void) signal(SIGINT, (SIG_RET_TYPE) done1);
1417.     if (wizard)
1418.         (void) signal(SIGQUIT, SIG_DFL);
1419. #else
1420.     /* I don't think we can really cope with external compression
1421.      * without signals, so we'll declare that compress failed and
1422.      * go on.  (We could do a better job by forcing off external
1423.      * compression if there are no signals, but we want this for
1424.      * testing with FailSafeC
1425.      */
1426.     i = 1;
1427. #endif
1428.     if (i == 0) {
1429.         /* (un)compress succeeded: remove file left behind */
1430.         if (uncomp)
1431.             (void) unlink(cfn);
1432.         else
1433.             (void) unlink(filename);
1434.     } else {
1435.         /* (un)compress failed; remove the new, bad file */
1436.         if (uncomp) {
1437.             raw_printf("Unable to uncompress %s", filename);
1438.             (void) unlink(filename);
1439.         } else {
1440.             /* no message needed for compress case; life will go on */
1441.             (void) unlink(cfn);
1442.         }
1443. #ifdef TTY_GRAPHICS
1444.         /* Give them a chance to read any error messages from the
1445.          * compression--these would go to stdout or stderr and would get
1446.          * overwritten only in tty mode.  It's still ugly, since the
1447.          * messages are being written on top of the screen, but at least
1448.          * the user can read them.
1449.          */
1450.         if (istty && iflags.window_inited) {
1451.             clear_nhwindow(WIN_MESSAGE);
1452.             more();
1453.             /* No way to know if this is feasible */
1454.             /* doredraw(); */
1455.         }
1456. #endif
1457.     }
1458. }
1459. #endif /* COMPRESS */
1460. 
1461. #if defined(COMPRESS) || defined(ZLIB_COMP)
1462. #define UNUSED_if_not_COMPRESS /*empty*/
1463. #else
1464. #define UNUSED_if_not_COMPRESS UNUSED
1465. #endif
1466. 
1467. /* compress file */
1468. void
1469. nh_compress(filename)
1470. const char *filename UNUSED_if_not_COMPRESS;
1471. {
1472. #if !defined(COMPRESS) && !defined(ZLIB_COMP)
1473. #ifdef PRAGMA_UNUSED
1474. #pragma unused(filename)
1475. #endif
1476. #else
1477.     docompress_file(filename, FALSE);
1478. #endif
1479. }
1480. 
1481. /* uncompress file if it exists */
1482. void
1483. nh_uncompress(filename)
1484. const char *filename UNUSED_if_not_COMPRESS;
1485. {
1486. #if !defined(COMPRESS) && !defined(ZLIB_COMP)
1487. #ifdef PRAGMA_UNUSED
1488. #pragma unused(filename)
1489. #endif
1490. #else
1491.     docompress_file(filename, TRUE);
1492. #endif
1493. }
1494. 
1495. #ifdef ZLIB_COMP /* RLC 09 Mar 1999: Support internal ZLIB */
1496. STATIC_OVL boolean
1497. make_compressed_name(filename, cfn)
1498. const char *filename;
1499. char *cfn;
1500. {
1501. #ifndef SHORT_FILENAMES
1502.     /* Assume free-form filename with no 8.3 restrictions */
1503.     strcpy(cfn, filename);
1504.     strcat(cfn, COMPRESS_EXTENSION);
1505.     return TRUE;
1506. #else
1507. #ifdef SAVE_EXTENSION
1508.     char *bp = (char *) 0;
1509. 
1510.     strcpy(cfn, filename);
1511.     if ((bp = strstri(cfn, SAVE_EXTENSION))) {
1512.         strsubst(bp, SAVE_EXTENSION, ".saz");
1513.         return TRUE;
1514.     } else {
1515.         /* find last occurrence of bon */
1516.         bp = eos(cfn);
1517.         while (bp-- > cfn) {
1518.             if (strstri(bp, "bon")) {
1519.                 strsubst(bp, "bon", "boz");
1520.                 return TRUE;
1521.             }
1522.         }
1523.     }
1524. #endif /* SAVE_EXTENSION */
1525.     return FALSE;
1526. #endif /* SHORT_FILENAMES */
1527. }
1528. 
1529. STATIC_OVL void
1530. docompress_file(filename, uncomp)
1531. const char *filename;
1532. boolean uncomp;
1533. {
1534.     gzFile compressedfile;
1535.     FILE *uncompressedfile;
1536.     char cfn[256];
1537.     char buf[1024];
1538.     unsigned len, len2;
1539. 
1540.     if (!make_compressed_name(filename, cfn))
1541.         return;
1542. 
1543.     if (!uncomp) {
1544.         /* Open the input and output files */
1545.         /* Note that gzopen takes "wb" as its mode, even on systems where
1546.            fopen takes "r" and "w" */
1547. 
1548.         uncompressedfile = fopen(filename, RDBMODE);
1549.         if (!uncompressedfile) {
1550.             pline("Error in zlib docompress_file %s", filename);
1551.             return;
1552.         }
1553.         compressedfile = gzopen(cfn, "wb");
1554.         if (compressedfile == NULL) {
1555.             if (errno == 0) {
1556.                 pline("zlib failed to allocate memory");
1557.             } else {
1558.                 panic("Error in docompress_file %d", errno);
1559.             }
1560.             fclose(uncompressedfile);
1561.             return;
1562.         }
1563. 
1564.         /* Copy from the uncompressed to the compressed file */
1565. 
1566.         while (1) {
1567.             len = fread(buf, 1, sizeof(buf), uncompressedfile);
1568.             if (ferror(uncompressedfile)) {
1569.                 pline("Failure reading uncompressed file");
1570.                 pline("Can't compress %s.", filename);
1571.                 fclose(uncompressedfile);
1572.                 gzclose(compressedfile);
1573.                 (void) unlink(cfn);
1574.                 return;
1575.             }
1576.             if (len == 0)
1577.                 break; /* End of file */
1578. 
1579.             len2 = gzwrite(compressedfile, buf, len);
1580.             if (len2 == 0) {
1581.                 pline("Failure writing compressed file");
1582.                 pline("Can't compress %s.", filename);
1583.                 fclose(uncompressedfile);
1584.                 gzclose(compressedfile);
1585.                 (void) unlink(cfn);
1586.                 return;
1587.             }
1588.         }
1589. 
1590.         fclose(uncompressedfile);
1591.         gzclose(compressedfile);
1592. 
1593.         /* Delete the file left behind */
1594. 
1595.         (void) unlink(filename);
1596. 
1597.     } else { /* uncomp */
1598. 
1599.         /* Open the input and output files */
1600.         /* Note that gzopen takes "rb" as its mode, even on systems where
1601.            fopen takes "r" and "w" */
1602. 
1603.         compressedfile = gzopen(cfn, "rb");
1604.         if (compressedfile == NULL) {
1605.             if (errno == 0) {
1606.                 pline("zlib failed to allocate memory");
1607.             } else if (errno != ENOENT) {
1608.                 panic("Error in zlib docompress_file %s, %d", filename,
1609.                       errno);
1610.             }
1611.             return;
1612.         }
1613.         uncompressedfile = fopen(filename, WRBMODE);
1614.         if (!uncompressedfile) {
1615.             pline("Error in zlib docompress file uncompress %s", filename);
1616.             gzclose(compressedfile);
1617.             return;
1618.         }
1619. 
1620.         /* Copy from the compressed to the uncompressed file */
1621. 
1622.         while (1) {
1623.             len = gzread(compressedfile, buf, sizeof(buf));
1624.             if (len == (unsigned) -1) {
1625.                 pline("Failure reading compressed file");
1626.                 pline("Can't uncompress %s.", filename);
1627.                 fclose(uncompressedfile);
1628.                 gzclose(compressedfile);
1629.                 (void) unlink(filename);
1630.                 return;
1631.             }
1632.             if (len == 0)
1633.                 break; /* End of file */
1634. 
1635.             fwrite(buf, 1, len, uncompressedfile);
1636.             if (ferror(uncompressedfile)) {
1637.                 pline("Failure writing uncompressed file");
1638.                 pline("Can't uncompress %s.", filename);
1639.                 fclose(uncompressedfile);
1640.                 gzclose(compressedfile);
1641.                 (void) unlink(filename);
1642.                 return;
1643.             }
1644.         }
1645. 
1646.         fclose(uncompressedfile);
1647.         gzclose(compressedfile);
1648. 
1649.         /* Delete the file left behind */
1650.         (void) unlink(cfn);
1651.     }
1652. }
1653. #endif /* RLC 09 Mar 1999: End ZLIB patch */
1654. 
1655. /* ----------  END FILE COMPRESSION HANDLING ----------- */
1656. 
1657. /* ----------  BEGIN FILE LOCKING HANDLING ----------- */
1658. 
1659. static int nesting = 0;
1660. 
1661. #if defined(NO_FILE_LINKS) || defined(USE_FCNTL) /* implies UNIX */
1662. static int lockfd = -1; /* for lock_file() to pass to unlock_file() */
1663. #endif
1664. #ifdef USE_FCNTL
1665. struct flock sflock; /* for unlocking, same as above */
1666. #endif
1667. 
1668. #define HUP if (!program_state.done_hup)
1669. 
1670. #ifndef USE_FCNTL
1671. STATIC_OVL char *
1672. make_lockname(filename, lockname)
1673. const char *filename;
1674. char *lockname;
1675. {
1676. #if defined(UNIX) || defined(VMS) || defined(AMIGA) || defined(WIN32) \
1677.     || defined(MSDOS)
1678. #ifdef NO_FILE_LINKS
1679.     Strcpy(lockname, LOCKDIR);
1680.     Strcat(lockname, "/");
1681.     Strcat(lockname, filename);
1682. #else
1683.     Strcpy(lockname, filename);
1684. #endif
1685. #ifdef VMS
1686.     {
1687.         char *semi_colon = rindex(lockname, ';');
1688.         if (semi_colon)
1689.             *semi_colon = '\0';
1690.     }
1691.     Strcat(lockname, ".lock;1");
1692. #else
1693.     Strcat(lockname, "_lock");
1694. #endif
1695.     return lockname;
1696. #else /* !(UNIX || VMS || AMIGA || WIN32 || MSDOS) */
1697. #ifdef PRAGMA_UNUSED
1698. #pragma unused(filename)
1699. #endif
1700.     lockname[0] = '\0';
1701.     return (char *) 0;
1702. #endif
1703. }
1704. #endif /* !USE_FCNTL */
1705. 
1706. /* lock a file */
1707. boolean
1708. lock_file(filename, whichprefix, retryct)
1709. const char *filename;
1710. int whichprefix;
1711. int retryct;
1712. {
1713. #if defined(PRAGMA_UNUSED) && !(defined(UNIX) || defined(VMS)) \
1714.     && !(defined(AMIGA) || defined(WIN32) || defined(MSDOS))
1715. #pragma unused(retryct)
1716. #endif
1717. #ifndef USE_FCNTL
1718.     char locknambuf[BUFSZ];
1719.     const char *lockname;
1720. #endif
1721. 
1722.     nesting++;
1723.     if (nesting > 1) {
1724.         impossible("TRIED TO NEST LOCKS");
1725.         return TRUE;
1726.     }
1727. 
1728. #ifndef USE_FCNTL
1729.     lockname = make_lockname(filename, locknambuf);
1730. #ifndef NO_FILE_LINKS /* LOCKDIR should be subsumed by LOCKPREFIX */
1731.     lockname = fqname(lockname, LOCKPREFIX, 2);
1732. #endif
1733. #endif
1734.     filename = fqname(filename, whichprefix, 0);
1735. #ifdef USE_FCNTL
1736.     lockfd = open(filename, O_RDWR);
1737.     if (lockfd == -1) {
1738.         HUP raw_printf("Cannot open file %s.  Is NetHack installed correctly?",
1739.                        filename);
1740.         nesting--;
1741.         return FALSE;
1742.     }
1743.     sflock.l_type = F_WRLCK;
1744.     sflock.l_whence = SEEK_SET;
1745.     sflock.l_start = 0;
1746.     sflock.l_len = 0;
1747. #endif
1748. 
1749. #if defined(UNIX) || defined(VMS)
1750. #ifdef USE_FCNTL
1751.     while (fcntl(lockfd, F_SETLK, &sflock) == -1) {
1752. #else
1753. #ifdef NO_FILE_LINKS
1754.     while ((lockfd = open(lockname, O_RDWR | O_CREAT | O_EXCL, 0666)) == -1) {
1755. #else
1756.     while (link(filename, lockname) == -1) {
1757. #endif
1758. #endif
1759. 
1760. #ifdef USE_FCNTL
1761.         if (retryct--) {
1762.             HUP raw_printf(
1763.                "Waiting for release of fcntl lock on %s.  (%d retries left.)",
1764.                            filename, retryct);
1765.             sleep(1);
1766.         } else {
1767.             HUP(void) raw_print("I give up.  Sorry.");
1768.             HUP raw_printf("Some other process has an unnatural grip on %s.",
1769.                            filename);
1770.             nesting--;
1771.             return FALSE;
1772.         }
1773. #else
1774.         int errnosv = errno;
1775. 
1776.         switch (errnosv) { /* George Barbanis */
1777.         case EEXIST:
1778.             if (retryct--) {
1779.                 HUP raw_printf(
1780.                     "Waiting for access to %s.  (%d retries left).", filename,
1781.                     retryct);
1782. #if defined(SYSV) || defined(ULTRIX) || defined(VMS)
1783.                 (void)
1784. #endif
1785.                     sleep(1);
1786.             } else {
1787.                 HUP(void) raw_print("I give up.  Sorry.");
1788.                 HUP raw_printf("Perhaps there is an old %s around?",
1789.                                lockname);
1790.                 nesting--;
1791.                 return FALSE;
1792.             }
1793. 
1794.             break;
1795.         case ENOENT:
1796.             HUP raw_printf("Can't find file %s to lock!", filename);
1797.             nesting--;
1798.             return FALSE;
1799.         case EACCES:
1800.             HUP raw_printf("No write permission to lock %s!", filename);
1801.             nesting--;
1802.             return FALSE;
1803. #ifdef VMS /* c__translate(vmsfiles.c) */
1804.         case EPERM:
1805.             /* could be misleading, but usually right */
1806.             HUP raw_printf("Can't lock %s due to directory protection.",
1807.                            filename);
1808.             nesting--;
1809.             return FALSE;
1810. #endif
1811.         case EROFS:
1812.             /* take a wild guess at the underlying cause */
1813.             HUP perror(lockname);
1814.             HUP raw_printf("Cannot lock %s.", filename);
1815.             HUP raw_printf(
1816.   "(Perhaps you are running NetHack from inside the distribution package?).");
1817.             nesting--;
1818.             return FALSE;
1819.         default:
1820.             HUP perror(lockname);
1821.             HUP raw_printf("Cannot lock %s for unknown reason (%d).",
1822.                            filename, errnosv);
1823.             nesting--;
1824.             return FALSE;
1825.         }
1826. #endif /* USE_FCNTL */
1827.     }
1828. #endif /* UNIX || VMS */
1829. 
1830. #if (defined(AMIGA) || defined(WIN32) || defined(MSDOS)) \
1831.     && !defined(USE_FCNTL)
1832. #ifdef AMIGA
1833. #define OPENFAILURE(fd) (!fd)
1834.     lockptr = 0;
1835. #else
1836. #define OPENFAILURE(fd) (fd < 0)
1837.     lockptr = -1;
1838. #endif
1839.     while (--retryct && OPENFAILURE(lockptr)) {
1840. #if defined(WIN32) && !defined(WIN_CE)
1841.         lockptr = sopen(lockname, O_RDWR | O_CREAT, SH_DENYRW, S_IWRITE);
1842. #else
1843.         (void) DeleteFile(lockname); /* in case dead process was here first */
1844. #ifdef AMIGA
1845.         lockptr = Open(lockname, MODE_NEWFILE);
1846. #else
1847.         lockptr = open(lockname, O_RDWR | O_CREAT | O_EXCL, S_IWRITE);
1848. #endif
1849. #endif
1850.         if (OPENFAILURE(lockptr)) {
1851.             raw_printf("Waiting for access to %s.  (%d retries left).",
1852.                        filename, retryct);
1853.             Delay(50);
1854.         }
1855.     }
1856.     if (!retryct) {
1857.         raw_printf("I give up.  Sorry.");
1858.         nesting--;
1859.         return FALSE;
1860.     }
1861. #endif /* AMIGA || WIN32 || MSDOS */
1862.     return TRUE;
1863. }
1864. 
1865. #ifdef VMS /* for unlock_file, use the unlink() routine in vmsunix.c */
1866. #ifdef unlink
1867. #undef unlink
1868. #endif
1869. #define unlink(foo) vms_unlink(foo)
1870. #endif
1871. 
1872. /* unlock file, which must be currently locked by lock_file */
1873. void
1874. unlock_file(filename)
1875. const char *filename;
1876. {
1877. #ifndef USE_FCNTL
1878.     char locknambuf[BUFSZ];
1879.     const char *lockname;
1880. #endif
1881. 
1882.     if (nesting == 1) {
1883. #ifdef USE_FCNTL
1884.         sflock.l_type = F_UNLCK;
1885.         if (lockfd >= 0) {
1886.             if (fcntl(lockfd, F_SETLK, &sflock) == -1)
1887.                 HUP raw_printf("Can't remove fcntl lock on %s.", filename);
1888.             (void) close(lockfd), lockfd = -1;
1889.         }
1890. #else
1891.         lockname = make_lockname(filename, locknambuf);
1892. #ifndef NO_FILE_LINKS /* LOCKDIR should be subsumed by LOCKPREFIX */
1893.         lockname = fqname(lockname, LOCKPREFIX, 2);
1894. #endif
1895. 
1896. #if defined(UNIX) || defined(VMS)
1897.         if (unlink(lockname) < 0)
1898.             HUP raw_printf("Can't unlink %s.", lockname);
1899. #ifdef NO_FILE_LINKS
1900.         (void) nhclose(lockfd), lockfd = -1;
1901. #endif
1902. 
1903. #endif /* UNIX || VMS */
1904. 
1905. #if defined(AMIGA) || defined(WIN32) || defined(MSDOS)
1906.         if (lockptr)
1907.             Close(lockptr);
1908.         DeleteFile(lockname);
1909.         lockptr = 0;
1910. #endif /* AMIGA || WIN32 || MSDOS */
1911. #endif /* USE_FCNTL */
1912.     }
1913. 
1914.     nesting--;
1915. }
1916. 
1917. /* ----------  END FILE LOCKING HANDLING ----------- */
1918. 
1919. /* ----------  BEGIN CONFIG FILE HANDLING ----------- */
1920. 
1921. const char *default_configfile =
1922. #ifdef UNIX
1923.     ".nethackrc";
1924. #else
1925. #if defined(MAC) || defined(__BEOS__)
1926.     "NetHack Defaults";
1927. #else
1928. #if defined(MSDOS) || defined(WIN32)
1929.     CONFIG_FILE;
1930. #else
1931.     "NetHack.cnf";
1932. #endif
1933. #endif
1934. #endif
1935. 
1936. /* used for messaging */
1937. char configfile[BUFSZ];
1938. 
1939. #ifdef MSDOS
1940. /* conflict with speed-dial under windows
1941.  * for XXX.cnf file so support of NetHack.cnf
1942.  * is for backward compatibility only.
1943.  * Preferred name (and first tried) is now defaults.nh but
1944.  * the game will try the old name if there
1945.  * is no defaults.nh.
1946.  */
1947. const char *backward_compat_configfile = "nethack.cnf";
1948. #endif
1949. 
1950. /* remember the name of the file we're accessing;
1951.    if may be used in option reject messages */
1952. STATIC_OVL void
1953. set_configfile_name(fname)
1954. const char *fname;
1955. {
1956.     (void) strncpy(configfile, fname, sizeof configfile - 1);
1957.     configfile[sizeof configfile - 1] = '\0';
1958. }
1959. 
1960. #ifndef MFLOPPY
1961. #define fopenp fopen
1962. #endif
1963. 
1964. STATIC_OVL FILE *
1965. fopen_config_file(filename, src)
1966. const char *filename;
1967. int src;
1968. {
1969.     FILE *fp;
1970. #if defined(UNIX) || defined(VMS)
1971.     char tmp_config[BUFSZ];
1972.     char *envp;
1973. #endif
1974. 
1975.     if (src == SET_IN_SYS) {
1976.         /* SYSCF_FILE; if we can't open it, caller will bail */
1977.         if (filename && *filename) {
1978.             set_configfile_name(fqname(filename, SYSCONFPREFIX, 0));
1979.             fp = fopenp(configfile, "r");
1980.         } else
1981.             fp = (FILE *) 0;
1982.         return  fp;
1983.     }
1984.     /* If src != SET_IN_SYS, "filename" is an environment variable, so it
1985.      * should hang around. If set, it is expected to be a full path name
1986.      * (if relevant)
1987.      */
1988.     if (filename && *filename) {
1989.         set_configfile_name(filename);
1990. #ifdef UNIX
1991.         if (access(configfile, 4) == -1) { /* 4 is R_OK on newer systems */
1992.             /* nasty sneaky attempt to read file through
1993.              * NetHack's setuid permissions -- this is the only
1994.              * place a file name may be wholly under the player's
1995.              * control (but SYSCF_FILE is not under the player's
1996.              * control so it's OK).
1997.              */
1998.             raw_printf("Access to %s denied (%d).", configfile, errno);
1999.             wait_synch();
2000.             /* fall through to standard names */
2001.         } else
2002. #endif
2003.         if ((fp = fopenp(configfile, "r")) != (FILE *) 0) {
2004.             return  fp;
2005. #if defined(UNIX) || defined(VMS)
2006.         } else {
2007.             /* access() above probably caught most problems for UNIX */
2008.             raw_printf("Couldn't open requested config file %s (%d).",
2009.                        configfile, errno);
2010.             wait_synch();
2011. #endif
2012.         }
2013.     }
2014.     /* fall through to standard names */
2015. 
2016. #if defined(MICRO) || defined(MAC) || defined(__BEOS__) || defined(WIN32)
2017.     set_configfile_name(fqname(default_configfile, CONFIGPREFIX, 0));
2018.     if ((fp = fopenp(configfile, "r")) != (FILE *) 0) {
2019.         return fp;
2020.     } else if (strcmp(default_configfile, configfile)) {
2021.         set_configfile_name(default_configfile);
2022.         if ((fp = fopenp(configfile, "r")) != (FILE *) 0)
2023.             return fp;
2024.     }
2025. #ifdef MSDOS
2026.     set_configfile_name(fqname(backward_compat_configfile, CONFIGPREFIX, 0));
2027.     if ((fp = fopenp(configfile, "r")) != (FILE *) 0) {
2028.         return fp;
2029.     } else if (strcmp(backward_compat_configfile, configfile)) {
2030.         set_configfile_name(backward_compat_configfile);
2031.         if ((fp = fopenp(configfile, "r")) != (FILE *) 0)
2032.             return fp;
2033.     }
2034. #endif
2035. #else
2036. /* constructed full path names don't need fqname() */
2037. #ifdef VMS
2038.     /* no punctuation, so might be a logical name */
2039.     set_configfile_name("nethackini");
2040.     if ((fp = fopenp(configfile, "r")) != (FILE *) 0)
2041.         return fp;
2042.     set_configfile_name("sys$login:nethack.ini");
2043.     if ((fp = fopenp(configfile, "r")) != (FILE *) 0)
2044.         return fp;
2045. 
2046.     envp = nh_getenv("HOME");
2047.     if (!envp || !*envp)
2048.         Strcpy(tmp_config, "NetHack.cnf");
2049.     else
2050.         Sprintf(tmp_config, "%s%s%s", envp,
2051.                 !index(":]>/", envp[strlen(envp) - 1]) ? "/" : "",
2052.                 "NetHack.cnf");
2053.     set_configfile_name(tmp_config);
2054.     if ((fp = fopenp(configfile, "r")) != (FILE *) 0)
2055.         return fp;
2056. #else /* should be only UNIX left */
2057.     envp = nh_getenv("HOME");
2058.     if (!envp)
2059.         Strcpy(tmp_config, ".nethackrc");
2060.     else
2061.         Sprintf(tmp_config, "%s/%s", envp, ".nethackrc");
2062. 
2063.     set_configfile_name(tmp_config);
2064.     if ((fp = fopenp(configfile, "r")) != (FILE *) 0)
2065.         return fp;
2066. #if defined(__APPLE__) /* UNIX+__APPLE__ => MacOSX */
2067.     /* try an alternative */
2068.     if (envp) {
2069.         /* OSX-style configuration settings */
2070.         Sprintf(tmp_config, "%s/%s", envp,
2071.                 "Library/Preferences/NetHack Defaults");
2072.         set_configfile_name(tmp_config);
2073.         if ((fp = fopenp(configfile, "r")) != (FILE *) 0)
2074.             return fp;
2075.         /* may be easier for user to edit if filename has '.txt' suffix */
2076.         Sprintf(tmp_config, "%s/%s", envp,
2077.                 "Library/Preferences/NetHack Defaults.txt");
2078.         set_configfile_name(tmp_config);
2079.         if ((fp = fopenp(configfile, "r")) != (FILE *) 0)
2080.             return fp;
2081.     }
2082. #endif /*__APPLE__*/
2083.     if (errno != ENOENT) {
2084.         const char *details;
2085. 
2086.         /* e.g., problems when setuid NetHack can't search home
2087.            directory restricted to user */
2088. #if defined(NHSTDC) && !defined(NOTSTDC)
2089.         if ((details = strerror(errno)) == 0)
2090. #endif
2091.             details = "";
2092.         raw_printf("Couldn't open default config file %s %s(%d).",
2093.                    configfile, details, errno);
2094.         wait_synch();
2095.     }
2096. #endif /* !VMS => Unix */
2097. #endif /* !(MICRO || MAC || __BEOS__ || WIN32) */
2098.     return (FILE *) 0;
2099. }
2100. 
2101. /*
2102.  * Retrieve a list of integers from buf into a uchar array.
2103.  *
2104.  * NOTE: zeros are inserted unless modlist is TRUE, in which case the list
2105.  *  location is unchanged.  Callers must handle zeros if modlist is FALSE.
2106.  */
2107. STATIC_OVL int
2108. get_uchars(bufp, list, modlist, size, name)
2109. char *bufp;       /* current pointer */
2110. uchar *list;      /* return list */
2111. boolean modlist;  /* TRUE: list is being modified in place */
2112. int size;         /* return list size */
2113. const char *name; /* name of option for error message */
2114. {
2115.     unsigned int num = 0;
2116.     int count = 0;
2117.     boolean havenum = FALSE;
2118. 
2119.     while (1) {
2120.         switch (*bufp) {
2121.         case ' ':
2122.         case '\0':
2123.         case '\t':
2124.         case '\n':
2125.             if (havenum) {
2126.                 /* if modifying in place, don't insert zeros */
2127.                 if (num || !modlist)
2128.                     list[count] = num;
2129.                 count++;
2130.                 num = 0;
2131.                 havenum = FALSE;
2132.             }
2133.             if (count == size || !*bufp)
2134.                 return count;
2135.             bufp++;
2136.             break;
2137. 
2138.         case '0':
2139.         case '1':
2140.         case '2':
2141.         case '3':
2142.         case '4':
2143.         case '5':
2144.         case '6':
2145.         case '7':
2146.         case '8':
2147.         case '9':
2148.             havenum = TRUE;
2149.             num = num * 10 + (*bufp - '0');
2150.             bufp++;
2151.             break;
2152. 
2153.         case '\\':
2154.             goto gi_error;
2155.             break;
2156. 
2157.         default:
2158.  gi_error:
2159.             raw_printf("Syntax error in %s", name);
2160.             wait_synch();
2161.             return count;
2162.         }
2163.     }
2164.     /*NOTREACHED*/
2165. }
2166. 
2167. #ifdef NOCWD_ASSUMPTIONS
2168. STATIC_OVL void
2169. adjust_prefix(bufp, prefixid)
2170. char *bufp;
2171. int prefixid;
2172. {
2173.     char *ptr;
2174. 
2175.     if (!bufp)
2176.         return;
2177. #ifdef WIN32
2178.     if (fqn_prefix_locked[prefixid])
2179.         return;
2180. #endif
2181.     /* Backward compatibility, ignore trailing ;n */
2182.     if ((ptr = index(bufp, ';')) != 0)
2183.         *ptr = '\0';
2184.     if (strlen(bufp) > 0) {
2185.         fqn_prefix[prefixid] = (char *) alloc(strlen(bufp) + 2);
2186.         Strcpy(fqn_prefix[prefixid], bufp);
2187.         append_slash(fqn_prefix[prefixid]);
2188.     }
2189. }
2190. #endif
2191. 
2192. /* Choose at random one of the sep separated parts from str. Mangles str. */
2193. STATIC_OVL char *
2194. choose_random_part(str,sep)
2195. char *str;
2196. char sep;
2197. {
2198.     int nsep = 1;
2199.     int csep;
2200.     int len = 0;
2201.     char *begin = str;
2202. 
2203.     if (!str)
2204.         return (char *) 0;
2205. 
2206.     while (*str) {
2207.         if (*str == sep)
2208.             nsep++;
2209.         str++;
2210.     }
2211.     csep = rn2(nsep);
2212.     str = begin;
2213.     while ((csep > 0) && *str) {
2214.         str++;
2215.         if (*str == sep)
2216.             csep--;
2217.     }
2218.     if (*str) {
2219.         if (*str == sep)
2220.             str++;
2221.         begin = str;
2222.         while (*str && *str != sep) {
2223.             str++;
2224.             len++;
2225.         }
2226.         *str = '\0';
2227.         if (len)
2228.             return begin;
2229.     }
2230.     return (char *) 0;
2231. }
2232. 
2233. STATIC_OVL void
2234. free_config_sections()
2235. {
2236.     if (config_section_chosen) {
2237.         free(config_section_chosen);
2238.         config_section_chosen = NULL;
2239.     }
2240.     if (config_section_current) {
2241.         free(config_section_current);
2242.         config_section_current = NULL;
2243.     }
2244. }
2245. 
2246. STATIC_OVL boolean
2247. is_config_section(str)
2248. const char *str;
2249. {
2250.     const char *a = rindex(str, ']');
2251. 
2252.     return (a && *str == '[' && *(a+1) == '\0' && (int)(a - str) > 0);
2253. }
2254. 
2255. STATIC_OVL boolean
2256. handle_config_section(buf)
2257. char *buf;
2258. {
2259.     if (is_config_section(buf)) {
2260.         char *send;
2261.         if (config_section_current) {
2262.             free(config_section_current);
2263.         }
2264.         config_section_current = dupstr(&buf[1]);
2265.         send = rindex(config_section_current, ']');
2266.         *send = '\0';
2267.         debugpline1("set config section: '%s'", config_section_current);
2268.         return TRUE;
2269.     }
2270. 
2271.     if (config_section_current) {
2272.         if (!config_section_chosen)
2273.             return TRUE;
2274.         if (strcmp(config_section_current, config_section_chosen))
2275.             return TRUE;
2276.     }
2277.     return FALSE;
2278. }
2279. 
2280. #define match_varname(INP, NAM, LEN) match_optname(INP, NAM, LEN, TRUE)
2281. 
2282. /* find the '=' or ':' */
2283. char *
2284. find_optparam(buf)
2285. const char *buf;
2286. {
2287.     char *bufp, *altp;
2288. 
2289.     bufp = index(buf, '=');
2290.     altp = index(buf, ':');
2291.     if (!bufp || (altp && altp < bufp))
2292.         bufp = altp;
2293. 
2294.     return bufp;
2295. }
2296. 
2297. boolean
2298. parse_config_line(origbuf)
2299. char *origbuf;
2300. {
2301. #if defined(MICRO) && !defined(NOCWD_ASSUMPTIONS)
2302.     static boolean ramdisk_specified = FALSE;
2303. #endif
2304. #ifdef SYSCF
2305.     int n, src = iflags.parse_config_file_src;
2306. #endif
2307.     char *bufp, buf[4 * BUFSZ];
2308.     uchar translate[MAXPCHARS];
2309.     int len;
2310.     boolean retval = TRUE;
2311. 
2312.     while (*origbuf == ' ' || *origbuf == '\t') /* skip leading whitespace */
2313.         ++origbuf;                   /* (caller probably already did this) */
2314.     (void) strncpy(buf, origbuf, sizeof buf - 1);
2315.     buf[sizeof buf - 1] = '\0'; /* strncpy not guaranteed to NUL terminate */
2316.     /* convert any tab to space, condense consecutive spaces into one,
2317.        remove leading and trailing spaces (exception: if there is nothing
2318.        but spaces, one of them will be kept even though it leads/trails) */
2319.     mungspaces(buf);
2320. 
2321.     /* find the '=' or ':' */
2322.     bufp = find_optparam(buf);
2323.     if (!bufp) {
2324.         config_error_add("Not a config statement, missing '='");
2325.         return FALSE;
2326.     }
2327.     /* skip past '=', then space between it and value, if any */
2328.     ++bufp;
2329.     if (*bufp == ' ')
2330.         ++bufp;
2331. 
2332.     /* Go through possible variables */
2333.     /* some of these (at least LEVELS and SAVE) should now set the
2334.      * appropriate fqn_prefix[] rather than specialized variables
2335.      */
2336.     if (match_varname(buf, "OPTIONS", 4)) {
2337.         /* hack: un-mungspaces to allow consecutive spaces in
2338.            general options until we verify that this is unnecessary;
2339.            '=' or ':' is guaranteed to be present */
2340.         bufp = find_optparam(origbuf);
2341.         ++bufp; /* skip '='; parseoptions() handles spaces */
2342. 
2343.         if (!parseoptions(bufp, TRUE, TRUE))
2344.             retval = FALSE;
2345.     } else if (match_varname(buf, "AUTOPICKUP_EXCEPTION", 5)) {
2346.         add_autopickup_exception(bufp);
2347.     } else if (match_varname(buf, "BINDINGS", 4)) {
2348.         if (!parsebindings(bufp))
2349.             retval = FALSE;
2350.     } else if (match_varname(buf, "AUTOCOMPLETE", 5)) {
2351.         parseautocomplete(bufp, TRUE);
2352.     } else if (match_varname(buf, "MSGTYPE", 7)) {
2353.         if (!msgtype_parse_add(bufp))
2354.             retval = FALSE;
2355. #ifdef NOCWD_ASSUMPTIONS
2356.     } else if (match_varname(buf, "HACKDIR", 4)) {
2357.         adjust_prefix(bufp, HACKPREFIX);
2358.     } else if (match_varname(buf, "LEVELDIR", 4)
2359.                || match_varname(buf, "LEVELS", 4)) {
2360.         adjust_prefix(bufp, LEVELPREFIX);
2361.     } else if (match_varname(buf, "SAVEDIR", 4)) {
2362.         adjust_prefix(bufp, SAVEPREFIX);
2363.     } else if (match_varname(buf, "BONESDIR", 5)) {
2364.         adjust_prefix(bufp, BONESPREFIX);
2365.     } else if (match_varname(buf, "DATADIR", 4)) {
2366.         adjust_prefix(bufp, DATAPREFIX);
2367.     } else if (match_varname(buf, "SCOREDIR", 4)) {
2368.         adjust_prefix(bufp, SCOREPREFIX);
2369.     } else if (match_varname(buf, "LOCKDIR", 4)) {
2370.         adjust_prefix(bufp, LOCKPREFIX);
2371.     } else if (match_varname(buf, "CONFIGDIR", 4)) {
2372.         adjust_prefix(bufp, CONFIGPREFIX);
2373.     } else if (match_varname(buf, "TROUBLEDIR", 4)) {
2374.         adjust_prefix(bufp, TROUBLEPREFIX);
2375. #else /*NOCWD_ASSUMPTIONS*/
2376. #ifdef MICRO
2377.     } else if (match_varname(buf, "HACKDIR", 4)) {
2378.         (void) strncpy(hackdir, bufp, PATHLEN - 1);
2379. #ifdef MFLOPPY
2380.     } else if (match_varname(buf, "RAMDISK", 3)) {
2381. /* The following ifdef is NOT in the wrong
2382.  * place.  For now, we accept and silently
2383.  * ignore RAMDISK */
2384. #ifndef AMIGA
2385.         if (strlen(bufp) >= PATHLEN)
2386.             bufp[PATHLEN - 1] = '\0';
2387.         Strcpy(levels, bufp);
2388.         ramdisk = (strcmp(permbones, levels) != 0);
2389.         ramdisk_specified = TRUE;
2390. #endif
2391. #endif
2392.     } else if (match_varname(buf, "LEVELS", 4)) {
2393.         if (strlen(bufp) >= PATHLEN)
2394.             bufp[PATHLEN - 1] = '\0';
2395.         Strcpy(permbones, bufp);
2396.         if (!ramdisk_specified || !*levels)
2397.             Strcpy(levels, bufp);
2398.         ramdisk = (strcmp(permbones, levels) != 0);
2399.     } else if (match_varname(buf, "SAVE", 4)) {
2400. #ifdef MFLOPPY
2401.         extern int saveprompt;
2402. #endif
2403.         char *ptr;
2404. 
2405.         if ((ptr = index(bufp, ';')) != 0) {
2406.             *ptr = '\0';
2407. #ifdef MFLOPPY
2408.             if (*(ptr + 1) == 'n' || *(ptr + 1) == 'N') {
2409.                 saveprompt = FALSE;
2410.             }
2411. #endif
2412.         }
2413. #if defined(SYSFLAGS) && defined(MFLOPPY)
2414.         else
2415.             saveprompt = sysflags.asksavedisk;
2416. #endif
2417. 
2418.         (void) strncpy(SAVEP, bufp, SAVESIZE - 1);
2419.         append_slash(SAVEP);
2420. #endif /* MICRO */
2421. #endif /*NOCWD_ASSUMPTIONS*/
2422. 
2423.     } else if (match_varname(buf, "NAME", 4)) {
2424.         (void) strncpy(plname, bufp, PL_NSIZ - 1);
2425.     } else if (match_varname(buf, "ROLE", 4)
2426.                || match_varname(buf, "CHARACTER", 4)) {
2427.         if ((len = str2role(bufp)) >= 0)
2428.             flags.initrole = len;
2429.     } else if (match_varname(buf, "DOGNAME", 3)) {
2430.         (void) strncpy(dogname, bufp, PL_PSIZ - 1);
2431.     } else if (match_varname(buf, "CATNAME", 3)) {
2432.         (void) strncpy(catname, bufp, PL_PSIZ - 1);
2433. 
2434. #ifdef SYSCF
2435.     } else if (src == SET_IN_SYS && match_varname(buf, "WIZARDS", 7)) {
2436.         if (sysopt.wizards)
2437.             free((genericptr_t) sysopt.wizards);
2438.         sysopt.wizards = dupstr(bufp);
2439.         if (strlen(sysopt.wizards) && strcmp(sysopt.wizards, "*")) {
2440.             /* pre-format WIZARDS list now; it's displayed during a panic
2441.                and since that panic might be due to running out of memory,
2442.                we don't want to risk attempting to allocate any memory then */
2443.             if (sysopt.fmtd_wizard_list)
2444.                 free((genericptr_t) sysopt.fmtd_wizard_list);
2445.             sysopt.fmtd_wizard_list = build_english_list(sysopt.wizards);
2446.         }
2447.     } else if (src == SET_IN_SYS && match_varname(buf, "SHELLERS", 8)) {
2448.         if (sysopt.shellers)
2449.             free((genericptr_t) sysopt.shellers);
2450.         sysopt.shellers = dupstr(bufp);
2451.     } else if (src == SET_IN_SYS && match_varname(buf, "EXPLORERS", 7)) {
2452.         if (sysopt.explorers)
2453.             free((genericptr_t) sysopt.explorers);
2454.         sysopt.explorers = dupstr(bufp);
2455.     } else if (src == SET_IN_SYS && match_varname(buf, "DEBUGFILES", 5)) {
2456.         /* if showdebug() has already been called (perhaps we've added
2457.            some debugpline() calls to option processing) and has found
2458.            a value for getenv("DEBUGFILES"), don't override that */
2459.         if (sysopt.env_dbgfl <= 0) {
2460.             if (sysopt.debugfiles)
2461.                 free((genericptr_t) sysopt.debugfiles);
2462.             sysopt.debugfiles = dupstr(bufp);
2463.         }
2464.     } else if (src == SET_IN_SYS && match_varname(buf, "DUMPLOGFILE", 7)) {
2465. #ifdef DUMPLOG
2466.         if (sysopt.dumplogfile)
2467.             free((genericptr_t) sysopt.dumplogfile);
2468.         sysopt.dumplogfile = dupstr(bufp);
2469. #endif
2470.     } else if (src == SET_IN_SYS && match_varname(buf, "GENERICUSERS", 12)) {
2471.         if (sysopt.genericusers)
2472.             free((genericptr_t) sysopt.genericusers);
2473.         sysopt.genericusers = dupstr(bufp);
2474.     } else if (src == SET_IN_SYS && match_varname(buf, "BONES_POOLS", 10)) {
2475.         /* max value of 10 guarantees (N % bones.pools) will be one digit
2476.            so we don't lose control of the length of bones file names */
2477.         n = atoi(bufp);
2478.         sysopt.bones_pools = (n <= 0) ? 0 : min(n, 10);
2479.         /* note: right now bones_pools==0 is the same as bones_pools==1,
2480.            but we could change that and make bones_pools==0 become an
2481.            indicator to suppress bones usage altogether */
2482.     } else if (src == SET_IN_SYS && match_varname(buf, "SUPPORT", 7)) {
2483.         if (sysopt.support)
2484.             free((genericptr_t) sysopt.support);
2485.         sysopt.support = dupstr(bufp);
2486.     } else if (src == SET_IN_SYS && match_varname(buf, "RECOVER", 7)) {
2487.         if (sysopt.recover)
2488.             free((genericptr_t) sysopt.recover);
2489.         sysopt.recover = dupstr(bufp);
2490.     } else if (src == SET_IN_SYS
2491.                && match_varname(buf, "CHECK_SAVE_UID", 14)) {
2492.         n = atoi(bufp);
2493.         sysopt.check_save_uid = n;
2494.     } else if (src == SET_IN_SYS
2495.                && match_varname(buf, "CHECK_PLNAME", 12)) {
2496.         n = atoi(bufp);
2497.         sysopt.check_plname = n;
2498.     } else if (match_varname(buf, "SEDUCE", 6)) {
2499.         n = !!atoi(bufp); /* XXX this could be tighter */
2500.         /* allow anyone to turn it off, but only sysconf to turn it on*/
2501.         if (src != SET_IN_SYS && n != 0) {
2502.             config_error_add("Illegal value in SEDUCE");
2503.             return FALSE;
2504.         }
2505.         sysopt.seduce = n;
2506.         sysopt_seduce_set(sysopt.seduce);
2507.     } else if (src == SET_IN_SYS && match_varname(buf, "MAXPLAYERS", 10)) {
2508.         n = atoi(bufp);
2509.         /* XXX to get more than 25, need to rewrite all lock code */
2510.         if (n < 0 || n > 25) {
2511.             config_error_add("Illegal value in MAXPLAYERS (maximum is 25).");
2512.             return FALSE;
2513.         }
2514.         sysopt.maxplayers = n;
2515.     } else if (src == SET_IN_SYS && match_varname(buf, "PERSMAX", 7)) {
2516.         n = atoi(bufp);
2517.         if (n < 1) {
2518.             config_error_add("Illegal value in PERSMAX (minimum is 1).");
2519.             return FALSE;
2520.         }
2521.         sysopt.persmax = n;
2522.     } else if (src == SET_IN_SYS && match_varname(buf, "PERS_IS_UID", 11)) {
2523.         n = atoi(bufp);
2524.         if (n != 0 && n != 1) {
2525.             config_error_add("Illegal value in PERS_IS_UID (must be 0 or 1).");
2526.             return FALSE;
2527.         }
2528.         sysopt.pers_is_uid = n;
2529.     } else if (src == SET_IN_SYS && match_varname(buf, "ENTRYMAX", 8)) {
2530.         n = atoi(bufp);
2531.         if (n < 10) {
2532.             config_error_add("Illegal value in ENTRYMAX (minimum is 10).");
2533.             return FALSE;
2534.         }
2535.         sysopt.entrymax = n;
2536.     } else if ((src == SET_IN_SYS) && match_varname(buf, "POINTSMIN", 9)) {
2537.         n = atoi(bufp);
2538.         if (n < 1) {
2539.             config_error_add("Illegal value in POINTSMIN (minimum is 1).");
2540.             return FALSE;
2541.         }
2542.         sysopt.pointsmin = n;
2543.     } else if (src == SET_IN_SYS
2544.                && match_varname(buf, "MAX_STATUENAME_RANK", 10)) {
2545.         n = atoi(bufp);
2546.         if (n < 1) {
2547.             config_error_add(
2548.                       "Illegal value in MAX_STATUENAME_RANK (minimum is 1).");
2549.             return FALSE;
2550.         }
2551.         sysopt.tt_oname_maxrank = n;
2552. 
2553.     /* SYSCF PANICTRACE options */
2554.     } else if (src == SET_IN_SYS
2555.                && match_varname(buf, "PANICTRACE_LIBC", 15)) {
2556.         n = atoi(bufp);
2557. #if defined(PANICTRACE) && defined(PANICTRACE_LIBC)
2558.         if (n < 0 || n > 2) {
2559.             config_error_add("Illegal value in PANICTRACE_LIBC (not 0,1,2).");
2560.             return FALSE;
2561.         }
2562. #endif
2563.         sysopt.panictrace_libc = n;
2564.     } else if (src == SET_IN_SYS
2565.                && match_varname(buf, "PANICTRACE_GDB", 14)) {
2566.         n = atoi(bufp);
2567. #if defined(PANICTRACE)
2568.         if (n < 0 || n > 2) {
2569.             config_error_add("Illegal value in PANICTRACE_GDB (not 0,1,2).");
2570.             return FALSE;
2571.         }
2572. #endif
2573.         sysopt.panictrace_gdb = n;
2574.     } else if (src == SET_IN_SYS && match_varname(buf, "GDBPATH", 7)) {
2575. #if defined(PANICTRACE) && !defined(VMS)
2576.         if (!file_exists(bufp)) {
2577.             config_error_add("File specified in GDBPATH does not exist.");
2578.             return FALSE;
2579.         }
2580. #endif
2581.         if (sysopt.gdbpath)
2582.             free((genericptr_t) sysopt.gdbpath);
2583.         sysopt.gdbpath = dupstr(bufp);
2584.     } else if (src == SET_IN_SYS && match_varname(buf, "GREPPATH", 7)) {
2585. #if defined(PANICTRACE) && !defined(VMS)
2586.         if (!file_exists(bufp)) {
2587.             config_error_add("File specified in GREPPATH does not exist.");
2588.             return FALSE;
2589.         }
2590. #endif
2591.         if (sysopt.greppath)
2592.             free((genericptr_t) sysopt.greppath);
2593.         sysopt.greppath = dupstr(bufp);
2594.     } else if (src == SET_IN_SYS
2595.                && match_varname(buf, "ACCESSIBILITY", 13)) {
2596.         n = atoi(bufp);
2597.         if (n < 0 || n > 1) {
2598.             config_error_add("Illegal value in ACCESSIBILITY (not 0,1).");
2599.             return FALSE;
2600.         }
2601.         sysopt.accessibility = n;
2602. #ifdef WIN32
2603.     } else if (src == SET_IN_SYS
2604.                 && match_varname(buf, "portable_device_paths", 8)) {
2605.         n = atoi(bufp);
2606.         if (n < 0 || n > 1) {
2607.             config_error_add("Illegal value in portable_device_paths (not 0,1).");
2608.             return FALSE;
2609.         }
2610.         sysopt.portable_device_paths = n;
2611. #endif
2612. #endif /* SYSCF */
2613. 
2614.     } else if (match_varname(buf, "BOULDER", 3)) {
2615.         (void) get_uchars(bufp, &ov_primary_syms[SYM_BOULDER + SYM_OFF_X],
2616.                           TRUE, 1, "BOULDER");
2617.     } else if (match_varname(buf, "MENUCOLOR", 9)) {
2618.         if (!add_menu_coloring(bufp))
2619.             retval = FALSE;
2620.     } else if (match_varname(buf, "HILITE_STATUS", 6)) {
2621. #ifdef STATUS_HILITES
2622.         if (!parse_status_hl1(bufp, TRUE))
2623.             retval = FALSE;
2624. #endif
2625.     } else if (match_varname(buf, "WARNINGS", 5)) {
2626.         (void) get_uchars(bufp, translate, FALSE, WARNCOUNT,
2627.                           "WARNINGS");
2628.         assign_warnings(translate);
2629.     } else if (match_varname(buf, "ROGUESYMBOLS", 4)) {
2630.         if (!parsesymbols(bufp, ROGUESET)) {
2631.             config_error_add("Error in ROGUESYMBOLS definition '%s'", bufp);
2632.             retval = FALSE;
2633.         }
2634.         switch_symbols(TRUE);
2635.     } else if (match_varname(buf, "SYMBOLS", 4)) {
2636.         if (!parsesymbols(bufp, PRIMARY)) {
2637.             config_error_add("Error in SYMBOLS definition '%s'", bufp);
2638.             retval = FALSE;
2639.         }
2640.         switch_symbols(TRUE);
2641.     } else if (match_varname(buf, "WIZKIT", 6)) {
2642.         (void) strncpy(wizkit, bufp, WIZKIT_MAX - 1);
2643. #ifdef AMIGA
2644.     } else if (match_varname(buf, "FONT", 4)) {
2645.         char *t;
2646. 
2647.         if (t = strchr(buf + 5, ':')) {
2648.             *t = 0;
2649.             amii_set_text_font(buf + 5, atoi(t + 1));
2650.             *t = ':';
2651.         }
2652.     } else if (match_varname(buf, "PATH", 4)) {
2653.         (void) strncpy(PATH, bufp, PATHLEN - 1);
2654.     } else if (match_varname(buf, "DEPTH", 5)) {
2655.         extern int amii_numcolors;
2656.         int val = atoi(bufp);
2657. 
2658.         amii_numcolors = 1L << min(DEPTH, val);
2659. #ifdef SYSFLAGS
2660.     } else if (match_varname(buf, "DRIPENS", 7)) {
2661.         int i, val;
2662.         char *t;
2663. 
2664.         for (i = 0, t = strtok(bufp, ",/"); t != (char *) 0;
2665.              i < 20 && (t = strtok((char *) 0, ",/")), ++i) {
2666.             sscanf(t, "%d", &val);
2667.             sysflags.amii_dripens[i] = val;
2668.         }
2669. #endif
2670.     } else if (match_varname(buf, "SCREENMODE", 10)) {
2671.         extern long amii_scrnmode;
2672. 
2673.         if (!stricmp(bufp, "req"))
2674.             amii_scrnmode = 0xffffffff; /* Requester */
2675.         else if (sscanf(bufp, "%x", &amii_scrnmode) != 1)
2676.             amii_scrnmode = 0;
2677.     } else if (match_varname(buf, "MSGPENS", 7)) {
2678.         extern int amii_msgAPen, amii_msgBPen;
2679.         char *t = strtok(bufp, ",/");
2680. 
2681.         if (t) {
2682.             sscanf(t, "%d", &amii_msgAPen);
2683.             if (t = strtok((char *) 0, ",/"))
2684.                 sscanf(t, "%d", &amii_msgBPen);
2685.         }
2686.     } else if (match_varname(buf, "TEXTPENS", 8)) {
2687.         extern int amii_textAPen, amii_textBPen;
2688.         char *t = strtok(bufp, ",/");
2689. 
2690.         if (t) {
2691.             sscanf(t, "%d", &amii_textAPen);
2692.             if (t = strtok((char *) 0, ",/"))
2693.                 sscanf(t, "%d", &amii_textBPen);
2694.         }
2695.     } else if (match_varname(buf, "MENUPENS", 8)) {
2696.         extern int amii_menuAPen, amii_menuBPen;
2697.         char *t = strtok(bufp, ",/");
2698. 
2699.         if (t) {
2700.             sscanf(t, "%d", &amii_menuAPen);
2701.             if (t = strtok((char *) 0, ",/"))
2702.                 sscanf(t, "%d", &amii_menuBPen);
2703.         }
2704.     } else if (match_varname(buf, "STATUSPENS", 10)) {
2705.         extern int amii_statAPen, amii_statBPen;
2706.         char *t = strtok(bufp, ",/");
2707. 
2708.         if (t) {
2709.             sscanf(t, "%d", &amii_statAPen);
2710.             if (t = strtok((char *) 0, ",/"))
2711.                 sscanf(t, "%d", &amii_statBPen);
2712.         }
2713.     } else if (match_varname(buf, "OTHERPENS", 9)) {
2714.         extern int amii_otherAPen, amii_otherBPen;
2715.         char *t = strtok(bufp, ",/");
2716. 
2717.         if (t) {
2718.             sscanf(t, "%d", &amii_otherAPen);
2719.             if (t = strtok((char *) 0, ",/"))
2720.                 sscanf(t, "%d", &amii_otherBPen);
2721.         }
2722.     } else if (match_varname(buf, "PENS", 4)) {
2723.         extern unsigned short amii_init_map[AMII_MAXCOLORS];
2724.         int i;
2725.         char *t;
2726. 
2727.         for (i = 0, t = strtok(bufp, ",/");
2728.              i < AMII_MAXCOLORS && t != (char *) 0;
2729.              t = strtok((char *) 0, ",/"), ++i) {
2730.             sscanf(t, "%hx", &amii_init_map[i]);
2731.         }
2732.         amii_setpens(amii_numcolors = i);
2733.     } else if (match_varname(buf, "FGPENS", 6)) {
2734.         extern int foreg[AMII_MAXCOLORS];
2735.         int i;
2736.         char *t;
2737. 
2738.         for (i = 0, t = strtok(bufp, ",/");
2739.              i < AMII_MAXCOLORS && t != (char *) 0;
2740.              t = strtok((char *) 0, ",/"), ++i) {
2741.             sscanf(t, "%d", &foreg[i]);
2742.         }
2743.     } else if (match_varname(buf, "BGPENS", 6)) {
2744.         extern int backg[AMII_MAXCOLORS];
2745.         int i;
2746.         char *t;
2747. 
2748.         for (i = 0, t = strtok(bufp, ",/");
2749.              i < AMII_MAXCOLORS && t != (char *) 0;
2750.              t = strtok((char *) 0, ",/"), ++i) {
2751.             sscanf(t, "%d", &backg[i]);
2752.         }
2753. #endif /*AMIGA*/
2754. #ifdef USER_SOUNDS
2755.     } else if (match_varname(buf, "SOUNDDIR", 8)) {
2756.         sounddir = dupstr(bufp);
2757.     } else if (match_varname(buf, "SOUND", 5)) {
2758.         add_sound_mapping(bufp);
2759. #endif
2760.     } else if (match_varname(buf, "QT_TILEWIDTH", 12)) {
2761. #ifdef QT_GRAPHICS
2762.         extern char *qt_tilewidth;
2763. 
2764.         if (qt_tilewidth == NULL)
2765.             qt_tilewidth = dupstr(bufp);
2766. #endif
2767.     } else if (match_varname(buf, "QT_TILEHEIGHT", 13)) {
2768. #ifdef QT_GRAPHICS
2769.         extern char *qt_tileheight;
2770. 
2771.         if (qt_tileheight == NULL)
2772.             qt_tileheight = dupstr(bufp);
2773. #endif
2774.     } else if (match_varname(buf, "QT_FONTSIZE", 11)) {
2775. #ifdef QT_GRAPHICS
2776.         extern char *qt_fontsize;
2777. 
2778.         if (qt_fontsize == NULL)
2779.             qt_fontsize = dupstr(bufp);
2780. #endif
2781.     } else if (match_varname(buf, "QT_COMPACT", 10)) {
2782. #ifdef QT_GRAPHICS
2783.         extern int qt_compact_mode;
2784. 
2785.         qt_compact_mode = atoi(bufp);
2786. #endif
2787.     } else {
2788.         config_error_add("Unknown config statement");
2789.         return FALSE;
2790.     }
2791.     return retval;
2792. }
2793. 
2794. #ifdef USER_SOUNDS
2795. boolean
2796. can_read_file(filename)
2797. const char *filename;
2798. {
2799.     return (boolean) (access(filename, 4) == 0);
2800. }
2801. #endif /* USER_SOUNDS */
2802. 
2803. struct _config_error_frame {
2804.     int line_num;
2805.     int num_errors;
2806.     boolean origline_shown;
2807.     boolean fromfile;
2808.     boolean secure;
2809.     char origline[4 * BUFSZ];
2810.     char source[BUFSZ];
2811.     struct _config_error_frame *next;
2812. };
2813. 
2814. static struct _config_error_frame *config_error_data = 0;
2815. 
2816. void
2817. config_error_init(from_file, sourcename, secure)
2818. boolean from_file;
2819. const char *sourcename;
2820. boolean secure;
2821. {
2822.     struct _config_error_frame *tmp = (struct _config_error_frame *)
2823.         alloc(sizeof (struct _config_error_frame));
2824. 
2825.     tmp->line_num = 0;
2826.     tmp->num_errors = 0;
2827.     tmp->origline_shown = FALSE;
2828.     tmp->fromfile = from_file;
2829.     tmp->secure = secure;
2830.     tmp->origline[0] = '\0';
2831.     if (sourcename && sourcename[0]) {
2832.         (void) strncpy(tmp->source, sourcename, sizeof (tmp->source) - 1);
2833.         tmp->source[sizeof (tmp->source) - 1] = '\0';
2834.     } else
2835.         tmp->source[0] = '\0';
2836. 
2837.     tmp->next = config_error_data;
2838.     config_error_data = tmp;
2839. }
2840. 
2841. STATIC_OVL boolean
2842. config_error_nextline(line)
2843. const char *line;
2844. {
2845.     struct _config_error_frame *ced = config_error_data;
2846. 
2847.     if (!ced)
2848.         return FALSE;
2849. 
2850.     if (ced->num_errors && ced->secure)
2851.         return FALSE;
2852. 
2853.     ced->line_num++;
2854.     ced->origline_shown = FALSE;
2855.     if (line && line[0]) {
2856.         (void) strncpy(ced->origline, line, sizeof (ced->origline) - 1);
2857.         ced->origline[sizeof (ced->origline) - 1] = '\0';
2858.     } else
2859.         ced->origline[0] = '\0';
2860. 
2861.     return TRUE;
2862. }
2863. 
2864. /* varargs 'config_error_add()' moved to pline.c */
2865. void
2866. config_erradd(buf)
2867. const char *buf;
2868. {
2869.     char lineno[QBUFSZ];
2870. 
2871.     if (!buf || !*buf)
2872.         buf = "Unknown error";
2873. 
2874.     if (!config_error_data) {
2875.         /* either very early, where pline() will use raw_print(), or
2876.            player gave bad value when prompted by interactive 'O' command */
2877.         pline("%s%s.", !iflags.window_inited ? "config_error_add: " : "", buf);
2878.         wait_synch();
2879.         return;
2880.     }
2881. 
2882.     config_error_data->num_errors++;
2883.     if (!config_error_data->origline_shown && !config_error_data->secure) {
2884.         pline("\n%s", config_error_data->origline);
2885.         config_error_data->origline_shown = TRUE;
2886.     }
2887.     if (config_error_data->line_num > 0 && !config_error_data->secure) {
2888.         Sprintf(lineno, "Line %d: ", config_error_data->line_num);
2889.     } else
2890.         lineno[0] = '\0';
2891. 
2892.     pline("%s %s%s.", config_error_data->secure ? "Error:" : " *",
2893.           lineno, buf);
2894. }
2895. 
2896. int
2897. config_error_done()
2898. {
2899.     int n;
2900.     struct _config_error_frame *tmp = config_error_data;
2901. 
2902.     if (!config_error_data)
2903.         return 0;
2904.     n = config_error_data->num_errors;
2905.     if (n) {
2906.         pline("\n%d error%s in %s.\n", n,
2907.                    (n > 1) ? "s" : "",
2908.                    *config_error_data->source
2909.               ? config_error_data->source : configfile);
2910.         wait_synch();
2911.     }
2912.     config_error_data = tmp->next;
2913.     free(tmp);
2914.     return n;
2915. }
2916. 
2917. boolean
2918. read_config_file(filename, src)
2919. const char *filename;
2920. int src;
2921. {
2922.     FILE *fp;
2923.     boolean rv = TRUE;
2924. 
2925.     if (!(fp = fopen_config_file(filename, src)))
2926.         return FALSE;
2927. 
2928.     /* begin detection of duplicate configfile options */
2929.     set_duplicate_opt_detection(1);
2930.     free_config_sections();
2931.     iflags.parse_config_file_src = src;
2932. 
2933.     rv = parse_conf_file(fp, parse_config_line);
2934.     (void) fclose(fp);
2935. 
2936.     free_config_sections();
2937.     /* turn off detection of duplicate configfile options */
2938.     set_duplicate_opt_detection(0);
2939.     return rv;
2940. }
2941. 
2942. STATIC_OVL FILE *
2943. fopen_wizkit_file()
2944. {
2945.     FILE *fp;
2946. #if defined(VMS) || defined(UNIX)
2947.     char tmp_wizkit[BUFSZ];
2948. #endif
2949.     char *envp;
2950. 
2951.     envp = nh_getenv("WIZKIT");
2952.     if (envp && *envp)
2953.         (void) strncpy(wizkit, envp, WIZKIT_MAX - 1);
2954.     if (!wizkit[0])
2955.         return (FILE *) 0;
2956. 
2957. #ifdef UNIX
2958.     if (access(wizkit, 4) == -1) {
2959.         /* 4 is R_OK on newer systems */
2960.         /* nasty sneaky attempt to read file through
2961.          * NetHack's setuid permissions -- this is a
2962.          * place a file name may be wholly under the player's
2963.          * control
2964.          */
2965.         raw_printf("Access to %s denied (%d).", wizkit, errno);
2966.         wait_synch();
2967.         /* fall through to standard names */
2968.     } else
2969. #endif
2970.         if ((fp = fopenp(wizkit, "r")) != (FILE *) 0) {
2971.         return fp;
2972. #if defined(UNIX) || defined(VMS)
2973.     } else {
2974.         /* access() above probably caught most problems for UNIX */
2975.         raw_printf("Couldn't open requested config file %s (%d).", wizkit,
2976.                    errno);
2977.         wait_synch();
2978. #endif
2979.     }
2980. 
2981. #if defined(MICRO) || defined(MAC) || defined(__BEOS__) || defined(WIN32)
2982.     if ((fp = fopenp(fqname(wizkit, CONFIGPREFIX, 0), "r")) != (FILE *) 0)
2983.         return fp;
2984. #else
2985. #ifdef VMS
2986.     envp = nh_getenv("HOME");
2987.     if (envp)
2988.         Sprintf(tmp_wizkit, "%s%s", envp, wizkit);
2989.     else
2990.         Sprintf(tmp_wizkit, "%s%s", "sys$login:", wizkit);
2991.     if ((fp = fopenp(tmp_wizkit, "r")) != (FILE *) 0)
2992.         return fp;
2993. #else /* should be only UNIX left */
2994.     envp = nh_getenv("HOME");
2995.     if (envp)
2996.         Sprintf(tmp_wizkit, "%s/%s", envp, wizkit);
2997.     else
2998.         Strcpy(tmp_wizkit, wizkit);
2999.     if ((fp = fopenp(tmp_wizkit, "r")) != (FILE *) 0)
3000.         return fp;
3001.     else if (errno != ENOENT) {
3002.         /* e.g., problems when setuid NetHack can't search home
3003.          * directory restricted to user */
3004.         raw_printf("Couldn't open default wizkit file %s (%d).", tmp_wizkit,
3005.                    errno);
3006.         wait_synch();
3007.     }
3008. #endif
3009. #endif
3010.     return (FILE *) 0;
3011. }
3012. 
3013. /* add to hero's inventory if there's room, otherwise put item on floor */
3014. STATIC_DCL void
3015. wizkit_addinv(obj)
3016. struct obj *obj;
3017. {
3018.     if (!obj || obj == &zeroobj)
3019.         return;
3020. 
3021.     /* subset of starting inventory pre-ID */
3022.     obj->dknown = 1;
3023.     if (Role_if(PM_PRIEST))
3024.         obj->bknown = 1; /* ok to bypass set_bknown() */
3025.     /* same criteria as lift_object()'s check for available inventory slot */
3026.     if (obj->oclass != COIN_CLASS && inv_cnt(FALSE) >= 52
3027.         && !merge_choice(invent, obj)) {
3028.         /* inventory overflow; can't just place & stack object since
3029.            hero isn't in position yet, so schedule for arrival later */
3030.         add_to_migration(obj);
3031.         obj->ox = 0; /* index of main dungeon */
3032.         obj->oy = 1; /* starting level number */
3033.         obj->owornmask =
3034.             (long) (MIGR_WITH_HERO | MIGR_NOBREAK | MIGR_NOSCATTER);
3035.     } else {
3036.         (void) addinv(obj);
3037.     }
3038. }
3039. 
3040. 
3041. boolean
3042. proc_wizkit_line(buf)
3043. char *buf;
3044. {
3045.     struct obj *otmp;
3046. 
3047.     if (strlen(buf) >= BUFSZ)
3048.         buf[BUFSZ - 1] = '\0';
3049.     otmp = readobjnam(buf, (struct obj *) 0);
3050. 
3051.     if (otmp) {
3052.         if (otmp != &zeroobj)
3053.             wizkit_addinv(otmp);
3054.     } else {
3055.         /* .60 limits output line width to 79 chars */
3056.         config_error_add("Bad wizkit item: \"%.60s\"", buf);
3057.         return FALSE;
3058.     }
3059.     return TRUE;
3060. }
3061. 
3062. void
3063. read_wizkit()
3064. {
3065.     FILE *fp;
3066. 
3067.     if (!wizard || !(fp = fopen_wizkit_file()))
3068.         return;
3069. 
3070.     program_state.wizkit_wishing = 1;
3071.     config_error_init(TRUE, "WIZKIT", FALSE);
3072. 
3073.     parse_conf_file(fp, proc_wizkit_line);
3074.     (void) fclose(fp);
3075. 
3076.     config_error_done();
3077.     program_state.wizkit_wishing = 0;
3078. 
3079.     return;
3080. }
3081. 
3082. /* parse_conf_file
3083.  *
3084.  * Read from file fp, handling comments, empty lines, config sections,
3085.  * CHOOSE, and line continuation, calling proc for every valid line.
3086.  *
3087.  * Continued lines are merged together with one space in between.
3088.  */
3089. STATIC_OVL boolean
3090. parse_conf_file(fp, proc)
3091. FILE *fp;
3092. boolean FDECL((*proc), (char *));
3093. {
3094.     char inbuf[4 * BUFSZ];
3095.     boolean rv = TRUE; /* assume successful parse */
3096.     char *ep;
3097.     boolean skip = FALSE, morelines = FALSE;
3098.     char *buf = (char *) 0;
3099.     size_t inbufsz = sizeof inbuf;
3100. 
3101.     free_config_sections();
3102. 
3103.     while (fgets(inbuf, (int) inbufsz, fp)) {
3104.         ep = index(inbuf, '\n');
3105.         if (skip) { /* in case previous line was too long */
3106.             if (ep)
3107.                 skip = FALSE; /* found newline; next line is normal */
3108.         } else {
3109.             if (!ep) {  /* newline missing */
3110.                 if (strlen(inbuf) < (inbufsz - 2)) {
3111.                     /* likely the last line of file is just
3112.                        missing a newline; process it anyway  */
3113.                     ep = eos(inbuf);
3114.                 } else {
3115.                     config_error_add("Line too long, skipping");
3116.                     skip = TRUE; /* discard next fgets */
3117.                 }
3118.             } else {
3119.                 *ep = '\0'; /* remove newline */
3120.             }
3121.             if (ep) {
3122.                 char *tmpbuf = (char *) 0;
3123.                 int len;
3124.                 boolean ignoreline = FALSE;
3125.                 boolean oldline = FALSE;
3126. 
3127.                 /* line continuation (trailing '\') */
3128.                 morelines = (--ep >= inbuf && *ep == '\\');
3129.                 if (morelines)
3130.                     *ep = '\0';
3131. 
3132.                 /* trim off spaces at end of line */
3133.                 while (ep >= inbuf
3134.                        && (*ep == ' ' || *ep == '\t' || *ep == '\r'))
3135.                     *ep-- = '\0';
3136. 
3137.                 if (!config_error_nextline(inbuf)) {
3138.                     rv = FALSE;
3139.                     if (buf)
3140.                         free(buf), buf = (char *) 0;
3141.                     break;
3142.                 }
3143. 
3144.                 ep = inbuf;
3145.                 while (*ep == ' ' || *ep == '\t')
3146.                     ++ep;
3147. 
3148.                 /* ignore empty lines and full-line comment lines */
3149.                 if (!*ep || *ep == '#')
3150.                     ignoreline = TRUE;
3151. 
3152.                 if (buf)
3153.                     oldline = TRUE;
3154. 
3155.                 /* merge now read line with previous ones, if necessary */
3156.                 if (!ignoreline) {
3157.                     len = (int) strlen(ep) + 1; /* +1: final '\0' */
3158.                     if (buf)
3159.                         len += (int) strlen(buf) + 1; /* +1: space */
3160.                     tmpbuf = (char *) alloc(len);
3161.                     *tmpbuf = '\0';
3162.                     if (buf) {
3163.                         Strcat(strcpy(tmpbuf, buf), " ");
3164.                         free(buf);
3165.                     }
3166.                     buf = strcat(tmpbuf, ep);
3167.                     if (strlen(buf) >= sizeof inbuf)
3168.                         buf[sizeof inbuf - 1] = '\0';
3169.                 }
3170. 
3171.                 if (morelines || (ignoreline && !oldline))
3172.                     continue;
3173. 
3174.                 if (handle_config_section(buf)) {
3175.                     free(buf);
3176.                     buf = (char *) 0;
3177.                     continue;
3178.                 }
3179. 
3180.                 /* from here onwards, we'll handle buf only */
3181. 
3182.                 if (match_varname(buf, "CHOOSE", 6)) {
3183.                     char *section;
3184.                     char *bufp = find_optparam(buf);
3185. 
3186.                     if (!bufp) {
3187.                         config_error_add(
3188.                                     "Format is CHOOSE=section1,section2,...");
3189.                         rv = FALSE;
3190.                         free(buf);
3191.                         buf = (char *) 0;
3192.                         continue;
3193.                     }
3194.                     bufp++;
3195.                     if (config_section_chosen)
3196.                         free(config_section_chosen), config_section_chosen = 0;
3197.                     section = choose_random_part(bufp, ',');
3198.                     if (section) {
3199.                         config_section_chosen = dupstr(section);
3200.                     } else {
3201.                         config_error_add("No config section to choose");
3202.                         rv = FALSE;
3203.                     }
3204.                     free(buf);
3205.                     buf = (char *) 0;
3206.                     continue;
3207.                 }
3208. 
3209.                 if (!proc(buf))
3210.                     rv = FALSE;
3211. 
3212.                 free(buf);
3213.                 buf = (char *) 0;
3214.             }
3215.         }
3216.     }
3217. 
3218.     if (buf)
3219.         free(buf);
3220. 
3221.     free_config_sections();
3222.     return rv;
3223. }
3224. 
3225. extern struct symsetentry *symset_list;  /* options.c */
3226. extern const char *known_handling[];     /* drawing.c */
3227. extern const char *known_restrictions[]; /* drawing.c */
3228. static int symset_count = 0;             /* for pick-list building only */
3229. static boolean chosen_symset_start = FALSE, chosen_symset_end = FALSE;
3230. static int symset_which_set = 0;
3231. 
3232. STATIC_OVL
3233. FILE *
3234. fopen_sym_file()
3235. {
3236.     FILE *fp;
3237. 
3238.     fp = fopen_datafile(SYMBOLS, "r",
3239. #ifdef WIN32
3240.                             SYSCONFPREFIX
3241. #else
3242.                             HACKPREFIX
3243. #endif
3244.                        );
3245. 
3246.     return fp;
3247. }
3248. 
3249. /*
3250.  * Returns 1 if the chose symset was found and loaded.
3251.  *         0 if it wasn't found in the sym file or other problem.
3252.  */
3253. int
3254. read_sym_file(which_set)
3255. int which_set;
3256. {
3257.     FILE *fp;
3258. 
3259.     symset[which_set].explicitly = FALSE;
3260.     if (!(fp = fopen_sym_file()))
3261.         return 0;
3262. 
3263.     symset[which_set].explicitly = TRUE;
3264.     symset_count = 0;
3265.     chosen_symset_start = chosen_symset_end = FALSE;
3266.     symset_which_set = which_set;
3267. 
3268.     config_error_init(TRUE, "symbols", FALSE);
3269. 
3270.     parse_conf_file(fp, proc_symset_line);
3271.     (void) fclose(fp);
3272. 
3273.     if (!chosen_symset_start && !chosen_symset_end) {
3274.         /* name caller put in symset[which_set].name was not found;
3275.            if it looks like "Default symbols", null it out and return
3276.            success to use the default; otherwise, return failure */
3277.         if (symset[which_set].name
3278.             && (fuzzymatch(symset[which_set].name, "Default symbols",
3279.                            " -_", TRUE)
3280.                 || !strcmpi(symset[which_set].name, "default")))
3281.             clear_symsetentry(which_set, TRUE);
3282.         config_error_done();
3283. 
3284.         /* If name was defined, it was invalid... Then we're loading fallback */
3285.         if (symset[which_set].name) {
3286.             symset[which_set].explicitly = FALSE;
3287.             return 0;
3288.         }
3289. 
3290.         return 1;
3291.     }
3292.     if (!chosen_symset_end)
3293.         config_error_add("Missing finish for symset \"%s\"",
3294.                          symset[which_set].name ? symset[which_set].name
3295.                                                 : "unknown");
3296.     config_error_done();
3297.     return 1;
3298. }
3299. 
3300. boolean
3301. proc_symset_line(buf)
3302. char *buf;
3303. {
3304.     return !((boolean) parse_sym_line(buf, symset_which_set));
3305. }
3306. 
3307. /* returns 0 on error */
3308. int
3309. parse_sym_line(buf, which_set)
3310. char *buf;
3311. int which_set;
3312. {
3313.     int val, i;
3314.     struct symparse *symp;
3315.     char *bufp, *commentp, *altp;
3316. 
3317.     if (strlen(buf) >= BUFSZ)
3318.         buf[BUFSZ - 1] = '\0';
3319.     /* convert each instance of whitespace (tabs, consecutive spaces)
3320.        into a single space; leading and trailing spaces are stripped */
3321.     mungspaces(buf);
3322. 
3323.     /* remove trailing comment, if any (this isn't strictly needed for
3324.        individual symbols, and it won't matter if "X#comment" without
3325.        separating space slips through; for handling or set description,
3326.        symbol set creator is responsible for preceding '#' with a space
3327.        and that comment itself doesn't contain " #") */
3328.     if ((commentp = rindex(buf, '#')) != 0 && commentp[-1] == ' ')
3329.         commentp[-1] = '\0';
3330. 
3331.     /* find the '=' or ':' */
3332.     bufp = index(buf, '=');
3333.     altp = index(buf, ':');
3334.     if (!bufp || (altp && altp < bufp))
3335.         bufp = altp;
3336.     if (!bufp) {
3337.         if (strncmpi(buf, "finish", 6) == 0) {
3338.             /* end current graphics set */
3339.             if (chosen_symset_start)
3340.                 chosen_symset_end = TRUE;
3341.             chosen_symset_start = FALSE;
3342.             return 1;
3343.         }
3344.         config_error_add("No \"finish\"");
3345.         return 0;
3346.     }
3347.     /* skip '=' and space which follows, if any */
3348.     ++bufp;
3349.     if (*bufp == ' ')
3350.         ++bufp;
3351. 
3352.     symp = match_sym(buf);
3353.     if (!symp) {
3354.         config_error_add("Unknown sym keyword");
3355.         return 0;
3356.     }
3357. 
3358.     if (!symset[which_set].name) {
3359.         /* A null symset name indicates that we're just
3360.            building a pick-list of possible symset
3361.            values from the file, so only do that */
3362.         if (symp->range == SYM_CONTROL) {
3363.             struct symsetentry *tmpsp, *lastsp;
3364. 
3365.             for (lastsp = symset_list; lastsp; lastsp = lastsp->next)
3366.                 if (!lastsp->next)
3367.                     break;
3368.             switch (symp->idx) {
3369.             case 0:
3370.                 tmpsp = (struct symsetentry *) alloc(sizeof *tmpsp);
3371.                 tmpsp->next = (struct symsetentry *) 0;
3372.                 if (!lastsp)
3373.                     symset_list = tmpsp;
3374.                 else
3375.                     lastsp->next = tmpsp;
3376.                 tmpsp->idx = symset_count++;
3377.                 tmpsp->name = dupstr(bufp);
3378.                 tmpsp->desc = (char *) 0;
3379.                 tmpsp->handling = H_UNK;
3380.                 /* initialize restriction bits */
3381.                 tmpsp->nocolor = 0;
3382.                 tmpsp->primary = 0;
3383.                 tmpsp->rogue = 0;
3384.                 break;
3385.             case 2:
3386.                 /* handler type identified */
3387.                 tmpsp = lastsp; /* most recent symset */
3388.                 for (i = 0; known_handling[i]; ++i)
3389.                     if (!strcmpi(known_handling[i], bufp)) {
3390.                         tmpsp->handling = i;
3391.                         break; /* for loop */
3392.                     }
3393.                 break;
3394.             case 3:
3395.                 /* description:something */
3396.                 tmpsp = lastsp; /* most recent symset */
3397.                 if (tmpsp && !tmpsp->desc)
3398.                     tmpsp->desc = dupstr(bufp);
3399.                 break;
3400.             case 5:
3401.                 /* restrictions: xxxx*/
3402.                 tmpsp = lastsp; /* most recent symset */
3403.                 for (i = 0; known_restrictions[i]; ++i) {
3404.                     if (!strcmpi(known_restrictions[i], bufp)) {
3405.                         switch (i) {
3406.                         case 0:
3407.                             tmpsp->primary = 1;
3408.                             break;
3409.                         case 1:
3410.                             tmpsp->rogue = 1;
3411.                             break;
3412.                         }
3413.                         break; /* while loop */
3414.                     }
3415.                 }
3416.                 break;
3417.             }
3418.         }
3419.         return 1;
3420.     }
3421.     if (symp->range) {
3422.         if (symp->range == SYM_CONTROL) {
3423.             switch (symp->idx) {
3424.             case 0:
3425.                 /* start of symset */
3426.                 if (!strcmpi(bufp, symset[which_set].name)) {
3427.                     /* matches desired one */
3428.                     chosen_symset_start = TRUE;
3429.                     /* these init_*() functions clear symset fields too */
3430.                     if (which_set == ROGUESET)
3431.                         init_rogue_symbols();
3432.                     else if (which_set == PRIMARY)
3433.                         init_primary_symbols();
3434.                 }
3435.                 break;
3436.             case 1:
3437.                 /* finish symset */
3438.                 if (chosen_symset_start)
3439.                     chosen_symset_end = TRUE;
3440.                 chosen_symset_start = FALSE;
3441.                 break;
3442.             case 2:
3443.                 /* handler type identified */
3444.                 if (chosen_symset_start)
3445.                     set_symhandling(bufp, which_set);
3446.                 break;
3447.             /* case 3: (description) is ignored here */
3448.             case 4: /* color:off */
3449.                 if (chosen_symset_start) {
3450.                     if (bufp) {
3451.                         if (!strcmpi(bufp, "true") || !strcmpi(bufp, "yes")
3452.                             || !strcmpi(bufp, "on"))
3453.                             symset[which_set].nocolor = 0;
3454.                         else if (!strcmpi(bufp, "false")
3455.                                  || !strcmpi(bufp, "no")
3456.                                  || !strcmpi(bufp, "off"))
3457.                             symset[which_set].nocolor = 1;
3458.                     }
3459.                 }
3460.                 break;
3461.             case 5: /* restrictions: xxxx*/
3462.                 if (chosen_symset_start) {
3463.                     int n = 0;
3464. 
3465.                     while (known_restrictions[n]) {
3466.                         if (!strcmpi(known_restrictions[n], bufp)) {
3467.                             switch (n) {
3468.                             case 0:
3469.                                 symset[which_set].primary = 1;
3470.                                 break;
3471.                             case 1:
3472.                                 symset[which_set].rogue = 1;
3473.                                 break;
3474.                             }
3475.                             break; /* while loop */
3476.                         }
3477.                         n++;
3478.                     }
3479.                 }
3480.                 break;
3481.             }
3482.         } else { /* !SYM_CONTROL */
3483.             val = sym_val(bufp);
3484.             if (chosen_symset_start) {
3485.                 if (which_set == PRIMARY) {
3486.                     update_primary_symset(symp, val);
3487.                 } else if (which_set == ROGUESET) {
3488.                     update_rogue_symset(symp, val);
3489.                 }
3490.             }
3491.         }
3492.     }
3493.     return 1;
3494. }
3495. 
3496. STATIC_OVL void
3497. set_symhandling(handling, which_set)
3498. char *handling;
3499. int which_set;
3500. {
3501.     int i = 0;
3502. 
3503.     symset[which_set].handling = H_UNK;
3504.     while (known_handling[i]) {
3505.         if (!strcmpi(known_handling[i], handling)) {
3506.             symset[which_set].handling = i;
3507.             return;
3508.         }
3509.         i++;
3510.     }
3511. }
3512. 
3513. /* ----------  END CONFIG FILE HANDLING ----------- */
3514. 
3515. /* ----------  BEGIN SCOREBOARD CREATION ----------- */
3516. 
3517. #ifdef OS2_CODEVIEW
3518. #define UNUSED_if_not_OS2_CODEVIEW /*empty*/
3519. #else
3520. #define UNUSED_if_not_OS2_CODEVIEW UNUSED
3521. #endif
3522. 
3523. /* verify that we can write to scoreboard file; if not, try to create one */
3524. /*ARGUSED*/
3525. void
3526. check_recordfile(dir)
3527. const char *dir UNUSED_if_not_OS2_CODEVIEW;
3528. {
3529. #if defined(PRAGMA_UNUSED) && !defined(OS2_CODEVIEW)
3530. #pragma unused(dir)
3531. #endif
3532.     const char *fq_record;
3533.     int fd;
3534. 
3535. #if defined(UNIX) || defined(VMS)
3536.     fq_record = fqname(RECORD, SCOREPREFIX, 0);
3537.     fd = open(fq_record, O_RDWR, 0);
3538.     if (fd >= 0) {
3539. #ifdef VMS /* must be stream-lf to use UPDATE_RECORD_IN_PLACE */
3540.         if (!file_is_stmlf(fd)) {
3541.             raw_printf(
3542.                    "Warning: scoreboard file '%s' is not in stream_lf format",
3543.                        fq_record);
3544.             wait_synch();
3545.         }
3546. #endif
3547.         (void) nhclose(fd); /* RECORD is accessible */
3548.     } else if ((fd = open(fq_record, O_CREAT | O_RDWR, FCMASK)) >= 0) {
3549.         (void) nhclose(fd); /* RECORD newly created */
3550. #if defined(VMS) && !defined(SECURE)
3551.         /* Re-protect RECORD with world:read+write+execute+delete access. */
3552.         (void) chmod(fq_record, FCMASK | 007);
3553. #endif /* VMS && !SECURE */
3554.     } else {
3555.         raw_printf("Warning: cannot write scoreboard file '%s'", fq_record);
3556.         wait_synch();
3557.     }
3558. #endif /* !UNIX && !VMS */
3559. #if defined(MICRO) || defined(WIN32)
3560.     char tmp[PATHLEN];
3561. 
3562. #ifdef OS2_CODEVIEW /* explicit path on opening for OS/2 */
3563.     /* how does this work when there isn't an explicit path or fopenp
3564.      * for later access to the file via fopen_datafile? ? */
3565.     (void) strncpy(tmp, dir, PATHLEN - 1);
3566.     tmp[PATHLEN - 1] = '\0';
3567.     if ((strlen(tmp) + 1 + strlen(RECORD)) < (PATHLEN - 1)) {
3568.         append_slash(tmp);
3569.         Strcat(tmp, RECORD);
3570.     }
3571.     fq_record = tmp;
3572. #else
3573.     Strcpy(tmp, RECORD);
3574.     fq_record = fqname(RECORD, SCOREPREFIX, 0);
3575. #endif
3576. #ifdef WIN32
3577.     /* If dir is NULL it indicates create but
3578.        only if it doesn't already exist */
3579.     if (!dir) {
3580.         char buf[BUFSZ];
3581. 
3582.         buf[0] = '\0';
3583.         fd = open(fq_record, O_RDWR);
3584.         if (!(fd == -1 && errno == ENOENT)) {
3585.             if (fd >= 0) {
3586.                 (void) nhclose(fd);
3587.             } else {
3588.                 /* explanation for failure other than missing file */
3589.                 Sprintf(buf, "error   \"%s\", (errno %d).",
3590.                         fq_record, errno);
3591.                 paniclog("scorefile", buf);
3592.             }
3593.             return;
3594.         }
3595.         Sprintf(buf, "missing \"%s\", creating new scorefile.",
3596.                 fq_record);
3597.         paniclog("scorefile", buf);
3598.     }
3599. #endif
3600. 
3601.     if ((fd = open(fq_record, O_RDWR)) < 0) {
3602.         /* try to create empty 'record' */
3603. #if defined(AZTEC_C) || defined(_DCC) \
3604.     || (defined(__GNUC__) && defined(__AMIGA__))
3605.         /* Aztec doesn't use the third argument */
3606.         /* DICE doesn't like it */
3607.         fd = open(fq_record, O_CREAT | O_RDWR);
3608. #else
3609.         fd = open(fq_record, O_CREAT | O_RDWR, S_IREAD | S_IWRITE);
3610. #endif
3611.         if (fd <= 0) {
3612.             raw_printf("Warning: cannot write record '%s'", tmp);
3613.             wait_synch();
3614.         } else {
3615.             (void) nhclose(fd);
3616.         }
3617.     } else {
3618.         /* open succeeded => 'record' exists */
3619.         (void) nhclose(fd);
3620.     }
3621. #else /* MICRO || WIN32*/
3622. 
3623. #ifdef MAC
3624.     /* Create the "record" file, if necessary */
3625.     fq_record = fqname(RECORD, SCOREPREFIX, 0);
3626.     fd = macopen(fq_record, O_RDWR | O_CREAT, TEXT_TYPE);
3627.     if (fd != -1)
3628.         macclose(fd);
3629. #endif /* MAC */
3630. 
3631. #endif /* MICRO || WIN32*/
3632. }
3633. 
3634. /* ----------  END SCOREBOARD CREATION ----------- */
3635. 
3636. /* ----------  BEGIN PANIC/IMPOSSIBLE/TESTING LOG ----------- */
3637. 
3638. /*ARGSUSED*/
3639. void
3640. paniclog(type, reason)
3641. const char *type;   /* panic, impossible, trickery */
3642. const char *reason; /* explanation */
3643. {
3644. #ifdef PANICLOG
3645.     FILE *lfile;
3646.     char buf[BUFSZ];
3647. 
3648.     if (!program_state.in_paniclog) {
3649.         program_state.in_paniclog = 1;
3650.         lfile = fopen_datafile(PANICLOG, "a", TROUBLEPREFIX);
3651.         if (lfile) {
3652. #ifdef PANICLOG_FMT2
3653.             (void) fprintf(lfile, "%ld %s: %s %s\n",
3654.                            ubirthday, (plname ? plname : "(none)"),
3655.                            type, reason);
3656. #else
3657.             time_t now = getnow();
3658.             int uid = getuid();
3659.             char playmode = wizard ? 'D' : discover ? 'X' : '-';
3660. 
3661.             (void) fprintf(lfile, "%s %08ld %06ld %d %c: %s %s\n",
3662.                            version_string(buf), yyyymmdd(now), hhmmss(now),
3663.                            uid, playmode, type, reason);
3664. #endif /* !PANICLOG_FMT2 */
3665.             (void) fclose(lfile);
3666.         }
3667.         program_state.in_paniclog = 0;
3668.     }
3669. #endif /* PANICLOG */
3670.     return;
3671. }
3672. 
3673. void
3674. testinglog(filenm, type, reason)
3675. const char *filenm;   /* ad hoc file name */
3676. const char *type;
3677. const char *reason;   /* explanation */
3678. {
3679.     FILE *lfile;
3680.     char fnbuf[BUFSZ];
3681. 
3682.     if (!filenm)
3683.         return;
3684.     Strcpy(fnbuf, filenm);
3685.     if (index(fnbuf, '.') == 0)
3686.         Strcat(fnbuf, ".log");
3687.     lfile = fopen_datafile(fnbuf, "a", TROUBLEPREFIX);
3688.     if (lfile) {
3689.         (void) fprintf(lfile, "%s\n%s\n", type, reason);
3690.         (void) fclose(lfile);
3691.     }
3692.     return;
3693. }
3694. 
3695. /* ----------  END PANIC/IMPOSSIBLE/TESTING LOG ----------- */
3696. 
3697. #ifdef SELF_RECOVER
3698. 
3699. /* ----------  BEGIN INTERNAL RECOVER ----------- */
3700. boolean
3701. recover_savefile()
3702. {
3703.     int gfd, lfd, sfd;
3704.     int lev, savelev, hpid, pltmpsiz;
3705.     xchar levc;
3706.     struct version_info version_data;
3707.     int processed[256];
3708.     char savename[SAVESIZE], errbuf[BUFSZ];
3709.     struct savefile_info sfi;
3710.     char tmpplbuf[PL_NSIZ];
3711. 
3712.     for (lev = 0; lev < 256; lev++)
3713.         processed[lev] = 0;
3714. 
3715.     /* level 0 file contains:
3716.      *  pid of creating process (ignored here)
3717.      *  level number for current level of save file
3718.      *  name of save file nethack would have created
3719.      *  savefile info
3720.      *  player name
3721.      *  and game state
3722.      */
3723.     gfd = open_levelfile(0, errbuf);
3724.     if (gfd < 0) {
3725.         raw_printf("%s\n", errbuf);
3726.         return FALSE;
3727.     }
3728.     if (read(gfd, (genericptr_t) &hpid, sizeof hpid) != sizeof hpid) {
3729.         raw_printf("\n%s\n%s\n",
3730.             "Checkpoint data incompletely written or subsequently clobbered.",
3731.                    "Recovery impossible.");
3732.         (void) nhclose(gfd);
3733.         return FALSE;
3734.     }
3735.     if (read(gfd, (genericptr_t) &savelev, sizeof(savelev))
3736.         != sizeof(savelev)) {
3737.         raw_printf(
3738.          "\nCheckpointing was not in effect for %s -- recovery impossible.\n",
3739.                    lock);
3740.         (void) nhclose(gfd);
3741.         return FALSE;
3742.     }
3743.     if ((read(gfd, (genericptr_t) savename, sizeof savename)
3744.          != sizeof savename)
3745.         || (read(gfd, (genericptr_t) &version_data, sizeof version_data)
3746.             != sizeof version_data)
3747.         || (read(gfd, (genericptr_t) &sfi, sizeof sfi) != sizeof sfi)
3748.         || (read(gfd, (genericptr_t) &pltmpsiz, sizeof pltmpsiz)
3749.             != sizeof pltmpsiz) || (pltmpsiz > PL_NSIZ)
3750.         || (read(gfd, (genericptr_t) &tmpplbuf, pltmpsiz) != pltmpsiz)) {
3751.         raw_printf("\nError reading %s -- can't recover.\n", lock);
3752.         (void) nhclose(gfd);
3753.         return FALSE;
3754.     }
3755. 
3756.     /* save file should contain:
3757.      *  version info
3758.      *  savefile info
3759.      *  player name
3760.      *  current level (including pets)
3761.      *  (non-level-based) game state
3762.      *  other levels
3763.      */
3764.     set_savefile_name(TRUE);
3765.     sfd = create_savefile();
3766.     if (sfd < 0) {
3767.         raw_printf("\nCannot recover savefile %s.\n", SAVEF);
3768.         (void) nhclose(gfd);
3769.         return FALSE;
3770.     }
3771. 
3772.     lfd = open_levelfile(savelev, errbuf);
3773.     if (lfd < 0) {
3774.         raw_printf("\n%s\n", errbuf);
3775.         (void) nhclose(gfd);
3776.         (void) nhclose(sfd);
3777.         delete_savefile();
3778.         return FALSE;
3779.     }
3780. 
3781.     if (write(sfd, (genericptr_t) &version_data, sizeof version_data)
3782.         != sizeof version_data) {
3783.         raw_printf("\nError writing %s; recovery failed.", SAVEF);
3784.         (void) nhclose(gfd);
3785.         (void) nhclose(sfd);
3786.         (void) nhclose(lfd);
3787.         delete_savefile();
3788.         return FALSE;
3789.     }
3790. 
3791.     if (write(sfd, (genericptr_t) &sfi, sizeof sfi) != sizeof sfi) {
3792.         raw_printf("\nError writing %s; recovery failed (savefile_info).\n",
3793.                    SAVEF);
3794.         (void) nhclose(gfd);
3795.         (void) nhclose(sfd);
3796.         (void) nhclose(lfd);
3797.         delete_savefile();
3798.         return FALSE;
3799.     }
3800. 
3801.     if (write(sfd, (genericptr_t) &pltmpsiz, sizeof pltmpsiz)
3802.         != sizeof pltmpsiz) {
3803.         raw_printf("Error writing %s; recovery failed (player name size).\n",
3804.                    SAVEF);
3805.         (void) nhclose(gfd);
3806.         (void) nhclose(sfd);
3807.         (void) nhclose(lfd);
3808.         delete_savefile();
3809.         return FALSE;
3810.     }
3811. 
3812.     if (write(sfd, (genericptr_t) &tmpplbuf, pltmpsiz) != pltmpsiz) {
3813.         raw_printf("Error writing %s; recovery failed (player name).\n",
3814.                    SAVEF);
3815.         (void) nhclose(gfd);
3816.         (void) nhclose(sfd);
3817.         (void) nhclose(lfd);
3818.         delete_savefile();
3819.         return FALSE;
3820.     }
3821. 
3822.     if (!copy_bytes(lfd, sfd)) {
3823.         (void) nhclose(gfd);
3824.         (void) nhclose(sfd);
3825.         (void) nhclose(lfd);
3826.         delete_savefile();
3827.         return FALSE;
3828.     }
3829.     (void) nhclose(lfd);
3830.     processed[savelev] = 1;
3831. 
3832.     if (!copy_bytes(gfd, sfd)) {
3833.         (void) nhclose(gfd);
3834.         (void) nhclose(sfd);
3835.         delete_savefile();
3836.         return FALSE;
3837.     }
3838.     (void) nhclose(gfd);
3839.     processed[0] = 1;
3840. 
3841.     for (lev = 1; lev < 256; lev++) {
3842.         /* level numbers are kept in xchars in save.c, so the
3843.          * maximum level number (for the endlevel) must be < 256
3844.          */
3845.         if (lev != savelev) {
3846.             lfd = open_levelfile(lev, (char *) 0);
3847.             if (lfd >= 0) {
3848.                 /* any or all of these may not exist */
3849.                 levc = (xchar) lev;
3850.                 write(sfd, (genericptr_t) &levc, sizeof(levc));
3851.                 if (!copy_bytes(lfd, sfd)) {
3852.                     (void) nhclose(lfd);
3853.                     (void) nhclose(sfd);
3854.                     delete_savefile();
3855.                     return FALSE;
3856.                 }
3857.                 (void) nhclose(lfd);
3858.                 processed[lev] = 1;
3859.             }
3860.         }
3861.     }
3862.     (void) nhclose(sfd);
3863. 
3864. #ifdef HOLD_LOCKFILE_OPEN
3865.     really_close();
3866. #endif
3867.     /*
3868.      * We have a successful savefile!
3869.      * Only now do we erase the level files.
3870.      */
3871.     for (lev = 0; lev < 256; lev++) {
3872.         if (processed[lev]) {
3873.             const char *fq_lock;
3874. 
3875.             set_levelfile_name(lock, lev);
3876.             fq_lock = fqname(lock, LEVELPREFIX, 3);
3877.             (void) unlink(fq_lock);
3878.         }
3879.     }
3880.     return TRUE;
3881. }
3882. 
3883. boolean
3884. copy_bytes(ifd, ofd)
3885. int ifd, ofd;
3886. {
3887.     char buf[BUFSIZ];
3888.     int nfrom, nto;
3889. 
3890.     do {
3891.         nfrom = read(ifd, buf, BUFSIZ);
3892.         nto = write(ofd, buf, nfrom);
3893.         if (nto != nfrom)
3894.             return FALSE;
3895.     } while (nfrom == BUFSIZ);
3896.     return TRUE;
3897. }
3898. 
3899. /* ----------  END INTERNAL RECOVER ----------- */
3900. #endif /*SELF_RECOVER*/
3901. 
3902. /* ----------  OTHER ----------- */
3903. 
3904. #ifdef SYSCF
3905. #ifdef SYSCF_FILE
3906. void
3907. assure_syscf_file()
3908. {
3909.     int fd;
3910. 
3911. #ifdef WIN32
3912.     /* We are checking that the sysconf exists ... lock the path */
3913.     fqn_prefix_locked[SYSCONFPREFIX] = TRUE;
3914. #endif
3915.     /*
3916.      * All we really care about is the end result - can we read the file?
3917.      * So just check that directly.
3918.      *
3919.      * Not tested on most of the old platforms (which don't attempt
3920.      * to implement SYSCF).
3921.      * Some ports don't like open()'s optional third argument;
3922.      * VMS overrides open() usage with a macro which requires it.
3923.      */
3924. #ifndef VMS
3925. # if defined(NOCWD_ASSUMPTIONS) && defined(WIN32)
3926.     fd = open(fqname(SYSCF_FILE, SYSCONFPREFIX, 0), O_RDONLY);
3927. # else
3928.     fd = open(SYSCF_FILE, O_RDONLY);
3929. # endif
3930. #else
3931.     fd = open(SYSCF_FILE, O_RDONLY, 0);
3932. #endif
3933.     if (fd >= 0) {
3934.         /* readable */
3935.         close(fd);
3936.         return;
3937.     }
3938.     raw_printf("Unable to open SYSCF_FILE.\n");
3939.     exit(EXIT_FAILURE);
3940. }
3941. 
3942. #endif /* SYSCF_FILE */
3943. #endif /* SYSCF */
3944. 
3945. #ifdef DEBUG
3946. /* used by debugpline() to decide whether to issue a message
3947.  * from a particular source file; caller passes __FILE__ and we check
3948.  * whether it is in the source file list supplied by SYSCF's DEBUGFILES
3949.  *
3950.  * pass FALSE to override wildcard matching; useful for files
3951.  * like dungeon.c and questpgr.c, which generate a ridiculous amount of
3952.  * output if DEBUG is defined and effectively block the use of a wildcard */
3953. boolean
3954. debugcore(filename, wildcards)
3955. const char *filename;
3956. boolean wildcards;
3957. {
3958.     const char *debugfiles, *p;
3959. 
3960.     if (!filename || !*filename)
3961.         return FALSE; /* sanity precaution */
3962. 
3963.     if (sysopt.env_dbgfl == 0) {
3964.         /* check once for DEBUGFILES in the environment;
3965.            if found, it supersedes the sysconf value
3966.            [note: getenv() rather than nh_getenv() since a long value
3967.            is valid and doesn't pose any sort of overflow risk here] */
3968.         if ((p = getenv("DEBUGFILES")) != 0) {
3969.             if (sysopt.debugfiles)
3970.                 free((genericptr_t) sysopt.debugfiles);
3971.             sysopt.debugfiles = dupstr(p);
3972.             sysopt.env_dbgfl = 1;
3973.         } else
3974.             sysopt.env_dbgfl = -1;
3975.     }
3976. 
3977.     debugfiles = sysopt.debugfiles;
3978.     /* usual case: sysopt.debugfiles will be empty */
3979.     if (!debugfiles || !*debugfiles)
3980.         return FALSE;
3981. 
3982. /* strip filename's path if present */
3983. #ifdef UNIX
3984.     if ((p = rindex(filename, '/')) != 0)
3985.         filename = p + 1;
3986. #endif
3987. #ifdef VMS
3988.     filename = vms_basename(filename);
3989.     /* vms_basename strips off 'type' suffix as well as path and version;
3990.        we want to put suffix back (".c" assumed); since it always returns
3991.        a pointer to a static buffer, we can safely modify its result */
3992.     Strcat((char *) filename, ".c");
3993. #endif
3994. 
3995.     /*
3996.      * Wildcard match will only work if there's a single pattern (which
3997.      * might be a single file name without any wildcarding) rather than
3998.      * a space-separated list.
3999.      * [to NOT do: We could step through the space-separated list and
4000.      * attempt a wildcard match against each element, but that would be
4001.      * overkill for the intended usage.]
4002.      */
4003.     if (wildcards && pmatch(debugfiles, filename))
4004.         return TRUE;
4005. 
4006.     /* check whether filename is an element of the list */
4007.     if ((p = strstr(debugfiles, filename)) != 0) {
4008.         int l = (int) strlen(filename);
4009. 
4010.         if ((p == debugfiles || p[-1] == ' ' || p[-1] == '/')
4011.             && (p[l] == ' ' || p[l] == '\0'))
4012.             return TRUE;
4013.     }
4014.     return FALSE;
4015. }
4016. 
4017. #endif /*DEBUG*/
4018. 
4019. #ifdef UNIX
4020. #ifndef PATH_MAX
4021. #include <limits.h>
4022. #endif
4023. #endif
4024. 
4025. void
4026. reveal_paths(VOID_ARGS)
4027. {
4028.     const char *fqn, *nodumpreason;
4029.     char buf[BUFSZ];
4030. #if defined(SYSCF) || !defined(UNIX) || defined(DLB)
4031.     const char *filep;
4032. #ifdef SYSCF
4033.     const char *gamename = (hname && *hname) ? hname : "NetHack";
4034. #endif
4035. #endif
4036. #ifdef UNIX
4037.     char *endp, *envp, cwdbuf[PATH_MAX];
4038. #endif
4039. #ifdef PREFIXES_IN_USE
4040.     const char *strp;
4041.     int i, maxlen = 0;
4042. 
4043.     raw_print("Variable playground locations:");
4044.     for (i = 0; i < PREFIX_COUNT; i++)
4045.         raw_printf("    [%-10s]=\"%s\"", fqn_prefix_names[i],
4046.                    fqn_prefix[i] ? fqn_prefix[i] : "not set");
4047. #endif
4048. 
4049.     /* sysconf file */
4050. 
4051. #ifdef SYSCF
4052. #ifdef PREFIXES_IN_USE
4053.     strp = fqn_prefix_names[SYSCONFPREFIX];
4054.     maxlen = BUFSZ - sizeof " (in )";
4055.     if (strp && (int) strlen(strp) < maxlen)
4056.         Sprintf(buf, " (in %s)", strp);
4057. #else
4058.     buf[0] = '\0';
4059. #endif
4060.     raw_printf("%s system configuration file%s:", s_suffix(gamename), buf);
4061. #ifdef SYSCF_FILE
4062.     filep = SYSCF_FILE;
4063. #else
4064.     filep = "sysconf";
4065. #endif
4066.     fqn = fqname(filep, SYSCONFPREFIX, 0);
4067.     if (fqn) {
4068.         set_configfile_name(fqn);
4069.         filep = configfile;
4070.     }
4071.     raw_printf("    \"%s\"", filep);
4072. #else /* !SYSCF */
4073.     raw_printf("No system configuration file.");
4074. #endif /* ?SYSCF */
4075. 
4076.     /* symbols file */
4077. 
4078.     buf[0] = '\0';
4079. #ifndef UNIX
4080. #ifdef PREFIXES_IN_USE
4081. #ifdef WIN32
4082.     strp = fqn_prefix_names[SYSCONFPREFIX];
4083. #else
4084.     strp = fqn_prefix_names[HACKPREFIX];
4085. #endif /* WIN32 */
4086.     maxlen = BUFSZ - sizeof " (in )";
4087.     if (strp && (int) strlen(strp) < maxlen)
4088.         Sprintf(buf, " (in %s)", strp);
4089. #endif /* PREFIXES_IN_USE */
4090.     raw_printf("The loadable symbols file%s:", buf);
4091. #endif /* UNIX */
4092. 
4093. #ifdef UNIX
4094.     envp = getcwd(cwdbuf, PATH_MAX);
4095.     if (envp) {
4096.         raw_print("The loadable symbols file:");
4097.         raw_printf("    \"%s/%s\"", envp, SYMBOLS);
4098.     }
4099. #else /* UNIX */
4100.     filep = SYMBOLS;
4101. #ifdef PREFIXES_IN_USE
4102. #ifdef WIN32
4103.     fqn = fqname(filep, SYSCONFPREFIX, 1);
4104. #else
4105.     fqn = fqname(filep, HACKPREFIX, 1);
4106. #endif /* WIN32 */
4107.     if (fqn)
4108.         filep = fqn;
4109. #endif /* PREFIXES_IN_USE */
4110.     raw_printf("    \"%s\"", filep);
4111. #endif /* UNIX */
4112. 
4113.     /* dlb vs non-dlb */
4114. 
4115.     buf[0] = '\0';
4116. #ifdef PREFIXES_IN_USE
4117.     strp = fqn_prefix_names[DATAPREFIX];
4118.     maxlen = BUFSZ - sizeof " (in )";
4119.     if (strp && (int) strlen(strp) < maxlen)
4120.         Sprintf(buf, " (in %s)", strp);
4121. #endif
4122. #ifdef DLB
4123.     raw_printf("Basic data files%s are collected inside:", buf);
4124.     filep = DLBFILE;
4125. #ifdef VERSION_IN_DLB_FILENAME
4126.     Strcpy(buf, build_dlb_filename((const char *) 0));
4127. #ifdef PREFIXES_IN_USE
4128.     fqn = fqname(buf, DATAPREFIX, 1);
4129.     if (fqn)
4130.         filep = fqn;
4131. #endif /* PREFIXES_IN_USE */
4132. #endif
4133.     raw_printf("    \"%s\"", filep);
4134. #ifdef DLBFILE2
4135.     filep = DLBFILE2;
4136.     raw_printf("    \"%s\"", filep);
4137. #endif
4138. #else /* !DLB */
4139.     raw_printf("Basic data files%s are in many separate files.", buf);
4140. #endif /* ?DLB */
4141. 
4142.     /* dumplog */
4143. 
4144. #ifndef DUMPLOG
4145.     nodumpreason = "not supported";
4146. #else
4147.     nodumpreason = "disabled";
4148. #ifdef SYSCF
4149.     fqn = sysopt.dumplogfile;
4150. #else  /* !SYSCF */
4151. #ifdef DUMPLOG_FILE
4152.     fqn = DUMPLOG_FILE;
4153. #else
4154.     fqn = (char *) 0;
4155. #endif
4156. #endif /* ?SYSCF */
4157.     if (fqn && *fqn) {
4158.         raw_print("Your end-of-game disclosure file:");
4159.         (void) dump_fmtstr(fqn, buf, FALSE);
4160.         buf[sizeof buf - sizeof "    \"\""] = '\0';
4161.         raw_printf("    \"%s\"", buf);
4162.     } else
4163. #endif /* ?DUMPLOG */
4164.         raw_printf("No end-of-game disclosure file (%s).", nodumpreason);
4165. 
4166. #ifdef WIN32
4167.     if (sysopt.portable_device_paths) {
4168.         const char *pd = get_portable_device();
4169. 
4170.         raw_printf("portable_device_paths (set in sysconf):");
4171.         raw_printf("    \"%s\"", pd);
4172.     }
4173. #endif
4174. 
4175.     /* personal configuration file */
4176. 
4177.     buf[0] = '\0';
4178. #ifdef PREFIXES_IN_USE
4179.     strp = fqn_prefix_names[CONFIGPREFIX];
4180.     maxlen = BUFSZ - sizeof " (in )";
4181.     if (strp && (int) strlen(strp) < maxlen)
4182.         Sprintf(buf, " (in %s)", strp);
4183. #endif /* PREFIXES_IN_USE */
4184.     raw_printf("Your personal configuration file%s:", buf);
4185. 
4186. #ifdef UNIX
4187.     buf[0] = '\0';
4188.     if ((envp = nh_getenv("HOME")) != 0) {
4189.         copynchars(buf, envp, (int) sizeof buf - 1 - 1);
4190.         Strcat(buf, "/");
4191.     }
4192.     endp = eos(buf);
4193.     copynchars(endp, default_configfile,
4194.                (int) (sizeof buf - 1 - strlen(buf)));
4195. #if defined(__APPLE__) /* UNIX+__APPLE__ => MacOSX aka OSX aka macOS */
4196.     if (envp) {
4197.         if (access(buf, 4) == -1) { /* 4: R_OK, -1: failure */
4198.             /* read access to default failed; might be protected excessively
4199.                but more likely it doesn't exist; try first alternate:
4200.                "$HOME/Library/Pref..."; 'endp' points past '/' */
4201.             copynchars(endp, "Library/Preferences/NetHack Defaults",
4202.                        (int) (sizeof buf - 1 - strlen(buf)));
4203.             if (access(buf, 4) == -1) {
4204.                 /* first alternate failed, try second:
4205.                    ".../NetHack Defaults.txt"; no 'endp', just append */
4206.                 copynchars(eos(buf), ".txt",
4207.                            (int) (sizeof buf - 1 - strlen(buf)));
4208.                 if (access(buf, 4) == -1) {
4209.                     /* second alternate failed too, so revert to the
4210.                        original default ("$HOME/.nethackrc") for message */
4211.                     copynchars(endp, default_configfile,
4212.                                (int) (sizeof buf - 1 - strlen(buf)));
4213.                 }
4214.             }
4215.         }
4216.     }
4217. #endif /* __APPLE__ */
4218.     raw_printf("    \"%s\"", buf);
4219. #else /* !UNIX */
4220.     fqn = (const char *) 0;
4221. #ifdef PREFIXES_IN_USE
4222.     fqn = fqname(default_configfile, CONFIGPREFIX, 2);
4223. #endif
4224.     raw_printf("    \"%s\"", fqn ? fqn : default_configfile);
4225. #endif  /* ?UNIX */
4226. 
4227.     raw_print("");
4228. }
4229. 
4230. /* ----------  BEGIN TRIBUTE ----------- */
4231. 
4232. /* 3.6 tribute code
4233.  */
4234. 
4235. #define SECTIONSCOPE 1
4236. #define TITLESCOPE 2
4237. #define PASSAGESCOPE 3
4238. 
4239. #define MAXPASSAGES SIZE(context.novel.pasg) /* 20 */
4240. 
4241. static int FDECL(choose_passage, (int, unsigned));
4242. 
4243. /* choose a random passage that hasn't been chosen yet; once all have
4244.    been chosen, reset the tracking to make all passages available again */
4245. static int
4246. choose_passage(passagecnt, oid)
4247. int passagecnt; /* total of available passages */
4248. unsigned oid; /* book.o_id, used to determine whether re-reading same book */
4249. {
4250.     int idx, res;
4251. 
4252.     if (passagecnt < 1)
4253.         return 0;
4254. 
4255.     /* if a different book or we've used up all the passages already,
4256.        reset in order to have all 'passagecnt' passages available */
4257.     if (oid != context.novel.id || context.novel.count == 0) {
4258.         int i, range = passagecnt, limit = MAXPASSAGES;
4259. 
4260.         context.novel.id = oid;
4261.         if (range <= limit) {
4262.             /* collect all of the N indices */
4263.             context.novel.count = passagecnt;
4264.             for (idx = 0; idx < MAXPASSAGES; idx++)
4265.                 context.novel.pasg[idx] = (xchar) ((idx < passagecnt)
4266.                                                    ? idx + 1 : 0);
4267.         } else {
4268.             /* collect MAXPASSAGES of the N indices */
4269.             context.novel.count = MAXPASSAGES;
4270.             for (idx = i = 0; i < passagecnt; ++i, --range)
4271.                 if (range > 0 && rn2(range) < limit) {
4272.                     context.novel.pasg[idx++] = (xchar) (i + 1);
4273.                     --limit;
4274.                 }
4275.         }
4276.     }
4277. 
4278.     idx = rn2(context.novel.count);
4279.     res = (int) context.novel.pasg[idx];
4280.     /* move the last slot's passage index into the slot just used
4281.        and reduce the number of passages available */
4282.     context.novel.pasg[idx] = context.novel.pasg[--context.novel.count];
4283.     return res;
4284. }
4285. 
4286. /* Returns True if you were able to read something. */
4287. boolean
4288. read_tribute(tribsection, tribtitle, tribpassage, nowin_buf, bufsz, oid)
4289. const char *tribsection, *tribtitle;
4290. int tribpassage, bufsz;
4291. char *nowin_buf;
4292. unsigned oid; /* book identifier */
4293. {
4294.     dlb *fp;
4295.     char line[BUFSZ], lastline[BUFSZ];
4296. 
4297.     int scope = 0;
4298.     int linect = 0, passagecnt = 0, targetpassage = 0;
4299.     const char *badtranslation = "an incomprehensible foreign translation";
4300.     boolean matchedsection = FALSE, matchedtitle = FALSE;
4301.     winid tribwin = WIN_ERR;
4302.     boolean grasped = FALSE;
4303.     boolean foundpassage = FALSE;
4304. 
4305.     if (nowin_buf)
4306.         *nowin_buf = '\0';
4307. 
4308.     /* check for mandatories */
4309.     if (!tribsection || !tribtitle) {
4310.         if (!nowin_buf)
4311.             pline("It's %s of \"%s\"!", badtranslation, tribtitle);
4312.         return grasped;
4313.     }
4314. 
4315.     debugpline3("read_tribute %s, %s, %d.", tribsection, tribtitle,
4316.                 tribpassage);
4317. 
4318.     fp = dlb_fopen(TRIBUTEFILE, "r");
4319.     if (!fp) {
4320.         /* this is actually an error - cannot open tribute file! */
4321.         if (!nowin_buf)
4322.             pline("You feel too overwhelmed to continue!");
4323.         return grasped;
4324.     }
4325. 
4326.     /*
4327.      * Syntax (not case-sensitive):
4328.      *  %section books
4329.      *
4330.      * In the books section:
4331.      *    %title booktitle (n)
4332.      *          where booktitle=book title without quotes
4333.      *          (n)= total number of passages present for this title
4334.      *    %passage k
4335.      *          where k=sequential passage number
4336.      *
4337.      * %e ends the passage/book/section
4338.      *    If in a passage, it marks the end of that passage.
4339.      *    If in a book, it marks the end of that book.
4340.      *    If in a section, it marks the end of that section.
4341.      *
4342.      *  %section death
4343.      */
4344. 
4345.     *line = *lastline = '\0';
4346.     while (dlb_fgets(line, sizeof line, fp) != 0) {
4347.         linect++;
4348.         (void) strip_newline(line);
4349.         switch (line[0]) {
4350.         case '%':
4351.             if (!strncmpi(&line[1], "section ", sizeof "section " - 1)) {
4352.                 char *st = &line[9]; /* 9 from "%section " */
4353. 
4354.                 scope = SECTIONSCOPE;
4355.                 matchedsection = !strcmpi(st, tribsection) ? TRUE : FALSE;
4356.             } else if (!strncmpi(&line[1], "title ", sizeof "title " - 1)) {
4357.                 char *st = &line[7]; /* 7 from "%title " */
4358.                 char *p1, *p2;
4359. 
4360.                 if ((p1 = index(st, '(')) != 0) {
4361.                     *p1++ = '\0';
4362.                     (void) mungspaces(st);
4363.                     if ((p2 = index(p1, ')')) != 0) {
4364.                         *p2 = '\0';
4365.                         passagecnt = atoi(p1);
4366.                         scope = TITLESCOPE;
4367.                         if (matchedsection && !strcmpi(st, tribtitle)) {
4368.                             matchedtitle = TRUE;
4369.                             targetpassage = !tribpassage
4370.                                              ? choose_passage(passagecnt, oid)
4371.                                              : (tribpassage <= passagecnt)
4372.                                                 ? tribpassage : 0;
4373.                         } else {
4374.                             matchedtitle = FALSE;
4375.                         }
4376.                     }
4377.                 }
4378.             } else if (!strncmpi(&line[1], "passage ",
4379.                                  sizeof "passage " - 1)) {
4380.                 int passagenum = 0;
4381.                 char *st = &line[9]; /* 9 from "%passage " */
4382. 
4383.                 mungspaces(st);
4384.                 passagenum = atoi(st);
4385.                 if (passagenum > 0 && passagenum <= passagecnt) {
4386.                     scope = PASSAGESCOPE;
4387.                     if (matchedtitle && passagenum == targetpassage) {
4388.                         foundpassage = TRUE;
4389.                         if (!nowin_buf) {
4390.                             tribwin = create_nhwindow(NHW_MENU);
4391.                             if (tribwin == WIN_ERR)
4392.                                 goto cleanup;
4393.                         }
4394.                     }
4395.                 }
4396.             } else if (!strncmpi(&line[1], "e ", sizeof "e " - 1)) {
4397.                 if (foundpassage)
4398.                     goto cleanup;
4399.                 if (scope == TITLESCOPE)
4400.                     matchedtitle = FALSE;
4401.                 if (scope == SECTIONSCOPE)
4402.                     matchedsection = FALSE;
4403.                 if (scope)
4404.                     --scope;
4405.             } else {
4406.                 debugpline1("tribute file error: bad %% command, line %d.",
4407.                             linect);
4408.             }
4409.             break;
4410.         case '#':
4411.             /* comment only, next! */
4412.             break;
4413.         default:
4414.             if (foundpassage) {
4415.                 if (!nowin_buf) {
4416.                     /* outputting multi-line passage to text window */
4417.                     putstr(tribwin, 0, line);
4418.                     if (*line)
4419.                         Strcpy(lastline, line);
4420.                 } else {
4421.                     /* fetching one-line passage into buffer */
4422.                     copynchars(nowin_buf, line, bufsz - 1);
4423.                     goto cleanup; /* don't wait for "%e passage" */
4424.                 }
4425.             }
4426.         }
4427.     }
4428. 
4429.  cleanup:
4430.     (void) dlb_fclose(fp);
4431.     if (nowin_buf) {
4432.         /* one-line buffer */
4433.         grasped = *nowin_buf ? TRUE : FALSE;
4434.     } else {
4435.         if (tribwin != WIN_ERR) { /* implies 'foundpassage' */
4436.             /* multi-line window, normal case;
4437.                if lastline is empty, there were no non-empty lines between
4438.                "%passage n" and "%e passage" so we leave 'grasped' False */
4439.             if (*lastline) {
4440.                 display_nhwindow(tribwin, FALSE);
4441.                 /* put the final attribution line into message history,
4442.                    analogous to the summary line from long quest messages */
4443.                 if (index(lastline, '['))
4444.                     mungspaces(lastline); /* to remove leading spaces */
4445.                 else /* construct one if necessary */
4446.                     Sprintf(lastline, "[%s, by Terry Pratchett]", tribtitle);
4447.                 putmsghistory(lastline, FALSE);
4448.                 grasped = TRUE;
4449.             }
4450.             destroy_nhwindow(tribwin);
4451.         }
4452.         if (!grasped)
4453.             /* multi-line window, problem */
4454.             pline("It seems to be %s of \"%s\"!", badtranslation, tribtitle);
4455.     }
4456.     return grasped;
4457. }
4458. 
4459. boolean
4460. Death_quote(buf, bufsz)
4461. char *buf;
4462. int bufsz;
4463. {
4464.     unsigned death_oid = 1; /* chance of oid #1 being a novel is negligible */
4465. 
4466.     return read_tribute("Death", "Death Quotes", 0, buf, bufsz, death_oid);
4467. }
4468. 
4469. /* ----------  END TRIBUTE ----------- */
4470. 
4471. /*files.c*/