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