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