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