home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / World_Of_Computer_Software-02-387-Vol-3of3.iso / c / ck5a188s.zip / CKOTIO.C < prev    next >
C/C++ Source or Header  |  1992-11-23  |  43KB  |  1,870 lines

  1. char *ckxv = "OS/2 Communications I/O, 16 Nov 92";
  2.  
  3. /* C K O T I O  --  Kermit communications I/O support for OS/2 systems */
  4.  
  5. /*
  6.   Also contains code to emulate the Unix 'alarm' function under OS/2
  7.   and a set of opendir/readdir/closedir etc. functions.
  8. */
  9.  
  10. /*
  11.  Author: Chris Adie (C.Adie@uk.ac.edinburgh)
  12.  Copyright (C) 1988 Edinburgh University Computing Service
  13.  Permission is granted to any individual or institution to use, copy, or
  14.  redistribute this software so long as it is not sold for profit, provided
  15.  this copyright notice is retained.
  16.  
  17.  Many changes for 5A by Kai Uwe Rommel (rommel@informatik.tu-muenchen.de)
  18. */
  19.  
  20. /* Includes */
  21.  
  22. #include "ckcdeb.h"            /* Typedefs, debug formats, etc */
  23. #include "ckcker.h"            /* Kermit definitions */
  24. #include "ckcnet.h"            /* Kermit definitions */
  25. #include "ckuxla.h"            /* Translation tables */
  26.  
  27. #include <ctype.h>            /* Character types */
  28. #include <stdio.h>            /* Standard i/o */
  29. #include <io.h>                /* File io function declarations */
  30. #include <fcntl.h>
  31. #include <process.h>            /* Process-control functions */
  32. #include <string.h>            /* String manipulation declarations */
  33. #include <stdlib.h>            /* Standard library declarations */
  34. #include <sys/types.h>
  35. #include <sys/stat.h>
  36. #include <time.h>            /* Time functions */
  37. #include <signal.h>
  38. #include <assert.h>
  39. #include <setjmp.h>
  40.  
  41. #include "ckodir.h"
  42.  
  43. #include "ckuver.h"            /* Version herald */
  44. char ckxsystem[64] = HERALD;
  45. char *ckxsys = ckxsystem;
  46.  
  47. #define DEL 127
  48. #define HUPTIME 500            /* Milliseconds for hangup */
  49.  
  50. #ifndef __32BIT__
  51. #define far _far
  52. #define near _near
  53. #define pascal _pascal
  54. #endif
  55. #define    INCL_NOPM
  56. #define    INCL_ERRORS
  57. #define    INCL_KBD
  58. #define    INCL_DOSPROCESS
  59. #define    INCL_DOSQUEUES
  60. #define    INCL_DOSSIGNALS
  61. #define    INCL_DOSDEVICES
  62. #define    INCL_DOSDEVIOCTL
  63. #define    INCL_DOSNLS
  64. #include <os2.h>    /* This pulls in a whole load of stuff */
  65. #undef COMMENT
  66.  
  67. #ifdef CHAR
  68. #undef CHAR
  69. #endif /* CHAR */
  70.  
  71. /*============================================================================*/
  72.  
  73. /*
  74.  Variables available to outside world:
  75.  
  76.    dftty  -- Pointer to default tty name string, like "/dev/tty".
  77.    dfloc  -- 0 if dftty is console, 1 if external line.
  78.    dfprty -- Default parity
  79.    dfflow -- Default flow control
  80.    ckxech -- Flag for who echoes console typein:
  81.      1 - The program (system echo is turned off)
  82.      0 - The system (or front end, or terminal).
  83.    functions that want to do their own echoing should check this flag
  84.    before doing so.
  85.  
  86.  Functions for assigned communication line (either external or console tty):
  87.  
  88.    sysinit()               -- System dependent program initialization
  89.    syscleanup()            -- System dependent program shutdown
  90.    ttopen(ttname,local,mdmtyp) -- Open the named tty for exclusive access.
  91.    ttclos()                -- Close & reset the tty, releasing any access lock.
  92.    ttpkt(speed,flow,parity)-- Put the tty in packet mode
  93.                 or in DIALING or CONNECT modem control state.
  94.    ttvt(speed,flow)        -- Put the tty in virtual terminal mode.
  95.    ttinl(dest,max,timo)    -- Timed read line from the tty.
  96.    ttinc(timo)             -- Timed read character from tty.
  97.    ttchk()                 -- See how many characters in tty input buffer.
  98.    ttxin(n,buf)            -- Read n characters from tty (untimed).
  99.    ttol(string,length)     -- Write a string to the tty.
  100.    ttoc(c)                 -- Write a character to the tty.
  101.    ttflui()                -- Flush tty input buffer.
  102.    ttgspd()                -- Speed of tty line.
  103.  
  104. Functions for console terminal:
  105.  
  106.    conraw()  -- Set console into Raw mode
  107.    concooked() -- Set console into Cooked mode
  108.    conoc(c)  -- Unbuffered output, one character to console.
  109.    conol(s)  -- Unbuffered output, null-terminated string to the console.
  110.    conola(s) -- Unbuffered output, array of strings to the console.
  111.    conxo(n,s) -- Unbuffered output, n characters to the console.
  112.    conchk()  -- Check if characters available at console (bsd 4.2).
  113.         Check if escape char (^\) typed at console (System III/V).
  114.    coninc(timo)  -- Timed get a character from the console.
  115.  Following routines are dummies:
  116.    congm()   -- Get console terminal mode.
  117.    concb()   -- Put console into single char mode with no echo.
  118.    conres()  -- Restore console to congm mode.
  119.    conint()  -- Enable console terminal interrupts.
  120.    connoi()  -- No console interrupts.
  121.  
  122. Time functions
  123.  
  124.    sleep(t)  -- Like UNIX sleep
  125.    msleep(m) -- Millisecond sleep
  126.    ztime(&s) -- Return pointer to date/time string
  127.    rtimer() --  Reset timer
  128.    gtimer()  -- Get elapsed time since last call to rtimer()
  129. */
  130.  
  131.  
  132. /* Defines */
  133.  
  134. #define DEVNAMLEN    14
  135.  
  136. /* Declarations */
  137.  
  138. /* dftty is the device name of the default device for file transfer */
  139. /* dfloc is 0 if dftty is the user's console terminal, 1 if an external line */
  140.  
  141. extern long speed;
  142. extern int parity, fcharset, flow, ttcarr;
  143.  
  144. #ifdef COMMENT
  145. /* This is to allow remote operation */
  146.     char *dftty = "0"; /* stdin */
  147.     int dfloc = 0;
  148. #else
  149.     char *dftty = "com1"; /* COM1 */
  150.     int dfloc = 1;
  151. #endif /* COMMENT */
  152.  
  153.     int dfprty = 0;            /* Default parity (0 = none) */
  154.     int ttprty = 0;            /* Parity in use. */
  155.     int ttmdm = 0;            /* Modem in use. */
  156.     int dfflow = FLO_KEEP;        /* Default flow is KEEP, no change*/
  157.     int backgrd = 0;            /* Assume in foreground (no '&' ) */
  158.     int ttcarr = CAR_AUT;        /* Carrier handling mode. */
  159.  
  160. int ckxech = 1; /* 0 if system normally echoes console characters, else 1 */
  161.  
  162. /* Declarations of variables global within this module */
  163.  
  164. static struct rdchbuf_rec {        /* Buffer for serial characters */
  165.     unsigned char buffer[256];
  166.     UINT length, index;
  167. } rdchbuf;
  168.  
  169. char startupdir[CCHMAXPATH] = ".";
  170.  
  171. static long tcount;            /* Elapsed time counter */
  172. static int conmode, consaved;
  173. static char ttnmsv[DEVNAMLEN];
  174. static int islocal;
  175. static int pid;
  176.  
  177. #ifdef COMMENT
  178. int ttyfd = 0;        /* TTY file descriptor = stdin */
  179. #else
  180. int ttyfd = -1;        /* TTY file descriptor (not open yet) */
  181. #endif /* COMMENT */
  182.  
  183. DCBINFO ttydcb;
  184.  
  185. extern KEY     *keymap;
  186. extern MACRO     *macrotab;
  187.  
  188. int ttsetspd(long sp);
  189.  
  190. #ifdef __32BIT__
  191.  
  192. USHORT DosDevIOCtl32(PVOID pData, USHORT cbData, PVOID pParms, USHORT cbParms,
  193.              USHORT usFunction, USHORT usCategory, HFILE hDevice)
  194. {
  195.   ULONG ulParmLengthInOut = cbParms, ulDataLengthInOut = cbData;
  196.   return (USHORT) DosDevIOCtl(hDevice, usCategory, usFunction,
  197.                   pParms, cbParms, &ulParmLengthInOut,
  198.                   pData, cbData, &ulDataLengthInOut);
  199. }
  200.  
  201. #define DosDevIOCtl DosDevIOCtl32
  202.  
  203. #else
  204.  
  205. #define DosDevIOCtl(pd, cbd, pp, cbp, f, c, h) DosDevIOCtl(pd, pp, f, c, h)
  206.  
  207. #endif
  208.  
  209.  
  210. void cc_trap(int sig)
  211. {
  212.   signal(sig, cc_trap);
  213. #ifdef __EMX__
  214.   signal(sig, SIG_ACK);
  215. #endif
  216. }
  217.  
  218. /* Saving/restoring of hot handles */
  219.  
  220. static int savedtty = 0;
  221. static long savedspeed;
  222. static LINECONTROL savedlc;
  223. static DCBINFO saveddcb;
  224. static BYTE savedstat;
  225.  
  226. savetty() {
  227.  
  228.   if (ttyfd != -1) {
  229.     savedspeed = ttgspd();
  230.     DosDevIOCtl(&savedlc,sizeof(savedlc),NULL,0,
  231.         ASYNC_GETLINECTRL,IOCTL_ASYNC,ttyfd);
  232.     DosDevIOCtl(&saveddcb,sizeof(saveddcb),NULL,0,
  233.         ASYNC_GETDCBINFO,IOCTL_ASYNC,ttyfd);
  234.     DosDevIOCtl(&savedstat,sizeof(savedstat),NULL,0,
  235.         ASYNC_GETMODEMOUTPUT,IOCTL_ASYNC,ttyfd);
  236.     savedtty = 1;
  237.   }
  238.  
  239.   return 0;
  240. }
  241.  
  242. restoretty() {
  243.   MODEMSTATUS ms;
  244.   UINT data;
  245.  
  246.   if (savedtty) {
  247.     ttsetspd(savedspeed);
  248.     DosDevIOCtl(NULL,0,&savedlc,sizeof(savedlc),
  249.         ASYNC_SETLINECTRL,IOCTL_ASYNC,ttyfd);
  250.     DosDevIOCtl(NULL,0,&saveddcb,sizeof(saveddcb),
  251.         ASYNC_SETDCBINFO,IOCTL_ASYNC,ttyfd);
  252.     ms.fbModemOn = 0;
  253.     ms.fbModemOff = 255;
  254.     if (savedstat & DTR_ON) ms.fbModemOn |= DTR_ON;
  255.     else ms.fbModemOff &= DTR_OFF;
  256.     if (savedstat & RTS_ON) ms.fbModemOn |= RTS_ON;
  257.     else ms.fbModemOff &= RTS_OFF;
  258.     DosDevIOCtl(&data,sizeof(data),&ms,sizeof(ms),
  259.         ASYNC_SETMODEMCTRL,IOCTL_ASYNC,ttyfd);
  260.     savedtty = 0;
  261.   }
  262.  
  263.   return 0;
  264. }
  265.  
  266. /*  S Y S I N I T  --  System-dependent program initialization.  */
  267.  
  268. sysinit() {
  269.     char *ptr;
  270.     int n;
  271. #ifdef __32BIT__
  272.     ULONG cbData, nCodePage[8];
  273. #else
  274.     USHORT cbData, nCodePage[8];
  275. #endif
  276.     if ( DosGetCp(sizeof(nCodePage), nCodePage, &cbData) == 0 )
  277.       switch (nCodePage[0]) {
  278.       case 437:
  279.     fcharset = FC_CP437;
  280.     break;
  281.       case 850:
  282.     fcharset = FC_CP850;
  283.     break;
  284.       case 852:
  285.     fcharset = FC_CP852;
  286.     break;
  287.       }
  288.     pid = getpid();
  289.     signal(SIGINT, cc_trap);
  290.     signal(SIGBREAK, cc_trap);
  291.     sprintf(ckxsystem, " OS/2 %1d.%02d", _osmajor / 10, _osminor);
  292. #ifdef __IBMC__
  293.     setvbuf(stdout, NULL, _IONBF, 0);
  294. #endif
  295.     strcpy(startupdir, GetLoadPath());
  296.     if ( (ptr = strrchr(startupdir, '\\')) != NULL )
  297.       *ptr = 0;
  298.     for (ptr = startupdir; *ptr; ptr++)    /* Convert backslashes to slashes */
  299.       if (*ptr == '\\')
  300.     *ptr = '/';
  301.     n = (int)strlen(startupdir);    /* Add slash to end if necessary */
  302.     if (n > -1 && n < CCHMAXPATH)
  303.       if (startupdir[n-1] != '/') {
  304.       startupdir[n] = '/';
  305.       startupdir[n+1] = '\0';
  306.       }
  307. #ifdef COMMENT
  308. /* This is a bit UNIXish and disconcerting */
  309.     strlwr(startupdir);
  310. #endif /* COMMENT */
  311. #ifdef __IBMC__
  312.     setmode(1, O_TEXT);
  313. #endif /* __IBMC__ */
  314.     strcpy(ttnmsv, dftty);
  315.     islocal = isatty(0) && !ttiscom(0);
  316.     if (!islocal) {
  317.       os2setdtr(1);
  318.       ttsettings(ttprty,0);
  319.       os2setflow(flow);
  320.       os2setcarr(ttcarr == CAR_ON);
  321.     }
  322.     return(0);
  323. }
  324.  
  325.  
  326. /*  S Y S C L E A N U P  --  System-dependent program cleanup.  */
  327.  
  328. syscleanup() {
  329.     signal(SIGINT, SIG_DFL);
  330.     signal(SIGBREAK, SIG_DFL);
  331.     return(0);
  332. }
  333.  
  334.  
  335. /*  O S 2 S E T F L O W -- set flow state of tty */
  336.  
  337. os2setflow(int nflow)
  338. {
  339.     /* Get the current settings */
  340.     if (DosDevIOCtl(&ttydcb,sizeof(ttydcb),NULL,0,
  341.             ASYNC_GETDCBINFO,IOCTL_ASYNC,ttyfd))
  342.         return(-1);
  343.  
  344.     ttydcb.fbCtlHndShake = MODE_DTR_CONTROL; 
  345.     ttydcb.fbFlowReplace &= ~(MODE_AUTO_RECEIVE | MODE_AUTO_TRANSMIT |
  346.     /* clear only a few */    MODE_RTS_CONTROL  | MODE_RTS_HANDSHAKE);
  347.  
  348.     if (nflow == FLO_XONX) {
  349.         ttydcb.fbFlowReplace |= 
  350.       (MODE_AUTO_RECEIVE | MODE_AUTO_TRANSMIT | MODE_RTS_CONTROL);
  351.     }
  352.     else if (nflow == FLO_RTSC) {
  353.         ttydcb.fbCtlHndShake |= MODE_CTS_HANDSHAKE;
  354.     ttydcb.fbFlowReplace |= MODE_RTS_HANDSHAKE;
  355.     }
  356.     else
  357.         ttydcb.fbFlowReplace |= MODE_RTS_CONTROL;
  358.  
  359.     /* Read "some" data from line mode */
  360.     ttydcb.fbTimeout &= ~MODE_NOWAIT_READ_TIMEOUT;
  361.     ttydcb.fbTimeout |= MODE_WAIT_READ_TIMEOUT;
  362.  
  363.     /* Set DCB */
  364.     if (DosDevIOCtl(NULL,0,&ttydcb,sizeof(ttydcb),
  365.             ASYNC_SETDCBINFO,IOCTL_ASYNC,ttyfd))
  366.         return(-1);
  367.  
  368.     if (nflow != FLO_RTSC) {        /* keep RTS permanently on */
  369.         MODEMSTATUS ms;
  370.     UINT data;
  371.     ms.fbModemOn = RTS_ON;
  372.     ms.fbModemOff = 255;
  373.     DosDevIOCtl(&data,sizeof(data),&ms,sizeof(ms),
  374.             ASYNC_SETMODEMCTRL,IOCTL_ASYNC,ttyfd);
  375.     }
  376.  
  377.     return(0);
  378. }
  379.  
  380.  
  381. os2setcarr(int ncarr)
  382. {
  383.     /* Get the current settings */
  384.     if (DosDevIOCtl(&ttydcb,sizeof(ttydcb),NULL,0,
  385.             ASYNC_GETDCBINFO,IOCTL_ASYNC,ttyfd))
  386.         return(-1);
  387.  
  388.     if (ncarr)
  389.       ttydcb.fbCtlHndShake |=  MODE_DCD_HANDSHAKE;
  390.     else
  391.       ttydcb.fbCtlHndShake &= ~MODE_DCD_HANDSHAKE;
  392.  
  393.     /* Set DCB */
  394.     if (DosDevIOCtl(NULL,0,&ttydcb,sizeof(ttydcb),
  395.             ASYNC_SETDCBINFO,IOCTL_ASYNC,ttyfd))
  396.         return(-1);
  397.  
  398.     return(0);
  399. }
  400.  
  401.  
  402. /*  O S 2 S E T D T R -- set state of DTR signal */
  403.  
  404. os2setdtr(int on)
  405. {
  406.     MODEMSTATUS ms;
  407.     UINT data;
  408.  
  409.     if (ttyfd == -1) return(0);
  410.     ms.fbModemOn = on ? DTR_ON : 0;
  411.     ms.fbModemOff = on ? 255 : DTR_OFF;
  412.     return(DosDevIOCtl(&data,sizeof(data),&ms,sizeof(ms),
  413.                ASYNC_SETMODEMCTRL,IOCTL_ASYNC,ttyfd));
  414. }
  415.  
  416.  
  417. /*  T T S E T T I N G S  --  Set the device driver parity and stop bits */
  418.  
  419. ttsettings(int par, int stop) {
  420.     LINECONTROL lc;
  421.  
  422.     if (DosDevIOCtl(&lc,sizeof(lc),NULL,0,
  423.             ASYNC_GETLINECTRL,IOCTL_ASYNC,ttyfd))
  424.       return(-1); /* Get line */
  425.  
  426.     switch (par) {
  427.     case 'o':
  428.         lc.bDataBits = 7;    /* Data bits */
  429.         lc.bParity   = 1;
  430.         break;
  431.         case 'e':
  432.         lc.bDataBits = 7;    /* Data bits */
  433.         lc.bParity   = 2;
  434.         break;
  435.     case 'm':
  436.         lc.bDataBits = 7;    /* Data bits */
  437.         lc.bParity   = 3;
  438.         break;
  439.     case 's':
  440.         lc.bDataBits = 7;    /* Data bits */
  441.         lc.bParity   = 4;
  442.         break;
  443.     default :
  444.         lc.bDataBits = 8;    /* Data bits */
  445.         lc.bParity   = 0;    /* No parity */
  446.     }
  447.     switch (stop) {
  448.         case 2:
  449.             lc.bStopBits = 2;    /* Two stop bits */
  450.             break;
  451.         case 1:
  452.             lc.bStopBits = 0;    /* One stop bit */
  453.             break;
  454.         default:         /* No change */
  455.             break;
  456.     }
  457.     if (DosDevIOCtl(NULL,0,&lc,sizeof(lc),
  458.             ASYNC_SETLINECTRL,IOCTL_ASYNC,ttyfd))
  459.       return(-1); /* Set line */
  460.     return(0);
  461. }
  462.  
  463. /*  T T O P E N  --  Open a tty for exclusive access.  */
  464.  
  465. /*  Returns 0 on success, -1 on failure.  */
  466. /*
  467.   If called with lcl < 0, sets value of lcl as follows:
  468.   0: the terminal named by ttname is the job's controlling terminal.
  469.   1: the terminal named by ttname is not the job's controlling terminal.
  470.   But watch out: if a line is already open, or if requested line can't
  471.   be opened, then lcl remains (and is returned as) -1.
  472. */
  473. ttopen(char *ttname, int *lcl, int modem, int spare)
  474. {
  475.     char *x; extern char* ttyname();
  476.     char cname[DEVNAMLEN+4];
  477. #ifdef __32BIT__
  478.     ULONG action, res;
  479. #else
  480.     USHORT action, res;
  481. #endif
  482.  
  483.     rdchbuf.length = rdchbuf.index = 0;
  484.  
  485.     if (ttyfd > -1) {            /* if device already opened */
  486.         if (strncmp(ttname,ttnmsv,DEVNAMLEN)) /* are new & old names equal? */
  487.           ttclos(ttyfd);        /* no, close old ttname, open new */
  488.         else                 /* else same, ignore this call, */
  489.       return(0);            /* and return. */
  490.     }
  491.  
  492.     if (*lcl == 0) return(-1);        /* Won't open in local mode */
  493.  
  494.     ttmdm = modem;            /* Make this available to other fns */
  495.     strcpy(ttnmsv, ttname);        /* Keep copy of name locally. */
  496.  
  497.     if (modem < 0) return netopen(ttname, lcl, -modem);
  498.  
  499. /*
  500.   This code lets you give Kermit an open file descriptor for a serial
  501.   communication device, rather than a device name.  Kermit assumes that the
  502.   line is already open, locked, conditioned with the right parameters, etc.
  503. */
  504.     for (x = ttname; isdigit(*x); x++) ; /* Check for all digits */
  505.  
  506.     if (*x == '\0') {
  507.     ttyfd = atoi(ttname);
  508.     *lcl = 1;            /* Assume it's local. */
  509.     if (ttiscom(ttyfd))
  510.         return savetty();
  511.     ttyfd = -1;
  512.     return(-4);
  513.     }
  514.  
  515.     if (res = DosOpen(ttname,(PHFILE)&ttyfd,&action,0L,0,FILE_OPEN,
  516.                       OPEN_ACCESS_READWRITE | OPEN_SHARE_DENYREADWRITE |
  517.                       OPEN_FLAGS_FAIL_ON_ERROR ,0L)) {
  518.     ttyfd = -1;
  519.     return((res == ERROR_SHARING_VIOLATION) ? -5 : -1);
  520.     }
  521.     debug(F111,"ttopen ok",ttname,*lcl);
  522.  
  523. /* Caller wants us to figure out if line is controlling tty */
  524.     if (*lcl == -1) {
  525.     *lcl = 1;            /* Can never transfer with console */
  526.     }
  527.     if (!ttiscom(ttyfd)) {        /* Not a serial port */
  528.         ttclos(0);
  529.         return(-4);
  530.     }
  531.     ttprty = dfprty;            /* Make parity the default parity */
  532.     if (ttsettings(ttprty,0)) return(-1);
  533.     return(ttflui());
  534. }
  535.  
  536. /*  T T I S C O M  --  Is the given handle an open COM port? */
  537.  
  538. ttiscom(int f) {
  539.     DCBINFO testdcb;
  540.     /* Read DCB */
  541.     if (DosDevIOCtl(&testdcb,sizeof(testdcb),NULL,0,
  542.             ASYNC_GETDCBINFO,IOCTL_ASYNC,f)) {
  543.         return( 0 );            /* Bad, not a serial port */
  544.     }
  545.     return( 1 );            /* Good */
  546. }
  547.  
  548. /*  T T C L O S  --  Close the TTY.  */
  549.  
  550. ttclos(int spare)
  551. {
  552.     if (ttmdm < 0) return netclos();
  553.     if (ttyfd == -1) return(0);        /* Wasn't open. */
  554.     if (savedtty)
  555.       restoretty();
  556.     else
  557.       DosClose(ttyfd);
  558.     ttyfd = -1;
  559.     return(0);
  560. }
  561.  
  562. /*  T T G S P D  --  return speed of tt line, or of default line */
  563.  
  564. long ttgspd() {
  565.     long sp = 0;
  566. #ifdef __32BIT__
  567.     struct {
  568.       long rate;
  569.       char fract;
  570.     } speed;
  571. #endif
  572.  
  573.     if (ttyfd == -1) /* if (ttopen(dftty,&sp,0,0)) */ return(-1);
  574.  
  575. #ifdef __32BIT__
  576.     if (DosDevIOCtl(NULL,0,&speed,sizeof(speed),0x0063,IOCTL_ASYNC,ttyfd) == 0)
  577.       return speed.rate;
  578.     else
  579. #endif
  580.     if (DosDevIOCtl(&sp,sizeof(sp),NULL,0,
  581.             ASYNC_GETBAUDRATE,IOCTL_ASYNC,ttyfd) == 0) 
  582.       return sp;
  583.     else
  584.       return -1;
  585. }
  586.  
  587. ttsetspd(long sp) {
  588. #ifdef __32BIT__
  589.     struct {
  590.       long rate;
  591.       char fract;
  592.     } speed;
  593. #endif
  594.  
  595.     if (ttyfd == -1) return(-1);    /* Not open */
  596.  
  597. #ifdef __32BIT__
  598.     if (sp > 65535) {
  599.       speed.rate = sp;
  600.       speed.fract = 0;
  601.       return DosDevIOCtl(NULL,0,&speed,sizeof(speed),0x0043,IOCTL_ASYNC,ttyfd);
  602.     } else
  603. #endif
  604.     return DosDevIOCtl(NULL,0,&sp,sizeof(sp),
  605.                ASYNC_SETBAUDRATE,IOCTL_ASYNC,ttyfd);
  606. }
  607.  
  608.  
  609.  
  610. /*  T T H A N G -- Hangup phone line */
  611.  
  612. tthang() {
  613.     if (os2setdtr(0)) return -1;
  614.     msleep(HUPTIME);
  615.     os2setdtr(1);
  616.     return 1;
  617. }
  618.  
  619.  
  620. /*  T T R E S  --  Restore terminal to "normal" mode.  */
  621.  
  622. ttres() {                /* Restore the tty to normal. */
  623.     if (ttyfd == -1) return(-1);    /* Not open */
  624.     return(0);
  625. }
  626.  
  627.  
  628. /*  T T P K T  --  Condition the communication line for packets. */
  629. /*        or for modem dialing */
  630.  
  631. /*  If called with speed > -1, also set the speed.  */
  632. /*  Returns 0 on success, -1 on failure.  */
  633.  
  634. ttpkt(long speed, int flow, int parity)
  635. {
  636.     int s;
  637.  
  638.     if (ttmdm < 0) return(0);
  639.     if (ttyfd < 0) return(-1);        /* Not open. */
  640.     if (speed < 0) return(-1);
  641.  
  642.     ttprty = parity;
  643.     os2setdtr(1);
  644.     if (ttsetspd(speed)) return(-1);
  645.     if (ttsettings(ttprty,0)) return(-1);
  646.     if (os2setflow(flow)) return(-1);
  647.     if (os2setcarr(ttcarr == CAR_ON && flow != FLO_DIAL)) return(-1);
  648.  
  649.     DosSetPrty(PRTYS_THREAD, PRTYC_FOREGROUNDSERVER, 0, 0);
  650.     return(0);
  651. }
  652.  
  653.  
  654. /*  T T V T -- Condition communication line for use as virtual terminal  */
  655.  
  656. ttvt(long speed, int flow)
  657. {
  658.  
  659.     if (ttmdm < 0) return(0);
  660.     if (ttyfd < 0) return(-1);        /* Not open. */
  661.     if (speed < 0) return(-1);
  662.  
  663.     ttprty = parity;
  664.     os2setdtr(1);
  665.     if (ttsetspd(speed)) return(-1);
  666.     if (ttsettings(ttprty,0)) return(-1);
  667.     if (os2setflow(flow)) return (-1);
  668.     if (os2setcarr(ttcarr == CAR_ON || ttcarr == CAR_AUT)) return(-1);
  669.  
  670.     return(0);
  671. }
  672.  
  673.  
  674. /*  T T S S P D  --  Return the speed if OK, otherwise -1 */
  675.  
  676. ttsspd(int speed)
  677. {
  678.     long s;
  679.  
  680.     if (speed < 0) return(-1);
  681.     switch (speed) {
  682.         case 11:
  683.         case 15:
  684.         case 30:
  685.         case 60:
  686.         case 120:
  687.         case 180:
  688.         case 240:
  689.         case 360:
  690.         case 480:
  691.         case 720:
  692.         case 960:
  693.         case 1440:
  694.         case 1920:
  695.         case 3840:
  696.         case 5760:
  697.             s = (long) speed * 10;
  698.         ttsetspd(s);
  699.                 break;
  700.         default:
  701.             return(-1);
  702.         break;
  703.     }
  704.     return(0);
  705.  }
  706.  
  707.  
  708. /*  T T F L U I  --  Flush tty input buffer */
  709.  
  710. ttflui() {
  711.     char parm=0;
  712.     long int data;
  713.     int i;
  714.  
  715.     rdchbuf.index = rdchbuf.length = 0;        /* Flush internal buffer */
  716.     DosDevIOCtl(&data,sizeof(data),&parm,sizeof(parm),
  717.         DEV_FLUSHINPUT,IOCTL_GENERAL,ttyfd); /* Flush driver */
  718.     return(0);
  719. }
  720.  
  721.  
  722. /*  T T C H K  --  Tell how many characters are waiting in tty input buffer  */
  723.  
  724. ttchk() {
  725.     USHORT data[2];
  726.     if (ttmdm < 0) return nettchk();
  727.     if(DosDevIOCtl(data,sizeof(data),NULL,0,
  728.            ASYNC_GETINQUECOUNT,IOCTL_ASYNC,ttyfd)) return(0);
  729.     else return((rdchbuf.length-rdchbuf.index)+data[0]);
  730. }
  731.  
  732.  
  733. /*  T T X I N  --  Get n characters from tty input buffer  */
  734.  
  735. /*  Returns number of characters actually gotten, or -1 on failure  */
  736.  
  737. /*  Intended for use only when it is known that n characters are actually */
  738. /*  available in the input buffer.  */
  739.  
  740. ttxin(int n, CHAR *buf)
  741. {
  742.     int i, j;
  743.  
  744.     if (ttyfd < 0) return(-1);        /* Not open. */
  745.     i = 0;
  746.     while (i < n) {
  747.         if ((j = ttinc(0)) < 0) break;
  748.         buf[i++] = j;
  749.     }
  750.     return(i);
  751. }
  752.  
  753. /*  T T O L  --  Similar to "ttinl", but for writing.  */
  754.  
  755. ttol(CHAR *s, int n) {
  756.     UINT i;
  757.  
  758.     if (ttmdm < 0) return nettol(s,n);
  759.  
  760.     if (ttyfd < 0) return(-1);        /* Not open. */
  761.     if (DosWrite(ttyfd,s,n,(PVOID)&i)) return(-1);
  762.     else return(i);
  763. }
  764.  
  765.  
  766. /*  T T O C  --  Output a character to the communication line  */
  767.  
  768. ttoc(char c) {
  769.     UINT i;
  770.  
  771.     if (ttmdm < 0) return nettoc(c);
  772.  
  773.     if (ttyfd < 0) return(-1);        /* Not open. */
  774.     if(DosWrite(ttyfd,&c,1,(PVOID)&i)) return(-1);
  775.     else return(i);
  776. }
  777.  
  778.  
  779. /*  T T O C I  --  Output a character to the communication line immediately */
  780.  
  781. ttoci(char c) {
  782.  
  783.     if (ttmdm < 0) return nettoc(c);
  784.  
  785.     if (ttyfd < 0) return(-1);        /* Not open. */
  786.     if(DosDevIOCtl(NULL,0,&c,sizeof(c),
  787.            ASYNC_TRANSMITIMM,IOCTL_ASYNC,ttyfd)) return(-1);
  788.     else return(1);
  789. }
  790.  
  791.  
  792. /*  T T I N L  --  Read a record (up to break character) from comm line.  */
  793. /*
  794.   If no break character encountered within "max", return "max" characters,
  795.   with disposition of any remaining characters undefined.  Otherwise, return
  796.   the characters that were read, including the break character, in "dest" and
  797.   the number of characters read as the value of the function, or 0 upon end of
  798.   file, or -1 if an error occurred.  Times out & returns error if not completed
  799.   within "timo" seconds.
  800. */
  801. ttinl(CHAR *dest, int max, int timo, CHAR eol) {
  802.     int x = 0, c, i, m;
  803.  
  804.     if (ttyfd < 0) return(-1);        /* Not open. */
  805.     *dest = '\0';            /* Clear destination buffer */
  806.     i = 0;                /* Next char to process */
  807.     while (1) {
  808.     if ((c = ttinc(timo)) == -1) {
  809.         x = -1;
  810.         break;
  811.     }
  812.         dest[i] = c;            /* Got one. */
  813.     if (dest[i] == eol) {
  814.         dest[++i] = '\0';
  815.         return(i);
  816.     }
  817.     if (i++ > max) {
  818.         debug(F101,"ttinl buffer overflow","",i);
  819.         x = -1;
  820.         break;
  821.     }
  822.     }
  823.     debug(F100,"ttinl timout","",0);    /* Get here on timeout. */
  824.     debug(F111," with",dest,i);
  825.     return(x);                /* and return error code. */
  826. }
  827.  
  828.  
  829. /*  T T I N C --  Read a character from the communication line  */
  830.  
  831. /* The time should be in secs for consitency with the other modules in      */
  832. /* kermit.  To retain the option of using times of less than 1s a negative  */
  833. /* parameter is interpreted as meaning multiples of 0.01s                  */
  834.  
  835. static rdch(void);
  836.  
  837. ttinc(timo) int timo; {
  838.     int m, i;
  839.     char ch = 0;
  840.  
  841.     if (ttmdm < 0) return netinc(timo);
  842.  
  843.     m = (ttprty) ? 0177 : 0377;        /* Parity stripping mask. */
  844.     if (ttyfd < 0) return(-1);        /* Not open. */
  845.  
  846.     if (timo == 0) {            /* Untimed. */
  847.         ttydcb.usReadTimeout = 9;       /* Test every  0.1s per call */
  848.         if (DosDevIOCtl(NULL,0,&ttydcb,sizeof(ttydcb),
  849.             ASYNC_SETDCBINFO,1,ttyfd))
  850.           return(-1);
  851.         do
  852.           i = rdch();
  853.         while (i < 0);   /* Wait for a character. */
  854.         return(i & m);
  855.     }
  856.  
  857.     if (timo < 0)
  858.         timo= -timo - 1;
  859.     else
  860.         timo = timo * 100 - 1;
  861.  
  862.     if (timo != ttydcb.usReadTimeout + 1) { /* Set timeout value */
  863.        ttydcb.usReadTimeout = timo;
  864.        if (DosDevIOCtl(NULL,0,&ttydcb,sizeof(ttydcb),
  865.                ASYNC_SETDCBINFO,IOCTL_ASYNC,ttyfd))
  866.           return(-1);
  867.     }
  868.  
  869.     i = rdch();
  870.  
  871.     if (i < 0) return(-1);
  872.     else return(i & m);
  873. }
  874.  
  875. /*  RDCH -- Read characters from the serial port, maintaining an internal
  876.             buffer of characters for the sake of efficiency. */
  877. static rdch() {
  878.  
  879.     if (rdchbuf.index == rdchbuf.length) {
  880.     rdchbuf.index = 0;
  881.         if (DosRead(ttyfd,rdchbuf.buffer,sizeof(rdchbuf.buffer),
  882. #ifdef __32BIT__
  883.                     (PULONG) &rdchbuf.length)) {
  884. #else
  885.                     (PUSHORT) &rdchbuf.length)) {
  886. #endif
  887.         rdchbuf.length = 0;
  888.         return(-1);
  889.         }
  890.     }
  891.  
  892.     return( (rdchbuf.index < rdchbuf.length)
  893.             ? rdchbuf.buffer[rdchbuf.index++] : -1 );
  894. }
  895.  
  896. /*  T T S C A R R  --  Set ttcarr variable, controlling carrier handling.
  897.  *
  898.  *  0 = Off: Always ignore carrier. E.g. you can connect without carrier.
  899.  *  1 = On: Heed carrier, except during dialing. Carrier loss gives disconnect.
  900.  *  2 = Auto: For "modem direct": The same as "Off".
  901.  *            For real modem types: Heed carrier during connect, but ignore
  902.  *                it anytime else.  Compatible with pre-5A C-Kermit versions.
  903.  */
  904.  
  905. int
  906. ttscarr(carrier) int carrier; {
  907.     ttcarr = carrier;
  908.     debug(F101, "ttscarr","",ttcarr);
  909.     return(ttcarr);
  910. }
  911.  
  912. /*  T T G M D M  --  Get modem signals  */
  913. /*
  914.  Looks for the modem signals CTS, DSR, and CTS, and returns those that are
  915.  on in as its return value, in a bit mask as described for ttwmdm.  Returns:
  916.  -3 Not implemented
  917.  -2 if the line does not have modem control
  918.  -1 on error.
  919.  >= 0 on success, with a bit mask containing the modem signals that are on.
  920. */
  921.  
  922. int
  923. ttgmdm() {
  924.     BYTE instat, outstat;
  925.     int modem = 0;
  926.  
  927.     if(DosDevIOCtl(&instat,sizeof(instat),NULL,0,
  928.            ASYNC_GETMODEMINPUT,IOCTL_ASYNC,ttyfd))
  929.        return(-1);
  930.     if(DosDevIOCtl(&outstat,sizeof(outstat),NULL,0,
  931.            ASYNC_GETMODEMOUTPUT,IOCTL_ASYNC,ttyfd))
  932.        return(-1);
  933.  
  934.     /* Clear To Send */
  935.     if (instat & CTS_ON) modem |= BM_CTS;
  936.     /* Data Set Ready */
  937.     if (instat & DSR_ON) modem |= BM_DSR;
  938.     /* Carrier */
  939.     if (instat & DCD_ON) modem |= BM_DCD;
  940.     /* Ring Indicate */
  941.     if (instat & RI_ON)  modem |= BM_RNG;
  942.  
  943.     /* Data Terminal Ready */
  944.     if (outstat & DTR_ON) modem |= BM_DTR;
  945.     /* Request To Send */
  946.     if (outstat & RTS_ON) modem |= BM_RTS;
  947.  
  948.     return(modem);
  949. }
  950.  
  951. /*  T T S N D B  --  Send a BREAK signal  */
  952.  
  953. ttsndb() {
  954.     MODEMSTATUS ms;
  955.     UINT data, i;
  956.  
  957.     if (ttmdm < 0) return netbreak();
  958.  
  959.     ms.fbModemOn = RTS_ON;
  960.     ms.fbModemOff = 255;
  961.     DosDevIOCtl(&data,sizeof(data),&ms,sizeof(ms),
  962.         ASYNC_SETMODEMCTRL,IOCTL_ASYNC,ttyfd);
  963.  
  964.     DosDevIOCtl(&i,sizeof(i),NULL,0,
  965.         ASYNC_SETBREAKON,IOCTL_ASYNC,ttyfd);    /* Break on */
  966.     DosSleep(275L);                    /* ZZZzzz */
  967.     DosDevIOCtl(&i,sizeof(i),NULL,0,
  968.         ASYNC_SETBREAKOFF,IOCTL_ASYNC,ttyfd);    /* Break off */
  969. }
  970.  
  971. /*  T T S N D L B  --  Send a LONG BREAK signal  */
  972.  
  973. ttsndlb() {
  974.     MODEMSTATUS ms;
  975.     UINT data, i;
  976.  
  977.     if (ttmdm < 0) return netbreak();
  978.  
  979.     ms.fbModemOn = RTS_ON;
  980.     ms.fbModemOff = 255;
  981.     DosDevIOCtl(&data,sizeof(data),&ms,sizeof(ms),
  982.         ASYNC_SETMODEMCTRL,IOCTL_ASYNC,ttyfd);
  983.  
  984.     DosDevIOCtl(&i,sizeof(i),NULL,0,
  985.         ASYNC_SETBREAKON,IOCTL_ASYNC,ttyfd);    /* Break on */
  986.     DosSleep(1800L);                    /* ZZZzzz */
  987.     DosDevIOCtl(&i,sizeof(i),NULL,0,
  988.         ASYNC_SETBREAKOFF,IOCTL_ASYNC,ttyfd);    /* Break off */
  989. }
  990.  
  991.  
  992. #ifndef __EMX__
  993. /*  S L E E P  --  Emulate the Unix sleep function  */
  994.  
  995. unsigned sleep(t) unsigned t; {
  996.     DosSleep((long)t*1000);
  997. }
  998. #endif
  999.  
  1000.  
  1001. /*  M S L E E P  --  Millisecond version of sleep().  */
  1002.  
  1003. /* Intended only for small intervals.  For big ones, just use sleep(). */
  1004.  
  1005. msleep(m) int m; {
  1006.     DosSleep((long)m);
  1007. }
  1008.  
  1009.  
  1010. /*  R T I M E R --  Reset elapsed time counter  */
  1011.  
  1012. void rtimer() {
  1013.     tcount = time((long *)NULL);
  1014. }
  1015.  
  1016.  
  1017. /*  G T I M E R --  Get current value of elapsed time counter in seconds  */
  1018.  
  1019. int gtimer(void) {
  1020.     int x;
  1021.     x = (int) (time( (long *) 0 ) - tcount);
  1022.     return( (x < 0) ? 0 : x );
  1023. }
  1024.  
  1025.  
  1026. /*  Z T I M E  --  Return date/time string  */
  1027.  
  1028. void ztime(char **s) {
  1029.     long clock_storage;
  1030.  
  1031.     clock_storage = time( (long *) 0 );
  1032.     *s = ctime( &clock_storage );
  1033. }
  1034.  
  1035. /*  C O N O C  --  Output a character to the console terminal  */
  1036.  
  1037. int conoc(char c) {
  1038.     write(1,&c,1);
  1039. }
  1040.  
  1041.  
  1042. /*  C O N X O  --  Write x characters to the console terminal  */
  1043.  
  1044. int conxo(int x, char *s) {
  1045.     write(1,s,x);
  1046. }
  1047.  
  1048.  
  1049. /*  C O N O L  --  Write a line to the console terminal  */
  1050.  
  1051. int conol(char *s) {
  1052.     int len;
  1053.     len = strlen(s);
  1054.     write(1,s,len);
  1055. }
  1056.  
  1057.  
  1058. /*  C O N O L A  --  Write an array of lines to the console terminal */
  1059.  
  1060. conola(s) char *s[]; {
  1061.     int i;
  1062.     for (i=0 ; *s[i] ; i++) conol(s[i]);
  1063. }
  1064.  
  1065.  
  1066. /*  C O N O L L  --  Output a string followed by CRLF  */
  1067.  
  1068. conoll(s) char *s; {
  1069.     conol(s);
  1070.     write(1,"\r\n",2);
  1071. }
  1072.  
  1073.  
  1074. /*  C O N C H K  --  Return how many characters available at console  */
  1075.  
  1076. conchk() {
  1077.     KBDKEYINFO k;
  1078.  
  1079.     KbdPeek(&k,0);
  1080.     return( (k.fbStatus & 0x40) ? 1 : 0 );
  1081. }
  1082.  
  1083.  
  1084. /*  C O N I N C  --  Get a character from the console  */
  1085.  
  1086. coninc(timo) int timo; {
  1087.     int c;
  1088.  
  1089.     while ( (c = congks(timo)) >= 0x100 );
  1090.  
  1091.     return c;
  1092. }
  1093.  
  1094. static jmp_buf kbbuf;
  1095. SIGTYP (*saval)(int);
  1096.  
  1097. SIGTYP kbdtimo(int sig)
  1098. {
  1099. #ifdef __EMX__
  1100.     signal(SIGALRM, SIG_ACK);
  1101. #endif
  1102.     signal(SIGALRM, saval);
  1103.     longjmp(kbbuf, 1);
  1104. }
  1105.  
  1106. congks(timo) int timo; {
  1107.     /* timeout isn't handled */
  1108.     KBDKEYINFO k;
  1109.     int c;
  1110.  
  1111.     if (!islocal) {
  1112.       c = 0;
  1113.       if ( read(ttyfd, &c, 1) < 1 )
  1114.     return -1;
  1115.       return c;
  1116.     };
  1117.  
  1118.     for (;;)
  1119.     {
  1120.         if (timo <= 0)
  1121.       KbdCharIn(&k, IO_WAIT, 0);
  1122.     else 
  1123.     {
  1124.       saval = signal(SIGALRM, kbdtimo);
  1125.       alarm(timo);
  1126.       
  1127.       if (setjmp(kbbuf))
  1128.         return -1;
  1129.       else
  1130.         KbdCharIn(&k, IO_WAIT, 0);
  1131.  
  1132.       alarm(0);
  1133.       signal(SIGALRM, saval);
  1134.     }
  1135.  
  1136.         if ( k.chChar || k.chScan )
  1137.         {
  1138.             c = k.chChar;
  1139.  
  1140.             if (c == 0x00) c = 0x100 | k.chScan;
  1141.             if (c == 0xE0) c = 0x200 | k.chScan;
  1142.  
  1143.         switch (c) /* handle ambiguous keypad and space keys */
  1144.         {
  1145.         case ' ':
  1146. #ifdef KBDSTF_CONTROL
  1147.           return (k.fsState & KBDSTF_CONTROL) ? 0x200 | c : c;
  1148. #else
  1149.           return (k.fsState & CONTROL) ? 0x200 | c : c;
  1150. #endif
  1151.         case '+':
  1152.           return k.chScan == 0x4E ? 0x200 | c : c;
  1153.         case '-':
  1154.           return k.chScan == 0x4A ? 0x200 | c : c;
  1155.         case '*':
  1156.           return k.chScan == 0x37 ? 0x200 | c : c;
  1157.         case '/':
  1158.           return k.chScan == 0xE0 ? 0x200 | c : c;
  1159.         case '\r':
  1160.         case '\n':
  1161.           return k.chScan == 0xE0 ? 0x200 | c : c;
  1162.         case '\b':
  1163.           return k.chScan == 0x0E ? DEL : c;
  1164.         case DEL:
  1165.           return 0x200 | c;
  1166.         default:
  1167.           return c;
  1168.         }
  1169.         }
  1170.  
  1171. #ifdef KBDTRF_SHIFT_KEY_IN
  1172.         if ( (k.fbStatus & KBDTRF_SHIFT_KEY_IN) &&
  1173. #else
  1174.         if ( (k.fbStatus & SHIFT_KEY_IN) &&
  1175. #endif
  1176. #ifdef KBDSTF_SCROLLLOCK
  1177.              (k.fsState & KBDSTF_SCROLLLOCK) )
  1178.             if ( k.fsState & KBDSTF_SCROLLLOCK_ON )
  1179. #else
  1180.              (k.fsState & SCROLLLOCK) )
  1181.             if ( k.fsState & SCROLLLOCK_ON )
  1182. #endif
  1183.                 return 0x2FF;
  1184.             else
  1185.                 return 0x1FF;
  1186.     }
  1187. }
  1188.  
  1189.  
  1190. conraw() {
  1191.     KBDINFO k;
  1192.  
  1193.     if (!islocal) return(0);
  1194.     conmode = 1;
  1195.     k.cb = sizeof(k);
  1196.     KbdGetStatus(&k,0);
  1197.     k.fsMask = KEYBOARD_ECHO_OFF
  1198.              | KEYBOARD_BINARY_MODE
  1199.              | KEYBOARD_SHIFT_REPORT;
  1200.     return(KbdSetStatus(&k,0));
  1201. }
  1202.  
  1203. concooked() {
  1204.     KBDINFO k;
  1205.  
  1206.     if (!islocal) return(0);
  1207.     conmode = 0;
  1208.     k.cb = sizeof(k);
  1209.     KbdGetStatus(&k,0);
  1210.     k.fsMask = KEYBOARD_ECHO_ON
  1211.              | KEYBOARD_ASCII_MODE;
  1212.     return(KbdSetStatus(&k,0));
  1213. }
  1214.  
  1215.  
  1216. /* init key map */
  1217.  
  1218. void keymapinit() {
  1219.     /* predefine NUL characters */
  1220.     keymap[0x103] = 0x00;
  1221.     keymap[0x200 | ' ' ] = 0x00;
  1222.     /* predefine ambiguous keypad keys */
  1223.     keymap[0x200 | '+' ] = '+';
  1224.     keymap[0x200 | '-' ] = '-';
  1225.     keymap[0x200 | '*' ] = '*';
  1226.     keymap[0x200 | '/' ] = '/';
  1227.     keymap[0x200 | '\r'] = '\r';
  1228.     keymap[0x200 | '\n'] = '\n';
  1229.     keymap[0x200 | DEL ] = DEL;
  1230. }
  1231.  
  1232. /*  C O N B I N  --  Put console in binary mode  */
  1233.  
  1234. /*  Returns 0 if ok, -1 if not  */
  1235.  
  1236. conbin(char esc) {
  1237.     if (!islocal) return(0);          /* only for real ttys */
  1238.     conraw();
  1239. }
  1240.  
  1241. /*  C O N C B  -- Put console into single char mode with no echo. */
  1242.  
  1243. concb(char esc) {
  1244.     if (!islocal) return(0);          /* only for real ttys */
  1245.     concooked();
  1246. }
  1247.  
  1248.  
  1249. /*  C O N G M  -- Get console terminal mode. */
  1250.  
  1251. congm() {}
  1252.  
  1253. /*  C O N R E S -- Restore console to congm mode. */
  1254.  
  1255. conres() {}
  1256.  
  1257.  
  1258. /*  C O N I N T -- Enable console terminal interrupts. */
  1259.  
  1260. void conint(f, s) SIGTYP (*f)(int), (*s)(int); {
  1261.     signal(SIGINT, f);
  1262.     signal(SIGBREAK, f);
  1263. }
  1264.  
  1265.  
  1266. /*  C O N N O I -- No console interrupts. */
  1267.  
  1268. void connoi() {
  1269.     signal(SIGINT, cc_trap);
  1270.     signal(SIGBREAK, cc_trap);
  1271. }
  1272.  
  1273.  
  1274. /* privilege dummy */
  1275.  
  1276. int priv_chk() {return 0;}
  1277.  
  1278.  
  1279. #ifndef __EMX__
  1280.  
  1281. /* alarm() implementation for all others, emx/gcc already has it built-in */
  1282.  
  1283. #ifdef __32BIT__
  1284.  
  1285. #define STACK 8192
  1286. static BOOL alrm, running;
  1287. static UINT delay;
  1288.  
  1289. static long FAR alarm_thread(VOID *args)
  1290. {
  1291.   for (;;)
  1292.   {
  1293.     DosSleep(1000L);
  1294.     DosEnterCritSec();
  1295.  
  1296.     if ( alrm )
  1297.       if ( --delay == 0 ) {
  1298.     alrm = FALSE;
  1299.     DosKillProcess(DKP_PROCESS, pid);
  1300.       }
  1301.  
  1302.     DosExitCritSec();
  1303.   }
  1304.  
  1305.   running = FALSE;
  1306.   DosExit(EXIT_THREAD, 0);
  1307. }
  1308.  
  1309. static void alarm_signal(int sig)
  1310. {
  1311.   signal(SIGTERM, SIG_DFL); /* avoid making us kill-proof all the time */
  1312.   /* DosBeep(440, 10); */
  1313.   raise(SIGALRM);
  1314. }
  1315.  
  1316. unsigned alarm(unsigned sec)
  1317. {
  1318.   TID tid;
  1319.   unsigned old;
  1320.  
  1321.   DosEnterCritSec();
  1322.  
  1323.   old = delay;
  1324.   delay = sec;
  1325.  
  1326.   if ( alrm = (delay > 0) )
  1327.     signal(SIGTERM, alarm_signal);
  1328.  
  1329.   DosExitCritSec();
  1330.  
  1331.   if ( !running )
  1332.   {
  1333.     running = TRUE;
  1334.     DosCreateThread(&tid, (PFNTHREAD)alarm_thread, 0, 0, STACK);
  1335.     DosSetPrty(PRTYS_THREAD, PRTYC_REGULAR, 0, tid);
  1336.   }
  1337.  
  1338.   return old;
  1339. }
  1340.  
  1341. #else
  1342.  
  1343. #define STACK 2048
  1344. static PBYTE pstack;
  1345. static BOOL alrm, running;
  1346. static USHORT delay;
  1347.  
  1348. #pragma check_stack(off)
  1349.  
  1350. static VOID FAR alarm_thread(VOID)
  1351. {
  1352.   for (;;)
  1353.   {
  1354.     DosSleep(1000L);
  1355.     DosEnterCritSec();
  1356.  
  1357.     if ( alrm )
  1358.       if ( --delay == 0 ) {
  1359.     alrm = FALSE;
  1360.     DosFlagProcess(pid, FLGP_PID, PFLG_A, 1);
  1361.       }
  1362.  
  1363.     DosExitCritSec();
  1364.   }
  1365.  
  1366.   running = FALSE;
  1367.   DosExit(EXIT_THREAD, 0);
  1368. }
  1369.  
  1370. #pragma check_stack()
  1371.  
  1372. static VOID PASCAL FAR alarm_signal(USHORT sigarg, USHORT signum)
  1373. {
  1374.   PFNSIGHANDLER prev;
  1375.   USHORT action;
  1376.   DosSetSigHandler(alarm_signal, &prev, &action, SIGA_ACKNOWLEDGE, SIG_PFLG_A);
  1377.   raise(SIGALRM);
  1378. }
  1379.  
  1380. unsigned alarm(unsigned sec)
  1381. {
  1382.   PFNSIGHANDLER prev;
  1383.   USHORT action;
  1384.   TID tid;
  1385.   unsigned old;
  1386.  
  1387.   if ( pstack == NULL )
  1388.   {
  1389.     pstack = malloc(STACK);
  1390.     assert(pstack != NULL);
  1391.     DosSetSigHandler(alarm_signal, &prev, &action, SIGA_ACCEPT, SIG_PFLG_A);
  1392.   }
  1393.  
  1394.   DosEnterCritSec();
  1395.  
  1396.   old = delay;
  1397.   delay = sec;
  1398.   alrm = (delay > 0);
  1399.  
  1400.   DosExitCritSec();
  1401.  
  1402.   if ( !running )
  1403.   {
  1404.     running = TRUE;
  1405.     DosCreateThread(alarm_thread, &tid, pstack + STACK);
  1406.     DosSetPrty(PRTYS_THREAD, PRTYC_REGULAR, 0, tid);
  1407.   }
  1408.  
  1409.   return old;
  1410. }
  1411.  
  1412. #endif
  1413.  
  1414.  
  1415. /*
  1416.  *  A public domain implementation of BSD directory routines for
  1417.  *  MS-DOS.  Written by Michael Rendell ({uunet,utai}michael@garfield),
  1418.  *  August 1897
  1419.  *  Ported to OS/2 by Kai Uwe Rommel
  1420.  *  December 1989, February 1990
  1421.  *  Change for HPFS support, October 1990
  1422.  */
  1423.  
  1424. int attributes = A_DIR | A_HIDDEN;
  1425.  
  1426. static char *getdirent(char *);
  1427. static void free_dircontents(struct _dircontents *);
  1428.  
  1429. static HDIR hdir;
  1430. #ifdef __32BIT__
  1431. static ULONG count;
  1432. static FILEFINDBUF3 find;
  1433. #define DosFindFirst(p1, p2, p3, p4, p5, p6) \
  1434.         DosFindFirst(p1, p2, p3, p4, p5, p6, 1)
  1435. #define DosQCurDisk     DosQueryCurrentDisk
  1436. #define DosQFSAttach    DosQueryFSAttach
  1437. #define DosQFSInfo      DosQueryFSInfo
  1438. #else
  1439. static USHORT count;
  1440. static FILEFINDBUF find;
  1441. #define DosFindFirst(p1, p2, p3, p4, p5, p6) \
  1442.         DosFindFirst(p1, p2, p3, p4, p5, p6, 0)
  1443. #define DosQFSAttach(p1, p2, p3, p4, p5) \
  1444.         DosQFSAttach(p1, p2, p3, p4, p5, 0)
  1445. #endif
  1446.  
  1447. int IsFileSystemFAT(char *dir)
  1448. {
  1449.   static USHORT nLastDrive = -1, nResult;
  1450.   ULONG lMap;
  1451.   BYTE bData[64], bName[3];
  1452. #ifdef __32BIT__
  1453.   ULONG nDrive, cbData;
  1454.   FSQBUFFER2 *pData = (FSQBUFFER2 *) bData;
  1455. #else
  1456.   USHORT nDrive, cbData;
  1457.   FSQBUFFER *pData = (FSQBUFFER *) bData;
  1458. #endif
  1459.  
  1460.   /* We separate FAT and HPFS file systems here. */
  1461.  
  1462.   if ( isalpha(dir[0]) && (dir[1] == ':') )
  1463.     nDrive = toupper(dir[0]) - '@';
  1464.   else
  1465.     DosQCurDisk(&nDrive, &lMap);
  1466.  
  1467.   if ( nDrive == nLastDrive )
  1468.     return nResult;
  1469.  
  1470.   bName[0] = (char) (nDrive + '@');
  1471.   bName[1] = ':';
  1472.   bName[2] = 0;
  1473.  
  1474.   nLastDrive = nDrive;
  1475.   cbData = sizeof(bData);
  1476.  
  1477.   if ( !DosQFSAttach(bName, 0, FSAIL_QUERYNAME, (PVOID) pData, &cbData) )
  1478.     nResult = !strcmp(pData -> szFSDName + pData -> cbName, "FAT");
  1479.   else
  1480.     nResult = FALSE;
  1481.  
  1482.   return nResult;
  1483. }
  1484.  
  1485. DIR *opendir(char *name)
  1486. {
  1487.   struct stat statb;
  1488.   DIR *dirp;
  1489.   char c;
  1490.   char *s;
  1491.   struct _dircontents *dp;
  1492.   char nbuf[MAXPATHLEN + 1];
  1493.   int len;
  1494.  
  1495.   strcpy(nbuf, name);
  1496.   len = strlen (nbuf);
  1497.   s = nbuf + len;
  1498.  
  1499.   if ( ((c = nbuf[strlen(nbuf) - 1]) == '\\' || c == '/') &&
  1500.        (strlen(nbuf) > 1) )
  1501.   {
  1502.     nbuf[strlen(nbuf) - 1] = 0;
  1503.  
  1504.     if ( nbuf[strlen(nbuf) - 1] == ':' )
  1505.       strcat(nbuf, "\\.");
  1506.   }
  1507.   else
  1508.     if ( nbuf[strlen(nbuf) - 1] == ':' )
  1509.       strcat(nbuf, ".");
  1510.  
  1511.   if (stat(nbuf, &statb) < 0 || (statb.st_mode & S_IFMT) != S_IFDIR)
  1512.     return NULL;
  1513.  
  1514.   if ( (dirp = malloc(sizeof(DIR))) == NULL )
  1515.     return NULL;
  1516.  
  1517.   if ( nbuf[strlen(nbuf) - 1] == '.' )
  1518.     strcpy(nbuf + strlen(nbuf) - 1, "*.*");
  1519.   else
  1520.     if ( ((c = nbuf[strlen(nbuf) - 1]) == '\\' || c == '/') &&
  1521.          (strlen(nbuf) == 1) )
  1522.       strcat(nbuf, "*.*");
  1523.     else
  1524.       strcat(nbuf, "\\*.*");
  1525.  
  1526.   dirp -> dd_loc = 0;
  1527.   dirp -> dd_contents = dirp -> dd_cp = NULL;
  1528.  
  1529.   if ((s = getdirent(nbuf)) == NULL)
  1530.     return dirp;
  1531.  
  1532.   do
  1533.   {
  1534.     if (((dp = malloc(sizeof(struct _dircontents))) == NULL) ||
  1535.         ((dp -> _d_entry = malloc(strlen(s) + 1)) == NULL)      )
  1536.     {
  1537.       if (dp)
  1538.         free(dp);
  1539.       free_dircontents(dirp -> dd_contents);
  1540.  
  1541.       return NULL;
  1542.     }
  1543.  
  1544.     if (dirp -> dd_contents)
  1545.     {
  1546.       dirp -> dd_cp -> _d_next = dp;
  1547.       dirp -> dd_cp = dirp -> dd_cp -> _d_next;
  1548.     }
  1549.     else
  1550.       dirp -> dd_contents = dirp -> dd_cp = dp;
  1551.  
  1552.     strcpy(dp -> _d_entry, s);
  1553.     dp -> _d_next = NULL;
  1554.  
  1555.     dp -> _d_size = find.cbFile;
  1556.     dp -> _d_mode = find.attrFile;
  1557.     dp -> _d_time = *(unsigned *) &(find.ftimeLastWrite);
  1558.     dp -> _d_date = *(unsigned *) &(find.fdateLastWrite);
  1559.   }
  1560.   while ((s = getdirent(NULL)) != NULL);
  1561.  
  1562.   dirp -> dd_cp = dirp -> dd_contents;
  1563.  
  1564.   return dirp;
  1565. }
  1566.  
  1567.  
  1568. void closedir(DIR * dirp)
  1569. {
  1570.   free_dircontents(dirp -> dd_contents);
  1571.   free(dirp);
  1572. }
  1573.  
  1574.  
  1575. struct dirent *readdir(DIR * dirp)
  1576. {
  1577.   static struct dirent dp;
  1578.  
  1579.   if (dirp -> dd_cp == NULL)
  1580.     return NULL;
  1581.  
  1582.   dp.d_namlen = dp.d_reclen =
  1583.     strlen(strcpy(dp.d_name, dirp -> dd_cp -> _d_entry));
  1584.  
  1585.   dp.d_ino = 1;
  1586.  
  1587.   dp.d_size = dirp -> dd_cp -> _d_size;
  1588.   dp.d_mode = dirp -> dd_cp -> _d_mode;
  1589.   dp.d_time = dirp -> dd_cp -> _d_time;
  1590.   dp.d_date = dirp -> dd_cp -> _d_date;
  1591.  
  1592.   dirp -> dd_cp = dirp -> dd_cp -> _d_next;
  1593.   dirp -> dd_loc++;
  1594.  
  1595.   return &dp;
  1596. }
  1597.  
  1598.  
  1599. void seekdir(DIR * dirp, long off)
  1600. {
  1601.   long i = off;
  1602.   struct _dircontents *dp;
  1603.  
  1604.   if (off >= 0)
  1605.   {
  1606.     for (dp = dirp -> dd_contents; --i >= 0 && dp; dp = dp -> _d_next);
  1607.  
  1608.     dirp -> dd_loc = off - (i + 1);
  1609.     dirp -> dd_cp = dp;
  1610.   }
  1611. }
  1612.  
  1613.  
  1614. long telldir(DIR * dirp)
  1615. {
  1616.   return dirp -> dd_loc;
  1617. }
  1618.  
  1619.  
  1620. static void free_dircontents(struct _dircontents * dp)
  1621. {
  1622.   struct _dircontents *odp;
  1623.  
  1624.   while (dp)
  1625.   {
  1626.     if (dp -> _d_entry)
  1627.       free(dp -> _d_entry);
  1628.  
  1629.     dp = (odp = dp) -> _d_next;
  1630.     free(odp);
  1631.   }
  1632. }
  1633.  
  1634.  
  1635. char *getdirent(char *dir)
  1636. {
  1637.   int done;
  1638.   static int lower = TRUE;
  1639.  
  1640.   if (dir != NULL)
  1641.   {                       /* get first entry */
  1642.     lower = IsFileSystemFAT(dir);
  1643.  
  1644.     hdir = HDIR_CREATE;
  1645.     count = 1;
  1646.     done = DosFindFirst(dir, &hdir, attributes, &find, sizeof(find), &count);
  1647.   }
  1648.   else                       /* get next entry */
  1649.     done = DosFindNext(hdir, &find, sizeof(find), &count);
  1650.  
  1651.   if (done == 0)
  1652.   {
  1653.     if ( lower )
  1654.       strlwr(find.achName);
  1655.     return find.achName;
  1656.   }
  1657.   else
  1658.   {
  1659.     DosFindClose(hdir);
  1660.     return NULL;
  1661.   }
  1662. }
  1663.  
  1664. #endif /* __EMX__ */
  1665.  
  1666. #ifdef __IBMC__
  1667.  
  1668. /* quick hack because IBM C lacks popen() and pclose() */
  1669.  
  1670. int pids[64];
  1671.  
  1672. FILE *
  1673. popen(char *cmd, char *mode) {
  1674.   HFILE end1, end2, std, old1, old2, temp;
  1675.   FILE *file;
  1676.   char fail[256], cmd_line[256], *cmd_exe, *args;
  1677.   RESULTCODES res;
  1678.   int rc;
  1679.  
  1680.   if (DosCreatePipe(&end1, &end2, 4096))
  1681.     return NULL;
  1682.  
  1683.   std = (*mode == 'w') ? 0 /* stdin */ : 1 /* stdout */;
  1684.   if (std == 0) {
  1685.     temp = end1; end1 = end2; end2 = temp;
  1686.   }
  1687.  
  1688.   old1 = -1; /* save stdin or stdout */
  1689.   DosDupHandle(std, &old1);
  1690.   DosSetFHState(old1, OPEN_FLAGS_NOINHERIT);
  1691.   temp = std; /* redirect stdin or stdout */
  1692.   DosDupHandle(end2, &temp);
  1693.  
  1694.   if ( std == 1 ) {
  1695.     old2 = -1; /* save stderr */
  1696.     DosDupHandle(2, &old2);
  1697.     DosSetFHState(old2, OPEN_FLAGS_NOINHERIT);
  1698.     temp = 2;   /* redirect stderr */
  1699.     DosDupHandle(end2, &temp);
  1700.   }
  1701.  
  1702.   DosClose(end2);
  1703.   DosSetFHState(end1, OPEN_FLAGS_NOINHERIT);
  1704.  
  1705.   if ( (cmd_exe = getenv("COMSPEC")) == NULL )
  1706.     cmd_exe = "cmd.exe";
  1707.  
  1708.   strcpy(cmd_line, cmd_exe);
  1709.   args = cmd_line + strlen(cmd_line) + 1; /* skip zero */
  1710.   strcpy(args, "/c ");
  1711.   strcat(args, cmd);
  1712.   args[strlen(args) + 1] = '\0'; /* two zeroes */
  1713.   rc = DosExecPgm(fail, sizeof(fail), EXEC_ASYNCRESULT, 
  1714.           cmd_line, 0, &res, cmd_exe);
  1715.  
  1716.   temp = std; /* restore stdin or stdout */
  1717.   DosDupHandle(old1, &temp);
  1718.   DosClose(old1);
  1719.  
  1720.   if ( std == 1 ) {
  1721.     temp = 2;   /* restore stderr */
  1722.     DosDupHandle(old2, &temp);
  1723.     DosClose(old2);
  1724.   }
  1725.  
  1726.   if (rc) {
  1727.     DosClose(end1);
  1728.     return NULL;
  1729.   }
  1730.   
  1731.   file = fdopen(end1, mode);
  1732.   pids[end1] = res.codeTerminate;
  1733.   return file;
  1734. }
  1735.  
  1736. int
  1737. pclose(FILE *pipe) {
  1738.   RESULTCODES rc;
  1739.   PID pid;
  1740.   int handle = fileno(pipe);
  1741.   fclose(pipe);
  1742.   if (pids[handle])
  1743.     DosWaitChild(DCWA_PROCESSTREE, DCWW_WAIT, &rc, &pid, pids[handle]);
  1744.   pids[handle] = 0;
  1745.   return rc.codeTerminate == 0 ? rc.codeResult : -1;
  1746. }
  1747. #endif
  1748.  
  1749. void
  1750. ChangeNameForFAT(char *name) {
  1751.   char *src, *dst, *next, *ptr, *dot, *start;
  1752.   static char invalid[] = ":;,=+\"[]<>| \t";
  1753.  
  1754.   if ( isalpha(name[0]) && (name[1] == ':') )
  1755.     start = name + 2;
  1756.   else
  1757.     start = name;
  1758.  
  1759.   src = dst = start;
  1760.   if ( (*src == '/') || (*src == '\\') )
  1761.     src++, dst++;
  1762.  
  1763.   while ( *src )
  1764.   {
  1765.     for ( next = src; *next && (*next != '/') && (*next != '\\'); next++ );
  1766.  
  1767.     for ( ptr = src, dot = NULL; ptr < next; ptr++ )
  1768.       if ( *ptr == '.' )
  1769.       {
  1770.         dot = ptr; /* remember last dot */
  1771.         *ptr = '_';
  1772.       }
  1773.  
  1774.     if ( dot == NULL )
  1775.       for ( ptr = src; ptr < next; ptr++ )
  1776.         if ( *ptr == '_' )
  1777.           dot = ptr; /* remember last _ as if it were a dot */
  1778.  
  1779.     if ( dot && (dot > src) &&
  1780.          ((next - dot <= 4) ||
  1781.           ((next - src > 8) && (dot - src > 3))) )
  1782.     {
  1783.       if ( dot )
  1784.         *dot = '.';
  1785.  
  1786.       for ( ptr = src; (ptr < dot) && ((ptr - src) < 8); ptr++ )
  1787.         *dst++ = *ptr;
  1788.  
  1789.       for ( ptr = dot; (ptr < next) && ((ptr - dot) < 4); ptr++ )
  1790.         *dst++ = *ptr;
  1791.     }
  1792.     else
  1793.     {
  1794.       if ( dot && (next - src == 1) )
  1795.         *dot = '.';           /* special case: "." as a path component */
  1796.  
  1797.       for ( ptr = src; (ptr < next) && ((ptr - src) < 8); ptr++ )
  1798.         *dst++ = *ptr;
  1799.     }
  1800.  
  1801.     *dst++ = *next; /* either '/' or 0 */
  1802.  
  1803.     if ( *next )
  1804.     {
  1805.       src = next + 1;
  1806.  
  1807.       if ( *src == 0 ) /* handle trailing '/' on dirs ! */
  1808.         *dst = 0;
  1809.     }
  1810.     else
  1811.       break;
  1812.   }
  1813.  
  1814.   for ( src = start; *src != 0; ++src )
  1815.     if ( strchr(invalid, *src) != NULL )
  1816.         *src = '_';
  1817. }
  1818.  
  1819.  
  1820. int IsFileNameValid(char *name)
  1821. {
  1822.   HFILE hf;
  1823. #ifdef __32BIT__
  1824.   ULONG uAction;
  1825. #else
  1826.   USHORT uAction;
  1827. #endif
  1828.  
  1829.   switch( DosOpen(name, &hf, &uAction, 0, 0, FILE_OPEN,
  1830.                   OPEN_ACCESS_READONLY | OPEN_SHARE_DENYNONE, 0) )
  1831.   {
  1832.   case ERROR_INVALID_NAME:
  1833.   case ERROR_FILENAME_EXCED_RANGE:
  1834.     return FALSE;
  1835.   case NO_ERROR:
  1836.     DosClose(hf);
  1837.   default:
  1838.     return TRUE;
  1839.   }
  1840. }
  1841.  
  1842. long
  1843. zdskspace(int drive) {
  1844.   FSALLOCATE fsa;
  1845.   if ( DosQFSInfo(drive, 1, (PBYTE) &fsa, sizeof(fsa)) )
  1846.     return 0;
  1847.   return fsa.cUnitAvail * fsa.cSectorUnit * fsa.cbSector;
  1848. }
  1849.  
  1850. char *
  1851. GetLoadPath(void) {
  1852. #ifdef __32BIT__
  1853.   PTIB pptib;
  1854.   PPIB pppib;
  1855.   char *szPath;
  1856.  
  1857.   DosGetInfoBlocks(&pptib, &pppib);
  1858.  
  1859.   szPath = pppib -> pib_pchenv;
  1860.  
  1861.   while (*szPath)
  1862.     szPath = strchr(szPath, 0) + 1;
  1863.  
  1864.   return szPath + 1;
  1865. #else
  1866.   extern char *_pgmptr;
  1867.   return _pgmptr;
  1868. #endif
  1869. }
  1870.