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