home *** CD-ROM | disk | FTP | other *** search
/ Columbia Kermit / kermit.zip / archives / ck9196.zip / ck9tio.c < prev    next >
C/C++ Source or Header  |  1999-06-02  |  64KB  |  1,899 lines

  1. char *ckxv = "OS-9 Communications I/O, 7.0.017, 31 May 1999";
  2.  
  3. /*  C K 9 T I O  */
  4.  
  5. /* C-Kermit interrupt, terminal control & i/o functions for os9/68k systems */
  6.  
  7. /*
  8.  Author: Peter Scholz
  9.  Ruhr University Bochum, Department of analytical chemistry
  10.  Federal Republic of Germany, February 1987
  11.  
  12.  Bob Larson (Blarson@ecla.usc.edu)
  13.  Cleanup, fix timeouts, fix connect escape
  14.  Rewrite ttinl for less overhead
  15.  
  16.  Edition: 5A(01)
  17.  Chris Hemsing (Chris@lfm.rwth-aachen.de)
  18.  Cleaned up timed i/o using F$Alarm
  19.  Tmode/Xmode stuff
  20.  Send break stuff
  21.  All time related stuff new
  22.  
  23.  07/25/91 Chris  Hemsing        minor bug fixes, changes for gnu (ansi) C
  24.  
  25.  12/02/91 Bob Larson    Blarson@usc.edu
  26.         alarm() code was a nice idea, but doesn't work.  Fixed back to
  27.         code that will interupt i/o in progress. Minor cleanup.
  28.         Retrofited current unix myread() code to speed things back up.
  29.  
  30.  01/14/92 Chris  Hemsing        minor xmode bug fixes, sigmask <->longjump
  31.                                 OS-9 does interrupt i/o, but bad drivers don't
  32.                                 -> alarm code not reintroduced.
  33.  Edition: 5A(05)
  34.           Bob Larson            conchk bug fix
  35.  Edition: 5A(06)
  36.  03/04/92 Chris  Hemsing        ttopen: dup(0) fix, compare upper case
  37.  Edition: 5A(07)
  38.  09/28/92 Chris  Hemsing        cccbrk bug fix
  39.  Edition: 5A(08)
  40.  10/12/92 Chris  Hemsing        improved CTRL-E handling (catch)
  41.  Edition: 5A(09)
  42.  12/09/93 ?                     added TRANSFER CANCELLATION variables
  43.  Edition: 5A(10)
  44.  12/23/94 Ulli Schlueter        improved performance (system load is reduced
  45.                                 about 80% on my system (68020, 25MHz) with the
  46.                                 little sleep in myread():achieved an efficiency
  47.                                 of 96% in a system transfer loop (two kermits
  48.                                 running on the same system) with all characters
  49.                                 unprefixed and a packet size of 2K at 19200),
  50.                                 fixed xfrnum bug and brought ttinl() near to
  51.                                 the unix version, added support of CK_REDIR,
  52.                                 added O_GOODRIVER compilation flag for
  53.                                 carefully written drivers (add or remove it
  54.                                 in the makefile)
  55.  Edition: 5A(11)
  56.  01/26/95 Ulli Schlueter        network support
  57.  Edition: 5A(12)
  58.  03/20/95 Ulli Schlueter        ttopen() accepts `/nil'
  59.  Edition: 5A(13)
  60.  04/21/95 Ulli Schlueter        tthang() has called netclos() and so the
  61.                                 event was not deleted
  62.  Edition: 5A(14)
  63.  04/25/95 Ulli Schlueter        Changed network ttopen() (event creation).
  64.  Edition: 5A(15)
  65.  06/20/95 Ulli Schlueter        Added MORE_DYNAMIC (not enabled), removed
  66.                                 `dfttystr[]'.
  67.  Edition: 5A(16)
  68.  28 May 99 Martin Whitaker    Added ttgwsiz().
  69.  31 May 99 Martin Whitaker    Removed declaration of ttnproto for non-
  70.                 networked versions - this is in ckcnet.c.
  71.  Edition: 7.0.017
  72.  
  73.   Adapted from UNIX C-Kermit.
  74.   Author: Frank da Cruz <fdc@columbia.edu>
  75.  
  76.   Copyright (C) 1985, 1999, Trustees of Columbia University in the City of New
  77.   York.  The C-Kermit software may not be, in whole or in part, licensed or
  78.   sold for profit as a software product itself, nor may it be included in or
  79.   distributed with commercial products or otherwise distributed by commercial
  80.   concerns to their clients or customers without written permission of the
  81.   Office of Kermit Development and Distribution, Columbia University.  This
  82.   copyright notice must not be removed, altered, or obscured.
  83. */
  84. #include <dir.h>   /* Directory */
  85. #ifdef NULL
  86. #undef NULL
  87. #endif /* NULL */
  88. #ifndef GREGORIAN
  89. #define GREGORIAN 0
  90. #define JULIAN 1
  91. #endif
  92. #include <signal.h>     /* Interrupts */
  93. #include <errno.h>
  94. #include <sgstat.h>     /* Set/Get tty modes */
  95. #include <sg_codes.h>   /* setstat/getstat function codes */
  96. #include <setsys.h>
  97. #include <setjmp.h>
  98. #include <strings.h>
  99. #include <time.h>
  100. #include <modes.h>      /* osk i/o modes S_IREAD, etc */
  101. #include "ckcsym.h"
  102. #include "ckcdeb.h"     /* Typedefs, formats for debug() */
  103. #include "ckcnet.h"
  104.  
  105. /* Maximum length for the name of a tty device */
  106.  
  107. #ifndef DEVNAMLEN
  108. #define DEVNAMLEN MAXNAMLEN*4+2 /* leave room for / and terminating \0 */
  109. #endif                          /* not really an OS-9 restriction */
  110.                                 /* *4 is arbitrary */
  111.                                 /* nfm getstat call bug: SS_DevNm always
  112.                                    copies all 32 bytes, nfm does the first
  113.                                    part of the name => sum is more than
  114.                                    32 bytes
  115.                                    e.g "term": all fine
  116.                                    because 32 bytes incl. "term" are copied
  117.                                    "n0/node1/term":  "n0/node1/" done by nfm
  118.                                    "term" is done by remote's scf
  119.                                    (32 bytes) */
  120. char *ckxsys = " OS-9/68000";
  121.  
  122. #define MYREAD                  /* use improved input code */
  123.                                 /* Warning: untested without this defiend */
  124.  
  125. /*
  126.    For drivers that interrupt I/O when signal code is less than S_DEADLY
  127. */
  128. #ifndef O_GOODDRIVER
  129. /*#define O_GOODDRIVER let's do it in the command line */
  130. #endif /* !O_GOODDRIVER */
  131.  
  132. /*
  133.  Variables available to outside world:
  134.  
  135.    dftty  -- Pointer to default tty name string, like "/dev/tty".
  136.    dfloc  -- 0 if dftty is console, 1 if external line.
  137.    dfprty -- Default parity
  138.    dfflow -- Default flow control
  139.    ckxech -- Flag for who echoes console typein:
  140.      1 - The program (system echo is turned off)
  141.      0 - The system (or front end, or terminal).
  142.    functions that want to do their own echoing should check this flag
  143.    before doing so.
  144.  
  145.  Functions for assigned communication line (either external or console tty):
  146.  
  147.    syscleanup()            -- System dependent shutdown
  148.    sysinit()               -- System dependent program initialization
  149.    ttopen(ttname,local,mdmtyp,timo) -- Open the named tty for exclusive access.
  150.    ttclos()                -- Close & reset the tty.
  151.    ttpkt(speed,flow)       -- Put the tty in packet mode and set the speed.
  152.    ttvt(speed,flow)        -- Put the tty in virtual terminal mode.
  153.     or in DIALING or CONNECTED modem control state.
  154.    ttinl(dest,max,timo)    -- Timed read line from the tty.
  155.    ttinc(timo)             -- Timed read character from tty.
  156.    myread()                -- Raw mode bulk buffer read, gives subsequent
  157.                                 chars one at a time and simulates FIONREAD.
  158.    myunrd(c)               -- Places c back in buffer to be read (one only)
  159.    ttchk()                 -- See how many characters in tty input buffer.
  160.    ttxin(n,buf)            -- Read n characters from tty (untimed).
  161.    ttol(string,length)     -- Write a string to the tty.
  162.    ttoc(c)                 -- Write a character to the tty.
  163.    ttflui()                -- Flush tty input buffer.
  164.  */
  165.  
  166. /*
  167. Functions for console terminal:
  168.  
  169.    congm()   -- Get console terminal modes.
  170.    concb(esc) -- Put the console in single-character wakeup mode with no echo.
  171.    conbin(esc) -- Put the console in binary (raw) mode.
  172.    conres()  -- Restore the console to mode obtained by congm().
  173.    conoc(c)  -- Unbuffered output, one character to console.
  174.    conol(s)  -- Unbuffered output, null-terminated string to the console.
  175.    conola(s) -- Unbuffered output, array of strings to the console.
  176.    conxo(n,s) -- Unbuffered output, n characters to the console.
  177.    conchk()  -- Check if characters available at console (bsd 4.2).
  178.   Check if escape char (^\) typed at console (System III/V).
  179.    coninc(timo)  -- Timed get a character from the console.
  180.    conint()  -- Enable terminal interrupts on the console if not background.
  181.    connoi()  -- Disable terminal interrupts on the console if not background.
  182.  
  183. Time functions
  184.  
  185.    msleep(m) -- Millisecond sleep
  186.    ztime(s) -- Return date/time string
  187.    rtimer() --  Reset timer
  188.    gtimer()  -- Get elapsed time since last call to rtimer()
  189. */
  190.  
  191. /* Declarations */
  192.  
  193. extern int errno;   /* System call error return */
  194.  
  195. /* dftty is the device name of the default device for file transfer */
  196. /* dfloc is 0 if dftty is the user's console terminal, 1 if an external line */
  197.  
  198.     char *dftty;        /* Remote by default, use normal */
  199.     int dfloc = 0;      /* controlling terminal name. */
  200.  
  201.     int dfprty = 0;     /* Parity (0 = none) */
  202.     int ttprty = 0;     /* current parity */
  203.     int ttpflg = 0;     /* Parity not sensed yet */
  204.     static int ttpmsk = 0377;           /* Parity stripping mask. */
  205.     int ttmdm = 0;      /* Modem in use */
  206.     int dfflow = 1;     /* Xon/Xoff flow control */
  207.     int backgrd = 0;    /* Assume in foreground (no '&' ) */
  208.  
  209.     int ckxech = 0;     /* 0 if system normally echoes console characters, else
  210.  1 */
  211.  
  212.     int ttyfd = -1;    /* TTY path number, also used in ck9con.c */
  213.  
  214.     int ttcarr = CAR_AUT;               /* Carrier handling mode. */
  215.  
  216. #ifdef NETCONN
  217. extern int ttnproto;                    /* Defined in ckcnet.c */
  218. extern int ttnet;                       /* Defined in ckcnet.c */
  219. #endif /* NETCONN */
  220. extern int xfrcan, xfrchr, xfrnum;      /* Defined in ckcmai.c */
  221.  
  222. int csigflg, tsigflg; /* console/tty signal flags (incremented by catch()) */
  223.  
  224. /* Declarations of variables global within this module */
  225.  
  226. static char ttnmsv[DEVNAMLEN];   /* always name of ttyfd device */
  227. char myttystr[DEVNAMLEN];
  228. static int
  229.     xlocal = 0;    /* Flag for tty local or remote */
  230.  
  231. #ifdef NETCONN
  232. static int netconn = 0;  /* 1 if network connection active */
  233. static char ttevnm[12];
  234. int ttevid;
  235. #endif /* NETCONN */
  236.  
  237. static struct sgbuf      /* sgtty info... */
  238. #ifndef MORE_DYNAMIC
  239.   ttold, ttraw, tttvt,   /* for communication line */
  240.   ccold, ccraw, cccbrk;  /* and for console */
  241. #else /* MORE_DYNAMIC */
  242.   *ttold_, *ttraw_, *tttvt_,   /* for communication line */
  243.   *ccold_, *ccraw_, *cccbrk_;  /* and for console */
  244. #define ttold (*ttold_)
  245. #define ttraw (*ttraw_)
  246. #define tttvt (*tttvt_)
  247. #define ccold (*ccold_)
  248. #define ccraw (*ccraw_)
  249. #define cccbrk (*cccbrk_)
  250. #endif /* MORE_DYNAMIC */
  251.  
  252. static time_t   tcount;   /* Elapsed time counter */
  253. static time_t   timowhen; /* timeout time */
  254.  
  255. static SIGTYP (*saval)() = NULL;                /* For saving alarm handler */
  256. static jmp_buf sjbuf;                   /* Longjump buffers */
  257. static SIGTYP timerh();
  258.  
  259. #define B50     0
  260. #define B75     1
  261. #define B110    2
  262. #define B134    3
  263. #define B150    4
  264. #define B300    5
  265. #define B600    6
  266. #define B1200   7
  267. #define B1800   8
  268. #define B2000   9
  269. #define B2400  10
  270. #define B3600  11
  271. #define B4800  12
  272. #define B7200  13
  273. #define B9600  14
  274. #define B19200 15
  275. #define B38400 16
  276.  
  277. static unsigned short bdrts[] = {
  278.         50, 75, 110, 134, 150, 300, 600, 1200,
  279.         1800, 2000, 2400, 3600, 4800, 7200, 9600, 19200, 38400
  280. };
  281.  
  282. /* for unix signal emulation */
  283.  
  284. #define MAXSIG 4
  285. typedef VOID (*fptr)();
  286. fptr sigtbl[MAXSIG+1];
  287. fptr signal();
  288.  
  289. syscleanup() {
  290.     return 0;                   /* none needed */
  291. }
  292.  
  293. /*  S Y S I N I T  --  System-dependent program initialization.  */
  294.  
  295. sysinit() {
  296. /* initialize unix signal emulation */
  297.     register int i;
  298.     register char *cp;
  299.     VOID catch();
  300.     char *getenv();
  301.  
  302.     for(i=0;i<=MAXSIG;i++)
  303.         sigtbl[i] = SIG_DFL;
  304.     intercept(catch);
  305.     if(isatty(0)) {             /* must disable buffering before io */
  306.         setbuf(stdin,(char *)NULL);
  307.         setbuf(stdout,(char *)NULL);
  308.     }
  309.     /* get terminal name from enviornment variable PORT,
  310.      * use device of stderr as a backup
  311.      */
  312.     myttystr[0] = '/';
  313.     if((cp = getenv("PORT")) == NULL) {
  314.         if(_gs_devn(2, myttystr+1) < 0) return -1;
  315.     } else strcpy(myttystr, cp);
  316.     dftty = &myttystr[0];
  317.     backgrd = (isatty(0) && isatty(1)) ? 0 : 1;
  318. #ifdef MORE_DYNAMIC
  319.     if ((cp = malloc(sizeof ttold + sizeof ttraw + sizeof tttvt + sizeof ccold
  320.                      + sizeof ccraw + sizeof cccbrk)) == NULL)
  321.       return -1;
  322.     ttold_ = (void *)cp;
  323.     ttraw_ = ttold_ + 1;
  324.     tttvt_ = ttraw_ + 1;
  325.     ccold_ = tttvt_ + 1;
  326.     ccraw_ = ccold_ + 1;
  327.     cccbrk_ = ccraw_ + 1;
  328. #endif /* MORE_DYNAMIC */
  329.     congm();
  330.     return 0;
  331. }
  332.  
  333. /*  T T O P E N  --  Open a tty for exclusive access.  */
  334.  
  335. /*
  336.   Call with:
  337.     ttname: character string - device name or network host name.
  338.     lcl:
  339.   If called with lcl < 0, sets value of lcl as follows:
  340.   0: the terminal named by ttname is the job's controlling terminal.
  341.   1: the terminal named by ttname is not the job's controlling terminal.
  342.   But watch out: if a line is already open, or if requested line can't
  343.   be opened, then lcl remains (and is returned as) -1.
  344.     modem:
  345.   Less than zero: ttname is a network host name.
  346.   Zero or greater: ttname is a terminal device name.
  347.   Zero means a local connection (don't use modem signals).
  348.   Positive means use modem signals.
  349.    timo:
  350.   0 = no timer.
  351.   nonzero = number of seconds to wait for open() to return before timing out.
  352.  
  353.   Returns:
  354.     0 on success
  355.    -5 if device is in use
  356.    -4 if access to device is denied
  357.    -3 if access to lock directory denied
  358.    -2 upon timeout waiting for device to open
  359.    -1 on other error
  360. */
  361.  
  362. int
  363. ttopen(ttname,lcl,modem,timo) char *ttname; int *lcl, modem, timo; {
  364.  
  365. char dev_buffer[DEVNAMLEN];
  366.     debug(F111,"ttopen entry modem",ttname,modem);
  367.     debug(F101," ttyfd","",ttyfd);
  368.     debug(F101," lcl","",*lcl);
  369.  
  370.     if (ttyfd > -1)             /* if device already opened */
  371.     {
  372.         if (ustrncmp(ttname,ttnmsv,DEVNAMLEN))/* are new & old names equal? */
  373.                                               /* compare ignoring case */
  374.           ttclos(0);                    /* no, close old ttname, open new */
  375.         else                            /* else same, ignore this call, */
  376.           return(0);                    /* and return. */
  377.     }
  378.  
  379. #ifdef  NETCONN
  380.     if (modem < 0) {                    /* modem < 0 = special code for net */
  381.         int x;
  382.         ttmdm = modem;
  383.         modem = -modem;                 /* Positive network type number */
  384.         /*fdflag = 0;*/                     /* Stdio not redirected. */
  385.         netconn = 1;                    /* And it's a network connection */
  386.         debug(F111,"ttopen net",ttname,modem);
  387.         x = netopen(ttname, lcl, modem); /* (see ckcnet.h) */
  388.         if (x >= 0) {
  389.             strncpy(ttnmsv,ttname,DEVNAMLEN);
  390.             sprintf(ttevnm, "cktn%d", getpid());
  391.             if ((x = _ev_creat(0, -1, -1, ttevnm)) == -1) {
  392.                 debug(F101, "ttopen ev_creat errno", "", errno);
  393.             }
  394.             else if ((x = _ss_sevent(ttyfd, ttevid = x)) == -1) {
  395.                 debug(F101, "ttopen sevent errno", "", errno);
  396.             }
  397. #if 0
  398.             else if (_gs_opt(ttyfd, &ttold) != -1) {
  399.                 if (ttold.sg_class == DT_SOCK) {
  400.                     ttold.sg_noblock = 0;
  401.                     if (_ss_opt(ttyfd, &ttold) != -1)
  402.                       debug(F100, "ttopen sockio blocking", "", 0);
  403.                 }
  404.             }
  405. #endif /* 0 */
  406.             if (x == -1) ttclos(0); /* Let ttclos do the clean up */
  407.         } else {
  408.             netconn = 0;
  409.         }
  410.  
  411.  
  412.         xlocal = *lcl = 1;              /* Network connections are local. */
  413.         debug(F101,"ttopen net x","",x);
  414.         return(x);
  415.     }
  416. #endif /* NETCONN */
  417.  
  418.     if (timo < 0) timo = 0;             /* Safety */
  419.     if (setjmp(sjbuf))                  /* Timer went off? */
  420.     {
  421.         debug(F100,"ttopen timout","",0); /*    Get here on timeout. */
  422.         return(-2);                     /* and return error code. */
  423.     }
  424.     else
  425.     {
  426.         if (timo)
  427.         {                           /* Don't time out if timo == 0 */
  428.             /* This won't work, since alarm() will not interupt i/o. */
  429.             /* Unfortunatatly, there is no non-blocking open to replace */
  430.             /* it with.   blarson@usc.edu */
  431.             /* Alarm will interrupt i/o when using a proper driver that */
  432.             /* checks for pending signals smaller than deadly */
  433.             /* chris@lfm.rwth-aachen.de */
  434.             saval = signal(SIGALRM,timerh); /* Enable timer interrupt */
  435.             alarm((unsigned int)timo);                      /* Set it. */
  436.         }
  437.         strncpy(ttnmsv,ttname,DEVNAMLEN); /* keep ttnmsv corresp. to ttyfd */
  438.         dev_buffer[0] = '/';
  439.         _gs_devn(0,&dev_buffer[1]);         /* get name of stdin */
  440.         if (*ttname == '\0' || ustrncmp(ttname,dev_buffer,DEVNAMLEN) == 0
  441.           || strcmp(ttname, "/nil") == 0)
  442.           ttyfd = open(ttname,S_IREAD|S_IWRITE);
  443.           /* Try open for read/write; we cannot open own stdin non-share*/
  444.           /* Don't simply dup(0) or dup(1); they might only be open
  445.              for mere read (0) or mere write (1) */
  446.         else
  447.           ttyfd = open(ttname,S_IREAD|S_IWRITE|S_ISHARE); /* Try to open for
  448.           read/write nonshare*/
  449.         if (timo)
  450.             ttimoff();                  /* Turn off timer */
  451.         if (ttyfd < 0)      /* If couldn't open, fail. */
  452.         {
  453.             perror(ttname);
  454.             if ((errno == E_DEVBSY) ||
  455.                 (errno == E_SHARE )) return(-5);
  456.             return(-1);
  457.         }
  458.     }
  459.     debug(F111,"ttopen ok",ttname,*lcl);
  460.  
  461.  
  462. /* Caller wants us to figure out if line is controlling tty */
  463.  
  464.     if (*lcl == -1)
  465.     {
  466.         if (isatty(0))
  467.         {               /* if stdin not redirected */
  468.             dev_buffer[0] = '/';
  469.             _gs_devn(0,&dev_buffer[1]); /* ...with real name of stdin   */
  470.             xlocal = (ustrncmp(ttname,dev_buffer,DEVNAMLEN) != 0);
  471.             debug(F111," ttyname",dev_buffer,xlocal);
  472.         }
  473.         else   /* Else, if stdin redirected... */
  474.         {
  475.         /* Just assume local, so "set speed" and similar commands will work */
  476.         /* If not really local, how could it work anyway?... */
  477.             xlocal = 1;
  478.             debug(F101," redirected stdin","",xlocal);
  479.         }
  480.     }
  481.  
  482. /* line locking not needed -- os9 has exclusive access flag on open */
  483.  
  484. /* Got the line, now set the desired value for local. */
  485.  
  486.     if (*lcl < 0) *lcl = xlocal;
  487.  
  488. /* Get tty device settings */
  489.  
  490.     _gs_opt(ttyfd,&ttold);   /* Get sgtty info */
  491.     _gs_opt(ttyfd,&ttraw);   /* And a copy of it for packets*/
  492.     _gs_opt(ttyfd,&tttvt);   /* And one for virtual tty service */
  493.     debug(F101,"ttopen, ttyfd","",ttyfd);
  494.     debug(F101," lcl","",*lcl);
  495.     return(0);
  496. }
  497.  
  498. /*  T T C L O S  --  Close the TTY */
  499.  
  500. ttclos(foo) int foo; {
  501.     if (ttyfd < 0) return(0);  /* Wasn't open. */
  502.  
  503. #ifdef  NETCONN
  504.     if (netconn) {                      /* If it's a network connection. */
  505.         debug(F100,"ttclos closing net","",0);
  506.         _ss_sevent(ttyfd, 0);
  507.         netclos();                      /* Let the network module close it. */
  508.         netconn = 0;                    /* No more network connection. */
  509.         if (ttevid != 0) {
  510.             _ev_unlink(ttevid);
  511.             _ev_delete(ttevnm);
  512.             ttevid = 0;
  513.         }
  514.         return(0);
  515.     }
  516. #endif /* NETCONN */
  517.  
  518.     if (xlocal) {
  519.         if (tthang())   /* Hang up phone line */
  520.             fprintf(stderr,"Warning, problem hanging up the phone\n");
  521.     }
  522.     ttres();    /* Reset modes. */
  523. /* Relinquish exclusive access if we might have had it... */
  524.     close(ttyfd);   /* Close it. */
  525.     debug (F101,"closed connection, ttyfd","",ttyfd);
  526.     ttyfd = -1;    /* Mark it as closed. */
  527.     return(0);
  528. }
  529.  
  530. #ifdef MYREAD
  531.  
  532. /* Private buffer for myread() and its companions.  Not for use by anything
  533.  * else.  ttflui() is allowed to reset them to initial values.  ttchk() is
  534.  * allowed to read my_count.
  535.  *
  536.  * my_item is an index into mybuf[].  Increment it *before* reading mybuf[].
  537.  *
  538.  * A global parity mask variable could be useful too.  We could use it to
  539.  * let myread() strip the parity on its own, instead of stripping sign
  540.  * bits as it does now.
  541.  */
  542.  
  543. #define MYBUFLEN 256
  544. static CHAR mybuf[MYBUFLEN];            /* Buffer, including push back */
  545. static int my_count = 0;                /* Number of chars still in mybuf */
  546. static int my_item = -1;                /* Last index read from mybuf[] */
  547.  
  548. /* myread() -- Efficient read of one character from communications line.
  549.  *
  550.  * Uses a private buffer to minimize the number of expensive read() system
  551.  * calls.  Essentially performs the equivalent of read() of 1 character, which
  552.  * is then returned.  By reading all available input from the system buffers
  553.  * to the private buffer in one chunk, and then working from this buffer, the
  554.  * number of system calls is reduced in any case where more than one character
  555.  * arrives during the processing of the previous chunk, for instance high
  556.  * baud rates or network type connections where input arrives in packets.
  557.  * If the time needed for a read() system call approaches the time for more
  558.  * than one character to arrive, then this mechanism automatically compensates
  559.  * for that by performing bigger read()s less frequently.  If the system load
  560.  * is high, the same mechanism compensates for that too.
  561.  *
  562.  * myread() is a macro that returns the next character from the buffer.  If the
  563.  * buffer is empty, mygetbuf() is called.  See mygetbuf() for possible error
  564.  * returns.
  565.  *
  566.  * This should be efficient enough for any one-character-at-a-time loops.
  567.  * For even better efficiency you might use memcpy()/bcopy() or such between
  568.  * buffers (since they are often better optimized for copying), but it may not
  569.  * be worth it if you have to take an extra pass over the buffer to strip
  570.  * parity and check for CTRL-C anyway.
  571.  *
  572.  * Note that if you have been using myread() from another program module, you
  573.  * may have some trouble accessing this macro version and the private variables
  574.  * it uses.  In that case, just add a function in this module, that invokes the
  575.  * macro.
  576.  */
  577. #define myread()  (--my_count < 0 ? mygetbuf() : 255 & (int)mybuf[++my_item])
  578.  
  579. /* Specification: Push back up to one character onto myread()'s queue.
  580.  *
  581.  * This implementation: Push back characters into mybuf. At least one character
  582.  * must have been read through myread() before myunrd() may be used.  After
  583.  * EOF or read error, again, myunrd() can not be used.  Sometimes more than
  584.  * one character can be pushed back, but only one character is guaranteed.
  585.  * Since a previous myread() must have read its character out of mybuf[],
  586.  * that guarantees that there is space for at least one character.  If push
  587.  * back was really needed after EOF, a small addition could provide that.
  588.  *
  589.  * myunrd() is currently not called from anywhere inside kermit...
  590.  */
  591. #ifdef NOTUSED
  592. myunrd(ch) CHAR ch; {
  593.     if (my_item >= 0) {
  594.         mybuf[my_item--] = ch;
  595.         ++my_count;
  596.     }
  597. }
  598. #endif
  599.  
  600. /* mygetbuf() -- Fill buffer for myread() and return first character.
  601.  *
  602.  * This function is what myread() uses when it can't get the next character
  603.  * directly from its buffer.  First, it calls a system dependent myfillbuf()
  604.  * to read at least one new character into the buffer, and then it returns
  605.  * the first character just as myread() would have done.  This function also
  606.  * is responsible for all error conditions that myread() can indicate.
  607.  *
  608.  * Returns: When OK     => a positive character, 0 or greater.
  609.  *          When EOF    => -2.
  610.  *          When error  => -3, error code in errno.
  611.  *
  612.  * Older myread()s additionally returned -1 to indicate that there was nothing
  613.  * to read, upon which the caller would call myread() again until it got
  614.  * something.  The new myread()/mygetbuf() always gets something.  If it
  615.  * doesn't, then make it do so!  Any program that actually depends on the old
  616.  * behaviour will break.
  617.  *
  618.  * The older version also used to return -2 both for EOF and other errors,
  619.  * and used to set errno to 9999 on EOF.  The errno stuff is gone, EOF and
  620.  * other errors now return different results, although Kermit currently never
  621.  * checks to see which it was.  It just disconnects in both cases.
  622.  *
  623.  * Kermit lets the user use the quit key to perform some special commands
  624.  * during file transfer.  This causes read(), and thus also mygetbuf(), to
  625.  * finish without reading anything and return the EINTR error.  This should
  626.  * be checked by the caller.  Mygetbuf() could retry the read() on EINTR,
  627.  * but if there is nothing to read, this could delay Kermit's reaction to
  628.  * the command, and make Kermit appear unresponsive.
  629.  *
  630.  * The debug() call should be removed for optimum performance.
  631.  */
  632. int
  633. mygetbuf() {
  634.     my_count = myfillbuf();
  635.     /* debug(F101, "myfillbuf read", "", my_count); */
  636.     if (my_count <= 0)
  637.       return(my_count < 0 ? -3 : -2);
  638.     --my_count;
  639.     return(255 & (int)mybuf[my_item = 0]);
  640. }
  641.  
  642. /* myfillbuf():
  643.  * System-dependent read() into mybuf[], as many characters as possible.
  644.  *
  645.  * Returns: OK => number of characters read, always more than zero.
  646.  *          EOF => 0
  647.  *          Error => -1, error code in errno.
  648.  *
  649.  * If there is input available in the system's buffers, all of it should be
  650.  * read into mybuf[] and the function return immediately.  If no input is
  651.  * available, it should wait for a character to arrive, and return with that
  652.  * one in mybuf[] as soon as possible.  It may wait somewhat past the first
  653.  * character, but be aware that any such delay lengthens the packet turnaround
  654.  * time during kermit file transfers.  Should never return with zero characters
  655.  * unless EOF or irrecoverable read error.
  656.  *
  657.  * Correct functioning depends on the correct tty parameters being used.
  658.  * Better control of current parameters is required than may have been the
  659.  * case in older Kermit releases.  For instance, O_NDELAY (or equivalent) can
  660.  * no longer be sometimes off and sometimes on like it used to, unless a
  661.  * special myfillbuf() is written to handle that.  Otherwise the ordinary
  662.  * myfillbuf()s may think they have come to EOF.
  663.  *
  664.  * If your system has a facility to directly perform the functioning of
  665.  * myfillbuf(), then use it.  If the system can tell you how many characters
  666.  * are available in its buffers, then read that amount (but not less than 1).
  667.  * If the system can return a special indication when you try to read without
  668.  * anything to read, while allowing you to read all there is when there is
  669.  * something, you may loop until there is something to read, but probably that
  670.  * is not good for the system load.
  671.  */
  672.  
  673.         /* This is for OSK.  _gs_rdy returns the number
  674.          * of characters available for reading. If none are available, wait
  675.          * until something arrives, otherwise return all there is.
  676.          * The OSK version needs to handle timeouts explicitly since
  677.          * OSK alarm() does not interupt I/O.  (Only done when filling buffer
  678.          * to reduce overhead.)
  679.          */
  680. int
  681. myfillbuf() {
  682.     register int avail;
  683.     register int x;
  684.  
  685. #ifdef O_GOODDRIVER
  686. /*
  687.   Drivers that conform with the Technical I/O Manual interrupt I/O when
  688.   the signal code is less than S_DEADLY.
  689. */
  690.     while (1) {
  691.         if ((avail = _gs_rdy(ttyfd)) <= 0)
  692.             avail = 1;
  693.         else if (avail > MYBUFLEN)
  694.             avail = MYBUFLEN;
  695.         if ((x = read(ttyfd, mybuf, (int)avail)) < 0) {
  696.             if ((errno & 0xff) == E_READ)
  697.                 /* Ingore framing, parity and break errors (like unix) */
  698.                 continue;
  699.         }
  700. /* Wait some arbitrary time for buffer fill to reduce system load. */
  701.         if (avail < 10) tsleep(2);
  702.         break;
  703.     }
  704.     return x;
  705. #else /* O_GOODDRIVER */
  706.     (void) remove_alarm();      /* let's fake it instead */
  707.     for(;;) {
  708.         if (timowhen && time((time_t *)0) >= timowhen) { /*check for timeout*/
  709.             timowhen = 0;
  710.             if (sigtbl[MAXSIG] != SIG_DFL) (*sigtbl[MAXSIG])(SIGALRM);
  711.             return -1;
  712.         }
  713.         if ((avail = _gs_rdy(ttyfd)) > 0) break;
  714.         sigmask(1);
  715.         _ss_ssig(ttyfd, SIGARB);
  716.         sleep(1);               /* interupted by signal if incoming char */
  717.         _ss_rel(ttyfd, SIGARB);
  718.     }
  719.  
  720.     if (avail > MYBUFLEN)
  721.       avail = MYBUFLEN;
  722.  
  723.     x = read(ttyfd, mybuf, (int) avail);
  724. /* Wait some arbitrary time for buffer fill to reduce system load. */
  725.     if (avail < 10) tsleep(2);
  726.     return(x);
  727. #endif /* !O_GOODDRIVER */
  728. }
  729.  
  730. #endif /* MYREAD */
  731. /*  T T H A N G -- Hangup phone line */
  732.  
  733. tthang() {
  734. /*    if (ttyfd < 0) return(0); /* Not open. */
  735.  
  736. #ifdef NETCONN
  737.     if (netconn)                        /* Network connection. */
  738.       return((ttclos(0) < 0) ? -1 : 1); /* Just close it. */
  739. #endif /* NETCONN */
  740.  
  741.     return 0;                   /* not implemented */
  742. }
  743.  
  744.  
  745. /*  T T R E S  --  Restore terminal to "normal" mode.  */
  746.  
  747. ttres() {    /* Restore the tty to normal. */
  748.     if (ttyfd < 0) return(-1);  /* Not open. */
  749.  
  750. #ifdef  NETCONN
  751.     if (netconn) return (0);            /* Network connection, do nothing */
  752. #endif  /* NETCONN */
  753.  
  754. #ifdef XMODE
  755.     if (xmode(ttold.sg_baud) < 0) return(-1);
  756. #endif
  757.     tsleep(2);    /* Wait for pending i/o to finish. */
  758.     if (_ss_opt(ttyfd,&ttold) < 0) return(-1); /* Restore sgtty stuff */
  759.     return(0);
  760. }
  761.  
  762. /*  T T P K T  --  Condition the communication line for packets. */
  763. /*  or for modem dialing */
  764.  
  765. /*  If called with speed > -1, also set the speed.  */
  766.  
  767. /*  Returns 0 on success, -1 on failure.  */
  768.  
  769. ttpkt(speed,flow,parity)
  770. long speed;
  771. int flow, parity;
  772. {
  773. int s;
  774.     if (ttyfd < 0) return(-1);  /* Not open. */
  775.  
  776. #ifdef NETCONN                          /* Nothing to do for telnet */
  777.     if (netconn) return (0);
  778. #endif /* NETCONN */
  779.  
  780.     if (speed >-1)
  781.         if ((s=ttsspd(speed/10)) <0) return(-1); /* Check the speed */
  782.  
  783.     ttprty = parity;          /* Let other functions see these. */
  784.     ttpflg = 0;               /* Parity not sensed yet */
  785.     ttpmsk = ttprty ? 0177 : 0377; /* Parity stripping mask */
  786.  
  787.     ttraw.sg_case =
  788.     ttraw.sg_backsp =
  789.     ttraw.sg_delete =
  790.     ttraw.sg_echo =
  791.     ttraw.sg_alf =
  792.     ttraw.sg_nulls =
  793.     ttraw.sg_pause =
  794.     ttraw.sg_bspch =
  795.     ttraw.sg_dlnch =
  796.     ttraw.sg_eorch =
  797.     ttraw.sg_eofch =
  798.     ttraw.sg_rlnch =
  799.     ttraw.sg_dulnch =
  800.     ttraw.sg_psch =
  801.     ttraw.sg_kbich =
  802.     ttraw.sg_kbach =
  803.     ttraw.sg_bsech =
  804.     ttraw.sg_tabcr = 0;
  805.     if (speed >-1)
  806.         ttraw.sg_baud = (char)s;
  807.     if (flow==1) {
  808.         ttraw.sg_xon  = 0x11;
  809.         ttraw.sg_xoff = 0x13;
  810.     } else ttraw.sg_xon = ttraw.sg_xoff = 0;
  811.     if(_ss_opt(ttyfd,&ttraw) < 0) return(-1);    /* set new modes . */
  812.     ttflui();    /* Flush any pending input */
  813.     return(0);
  814. }
  815.  
  816. /*  T T V T -- Condition communication line for use as virtual terminal  */
  817.  
  818. ttvt(speed,flow) long speed; int flow; {
  819.  
  820. int s;
  821.     if (ttyfd < 0) return(-1);  /* Not open. */
  822.  
  823. #ifdef NETCONN
  824.     if (netconn) {
  825.         /*tvtflg = 1;*/                     /* Network connections */
  826.         debug(F100,"ttvt network connection, skipping...","",0);
  827.         return(0);                      /* require no special setup */
  828.     }
  829. #endif /* NETCONN */
  830.  
  831.     if ((s=ttsspd(speed/10)) <0) return(-1); /* This speed not supported */
  832.  
  833.     tttvt.sg_case =
  834.     tttvt.sg_backsp =
  835.     tttvt.sg_delete =
  836.     tttvt.sg_echo =
  837.     tttvt.sg_alf =
  838.     tttvt.sg_nulls =
  839.     tttvt.sg_pause =
  840.     tttvt.sg_bspch =
  841.     tttvt.sg_dlnch =
  842.     tttvt.sg_eorch =
  843.     tttvt.sg_eofch =
  844.     tttvt.sg_rlnch =
  845.     tttvt.sg_dulnch =
  846.     tttvt.sg_psch =
  847.     tttvt.sg_kbich =
  848.     tttvt.sg_kbach =
  849.     tttvt.sg_bsech =
  850.     tttvt.sg_tabcr = 0;
  851.     tttvt.sg_baud = (char)s;
  852.     if (flow==1) {
  853.         tttvt.sg_xon  = 0x11;
  854.         tttvt.sg_xoff = 0x13;
  855.     } else tttvt.sg_xon = tttvt.sg_xoff = 0;
  856.     s = _ss_opt(ttyfd,&tttvt);   /* set new modes . */
  857.     debug (F101,"ss_opt on tty was :","",s);
  858.     return(0);
  859. }
  860.  
  861. /*  T T F L U I  --  Flush tty input buffer */
  862.  
  863. ttflui() {
  864.     int n;
  865.     char flushbuf[256];
  866.  
  867.     if (ttyfd < 0) return(-1);  /* Not open. */
  868. #ifdef MYREAD
  869.     my_count = 0;                       /* initialize myread() stuff */
  870.     my_item = -1;
  871. #endif /* MYREAD */
  872.  
  873. #ifdef NETCONN
  874. /*
  875.   Network flush is done specially, in the network support module.
  876. */
  877.     debug(F100,"ttflui netflui","",0);
  878.     if (netconn) return(netflui());
  879. #endif /* NETCONN */
  880.  
  881.     while((n=_gs_rdy(ttyfd))>0)
  882.         read(ttyfd, flushbuf, n>256 ? 256 : (unsigned int)n);
  883.     return 0;
  884. }
  885.  
  886. /*  T T C H K  --  Tell how many characters are waiting in tty input buffer  */
  887. ttchk() {
  888.     register int n;
  889.  
  890.     n = _gs_rdy(ttyfd);
  891.     if (n < 0) n = 0;
  892. #ifdef MYREAD
  893.     if (my_count > 0) n += my_count;
  894. #endif /* MYREAD */
  895.     return n;
  896. }
  897.  
  898. /*  T T X I N  --  Get n characters from tty input buffer  */
  899. /*  Returns number of characters actually gotten, or -1 on failure  */
  900. /*  Intended for use only when it is known that n characters are actually */
  901. /*  Available in the input buffer.  */
  902.  
  903. ttxin(n,buf) int n; CHAR *buf; {
  904.     register int c;
  905. #ifdef MYREAD
  906.     register CHAR *bp, *bpe;
  907. #else
  908.     register int x;
  909. #endif /* MYREAD */
  910.  
  911.     ttpmsk = (ttprty) ? 0177 : 0377;         /* Parity stripping mask. */
  912.     debug(F101,"ttxin n","",n);
  913. #ifdef MYREAD
  914.     for( bpe = (bp = buf) + n; (bp != bpe) && (c = myread()) >= 0; )
  915.         *bp++ = c & ttpmsk;
  916.     if (c < 0) return -1;
  917.     *bp = '\0';
  918.     return n;
  919. #else
  920.     x = read(ttyfd,(char *)buf,(unsigned int)n);
  921.     if (ttprty) {
  922.         for (c = 0; c < n; c++) buf[c] &= 0177;
  923.     }
  924.     if (x > 0) buf[x] = '\0';
  925.     if (x < 0) x = -1;
  926.     return(x);
  927. #endif /* MYREAD */
  928. }
  929.  
  930. /*  C O N I N T  --  Console Interrupt setter  */
  931. VOID
  932. conint(f,s) SIGTYP (*f)(), (*s)();
  933. {
  934.     if (backgrd) return;  /* must ignore signals in bkgrd */
  935.     signal(SIGINT,f);  /* console escape in pkt modes */
  936. }
  937.  
  938.  
  939. /*  C O N N O I  --  Reset console terminal interrupts */
  940. VOID
  941. connoi() {    /* Console-no-interrupts */
  942.     signal(SIGQUIT,(fptr)SIG_IGN);
  943.     signal(SIGINT,(fptr)SIG_IGN);
  944. }
  945.  
  946.  
  947.  
  948. /*  T T O L  --  Similar to "ttinl", but for writing.  */
  949.  
  950. ttol(s,n) int n; CHAR *s; {
  951.     int x;
  952.     if (ttyfd < 0) {
  953.         debug(F101,"ttol: ttyfd",NULL,ttyfd);
  954.         return(-1);  /* Not open. */
  955.     }
  956.     x = write(ttyfd,s,(unsigned int)n);
  957.     debug(F111,"ttol",s,n); /* `s' schould be null terminated !? */
  958.     if (x < 0) {
  959.         debug(F101,"ttol failed errno",NULL,errno);
  960. #ifdef TCPSOCKET
  961.         if (netconn && ttnet == NET_TCPB) {
  962.             if (errno) perror("TCP/IP"); /* Say why */
  963.             ttclos(0);              /* Close the connection. */
  964.         }
  965. #endif /* TCPSOCKET */
  966.     }
  967.     return(x);
  968. }
  969.  
  970.  
  971. /*  T T O C  --  Output a character to the communication line  */
  972.  
  973. int
  974. #ifdef CK_ANSIC
  975. ttoc(char c)
  976. #else
  977. ttoc(c) char c;
  978. #endif /* CK_ANSIC */
  979. /* ttoc */{
  980.     if (ttyfd < 0) return(-1);  /* Not open. */
  981.     return(write(ttyfd,&c,1));
  982. }
  983.  
  984.  
  985. /*  T T I N L  --  Read a record (up to break character) from comm line.  */
  986. /*
  987.   Reads up to "max" characters from the communication line, terminating on:
  988.  
  989.     (a) the packet length field if the "turn" argument is zero, or
  990.     (b) on the packet-end character (eol) if the "turn" argument is nonzero
  991.     (c) two Ctrl-C's in a row
  992.  
  993.   and returns the number of characters read upon success, or if "max" was
  994.   exceeded or the timeout interval expired before (a) or (b), returns -1.
  995.  
  996.   The characters that were input are copied into "dest" with their parity bits
  997.   stripped if parity was selected.  Returns the number of characters read.
  998.   Characters after the eol are available upon the next call to this function.
  999.  
  1000.   The idea is to minimize the number of system calls per packet, and also to
  1001.   minimize timeouts.  This function is the inner loop of the program and must
  1002.   be as efficient as possible.  The current strategy is to use myread().
  1003.  
  1004.   WARNING: this function calls parchk(), which is defined in another module.
  1005.   Normally, ckutio.c does not depend on code from any other module, but there
  1006.   is an exception in this case because all the other ck?tio.c modules also
  1007.   need to call parchk(), so it's better to have it defined in a common place.
  1008.  
  1009.   Since this function has grown to have its fingers so deeply into the 
  1010.   protocol, it is slated for removal: rpack() will take care of everything.
  1011. */
  1012. #ifdef CTRLC
  1013. #undef CTRLC
  1014. #endif /* CTRLC */
  1015. #define CTRLC '\03'
  1016. /*
  1017.   We have four different declarations here because:
  1018.   (a) to allow Kermit to be built without the automatic parity sensing feature
  1019.   (b) one of each type for ANSI C, one for non-ANSI.
  1020. */
  1021. int
  1022. #ifdef PARSENSE
  1023. #ifdef CK_ANSIC
  1024. ttinl(CHAR *dest, int max,int timo, CHAR eol, CHAR start, int turn)
  1025. #else
  1026. ttinl(dest,max,timo,eol,start,turn) int max,timo,turn; CHAR *dest, eol, start;
  1027. #endif /* CK_ANSIC */
  1028. #else /* not PARSENSE */
  1029. #ifdef CK_ANSIC
  1030. ttinl(CHAR *dest, int max,int timo, CHAR eol)
  1031. #else
  1032. ttinl(dest,max,timo,eol) int max,timo; CHAR *dest, eol;
  1033. #endif /* __SDTC__ */
  1034. #endif /* PARSENSE */
  1035. /* ttinl */ {
  1036.  
  1037.     if (ttyfd < 0) return(-1);          /* Not open. */
  1038.  
  1039.     debug(F101,"ttinl max","",max);
  1040.     debug(F101,"ttinl timo","",timo);
  1041.  
  1042.     *dest = '\0';                       /* Clear destination buffer */
  1043.     if (timo < 0) timo = 0;             /* Safety */
  1044.     if (
  1045. #ifdef CK_POSIX_SIG
  1046.         sigsetjmp(sjbuf,1)
  1047. #else
  1048.         setjmp(sjbuf)
  1049. #endif /* CK_POSIX_SIG */
  1050.         ) {                /* Timer went off? */
  1051.         debug(F100,"ttinl timout","",0); /* Get here on timeout. */
  1052.         /* debug(F110," with",(char *) dest,0); */
  1053. #ifndef OSK
  1054.         ttimoff();                      /* Turn off timer */
  1055. #endif /* !OSK */
  1056.         return(-1);                     /* and return error code. */
  1057.     } else {
  1058. #ifndef MYREAD
  1059.         CHAR ch;
  1060. #endif /* MYREAD */
  1061.         register int i, n;              /* local variables */
  1062.         int ccn = 0;
  1063. #ifdef PARSENSE
  1064.         int pktlen = -1;
  1065.         int lplen = 0;
  1066.         int havelen = 0;
  1067.         int flag = 0;
  1068.         debug(F000,"ttinl start","",start);
  1069. #endif /* PARSENSE */
  1070.  
  1071.         if (timo) {                     /* Don't time out if timo == 0 */
  1072.             int xx;
  1073.             saval = signal(SIGALRM,timerh); /* Enable timer interrupt */
  1074.             xx = alarm(timo);           /* Set it. */
  1075.             debug(F101,"ttinl alarm","",xx);
  1076.         }
  1077.         ttpmsk = (ttprty) ? 0177 : 0377; /* Set parity stripping mask. */
  1078.  
  1079. #ifdef COMMENT
  1080. /*
  1081.   No longer needed.
  1082. */
  1083. #ifdef SUNX25
  1084.         if (netconn && (ttnet == NET_SX25))
  1085. #ifdef PARSENSE
  1086.           return(x25inl(dest,max,timo,eol,start));
  1087. #else
  1088.           return(x25inl(dest,max,timo,eol));
  1089. #endif /* PARSENSE */
  1090. #endif /* SUNX25 */
  1091. #endif /* COMMENT */
  1092.  
  1093. /* Now read into destination, stripping parity and looking for the */
  1094. /* the packet terminator, and also for two Ctrl-C's typed in a row. */
  1095.  
  1096.         i = 0;                          /* Destination index */
  1097.         debug(F101,"ttinl eol","",eol);
  1098.  
  1099. #ifdef MYREAD
  1100.         while (i < max-1) {
  1101.             /* debug(F101,"ttinl i","",i); */
  1102.             if ((n = myread()) < 0) {
  1103.                 debug(F101,"ttinl myread failure, n","",n);
  1104.                 debug(F101,"ttinl myread errno","",errno);
  1105. #ifndef OSK
  1106.                 /* Don't let EINTR break packets. */
  1107.                 if (n == -3 && errno == EINTR && i > 0) {
  1108.                     debug(F101,"ttinl myread i","",i);
  1109.                     continue;
  1110.                 }
  1111. #endif /* !OSK */
  1112.                 break;
  1113.             }
  1114. #else
  1115.         while ((i < max-1)  &&  (n = read(ttyfd, &ch, 1)) > 0) {
  1116.             n = ch;
  1117. #endif /* MYREAD */
  1118.  
  1119.             /* debug(F101,"ttinl char","", (n & ttpmsk)); */
  1120.  
  1121. #ifdef PARSENSE
  1122. /*
  1123.   Figure out what the length is supposed to be in case the packet
  1124.   has no terminator (as with Honeywell GCOS-8 Kermit).
  1125. */
  1126. #ifndef xunchar
  1127. #define xunchar(ch) (((ch) - 32 ) & 0xFF )      /* Character to number */
  1128. #endif /* xunchar */
  1129.             if ((flag == 0) && ((n & 0x7f) == start)) flag = 1;
  1130.             if (flag) dest[i++] = n & ttpmsk;
  1131. /*
  1132.   If we have not been instructed to wait for a turnaround character, we
  1133.   can go by the packet length field.  If turn != 0, we must wait for the
  1134.   end of line (eol) character before returning.
  1135. */
  1136.             if (i == 2) {
  1137.                 pktlen = xunchar(dest[1] & 0x7f);
  1138.                 havelen = (pktlen > 1);
  1139.                 debug(F101,"ttinl length","",pktlen);
  1140.             } else if (i == 5 && pktlen == 0) {
  1141.                 lplen = xunchar(dest[4] & 0x7f);
  1142.             } else if (i == 6 && pktlen == 0) {
  1143.                 pktlen = lplen * 95 + xunchar(dest[5] & 0x7f) + 5;
  1144.                 havelen = 1;
  1145.                 debug(F101,"ttinl length","",pktlen);
  1146.             }
  1147. #else
  1148.             dest[i++] = n & ttpmsk;
  1149. #endif /* PARSENSE */
  1150. /*
  1151.   Use parity mask, rather than always stripping parity, to check for
  1152.   cancellation.  Otherwise, runs like \x03\x83\x03 in packet could cancel
  1153.   the transfer when parity is NONE.
  1154. */
  1155.             /* Check cancellation */
  1156.             if (!xlocal && xfrcan && ((n & ttpmsk) == xfrchr)) {
  1157.                 if (++ccn >= xfrnum) {  /* If xfrnum in a row, bail out. */
  1158.                     if (timo) {         /* Clear timer. */
  1159.                         ttimoff();
  1160.                     }
  1161. #ifdef OSK
  1162.                     fprintf(stderr,"^C...\r\012"); /* Echo Ctrl-C */
  1163. #else /* OSK */
  1164.                     fprintf(stderr,"^C...\r\n"); /* Echo Ctrl-C */
  1165. #endif /* !OSK */
  1166.                     return(-2);
  1167.                 }
  1168.             } else ccn = 0;             /* No cancellation, reset counter, */
  1169.  
  1170. #ifdef PARSENSE
  1171.             if (flag == 0) {
  1172.                 debug(F101,"ttinl skipping","",n);
  1173.                 continue;
  1174.             }
  1175. #endif /* PARSENSE */
  1176.  
  1177.     /* Check for end of packet */
  1178.  
  1179.             if (
  1180. #ifdef PARSENSE
  1181. /*
  1182.   Purely length-driven if SET HANDSHAKE NONE (i.e. turn == 0).
  1183.   This allows packet terminators and handshake characters to appear
  1184.   literally inside a packet data field.
  1185. */
  1186.                 (havelen && (i > pktlen+1) &&
  1187.                  (!turn || (turn && (n & 0x7f) == eol)))
  1188. #ifdef COMMENT
  1189.                 (!turn && havelen && (i > pktlen+1)) ||
  1190.                 (turn && havelen && (i > pktlen+1) && (n & 0x7f) == eol)
  1191. #endif /* COMMENT */
  1192. #else /* !PARSENSE */
  1193. /*
  1194.   Built without PARSENSE, so just look for packet terminator.
  1195. */
  1196.                 ((n & 0x7f) == eol)
  1197. #endif /* PARSENSE */
  1198.                 ) {
  1199. #ifndef PARSENSE
  1200.                 debug(F101,"ttinl got eol","",eol);
  1201.                 dest[i] = '\0';         /* Yes, terminate the string, */
  1202.                 /* debug(F101,"ttinl i","",i); */
  1203. #else
  1204.                 if ((n & 0x7f) != eol) {
  1205.                     debug(F101,"ttinl EOP length","",pktlen);
  1206.                     debug(F101,"ttinl i","",i);
  1207.                 } else debug(F101,"ttinl got eol","",eol);
  1208.                 dest[i] = '\0';         /* Terminate the string, */
  1209.                 /* Parity checked yet? */
  1210.                 if (ttpflg++ == 0 && ttprty == 0) {
  1211.                     if ((ttprty = parchk(dest,start,i)) > 0) { /* No, check. */
  1212.                         int j;
  1213.                         debug(F101,"ttinl senses parity","",ttprty);
  1214.                         debug(F110,"ttinl packet before",dest,0);
  1215.                         ttpmsk = 0x7f;
  1216.                         for (j = 0; j < i; j++)
  1217.                           dest[j] &= 0x7f;      /* Strip parity from packet */
  1218.                         debug(F110,"ttinl packet after ",dest,0);
  1219.                     } else ttprty = 0;  /* restore if parchk error */
  1220.                 }
  1221. #endif /* PARSENSE */
  1222.                 if (timo) {                     /* Turn off timer. */
  1223.                     ttimoff();
  1224.                 }
  1225.                 debug(F111,"ttinl got", dest,i);
  1226.                 return(i);
  1227.             }
  1228.         }                               /* end of while() */
  1229. #ifdef OSK
  1230.         if (timo)
  1231. #endif /* OSK */
  1232.             ttimoff();
  1233.         return(-1);
  1234.     }
  1235. }
  1236.  
  1237. /*  T T I N C --  Read a character from the communication line  */
  1238. /*
  1239.  On success, returns the character that was read, >= 0.
  1240.  On failure, returns -3 on internal error, -2 on communication disconnect,
  1241.  -1 on timeout and other
  1242. */
  1243. int
  1244. ttinc(timo) int timo; {
  1245. #ifndef MYREAD
  1246.     CHAR ch = 0;
  1247. #endif /* MYREAD */
  1248.     int n = 0;
  1249.  
  1250.     if (ttyfd < 0) return(-1);          /* Not open. */
  1251.     if (timo <= 0                       /* Untimed. */
  1252. #ifdef MYREAD
  1253.         || my_count > 0                 /* Buffered char already waiting. */
  1254. #endif /* MYREAD */
  1255.     ) {
  1256.         /* not realy untimed, ckudia.c uses alarm() */
  1257. #ifdef MYREAD
  1258.         /* comm line failure returns -1 thru myread, so no &= 0377 */
  1259.         n = myread();                   /* Wait for a character... */
  1260.         /* debug(F101,"ttinc n","",n); */
  1261. #else
  1262.         while ((n = read(ttyfd,&ch,1)) == 0) /* Wait for a character. */
  1263.         /* Shouldn't have to loop in ver 5A. */
  1264.           ;
  1265. /* debug(F000,"ttinc","",ch); */
  1266.         return( (n < 1) ? -3 : (ch & ttpmsk) );
  1267. #endif /* MYREAD */
  1268.     } else {
  1269.         saval = signal(SIGALRM,timerh); /* Timed, set up timer. */
  1270.         alarm((unsigned int)timo);
  1271.         if (setjmp(sjbuf)) {
  1272.             n = -1;
  1273.         } else {
  1274. #ifdef MYREAD
  1275.             n = myread();               /* If managing own buffer... */
  1276.             debug(F101,"ttinc myread","",n);
  1277. #else
  1278. #ifdef O_GOODDRIVER
  1279.             n = read(ttyfd,(char *)&ch,1);
  1280. #else /* O_GOODDRIVER */
  1281.             n = timoread(ttyfd,(char *)&ch,1);  /*Otherwise call the system.*/
  1282. #endif /* !O_GOODDRIVER */
  1283.             debug(F101,"ttinc read","",n);
  1284.             if (n > 0)
  1285.               n = ch & 255;
  1286.             else
  1287.               n = (n < 0) ? -3 : -2;    /* Special return codes */
  1288. #endif /* MYREAD */
  1289.         }
  1290.         ttimoff();                          /* Turn off timer */
  1291.     }
  1292.     return( (n < 0) ? n : (n & ttpmsk) ); /* Return masked char or neg. */
  1293. }
  1294.  
  1295. /*  T T S N D B  --  Send a BREAK signal  */
  1296.  
  1297. ttsndb()
  1298. {
  1299. struct sgbuf before;
  1300. int i;
  1301.     if (ttyfd < 0) return(-1);  /* Not open. */
  1302.  
  1303. #ifdef NETCONN
  1304.     if (netconn)                        /* Send network BREAK */
  1305.       return(netbreak());
  1306. #endif /* NETCONN */
  1307.  
  1308. #ifndef XMODE
  1309.     if (send_break(ttyfd) == 0) return(0); /* all fine done by driver */
  1310.     if (errno!=E_UNKSVC) return(-1); /*should have been unknown service call*/
  1311.     if (_gs_opt(ttyfd,&before) < 0) return(-1); /* din't get old speed */
  1312.     for (i=B50; i<before.sg_baud; i++) /* try to switch to a lower speed */
  1313.     {
  1314.       if (ttsspd((int)bdrts[i]/10) != -1) break;
  1315.     }
  1316.     if (i == before.sg_baud) return(-1); /* no lower speed supported */
  1317. #else
  1318.     if (_gs_opt(ttyfd,&before) < 0) return(-1); /* din't get old speed */
  1319.     ttsspd((int)bdrts[B300]/10);/* xmode always return success, since it only
  1320.                                    patches device descriptor */
  1321. #endif
  1322.     write(ttyfd,"\0",1);
  1323.     write(ttyfd,"\0",1); /* send two zeroes */
  1324.     msleep(400);      /* wait chars to appear (50 baud == 400 milli seconds */
  1325.     ttsspd((int)bdrts[before.sg_baud]/10); /* restore old baud rate*/
  1326.     return(0);
  1327. }
  1328.  
  1329. VOID
  1330. rtimer() {
  1331.     tcount = time( (time_t *) 0 );
  1332. }
  1333.  
  1334.  
  1335. /*  G T I M E R --  Get current value of elapsed time counter in seconds  */
  1336.  
  1337. int
  1338. gtimer() {
  1339.     int x;
  1340.     x = (int) (time( (time_t *) 0 ) - tcount);
  1341.     return( (x < 0) ? 0 : x );
  1342. }
  1343.  
  1344. /*  Z T I M E  --  Return date/time string  */
  1345. VOID
  1346. ztime(s) char **s;
  1347. {
  1348. time_t t;
  1349.   t = time((time_t*)NULL);
  1350.   if (t != (time_t)-1)
  1351.     *s =ctime(&t);
  1352.   else
  1353.     *s = "Ddd Mmm 00 00:00:00 0000\n";  /* Return dummy in asctime() format */
  1354. }
  1355.  
  1356. /*  C O N G M  --  Get console terminal modes.  */
  1357.  
  1358. /*
  1359.  Saves current console mode, and establishes variables for switching between
  1360.  current (presumably normal) mode and other modes.
  1361. */
  1362.  
  1363. congm() {
  1364.     if (!isatty(0)) return(-1);  /* only for real ttys */
  1365.     _gs_opt(0,&ccold);   /* Structure for restoring */
  1366.     _gs_opt(0,&cccbrk);  /* For setting CBREAK mode */
  1367.     cccbrk.sg_echo  =
  1368.     cccbrk.sg_pause =
  1369.     cccbrk.sg_eofch =
  1370.     cccbrk.sg_psch = 0; /* kermit interpreter uses CTRL-W */
  1371.  
  1372.     _gs_opt(0,&ccraw);   /* For setting RAW mode */
  1373.     ccraw.sg_case =
  1374.     ccraw.sg_backsp =
  1375.     ccraw.sg_delete =
  1376.     ccraw.sg_echo =
  1377.     ccraw.sg_alf =
  1378.     ccraw.sg_nulls =
  1379.     ccraw.sg_pause =
  1380.     ccraw.sg_bspch =
  1381.     ccraw.sg_dlnch =
  1382.     ccraw.sg_eorch =
  1383.     ccraw.sg_eofch =
  1384.     ccraw.sg_rlnch =
  1385.     ccraw.sg_dulnch =
  1386.     ccraw.sg_psch =
  1387.     ccraw.sg_kbich =
  1388.     ccraw.sg_kbach =
  1389.     ccraw.sg_bsech =
  1390.     ccraw.sg_tabcr =
  1391.     ccraw.sg_xon =
  1392.     ccraw.sg_xoff = 0;
  1393.         return(0);
  1394. }
  1395.  
  1396.  
  1397. /*  C O N C B --  Put console in cbreak mode.  */
  1398. /* we can ignore esc since conchk() works on OS-9, no need for a special esc */
  1399. /*  Returns 0 if ok, -1 if not  */
  1400.  
  1401. int
  1402. #ifdef CK_ANSIC
  1403. concb(char esc)
  1404. #else
  1405. concb(esc) char esc;
  1406. #endif /* CK_ANSIC */
  1407. /* concb */ {
  1408.     int x;
  1409.     if (!isatty(0)) return(0);  /* only for real ttys */
  1410.     ckxech = 1;                 /* Program can echo characters */
  1411.     x = _ss_opt(0,&cccbrk) | _ss_opt(1,&cccbrk);
  1412.     debug(F101,"console set to cbreak mode","",esc);
  1413.     return(x);
  1414. }
  1415.  
  1416. /*  C O N B I N  --  Put console in binary mode  */
  1417.  
  1418. /* we can ignore esc since conchk() works on OS-9, no need for a special esc */
  1419. /*  Returns 0 if ok, -1 if not  */
  1420.  
  1421. int
  1422. #ifdef CK_ANSIC
  1423. conbin(char esc)
  1424. #else
  1425. conbin(esc) char esc;
  1426. #endif /* CK_ANSIC */
  1427. /* conbin */ {
  1428.     if (!isatty(0)) return(0);  /* only for real ttys */
  1429.     ckxech = 1;                 /* Program can echo characters */
  1430.     _ss_opt(0,&ccraw);
  1431.     _ss_opt(1,&ccraw);          /* set new modes . */
  1432.     debug(F101,"console switched to raw mode","",esc);
  1433.     return(0);
  1434. }
  1435.  
  1436.  
  1437. /*  C O N R E S  --  Restore the console terminal  */
  1438.  
  1439. conres() {
  1440.     if(!isatty(0)) return 0; /* only for real ttys with known modes*/
  1441.     tsleep(2);
  1442.     ckxech = 0;    /* OS-9 will echo chars */
  1443.     return(_ss_opt(0,&ccold)| _ss_opt(1,&ccold)); /* Restore controlling tty */
  1444. }
  1445.  
  1446. /*  C O N O C  --  Output a character to the console terminal  */
  1447. int
  1448. #ifdef CK_ANSIC
  1449. conoc(char c)
  1450. #else
  1451. conoc(c) char c;
  1452. #endif /* CK_ANSIC */
  1453. /* conoc */ {
  1454.     return((write(1,&c,1)>0) ? 1:0);
  1455. }
  1456.  
  1457. /*  C O N X O  --  Write x characters to the console terminal  */
  1458. /*VOID*/
  1459. int
  1460. conxo(x,s) char *s; int x; {
  1461.     write(1,s,(unsigned int)x);
  1462. }
  1463.  
  1464. /*  C O N O L  --  Write a line to the console terminal  */
  1465. /*VOID*/
  1466. int
  1467. conol(s) char *s; {
  1468.     int len;
  1469.     len = strlen(s);
  1470.     write(1,s,(unsigned int)len);
  1471. }
  1472.  
  1473. /*  C O N O L L L  --  Output a string followed by LF  */
  1474. static VOID
  1475. conolll(s) char *s; {
  1476.     conol(s);
  1477.     write(1,"\012",1);
  1478. }
  1479.  
  1480. /*  C O N O L A  --  Write an array of lines to the console terminal */
  1481. /*VOID */
  1482. int
  1483. conola(s) char *s[]; {
  1484.     int i;
  1485.     for (i=0 ; *s[i] ; i++) conolll(s[i]);
  1486. }
  1487.  
  1488. /*  C O N O L L  --  Output a string followed by CRLF  */
  1489. /*VOID*/
  1490. int
  1491. conoll(s) char *s; {
  1492.     conol(s);
  1493.     write(1,"\r\012",2);
  1494. }
  1495.  
  1496. /*  C O N C H K  --  Return how many characters available at console  */
  1497. conchk()
  1498. {
  1499.     int x;
  1500.     x=_gs_rdy(0);
  1501.     if(x<0) x=0; /* always return 0 irrespective the type of error */
  1502.                  /* e.q. /nil would return E_UNKSVC and conchk is only */
  1503.                  /* checked on != 0 anyway, Bob Larson */
  1504.     debug (F101,"conchk","",x);
  1505.     return x;
  1506. }
  1507.  
  1508. /*  C O N I N C  --  Get a character from the console  */
  1509. int
  1510. coninc(timo) int timo; {
  1511.     int n = 0; CHAR ch;
  1512.  
  1513.     if (timo <= 0 ) {                   /* Untimed. */
  1514.         n = read(0, (char *)&ch, 1);            /* Read a character. */
  1515.         ch &= 0377;
  1516.         if (n > 0)                      /* Return the character if read ok */
  1517.           return(ch);
  1518.         else                            /* otherwise... */
  1519.         {
  1520.             debug(F101, "coninc(0) errno","",errno);
  1521.             return(-1);             /* Return -1 as error indication */
  1522.         }
  1523.     }
  1524.     if (setjmp(sjbuf)) n = -2;
  1525.     else {
  1526.         saval = signal(SIGALRM,timerh); /* Timed read, so set up timer */
  1527.         alarm((unsigned int)timo);
  1528. #ifdef O_GOODDRIVER
  1529.         n = read(0, (char *)&ch, 1);
  1530. #else /* O_GOODDRIVER */
  1531.         n = timoread(0, (char *)&ch, 1);
  1532. #endif /* !O_GOODDRIVER */
  1533.         ttimoff();                          /* Turn off timer */
  1534.         ch &= 0377;
  1535.     }
  1536.     if (n > 0) return(ch);
  1537.     else
  1538.         return(-1);
  1539. }
  1540.  
  1541. /* emulate unix signal functions */
  1542. fptr
  1543. signal(sig,func)
  1544. int sig;
  1545. fptr func;
  1546. {
  1547.     fptr temp;
  1548.     if (sig < MAXSIG) {
  1549.         temp = sigtbl[sig];
  1550.         sigtbl[sig] = func;
  1551.         return temp;
  1552.     }
  1553.     if (sig == SIGALRM) {
  1554.         temp = sigtbl[MAXSIG];
  1555.         sigtbl[MAXSIG] = func;
  1556.         return temp;
  1557.     }
  1558.     return (fptr)-1;
  1559. }
  1560.  
  1561. VOID
  1562. catch(sig) register int sig;{
  1563.     register fptr temp;
  1564.  
  1565.     if(sig == SIGARB) {
  1566.         csigflg += 1;
  1567.         return;
  1568.     }
  1569.     if (sig == SIGARB+1) {
  1570.         tsigflg += 1;
  1571.         return;
  1572.     }
  1573.     if(sig < MAXSIG) {
  1574.         if ((temp = sigtbl[sig]) == SIG_DFL) doexit(sig,-1);
  1575.         if(temp != (SIGTYP (*)())SIG_IGN)
  1576.           (*temp)(sig);
  1577.         else
  1578.         {
  1579.           if (sig == SIGQUIT) /* output ceises on CTRL-E typed, so notify */
  1580.             stdin->_flag |= _ERR;
  1581.         }
  1582.         return;
  1583.     }
  1584.     if(sig == SIGALRM) {
  1585.         if ((temp = sigtbl[MAXSIG]) == SIG_DFL) return;
  1586.         if (temp != (SIGTYP (*)())SIG_IGN) (*temp)(sig);
  1587.         return;
  1588.     }
  1589.     doexit(sig,-1);
  1590. }
  1591.  
  1592. int isatty(path)
  1593. int path;
  1594. {
  1595.     struct sgbuf buffer;
  1596.     return((_gs_opt(path,&buffer)<0) ? 0 : buffer.sg_class == 0);
  1597. }
  1598.  
  1599. /*********************************************************************/
  1600. int msleep(m_secs) /* sleeps at least !! (not exact) m_secs milli seconds */
  1601. register int m_secs;
  1602. {
  1603. register unsigned int i;
  1604. register int tick_rate;
  1605.   if ((tick_rate = _getsys(D_TckSec,2)) < 0) return(-1); /* clock   not on */
  1606.   i = (unsigned int)(((double)m_secs*(double)tick_rate)/1000.0);
  1607.   tsleep(i+2);  /* +1 for rounding and another
  1608.                    +1 because tsleep is accurate not more than +/-(!) 1 tick */
  1609.   return(0);
  1610. }
  1611. /**********************************************************************/
  1612. psuspend(foo) int foo;
  1613. {
  1614.   return(-1);
  1615. }
  1616.  
  1617. long ttgspd()                           /* Get current tty speed */
  1618. {
  1619. struct sgbuf buffer;
  1620.   if (ttyfd < 0) return(-1);
  1621.  
  1622. #ifdef NETCONN
  1623.     if (netconn) return(-1);            /* -1 if network connection */
  1624. #endif /* NETCONN */
  1625.  
  1626.   if(_gs_opt(ttyfd,&buffer) < 0) return(-1);
  1627.   return(bdrts[buffer.sg_baud]);
  1628. }
  1629.  
  1630.  
  1631. /*  T T S C A R R  --  Set ttcarr variable, controlling carrier handling.
  1632.  *
  1633.  *  0 = Off: Always ignore carrier. E.g. you can connect without carrier.
  1634.  *  1 = On: Heed carrier, except during dialing. Carrier loss gives disconnect.
  1635.  *  2 = Auto: For "modem direct": The same as "Off".
  1636.  *            For real modem types: Heed carrier during connect, but ignore
  1637.  *                it anytime else.  Compatible with pre-5A C-Kermit versions.
  1638.  *
  1639.  * As you can see, this setting does not affect dialing, which always ignores
  1640.  * carrier (unless there is some special exception for some modem type).  It
  1641.  * does affect ttopen() if it is set before ttopen() is used.  This setting
  1642.  * takes effect on the next call to ttopen()/ttpkt()/ttvt().  And they are
  1643.  * (or should be) always called before any communications is tried, which
  1644.  * means that, practically speaking, the effect is immediate.
  1645.  *
  1646.  * Of course, nothing of this applies to remote mode (xlocal = 0).
  1647.  *
  1648.  * Someone has yet to uncover how to manipulate the carrier in the BSD
  1649.  * environment (or any non-termio using environment).  Until that time, this
  1650.  * will simply be a no-op for BSD.
  1651.  *
  1652.  * Note that in previous versions, the carrier was most often left unchanged
  1653.  * in ttpkt()/ttvt() unless they were called with DIALING or CONNECT.  This
  1654.  * has changed.  Now it is controlled by ttcarr in conjunction with these
  1655.  * modes.
  1656.  */
  1657. ttscarr(carrier) int carrier; {
  1658.     ttcarr = carrier;
  1659.     debug(F101, "ttscarr","",ttcarr);
  1660.     return(ttcarr);
  1661. }
  1662.  
  1663. /*  T T G M D M  --  Get modem signals  */
  1664. /*
  1665.  Looks for the modem signals CTS, DSR, and CTS, and returns those that are
  1666.  on in as its return value, in a bit mask as described for ttwmdm.  Returns:
  1667.  -3 Not implemented
  1668.  -2 if the line does not have modem control
  1669.  -1 on error.
  1670.  >= 0 on success, with a bit mask containing the modem signals that are on.
  1671. */
  1672. ttgmdm()
  1673. {
  1674. #ifdef NETCONN
  1675.     if (netconn)                        /* Network connection */
  1676.       return(-2);                       /* No modem signals */
  1677. #endif /* NETCONN */
  1678.   return(-3);
  1679. }
  1680.  
  1681. /*  T T S S P D  --  Set the transmission of tty to ten times the argument */
  1682.  
  1683. ttsspd(speed) int speed; {
  1684. int s;
  1685. struct sgbuf before;
  1686.     debug (F101,"ttsspd: speed(cps):","",speed);
  1687.     if (ttyfd < 0) return(-1);
  1688.  
  1689. #ifdef  NETCONN
  1690.     if (netconn)
  1691.       return(0);
  1692. #endif  /* NETCONN */
  1693.  
  1694.     switch (speed) {
  1695.         case 5:         s = B50;        break;
  1696.         case 7:         s = B75;        break;
  1697.         case 11:        s = B110;       break;
  1698.         case 13:        s = B134;       break;
  1699.         case 15:        s = B150;       break;
  1700.         case 30:        s = B300;       break;
  1701.         case 60:        s = B600;       break;
  1702.         case 120:       s = B1200;      break;
  1703.         case 180:       s = B1800;      break;
  1704.         case 200:       s = B2000;      break;
  1705.         case 240:       s = B2400;      break;
  1706.         case 360:       s = B3600;      break;
  1707.         case 480:       s = B4800;      break;
  1708.         case 720:       s = B7200;      break;
  1709.         case 960:       s = B9600;      break;
  1710.         case 1920:      s = B19200;     break;
  1711.         case 3840:      s = B38400;     break;
  1712.         case 888:       return(-1); /* no 75/1200 split speed */
  1713.         default:        return -1;
  1714.     }
  1715.     _gs_opt(ttyfd,&before);
  1716.     before.sg_baud = (char)s;
  1717. #ifdef XMODE
  1718.     xmode((char)s); /* xmode open and closes => new options
  1719.                        => restore as they were before */
  1720.     return(_ss_opt(ttyfd,&before) < 0 ? -1 : s);
  1721. #else
  1722.     return(_ss_opt(ttyfd,&before) < 0 ? -1 : s);
  1723. #endif /* !XMODE */
  1724. }
  1725.  
  1726. #ifdef XMODE
  1727. int     /* change the line tty speed via xmode, special hack for bad drivers*/
  1728. xmode(os9_speed) char os9_speed;
  1729. {
  1730. char command[DEVNAMLEN+17]; /* e.g. xmode baud=38400 = 17 chars */
  1731. char devicename[DEVNAMLEN];
  1732. long old_speed;
  1733.     if ((old_speed = ttgspd()) < 0) return(-1);
  1734.     devicename[0] = '/';
  1735.     _gs_devn(ttyfd,&devicename[1]);
  1736.     sprintf(command,"xmode %s baud=%d",devicename,bdrts[os9_speed]);
  1737.     debug (F110,"xmode command = ",command,0);
  1738.     debug (F101,"xmode baud","",os9_speed);
  1739.     zsyscmd(command);
  1740.     close(ttyfd);       /* hopefully not iniz'ed */
  1741.     if ((ttyfd=open(devicename,0x43)) < 0) /* no open with new speed anymore*/
  1742.     {
  1743.       sprintf(command,"xmode %s baud=%d",devicename,old_speed);
  1744.       zsyscmd(command); /* restore old speed */
  1745.       ttyfd=open(devicename,0x43); /* now it should work again */
  1746.       return (-1);
  1747.     }
  1748.     return(os9_speed);
  1749. }
  1750. #endif /* XMODE */
  1751.  
  1752. VOID
  1753. ttimoff() {                           /* Turn off any timer interrupts */
  1754.     alarm(0);
  1755.     if (saval)
  1756.       signal(SIGALRM,saval);
  1757.     else
  1758.       signal(SIGALRM,(fptr)SIG_DFL);
  1759.     saval = NULL;
  1760. }
  1761.  
  1762. int alarm(secs) unsigned int secs;
  1763. /* after secs seconds the signal SIGALRM will be sent */
  1764. /* 0 will clear the alarm */
  1765. {
  1766.     if (secs) {
  1767.         timowhen = time((time_t *)0) + secs;
  1768.         return(add_alarm(secs,SIGALRM));
  1769.     }
  1770.     timowhen = 0;
  1771.     return(remove_alarm());
  1772. }
  1773.  
  1774. #ifndef O_GOODDRIVER
  1775. /* read from serial device with working timeout */
  1776. int
  1777. timoread(ttyfd, cp, n)
  1778. int ttyfd;
  1779. char *cp;
  1780. int n;
  1781. {
  1782.     if (timowhen == 0) return read(ttyfd, cp, n);
  1783.     (void) remove_alarm();
  1784.     for(;;) {
  1785.         if (_gs_rdy(ttyfd) >= n) return read(ttyfd, cp, n);
  1786.         if (time((time_t *)0) >= timowhen) {
  1787.             timowhen = 0;
  1788.             if (sigtbl[MAXSIG] != SIG_DFL) (*sigtbl[MAXSIG])(SIGALRM);
  1789.             return -1;
  1790.         }
  1791.         _ss_ssig(ttyfd, SIGARB);
  1792.         sleep(1);       /* interupted by _ss_ssig if incoming char */
  1793.         _ss_rel(ttyfd, SIGARB);
  1794.     }
  1795. }
  1796. #endif /* !O_GOODDRIVER */
  1797.  
  1798. /* Timeout handler for communication line input functions */
  1799. static SIGTYP
  1800. timerh(sig) int sig;{
  1801.     ttimoff();
  1802.     sigmask(-1);        /*  we are in an intercept routine but do not perform
  1803.                             a F$RTE (done implicitly but rts). => we have to
  1804.                             decrement the sigmask as F$RTE does. Warning:
  1805.                             longjump only restores the cpu registers NOT the
  1806.                             fpu registers. So, don't use fpu at all or at
  1807.                             least don't use common fpu (double or float)
  1808.                             register variables */
  1809.     longjmp(sjbuf,1);
  1810. }
  1811. int ustrncmp(a2,a3,d4) /*string compare but ignore upper and lower case*/
  1812. register char *a2,*a3;
  1813. register int d4;
  1814. {
  1815.   while((--d4>=0)&&(_toupper(*a2)==_toupper(*a3)))
  1816.   {
  1817.     if (*a3++ == '\0') return 0;
  1818.     a2++;
  1819.   }
  1820.   return (d4 < 0) ? 0 : *a2-*a3;
  1821. }
  1822.  
  1823. /* Sorry...gotta avoid namespace pollution! */
  1824. #ifdef _UCC
  1825. #define environ _environ
  1826. #endif /* _UCC */
  1827.  
  1828. #ifdef CK_REDIR
  1829. int
  1830. ttruncmd(s) char *s; {
  1831.     int r = 0;                          /* Return code */
  1832.                                         /* 0 = failure, 1 = success */
  1833.     int x, status;
  1834.     int pd[2];
  1835.     int pid;
  1836.     char *argb[3];
  1837.     extern char **environ;
  1838.     extern int os9forkc();
  1839.     extern char *getenv();
  1840.  
  1841.     if (ttyfd == -1) {
  1842.         printf("?Sorry, device is not open\n");
  1843.         return(0);
  1844.     }
  1845.     conres();                           /* Make console normal  */
  1846.     pd[0] = dup(0);
  1847.     pd[1] = dup(1);
  1848.     if (pd[0] != -1) close(0);
  1849.     if (pd[1] != -1) close(1);
  1850.     if (dup(ttyfd) == 0 && dup(ttyfd) == 1) {
  1851.         SIGTYP (*istat)(), (*qstat)();
  1852.         
  1853.         istat = signal(SIGINT,SIG_IGN); /* Let the fork handle keyboard */
  1854.         qstat = signal(SIGQUIT,SIG_IGN); /* interrupts itself... */
  1855.         if ((argb[0] = getenv("SHELL")) == (char *)0)
  1856.             argb[0] = "shell";
  1857.         argb[1] = s;
  1858.         argb[2] = (char *)0;
  1859.         if ((pid = os9exec(os9forkc, argb[0], argb, environ, 0, 0, 3)) > 0) {
  1860.             while ((x = wait(&status)) != pid && x != -1) {}
  1861.             r = 1;
  1862.         }
  1863.         signal(SIGINT,istat);           /* Restore interrupts */
  1864.         signal(SIGQUIT,qstat);
  1865.     }
  1866.     close(0);
  1867.     close(1);
  1868.     if (pd[0] != -1) dup(pd[0]);
  1869.     if (pd[1] != -1) dup(pd[1]);
  1870.     if (pd[0] != -1) close(pd[0]);
  1871.     if (pd[1] != -1) close(pd[1]);
  1872.     if (r) {
  1873.         r = 0;
  1874.         if (x == -1) {
  1875.             printf("?Can't wait for child process?\n");
  1876.         } else if (status != 0) {
  1877.             printf("?Command exit status: %d\n", status);
  1878.         } else r = 1;
  1879.     }
  1880.     concb((char)0/*escchr*/);           /* Restore console to CBREAK mode */
  1881.     return(r);
  1882. }
  1883. #endif /* CK_REDIR */
  1884.  
  1885. /* T T G W S I Z  -- get terminal window size */
  1886. /* The terminal screen size is stored in tt_rows and tt_cols */
  1887. /* We should probably get this from termcap, but for now, just use the page
  1888. /* length defined for the console device, and assume 80 columns. */
  1889.  
  1890. extern int tt_rows, tt_cols;
  1891.  
  1892. int
  1893. ttgwsiz()
  1894. {
  1895.     tt_rows = ccold.sg_page;
  1896.     tt_cols = 80;
  1897.     return 1;
  1898. }
  1899.