Buglet in last commit, the first argument of bpf_ptap is the actual bpf_if.
[dragonfly.git] / games / rogue / machdep.c
1 /*
2  * Copyright (c) 1988, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Timothy C. Stoehr.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by the University of
19  *      California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * @(#)machdep.c        8.1 (Berkeley) 5/31/93
37  * $FreeBSD: src/games/rogue/machdep.c,v 1.6.2.1 2001/12/17 12:43:23 phantom Exp $
38  * $DragonFly: src/games/rogue/machdep.c,v 1.2 2003/06/17 04:25:24 dillon Exp $
39  */
40
41 /*
42  * machdep.c
43  *
44  * This source herein may be modified and/or distributed by anybody who
45  * so desires, with the following restrictions:
46  *    1.)  No portion of this notice shall be removed.
47  *    2.)  Credit shall not be taken for the creation of this source.
48  *    3.)  This code is not to be traded, sold, or used for personal
49  *         gain or profit.
50  *
51  */
52
53 /* Included in this file are all system dependent routines.  Extensive use
54  * of #ifdef's will be used to compile the appropriate code on each system:
55  *
56  *    UNIX:        all UNIX systems.
57  *    UNIX_BSD4_2: UNIX BSD 4.2 and later, UTEK, (4.1 BSD too?)
58  *    UNIX_SYSV:   UNIX system V
59  *    UNIX_V7:     UNIX version 7
60  *
61  * All UNIX code should be included between the single "#ifdef UNIX" at the
62  * top of this file, and the "#endif" at the bottom.
63  *
64  * To change a routine to include a new UNIX system, simply #ifdef the
65  * existing routine, as in the following example:
66  *
67  *   To make a routine compatible with UNIX system 5, change the first
68  *   function to the second:
69  *
70  *      md_function()
71  *      {
72  *         code;
73  *      }
74  *
75  *      md_function()
76  *      {
77  *      #ifdef UNIX_SYSV
78  *         sys5code;
79  *      #else
80  *         code;
81  *      #endif
82  *      }
83  *
84  * Appropriate variations of this are of course acceptible.
85  * The use of "#elseif" is discouraged because of non-portability.
86  * If the correct #define doesn't exist, "UNIX_SYSV" in this case, make it up
87  * and insert it in the list at the top of the file.  Alter the CFLAGS
88  * in you Makefile appropriately.
89  *
90  */
91
92 #ifdef UNIX
93
94 #include <stdio.h>
95 #include <sys/types.h>
96 #include <sys/file.h>
97 #include <sys/stat.h>
98 #include <pwd.h>
99
100 #ifdef UNIX_BSD4_2
101 #include <sys/time.h>
102 #include <sgtty.h>
103 #endif
104
105 #ifdef UNIX_SYSV
106 #include <time.h>
107 #include <termio.h>
108 #endif
109
110 #include <signal.h>
111 #include <stdlib.h>
112 #include <unistd.h>
113 #include "rogue.h"
114 #include "pathnames.h"
115
116 /* md_slurp:
117  *
118  * This routine throws away all keyboard input that has not
119  * yet been read.  It is used to get rid of input that the user may have
120  * typed-ahead.
121  *
122  * This function is not necessary, so it may be stubbed.  The might cause
123  * message-line output to flash by because the game has continued to read
124  * input without waiting for the user to read the message.  Not such a
125  * big deal.
126  */
127
128 md_slurp()
129 {
130         (void)fpurge(stdin);
131 }
132
133 /* md_control_keyboard():
134  *
135  * This routine is much like md_cbreak_no_echo_nonl() below.  It sets up the
136  * keyboard for appropriate input.  Specifically, it prevents the tty driver
137  * from stealing characters.  For example, ^Y is needed as a command
138  * character, but the tty driver intercepts it for another purpose.  Any
139  * such behavior should be stopped.  This routine could be avoided if
140  * we used RAW mode instead of CBREAK.  But RAW mode does not allow the
141  * generation of keyboard signals, which the program uses.
142  *
143  * The parameter 'mode' when true, indicates that the keyboard should
144  * be set up to play rogue.  When false, it should be restored if
145  * necessary.
146  *
147  * This routine is not strictly necessary and may be stubbed.  This may
148  * cause certain command characters to be unavailable.
149  */
150
151 md_control_keybord(mode)
152 boolean mode;
153 {
154         static boolean called_before = 0;
155 #ifdef UNIX_BSD4_2
156         static struct ltchars ltc_orig;
157         static struct tchars tc_orig;
158         struct ltchars ltc_temp;
159         struct tchars tc_temp;
160 #endif
161 #ifdef UNIX_SYSV
162         static struct termio _oldtty;
163         struct termio _tty;
164 #endif
165
166         if (!called_before) {
167                 called_before = 1;
168 #ifdef UNIX_BSD4_2
169                 ioctl(0, TIOCGETC, &tc_orig);
170                 ioctl(0, TIOCGLTC, &ltc_orig);
171 #endif
172 #ifdef UNIX_SYSV
173                 ioctl(0, TCGETA, &_oldtty);
174 #endif
175         }
176 #ifdef UNIX_BSD4_2
177         ltc_temp = ltc_orig;
178         tc_temp = tc_orig;
179 #endif
180 #ifdef UNIX_SYSV
181         _tty = _oldtty;
182 #endif
183
184         if (!mode) {
185 #ifdef UNIX_BSD4_2
186                 ltc_temp.t_suspc = ltc_temp.t_dsuspc = -1;
187                 ltc_temp.t_rprntc = ltc_temp.t_flushc = -1;
188                 ltc_temp.t_werasc = ltc_temp.t_lnextc = -1;
189                 tc_temp.t_startc = tc_temp.t_stopc = -1;
190 #endif
191 #ifdef UNIX_SYSV
192                 _tty.c_cc[VSWTCH] = CNSWTCH;
193 #endif
194         }
195 #ifdef UNIX_BSD4_2
196         ioctl(0, TIOCSETC, &tc_temp);
197         ioctl(0, TIOCSLTC, &ltc_temp);
198 #endif
199 #ifdef UNIX_SYSV
200         ioctl(0, TCSETA, &_tty);
201 #endif
202 }
203
204 /* md_heed_signals():
205  *
206  * This routine tells the program to call particular routines when
207  * certain interrupts/events occur:
208  *
209  *      SIGINT: call onintr() to interrupt fight with monster or long rest.
210  *      SIGQUIT: call byebye() to check for game termination.
211  *      SIGHUP: call error_save() to save game when terminal hangs up.
212  *
213  *              On VMS, SIGINT and SIGQUIT correspond to ^C and ^Y.
214  *
215  * This routine is not strictly necessary and can be stubbed.  This will
216  * mean that the game cannot be interrupted properly with keyboard
217  * input, this is not usually critical.
218  */
219
220 md_heed_signals()
221 {
222         signal(SIGINT, onintr);
223         signal(SIGQUIT, byebye);
224         signal(SIGHUP, error_save);
225 }
226
227 /* md_ignore_signals():
228  *
229  * This routine tells the program to completely ignore the events mentioned
230  * in md_heed_signals() above.  The event handlers will later be turned on
231  * by a future call to md_heed_signals(), so md_heed_signals() and
232  * md_ignore_signals() need to work together.
233  *
234  * This function should be implemented or the user risks interrupting
235  * critical sections of code, which could cause score file, or saved-game
236  * file, corruption.
237  */
238
239 md_ignore_signals()
240 {
241         signal(SIGQUIT, SIG_IGN);
242         signal(SIGINT, SIG_IGN);
243         signal(SIGHUP, SIG_IGN);
244 }
245
246 /* md_get_file_id():
247  *
248  * This function returns an integer that uniquely identifies the specified
249  * file.  It need not check for the file's existence.  In UNIX, the inode
250  * number is used.
251  *
252  * This function is used to identify saved-game files.
253  */
254
255 int
256 md_get_file_id(fname)
257 const char *fname;
258 {
259         struct stat sbuf;
260
261         if (stat(fname, &sbuf)) {
262                 return(-1);
263         }
264         return((int) sbuf.st_ino);
265 }
266
267 /* md_link_count():
268  *
269  * This routine returns the number of hard links to the specified file.
270  *
271  * This function is not strictly necessary.  On systems without hard links
272  * this routine can be stubbed by just returning 1.
273  */
274
275 int
276 md_link_count(fname)
277 const char *fname;
278 {
279         struct stat sbuf;
280
281         stat(fname, &sbuf);
282         return((int) sbuf.st_nlink);
283 }
284
285 /* md_gct(): (Get Current Time)
286  *
287  * This function returns the current year, month(1-12), day(1-31), hour(0-23),
288  * minute(0-59), and second(0-59).  This is used for identifying the time
289  * at which a game is saved.
290  *
291  * This function is not strictly necessary.  It can be stubbed by returning
292  * zeros instead of the correct year, month, etc.  If your operating
293  * system doesn't provide all of the time units requested here, then you
294  * can provide only those that it does, and return zeros for the others.
295  * If you cannot provide good time values, then users may be able to copy
296  * saved-game files and play them.
297  */
298
299 md_gct(rt_buf)
300 struct rogue_time *rt_buf;
301 {
302         struct tm *t, *localtime();
303         time_t seconds;
304
305         time(&seconds);
306         t = localtime(&seconds);
307
308         rt_buf->year = t->tm_year;
309         rt_buf->month = t->tm_mon + 1;
310         rt_buf->day = t->tm_mday;
311         rt_buf->hour = t->tm_hour;
312         rt_buf->minute = t->tm_min;
313         rt_buf->second = t->tm_sec;
314 }
315
316 /* md_gfmt: (Get File Modification Time)
317  *
318  * This routine returns a file's date of last modification in the same format
319  * as md_gct() above.
320  *
321  * This function is not strictly necessary.  It is used to see if saved-game
322  * files have been modified since they were saved.  If you have stubbed the
323  * routine md_gct() above by returning constant values, then you may do
324  * exactly the same here.
325  * Or if md_gct() is implemented correctly, but your system does not provide
326  * file modification dates, you may return some date far in the past so
327  * that the program will never know that a saved-game file being modified.
328  * You may also do this if you wish to be able to restore games from
329  * saved-games that have been modified.
330  */
331
332 md_gfmt(fname, rt_buf)
333 const char *fname;
334 struct rogue_time *rt_buf;
335 {
336         struct stat sbuf;
337         time_t seconds;
338         struct tm *t;
339
340         stat(fname, &sbuf);
341         seconds = sbuf.st_mtime;
342         t = localtime(&seconds);
343
344         rt_buf->year = t->tm_year;
345         rt_buf->month = t->tm_mon + 1;
346         rt_buf->day = t->tm_mday;
347         rt_buf->hour = t->tm_hour;
348         rt_buf->minute = t->tm_min;
349         rt_buf->second = t->tm_sec;
350 }
351
352 /* md_df: (Delete File)
353  *
354  * This function deletes the specified file, and returns true (1) if the
355  * operation was successful.  This is used to delete saved-game files
356  * after restoring games from them.
357  *
358  * Again, this function is not strictly necessary, and can be stubbed
359  * by simply returning 1.  In this case, saved-game files will not be
360  * deleted and can be replayed.
361  */
362
363 boolean
364 md_df(fname)
365 const char *fname;
366 {
367         if (unlink(fname)) {
368                 return(0);
369         }
370         return(1);
371 }
372
373 /* md_gln: (Get login name)
374  *
375  * This routine returns the login name of the user.  This string is
376  * used mainly for identifying users in score files.
377  *
378  * A dummy string may be returned if you are unable to implement this
379  * function, but then the score file would only have one name in it.
380  */
381
382 const char *
383 md_gln()
384 {
385         struct passwd *p;
386         char *s;
387
388         if ((s = getlogin()))
389                 return s;
390         if (!(p = getpwuid(getuid())))
391                 return((char *)NULL);
392         return(p->pw_name);
393 }
394
395 /* md_sleep:
396  *
397  * This routine causes the game to pause for the specified number of
398  * seconds.
399  *
400  * This routine is not particularly necessary at all.  It is used for
401  * delaying execution, which is useful to this program at some times.
402  */
403
404 md_sleep(nsecs)
405 int nsecs;
406 {
407         (void) sleep(nsecs);
408 }
409
410 /* md_getenv()
411  *
412  * This routine gets certain values from the user's environment.  These
413  * values are strings, and each string is identified by a name.  The names
414  * of the values needed, and their use, is as follows:
415  *
416  *   ROGUEOPTS
417  *     A string containing the various game options.  This need not be
418  *     defined.
419  *   HOME
420  *     The user's home directory.  This is only used when the user specifies
421  *     '~' as the first character of a saved-game file.  This string need
422  *     not be defined.
423  *   SHELL
424  *     The user's favorite shell.  If not found, "/bin/sh" is assumed.
425  *
426  */
427
428 char *
429 md_getenv(name)
430 const char *name;
431 {
432         char *value;
433
434         value = getenv(name);
435
436         return(value);
437 }
438
439 /* md_malloc()
440  *
441  * This routine allocates, and returns a pointer to, the specified number
442  * of bytes.  This routines absolutely MUST be implemented for your
443  * particular system or the program will not run at all.  Return zero
444  * when no more memory can be allocated.
445  */
446
447 char *
448 md_malloc(n)
449 int n;
450 {
451         char *t;
452
453         t = malloc(n);
454         return(t);
455 }
456
457 /* md_gseed() (Get Seed)
458  *
459  * This function returns a seed for the random number generator (RNG).  This
460  * seed causes the RNG to begin generating numbers at some point in it's
461  * sequence.  Without a random seed, the RNG will generate the same set
462  * of numbers, and every game will start out exactly the same way.  A good
463  * number to use is the process id, given by getpid() on most UNIX systems.
464  *
465  * You need to find some single random integer, such as:
466  *   process id.
467  *   current time (minutes + seconds) returned from md_gct(), if implemented.
468  *
469  * It will not help to return "get_rand()" or "rand()" or the return value of
470  * any pseudo-RNG.  If you don't have a random number, you can just return 1,
471  * but this means your games will ALWAYS start the same way, and will play
472  * exactly the same way given the same input.
473  */
474
475 md_gseed()
476 {
477         time_t seconds;
478
479         time(&seconds);
480         return((int) seconds);
481 }
482
483 /* md_exit():
484  *
485  * This function causes the program to discontinue execution and exit.
486  * This function must be implemented or the program will continue to
487  * hang when it should quit.
488  */
489
490 md_exit(status)
491 int status;
492 {
493         exit(status);
494 }
495
496 /* md_lock():
497  *
498  * This function is intended to give the user exclusive access to the score
499  * file.  It does so by flock'ing the score file.  The full path name of the
500  * score file should be defined for any particular site in rogue.h.  The
501  * constants _PATH_SCOREFILE defines this file name.
502  *
503  * When the parameter 'l' is non-zero (true), a lock is requested.  Otherwise
504  * the lock is released.
505  */
506
507 md_lock(l)
508 boolean l;
509 {
510         static int fd;
511         short tries;
512
513         if (l) {
514                 if ((fd = open(_PATH_SCOREFILE, O_RDONLY)) < 1) {
515                         message("cannot lock score file", 0);
516                         return;
517                 }
518                 for (tries = 0; tries < 5; tries++)
519                         if (!flock(fd, LOCK_EX|LOCK_NB))
520                                 return;
521         } else {
522                 (void)flock(fd, LOCK_NB);
523                 (void)close(fd);
524         }
525 }
526
527 /* md_shell():
528  *
529  * This function spawns a shell for the user to use.  When this shell is
530  * terminated, the game continues.  Since this program may often be run
531  * setuid to gain access to privileged files, care is taken that the shell
532  * is run with the user's REAL user id, and not the effective user id.
533  * The effective user id is restored after the shell completes.
534  */
535
536 md_shell(shell)
537 const char *shell;
538 {
539         long w[2];
540
541         if (!fork()) {
542                 /* revoke */
543                 setgid(getgid());
544                 execl(shell, shell, 0);
545         }
546         wait(w);
547 }
548
549 #endif /* UNIX */