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