home *** CD-ROM | disk | FTP | other *** search
/ Columbia Kermit / kermit.zip / archives / ckl196.zip / ckutio.c < prev    next >
C/C++ Source or Header  |  2000-01-06  |  382KB  |  13,102 lines

  1. #ifdef aegis
  2. char *ckxv = "Aegis Communications support, 7.0.231, 31 Dec 1999";
  3. #else
  4. #ifdef Plan9
  5. char *ckxv = "Plan 9 Communications support, 7.0.231, 31 Dec 1999";
  6. #else
  7. char *ckxv = "UNIX Communications support, 7.0.231, 31 Dec 1999";
  8. #endif /* Plan9 */
  9. #endif /* aegis */
  10.  
  11. /*  C K U T I O  */
  12.  
  13. /* C-Kermit interrupt, communications control and I/O functions for UNIX */
  14.  
  15. /*
  16.   Author: Frank da Cruz (fdc@columbia.edu),
  17.   Columbia University Academic Information Systems, New York City.
  18.  
  19.   Copyright (C) 1985, 2000,
  20.     Trustees of Columbia University in the City of New York.
  21.     All rights reserved.  See the C-Kermit COPYING.TXT file or the
  22.     copyright text in the ckcmai.c module for disclaimer and permissions.
  23. */
  24.  
  25. /*
  26.   NOTE TO CONTRIBUTORS: This file, and all the other C-Kermit files, must be
  27.   compatible with C preprocessors that support only #ifdef, #else, #endif,
  28.   #define, and #undef.  Please do not use #if, logical operators, or other
  29.   preprocessor features in any of the portable C-Kermit modules.  You can,
  30.   of course, use these constructions in platform-specific modules when they
  31.   are supported by all compilers/preprocessors that could be used on that
  32.   platform.
  33. */
  34.  
  35. /* Includes */
  36.  
  37. #include "ckcsym.h"            /* This must go first   */
  38. #include "ckcdeb.h"            /* This must go second  */
  39. #include <errno.h>            /* System error numbers */
  40.  
  41. #ifdef __386BSD__
  42. #define ENOTCONN 57
  43. #else
  44. #ifdef __bsdi__
  45. #define ENOTCONN 57
  46. #else
  47. #ifdef __FreeBSD__
  48. #define ENOTCONN 57
  49. #endif /* __FreeBSD__ */
  50. #endif /* __bsdi__ */
  51. #endif /* __386BSD__ */
  52.  
  53. #ifdef SCO_OSR504
  54. #define NBBY 8
  55. #endif /* SCO_OSR504 */
  56.  
  57. #ifdef Plan9
  58. #define SELECT
  59. #include <sys/time.h>
  60. #include <select.h>
  61. #define FD_SETSIZE (3 * sizeof(long) * 8)
  62. static struct timeval tv;
  63. #endif /* Plan9 */
  64.  
  65. #include "ckcnet.h"            /* Symbols for network types. */
  66. #ifdef CK_SSL
  67. #include "ck_ssl.h"
  68. #endif /* CK_SSL */
  69.  
  70. /*
  71.   The directory-related includes are here because we need to test some
  72.   file-system-related symbols to find out which system we're being compiled
  73.   under.  For example, MAXNAMLEN is defined in BSD4.2 but not 4.1.
  74. */
  75. #ifdef SDIRENT                /* Directory bits... */
  76. #define DIRENT
  77. #endif /* SDIRENT */
  78.  
  79. #ifdef XNDIR
  80. #include <sys/ndir.h>
  81. #else /* !XNDIR */
  82. #ifdef NDIR
  83. #include <ndir.h>
  84. #else /* !NDIR, !XNDIR */
  85. #ifdef RTU
  86. #include "/usr/lib/ndir.h"
  87. #else /* !RTU, !NDIR, !XNDIR */
  88. #ifdef DIRENT
  89. #ifdef SDIRENT
  90. #include <sys/dirent.h>
  91. #else
  92. #include <dirent.h>
  93. #endif /* SDIRENT */
  94. #else /* !RTU, !NDIR, !XNDIR, !DIRENT, i.e. all others */
  95. #include <sys/dir.h>
  96. #endif /* DIRENT */
  97. #endif /* RTU */
  98. #endif /* NDIR */
  99. #endif /* XNDIR */
  100.  
  101. #ifdef QNX
  102. #include <sys/dev.h>
  103. #endif /* QNX */
  104.  
  105. #ifdef HPUX5
  106. #ifndef TCPSOCKET
  107. /* I don't know why this is needed here since we never reference bzero(). */
  108. /* But without it C-Kermit won't link in an HP-UX 5.xx non-TCP build. */
  109. void
  110. bzero(s,n) char *s; int n; {
  111.     extern char * memset();
  112.     memset(s,0,n);
  113. }
  114. #endif /* TCPSOCKET */
  115. #endif /* HPUX5 */
  116.  
  117. /* Definition of HZ, used in msleep() */
  118.  
  119. #ifdef MIPS
  120. #define HZ ( 1000 / CLOCK_TICK )
  121. #else
  122. #ifdef ATTSV
  123. #ifndef NAP
  124. #ifndef TRS16
  125. #include <sys/param.h>
  126. #else
  127. #define HZ ( 1000 / CLOCK_TICK )
  128. #endif /* TRS16 */
  129. #ifdef NAPHACK
  130. #define nap(x) (void)syscall(3112, (x))
  131. #define NAP
  132. #endif /* NAPHACK */
  133. #endif /* NAP */
  134. #endif /* ATTSV */
  135. #endif /* MIPS */
  136.  
  137. #ifdef M_UNIX
  138. #undef NGROUPS_MAX        /* Prevent multiple definition warnings */
  139. #endif /* M_UNIX */
  140.  
  141. /*
  142.   NOTE: HP-UX 8.0 has a <sys/poll.h>, but there is no corresponding
  143.   library routine, so _poll comes up undefined at link time.
  144. */
  145. #ifdef CK_POLL
  146. #ifndef AIXRS            /* IBM AIX needs special handling */
  147. #include <poll.h>        /* "standard" (SVID) i/o multiplexing, etc */
  148. #else /* AIXRS */
  149. #ifdef SVR4            /* AIX 3.2 is like SVID... */
  150. #include <poll.h>
  151. #else                /* But AIX 3.1 is not ... */
  152. #include <sys/poll.h>        /* The include file is in include/sys */
  153. #define events reqevents    /* And it does not map IBM-specific member */
  154. #define revents rtnevents    /* names to the System V equivalents */
  155. #endif /* SVR4 */
  156. #endif /* AIXRS */
  157. #endif /* CK_POLL */
  158.  
  159. #include <signal.h>                     /* Signals */
  160.  
  161. /* For setjmp and longjmp */
  162.  
  163. #ifndef ZILOG
  164. #include <setjmp.h>
  165. #else
  166. #include <setret.h>
  167. #endif /* ZILOG */
  168.  
  169. /* Maximum length for the name of a tty device */
  170.  
  171. #ifndef DEVNAMLEN
  172. #define DEVNAMLEN 32
  173. #endif /* DEVNAMLEN */
  174.  
  175. #ifdef    NETCONN
  176. #undef DEVNAMLEN
  177. #define DEVNAMLEN 256            /* Longer field for host:service */
  178. #endif  /* NETCONN */
  179.  
  180. /*
  181.   The following test differentiates between 4.1 BSD and 4.2 & later.
  182.   If you have a 4.1BSD system with the DIRENT library, this test could
  183.   mistakenly diagnose 4.2BSD and then later enable the use of system calls
  184.   that aren't defined.  If indeed there are such systems, we can use some
  185.   other way of testing for 4.1BSD, or add yet another compile-time switch.
  186. */
  187. #ifdef BSD4
  188. #ifdef MAXNAMLEN
  189. #ifndef FT21                /* Except for Fortune. */
  190. #ifndef FT18
  191. #ifndef BELLV10                /* And Bell Labs Research UNIX V10 */
  192. #define BSD42
  193. #endif /* BELLV10 */
  194. #endif /* FT18 */
  195. #endif /* FT21 */
  196. #endif /* MAXNAMLEN */
  197. #endif /* BSD4 */
  198. /*
  199.   Minix 2.0 support added by Terry McConnell,
  200.   Syracuse University <tmc@barnyard.syr.edu>
  201.   No more sgtty interface, posix compliant.
  202. */
  203. #ifdef MINIX2
  204. #define _MINIX   /* Needed for some Minix header files */
  205. #undef MINIX     /* Old minix 1.0: used sgtty interface */
  206. #define BSD44ORPOSIX
  207. #define SVORPOSIX
  208. #define DCLTIMEVAL
  209. #define NOFILEH
  210. #include <sys/types.h>
  211. #include <sys/ioctl.h>
  212. #include <termios.h>
  213. #include <limits.h>
  214. #undef TIOCGETC    /* defined in sys/ioctl.h, but not really supported */
  215. #define TANDEM 0
  216. #endif /* MINIX2 */
  217.  
  218. /*
  219.  MINIX 1.0 support added by Charles Hedrick,
  220.  Rutgers University <hedrick@aramis.rutgers.edu>.
  221.  MINIX also has V7 enabled.
  222. */
  223. #ifdef MINIX
  224. #define TANDEM 0
  225. #define MYREAD
  226. #define NOSYSIOCTLH
  227. #include <limits.h>
  228. #endif /* MINIX */
  229.  
  230. #ifdef CK_REDIR        /* <sys/wait.h> needed only for REDIRECT command. */
  231. /*
  232.   If anybody can figure out how to make this work with NeXTSTEP, be
  233.   my guest!  (NeXTBlah/NeXTBlah/bsd/sys/wait.h does not define WEXITSTATUS)
  234. */
  235. #ifndef CK_WAIT_H            /* If wait.h not already included... */
  236. #include <sys/wait.h>            /* Include it */
  237. #endif /* CK_WAIT_H */
  238. #endif /* CK_REDIR */
  239.  
  240. #include "ckuver.h"            /* Version herald */
  241. char *ckxsys = HERALD;
  242.  
  243. #ifdef CK_UTSNAME
  244. #include <sys/utsname.h>
  245. #ifdef UW7
  246. #ifndef SYS_NMLN
  247. #define SYS_NMLN 257
  248. #endif /* NMLN */
  249. #endif /* UW7 */
  250. #ifdef HPUX9PLUS
  251. static int hpis800 = 0;
  252. #endif /* HPUX9PLUS */
  253. #ifdef SYS_NMLN
  254. #define CK_SYSNMLN SYS_NMLN
  255. #else
  256. #ifdef _SYS_NMLN
  257. #define CK_SYSNMLN _SYS_NMLN
  258. #else
  259. #ifdef UTSLEN
  260. #define CK_SYSNMLN UTSLEN
  261. #else
  262. #define CK_SYSNMLN 31
  263. #endif /* UTSLEN */
  264. #endif /* _SYS_NMLN */
  265. #endif /* SYS_NMLN */
  266. char unm_mch[CK_SYSNMLN+1] = { '\0', '\0' };
  267. char unm_mod[CK_SYSNMLN+1] = { '\0', '\0' };
  268. char unm_nam[CK_SYSNMLN+1] = { '\0', '\0' };
  269. char unm_rel[CK_SYSNMLN+1] = { '\0', '\0' };
  270. char unm_ver[CK_SYSNMLN+1] = { '\0', '\0' };
  271. #endif /* CK_UTSNAME */
  272.  
  273. #ifdef CIE
  274. #include <stat.h>            /* For chasing symlinks, etc. */
  275. #else
  276. #include <sys/stat.h>
  277. #endif /* CIE */
  278.  
  279. /* UUCP lockfile material... */
  280.  
  281. #ifndef NOUUCP
  282. #ifdef USETTYLOCK
  283. #ifdef USE_UU_LOCK
  284. #include <libutil.h>
  285. #endif /* USE_UU_LOCK */
  286. #else  /* USETTYLOCK */
  287.  
  288. /* Name of UUCP tty device lockfile */
  289.  
  290. #ifdef LINUXFSSTND
  291. #ifndef HDBUUCP
  292. #define HDBUUCP
  293. #endif /* HDBUUCP */
  294. #endif /* LINUXFSSTND */
  295.  
  296. #ifdef ACUCNTRL
  297. #define LCKDIR
  298. #endif /* ACUCNTRL */
  299.  
  300. /*
  301.   PIDSTRING means use ASCII string to represent pid in lockfile.
  302. */
  303. #ifndef PIDSTRING
  304. #ifdef HDBUUCP
  305. #define PIDSTRING
  306. #else
  307. #ifdef BSD44
  308. #define PIDSTRING
  309. #else
  310. #ifdef RTAIX
  311. #define PIDSTRING
  312. #else
  313. #ifdef AIXRS
  314. #define PIDSTRING
  315. #else
  316. #ifdef COHERENT
  317. #define PIDSTRING
  318. #endif /* COHERENT */
  319. #endif /* AIXRS */
  320. #endif /* RTAIX */
  321. #endif /* BSD44 */
  322. #endif /* HDBUUCP */
  323. #endif /* PIDSTRING */
  324.  
  325. /* Now the PIDSTRING exceptions... */
  326.  
  327. #ifdef PIDSTRING
  328. #ifdef HPUX
  329. #undef PIDSTRING
  330. #endif /* HPUX */
  331. #endif /* PIDSTRING */
  332.  
  333. #ifdef __bsdi__                /* BSDI (at least thru 1.1) */
  334. #ifdef PIDSTRING
  335. #undef PIDSTRING
  336. #endif /* PIDSTRING */
  337. #endif /* __bsdi__ */
  338.  
  339. #ifdef OSF32                /* Digital UNIX (OSF/1) 3.2 */
  340. #ifdef PIDSTRING
  341. #undef PIDSTRING
  342. #endif /* PIDSTRING */
  343. #endif /* OSF32 */
  344.  
  345. /*
  346.   LOCK_DIR is the name of the lockfile directory.
  347.   If LOCK_DIR is already defined (e.g. on command line), we don't change it.
  348. */
  349. #ifndef LOCK_DIR
  350. #ifdef BSD44
  351. #ifdef __386BSD__
  352. #define LOCK_DIR "/var/spool/lock"
  353. #else
  354. #ifdef __FreeBSD__
  355. #define LOCK_DIR "/var/spool/lock"
  356. #else
  357. #ifdef __NetBSD__
  358. #define LOCK_DIR "/var/spool/lock"
  359. #else
  360. #define LOCK_DIR "/var/spool/uucp"
  361. #endif /* __NetBSD__ */
  362. #endif /* __FreeBSD__ */
  363. #endif /* __386BSD__ */
  364. #else
  365. #ifdef DGUX430
  366. #define LOCK_DIR "/var/spool/locks"
  367. #else
  368. #ifdef HPUX10
  369. #define LOCK_DIR "/var/spool/locks"
  370. #else
  371. #ifdef RTAIX                /* IBM RT PC AIX 2.2.1 */
  372. #define LOCK_DIR "/etc/locks"
  373. #else
  374. #ifdef AIXRS
  375. #define LOCK_DIR "/etc/locks"
  376. #else
  377. #ifdef ISIII
  378. #define LOCK_DIR "/etc/locks"
  379. #else
  380. #ifdef HDBUUCP
  381. #ifdef M_SYS5
  382. #define LOCK_DIR "/usr/spool/uucp"
  383. #else
  384. #ifdef M_UNIX
  385. #define LOCK_DIR "/usr/spool/uucp"
  386. #else
  387. #ifdef SVR4
  388. #define LOCK_DIR "/var/spool/locks"
  389. #else
  390. #ifdef SUNOS4
  391. #define LOCK_DIR "/var/spool/locks"
  392. #else
  393. #ifdef LINUXFSSTND
  394. #define LOCK_DIR "/var/lock";
  395. #else
  396. #define LOCK_DIR "/usr/spool/locks"
  397. #endif /* LINUXFSSTND */
  398. #endif /* SUNOS4 */
  399. #endif /* SVR4 */
  400. #endif /* M_UNIX */
  401. #endif /* M_SYS5 */
  402. #else
  403. #ifdef LCKDIR
  404. #define LOCK_DIR "/usr/spool/uucp/LCK"
  405. #else
  406. #ifdef COHERENT
  407. #define LOCK_DIR "/usr/spool/uucp"
  408. #else
  409. #define LOCK_DIR "/usr/spool/uucp"
  410. #endif /* COHERENT */
  411. #endif /* LCKDIR */
  412. #endif /* HDBUUCP */
  413. #endif /* ISIII */
  414. #endif /* AIXRS */
  415. #endif /* RTAIX */
  416. #endif /* HPUX10 */
  417. #endif /* DGUX430 */
  418. #endif /* BSD44 */
  419. #endif /* !LOCK_DIR (outside ifndef) */
  420.  
  421. #ifdef OSF2                /* OSF/1 2.0 or later */
  422. #ifdef LOCK_DIR                /* (maybe 1.x too, who knows...) */
  423. #undef LOCK_DIR
  424. #define LOCK_DIR "/var/spool/locks"
  425. #endif /* LOCK_DIR */
  426. #endif /* OSF2 */
  427.  
  428. #ifdef SVR4
  429. #ifndef BSD44
  430. #ifndef LOCKF
  431. #define LOCKF                /* Use lockf() on tty device in SVR4 */
  432. #endif /* LOCKF */
  433. #endif /* BSD44 */
  434. #endif /* SVR4 */
  435.  
  436. #ifdef NOLOCKF                /* But NOLOCKF cancels LOCKF */
  437. #ifdef LOCKF
  438. #undef LOCKF
  439. #endif /* LOCKF */
  440. #endif /* NOLOCKF */
  441.  
  442. /* More about this below... */
  443.  
  444. #endif /* USETTYLOCK */
  445. #endif /* NOUUCP */
  446.  
  447. /*
  448.   MYREAD means use our internally defined nonblocking buffered read routine.
  449. */
  450. #ifdef ATTSV
  451. #define MYREAD
  452. #endif /* ATTSV */
  453.  
  454. #ifdef ATT7300
  455. #ifndef MYREAD
  456. #define MYREAD
  457. #endif /* MYREAD */
  458. /* bits for attmodem: internal modem in use, restart getty */
  459. #define ISMODEM 1
  460. #define DOGETY 512
  461. #endif  /* ATT7300 */
  462.  
  463. #ifdef BSD42
  464. #define MYREAD
  465. #endif /* BSD42 */
  466.  
  467. #ifdef POSIX
  468. #define MYREAD
  469. #endif /* POSIX */
  470. #ifdef __bsdi__
  471. #ifndef O_NDELAY
  472. #define O_NDELAY O_NONBLOCK
  473. #endif /* O_NDELAY */
  474. #endif /* __bsdi__ */
  475.  
  476. /*
  477.  Variables available to outside world:
  478.  
  479.    dftty  -- Pointer to default tty name string, like "/dev/tty".
  480.    dfloc  -- 0 if dftty is console, 1 if external line.
  481.    dfprty -- Default parity
  482.    dfflow -- Default flow control
  483.    ckxech -- Flag for who echoes console typein:
  484.      1 - The program (system echo is turned off)
  485.      0 - The system (or front end, or terminal).
  486.    functions that want to do their own echoing should check this flag
  487.    before doing so.
  488.  
  489.    flfnam  -- Name of lock file, including its path, e.g.,
  490.                 "/usr/spool/uucp/LCK..cul0" or "/etc/locks/tty77"
  491.    lkflfn  -- Name of link to lock file, including its paths
  492.    haslock -- Flag set if this kermit established a uucp lock.
  493.    lockpid -- PID of other process that has desired line open, as string.
  494.    backgrd -- Flag indicating program executing in background ( & on
  495.                 end of shell command). Used to ignore INT and QUIT signals.
  496.    rtu_bug -- Set by stptrap().  RTU treats ^Z as EOF (but only when we handle
  497.                 SIGTSTP)
  498.  
  499.  Functions for assigned communication line (either external or console tty):
  500.  
  501.    sysinit()               -- System dependent program initialization
  502.    syscleanup()            -- System dependent program shutdown
  503.    ttopen(ttname,local,mdmtyp,timo) -- Open the named tty for exclusive access.
  504.    ttclos()                -- Close & reset the tty, releasing any access lock.
  505.    ttsspd(cps)             -- Set the transmission speed of the tty.
  506.    ttgspd()                -- Get (read) the the transmission speed of the tty.
  507.    ttpkt(speed,flow,parity) -- Put the tty in packet mode and set the speed.
  508.    ttvt(speed,flow)        -- Put the tty in virtual terminal mode.
  509.                                 or in DIALING or CONNECTED modem control state.
  510.    ttres()                 -- Restore original tty modes.
  511.    ttscarr(carrier)        -- Set carrier control mode, on/off/auto.
  512.    ttinl(dest,max,timo)    -- Timed read line from the tty.
  513.    ttinc(timo)             -- Timed read character from tty.
  514.    myread()                -- Raw mode bulk buffer read, gives subsequent
  515.                                 chars one at a time and simulates FIONREAD.
  516.    myunrd(c)               -- Places c back in buffer to be read (one only)
  517.    ttchk()                 -- See how many characters in tty input buffer.
  518.    ttxin(n,buf)            -- Read n characters from tty (untimed).
  519.    ttol(string,length)     -- Write a string to the tty.
  520.    ttoc(c)                 -- Write a character to the tty.
  521.    ttflui()                -- Flush tty input buffer.
  522.    ttsndb()                -- Send BREAK signal.
  523.    ttsndlb()               -- Send Long BREAK signal.
  524.  
  525.    ttlock(ttname)          -- "Lock" tty device against uucp collisions.
  526.    ttunlck()               -- Unlock tty device.
  527.  
  528.                               For ATT7300/Unix PC, System V:
  529.    attdial(ttname,speed,telnbr) -- dials ATT7300/Unix PC internal modem
  530.    offgetty(ttname)        -- Turns off getty(1m) for comms line
  531.    ongetty(ttname)         -- Restores getty() to comms line
  532. */
  533.  
  534. /*
  535. Functions for console terminal:
  536.  
  537.    congm()   -- Get console terminal modes.
  538.    concb(esc) -- Put the console in single-character wakeup mode with no echo.
  539.    conbin(esc) -- Put the console in binary (raw) mode.
  540.    conres()  -- Restore the console to mode obtained by congm().
  541.    conoc(c)  -- Unbuffered output, one character to console.
  542.    conol(s)  -- Unbuffered output, null-terminated string to the console.
  543.    conola(s) -- Unbuffered output, array of strings to the console.
  544.    conxo(n,s) -- Unbuffered output, n characters to the console.
  545.    conchk()  -- Check if characters available at console (bsd 4.2).
  546.                 Check if escape char (^\) typed at console (System III/V).
  547.    coninc(timo)  -- Timed get a character from the console.
  548.    congks(timo)  -- Timed get keyboard scan code.
  549.    conint()  -- Enable terminal interrupts on the console if not background.
  550.    connoi()  -- Disable terminal interrupts on the console if not background.
  551.  
  552. Time functions
  553.  
  554.    msleep(m) -- Millisecond sleep
  555.    ztime(&s) -- Return pointer to date/time string
  556.    rtimer() --  Reset timer
  557.    gtimer()  -- Get elapsed time since last call to rtimer()
  558. */
  559.  
  560. /* Conditional Includes */
  561.  
  562. /* Whether to include <sys/file.h> */
  563.  
  564. #ifdef RTU                /* RTU doesn't */
  565. #define NOFILEH
  566. #endif /* RTU */
  567.  
  568. #ifdef CIE                /* CIE does. */
  569. #undef NOFILEH
  570. #endif /* CIE */
  571.  
  572. #ifdef BSD41                /* 4.1 BSD doesn't */
  573. #define NOFILEH
  574. #endif /* BSD41 */
  575.  
  576. #ifdef is68k                /* is68k (whatever that is)  */
  577. #define NOFILEH
  578. #endif /* is68k */
  579.  
  580. #ifdef MINIX                /* MINIX */
  581. #define NOFILEH
  582. #endif /* MINIX */
  583.  
  584. #ifdef COHERENT                /* Coherent */
  585. #define NOFILEH
  586. #endif /* COHERENT */
  587.  
  588. #ifndef NOFILEH                /* Now include if selected. */
  589. #include <sys/file.h>
  590. #endif /* NOFILEH */
  591.  
  592. /* POSIX */
  593.  
  594. #ifdef BSD44ORPOSIX            /* POSIX uses termios.h */
  595. #define TERMIOS
  596. #ifdef __bsdi__
  597. #ifdef POSIX
  598. #undef _POSIX_SOURCE            /* Get extra stuff from termios.h */
  599. #endif /* POSIX */
  600. #endif /* __bsdi__ */
  601. #include <termios.h>
  602. #ifdef LINUX
  603. #include <sys/ioctl.h>
  604. #endif /* LINUX */
  605. #ifdef QNX16
  606. #include <ioctl.h>
  607. #endif /* QNX16 */
  608. #ifdef __bsdi__
  609. #ifdef POSIX
  610. #define _POSIX_SOURCE
  611. #endif /* POSIX */
  612. #endif /* __bsdi__ */
  613. #ifndef BSD44                /* Really POSIX */
  614. #ifndef CK_QNX32            /* was CK_QNX32 */
  615. #define NOSYSIOCTLH            /* No ioctl's allowed. */
  616. #undef ultrix                /* Turn off any ultrix features. */
  617. #endif /* CK_QNX32 */
  618. #endif /* BSD44 */
  619. #endif /* POSIX */
  620.  
  621. /* System III, System V */
  622.  
  623. #ifdef ATTSV
  624. #ifndef BSD44
  625. #ifndef POSIX
  626. #include <termio.h>
  627. #endif /* POSIX */
  628. #endif /* BSD44 */
  629. #ifdef TERMIOX
  630. /* Need this for termiox structure, RTS/CTS and DTR/CD flow control */
  631. #include <termiox.h>
  632.   struct termiox rctsx;
  633. #else
  634. #ifdef STERMIOX
  635. #ifdef SCO_OSR504
  636. /* Sorry, this is truly disgusting but it's SCO's fault. */
  637. #ifndef _SVID3
  638. #define _CK_SVID3_X
  639. #define _SVID3
  640. #endif /* _SVID3 */
  641. #endif /* SCO_OSR504 */
  642. #include <sys/termiox.h>
  643.   struct termiox rctsx;
  644. #ifdef CK_SVID3_X
  645. #undef _SVID3
  646. #undef CK_SVID3_X
  647. #endif /* CK_SVID3_X */
  648. #endif /* STERMIOX */
  649. #endif /* TERMIOX */
  650. #endif /* ATTSV */
  651.  
  652. #ifdef COHERENT            /* Use termio.h, not sgtty.h for Coherent */
  653. #include <termio.h>
  654. #endif /* COHERENT */
  655.  
  656. #ifdef MINIX                /* MINIX uses ioctl's */
  657. #define NOSYSIOCTLH            /* but has no <sys/ioctl.h> */
  658. #endif /* MINIX */
  659.  
  660. /* Others */
  661.  
  662. #ifndef NOSYSIOCTLH            /* Others use ioctl() */
  663. #ifdef SUN4S5
  664. /*
  665.   This is to get rid of cpp warning messages that occur because all of
  666.   these symbols are defined by both termios.h and ioctl.h on the SUN.
  667. */
  668. #undef ECHO
  669. #undef NL0
  670. #undef NL1
  671. #undef TAB0
  672. #undef TAB1
  673. #undef TAB2
  674. #undef XTABS
  675. #undef CR0
  676. #undef CR1
  677. #undef CR2
  678. #undef CR3
  679. #undef FF0
  680. #undef FF1
  681. #undef BS0
  682. #undef BS1
  683. #undef TOSTOP
  684. #undef FLUSHO
  685. #undef PENDIN
  686. #undef NOFLSH
  687. #endif /* SUN4S5 */
  688. #include <sys/ioctl.h>
  689. #endif /* NOSYSIOCTLH */
  690. /*
  691.   We really, really, REALLY want FIONREAD, because it is the only way to find
  692.   out not just *if* stuff is waiting to be read, but how much, which is
  693.   critical to our sliding-window and streaming procedures, not to mention
  694.   efficiency of CONNECT, etc.
  695. */
  696. #ifdef BELLV10
  697. #include <sys/filio.h>            /* For FIONREAD */
  698. #ifdef FIONREAD
  699. #define MYREAD
  700. #endif /* MYREAD */
  701. #endif /* BELLV10 */
  702.  
  703. #ifndef FIONREAD
  704. /* It wasn't found in ioctl.h or term*.h - try these places: */
  705. #ifdef UNIXWARE
  706. #include <sys/filio.h>
  707. #else
  708. #ifdef SOLARIS
  709. #include <sys/filio.h>
  710. #endif /* SOLARIS */
  711. #endif /* UNIXWARE */
  712. #endif /* FIONREAD */
  713.  
  714. #ifdef XENIX /* Was M_UNIX but XENIX implies M_UNIX and applies to XENIX too */
  715. /*
  716.   <sys/socket.h> included above via "ckcnet.h" defines FIONREAD as
  717.   something.  Due to this, in_chk() uses the FIONREAD instead of RDCHK
  718.   and the hot keys during file transfer (X to cancel file etc) do not
  719.   work because FIONREAD doesn't work even though it is defined.
  720.  
  721.   NOTE: This might also be true elsewhere.
  722. */
  723. #ifdef FIONREAD
  724. #undef FIONREAD
  725. #endif /* FIONREAD */
  726. #endif /* XENIX */
  727.  
  728. #ifdef CK_SCOV5                /* Ditto for SCO OpenServer 5.0 */
  729. #ifdef FIONREAD
  730. #undef FIONREAD
  731. #endif /* FIONREAD */
  732. #endif /* XENIX */
  733.  
  734. /* Whether to include <fcntl.h> */
  735.  
  736. #ifndef is68k                /* Only a few don't have this one. */
  737. #ifndef BSD41
  738. #ifndef FT21
  739. #ifndef FT18
  740. #ifndef COHERENT
  741. #include <fcntl.h>
  742. #endif /* COHERENT */
  743. #endif /* FT18 */
  744. #endif /* FT21 */
  745. #endif /* BSD41 */
  746. #endif /* not is68k */
  747.  
  748. #ifdef COHERENT
  749. #ifdef _I386
  750. #include <fcntl.h>
  751. #else
  752. #include <sys/fcntl.h>
  753. #endif /* _I386 */
  754. #endif /* COHERENT */
  755.  
  756. #ifdef ATT7300                /* Unix PC, internal modem dialer */
  757. #include <sys/phone.h>
  758. #endif /* ATT7300 */
  759.  
  760. #ifdef HPUX                /* HP-UX variations. */
  761. #define HPUXJOBCTL
  762. #include <sys/modem.h>            /* HP-UX modem signals */
  763. #ifdef hp9000s500            /* Model 500 */
  764. #undef HPUXJOBCTL
  765. #endif /* hp9000s500 */
  766. #ifdef HPUXPRE65
  767. #undef HPUXJOBCTL
  768. typedef long mflag;
  769. #endif /* HPUXPRE65 */
  770. #ifdef HPUXJOBCTL
  771. #include <sys/bsdtty.h>            /* HP-UX Berkeley tty support */
  772. #endif /* HPUXJOBCTL */
  773. #endif /* HPUX */
  774.  
  775. /*
  776.   Which time.h files to include... See ckcdeb.h for defaults.
  777.   Note that 0, 1, 2, or all 3 of these can be included according to
  778.   the symbold definitions.
  779. */
  780. #ifndef NOTIMEH
  781. #ifdef TIMEH
  782. #include <time.h>
  783. #endif /* TIMEH */
  784. #endif /* NOTIMEH */
  785.  
  786. #ifndef NOSYSTIMEH
  787. #ifdef SYSTIMEH
  788. #include <sys/time.h>
  789. #endif /* SYSTIMEH */
  790. #endif /* NOSYSTIMEH */
  791.  
  792. #ifndef NOSYSTIMEBH
  793. #ifdef SYSTIMEBH
  794. #include <sys/timeb.h>
  795. #endif /* SYSTIMEBH */
  796. #endif /* NOSYSTIMEBH */
  797.  
  798. #ifdef DCLTIMEVAL
  799. /*
  800.   In certain POSIX builds (like Unixware 7), <[sys/]time.h> refuses to
  801.   define the structs we need to access the higher speeds, so we have to
  802.   do it ourselves.
  803. */
  804. struct timeval {
  805.     long tv_sec;
  806.     long tv_usec;
  807. };
  808. struct timezone {
  809.     int tz_minuteswest;
  810.     int tz_dsttime;
  811. };
  812. #endif /* DCLTIMEVAL */
  813.  
  814. #ifdef __linux__
  815. /* THIS IS OBSOLETE since about Linux 0.92 */
  816. #ifdef OLINUXHISPEED
  817. #include <linux/serial.h>
  818. #endif /* OLINUXHISPEED */
  819. #ifdef __alpha__            /* Linux on DEC Alpha */
  820. #ifndef __GLIBC__            /* But not with glibc */
  821. #include <asm/termios.h>
  822. #endif /* __GLIBC__ */
  823. #endif /* __alpha__ */
  824. #endif /* __linux__ */
  825.  
  826. #ifdef NOIEXTEN                /* This is broken on some systems */
  827. #undef IEXTEN                /* like Convex/OS 9.1 */
  828. #endif /* NOIEXTEN */
  829. #ifndef IEXTEN                /* Turn off ^O/^V processing. */
  830. #define IEXTEN 0            /* Needed, at least, on BSDI. */
  831. #endif /* IEXTEN */
  832. /*
  833.   Pick up definitions needed for select() if we don't have them already.
  834.   Normally they come from <sys/types.h> but some systems get them from
  835.   <sys/select.h>...  Rather than hardwire all of them into the source, we
  836.   include it if SELECT_H is defined in compile-time CFLAGS.
  837. */
  838. #ifndef SCO_OSR504
  839. #ifdef SELECT_H
  840. #include <sys/select.h>
  841. #endif /* SELECT_H */
  842. #endif /* SCO_OSR504 */
  843.  
  844. #ifdef aegis
  845. #include "/sys/ins/base.ins.c"
  846. #include "/sys/ins/error.ins.c"
  847. #include "/sys/ins/ios.ins.c"
  848. #include "/sys/ins/sio.ins.c"
  849. #include "/sys/ins/pad.ins.c"
  850. #include "/sys/ins/time.ins.c"
  851. #include "/sys/ins/pfm.ins.c"
  852. #include "/sys/ins/pgm.ins.c"
  853. #include "/sys/ins/ec2.ins.c"
  854. #include "/sys/ins/type_uids.ins.c"
  855. #include <default_acl.h>
  856. #undef TIOCEXCL
  857. #undef FIONREAD
  858. #endif /* aegis */
  859.  
  860. #ifdef sxaE50                /* PFU Compact A SX/A TISP V10/L50 */
  861. #undef FIONREAD
  862. #endif /* sxaE50 */
  863.  
  864. /* The following #defines are catch-alls for those systems */
  865. /* that didn't have or couldn't find <file.h>... */
  866.  
  867. #ifndef FREAD
  868. #define FREAD 0x01
  869. #endif /* FREAD */
  870.  
  871. #ifndef FWRITE
  872. #define FWRITE 0x10
  873. #endif /* FWRITE */
  874.  
  875. #ifndef O_RDONLY
  876. #define O_RDONLY 000
  877. #endif /* O_RDONLY */
  878.  
  879. #ifdef SVORPOSIX
  880. /*
  881.   Modem signals are also forbidden in the POSIX world.  But some POSIX-based
  882.   platforms let us at them anyway if we know where to look.
  883. */
  884. #ifndef NEEDMDMDEFS
  885. /* Doesn't work for Linux */
  886. #ifdef UNIXWARE7
  887. #define NEEDMDMDEFS
  888. #endif /* UNIXWARE7 */
  889. #endif /* NEEDMDMDEFS */
  890.  
  891. #ifdef NEEDMDMDEFS
  892. #ifndef TIOCMGET
  893. #define TIOCMGET (('t'<<8)|29)
  894. #endif /* TIOCMGET */
  895.  
  896. #ifndef TIOCM_DTR
  897. #define TIOCM_DTR 0x0002
  898. #endif /* TIOCM_DTR */
  899. #ifndef TIOCM_RTS
  900. #define TIOCM_RTS 0x0004
  901. #endif /* TIOCM_RTS */
  902. #ifndef TIOCM_CTS
  903. #define TIOCM_CTS 0x0020
  904. #endif /* TIOCM_CTS */
  905. #ifndef TIOCM_CAR
  906. #define TIOCM_CAR 0x0040
  907. #endif /* TIOCM_CAR */
  908. #ifndef TIOCM_RNG
  909. #define TIOCM_RNG 0x0080
  910. #endif /* TIOCM_RNG */
  911. #ifndef TIOCM_DSR
  912. #define TIOCM_DSR 0x0100
  913. #endif /* TIOCM_DSR */
  914. #endif /* NEEDMDMDEFS */
  915. #endif /* SVORPOSIX */
  916.  
  917. /* Declarations */
  918.  
  919. #ifdef OXOS
  920. #undef TCGETA
  921. #undef TCSETA
  922. #undef TCSETAW
  923. #undef TCSETAF
  924. #define TCGETA TCGETS
  925. #define TCSETA TCSETS
  926. #define TCSETAW TCSETSW
  927. #define TCSETAF TCSETSF
  928. #define termio termios
  929. #endif /* OXOS */
  930.  
  931. #ifdef SVORPOSIX            /* AT&T Sys V or POSIX */
  932. #ifdef UNIXWAREPOSIX            /* UnixWare 7 POSIX build */
  933. /*
  934.   In Unixware POSIX builds, <[sys/]time.h> refuses to define the
  935.   structs we need to access the higher speeds, so we have to do it
  936.   ourselves.
  937. */
  938. struct timeval {
  939.     long tv_sec;
  940.     long tv_usec;
  941. };
  942. struct timezone {
  943.     int tz_minuteswest;
  944.     int tz_dsttime;
  945. };
  946. #endif /* UNIXWAREPOSIX */
  947. #endif /* SVORPOSIX */
  948.  
  949. #ifdef __GNUC__
  950. #ifdef XENIX
  951. /*
  952.   Because Xenix <time.h> doesn't declare time() if we're using gcc.
  953. */
  954. time_t time();
  955. #endif /* XENIX */
  956. #endif /* __GNUC__ */
  957.  
  958. /* Special stuff for V7 input buffer peeking */
  959.  
  960. #ifdef  V7
  961. int kmem[2] = { -1, -1};
  962. char *initrawq(), *qaddr[2]={0,0};
  963. #define CON 0
  964. #define TTY 1
  965. #endif /* V7 */
  966.  
  967. /* dftty is the device name of the default device for file transfer */
  968. /* dfloc is 0 if dftty is the user's console terminal, 1 if an external line */
  969.  
  970. #ifndef DFTTY
  971. #ifdef PROVX1
  972.     char *dftty = "/dev/com1.dout"; /* Only example so far of a system */
  973.     char *dfmdm = "none";
  974.     int dfloc = 1;                  /* that goes in local mode by default */
  975. #else
  976.     char *dftty = CTTNAM;               /* Remote by default, use normal */
  977.     char *dfmdm = "none";
  978.     int dfloc = 0;                      /* controlling terminal name. */
  979. #endif /* PROVX1 */
  980. #else
  981.     char *dftty = DFTTY;        /* Default location specified on */
  982.     char *dfmdm = "none";        /* command line. */
  983.     int dfloc = 1;                      /* controlling terminal name. */
  984. #endif /* DFTTY */
  985.  
  986.     char cttnam[DEVNAMLEN+1] = { '\0', '\0' }; /* Determined at runtime */
  987.  
  988. #ifdef RTU
  989.     int rtu_bug = 0;            /* set to 1 when returning from SIGTSTP */
  990. #endif /* RTU */
  991.  
  992.     int dfprty = DEFPAR;                /* Default parity (0 = none) */
  993.     int ttprty = 0;                     /* The parity that is in use. */
  994.     static int ttpmsk = 0xff;        /* Parity stripping mask. */
  995.     int ttmdm = 0;                      /* Modem in use. */
  996.     int ttcarr = CAR_AUT;        /* Carrier handling mode. */
  997.     int dfflow = FLO_NONE;        /* Default flow control is NONE */
  998.     int backgrd = 0;                    /* Assume in foreground (no '&' ) */
  999. #ifdef F_SETFL
  1000.     int iniflags = -1;            /* fcntl flags for ttyfd */
  1001. #endif /* F_SETFL */
  1002.     int fdflag = 0;            /* Flag for redirected stdio */
  1003.     int ttfdflg = 0;            /* Open File descriptor was given */
  1004.     int tvtflg = 0;            /* Flag that ttvt has been called */
  1005.     long ttspeed = -1L;            /* For saving speed */
  1006.     int ttflow = -9;            /* For saving flow */
  1007.     int ttld = -1;            /* Line discipline */
  1008.  
  1009. #ifdef sony_news
  1010.     static int km_con = -1;        /* Kanji mode for console tty */
  1011.     static int km_ext = -1;        /* Kanji mode for external device */
  1012. #endif /* sony_news */
  1013.  
  1014. #ifdef PARSENSE
  1015.     static int needpchk = 1;        /* Need parity check */
  1016. #else
  1017.     static int needpchk = 0;
  1018. #endif /* PARSENSE */
  1019.  
  1020. #ifdef HWPARITY
  1021. /*
  1022.   Unfortunately we must do this with global variables rather than through the
  1023.   tt...() APIs to avoid changing the APIs and the many modules that use them.
  1024.   If hwparity != 0, this indicates 8 data bits + parity, rather than 7 data
  1025.   bits + parity or 8 data bits and no parity, and overrides the regular parity
  1026.   variable, which is communicated to this module thru ttpkt(), and represented
  1027.   locally by the ttprty variable.
  1028. */
  1029.     extern int hwparity;        /* Hardware parity */
  1030.     extern int stopbits;        /* Stop bits */
  1031. #endif /* HWPARITY */
  1032.  
  1033. #ifdef TCPSOCKET
  1034. #ifdef TCP_NODELAY
  1035. static int nodelay_sav = -1;
  1036. #endif /* TCP_NODELAY */
  1037. #endif /* TCPSOCKET */
  1038.  
  1039. static int sigint_ign = 0;        /* SIGINT is ignored */
  1040.  
  1041. /*
  1042.   Having this module rely on external globals is bad, but fixing this
  1043.   requires overhaul of the ck*tio.c modules for all the different operating
  1044.   systems supported by C-Kermit.  Left for a future release.
  1045. */
  1046. extern int ttnproto;            /* Defined in ckcnet.c */
  1047. extern int ttnet;            /* Defined in ckcnet.c */
  1048. extern int nopush, xfrcan, xfrchr, xfrnum; /* Defined in ckcmai.c */
  1049. extern int suspend, wasclosed;
  1050. #ifdef IKSD
  1051. extern int inserver, local;
  1052. #endif /* IKSD */
  1053.  
  1054. extern int nettype;            /* defined in ckcmai.c */
  1055.  
  1056. int ckxech = 0; /* 0 if system normally echoes console characters, else 1 */
  1057.  
  1058. int ckmaxfiles = 0;            /* Max number of open files */
  1059.  
  1060. #ifdef CK_ENCRYPTION            /* Kerberos */
  1061. #include "ckuath.h"
  1062. extern int me_encrypt, u_encrypt;
  1063. #endif /* CK_ENCRYPTION */
  1064.  
  1065. /* Declarations of variables global within this module */
  1066.  
  1067. #ifdef TTLEBUF                /* See ckcnet.h */
  1068. int ttpush = -1;
  1069. #define LEBUFSIZ 4096
  1070. static CHAR le_buf[LEBUFSIZ];
  1071. static int le_start = 0, le_end = 0, le_data = 0;
  1072. #endif /* TTLEBUF */
  1073.  
  1074. static time_t tcount = (time_t)0;    /* Elapsed time counter */
  1075.  
  1076. static SIGTYP (*saval)()     = NULL;    /* For saving alarm() handler */
  1077. static SIGTYP (*savquit)()   = NULL;    /* and other signal handlers */
  1078. #ifdef SIGUSR1
  1079. static SIGTYP (*savusr1)()   = NULL;
  1080. #endif /* SIGUSR1 */
  1081. #ifdef SIGUSR2
  1082. static SIGTYP (*savusr2)()   = NULL;
  1083. #endif /* SIGUSR2 */
  1084. #ifdef SIGPIPE
  1085. static SIGTYP (*savpipe)()   = NULL;
  1086. #endif /* SIGPIPE */
  1087. #ifdef SIGDANGER
  1088. static SIGTYP (*savdanger)() = NULL;
  1089. #endif /* SIGDANGER */
  1090.  
  1091. #ifndef NOJC
  1092. static SIGTYP (*jchdlr)()    = NULL;    /* For checking suspend handler */
  1093. #endif /* NOJC */
  1094. static int jcshell = -1;        /* And flag for result */
  1095.  
  1096. /*
  1097.   BREAKNULS is defined for systems that simulate sending a BREAK signal
  1098.   by sending a bunch of NUL characters at low speed.
  1099. */
  1100. #ifdef PROVX1
  1101. #ifndef BREAKNULS
  1102. #define BREAKNULS
  1103. #endif /* BREAKNULS */
  1104. #endif /* PROVX1 */
  1105.  
  1106. #ifdef V7
  1107. #ifndef BREAKNULS
  1108. #define BREAKNULS
  1109. #endif /* BREAKNULS */
  1110. #endif /* V7 */
  1111.  
  1112. #ifdef BREAKNULS
  1113. static char                /* A string of nulls */
  1114. *brnuls = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
  1115. #endif /* BREAKNULS */
  1116.  
  1117. #ifdef CK_POSIX_SIG            /* Longjump buffers */
  1118. static sigjmp_buf sjbuf;        /* POSIX signal handling */
  1119. #else
  1120. static jmp_buf sjbuf;
  1121. #endif /* CK_POSIX_SIG */
  1122.  
  1123. #ifdef V7
  1124. static jmp_buf jjbuf;
  1125. #endif /* V7 */
  1126.  
  1127. /* static */                /* (Not static any more) */
  1128. int ttyfd = -1;                /* TTY file descriptor */
  1129.  
  1130. int ttpipe = 0;                /* NETCMD: Use pipe instead of ttyfd */
  1131. int ttpty  = 0;                         /* NETPTY: Use pty instead of ttfyd */
  1132.  
  1133. #ifdef NETCMD
  1134. static int pipe0[2], pipe1[2];        /* Pipes for net i/o */
  1135. static PID_T ttpid = 0;            /* Process ID for fork */
  1136. static int fdin, fdout;            /* File descriptors for pipe */
  1137. static FILE * ttout = NULL;        /* File pointer for output pipe */
  1138. #ifdef DCLFDOPEN
  1139. /* fdopen() needs declaring because it's not declared in <stdio.h> */
  1140. _PROTOTYP( FILE * fdopen, (int, char *) );
  1141. #endif /* DCLFDOPEN */
  1142. #endif /* NETCMD */
  1143.  
  1144. extern int pexitstat, quiet;
  1145.  
  1146. #ifdef Plan9
  1147. int ttyctlfd  = -1;   /* TTY control channel - What? UNIX doesn't have one? */
  1148. int consctlfd = -1;            /* Console control channel */
  1149. int noisefd = -1;            /* tone channel */
  1150. static int ttylastspeed = -1;        /* So we can lie about the speed */
  1151. #endif /* Plan9 */
  1152.  
  1153. int telnetfd = 0;            /* File descriptor is for telnet */
  1154. int x25fd = 0;                /* File descriptor is for X.25 */
  1155.  
  1156. char lockpid[16] = { '\0', '\0' };    /* PID stored in lockfile, as string */
  1157.  
  1158. static int lkf = 0,                     /* Line lock flag */
  1159.     cgmf = 0,                           /* Flag that console modes saved */
  1160.     xlocal = 0,                         /* Flag for tty local or remote */
  1161.     curcarr = 0;            /* Carrier mode: require/ignore. */
  1162.  
  1163. static int netconn = 0;            /* 1 if network connection active */
  1164.  
  1165. static char escchr;                     /* Escape or attn character */
  1166.  
  1167. #ifdef CK_SCO32V4
  1168. #include <sys/time.h>
  1169. #endif /* CK_SCO32V4 */
  1170.  
  1171. #ifdef HAVE_TV
  1172.     static struct timeval tv;        /* For getting time, from sys/time.h */
  1173. #endif /* HAVE_TV */
  1174. #ifdef HAVE_TZ
  1175.     static struct timezone tz;
  1176. #endif /* HAVE_TZ */
  1177.  
  1178. #ifdef OSF
  1179.     static struct timeb ftp;            /* And from sys/timeb.h */
  1180. #endif /* OSF */
  1181.  
  1182. #ifdef BSD29
  1183.     static long xclock;            /* For getting time from sys/time.h */
  1184.     static struct timeb ftp;            /* And from sys/timeb.h */
  1185. #endif /* BSD29 */
  1186.  
  1187. #ifdef BSD41
  1188.     static long xclock;            /* For getting time from sys/time.h */
  1189.     static struct timeb ftp;            /* And from sys/timeb.h */
  1190. #endif /* BSD41 */
  1191.  
  1192. #ifdef BELLV10
  1193.     static long xclock;            /* For getting time from sys/time.h */
  1194.     static struct timeb ftp;            /* And from sys/timeb.h */
  1195. #endif /* BELLV10 */
  1196.  
  1197. #ifdef FT21
  1198.     static long xclock;            /* For getting time from sys/time.h */
  1199.     static struct timeb ftp;            /* And from sys/timeb.h */
  1200. #endif /* FT21 */
  1201.  
  1202. #ifdef TOWER1
  1203.     static long xclock;            /* For getting time from sys/time.h */
  1204.     static struct timeb ftp;        /* And from sys/timeb.h */
  1205. #endif /* TOWER1 */
  1206.  
  1207. #ifdef COHERENT
  1208.     static long xclock;            /* For getting time from sys/time.h */
  1209.     static struct timeb ftp;        /* And from sys/timeb.h */
  1210. #endif /* COHERENT */
  1211.  
  1212. #ifdef V7
  1213.     static long xclock;
  1214. #endif /* V7 */
  1215.  
  1216. /* sgtty/termio information... */
  1217.  
  1218. #ifdef BSD44ORPOSIX            /* POSIX or BSD44 */
  1219.   static struct termios
  1220.     ttold, ttraw, tttvt, ttcur,
  1221.     ccold, ccraw, cccbrk;
  1222. #else                    /* BSD, V7, etc */
  1223.  
  1224. #ifdef COHERENT                /* Hack alert... */
  1225. #define ATTSV
  1226. #endif /* COHERENT */
  1227.  
  1228. #ifdef ATTSV
  1229.   static struct termio ttold = {0};    /* Init'd for word alignment, */
  1230.   static struct termio ttraw = {0};    /* which is important for some */
  1231.   static struct termio tttvt = {0};    /* systems, like Zilog... */
  1232.   static struct termio ttcur = {0};
  1233.   static struct termio ccold = {0};
  1234.   static struct termio ccraw = {0};
  1235.   static struct termio cccbrk = {0};
  1236. #else
  1237.   static struct sgttyb                  /* sgtty info... */
  1238.     ttold, ttraw, tttvt, ttcur,     /* for communication line */
  1239.     ccold, ccraw, cccbrk;        /* and for console */
  1240. #ifdef BELLV10
  1241.   static struct ttydevb            /* Device info... */
  1242.     tdold, tdcur;            /* for communication device */
  1243. #endif /* BELLV10 */
  1244. #ifdef TIOCGETC
  1245.   static struct tchars tchold, tchnoi;
  1246.  
  1247.   static int tcharf;
  1248. #endif /* TIOCGETC */
  1249. #ifdef TIOCGLTC
  1250.   static struct ltchars ltchold, ltchnoi;
  1251.   static int ltcharf;
  1252. #endif /* TIOCGLTC */
  1253.   int lmodef = 0;            /* Local modes */
  1254.   int lmode = 0;
  1255. #endif /* ATTSV */
  1256. #endif /* BSD44ORPOSIX */
  1257.  
  1258. #ifdef COMMENT
  1259. /* It picks up the speeds but they don't work */
  1260. #ifdef UNIXWARE                /* For higher serial speeds */
  1261. #ifdef UW7                /* in Unixware 7.0 */
  1262. #include <sys/asyc.h>            /* This picks up 57600 and 115200 */
  1263. #endif /* UW7 */
  1264. #endif /* UNIXWARE */
  1265. #endif /* COMMENT */
  1266.  
  1267. #ifdef PROVX1
  1268.   static struct sgttyb ttbuf;
  1269. #endif /* PROVX1 */
  1270.  
  1271. #ifdef ultrix
  1272. /* do we really need this? */
  1273.   static struct sgttyb vanilla;
  1274. #endif /* ultrix */
  1275.  
  1276. #ifdef ATT7300
  1277. static int attmodem = 0;                /* ATT7300 internal-modem status */
  1278. struct updata dialer = {0};        /* Condition dialer for data call */
  1279. #endif /* ATT7300 */
  1280.  
  1281. #ifndef NOUUCP
  1282. #define FLFNAML 128
  1283. #ifndef USETTYLOCK
  1284. #ifdef RTAIX
  1285. char lkflfn[128] = { '\0', '\0' };    /* and possible link to it */
  1286. #endif /* RTAIX */
  1287. char lock2[128] =  { '\0', '\0' };    /* Name of second lockfile */
  1288. #endif /* USETTYLOCK */
  1289. #else
  1290. #define FLFNAML 7
  1291. #endif /* NOUUCP */
  1292. char flfnam[FLFNAML+1] = { '\0', '\0' }; /* UUCP lock file path name */
  1293.  
  1294. int haslock = 0;            /* =1 if this kermit locked uucp */
  1295.  
  1296. #ifndef OXOS
  1297. #ifdef SVORPOSIX
  1298. static int conesc = 0;                  /* set to 1 if esc char (^\) typed */
  1299. #else
  1300. #ifdef V7
  1301. static int conesc = 0;
  1302. #else
  1303. #ifdef C70
  1304. static int conesc = 0;
  1305. #endif /* C70 */
  1306. #endif /* V7 */
  1307. #endif /* SVORPOSIX */
  1308. #endif /* OXOS */
  1309.  
  1310. static char ttnmsv[DEVNAMLEN+1];    /* Local copy of comm device name */
  1311. #ifdef USETTYLOCK
  1312. static char lockname[DEVNAMLEN+1];    /* Ditto, the part after "/dev/". */
  1313. #endif /* USETTYLOCK */
  1314.  
  1315. #ifdef aegis
  1316. static status_$t st;                    /* error status return value */
  1317. static short concrp = 0;                /* true if console is CRP pad */
  1318. #define CONBUFSIZ 10
  1319. static char conbuf[CONBUFSIZ];          /* console readahead buffer */
  1320. static int  conbufn = 0;                /* # chars in readahead buffer */
  1321. static char *conbufp;                   /* next char in readahead buffer */
  1322. static uid_$t ttyuid;                   /* tty type uid */
  1323. static uid_$t conuid;                   /* stdout type uid */
  1324.  
  1325. /* APOLLO Aegis main()
  1326.  * establish acl usage and cleanup handling
  1327.  *    this makes sure that CRP pads
  1328.  *    get restored to a usable mode
  1329.  */
  1330. main(argc,argv) int argc; char **argv; {
  1331.         status_$t status;
  1332.         pfm_$cleanup_rec dirty;
  1333.  
  1334.         PID_T pid = getpid();
  1335.  
  1336.         /* acl usage according to invoking environment */
  1337.         default_acl(USE_DEFENV);
  1338.  
  1339.         /* establish a cleanup continuation */
  1340.         status = pfm_$cleanup(dirty);
  1341.         if (status.all != pfm_$cleanup_set) {
  1342.                 /* only handle faults for the original process */
  1343.                 if (pid == getpid() && status.all > pgm_$max_severity) {
  1344.             /* blew up in main process */
  1345.             status_$t quo;
  1346.             pfm_$cleanup_rec clean;
  1347.  
  1348.             /* restore the console in any case */
  1349.             conres();
  1350.  
  1351.             /* attempt a clean exit */
  1352.             debug(F101, "cleanup fault status", "", status.all);
  1353.  
  1354.             /* doexit(), then send status to continuation */
  1355.             quo = pfm_$cleanup(clean);
  1356.             if (quo.all == pfm_$cleanup_set)
  1357.               doexit(pgm_$program_faulted,-1);
  1358.             else if (quo.all > pgm_$max_severity)
  1359.               pfm_$signal(quo); /* blew up in doexit() */
  1360.                 }
  1361.                 /* send to the original continuation */
  1362.                 pfm_$signal(status);
  1363.                 /*NOTREACHED*/
  1364.         }
  1365.         return(ckcmai(argc, argv));
  1366. }
  1367. #endif /* aegis */
  1368.  
  1369. /* ANSI-style prototypes for internal functions. */
  1370. /* Functions used outside this module are prototyped in ckcker.h. */
  1371.  
  1372. #ifdef apollo
  1373. _PROTOTYP( SIGTYP timerh, () );
  1374. _PROTOTYP( SIGTYP cctrap, () );
  1375. _PROTOTYP( SIGTYP esctrp, () );
  1376. _PROTOTYP( SIGTYP sig_ign, () );
  1377. #else
  1378. _PROTOTYP( SIGTYP timerh, (int) );
  1379. _PROTOTYP( SIGTYP cctrap, (int) );
  1380. _PROTOTYP( SIGTYP esctrp, (int) );
  1381. #endif /* apollo */
  1382. _PROTOTYP( int do_open, (char *) );
  1383. _PROTOTYP( static int in_chk, (int, int) );
  1384. _PROTOTYP( static int ttrpid, (char *) );
  1385. _PROTOTYP( static int ttchkpid, (char *) );
  1386. _PROTOTYP( static int ttlock, (char *) );
  1387. _PROTOTYP( static int ttunlck, (void) );
  1388. _PROTOTYP( int mygetbuf, (void) );
  1389. _PROTOTYP( int myfillbuf, (void) );
  1390. _PROTOTYP( VOID conbgt, (int) );
  1391. #ifdef ACUCNTRL
  1392. _PROTOTYP( VOID acucntrl, (char *, char *) );
  1393. #endif /* ACUCNTRL */
  1394.  
  1395. #ifdef BSD44ORPOSIX
  1396. _PROTOTYP( int carrctl, (struct termios *, int) );
  1397. #else
  1398. #ifdef ATTSV
  1399. _PROTOTYP( int carrctl, (struct termio *, int) );
  1400. #else
  1401. _PROTOTYP( int carrctl, (struct sgttyb *, int) );
  1402. #endif /* ATTSV */
  1403. #endif /* BSD44ORPOSIX */
  1404.  
  1405. #ifdef ATT7300
  1406. _PROTOTYP( int attdial, (char *, long, char *) );
  1407. _PROTOTYP( int offgetty, (char *) );
  1408. _PROTOTYP( int ongetty, (char *) );
  1409. #endif /* ATT7300 */
  1410.  
  1411. #ifdef BEBOX
  1412. #ifdef SELECT
  1413.     /* BeOS is not capable of using SELECT on anything but sockets */
  1414. #undef SELECT
  1415. #endif /* SELECT */
  1416. #include <kernel/OS.h>
  1417. #ifdef BE_DR_7
  1418. static double time_started = 0.0;
  1419. struct ALARM_STRUCT {
  1420.     thread_id thread;
  1421.     int time;
  1422. };
  1423. static thread_id alarm_thread = -1;
  1424. static struct ALARM_STRUCT alarm_struct;
  1425. _PROTOTYP( long do_alarm, (void *) );
  1426. _PROTOTYP( unsigned int alarm, (unsigned int) );
  1427. _PROTOTYP( void alarm_expired, (void) );
  1428. #endif /* BE_DR_7 */
  1429. #endif /* BEBOX */
  1430.  
  1431. #ifndef xunchar
  1432. #define xunchar(ch) (((ch) - 32 ) & 0xFF )    /* Character to number */
  1433. #endif /* xunchar */
  1434.  
  1435. #ifdef CK_ANSIC
  1436. static char *
  1437. xxlast(char *s, char c)
  1438. #else
  1439. static char *
  1440. xxlast(s,c) char *s; char c;
  1441. #endif /* CK_ANSIC */
  1442. /* xxlast */ {        /*  Last occurrence of character c in string s. */
  1443.     int i;
  1444.     for (i = (int)strlen(s); i > 0; i--)
  1445.       if (s[i-1] == c ) return(s + (i - 1));
  1446.     return(NULL);
  1447. }
  1448.  
  1449. /* Timeout handler for communication line input functions */
  1450.  
  1451. SIGTYP
  1452. timerh(foo) int foo; {
  1453.     ttimoff();
  1454. #ifdef BEBOX
  1455. #ifdef BE_DR_7
  1456.     alarm_expired();
  1457. #endif /* BE_DR_7 */
  1458. #endif /* BEBOX */
  1459. #ifdef CK_POSIX_SIG
  1460.     siglongjmp(sjbuf,1);
  1461. #else
  1462.     longjmp(sjbuf,1);
  1463. #endif /* CK_POSIX_SIG */
  1464. }
  1465.  
  1466. SIGTYP
  1467. xtimerh(foo) int foo; {            /* Like timerh() but does */
  1468. #ifdef BEBOX                /* not reset the itslef */
  1469. #ifdef BE_DR_7
  1470.     alarm_expired();
  1471. #endif /* BE_DR_7 */
  1472. #endif /* BEBOX */
  1473. #ifdef CK_POSIX_SIG
  1474.     siglongjmp(sjbuf,1);
  1475. #else
  1476.     longjmp(sjbuf,1);
  1477. #endif /* CK_POSIX_SIG */
  1478. }
  1479.  
  1480.  
  1481. /* Control-C trap for communication line input functions */
  1482.  
  1483. int cc_int;                /* Flag */
  1484. SIGTYP (* occt)();            /* For saving old SIGINT handler */
  1485.  
  1486. SIGTYP
  1487. cctrap(foo) int foo; {            /* Needs arg for ANSI C */
  1488.   cc_int = 1;                /* signal() prototype. */
  1489.   return;
  1490. }
  1491.  
  1492. /*  S Y S I N I T  --  System-dependent program initialization.  */
  1493.  
  1494. /*
  1495.  * ttgwsiz() returns:
  1496.  *    1    tt_rows and tt_cols are known, both altered, both > 0
  1497.  *    0    tt_rows and/or tt_cols are known, both altered, one or both <= 0
  1498.  *    -1   tt_rows and tt_cols are unknown and unaltered
  1499.  */
  1500.  
  1501. #ifndef NONAWS
  1502. extern int tt_rows, tt_cols;
  1503. #endif /* NONAWS */
  1504.  
  1505. static int
  1506. xttgwsiz() {
  1507.     char *p;
  1508.     int rows = 0, cols = 0;
  1509.     p = getenv("LINES");
  1510.     debug(F110,"xttgwsiz LINES",p,0);
  1511.     if (p) {
  1512.     rows = atol(p);
  1513.     if (rows > 0) {
  1514.         p = getenv("COLUMNS");
  1515.         debug(F110,"xttgwsiz COLUMNS",p,0);
  1516.         if (p) {
  1517.         cols = atol(p);
  1518.         if (cols > 0) {
  1519.             tt_rows = rows;
  1520.             tt_cols = cols;
  1521.             return(1);
  1522.         }
  1523.         return(0);
  1524.         }
  1525.     }
  1526.     }
  1527.     return(-1);
  1528. }
  1529.  
  1530. #ifdef TTLEBUF
  1531. VOID
  1532. le_init() {                /* LocalEchoInit() */
  1533.     int i;
  1534.     for (i = 0; i < LEBUFSIZ; i++)
  1535.       le_buf[i] = '\0';
  1536.     le_start = 0;
  1537.     le_end = 0;
  1538.     le_data = 0;
  1539. }
  1540.  
  1541. VOID
  1542. le_clean() {                /* LocalEchoCleanup() */
  1543.     le_init();
  1544.     return;
  1545. }
  1546.  
  1547. int
  1548. le_inbuf() {
  1549.     int rc = 0;
  1550.     if (le_start != le_end) {
  1551.     rc = (le_end -
  1552.           le_start +
  1553.           LEBUFSIZ) % LEBUFSIZ;
  1554.     }
  1555.     debug(F111,"le_inbuf","chars waiting",rc);
  1556.     return(rc);
  1557. }
  1558.  
  1559. int
  1560. #ifdef CK_ANSIC
  1561. le_putchar(CHAR ch)
  1562. #else
  1563. le_putchar(ch) CHAR ch;
  1564. #endif /* CK_ANSIC */
  1565. /* le_putchar */ {
  1566. #ifdef COMMENT
  1567.     /* In UNIX we do not have another thread taking chars out of the buffer */
  1568.     while ((le_start - le_end == 1) ||
  1569.             (le_start == 0 && le_end == LEBUFSIZ - 1)) {
  1570.     /* Buffer is full */
  1571.         debug(F111,"le_putchar","Buffer is Full",ch);
  1572.         ReleaseLocalEchoMutex() ;
  1573.         msleep(250);
  1574.         RequestLocalEchoMutex( SEM_INDEFINITE_WAIT ) ;
  1575.     }
  1576. #else
  1577.     if ((le_start - le_end + LEBUFSIZ)%LEBUFSIZ == 1) {
  1578.         debug(F110,"le_putchar","buffer is full",0);
  1579.         return(-1);
  1580.     }
  1581. #endif /* COMMENT */
  1582.     le_buf[le_end++] = ch;
  1583.     if (le_end == LEBUFSIZ)
  1584.       le_end = 0;
  1585.     le_data = 1;
  1586.     return(0);
  1587. }
  1588.  
  1589. int
  1590. #ifdef CK_ANSIC
  1591. le_puts(CHAR * s, int n)
  1592. #else
  1593. le_puts(s,n) CHAR * s; int n;
  1594. #endif /* CK_ANSIC */
  1595. /* le_puts */ {
  1596.     int rc = 0;
  1597.     int i = 0;
  1598.     CHAR * p = (CHAR *)"le_puts";
  1599.     hexdump(p,s,n);
  1600.     for (i = 0; i < n; i++)
  1601.       rc = le_putchar((char)s[i]);
  1602.     debug(F101,"le_puts","",rc);
  1603.     return(rc);
  1604. }
  1605.  
  1606. int
  1607. #ifdef CK_ANSIC
  1608. le_putstr(CHAR * s)
  1609. #else
  1610. le_putstr(s) CHAR * s;
  1611. #endif /* CK_ANSIC */
  1612. /* le_puts */ {
  1613.     CHAR * p;
  1614.     int rc = 0;
  1615.     p = (CHAR *)"le_putstr";
  1616.     hexdump(p,s,(int)strlen((char *)s));
  1617.     for (p = s; *p && !rc; p++)
  1618.       rc = le_putchar(*p);
  1619.     return(rc);
  1620. }
  1621.  
  1622. int
  1623. #ifdef CK_ANSIC
  1624. le_getchar(CHAR * pch)
  1625. #else /* CK_ANSIC */
  1626. le_getchar(pch) CHAR * pch;
  1627. #endif /* CK_ANSIC */
  1628. /* le_gatchar */ {
  1629.     int rc = 0;
  1630.     if (le_start != le_end) {
  1631.         *pch = le_buf[le_start];
  1632.         le_buf[le_start] = 0;
  1633.         le_start++;
  1634.  
  1635.         if (le_start == LEBUFSIZ)
  1636.           le_start = 0;
  1637.  
  1638.         if (le_start == le_end) {
  1639.             le_data = 0;
  1640.         }
  1641.         rc++;
  1642.     } else {
  1643.         *pch = 0;
  1644.     }
  1645.     return(rc);
  1646. }
  1647. #endif /* TTLEBUF */
  1648.  
  1649. #ifdef COMMENT
  1650. /*
  1651.   Some systems like OSF/1 use TIOCGSIZE instead of TIOCGWINSZ.
  1652.   But as far as I know, whenever TIOCGSIZE is defined, it is
  1653.   equated to TIOCGWINSZ.  For cases where this is not done, try this:
  1654. */
  1655. #ifndef TIOCGWINSZ
  1656. #ifdef TIOCGSIZE
  1657. #define TIOCGWINSZ TIOCGSIZE
  1658. #endif /* TIOCGSIZE */
  1659. #endif /* TIOCGWINSZ */
  1660. #endif /* COMMENT */
  1661.  
  1662. int
  1663. ttgwsiz() {
  1664.     int x = 0;
  1665. #ifndef NONAWS
  1666. #ifdef QNX
  1667. /*
  1668.   NOTE: TIOCGWSIZ works here too, but only in the 32-bit version.
  1669.   This code works for both the 16- and 32-bit versions.
  1670. */
  1671.     extern int dev_size(int, int, int, int *, int *);
  1672.     int r, c;
  1673.  
  1674.     if (dev_size(0, -1, -1, &r, &c) == 0) {
  1675.     debug(F101,"ttgwsiz QNX r","",r);
  1676.     debug(F101,"ttgwsiz QNX c","",c);
  1677.     tt_rows = r;
  1678.     tt_cols = c;
  1679.     return ((r > 0 && c > 0) ? 1 : 0);
  1680.     } else return(xttgwsiz());
  1681. #else /* QNX */
  1682. #ifdef TIOCGWINSZ
  1683.  
  1684. /* Note, this was M_UNIX, changed to XENIX to allow cross compilation... */
  1685. #ifdef XENIX                /* SCO UNIX 3.2v4.0 */
  1686. #include <sys/stream.h>            /* typedef mblk_t needed by ptem.h */
  1687. #include <sys/ptem.h>            /* for ttgwsiz() */
  1688. #endif /* XENIX */
  1689.  
  1690. #ifdef I386IX                /* Ditto for Interactive */
  1691. #include <sys/stream.h>
  1692. #include <sys/ptem.h>
  1693. #endif /* I386IX */
  1694.  
  1695. /* Note, the above might be needed for some other older SVR3 Intel makes... */
  1696.  
  1697.     struct winsize w;
  1698. #ifdef IKSD
  1699.     if (inserver)
  1700.       return(xttgwsiz());
  1701. #endif /* IKSD */
  1702.     x = ioctl(0, (int)TIOCGWINSZ, (char *)&w);
  1703.     debug(F101,"ttgwsiz TIOCGWINSZ","",x);
  1704.     if (x < 0) {
  1705.     return(xttgwsiz());
  1706.     } else if (w.ws_row > 0 && w.ws_col > 0) {
  1707.     tt_rows = w.ws_row;
  1708.     tt_cols = w.ws_col;
  1709.     debug(F101,"ttgwsiz tt_rows","",tt_rows);
  1710.     debug(F101,"ttgwsiz tt_cols","",tt_cols);
  1711.     return(1);
  1712.     } else {
  1713.     debug(F100,"ttgwsiz TIOCGWINSZ 00","",0);
  1714.     return(xttgwsiz());
  1715.     }
  1716. #else
  1717.     return(xttgwsiz());
  1718. #endif /* TIOCGWINSZ */
  1719. #endif /* QNX */
  1720. #endif /* NONAWS */
  1721. }
  1722.  
  1723. SIGTYP
  1724. sighup(foo) int foo; {            /* SIGHUP handler */
  1725.     backgrd = 1;
  1726.     debug(F100,"***************","",0);
  1727.     debug(F100,"SIGHUP received","",0);
  1728.     debug(F100,"***************","",0);
  1729.     doexit(BAD_EXIT,-1);
  1730.     /*NOTREACHED*/
  1731.     SIGRETURN;                /* Shut picky compilers up... */
  1732. }
  1733.  
  1734. #ifdef CK_SCO32V4
  1735. /* Exists but there is no prototype in the header files */
  1736. _PROTOTYP( char * ttyname, (int) );
  1737. #else
  1738. #ifdef SV68R3V6
  1739. _PROTOTYP( char * ttyname, (int) );
  1740. #else
  1741. #ifdef ultrix
  1742. _PROTOTYP( char * ttyname, (int) );
  1743. #else
  1744. #ifdef HPUX6
  1745. _PROTOTYP( char * ttyname, (int) );
  1746. #else
  1747. #ifdef HPUX5
  1748. _PROTOTYP( char * ttyname, (int) );
  1749. #else
  1750. #ifdef PS2AIX10
  1751. _PROTOTYP( char * ttyname, (int) );
  1752. #endif /* PS2AIX10 */
  1753. #endif /* HPUX5 */
  1754. #endif /* HPUX6 */
  1755. #endif /* ultrix */
  1756. #endif /* SV68R3V6 */
  1757. #endif /* CK_SCO32V4 */
  1758.  
  1759. #ifndef SIGUSR1                /* User-defined signals */
  1760. #define SIGUSR1 30
  1761. #endif /* SIGUSR1 */
  1762.  
  1763. #ifndef SIGUSR2
  1764. #define SIGUSR2 31
  1765. #endif /* SIGUSR2 */
  1766.  
  1767. /*
  1768.   ignorsigs() sets certain signals to SIG_IGN.  But when a signal is
  1769.   ignored, it remains ignored across exec(), so we have to restore these
  1770.   signals before exec(), which is the purpose of restorsigs().
  1771. */
  1772. static VOID
  1773. ignorsigs() {                /* Ignore these signals */
  1774.     savquit = signal(SIGQUIT,SIG_IGN);    /* Ignore Quit signal */
  1775.  
  1776. #ifdef SIGDANGER            /* Ignore danger signals */
  1777. /*
  1778.   This signal is sent when the system is low on swap space.  Processes
  1779.   that don't handle it are candidates for termination.  If swap space doesn't
  1780.   clear out enough, we still might be terminated via kill() -- nothing we can
  1781.   do about that!  Conceivably, this could be improved by installing a real
  1782.   signal handler that warns the user, but that would be pretty complicated,
  1783.   since we are not always in control of the screen -- e.g. during remote-mode
  1784.   file transfer.
  1785. */
  1786.     savdanger = signal(SIGDANGER,SIG_IGN); /* e.g. in AIX */
  1787. #endif /* SIGDANGER */
  1788. #ifdef SIGPIPE
  1789. /*
  1790.   This one comes when a TCP/IP connection is broken by the remote.
  1791.   We prefer to catch this situation by examining error codes from write().
  1792. */
  1793.     savpipe = signal(SIGPIPE,SIG_IGN);
  1794. #endif /* SIGPIPE */
  1795.     savusr1 = signal(SIGUSR1,SIG_IGN);    /* Ignore user-defined signals */
  1796.     savusr2 = signal(SIGUSR2,SIG_IGN);
  1797. }
  1798.  
  1799. VOID
  1800. restorsigs() {                /* Restore these signals */
  1801.     (VOID) signal(SIGQUIT,savquit);    /* (used in ckufio.c) */
  1802. #ifdef SIGDANGER
  1803.     (VOID) signal(SIGDANGER,savdanger);
  1804. #endif /* SIGDANGER */
  1805. #ifdef SIGPIPE
  1806.     (VOID) signal(SIGPIPE,savpipe);
  1807. #endif /* SIGPIPE */
  1808.     (VOID) signal(SIGUSR1,savusr1);
  1809.     (VOID) signal(SIGUSR2,savusr2);
  1810. }
  1811.  
  1812. int
  1813. sysinit() {
  1814.     int x;
  1815.     char * s;
  1816. #ifdef CK_UTSNAME
  1817.     struct utsname name;
  1818. #endif /* CK_UTSNAME */
  1819.  
  1820.     extern char startupdir[];
  1821. /*
  1822.   BEFORE ANYTHING ELSE: Initialize the setuid package.
  1823.   Change to the user's real user and group ID.
  1824.   If this can't be done, don't run at all.
  1825. */
  1826.     debug(F100,"sysinit calling priv_ini","",0);
  1827.     if (x = priv_ini()) {
  1828.     if (x & 1) fprintf(stderr,"Fatal: setuid failure.\n");
  1829.     if (x & 2) fprintf(stderr,"Fatal: setgid failure.\n");
  1830.     if (x & 4) fprintf(stderr,"Fatal: C-Kermit setuid to root!\n");
  1831.     exit(1);
  1832.     }
  1833.     signal(SIGINT,SIG_IGN);        /* Ignore interrupts at first */
  1834.     signal(SIGHUP,sighup);        /* Catch SIGHUP */
  1835.  
  1836. #ifndef NOJC
  1837. /*
  1838.   Get the initial job control state.
  1839.   If it is SIG_IGN, that means the shell does not support job control,
  1840.   and so we'd better not suspend ourselves.
  1841. */
  1842. #ifdef SIGTSTP
  1843.     jchdlr = signal(SIGTSTP,SIG_IGN);
  1844.     if (jchdlr == SIG_IGN) {
  1845.     jcshell = 0;
  1846.     debug(F100,"sysinit jchdlr: SIG_IGN","",0);
  1847.     } else if (jchdlr == SIG_DFL) {
  1848.     debug(F100,"sysinit jchdlr: SIG_DFL","",0);
  1849.     jcshell = 1;
  1850.     } else {
  1851.     debug(F100,"sysinit jchdlr: other","",0);
  1852.     jcshell = 3;
  1853.     }
  1854.     (VOID) signal(SIGTSTP,jchdlr);    /* Put it back... */
  1855. #endif /* SIGTSTP */
  1856. #endif /* NOJC */
  1857.  
  1858.     conbgt(0);                /* See if we're in the background */
  1859.     congm();                /* Get console modes */
  1860.  
  1861.     (VOID) signal(SIGALRM,SIG_IGN);    /* Ignore alarms */
  1862.  
  1863.     ignorsigs();            /* Ignore some other signals */
  1864.  
  1865. #ifdef F_SETFL
  1866.     iniflags = fcntl(0,F_GETFL,0);    /* Get stdin flags */
  1867. #endif /* F_SETFL */
  1868.  
  1869. #ifdef ultrix
  1870.     gtty(0,&vanilla);            /* Get sgtty info */
  1871. #else
  1872. #ifdef AUX
  1873.     set42sig();                /* Don't ask! (hakanson@cs.orst.edu) */
  1874. #endif /* AUX */
  1875. #endif /* ultrix */
  1876. /*
  1877.   Warning: on some UNIX systems (SVR4?), ttyname() reportedly opens /dev but
  1878.   never closes it.  If it is called often enough, we run out of file
  1879.   descriptors and subsequent open()'s of other devices or files can fail.
  1880. */
  1881.     s = NULL;
  1882. #ifndef MINIX
  1883.     if (isatty(0))            /* Name of controlling terminal */
  1884.       s = ttyname(0);
  1885.     else if (isatty(1))
  1886.       s = ttyname(1);
  1887.     else if (isatty(2))
  1888.       s = ttyname(2);
  1889.     debug(F110,"sysinit ttyname(0)",s,0);
  1890. #endif /* MINIX */
  1891.     if (s)
  1892.       ckstrncpy((char *)cttnam,s,DEVNAMLEN+1);
  1893. #ifdef SVORPOSIX
  1894.     if (!cttnam[0])
  1895.       ctermid(cttnam);
  1896. #endif /* SVORPOSIX */
  1897.     if (!cttnam[0])
  1898.       ckstrncpy((char *)cttnam,dftty,DEVNAMLEN+1);
  1899.     debug(F110,"sysinit CTTNAM",CTTNAM,0);
  1900.     debug(F110,"sysinit cttnam",cttnam,0);
  1901.  
  1902.     ttgwsiz();                /* Get window (screen) dimensions. */
  1903.  
  1904. #ifdef _SC_OPEN_MAX
  1905.     ckmaxfiles = sysconf(_SC_OPEN_MAX);
  1906. #endif /* _SC_OPEN_MAX */
  1907.  
  1908. #ifdef Plan9
  1909.     if (!backgrd) {
  1910.         consctlfd = open("/dev/consctl", O_WRONLY);
  1911.         /*noisefd = open("/dev/noise", O_WRONLY)*/
  1912.     }
  1913.     ckxech = 1;
  1914. #endif /* Plan9 */
  1915.  
  1916. #ifdef CK_UTSNAME
  1917.     if (uname(&name) > -1) {
  1918.     ckstrncpy(unm_mch,name.machine,CK_SYSNMLN);
  1919.     ckstrncpy(unm_nam,name.sysname,CK_SYSNMLN);
  1920.     ckstrncpy(unm_rel,name.release,CK_SYSNMLN);
  1921.     ckstrncpy(unm_ver,name.version,CK_SYSNMLN);
  1922. #ifdef DEBUG
  1923.     if (deblog) {
  1924.         debug(F110,"sysinit uname machine",unm_mch,0);
  1925.         debug(F110,"sysinit uname sysname",unm_nam,0);
  1926.         debug(F110,"sysinit uname release",unm_rel,0);
  1927.         debug(F110,"sysinit uname version",unm_ver,0);
  1928.     }
  1929. #endif /* DEBUG */
  1930.  
  1931. #ifdef HPUX9PLUS
  1932.     if (name.machine[5] == '8')
  1933.       hpis800 = 1;
  1934.     else
  1935.       hpis800 = 0;
  1936.     debug(F101,"sysinit hpis800","",hpis800);
  1937. #endif /* HPUX9PLUS */
  1938.     }
  1939. #endif /* CK_UTSNAME */
  1940.  
  1941. #ifdef CK_ENVIRONMENT
  1942.     {
  1943.     extern char tn_env_acct[], tn_env_disp[], tn_env_job[],
  1944.     tn_env_prnt[], tn_env_sys[], uidbuf[];
  1945.         extern char * whoami();
  1946.     char *p;
  1947. #ifdef CKSENDUID
  1948.         uidbuf[0] = '\0';
  1949. #ifdef IKSD
  1950.         if (!inserver) {
  1951. #endif /* IKSD */
  1952.             p = getenv("USER");
  1953.             debug(F110,"sysinit uidbuf from USER",uidbuf,0);
  1954.             if (!p) {
  1955.                 p = getenv("LOGNAME");
  1956.                 debug(F110,"sysinit uidbuf from LOGNAME",uidbuf,0);
  1957.             }
  1958.             if (!p) {
  1959.                 p = whoami();
  1960.                 debug(F110,"sysinit uidbuf from whoami()",uidbuf,0);
  1961.             }
  1962.             if (p)
  1963.           ckstrncpy(uidbuf,p,UIDBUFLEN);
  1964. #ifdef IKSD
  1965.         }
  1966. #endif /* IKSD */
  1967.     debug(F110,"sysinit final uidbuf",uidbuf,0);
  1968. #endif /* CKSENDUID */
  1969.  
  1970.     if (p = getenv("JOB")) ckstrncpy(tn_env_job,p,63);
  1971.     if (p = getenv("ACCT")) ckstrncpy(tn_env_acct,p,63);
  1972.     if (p = getenv("PRINTER")) ckstrncpy(tn_env_prnt,p,63);
  1973.     if (p = getenv("DISPLAY")) ckstrncpy(tn_env_disp,p,63);
  1974. #ifdef aegis
  1975.     strcpy(tn_env_sys,"Aegis");
  1976. #else
  1977. #ifdef Plan9
  1978.     strcpy(tn_env_sys,"Plan9");
  1979. #else
  1980.     strcpy(tn_env_sys,"UNIX");
  1981. #endif /* Plan9 */
  1982. #endif /* aegis */
  1983.     }
  1984. #endif /* CK_ENVIRONMENT */
  1985. #ifdef CK_SNDLOC
  1986.     {
  1987.     extern char * tn_loc;
  1988.     char *p;
  1989.     if (p = getenv("LOCATION"))
  1990.       if (tn_loc = (char *)malloc((int)strlen(p)+1))
  1991.         strcpy(tn_loc,p);
  1992.     }
  1993. #endif /* CK_SNDLOC */
  1994.  
  1995.     ckstrncpy(startupdir, zgtdir(), CKMAXPATH);
  1996.     startupdir[CKMAXPATH] = '\0';
  1997.     x = strlen(startupdir);
  1998.     if (x <= 0) {
  1999.     startupdir[0] = '/';
  2000.     startupdir[1] = '\0';
  2001.     } else if (startupdir[x-1] != '/') {
  2002.     startupdir[x] = '/';
  2003.     startupdir[x+1] = '\0';
  2004.     }
  2005.     debug(F110,"sysinit startupdir",startupdir,0);
  2006. #ifdef TTLEBUF
  2007.     le_init();
  2008. #endif /* TTLEBUF */
  2009.     return(0);
  2010. }
  2011.  
  2012. /*  S Y S C L E A N U P  --  System-dependent program cleanup.  */
  2013.  
  2014. int
  2015. syscleanup() {
  2016. #ifdef F_SETFL
  2017.     if (iniflags > -1)
  2018.       fcntl(0,F_SETFL,iniflags);    /* Restore stdin flags */
  2019. #endif /* F_SETFL */
  2020. #ifdef ultrix
  2021.     stty(0,&vanilla);                   /* Get sgtty info */
  2022. #endif /* ultrix */
  2023. #ifdef NETCMD
  2024.     if (ttpid) kill(ttpid,9);
  2025. #endif /* NETCMD */
  2026.     return(0);
  2027. }
  2028.  
  2029. /*  T T O P E N  --  Open a tty for exclusive access.  */
  2030.  
  2031. /*
  2032.   Call with:
  2033.     ttname: character string - device name or network host name.
  2034.     lcl:
  2035.   If called with lcl < 0, sets value of lcl as follows:
  2036.   0: the terminal named by ttname is the job's controlling terminal.
  2037.   1: the terminal named by ttname is not the job's controlling terminal.
  2038.   But watch out: if a line is already open, or if requested line can't
  2039.   be opened, then lcl remains (and is returned as) -1.
  2040.     modem:
  2041.   Less than zero: ttname is a network host name.
  2042.   Zero or greater: ttname is a terminal device name.
  2043.   Zero means a local connection (don't use modem signals).
  2044.   Positive means use modem signals.
  2045.    timo:
  2046.   0 = no timer.
  2047.   nonzero = number of seconds to wait for open() to return before timing out.
  2048.  
  2049.   Returns:
  2050.     0 on success
  2051.    -5 if device is in use
  2052.    -4 if access to device is denied
  2053.    -3 if access to lock directory denied
  2054.    -2 upon timeout waiting for device to open
  2055.    -1 on other error
  2056. */
  2057. static int ttotmo = 0;            /* Timeout flag */
  2058. /* Flag kept here to avoid being clobbered by longjmp.  */
  2059.  
  2060. int
  2061. ttopen(ttname,lcl,modem,timo) char *ttname; int *lcl, modem, timo; {
  2062.  
  2063. #ifdef BSD44
  2064. #define ctermid(x) strcpy(x,"")
  2065. #else
  2066. #ifdef SVORPOSIX
  2067. #ifndef CIE
  2068.     extern char *ctermid();        /* Wish they all had this! */
  2069. #else                    /* CIE Regulus */
  2070. #define ctermid(x) strcpy(x,"")
  2071. #endif /* CIE */
  2072. #endif /* SVORPOSIX */
  2073. #endif /* BSD44 */
  2074.  
  2075. #ifdef ultrix
  2076.     int temp = 0;
  2077. #endif /* ultrix */
  2078.  
  2079.     char *x;                /* Worker string pointer */
  2080.     int y;
  2081.  
  2082. #ifndef pdp11
  2083. #define NAMEFD     /* Feature to allow name to be an open file descriptor */
  2084. #endif /* pdp11 */
  2085.  
  2086. #ifdef NAMEFD
  2087.     char *p;
  2088.     debug(F101,"ttopen telnetfd","",telnetfd);
  2089. #endif /* NAMEFD */
  2090.  
  2091.     debug(F111,"ttopen entry modem",ttname,modem);
  2092.     debug(F101," ttyfd","",ttyfd);
  2093.     debug(F101," lcl","",*lcl);
  2094.  
  2095. #ifdef MAXNAMLEN
  2096.     debug(F100,"ttopen MAXNAMLEN defined","",0);
  2097. #else
  2098.     debug(F100,"ttopen MAXNAMLEN *NOT* defined","",0);
  2099. #endif
  2100.  
  2101. #ifdef BSD4
  2102.     debug(F100,"ttopen BSD4 defined","",0);
  2103. #else
  2104.     debug(F100,"ttopen BSD4 *NOT* defined","",0);
  2105. #endif /* BSD4 */
  2106.  
  2107. #ifdef BSD42
  2108.     debug(F100,"ttopen BSD42 defined","",0);
  2109. #else
  2110.     debug(F100,"ttopen BSD42 *NOT* defined","",0);
  2111. #endif /* BSD42 */
  2112.  
  2113. #ifdef MYREAD
  2114.     debug(F100,"ttopen MYREAD defined","",0);
  2115. #else
  2116.     debug(F100,"ttopen MYREAD *NOT* defined","",0);
  2117. #endif /* MYREAD */
  2118.  
  2119.     ttpmsk = 0xff;
  2120.     lockpid[0] = '\0';
  2121.  
  2122.     if (ttyfd > -1) {            /* if device already opened */
  2123.     debug(F110,"ttopen ttname",ttname,0);
  2124.     debug(F110,"ttopen ttnmsv",ttnmsv,0);
  2125.         if (strncmp(ttname,ttnmsv,DEVNAMLEN)) /* are new & old names equal? */
  2126.           ttclos(ttyfd);        /* no, close old ttname, open new */
  2127.         else                 /* else same, ignore this call, */
  2128.       return(0);            /* and return. */
  2129.     }
  2130.     wasclosed = 0;
  2131.     ttpipe = 0;                /* Assume it's not a pipe */
  2132.     ttpty = 0;
  2133.  
  2134. #ifdef    NETCONN
  2135.     if (modem < 0) {            /* modem < 0 = special code for net */
  2136.     int x;
  2137.     ttmdm = modem;
  2138.     modem = -modem;            /* Positive network type number */
  2139.     fdflag = 0;            /* Stdio not redirected. */
  2140.     netconn = 1;            /* And it's a network connection */
  2141.     debug(F111,"ttopen net",ttname,modem);
  2142. #ifdef NAMEFD
  2143.     for (p = ttname; isdigit(*p); p++) ; /* Check for all digits */
  2144.      if (*p == '\0' && (telnetfd || x25fd)) { /* Avoid X.121 addresses */
  2145.         ttyfd = atoi(ttname);    /* Is there a way to test it's open? */
  2146.         ttfdflg = 1;        /* We got an open file descriptor */
  2147.         debug(F111,"ttopen got open network fd",ttname,ttyfd);
  2148.         ckstrncpy(ttnmsv,ttname,DEVNAMLEN); /* Remember the "name". */
  2149.         x = 1;            /* Return code is "good". */
  2150.         if (telnetfd) {
  2151.         ttnet = NET_TCPB;
  2152.         if (ttnproto != NP_TCPRAW)
  2153.           ttnproto = NP_TELNET;
  2154. #ifdef SUNX25
  2155.         } else if (x25fd) {
  2156.         ttnet = NET_SX25;
  2157.         ttnproto = NP_NONE;
  2158. #endif /* SUNX25 */
  2159.         }
  2160.     } else {            /* Host name or address given */
  2161. #ifdef NETPTY
  2162.         if (modem == NET_PTY) {
  2163.         int x;
  2164.         if (nopush) {
  2165.             debug(F100,"ttopen PTY: nopush","",0);
  2166.             return(-1);
  2167.         }
  2168.                 ttnet = NET_PTY;
  2169.         ttnproto = NP_NONE;
  2170.                 netconn = 1;            /* but we don't use network i/o */
  2171.                 ttpty = 1;
  2172.                 debug(F110,"ttopen PTY",ttname,0);
  2173.         x = do_pty(ttname);
  2174.         if (x > -1) {
  2175.             ckstrncpy(ttnmsv,ttname,DEVNAMLEN);
  2176.             xlocal = *lcl = 1;    /* It's local */
  2177.         } else {
  2178.             ttpty = 0;
  2179.             netconn = 0;
  2180.         }
  2181.         return(x);
  2182.         }
  2183. #endif /* NETPTY */
  2184. #ifdef NETCMD
  2185. /*
  2186.   dup2() is not available on older System V platforms like AT&T 3Bx.  For
  2187.   those systems we punt by not defining NETCMD, but we might be able to do
  2188.   better -- see workarounds for this problem in ckufio.c (search for dup2).
  2189. */
  2190.         if (modem == NET_CMD) {
  2191.         if (nopush) {
  2192.             debug(F100,"ttopen pipe: nopush","",0);
  2193.             return(-1);
  2194.         }
  2195.         if (pipe(pipe0) || pipe(pipe1)) {
  2196.             perror("Pipe error");
  2197.             return(-1);
  2198.         }
  2199.         ttpid = fork();        /* Make a fork */
  2200.  
  2201.         switch (ttpid) {
  2202.           case -1:        /* Error making fork */
  2203.             close(pipe0[0]);
  2204.             close(pipe0[1]);
  2205.             close(pipe1[0]);
  2206.             close(pipe1[1]);
  2207.             perror("Fork error");
  2208.             return(-1);
  2209.           case 0:        /* Child. */
  2210.             close(pipe0[0]);
  2211.             close(pipe1[1]);
  2212.             dup2(pipe0[1], 1);
  2213.             close(pipe0[1]);
  2214.             dup2(pipe1[0], 0);
  2215.             close(pipe1[0]);
  2216.             system(ttname);
  2217.             _exit(0);
  2218.           default:        /* Parent */
  2219.             close(pipe0[1]);
  2220.             close(pipe1[0]);
  2221.             fdin = pipe0[0];    /* Read from pipe */
  2222.             fdout = pipe1[1];    /* Write to pipe */
  2223.             ttout = fdopen(fdout,"w"); /* Get stream so we can */
  2224.             if (!ttout) {    /* make it unbuffered. */
  2225.             perror("fdopen failure");
  2226.             return(-1);
  2227.             }
  2228.             setbuf(ttout,NULL);
  2229.             ckstrncpy(ttnmsv,ttname,DEVNAMLEN);
  2230.             xlocal = *lcl = 1;    /* It's local */
  2231.             netconn = 1;    /* Call it a network connection */
  2232.             ttmdm = modem;    /* Remember network type */
  2233.             ttyfd = fdin;
  2234.             ttpipe = 1;
  2235.             return(0);
  2236.         }
  2237.         }
  2238. #endif /* NETCMD */
  2239. #endif /* NAMEFD */
  2240.         x = netopen(ttname, lcl, modem); /* (see ckcnet.h) */
  2241.         if (x > -1) {
  2242.         ckstrncpy(ttnmsv,ttname,DEVNAMLEN);
  2243.         } else netconn = 0;
  2244. #ifdef NAMEFD
  2245.     }
  2246. #endif /* NAMEFD */
  2247.  
  2248. #ifdef sony_news            /* Sony NEWS */
  2249.     if (ioctl(ttyfd,TIOCKGET,&km_ext) < 0) { /* Get Kanji mode */
  2250.         perror("ttopen error getting Kanji mode (network)");
  2251.         debug(F111,"ttopen error getting Kanji mode","network",0);
  2252.         km_ext = -1;        /* Make sure this stays undefined. */
  2253.     }
  2254. #endif /* sony_news */
  2255.  
  2256.     xlocal = *lcl = 1;        /* Network connections are local. */
  2257.     debug(F101,"ttopen net x","",x);
  2258. #ifdef COMMENT
  2259. /* Let netopen() do this */
  2260.     if (x > -1 && !x25fd)
  2261.       x = tn_ini();            /* Initialize TELNET protocol */
  2262. #endif /* COMMENT */
  2263.     return(x);
  2264.     } else {                /* Terminal device */
  2265. #endif    /* NETCONN */
  2266.  
  2267. #ifdef NAMEFD
  2268. /*
  2269.   This code lets you give Kermit an open file descriptor for a serial
  2270.   communication device, rather than a device name.  Kermit assumes that the
  2271.   line is already open, locked, conditioned with the right parameters, etc.
  2272. */
  2273.     for (p = ttname; isdigit(*p); p++) ; /* Check for all digits */
  2274.     if (*p == '\0') {
  2275.         ttyfd = atoi(ttname);    /* Is there a way to test it's open? */
  2276.         debug(F111,"ttopen got open fd",ttname,ttyfd);
  2277.         ckstrncpy(ttnmsv,ttname,DEVNAMLEN); /* Remember the "name". */
  2278.         if (ttyfd == 0)        /* If it's stdio... */
  2279.           xlocal = *lcl = 0;    /* we're in remote mode */
  2280.         else            /* otherwise */
  2281.           xlocal = *lcl = 1;    /* local mode. */
  2282.         netconn = 0;        /* Assume it's not a network. */
  2283.         tvtflg = 0;            /* Might need to initialize modes. */
  2284.         ttmdm = modem;        /* Remember modem type. */
  2285.         fdflag = 0;            /* Stdio not redirected. */
  2286.         ttfdflg = 1;        /* Flag we were opened this way. */
  2287.  
  2288. #ifdef sony_news            /* Sony NEWS */
  2289.         /* Get device Kanji mode */
  2290.         if (ioctl(ttyfd,TIOCKGET,&km_ext) < 0) {
  2291.         perror("ttopen error getting Kanji mode");
  2292.         debug(F101,"ttopen error getting Kanji mode","",0);
  2293.         km_ext = -1;        /* Make sure this stays undefined. */
  2294.         }
  2295. #endif /* sony_news */
  2296.         return(0);            /* Return success */
  2297.     }
  2298. #endif /* NAMEFD */
  2299. #ifdef NETCONN
  2300.     }
  2301. #endif /* NETCONN */
  2302.  
  2303. /* Here we have to open a serial device of the given name. */
  2304.  
  2305.     netconn = 0;            /* So it's not a network connection */
  2306.     occt = signal(SIGINT, cctrap);    /* Set Control-C trap, save old one */
  2307.     sigint_ign = 0;
  2308.  
  2309.     tvtflg = 0;            /* Flag for use by ttvt(). */
  2310.                 /* 0 = ttvt not called yet for this device */
  2311.  
  2312.     fdflag = (!isatty(0) || !isatty(1)); /* Flag for stdio redirected */
  2313.     debug(F101,"ttopen fdflag","",fdflag);
  2314.  
  2315.     ttmdm = modem;                      /* Make this available to other fns */
  2316.     xlocal = *lcl;                      /* Make this available to other fns */
  2317.  
  2318. /* Code for handling bidirectional tty lines goes here. */
  2319. /* Use specified method for turning off logins and suppressing getty. */
  2320.  
  2321. #ifdef ACUCNTRL
  2322.     /* Should put call to priv_on() here, but that would be very risky! */
  2323.     acucntrl("disable",ttname);         /* acucntrl() program. */
  2324.     /* and priv_off() here... */
  2325. #else
  2326. #ifdef ATT7300
  2327.     if ((attmodem & DOGETY) == 0)       /* offgetty() program. */
  2328.       attmodem |= offgetty(ttname);    /* Remember response.  */
  2329. #endif /* ATT7300 */
  2330. #endif /* ACUCNTRL */
  2331. /*
  2332.  In the following section, we open the tty device for read/write.
  2333.  If a modem has been specified via "set modem" prior to "set line"
  2334.  then the O_NDELAY parameter is used in the open, provided this symbol
  2335.  is defined (e.g. in fcntl.h), so that the program does not hang waiting
  2336.  for carrier (which in most cases won't be present because a connection
  2337.  has not been dialed yet).  O_NDELAY is removed later on in ttopen().  It
  2338.  would make more sense to first determine if the line is local before
  2339.  doing this, but because ttyname() requires a file descriptor, we have
  2340.  to open it first.  See do_open().
  2341.  
  2342.  Now open the device using the desired treatment of carrier.
  2343.  If carrier is REQUIRED, then open could hang forever, so an optional
  2344.  timer is provided.  If carrier is not required, the timer should never
  2345.  go off, and should do no harm...
  2346. */
  2347.     ttotmo = 0;                /* Flag no timeout */
  2348.     debug(F101,"ttopen timo","",timo);
  2349.     if (timo > 0) {
  2350.     int xx;
  2351.     saval = signal(SIGALRM,timerh);    /* Timed, set up timer. */
  2352.     xx = alarm(timo);        /* Timed open() */
  2353.     debug(F101,"ttopen alarm","",xx);
  2354.     if (
  2355. #ifdef CK_POSIX_SIG
  2356.         sigsetjmp(sjbuf,1)
  2357. #else
  2358.         setjmp(sjbuf)
  2359. #endif /* CK_POSIX_SIG */
  2360.         ) {
  2361.         ttotmo = 1;            /* Flag timeout. */
  2362.     } else ttyfd = do_open(ttname);
  2363.     ttimoff();
  2364.     debug(F111,"ttopen","modem",modem);
  2365.     debug(F101,"ttopen ttyfd","",ttyfd);
  2366.     debug(F101,"ttopen alarm return","",ttotmo);
  2367.     } else {
  2368.     errno = 0;
  2369.     ttyfd = do_open(ttname);
  2370.     }
  2371.     debug(F111,"ttopen ttyfd",ttname,ttyfd);
  2372.     if (ttyfd < 0) {            /* If couldn't open, fail. */
  2373.     debug(F101,"ttopen errno","",errno);
  2374.     if (errno > 0 && !quiet)
  2375.       perror(ttname);        /* Print message */
  2376.  
  2377. #ifdef ATT7300
  2378.     if (attmodem & DOGETY)        /* was getty(1m) running before us? */
  2379.       ongetty(ttnmsv);        /* yes, restart on tty line */
  2380.     attmodem &= ~DOGETY;        /* no phone in use, getty restored */
  2381. #else
  2382. #ifdef ACUCNTRL
  2383.         /* Should put call to priv_on() here, but that would be risky! */
  2384.     acucntrl("enable",ttname);    /* acucntrl() program. */
  2385.     /* and priv_off() here... */
  2386. #endif /* ACUNTRL */
  2387. #endif /* ATT7300 */
  2388.  
  2389.     signal(SIGINT,occt);        /* Put old Ctrl-C trap back. */
  2390.     if (errno == EACCES) {        /* Device is protected against user */
  2391.         debug(F110,"ttopen EACCESS",ttname,0); /* Return -4 */
  2392.         return(-4);
  2393.     } else return(ttotmo ? -2 : -1); /* Otherwise -2 if timeout, or -1 */
  2394.     }
  2395.  
  2396. #ifdef Plan9
  2397.     /* take this opportunity to open the control channel */
  2398.     if (p9openttyctl(ttname) < 0)
  2399. #else
  2400.     /* Make sure it's a real tty. */
  2401.     if (!isatty(ttyfd) && strcmp(ttname,"/dev/null"))
  2402. #endif /* Plan9 */
  2403.       {
  2404.     fprintf(stderr,"%s is not a terminal device\n",ttname);
  2405.     debug(F111,"ttopen not a tty",ttname,errno);
  2406.     close(ttyfd);
  2407.     ttyfd = -1;
  2408.     wasclosed = 1;
  2409.     signal(SIGINT,occt);
  2410.     return(-1);
  2411.     }
  2412.  
  2413. #ifdef aegis
  2414.     /* Apollo C runtime claims that console pads are tty devices, which
  2415.      * is reasonable, but they aren't any good for packet transfer. */
  2416.     ios_$inq_type_uid((short)ttyfd, ttyuid, st);
  2417.     if (st.all != status_$ok) {
  2418.         fprintf(stderr, "problem getting tty object type: ");
  2419.         error_$print(st);
  2420.     } else if (ttyuid != sio_$uid) { /* reject non-SIO lines */
  2421.         close(ttyfd); ttyfd = -1;
  2422.         wasclosed = 1;
  2423.         errno = ENOTTY; perror(ttname);
  2424.         signal(SIGINT,occt);
  2425.         return(-1);
  2426.     }
  2427. #endif /* aegis */
  2428.  
  2429.     sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  2430.  
  2431.     ckstrncpy(ttnmsv,ttname,DEVNAMLEN);    /* Keep copy of name locally. */
  2432.  
  2433. /* Caller wants us to figure out if line is controlling tty */
  2434.  
  2435.     if (*lcl < 0) {
  2436.         if (strcmp(ttname,CTTNAM) == 0) { /* "/dev/tty" always remote */
  2437.             xlocal = 0;
  2438.         debug(F111,"ttopen ttname=CTTNAM",ttname,xlocal);
  2439.         } else if (strcmp(ttname,cttnam) == 0) {
  2440.             xlocal = 0;
  2441.         debug(F111,"ttopen ttname=cttnam",ttname,xlocal);
  2442.     } else if (cttnam[0]) {
  2443. #ifdef BEBOX_DR7
  2444.             x = ttnmsv;            /* ttyname() is broken */
  2445. #else
  2446.             x = ttyname(ttyfd);         /* Get real name of ttname. */
  2447. #endif /* BEBOX_DR7 */
  2448.         if (!x) x = "";
  2449.         if (*x)
  2450.           xlocal = ((strncmp(x,cttnam,DEVNAMLEN) == 0) ? 0 : 1);
  2451.         else
  2452.           xlocal = 1;
  2453.             debug(F111,"ttopen ttyname(ttyfd) xlocal",x,xlocal);
  2454.         }
  2455.     }
  2456.  
  2457. #ifndef NOFDZERO
  2458. /* Note, the following code was added so that Unix "idle-line" snoopers */
  2459. /* would not think Kermit was idle when it was transferring files, and */
  2460. /* maybe log people out. */
  2461.     if (xlocal == 0) {            /* Remote mode */
  2462.     if (fdflag == 0) {        /* Standard i/o is not redirected */
  2463.         debug(F100,"ttopen setting ttyfd = 0","",0);
  2464. #ifdef LYNXOS
  2465.         /* On Lynx OS, fd 0 is open for read only. */
  2466.         dup2(ttyfd,0);
  2467. #endif /* LYNXOS */
  2468.         close(ttyfd);        /* Use file descriptor 0 */
  2469.         ttyfd = 0;
  2470.     } else {            /* Standard i/o is redirected */
  2471.         debug(F101,"ttopen stdio redirected","",ttyfd);
  2472.     }
  2473.     }
  2474. #endif /* NOFDZERO */
  2475.  
  2476. /* Now check if line is locked -- if so fail, else lock for ourselves */
  2477. /* Note: After having done this, don't forget to delete the lock if you */
  2478. /* leave ttopen() with an error condition. */
  2479.  
  2480.     lkf = 0;                            /* Check lock */
  2481.     if (xlocal > 0) {
  2482.     int xx; int xpid;
  2483.         if ((xx = ttlock(ttname)) < 0) { /* Can't lock it. */
  2484.             debug(F111,"ttopen ttlock fails",ttname,xx);
  2485.         /* WARNING - This close() can hang if tty is an empty socket... */
  2486.             close(ttyfd);        /* Close the device. */
  2487.         ttyfd = -1;            /* Erase its file descriptor. */
  2488.         wasclosed = 1;
  2489.         signal(SIGINT,occt);    /* Put old SIGINT back. */
  2490.         sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  2491.         if (xx == -2) {        /* If lockfile says device in use, */
  2492. #ifndef NOUUCP
  2493.         debug(F111,"ttopen reading lockfile pid",flfnam,xx);
  2494.         xpid = ttrpid(flfnam);    /* Try to read pid from lockfile */
  2495.         if (xpid > -1) {    /* If we got a pid */
  2496.             printf("Locked by process %d\n",xpid); /* tell them. */
  2497.             sprintf(lockpid,"%d",xpid);    /* Record it too */
  2498.             debug(F110,"ttopen lockpid",lockpid,0);
  2499.         } else if (*flfnam) {
  2500.             char *p = malloc(280); /* Print a directory listing. */
  2501. /*
  2502.   Note: priv_on() won't help here, because we do not pass privs along to
  2503.   to inferior processes, in this case ls.  So if the real user does not have
  2504.   directory-listing access to the lockfile directory, this will result in
  2505.   something like "not found".  That's why we try this only as a last resort.
  2506. */
  2507.             if (p) {        /* If we got the space... */
  2508.             extern char *DIRCMD;
  2509.             sprintf(p,"%s %s",DIRCMD,flfnam);
  2510.             zsyscmd(p);    /* Get listing. */
  2511.             if (p) {    /* free the space */
  2512.                 free(p);
  2513.                 p = NULL;
  2514.             }
  2515.             }
  2516.         }
  2517. #endif /* NOUUCP */
  2518.         return(-5);        /* Code for device in use */
  2519.         } else return(-3);        /* Access denied */
  2520.         } else lkf = 1;
  2521.     }
  2522.  
  2523. /* Got the line, now set the desired value for local. */
  2524.  
  2525.     if (*lcl != 0) *lcl = xlocal;
  2526.  
  2527. /* Some special stuff for v7... */
  2528.  
  2529. #ifdef  V7
  2530. #ifndef MINIX
  2531.     if (kmem[TTY] < 0) {        /*  If open, then skip this.  */
  2532.     qaddr[TTY] = initrawq(ttyfd);   /* Init the queue. */
  2533.     if ((kmem[TTY] = open("/dev/kmem", 0)) < 0) {
  2534.         fprintf(stderr, "Can't read /dev/kmem in ttopen.\n");
  2535.         perror("/dev/kmem");
  2536.         exit(1);
  2537.     }
  2538.     }
  2539. #endif /* !MINIX */
  2540. #endif /* V7 */
  2541.  
  2542. /* No failure returns after this point */
  2543.  
  2544. #ifdef ultrix
  2545.     ioctl(ttyfd, TIOCMODEM, &temp);
  2546. #ifdef TIOCSINUSE
  2547.     if (xlocal && ioctl(ttyfd, TIOCSINUSE, NULL) < 0) {
  2548.     if (!quiet)
  2549.       perror(ttname);
  2550.     }
  2551. #endif /* TIOCSINUSE */
  2552. #endif /* ultrix */
  2553.  
  2554. /* Get tty device settings  */
  2555.  
  2556. #ifdef BSD44ORPOSIX            /* POSIX */
  2557.     tcgetattr(ttyfd,&ttold);
  2558.     debug(F101,"ttopen tcgetattr ttold.c_lflag","",ttold.c_lflag);
  2559.     tcgetattr(ttyfd,&ttraw);
  2560.     debug(F101,"ttopen tcgetattr ttraw.c_lflag","",ttraw.c_lflag);
  2561.     tcgetattr(ttyfd,&tttvt);
  2562.     debug(F101,"ttopen tcgetattr tttvt.c_lflag","",tttvt.c_lflag);
  2563. #else                    /* BSD, V7, and all others */
  2564. #ifdef ATTSV                /* AT&T UNIX */
  2565.     ioctl(ttyfd,TCGETA,&ttold);
  2566.     debug(F101,"ttopen ioctl TCGETA ttold.c_lflag","",ttold.c_lflag);
  2567.     ioctl(ttyfd,TCGETA,&ttraw);
  2568.     ioctl(ttyfd,TCGETA,&tttvt);
  2569. #else
  2570. #ifdef BELLV10
  2571.     ioctl(ttyfd,TIOCGETP,&ttold);
  2572.     debug(F101,"ttopen BELLV10 ttold.sg_flags","",ttold.sg_flags);
  2573.     ioctl(ttyfd,TIOCGDEV,&tdold);
  2574.     debug(F101,"ttopen BELLV10 tdold.flags","",tdold.flags);
  2575. #else
  2576.     gtty(ttyfd,&ttold);
  2577.     debug(F101,"ttopen gtty ttold.sg_flags","",ttold.sg_flags);
  2578. #endif /* BELLV10 */
  2579.  
  2580. #ifdef sony_news            /* Sony NEWS */
  2581.     if (ioctl(ttyfd,TIOCKGET,&km_ext) < 0) { /* Get console Kanji mode */
  2582.     perror("ttopen error getting Kanji mode");
  2583.     debug(F101,"ttopen error getting Kanji mode","",0);
  2584.     km_ext = -1;            /* Make sure this stays undefined. */
  2585.     }
  2586. #endif /* sony_news */
  2587.  
  2588. #ifdef TIOCGETC
  2589.     debug(F100,"ttopen TIOCGETC","",0);
  2590.     tcharf = 0;                /* In remote mode, also get */
  2591.     if (xlocal == 0) {            /* special characters */
  2592.     if (ioctl(ttyfd,TIOCGETC,&tchold) < 0) {
  2593.         debug(F100,"ttopen TIOCGETC failed","",0);
  2594.     } else {
  2595.         tcharf = 1;            /* It worked. */
  2596.         ioctl(ttyfd,TIOCGETC,&tchnoi); /* Get another copy */
  2597.         debug(F100,"ttopen TIOCGETC ok","",0);
  2598.     }
  2599.     }
  2600. #else
  2601.     debug(F100,"ttopen TIOCGETC not defined","",0);
  2602. #endif /* TIOCGETC */
  2603.  
  2604. #ifdef TIOCGLTC
  2605.     debug(F100,"ttopen TIOCGLTC","",0);
  2606.     ltcharf = 0;            /* In remote mode, also get */
  2607.     if (xlocal == 0) {            /* local special characters */
  2608.     if (ioctl(ttyfd,TIOCGLTC,<chold) < 0) {
  2609.         debug(F100,"ttopen TIOCGLTC failed","",0);
  2610.     } else {
  2611.         ltcharf = 1;        /* It worked. */
  2612.         ioctl(ttyfd,TIOCGLTC,<chnoi); /* Get another copy */
  2613.         debug(F100,"ttopen TIOCGLTC ok","",0);
  2614.     }
  2615.     }
  2616. #else
  2617.     debug(F100,"ttopen TIOCGLTC not defined","",0);
  2618. #endif /* TIOCGLTC */
  2619.  
  2620. #ifdef TIOCLGET
  2621.     debug(F100,"ttopen TIOCLGET","",0);
  2622.     lmodef = 0;
  2623.     if (ioctl(ttyfd,TIOCLGET,&lmode) < 0) {
  2624.     debug(F100,"ttopen TIOCLGET failed","",0);
  2625.     } else {
  2626.     lmodef = 1;
  2627.     debug(F100,"ttopen TIOCLGET ok","",0);
  2628.     }
  2629. #endif /* TIOCLGET */
  2630.  
  2631. #ifdef BELLV10
  2632.     ioctl(ttyfd,TIOCGETP,&ttraw);
  2633.     ioctl(ttyfd,TIOCGETP,&tttvt);
  2634. #else
  2635.     gtty(ttyfd,&ttraw);                 /* And a copy of it for packets*/
  2636.     gtty(ttyfd,&tttvt);                 /* And one for virtual tty service */
  2637. #endif /* BELLV10 */
  2638.  
  2639. #endif /* ATTSV */
  2640. #endif /* BSD44ORPOSIX */
  2641.  
  2642. /* Section for changing line discipline.  It's restored in ttres(). */
  2643.  
  2644. #ifdef AIXRS
  2645. #ifndef AIX41
  2646.     { union txname ld_name; int ld_idx = 0;
  2647.       ttld = 0;
  2648.         do {
  2649.         ld_name.tx_which = ld_idx++;
  2650.         ioctl(ttyfd, TXGETCD, &ld_name);
  2651.       if (!strncmp(ld_name.tx_name, "rts", 3))
  2652.           ttld |= 1;
  2653.         } while (*ld_name.tx_name);
  2654.         debug(F101,"AIX line discipline","",ttld);
  2655.       }
  2656. #endif /* AIX41 */
  2657. #endif /* AIXRS */
  2658.  
  2659. #ifdef BSD41
  2660. /* For 4.1BSD only, force "old" tty driver, new one botches TANDEM. */
  2661.     { int k;
  2662.       ioctl(ttyfd, TIOCGETD, &ttld);    /* Get and save line discipline */
  2663.       debug(F101,"4.1bsd line discipline","",ttld);
  2664.       k = OTTYDISC;            /* Switch to "old" discipline */
  2665.       k = ioctl(ttyfd, TIOCSETD, &k);
  2666.       debug(F101,"4.1bsd tiocsetd","",k);
  2667.     }
  2668. #endif /* BSD41 */
  2669.  
  2670. #ifdef aegis
  2671.     /* This was previously done before the last two TCGETA or gtty above,
  2672.      * in both the ATTSV and not-ATTSV case.  If it is not okay to have only
  2673.      * one copy if it here instead, give us a shout!
  2674.      */
  2675.     sio_$control((short)ttyfd, sio_$raw_nl, false, st);
  2676.     if (xlocal) {       /* ignore breaks from local line */
  2677.         sio_$control((short)ttyfd, sio_$int_enable, false, st);
  2678.         sio_$control((short)ttyfd, sio_$quit_enable, false, st);
  2679.     }
  2680. #endif /* aegis */
  2681.  
  2682. #ifdef VXVE
  2683.     ttraw.c_line = 0;                   /* STTY line 0 for VX/VE */
  2684.     tttvt.c_line = 0;                   /* STTY line 0 for VX/VE */
  2685.     ioctl(ttyfd,TCSETA,&ttraw);
  2686. #endif /* vxve */
  2687.  
  2688. /* If O_NDELAY was used during open(), then remove it now. */
  2689.  
  2690. #ifdef O_NDELAY
  2691.     debug(F100,"ttopen O_NDELAY","",0);
  2692.     if (fcntl(ttyfd, F_GETFL, 0) & O_NDELAY) {
  2693.     debug(F100,"ttopen fcntl O_NDELAY","",0);
  2694. #ifndef aegis
  2695.     if (fcntl(ttyfd,F_SETFL, fcntl(ttyfd, F_GETFL, 0) & ~O_NDELAY) < 0) {
  2696.         debug(F100,"ttopen fcntl failure to unset O_NDELAY","",0);
  2697.         perror("Can't unset O_NDELAY");
  2698.     }
  2699. #endif /* aegis */
  2700.     /* Some systems, notably Xenix (don't know how common this is in
  2701.      * other systems), need special treatment to get rid of the O_NDELAY
  2702.      * behaviour on read() with respect to carrier presence (i.e. read()
  2703.      * returning 0 when carrier absent), even though the above fcntl()
  2704.      * is enough to make read() wait for input when carrier is present.
  2705.      * This magic, in turn, requires CLOCAL for working when the carrier
  2706.      * is absent. But if xlocal == 0, presumably you already have CLOCAL
  2707.      * or you have a carrier, otherwise you wouldn't be running this.
  2708.      */
  2709.     debug(F101,"ttopen xlocal","",xlocal);
  2710. #ifdef ATTSV
  2711. #ifdef BSD44ORPOSIX
  2712. #ifdef COMMENT                /* 12 Aug 1997 */
  2713. #ifdef __bsdi__
  2714.     if (xlocal)
  2715.       ttraw.c_cflag |= CLOCAL;
  2716. #else
  2717. #ifdef __FreeBSD__
  2718.     if (xlocal)
  2719.       ttraw.c_cflag |= CLOCAL;
  2720. #endif /* __FreeBSD__ */
  2721. #endif /* __bsdi__ */
  2722. #else /* Not COMMENT */
  2723. #ifdef CLOCAL
  2724.     if (xlocal)            /* Unset this if it's defined. */
  2725.       ttraw.c_cflag |= CLOCAL;
  2726. #endif /* CLOCAL */
  2727. #endif /* COMMENT */
  2728.     debug(F100,"ttopen calling POSIX tcseattr","",0);
  2729.     if (tcsetattr(ttyfd, TCSADRAIN, &ttraw) < 0) {
  2730.         debug(F100,"ttopen POSIX tcseattr fails","",0);
  2731.         perror("tcsetattr");
  2732.     }
  2733. #else /* !BSD44ORPOSIX */
  2734.     if (xlocal) {
  2735.         ttraw.c_cflag |= CLOCAL;
  2736.         debug(F100,"ttopen calling ioctl(TCSETA)","",0);
  2737.         errno = 0;
  2738.         if (ioctl(ttyfd, TCSETA, &ttraw) < 0) {
  2739.                 debug(F101,"ttopen ioctl(TCSETA) fails","",errno);
  2740.                 perror("ioctl(TCSETA)");
  2741.             }
  2742.     }
  2743. #endif /* BSD44ORPOSIX */
  2744. #endif /* ATTSV */
  2745. #ifndef NOCOTFMC /* = NO Close(Open()) To Force Mode Change */
  2746. /* Reportedly lets uugetty grab the device in SCO UNIX 3.2 / XENIX 2.3 */
  2747.     debug(F100,"ttopen executing close/open","",0);
  2748.     close( priv_opn(ttname, O_RDWR) ); /* Magic to force change. */
  2749. #endif /* NOCOTFMC */
  2750.     }
  2751. #endif /* O_NDELAY */
  2752.  
  2753. /* Instruct the system how to treat the carrier, and set a few other tty
  2754.  * parameters.
  2755.  *
  2756.  * This also undoes the temporary setting of CLOCAL that may have been done
  2757.  * for the close(open()) above (except in Xenix).  Also throw in ~ECHO, to
  2758.  * prevent the other end of the line from sitting there talking to itself,
  2759.  * producing garbage when the user performs a connect.
  2760.  *
  2761.  * SCO Xenix unfortunately seems to ignore the actual state of CLOCAL.
  2762.  * Now it thinks CLOCAL is always on. It seems the only real solution for
  2763.  * Xenix is to switch between the lower and upper case device names.
  2764.  *
  2765.  * This section may at some future time expand into setting a complete
  2766.  * collection of tty parameters, or call a function shared with ttpkt()/
  2767.  * ttvt() that does so.  On the other hand, the initial parameters are not
  2768.  * that important, since ttpkt() or ttvt() should always fix that before
  2769.  * any communication is done.  Well, we'll see...
  2770.  */
  2771.     if (xlocal) {
  2772.         curcarr = -2;
  2773.     debug(F100,"ttopen calling carrctl","",0);
  2774.     carrctl(&ttraw, ttcarr == CAR_ON);
  2775.     debug(F100,"ttopen carrctl ok","",0);
  2776.  
  2777. #ifdef COHERENT
  2778. #define SVORPOSIX
  2779. #endif /* COHERENT */
  2780.  
  2781. #ifdef SVORPOSIX
  2782.     ttraw.c_lflag &= ~ECHO;
  2783.     ttold.c_lflag &= ~ECHO;
  2784. #ifdef BSD44ORPOSIX
  2785.     y = tcsetattr(ttyfd, TCSADRAIN, &ttraw);
  2786.     debug(F101,"ttopen tcsetattr","",y);
  2787. #else
  2788.     y = ioctl(ttyfd, TCSETA, &ttraw);
  2789.     debug(F100,"ttopen ioctl","",y);
  2790. #endif /* BSD44ORPOSIX */
  2791.  
  2792. #else /* BSD, etc */
  2793.     ttraw.sg_flags &= ~ECHO;
  2794.     ttold.sg_flags &= ~ECHO;
  2795. #ifdef BELLV10
  2796.     y = ioctl(ttyfd,TIOCSETP,&ttraw);
  2797.     debug(F100,"ttopen ioctl","",y);
  2798. #else
  2799.     y = stty(ttyfd,&ttraw);
  2800.     debug(F100,"ttopen stty","",y);
  2801. #endif /* BELLV10 */
  2802. #endif /* SVORPOSIX */
  2803.  
  2804. #ifdef COHERENT
  2805. #undef SVORPOSIX
  2806. #endif /* COHERENT */
  2807.  
  2808.     /* ttflui(); */  /*  This fails for some reason.  */
  2809.     }
  2810.  
  2811.     /* Get current speed */
  2812.  
  2813. #ifndef BEBOX
  2814.     ttspeed = ttgspd();
  2815. #else
  2816.     ttspeed = 19200;
  2817. #endif /* !BEBOX */
  2818.     debug(F101,"ttopen ttspeed","",ttspeed);
  2819.  
  2820.     /* Done, make entries in debug log, restore Ctrl-C trap, and return. */
  2821.  
  2822.     debug(F101,"ttopen ttyfd","",ttyfd);
  2823.     debug(F101,"ttopen *lcl","",*lcl);
  2824.     debug(F111,"ttopen lock file",flfnam,lkf);
  2825.     signal(SIGINT,occt);
  2826.     sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  2827.     return(0);
  2828. }
  2829.  
  2830.  
  2831. /*  D O _ O P E N  --  Do the right kind of open() call for the tty. */
  2832.  
  2833. int
  2834. do_open(ttname) char *ttname; {
  2835.  
  2836. #ifndef    O_NDELAY            /* O_NDELAY not defined */
  2837.     return(priv_opn(ttname,2));
  2838. #else                    /* O_NDELAY defined */
  2839.  
  2840. #ifdef ATT7300
  2841. /*
  2842.  Open comms line without waiting for carrier so initial call does not hang
  2843.  because state of "modem" is likely unknown at the initial call  -jrd.
  2844.  If this is needed for the getty stuff to work, and the open would not work
  2845.  without O_NDELAY when getty is still on, then this special case is ok.
  2846.  Otherwise, get rid of it. -ske
  2847. */
  2848.     return(priv_opn(ttname, O_RDWR | O_NDELAY));
  2849.  
  2850. #else    /* !ATT7300 */
  2851.  
  2852.     /* Normal case. Use O_NDELAY according to SET CARRIER. See ttscarr(). */
  2853.  
  2854.     return(priv_opn(ttname, O_RDWR | ((ttcarr != CAR_ON) ? O_NDELAY : 0) ));
  2855.  
  2856. #endif    /* !ATT7300 */
  2857. #endif    /* O_NDELAY */
  2858. }
  2859.  
  2860. /*  T T C L O S  --  Close the TTY, releasing any lock.  */
  2861.  
  2862. static int ttc_state = 0;        /* ttclose() state */
  2863. static char * ttc_nam[] = { "setup", "hangup", "reset", "close" };
  2864.  
  2865. int
  2866. ttclos(foo) int foo; {            /* Arg req'd for signal() prototype */
  2867.     int xx, x = 0;
  2868.  
  2869.     debug(F101,"ttclos ttyfd","",ttyfd);
  2870.     debug(F101,"ttclos netconn","",netconn);
  2871.     debug(F101,"ttclos xlocal","",xlocal);
  2872. #ifdef NOFDZERO
  2873.     debug(F100,"ttclos NOFDZERO","",0);
  2874. #endif /* NOFDZERO */
  2875.  
  2876. #ifdef COMMENT
  2877. #ifdef TTLEBUF
  2878.     le_init();                /* No need for any of this */
  2879. #endif /* TTLEBUF */
  2880. #endif /* COMMENT */
  2881.  
  2882.     if (ttyfd < 0)            /* Wasn't open. */
  2883.       return(0);
  2884.  
  2885.     if (ttfdflg)            /* If we inherited ttyfd from */
  2886.       return(0);            /* another process, don't close it. */
  2887.  
  2888.     tvtflg = 0;                /* (some day get rid of this...) */
  2889.  
  2890. #ifdef IKSD
  2891.     if (inserver) {
  2892. #ifdef TNCODE
  2893.           tn_push();                    /* Place any waiting data into input*/
  2894.           tn_sopt(DO,TELOPT_LOGOUT);    /* Send LOGOUT option before close */
  2895.           TELOPT_UNANSWERED_DO(TELOPT_LOGOUT) = 1;
  2896.           tn_reset();                   /* The Reset Telnet Option table.  */
  2897. #endif /* TNCODE */
  2898. #ifdef CK_SSL
  2899.       if (ssl_active_flag) {
  2900.           if (ssl_debug_flag)
  2901.         BIO_printf(bio_err,"calling SSL_shutdown(ssl)\n");
  2902.           SSL_shutdown(ssl_con);
  2903.           SSL_free(ssl_con);
  2904.           ssl_con = NULL;
  2905.           ssl_active_flag = 0;
  2906.       }
  2907.       if (tls_active_flag) {
  2908.           if (ssl_debug_flag)
  2909.         BIO_printf(bio_err,"calling SSL_shutdown(tls)\n");
  2910.           SSL_shutdown(tls_con);
  2911.           SSL_free(tls_con);
  2912.           tls_con = NULL;
  2913.           tls_active_flag = 0;
  2914.       }
  2915. #endif /* CK_SSL */
  2916.     }
  2917. #endif /* IKSD */
  2918. #ifdef NETCMD
  2919.     if (ttpipe) {            /* We've been using a pipe */
  2920.     /* ttpipe = 0; */
  2921.     if (ttpid > 0) {
  2922.         int wstat;
  2923. #ifdef OSF40
  2924.         union wait statusp_w;
  2925.         int statusp;
  2926. #else
  2927.         int statusp;
  2928. #endif /* OSF40 */
  2929.         close(fdin);        /* Close these. */
  2930.         close(fdout);
  2931.         fdin = fdout = -1;
  2932.         kill(ttpid,1);        /* Kill fork with SIGHUP */
  2933.         while (1) {
  2934.         wstat = wait(
  2935. #ifdef OSF40
  2936.                  &statusp_w
  2937. #else
  2938.                  &statusp
  2939. #endif /* OSF40 */
  2940.                  );
  2941.         if (wstat == ttpid || wstat == -1)
  2942.           break;
  2943. #ifdef OSF40
  2944.         statusp = (*(int *)&(statusp_w));
  2945. #endif /* OSF40 */
  2946.         pexitstat = (statusp & 0xff) ? statusp : statusp >> 8;
  2947.         }
  2948.         ttpid = 0;
  2949.     }
  2950.     netconn = 0;
  2951.     wasclosed = 1;
  2952.     ttyfd = -1;
  2953.     return(0);
  2954.     }
  2955. #endif /* NETCMD */
  2956. #ifdef NETPTY
  2957.     if (ttpty) {
  2958. #ifndef NODOPTY
  2959.         end_pty();
  2960. #endif /* NODOPTY */
  2961.         close(ttyfd);
  2962.     netconn = 0;
  2963.     wasclosed = 1;
  2964.         ttpty = 0;
  2965.         ttyfd = -1;
  2966.         return(0);
  2967.     }
  2968. #endif /* NETPTY */
  2969.  
  2970. #ifdef    NETCONN
  2971.     if (netconn) {            /* If it's a network connection. */
  2972.     debug(F100,"ttclos closing net","",0);
  2973.     netclos();            /* Let the network module close it. */
  2974.     netconn = 0;            /* No more network connection. */
  2975.     debug(F101,"ttclos ttyfd after netclos","",ttyfd); /* Should be -1 */
  2976.     return(0);
  2977.     }
  2978. #endif    /* NETCONN */
  2979.  
  2980.     if (xlocal) {            /* We're closing a SET LINE device */
  2981. #ifdef FT21                /* Fortune 2.1-specific items ... */
  2982.     ioctl(ttyfd,TIOCHPCL, NULL);
  2983. #endif /* FT21 */
  2984. #ifdef ultrix                /* Ultrix-specific items ... */
  2985. #ifdef TIOCSINUSE
  2986.     /* Unset the INUSE flag that we set in ttopen() */
  2987.     ioctl(ttyfd, TIOCSINUSE, NULL);
  2988. #endif /* TIOCSINUSE */
  2989.     ioctl(ttyfd, TIOCNMODEM, &x);
  2990. #ifdef COMMENT
  2991.     /* What was this? */
  2992.     ioctl(ttyfd, TIOCNCAR, NULL);
  2993. #endif /* COMMENT */
  2994. #endif /* ultrix */
  2995.     debug(F100,"ttclos about to call ttunlck","",0);
  2996.         if (ttunlck())                  /* Release uucp-style lock */
  2997.       fprintf(stderr,"Warning, problem releasing lock\r\n");
  2998.     }
  2999.  
  3000.     /* This is to prevent us from sticking in tthang() or close(). */
  3001.  
  3002. #ifdef O_NDELAY
  3003. #ifndef aegis
  3004.     if (ttyfd > 0) {            /* But skip it on stdin. */
  3005.     debug(F100,"ttclos setting O_NDELAY","",0);
  3006.     x = fcntl(ttyfd,F_SETFL,fcntl(ttyfd,F_GETFL, 0)|O_NDELAY);
  3007. #ifdef DEBUG
  3008.     if (deblog && x == -1) {
  3009.         perror("Warning - Can't set O_NDELAY");
  3010.         debug(F101,"ttclos fcntl failure to set O_NDELAY","",x);
  3011.     }
  3012. #endif /* DEBUG */
  3013.     }
  3014. #endif /* aegis */
  3015. #endif /* O_NDELAY */
  3016.  
  3017.     x = 0;
  3018.     ttc_state = 0;
  3019.     if (xlocal
  3020. #ifdef NOFDZERO
  3021.     || ttyfd > 0
  3022. #endif /* NOFDZERO */
  3023.     ) {
  3024.     saval = signal(SIGALRM,xtimerh); /* Enable timer interrupt. */
  3025.     xx = alarm(8);            /* Allow 8 seconds. */
  3026.     debug(F101,"ttclos alarm","",xx);
  3027.     if (
  3028. #ifdef CK_POSIX_SIG
  3029.         sigsetjmp(sjbuf,1)
  3030. #else
  3031.         setjmp(sjbuf)
  3032. #endif /* CK_POSIX_SIG */
  3033.         ) {                /* Timer went off? */
  3034.         x = -1;
  3035. #ifdef DEBUG
  3036.         debug(F111,"ttclos ALARM TRAP errno",ckitoa(ttc_state),errno);
  3037.         printf("ttclos() timeout: %s\n", ttc_nam[ttc_state]);
  3038. #endif /* DEBUG */
  3039.     }
  3040.     errno = 0;
  3041.     debug(F101,"ttclos A","",ttc_state);
  3042.     if (ttc_state < 1) {
  3043.         ttc_state = 1;
  3044.         alarm(8);            /* Re-arm the timer */
  3045.         debug(F101,"ttclos calling tthang()","",x);
  3046.         x = tthang();        /* Hang up first, then... */
  3047.         debug(F101,"ttclos tthang()","",x);
  3048.     }
  3049.     debug(F101,"ttclos B","",ttc_state);
  3050.     if (ttc_state < 2) {
  3051.         ttc_state = 2;
  3052.         debug(F101,"ttclos calling ttres()","",x);
  3053.         alarm(8);            /* Re-arm the timer */
  3054.         x = ttres();        /* Reset device modes. */
  3055.         debug(F101,"ttclos ttres()","",x);
  3056.     }
  3057.     debug(F101,"ttclos C","",ttc_state);
  3058.     if (ttc_state < 3) {
  3059.         ttc_state = 3;
  3060.         errno = 0;
  3061.         debug(F101,"ttclos calling close","",x);
  3062.         alarm(8);            /* Re-arm the timer */
  3063.         x = close(ttyfd);        /* Close the device. */
  3064.         debug(F101,"ttclos close()","",x);
  3065.     }
  3066.     debug(F101,"ttclos D","",ttc_state);
  3067.     ttimoff();            /* Turn off timer. */
  3068.     if (x < 0) {
  3069.         printf("?WARNING - close failed: %s\n",ttnmsv);
  3070. #ifdef DEBUG
  3071.         if (deblog) {
  3072.         printf("errno = %d\n", errno);
  3073.         debug(F101,"ttclos failed","",errno);
  3074.         }
  3075. #endif /* DEBUG */
  3076.     }
  3077.     }
  3078.  
  3079. /* For bidirectional lines, restore getty if it was there before. */
  3080.  
  3081. #ifdef ACUCNTRL                /* 4.3BSD acucntrl() method. */
  3082.     if (xlocal) {
  3083.     debug(F100,"ttclos ACUCNTRL","",0);
  3084.     acucntrl("enable",ttnmsv);    /* Enable getty on the device. */
  3085.     }
  3086. #else
  3087. #ifdef ATT7300                /* ATT UNIX PC (3B1, 7300) method. */
  3088.     if (xlocal) {
  3089.     debug(F100,"ttclos ATT7300 ongetty","",0);
  3090.     if (attmodem & DOGETY)        /* Was getty(1m) running before us? */
  3091.       ongetty(ttnmsv);        /* Yes, restart getty on tty line */
  3092.     attmodem &= ~DOGETY;        /* No phone in use, getty restored */
  3093.     }
  3094. #endif /* ATT7300 */
  3095. #endif /* System-dependent getty-restoring methods */
  3096.  
  3097. #ifdef sony_news
  3098.     km_ext = -1;            /* Invalidate device's Kanji-mode */
  3099. #endif /* sony_news */
  3100.  
  3101.     ttyfd = -1;                         /* Invalidate the file descriptor. */
  3102.     wasclosed = 1;
  3103.     debug(F100,"ttclos done","",0);
  3104.     return(0);
  3105. }
  3106.  
  3107. /*  T T H A N G  --  Hangup phone line or network connection.  */
  3108. /*
  3109.   Returns:
  3110.   0 if it does nothing.
  3111.   1 if it believes that it hung up successfully.
  3112.  -1 if it believes that the hangup attempt failed.
  3113. */
  3114.  
  3115. #define HUPTIME 500            /* Milliseconds for hangup */
  3116.  
  3117. /* Define HUP_POSIX to force non-POSIX builds to use the POSIX hangup method */
  3118.  
  3119. #ifdef UNIXWARE                /* Such as Unixware 1.x, 2.x */
  3120. #ifndef POSIX
  3121. #ifndef HUP_POSIX
  3122. #define HUP_POSIX
  3123. #endif /* HUP_POSIX */
  3124. #endif /* POSIX */
  3125. #endif /* UNIXWARE */
  3126.  
  3127. int
  3128. tthang() {
  3129. #ifdef NOLOCAL
  3130.     return(0);
  3131. #else
  3132.     int x = 0;                /* Sometimes used as return code. */
  3133. #ifndef POSIX
  3134.     int z;                /* worker */
  3135. #endif /* POSIX */
  3136.  
  3137. #ifdef COHERENT
  3138. #define SVORPOSIX
  3139. #endif /* COHERENT */
  3140.  
  3141. #ifdef SVORPOSIX            /* AT&T, POSIX, HPUX declarations. */
  3142.     int spdsav;                /* for saving speed */
  3143. #ifdef HUP_POSIX
  3144.     int spdsavi;
  3145. #else
  3146. #ifdef BSD44ORPOSIX
  3147.     int spdsavi;
  3148. #endif /* BSD44ORPOSIX */
  3149. #endif /* HUP_POSIX */
  3150. #ifdef HPUX
  3151. /*
  3152.   Early versions of HP-UX omitted the mflag typedef.  If you get complaints
  3153.   about it, just change it to long (or better still, unsigned long).
  3154. */
  3155.     mflag
  3156.       dtr_down = 00000000000,
  3157.       modem_rtn,
  3158.       modem_sav;
  3159.     char modem_state[64];
  3160. #endif /* HPUX */
  3161.     int flags;                /* fcntl flags */
  3162.     unsigned short ttc_save;
  3163. #endif /* SVORPOSIX */
  3164.  
  3165. #ifdef COHERENT
  3166. #undef SVORPOSIX
  3167. #endif /* COHERENT */
  3168.  
  3169.     if (ttyfd < 0) return(0);           /* Don't do this if not open  */
  3170.     if (xlocal < 1) return(0);        /* Don't do this if not local */
  3171.  
  3172. #ifdef NETCMD
  3173.     if (ttpipe)
  3174.       return((ttclos(0) < 0) ? -1 : 1);
  3175. #endif /* NETCMD */
  3176. #ifdef NETPTY
  3177.     if (ttpty)
  3178.       return((ttclos(0) < 0) ? -1 : 1);
  3179. #endif /* NETPTY */
  3180. #ifdef NETCONN
  3181.     if (netconn)            /* Network connection. */
  3182.       return((netclos() < 0) ? -1 : 1);    /* Just close it. */
  3183. #endif /* NETCONN */
  3184.  
  3185. /* From here down, we handle real tty devices. */
  3186. #ifdef HUP_POSIX
  3187. /*
  3188.   e.g. for Unixware 2, where we don't have a full POSIX build, we
  3189.   still have to use POSIX-style hangup.  Thus the duplication of this
  3190.   and the next case, the only difference being we use a local termios
  3191.   struct here, since a different model is used elsewhere.
  3192. */
  3193.     {
  3194.     struct termios ttcur;
  3195.     int x;
  3196.     debug(F100,"tthang HUP_POSIX style","",0);
  3197.     x = tcgetattr(ttyfd, &ttcur);    /* Get current attributes */
  3198.     debug(F111,"tthang tcgetattr",ckitoa(errno),x);
  3199.     if (x < 0) return(-1);
  3200.     spdsav = cfgetospeed(&ttcur);    /* Get current speed */
  3201.     debug(F111,"tthang cfgetospeed",ckitoa(errno),spdsav);
  3202.     spdsavi = cfgetispeed(&ttcur);    /* Get current speed */
  3203.     debug(F111,"tthang cfgetispeed",ckitoa(errno),spdsavi);
  3204.     x = cfsetospeed(&ttcur,B0);    /* Replace by 0 */
  3205.     debug(F111,"tthang cfsetospeed",ckitoa(errno),x);
  3206.     if (x < 0) return(-1);
  3207.     x = cfsetispeed(&ttcur,B0);
  3208.     debug(F111,"tthang cfsetispeed",ckitoa(errno),x);
  3209.     if (x < 0) return(-1);
  3210.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3211.     debug(F111,"tthang tcsetattr B0",ckitoa(errno),x);
  3212.     if (x < 0) return(-1);
  3213.     msleep(HUPTIME);        /* Sleep 0.5 sec */
  3214.     x = cfsetospeed(&ttcur,spdsav); /* Restore prev speed */
  3215.     if (x < 0) return(-1);
  3216.     debug(F111,"tthang cfsetospeed prev",ckitoa(errno),x);
  3217.     x = cfsetispeed(&ttcur,spdsavi);
  3218.     debug(F111,"tthang cfsetispeed prev",ckitoa(errno),x);
  3219.     if (x < 0) return(-1);
  3220.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3221.     debug(F111,"tthang tcsetattr restore",ckitoa(errno),x);
  3222.     if (x < 0) return(-1);
  3223.     return(1);
  3224.     }
  3225. #else
  3226. #ifdef BSD44ORPOSIX
  3227. /*
  3228.   NOTE: This should work for QNX too, but in case it doesn't, it is also
  3229.   possible to toggle DTR using qnx_ioctl(ttyfd,QCTL_DEV_CTL,&new,&old);
  3230.   see <sys/qioctl.h> and QNX News V10, Sep 96, p44.
  3231.   Newer versions of QNX also have a tcdropline(howlong) function.
  3232. */
  3233.     {
  3234.     int x;
  3235.     debug(F100,"tthang POSIX style","",0);
  3236.     x = tcgetattr(ttyfd, &ttcur);    /* Get current attributes */
  3237.     debug(F111,"tthang tcgetattr",ckitoa(errno),x);
  3238.     if (x < 0) return(-1);
  3239.     spdsav = cfgetospeed(&ttcur);    /* Get current speed */
  3240.     debug(F111,"tthang cfgetospeed",ckitoa(errno),spdsav);
  3241.     spdsavi = cfgetispeed(&ttcur);    /* Get current speed */
  3242.     debug(F111,"tthang cfgetispeed",ckitoa(errno),spdsavi);
  3243.     x = cfsetospeed(&ttcur,B0);    /* Replace by 0 */
  3244.     debug(F111,"tthang cfsetospeed",ckitoa(errno),x);
  3245.     if (x < 0) return(-1);
  3246.     x = cfsetispeed(&ttcur,B0);
  3247.     debug(F111,"tthang cfsetispeed",ckitoa(errno),x);
  3248.     if (x < 0) return(-1);
  3249.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3250.     debug(F111,"tthang tcsetattr B0",ckitoa(errno),x);
  3251.     if (x < 0) return(-1);
  3252.     msleep(HUPTIME);        /* Sleep 0.5 sec */
  3253.     x = cfsetospeed(&ttcur,spdsav); /* Restore prev speed */
  3254.     if (x < 0) return(-1);
  3255.     debug(F111,"tthang cfsetospeed prev",ckitoa(errno),x);
  3256.     x = cfsetispeed(&ttcur,spdsavi);
  3257.     debug(F111,"tthang cfsetispeed prev",ckitoa(errno),x);
  3258.     if (x < 0) return(-1);
  3259.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3260.     debug(F111,"tthang tcsetattr restore",ckitoa(errno),x);
  3261.     if (x < 0) return(-1);
  3262.     return(1);
  3263.     }
  3264.  
  3265.  
  3266. #else /* BSD44ORPOSIX */
  3267.  
  3268. #ifdef aegis                /* Apollo Aegis */
  3269.     sio_$control((short)ttyfd, sio_$dtr, false, st);    /* DTR down */
  3270.     msleep(HUPTIME);                    /* pause */
  3271.     sio_$control((short)ttyfd, sio_$dtr, true,  st);    /* DTR up */
  3272.     return(1);
  3273. #endif /* aegis */
  3274.  
  3275. #ifdef ANYBSD                /* Any BSD version. */
  3276. #ifdef TIOCCDTR                /* Except those that don't have this */
  3277.     debug(F100,"tthang BSD style","",0);
  3278.     if (ioctl(ttyfd,TIOCCDTR,0) < 0) {    /* Clear DTR. */
  3279.     debug(F101,"tthang TIOCCDTR fails","",errno);
  3280.     return(-1);
  3281.     }
  3282.     msleep(HUPTIME);            /* For about 1/2 sec */
  3283.     errno = 0;
  3284.     x = ioctl(ttyfd,TIOCSDTR,0);    /* Restore DTR */
  3285.     if (x < 0) {
  3286.     /*
  3287.       For some reason, this tends to fail with "no such device or address"
  3288.       but the operation still works, probably because of the close/open
  3289.       later on.  So let's not scare the user unnecessarily here.
  3290.     */
  3291.     debug(F101,"tthang TIOCSDTR errno","",errno); /* Log the error */
  3292.     x = 1;                /* Pretend we succeeded */
  3293.     } else if (x == 0) x = 1;        /* Success */
  3294. #ifdef COMMENT
  3295. #ifdef FT21
  3296.     ioctl(ttyfd, TIOCSAVEMODES, 0);
  3297.     ioctl(ttyfd, TIOCHPCL, 0);
  3298.     close(ttyfd);            /* Yes, must do this twice */
  3299.     if ((ttyfd = open(ttnmsv,2)) < 0)    /* on Fortune computers... */
  3300.       return(-1);            /* (but why?) */
  3301.     else x = 1;
  3302. #endif /* FT21 */
  3303. #endif /* COMMENT */
  3304. #endif /* TIOCCDTR */
  3305.     close(do_open(ttnmsv));        /* Clear i/o error condition */
  3306.     errno = 0;
  3307. #ifdef COMMENT
  3308. /* This is definitely dangerous.  Why was it here? */
  3309.     z = ttvt(ttspeed,ttflow);        /* Restore modes. */
  3310.     debug(F101,"tthang ttvt returns","",z);
  3311.     return(z < 0 ? -1 : 1);
  3312. #else
  3313.     return(x);
  3314. #endif /* COMMENT */
  3315. #endif /* ANYBSD */
  3316.  
  3317. #ifdef ATTSV
  3318. /* AT&T UNIX section, includes HP-UX and generic AT&T System III/V... */
  3319.  
  3320. #ifdef HPUX
  3321. /* Hewlett Packard allows explicit manipulation of modem signals. */
  3322.  
  3323. #ifdef COMMENT
  3324. /* Old way... */
  3325.     debug(F100,"tthang HP-UX style","",0);
  3326.     if (ioctl(ttyfd,MCSETAF,&dtr_down) < 0)        /* lower DTR */
  3327.       return(-1);                           /* oops, can't. */
  3328.     msleep(HUPTIME);                       /* Pause half a second. */
  3329.     x = 1;                           /* Set return code */
  3330.     if (ioctl(ttyfd,MCGETA,&modem_rtn) > -1) {     /* Get line status. */
  3331.     if ((modem_rtn & MDCD) != 0)             /* Check if CD is low. */
  3332.       x = -1;                                  /* CD didn't drop, fail. */
  3333.     } else x = -1;
  3334.  
  3335.     /* Even if above calls fail, RTS & DTR should be turned back on. */
  3336.     modem_rtn = MRTS | MDTR;
  3337.     if (ioctl(ttyfd,MCSETAF,&modem_rtn) < 0) x = -1;
  3338.     return(x);
  3339. #else
  3340. /* New way, from Hellmuth Michaelis */
  3341.     debug(F100,"tthang HP-UX style, HPUXDEBUG","",0);
  3342.     if (ioctl(ttyfd,MCGETA,&modem_rtn) == -1) { /* Get current status. */
  3343.     debug(F100,"tthang HP-UX: can't get modem lines, NO HANGUP!","",0);
  3344.     return(-1);
  3345.     }
  3346.     sprintf(modem_state,"%#lx",modem_rtn);
  3347.     debug(F110,"tthang HP-UX: modem lines = ",modem_state,0);
  3348.     modem_sav = modem_rtn;        /* Save current modem signals */
  3349.     modem_rtn &= ~MDTR;            /* Turn DTR bit off */
  3350.     sprintf(modem_state,"%#lx",modem_rtn);
  3351.     debug(F110,"tthang HP-UX: DTR down = ",modem_state,0);
  3352.     if (ioctl(ttyfd,MCSETAF,&modem_rtn) < 0) { /* lower DTR */
  3353.     debug(F100,"tthang HP-UX: can't lower DTR!","",0);
  3354.     return(-1);            /* oops, can't. */
  3355.     }
  3356.     msleep(HUPTIME);            /* Pause half a second. */
  3357.     x = 1;                /* Set return code */
  3358.     if (ioctl(ttyfd,MCGETA,&modem_rtn) > -1) { /* Get line status. */
  3359.     sprintf(modem_state,"%#lx",modem_rtn);
  3360.     debug(F110,"tthang HP-UX: modem lines got = ",modem_state,0);
  3361.     if ((modem_rtn & MDCD) != 0) {    /* Check if CD is low. */
  3362.         debug(F100,"tthang HP-UX: DCD not down","",0);
  3363.         x = -1;            /* CD didn't drop, fail. */
  3364.     } else {
  3365.         debug(F100,"tthang HP-UX: DCD down","",0);
  3366.     }
  3367.     } else {
  3368.     x = -1;
  3369.     debug(F100,"tthang HP-UX: can't get DCD status !","",0);
  3370.     }
  3371.  
  3372.     /* Even if above calls fail, DTR should be turned back on. */
  3373.  
  3374.     modem_sav |= MDTR;
  3375.     if (ioctl(ttyfd,MCSETAF,&modem_sav) < 0) {
  3376.     x = -1;
  3377.     debug(F100,"tthang HP-UX: can't set saved state","",0);
  3378.     } else {
  3379.     sprintf(modem_state,"%#lx",modem_sav);
  3380.     debug(F110,"tthang HP-UX: final modem lines = ",modem_state,0);
  3381.     }
  3382.     return(x);
  3383. #endif /* COMMENT */
  3384.  
  3385. #else /* AT&T but not HP-UX */
  3386.  
  3387. /* SVID for AT&T System V R3 defines ioctl's for handling modem signals. */
  3388. /* It is not known how many, if any, systems actually implement them, */
  3389. /* so we include them here in ifdef's. */
  3390.  
  3391. /*
  3392.   Unixware has the TIOCMxxx symbols defined, but calling ioctl() with them
  3393.   gives error 22 (invalid argument).
  3394. */
  3395. #ifndef _IBMR2
  3396. /*
  3397.   No modem-signal twiddling for IBM RT PC or RS/6000.
  3398.   In AIX 3.1 and earlier, the ioctl() call is broken.
  3399.   This code could be activated for AIX 3.1 with PTF 2006 or later
  3400.   (e.g. AIX 3.2), but close/open does the job too, so why bother.
  3401. */
  3402. #ifdef TIOCMBIS                /* Bit Set */
  3403. #ifdef TIOCMBIC                /* Bit Clear */
  3404. #ifdef TIOCM_DTR            /* DTR */
  3405.  
  3406. /* Clear DTR, sleep 300 msec, turn it back on. */
  3407. /* If any of the ioctl's return failure, go on to the next section. */
  3408.  
  3409.     z = TIOCM_DTR;            /* Code for DTR. */
  3410. #ifdef COMMENT
  3411. /*
  3412.   This was the cause of the troubles with the Solaris Port Monitor.
  3413.   The problem is: RTS never comes back on.  Moral: Don't do it!
  3414.   (But why doesn't it come back on?  See the TIOCMBIS call...)
  3415. */
  3416. #ifdef TIOCM_RTS            /* Lower RTS too if symbol is known. */
  3417.     z |= TIOCM_RTS;
  3418. #endif /* TIOCM_RTS */
  3419. #endif /* COMMENT */
  3420.  
  3421.     debug(F101,"tthang TIOCM signal mask","",z);
  3422.     if (ioctl(ttyfd,TIOCMBIC,&z) > -1) {   /* Try to lower DTR. */
  3423.     debug(F100,"tthang TIOCMBIC ok","",0);
  3424.     msleep(HUPTIME);           /* Pause half a second. */
  3425.     if (ioctl(ttyfd,TIOCMBIS,&z) > -1) { /* Try to turn it back on. */
  3426.         debug(F100,"tthang TIOCMBIS ok","",0);
  3427. #ifndef CLSOPN
  3428.         return(1);            /* Success, done. */
  3429. #endif /* CLSOPN */
  3430.     } else {            /* Couldn't raise, continue. */
  3431.         debug(F101,"tthang TIOCMBIS errno","",errno);
  3432.     }
  3433.     } else {                /* Couldn't lower, continue. */
  3434.      debug(F101,"tthang TIOCMBIC errno","",errno);
  3435.     }
  3436. #endif /* TIOCM_DTR */
  3437. #endif /* TIOCMBIC */
  3438. #endif /* TIOCMBIS */
  3439. #endif /* _IBMR2 */
  3440.  
  3441. /*
  3442.   General AT&T UNIX case, not HPUX.  The following code is highly suspect.  No
  3443.   two AT&T-based systems seem to do this the same way.  The object is simply
  3444.   to turn off DTR and then turn it back on.  SVID says the universal method
  3445.   for turning off DTR is to set the speed to zero, and this does seem to do
  3446.   the trick in all cases.  But neither SVID nor any known man pages say how to
  3447.   turn DTR back on again.  Some variants, like most Xenix implementations,
  3448.   raise DTR again when the speed is restored to a nonzero value.  Others
  3449.   require the device to be closed and opened again, but this is risky because
  3450.   getty could seize the device during the instant it is closed.
  3451. */
  3452.  
  3453. /* Return code for ioctl failures... */
  3454. #ifdef ATT6300
  3455.     x = 1;                /* ATT6300 doesn't want to fail... */
  3456. #else
  3457.     x = -1;
  3458. #endif /* ATT6300 */
  3459.  
  3460.     debug(F100,"tthang get settings","",0);
  3461.     if (ioctl(ttyfd,TCGETA,&ttcur) < 0) /* Get current settings. */
  3462.       return(x);            /* Fail if this doesn't work. */
  3463.     if ((flags = fcntl(ttyfd,F_GETFL,0)) < 0) /* Get device flags. */
  3464.       return(x);
  3465.     ttc_save = ttcur.c_cflag;        /* Remember current speed. */
  3466.     spdsav = ttc_save & CBAUD;
  3467.     debug(F101,"tthang speed","",spdsav);
  3468.  
  3469. #ifdef O_NDELAY
  3470.     debug(F100,"tthang turning O_NDELAY on","",0);
  3471.     fcntl(ttyfd, F_SETFL, flags | O_NDELAY); /* Activate O_NDELAY */
  3472. #endif /* O_NDELAY */
  3473.  
  3474. #ifdef ATT7300 /* This is the way it is SUPPOSED to work */
  3475.     ttcur.c_cflag &= ~CBAUD;        /* Change the speed to zero.  */
  3476. #else
  3477. #ifdef RTAIX
  3478.     ttcur.c_cflag &= ~CBAUD;        /* Change the speed to zero.  */
  3479. #else          /* This way really works but may be dangerous */
  3480. #ifdef u3b2
  3481.     ttcur.c_cflag = ~(CBAUD|CLOCAL);    /* Special for AT&T 3B2s */
  3482.                     /* (CLOCAL must be OFF) */
  3483. #else
  3484. #ifdef SCO3R2                /* SCO UNIX 3.2 */
  3485. /*
  3486.   This is complete nonsense, but an SCO user claimed this change made
  3487.   hanging up work.  Comments from other SCO UNIX 3.2 users would be
  3488.   appreciated.
  3489. */
  3490.     ttcur.c_cflag = CBAUD|B0;
  3491. #else
  3492. #ifdef AIXRS                /* AIX on RS/6000 */
  3493. /*
  3494.   Can't set speed to zero on AIX 3.1 on RS/6000 64-port adapter,
  3495.   even though you can do it on the built-in port and the 8- and 16-port
  3496.   adapters.  (Untested on 128-port adapter.)
  3497. */
  3498.     ttcur.c_cflag = CLOCAL|HUPCL|spdsav; /* Speed 0 causes EINVAL */
  3499. #else                    /* None of the above */
  3500. /*
  3501.   Set everything, including the speed, to zero, except for the CLOCAL
  3502.   and HUPCL bits.
  3503. */
  3504.     ttcur.c_cflag = CLOCAL|HUPCL;
  3505. #endif /* AIXRS */
  3506. #endif /* SCO3R2 */
  3507. #endif /* u3b2 */
  3508. #endif /* RTAIX */
  3509. #endif /* ATT7300 */
  3510.  
  3511. #ifdef COMMENT
  3512.     /* and if none of those work, try one of these... */
  3513.     ttcur.c_cflag = 0;
  3514.     ttcur.c_cflag = CLOCAL;
  3515.     ttcur.c_cflag &= ~(CBAUD|HUPCL);
  3516.     ttcur.c_cflag &= ~(CBAUD|CREAD);
  3517.     ttcur.c_cflag &= ~(CBAUD|CREAD|HUPCL);
  3518.     /* or other combinations */
  3519. #endif /* COMMENT */
  3520.  
  3521. #ifdef TCXONC
  3522.     debug(F100,"tthang TCXONC","",0);
  3523.     if (ioctl(ttyfd, TCXONC, 1) < 0) {
  3524.     debug(F101,"tthang TCXONC failed","",errno);
  3525.     }
  3526. #endif /* TCXONC */
  3527.  
  3528. #ifdef TIOCSTART
  3529.     debug(F100,"tthang TIOCSTART","",0);
  3530.     if (ioctl(ttyfd, TIOCSTART, 0) < 0) {
  3531.     debug(F101,"tthang TIOCSTART failed","",errno);
  3532.     }
  3533. #endif /* TIOCSTART */
  3534.  
  3535.     if (ioctl(ttyfd,TCSETAF,&ttcur) < 0) { /* Fail if we can't. */
  3536.     debug(F101,"tthang TCSETAF failed","",errno);
  3537.     fcntl(ttyfd, F_SETFL, flags);    /* Restore flags */
  3538.     return(-1);            /* before returning. */
  3539.     }
  3540.     msleep(300);            /* Give modem time to notice. */
  3541.  
  3542. #ifndef NOCOTFMC
  3543.  
  3544. /* Now, even though it doesn't say this in SVID or any man page, we have */
  3545. /* to close and reopen the device.  This is not necessary for all systems, */
  3546. /* but it's impossible to predict which ones need it and which ones don't. */
  3547.  
  3548. #ifdef ATT7300
  3549. /*
  3550.   Special handling for ATT 7300 UNIX PC and 3B1, which have "phone"
  3551.   related ioctl's for their internal modems.  attmodem has getty status and
  3552.   modem-in-use bit.  Reportedly the ATT7300/3B1 PIOCDISC call is necessary,
  3553.   but also ruins the file descriptor, and no other phone(7) ioctl call can fix
  3554.   it.  Whateverit does, it seems to escape detection with PIOCGETA and TCGETA.
  3555.   The only way to undo the damage is to close the fd and then reopen it.
  3556. */
  3557.     if (attmodem & ISMODEM) {
  3558.     debug(F100,"tthang attmodem close/open","",0);
  3559.     ioctl(ttyfd,PIOCUNHOLD,&dialer); /* Return call to handset. */
  3560.     ioctl(ttyfd,PIOCDISC,&dialer);    /* Disconnect phone. */
  3561.     close(ttyfd);            /* Close and reopen the fd. */
  3562.     ttyfd = priv_opn(ttnmsv, O_RDWR | O_NDELAY);
  3563.     attmodem &= ~ISMODEM;        /* Phone no longer in use. */
  3564.     }
  3565. #else /* !ATT7300 */
  3566. /* It seems we have to close and open the device for other AT&T systems */
  3567. /* too, and this is the place to do it.  The following code does the */
  3568. /* famous close(open(...)) magic by default.  If that doesn't work for you, */
  3569. /* then try uncommenting the following statement or putting -DCLSOPN in */
  3570. /* the makefile CFLAGS. */
  3571.  
  3572. /* #define CLSOPN */
  3573.  
  3574. #ifndef SCO32 /* Not needed by, and harmful to, SCO UNIX 3.2 / Xenix 2.3 */
  3575.  
  3576. #ifdef O_NDELAY
  3577. #define OPENFLGS O_RDWR | O_NDELAY
  3578. #else
  3579. #define OPENFLGS O_RDWR
  3580. #endif
  3581.  
  3582. #ifndef CLSOPN
  3583. /* This method is used by default, i.e. unless CLSOPN is defined. */
  3584. /* It is thought to be safer because there is no window where getty */
  3585. /* can seize control of the device.  The drawback is that it might not work. */
  3586.  
  3587.     debug(F101,"tthang close(open()), OPENFLGS","",OPENFLGS);
  3588.     close(priv_opn(ttnmsv, OPENFLGS));
  3589.  
  3590. #else
  3591. /* This method is used if you #define CLSOPN.  It is more likely to work */
  3592. /* than the previous method, but it's also more dangerous. */
  3593.  
  3594.     debug(F101,"tthang close/open, OPENFLGS","",OPENFLGS);
  3595.     close(ttyfd);
  3596.     msleep(10);
  3597.     ttyfd = priv_opn(ttnmsv, OPENFLGS);    /* Open it again */
  3598. #endif /* CLSOPN */
  3599. #undef OPENFLGS
  3600.  
  3601. #endif /* SCO32 */
  3602. #endif /* ATT7300 */
  3603.  
  3604. #endif /* NOCOTFMC */
  3605.  
  3606. /* Now put all flags & modes back the way we found them. */
  3607. /* (Does the order of ioctl & fcntl matter ? ) */
  3608.  
  3609.     debug(F100,"tthang restore settings","",0);
  3610.     ttcur.c_cflag = ttc_save;        /* Get old speed back. */
  3611.     if (ioctl(ttyfd,TCSETAF,&ttcur) < 0) /* ioctl parameters. */
  3612.       return(-1);
  3613. #ifdef O_NDELAY
  3614. /*
  3615.   This is required for IBM RT and RS/6000, probably helps elsewhere too (?).
  3616.   After closing a modem line, the modem will probably not be asserting
  3617.   carrier any more, so we should not require carrier any more.  If this
  3618.   causes trouble on non-IBM UNIXes, change the #ifdef to use _IBMR2 rather
  3619.   than O_NDELAY.
  3620. */
  3621.     flags &= ~O_NDELAY;            /* Don't require carrier on reopen */
  3622. #endif /* O_NDELAY */
  3623.     if (fcntl(ttyfd,F_SETFL,flags) < 0)    /* fcntl parameters */
  3624.       return(-1);
  3625.  
  3626.     return(1);
  3627. #endif /* not HPUX */
  3628. #endif /* ATTSV */
  3629. #endif /* BSD44ORPOSIX */
  3630. #endif /* HUP_POSIX */
  3631. #endif /* NOLOCAL */
  3632. }
  3633.  
  3634. /*
  3635.   Major change in 5A(174).  We used to use LPASS8, if it was defined, to
  3636.   allow 8-bit data and Xon/Xoff flow control at the same time.  But this
  3637.   LPASS8 business seems to have been causing trouble for everybody but me!
  3638.   For example, Annex terminal servers, commonly used with Encore computers,
  3639.   do not support LPASS8 even though the Encore itself does.  Ditto for many
  3640.   other terminal servers, TELNET connections, rlogin connections, etc etc.
  3641.   Now, reportedly, even vanilla 4.3 BSD systems can't do this right on their
  3642.   serial lines, even though LPASS8 is a feature of 4.3BSD.  So let's turn it
  3643.   off for everybody.  That means we goes back to using raw mode, with no
  3644.   flow control.  Phooey.
  3645.  
  3646.   NOTE: This must be done before the first reference to LPASS8 in this file,
  3647.   and after the last #include statment.
  3648. */
  3649. #ifdef LPASS8
  3650. #undef LPASS8
  3651. #endif /* LPASS8 */
  3652.  
  3653. /*  T T R E S  --  Restore terminal to "normal" mode.  */
  3654.  
  3655. /* ske@pkmab.se: There are two choices for what this function should do.
  3656.  * (1) Restore the tty to current "normal" mode, with carrier treatment
  3657.  * according to ttcarr, to be used after every kermit command. (2) Restore
  3658.  * the tty to the state it was in before kermit opened it. These choices
  3659.  * conflict, since ttold can't hold both choices of tty parameters.  ttres()
  3660.  * is currently being called as in choice (1), but ttold basically holds
  3661.  * the initial parameters, as in (2), and the description at the beginning
  3662.  * of this file says (2).
  3663.  *
  3664.  * I don't think restoring tty parameters after all kermit commands makes
  3665.  * much of a difference.  Restoring them upon exit from kermit may be of
  3666.  * some use in some cases (when the line is not restored automatically on
  3667.  * close, by the operating system).
  3668.  *
  3669.  * I can't choose which one it should be, so I haven't changed it. It
  3670.  * probably works as it is, too. It would probably even work even with
  3671.  * ttres() entirely deleted...
  3672.  *
  3673.  * (from fdc: Actually, this function operates in remote mode too, so
  3674.  * it restores the console (command) terminal to whatever mode it was
  3675.  * in before packet operations began, so that commands work right again.)
  3676.  */
  3677. int
  3678. ttres() {                               /* Restore the tty to normal. */
  3679.     int x;
  3680.  
  3681.     if (ttyfd < 0) return(-1);          /* Not open. */
  3682.  
  3683.     if (ttfdflg) return(0);        /* Don't mess with terminal modes if */
  3684.                     /* we got ttyfd from another process */
  3685. #ifdef    NETCONN
  3686.     if (netconn) {            /* Network connection */
  3687.         tvtflg = 0;
  3688. #ifdef TCPSOCKET
  3689. #ifdef TCP_NODELAY
  3690.         {
  3691.         extern int tcp_nodelay;    /* Just put this back if necessary */
  3692.         if (ttnet == NET_TCPB) {
  3693.         if (nodelay_sav > -1) {
  3694.             no_delay(nodelay_sav);
  3695.             nodelay_sav = -1;
  3696.         }
  3697.         }
  3698.         }
  3699. #endif /* TCP_NODELAY */
  3700. #endif /* TCPSOCKET */
  3701.     return(0);
  3702.     }
  3703. #endif    /* NETCONN */
  3704. #ifdef NETCMD
  3705.     if (ttpipe) return(0);
  3706. #endif /* NETCMD */
  3707. #ifdef NETPTY
  3708.     if (ttpty) return(0);
  3709. #endif /* NETPTY */
  3710.  
  3711. /* Real terminal device, so restore its original modes */
  3712.  
  3713. #ifdef BSD44ORPOSIX            /* For POSIX like this */
  3714.     debug(F100,"ttres BSD44ORPOSIX","",0);
  3715.     x = tcsetattr(ttyfd,TCSADRAIN,&ttold);
  3716. #else                    /* For all others... */
  3717. #ifdef ATTSV                            /* For AT&T versions... */
  3718.     debug(F100,"ttres ATTSV","",0);
  3719.     x = ioctl(ttyfd,TCSETAW,&ttold);    /* Restore tty modes this way. */
  3720. #else
  3721. /* Here we restore the modes for BSD */
  3722.  
  3723. #ifdef LPASS8                /* Undo "pass8" if it were done */
  3724.     if (lmodef) {
  3725.     if (ioctl(ttyfd,TIOCLSET,&lmode) < 0)
  3726.       debug(F100,"ttres TIOCLSET failed","",0);
  3727.     else
  3728.       debug(F100,"ttres TIOCLSET ok","",0);
  3729.     }
  3730. #endif /* LPASS8 */
  3731.  
  3732. #ifdef CK_DTRCTS           /* Undo hardware flow if it were done */
  3733.     if (lmodef) {
  3734.      if (ioctl(ttyfd,TIOCLSET,&lmode) < 0)
  3735.        debug(F100,"ttres TIOCLSET failed","",0);
  3736.      else
  3737.        debug(F100,"ttres TIOCLSET ok","",0);
  3738.     }
  3739. #endif /* CK_DTRCTS */
  3740.  
  3741. #ifdef TIOCGETC                /* Put back special characters */
  3742.     if (tcharf && (xlocal == 0)) {
  3743.     if (ioctl(ttyfd,TIOCSETC,&tchold) < 0)
  3744.       debug(F100,"ttres TIOCSETC failed","",0);
  3745.     else
  3746.       debug(F100,"ttres TIOCSETC ok","",0);
  3747.     }
  3748. #endif /* TIOCGETC */
  3749.  
  3750. #ifdef TIOCGLTC                /* Put back local special characters */
  3751.     if (ltcharf && (xlocal == 0)) {
  3752.     if (ioctl(ttyfd,TIOCSLTC,<chold) < 0)
  3753.       debug(F100,"ttres TIOCSLTC failed","",0);
  3754.     else
  3755.       debug(F100,"ttres TIOCSLTC ok","",0);
  3756.     }
  3757. #endif /* TIOCGLTC */
  3758.  
  3759. #ifdef BELLV10
  3760.     debug(F100,"ttres BELLV10","",0);
  3761.     x = ioctl(ttyfd,TIOCSETP,&ttold);    /* Restore both structs */
  3762.     x = ioctl(ttyfd,TIOCSDEV,&tdold);
  3763. #else
  3764.     debug(F100,"ttres stty","",0);
  3765.     x = stty(ttyfd,&ttold);             /* Restore tty modes the old way. */
  3766. #endif /* BELLV10 */
  3767.  
  3768.     if (!xlocal)
  3769.       msleep(100);            /* This replaces sleep(1)... */
  3770.                     /* Put back sleep(1) if tty is */
  3771.                     /* messed up after close. */
  3772. #endif /* ATTSV */
  3773. #endif /* BSD44ORPOSIX */
  3774.  
  3775.     debug(F101,"ttres result","",x);
  3776. #ifndef QNX
  3777.     if (x < 0) debug(F101,"ttres errno","",errno);
  3778. #endif /* QNX */
  3779.  
  3780. #ifdef AIXRS
  3781. #ifndef AIX41
  3782.     x = ioctl(ttyfd, ttld & 1 ? TXADDCD : TXDELCD, "rts");
  3783.     debug(F101,"ttres AIX line discipline rts restore","",x);
  3784. #endif /* AIX41 */
  3785. #endif /* AIXRS */
  3786.  
  3787. #ifdef BSD41
  3788.     if (ttld > -1) {            /* Put back line discipline */
  3789.     x = ioctl(ttyfd, TIOCSETD, &ttld);
  3790.     debug(F101,"ttres BSD41 line discipline restore","",x);
  3791.     if (x < 0) debug(F101,"...ioctl errno","",errno);
  3792.     ttld = -1;
  3793.     }
  3794. #endif /* BSD41 */
  3795.  
  3796. #ifdef sony_news
  3797.     x = xlocal ? km_ext : km_con;    /* Restore Kanji mode. */
  3798.     if (x != -1) {            /* Make sure we know original modes. */
  3799.     if (ioctl(ttyfd,TIOCKSET, &x) < 0) {
  3800.         perror("ttres can't set Kanji mode");
  3801.         debug(F101,"ttres error setting Kanji mode","",x);
  3802.         return(-1);
  3803.     }
  3804.     }
  3805.     debug(F100,"ttres set Kanji mode ok","",0);
  3806. #endif /* sony_news */
  3807.  
  3808.     tvtflg = 0;                /* Invalidate terminal mode settings */
  3809.     debug(F101,"ttres return code","",x);
  3810.     return(x);
  3811. }
  3812.  
  3813. #ifndef NOUUCP
  3814.  
  3815. /*  T T C H K P I D  --  Check lockfile pid  */
  3816. /*
  3817.   Read pid from lockfile named f, check that it's still valid.
  3818.   If so, return 1.
  3819.   On failure to read pid, return 1.
  3820.   Otherwise, try to delete lockfile f and return 0 if successful, else 1.
  3821. */
  3822. static int
  3823. ttchkpid(f) char *f; {
  3824.     int pid, mypid, x;
  3825.     pid = ttrpid(f);            /* Read pid from file. */
  3826.     if (pid > -1) {            /* If we were able to read the pid.. */
  3827.     debug(F101,"ttchkpid lock pid","",pid);
  3828.     errno = 0;            /* See if process still exists. */
  3829.     mypid = (int)getpid();        /* Get my own pid. */
  3830.     debug(F101,"ttchkpid my pid","",mypid);
  3831.     if (pid == mypid) {        /* It's me! */
  3832.         x = -1;            /* So I can delete it */
  3833.         errno = ESRCH;        /* pretend it's invalid */
  3834.     } else {            /* It's not me */
  3835.         x = kill((PID_T)pid, 0);    /* See if it's a live process */
  3836.         debug(F101,"ttchkpid kill errno","",errno);
  3837.     }
  3838.     debug(F101,"ttchkpid pid test","",x);
  3839.     if (x < 0 && errno == ESRCH) { /* pid is invalid */
  3840.         debug(F111,"removing stale lock",f,pid);
  3841.         if (!backgrd)
  3842.           printf("Removing stale lock %s (pid %d terminated)\n", f, pid);
  3843.         priv_on();
  3844.         x = unlink(f);        /* Remove the lockfile. */
  3845.         priv_off();
  3846.         debug(F111,"ttchkpid unlink",f,x);
  3847.         if (x > -1)
  3848.           return(0);        /* Device is not locked after all */
  3849.         else if (!backgrd)
  3850.           perror(f);
  3851.     }
  3852.     return(1);
  3853.     }
  3854.     return(1);                /* Failure to read pid */
  3855. }
  3856.  
  3857. #ifdef HPUX
  3858.  
  3859. /* Aliases (different drivers) for HP-UX dialout devices: */
  3860.  
  3861. static char *devprefix[] = { "tty", "ttyd", "cul", "cua", "cuad", "culd", "" };
  3862. static int ttydexists = 0;
  3863.  
  3864. #endif /* HPUX */
  3865.  
  3866. /*  T T R P I D  --  Read pid from lockfile "name" */
  3867.  
  3868. static int
  3869. ttrpid(name) char *name; {
  3870.     long len;
  3871.     int x, i, fd, pid, flag;
  3872.     short spid;
  3873.     char buf[32];
  3874.  
  3875.     debug(F110,"ttrpid",name,0);
  3876.     if (!name) return(-1);
  3877.     if (!*name) return(-1);
  3878.     priv_on();
  3879.     len = zchki(name);            /* Get file length */
  3880.     priv_off();
  3881.     debug(F101,"ttrpid zchki","",len);
  3882.     if (len < 0)
  3883.       return(-1);
  3884.     if (len > 31)
  3885.       return(-1);
  3886.     priv_on();
  3887.     fd = open(name,O_RDONLY);        /* Try to open lockfile. */
  3888.     priv_off();
  3889.     debug(F101,"ttrpid fd","",fd);
  3890.     if (fd <= 0)
  3891.       return(-1);
  3892. /*
  3893.   Here we try to be flexible and allow for all different binary and string
  3894.   formats at runtime, rather than a specific format for each configuration
  3895.   hardwired at compile time.
  3896. */
  3897.     pid = -1;
  3898. #ifndef COHERENT
  3899. /*
  3900.   COHERENT uses a string PID but without leading spaces or 0's, so there is
  3901.   no way to tell from the file's length whether it contains a string or binary
  3902.   pid.  So for COHERENT only, we only allow string pids.  For all others, we
  3903.   decide based on the size of the lockfile.
  3904. */
  3905.     if (len > 4) {            /* If file > 4 bytes it's a string */
  3906. #endif /* COHERENT */
  3907.     x = read(fd,buf,len);
  3908.     debug(F111,"ttrpid string read",buf,x);
  3909.     if (x < 0) {
  3910.         pid = -1;
  3911.     } else {
  3912.         buf[31] = '\0';
  3913.         x = sscanf(buf,"%d",&pid);    /* Get the integer pid from it. */
  3914.     }
  3915. #ifndef COHERENT
  3916.     } else if (len == 4) {        /* 4 bytes so binary */
  3917.     x = read(fd, (char *)&pid, 4);    /* Read the bytes into an int */
  3918.     debug(F101,"ttrpid integer read","",x);
  3919.     if (x < 4)
  3920.       pid = -1;
  3921.     } else if (len == 2) {        /* 2 bytes binary */
  3922.     x = read(fd, (char *)&spid, 2);    /* Read the bytes into a short */
  3923.     debug(F101,"ttrpid short read","",x);
  3924.     if (x < 2)
  3925.       pid = -1;
  3926.     else
  3927.       pid = spid;
  3928.     } else
  3929.       pid = -1;
  3930. #endif /* COHERENT */
  3931.     close(fd);                /* Close the lockfile */
  3932.     debug(F101,"ttrpid pid","",pid);
  3933.     return(pid);
  3934. }
  3935. #endif /* NOUUCP */
  3936.  
  3937. /*  T T L O C K  */
  3938.  
  3939. /*
  3940.   This function attempts to coordinate use of the communication device with
  3941.   other copies of Kermit and any other program that follows the UUCP
  3942.   device-locking conventions, which, unfortunately, vary among different UNIX
  3943.   implementations.  The idea is to look for a file of a certain name, the
  3944.   "lockfile", in a certain directory.  If such a file is found, then the line
  3945.   is presumed to be in use, and Kermit should not use it.  If no such file is
  3946.   found, Kermit attempts to create one so that other programs will not use the
  3947.   same line at the same time.  Because the lockfile and/or the directory it's
  3948.   in might lack write permission for the person running Kermit, Kermit could
  3949.   find itself running setuid to uucp or other user that does have the
  3950.   necessary permissions.  At startup, Kermit has changed its effective uid to
  3951.   the user's real uid, and so ttlock() must switch back to the original
  3952.   effective uid in order to create the lockfile, and then back again to the
  3953.   real uid to prevent unauthorized access to other directories or files owned
  3954.   by the user the program is setuid to.
  3955.  
  3956.   Totally rewritten for C-Kermit 5A to eliminate windows of vulnerability,
  3957.   based on suggestions from Warren Tucker.  Call with pointer to name of
  3958.   tty device.  Returns:
  3959.  
  3960.    0 on success
  3961.   -1 on failure
  3962.  
  3963.   Note: Once privileges are turned on using priv_on(), it is essential that
  3964.   they are turned off again before this function returns.
  3965. */
  3966. #ifdef SVR4                /* Lockfile uses device numbers. */
  3967. /*
  3968.   Although I can't find this in writing anywhere (e.g. in SVID for SVR4),
  3969.   it is the behavior of the "reference version" of SVR4, i.e. the Intel
  3970.   port from UNIX Systems Laboratories, then called Univel UnixWare,
  3971.   then called Novell UnixWare, now called SCO Unixware...  It also makes
  3972.   much more sense than device-name-based lockfiles, since there can be
  3973.   multiple names for the same device, symlinks, etc.
  3974. */
  3975. #ifndef LFDEVNO                /* Define this for SVR4 */
  3976. #ifndef AIXRS                /* But not for RS/6000 AIX 3.2, etc. */
  3977. #ifndef BSD44                /* If anybody else needs it... */
  3978. #ifndef __386BSD__
  3979. #ifndef __FreeBSD__
  3980. #ifndef HPUX10
  3981. #ifndef IRIX51                /* SGI IRIX 5.1 or later */
  3982. #ifndef CK_SCOV5            /* SCO Open Server 5.0 */
  3983. #define LFDEVNO
  3984. #endif /* CK_SCOV5 */
  3985. #endif /* IRIX51 */
  3986. #endif /* HPUX10 */
  3987. #endif /* __FreeBSD__ */
  3988. #endif /* __386BSD__ */
  3989. #endif /* BSD44 */
  3990. #endif /* AIXRS */
  3991. #endif /* LFDEVNO */            /* ... define it here or on CC */
  3992. #endif /* SVR4 */            /* command line. */
  3993.  
  3994. #ifdef COHERENT
  3995. #define LFDEVNO
  3996. #endif /* COHERENT */
  3997.  
  3998. /*
  3999.   For platforms where the lockfile name is made from inode/major/minor
  4000.   device number, as in SVR4.  Which, if we must have lockfiles at all, is
  4001.   by far the best format, since it eliminates all the confusion that stems
  4002.   from multiple names (or drivers) for the same port, not to mention
  4003.   symlinks.  It might even be a good idea to start using this form even
  4004.   on platforms where it's not supported, alongside the normal forms for those
  4005.   platforms, in order to get people used to it...
  4006. */
  4007. #ifdef LFDEVNO
  4008. #ifndef major                /* If we didn't find it */
  4009. #ifdef SVR4                /* then for Sys V R4 */
  4010. #include <sys/mkdev.h>            /* look here */
  4011. #else                    /* or for SunOS versions */
  4012. #ifdef SUNOS4                /* ... */
  4013. #include <sys/sysmacros.h>        /* look here */
  4014. #else                    /* Otherwise take a chance: */
  4015. #define    major(dev) ( (int) ( ((unsigned)(dev) >> 8) & 0xff))
  4016. #define    minor(dev) ( (int) ( (dev) & 0xff))
  4017. #endif /* SUNOS4 */
  4018. #endif /* SVR4 */
  4019. #endif /* major */
  4020. #endif /* LFDEVNO */
  4021.  
  4022. /* No advisory locks if F_TLOCK and F_ULOCK are not defined at this point */
  4023.  
  4024. #ifdef LOCKF
  4025. #ifndef F_TLOCK
  4026. #undef LOCKF
  4027. #ifndef NOLOCKF
  4028. #define NOLOCKF
  4029. #endif /* NOLOCKF */
  4030. #endif /* F_TLOCK */
  4031. #endif /* LOCKF */
  4032.  
  4033. #ifdef LOCKF
  4034. #ifndef F_ULOCK
  4035. #undef LOCKF
  4036. #ifndef NOLOCKF
  4037. #define NOLOCKF
  4038. #endif /* NOLOCKF */
  4039. #endif /* F_ULOCK */
  4040. #endif /* LOCKF */
  4041.  
  4042. static char linkto[DEVNAMLEN+1];
  4043. static char * linkdev = NULL;
  4044.  
  4045. #ifndef NOUUCP
  4046. #ifdef USETTYLOCK
  4047. char * uucplockdir = "";
  4048. #else
  4049. #ifdef LOCK_DIR
  4050. char * uucplockdir = LOCK_DIR;
  4051. #else
  4052. char * uucplockdir = "";
  4053. #endif /* LOCK_DIR */
  4054. #endif /* USETTYLOCK */
  4055. #else
  4056. char * uucplockdir = "";
  4057. #endif /* NOUUCP */
  4058.  
  4059. #ifdef QNX
  4060. int                    /* Visible to outside world */
  4061. qnxopencount() {            /* Get QNX device open count */
  4062.     struct _dev_info_entry info;
  4063.     int x;
  4064.  
  4065.     x = -1;                /* Unknown */
  4066.     if (ttyfd > -1) {
  4067.     if (!dev_info(ttyfd, &info)) {
  4068.         debug(F101,"ttlock QNX open_count","",info.open_count);
  4069.         x = info.open_count;
  4070.     }
  4071.     }
  4072.     return(x);
  4073. }
  4074. #endif /* QNX */
  4075.  
  4076. static int
  4077. ttlock(ttdev) char *ttdev; {
  4078.  
  4079.     int x, n;
  4080.     int islink = 0;
  4081.  
  4082. #ifdef NOUUCP
  4083. #ifdef QNX
  4084.     extern int qnxportlock;
  4085.  
  4086.     if ((x = qnxopencount()) < 0)
  4087.       return(x);
  4088.     if (x > 1) {            /* 1 = me */
  4089.     if (qnxportlock)
  4090.       return(-2);            /* Indicate device is in use */
  4091.     else if (!quiet)
  4092.       printf("WARNING: \"%s\" looks busy...\n",ttdev);
  4093.     }
  4094. #endif /* QNX */
  4095.     strcpy(flfnam,"NOLOCK");
  4096.     haslock = 1;
  4097.     return(0);
  4098. #else /* !NOUUCP */
  4099.  
  4100. #ifdef USETTYLOCK
  4101.     haslock = 0;                        /* Not locked yet. */
  4102.     *flfnam = '\0';            /* Lockfile name is empty. */
  4103.     if (!strncmp(ttdev,"/dev/",5) && ttdev[5])
  4104.       ckstrncpy(lockname,ttdev+5,DEVNAMLEN);
  4105.     else
  4106.       ckstrncpy(lockname,ttdev,DEVNAMLEN);
  4107. /*
  4108.   This might be overkill, but it's not clear from the man pages whether
  4109.   ttylock() can be called without calling ttylocked() first, since the doc
  4110.   says that ttylocked() removes any stale lockfiles, but it does not say this
  4111.   about ttylock().  Also the docs don't say what ttylocked() returns in the
  4112.   case when it finds and removes a stale lockfile.  So one or both calls to
  4113.   to ttylocked() might be superfluous, but they should do no harm.  Also I'm
  4114.   assuming that we have to do all the same ID swapping, etc, with these
  4115.   routines as we do without them.  Thus the priv_on/off() sandwich.
  4116. */
  4117. #ifdef USE_UU_LOCK
  4118.     priv_on();                /* Turn on privs */
  4119.     x = uu_lock(lockname);        /* Try to set the lock */
  4120.     priv_off();                /* Turn privs off */
  4121.     debug(F111,"ttlock uu_lock",lockname,x);
  4122.     switch (x) {
  4123.       case UU_LOCK_INUSE:
  4124.     return(-2);
  4125.       case UU_LOCK_OK:
  4126. #ifdef BSD44
  4127.     sprintf(flfnam,"/var/spool/lock/LCK..%s",lockname);
  4128. #endif /* BSD44 */
  4129.     haslock = 1;
  4130.     return(0);
  4131.       default:
  4132.     return(-1);
  4133.     }
  4134. #else  /* USE_UU_LOCK */
  4135.     priv_on();                /* Turn on privs */
  4136.     if (ttylocked(lockname)) {        /* This should remove any stale lock */
  4137.     if (ttylocked(lockname)) {    /* so check again. */
  4138.         priv_off();
  4139.         return(-5);            /* Still locked, fail. */
  4140.     }
  4141.     }
  4142.     x = ttylock(lockname);        /* Lock it. */
  4143.     priv_off();                /* Turn off privs */
  4144.  
  4145.     debug(F111,"ttlock lockname",lockname,x);
  4146.     if (x > -1) {
  4147.     /*
  4148.       We don't really know the name of the lockfile, but
  4149.       this is what the man page says it is.  In USETTYLOCK
  4150.           builds, it is used only for display by SHOW COMM.
  4151.     */
  4152.     sprintf(flfnam,"/etc/locks/LCK..%s",lockname);
  4153.     haslock = 1;
  4154.     }
  4155.     return(x);
  4156. #endif /* USE_UU_LOCK */
  4157. #else  /* Systems that don't have ttylock()... */
  4158.  
  4159. #ifndef HPUX
  4160.  
  4161.     int lockfd;                /* File descriptor for lock file. */
  4162.     PID_T pid;                /* Process id of this process. */
  4163.     int tries;                /* How many times we've tried... */
  4164.     struct stat devbuf;            /* For device numbers (SVR4). */
  4165.  
  4166. #ifdef PIDSTRING
  4167.     char pid_str[12];            /* My pid in string format. */
  4168. #endif /* PIDSTRING */
  4169.  
  4170.     char *device, *devname;
  4171.  
  4172. #define LFNAML 50            /* Max length for lock file name. */
  4173.     char lockfil[LFNAML];        /* Lock file name */
  4174. #ifdef RTAIX
  4175.     char lklockf[LFNAML];        /* Name for link to lock file  */
  4176. #endif /* RTAIX */
  4177. #ifdef CKSYMLINK
  4178.     char symlock[LFNAML];        /* Name for symlink lockfile name */
  4179. #endif /* CKSYMLINK */
  4180.     char tmpnam[LFNAML+30];        /* Temporary lockfile name. */
  4181.     char *lockdir = LOCK_DIR;        /* Defined near top of this file, */
  4182.                     /* or on cc command line. */
  4183.     haslock = 0;                        /* Not locked yet. */
  4184.     *flfnam = '\0';            /* Lockfile name is empty. */
  4185.     lock2[0] = '\0';            /* Clear secondary lockfile name. */
  4186.     pid = getpid();            /* Get id of this process. */
  4187.  
  4188. /*  Construct name of lockfile and temporary file */
  4189.  
  4190. /*  device  = name of tty device without the path, e.g. "ttyh8" */
  4191. /*  lockfil = name of lock file, without path, e.g. "LCK..ttyh8" */
  4192.  
  4193.     device = ((devname = xxlast(ttdev,'/')) != NULL ? devname+1 : ttdev);
  4194.  
  4195.     if (stat(ttdev,&devbuf) < 0)
  4196.       return(-1);
  4197.  
  4198. #ifdef CKSYMLINK
  4199.     islink = 1;                /* Assume it's a symlink */
  4200.     linkto[0] = '\0';            /* But we don't know to what */
  4201. #ifdef COMMENT
  4202. /*
  4203.   This is undependable.  If it worked it would save the readlink call if
  4204.   we knew the device name was not a link.
  4205. */
  4206. #ifdef S_ISLNK
  4207.     islink = S_ISLNK(devbuf.st_mode);
  4208.     debug(F101,"ttlock stat S_ISLNK","",islink);
  4209. #endif /* S_ISLNK */
  4210. #endif /* COMMENT */
  4211.     if (islink) {
  4212.     n = readlink(ttdev,linkto,DEVNAMLEN); /* See if it's a link */
  4213.     debug(F111,"ttlock readlink",ttdev,n);
  4214.     if (n > -1)            /* It is */
  4215.       linkto[n] = '\0';
  4216.     else                /* It's not */
  4217.       islink = 0;
  4218.     debug(F111,"ttlock link",linkto,islink);
  4219.     }
  4220.     if (islink) {
  4221.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  4222.     debug(F110,"ttlock linkdev",linkdev,0);
  4223.     }
  4224. #endif /* CKSYMLINK */
  4225.  
  4226. /*
  4227.   On SCO platforms, if we don't have a symlink, then let's pretend the
  4228.   name given for the device is a symlink, because later we will change
  4229.   the name if it contains any uppercase characters.
  4230. */
  4231. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  4232.     if (!islink) {
  4233.     islink = 1;
  4234.     ckstrncpy(linkto,ttdev,DEVNAMLEN);
  4235.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  4236.     debug(F110,"ttlock linkdev",linkdev,0);
  4237.     }
  4238. #else
  4239. #ifdef M_XENIX                /* SCO Xenix or UNIX */
  4240.     if (!islink) {
  4241.     islink = 1;
  4242.     ckstrncpy(linkto,ttdev,DEVNAMLEN);
  4243.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  4244.     debug(F110,"ttlock linkdev",linkdev,0);
  4245.     }
  4246. #endif /* M_XENIX */
  4247. #endif /* CK_SCOV5 */
  4248.  
  4249. #ifdef ISIII                /* Interactive System III, PC/IX */
  4250.     ckstrncpy(lockfil, device, DEVNAMLEN);
  4251. #else  /* not ISIII */
  4252. #ifdef LFDEVNO                /* Lockfilename has device numbers. */
  4253. #ifdef COHERENT
  4254.     sprintf(lockfil,"LCK..%d.%d",
  4255.         major(devbuf.st_rdev),       /* major device number */
  4256.         0x1f & minor(devbuf.st_rdev)); /* minor device number */
  4257. #else
  4258.     sprintf(lockfil,"LK.%03d.%03d.%03d",
  4259.         major(devbuf.st_dev),    /* inode */
  4260.         major(devbuf.st_rdev),    /* major device number */
  4261.         minor(devbuf.st_rdev));    /* minor device number */
  4262. #endif /* COHERENT */
  4263. #else                    /* Others... */
  4264. #ifdef PTX                /* Dynix PTX */
  4265.     if (device != &ttdev[5] && strncmp(ttdev,"/dev/",5)==0) {
  4266.     sprintf(lockfil,"LCK..%.3s%s", &ttdev[5], device);
  4267.     } else
  4268. #endif /* PTX */
  4269.     sprintf(lockfil,"LCK..%s", device);
  4270. #ifdef RTAIX
  4271.     ckstrncpy(lklockf,device,DEVNAMLEN);
  4272. #endif /* RTAIX */
  4273. #ifdef CKSYMLINK
  4274.     symlock[0] = '\0';
  4275.     if (islink)
  4276.       sprintf(symlock,"LCK..%s", linkdev);
  4277. #endif /* CKSYMLINK */
  4278. #endif /* LFDEVNO */
  4279. #endif /* ISIII */
  4280.  
  4281. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  4282.     {
  4283.     /* Lowercase the entire filename. */
  4284.         /* SCO says we must do this in V5.0 and later. */
  4285.     /* BUT... watch out for devices -- like Digiboard Portserver */
  4286.     /* That can have hundreds of ports... */
  4287.     char *p = (char *)(lockfil + 5);
  4288.     while (*p) { if (isupper(*p)) *p = (char) tolower(*p); p++; }
  4289.     }
  4290. #ifdef CKSYMLINK
  4291.     if (islink) {            /* If no change */
  4292.     if (!strcmp(lockfil,symlock)) {    /* then no second lockfile needed */
  4293.         islink = 0;
  4294.         symlock[0] = '\0';
  4295.     }
  4296.     }
  4297. #endif /* CKSYMLINK */
  4298. #else
  4299. #ifdef M_XENIX                /* SCO Xenix or UNIX */
  4300.     {
  4301.     int x; char c;
  4302.     x = (int)strlen(lockfil) - 1;    /* Get last letter of device name. */
  4303.     if (x > 0) {            /* If it's uppercase, lower it. */
  4304.         c = lockfil[x];
  4305.         if (c >= 'A' && c <= 'Z') lockfil[x] += ('a' - 'A');
  4306.     }
  4307.     }
  4308. #ifdef CKSYMLINK
  4309.     if (islink) {
  4310.     if (!strcmp(lockfil,symlock)) {    /* No change */
  4311.         islink = 0;            /* so no second lockfile */
  4312.         symlock[0] = '\0';
  4313.     }
  4314.     }
  4315. #endif /* CKSYMLINK */
  4316. #endif /* M_XENIX */
  4317. #endif /* CK_SCOV5 */
  4318.  
  4319. /*  flfnam = full lockfile pathname, e.g. "/usr/spool/uucp/LCK..ttyh8" */
  4320. /*  tmpnam = temporary unique, e.g. "/usr/spool/uucp/LTMP..pid" */
  4321.  
  4322.     sprintf(flfnam,"%s/%s",lockdir,lockfil);
  4323. #ifdef RTAIX
  4324.     sprintf(lkflfn,"%s/%s",lockdir,lklockf);
  4325. #endif /* RTAIX */
  4326. #ifdef CKSYMLINK
  4327.     /* If it's a link then also make a lockfile for the real name */
  4328.     debug(F111,"ttlock link symlock",symlock,islink);
  4329.     if (islink && symlock[0]) {
  4330.     /* But only if the lockfile names would be different. */
  4331.     /* WARNING: They won't be, e.g. for /dev/ttyd2 => /hw/ttys/ttyd2 */
  4332.     sprintf(lock2,"%s/%s",lockdir,symlock); /* No, make 2nd lockfile */
  4333.     debug(F110,"ttlock lock2",lock2,0);
  4334.     if (!strcmp(lock2,flfnam)) {    /* Are lockfile names the same? */
  4335.         debug(F100,"ttlock lock2 cleared","",0);
  4336.         lock2[0] = '\0';        /* Clear secondary lockfile name. */
  4337.     }
  4338.     }
  4339. #endif /* CKSYMLINK */
  4340.     sprintf(tmpnam,"%s/LTMP.%05d",lockdir,(int) pid);
  4341.     debug(F110,"ttlock flfnam",flfnam,0);
  4342.     debug(F110,"ttlock tmpnam",tmpnam,0);
  4343.  
  4344.     priv_on();                /* Turn on privileges if possible. */
  4345.     lockfd = creat(tmpnam, 0444);    /* Try to create temp lock file. */
  4346.     if (lockfd < 0) {            /* Create failed. */
  4347.     debug(F111,"ttlock creat failed",tmpnam,errno);
  4348.     if (errno == ENOENT) {
  4349.         perror(lockdir);
  4350.         printf("UUCP not installed or Kermit misconfigured\n");
  4351.     } else {
  4352.         if (!quiet)
  4353.           perror(lockdir);
  4354.         unlink(tmpnam);        /* Get rid of the temporary file. */
  4355.     }
  4356.     priv_off();            /* Turn off privileges!!! */
  4357.     return(-1);            /* Return failure code. */
  4358.     }
  4359. /* Now write the pid into the temp lockfile in the appropriate format */
  4360.  
  4361. #ifdef PIDSTRING            /* For Honey DanBer UUCP, */
  4362.     sprintf(                /* write PID as decimal string */
  4363.         pid_str,
  4364. #ifdef LINUXFSSTND            /* The "Linux File System Standard" */
  4365. #ifdef FSSTND10                /* Version 1.0 calls for */
  4366.         "%010d\n",            /* leading zeros */
  4367. #else                    /* while version 1.2 calls for */
  4368.         "%10d\n",            /* leading spaces */
  4369. #endif /* FSSTND10 */
  4370. #else
  4371. #ifdef COHERENT
  4372.         "%d\n",            /* with leading nothing */
  4373. #else
  4374.         "%10d\n",            /* with leading blanks */
  4375. #endif /* COHERENT */
  4376. #endif /* LINUXFSSTND */
  4377.         (int) pid
  4378.         );
  4379.     write(lockfd, pid_str, 11);
  4380.     debug(F111,"ttlock hdb pid string",pid_str,(int) pid);
  4381.  
  4382. #else /* Not PIDSTRING, use integer PID */
  4383.  
  4384.     write(lockfd, (char *)&pid, sizeof(pid) );
  4385.     debug(F101,"ttlock pid","",(int) pid);
  4386.  
  4387. #endif /* PIDSTRING */
  4388.  
  4389. /* Now try to rename the temp file to the real lock file name. */
  4390. /* This will fail if a lock file of that name already exists.  */
  4391.  
  4392.     close(lockfd);            /* Close the temp lockfile. */
  4393.     chmod(tmpnam,0444);            /* Permission for a valid lock. */
  4394.     tries = 0;
  4395.     while (!haslock && tries++ < 2) {
  4396.     haslock = (link(tmpnam,flfnam) == 0); /* Create a link to it. */
  4397.     if (haslock) {                  /* If we got the lockfile */
  4398. #ifdef RTAIX
  4399.         link(flfnam,lkflfn);
  4400. #endif /* RTAIX */
  4401. #ifdef CKSYMLINK
  4402.         if (islink && lock2[0])
  4403.           link(flfnam,lock2);
  4404. #endif /* CKSYMLINK */
  4405.  
  4406. #ifdef LOCKF
  4407. /*
  4408.   Advisory file locking works on SVR4, so we use it.  In fact, it is
  4409.   necessary in some cases, e.g. when SLIP is involved.  But it still doesn't
  4410.   seem to prevent multiple users accessing the same device by different names.
  4411. */
  4412.             while (lockf(ttyfd, F_TLOCK, 0L) != 0) {
  4413.                 debug(F111, "ttlock: lockf returns errno", "", errno);
  4414.                 if ((++tries >= 3) || (errno != EAGAIN)) {
  4415.                     x = unlink(flfnam); /* remove the lockfile */
  4416. #ifdef RTAIX
  4417.             unlink(lkflfn);    /* And any links to it... */
  4418. #endif /* RTAIX */
  4419. #ifdef CKSYMLINK
  4420.             if (islink && lock2[0])
  4421.               unlink(lock2);    /* ditto... */
  4422. #endif /* CKSYMLINK */
  4423.                     debug(F111,"ttlock unlink",flfnam,x);
  4424.                     haslock = 0;
  4425.             break;
  4426.         }
  4427.                 sleep(2);
  4428.         }
  4429.         if (haslock)        /* If we got an advisory lock */
  4430. #endif /* LOCKF */
  4431.           break;            /* We're done. */
  4432.  
  4433.     } else {            /* We didn't create a new lockfile. */
  4434.         priv_off();
  4435.         if (ttchkpid(flfnam)) {    /* Check existing lockfile */
  4436.         priv_on();        /* cause ttchkpid turns priv_off... */
  4437.         unlink(tmpnam);        /* Delete the tempfile */
  4438.         debug(F100,"ttlock found tty locked","",0);
  4439.         priv_off();        /* Turn off privs */
  4440.         return(-2);        /* Code for device is in use. */
  4441.         }
  4442.         priv_on();
  4443.     }
  4444.     }
  4445.     unlink(tmpnam);            /* Unlink (remove) the temp file. */
  4446.     priv_off();                /* Turn off privs */
  4447.     return(haslock ? 0 : -1);        /* Return link's return code. */
  4448.  
  4449. #else /* HPUX */
  4450.  
  4451. /*
  4452.   HP-UX gets its own copy of this routine, modeled after the observed behavior
  4453.   of the HP-UX 'cu' program.  HP-UX serial device names consist of a base name
  4454.   such as "tty", "ttyd", "cua", "cul", "cuad", or "culd", followed by a unit
  4455.   designator which is a string of digits, possibly containing an imbedded
  4456.   letter "p".  Examples (for base name "tty"):
  4457.  
  4458.      /dev/tty0, /dev/tty00, dev/ttyd00, /dev/tty0p0
  4459.  
  4460.   According to the HP-UX UUCP manual of 1988, the "0p0" notation has been
  4461.   used on Series 800 since HP-UX 2.00, and the "non-p" notation was used
  4462.   on other models.  In HP-UX 10.00, "0p0" notation was adopted for all models.
  4463.   However, we make and enforce no such distinctions; either notation is
  4464.   accepted on any model or HP-UX version as a valid unit designator.
  4465.  
  4466.   If a valid unit is specified (as opposed to a designer name or symlink), we
  4467.   check for all aliases of the given unit according to the devprefix[] array.
  4468.   If no lockfiles are found for the given unit, we can have the device; we
  4469.   create a lockfile LCK..name in the lockfile directory appropriate for the
  4470.   HP-UX version (/var/spool/locks for 10.00 and later, /usr/spool/uucp for
  4471.   9.xx and earlier).  If it is a "cua" or "cul" device, a second lockfile is
  4472.   created with the "ttyd" prefix.  This is exactly what cu does.
  4473.  
  4474.   If the "set line" device does not have a valid unit designator, then it is
  4475.   used literally and no synomyms are searched for and only one lockfile is
  4476.   created.
  4477.  
  4478.   -fdc, March 1998.
  4479. */
  4480. #define LFNAML 80            /* Max length for lock file name. */
  4481.  
  4482.     int lockfd;                /* File descriptor for lock file. */
  4483.     PID_T pid;                /* Process ID of this process. */
  4484.     int fpid;                /* pid found in existing lockfile. */
  4485.     int tries;                /* How many times we've tried... */
  4486.     int i, k;                /* Workers */
  4487.  
  4488.     char *device, *devname;        /* "/dev/xxx", "xxx" */
  4489.     char *unit, *p;            /* <instance>p<port> part of xxx */
  4490.  
  4491.     char lockfil[LFNAML];        /* Lockfile name (no path) */
  4492.     char tmpnam[LFNAML];        /* Temporary lockfile name. */
  4493.  
  4494. #ifdef HPUX10                /* Lockfile directory */
  4495.     char *lockdir = "/var/spool/locks";    /* Always this for 10.00 and higher */
  4496. #else  /* HP-UX 9.xx and below */
  4497. #ifdef LOCK_DIR
  4498.     char *lockdir = LOCK_DIR;        /* Defined near top of this file */
  4499. #else
  4500.     char *lockdir = "/usr/spool/uucp";    /* or not... */
  4501. #endif /* LOCK_DIR */
  4502. #endif /* HPUX10 */
  4503.  
  4504.     haslock = 0;                        /* Not locked yet. */
  4505.     *flfnam = '\0';            /* Lockfile name is empty. */
  4506.     lock2[0] = '\0';            /* Second one too. */
  4507.     pid = getpid();            /* Get my process ID */
  4508. /*
  4509.   Construct name of lockfile and temporary file...
  4510.   device  = name of tty device without the path, e.g. "tty0p0"
  4511.   lockfil = name of lock file, without path, e.g. "LCK..tty0p0"
  4512. */
  4513.     device = ((devname = xxlast(ttdev,'/')) != NULL ? devname+1 : ttdev);
  4514.     debug(F110,"TTLOCK device",device,0);
  4515.     sprintf(lockfil,"LCK..%s", device);
  4516.  
  4517.     k = 0;                /* Assume device is not locked */
  4518.     n = 0;                /* Digit counter */
  4519.     unit = device;            /* Unit = <instance>p<port> */
  4520.     while (*unit && !isdigit(*unit))    /* Search for digit... */
  4521.       unit++;
  4522.     p = unit;                /* Verify <num>p<num> format... */
  4523.     debug(F110,"TTLOCK unit 1",unit,0);
  4524. /*
  4525.   The unit number is recognized as:
  4526.   (a) any sequence of digits that runs to the end of the string.
  4527.   (b) any (a) that includes one and only one letter "p", with at least
  4528.       one digit before and after it.
  4529. */
  4530.     while (isdigit(*p)) p++, n++;    /* Get a run of digits */
  4531.     if (*p && n > 0) {            /* Have a "p"? */
  4532.     if (*p == 'p' && isdigit(*(p+1))) {
  4533.         p++;
  4534.         n = 0;
  4535.         while (isdigit(*p)) p++, n++;
  4536.     }
  4537.     }
  4538.     if (n == 0 || *p) unit = "";
  4539.     debug(F110,"TTLOCK unit 2",unit,0);
  4540.  
  4541.     if (*unit) {            /* Device name has unit number. */
  4542.     /* The following loop not only searches for the various lockfile    */
  4543.     /* synonyms, but also removes all -- not just one -- stale lockfile */
  4544.     /* for the device, should there be more than one.  See ttchkpid().  */
  4545.     ttydexists = 0;
  4546.     for (i = 0; *devprefix[i]; i++) { /* For each driver... */
  4547.         /* Make device name */
  4548.         sprintf(lock2,"/dev/%s%s",devprefix[i],unit);
  4549.         priv_on();            /* Privs on */
  4550.         k = zchki(lock2) != -1;    /* See if device exists */
  4551.         priv_off();            /* Privs off */
  4552.         debug(F111,"TTLOCK exist",lock2,k);
  4553.             if (k) {
  4554.         if (!strcmp(devprefix[i],"ttyd")) /* ttyd device exists */
  4555.           ttydexists = 1;
  4556.         /* Make lockfile name */
  4557.         sprintf(lock2,"%s/LCK..%s%s",lockdir,devprefix[i],unit);
  4558.         debug(F110,"TTLOCK checking",lock2,0);
  4559.         priv_on();        /* Privs on */
  4560.         k = zchki(lock2) != -1;    /* See if lockfile exists */
  4561.         priv_off();        /* Privs off */
  4562.         debug(F111,"TTLOCK check for lock A",lock2,k);
  4563.         if (k) if (ttchkpid(lock2)) { /* If pid still active, fail. */
  4564.             ckstrncpy(flfnam,lock2,FLFNAML);
  4565.             return(-2);
  4566.         }
  4567.         }
  4568.     }
  4569.     } else {                /* Some other device-name format */
  4570.     /* This takes care of symbolic links, etc... */
  4571.     /* But does not chase them down! */
  4572.     sprintf(lock2,"%s/LCK..%s",lockdir,device); /* Use the name as-is */
  4573.     priv_on();
  4574.     k = zchki(lock2) != -1;        /* Check for existing lockfile */
  4575.     priv_off();
  4576.     debug(F111,"TTLOCK check for lock B",lock2,k);
  4577.     if (k) if (ttchkpid(lock2)) {    /* Check pid from lockfile */
  4578.         ckstrncpy(flfnam,lock2,FLFNAML);
  4579.         debug(F110,"TTLOCK in use",device,0);
  4580.         debug(F101,"TTLOCK returns","",-2);
  4581.         return(-2);
  4582.     }
  4583.     }
  4584. /*
  4585.   Get here only if there is no (more) lockfile, so now we make one (or two)...
  4586.   flfnam = full lockfile pathname, e.g. "/usr/spool/uucp/LCK..cul0p0".
  4587.   tmpnam = unique temporary filname, e.g. "/usr/spool/uucp/LTMP..pid".
  4588. */
  4589.     sprintf(flfnam,"%s/%s",lockdir,lockfil); /* Our SET LINE device */
  4590.  
  4591.     /* If dialout device, also make one for corresponding dialin device */
  4592.     lock2[0] = '\0';
  4593.     if (!strncmp(device,"cu",2) && *unit && ttydexists)
  4594.       sprintf(lock2, "%s/LCK..ttyd%s", lockdir, unit);
  4595.  
  4596.     sprintf(tmpnam,"%s/LTMP.%05d",lockdir,(int) pid); /* Make temporary name */
  4597. #ifdef DEBUG
  4598.     if (deblog) {
  4599.     debug(F110,"TTLOCK flfnam",flfnam,0);
  4600.     debug(F110,"TTLOCK lock2",lock2,0);
  4601.     debug(F110,"TTLOCK tmpnam",tmpnam,0);
  4602.     }
  4603. #endif /* DEBUG */
  4604. /*
  4605.    Lockfile permissions...
  4606.    444 is standard, HP-UX 10.00 uses 664.  It doesn't matter.
  4607.    Kermit uses 444; the difference lets us tell whether Kermit created
  4608.    the lock file.
  4609. */
  4610.     priv_on();                /* Turn on privileges. */
  4611.     lockfd = creat(tmpnam, 0444);    /* Try to create temporary file. */
  4612.     if (lockfd < 0) {            /* Create failed. */
  4613.     debug(F111,"TTLOCK creat failed",tmpnam,errno);
  4614.     if (errno == ENOENT) {
  4615.         perror(lockdir);
  4616.         printf("UUCP not installed or Kermit misconfigured\n");
  4617.     } else {
  4618.         if (!quiet)
  4619.           perror(lockdir);
  4620.         unlink(tmpnam);        /* Get rid of the temporary file. */
  4621.     }
  4622.     priv_off();            /* Turn off privileges!!! */
  4623.     debug(F101,"TTLOCK returns","",-1);
  4624.     return(-1);            /* Return failure code. */
  4625.     }
  4626.     debug(F110,"TTLOCK temp ok",tmpnam,0);
  4627.  
  4628. /* Now write our pid into the temp lockfile in integer format. */
  4629.  
  4630.     i = write(lockfd, (char *)&pid, sizeof(pid));
  4631.  
  4632. #ifdef DEBUG
  4633.     if (deblog) {
  4634.     debug(F101,"TTLOCK pid","",pid);
  4635.     debug(F101,"TTLOCK sizeof pid","",sizeof(pid));
  4636.     debug(F101,"TTLOCK write pid returns","",i);
  4637.     }
  4638. #endif /* DEBUG */
  4639.  
  4640. /*
  4641.   Now try to rename the temporary file to the real lockfile name.
  4642.   This will fail if a lock file of that name already exists, which
  4643.   will catch race conditions with other users.
  4644. */
  4645.     close(lockfd);            /* Close the temp lockfile. */
  4646.     chmod(tmpnam,0444);
  4647.  
  4648.     tries = 0;
  4649.     while (!haslock && tries++ < 2) {
  4650.     haslock = (link(tmpnam,flfnam) == 0); /* Create a link to it. */
  4651.     debug(F101,"TTLOCK link","",haslock);
  4652.     if (haslock) {            /* If we made the lockfile... */
  4653.  
  4654. #ifdef LOCKF                /* Can be canceled with -DNOLOCKF */
  4655. /*
  4656.   Create an advisory lock on the device through its file descriptor.
  4657.   This code actually seems to work.  If it is executed, and then another
  4658.   process tries to open the same device under a different name to circumvent
  4659.   the lockfile, they get a "device busy" error.
  4660. */
  4661.         debug(F100,"TTLOCK LOCKF code...","",0);
  4662.             while ( lockf(ttyfd, F_TLOCK, 0L) != 0 ) {
  4663.                 debug(F111, "TTLOCK lockf error", "", errno);
  4664.                 if ((++tries >= 3) || (errno != EAGAIN)) {
  4665.                     x = unlink(flfnam); /* Remove the lockfile */
  4666.             if (errno == EACCES && !quiet)
  4667.               printf("Device already locked by another process\n");
  4668.                     haslock = 0;
  4669.             break;
  4670.         }
  4671.                 sleep(2);
  4672.         }
  4673. #endif /* LOCKF */
  4674.  
  4675.         if (haslock) {        /* If we made the lockfile ... */
  4676.         if (lock2[0]) {        /* if there is to be a 2nd lockfile */
  4677.             lockfd = creat(lock2, 0444); /* Create it */
  4678.             debug(F111,"TTLOCK lock2 creat", lock2, lockfd);
  4679.             if (lockfd > -1) {    /* Created OK, write pid. */
  4680.             write(lockfd, (char *)&pid, sizeof(pid) );
  4681.             close(lockfd);    /* Close and */
  4682.             chmod(lock2, 0444); /* set permissions. */
  4683.             } else {         /* Not OK, but don't fail. */
  4684.             lock2[0] = '\0'; /* Just remember it's not there. */
  4685.             }
  4686.         }
  4687.         break;            /* and we're done. */
  4688.         }
  4689.     }
  4690.     }
  4691.     unlink(tmpnam);            /* Unlink (remove) the temp file. */
  4692.     priv_off();                /* Turn off privs */
  4693.     i = haslock ? 0 : -1;        /* Our return value */
  4694.     debug(F101,"TTLOCK returns","",i);
  4695.     return(i);
  4696. #endif /* HPUX */
  4697. #endif /* USETTYLOCK */
  4698. #endif /* !NOUUCP */
  4699. }
  4700.  
  4701. /*  T T U N L O C K  */
  4702.  
  4703. static int
  4704. ttunlck() {                             /* Remove UUCP lockfile(s). */
  4705. #ifndef NOUUCP
  4706.     int x;
  4707.  
  4708.     debug(F111,"ttunlck",flfnam,haslock);
  4709.  
  4710. #ifdef USETTYLOCK
  4711.  
  4712.     if (haslock && *flfnam) {
  4713.     int x;
  4714.     priv_on();            /* Turn on privs */
  4715. #ifdef USE_UU_LOCK
  4716.     x = uu_unlock(lockname);
  4717. #else  /* USE_UU_LOCK */
  4718.     x = ttyunlock(lockname);    /* Try to unlock */
  4719. #endif /* USE_UU_LOCK */
  4720.     priv_off();            /* Turn off privs */
  4721.     if (x < 0 && !quiet)
  4722.       printf("Warning - Can't remove lockfile: %s\n", flfnam);
  4723.  
  4724.     *flfnam = '\0';            /* Erase the name. */
  4725.     haslock = 0;
  4726.     return(0);
  4727.     }
  4728.  
  4729. #else  /* No ttylock()... */
  4730.  
  4731.     if (haslock && *flfnam) {
  4732.     /* Don't remove lockfile if we didn't make it ourselves */
  4733.     if ((x = ttrpid(flfnam)) != (int)getpid()) {
  4734.         debug(F111,"ttunlck lockfile seized",flfnam,x);
  4735.         printf("Warning - Lockfile %s seized by pid %d\n",
  4736.            flfnam,
  4737.            x
  4738.            );
  4739.         return(0);
  4740.     }
  4741.     priv_on();            /* Turn privileges on.  */
  4742.     errno = 0;
  4743.     x = unlink(flfnam);        /* Remove the lockfile. */
  4744.     debug(F111,"ttunlck unlink",flfnam,x);
  4745.     if (x < 0) {
  4746.         if (errno && !quiet)
  4747.           perror(ttnmsv);
  4748.         printf("Warning - Can't remove lockfile: %s\n", flfnam);
  4749.     }
  4750.     haslock = 0;
  4751.     *flfnam = '\0';            /* Erase the name. */
  4752.  
  4753. #ifdef RTAIX
  4754.     errno = 0;
  4755.     x = unlink(lkflfn);        /* Remove link to lockfile */
  4756.     debug(F111,"ttunlck AIX link unlink",lkflfn,x);
  4757.     if (x < 0) {
  4758.         if (errno && !quiet)
  4759.           perror(ttnmsv);
  4760.         printf("Warning - Can't remove link to lockfile: %s\n", lkflfn);
  4761.     }
  4762.     *lkflfn = '\0';
  4763. #else
  4764.     if (lock2[0]) {            /* If there is a second lockfile, */
  4765.         errno = 0;
  4766.         x = unlink(lock2);        /*  remove it too. */
  4767.         debug(F111,"ttunlck lock2 unlink",lock2,x);
  4768.         if (x < 0) {
  4769.         if (errno && !quiet)
  4770.           perror(ttnmsv);
  4771.         printf("Warning - Can't remove secondary lockfile: %s\n",
  4772.                lock2
  4773.                );
  4774.         }
  4775.         lock2[0] = '\0';        /* Forget its name. */
  4776.     }
  4777. #endif /* RTAIX */
  4778.  
  4779. #ifdef LOCKF
  4780.         (VOID) lockf(ttyfd, F_ULOCK, 0L); /* Remove advisory lock */
  4781. #endif /* LOCKF */
  4782.     priv_off();            /* Turn privileges off. */
  4783.     }
  4784. #endif /* USETTYLOCK */
  4785. #endif /* !NOUUCP */
  4786.     return(0);
  4787. }
  4788.  
  4789. /*
  4790.   4.3BSD-style UUCP line direction control.
  4791.   (Stan Barber, Rice U, 1980-something...)
  4792. */
  4793. #ifndef NOUUCP
  4794. #ifdef ACUCNTRL
  4795. VOID
  4796. acucntrl(flag,ttname) char *flag, *ttname; {
  4797.     char x[DEVNAMLEN+32], *device, *devname;
  4798.  
  4799.     if (strcmp(ttname,CTTNAM) == 0 || xlocal == 0) /* If not local, */
  4800.       return;                /* just return. */
  4801.     device = ((devname = xxlast(ttname,'/')) != NULL ? devname+1 : ttname);
  4802.     if (strncmp(device,"LCK..",4) == 0) device += 5;
  4803.     sprintf(x,"/usr/lib/uucp/acucntrl %s %s",flag,device);
  4804.     debug(F110,"called ",x,0);
  4805.     zsyscmd(x);
  4806. }
  4807. #endif /* ACUCNTRL */
  4808. #endif /* NOUUCP */
  4809.  
  4810. /*
  4811.   T T H F L O W  --  Set or Reset hardware flow control.
  4812.  
  4813.   This is an attempt to collect all hardware-flow-control related code
  4814.   into a single module.  Thanks to Rick Sladkey and John Kohl for lots of
  4815.   help here.  Overview:
  4816.  
  4817.   Hardware flow control is not supported in many UNIX implementions.  Even
  4818.   when it is supported, there is no (ha ha) "standard" for the programming
  4819.   interface.  In general, 4.3BSD and earlier (sometimes), 4.4BSD, System V,
  4820.   SunOS, AIX, etc, have totally different methods.  (And, not strictly
  4821.   relevant here, the programming interface often brings one only to a no-op
  4822.   in the device driver!)
  4823.  
  4824.   Among all these, we have two major types of APIs: those in which hardware
  4825.   flow control is determined by bits in the same termio/termios/sgtty mode
  4826.   word(s) that are used for controlling such items as CBREAK vs RAW mode, and
  4827.   which are also used by the ttvt(), ttpkt(), conbin(), and concb() routines
  4828.   for changing terminal modes.  And those that use entirely different
  4829.   mechanisms.
  4830.  
  4831.   In the first category, it is important that any change in the mode bits be
  4832.   reflected in the relevant termio(s)/sgtty structure, so that subsequent
  4833.   changes to that structure do not wipe out the effects of this routine.  That
  4834.   is why a pointer, attrs, to the appropriate structure is passed as a
  4835.   parameter to this routine.
  4836.  
  4837.   The second category should give us no worries, since any changes to hardware
  4838.   flow control accomplished by this routine should not affect the termio(s)/
  4839.   sgtty structures, and therefore will not be undone by later changes to them.
  4840.  
  4841.   The second argument, status, means to turn on hardware flow control if
  4842.   nonzero, and to turn it off if zero.
  4843.  
  4844.   Returns: 0 on apparent success, -1 on probable failure.
  4845. */
  4846. static int
  4847. tthflow(flow, status, attrs)
  4848.     int flow,                /* Type of flow control (ckcdeb.h) */
  4849.     status;                /* Nonzero = turn it on */
  4850.                     /* Zero = turn it off */
  4851. #ifdef BSD44ORPOSIX            /* POSIX or BSD44 */
  4852.     struct termios *attrs;
  4853. #else                    /* System V */
  4854. #ifdef ATTSV
  4855. #ifdef ATT7300
  4856. #ifdef UNIX351M
  4857. /* AT&T UNIX 3.51m can set but not test for hardware flow control */
  4858. #define RTSFLOW CTSCD
  4859. #define CTSFLOW CTSCD
  4860. #endif /* ATT7300 */
  4861. #endif /* UNIX351M */
  4862.     struct termio *attrs;
  4863. #else                    /* BSD, V7, etc */
  4864.     struct sgttyb *attrs;        /* sgtty info... */
  4865. #endif /* ATTSV */
  4866. #endif /* BSD44ORPOSIX */
  4867. /* tthflow */ {
  4868.  
  4869.     int x = 0;                /* tthflow() return code */
  4870.  
  4871. #ifdef Plan9
  4872.     return p9tthflow(flow, status);
  4873. #else
  4874.  
  4875. #ifndef OXOS                /* NOT Olivetti X/OS... */
  4876. /*
  4877.   For SunOS 4.0 and later in the BSD environment ...
  4878.  
  4879.   The declarations are copied and interpreted from the System V header files,
  4880.   so we don't actually have to pull in all the System V junk when building
  4881.   C-Kermit for SunOS in the BSD environment, which would be dangerous because
  4882.   having those symbols defined would cause us to take the wrong paths through
  4883.   the code.  The code in this section is used in both the BSD and Sys V SunOS
  4884.   versions.
  4885. */
  4886. #ifdef SUNOS41
  4887. /*
  4888.   In SunOS 4.1 and later, we use the POSIX calls rather than ioctl calls
  4889.   because GNU CC uses different formats for the _IOxxx macros than regular CC;
  4890.   the POSIX forms work for both.  But the POSIX calls are not available in
  4891.   SunOS 4.0.
  4892. */
  4893. #define CRTSCTS 0x80000000        /* RTS/CTS flow control */
  4894. #define TCSANOW 0            /* Do it now */
  4895.  
  4896.     struct termios {
  4897.     unsigned long c_iflag;        /* Input modes */
  4898.     unsigned long c_oflag;        /* Output modes */
  4899.     unsigned long c_cflag;        /* Control modes */
  4900.     unsigned long c_lflag;        /* Line discipline modes */
  4901.     char c_line;
  4902.     CHAR c_cc[17];
  4903.     };
  4904.     struct termios temp;
  4905.  
  4906. _PROTOTYP( int tcgetattr, (int, struct termios *) );
  4907. _PROTOTYP( int tcsetattr, (int, int, struct termios *) );
  4908. /*
  4909.   When CRTSCTS is set, SunOS won't do output unless both CTS and CD are
  4910.   asserted.  So we don't set CRTSCTS unless CD is up.  This should be OK,
  4911.   since we don't need RTS/CTS during dialing, and after dialing is complete,
  4912.   we should have CD.  If not, we still communicate, but without RTS/CTS.
  4913. */
  4914.     int mflags;                /* Modem signal flags */
  4915.  
  4916. #ifdef NETCMD
  4917.     if (ttpipe) return(0);
  4918. #endif /* NETCMD */
  4919. #ifdef NETPTY
  4920.     if (ttpty) return(0);
  4921. #endif /* NETPTY */
  4922.  
  4923.     debug(F101,"tthflow SUNOS41 entry status","",status);
  4924.     if (!status) {            /* Turn hard flow off */
  4925.     if (tcgetattr(ttyfd, &temp) > -1 && /* Get device attributes */
  4926.         (temp.c_cflag & CRTSCTS)) { /* Check for RTS/CTS */
  4927.         temp.c_cflag &= ~CRTSCTS;    /* It's there, remove it */
  4928.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  4929.     }
  4930.     } else {                /* Turn hard flow on */
  4931.     if (ioctl(ttyfd,TIOCMGET,&mflags) > -1 && /* Get modem signals */
  4932.         (mflags & TIOCM_CAR)) {        /* Check for CD */
  4933.         debug(F100,"tthflow SunOS has CD","",0);
  4934.         if (tcgetattr(ttyfd, &temp) > -1 && /* Get device attributes */
  4935.         !(temp.c_cflag & CRTSCTS)) { /* Check for RTS/CTS */
  4936.         temp.c_cflag |= CRTSCTS;    /* Not there, add it */
  4937.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  4938.         }
  4939.     } else {
  4940.         x = -1;
  4941.         debug(F100,"tthflow SunOS no CD","",0);
  4942.     }
  4943.     }
  4944. #else
  4945. #ifdef QNX
  4946.     struct termios temp;
  4947. #ifdef NETCMD
  4948.     if (ttpipe) return(0);
  4949. #endif /* NETCMD */
  4950. #ifdef NETPTY
  4951.     if (ttpty) return(0);
  4952. #endif /* NETPTY */
  4953.     debug(F101,"tthflow QNX entry status","",status);
  4954.     if (tcgetattr(ttyfd, &temp) > -1) {    /* Get device attributes */
  4955.     if (!status) {            /* Turn hard flow off */
  4956.         if ((temp.c_cflag & (IHFLOW|OHFLOW)) == (IHFLOW|OHFLOW)) {
  4957.         temp.c_cflag &= ~(IHFLOW|OHFLOW); /* It's there, remove it */
  4958.         attrs->c_cflag &= ~(IHFLOW|OHFLOW);
  4959.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  4960.         }
  4961.     } else {            /* Turn hard flow on */
  4962.         if ((temp.c_cflag & (IHFLOW|OHFLOW)) != (IHFLOW|OHFLOW)) {
  4963.         temp.c_cflag |= (IHFLOW|OHFLOW); /* Not there, add it */
  4964.         temp.c_iflag &= ~(IXON|IXOFF);   /* Bye to IXON/IXOFF */
  4965.         ttraw.c_lflag |= IEXTEN;         /* Must be on */
  4966.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  4967.         attrs->c_cflag |= (IHFLOW|OHFLOW);
  4968.         attrs->c_iflag &= ~(IXON|IXOFF);
  4969.         }
  4970.     }
  4971.     } else {
  4972.     x = -1;
  4973.     debug(F100, "tthflow QNX getattr fails", "", 0);
  4974.     }
  4975. #else
  4976. #ifdef POSIX_CRTSCTS
  4977. /*
  4978.   POSIX_CRTSCTS is defined in ckcdeb.h or on CC command line.
  4979.   Note: Do not assume CRTSCTS is a one-bit field!
  4980. */
  4981.     struct termios temp;
  4982. #ifdef NETCMD
  4983.     if (ttpipe) return(0);
  4984. #endif /* NETCMD */
  4985. #ifdef NETPTY
  4986.     if (ttpty) return(0);
  4987. #endif /* NETPTY */
  4988.     debug(F101,"tthflow POSIX_CRTSCTS entry status","",status);
  4989.     errno = 0;
  4990.     x = tcgetattr(ttyfd, &temp);
  4991.     debug(F111,"tthflow POSIX_CRTSCTS tcgetattr",ckitoa(x),errno);
  4992.     errno = 0;
  4993.     if (x < 0) {
  4994.     x = -1;
  4995.     } else {
  4996.     if (!status) {            /* Turn hard flow off */
  4997.         if (
  4998. #ifdef COMMENT
  4999.         /* This can fail because of sign extension */
  5000.         /* e.g. in Linux where it's Bit 31 */
  5001.         (temp.c_cflag & CRTSCTS) == CRTSCTS
  5002. #else
  5003.         (temp.c_cflag & CRTSCTS) != 0
  5004. #endif /* COMMENT */
  5005.         ) {
  5006.         temp.c_cflag &= ~CRTSCTS;    /* It's there, remove it */
  5007.         attrs->c_cflag &= ~CRTSCTS;
  5008.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5009.         debug(F111,"tthflow POSIX_CRTSCTS OFF tcsetattr",
  5010.               ckitoa(x),errno);
  5011.         }
  5012.     } else {            /* Turn hard flow on */
  5013.         if (
  5014. #ifdef COMMENT
  5015.         /* This can fail because of sign extension */
  5016.         (temp.c_cflag & CRTSCTS) != CRTSCTS
  5017. #else
  5018.         (temp.c_cflag & CRTSCTS) == 0
  5019. #endif /* COMMENT */
  5020.         ) {
  5021.         temp.c_cflag |= CRTSCTS; /* Not there, add it */
  5022.         temp.c_iflag &= ~(IXON|IXOFF|IXANY); /* Bye to IXON/IXOFF */
  5023.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5024.         debug(F111,"tthflow POSIX_CRTSCTS ON tcsetattr",
  5025.               ckitoa(x),errno);
  5026.         attrs->c_cflag |= CRTSCTS;
  5027.         attrs->c_iflag &= ~(IXON|IXOFF|IXANY);
  5028.         }
  5029.     }
  5030.     }
  5031. #else
  5032. #ifdef SUNOS4
  5033. /*
  5034.   SunOS 4.0 (and maybe earlier?).  This code is dangerous because it
  5035.   prevents compilation with GNU gcc, which uses different formats for the
  5036.   _IORxxx macros than regular cc.  SunOS 4.1 and later can use the POSIX
  5037.   routines above, which work for both cc and gcc.
  5038. */
  5039. #define TCGETS _IOR(T, 8, struct termios) /* Get modes into termios struct */
  5040. #define TCSETS _IOW(T, 9, struct termios) /* Set modes from termios struct */
  5041. #define CRTSCTS 0x80000000          /* RTS/CTS flow control */
  5042.  
  5043.     struct termios {
  5044.     unsigned long c_iflag;        /* Input modes */
  5045.     unsigned long c_oflag;        /* Output modes */
  5046.     unsigned long c_cflag;        /* Control modes */
  5047.     unsigned long c_lflag;        /* Line discipline modes */
  5048.     char c_line;
  5049.     CHAR c_cc[17];
  5050.     };
  5051.     struct termios temp;
  5052. #ifdef NETCMD
  5053.     if (ttpipe) return(0);
  5054. #endif /* NETCMD */
  5055. #ifdef NETPTY
  5056.     if (ttpty) return(0);
  5057. #endif /* NETPTY */
  5058.     debug(F101,"tthflow entry status","",status);
  5059.     if (ioctl(ttyfd,TCGETS,&temp) > -1) { /* Get terminal modes. */
  5060.     if (status) {            /* Turn hard flow on */
  5061.         temp.c_cflag |= CRTSCTS;    /* Add RTS/CTS to them. */
  5062.         x = ioctl(ttyfd,TCSETS,&temp); /* Set them again. */
  5063.         attrs->c_cflag |= CRTSCTS;    /* Add to global info. */
  5064.     } else {            /* Turn hard flow off */
  5065.         temp.c_cflag &= ~CRTSCTS;
  5066.         x = ioctl(ttyfd,TCSETS,&temp);
  5067.         attrs->c_cflag &= ~CRTSCTS;
  5068.     }
  5069.     }
  5070. #else                    /* Not SunOS 4.0 or later */
  5071. #ifdef AIXRS                /* IBM AIX RS/6000 */
  5072. #ifndef AIX41                /* But only pre-4.x == SVR4 */
  5073. #ifdef NETCMD
  5074.     if (ttpipe) return(0);
  5075. #endif /* NETCMD */
  5076. #ifdef NETPTY
  5077.     if (ttpty) return(0);
  5078. #endif /* NETPTY */
  5079.     if (status) {
  5080.     if ((x = ioctl(ttyfd, TXADDCD, "rts")) < 0 && errno != EBUSY)
  5081.       debug(F100,"hardflow TXADDCD (rts) error", "", 0);
  5082.     } else {
  5083.     if ((x = ioctl(ttyfd, TXDELCD, "rts")) < 0 && errno != EINVAL)
  5084.       debug(F100,"hardflow TXDELCD (rts) error", "", 0);
  5085.     }
  5086. #endif /* AIX41 */
  5087. #else                    /* Not AIX RS/6000 */
  5088.  
  5089. #ifdef ATTSV                /* System V... */
  5090.  
  5091. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  5092. #define CK_SCOUNIX
  5093. #else
  5094. #ifdef M_UNIX                /* SCO UNIX 3.2v4.x or earlier */
  5095. #define CK_SCOUNIX
  5096. #endif /* M_UNIX */
  5097. #endif /* CK_SCOV5 */
  5098.  
  5099. #ifdef SCO_FORCE_RTSXOFF
  5100. #ifdef CK_SCOUNIX            /* But not SCO OpenServer 5.0.4 */
  5101. #ifdef SCO_OSR504            /* or later... */
  5102. #undef CK_SCOUNIX
  5103. #endif /* SCO_OSR504 */
  5104. #endif /* CK_SCOUNIX */
  5105. #endif /* SCO_FORCE_RTSXOFF */
  5106.  
  5107. #ifdef CK_SCOUNIX
  5108. #ifdef POSIX
  5109.     struct termios temp;
  5110. #ifdef NETCMD
  5111.     if (ttpipe) return(0);
  5112. #endif /* NETCMD */
  5113. #ifdef NETPTY
  5114.     if (ttpty) return(0);
  5115. #endif /* NETPTY */
  5116.     debug(F101,"tthflow SCOUNIX POSIX entry status","",status);
  5117.     errno = 0;
  5118.     x = tcgetattr(ttyfd, &temp);
  5119.     debug(F111,"tthflow SCO UNIX POSIX tcgetattr",ckitoa(x),errno);
  5120. #else /* POSIX */
  5121.     struct termio temp;
  5122. #ifdef NETCMD
  5123.     if (ttpipe) return(0);
  5124. #endif /* NETCMD */
  5125. #ifdef NETPTY
  5126.     if (ttpty) return(0);
  5127. #endif /* NETPTY */
  5128.     debug(F101,"tthflow SCOUNIX non-POSIX entry status","",status);
  5129.     x = ioctl(ttyfd, TCGETA, &temp);
  5130.     debug(F111,"tthflow SCO UNIX non-POSIX TCGETA",ckitoa(x),errno);
  5131. #endif /* POSIX */
  5132. /*
  5133.   This is not really POSIX, since POSIX does not deal with hardware flow
  5134.   control, but we are using the POSIX APIs.  In fact, RTSFLOW and CTSFLOW
  5135.   are defined in termio.h, but within #ifndef _POSIX_SOURCE..#endif.  So
  5136.   let's try forcing their definitions here.
  5137. */
  5138. #ifndef CTSFLOW
  5139. #define CTSFLOW 0020000
  5140.     debug(F101,"tthflow SCO defining CTSFLOW","",CTSFLOW);
  5141. #else
  5142.     debug(F101,"tthflow SCO CTSFLOW","",CTSFLOW);
  5143. #endif /* CTSFLOW */
  5144. #ifndef RTSFLOW
  5145. #define RTSFLOW 0040000
  5146.     debug(F101,"tthflow SCO defining RTSFLOW","",RTSFLOW);
  5147. #else
  5148.     debug(F101,"tthflow SCO RTSFLOW","",RTSFLOW);
  5149. #endif /* RTSFLOW */
  5150. #ifndef ORTSFL
  5151. #define ORTSFL 0100000
  5152.     debug(F101,"tthflow SCO defining ORTSFL","",ORTSFL);
  5153. #else
  5154.     debug(F101,"tthflow SCO ORTSFL","",ORTSFL);
  5155. #endif /* ORTSFL */
  5156.  
  5157.     if (x != -1) {
  5158.     if (status) {            /* Turn it ON */
  5159.         temp.c_cflag |= RTSFLOW|CTSFLOW;
  5160.         attrs->c_cflag |= RTSFLOW|CTSFLOW;
  5161. #ifdef ORTSFL
  5162.         temp.c_cflag &= ~ORTSFL;
  5163.         attrs->c_cflag &= ~ORTSFL;
  5164. #endif /* ORTSFL */
  5165.         temp.c_iflag &= ~(IXON|IXOFF|IXANY);
  5166.         attrs->c_iflag &= ~(IXON|IXOFF|IXANY);
  5167.     } else {            /* Turn it OFF */
  5168. #ifdef ORTSFL
  5169.         temp.c_cflag &= ~(RTSFLOW|CTSFLOW|ORTSFL);
  5170.         attrs->c_cflag &= ~(RTSFLOW|CTSFLOW|ORTSFL);
  5171. #else  /* ORTSFL */
  5172.         temp.c_cflag &= ~(RTSFLOW|CTSFLOW);
  5173.         attrs->c_cflag &= ~(RTSFLOW|CTSFLOW);
  5174. #endif /* ORTSFL */
  5175.     }
  5176. #ifdef POSIX
  5177.     x = tcsetattr(ttyfd, TCSADRAIN, &temp);
  5178. #else
  5179.     x = ioctl(ttyfd, TCSETA, &temp);
  5180. #endif /* POSIX */
  5181.     debug(F101,"tthflow SCO set modes","",x);
  5182.     }
  5183. #else /* Not SCO UNIX */
  5184. #ifdef NETCMD
  5185.     if (ttpipe) return(0);
  5186. #endif /* NETCMD */
  5187. #ifdef NETPTY
  5188.     if (ttpty) return(0);
  5189. #endif /* NETPTY */
  5190.     if (!status) {            /* Turn it OFF */
  5191. #ifdef RTSXOFF
  5192.     debug(F100,"tthflow ATTSV RTS/CTS OFF","",0);
  5193.     rctsx.x_hflag &= ~(RTSXOFF|CTSXON);
  5194. #ifdef TCSETX
  5195.     x = ioctl(ttyfd,TCSETX,&rctsx);
  5196.     debug(F101,"tthflow ATTSV TCSETX OFF","",x);
  5197. #else
  5198.     x = -1
  5199.     debug(F100,"tthflow TCSETX not defined","",0);
  5200. #endif /* TCSETX */
  5201. #else
  5202.     debug(F100,"tthflow ATTSV RTSXOFF not defined","",0);
  5203. #endif /* RTSXOFF */
  5204. #ifdef DTRXOFF
  5205.     debug(F100,"tthflow ATTSV DTR/CD OFF","",0);
  5206.     rctsx.x_hflag &= ~(DTRXOFF|CDXON);
  5207.     x = ioctl(ttyfd,TCSETX,&rctsx);
  5208.     debug(F101,"tthflow ATTSV DTRXOFF OFF","",x);
  5209. #else
  5210.     debug(F100,"tthflow ATTSV DTRXOFF not defined","",0);
  5211. #endif /* DTRXOFF */
  5212.     } else {                /* Turn it ON. */
  5213.     if (flow == FLO_RTSC) {    /* RTS/CTS Flow control... */
  5214.         debug(F100,"tthflow ATTSV RTS/CTS ON","",0);
  5215. #ifdef RTSXOFF
  5216.         /* This is the preferred way, according to SVID3 */
  5217. #ifdef TCGETX
  5218.         x = ioctl(ttyfd,TCGETX,&rctsx);
  5219.         debug(F101,"tthflow TCGETX","",x);
  5220.         if (x > -1) {
  5221.         rctsx.x_hflag |= RTSXOFF | CTSXON;
  5222.         x = ioctl(ttyfd,TCSETX,&rctsx);
  5223.         debug(F100,"tthflow ATTSV ioctl","",x);
  5224.         }
  5225. #else
  5226.         debug(F100,"tthflow TCGETX not defined","",0);
  5227.         x = -1
  5228. #endif /* TCGETX */
  5229. #else
  5230.         debug(F100,"tthflow RTSXOFF not defined","",0);
  5231.         x = -1;
  5232. #endif /* RTSXOFF */
  5233.     } else if (flow == FLO_DTRC) {    /* DTR/CD Flow control... */
  5234.         debug(F100,"tthflow ATTSV DTR/CD ON","",0);
  5235. #ifdef DTRXOFF
  5236.         /* This is straight out of SVID R4 */
  5237.         if (ioctl(ttyfd,TCGETX,&rctsx) > -1) {
  5238.         rctsx.x_hflag &= ~(DTRXOFF|CDXON);
  5239.         x = ioctl(ttyfd,TCSETX,&rctsx);
  5240.         }
  5241. #else
  5242.         debug(F100,"tthflow ATTSV DTRXOFF not defined","",0);
  5243.         x = -1;
  5244. #endif /* DTRXOFF */
  5245.     }
  5246.     }
  5247. #endif /* CK_SCOUNIX */
  5248.  
  5249. #else /* not System V... */
  5250.  
  5251. #ifdef CK_DTRCTS
  5252. #ifdef LDODTR
  5253. #ifdef LDOCTS
  5254. #ifdef NETCMD
  5255.     if (ttpipe) return(0);
  5256. #endif /* NETCMD */
  5257. #ifdef NETPTY
  5258.     if (ttpty) return(0);
  5259. #endif /* NETPTY */
  5260.     x = LDODTR | LDOCTS;        /* Found only on UTEK? */
  5261.     if (flow == FLO_DTRT && status) {    /* Use hardware flow control */
  5262.     if (lmodef) {
  5263.         x = ioctl(ttyfd,TIOCLBIS,&x);
  5264.         if (x < 0) {
  5265.             debug(F100,"hardflow TIOCLBIS error","",0);
  5266.         } else {
  5267.         lmodef++;
  5268.         debug(F100,"hardflow TIOCLBIS ok","",0);
  5269.         }
  5270.     }
  5271.     } else {
  5272.     if (lmodef) {
  5273.         x = ioctl(ttyfd,TIOCLBIC,&x);
  5274.         if (x < 0) {
  5275.             debug(F100,"hardflow TIOCLBIC error","",0);
  5276.         } else {
  5277.         lmodef++;
  5278.         debug(F100,"hardflow TIOCLBIC ok","",0);
  5279.         }
  5280.     }
  5281.     }
  5282. #endif /* LDODTR */
  5283. #endif /* LDOCTS */
  5284. #endif /* CK_DTRCTS */
  5285. #endif /* ATTSV */
  5286. #endif /* AIXRS */
  5287. #endif /* SUNOS4 */
  5288. #endif /* QNX */
  5289. #endif /* POSIX_CRTSCTS */
  5290. #endif /* SUNOS41 */
  5291.  
  5292. #else /* OXOS */
  5293.  
  5294.     struct termios temp;        /* Olivetti X/OS ... */
  5295.  
  5296. #ifdef NETCMD
  5297.     if (ttpipe) return(0);
  5298. #endif /* NETCMD */
  5299. #ifdef NETPTY
  5300.     if (ttpty) return(0);
  5301. #endif /* NETPTY */
  5302.     x = ioctl(ttyfd,TCGETS,&temp);
  5303.     if (x == 0) {
  5304.     temp.c_cflag &= ~(CRTSCTS|CDTRCTS|CBRKFLOW|CDTRDSR|CRTSDSR);
  5305.     if (status) {
  5306.         switch (flow) {
  5307.           case FLO_RTSC: temp.c_cflag |= CRTSCTS; /* RTS/CTS (hard) */
  5308.         break;
  5309.           case FLO_DTRT: temp.c_cflag |= CDTRCTS; /* DTR/CTS (hard) */
  5310.         break;
  5311.         }
  5312.     }
  5313.     x = ioctl(ttyfd,TCSETS,&temp);
  5314.     }
  5315. #endif /* OXOS */
  5316.     return(x);
  5317.  
  5318. #endif /* Plan9 */
  5319. }
  5320.  
  5321. /*  T T P K T  --  Condition the communication line for packets */
  5322. /*                 or for modem dialing */
  5323.  
  5324. /*
  5325.   If called with speed > -1, also set the speed.
  5326.   Returns 0 on success, -1 on failure.
  5327.  
  5328.   NOTE: the "xflow" parameter is supposed to be the currently selected
  5329.   type of flow control, but for historical reasons, this parameter is also
  5330.   used to indicate that we are dialing.  Therefore, when the true flow
  5331.   control setting is needed, we access the external variable "flow", rather
  5332.   than trusting our "xflow" argument.
  5333. */
  5334. int
  5335. #ifdef CK_ANSIC
  5336. ttpkt(long speed, int xflow, int parity)
  5337. #else
  5338. ttpkt(speed,xflow,parity) long speed; int xflow, parity;
  5339. #endif /* CK_ANSIC */
  5340. /* ttpkt */ {
  5341. #ifndef NOLOCAL
  5342.     int s2;
  5343.     int s = -1;
  5344. #endif /* NOLOCAL */
  5345. #ifndef SVORPOSIX
  5346.     int x;
  5347. #endif /* SVORPOSIX */
  5348.     extern int flow;            /* REAL flow-control setting */
  5349.  
  5350.     if (ttyfd < 0) return(-1);          /* Not open. */
  5351.  
  5352.     debug(F101,"ttpkt parity","",parity);
  5353.     debug(F101,"ttpkt xflow","",xflow);
  5354.     debug(F101,"ttpkt speed","",(int) speed);
  5355.  
  5356.     ttprty = parity;                    /* Let other tt functions see these. */
  5357.     ttspeed = speed;            /* Make global copy for this module */
  5358.     ttpmsk = ttprty ? 0177 : 0377;    /* Parity stripping mask */
  5359. #ifdef PARSENSE
  5360.     needpchk = ttprty ? 0 : 1;        /* Parity check needed? */
  5361. #else
  5362.     needpchk = 0;
  5363. #endif /* PARSENSE */
  5364.  
  5365.     debug(F101,"ttpkt ttpmsk","",ttpmsk);
  5366.     debug(F101,"ttpkt netconn","",netconn);
  5367.  
  5368. #ifdef NETCONN                /* No mode-changing for telnet */
  5369.     if (netconn) {
  5370. #ifdef TCPSOCKET
  5371. #ifdef TCP_NODELAY
  5372.         if (ttnet == NET_TCPB) {    /* But turn off Nagle */
  5373.             extern int tcp_nodelay;
  5374.             nodelay_sav = tcp_nodelay;
  5375.             no_delay(1);
  5376.         }
  5377. #endif /* TCP_NODELAY */
  5378. #endif /* TCPSOCKET */
  5379.         return(0);
  5380.     }
  5381. #endif /* NETCONN */
  5382. #ifdef NETCMD
  5383.     if (ttpipe) return(0);
  5384. #endif /* NETCMD */
  5385. #ifdef NETPTY
  5386.     if (ttpty) return(0);
  5387. #endif /* NETPTY */
  5388.  
  5389. #ifndef Plan9
  5390.     if (ttfdflg && !isatty(ttyfd)) return(0);
  5391. #endif /* Plan9 */
  5392.  
  5393. #ifdef COHERENT
  5394. #define SVORPOSIX
  5395. #endif /* COHERENT */
  5396.  
  5397. #ifndef SVORPOSIX            /* Berkeley, V7, etc. */
  5398. #ifdef LPASS8
  5399. /*
  5400.  For some reason, with BSD terminal drivers, you can't set FLOW to XON/XOFF
  5401.  after having previously set it to NONE without closing and reopening the
  5402.  device.  Unless there's something I overlooked below...
  5403. */
  5404.     if (ttflow == FLO_NONE && flow == FLO_XONX && xlocal == 0) {
  5405.     debug(F101,"ttpkt executing horrible flow kludge","",0);
  5406.     ttclos(0);            /* Close it */
  5407.     x = 0;
  5408.     ttopen(ttnmsv,&x,ttmdm,0);    /* Open it again */
  5409.     }
  5410. #endif /* LPASS8 */
  5411. #endif /* SVORPOSIX */
  5412.  
  5413. #ifdef COHERENT                /* This must be vestigial since we */
  5414. #undef SVORPOSIX            /* reverse it a few lines below... */
  5415. #endif /* COHERENT */
  5416.  
  5417.     if (xflow != FLO_DIAL && xflow != FLO_DIAX)
  5418.       ttflow = xflow;            /* Now make this available too. */
  5419.  
  5420. #ifndef NOLOCAL
  5421.     if (xlocal) {
  5422.     s2 = (int) (speed / 10L);    /* Convert bps to cps */
  5423.     debug(F101,"ttpkt calling ttsspd","",s2);
  5424.     s = ttsspd(s2);            /* Check and set the speed */
  5425.     debug(F101,"ttpkt ttsspd result","",s);
  5426.      carrctl(&ttraw, xflow != FLO_DIAL /* Carrier control */
  5427.         && (ttcarr == CAR_ON || (ttcarr == CAR_AUT && ttmdm != 0)));
  5428.     tvtflg = 0;            /* So ttvt() will work next time */
  5429.     }
  5430. #endif /* NOLOCAL */
  5431.  
  5432. #ifdef COHERENT
  5433. #define SVORPOSIX
  5434. #endif /* COHERENT */
  5435.  
  5436. #ifndef SVORPOSIX            /* BSD section */
  5437.     if (flow == FLO_RTSC ||        /* Hardware flow control */
  5438.     flow == FLO_DTRC ||
  5439.     flow == FLO_DTRT) {
  5440.     tthflow(flow, 1, &ttraw);
  5441.     debug(F100,"ttpkt hard flow, TANDEM off, RAW on","",0);
  5442.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  5443.     ttraw.sg_flags |= RAW;        /* Enter raw mode */
  5444.     } else if (flow == FLO_NONE) {    /* No flow control */
  5445.     debug(F100,"ttpkt no flow, TANDEM off, RAW on","",0);
  5446.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  5447.     tthflow(flow, 0, &ttraw);    /* Turn off any hardware f/c too */
  5448.     ttraw.sg_flags |= RAW;        /* Enter raw mode */
  5449.     } else if (flow == FLO_KEEP) {    /* Keep device's original setting */
  5450.     debug(F100,"ttpkt keeping original TANDEM","",0);
  5451.     ttraw.sg_flags &= ~TANDEM;
  5452.     ttraw.sg_flags |= (ttold.sg_flags & TANDEM);
  5453.     /* NOTE: We should also handle hardware flow control here! */
  5454.     }
  5455.  
  5456. /* SET FLOW XON/XOFF is in effect, or SET FLOW KEEP resulted in Xon/Xoff */
  5457.  
  5458.     if ((flow == FLO_XONX) || (ttraw.sg_flags & TANDEM)) {
  5459.     debug(F100,"ttpkt turning on TANDEM","",0);
  5460.     ttraw.sg_flags |= TANDEM;    /* So ask for it. */
  5461.  
  5462. #ifdef LPASS8                /* Can pass 8-bit data through? */
  5463. /* If the LPASS8 local mode is available, then flow control can always  */
  5464. /* be used, even if parity is none and we are transferring 8-bit data.  */
  5465. /* But we only need to do all this if Xon/Xoff is requested. */
  5466. /* BUT... this tends not to work through IP or LAT connections, terminal */
  5467. /* servers, telnet, rlogin, etc, so it is currently disabled. */
  5468.     x = LPASS8;            /* If LPASS8 defined, then */
  5469.     debug(F100,"ttpkt executing LPASS8 code","",0);
  5470.     if (lmodef) {            /* TIOCLBIS must be too. */
  5471.         x = ioctl(ttyfd,TIOCLBIS,&x); /* Try to set LPASS8. */
  5472.         if (x < 0) {
  5473.         debug(F100,"ttpkt TIOCLBIS error","",0);
  5474.         } else {
  5475.         lmodef++;
  5476.         debug(F100,"ttpkt TIOCLBIS ok","",0);
  5477.         }
  5478.     }
  5479. /*
  5480.  But if we use LPASS8 mode, we must explicitly turn off
  5481.  terminal interrupts of all kinds.
  5482. */
  5483. #ifdef TIOCGETC                /* Not rawmode, */
  5484.     if (tcharf && (xlocal == 0)) {    /* must turn off */
  5485.         tchnoi.t_intrc = -1;    /* interrupt character */
  5486.         tchnoi.t_quitc = -1;    /* and quit character. */
  5487.         tchnoi.t_startc = 17;    /* Make sure xon */
  5488.         tchnoi.t_stopc = 19;    /* and xoff not ignored. */
  5489. #ifndef NOBRKC
  5490.         tchnoi.t_eofc = -1;        /* eof character. */
  5491.         tchnoi.t_brkc = -1;        /* brk character. */
  5492. #endif /* NOBRKC */
  5493.         if (ioctl(ttyfd,TIOCSETC,&tchnoi) < 0) {
  5494.         debug(F100,"ttpkt TIOCSETC failed","",0);
  5495.         } else {
  5496.         tcharf = 1;
  5497.         debug(F100,"ttpkt TIOCSETC ok","",0);
  5498.         }
  5499. #ifdef COMMENT
  5500. /* only for paranoid debugging */
  5501.         if (tcharf) {
  5502.         struct tchars foo;
  5503.         char tchbuf[100];
  5504.         ioctl(0,TIOCGETC,&foo);
  5505.         sprintf(tchbuf,
  5506.             "intr=%d,quit=%d, start=%d, stop=%d, eof=%d, brk=%d",
  5507.             foo.t_intrc, foo.t_quitc, foo.t_startc,
  5508.             foo.t_stopc, foo.t_eofc,  foo.t_brkc);
  5509.         debug(F110,"ttpkt chars",tchbuf,0);
  5510.         }
  5511. #endif /* COMMENT */
  5512.     }
  5513.     ttraw.sg_flags |= CBREAK;    /* Needed for unknown reason */
  5514. #endif /* TIOCGETC */
  5515.  
  5516. /* Prevent suspend during packet mode */
  5517. #ifdef TIOCGLTC                /* Not rawmode, */
  5518.     if (ltcharf && (xlocal == 0)) {    /* must turn off */
  5519.         ltchnoi.t_suspc = -1;    /* suspend character */
  5520.         ltchnoi.t_dsuspc = -1;    /* and delayed suspend character */
  5521.         if (ioctl(ttyfd,TIOCSLTC,&tchnoi) < 0) {
  5522.         debug(F100,"ttpkt TIOCSLTC failed","",0);
  5523.         } else {
  5524.         ltcharf = 1;
  5525.         debug(F100,"ttpkt TIOCSLTC ok","",0);
  5526.         }
  5527.     }
  5528. #endif /* TIOCGLTC */
  5529.  
  5530. #else /* LPASS8 not defined */
  5531.  
  5532. /* Previously, BSD-based implementations always */
  5533. /* used rawmode for packets.  Now, we use rawmode only if parity is NONE. */
  5534. /* This allows the flow control requested above to actually work, but only */
  5535. /* if the user asks for parity (which also means they get 8th-bit quoting). */
  5536.  
  5537.     if (parity) {            /* If parity, */
  5538.         ttraw.sg_flags &= ~RAW;    /* use cooked mode */
  5539. #ifdef COMMENT
  5540. /* WHY??? */
  5541.         if (xlocal)
  5542. #endif /* COMMENT */
  5543.           ttraw.sg_flags |= CBREAK;
  5544.         debug(F101,"ttpkt cooked, cbreak, parity","",parity);
  5545. #ifdef TIOCGETC                /* Not rawmode, */
  5546.         if (tcharf && (xlocal == 0)) { /* must turn off */
  5547.         tchnoi.t_intrc = -1;    /* interrupt character */
  5548.         tchnoi.t_quitc = -1;    /* and quit character. */
  5549.         tchnoi.t_startc = 17;    /* Make sure xon */
  5550.         tchnoi.t_stopc = 19;    /* and xoff not ignored. */
  5551. #ifndef NOBRKC
  5552.         tchnoi.t_eofc = -1;    /* eof character. */
  5553.         tchnoi.t_brkc = -1;    /* brk character. */
  5554. #endif /* NOBRKC */
  5555.         if (ioctl(ttyfd,TIOCSETC,&tchnoi) < 0) {
  5556.             debug(F100,"ttpkt TIOCSETC failed","",0);
  5557.         } else {
  5558.             tcharf = 1;
  5559.             debug(F100,"ttpkt TIOCSETC ok","",0);
  5560.         }
  5561.         }
  5562. #endif /* TIOCGETC */
  5563. #ifdef TIOCGLTC                /* Not rawmode, */
  5564. /* Prevent suspend during packet mode */
  5565.         if (ltcharf && (xlocal == 0)) { /* must turn off */
  5566.         ltchnoi.t_suspc = -1;    /* suspend character */
  5567.         ltchnoi.t_dsuspc = -1;    /* and delayed suspend character */
  5568.         if (ioctl(ttyfd,TIOCSLTC,&tchnoi) < 0) {
  5569.             debug(F100,"ttpkt TIOCSLTC failed","",0);
  5570.         } else {
  5571.             ltcharf = 1;
  5572.             debug(F100,"ttpkt TIOCSLTC ok","",0);
  5573.         }
  5574.         }
  5575. #endif /* TIOCGLTC */
  5576.     } else {            /* If no parity, */
  5577.         ttraw.sg_flags |= RAW;    /* must use 8-bit raw mode. */
  5578.         debug(F101,"ttpkt setting rawmode, parity","",parity);
  5579.     }
  5580. #endif /* LPASS8 */
  5581.     } /* End of Xon/Xoff section */
  5582.  
  5583.     /* Don't echo, don't map CR to CRLF on output, don't fool with case */
  5584. #ifdef LCASE
  5585.     ttraw.sg_flags &= ~(ECHO|CRMOD|LCASE);
  5586. #else
  5587.     ttraw.sg_flags &= ~(ECHO|CRMOD);
  5588. #endif /* LCASE */
  5589.  
  5590. #ifdef TOWER1
  5591.     ttraw.sg_flags &= ~ANYP;            /* Must set this on old Towers */
  5592. #endif /* TOWER1 */
  5593.  
  5594. #ifdef BELLV10
  5595.     if (ioctl(ttyfd,TIOCSETP,&ttraw) < 0) /* Set the new modes. */
  5596.       return(-1);
  5597. #else
  5598.     errno = 0;
  5599.     if (stty(ttyfd,&ttraw) < 0) {       /* Set the new modes. */
  5600.         debug(F101,"ttpkt stty failed","",errno);
  5601.         return(-1);
  5602.     }
  5603. #endif /* BELLV10 */
  5604.     debug(F100,"ttpkt stty ok","",0);
  5605.  
  5606. #ifdef sony_news
  5607.     x = xlocal ? km_ext : km_con;    /* Put line in ASCII mode. */
  5608.     if (x != -1) {            /* Make sure we know original modes. */
  5609.     x &= ~KM_TTYPE;
  5610.     x |= KM_ASCII;
  5611.     if (ioctl(ttyfd,TIOCKSET, &x) < 0) {
  5612.         perror("ttpkt can't set ASCII mode");
  5613.         debug(F101,"ttpkt error setting ASCII mode","",x);
  5614.         return(-1);
  5615.     }
  5616.     }
  5617.     debug(F100,"ttpkt set ASCII mode ok","",0);
  5618. #endif /* sony_news */
  5619.  
  5620.     if (xlocal == 0) {            /* Turn this off so we can read */
  5621.     signal(SIGINT,SIG_IGN);        /* Ctrl-C chars typed at console */
  5622.     sigint_ign = 1;
  5623.     }
  5624.     tvtflg = 0;                /* So ttvt() will work next time */
  5625.     debug(F100,"ttpkt success","",0);
  5626.     return(0);
  5627.  
  5628. #endif /* Not ATTSV or POSIX */
  5629.  
  5630. /* AT&T UNIX and POSIX */
  5631.  
  5632. #ifdef COHERENT
  5633. #define SVORPOSIX
  5634. #endif /* COHERENT */
  5635.  
  5636. #ifdef SVORPOSIX
  5637.     if (flow == FLO_XONX) {        /* Xon/Xoff */
  5638.     ttraw.c_iflag |= (IXON|IXOFF);
  5639.     tthflow(flow, 0, &ttraw);
  5640.     } else if (flow == FLO_NONE) {    /* None */
  5641.     /* NOTE: We should also turn off hardware flow control here! */
  5642.     ttraw.c_iflag &= ~(IXON|IXOFF);
  5643.     tthflow(flow, 0, &ttraw);
  5644.     } else if (flow == FLO_KEEP) {    /* Keep */
  5645.     ttraw.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff flags */
  5646.     ttraw.c_iflag |= (ttold.c_iflag & (IXON|IXOFF)); /* OR in old ones */
  5647.     /* NOTE: We should also handle hardware flow control here! */
  5648. #ifdef POSIX_CRTSCTS
  5649. /* In Linux case, we do this, which is unlikely to be portable */
  5650.         ttraw.c_cflag &= ~CRTSCTS;    /* Turn off RTS/CTS flag */
  5651.         ttraw.c_cflag |= (ttold.c_cflag & CRTSCTS); /* OR in old one */
  5652. #endif /* POSIX_CRTSCTS */
  5653.     } else if (flow == FLO_RTSC ||    /* Hardware */
  5654.            flow == FLO_DTRC ||
  5655.            flow == FLO_DTRT) {
  5656.     ttraw.c_iflag &= ~(IXON|IXOFF);    /* (190) */
  5657.     tthflow(flow, 1, &ttraw);
  5658.     }
  5659.     ttraw.c_lflag &= ~(ICANON|ECHO);
  5660.     ttraw.c_lflag &= ~ISIG;        /* Do NOT check for interrupt chars */
  5661.  
  5662. #ifndef OXOS
  5663. #ifdef QNX
  5664.     if (flow != FLO_RTSC && flow != FLO_DTRC && flow != FLO_DTRT)
  5665. #endif /* QNX */
  5666. #ifndef COHERENT
  5667.       ttraw.c_lflag &= ~IEXTEN;        /* Turn off ^O/^V processing */
  5668. #endif /* COHERENT */
  5669. #else /* OXOS */
  5670.     ttraw.c_cc[VDISCARD] = ttraw.c_cc[VLNEXT] = CDISABLE;
  5671. #endif /* OXOS */
  5672.     ttraw.c_lflag |= NOFLSH;        /* Don't flush */
  5673.     ttraw.c_iflag |= IGNPAR;        /* Ignore parity errors */
  5674. #ifdef ATTSV
  5675. #ifdef BSD44
  5676.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|INPCK|ISTRIP|IXANY);
  5677. #else
  5678.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IUCLC|INPCK|ISTRIP|IXANY);
  5679. #endif /* BSD44 */
  5680. #else /* POSIX */
  5681.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|INPCK|ISTRIP);
  5682. #endif /* ATTSV */
  5683.     ttraw.c_oflag &= ~OPOST;
  5684.     ttraw.c_cflag &= ~(CSIZE);
  5685.     ttraw.c_cflag |= (CS8|CREAD|HUPCL);
  5686.  
  5687. #ifdef HWPARITY
  5688.     if (hwparity && xlocal) {        /* Hardware parity & stop bits */
  5689. #ifdef CSTOPB
  5690.     if (stopbits == 2) {
  5691.         ttraw.c_cflag |= CSTOPB;    /* 2 stop bits */
  5692.         debug(F100,"ttpkt 2 stopbits","",0);
  5693.     } else if (stopbits == 1) {
  5694.         ttraw.c_cflag &= ~(CSTOPB);    /* 1 stop bit */
  5695.         debug(F100,"ttpkt 1 stopbit","",0);
  5696.     }
  5697. #else
  5698.     debug(F101,"ttpkt CSTOPB not def","",stopbits);
  5699. #endif /* CSTOPB */
  5700.     ttraw.c_cflag |= PARENB;    /* Enable parity */
  5701.     switch (hwparity) {
  5702.       case 'e':            /* Even */
  5703.         ttraw.c_cflag &= ~(PARODD);
  5704.         debug(F100,"ttpkt 8 bits + even parity","",0);
  5705.         break;
  5706.       case 'o':            /* Odd */
  5707.         ttraw.c_cflag |= PARODD;
  5708.         debug(F100,"ttpkt 8 bits + odd parity","",0);
  5709.         break;
  5710.       case 'm':            /* Mark */
  5711.       case 's':            /* Space */
  5712.         debug(F100,"ttpkt 8 bits + invalid parity","",0);
  5713.         break;
  5714.     }
  5715.     } else {                /* We handle parity ourselves */
  5716. #endif /* HWPARITY */
  5717.     ttraw.c_cflag &= ~(PARENB);    /* Don't enable parity */
  5718. #ifdef HWPARITY
  5719.     }
  5720. #endif /* HWPARITY */
  5721.  
  5722. #ifdef IX370
  5723.     ttraw.c_cc[4] = 48;  /* So Series/1 doesn't interrupt on every char */
  5724.     ttraw.c_cc[5] = 1;
  5725. #else
  5726. #ifndef VEOF                /* for DGUX this is VEOF, not VMIN */
  5727.     ttraw.c_cc[4] = 1;   /* [VMIN]  return max of this many characters or */
  5728. #else
  5729. #ifndef OXOS
  5730. #ifdef VMIN
  5731.     ttraw.c_cc[VMIN] = 1;
  5732. #endif /* VMIN */
  5733. #else /* OXOS */
  5734.     ttraw.c_min = 1;
  5735. #endif /* OXOS */
  5736. #endif /* VEOF */
  5737. #ifndef VEOL                /* for DGUX this is VEOL, not VTIME */
  5738.     ttraw.c_cc[5] = 0;     /* [VTIME] when this many secs/10 expire w/no input */
  5739. #else
  5740. #ifndef OXOS
  5741. #ifdef VTIME
  5742.     ttraw.c_cc[VTIME] = 0;
  5743. #endif /* VTIME */
  5744. #else /* OXOS */
  5745.     ttraw.c_time = 0;
  5746. #endif /* OXOS */
  5747. #endif /* VEOL */
  5748. #endif /* IX370 */
  5749.  
  5750. #ifdef VINTR                /* Turn off interrupt character */
  5751.     if (xlocal == 0)            /* so ^C^C can break us out of */
  5752.       ttraw.c_cc[VINTR] = 0;        /* packet mode. */
  5753. #endif /* VINTR */
  5754.  
  5755. #ifdef Plan9
  5756.     if (p9ttyparity('n') < 0)
  5757.     return -1;
  5758. #else
  5759. #ifdef BSD44ORPOSIX
  5760. #ifdef BEBOX
  5761.     ttraw.c_cc[VMIN] = 0;        /* DR7 can only poll. */
  5762. #endif /* BEBOX */
  5763.     debug(F100,"ttpkt calling tcsetattr(TCSETAW)","",0);
  5764.     errno = 0;
  5765.     if (tcsetattr(ttyfd,TCSADRAIN,&ttraw) < 0) {
  5766.         debug(F101,"ttpkt BSD44ORPOSIX tcsetattr(TCSADRAIN) fail","",errno);
  5767.         return(-1);
  5768.     }
  5769. #else /* BSD44ORPOSIX */
  5770.     errno = 0;
  5771.     debug(F100,"ttpkt calling ioctl(TCSETAW)","",0);
  5772.     if (ioctl(ttyfd,TCSETAW,&ttraw) < 0) {  /* set new modes . */
  5773.         debug(F100,"ttpkt ATTSV ioctl(TCSETAW) fail","",errno);
  5774.         return(-1);
  5775.     }
  5776. #endif /* BSD44ORPOSIX */
  5777. #endif /* Plan9 */
  5778.     tvtflg = 0;
  5779.     debug(F100,"ttpkt success","",0);
  5780.     return(0);
  5781. #endif /* ATTSV */
  5782.  
  5783. #ifdef COHERENT
  5784. #undef SVORPOSIX
  5785. #endif /* COHERENT */
  5786.  
  5787. }
  5788.  
  5789. /*  T T S E T F L O W  --  Set flow control immediately.  */
  5790.  
  5791. #ifdef COHERENT
  5792. #define SVORPOSIX
  5793. #endif /* COHERENT */
  5794.  
  5795. int
  5796. ttsetflow(flow) int flow; {
  5797.     if (ttyfd < 0)            /* Communications channel must open */
  5798.       return(-1);
  5799.  
  5800.     debug(F101,"ttsetflow","",flow);
  5801.  
  5802. #ifdef NETCMD
  5803.     if (ttpipe) return(0);
  5804. #endif /* NETCMD */
  5805. #ifdef NETPTY
  5806.     if (ttpty) return(0);
  5807. #endif /* NETPTY */
  5808.  
  5809. #ifdef COMMENT
  5810.     /* This seems to hurt... */
  5811.     if (flow == FLO_KEEP)
  5812.       return(0);
  5813. #endif /* COMMENT */
  5814.  
  5815.     if (flow == FLO_RTSC ||        /* Hardware flow control... */
  5816.     flow == FLO_DTRC ||
  5817.     flow == FLO_DTRT) {
  5818.     tthflow(flow, 1, &ttraw);
  5819. #ifndef SVORPOSIX
  5820.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  5821. #else
  5822.     ttraw.c_iflag &= ~(IXON|IXOFF);
  5823. #endif /* SVORPOSIX */
  5824.  
  5825.     } else if (flow == FLO_XONX) {    /* Xon/Xoff... */
  5826.  
  5827. #ifndef SVORPOSIX
  5828.     ttraw.sg_flags |= TANDEM;
  5829. #else
  5830.     ttraw.c_iflag |= (IXON|IXOFF);
  5831. #endif /* SVORPOSIX */
  5832.     tthflow(FLO_RTSC, 0, &ttraw);    /* Turn off hardware flow control */
  5833.  
  5834.     } else if (flow == FLO_NONE) {    /* No flow control */
  5835.  
  5836. #ifndef SVORPOSIX
  5837.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  5838. #else
  5839.     ttraw.c_iflag &= ~(IXON|IXOFF);
  5840. #endif /* SVORPOSIX */
  5841.     tthflow(FLO_RTSC, 0, &ttraw);    /* Turn off any hardware f/c too */
  5842.     }
  5843.  
  5844. /* Set the new modes... */
  5845.  
  5846. #ifndef SVORPOSIX            /* BSD and friends */
  5847. #ifdef BELLV10
  5848.     if (ioctl(ttyfd,TIOCSETP,&ttraw) < 0)
  5849.       return(-1);
  5850. #else
  5851. #ifndef MINIX2
  5852.     if (stty(ttyfd,&ttraw) < 0)
  5853.       return(-1);
  5854. #endif /* MINIX2 */
  5855. #endif /* BELLV10 */
  5856. #else
  5857. #ifdef BSD44ORPOSIX            /* POSIX */
  5858.     if (tcsetattr(ttyfd,TCSADRAIN,&ttraw) < 0)
  5859.       return(-1);
  5860. #else                    /* System V */
  5861.     if (ioctl(ttyfd,TCSETAW,&ttraw) < 0)
  5862.       return(-1);
  5863. #endif /* BSD44ORPOSIX */
  5864. #endif /* SVORPOSIX */
  5865.     return(0);
  5866. }
  5867. #ifdef COHERENT
  5868. #undef SVORPOSIX
  5869. #endif /* COHERENT */
  5870.  
  5871. /*  T T V T -- Condition communication device for use as virtual terminal. */
  5872.  
  5873. int
  5874. #ifdef CK_ANSIC
  5875. ttvt(long speed, int flow)
  5876. #else
  5877. ttvt(speed,flow) long speed; int flow;
  5878. #endif /* CK_ANSIC */
  5879. /* ttvt */ {
  5880.     int s, s2;
  5881.  
  5882.     debug(F101,"ttvt ttyfd","",ttyfd);
  5883.     debug(F101,"ttvt tvtflg","",tvtflg);
  5884.     debug(F101,"ttvt speed","",speed);
  5885.     debug(F101,"ttvt flow","",flow);
  5886.  
  5887.     ttpmsk = 0xff;
  5888. #ifdef NOLOCAL
  5889.     return(conbin((char)escchr));
  5890. #else
  5891.     if (ttyfd < 0) {            /* Not open. */
  5892.     if (ttchk() < 0)
  5893.       return(-1);
  5894.     else                /* But maybe something buffered. */
  5895.       return(0);
  5896.     }
  5897. #ifdef NETCMD
  5898.     if (ttpipe) return(0);
  5899. #endif /* NETCMD */
  5900. #ifdef NETPTY
  5901.     if (ttpty) return(0);
  5902. #endif /* NETPTY */
  5903. #ifdef NETCONN
  5904.     if (netconn) {
  5905.     tvtflg = 1;            /* Network connections... */
  5906.     debug(F100,"ttvt network connection, skipping...","",0);
  5907. #ifdef TCPSOCKET
  5908. #ifdef TCP_NODELAY
  5909.         {
  5910.         extern int tcp_nodelay;
  5911.         if (ttnet == NET_TCPB) {
  5912.         if (nodelay_sav > -1) {
  5913.             no_delay(nodelay_sav);
  5914.             nodelay_sav = -1;
  5915.         }
  5916.         }
  5917.         }
  5918. #endif /* TCP_NODELAY */
  5919. #endif /* TCPSOCKET */
  5920.     return(0);            /* ... require no special setup */
  5921.     }
  5922. #endif /* NETCONN */
  5923.  
  5924.     if (tvtflg != 0 && speed == ttspeed && flow == ttflow && ttcarr == curcarr)
  5925.       {
  5926.       debug(F100,"ttvt modes already set, skipping...","",0);
  5927.       return(0);            /* Already been called. */
  5928.       }
  5929.  
  5930.     if (ttfdflg
  5931. #ifndef Plan9
  5932.     && !isatty(ttyfd)
  5933. #endif /* Plan9 */
  5934.     ) {
  5935.     debug(F100,"ttvt using external fd, skipping...","",0);
  5936.     return(0);
  5937.     }
  5938.  
  5939.     debug(F100,"ttvt setting modes...","",0);
  5940.  
  5941.     if (xlocal) {            /* For external lines... */
  5942.     s2 = (int) (speed / 10L);
  5943.     s = ttsspd(s2);            /* Check/set the speed */
  5944.     carrctl(&tttvt, flow != FLO_DIAL /* Do carrier control */
  5945.         && (ttcarr == CAR_ON || (ttcarr == CAR_AUT && ttmdm != 0)));
  5946.     } else
  5947.       s = s2 = -1;
  5948.  
  5949. #ifdef COHERENT
  5950. #define SVORPOSIX
  5951. #endif /* COHERENT */
  5952.  
  5953. #ifndef SVORPOSIX
  5954.     /* Berkeley, V7, etc */
  5955.     if (flow == FLO_RTSC ||        /* Hardware flow control */
  5956.     flow == FLO_DTRC ||
  5957.     flow == FLO_DTRT) {
  5958.     tthflow(flow, 1, &tttvt);
  5959.     debug(F100,"ttvt hard flow, TANDEM off","",0);
  5960.     tttvt.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  5961.     } else if (flow == FLO_XONX) {    /* Xon/Xoff flow control */
  5962.     debug(F100,"ttvt TANDEM on","",0);
  5963.     tttvt.sg_flags |= TANDEM;    /* Ask for it. */
  5964.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  5965.     } else if (flow == FLO_NONE) {
  5966.     debug(F100,"ttvt no flow, TANDEM off, RAW on","",0);
  5967.     tttvt.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  5968.     tthflow(flow, 0, &tttvt);    /* Turn off any hardware f/c too */
  5969.     tttvt.sg_flags |= RAW;        /* Enter raw mode */
  5970.     } else if (flow == FLO_KEEP) {    /* Keep device's original setting */
  5971.     debug(F100,"ttvt keeping original TANDEM","",0);
  5972.     tttvt.sg_flags &= ~TANDEM;
  5973.     tttvt.sg_flags |= (ttold.sg_flags & TANDEM);
  5974.     /* NOTE: We should also handle hardware flow control here! */
  5975.     }
  5976.     tttvt.sg_flags |= RAW;              /* Raw mode in all cases */
  5977. #ifdef TOWER1
  5978.     tttvt.sg_flags &= ~(ECHO|ANYP);     /* No echo or parity */
  5979. #else
  5980.     tttvt.sg_flags &= ~ECHO;            /* No echo */
  5981. #endif /* TOWER1 */
  5982.  
  5983. #ifdef BELLV10
  5984.     if (ioctl(ttyfd,TIOCSETP,&tttvt) < 0) /* Set the new modes */
  5985.       return(-1);
  5986. #else
  5987.     if (stty(ttyfd,&tttvt) < 0)        /* Set the new modes */
  5988.       return(-1);
  5989. #endif /* BELLV10 */
  5990.  
  5991. #else /* It is ATTSV or POSIX */
  5992.  
  5993.     if (flow == FLO_XONX) {        /* Software flow control */
  5994.     tttvt.c_iflag |= (IXON|IXOFF);    /* On if requested. */
  5995.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  5996.     debug(F100,"ttvt SVORPOSIX flow XON/XOFF","",0);
  5997.     } else if (flow == FLO_NONE) {    /* NONE */
  5998.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff */
  5999.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  6000.     debug(F100,"ttvt SVORPOSIX flow NONE","",0);
  6001.     } else if (flow == FLO_KEEP) {
  6002.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff flags */
  6003.     tttvt.c_iflag |= (ttold.c_iflag & (IXON|IXOFF)); /* OR in old ones */
  6004. #ifdef POSIX_CRTSCTS
  6005.         tttvt.c_cflag &= ~CRTSCTS;    /* Turn off RTS/CTS flag */
  6006.         tttvt.c_cflag |= (ttold.c_cflag & CRTSCTS); /* OR in old one */
  6007. #endif /* POSIX_CRTSCTS */
  6008.     debug(F100,"ttvt SVORPOSIX flow KEEP","",0);
  6009.     } else if (flow == FLO_RTSC ||    /* Hardware flow control */
  6010.            flow == FLO_DTRC ||
  6011.            flow == FLO_DTRT) {
  6012.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* (196) */
  6013.     tthflow(flow, 1, &tttvt);
  6014.     debug(F100,"ttvt SVORPOSIX flow HARD","",0);
  6015.     }
  6016. #ifndef OXOS
  6017. #ifdef COHERENT
  6018.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO);
  6019. #else
  6020.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO|IEXTEN);
  6021. #endif /* COHERENT */
  6022. #ifdef QNX
  6023.     /* Needed for hwfc */
  6024.     if (flow == FLO_RTSC || flow == FLO_DTRC || flow == FLO_DTRT)
  6025.       tttvt.c_lflag |= IEXTEN;
  6026. #endif /* QNX */
  6027. #else /* OXOS */
  6028.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO);
  6029.     tttvt.c_cc[VDISCARD] = tttvt.c_cc[VLNEXT] = CDISABLE;
  6030. #endif /* OXOS */
  6031.  
  6032.     tttvt.c_iflag |= (IGNBRK|IGNPAR);
  6033.  
  6034. /* Parity */
  6035.  
  6036. #ifdef HWPARITY
  6037.     if (hwparity && xlocal) {        /* Hardware parity */
  6038. #ifdef CSTOPB
  6039.     if (stopbits == 2) {
  6040.         ttraw.c_cflag |= CSTOPB;    /* 2 stop bits */
  6041.         debug(F100,"ttpkt 2 stopbits","",0);
  6042.     } else if (stopbits == 1) {
  6043.         ttraw.c_cflag &= ~(CSTOPB);    /* 1 stop bit */
  6044.         debug(F100,"ttpkt 1 stopbit","",0);
  6045.     }
  6046. #endif /* CSTOPB */
  6047.     tttvt.c_cflag |= PARENB;    /* Enable parity */
  6048.     switch (hwparity) {
  6049.       case 'e':            /* Even */
  6050.         tttvt.c_cflag &= ~(PARODD);
  6051.         debug(F100,"ttvt 8 bits + even parity","",0);
  6052.         break;
  6053.       case 'o':            /* Odd */
  6054.         tttvt.c_cflag |= PARODD;
  6055.         debug(F100,"ttvt 8 bits + odd parity","",0);
  6056.         break;
  6057.       case 'm':            /* Mark */
  6058.       case 's':            /* Space */
  6059.         debug(F100,"ttvt 8 bits + invalid parity","",0);
  6060.         break;
  6061.     }
  6062.     } else {                /* We handle parity ourselves */
  6063. #endif /* HWPARITY */
  6064.     tttvt.c_cflag &= ~(PARENB);    /* Don't enable parity */
  6065. #ifdef HWPARITY
  6066.     }
  6067. #endif /* HWPARITY */
  6068.  
  6069. #ifdef ATTSV
  6070. #ifdef BSD44
  6071.     /* Things not to do... */
  6072.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|INPCK|ISTRIP|IXANY);
  6073. #else
  6074.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|IUCLC|INPCK|ISTRIP|IXANY);
  6075. #endif /* BSD44 */
  6076. #else /* POSIX */
  6077.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|INPCK|ISTRIP);
  6078. #endif /* ATTSV */
  6079.     tttvt.c_cflag &= ~(CSIZE);        /* Zero out the char size field */
  6080.     tttvt.c_cflag |= (CS8|CREAD|HUPCL);    /* Char size 8, enable receiver, hup */
  6081.     tttvt.c_oflag &= ~OPOST;        /* Don't postprocess output */
  6082. #ifndef VEOF /* DGUX termio has VEOF at entry 4, see comment above */
  6083.     tttvt.c_cc[4] = 1;
  6084. #else
  6085. #ifndef OXOS
  6086. #ifdef VMIN
  6087.     tttvt.c_cc[VMIN] = 1;
  6088. #endif /* VMIN */
  6089. #else /* OXOS */
  6090.     tttvt.c_min = 1;
  6091. #endif /* OXOS */
  6092. #endif /* VEOF */
  6093. #ifndef VEOL    /* DGUX termio has VEOL at entry 5, see comment above */
  6094.     tttvt.c_cc[5] = 0;
  6095. #else
  6096. #ifndef OXOS
  6097. #ifdef VTIME
  6098.     tttvt.c_cc[VTIME] = 0;
  6099. #endif /* VTIME */
  6100. #else /* OXOS */
  6101.     tttvt.c_time = 0;
  6102. #endif /* OXOS */
  6103. #endif /* VEOL */
  6104.  
  6105. #ifdef Plan9
  6106.     if (p9ttyparity('n') < 0)
  6107.       return -1;
  6108. #else
  6109. #ifdef BSD44ORPOSIX
  6110. #ifdef BEBOX
  6111.     tttvt.c_cc[VMIN] = 0;        /* DR7 can only poll. */
  6112. #endif /* BEBOX */
  6113.     if (tcsetattr(ttyfd,TCSADRAIN,&tttvt) < 0) return(-1);
  6114. #else /* ATTSV */
  6115.     if (ioctl(ttyfd,TCSETAW,&tttvt) < 0) return(-1);  /* set new modes . */
  6116. #endif /* BSD44ORPOSIX */
  6117. #endif /* Plan9 */
  6118. #endif /* ATTSV */
  6119.  
  6120.     ttspeed = speed;            /* Done, remember how we were */
  6121.     ttflow = flow;            /* called, so we can decide how to */
  6122.     tvtflg = 1;                /* respond next time. */
  6123.     debug(F101,"ttvt done","",tvtflg);
  6124.     return(0);
  6125.  
  6126. #ifdef COHERENT
  6127. #undef SVORPOSIX
  6128. #endif /* COHERENT */
  6129.  
  6130. #endif /* NOLOCAL */
  6131. }
  6132.  
  6133. #ifndef NOLOCAL
  6134.  
  6135. /* Serial speed department . . . */
  6136.  
  6137. /*
  6138.   Plan 9's native speed setting interface lets you set anything you like,
  6139.   but will fail if the hardware doesn't like it, so we allow all the common
  6140.   speeds.
  6141. */
  6142. #ifdef Plan9
  6143. #ifndef B50
  6144. #define B50 50
  6145. #endif /* B50 */
  6146. #ifndef B75
  6147. #define B75 75
  6148. #endif /* B75 */
  6149. #ifndef B110
  6150. #define B110 110
  6151. #endif /* B110 */
  6152. #ifndef B134
  6153. #define B134 134
  6154. #endif /* B134 */
  6155. #ifndef B200
  6156. #define B200 200
  6157. #endif /* B200 */
  6158. #ifndef B300
  6159. #define B300 300
  6160. #endif /* B300 */
  6161. #ifndef B1200
  6162. #define B1200 1200
  6163. #endif /* B1200 */
  6164. #ifndef B1800
  6165. #define B1800 1800
  6166. #endif /* B1800 */
  6167. #ifndef B2400
  6168. #define B2400 2400
  6169. #endif /* B2400 */
  6170. #ifndef B4800
  6171. #define B4800 4800
  6172. #endif /* B4800 */
  6173. #ifndef B9600
  6174. #define B9600 9600
  6175. #endif /* B9600 */
  6176. #ifndef B14400
  6177. #define B14400 14400
  6178. #endif /* B14400 */
  6179. #ifndef B19200
  6180. #define B19200 19200
  6181. #endif /* B19200 */
  6182. #ifndef B28800
  6183. #define B28800 28800
  6184. #endif /* B28800 */
  6185. #ifndef B38400
  6186. #define B38400 38400
  6187. #endif /* B38400 */
  6188. #ifndef B57600
  6189. #define B57600 57600
  6190. #endif /* B57600 */
  6191. #ifndef B76800
  6192. #define B76800 76800
  6193. #endif /* B76800 */
  6194. #ifndef B115200
  6195. #define B115200 115200
  6196. #endif /* B115200 */
  6197. #ifndef B230400
  6198. #define B230400 230400
  6199. #endif /* B230400 */
  6200. #ifndef B460800
  6201. #define B460800 460800
  6202. #endif /* B460800 */
  6203. #ifndef B921600
  6204. #define B921600 921600
  6205. #endif /* B921600 */
  6206. #endif /* Plan9 */
  6207.  
  6208. /*  T T S S P D  --  Checks and sets transmission rate.  */
  6209.  
  6210. /*  Call with speed in characters (not bits!) per second. */
  6211. /*  Returns -1 on failure, 0 if it did nothing, 1 if it changed the speed. */
  6212.  
  6213. #ifdef USETCSETSPEED
  6214. /*
  6215.   The tcsetspeed() / tcgetspeed() interface lets you pass any number at all
  6216.   to be used as a speed to be set, rather than forcing a choice from a
  6217.   predefined list.  It seems to be peculiar to UnixWare 7.
  6218.  
  6219.   These are the function codes to be passed to tc[gs]etspeed(),
  6220.   but for some reason they don't seem to be picked up from termios.h.
  6221. */
  6222. #ifndef TCS_ALL
  6223. #define TCS_ALL 0
  6224. #endif /* TCS_ALL */
  6225. #ifndef TCS_IN
  6226. #define TCS_IN 1
  6227. #endif /* TCS_IN */
  6228. #ifndef TCS_OUT
  6229. #define TCS_OUT 2
  6230. #endif /* TCS_OUT */
  6231. #endif /* USETCSETSPEED */
  6232.  
  6233. int
  6234. ttsspd(cps) int cps; {
  6235.     int x;
  6236. #ifdef POSIX
  6237. /* Watch out, speed_t should be unsigned, so don't compare with -1, etc... */
  6238.     speed_t
  6239. #else
  6240.     int
  6241. #endif /* POSIX */
  6242.       s, s2;
  6243.     int ok = 1;                /* Speed check result, assume ok */
  6244.  
  6245. #ifdef OLINUXHISPEED
  6246.     unsigned int spd_flags = 0;
  6247.     struct serial_struct serinfo;
  6248. #endif /* OLINUXHISPEED */
  6249.  
  6250.     debug(F101,"ttsspd cps","",cps);
  6251.     debug(F101,"ttsspd ttyfd","",ttyfd);
  6252.     debug(F101,"ttsspd xlocal","",xlocal);
  6253.  
  6254.     if (ttyfd < 0 || xlocal == 0 )    /* Don't set speed on console */
  6255.       return(0);
  6256.  
  6257. #ifdef    NETCONN
  6258.     if (netconn)
  6259.       return(0);
  6260. #endif    /* NETCONN */
  6261. #ifdef NETCMD
  6262.     if (ttpipe) return(0);
  6263. #endif /* NETCMD */
  6264. #ifdef NETPTY
  6265.     if (ttpty) return(0);
  6266. #endif /* NETPTY */
  6267.  
  6268.     if (cps < 0) return(-1);
  6269.     s = s2 = 0;                /* NB: s and s2 might be unsigned */
  6270.  
  6271. #ifdef USETCSETSPEED
  6272.  
  6273.     s = cps * 10L;
  6274.  
  6275.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  6276.     debug(F101,"ttsspd tcgetattr","",x);
  6277.     if (x < 0)
  6278.       return(-1);
  6279.     debug(F101,"ttsspd TCSETSPEED speed","",s);
  6280.  
  6281.     errno = 0;
  6282.     if (s == 8880L) {            /* 75/1200 split speed requested */
  6283.     tcsetspeed(TCS_IN, &ttcur, 1200L);
  6284.     tcsetspeed(TCS_OUT, &ttcur, 75L);
  6285.     } else
  6286.       tcsetspeed(TCS_ALL, &ttcur, s);    /* Put new speed in structs */
  6287. #ifdef DEBUG
  6288.     if (errno & deblog) {
  6289.     debug(F101,"ttsspd TCSETSPEED errno","",errno);
  6290.     }
  6291. #endif /* DEBUG */
  6292.  
  6293. #ifdef COMMENT
  6294.     tcsetspeed(TCS_ALL, &ttraw, s);
  6295.     tcsetspeed(TCS_ALL, &tttvt, s);
  6296.     tcsetspeed(TCS_ALL, &ttold, s);
  6297. #else
  6298.     if (s == 8880L) {            /* 75/1200 split speed requested */
  6299.     tcsetspeed(TCS_IN, &ttraw, 1200L);
  6300.     tcsetspeed(TCS_OUT, &ttraw, 75L);
  6301.     tcsetspeed(TCS_IN, &tttvt, 1200L);
  6302.     tcsetspeed(TCS_OUT, &tttvt, 75L);
  6303.     tcsetspeed(TCS_IN, &ttold, 1200L);
  6304.     tcsetspeed(TCS_OUT, &ttold, 75L);
  6305.     } else {
  6306.     tcsetspeed(TCS_ALL, &ttraw, s);
  6307.     tcsetspeed(TCS_ALL, &tttvt, s);
  6308.     tcsetspeed(TCS_ALL, &ttold, s);
  6309.     }
  6310. #endif /* COMMENT */
  6311.  
  6312.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur); /* Set the speed */
  6313.     debug(F101,"ttsspd tcsetattr","",x);
  6314.     if (x < 0)
  6315.       return(-1);
  6316.  
  6317. #else  /* Not USETCSETSPEED */
  6318.  
  6319. #ifdef MINIX2        /* Hack alert */
  6320. #define MINIX        /* Use pre-2.0 speed selection for Minix 2.0 as well */
  6321. #endif /* MINIX2 */
  6322.  
  6323.     /* First check that the given speed is valid. */
  6324.  
  6325.     switch (cps) {
  6326. #ifndef MINIX
  6327.       case 0:   s = B0;    break;
  6328.       case 5:   s = B50;   break;
  6329.       case 7:   s = B75;   break;
  6330. #endif /* MINIX */
  6331.       case 11:  s = B110;  break;
  6332. #ifndef MINIX
  6333.       case 13:  s = B134;  break;
  6334.       case 15:  s = B150;  break;
  6335.       case 20:  s = B200;  break;
  6336. #endif /* MINIX */
  6337.       case 30:  s = B300;  break;
  6338. #ifndef MINIX
  6339.       case 60:  s = B600;  break;
  6340. #endif /* MINIX */
  6341.       case 120: s = B1200; break;
  6342. #ifndef MINIX
  6343.       case 180: s = B1800; break;
  6344. #endif /* MINIX */
  6345.       case 240: s = B2400; break;
  6346.       case 480: s = B4800; break;
  6347. #ifndef MINIX
  6348.       case 888: s = B75; s2 = B1200; break; /* 888 = 75/1200 split speed */
  6349. #endif /* MINIX */
  6350. #ifdef B7200
  6351.       case 720: s = B7200; break;
  6352. #endif /* B7200 */
  6353.       case 960: s = B9600; break;
  6354. #ifdef B14400
  6355.       case 1440: s = B14400; break;
  6356. #endif /* B14400 */
  6357. #ifdef B19200
  6358.       case 1920: s = B19200; break;
  6359. #else
  6360. #ifdef EXTA
  6361.       case 1920: s = EXTA; break;
  6362. #endif /* EXTA */
  6363. #endif /* B19200 */
  6364. #ifdef B28800
  6365.       case 2880: s = B28800; break;
  6366. #endif /* B28800 */
  6367. #ifdef B38400
  6368.       case 3840: s = B38400;
  6369. #ifdef OLINUXHISPEED
  6370.         spd_flags = ~ASYNC_SPD_MASK;    /* Nonzero, but zero flags */
  6371. #endif /* OLINUXHISPEED */
  6372.     break;
  6373. #else /* B38400 not defined... */
  6374. #ifdef EXTB
  6375.       case 3840: s = EXTB; break;
  6376. #endif /* EXTB */
  6377. #endif /* B38400 */
  6378.  
  6379. #ifdef HPUX
  6380. #ifdef _B57600
  6381.       case 5760: s = _B57600; break;
  6382. #endif /* _B57600 */
  6383. #ifdef _B115200
  6384.       case 11520: s = _B115200; break;
  6385. #endif /* _B115200 */
  6386. #else
  6387. #ifdef OLINUXHISPEED
  6388. /*
  6389.   This bit from <carlo@sg.tn.tudelft.nl>:
  6390.   "Only note to make is maybe this: When the ASYNC_SPD_CUST flags are set then
  6391.   setting the speed to 38400 will set the custom speed (and ttgspd returns
  6392.   38400), but speeds 57600 and 115200 won't work any more because I didn't
  6393.   want to mess up the speed flags when someone is doing sophisticated stuff
  6394.   like custom speeds..."
  6395. */
  6396.       case 5760: s = B38400; spd_flags = ASYNC_SPD_HI; break;
  6397.       case 11520: s = B38400; spd_flags = ASYNC_SPD_VHI; break;
  6398. #else
  6399. #ifdef B57600
  6400.       case 5760: s = B57600; break;
  6401. #endif /* B57600 */
  6402. #ifdef B76800
  6403.       case 7680: s = B76800; break;
  6404. #endif /* B76800 */
  6405. #ifdef B115200
  6406.       case 11520: s = B115200; break;
  6407. #endif /* B115200 */
  6408. #endif /* OLINUXHISPEED */
  6409. #ifdef B153600
  6410.       case 15360: s = B153600; break;
  6411. #endif /* B153600 */
  6412. #ifdef B230400
  6413.       case 23040: s = B230400; break;
  6414. #endif /* B230400 */
  6415. #ifdef B307200
  6416.       case 30720: s = B307200; break;
  6417. #endif /* B307200 */
  6418. #ifdef B460800
  6419.       case 46080: s = B460800; break;
  6420. #endif /* 460800 */
  6421. #ifdef B921600
  6422.       case 92160: s = B921600; break;
  6423. #endif /* B921600 */
  6424. #endif /* HPUX */
  6425.       default:
  6426.     ok = 0;                /* Good speed not found, so not ok */
  6427.     break;
  6428.     }
  6429.     debug(F101,"ttsspd ok","",ok);
  6430.     debug(F101,"ttsspd s","",s);
  6431.  
  6432.     if (!ok) {
  6433.     debug(F100,"ttsspd fails","",0);
  6434.     return(-1);
  6435.     } else {
  6436.     if (!s2) s2 = s;        /* Set input speed */
  6437. #ifdef Plan9
  6438.     if (p9ttsspd(cps) < 0)
  6439.       return(-1);
  6440. #else
  6441. #ifdef BSD44ORPOSIX
  6442.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  6443.     debug(F101,"ttsspd tcgetattr","",x);
  6444.     if (x < 0)
  6445.       return(-1);
  6446. #ifdef OLINUXHISPEED
  6447.     debug(F101,"ttsspd spd_flags","",spd_flags);
  6448.     if (spd_flags && spd_flags != ASYNC_SPD_CUST) {
  6449.         if (ioctl(ttyfd, TIOCGSERIAL, &serinfo) < 0) {
  6450.         debug(F100,"ttsspd: TIOCGSERIAL failed","",0);
  6451.         return(-1);
  6452.         } else debug(F100,"ttsspd: TIOCGSERIAL ok","",0);
  6453.         serinfo.flags &= ~ASYNC_SPD_MASK;
  6454.         serinfo.flags |= (spd_flags & ASYNC_SPD_MASK);
  6455.         if (ioctl(ttyfd, TIOCSSERIAL, &serinfo) < 0)
  6456.           return(-1);
  6457.     }
  6458. #endif /* OLINUXHISPEED */
  6459.     cfsetospeed(&ttcur,s);
  6460.     cfsetispeed(&ttcur,s2);
  6461.     cfsetospeed(&ttraw,s);
  6462.     cfsetispeed(&ttraw,s2);
  6463.     cfsetospeed(&tttvt,s);
  6464.     cfsetispeed(&tttvt,s2);
  6465.     cfsetospeed(&ttold,s);
  6466.     cfsetispeed(&ttold,s2);
  6467.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  6468.     debug(F101,"ttsspd tcsetattr","",x);
  6469.     if (x < 0) return(-1);
  6470. #else
  6471. #ifdef ATTSV
  6472.     if (cps == 888) return(-1);    /* No split speeds, sorry. */
  6473.     x = ioctl(ttyfd,TCGETA,&ttcur);
  6474.     debug(F101,"ttsspd TCGETA ioctl","",x);
  6475.     if (x < 0) return(-1);
  6476.     ttcur.c_cflag &= ~CBAUD;
  6477.     ttcur.c_cflag |= s;
  6478.     tttvt.c_cflag &= ~CBAUD;
  6479.     tttvt.c_cflag |= s;
  6480.     ttraw.c_cflag &= ~CBAUD;
  6481.     ttraw.c_cflag |= s;
  6482.     ttold.c_cflag &= ~CBAUD;
  6483.     ttold.c_cflag |= s;
  6484.     x = ioctl(ttyfd,TCSETAW,&ttcur);
  6485.     debug(F101,"ttsspd TCSETAW ioctl","",x);
  6486.     if (x < 0) return(-1);
  6487. #else
  6488. #ifdef BELLV10
  6489.     x = ioctl(ttyfd,TIOCGDEV,&tdcur);
  6490.     debug(F101,"ttsspd TIOCGDEV ioctl","",x);
  6491.     if (x < 0) return(-1);
  6492.     tdcur.ispeed = s2;
  6493.     tdcur.ospeed = s;
  6494.     errno = 0;
  6495.     ok = ioctl(ttyfd,TIOCSDEV,&tdcur);
  6496.     debug(F101,"ttsspd BELLV10 ioctl","",ok);
  6497.     if (ok < 0) {
  6498.         perror(ttnmsv);
  6499.         debug(F101,"ttsspd BELLV10 errno","",ok);
  6500.         return(-1);
  6501.     }
  6502. #else
  6503.     x = gtty(ttyfd,&ttcur);
  6504.     debug(F101,"ttsspd gtty","",x);
  6505.     if (x < 0) return(-1);
  6506.     ttcur.sg_ospeed = s; ttcur.sg_ispeed = s2;
  6507.     tttvt.sg_ospeed = s; tttvt.sg_ispeed = s2;
  6508.     ttraw.sg_ospeed = s; ttraw.sg_ispeed = s2;
  6509.     ttold.sg_ospeed = s; ttold.sg_ispeed = s2;
  6510.     x = stty(ttyfd,&ttcur);
  6511.     debug(F101,"ttsspd stty","",x);
  6512.     if (x < 0) return(-1);
  6513. #endif /* BELLV10 */
  6514. #endif /* ATTSV */
  6515. #endif /* BSD44ORPOSIX */
  6516. #endif /* Plan9 */
  6517.     }
  6518.     return(1);                /* Return 1 = success. */
  6519. #endif /* USETCSETSPEED */
  6520. }
  6521.  
  6522. #endif /* NOLOCAL */
  6523.  
  6524. /* C O N G S P D  -  Get speed of console terminal  */
  6525.  
  6526. long
  6527. congspd() {
  6528. /*
  6529.   This is a disgusting hack.  The right way to do this would be to pass an
  6530.   argument to ttgspd(), but then we'd need to change the Kermit API and
  6531.   all of the ck?tio.c modules.  (Currently used only for rlogin.)
  6532. */
  6533.     int t1, t2;
  6534.     long spd;
  6535. #ifdef NETCONN
  6536.  
  6537.     t2 = netconn;
  6538.     netconn = 0;
  6539. #endif /* NETCONN */
  6540.     t1 = ttyfd;
  6541.     ttyfd = -1;
  6542.     spd = ttgspd();
  6543.     debug(F101,"congspd","",spd);
  6544. #ifdef NETCONN
  6545.     netconn = t2;
  6546. #endif /* NETCONN */
  6547.     ttyfd = t1;
  6548.     return(spd);
  6549. }
  6550.  
  6551. /*  T T S P D L I S T  -- Get list of serial speeds allowed on this platform */
  6552.  
  6553. #define NSPDLIST 64
  6554. static long spdlist[NSPDLIST];
  6555. /*
  6556.   As written, this picks up the speeds known at compile time, and thus
  6557.   apply to the system where C-Kermit was built, rather than to the one where
  6558.   it is running.  Suggestions for improvement are always welcome.
  6559. */
  6560. long *
  6561. ttspdlist() {
  6562.     int i;
  6563.     for (i = 0; i < NSPDLIST; i++)    /* Initialize the list */
  6564.       spdlist[i] = -1L;
  6565.     i = 1;
  6566.  
  6567. #ifdef USETCSETSPEED            /* No way to find out what's legal */
  6568.  
  6569.     spdlist[i++] = 50L;
  6570. #ifndef UW7
  6571.     spdlist[i++] = 75L;
  6572. #endif /* UW7 */
  6573.     spdlist[i++] = 110L;
  6574. #ifndef UW7
  6575.     spdlist[i++] = 134L;
  6576. #endif /* UW7 */
  6577.     spdlist[i++] = 150L;
  6578.     spdlist[i++] = 200L;
  6579.     spdlist[i++] = 300L;
  6580.     spdlist[i++] = 600L;
  6581.     spdlist[i++] = 1200L;
  6582.     spdlist[i++] = 1800L;
  6583.     spdlist[i++] = 2400L;
  6584.     spdlist[i++] = 4800L;
  6585.     spdlist[i++] = 8880L;
  6586.     spdlist[i++] = 9600L;
  6587.     spdlist[i++] = 14400L;
  6588.     spdlist[i++] = 19200L;
  6589.     spdlist[i++] = 28800L;
  6590. #ifndef UW7
  6591.     spdlist[i++] = 33600L;
  6592. #endif /* UW7 */
  6593.     spdlist[i++] = 38400L;
  6594.     spdlist[i++] = 57600L;
  6595.     spdlist[i++] = 76800L;
  6596.     spdlist[i++] = 115200L;
  6597. #ifndef UW7
  6598.     spdlist[i++] = 153600L;
  6599.     spdlist[i++] = 230400L;
  6600.     spdlist[i++] = 307200L;
  6601.     spdlist[i++] = 460800L;
  6602.     spdlist[i++] = 921600L;
  6603. #endif /* UW7 */
  6604.  
  6605. #else  /* USETCSETSPEED */
  6606.  
  6607. #ifdef B50
  6608.     spdlist[i++] = 50L;
  6609. #endif /* B50 */
  6610. #ifdef B75
  6611.     spdlist[i++] = 75L;
  6612. #endif /* B75 */
  6613. #ifdef B110
  6614.     spdlist[i++] = 110L;
  6615. #endif /* B110 */
  6616. #ifdef B134
  6617.     spdlist[i++] = 134L;
  6618. #endif /* B134 */
  6619. #ifdef B150
  6620.     spdlist[i++] = 150L;
  6621. #endif /* B150 */
  6622. #ifdef B200
  6623.     spdlist[i++] = 200L;
  6624. #endif /* B200 */
  6625. #ifdef B300
  6626.     spdlist[i++] = 300L;
  6627. #endif /* B300 */
  6628. #ifdef B600
  6629.     spdlist[i++] = 600L;
  6630. #endif /* B600 */
  6631. #ifdef B1200
  6632.     spdlist[i++] = 1200L;
  6633. #endif /* B1200 */
  6634. #ifdef B1800
  6635.     spdlist[i++] = 1800L;
  6636. #endif /* B1800 */
  6637. #ifdef B2400
  6638.     spdlist[i++] = 2400L;
  6639. #endif /* B2400 */
  6640. #ifdef B4800
  6641.     spdlist[i++] = 4800L;
  6642. #endif /* B4800 */
  6643. #ifdef B9600
  6644.     spdlist[i++] = 9600L;
  6645. #endif /* B9600 */
  6646. #ifdef B14400
  6647.     spdlist[i++] = 14400L;
  6648. #endif /* B14400 */
  6649. #ifdef B19200
  6650.     spdlist[i++] = 19200L;
  6651. #else
  6652. #ifdef EXTA
  6653.     spdlist[i++] = 19200L;
  6654. #endif /* EXTA */
  6655. #endif /* B19200 */
  6656. #ifdef B28800
  6657.     spdlist[i++] = 28800L;
  6658. #endif /* B28800 */
  6659. #ifdef B33600
  6660.     spdlist[i++] = 33600L;
  6661. #endif /* B33600 */
  6662. #ifdef B38400
  6663.     spdlist[i++] = 38400L;
  6664. #else
  6665. #ifdef EXTB
  6666.     spdlist[i++] = 38400L;
  6667. #endif /* EXTB */
  6668. #endif /* B38400 */
  6669. #ifdef _B57600
  6670.     spdlist[i++] = 57600L;
  6671. #else
  6672. #ifdef B57600
  6673.     spdlist[i++] = 57600L;
  6674. #endif /* B57600 */
  6675. #endif /* _B57600 */
  6676. #ifdef B76800
  6677.     spdlist[i++] = 76800L;
  6678. #endif /* B76800 */
  6679. #ifdef _B115200
  6680.     spdlist[i++] = 115200L;
  6681. #else
  6682. #ifdef B115200
  6683.     spdlist[i++] = 115200L;
  6684. #endif /* B115200 */
  6685. #endif /* _B115200 */
  6686. #ifdef B153600
  6687.     spdlist[i++] = 153600L;
  6688. #endif /* B153600 */
  6689. #ifdef B230400
  6690.     spdlist[i++] = 230400L;
  6691. #endif /* B230400 */
  6692. #ifdef B307200
  6693.     spdlist[i++] = 307200L;
  6694. #endif /* B307200 */
  6695. #ifdef B460800
  6696.     spdlist[i++] = 460800L;
  6697. #endif /* B460800 */
  6698. #ifdef B921600
  6699.     spdlist[i++] = 921600L;
  6700. #endif /* B921600 */
  6701. #endif /* USETCSETSPEED */
  6702.     spdlist[0] = i - 1;            /* Return count in 0th element */
  6703.     return((long *)spdlist);
  6704. }
  6705.  
  6706. /* T T G S P D  -  Get speed of currently selected tty line  */
  6707.  
  6708. /*
  6709.   Unreliable.  After SET LINE, it returns an actual speed, but not necessarily
  6710.   the real speed.  On some systems, it returns the line's nominal speed, from
  6711.   /etc/ttytab.  Even if you SET SPEED to something else, this function might
  6712.   not notice.
  6713. */
  6714. long
  6715. ttgspd() {                /* Get current serial device speed */
  6716. #ifdef NOLOCAL
  6717.     return(-1L);
  6718. #else
  6719. #ifdef POSIX
  6720.     speed_t                /* Should be unsigned */
  6721. #else
  6722.     int                    /* Isn't unsigned */
  6723. #endif /* POSIX */
  6724.       s;
  6725.     int x;
  6726.     long ss;
  6727. #ifdef OLINUXHISPEED
  6728.     unsigned int spd_flags = 0;
  6729.     struct serial_struct serinfo;
  6730. #endif /* OLINUXHISPEED */
  6731.  
  6732. #ifdef NETCONN
  6733.     if (netconn) return(-1);        /* -1 if network connection */
  6734. #endif /* NETCONN */
  6735. #ifdef NETCMD
  6736.     if (ttpipe) return(-1);
  6737. #endif /* NETCMD */
  6738. #ifdef NETPTY
  6739.     if (ttpty) return(-1);
  6740. #endif /* NETPTY */
  6741.  
  6742.     debug(F101,"ttgspd ttyfd","",ttyfd);
  6743.  
  6744. #ifdef USETCSETSPEED
  6745.  
  6746.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  6747.     debug(F101,"ttgspd tcgetattr","",x);
  6748.     if (x < 0)
  6749.       return(-1);
  6750.     errno = 0;
  6751.     s = tcgetspeed(TCS_ALL, &ttcur);
  6752.     debug(F101,"ttsspd TCGETSPEED speed","",s);
  6753.     if (s == 0) {
  6754.     long s1, s2;
  6755.     s1 = tcgetspeed(TCS_IN, &ttcur);
  6756.     s2 = tcgetspeed(TCS_OUT, &ttcur);
  6757.     if (s1 == 1200L && s2 == 75L)
  6758.       return(8880L);
  6759.     }
  6760. #ifdef DEBUG
  6761.     if (errno & deblog) {
  6762.     debug(F101,"ttsspd TCGETSPEED errno","",errno);
  6763.     }
  6764. #endif /* DEBUG */
  6765.     return(s);
  6766.  
  6767. #else  /* Not USETCSETSPEED */
  6768.  
  6769. #ifdef Plan9
  6770.     if (ttyfd < 0)
  6771.       ss = -1;
  6772.     else
  6773.       ss = ttylastspeed;
  6774. #else
  6775. #ifdef OLINUXHISPEED
  6776.     debug(F100,"ttgspd Linux OLINUXHISPEED","",0);
  6777. #endif /* OLINUXHISPEED */
  6778.  
  6779.     if (ttyfd < 0) {
  6780. #ifdef BSD44ORPOSIX
  6781.     s = cfgetospeed(&ccold);
  6782.     debug(F101,"ttgspd cfgetospeed 1 POSIX","",s);
  6783. #else
  6784. #ifdef ATTSV
  6785.     s = ccold.c_cflag & CBAUD;
  6786.     debug(F101,"ttgspd c_cflag CBAUD 1 ATTSV","",s);
  6787. #else
  6788.     s = ccold.sg_ospeed;        /* (obtained by congm()) */
  6789.     debug(F101,"ttgspd sg_ospeed 1","",s);
  6790. #endif /* ATTSV */
  6791. #endif /* BSD44POSIX */
  6792.  
  6793.     } else {
  6794. #ifdef BSD44ORPOSIX
  6795.     if (tcgetattr(ttyfd,&ttcur) < 0) return(-1);
  6796.     s = cfgetospeed(&ttcur);
  6797.     debug(F101,"ttgspd cfgetospeed 2 BSDORPOSIX","",s);
  6798. #ifdef OLINUXHISPEED
  6799.     if (ioctl(ttyfd,TIOCGSERIAL,&serinfo) > -1)
  6800.       spd_flags = serinfo.flags & ASYNC_SPD_MASK;
  6801.     debug(F101,"ttgspd spd_flags","",spd_flags);
  6802. #endif /* OLINUXHISPEED */
  6803. #else
  6804. #ifdef ATTSV
  6805.     x = ioctl(ttyfd,TCGETA,&ttcur);
  6806.     debug(F101,"ttgspd ioctl 2 ATTSV x","",x);
  6807.     debug(F101,"ttgspd ioctl 2 ATTSV errno","",errno);
  6808.     if (x < 0) return(-1);
  6809.     s = ttcur.c_cflag & CBAUD;
  6810.     debug(F101,"ttgspd ioctl 2 ATTSV speed","",s);
  6811. #else
  6812. #ifdef BELLV10
  6813.     x = ioctl(ttyfd,TIOCGDEV,&tdcur);
  6814.     debug(F101,"ttgspd ioctl 2 BELLV10 x","",x);
  6815.     if (x < 0) return(-1);
  6816.     s = tdcur.ospeed;
  6817.     debug(F101,"ttgspd ioctl 2 BELLV10 speed","",s);
  6818. #else
  6819.     x = gtty(ttyfd,&ttcur);
  6820.     debug(F101,"ttgspd gtty 2 x","",x);
  6821.     debug(F101,"ttgspd gtty 2 errno","",errno);
  6822.     if (x < 0) return(-1);
  6823.     s = ttcur.sg_ospeed;
  6824.     debug(F101,"ttgspd gtty 2 speed","",s);
  6825. #endif /* BELLV10 */
  6826. #endif /* ATTSV */
  6827. #endif /* BSD44ORPOSIX */
  6828.     }
  6829.     debug(F101,"ttgspd code","",s);
  6830. #ifdef OLINUXHISPEED
  6831.     debug(F101,"ttgspd spd_flags","",spd_flags);
  6832. #endif /* OLINUXHISPEED */
  6833.     switch (s) {
  6834. #ifdef B0
  6835.       case B0:    ss = 0L; break;
  6836. #endif /* B0 */
  6837.  
  6838. #ifndef MINIX
  6839. /*
  6840.  MINIX defines the Bxx symbols to be bps/100, so B50==B75, B110==B134==B150,
  6841.  etc, making for many "duplicate case in switch" errors, which are fatal.
  6842. */
  6843. #ifdef B50
  6844.       case B50:   ss = 50L; break;
  6845. #endif /* B50 */
  6846. #ifdef B75
  6847.       case B75:   ss = 75L; break;
  6848. #endif /* B75 */
  6849. #endif /* MINIX */
  6850.  
  6851. #ifdef B110
  6852.       case B110:  ss = 110L; break;
  6853. #endif /* B110 */
  6854.  
  6855. #ifndef MINIX
  6856. #ifdef B134
  6857.       case B134:  ss = 134L; break;
  6858. #endif /* B134 */
  6859. #ifdef B150
  6860.       case B150:  ss = 150L; break;
  6861. #endif /* B150 */
  6862. #endif /* MINIX */
  6863.  
  6864. #ifdef B200
  6865.       case B200:  ss = 200L; break;
  6866. #endif /* B200 */
  6867.  
  6868. #ifdef B300
  6869.       case B300:  ss = 300L; break;
  6870. #endif /* B300 */
  6871.  
  6872. #ifdef B600
  6873.       case B600:  ss = 600L; break;
  6874. #endif /* B600 */
  6875.  
  6876. #ifdef B1200
  6877.       case B1200: ss = 1200L; break;
  6878. #endif /* B1200 */
  6879.  
  6880. #ifdef B1800
  6881.       case B1800: ss = 1800L; break;
  6882. #endif /* B1800 */
  6883.  
  6884. #ifdef B2400
  6885.       case B2400: ss = 2400L; break;
  6886. #endif /* B2400 */
  6887.  
  6888. #ifdef B4800
  6889.       case B4800: ss = 4800L; break;
  6890. #endif /* B4800 */
  6891.  
  6892. #ifdef B7200
  6893.       case B7200: ss = 7200L; break;
  6894. #endif /* B7200 */
  6895.  
  6896. #ifdef B9600
  6897.       case B9600: ss = 9600L; break;
  6898. #endif /* B9600 */
  6899.  
  6900. #ifdef B19200
  6901.       case B19200: ss = 19200L; break;
  6902. #else
  6903. #ifdef EXTA
  6904.       case EXTA: ss = 19200L; break;
  6905. #endif /* EXTA */
  6906. #endif /* B19200 */
  6907.  
  6908. #ifdef MINIX2
  6909. /* End of hack to make MINIX2 use MINIX1 speed setting */
  6910. #undef MINIX
  6911. #endif /* MINIX2 */
  6912.  
  6913. #ifndef MINIX
  6914. #ifdef B38400
  6915.       case B38400:
  6916.         ss = 38400L;
  6917. #ifdef OLINUXHISPEED
  6918.         switch(spd_flags) {
  6919.           case ASYNC_SPD_HI:  ss =  57600L; break;
  6920.           case ASYNC_SPD_VHI: ss = 115200L; break;
  6921.     }
  6922. #endif /* OLINUXHISPEED */
  6923.         break;
  6924. #else
  6925. #ifdef EXTB
  6926.       case EXTB: ss = 38400L; break;
  6927. #endif /* EXTB */
  6928. #endif /* B38400 */
  6929. #endif /* MINIX */
  6930.  
  6931. #ifdef HPUX
  6932. #ifdef _B57600
  6933.       case _B57600: ss = 57600L; break;
  6934. #endif /* _B57600 */
  6935. #ifdef _B115200
  6936.       case _B115200: ss = 115200L; break;
  6937. #endif /* _B115200 */
  6938. #else
  6939. #ifdef B57600
  6940.       case B57600: ss = 57600L; break;
  6941. #endif /* B57600 */
  6942. #ifdef B76800
  6943.       case B76800: ss = 76800L; break;
  6944. #endif /* B76800 */
  6945. #ifdef B115200
  6946.       case B115200: ss = 115200L; break;
  6947. #endif /* B115200 */
  6948. #ifdef B153600
  6949.       case B153600: ss = 153600L; break;
  6950. #endif /* B153600 */
  6951. #ifdef B230400
  6952.       case B230400: ss = 230400L; break;
  6953. #endif /* B230400 */
  6954. #ifdef B307200
  6955.       case B307200: ss = 307200L; break;
  6956. #endif /* B307200 */
  6957. #ifdef B460800
  6958.       case B460800: ss = 460800L; break;
  6959. #endif /* B460800 */
  6960. #endif /* HPUX */
  6961. #ifdef B921600
  6962.       case 92160: ss = 921600L; break;
  6963. #endif /* B921600 */
  6964.       default:
  6965.     ss = -1; break;
  6966.     }
  6967. #endif /* Plan9 */
  6968.     debug(F101,"ttgspd speed","",ss);
  6969.     return(ss);
  6970.  
  6971. #endif /* USETCSETSPEED */
  6972. #endif /* NOLOCAL */
  6973. }
  6974. #ifdef MINIX2                /* Another hack alert */
  6975. #define MINIX
  6976. #endif /* MINIX2 */
  6977.  
  6978. /*
  6979.   FIONREAD data type...  This has been defined as "long" for many, many
  6980.   years, and it worked OK until 64-bit platforms appeared.  Thus we use
  6981.   int for 64-bit platforms, but keep long for the others.  If we changed
  6982.   the default PEEKTYPE to int, this would probably break 16-bit builds
  6983.   (note that sizeof(long) == sizeof(int) on most 32-bit platforms), many
  6984.   of which we have no way of testing any more.  Therefore, do not change
  6985.   the default definition of PEEKTYPE -- only add exceptions to it as needed.
  6986. */
  6987. #ifdef COHERENT
  6988. #ifdef FIONREAD
  6989. #undef FIONREAD
  6990. #endif /* FIONREAD */
  6991. /* #define FIONREAD TIOCQUERY */
  6992. /* #define PEEKTYPE int */
  6993. #else  /* Not COHERENT... */
  6994.  
  6995. #ifdef OSF32                /* Digital UNIX 3.2 or higher */
  6996. #define PEEKTYPE int
  6997. #else
  6998. #define PEEKTYPE long            /* Elsewhere (see notes above) */
  6999. #endif /* OSF32 */
  7000. #endif /* COHERENT */
  7001.  
  7002. /* ckumyr.c by Kristoffer Eriksson, ske@pkmab.se, 15 Mar 1990. */
  7003.  
  7004. #ifdef MYREAD
  7005.  
  7006. /* Private buffer for myread() and its companions.  Not for use by anything
  7007.  * else.  ttflui() is allowed to reset them to initial values.  ttchk() is
  7008.  * allowed to read my_count.
  7009.  *
  7010.  * my_item is an index into mybuf[].  Increment it *before* reading mybuf[].
  7011.  *
  7012.  * A global parity mask variable could be useful too.  We could use it to
  7013.  * let myread() strip the parity on its own, instead of stripping sign
  7014.  * bits as it does now.
  7015.  */
  7016. #ifdef BIGBUFOK
  7017. #define MYBUFLEN 32768
  7018. #else
  7019. #ifdef pdp11
  7020. #define MYBUFLEN 256
  7021. #else
  7022. #define MYBUFLEN 1024
  7023. #endif /* pdp11 */
  7024. #endif /* BIGBUFOK */
  7025.  
  7026. #ifdef ANYX25
  7027. #undef MYBUFLEN
  7028. #define MYBUFLEN 256
  7029. /*
  7030.   On X.25 connections, there is an extra control byte at the beginning.
  7031. */
  7032. static CHAR x25buf[MYBUFLEN+1];        /* Communication device input buffer */
  7033. static CHAR  *mybuf = x25buf+1;
  7034. #else
  7035. static CHAR mybuf[MYBUFLEN];
  7036. #endif /* ANYX25 */
  7037.  
  7038. static int my_count = 0;        /* Number of chars still in mybuf */
  7039. static int my_item = -1;        /* Last index read from mybuf[]   */
  7040.  
  7041. /*  T T P E E K  --  Peek into our internal communications input buffers. */
  7042.  
  7043. /*
  7044.   NOTE: This routine is peculiar to UNIX, and is used only by the
  7045.   select()-based CONNECT module, ckucns.c.  It need not be replicated in
  7046.   the ck?tio.c of other platforms.
  7047. */
  7048. int
  7049. ttpeek() {
  7050.     int rc = 0;
  7051. #ifdef TTLEBUF
  7052.     if (ttpush >= 0)
  7053.       rc++;
  7054.     rc += le_inbuf();
  7055.     if (rc > 0)
  7056.       return(rc);
  7057.     else
  7058. #endif /* TTLEBUF */
  7059.  
  7060. #ifdef MYREAD
  7061.     return(my_count);
  7062. #else
  7063.     return(0);
  7064. #endif /* MYREAD */
  7065. }
  7066.  
  7067. /* myread() -- Efficient read of one character from communications line.
  7068.  *
  7069.  * Uses a private buffer to minimize the number of expensive read() system
  7070.  * calls.  Essentially performs the equivalent of read() of 1 character, which
  7071.  * is then returned.  By reading all available input from the system buffers
  7072.  * to the private buffer in one chunk, and then working from this buffer, the
  7073.  * number of system calls is reduced in any case where more than one character
  7074.  * arrives during the processing of the previous chunk, for instance high
  7075.  * baud rates or network type connections where input arrives in packets.
  7076.  * If the time needed for a read() system call approaches the time for more
  7077.  * than one character to arrive, then this mechanism automatically compensates
  7078.  * for that by performing bigger read()s less frequently.  If the system load
  7079.  * is high, the same mechanism compensates for that too.
  7080.  *
  7081.  * myread() is a macro that returns the next character from the buffer.  If the
  7082.  * buffer is empty, mygetbuf() is called.  See mygetbuf() for possible error
  7083.  * returns.
  7084.  *
  7085.  * This should be efficient enough for any one-character-at-a-time loops.
  7086.  * For even better efficiency you might use memcpy()/bcopy() or such between
  7087.  * buffers (since they are often better optimized for copying), but it may not
  7088.  * be worth it if you have to take an extra pass over the buffer to strip
  7089.  * parity and check for CTRL-C anyway.
  7090.  *
  7091.  * Note that if you have been using myread() from another program module, you
  7092.  * may have some trouble accessing this macro version and the private variables
  7093.  * it uses.  In that case, just add a function in this module, that invokes the
  7094.  * macro.
  7095.  */
  7096. #define myread() (--my_count < 0 ? mygetbuf() : 255 & (int)mybuf[++my_item])
  7097.  
  7098. /* Specification: Push back up to one character onto myread()'s queue.
  7099.  *
  7100.  * This implementation: Push back characters into mybuf. At least one character
  7101.  * must have been read through myread() before myunrd() may be used.  After
  7102.  * EOF or read error, again, myunrd() can not be used.  Sometimes more than
  7103.  * one character can be pushed back, but only one character is guaranteed.
  7104.  * Since a previous myread() must have read its character out of mybuf[],
  7105.  * that guarantees that there is space for at least one character.  If push
  7106.  * back was really needed after EOF, a small addition could provide that.
  7107.  *
  7108.  * myunrd() is currently not called from anywhere inside kermit...
  7109.  */
  7110. #ifdef COMMENT /* not used */
  7111. myunrd(ch) CHAR ch; {
  7112.     if (my_item >= 0) {
  7113.     mybuf[my_item--] = ch;
  7114.     ++my_count;
  7115.     }
  7116. }
  7117. #endif /* COMMENT */
  7118.  
  7119. /*  T T P U S H B A C K  --  Put n bytes back into the myread buffer */
  7120.  
  7121. static CHAR * pushbuf = NULL;
  7122. static int pushed = 0;
  7123.  
  7124. int
  7125. ttpushback(s,n) CHAR * s; int n; {
  7126.     debug(F101,"ttpushback n","",n);
  7127.     if (pushbuf || n > MYBUFLEN || n < 1)
  7128.       return(-1);
  7129.     debug(F101,"ttpushback my_count","",my_count);
  7130.     if (my_count > 0) {
  7131.     if (!(pushbuf = (CHAR *)malloc(n+1)))
  7132.       return(-1);
  7133.     memcpy(pushbuf,mybuf,my_count);
  7134.     pushed = my_count;
  7135.     }
  7136.     memcpy(mybuf,s,n);
  7137.     my_count = n;
  7138.     my_item = -1;
  7139.     return(0);
  7140. }
  7141.  
  7142. /* mygetbuf() -- Fill buffer for myread() and return first character.
  7143.  *
  7144.  * This function is what myread() uses when it can't get the next character
  7145.  * directly from its buffer.  First, it calls a system dependent myfillbuf()
  7146.  * to read at least one new character into the buffer, and then it returns
  7147.  * the first character just as myread() would have done.  This function also
  7148.  * is responsible for all error conditions that myread() can indicate.
  7149.  *
  7150.  * Returns: When OK    => a positive character, 0 or greater.
  7151.  *        When EOF    => -2.
  7152.  *        When error    => -3, error code in errno.
  7153.  *
  7154.  * Older myread()s additionally returned -1 to indicate that there was nothing
  7155.  * to read, upon which the caller would call myread() again until it got
  7156.  * something.  The new myread()/mygetbuf() always gets something.  If it
  7157.  * doesn't, then make it do so!  Any program that actually depends on the old
  7158.  * behaviour will break.
  7159.  *
  7160.  * The older version also used to return -2 both for EOF and other errors,
  7161.  * and used to set errno to 9999 on EOF.  The errno stuff is gone, EOF and
  7162.  * other errors now return different results, although Kermit currently never
  7163.  * checks to see which it was.  It just disconnects in both cases.
  7164.  *
  7165.  * Kermit lets the user use the quit key to perform some special commands
  7166.  * during file transfer.  This causes read(), and thus also mygetbuf(), to
  7167.  * finish without reading anything and return the EINTR error.  This should
  7168.  * be checked by the caller.  Mygetbuf() could retry the read() on EINTR,
  7169.  * but if there is nothing to read, this could delay Kermit's reaction to
  7170.  * the command, and make Kermit appear unresponsive.
  7171.  *
  7172.  * The debug() call should be removed for optimum performance.
  7173.  */
  7174. int
  7175. mygetbuf() {
  7176.     int x;
  7177.     errno = 0;
  7178. #ifdef DEBUG
  7179.     if (deblog && my_count > 0)
  7180.       debug(F101,"mygetbuf IMPROPERLY CALLED with my_count","",my_count);
  7181. #endif /* DEBUG */
  7182.     if (my_count <= 0)
  7183.       my_count = myfillbuf();
  7184.  
  7185. #ifdef DEBUG
  7186.     if (deblog) debug(F101, "mygetbuf read", "", my_count);
  7187. #endif /* DEBUG */
  7188.     x = my_count;
  7189.     if (my_count <= 0) {
  7190.     my_count = 0;
  7191.     my_item = -1;
  7192.     debug(F101,"mygetbuf errno","",errno);
  7193. #ifdef TCPSOCKET
  7194.     if (netconn && ttnet == NET_TCPB && errno != 0) {
  7195.         if (errno != EINTR) {
  7196.         debug(F101,"mygetbuf TCP error","",errno);
  7197.         ttclos(0);        /* Close the connection. */
  7198.         }
  7199.         return(-3);
  7200.     }
  7201. #endif /* TCPSOCKET */
  7202.     if (!netconn && xlocal && errno) {
  7203.         if (errno != EINTR) {
  7204.         debug(F101,"mygetbuf SERIAL error","",errno);
  7205.         x = -3;
  7206.         ttclos(0);        /* Close the connection. */
  7207.         }
  7208.     }
  7209.     return((x < 0) ? -3 : -2);
  7210.     }
  7211.     --my_count;
  7212.     return((unsigned)(0xff & mybuf[my_item = 0]));
  7213. }
  7214.  
  7215. /* myfillbuf():
  7216.  * System-dependent read() into mybuf[], as many characters as possible.
  7217.  *
  7218.  * Returns: OK => number of characters read, always more than zero.
  7219.  *          EOF => 0
  7220.  *          Error => -1, error code in errno.
  7221.  *
  7222.  * If there is input available in the system's buffers, all of it should be
  7223.  * read into mybuf[] and the function return immediately.  If no input is
  7224.  * available, it should wait for a character to arrive, and return with that
  7225.  * one in mybuf[] as soon as possible.  It may wait somewhat past the first
  7226.  * character, but be aware that any such delay lengthens the packet turnaround
  7227.  * time during kermit file transfers.  Should never return with zero characters
  7228.  * unless EOF or irrecoverable read error.
  7229.  *
  7230.  * Correct functioning depends on the correct tty parameters being used.
  7231.  * Better control of current parameters is required than may have been the
  7232.  * case in older Kermit releases.  For instance, O_NDELAY (or equivalent) can
  7233.  * no longer be sometimes off and sometimes on like it used to, unless a
  7234.  * special myfillbuf() is written to handle that.  Otherwise the ordinary
  7235.  * myfillbuf()s may think they have come to EOF.
  7236.  *
  7237.  * If your system has a facility to directly perform the functioning of
  7238.  * myfillbuf(), then use it.  If the system can tell you how many characters
  7239.  * are available in its buffers, then read that amount (but not less than 1).
  7240.  * If the system can return a special indication when you try to read without
  7241.  * anything to read, while allowing you to read all there is when there is
  7242.  * something, you may loop until there is something to read, but probably that
  7243.  * is not good for the system load.
  7244.  */
  7245.  
  7246. #ifdef SVORPOSIX
  7247.     /* This is for System III/V with VMIN>0, VTIME=0 and O_NDELAY off,
  7248.      * and CLOCAL set any way you like.  This way, read() will do exactly
  7249.      * what is required by myfillbuf(): If there is data in the buffers
  7250.      * of the O.S., all available data is read into mybuf, up to the size
  7251.      * of mybuf.  If there is none, the first character to arrive is
  7252.      * awaited and returned.
  7253.      */
  7254. int
  7255. myfillbuf() {
  7256.     int fd, n;
  7257. #ifdef NETCMD
  7258.     if (ttpipe)
  7259.       fd = fdin;
  7260.     else
  7261. #endif /* NETCMD */
  7262.       fd = ttyfd;
  7263.  
  7264. #ifdef sxaE50
  7265.     /* From S. Dezawa at Fujifilm in Japan.  I don't know why this is */
  7266.     /* necessary for the sxa E50, but it is. */
  7267.     return read(fd, mybuf, 255);
  7268. #else
  7269. #ifdef BEBOX
  7270.     while (1) {
  7271. #ifdef NETCONN
  7272.         if (netconn) {
  7273.             n = netxin(sizeof(mybuf), (char *)mybuf);
  7274.             debug(F101,"BEBOX SVORPOSIX network myfillbuf","",n);
  7275.     }
  7276.         else
  7277. #endif /* NETCONN */
  7278.       n = read(fd, mybuf, sizeof(mybuf));
  7279.     debug(F101,"BEBOX SVORPOSIX notnet myfillbuf","",n);
  7280.         if (n > 0)
  7281.       return(n);
  7282.         snooze(1000.0);
  7283.     }
  7284. #else /* BEBOX */
  7285.     errno = 0;
  7286.     debug(F100,"SVORPOSIX myfillbuf calling read()","",0);
  7287. #ifdef IBMX25
  7288.     if (netconn && (nettype == NET_IX25)) {
  7289.     /* can't use sizeof because mybuf is a pointer, and not an array! */
  7290.     n = x25xin( MYBUFLEN, mybuf );
  7291.     } else
  7292. #endif /* IBMX25 */
  7293.  
  7294. #ifdef CK_SSL
  7295.       if (ssl_active_flag || tls_active_flag) {
  7296.       int error, n = 0;
  7297.       while (n == 0) {
  7298.           if (ssl_active_flag)
  7299.                 n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  7300.           else if (tls_active_flag)
  7301.                 n = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  7302.               else
  7303.         break;
  7304.           switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  7305.         case SSL_ERROR_NONE:
  7306.           if (n > 0)
  7307.                     return(n);
  7308.           if (n < 0)
  7309.                     return(-2);
  7310.           msleep(50);
  7311.           break;
  7312.         case SSL_ERROR_WANT_WRITE:
  7313.         case SSL_ERROR_WANT_READ:
  7314.           return(-1);
  7315.         case SSL_ERROR_SYSCALL:
  7316.         case SSL_ERROR_WANT_X509_LOOKUP:
  7317.         case SSL_ERROR_SSL:
  7318.         case SSL_ERROR_ZERO_RETURN:
  7319.         default:
  7320.           ttclos(0);
  7321.           return(-3);
  7322.             }
  7323.         }
  7324.     }
  7325. #endif /* CK_SSL */
  7326. #ifdef RLOGCODE
  7327. #ifdef CK_KERBEROS
  7328. #ifdef KRB4
  7329.     if (ttnproto == NP_EK4LOGIN) {
  7330.         if ((n = krb4_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  7331.       return(-3);
  7332.         else
  7333.       return(n);
  7334.     }
  7335. #endif /* KRB4 */
  7336. #ifdef KRB5
  7337.     if (ttnproto == NP_EK5LOGIN) {
  7338.         if ((n = krb5_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  7339.       return(-3);
  7340.         else
  7341.       return(n);
  7342.     }
  7343. #endif /* KRB5 */
  7344. #endif /* CK_KERBEROS */
  7345. #endif /* RLOGCODE */
  7346.  
  7347. #ifdef NETPTY
  7348. #ifdef HAVE_PTYTRAP
  7349.     /* Special handling for HP-UX pty i/o */
  7350.   ptyread:
  7351.     if (ttpty && pty_trap_pending(ttyfd) > 0) {
  7352.         if (pty_trap_handler(ttyfd) > 0) {
  7353.             ttclos(0);
  7354.             return(-3);
  7355.         }
  7356.     }
  7357. #endif /* HAVE_PTYTRAP */
  7358. #endif /* NETPTY */
  7359.     n = read(fd, mybuf, sizeof(mybuf));
  7360.     debug(F101,"SVORPOSIX myfillbuf","",n);
  7361.     debug(F101,"SVORPOSIX myfillbuf ttcarr","",ttcarr);
  7362.     debug(F101,"SVORPOSIX myfillbuf errno","",errno);
  7363.     if (n < 1) {
  7364. #ifdef NETPTY
  7365. #ifdef HAVE_PTYTRAP
  7366.         /* When we have a PTY trap in place the connection cannot */
  7367.         /* be closed until the trap receives a close indication.  */
  7368.         if (n == 0 && ttpty)
  7369.             goto ptyread;
  7370. #endif /* HAVE_PTYTRAP */
  7371. #endif /* NETPTY */
  7372.         return(-3);
  7373.     }
  7374.     return(n);
  7375. #endif /* BEBOX */
  7376. #endif /* sxaE50 */
  7377. }
  7378.  
  7379. #else /* not AT&T or POSIX */
  7380.  
  7381. #ifdef aegis
  7382.     /* This is quoted from the old myread().  The semantics seem to be
  7383.      * alright, but maybe errno would not need to be set even when
  7384.      * there is no error?  I don't know aegis.
  7385.      */
  7386. int
  7387. myfillbuf() {
  7388.     int count;
  7389. #ifdef NETCMD
  7390.     if (ttpipe)
  7391.       fd = fdin;
  7392.     else
  7393. #endif /* NETCMD */
  7394.       fd = ttyfd;
  7395.  
  7396.     count = ios_$get((short)fd, ios_$cond_opt, mybuf, 256L, st);
  7397.     errno = EIO;
  7398.     if (st.all == ios_$get_conditional_failed) /* get at least one */
  7399.       count = ios_$get((short)fd, 0, mybuf, 1L, st);
  7400.     if (st.all == ios_$end_of_file)
  7401.       return(-3);
  7402.     else if (st.all != status_$ok) {
  7403.     errno = EIO;
  7404.     return(-1);
  7405.     }
  7406.     return(count > 0 ? count : -3);
  7407. }
  7408. #else /* !aegis */
  7409.  
  7410. #ifdef FIONREAD
  7411.     /* This is for systems with FIONREAD.  FIONREAD returns the number
  7412.      * of characters available for reading. If none are available, wait
  7413.      * until something arrives, otherwise return all there is.
  7414.      */
  7415. int
  7416. myfillbuf() {
  7417.     PEEKTYPE avail = 0;
  7418.     int x, fd;
  7419. #ifdef NETCMD
  7420.     if (ttpipe)
  7421.       fd = fdin;
  7422.     else
  7423. #endif /* NETCMD */
  7424.       fd = ttyfd;
  7425.  
  7426. #ifdef SUNX25
  7427. /*
  7428.   SunLink X.25 support in this routine from Stefaan A. Eeckels, Eurostat (CEC).
  7429.   Depends on SunOS having FIONREAD, not because we use it, but just so this
  7430.   code is grouped correctly within the #ifdefs.  Let's hope Solaris keeps it.
  7431.  
  7432.   We call x25xin() instead of read() so that Q-Bit packets, which contain
  7433.   X.25 service-level information (e.g. PAD parameter changes), can be processed
  7434.   transparently to the upper-level code.  This is a blocking read, and so
  7435.   we depend on higher-level code (such as ttinc()) to set any necessary alarms.
  7436. */
  7437.     extern int nettype;
  7438.     if (netconn && nettype == NET_SX25) {
  7439.     while ((x = x25xin(sizeof(x25buf), x25buf)) < 1) ;
  7440.     return(x - 1);            /* "-1" compensates for extra status byte */
  7441.     }
  7442. #endif /* SUNX25 */
  7443.  
  7444. #ifdef CK_SSL
  7445.     if (ssl_active_flag || tls_active_flag) {
  7446.         int error, n = 0;
  7447.         while (n == 0) {
  7448.             if (ssl_active_flag)
  7449.           n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  7450.             else
  7451.           n = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  7452.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  7453.           case SSL_ERROR_NONE:
  7454.                 if (n > 0)
  7455.           return(n);
  7456.                 if (n < 0)
  7457.           return(-2);
  7458.                 msleep(50);
  7459.                 break;
  7460.           case SSL_ERROR_WANT_WRITE:
  7461.           case SSL_ERROR_WANT_READ:
  7462.                 return(-1);
  7463.           case SSL_ERROR_SYSCALL:
  7464.           case SSL_ERROR_WANT_X509_LOOKUP:
  7465.           case SSL_ERROR_SSL:
  7466.           case SSL_ERROR_ZERO_RETURN:
  7467.           default:
  7468.                 ttclos(0);
  7469.                 return(-2);
  7470.             }
  7471.         }
  7472.     }
  7473. #endif /* CK_SSL */
  7474. #ifdef RLOGCODE
  7475. #ifdef CK_KERBEROS
  7476. #ifdef KRB4
  7477.     if (ttnproto == NP_EK4LOGIN) {
  7478.         if ((x = krb4_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  7479.       return(-1);
  7480.         else
  7481.       return(x);
  7482.     }
  7483. #endif /* KRB4 */
  7484. #ifdef KRB5
  7485.     if (ttnproto == NP_EK5LOGIN) {
  7486.         if ((x = krb5_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  7487.       return(-1);
  7488.         else
  7489.       return(x);
  7490.     }
  7491. #endif /* KRB5 */
  7492. #endif /* CK_KERBEROS */
  7493. #endif /* RLOGCODE */
  7494.  
  7495.     errno = 0;
  7496.     debug(F101,"myfillbuf calling FIONREAD ioctl","",xlocal);
  7497.     x = ioctl(fd, FIONREAD, &avail);
  7498. #ifdef DEBUG
  7499.     if (deblog) {
  7500.     debug(F101,"myfillbuf FIONREAD","",x);
  7501.     debug(F101,"myfillbuf FIONREAD avail","",avail);
  7502.     debug(F101,"myfillbuf FIONREAD errno","",errno);
  7503.     }
  7504. #endif /* DEBUG */
  7505.     if (x < 0 || avail == 0)
  7506.       avail = 1;
  7507.  
  7508.     if (avail > MYBUFLEN)
  7509.       avail = MYBUFLEN;
  7510.  
  7511.     errno = 0;
  7512.  
  7513.     x = read(fd, mybuf, (int) avail);
  7514. #ifdef DEBUG
  7515.     if (deblog) {
  7516.     debug(F101,"myfillbuf avail","",avail);
  7517.     debug(F101,"myfillbuf read","",x);
  7518.     debug(F101,"myfillbuf read errno","",errno);
  7519.         if (x > 0)
  7520.       hexdump("myfillbuf mybuf",mybuf,x);
  7521.     }
  7522. #endif /* DEBUG */
  7523.     if (x < 1) x = -3;            /* read 0 == connection loss */
  7524.     return(x);
  7525. }
  7526.  
  7527. #else /* !FIONREAD */
  7528. /* Add other systems here, between #ifdef and #else, e.g. NETCONN. */
  7529. /* When there is no other possibility, read 1 character at a time. */
  7530. int
  7531. myfillbuf() {
  7532.     int x;
  7533.  
  7534. #ifdef CK_SSL
  7535.     if (ssl_active_flag || tls_active_flag) {
  7536.         int error, n = 0;
  7537.         while (n == 0) {
  7538.             if (ssl_active_flag)
  7539.           n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  7540.             else
  7541.           count = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  7542.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  7543.           case SSL_ERROR_NONE:
  7544.                 if (n > 0)
  7545.           return(n);
  7546.                 if (n < 0)
  7547.           return(-2);
  7548.                 msleep(50);
  7549.                 break;
  7550.           case SSL_ERROR_WANT_WRITE:
  7551.           case SSL_ERROR_WANT_READ:
  7552.                 return(-1);
  7553.           case SSL_ERROR_SYSCALL:
  7554.           case SSL_ERROR_WANT_X509_LOOKUP:
  7555.           case SSL_ERROR_SSL:
  7556.           case SSL_ERROR_ZERO_RETURN:
  7557.           default:
  7558.                 ttclos(0);
  7559.                 return(-2);
  7560.             }
  7561.         }
  7562.     }
  7563. #endif /* CK_SSL */
  7564. #ifdef RLOGCODE
  7565. #ifdef CK_KERBEROS
  7566. #ifdef KRB4
  7567.     if (ttnproto == NP_EK4LOGIN) {
  7568.         if ((len = krb4_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  7569.       return(-1);
  7570.         else
  7571.       return(len);
  7572.     }
  7573. #endif /* KRB4 */
  7574. #ifdef KRB5
  7575.     if (ttnproto == NP_EK5LOGIN) {
  7576.         if ((len = krb5_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  7577.       return(-1);
  7578.         else
  7579.       return(len);
  7580.     }
  7581. #endif /* KRB5 */
  7582. #endif /* CK_KERBEROS */
  7583. #endif /* RLOGCODE */
  7584.  
  7585. #ifdef NETCMD
  7586.     if (ttpipe)
  7587.       fd = fdin;
  7588.     else
  7589. #endif /* NETCMD */
  7590.       fd = ttyfd;
  7591.     x = read(fd, mybuf, 1);
  7592.     return(x > 0 ? x : -3);
  7593. }
  7594.  
  7595. #endif /* !FIONREAD */
  7596. #endif /* !aegis */
  7597. #endif /* !ATTSV */
  7598.  
  7599. #endif /* MYREAD */
  7600.  
  7601. #ifdef MINIX2
  7602. #undef MINIX
  7603. #endif /* MINIX2 */
  7604.  
  7605. /*  T T _ T N O P T  --  Handle Telnet negotions in incoming data */
  7606. /*
  7607.   Call with the IAC that was encountered.
  7608.   Returns:
  7609.    -3: If connection has dropped or gone bad.
  7610.    -2: On Telnet protocol error resulting in inconsistent states.
  7611.     0: If negotiation OK and caller has nothing to do.
  7612.     1: If packet start character has changed (new value is in global stchr).
  7613.   255: If there was a quoted IAC as data.
  7614.    or: Not at all if we got a legitimate Telnet Logout request.
  7615. */
  7616. #ifdef TCPSOCKET
  7617. static int
  7618. tt_tnopt(n) int n; {            /* Handle Telnet options */
  7619.     /* In case caller did not already check these conditions...  */
  7620.     if (n == IAC &&
  7621.     ((xlocal && netconn && (ttnproto == NP_TELNET)) ||
  7622.      (!xlocal && sstelnet))) {
  7623.     extern int duplex;
  7624.     extern int server;
  7625.     int tx = 0;
  7626.     debug(F100,"ttinl calling tn_doop()","",0);
  7627.     tx = tn_doop((CHAR)(n & 0xff),duplex,ttinc);
  7628.     debug(F111,"ttinl tn_doop() returned","tx",tx);
  7629.     switch (tx) {
  7630.       case 0:
  7631.         return(0);
  7632.       case -1:            /* I/O error */
  7633.         ttimoff();            /* Turn off timer */
  7634.         return(-3);
  7635.           case -2:            /* Connection failed. */
  7636.           case -3:
  7637.         ttimoff();            /* Turn off timer */
  7638.         ttclos(0);
  7639.         return(-3);
  7640.       case 1:            /* ECHO change */
  7641.         duplex = 1;
  7642.         return(0);
  7643.       case 2:            /* ECHO change */
  7644.         duplex = 0;
  7645.         return(0);
  7646.       case 3:            /* Quoted IAC */
  7647.         n = 255;
  7648.         return((unsigned)255);
  7649. #ifdef IKS_OPTION
  7650.       case 4: {
  7651.           if (TELOPT_SB(TELOPT_KERMIT).kermit.u_start && server
  7652. #ifdef IKSD
  7653.           && !inserver
  7654. #endif /* IKSD */
  7655.           ) {            /* Remote in Server mode */
  7656.           ttimoff();        /* Turn off timer */
  7657.           debug(F100,"u_start and !inserver","",0);
  7658.           return(-2);        /* End server mode */
  7659.           } else if (!TELOPT_SB(TELOPT_KERMIT).kermit.me_start &&
  7660.              server
  7661.              ) {        /* I'm no longer in Server Mode */
  7662.           debug(F100,"me_start and server","",0);
  7663.           ttimoff();
  7664.           return(-2);
  7665.           }
  7666.           return(0);
  7667.       }
  7668.       case 5: {            /* Start character change */
  7669.           /* extern CHAR stchr; */
  7670.           /* start = stchr; */
  7671.           return(1);
  7672.       }
  7673. #endif /* IKS_OPTION */
  7674.       case 6:            /* Remote Logout */
  7675.         ttimoff();
  7676.         ttclos(0);
  7677. #ifdef IKSD
  7678.         if (inserver && !local)
  7679.           doexit(GOOD_EXIT,0);
  7680.         else
  7681. #endif /* IKSD */
  7682.           return(-2);
  7683.       default:
  7684.         return(0);
  7685.     }
  7686.     } else
  7687.       return(0);
  7688. }
  7689. #endif /* TCPSOCKET */
  7690.  
  7691. /*  T T F L U I  --  Flush tty input buffer */
  7692.  
  7693. void
  7694. ttflux() {                /* But first... */
  7695. #ifdef MYREAD
  7696. /*
  7697.   Flush internal MYREAD buffer.
  7698. */
  7699. #ifdef TCPSOCKET
  7700.     int dotnopts, x;
  7701.     dotnopts = (((xlocal && netconn && (ttnproto == NP_TELNET)) ||
  7702.          (!xlocal && sstelnet)));
  7703. #endif /* TCPSOCKET */
  7704.     debug(F101,"ttflux my_count","",my_count);
  7705. #ifdef TCPSOCKET
  7706.     if (dotnopts) {
  7707.     CHAR ch = '\0';
  7708.         while (my_count > 0) {
  7709.         ch = myread();
  7710. #ifdef CK_ENCRYPTION
  7711.             if (TELOPT_U(TELOPT_ENCRYPTION))
  7712.           ck_tn_decrypt(&ch,1);
  7713. #endif /* CK_ENCRYPTION */
  7714.             if (ch == IAC)
  7715.           x = tt_tnopt(ch);
  7716.         }
  7717.     } else
  7718. #endif /* TCPSOCKET */
  7719. #ifdef COMMENT
  7720. #ifdef CK_ENCRYPTION
  7721.     if (TELOPT_U(TELOPT_ENCRYPTION) && my_count > 0)
  7722.       ck_tn_decrypt(&mybuf[my_item+1],my_count);
  7723. #endif /* CK_ENCRYPTION */
  7724. #endif /* COMMENT */
  7725.     my_count = 0;            /* Reset count to zero */
  7726.     my_item = -1;            /* And buffer index to -1 */
  7727. #endif /* MYREAD */
  7728. }
  7729.  
  7730. int
  7731. ttflui() {
  7732.     int n, fd;
  7733. #ifdef TCPSOCKET
  7734.     int dotnopts;
  7735.     dotnopts = (((xlocal && netconn && (ttnproto == NP_TELNET)) ||
  7736.          (!xlocal && sstelnet)));
  7737. #endif /* TCPSOCKET */
  7738.  
  7739. #ifdef NETCMD
  7740.     if (ttpipe)
  7741.       fd = fdin;
  7742.     else
  7743. #endif /* NETCMD */
  7744.       fd = ttyfd;
  7745.  
  7746. #ifdef TTLEBUF
  7747.     ttpush = -1;            /* Clear the peek-ahead char */
  7748.     while (le_data && (le_inbuf() > 0)) {
  7749.         CHAR ch = '\0';
  7750.         if (le_getchar(&ch) > 0) {    /* Clear any more... */
  7751.             debug(F101,"ttflui le_inbuf ch","",ch);
  7752.         }
  7753.     }
  7754. #endif /* TTLEBUF */
  7755.     debug(F101,"ttflui ttpipe","",ttpipe);
  7756.  
  7757. #ifdef MYREAD
  7758. /*
  7759.   Flush internal MYREAD buffer *NEXT*, in all cases.
  7760. */
  7761.     ttflux();
  7762. #endif /* MYREAD */
  7763.  
  7764. #ifdef NETCONN
  7765. /* Network flush is done specially, in the network support module. */
  7766.     if ((netconn || sstelnet) && !ttpipe && !ttpty) {
  7767.     debug(F100,"ttflui netflui","",0);
  7768.     return(netflui());
  7769.     }
  7770. #endif /* NETCONN */
  7771.  
  7772.     debug(F101,"ttflui ttyfd","",ttyfd); /* Not network */
  7773.     if (ttyfd < 0)
  7774.       return(-1);
  7775.  
  7776. #ifdef aegis
  7777.     sio_$control((short)yfd, sio_$flush_in, true, st);
  7778.     if (st.all != status_$ok) {
  7779.     fprintf(stderr, "flush failed: "); error_$print(st);
  7780.     } else {      /* sometimes the flush doesn't work */
  7781.         for (;;) {
  7782.         char buf[256];
  7783.             /* eat all the characters that shouldn't be available */
  7784.             ios_$get((short)fd, ios_$cond_opt, buf, 256L, st); /* (void) */
  7785.             if (st.all == ios_$get_conditional_failed) break;
  7786.             fprintf(stderr, "flush failed(2): "); error_$print(st);
  7787.         }
  7788.     }
  7789. #else
  7790. #ifdef BSD44                /* 4.4 BSD */
  7791.     n = FREAD;                          /* Specify read queue */
  7792.     debug(F100,"ttflui BSD44","",0);
  7793.     ioctl(fd,TIOCFLUSH,&n);
  7794. #else
  7795. #ifdef Plan9
  7796. #undef POSIX                /* Uh oh... */
  7797. #endif /* Plan9 */
  7798. #ifdef POSIX                /* POSIX */
  7799.     debug(F100,"ttflui POSIX","",0);
  7800.     tcflush(fd,TCIFLUSH);
  7801. #else
  7802. #ifdef ATTSV                /* System V */
  7803. #ifndef VXVE
  7804.     debug(F100,"ttflui ATTSV","",0);
  7805.     ioctl(fd,TCFLSH,0);
  7806. #endif /* VXVE */
  7807. #else                    /* Not BSD44, POSIX, or Sys V */
  7808. #ifdef TIOCFLUSH            /* Those with TIOCFLUSH defined */
  7809. #ifdef ANYBSD                /* Berkeley */
  7810.     n = FREAD;                          /* Specify read queue */
  7811.     debug(F100,"ttflui TIOCFLUSH ANYBSD","",0);
  7812.     ioctl(fd,TIOCFLUSH,&n);
  7813. #else                    /* Others (V7, etc) */
  7814.     debug(F100,"ttflui TIOCFLUSH","",0);
  7815.     ioctl(fd,TIOCFLUSH,0);
  7816. #endif /* ANYBSD */
  7817. #else                    /* All others... */
  7818. /*
  7819.   No system call (that we know about) for input buffer flushing.
  7820.   So see how many there are and read them in a loop, using ttinc().
  7821.   ttinc() is buffered, so we're not getting charged with a system call
  7822.   per character, just a function call.
  7823. */
  7824.     if ((n = ttchk()) > 0) {
  7825.     debug(F101,"ttflui read loop","",n);
  7826.     while ((n--) && ttinc(0) > 0) ;
  7827.     }
  7828. #endif /* TIOCFLUSH */
  7829. #endif /* ATTSV */
  7830. #endif /* POSIX */
  7831. #ifdef Plan9
  7832. #define POSIX
  7833. #endif /* Plan9 */
  7834. #endif /* BSD44 */
  7835. #endif /* aegis */
  7836.     return(0);
  7837. }
  7838.  
  7839. int
  7840. ttfluo() {                /* Flush output buffer */
  7841.     int fd;
  7842. #ifdef NETCMD
  7843.     if (ttpipe)
  7844.       fd = fdout;
  7845.     else
  7846. #endif /* NETCMD */
  7847.       fd = ttyfd;
  7848.  
  7849. #ifdef Plan9
  7850.     return 0;
  7851. #else
  7852. #ifdef POSIX
  7853.     return(tcflush(fd,TCOFLUSH));
  7854. #else
  7855. #ifdef OXOS
  7856.     return(ioctl(fd,TCFLSH,1));
  7857. #else
  7858.     return(0);                /* All others, nothing */
  7859. #endif /* OXOS */
  7860. #endif /* POSIX */
  7861. #endif /* Plan9 */
  7862. }
  7863.  
  7864. /* Interrupt Functions */
  7865.  
  7866. /* Set up terminal interrupts on console terminal */
  7867.  
  7868. #ifndef FIONREAD            /* We don't need esctrp() */
  7869. #ifndef SELECT                /* if we have any of these... */
  7870. #ifndef CK_POLL
  7871. #ifndef RDCHK
  7872.  
  7873. #ifndef OXOS
  7874. #ifdef SVORPOSIX
  7875. SIGTYP
  7876. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  7877.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  7878.     conesc = 1;
  7879.     debug(F101,"esctrp caught SIGQUIT","",conesc);
  7880. }
  7881. #endif /* SVORPOSIX */
  7882. #endif /* OXOS */
  7883.  
  7884. #ifdef V7
  7885. #ifndef MINIX2
  7886. SIGTYP
  7887. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  7888.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  7889.     conesc = 1;
  7890.     debug(F101,"esctrp caught SIGQUIT","",conesc);
  7891. }
  7892. #endif /* MINIX2 */
  7893. #endif /* V7 */
  7894.  
  7895. #ifdef C70
  7896. SIGTYP
  7897. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  7898.     conesc = 1;
  7899.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  7900. }
  7901. #endif /* C70 */
  7902.  
  7903. #endif /* RDCHK */
  7904. #endif /* CK_POLL */
  7905. #endif /* SELECT */
  7906. #endif /* FIONREAD */
  7907.  
  7908. /*  C O N B G T  --  Background Test  */
  7909.  
  7910. static int jc = 0;            /* 0 = no job control */
  7911.  
  7912. /*
  7913.   Call with flag == 1 to prevent signal test, which can not be expected
  7914.   to work during file transfer, when SIGINT probably *is* set to SIG_IGN.
  7915.  
  7916.   Call with flag == 0 to use the signal test, but only if the process-group
  7917.   test fails, as it does on some UNIX systems, where getpgrp() is buggy,
  7918.   requires an argument when the man page says it doesn't, or vice versa.
  7919.  
  7920.   If flag == 0 and the process-group test fails, then we determine background
  7921.   status simply (but not necessarily reliably) from isatty().
  7922.  
  7923.   conbgt() sets the global backgrd = 1 if we appear to be in the background,
  7924.   and to 0 if we seem to be in the foreground.  conbgt() is highly prone to
  7925.   misbehavior.
  7926. */
  7927. VOID
  7928. conbgt(flag) int flag; {
  7929.     int x = -1,                /* process group or SIGINT test */
  7930.         y = 0;                /* isatty() test */
  7931. /*
  7932.   Check for background operation, even if not running on real tty, so that
  7933.   background flag can be set correctly.  If background status is detected,
  7934.   then Kermit will not issue its interactive prompt or most messages.
  7935.   If your prompt goes away, you can blame (and fix?) this function.
  7936. */
  7937.  
  7938. /* Use process-group test if possible. */
  7939.  
  7940. #ifdef POSIX                /* We can do it in POSIX */
  7941. #define PGROUP_T
  7942. #else
  7943. #ifdef BSD4                /* and in BSD 4.x. */
  7944. #define PGROUP_T
  7945. #else
  7946. #ifdef HPUXJOBCTL            /* and in most HP-UX's */
  7947. #define PGROUP_T
  7948. #else
  7949. #ifdef TIOCGPGRP            /* and anyplace that has this ioctl. */
  7950. #define PGROUP_T
  7951. #endif /* TIOCGPGRP */
  7952. #endif /* HPUXJOBCTL */
  7953. #endif /* BSD4 */
  7954. #endif /* POSIX */
  7955.  
  7956. #ifdef MIPS                /* Except if it doesn't work... */
  7957. #undef PGROUP_T
  7958. #endif /* MIPS */
  7959.  
  7960. #ifdef PGROUP_T
  7961. /*
  7962.   Semi-reliable process-group test.  Check whether this process's group is
  7963.   the same as the controlling terminal's process group.  This works if the
  7964.   getpgrp() call doesn't lie (as it does in the SUNOS System V environment).
  7965. */
  7966.     PID_T mypgrp = (PID_T)0;        /* Kermit's process group */
  7967.     PID_T ctpgrp = (PID_T)0;        /* The terminal's process group */
  7968. #ifndef _POSIX_SOURCE
  7969. /*
  7970.   The getpgrp() prototype is obtained from system header files for POSIX
  7971.   and Sys V R4 compilations.  Other systems, who knows.  Some complain about
  7972.   a duplicate declaration here, others don't, so it's safer to leave it in
  7973.   if we don't know for certain.
  7974. */
  7975. #ifndef SVR4
  7976. #ifndef PS2AIX10
  7977. #ifndef HPUX9
  7978.     extern PID_T getpgrp();
  7979. #endif /* HPUX9 */
  7980. #endif /* PS2AIX10 */
  7981. #endif /* SVR4 */
  7982. #endif /* _POSIX_SOURCE */
  7983.  
  7984. /* Get my process group. */
  7985.  
  7986. #ifdef SVR3 /* Maybe this should be ATTSV? */
  7987. /* This function is not described in SVID R2 */
  7988.     mypgrp = getpgrp();
  7989.     /* debug(F101,"ATTSV conbgt process group","",(int) mypgrp); */
  7990. #else
  7991. #ifdef POSIX
  7992.     mypgrp = getpgrp();
  7993.     /* debug(F101,"POSIX conbgt process group","",(int) mypgrp); */
  7994. #else
  7995. #ifdef OSFPC
  7996.     mypgrp = getpgrp();
  7997.     /* debug(F101,"OSF conbgt process group","",(int) mypgrp); */
  7998. #else
  7999. #ifdef QNX
  8000.     mypgrp = getpgrp();
  8001.     /* debug(F101,"QNX conbgt process group","",(int) mypgrp); */
  8002. #else
  8003. #ifdef OSF32                /* (was OSF40) */
  8004.     mypgrp = getpgrp();
  8005.     /* debug(F101,"Digital UNIX conbgt process group","",(int) mypgrp); */
  8006. #else /* BSD, V7, etc */
  8007. #ifdef MINIX2
  8008.     mypgrp = getpgrp();
  8009. #else
  8010.     mypgrp = getpgrp(0);
  8011. #endif /* MINIX2 */
  8012.     /* debug(F101,"BSD conbgt process group","",(int) mypgrp); */
  8013. #endif /* OSF32 */
  8014. #endif /* QNX */
  8015. #endif /* OSFPC */
  8016. #endif /* POSIX */
  8017. #endif /* SVR3 */
  8018.  
  8019. #ifdef MINIX2
  8020. #undef BSD44ORPOSIX
  8021. #endif /* MINIX2 */
  8022.  
  8023. /* Now get controlling tty's process group */
  8024. #ifdef BSD44ORPOSIX
  8025.     ctpgrp = tcgetpgrp(1);        /* The POSIX way */
  8026.     /* debug(F101,"POSIX conbgt terminal process group","",(int) ctpgrp); */
  8027. #else
  8028.     ioctl(1, TIOCGPGRP, &ctpgrp);    /* Or the BSD way */
  8029.    /* debug(F101,"non-POSIX conbgt terminal process group","",(int) ctpgrp); */
  8030. #endif /* BSD44ORPOSIX */
  8031.  
  8032. #ifdef MINIX2
  8033. #define BSD44ORPOSIX
  8034. #endif /* MINIX2 */
  8035.  
  8036.     if ((mypgrp > (PID_T) 0) && (ctpgrp > (PID_T) 0))
  8037.       x = (mypgrp == ctpgrp) ? 0 : 1;    /* If they differ, then background. */
  8038.     else x = -1;            /* If error, remember. */
  8039.     debug(F101,"conbgt process group test","",x);
  8040. #endif /* PGROUP_T */
  8041.  
  8042. /* Try to see if job control is available */
  8043.  
  8044. #ifdef NOJC                /* User override */
  8045.     jc = 0;                /* No job control allowed */
  8046.     debug(F111,"NOJC","jc",jc);
  8047. #else
  8048. #ifdef BSD44
  8049.     jc = 1;
  8050. #else
  8051. #ifdef SVR4ORPOSIX            /* POSIX actually tells us */
  8052.     debug(F100,"SVR4ORPOSIX jc test...","",0);
  8053. #ifdef _SC_JOB_CONTROL
  8054. #ifdef __bsdi__
  8055.     jc = 1;
  8056. #else
  8057. #ifdef __386BSD__
  8058.     jc = 1;
  8059. #else
  8060.     jc = sysconf(_SC_JOB_CONTROL);    /* Whatever system says */
  8061.     if (jc < 0) {
  8062.     debug(F101,"sysconf fails, jcshell","",jcshell);
  8063.     jc = (jchdlr == SIG_DFL) ? 1 : 0;
  8064.     } else
  8065.       debug(F111,"sysconf(_SC_JOB_CONTROL)","jc",jc);
  8066. #endif /* __386BSD__ */
  8067. #endif /* __bsdi__ */
  8068. #else
  8069. #ifdef _POSIX_JOB_CONTROL
  8070.     jc = 1;                /* By definition */
  8071.     debug(F111,"_POSIX_JOB_CONTROL is defined","jc",jc);
  8072. #else
  8073.     jc = 0;                /* Assume job control not allowed */
  8074.     debug(F111,"SVR4ORPOSIX _SC/POSIX_JOB_CONTROL not defined","jc",jc);
  8075. #endif /* _POSIX_JOB_CONTROL */
  8076. #endif /* _SC_JOB_CONTROL */
  8077. #else
  8078. #ifdef BSD4
  8079.     jc = 1;                /* Job control allowed */
  8080.     debug(F111,"BSD job control","jc",jc);
  8081. #else
  8082. #ifdef SVR3JC
  8083.     jc = 1;                /* JC allowed */
  8084.     debug(F111,"SVR3 job control","jc",jc);
  8085. #else
  8086. #ifdef OXOS
  8087.     jc = 1;                /* JC allowed */
  8088.     debug(F111,"X/OS job control","jc",jc);
  8089. #else
  8090. #ifdef HPUX9
  8091.     jc = 1;                /* JC allowed */
  8092.     debug(F111,"HP-UX 9.0 job control","jc",jc);
  8093. #else
  8094. #ifdef HPUX10
  8095.     jc = 1;                /* JC allowed */
  8096.     debug(F111,"HP-UX 10.0 job control","jc",jc);
  8097. #else
  8098.     jc = 0;                /* JC not allowed */
  8099.     debug(F111,"job control catch-all","jc",jc);
  8100. #endif /* HPUX10 */
  8101. #endif /* HPUX9 */
  8102. #endif /* OXOS */
  8103. #endif /* SVR3JC */
  8104. #endif /* BSD4 */
  8105. #endif /* SVR4ORPOSIX */
  8106. #endif /* BSD44 */
  8107. #endif /* NOJC */
  8108.     debug(F101,"conbgt jc","",jc);
  8109. #ifndef NOJC
  8110.     debug(F101,"conbgt jcshell","",jcshell);
  8111. /*
  8112.   At this point, if jc == 1 but jcshell == 0, it means that the OS supports
  8113.   job control, but the shell or other process we are running under does not
  8114.   (jcshell is set in sysinit()) and so if we suspend ourselves, nothing good
  8115.   will come of it.  So...
  8116. */
  8117.     if (jc < 0) jc = 0;
  8118.     if (jc > 0 && jcshell == 0) jc = 0;
  8119. #endif /* NOJC */
  8120.  
  8121. /*
  8122.   Another background test.
  8123.   Test if SIGINT (terminal interrupt) is set to SIG_IGN (ignore),
  8124.   which is done by the shell (sh) if the program is started with '&'.
  8125.   Unfortunately, this is NOT done by csh or ksh so watch out!
  8126.   Note, it's safe to set SIGINT to SIG_IGN here, because further down
  8127.   we always set it to something else.
  8128.   Note: as of 16 Jul 1999, we also skip this test if we set SIGINT to
  8129.   SIG_IGN ourselves.
  8130. */
  8131.     if (x < 0 && !flag && !sigint_ign) { /* Didn't get good results above... */
  8132.  
  8133.     SIGTYP (*osigint)();
  8134.  
  8135.     osigint = signal(SIGINT,SIG_IGN);    /* What is SIGINT set to? */
  8136.     sigint_ign = 1;
  8137.     x = (osigint == SIG_IGN) ? 1 : 0;    /* SIG_IGN? */
  8138.     debug(F101,"conbgt osigint","",osigint);
  8139.     debug(F101,"conbgt signal test","",x);
  8140.     }
  8141.  
  8142. /* Also check to see if we're running with redirected stdio. */
  8143. /* This is not really background operation, but we want to act as though */
  8144. /* it were. */
  8145.  
  8146. #ifdef IKSD
  8147.     if (inserver) {            /* Internet Kermit Server */
  8148.     backgrd = 0;            /* is not in the background */
  8149.     return;
  8150.     }
  8151. #endif /* IKSD */
  8152.  
  8153.     y = (isatty(0) && isatty(1)) ? 1 : 0;
  8154.     debug(F101,"conbgt isatty test","",y);
  8155.  
  8156. #ifdef BSD29
  8157. /* The process group and/or signal test doesn't work under these... */
  8158.     backgrd = !y;
  8159. #else
  8160. #ifdef sxaE50
  8161.     backgrd = !y;
  8162. #else
  8163. #ifdef MINIX
  8164.     backgrd = !y;
  8165. #else
  8166. #ifdef MINIX2
  8167.     backgrd = !y;
  8168. #else
  8169.     if (x > -1)
  8170.       backgrd = (x || !y) ? 1 : 0;
  8171.     else backgrd = !y;
  8172. #endif /* BSD29 */
  8173. #endif /* sxaE50 */
  8174. #endif /* MINIX */
  8175. #endif /* MINIX2 */
  8176.     debug(F101,"conbgt backgrd","",backgrd);
  8177. }
  8178.  
  8179. /*  C O N I N T  --  Console Interrupt setter  */
  8180.  
  8181. /*
  8182.   First arg is pointer to function to handle SIGTERM & SIGINT (like Ctrl-C).
  8183.   Second arg is pointer to function to handle SIGTSTP (suspend).
  8184. */
  8185.  
  8186. VOID                    /* Set terminal interrupt traps. */
  8187. #ifdef CK_ANSIC
  8188. #ifdef apollo
  8189. conint(f,s) SIGTYP (*f)(), (*s)();
  8190. #else
  8191. conint(SIGTYP (*f)(int), SIGTYP (*s)(int))
  8192. #endif /* apollo */
  8193. #else
  8194. conint(f,s) SIGTYP (*f)(), (*s)();
  8195. #endif /* CK_ANSIC */
  8196. /* conint */ {
  8197.  
  8198.     conbgt(0);                /* Do background test. */
  8199.  
  8200. /* Set the desired handlers for hangup and software termination. */
  8201.  
  8202. #ifdef SIGTERM
  8203.     signal(SIGTERM,f);                  /* Software termination */
  8204. #endif /* SIGTERM */
  8205.  
  8206. /*
  8207.   Prior to July 1999 we used to call sighup() here but now it's called in
  8208.   sysinit() so SIGHUP can be caught during execution of the init file or
  8209.   a kerbang script.
  8210. */
  8211.  
  8212. /* Now handle keyboard stop, quit, and interrupt signals. */
  8213. /* Check if invoked in background -- if so signals set to be ignored. */
  8214. /* However, if running under a job control shell, don't ignore them. */
  8215. /* We won't be getting any, as we aren't in the terminal's process group. */
  8216.  
  8217.     debug(F101,"conint backgrd","",backgrd);
  8218.     debug(F101,"conint jc","",jc);
  8219.  
  8220.     if (backgrd && !jc) {        /* In background, ignore signals */
  8221.     debug(F101,"conint background ignoring signals, jc","",jc);
  8222. #ifdef SIGTSTP
  8223.         signal(SIGTSTP,SIG_IGN);        /* Keyboard stop */
  8224. #endif /* SIGTSTP */
  8225.         signal(SIGQUIT,SIG_IGN);        /* Keyboard quit */
  8226.         signal(SIGINT,SIG_IGN);         /* Keyboard interrupt */
  8227.     sigint_ign = 1;
  8228.     } else {                /* Else in foreground or suspended */
  8229.     debug(F101,"conint foreground catching signals, jc","",jc);
  8230.         signal(SIGINT,f);               /* Catch terminal interrupt */
  8231.     sigint_ign = (f == SIG_IGN) ? 1 : 0;
  8232.  
  8233. #ifdef SIGTSTP                /* Keyboard stop (suspend) */
  8234.     /* debug(F101,"conint SIGSTSTP","",s); */
  8235.     if (s == NULL) s = SIG_DFL;
  8236. #ifdef NOJC                /* No job control allowed. */
  8237.     signal(SIGTSTP,SIG_IGN);
  8238. #else                    /* Job control allowed */
  8239.     if (jc)                /* if available. */
  8240.       signal(SIGTSTP,s);
  8241.     else
  8242.       signal(SIGTSTP,SIG_IGN);
  8243. #endif /* NOJC */
  8244. #endif /* SIGTSTP */
  8245.  
  8246. #ifndef OXOS
  8247. #ifdef SVORPOSIX
  8248. #ifndef FIONREAD            /* Watch out, we don't know this... */
  8249. #ifndef SELECT
  8250. #ifndef CK_POLL
  8251. #ifndef RDCHK
  8252.         signal(SIGQUIT,esctrp);         /* Quit signal, Sys III/V. */
  8253. #endif /* RDCHK */
  8254. #endif /* CK_POLL */
  8255. #endif /* SELECT */
  8256. #endif /* FIONREAD */
  8257.         if (conesc) conesc = 0;         /* Clear out pending escapes */
  8258. #else
  8259. #ifdef V7
  8260.         signal(SIGQUIT,esctrp);         /* V7 like Sys III/V */
  8261.         if (conesc) conesc = 0;
  8262. #else
  8263. #ifdef aegis
  8264.         signal(SIGQUIT,f);              /* Apollo, catch it like others. */
  8265. #else
  8266.         signal(SIGQUIT,SIG_IGN);        /* Others, ignore like 4D & earlier. */
  8267. #endif /* aegis */
  8268. #endif /* V7 */
  8269. #endif /* SVORPOSIX */
  8270. #endif /* OXOS */
  8271.     }
  8272. }
  8273.  
  8274.  
  8275. /*  C O N N O I  --  Reset console terminal interrupts */
  8276.  
  8277. VOID
  8278. connoi() {                              /* Console-no-interrupts */
  8279.  
  8280.     debug(F100,"connoi","",0);
  8281. #ifdef SIGTSTP
  8282.     signal(SIGTSTP,SIG_IGN);        /* Suspend */
  8283. #endif /* SIGTSTP */
  8284.     conint(SIG_IGN,SIG_IGN);        /* Interrupt */
  8285.     sigint_ign = 1;            /* Remember we did this ourselves */
  8286. #ifdef SIGQUIT
  8287.     signal(SIGQUIT,SIG_IGN);        /* Quit */
  8288. #endif /* SIGQUIT */
  8289. #ifdef SIGTERM
  8290.     signal(SIGTERM,SIG_IGN);        /* Term */
  8291. #endif /* SIGTERM */
  8292. }
  8293.  
  8294. /*  I N I T R A W Q  --  Set up to read /dev/kmem for character count.  */
  8295.  
  8296. #ifdef  V7
  8297. /*
  8298.  Used in Version 7 to simulate Berkeley's FIONREAD ioctl call.  This
  8299.  eliminates blocking on a read, because we can read /dev/kmem to get the
  8300.  number of characters available for raw input.  If your system can't
  8301.  or you won't let the world read /dev/kmem then you must figure out a
  8302.  different way to do the counting of characters available, or else replace
  8303.  this by a dummy function that always returns 0.
  8304. */
  8305. /*
  8306.  * Call this routine as: initrawq(tty)
  8307.  * where tty is the file descriptor of a terminal.  It will return
  8308.  * (as a char *) the kernel-mode memory address of the rawq character
  8309.  * count, which may then be read.  It has the side-effect of flushing
  8310.  * input on the terminal.
  8311.  */
  8312. /*
  8313.  * John Mackin, Physiology Dept., University of Sydney (Australia)
  8314.  * ...!decvax!mulga!physiol.su.oz!john
  8315.  *
  8316.  * Permission is hereby granted to do anything with this code, as
  8317.  * long as this comment is retained unmodified and no commercial
  8318.  * advantage is gained.
  8319.  */
  8320. #ifndef MINIX
  8321. #ifndef MINIX2
  8322. #ifndef COHERENT
  8323. #include <a.out.h>
  8324. #include <sys/proc.h>
  8325. #endif /* COHERENT */
  8326. #endif /* MINIX2 */
  8327. #endif /* MINIX */
  8328.  
  8329. #ifdef COHERENT
  8330. #include <l.out.h>
  8331. #include <sys/proc.h>
  8332. #endif /* COHERENT */
  8333.  
  8334. char *
  8335. initrawq(tty) int tty; {
  8336. #ifdef MINIX
  8337.     return(0);
  8338. #else
  8339. #ifdef MINIX2
  8340.     return(0);
  8341. #else
  8342. #ifdef UTS24
  8343.     return(0);
  8344. #else
  8345. #ifdef BSD29
  8346.     return(0);
  8347. #else
  8348.     long lseek();
  8349.     static struct nlist nl[] = {
  8350.         {PROCNAME},
  8351.         {NPROCNAME},
  8352.         {""}
  8353.     };
  8354.     static struct proc *pp;
  8355.     char *qaddr, *p, c;
  8356.     int m;
  8357.     PID_T pid, me;
  8358.     NPTYPE xproc;                       /* Its type is defined in makefile. */
  8359.     int catch();
  8360.  
  8361.     me = getpid();
  8362.     if ((m = open("/dev/kmem", 0)) < 0) err("kmem");
  8363.     nlist(BOOTNAME, nl);
  8364.     if (nl[0].n_type == 0) err("proc array");
  8365.  
  8366.     if (nl[1].n_type == 0) err("nproc");
  8367.  
  8368.     lseek(m, (long)(nl[1].n_value), 0);
  8369.     read (m, &xproc, sizeof(xproc));
  8370.     saval = signal(SIGALRM, catch);
  8371.     if ((pid = fork()) == 0) {
  8372.         while(1)
  8373.             read(tty, &c, 1);
  8374.     }
  8375.     alarm(2);
  8376.  
  8377.     if(setjmp(jjbuf) == 0) {
  8378.         while(1)
  8379.       read(tty, &c, 1);
  8380.     }
  8381.     signal(SIGALRM, SIG_DFL);
  8382.  
  8383. #ifdef DIRECT
  8384.     pp = (struct proc *) nl[0].n_value;
  8385. #else
  8386.     if (lseek(m, (long)(nl[0].n_value), 0) < 0L) err("seek");
  8387.     if (read(m, &pp, sizeof(pp)) != sizeof(pp))  err("no read of proc ptr");
  8388. #endif
  8389.     lseek(m, (long)(nl[1].n_value), 0);
  8390.     read(m, &xproc, sizeof(xproc));
  8391.  
  8392.     if (lseek(m, (long)pp, 0) < 0L) err("Can't seek to proc");
  8393.     if ((p = malloc(xproc * sizeof(struct proc))) == NULL) err("malloc");
  8394.     if (read(m,p,xproc * sizeof(struct proc)) != xproc*sizeof(struct proc))
  8395.         err("read proc table");
  8396.     for (pp = (struct proc *)p; xproc > 0; --xproc, ++pp) {
  8397.         if (pp -> p_pid == (short) pid) goto iout;
  8398.     }
  8399.     err("no such proc");
  8400.  
  8401. iout:
  8402.     close(m);
  8403.     qaddr = (char *)(pp -> p_wchan);
  8404.     free (p);
  8405.     kill(pid, SIGKILL);
  8406.     wait((WAIT_T *)0);
  8407.     return (qaddr);
  8408. #endif
  8409. #endif
  8410. #endif
  8411. #endif
  8412. }
  8413.  
  8414. /*  More V7-support functions...  */
  8415.  
  8416. static VOID
  8417. err(s) char *s; {
  8418.     char buf[200];
  8419.  
  8420.     sprintf(buf, "fatal error in initrawq: %s", s);
  8421.     perror(buf);
  8422.     doexit(1,-1);
  8423. }
  8424.  
  8425. static VOID
  8426. catch(foo) int foo; {
  8427.     longjmp(jjbuf, -1);
  8428. }
  8429.  
  8430.  
  8431. /*  G E N B R K  --  Simulate a modem break.  */
  8432.  
  8433. #ifdef MINIX
  8434. #define BSPEED B110
  8435. #else
  8436. #ifdef MINIX2
  8437. #define BSPEED B110
  8438. #else
  8439. #define BSPEED B150
  8440. #endif /* MINIX2 */
  8441. #endif /* MINIX */
  8442.  
  8443. #ifndef MINIX2
  8444. VOID
  8445. genbrk(fn,msec) int fn, msec; {
  8446.     struct sgttyb ttbuf;
  8447.     int ret, sospeed, x, y;
  8448.  
  8449.     ret = ioctl(fn, TIOCGETP, &ttbuf);
  8450.     sospeed = ttbuf.sg_ospeed;
  8451.     ttbuf.sg_ospeed = BSPEED;
  8452.     ret = ioctl(fn, TIOCSETP, &ttbuf);
  8453.     y = (int)strlen(brnuls);
  8454.     x = ( BSPEED * 100 ) / msec;
  8455.     if (x > y) x = y;
  8456.     ret = write(fn, brnuls, (( BSPEED * 100 ) / msec ));
  8457.     ttbuf.sg_ospeed = sospeed;
  8458.     ret = ioctl(fn, TIOCSETP, &ttbuf);
  8459.     ret = write(fn, "@", 1);
  8460.     return;
  8461. }
  8462. #endif /* MINIX2 */
  8463.  
  8464. #ifdef MINIX2
  8465. int
  8466. genbrk(fn,msec) int fn, msec; {
  8467.     struct termios ttbuf;
  8468.     int ret, x, y;
  8469.     speed_t sospeed;
  8470.  
  8471.     ret = tcgetattr(fn, &ttbuf);
  8472.     sospeed = ttbuf.c_ospeed;
  8473.     ttbuf.c_ospeed = BSPEED;
  8474.     ret = tcsetattr(fn,TCSADRAIN, &ttbuf);
  8475.     y = (int)strlen(brnuls);
  8476.     x = ( BSPEED * 100 ) / msec;
  8477.     if (x > y) x = y;
  8478.     ret = write(fn, brnuls, (( BSPEED * 100 ) / msec ));
  8479.     ttbuf.c_ospeed = sospeed;
  8480.     ret = tcsetattr(fn, TCSADRAIN, &ttbuf);
  8481.     ret = write(fn, "@", 1);
  8482.     return ret;
  8483. }
  8484. #endif /* MINIX2 */
  8485. #endif /* V7 */
  8486.  
  8487. /*
  8488.   I N C H K  --  Check if chars waiting to be read on given file descriptor.
  8489.  
  8490.   This routine is a merger of ttchk() and conchk().
  8491.   Call with:
  8492.     channel == 0 to check console.
  8493.     channel == 1 to check communications connection.
  8494.   and:
  8495.     fd = file descriptor.
  8496.   Returns:
  8497.    >= 0: number of characters waiting, 0 or greater,
  8498.      -1: on any kind of error,
  8499.      -2: if there is (definitely) no connection.
  8500.   Note: In UNIX we don't have to call nettchk() because a socket
  8501.   file descriptor works just like in serial i/o, ioctls and all.
  8502.   (But this will change if we add non-file-descriptor channels,
  8503.   such as IBM X.25 for AIX...)
  8504. */
  8505. static int
  8506. in_chk(channel, fd) int channel, fd; {
  8507.     int x, n = 0;            /* Workers, n = return value */
  8508.     extern int clsondisc;        /* Close on disconnect */
  8509. /*
  8510.   The first section checks to make sure we have a connection,
  8511.   but only if we're in local mode.
  8512. */
  8513. #ifdef DEBUG
  8514.     if (deblog) {
  8515.     char buf[16];
  8516.     sprintf(buf,"%d",fd);        /* File descriptor */
  8517.     debug(F111,"in_chk entry",buf,channel);
  8518.     debug(F101,"in_chk ttyfd","",ttyfd);
  8519.     debug(F101,"in_chk ttpty","",ttpty);
  8520.     }
  8521. #endif /* DEBUG */
  8522. /*
  8523.   But don't say connection is gone if we have any buffered-stuff.
  8524. */
  8525. #ifdef TTLEBUF
  8526.     debug(F101,"in_chk ttpush","",ttpush);
  8527.     if (channel == 1) {
  8528.     if (ttpush >= 0)
  8529.       n++;
  8530.     n += le_inbuf();
  8531.     if (n > 0)
  8532.       return(n);
  8533.     }
  8534. #endif /* TTLEBUF */
  8535.  
  8536. #ifdef NETPTY
  8537. #ifdef HAVE_PTYTRAP
  8538.     /* Special handling for HP-UX pty i/o */
  8539.     if (ttpty && pty_trap_pending(ttyfd) > 0) {
  8540.         if (pty_trap_handler(ttyfd) > 0) {
  8541.             ttclos(0);
  8542.             return(-2);
  8543.         }
  8544.     }
  8545. #endif /* HAVE_PTYTRAP */
  8546. #endif /* NETPTY */
  8547.  
  8548.     if (channel) {            /* Checking communications channel */
  8549.     if (ttyfd < 0) {        /* No connection */
  8550.       return(-2);            /* That's what this means */
  8551.     } else if (xlocal &&        /* In local mode */
  8552.            !netconn &&        /* Serial connection */
  8553.            ttcarr != CAR_OFF    /* with CARRIER WATCH ON (or AUTO) */
  8554. #ifdef COMMENT
  8555. #ifdef MYREAD
  8556. /*
  8557.   Seems like this would be a good idea but it prevents C-Kermit from
  8558.   popping back to the prompt automatically when carrier drops.  However,
  8559.   commenting this out prevents us from seeing the NO CARRIER message.
  8560.   Needs more work...
  8561. */
  8562.            && my_count < 1    /* Nothing in our internal buffer */
  8563. #endif /* MYREAD */
  8564. #endif /* COMMENT */
  8565.            ) {
  8566.         int x;
  8567.         x = ttgmdm();        /* So get modem signals */
  8568.         if (x > -1) {        /* Check for carrier */
  8569.         if (!(x & BM_DCD)) {    /* No carrier */
  8570.             debug(F101,"in_chk carrier lost","",x);
  8571.             if (clsondisc) {    /* If "close-on-disconnect" */
  8572.             debug(F100,"in_chk close-on-disconnect","",0);
  8573.             ttclos(0);    /* close device & release lock. */
  8574.             }
  8575.             return(-2);        /* This means "disconnected" */
  8576.         }
  8577.         }
  8578.     }
  8579.     }
  8580.  
  8581. /* We seem to have a connection so now see if any bytes are waiting on it */
  8582.  
  8583. #ifdef CK_SSL
  8584.     if (ssl_active_flag) {
  8585.         n += SSL_pending(ssl_con);
  8586.         debug(F101,"in_chk SSL_pending","",n);
  8587.         if (n < 0)            /* Is this right? */
  8588.       return(-1);
  8589.         else
  8590.       return(n);
  8591.     } else if (tls_active_flag) {
  8592.         n += SSL_pending(tls_con);
  8593.         debug(F101,"in_chk TLS_pending","",n);
  8594.         if (n < 0)            /* Is this right? */
  8595.       return(-1);
  8596.         else
  8597.       return(n);
  8598.     }
  8599. #endif /* CK_SSL */
  8600. #ifdef RLOGCODE
  8601. #ifdef CK_KERBEROS
  8602.     /* It is not safe to read any data when using encrypted Klogin */
  8603.     if (ttnproto == NP_EK4LOGIN || ttnproto == NP_EK5LOGIN) {
  8604. #ifdef KRB4
  8605.         if (ttnproto == NP_EK4LOGIN) {
  8606.             n += krb4_des_avail(ttyfd);
  8607.             debug(F101,"in_chk krb4_des_avail","",n);
  8608.         }
  8609. #endif /* KRB4 */
  8610. #ifdef KRB5
  8611.         if (ttnproto == NP_EK5LOGIN) {
  8612.             n += krb5_des_avail(ttyfd);
  8613.             debug(F101,"in_chk krb5_des_avail","",n);
  8614.         }
  8615. #endif /* KRB5 */
  8616.         if (n < 0)            /* Is this right? */
  8617.       return(-1);
  8618.         else
  8619.       return(n);
  8620.     }
  8621. #endif /* CK_KERBEROS */
  8622. #endif /* RLOGCODE */
  8623.  
  8624.     errno = 0;                /* Reset this so we log good info */
  8625. #ifdef FIONREAD
  8626.     x = ioctl(fd, FIONREAD, &n);    /* BSD and lots of others */
  8627. #ifdef DEBUG                /* (the more the better) */
  8628.     if (deblog) {
  8629.     debug(F101,"in_chk FIONREAD return code","",x);
  8630.     debug(F101,"in_chk FIONREAD count","",n);
  8631.     debug(F101,"in_chk FIONREAD errno","",errno);
  8632.     }
  8633. #endif /* DEBUG */
  8634. #else /* FIONREAD not defined */
  8635. /*
  8636.   Here, if (netconn && ttnet == NET_TCPB), we might try calling recvmsg()
  8637.   with flags MSG_PEEK|MSG_DONTWAIT on the socket (ttyfd), except this is not
  8638.   portable (MSG_DONTWAIT isn't defined in any of the <sys/socket.h> files
  8639.   that I looked at, but it is needed to prevent the call from blocking), and
  8640.   the msghdr struct differs from place to place, so we would need another
  8641.   avalanche of ifdefs.  Still, when FIONREAD is not available, this is the
  8642.   only other known method of asking the OS for the *number* of characters
  8643.   available for reading.
  8644. */
  8645. #ifdef V7                /* UNIX V7: look in kernel memory */
  8646. #ifdef MINIX
  8647.     n = 0;                /* But not in MINIX */
  8648. #else
  8649. #ifdef MINIX2
  8650.     n = 0;
  8651. #else
  8652.     lseek(kmem[TTY], (long) qaddr[TTY], 0); /* 7th Edition Unix */
  8653.     x = read(kmem[TTY], &n, sizeof(int));
  8654.     if (x != sizeof(int))
  8655.       n = 0;
  8656. #endif /* MINIX2 */
  8657. #endif /* MINIX */
  8658. #else /* Not V7 */
  8659. #ifdef PROVX1
  8660.     x = ioctl(fd, TIOCQCNT, &ttbuf);    /* DEC Pro/3xx Venix V.1 */
  8661.     n = ttbuf.sg_ispeed & 0377;        /* Circa 1984 */
  8662.     if (x < 0) n = 0;
  8663. #else
  8664. #ifdef MYREAD
  8665. /*
  8666.   Here we skip all the undependable and expensive calls below if we
  8667.   already have something in our internal buffer.  This tends to work quite
  8668.   nicely, so the only really bad case remaining is the one in which neither
  8669.   FIONREAD or MYREAD are defined, which is increasingly rare these days.
  8670. */
  8671.     if (channel != 0 && my_count > 0) {
  8672.     debug(F101,"in_chk buf my_count","",my_count);
  8673.     n = my_count;            /* n was 0 before we got here */
  8674.     return(n);
  8675.     }
  8676. #endif /* MYREAD */
  8677. /*
  8678.   rdchk(), select(), and poll() tell us *if* data is available to be read, but
  8679.   not how much, so these should be used only as a final resort.  Especially
  8680.   since these calls tend to add a lot overhead.
  8681. */
  8682. #ifdef RDCHK                /* This mostly SCO-specific */
  8683.     n = rdchk(fd);
  8684.     debug(F101,"in_chk rdchk","",n);
  8685. #else /* No RDCHK */
  8686. #ifdef SELECT
  8687. #ifdef Plan9
  8688.     /* Only allows select on the console ... don't ask */
  8689.     if (channel == 0)
  8690. #endif /* Plan9 */
  8691.       {
  8692.     fd_set rfds;            /* Read file descriptors */
  8693. #ifdef BELLV10
  8694.     FD_ZERO(rfds);            /* Initialize them */
  8695.     FD_SET(fd,rfds);        /* We want to look at this fd */
  8696. #else
  8697.     FD_ZERO(&rfds);            /* Initialize them */
  8698.     FD_SET(fd,&rfds);        /* We want to look at this fd */
  8699.     tv.tv_sec = tv.tv_usec = 0L;    /* A 0-valued timeval structure */
  8700. #endif /* BELLV10 */
  8701. #ifdef Plan9
  8702.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  8703.     debug(F101,"in_chk Plan 9 select","",n);
  8704. #else
  8705. #ifdef BELLV10
  8706.     n = select( 128, rfds, (fd_set *)0, (fd_set *)0, 0 );
  8707.     debug(F101,"in_chk BELLV10 select","",n);
  8708. #else
  8709. #ifdef BSD44
  8710.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  8711.     debug(F101,"in_chk BSD44 select","",n);
  8712. #else
  8713. #ifdef BSD43
  8714.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  8715.     debug(F101,"in_chk BSD43 select","",n);
  8716. #else
  8717. #ifdef SOLARIS
  8718.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  8719.     debug(F101,"in_chk SOLARIS select","",n);
  8720. #else
  8721. #ifdef QNX
  8722.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  8723.     debug(F101,"in_chk QNX select","",n);
  8724. #else
  8725. #ifdef COHERENT
  8726.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  8727.     debug(F101,"in_chk COHERENT select","",n);
  8728. #else
  8729. #ifdef SVR4
  8730.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  8731.     debug(F101,"in_chk SVR4 select","",n);
  8732. #else
  8733. #ifdef __linux__
  8734.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  8735.     debug(F101,"in_chk LINUX select","",n);
  8736. #else
  8737.     n = select( FD_SETSIZE, &rfds, (int *)0, (int *)0, &tv );
  8738.     debug(F101,"in_chk catchall select","",n);
  8739. #endif /* __linux__ */
  8740. #endif /* SVR4 */
  8741. #endif /* COHERENT */
  8742. #endif /* QNX */
  8743. #endif /* SOLARIS */
  8744. #endif /* BSD43 */
  8745. #endif /* BSD44 */
  8746. #endif /* BELLV10 */
  8747. #endif /* Plan9 */
  8748.     }
  8749. #else  /* Not SELECT */
  8750. #ifdef CK_POLL
  8751.     {
  8752.       struct pollfd pfd;
  8753.  
  8754.       pfd.fd = fd;
  8755.       pfd.events = POLLIN;
  8756.       pfd.revents = 0;
  8757.       n = poll(&pfd, 1, 0);
  8758.       debug(F101,"in_chk poll","",n);
  8759.       if ((n > 0) && (pfd.revents & POLLIN))
  8760.     n = 1;
  8761.     }
  8762. #endif /* CK_POLL */
  8763. #endif /* SELECT */
  8764. #endif /* RDCHK */
  8765. #endif /* PROVX1 */
  8766. #endif /* V7 */
  8767. #endif /* FIONREAD */
  8768.  
  8769. /* From here down, treat console and communication device differently... */
  8770.  
  8771.     if (channel == 0) {            /* Console */
  8772.  
  8773. #ifdef SVORPOSIX
  8774. #ifndef FIONREAD
  8775. #ifndef SELECT
  8776. #ifndef CK_POLL
  8777. #ifndef RDCHK
  8778. /*
  8779.   This is the hideous hack used in System V and POSIX systems that don't
  8780.   support FIONREAD, rdchk(), select(), poll(), etc, in which the user's
  8781.   CONNECT-mode escape character is attached to SIGQUIT.  Used, obviously,
  8782.   only on the console.
  8783. */
  8784.     if (conesc) {            /* Escape character typed == SIGQUIT */
  8785.         debug(F100,"in_chk conesc","",conesc);
  8786.         conesc = 0;
  8787.         signal(SIGQUIT,esctrp);    /* Restore signal */
  8788.         n += 1;
  8789.     }
  8790. #endif /* RDCHK */
  8791. #endif /* CK_POLL */
  8792. #endif /* SELECT */
  8793. #endif /* FIONREAD */
  8794. #endif /* SVORPOSIX */
  8795.  
  8796.     return(n);            /* Done with console */
  8797.     }
  8798.  
  8799.     if (channel != 0) {            /* Communications connection */
  8800.  
  8801. #ifdef MYREAD
  8802. #ifndef FIONREAD
  8803. /*
  8804.   select() or rdchk(), etc, has told us that something is waiting, but we
  8805.   don't know how much.  So we do a read to get it and then we know.  Note:
  8806.   This read is NOT nonblocking if nothing is there (because of VMIN=1), but
  8807.   it should be safe in this case since the OS tells us at least one byte is
  8808.   waiting to be read, and MYREAD reads return as much as is there without
  8809.   waiting for any more.  Controlled tests on Solaris and Unixware (with
  8810.   FIONREAD deliberately undefined) show this to be true.
  8811. */
  8812.     debug(F101,"in_chk read my_count","",my_count);
  8813.     debug(F101,"in_chk read n","",n);
  8814.     if (n > 0 && my_count == 0) {
  8815.         /* This also catches disconnects etc */
  8816.         /* Do what mygetbuf does except don't grab a character */
  8817.         my_count = myfillbuf();
  8818.         my_item = -1;        /* ^^^ */
  8819.         debug(F101,"in_chk myfillbuf my_count","",my_count);
  8820.         if (my_count < 0)
  8821.           return(-1);
  8822.         else
  8823.           n = 0;            /* NB: n is replaced by my_count */
  8824.     }
  8825. #endif /* FIONREAD */
  8826. /*
  8827.   Here we add whatever we think is unread to what is still in our
  8828.   our internal buffer.  Thus the importance of setting n to 0 just above.
  8829. */
  8830.     debug(F101,"in_chk my_count","",my_count);
  8831.     debug(F101,"in_chk n","",n);
  8832.     if (my_count > 0)
  8833.       n += my_count;
  8834. #endif /* MYREAD */
  8835.     }
  8836.     debug(F101,"in_chk result","",n);
  8837.  
  8838.     /* Errors here don't prove the connection has dropped so just say 0 */
  8839.  
  8840.     return(n < 0 ? 0 : n);
  8841. }
  8842.  
  8843.  
  8844. /*  T T C H K  --  Tell how many characters are waiting in tty input buffer  */
  8845.  
  8846. int
  8847. ttchk() {
  8848.     int fd;
  8849. #ifdef NETCMD
  8850.     if (ttpipe)
  8851.       fd = fdin;
  8852.     else
  8853. #endif /* NETCMD */
  8854.       fd = ttyfd;
  8855.     return(in_chk(1,fd));
  8856. }
  8857.  
  8858. /*  T T X I N  --  Get n characters from tty input buffer  */
  8859.  
  8860. /*  Returns number of characters actually gotten, or -1 on failure  */
  8861.  
  8862. /*  Intended for use only when it is known that n characters are actually */
  8863. /*  Available in the input buffer.  */
  8864.  
  8865. int
  8866. ttxin(n,buf) int n; CHAR *buf; {
  8867.     register int x = 0, i = 0, c = -2;
  8868.     char cc;
  8869.     int fd;
  8870.  
  8871.     if (n < 1)                /* Nothing to do */
  8872.       return(0);
  8873.  
  8874. #ifdef TTLEBUF
  8875.     if (ttpush >= 0) {
  8876.         buf[0] = ttpush;        /* Put pushed char in buffer*/
  8877.         ttpush = -1;            /* Clear the push buffer */
  8878.         if (ttchk() > 0)
  8879.       return(ttxin(n-1, &buf[1]) + 1);
  8880.         else
  8881.       return(1);
  8882.     }
  8883.     if (le_data) {
  8884.         while (le_inbuf() > 0) {
  8885.         if (le_getchar(&buf[i])) {
  8886.                 i++;
  8887.                 n--;
  8888.             }
  8889.         }
  8890.         if (ttchk() > 0)
  8891.       return(ttxin(n,&buf[i])+i);
  8892.         else
  8893.       return(i);
  8894.     }
  8895. #endif /* TTLEBUF */
  8896.  
  8897. #ifdef NETCMD
  8898.     if (ttpipe)
  8899.       fd = fdin;
  8900.     else
  8901. #endif /* NETCMD */
  8902.       fd = ttyfd;
  8903.  
  8904. #ifdef SUNX25
  8905.     if (netconn && (ttnet == NET_SX25))    /* X.25 connection */
  8906.       return(x25xin(n,buf));
  8907. #endif /* SUNX25 */
  8908.  
  8909. #ifdef IBMX25
  8910.     /* riehm: possibly not needed. Test worked with normal reads and writes */
  8911.     if (netconn && (ttnet == NET_IX25))    { /* X.25 connection */
  8912.     x = x25xin(n,buf);
  8913.     if (x > 0) buf[x] = '\0';
  8914.     return(x);
  8915.     }
  8916. #endif /* IBMX25 */
  8917.  
  8918. #ifdef MYREAD
  8919.     debug(F101,"ttxin MYREAD","",n);
  8920.     while (x < n) {
  8921.     c = myread();
  8922.     if (c < 0) {
  8923.         debug(F101,"ttxin myread returns","",c);
  8924.         if (c == -3) x = -1;
  8925.         break;
  8926.         }
  8927.     buf[x++] = c & ttpmsk;
  8928. #ifdef RLOGCODE
  8929. #ifdef CK_KERBEROS
  8930.         /* It is impossible to know how many characters are waiting */
  8931.         /* to be read when you are using Encrypted Rlogin or SSL    */
  8932.         /* as the transport since the number of real data bytes     */
  8933.         /* can be greater or less than the number of bytes on the   */
  8934.         /* wire which is what ttchk() returns.                      */
  8935.         if (netconn && (ttnproto == NP_EK4LOGIN || ttnproto == NP_EK5LOGIN))
  8936.       if (ttchk() <= 0)
  8937.         break;
  8938. #endif /* CK_KERBEROS */
  8939. #endif /* RLOGCODE */
  8940. #ifdef CK_SSL
  8941.         if (ssl_active_flag || tls_active_flag)
  8942.       if (ttchk() <= 0)
  8943.         break;
  8944. #endif /* CK_SSL */
  8945.     }
  8946. #else
  8947.     debug(F101,"ttxin READ","",n);
  8948.     x = read(fd,buf,n);
  8949.     for (c = 0; c < n; c++)        /* Strip any parity */
  8950.       buf[c] &= ttpmsk;
  8951. #endif /* MYREAD */
  8952.  
  8953.     debug(F101,"ttxin x","",x);        /* Done */
  8954.     if (x > 0) buf[x] = '\0';
  8955.     if (x < 0) x = -1;
  8956.     return(x);
  8957. }
  8958.  
  8959. /*  T T O L  --  Write string s, length n, to communication device.  */
  8960. /*
  8961.   Returns:
  8962.    >= 0 on success, number of characters actually written.
  8963.    -1 on failure.
  8964. */
  8965. #ifdef CK_ENCRYPTION
  8966. CHAR * xpacket = NULL;
  8967. int nxpacket = 0;
  8968. #endif /* CK_ENCRYPTION */
  8969.  
  8970. #define TTOLMAXT 5
  8971. int
  8972. ttol(s,n) int n; CHAR *s; {
  8973.     int x, len, tries, fd;
  8974. #ifdef CKXXCHAR
  8975.     extern int dblflag;            /* For SET SEND DOUBLE-CHARACTER */
  8976.     extern short dblt[];
  8977.     CHAR *p = NULL, *p2, *s2, c;
  8978.     int n2 = 0;
  8979. #endif /* CKXXCHAR */
  8980.  
  8981.     if (ttyfd < 0)            /* Not open? */
  8982.       return(-3);
  8983. #ifdef DEBUG
  8984.     if (deblog) hexdump("ttol s",s,n);
  8985. #endif /* DEBUG */
  8986.  
  8987. #ifdef NETCMD
  8988.     if (ttpipe)
  8989.       fd = fdout;
  8990.     else
  8991. #endif /* NETCMD */
  8992.       fd = ttyfd;
  8993.  
  8994. #ifdef CKXXCHAR
  8995. /*  Double any characters that must be doubled.  */
  8996.     debug(F101,"ttol dblflag","",dblflag);
  8997.     if (dblflag) {
  8998.     p = (CHAR *) malloc(n + n + 1);
  8999.     if (p) {
  9000.         s2 = s;
  9001.         p2 = p;
  9002.         n2 = 0;
  9003.         while (*s2) {
  9004.         c = *s2++;
  9005.         *p2++ = c;
  9006.         n2++;
  9007.         if (dblt[(unsigned) c] & 2) {
  9008.             *p2++ = c;
  9009.             n2++;
  9010.         }
  9011.         }
  9012.         s = p;
  9013.         n = n2;
  9014.         s[n] = '\0';
  9015.     }
  9016.     }
  9017.     debug(F111,"ttol doubled",s,n);
  9018. #endif /* CKXXCHAR */
  9019.  
  9020.     tries = TTOLMAXT;            /* Allow up to this many tries */
  9021.     len = n;                /* Remember original length */
  9022.  
  9023. #ifdef CK_ENCRYPTION
  9024. /*
  9025.   This is to avoid encrypting a packet that is already encrypted, e.g.
  9026.   when we resend a packet directly out of the packet buffer, and also to
  9027.   avoid encrypting a constant (literal) string, which can cause a memory
  9028.   fault.
  9029. */
  9030.     if (TELOPT_ME(TELOPT_ENCRYPTION)) {
  9031.     int x;
  9032.     if (nxpacket < n) {
  9033.         if (xpacket) {
  9034.         free(xpacket);
  9035.         xpacket = NULL;
  9036.         nxpacket = 0;
  9037.         }
  9038.         x = n > 10240 ? n : 10240;
  9039.         xpacket = (CHAR *)malloc(x);
  9040.         if (!xpacket) {
  9041.         fprintf(stderr,"ttol malloc failure\n");
  9042.         return(-1);
  9043.         } else
  9044.           nxpacket = x;
  9045.     }
  9046.     memcpy((char *)xpacket,(char *)s,n);
  9047.     s = xpacket;
  9048.     ck_tn_encrypt((char *)s,n);
  9049.     }
  9050. #endif /* CK_ENCRYPTION */
  9051.  
  9052.     while (n > 0 &&
  9053.        (tries-- > 0
  9054. #ifdef CK_ENCRYPTION
  9055.         /* keep trying if we are encrypting */
  9056.         || TELOPT_ME(TELOPT_ENCRYPTION)
  9057. #endif /* CK_ENCRYPTION */
  9058.             )) {            /* Be persistent */
  9059.     debug(F101,"ttol try","",TTOLMAXT - tries);
  9060. #ifdef BEBOX
  9061.         if (netconn && !ttpipe && !ttpty)
  9062.       x = nettol((char *)s,n);    /* Write string to device */
  9063.         else
  9064. #endif /* BEBOX */
  9065. #ifdef IBMX25
  9066.       if (ttnet == NET_IX25)
  9067.         /*
  9068.          * this is a more controlled way of writing to X25
  9069.          * STREAMS, however write should also work!
  9070.          */
  9071.         x = x25write(ttyfd, s, n);
  9072.       else
  9073. #endif /* IBMX25 */
  9074. #ifdef CK_SSL
  9075.         if (ssl_active_flag || tls_active_flag) {
  9076.         int error;
  9077.         /* Write using SSL */
  9078.         if (ssl_active_flag)
  9079.                   x = SSL_write(ssl_con, s, n);
  9080.         else
  9081.                   x = SSL_write(tls_con, s, n);
  9082.         switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,x)) {
  9083.           case SSL_ERROR_NONE:
  9084.             break;
  9085.           case SSL_ERROR_WANT_WRITE:
  9086.           case SSL_ERROR_WANT_READ:
  9087.             x = 0;
  9088.             break;
  9089.           case SSL_ERROR_SYSCALL:
  9090.           case SSL_ERROR_WANT_X509_LOOKUP:
  9091.           case SSL_ERROR_SSL:
  9092.           case SSL_ERROR_ZERO_RETURN:
  9093.           default:
  9094.             ttclos(0);
  9095.             return(-3);
  9096.         }
  9097.         } else
  9098. #endif /* CK_SSL */
  9099. #ifdef RLOGCODE
  9100. #ifdef CK_KERBEROS
  9101. #ifdef KRB4
  9102.         if (ttnproto == NP_EK4LOGIN) {
  9103.         return(krb4_des_write(ttyfd,s,n));
  9104.         } else
  9105. #endif /* KRB4 */
  9106. #ifdef KRB5
  9107.             if (ttnproto == NP_EK5LOGIN) {
  9108.                 return(krb5_des_write(ttyfd,s,n));
  9109.             } else
  9110. #endif /* KRB5 */
  9111. #endif /* CK_KERBEROS */
  9112. #endif /* RLOGCODE */
  9113.           x = write(fd,s,n);    /* Write string to device */
  9114.  
  9115.     if (x == n) {            /* Worked? */
  9116.         debug(F101,"ttol ok","",x);    /* OK */
  9117. #ifdef CKXXCHAR
  9118.         if (p) free(p);
  9119. #endif /* CKXXCHAR */
  9120.         return(len);        /* Done */
  9121.     } else if (x < 0) {        /* No, got error? */
  9122.         debug(F101,"ttol write error","",errno);
  9123. #ifdef EWOULDBLOCK
  9124.         if (errno == EWOULDBLOCK) {
  9125.         msleep(10);
  9126.         continue;
  9127.         } else
  9128. #endif /* EWOULDBLOCK */
  9129. #ifdef TCPSOCKET
  9130.         if (netconn && ttnet == NET_TCPB) {
  9131.         debug(F101,"ttol TCP error","",errno);
  9132.         ttclos(0);        /* Close the connection. */
  9133.         x = -3;
  9134.         }
  9135. #endif /* TCPSOCKET */
  9136. #ifdef CKXXCHAR
  9137.         if (p) free(p);
  9138. #endif /* CKXXCHAR */
  9139.         return(x);
  9140.     } else {            /* No error, so partial success */
  9141.         debug(F101,"ttol partial","",x); /* This never happens */
  9142.         s += x;            /* Point to part not written yet */
  9143.         n -= x;            /* Adjust length */
  9144.         if (x > 0) msleep(10);    /* Wait 10 msec */
  9145.     }                /* Go back and try again */
  9146.     }
  9147. #ifdef CKXXCHAR
  9148.     if (p) free(p);
  9149. #endif /* CKXXCHAR */
  9150.     return(n < 1 ? len : -1);        /* Return the results */
  9151. }
  9152.  
  9153. /*  T T O C  --  Output a character to the communication line  */
  9154.  
  9155. /*
  9156.  This function should only be used for interactive, character-mode operations,
  9157.  like terminal connection, script execution, dialer i/o, where the overhead
  9158.  of the signals and alarms does not create a bottleneck.
  9159. */
  9160. int
  9161. #ifdef CK_ANSIC
  9162. ttoc(char c)
  9163. #else
  9164. ttoc(c) char c;
  9165. #endif /* CK_ANSIC */
  9166. /* ttoc */ {
  9167. #define TTOC_TMO 15            /* Timeout in case we get stuck */
  9168.     int xx, fd;
  9169.  
  9170.     if (ttyfd < 0)            /* Check for not open. */
  9171.       return(-1);
  9172.  
  9173. #ifdef NETCMD
  9174.     if (ttpipe)
  9175.       fd = fdout;
  9176.     else
  9177. #endif /* NETCMD */
  9178.       fd = ttyfd;
  9179.  
  9180.     c &= 0xff;
  9181.     /* debug(F101,"ttoc","",(CHAR) c); */
  9182.     saval = signal(SIGALRM,timerh);    /* Enable timer interrupt */
  9183.     xx = alarm(TTOC_TMO);        /* for this many seconds. */
  9184.     if (xx < 0) xx = 0;            /* Save old alarm value. */
  9185.     /* debug(F101,"ttoc alarm","",xx); */
  9186.     if (
  9187. #ifdef CK_POSIX_SIG
  9188.     sigsetjmp(sjbuf,1)
  9189. #else
  9190.     setjmp(sjbuf)
  9191. #endif /* CK_POSIX_SIG */
  9192.     ) {        /* Timer went off? */
  9193.     ttimoff();            /* Yes, cancel this alarm. */
  9194.     if (xx - TTOC_TMO > 0) alarm(xx - TTOC_TMO); /* Restore previous one */
  9195.         /* debug(F100,"ttoc timeout","",0); */
  9196. #ifdef NETCONN
  9197.     if (!netconn) {
  9198. #endif /* NETCONN */
  9199.         debug(F101,"ttoc timeout","",c);
  9200.         if (ttflow == FLO_XONX) {
  9201.         debug(F101,"ttoc flow","",ttflow); /* Maybe we're xoff'd */
  9202. #ifndef Plan9
  9203. #ifdef POSIX
  9204.         /* POSIX way to unstick. */
  9205.         debug(F100,"ttoc tcflow","",tcflow(ttyfd,TCOON));
  9206. #else
  9207. #ifdef BSD4                /* Berkeley way to do it. */
  9208. #ifdef TIOCSTART
  9209. /* .... Used to be "ioctl(ttyfd, TIOCSTART, 0);".  Who knows? */
  9210.         {
  9211.           int x = 0;
  9212.           debug(F101,"ttoc TIOCSTART","",ioctl(ttyfd, TIOCSTART, &x));
  9213.         }
  9214. #endif /* TIOCSTART */
  9215. #endif /* BSD4 */
  9216.                     /* Is there a Sys V way to do this? */
  9217. #endif /* POSIX */
  9218. #endif /* Plan9 */
  9219.         }
  9220. #ifdef NETCONN
  9221.         }
  9222. #endif /* NETCONN */
  9223.     return(-1);            /* Return failure code. */
  9224.     } else {
  9225.         int rc;
  9226. #ifdef BEBOX
  9227. #ifdef NETCONN
  9228.         if (netconn && !ttpipe && !ttpty)
  9229.       rc = nettoc(c);
  9230.         else
  9231. #endif /*  BEBOX */
  9232. #endif /* NETCONN */
  9233. #ifdef CK_ENCRYPTION
  9234.       if (TELOPT_ME(TELOPT_ENCRYPTION))
  9235.         ck_tn_encrypt(&c,1);
  9236. #endif /* CK_ENCRYPTION */
  9237. #ifdef IBMX25
  9238.     /* riehm: maybe this isn't necessary after all. Test program
  9239.      * worked fine with data being sent and retrieved with normal
  9240.      * read's and writes!
  9241.      */
  9242.     if (ttnet == NET_IX25)
  9243.       rc = x25write(ttyfd,&c,1); /* as above for X25 streams */
  9244.     else
  9245. #endif /* IBMX25 */
  9246. #ifdef CK_SSL
  9247.       if (ssl_active_flag || tls_active_flag) {
  9248.           int error;
  9249.           /* Write using SSL */
  9250.           if (ssl_active_flag)
  9251.                 rc = SSL_write(ssl_con, &c, 1);
  9252.           else
  9253.                 rc = SSL_write(tls_con, &c, 1);
  9254.           switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,rc)){
  9255.         case SSL_ERROR_NONE:
  9256.           break;
  9257.         case SSL_ERROR_WANT_WRITE:
  9258.         case SSL_ERROR_WANT_READ:
  9259.           rc = 0;
  9260.           break;
  9261.         case SSL_ERROR_SYSCALL:
  9262.         case SSL_ERROR_WANT_X509_LOOKUP:
  9263.         case SSL_ERROR_SSL:
  9264.         case SSL_ERROR_ZERO_RETURN:
  9265.         default:
  9266.           ttclos(0);
  9267.           return(-1);
  9268.           }
  9269.       } else
  9270. #endif /* CK_SSL */
  9271. #ifdef RLOGCODE
  9272. #ifdef CK_KERBEROS
  9273. #ifdef KRB4
  9274.       if (ttnproto == NP_EK4LOGIN) {
  9275.           rc = (krb4_des_write(ttyfd,&c,1) == 1);
  9276.       } else
  9277. #endif /* KRB4 */
  9278. #ifdef KRB5
  9279.           if (ttnproto == NP_EK5LOGIN) {
  9280.               rc = (krb5_des_write(ttyfd,&c,1) == 1);
  9281.           } else
  9282. #endif /* KRB5 */
  9283. #endif /* CK_KERBEROS */
  9284. #endif /* RLOGCODE */
  9285.         rc = write(fd,&c,1);    /* Try to write the character. */
  9286.     if (rc < 1) {            /* Failed */
  9287.         ttimoff();            /* Turn off the alarm. */
  9288.         alarm(xx);            /* Restore previous alarm. */
  9289.         debug(F101,"ttoc errno","",errno); /* Log the error, */
  9290.         return(-1);            /* and return the error code. */
  9291.     }
  9292.     }
  9293.     ttimoff();                /* Success, turn off the alarm. */
  9294.     alarm(xx);                /* Restore previous alarm. */
  9295.     return(0);                /* Return good code. */
  9296. }
  9297.  
  9298. /*  T T I N L  --  Read a record (up to break character) from comm line.  */
  9299. /*
  9300.   Reads up to "max" characters from the communication line, terminating on:
  9301.     (a) the packet length field if the "turn" argument is zero, or
  9302.     (b) on the packet-end character (eol) if the "turn" argument is nonzero
  9303.     (c) a certain number of Ctrl-C's in a row
  9304.  
  9305.   Returns:
  9306.     >= 0, the number of characters read upon success;
  9307.     -1 if "max" exceeded, timeout, or other correctable error;
  9308.     -2 on user interruption (c);
  9309.     -3 on fatal error like connection lost.
  9310.  
  9311.   The characters that were input are copied into "dest" with their parity bits
  9312.   stripped if parity was selected.  Returns the number of characters read.
  9313.   Characters after the eol are available upon the next call to this function.
  9314.  
  9315.   The idea is to minimize the number of system calls per packet, and also to
  9316.   minimize timeouts.  This function is the inner loop of the protocol and must
  9317.   be as efficient as possible.  The current strategy is to use myread().
  9318.  
  9319.   WARNING: This function calls parchk(), which is defined in another module.
  9320.   Normally, ckutio.c does not depend on code from any other module, but there
  9321.   is an exception in this case because all the other ck?tio.c modules also
  9322.   need to call parchk(), so it's better to have it defined in a common place.
  9323. */
  9324. #ifdef CTRLC
  9325. #undef CTRLC
  9326. #endif /* CTRLC */
  9327. #define CTRLC '\03'
  9328. /*
  9329.   We have four different declarations here because:
  9330.   (a) to allow Kermit to be built without the automatic parity sensing feature
  9331.   (b) one of each type for ANSI C, one for non-ANSI.
  9332. */
  9333.  
  9334. static int csave = -1;
  9335.  
  9336. #ifndef NOXFER
  9337. int
  9338. #ifdef PARSENSE
  9339. #ifdef CK_ANSIC
  9340. ttinl(CHAR *dest, int max,int timo, CHAR eol, CHAR start, int turn)
  9341. #else
  9342. ttinl(dest,max,timo,eol,start,turn) int max,timo,turn; CHAR *dest, eol, start;
  9343. #endif /* CK_ANSIC */
  9344. #else /* not PARSENSE */
  9345. #ifdef CK_ANSIC
  9346. ttinl(CHAR *dest, int max,int timo, CHAR eol)
  9347. #else
  9348. ttinl(dest,max,timo,eol) int max,timo; CHAR *dest, eol;
  9349. #endif /* __SDTC__ */
  9350. #endif /* PARSENSE */
  9351. /* ttinl */ {
  9352.  
  9353. #ifndef MYREAD
  9354.     CHAR ch, dum;
  9355. #endif /* MYREAD */
  9356. #ifdef PARSENSE
  9357.     int pktlen = -1;
  9358.     int lplen = 0;
  9359.     int havelen = 0;
  9360. #endif /* PARSENSE */
  9361.     int cc = 0;                /* Character count */
  9362.     int fd;
  9363.     int sopmask = 0xff;            /* Start-Of-Packet mask */
  9364. #ifdef CKXXCHAR
  9365.     extern short dblt[];        /* Ignore-character table */
  9366.     extern int ignflag;
  9367. #endif /* CKXXCHAR */
  9368. #ifdef TCPSOCKET
  9369.     extern CHAR stchr;
  9370. #endif /* TCPSOCKET */
  9371.     int x;
  9372.  
  9373.     if (ttyfd < 0) return(-3);          /* Not open. */
  9374.  
  9375.     debug(F101,"ttinl max","",max);
  9376.     debug(F101,"ttinl timo","",timo);
  9377.  
  9378. #ifdef NETCMD
  9379.     if (ttpipe)
  9380.       fd = fdin;
  9381.     else
  9382. #endif /* NETCMD */
  9383.       fd = ttyfd;
  9384.  
  9385. #ifdef COMMENT
  9386.     if (xlocal && conchk() > 0)        /* Allow for console interruptions */
  9387.       return(-1);
  9388. #endif /* COMMENT */
  9389.  
  9390.     *dest = '\0';                       /* Clear destination buffer */
  9391.     if (timo < 0) timo = 0;        /* Safety */
  9392.     if (timo) {                /* Don't time out if timo == 0 */
  9393.     int xx;
  9394.     saval = signal(SIGALRM,timerh);    /* Enable timer interrupt */
  9395.     xx = alarm(timo);        /* Set it. */
  9396.     debug(F101,"ttinl alarm","",xx);
  9397.     }
  9398.     if (
  9399. #ifdef CK_POSIX_SIG
  9400.     sigsetjmp(sjbuf,1)
  9401. #else
  9402.     setjmp(sjbuf)
  9403. #endif /* CK_POSIX_SIG */
  9404.     ) {                /* Timer went off? */
  9405.     debug(F100,"ttinl timout","",0); /* Get here on timeout. */
  9406.     /* debug(F110," with",(char *) dest,0); */
  9407.     ttimoff();            /* Turn off timer */
  9408.     return(-1);            /* and return error code. */
  9409.     } else {
  9410.     register int i, n;        /* local variables */
  9411.     int ccn = 0;
  9412. #ifdef PARSENSE
  9413.     register int flag = 0;
  9414.     debug(F000,"ttinl start","",start);
  9415. #endif /* PARSENSE */
  9416.  
  9417.     ttpmsk = ttprty ? 0177 : 0377;    /* Set parity stripping mask. */
  9418.     sopmask = needpchk ? 0177 : ttpmsk; /* And SOP matching mask. */
  9419.  
  9420. /* Now read into destination, stripping parity and looking for the */
  9421. /* the packet terminator, and also for several Ctrl-C's typed in a row. */
  9422.  
  9423.     i = 0;                /* Destination index */
  9424.     debug(F101,"ttinl eol","",eol);
  9425.  
  9426.     while (i < max-1) {
  9427. #ifdef MYREAD
  9428.         /* debug(F101,"ttinl i","",i); */
  9429.         errno = 0;
  9430.         if (csave > -1) {
  9431.             n = csave;
  9432.         debug(F101,"ttinl unsaving","",n);
  9433.         } else
  9434. #ifdef COMMENT
  9435.           if (xlocal && conchk() > 0) {
  9436.           /* Here we could catch keyboard interruptions. */
  9437.           /* But this would be VERY expensive. */
  9438.           /* We could also do it in myread() but it would be */
  9439.           /* expensive there too -- even if done with select()... */
  9440.           }
  9441. #endif /* COMMENT */
  9442.           if ((n = myread()) < 0) {    /* Timeout or i/o error? */
  9443. #ifdef DEBUG
  9444.         if (deblog) {
  9445.             debug(F101,"ttinl myread failure, n","",n);
  9446.             debug(F101,"ttinl myread errno","",errno);
  9447.         }
  9448. #endif /* DEBUG */
  9449.         /* Don't let EINTR break packets. */
  9450.         if (n == -3) {
  9451.             if (errno == EINTR && i > 0) {
  9452.             debug(F111,"ttinl EINTR myread i","continuing",i);
  9453.             continue;
  9454.             } else {
  9455.             debug(F110,"ttinl non-EINTR -3","closing",0);
  9456.             wasclosed = 1;
  9457.             ttimoff();    /* Turn off timer */
  9458.             ttclos(0);
  9459.             return(n);
  9460.             }
  9461.         } else if (n == -2 && netconn /* && timo == 0 */ ) {
  9462.             /* Here we try to catch broken network connections */
  9463.             /* even when ioctl() and read() do not catch them */
  9464.             debug(F111,"ttinl network myread failure","closing",n);
  9465.             wasclosed = 1;
  9466.             ttimoff();
  9467.             ttclos(0);
  9468.             return(-3);
  9469.         }
  9470.         break;            /* Break out of while loop */
  9471.         }
  9472.  
  9473. #else /* not MYREAD (is this code used anywhere any more?) */
  9474.  
  9475.         if (csave > -1)        /* Char saved from last time */
  9476.           ch = csave;
  9477.         else if ((n = read(fd, &ch, 1)) < 1)
  9478.           break;            /* Error - break out of while loop */
  9479.         n = ch;
  9480.  
  9481. #endif /* MYREAD */
  9482.  
  9483.         /* Get here with char in n */
  9484.  
  9485. #ifdef CK_ENCRYPTION
  9486.         /* If csave > -1 we already decrypted this character */
  9487.         /* So don't decrypt it again */
  9488.         if (TELOPT_U(TELOPT_ENCRYPTION) && csave == -1) {
  9489.         CHAR ch = n;
  9490.         ck_tn_decrypt(&ch,1);
  9491.         n = ch;
  9492.         }
  9493. #endif /* CK_ENCRYPTION */
  9494.  
  9495.         csave = -1;            /* Unflag that we unsaved a char */
  9496.  
  9497. #ifdef TCPSOCKET
  9498.         if (n == IAC &&        /* Handle Telnet options */
  9499.         ((xlocal && netconn && (ttnproto == NP_TELNET)) ||
  9500.         (!xlocal && sstelnet))) {
  9501.         n = tt_tnopt(n);
  9502.         if (n < 0)
  9503.           return(n);
  9504.         else if (n == 1)
  9505.           start = stchr;
  9506.         if (n != 255)        /* No data - go back for next char */
  9507.           continue;
  9508.         }                /* Quoted IAC - keep going */
  9509. #endif /* TCPSOCKET */
  9510. #ifdef CKXXCHAR
  9511.         if (ignflag)
  9512.           if (dblt[(unsigned) n] & 1) /* Character to ignore? */
  9513.         continue;
  9514. #endif /* CKXXCHAR */
  9515.  
  9516. /*
  9517.   Use parity mask, rather than always stripping parity, to check for
  9518.   cancellation.  Otherwise, runs like \x03\x83\x03 in a packet could cancel
  9519.   the transfer when parity is NONE.  (Note that \x03\x03\x03 is extremely
  9520.   unlikely due to run-length encoding.)
  9521. */
  9522.         /* Check cancellation */
  9523.         if (!xlocal && xfrcan && ((n & ttpmsk) == xfrchr)) {
  9524.         if (++ccn >= xfrnum) {    /* If xfrnum in a row, bail out. */
  9525.             if (timo) {        /* Clear timer. */
  9526.             ttimoff();
  9527.             }
  9528.             if (xfrchr < 32)
  9529.               printf("^%c...\r\n",(char)(xfrchr+64));
  9530.             else
  9531.               printf("Canceled...\r\n");
  9532.             return(-2);
  9533.         }
  9534.         } else ccn = 0;        /* No cancellation, reset counter, */
  9535.  
  9536. #ifdef PARSENSE
  9537.         if (flag == 0) {        /* Find the Start-Of-Packet. */
  9538.         if ((n & sopmask) == start) { /* Got it */
  9539.             flag = 1;
  9540.         } else {        /* Keep looking... */
  9541.             debug(F000,"ttinl skipping","",n);
  9542.             continue;
  9543.         }
  9544.         }
  9545.         dest[i++] = n & ttpmsk;
  9546. /*
  9547.   If we have not been instructed to wait for a turnaround character, we
  9548.   can go by the packet length field.  If turn != 0, we must wait for the
  9549.   end of line (eol) character before returning.  This is an egregious
  9550.   violation of all principles of layering...
  9551. */
  9552.         if (!havelen) {
  9553.         if (i == 2) {
  9554.             pktlen = xunchar(dest[1] & 0x7f);
  9555.             if (pktlen > 1) {
  9556.             havelen = 1;
  9557.             debug(F101,"ttinl length","",pktlen);
  9558.             }
  9559.         } else if (i == 5 && pktlen == 0) {
  9560.             lplen = xunchar(dest[4] & 0x7f);
  9561.         } else if (i == 6 && pktlen == 0) {
  9562.             pktlen = lplen * 95 + xunchar(dest[5] & 0x7f) + 5;
  9563.             havelen = 1;
  9564.             debug(F101,"ttinl extended length","",pktlen);
  9565.         }
  9566.         }
  9567.  
  9568. /*
  9569.   Suppose we looked at the sequence number here and found it was out of
  9570.   range?  This would mean either (a) incoming packets had SOP unprefixed
  9571.   and we are out of sync, or (b) the packet is damaged.  Since (a) is bad
  9572.   practice, let's ignore it.  So what should we do here if we know the
  9573.   packet is damaged?
  9574.  
  9575.    1. Nothing -- keep trying to read the packet till we find what we think
  9576.       is the end, or we time out, and let the upper layer decide what to
  9577.       do.  But since either the packet is corrupt or we are out of sync,
  9578.       our criterion for finding the end does not apply and we are likely
  9579.       to time out (or swallow a piece of the next packet) if our assumed
  9580.       length is too long.  (This was the behavior prior to version 7.0.)
  9581.  
  9582.    2. set flag = 0 and continue?  This would force us to wait for the
  9583.       next packet to come in, and therefore (in the nonwindowing case),
  9584.       would force a timeout in the other Kermit.
  9585.  
  9586.    3. set flag = 0 and continue, but only if the window size is > 1 and
  9587.       the window is not blocked?  Talk about cheating!
  9588.  
  9589.    4. Return a failure code and let the upper layer decide what to do.
  9590.       This should be equivalent to 3, but without the cheating.  So let's
  9591.       do it that way...
  9592. */
  9593.         if (i == 3) {        /* Peek at sequence number */
  9594.         x = xunchar(dest[i-1]);    /* If it's not in range... */
  9595.         if (x < 0 || x > 63) {
  9596.             debug(F111,"ttinl bad seq",dest,x);
  9597.             if (timo) ttimoff();
  9598.             return(-1);        /* return a nonfatal error */
  9599.         }
  9600.         }
  9601.  
  9602. #else /* PARSENSE */
  9603.         dest[i++] = n & ttpmsk;
  9604. #endif /* PARSENSE */
  9605.  
  9606.     /* Check for end of packet */
  9607.  
  9608.         if (
  9609. #ifdef PARSENSE
  9610. /*
  9611.   Purely length-driven if SET HANDSHAKE NONE (i.e. turn == 0).
  9612.   This allows packet terminators and handshake characters to appear
  9613.   literally inside a packet data field.
  9614. */
  9615.         (havelen && (i > pktlen+1) &&
  9616.          (!turn || (turn && (n & 0x7f) == turn))) /* (turn, not eol) */
  9617. #else /* !PARSENSE */
  9618. /*
  9619.   Built without PARSENSE, so just look for packet terminator.
  9620. */
  9621.         ((n & 0x7f) == eol)
  9622. #endif /* PARSENSE */
  9623.         ) {
  9624. #ifndef PARSENSE
  9625.         debug(F101,"ttinl got eol","",eol); /* (or turn) */
  9626.         dest[i] = '\0';        /* Yes, terminate the string, */
  9627.         /* debug(F101,"ttinl i","",i); */
  9628. #else
  9629. #ifdef DEBUG
  9630.         if (deblog) {
  9631.             if ((n & 0x7f) != eol) {
  9632.             debug(F101,"ttinl EOP length","",pktlen);
  9633.             debug(F101,"ttinl i","",i);
  9634. #ifdef MYREAD
  9635. #ifdef PARSENSE
  9636. /*
  9637.   We read a packet based on its length.  This leaves the EOP character still
  9638.   unread, and so ttchk() will always return at least 1 because of this.  But
  9639.   if we know it is there, we can safely get rid of it.  So...
  9640. */
  9641.             {
  9642.                 int x;
  9643.                 while (my_count > 0) {
  9644.                 x = ttinc(0);
  9645.                 /* Start of next packet */
  9646.                 if (x == start) { /* Save for next time */
  9647.                     csave = (unsigned)((unsigned)x & 0xff);
  9648.                     debug(F000,"ttinl csaved","",x);
  9649.                     break;
  9650.                 }
  9651.                 debug(F000,"ttinl removed","",x);
  9652.                 }
  9653.             }
  9654. #endif /* PARSENSE */
  9655. #endif /* MYREAD */
  9656.  
  9657.             } else debug(F101,"ttinl got eol","",eol); /* (or turn) */
  9658.         }
  9659. #endif /* DEBUG */
  9660.         dest[i] = '\0';        /* Terminate the string, */
  9661.             if (needpchk) {        /* Parity checked yet? */
  9662.             if (ttprty == 0) {    /* No, check. */
  9663.             if ((ttprty = parchk(dest,start,i)) > 0) {
  9664.                 int j;
  9665.                 debug(F101,"ttinl senses parity","",ttprty);
  9666.                 debug(F110,"ttinl packet before",dest,0);
  9667.                 ttpmsk = 0x7f;
  9668.                 for (j = 0; j < i; j++)
  9669.                   dest[j] &= 0x7f;    /* Strip parity from packet */
  9670.                 debug(F110,"ttinl packet after ",dest,0);
  9671.             } else ttprty = 0; /* Restore if parchk error */
  9672.             }
  9673.             sopmask = ttprty;
  9674.             needpchk = 0;
  9675.         }
  9676. #endif /* PARSENSE */
  9677.         if (timo) {        /* Turn off timer. */
  9678.             ttimoff();
  9679.         }
  9680.         debug(F011,"ttinl got", dest, (i < 60) ? i : -60);
  9681.         return(i);
  9682.         }
  9683.     } /* End of while() */
  9684.     ttimoff();
  9685.     return(n);
  9686.     }
  9687. }
  9688. #endif /* NOXFER */
  9689.  
  9690. /*  T T I N C --  Read a character from the communication line  */
  9691. /*
  9692.  On success, returns the character that was read, >= 0.
  9693.  On failure, returns -1 or other negative myread error code,
  9694.    or -2 if connection is broken or ttyfd < 0.
  9695.    or -3 if session limit has expired,
  9696.    or -4 if something or other...
  9697.  NOTE: The API does not provide for ttinc() returning a special code
  9698.  upon timeout, but we need it.  So for this we have a global variable,
  9699.  ttinctimo.
  9700. */
  9701. static int ttinctimo = 0;        /* Yuk */
  9702.  
  9703. int
  9704. ttinc(timo) int timo; {
  9705.  
  9706.     int n = 0, fd;
  9707.     int is_tn = 0;
  9708.     CHAR ch = 0;
  9709.  
  9710.     ttinctimo = 0;
  9711.  
  9712.     if (ttyfd < 0) return(-2);          /* Not open. */
  9713.  
  9714.     is_tn = (xlocal && netconn && ttnproto == NP_TELNET) ||
  9715.         (!xlocal && sstelnet);
  9716.  
  9717. #ifdef TTLEBUF
  9718.     if (ttpush >= 0) {
  9719.         debug(F111,"ttinc","ttpush",ttpush);
  9720.         ch = ttpush;
  9721.         ttpush = -1;
  9722.         return(ch);
  9723.     }
  9724.     if (le_data) {
  9725.         if (le_getchar(&ch) > 0) {
  9726.             debug(F111,"ttinc le_getchar","ch",ch);
  9727.             return(ch);
  9728.         }
  9729.     }
  9730. #endif /* TTLEBUF */
  9731.  
  9732. #ifdef NETCMD
  9733.     if (ttpipe)
  9734.       fd = fdin;
  9735.     else
  9736. #endif /* NETCMD */
  9737.       fd = ttyfd;
  9738.  
  9739.     if ((timo <= 0)            /* Untimed. */
  9740. #ifdef MYREAD
  9741.     || (my_count > 0)        /* Buffered char already waiting. */
  9742. #endif /* MYREAD */
  9743.     ) {
  9744. #ifdef MYREAD
  9745.         /* Comm line failure returns -1 thru myread, so no &= 0377 */
  9746.     n = myread();            /* Wait for a character... */
  9747.     /* debug(F000,"ttinc MYREAD n","",n); */
  9748. #ifdef CK_ENCRYPTION
  9749.     /* debug(F101,"ttinc u_encrypt","",TELOPT_U(TELOPT_ENCRYPTION)); */
  9750.     if (TELOPT_U(TELOPT_ENCRYPTION) && n >= 0) {
  9751.         ch = n;
  9752.         ck_tn_decrypt(&ch,1);
  9753.         n = ch;
  9754.     }
  9755. #endif /* CK_ENCRYPTION */
  9756.  
  9757. #ifdef NETPTY
  9758.     if (ttpty && n < 0) {
  9759.         debug(F101,"ttinc error on pty","",n);
  9760.         ttclos(0);
  9761.         return(n);
  9762.     }
  9763. #endif /* NETPTY */
  9764.  
  9765. #ifdef TNCODE
  9766.     if ((n > -1) && is_tn)
  9767.       return((unsigned)(n & 0xff));
  9768.     else
  9769. #endif /* TNCODE */
  9770.       return(n < 0 ? n : (unsigned)(n & ttpmsk));
  9771.  
  9772. #else  /* MYREAD */
  9773.  
  9774.         while ((n = read(fd,&ch,1)) == 0) /* Wait for a character. */
  9775.         /* Shouldn't have to loop in ver 5A. */
  9776. #ifdef NETCONN
  9777.       if (netconn) {        /* Special handling for net */
  9778.           netclos();        /* If read() returns 0 it means */
  9779.           netconn = 0;        /* the connection has dropped. */
  9780.           errno = ENOTCONN;
  9781.           return(-2);
  9782.       }
  9783. #endif /* NETCONN */
  9784.       ;
  9785.     /* debug(F101,"ttinc","",ch); */
  9786. #ifdef TNCODE
  9787.     if ((n > 0) && is_tn) {
  9788. #ifdef CK_ENCRYPTION
  9789.         if (TELOPT_U(TELOPT_ENCRYPTION)) {
  9790.         ck_tn_decrypt(&ch,1);
  9791.         n = ch;
  9792.         }
  9793. #endif /* CK_ENCRYPTION */
  9794.         return((unsigned)(ch & 0xff));
  9795.     } else
  9796. #endif /* TNCODE */
  9797.         return((n < 0) ? -4 : ((n == 0) ? -1 : (unsigned)(ch & ttpmsk)));
  9798. #endif /* MYREAD */
  9799.  
  9800.     } else {                /* Timed read */
  9801.  
  9802.     int oldalarm;
  9803.     saval = signal(SIGALRM,timerh);    /* Set up handler, save old one. */
  9804.     oldalarm = alarm(timo);        /* Set alarm, save old one. */
  9805.     if (
  9806. #ifdef CK_POSIX_SIG
  9807.         sigsetjmp(sjbuf,1)
  9808. #else
  9809.         setjmp(sjbuf)
  9810. #endif /* CK_POSIX_SIG */
  9811.         ) {                /* Timer expired */
  9812.         ttinctimo = 1;
  9813.         n = -1;            /* set flag */
  9814.     } else {
  9815. #ifdef MYREAD
  9816.         n = myread();        /* If managing own buffer... */
  9817.         debug(F101,"ttinc myread","",n);
  9818.         ch = n;
  9819. #else
  9820.         n = read(fd,&ch,1);        /* Otherwise call the system. */
  9821.         if (n == 0) n = -1;
  9822.         debug(F101,"ttinc read","",n);
  9823. #endif /* MYREAD */
  9824.  
  9825. #ifdef CK_ENCRYPTION
  9826.         if (TELOPT_U(TELOPT_ENCRYPTION) && n >= 0) {
  9827.         ck_tn_decrypt(&ch,1);
  9828.         }
  9829. #endif /* CK_ENCRYPTION */
  9830.         if (n >= 0)
  9831.           n = (unsigned) (ch & 0xff);
  9832.         else
  9833.           n = (n < 0) ? -4 : -2;    /* Special return codes. */
  9834.     }
  9835.     ttimoff();            /* Turn off the timer */
  9836.     if (oldalarm > 0) {
  9837.         if (n == -1)        /* and restore any previous alarm */
  9838.           oldalarm -= timo;
  9839.         if (oldalarm < 0)        /* adjusted by our timeout interval */
  9840.           oldalarm = 0;
  9841.         if (oldalarm) {
  9842.             debug(F101,"ttinc restoring oldalarm","",oldalarm);
  9843.         alarm(oldalarm);
  9844.         }
  9845.     }
  9846. #ifdef NETCONN
  9847.     if (netconn) {
  9848.         if (n == -2) {        /* read() returns 0 */
  9849.         netclos();        /* on network read failure */
  9850.         netconn = 0;
  9851.         errno = ENOTCONN;
  9852.         }
  9853.     }
  9854. #endif    /* NETCONN */
  9855. #ifdef TNCODE
  9856.     if ((n > -1) && is_tn)
  9857.       return((unsigned)(n & 0xff));
  9858.     else
  9859. #endif /* TNCODE */
  9860.       /* Return masked char or neg. */
  9861.       return( (n < 0) ? n : (unsigned)(n & ttpmsk) );
  9862.     }
  9863. }
  9864.  
  9865. /*  S N D B R K  --  Send a BREAK signal of the given duration  */
  9866.  
  9867. static int
  9868. #ifdef CK_ANSIC
  9869. sndbrk(int msec) {            /* Argument is milliseconds */
  9870. #else
  9871. sndbrk(msec) int msec; {
  9872. #endif /* CK_ANSIC */
  9873. #ifndef POSIX
  9874.     int x, n;
  9875. #endif /* POSIX */
  9876.  
  9877. #ifdef OXOS
  9878. #define BSDBREAK
  9879. #endif /* OXOS */
  9880.  
  9881. #ifdef ANYBSD
  9882. #define BSDBREAK
  9883. #endif /* ANYBSD */
  9884.  
  9885. #ifdef BSD44
  9886. #define BSDBREAK
  9887. #endif /* BSD44 */
  9888.  
  9889. #ifdef COHERENT
  9890. #ifdef BSDBREAK
  9891. #undef BSDBREAK
  9892. #endif /* BSDBREAK */
  9893. #endif /* COHERENT */
  9894.  
  9895. #ifdef BELLV10
  9896. #ifdef BSDBREAK
  9897. #undef BSDBREAK
  9898. #endif /* BSDBREAK */
  9899. #endif /* BELLV10 */
  9900.  
  9901. #ifdef PROVX1
  9902.     char spd;
  9903. #endif /* PROVX1 */
  9904.  
  9905.     debug(F101,"ttsndb ttyfd","",ttyfd);
  9906.     if (ttyfd < 0) return(-1);          /* Not open. */
  9907.  
  9908. #ifdef Plan9
  9909.     return p9sndbrk(msec);
  9910. #else
  9911. #ifdef NETCONN
  9912. #ifdef NETCMD
  9913.     if (ttpipe)                /* Pipe */
  9914.       return(ttoc('\0'));
  9915. #endif /* NETCMD */
  9916. #ifdef NETPTY
  9917.     if (ttpty)
  9918.       return(ttoc('\0'));
  9919. #endif /* NETPTY */
  9920.     if (netconn)             /* Send network BREAK */
  9921.       return(netbreak());
  9922. #endif /* NETCONN */
  9923.  
  9924.     if (msec < 1 || msec > 5000) return(-1); /* Bad argument */
  9925.  
  9926. #ifdef POSIX                /* Easy in POSIX */
  9927.     debug(F101,"sndbrk POSIX","",msec);
  9928.     return(tcsendbreak(ttyfd,msec / 375));
  9929. #else
  9930. #ifdef PROVX1
  9931.     gtty(ttyfd,&ttbuf);                 /* Get current tty flags */
  9932.     spd = ttbuf.sg_ospeed;              /* Save speed */
  9933.     ttbuf.sg_ospeed = B50;              /* Change to 50 baud */
  9934.     stty(ttyfd,&ttbuf);                 /*  ... */
  9935.     n = (int)strlen(brnuls);        /* Send the right number of nulls */
  9936.     x = msec / 91;
  9937.     if (x > n) x = n;
  9938.     write(ttyfd,brnuls,n);
  9939.     ttbuf.sg_ospeed = spd;              /* Restore speed */
  9940.     stty(ttyfd,&ttbuf);                 /*  ... */
  9941.     return(0);
  9942. #else
  9943. #ifdef aegis
  9944.     sio_$control((short)ttyfd, sio_$send_break, msec, st);
  9945.     return(0);
  9946. #else
  9947. #ifdef BSDBREAK
  9948.     n = FWRITE;                         /* Flush output queue. */
  9949. /* Watch out for int vs long problems in &n arg! */
  9950.     debug(F101,"sndbrk BSDBREAK","",msec);
  9951.     ioctl(ttyfd,TIOCFLUSH,&n);          /* Ignore any errors.. */
  9952.     if (ioctl(ttyfd,TIOCSBRK,(char *)0) < 0) {  /* Turn on BREAK */
  9953.         perror("Can't send BREAK");
  9954.         return(-1);
  9955.     }
  9956.     x = msleep(msec);                    /* Sleep for so many milliseconds */
  9957.     if (ioctl(ttyfd,TIOCCBRK,(char *)0) < 0) {  /* Turn off BREAK */
  9958.         perror("BREAK stuck!!!");
  9959.         doexit(BAD_EXIT,-1);        /* Get out, closing the line. */
  9960.                                         /*   with bad exit status */
  9961.     }
  9962.     return(x);
  9963. #else
  9964. #ifdef ATTSV
  9965. /*
  9966.   No way to send a long BREAK in Sys V, so send a bunch of regular ones.
  9967.   (Actually, Sys V R4 is *supposed* to have the POSIX tcsendbreak() function,
  9968.   but there's no way for this code to know for sure.)
  9969. */
  9970.     debug(F101,"sndbrk ATTSV","",msec);
  9971.     x = msec / 275;
  9972.     for (n = 0; n < x; n++) {
  9973.     /* Reportedly the cast breaks this function on some systems */
  9974.     /* But then why was it here in the first place? */
  9975.     if (ioctl(ttyfd,TCSBRK, /* (char *) */ 0) < 0) {
  9976.         perror("Can't send BREAK");
  9977.         return(-1);
  9978.     }
  9979.     }
  9980.     return(0);
  9981. #else
  9982. #ifdef  V7
  9983.     debug(F101,"sndbrk V7","",msec);
  9984.     return(genbrk(ttyfd,250));        /* Simulate a BREAK */
  9985. #else
  9986.     debug(F101,"sndbrk catchall","",msec);
  9987.     ttoc(0);ttoc(0);ttoc(0);ttoc(0);
  9988.     return(0);
  9989. #endif /* V7 */
  9990. #endif /* BSDBREAK */
  9991. #endif /* ATTSV */
  9992. #endif /* aegis */
  9993. #endif /* PROVX1 */
  9994. #endif /* POSIX */
  9995. #endif /* Plan9 */
  9996. }
  9997.  
  9998. /*  T T S N D B  --  Send a BREAK signal  */
  9999.  
  10000. int
  10001. ttsndb() {
  10002.     return(sndbrk(275));
  10003. }
  10004.  
  10005. /*  T T S N D L B  --  Send a Long BREAK signal  */
  10006.  
  10007. int
  10008. ttsndlb() {
  10009.     return(sndbrk(1500));
  10010. }
  10011.  
  10012. /*  M S L E E P  --  Millisecond version of sleep().  */
  10013.  
  10014. /*
  10015.   Call with number of milliseconds (thousandths of seconds) to sleep.
  10016.   Intended only for small intervals.  For big ones, just use sleep().
  10017.   Highly system-dependent.
  10018.   Returns 0 always, even if it didn't work.
  10019. */
  10020.  
  10021. /* Define MSLFTIME for systems that must use an ftime() loop. */
  10022. #ifdef ANYBSD                /* For pre-4.2 BSD versions */
  10023. #ifndef BSD4
  10024. #define MSLFTIME
  10025. #endif /* BSD4 */
  10026. #endif /* ANYBSD */
  10027.  
  10028. #ifdef TOWER1                /* NCR Tower OS 1.0 */
  10029. #define MSLFTIME
  10030. #endif /* TOWER1 */
  10031.  
  10032. #ifdef COHERENT         /* Coherent... */
  10033. #ifndef _I386           /* Maybe Coherent/386 should get this, too */
  10034. #define MSLFTIME        /* Opinions are divided */
  10035. #endif /* _I386 */
  10036. #endif /* COHERENT */
  10037.  
  10038. #ifdef COMMENT
  10039. #ifdef GETMSEC
  10040.  
  10041. /* Millisecond timer */
  10042.  
  10043. static long msecbase = 0L;        /* Unsigned long not portable */
  10044.  
  10045. long
  10046. getmsec() {                /* Milliseconds since base time */
  10047.     struct timeval xv;
  10048.     struct timezone xz;
  10049.     long secs, msecs;
  10050.     if (
  10051. #ifdef GTODONEARG
  10052.     gettimeofday(&tv)
  10053. #else
  10054. #ifdef PTX
  10055.     gettimeofday(&tv, NULL)
  10056. #else
  10057.     gettimeofday(&tv, &tz)
  10058. #endif /* PTX */
  10059. #endif /* GTODONEARG */
  10060.     < 0)
  10061.       return(-1);
  10062.     if (msecbase == 0L) {        /* First call, set base time. */
  10063.     msecbase = tv.tv_sec;
  10064.     debug(F101,"getmsec base","",msecbase);
  10065.     }
  10066.     return(((tv.tv_sec - msecbase) * 1000L) + (tv.tv_usec / 1000L));
  10067. }
  10068. #endif /* GETMSEC */
  10069. #endif /* COMMENT */
  10070.  
  10071. #ifdef SELECT
  10072. int
  10073. ttwait(fd, secs) int fd, secs; {
  10074.     int x;
  10075.     fd_set rfds;
  10076.     FD_ZERO(&rfds);
  10077.     FD_SET(fd,&rfds);
  10078.     tv.tv_sec = secs;
  10079.     tv.tv_usec = 0L;
  10080.     errno = 0;
  10081.     if ((x = select(FD_SETSIZE,
  10082. #ifdef HPUX9
  10083.             (int *)
  10084. #else
  10085. #ifdef HPUX1000
  10086.             (int *)
  10087. #endif /* HPUX1000 */
  10088. #endif /* HPUX9 */
  10089.             &rfds,
  10090.             0, 0, &tv)) < 0) {
  10091.     debug(F101,"ttwait select errno","",errno);
  10092.     return(0);
  10093.     } else {
  10094.     debug(F101,"ttwait OK","",errno);
  10095.     x = FD_ISSET(fd, &rfds);
  10096.     debug(F101,"ttwait select x","",x);
  10097.     return(x ? 1 : 0);
  10098.     }
  10099. }
  10100. #endif /* SELECT */
  10101.  
  10102. int
  10103. msleep(m) int m; {
  10104. /*
  10105.   Other possibilities here are:
  10106.    nanosleep(), reportedly defined in POSIX.4.
  10107.    sginap(), IRIX only (back to what IRIX version I don't know).
  10108. */
  10109. #ifdef Plan9
  10110.     return _SLEEP(m);
  10111. #else
  10112. #ifdef BEBOX
  10113.     snooze(m*1000);
  10114. #else /* BEBOX */
  10115. #ifdef SELECT
  10116.     int t1, x;
  10117.     debug(F101,"msleep SELECT 1","",m);
  10118.     if (m <= 0) return(0);
  10119.     if (m >= 1000) {            /* Catch big arguments. */
  10120.     sleep(m/1000);
  10121.     m = m % 1000;
  10122.     if (m < 10) return(0);
  10123.     }
  10124.     debug(F101,"msleep SELECT 2","",m);
  10125. #ifdef BELLV10
  10126.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, m );
  10127.     debug(F101,"msleep BELLV10 select","",x);
  10128. #else /* BELLV10 */
  10129. #ifdef HPUX9
  10130.     gettimeofday(&tv, &tz);
  10131. #else
  10132.  
  10133. #ifndef COHERENT
  10134. #ifdef GTODONEARG
  10135.     if (gettimeofday(&tv) < 0)
  10136. #else
  10137. #ifdef PTX
  10138.     if (gettimeofday(&tv,NULL) < 0)
  10139. #else
  10140.     if (gettimeofday(&tv, &tz) < 0)
  10141. #endif /* PTX */
  10142. #endif /* GTODONEARG */
  10143.       return(-1);
  10144.     t1 = tv.tv_sec;                     /* Seconds */
  10145. #endif /* COHERENT */
  10146. #endif /* HPUX9 */
  10147.     tv.tv_sec = 0;                      /* Use select() */
  10148.     tv.tv_usec = m * 1000L;
  10149. #ifdef BSD44
  10150.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  10151.     debug(F101,"msleep BSD44 select","",x);
  10152. #else /* BSD44 */
  10153. #ifdef __linux__
  10154.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  10155.     debug(F101,"msleep __linux__ select","",x);
  10156. #else /* __linux__ */
  10157. #ifdef BSD43
  10158.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  10159.     debug(F101,"msleep BSD43 select","",x);
  10160. #else /* BSD43 */
  10161. #ifdef QNX
  10162.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  10163.     debug(F101,"msleep QNX select","",x);
  10164. #else /* QNX */
  10165. #ifdef COHERENT
  10166.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  10167.     debug(F101,"msleep COHERENT select","",x);
  10168. #else /* COHERENT */
  10169. #ifdef HPUX1000                /* 10.00 only, not 10.10 or later */
  10170.     x = select( 0, (int *)0, (int *)0, (int *)0, &tv );
  10171.     debug(F101,"msleep HP-UX 10.00 select","",x);
  10172. #else /* HPUX1000 */
  10173. #ifdef SVR4
  10174.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  10175.     debug(F101,"msleep SVR4 select","",x);
  10176. #else /* SVR4 */
  10177. #ifdef OSF40
  10178.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  10179.     debug(F101,"msleep OSF40 select","",x);
  10180. #else /* OSF40 */
  10181. #ifdef PTX
  10182.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  10183.     debug(F101,"msleep OSF40 select","",x);
  10184. #else
  10185.     x = select( 0, (int *)0, (int *)0, (int *)0, &tv );
  10186.     debug(F101,"msleep catch-all select","",x);
  10187. #endif /* PTX */
  10188. #endif /* OSF40 */
  10189. #endif /* HP1000 */
  10190. #endif /* SVR4 */
  10191. #endif /* COHERENT */
  10192. #endif /* QNX */
  10193. #endif /* BSD43 */
  10194. #endif /* __linux__ */
  10195. #endif /* BSD44 */
  10196. #endif /* BELLV10 */
  10197.     return(0);
  10198.  
  10199. #else                    /* Not SELECT */
  10200. #ifdef CK_POLL                /* We have poll() */
  10201.     struct pollfd pfd;            /* Supply a valid address for poll() */
  10202.  
  10203. #ifdef ODT30                /* But in SCO ODT 3.0 */
  10204. #ifdef NAP                /* we should use nap() instead */
  10205.     debug(F101,"msleep ODT 3.0 NAP","",m); /* because using poll() here */
  10206.     nap((long)m);               /* seems to break dialing. */
  10207.     return(0);
  10208. #else
  10209.     debug(F101,"msleep ODT 3.0 POLL","",m);
  10210.     poll(&pfd, 0, m);
  10211.     return(0);
  10212. #endif /* NAP */
  10213. #else
  10214.     debug(F101,"msleep POLL","",m);
  10215.     poll(&pfd, 0, m);
  10216.     return(0);
  10217. #endif /* ODT30 */
  10218.  
  10219. /*
  10220.   We could handle the above more cleanly by just letting nap() take
  10221.   always take precedence over poll() in this routine, but there is no way
  10222.   to know whether that would break something else.
  10223. */
  10224.  
  10225. #else                    /* Not POLL */
  10226. #ifdef USLEEP
  10227. /*
  10228.   "This routine is implemented using setitimer(2); it requires eight
  10229.   system calls...".  In other words, it might take 5 minutes to sleep
  10230.   10 milliseconds...
  10231. */
  10232.     debug(F101,"msleep USLEEP","",m);
  10233.     if (m >= 1000) {            /* Catch big arguments. */
  10234.     sleep(m/1000);
  10235.     m = m % 1000;
  10236.     if (m < 10) return(0);
  10237.     }
  10238.     usleep((unsigned int)(m * 1000));
  10239.     return(0);
  10240. #else
  10241. #ifdef aegis
  10242.     time_$clock_t dur;
  10243.     debug(F101,"msleep aegis","",m);
  10244.     dur.c2.high16 = 0;
  10245.     dur.c2.low32  = 250 * m; /* one millisecond = 250 four microsecond ticks */
  10246.     time_$wait(time_$relative, dur, st);
  10247.     return(0);
  10248. #else
  10249. #ifdef PROVX1
  10250.     debug(F101,"msleep Venix","",m);
  10251.     if (m <= 0) return(0);
  10252.     sleep(-((m * 60 + 500) / 1000));
  10253.     return(0);
  10254. #else
  10255. #ifdef NAP
  10256.     debug(F101,"msleep NAP","",m);
  10257.     nap((long)m);
  10258.     return(0);
  10259. #else
  10260. #ifdef ATTSV
  10261. #ifndef BSD44
  10262.     extern long times();        /* Or #include <times.h> ? */
  10263. #endif /* BSD44 */
  10264.     long t1, t2, tarray[4];
  10265.     int t3;
  10266.     char *cp = getenv("HZ");
  10267.     int CLOCK_TICK;
  10268.     int hertz;
  10269.  
  10270.     if (cp && (hertz = atoi(cp))) {
  10271.         CLOCK_TICK  = 1000 / hertz;
  10272.     } else {                /* probably single user mode */
  10273. #ifdef HZ
  10274.         CLOCK_TICK  = 1000 / HZ;
  10275. #else
  10276.     static warned = 0;
  10277.     /* HZ always exists in, for instance, SCO Xenix, so you don't have to
  10278.      * make special #ifdefs for XENIX here, like in ver 4F. Also, if you
  10279.      * have Xenix, you have should have nap(), so the best is to use -DNAP
  10280.      * in the makefile. Most systems have HZ.
  10281.      */
  10282.     CLOCK_TICK = 17;        /* 1/60 sec */
  10283.     if (!warned) {
  10284.           printf("warning: environment variable HZ bad... using HZ=%d\r\n",
  10285.          1000 / CLOCK_TICK);
  10286.           warned = 1;
  10287.     }
  10288. #endif /* !HZ */
  10289.     }
  10290.     debug(F101,"msleep ATTSV","",m);
  10291.     if (m <= 0) return(0);
  10292.     if (m >= 1000) {            /* Catch big arguments. */
  10293.     sleep(m/1000);
  10294.     m = m % 1000;
  10295.     if (m < 10) return(0);
  10296.     }
  10297.     if ((t1 = times(tarray)) < 0) return(-1);
  10298.     while (1) {
  10299.         if ((t2 = times(tarray)) < 0) return(-1);
  10300.         t3 = ((int)(t2 - t1)) * CLOCK_TICK;
  10301.         if (t3 > m) return(t3);
  10302.     }
  10303. #else /* Not ATTSV */
  10304. #ifdef MSLFTIME                /* Use ftime() loop... */
  10305.     int t1, t3 = 0;
  10306.     debug(F101,"msleep MSLFTIME","",m);
  10307.     if (m <= 0) return(0);
  10308.     if (m >= 1000) {            /* Catch big arguments. */
  10309.     sleep(m/1000);
  10310.     m = m % 1000;
  10311.     if (m < 10) return(0);
  10312.     }
  10313. #ifdef QNX
  10314.     ftime(&ftp);            /* void ftime() in QNX */
  10315. #else
  10316.     if (ftime(&ftp) < 0) return(-1);    /* Get base time. */
  10317. #endif /* QNX */
  10318.     t1 = ((ftp.time & 0xff) * 1000) + ftp.millitm;
  10319.     while (1) {
  10320.         ftime(&ftp);            /* Get current time and compare. */
  10321.         t3 = (((ftp.time & 0xff) * 1000) + ftp.millitm) - t1;
  10322.         if (t3 > m) return(0);
  10323.     }
  10324. #else
  10325. /* This includes true POSIX, which has no way to do this. */
  10326.     debug(F101,"msleep busy loop","",m);
  10327.     if (m >= 1000) {            /* Catch big arguments. */
  10328.     sleep(m/1000);
  10329.     m = m % 1000;
  10330.     if (m < 10) return(0);
  10331.     }
  10332.     if (m > 0) while (m > 0) m--;    /* Just a dumb busy loop */
  10333.     return(0);
  10334. #endif /* MSLFTIME */
  10335. #endif /* ATTSV */
  10336. #endif /* NAP */
  10337. #endif /* PROVX1 */
  10338. #endif /* aegis */
  10339. #endif /* CK_POLL */
  10340. #endif /* SELECT */
  10341. #endif /* BEBOX */
  10342. #endif /* USLEEP */
  10343. #endif /* Plan9 */
  10344. }
  10345.  
  10346. /*  R T I M E R --  Reset elapsed time counter  */
  10347.  
  10348. VOID
  10349. rtimer() {
  10350.     tcount = time( (time_t *) 0 );
  10351. }
  10352.  
  10353.  
  10354. /*  G T I M E R --  Get current value of elapsed time counter in seconds  */
  10355.  
  10356. int
  10357. gtimer() {
  10358.     int x;
  10359.     x = (int) (time( (time_t *) 0 ) - tcount);
  10360.     debug(F101,"gtimer","",x);
  10361.     return( (x < 0) ? 0 : x );
  10362. }
  10363.  
  10364. #ifdef GFTIMER
  10365. /*
  10366.   Floating-point timers.  Require not only floating point support, but
  10367.   also gettimeofday().
  10368. */
  10369. static struct timeval tzero;
  10370.  
  10371. VOID
  10372. rftimer() {
  10373. #ifdef GTODONEARG    /* Account for Mot's definition */
  10374.     (VOID) gettimeofday(&tzero);
  10375. #else
  10376.     (VOID) gettimeofday(&tzero, (struct timezone *)0);
  10377. #endif /* GTODONEARG */
  10378. }
  10379.  
  10380. CKFLOAT
  10381. gftimer() {
  10382.     struct timeval tnow, tdelta;
  10383.     CKFLOAT s, sb;
  10384. #ifdef DEBUG
  10385.     char fpbuf[64];
  10386. #endif /* DEBUG */
  10387. #ifdef GTODONEARG    /* Acount for Mot's definition */
  10388.     (VOID) gettimeofday(&tnow);
  10389. #else
  10390.     (VOID) gettimeofday(&tnow, (struct timezone *)0);
  10391. #endif /* GTODONEARG */
  10392.     tdelta.tv_sec = tnow.tv_sec - tzero.tv_sec;
  10393.     tdelta.tv_usec = tnow.tv_usec - tzero.tv_usec;
  10394.     if (tdelta.tv_usec < 0) {
  10395.     tdelta.tv_sec--;
  10396.     tdelta.tv_usec += 1000000;
  10397.     }
  10398.     s = (CKFLOAT) tdelta.tv_sec + ((CKFLOAT) tdelta.tv_usec / 1000000.0);
  10399.     if (s < GFMINTIME)
  10400.       s = GFMINTIME;
  10401. #ifdef DEBUG
  10402.     if (deblog) {
  10403.     sprintf(fpbuf,"%f",s);
  10404.     debug(F110,"gftimer",fpbuf,0);
  10405.     }
  10406. #endif /* DEBUG */
  10407.     return(s);
  10408. }
  10409. #endif /* GFTIMER */
  10410.  
  10411.  
  10412. /*  Z T I M E  --  Return asctime()-format date/time string  */
  10413. /*
  10414.   NOTE: as a side effect of calling this routine, we can also set the
  10415.   following two variables, giving the micro- and milliseconds (fractions of
  10416.   seconds) of the clock time.  Currently this is done only in BSD-based builds
  10417.   that use gettimeofday().  When these variables are not filled in, they are
  10418.   left with a value of -1L.
  10419. */
  10420. VOID
  10421. ztime(s) char **s; {
  10422.  
  10423. #ifdef GFTIMER
  10424. /*
  10425.   The gettimeofday() method, which also sets ztmsec and ztusec, works for
  10426.   all GFTIMER builds.  NOTE: ztmsec and ztusec are defined in ckcmai.c,
  10427.   and extern declarations for them are in ckcdeb.h; thus they are
  10428.   declared in this file by inclusion of ckcdeb.h.
  10429. */
  10430.     char *asctime();
  10431.     struct tm *localtime();
  10432.     struct tm *tp;
  10433.     ztmsec = -1L;
  10434.     ztusec = -1L;
  10435.  
  10436. #ifdef GTODONEARG
  10437.     /* No 2nd arg in Motorola SV88 and some others */
  10438.     if (gettimeofday(&tv) > -1)
  10439. #else
  10440. #ifndef COHERENT
  10441. #ifdef PTX
  10442.     if (gettimeofday(&tv,NULL) > -1)
  10443. #else
  10444.     if (gettimeofday(&tv,&tz) > -1)
  10445. #endif /* PTX */
  10446. #endif /* COHERENT */
  10447. #endif /* GTODONEARG */
  10448.       {                    /* Fill in tm struct */
  10449.     ztusec = tv.tv_usec;        /* Microseconds */
  10450.     ztmsec = ztusec / 1000L;    /* Milliseconds */
  10451. #ifdef HPUX9
  10452.     {
  10453.         time_t zz;
  10454.         zz = tv.tv_sec;
  10455.         tp = localtime(&zz);    /* Convert to local time */
  10456.     }
  10457. #else
  10458. #ifdef HPUX1000
  10459.     {
  10460.         time_t zz;
  10461.         zz = tv.tv_sec;
  10462.         tp = localtime(&zz);
  10463.     }
  10464. #else
  10465. #ifdef LINUX
  10466.     {   /* avoid unaligned access trap on 64-bit platforms */
  10467.         time_t zz;
  10468.         zz = tv.tv_sec;
  10469.         tp = localtime(&zz);
  10470.     }
  10471. #else
  10472. #ifdef MACOSX
  10473.     tp = localtime((time_t *)&tv.tv_sec); /* Convert to local time */
  10474. #else
  10475.     tp = localtime(&tv.tv_sec);
  10476. #endif /* MACOSX */
  10477. #endif /* LINUX */
  10478. #endif /* HPUX1000 */
  10479. #endif /* HPUX9 */
  10480.     *s = asctime(tp);        /* Convert result to ASCII string */
  10481.     debug(F111,"ztime GFTIMER gettimeofday",*s,ztusec);
  10482.     }
  10483. #else  /* Not GFTIMER */
  10484.  
  10485. #undef ZTIMEV7                /* Which systems need to use */
  10486. #ifdef COHERENT                /* old UNIX Version 7 way... */
  10487. #define ZTIMEV7
  10488. #endif /* COHERENT */
  10489. #ifdef TOWER1
  10490. #define ZTIMEV7
  10491. #endif /* TOWER1 */
  10492. #ifdef ANYBSD
  10493. #ifndef BSD42
  10494. #define ZTIMEV7
  10495. #endif /* BSD42 */
  10496. #endif /* ANYBSD */
  10497. #ifdef V7
  10498. #ifndef MINIX
  10499. #define ZTIMEV7
  10500. #endif /* MINIX */
  10501. #endif /* V7 */
  10502. #ifdef POSIX
  10503. #define ZTIMEV7
  10504. #endif /* POSIX */
  10505.  
  10506. #ifdef HPUX1020
  10507. /*
  10508.   Prototypes are in <time.h>, included above.
  10509. */
  10510.     time_t clock_storage;
  10511.     clock_storage = time((void *) 0);
  10512.     *s = ctime(&clock_storage);
  10513.     debug(F110,"ztime: HPUX 10.20",*s,0);
  10514. #else
  10515. #ifdef ATTSV                /* AT&T way */
  10516. /*  extern long time(); */        /* Theoretically these should */
  10517.     char *ctime();            /* already been dcl'd in <time.h> */
  10518.     time_t clock_storage;
  10519.     clock_storage = time(
  10520. #ifdef IRIX60
  10521.              (time_t *)
  10522. #else
  10523. #ifdef BSD44
  10524.              (time_t *)
  10525. #else
  10526.              (long *)
  10527. #endif /* BSD44 */
  10528. #endif /* IRIX60 */
  10529.              0 );
  10530.     *s = ctime( &clock_storage );
  10531.     debug(F110,"ztime: ATTSV",*s,0);
  10532. #else
  10533. #ifdef PROVX1                /* Venix 1.0 way */
  10534.     int utime[2];
  10535.     time(utime);
  10536.     *s = ctime(utime);
  10537.     debug(F110,"ztime: PROVX1",*s,0);
  10538. #else
  10539. #ifdef BSD42                /* 4.2BSD way */
  10540.     char *asctime();
  10541.     struct tm *localtime();
  10542.     struct tm *tp;
  10543.     gettimeofday(&tv, &tz);
  10544.     ztusec = tv.tv_usec;
  10545.     ztmsec = tv.tv_usec / 1000L;
  10546.     tp = localtime(&tv.tv_sec);
  10547.     *s = asctime(tp);
  10548.     debug(F111,"ztime: BSD42",*s,ztusec);
  10549. #else
  10550. #ifdef MINIX                /* MINIX way */
  10551. #ifdef COMMENT
  10552.     extern long time();            /* Already got these from <time.h> */
  10553.     extern char *ctime();
  10554. #endif /* COMMENT */
  10555.     time_t utime[2];
  10556.     time(utime);
  10557.     *s = ctime(utime);
  10558.     debug(F110,"ztime: MINIX",*s,0);
  10559. #else
  10560. #ifdef ZTIMEV7                /* The regular way */
  10561.     char *asctime();
  10562.     struct tm *localtime();
  10563.     struct tm *tp;
  10564.     long xclock;            /* or unsigned long for BeBox? */
  10565.     time(&xclock);
  10566.     tp = localtime(&xclock);
  10567.     *s = asctime(tp);
  10568.     debug(F110,"ztime: ZTIMEV7",*s,0);
  10569. #else                    /* Catch-all for others... */
  10570.     *s = "Day Mon 00 00:00:00 0000\n";    /* Return dummy in asctime() format */
  10571.     debug(F110,"ztime: catch-all",*s,0);
  10572. #endif /* ZTIMEV7 */
  10573. #endif /* MINIX */
  10574. #endif /* BSD42 */
  10575. #endif /* PROVX1 */
  10576. #endif /* ATTSV */
  10577. #endif /* HPUX1020 */
  10578. #endif /* GFTIMER */
  10579. }
  10580.  
  10581. /*  C O N G M  --  Get console terminal modes.  */
  10582.  
  10583. /*
  10584.   Saves initial console mode, and establishes variables for switching
  10585.   between current (presumably normal) mode and other modes.
  10586.   Should be called when program starts, but only after establishing
  10587.   whether program is in the foreground or background.
  10588.   Returns 1 if it got the modes OK, 0 if it did nothing, -1 on error.
  10589. */
  10590. int
  10591. congm() {
  10592.     int fd;
  10593.     if (backgrd || !isatty(0)) {    /* If in background. */
  10594.     cgmf = -1;            /* Don't bother, modes are garbage. */
  10595.     return(-1);
  10596.     }
  10597.     if (cgmf > 0) return(0);        /* Already did this. */
  10598.     debug(F100,"congm getting modes","",0); /* Need to do it. */
  10599. #ifdef aegis
  10600.     ios_$inq_type_uid(ios_$stdin, conuid, st);
  10601.     if (st.all != status_$ok) {
  10602.     fprintf(stderr, "problem getting stdin objtype: ");
  10603.     error_$print(st);
  10604.     }
  10605.     concrp = (conuid == mbx_$uid);
  10606.     conbufn = 0;
  10607. #endif /* aegis */
  10608.  
  10609. #ifndef BEBOX
  10610.     if ((fd = open(CTTNAM,2)) < 0) {    /* Open controlling terminal */
  10611. #ifdef COMMENT
  10612.     fprintf(stderr,"Error opening %s\n", CTTNAM);
  10613.     perror("congm");
  10614.     return(-1);
  10615. #else
  10616.     fd = 0;
  10617. #endif /* COMMENT */
  10618.     }
  10619. #else
  10620.     fd = 0;
  10621. #endif /* !BEBOX */
  10622. #ifdef BSD44ORPOSIX
  10623.     if (tcgetattr(fd,&ccold) < 0) return(-1);
  10624.     if (tcgetattr(fd,&cccbrk) < 0) return(-1);
  10625.     if (tcgetattr(fd,&ccraw) < 0) return(-1);
  10626. #else
  10627. #ifdef ATTSV
  10628.     if (ioctl(fd,TCGETA,&ccold)  < 0) return(-1);
  10629.     if (ioctl(fd,TCGETA,&cccbrk) < 0) return(-1);
  10630.     if (ioctl(fd,TCGETA,&ccraw)  < 0) return(-1);
  10631. #ifdef VXVE
  10632.     cccbrk.c_line = 0;            /* STTY line 0 for CDC VX/VE */
  10633.     if (ioctl(fd,TCSETA,&cccbrk) < 0) return(-1);
  10634.     ccraw.c_line = 0;            /* STTY line 0 for CDC VX/VE */
  10635.     if (ioctl(fd,TCSETA,&ccraw) < 0) return(-1);
  10636. #endif /* VXVE */
  10637. #else
  10638. #ifdef BELLV10
  10639.     if (ioctl(fd,TIOCGETP,&ccold) < 0) return(-1);
  10640.     if (ioctl(fd,TIOCGETP,&cccbrk) < 0) return(-1);
  10641.     if (ioctl(fd,TIOCGETP,&ccraw) < 0) return(-1);
  10642.     debug(F101,"cccbrk.sg_flags orig","", cccbrk.sg_flags);
  10643. #else
  10644.     if (gtty(fd,&ccold) < 0) return(-1);
  10645.     if (gtty(fd,&cccbrk) < 0) return(-1);
  10646.     if (gtty(fd,&ccraw) < 0) return(-1);
  10647. #endif /* BELLV10 */
  10648. #endif /* ATTSV */
  10649. #endif /* BSD44ORPOSIX */
  10650. #ifdef sony_news            /* Sony NEWS */
  10651.     if (ioctl(fd,TIOCKGET,&km_con) < 0) { /* Get console Kanji mode */
  10652.     perror("congm error getting Kanji mode");
  10653.     debug(F101,"congm error getting Kanji mode","",0);
  10654.     km_con = -1;            /* Make sure this stays undefined. */
  10655.     return(-1);
  10656.     }
  10657. #endif /* sony_news */
  10658.     if (fd > 0)
  10659.       close(fd);
  10660.     cgmf = 1;                /* Flag that we got them. */
  10661.     return(1);
  10662. }
  10663.  
  10664.  
  10665. /*  C O N C B --  Put console in cbreak mode.  */
  10666.  
  10667. /*  Returns 0 if ok, -1 if not  */
  10668.  
  10669. int
  10670. #ifdef CK_ANSIC
  10671. concb(char esc)
  10672. #else
  10673. concb(esc) char esc;
  10674. #endif /* CK_ANSIC */
  10675. /* concb */ {
  10676.     int x;
  10677.     debug(F101,"concb cgmf","",cgmf);
  10678.     debug(F101,"concb backgrd","",backgrd);
  10679.  
  10680.     if (cgmf < 1)            /* Did we get console modes yet? */
  10681.       if (!backgrd)            /* No, in background? */
  10682.     congm();            /* No, try to get them now. */
  10683.     if (cgmf < 1)            /* Still don't have them? */
  10684.       return(0);            /* Give up. */
  10685.     debug(F101,"concb ttyfd","",ttyfd);
  10686.     debug(F101,"concb ttfdflg","",ttfdflg);
  10687. #ifdef COMMENT
  10688.     /* This breaks returning to prompt after protocol with "-l 0" */
  10689.     /* Commented out July 1998 */
  10690.     if (ttfdflg && ttyfd >= 0 && ttyfd < 3)
  10691.       return(0);
  10692. #endif /* COMMENT */
  10693.     x = isatty(0);
  10694.     debug(F101,"concb isatty","",x);
  10695.     if (!x) return(0);            /* Only when running on real ttys */
  10696.     debug(F101,"concb suspend","",suspend);
  10697.     if (backgrd) return(0);        /* Do nothing if in background. */
  10698.     escchr = esc;                       /* Make this available to other fns */
  10699.     ckxech = 1;                         /* Program can echo characters */
  10700. #ifdef aegis
  10701.     conbufn = 0;
  10702.     if (concrp) return(write(1, "\035\002", 2));
  10703.     if (conuid == input_pad_$uid) {pad_$raw(ios_$stdin, st); return(0);}
  10704. #endif /* aegis */
  10705.  
  10706. #ifdef COHERENT
  10707. #define SVORPOSIX
  10708. #endif /* COHERENT */
  10709.  
  10710. #ifdef Plan9
  10711.     x = p9concb();
  10712. #else
  10713. #ifndef SVORPOSIX            /* BSD, V7, etc */
  10714.     debug(F101,"cccbrk.sg_flags concb 1","", cccbrk.sg_flags);
  10715.     debug(F101,"concb stty CBREAK","",0);
  10716.     cccbrk.sg_flags |= (CBREAK|CRMOD);    /* Set to character wakeup, */
  10717.     cccbrk.sg_flags &= ~ECHO;           /* no echo. */
  10718.     debug(F101,"cccbrk.sg_flags concb 2","", cccbrk.sg_flags);
  10719. #ifdef BELLV10
  10720.     x = ioctl(0,TIOCSETP,&cccbrk);
  10721. #else
  10722.     x = stty(0,&cccbrk);
  10723.     debug(F101,"cccbrk.sg_flags concb x","", x);
  10724. #endif /* BELLV10 */
  10725. #else                    /* Sys V and POSIX */
  10726. #ifndef OXOS
  10727.     debug(F101,"concb cccbrk.c_flag","",cccbrk.c_lflag);
  10728. #ifdef QNX
  10729.     /* Don't mess with IEXTEN */
  10730.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  10731. #else
  10732. #ifdef COHERENT
  10733.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  10734. #else
  10735.     cccbrk.c_lflag &= ~(ICANON|ECHO|IEXTEN);
  10736. #endif /* COHERENT */
  10737. #endif /* QNX */
  10738.     cccbrk.c_lflag |= ISIG;        /* Allow signals in command mode. */
  10739.     cccbrk.c_iflag |= IGNBRK;        /* But ignore BREAK signal */
  10740.     cccbrk.c_iflag &= ~BRKINT;
  10741.  
  10742. #else /* OXOS */
  10743.     debug(F100,"concb OXOS is defined","",0);
  10744.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  10745.     cccbrk.c_cc[VDISCARD] = cccbrk.c_cc[VLNEXT] = CDISABLE;
  10746. #endif /* OXOS */
  10747. #ifdef COMMENT
  10748. /*
  10749.   Believe it or not, in SCO UNIX, VSUSP is greater than NCC, and so this
  10750.   array reference is out of bounds.  It's only a debug() call so who needs it.
  10751. */
  10752. #ifdef VSUSP
  10753.     debug(F101,"concb c_cc[VSUSP]","",cccbrk.c_cc[VSUSP]);
  10754. #endif /* VSUSP */
  10755. #endif /* COMMENT */
  10756. #ifndef VINTR
  10757.     debug(F101,"concb c_cc[0]","",cccbrk.c_cc[0]);
  10758.     cccbrk.c_cc[0] = 003;               /* Interrupt char is Control-C */
  10759. #else
  10760.     debug(F101,"concb c_cc[VINTR]","",cccbrk.c_cc[0]);
  10761.     cccbrk.c_cc[VINTR] = 003;
  10762. #endif /* VINTR */
  10763. #ifndef VQUIT
  10764.     cccbrk.c_cc[1] = escchr;            /* escape during packet modes */
  10765. #else
  10766.     cccbrk.c_cc[VQUIT] = escchr;
  10767. #endif /* VQUIT */
  10768. #ifndef VEOF
  10769.     cccbrk.c_cc[4] = 1;
  10770. #else
  10771. #ifndef OXOS
  10772. #ifdef VMIN
  10773.     cccbrk.c_cc[VMIN] = 1;
  10774. #endif /* VMIN */
  10775. #else /* OXOS */
  10776.     cccbrk.c_min = 1;
  10777. #endif /* OXOS */
  10778. #endif /* VEOF */
  10779. #ifdef ZILOG
  10780.     cccbrk.c_cc[5] = 0;
  10781. #else
  10782. #ifndef VEOL
  10783.     cccbrk.c_cc[5] = 1;
  10784. #else
  10785. #ifndef OXOS
  10786. #ifdef VTIME
  10787.     cccbrk.c_cc[VTIME] = 1;
  10788. #endif /* VTIME */
  10789. #else /* OXOS */
  10790.     cccbrk.c_time = 1;
  10791. #endif /* OXOS */
  10792. #endif /* VEOL */
  10793. #endif /* ZILOG */
  10794. #ifdef BSD44ORPOSIX            /* Set new modes */
  10795.     x = tcsetattr(0,TCSADRAIN,&cccbrk);
  10796. #else /* ATTSV */                  /* or the POSIX way */
  10797.     x = ioctl(0,TCSETAW,&cccbrk);    /* the Sys V way */
  10798. #endif /* BSD44ORPOSIX */
  10799. #endif /* SVORPOSIX */
  10800.  
  10801. #ifdef COHERENT
  10802. #undef SVORPOSIX
  10803. #endif /* COHERENT */
  10804.  
  10805. #ifndef aegis
  10806. #ifndef NOSETBUF
  10807.     if (x > -1) setbuf(stdout,NULL);    /* Make console unbuffered. */
  10808. #endif /* NOSETBUF */
  10809. #endif /* aegis */
  10810.  
  10811. #ifdef  V7
  10812. #ifndef MINIX
  10813.     if (kmem[CON] < 0) {
  10814.         qaddr[CON] = initrawq(0);
  10815.         if((kmem[CON] = open("/dev/kmem", 0)) < 0) {
  10816.             fprintf(stderr, "Can't read /dev/kmem in concb.\n");
  10817.             perror("/dev/kmem");
  10818.             exit(1);
  10819.         }
  10820.     }
  10821. #endif /* MINIX */
  10822. #endif /* V7 */
  10823. #endif /* Plan9 */
  10824.     debug(F101,"concb returns","",x);
  10825.     return(x);
  10826. }
  10827.  
  10828. /*  C O N B I N  --  Put console in binary mode  */
  10829.  
  10830. /*  Returns 0 if ok, -1 if not  */
  10831.  
  10832. int
  10833. #ifdef CK_ANSIC
  10834. conbin(char esc)
  10835. #else
  10836. conbin(esc) char esc;
  10837. #endif /* CK_ANSIC */
  10838. /* conbin */  {
  10839.  
  10840.     if (!isatty(0)) return(0);          /* only for real ttys */
  10841.     congm();                /* Get modes if necessary. */
  10842.     debug(F100,"conbin","",0);
  10843.     escchr = esc;                       /* Make this available to other fns */
  10844.     ckxech = 1;                         /* Program can echo characters */
  10845. #ifdef aegis
  10846.     conbufn = 0;
  10847.     if (concrp) return(write(1, "\035\002", 2));
  10848.     if (conuid == input_pad_$uid) {
  10849.     pad_$raw(ios_$stdin, st);
  10850.     return(0);
  10851.       }
  10852. #endif /* aegis */
  10853.  
  10854. #ifdef COHERENT
  10855. #define SVORPOSIX
  10856. #endif /* COHERENT */
  10857.  
  10858. #ifdef Plan9
  10859.     return p9conbin();
  10860. #else
  10861. #ifdef SVORPOSIX
  10862. #ifndef OXOS
  10863. #ifdef QNX
  10864.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  10865. #else
  10866. #ifdef COHERENT
  10867.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  10868. #else
  10869.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO|IEXTEN);
  10870. #endif /* COHERENT */
  10871. #endif /* QNX */
  10872. #else /* OXOS */
  10873.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  10874.     ccraw.c_cc[VDISCARD] = ccraw.c_cc[VLNEXT] = CDISABLE;
  10875. #endif /* OXOS */
  10876.     ccraw.c_iflag |= IGNPAR;
  10877. /*
  10878.   Note that for terminal sessions we disable Xon/Xoff flow control to allow
  10879.   the passage ^Q and ^S as data characters for EMACS, and to allow XMODEM
  10880.   transfers to work when C-Kermit is in the middle, etc.  Hardware flow
  10881.   control, if in use, is not affected.
  10882. */
  10883. #ifdef ATTSV
  10884. #ifdef BSD44
  10885.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IXON|IXANY|IXOFF
  10886.                         |INPCK|ISTRIP);
  10887. #else
  10888.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IUCLC|IXON|IXANY|IXOFF
  10889.                         |INPCK|ISTRIP);
  10890. #endif /* BSD44 */
  10891. #else /* POSIX */
  10892.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IXON|IXOFF|INPCK|ISTRIP);
  10893. #endif /* ATTSV */
  10894.     ccraw.c_oflag &= ~OPOST;
  10895. #ifdef COMMENT
  10896. /*
  10897.   WHAT THE HECK WAS THIS FOR?
  10898.   The B9600 setting (obviously) prevents CONNECT from working at any
  10899.   speed other than 9600 when you are logged in to the 7300 on a serial
  10900.   line.  Maybe some of the other flags are necessary -- if so, put back
  10901.   the ones that are needed.  This code is supposed to work the same, no
  10902.   matter whether you are logged in to the 7300 on the real console device,
  10903.   or through a serial port.
  10904. */
  10905. #ifdef ATT7300
  10906.     ccraw.c_cflag = CLOCAL | B9600 | CS8 | CREAD | HUPCL;
  10907. #endif /* ATT7300 */
  10908. #endif /* COMMENT */
  10909.  
  10910. /*** Kermit used to put the console in 8-bit raw mode, but some users have
  10911.  *** pointed out that this should not be done, since some sites actually
  10912.  *** use terminals with parity settings on their Unix systems, and if we
  10913.  *** override the current settings and stop doing parity, then their terminals
  10914.  *** will display blotches for characters whose parity is wrong.  Therefore,
  10915.  *** the following two lines are commented out (Larry Afrin, Clemson U):
  10916.  ***
  10917.  ***   ccraw.c_cflag &= ~(PARENB|CSIZE);
  10918.  ***   ccraw.c_cflag |= (CS8|CREAD);
  10919.  ***
  10920.  *** Sys III/V sites that have trouble with this can restore these lines.
  10921.  ***/
  10922. #ifndef VINTR
  10923.     ccraw.c_cc[0] = 003;        /* Interrupt char is Ctrl-C */
  10924. #else
  10925.     ccraw.c_cc[VINTR] = 003;
  10926. #endif /* VINTR */
  10927. #ifndef VQUIT
  10928.     ccraw.c_cc[1] = escchr;        /* Escape during packet mode */
  10929. #else
  10930.     ccraw.c_cc[VQUIT] = escchr;
  10931. #endif /* VQUIT */
  10932. #ifndef VEOF
  10933.     ccraw.c_cc[4] = 1;
  10934. #else
  10935. #ifndef OXOS
  10936. #ifdef VMIN
  10937.     ccraw.c_cc[VMIN] = 1;
  10938. #endif /* VMIN */
  10939. #else /* OXOS */
  10940.     ccraw.c_min = 1;
  10941. #endif /* OXOS */
  10942. #endif /* VEOF */
  10943.  
  10944. #ifdef ZILOG
  10945.     ccraw.c_cc[5] = 0;
  10946. #else
  10947. #ifndef VEOL
  10948.     ccraw.c_cc[5] = 1;
  10949. #else
  10950. #ifndef OXOS
  10951. #ifdef VTIME
  10952.     ccraw.c_cc[VTIME] = 1;
  10953. #endif /* VTIME */
  10954. #else /* OXOS */
  10955.     ccraw.c_time = 1;
  10956. #endif /* OXOS */
  10957. #endif /* VEOL */
  10958. #endif /* ZILOG */
  10959.  
  10960. #ifdef BSD44ORPOSIX
  10961.     return(tcsetattr(0,TCSADRAIN,&ccraw));
  10962. #else
  10963.     return(ioctl(0,TCSETAW,&ccraw));    /* Set new modes. */
  10964. #endif /* BSD44ORPOSIX */
  10965.  
  10966. #else /* Berkeley, etc. */
  10967.     ccraw.sg_flags |= (RAW|TANDEM);     /* Set rawmode, XON/XOFF (ha) */
  10968.     ccraw.sg_flags &= ~(ECHO|CRMOD);    /* Set char wakeup, no echo */
  10969. #ifdef BELLV10
  10970.     return(ioctl(0,TIOCSETP,&ccraw));
  10971. #else
  10972.     return(stty(0,&ccraw));
  10973. #endif /* BELLV10 */
  10974. #endif /* SVORPOSIX */
  10975. #endif /* Plan9 */
  10976.  
  10977. #ifdef COHERENT
  10978. #undef SVORPOSIX
  10979. #endif /* COHERENT */
  10980.  
  10981. }
  10982.  
  10983.  
  10984. /*  C O N R E S  --  Restore the console terminal  */
  10985.  
  10986. int
  10987. conres() {
  10988.     debug(F101,"conres cgmf","",cgmf);
  10989.  
  10990.     if (cgmf < 1) return(0);        /* Do nothing if modes unchanged */
  10991.     if (!isatty(0)) return(0);          /* only for real ttys */
  10992.     debug(F100,"conres isatty ok","",0);
  10993.     ckxech = 0;                         /* System should echo chars */
  10994.  
  10995. #ifdef aegis
  10996.     conbufn = 0;
  10997.     if (concrp) return(write(1, "\035\001", 2));
  10998.     if (conuid == input_pad_$uid) {
  10999.     pad_$cooked(ios_$stdin, st);
  11000.     return(0);
  11001.     }
  11002. #endif /* aegis */
  11003.  
  11004. #ifdef Plan9
  11005.     p9conres();
  11006. #else
  11007. #ifdef BSD44ORPOSIX
  11008.     debug(F100,"conres restoring tcsetattr","",0);
  11009.     return(tcsetattr(0,TCSADRAIN,&ccold));
  11010. #else
  11011. #ifdef ATTSV
  11012.     debug(F100,"conres restoring ioctl","",0);
  11013.     return(ioctl(0,TCSETAW,&ccold));
  11014. #else /* BSD, V7, and friends */
  11015. #ifdef sony_news            /* Sony NEWS */
  11016.     if (km_con != -1)
  11017.       ioctl(0,TIOCKSET,&km_con);    /* Restore console Kanji mode */
  11018. #endif /* sony_news */
  11019.     msleep(100);
  11020.     debug(F100,"conres restoring stty","",0);
  11021. #ifdef BELLV10
  11022.     return(ioctl(0,TIOCSETP,&ccold));
  11023. #else
  11024.     return(stty(0,&ccold));
  11025. #endif /* BELLV10 */
  11026. #endif /* ATTSV */
  11027. #endif /* BSD44ORPOSIX */
  11028. #endif /* Plan9 */
  11029. }
  11030.  
  11031. /*  C O N O C  --  Output a character to the console terminal  */
  11032.  
  11033. int
  11034. #ifdef CK_ANSIC
  11035. conoc(char c)
  11036. #else
  11037. conoc(c) char c;
  11038. #endif /* CK_ANSIC */
  11039. /* conoc */ {
  11040.  
  11041. #ifdef IKSD
  11042.     if (inserver && !local)
  11043.       return(ttoc(c));
  11044.  
  11045. #ifdef CK_ENCRYPTION
  11046.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  11047.         ck_tn_encrypt(&c,1);
  11048. #endif /* CK_ENCRYPTION */
  11049. #endif /* IKSD */
  11050.  
  11051. #ifdef Plan9
  11052.     return conwrite(&c,1);
  11053. #else
  11054.     return(write(1,&c,1));
  11055. #endif /* Plan9 */
  11056. }
  11057.  
  11058. /*  C O N X O  --  Write x characters to the console terminal  */
  11059.  
  11060. int
  11061. conxo(x,s) int x; char *s; {
  11062.  
  11063. #ifdef IKSD
  11064.     if (inserver && !local)
  11065.       return(ttol((CHAR *)s,x));
  11066.  
  11067. #ifdef CK_ENCRYPTION
  11068.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  11069.         ck_tn_encrypt(s,x);
  11070. #endif /* CK_ENCRYPTION */
  11071. #endif /* IKSD */
  11072.  
  11073. #ifdef Plan9
  11074.     return(conwrite(s,x));
  11075. #else
  11076.     return(write(1,s,x));
  11077. #endif /* Plan9 */
  11078. }
  11079.  
  11080. /*  C O N O L  --  Write a line to the console terminal  */
  11081.  
  11082. int
  11083. conol(s) char *s; {
  11084.     int len;
  11085.     if (!s) s = "";            /* Always do this! */
  11086.     len = strlen(s);
  11087.  
  11088. #ifdef IKSD
  11089.     if (inserver && !local)
  11090.       return(ttol((CHAR *)s,len));
  11091.  
  11092. #ifdef CK_ENCRYPTION
  11093.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION)) {
  11094.     if (nxpacket < len) {
  11095.         if (xpacket) {
  11096.         free(xpacket);
  11097.         xpacket = NULL;
  11098.         nxpacket = 0;
  11099.         }
  11100.         len = len > 10240 ? len : 10240;
  11101.         xpacket = (char *)malloc(len);
  11102.         if (!xpacket) {
  11103.         fprintf(stderr,"ttol malloc failure\n");
  11104.         return(-1);
  11105.         } else
  11106.           nxpacket = len;
  11107.     }
  11108.     memcpy(xpacket,s,len);
  11109.     s = xpacket;
  11110.     ck_tn_encrypt(s,len);
  11111.     }
  11112. #endif /* CK_ENCRYPTION */
  11113. #endif /* IKSD */
  11114.  
  11115. #ifdef Plan9
  11116.     return(conwrite(s,len));
  11117. #else
  11118.     return(write(1,s,len));
  11119. #endif /* Plan9 */
  11120. }
  11121.  
  11122. /*  C O N O L A  --  Write an array of lines to the console terminal */
  11123.  
  11124. int
  11125. conola(s) char *s[]; {
  11126.     char * p;
  11127.     int i, x;
  11128.  
  11129.  
  11130.     if (!s) return(0);
  11131.     for (i = 0; ; i++) {
  11132.     p = s[i];
  11133.     if (!p) p = "";            /* Let's not dump core shall we? */
  11134.     if (!*p)
  11135.       break;
  11136. #ifdef IKSD
  11137.     if (inserver && !local)
  11138.       x = ttol((CHAR *)p,(int)strlen(p));
  11139.     else
  11140. #endif /* IKSD */
  11141.       x = conol(p);
  11142.     if (x < 0)
  11143.       return(-1);
  11144.     }
  11145.     return(0);
  11146. }
  11147.  
  11148. /*  C O N O L L  --  Output a string followed by CRLF  */
  11149.  
  11150. int
  11151. conoll(s) char *s; {
  11152.     CHAR buf[3];
  11153.     buf[0] = '\r';
  11154.     buf[1] = '\n';
  11155.     buf[2] = '\0';
  11156.     if (!s) s = "";
  11157.  
  11158. #ifdef IKSD
  11159.     if (inserver && !local) {
  11160.     ttol((CHAR *)s,(int)strlen(s));
  11161.     return(ttol(buf,2));
  11162.     }
  11163. #endif /* IKSD */
  11164.  
  11165.     conol(s);
  11166. #ifdef IKSD
  11167. #ifdef CK_ENCRYPTION
  11168.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  11169.       ck_tn_encrypt(buf,2);
  11170. #endif /* CK_ENCRYPTION */
  11171. #endif /* IKSD */
  11172.  
  11173. #ifdef Plan9
  11174.     return(conwrite(buf, 2));
  11175. #else
  11176.     return(write(1,buf,2));
  11177. #endif /* Plan9 */
  11178. }
  11179.  
  11180. /*  C O N C H K  --  Return how many characters available at console  */
  11181. /*
  11182.   We could also use select() here to cover a few more systems that are not
  11183.   covered by any of the following, e.g. HP-UX 9.0x on the model 800.
  11184. */
  11185. int
  11186. conchk() {
  11187.     static int contyp = 0;        /* +1 for isatty, -1 otherwise */
  11188.  
  11189.     if (contyp == 0)            /* This prevents unnecessary */
  11190.       contyp = (isatty(0) ? 1 : -1);    /* duplicated calls to isatty() */
  11191.     debug(F101,"conchk contyp","",contyp);
  11192.     if (backgrd || (contyp < 0))
  11193.       return(0);
  11194.  
  11195. #ifdef aegis
  11196.     if (conbufn > 0) return(conbufn);   /* use old count if nonzero */
  11197.  
  11198.     /* read in more characters */
  11199.     conbufn = ios_$get(ios_$stdin,
  11200.               ios_$cond_opt, conbuf, (long)sizeof(conbuf), st);
  11201.     if (st.all != status_$ok) conbufn = 0;
  11202.     conbufp = conbuf;
  11203.     return(conbufn);
  11204. #else
  11205. #ifdef IKSD
  11206.     if (inserver && !local)
  11207.       return(in_chk(1,ttyfd));
  11208.     else
  11209. #endif /* IKSD */
  11210.       return(in_chk(0,0));
  11211. #endif /* aegis */
  11212. }
  11213.  
  11214. /*  C O N I N C  --  Get a character from the console  */
  11215. /*
  11216.   Call with timo > 0 to do a timed read, timo == 0 to do an untimed blocking
  11217.   read.  Upon success, returns the character.  Upon failure, returns -1.
  11218.   A timed read that does not complete within the timeout period returns -2.
  11219. */
  11220. int
  11221. coninc(timo) int timo; {
  11222.     int n = 0; CHAR ch;
  11223.     int xx;
  11224.  
  11225.     errno = 0;                /* Clear this */
  11226. #ifdef IKSD
  11227.     if (inserver && !local) {
  11228.     xx = ttinc(timo);
  11229.     if (xx < 0)
  11230.       return(ttinctimo ? -2 : -1);
  11231.     else
  11232.       return(xx);
  11233.     }
  11234. #endif /* IKSD */
  11235.  
  11236. #ifdef aegis                /* Apollo Aegis only... */
  11237.     debug(F101,"coninc timo","",timo);
  11238.     fflush(stdout);
  11239.     if (conchk() > 0) {
  11240.     --conbufn;
  11241.     return((unsigned)(*conbufp++ & 0xff));
  11242.     }
  11243. #endif /* aegis */
  11244.  
  11245. #ifdef TTLEBUF
  11246.     if (
  11247. #ifdef IKSD
  11248.     inserver &&
  11249. #endif /* IKSD */
  11250.     !xlocal
  11251.     ) {
  11252.     if (ttpush >= 0) {
  11253.         debug(F111,"ttinc","ttpush",ttpush);
  11254.         ch = ttpush;
  11255.         ttpush = -1;
  11256.         return(ch);
  11257.     }
  11258.     if (le_data) {
  11259.         if (le_getchar(&ch) > 0) {
  11260.         debug(F111,"ttinc LocalEchoInBuf","ch",ch);
  11261.         return(ch);
  11262.         }
  11263.     }
  11264.     }
  11265. #endif /* TTLEBUF */
  11266.  
  11267.     if (timo <= 0) {            /* Untimed, blocking read. */
  11268.     while (1) {            /* Keep trying till we get one. */
  11269.         n = read(0, &ch, 1);    /* Read a character. */
  11270.         if (n == 0) continue;    /* Shouldn't happen. */
  11271.         if (n > 0) {        /* If read was successful, */
  11272. #ifdef IKSD
  11273. #ifdef CK_ENCRYPTION
  11274.                 debug(F100,"coninc decrypt 1","",0);
  11275.                 if (inserver && !local && TELOPT_U(TELOPT_ENCRYPTION))
  11276.           ck_tn_decrypt(&ch,1);
  11277. #endif /* CK_ENCRYPTION */
  11278. #endif /* IKSD */
  11279.         return((unsigned)(ch & 0xff)); /* return the character. */
  11280.             }
  11281.  
  11282. /* Come here if read() returned an error. */
  11283.  
  11284.         debug(F101, "coninc(0) errno","",errno); /* Log the error. */
  11285. #ifndef OXOS
  11286. #ifdef SVORPOSIX
  11287. #ifdef CIE                             /* CIE Regulus has no EINTR symbol? */
  11288. #ifndef EINTR
  11289. #define EINTR 4
  11290. #endif /* EINTR */
  11291. #endif /* CIE */
  11292. /*
  11293.   This routine is used for several different purposes.  In CONNECT mode, it is
  11294.   used to do an untimed, blocking read from the keyboard in the lower CONNECT
  11295.   fork.  During local-mode file transfer, it reads a character from the
  11296.   console to interrupt the file transfer (like A for a status report, X to
  11297.   cancel a file, etc).  Obviously, we don't want the reads in the latter case
  11298.   to be blocking, or the file transfer would stop until the user typed
  11299.   something.  Unfortunately, System V does not allow the console device input
  11300.   buffer to be sampled nondestructively (e.g. by conchk()), so a kludge is
  11301.   used instead.  During local-mode file transfer, the SIGQUIT signal is armed
  11302.   and trapped by esctrp(), and this routine pretends to have read the quit
  11303.   character from the keyboard normally.  But, kludge or no kludge, the read()
  11304.   issued by this command, under System V only, can fail if a signal -- ANY
  11305.   signal -- is caught while the read is pending.  This can occur not only when
  11306.   the user types the quit character, but also during telnet negotiations, when
  11307.   the lower CONNECT fork signals the upper one about an echoing mode change.
  11308.   When this happens, we have to post the read() again.  This is apparently not
  11309.   a problem in BSD-based UNIX versions.
  11310. */
  11311.         if (errno == EINTR)        /* Read interrupted. */
  11312.           if (conesc)  {        /* If by SIGQUIT, */
  11313.           conesc = 0;        /* the conesc variable is set, */
  11314.           return(escchr);    /* so return the escape character. */
  11315.          } else continue;        /* By other signal, try again. */
  11316. #else
  11317. /*
  11318.   This might be dangerous, but let's do this on non-System V versions too,
  11319.   since at least one SunOS 4.1.2 user complains of immediate disconnections
  11320.   upon first making a TELNET connection.
  11321. */
  11322.         if (errno == EINTR)        /* Read interrupted. */
  11323.           continue;
  11324. #endif /* SVORPOSIX */
  11325. #else /* OXOS */
  11326.         if (errno == EINTR)        /* Read interrupted. */
  11327.           continue;
  11328. #endif /* OXOS */
  11329.         return(-1);            /* Error */
  11330.     }
  11331.     }
  11332. #ifdef DEBUG
  11333.     if (deblog && timo <= 0) {
  11334.     debug(F100,"coninc timeout logic error","",0);
  11335.     timo = 1;
  11336.     }
  11337. #endif /* DEBUG */
  11338.  
  11339. /* Timed read... */
  11340.  
  11341.     saval = signal(SIGALRM,timerh);    /* Set up timeout handler. */
  11342.     xx = alarm(timo);            /* Set the alarm. */
  11343.     debug(F101,"coninc alarm set","",timo);
  11344.     if (
  11345. #ifdef CK_POSIX_SIG
  11346.     sigsetjmp(sjbuf,1)
  11347. #else
  11348.     setjmp(sjbuf)
  11349. #endif /* CK_POSIX_SIG */
  11350.     )                /* The read() timed out. */
  11351.       n = -2;                /* Code for timeout. */
  11352.     else
  11353.       n = read(0, &ch, 1);
  11354.     ttimoff();                /* Turn off timer */
  11355.     if (n > 0) {            /* Got character OK. */
  11356. #ifdef IKSD
  11357. #ifdef CK_ENCRYPTION
  11358.         debug(F100,"coninc decrypt 2","",0);
  11359.         if (inserver && !local && TELOPT_U(TELOPT_ENCRYPTION))
  11360.       ck_tn_decrypt(&ch,1);
  11361. #endif /* CK_ENCRYPTION */
  11362. #endif /* IKSD */
  11363.     return((unsigned)(ch & 0xff));    /* Return it. */
  11364.     }
  11365. /*
  11366.   read() returned an error.  Same deal as above, but without the loop.
  11367. */
  11368.     debug(F101, "coninc(timo) n","",n);
  11369.     debug(F101, "coninc(timo) errno","",errno);
  11370. #ifndef OXOS
  11371. #ifdef SVORPOSIX
  11372.     if (n == -1 && errno == EINTR && conesc != 0) {
  11373.     conesc = 0;
  11374.     return(escchr);            /* User entered escape character. */
  11375.     }
  11376. #endif /* SVORPOSIX */
  11377.     if (n == 0 && errno > 0) {        /* It's an error */
  11378.     return(-1);
  11379.     }
  11380. #endif /* ! OXOS */
  11381.     return(n);
  11382. }
  11383.  
  11384. /*  C O N G K S  --  Console Get Keyboard Scancode  */
  11385.  
  11386. #ifndef congks
  11387. /*
  11388.   This function needs to be filled in with the various system-dependent
  11389.   system calls used by SUNOS, NeXT OS, Xenix, Aviion, etc, to read a full
  11390.   keyboard scan code.  For now, it's a dummy.
  11391. */
  11392. int
  11393. congks(timo) int timo; {
  11394.  
  11395. #ifdef IKSD
  11396.     if (inserver && !local)
  11397.       return(ttinc(timo));
  11398. #endif /* IKSD */
  11399.  
  11400.     return(coninc(timo));
  11401. }
  11402. #endif /* congks */
  11403.  
  11404. #ifdef ATT7300
  11405.  
  11406. /*  A T T D I A L  --  Dial up the remote system using internal modem
  11407.  * Purpose: to open and dial a number on the internal modem available on the
  11408.  * ATT7300 UNIX PC.  Written by Joe Doupnik. Superceeds version written by
  11409.  * Richard E. Hill, Dickinson, TX. which employed dial(3c).
  11410.  * Uses information in <sys/phone.h> and our status int attmodem.
  11411.  */
  11412. attdial(ttname,speed,telnbr) char *ttname,*telnbr; long speed; {
  11413.     char *telnum;
  11414.  
  11415.     attmodem &= ~ISMODEM;                       /* modem not in use yet */
  11416.                     /* Ensure O_NDELAY is set, else i/o traffic hangs */
  11417.                     /* We turn this flag off once the dial is complete */
  11418.     fcntl(ttyfd, F_SETFL, fcntl(ttyfd, F_GETFL, 0) | O_NDELAY);
  11419.  
  11420.     /* Condition line, check availability & DATA mode, turn on speaker */
  11421.     if (ioctl(ttyfd,PIOCOFFHOOK, &dialer) == -1) {
  11422.         printf("cannot access phone\n");
  11423.         ttclos(0);
  11424.         return (-2);
  11425.     }
  11426.     ioctl(ttyfd,PIOCGETP,&dialer);      /* get phone dialer parameters */
  11427.  
  11428.     if (dialer.c_lineparam & VOICE) {    /* phone must be in DATA mode */
  11429.         printf(" Should not dial with modem in VOICE mode.\n");
  11430.         printf(" Exit Kermit, switch to DATA and retry call.\n");
  11431.         ttclos(0);
  11432.         return (-2);
  11433.     }
  11434. #ifdef ATTTONED                /* Old way, tone dialing only. */
  11435.     dialer.c_lineparam = DATA | DTMF;    /* Dial with tones, */
  11436.     dialer.c_lineparam &= ~PULSE;    /* not with pulses. */
  11437. #else
  11438.     /* Leave current pulse/tone state alone. */
  11439.     /* But what about DATA?  Add it back if you have trouble. */
  11440.     /* sys/phone says you get DATA automatically by opening device RDWR */
  11441. #endif
  11442.     dialer.c_waitdialtone = 5;                  /* wait 5 sec for dialtone */
  11443. #ifdef COMMENT
  11444.     dialer.c_feedback = SPEAKERON|NORMSPK|RINGON;  /* control speaker */
  11445. #else
  11446.     /* sys/phone says RINGON used only for incoming voice calls */
  11447.     dialer.c_feedback &= ~(SOFTSPK|LOUDSPK);
  11448.     dialer.c_feedback |= SPEAKERON|NORMSPK;
  11449. #endif
  11450.     dialer.c_waitflash = 500;                   /* 0.5 sec flash hook */
  11451.     if(ioctl(ttyfd,PIOCSETP,&dialer) == -1) {   /* set phone parameters */
  11452.         printf("Cannot set modem characteristics\n");
  11453.         ttclos(0);
  11454.         return (-2);
  11455.     }
  11456.     ioctl(ttyfd,PIOCRECONN,0);        /* Turns on speaker for pulse */
  11457.  
  11458. #ifdef COMMENT
  11459.     fprintf(stderr,"Phone line status. line_par:%o dialtone_wait:%o \
  11460. line_status:%o feedback:%o\n",
  11461.     dialer.c_lineparam, dialer.c_waitdialtone,
  11462.     dialer.c_linestatus, dialer.c_feedback);
  11463. #endif
  11464.  
  11465.     attmodem |= ISMODEM;                        /* modem is now in-use */
  11466.     sleep(1);
  11467.     for (telnum = telnbr; *telnum != '\0'; telnum++)    /* dial number */
  11468. #ifdef ATTTONED
  11469.       /* Tone dialing only */
  11470.       if (ioctl(ttyfd,PIOCDIAL,telnum) != 0) {
  11471.       perror("Error in dialing");
  11472.       ttclos(0);
  11473.       return(-2);
  11474.       }
  11475. #else /* Allow Pulse or Tone dialing */
  11476.     switch (*telnum) {
  11477.       case 't': case 'T': case '%':    /* Tone dialing requested */
  11478.     dialer.c_lineparam |= DTMF;
  11479.     dialer.c_lineparam &= ~PULSE;
  11480.     if (ioctl(ttyfd,PIOCSETP,&dialer) == -1) {
  11481.         printf("Cannot set modem to tone dialing\n");
  11482.         ttclos(0);
  11483.         return(-2);
  11484.     }
  11485.     break;
  11486.       case 'd': case 'D': case 'p': case 'P': case '^':
  11487.     dialer.c_lineparam |= PULSE;
  11488.     dialer.c_lineparam &= ~DTMF;
  11489.     if (ioctl(ttyfd,PIOCSETP,&dialer) == -1) {
  11490.         printf("Cannot set modem to pulse dialing\n");
  11491.         ttclos(0);
  11492.         return(-2);
  11493.     }
  11494.     break;
  11495.       default:
  11496.         if (ioctl(ttyfd,PIOCDIAL,telnum) != 0) {
  11497.         perror("Dialing error");
  11498.         ttclos(0);
  11499.         return(-2);
  11500.     }
  11501.     break;
  11502.     }
  11503. #endif
  11504.  
  11505.     ioctl(ttyfd,PIOCDIAL,"@");        /* terminator for data call */
  11506.     do {                /* wait for modems to Connect */
  11507.         if (ioctl(ttyfd,PIOCGETP,&dialer) != 0)    { /* get params */
  11508.         perror("Cannot get modems to connect");
  11509.         ttclos(0);
  11510.         return(-2);
  11511.     }
  11512.     } while ((dialer.c_linestatus & MODEMCONNECTED) == 0);
  11513.     /* Turn off O_NDELAY flag now. */
  11514.     fcntl(ttyfd, F_SETFL, fcntl(ttyfd, F_GETFL, 0) & ~O_NDELAY);
  11515.     signal(SIGHUP, sighup);             /* hangup on loss of carrier */
  11516.     return(0);                          /* return success */
  11517. }
  11518.  
  11519. /*
  11520.   Offgetty, ongetty functions. These function get the 'getty(1m)' off
  11521.   and restore it to the indicated line.  Shell's return codes are:
  11522.     0: Can't do it.  Probably a user logged on.
  11523.     1: No need.  No getty on that line.
  11524.     2: Done, you should restore the getty when you're done.
  11525.   DOGETY System(3), however, returns them as 0, 256, 512, respectively.
  11526.   Thanks to Kevin O'Gorman, Anarm Software Systems.
  11527.  
  11528.    getoff.sh looks like:   geton.sh looks like:
  11529.      setgetty $1 0           setgetty $1 1
  11530.      err=$?                  exit $?
  11531.      sleep 2
  11532.      exit $err
  11533. */
  11534.  
  11535. /*  O F F G E T T Y  --  Turn off getty(1m) for the communications tty line
  11536.  * and get status so it can be restarted after the line is hung up.
  11537.  */
  11538. int
  11539. offgetty(ttname) char *ttname; {
  11540.     char temp[30];
  11541.     while (*ttname != '\0') ttname++;       /* seek terminator of path */
  11542.     ttname -= 3;                            /* get last 3 chars of name */
  11543.     sprintf(temp,"/usr/bin/getoff.sh %s",ttname);
  11544.     return(zsyscmd(temp));
  11545. }
  11546.  
  11547. /*  O N G E T T Y  --  Turn on getty(1m) for the communications tty line */
  11548.  
  11549. int
  11550. ongetty(ttname) char *ttname; {
  11551.     char temp[30];
  11552.     while (*ttname != '\0') ttname++;       /* comms tty path name */
  11553.     ttname -= 3;
  11554.     sprintf(temp,"/usr/bin/geton.sh %s",ttname);
  11555.     return(zsyscmd(temp));
  11556. }
  11557. #endif /* ATT7300 */
  11558.  
  11559. /*  T T S C A R R  --  Set ttcarr variable, controlling carrier handling.
  11560.  *
  11561.  *  0 = Off: Always ignore carrier. E.g. you can connect without carrier.
  11562.  *  1 = On: Heed carrier, except during dialing. Carrier loss gives disconnect.
  11563.  *  2 = Auto: For "modem direct": The same as "Off".
  11564.  *            For real modem types: Heed carrier during connect, but ignore
  11565.  *                it anytime else.  Compatible with pre-5A C-Kermit versions.
  11566.  *
  11567.  * As you can see, this setting does not affect dialing, which always ignores
  11568.  * carrier (unless there is some special exception for some modem type).  It
  11569.  * does affect ttopen() if it is set before ttopen() is used.  This setting
  11570.  * takes effect on the next call to ttopen()/ttpkt()/ttvt().  And they are
  11571.  * (or should be) always called before any communications is tried, which
  11572.  * means that, practically speaking, the effect is immediate.
  11573.  *
  11574.  * Of course, nothing of this applies to remote mode (xlocal = 0).
  11575.  *
  11576.  * Someone has yet to uncover how to manipulate the carrier in the BSD
  11577.  * environment (or any non-termio using environment).  Until that time, this
  11578.  * will simply be a no-op for BSD.
  11579.  *
  11580.  * Note that in previous versions, the carrier was most often left unchanged
  11581.  * in ttpkt()/ttvt() unless they were called with FLO_DIAL or FLO_DIAX.  This
  11582.  * has changed.  Now it is controlled by ttcarr in conjunction with these
  11583.  * modes.
  11584.  */
  11585. int
  11586. ttscarr(carrier) int carrier; {
  11587.     ttcarr = carrier;
  11588.     debug(F101, "ttscarr","",ttcarr);
  11589.     return(ttcarr);
  11590. }
  11591.  
  11592. /* C A R R C T L  --  Set tty modes for carrier treatment.
  11593.  *
  11594.  * Sets the appropriate bits in a termio or sgttyb struct for carrier control
  11595.  * (actually, there are no bits in sgttyb for that), or performs any other
  11596.  * operations needed to control this on the current system.  The function does
  11597.  * not do the actual TCSETA or stty, since often we want to set other bits too
  11598.  * first.  Don't call this function when xlocal is 0, or the tty is not opened.
  11599.  *
  11600.  * We don't know how to do anything like carrier control on non-ATTSV systems,
  11601.  * except, apparently, ultrix.  See above.  It is also known that this doesn't
  11602.  * have much effect on a Xenix system.  For Xenix, one should switch back and
  11603.  * forth between the upper and lower case device files.  Maybe later.
  11604.  * Presently, Xenix will stick to the mode it was opened with.
  11605.  *
  11606.  * carrier: 0 = ignore carrier, 1 = require carrier.
  11607.  * The current state is saved in curcarr, and checked to save labour.
  11608.  */
  11609. #ifdef SVORPOSIX
  11610. int
  11611. #ifdef BSD44ORPOSIX
  11612. carrctl(ttpar, carrier)    struct termios *ttpar; int carrier;
  11613. #else /* ATTSV */
  11614. carrctl(ttpar, carrier)    struct termio *ttpar; int carrier;
  11615. #endif /* BSD44ORPOSIX */
  11616. /* carrctl */ {
  11617.     debug(F101, "carrctl","",carrier);
  11618.     if (carrier)
  11619.       ttpar->c_cflag &= ~CLOCAL;
  11620.     else
  11621.       ttpar->c_cflag |= CLOCAL;
  11622.     return(0);
  11623. }
  11624. #else /* Berkeley, V7, et al... */
  11625. int
  11626. carrctl(ttpar, carrier) struct sgttyb *ttpar; int carrier; {
  11627.     debug(F101, "carrctl","",carrier);
  11628.     if (carrier == curcarr)
  11629.       return(0);
  11630.     curcarr = carrier;
  11631. #ifdef ultrix
  11632. #ifdef COMMENT
  11633. /*
  11634.   Old code from somebody at DEC that tends to get stuck, time out, etc.
  11635. */
  11636.     if (carrier) {
  11637.     ioctl(ttyfd, TIOCMODEM, &temp);
  11638.     ioctl(ttyfd, TIOCHPCL, 0);
  11639.     } else {
  11640.     /* (According to the manuals, TIOCNCAR should be preferred */
  11641.     /* over TIOCNMODEM...) */
  11642.     ioctl(ttyfd, TIOCNMODEM, &temp);
  11643.     }
  11644. #else
  11645. /*
  11646.   New code from Jamie Watson that, he says, eliminates the problems.
  11647. */
  11648.     if (carrier) {
  11649.     ioctl(ttyfd, TIOCCAR);
  11650.     ioctl(ttyfd, TIOCHPCL);
  11651.     } else {
  11652.     ioctl(ttyfd, TIOCNCAR);
  11653.     }
  11654. #endif /* COMMENT */
  11655. #endif /* ultrix */
  11656.     return(0);
  11657. }
  11658. #endif /* SVORPOSIX */
  11659.  
  11660.  
  11661. /*  T T G M D M  --  Get modem signals  */
  11662. /*
  11663.  Looks for RS-232 modem signals, and returns those that are on in as its
  11664.  return value, in a bit mask composed of the BM_xxx values defined in ckcdeb.h.
  11665.  Returns:
  11666.  -3 Not implemented
  11667.  -2 if the communication device does not have modem control (e.g. telnet)
  11668.  -1 on error.
  11669.  >= 0 on success, with a bit mask containing the modem signals that are on.
  11670. */
  11671.  
  11672. /*
  11673.   Define the symbol K_MDMCTL if we have Sys V R3 / 4.3 BSD style
  11674.   modem control, namely the TIOCMGET ioctl.
  11675. */
  11676.  
  11677. #ifdef BSD43
  11678. #define K_MDMCTL
  11679. #endif /* BSD43 */
  11680.  
  11681. #ifdef SUNOS4
  11682. #define K_MDMCTL
  11683. #endif /* SUNOS4 */
  11684.  
  11685. /*
  11686.   SCO OpenServer R5.0.4.  The TIOCMGET definition is hardwired in because it
  11687.   is skipped in termio.h when _POSIX_SOURCE is defined.  But _POSIX_SOURCE
  11688.   must be defined in order to get the high serial speeds that are new to
  11689.   5.0.4.  However, the regular SCO drivers do not implement TIOCMGET, so the
  11690.   ioctl() returns -1 with errno 22 (invalid function).  But third-party
  11691.   drivers, e.g. for Digiboard, do implement it, and so it should work on ports
  11692.   driven by those drivers.
  11693. */
  11694. #ifdef SCO_OSR504
  11695. #ifndef TIOCMGET
  11696. #define TIOCMGET (('t'<<8)|29)
  11697. #endif /* TIOCMGET */
  11698. #endif /* SCO_OSR504 */
  11699.  
  11700. #ifdef QNX
  11701. #define K_MDMCTL
  11702. #else
  11703. #ifdef TIOCMGET
  11704. #define K_MDMCTL
  11705. #endif /* TIOCMGET */
  11706. #endif /* QNX */
  11707. /*
  11708.   "A serial communication program that can't read modem signals
  11709.    is like a car without windows."
  11710. */
  11711. int
  11712. ttgmdm() {
  11713.  
  11714. #ifdef QNX
  11715. #include <sys/qioctl.h>
  11716.  
  11717.     unsigned long y, mdmbits[2] = { 0L, 0L };
  11718.     int z = 0;
  11719.  
  11720.     if (xlocal && ttyfd < 0)
  11721.       return(-1);
  11722.  
  11723. #ifdef NETCMD
  11724.     if (ttpipe) return(-2);
  11725. #endif /* NETCMD */
  11726. #ifdef NETPTY
  11727.     if (ttpty) return(-2);
  11728. #endif /* NETPTY */
  11729.  
  11730.     if (!qnx_ioctl(ttyfd, QCTL_DEV_CTL, &mdmbits[0], 8, &mdmbits[0], 4)) {
  11731.     y = mdmbits[0];
  11732.     if (y & 0x100000L) z |= BM_CTS;    /* Values from comment */
  11733.     if (y & 0x200000L) z |= BM_DSR;    /* in sys/qioctl.h */
  11734.     if (y & 0x800000L) z |= BM_DCD;
  11735.     if (y & 0x400000L) z |= BM_RNG;
  11736.     if (y & 0x000001L) z |= BM_DTR;
  11737.     if (y & 0x000002L) z |= BM_RTS;
  11738.     return(z);
  11739.     } else return(-1);
  11740. #else
  11741. #ifdef HPUX                /* HPUX has its own way */
  11742.     int x, z;
  11743.  
  11744. #ifdef HPUX10                /* Modem flag word */
  11745.     mflag y;                /* mflag typedef'd in <sys/modem.h> */
  11746. #else
  11747. #ifdef HPUX9
  11748.     mflag y;
  11749. #else
  11750. #ifdef HPUX8
  11751.     mflag y;
  11752. #else
  11753.     unsigned long y;            /* Not sure about pre-8.0... */
  11754. #endif /* HPUX8 */
  11755. #endif /* HPUX9 */
  11756. #endif /* HPUX10 */
  11757.  
  11758.     if (xlocal && ttyfd < 0)
  11759.       return(-1);
  11760.  
  11761.     if (netconn)            /* Network connection */
  11762.       return(-2);            /* No modem signals */
  11763.  
  11764. #ifdef NETCMD
  11765.     if (ttpipe) return(-2);
  11766. #endif /* NETCMD */
  11767. #ifdef NETPTY
  11768.     if (ttpty) return(-2);
  11769. #endif /* NETPTY */
  11770.  
  11771.     if (xlocal)                /* Get modem signals */
  11772.       x = ioctl(ttyfd,MCGETA,&y);
  11773.     else
  11774.       x = ioctl(0,MCGETA,&y);
  11775.     if (x < 0) return(-1);
  11776.     debug(F101,"ttgmdm","",y);
  11777.  
  11778.     z = 0;                /* Initialize return value */
  11779.  
  11780. /* Now set bits for each modem signal that is reported to be on. */
  11781.  
  11782. #ifdef MCTS
  11783.     /* Clear To Send */
  11784.     if (y & MCTS) z |= BM_CTS;
  11785. #endif
  11786. #ifdef MDSR
  11787.     /* Data Set Ready */
  11788.     if (y & MDSR) z |= BM_DSR;
  11789. #endif
  11790. #ifdef MDCD
  11791.     /* Carrier */
  11792.     if (y & MDCD) z |= BM_DCD;
  11793. #endif
  11794. #ifdef MRI
  11795.     /* Ring Indicate */
  11796.     if (y & MRI) z |= BM_RNG;
  11797. #endif
  11798. #ifdef MDTR
  11799.     /* Data Terminal Ready */
  11800.     if (y & MDTR) z |= BM_DTR;
  11801. #endif
  11802. #ifdef MRTS
  11803.     /* Request To Send */
  11804.     if (y & MRTS) z |= BM_RTS;
  11805. #endif
  11806.     return(z);
  11807.  
  11808. #else /* ! HPUX */
  11809.  
  11810. #ifdef K_MDMCTL
  11811. /*
  11812.   Note, TIOCMGET might already have been defined in <sys/ioctl.h> or elsewhere.
  11813.   If not, we try including <sys/ttycom.h> -- if this blows up then more ifdefs
  11814.   are needed.
  11815. */
  11816. #ifndef TIOCMGET
  11817. #include <sys/ttycom.h>
  11818. #endif /* TIOCMGET */
  11819.  
  11820.     int x, y, z;
  11821.  
  11822.     debug(F100,"ttgmdm K_MDMCTL defined","",0);
  11823.  
  11824.     if (netconn)            /* Network connection */
  11825.       return(-2);            /* No modem signals */
  11826.  
  11827. #ifdef NETCMD
  11828.     if (ttpipe) return(-2);
  11829. #endif /* NETCMD */
  11830. #ifdef NETPTY
  11831.     if (ttpty) return(-2);
  11832. #endif /* NETPTY */
  11833.  
  11834.     if (xlocal && ttyfd < 0)
  11835.       return(-1);
  11836.  
  11837.     if (xlocal)
  11838.       x = ioctl(ttyfd,TIOCMGET,&y);    /* Get modem signals. */
  11839.     else
  11840.       x = ioctl(0,TIOCMGET,&y);
  11841.     debug(F101,"ttgmdm TIOCMGET ioctl","",x);
  11842.     if (x < 0) {
  11843.     debug(F101,"ttgmdm errno","",errno);
  11844.     return(-1);
  11845.     }
  11846.     debug(F101,"ttgmdm bits","",y);
  11847.  
  11848.     z = 0;                /* Initialize return value. */
  11849. #ifdef TIOCM_CTS
  11850.     /* Clear To Send */
  11851.     if (y & TIOCM_CTS) z |= BM_CTS;
  11852. #endif
  11853. #ifdef TIOCM_DSR
  11854.     /* Data Set Ready */
  11855.     if (y & TIOCM_DSR) z |= BM_DSR;
  11856. #endif
  11857. #ifdef TIOCM_CAR
  11858.     /* Carrier */
  11859.     if (y & TIOCM_CAR) z |= BM_DCD;
  11860. #endif
  11861. #ifdef TIOCM_RNG
  11862.     /* Ring Indicate */
  11863.     if (y & TIOCM_RNG) z |= BM_RNG;
  11864. #endif
  11865. #ifdef TIOCM_DTR
  11866.     /* Data Terminal Ready */
  11867.     if (y & TIOCM_DTR) z |= BM_DTR;
  11868. #endif
  11869. #ifdef TIOCM_RTS
  11870.     /* Request To Send */
  11871.     if (y & TIOCM_RTS) z |= BM_RTS;
  11872. #endif
  11873.     return(z);
  11874.  
  11875. #else /* !K_MDMCTL catch-All */
  11876.  
  11877.     debug(F100,"ttgmdm K_MDMCTL not defined","",0);
  11878. #ifdef TIOCMGET
  11879.     debug(F100,"ttgmdm TIOCMGET defined","",0);
  11880. #else
  11881.     debug(F100,"ttgmdm TIOCMGET not defined","",0);
  11882. #endif /* TIOCMGET */
  11883. #ifdef _SVID3
  11884.     debug(F100,"ttgmdm _SVID3 defined","",0);
  11885. #else
  11886.     debug(F100,"ttgmdm _SVID3 not defined","",0);
  11887. #endif /* _SVID3 */
  11888.  
  11889.     if (netconn)            /* Network connection */
  11890.       return(-2);            /* No modem signals */
  11891.  
  11892. #ifdef NETCMD
  11893.     if (ttpipe) return(-2);
  11894. #endif /* NETCMD */
  11895. #ifdef NETPTY
  11896.     if (ttpty) return(-2);
  11897. #endif /* NETPTY */
  11898.  
  11899.     return(-3);                /* Sorry, I don't know how... */
  11900.  
  11901. #endif /* K_MDMCTL */
  11902. #endif /* HPUX */
  11903. #endif /* QNX */
  11904. }
  11905.  
  11906. /*  P S U S P E N D  --  Put this process in the background.  */
  11907.  
  11908. /*
  11909.   Call with flag nonzero if suspending is allowed, zero if not allowed.
  11910.   Returns 0 on apparent success, -1 on failure (flag was zero, or
  11911.   kill() returned an error code.
  11912. */
  11913. int
  11914. psuspend(flag) int flag; {
  11915.  
  11916. #ifdef RTU
  11917.     extern int rtu_bug;
  11918. #endif /* RTU */
  11919.  
  11920.     if (flag == 0) return(-1);
  11921.  
  11922. #ifdef NOJC
  11923.     return(-1);
  11924. #else
  11925. #ifdef SIGTSTP
  11926. /*
  11927.   The big question here is whether job control is *really* supported.
  11928.   There's no way Kermit can know for sure.  The fact that SIGTSTP is
  11929.   defined does not guarantee the Unix kernel supports it, and the fact
  11930.   that the Unix kernel supports it doesn't guarantee that the user's
  11931.   shell (or other process that invoked Kermit) supports it.
  11932. */
  11933. #ifdef RTU
  11934.     rtu_bug = 1;
  11935. #endif /* RTU */
  11936.     if (kill(0,SIGSTOP) < 0
  11937. #ifdef MIPS
  11938. /* Let's try this for MIPS too. */
  11939.     && kill(getpid(),SIGSTOP) < 0
  11940. #endif /* MIPS */
  11941.     ) {                /* If job control, suspend the job */
  11942.     perror("suspend");
  11943.     debug(F101,"psuspend error","",errno);
  11944.     return(-1);
  11945.     }
  11946.     debug(F100,"psuspend ok","",0);
  11947.     return(0);
  11948. #else
  11949.     return(-1);
  11950. #endif /* SIGTSTP */
  11951. #endif /* NOJC */
  11952. }
  11953.  
  11954. /*
  11955.   setuid package, by Kristoffer Eriksson, with contributions from Dean
  11956.   Long and fdc.
  11957. */
  11958.  
  11959. /* The following is for SCO when CK_ANSILIBS is defined... */
  11960. #ifdef M_UNIX
  11961. #ifdef CK_ANSILIBS
  11962. #ifndef NOGETID_PROTOS
  11963. #define NOGETID_PROTOS
  11964. #endif /* NOGETID_PROTOS */
  11965. #endif /* CK_ANSILIBS */
  11966. #endif /* M_UNIX */
  11967.  
  11968. #ifndef _POSIX_SOURCE
  11969. #ifndef SUNOS4
  11970. #ifndef NEXT
  11971. #ifndef PS2AIX10
  11972. #ifndef sequent
  11973. #ifndef HPUX9
  11974. #ifndef COHERENT
  11975. #ifndef NOGETID_PROTOS
  11976. extern UID_T getuid(), geteuid(), getreuid();
  11977. extern GID_T getgid(), getegid(), getregid();
  11978. #endif /* NOGETID_PROTOS */
  11979. #else
  11980. extern UID_T getreuid();
  11981. extern GID_T getregid();
  11982. #endif /* COHERENT */
  11983. #endif /* HPUX9 */
  11984. #endif /* sequent */
  11985. #endif /* PS2AIX10 */
  11986. #endif /* NEXT */
  11987. #endif /* SUNOS4 */
  11988. #endif /* _POSIX_SOURCE */
  11989.  
  11990. /*
  11991. Subject: Set-user-id
  11992. To: fdc@watsun.cc.columbia.edu (Frank da Cruz)
  11993. Date: Sat, 21 Apr 90 4:48:25 MES
  11994. From: Kristoffer Eriksson <ske@pkmab.se>
  11995.  
  11996. This is a set of functions to be used in programs that may be run set-user-id
  11997. and/or set-group-id. They handle both the case where the program is not run
  11998. with such privileges (nothing special happens then), and the case where one
  11999. or both of these set-id modes are used.  The program is made to run with the
  12000. user's real user and group ids most of the time, except for when more
  12001. privileges are needed.  Don't set-user-id to "root".
  12002.  
  12003. This works on System V and POSIX.  In BSD, it depends on the
  12004. "saved-set-user-id" feature.
  12005. */
  12006.  
  12007. #define UID_ROOT 0            /* Root user and group ids */
  12008. #define GID_ROOT 0
  12009.  
  12010. /*
  12011.   The following code defines the symbol SETEUID for UNIX systems based
  12012.   on BSD4.4 (either -Encumbered or -Lite).  This program will then use
  12013.   seteuid() and setegid() instead of setuid() and setgid(), which still
  12014.   don't allow arbitrary switching.  It also avoids setreuid() and
  12015.   setregid(), which are included in BSD4.4 for compatibility only, are
  12016.   insecure, and print warnings to stderr under at least one system (NetBSD
  12017.   1.0).  Note that POSIX systems should still use setuid() and setgid();
  12018.   the seteuid() and setegid() functions are BSD4.4 extensions to the
  12019.   POSIX model.  Mike Long <mike.long@analog.com>, 8/94.
  12020. */
  12021. #ifdef BSD44
  12022. #define SETEUID
  12023. #endif /* BSD44 */
  12024.  
  12025. /*
  12026.   The following construction automatically defines the symbol SETREUID for
  12027.   UNIX versions based on Berkeley Unix 4.2 and 4.3.  If this symbol is
  12028.   defined, then this program will use getreuid() and getregid() calls in
  12029.   preference to getuid() and getgid(), which in Berkeley-based Unixes do
  12030.   not allow arbitrary switching back and forth of real & effective uid.
  12031.   This construction also allows -DSETREUID to be put on the cc command line
  12032.   for any system that has and wants to use setre[ug]id().  It also prevents
  12033.   automatic definition of SETREUID if -DNOSETREU is included on the cc
  12034.   command line (or otherwise defined).
  12035. */
  12036. #ifdef FT18                /* None of this for Fortune. */
  12037. #define NOSETREU
  12038. #endif /* FT18 */
  12039.  
  12040. #ifdef ANYBSD
  12041. #ifndef BSD29
  12042. #ifndef BSD41
  12043. #ifndef SETREUID
  12044. #ifndef NOSETREU
  12045. #ifndef SETEUID
  12046. #define SETREUID
  12047. #endif /* SETEUID */
  12048. #endif /* NOSETREU */
  12049. #endif /* SETREUID */
  12050. #endif /* !BSD41 */
  12051. #endif /* !BSD29 */
  12052. #endif /* ANYBSD */
  12053.  
  12054. /* Variables for user and group IDs. */
  12055.  
  12056. static UID_T realuid = (UID_T) -1, privuid = (UID_T) -1;
  12057. static GID_T realgid = (GID_T) -1, privgid = (GID_T) -1;
  12058.  
  12059.  
  12060. /* P R I V _ I N I  --  Initialize privileges package  */
  12061.  
  12062. /* Called as early as possible in a set-uid or set-gid program to store the
  12063.  * set-to uid and/or gid and step down to the users real uid and gid. The
  12064.  * stored id's can be temporarily restored (allowed in System V) during
  12065.  * operations that require the privilege.  Most of the time, the program
  12066.  * should execute in unpriviliged state, to not impose any security threat.
  12067.  *
  12068.  * Note: Don't forget that access() always uses the real id:s to determine
  12069.  * file access, even with privileges restored.
  12070.  *
  12071.  * Returns an error mask, with error values or:ed together:
  12072.  *   1 if setuid() fails,
  12073.  *   2 if setgid() fails, and
  12074.  *   4 if the program is set-user-id to "root", which can't be handled.
  12075.  *
  12076.  * Only the return value 0 indicates real success. In case of failure,
  12077.  * those privileges that could be reduced have been, at least, but the
  12078.  * program should be aborted none-the-less.
  12079.  *
  12080.  * Also note that these functions do not expect the uid or gid to change
  12081.  * without their knowing. It may work if it is only done temporarily, but
  12082.  * you're on your own.
  12083.  */
  12084. int
  12085. priv_ini() {
  12086.     int err = 0;
  12087.  
  12088.     /* Save real ID:s. */
  12089.     realuid = getuid();
  12090.     realgid = getgid();
  12091.  
  12092.     /* Save current effective ID:s, those set to at program exec. */
  12093.     privuid = geteuid();
  12094.     privgid = getegid();
  12095.  
  12096.     /* If running set-uid, go down to real uid, otherwise remember that
  12097.      * no privileged uid is available.
  12098.      *
  12099.      * Exceptions:
  12100.      *
  12101.      * 1) If the real uid is already "root" and the set-uid uid (the
  12102.      * initial effective uid) is not "root", then we would have trouble
  12103.      * if we went "down" to "root" here, and then temporarily back to the
  12104.      * set-uid uid (not "root") and then again tried to become "root". I
  12105.      * think the "saved set-uid" is lost when changing uid from effective
  12106.      * uid "root", which changes all uid, not only the effective uid. But
  12107.      * in this situation, we can simply go to "root" and stay there all
  12108.      * the time. That should give sufficient privilege (understatement!),
  12109.      * and give the right uids for subprocesses.
  12110.      *
  12111.      * 2) If the set-uid (the initial effective uid) is "root", and we
  12112.      * change uid to the real uid, we can't change it back to "root" when
  12113.      * we need the privilege, for the same reason as in 1). Thus, we can't
  12114.      * handle programs that are set-user-id to "root" at all. The program
  12115.      * should be stopped.  Use some other uid.  "root" is probably too
  12116.      * privileged for such things, anyway. (The uid is reverted to the
  12117.      * real uid until termination.)
  12118.      *
  12119.      * These two exceptions have the effect that the "root" uid will never
  12120.      * be one of the two uids that are being switched between, which also
  12121.      * means we don't have to check for such cases in the switching
  12122.      * functions.
  12123.      *
  12124.      * Note that exception 1) is handled by these routines (by constantly
  12125.      * running with uid "root", while exception 2) is a serious error, and
  12126.      * is not provided for at all in the switching functions.
  12127.      */
  12128.     if (realuid == privuid)
  12129.     privuid = (UID_T) -1;        /* Not running set-user-id. */
  12130.  
  12131.     /* If running set-gid, go down to real gid, otherwise remember that
  12132.      * no privileged gid is available.
  12133.      *
  12134.      * There are no exception like there is for the user id, since there
  12135.      * is no group id that is privileged in the manner of uid "root".
  12136.      * There could be equivalent problems for group changing if the
  12137.      * program sometimes ran with uid "root" and sometimes not, but
  12138.      * that is already avoided as explained above.
  12139.      *
  12140.      * Thus we can expect always to be able to switch to the "saved set-
  12141.      * gid" when we want, and back to the real gid again. You may also
  12142.      * draw the conclusion that set-gid provides for fewer hassles than
  12143.      * set-uid.
  12144.      */
  12145.  
  12146.     if (realgid == privgid)        /* If not running set-user-id, */
  12147.       privgid = (GID_T) -1;        /*  remember it this way. */
  12148.  
  12149.     err = priv_off();            /* Turn off setuid privilege. */
  12150.  
  12151.     if (privuid == UID_ROOT)        /* If setuid to root, */
  12152.       err |= 4;                /* return this error. */
  12153.  
  12154.     if (realuid == UID_ROOT) {        /* If real id is root, */
  12155.     privuid = (UID_T) -1;        /* stay root at all times. */
  12156. #ifdef ATT7300
  12157.     /* If Kermit installed SUID uucp and user is running as root */
  12158.     err &= ~1;            /* System V R0 does not save UID */
  12159. #endif /* ATT7300 */
  12160.     }
  12161.     return(err);
  12162. }
  12163.  
  12164.  
  12165. /* Macros for hiding the differences in UID/GID setting between various Unix
  12166.  * systems. These macros should always be called with both the privileged ID
  12167.  * and the non-privileged ID. The one in the second argument, will become the
  12168.  * effective ID. The one in the first argument will be retained for later
  12169.  * retrieval.
  12170.  */
  12171. #ifdef SETREUID
  12172. #ifdef SAVEDUID
  12173. /* On BSD systems with the saved-UID feature, we just juggle the effective
  12174.  * UID back and forth, and leave the real UID at its true value.  The kernel
  12175.  * allows switching to both the current real UID, the effective UID, and the
  12176.  * UID which the program is set-UID to.  The saved set-UID always holds the
  12177.  * privileged UID for us, and the real UID will always be the non-privileged,
  12178.  * and we can freely choose one of them for the effective UID at any time.
  12179.  */
  12180. #define switchuid(hidden,active) setreuid( (UID_T) -1, active)
  12181. #define switchgid(hidden,active) setregid( (GID_T) -1, active)
  12182.  
  12183. #else   /* SETREUID,!SAVEDUID */
  12184.  
  12185. /* On systems with setreXid() but without the saved-UID feature, notably
  12186.  * BSD 4.2, we swap the real and effective UIDs each time.  It's
  12187.  * the effective UID that we are interested in, but we have to retain the
  12188.  * unused UID somewhere to enable us to restore it later, and we do this
  12189.  * in the real UID.  The kernel only allows switching to either the current
  12190.  * real or the effective UID, unless you're "root".
  12191.  */
  12192. #define switchuid(hidden,active)    setreuid(hidden,active)
  12193. #define switchgid(hidden,active)    setregid(hidden,active)
  12194. #endif
  12195.  
  12196. #else /* !SETREUID, !SAVEDUID */
  12197.  
  12198. #ifdef SETEUID
  12199. /*
  12200.   BSD 4.4 works similarly to System V and POSIX (see below), but uses
  12201.   seteXid() instead of setXid() to change effective IDs.  In addition, the
  12202.   seteXid() functions work the same for "root" as for other users.
  12203. */
  12204. #define switchuid(hidden,active)    seteuid(active)
  12205. #define switchgid(hidden,active)    setegid(active)
  12206.  
  12207. #else /* !SETEUID */
  12208.  
  12209. /* On System V and POSIX, the only thing we can change is the effective UID
  12210.  * (unless the current effective UID is "root", but initsuid() avoids that for
  12211.  * us).  The kernel allows switching to the current real UID or to the saved
  12212.  * set-UID.  These are always set to the non-privileged UID and the privileged
  12213.  * UID, respectively, and we only change the effective UID.  This breaks if
  12214.  * the current effective UID is "root", though, because for "root" setuid/gid
  12215.  * becomes more powerful, which is why initsuid() treats "root" specially.
  12216.  * Note: That special treatment maybe could be ignored for BSD?  Note: For
  12217.  * systems that don't fit any of these four cases, we simply can't support
  12218.  * set-UID.
  12219.  */
  12220. #define switchuid(hidden,active)    setuid(active)
  12221. #define switchgid(hidden,active)    setgid(active)
  12222.  
  12223. #endif /* SETEUID */
  12224. #endif /* SETREUID */
  12225.  
  12226.  
  12227. /* P R I V _ O N  --  Turn on the setuid and/or setgid */
  12228.  
  12229. /* Go to the privileged uid (gid) that the program is set-user-id
  12230.  * (set-group-id) to, unless the program is running unprivileged.
  12231.  * If setuid() fails, return value will be 1. If getuid() fails it
  12232.  * will be 2.  Return immediately after first failure, and the function
  12233.  * tries to restore any partial work done.  Returns 0 on success.
  12234.  * Group id is changed first, since it is less serious than user id.
  12235.  */
  12236. int
  12237. priv_on() {
  12238.     if (privgid != (GID_T) -1)
  12239.       if (switchgid(realgid,privgid))
  12240.         return(2);
  12241.  
  12242.     if (privuid != (UID_T) -1)
  12243.       if (switchuid(realuid,privuid)) {
  12244.       if (privgid != (GID_T) -1)
  12245.         switchgid(privgid,realgid);
  12246.       return(1);
  12247.       }
  12248.     return(0);
  12249. }
  12250.  
  12251. /* P R I V _ O F F  --  Turn on the real uid and gid */
  12252.  
  12253. /* Return to the unprivileged uid (gid) after an temporary visit to
  12254.  * privileged status, unless the program is running without set-user-id
  12255.  * (set-group-id). Returns 1 for failure in setuid() and 2 for failure
  12256.  * in setgid() or:ed together. The functions tries to return both uid
  12257.  * and gid to unprivileged state, regardless of errors. Returns 0 on
  12258.  * success.
  12259.  */
  12260. int
  12261. priv_off() {
  12262.     int err = 0;
  12263.  
  12264.     if (privuid != (UID_T) -1)
  12265.        if (switchuid(privuid,realuid))
  12266.       err |= 1;
  12267.  
  12268.     if (privgid != (GID_T) -1)
  12269.        if (switchgid(privgid,realgid))
  12270.     err |= 2;
  12271.  
  12272.     return(err);
  12273. }
  12274.  
  12275. /* Turn off privilege permanently.  No going back.  This is necessary before
  12276.  * a fork() on BSD43 machines that don't save the setUID or setGID, because
  12277.  * we swap the real and effective ids, and we don't want to let the forked
  12278.  * process swap them again and get the privilege back. It will work on other
  12279.  * machines too, such that you can rely on its effect always being the same,
  12280.  * for instance, even when you're in priv_on() state when this is called.
  12281.  * (Well, that part about "permanent" is on System V only true if you follow
  12282.  * this with a call to exec(), but that's what we want it for anyway.)
  12283.  * Added by Dean Long -- dlong@midgard.ucsc.edu
  12284.  */
  12285. int
  12286. priv_can() {
  12287.  
  12288. #ifdef SETREUID
  12289.     int err = 0;
  12290.     if (privuid != (UID_T) -1)
  12291.        if (setreuid(realuid,realuid))
  12292.       err |= 1;
  12293.  
  12294.     if (privgid != (GID_T) -1)
  12295.         if (setregid(realgid,realgid))
  12296.        err |= 2;
  12297.  
  12298.     return(err);
  12299.  
  12300. #else
  12301. #ifdef SETEUID
  12302.     int err = 0;
  12303.     if (privuid != (UID_T) -1)
  12304.     if (setuid(realuid)) {
  12305.         debug(F101,"setuid failed","",errno);
  12306.         err |= 1;
  12307.         debug(F101,"ruid","",getuid());
  12308.         debug(F101,"euid","",geteuid());
  12309.     }
  12310.     debug(F101,"setuid","",realuid);
  12311.     if (privgid != (GID_T) -1)
  12312.         if (setgid(realgid)) {
  12313.         debug(F101,"setgid failed","",errno);
  12314.         err |= 2;
  12315.         debug(F101,"rgid","",getgid());
  12316.         debug(F101,"egid","",getegid());
  12317.     }
  12318.     debug(F101,"setgid","",realgid);
  12319.     return(err);
  12320. #else
  12321.     /* Easy way of using setuid()/setgid() instead of setreuid()/setregid().*/
  12322.     return(priv_off());
  12323. #endif /* SETEUID */
  12324. #endif /* SETREUID */
  12325. }
  12326.  
  12327. /* P R I V _ O P N  --  For opening protected files or devices. */
  12328.  
  12329. int
  12330. priv_opn(name, modes) char *name; int modes; {
  12331.     int x;
  12332.     priv_on();                /* Turn privileges on */
  12333.     x = open(name, modes);        /* Try to open the device */
  12334.     priv_off();                /* Turn privileges off */
  12335.     return(x);                /* Return open's return code */
  12336. }
  12337.  
  12338. /*  P R I V _ C H K  --  Check privileges.  */
  12339.  
  12340. /*  Try to turn them off.  If turning them off did not succeed, cancel them */
  12341.  
  12342. int
  12343. priv_chk() {
  12344.     int x, y = 0;
  12345.     x = priv_off();            /* Turn off privs. */
  12346.     if (x != 0 || getuid() == privuid || geteuid() == privuid)
  12347.       y = priv_can();
  12348.     if (x != 0 || getgid() == privgid || getegid() == privgid)
  12349.       y = y | priv_can();
  12350.     return(y);
  12351. }
  12352.  
  12353. UID_T
  12354. real_uid() {
  12355.     return(realuid);
  12356. }
  12357.  
  12358. VOID
  12359. ttimoff() {                /* Turn off any timer interrupts */
  12360.     /* int xx; */
  12361. /*
  12362.   As of 5A(183), we set SIGALRM to SIG_IGN (to ignore alarms) rather than to
  12363.   SIG_DFL (to catch alarms, or if there is no handler, to exit).  This is to
  12364.   cure (mask, really) a deeper problem with stray alarms that occurs on some
  12365.   systems, possibly having to do with sleep(), that caused core dumps.  It
  12366.   should be OK to do this, because no code in this module uses nested alarms.
  12367.   (But we still have to watch out for SCRIPT and DIAL...)
  12368. */
  12369.     /* xx = */ alarm(0);
  12370.     /* debug(F101,"ttimoff alarm","",xx); */
  12371.     if (saval) {            /* Restore any previous */
  12372.     signal(SIGALRM,saval);        /* alarm handler. */
  12373.     /* debug(F101,"ttimoff alarm restoring saval","",saval); */
  12374.     saval = NULL;
  12375.     } else {
  12376.     signal(SIGALRM,SIG_IGN);    /* Used to be SIG_DFL */
  12377.     /* debug(F100,"ttimoff alarm SIG_IGN","",0); */
  12378.     }
  12379. }
  12380.  
  12381. #ifdef CK_REDIR
  12382. #ifdef COMMENT
  12383. /* Old way - not portable */
  12384. int
  12385. ttruncmd(s) char *s; {
  12386.     int r = 0;                /* Return code */
  12387.                     /* 0 = failure, 1 = success */
  12388. #ifdef WIFEXITED
  12389. #ifndef WEXITSTATUS
  12390. #ifdef w_retcode
  12391. #define WEXITSTATUS(x) ((x).w_retcode)
  12392. #endif /* w_retcode */
  12393. #endif /* WEXITSTATUS */
  12394. #ifdef WEXITSTATUS
  12395. #define CK_FUN_OK
  12396. #endif /* WEXITSTATUS */
  12397. #endif /* WIFEXITED */
  12398. #ifdef NEXT
  12399. #define waitpid(pid,status,option) wait4((pid),(status),(option),NULL)
  12400. #else
  12401. #ifdef sony_news
  12402. #define waitpid(pid,status,option) wait4((pid),(status),(option),NULL)
  12403. #endif /* sony_news */
  12404. #endif /* NEXT */
  12405.  
  12406. #ifdef CK_FUN_OK
  12407.     PID_T pid;
  12408.  
  12409.     if (ttyfd == -1) {
  12410.     printf("?Sorry, device is not open\n");
  12411.     return(0);
  12412.     }
  12413.     if (nopush) {
  12414.     debug(F100,"ttruncmd fail: nopush","",0);
  12415.     return(0);
  12416.     }
  12417.     conres();                /* Make console normal  */
  12418.     if ((pid = fork()) == 0) {        /* Make a child fork */
  12419.     /* give it stdin,out to the line */
  12420.     if (priv_can())            /* Turn off privs. */
  12421.       exit(1);
  12422.     dup2(ttyfd, 0);
  12423.     dup2(ttyfd, 1);
  12424.     _exit(system(s) ? BAD_EXIT : 0);
  12425.     } else {
  12426.     WAIT_T status;            /* This is int for all but NeXT */
  12427.     SIGTYP (*istat)(), (*qstat)();
  12428.  
  12429.     if (pid == (PID_T) -1)        /* fork() failed? */
  12430.       return(0);
  12431.     istat = signal(SIGINT,SIG_IGN); /* Let the fork handle keyboard */
  12432.     qstat = signal(SIGQUIT,SIG_IGN); /* interrupts itself... */
  12433.  
  12434.     if (waitpid(pid, &status, 0) != pid) {
  12435.         printf("?Can't wait for child process?\r\n");
  12436.     } else {
  12437.         if (WIFEXITED(status)) {
  12438.         if (WEXITSTATUS(status)) {
  12439.             printf("?Command exit status: %d\r\n",
  12440.                WEXITSTATUS(status));
  12441.         } else r = 1;
  12442.         } else {
  12443.         printf("?Command did not exit - cancelling it now.\r\n");
  12444.         kill(pid, SIGKILL);
  12445.         }
  12446.     }
  12447.     signal(SIGINT,istat);        /* Restore interrupts */
  12448.     signal(SIGQUIT,qstat);
  12449.     }
  12450.     concb((char)escchr);        /* Restore console to CBREAK mode */
  12451. #else
  12452.     printf("?Sorry, can't execute this command - pieces missing.\n");
  12453. #endif /* CK_FUN_OK */
  12454.     return(r);
  12455. }
  12456. #else
  12457. int
  12458. ttruncmd(s) char *s; {
  12459.     PID_T pid;                /* pid of lower fork */
  12460.     int wstat;                /* for wait() */
  12461.     int x;
  12462. #ifdef OSF40
  12463. /*
  12464.   This is to shut up warnings from DECC - if it causes trouble, just remove
  12465.   it, since the warnings don't seem to affect correct operation at runtime.
  12466. */
  12467.     union wait statusp_w;
  12468.     int statusp;
  12469. #else
  12470.     int statusp;
  12471. #endif /* OSF40 */
  12472.  
  12473.     if (ttyfd == -1) {
  12474.     printf("?Sorry, device is not open\n");
  12475.     return(0);
  12476.     }
  12477.     if (nopush) {
  12478.     debug(F100,"ttruncmd fail: nopush","",0);
  12479.     return(0);
  12480.     }
  12481.     conres();                /* Make console normal  */
  12482.     pexitstat = -4;
  12483.     if ((pid = fork()) == 0) {        /* Make a child fork */
  12484.     if (priv_can())            /* Child: turn off privs. */
  12485.       exit(1);
  12486.     dup2(ttyfd, 0);            /* Give stdin/out to the line */
  12487.     dup2(ttyfd, 1);
  12488.     x = system(s);
  12489.     debug(F101,"ttruncmd system",s,x);
  12490.     _exit(x ? BAD_EXIT : 0);
  12491.     } else {
  12492.     SIGTYP (*istat)(), (*qstat)();
  12493.     if (pid == (PID_T) -1)        /* fork() failed? */
  12494.       return(0);
  12495.     istat = signal(SIGINT,SIG_IGN); /* Let the fork handle keyboard */
  12496.     qstat = signal(SIGQUIT,SIG_IGN); /* interrupts itself... */
  12497.  
  12498. #ifdef COMMENT
  12499.         while (((wstat = wait(
  12500. #ifdef OSF40
  12501.                   &statusp_w
  12502. #else
  12503.                   &statusp
  12504. #endif /* OSF40 */
  12505.                   )) != pid)
  12506.            && (wstat != -1))
  12507.       ;
  12508. #else  /* Not COMMENT */
  12509.         while (1) {
  12510.         wstat = wait(
  12511. #ifdef OSF40
  12512.              &statusp_w
  12513. #else
  12514.              &statusp
  12515. #endif /* OSF40 */
  12516.              );
  12517.         debug(F101,"ttruncmd wait","",wstat);
  12518.         if (wstat == pid || wstat == -1)
  12519.           break;
  12520.     }
  12521. #endif /* COMMENT */
  12522.  
  12523. #ifdef OSF40
  12524.     statusp = (*(int *)&(statusp_w));
  12525. #endif /* OSF40 */
  12526.  
  12527.     pexitstat = (statusp & 0xff) ? statusp : statusp >> 8;
  12528.     debug(F101,"ttruncmd wait statusp","",statusp);
  12529.     debug(F101,"ttruncmd wait pexitstat","",pexitstat);
  12530.     signal(SIGINT,istat);        /* Restore interrupts */
  12531.     signal(SIGQUIT,qstat);
  12532.     }
  12533.     concb((char)escchr);        /* Restore console to CBREAK mode */
  12534.     return(statusp == 0 ? 1 : 0);
  12535. }
  12536. #endif /* COMMENT */
  12537. #endif /* CK_REDIR */
  12538.  
  12539. struct tm *
  12540. #ifdef CK_ANSIC
  12541. cmdate2tm(char * date, int gmt)         /* date as "yyyymmdd hh:mm:ss" */
  12542. #else
  12543. cmdate2tm(date,gmt) char * date; int gmt;
  12544. #endif
  12545. {
  12546.     /* date as "yyyymmdd hh:mm:ss" */
  12547.     static struct tm _tm;
  12548.     time_t now;
  12549.  
  12550.     if (strlen(date) != 17 ||
  12551.     date[8] != ' ' ||
  12552.     date[11] != ':' ||
  12553.     date[14] != ':')
  12554.       return(NULL);
  12555.  
  12556.     time(&now);
  12557.     if (gmt)
  12558.       _tm = *gmtime(&now);
  12559.     else
  12560.       _tm = *localtime(&now);
  12561.     _tm.tm_year = (date[0]-'0')*1000 + (date[1]-'0')*100 +
  12562.                   (date[2]-'0')*10   + (date[3]-'0')-1900;
  12563.     _tm.tm_mon  = (date[4]-'0')*10   + (date[5]-'0')-1;
  12564.     _tm.tm_mday = (date[6]-'0')*10   + (date[7]-'0');
  12565.     _tm.tm_hour = (date[9]-'0')*10   + (date[10]-'0');
  12566.     _tm.tm_min  = (date[12]-'0')*10  + (date[13]-'0');
  12567.     _tm.tm_sec  = (date[15]-'0')*10  + (date[16]-'0');
  12568.  
  12569.     _tm.tm_wday = 0;
  12570.     _tm.tm_yday = 0;
  12571.  
  12572.     return(&_tm);
  12573. }
  12574.  
  12575. #ifdef OXOS
  12576. #undef kill
  12577. #endif /* OXOS */
  12578.  
  12579. #ifdef OXOS
  12580. int
  12581. priv_kill(pid, sig) int pid, sig; {
  12582.     int    i;
  12583.  
  12584.     if (priv_on())
  12585.     debug(F100,"priv_kill priv_on failed","",0);
  12586.     i = kill(pid, sig);
  12587.     if (priv_off())
  12588.     debug(F100,"priv_kill priv_off failed","",0);
  12589.     return(i);
  12590. }
  12591. #endif /* OXOS */
  12592.  
  12593. #ifdef BEBOX
  12594. #ifdef BE_DR_7
  12595. /*
  12596.   alarm() function not supplied with Be OS DR7 - this one contributed by
  12597.   Neal P. Murphy.
  12598. */
  12599.  
  12600. /*
  12601.   This should mimic the UNIX/POSIX alarm() function well enough, with the
  12602.   caveat that one's SIGALRM handler must call alarm_expired() to clean up vars
  12603.   and wait for the alarm thread to finish.
  12604. */
  12605. unsigned int
  12606. alarm(unsigned int seconds) {
  12607.     long time_left = 0;
  12608.  
  12609. /* If an alarm is active, turn it off, saving the unused time */
  12610.     if (alarm_thread != -1) {
  12611.         /* We'll be generous and count partial seconds as whole seconds. */
  12612.         time_left = alarm_struct.time -
  12613.       ((system_time() - time_started) / 1000000.0);
  12614.  
  12615.         /* Kill the alarm thread */
  12616.         kill_thread (alarm_thread);
  12617.  
  12618.         /* We need to clean up as though the alarm occured. */
  12619.         time_started = 0;
  12620.         alarm_struct.thread = -1;
  12621.         alarm_struct.time = 0;
  12622.         alarm_expired();
  12623.     }
  12624.  
  12625. /* Set a new alarm clock, if requested. */
  12626.     if (seconds > 0) {
  12627.         alarm_struct.thread = find_thread(NULL);
  12628.         alarm_struct.time = seconds;
  12629.         time_started = system_time();
  12630.         alarm_thread = spawn_thread (do_alarm,
  12631.                                      "alarm_thread",
  12632.                                      B_NORMAL_PRIORITY,
  12633.                                      (void *) &alarm_struct
  12634.                      );
  12635.         resume_thread (alarm_thread);
  12636.     }
  12637.  
  12638. /* Now return [unused time | 0] */
  12639.     return ((unsigned int) time_left);
  12640. }
  12641.  
  12642. /*
  12643.   This function is the departure from UNIX/POSIX alarm handling. In the case
  12644.   of Be's missing alarm() function, this stuff needs to be done in the SIGALRM
  12645.   handler. When Be implements alarm(), this function call can be eliminated
  12646.   from user's SIGALRM signal handlers.
  12647. */
  12648.  
  12649. void
  12650. alarm_expired(void) {
  12651.     long ret_val;
  12652.  
  12653.     if (alarm_thread != -1) {
  12654.         wait_for_thread (alarm_thread, &ret_val);
  12655.         alarm_thread = -1;
  12656.     }
  12657. }
  12658.  
  12659. /*
  12660.   This is the function that snoozes the requisite number of seconds and then
  12661.   SIGALRMs the calling thread. Note that kill() wants a pid_t arg, whilst Be
  12662.   uses thread_id; currently they are both typdef'ed as long, but I'll do the
  12663.   cast anyway. This function is run in a separate thread.
  12664. */
  12665.  
  12666. long
  12667. do_alarm (void *alarm_struct) {
  12668.     snooze ((double) ((struct ALARM_STRUCT *) alarm_struct)->time * 1000000.0);
  12669.     kill ((pid_t)((struct ALARM_STRUCT *) alarm_struct)->thread, SIGALRM);
  12670.     time_started = 0;
  12671.     ((struct ALARM_STRUCT *) alarm_struct)->thread = -1;
  12672.     ((struct ALARM_STRUCT *) alarm_struct)->time = 0;
  12673. }
  12674. #endif /* BE_DR_7 */
  12675. #endif /* BEBOX */
  12676.  
  12677. #ifdef Plan9
  12678.  
  12679. int
  12680. p9ttyctl(char letter, int num, int param) {
  12681.     char cmd[20];
  12682.     int len;
  12683.  
  12684.     if (ttyctlfd < 0)
  12685.       return -1;
  12686.  
  12687.     cmd[0] = letter;
  12688.     if (num)
  12689.       len = sprintf(cmd + 1, "%d", param) + 1;
  12690.     else {
  12691.     cmd[1] = param;
  12692.     len = 2;
  12693.     }
  12694.     if (write(ttyctlfd, cmd, len) == len) {
  12695.     cmd[len] = 0;
  12696.     /* fprintf(stdout, "wrote '%s'\n", cmd); */
  12697.     return 0;
  12698.     }
  12699.     return -1;
  12700. }
  12701.  
  12702. int
  12703. p9ttyparity(char l) {
  12704.     return p9ttyctl('p', 0, l);
  12705. }
  12706.  
  12707. int
  12708. p9tthflow(int flow, int status) {
  12709.     return p9ttyctl('m', 1, status);
  12710. }
  12711.  
  12712. int
  12713. p9ttsspd(int cps) {
  12714.     if (p9ttyctl('b', 1, cps * 10) < 0)
  12715.       return -1;
  12716.     ttylastspeed = cps * 10;
  12717.     return 0;
  12718. }
  12719.  
  12720. int
  12721. p9openttyctl(char *ttname) {
  12722.     char name[100];
  12723.  
  12724.     if (ttyctlfd >= 0) {
  12725.     close(ttyctlfd);
  12726.     ttyctlfd = -1;
  12727.     ttylastspeed = -1;
  12728.     }
  12729.     sprintf(name, "%sctl", ttname);
  12730.     ttyctlfd = open(name, 1);
  12731.     return ttyctlfd;
  12732. }
  12733.  
  12734. int
  12735. p9concb() {
  12736.     if (consctlfd >= 0) {
  12737.     if (write(consctlfd, "rawon", 5) == 5)
  12738.       return 0;
  12739.     }
  12740.     return -1;
  12741. }
  12742.  
  12743. int
  12744. p9conbin() {
  12745.     return p9concb();
  12746. }
  12747.  
  12748. int
  12749. p9conres() {
  12750.     if (consctlfd >= 0) {
  12751.     if (write(consctlfd, "rawoff", 6) == 6)
  12752.       return 0;
  12753.     }
  12754.     return -1;
  12755. }
  12756.  
  12757. int
  12758. p9sndbrk(int msec) {
  12759.     if (ttyctlfd >= 0) {
  12760.     char cmd[20];
  12761.     int i = sprintf(cmd, "k%d", msec);
  12762.     if (write(ttyctlfd, cmd, i) == i)
  12763.       return 0;
  12764.     }
  12765.     return -1;
  12766. }
  12767.  
  12768. int
  12769. conwrite(char *buf, int n) {
  12770.     int x;
  12771.     static int length = 0;
  12772.     static int holdingcr = 0;
  12773.     int normal = 0;
  12774.     for (x = 0; x < n; x++) {
  12775.     char c = buf[x];
  12776.     if (c == 007) {
  12777.         if (normal) {
  12778.         write(1, buf + (x - normal), normal);
  12779.         length += normal;
  12780.         normal = 0;
  12781.         }
  12782.         /* write(noisefd, "1000 300", 8); */
  12783.         holdingcr = 0;
  12784.     } else if (c == '\r') {
  12785.         if (normal) {
  12786.         write(1, buf + (x - normal), normal);
  12787.         length += normal;
  12788.         normal = 0;
  12789.         }
  12790.         holdingcr = 1;
  12791.     } else if (c == '\n') {
  12792.         write(1, buf + (x - normal), normal + 1);
  12793.         normal = 0;
  12794.         length = 0;
  12795.         holdingcr = 0;
  12796.     } else if (c == '\b') {
  12797.         if (normal) {
  12798.         write(1, buf + (x - normal), normal);
  12799.         length += normal;
  12800.         normal = 0;
  12801.         }
  12802.         if (length) {
  12803.         write(1, &c, 1);
  12804.         length--;
  12805.         }
  12806.         holdingcr = 0;
  12807.     } else {
  12808.         if (holdingcr) {
  12809.         char b = '\b';
  12810.         while (length-- > 0)
  12811.           write(1, &b, 1);
  12812.         length = 0;    /* compiler bug */
  12813.         }
  12814.         holdingcr = 0;
  12815.         normal++;
  12816.     }
  12817.     }
  12818.     if (normal) {
  12819.     write(1, buf + (x - normal), normal);
  12820.     length += normal;
  12821.     }
  12822.     return n;
  12823. }
  12824.  
  12825. void
  12826. conprint(char *fmt, ...) {
  12827.     char buf[1000];
  12828.  
  12829.     va_list ap;
  12830.     int i;
  12831.  
  12832.     va_start(ap, fmt);
  12833.     i = vsprintf(buf, fmt, ap);
  12834.     conwrite(buf, i);
  12835. }
  12836. #endif /* Plan9 */
  12837.  
  12838. /* fprintf, printf, perror replacements... */
  12839.  
  12840. /* f p r i n t f */
  12841.  
  12842. #ifdef UNIX
  12843. #ifdef CK_ANSIC
  12844. #include <stdarg.h>
  12845. #else /* CK_ANSIC */
  12846. #include <varargs.h>
  12847. #endif /* CK_ANSIC */
  12848. static char str1[1024];
  12849. static char str2[1024];
  12850. #ifdef fprintf
  12851. #undef fprintf
  12852. int
  12853. #ifdef CK_ANSIC
  12854. ckxfprintf(FILE * file, const char * format, ...)
  12855. #else /* CK_ANSIC */
  12856. ckxfprintf(va_alist) va_dcl
  12857. #endif /* CK_ANSIC */
  12858. /* ckxfprintf */ {
  12859.     int i, j, len, got_cr;
  12860.     va_list args;
  12861.     int rc = 0;
  12862.  
  12863. #ifdef CK_ANSIC
  12864.     va_start(args, format);
  12865. #else /* CK_ANSIC */
  12866.     char * format;
  12867.     FILE * file;
  12868.     va_start(args);
  12869.     file = va_arg(args,FILE *);
  12870.     format = va_arg(args,char *);
  12871. #endif /* CK_ANSIC */
  12872.  
  12873.     if (!inserver || (file != stdout && file != stderr && file != stdin)) {
  12874.     rc = vfprintf(file,format,args);
  12875.     } else {
  12876.     unsigned int c;
  12877.         rc = vsprintf(str1, format, args);
  12878.         for (i = 0, j = 0, len = strlen(str1), got_cr = 0;
  12879.          i < len && j < 1022;
  12880.          i++, j++ ) {
  12881.         /* We can't use 255 as a case label because of signed chars */
  12882.         c = (unsigned)(str1[i] & 0xff);
  12883. #ifdef TNCODE
  12884.         if (c == 255) {
  12885.         if (got_cr && !TELOPT_ME(TELOPT_BINARY))
  12886.           str2[j++] = '\0';
  12887.         str2[j++] = IAC;
  12888.         str2[j] = IAC;
  12889.         got_cr = 0;
  12890.         } else
  12891. #endif /* TNCODE */
  12892.         switch (c) {
  12893.           case '\r':
  12894.                 if (got_cr
  12895. #ifdef TNCODE
  12896.             && !TELOPT_ME(TELOPT_BINARY)
  12897. #endif /* TNCODE */
  12898.             )
  12899.           str2[j++] = '\0';
  12900.                 str2[j] = str1[i];
  12901.                 got_cr = 1;
  12902.                 break;
  12903.           case '\n':
  12904.                 if (!got_cr)
  12905.           str2[j++] = '\r';
  12906.                 str2[j] = str1[i];
  12907.                 got_cr = 0;
  12908.                 break;
  12909.           default:
  12910.                 if (got_cr
  12911. #ifdef TNCODE
  12912.             && !TELOPT_ME(TELOPT_BINARY)
  12913. #endif /* TNCODE */
  12914.             )
  12915.           str2[j++] = '\0';
  12916.                 str2[j] = str1[i];
  12917.                 got_cr = 0;
  12918.             }
  12919.         }
  12920.         if (got_cr
  12921. #ifdef TNCODE
  12922.              && !TELOPT_ME(TELOPT_BINARY)
  12923. #endif /* TNCODE */
  12924.              )
  12925.             str2[j++] = '\0';
  12926. #ifdef CK_ENCRYPTION
  12927. #ifdef TNCODE
  12928.         if (TELOPT_ME(TELOPT_ENCRYPTION))
  12929.       ck_tn_encrypt(str2,j);
  12930. #endif /* TNCODE */
  12931. #endif /* CK_ENCRYPTION */
  12932. #ifdef CK_SSL
  12933.     if (inserver && ssl_active_flag) {
  12934.         /* Write using SSL */
  12935.         rc = SSL_write(ssl_con, str2, j);
  12936.         debug(F111,"ckxfprintf","SSL_write",rc);
  12937.     } else if (inserver && tls_active_flag) {
  12938.         /* Write using SSL */
  12939.         rc = SSL_write(tls_con, str2, j);
  12940.         debug(F111,"ckxfprintf","TLS_write",rc);
  12941.     } else
  12942. #endif /* CK_SSL */
  12943.         fwrite(str2,sizeof(char),j,stdout);
  12944.     }
  12945.     va_end(args);
  12946.     return(rc);
  12947. }
  12948. #endif /* fprintf */
  12949.  
  12950. /* p r i n t f */
  12951.  
  12952. #ifdef printf
  12953. #undef printf
  12954. int
  12955. #ifdef CK_ANSIC
  12956. ckxprintf(const char * format, ...)
  12957. #else /* CK_ANSIC */
  12958. ckxprintf(va_alist) va_dcl
  12959. #endif /* CK_ANSIC */
  12960. /* ckxprintf */ {
  12961.     int i, j, len, got_cr;
  12962.     va_list args;
  12963.     int rc = 0;
  12964.  
  12965. #ifdef CK_ANSIC
  12966.     va_start(args, format);
  12967. #else /* CK_ANSIC */
  12968.     char * format;
  12969.     va_start(args);
  12970.     format = va_arg(args,char *);
  12971. #endif /* CK_ANSIC */
  12972.  
  12973.     if (!inserver) {
  12974.     rc = vprintf(format, args);
  12975.     } else {
  12976.     unsigned int c;
  12977.         rc = vsprintf(str1, format, args);
  12978.         for (i = 0, j = 0, len = strlen(str1), got_cr=0;
  12979.          i < len && j < 1022;
  12980.          i++, j++ ) {
  12981.         c = (unsigned)(str1[i] & 0xff);
  12982. #ifdef TNCODE
  12983.         if (c == 255) {
  12984.         if (got_cr && !TELOPT_ME(TELOPT_BINARY))
  12985.           str2[j++] = '\0';
  12986.         str2[j++] = IAC;
  12987.         str2[j] = IAC;
  12988.         got_cr = 0;
  12989.         } else
  12990. #endif /* TNCODE */
  12991.         switch (c) {
  12992.           case '\r':
  12993.                 if (got_cr
  12994. #ifdef TNCODE
  12995.             && !TELOPT_ME(TELOPT_BINARY)
  12996. #endif /* TNCODE */
  12997.             )
  12998.           str2[j++] = '\0';
  12999.                 str2[j] = str1[i];
  13000.                 got_cr = 1;
  13001.                 break;
  13002.           case '\n':
  13003.                 if (!got_cr)
  13004.           str2[j++] = '\r';
  13005.                 str2[j] = str1[i];
  13006.                 got_cr = 0;
  13007.                 break;
  13008.           default:
  13009.                 if (got_cr
  13010. #ifdef TNCODE
  13011.             && !TELOPT_ME(TELOPT_BINARY)
  13012. #endif /* TNCODE */
  13013.             )
  13014.           str2[j++] = '\0';
  13015.                 str2[j] = str1[i];
  13016.                 got_cr = 0;
  13017.                 break;
  13018.         }
  13019.         }
  13020.         if (got_cr
  13021. #ifdef TNCODE
  13022.              && !TELOPT_ME(TELOPT_BINARY)
  13023. #endif /* TNCODE */
  13024.              )
  13025.             str2[j++] = '\0';
  13026. #ifdef CK_ENCRYPTION
  13027. #ifdef TNCODE
  13028.         if (TELOPT_ME(TELOPT_ENCRYPTION))
  13029.       ck_tn_encrypt(str2,j);
  13030. #endif /* TNCODE */
  13031. #endif /* CK_ENCRYPTION */
  13032. #ifdef CK_SSL
  13033.           if (inserver && ssl_active_flag) {
  13034.               /* Write using SSL */
  13035.               rc = SSL_write(ssl_con, str2, j);
  13036.               debug(F111,"ckxprintf","SSL_write",rc);
  13037.           } else if (inserver && tls_active_flag) {
  13038.               /* Write using SSL */
  13039.               rc = SSL_write(tls_con, str2, j);
  13040.               debug(F111,"ckxprintf","TLS_write",rc);
  13041.           } else
  13042. #endif /* CK_SSL */
  13043.         rc = fwrite(str2,sizeof(char),j,stdout);
  13044.     }
  13045.     va_end(args);
  13046.     return(rc);
  13047. }
  13048. #endif /* printf */
  13049.  
  13050. /*  p e r r o r  */
  13051.  
  13052. #ifdef perror
  13053. #undef perror
  13054. _PROTOTYP(char * ck_errstr,(VOID));
  13055. #ifdef NEXT
  13056. void
  13057. #else
  13058. #ifdef CK_SCOV5
  13059. void
  13060. #else
  13061. int
  13062. #endif /* CK_SCOV5 */
  13063. #endif /* NEXT */
  13064. #ifdef CK_ANSIC
  13065. ckxperror(const char * str)
  13066. #else /* CK_ANSIC */
  13067. ckxperror(str) char * str;
  13068. #endif /* CK_ANSIC */
  13069. /* ckxperror */ {
  13070.     char * errstr = ck_errstr();
  13071. #ifndef NEXT
  13072. #ifndef CK_SCOV5
  13073.     return
  13074. #endif /* CK_SCOV5 */
  13075. #endif /* NEXT */
  13076.       ckxprintf("%s%s %s\n",str,*errstr?":":"",errstr);
  13077. }
  13078. #endif /* perror */
  13079. #endif /* UNIX */
  13080.  
  13081. #ifdef MINIX2
  13082.  
  13083. /* Minix doesn't have a gettimeofday call. We fake one here using time(2) */
  13084.  
  13085. int
  13086. gettimeofday(struct timeval *tp, struct timezone *tzp) {
  13087.     tp->tv_usec = 0L;            /* Close enough for horseshoes */
  13088.     if(time(&(tp->tv_sec))==-1)
  13089.       return(-1);
  13090.     return(0);
  13091. }
  13092.  
  13093. /* Minix does not support symbolic links. We implement a version of
  13094.    readlink that always fails */
  13095.  
  13096. int
  13097. readlink(const char *path, void *buf, size_t bufsiz) {
  13098.     errno = ENOSYS;
  13099.     return(-1);
  13100. }
  13101. #endif /* MINIX2 */
  13102.