home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / nethack-3.1 / sys / vms / vmsunix.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-01-24  |  14.7 KB  |  537 lines

  1. /*    SCCS Id: @(#)vmsunix.c    3.1    93/01/24    */
  2. /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
  3. /* NetHack may be freely redistributed.  See license for details. */
  4.  
  5. /* This file implements things from unixunix.c, plus related stuff */
  6.  
  7. #include "hack.h"
  8. #include "date.h"    /* generated by 'makedefs' */
  9.  
  10. #include <descrip.h>
  11. #include <dvidef.h>
  12. #include <jpidef.h>
  13. #include <ssdef.h>
  14. #include <errno.h>
  15. #include <signal.h>
  16. #undef off_t
  17. #ifdef GNUC
  18. #include <sys/stat.h>
  19. #else
  20. #include <stat.h>
  21. #endif
  22. #include <ctype.h>
  23.  
  24. #ifndef L_tmpnam
  25. #define L_tmpnam 256
  26. #endif
  27.  
  28. extern unsigned long SYS$SETPRV();
  29. extern unsigned long LIB$GETDVI(), LIB$GETJPI(), LIB$SPAWN(), LIB$ATTACH();
  30. extern unsigned long SMG$INIT_TERM_TABLE_BY_TYPE(), SMG$DEL_TERM_TABLE();
  31. #define vms_ok(sts) ((sts) & 1) /* odd => success */
  32.  
  33. static long exe_time = BUILD_TIME;
  34.  
  35. static int FDECL(veryold, (int));
  36. static char *NDECL(verify_term);
  37. #if defined(SHELL) || defined(SUSPEND)
  38. static void FDECL(hack_escape, (BOOLEAN_P,const char *));
  39. static void FDECL(hack_resume, (BOOLEAN_P));
  40. #endif
  41.  
  42. void
  43. gethdate(name)        /* get the creation date & time of file 'name' */
  44. const char *name;    /* assumed to be argv[0], full path to nethack.exe */
  45. {
  46.     struct stat hbuf;
  47.     /*
  48.        [f]stat() won't work across a DECnet link.  Would somebody be
  49.        masochistic enough to try ``$ RUN node::NETHACK''?  One hopes
  50.        not, but don't inadvertently forbid it.  If stat() fails, use
  51.        the compile time provided by 'makedefs' instead of just quitting.
  52.        The playground must be local, otherwise all level files will
  53.        fail their status check, but the exe image could be remote.
  54.  
  55.        Note that we care about the executable's creation time, not
  56.        its modification time, since the latter is touched by changing
  57.        file protection or renaming, two naive ways someone might use
  58.        to disable the program during prime time.
  59.      */
  60.     if (stat(name, &hbuf) == 0) exe_time = hbuf.st_ctime;
  61. }
  62.  
  63. boolean
  64. uptodate(fd)
  65. int fd;
  66. {
  67.     struct stat buf;
  68.  
  69.     if (fstat(fd, &buf) != 0)
  70.         pline("Cannot get status of saved level? ");
  71.     else if (buf.st_mtime < exe_time)
  72.         pline("Saved level is out of date. ");
  73.     else
  74.         return TRUE;    /* passed the test */
  75.     wait_synch();
  76.     return FALSE;            /* failed the test */
  77. }
  78.  
  79. static int
  80. veryold(fd)
  81. int fd;
  82. {
  83.     register int i;
  84.     time_t date;
  85.     struct stat buf;
  86.  
  87.     if(fstat(fd, &buf)) return(0);            /* cannot get status */
  88. #ifndef INSURANCE
  89.     if(buf.st_size != sizeof(int)) return(0);    /* not an xlock file */
  90. #endif
  91.     (void) time(&date);
  92.     if(date - buf.st_mtime < 3L*24L*60L*60L) {    /* recent */
  93.         int lockedpid;    /* should be the same size as hackpid */
  94.         unsigned long status, dummy, code = JPI$_PID;
  95.  
  96.         if (read(fd, (genericptr_t)&lockedpid, sizeof(lockedpid)) !=
  97.                 sizeof(lockedpid))    /* strange ... */
  98.             return 0;
  99.         status = LIB$GETJPI(&code, &lockedpid, 0, &dummy);
  100.         if (vms_ok(status) || status != SS$_NONEXPR)
  101.             return 0;
  102.     }
  103.     (void) close(fd);
  104.  
  105.     /* cannot use maxledgerno() here, because we need to find a lock name
  106.      * before starting everything (including the dungeon initialization
  107.      * that sets astral_level, needed for maxledgerno()) up
  108.      */
  109.     for(i = 1; i <= MAXDUNGEON*MAXLEVEL + 1; i++) {
  110.         /* try to remove all */
  111.         set_levelfile_name(lock, i);
  112.         (void) delete(lock);
  113.     }
  114.     set_levelfile_name(lock, 0);
  115.     if(delete(lock)) return(0);            /* cannot remove it */
  116.     return(1);                    /* success! */
  117. }
  118.  
  119. void
  120. getlock()
  121. {
  122.     register int i = 0, fd;
  123.  
  124.     /* idea from rpick%ucqais@uccba.uc.edu
  125.      * prevent automated rerolling of characters
  126.      * test input (fd0) so that tee'ing output to get a screen dump still
  127.      * works
  128.      * also incidentally prevents development of any hack-o-matic programs
  129.      */
  130.     if (isatty(0) <= 0)
  131.         error("You must play from a terminal.");
  132.  
  133.     /* we ignore QUIT and INT at this point */
  134.     if (!lock_file(HLOCK, 10)) {
  135.         wait_synch();
  136.         error("Quitting.");
  137.     }
  138.  
  139.     regularize(lock);
  140.     set_levelfile_name(lock, 0);
  141.     if(locknum > 25) locknum = 25;
  142.  
  143.     do {
  144.         if(locknum) lock[0] = 'a' + i++;
  145.  
  146.         if((fd = open(lock, 0, 0)) == -1) {
  147.             if(errno == ENOENT) goto gotlock;    /* no such file */
  148.             perror(lock);
  149.             unlock_file(HLOCK);
  150.             error("Cannot open %s", lock);
  151.         }
  152.  
  153.         if(veryold(fd))    /* if true, this closes fd and unlinks lock */
  154.             goto gotlock;
  155.         (void) close(fd);
  156.     } while(i < locknum);
  157.  
  158.     unlock_file(HLOCK);
  159.     error(locknum ? "Too many hacks running now."
  160.               : "There is a game in progress under your name.");
  161.  
  162. gotlock:
  163.     fd = creat(lock, FCMASK);
  164.     unlock_file(HLOCK);
  165.     if(fd == -1) {
  166.         error("cannot creat lock file.");
  167.     } else {
  168.         if(write(fd, (char *) &hackpid, sizeof(hackpid))
  169.             != sizeof(hackpid)){
  170.             error("cannot write lock");
  171.         }
  172.         if(close(fd) == -1) {
  173.             error("cannot close lock");
  174.         }
  175.     }
  176. }    
  177.  
  178. void
  179. regularize(s)    /* normalize file name */
  180. register char *s;
  181. {
  182.     register char *lp;
  183.  
  184.     for (lp = s; *lp; lp++)         /* note: '-' becomes '_' */
  185.         if (!(isalpha(*lp) || isdigit(*lp) || *lp == '$'))
  186.             *lp = '_';
  187. }
  188.  
  189. #undef getuid
  190. int
  191. vms_getuid()
  192. {
  193.     return (getgid() << 16) | getuid();
  194. }
  195.  
  196. /* return a copy of the 'base' portion of a filename */
  197. char *
  198. basename(name)
  199. const char *name;
  200. {
  201.     unsigned len;
  202.     char *base;
  203.     register const char *p;
  204.  
  205.     /* skip directory/path */
  206.     if ((p = strrchr(name, ']')) != 0) name = p + 1;
  207.     if ((p = strrchr(name, '>')) != 0) name = p + 1;
  208.     if ((p = strrchr(name, ':')) != 0) name = p + 1;
  209.     if ((p = strrchr(name, '/')) != 0) name = p + 1;
  210.     if (!*name) name = ".";        /* this should never happen */
  211.  
  212.     /* find extension/version and derive length of basename */
  213.     if ((p = strchr(name, '.')) == 0 || p == name) p = strchr(name, ';');
  214.     len = p && p > name ? p - name : strlen(name);
  215.  
  216.     /* copy and return name */
  217.     base = strncpy((char *)alloc(len + 1), name, len);
  218.     base[len] = '\0';
  219.     return lcase(base);
  220. }
  221.  
  222. #ifndef FAB$C_STMLF
  223. #define FAB$C_STMLF 5
  224. #endif
  225. /* check whether the open file specified by `fd' is in stream-lf format */
  226. boolean
  227. file_is_stmlf(fd)
  228. int fd;
  229. {
  230.     int rfm;
  231.     struct stat buf;
  232.  
  233.     if (fstat(fd, &buf)) return FALSE;    /* cannot get status? */
  234.  
  235. #ifdef stat_alignment_fix    /* gcc-vms alignment kludge */
  236.     rfm = stat_alignment_fix(&buf)->st_fab_rfm;
  237. #else
  238.     rfm = buf.st_fab_rfm;
  239. #endif
  240.     return rfm == FAB$C_STMLF;
  241. }
  242.  
  243. /*------*/
  244. #ifndef LNM$_STRING
  245. #include <lnmdef.h>    /* logical name definitions */
  246. #endif
  247. #define ENVSIZ LNM$C_NAMLENGTH  /*255*/
  248.  
  249. #define ENV_USR 0    /* user-mode */
  250. #define ENV_SUP 1    /* supervisor-mode */
  251. #define ENV_JOB 2    /* job-wide entry */
  252.  
  253. /* vms_define() - assign a value to a logical name */
  254. int
  255. vms_define(name, value, flag)
  256. const char *name;
  257. const char *value;
  258. int flag;
  259. {
  260.     struct dsc { int len; const char *adr; };    /* string descriptor */
  261.     struct itm3 { short buflen, itmcode; const char *bufadr; short *retlen; };
  262.     static struct itm3 itm_lst[] = { {0,LNM$_STRING,0,0}, {0,0} };
  263.     struct dsc nam_dsc, val_dsc, tbl_dsc;
  264.     unsigned long result, SYS$CRELNM(), LIB$SET_LOGICAL();
  265.  
  266.     /* set up string descriptors */
  267.     nam_dsc.len = strlen( nam_dsc.adr = name );
  268.     val_dsc.len = strlen( val_dsc.adr = value );
  269.     tbl_dsc.len = strlen( tbl_dsc.adr = "LNM$PROCESS" );
  270.  
  271.     switch (flag) {
  272.     case ENV_JOB:    /* job logical name */
  273.         tbl_dsc.len = strlen( tbl_dsc.adr = "LNM$JOB" );
  274.         /*FALLTHRU*/
  275.     case ENV_SUP:    /* supervisor-mode process logical name */
  276.         result = LIB$SET_LOGICAL(&nam_dsc, &val_dsc, &tbl_dsc);
  277.         break;
  278.     case ENV_USR:    /* user-mode process logical name */
  279.         itm_lst[0].buflen = val_dsc.len;
  280.         itm_lst[0].bufadr = val_dsc.adr;
  281.         result = SYS$CRELNM(0, &tbl_dsc, &nam_dsc, 0, itm_lst);
  282.         break;
  283.     default:    /*[ bad input ]*/
  284.         result = 0;
  285.         break;
  286.     }
  287.     result &= 1;    /* odd => success (== 1), even => failure (== 0) */
  288.     return !result;    /* 0 == success, 1 == failure */
  289. }
  290.  
  291. /* vms_putenv() - create or modify an environment value */
  292. int
  293. vms_putenv(string)
  294. const char *string;
  295. {
  296.     char name[ENVSIZ+1], value[ENVSIZ+1], *p;   /* [255+1] */
  297.  
  298.     p = strchr(string, '=');
  299.     if (p > string && p < string + sizeof name && strlen(p+1) < sizeof value) {
  300.     (void)strncpy(name, string, p - string),  name[p - string] = '\0';
  301.     (void)strcpy(value, p+1);
  302.     return vms_define(name, value, ENV_USR);
  303.     } else
  304.     return 1;    /* failure */
  305. }
  306.  
  307. /*
  308.    Support for VT420 was added to VMS in version V5.4, but as of V5.5-2
  309.    VAXCRTL still doesn't handle it and puts TERM=undefined into the
  310.    environ[] array.  getenv("TERM") will return "undefined" instead of
  311.    something sensible.  Even though that's finally fixed in V6.0, site
  312.    defined terminals also return "undefined" so query SMG's TERMTABLE
  313.    instead of just checking VMS's device-type value for VT400_Series.
  314.  
  315.    Called by verify_termcap() for convenience.
  316.  */
  317. static
  318. char *verify_term()
  319. {
  320.     char      *term = getenv("NETHACK_TERM");
  321.     if (!term) term = getenv("HACK_TERM");
  322.     if (!term) term = getenv("EMACS_TERM");
  323.     if (!term) term = getenv("TERM");
  324.     if (!term || !*term
  325.     || !strcmpi(term, "undefined") || !strcmpi(term, "unknown")) {
  326.     static char smgdevtyp[31+1];    /* size is somewhat arbitrary */
  327.     static $DESCRIPTOR(smgdsc, smgdevtyp);
  328.     static $DESCRIPTOR(tt, "TT:");
  329.     unsigned short dvicode = DVI$_DEVTYPE;
  330.     unsigned long devtype = 0L, termtab = 0L;
  331.  
  332.     (void)LIB$GETDVI(&dvicode, (unsigned short *)0, &tt, &devtype,
  333.              (genericptr_t)0, (unsigned short *)0);
  334.  
  335.     if (devtype &&
  336.         vms_ok(SMG$INIT_TERM_TABLE_BY_TYPE(&devtype, &termtab, &smgdsc))) {
  337.         register char *p = &smgdevtyp[smgdsc.dsc$w_length];
  338.         /* strip trailing blanks */
  339.         while (p > smgdevtyp && *--p == ' ') *p = '\0';
  340.         /* (void)SMG$DEL_TERM_TABLE(); */
  341.         term = smgdevtyp;
  342.     }
  343.     }
  344.     return term;
  345. }
  346.  
  347. /*
  348.    Figure out whether the termcap code will find a termcap file; if not,
  349.    try to help it out.  This avoids modifying the GNU termcap sources and
  350.    can simplify configuration for sites which don't already use termcap.
  351.  */
  352. #define GNU_DEFAULT_TERMCAP "emacs_library:[etc]termcap.dat"
  353. #define NETHACK_DEF_TERMCAP "nethackdir:termcap"
  354. #define HACK_DEF_TERMCAP    "hackdir:termcap"
  355.  
  356. char *
  357. verify_termcap()    /* called from startup(src/termcap.c) */
  358. {
  359.     struct stat dummy;
  360.     char *tc = getenv("TERMCAP");
  361.     if (tc) return verify_term();    /* no termcap fixups needed */
  362.     if (!tc && !stat(NETHACK_DEF_TERMCAP, &dummy)) tc = NETHACK_DEF_TERMCAP;
  363.     if (!tc && !stat(HACK_DEF_TERMCAP, &dummy))    tc = HACK_DEF_TERMCAP;
  364.     if (!tc && !stat(GNU_DEFAULT_TERMCAP, &dummy)) tc = GNU_DEFAULT_TERMCAP;
  365.     if (!tc && !stat("[]termcap", &dummy)) tc = "[]termcap"; /* current dir */
  366.     if (!tc && !stat("$TERMCAP", &dummy))  tc = "$TERMCAP";  /* alt environ */
  367.     if (tc) {
  368.     /* putenv(strcat(strcpy(buffer,"TERMCAP="),tc)); */
  369.     vms_define("TERMCAP", tc, ENV_USR);
  370.     } else {
  371.     /* perhaps someday we'll construct a termcap entry string */
  372.     }
  373.     return verify_term();
  374. }
  375. /*------*/
  376.  
  377. #ifdef SHELL
  378. # ifndef CLI$M_NOWAIT
  379. #  define CLI$M_NOWAIT 1
  380. # endif
  381. #endif
  382.  
  383. #if defined(CHDIR) || defined(SHELL) || defined(SECURE)
  384. static unsigned long oprv[2];
  385.  
  386. void
  387. privoff()
  388. {
  389.     unsigned long prv[2] = { ~0, ~0 }, code = JPI$_PROCPRIV;
  390.  
  391.     (void) SYS$SETPRV(0, prv, 0, oprv);
  392.     (void) LIB$GETJPI(&code, 0, 0, prv);
  393.     (void) SYS$SETPRV(1, prv, 0, 0);
  394. }
  395.  
  396. void
  397. privon()
  398. {
  399.     (void) SYS$SETPRV(1, oprv, 0, 0);
  400. }
  401. #endif    /* CHDIR || SHELL || SECURE */
  402.  
  403. #if defined(SHELL) || defined(SUSPEND)
  404. static void
  405. hack_escape(screen_manip, msg_str)
  406. boolean screen_manip;
  407. const char *msg_str;
  408. {
  409.     suspend_nhwindows(msg_str);    /* clear screen, reset terminal, &c */
  410.     (void) signal(SIGQUIT,SIG_IGN);    /* ignore ^Y */
  411.     (void) signal(SIGINT,SIG_DFL);    /* don't trap ^C (implct cnvrs to ^Y) */
  412. }
  413.  
  414. static void
  415. hack_resume(screen_manip)
  416. boolean screen_manip;
  417. {
  418.     (void) signal(SIGINT, (SIG_RET_TYPE) done1);
  419. # ifdef WIZARD
  420.     if (wizard) (void) signal(SIGQUIT,SIG_DFL);
  421. # endif
  422.     resume_nhwindows();    /* setup terminal modes, redraw screen, &c */
  423. }
  424. #endif    /* SHELL || SUSPEND */
  425.  
  426. #ifdef SHELL
  427. unsigned long dosh_pid = 0,    /* this should cover any interactive escape */
  428.     mail_pid = 0;    /* this only covers the last mail or phone; */
  429. /*(mail & phone commands aren't expected to leave any process hanging around)*/
  430.  
  431. int dosh()
  432. {
  433.     return vms_doshell("", TRUE);    /* call for interactive child process */
  434. }
  435.  
  436. /* vms_doshell -- called by dosh() and readmail() */
  437.  
  438. /* If execstring is not a null string, then it will be executed in a spawned */
  439. /* subprocess, which will then return.  It is for handling mail or phone     */
  440. /* interactive commands, which are only available if both MAIL and SHELL are */
  441. /* #defined, but we don't bother making the support code conditionalized on  */
  442. /* MAIL here, just on SHELL being enabled.                     */
  443.  
  444. /* Normally, all output from this interaction will be 'piped' to the user's  */
  445. /* screen (SYS$OUTPUT).  However, if 'screenoutput' is set to FALSE, output  */
  446. /* will be piped into oblivion.  Used for silent phone call rejection.         */
  447.  
  448. int
  449. vms_doshell(execstring, screenoutput)
  450. const char *execstring;
  451. boolean screenoutput;
  452. {
  453.     unsigned long status, new_pid, spawnflags = 0;
  454.     struct dsc$descriptor_s comstring, *command, *inoutfile = 0;
  455.     static $DESCRIPTOR(nulldevice, "_NLA0:");
  456.  
  457.     /* Is this an interactive shell spawn, or do we have a command to do? */
  458.     if (execstring && *execstring) {
  459.         comstring.dsc$w_length = strlen(execstring);
  460.         comstring.dsc$b_dtype = DSC$K_DTYPE_T;
  461.         comstring.dsc$b_class = DSC$K_CLASS_S;
  462.         comstring.dsc$a_pointer = (char *)execstring;
  463.         command = &comstring;
  464.     } else
  465.         command = 0;
  466.  
  467.     /* use asynch subprocess and suppress output iff one-shot command */
  468.     if (!screenoutput) {
  469.         spawnflags = CLI$M_NOWAIT;
  470.         inoutfile = &nulldevice;
  471.     }
  472.  
  473.     hack_escape(screenoutput, command ? (const char *) 0 :
  474.      "  \"Escaping\" into a subprocess; LOGOUT to reconnect and resume play. ");
  475.  
  476.     if (command || !dosh_pid || !vms_ok(status = LIB$ATTACH(&dosh_pid))) {
  477. # ifdef CHDIR
  478.         (void) chdir(getenv("PATH"));
  479. # endif
  480.         privoff();
  481.         new_pid = 0;
  482.         status = LIB$SPAWN(command, inoutfile, inoutfile, &spawnflags,
  483.                    (struct dsc$descriptor_s *) 0, &new_pid);
  484.         if (!command) dosh_pid = new_pid; else mail_pid = new_pid;
  485.         privon();
  486. # ifdef CHDIR
  487.         chdirx((char *) 0, 0);
  488. # endif
  489.     }
  490.  
  491.     hack_resume(screenoutput);
  492.  
  493.     if (!vms_ok(status)) {
  494.         pline("  Spawn failed.  (%%x%08X) ", status);
  495.         mark_synch();
  496.     }
  497.     return 0;
  498. }
  499. #endif    /* SHELL */
  500.  
  501. #ifdef SUSPEND
  502. /* dosuspend() -- if we're a subprocess, attach to our parent;
  503.  *        if not, there's nothing we can do.
  504.  */
  505. int
  506. dosuspend()
  507. {
  508.     static long owner_pid = -1;
  509.     unsigned long status;
  510.  
  511.     if (owner_pid == -1)    /* need to check for parent */
  512.         owner_pid = getppid();
  513.     if (owner_pid == 0) {
  514.         pline(
  515.      "  No parent process.  Use '!' to Spawn, 'S' to Save,  or 'Q' to Quit. ");
  516.         mark_synch();
  517.         return 0;
  518.     }
  519.  
  520.     /* restore normal tty environment & clear screen */
  521.     hack_escape(1,
  522.      " Attaching to parent process; use the ATTACH command to resume play. ");
  523.  
  524.     status = LIB$ATTACH(&owner_pid);    /* connect to parent */
  525.  
  526.     hack_resume(1);    /* resume game tty environment & refresh screen */
  527.  
  528.     if (!vms_ok(status)) {
  529.         pline("  Unable to attach to parent.  (%%x%08X) ", status);
  530.         mark_synch();
  531.     }
  532.     return 0;
  533. }
  534. #endif    /* SUSPEND */
  535.  
  536. /*vmsunix.c*/
  537.