xref: /netbsd-src/games/hack/hack.unix.c (revision aaf4ece63a859a04e37cf3a7229b5fab0157cc06)
1 /*	$NetBSD: hack.unix.c,v 1.9 2003/04/02 18:36:41 jsm Exp $	*/
2 
3 /*
4  * Copyright (c) 1985, Stichting Centrum voor Wiskunde en Informatica,
5  * Amsterdam
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are
10  * met:
11  *
12  * - Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * - Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in the
17  * documentation and/or other materials provided with the distribution.
18  *
19  * - Neither the name of the Stichting Centrum voor Wiskunde en
20  * Informatica, nor the names of its contributors may be used to endorse or
21  * promote products derived from this software without specific prior
22  * written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
25  * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
26  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
27  * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
28  * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
30  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
31  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
33  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35  */
36 
37 /*
38  * Copyright (c) 1982 Jay Fenlason <hack@gnu.org>
39  * All rights reserved.
40  *
41  * Redistribution and use in source and binary forms, with or without
42  * modification, are permitted provided that the following conditions
43  * are met:
44  * 1. Redistributions of source code must retain the above copyright
45  *    notice, this list of conditions and the following disclaimer.
46  * 2. Redistributions in binary form must reproduce the above copyright
47  *    notice, this list of conditions and the following disclaimer in the
48  *    documentation and/or other materials provided with the distribution.
49  * 3. The name of the author may not be used to endorse or promote products
50  *    derived from this software without specific prior written permission.
51  *
52  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
53  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
54  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
55  * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
56  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
57  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
58  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
59  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
60  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
61  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
62  */
63 
64 #include <sys/cdefs.h>
65 #ifndef lint
66 __RCSID("$NetBSD: hack.unix.c,v 1.9 2003/04/02 18:36:41 jsm Exp $");
67 #endif				/* not lint */
68 
69 /* This file collects some Unix dependencies; hack.pager.c contains some more */
70 
71 /*
72  * The time is used for:
73  *	- seed for random()
74  *	- year on tombstone and yymmdd in record file
75  *	- phase of the moon (various monsters react to NEW_MOON or FULL_MOON)
76  *	- night and midnight (the undead are dangerous at midnight)
77  *	- determination of what files are "very old"
78  */
79 
80 #include <errno.h>
81 #include <sys/types.h>	/* for time_t and stat */
82 #include <sys/stat.h>
83 #ifdef BSD
84 #include <sys/time.h>
85 #else
86 #include <time.h>
87 #endif	/* BSD */
88 #include <stdlib.h>
89 #include <unistd.h>
90 #include <signal.h>
91 #include <fcntl.h>
92 
93 #include "hack.h"		/* mainly for strchr() which depends on BSD */
94 #include "extern.h"
95 
96 extern int locknum;
97 
98 
99 void
100 setrandom()
101 {
102 	(void) srandom((int) time((time_t *) 0));
103 }
104 
105 struct tm      *
106 getlt()
107 {
108 	time_t          date;
109 
110 	(void) time(&date);
111 	return (localtime(&date));
112 }
113 
114 int
115 getyear()
116 {
117 	return (1900 + getlt()->tm_year);
118 }
119 
120 char           *
121 getdate()
122 {
123 	static char     datestr[7];
124 	struct tm      *lt = getlt();
125 
126 	(void) sprintf(datestr, "%02d%02d%02d",
127 		       lt->tm_year % 100, lt->tm_mon + 1, lt->tm_mday);
128 	return (datestr);
129 }
130 
131 int
132 phase_of_the_moon()
133 {				/* 0-7, with 0: new, 4: full *//* moon
134 				 * period: 29.5306 days */
135 	/* year: 365.2422 days */
136 	struct tm      *lt = getlt();
137 	int             epact, diy, golden;
138 
139 	diy = lt->tm_yday;
140 	golden = (lt->tm_year % 19) + 1;
141 	epact = (11 * golden + 18) % 30;
142 	if ((epact == 25 && golden > 11) || epact == 24)
143 		epact++;
144 
145 	return ((((((diy + epact) * 6) + 11) % 177) / 22) & 7);
146 }
147 
148 int
149 night()
150 {
151 	int             hour = getlt()->tm_hour;
152 
153 	return (hour < 6 || hour > 21);
154 }
155 
156 int
157 midnight()
158 {
159 	return (getlt()->tm_hour == 0);
160 }
161 
162 struct stat     buf, hbuf;
163 
164 void
165 gethdate(name)
166 	char           *name;
167 {
168 #if 0
169 	/* old version - for people short of space */
170 
171 	char *np;
172 
173 	if(stat(name, &hbuf))
174 	    error("Cannot get status of %s.",
175 		(np = strrchr(name, '/')) ? np+1 : name);
176 #else
177 	/* version using PATH from: seismo!gregc@ucsf-cgl.ARPA (Greg Couch) */
178 
179 
180 	/*
181 	 * The problem with   #include	<sys/param.h>   is that this include file
182 	 * does not exist on all systems, and moreover, that it sometimes includes
183 	 * <sys/types.h> again, so that the compiler sees these typedefs twice.
184 	 */
185 #define		MAXPATHLEN	1024
186 
187 	const char           *np, *path;
188 	char            filename[MAXPATHLEN + 1];
189 	if (strchr(name, '/') != NULL || (path = getenv("PATH")) == NULL)
190 		path = "";
191 
192 	for (;;) {
193 		if ((np = strchr(path, ':')) == NULL)
194 			np = path + strlen(path);	/* point to end str */
195 		if (np - path <= 1)	/* %% */
196 			(void) strcpy(filename, name);
197 		else {
198 			(void) strncpy(filename, path, np - path);
199 			filename[np - path] = '/';
200 			(void) strcpy(filename + (np - path) + 1, name);
201 		}
202 		if (stat(filename, &hbuf) == 0)
203 			return;
204 		if (*np == '\0')
205 			break;
206 		path = np + 1;
207 	}
208 	error("Cannot get status of %s.",
209 	      (np = strrchr(name, '/')) ? np + 1 : name);
210 #endif
211 }
212 
213 int
214 uptodate(int fd)
215 {
216 	if (fstat(fd, &buf)) {
217 		pline("Cannot get status of saved level? ");
218 		return (0);
219 	}
220 	if (buf.st_mtime < hbuf.st_mtime) {
221 		pline("Saved level is out of date. ");
222 		return (0);
223 	}
224 	return (1);
225 }
226 
227 /* see whether we should throw away this xlock file */
228 int
229 veryold(fd)
230 	int fd;
231 {
232 	int             i;
233 	time_t          date;
234 
235 	if (fstat(fd, &buf))
236 		return (0);	/* cannot get status */
237 	if (buf.st_size != sizeof(int))
238 		return (0);	/* not an xlock file */
239 	(void) time(&date);
240 	if (date - buf.st_mtime < 3L * 24L * 60L * 60L) {	/* recent */
241 		int             lockedpid;	/* should be the same size as
242 						 * hackpid */
243 
244 		if (read(fd, (char *) &lockedpid, sizeof(lockedpid)) !=
245 		    sizeof(lockedpid))
246 			/* strange ... */
247 			return (0);
248 
249 		/*
250 		 * From: Rick Adams <seismo!rick> This will work on
251 		 * 4.1cbsd, 4.2bsd and system 3? & 5. It will do nothing
252 		 * on V7 or 4.1bsd.
253 		 */
254 		if (!(kill(lockedpid, 0) == -1 && errno == ESRCH))
255 			return (0);
256 	}
257 	(void) close(fd);
258 	for (i = 1; i <= MAXLEVEL; i++) {	/* try to remove all */
259 		glo(i);
260 		(void) unlink(lock);
261 	}
262 	glo(0);
263 	if (unlink(lock))
264 		return (0);	/* cannot remove it */
265 	return (1);		/* success! */
266 }
267 
268 void
269 getlock()
270 {
271 	int             i = 0, fd;
272 
273 	(void) fflush(stdout);
274 
275 	/* we ignore QUIT and INT at this point */
276 	if (link(HLOCK, LLOCK) == -1) {
277 		int             errnosv = errno;
278 
279 		perror(HLOCK);
280 		printf("Cannot link %s to %s\n", LLOCK, HLOCK);
281 		switch (errnosv) {
282 		case ENOENT:
283 			printf("Perhaps there is no (empty) file %s ?\n", HLOCK);
284 			break;
285 		case EACCES:
286 			printf("It seems you don't have write permission here.\n");
287 			break;
288 		case EEXIST:
289 			printf("(Try again or rm %s.)\n", LLOCK);
290 			break;
291 		default:
292 			printf("I don't know what is wrong.");
293 		}
294 		getret();
295 		error("%s", "");
296 		/* NOTREACHED */
297 	}
298 	regularize(lock);
299 	glo(0);
300 	if (locknum > 25)
301 		locknum = 25;
302 
303 	do {
304 		if (locknum)
305 			lock[0] = 'a' + i++;
306 
307 		if ((fd = open(lock, O_RDONLY)) == -1) {
308 			if (errno == ENOENT)
309 				goto gotlock;	/* no such file */
310 			perror(lock);
311 			(void) unlink(LLOCK);
312 			error("Cannot open %s", lock);
313 		}
314 		if (veryold(fd))/* if true, this closes fd and unlinks lock */
315 			goto gotlock;
316 		(void) close(fd);
317 	} while (i < locknum);
318 
319 	(void) unlink(LLOCK);
320 	error(locknum ? "Too many hacks running now."
321 	      : "There is a game in progress under your name.");
322 gotlock:
323 	fd = creat(lock, FMASK);
324 	if (unlink(LLOCK) == -1)
325 		error("Cannot unlink %s.", LLOCK);
326 	if (fd == -1) {
327 		error("cannot creat lock file.");
328 	} else {
329 		if (write(fd, (char *) &hackpid, sizeof(hackpid))
330 		    != sizeof(hackpid)) {
331 			error("cannot write lock");
332 		}
333 		if (close(fd) == -1) {
334 			error("cannot close lock");
335 		}
336 	}
337 }
338 
339 #ifdef MAIL
340 
341 /*
342  * Notify user when new mail has arrived. [Idea from Merlyn Leroy, but
343  * I don't know the details of his implementation.]
344  * { Later note: he disliked my calling a general mailreader and felt that
345  *   hack should do the paging itself. But when I get mail, I want to put it
346  *   in some folder, reply, etc. - it would be unreasonable to put all these
347  *   functions in hack. }
348  * The mail daemon '2' is at present not a real monster, but only a visual
349  * effect. Thus, makemon() is superfluous. This might become otherwise,
350  * however. The motion of '2' is less restrained than usual: diagonal moves
351  * from a DOOR are possible. He might also use SDOOR's. Also, '2' is visible
352  * in a ROOM, even when you are Blind.
353  * Its path should be longer when you are Telepat-hic and Blind.
354  *
355  * Interesting side effects:
356  *	- You can get rich by sending yourself a lot of mail and selling
357  *	  it to the shopkeeper. Unfortunately mail isn't very valuable.
358  *	- You might die in case '2' comes along at a critical moment during
359  *	  a fight and delivers a scroll the weight of which causes you to
360  *	  collapse.
361  *
362  * Possible extensions:
363  *	- Open the file MAIL and do fstat instead of stat for efficiency.
364  *	  (But sh uses stat, so this cannot be too bad.)
365  *	- Examine the mail and produce a scroll of mail called "From somebody".
366  *	- Invoke MAILREADER in such a way that only this single letter is read.
367  *
368  *	- Make him lose his mail when a Nymph steals the letter.
369  *	- Do something to the text when the scroll is enchanted or cancelled.
370  */
371 #include	"def.mkroom.h"
372 static struct stat omstat, nmstat;
373 static char    *mailbox;
374 static long     laststattime;
375 
376 void
377 getmailstatus()
378 {
379 	if (!(mailbox = getenv("MAIL")))
380 		return;
381 	if (stat(mailbox, &omstat)) {
382 #ifdef PERMANENT_MAILBOX
383 		pline("Cannot get status of MAIL=%s .", mailbox);
384 		mailbox = 0;
385 #else
386 		omstat.st_mtime = 0;
387 #endif	/* PERMANENT_MAILBOX */
388 	}
389 }
390 
391 void
392 ckmailstatus()
393 {
394 	if (!mailbox
395 #ifdef MAILCKFREQ
396 	    || moves < laststattime + MAILCKFREQ
397 #endif	/* MAILCKFREQ */
398 		)
399 		return;
400 	laststattime = moves;
401 	if (stat(mailbox, &nmstat)) {
402 #ifdef PERMANENT_MAILBOX
403 		pline("Cannot get status of MAIL=%s anymore.", mailbox);
404 		mailbox = 0;
405 #else
406 		nmstat.st_mtime = 0;
407 #endif	/* PERMANENT_MAILBOX */
408 	} else if (nmstat.st_mtime > omstat.st_mtime) {
409 		if (nmstat.st_size)
410 			newmail();
411 		getmailstatus();/* might be too late ... */
412 	}
413 }
414 
415 void
416 newmail()
417 {
418 	/* produce a scroll of mail */
419 	struct obj     *obj;
420 	struct monst   *md;
421 
422 	obj = mksobj(SCR_MAIL);
423 	if (md = makemon(&pm_mail_daemon, u.ux, u.uy))	/* always succeeds */
424 		mdrush(md, 0);
425 
426 	pline("\"Hello, %s! I have some mail for you.\"", plname);
427 	if (md) {
428 		if (dist(md->mx, md->my) > 2)
429 			pline("\"Catch!\"");
430 		more();
431 
432 		/* let him disappear again */
433 		mdrush(md, 1);
434 		mondead(md);
435 	}
436 	obj = addinv(obj);
437 	(void) identify(obj);	/* set known and do prinv() */
438 }
439 
440 /* make md run through the cave */
441 void
442 mdrush(md, away)
443 	struct monst   *md;
444 	boolean         away;
445 {
446 	int             uroom = inroom(u.ux, u.uy);
447 	if (uroom >= 0) {
448 		int             tmp = rooms[uroom].fdoor;
449 		int             cnt = rooms[uroom].doorct;
450 		int             fx = u.ux, fy = u.uy;
451 		while (cnt--) {
452 			if (dist(fx, fy) < dist(doors[tmp].x, doors[tmp].y)) {
453 				fx = doors[tmp].x;
454 				fy = doors[tmp].y;
455 			}
456 			tmp++;
457 		}
458 		tmp_at(-1, md->data->mlet);	/* open call */
459 		if (away) {	/* interchange origin and destination */
460 			unpmon(md);
461 			tmp = fx;
462 			fx = md->mx;
463 			md->mx = tmp;
464 			tmp = fy;
465 			fy = md->my;
466 			md->my = tmp;
467 		}
468 		while (fx != md->mx || fy != md->my) {
469 			int             dx, dy, nfx = fx, nfy = fy, d1,
470 			                d2;
471 
472 			tmp_at(fx, fy);
473 			d1 = DIST(fx, fy, md->mx, md->my);
474 			for (dx = -1; dx <= 1; dx++)
475 				for (dy = -1; dy <= 1; dy++)
476 					if (dx || dy) {
477 						d2 = DIST(fx + dx, fy + dy, md->mx, md->my);
478 						if (d2 < d1) {
479 							d1 = d2;
480 							nfx = fx + dx;
481 							nfy = fy + dy;
482 						}
483 					}
484 			if (nfx != fx || nfy != fy) {
485 				fx = nfx;
486 				fy = nfy;
487 			} else {
488 				if (!away) {
489 					md->mx = fx;
490 					md->my = fy;
491 				}
492 				break;
493 			}
494 		}
495 		tmp_at(-1, -1);	/* close call */
496 	}
497 	if (!away)
498 		pmon(md);
499 }
500 
501 void
502 readmail()
503 {
504 #ifdef DEF_MAILREADER		/* This implies that UNIX is defined */
505 	char           *mr = 0;
506 	more();
507 	if (!(mr = getenv("MAILREADER")))
508 		mr = DEF_MAILREADER;
509 	if (child(1)) {
510 		execl(mr, mr, (char *) 0);
511 		exit(1);
512 	}
513 #else	/* DEF_MAILREADER */
514 	(void) page_file(mailbox, FALSE);
515 #endif	/* DEF_MAILREADER */
516 	/*
517 	 * get new stat; not entirely correct: there is a small time window
518 	 * where we do not see new mail
519 	 */
520 	getmailstatus();
521 }
522 #endif	/* MAIL */
523 
524 void
525 regularize(s)			/* normalize file name - we don't like ..'s
526 				 * or /'s */
527 	char           *s;
528 {
529 	char           *lp;
530 
531 	while ((lp = strchr(s, '.')) || (lp = strchr(s, '/')))
532 		*lp = '_';
533 }
534