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