xref: /netbsd-src/games/hack/hack.unix.c (revision da9817918ec7e88db2912a2882967c7570a83f47)
1 /*	$NetBSD: hack.unix.c,v 1.12 2009/06/07 20:13:18 dholland 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.12 2009/06/07 20:13:18 dholland 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(void)
101 {
102 	(void) srandom((int) time((time_t *) 0));
103 }
104 
105 struct tm      *
106 getlt(void)
107 {
108 	time_t          date;
109 
110 	(void) time(&date);
111 	return (localtime(&date));
112 }
113 
114 int
115 getyear(void)
116 {
117 	return (1900 + getlt()->tm_year);
118 }
119 
120 char           *
121 getdatestr(void)
122 {
123 	static char     datestr[7];
124 	struct tm      *lt = getlt();
125 
126 	(void) snprintf(datestr, sizeof(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(void)
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(void)
150 {
151 	int             hour = getlt()->tm_hour;
152 
153 	return (hour < 6 || hour > 21);
154 }
155 
156 int
157 midnight(void)
158 {
159 	return (getlt()->tm_hour == 0);
160 }
161 
162 struct stat     buf, hbuf;
163 
164 void
165 gethdate(char *name)
166 {
167 #if 0
168 	/* old version - for people short of space */
169 
170 	char *np;
171 
172 	if(stat(name, &hbuf))
173 	    error("Cannot get status of %s.",
174 		(np = strrchr(name, '/')) ? np+1 : name);
175 #else
176 	/* version using PATH from: seismo!gregc@ucsf-cgl.ARPA (Greg Couch) */
177 
178 
179 	/*
180 	 * The problem with   #include	<sys/param.h>   is that this include file
181 	 * does not exist on all systems, and moreover, that it sometimes includes
182 	 * <sys/types.h> again, so that the compiler sees these typedefs twice.
183 	 */
184 #define		MAXPATHLEN	1024
185 
186 	const char           *np, *path;
187 	char            filename[MAXPATHLEN + 1];
188 	if (strchr(name, '/') != NULL || (path = getenv("PATH")) == NULL)
189 		path = "";
190 
191 	for (;;) {
192 		if ((np = strchr(path, ':')) == NULL)
193 			np = path + strlen(path);	/* point to end str */
194 		if (np - path <= 1)	/* %% */
195 			(void) strcpy(filename, name);
196 		else {
197 			(void) strncpy(filename, path, np - path);
198 			filename[np - path] = '/';
199 			(void) strcpy(filename + (np - path) + 1, name);
200 		}
201 		if (stat(filename, &hbuf) == 0)
202 			return;
203 		if (*np == '\0')
204 			break;
205 		path = np + 1;
206 	}
207 	error("Cannot get status of %s.",
208 	      (np = strrchr(name, '/')) ? np + 1 : name);
209 #endif
210 }
211 
212 int
213 uptodate(int fd)
214 {
215 	if (fstat(fd, &buf)) {
216 		pline("Cannot get status of saved level? ");
217 		return (0);
218 	}
219 	if (buf.st_mtime < hbuf.st_mtime) {
220 		pline("Saved level is out of date. ");
221 		return (0);
222 	}
223 	return (1);
224 }
225 
226 /* see whether we should throw away this xlock file */
227 int
228 veryold(int fd)
229 {
230 	int             i;
231 	time_t          date;
232 
233 	if (fstat(fd, &buf))
234 		return (0);	/* cannot get status */
235 	if (buf.st_size != sizeof(int))
236 		return (0);	/* not an xlock file */
237 	(void) time(&date);
238 	if (date - buf.st_mtime < 3L * 24L * 60L * 60L) {	/* recent */
239 		int             lockedpid;	/* should be the same size as
240 						 * hackpid */
241 
242 		if (read(fd, (char *) &lockedpid, sizeof(lockedpid)) !=
243 		    sizeof(lockedpid))
244 			/* strange ... */
245 			return (0);
246 
247 		/*
248 		 * From: Rick Adams <seismo!rick> This will work on
249 		 * 4.1cbsd, 4.2bsd and system 3? & 5. It will do nothing
250 		 * on V7 or 4.1bsd.
251 		 */
252 		if (!(kill(lockedpid, 0) == -1 && errno == ESRCH))
253 			return (0);
254 	}
255 	(void) close(fd);
256 	for (i = 1; i <= MAXLEVEL; i++) {	/* try to remove all */
257 		glo(i);
258 		(void) unlink(lock);
259 	}
260 	glo(0);
261 	if (unlink(lock))
262 		return (0);	/* cannot remove it */
263 	return (1);		/* success! */
264 }
265 
266 void
267 getlock(void)
268 {
269 	int             i = 0, fd;
270 
271 	(void) fflush(stdout);
272 
273 	/* we ignore QUIT and INT at this point */
274 	if (link(HLOCK, LLOCK) == -1) {
275 		int             errnosv = errno;
276 
277 		perror(HLOCK);
278 		printf("Cannot link %s to %s\n", LLOCK, HLOCK);
279 		switch (errnosv) {
280 		case ENOENT:
281 			printf("Perhaps there is no (empty) file %s ?\n", HLOCK);
282 			break;
283 		case EACCES:
284 			printf("It seems you don't have write permission here.\n");
285 			break;
286 		case EEXIST:
287 			printf("(Try again or rm %s.)\n", LLOCK);
288 			break;
289 		default:
290 			printf("I don't know what is wrong.");
291 		}
292 		getret();
293 		error("%s", "");
294 		/* NOTREACHED */
295 	}
296 	regularize(lock);
297 	glo(0);
298 	if (locknum > 25)
299 		locknum = 25;
300 
301 	do {
302 		if (locknum)
303 			lock[0] = 'a' + i++;
304 
305 		if ((fd = open(lock, O_RDONLY)) == -1) {
306 			if (errno == ENOENT)
307 				goto gotlock;	/* no such file */
308 			perror(lock);
309 			(void) unlink(LLOCK);
310 			error("Cannot open %s", lock);
311 		}
312 		if (veryold(fd))/* if true, this closes fd and unlinks lock */
313 			goto gotlock;
314 		(void) close(fd);
315 	} while (i < locknum);
316 
317 	(void) unlink(LLOCK);
318 	error(locknum ? "Too many hacks running now."
319 	      : "There is a game in progress under your name.");
320 gotlock:
321 	fd = creat(lock, FMASK);
322 	if (unlink(LLOCK) == -1)
323 		error("Cannot unlink %s.", LLOCK);
324 	if (fd == -1) {
325 		error("cannot creat lock file.");
326 	} else {
327 		if (write(fd, (char *) &hackpid, sizeof(hackpid))
328 		    != sizeof(hackpid)) {
329 			error("cannot write lock");
330 		}
331 		if (close(fd) == -1) {
332 			error("cannot close lock");
333 		}
334 	}
335 }
336 
337 #ifdef MAIL
338 
339 /*
340  * Notify user when new mail has arrived. [Idea from Merlyn Leroy, but
341  * I don't know the details of his implementation.]
342  * { Later note: he disliked my calling a general mailreader and felt that
343  *   hack should do the paging itself. But when I get mail, I want to put it
344  *   in some folder, reply, etc. - it would be unreasonable to put all these
345  *   functions in hack. }
346  * The mail daemon '2' is at present not a real monster, but only a visual
347  * effect. Thus, makemon() is superfluous. This might become otherwise,
348  * however. The motion of '2' is less restrained than usual: diagonal moves
349  * from a DOOR are possible. He might also use SDOOR's. Also, '2' is visible
350  * in a ROOM, even when you are Blind.
351  * Its path should be longer when you are Telepat-hic and Blind.
352  *
353  * Interesting side effects:
354  *	- You can get rich by sending yourself a lot of mail and selling
355  *	  it to the shopkeeper. Unfortunately mail isn't very valuable.
356  *	- You might die in case '2' comes along at a critical moment during
357  *	  a fight and delivers a scroll the weight of which causes you to
358  *	  collapse.
359  *
360  * Possible extensions:
361  *	- Open the file MAIL and do fstat instead of stat for efficiency.
362  *	  (But sh uses stat, so this cannot be too bad.)
363  *	- Examine the mail and produce a scroll of mail called "From somebody".
364  *	- Invoke MAILREADER in such a way that only this single letter is read.
365  *
366  *	- Make him lose his mail when a Nymph steals the letter.
367  *	- Do something to the text when the scroll is enchanted or cancelled.
368  */
369 #include	"def.mkroom.h"
370 static struct stat omstat, nmstat;
371 static char    *mailbox;
372 static long     laststattime;
373 
374 void
375 getmailstatus(void)
376 {
377 	if (!(mailbox = getenv("MAIL")))
378 		return;
379 	if (stat(mailbox, &omstat)) {
380 #ifdef PERMANENT_MAILBOX
381 		pline("Cannot get status of MAIL=%s .", mailbox);
382 		mailbox = 0;
383 #else
384 		omstat.st_mtime = 0;
385 #endif	/* PERMANENT_MAILBOX */
386 	}
387 }
388 
389 void
390 ckmailstatus(void)
391 {
392 	if (!mailbox
393 #ifdef MAILCKFREQ
394 	    || moves < laststattime + MAILCKFREQ
395 #endif	/* MAILCKFREQ */
396 		)
397 		return;
398 	laststattime = moves;
399 	if (stat(mailbox, &nmstat)) {
400 #ifdef PERMANENT_MAILBOX
401 		pline("Cannot get status of MAIL=%s anymore.", mailbox);
402 		mailbox = 0;
403 #else
404 		nmstat.st_mtime = 0;
405 #endif	/* PERMANENT_MAILBOX */
406 	} else if (nmstat.st_mtime > omstat.st_mtime) {
407 		if (nmstat.st_size)
408 			newmail();
409 		getmailstatus();/* might be too late ... */
410 	}
411 }
412 
413 void
414 newmail(void)
415 {
416 	/* produce a scroll of mail */
417 	struct obj     *obj;
418 	struct monst   *md;
419 
420 	obj = mksobj(SCR_MAIL);
421 	if (md = makemon(&pm_mail_daemon, u.ux, u.uy))	/* always succeeds */
422 		mdrush(md, 0);
423 
424 	pline("\"Hello, %s! I have some mail for you.\"", plname);
425 	if (md) {
426 		if (dist(md->mx, md->my) > 2)
427 			pline("\"Catch!\"");
428 		more();
429 
430 		/* let him disappear again */
431 		mdrush(md, 1);
432 		mondead(md);
433 	}
434 	obj = addinv(obj);
435 	(void) identify(obj);	/* set known and do prinv() */
436 }
437 
438 /* make md run through the cave */
439 void
440 mdrush(struct monst *md, boolean away)
441 {
442 	int             uroom = inroom(u.ux, u.uy);
443 	if (uroom >= 0) {
444 		int             tmp = rooms[uroom].fdoor;
445 		int             cnt = rooms[uroom].doorct;
446 		int             fx = u.ux, fy = u.uy;
447 		while (cnt--) {
448 			if (dist(fx, fy) < dist(doors[tmp].x, doors[tmp].y)) {
449 				fx = doors[tmp].x;
450 				fy = doors[tmp].y;
451 			}
452 			tmp++;
453 		}
454 		tmp_at(-1, md->data->mlet);	/* open call */
455 		if (away) {	/* interchange origin and destination */
456 			unpmon(md);
457 			tmp = fx;
458 			fx = md->mx;
459 			md->mx = tmp;
460 			tmp = fy;
461 			fy = md->my;
462 			md->my = tmp;
463 		}
464 		while (fx != md->mx || fy != md->my) {
465 			int             dx, dy, nfx = fx, nfy = fy, d1,
466 			                d2;
467 
468 			tmp_at(fx, fy);
469 			d1 = DIST(fx, fy, md->mx, md->my);
470 			for (dx = -1; dx <= 1; dx++)
471 				for (dy = -1; dy <= 1; dy++)
472 					if (dx || dy) {
473 						d2 = DIST(fx + dx, fy + dy, md->mx, md->my);
474 						if (d2 < d1) {
475 							d1 = d2;
476 							nfx = fx + dx;
477 							nfy = fy + dy;
478 						}
479 					}
480 			if (nfx != fx || nfy != fy) {
481 				fx = nfx;
482 				fy = nfy;
483 			} else {
484 				if (!away) {
485 					md->mx = fx;
486 					md->my = fy;
487 				}
488 				break;
489 			}
490 		}
491 		tmp_at(-1, -1);	/* close call */
492 	}
493 	if (!away)
494 		pmon(md);
495 }
496 
497 void
498 readmail(void)
499 {
500 #ifdef DEF_MAILREADER		/* This implies that UNIX is defined */
501 	char           *mr = 0;
502 	more();
503 	if (!(mr = getenv("MAILREADER")))
504 		mr = DEF_MAILREADER;
505 	if (child(1)) {
506 		execl(mr, mr, (char *) 0);
507 		exit(1);
508 	}
509 #else	/* DEF_MAILREADER */
510 	(void) page_file(mailbox, FALSE);
511 #endif	/* DEF_MAILREADER */
512 	/*
513 	 * get new stat; not entirely correct: there is a small time window
514 	 * where we do not see new mail
515 	 */
516 	getmailstatus();
517 }
518 #endif	/* MAIL */
519 
520 /*
521  * normalize file name - we don't like ..'s or /'s
522  */
523 void
524 regularize(char *s)
525 {
526 	char           *lp;
527 
528 	while ((lp = strchr(s, '.')) || (lp = strchr(s, '/')))
529 		*lp = '_';
530 }
531