xref: /original-bsd/games/rogue/machdep.c (revision 454fcdce)
1 /*
2  * Copyright (c) 1988 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Timothy C. Stoehr.
7  *
8  * %sccs.include.redist.c%
9  */
10 
11 #ifndef lint
12 static char sccsid[] = "@(#)machdep.c	5.7 (Berkeley) 02/28/91";
13 #endif /* not lint */
14 
15 /*
16  * machdep.c
17  *
18  * This source herein may be modified and/or distributed by anybody who
19  * so desires, with the following restrictions:
20  *    1.)  No portion of this notice shall be removed.
21  *    2.)  Credit shall not be taken for the creation of this source.
22  *    3.)  This code is not to be traded, sold, or used for personal
23  *         gain or profit.
24  *
25  */
26 
27 /* Included in this file are all system dependent routines.  Extensive use
28  * of #ifdef's will be used to compile the appropriate code on each system:
29  *
30  *    UNIX:        all UNIX systems.
31  *    UNIX_BSD4_2: UNIX BSD 4.2 and later, UTEK, (4.1 BSD too?)
32  *    UNIX_SYSV:   UNIX system V
33  *    UNIX_V7:     UNIX version 7
34  *
35  * All UNIX code should be included between the single "#ifdef UNIX" at the
36  * top of this file, and the "#endif" at the bottom.
37  *
38  * To change a routine to include a new UNIX system, simply #ifdef the
39  * existing routine, as in the following example:
40  *
41  *   To make a routine compatible with UNIX system 5, change the first
42  *   function to the second:
43  *
44  *      md_function()
45  *      {
46  *         code;
47  *      }
48  *
49  *      md_function()
50  *      {
51  *      #ifdef UNIX_SYSV
52  *         sys5code;
53  *      #else
54  *         code;
55  *      #endif
56  *      }
57  *
58  * Appropriate variations of this are of course acceptible.
59  * The use of "#elseif" is discouraged because of non-portability.
60  * If the correct #define doesn't exist, "UNIX_SYSV" in this case, make it up
61  * and insert it in the list at the top of the file.  Alter the CFLAGS
62  * in you Makefile appropriately.
63  *
64  */
65 
66 #ifdef UNIX
67 
68 #include <stdio.h>
69 #include <sys/types.h>
70 #include <sys/file.h>
71 #include <sys/stat.h>
72 #include <pwd.h>
73 
74 #ifdef UNIX_BSD4_2
75 #include <sys/time.h>
76 #include <sgtty.h>
77 #endif
78 
79 #ifdef UNIX_SYSV
80 #include <time.h>
81 #include <termio.h>
82 #endif
83 
84 #include <signal.h>
85 #include "rogue.h"
86 #include "pathnames.h"
87 
88 /* md_slurp:
89  *
90  * This routine throws away all keyboard input that has not
91  * yet been read.  It is used to get rid of input that the user may have
92  * typed-ahead.
93  *
94  * This function is not necessary, so it may be stubbed.  The might cause
95  * message-line output to flash by because the game has continued to read
96  * input without waiting for the user to read the message.  Not such a
97  * big deal.
98  */
99 
100 md_slurp()
101 {
102 	(void)fpurge(stdin);
103 }
104 
105 /* md_control_keyboard():
106  *
107  * This routine is much like md_cbreak_no_echo_nonl() below.  It sets up the
108  * keyboard for appropriate input.  Specifically, it prevents the tty driver
109  * from stealing characters.  For example, ^Y is needed as a command
110  * character, but the tty driver intercepts it for another purpose.  Any
111  * such behavior should be stopped.  This routine could be avoided if
112  * we used RAW mode instead of CBREAK.  But RAW mode does not allow the
113  * generation of keyboard signals, which the program uses.
114  *
115  * The parameter 'mode' when true, indicates that the keyboard should
116  * be set up to play rogue.  When false, it should be restored if
117  * necessary.
118  *
119  * This routine is not strictly necessary and may be stubbed.  This may
120  * cause certain command characters to be unavailable.
121  */
122 
123 md_control_keybord(mode)
124 boolean mode;
125 {
126 	static boolean called_before = 0;
127 #ifdef UNIX_BSD4_2
128 	static struct ltchars ltc_orig;
129 	static struct tchars tc_orig;
130 	struct ltchars ltc_temp;
131 	struct tchars tc_temp;
132 #endif
133 #ifdef UNIX_SYSV
134 	static struct termio _oldtty;
135 	struct termio _tty;
136 #endif
137 
138 	if (!called_before) {
139 		called_before = 1;
140 #ifdef UNIX_BSD4_2
141 		ioctl(0, TIOCGETC, &tc_orig);
142 		ioctl(0, TIOCGLTC, &ltc_orig);
143 #endif
144 #ifdef UNIX_SYSV
145 		ioctl(0, TCGETA, &_oldtty);
146 #endif
147 	}
148 #ifdef UNIX_BSD4_2
149 	ltc_temp = ltc_orig;
150 	tc_temp = tc_orig;
151 #endif
152 #ifdef UNIX_SYSV
153 	_tty = _oldtty;
154 #endif
155 
156 	if (!mode) {
157 #ifdef UNIX_BSD4_2
158 		ltc_temp.t_suspc = ltc_temp.t_dsuspc = -1;
159 		ltc_temp.t_rprntc = ltc_temp.t_flushc = -1;
160 		ltc_temp.t_werasc = ltc_temp.t_lnextc = -1;
161 		tc_temp.t_startc = tc_temp.t_stopc = -1;
162 #endif
163 #ifdef UNIX_SYSV
164 		_tty.c_cc[VSWTCH] = CNSWTCH;
165 #endif
166 	}
167 #ifdef UNIX_BSD4_2
168 	ioctl(0, TIOCSETC, &tc_temp);
169 	ioctl(0, TIOCSLTC, &ltc_temp);
170 #endif
171 #ifdef UNIX_SYSV
172 	ioctl(0, TCSETA, &_tty);
173 #endif
174 }
175 
176 /* md_heed_signals():
177  *
178  * This routine tells the program to call particular routines when
179  * certain interrupts/events occur:
180  *
181  *      SIGINT: call onintr() to interrupt fight with monster or long rest.
182  *      SIGQUIT: call byebye() to check for game termination.
183  *      SIGHUP: call error_save() to save game when terminal hangs up.
184  *
185  *		On VMS, SIGINT and SIGQUIT correspond to ^C and ^Y.
186  *
187  * This routine is not strictly necessary and can be stubbed.  This will
188  * mean that the game cannot be interrupted properly with keyboard
189  * input, this is not usually critical.
190  */
191 
192 md_heed_signals()
193 {
194 	signal(SIGINT, onintr);
195 	signal(SIGQUIT, byebye);
196 	signal(SIGHUP, error_save);
197 }
198 
199 /* md_ignore_signals():
200  *
201  * This routine tells the program to completely ignore the events mentioned
202  * in md_heed_signals() above.  The event handlers will later be turned on
203  * by a future call to md_heed_signals(), so md_heed_signals() and
204  * md_ignore_signals() need to work together.
205  *
206  * This function should be implemented or the user risks interrupting
207  * critical sections of code, which could cause score file, or saved-game
208  * file, corruption.
209  */
210 
211 md_ignore_signals()
212 {
213 	signal(SIGQUIT, SIG_IGN);
214 	signal(SIGINT, SIG_IGN);
215 	signal(SIGHUP, SIG_IGN);
216 }
217 
218 /* md_get_file_id():
219  *
220  * This function returns an integer that uniquely identifies the specified
221  * file.  It need not check for the file's existence.  In UNIX, the inode
222  * number is used.
223  *
224  * This function is used to identify saved-game files.
225  */
226 
227 int
228 md_get_file_id(fname)
229 char *fname;
230 {
231 	struct stat sbuf;
232 
233 	if (stat(fname, &sbuf)) {
234 		return(-1);
235 	}
236 	return((int) sbuf.st_ino);
237 }
238 
239 /* md_link_count():
240  *
241  * This routine returns the number of hard links to the specified file.
242  *
243  * This function is not strictly necessary.  On systems without hard links
244  * this routine can be stubbed by just returning 1.
245  */
246 
247 int
248 md_link_count(fname)
249 char *fname;
250 {
251 	struct stat sbuf;
252 
253 	stat(fname, &sbuf);
254 	return((int) sbuf.st_nlink);
255 }
256 
257 /* md_gct(): (Get Current Time)
258  *
259  * This function returns the current year, month(1-12), day(1-31), hour(0-23),
260  * minute(0-59), and second(0-59).  This is used for identifying the time
261  * at which a game is saved.
262  *
263  * This function is not strictly necessary.  It can be stubbed by returning
264  * zeros instead of the correct year, month, etc.  If your operating
265  * system doesn't provide all of the time units requested here, then you
266  * can provide only those that it does, and return zeros for the others.
267  * If you cannot provide good time values, then users may be able to copy
268  * saved-game files and play them.
269  */
270 
271 md_gct(rt_buf)
272 struct rogue_time *rt_buf;
273 {
274 	struct tm *t, *localtime();
275 	long seconds;
276 
277 	time(&seconds);
278 	t = localtime(&seconds);
279 
280 	rt_buf->year = t->tm_year;
281 	rt_buf->month = t->tm_mon + 1;
282 	rt_buf->day = t->tm_mday;
283 	rt_buf->hour = t->tm_hour;
284 	rt_buf->minute = t->tm_min;
285 	rt_buf->second = t->tm_sec;
286 }
287 
288 /* md_gfmt: (Get File Modification Time)
289  *
290  * This routine returns a file's date of last modification in the same format
291  * as md_gct() above.
292  *
293  * This function is not strictly necessary.  It is used to see if saved-game
294  * files have been modified since they were saved.  If you have stubbed the
295  * routine md_gct() above by returning constant values, then you may do
296  * exactly the same here.
297  * Or if md_gct() is implemented correctly, but your system does not provide
298  * file modification dates, you may return some date far in the past so
299  * that the program will never know that a saved-game file being modified.
300  * You may also do this if you wish to be able to restore games from
301  * saved-games that have been modified.
302  */
303 
304 md_gfmt(fname, rt_buf)
305 char *fname;
306 struct rogue_time *rt_buf;
307 {
308 	struct stat sbuf;
309 	long seconds;
310 	struct tm *t;
311 
312 	stat(fname, &sbuf);
313 	seconds = (long) sbuf.st_mtime;
314 	t = localtime(&seconds);
315 
316 	rt_buf->year = t->tm_year;
317 	rt_buf->month = t->tm_mon + 1;
318 	rt_buf->day = t->tm_mday;
319 	rt_buf->hour = t->tm_hour;
320 	rt_buf->minute = t->tm_min;
321 	rt_buf->second = t->tm_sec;
322 }
323 
324 /* md_df: (Delete File)
325  *
326  * This function deletes the specified file, and returns true (1) if the
327  * operation was successful.  This is used to delete saved-game files
328  * after restoring games from them.
329  *
330  * Again, this function is not strictly necessary, and can be stubbed
331  * by simply returning 1.  In this case, saved-game files will not be
332  * deleted and can be replayed.
333  */
334 
335 boolean
336 md_df(fname)
337 char *fname;
338 {
339 	if (unlink(fname)) {
340 		return(0);
341 	}
342 	return(1);
343 }
344 
345 /* md_gln: (Get login name)
346  *
347  * This routine returns the login name of the user.  This string is
348  * used mainly for identifying users in score files.
349  *
350  * A dummy string may be returned if you are unable to implement this
351  * function, but then the score file would only have one name in it.
352  */
353 
354 char *
355 md_gln()
356 {
357 	struct passwd *p;
358 
359 	if (!(p = getpwuid(getuid())))
360 		return((char *)NULL);
361 	return(p->pw_name);
362 }
363 
364 /* md_sleep:
365  *
366  * This routine causes the game to pause for the specified number of
367  * seconds.
368  *
369  * This routine is not particularly necessary at all.  It is used for
370  * delaying execution, which is useful to this program at some times.
371  */
372 
373 md_sleep(nsecs)
374 int nsecs;
375 {
376 	(void) sleep(nsecs);
377 }
378 
379 /* md_getenv()
380  *
381  * This routine gets certain values from the user's environment.  These
382  * values are strings, and each string is identified by a name.  The names
383  * of the values needed, and their use, is as follows:
384  *
385  *   TERMCAP
386  *     The name of the users's termcap file, NOT the termcap entries
387  *     themselves.  This is used ONLY if the program is compiled with
388  *     CURSES defined (-DCURSES).  Even in this case, the program need
389  *     not find a string for TERMCAP.  If it does not, it will use the
390  *     default termcap file as returned by md_gdtcf();
391  *   TERM
392  *     The name of the users's terminal.  This is used ONLY if the program
393  *     is compiled with CURSES defined (-DCURSES).  In this case, the string
394  *     value for TERM must be found, or the routines in curses.c cannot
395  *     function, and the program will quit.
396  *   ROGUEOPTS
397  *     A string containing the various game options.  This need not be
398  *     defined.
399  *   HOME
400  *     The user's home directory.  This is only used when the user specifies
401  *     '~' as the first character of a saved-game file.  This string need
402  *     not be defined.
403  *   SHELL
404  *     The user's favorite shell.  If not found, "/bin/sh" is assumed.
405  *
406  * If your system does not provide a means of searching for these values,
407  * you will have to do it yourself.  None of the values above really need
408  * to be defined except TERM when the program is compiled with CURSES
409  * defined.  In this case, as a bare minimum, you can check the 'name'
410  * parameter, and if it is "TERM" find the terminal name and return that,
411  * else return zero.  If the program is not compiled with CURSES, you can
412  * get by with simply always returning zero.  Returning zero indicates
413  * that their is no defined value for the given string.
414  */
415 
416 char *
417 md_getenv(name)
418 char *name;
419 {
420 	char *value;
421 	char *getenv();
422 
423 	value = getenv(name);
424 
425 	return(value);
426 }
427 
428 /* md_malloc()
429  *
430  * This routine allocates, and returns a pointer to, the specified number
431  * of bytes.  This routines absolutely MUST be implemented for your
432  * particular system or the program will not run at all.  Return zero
433  * when no more memory can be allocated.
434  */
435 
436 char *
437 md_malloc(n)
438 int n;
439 {
440 	char *malloc();
441 	char *t;
442 
443 	t = malloc(n);
444 	return(t);
445 }
446 
447 /* md_gseed() (Get Seed)
448  *
449  * This function returns a seed for the random number generator (RNG).  This
450  * seed causes the RNG to begin generating numbers at some point in it's
451  * sequence.  Without a random seed, the RNG will generate the same set
452  * of numbers, and every game will start out exactly the same way.  A good
453  * number to use is the process id, given by getpid() on most UNIX systems.
454  *
455  * You need to find some single random integer, such as:
456  *   process id.
457  *   current time (minutes + seconds) returned from md_gct(), if implemented.
458  *
459  * It will not help to return "get_rand()" or "rand()" or the return value of
460  * any pseudo-RNG.  If you don't have a random number, you can just return 1,
461  * but this means your games will ALWAYS start the same way, and will play
462  * exactly the same way given the same input.
463  */
464 
465 md_gseed()
466 {
467 	return(getpid());
468 }
469 
470 /* md_exit():
471  *
472  * This function causes the program to discontinue execution and exit.
473  * This function must be implemented or the program will continue to
474  * hang when it should quit.
475  */
476 
477 md_exit(status)
478 int status;
479 {
480 	exit(status);
481 }
482 
483 /* md_lock():
484  *
485  * This function is intended to give the user exclusive access to the score
486  * file.  It does so by "creat"ing a lock file, which can only be created
487  * if it does not already exist.  The file is deleted when score file
488  * processing is finished.  The lock file should be located in the same
489  * directory as the score file.  These full path names should be defined for
490  * any particular site in rogue.h.  The constants _PATH_SCOREFILE and
491  * _PATH_LOCKFILE define these file names.
492  *
493  * When the parameter 'l' is non-zero (true), a lock is requested.  Otherwise
494  * the lock is released by removing the lock file.
495  */
496 
497 md_lock(l)
498 boolean l;
499 {
500 	short tries;
501 	char *lock_file = _PATH_LOCKFILE;
502 
503 	if (l) {
504 		for (tries = 0; tries < 5; tries++) {
505 			if (md_get_file_id(lock_file) == -1) {
506 				if (creat(lock_file, 0444) != -1) {
507 					break;
508 				} else {
509 					message("cannot lock score file", 0);
510 				}
511 			} else {
512 				message("waiting to lock score file", 0);
513 			}
514 			sleep(2);
515 		}
516 	} else {
517 		(void) unlink(lock_file);
518 	}
519 }
520 
521 /* md_shell():
522  *
523  * This function spawns a shell for the user to use.  When this shell is
524  * terminated, the game continues.  Since this program may often be run
525  * setuid to gain access to privileged files, care is taken that the shell
526  * is run with the user's REAL user id, and not the effective user id.
527  * The effective user id is restored after the shell completes.
528  */
529 
530 md_shell(shell)
531 char *shell;
532 {
533 	long w[2];
534 
535 	if (!fork()) {
536 		int uid;
537 
538 		uid = getuid();
539 		setuid(uid);
540 		execl(shell, shell, 0);
541 	}
542 	wait(w);
543 }
544 
545 /* If you have a viable curses/termlib library, then use it and don't bother
546  * implementing the routines below.  And don't compile with -DCURSES.
547  */
548 
549 #ifdef CURSES
550 
551 /* md_cbreak_no_echo_nonl:
552  *
553  * This routine sets up some terminal characteristics.  The tty-driver
554  * must be told to:
555  *   1.)  Not echo input.
556  *   2.)  Transmit input characters immediately upon typing. (cbreak mode)
557  *   3.)  Move the cursor down one line, without changing column, and
558  *        without generating a carriage-return, when it
559  *        sees a line-feed.  This is only necessary if line-feed is ever
560  *        used in the termcap 'do' (cursor down) entry, in which case,
561  *        your system should must have a way of accomplishing this.
562  *
563  * When the parameter 'on' is true, the terminal is set up as specified
564  * above.  When this parameter is false, the terminal is restored to the
565  * original state.
566  *
567  * Raw mode should not to be used.  Keyboard signals/events/interrupts should
568  * be sent, although they are not strictly necessary.  See notes in
569  * md_heed_signals().
570  *
571  * This function must be implemented for rogue to run properly if the
572  * program is compiled with CURSES defined to use the enclosed curses
573  * emulation package.  If you are not using this, then this routine is
574  * totally unnecessary.
575  *
576  * Notice that information is saved between calls.  This is used to
577  * restore the terminal to an initial saved state.
578  *
579  */
580 
581 md_cbreak_no_echo_nonl(on)
582 boolean on;
583 {
584 #ifdef UNIX_BSD4_2
585 	static struct sgttyb tty_buf;
586 	static int tsave_flags;
587 
588 	if (on) {
589 		ioctl(0, TIOCGETP, &tty_buf);
590 		tsave_flags = tty_buf.sg_flags;
591 		tty_buf.sg_flags |= CBREAK;
592 		tty_buf.sg_flags &= ~(ECHO | CRMOD);	/* CRMOD: see note 3 above */
593 		ioctl(0, TIOCSETP, &tty_buf);
594 	} else {
595 		tty_buf.sg_flags = tsave_flags;
596 		ioctl(0, TIOCSETP, &tty_buf);
597 	}
598 #endif
599 #ifdef UNIX_SYSV
600 	struct termio tty_buf;
601 	static struct termio tty_save;
602 
603 	if (on) {
604 		ioctl(0, TCGETA, &tty_buf);
605 		tty_save = tty_buf;
606 		tty_buf.c_lflag &= ~(ICANON | ECHO);
607 		tty_buf.c_oflag &= ~ONLCR;
608 		tty_buf.c_cc[4] = 1;  /* MIN */
609 		tty_buf.c_cc[5] = 2;  /* TIME */
610 		ioctl(0, TCSETAF, &tty_buf);
611 	} else {
612 		ioctl(0, TCSETAF, &tty_save);
613 	}
614 #endif
615 }
616 
617 /* md_gdtcf(): (Get Default Termcap File)
618  *
619  * This function is called ONLY when the program is compiled with CURSES
620  * defined.  If you use your system's curses/termlib library, this function
621  * won't be called.  On most UNIX systems, "/etc/termcap" suffices.
622  *
623  * If their is no such termcap file, then return 0, but in that case, you
624  * must have a TERMCAP file returned from md_getenv("TERMCAP").  The latter
625  * will override the value returned from md_gdtcf().  If the program is
626  * compiled with CURSES defined, and md_gdtcf() returns 0, and
627  * md_getenv("TERMCAP") returns 0, the program will have no terminal
628  * capability information and will quit.
629  */
630 
631 char *
632 md_gdtcf()
633 {
634 	return("/etc/termcap");
635 }
636 
637 /* md_tstp():
638  *
639  * This function puts the game to sleep and returns to the shell.  This
640  * only applies to UNIX 4.2 and 4.3.  For other systems, the routine should
641  * be provided as a do-nothing routine.  md_tstp() will only be referenced
642  * in the code when compiled with CURSES defined.
643  *
644  */
645 
646 md_tstp()
647 {
648 #ifdef UNIX_BSD4_2
649 	kill(0, SIGTSTP);
650 #endif
651 }
652 
653 #endif
654 
655 #endif
656