home *** CD-ROM | disk | FTP | other *** search
/ Columbia Kermit / kermit.zip / archives / cku208.zip / ckutio.c < prev    next >
C/C++ Source or Header  |  2003-03-26  |  424KB  |  14,473 lines

  1. #ifdef aegis
  2. char *ckxv = "Aegis Communications support, 8.0.301, 20 Aug 2002";
  3. #else
  4. #ifdef Plan9
  5. char *ckxv = "Plan 9 Communications support, 8.0.301, 20 Aug 2002";
  6. #else
  7. char *ckxv = "UNIX Communications support, 8.0.301, 20 Aug 2002";
  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, 2002,
  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. extern int nettype;            /* Defined in ckcmai.c */
  36.  
  37. /* Includes */
  38.  
  39. #include "ckcsym.h"            /* This must go first   */
  40. #include "ckcdeb.h"            /* This must go second  */
  41.  
  42. #ifdef OSF13
  43. #ifdef CK_ANSIC
  44. #ifdef _NO_PROTO
  45. #undef _NO_PROTO
  46. #endif /* _NO_PROTO */
  47. #endif /* CK_ANSIC */
  48. #endif /* OSF13 */
  49.  
  50. #include <errno.h>            /* System error numbers */
  51.  
  52. #ifdef __386BSD__
  53. #define ENOTCONN 57
  54. #else
  55. #ifdef __bsdi__
  56. #define ENOTCONN 57
  57. #else
  58. #ifdef __FreeBSD__
  59. #define ENOTCONN 57
  60. #endif /* __FreeBSD__ */
  61. #endif /* __bsdi__ */
  62. #endif /* __386BSD__ */
  63.  
  64. #ifdef SCO_OSR504
  65. #define NBBY 8
  66. #endif /* SCO_OSR504 */
  67.  
  68. #ifdef Plan9
  69. #define SELECT
  70. #include <sys/time.h>
  71. #include <select.h>
  72. #define FD_SETSIZE (3 * sizeof(long) * 8)
  73. static struct timeval tv;
  74. #endif /* Plan9 */
  75.  
  76. #ifdef CLIX
  77. #include <sys/time.h>
  78. #endif /* CLIX */
  79.  
  80. #include "ckcnet.h"            /* Symbols for network types. */
  81. #ifdef CK_SSL
  82. #include "ck_ssl.h"
  83. #endif /* CK_SSL */
  84.  
  85. /*
  86.   The directory-related includes are here because we need to test some
  87.   file-system-related symbols to find out which system we're being compiled
  88.   under.  For example, MAXNAMLEN is defined in BSD4.2 but not 4.1.
  89. */
  90. #ifdef SDIRENT                /* Directory bits... */
  91. #define DIRENT
  92. #endif /* SDIRENT */
  93.  
  94. #ifdef XNDIR
  95. #include <sys/ndir.h>
  96. #else /* !XNDIR */
  97. #ifdef NDIR
  98. #include <ndir.h>
  99. #else /* !NDIR, !XNDIR */
  100. #ifdef RTU
  101. #include "/usr/lib/ndir.h"
  102. #else /* !RTU, !NDIR, !XNDIR */
  103. #ifdef DIRENT
  104. #ifdef SDIRENT
  105. #include <sys/dirent.h>
  106. #else
  107. #include <dirent.h>
  108. #endif /* SDIRENT */
  109. #else /* !RTU, !NDIR, !XNDIR, !DIRENT, i.e. all others */
  110. #include <sys/dir.h>
  111. #endif /* DIRENT */
  112. #endif /* RTU */
  113. #endif /* NDIR */
  114. #endif /* XNDIR */
  115.  
  116. #ifdef QNX
  117. #include <sys/dev.h>
  118. #endif /* QNX */
  119.  
  120. #ifdef HPUX5
  121. #ifndef TCPSOCKET
  122. /* I don't know why this is needed here since we never reference bzero(). */
  123. /* But without it C-Kermit won't link in an HP-UX 5.xx non-TCP build. */
  124. void
  125. bzero(s,n) char *s; int n; {
  126.     extern char * memset();
  127.     memset(s,0,n);
  128. }
  129. #endif /* TCPSOCKET */
  130. #endif /* HPUX5 */
  131.  
  132. /* Definition of HZ, used in msleep() */
  133.  
  134. #ifdef MIPS
  135. #define HZ ( 1000 / CLOCK_TICK )
  136. #else  /* MIPS */
  137. #ifdef ATTSV
  138. #ifndef NAP
  139. #ifdef TRS16
  140. #define HZ ( 1000 / CLOCK_TICK )
  141. #endif /* TRS16 */
  142. #ifdef NAPHACK
  143. #define nap(x) (void)syscall(3112, (x))
  144. #define NAP
  145. #endif /* NAPHACK */
  146. #endif /* NAP */
  147. #endif /* ATTSV */
  148. #endif /* MIPS */
  149.  
  150. #ifdef M_UNIX
  151. #undef NGROUPS_MAX        /* Prevent multiple definition warnings */
  152. #endif /* M_UNIX */
  153.  
  154. /*
  155.   NOTE: HP-UX 8.0 has a <sys/poll.h>, but there is no corresponding
  156.   library routine, so _poll comes up undefined at link time.
  157. */
  158. #ifdef CK_POLL
  159. #ifndef AIXRS            /* IBM AIX needs special handling */
  160. #include <poll.h>        /* "standard" (SVID) i/o multiplexing, etc */
  161. #else /* AIXRS */
  162. #ifdef SVR4            /* AIX 3.2 is like SVID... */
  163. #include <poll.h>
  164. #else                /* But AIX 3.1 is not ... */
  165. #include <sys/poll.h>        /* The include file is in include/sys */
  166. #define events reqevents    /* And it does not map IBM-specific member */
  167. #define revents rtnevents    /* names to the System V equivalents */
  168. #endif /* SVR4 */
  169. #endif /* AIXRS */
  170. #endif /* CK_POLL */
  171.  
  172. #include <signal.h>                     /* Signals */
  173.  
  174. /* For setjmp and longjmp */
  175.  
  176. #ifndef ZILOG
  177. #include <setjmp.h>
  178. #else
  179. #include <setret.h>
  180. #endif /* ZILOG */
  181.  
  182. /*
  183.   The following test differentiates between 4.1 BSD and 4.2 & later.
  184.   If you have a 4.1BSD system with the DIRENT library, this test could
  185.   mistakenly diagnose 4.2BSD and then later enable the use of system calls
  186.   that aren't defined.  If indeed there are such systems, we can use some
  187.   other way of testing for 4.1BSD, or add yet another compile-time switch.
  188. */
  189. #ifdef BSD4
  190. #ifdef MAXNAMLEN
  191. #ifndef FT21                /* Except for Fortune. */
  192. #ifndef FT18
  193. #ifndef BELLV10                /* And Bell Labs Research UNIX V10 */
  194. #define BSD42
  195. #endif /* BELLV10 */
  196. #endif /* FT18 */
  197. #endif /* FT21 */
  198. #endif /* MAXNAMLEN */
  199. #endif /* BSD4 */
  200. /*
  201.   Minix 2.0 support added by Terry McConnell,
  202.   Syracuse University <tmc@barnyard.syr.edu>
  203.   No more sgtty interface, posix compliant.
  204. */
  205. #ifdef MINIX2
  206. #define _MINIX   /* Needed for some Minix header files */
  207. #undef MINIX     /* Old minix 1.0: used sgtty interface */
  208. #define BSD44ORPOSIX
  209. #define SVORPOSIX
  210. #define DCLTIMEVAL
  211. #define NOFILEH
  212. #include <sys/types.h>
  213. #include <sys/ioctl.h>
  214. #include <termios.h>
  215. #include <limits.h>
  216. #undef TIOCGETC    /* defined in sys/ioctl.h, but not really supported */
  217. #define TANDEM 0
  218. #endif /* MINIX2 */
  219.  
  220. /*
  221.  MINIX 1.0 support added by Charles Hedrick,
  222.  Rutgers University <hedrick@aramis.rutgers.edu>.
  223.  MINIX also has V7 enabled.
  224. */
  225. #ifdef MINIX
  226. #define TANDEM 0
  227. #define MYREAD
  228. #define NOSYSIOCTLH
  229. #include <limits.h>
  230. #endif /* MINIX */
  231.  
  232. #ifdef CK_REDIR        /* <sys/wait.h> needed only for REDIRECT command. */
  233. /*
  234.   If anybody can figure out how to make this work with NeXTSTEP, be
  235.   my guest!  (NeXTBlah/NeXTBlah/bsd/sys/wait.h does not define WEXITSTATUS)
  236. */
  237. #ifndef CK_WAIT_H            /* If wait.h not already included... */
  238. #ifdef OSF                /* force OSF to select POSIX wait */
  239. #ifdef _BSD                /* instead of BSD (see ckcdeb.h) */
  240. #define CK_OSF_BSD
  241. #undef _BSD
  242. #endif /* _BSD */
  243. #endif /* OSF */
  244. #include <sys/wait.h>            /* Include it */
  245. #ifdef OSF
  246. #ifdef CK_OSF_BSD
  247. #define _BSD                /* Restore it */
  248. #undef CK_OSF_BSD
  249. #endif /* CK_OSF_BSD */
  250. #endif /* OSF */
  251. #endif /* CK_WAIT_H */
  252. #endif /* CK_REDIR */
  253.  
  254. #include "ckuver.h"            /* Version herald */
  255. char *ckxsys = HERALD;
  256.  
  257. #ifdef CK_UTSNAME
  258. #include <sys/utsname.h>
  259.  
  260. #ifdef TRU64                /* Tru64 UNIX 4.0 and later */
  261. /* Verified on Tru64 4.0F - might break on 4.0E or earlier */
  262. #include <sys/sysinfo.h>        /* (don't know about OSF/1 or DU) */
  263. #include <machine/hal_sysinfo.h>
  264. #endif /* TRU64 */
  265.  
  266. #ifdef SOLARIS25            /* Solaris 2.5 and later */
  267. #include <sys/systeminfo.h>        /* (don't know about earlier ones) */
  268. #endif /* SOLARIS25 */
  269.  
  270. #ifdef UW7
  271. #ifndef SYS_NMLN
  272. #define SYS_NMLN 257
  273. #endif /* NMLN */
  274. #endif /* UW7 */
  275. #ifdef HPUX9PLUS
  276. static int hpis800 = 0;
  277. #endif /* HPUX9PLUS */
  278. #ifdef SYS_NMLN
  279. #define CK_SYSNMLN SYS_NMLN
  280. #else
  281. #ifdef _SYS_NMLN
  282. #define CK_SYSNMLN _SYS_NMLN
  283. #else
  284. #ifdef UTSLEN
  285. #define CK_SYSNMLN UTSLEN
  286. #else
  287. #define CK_SYSNMLN 31
  288. #endif /* UTSLEN */
  289. #endif /* _SYS_NMLN */
  290. #endif /* SYS_NMLN */
  291. char unm_mch[CK_SYSNMLN+1] = { '\0', '\0' };
  292. char unm_mod[CK_SYSNMLN+1] = { '\0', '\0' };
  293. char unm_nam[CK_SYSNMLN+1] = { '\0', '\0' };
  294. char unm_rel[CK_SYSNMLN+1] = { '\0', '\0' };
  295. char unm_ver[CK_SYSNMLN+1] = { '\0', '\0' };
  296. #endif /* CK_UTSNAME */
  297.  
  298. #ifdef CIE
  299. #include <stat.h>            /* For chasing symlinks, etc. */
  300. #else
  301. #include <sys/stat.h>
  302. #endif /* CIE */
  303.  
  304. /* UUCP lockfile material... */
  305.  
  306. #ifndef NOUUCP
  307. #ifdef USETTYLOCK
  308. #ifdef USE_UU_LOCK
  309. #ifdef __FreeBSD__
  310. #include <libutil.h>            /* FreeBSD */
  311. #else
  312. #include <util.h>            /* OpenBSD */
  313. #endif /* __FreeBSD */
  314. #endif /* USE_UU_LOCK */
  315. #else  /* USETTYLOCK */
  316.  
  317. /* Name of UUCP tty device lockfile */
  318.  
  319. #ifdef LINUXFSSTND
  320. #ifndef HDBUUCP
  321. #define HDBUUCP
  322. #endif /* HDBUUCP */
  323. #endif /* LINUXFSSTND */
  324.  
  325. #ifdef ACUCNTRL
  326. #define LCKDIR
  327. #endif /* ACUCNTRL */
  328.  
  329. /*
  330.   PIDSTRING means use ASCII string to represent pid in lockfile.
  331. */
  332. #ifndef PIDSTRING
  333. #ifdef HDBUUCP
  334. #define PIDSTRING
  335. #else
  336. #ifdef BSD44
  337. #define PIDSTRING
  338. #else
  339. #ifdef RTAIX
  340. #define PIDSTRING
  341. #else
  342. #ifdef AIXRS
  343. #define PIDSTRING
  344. #else
  345. #ifdef COHERENT
  346. #define PIDSTRING
  347. #endif /* COHERENT */
  348. #endif /* AIXRS */
  349. #endif /* RTAIX */
  350. #endif /* BSD44 */
  351. #endif /* HDBUUCP */
  352. #endif /* PIDSTRING */
  353.  
  354. /* Now the PIDSTRING exceptions... */
  355.  
  356. #ifdef PIDSTRING
  357. #ifdef HPUX
  358. #undef PIDSTRING
  359. #endif /* HPUX */
  360. #endif /* PIDSTRING */
  361.  
  362. #ifdef __bsdi__                /* BSDI (at least thru 1.1) */
  363. #ifdef PIDSTRING
  364. #undef PIDSTRING
  365. #endif /* PIDSTRING */
  366. #endif /* __bsdi__ */
  367.  
  368. #ifdef OSF32                /* Digital UNIX (OSF/1) 3.2 */
  369. #ifdef PIDSTRING
  370. #undef PIDSTRING
  371. #endif /* PIDSTRING */
  372. #endif /* OSF32 */
  373.  
  374. /*
  375.   LOCK_DIR is the name of the lockfile directory.
  376.   If LOCK_DIR is already defined (e.g. on command line), we don't change it.
  377. */
  378.  
  379. #ifndef LOCK_DIR
  380. #ifdef BSD44
  381. #ifdef __386BSD__
  382. #define LOCK_DIR "/var/spool/lock"
  383. #else
  384. #ifdef __FreeBSD__
  385. #define LOCK_DIR "/var/spool/lock"
  386. #else
  387. #ifdef __NetBSD__
  388. #define LOCK_DIR "/var/spool/lock"
  389. #else
  390. #ifdef __OpenBSD__
  391. #define LOCK_DIR "/var/spool/lock"
  392. #else
  393. /* So which ones is this for? */
  394. /* Probably original 4.4BSD on Vangogh */
  395. /* Plus who knows about Mac OS X... It doesn't even have a cu program */
  396. #define LOCK_DIR "/var/spool/uucp"
  397. #endif /* __OpenBSD__ */
  398. #endif /* __NetBSD__ */
  399. #endif /* __FreeBSD__ */
  400. #endif /* __386BSD__ */
  401. #else
  402. #ifdef DGUX430
  403. #define LOCK_DIR "/var/spool/locks"
  404. #else
  405. #ifdef HPUX10
  406. #define LOCK_DIR "/var/spool/locks"
  407. #else
  408. #ifdef RTAIX                /* IBM RT PC AIX 2.2.1 */
  409. #define LOCK_DIR "/etc/locks"
  410. #else
  411. #ifdef AIXRS
  412. #define LOCK_DIR "/etc/locks"
  413. #else
  414. #ifdef ISIII
  415. #define LOCK_DIR "/etc/locks"
  416. #else
  417. #ifdef HDBUUCP
  418. #ifdef M_SYS5
  419. #define LOCK_DIR "/usr/spool/uucp"
  420. #else
  421. #ifdef M_UNIX
  422. #define LOCK_DIR "/usr/spool/uucp"
  423. #else
  424. #ifdef SVR4
  425. #define LOCK_DIR "/var/spool/locks"
  426. #else
  427. #ifdef SUNOS4
  428. #define LOCK_DIR "/var/spool/locks"
  429. #else
  430. #ifdef LINUXFSSTND
  431. #define LOCK_DIR "/var/lock";
  432. #else
  433. #define LOCK_DIR "/usr/spool/locks"
  434. #endif /* LINUXFSSTND */
  435. #endif /* SUNOS4 */
  436. #endif /* SVR4 */
  437. #endif /* M_UNIX */
  438. #endif /* M_SYS5 */
  439. #else
  440. #ifdef LCKDIR
  441. #define LOCK_DIR "/usr/spool/uucp/LCK"
  442. #else
  443. #ifdef COHERENT
  444. #define LOCK_DIR "/usr/spool/uucp"
  445. #else
  446. #define LOCK_DIR "/usr/spool/uucp"
  447. #endif /* COHERENT */
  448. #endif /* LCKDIR */
  449. #endif /* HDBUUCP */
  450. #endif /* ISIII */
  451. #endif /* AIXRS */
  452. #endif /* RTAIX */
  453. #endif /* HPUX10 */
  454. #endif /* DGUX430 */
  455. #endif /* BSD44 */
  456. #endif /* !LOCK_DIR (outside ifndef) */
  457.  
  458. #ifdef OSF2                /* OSF/1 2.0 or later */
  459. #ifdef LOCK_DIR                /* (maybe 1.x too, who knows...) */
  460. #undef LOCK_DIR
  461. #define LOCK_DIR "/var/spool/locks"
  462. #endif /* LOCK_DIR */
  463. #endif /* OSF2 */
  464.  
  465. #ifdef COMMENT
  466. /* Sorry no more lockf() -- we lock first and THEN open the device. */
  467. #ifdef SVR4
  468. #ifndef BSD44
  469. #ifndef LOCKF
  470. #define LOCKF                /* Use lockf() on tty device in SVR4 */
  471. #endif /* LOCKF */
  472. #endif /* BSD44 */
  473. #endif /* SVR4 */
  474. #endif /* COMMENT */
  475.  
  476. #ifdef NOLOCKF                /* But NOLOCKF cancels LOCKF */
  477. #ifdef LOCKF
  478. #undef LOCKF
  479. #endif /* LOCKF */
  480. #endif /* NOLOCKF */
  481.  
  482. /* More about this below... */
  483.  
  484. #endif /* USETTYLOCK */
  485. #endif /* NOUUCP */
  486.  
  487. /*
  488.   MYREAD means use our internally defined nonblocking buffered read routine.
  489. */
  490. #ifdef ATTSV
  491. #define MYREAD
  492. #endif /* ATTSV */
  493.  
  494. #ifdef ATT7300
  495. #ifndef MYREAD
  496. #define MYREAD
  497. #endif /* MYREAD */
  498. /* bits for attmodem: internal modem in use, restart getty */
  499. #define ISMODEM 1
  500. #define DOGETY 512
  501. #endif  /* ATT7300 */
  502.  
  503. #ifdef BSD42
  504. #define MYREAD
  505. #endif /* BSD42 */
  506.  
  507. #ifdef POSIX
  508. #define MYREAD
  509. #endif /* POSIX */
  510. #ifdef __bsdi__
  511. #ifndef O_NDELAY
  512. #define O_NDELAY O_NONBLOCK
  513. #endif /* O_NDELAY */
  514. #endif /* __bsdi__ */
  515.  
  516. /*
  517.  Variables available to outside world:
  518.  
  519.    dftty  -- Pointer to default tty name string, like "/dev/tty".
  520.    dfloc  -- 0 if dftty is console, 1 if external line.
  521.    dfprty -- Default parity
  522.    dfflow -- Default flow control
  523.    ckxech -- Flag for who echoes console typein:
  524.      1 - The program (system echo is turned off)
  525.      0 - The system (or front end, or terminal).
  526.    functions that want to do their own echoing should check this flag
  527.    before doing so.
  528.  
  529.    flfnam  -- Name of lock file, including its path, e.g.,
  530.                 "/usr/spool/uucp/LCK..cul0" or "/etc/locks/tty77"
  531.    lkflfn  -- Name of link to lock file, including its paths
  532.    haslock -- Flag set if this kermit established a uucp lock.
  533.    lockpid -- PID of other process that has desired line open, as string.
  534.    backgrd -- Flag indicating program executing in background ( & on
  535.                 end of shell command). Used to ignore INT and QUIT signals.
  536.    rtu_bug -- Set by stptrap().  RTU treats ^Z as EOF (but only when we handle
  537.                 SIGTSTP)
  538.  
  539.  Functions for assigned communication line (either external or console tty):
  540.  
  541.    sysinit()               -- System dependent program initialization
  542.    syscleanup()            -- System dependent program shutdown
  543.    ttopen(ttname,local,mdmtyp,timo) -- Open the named tty for exclusive access.
  544.    ttclos()                -- Close & reset the tty, releasing any access lock.
  545.    ttsspd(cps)             -- Set the transmission speed of the tty.
  546.    ttgspd()                -- Get (read) the the transmission speed of the tty.
  547.    ttpkt(speed,flow,parity) -- Put the tty in packet mode and set the speed.
  548.    ttvt(speed,flow)        -- Put the tty in virtual terminal mode.
  549.                                 or in DIALING or CONNECTED modem control state.
  550.    ttres()                 -- Restore original tty modes.
  551.    ttscarr(carrier)        -- Set carrier control mode, on/off/auto.
  552.    ttinl(dest,max,timo)    -- Timed read line from the tty.
  553.    ttinc(timo)             -- Timed read character from tty.
  554.    myread()                -- Raw mode bulk buffer read, gives subsequent
  555.                                 chars one at a time and simulates FIONREAD.
  556.    myunrd(c)               -- Places c back in buffer to be read (one only)
  557.    ttchk()                 -- See how many characters in tty input buffer.
  558.    ttxin(n,buf)            -- Read n characters from tty (untimed).
  559.    ttol(string,length)     -- Write a string to the tty.
  560.    ttoc(c)                 -- Write a character to the tty.
  561.    ttflui()                -- Flush tty input buffer.
  562.    ttsndb()                -- Send BREAK signal.
  563.    ttsndlb()               -- Send Long BREAK signal.
  564.  
  565.    ttlock(ttname)          -- "Lock" tty device against uucp collisions.
  566.    ttunlck()               -- Unlock tty device.
  567.  
  568.                               For ATT7300/Unix PC, System V:
  569.    attdial(ttname,speed,telnbr) -- dials ATT7300/Unix PC internal modem
  570.    offgetty(ttname)        -- Turns off getty(1m) for comms line
  571.    ongetty(ttname)         -- Restores getty() to comms line
  572. */
  573.  
  574. /*
  575. Functions for console terminal:
  576.  
  577.    congm()   -- Get console terminal modes.
  578.    concb(esc) -- Put the console in single-character wakeup mode with no echo.
  579.    conbin(esc) -- Put the console in binary (raw) mode.
  580.    conres()  -- Restore the console to mode obtained by congm().
  581.    conoc(c)  -- Unbuffered output, one character to console.
  582.    conol(s)  -- Unbuffered output, null-terminated string to the console.
  583.    conola(s) -- Unbuffered output, array of strings to the console.
  584.    conxo(n,s) -- Unbuffered output, n characters to the console.
  585.    conchk()  -- Check if characters available at console (bsd 4.2).
  586.                 Check if escape char (^\) typed at console (System III/V).
  587.    coninc(timo)  -- Timed get a character from the console.
  588.    congks(timo)  -- Timed get keyboard scan code.
  589.    conint()  -- Enable terminal interrupts on the console if not background.
  590.    connoi()  -- Disable terminal interrupts on the console if not background.
  591.  
  592. Time functions
  593.  
  594.    msleep(m) -- Millisecond sleep
  595.    ztime(&s) -- Return pointer to date/time string
  596.    rtimer() --  Reset timer
  597.    gtimer()  -- Get elapsed time since last call to rtimer()
  598. */
  599.  
  600. /* Conditional Includes */
  601.  
  602. /* Whether to include <sys/file.h> */
  603.  
  604. #ifdef RTU                /* RTU doesn't */
  605. #define NOFILEH
  606. #endif /* RTU */
  607.  
  608. #ifdef CIE                /* CIE does. */
  609. #undef NOFILEH
  610. #endif /* CIE */
  611.  
  612. #ifdef BSD41                /* 4.1 BSD doesn't */
  613. #define NOFILEH
  614. #endif /* BSD41 */
  615.  
  616. #ifdef is68k                /* Integrated Solutions 68000 UNIX  */
  617. #define NOFILEH                /* e.g. on Plexux P60 and Sun-1 */
  618. #endif /* is68k */
  619.  
  620. #ifdef MINIX                /* MINIX */
  621. #define NOFILEH
  622. #endif /* MINIX */
  623.  
  624. #ifdef COHERENT                /* Coherent */
  625. #define NOFILEH
  626. #endif /* COHERENT */
  627.  
  628. #ifndef NOFILEH                /* Now include if selected. */
  629. #include <sys/file.h>
  630. #endif /* NOFILEH */
  631.  
  632. /* POSIX */
  633.  
  634. #ifdef BSD44ORPOSIX            /* POSIX uses termios.h */
  635. #define TERMIOS
  636. #ifdef __bsdi__
  637. #ifdef POSIX
  638. #undef _POSIX_SOURCE            /* Get extra stuff from termios.h */
  639. #endif /* POSIX */
  640. #endif /* __bsdi__ */
  641. #include <termios.h>
  642. #ifdef LINUX
  643. #include <sys/ioctl.h>
  644. #endif /* LINUX */
  645. #ifdef QNX16
  646. #include <ioctl.h>
  647. #else
  648. #ifdef QNX6
  649. #include <ioctl.h>
  650. #endif /* QNX6 */
  651. #endif /* QNX16 */
  652. #ifdef __bsdi__
  653. #ifdef POSIX
  654. #define _POSIX_SOURCE
  655. #endif /* POSIX */
  656. #endif /* __bsdi__ */
  657. #ifndef BSD44                /* Really POSIX */
  658. #ifndef CK_QNX32            /* was CK_QNX32 */
  659. #define NOSYSIOCTLH            /* No ioctl's allowed. */
  660. #undef ultrix                /* Turn off any ultrix features. */
  661. #endif /* CK_QNX32 */
  662. #endif /* BSD44 */
  663. #endif /* POSIX */
  664.  
  665. /* System III, System V */
  666.  
  667. #ifdef ATTSV
  668. #ifndef BSD44
  669. #ifndef POSIX
  670. #include <termio.h>
  671. #endif /* POSIX */
  672. #endif /* BSD44 */
  673. #ifdef TERMIOX
  674. /* Need this for termiox structure, RTS/CTS and DTR/CD flow control */
  675. #include <termiox.h>
  676.   struct termiox rctsx;
  677. #else
  678. #ifdef STERMIOX
  679. #ifdef SCO_OSR504
  680. /* Sorry, this is truly disgusting but it's SCO's fault. */
  681. #ifndef _SVID3
  682. #define _CK_SVID3_X
  683. #define _SVID3
  684. #endif /* _SVID3 */
  685. #endif /* SCO_OSR504 */
  686. #include <sys/termiox.h>
  687.   struct termiox rctsx;
  688. #ifdef CK_SVID3_X
  689. #undef _SVID3
  690. #undef CK_SVID3_X
  691. #endif /* CK_SVID3_X */
  692. #endif /* STERMIOX */
  693. #endif /* TERMIOX */
  694. #endif /* ATTSV */
  695.  
  696. #ifdef COHERENT            /* Use termio.h, not sgtty.h for Coherent */
  697. #include <termio.h>
  698. #endif /* COHERENT */
  699.  
  700. #ifdef MINIX                /* MINIX uses ioctl's */
  701. #define NOSYSIOCTLH            /* but has no <sys/ioctl.h> */
  702. #endif /* MINIX */
  703.  
  704. /* Others */
  705.  
  706. #ifndef NOSYSIOCTLH            /* Others use ioctl() */
  707. #ifdef SUN4S5
  708. /*
  709.   This is to get rid of cpp warning messages that occur because all of
  710.   these symbols are defined by both termios.h and ioctl.h on the SUN.
  711. */
  712. #undef ECHO
  713. #undef NL0
  714. #undef NL1
  715. #undef TAB0
  716. #undef TAB1
  717. #undef TAB2
  718. #undef XTABS
  719. #undef CR0
  720. #undef CR1
  721. #undef CR2
  722. #undef CR3
  723. #undef FF0
  724. #undef FF1
  725. #undef BS0
  726. #undef BS1
  727. #undef TOSTOP
  728. #undef FLUSHO
  729. #undef PENDIN
  730. #undef NOFLSH
  731. #endif /* SUN4S5 */
  732. #include <sys/ioctl.h>
  733. #endif /* NOSYSIOCTLH */
  734. /*
  735.   We really, really, REALLY want FIONREAD, because it is the only way to find
  736.   out not just *if* stuff is waiting to be read, but how much, which is
  737.   critical to our sliding-window and streaming procedures, not to mention
  738.   efficiency of CONNECT, etc.
  739. */
  740. #ifdef BELLV10
  741. #include <sys/filio.h>            /* For FIONREAD */
  742. #ifdef FIONREAD
  743. #define MYREAD
  744. #endif /* MYREAD */
  745. #endif /* BELLV10 */
  746.  
  747. #ifndef FIONREAD
  748. /* It wasn't found in ioctl.h or term*.h - try these places: */
  749. #ifdef UNIXWARE
  750. #include <sys/filio.h>
  751. #else
  752. #ifdef SOLARIS
  753. #include <sys/filio.h>
  754. #endif /* SOLARIS */
  755. #endif /* UNIXWARE */
  756. #endif /* FIONREAD */
  757.  
  758. #ifdef XENIX /* Was M_UNIX but XENIX implies M_UNIX and applies to XENIX too */
  759. /*
  760.   <sys/socket.h> included above via "ckcnet.h" defines FIONREAD as
  761.   something.  Due to this, in_chk() uses the FIONREAD instead of RDCHK
  762.   and the hot keys during file transfer (X to cancel file etc) do not
  763.   work because FIONREAD doesn't work even though it is defined.
  764.  
  765.   NOTE: This might also be true elsewhere.
  766. */
  767. #ifdef FIONREAD
  768. #undef FIONREAD
  769. #endif /* FIONREAD */
  770. #endif /* XENIX */
  771.  
  772. #ifdef CK_SCOV5                /* Ditto for SCO OpenServer 5.0 */
  773. #ifdef FIONREAD
  774. #undef FIONREAD
  775. #endif /* FIONREAD */
  776. #endif /* XENIX */
  777.  
  778. /* Whether to include <fcntl.h> */
  779.  
  780. #ifndef is68k                /* Only a few don't have this one. */
  781. #ifndef BSD41
  782. #ifndef FT21
  783. #ifndef FT18
  784. #ifndef COHERENT
  785. #include <fcntl.h>
  786. #endif /* COHERENT */
  787. #endif /* FT18 */
  788. #endif /* FT21 */
  789. #endif /* BSD41 */
  790. #endif /* not is68k */
  791.  
  792. #ifdef COHERENT
  793. #ifdef _I386
  794. #include <fcntl.h>
  795. #else
  796. #include <sys/fcntl.h>
  797. #endif /* _I386 */
  798. #endif /* COHERENT */
  799.  
  800. #ifdef ATT7300                /* Unix PC, internal modem dialer */
  801. #include <sys/phone.h>
  802. #endif /* ATT7300 */
  803.  
  804. #ifdef HPUX                /* HP-UX variations. */
  805. #define HPUXJOBCTL
  806. #include <sys/modem.h>            /* HP-UX modem signals */
  807. #ifdef hp9000s500            /* Model 500 */
  808. #undef HPUXJOBCTL
  809. #endif /* hp9000s500 */
  810. #ifdef HPUXPRE65
  811. #undef HPUXJOBCTL
  812. typedef long mflag;
  813. #endif /* HPUXPRE65 */
  814. #ifdef HPUXJOBCTL
  815. #include <sys/bsdtty.h>            /* HP-UX Berkeley tty support */
  816. #endif /* HPUXJOBCTL */
  817. #endif /* HPUX */
  818.  
  819. /*
  820.   Which time.h files to include... See ckcdeb.h for defaults.
  821.   Note that 0, 1, 2, or all 3 of these can be included according to
  822.   the symbol definitions.
  823. */
  824. #ifndef NOTIMEH
  825. #ifdef TIMEH
  826. #include <time.h>
  827. #endif /* TIMEH */
  828. #endif /* NOTIMEH */
  829.  
  830. #ifndef NOSYSTIMEH
  831. #ifdef SYSTIMEH
  832. #include <sys/time.h>
  833. #endif /* SYSTIMEH */
  834. #endif /* NOSYSTIMEH */
  835.  
  836. #ifndef NOSYSTIMEBH
  837. #ifdef SYSTIMEBH
  838. #include <sys/timeb.h>
  839. #endif /* SYSTIMEBH */
  840. #endif /* NOSYSTIMEBH */
  841.  
  842. #ifndef NODCLTIMEVAL
  843. #ifdef DCLTIMEVAL
  844. /*
  845.   In certain POSIX builds (like Unixware 7), <[sys/]time.h> refuses to
  846.   define the structs we need to access the higher speeds, so we have to
  847.   do it ourselves.
  848. */
  849. struct timeval {
  850.     long tv_sec;
  851.     long tv_usec;
  852. };
  853. struct timezone {
  854.     int tz_minuteswest;
  855.     int tz_dsttime;
  856. };
  857. #endif /* DCLTIMEVAL */
  858. #endif /* NODCLTIMEVAL */
  859.  
  860. #ifdef __linux__
  861. /* THIS IS OBSOLETE since about Linux 0.92 */
  862. #ifdef OLINUXHISPEED
  863. #include <linux/serial.h>
  864. #endif /* OLINUXHISPEED */
  865. #ifdef __alpha__            /* Linux on DEC Alpha */
  866. #ifndef __GLIBC__            /* But not with glibc */
  867. #include <asm/termios.h>
  868. #endif /* __GLIBC__ */
  869. #endif /* __alpha__ */
  870. #endif /* __linux__ */
  871.  
  872. #ifdef NOIEXTEN                /* This is broken on some systems */
  873. #undef IEXTEN                /* like Convex/OS 9.1 */
  874. #endif /* NOIEXTEN */
  875. #ifndef IEXTEN                /* Turn off ^O/^V processing. */
  876. #define IEXTEN 0            /* Needed, at least, on BSDI. */
  877. #endif /* IEXTEN */
  878. /*
  879.   Pick up definitions needed for select() if we don't have them already.
  880.   Normally they come from <sys/types.h> but some systems get them from
  881.   <sys/select.h>...  Rather than hardwire all of them into the source, we
  882.   include it if SELECT_H is defined in compile-time CFLAGS.
  883. */
  884. #ifndef SCO_OSR504
  885. #ifdef SELECT_H
  886. #include <sys/select.h>
  887. #endif /* SELECT_H */
  888. #endif /* SCO_OSR504 */
  889.  
  890. #ifdef aegis
  891. #include "/sys/ins/base.ins.c"
  892. #include "/sys/ins/error.ins.c"
  893. #include "/sys/ins/ios.ins.c"
  894. #include "/sys/ins/sio.ins.c"
  895. #include "/sys/ins/pad.ins.c"
  896. #include "/sys/ins/time.ins.c"
  897. #include "/sys/ins/pfm.ins.c"
  898. #include "/sys/ins/pgm.ins.c"
  899. #include "/sys/ins/ec2.ins.c"
  900. #include "/sys/ins/type_uids.ins.c"
  901. #include <default_acl.h>
  902. #undef TIOCEXCL
  903. #undef FIONREAD
  904. #endif /* aegis */
  905.  
  906. #ifdef sxaE50                /* PFU Compact A SX/A TISP V10/L50 */
  907. #undef FIONREAD
  908. #endif /* sxaE50 */
  909.  
  910. /* The following #defines are catch-alls for those systems */
  911. /* that didn't have or couldn't find <file.h>... */
  912.  
  913. #ifndef FREAD
  914. #define FREAD 0x01
  915. #endif /* FREAD */
  916.  
  917. #ifndef FWRITE
  918. #define FWRITE 0x10
  919. #endif /* FWRITE */
  920.  
  921. #ifndef O_RDONLY
  922. #define O_RDONLY 000
  923. #endif /* O_RDONLY */
  924.  
  925. #ifdef SVORPOSIX
  926. /*
  927.   Modem signals are also forbidden in the POSIX world.  But some POSIX-based
  928.   platforms let us at them anyway if we know where to look.
  929. */
  930. #ifndef NEEDMDMDEFS
  931. /* Doesn't work for Linux */
  932. #ifdef UNIXWARE7
  933. #define NEEDMDMDEFS
  934. #endif /* UNIXWARE7 */
  935. #endif /* NEEDMDMDEFS */
  936.  
  937. #ifdef NEEDMDMDEFS
  938. #ifndef TIOCMGET
  939. #define TIOCMGET (('t'<<8)|29)
  940. #endif /* TIOCMGET */
  941.  
  942. #ifndef TIOCM_DTR
  943. #define TIOCM_DTR 0x0002
  944. #endif /* TIOCM_DTR */
  945. #ifndef TIOCM_RTS
  946. #define TIOCM_RTS 0x0004
  947. #endif /* TIOCM_RTS */
  948. #ifndef TIOCM_CTS
  949. #define TIOCM_CTS 0x0020
  950. #endif /* TIOCM_CTS */
  951. #ifndef TIOCM_CAR
  952. #define TIOCM_CAR 0x0040
  953. #endif /* TIOCM_CAR */
  954. #ifndef TIOCM_RNG
  955. #define TIOCM_RNG 0x0080
  956. #endif /* TIOCM_RNG */
  957. #ifndef TIOCM_DSR
  958. #define TIOCM_DSR 0x0100
  959. #endif /* TIOCM_DSR */
  960. #endif /* NEEDMDMDEFS */
  961. #endif /* SVORPOSIX */
  962.  
  963. /* Declarations */
  964.  
  965. #ifdef OXOS
  966. #undef TCGETA
  967. #undef TCSETA
  968. #undef TCSETAW
  969. #undef TCSETAF
  970. #define TCGETA TCGETS
  971. #define TCSETA TCSETS
  972. #define TCSETAW TCSETSW
  973. #define TCSETAF TCSETSF
  974. #define termio termios
  975. #endif /* OXOS */
  976.  
  977. #ifdef SVORPOSIX            /* AT&T Sys V or POSIX */
  978. #ifdef UNIXWAREPOSIX            /* UnixWare 7 POSIX build */
  979. /*
  980.   In Unixware POSIX builds, <[sys/]time.h> refuses to define the
  981.   structs we need to access the higher speeds, so we have to do it
  982.   ourselves.
  983. */
  984. struct timeval {
  985.     long tv_sec;
  986.     long tv_usec;
  987. };
  988. struct timezone {
  989.     int tz_minuteswest;
  990.     int tz_dsttime;
  991. };
  992. #endif /* UNIXWAREPOSIX */
  993. #endif /* SVORPOSIX */
  994.  
  995. #ifdef __GNUC__
  996. #ifdef XENIX
  997. /*
  998.   Because Xenix <time.h> doesn't declare time() if we're using gcc.
  999. */
  1000. time_t time();
  1001. #endif /* XENIX */
  1002. #endif /* __GNUC__ */
  1003.  
  1004. /* Special stuff for V7 input buffer peeking */
  1005.  
  1006. #ifdef  V7
  1007. int kmem[2] = { -1, -1};
  1008. char *initrawq(), *qaddr[2]={0,0};
  1009. #define CON 0
  1010. #define TTY 1
  1011. #endif /* V7 */
  1012.  
  1013. /* dftty is the device name of the default device for file transfer */
  1014. /* dfloc is 0 if dftty is the user's console terminal, 1 if an external line */
  1015.  
  1016. #ifdef BEOS
  1017.     char * dftty = NULL;
  1018.     char * dfmdm = "none";
  1019.     int dfloc = 0;                  /* that goes in local mode by default */
  1020. #else
  1021. #ifndef DFTTY
  1022. #ifdef PROVX1
  1023.     char *dftty = "/dev/com1.dout"; /* Only example so far of a system */
  1024.     char *dfmdm = "none";
  1025.     int dfloc = 1;                  /* that goes in local mode by default */
  1026. #else
  1027.     char *dftty = CTTNAM;               /* Remote by default, use normal */
  1028.     char *dfmdm = "none";
  1029.     int dfloc = 0;                      /* controlling terminal name. */
  1030. #endif /* PROVX1 */
  1031. #else
  1032.     char *dftty = DFTTY;        /* Default location specified on */
  1033.     char *dfmdm = "none";        /* command line. */
  1034.     int dfloc = 1;                      /* controlling terminal name. */
  1035. #endif /* DFTTY */
  1036. #endif /* BEOS */
  1037.  
  1038. #define CON_RES 0            /* Console state is "reset" */
  1039. #define CON_CB  1            /* Console state is CBREAK */
  1040. #define CON_BIN 2            /* Console state is binary */
  1041.     static int constate = CON_RES;
  1042.  
  1043. #define CONI_RES 0            /* Console interrupts are "reset" */
  1044. #define CONI_INT 1            /* Console intterupts are set */
  1045. #define CONI_NOI 2            /* Console intterupts are disabled */
  1046.     static int conistate = CONI_RES;
  1047.  
  1048. #ifdef CK_SMALL
  1049. #define CONBUFSIZ 15
  1050. #else
  1051. #define CONBUFSIZ 255
  1052. #endif /* CK_SMALL */
  1053.     static char conbuf[CONBUFSIZ];    /* Console readahead buffer */
  1054.     static int  conbufn = 0;        /* Chars in readahead buffer */
  1055.     static char *conbufp = conbuf;    /* Next char in readahead buffer */
  1056.  
  1057.     char cttnam[DEVNAMLEN+1] = { '\0', '\0' }; /* Determined at runtime */
  1058.  
  1059. #ifdef RTU
  1060.     int rtu_bug = 0;            /* set to 1 when returning from SIGTSTP */
  1061. #endif /* RTU */
  1062.  
  1063.     int dfprty = DEFPAR;                /* Default parity (0 = none) */
  1064.     int ttprty = 0;                     /* The parity that is in use. */
  1065.     static int ttpmsk = 0xff;        /* Parity stripping mask. */
  1066.     int ttmdm = 0;                      /* Modem in use. */
  1067.     int ttcarr = CAR_AUT;        /* Carrier handling mode. */
  1068.     int dfflow = FLO_NONE;        /* Default flow control is NONE */
  1069.     int backgrd = 0;                    /* Assume in foreground (no '&' ) */
  1070. #ifdef F_SETFL
  1071.     int iniflags = -1;            /* fcntl flags for ttyfd */
  1072. #endif /* F_SETFL */
  1073.     int fdflag = 0;            /* Flag for redirected stdio */
  1074.     int ttfdflg = 0;            /* Open File descriptor was given */
  1075.     int tvtflg = 0;            /* Flag that ttvt has been called */
  1076.     long ttspeed = -1L;            /* For saving speed */
  1077.     int ttflow = -9;            /* For saving flow */
  1078.     int ttld = -1;            /* Line discipline */
  1079.  
  1080. #ifdef sony_news
  1081.     static int km_con = -1;        /* Kanji mode for console tty */
  1082.     static int km_ext = -1;        /* Kanji mode for external device */
  1083. #endif /* sony_news */
  1084.  
  1085. #ifdef PARSENSE
  1086.     static int needpchk = 1;        /* Need parity check */
  1087. #else
  1088.     static int needpchk = 0;
  1089. #endif /* PARSENSE */
  1090.  
  1091.     extern int stopbits;        /* Stop bits */
  1092. #ifdef HWPARITY
  1093. /*
  1094.   Unfortunately we must do this with global variables rather than through the
  1095.   tt...() APIs to avoid changing the APIs and the many modules that use them.
  1096.   If hwparity != 0, this indicates 8 data bits + parity, rather than 7 data
  1097.   bits + parity or 8 data bits and no parity, and overrides the regular parity
  1098.   variable, which is communicated to this module thru ttpkt(), and represented
  1099.   locally by the ttprty variable.
  1100. */
  1101.     extern int hwparity;        /* Hardware parity */
  1102. #endif /* HWPARITY */
  1103.  
  1104. #ifdef TCPSOCKET
  1105. #ifdef TCP_NODELAY
  1106. static int nodelay_sav = -1;
  1107. #endif /* TCP_NODELAY */
  1108. #endif /* TCPSOCKET */
  1109.  
  1110. static int sigint_ign = 0;        /* SIGINT is ignored */
  1111.  
  1112. /*
  1113.   Having this module rely on external globals is bad, but fixing this
  1114.   requires overhaul of the ck*tio.c modules for all the different operating
  1115.   systems supported by C-Kermit.  Left for a future release.
  1116. */
  1117. extern int ttnproto;            /* Defined in ckcnet.c */
  1118. extern int ttnet;            /* Defined in ckcnet.c */
  1119. extern int nopush, xfrcan, xfrchr, xfrnum; /* Defined in ckcmai.c */
  1120. extern int xsuspend, wasclosed;
  1121. extern int inserver, local;
  1122.  
  1123. int ckxech = 0; /* 0 if system normally echoes console characters, else 1 */
  1124.  
  1125. int ckmaxfiles = 0;            /* Max number of open files */
  1126.  
  1127. #ifdef CK_ENCRYPTION            /* Kerberos */
  1128. #include "ckuath.h"
  1129. extern int me_encrypt, u_encrypt;
  1130. #endif /* CK_ENCRYPTION */
  1131.  
  1132. /* Declarations of variables global within this module */
  1133.  
  1134. #ifdef TTLEBUF                /* See ckcnet.h */
  1135. int ttpush = -1;
  1136. #define LEBUFSIZ 4096
  1137. static CHAR le_buf[LEBUFSIZ];
  1138. static int le_start = 0, le_end = 0, le_data = 0;
  1139. #endif /* TTLEBUF */
  1140.  
  1141. static int gotsigs = 0;
  1142.  
  1143. static time_t tcount = (time_t)0;    /* Elapsed time counter */
  1144.  
  1145. static SIGTYP (*saval)()     = NULL;    /* For saving alarm() handler */
  1146. static SIGTYP (*savquit)()   = NULL;    /* and other signal handlers */
  1147. #ifdef SIGUSR1
  1148. static SIGTYP (*savusr1)()   = NULL;
  1149. #endif /* SIGUSR1 */
  1150. #ifdef SIGUSR2
  1151. static SIGTYP (*savusr2)()   = NULL;
  1152. #endif /* SIGUSR2 */
  1153. #ifdef SIGPIPE
  1154. static SIGTYP (*savpipe)()   = NULL;
  1155. #endif /* SIGPIPE */
  1156. #ifdef SIGDANGER
  1157. static SIGTYP (*savdanger)() = NULL;
  1158. #endif /* SIGDANGER */
  1159.  
  1160. #ifndef NOJC
  1161. static SIGTYP (*jchdlr)()    = NULL;    /* For checking suspend handler */
  1162. #endif /* NOJC */
  1163. static int jcshell = -1;        /* And flag for result */
  1164.  
  1165. /*
  1166.   BREAKNULS is defined for systems that simulate sending a BREAK signal
  1167.   by sending a bunch of NUL characters at low speed.
  1168. */
  1169. #ifdef PROVX1
  1170. #ifndef BREAKNULS
  1171. #define BREAKNULS
  1172. #endif /* BREAKNULS */
  1173. #endif /* PROVX1 */
  1174.  
  1175. #ifdef V7
  1176. #ifndef BREAKNULS
  1177. #define BREAKNULS
  1178. #endif /* BREAKNULS */
  1179. #endif /* V7 */
  1180.  
  1181. #ifdef BREAKNULS
  1182. static char                /* A string of nulls */
  1183. *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";
  1184. #endif /* BREAKNULS */
  1185.  
  1186. #ifdef CK_POSIX_SIG            /* Longjump buffers */
  1187. static sigjmp_buf sjbuf;        /* POSIX signal handling */
  1188. #else
  1189. static jmp_buf sjbuf;
  1190. #endif /* CK_POSIX_SIG */
  1191.  
  1192. #ifdef V7
  1193. static jmp_buf jjbuf;
  1194. #endif /* V7 */
  1195.  
  1196. /* static */                /* (Not static any more) */
  1197. int ttyfd = -1;                /* TTY file descriptor */
  1198.  
  1199. int ttpipe = 0;                /* NETCMD: Use pipe instead of ttyfd */
  1200. int ttpty  = 0;                         /* NETPTY: Use pty instead of ttfyd */
  1201.  
  1202. #ifdef NETCMD
  1203. #ifdef NETCONN
  1204. static int pipe0[2], pipe1[2];        /* Pipes for net i/o */
  1205. #endif /* NETCONN */
  1206. static PID_T ttpid = 0;            /* Process ID for fork */
  1207. static int fdin, fdout;            /* File descriptors for pipe */
  1208. static FILE * ttout = NULL;        /* File pointer for output pipe */
  1209. #ifdef DCLFDOPEN
  1210. /* fdopen() needs declaring because it's not declared in <stdio.h> */
  1211. _PROTOTYP( FILE * fdopen, (int, char *) );
  1212. #endif /* DCLFDOPEN */
  1213. #endif /* NETCMD */
  1214.  
  1215. extern int pexitstat, quiet;
  1216.  
  1217. #ifdef Plan9
  1218. int ttyctlfd  = -1;   /* TTY control channel - What? UNIX doesn't have one? */
  1219. int consctlfd = -1;            /* Console control channel */
  1220. int noisefd = -1;            /* tone channel */
  1221. static int ttylastspeed = -1;        /* So we can lie about the speed */
  1222. #endif /* Plan9 */
  1223.  
  1224. int telnetfd = 0;            /* File descriptor is for telnet */
  1225. #ifdef NETCONN
  1226. int x25fd = 0;                /* File descriptor is for X.25 */
  1227. #endif /* NETCONN */
  1228.  
  1229. char lockpid[16] = { '\0', '\0' };    /* PID stored in lockfile, as string */
  1230.  
  1231. static int lkf = 0,                     /* Line lock flag */
  1232.     cgmf = 0,                           /* Flag that console modes saved */
  1233.     xlocal = 0,                         /* Flag for tty local or remote */
  1234.     curcarr = 0;            /* Carrier mode: require/ignore. */
  1235.  
  1236. static int netconn = 0;            /* 1 if network connection active */
  1237.  
  1238. static char escchr;                     /* Escape or attn character */
  1239.  
  1240. #ifdef CK_SCO32V4
  1241. #include <sys/time.h>
  1242. #endif /* CK_SCO32V4 */
  1243.  
  1244. #ifdef HAVE_TV
  1245.     static struct timeval tv;        /* For getting time, from sys/time.h */
  1246. #endif /* HAVE_TV */
  1247. #ifdef HAVE_TZ
  1248.     static struct timezone tz;
  1249. #endif /* HAVE_TZ */
  1250.  
  1251. #ifdef OSF
  1252.     static struct timeb ftp;            /* And from sys/timeb.h */
  1253. #endif /* OSF */
  1254.  
  1255. #ifdef BSD29
  1256.     static long xclock;            /* For getting time from sys/time.h */
  1257.     static struct timeb ftp;            /* And from sys/timeb.h */
  1258. #endif /* BSD29 */
  1259.  
  1260. #ifdef BSD41
  1261.     static long xclock;            /* For getting time from sys/time.h */
  1262.     static struct timeb ftp;            /* And from sys/timeb.h */
  1263. #endif /* BSD41 */
  1264.  
  1265. #ifdef BELLV10
  1266.     static long xclock;            /* For getting time from sys/time.h */
  1267.     static struct timeb ftp;            /* And from sys/timeb.h */
  1268. #endif /* BELLV10 */
  1269.  
  1270. #ifdef FT21
  1271.     static long xclock;            /* For getting time from sys/time.h */
  1272.     static struct timeb ftp;            /* And from sys/timeb.h */
  1273. #endif /* FT21 */
  1274.  
  1275. #ifdef TOWER1
  1276.     static long xclock;            /* For getting time from sys/time.h */
  1277.     static struct timeb ftp;        /* And from sys/timeb.h */
  1278. #endif /* TOWER1 */
  1279.  
  1280. #ifdef COHERENT
  1281.     static long xclock;            /* For getting time from sys/time.h */
  1282.     static struct timeb ftp;        /* And from sys/timeb.h */
  1283. #endif /* COHERENT */
  1284.  
  1285. #ifdef V7
  1286.     static long xclock;
  1287. #endif /* V7 */
  1288.  
  1289. /* sgtty/termio information... */
  1290.  
  1291. #ifdef BSD44ORPOSIX            /* POSIX or BSD44 */
  1292.   static struct termios
  1293.     ttold, ttraw, tttvt, ttcur,
  1294.     ccold, ccraw, cccbrk;
  1295. #else                    /* BSD, V7, etc */
  1296.  
  1297. #ifdef COHERENT                /* Hack alert... */
  1298. #define ATTSV
  1299. #endif /* COHERENT */
  1300.  
  1301. #ifdef ATTSV
  1302.   static struct termio ttold = {0};    /* Init'd for word alignment, */
  1303.   static struct termio ttraw = {0};    /* which is important for some */
  1304.   static struct termio tttvt = {0};    /* systems, like Zilog... */
  1305.   static struct termio ttcur = {0};
  1306.   static struct termio ccold = {0};
  1307.   static struct termio ccraw = {0};
  1308.   static struct termio cccbrk = {0};
  1309. #else
  1310.   static struct sgttyb                  /* sgtty info... */
  1311.     ttold, ttraw, tttvt, ttcur,     /* for communication line */
  1312.     ccold, ccraw, cccbrk;        /* and for console */
  1313. #ifdef BELLV10
  1314.   static struct ttydevb            /* Device info... */
  1315.     tdold, tdcur;            /* for communication device */
  1316. #endif /* BELLV10 */
  1317. #ifdef TIOCGETC
  1318.   static struct tchars tchold, tchnoi;
  1319.  
  1320.   static int tcharf;
  1321. #endif /* TIOCGETC */
  1322. #ifdef TIOCGLTC
  1323.   static struct ltchars ltchold, ltchnoi;
  1324.   static int ltcharf;
  1325. #endif /* TIOCGLTC */
  1326.   int lmodef = 0;            /* Local modes */
  1327.   int lmode = 0;
  1328. #endif /* ATTSV */
  1329. #endif /* BSD44ORPOSIX */
  1330.  
  1331. #ifdef COMMENT
  1332. /* It picks up the speeds but they don't work */
  1333. #ifdef UNIXWARE                /* For higher serial speeds */
  1334. #ifdef UW7                /* in Unixware 7.0 */
  1335. #include <sys/asyc.h>            /* This picks up 57600 and 115200 */
  1336. #endif /* UW7 */
  1337. #endif /* UNIXWARE */
  1338. #endif /* COMMENT */
  1339.  
  1340. #ifdef PROVX1
  1341.   static struct sgttyb ttbuf;
  1342. #endif /* PROVX1 */
  1343.  
  1344. #ifdef ultrix
  1345. /* do we really need this? */
  1346.   static struct sgttyb vanilla;
  1347. #endif /* ultrix */
  1348.  
  1349. #ifdef ATT7300
  1350. static int attmodem = 0;                /* ATT7300 internal-modem status */
  1351. struct updata dialer = {0};        /* Condition dialer for data call */
  1352. #endif /* ATT7300 */
  1353.  
  1354. #ifndef NOUUCP
  1355. #define FLFNAML 128
  1356. #ifndef USETTYLOCK
  1357. #ifdef RTAIX
  1358. char lkflfn[FLFNAML] = { '\0', '\0' };    /* and possible link to it */
  1359. #endif /* RTAIX */
  1360. char lock2[FLFNAML] =  { '\0', '\0' };    /* Name of second lockfile */
  1361. #endif /* USETTYLOCK */
  1362. #else
  1363. #define FLFNAML 7
  1364. #endif /* NOUUCP */
  1365. char flfnam[FLFNAML+1] = { '\0', '\0' }; /* UUCP lock file path name */
  1366.  
  1367. int haslock = 0;            /* =1 if this kermit locked uucp */
  1368.  
  1369. #ifndef OXOS
  1370. #ifdef SVORPOSIX
  1371. static int conesc = 0;                  /* set to 1 if esc char (^\) typed */
  1372. #else
  1373. #ifdef V7
  1374. static int conesc = 0;
  1375. #else
  1376. #ifdef C70
  1377. static int conesc = 0;
  1378. #endif /* C70 */
  1379. #endif /* V7 */
  1380. #endif /* SVORPOSIX */
  1381. #endif /* OXOS */
  1382.  
  1383. /* Local copy of comm device name or network host */
  1384. static char ttnmsv[DEVNAMLEN+1] = { '\0', '\0' };
  1385. #ifdef USETTYLOCK
  1386. static char lockname[DEVNAMLEN+1];    /* Ditto, the part after "/dev/". */
  1387. #endif /* USETTYLOCK */
  1388.  
  1389. #ifdef aegis
  1390. static status_$t st;                    /* error status return value */
  1391. static short concrp = 0;                /* true if console is CRP pad */
  1392. static uid_$t ttyuid;                   /* tty type uid */
  1393. static uid_$t conuid;                   /* stdout type uid */
  1394.  
  1395. /* APOLLO Aegis main()
  1396.  * establish acl usage and cleanup handling
  1397.  *    this makes sure that CRP pads
  1398.  *    get restored to a usable mode
  1399.  */
  1400. main(argc,argv) int argc; char **argv; {
  1401.         status_$t status;
  1402.         pfm_$cleanup_rec dirty;
  1403.  
  1404.         PID_T pid = getpid();
  1405.  
  1406.         /* acl usage according to invoking environment */
  1407.         default_acl(USE_DEFENV);
  1408.  
  1409.         /* establish a cleanup continuation */
  1410.         status = pfm_$cleanup(dirty);
  1411.         if (status.all != pfm_$cleanup_set) {
  1412.                 /* only handle faults for the original process */
  1413.                 if (pid == getpid() && status.all > pgm_$max_severity) {
  1414.             /* blew up in main process */
  1415.             status_$t quo;
  1416.             pfm_$cleanup_rec clean;
  1417.  
  1418.             /* restore the console in any case */
  1419.             conres();
  1420.  
  1421.             /* attempt a clean exit */
  1422.             debug(F101, "cleanup fault status", "", status.all);
  1423.  
  1424.             /* doexit(), then send status to continuation */
  1425.             quo = pfm_$cleanup(clean);
  1426.             if (quo.all == pfm_$cleanup_set)
  1427.               doexit(pgm_$program_faulted,-1);
  1428.             else if (quo.all > pgm_$max_severity)
  1429.               pfm_$signal(quo); /* blew up in doexit() */
  1430.                 }
  1431.                 /* send to the original continuation */
  1432.                 pfm_$signal(status);
  1433.                 /*NOTREACHED*/
  1434.         }
  1435.         return(ckcmai(argc, argv));
  1436. }
  1437. #endif /* aegis */
  1438.  
  1439. /* ANSI-style prototypes for internal functions. */
  1440. /* Functions used outside this module are prototyped in ckcker.h. */
  1441.  
  1442. #ifdef apollo
  1443. _PROTOTYP( SIGTYP timerh, () );
  1444. _PROTOTYP( SIGTYP cctrap, () );
  1445. _PROTOTYP( SIGTYP esctrp, () );
  1446. _PROTOTYP( SIGTYP sig_ign, () );
  1447. #else
  1448. _PROTOTYP( SIGTYP timerh, (int) );
  1449. _PROTOTYP( SIGTYP cctrap, (int) );
  1450. _PROTOTYP( SIGTYP esctrp, (int) );
  1451. #endif /* apollo */
  1452. _PROTOTYP( int do_open, (char *) );
  1453. _PROTOTYP( static int in_chk, (int, int) );
  1454. _PROTOTYP( static int ttrpid, (char *) );
  1455. _PROTOTYP( static int ttchkpid, (char *) );
  1456. _PROTOTYP( static int ttlock, (char *) );
  1457. _PROTOTYP( static int ttunlck, (void) );
  1458. _PROTOTYP( int mygetbuf, (void) );
  1459. _PROTOTYP( int myfillbuf, (void) );
  1460. _PROTOTYP( VOID conbgt, (int) );
  1461. #ifdef ACUCNTRL
  1462. _PROTOTYP( VOID acucntrl, (char *, char *) );
  1463. #endif /* ACUCNTRL */
  1464.  
  1465. #ifdef BSD44ORPOSIX
  1466. _PROTOTYP( int carrctl, (struct termios *, int) );
  1467. #else
  1468. #ifdef ATTSV
  1469. _PROTOTYP( int carrctl, (struct termio *, int) );
  1470. #else
  1471. _PROTOTYP( int carrctl, (struct sgttyb *, int) );
  1472. #endif /* ATTSV */
  1473. #endif /* BSD44ORPOSIX */
  1474.  
  1475. #ifdef ATT7300
  1476. _PROTOTYP( int attdial, (char *, long, char *) );
  1477. _PROTOTYP( int offgetty, (char *) );
  1478. _PROTOTYP( int ongetty, (char *) );
  1479. #endif /* ATT7300 */
  1480.  
  1481. #ifdef BEOSORBEBOX
  1482. #ifdef SELECT
  1483.     /* BeOS is not capable of using SELECT on anything but sockets */
  1484. #undef SELECT
  1485. #endif /* SELECT */
  1486. #include <kernel/OS.h>
  1487. /* #ifdef BE_DR_7 */
  1488. static double time_started = 0.0;
  1489. struct ALARM_STRUCT {
  1490.     thread_id thread;
  1491.     int time;
  1492. };
  1493. static thread_id alarm_thread = -1;
  1494. static struct ALARM_STRUCT alarm_struct;
  1495. _PROTOTYP( long do_alarm, (void *) );
  1496. _PROTOTYP( unsigned int alarm, (unsigned int) );
  1497. _PROTOTYP( void alarm_expired, (void) );
  1498. /* #endif */ /* BE_DR_7 */
  1499. #endif /* BEOSORBEBOX */
  1500.  
  1501. #ifndef xunchar
  1502. #define xunchar(ch) (((ch) - 32 ) & 0xFF )    /* Character to number */
  1503. #endif /* xunchar */
  1504.  
  1505. #ifdef CK_ANSIC
  1506. static char *
  1507. xxlast(char *s, char c)
  1508. #else
  1509. static char *
  1510. xxlast(s,c) char *s; char c;
  1511. #endif /* CK_ANSIC */
  1512. /* xxlast */ {        /*  Last occurrence of character c in string s. */
  1513.     int i;
  1514.     for (i = (int)strlen(s); i > 0; i--)
  1515.       if (s[i-1] == c ) return(s + (i - 1));
  1516.     return(NULL);
  1517. }
  1518.  
  1519. /* Timeout handler for communication line input functions */
  1520.  
  1521. /*ARGSUSED*/
  1522. SIGTYP
  1523. timerh(foo) int foo; {
  1524.     ttimoff();
  1525. #ifdef BEOSORBEBOX
  1526. /* #ifdef BE_DR_7 */
  1527.     alarm_expired();
  1528. /* #endif */ /* BE_DR_7 */
  1529. #endif /* BEOSORBEBOX */
  1530. #ifdef CK_POSIX_SIG
  1531.     siglongjmp(sjbuf,1);
  1532. #else
  1533.     longjmp(sjbuf,1);
  1534. #endif /* CK_POSIX_SIG */
  1535. }
  1536.  
  1537. /*ARGSUSED*/
  1538. SIGTYP
  1539. xtimerh(foo) int foo; {            /* Like timerh() but does */
  1540. #ifdef BEOSORBEBOX            /* not reset the timer itslef */
  1541. /* #ifdef BE_DR_7 */
  1542.     alarm_expired();
  1543. /* #endif */ /* BE_DR_7 */
  1544. #endif /* BEOSORBEBOX */
  1545. #ifdef CK_POSIX_SIG
  1546.     siglongjmp(sjbuf,1);
  1547. #else
  1548.     longjmp(sjbuf,1);
  1549. #endif /* CK_POSIX_SIG */
  1550. }
  1551.  
  1552.  
  1553. /* Control-C trap for communication line input functions */
  1554.  
  1555. int cc_int;                /* Flag */
  1556. SIGTYP (* occt)();            /* For saving old SIGINT handler */
  1557.  
  1558. /*ARGSUSED*/
  1559. SIGTYP
  1560. cctrap(foo) int foo; {            /* Needs arg for ANSI C */
  1561.   cc_int = 1;                /* signal() prototype. */
  1562.   return;
  1563. }
  1564.  
  1565. /*  S Y S I N I T  --  System-dependent program initialization.  */
  1566.  
  1567. /*
  1568.  * ttgwsiz() returns:
  1569.  *    1    tt_rows and tt_cols are known, both altered, both > 0
  1570.  *    0    tt_rows and/or tt_cols are known, both altered, one or both <= 0
  1571.  *    -1   tt_rows and tt_cols are unknown and unaltered
  1572.  */
  1573.  
  1574. extern int tt_rows, tt_cols;
  1575.  
  1576. static int
  1577. xttgwsiz() {
  1578.     char *p;
  1579.     int rows = 0, cols = 0;
  1580.     p = getenv("LINES");
  1581.     debug(F110,"xttgwsiz LINES",p,0);
  1582.     if (p) {
  1583.     rows = atol(p);
  1584.     if (rows > 0) {
  1585.         p = getenv("COLUMNS");
  1586.         debug(F110,"xttgwsiz COLUMNS",p,0);
  1587.         if (p) {
  1588.         cols = atol(p);
  1589.         if (cols > 0) {
  1590.             tt_rows = rows;
  1591.             tt_cols = cols;
  1592.             return(1);
  1593.         }
  1594.         return(0);
  1595.         }
  1596.     }
  1597.     }
  1598.     return(-1);
  1599. }
  1600.  
  1601. #ifdef TTLEBUF
  1602. VOID
  1603. le_init() {                /* LocalEchoInit() */
  1604.     int i;
  1605.     for (i = 0; i < LEBUFSIZ; i++)
  1606.       le_buf[i] = '\0';
  1607.     le_start = 0;
  1608.     le_end = 0;
  1609.     le_data = 0;
  1610. }
  1611.  
  1612. VOID
  1613. le_clean() {                /* LocalEchoCleanup() */
  1614.     le_init();
  1615.     return;
  1616. }
  1617.  
  1618. int
  1619. le_inbuf() {
  1620.     int rc = 0;
  1621.     if (le_start != le_end) {
  1622.     rc = (le_end -
  1623.           le_start +
  1624.           LEBUFSIZ) % LEBUFSIZ;
  1625.     }
  1626.     debug(F111,"le_inbuf","chars waiting",rc);
  1627.     return(rc);
  1628. }
  1629.  
  1630. int
  1631. #ifdef CK_ANSIC
  1632. le_putchar(CHAR ch)
  1633. #else
  1634. le_putchar(ch) CHAR ch;
  1635. #endif /* CK_ANSIC */
  1636. /* le_putchar */ {
  1637. #ifdef COMMENT
  1638.     /* In UNIX we do not have another thread taking chars out of the buffer */
  1639.     while ((le_start - le_end == 1) ||
  1640.             (le_start == 0 && le_end == LEBUFSIZ - 1)) {
  1641.     /* Buffer is full */
  1642.         debug(F111,"le_putchar","Buffer is Full",ch);
  1643.         ReleaseLocalEchoMutex() ;
  1644.         msleep(250);
  1645.         RequestLocalEchoMutex( SEM_INDEFINITE_WAIT ) ;
  1646.     }
  1647. #else
  1648.     if ((le_start - le_end + LEBUFSIZ)%LEBUFSIZ == 1) {
  1649.         debug(F110,"le_putchar","buffer is full",0);
  1650.         return(-1);
  1651.     }
  1652. #endif /* COMMENT */
  1653.     le_buf[le_end++] = ch;
  1654.     if (le_end == LEBUFSIZ)
  1655.       le_end = 0;
  1656.     le_data = 1;
  1657.     return(0);
  1658. }
  1659.  
  1660. int
  1661. #ifdef CK_ANSIC
  1662. le_puts(CHAR * s, int n)
  1663. #else
  1664. le_puts(s,n) CHAR * s; int n;
  1665. #endif /* CK_ANSIC */
  1666. /* le_puts */ {
  1667.     int rc = 0;
  1668.     int i = 0;
  1669.     CHAR * p = (CHAR *)"le_puts";
  1670.     hexdump(p,s,n);
  1671.     for (i = 0; i < n; i++)
  1672.       rc = le_putchar((char)s[i]);
  1673.     debug(F101,"le_puts","",rc);
  1674.     return(rc);
  1675. }
  1676.  
  1677. int
  1678. #ifdef CK_ANSIC
  1679. le_putstr(CHAR * s)
  1680. #else
  1681. le_putstr(s) CHAR * s;
  1682. #endif /* CK_ANSIC */
  1683. /* le_puts */ {
  1684.     CHAR * p;
  1685.     int rc = 0;
  1686.     p = (CHAR *)"le_putstr";
  1687.     hexdump(p,s,(int)strlen((char *)s));
  1688.     for (p = s; *p && !rc; p++)
  1689.       rc = le_putchar(*p);
  1690.     return(rc);
  1691. }
  1692.  
  1693. int
  1694. #ifdef CK_ANSIC
  1695. le_getchar(CHAR * pch)
  1696. #else /* CK_ANSIC */
  1697. le_getchar(pch) CHAR * pch;
  1698. #endif /* CK_ANSIC */
  1699. /* le_gatchar */ {
  1700.     int rc = 0;
  1701.     if (le_start != le_end) {
  1702.         *pch = le_buf[le_start];
  1703.         le_buf[le_start] = 0;
  1704.         le_start++;
  1705.  
  1706.         if (le_start == LEBUFSIZ)
  1707.           le_start = 0;
  1708.  
  1709.         if (le_start == le_end) {
  1710.             le_data = 0;
  1711.         }
  1712.         rc++;
  1713.     } else {
  1714.         *pch = 0;
  1715.     }
  1716.     return(rc);
  1717. }
  1718. #endif /* TTLEBUF */
  1719.  
  1720. #ifdef COMMENT
  1721. /*
  1722.   Some systems like OSF/1 use TIOCGSIZE instead of TIOCGWINSZ.
  1723.   But as far as I know, whenever TIOCGSIZE is defined, it is
  1724.   equated to TIOCGWINSZ.  For cases where this is not done, try this:
  1725. */
  1726. #ifndef TIOCGWINSZ
  1727. #ifdef TIOCGSIZE
  1728. #define TIOCGWINSZ TIOCGSIZE
  1729. #endif /* TIOCGSIZE */
  1730. #endif /* TIOCGWINSZ */
  1731. #endif /* COMMENT */
  1732.  
  1733. static int tt_xpixel = 0, tt_ypixel = 0;
  1734.  
  1735. int
  1736. ttgwsiz() {
  1737.     int x = 0;
  1738. #ifndef NONAWS
  1739. #ifdef QNX
  1740. /*
  1741.   NOTE: TIOCGWSIZ works here too, but only in the 32-bit version.
  1742.   This code works for both the 16- and 32-bit versions.
  1743. */
  1744.     extern int dev_size(int, int, int, int *, int *);
  1745.     int r, c;
  1746.  
  1747.     if (dev_size(0, -1, -1, &r, &c) == 0) {
  1748.     debug(F101,"ttgwsiz QNX r","",r);
  1749.     debug(F101,"ttgwsiz QNX c","",c);
  1750.     tt_rows = r;
  1751.     tt_cols = c;
  1752.     return ((r > 0 && c > 0) ? 1 : 0);
  1753.     } else return(xttgwsiz());
  1754. #else /* QNX */
  1755. #ifdef TIOCGWINSZ
  1756.  
  1757. /* Note, this was M_UNIX, changed to XENIX to allow cross compilation... */
  1758. #ifdef XENIX                /* SCO UNIX 3.2v4.0 */
  1759. #include <sys/stream.h>            /* typedef mblk_t needed by ptem.h */
  1760. #include <sys/ptem.h>            /* for ttgwsiz() */
  1761. #endif /* XENIX */
  1762.  
  1763. #ifdef I386IX                /* Ditto for Interactive */
  1764. #include <sys/stream.h>
  1765. #include <sys/ptem.h>
  1766. #endif /* I386IX */
  1767.  
  1768. /* Note, the above might be needed for some other older SVR3 Intel makes... */
  1769.  
  1770.     struct winsize w;
  1771.     tt_xpixel = 0;
  1772.     tt_ypixel = 0;
  1773.  
  1774. #ifdef IKSD
  1775.     if (inserver)
  1776.       return(xttgwsiz());
  1777. #endif /* IKSD */
  1778.     x = ioctl(0, (int)TIOCGWINSZ, (char *)&w);
  1779.     debug(F101,"ttgwsiz TIOCGWINSZ","",x);
  1780.     if (x < 0) {
  1781.     return(xttgwsiz());
  1782.     } else if (w.ws_row > 0 && w.ws_col > 0) {
  1783.     tt_rows = w.ws_row;
  1784.     tt_cols = w.ws_col;
  1785.     tt_xpixel = w.ws_xpixel;
  1786.     tt_ypixel = w.ws_ypixel;
  1787.     debug(F101,"ttgwsiz tt_rows","",tt_rows);
  1788.     debug(F101,"ttgwsiz tt_cols","",tt_cols);
  1789.     return(1);
  1790.     } else {
  1791.     debug(F100,"ttgwsiz TIOCGWINSZ 00","",0);
  1792.     return(xttgwsiz());
  1793.     }
  1794. #else
  1795.     return(xttgwsiz());
  1796. #endif /* TIOCGWINSZ */
  1797. #endif /* QNX */
  1798. #endif /* NONAWS */
  1799. }
  1800.  
  1801.  
  1802. #ifndef NOSIGWINCH
  1803. #ifdef SIGWINCH
  1804. SIGTYP
  1805. winchh(foo) int foo; {            /* SIGWINCH handler */
  1806.     int x = 0;
  1807. #ifdef NETPTY
  1808.     extern int pty_fork_pid;
  1809. #endif /* NETPTY */
  1810. #ifdef CK_TTYFD
  1811. #ifndef VMS
  1812.     extern int ttyfd;
  1813. #endif /* VMS */
  1814. #endif /* CK_TTYFD */
  1815.     extern int tt_rows, tt_cols, cmd_rows, cmd_cols;
  1816. #ifdef DEBUG
  1817.     if (deblog) {
  1818.     debug(F100,"***************","",0);
  1819.     debug(F100,"SIGWINCH caught","",0);
  1820.     debug(F100,"***************","",0);
  1821. #ifdef NETPTY
  1822.     debug(F101,"SIGWINCH pty_fork_pid","",pty_fork_pid);
  1823. #endif /* NETPTY */
  1824.     }
  1825. #endif /* DEUB */
  1826.     signal(SIGWINCH,winchh);            /* Re-arm the signal */
  1827.     x = ttgwsiz();                      /* Get new window size */
  1828.     cmd_rows = tt_rows;            /* Adjust command screen too */
  1829.     cmd_cols = tt_cols;
  1830.  
  1831. #ifdef CK_TTYFD
  1832.     if                    /* If we don't have a connection */
  1833. #ifdef VMS                /* we're done. */
  1834.       (vmsttyfd() == -1)
  1835. #else
  1836.       (ttyfd == -1)
  1837. #endif /* VMS */
  1838. #else
  1839.       (!local)
  1840. #endif /* CK_TTYFD */
  1841.         return;
  1842.  
  1843. #ifdef NETPTY
  1844.     if (pty_fork_pid > -1) {        /* "set host" to a PTY? */
  1845.     int x;
  1846.  
  1847. #ifdef TIOCSWINSZ
  1848.     struct winsize w;        /* Resize the PTY */
  1849.     errno = 0;
  1850.     w.ws_col = tt_cols;
  1851.     w.ws_row = tt_rows;
  1852.     w.ws_xpixel = tt_xpixel;
  1853.     w.ws_ypixel = tt_ypixel;
  1854.     x = ioctl(ttyfd,TIOCSWINSZ,&w);
  1855.     debug(F101,"winchh TIOCSWINSZ","",x);
  1856.     debug(F101,"winchh TIOCSWINSZ errno","",errno);
  1857. #endif /* TIOCSWINSZ */
  1858.  
  1859.     errno = 0;
  1860.     x = kill(pty_fork_pid,SIGWINCH);
  1861.     debug(F101,"winchh kill","",x);
  1862.     debug(F101,"winchh kill errno","",errno);
  1863.     }
  1864. #endif /* NETPTY */
  1865.  
  1866. /*
  1867.   This should be OK.  It might seem that sending this from
  1868.   interrupt level could interfere with another TELNET IAC string
  1869.   that was in the process of being sent.  But we always send
  1870.   TELNET strings with a single write(), which should prevent mixups.
  1871.   blah_snaws() should protect themselves from being called on the
  1872.   wrong kind of connection.
  1873. */
  1874. #ifdef TCPSOCKET
  1875. #ifndef NOTTGWSIZ
  1876.     if (x > 0 && tt_rows > 0 && tt_cols > 0) {
  1877.         tn_snaws();
  1878. #ifdef RLOGCODE
  1879.         rlog_naws();
  1880. #endif /* RLOGCODE */
  1881.     }
  1882. #endif /* NOTTGWSIZ */
  1883. #endif /* TCPSOCKET */
  1884.     SIGRETURN;
  1885. }
  1886. #endif /* SIGWINCH */
  1887. #endif /* NOSIGWINCH */
  1888.  
  1889. SIGTYP
  1890. sighup(foo) int foo; {            /* SIGHUP handler */
  1891.     backgrd = 1;
  1892.     debug(F100,"***************","",0);
  1893.     debug(F100,"SIGHUP received","",0);
  1894.     debug(F100,"***************","",0);
  1895.     doexit(BAD_EXIT,-1);
  1896.     /*NOTREACHED*/
  1897.     SIGRETURN;                /* Shut picky compilers up... */
  1898. }
  1899.  
  1900. #ifdef CK_SCO32V4
  1901. /* Exists but there is no prototype in the header files */
  1902. _PROTOTYP( char * ttyname, (int) );
  1903. #else
  1904. #ifdef SV68R3V6
  1905. _PROTOTYP( char * ttyname, (int) );
  1906. #else
  1907. #ifdef ultrix
  1908. _PROTOTYP( char * ttyname, (int) );
  1909. #else
  1910. #ifdef HPUX6
  1911. _PROTOTYP( char * ttyname, (int) );
  1912. #else
  1913. #ifdef HPUX5
  1914. _PROTOTYP( char * ttyname, (int) );
  1915. #else
  1916. #ifdef PS2AIX10
  1917. _PROTOTYP( char * ttyname, (int) );
  1918. #else
  1919. #ifdef BSD42
  1920. _PROTOTYP( char * ttyname, (int) );
  1921. #endif /* BSD42 */
  1922. #endif /* PS2AIX10 */
  1923. #endif /* HPUX5 */
  1924. #endif /* HPUX6 */
  1925. #endif /* ultrix */
  1926. #endif /* SV68R3V6 */
  1927. #endif /* CK_SCO32V4 */
  1928.  
  1929. #ifndef SIGUSR1                /* User-defined signals */
  1930. #define SIGUSR1 30
  1931. #endif /* SIGUSR1 */
  1932.  
  1933. #ifndef SIGUSR2
  1934. #define SIGUSR2 31
  1935. #endif /* SIGUSR2 */
  1936.  
  1937. /*
  1938.   ignorsigs() sets certain signals to SIG_IGN.  But when a signal is
  1939.   ignored, it remains ignored across exec(), so we have to restore these
  1940.   signals before exec(), which is the purpose of restorsigs().
  1941. */
  1942. static VOID
  1943. ignorsigs() {                /* Ignore these signals */
  1944.     savquit = signal(SIGQUIT,SIG_IGN);    /* Ignore Quit signal */
  1945.  
  1946. #ifdef SIGDANGER            /* Ignore danger signals */
  1947. /*
  1948.   This signal is sent when the system is low on swap space.  Processes
  1949.   that don't handle it are candidates for termination.  If swap space doesn't
  1950.   clear out enough, we still might be terminated via kill() -- nothing we can
  1951.   do about that!  Conceivably, this could be improved by installing a real
  1952.   signal handler that warns the user, but that would be pretty complicated,
  1953.   since we are not always in control of the screen -- e.g. during remote-mode
  1954.   file transfer.
  1955. */
  1956.     savdanger = signal(SIGDANGER,SIG_IGN); /* e.g. in AIX */
  1957. #endif /* SIGDANGER */
  1958. #ifdef SIGPIPE
  1959. /*
  1960.   This one comes when a TCP/IP connection is broken by the remote.
  1961.   We prefer to catch this situation by examining error codes from write().
  1962. */
  1963.     savpipe = signal(SIGPIPE,SIG_IGN);
  1964. #endif /* SIGPIPE */
  1965.     savusr1 = signal(SIGUSR1,SIG_IGN);    /* Ignore user-defined signals */
  1966.     savusr2 = signal(SIGUSR2,SIG_IGN);
  1967. }
  1968.  
  1969. VOID
  1970. restorsigs() {                /* Restore these signals */
  1971.     (VOID) signal(SIGQUIT,savquit);    /* (used in ckufio.c) */
  1972. #ifdef SIGDANGER
  1973.     (VOID) signal(SIGDANGER,savdanger);
  1974. #endif /* SIGDANGER */
  1975. #ifdef SIGPIPE
  1976.     (VOID) signal(SIGPIPE,savpipe);
  1977. #endif /* SIGPIPE */
  1978.     (VOID) signal(SIGUSR1,savusr1);
  1979.     (VOID) signal(SIGUSR2,savusr2);
  1980. }
  1981.  
  1982. int
  1983. sysinit() {
  1984.     int x;
  1985.     char * s;
  1986. #ifdef CK_UTSNAME
  1987.     struct utsname name;
  1988. #endif /* CK_UTSNAME */
  1989.  
  1990.     extern char startupdir[];
  1991. /*
  1992.   BEFORE ANYTHING ELSE: Initialize the setuid package.
  1993.   Change to the user's real user and group ID.
  1994.   If this can't be done, don't run at all.
  1995. */
  1996.     x = priv_ini();
  1997. #ifdef SUIDDEBUG
  1998.     fprintf(stderr,"PRIV_INI=%d\n",x);
  1999. #endif /* SUIDDEBUG */
  2000.     if (x) {
  2001.     if (x & 1) fprintf(stderr,"Fatal: setuid failure.\n");
  2002.     if (x & 2) fprintf(stderr,"Fatal: setgid failure.\n");
  2003.     if (x & 4) fprintf(stderr,"Fatal: C-Kermit setuid to root!\n");
  2004.     exit(1);
  2005.     }
  2006.     signal(SIGINT,SIG_IGN);        /* Ignore interrupts at first */
  2007.     signal(SIGFPE,SIG_IGN);        /* Ignore floating-point exceptions */
  2008.     signal(SIGHUP,sighup);        /* Catch SIGHUP */
  2009. #ifndef NOSIGWINCH
  2010. #ifdef SIGWINCH
  2011.     signal(SIGWINCH,winchh);        /* Catch window-size change */
  2012. #endif /* SIGWINCH */
  2013. #endif /* NOSIGWINCH */
  2014.  
  2015. #ifndef NOJC
  2016. /*
  2017.   Get the initial job control state.
  2018.   If it is SIG_IGN, that means the shell does not support job control,
  2019.   and so we'd better not suspend ourselves.
  2020. */
  2021. #ifdef SIGTSTP
  2022.     jchdlr = signal(SIGTSTP,SIG_IGN);
  2023.     if (jchdlr == SIG_IGN) {
  2024.     jcshell = 0;
  2025.     debug(F100,"sysinit jchdlr: SIG_IGN","",0);
  2026.     } else if (jchdlr == SIG_DFL) {
  2027.     debug(F100,"sysinit jchdlr: SIG_DFL","",0);
  2028.     jcshell = 1;
  2029.     } else {
  2030.     debug(F100,"sysinit jchdlr: other","",0);
  2031.     jcshell = 3;
  2032.     }
  2033.     (VOID) signal(SIGTSTP,jchdlr);    /* Put it back... */
  2034. #endif /* SIGTSTP */
  2035. #endif /* NOJC */
  2036.  
  2037.     conbgt(0);                /* See if we're in the background */
  2038.     congm();                /* Get console modes */
  2039.  
  2040.     (VOID) signal(SIGALRM,SIG_IGN);    /* Ignore alarms */
  2041.  
  2042.     ignorsigs();            /* Ignore some other signals */
  2043.  
  2044. #ifdef F_SETFL
  2045.     iniflags = fcntl(0,F_GETFL,0);    /* Get stdin flags */
  2046. #endif /* F_SETFL */
  2047.  
  2048. #ifdef ultrix
  2049.     gtty(0,&vanilla);            /* Get sgtty info */
  2050. #else
  2051. #ifdef AUX
  2052.     set42sig();                /* Don't ask! (hakanson@cs.orst.edu) */
  2053. #endif /* AUX */
  2054. #endif /* ultrix */
  2055. /*
  2056.   Warning: on some UNIX systems (SVR4?), ttyname() reportedly opens /dev but
  2057.   never closes it.  If it is called often enough, we run out of file
  2058.   descriptors and subsequent open()'s of other devices or files can fail.
  2059. */
  2060.     s = NULL;
  2061. #ifndef MINIX
  2062.     if (isatty(0))            /* Name of controlling terminal */
  2063.       s = ttyname(0);
  2064.     else if (isatty(1))
  2065.       s = ttyname(1);
  2066.     else if (isatty(2))
  2067.       s = ttyname(2);
  2068.     debug(F110,"sysinit ttyname(0)",s,0);
  2069. #endif /* MINIX */
  2070.  
  2071. #ifdef BEOS
  2072.     if (!dftty)
  2073.       makestr(&dftty,s);
  2074. #endif /* BEOS */
  2075.  
  2076.     if (s)
  2077.       ckstrncpy((char *)cttnam,s,DEVNAMLEN+1);
  2078. #ifdef SVORPOSIX
  2079.     if (!cttnam[0])
  2080.       ctermid(cttnam);
  2081. #endif /* SVORPOSIX */
  2082.     if (!cttnam[0])
  2083.       ckstrncpy((char *)cttnam,dftty,DEVNAMLEN+1);
  2084.     debug(F110,"sysinit CTTNAM",CTTNAM,0);
  2085.     debug(F110,"sysinit cttnam",cttnam,0);
  2086.  
  2087.     ttgwsiz();                /* Get window (screen) dimensions. */
  2088.  
  2089. #ifndef NOSYSCONF
  2090. #ifdef _SC_OPEN_MAX
  2091.     ckmaxfiles = sysconf(_SC_OPEN_MAX);
  2092. #endif /* _SC_OPEN_MAX */
  2093. #endif /* NOSYSCONF */
  2094.  
  2095. #ifdef Plan9
  2096.     if (!backgrd) {
  2097.         consctlfd = open("/dev/consctl", O_WRONLY);
  2098.         /*noisefd = open("/dev/noise", O_WRONLY)*/
  2099.     }
  2100.     ckxech = 1;
  2101. #endif /* Plan9 */
  2102.  
  2103. #ifdef CK_UTSNAME
  2104.     if (uname(&name) > -1) {
  2105.     ckstrncpy(unm_mch,name.machine,CK_SYSNMLN);
  2106.     ckstrncpy(unm_nam,name.sysname,CK_SYSNMLN);
  2107.     ckstrncpy(unm_rel,name.release,CK_SYSNMLN);
  2108.     ckstrncpy(unm_ver,name.version,CK_SYSNMLN);
  2109. #ifdef DEBUG
  2110.     if (deblog) {
  2111.         debug(F110,"sysinit uname machine",unm_mch,0);
  2112.         debug(F110,"sysinit uname sysname",unm_nam,0);
  2113.         debug(F110,"sysinit uname release",unm_rel,0);
  2114.         debug(F110,"sysinit uname version",unm_ver,0);
  2115.     }
  2116. #endif /* DEBUG */
  2117.  
  2118. #ifdef HPUX9PLUS
  2119.     if (name.machine[5] == '8')
  2120.       hpis800 = 1;
  2121.     else
  2122.       hpis800 = 0;
  2123.     debug(F101,"sysinit hpis800","",hpis800);
  2124. #endif /* HPUX9PLUS */
  2125. #ifdef TRU64
  2126.         getsysinfo(GSI_PLATFORM_NAME, unm_mod, CK_SYSNMLN, 0, 0);
  2127.         debug(F110,"sysinit getsysinfo model",unm_mod,0);
  2128. #endif /* TRU64 */
  2129. #ifdef SOLARIS25
  2130.         sysinfo(SI_PLATFORM, unm_mod, CK_SYSNMLN);
  2131.         debug(F110,"sysinit sysinfo model",unm_mod,0);
  2132. #endif /* SOLARIS25 */
  2133.     }
  2134. #endif /* CK_UTSNAME */
  2135.  
  2136. #ifdef CK_ENVIRONMENT
  2137.     {
  2138. #ifdef TNCODE
  2139.     extern char tn_env_acct[], tn_env_disp[], tn_env_job[],
  2140.     tn_env_prnt[], tn_env_sys[];
  2141. #endif /* TNCODE */
  2142.     extern char uidbuf[];
  2143.         extern char * whoami();
  2144.     char *p;
  2145. #ifdef CKSENDUID
  2146.         uidbuf[0] = '\0';
  2147. #ifdef IKSD
  2148.         if (!inserver) {
  2149. #endif /* IKSD */
  2150.             p = getenv("USER");
  2151.             debug(F110,"sysinit uidbuf from USER",uidbuf,0);
  2152.         if (!p) p = "";
  2153.             if (!*p) {
  2154.                 p = getenv("LOGNAME");
  2155.                 debug(F110,"sysinit uidbuf from LOGNAME",uidbuf,0);
  2156.             }
  2157.         if (!p) p = "";
  2158.             if (!*p) {
  2159.                 p = whoami();
  2160.                 debug(F110,"sysinit uidbuf from whoami()",uidbuf,0);
  2161.             }
  2162.         if (!p) p = "";
  2163.         ckstrncpy(uidbuf, *p ? p : "UNKNOWN", UIDBUFLEN);
  2164. #ifdef IKSD
  2165.         }
  2166. #endif /* IKSD */
  2167.     debug(F110,"sysinit final uidbuf",uidbuf,0);
  2168. #endif /* CKSENDUID */
  2169.  
  2170. #ifdef TNCODE
  2171.     if ((p = getenv("JOB"))) ckstrncpy(tn_env_job,p,63);
  2172.     if ((p = getenv("ACCT"))) ckstrncpy(tn_env_acct,p,63);
  2173.     if ((p = getenv("PRINTER"))) ckstrncpy(tn_env_prnt,p,63);
  2174.     if ((p = getenv("DISPLAY"))) ckstrncpy(tn_env_disp,p,63);
  2175. #ifdef aegis
  2176.     ckstrncpy(tn_env_sys,"Aegis",64);
  2177. #else
  2178. #ifdef Plan9
  2179.     ckstrncpy(tn_env_sys,"Plan9",64);
  2180. #else
  2181.     ckstrncpy(tn_env_sys,"UNIX",64);
  2182. #endif /* Plan9 */
  2183. #endif /* aegis */
  2184. #endif /* TNCODE */
  2185.     }
  2186. #endif /* CK_ENVIRONMENT */
  2187. #ifdef CK_SNDLOC
  2188.     {
  2189.     extern char * tn_loc;
  2190.     char *p;
  2191.     if (p = getenv("LOCATION"))
  2192.       if (tn_loc = (char *)malloc((int)strlen(p)+1))
  2193.         strcpy(tn_loc,p);        /* safe */
  2194.     }
  2195. #endif /* CK_SNDLOC */
  2196.  
  2197.     ckstrncpy(startupdir, zgtdir(), CKMAXPATH);
  2198.     startupdir[CKMAXPATH] = '\0';
  2199.     x = strlen(startupdir);
  2200.     if (x <= 0) {
  2201.     startupdir[0] = '/';
  2202.     startupdir[1] = '\0';
  2203.     } else if (startupdir[x-1] != '/') {
  2204.     startupdir[x] = '/';
  2205.     startupdir[x+1] = '\0';
  2206.     }
  2207.     debug(F110,"sysinit startupdir",startupdir,0);
  2208. #ifdef TTLEBUF
  2209.     le_init();
  2210. #endif /* TTLEBUF */
  2211. #ifdef BSD44ORPOSIX
  2212.     /* This should catch the ncurses platforms */
  2213.     /* Some platforms don't have putenv(), like NeXTSTEP */
  2214.     putenv("NCURSES_NO_SETBUF=1");
  2215. #endif /* BSD44ORPOSIX */
  2216.     return(0);
  2217. }
  2218.  
  2219. /*  S Y S C L E A N U P  --  System-dependent program cleanup.  */
  2220.  
  2221. int
  2222. syscleanup() {
  2223. #ifdef F_SETFL
  2224.     if (iniflags > -1)
  2225.       fcntl(0,F_SETFL,iniflags);    /* Restore stdin flags */
  2226. #endif /* F_SETFL */
  2227. #ifdef ultrix
  2228.     stty(0,&vanilla);                   /* Get sgtty info */
  2229. #endif /* ultrix */
  2230. #ifdef NETCMD
  2231.     if (ttpid) kill(ttpid,9);
  2232. #endif /* NETCMD */
  2233.     return(0);
  2234. }
  2235.  
  2236. /*  T T O P E N  --  Open a tty for exclusive access.  */
  2237.  
  2238. /*
  2239.   Call with:
  2240.     ttname: character string - device name or network host name.
  2241.     lcl:
  2242.   If called with lcl < 0, sets value of lcl as follows:
  2243.   0: the terminal named by ttname is the job's controlling terminal.
  2244.   1: the terminal named by ttname is not the job's controlling terminal.
  2245.   But watch out: if a line is already open, or if requested line can't
  2246.   be opened, then lcl remains (and is returned as) -1.
  2247.     modem:
  2248.   Less than zero: ttname is a network host name.
  2249.   Zero or greater: ttname is a terminal device name.
  2250.   Zero means a local connection (don't use modem signals).
  2251.   Positive means use modem signals.
  2252.    timo:
  2253.   0 = no timer.
  2254.   nonzero = number of seconds to wait for open() to return before timing out.
  2255.  
  2256.   Returns:
  2257.     0 on success
  2258.    -5 if device is in use
  2259.    -4 if access to device is denied
  2260.    -3 if access to lock directory denied
  2261.    -2 upon timeout waiting for device to open
  2262.    -1 on other error
  2263. */
  2264. static int ttotmo = 0;            /* Timeout flag */
  2265. /* Flag kept here to avoid being clobbered by longjmp.  */
  2266.  
  2267. int
  2268. ttopen(ttname,lcl,modem,timo) char *ttname; int *lcl, modem, timo; {
  2269.  
  2270. #ifdef BSD44
  2271. #define ctermid(x) strcpy(x,"")
  2272. #else
  2273. #ifdef SVORPOSIX
  2274. #ifndef CIE
  2275.     extern char *ctermid();        /* Wish they all had this! */
  2276. #else                    /* CIE Regulus */
  2277. #define ctermid(x) strcpy(x,"")
  2278. #endif /* CIE */
  2279. #endif /* SVORPOSIX */
  2280. #endif /* BSD44 */
  2281.  
  2282. #ifdef ultrix
  2283.     int temp = 0;
  2284. #endif /* ultrix */
  2285.  
  2286. #ifndef OPENFIRST
  2287.     char fullname[DEVNAMLEN+1];
  2288. #endif /* OPENFIRST */
  2289.  
  2290.     char * fnam;            /* Full name after expansion */
  2291.  
  2292.     int y;
  2293.  
  2294. #ifndef pdp11
  2295. #define NAMEFD     /* Feature to allow name to be an open file descriptor */
  2296. #endif /* pdp11 */
  2297.  
  2298. #ifdef NAMEFD
  2299.     char *p;
  2300.     debug(F101,"ttopen telnetfd","",telnetfd);
  2301. #endif /* NAMEFD */
  2302.  
  2303.     debug(F110,"ttopen ttname",ttname,0);
  2304.     debug(F110,"ttopen ttnmsv",ttnmsv,0);
  2305.     debug(F101,"ttopen modem","",modem);
  2306.     debug(F101,"ttopen netconn","",netconn);
  2307.     debug(F101,"ttopen ttyfd","",ttyfd);
  2308.     debug(F101,"ttopen *lcl","",*lcl);
  2309.     debug(F101,"ttopen ttmdm","",ttmdm);
  2310.     debug(F101,"ttopen ttnet","",ttnet);
  2311.  
  2312.     ttpmsk = 0xff;
  2313.     lockpid[0] = '\0';
  2314.  
  2315.     if (ttyfd > -1) {            /* If device already opened */
  2316.         if (!strncmp(ttname,ttnmsv,DEVNAMLEN)) /* are new & old names equal? */
  2317.       return(0);            /* Yes, nothing to do - just return */
  2318.     ttnmsv[0] = '\0';        /* No, clear out old name */
  2319.     ttclos(ttyfd);            /* close old connection.  */
  2320.     }
  2321.     wasclosed = 0;            /* New connection, not closed yet. */
  2322.     ttpipe = 0;                /* Assume it's not a pipe */
  2323.     ttpty = 0;                /* or a pty... */
  2324.  
  2325. #ifdef NETCONN
  2326. /*
  2327.   This is a bit tricky...  Suppose that previously Kermit had dialed a telnet
  2328.   modem server ("set host xxx:2001, set modem type usr, dial ...").  Then the
  2329.   connection was closed (ttyfd = -1), and then a REDIAL command was given.  At
  2330.   this point we've obliterated the negative modem type hack, and so would
  2331.   treat the IP hostname as a device name, and would then fail because of "No
  2332.   such device or directory".  But the previous connection has left behind some
  2333.   clues, so let's use them...
  2334. */
  2335.     if (ttyfd < 0) {            /* Connection is not open */
  2336.     if (!strcmp(ttname,ttnmsv)) {    /* Old and new names the same? */
  2337.         if (((netconn > 0) && (ttmdm < 0)) ||
  2338.         ((ttnet > 0) &&
  2339.          (!ckstrchr(ttname,'/')) && (ckstrchr(ttname,':')))
  2340.         ) {
  2341.         int x, rc;
  2342.         x = (ttmdm < 0) ? -ttmdm : ttnet;
  2343.         rc = netopen(ttname, lcl, x);
  2344.         debug(F111,"ttopen REOPEN netopen",ttname,rc);
  2345.         if (rc > -1) {
  2346.             netconn = 1;
  2347.             xlocal = *lcl = 1;
  2348.         } else {
  2349.             netconn = 0;
  2350.         }
  2351.         gotsigs = 0;
  2352.         return(rc);
  2353.         }
  2354.     }
  2355.     }
  2356. #endif /* NETCONN */
  2357.  
  2358. #ifdef MAXNAMLEN
  2359.     debug(F100,"ttopen MAXNAMLEN defined","",0);
  2360. #else
  2361.     debug(F100,"ttopen MAXNAMLEN *NOT* defined","",0);
  2362. #endif
  2363.  
  2364. #ifdef BSD4
  2365.     debug(F100,"ttopen BSD4 defined","",0);
  2366. #else
  2367.     debug(F100,"ttopen BSD4 *NOT* defined","",0);
  2368. #endif /* BSD4 */
  2369.  
  2370. #ifdef BSD42
  2371.     debug(F100,"ttopen BSD42 defined","",0);
  2372. #else
  2373.     debug(F100,"ttopen BSD42 *NOT* defined","",0);
  2374. #endif /* BSD42 */
  2375.  
  2376. #ifdef MYREAD
  2377.     debug(F100,"ttopen MYREAD defined","",0);
  2378. #else
  2379.     debug(F100,"ttopen MYREAD *NOT* defined","",0);
  2380. #endif /* MYREAD */
  2381.  
  2382. #ifdef    NETCONN
  2383.     if (modem < 0) {            /* modem < 0 = code for network */
  2384.     int x;
  2385.     ttmdm = modem;
  2386.     modem = -modem;            /* Positive network type number */
  2387.     fdflag = 0;            /* Stdio not redirected. */
  2388.     netconn = 1;            /* And it's a network connection */
  2389.     debug(F111,"ttopen net",ttname,modem);
  2390. #ifdef NAMEFD
  2391.     for (p = ttname; isdigit(*p); p++) ; /* Check for all digits */
  2392.      if (*p == '\0' && (telnetfd || x25fd)) { /* Avoid X.121 addresses */
  2393.         ttyfd = atoi(ttname);    /* Is there a way to test it's open? */
  2394.         ttfdflg = 1;        /* We got an open file descriptor */
  2395.         debug(F111,"ttopen net ttfdflg",ttname,ttfdflg);
  2396.         debug(F101,"ttopen net ttyfd","",ttyfd);
  2397.         ckstrncpy(ttnmsv,ttname,DEVNAMLEN); /* Remember the "name". */
  2398.         x = 1;            /* Return code is "good". */
  2399.         if (telnetfd) {
  2400.         ttnet = NET_TCPB;
  2401.         if (ttnproto != NP_TCPRAW)
  2402.           ttnproto = NP_TELNET;
  2403. #ifdef SUNX25
  2404.         } else if (x25fd) {
  2405.         ttnet = NET_SX25;
  2406.         ttnproto = NP_NONE;
  2407. #endif /* SUNX25 */
  2408.         }
  2409.     } else {            /* Host name or address given */
  2410. #ifdef NETPTY
  2411.         if (modem == NET_PTY) {
  2412.         int x;
  2413.         if (nopush) {
  2414.             debug(F100,"ttopen PTY: nopush","",0);
  2415.             return(-1);
  2416.         }
  2417.                 ttnet = NET_PTY;
  2418.         ttnproto = NP_NONE;
  2419.                 netconn = 1;            /* but we don't use network i/o */
  2420.                 ttpty = 1;
  2421.                 debug(F110,"ttopen PTY",ttname,0);
  2422.         x = do_pty(ttname);
  2423.         if (x > -1) {
  2424.             ckstrncpy(ttnmsv,ttname,DEVNAMLEN);
  2425.             xlocal = *lcl = 1;    /* It's local */
  2426.         } else {
  2427.             ttpty = 0;
  2428.             netconn = 0;
  2429.         }
  2430.         gotsigs = 0;
  2431.         return(x);
  2432.         }
  2433. #endif /* NETPTY */
  2434. #ifdef NETCMD
  2435. /*
  2436.   dup2() is not available on older System V platforms like AT&T 3Bx.  For
  2437.   those systems we punt by not defining NETCMD, but we might be able to do
  2438.   better -- see workarounds for this problem in ckufio.c (search for dup2).
  2439. */
  2440.         if (modem == NET_CMD) {
  2441.         if (nopush) {
  2442.             debug(F100,"ttopen pipe: nopush","",0);
  2443.             return(-1);
  2444.         }
  2445.         if (pipe(pipe0) || pipe(pipe1)) {
  2446.             perror("Pipe error");
  2447.             return(-1);
  2448.         }
  2449.         ttpid = fork();        /* Make a fork */
  2450.  
  2451.         switch (ttpid) {
  2452.           case -1:        /* Error making fork */
  2453.             close(pipe0[0]);
  2454.             close(pipe0[1]);
  2455.             close(pipe1[0]);
  2456.             close(pipe1[1]);
  2457.             perror("Fork error");
  2458.             return(-1);
  2459.           case 0:        /* Child. */
  2460.             close(pipe0[0]);
  2461.             close(pipe1[1]);
  2462.             dup2(pipe0[1], 1);
  2463.             close(pipe0[1]);
  2464.             dup2(pipe1[0], 0);
  2465.             close(pipe1[0]);
  2466.             system(ttname);
  2467.             _exit(0);
  2468.           default:        /* Parent */
  2469.             close(pipe0[1]);
  2470.             close(pipe1[0]);
  2471.             fdin = pipe0[0];    /* Read from pipe */
  2472.             fdout = pipe1[1];    /* Write to pipe */
  2473.             ttout = fdopen(fdout,"w"); /* Get stream so we can */
  2474.             if (!ttout) {    /* make it unbuffered. */
  2475.             perror("fdopen failure");
  2476.             return(-1);
  2477.             }
  2478.             setbuf(ttout,NULL);
  2479.             ckstrncpy(ttnmsv,ttname,DEVNAMLEN);
  2480.             xlocal = *lcl = 1;    /* It's local */
  2481.             netconn = 1;    /* Call it a network connection */
  2482.             ttmdm = modem;    /* Remember network type */
  2483.             ttyfd = fdin;
  2484.             ttpipe = 1;
  2485.             gotsigs = 0;
  2486.             return(0);
  2487.         }
  2488.         }
  2489. #endif /* NETCMD */
  2490. #endif /* NAMEFD */
  2491.         x = netopen(ttname, lcl, modem); /* (see ckcnet.h) */
  2492.         if (x > -1) {
  2493.         ckstrncpy(ttnmsv,ttname,DEVNAMLEN);
  2494.         } else netconn = 0;
  2495. #ifdef NAMEFD
  2496.     }
  2497. #endif /* NAMEFD */
  2498.  
  2499. #ifdef sony_news            /* Sony NEWS */
  2500.     if (ioctl(ttyfd,TIOCKGET,&km_ext) < 0) { /* Get Kanji mode */
  2501.         perror("ttopen error getting Kanji mode (network)");
  2502.         debug(F111,"ttopen error getting Kanji mode","network",0);
  2503.         km_ext = -1;        /* Make sure this stays undefined. */
  2504.     }
  2505. #endif /* sony_news */
  2506.  
  2507.     xlocal = *lcl = 1;        /* Network connections are local. */
  2508.     debug(F101,"ttopen net x","",x);
  2509. #ifdef COMMENT
  2510. /* Let netopen() do this */
  2511.     if (x > -1 && !x25fd)
  2512.       x = tn_ini();            /* Initialize TELNET protocol */
  2513. #endif /* COMMENT */
  2514.     gotsigs = 0;
  2515.     return(x);
  2516.     } else {                /* Terminal device */
  2517. #endif    /* NETCONN */
  2518.  
  2519. #ifdef NAMEFD
  2520. /*
  2521.   This code lets you give Kermit an open file descriptor for a serial
  2522.   communication device, rather than a device name.  Kermit assumes that the
  2523.   line is already open, locked, conditioned with the right parameters, etc.
  2524. */
  2525.     for (p = ttname; isdigit(*p); p++) ; /* Check for all-digits */
  2526.     if (*p == '\0') {
  2527.         ttyfd = atoi(ttname);    /* Is there a way to test it's open? */
  2528.         debug(F111,"ttopen got open fd",ttname,ttyfd);
  2529.         ckstrncpy(ttnmsv,ttname,DEVNAMLEN); /* Remember the "name". */
  2530.         if (ttyfd >= 0 && ttyfd < 3) /* If it's stdio... */
  2531.           xlocal = *lcl = 0;    /* we're in remote mode */
  2532.         else            /* otherwise */
  2533.           xlocal = *lcl = 1;    /* local mode. */
  2534.         netconn = 0;        /* Assume it's not a network. */
  2535.         tvtflg = 0;            /* Might need to initialize modes. */
  2536.         ttmdm = modem;        /* Remember modem type. */
  2537.         fdflag = 0;            /* Stdio not redirected. */
  2538.         ttfdflg = 1;        /* Flag we were opened this way. */
  2539.         debug(F111,"ttopen non-net ttfdflg",ttname,ttfdflg);
  2540.         debug(F101,"ttopen non-net ttyfd","",ttyfd);
  2541.  
  2542. #ifdef sony_news            /* Sony NEWS */
  2543.         /* Get device Kanji mode */
  2544.         if (ioctl(ttyfd,TIOCKGET,&km_ext) < 0) {
  2545.         perror("ttopen error getting Kanji mode");
  2546.         debug(F101,"ttopen error getting Kanji mode","",0);
  2547.         km_ext = -1;        /* Make sure this stays undefined. */
  2548.         }
  2549. #endif /* sony_news */
  2550.         gotsigs = 0;
  2551.         return(0);            /* Return success */
  2552.     }
  2553. #endif /* NAMEFD */
  2554. #ifdef NETCONN
  2555.     }
  2556. #endif /* NETCONN */
  2557.  
  2558. /* Here we have to open a serial device of the given name. */
  2559.  
  2560.     netconn = 0;            /* So it's not a network connection */
  2561.     occt = signal(SIGINT, cctrap);    /* Set Control-C trap, save old one */
  2562.     sigint_ign = 0;
  2563.  
  2564.     tvtflg = 0;            /* Flag for use by ttvt(). */
  2565.                 /* 0 = ttvt not called yet for this device */
  2566.  
  2567.     fdflag = (!isatty(0) || !isatty(1)); /* Flag for stdio redirected */
  2568.     debug(F101,"ttopen fdflag","",fdflag);
  2569.  
  2570.     ttmdm = modem;                      /* Make this available to other fns */
  2571.     xlocal = *lcl;                      /* Make this available to other fns */
  2572.  
  2573. /* Code for handling bidirectional tty lines goes here. */
  2574. /* Use specified method for turning off logins and suppressing getty. */
  2575.  
  2576. #ifdef ACUCNTRL
  2577.     /* Should put call to priv_on() here, but that would be very risky! */
  2578.     acucntrl("disable",ttname);         /* acucntrl() program. */
  2579.     /* and priv_off() here... */
  2580. #else
  2581. #ifdef ATT7300
  2582.     if ((attmodem & DOGETY) == 0)       /* offgetty() program. */
  2583.       attmodem |= offgetty(ttname);    /* Remember response.  */
  2584. #endif /* ATT7300 */
  2585. #endif /* ACUCNTRL */
  2586.  
  2587. #ifdef OPENFIRST
  2588. /*
  2589.  1985-2001: opens device first then gets lock; reason:
  2590.  Kermit usually has to run setuid or setgid in order to create a lockfile.
  2591.  If you give a SET LINE command for a device that happens to be your job's
  2592.  controlling terminal, Kermit doesn't have to create a lockfile, and in fact
  2593.  should not create one, and would fail if it tried to if it did not have the
  2594.  required privileges.  But you can't find out if two tty device names are
  2595.  equivalent until you have a file descriptor that you can give to ttyname().
  2596.  But this can cause a race condition between Kermit and [m]getty.  So see
  2597.  the [#]else part...
  2598. */ 
  2599.  
  2600. /*
  2601.  In the following section, we open the tty device for read/write.
  2602.  If a modem has been specified via "set modem" prior to "set line"
  2603.  then the O_NDELAY parameter is used in the open, provided this symbol
  2604.  is defined (e.g. in fcntl.h), so that the program does not hang waiting
  2605.  for carrier (which in most cases won't be present because a connection
  2606.  has not been dialed yet).  O_NDELAY is removed later on in ttopen().  It
  2607.  would make more sense to first determine if the line is local before
  2608.  doing this, but because ttyname() requires a file descriptor, we have
  2609.  to open it first.  See do_open().
  2610.  
  2611.  Now open the device using the desired treatment of carrier.
  2612.  If carrier is REQUIRED, then open could hang forever, so an optional
  2613.  timer is provided.  If carrier is not required, the timer should never
  2614.  go off, and should do no harm...
  2615. */
  2616.     ttotmo = 0;                /* Flag no timeout */
  2617.     debug(F101,"ttopen timo","",timo);
  2618.     debug(F101,"ttopen xlocal","",xlocal);
  2619.     if (timo > 0) {
  2620.     int xx;
  2621.     saval = signal(SIGALRM,timerh);    /* Timed, set up timer. */
  2622.     xx = alarm(timo);        /* Timed open() */
  2623.     debug(F101,"ttopen alarm","",xx);
  2624.     if (
  2625. #ifdef CK_POSIX_SIG
  2626.         sigsetjmp(sjbuf,1)
  2627. #else
  2628.         setjmp(sjbuf)
  2629. #endif /* CK_POSIX_SIG */
  2630.         ) {
  2631.         ttotmo = 1;            /* Flag timeout. */
  2632.     } else ttyfd = do_open(ttname);
  2633.     ttimoff();
  2634.     debug(F111,"ttopen","modem",modem);
  2635.     debug(F101,"ttopen ttyfd","",ttyfd);
  2636.     debug(F101,"ttopen alarm return","",ttotmo);
  2637.     } else {
  2638.     errno = 0;
  2639.     ttyfd = do_open(ttname);
  2640.     }
  2641.     debug(F111,"ttopen ttyfd",ttname,ttyfd);
  2642.     if (ttyfd < 0) {            /* If couldn't open, fail. */
  2643.     debug(F101,"ttopen errno","",errno);
  2644.     if (errno > 0 && !quiet)
  2645.       perror(ttname);        /* Print message */
  2646.  
  2647. #ifdef ATT7300
  2648.     if (attmodem & DOGETY)        /* was getty(1m) running before us? */
  2649.       ongetty(ttnmsv);        /* yes, restart on tty line */
  2650.     attmodem &= ~DOGETY;        /* no phone in use, getty restored */
  2651. #else
  2652. #ifdef ACUCNTRL
  2653.         /* Should put call to priv_on() here, but that would be risky! */
  2654.     acucntrl("enable",ttname);    /* acucntrl() program. */
  2655.     /* and priv_off() here... */
  2656. #endif /* ACUNTRL */
  2657. #endif /* ATT7300 */
  2658.  
  2659.     signal(SIGINT,occt);        /* Put old Ctrl-C trap back. */
  2660.     if (errno == EACCES) {        /* Device is protected against user */
  2661.         debug(F110,"ttopen EACCESS",ttname,0); /* Return -4 */
  2662.         return(-4);
  2663.     } else return(ttotmo ? -2 : -1); /* Otherwise -2 if timeout, or -1 */
  2664.     }
  2665.  
  2666. #ifdef QNX
  2667.     {
  2668.     extern int qnxportlock;
  2669.     x = qnxopencount();
  2670.     debug(F101,"ttopen qnxopencount","",x);
  2671.     debug(F101,"ttopen qnxportlock","",qnxportlock);
  2672.     if (x < 0 && qnxportlock) {
  2673.         ttclos(0);
  2674.         printf("?Can't get port open count\n");
  2675.         printf("(Try again with SET QNX-PORT-LOCK OFF)\n");
  2676.         return(-1);            /* Indicate device is in use */
  2677.     }
  2678.     if (x > 1) {            /* 1 == me */
  2679.         if (qnxportlock)
  2680.           ttclos(0);
  2681.           return(-2);        /* Indicate device is in use */
  2682.         else if (!quiet)
  2683.           printf("WARNING: \"%s\" looks busy...\n",ttdev);
  2684.     }
  2685.     }
  2686. #endif /* QNX */
  2687.  
  2688. #ifdef Plan9
  2689.     /* take this opportunity to open the control channel */
  2690.     if (p9openttyctl(ttname) < 0)
  2691. #else
  2692.     /* Make sure it's a real tty. */
  2693.     if (!ttfdflg && !isatty(ttyfd) && strcmp(ttname,"/dev/null"))
  2694. #endif /* Plan9 */
  2695.       {
  2696.     fprintf(stderr,"%s is not a terminal device\n",ttname);
  2697.     debug(F111,"ttopen not a tty",ttname,errno);
  2698.     close(ttyfd);
  2699.     ttyfd = -1;
  2700.     wasclosed = 1;
  2701.     signal(SIGINT,occt);
  2702.     return(-1);
  2703.     }
  2704.  
  2705. #ifdef aegis
  2706.     /* Apollo C runtime claims that console pads are tty devices, which
  2707.      * is reasonable, but they aren't any good for packet transfer. */
  2708.     ios_$inq_type_uid((short)ttyfd, ttyuid, st);
  2709.     if (st.all != status_$ok) {
  2710.         fprintf(stderr, "problem getting tty object type: ");
  2711.         error_$print(st);
  2712.     } else if (ttyuid != sio_$uid) { /* reject non-SIO lines */
  2713.         close(ttyfd); ttyfd = -1;
  2714.         wasclosed = 1;
  2715.         errno = ENOTTY; perror(ttname);
  2716.         signal(SIGINT,occt);
  2717.         return(-1);
  2718.     }
  2719. #endif /* aegis */
  2720.  
  2721.     sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  2722.  
  2723.     ckstrncpy(ttnmsv,ttname,DEVNAMLEN);    /* Keep copy of name locally. */
  2724.  
  2725. /* Caller wants us to figure out if line is controlling tty */
  2726.  
  2727.     if (*lcl < 0) {
  2728.         if (strcmp(ttname,CTTNAM) == 0) { /* "/dev/tty" always remote */
  2729.             xlocal = 0;
  2730.         debug(F111,"ttopen ttname=CTTNAM",ttname,xlocal);
  2731.         } else if (strcmp(ttname,cttnam) == 0) {
  2732.             xlocal = 0;
  2733.         debug(F111,"ttopen ttname=cttnam",ttname,xlocal);
  2734.     } else if (cttnam[0]) {
  2735. #ifdef BEBOX_DR7
  2736.             x = ttnmsv;            /* ttyname() is broken */
  2737. #else
  2738.             x = ttyname(ttyfd);         /* Get real name of ttname. */
  2739. #endif /* BEBOX_DR7 */
  2740.         if (!x) x = "";
  2741.         if (*x)
  2742.           xlocal = ((strncmp(x,cttnam,DEVNAMLEN) == 0) ? 0 : 1);
  2743.         else
  2744.           xlocal = 1;
  2745.             debug(F111,"ttopen ttyname(ttyfd) xlocal",x,xlocal);
  2746.         }
  2747.     }
  2748.  
  2749. #ifndef NOFDZERO
  2750. /* Note, the following code was added so that Unix "idle-line" snoopers */
  2751. /* would not think Kermit was idle when it was transferring files, and */
  2752. /* maybe log people out. */
  2753.     if (xlocal == 0) {            /* Remote mode */
  2754.     if (fdflag == 0) {        /* Standard i/o is not redirected */
  2755.         debug(F100,"ttopen setting ttyfd = 0","",0);
  2756. #ifdef LYNXOS
  2757.         /* On Lynx OS, fd 0 is open for read only. */
  2758.         dup2(ttyfd,0);
  2759. #endif /* LYNXOS */
  2760.         close(ttyfd);        /* Use file descriptor 0 */
  2761.         ttyfd = 0;
  2762.     } else {            /* Standard i/o is redirected */
  2763.         debug(F101,"ttopen stdio redirected","",ttyfd);
  2764.     }
  2765.     }
  2766. #endif /* NOFDZERO */
  2767.  
  2768. /* Now check if line is locked -- if so fail, else lock for ourselves */
  2769. /* Note: After having done this, don't forget to delete the lock if you */
  2770. /* leave ttopen() with an error condition. */
  2771.  
  2772.     lkf = 0;                            /* Check lock */
  2773.     if (xlocal > 0) {
  2774.     int xx; int xpid;
  2775.         if ((xx = ttlock(ttname)) < 0) { /* Can't lock it. */
  2776.             debug(F111,"ttopen ttlock fails",ttname,xx);
  2777.         /* WARNING - This close() can hang if tty is an empty socket... */
  2778.             close(ttyfd);        /* Close the device. */
  2779.         ttyfd = -1;            /* Erase its file descriptor. */
  2780.         wasclosed = 1;
  2781.         signal(SIGINT,occt);    /* Put old SIGINT back. */
  2782.         sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  2783.         if (xx == -2) {        /* If lockfile says device in use, */
  2784. #ifndef NOUUCP
  2785.         debug(F111,"ttopen reading lockfile pid",flfnam,xx);
  2786.         xpid = ttrpid(flfnam);    /* Try to read pid from lockfile */
  2787.         if (xpid > -1) {    /* If we got a pid */
  2788.                     if (!quiet)
  2789.               printf("Locked by process %d\n",xpid); /* tell them. */
  2790.             sprintf(lockpid,"%d",xpid);    /* Record it too */
  2791.             debug(F110,"ttopen lockpid",lockpid,0);
  2792.         } else if (*flfnam) {
  2793.             extern char *DIRCMD;
  2794.             char *p = NULL;
  2795.             int x;
  2796.             x = (int)strlen(flfnam) + (int)strlen(DIRCMD) + 2;
  2797.             p = malloc(x);    /* Print a directory listing. */
  2798. /*
  2799.   Note: priv_on() won't help here, because we do not pass privs along to
  2800.   to inferior processes, in this case ls.  So if the real user does not have
  2801.   directory-listing access to the lockfile directory, this will result in
  2802.   something like "not found".  That's why we try this only as a last resort.
  2803. */
  2804.             if (p) {        /* If we got the space... */
  2805.             ckmakmsg(p,x,DIRCMD," ",flfnam,NULL);
  2806.             zsyscmd(p);    /* Get listing. */
  2807.             if (p) {    /* free the space */
  2808.                 free(p);
  2809.                 p = NULL;
  2810.             }
  2811.             }
  2812.         }
  2813. #endif /* NOUUCP */
  2814.         return(-5);        /* Code for device in use */
  2815.         } else return(-3);        /* Access denied */
  2816.         } else lkf = 1;
  2817.     }
  2818. #else  /* OPENFIRST */
  2819.  
  2820. /*
  2821.   27 Oct 2001: New simpler code that gets the lock first and then opens the
  2822.   device, which eliminates the race condition.  The downside is you can no
  2823.   longer say "set line /dev/ttyp0" or whatever, where /dev/ttyp0 is your login
  2824.   terminal, without trying to create a lockfile, which fails if C-Kermit lacks
  2825.   privs, and if it succeeds, it has created a lockfile where it didn't create
  2826.   one before.
  2827. */
  2828.     xlocal = *lcl;            /* Is the device my login terminal? */
  2829.     debug(F111,"ttopen xlocal","A",xlocal);
  2830.     fnam = ttname;
  2831.     if (strcmp(ttname,CTTNAM) && netconn == 0) {
  2832.     if (zfnqfp(ttname,DEVNAMLEN+1,fullname)) {
  2833.         if ((int)strlen(fullname) > 0)
  2834.           fnam = fullname;
  2835.     }
  2836.     }
  2837.     debug(F110,"ttopen fnam",fnam,0);
  2838.     if (xlocal < 0) {
  2839.     xlocal = (strcmp(fnam,CTTNAM) != 0);
  2840.     }
  2841.     debug(F111,"ttopen xlocal","B",xlocal);
  2842.  
  2843.     lkf = 0;                            /* No lock yet */
  2844.     if (xlocal > 0) {            /* If not... */
  2845.     int xx; int xpid;
  2846.     xx = ttlock(fnam);        /* Try to lock it. */
  2847.     debug(F101,"ttopen ttlock","",xx);
  2848.         if (xx < 0) {            /* Can't lock it. */
  2849.             debug(F111,"ttopen ttlock fails",fnam,xx);
  2850.         if (xx == -2) {        /* If lockfile says device in use, */
  2851. #ifndef NOUUCP
  2852.         debug(F111,"ttopen reading lockfile pid",flfnam,xx);
  2853.         xpid = ttrpid(flfnam);    /* Try to read pid from lockfile */
  2854.         if (xpid > -1) {    /* If we got a pid */
  2855.                     if (!quiet)
  2856.               printf("Locked by process %d\n",xpid); /* tell them. */
  2857.             ckstrncpy(lockpid,ckitoa(xpid),16);
  2858.             debug(F110,"ttopen lockpid",lockpid,0);
  2859. #ifndef NOPUSH
  2860.         } else if (flfnam[0] && !nopush) {
  2861.             extern char *DIRCMD;
  2862.             char *p = NULL;
  2863.             int x;
  2864.             x = (int)strlen(flfnam) + (int)strlen(DIRCMD) + 2;
  2865.             p = malloc(x);    /* Print a directory listing. */
  2866. /*
  2867.   Note: priv_on() won't help here, because we do not pass privs along to
  2868.   to inferior processes, in this case ls.  So if the real user does not have
  2869.   directory-listing access to the lockfile directory, this will result in
  2870.   something like "not found".  That's why we try this only as a last resort.
  2871. */
  2872.             if (p) {        /* If we got the space... */
  2873.             ckmakmsg(p,x,DIRCMD," ",flfnam,NULL);
  2874.             zsyscmd(p);    /* Get listing. */
  2875.             if (p) {    /* free the space */
  2876.                 free(p);
  2877.                 p = NULL;
  2878.             }
  2879.             }
  2880. #endif /* NOPUSH */
  2881.         }
  2882. #endif /* NOUUCP */
  2883.         return(-5);        /* Code for device in use */
  2884.         } else return(-3);        /* Access denied */
  2885.         } else lkf = 1;
  2886.     }
  2887.     /* Have lock -- now it's safe to open the device */
  2888.  
  2889.     debug(F101,"ttopen lkf","",lkf);
  2890.     debug(F101,"ttopen timo","",timo);
  2891.  
  2892.     ttotmo = 0;                /* Flag no timeout */
  2893.     if (timo > 0) {
  2894.     int xx;
  2895.     saval = signal(SIGALRM,timerh);    /* Timed, set up timer. */
  2896.     xx = alarm(timo);        /* Timed open() */
  2897.     debug(F101,"ttopen alarm","",xx);
  2898.     if (
  2899. #ifdef CK_POSIX_SIG
  2900.         sigsetjmp(sjbuf,1)
  2901. #else
  2902.         setjmp(sjbuf)
  2903. #endif /* CK_POSIX_SIG */
  2904.         ) {
  2905.         ttotmo = 1;            /* Flag timeout. */
  2906.     } else {
  2907.         ttyfd = do_open(fnam);
  2908.     }
  2909.     ttimoff();
  2910.     debug(F111,"ttopen timed ttyfd",fnam,ttyfd);
  2911.     } else {
  2912.     errno = 0;
  2913.     ttyfd = do_open(fnam);
  2914.     debug(F111,"ttopen untimed ttyfd",fnam,ttyfd);
  2915.     }
  2916.     if (ttyfd < 0) {            /* If couldn't open, fail. */
  2917.     debug(F111,"ttopen errno",fnam,errno);
  2918.     debug(F111,"ttopen xlocal","C",xlocal);
  2919.     if (xlocal == 0) {
  2920.         debug(F100,"ttopen substituting 0","",0);
  2921.         ttyfd = 0;
  2922.     } else {
  2923.         if (errno > 0 && !quiet) {
  2924.             debug(F111,"ttopen perror",fnam,errno);
  2925.         perror(fnam);        /* Print message */
  2926.         }
  2927.         if (ttunlck())                  /* Release the lock file */
  2928.           fprintf(stderr,"Warning, problem releasing lock\r\n");
  2929.     }
  2930.     }
  2931.  
  2932.     if (ttyfd < 0) {            /* ttyfd is still < 0? */
  2933. #ifdef ATT7300
  2934.     if (attmodem & DOGETY)        /* was getty(1m) running before us? */
  2935.       ongetty(ttnmsv);        /* yes, restart on tty line */
  2936.     attmodem &= ~DOGETY;        /* no phone in use, getty restored */
  2937. #else
  2938. #ifdef ACUCNTRL
  2939.         /* Should put call to priv_on() here, but that would be risky! */
  2940.     acucntrl("enable",fnam);    /* acucntrl() program. */
  2941.     /* and priv_off() here... */
  2942. #endif /* ACUNTRL */
  2943. #endif /* ATT7300 */
  2944.  
  2945.     signal(SIGINT,occt);        /* Put old Ctrl-C trap back. */
  2946.     if (errno == EACCES) {        /* Device is protected against user */
  2947.         debug(F110,"ttopen EACCESS",fnam,0); /* Return -4 */
  2948.         return(-4);
  2949.     } else return(ttotmo ? -2 : -1); /* Otherwise -2 if timeout, or -1 */
  2950.     }
  2951.  
  2952. /* Make sure it's a real tty. */
  2953.  
  2954. #ifdef Plan9
  2955.     /* take this opportunity to open the control channel */
  2956.     if (p9openttyctl(fnam) < 0)       
  2957. #else
  2958.       if (!ttfdflg && !isatty(ttyfd) && strcmp(fnam,"/dev/null"))
  2959. #endif /* Plan9 */
  2960.     {
  2961.         fprintf(stderr,"%s is not a terminal device\n",fnam);
  2962.         debug(F111,"ttopen not a tty",fnam,errno);
  2963.         if (ttunlck())        /* Release the lock file */
  2964.           fprintf(stderr,"Warning, problem releasing lock\r\n");
  2965.         close(ttyfd);
  2966.         ttyfd = -1;
  2967.         wasclosed = 1;
  2968.         signal(SIGINT,occt);
  2969.         return(-1);
  2970.     }
  2971.  
  2972. #ifdef aegis
  2973.     /*
  2974.       Apollo C runtime claims that console pads are tty devices, which
  2975.       is reasonable, but they aren't any good for packet transfer.
  2976.     */
  2977.     ios_$inq_type_uid((short)ttyfd, ttyuid, st);
  2978.     if (st.all != status_$ok) {
  2979.     fprintf(stderr, "problem getting tty object type: ");
  2980.     error_$print(st);
  2981.     } else if (ttyuid != sio_$uid) {    /* Reject non-SIO lines */
  2982.     close(ttyfd); ttyfd = -1;
  2983.     wasclosed = 1;
  2984.     errno = ENOTTY; perror(fnam);
  2985.     signal(SIGINT,occt);
  2986.     return(-1);
  2987.     }
  2988. #endif /* aegis */
  2989.  
  2990.     sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  2991.  
  2992.     ckstrncpy(ttnmsv,ttname,DEVNAMLEN);    /* Keep copy of name locally. */
  2993.  
  2994. /* Caller wants us to figure out if line is controlling tty */
  2995.  
  2996.     if (*lcl < 0) {
  2997.     char * s;
  2998.         if (strcmp(fnam,CTTNAM) == 0) { /* "/dev/tty" always remote */
  2999.             xlocal = 0;
  3000.         debug(F111,"ttopen fnam=CTTNAM",fnam,xlocal);
  3001.         } else if (strcmp(fnam,cttnam) == 0) {
  3002.             xlocal = 0;
  3003.         debug(F111,"ttopen fnam=cttnam",fnam,xlocal);
  3004.     } else if (cttnam[0]) {
  3005. #ifdef BEBOX_DR7
  3006.             s = ttnmsv;            /* ttyname() is broken */
  3007. #else
  3008.             s = ttyname(ttyfd);         /* Get real name of ttname. */
  3009. #endif /* BEBOX_DR7 */
  3010.         if (!s) s = "";
  3011.         if (*s)
  3012.           xlocal = ((strncmp(s,cttnam,DEVNAMLEN) == 0) ? 0 : 1);
  3013.         else
  3014.           xlocal = 1;
  3015.             debug(F111,"ttopen ttyname(ttyfd) xlocal",s,xlocal);
  3016.         }
  3017.     }
  3018.  
  3019. #ifndef NOFDZERO
  3020. /* Note, the following code was added so that Unix "idle-line" snoopers */
  3021. /* would not think Kermit was idle when it was transferring files, and */
  3022. /* maybe log people out. */
  3023.     if (xlocal == 0) {            /* Remote mode */
  3024.     if (fdflag == 0) {        /* Standard i/o is not redirected */
  3025.         debug(F100,"ttopen setting ttyfd = 0","",0);
  3026. #ifdef LYNXOS
  3027.         /* On Lynx OS, fd 0 is open for read only. */
  3028.         dup2(ttyfd,0);
  3029. #endif /* LYNXOS */
  3030.         close(ttyfd);        /* Use file descriptor 0 */
  3031.         ttyfd = 0;
  3032.     } else {            /* Standard i/o is redirected */
  3033.         debug(F101,"ttopen stdio redirected","",ttyfd);
  3034.     }
  3035.     }
  3036. #endif /* NOFDZERO */
  3037. #endif /* OPENFIRST */
  3038.  
  3039. /* Got the line, now set the desired value for local. */
  3040.  
  3041.     if (*lcl != 0) *lcl = xlocal;
  3042.  
  3043. /* Some special stuff for v7... */
  3044.  
  3045. #ifdef  V7
  3046. #ifndef MINIX
  3047.     if (kmem[TTY] < 0) {        /*  If open, then skip this.  */
  3048.     qaddr[TTY] = initrawq(ttyfd);   /* Init the queue. */
  3049.     if ((kmem[TTY] = open("/dev/kmem", 0)) < 0) {
  3050.         fprintf(stderr, "Can't read /dev/kmem in ttopen.\n");
  3051.         perror("/dev/kmem");
  3052.         exit(1);
  3053.     }
  3054.     }
  3055. #endif /* !MINIX */
  3056. #endif /* V7 */
  3057.  
  3058. /* No failure returns after this point */
  3059.  
  3060. #ifdef ultrix
  3061.     ioctl(ttyfd, TIOCMODEM, &temp);
  3062. #ifdef TIOCSINUSE
  3063.     if (xlocal && ioctl(ttyfd, TIOCSINUSE, NULL) < 0) {
  3064.     if (!quiet)
  3065.       perror(fnam);
  3066.     }
  3067. #endif /* TIOCSINUSE */
  3068. #endif /* ultrix */
  3069.  
  3070. /* Get tty device settings  */
  3071.  
  3072. #ifdef BSD44ORPOSIX            /* POSIX */
  3073.     tcgetattr(ttyfd,&ttold);
  3074.     debug(F101,"ttopen tcgetattr ttold.c_lflag","",ttold.c_lflag);
  3075.     tcgetattr(ttyfd,&ttraw);
  3076.     debug(F101,"ttopen tcgetattr ttraw.c_lflag","",ttraw.c_lflag);
  3077.     tcgetattr(ttyfd,&tttvt);
  3078.     debug(F101,"ttopen tcgetattr tttvt.c_lflag","",tttvt.c_lflag);
  3079. #else                    /* BSD, V7, and all others */
  3080. #ifdef ATTSV                /* AT&T UNIX */
  3081.     ioctl(ttyfd,TCGETA,&ttold);
  3082.     debug(F101,"ttopen ioctl TCGETA ttold.c_lflag","",ttold.c_lflag);
  3083.     ioctl(ttyfd,TCGETA,&ttraw);
  3084.     ioctl(ttyfd,TCGETA,&tttvt);
  3085. #else
  3086. #ifdef BELLV10
  3087.     ioctl(ttyfd,TIOCGETP,&ttold);
  3088.     debug(F101,"ttopen BELLV10 ttold.sg_flags","",ttold.sg_flags);
  3089.     ioctl(ttyfd,TIOCGDEV,&tdold);
  3090.     debug(F101,"ttopen BELLV10 tdold.flags","",tdold.flags);
  3091. #else
  3092.     gtty(ttyfd,&ttold);
  3093.     debug(F101,"ttopen gtty ttold.sg_flags","",ttold.sg_flags);
  3094. #endif /* BELLV10 */
  3095.  
  3096. #ifdef sony_news            /* Sony NEWS */
  3097.     if (ioctl(ttyfd,TIOCKGET,&km_ext) < 0) { /* Get console Kanji mode */
  3098.     perror("ttopen error getting Kanji mode");
  3099.     debug(F101,"ttopen error getting Kanji mode","",0);
  3100.     km_ext = -1;            /* Make sure this stays undefined. */
  3101.     }
  3102. #endif /* sony_news */
  3103.  
  3104. #ifdef TIOCGETC
  3105.     debug(F100,"ttopen TIOCGETC","",0);
  3106.     tcharf = 0;                /* In remote mode, also get */
  3107.     if (xlocal == 0) {            /* special characters */
  3108.     if (ioctl(ttyfd,TIOCGETC,&tchold) < 0) {
  3109.         debug(F100,"ttopen TIOCGETC failed","",0);
  3110.     } else {
  3111.         tcharf = 1;            /* It worked. */
  3112.         ioctl(ttyfd,TIOCGETC,&tchnoi); /* Get another copy */
  3113.         debug(F100,"ttopen TIOCGETC ok","",0);
  3114.     }
  3115.     }
  3116. #else
  3117.     debug(F100,"ttopen TIOCGETC not defined","",0);
  3118. #endif /* TIOCGETC */
  3119.  
  3120. #ifdef TIOCGLTC
  3121.     debug(F100,"ttopen TIOCGLTC","",0);
  3122.     ltcharf = 0;            /* In remote mode, also get */
  3123.     if (xlocal == 0) {            /* local special characters */
  3124.     if (ioctl(ttyfd,TIOCGLTC,<chold) < 0) {
  3125.         debug(F100,"ttopen TIOCGLTC failed","",0);
  3126.     } else {
  3127.         ltcharf = 1;        /* It worked. */
  3128.         ioctl(ttyfd,TIOCGLTC,<chnoi); /* Get another copy */
  3129.         debug(F100,"ttopen TIOCGLTC ok","",0);
  3130.     }
  3131.     }
  3132. #else
  3133.     debug(F100,"ttopen TIOCGLTC not defined","",0);
  3134. #endif /* TIOCGLTC */
  3135.  
  3136. #ifdef TIOCLGET
  3137.     debug(F100,"ttopen TIOCLGET","",0);
  3138.     lmodef = 0;
  3139.     if (ioctl(ttyfd,TIOCLGET,&lmode) < 0) {
  3140.     debug(F100,"ttopen TIOCLGET failed","",0);
  3141.     } else {
  3142.     lmodef = 1;
  3143.     debug(F100,"ttopen TIOCLGET ok","",0);
  3144.     }
  3145. #endif /* TIOCLGET */
  3146.  
  3147. #ifdef BELLV10
  3148.     ioctl(ttyfd,TIOCGETP,&ttraw);
  3149.     ioctl(ttyfd,TIOCGETP,&tttvt);
  3150. #else
  3151.     gtty(ttyfd,&ttraw);                 /* And a copy of it for packets*/
  3152.     gtty(ttyfd,&tttvt);                 /* And one for virtual tty service */
  3153. #endif /* BELLV10 */
  3154.  
  3155. #endif /* ATTSV */
  3156. #endif /* BSD44ORPOSIX */
  3157.  
  3158. /* Section for changing line discipline.  It's restored in ttres(). */
  3159.  
  3160. #ifdef AIXRS
  3161. #ifndef AIX41
  3162.     { union txname ld_name; int ld_idx = 0;
  3163.       ttld = 0;
  3164.         do {
  3165.         ld_name.tx_which = ld_idx++;
  3166.         ioctl(ttyfd, TXGETCD, &ld_name);
  3167.       if (!strncmp(ld_name.tx_name, "rts", 3))
  3168.           ttld |= 1;
  3169.         } while (*ld_name.tx_name);
  3170.         debug(F101,"AIX line discipline","",ttld);
  3171.       }
  3172. #endif /* AIX41 */
  3173. #endif /* AIXRS */
  3174.  
  3175. #ifdef BSD41
  3176. /* For 4.1BSD only, force "old" tty driver, new one botches TANDEM. */
  3177.     { int k;
  3178.       ioctl(ttyfd, TIOCGETD, &ttld);    /* Get and save line discipline */
  3179.       debug(F101,"4.1bsd line discipline","",ttld);
  3180.       k = OTTYDISC;            /* Switch to "old" discipline */
  3181.       k = ioctl(ttyfd, TIOCSETD, &k);
  3182.       debug(F101,"4.1bsd tiocsetd","",k);
  3183.     }
  3184. #endif /* BSD41 */
  3185.  
  3186. #ifdef aegis
  3187.     /* This was previously done before the last two TCGETA or gtty above,
  3188.      * in both the ATTSV and not-ATTSV case.  If it is not okay to have only
  3189.      * one copy if it here instead, give us a shout!
  3190.      */
  3191.     sio_$control((short)ttyfd, sio_$raw_nl, false, st);
  3192.     if (xlocal) {       /* ignore breaks from local line */
  3193.         sio_$control((short)ttyfd, sio_$int_enable, false, st);
  3194.         sio_$control((short)ttyfd, sio_$quit_enable, false, st);
  3195.     }
  3196. #endif /* aegis */
  3197.  
  3198. #ifdef VXVE
  3199.     ttraw.c_line = 0;                   /* STTY line 0 for VX/VE */
  3200.     tttvt.c_line = 0;                   /* STTY line 0 for VX/VE */
  3201.     ioctl(ttyfd,TCSETA,&ttraw);
  3202. #endif /* vxve */
  3203.  
  3204. /* If O_NDELAY was used during open(), then remove it now. */
  3205.  
  3206. #ifdef O_NDELAY
  3207.     debug(F100,"ttopen O_NDELAY","",0);
  3208.     if (xlocal > 0) {
  3209.       if (fcntl(ttyfd, F_GETFL, 0) & O_NDELAY) {
  3210.     debug(F100,"ttopen fcntl O_NDELAY","",0);
  3211. #ifndef aegis
  3212.     if (fcntl(ttyfd,F_SETFL, fcntl(ttyfd, F_GETFL, 0) & ~O_NDELAY) < 0) {
  3213.         debug(F100,"ttopen fcntl failure to unset O_NDELAY","",0);
  3214.         perror("Can't unset O_NDELAY");
  3215.     }
  3216. #endif /* aegis */
  3217.     /* Some systems, notably Xenix (don't know how common this is in
  3218.      * other systems), need special treatment to get rid of the O_NDELAY
  3219.      * behaviour on read() with respect to carrier presence (i.e. read()
  3220.      * returning 0 when carrier absent), even though the above fcntl()
  3221.      * is enough to make read() wait for input when carrier is present.
  3222.      * This magic, in turn, requires CLOCAL for working when the carrier
  3223.      * is absent. But if xlocal == 0, presumably you already have CLOCAL
  3224.      * or you have a carrier, otherwise you wouldn't be running this.
  3225.      */
  3226.     debug(F101,"ttopen xlocal","",xlocal);
  3227. #ifdef ATTSV
  3228. #ifdef BSD44ORPOSIX
  3229. #ifdef COMMENT                /* 12 Aug 1997 */
  3230. #ifdef __bsdi__
  3231.     if (xlocal)
  3232.       ttraw.c_cflag |= CLOCAL;
  3233. #else
  3234. #ifdef __FreeBSD__
  3235.     if (xlocal)
  3236.       ttraw.c_cflag |= CLOCAL;
  3237. #endif /* __FreeBSD__ */
  3238. #endif /* __bsdi__ */
  3239. #else /* Not COMMENT */
  3240. #ifdef CLOCAL
  3241.     if (xlocal)            /* Unset this if it's defined. */
  3242.       ttraw.c_cflag |= CLOCAL;
  3243. #endif /* CLOCAL */
  3244. #endif /* COMMENT */
  3245.     debug(F101,"ttopen BSD44ORPOSIX calling tcsetattr","",TCSADRAIN);
  3246.     if (tcsetattr(ttyfd, TCSADRAIN, &ttraw) < 0) {
  3247.         debug(F100,"ttopen POSIX tcseattr fails","",0);
  3248.         perror("tcsetattr");
  3249.     }
  3250. #else /* !BSD44ORPOSIX */
  3251.     if (xlocal) {
  3252.         ttraw.c_cflag |= CLOCAL;
  3253.         debug(F100,"ttopen calling ioctl(TCSETA)","",0);
  3254.         errno = 0;
  3255.         if (ioctl(ttyfd, TCSETA, &ttraw) < 0) {
  3256.                 debug(F101,"ttopen ioctl(TCSETA) fails","",errno);
  3257.                 perror("ioctl(TCSETA)");
  3258.             }
  3259.     }
  3260. #endif /* BSD44ORPOSIX */
  3261. #endif /* ATTSV */
  3262. #ifndef NOCOTFMC /* = NO Close(Open()) To Force Mode Change */
  3263. /* Reportedly lets uugetty grab the device in SCO UNIX 3.2 / XENIX 2.3 */
  3264.     debug(F100,"ttopen executing close/open","",0);
  3265.     close( priv_opn(fnam, O_RDWR) ); /* Magic to force change. */
  3266. #endif /* NOCOTFMC */
  3267.       }
  3268.     }
  3269. #endif /* O_NDELAY */
  3270.  
  3271. /* Instruct the system how to treat the carrier, and set a few other tty
  3272.  * parameters.
  3273.  *
  3274.  * This also undoes the temporary setting of CLOCAL that may have been done
  3275.  * for the close(open()) above (except in Xenix).  Also throw in ~ECHO, to
  3276.  * prevent the other end of the line from sitting there talking to itself,
  3277.  * producing garbage when the user performs a connect.
  3278.  *
  3279.  * SCO Xenix unfortunately seems to ignore the actual state of CLOCAL.
  3280.  * Now it thinks CLOCAL is always on. It seems the only real solution for
  3281.  * Xenix is to switch between the lower and upper case device names.
  3282.  *
  3283.  * This section may at some future time expand into setting a complete
  3284.  * collection of tty parameters, or call a function shared with ttpkt()/
  3285.  * ttvt() that does so.  On the other hand, the initial parameters are not
  3286.  * that important, since ttpkt() or ttvt() should always fix that before
  3287.  * any communication is done.  Well, we'll see...
  3288.  */
  3289.     if (xlocal) {
  3290.         curcarr = -2;
  3291.     debug(F100,"ttopen calling carrctl","",0);
  3292.     carrctl(&ttraw, ttcarr == CAR_ON);
  3293.     debug(F100,"ttopen carrctl ok","",0);
  3294.  
  3295. #ifdef COHERENT
  3296. #define SVORPOSIX
  3297. #endif /* COHERENT */
  3298.  
  3299. #ifdef SVORPOSIX
  3300.     ttraw.c_lflag &= ~ECHO;
  3301.     ttold.c_lflag &= ~ECHO;
  3302. #ifdef BSD44ORPOSIX
  3303.     y = tcsetattr(ttyfd, TCSADRAIN, &ttraw);
  3304.     debug(F101,"ttopen tcsetattr","",y);
  3305. #else
  3306.     y = ioctl(ttyfd, TCSETA, &ttraw);
  3307.     debug(F100,"ttopen ioctl","",y);
  3308. #endif /* BSD44ORPOSIX */
  3309.  
  3310. #else /* BSD, etc */
  3311.     ttraw.sg_flags &= ~ECHO;
  3312.     ttold.sg_flags &= ~ECHO;
  3313. #ifdef BELLV10
  3314.     y = ioctl(ttyfd,TIOCSETP,&ttraw);
  3315.     debug(F100,"ttopen ioctl","",y);
  3316. #else
  3317.     y = stty(ttyfd,&ttraw);
  3318.     debug(F100,"ttopen stty","",y);
  3319. #endif /* BELLV10 */
  3320. #endif /* SVORPOSIX */
  3321.  
  3322. #ifdef COHERENT
  3323. #undef SVORPOSIX
  3324. #endif /* COHERENT */
  3325.  
  3326.     /* ttflui(); */  /*  This fails for some reason.  */
  3327.     }
  3328.  
  3329.     /* Get current speed */
  3330.  
  3331. #ifndef BEBOX
  3332.     ttspeed = ttgspd();
  3333. #else
  3334.     ttspeed = 19200;
  3335. #endif /* !BEBOX */
  3336.     debug(F101,"ttopen ttspeed","",ttspeed);
  3337.  
  3338.     /* Done, make entries in debug log, restore Ctrl-C trap, and return. */
  3339.  
  3340.     debug(F101,"ttopen ttyfd","",ttyfd);
  3341.     debug(F101,"ttopen *lcl","",*lcl);
  3342.     debug(F111,"ttopen lock file",flfnam,lkf);
  3343.     signal(SIGINT,occt);
  3344.     sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  3345.     gotsigs = 0;
  3346.     return(0);
  3347. }
  3348.  
  3349.  
  3350. /*  D O _ O P E N  --  Do the right kind of open() call for the tty. */
  3351.  
  3352. int
  3353. do_open(ttname) char *ttname; {
  3354.     int flags;
  3355.  
  3356. #ifdef QNX6
  3357.     /* O_NONBLOCK on /dev/tty makes open() fail */
  3358.     return(priv_opn(ttname, O_RDWR |
  3359.             (
  3360.              ((int)strcmp(ttname,"/dev/tty") == 0) ?
  3361.              0 :
  3362.              (ttcarr != CAR_ON) ? O_NONBLOCK : 0)
  3363.             )
  3364.        ); 
  3365. #else  /* !QNX6 */
  3366.  
  3367. #ifndef    O_NDELAY            /* O_NDELAY not defined */
  3368.     return(priv_opn(ttname,2));
  3369. #else                    /* O_NDELAY defined */
  3370.  
  3371. #ifdef ATT7300
  3372. /*
  3373.  Open comms line without waiting for carrier so initial call does not hang
  3374.  because state of "modem" is likely unknown at the initial call  -jrd.
  3375.  If this is needed for the getty stuff to work, and the open would not work
  3376.  without O_NDELAY when getty is still on, then this special case is ok.
  3377.  Otherwise, get rid of it. -ske
  3378. */
  3379.     return(priv_opn(ttname, O_RDWR | O_NDELAY));
  3380.  
  3381. #else    /* !ATT7300 */
  3382.  
  3383.     /* Normal case. Use O_NDELAY according to SET CARRIER. See ttscarr(). */
  3384.     flags = O_RDWR;
  3385.     debug(F101,"do_open xlocal","",xlocal);
  3386.     debug(F111,"do_open flags A",ttname,flags);
  3387.     if (xlocal && (ttcarr != CAR_ON))
  3388.       flags |= O_NDELAY;
  3389.     debug(F111,"do_open flags B",ttname,flags);
  3390.     return(priv_opn(ttname, flags));
  3391. #endif /* !ATT7300 */
  3392. #endif /* O_NDELAY */
  3393. #endif /* QNX6 */
  3394. }
  3395.  
  3396. /*  T T C L O S  --  Close the TTY, releasing any lock.  */
  3397.  
  3398. static int ttc_state = 0;        /* ttclose() state */
  3399. static char * ttc_nam[] = { "setup", "hangup", "reset", "close" };
  3400.  
  3401. int
  3402. ttclos(foo) int foo; {            /* Arg req'd for signal() prototype */
  3403.     int xx, x = 0;
  3404.     extern int exithangup;
  3405.  
  3406.     debug(F101,"ttclos ttyfd","",ttyfd);
  3407.     debug(F101,"ttclos netconn","",netconn);
  3408.     debug(F101,"ttclos xlocal","",xlocal);
  3409. #ifdef NOFDZERO
  3410.     debug(F100,"ttclos NOFDZERO","",0);
  3411. #endif /* NOFDZERO */
  3412.  
  3413. #ifdef COMMENT
  3414. #ifdef TTLEBUF
  3415.     le_init();                /* No need for any of this */
  3416. #endif /* TTLEBUF */
  3417. #endif /* COMMENT */
  3418.  
  3419.     if (ttyfd < 0)            /* Wasn't open. */
  3420.       return(0);
  3421.  
  3422.     if (ttfdflg)            /* If we inherited ttyfd from */
  3423.       return(0);            /* another process, don't close it. */
  3424.  
  3425.     tvtflg = 0;                /* (some day get rid of this...) */
  3426.     gotsigs = 0;
  3427.  
  3428. #ifdef IKSD
  3429.     if (inserver) {
  3430. #ifdef TNCODE
  3431.           tn_push();                    /* Place any waiting data into input*/
  3432.           tn_sopt(DO,TELOPT_LOGOUT);    /* Send LOGOUT option before close */
  3433.           TELOPT_UNANSWERED_DO(TELOPT_LOGOUT) = 1;
  3434.           tn_reset();                   /* The Reset Telnet Option table.  */
  3435. #endif /* TNCODE */
  3436. #ifdef CK_SSL
  3437.       if (ssl_active_flag) {
  3438.           if (ssl_debug_flag)
  3439.         BIO_printf(bio_err,"calling SSL_shutdown(ssl)\n");
  3440.           SSL_shutdown(ssl_con);
  3441.           SSL_free(ssl_con);
  3442.           ssl_con = NULL;
  3443.           ssl_active_flag = 0;
  3444.       }
  3445.       if (tls_active_flag) {
  3446.           if (ssl_debug_flag)
  3447.         BIO_printf(bio_err,"calling SSL_shutdown(tls)\n");
  3448.           SSL_shutdown(tls_con);
  3449.           SSL_free(tls_con);
  3450.           tls_con = NULL;
  3451.           tls_active_flag = 0;
  3452.       }
  3453. #endif /* CK_SSL */
  3454.     }
  3455. #endif /* IKSD */
  3456. #ifdef NETCMD
  3457.     if (ttpipe) {            /* We've been using a pipe */
  3458.     /* ttpipe = 0; */
  3459.     if (ttpid > 0) {
  3460.         int wstat;
  3461.         int statusp;
  3462.         close(fdin);        /* Close these. */
  3463.         close(fdout);
  3464.         fdin = fdout = -1;
  3465.         kill(ttpid,1);        /* Kill fork with SIGHUP */
  3466.         while (1) {
  3467.         wstat = wait(&statusp);
  3468.         if (wstat == ttpid || wstat == -1)
  3469.           break;
  3470.         pexitstat = (statusp & 0xff) ? statusp : statusp >> 8;
  3471.         }
  3472.         ttpid = 0;
  3473.     }
  3474.     netconn = 0;
  3475.     wasclosed = 1;
  3476.     ttyfd = -1;
  3477.     return(0);
  3478.     }
  3479. #endif /* NETCMD */
  3480. #ifdef NETPTY
  3481.     if (ttpty) {
  3482. #ifndef NODOPTY
  3483.         end_pty();
  3484. #endif /* NODOPTY */
  3485.         close(ttyfd);
  3486.     netconn = 0;
  3487.     wasclosed = 1;
  3488.         ttpty = 0;
  3489.         ttyfd = -1;
  3490.         return(0);
  3491.     }
  3492. #endif /* NETPTY */
  3493.  
  3494. #ifdef    NETCONN
  3495.     if (netconn) {            /* If it's a network connection. */
  3496.     debug(F100,"ttclos closing net","",0);
  3497.     netclos();            /* Let the network module close it. */
  3498.     netconn = 0;            /* No more network connection. */
  3499.     debug(F101,"ttclos ttyfd after netclos","",ttyfd); /* Should be -1 */
  3500.     return(0);
  3501.     }
  3502. #endif    /* NETCONN */
  3503.  
  3504.     if (xlocal) {            /* We're closing a SET LINE device */
  3505. #ifdef FT21                /* Fortune 2.1-specific items ... */
  3506.     ioctl(ttyfd,TIOCHPCL, NULL);
  3507. #endif /* FT21 */
  3508. #ifdef ultrix                /* Ultrix-specific items ... */
  3509. #ifdef TIOCSINUSE
  3510.     /* Unset the INUSE flag that we set in ttopen() */
  3511.     ioctl(ttyfd, TIOCSINUSE, NULL);
  3512. #endif /* TIOCSINUSE */
  3513.     ioctl(ttyfd, TIOCNMODEM, &x);
  3514. #ifdef COMMENT
  3515.     /* What was this? */
  3516.     ioctl(ttyfd, TIOCNCAR, NULL);
  3517. #endif /* COMMENT */
  3518. #endif /* ultrix */
  3519.     }
  3520.  
  3521.     /* This is to prevent us from sticking in tthang() or close(). */
  3522.  
  3523. #ifdef O_NDELAY
  3524. #ifndef aegis
  3525.     if (ttyfd > 0) {            /* But skip it on stdin. */
  3526.     debug(F100,"ttclos setting O_NDELAY","",0);
  3527.     x = fcntl(ttyfd,F_SETFL,fcntl(ttyfd,F_GETFL, 0)|O_NDELAY);
  3528. #ifdef DEBUG
  3529.     if (deblog && x == -1) {
  3530.         perror("Warning - Can't set O_NDELAY");
  3531.         debug(F101,"ttclos fcntl failure to set O_NDELAY","",x);
  3532.     }
  3533. #endif /* DEBUG */
  3534.     }
  3535. #endif /* aegis */
  3536. #endif /* O_NDELAY */
  3537.  
  3538.     x = 0;
  3539.     ttc_state = 0;
  3540.     if (xlocal
  3541. #ifdef NOFDZERO
  3542.     || ttyfd > 0
  3543. #endif /* NOFDZERO */
  3544.     ) {
  3545.     saval = signal(SIGALRM,xtimerh); /* Enable timer interrupt. */
  3546.     xx = alarm(8);            /* Allow 8 seconds. */
  3547.     debug(F101,"ttclos alarm","",xx);
  3548.     if (
  3549. #ifdef CK_POSIX_SIG
  3550.         sigsetjmp(sjbuf,1)
  3551. #else
  3552.         setjmp(sjbuf)
  3553. #endif /* CK_POSIX_SIG */
  3554.         ) {                /* Timer went off? */
  3555.         x = -1;
  3556. #ifdef DEBUG
  3557.         debug(F111,"ttclos ALARM TRAP errno",ckitoa(ttc_state),errno);
  3558.         printf("ttclos() timeout: %s\n", ttc_nam[ttc_state]);
  3559. #endif /* DEBUG */
  3560.     }
  3561.     /* Hang up the device (drop DTR) */
  3562.  
  3563.     errno = 0;
  3564.     debug(F111,"ttclos A",ckitoa(x),ttc_state);
  3565.     if (ttc_state < 1) {
  3566.         ttc_state = 1;
  3567.         debug(F101,"ttclos exithangup","",exithangup);
  3568.         if (exithangup) {
  3569.         alarm(8);        /* Re-arm the timer */
  3570.         debug(F101,"ttclos calling tthang()","",x);
  3571.         x = tthang();        /* Hang up first, then... */
  3572.         debug(F101,"ttclos tthang()","",x);
  3573.         }
  3574.     }
  3575.     /* Put back device modes as we found them */
  3576.  
  3577.     errno = 0;
  3578.     debug(F111,"ttclos B",ckitoa(x),ttc_state);
  3579.     if (ttc_state < 2) {
  3580.         ttc_state = 2;
  3581.         /* Don't try to mess with tty modes if tthang failed() */
  3582.         /* since it probably won't work. */
  3583.         if (x > -1) {
  3584.         debug(F101,"ttclos calling ttres()","",x);
  3585.         signal(SIGALRM,xtimerh); /* Re-enable the alarm. */
  3586.         alarm(8);        /* Re-arm the timer */
  3587.         x = ttres();        /* Reset device modes. */
  3588.         debug(F101,"ttclos ttres()","",x);
  3589.         alarm(0);
  3590.         }
  3591.     }
  3592.     /* Close the device */
  3593.  
  3594.     errno = 0;
  3595.     debug(F101,"ttclos C","",ttc_state);
  3596.     if (ttc_state < 3) {
  3597.         ttc_state = 3;
  3598.         errno = 0;
  3599.         debug(F101,"ttclos calling close","",x);
  3600.         signal(SIGALRM,xtimerh);    /* Re-enable alarm. */
  3601.         alarm(8);            /* Re-arm the timer */
  3602.         x = close(ttyfd);        /* Close the device. */
  3603.         debug(F101,"ttclos close()","",x);
  3604.         if (x > -1)
  3605.           ttc_state = 3;
  3606.     }
  3607.     debug(F101,"ttclos D","",ttc_state);
  3608.     ttimoff();            /* Turn off timer. */
  3609.     if (x < 0) {
  3610.         printf("?WARNING - close failed: %s\n",ttnmsv);
  3611. #ifdef DEBUG
  3612.         if (deblog) {
  3613.         printf("errno = %d\n", errno);
  3614.         debug(F101,"ttclos failed","",errno);
  3615.         }
  3616. #endif /* DEBUG */
  3617.     }
  3618.     /* Unlock after closing but before any getty mumbo jumbo */
  3619.  
  3620.     debug(F100,"ttclos about to call ttunlck","",0);
  3621.         if (ttunlck())                  /* Release uucp-style lock */
  3622.       fprintf(stderr,"Warning, problem releasing lock\r\n");
  3623.     }
  3624.  
  3625. /* For bidirectional lines, restore getty if it was there before. */
  3626.  
  3627. #ifdef ACUCNTRL                /* 4.3BSD acucntrl() method. */
  3628.     if (xlocal) {
  3629.     debug(F100,"ttclos ACUCNTRL","",0);
  3630.     acucntrl("enable",ttnmsv);    /* Enable getty on the device. */
  3631.     }
  3632. #else
  3633. #ifdef ATT7300                /* ATT UNIX PC (3B1, 7300) method. */
  3634.     if (xlocal) {
  3635.     debug(F100,"ttclos ATT7300 ongetty","",0);
  3636.     if (attmodem & DOGETY)        /* Was getty(1m) running before us? */
  3637.       ongetty(ttnmsv);        /* Yes, restart getty on tty line */
  3638.     attmodem &= ~DOGETY;        /* No phone in use, getty restored */
  3639.     }
  3640. #endif /* ATT7300 */
  3641. #endif /* System-dependent getty-restoring methods */
  3642.  
  3643. #ifdef sony_news
  3644.     km_ext = -1;            /* Invalidate device's Kanji-mode */
  3645. #endif /* sony_news */
  3646.  
  3647.     ttyfd = -1;                         /* Invalidate the file descriptor. */
  3648.     wasclosed = 1;
  3649.     debug(F100,"ttclos done","",0);
  3650.     return(0);
  3651. }
  3652.  
  3653. /*  T T H A N G  --  Hangup phone line or network connection.  */
  3654. /*
  3655.   Returns:
  3656.   0 if it does nothing.
  3657.   1 if it believes that it hung up successfully.
  3658.  -1 if it believes that the hangup attempt failed.
  3659. */
  3660.  
  3661. #define HUPTIME 500            /* Milliseconds for hangup */
  3662.  
  3663. #ifdef COMMENT
  3664. /* The following didn't work but TIOCSDTR does work */
  3665. #ifdef UNIXWARE
  3666. /* Define HUP_POSIX to force non-POSIX builds to use the POSIX hangup method */
  3667. #ifndef POSIX                /* Such as Unixware 1.x, 2.x */
  3668. #ifndef HUP_POSIX
  3669. #define HUP_POSIX
  3670. #endif /* HUP_POSIX */
  3671. #endif /* POSIX */
  3672. #endif /* UNIXWARE */
  3673. #endif /* COMMENT */
  3674.  
  3675. #ifndef USE_TIOCSDTR
  3676. #ifdef __NetBSD__
  3677. /* Because the POSIX method (set output speed to 0) doesn't work in NetBSD */
  3678. #ifdef TIOCSDTR
  3679. #ifdef TIOCCDTR
  3680. #define USE_TIOCSDTR
  3681. #endif /* TIOCCDTR */
  3682. #endif /* TIOCSDTR */
  3683. #endif /* __NetBSD__ */
  3684. #endif /* USE_TIOCSDTR */
  3685.  
  3686. #ifndef HUP_CLOSE_POSIX
  3687. #ifdef OU8
  3688. #define HUP_CLOSE_POSIX
  3689. #else
  3690. #ifdef CK_SCOV5
  3691. #define HUP_CLOSE_POSIX
  3692. #endif /* CK_SCOV5 */
  3693. #endif /* OU8 */
  3694. #endif /* HUP_CLOSE_POSIX */
  3695.  
  3696. #ifdef NO_HUP_CLOSE_POSIX
  3697. #ifdef HUP_CLOSE_POSIX
  3698. #undef HUP_CLOSE_POSIX
  3699. #endif /* HUP_CLOSE_POSIX */
  3700. #endif /* NO_HUP_CLOSE_POSIX */
  3701.  
  3702. int
  3703. tthang() {
  3704. #ifdef NOLOCAL
  3705.     return(0);
  3706. #else
  3707.     int x = 0;                /* Sometimes used as return code. */
  3708. #ifndef POSIX
  3709.     int z;                /* worker */
  3710. #endif /* POSIX */
  3711.  
  3712. #ifdef COHERENT
  3713. #define SVORPOSIX
  3714. #endif /* COHERENT */
  3715.  
  3716. #ifdef SVORPOSIX            /* AT&T, POSIX, HPUX declarations. */
  3717.     int spdsav;                /* for saving speed */
  3718. #ifdef HUP_POSIX
  3719.     int spdsavi;
  3720. #else
  3721. #ifdef BSD44ORPOSIX
  3722.     int spdsavi;
  3723. #endif /* BSD44ORPOSIX */
  3724. #endif /* HUP_POSIX */
  3725. #ifdef HPUX
  3726. /*
  3727.   Early versions of HP-UX omitted the mflag typedef.  If you get complaints
  3728.   about it, just change it to long (or better still, unsigned long).
  3729. */
  3730.     mflag
  3731.       dtr_down = 00000000000,
  3732.       modem_rtn,
  3733.       modem_sav;
  3734.     char modem_state[64];
  3735. #endif /* HPUX */
  3736.     int flags;                /* fcntl flags */
  3737.     unsigned short ttc_save;
  3738. #endif /* SVORPOSIX */
  3739.  
  3740.     if (ttyfd < 0) return(0);           /* Don't do this if not open  */
  3741.     if (xlocal < 1) return(0);        /* Don't do this if not local */
  3742.  
  3743. #ifdef NETCMD
  3744.     if (ttpipe)
  3745.       return((ttclos(0) < 0) ? -1 : 1);
  3746. #endif /* NETCMD */
  3747. #ifdef NETPTY
  3748.     if (ttpty)
  3749.       return((ttclos(0) < 0) ? -1 : 1);
  3750. #endif /* NETPTY */
  3751. #ifdef NETCONN
  3752.     if (netconn) {            /* Network connection. */
  3753. #ifdef TN_COMPORT
  3754.         if (istncomport()) {
  3755.             int rc = tnc_set_dtr_state(0);
  3756.             if (rc >= 0) {
  3757.                 msleep(HUPTIME);
  3758.                 rc = tnc_set_dtr_state(1);
  3759.             }
  3760.             return(rc >= 0 ? 1 : -1);
  3761.         } else
  3762. #endif /* TN_COMPORT */
  3763.       return((netclos() < 0) ? -1 : 1); /* Just close it. */
  3764.   }
  3765. #endif /* NETCONN */
  3766.  
  3767. /* From here down, we handle real tty devices. */
  3768. #ifdef HUP_POSIX
  3769. /*
  3770.   e.g. for Unixware 2, where we don't have a full POSIX build, we
  3771.   still have to use POSIX-style hangup.  Thus the duplication of this
  3772.   and the next case, the only difference being we use a local termios
  3773.   struct here, since a different model is used elsewhere.
  3774.  
  3775.   NO LONGER USED as of C-Kermit 8.0 -- it turns out that this method,
  3776.   even though it compiles and executes without error, doesn't actually
  3777.   work (i.e. DTR does not drop), whereas the TIOCSDTR method works just fine,
  3778. */
  3779.     {
  3780.     struct termios ttcur;
  3781.     int x;
  3782.     debug(F100,"tthang HUP_POSIX style","",0);
  3783.     x = tcgetattr(ttyfd, &ttcur);    /* Get current attributes */
  3784.     debug(F111,"tthang tcgetattr",ckitoa(errno),x);
  3785.     if (x < 0) return(-1);
  3786.     spdsav = cfgetospeed(&ttcur);    /* Get current speed */
  3787.     debug(F111,"tthang cfgetospeed",ckitoa(errno),spdsav);
  3788.     spdsavi = cfgetispeed(&ttcur);    /* Get current speed */
  3789.     debug(F111,"tthang cfgetispeed",ckitoa(errno),spdsavi);
  3790.     x = cfsetospeed(&ttcur,B0);    /* Replace by 0 */
  3791.     debug(F111,"tthang cfsetospeed",ckitoa(errno),x);
  3792.     if (x < 0) return(-1);
  3793.     x = cfsetispeed(&ttcur,B0);
  3794.     debug(F111,"tthang cfsetispeed",ckitoa(errno),x);
  3795.     if (x < 0) return(-1);
  3796.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3797.     debug(F111,"tthang tcsetattr B0",ckitoa(errno),x);
  3798.     if (x < 0) return(-1);
  3799.     msleep(HUPTIME);        /* Sleep 0.5 sec */
  3800.     x = cfsetospeed(&ttcur,spdsav); /* Restore prev speed */
  3801.     if (x < 0) return(-1);
  3802.     debug(F111,"tthang cfsetospeed prev",ckitoa(errno),x);
  3803.     x = cfsetispeed(&ttcur,spdsavi);
  3804.     debug(F111,"tthang cfsetispeed prev",ckitoa(errno),x);
  3805.     if (x < 0) return(-1);
  3806.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3807.     debug(F111,"tthang tcsetattr restore",ckitoa(errno),x);
  3808.     if (x < 0) return(-1);
  3809.     return(1);
  3810.     }
  3811. #else
  3812. #ifdef BSD44ORPOSIX
  3813. #ifdef QNX
  3814.     {
  3815.     int x;
  3816.     x = tcdropline(ttyfd,500);
  3817.     debug(F101,"tthang QNX tcdropline","",x);
  3818.     ttcur.c_cflag |= CLOCAL;
  3819.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3820.     debug(F101,"tthang QNX tcsetattr restore","",x);
  3821.     if (x < 0) {
  3822.         debug(F101,"tthang QNX tcsetattr restore errno","",errno);
  3823.         return(-1);
  3824.     }
  3825.     /* Fix flags - ensure O_NONBLOCK is off */
  3826.  
  3827.     errno = 0;
  3828.     debug(F101,"tthang QNX iniflags","",iniflags);
  3829.     if (fcntl(ttyfd, F_SETFL, iniflags) == -1) {
  3830.         debug(F101,"tthang QNX F_SETFL errno","",errno);
  3831.         return(-1);
  3832.     }
  3833.     return(x);
  3834.     }
  3835. #else  /* QNX */
  3836.     {
  3837.     int x;
  3838. #ifdef USE_TIOCSDTR
  3839.     debug(F100,"tthang BSD44ORPOSIX USE_TIOCSDTR","",0);
  3840.     errno = 0;
  3841.     x = ioctl(ttyfd, TIOCCDTR, NULL);
  3842.     debug(F111,"tthang BSD44ORPOSIX ioctl TIOCCDTR",ckitoa(errno),x);
  3843.     if (x < 0) return(-1);
  3844.     msleep(HUPTIME);        /* Sleep 0.5 sec */
  3845.     errno = 0;
  3846.     x = ioctl(ttyfd, TIOCSDTR, NULL);
  3847.     debug(F111,"tthang BSD44ORPOSIX ioctl TIOCSDTR",ckitoa(errno),x);
  3848.     if (x < 0) return(-1);
  3849. #else  /* USE_TIOCSDTR */
  3850.  
  3851. #ifdef HUP_CLOSE_POSIX
  3852. /*
  3853.   In OSR5 versions where TIOCSDTR is not defined (up to and including at
  3854.   least 5.0.6a) the POSIX APIs in the "#else" part below are available but
  3855.   don't work, and no other APIs are available that do work.  In this case
  3856.   we have to drop DTR by brute force: close and reopen the port.  This
  3857.   code actually works, but all the steps are crucial: setting CLOCAL, the
  3858.   O_NDELAY manipulations, etc.
  3859. */
  3860.     debug(F100,"tthang HUP_CLOSE_POSIX close/open","",0);
  3861.     debug(F101,"tthang HUP_CLOSE_POSIX O_NONBLOCK","",O_NONBLOCK);
  3862.     debug(F101,"tthang HUP_CLOSE_POSIX O_NDELAY","",O_NDELAY);
  3863.     errno = 0;
  3864.     x = tcgetattr(ttyfd, &ttcur);    /* Get current attributes */
  3865.     debug(F101,"tthang HUP_CLOSE_POSIX tcgetattr","",x);
  3866.     if (x < 0) {
  3867.         debug(F101,"tthang HUP_CLOSE_POSIX tcgetattr errno","",errno);
  3868.         return(-1);
  3869.     }
  3870.     errno = 0;
  3871.  
  3872.     x = close(ttyfd);        /* Close without releasing lock */
  3873.     if (x < 0) {
  3874.         debug(F101,"tthang HUP_CLOSE_POSIX close errno","",errno);
  3875.         return(-1);
  3876.     }
  3877.     errno = 0;
  3878.     x = msleep(500);        /* Pause half a second */
  3879.     if (x < 0) {            /* Or if that doesn't work, 1 sec */
  3880.         debug(F101,"tthang HUP_CLOSE_POSIX msleep errno","",errno);
  3881.         sleep(1);
  3882.     }
  3883.     errno = 0;
  3884.     ttyfd = priv_opn(ttnmsv, (O_RDWR|O_NDELAY)); /* Reopen the device */
  3885.     debug(F111,"tthang HUP_CLOSE_POSIX reopen",ttnmsv,ttyfd);
  3886.     if (ttyfd < 0) {
  3887.         debug(F101,"tthang HUP_CLOSE_POSIX reopen errno","",errno);
  3888.         return(-1);
  3889.     }
  3890.     debug(F101,"tthang HUP_CLOSE_POSIX re-ttopen ttyfd","",ttyfd);
  3891.  
  3892.     /* Restore previous attributes */
  3893.  
  3894.     errno = 0;
  3895.     tvtflg = 0;
  3896.     ttcur.c_cflag |= CLOCAL;
  3897.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3898.     debug(F101,"tthang HUP_CLOSE_POSIX tcsetattr restore","",x);
  3899.     if (x < 0) {
  3900.         debug(F101,"tthang HUP_CLOSE_POSIX tcsetattr restore errno",
  3901.           "",errno);
  3902.         return(-1);
  3903.     }
  3904.     /* Fix flags - ensure O_NDELAY and O_NONBLOCK are off */
  3905.  
  3906.     errno = 0;
  3907.         if ((x = fcntl(ttyfd, F_GETFL, 0)) == -1) {
  3908.         debug(F101,"tthang HUP_CLOSE_POSIX F_GETFL errno","",errno);
  3909.         return(-1);
  3910.     }
  3911.     debug(F101,"tthang HUP_CLOSE_POSIX flags","",x);
  3912.     errno = 0;
  3913.         x &= ~(O_NONBLOCK|O_NDELAY);
  3914.     debug(F101,"tthang HUP_CLOSE_POSIX flags to set","",x);
  3915.     debug(F101,"tthang HUP_CLOSE_POSIX iniflags","",iniflags);
  3916.     if (fcntl(ttyfd, F_SETFL, x) == -1) {
  3917.         debug(F101,"tthang HUP_CLOSE_POSIX F_SETFL errno","",errno);
  3918.         return(-1);
  3919.     }
  3920. #ifdef DEBUG
  3921.     if (deblog) {
  3922.         if ((x = fcntl(ttyfd, F_GETFL, 0)) > -1) {
  3923.         debug(F101,"tthang HUP_CLOSE_POSIX flags","",x);
  3924.         debug(F101,"tthang HUP_CLOSE_POSIX flags & O_NONBLOCK",
  3925.               "",x&O_NONBLOCK);
  3926.         debug(F101,"tthang HUP_CLOSE_POSIX flags & O_NDELAY",
  3927.               "",x&O_NDELAY);
  3928.         }
  3929.     }
  3930. #endif /* DEBUG */
  3931.  
  3932. #else  /* HUP_CLOSE_POSIX */
  3933.     
  3934.     /* General BSD44ORPOSIX case (Linux, BSDI, FreeBSD, etc) */
  3935.  
  3936.     debug(F100,"tthang BSD44ORPOSIX B0","",0);
  3937.     x = tcgetattr(ttyfd, &ttcur);    /* Get current attributes */
  3938.     debug(F111,"tthang BSD44ORPOSIX tcgetattr",ckitoa(errno),x);
  3939.     if (x < 0) return(-1);
  3940.     spdsav = cfgetospeed(&ttcur);    /* Get current speed */
  3941.     debug(F111,"tthang BSD44ORPOSIX cfgetospeed",ckitoa(errno),spdsav);
  3942.     spdsavi = cfgetispeed(&ttcur);    /* Get current speed */
  3943.     debug(F111,"tthang BSD44ORPOSIX cfgetispeed",ckitoa(errno),spdsavi);
  3944.     x = cfsetospeed(&ttcur,B0);    /* Replace by 0 */
  3945.     debug(F111,"tthang BSD44ORPOSIX cfsetospeed",ckitoa(errno),x);
  3946.     if (x < 0) return(-1);
  3947.     x = cfsetispeed(&ttcur,B0);
  3948.     debug(F111,"tthang BSD44ORPOSIX cfsetispeed",ckitoa(errno),x);
  3949.     if (x < 0) return(-1);
  3950.     /* This gets EINVAL on NetBSD 1.4.1 because of B0... */
  3951.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3952.     debug(F111,"tthang BSD44ORPOSIX tcsetattr B0",ckitoa(errno),x);
  3953.     if (x < 0) return(-1);
  3954.     msleep(HUPTIME);        /* Sleep 0.5 sec */
  3955.     debug(F101,"tthang BSD44ORPOSIX restore output speed","",spdsav);
  3956.     x = cfsetospeed(&ttcur,spdsav); /* Restore prev speed */
  3957.     debug(F111,"tthang BSD44ORPOSIX cfsetospeed prev",ckitoa(errno),x);
  3958.     if (x < 0) return(-1);
  3959.     debug(F101,"tthang BSD44ORPOSIX restore input speed","",spdsavi);
  3960.     x = cfsetispeed(&ttcur,spdsavi);
  3961.     debug(F111,"tthang BSD44ORPOSIX cfsetispeed prev",ckitoa(errno),x);
  3962.     if (x < 0) return(-1);
  3963.     ttcur.c_cflag |= CLOCAL;    /* Don't expect CD after hangup */
  3964.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3965.     debug(F111,"tthang BSD44ORPOSIX tcsetattr restore",ckitoa(errno),x);
  3966.     if (x < 0) return(-1);
  3967.  
  3968. #endif /* HUP_CLOSE_POSIX */
  3969. #endif /* USE_TIOCSDTR */
  3970.  
  3971.     return(1);
  3972.     }
  3973.  
  3974. #endif /* QNX */
  3975. #else /* BSD44ORPOSIX */
  3976.  
  3977. #ifdef aegis                /* Apollo Aegis */
  3978.     sio_$control((short)ttyfd, sio_$dtr, false, st);    /* DTR down */
  3979.     msleep(HUPTIME);                    /* pause */
  3980.     sio_$control((short)ttyfd, sio_$dtr, true,  st);    /* DTR up */
  3981.     return(1);
  3982. #endif /* aegis */
  3983.  
  3984. #ifdef ANYBSD                /* Any BSD version. */
  3985. #ifdef TIOCCDTR                /* Except those that don't have this */
  3986.     debug(F100,"tthang BSD style","",0);
  3987.     if (ioctl(ttyfd,TIOCCDTR,0) < 0) {    /* Clear DTR. */
  3988.     debug(F101,"tthang TIOCCDTR fails","",errno);
  3989.     return(-1);
  3990.     }
  3991.     msleep(HUPTIME);            /* For about 1/2 sec */
  3992.     errno = 0;
  3993.     x = ioctl(ttyfd,TIOCSDTR,0);    /* Restore DTR */
  3994.     if (x < 0) {
  3995.     /*
  3996.       For some reason, this tends to fail with "no such device or address"
  3997.       but the operation still works, probably because of the close/open
  3998.       later on.  So let's not scare the user unnecessarily here.
  3999.     */
  4000.     debug(F101,"tthang TIOCSDTR errno","",errno); /* Log the error */
  4001.     x = 1;                /* Pretend we succeeded */
  4002.     } else if (x == 0) x = 1;        /* Success */
  4003. #ifdef COMMENT
  4004. #ifdef FT21
  4005.     ioctl(ttyfd, TIOCSAVEMODES, 0);
  4006.     ioctl(ttyfd, TIOCHPCL, 0);
  4007.     close(ttyfd);            /* Yes, must do this twice */
  4008.     if ((ttyfd = open(ttnmsv,2)) < 0)    /* on Fortune computers... */
  4009.       return(-1);            /* (but why?) */
  4010.     else x = 1;
  4011. #endif /* FT21 */
  4012. #endif /* COMMENT */
  4013. #endif /* TIOCCDTR */
  4014.     close(do_open(ttnmsv));        /* Clear i/o error condition */
  4015.     errno = 0;
  4016. #ifdef COMMENT
  4017. /* This is definitely dangerous.  Why was it here? */
  4018.     z = ttvt(ttspeed,ttflow);        /* Restore modes. */
  4019.     debug(F101,"tthang ttvt returns","",z);
  4020.     return(z < 0 ? -1 : 1);
  4021. #else
  4022.     return(x);
  4023. #endif /* COMMENT */
  4024. #endif /* ANYBSD */
  4025.  
  4026. #ifdef ATTSV
  4027. /* AT&T UNIX section, includes HP-UX and generic AT&T System III/V... */
  4028.  
  4029. #ifdef HPUX
  4030. /* Hewlett Packard allows explicit manipulation of modem signals. */
  4031.  
  4032. #ifdef COMMENT
  4033. /* Old way... */
  4034.     debug(F100,"tthang HP-UX style","",0);
  4035.     if (ioctl(ttyfd,MCSETAF,&dtr_down) < 0)        /* lower DTR */
  4036.       return(-1);                           /* oops, can't. */
  4037.     msleep(HUPTIME);                       /* Pause half a second. */
  4038.     x = 1;                           /* Set return code */
  4039.     if (ioctl(ttyfd,MCGETA,&modem_rtn) > -1) {     /* Get line status. */
  4040.     if ((modem_rtn & MDCD) != 0)             /* Check if CD is low. */
  4041.       x = -1;                                  /* CD didn't drop, fail. */
  4042.     } else x = -1;
  4043.  
  4044.     /* Even if above calls fail, RTS & DTR should be turned back on. */
  4045.     modem_rtn = MRTS | MDTR;
  4046.     if (ioctl(ttyfd,MCSETAF,&modem_rtn) < 0) x = -1;
  4047.     return(x);
  4048. #else
  4049. /* New way, from Hellmuth Michaelis */
  4050.     debug(F100,"tthang HP-UX style, HPUXDEBUG","",0);
  4051.     if (ioctl(ttyfd,MCGETA,&modem_rtn) == -1) { /* Get current status. */
  4052.     debug(F100,"tthang HP-UX: can't get modem lines, NO HANGUP!","",0);
  4053.     return(-1);
  4054.     }
  4055.     sprintf(modem_state,"%#lx",modem_rtn);
  4056.     debug(F110,"tthang HP-UX: modem lines = ",modem_state,0);
  4057.     modem_sav = modem_rtn;        /* Save current modem signals */
  4058.     modem_rtn &= ~MDTR;            /* Turn DTR bit off */
  4059.     sprintf(modem_state,"%#lx",modem_rtn);
  4060.     debug(F110,"tthang HP-UX: DTR down = ",modem_state,0);
  4061.     if (ioctl(ttyfd,MCSETAF,&modem_rtn) < 0) { /* lower DTR */
  4062.     debug(F100,"tthang HP-UX: can't lower DTR!","",0);
  4063.     return(-1);            /* oops, can't. */
  4064.     }
  4065.     msleep(HUPTIME);            /* Pause half a second. */
  4066.     x = 1;                /* Set return code */
  4067.     if (ioctl(ttyfd,MCGETA,&modem_rtn) > -1) { /* Get line status. */
  4068.     sprintf(modem_state,"%#lx",modem_rtn);
  4069.     debug(F110,"tthang HP-UX: modem lines got = ",modem_state,0);
  4070.     if ((modem_rtn & MDCD) != 0) {    /* Check if CD is low. */
  4071.         debug(F100,"tthang HP-UX: DCD not down","",0);
  4072.         x = -1;            /* CD didn't drop, fail. */
  4073.     } else {
  4074.         debug(F100,"tthang HP-UX: DCD down","",0);
  4075.     }
  4076.     } else {
  4077.     x = -1;
  4078.     debug(F100,"tthang HP-UX: can't get DCD status !","",0);
  4079.     }
  4080.  
  4081.     /* Even if above calls fail, DTR should be turned back on. */
  4082.  
  4083.     modem_sav |= MDTR;
  4084.     if (ioctl(ttyfd,MCSETAF,&modem_sav) < 0) {
  4085.     x = -1;
  4086.     debug(F100,"tthang HP-UX: can't set saved state","",0);
  4087.     } else {
  4088.     sprintf(modem_state,"%#lx",modem_sav);
  4089.     debug(F110,"tthang HP-UX: final modem lines = ",modem_state,0);
  4090.     }
  4091.     return(x);
  4092. #endif /* COMMENT */
  4093.  
  4094. #else /* AT&T but not HP-UX */
  4095.  
  4096. /* SVID for AT&T System V R3 defines ioctl's for handling modem signals. */
  4097. /* It is not known how many, if any, systems actually implement them, */
  4098. /* so we include them here in ifdef's. */
  4099.  
  4100. /*
  4101.   Unixware has the TIOCMxxx symbols defined, but calling ioctl() with them
  4102.   gives error 22 (invalid argument).
  4103. */
  4104. #ifndef _IBMR2
  4105. /*
  4106.   No modem-signal twiddling for IBM RT PC or RS/6000.
  4107.   In AIX 3.1 and earlier, the ioctl() call is broken.
  4108.   This code could be activated for AIX 3.1 with PTF 2006 or later
  4109.   (e.g. AIX 3.2), but close/open does the job too, so why bother.
  4110. */
  4111. #ifdef TIOCMBIS                /* Bit Set */
  4112. #ifdef TIOCMBIC                /* Bit Clear */
  4113. #ifdef TIOCM_DTR            /* DTR */
  4114.  
  4115. /* Clear DTR, sleep 300 msec, turn it back on. */
  4116. /* If any of the ioctl's return failure, go on to the next section. */
  4117.  
  4118.     z = TIOCM_DTR;            /* Code for DTR. */
  4119. #ifdef COMMENT
  4120. /*
  4121.   This was the cause of the troubles with the Solaris Port Monitor.
  4122.   The problem is: RTS never comes back on.  Moral: Don't do it!
  4123.   (But why doesn't it come back on?  See the TIOCMBIS call...)
  4124. */
  4125. #ifdef TIOCM_RTS            /* Lower RTS too if symbol is known. */
  4126.     z |= TIOCM_RTS;
  4127. #endif /* TIOCM_RTS */
  4128. #endif /* COMMENT */
  4129.  
  4130.     debug(F101,"tthang TIOCM signal mask","",z);
  4131.     if (ioctl(ttyfd,TIOCMBIC,&z) > -1) {   /* Try to lower DTR. */
  4132.     debug(F100,"tthang TIOCMBIC ok","",0);
  4133.     msleep(HUPTIME);           /* Pause half a second. */
  4134.     if (ioctl(ttyfd,TIOCMBIS,&z) > -1) { /* Try to turn it back on. */
  4135.         debug(F100,"tthang TIOCMBIS ok","",0);
  4136. #ifndef CLSOPN
  4137.         return(1);            /* Success, done. */
  4138. #endif /* CLSOPN */
  4139.     } else {            /* Couldn't raise, continue. */
  4140.         debug(F101,"tthang TIOCMBIS errno","",errno);
  4141.     }
  4142.     } else {                /* Couldn't lower, continue. */
  4143.      debug(F101,"tthang TIOCMBIC errno","",errno);
  4144.     }
  4145. #endif /* TIOCM_DTR */
  4146. #endif /* TIOCMBIC */
  4147. #endif /* TIOCMBIS */
  4148. #endif /* _IBMR2 */
  4149.  
  4150. /*
  4151.   General AT&T UNIX case, not HPUX.  The following code is highly suspect.  No
  4152.   two AT&T-based systems seem to do this the same way.  The object is simply
  4153.   to turn off DTR and then turn it back on.  SVID says the universal method
  4154.   for turning off DTR is to set the speed to zero, and this does seem to do
  4155.   the trick in all cases.  But neither SVID nor any known man pages say how to
  4156.   turn DTR back on again.  Some variants, like most Xenix implementations,
  4157.   raise DTR again when the speed is restored to a nonzero value.  Others
  4158.   require the device to be closed and opened again, but this is risky because
  4159.   getty could seize the device during the instant it is closed.
  4160. */
  4161.  
  4162. /* Return code for ioctl failures... */
  4163. #ifdef ATT6300
  4164.     x = 1;                /* ATT6300 doesn't want to fail... */
  4165. #else
  4166.     x = -1;
  4167. #endif /* ATT6300 */
  4168.  
  4169.     debug(F100,"tthang get settings","",0);
  4170.     if (ioctl(ttyfd,TCGETA,&ttcur) < 0) /* Get current settings. */
  4171.       return(x);            /* Fail if this doesn't work. */
  4172.     if ((flags = fcntl(ttyfd,F_GETFL,0)) < 0) /* Get device flags. */
  4173.       return(x);
  4174.     ttc_save = ttcur.c_cflag;        /* Remember current speed. */
  4175.     spdsav = ttc_save & CBAUD;
  4176.     debug(F101,"tthang speed","",spdsav);
  4177.  
  4178. #ifdef O_NDELAY
  4179.     debug(F100,"tthang turning O_NDELAY on","",0);
  4180.     fcntl(ttyfd, F_SETFL, flags | O_NDELAY); /* Activate O_NDELAY */
  4181. #endif /* O_NDELAY */
  4182.  
  4183. #ifdef ATT7300 /* This is the way it is SUPPOSED to work */
  4184.     ttcur.c_cflag &= ~CBAUD;        /* Change the speed to zero.  */
  4185. #else
  4186. #ifdef RTAIX
  4187.     ttcur.c_cflag &= ~CBAUD;        /* Change the speed to zero.  */
  4188. #else          /* This way really works but may be dangerous */
  4189. #ifdef u3b2
  4190.     ttcur.c_cflag = ~(CBAUD|CLOCAL);    /* Special for AT&T 3B2s */
  4191.                     /* (CLOCAL must be OFF) */
  4192. #else
  4193. #ifdef SCO3R2                /* SCO UNIX 3.2 */
  4194. /*
  4195.   This is complete nonsense, but an SCO user claimed this change made
  4196.   hanging up work.  Comments from other SCO UNIX 3.2 users would be
  4197.   appreciated.
  4198. */
  4199.     ttcur.c_cflag = CBAUD|B0;
  4200. #else
  4201. #ifdef AIXRS                /* AIX on RS/6000 */
  4202. /*
  4203.   Can't set speed to zero on AIX 3.1 on RS/6000 64-port adapter,
  4204.   even though you can do it on the built-in port and the 8- and 16-port
  4205.   adapters.  (Untested on 128-port adapter.)
  4206. */
  4207.     ttcur.c_cflag = CLOCAL|HUPCL|spdsav; /* Speed 0 causes EINVAL */
  4208. #else                    /* None of the above */
  4209. /*
  4210.   Set everything, including the speed, to zero, except for the CLOCAL
  4211.   and HUPCL bits.
  4212. */
  4213.     ttcur.c_cflag = CLOCAL|HUPCL;
  4214. #endif /* AIXRS */
  4215. #endif /* SCO3R2 */
  4216. #endif /* u3b2 */
  4217. #endif /* RTAIX */
  4218. #endif /* ATT7300 */
  4219.  
  4220. #ifdef COMMENT
  4221.     /* and if none of those work, try one of these... */
  4222.     ttcur.c_cflag = 0;
  4223.     ttcur.c_cflag = CLOCAL;
  4224.     ttcur.c_cflag &= ~(CBAUD|HUPCL);
  4225.     ttcur.c_cflag &= ~(CBAUD|CREAD);
  4226.     ttcur.c_cflag &= ~(CBAUD|CREAD|HUPCL);
  4227.     /* or other combinations */
  4228. #endif /* COMMENT */
  4229.  
  4230. #ifdef TCXONC
  4231.     debug(F100,"tthang TCXONC","",0);
  4232.     if (ioctl(ttyfd, TCXONC, 1) < 0) {
  4233.     debug(F101,"tthang TCXONC failed","",errno);
  4234.     }
  4235. #endif /* TCXONC */
  4236.  
  4237. #ifdef TIOCSTART
  4238.     debug(F100,"tthang TIOCSTART","",0);
  4239.     if (ioctl(ttyfd, TIOCSTART, 0) < 0) {
  4240.     debug(F101,"tthang TIOCSTART failed","",errno);
  4241.     }
  4242. #endif /* TIOCSTART */
  4243.  
  4244.     if (ioctl(ttyfd,TCSETAF,&ttcur) < 0) { /* Fail if we can't. */
  4245.     debug(F101,"tthang TCSETAF failed","",errno);
  4246.     fcntl(ttyfd, F_SETFL, flags);    /* Restore flags */
  4247.     return(-1);            /* before returning. */
  4248.     }
  4249.     msleep(300);            /* Give modem time to notice. */
  4250.  
  4251. #ifndef NOCOTFMC
  4252.  
  4253. /* Now, even though it doesn't say this in SVID or any man page, we have */
  4254. /* to close and reopen the device.  This is not necessary for all systems, */
  4255. /* but it's impossible to predict which ones need it and which ones don't. */
  4256.  
  4257. #ifdef ATT7300
  4258. /*
  4259.   Special handling for ATT 7300 UNIX PC and 3B1, which have "phone"
  4260.   related ioctl's for their internal modems.  attmodem has getty status and
  4261.   modem-in-use bit.  Reportedly the ATT7300/3B1 PIOCDISC call is necessary,
  4262.   but also ruins the file descriptor, and no other phone(7) ioctl call can fix
  4263.   it.  Whatever it does, it seems to escape detection with PIOCGETA and TCGETA.
  4264.   The only way to undo the damage is to close the fd and then reopen it.
  4265. */
  4266.     if (attmodem & ISMODEM) {
  4267.     debug(F100,"tthang attmodem close/open","",0);
  4268.     ioctl(ttyfd,PIOCUNHOLD,&dialer); /* Return call to handset. */
  4269.     ioctl(ttyfd,PIOCDISC,&dialer);    /* Disconnect phone. */
  4270.     close(ttyfd);            /* Close and reopen the fd. */
  4271.     ttyfd = priv_opn(ttnmsv, O_RDWR | O_NDELAY);
  4272.     attmodem &= ~ISMODEM;        /* Phone no longer in use. */
  4273.     }
  4274. #else /* !ATT7300 */
  4275. /* It seems we have to close and open the device for other AT&T systems */
  4276. /* too, and this is the place to do it.  The following code does the */
  4277. /* famous close(open(...)) magic by default.  If that doesn't work for you, */
  4278. /* then try uncommenting the following statement or putting -DCLSOPN in */
  4279. /* the makefile CFLAGS. */
  4280.  
  4281. /* #define CLSOPN */
  4282.  
  4283. #ifndef SCO32 /* Not needed by, and harmful to, SCO UNIX 3.2 / Xenix 2.3 */
  4284.  
  4285. #ifdef O_NDELAY
  4286. #define OPENFLGS O_RDWR | O_NDELAY
  4287. #else
  4288. #define OPENFLGS O_RDWR
  4289. #endif
  4290.  
  4291. #ifndef CLSOPN
  4292. /* This method is used by default, i.e. unless CLSOPN is defined. */
  4293. /* It is thought to be safer because there is no window where getty */
  4294. /* can seize control of the device.  The drawback is that it might not work. */
  4295.  
  4296.     debug(F101,"tthang close(open()), OPENFLGS","",OPENFLGS);
  4297.     close(priv_opn(ttnmsv, OPENFLGS));
  4298.  
  4299. #else
  4300. /* This method is used if you #define CLSOPN.  It is more likely to work */
  4301. /* than the previous method, but it's also more dangerous. */
  4302.  
  4303.     debug(F101,"tthang close/open, OPENFLGS","",OPENFLGS);
  4304.     close(ttyfd);
  4305.     msleep(10);
  4306.     ttyfd = priv_opn(ttnmsv, OPENFLGS);    /* Open it again */
  4307. #endif /* CLSOPN */
  4308. #undef OPENFLGS
  4309.  
  4310. #endif /* SCO32 */
  4311. #endif /* ATT7300 */
  4312.  
  4313. #endif /* NOCOTFMC */
  4314.  
  4315. /* Now put all flags & modes back the way we found them. */
  4316. /* (Does the order of ioctl & fcntl matter ? ) */
  4317.  
  4318.     debug(F100,"tthang restore settings","",0);
  4319.     ttcur.c_cflag = ttc_save;        /* Get old speed back. */
  4320.     if (ioctl(ttyfd,TCSETAF,&ttcur) < 0) /* ioctl parameters. */
  4321.       return(-1);
  4322. #ifdef O_NDELAY
  4323. /*
  4324.   This is required for IBM RT and RS/6000, probably helps elsewhere too (?).
  4325.   After closing a modem line, the modem will probably not be asserting
  4326.   carrier any more, so we should not require carrier any more.  If this
  4327.   causes trouble on non-IBM UNIXes, change the #ifdef to use _IBMR2 rather
  4328.   than O_NDELAY.
  4329. */
  4330.     flags &= ~O_NDELAY;            /* Don't require carrier on reopen */
  4331. #endif /* O_NDELAY */
  4332.     if (fcntl(ttyfd,F_SETFL,flags) < 0)    /* fcntl parameters */
  4333.       return(-1);
  4334.  
  4335.     return(1);
  4336. #endif /* not HPUX */
  4337. #endif /* ATTSV */
  4338. #endif /* BSD44ORPOSIX */
  4339. #endif /* HUP_POSIX */
  4340. #endif /* NOLOCAL */
  4341. }
  4342.  
  4343. /*
  4344.   Major change in 5A(174).  We used to use LPASS8, if it was defined, to
  4345.   allow 8-bit data and Xon/Xoff flow control at the same time.  But this
  4346.   LPASS8 business seems to have been causing trouble for everybody but me!
  4347.   For example, Annex terminal servers, commonly used with Encore computers,
  4348.   do not support LPASS8 even though the Encore itself does.  Ditto for many
  4349.   other terminal servers, TELNET connections, rlogin connections, etc etc.
  4350.   Now, reportedly, even vanilla 4.3 BSD systems can't do this right on their
  4351.   serial lines, even though LPASS8 is a feature of 4.3BSD.  So let's turn it
  4352.   off for everybody.  That means we goes back to using raw mode, with no
  4353.   flow control.  Phooey.
  4354.  
  4355.   NOTE: This must be done before the first reference to LPASS8 in this file,
  4356.   and after the last #include statment.
  4357. */
  4358. #ifdef LPASS8
  4359. #undef LPASS8
  4360. #endif /* LPASS8 */
  4361.  
  4362. /*  T T R E S  --  Restore terminal to "normal" mode.  */
  4363.  
  4364. /* ske@pkmab.se: There are two choices for what this function should do.
  4365.  * (1) Restore the tty to current "normal" mode, with carrier treatment
  4366.  * according to ttcarr, to be used after every kermit command. (2) Restore
  4367.  * the tty to the state it was in before kermit opened it. These choices
  4368.  * conflict, since ttold can't hold both choices of tty parameters.  ttres()
  4369.  * is currently being called as in choice (1), but ttold basically holds
  4370.  * the initial parameters, as in (2), and the description at the beginning
  4371.  * of this file says (2).
  4372.  *
  4373.  * I don't think restoring tty parameters after all kermit commands makes
  4374.  * much of a difference.  Restoring them upon exit from kermit may be of
  4375.  * some use in some cases (when the line is not restored automatically on
  4376.  * close, by the operating system).
  4377.  *
  4378.  * I can't choose which one it should be, so I haven't changed it. It
  4379.  * probably works as it is, too. It would probably even work even with
  4380.  * ttres() entirely deleted...
  4381.  *
  4382.  * (from fdc: Actually, this function operates in remote mode too, so
  4383.  * it restores the console (command) terminal to whatever mode it was
  4384.  * in before packet operations began, so that commands work right again.)
  4385.  */
  4386. int
  4387. ttres() {                               /* Restore the tty to normal. */
  4388.     int x;
  4389.  
  4390.     if (ttyfd < 0) return(-1);          /* Not open. */
  4391.  
  4392.     if (ttfdflg) return(0);        /* Don't mess with terminal modes if */
  4393.                     /* we got ttyfd from another process */
  4394. #ifdef    NETCONN
  4395.     if (netconn) {            /* Network connection */
  4396.         tvtflg = 0;
  4397. #ifdef TCPSOCKET
  4398. #ifdef TCP_NODELAY
  4399.         {
  4400.         extern int tcp_nodelay;    /* Just put this back if necessary */
  4401.         if (ttnet == NET_TCPB) {
  4402.         if (nodelay_sav > -1) {
  4403.             no_delay(ttyfd,nodelay_sav);
  4404.             nodelay_sav = -1;
  4405.         }
  4406.         }
  4407.         }
  4408. #endif /* TCP_NODELAY */
  4409. #ifdef TN_COMPORT
  4410.         if (istncomport()) {
  4411.             int rc = -1;
  4412.             if ((rc = tnsetflow(ttflow)) < 0)
  4413.           return(rc);
  4414.             if (ttspeed <= 0) 
  4415.           ttspeed = tnc_get_baud();
  4416.             else if ((rc = tnc_set_baud(ttspeed)) < 0)
  4417.           return(rc);
  4418.             tnc_set_datasize(8);
  4419.         tnc_set_stopsize(stopbits);
  4420.  
  4421. #ifdef HWPARITY
  4422.             if (hwparity) {
  4423.                 switch (hwparity) {
  4424.           case 'e':            /* Even */
  4425.                     debug(F100,"ttres 8 bits + even parity","",0);
  4426.                     tnc_set_parity(3);
  4427.                     break;
  4428.           case 'o':            /* Odd */
  4429.                     debug(F100,"ttres 8 bits + odd parity","",0);
  4430.                     tnc_set_parity(2);
  4431.                     break;
  4432.           case 'm':            /* Mark */
  4433.                     debug(F100,"ttres 8 bits + invalid parity: mark","",0);
  4434.                     tnc_set_parity(4);
  4435.                     break;
  4436.           case 's':            /* Space */
  4437.                     debug(F100,"ttres 8 bits + invalid parity: space","",0);
  4438.                     tnc_set_parity(5);
  4439.                     break;
  4440.                 }
  4441.             } else
  4442. #endif /* HWPARITY */
  4443.         {
  4444.                 tnc_set_parity(1);              /* None */
  4445.             }
  4446.             tvtflg = 0;
  4447.             return(0);
  4448.         }
  4449. #endif /* TN_COMPORT */
  4450. #endif /* TCPSOCKET */
  4451.     return(0);
  4452.     }
  4453. #endif    /* NETCONN */
  4454. #ifdef NETCMD
  4455.     if (ttpipe) return(0);
  4456. #endif /* NETCMD */
  4457. #ifdef NETPTY
  4458.     if (ttpty) return(0);
  4459. #endif /* NETPTY */
  4460.  
  4461. /* Real terminal device, so restore its original modes */
  4462.  
  4463. #ifdef BSD44ORPOSIX            /* For POSIX like this */
  4464.     debug(F100,"ttres BSD44ORPOSIX","",0);
  4465.     x = tcsetattr(ttyfd,TCSADRAIN,&ttold);
  4466. #else                    /* For all others... */
  4467. #ifdef ATTSV                            /* For AT&T versions... */
  4468.     debug(F100,"ttres ATTSV","",0);
  4469.     x = ioctl(ttyfd,TCSETAW,&ttold);    /* Restore tty modes this way. */
  4470. #else
  4471. /* Here we restore the modes for BSD */
  4472.  
  4473. #ifdef LPASS8                /* Undo "pass8" if it were done */
  4474.     if (lmodef) {
  4475.     if (ioctl(ttyfd,TIOCLSET,&lmode) < 0)
  4476.       debug(F100,"ttres TIOCLSET failed","",0);
  4477.     else
  4478.       debug(F100,"ttres TIOCLSET ok","",0);
  4479.     }
  4480. #endif /* LPASS8 */
  4481.  
  4482. #ifdef CK_DTRCTS           /* Undo hardware flow if it were done */
  4483.     if (lmodef) {
  4484.      if (ioctl(ttyfd,TIOCLSET,&lmode) < 0)
  4485.        debug(F100,"ttres TIOCLSET failed","",0);
  4486.      else
  4487.        debug(F100,"ttres TIOCLSET ok","",0);
  4488.     }
  4489. #endif /* CK_DTRCTS */
  4490.  
  4491. #ifdef TIOCGETC                /* Put back special characters */
  4492.     if (tcharf && (xlocal == 0)) {
  4493.     if (ioctl(ttyfd,TIOCSETC,&tchold) < 0)
  4494.       debug(F100,"ttres TIOCSETC failed","",0);
  4495.     else
  4496.       debug(F100,"ttres TIOCSETC ok","",0);
  4497.     }
  4498. #endif /* TIOCGETC */
  4499.  
  4500. #ifdef TIOCGLTC                /* Put back local special characters */
  4501.     if (ltcharf && (xlocal == 0)) {
  4502.     if (ioctl(ttyfd,TIOCSLTC,<chold) < 0)
  4503.       debug(F100,"ttres TIOCSLTC failed","",0);
  4504.     else
  4505.       debug(F100,"ttres TIOCSLTC ok","",0);
  4506.     }
  4507. #endif /* TIOCGLTC */
  4508.  
  4509. #ifdef BELLV10
  4510.     debug(F100,"ttres BELLV10","",0);
  4511.     x = ioctl(ttyfd,TIOCSETP,&ttold);    /* Restore both structs */
  4512.     x = ioctl(ttyfd,TIOCSDEV,&tdold);
  4513. #else
  4514.     debug(F100,"ttres stty","",0);
  4515.     x = stty(ttyfd,&ttold);             /* Restore tty modes the old way. */
  4516. #endif /* BELLV10 */
  4517.  
  4518.     if (!xlocal)
  4519.       msleep(100);            /* This replaces sleep(1)... */
  4520.                     /* Put back sleep(1) if tty is */
  4521.                     /* messed up after close. */
  4522. #endif /* ATTSV */
  4523. #endif /* BSD44ORPOSIX */
  4524.  
  4525.     debug(F101,"ttres result","",x);
  4526. #ifndef QNX
  4527.     if (x < 0) debug(F101,"ttres errno","",errno);
  4528. #endif /* QNX */
  4529.  
  4530. #ifdef AIXRS
  4531. #ifndef AIX41
  4532.     x = ioctl(ttyfd, ttld & 1 ? TXADDCD : TXDELCD, "rts");
  4533.     debug(F101,"ttres AIX line discipline rts restore","",x);
  4534. #endif /* AIX41 */
  4535. #endif /* AIXRS */
  4536.  
  4537. #ifdef BSD41
  4538.     if (ttld > -1) {            /* Put back line discipline */
  4539.     x = ioctl(ttyfd, TIOCSETD, &ttld);
  4540.     debug(F101,"ttres BSD41 line discipline restore","",x);
  4541.     if (x < 0) debug(F101,"...ioctl errno","",errno);
  4542.     ttld = -1;
  4543.     }
  4544. #endif /* BSD41 */
  4545.  
  4546. #ifdef sony_news
  4547.     x = xlocal ? km_ext : km_con;    /* Restore Kanji mode. */
  4548.     if (x != -1) {            /* Make sure we know original modes. */
  4549.     if (ioctl(ttyfd,TIOCKSET, &x) < 0) {
  4550.         perror("ttres can't set Kanji mode");
  4551.         debug(F101,"ttres error setting Kanji mode","",x);
  4552.         return(-1);
  4553.     }
  4554.     }
  4555.     debug(F100,"ttres set Kanji mode ok","",0);
  4556. #endif /* sony_news */
  4557.  
  4558.     tvtflg = 0;                /* Invalidate terminal mode settings */
  4559.     debug(F101,"ttres return code","",x);
  4560.     return(x);
  4561. }
  4562.  
  4563. #ifndef NOUUCP
  4564.  
  4565. /*  T T C H K P I D  --  Check lockfile pid  */
  4566. /*
  4567.   Read pid from lockfile named f, check that it's still valid.
  4568.   If so, return 1.
  4569.   On failure to read pid, return 1.
  4570.   Otherwise, try to delete lockfile f and return 0 if successful, else 1.
  4571. */
  4572. static int
  4573. ttchkpid(f) char *f; {
  4574.     int pid, mypid, x;
  4575.     pid = ttrpid(f);            /* Read pid from file. */
  4576.     if (pid > -1) {            /* If we were able to read the pid.. */
  4577.     debug(F101,"ttchkpid lock pid","",pid);
  4578.     errno = 0;            /* See if process still exists. */
  4579.     mypid = (int)getpid();        /* Get my own pid. */
  4580.     debug(F101,"ttchkpid my pid","",mypid);
  4581.     if (pid == mypid) {        /* It's me! */
  4582.         x = -1;            /* So I can delete it */
  4583.         errno = ESRCH;        /* pretend it's invalid */
  4584.     } else {            /* It's not me */
  4585.         x = kill((PID_T)pid, 0);    /* See if it's a live process */
  4586.         debug(F101,"ttchkpid kill errno","",errno);
  4587.     }
  4588.     debug(F101,"ttchkpid pid test","",x);
  4589.     if (x < 0 && errno == ESRCH) { /* pid is invalid */
  4590.         debug(F111,"removing stale lock",f,pid);
  4591.         if (!backgrd)
  4592.           printf("Removing stale lock %s (pid %d terminated)\n", f, pid);
  4593.         priv_on();
  4594.         x = unlink(f);        /* Remove the lockfile. */
  4595.         priv_off();
  4596.         debug(F111,"ttchkpid unlink",f,x);
  4597.         if (x > -1)
  4598.           return(0);        /* Device is not locked after all */
  4599.         else if (!backgrd)
  4600.           perror(f);
  4601.     }
  4602.     return(1);
  4603.     }
  4604.     return(1);                /* Failure to read pid */
  4605. }
  4606.  
  4607. #ifdef HPUX
  4608.  
  4609. /* Aliases (different drivers) for HP-UX dialout devices: */
  4610.  
  4611. static char *devprefix[] = { "tty", "ttyd", "cul", "cua", "cuad", "culd", "" };
  4612. static int ttydexists = 0;
  4613.  
  4614. #endif /* HPUX */
  4615.  
  4616. /*  T T R P I D  --  Read pid from lockfile "name" */
  4617.  
  4618. static int
  4619. ttrpid(name) char *name; {
  4620.     long len;
  4621.     int x, fd, pid;
  4622.     short spid;
  4623.     char buf[32];
  4624.  
  4625.     debug(F110,"ttrpid",name,0);
  4626.     if (!name) return(-1);
  4627.     if (!*name) return(-1);
  4628.     priv_on();
  4629.     len = zchki(name);            /* Get file length */
  4630.     priv_off();
  4631.     debug(F101,"ttrpid zchki","",len);
  4632.     if (len < 0)
  4633.       return(-1);
  4634.     if (len > 31)
  4635.       return(-1);
  4636.     priv_on();
  4637.     fd = open(name,O_RDONLY);        /* Try to open lockfile. */
  4638.     priv_off();
  4639.     debug(F101,"ttrpid fd","",fd);
  4640.     if (fd <= 0)
  4641.       return(-1);
  4642. /*
  4643.   Here we try to be flexible and allow for all different binary and string
  4644.   formats at runtime, rather than a specific format for each configuration
  4645.   hardwired at compile time.
  4646. */
  4647.     pid = -1;
  4648. #ifndef COHERENT
  4649. /*
  4650.   COHERENT uses a string PID but without leading spaces or 0's, so there is
  4651.   no way to tell from the file's length whether it contains a string or binary
  4652.   pid.  So for COHERENT only, we only allow string pids.  For all others, we
  4653.   decide based on the size of the lockfile.
  4654. */
  4655.     if (len > 4) {            /* If file > 4 bytes it's a string */
  4656. #endif /* COHERENT */
  4657.     x = read(fd,buf,(int)len);
  4658.     debug(F111,"ttrpid string read",buf,x);
  4659.     if (x < 0) {
  4660.         pid = -1;
  4661.     } else {
  4662.         buf[31] = '\0';
  4663.         x = sscanf(buf,"%d",&pid);    /* Get the integer pid from it. */
  4664.     }
  4665. #ifndef COHERENT
  4666.     } else if (len == 4) {        /* 4 bytes so binary */
  4667.     x = read(fd, (char *)&pid, 4);    /* Read the bytes into an int */
  4668.     debug(F101,"ttrpid integer read","",x);
  4669.     if (x < 4)
  4670.       pid = -1;
  4671.     } else if (len == 2) {        /* 2 bytes binary */
  4672.     x = read(fd, (char *)&spid, 2);    /* Read the bytes into a short */
  4673.     debug(F101,"ttrpid short read","",x);
  4674.     if (x < 2)
  4675.       pid = -1;
  4676.     else
  4677.       pid = spid;
  4678.     } else
  4679.       pid = -1;
  4680. #endif /* COHERENT */
  4681.     close(fd);                /* Close the lockfile */
  4682.     debug(F101,"ttrpid pid","",pid);
  4683.     return(pid);
  4684. }
  4685. #endif /* NOUUCP */
  4686.  
  4687. /*  T T L O C K  */
  4688.  
  4689. /*
  4690.   This function attempts to coordinate use of the communication device with
  4691.   other copies of Kermit and any other program that follows the UUCP
  4692.   device-locking conventions, which, unfortunately, vary among different UNIX
  4693.   implementations.  The idea is to look for a file of a certain name, the
  4694.   "lockfile", in a certain directory.  If such a file is found, then the line
  4695.   is presumed to be in use, and Kermit should not use it.  If no such file is
  4696.   found, Kermit attempts to create one so that other programs will not use the
  4697.   same line at the same time.  Because the lockfile and/or the directory it's
  4698.   in might lack write permission for the person running Kermit, Kermit could
  4699.   find itself running setuid to uucp or other user that does have the
  4700.   necessary permissions.  At startup, Kermit has changed its effective uid to
  4701.   the user's real uid, and so ttlock() must switch back to the original
  4702.   effective uid in order to create the lockfile, and then back again to the
  4703.   real uid to prevent unauthorized access to other directories or files owned
  4704.   by the user the program is setuid to.
  4705.  
  4706.   Totally rewritten for C-Kermit 5A to eliminate windows of vulnerability,
  4707.   based on suggestions from Warren Tucker.  Call with pointer to name of
  4708.   tty device.  Returns:
  4709.  
  4710.    0 on success
  4711.   -1 on failure
  4712.  
  4713.   Note: Once privileges are turned on using priv_on(), it is essential that
  4714.   they are turned off again before this function returns.
  4715. */
  4716. #ifdef SVR4                /* Lockfile uses device numbers. */
  4717. /*
  4718.   Although I can't find this in writing anywhere (e.g. in SVID for SVR4),
  4719.   it is the behavior of the "reference version" of SVR4, i.e. the Intel
  4720.   port from UNIX Systems Laboratories, then called Univel UnixWare,
  4721.   then called Novell UnixWare, then called SCO Unixware, then called Caldera
  4722.   Open UNIX...  It also makes much more sense than device-name-based lockfiles
  4723.   since there can be multiple names for the same device, symlinks, etc.
  4724. */
  4725. #ifndef NOLFDEVNO
  4726. #ifndef LFDEVNO                /* Define this for SVR4 */
  4727. #ifndef AIXRS                /* But not for RS/6000 AIX 3.2, etc. */
  4728. #ifndef BSD44                /* If anybody else needs it... */
  4729. #ifndef __386BSD__
  4730. #ifndef __FreeBSD__
  4731. #ifndef HPUX10
  4732. #ifndef IRIX51                /* SGI IRIX 5.1 or later */
  4733. #ifndef CK_SCOV5            /* SCO Open Server 5.0 */
  4734. #define LFDEVNO
  4735. #endif /* CK_SCOV5 */
  4736. #endif /* IRIX51 */
  4737. #endif /* HPUX10 */
  4738. #endif /* __FreeBSD__ */
  4739. #endif /* __386BSD__ */
  4740. #endif /* BSD44 */
  4741. #endif /* AIXRS */
  4742. #endif /* LFDEVNO */            /* ... define it here or on CC */
  4743. #endif /* NOLFDEVNO */
  4744. #endif /* SVR4 */            /* command line. */
  4745.  
  4746. #ifdef COHERENT
  4747. #define LFDEVNO
  4748. #endif /* COHERENT */
  4749.  
  4750. /*
  4751.   For platforms where the lockfile name is made from device/major/minor
  4752.   device number, as in SVR4.  Which, if we must have lockfiles at all, is
  4753.   by far the best format, since it eliminates all the confusion that stems
  4754.   from multiple names (or drivers) for the same port, not to mention
  4755.   symlinks.  It might even be a good idea to start using this form even
  4756.   on platforms where it's not supported, alongside the normal forms for those
  4757.   platforms, in order to get people used to it...
  4758. */
  4759. #ifdef LFDEVNO
  4760. #ifndef major                /* If we didn't find it */
  4761. #ifdef SVR4                /* then for Sys V R4 */
  4762. #include <sys/mkdev.h>            /* look here */
  4763. #else                    /* or for SunOS versions */
  4764. #ifdef SUNOS4                /* ... */
  4765. #include <sys/sysmacros.h>        /* look here */
  4766. #else                    /* Otherwise take a chance: */
  4767. #define    major(dev) ( (int) ( ((unsigned)(dev) >> 8) & 0xff))
  4768. #define    minor(dev) ( (int) ( (dev) & 0xff))
  4769. #endif /* SUNOS4 */
  4770. #endif /* SVR4 */
  4771. #endif /* major */
  4772. #endif /* LFDEVNO */
  4773.  
  4774. /* No advisory locks if F_TLOCK and F_ULOCK are not defined at this point */
  4775.  
  4776. #ifdef LOCKF
  4777. #ifndef F_TLOCK
  4778. #undef LOCKF
  4779. #ifndef NOLOCKF
  4780. #define NOLOCKF
  4781. #endif /* NOLOCKF */
  4782. #endif /* F_TLOCK */
  4783. #endif /* LOCKF */
  4784.  
  4785. #ifdef LOCKF
  4786. #ifndef F_ULOCK
  4787. #undef LOCKF
  4788. #ifndef NOLOCKF
  4789. #define NOLOCKF
  4790. #endif /* NOLOCKF */
  4791. #endif /* F_ULOCK */
  4792. #endif /* LOCKF */
  4793.  
  4794. static char linkto[DEVNAMLEN+1];
  4795. static char * linkdev = NULL;
  4796.  
  4797. #ifndef NOUUCP
  4798. #ifdef USETTYLOCK
  4799. #ifdef LOCK_DIR
  4800. char * uucplockdir = LOCK_DIR;
  4801. #else
  4802. char * uucplockdir = "";
  4803. #endif /* LOCK_DIR */
  4804. #else
  4805. #ifdef LOCK_DIR
  4806. char * uucplockdir = LOCK_DIR;
  4807. #else
  4808. char * uucplockdir = "";
  4809. #endif /* LOCK_DIR */
  4810. #endif /* USETTYLOCK */
  4811. #else
  4812. char * uucplockdir = "";
  4813. #endif /* NOUUCP */
  4814.  
  4815. #ifdef QNX                /* Only for QNX4 */
  4816. int                    /* Visible to outside world */
  4817. qnxopencount() {            /* Get QNX device open count */
  4818.     struct _dev_info_entry info;
  4819.     int x;
  4820.  
  4821.     x = -1;                /* Unknown */
  4822.     if (ttyfd > -1) {
  4823.     if (!dev_info(ttyfd, &info)) {
  4824.         debug(F101,"ttlock QNX open_count","",info.open_count);
  4825.         x = info.open_count;
  4826.     }
  4827.     }
  4828.     return(x);
  4829. }
  4830. #endif /* QNX */
  4831.  
  4832. char *
  4833. ttglckdir() {                /* Get Lockfile directory name */
  4834. #ifdef __OpenBSD__
  4835.     return("/var/spool/lock");
  4836. #else /* __OpenBSD__ */
  4837. #ifdef __FreeBSD__
  4838.     return("/var/spool/lock");
  4839. #else  /* __FreeBSD__ */
  4840. #ifdef LOCK_DIR
  4841.     char * s = LOCK_DIR;
  4842. #endif /* LOCK_DIR */
  4843. #ifdef NOUUCP
  4844.     return("");
  4845. #else  /* NOUUCP */
  4846. #ifdef LOCK_DIR
  4847.     return(s);
  4848. #else  /* LOCK_DIR */
  4849.     return("");
  4850. #endif /* LOCK_DIR */
  4851. #endif /* NOUUCP */
  4852. #endif /* __FreeBSD__ */
  4853. #endif /* __OpenBSD__ */
  4854. }
  4855.  
  4856. static int
  4857. ttlock(ttdev) char *ttdev; {
  4858.  
  4859.     int x, n;
  4860.     int islink = 0;
  4861.  
  4862. #ifdef NOUUCP
  4863.     debug(F100,"ttlock NOUUCP","",0);
  4864.     ckstrncpy(flfnam,"NOLOCK",FLFNAML);
  4865.     haslock = 1;
  4866.     return(0);
  4867. #else /* !NOUUCP */
  4868.  
  4869. #ifdef USETTYLOCK
  4870.     haslock = 0;                        /* Not locked yet. */
  4871.     *flfnam = '\0';            /* Lockfile name is empty. */
  4872.     if (!strncmp(ttdev,"/dev/",5) && ttdev[5])
  4873.       ckstrncpy(lockname,ttdev+5,DEVNAMLEN);
  4874.     else
  4875.       ckstrncpy(lockname,ttdev,DEVNAMLEN);
  4876. /*
  4877.   This might be overkill, but it's not clear from the man pages whether
  4878.   ttylock() can be called without calling ttylocked() first, since the doc
  4879.   says that ttylocked() removes any stale lockfiles, but it does not say this
  4880.   about ttylock().  Also the docs don't say what ttylocked() returns in the
  4881.   case when it finds and removes a stale lockfile.  So one or both calls to
  4882.   to ttylocked() might be superfluous, but they should do no harm.  Also I'm
  4883.   assuming that we have to do all the same ID swapping, etc, with these
  4884.   routines as we do without them.  Thus the priv_on/off() sandwich.
  4885. */
  4886. #ifdef USE_UU_LOCK
  4887.     priv_on();                /* Turn on privs */
  4888.     x = uu_lock(lockname);        /* Try to set the lock */
  4889.     priv_off();                /* Turn privs off */
  4890.     debug(F111,"ttlock uu_lock",lockname,x);
  4891.     switch (x) {
  4892.       case UU_LOCK_INUSE:
  4893.     return(-2);
  4894.       case UU_LOCK_OK:
  4895. #ifdef BSD44
  4896.     ckmakmsg(flfnam,FLFNAML,"/var/spool/lock/LCK..",lockname,NULL,NULL);
  4897. #endif /* BSD44 */
  4898.     haslock = 1;
  4899.     return(0);
  4900.       default:
  4901.     return(-1);
  4902.     }
  4903. #else  /* USE_UU_LOCK */
  4904.     priv_on();                /* Turn on privs */
  4905.     if (ttylocked(lockname)) {        /* This should remove any stale lock */
  4906.     if (ttylocked(lockname)) {    /* so check again. */
  4907.         priv_off();
  4908.         return(-5);            /* Still locked, fail. */
  4909.     }
  4910.     }
  4911.     x = ttylock(lockname);        /* Lock it. */
  4912.     priv_off();                /* Turn off privs */
  4913.  
  4914.     debug(F111,"ttlock lockname",lockname,x);
  4915.     if (x > -1) {
  4916.     /*
  4917.       We don't really know the name of the lockfile, but
  4918.       this is what the man page says it is.  In USETTYLOCK
  4919.           builds, it is used only for display by SHOW COMM.
  4920.     */
  4921.     ckmakmsg(flfnam,FLFNAML,"/etc/locks/LCK..",lockname,NULL,NULL);
  4922.     haslock = 1;
  4923.     }
  4924.     return(x);
  4925. #endif /* USE_UU_LOCK */
  4926. #else  /* Systems that don't have ttylock()... */
  4927.  
  4928. #ifndef HPUX
  4929.  
  4930.     int lockfd;                /* File descriptor for lock file. */
  4931.     PID_T pid;                /* Process id of this process. */
  4932.     int tries;                /* How many times we've tried... */
  4933.     struct stat devbuf;            /* For device numbers (SVR4). */
  4934.  
  4935. #ifdef PIDSTRING
  4936.     char pid_str[32];            /* My pid in string format. */
  4937. #endif /* PIDSTRING */
  4938.  
  4939.     char *device, *devname;
  4940.  
  4941. #define LFNAML 256            /* Max length for lock file name. */
  4942.     char lockfil[LFNAML];        /* Lock file name */
  4943. #ifdef RTAIX
  4944.     char lklockf[LFNAML];        /* Name for link to lock file  */
  4945. #endif /* RTAIX */
  4946. #ifdef CKSYMLINK
  4947.     char symlock[LFNAML];        /* Name for symlink lockfile name */
  4948. #endif /* CKSYMLINK */
  4949.     char tmpnam[LFNAML+30];        /* Temporary lockfile name. */
  4950.     char *lockdir = LOCK_DIR;        /* Defined near top of this file, */
  4951.                     /* or on cc command line. */
  4952.     haslock = 0;                        /* Not locked yet. */
  4953.     *flfnam = '\0';            /* Lockfile name is empty. */
  4954.     lock2[0] = '\0';            /* Clear secondary lockfile name. */
  4955.     pid = getpid();            /* Get id of this process. */
  4956.  
  4957. /*  Construct name of lockfile and temporary file */
  4958.  
  4959. /*  device  = name of tty device without the path, e.g. "ttyh8" */
  4960. /*  lockfil = name of lock file, without path, e.g. "LCK..ttyh8" */
  4961.  
  4962.     device = ((devname = xxlast(ttdev,'/')) != NULL ? devname+1 : ttdev);
  4963.  
  4964.     if (stat(ttdev,&devbuf) < 0)
  4965.       return(-1);
  4966.  
  4967. #ifdef CKSYMLINK
  4968.     islink = 1;                /* Assume it's a symlink */
  4969.     linkto[0] = '\0';            /* But we don't know to what */
  4970. #ifdef COMMENT
  4971. /*
  4972.   This is undependable.  If it worked it would save the readlink call if
  4973.   we knew the device name was not a link.
  4974. */
  4975. #ifdef S_ISLNK
  4976.     islink = S_ISLNK(devbuf.st_mode);
  4977.     debug(F101,"ttlock stat S_ISLNK","",islink);
  4978. #endif /* S_ISLNK */
  4979. #endif /* COMMENT */
  4980.     if (islink) {
  4981.     n = readlink(ttdev,linkto,DEVNAMLEN); /* See if it's a link */
  4982.     debug(F111,"ttlock readlink",ttdev,n);
  4983.     if (n > -1)            /* It is */
  4984.       linkto[n] = '\0';
  4985.     else                /* It's not */
  4986.       islink = 0;
  4987.     debug(F111,"ttlock link",linkto,islink);
  4988.     }
  4989.     if (islink) {
  4990.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  4991.     debug(F110,"ttlock linkdev",linkdev,0);
  4992.     }
  4993. #endif /* CKSYMLINK */
  4994.  
  4995. /*
  4996.   On SCO platforms, if we don't have a symlink, then let's pretend the
  4997.   name given for the device is a symlink, because later we will change
  4998.   the name if it contains any uppercase characters.
  4999. */
  5000. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  5001.     if (!islink) {
  5002.     islink = 1;
  5003.     ckstrncpy(linkto,ttdev,DEVNAMLEN);
  5004.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  5005.     debug(F110,"ttlock linkdev",linkdev,0);
  5006.     }
  5007. #else
  5008. #ifdef M_XENIX                /* SCO Xenix or UNIX */
  5009.     if (!islink) {
  5010.     islink = 1;
  5011.     ckstrncpy(linkto,ttdev,DEVNAMLEN);
  5012.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  5013.     debug(F110,"ttlock linkdev",linkdev,0);
  5014.     }
  5015. #endif /* M_XENIX */
  5016. #endif /* CK_SCOV5 */
  5017.  
  5018. #ifdef ISIII                /* Interactive System III, PC/IX */
  5019.     ckstrncpy(lockfil, device, DEVNAMLEN);
  5020. #else  /* not ISIII */
  5021. #ifdef LFDEVNO                /* Lockfilename has device numbers. */
  5022. #ifdef COHERENT
  5023.     sprintf(lockfil,"LCK..%d.%d",    /* SAFE */
  5024.         major(devbuf.st_rdev),       /* major device number */
  5025.         0x1f & minor(devbuf.st_rdev)); /* minor device number */
  5026. #else
  5027.     /* Note: %d changed to %u in 8.0 -- %u is part of SVID for SVR4 */
  5028.     /* Lockfile name format verified to agree with Solaris cu, Dec 2001 */
  5029.     sprintf(lockfil,"LK.%03u.%03u.%03u", /* SAFE */
  5030.         major(devbuf.st_dev),    /* device */
  5031.         major(devbuf.st_rdev),    /* major device number */
  5032.         minor(devbuf.st_rdev));    /* minor device number */
  5033. #endif /* COHERENT */
  5034. #else  /* Not LFDEVNO */
  5035. #ifdef PTX                /* Dynix PTX */
  5036.     if ((device != &ttdev[5]) && (strncmp(ttdev,"/dev/",5) == 0)) {
  5037.     if ((int)strlen(device) + 8 < LFNAML)
  5038.       sprintf(lockfil,"LCK..%.3s%s", &ttdev[5], device);
  5039.     else
  5040.       ckstrncpy(lockfil,"LOCKFILE_NAME_TOO_LONG",LFNAML);
  5041.     } else
  5042. #endif /* PTX */
  5043.       if ((int)strlen(device) + 5 < LFNAML)
  5044.     sprintf(lockfil,"LCK..%s", device);
  5045.       else
  5046.     ckstrncpy(lockfil,"LOCKFILE_NAME_TOO_LONG",LFNAML);
  5047. #ifdef RTAIX
  5048.     ckstrncpy(lklockf,device,DEVNAMLEN);
  5049. #endif /* RTAIX */
  5050. #ifdef CKSYMLINK
  5051.     symlock[0] = '\0';
  5052.     if (islink)
  5053.       ckmakmsg(symlock,LFNAML, "LCK..", linkdev, NULL, NULL);
  5054. #endif /* CKSYMLINK */
  5055. #endif /* LFDEVNO */
  5056. #endif /* ISIII */
  5057.  
  5058. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  5059.     {
  5060.     /* Lowercase the entire filename. */
  5061.         /* SCO says we must do this in V5.0 and later. */
  5062.     /* BUT... watch out for devices -- like Digiboard Portserver */
  5063.     /* That can have hundreds of ports... */
  5064.     char *p = (char *)(lockfil + 5);
  5065.     while (*p) { if (isupper(*p)) *p = (char) tolower(*p); p++; }
  5066.     }
  5067. #ifdef CKSYMLINK
  5068.     if (islink) {            /* If no change */
  5069.     if (!strcmp(lockfil,symlock)) {    /* then no second lockfile needed */
  5070.         islink = 0;
  5071.         symlock[0] = '\0';
  5072.     }
  5073.     }
  5074. #endif /* CKSYMLINK */
  5075. #else
  5076. #ifdef M_XENIX                /* SCO Xenix or UNIX */
  5077.     {
  5078.     int x; char c;
  5079.     x = (int)strlen(lockfil) - 1;    /* Get last letter of device name. */
  5080.     if (x > 0) {            /* If it's uppercase, lower it. */
  5081.         c = lockfil[x];
  5082.         if (c >= 'A' && c <= 'Z') lockfil[x] += ('a' - 'A');
  5083.     }
  5084.     }
  5085. #ifdef CKSYMLINK
  5086.     if (islink) {
  5087.     if (!strcmp(lockfil,symlock)) {    /* No change */
  5088.         islink = 0;            /* so no second lockfile */
  5089.         symlock[0] = '\0';
  5090.     }
  5091.     }
  5092. #endif /* CKSYMLINK */
  5093. #endif /* M_XENIX */
  5094. #endif /* CK_SCOV5 */
  5095.  
  5096. /*  flfnam = full lockfile pathname, e.g. "/usr/spool/uucp/LCK..ttyh8" */
  5097. /*  tmpnam = temporary unique, e.g. "/usr/spool/uucp/LTMP..pid" */
  5098.  
  5099.     ckmakmsg(flfnam,LFNAML,lockdir,"/",lockfil,NULL);
  5100.  
  5101. #ifdef RTAIX
  5102.     ckmakmsg(lkflfn,FLFNAML,lockdir,"/",lklockf,NULL);
  5103. #endif /* RTAIX */
  5104.  
  5105. #ifndef LFDEVNO
  5106. #ifdef CKSYMLINK
  5107.     /* If it's a link then also make a lockfile for the real name */
  5108.     debug(F111,"ttlock link symlock",symlock,islink);
  5109.     if (islink && symlock[0]) {
  5110.     /* But only if the lockfile names would be different. */
  5111.     /* WARNING: They won't be, e.g. for /dev/ttyd2 => /hw/ttys/ttyd2 */
  5112.     ckmakmsg(lock2,FLFNAML,lockdir,"/",symlock,NULL);
  5113.     debug(F110,"ttlock lock2",lock2,0);
  5114.     if (!strcmp(lock2,flfnam)) {    /* Are lockfile names the same? */
  5115.         debug(F100,"ttlock lock2 cleared","",0);
  5116.         lock2[0] = '\0';        /* Clear secondary lockfile name. */
  5117.     }
  5118.     }
  5119. #endif /* CKSYMLINK */
  5120. #endif /* LFDEVNO */
  5121.  
  5122.     sprintf(tmpnam,"%s/LTMP.%05d",lockdir,(int) pid); /* safe */
  5123.     debug(F110,"ttlock flfnam",flfnam,0);
  5124.     debug(F110,"ttlock tmpnam",tmpnam,0);
  5125.  
  5126.     priv_on();                /* Turn on privileges if possible. */
  5127.     lockfd = creat(tmpnam, 0444);    /* Try to create temp lock file. */
  5128.     if (lockfd < 0) {            /* Create failed. */
  5129.     debug(F111,"ttlock creat failed",tmpnam,errno);
  5130.     if (errno == ENOENT) {
  5131.         perror(lockdir);
  5132.         printf("UUCP not installed or Kermit misconfigured\n");
  5133.     } else {
  5134.         if (!quiet)
  5135.           perror(lockdir);
  5136.         unlink(tmpnam);        /* Get rid of the temporary file. */
  5137.     }
  5138.     priv_off();            /* Turn off privileges!!! */
  5139.     return(-1);            /* Return failure code. */
  5140.     }
  5141. /* Now write the pid into the temp lockfile in the appropriate format */
  5142.  
  5143. #ifdef PIDSTRING            /* For Honey DanBer UUCP, */
  5144.     sprintf(                /* write PID as decimal string */
  5145.         pid_str,
  5146. #ifdef LINUXFSSTND            /* The "Linux File System Standard" */
  5147. #ifdef FSSTND10                /* Version 1.0 calls for */
  5148.         "%010d\n",            /* leading zeros */
  5149. #else                    /* while version 1.2 calls for */
  5150.         "%10d\n",            /* leading spaces */
  5151. #endif /* FSSTND10 */
  5152. #else
  5153. #ifdef COHERENT
  5154.         "%d\n",            /* with leading nothing */
  5155. #else
  5156.         "%10d\n",            /* with leading blanks */
  5157. #endif /* COHERENT */
  5158. #endif /* LINUXFSSTND */
  5159.         (int) pid
  5160.         );                /* safe */
  5161.     write(lockfd, pid_str, 11);
  5162.     debug(F111,"ttlock hdb pid string",pid_str,(int) pid);
  5163.  
  5164. #else /* Not PIDSTRING, use integer PID */
  5165.  
  5166.     write(lockfd, (char *)&pid, sizeof(pid) );
  5167.     debug(F101,"ttlock pid","",(int) pid);
  5168.  
  5169. #endif /* PIDSTRING */
  5170.  
  5171. /* Now try to rename the temp file to the real lock file name. */
  5172. /* This will fail if a lock file of that name already exists.  */
  5173.  
  5174.     close(lockfd);            /* Close the temp lockfile. */
  5175.     chmod(tmpnam,0444);            /* Permission for a valid lock. */
  5176.     tries = 0;
  5177.     while (!haslock && tries++ < 2) {
  5178.     haslock = (link(tmpnam,flfnam) == 0); /* Create a link to it. */
  5179.     if (haslock) {                  /* If we got the lockfile */
  5180. #ifdef RTAIX
  5181.         link(flfnam,lkflfn);
  5182. #endif /* RTAIX */
  5183. #ifdef CKSYMLINK
  5184. #ifndef LFDEVNO
  5185.         if (islink && lock2[0])
  5186.           link(flfnam,lock2);
  5187. #endif /* LFDEVNO */
  5188. #endif /* CKSYMLINK */
  5189.  
  5190. #ifdef COMMENT
  5191. /* Can't do this any more because device is not open yet so no ttyfd. */
  5192. #ifdef LOCKF
  5193. /*
  5194.   Advisory file locking works on SVR4, so we use it.  In fact, it is
  5195.   necessary in some cases, e.g. when SLIP is involved.  But it still doesn't
  5196.   seem to prevent multiple users accessing the same device by different names.
  5197. */
  5198.             while (lockf(ttyfd, F_TLOCK, 0L) != 0) {
  5199.                 debug(F111, "ttlock lockf returns errno", "", errno);
  5200.                 if ((++tries >= 3) || (errno != EAGAIN)) {
  5201.                     x = unlink(flfnam); /* remove the lockfile */
  5202. #ifdef RTAIX
  5203.             unlink(lkflfn);    /* And any links to it... */
  5204. #endif /* RTAIX */
  5205. #ifdef CKSYMLINK
  5206. #ifndef LFDEVNO
  5207.             if (islink && lock2[0])
  5208.               unlink(lock2);    /* ditto... */
  5209. #endif /* LFDEVNO */
  5210. #endif /* CKSYMLINK */
  5211.                     debug(F111,"ttlock unlink",flfnam,x);
  5212.                     haslock = 0;
  5213.             break;
  5214.         }
  5215.                 sleep(2);
  5216.         }
  5217.         if (haslock)        /* If we got an advisory lock */
  5218. #endif /* LOCKF */
  5219. #endif /* COMMENT */
  5220.           break;            /* We're done. */
  5221.  
  5222.     } else {            /* We didn't create a new lockfile. */
  5223.         priv_off();
  5224.         if (ttchkpid(flfnam)) {    /* Check existing lockfile */
  5225.         priv_on();        /* cause ttchkpid turns priv_off... */
  5226.         unlink(tmpnam);        /* Delete the tempfile */
  5227.         debug(F100,"ttlock found tty locked","",0);
  5228.         priv_off();        /* Turn off privs */
  5229.         return(-2);        /* Code for device is in use. */
  5230.         }
  5231.         priv_on();
  5232.     }
  5233.     }
  5234.     unlink(tmpnam);            /* Unlink (remove) the temp file. */
  5235.     priv_off();                /* Turn off privs */
  5236.     return(haslock ? 0 : -1);        /* Return link's return code. */
  5237.  
  5238. #else /* HPUX */
  5239.  
  5240. /*
  5241.   HP-UX gets its own copy of this routine, modeled after the observed behavior
  5242.   of the HP-UX 'cu' program.  HP-UX serial device names consist of a base name
  5243.   such as "tty", "ttyd", "cua", "cul", "cuad", or "culd", followed by a unit
  5244.   designator which is a string of digits, possibly containing an imbedded
  5245.   letter "p".  Examples (for base name "tty"):
  5246.  
  5247.      /dev/tty0, /dev/tty00, dev/ttyd00, /dev/tty0p0
  5248.  
  5249.   According to the HP-UX UUCP manual of 1988, the "0p0" notation has been
  5250.   used on Series 800 since HP-UX 2.00, and the "non-p" notation was used
  5251.   on other models.  In HP-UX 10.00, "0p0" notation was adopted for all models.
  5252.   However, we make and enforce no such distinctions; either notation is
  5253.   accepted on any model or HP-UX version as a valid unit designator.
  5254.  
  5255.   If a valid unit is specified (as opposed to a designer name or symlink), we
  5256.   check for all aliases of the given unit according to the devprefix[] array.
  5257.   If no lockfiles are found for the given unit, we can have the device; we
  5258.   create a lockfile LCK..name in the lockfile directory appropriate for the
  5259.   HP-UX version (/var/spool/locks for 10.00 and later, /usr/spool/uucp for
  5260.   9.xx and earlier).  If it is a "cua" or "cul" device, a second lockfile is
  5261.   created with the "ttyd" prefix.  This is exactly what cu does.
  5262.  
  5263.   If the "set line" device does not have a valid unit designator, then it is
  5264.   used literally and no synomyms are searched for and only one lockfile is
  5265.   created.
  5266.  
  5267.   -fdc, March 1998.
  5268. */
  5269. #define LFNAML 80            /* Max length for lock file name. */
  5270.  
  5271.     int lockfd;                /* File descriptor for lock file. */
  5272.     PID_T pid;                /* Process ID of this process. */
  5273.     int fpid;                /* pid found in existing lockfile. */
  5274.     int tries;                /* How many times we've tried... */
  5275.     int i, k;                /* Workers */
  5276.  
  5277.     char *device, *devname;        /* "/dev/xxx", "xxx" */
  5278.     char *unit, *p;            /* <instance>p<port> part of xxx */
  5279.  
  5280.     char lockfil[LFNAML];        /* Lockfile name (no path) */
  5281.     char tmpnam[LFNAML];        /* Temporary lockfile name. */
  5282.  
  5283. #ifdef HPUX10                /* Lockfile directory */
  5284.     char *lockdir = "/var/spool/locks";    /* Always this for 10.00 and higher */
  5285. #else  /* HP-UX 9.xx and below */
  5286. #ifdef LOCK_DIR
  5287.     char *lockdir = LOCK_DIR;        /* Defined near top of this file */
  5288. #else
  5289.     char *lockdir = "/usr/spool/uucp";    /* or not... */
  5290. #endif /* LOCK_DIR */
  5291. #endif /* HPUX10 */
  5292.  
  5293.     haslock = 0;                        /* Not locked yet. */
  5294.     *flfnam = '\0';            /* Lockfile name is empty. */
  5295.     lock2[0] = '\0';            /* Second one too. */
  5296.     pid = getpid();            /* Get my process ID */
  5297. /*
  5298.   Construct name of lockfile and temporary file...
  5299.   device  = name of tty device without the path, e.g. "tty0p0"
  5300.   lockfil = name of lock file, without path, e.g. "LCK..tty0p0"
  5301. */
  5302.     device = ((devname = xxlast(ttdev,'/')) != NULL ? devname+1 : ttdev);
  5303.     debug(F110,"TTLOCK device",device,0);
  5304.     ckmakmsg(lockfil,LFNAML,"LCK..",device,NULL,NULL);
  5305.  
  5306.     k = 0;                /* Assume device is not locked */
  5307.     n = 0;                /* Digit counter */
  5308.     unit = device;            /* Unit = <instance>p<port> */
  5309.     while (*unit && !isdigit(*unit))    /* Search for digit... */
  5310.       unit++;
  5311.     p = unit;                /* Verify <num>p<num> format... */
  5312.     debug(F110,"TTLOCK unit 1",unit,0);
  5313. /*
  5314.   The unit number is recognized as:
  5315.   (a) any sequence of digits that runs to the end of the string.
  5316.   (b) any (a) that includes one and only one letter "p", with at least
  5317.       one digit before and after it.
  5318. */
  5319.     while (isdigit(*p)) p++, n++;    /* Get a run of digits */
  5320.     if (*p && n > 0) {            /* Have a "p"? */
  5321.     if (*p == 'p' && isdigit(*(p+1))) {
  5322.         p++;
  5323.         n = 0;
  5324.         while (isdigit(*p)) p++, n++;
  5325.     }
  5326.     }
  5327.     if (n == 0 || *p) unit = "";
  5328.     debug(F110,"TTLOCK unit 2",unit,0);
  5329.  
  5330.     if (*unit) {            /* Device name has unit number. */
  5331.     /* The following loop not only searches for the various lockfile    */
  5332.     /* synonyms, but also removes all -- not just one -- stale lockfile */
  5333.     /* for the device, should there be more than one.  See ttchkpid().  */
  5334.     ttydexists = 0;
  5335.     for (i = 0; *devprefix[i]; i++) { /* For each driver... */
  5336.         /* Make device name */
  5337.         ckmakmsg(lock2,FLFNAML,"/dev/",devprefix[i],unit,NULL);
  5338.         priv_on();            /* Privs on */
  5339.         k = zchki(lock2) != -1;    /* See if device exists */
  5340.         priv_off();            /* Privs off */
  5341.         debug(F111,"TTLOCK exist",lock2,k);
  5342.             if (k) {
  5343.         if (!strcmp(devprefix[i],"ttyd")) /* ttyd device exists */
  5344.           ttydexists = 1;
  5345.         /* Make lockfile name */
  5346.         ckmakmsg(lock2,FLFNAML,lockdir,"/LCK..",devprefix[i],unit);
  5347.         debug(F110,"TTLOCK checking",lock2,0);
  5348.         priv_on();        /* Privs on */
  5349.         k = zchki(lock2) != -1;    /* See if lockfile exists */
  5350.         priv_off();        /* Privs off */
  5351.         debug(F111,"TTLOCK check for lock A",lock2,k);
  5352.         if (k) if (ttchkpid(lock2)) { /* If pid still active, fail. */
  5353.             ckstrncpy(flfnam,lock2,FLFNAML);
  5354.             return(-2);
  5355.         }
  5356.         }
  5357.     }
  5358.     } else {                /* Some other device-name format */
  5359.     /* This takes care of symbolic links, etc... */
  5360.     /* But does not chase them down! */
  5361.     ckmakmsg(lock2,FLFNAML,lockdir,"/LCK..",device,NULL);
  5362.     priv_on();
  5363.     k = zchki(lock2) != -1;        /* Check for existing lockfile */
  5364.     priv_off();
  5365.     debug(F111,"TTLOCK check for lock B",lock2,k);
  5366.     if (k) if (ttchkpid(lock2)) {    /* Check pid from lockfile */
  5367.         ckstrncpy(flfnam,lock2,FLFNAML);
  5368.         debug(F110,"TTLOCK in use",device,0);
  5369.         debug(F101,"TTLOCK returns","",-2);
  5370.         return(-2);
  5371.     }
  5372.     }
  5373. /*
  5374.   Get here only if there is no (more) lockfile, so now we make one (or two)...
  5375.   flfnam = full lockfile pathname, e.g. "/usr/spool/uucp/LCK..cul0p0".
  5376.   tmpnam = unique temporary filname, e.g. "/usr/spool/uucp/LTMP..pid".
  5377. */
  5378.     ckmakmsg(flfnam,FLFNAML,lockdir,"/",lockfil,NULL); /* SET LINE device */
  5379.  
  5380.     /* If dialout device, also make one for corresponding dialin device */
  5381.     lock2[0] = '\0';
  5382.     if (!strncmp(device,"cu",2) && *unit && ttydexists)
  5383.       ckmakmsg(lock2,FLFNAML,lockdir,"/LCK..ttyd",unit,NULL);
  5384.  
  5385.     if ((int)strlen(lockdir)+12 < LFNAML)
  5386.       sprintf(tmpnam,"%s/LTMP.%05d",lockdir,(int) pid); /* Make temp name */
  5387. #ifdef DEBUG
  5388.     if (deblog) {
  5389.     debug(F110,"TTLOCK flfnam",flfnam,0);
  5390.     debug(F110,"TTLOCK lock2",lock2,0);
  5391.     debug(F110,"TTLOCK tmpnam",tmpnam,0);
  5392.     }
  5393. #endif /* DEBUG */
  5394. /*
  5395.    Lockfile permissions...
  5396.    444 is standard, HP-UX 10.00 uses 664.  It doesn't matter.
  5397.    Kermit uses 444; the difference lets us tell whether Kermit created
  5398.    the lock file.
  5399. */
  5400.     priv_on();                /* Turn on privileges. */
  5401.     lockfd = creat(tmpnam, 0444);    /* Try to create temporary file. */
  5402.     if (lockfd < 0) {            /* Create failed. */
  5403.     debug(F111,"TTLOCK creat failed",tmpnam,errno);
  5404.     if (errno == ENOENT) {
  5405.         perror(lockdir);
  5406.         printf("UUCP not installed or Kermit misconfigured\n");
  5407.     } else {
  5408.         if (!quiet)
  5409.           perror(lockdir);
  5410.         unlink(tmpnam);        /* Get rid of the temporary file. */
  5411.     }
  5412.     priv_off();            /* Turn off privileges!!! */
  5413.     debug(F101,"TTLOCK returns","",-1);
  5414.     return(-1);            /* Return failure code. */
  5415.     }
  5416.     debug(F110,"TTLOCK temp ok",tmpnam,0);
  5417.  
  5418. /* Now write our pid into the temp lockfile in integer format. */
  5419.  
  5420.     i = write(lockfd, (char *)&pid, sizeof(pid));
  5421.  
  5422. #ifdef DEBUG
  5423.     if (deblog) {
  5424.     debug(F101,"TTLOCK pid","",pid);
  5425.     debug(F101,"TTLOCK sizeof pid","",sizeof(pid));
  5426.     debug(F101,"TTLOCK write pid returns","",i);
  5427.     }
  5428. #endif /* DEBUG */
  5429.  
  5430. /*
  5431.   Now try to rename the temporary file to the real lockfile name.
  5432.   This will fail if a lock file of that name already exists, which
  5433.   will catch race conditions with other users.
  5434. */
  5435.     close(lockfd);            /* Close the temp lockfile. */
  5436.     chmod(tmpnam,0444);
  5437.  
  5438.     tries = 0;
  5439.     while (!haslock && tries++ < 2) {
  5440.     haslock = (link(tmpnam,flfnam) == 0); /* Create a link to it. */
  5441.     debug(F101,"TTLOCK link","",haslock);
  5442.     if (haslock) {            /* If we made the lockfile... */
  5443.  
  5444. #ifdef COMMENT
  5445. /* We can't do this any more because we don't have a file descriptor yet. */
  5446. #ifdef LOCKF                /* Can be canceled with -DNOLOCKF */
  5447. /*
  5448.   Create an advisory lock on the device through its file descriptor.
  5449.   This code actually seems to work.  If it is executed, and then another
  5450.   process tries to open the same device under a different name to circumvent
  5451.   the lockfile, they get a "device busy" error.
  5452. */
  5453.         debug(F100,"TTLOCK LOCKF code...","",0);
  5454.             while ( lockf(ttyfd, F_TLOCK, 0L) != 0 ) {
  5455.                 debug(F111, "TTLOCK lockf error", "", errno);
  5456.                 if ((++tries >= 3) || (errno != EAGAIN)) {
  5457.                     x = unlink(flfnam); /* Remove the lockfile */
  5458.             if (errno == EACCES && !quiet)
  5459.               printf("Device already locked by another process\n");
  5460.                     haslock = 0;
  5461.             break;
  5462.         }
  5463.                 sleep(2);
  5464.         }
  5465. #endif /* LOCKF */
  5466. #endif /* COMMENT */
  5467.  
  5468.         if (haslock) {        /* If we made the lockfile ... */
  5469.         if (lock2[0]) {        /* if there is to be a 2nd lockfile */
  5470.             lockfd = creat(lock2, 0444); /* Create it */
  5471.             debug(F111,"TTLOCK lock2 creat", lock2, lockfd);
  5472.             if (lockfd > -1) {    /* Created OK, write pid. */
  5473.             write(lockfd, (char *)&pid, sizeof(pid) );
  5474.             close(lockfd);    /* Close and */
  5475.             chmod(lock2, 0444); /* set permissions. */
  5476.             } else {         /* Not OK, but don't fail. */
  5477.             lock2[0] = '\0'; /* Just remember it's not there. */
  5478.             }
  5479.         }
  5480.         break;            /* and we're done. */
  5481.         }
  5482.     }
  5483.     }
  5484.     unlink(tmpnam);            /* Unlink (remove) the temp file. */
  5485.     priv_off();                /* Turn off privs */
  5486.     i = haslock ? 0 : -1;        /* Our return value */
  5487.     debug(F101,"TTLOCK returns","",i);
  5488.     return(i);
  5489. #endif /* HPUX */
  5490. #endif /* USETTYLOCK */
  5491. #endif /* !NOUUCP */
  5492. }
  5493.  
  5494. /*  T T U N L O C K  */
  5495.  
  5496. static int
  5497. ttunlck() {                             /* Remove UUCP lockfile(s). */
  5498. #ifndef NOUUCP
  5499.     int x;
  5500.  
  5501.     debug(F111,"ttunlck",flfnam,haslock);
  5502.  
  5503. #ifdef USETTYLOCK
  5504.  
  5505.     if (haslock && *flfnam) {
  5506.     int x;
  5507.     priv_on();            /* Turn on privs */
  5508. #ifdef USE_UU_LOCK
  5509.     x = uu_unlock(lockname);
  5510. #else  /* USE_UU_LOCK */
  5511.     x = ttyunlock(lockname);    /* Try to unlock */
  5512. #endif /* USE_UU_LOCK */
  5513.     priv_off();            /* Turn off privs */
  5514.     if (x < 0 && !quiet)
  5515.       printf("Warning - Can't remove lockfile: %s\n", flfnam);
  5516.  
  5517.     *flfnam = '\0';            /* Erase the name. */
  5518.     haslock = 0;
  5519.     return(0);
  5520.     }
  5521.  
  5522. #else  /* No ttylock()... */
  5523.  
  5524.     if (haslock && *flfnam) {
  5525.     /* Don't remove lockfile if we didn't make it ourselves */
  5526.     if ((x = ttrpid(flfnam)) != (int)getpid()) {
  5527.         debug(F111,"ttunlck lockfile seized",flfnam,x);
  5528.         printf("Warning - Lockfile %s seized by pid %d\n",
  5529.            flfnam,
  5530.            x
  5531.            );
  5532.         return(0);
  5533.     }
  5534.     priv_on();            /* Turn privileges on.  */
  5535.     errno = 0;
  5536.     x = unlink(flfnam);        /* Remove the lockfile. */
  5537.     debug(F111,"ttunlck unlink",flfnam,x);
  5538.     if (x < 0) {
  5539.         if (errno && !quiet)
  5540.           perror(ttnmsv);
  5541.         printf("Warning - Can't remove lockfile: %s\n", flfnam);
  5542.     }
  5543.     haslock = 0;
  5544.     *flfnam = '\0';            /* Erase the name. */
  5545.  
  5546. #ifdef RTAIX
  5547.     errno = 0;
  5548.     x = unlink(lkflfn);        /* Remove link to lockfile */
  5549.     debug(F111,"ttunlck AIX link unlink",lkflfn,x);
  5550.     if (x < 0) {
  5551.         if (errno && !quiet)
  5552.           perror(ttnmsv);
  5553.         printf("Warning - Can't remove link to lockfile: %s\n", lkflfn);
  5554.     }
  5555.     *lkflfn = '\0';
  5556. #else
  5557.     if (lock2[0]) {            /* If there is a second lockfile, */
  5558.         errno = 0;
  5559.         x = unlink(lock2);        /*  remove it too. */
  5560.         debug(F111,"ttunlck lock2 unlink",lock2,x);
  5561.         if (x < 0) {
  5562.         if (errno && !quiet)
  5563.           perror(ttnmsv);
  5564.         printf("Warning - Can't remove secondary lockfile: %s\n",
  5565.                lock2
  5566.                );
  5567.         }
  5568.         lock2[0] = '\0';        /* Forget its name. */
  5569.     }
  5570. #endif /* RTAIX */
  5571.  
  5572. #ifdef COMMENT
  5573. #ifdef LOCKF
  5574.         (VOID) lockf(ttyfd, F_ULOCK, 0L); /* Remove advisory lock */
  5575. #endif /* LOCKF */
  5576. #endif /* COMMENT */
  5577.  
  5578.     priv_off();            /* Turn privileges off. */
  5579.     }
  5580. #endif /* USETTYLOCK */
  5581. #endif /* !NOUUCP */
  5582.     return(0);
  5583. }
  5584.  
  5585. /*
  5586.   4.3BSD-style UUCP line direction control.
  5587.   (Stan Barber, Rice U, 1980-something...)
  5588. */
  5589. #ifndef NOUUCP
  5590. #ifdef ACUCNTRL
  5591. VOID
  5592. acucntrl(flag,ttname) char *flag, *ttname; {
  5593.     char x[DEVNAMLEN+32], *device, *devname;
  5594.  
  5595.     if (strcmp(ttname,CTTNAM) == 0 || xlocal == 0) /* If not local, */
  5596.       return;                /* just return. */
  5597.     device = ((devname = xxlast(ttname,'/')) != NULL ? devname+1 : ttname);
  5598.     if (strncmp(device,"LCK..",4) == 0) device += 5;
  5599.     ckmakmsg(x,DEVNAMLEN+32,"/usr/lib/uucp/acucntrl ",flag," ",device);
  5600.     debug(F110,"called ",x,0);
  5601.     zsyscmd(x);
  5602. }
  5603. #endif /* ACUCNTRL */
  5604. #endif /* NOUUCP */
  5605.  
  5606. /*
  5607.   T T H F L O W  --  Set or Reset hardware flow control.
  5608.  
  5609.   This is an attempt to collect all hardware-flow-control related code
  5610.   into a single module.  Thanks to Rick Sladkey and John Kohl for lots of
  5611.   help here.  Overview:
  5612.  
  5613.   Hardware flow control is not supported in many UNIX implementions.  Even
  5614.   when it is supported, there is no (ha ha) "standard" for the programming
  5615.   interface.  In general, 4.3BSD and earlier (sometimes), 4.4BSD, System V,
  5616.   SunOS, AIX, etc, have totally different methods.  (And, not strictly
  5617.   relevant here, the programming interface often brings one only to a no-op
  5618.   in the device driver!)
  5619.  
  5620.   Among all these, we have two major types of APIs: those in which hardware
  5621.   flow control is determined by bits in the same termio/termios/sgtty mode
  5622.   word(s) that are used for controlling such items as CBREAK vs RAW mode, and
  5623.   which are also used by the ttvt(), ttpkt(), conbin(), and concb() routines
  5624.   for changing terminal modes.  And those that use entirely different
  5625.   mechanisms.
  5626.  
  5627.   In the first category, it is important that any change in the mode bits be
  5628.   reflected in the relevant termio(s)/sgtty structure, so that subsequent
  5629.   changes to that structure do not wipe out the effects of this routine.  That
  5630.   is why a pointer, attrs, to the appropriate structure is passed as a
  5631.   parameter to this routine.
  5632.  
  5633.   The second category should give us no worries, since any changes to hardware
  5634.   flow control accomplished by this routine should not affect the termio(s)/
  5635.   sgtty structures, and therefore will not be undone by later changes to them.
  5636.  
  5637.   The second argument, status, means to turn on hardware flow control if
  5638.   nonzero, and to turn it off if zero.
  5639.  
  5640.   Returns: 0 on apparent success, -1 on probable failure.
  5641. */
  5642.  
  5643. /*
  5644.   The following business is for BSDI, where it was discovered that two
  5645.   separate bits, CCTS_OFLOW and CRTS_IFLOW, are used in hardware flow control,
  5646.   but CTRSCTS is defined (in <termios.h>) to be just CCTS_OFLOW rather both
  5647.   bits, so hwfc only works in one direction if you use CRTSCTS to control it.
  5648.   Other 4.4BSD-based Unixes such as FreeBSD 4.1, which use these two bits,
  5649.   define CRTSCTS correctly.
  5650. */
  5651. #ifdef FIXCRTSCTS
  5652. #ifdef CRTSCTS
  5653. #ifdef CCTS_OFLOW
  5654. #ifdef CRTS_IFLOW
  5655. #undef CRTSCTS
  5656. #define CRTSCTS (CRTS_IFLOW|CCTS_OFLOW)
  5657. #endif /* CRTS_IFLOW */
  5658. #endif /* CCTS_OFLOW */
  5659. #endif /* CRTSCTS */
  5660. #endif /* FIXCRTSCTS */
  5661.  
  5662. static int
  5663. tthflow(flow, status, attrs)
  5664.     int flow,                /* Type of flow control (ckcdeb.h) */
  5665.     status;                /* Nonzero = turn it on */
  5666.                     /* Zero = turn it off */
  5667. #ifdef BSD44ORPOSIX            /* POSIX or BSD44 */
  5668.     struct termios *attrs;
  5669. #else                    /* System V */
  5670. #ifdef ATTSV
  5671. #ifdef ATT7300
  5672. #ifdef UNIX351M
  5673. /* AT&T UNIX 3.51m can set but not test for hardware flow control */
  5674. #define RTSFLOW CTSCD
  5675. #define CTSFLOW CTSCD
  5676. #endif /* ATT7300 */
  5677. #endif /* UNIX351M */
  5678.     struct termio *attrs;
  5679. #else                    /* BSD, V7, etc */
  5680.     struct sgttyb *attrs;        /* sgtty info... */
  5681. #endif /* ATTSV */
  5682. #endif /* BSD44ORPOSIX */
  5683. /* tthflow */ {
  5684.  
  5685.     int x = 0;                /* tthflow() return code */
  5686.  
  5687. #ifdef Plan9
  5688.     return p9tthflow(flow, status);
  5689. #else
  5690.  
  5691. #ifndef OXOS                /* NOT Olivetti X/OS... */
  5692. /*
  5693.   For SunOS 4.0 and later in the BSD environment ...
  5694.  
  5695.   The declarations are copied and interpreted from the System V header files,
  5696.   so we don't actually have to pull in all the System V junk when building
  5697.   C-Kermit for SunOS in the BSD environment, which would be dangerous because
  5698.   having those symbols defined would cause us to take the wrong paths through
  5699.   the code.  The code in this section is used in both the BSD and Sys V SunOS
  5700.   versions.
  5701. */
  5702. #ifdef SUNOS41
  5703. /*
  5704.   In SunOS 4.1 and later, we use the POSIX calls rather than ioctl calls
  5705.   because GNU CC uses different formats for the _IOxxx macros than regular CC;
  5706.   the POSIX forms work for both.  But the POSIX calls are not available in
  5707.   SunOS 4.0.
  5708. */
  5709. #define CRTSCTS 0x80000000        /* RTS/CTS flow control */
  5710. #define TCSANOW 0            /* Do it now */
  5711.  
  5712.     struct termios {
  5713.     unsigned long c_iflag;        /* Input modes */
  5714.     unsigned long c_oflag;        /* Output modes */
  5715.     unsigned long c_cflag;        /* Control modes */
  5716.     unsigned long c_lflag;        /* Line discipline modes */
  5717.     char c_line;
  5718.     CHAR c_cc[17];
  5719.     };
  5720.     struct termios temp;
  5721.  
  5722. _PROTOTYP( int tcgetattr, (int, struct termios *) );
  5723. _PROTOTYP( int tcsetattr, (int, int, struct termios *) );
  5724. /*
  5725.   When CRTSCTS is set, SunOS won't do output unless both CTS and CD are
  5726.   asserted.  So we don't set CRTSCTS unless CD is up.  This should be OK,
  5727.   since we don't need RTS/CTS during dialing, and after dialing is complete,
  5728.   we should have CD.  If not, we still communicate, but without RTS/CTS.
  5729. */
  5730.     int mflags;                /* Modem signal flags */
  5731.  
  5732. #ifdef NETCMD
  5733.     if (ttpipe) return(0);
  5734. #endif /* NETCMD */
  5735. #ifdef NETPTY
  5736.     if (ttpty) return(0);
  5737. #endif /* NETPTY */
  5738.  
  5739.     debug(F101,"tthflow SUNOS41 entry status","",status);
  5740.     if (!status) {            /* Turn hard flow off */
  5741.     if (tcgetattr(ttyfd, &temp) > -1 && /* Get device attributes */
  5742.         (temp.c_cflag & CRTSCTS)) { /* Check for RTS/CTS */
  5743.         temp.c_cflag &= ~CRTSCTS;    /* It's there, remove it */
  5744.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5745.     }
  5746.     } else {                /* Turn hard flow on */
  5747.     if (ioctl(ttyfd,TIOCMGET,&mflags) > -1 && /* Get modem signals */
  5748.         (mflags & TIOCM_CAR)) {        /* Check for CD */
  5749.         debug(F100,"tthflow SunOS has CD","",0);
  5750.         if (tcgetattr(ttyfd, &temp) > -1 && /* Get device attributes */
  5751.         !(temp.c_cflag & CRTSCTS)) { /* Check for RTS/CTS */
  5752.         temp.c_cflag |= CRTSCTS;    /* Not there, add it */
  5753.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5754.         }
  5755.     } else {
  5756.         x = -1;
  5757.         debug(F100,"tthflow SunOS no CD","",0);
  5758.     }
  5759.     }
  5760. #else
  5761. #ifdef QNX
  5762.     struct termios temp;
  5763. #ifdef NETCMD
  5764.     if (ttpipe) return(0);
  5765. #endif /* NETCMD */
  5766. #ifdef NETPTY
  5767.     if (ttpty) return(0);
  5768. #endif /* NETPTY */
  5769.     debug(F101,"tthflow QNX entry status","",status);
  5770.     if (tcgetattr(ttyfd, &temp) > -1) {    /* Get device attributes */
  5771.     if (!status) {            /* Turn hard flow off */
  5772.         if ((temp.c_cflag & (IHFLOW|OHFLOW)) == (IHFLOW|OHFLOW)) {
  5773.         temp.c_cflag &= ~(IHFLOW|OHFLOW); /* It's there, remove it */
  5774.         attrs->c_cflag &= ~(IHFLOW|OHFLOW);
  5775.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5776.         }
  5777.     } else {            /* Turn hard flow on */
  5778.         if ((temp.c_cflag & (IHFLOW|OHFLOW)) != (IHFLOW|OHFLOW)) {
  5779.         temp.c_cflag |= (IHFLOW|OHFLOW); /* Not there, add it */
  5780.         temp.c_iflag &= ~(IXON|IXOFF);   /* Bye to IXON/IXOFF */
  5781.         ttraw.c_lflag |= IEXTEN;         /* Must be on */
  5782.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5783.         attrs->c_cflag |= (IHFLOW|OHFLOW);
  5784.         attrs->c_iflag &= ~(IXON|IXOFF);
  5785.         }
  5786.     }
  5787.     } else {
  5788.     x = -1;
  5789.     debug(F100, "tthflow QNX getattr fails", "", 0);
  5790.     }
  5791. #else
  5792. #ifdef POSIX_CRTSCTS
  5793. /*
  5794.   POSIX_CRTSCTS is defined in ckcdeb.h or on CC command line.
  5795.   Note: Do not assume CRTSCTS is a one-bit field!
  5796. */
  5797.     struct termios temp;
  5798. #ifdef NETCMD
  5799.     if (ttpipe) return(0);
  5800. #endif /* NETCMD */
  5801. #ifdef NETPTY
  5802.     if (ttpty) return(0);
  5803. #endif /* NETPTY */
  5804.     debug(F101,"tthflow POSIX_CRTSCTS entry status","",status);
  5805.     errno = 0;
  5806.     x = tcgetattr(ttyfd, &temp);
  5807.     debug(F111,"tthflow POSIX_CRTSCTS tcgetattr",ckitoa(x),errno);
  5808.     errno = 0;
  5809.     if (x < 0) {
  5810.     x = -1;
  5811.     } else {
  5812.     if (!status) {            /* Turn hard flow off */
  5813.         if (
  5814. #ifdef COMMENT
  5815.         /* This can fail because of sign extension */
  5816.         /* e.g. in Linux where it's Bit 31 */
  5817.         (temp.c_cflag & CRTSCTS) == CRTSCTS
  5818. #else
  5819.         (temp.c_cflag & CRTSCTS) != 0
  5820. #endif /* COMMENT */
  5821.         ) {
  5822.         temp.c_cflag &= ~CRTSCTS; /* It's there, remove it */
  5823.         attrs->c_cflag &= ~CRTSCTS;
  5824.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5825.         debug(F111,"tthflow POSIX_CRTSCTS OFF tcsetattr",
  5826.               ckitoa(x),errno);
  5827.         }
  5828.     } else {            /* Turn hard flow on */
  5829.         if (
  5830. #ifdef COMMENT
  5831.         /* This can fail because of sign extension */
  5832.         (temp.c_cflag & CRTSCTS) != CRTSCTS
  5833. #else
  5834.         (temp.c_cflag & CRTSCTS) == 0
  5835. #endif /* COMMENT */
  5836.         ) {
  5837.         temp.c_cflag |= CRTSCTS; /* Not there, add it */
  5838.         temp.c_iflag &= ~(IXON|IXOFF|IXANY); /* Bye to IXON/IXOFF */
  5839.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5840.         debug(F111,"tthflow POSIX_CRTSCTS ON tcsetattr",
  5841.               ckitoa(x),errno);
  5842.         attrs->c_cflag |= CRTSCTS;
  5843.         attrs->c_iflag &= ~(IXON|IXOFF|IXANY);
  5844.         }
  5845.     }
  5846.     }
  5847. #else
  5848. #ifdef SUNOS4
  5849. /*
  5850.   SunOS 4.0 (and maybe earlier?).  This code is dangerous because it
  5851.   prevents compilation with GNU gcc, which uses different formats for the
  5852.   _IORxxx macros than regular cc.  SunOS 4.1 and later can use the POSIX
  5853.   routines above, which work for both cc and gcc.
  5854. */
  5855. #define TCGETS _IOR(T, 8, struct termios) /* Get modes into termios struct */
  5856. #define TCSETS _IOW(T, 9, struct termios) /* Set modes from termios struct */
  5857. #define CRTSCTS 0x80000000          /* RTS/CTS flow control */
  5858.  
  5859.     struct termios {
  5860.     unsigned long c_iflag;        /* Input modes */
  5861.     unsigned long c_oflag;        /* Output modes */
  5862.     unsigned long c_cflag;        /* Control modes */
  5863.     unsigned long c_lflag;        /* Line discipline modes */
  5864.     char c_line;
  5865.     CHAR c_cc[17];
  5866.     };
  5867.     struct termios temp;
  5868. #ifdef NETCMD
  5869.     if (ttpipe) return(0);
  5870. #endif /* NETCMD */
  5871. #ifdef NETPTY
  5872.     if (ttpty) return(0);
  5873. #endif /* NETPTY */
  5874.     debug(F101,"tthflow entry status","",status);
  5875.     if (ioctl(ttyfd,TCGETS,&temp) > -1) { /* Get terminal modes. */
  5876.     if (status) {            /* Turn hard flow on */
  5877.         temp.c_cflag |= CRTSCTS;    /* Add RTS/CTS to them. */
  5878.         x = ioctl(ttyfd,TCSETS,&temp); /* Set them again. */
  5879.         attrs->c_cflag |= CRTSCTS;    /* Add to global info. */
  5880.     } else {            /* Turn hard flow off */
  5881.         temp.c_cflag &= ~CRTSCTS;
  5882.         x = ioctl(ttyfd,TCSETS,&temp);
  5883.         attrs->c_cflag &= ~CRTSCTS;
  5884.     }
  5885.     }
  5886. #else                    /* Not SunOS 4.0 or later */
  5887. #ifdef AIXRS                /* IBM AIX RS/6000 */
  5888. #ifndef AIX41                /* But only pre-4.x == SVR4 */
  5889. #ifdef NETCMD
  5890.     if (ttpipe) return(0);
  5891. #endif /* NETCMD */
  5892. #ifdef NETPTY
  5893.     if (ttpty) return(0);
  5894. #endif /* NETPTY */
  5895.     if (status) {
  5896.     if ((x = ioctl(ttyfd, TXADDCD, "rts")) < 0 && errno != EBUSY)
  5897.       debug(F100,"hardflow TXADDCD (rts) error", "", 0);
  5898.     } else {
  5899.     if ((x = ioctl(ttyfd, TXDELCD, "rts")) < 0 && errno != EINVAL)
  5900.       debug(F100,"hardflow TXDELCD (rts) error", "", 0);
  5901.     }
  5902. #endif /* AIX41 */
  5903. #else                    /* Not AIX RS/6000 */
  5904.  
  5905. #ifdef ATTSV                /* System V... */
  5906.  
  5907. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  5908. #define CK_SCOUNIX
  5909. #else
  5910. #ifdef M_UNIX                /* SCO UNIX 3.2v4.x or earlier */
  5911. #define CK_SCOUNIX
  5912. #endif /* M_UNIX */
  5913. #endif /* CK_SCOV5 */
  5914.  
  5915. #ifdef SCO_FORCE_RTSXOFF
  5916. #ifdef CK_SCOUNIX            /* But not SCO OpenServer 5.0.4 */
  5917. #ifdef SCO_OSR504            /* or later... */
  5918. #undef CK_SCOUNIX
  5919. #endif /* SCO_OSR504 */
  5920. #endif /* CK_SCOUNIX */
  5921. #endif /* SCO_FORCE_RTSXOFF */
  5922.  
  5923. #ifdef CK_SCOUNIX
  5924. #ifdef POSIX
  5925.     struct termios temp;
  5926. #ifdef NETCMD
  5927.     if (ttpipe) return(0);
  5928. #endif /* NETCMD */
  5929. #ifdef NETPTY
  5930.     if (ttpty) return(0);
  5931. #endif /* NETPTY */
  5932.     debug(F101,"tthflow SCOUNIX POSIX entry status","",status);
  5933.     errno = 0;
  5934.     x = tcgetattr(ttyfd, &temp);
  5935.     debug(F111,"tthflow SCO UNIX POSIX tcgetattr",ckitoa(x),errno);
  5936. #else /* POSIX */
  5937.     struct termio temp;
  5938. #ifdef NETCMD
  5939.     if (ttpipe) return(0);
  5940. #endif /* NETCMD */
  5941. #ifdef NETPTY
  5942.     if (ttpty) return(0);
  5943. #endif /* NETPTY */
  5944.     debug(F101,"tthflow SCOUNIX non-POSIX entry status","",status);
  5945.     x = ioctl(ttyfd, TCGETA, &temp);
  5946.     debug(F111,"tthflow SCO UNIX non-POSIX TCGETA",ckitoa(x),errno);
  5947. #endif /* POSIX */
  5948. /*
  5949.   This is not really POSIX, since POSIX does not deal with hardware flow
  5950.   control, but we are using the POSIX APIs.  In fact, RTSFLOW and CTSFLOW
  5951.   are defined in termio.h, but within #ifndef _POSIX_SOURCE..#endif.  So
  5952.   let's try forcing their definitions here.
  5953. */
  5954. #ifndef CTSFLOW
  5955. #define CTSFLOW 0020000
  5956.     debug(F101,"tthflow SCO defining CTSFLOW","",CTSFLOW);
  5957. #else
  5958.     debug(F101,"tthflow SCO CTSFLOW","",CTSFLOW);
  5959. #endif /* CTSFLOW */
  5960. #ifndef RTSFLOW
  5961. #define RTSFLOW 0040000
  5962.     debug(F101,"tthflow SCO defining RTSFLOW","",RTSFLOW);
  5963. #else
  5964.     debug(F101,"tthflow SCO RTSFLOW","",RTSFLOW);
  5965. #endif /* RTSFLOW */
  5966. #ifndef ORTSFL
  5967. #define ORTSFL 0100000
  5968.     debug(F101,"tthflow SCO defining ORTSFL","",ORTSFL);
  5969. #else
  5970.     debug(F101,"tthflow SCO ORTSFL","",ORTSFL);
  5971. #endif /* ORTSFL */
  5972.  
  5973.     if (x != -1) {
  5974.     if (status) {            /* Turn it ON */
  5975.         temp.c_cflag |= RTSFLOW|CTSFLOW;
  5976.         attrs->c_cflag |= RTSFLOW|CTSFLOW;
  5977. #ifdef ORTSFL
  5978.         temp.c_cflag &= ~ORTSFL;
  5979.         attrs->c_cflag &= ~ORTSFL;
  5980. #endif /* ORTSFL */
  5981.         temp.c_iflag &= ~(IXON|IXOFF|IXANY);
  5982.         attrs->c_iflag &= ~(IXON|IXOFF|IXANY);
  5983.     } else {            /* Turn it OFF */
  5984. #ifdef ORTSFL
  5985.         temp.c_cflag &= ~(RTSFLOW|CTSFLOW|ORTSFL);
  5986.         attrs->c_cflag &= ~(RTSFLOW|CTSFLOW|ORTSFL);
  5987. #else  /* ORTSFL */
  5988.         temp.c_cflag &= ~(RTSFLOW|CTSFLOW);
  5989.         attrs->c_cflag &= ~(RTSFLOW|CTSFLOW);
  5990. #endif /* ORTSFL */
  5991.     }
  5992. #ifdef POSIX
  5993.     x = tcsetattr(ttyfd, TCSADRAIN, &temp);
  5994. #else
  5995.     x = ioctl(ttyfd, TCSETA, &temp);
  5996. #endif /* POSIX */
  5997.     debug(F101,"tthflow SCO set modes","",x);
  5998.     }
  5999. #else /* Not SCO UNIX */
  6000. #ifdef NETCMD
  6001.     if (ttpipe) return(0);
  6002. #endif /* NETCMD */
  6003. #ifdef NETPTY
  6004.     if (ttpty) return(0);
  6005. #endif /* NETPTY */
  6006.     if (!status) {            /* Turn it OFF */
  6007. #ifdef RTSXOFF
  6008.     debug(F100,"tthflow ATTSV RTS/CTS OFF","",0);
  6009.     rctsx.x_hflag &= ~(RTSXOFF|CTSXON);
  6010. #ifdef TCSETX
  6011.     x = ioctl(ttyfd,TCSETX,&rctsx);
  6012.     debug(F101,"tthflow ATTSV TCSETX OFF","",x);
  6013. #else
  6014.     x = -1
  6015.     debug(F100,"tthflow TCSETX not defined","",0);
  6016. #endif /* TCSETX */
  6017. #else
  6018.     debug(F100,"tthflow ATTSV RTSXOFF not defined","",0);
  6019. #endif /* RTSXOFF */
  6020. #ifdef DTRXOFF
  6021.     debug(F100,"tthflow ATTSV DTR/CD OFF","",0);
  6022.     rctsx.x_hflag &= ~(DTRXOFF|CDXON);
  6023.     x = ioctl(ttyfd,TCSETX,&rctsx);
  6024.     debug(F101,"tthflow ATTSV DTRXOFF OFF","",x);
  6025. #else
  6026.     debug(F100,"tthflow ATTSV DTRXOFF not defined","",0);
  6027. #endif /* DTRXOFF */
  6028.     } else {                /* Turn it ON. */
  6029.     if (flow == FLO_RTSC) {    /* RTS/CTS Flow control... */
  6030.         debug(F100,"tthflow ATTSV RTS/CTS ON","",0);
  6031. #ifdef RTSXOFF
  6032.         /* This is the preferred way, according to SVID3 */
  6033. #ifdef TCGETX
  6034.         x = ioctl(ttyfd,TCGETX,&rctsx);
  6035.         debug(F101,"tthflow TCGETX","",x);
  6036.         if (x > -1) {
  6037.         rctsx.x_hflag |= RTSXOFF | CTSXON;
  6038.         x = ioctl(ttyfd,TCSETX,&rctsx);
  6039.         debug(F100,"tthflow ATTSV ioctl","",x);
  6040.         }
  6041. #else
  6042.         debug(F100,"tthflow TCGETX not defined","",0);
  6043.         x = -1
  6044. #endif /* TCGETX */
  6045. #else
  6046.         debug(F100,"tthflow RTSXOFF not defined","",0);
  6047.         x = -1;
  6048. #endif /* RTSXOFF */
  6049.     } else if (flow == FLO_DTRC) {    /* DTR/CD Flow control... */
  6050.         debug(F100,"tthflow ATTSV DTR/CD ON","",0);
  6051. #ifdef DTRXOFF
  6052.         /* This is straight out of SVID R4 */
  6053.         if (ioctl(ttyfd,TCGETX,&rctsx) > -1) {
  6054.         rctsx.x_hflag &= ~(DTRXOFF|CDXON);
  6055.         x = ioctl(ttyfd,TCSETX,&rctsx);
  6056.         }
  6057. #else
  6058.         debug(F100,"tthflow ATTSV DTRXOFF not defined","",0);
  6059.         x = -1;
  6060. #endif /* DTRXOFF */
  6061.     }
  6062.     }
  6063. #endif /* CK_SCOUNIX */
  6064.  
  6065. #else /* not System V... */
  6066.  
  6067. #ifdef CK_DTRCTS
  6068. #ifdef LDODTR
  6069. #ifdef LDOCTS
  6070. #ifdef NETCMD
  6071.     if (ttpipe) return(0);
  6072. #endif /* NETCMD */
  6073. #ifdef NETPTY
  6074.     if (ttpty) return(0);
  6075. #endif /* NETPTY */
  6076.     x = LDODTR | LDOCTS;        /* Found only on UTEK? */
  6077.     if (flow == FLO_DTRT && status) {    /* Use hardware flow control */
  6078.     if (lmodef) {
  6079.         x = ioctl(ttyfd,TIOCLBIS,&x);
  6080.         if (x < 0) {
  6081.             debug(F100,"hardflow TIOCLBIS error","",0);
  6082.         } else {
  6083.         lmodef++;
  6084.         debug(F100,"hardflow TIOCLBIS ok","",0);
  6085.         }
  6086.     }
  6087.     } else {
  6088.     if (lmodef) {
  6089.         x = ioctl(ttyfd,TIOCLBIC,&x);
  6090.         if (x < 0) {
  6091.             debug(F100,"hardflow TIOCLBIC error","",0);
  6092.         } else {
  6093.         lmodef++;
  6094.         debug(F100,"hardflow TIOCLBIC ok","",0);
  6095.         }
  6096.     }
  6097.     }
  6098. #endif /* LDODTR */
  6099. #endif /* LDOCTS */
  6100. #endif /* CK_DTRCTS */
  6101. #endif /* ATTSV */
  6102. #endif /* AIXRS */
  6103. #endif /* SUNOS4 */
  6104. #endif /* QNX */
  6105. #endif /* POSIX_CRTSCTS */
  6106. #endif /* SUNOS41 */
  6107.  
  6108. #else /* OXOS */
  6109.  
  6110.     struct termios temp;        /* Olivetti X/OS ... */
  6111.  
  6112. #ifdef NETCMD
  6113.     if (ttpipe) return(0);
  6114. #endif /* NETCMD */
  6115. #ifdef NETPTY
  6116.     if (ttpty) return(0);
  6117. #endif /* NETPTY */
  6118.     x = ioctl(ttyfd,TCGETS,&temp);
  6119.     if (x == 0) {
  6120.     temp.c_cflag &= ~(CRTSCTS|CDTRCTS|CBRKFLOW|CDTRDSR|CRTSDSR);
  6121.     if (status) {
  6122.         switch (flow) {
  6123.           case FLO_RTSC: temp.c_cflag |= CRTSCTS; /* RTS/CTS (hard) */
  6124.         break;
  6125.           case FLO_DTRT: temp.c_cflag |= CDTRCTS; /* DTR/CTS (hard) */
  6126.         break;
  6127.         }
  6128.     }
  6129.     x = ioctl(ttyfd,TCSETS,&temp);
  6130.     }
  6131. #endif /* OXOS */
  6132.     return(x);
  6133.  
  6134. #endif /* Plan9 */
  6135. }
  6136.  
  6137. /*  T T P K T  --  Condition the communication line for packets */
  6138. /*                 or for modem dialing */
  6139.  
  6140. /*
  6141.   If called with speed > -1, also set the speed.
  6142.   Returns 0 on success, -1 on failure.
  6143.  
  6144.   NOTE: the "xflow" parameter is supposed to be the currently selected
  6145.   type of flow control, but for historical reasons, this parameter is also
  6146.   used to indicate that we are dialing.  Therefore, when the true flow
  6147.   control setting is needed, we access the external variable "flow", rather
  6148.   than trusting our "xflow" argument.
  6149. */
  6150. int
  6151. #ifdef CK_ANSIC
  6152. ttpkt(long speed, int xflow, int parity)
  6153. #else
  6154. ttpkt(speed,xflow,parity) long speed; int xflow, parity;
  6155. #endif /* CK_ANSIC */
  6156. /* ttpkt */ {
  6157. #ifndef NOLOCAL
  6158.     int s2;
  6159.     int s = -1;
  6160. #endif /* NOLOCAL */
  6161.     int x;
  6162.     extern int flow;            /* REAL flow-control setting */
  6163.  
  6164.     if (ttyfd < 0) return(-1);          /* Not open. */
  6165.  
  6166.     debug(F101,"ttpkt parity","",parity);
  6167.     debug(F101,"ttpkt xflow","",xflow);
  6168.     debug(F101,"ttpkt speed","",(int) speed);
  6169.  
  6170.     ttprty = parity;                    /* Let other tt functions see these. */
  6171.     ttspeed = speed;            /* Make global copy for this module */
  6172.     ttpmsk = ttprty ? 0177 : 0377;    /* Parity stripping mask */
  6173. #ifdef PARSENSE
  6174.     needpchk = ttprty ? 0 : 1;        /* Parity check needed? */
  6175. #else
  6176.     needpchk = 0;
  6177. #endif /* PARSENSE */
  6178.  
  6179.     debug(F101,"ttpkt ttpmsk","",ttpmsk);
  6180.     debug(F101,"ttpkt netconn","",netconn);
  6181.  
  6182. #ifdef NETCONN                /* No mode-changing for telnet */
  6183.     if (netconn) {
  6184. #ifdef TCPSOCKET
  6185. #ifdef TCP_NODELAY
  6186.         if (ttnet == NET_TCPB) {    /* But turn off Nagle */
  6187.             extern int tcp_nodelay;
  6188.             nodelay_sav = tcp_nodelay;
  6189.             no_delay(ttyfd,1);
  6190.         }
  6191. #endif /* TCP_NODELAY */
  6192. #ifdef TN_COMPORT
  6193.         if (istncomport()) {
  6194.             int rc = -1;
  6195.             if (tvtflg == 0 && speed == ttspeed && flow == ttflow
  6196.                  /* && ttcarr == curcarr */ ) {
  6197.                 debug(F100,"ttpkt modes already set, skipping...","",0);
  6198.                 return(0);        /* Already been called. */
  6199.             }
  6200.             if (flow != ttflow) {
  6201.                 if ((rc = tnsetflow(flow)) < 0)
  6202.           return(rc);
  6203.                 ttflow = flow;
  6204.             }
  6205.             if (speed != ttspeed) {
  6206.                 if (speed <= 0) 
  6207.           speed = tnc_get_baud();
  6208.                 else if ((rc = tnc_set_baud(speed)) < 0)
  6209.           return(rc);
  6210.                 ttspeed = speed;
  6211.             }
  6212.             tnc_set_datasize(8);
  6213.         tnc_set_stopsize(stopbits);
  6214.  
  6215. #ifdef HWPARITY
  6216.             if (hwparity) {
  6217.                 switch (hwparity) {
  6218.           case 'e':            /* Even */
  6219.                     debug(F100,"ttres 8 bits + even parity","",0);
  6220.                     tnc_set_parity(3);
  6221.                     break;
  6222.           case 'o':            /* Odd */
  6223.                     debug(F100,"ttres 8 bits + odd parity","",0);
  6224.                     tnc_set_parity(2);
  6225.                     break;
  6226.           case 'm':            /* Mark */
  6227.                     debug(F100,"ttres 8 bits + invalid parity: mark","",0);
  6228.                     tnc_set_parity(4);
  6229.                     break;
  6230.           case 's':            /* Space */
  6231.                     debug(F100,"ttres 8 bits + invalid parity: space","",0);
  6232.                     tnc_set_parity(5);
  6233.                     break;
  6234.                 }
  6235.             } else 
  6236. #endif /* HWPARITY */
  6237.         {
  6238.                 tnc_set_parity(1);              /* None */
  6239.             }
  6240.             tvtflg = 0;
  6241.             return(0);
  6242.         }
  6243. #endif /* TN_COMPORT */
  6244. #endif /* TCPSOCKET */
  6245.         tvtflg = 0;
  6246.         return(0);
  6247.     }
  6248. #endif /* NETCONN */
  6249. #ifdef NETCMD
  6250.     if (ttpipe) return(0);
  6251. #endif /* NETCMD */
  6252. #ifdef NETPTY
  6253.     if (ttpty) return(0);
  6254. #endif /* NETPTY */
  6255.  
  6256. #ifndef Plan9
  6257.     if (ttfdflg && !isatty(ttyfd)) return(0);
  6258. #endif /* Plan9 */
  6259.  
  6260. #ifdef COHERENT
  6261. #define SVORPOSIX
  6262. #endif /* COHERENT */
  6263.  
  6264. #ifndef SVORPOSIX            /* Berkeley, V7, etc. */
  6265. #ifdef LPASS8
  6266. /*
  6267.  For some reason, with BSD terminal drivers, you can't set FLOW to XON/XOFF
  6268.  after having previously set it to NONE without closing and reopening the
  6269.  device.  Unless there's something I overlooked below...
  6270. */
  6271.     if (ttflow == FLO_NONE && flow == FLO_XONX && xlocal == 0) {
  6272.     debug(F101,"ttpkt executing horrible flow kludge","",0);
  6273.     ttclos(0);            /* Close it */
  6274.     x = 0;
  6275.     ttopen(ttnmsv,&x,ttmdm,0);    /* Open it again */
  6276.     }
  6277. #endif /* LPASS8 */
  6278. #endif /* SVORPOSIX */
  6279.  
  6280. #ifdef COHERENT                /* This must be vestigial since we */
  6281. #undef SVORPOSIX            /* reverse it a few lines below... */
  6282. #endif /* COHERENT */
  6283.  
  6284.     if (xflow != FLO_DIAL && xflow != FLO_DIAX)
  6285.       ttflow = xflow;            /* Now make this available too. */
  6286.  
  6287. #ifndef NOLOCAL
  6288.     if (xlocal) {
  6289.     s2 = (int) (speed / 10L);    /* Convert bps to cps */
  6290.     debug(F101,"ttpkt calling ttsspd","",s2);
  6291.     s = ttsspd(s2);            /* Check and set the speed */
  6292.     debug(F101,"ttpkt ttsspd result","",s);
  6293.      carrctl(&ttraw, xflow != FLO_DIAL /* Carrier control */
  6294.         && (ttcarr == CAR_ON || (ttcarr == CAR_AUT && ttmdm != 0)));
  6295.     tvtflg = 0;            /* So ttvt() will work next time */
  6296.     }
  6297. #endif /* NOLOCAL */
  6298.  
  6299. #ifdef COHERENT
  6300. #define SVORPOSIX
  6301. #endif /* COHERENT */
  6302.  
  6303. #ifndef SVORPOSIX            /* BSD section */
  6304.     if (flow == FLO_RTSC ||        /* Hardware flow control */
  6305.     flow == FLO_DTRC ||
  6306.     flow == FLO_DTRT) {
  6307.     tthflow(flow, 1, &ttraw);
  6308.     debug(F100,"ttpkt hard flow, TANDEM off, RAW on","",0);
  6309.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6310.     ttraw.sg_flags |= RAW;        /* Enter raw mode */
  6311.     } else if (flow == FLO_NONE) {    /* No flow control */
  6312.     debug(F100,"ttpkt no flow, TANDEM off, RAW on","",0);
  6313.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6314.     tthflow(flow, 0, &ttraw);    /* Turn off any hardware f/c too */
  6315.     ttraw.sg_flags |= RAW;        /* Enter raw mode */
  6316.     } else if (flow == FLO_KEEP) {    /* Keep device's original setting */
  6317.     debug(F100,"ttpkt keeping original TANDEM","",0);
  6318.     ttraw.sg_flags &= ~TANDEM;
  6319.     ttraw.sg_flags |= (ttold.sg_flags & TANDEM);
  6320.     /* NOTE: We should also handle hardware flow control here! */
  6321.     }
  6322.  
  6323. /* SET FLOW XON/XOFF is in effect, or SET FLOW KEEP resulted in Xon/Xoff */
  6324.  
  6325.     if ((flow == FLO_XONX) || (ttraw.sg_flags & TANDEM)) {
  6326.     debug(F100,"ttpkt turning on TANDEM","",0);
  6327.     ttraw.sg_flags |= TANDEM;    /* So ask for it. */
  6328.  
  6329. #ifdef LPASS8                /* Can pass 8-bit data through? */
  6330. /* If the LPASS8 local mode is available, then flow control can always  */
  6331. /* be used, even if parity is none and we are transferring 8-bit data.  */
  6332. /* But we only need to do all this if Xon/Xoff is requested. */
  6333. /* BUT... this tends not to work through IP or LAT connections, terminal */
  6334. /* servers, telnet, rlogin, etc, so it is currently disabled. */
  6335.     x = LPASS8;            /* If LPASS8 defined, then */
  6336.     debug(F100,"ttpkt executing LPASS8 code","",0);
  6337.     if (lmodef) {            /* TIOCLBIS must be too. */
  6338.         x = ioctl(ttyfd,TIOCLBIS,&x); /* Try to set LPASS8. */
  6339.         if (x < 0) {
  6340.         debug(F100,"ttpkt TIOCLBIS error","",0);
  6341.         } else {
  6342.         lmodef++;
  6343.         debug(F100,"ttpkt TIOCLBIS ok","",0);
  6344.         }
  6345.     }
  6346. /*
  6347.  But if we use LPASS8 mode, we must explicitly turn off
  6348.  terminal interrupts of all kinds.
  6349. */
  6350. #ifdef TIOCGETC                /* Not rawmode, */
  6351.     if (tcharf && (xlocal == 0)) {    /* must turn off */
  6352.         tchnoi.t_intrc = -1;    /* interrupt character */
  6353.         tchnoi.t_quitc = -1;    /* and quit character. */
  6354.         tchnoi.t_startc = 17;    /* Make sure xon */
  6355.         tchnoi.t_stopc = 19;    /* and xoff not ignored. */
  6356. #ifndef NOBRKC
  6357.         tchnoi.t_eofc = -1;        /* eof character. */
  6358.         tchnoi.t_brkc = -1;        /* brk character. */
  6359. #endif /* NOBRKC */
  6360.         if (ioctl(ttyfd,TIOCSETC,&tchnoi) < 0) {
  6361.         debug(F100,"ttpkt TIOCSETC failed","",0);
  6362.         } else {
  6363.         tcharf = 1;
  6364.         debug(F100,"ttpkt TIOCSETC ok","",0);
  6365.         }
  6366. #ifdef COMMENT
  6367. /* only for paranoid debugging */
  6368.         if (tcharf) {
  6369.         struct tchars foo;
  6370.         char tchbuf[100];
  6371.         ioctl(0,TIOCGETC,&foo);
  6372.         sprintf(tchbuf,
  6373.             "intr=%d,quit=%d, start=%d, stop=%d, eof=%d, brk=%d",
  6374.             foo.t_intrc, foo.t_quitc, foo.t_startc,
  6375.             foo.t_stopc, foo.t_eofc,  foo.t_brkc);
  6376.         debug(F110,"ttpkt chars",tchbuf,0);
  6377.         }
  6378. #endif /* COMMENT */
  6379.     }
  6380.     ttraw.sg_flags |= CBREAK;    /* Needed for unknown reason */
  6381. #endif /* TIOCGETC */
  6382.  
  6383. /* Prevent suspend during packet mode */
  6384. #ifdef TIOCGLTC                /* Not rawmode, */
  6385.     if (ltcharf && (xlocal == 0)) {    /* must turn off */
  6386.         ltchnoi.t_suspc = -1;    /* suspend character */
  6387.         ltchnoi.t_dsuspc = -1;    /* and delayed suspend character */
  6388.         if (ioctl(ttyfd,TIOCSLTC,&tchnoi) < 0) {
  6389.         debug(F100,"ttpkt TIOCSLTC failed","",0);
  6390.         } else {
  6391.         ltcharf = 1;
  6392.         debug(F100,"ttpkt TIOCSLTC ok","",0);
  6393.         }
  6394.     }
  6395. #endif /* TIOCGLTC */
  6396.  
  6397. #else /* LPASS8 not defined */
  6398.  
  6399. /* Previously, BSD-based implementations always */
  6400. /* used rawmode for packets.  Now, we use rawmode only if parity is NONE. */
  6401. /* This allows the flow control requested above to actually work, but only */
  6402. /* if the user asks for parity (which also means they get 8th-bit quoting). */
  6403.  
  6404.     if (parity) {            /* If parity, */
  6405.         ttraw.sg_flags &= ~RAW;    /* use cooked mode */
  6406. #ifdef COMMENT
  6407. /* WHY??? */
  6408.         if (xlocal)
  6409. #endif /* COMMENT */
  6410.           ttraw.sg_flags |= CBREAK;
  6411.         debug(F101,"ttpkt cooked, cbreak, parity","",parity);
  6412. #ifdef TIOCGETC                /* Not rawmode, */
  6413.         if (tcharf && (xlocal == 0)) { /* must turn off */
  6414.         tchnoi.t_intrc = -1;    /* interrupt character */
  6415.         tchnoi.t_quitc = -1;    /* and quit character. */
  6416.         tchnoi.t_startc = 17;    /* Make sure xon */
  6417.         tchnoi.t_stopc = 19;    /* and xoff not ignored. */
  6418. #ifndef NOBRKC
  6419.         tchnoi.t_eofc = -1;    /* eof character. */
  6420.         tchnoi.t_brkc = -1;    /* brk character. */
  6421. #endif /* NOBRKC */
  6422.         if (ioctl(ttyfd,TIOCSETC,&tchnoi) < 0) {
  6423.             debug(F100,"ttpkt TIOCSETC failed","",0);
  6424.         } else {
  6425.             tcharf = 1;
  6426.             debug(F100,"ttpkt TIOCSETC ok","",0);
  6427.         }
  6428.         }
  6429. #endif /* TIOCGETC */
  6430. #ifdef TIOCGLTC                /* Not rawmode, */
  6431. /* Prevent suspend during packet mode */
  6432.         if (ltcharf && (xlocal == 0)) { /* must turn off */
  6433.         ltchnoi.t_suspc = -1;    /* suspend character */
  6434.         ltchnoi.t_dsuspc = -1;    /* and delayed suspend character */
  6435.         if (ioctl(ttyfd,TIOCSLTC,&tchnoi) < 0) {
  6436.             debug(F100,"ttpkt TIOCSLTC failed","",0);
  6437.         } else {
  6438.             ltcharf = 1;
  6439.             debug(F100,"ttpkt TIOCSLTC ok","",0);
  6440.         }
  6441.         }
  6442. #endif /* TIOCGLTC */
  6443.     } else {            /* If no parity, */
  6444.         ttraw.sg_flags |= RAW;    /* must use 8-bit raw mode. */
  6445.         debug(F101,"ttpkt setting rawmode, parity","",parity);
  6446.     }
  6447. #endif /* LPASS8 */
  6448.     } /* End of Xon/Xoff section */
  6449.  
  6450.     /* Don't echo, don't map CR to CRLF on output, don't fool with case */
  6451. #ifdef LCASE
  6452.     ttraw.sg_flags &= ~(ECHO|CRMOD|LCASE);
  6453. #else
  6454.     ttraw.sg_flags &= ~(ECHO|CRMOD);
  6455. #endif /* LCASE */
  6456.  
  6457. #ifdef TOWER1
  6458.     ttraw.sg_flags &= ~ANYP;            /* Must set this on old Towers */
  6459. #endif /* TOWER1 */
  6460.  
  6461. #ifdef BELLV10
  6462.     if (ioctl(ttyfd,TIOCSETP,&ttraw) < 0) /* Set the new modes. */
  6463.       return(-1);
  6464. #else
  6465.     errno = 0;
  6466.     if (stty(ttyfd,&ttraw) < 0) {       /* Set the new modes. */
  6467.         debug(F101,"ttpkt stty failed","",errno);
  6468.         return(-1);
  6469.     }
  6470. #endif /* BELLV10 */
  6471.     debug(F100,"ttpkt stty ok","",0);
  6472.  
  6473. #ifdef sony_news
  6474.     x = xlocal ? km_ext : km_con;    /* Put line in ASCII mode. */
  6475.     if (x != -1) {            /* Make sure we know original modes. */
  6476.     x &= ~KM_TTYPE;
  6477.     x |= KM_ASCII;
  6478.     if (ioctl(ttyfd,TIOCKSET, &x) < 0) {
  6479.         perror("ttpkt can't set ASCII mode");
  6480.         debug(F101,"ttpkt error setting ASCII mode","",x);
  6481.         return(-1);
  6482.     }
  6483.     }
  6484.     debug(F100,"ttpkt set ASCII mode ok","",0);
  6485. #endif /* sony_news */
  6486.  
  6487.     if (xlocal == 0) {            /* Turn this off so we can read */
  6488.     signal(SIGINT,SIG_IGN);        /* Ctrl-C chars typed at console */
  6489.     sigint_ign = 1;
  6490.     }
  6491.     tvtflg = 0;                /* So ttvt() will work next time */
  6492.     debug(F100,"ttpkt success","",0);
  6493.     return(0);
  6494.  
  6495. #endif /* Not ATTSV or POSIX */
  6496.  
  6497. /* AT&T UNIX and POSIX */
  6498.  
  6499. #ifdef COHERENT
  6500. #define SVORPOSIX
  6501. #endif /* COHERENT */
  6502.  
  6503. #ifdef SVORPOSIX
  6504.     if (flow == FLO_XONX) {        /* Xon/Xoff */
  6505.     ttraw.c_iflag |= (IXON|IXOFF);
  6506.     tthflow(flow, 0, &ttraw);
  6507.     } else if (flow == FLO_NONE) {    /* None */
  6508.     /* NOTE: We should also turn off hardware flow control here! */
  6509.     ttraw.c_iflag &= ~(IXON|IXOFF);
  6510.     tthflow(flow, 0, &ttraw);
  6511.     } else if (flow == FLO_KEEP) {    /* Keep */
  6512.     ttraw.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff flags */
  6513.     ttraw.c_iflag |= (ttold.c_iflag & (IXON|IXOFF)); /* OR in old ones */
  6514.     /* NOTE: We should also handle hardware flow control here! */
  6515. #ifdef POSIX_CRTSCTS
  6516. /* In Linux case, we do this, which is unlikely to be portable */
  6517.         ttraw.c_cflag &= ~CRTSCTS;    /* Turn off RTS/CTS flag */
  6518.         ttraw.c_cflag |= (ttold.c_cflag & CRTSCTS); /* OR in old one */
  6519. #endif /* POSIX_CRTSCTS */
  6520.     } else if (flow == FLO_RTSC ||    /* Hardware */
  6521.            flow == FLO_DTRC ||
  6522.            flow == FLO_DTRT) {
  6523.     ttraw.c_iflag &= ~(IXON|IXOFF);    /* (190) */
  6524.     tthflow(flow, 1, &ttraw);
  6525.     }
  6526.     ttraw.c_lflag &= ~(ICANON|ECHO);
  6527.     ttraw.c_lflag &= ~ISIG;        /* Do NOT check for interrupt chars */
  6528.  
  6529. #ifndef OXOS
  6530. #ifdef QNX
  6531.     if (flow != FLO_RTSC && flow != FLO_DTRC && flow != FLO_DTRT)
  6532. #endif /* QNX */
  6533. #ifndef COHERENT
  6534.       ttraw.c_lflag &= ~IEXTEN;        /* Turn off ^O/^V processing */
  6535. #endif /* COHERENT */
  6536. #else /* OXOS */
  6537.     ttraw.c_cc[VDISCARD] = ttraw.c_cc[VLNEXT] = CDISABLE;
  6538. #endif /* OXOS */
  6539.     ttraw.c_lflag |= NOFLSH;        /* Don't flush */
  6540.     ttraw.c_iflag |= IGNPAR;        /* Ignore parity errors */
  6541. #ifdef ATTSV
  6542. #ifdef BSD44
  6543.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|INPCK|ISTRIP|IXANY);
  6544. #else
  6545.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IUCLC|INPCK|ISTRIP|IXANY);
  6546. #endif /* BSD44 */
  6547. #else /* POSIX */
  6548.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|INPCK|ISTRIP);
  6549. #endif /* ATTSV */
  6550.     ttraw.c_oflag &= ~OPOST;
  6551.     ttraw.c_cflag &= ~(CSIZE);
  6552.     ttraw.c_cflag |= (CS8|CREAD|HUPCL);
  6553.  
  6554. #ifdef CSTOPB
  6555.     if (xlocal) {
  6556.     if (stopbits == 2) {
  6557.         ttraw.c_cflag |= CSTOPB;    /* 2 stop bits */
  6558.         debug(F100,"ttpkt 2 stopbits","",0);
  6559.     } else if (stopbits == 1) {
  6560.         ttraw.c_cflag &= ~(CSTOPB);    /* 1 stop bit */
  6561.         debug(F100,"ttpkt 1 stopbit","",0);
  6562.     }
  6563.     }
  6564. #endif /* CSTOPB */
  6565.  
  6566. #ifdef HWPARITY
  6567.     if (hwparity && xlocal) {        /* Hardware parity */
  6568.     ttraw.c_cflag |= PARENB;    /* Enable parity */
  6569. #ifdef COMMENT
  6570. /* Uncomment this only if needed -- I don't think it is */
  6571.     ttraw.c_cflag &= ~(CSIZE);    /* Clear out character-size mask */
  6572.     ttraw.c_cflag |= CS8;        /* And set it to 8 */
  6573. #endif /* COMMENT */
  6574. #ifdef IGNPAR
  6575.     ttraw.c_iflag |= IGNPAR;    /* Don't discard incoming bytes */
  6576.     debug(F100,"ttpkt IGNPAR","",0); /* that have parity errors */
  6577. #endif /* IGNPAR */
  6578.     switch (hwparity) {
  6579.       case 'e':            /* Even */
  6580.         ttraw.c_cflag &= ~(PARODD);
  6581.         debug(F100,"ttpkt 8 bits + even parity","",0);
  6582.         break;
  6583.       case 'o':            /* Odd */
  6584.         ttraw.c_cflag |= PARODD;
  6585.         debug(F100,"ttpkt 8 bits + odd parity","",0);
  6586.         break;
  6587.       case 'm':            /* Mark */
  6588.       case 's':            /* Space */
  6589.         /* PAREXT is mentioned in SVID but the details are not given. */
  6590.         /* PAREXT is not included in POSIX ISO/IEC 9945-1. */
  6591.         debug(F100,"ttpkt 8 bits + invalid parity","",0);
  6592.         break;
  6593.     }
  6594.     } else {                /* We handle parity ourselves */
  6595. #endif /* HWPARITY */
  6596.     ttraw.c_cflag &= ~(PARENB);    /* Don't enable parity */
  6597. #ifdef HWPARITY
  6598.     }
  6599. #endif /* HWPARITY */
  6600.  
  6601. #ifdef IX370
  6602.     ttraw.c_cc[4] = 48;  /* So Series/1 doesn't interrupt on every char */
  6603.     ttraw.c_cc[5] = 1;
  6604. #else
  6605. #ifndef VEOF                /* for DGUX this is VEOF, not VMIN */
  6606.     ttraw.c_cc[4] = 1;   /* [VMIN]  return max of this many characters or */
  6607. #else
  6608. #ifndef OXOS
  6609. #ifdef VMIN
  6610.     ttraw.c_cc[VMIN] = 1;
  6611. #endif /* VMIN */
  6612. #else /* OXOS */
  6613.     ttraw.c_min = 1;
  6614. #endif /* OXOS */
  6615. #endif /* VEOF */
  6616. #ifndef VEOL                /* for DGUX this is VEOL, not VTIME */
  6617.     ttraw.c_cc[5] = 0;     /* [VTIME] when this many secs/10 expire w/no input */
  6618. #else
  6619. #ifndef OXOS
  6620. #ifdef VTIME
  6621.     ttraw.c_cc[VTIME] = 0;
  6622. #endif /* VTIME */
  6623. #else /* OXOS */
  6624.     ttraw.c_time = 0;
  6625. #endif /* OXOS */
  6626. #endif /* VEOL */
  6627. #endif /* IX370 */
  6628.  
  6629. #ifdef VINTR                /* Turn off interrupt character */
  6630.     if (xlocal == 0)            /* so ^C^C can break us out of */
  6631.       ttraw.c_cc[VINTR] = 0;        /* packet mode. */
  6632. #endif /* VINTR */
  6633.  
  6634. #ifdef Plan9
  6635.     if (p9ttyparity('n') < 0)
  6636.     return -1;
  6637. #else
  6638. #ifdef BSD44ORPOSIX
  6639.     errno = 0;
  6640. #ifdef BEOSORBEBOX
  6641.     ttraw.c_cc[VMIN] = 0;        /* DR7 can only poll. */
  6642. #endif /* BEOSORBEBOX */
  6643.     debug(F100,"ttpkt calling tcsetattr(TCSETAW)","",0);
  6644.     x = tcsetattr(ttyfd,TCSADRAIN,&ttraw);
  6645.     debug(F101,"ttpkt BSD44ORPOSIX tcsetattr","",x);
  6646.     if (x < 0) {
  6647.     debug(F101,"ttpkt BSD44ORPOSIX tcsetattr errno","",errno);
  6648.         return(-1);
  6649.     }
  6650. #else /* BSD44ORPOSIX */
  6651.     x = ioctl(ttyfd,TCSETAW,&ttraw);
  6652.     debug(F101,"ttpkt ATTSV ioctl TCSETAW","",x);
  6653.     if (x < 0) {  /* set new modes . */
  6654.     debug(F101,"ttpkt ATTSV ioctl TCSETAW errno","",errno);
  6655.         return(-1);
  6656.     }
  6657. #endif /* BSD44ORPOSIX */
  6658. #endif /* Plan9 */
  6659.     tvtflg = 0;
  6660.     debug(F100,"ttpkt ok","",0);
  6661.     return(0);
  6662. #endif /* ATTSV */
  6663.  
  6664. #ifdef COHERENT
  6665. #undef SVORPOSIX
  6666. #endif /* COHERENT */
  6667.  
  6668. }
  6669.  
  6670. /*  T T S E T F L O W  --  Set flow control immediately.  */
  6671.  
  6672. #ifdef COHERENT
  6673. #define SVORPOSIX
  6674. #endif /* COHERENT */
  6675.  
  6676. int
  6677. ttsetflow(flow) int flow; {
  6678.     if (ttyfd < 0)            /* A channel must be open */
  6679.       return(-1);
  6680.  
  6681.     debug(F101,"ttsetflow flow","",flow);
  6682.  
  6683. #ifdef TN_COMPORT
  6684.     if (netconn && istncomport()) {
  6685.     debug(F101,"ttsetflow net modem","",ttmdm);
  6686.     return(tnsetflow(flow));
  6687.     }
  6688. #endif /* TN_COMPORT */
  6689. #ifdef NETCMD
  6690.     if (ttpipe) return(0);
  6691. #endif /* NETCMD */
  6692. #ifdef NETPTY
  6693.     if (ttpty) return(0);
  6694. #endif /* NETPTY */
  6695.  
  6696. #ifdef COMMENT
  6697.     /* This seems to hurt... */
  6698.     if (flow == FLO_KEEP)
  6699.       return(0);
  6700. #endif /* COMMENT */
  6701.  
  6702.     if (flow == FLO_RTSC ||        /* Hardware flow control... */
  6703.     flow == FLO_DTRC ||
  6704.     flow == FLO_DTRT) {
  6705.     tthflow(flow, 1, &ttraw);
  6706. #ifndef SVORPOSIX
  6707.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6708. #else
  6709.     ttraw.c_iflag &= ~(IXON|IXOFF);
  6710. #endif /* SVORPOSIX */
  6711.  
  6712.     } else if (flow == FLO_XONX) {    /* Xon/Xoff... */
  6713.  
  6714. #ifndef SVORPOSIX
  6715.     ttraw.sg_flags |= TANDEM;
  6716. #else
  6717.     ttraw.c_iflag |= (IXON|IXOFF);
  6718. #endif /* SVORPOSIX */
  6719.     tthflow(FLO_RTSC, 0, &ttraw);    /* Turn off hardware flow control */
  6720.  
  6721.     } else if (flow == FLO_NONE) {    /* No flow control */
  6722.  
  6723. #ifndef SVORPOSIX
  6724.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6725. #else
  6726.     ttraw.c_iflag &= ~(IXON|IXOFF);
  6727. #endif /* SVORPOSIX */
  6728.     tthflow(FLO_RTSC, 0, &ttraw);    /* Turn off any hardware f/c too */
  6729.     }
  6730.  
  6731. /* Set the new modes... */
  6732.  
  6733. #ifndef SVORPOSIX            /* BSD and friends */
  6734. #ifdef BELLV10
  6735.     if (ioctl(ttyfd,TIOCSETP,&ttraw) < 0)
  6736.       return(-1);
  6737. #else
  6738. #ifndef MINIX2
  6739.     if (stty(ttyfd,&ttraw) < 0)
  6740.       return(-1);
  6741. #endif /* MINIX2 */
  6742. #endif /* BELLV10 */
  6743. #else
  6744. #ifdef BSD44ORPOSIX            /* POSIX */
  6745.     if (tcsetattr(ttyfd,TCSADRAIN,&ttraw) < 0)
  6746.       return(-1);
  6747. #else                    /* System V */
  6748.     if (ioctl(ttyfd,TCSETAW,&ttraw) < 0)
  6749.       return(-1);
  6750. #endif /* BSD44ORPOSIX */
  6751. #endif /* SVORPOSIX */
  6752.     return(0);
  6753. }
  6754. #ifdef COHERENT
  6755. #undef SVORPOSIX
  6756. #endif /* COHERENT */
  6757.  
  6758. /*  T T V T -- Condition communication device for use as virtual terminal. */
  6759.  
  6760. int
  6761. #ifdef CK_ANSIC
  6762. ttvt(long speed, int flow)
  6763. #else
  6764. ttvt(speed,flow) long speed; int flow;
  6765. #endif /* CK_ANSIC */
  6766. /* ttvt */ {
  6767.     int s, s2, x;
  6768.  
  6769.     debug(F101,"ttvt ttyfd","",ttyfd);
  6770.     debug(F101,"ttvt tvtflg","",tvtflg);
  6771.     debug(F111,"ttvt speed",ckitoa(ttspeed),speed);
  6772.     debug(F111,"ttvt flow",ckitoa(ttflow),flow);
  6773.     debug(F111,"ttvt curcarr",ckitoa(ttcarr),curcarr);
  6774.  
  6775. /* Note: NetBSD and maybe other BSD44s have cfmakeraw() */
  6776. /* Maybe it would be simpler to use it... */
  6777.  
  6778.     ttpmsk = 0xff;
  6779. #ifdef NOLOCAL
  6780.     return(conbin((char)escchr));
  6781. #else
  6782.     if (ttyfd < 0) {            /* Not open. */
  6783.     if (ttchk() < 0)
  6784.       return(-1);
  6785.     else                /* But maybe something buffered. */
  6786.       return(0);
  6787.     }
  6788. #ifdef NETCMD
  6789.     if (ttpipe) return(0);
  6790. #endif /* NETCMD */
  6791. #ifdef NETPTY
  6792.     if (ttpty) return(0);
  6793. #endif /* NETPTY */
  6794. #ifdef NETCONN
  6795.     if (netconn) {
  6796. #ifdef TCPSOCKET
  6797. #ifdef TCP_NODELAY
  6798.         {
  6799.         extern int tcp_nodelay;
  6800.         if (ttnet == NET_TCPB) {
  6801.         if (nodelay_sav > -1) {
  6802.             no_delay(ttyfd,nodelay_sav);
  6803.             nodelay_sav = -1;
  6804.         }
  6805.         }
  6806.         }
  6807. #endif /* TCP_NODELAY */
  6808. #ifdef TN_COMPORT
  6809.         if (istncomport()) {
  6810.             int rc = -1;
  6811.             if (tvtflg != 0 && speed == ttspeed && flow == ttflow
  6812.                  /* && ttcarr == curcarr */ ) {
  6813.                 debug(F100,"ttvt modes already set, skipping...","",0);
  6814.                 return(0);            /* Already been called. */
  6815.             }
  6816.             if (flow != ttflow) {
  6817.                 if ((rc = tnsetflow(flow)) < 0)
  6818.           return(rc);
  6819.                 ttflow = flow;
  6820.             }
  6821.             if (speed != ttspeed) {
  6822.                 if (speed <= 0) 
  6823.           speed = tnc_get_baud();
  6824.                 else if ((rc = tnc_set_baud(speed)) < 0)
  6825.           return(rc);
  6826.                 ttspeed = speed;
  6827.             }
  6828.             tnc_set_datasize(8);
  6829.         tnc_set_stopsize(stopbits);
  6830.  
  6831. #ifdef HWPARITY
  6832.             if (hwparity) {
  6833.                 switch (hwparity) {
  6834.           case 'e':        /* Even */
  6835.                     debug(F100,"ttres 8 bits + even parity","",0);
  6836.                     tnc_set_parity(3);
  6837.                     break;
  6838.           case 'o':        /* Odd */
  6839.                     debug(F100,"ttres 8 bits + odd parity","",0);
  6840.                     tnc_set_parity(2);
  6841.                     break;
  6842.           case 'm':        /* Mark */
  6843.                     debug(F100,"ttres 8 bits + invalid parity: mark","",0);
  6844.                     tnc_set_parity(4);
  6845.                     break;
  6846.           case 's':        /* Space */
  6847.                     debug(F100,"ttres 8 bits + invalid parity: space","",0);
  6848.                     tnc_set_parity(5);
  6849.                     break;
  6850.                 }
  6851.             } else
  6852. #endif /* HWPARITY */
  6853.             {
  6854.                 tnc_set_parity(1);    /* None */
  6855.             }
  6856.             tvtflg = 1;
  6857.             return(0);
  6858.         }
  6859. #endif /* TN_COMPORT */
  6860. #endif /* TCPSOCKET */
  6861.     tvtflg = 1;            /* Network connections... */
  6862.     debug(F100,"ttvt network connection, skipping...","",0);
  6863.     return(0);            /* ... require no special setup */
  6864.     }
  6865. #endif /* NETCONN */
  6866.  
  6867.     if (tvtflg != 0 && speed == ttspeed && flow == ttflow
  6868.     /* && ttcarr == curcarr */ )
  6869.       {
  6870.       debug(F100,"ttvt modes already set, skipping...","",0);
  6871.       return(0);            /* Already been called. */
  6872.       }
  6873.  
  6874.     if (ttfdflg
  6875. #ifndef Plan9
  6876.     && !isatty(ttyfd)
  6877. #endif /* Plan9 */
  6878.     ) {
  6879.     debug(F100,"ttvt using external fd, skipping...","",0);
  6880.     return(0);
  6881.     }
  6882.  
  6883.     debug(F100,"ttvt setting modes...","",0);
  6884.  
  6885.     if (xlocal) {            /* For external lines... */
  6886.     s2 = (int) (speed / 10L);
  6887.     s = ttsspd(s2);            /* Check/set the speed */
  6888.     carrctl(&tttvt, flow != FLO_DIAL /* Do carrier control */
  6889.         && (ttcarr == CAR_ON || (ttcarr == CAR_AUT && ttmdm != 0)));
  6890.     } else
  6891.       s = s2 = -1;
  6892.  
  6893. #ifdef COHERENT
  6894. #define SVORPOSIX
  6895. #endif /* COHERENT */
  6896.  
  6897. #ifndef SVORPOSIX
  6898.     /* Berkeley, V7, etc */
  6899.     if (flow == FLO_RTSC ||        /* Hardware flow control */
  6900.     flow == FLO_DTRC ||
  6901.     flow == FLO_DTRT) {
  6902.     tthflow(flow, 1, &tttvt);
  6903.     debug(F100,"ttvt hard flow, TANDEM off","",0);
  6904.     tttvt.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6905.     } else if (flow == FLO_XONX) {    /* Xon/Xoff flow control */
  6906.     debug(F100,"ttvt TANDEM on","",0);
  6907.     tttvt.sg_flags |= TANDEM;    /* Ask for it. */
  6908.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  6909.     } else if (flow == FLO_NONE) {
  6910.     debug(F100,"ttvt no flow, TANDEM off, RAW on","",0);
  6911.     tttvt.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6912.     tthflow(flow, 0, &tttvt);    /* Turn off any hardware f/c too */
  6913.     tttvt.sg_flags |= RAW;        /* Enter raw mode */
  6914.     } else if (flow == FLO_KEEP) {    /* Keep device's original setting */
  6915.     debug(F100,"ttvt keeping original TANDEM","",0);
  6916.     tttvt.sg_flags &= ~TANDEM;
  6917.     tttvt.sg_flags |= (ttold.sg_flags & TANDEM);
  6918.     /* NOTE: We should also handle hardware flow control here! */
  6919.     }
  6920.     tttvt.sg_flags |= RAW;              /* Raw mode in all cases */
  6921. #ifdef TOWER1
  6922.     tttvt.sg_flags &= ~(ECHO|ANYP);     /* No echo or parity */
  6923. #else
  6924.     tttvt.sg_flags &= ~ECHO;            /* No echo */
  6925. #endif /* TOWER1 */
  6926.  
  6927. #ifdef BELLV10
  6928.     if (ioctl(ttyfd,TIOCSETP,&tttvt) < 0) /* Set the new modes */
  6929.       return(-1);
  6930. #else
  6931.     if (stty(ttyfd,&tttvt) < 0)        /* Set the new modes */
  6932.       return(-1);
  6933. #endif /* BELLV10 */
  6934.  
  6935. #else /* It is ATTSV or POSIX */
  6936.  
  6937.     if (flow == FLO_XONX) {        /* Software flow control */
  6938.     tttvt.c_iflag |= (IXON|IXOFF);    /* On if requested. */
  6939.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  6940.     debug(F100,"ttvt SVORPOSIX flow XON/XOFF","",0);
  6941.     } else if (flow == FLO_NONE) {    /* NONE */
  6942.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff */
  6943.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  6944.     debug(F100,"ttvt SVORPOSIX flow NONE","",0);
  6945.     } else if (flow == FLO_KEEP) {
  6946.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff flags */
  6947.     tttvt.c_iflag |= (ttold.c_iflag & (IXON|IXOFF)); /* OR in old ones */
  6948. #ifdef POSIX_CRTSCTS
  6949.         tttvt.c_cflag &= ~CRTSCTS;    /* Turn off RTS/CTS flag */
  6950.         tttvt.c_cflag |= (ttold.c_cflag & CRTSCTS); /* OR in old one */
  6951. #endif /* POSIX_CRTSCTS */
  6952.     debug(F100,"ttvt SVORPOSIX flow KEEP","",0);
  6953.     } else if (flow == FLO_RTSC ||    /* Hardware flow control */
  6954.            flow == FLO_DTRC ||
  6955.            flow == FLO_DTRT) {
  6956.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* (196) */
  6957.     tthflow(flow, 1, &tttvt);
  6958.     debug(F100,"ttvt SVORPOSIX flow HARD","",0);
  6959.     }
  6960. #ifndef OXOS
  6961. #ifdef COHERENT
  6962.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO);
  6963. #else
  6964.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO|IEXTEN);
  6965. #endif /* COHERENT */
  6966. #ifdef QNX
  6967.     /* Needed for hwfc */
  6968.     if (flow == FLO_RTSC || flow == FLO_DTRC || flow == FLO_DTRT)
  6969.       tttvt.c_lflag |= IEXTEN;
  6970. #endif /* QNX */
  6971. #else /* OXOS */
  6972.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO);
  6973.     tttvt.c_cc[VDISCARD] = tttvt.c_cc[VLNEXT] = CDISABLE;
  6974. #endif /* OXOS */
  6975.  
  6976.     tttvt.c_iflag |= (IGNBRK|IGNPAR);
  6977.  
  6978. /* Stop bits */
  6979.  
  6980. #ifdef CSTOPB
  6981.     if (xlocal) {
  6982.     if (stopbits == 2) {
  6983.         tttvt.c_cflag |= CSTOPB;    /* 2 stop bits */
  6984.         debug(F100,"ttvt 2 stopbits","",0);
  6985.     } else if (stopbits == 1) {
  6986.         tttvt.c_cflag &= ~(CSTOPB);    /* 1 stop bit */
  6987.         debug(F100,"ttvt 1 stopbit","",0);
  6988.     }
  6989.     }
  6990. #endif /* CSTOPB */
  6991.  
  6992. /* Parity */
  6993.  
  6994. #ifdef HWPARITY
  6995.     if (hwparity && xlocal) {        /* Hardware parity */
  6996. #ifdef COMMENT
  6997. /* Uncomment this only if needed -- I don't think it is */
  6998.     ttraw.c_cflag &= ~(CSIZE);    /* Clear out character-size mask */
  6999.     ttraw.c_cflag |= CS8;        /* And set it to 8 */
  7000. #endif /* COMMENT */
  7001. #ifdef IGNPAR
  7002.     debug(F101,"ttvt hwparity IGNPAR","",IGNPAR);
  7003.     tttvt.c_iflag |= IGNPAR;    /* Don't discard incoming bytes */
  7004. #endif /* IGNPAR */
  7005.     tttvt.c_cflag |= PARENB;    /* Enable parity */
  7006.  
  7007.     switch (hwparity) {
  7008.       case 'e':            /* Even */
  7009.         tttvt.c_cflag &= ~(PARODD);
  7010.         debug(F100,"ttvt 8 bits + even parity","",0);
  7011.         break;
  7012.       case 'o':            /* Odd */
  7013.         tttvt.c_cflag |= PARODD;
  7014.         debug(F100,"ttvt 8 bits + odd parity","",0);
  7015.         break;
  7016.       case 'm':            /* Mark */
  7017.       case 's':            /* Space */
  7018.         /* PAREXT is mentioned in SVID but the details are not given. */
  7019.         /* PAREXT is not included in POSIX ISO/IEC 9945-1. */
  7020.         debug(F100,"ttvt 8 bits + invalid parity","",0);
  7021.         break;
  7022.     }
  7023.     } else {                /* We handle parity ourselves */
  7024. #endif /* HWPARITY */
  7025.     tttvt.c_cflag &= ~(PARENB);    /* Don't enable parity */
  7026. #ifdef HWPARITY
  7027.     }
  7028. #endif /* HWPARITY */
  7029.  
  7030. #ifdef ATTSV
  7031. #ifdef BSD44
  7032.     /* Things not to do... */
  7033.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|INPCK|ISTRIP|IXANY);
  7034. #else
  7035.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|IUCLC|INPCK|ISTRIP|IXANY);
  7036. #endif /* BSD44 */
  7037. #else /* POSIX */
  7038.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|INPCK|ISTRIP);
  7039. #endif /* ATTSV */
  7040.     tttvt.c_cflag &= ~(CSIZE);        /* Zero out the char size field */
  7041.     tttvt.c_cflag |= (CS8|CREAD|HUPCL);    /* Char size 8, enable receiver, hup */
  7042.     tttvt.c_oflag &= ~OPOST;        /* Don't postprocess output */
  7043. #ifndef VEOF /* DGUX termio has VEOF at entry 4, see comment above */
  7044.     tttvt.c_cc[4] = 1;
  7045. #else
  7046. #ifndef OXOS
  7047. #ifdef VMIN
  7048.     tttvt.c_cc[VMIN] = 1;
  7049. #endif /* VMIN */
  7050. #else /* OXOS */
  7051.     tttvt.c_min = 1;
  7052. #endif /* OXOS */
  7053. #endif /* VEOF */
  7054. #ifndef VEOL    /* DGUX termio has VEOL at entry 5, see comment above */
  7055.     tttvt.c_cc[5] = 0;
  7056. #else
  7057. #ifndef OXOS
  7058. #ifdef VTIME
  7059.     tttvt.c_cc[VTIME] = 0;
  7060. #endif /* VTIME */
  7061. #else /* OXOS */
  7062.     tttvt.c_time = 0;
  7063. #endif /* OXOS */
  7064. #endif /* VEOL */
  7065.  
  7066. #ifdef Plan9
  7067.     if (p9ttyparity('n') < 0)
  7068.       return -1;
  7069. #else
  7070. #ifdef BSD44ORPOSIX
  7071.     errno = 0;
  7072. #ifdef BEOSORBEBOX
  7073.     tttvt.c_cc[VMIN] = 0;        /* DR7 can only poll. */
  7074. #endif /* BEOSORBEBOX */
  7075.  
  7076.     x = tcsetattr(ttyfd,TCSADRAIN,&tttvt);
  7077.     debug(F101,"ttvt BSD44ORPOSIX tcsetattr","",x);
  7078.     if (x < 0) {
  7079.     debug(F101,"ttvt BSD44ORPOSIX tcsetattr errno","",errno);
  7080.     return(-1);
  7081.     }
  7082. #else /* ATTSV */
  7083.     x = ioctl(ttyfd,TCSETAW,&tttvt);
  7084.     debug(F101,"ttvt ATTSV ioctl TCSETAW","",x);
  7085.     if (x < 0) {            /* set new modes . */
  7086.     debug(F101,"ttvt ATTSV ioctl TCSETAW errno","",errno);
  7087.     return(-1);    
  7088.     }
  7089. #endif /* BSD44ORPOSIX */
  7090. #endif /* Plan9 */
  7091. #endif /* ATTSV */
  7092.  
  7093.     ttspeed = speed;            /* Done, remember how we were */
  7094.     ttflow = flow;            /* called, so we can decide how to */
  7095.     tvtflg = 1;                /* respond next time. */
  7096.     debug(F100,"ttvt ok","",0);
  7097.     return(0);
  7098.  
  7099. #ifdef COHERENT
  7100. #undef SVORPOSIX
  7101. #endif /* COHERENT */
  7102.  
  7103. #endif /* NOLOCAL */
  7104. }
  7105.  
  7106. #ifndef NOLOCAL
  7107.  
  7108. /* Serial speed department . . . */
  7109.  
  7110. /*
  7111.   SCO OSR5.0.x might or might not support high speeds.  Sometimes they are not
  7112.   defined in the header files but they are supported (e.g. when building with
  7113.   UDK compiler rather than /bin/cc), sometimes vice versa.  Even though 5.0.4
  7114.   was the first release that came with high serial speeds standard, releases
  7115.   back to 5.0.0 could use them if certain patches (or "supplements") were
  7116.   applied to the SIO driver.  Plus a lot of SCO installations run third-party
  7117.   drivers.
  7118. */
  7119. #ifdef CK_SCOV5
  7120. #ifndef B38400
  7121. #define    B38400    0000017
  7122. #endif /* B38400 */
  7123. #ifndef B57600
  7124. #define    B57600    0000021
  7125. #endif /* B57600 */
  7126. #ifndef B76800
  7127. #define    B76800    0000022
  7128. #endif /* B76800 */
  7129. #ifndef B115200
  7130. #define    B115200    0000023
  7131. #endif /* B115200 */
  7132. #ifndef B230400
  7133. #define    B230400    0000024
  7134. #endif /* B230400 */
  7135. #ifndef B460800
  7136. #define    B460800    0000025
  7137. #endif /* B460800 */
  7138. #ifndef B921600
  7139. #define    B921600    0000026
  7140. #endif /* B921600 */
  7141. #endif /* CK_SCOV5 */
  7142. /*
  7143.   Plan 9's native speed setting interface lets you set anything you like,
  7144.   but will fail if the hardware doesn't like it, so we allow all the common
  7145.   speeds.
  7146. */
  7147. #ifdef Plan9
  7148. #ifndef B50
  7149. #define B50 50
  7150. #endif /* B50 */
  7151. #ifndef B75
  7152. #define B75 75
  7153. #endif /* B75 */
  7154. #ifndef B110
  7155. #define B110 110
  7156. #endif /* B110 */
  7157. #ifndef B134
  7158. #define B134 134
  7159. #endif /* B134 */
  7160. #ifndef B200
  7161. #define B200 200
  7162. #endif /* B200 */
  7163. #ifndef B300
  7164. #define B300 300
  7165. #endif /* B300 */
  7166. #ifndef B1200
  7167. #define B1200 1200
  7168. #endif /* B1200 */
  7169. #ifndef B1800
  7170. #define B1800 1800
  7171. #endif /* B1800 */
  7172. #ifndef B2400
  7173. #define B2400 2400
  7174. #endif /* B2400 */
  7175. #ifndef B4800
  7176. #define B4800 4800
  7177. #endif /* B4800 */
  7178. #ifndef B9600
  7179. #define B9600 9600
  7180. #endif /* B9600 */
  7181. #ifndef B14400
  7182. #define B14400 14400
  7183. #endif /* B14400 */
  7184. #ifndef B19200
  7185. #define B19200 19200
  7186. #endif /* B19200 */
  7187. #ifndef B28800
  7188. #define B28800 28800
  7189. #endif /* B28800 */
  7190. #ifndef B38400
  7191. #define B38400 38400
  7192. #endif /* B38400 */
  7193. #ifndef B57600
  7194. #define B57600 57600
  7195. #endif /* B57600 */
  7196. #ifndef B76800
  7197. #define B76800 76800
  7198. #endif /* B76800 */
  7199. #ifndef B115200
  7200. #define B115200 115200
  7201. #endif /* B115200 */
  7202. #ifndef B230400
  7203. #define B230400 230400
  7204. #endif /* B230400 */
  7205. #ifndef B460800
  7206. #define B460800 460800
  7207. #endif /* B460800 */
  7208. #ifndef B921600
  7209. #define B921600 921600
  7210. #endif /* B921600 */
  7211. #endif /* Plan9 */
  7212.  
  7213. /*  T T S S P D  --  Checks and sets transmission rate.  */
  7214.  
  7215. /*  Call with speed in characters (not bits!) per second. */
  7216. /*  Returns -1 on failure, 0 if it did nothing, 1 if it changed the speed. */
  7217.  
  7218. #ifdef USETCSETSPEED
  7219. /*
  7220.   The tcsetspeed() / tcgetspeed() interface lets you pass any number at all
  7221.   to be used as a speed to be set, rather than forcing a choice from a
  7222.   predefined list.  It seems to be peculiar to UnixWare 7.
  7223.  
  7224.   These are the function codes to be passed to tc[gs]etspeed(),
  7225.   but for some reason they don't seem to be picked up from termios.h.
  7226. */
  7227. #ifndef TCS_ALL
  7228. #define TCS_ALL 0
  7229. #endif /* TCS_ALL */
  7230. #ifndef TCS_IN
  7231. #define TCS_IN 1
  7232. #endif /* TCS_IN */
  7233. #ifndef TCS_OUT
  7234. #define TCS_OUT 2
  7235. #endif /* TCS_OUT */
  7236. #endif /* USETCSETSPEED */
  7237.  
  7238. int
  7239. ttsspd(cps) int cps; {
  7240.     int x;
  7241. #ifdef POSIX
  7242. /* Watch out, speed_t should be unsigned, so don't compare with -1, etc... */
  7243.     speed_t
  7244. #else
  7245.     int
  7246. #endif /* POSIX */
  7247.       s, s2;
  7248.     int ok = 1;                /* Speed check result, assume ok */
  7249.  
  7250. #ifdef OLINUXHISPEED
  7251.     unsigned int spd_flags = 0;
  7252.     struct serial_struct serinfo;
  7253. #endif /* OLINUXHISPEED */
  7254.  
  7255.     debug(F101,"ttsspd cps","",cps);
  7256.     debug(F101,"ttsspd ttyfd","",ttyfd);
  7257.     debug(F101,"ttsspd xlocal","",xlocal);
  7258.  
  7259.     if (ttyfd < 0 || xlocal == 0)    /* Don't set speed on console */
  7260.       return(0);
  7261.  
  7262. #ifdef    NETCONN
  7263.     if (netconn) {
  7264. #ifdef TN_COMPORT
  7265.         if (istncomport())
  7266.       return(tnc_set_baud(cps * 10));
  7267.         else
  7268. #endif /* TN_COMPORT */
  7269.     return(0);
  7270.   }
  7271. #endif    /* NETCONN */
  7272. #ifdef NETCMD
  7273.     if (ttpipe) return(0);
  7274. #endif /* NETCMD */
  7275. #ifdef NETPTY
  7276.     if (ttpty) return(0);
  7277. #endif /* NETPTY */
  7278.  
  7279.     if (cps < 0) return(-1);
  7280.     s = s2 = 0;                /* NB: s and s2 might be unsigned */
  7281.  
  7282. #ifdef USETCSETSPEED
  7283.  
  7284.     s = cps * 10L;
  7285.  
  7286.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  7287.     debug(F101,"ttsspd tcgetattr","",x);
  7288.     if (x < 0)
  7289.       return(-1);
  7290.     debug(F101,"ttsspd TCSETSPEED speed","",s);
  7291.  
  7292.     errno = 0;
  7293.     if (s == 8880L) {            /* 75/1200 split speed requested */
  7294.     tcsetspeed(TCS_IN, &ttcur, 1200L);
  7295.     tcsetspeed(TCS_OUT, &ttcur, 75L);
  7296.     } else
  7297.       tcsetspeed(TCS_ALL, &ttcur, s);    /* Put new speed in structs */
  7298. #ifdef DEBUG
  7299.     if (errno & deblog) {
  7300.     debug(F101,"ttsspd TCSETSPEED errno","",errno);
  7301.     }
  7302. #endif /* DEBUG */
  7303.  
  7304. #ifdef COMMENT
  7305.     tcsetspeed(TCS_ALL, &ttraw, s);
  7306.     tcsetspeed(TCS_ALL, &tttvt, s);
  7307.     tcsetspeed(TCS_ALL, &ttold, s);
  7308. #else
  7309.     if (s == 8880L) {            /* 75/1200 split speed requested */
  7310.     tcsetspeed(TCS_IN, &ttraw, 1200L);
  7311.     tcsetspeed(TCS_OUT, &ttraw, 75L);
  7312.     tcsetspeed(TCS_IN, &tttvt, 1200L);
  7313.     tcsetspeed(TCS_OUT, &tttvt, 75L);
  7314.     tcsetspeed(TCS_IN, &ttold, 1200L);
  7315.     tcsetspeed(TCS_OUT, &ttold, 75L);
  7316.     } else {
  7317.     tcsetspeed(TCS_ALL, &ttraw, s);
  7318.     tcsetspeed(TCS_ALL, &tttvt, s);
  7319.     tcsetspeed(TCS_ALL, &ttold, s);
  7320.     }
  7321. #endif /* COMMENT */
  7322.  
  7323.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur); /* Set the speed */
  7324.     debug(F101,"ttsspd tcsetattr","",x);
  7325.     if (x < 0)
  7326.       return(-1);
  7327.  
  7328. #else  /* Not USETCSETSPEED */
  7329.  
  7330. #ifdef MINIX2        /* Hack alert */
  7331. #define MINIX        /* Use pre-2.0 speed selection for Minix 2.0 as well */
  7332. #endif /* MINIX2 */
  7333.  
  7334.     /* First check that the given speed is valid. */
  7335.  
  7336.     switch (cps) {
  7337. #ifndef MINIX
  7338.       case 0:   s = B0;    break;
  7339.       case 5:   s = B50;   break;
  7340.       case 7:   s = B75;   break;
  7341. #endif /* MINIX */
  7342.       case 11:  s = B110;  break;
  7343. #ifndef MINIX
  7344.       case 13:  s = B134;  break;
  7345.       case 15:  s = B150;  break;
  7346.       case 20:  s = B200;  break;
  7347. #endif /* MINIX */
  7348.       case 30:  s = B300;  break;
  7349. #ifndef MINIX
  7350.       case 60:  s = B600;  break;
  7351. #endif /* MINIX */
  7352.       case 120: s = B1200; break;
  7353. #ifndef MINIX
  7354.       case 180: s = B1800; break;
  7355. #endif /* MINIX */
  7356.       case 240: s = B2400; break;
  7357.       case 480: s = B4800; break;
  7358. #ifndef MINIX
  7359.       case 888: s = B75; s2 = B1200; break; /* 888 = 75/1200 split speed */
  7360. #endif /* MINIX */
  7361. #ifdef B7200
  7362.       case 720: s = B7200; break;
  7363. #endif /* B7200 */
  7364.       case 960: s = B9600; break;
  7365. #ifdef B14400
  7366.       case 1440: s = B14400; break;
  7367. #endif /* B14400 */
  7368. #ifdef B19200
  7369.       case 1920: s = B19200; break;
  7370. #else
  7371. #ifdef EXTA
  7372.       case 1920: s = EXTA; break;
  7373. #endif /* EXTA */
  7374. #endif /* B19200 */
  7375. #ifdef B28800
  7376.       case 2880: s = B28800; break;
  7377. #endif /* B28800 */
  7378. #ifdef B38400
  7379.       case 3840: s = B38400;
  7380. #ifdef OLINUXHISPEED
  7381.         spd_flags = ~ASYNC_SPD_MASK;    /* Nonzero, but zero flags */
  7382. #endif /* OLINUXHISPEED */
  7383.     break;
  7384. #else /* B38400 not defined... */
  7385. #ifdef EXTB
  7386.       case 3840: s = EXTB; break;
  7387. #endif /* EXTB */
  7388. #endif /* B38400 */
  7389.  
  7390. #ifdef HPUX
  7391. #ifdef _B57600
  7392.       case 5760: s = _B57600; break;
  7393. #endif /* _B57600 */
  7394. #ifdef _B115200
  7395.       case 11520: s = _B115200; break;
  7396. #endif /* _B115200 */
  7397. #else
  7398. #ifdef OLINUXHISPEED
  7399. /*
  7400.   This bit from <carlo@sg.tn.tudelft.nl>:
  7401.   "Only note to make is maybe this: When the ASYNC_SPD_CUST flags are set then
  7402.   setting the speed to 38400 will set the custom speed (and ttgspd returns
  7403.   38400), but speeds 57600 and 115200 won't work any more because I didn't
  7404.   want to mess up the speed flags when someone is doing sophisticated stuff
  7405.   like custom speeds..."
  7406. */
  7407.       case 5760: s = B38400; spd_flags = ASYNC_SPD_HI; break;
  7408.       case 11520: s = B38400; spd_flags = ASYNC_SPD_VHI; break;
  7409. #else
  7410. #ifdef B57600
  7411.       case 5760: s = B57600; break;
  7412. #endif /* B57600 */
  7413. #ifdef B76800
  7414.       case 7680: s = B76800; break;
  7415. #endif /* B76800 */
  7416. #ifdef B115200
  7417.       case 11520: s = B115200; break;
  7418. #endif /* B115200 */
  7419. #endif /* OLINUXHISPEED */
  7420. #ifdef B153600
  7421.       case 15360: s = B153600; break;
  7422. #endif /* B153600 */
  7423. #ifdef B230400
  7424.       case 23040: s = B230400; break;
  7425. #endif /* B230400 */
  7426. #ifdef B307200
  7427.       case 30720: s = B307200; break;
  7428. #endif /* B307200 */
  7429. #ifdef B460800
  7430.       case 46080: s = B460800; break;
  7431. #endif /* 460800 */
  7432. #ifdef B921600
  7433.       case 92160: s = B921600; break;
  7434. #endif /* B921600 */
  7435. #endif /* HPUX */
  7436.       default:
  7437.     ok = 0;                /* Good speed not found, so not ok */
  7438.     break;
  7439.     }
  7440.     debug(F101,"ttsspd ok","",ok);
  7441.     debug(F101,"ttsspd s","",s);
  7442.  
  7443.     if (!ok) {
  7444.     debug(F100,"ttsspd fails","",0);
  7445.     return(-1);
  7446.     } else {
  7447.     if (!s2) s2 = s;        /* Set input speed */
  7448. #ifdef Plan9
  7449.     if (p9ttsspd(cps) < 0)
  7450.       return(-1);
  7451. #else
  7452. #ifdef BSD44ORPOSIX
  7453.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  7454.     debug(F101,"ttsspd tcgetattr","",x);
  7455.     if (x < 0)
  7456.       return(-1);
  7457. #ifdef OLINUXHISPEED
  7458.     debug(F101,"ttsspd spd_flags","",spd_flags);
  7459.     if (spd_flags && spd_flags != ASYNC_SPD_CUST) {
  7460.         if (ioctl(ttyfd, TIOCGSERIAL, &serinfo) < 0) {
  7461.         debug(F100,"ttsspd: TIOCGSERIAL failed","",0);
  7462.         return(-1);
  7463.         } else debug(F100,"ttsspd: TIOCGSERIAL ok","",0);
  7464.         serinfo.flags &= ~ASYNC_SPD_MASK;
  7465.         serinfo.flags |= (spd_flags & ASYNC_SPD_MASK);
  7466.         if (ioctl(ttyfd, TIOCSSERIAL, &serinfo) < 0)
  7467.           return(-1);
  7468.     }
  7469. #endif /* OLINUXHISPEED */
  7470.     cfsetospeed(&ttcur,s);
  7471.     cfsetispeed(&ttcur,s2);
  7472.     cfsetospeed(&ttraw,s);
  7473.     cfsetispeed(&ttraw,s2);
  7474.     cfsetospeed(&tttvt,s);
  7475.     cfsetispeed(&tttvt,s2);
  7476.     cfsetospeed(&ttold,s);
  7477.     cfsetispeed(&ttold,s2);
  7478.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  7479.     debug(F101,"ttsspd tcsetattr","",x);
  7480.     if (x < 0) return(-1);
  7481. #else
  7482. #ifdef ATTSV
  7483.     if (cps == 888) return(-1);    /* No split speeds, sorry. */
  7484.     x = ioctl(ttyfd,TCGETA,&ttcur);
  7485.     debug(F101,"ttsspd TCGETA ioctl","",x);
  7486.     if (x < 0) return(-1);
  7487.     ttcur.c_cflag &= ~CBAUD;
  7488.     ttcur.c_cflag |= s;
  7489.     tttvt.c_cflag &= ~CBAUD;
  7490.     tttvt.c_cflag |= s;
  7491.     ttraw.c_cflag &= ~CBAUD;
  7492.     ttraw.c_cflag |= s;
  7493.     ttold.c_cflag &= ~CBAUD;
  7494.     ttold.c_cflag |= s;
  7495.     x = ioctl(ttyfd,TCSETAW,&ttcur);
  7496.     debug(F101,"ttsspd TCSETAW ioctl","",x);
  7497.     if (x < 0) return(-1);
  7498. #else
  7499. #ifdef BELLV10
  7500.     x = ioctl(ttyfd,TIOCGDEV,&tdcur);
  7501.     debug(F101,"ttsspd TIOCGDEV ioctl","",x);
  7502.     if (x < 0) return(-1);
  7503.     tdcur.ispeed = s2;
  7504.     tdcur.ospeed = s;
  7505.     errno = 0;
  7506.     ok = ioctl(ttyfd,TIOCSDEV,&tdcur);
  7507.     debug(F101,"ttsspd BELLV10 ioctl","",ok);
  7508.     if (ok < 0) {
  7509.         perror(ttnmsv);
  7510.         debug(F101,"ttsspd BELLV10 errno","",ok);
  7511.         return(-1);
  7512.     }
  7513. #else
  7514.     x = gtty(ttyfd,&ttcur);
  7515.     debug(F101,"ttsspd gtty","",x);
  7516.     if (x < 0) return(-1);
  7517.     ttcur.sg_ospeed = s; ttcur.sg_ispeed = s2;
  7518.     tttvt.sg_ospeed = s; tttvt.sg_ispeed = s2;
  7519.     ttraw.sg_ospeed = s; ttraw.sg_ispeed = s2;
  7520.     ttold.sg_ospeed = s; ttold.sg_ispeed = s2;
  7521.     x = stty(ttyfd,&ttcur);
  7522.     debug(F101,"ttsspd stty","",x);
  7523.     if (x < 0) return(-1);
  7524. #endif /* BELLV10 */
  7525. #endif /* ATTSV */
  7526. #endif /* BSD44ORPOSIX */
  7527. #endif /* Plan9 */
  7528.     }
  7529.     return(1);                /* Return 1 = success. */
  7530. #endif /* USETCSETSPEED */
  7531. }
  7532.  
  7533. #endif /* NOLOCAL */
  7534.  
  7535. /* C O N G S P D  -  Get speed of console terminal  */
  7536.  
  7537. long
  7538. congspd() {
  7539. /*
  7540.   This is a disgusting hack.  The right way to do this would be to pass an
  7541.   argument to ttgspd(), but then we'd need to change the Kermit API and
  7542.   all of the ck?tio.c modules.  (Currently used only for rlogin.)
  7543. */
  7544.     int t1;
  7545.     long spd;
  7546. #ifdef NETCONN
  7547.     int t2 = netconn;
  7548.     netconn = 0;
  7549. #endif /* NETCONN */
  7550.     t1 = ttyfd;
  7551.     ttyfd = -1;
  7552.     spd = ttgspd();
  7553.     debug(F101,"congspd","",spd);
  7554. #ifdef NETCONN
  7555.     netconn = t2;
  7556. #endif /* NETCONN */
  7557.     ttyfd = t1;
  7558.     return(spd);
  7559. }
  7560.  
  7561. /*  T T S P D L I S T  -- Get list of serial speeds allowed on this platform */
  7562.  
  7563. #define NSPDLIST 64
  7564. static long spdlist[NSPDLIST];
  7565. /*
  7566.   As written, this picks up the speeds known at compile time, and thus
  7567.   apply to the system where C-Kermit was built, rather than to the one where
  7568.   it is running.  Suggestions for improvement are always welcome.
  7569. */
  7570. long *
  7571. ttspdlist() {
  7572.     int i;
  7573.     for (i = 0; i < NSPDLIST; i++)    /* Initialize the list */
  7574.       spdlist[i] = -1L;
  7575.     i = 1;
  7576.  
  7577. #ifdef USETCSETSPEED            /* No way to find out what's legal */
  7578.     debug(F100,"ttspdlist USETCSETSPEED","",0);
  7579.     spdlist[i++] = 50L;
  7580. #ifndef UW7
  7581.     spdlist[i++] = 75L;
  7582. #endif /* UW7 */
  7583.     spdlist[i++] = 110L;
  7584. #ifndef UW7
  7585.     spdlist[i++] = 134L;
  7586. #endif /* UW7 */
  7587.     spdlist[i++] = 150L;
  7588.     spdlist[i++] = 200L;
  7589.     spdlist[i++] = 300L;
  7590.     spdlist[i++] = 600L;
  7591.     spdlist[i++] = 1200L;
  7592.     spdlist[i++] = 1800L;
  7593.     spdlist[i++] = 2400L;
  7594.     spdlist[i++] = 4800L;
  7595.     spdlist[i++] = 8880L;
  7596.     spdlist[i++] = 9600L;
  7597.     spdlist[i++] = 14400L;
  7598.     spdlist[i++] = 19200L;
  7599.     spdlist[i++] = 28800L;
  7600. #ifndef UW7
  7601.     spdlist[i++] = 33600L;
  7602. #endif /* UW7 */
  7603.     spdlist[i++] = 38400L;
  7604.     spdlist[i++] = 57600L;
  7605.     spdlist[i++] = 76800L;
  7606.     spdlist[i++] = 115200L;
  7607. #ifndef UW7
  7608.     spdlist[i++] = 153600L;
  7609.     spdlist[i++] = 230400L;
  7610.     spdlist[i++] = 307200L;
  7611.     spdlist[i++] = 460800L;
  7612.     spdlist[i++] = 921600L;
  7613. #endif /* UW7 */
  7614.  
  7615. #else  /* USETCSETSPEED */
  7616.  
  7617.     debug(F100,"ttspdlist no USETCSETSPEED","",0);
  7618.  
  7619. #ifdef B50
  7620.     debug(F101,"ttspdlist B50","",B50);
  7621.     spdlist[i++] = 50L;
  7622. #endif /* B50 */
  7623. #ifdef B75
  7624.     debug(F101,"ttspdlist B75","",B75);
  7625.     spdlist[i++] = 75L;
  7626. #endif /* B75 */
  7627. #ifdef B110
  7628.     debug(F101,"ttspdlist B110","",B110);
  7629.     spdlist[i++] = 110L;
  7630. #endif /* B110 */
  7631. #ifdef B134
  7632.     debug(F101,"ttspdlist B134","",B134);
  7633.     spdlist[i++] = 134L;
  7634. #endif /* B134 */
  7635. #ifdef B150
  7636.     debug(F101,"ttspdlist B150","",B150);
  7637.     spdlist[i++] = 150L;
  7638. #endif /* B150 */
  7639. #ifdef B200
  7640.     debug(F101,"ttspdlist B200","",B200);
  7641.     spdlist[i++] = 200L;
  7642. #endif /* B200 */
  7643. #ifdef B300
  7644.     debug(F101,"ttspdlist B300","",B300);
  7645.     spdlist[i++] = 300L;
  7646. #endif /* B300 */
  7647. #ifdef B600
  7648.     debug(F101,"ttspdlist B600","",B600);
  7649.     spdlist[i++] = 600L;
  7650. #endif /* B600 */
  7651. #ifdef B1200
  7652.     debug(F101,"ttspdlist B1200","",B1200);
  7653.     spdlist[i++] = 1200L;
  7654. #endif /* B1200 */
  7655. #ifdef B1800
  7656.     debug(F101,"ttspdlist B1800","",B1800);
  7657.     spdlist[i++] = 1800L;
  7658. #endif /* B1800 */
  7659. #ifdef B2400
  7660.     debug(F101,"ttspdlist B2400","",B2400);
  7661.     spdlist[i++] = 2400L;
  7662. #endif /* B2400 */
  7663. #ifdef B4800
  7664.     debug(F101,"ttspdlist B4800","",B4800);
  7665.     spdlist[i++] = 4800L;
  7666. #endif /* B4800 */
  7667. #ifdef B9600
  7668.     debug(F101,"ttspdlist B9600","",B9600);
  7669.     spdlist[i++] = 9600L;
  7670. #endif /* B9600 */
  7671. #ifdef B14400
  7672.     debug(F101,"ttspdlist B14400","",B14400);
  7673.     spdlist[i++] = 14400L;
  7674. #endif /* B14400 */
  7675. #ifdef B19200
  7676.     debug(F101,"ttspdlist B19200","",B19200);
  7677.     spdlist[i++] = 19200L;
  7678. #else
  7679. #ifdef EXTA
  7680.     debug(F101,"ttspdlist EXTA","",EXTA);
  7681.     spdlist[i++] = 19200L;
  7682. #endif /* EXTA */
  7683. #endif /* B19200 */
  7684. #ifdef B28800
  7685.     debug(F101,"ttspdlist B28800","",B28800);
  7686.     spdlist[i++] = 28800L;
  7687. #endif /* B28800 */
  7688. #ifdef B33600
  7689.     debug(F101,"ttspdlist B33600","",B33600);
  7690.     spdlist[i++] = 33600L;
  7691. #endif /* B33600 */
  7692. #ifdef B38400
  7693.     debug(F101,"ttspdlist B38400","",B38400);
  7694.     spdlist[i++] = 38400L;
  7695. #else
  7696. #ifdef EXTB
  7697.     debug(F101,"ttspdlist EXTB","",EXTB);
  7698.     spdlist[i++] = 38400L;
  7699. #endif /* EXTB */
  7700. #endif /* B38400 */
  7701. #ifdef _B57600
  7702.     debug(F101,"ttspdlist _B57600","",_B57600);
  7703.     spdlist[i++] = 57600L;
  7704. #else
  7705. #ifdef B57600
  7706.     debug(F101,"ttspdlist B57600","",B57600);
  7707.     spdlist[i++] = 57600L;
  7708. #endif /* B57600 */
  7709. #endif /* _B57600 */
  7710. #ifdef B76800
  7711.     debug(F101,"ttspdlist B76800","",B76800);
  7712.     spdlist[i++] = 76800L;
  7713. #endif /* B76800 */
  7714. #ifdef _B115200
  7715.     debug(F101,"ttspdlist _B115200","",_B115200);
  7716.     spdlist[i++] = 115200L;
  7717. #else
  7718. #ifdef B115200
  7719.     debug(F101,"ttspdlist B115200","",B115200);
  7720.     spdlist[i++] = 115200L;
  7721. #endif /* B115200 */
  7722. #endif /* _B115200 */
  7723. #ifdef B153600
  7724.     debug(F101,"ttspdlist B153600","",B153600);
  7725.     spdlist[i++] = 153600L;
  7726. #endif /* B153600 */
  7727. #ifdef B230400
  7728.     debug(F101,"ttspdlist B230400","",B230400);
  7729.     spdlist[i++] = 230400L;
  7730. #endif /* B230400 */
  7731. #ifdef B307200
  7732.     debug(F101,"ttspdlist B307200","",B307200);
  7733.     spdlist[i++] = 307200L;
  7734. #endif /* B307200 */
  7735. #ifdef B460800
  7736.     debug(F101,"ttspdlist B460800","",B460800);
  7737.     spdlist[i++] = 460800L;
  7738. #endif /* B460800 */
  7739. #ifdef B921600
  7740.     debug(F101,"ttspdlist B921600","",B921600);
  7741.     spdlist[i++] = 921600L;
  7742. #endif /* B921600 */
  7743. #endif /* USETCSETSPEED */
  7744.     spdlist[0] = i - 1;            /* Return count in 0th element */
  7745.     debug(F111,"ttspdlist spdlist","0",spdlist[0]);
  7746.     return((long *)spdlist);
  7747. }
  7748.  
  7749. /* T T G S P D  -  Get speed of currently selected tty line  */
  7750.  
  7751. /*
  7752.   Unreliable.  After SET LINE, it returns an actual speed, but not necessarily
  7753.   the real speed.  On some systems, it returns the line's nominal speed, from
  7754.   /etc/ttytab.  Even if you SET SPEED to something else, this function might
  7755.   not notice.
  7756. */
  7757. long
  7758. ttgspd() {                /* Get current serial device speed */
  7759. #ifdef NOLOCAL
  7760.     return(-1L);
  7761. #else
  7762. #ifdef POSIX
  7763.     speed_t                /* Should be unsigned */
  7764. #else
  7765.     int                    /* Isn't unsigned */
  7766. #endif /* POSIX */
  7767.       s;
  7768.     int x;
  7769.     long ss;
  7770. #ifdef OLINUXHISPEED
  7771.     unsigned int spd_flags = 0;
  7772.     struct serial_struct serinfo;
  7773. #endif /* OLINUXHISPEED */
  7774.  
  7775. #ifdef NETCONN
  7776.     if (netconn) {
  7777. #ifdef TN_COMPORT
  7778.     if (istncomport())
  7779.       return(tnc_get_baud());
  7780.     else
  7781. #endif /* TN_COMPORT */
  7782.       return(-1);            /* -1 if network connection */
  7783.     }
  7784. #endif /* NETCONN */
  7785. #ifdef NETCMD
  7786.     if (ttpipe) return(-1);
  7787. #endif /* NETCMD */
  7788. #ifdef NETPTY
  7789.     if (ttpty) return(-1);
  7790. #endif /* NETPTY */
  7791.  
  7792.     debug(F101,"ttgspd ttyfd","",ttyfd);
  7793.  
  7794. #ifdef USETCSETSPEED
  7795.  
  7796.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  7797.     debug(F101,"ttgspd tcgetattr","",x);
  7798.     if (x < 0)
  7799.       return(-1);
  7800.     errno = 0;
  7801.     s = tcgetspeed(TCS_ALL, &ttcur);
  7802.     debug(F101,"ttsspd TCGETSPEED speed","",s);
  7803.     if (s == 0) {
  7804.     long s1, s2;
  7805.     s1 = tcgetspeed(TCS_IN, &ttcur);
  7806.     s2 = tcgetspeed(TCS_OUT, &ttcur);
  7807.     if (s1 == 1200L && s2 == 75L)
  7808.       return(8880L);
  7809.     }
  7810. #ifdef DEBUG
  7811.     if (errno & deblog) {
  7812.     debug(F101,"ttsspd TCGETSPEED errno","",errno);
  7813.     }
  7814. #endif /* DEBUG */
  7815.     return(s);
  7816.  
  7817. #else  /* Not USETCSETSPEED */
  7818.  
  7819. #ifdef Plan9
  7820.     if (ttyfd < 0)
  7821.       ss = -1;
  7822.     else
  7823.       ss = ttylastspeed;
  7824. #else
  7825. #ifdef OLINUXHISPEED
  7826.     debug(F100,"ttgspd Linux OLINUXHISPEED","",0);
  7827. #endif /* OLINUXHISPEED */
  7828.  
  7829.     if (ttyfd < 0) {
  7830. #ifdef BSD44ORPOSIX
  7831.     s = cfgetospeed(&ccold);
  7832.     debug(F101,"ttgspd cfgetospeed 1 POSIX","",s);
  7833. #else
  7834. #ifdef ATTSV
  7835.     s = ccold.c_cflag & CBAUD;
  7836.     debug(F101,"ttgspd c_cflag CBAUD 1 ATTSV","",s);
  7837. #else
  7838.     s = ccold.sg_ospeed;        /* (obtained by congm()) */
  7839.     debug(F101,"ttgspd sg_ospeed 1","",s);
  7840. #endif /* ATTSV */
  7841. #endif /* BSD44POSIX */
  7842.  
  7843.     } else {
  7844. #ifdef BSD44ORPOSIX
  7845.     if (tcgetattr(ttyfd,&ttcur) < 0) return(-1);
  7846.     s = cfgetospeed(&ttcur);
  7847.     debug(F101,"ttgspd cfgetospeed 2 BSDORPOSIX","",s);
  7848. #ifdef OLINUXHISPEED
  7849.     if (ioctl(ttyfd,TIOCGSERIAL,&serinfo) > -1)
  7850.       spd_flags = serinfo.flags & ASYNC_SPD_MASK;
  7851.     debug(F101,"ttgspd spd_flags","",spd_flags);
  7852. #endif /* OLINUXHISPEED */
  7853. #else
  7854. #ifdef ATTSV
  7855.     x = ioctl(ttyfd,TCGETA,&ttcur);
  7856.     debug(F101,"ttgspd ioctl 2 ATTSV x","",x);
  7857.     debug(F101,"ttgspd ioctl 2 ATTSV errno","",errno);
  7858.     if (x < 0) return(-1);
  7859.     s = ttcur.c_cflag & CBAUD;
  7860.     debug(F101,"ttgspd ioctl 2 ATTSV speed","",s);
  7861. #else
  7862. #ifdef BELLV10
  7863.     x = ioctl(ttyfd,TIOCGDEV,&tdcur);
  7864.     debug(F101,"ttgspd ioctl 2 BELLV10 x","",x);
  7865.     if (x < 0) return(-1);
  7866.     s = tdcur.ospeed;
  7867.     debug(F101,"ttgspd ioctl 2 BELLV10 speed","",s);
  7868. #else
  7869.     x = gtty(ttyfd,&ttcur);
  7870.     debug(F101,"ttgspd gtty 2 x","",x);
  7871.     debug(F101,"ttgspd gtty 2 errno","",errno);
  7872.     if (x < 0) return(-1);
  7873.     s = ttcur.sg_ospeed;
  7874.     debug(F101,"ttgspd gtty 2 speed","",s);
  7875. #endif /* BELLV10 */
  7876. #endif /* ATTSV */
  7877. #endif /* BSD44ORPOSIX */
  7878.     }
  7879.     debug(F101,"ttgspd code","",s);
  7880. #ifdef OLINUXHISPEED
  7881.     debug(F101,"ttgspd spd_flags","",spd_flags);
  7882. #endif /* OLINUXHISPEED */
  7883.     switch (s) {
  7884. #ifdef B0
  7885.       case B0:    ss = 0L; break;
  7886. #endif /* B0 */
  7887.  
  7888. #ifndef MINIX
  7889. /*
  7890.  MINIX defines the Bxx symbols to be bps/100, so B50==B75, B110==B134==B150,
  7891.  etc, making for many "duplicate case in switch" errors, which are fatal.
  7892. */
  7893. #ifdef B50
  7894.       case B50:   ss = 50L; break;
  7895. #endif /* B50 */
  7896. #ifdef B75
  7897.       case B75:   ss = 75L; break;
  7898. #endif /* B75 */
  7899. #endif /* MINIX */
  7900.  
  7901. #ifdef B110
  7902.       case B110:  ss = 110L; break;
  7903. #endif /* B110 */
  7904.  
  7905. #ifndef MINIX
  7906. #ifdef B134
  7907.       case B134:  ss = 134L; break;
  7908. #endif /* B134 */
  7909. #ifdef B150
  7910.       case B150:  ss = 150L; break;
  7911. #endif /* B150 */
  7912. #endif /* MINIX */
  7913.  
  7914. #ifdef B200
  7915.       case B200:  ss = 200L; break;
  7916. #endif /* B200 */
  7917.  
  7918. #ifdef B300
  7919.       case B300:  ss = 300L; break;
  7920. #endif /* B300 */
  7921.  
  7922. #ifdef B600
  7923.       case B600:  ss = 600L; break;
  7924. #endif /* B600 */
  7925.  
  7926. #ifdef B1200
  7927.       case B1200: ss = 1200L; break;
  7928. #endif /* B1200 */
  7929.  
  7930. #ifdef B1800
  7931.       case B1800: ss = 1800L; break;
  7932. #endif /* B1800 */
  7933.  
  7934. #ifdef B2400
  7935.       case B2400: ss = 2400L; break;
  7936. #endif /* B2400 */
  7937.  
  7938. #ifdef B4800
  7939.       case B4800: ss = 4800L; break;
  7940. #endif /* B4800 */
  7941.  
  7942. #ifdef B7200
  7943.       case B7200: ss = 7200L; break;
  7944. #endif /* B7200 */
  7945.  
  7946. #ifdef B9600
  7947.       case B9600: ss = 9600L; break;
  7948. #endif /* B9600 */
  7949.  
  7950. #ifdef B19200
  7951.       case B19200: ss = 19200L; break;
  7952. #else
  7953. #ifdef EXTA
  7954.       case EXTA: ss = 19200L; break;
  7955. #endif /* EXTA */
  7956. #endif /* B19200 */
  7957.  
  7958. #ifdef MINIX2
  7959. /* End of hack to make MINIX2 use MINIX1 speed setting */
  7960. #undef MINIX
  7961. #endif /* MINIX2 */
  7962.  
  7963. #ifndef MINIX
  7964. #ifdef B38400
  7965.       case B38400:
  7966.         ss = 38400L;
  7967. #ifdef OLINUXHISPEED
  7968.         switch(spd_flags) {
  7969.           case ASYNC_SPD_HI:  ss =  57600L; break;
  7970.           case ASYNC_SPD_VHI: ss = 115200L; break;
  7971.     }
  7972. #endif /* OLINUXHISPEED */
  7973.         break;
  7974. #else
  7975. #ifdef EXTB
  7976.       case EXTB: ss = 38400L; break;
  7977. #endif /* EXTB */
  7978. #endif /* B38400 */
  7979. #endif /* MINIX */
  7980.  
  7981. #ifdef HPUX
  7982. #ifdef _B57600
  7983.       case _B57600: ss = 57600L; break;
  7984. #endif /* _B57600 */
  7985. #ifdef _B115200
  7986.       case _B115200: ss = 115200L; break;
  7987. #endif /* _B115200 */
  7988. #else
  7989. #ifdef B57600
  7990.       case B57600: ss = 57600L; break;
  7991. #endif /* B57600 */
  7992. #ifdef B76800
  7993.       case B76800: ss = 76800L; break;
  7994. #endif /* B76800 */
  7995. #ifdef B115200
  7996.       case B115200: ss = 115200L; break;
  7997. #endif /* B115200 */
  7998. #ifdef B153600
  7999.       case B153600: ss = 153600L; break;
  8000. #endif /* B153600 */
  8001. #ifdef B230400
  8002.       case B230400: ss = 230400L; break;
  8003. #endif /* B230400 */
  8004. #ifdef B307200
  8005.       case B307200: ss = 307200L; break;
  8006. #endif /* B307200 */
  8007. #ifdef B460800
  8008.       case B460800: ss = 460800L; break;
  8009. #endif /* B460800 */
  8010. #endif /* HPUX */
  8011. #ifdef B921600
  8012.       case 92160: ss = 921600L; break;
  8013. #endif /* B921600 */
  8014.       default:
  8015.     ss = -1; break;
  8016.     }
  8017. #endif /* Plan9 */
  8018.     debug(F101,"ttgspd speed","",ss);
  8019.     return(ss);
  8020.  
  8021. #endif /* USETCSETSPEED */
  8022. #endif /* NOLOCAL */
  8023. }
  8024. #ifdef MINIX2                /* Another hack alert */
  8025. #define MINIX
  8026. #endif /* MINIX2 */
  8027.  
  8028. /*
  8029.   FIONREAD data type...  This has been defined as "long" for many, many
  8030.   years, and it worked OK until 64-bit platforms appeared.  Thus we use
  8031.   int for 64-bit platforms, but keep long for the others.  If we changed
  8032.   the default PEEKTYPE to int, this would probably break 16-bit builds
  8033.   (note that sizeof(long) == sizeof(int) on most 32-bit platforms), many
  8034.   of which we have no way of testing any more.  Therefore, do not change
  8035.   the default definition of PEEKTYPE -- only add exceptions to it as needed.
  8036. */
  8037. #ifdef COHERENT
  8038. #ifdef FIONREAD
  8039. #undef FIONREAD
  8040. #endif /* FIONREAD */
  8041. /* #define FIONREAD TIOCQUERY */
  8042. /* #define PEEKTYPE int */
  8043. #else  /* Not COHERENT... */
  8044.  
  8045. #ifdef OSF32                /* Digital UNIX 3.2 or higher */
  8046. #define PEEKTYPE int
  8047. #else
  8048. #define PEEKTYPE long            /* Elsewhere (see notes above) */
  8049. #endif /* OSF32 */
  8050. #endif /* COHERENT */
  8051.  
  8052. /* ckumyr.c by Kristoffer Eriksson, ske@pkmab.se, 15 Mar 1990. */
  8053.  
  8054. #ifdef MYREAD
  8055.  
  8056. /* Private buffer for myread() and its companions.  Not for use by anything
  8057.  * else.  ttflui() is allowed to reset them to initial values.  ttchk() is
  8058.  * allowed to read my_count.
  8059.  *
  8060.  * my_item is an index into mybuf[].  Increment it *before* reading mybuf[].
  8061.  *
  8062.  * A global parity mask variable could be useful too.  We could use it to
  8063.  * let myread() strip the parity on its own, instead of stripping sign
  8064.  * bits as it does now.
  8065.  */
  8066. #ifdef BIGBUFOK
  8067. #define MYBUFLEN 32768
  8068. #else
  8069. #ifdef pdp11
  8070. #define MYBUFLEN 256
  8071. #else
  8072. #define MYBUFLEN 1024
  8073. #endif /* pdp11 */
  8074. #endif /* BIGBUFOK */
  8075.  
  8076. #ifdef ANYX25
  8077. #undef MYBUFLEN
  8078. #define MYBUFLEN 256
  8079. /*
  8080.   On X.25 connections, there is an extra control byte at the beginning.
  8081. */
  8082. static CHAR x25buf[MYBUFLEN+1];        /* Communication device input buffer */
  8083. static CHAR  *mybuf = x25buf+1;
  8084. #else
  8085. static CHAR mybuf[MYBUFLEN];
  8086. #endif /* ANYX25 */
  8087.  
  8088. static int my_count = 0;        /* Number of chars still in mybuf */
  8089. static int my_item = -1;        /* Last index read from mybuf[]   */
  8090.  
  8091. /*  T T P E E K  --  Peek into our internal communications input buffers. */
  8092.  
  8093. /*
  8094.   NOTE: This routine is peculiar to UNIX, and is used only by the
  8095.   select()-based CONNECT module, ckucns.c.  It need not be replicated in
  8096.   the ck?tio.c of other platforms.
  8097. */
  8098. int
  8099. ttpeek() {
  8100. #ifdef TTLEBUF
  8101.     int rc = 0;
  8102.     if (ttpush >= 0)
  8103.       rc++;
  8104.     rc += le_inbuf();
  8105.     if (rc > 0)
  8106.       return(rc);
  8107.     else
  8108. #endif /* TTLEBUF */
  8109.  
  8110. #ifdef MYREAD
  8111.     return(my_count);
  8112. #else
  8113.     return(0);
  8114. #endif /* MYREAD */
  8115. }
  8116.  
  8117. /* myread() -- Efficient read of one character from communications line.
  8118.  *
  8119.  * Uses a private buffer to minimize the number of expensive read() system
  8120.  * calls.  Essentially performs the equivalent of read() of 1 character, which
  8121.  * is then returned.  By reading all available input from the system buffers
  8122.  * to the private buffer in one chunk, and then working from this buffer, the
  8123.  * number of system calls is reduced in any case where more than one character
  8124.  * arrives during the processing of the previous chunk, for instance high
  8125.  * baud rates or network type connections where input arrives in packets.
  8126.  * If the time needed for a read() system call approaches the time for more
  8127.  * than one character to arrive, then this mechanism automatically compensates
  8128.  * for that by performing bigger read()s less frequently.  If the system load
  8129.  * is high, the same mechanism compensates for that too.
  8130.  *
  8131.  * myread() is a macro that returns the next character from the buffer.  If the
  8132.  * buffer is empty, mygetbuf() is called.  See mygetbuf() for possible error
  8133.  * returns.
  8134.  *
  8135.  * This should be efficient enough for any one-character-at-a-time loops.
  8136.  * For even better efficiency you might use memcpy()/bcopy() or such between
  8137.  * buffers (since they are often better optimized for copying), but it may not
  8138.  * be worth it if you have to take an extra pass over the buffer to strip
  8139.  * parity and check for CTRL-C anyway.
  8140.  *
  8141.  * Note that if you have been using myread() from another program module, you
  8142.  * may have some trouble accessing this macro version and the private variables
  8143.  * it uses.  In that case, just add a function in this module, that invokes the
  8144.  * macro.
  8145.  */
  8146. #define myread() (--my_count < 0 ? mygetbuf() : 255 & (int)mybuf[++my_item])
  8147.  
  8148. /* Specification: Push back up to one character onto myread()'s queue.
  8149.  *
  8150.  * This implementation: Push back characters into mybuf. At least one character
  8151.  * must have been read through myread() before myunrd() may be used.  After
  8152.  * EOF or read error, again, myunrd() can not be used.  Sometimes more than
  8153.  * one character can be pushed back, but only one character is guaranteed.
  8154.  * Since a previous myread() must have read its character out of mybuf[],
  8155.  * that guarantees that there is space for at least one character.  If push
  8156.  * back was really needed after EOF, a small addition could provide that.
  8157.  *
  8158.  * myunrd() is currently not called from anywhere inside kermit...
  8159.  */
  8160. #ifdef COMMENT /* not used */
  8161. myunrd(ch) CHAR ch; {
  8162.     if (my_item >= 0) {
  8163.     mybuf[my_item--] = ch;
  8164.     ++my_count;
  8165.     }
  8166. }
  8167. #endif /* COMMENT */
  8168.  
  8169. /*  T T P U S H B A C K  --  Put n bytes back into the myread buffer */
  8170.  
  8171. static CHAR * pushbuf = NULL;
  8172. /* static int pushed = 0; */
  8173.  
  8174. int
  8175. ttpushback(s,n) CHAR * s; int n; {
  8176.     debug(F101,"ttpushback n","",n);
  8177.     if (pushbuf || n > MYBUFLEN || n < 1)
  8178.       return(-1);
  8179.     debug(F101,"ttpushback my_count","",my_count);
  8180.     if (my_count > 0) {
  8181.     if (!(pushbuf = (CHAR *)malloc(n+1)))
  8182.       return(-1);
  8183.     memcpy(pushbuf,mybuf,my_count);
  8184.     /* pushed = my_count; */ /* (set but never used) */
  8185.     }
  8186.     memcpy(mybuf,s,n);
  8187.     my_count = n;
  8188.     my_item = -1;
  8189.     return(0);
  8190. }
  8191.  
  8192. /* mygetbuf() -- Fill buffer for myread() and return first character.
  8193.  *
  8194.  * This function is what myread() uses when it can't get the next character
  8195.  * directly from its buffer.  First, it calls a system dependent myfillbuf()
  8196.  * to read at least one new character into the buffer, and then it returns
  8197.  * the first character just as myread() would have done.  This function also
  8198.  * is responsible for all error conditions that myread() can indicate.
  8199.  *
  8200.  * Returns: When OK    => a positive character, 0 or greater.
  8201.  *        When EOF    => -2.
  8202.  *        When error    => -3, error code in errno.
  8203.  *
  8204.  * Older myread()s additionally returned -1 to indicate that there was nothing
  8205.  * to read, upon which the caller would call myread() again until it got
  8206.  * something.  The new myread()/mygetbuf() always gets something.  If it
  8207.  * doesn't, then make it do so!  Any program that actually depends on the old
  8208.  * behaviour will break.
  8209.  *
  8210.  * The older version also used to return -2 both for EOF and other errors,
  8211.  * and used to set errno to 9999 on EOF.  The errno stuff is gone, EOF and
  8212.  * other errors now return different results, although Kermit currently never
  8213.  * checks to see which it was.  It just disconnects in both cases.
  8214.  *
  8215.  * Kermit lets the user use the quit key to perform some special commands
  8216.  * during file transfer.  This causes read(), and thus also mygetbuf(), to
  8217.  * finish without reading anything and return the EINTR error.  This should
  8218.  * be checked by the caller.  Mygetbuf() could retry the read() on EINTR,
  8219.  * but if there is nothing to read, this could delay Kermit's reaction to
  8220.  * the command, and make Kermit appear unresponsive.
  8221.  *
  8222.  * The debug() call should be removed for optimum performance.
  8223.  */
  8224. int
  8225. mygetbuf() {
  8226.     int x;
  8227.     errno = 0;
  8228. #ifdef DEBUG
  8229.     if (deblog && my_count > 0)
  8230.       debug(F101,"mygetbuf IMPROPERLY CALLED with my_count","",my_count);
  8231. #endif /* DEBUG */
  8232.     if (my_count <= 0)
  8233.       my_count = myfillbuf();
  8234.  
  8235. #ifdef DEBUG
  8236. #ifdef COMMENT
  8237.     if (deblog) debug(F101, "mygetbuf read", "", my_count);
  8238. #else /* COMMENT */
  8239.     if (deblog) hexdump("mygetbuf read", mybuf, my_count);
  8240. #endif /* COMMENT */
  8241. #endif /* DEBUG */
  8242.     x = my_count;
  8243.     if (my_count <= 0) {
  8244.     my_count = 0;
  8245.     my_item = -1;
  8246.     debug(F101,"mygetbuf errno","",errno);
  8247. #ifdef TCPSOCKET
  8248.     if (netconn && ttnet == NET_TCPB && errno != 0) {
  8249.         if (errno != EINTR) {
  8250.         debug(F101,"mygetbuf TCP error","",errno);
  8251.         ttclos(0);        /* Close the connection. */
  8252.         }
  8253.         return(-3);
  8254.     }
  8255. #endif /* TCPSOCKET */
  8256.     if (!netconn && xlocal && errno) {
  8257.         if (errno != EINTR) {
  8258.         debug(F101,"mygetbuf SERIAL error","",errno);
  8259.         x = -3;
  8260.         ttclos(0);        /* Close the connection. */
  8261.         }
  8262.     }
  8263.     return((x < 0) ? -3 : -2);
  8264.     }
  8265.     --my_count;
  8266.     return((unsigned)(0xff & mybuf[my_item = 0]));
  8267. }
  8268.  
  8269. /* myfillbuf():
  8270.  * System-dependent read() into mybuf[], as many characters as possible.
  8271.  *
  8272.  * Returns: OK => number of characters read, always more than zero.
  8273.  *          EOF => 0
  8274.  *          Error => -1, error code in errno.
  8275.  *
  8276.  * If there is input available in the system's buffers, all of it should be
  8277.  * read into mybuf[] and the function return immediately.  If no input is
  8278.  * available, it should wait for a character to arrive, and return with that
  8279.  * one in mybuf[] as soon as possible.  It may wait somewhat past the first
  8280.  * character, but be aware that any such delay lengthens the packet turnaround
  8281.  * time during kermit file transfers.  Should never return with zero characters
  8282.  * unless EOF or irrecoverable read error.
  8283.  *
  8284.  * Correct functioning depends on the correct tty parameters being used.
  8285.  * Better control of current parameters is required than may have been the
  8286.  * case in older Kermit releases.  For instance, O_NDELAY (or equivalent) can
  8287.  * no longer be sometimes off and sometimes on like it used to, unless a
  8288.  * special myfillbuf() is written to handle that.  Otherwise the ordinary
  8289.  * myfillbuf()s may think they have come to EOF.
  8290.  *
  8291.  * If your system has a facility to directly perform the functioning of
  8292.  * myfillbuf(), then use it.  If the system can tell you how many characters
  8293.  * are available in its buffers, then read that amount (but not less than 1).
  8294.  * If the system can return a special indication when you try to read without
  8295.  * anything to read, while allowing you to read all there is when there is
  8296.  * something, you may loop until there is something to read, but probably that
  8297.  * is not good for the system load.
  8298.  */
  8299.  
  8300. #ifdef SVORPOSIX
  8301.     /* This is for System III/V with VMIN>0, VTIME=0 and O_NDELAY off,
  8302.      * and CLOCAL set any way you like.  This way, read() will do exactly
  8303.      * what is required by myfillbuf(): If there is data in the buffers
  8304.      * of the O.S., all available data is read into mybuf, up to the size
  8305.      * of mybuf.  If there is none, the first character to arrive is
  8306.      * awaited and returned.
  8307.      */
  8308. int
  8309. myfillbuf() {
  8310.     int fd, n;
  8311. #ifdef NETCMD
  8312.     if (ttpipe)
  8313.       fd = fdin;
  8314.     else
  8315. #endif /* NETCMD */
  8316.       fd = ttyfd;
  8317.  
  8318. #ifdef sxaE50
  8319.     /* From S. Dezawa at Fujifilm in Japan.  I don't know why this is */
  8320.     /* necessary for the sxa E50, but it is. */
  8321.     return read(fd, mybuf, 255);
  8322. #else
  8323. #ifdef BEOSORBEBOX
  8324.     while (1) {
  8325. #ifdef NETCONN
  8326.         if (netconn) {
  8327.             n = netxin(sizeof(mybuf), (char *)mybuf);
  8328.             debug(F101,"BEBOX SVORPOSIX network myfillbuf","",n);
  8329.     }
  8330.         else
  8331. #endif /* NETCONN */
  8332.       n = read(fd, mybuf, sizeof(mybuf));
  8333.     debug(F101,"BEBOX SVORPOSIX notnet myfillbuf","",n);
  8334.         if (n > 0)
  8335.       return(n);
  8336.         snooze(1000.0);
  8337.     }
  8338. #else /* BEOSORBEBOX */
  8339.     errno = 0;
  8340.     debug(F100,"SVORPOSIX myfillbuf calling read()","",0);
  8341. #ifdef IBMX25
  8342.     if (netconn && (nettype == NET_IX25)) {
  8343.     /* can't use sizeof because mybuf is a pointer, and not an array! */
  8344.     n = x25xin( MYBUFLEN, mybuf );
  8345.     } else
  8346. #endif /* IBMX25 */
  8347.  
  8348. #ifdef CK_SSL
  8349.       if (ssl_active_flag || tls_active_flag) {
  8350.       int error, n = 0;
  8351.       while (n == 0) {
  8352.           if (ssl_active_flag)
  8353.                 n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  8354.           else if (tls_active_flag)
  8355.                 n = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  8356.               else
  8357.         break;
  8358.           switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  8359.         case SSL_ERROR_NONE:
  8360.           if (n > 0)
  8361.                     return(n);
  8362.           if (n < 0)
  8363.                     return(-2);
  8364.           msleep(50);
  8365.           break;
  8366.         case SSL_ERROR_WANT_WRITE:
  8367.         case SSL_ERROR_WANT_READ:
  8368.           return(-1);
  8369.         case SSL_ERROR_SYSCALL:
  8370.           if (n != 0)
  8371.             return(-1);
  8372.         case SSL_ERROR_WANT_X509_LOOKUP:
  8373.         case SSL_ERROR_SSL:
  8374.         case SSL_ERROR_ZERO_RETURN:
  8375.         default:
  8376.           ttclos(0);
  8377.           return(-3);
  8378.             }
  8379.         }
  8380.     }
  8381. #endif /* CK_SSL */
  8382. #ifdef CK_KERBEROS
  8383. #ifdef KRB4
  8384. #ifdef RLOGCODE
  8385.     if (ttnproto == NP_EK4LOGIN) {
  8386.         if ((n = krb4_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8387.       return(-3);
  8388.         else
  8389.       return(n);
  8390.     }
  8391. #endif /* RLOGCODE */
  8392. #endif /* KRB4 */
  8393. #ifdef KRB5
  8394. #ifdef RLOGCODE
  8395.     if (ttnproto == NP_EK5LOGIN) {
  8396.         if ((n = krb5_des_read(ttyfd,mybuf,sizeof(mybuf),0)) < 0)
  8397.       return(-3);
  8398.         else
  8399.       return(n);
  8400.     }
  8401. #endif /* RLOGCODE */
  8402. #ifdef KRB5_U2U
  8403.     if (ttnproto == NP_K5U2U) {
  8404.         if ((n = krb5_u2u_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8405.       return(-3);
  8406.         else
  8407.       return(n);
  8408.     }
  8409. #endif /* KRB5_U2U */
  8410. #endif /* KRB5 */
  8411. #endif /* CK_KERBEROS */
  8412.  
  8413. #ifdef NETPTY
  8414. #ifdef HAVE_PTYTRAP
  8415.     /* Special handling for HP-UX pty i/o */
  8416.   ptyread:
  8417.     if (ttpty && pty_trap_pending(ttyfd) > 0) {
  8418.         if (pty_trap_handler(ttyfd) > 0) {
  8419.             ttclos(0);
  8420.             return(-3);
  8421.         }
  8422.     }
  8423. #endif /* HAVE_PTYTRAP */
  8424. #endif /* NETPTY */
  8425.     n = read(fd, mybuf, sizeof(mybuf));
  8426.     debug(F101,"SVORPOSIX myfillbuf","",n);
  8427.     debug(F101,"SVORPOSIX myfillbuf ttcarr","",ttcarr);
  8428.     debug(F101,"SVORPOSIX myfillbuf errno","",errno);
  8429.     if (n < 1) {
  8430. #ifdef NETPTY
  8431. #ifdef HAVE_PTYTRAP
  8432.         /* When we have a PTY trap in place the connection cannot */
  8433.         /* be closed until the trap receives a close indication.  */
  8434.         if (n == 0 && ttpty)
  8435.             goto ptyread;
  8436. #endif /* HAVE_PTYTRAP */
  8437. #endif /* NETPTY */
  8438.         return(-3);
  8439.     }
  8440.     return(n);
  8441. #endif /* BEOSORBEBOX */
  8442. #endif /* sxaE50 */
  8443. }
  8444.  
  8445. #else /* not AT&T or POSIX */
  8446.  
  8447. #ifdef aegis
  8448.     /* This is quoted from the old myread().  The semantics seem to be
  8449.      * alright, but maybe errno would not need to be set even when
  8450.      * there is no error?  I don't know aegis.
  8451.      */
  8452. int
  8453. myfillbuf() {
  8454.     int count;
  8455. #ifdef NETCMD
  8456.     if (ttpipe)
  8457.       fd = fdin;
  8458.     else
  8459. #endif /* NETCMD */
  8460.       fd = ttyfd;
  8461.  
  8462.     count = ios_$get((short)fd, ios_$cond_opt, mybuf, 256L, st);
  8463.     errno = EIO;
  8464.     if (st.all == ios_$get_conditional_failed) /* get at least one */
  8465.       count = ios_$get((short)fd, 0, mybuf, 1L, st);
  8466.     if (st.all == ios_$end_of_file)
  8467.       return(-3);
  8468.     else if (st.all != status_$ok) {
  8469.     errno = EIO;
  8470.     return(-1);
  8471.     }
  8472.     return(count > 0 ? count : -3);
  8473. }
  8474. #else /* !aegis */
  8475.  
  8476. #ifdef FIONREAD
  8477.     /* This is for systems with FIONREAD.  FIONREAD returns the number
  8478.      * of characters available for reading. If none are available, wait
  8479.      * until something arrives, otherwise return all there is.
  8480.      */
  8481. int
  8482. myfillbuf() {
  8483.     PEEKTYPE avail = 0;
  8484.     int x, fd;
  8485. #ifdef NETCMD
  8486.     if (ttpipe)
  8487.       fd = fdin;
  8488.     else
  8489. #endif /* NETCMD */
  8490.       fd = ttyfd;
  8491.  
  8492. #ifdef SUNX25
  8493. /*
  8494.   SunLink X.25 support in this routine from Stefaan A. Eeckels, Eurostat (CEC).
  8495.   Depends on SunOS having FIONREAD, not because we use it, but just so this
  8496.   code is grouped correctly within the #ifdefs.  Let's hope Solaris keeps it.
  8497.  
  8498.   We call x25xin() instead of read() so that Q-Bit packets, which contain
  8499.   X.25 service-level information (e.g. PAD parameter changes), can be processed
  8500.   transparently to the upper-level code.  This is a blocking read, and so
  8501.   we depend on higher-level code (such as ttinc()) to set any necessary alarms.
  8502. */
  8503.     extern int nettype;
  8504.     if (netconn && nettype == NET_SX25) {
  8505.     while ((x = x25xin(sizeof(x25buf), x25buf)) < 1) ;
  8506.     return(x - 1);            /* "-1" compensates for extra status byte */
  8507.     }
  8508. #endif /* SUNX25 */
  8509.  
  8510. #ifdef CK_SSL
  8511.     if (ssl_active_flag || tls_active_flag) {
  8512.         int error, n = 0;
  8513.         while (n == 0) {
  8514.             if (ssl_active_flag)
  8515.           n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  8516.             else
  8517.           n = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  8518.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  8519.           case SSL_ERROR_NONE:
  8520.                 if (n > 0)
  8521.           return(n);
  8522.                 if (n < 0)
  8523.           return(-2);
  8524.                 msleep(50);
  8525.                 break;
  8526.           case SSL_ERROR_WANT_WRITE:
  8527.           case SSL_ERROR_WANT_READ:
  8528.                 return(-1);
  8529.           case SSL_ERROR_SYSCALL:
  8530.         if (n != 0)
  8531.           return(-1);
  8532.           case SSL_ERROR_WANT_X509_LOOKUP:
  8533.           case SSL_ERROR_SSL:
  8534.           case SSL_ERROR_ZERO_RETURN:
  8535.           default:
  8536.                 ttclos(0);
  8537.                 return(-2);
  8538.             }
  8539.         }
  8540.     }
  8541. #endif /* CK_SSL */
  8542. #ifdef CK_KERBEROS
  8543. #ifdef KRB4
  8544. #ifdef RLOGCODE
  8545.     if (ttnproto == NP_EK4LOGIN) {
  8546.         if ((x = krb4_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8547.       return(-1);
  8548.         else
  8549.       return(x);
  8550.     }
  8551. #endif /* RLOGCODE */
  8552. #endif /* KRB4 */
  8553. #ifdef KRB5
  8554. #ifdef RLOGCODE
  8555.     if (ttnproto == NP_EK5LOGIN) {
  8556.         if ((x = krb5_des_read(ttyfd,mybuf,sizeof(mybuf),0)) < 0)
  8557.       return(-1);
  8558.         else
  8559.       return(x);
  8560.     }
  8561. #endif /* RLOGCODE */
  8562. #ifdef KRB5_U2U
  8563.     if (ttnproto == NP_K5U2U) {
  8564.         if ((x = krb5_u2u_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8565.       return(-1);
  8566.         else
  8567.       return(x);
  8568.     }
  8569. #endif /* KRB5_U2U */
  8570. #endif /* KRB5 */
  8571. #endif /* CK_KERBEROS */
  8572.  
  8573.     errno = 0;
  8574.     debug(F101,"myfillbuf calling FIONREAD ioctl","",xlocal);
  8575.     x = ioctl(fd, FIONREAD, &avail);
  8576. #ifdef DEBUG
  8577.     if (deblog) {
  8578.     debug(F101,"myfillbuf FIONREAD","",x);
  8579.     debug(F101,"myfillbuf FIONREAD avail","",avail);
  8580.     debug(F101,"myfillbuf FIONREAD errno","",errno);
  8581.     }
  8582. #endif /* DEBUG */
  8583.     if (x < 0 || avail == 0)
  8584.       avail = 1;
  8585.  
  8586.     if (avail > MYBUFLEN)
  8587.       avail = MYBUFLEN;
  8588.  
  8589.     errno = 0;
  8590.  
  8591.     x = read(fd, mybuf, (int) avail);
  8592. #ifdef DEBUG
  8593.     if (deblog) {
  8594.     debug(F101,"myfillbuf avail","",avail);
  8595.     debug(F101,"myfillbuf read","",x);
  8596.     debug(F101,"myfillbuf read errno","",errno);
  8597.         if (x > 0)
  8598.       hexdump("myfillbuf mybuf",mybuf,x);
  8599.     }
  8600. #endif /* DEBUG */
  8601.     if (x < 1) x = -3;            /* read 0 == connection loss */
  8602.     return(x);
  8603. }
  8604.  
  8605. #else /* !FIONREAD */
  8606. /* Add other systems here, between #ifdef and #else, e.g. NETCONN. */
  8607. /* When there is no other possibility, read 1 character at a time. */
  8608. int
  8609. myfillbuf() {
  8610.     int x;
  8611.  
  8612. #ifdef CK_SSL
  8613.     if (ssl_active_flag || tls_active_flag) {
  8614.         int error, n = 0;
  8615.         while (n == 0) {
  8616.             if (ssl_active_flag)
  8617.           n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  8618.             else
  8619.           count = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  8620.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  8621.           case SSL_ERROR_NONE:
  8622.                 if (n > 0)
  8623.           return(n);
  8624.                 if (n < 0)
  8625.           return(-2);
  8626.                 msleep(50);
  8627.                 break;
  8628.           case SSL_ERROR_WANT_WRITE:
  8629.           case SSL_ERROR_WANT_READ:
  8630.                 return(-1);
  8631.           case SSL_ERROR_SYSCALL:
  8632.         if (n != 0)
  8633.           return(-1);
  8634.           case SSL_ERROR_WANT_X509_LOOKUP:
  8635.           case SSL_ERROR_SSL:
  8636.           case SSL_ERROR_ZERO_RETURN:
  8637.           default:
  8638.                 ttclos(0);
  8639.                 return(-2);
  8640.             }
  8641.         }
  8642.     }
  8643. #endif /* CK_SSL */
  8644. #ifdef CK_KERBEROS
  8645. #ifdef KRB4
  8646. #ifdef RLOGCODE
  8647.     if (ttnproto == NP_EK4LOGIN) {
  8648.         if ((len = krb4_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8649.       return(-1);
  8650.         else
  8651.       return(len);
  8652.     }
  8653. #endif /* RLOGCODE */
  8654. #endif /* KRB4 */
  8655. #ifdef KRB5
  8656. #ifdef RLOGCODE
  8657.     if (ttnproto == NP_EK5LOGIN) {
  8658.         if ((len = krb5_des_read(ttyfd,mybuf,sizeof(mybuf),0)) < 0)
  8659.       return(-1);
  8660.         else
  8661.       return(len);
  8662.     }
  8663. #endif /* RLOGCODE */
  8664. #ifdef KRB5_U2U
  8665.     if (ttnproto == NP_K5U2U) {
  8666.         if ((len = krb5_u2u_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8667.       return(-1);
  8668.         else
  8669.       return(len);
  8670.     }
  8671. #endif /* KRB5_U2U */
  8672. #endif /* KRB5 */
  8673. #endif /* CK_KERBEROS */
  8674.  
  8675. #ifdef NETCMD
  8676.     if (ttpipe)
  8677.       fd = fdin;
  8678.     else
  8679. #endif /* NETCMD */
  8680.       fd = ttyfd;
  8681.     x = read(fd, mybuf, 1);
  8682.     return(x > 0 ? x : -3);
  8683. }
  8684.  
  8685. #endif /* !FIONREAD */
  8686. #endif /* !aegis */
  8687. #endif /* !ATTSV */
  8688.  
  8689. #endif /* MYREAD */
  8690.  
  8691. #ifdef MINIX2
  8692. #undef MINIX
  8693. #endif /* MINIX2 */
  8694.  
  8695. /*  T T _ T N O P T  --  Handle Telnet negotions in incoming data */
  8696. /*
  8697.   Call with the IAC that was encountered.
  8698.   Returns:
  8699.    -3: If connection has dropped or gone bad.
  8700.    -2: On Telnet protocol error resulting in inconsistent states.
  8701.     0: If negotiation OK and caller has nothing to do.
  8702.     1: If packet start character has changed (new value is in global stchr).
  8703.   255: If there was a quoted IAC as data.
  8704.    or: Not at all if we got a legitimate Telnet Logout request.
  8705. */
  8706. #ifdef TCPSOCKET
  8707. static int
  8708. tt_tnopt(n) int n; {            /* Handle Telnet options */
  8709.     /* In case caller did not already check these conditions...  */
  8710.     if (n == IAC &&
  8711.     ((xlocal && netconn && IS_TELNET()) ||
  8712.      (!xlocal && sstelnet))) {
  8713.     extern int duplex;
  8714.     extern int server;
  8715.     int tx = 0;
  8716.     debug(F100,"ttinl calling tn_doop()","",0);
  8717.     tx = tn_doop((CHAR)(n & 0xff),duplex,ttinc);
  8718.     debug(F111,"ttinl tn_doop() returned","tx",tx);
  8719.     switch (tx) {
  8720.       case 0:
  8721.         return(0);
  8722.       case -1:            /* I/O error */
  8723.         ttimoff();            /* Turn off timer */
  8724.         return(-3);
  8725.           case -2:            /* Connection failed. */
  8726.           case -3:
  8727.         ttimoff();            /* Turn off timer */
  8728.         ttclos(0);
  8729.         return(-3);
  8730.       case 1:            /* ECHO change */
  8731.         duplex = 1;
  8732.         return(0);
  8733.       case 2:            /* ECHO change */
  8734.         duplex = 0;
  8735.         return(0);
  8736.       case 3:            /* Quoted IAC */
  8737.         n = 255;
  8738.         return((unsigned)255);
  8739. #ifdef IKS_OPTION
  8740.       case 4: {
  8741.           if (TELOPT_SB(TELOPT_KERMIT).kermit.u_start && server
  8742. #ifdef IKSD
  8743.           && !inserver
  8744. #endif /* IKSD */
  8745.           ) {            /* Remote in Server mode */
  8746.           ttimoff();        /* Turn off timer */
  8747.           debug(F100,"u_start and !inserver","",0);
  8748.           return(-2);        /* End server mode */
  8749.           } else if (!TELOPT_SB(TELOPT_KERMIT).kermit.me_start &&
  8750.              server
  8751.              ) {        /* I'm no longer in Server Mode */
  8752.           debug(F100,"me_start and server","",0);
  8753.           ttimoff();
  8754.           return(-2);
  8755.           }
  8756.           return(0);
  8757.       }
  8758.       case 5: {            /* Start character change */
  8759.           /* extern CHAR stchr; */
  8760.           /* start = stchr; */
  8761.           return(1);
  8762.       }
  8763. #endif /* IKS_OPTION */
  8764.       case 6:            /* Remote Logout */
  8765.         ttimoff();
  8766.         ttclos(0);
  8767. #ifdef IKSD
  8768.         if (inserver && !local)
  8769.           doexit(GOOD_EXIT,0);
  8770.         else
  8771. #endif /* IKSD */
  8772.           return(-2);
  8773.       default:
  8774.         return(0);
  8775.     }
  8776.     } else
  8777.       return(0);
  8778. }
  8779. #endif /* TCPSOCKET */
  8780.  
  8781. /*  T T F L U I  --  Flush tty input buffer */
  8782.  
  8783. void
  8784. ttflux() {                /* But first... */
  8785. #ifdef MYREAD
  8786. /*
  8787.   Flush internal MYREAD buffer.
  8788. */
  8789. #ifdef TCPSOCKET
  8790.     int dotnopts, x;
  8791.     dotnopts = (((xlocal && netconn && IS_TELNET()) ||
  8792.          (!xlocal && sstelnet)));
  8793. #endif /* TCPSOCKET */
  8794.     debug(F101,"ttflux my_count","",my_count);
  8795. #ifdef TCPSOCKET
  8796.     if (dotnopts) {
  8797.     CHAR ch = '\0';
  8798.         while (my_count > 0) {
  8799.         ch = myread();
  8800. #ifdef CK_ENCRYPTION
  8801.             if (TELOPT_U(TELOPT_ENCRYPTION))
  8802.           ck_tn_decrypt(&ch,1);
  8803. #endif /* CK_ENCRYPTION */
  8804.             if (ch == IAC)
  8805.           x = tt_tnopt(ch);
  8806.         }
  8807.     } else
  8808. #endif /* TCPSOCKET */
  8809. #ifdef COMMENT
  8810. #ifdef CK_ENCRYPTION
  8811.     if (TELOPT_U(TELOPT_ENCRYPTION) && my_count > 0)
  8812.       ck_tn_decrypt(&mybuf[my_item+1],my_count);
  8813. #endif /* CK_ENCRYPTION */
  8814. #endif /* COMMENT */
  8815.     my_count = 0;            /* Reset count to zero */
  8816.     my_item = -1;            /* And buffer index to -1 */
  8817. #endif /* MYREAD */
  8818. }
  8819.  
  8820. int
  8821. ttflui() {
  8822.     int n, fd;
  8823. #ifdef TCPSOCKET
  8824.     int dotnopts;
  8825.     dotnopts = (((xlocal && netconn && IS_TELNET()) ||
  8826.          (!xlocal && sstelnet)));
  8827. #endif /* TCPSOCKET */
  8828.  
  8829. #ifdef NETCMD
  8830.     if (ttpipe)
  8831.       fd = fdin;
  8832.     else
  8833. #endif /* NETCMD */
  8834.       fd = ttyfd;
  8835.  
  8836. #ifdef TTLEBUF
  8837.     ttpush = -1;            /* Clear the peek-ahead char */
  8838.     while (le_data && (le_inbuf() > 0)) {
  8839.         CHAR ch = '\0';
  8840.         if (le_getchar(&ch) > 0) {    /* Clear any more... */
  8841.             debug(F101,"ttflui le_inbuf ch","",ch);
  8842.         }
  8843.     }
  8844. #endif /* TTLEBUF */
  8845.     debug(F101,"ttflui ttpipe","",ttpipe);
  8846.  
  8847. #ifdef MYREAD
  8848. /*
  8849.   Flush internal MYREAD buffer *NEXT*, in all cases.
  8850. */
  8851.     ttflux();
  8852. #endif /* MYREAD */
  8853.  
  8854. #ifdef NETCONN
  8855. /* Network flush is done specially, in the network support module. */
  8856.     if ((netconn || sstelnet) && !ttpipe && !ttpty) {
  8857.     debug(F100,"ttflui netflui","",0);
  8858. #ifdef COMMENT
  8859. #ifdef TN_COMPORT
  8860.     if (istncomport())
  8861.             tnc_send_purge_data(TNC_PURGE_RECEIVE);
  8862. #endif /* TN_COMPORT */
  8863. #endif /* COMMENT */
  8864.     return(netflui());
  8865.     }
  8866. #endif /* NETCONN */
  8867.  
  8868.     debug(F101,"ttflui ttyfd","",ttyfd); /* Not network */
  8869.     if (ttyfd < 0)
  8870.       return(-1);
  8871.  
  8872. #ifdef aegis
  8873.     sio_$control((short)yfd, sio_$flush_in, true, st);
  8874.     if (st.all != status_$ok) {
  8875.     fprintf(stderr, "flush failed: "); error_$print(st);
  8876.     } else {      /* sometimes the flush doesn't work */
  8877.         for (;;) {
  8878.         char buf[256];
  8879.             /* eat all the characters that shouldn't be available */
  8880.             ios_$get((short)fd, ios_$cond_opt, buf, 256L, st); /* (void) */
  8881.             if (st.all == ios_$get_conditional_failed) break;
  8882.             fprintf(stderr, "flush failed(2): "); error_$print(st);
  8883.         }
  8884.     }
  8885. #else
  8886. #ifdef BSD44                /* 4.4 BSD */
  8887.     n = FREAD;                          /* Specify read queue */
  8888.     debug(F100,"ttflui BSD44","",0);
  8889.     ioctl(fd,TIOCFLUSH,&n);
  8890. #else
  8891. #ifdef Plan9
  8892. #undef POSIX                /* Uh oh... */
  8893. #endif /* Plan9 */
  8894. #ifdef POSIX                /* POSIX */
  8895.     debug(F100,"ttflui POSIX","",0);
  8896.     tcflush(fd,TCIFLUSH);
  8897. #else
  8898. #ifdef ATTSV                /* System V */
  8899. #ifndef VXVE
  8900.     debug(F100,"ttflui ATTSV","",0);
  8901.     ioctl(fd,TCFLSH,0);
  8902. #endif /* VXVE */
  8903. #else                    /* Not BSD44, POSIX, or Sys V */
  8904. #ifdef TIOCFLUSH            /* Those with TIOCFLUSH defined */
  8905. #ifdef ANYBSD                /* Berkeley */
  8906.     n = FREAD;                          /* Specify read queue */
  8907.     debug(F100,"ttflui TIOCFLUSH ANYBSD","",0);
  8908.     ioctl(fd,TIOCFLUSH,&n);
  8909. #else                    /* Others (V7, etc) */
  8910.     debug(F100,"ttflui TIOCFLUSH","",0);
  8911.     ioctl(fd,TIOCFLUSH,0);
  8912. #endif /* ANYBSD */
  8913. #else                    /* All others... */
  8914. /*
  8915.   No system call (that we know about) for input buffer flushing.
  8916.   So see how many there are and read them in a loop, using ttinc().
  8917.   ttinc() is buffered, so we're not getting charged with a system call
  8918.   per character, just a function call.
  8919. */
  8920.     if ((n = ttchk()) > 0) {
  8921.     debug(F101,"ttflui read loop","",n);
  8922.     while ((n--) && ttinc(0) > 0) ;
  8923.     }
  8924. #endif /* TIOCFLUSH */
  8925. #endif /* ATTSV */
  8926. #endif /* POSIX */
  8927. #ifdef Plan9
  8928. #define POSIX
  8929. #endif /* Plan9 */
  8930. #endif /* BSD44 */
  8931. #endif /* aegis */
  8932.     return(0);
  8933. }
  8934.  
  8935. int
  8936. ttfluo() {                /* Flush output buffer */
  8937.     int fd;
  8938. #ifdef NETCMD
  8939.     if (ttpipe)
  8940.       fd = fdout;
  8941.     else
  8942. #endif /* NETCMD */
  8943.       fd = ttyfd;
  8944.  
  8945. #ifdef Plan9
  8946.     return 0;
  8947. #else
  8948. #ifdef POSIX
  8949.     return(tcflush(fd,TCOFLUSH));
  8950. #else
  8951. #ifdef OXOS
  8952.     return(ioctl(fd,TCFLSH,1));
  8953. #else
  8954.     return(0);                /* All others, nothing */
  8955. #endif /* OXOS */
  8956. #endif /* POSIX */
  8957. #endif /* Plan9 */
  8958. }
  8959.  
  8960. /* Interrupt Functions */
  8961.  
  8962. /* Set up terminal interrupts on console terminal */
  8963.  
  8964. #ifndef FIONREAD            /* We don't need esctrp() */
  8965. #ifndef SELECT                /* if we have any of these... */
  8966. #ifndef CK_POLL
  8967. #ifndef RDCHK
  8968.  
  8969. #ifndef OXOS
  8970. #ifdef SVORPOSIX
  8971. SIGTYP
  8972. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  8973.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  8974.     conesc = 1;
  8975.     debug(F101,"esctrp caught SIGQUIT","",conesc);
  8976. }
  8977. #endif /* SVORPOSIX */
  8978. #endif /* OXOS */
  8979.  
  8980. #ifdef V7
  8981. #ifndef MINIX2
  8982. SIGTYP
  8983. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  8984.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  8985.     conesc = 1;
  8986.     debug(F101,"esctrp caught SIGQUIT","",conesc);
  8987. }
  8988. #endif /* MINIX2 */
  8989. #endif /* V7 */
  8990.  
  8991. #ifdef C70
  8992. SIGTYP
  8993. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  8994.     conesc = 1;
  8995.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  8996. }
  8997. #endif /* C70 */
  8998.  
  8999. #endif /* RDCHK */
  9000. #endif /* CK_POLL */
  9001. #endif /* SELECT */
  9002. #endif /* FIONREAD */
  9003.  
  9004. /*  C O N B G T  --  Background Test  */
  9005.  
  9006. static int jc = 0;            /* 0 = no job control */
  9007.  
  9008. /*
  9009.   Call with flag == 1 to prevent signal test, which can not be expected
  9010.   to work during file transfer, when SIGINT probably *is* set to SIG_IGN.
  9011.  
  9012.   Call with flag == 0 to use the signal test, but only if the process-group
  9013.   test fails, as it does on some UNIX systems, where getpgrp() is buggy,
  9014.   requires an argument when the man page says it doesn't, or vice versa.
  9015.  
  9016.   If flag == 0 and the process-group test fails, then we determine background
  9017.   status simply (but not necessarily reliably) from isatty().
  9018.  
  9019.   conbgt() sets the global backgrd = 1 if we appear to be in the background,
  9020.   and to 0 if we seem to be in the foreground.  conbgt() is highly prone to
  9021.   misbehavior.
  9022. */
  9023. VOID
  9024. conbgt(flag) int flag; {
  9025.     int x = -1,                /* process group or SIGINT test */
  9026.         y = 0;                /* isatty() test */
  9027. /*
  9028.   Check for background operation, even if not running on real tty, so that
  9029.   background flag can be set correctly.  If background status is detected,
  9030.   then Kermit will not issue its interactive prompt or most messages.
  9031.   If your prompt goes away, you can blame (and fix?) this function.
  9032. */
  9033.  
  9034. /* Use process-group test if possible. */
  9035.  
  9036. #ifdef POSIX                /* We can do it in POSIX */
  9037. #define PGROUP_T
  9038. #else
  9039. #ifdef BSD4                /* and in BSD 4.x. */
  9040. #define PGROUP_T
  9041. #else
  9042. #ifdef HPUXJOBCTL            /* and in most HP-UX's */
  9043. #define PGROUP_T
  9044. #else
  9045. #ifdef TIOCGPGRP            /* and anyplace that has this ioctl. */
  9046. #define PGROUP_T
  9047. #endif /* TIOCGPGRP */
  9048. #endif /* HPUXJOBCTL */
  9049. #endif /* BSD4 */
  9050. #endif /* POSIX */
  9051.  
  9052. #ifdef MIPS                /* Except if it doesn't work... */
  9053. #undef PGROUP_T
  9054. #endif /* MIPS */
  9055.  
  9056. #ifdef PGROUP_T
  9057. /*
  9058.   Semi-reliable process-group test.  Check whether this process's group is
  9059.   the same as the controlling terminal's process group.  This works if the
  9060.   getpgrp() call doesn't lie (as it does in the SUNOS System V environment).
  9061. */
  9062.     PID_T mypgrp = (PID_T)0;        /* Kermit's process group */
  9063.     PID_T ctpgrp = (PID_T)0;        /* The terminal's process group */
  9064. #ifndef _POSIX_SOURCE
  9065. /*
  9066.   The getpgrp() prototype is obtained from system header files for POSIX
  9067.   and Sys V R4 compilations.  Other systems, who knows.  Some complain about
  9068.   a duplicate declaration here, others don't, so it's safer to leave it in
  9069.   if we don't know for certain.
  9070. */
  9071. #ifndef SVR4
  9072. #ifndef PS2AIX10
  9073. #ifndef HPUX9
  9074.     extern PID_T getpgrp();
  9075. #endif /* HPUX9 */
  9076. #endif /* PS2AIX10 */
  9077. #endif /* SVR4 */
  9078. #endif /* _POSIX_SOURCE */
  9079.  
  9080. /* Get my process group. */
  9081.  
  9082. #ifdef SVR3 /* Maybe this should be ATTSV? */
  9083. /* This function is not described in SVID R2 */
  9084.     mypgrp = getpgrp();
  9085.     /* debug(F101,"ATTSV conbgt process group","",(int) mypgrp); */
  9086. #else
  9087. #ifdef POSIX
  9088.     mypgrp = getpgrp();
  9089.     /* debug(F101,"POSIX conbgt process group","",(int) mypgrp); */
  9090. #else
  9091. #ifdef OSFPC
  9092.     mypgrp = getpgrp();
  9093.     /* debug(F101,"OSF conbgt process group","",(int) mypgrp); */
  9094. #else
  9095. #ifdef QNX
  9096.     mypgrp = getpgrp();
  9097.     /* debug(F101,"QNX conbgt process group","",(int) mypgrp); */
  9098. #else
  9099. #ifdef OSF32                /* (was OSF40) */
  9100.     mypgrp = getpgrp();
  9101.     /* debug(F101,"Digital UNIX conbgt process group","",(int) mypgrp); */
  9102. #else /* BSD, V7, etc */
  9103. #ifdef MINIX2
  9104.     mypgrp = getpgrp();
  9105. #else
  9106.     mypgrp = getpgrp(0);
  9107. #endif /* MINIX2 */
  9108.     /* debug(F101,"BSD conbgt process group","",(int) mypgrp); */
  9109. #endif /* OSF32 */
  9110. #endif /* QNX */
  9111. #endif /* OSFPC */
  9112. #endif /* POSIX */
  9113. #endif /* SVR3 */
  9114.  
  9115. #ifdef MINIX2
  9116. #undef BSD44ORPOSIX
  9117. #endif /* MINIX2 */
  9118.  
  9119. /* Now get controlling tty's process group */
  9120. #ifdef BSD44ORPOSIX
  9121.     ctpgrp = tcgetpgrp(1);        /* The POSIX way */
  9122.     /* debug(F101,"POSIX conbgt terminal process group","",(int) ctpgrp); */
  9123. #else
  9124.     ioctl(1, TIOCGPGRP, &ctpgrp);    /* Or the BSD way */
  9125.    /* debug(F101,"non-POSIX conbgt terminal process group","",(int) ctpgrp); */
  9126. #endif /* BSD44ORPOSIX */
  9127.  
  9128. #ifdef MINIX2
  9129. #define BSD44ORPOSIX
  9130. #endif /* MINIX2 */
  9131.  
  9132.     if ((mypgrp > (PID_T) 0) && (ctpgrp > (PID_T) 0))
  9133.       x = (mypgrp == ctpgrp) ? 0 : 1;    /* If they differ, then background. */
  9134.     else x = -1;            /* If error, remember. */
  9135.     debug(F101,"conbgt process group test","",x);
  9136. #endif /* PGROUP_T */
  9137.  
  9138. /* Try to see if job control is available */
  9139.  
  9140. #ifdef NOJC                /* User override */
  9141.     jc = 0;                /* No job control allowed */
  9142.     debug(F111,"NOJC","jc",jc);
  9143. #else
  9144. #ifdef BSD44
  9145.     jc = 1;
  9146. #else
  9147. #ifdef SVR4ORPOSIX            /* POSIX actually tells us */
  9148.     debug(F100,"SVR4ORPOSIX jc test...","",0);
  9149. #ifdef _SC_JOB_CONTROL
  9150. #ifdef __bsdi__
  9151.     jc = 1;
  9152. #else
  9153. #ifdef __386BSD__
  9154.     jc = 1;
  9155. #else
  9156.     jc = sysconf(_SC_JOB_CONTROL);    /* Whatever system says */
  9157.     if (jc < 0) {
  9158.     debug(F101,"sysconf fails, jcshell","",jcshell);
  9159.     jc = (jchdlr == SIG_DFL) ? 1 : 0;
  9160.     } else
  9161.       debug(F111,"sysconf(_SC_JOB_CONTROL)","jc",jc);
  9162. #endif /* __386BSD__ */
  9163. #endif /* __bsdi__ */
  9164. #else
  9165. #ifdef _POSIX_JOB_CONTROL
  9166.     jc = 1;                /* By definition */
  9167.     debug(F111,"_POSIX_JOB_CONTROL is defined","jc",jc);
  9168. #else
  9169.     jc = 0;                /* Assume job control not allowed */
  9170.     debug(F111,"SVR4ORPOSIX _SC/POSIX_JOB_CONTROL not defined","jc",jc);
  9171. #endif /* _POSIX_JOB_CONTROL */
  9172. #endif /* _SC_JOB_CONTROL */
  9173. #else
  9174. #ifdef BSD4
  9175.     jc = 1;                /* Job control allowed */
  9176.     debug(F111,"BSD job control","jc",jc);
  9177. #else
  9178. #ifdef SVR3JC
  9179.     jc = 1;                /* JC allowed */
  9180.     debug(F111,"SVR3 job control","jc",jc);
  9181. #else
  9182. #ifdef OXOS
  9183.     jc = 1;                /* JC allowed */
  9184.     debug(F111,"X/OS job control","jc",jc);
  9185. #else
  9186. #ifdef HPUX9
  9187.     jc = 1;                /* JC allowed */
  9188.     debug(F111,"HP-UX 9.0 job control","jc",jc);
  9189. #else
  9190. #ifdef HPUX10
  9191.     jc = 1;                /* JC allowed */
  9192.     debug(F111,"HP-UX 10.0 job control","jc",jc);
  9193. #else
  9194.     jc = 0;                /* JC not allowed */
  9195.     debug(F111,"job control catch-all","jc",jc);
  9196. #endif /* HPUX10 */
  9197. #endif /* HPUX9 */
  9198. #endif /* OXOS */
  9199. #endif /* SVR3JC */
  9200. #endif /* BSD4 */
  9201. #endif /* SVR4ORPOSIX */
  9202. #endif /* BSD44 */
  9203. #endif /* NOJC */
  9204.     debug(F101,"conbgt jc","",jc);
  9205. #ifndef NOJC
  9206.     debug(F101,"conbgt jcshell","",jcshell);
  9207. /*
  9208.   At this point, if jc == 1 but jcshell == 0, it means that the OS supports
  9209.   job control, but the shell or other process we are running under does not
  9210.   (jcshell is set in sysinit()) and so if we suspend ourselves, nothing good
  9211.   will come of it.  So...
  9212. */
  9213.     if (jc < 0) jc = 0;
  9214.     if (jc > 0 && jcshell == 0) jc = 0;
  9215. #endif /* NOJC */
  9216.  
  9217. /*
  9218.   Another background test.
  9219.   Test if SIGINT (terminal interrupt) is set to SIG_IGN (ignore),
  9220.   which is done by the shell (sh) if the program is started with '&'.
  9221.   Unfortunately, this is NOT done by csh or ksh so watch out!
  9222.   Note, it's safe to set SIGINT to SIG_IGN here, because further down
  9223.   we always set it to something else.
  9224.   Note: as of 16 Jul 1999, we also skip this test if we set SIGINT to
  9225.   SIG_IGN ourselves.
  9226. */
  9227.     if (x < 0 && !flag && !sigint_ign) { /* Didn't get good results above... */
  9228.  
  9229.     SIGTYP (*osigint)();
  9230.  
  9231.     osigint = signal(SIGINT,SIG_IGN);    /* What is SIGINT set to? */
  9232.     sigint_ign = 1;
  9233.     x = (osigint == SIG_IGN) ? 1 : 0;    /* SIG_IGN? */
  9234.     debug(F101,"conbgt osigint","",osigint);
  9235.     debug(F101,"conbgt signal test","",x);
  9236.     }
  9237.  
  9238. /* Also check to see if we're running with redirected stdio. */
  9239. /* This is not really background operation, but we want to act as though */
  9240. /* it were. */
  9241.  
  9242. #ifdef IKSD
  9243.     if (inserver) {            /* Internet Kermit Server */
  9244.     backgrd = 0;            /* is not in the background */
  9245.     return;
  9246.     }
  9247. #endif /* IKSD */
  9248.  
  9249.     y = (isatty(0) && isatty(1)) ? 1 : 0;
  9250.     debug(F101,"conbgt isatty test","",y);
  9251.  
  9252. #ifdef BSD29
  9253. /* The process group and/or signal test doesn't work under these... */
  9254.     backgrd = !y;
  9255. #else
  9256. #ifdef sxaE50
  9257.     backgrd = !y;
  9258. #else
  9259. #ifdef MINIX
  9260.     backgrd = !y;
  9261. #else
  9262. #ifdef MINIX2
  9263.     backgrd = !y;
  9264. #else
  9265.     if (x > -1)
  9266.       backgrd = (x || !y) ? 1 : 0;
  9267.     else backgrd = !y;
  9268. #endif /* BSD29 */
  9269. #endif /* sxaE50 */
  9270. #endif /* MINIX */
  9271. #endif /* MINIX2 */
  9272.     debug(F101,"conbgt backgrd","",backgrd);
  9273. }
  9274.  
  9275. /*  C O N I N T  --  Console Interrupt setter  */
  9276.  
  9277. /*
  9278.   First arg is pointer to function to handle SIGTERM & SIGINT (like Ctrl-C).
  9279.   Second arg is pointer to function to handle SIGTSTP (suspend).
  9280. */
  9281.  
  9282. VOID                    /* Set terminal interrupt traps. */
  9283. #ifdef CK_ANSIC
  9284. #ifdef apollo
  9285. conint(f,s) SIGTYP (*f)(), (*s)();
  9286. #else
  9287. conint(SIGTYP (*f)(int), SIGTYP (*s)(int))
  9288. #endif /* apollo */
  9289. #else
  9290. conint(f,s) SIGTYP (*f)(), (*s)();
  9291. #endif /* CK_ANSIC */
  9292. /* conint */ {
  9293.  
  9294.     debug(F101,"conint conistate","",conistate);
  9295.  
  9296.     conbgt(0);                /* Do background test. */
  9297.  
  9298. /* Set the desired handlers for hangup and software termination. */
  9299.  
  9300. #ifdef SIGTERM
  9301.     signal(SIGTERM,f);                  /* Software termination */
  9302. #endif /* SIGTERM */
  9303.  
  9304. /*
  9305.   Prior to July 1999 we used to call sighup() here but now it's called in
  9306.   sysinit() so SIGHUP can be caught during execution of the init file or
  9307.   a kerbang script.
  9308. */
  9309.  
  9310. /* Now handle keyboard stop, quit, and interrupt signals. */
  9311. /* Check if invoked in background -- if so signals set to be ignored. */
  9312. /* However, if running under a job control shell, don't ignore them. */
  9313. /* We won't be getting any, as we aren't in the terminal's process group. */
  9314.  
  9315.     debug(F101,"conint backgrd","",backgrd);
  9316.     debug(F101,"conint jc","",jc);
  9317.  
  9318.     if (backgrd && !jc) {        /* In background, ignore signals */
  9319.     debug(F101,"conint background ignoring signals, jc","",jc);
  9320. #ifdef SIGTSTP
  9321.         signal(SIGTSTP,SIG_IGN);        /* Keyboard stop */
  9322. #endif /* SIGTSTP */
  9323.         signal(SIGQUIT,SIG_IGN);        /* Keyboard quit */
  9324.         signal(SIGINT,SIG_IGN);         /* Keyboard interrupt */
  9325.     sigint_ign = 1;
  9326.     conistate = CONI_NOI;
  9327.     } else {                /* Else in foreground or suspended */
  9328.     debug(F101,"conint foreground catching signals, jc","",jc);
  9329.         signal(SIGINT,f);               /* Catch terminal interrupt */
  9330.     sigint_ign = (f == SIG_IGN) ? 1 : 0;
  9331.  
  9332. #ifdef SIGTSTP                /* Keyboard stop (suspend) */
  9333.     /* debug(F101,"conint SIGSTSTP","",s); */
  9334.     if (s == NULL) s = SIG_DFL;
  9335. #ifdef NOJC                /* No job control allowed. */
  9336.     signal(SIGTSTP,SIG_IGN);
  9337. #else                    /* Job control allowed */
  9338.     if (jc)                /* if available. */
  9339.       signal(SIGTSTP,s);
  9340.     else
  9341.       signal(SIGTSTP,SIG_IGN);
  9342. #endif /* NOJC */
  9343. #endif /* SIGTSTP */
  9344.  
  9345. #ifndef OXOS
  9346. #ifdef SVORPOSIX
  9347. #ifndef FIONREAD            /* Watch out, we don't know this... */
  9348. #ifndef SELECT
  9349. #ifndef CK_POLL
  9350. #ifndef RDCHK
  9351.         signal(SIGQUIT,esctrp);         /* Quit signal, Sys III/V. */
  9352. #endif /* RDCHK */
  9353. #endif /* CK_POLL */
  9354. #endif /* SELECT */
  9355. #endif /* FIONREAD */
  9356.         if (conesc) conesc = 0;         /* Clear out pending escapes */
  9357. #else
  9358. #ifdef V7
  9359.         signal(SIGQUIT,esctrp);         /* V7 like Sys III/V */
  9360.         if (conesc) conesc = 0;
  9361. #else
  9362. #ifdef aegis
  9363.         signal(SIGQUIT,f);              /* Apollo, catch it like others. */
  9364. #else
  9365.         signal(SIGQUIT,SIG_IGN);        /* Others, ignore like 4D & earlier. */
  9366. #endif /* aegis */
  9367. #endif /* V7 */
  9368. #endif /* SVORPOSIX */
  9369. #endif /* OXOS */
  9370.     conistate = CONI_INT;
  9371.     }
  9372. }
  9373.  
  9374.  
  9375. /*  C O N N O I  --  Reset console terminal interrupts */
  9376.  
  9377. VOID
  9378. connoi() {                              /* Console-no-interrupts */
  9379.  
  9380.     debug(F101,"connoi conistate","",conistate);
  9381. #ifdef SIGTSTP
  9382.     signal(SIGTSTP,SIG_IGN);        /* Suspend */
  9383. #endif /* SIGTSTP */
  9384.     conint(SIG_IGN,SIG_IGN);        /* Interrupt */
  9385.     sigint_ign = 1;            /* Remember we did this ourselves */
  9386. #ifdef SIGQUIT
  9387.     signal(SIGQUIT,SIG_IGN);        /* Quit */
  9388. #endif /* SIGQUIT */
  9389. #ifdef SIGTERM
  9390.     signal(SIGTERM,SIG_IGN);        /* Term */
  9391. #endif /* SIGTERM */
  9392.     conistate = CONI_NOI;
  9393. }
  9394.  
  9395. /*  I N I T R A W Q  --  Set up to read /dev/kmem for character count.  */
  9396.  
  9397. #ifdef  V7
  9398. /*
  9399.  Used in Version 7 to simulate Berkeley's FIONREAD ioctl call.  This
  9400.  eliminates blocking on a read, because we can read /dev/kmem to get the
  9401.  number of characters available for raw input.  If your system can't
  9402.  or you won't let the world read /dev/kmem then you must figure out a
  9403.  different way to do the counting of characters available, or else replace
  9404.  this by a dummy function that always returns 0.
  9405. */
  9406. /*
  9407.  * Call this routine as: initrawq(tty)
  9408.  * where tty is the file descriptor of a terminal.  It will return
  9409.  * (as a char *) the kernel-mode memory address of the rawq character
  9410.  * count, which may then be read.  It has the side-effect of flushing
  9411.  * input on the terminal.
  9412.  */
  9413. /*
  9414.  * John Mackin, Physiology Dept., University of Sydney (Australia)
  9415.  * ...!decvax!mulga!physiol.su.oz!john
  9416.  *
  9417.  * Permission is hereby granted to do anything with this code, as
  9418.  * long as this comment is retained unmodified and no commercial
  9419.  * advantage is gained.
  9420.  */
  9421. #ifndef MINIX
  9422. #ifndef MINIX2
  9423. #ifndef COHERENT
  9424. #include <a.out.h>
  9425. #include <sys/proc.h>
  9426. #endif /* COHERENT */
  9427. #endif /* MINIX2 */
  9428. #endif /* MINIX */
  9429.  
  9430. #ifdef COHERENT
  9431. #include <l.out.h>
  9432. #include <sys/proc.h>
  9433. #endif /* COHERENT */
  9434.  
  9435. char *
  9436. initrawq(tty) int tty; {
  9437. #ifdef MINIX
  9438.     return(0);
  9439. #else
  9440. #ifdef MINIX2
  9441.     return(0);
  9442. #else
  9443. #ifdef UTS24
  9444.     return(0);
  9445. #else
  9446. #ifdef BSD29
  9447.     return(0);
  9448. #else
  9449.     long lseek();
  9450.     static struct nlist nl[] = {
  9451.         {PROCNAME},
  9452.         {NPROCNAME},
  9453.         {""}
  9454.     };
  9455.     static struct proc *pp;
  9456.     char *qaddr, *p, c;
  9457.     int m;
  9458.     PID_T pid, me;
  9459.     NPTYPE xproc;                       /* Its type is defined in makefile. */
  9460.     int catch();
  9461.  
  9462.     me = getpid();
  9463.     if ((m = open("/dev/kmem", 0)) < 0) err("kmem");
  9464.     nlist(BOOTNAME, nl);
  9465.     if (nl[0].n_type == 0) err("proc array");
  9466.  
  9467.     if (nl[1].n_type == 0) err("nproc");
  9468.  
  9469.     lseek(m, (long)(nl[1].n_value), 0);
  9470.     read (m, &xproc, sizeof(xproc));
  9471.     saval = signal(SIGALRM, catch);
  9472.     if ((pid = fork()) == 0) {
  9473.         while(1)
  9474.             read(tty, &c, 1);
  9475.     }
  9476.     alarm(2);
  9477.  
  9478.     if(setjmp(jjbuf) == 0) {
  9479.         while(1)
  9480.       read(tty, &c, 1);
  9481.     }
  9482.     signal(SIGALRM, SIG_DFL);
  9483.  
  9484. #ifdef DIRECT
  9485.     pp = (struct proc *) nl[0].n_value;
  9486. #else
  9487.     if (lseek(m, (long)(nl[0].n_value), 0) < 0L) err("seek");
  9488.     if (read(m, &pp, sizeof(pp)) != sizeof(pp))  err("no read of proc ptr");
  9489. #endif
  9490.     lseek(m, (long)(nl[1].n_value), 0);
  9491.     read(m, &xproc, sizeof(xproc));
  9492.  
  9493.     if (lseek(m, (long)pp, 0) < 0L) err("Can't seek to proc");
  9494.     if ((p = malloc(xproc * sizeof(struct proc))) == NULL) err("malloc");
  9495.     if (read(m,p,xproc * sizeof(struct proc)) != xproc*sizeof(struct proc))
  9496.         err("read proc table");
  9497.     for (pp = (struct proc *)p; xproc > 0; --xproc, ++pp) {
  9498.         if (pp -> p_pid == (short) pid) goto iout;
  9499.     }
  9500.     err("no such proc");
  9501.  
  9502. iout:
  9503.     close(m);
  9504.     qaddr = (char *)(pp -> p_wchan);
  9505.     free (p);
  9506.     kill(pid, SIGKILL);
  9507.     wait((WAIT_T *)0);
  9508.     return (qaddr);
  9509. #endif
  9510. #endif
  9511. #endif
  9512. #endif
  9513. }
  9514.  
  9515. /*  More V7-support functions...  */
  9516.  
  9517. static VOID
  9518. err(s) char *s; {
  9519.     char buf[200];
  9520.  
  9521.     ckmakmsg(buf,200,"fatal error in initrawq: ", s, NULL, NULL);
  9522.     perror(buf);
  9523.     doexit(1,-1);
  9524. }
  9525.  
  9526. static VOID
  9527. catch(foo) int foo; {
  9528.     longjmp(jjbuf, -1);
  9529. }
  9530.  
  9531.  
  9532. /*  G E N B R K  --  Simulate a modem break.  */
  9533.  
  9534. #ifdef MINIX
  9535. #define BSPEED B110
  9536. #else
  9537. #ifdef MINIX2
  9538. #define BSPEED B110
  9539. #else
  9540. #define BSPEED B150
  9541. #endif /* MINIX2 */
  9542. #endif /* MINIX */
  9543.  
  9544. #ifndef MINIX2
  9545. VOID
  9546. genbrk(fn,msec) int fn, msec; {
  9547.     struct sgttyb ttbuf;
  9548.     int ret, sospeed, x, y;
  9549.  
  9550.     ret = ioctl(fn, TIOCGETP, &ttbuf);
  9551.     sospeed = ttbuf.sg_ospeed;
  9552.     ttbuf.sg_ospeed = BSPEED;
  9553.     ret = ioctl(fn, TIOCSETP, &ttbuf);
  9554.     y = (int)strlen(brnuls);
  9555.     x = ( BSPEED * 100 ) / msec;
  9556.     if (x > y) x = y;
  9557.     ret = write(fn, brnuls, (( BSPEED * 100 ) / msec ));
  9558.     ttbuf.sg_ospeed = sospeed;
  9559.     ret = ioctl(fn, TIOCSETP, &ttbuf);
  9560.     ret = write(fn, "@", 1);
  9561.     return;
  9562. }
  9563. #endif /* MINIX2 */
  9564.  
  9565. #ifdef MINIX2
  9566. int
  9567. genbrk(fn,msec) int fn, msec; {
  9568.     struct termios ttbuf;
  9569.     int ret, x, y;
  9570.     speed_t sospeed;
  9571.  
  9572.     ret = tcgetattr(fn, &ttbuf);
  9573.     sospeed = ttbuf.c_ospeed;
  9574.     ttbuf.c_ospeed = BSPEED;
  9575.     ret = tcsetattr(fn,TCSADRAIN, &ttbuf);
  9576.     y = (int)strlen(brnuls);
  9577.     x = ( BSPEED * 100 ) / msec;
  9578.     if (x > y) x = y;
  9579.     ret = write(fn, brnuls, (( BSPEED * 100 ) / msec ));
  9580.     ttbuf.c_ospeed = sospeed;
  9581.     ret = tcsetattr(fn, TCSADRAIN, &ttbuf);
  9582.     ret = write(fn, "@", 1);
  9583.     return ret;
  9584. }
  9585. #endif /* MINIX2 */
  9586. #endif /* V7 */
  9587.  
  9588. /*
  9589.   I N C H K  --  Check if chars waiting to be read on given file descriptor.
  9590.  
  9591.   This routine is a merger of ttchk() and conchk().
  9592.   Call with:
  9593.     channel == 0 to check console.
  9594.     channel == 1 to check communications connection.
  9595.   and:
  9596.     fd = file descriptor.
  9597.   Returns:
  9598.    >= 0: number of characters waiting, 0 or greater,
  9599.      -1: on any kind of error,
  9600.      -2: if there is (definitely) no connection.
  9601.   Note: In UNIX we don't have to call nettchk() because a socket
  9602.   file descriptor works just like in serial i/o, ioctls and all.
  9603.   (But this will change if we add non-file-descriptor channels,
  9604.   such as IBM X.25 for AIX...)
  9605. */
  9606. static int
  9607. in_chk(channel, fd) int channel, fd; {
  9608.     int x, n = 0;            /* Workers, n = return value */
  9609.     extern int clsondisc;        /* Close on disconnect */
  9610. /*
  9611.   The first section checks to make sure we have a connection,
  9612.   but only if we're in local mode.
  9613. */
  9614. #ifdef DEBUG
  9615.     if (deblog) {
  9616.     debug(F111,"in_chk entry",ckitoa(fd),channel);
  9617.     debug(F101,"in_chk ttyfd","",ttyfd);
  9618.     debug(F101,"in_chk ttpty","",ttpty);
  9619.     }
  9620. #endif /* DEBUG */
  9621. /*
  9622.   But don't say connection is gone if we have any buffered-stuff.
  9623. */
  9624. #ifdef TTLEBUF
  9625.     debug(F101,"in_chk ttpush","",ttpush);
  9626.     if (channel == 1) {
  9627.     if (ttpush >= 0)
  9628.       n++;
  9629.     n += le_inbuf();
  9630.     if (n > 0)
  9631.       return(n);
  9632.     }
  9633. #endif /* TTLEBUF */
  9634.  
  9635. #ifdef NETPTY
  9636. #ifdef HAVE_PTYTRAP
  9637.     /* Special handling for HP-UX pty i/o */
  9638.     if (ttpty && pty_trap_pending(ttyfd) > 0) {
  9639.         if (pty_trap_handler(ttyfd) > 0) {
  9640.             ttclos(0);
  9641.             return(-2);
  9642.         }
  9643.     }
  9644. #endif /* HAVE_PTYTRAP */
  9645. #endif /* NETPTY */
  9646.  
  9647.     if (channel) {            /* Checking communications channel */
  9648.     if (ttyfd < 0) {        /* No connection */
  9649.       return(-2);            /* That's what this means */
  9650.     } else if (xlocal &&        /* In local mode */
  9651.            (!netconn        /* Serial connection or */
  9652. #ifdef TN_COMPORT
  9653.             || istncomport()    /* Telnet Com Port */
  9654. #endif /* TN_COMPORT */
  9655.            ) && ttcarr != CAR_OFF /* with CARRIER WATCH ON (or AUTO) */
  9656. #ifdef COMMENT
  9657. #ifdef MYREAD
  9658. /*
  9659.   Seems like this would be a good idea but it prevents C-Kermit from
  9660.   popping back to the prompt automatically when carrier drops.  However,
  9661.   commenting this out prevents us from seeing the NO CARRIER message.
  9662.   Needs more work...
  9663. */
  9664.            && my_count < 1    /* Nothing in our internal buffer */
  9665. #endif /* MYREAD */
  9666. #endif /* COMMENT */
  9667.            ) {
  9668.         int x;
  9669.         x = ttgmdm();        /* So get modem signals */
  9670.         debug(F101,"in_chk close-on-disconnect","",clsondisc);
  9671.         if (x > -1) {        /* Check for carrier */
  9672.         if (!(x & BM_DCD)) {    /* No carrier */
  9673.             debug(F101,"in_chk carrier lost","",x);
  9674.             if (clsondisc)    /* If "close-on-disconnect" */
  9675.               ttclos(0);    /* close device & release lock. */
  9676.             return(-2);        /* This means "disconnected" */
  9677.         }
  9678.         /* In case I/O to device after CD dropped always fails */
  9679.         /* as in Debian Linux 2.1 and Unixware 2.1... */
  9680.         } else {
  9681.             debug(F101,"in_chk ttgmdm I/O error","",errno);
  9682.             debug(F101,"in_chk ttgmdm gotsigs","",gotsigs);
  9683.             if (gotsigs) {        /* If we got signals before... */
  9684.             if (errno == 5 || errno == 6) { /* I/O error etc */
  9685.                 if (clsondisc)    /* like when modem hangs up */
  9686.               ttclos(0);
  9687.             return(-2);
  9688.             }
  9689.         }
  9690.         /* If we never got modem signals successfully on this */
  9691.         /* connection before, we can't conclude that THIS failure */
  9692.         /* means the connection was lost. */
  9693.         return(0);
  9694.         }
  9695.     }
  9696.     }
  9697.  
  9698. /* We seem to have a connection so now see if any bytes are waiting on it */
  9699.  
  9700. #ifdef CK_SSL
  9701.     if (ssl_active_flag || tls_active_flag) {
  9702.         n += SSL_pending(ssl_active_flag?ssl_con:tls_con);
  9703.         debug(F101,"in_chk SSL_pending","",n);
  9704.         if (n < 0) {
  9705.             ttclos(0);
  9706.             return(-1);
  9707.         } else if (n > 0) {
  9708.             return(n);
  9709.         }
  9710.     }
  9711. #endif /* CK_SSL */
  9712. #ifdef RLOGCODE
  9713. #ifdef CK_KERBEROS
  9714.     /* It is not safe to read any data when using encrypted Klogin */
  9715.     if (ttnproto == NP_EK4LOGIN || ttnproto == NP_EK5LOGIN) {
  9716. #ifdef KRB4
  9717.         if (ttnproto == NP_EK4LOGIN) {
  9718.             n += krb4_des_avail(ttyfd);
  9719.             debug(F101,"in_chk krb4_des_avail","",n);
  9720.         }
  9721. #endif /* KRB4 */
  9722. #ifdef KRB5
  9723.         if (ttnproto == NP_EK5LOGIN) {
  9724.             n += krb5_des_avail(ttyfd);
  9725.             debug(F101,"in_chk krb5_des_avail","",n);
  9726.         }
  9727. #ifdef KRB5_U2U
  9728.         if (ttnproto == NP_K5U2U) {
  9729.             n += krb5_u2u_avail(ttyfd);
  9730.             debug(F101,"in_chk krb5_des_avail","",n);
  9731.         }
  9732. #endif /* KRB5_U2U */
  9733. #endif /* KRB5 */
  9734.         if (n < 0)            /* Is this right? */
  9735.       return(-1);
  9736.         else
  9737.       return(n);
  9738.     }
  9739. #endif /* CK_KERBEROS */
  9740. #endif /* RLOGCODE */
  9741.  
  9742.     errno = 0;                /* Reset this so we log good info */
  9743. #ifdef FIONREAD
  9744.     x = ioctl(fd, FIONREAD, &n);    /* BSD and lots of others */
  9745. #ifdef DEBUG                /* (the more the better) */
  9746.     if (deblog) {
  9747.     debug(F101,"in_chk FIONREAD return code","",x);
  9748.     debug(F101,"in_chk FIONREAD count","",n);
  9749.     debug(F101,"in_chk FIONREAD errno","",errno);
  9750.     }
  9751. #endif /* DEBUG */
  9752. #else /* FIONREAD not defined */
  9753. /*
  9754.   Here, if (netconn && ttnet == NET_TCPB), we might try calling recvmsg()
  9755.   with flags MSG_PEEK|MSG_DONTWAIT on the socket (ttyfd), except this is not
  9756.   portable (MSG_DONTWAIT isn't defined in any of the <sys/socket.h> files
  9757.   that I looked at, but it is needed to prevent the call from blocking), and
  9758.   the msghdr struct differs from place to place, so we would need another
  9759.   avalanche of ifdefs.  Still, when FIONREAD is not available, this is the
  9760.   only other known method of asking the OS for the *number* of characters
  9761.   available for reading.
  9762. */
  9763. #ifdef V7                /* UNIX V7: look in kernel memory */
  9764. #ifdef MINIX
  9765.     n = 0;                /* But not in MINIX */
  9766. #else
  9767. #ifdef MINIX2
  9768.     n = 0;
  9769. #else
  9770.     lseek(kmem[TTY], (long) qaddr[TTY], 0); /* 7th Edition Unix */
  9771.     x = read(kmem[TTY], &n, sizeof(int));
  9772.     if (x != sizeof(int))
  9773.       n = 0;
  9774. #endif /* MINIX2 */
  9775. #endif /* MINIX */
  9776. #else /* Not V7 */
  9777. #ifdef PROVX1
  9778.     x = ioctl(fd, TIOCQCNT, &ttbuf);    /* DEC Pro/3xx Venix V.1 */
  9779.     n = ttbuf.sg_ispeed & 0377;        /* Circa 1984 */
  9780.     if (x < 0) n = 0;
  9781. #else
  9782. #ifdef MYREAD
  9783. /*
  9784.   Here we skip all the undependable and expensive calls below if we
  9785.   already have something in our internal buffer.  This tends to work quite
  9786.   nicely, so the only really bad case remaining is the one in which neither
  9787.   FIONREAD or MYREAD are defined, which is increasingly rare these days.
  9788. */
  9789.     if (channel != 0 && my_count > 0) {
  9790.     debug(F101,"in_chk buf my_count","",my_count);
  9791.     n = my_count;            /* n was 0 before we got here */
  9792.     return(n);
  9793.     }
  9794. #endif /* MYREAD */
  9795. /*
  9796.   rdchk(), select(), and poll() tell us *if* data is available to be read, but
  9797.   not how much, so these should be used only as a final resort.  Especially
  9798.   since these calls tend to add a lot overhead.
  9799. */
  9800. #ifdef RDCHK                /* This mostly SCO-specific */
  9801.     n = rdchk(fd);
  9802.     debug(F101,"in_chk rdchk","",n);
  9803. #else /* No RDCHK */
  9804. #ifdef SELECT
  9805. #ifdef Plan9
  9806.     /* Only allows select on the console ... don't ask */
  9807.     if (channel == 0)
  9808. #endif /* Plan9 */
  9809.       {
  9810.     fd_set rfds;            /* Read file descriptors */
  9811. #ifdef BELLV10
  9812.     FD_ZERO(rfds);            /* Initialize them */
  9813.     FD_SET(fd,rfds);        /* We want to look at this fd */
  9814. #else
  9815.     FD_ZERO(&rfds);            /* Initialize them */
  9816.     FD_SET(fd,&rfds);        /* We want to look at this fd */
  9817.     tv.tv_sec = tv.tv_usec = 0L;    /* A 0-valued timeval structure */
  9818. #endif /* BELLV10 */
  9819. #ifdef Plan9
  9820.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9821.     debug(F101,"in_chk Plan 9 select","",n);
  9822. #else
  9823. #ifdef BELLV10
  9824.     n = select( 128, rfds, (fd_set *)0, (fd_set *)0, 0 );
  9825.     debug(F101,"in_chk BELLV10 select","",n);
  9826. #else
  9827. #ifdef BSD44
  9828.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9829.     debug(F101,"in_chk BSD44 select","",n);
  9830. #else
  9831. #ifdef BSD43
  9832.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9833.     debug(F101,"in_chk BSD43 select","",n);
  9834. #else
  9835. #ifdef SOLARIS
  9836.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9837.     debug(F101,"in_chk SOLARIS select","",n);
  9838. #else
  9839. #ifdef QNX6
  9840.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9841.     debug(F101,"in_chk QNX6 select","",n);
  9842. #else
  9843. #ifdef QNX
  9844.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9845.     debug(F101,"in_chk QNX select","",n);
  9846. #else
  9847. #ifdef COHERENT
  9848.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9849.     debug(F101,"in_chk COHERENT select","",n);
  9850. #else
  9851. #ifdef SVR4
  9852.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9853.     debug(F101,"in_chk SVR4 select","",n);
  9854. #else
  9855. #ifdef __linux__
  9856.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9857.     debug(F101,"in_chk LINUX select","",n);
  9858. #ifdef OSF
  9859.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9860.     debug(F101,"in_chk OSF select","",n);
  9861. #else
  9862.     n = select( FD_SETSIZE, &rfds, (int *)0, (int *)0, &tv );
  9863.     debug(F101,"in_chk catchall select","",n);
  9864. #endif /* OSF */
  9865. #endif /* __linux__ */
  9866. #endif /* SVR4 */
  9867. #endif /* COHERENT */
  9868. #endif /* QNX */
  9869. #endif /* QNX6 */
  9870. #endif /* SOLARIS */
  9871. #endif /* BSD43 */
  9872. #endif /* BSD44 */
  9873. #endif /* BELLV10 */
  9874. #endif /* Plan9 */
  9875.     }
  9876. #else  /* Not SELECT */
  9877. #ifdef CK_POLL
  9878.     {
  9879.       struct pollfd pfd;
  9880.  
  9881.       pfd.fd = fd;
  9882.       pfd.events = POLLIN;
  9883.       pfd.revents = 0;
  9884.       n = poll(&pfd, 1, 0);
  9885.       debug(F101,"in_chk poll","",n);
  9886.       if ((n > 0) && (pfd.revents & POLLIN))
  9887.     n = 1;
  9888.     }
  9889. #endif /* CK_POLL */
  9890. #endif /* SELECT */
  9891. #endif /* RDCHK */
  9892. #endif /* PROVX1 */
  9893. #endif /* V7 */
  9894. #endif /* FIONREAD */
  9895.  
  9896. /* From here down, treat console and communication device differently... */
  9897.  
  9898.     if (channel == 0) {            /* Console */
  9899.  
  9900. #ifdef SVORPOSIX
  9901. #ifndef FIONREAD
  9902. #ifndef SELECT
  9903. #ifndef CK_POLL
  9904. #ifndef RDCHK
  9905. /*
  9906.   This is the hideous hack used in System V and POSIX systems that don't
  9907.   support FIONREAD, rdchk(), select(), poll(), etc, in which the user's
  9908.   CONNECT-mode escape character is attached to SIGQUIT.  Used, obviously,
  9909.   only on the console.
  9910. */
  9911.     if (conesc) {            /* Escape character typed == SIGQUIT */
  9912.         debug(F100,"in_chk conesc","",conesc);
  9913.         conesc = 0;
  9914.         signal(SIGQUIT,esctrp);    /* Restore signal */
  9915.         n += 1;
  9916.     }
  9917. #endif /* RDCHK */
  9918. #endif /* CK_POLL */
  9919. #endif /* SELECT */
  9920. #endif /* FIONREAD */
  9921. #endif /* SVORPOSIX */
  9922.  
  9923.     return(n);            /* Done with console */
  9924.     }
  9925.  
  9926.     if (channel != 0) {            /* Communications connection */
  9927.  
  9928. #ifdef MYREAD
  9929. #ifndef FIONREAD
  9930. /*
  9931.   select() or rdchk(), etc, has told us that something is waiting, but we
  9932.   don't know how much.  So we do a read to get it and then we know.  Note:
  9933.   This read is NOT nonblocking if nothing is there (because of VMIN=1), but
  9934.   it should be safe in this case since the OS tells us at least one byte is
  9935.   waiting to be read, and MYREAD reads return as much as is there without
  9936.   waiting for any more.  Controlled tests on Solaris and Unixware (with
  9937.   FIONREAD deliberately undefined) show this to be true.
  9938. */
  9939.     debug(F101,"in_chk read my_count","",my_count);
  9940.     debug(F101,"in_chk read n","",n);
  9941.     if (n > 0 && my_count == 0) {
  9942.         /* This also catches disconnects etc */
  9943.         /* Do what mygetbuf does except don't grab a character */
  9944.         my_count = myfillbuf();
  9945.         my_item = -1;        /* ^^^ */
  9946.         debug(F101,"in_chk myfillbuf my_count","",my_count);
  9947.         if (my_count < 0)
  9948.           return(-1);
  9949.         else
  9950.           n = 0;            /* NB: n is replaced by my_count */
  9951.     }
  9952. #endif /* FIONREAD */
  9953. /*
  9954.   Here we add whatever we think is unread to what is still in our
  9955.   our internal buffer.  Thus the importance of setting n to 0 just above.
  9956. */
  9957.     debug(F101,"in_chk my_count","",my_count);
  9958.     debug(F101,"in_chk n","",n);
  9959.     if (my_count > 0)
  9960.       n += my_count;
  9961. #endif /* MYREAD */
  9962.     }
  9963.     debug(F101,"in_chk result","",n);
  9964.  
  9965.     /* Errors here don't prove the connection has dropped so just say 0 */
  9966.  
  9967.     return(n < 0 ? 0 : n);
  9968. }
  9969.  
  9970.  
  9971. /*  T T C H K  --  Tell how many characters are waiting in tty input buffer  */
  9972.  
  9973. int
  9974. ttchk() {
  9975.     int fd;
  9976. #ifdef NETCMD
  9977.     if (ttpipe)
  9978.       fd = fdin;
  9979.     else
  9980. #endif /* NETCMD */
  9981.       fd = ttyfd;
  9982.     return(in_chk(1,fd));
  9983. }
  9984.  
  9985. /*  T T X I N  --  Get n characters from tty input buffer  */
  9986.  
  9987. /*  Returns number of characters actually gotten, or -1 on failure  */
  9988.  
  9989. /*  Intended for use only when it is known that n characters are actually */
  9990. /*  Available in the input buffer.  */
  9991.  
  9992. int
  9993. ttxin(n,buf) int n; CHAR *buf; {
  9994.     register int x = 0, c = -2;
  9995. #ifdef TTLEBUF
  9996.     register int i = 0;
  9997. #endif /* TTLEBUF */
  9998.     int fd;
  9999.  
  10000.     if (n < 1)                /* Nothing to do */
  10001.       return(0);
  10002.  
  10003. #ifdef TTLEBUF
  10004.     if (ttpush >= 0) {
  10005.         buf[0] = ttpush;        /* Put pushed char in buffer*/
  10006.         ttpush = -1;            /* Clear the push buffer */
  10007.         if (ttchk() > 0)
  10008.       return(ttxin(n-1, &buf[1]) + 1);
  10009.         else
  10010.       return(1);
  10011.     }
  10012.     if (le_data) {
  10013.         while (le_inbuf() > 0) {
  10014.         if (le_getchar(&buf[i])) {
  10015.                 i++;
  10016.                 n--;
  10017.             }
  10018.         }
  10019.         if (ttchk() > 0)
  10020.       return(ttxin(n,&buf[i])+i);
  10021.         else
  10022.       return(i);
  10023.     }
  10024. #endif /* TTLEBUF */
  10025.  
  10026. #ifdef NETCMD
  10027.     if (ttpipe)
  10028.       fd = fdin;
  10029.     else
  10030. #endif /* NETCMD */
  10031.       fd = ttyfd;
  10032.  
  10033. #ifdef SUNX25
  10034.     if (netconn && (ttnet == NET_SX25))    /* X.25 connection */
  10035.       return(x25xin(n,buf));
  10036. #endif /* SUNX25 */
  10037.  
  10038. #ifdef IBMX25
  10039.     /* riehm: possibly not needed. Test worked with normal reads and writes */
  10040.     if (netconn && (ttnet == NET_IX25))    { /* X.25 connection */
  10041.     x = x25xin(n,buf);
  10042.     if (x > 0) buf[x] = '\0';
  10043.     return(x);
  10044.     }
  10045. #endif /* IBMX25 */
  10046.  
  10047. #ifdef MYREAD
  10048.     debug(F101,"ttxin MYREAD","",n);
  10049.     while (x < n) {
  10050.     c = myread();
  10051.     if (c < 0) {
  10052.         debug(F101,"ttxin myread returns","",c);
  10053.         if (c == -3) x = -1;
  10054.         break;
  10055.         }
  10056.     buf[x++] = c & ttpmsk;
  10057. #ifdef RLOGCODE
  10058. #ifdef CK_KERBEROS
  10059.         /* It is impossible to know how many characters are waiting */
  10060.         /* to be read when you are using Encrypted Rlogin or SSL    */
  10061.         /* as the transport since the number of real data bytes     */
  10062.         /* can be greater or less than the number of bytes on the   */
  10063.         /* wire which is what ttchk() returns.                      */
  10064.         if (netconn && (ttnproto == NP_EK4LOGIN || ttnproto == NP_EK5LOGIN))
  10065.       if (ttchk() <= 0)
  10066.         break;
  10067. #endif /* CK_KERBEROS */
  10068. #endif /* RLOGCODE */
  10069. #ifdef CK_SSL
  10070.         if (ssl_active_flag || tls_active_flag)
  10071.       if (ttchk() <= 0)
  10072.         break;
  10073. #endif /* CK_SSL */
  10074.     }
  10075. #else
  10076.     debug(F101,"ttxin READ","",n);
  10077.     x = read(fd,buf,n);
  10078.     for (c = 0; c < n; c++)        /* Strip any parity */
  10079.       buf[c] &= ttpmsk;
  10080. #endif /* MYREAD */
  10081.  
  10082.     debug(F101,"ttxin x","",x);        /* Done */
  10083.     if (x > 0) buf[x] = '\0';
  10084.     if (x < 0) x = -1;
  10085.     return(x);
  10086. }
  10087.  
  10088. /*  T T O L  --  Write string s, length n, to communication device.  */
  10089. /*
  10090.   Returns:
  10091.    >= 0 on success, number of characters actually written.
  10092.    -1 on failure.
  10093. */
  10094. #ifdef CK_ENCRYPTION
  10095. CHAR * xpacket = NULL;
  10096. int nxpacket = 0;
  10097. #endif /* CK_ENCRYPTION */
  10098.  
  10099. #define TTOLMAXT 5
  10100. int
  10101. ttol(s,n) int n; CHAR *s; {
  10102.     int x, len, tries, fd;
  10103. #ifdef CKXXCHAR
  10104.     extern int dblflag;            /* For SET SEND DOUBLE-CHARACTER */
  10105.     extern short dblt[];
  10106.     CHAR *p = NULL, *p2, *s2, c;
  10107.     int n2 = 0;
  10108. #endif /* CKXXCHAR */
  10109.  
  10110.     if (ttyfd < 0)            /* Not open? */
  10111.       return(-3);
  10112. #ifdef DEBUG
  10113.     if (deblog) hexdump("ttol s",s,n);
  10114. #endif /* DEBUG */
  10115.  
  10116. #ifdef NETCMD
  10117.     if (ttpipe)
  10118.       fd = fdout;
  10119.     else
  10120. #endif /* NETCMD */
  10121.       fd = ttyfd;
  10122.  
  10123. #ifdef CKXXCHAR
  10124. /*  Double any characters that must be doubled.  */
  10125.     debug(F101,"ttol dblflag","",dblflag);
  10126.     if (dblflag) {
  10127.     p = (CHAR *) malloc(n + n + 1);
  10128.     if (p) {
  10129.         s2 = s;
  10130.         p2 = p;
  10131.         n2 = 0;
  10132.         while (*s2) {
  10133.         c = *s2++;
  10134.         *p2++ = c;
  10135.         n2++;
  10136.         if (dblt[(unsigned) c] & 2) {
  10137.             *p2++ = c;
  10138.             n2++;
  10139.         }
  10140.         }
  10141.         s = p;
  10142.         n = n2;
  10143.         s[n] = '\0';
  10144.     }
  10145. #ifdef DEBUG
  10146.         if (deblog) hexdump("ttol doubled s",s,n);
  10147. #endif /* DEBUG */
  10148.     }
  10149. #endif /* CKXXCHAR */
  10150.  
  10151.     tries = TTOLMAXT;            /* Allow up to this many tries */
  10152.     len = n;                /* Remember original length */
  10153.  
  10154. #ifdef CK_ENCRYPTION
  10155. /*
  10156.   This is to avoid encrypting a packet that is already encrypted, e.g.
  10157.   when we resend a packet directly out of the packet buffer, and also to
  10158.   avoid encrypting a constant (literal) string, which can cause a memory
  10159.   fault.
  10160. */
  10161.     if (TELOPT_ME(TELOPT_ENCRYPTION)) {
  10162.     int x;
  10163.     if (nxpacket < n) {
  10164.         if (xpacket) {
  10165.         free(xpacket);
  10166.         xpacket = NULL;
  10167.         nxpacket = 0;
  10168.         }
  10169.         x = n > 10240 ? n : 10240;
  10170.         xpacket = (CHAR *)malloc(x);
  10171.         if (!xpacket) {
  10172.         fprintf(stderr,"ttol malloc failure\n");
  10173.         return(-1);
  10174.         } else
  10175.           nxpacket = x;
  10176.     }
  10177.     memcpy((char *)xpacket,(char *)s,n);
  10178.     s = xpacket;
  10179.     ck_tn_encrypt((char *)s,n);
  10180.     }
  10181. #endif /* CK_ENCRYPTION */
  10182.  
  10183.     while (n > 0 &&
  10184.        (tries-- > 0
  10185. #ifdef CK_ENCRYPTION
  10186.         /* keep trying if we are encrypting */
  10187.         || TELOPT_ME(TELOPT_ENCRYPTION)
  10188. #endif /* CK_ENCRYPTION */
  10189.             )) {            /* Be persistent */
  10190.     debug(F101,"ttol try","",TTOLMAXT - tries);
  10191. #ifdef BEOSORBEBOX
  10192.         if (netconn && !ttpipe && !ttpty)
  10193.       x = nettol((char *)s,n);    /* Write string to device */
  10194.         else
  10195. #endif /* BEOSORBEBOX */
  10196. #ifdef IBMX25
  10197.       if (ttnet == NET_IX25)
  10198.         /*
  10199.          * this is a more controlled way of writing to X25
  10200.          * STREAMS, however write should also work!
  10201.          */
  10202.         x = x25write(ttyfd, s, n);
  10203.       else
  10204. #endif /* IBMX25 */
  10205. #ifdef CK_SSL
  10206.         if (ssl_active_flag || tls_active_flag) {
  10207.         int error;
  10208.         /* Write using SSL */
  10209.                 ssl_retry:
  10210.         if (ssl_active_flag)
  10211.                   x = SSL_write(ssl_con, s, n);
  10212.         else
  10213.                   x = SSL_write(tls_con, s, n);
  10214.         switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,x)) {
  10215.                 case SSL_ERROR_NONE:
  10216.                     if (x == n)
  10217.               return(len);
  10218.                     s += x;
  10219.                     n -= x;
  10220.                     goto ssl_retry;
  10221.           case SSL_ERROR_WANT_WRITE:
  10222.           case SSL_ERROR_WANT_READ:
  10223.             x = 0;
  10224.             break;
  10225.           case SSL_ERROR_SYSCALL:
  10226.                     if (x != 0)
  10227.               return(-1);
  10228.           case SSL_ERROR_WANT_X509_LOOKUP:
  10229.           case SSL_ERROR_SSL:
  10230.           case SSL_ERROR_ZERO_RETURN:
  10231.           default:
  10232.             ttclos(0);
  10233.             return(-3);
  10234.         }
  10235.         } else
  10236. #endif /* CK_SSL */
  10237. #ifdef CK_KERBEROS
  10238. #ifdef KRB4
  10239. #ifdef RLOGCODE
  10240.         if (ttnproto == NP_EK4LOGIN) {
  10241.         return(krb4_des_write(ttyfd,s,n));
  10242.         } else
  10243. #endif /* RLOGCODE */
  10244. #endif /* KRB4 */
  10245. #ifdef KRB5
  10246. #ifdef RLOGCODE
  10247.             if (ttnproto == NP_EK5LOGIN) {
  10248.                 return(krb5_des_write(ttyfd,s,n,0));
  10249.             } else
  10250. #endif /* RLOGCODE */
  10251. #ifdef KRB5_U2U
  10252.             if (ttnproto == NP_K5U2U) {
  10253.                 return(krb5_u2u_write(ttyfd,s,n));
  10254.             } else
  10255. #endif /* KRB5_U2U */
  10256. #endif /* KRB5 */
  10257. #endif /* CK_KERBEROS */
  10258.           x = write(fd,s,n);    /* Write string to device */
  10259.  
  10260.     if (x == n) {            /* Worked? */
  10261.         debug(F101,"ttol ok","",x);    /* OK */
  10262. #ifdef CKXXCHAR
  10263.         if (p) free(p);
  10264. #endif /* CKXXCHAR */
  10265.         return(len);        /* Done */
  10266.     } else if (x < 0) {        /* No, got error? */
  10267.         debug(F101,"ttol write error","",errno);
  10268. #ifdef EWOULDBLOCK
  10269.         if (errno == EWOULDBLOCK) {
  10270.         msleep(10);
  10271.         continue;
  10272.         } else
  10273. #endif /* EWOULDBLOCK */
  10274. #ifdef TCPSOCKET
  10275.         if (netconn && ttnet == NET_TCPB) {
  10276.         debug(F101,"ttol TCP error","",errno);
  10277.         ttclos(0);        /* Close the connection. */
  10278.         x = -3;
  10279.         }
  10280. #endif /* TCPSOCKET */
  10281. #ifdef CKXXCHAR
  10282.         if (p) free(p);
  10283. #endif /* CKXXCHAR */
  10284.         return(x);
  10285.     } else {            /* No error, so partial success */
  10286.         debug(F101,"ttol partial","",x); /* This never happens */
  10287.         s += x;            /* Point to part not written yet */
  10288.         n -= x;            /* Adjust length */
  10289.         if (x > 0) msleep(10);    /* Wait 10 msec */
  10290.     }                /* Go back and try again */
  10291.     }
  10292. #ifdef CKXXCHAR
  10293.     if (p) free(p);
  10294. #endif /* CKXXCHAR */
  10295.     return(n < 1 ? len : -1);        /* Return the results */
  10296. }
  10297.  
  10298. /*  T T O C  --  Output a character to the communication line  */
  10299.  
  10300. /*
  10301.  This function should only be used for interactive, character-mode operations,
  10302.  like terminal connection, script execution, dialer i/o, where the overhead
  10303.  of the signals and alarms does not create a bottleneck.
  10304. */
  10305. int
  10306. #ifdef CK_ANSIC
  10307. ttoc(char c)
  10308. #else
  10309. ttoc(c) char c;
  10310. #endif /* CK_ANSIC */
  10311. /* ttoc */ {
  10312. #define TTOC_TMO 15            /* Timeout in case we get stuck */
  10313.     int xx, fd;
  10314.  
  10315.     if (ttyfd < 0)            /* Check for not open. */
  10316.       return(-1);
  10317.  
  10318. #ifdef NETCMD
  10319.     if (ttpipe)
  10320.       fd = fdout;
  10321.     else
  10322. #endif /* NETCMD */
  10323.       fd = ttyfd;
  10324.  
  10325.     c &= 0xff;
  10326.     /* debug(F101,"ttoc","",(CHAR) c); */
  10327.     saval = signal(SIGALRM,timerh);    /* Enable timer interrupt */
  10328.     xx = alarm(TTOC_TMO);        /* for this many seconds. */
  10329.     if (xx < 0) xx = 0;            /* Save old alarm value. */
  10330.     /* debug(F101,"ttoc alarm","",xx); */
  10331.     if (
  10332. #ifdef CK_POSIX_SIG
  10333.     sigsetjmp(sjbuf,1)
  10334. #else
  10335.     setjmp(sjbuf)
  10336. #endif /* CK_POSIX_SIG */
  10337.     ) {        /* Timer went off? */
  10338.     ttimoff();            /* Yes, cancel this alarm. */
  10339.     if (xx - TTOC_TMO > 0) alarm(xx - TTOC_TMO); /* Restore previous one */
  10340.         /* debug(F100,"ttoc timeout","",0); */
  10341. #ifdef NETCONN
  10342.     if (!netconn) {
  10343. #endif /* NETCONN */
  10344.         debug(F101,"ttoc timeout","",c);
  10345.         if (ttflow == FLO_XONX) {
  10346.         debug(F101,"ttoc flow","",ttflow); /* Maybe we're xoff'd */
  10347. #ifndef Plan9
  10348. #ifdef POSIX
  10349.         /* POSIX way to unstick. */
  10350.         debug(F100,"ttoc tcflow","",tcflow(ttyfd,TCOON));
  10351. #else
  10352. #ifdef BSD4                /* Berkeley way to do it. */
  10353. #ifdef TIOCSTART
  10354. /* .... Used to be "ioctl(ttyfd, TIOCSTART, 0);".  Who knows? */
  10355.         {
  10356.           int x = 0;
  10357.           debug(F101,"ttoc TIOCSTART","",ioctl(ttyfd, TIOCSTART, &x));
  10358.         }
  10359. #endif /* TIOCSTART */
  10360. #endif /* BSD4 */
  10361.                     /* Is there a Sys V way to do this? */
  10362. #endif /* POSIX */
  10363. #endif /* Plan9 */
  10364.         }
  10365. #ifdef NETCONN
  10366.         }
  10367. #endif /* NETCONN */
  10368.     return(-1);            /* Return failure code. */
  10369.     } else {
  10370.         int rc;
  10371. #ifdef BEOSORBEBOX
  10372. #ifdef NETCONN
  10373.         if (netconn && !ttpipe && !ttpty)
  10374.       rc = nettoc(c);
  10375.         else
  10376. #endif /*  BEOSORBEBOX */
  10377. #endif /* NETCONN */
  10378. #ifdef CK_ENCRYPTION
  10379.       if (TELOPT_ME(TELOPT_ENCRYPTION))
  10380.         ck_tn_encrypt(&c,1);
  10381. #endif /* CK_ENCRYPTION */
  10382. #ifdef IBMX25
  10383.     /* riehm: maybe this isn't necessary after all. Test program
  10384.      * worked fine with data being sent and retrieved with normal
  10385.      * read's and writes!
  10386.      */
  10387.     if (ttnet == NET_IX25)
  10388.       rc = x25write(ttyfd,&c,1); /* as above for X25 streams */
  10389.     else
  10390. #endif /* IBMX25 */
  10391. #ifdef CK_SSL
  10392.       if (ssl_active_flag || tls_active_flag) {
  10393.           int error;
  10394.           /* Write using SSL */
  10395.           if (ssl_active_flag)
  10396.                 rc = SSL_write(ssl_con, &c, 1);
  10397.           else
  10398.                 rc = SSL_write(tls_con, &c, 1);
  10399.           switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,rc)){
  10400.         case SSL_ERROR_NONE:
  10401.           break;
  10402.         case SSL_ERROR_WANT_WRITE:
  10403.         case SSL_ERROR_WANT_READ:
  10404.           rc = 0;
  10405.           break;
  10406.         case SSL_ERROR_SYSCALL:
  10407.           if (rc != 0)
  10408.             return(-1);
  10409.         case SSL_ERROR_WANT_X509_LOOKUP:
  10410.         case SSL_ERROR_SSL:
  10411.         case SSL_ERROR_ZERO_RETURN:
  10412.         default:
  10413.           ttclos(0);
  10414.           return(-1);
  10415.           }
  10416.       } else
  10417. #endif /* CK_SSL */
  10418. #ifdef CK_KERBEROS
  10419. #ifdef KRB4
  10420. #ifdef RLOGCODE
  10421.       if (ttnproto == NP_EK4LOGIN) {
  10422.           rc = (krb4_des_write(ttyfd,&c,1) == 1);
  10423.       } else
  10424. #endif /* RLOGCODE */
  10425. #endif /* KRB4 */
  10426. #ifdef KRB5
  10427. #ifdef RLOGCODE
  10428.           if (ttnproto == NP_EK5LOGIN) {
  10429.               rc = (krb5_des_write(ttyfd,&c,1,0) == 1);
  10430.           } else
  10431. #endif /* RLOGCODE */
  10432. #ifdef KRB5_U2U
  10433.           if (ttnproto == NP_K5U2U) {
  10434.               rc = (krb5_u2u_write(ttyfd,&c,1) == 1);
  10435.           } else
  10436. #endif /* KRB5_U2U */
  10437. #endif /* KRB5 */
  10438. #endif /* CK_KERBEROS */
  10439.         rc = write(fd,&c,1);    /* Try to write the character. */
  10440.     if (rc < 1) {            /* Failed */
  10441.         ttimoff();            /* Turn off the alarm. */
  10442.         alarm(xx);            /* Restore previous alarm. */
  10443.         debug(F101,"ttoc errno","",errno); /* Log the error, */
  10444.         return(-1);            /* and return the error code. */
  10445.     }
  10446.     }
  10447.     ttimoff();                /* Success, turn off the alarm. */
  10448.     alarm(xx);                /* Restore previous alarm. */
  10449.     return(0);                /* Return good code. */
  10450. }
  10451.  
  10452. /*  T T I N L  --  Read a record (up to break character) from comm line.  */
  10453. /*
  10454.   Reads up to "max" characters from the communication line, terminating on:
  10455.     (a) the packet length field if the "turn" argument is zero, or
  10456.     (b) on the packet-end character (eol) if the "turn" argument is nonzero
  10457.     (c) a certain number of Ctrl-C's in a row
  10458.  
  10459.   Returns:
  10460.     >= 0, the number of characters read upon success;
  10461.     -1 if "max" exceeded, timeout, or other correctable error;
  10462.     -2 on user interruption (c);
  10463.     -3 on fatal error like connection lost.
  10464.  
  10465.   The characters that were input are copied into "dest" with their parity bits
  10466.   stripped if parity was selected.  Returns the number of characters read.
  10467.   Characters after the eol are available upon the next call to this function.
  10468.  
  10469.   The idea is to minimize the number of system calls per packet, and also to
  10470.   minimize timeouts.  This function is the inner loop of the protocol and must
  10471.   be as efficient as possible.  The current strategy is to use myread().
  10472.  
  10473.   WARNING: This function calls parchk(), which is defined in another module.
  10474.   Normally, ckutio.c does not depend on code from any other module, but there
  10475.   is an exception in this case because all the other ck?tio.c modules also
  10476.   need to call parchk(), so it's better to have it defined in a common place.
  10477. */
  10478. #ifdef CTRLC
  10479. #undef CTRLC
  10480. #endif /* CTRLC */
  10481. #define CTRLC '\03'
  10482. /*
  10483.   We have four different declarations here because:
  10484.   (a) to allow Kermit to be built without the automatic parity sensing feature
  10485.   (b) one of each type for ANSI C, one for non-ANSI.
  10486. */
  10487.  
  10488. static int csave = -1;
  10489.  
  10490. #ifndef NOXFER
  10491. int
  10492. #ifdef PARSENSE
  10493. #ifdef CK_ANSIC
  10494. ttinl(CHAR *dest, int max,int timo, CHAR eol, CHAR start, int turn)
  10495. #else
  10496. ttinl(dest,max,timo,eol,start,turn) int max,timo,turn; CHAR *dest, eol, start;
  10497. #endif /* CK_ANSIC */
  10498. #else /* not PARSENSE */
  10499. #ifdef CK_ANSIC
  10500. ttinl(CHAR *dest, int max,int timo, CHAR eol)
  10501. #else
  10502. ttinl(dest,max,timo,eol) int max,timo; CHAR *dest, eol;
  10503. #endif /* __SDTC__ */
  10504. #endif /* PARSENSE */
  10505. /* ttinl */ {
  10506.  
  10507. #ifndef MYREAD
  10508.     CHAR ch, dum;
  10509. #endif /* MYREAD */
  10510. #ifdef PARSENSE
  10511.     int pktlen = -1;
  10512.     int lplen = 0;
  10513.     int havelen = 0;
  10514. #endif /* PARSENSE */
  10515.     int fd;
  10516.     int sopmask = 0xff;            /* Start-Of-Packet mask */
  10517. #ifdef CKXXCHAR
  10518.     extern short dblt[];        /* Ignore-character table */
  10519.     extern int ignflag;
  10520. #endif /* CKXXCHAR */
  10521. #ifdef TCPSOCKET
  10522.     extern CHAR stchr;
  10523. #endif /* TCPSOCKET */
  10524.     int x;
  10525. #ifdef STREAMING
  10526.     extern int streaming;
  10527.     extern int sndtyp;
  10528. #endif /* STREAMING */
  10529.  
  10530.     if (ttyfd < 0) return(-3);          /* Not open. */
  10531.  
  10532.     debug(F101,"ttinl max","",max);
  10533.     debug(F101,"ttinl timo","",timo);
  10534.  
  10535. #ifdef NETCMD
  10536.     if (ttpipe)
  10537.       fd = fdin;
  10538.     else
  10539. #endif /* NETCMD */
  10540.       fd = ttyfd;
  10541.  
  10542. #ifdef COMMENT
  10543.     if (xlocal && conchk() > 0)        /* Allow for console interruptions */
  10544.       return(-1);
  10545. #endif /* COMMENT */
  10546.  
  10547.     *dest = '\0';                       /* Clear destination buffer */
  10548.     if (timo < 0) timo = 0;        /* Safety */
  10549.     if (timo) {                /* Don't time out if timo == 0 */
  10550.     int xx;
  10551.     saval = signal(SIGALRM,timerh);    /* Enable timer interrupt */
  10552.     xx = alarm(timo);        /* Set it. */
  10553.     debug(F101,"ttinl alarm","",xx);
  10554.     }
  10555.     if (
  10556. #ifdef CK_POSIX_SIG
  10557.     sigsetjmp(sjbuf,1)
  10558. #else
  10559.     setjmp(sjbuf)
  10560. #endif /* CK_POSIX_SIG */
  10561.     ) {                /* Timer went off? */
  10562.     debug(F100,"ttinl timout","",0); /* Get here on timeout. */
  10563.     /* debug(F110," with",(char *) dest,0); */
  10564.     ttimoff();            /* Turn off timer */
  10565.     return(-1);            /* and return error code. */
  10566.     } else {
  10567.     register int i, n = -1;        /* local variables */
  10568.     int ccn = 0;
  10569. #ifdef PARSENSE
  10570.     register int flag = 0;
  10571.     debug(F000,"ttinl start","",start);
  10572. #endif /* PARSENSE */
  10573.  
  10574.     ttpmsk = ttprty ? 0177 : 0377;    /* Set parity stripping mask. */
  10575.     sopmask = needpchk ? 0177 : ttpmsk; /* And SOP matching mask. */
  10576.  
  10577. /* Now read into destination, stripping parity and looking for the */
  10578. /* the packet terminator, and also for several Ctrl-C's typed in a row. */
  10579.  
  10580.     i = 0;                /* Destination index */
  10581.     debug(F101,"ttinl eol","",eol);
  10582.  
  10583.     while (i < max-1) {
  10584. #ifdef MYREAD
  10585.         /* debug(F101,"ttinl i","",i); */
  10586.         errno = 0;
  10587.         if (csave > -1) {
  10588.             n = csave;
  10589.         debug(F101,"ttinl unsaving","",n);
  10590.         } else
  10591. #ifdef COMMENT
  10592.           if (xlocal && conchk() > 0) {
  10593.           /* Here we could catch keyboard interruptions. */
  10594.           /* But this would be VERY expensive. */
  10595.           /* We could also do it in myread() but it would be */
  10596.           /* expensive there too -- even if done with select()... */
  10597.           }
  10598. #endif /* COMMENT */
  10599.           if ((n = myread()) < 0) {    /* Timeout or i/o error? */
  10600. #ifdef DEBUG
  10601.         if (deblog) {
  10602.             debug(F101,"ttinl myread failure, n","",n);
  10603.             debug(F101,"ttinl myread errno","",errno);
  10604.         }
  10605. #endif /* DEBUG */
  10606.         /* Don't let EINTR break packets. */
  10607.         if (n == -3) {
  10608.             if (errno == EINTR && i > 0) {
  10609.             debug(F111,"ttinl EINTR myread i","continuing",i);
  10610.             continue;
  10611.             } else {
  10612.             debug(F110,"ttinl non-EINTR -3","closing",0);
  10613.             wasclosed = 1;
  10614.             ttimoff();    /* Turn off timer */
  10615.             ttclos(0);
  10616.             return(n);
  10617.             }
  10618.         } else if (n == -2 && netconn /* && timo == 0 */ ) {
  10619.             /* Here we try to catch broken network connections */
  10620.             /* even when ioctl() and read() do not catch them */
  10621.             debug(F111,"ttinl network myread failure","closing",n);
  10622.             wasclosed = 1;
  10623.             ttimoff();
  10624.             ttclos(0);
  10625.             return(-3);
  10626.         }
  10627. #ifdef STREAMING
  10628.         /* Streaming and no data to read */
  10629.         else if (n == 0 && streaming && sndtyp == 'D')
  10630.           return(0);
  10631. #endif /* STREAMING */
  10632.         break;            /* Break out of while loop */
  10633.         }
  10634.  
  10635. #else /* not MYREAD (is this code used anywhere any more?) */
  10636.  
  10637.         if (csave > -1)        /* Char saved from last time */
  10638.           ch = csave;
  10639.         else if ((n = read(fd, &ch, 1)) < 1)
  10640.           break;            /* Error - break out of while loop */
  10641.         n = ch;
  10642.  
  10643. #endif /* MYREAD */
  10644.  
  10645.         /* Get here with char in n */
  10646.  
  10647. #ifdef CK_ENCRYPTION
  10648.         /* If csave > -1 we already decrypted this character */
  10649.         /* So don't decrypt it again */
  10650.         if (TELOPT_U(TELOPT_ENCRYPTION) && csave == -1) {
  10651.         CHAR ch = n;
  10652.         ck_tn_decrypt(&ch,1);
  10653.         n = ch;
  10654.         }
  10655. #endif /* CK_ENCRYPTION */
  10656.  
  10657.         csave = -1;            /* Unflag that we unsaved a char */
  10658.  
  10659. #ifdef TCPSOCKET
  10660.         if (n == IAC &&        /* Handle Telnet options */
  10661.         ((xlocal && netconn && IS_TELNET()) ||
  10662.         (!xlocal && sstelnet))) {
  10663.         n = tt_tnopt(n);
  10664.         if (n < 0)
  10665.           return(n);
  10666. #ifndef NOPARSEN
  10667.         else if (n == 1)
  10668.           start = stchr;
  10669. #endif /* NOPARSEN */
  10670.         if (n != 255)        /* No data - go back for next char */
  10671.           continue;
  10672.         }                /* Quoted IAC - keep going */
  10673. #endif /* TCPSOCKET */
  10674. #ifdef CKXXCHAR
  10675.         if (ignflag)
  10676.           if (dblt[(unsigned) n] & 1) /* Character to ignore? */
  10677.         continue;
  10678. #endif /* CKXXCHAR */
  10679.  
  10680. /*
  10681.   Use parity mask, rather than always stripping parity, to check for
  10682.   cancellation.  Otherwise, runs like \x03\x83\x03 in a packet could cancel
  10683.   the transfer when parity is NONE.  (Note that \x03\x03\x03 is extremely
  10684.   unlikely due to run-length encoding.)
  10685. */
  10686.         /* Check cancellation */
  10687.         if (!xlocal && xfrcan && ((n & ttpmsk) == xfrchr)) {
  10688.         if (++ccn >= xfrnum) {    /* If xfrnum in a row, bail out. */
  10689.             if (timo) {        /* Clear timer. */
  10690.             ttimoff();
  10691.             }
  10692.             if (xfrchr < 32)
  10693.               printf("^%c...\r\n",(char)(xfrchr+64));
  10694.             else
  10695.               printf("Canceled...\r\n");
  10696.             return(-2);
  10697.         }
  10698.         } else ccn = 0;        /* No cancellation, reset counter, */
  10699.  
  10700. #ifdef PARSENSE
  10701.         if (flag == 0) {        /* Find the Start-Of-Packet. */
  10702.         if ((n & sopmask) == start) { /* Got it */
  10703.             flag = 1;
  10704.         } else {        /* Keep looking... */
  10705.             debug(F000,"ttinl skipping","",n);
  10706.             continue;
  10707.         }
  10708.         }
  10709.         dest[i++] = n & ttpmsk;
  10710. /*
  10711.   If we have not been instructed to wait for a turnaround character, we
  10712.   can go by the packet length field.  If turn != 0, we must wait for the
  10713.   end of line (eol) character before returning.  This is an egregious
  10714.   violation of all principles of layering...
  10715. */
  10716.         if (!havelen) {
  10717.         if (i == 2) {
  10718.             pktlen = xunchar(dest[1] & 0x7f);
  10719.             if (pktlen > 1) {
  10720.             havelen = 1;
  10721.             debug(F101,"ttinl length","",pktlen);
  10722.             }
  10723.         } else if (i == 5 && pktlen == 0) {
  10724.             lplen = xunchar(dest[4] & 0x7f);
  10725.         } else if (i == 6 && pktlen == 0) {
  10726.             pktlen = lplen * 95 + xunchar(dest[5] & 0x7f) + 5;
  10727.             havelen = 1;
  10728.             debug(F101,"ttinl extended length","",pktlen);
  10729.         }
  10730.         }
  10731.  
  10732. /*
  10733.   Suppose we looked at the sequence number here and found it was out of
  10734.   range?  This would mean either (a) incoming packets had SOP unprefixed
  10735.   and we are out of sync, or (b) the packet is damaged.  Since (a) is bad
  10736.   practice, let's ignore it.  So what should we do here if we know the
  10737.   packet is damaged?
  10738.  
  10739.    1. Nothing -- keep trying to read the packet till we find what we think
  10740.       is the end, or we time out, and let the upper layer decide what to
  10741.       do.  But since either the packet is corrupt or we are out of sync,
  10742.       our criterion for finding the end does not apply and we are likely
  10743.       to time out (or swallow a piece of the next packet) if our assumed
  10744.       length is too long.  (This was the behavior prior to version 7.0.)
  10745.  
  10746.    2. set flag = 0 and continue?  This would force us to wait for the
  10747.       next packet to come in, and therefore (in the nonwindowing case),
  10748.       would force a timeout in the other Kermit.
  10749.  
  10750.    3. set flag = 0 and continue, but only if the window size is > 1 and
  10751.       the window is not blocked?  Talk about cheating!
  10752.  
  10753.    4. Return a failure code and let the upper layer decide what to do.
  10754.       This should be equivalent to 3, but without the cheating.  So let's
  10755.       do it that way...  But note that we must ignore the parity bit
  10756.       in case this is the first packet and we have not yet run parchk().
  10757. */
  10758.         if (i == 3) {        /* Peek at sequence number */
  10759.         x = xunchar((dest[i-1] & 0x7f)); /* If it's not in range... */
  10760.         if (x < 0 || x > 63) {
  10761.             debug(F111,"ttinl bad seq",dest,x);
  10762.             if (timo) ttimoff();
  10763.             return(-1);        /* return a nonfatal error */
  10764.         }
  10765.         }
  10766.  
  10767. #else /* PARSENSE */
  10768.         dest[i++] = n & ttpmsk;
  10769. #endif /* PARSENSE */
  10770.  
  10771.     /* Check for end of packet */
  10772.  
  10773.         if (
  10774. #ifdef PARSENSE
  10775. /*
  10776.   Purely length-driven if SET HANDSHAKE NONE (i.e. turn == 0).
  10777.   This allows packet terminators and handshake characters to appear
  10778.   literally inside a packet data field.
  10779. */
  10780.         (havelen && (i > pktlen+1) &&
  10781.          (!turn || (turn && (n & 0x7f) == turn))) /* (turn, not eol) */
  10782. #else /* !PARSENSE */
  10783. /*
  10784.   Built without PARSENSE, so just look for packet terminator.
  10785. */
  10786.         ((n & 0x7f) == eol)
  10787. #endif /* PARSENSE */
  10788.         ) {
  10789. #ifndef PARSENSE
  10790.         debug(F101,"ttinl got eol","",eol); /* (or turn) */
  10791.         dest[i] = '\0';        /* Yes, terminate the string, */
  10792.         /* debug(F101,"ttinl i","",i); */
  10793. #else
  10794. #ifdef DEBUG
  10795.         if (deblog) {
  10796.             if ((n & 0x7f) != eol) {
  10797.             debug(F101,"ttinl EOP length","",pktlen);
  10798.             debug(F101,"ttinl i","",i);
  10799. #ifdef MYREAD
  10800. #ifdef PARSENSE
  10801. /*
  10802.   We read a packet based on its length.  This leaves the EOP character still
  10803.   unread, and so ttchk() will always return at least 1 because of this.  But
  10804.   if we know it is there, we can safely get rid of it.  So...
  10805. */
  10806.             {
  10807.                 int x;
  10808.                 while (my_count > 0) {
  10809.                 x = ttinc(0);
  10810.                 /* Start of next packet */
  10811.                 if (x == start) { /* Save for next time */
  10812.                     csave = (unsigned)((unsigned)x & 0xff);
  10813.                     debug(F000,"ttinl csaved","",x);
  10814.                     break;
  10815.                 }
  10816.                 debug(F000,"ttinl removed","",x);
  10817.                 }
  10818.             }
  10819. #endif /* PARSENSE */
  10820. #endif /* MYREAD */
  10821.  
  10822.             } else debug(F101,"ttinl got eol","",eol); /* (or turn) */
  10823.         }
  10824. #endif /* DEBUG */
  10825.         dest[i] = '\0';        /* Terminate the string, */
  10826.             if (needpchk) {        /* Parity checked yet? */
  10827.             if (ttprty == 0) {    /* No, check. */
  10828.             if ((ttprty = parchk(dest,start,i)) > 0) {
  10829.                 int j;
  10830.                 debug(F101,"ttinl senses parity","",ttprty);
  10831.                 debug(F110,"ttinl packet before",dest,0);
  10832.                 ttpmsk = 0x7f;
  10833.                 for (j = 0; j < i; j++)
  10834.                   dest[j] &= 0x7f;    /* Strip parity from packet */
  10835.                 debug(F110,"ttinl packet after ",dest,0);
  10836.             } else ttprty = 0; /* Restore if parchk error */
  10837.             }
  10838.             sopmask = ttprty;
  10839.             needpchk = 0;
  10840.         }
  10841. #endif /* PARSENSE */
  10842.         if (timo) {        /* Turn off timer. */
  10843.             ttimoff();
  10844.         }
  10845. #ifdef COMMENT
  10846.         debug(F011,"ttinl got", dest, (i < 60) ? i : -60);
  10847. #else /* COMMENT */
  10848.                 hexdump("ttinl got",dest,i);
  10849. #endif /* COMMENT */
  10850. #ifdef STREAMING
  10851.         /* ttinl() was called because there was non-packet */
  10852.         /* data sitting int the channel.  Ignore it.       */
  10853.         if (streaming && sndtyp == 'D')
  10854.           return(-1);
  10855. #endif /* STREAMING */
  10856.         return(i);
  10857.         }
  10858.     } /* End of while() */
  10859.     ttimoff();
  10860.     return(n);
  10861.     }
  10862. }
  10863. #endif /* NOXFER */
  10864.  
  10865. /*  T T I N C --  Read a character from the communication line  */
  10866. /*
  10867.  On success, returns the character that was read, >= 0.
  10868.  On failure, returns -1 or other negative myread error code,
  10869.    or -2 if connection is broken or ttyfd < 0.
  10870.    or -3 if session limit has expired,
  10871.    or -4 if something or other...
  10872.  NOTE: The API does not provide for ttinc() returning a special code
  10873.  upon timeout, but we need it.  So for this we have a global variable,
  10874.  ttinctimo.
  10875. */
  10876. static int ttinctimo = 0;        /* Yuk */
  10877.  
  10878. int
  10879. ttinc(timo) int timo; {
  10880.  
  10881.     int n = 0, fd;
  10882.     int is_tn = 0;
  10883.     CHAR ch = 0;
  10884.  
  10885.     ttinctimo = 0;
  10886.  
  10887.     if (ttyfd < 0) return(-2);          /* Not open. */
  10888.  
  10889.     is_tn = (xlocal && netconn && IS_TELNET()) ||
  10890.         (!xlocal && sstelnet);
  10891.  
  10892. #ifdef TTLEBUF
  10893.     if (ttpush >= 0) {
  10894.         debug(F111,"ttinc","ttpush",ttpush);
  10895.         ch = ttpush;
  10896.         ttpush = -1;
  10897.         return(ch);
  10898.     }
  10899.     if (le_data) {
  10900.         if (le_getchar(&ch) > 0) {
  10901.             debug(F111,"ttinc le_getchar","ch",ch);
  10902.             return(ch);
  10903.         }
  10904.     }
  10905. #endif /* TTLEBUF */
  10906.  
  10907. #ifdef NETCMD
  10908.     if (ttpipe)
  10909.       fd = fdin;
  10910.     else
  10911. #endif /* NETCMD */
  10912.       fd = ttyfd;
  10913.  
  10914.     if ((timo <= 0)            /* Untimed. */
  10915. #ifdef MYREAD
  10916.     || (my_count > 0)        /* Buffered char already waiting. */
  10917. #endif /* MYREAD */
  10918.     ) {
  10919. #ifdef MYREAD
  10920.         /* Comm line failure returns -1 thru myread, so no &= 0377 */
  10921.     n = myread();            /* Wait for a character... */
  10922.     /* debug(F000,"ttinc MYREAD n","",n); */
  10923. #ifdef CK_ENCRYPTION
  10924.     /* debug(F101,"ttinc u_encrypt","",TELOPT_U(TELOPT_ENCRYPTION)); */
  10925.     if (TELOPT_U(TELOPT_ENCRYPTION) && n >= 0) {
  10926.         ch = n;
  10927.         ck_tn_decrypt(&ch,1);
  10928.         n = ch;
  10929.     }
  10930. #endif /* CK_ENCRYPTION */
  10931.  
  10932. #ifdef NETPTY
  10933.     if (ttpty && n < 0) {
  10934.         debug(F101,"ttinc error on pty","",n);
  10935.         ttclos(0);
  10936.         return(n);
  10937.     }
  10938. #endif /* NETPTY */
  10939.  
  10940. #ifdef TNCODE
  10941.     if ((n > -1) && is_tn)
  10942.       return((unsigned)(n & 0xff));
  10943.     else
  10944. #endif /* TNCODE */
  10945.       return(n < 0 ? n : (unsigned)(n & ttpmsk));
  10946.  
  10947. #else  /* MYREAD */
  10948.  
  10949.         while ((n = read(fd,&ch,1)) == 0) /* Wait for a character. */
  10950.         /* Shouldn't have to loop in ver 5A. */
  10951. #ifdef NETCONN
  10952.       if (netconn) {        /* Special handling for net */
  10953.           netclos();        /* If read() returns 0 it means */
  10954.           netconn = 0;        /* the connection has dropped. */
  10955.           errno = ENOTCONN;
  10956.           return(-2);
  10957.       }
  10958. #endif /* NETCONN */
  10959.       ;
  10960.     /* debug(F101,"ttinc","",ch); */
  10961. #ifdef TNCODE
  10962.     if ((n > 0) && is_tn) {
  10963. #ifdef CK_ENCRYPTION
  10964.         if (TELOPT_U(TELOPT_ENCRYPTION)) {
  10965.         ck_tn_decrypt(&ch,1);
  10966.         n = ch;
  10967.         }
  10968. #endif /* CK_ENCRYPTION */
  10969.         return((unsigned)(ch & 0xff));
  10970.     } else
  10971. #endif /* TNCODE */
  10972.         return((n < 0) ? -4 : ((n == 0) ? -1 : (unsigned)(ch & ttpmsk)));
  10973. #endif /* MYREAD */
  10974.  
  10975.     } else {                /* Timed read */
  10976.  
  10977.     int oldalarm;
  10978.     saval = signal(SIGALRM,timerh);    /* Set up handler, save old one. */
  10979.     oldalarm = alarm(timo);        /* Set alarm, save old one. */
  10980.     if (
  10981. #ifdef CK_POSIX_SIG
  10982.         sigsetjmp(sjbuf,1)
  10983. #else
  10984.         setjmp(sjbuf)
  10985. #endif /* CK_POSIX_SIG */
  10986.         ) {                /* Timer expired */
  10987.         ttinctimo = 1;
  10988.         n = -1;            /* set flag */
  10989.     } else {
  10990. #ifdef MYREAD
  10991.         n = myread();        /* If managing own buffer... */
  10992.         debug(F101,"ttinc myread","",n);
  10993.         ch = n;
  10994. #else
  10995.         n = read(fd,&ch,1);        /* Otherwise call the system. */
  10996.         if (n == 0) n = -1;
  10997.         debug(F101,"ttinc read","",n);
  10998. #endif /* MYREAD */
  10999.  
  11000. #ifdef CK_ENCRYPTION
  11001.         if (TELOPT_U(TELOPT_ENCRYPTION) && n >= 0) {
  11002.         ck_tn_decrypt(&ch,1);
  11003.         }
  11004. #endif /* CK_ENCRYPTION */
  11005.         if (n >= 0)
  11006.           n = (unsigned) (ch & 0xff);
  11007.         else
  11008.           n = (n < 0) ? -4 : -2;    /* Special return codes. */
  11009.     }
  11010.     ttimoff();            /* Turn off the timer */
  11011.     if (oldalarm > 0) {
  11012.         if (n == -1)        /* and restore any previous alarm */
  11013.           oldalarm -= timo;
  11014.         if (oldalarm < 0)        /* adjusted by our timeout interval */
  11015.           oldalarm = 0;
  11016.         if (oldalarm) {
  11017.             debug(F101,"ttinc restoring oldalarm","",oldalarm);
  11018.         alarm(oldalarm);
  11019.         }
  11020.     }
  11021. #ifdef NETCONN
  11022.     if (netconn) {
  11023.         if (n == -2) {        /* read() returns 0 */
  11024.         netclos();        /* on network read failure */
  11025.         netconn = 0;
  11026.         errno = ENOTCONN;
  11027.         }
  11028.     }
  11029. #endif    /* NETCONN */
  11030. #ifdef TNCODE
  11031.     if ((n > -1) && is_tn)
  11032.       return((unsigned)(n & 0xff));
  11033.     else
  11034. #endif /* TNCODE */
  11035.       /* Return masked char or neg. */
  11036.       return( (n < 0) ? n : (unsigned)(n & ttpmsk) );
  11037.     }
  11038. }
  11039.  
  11040. /*  S N D B R K  --  Send a BREAK signal of the given duration  */
  11041.  
  11042. static int
  11043. #ifdef CK_ANSIC
  11044. sndbrk(int msec) {            /* Argument is milliseconds */
  11045. #else
  11046. sndbrk(msec) int msec; {
  11047. #endif /* CK_ANSIC */
  11048. #ifndef POSIX
  11049.     int x, n;
  11050. #endif /* POSIX */
  11051.  
  11052. #ifdef OXOS
  11053. #define BSDBREAK
  11054. #endif /* OXOS */
  11055.  
  11056. #ifdef ANYBSD
  11057. #define BSDBREAK
  11058. #endif /* ANYBSD */
  11059.  
  11060. #ifdef BSD44
  11061. #define BSDBREAK
  11062. #endif /* BSD44 */
  11063.  
  11064. #ifdef COHERENT
  11065. #ifdef BSDBREAK
  11066. #undef BSDBREAK
  11067. #endif /* BSDBREAK */
  11068. #endif /* COHERENT */
  11069.  
  11070. #ifdef BELLV10
  11071. #ifdef BSDBREAK
  11072. #undef BSDBREAK
  11073. #endif /* BSDBREAK */
  11074. #endif /* BELLV10 */
  11075.  
  11076. #ifdef PROVX1
  11077.     char spd;
  11078. #endif /* PROVX1 */
  11079.  
  11080.     debug(F101,"ttsndb ttyfd","",ttyfd);
  11081.     if (ttyfd < 0) return(-1);          /* Not open. */
  11082.  
  11083. #ifdef Plan9
  11084.     return p9sndbrk(msec);
  11085. #else
  11086. #ifdef NETCONN
  11087. #ifdef NETCMD
  11088.     if (ttpipe)                /* Pipe */
  11089.       return(ttoc('\0'));
  11090. #endif /* NETCMD */
  11091. #ifdef NETPTY
  11092.     if (ttpty)
  11093.       return(ttoc('\0'));
  11094. #endif /* NETPTY */
  11095.     if (netconn)             /* Send network BREAK */
  11096.       return(netbreak());
  11097. #endif /* NETCONN */
  11098.  
  11099.     if (msec < 1 || msec > 5000) return(-1); /* Bad argument */
  11100.  
  11101. #ifdef POSIX                /* Easy in POSIX */
  11102.     {
  11103.     int x;
  11104.     debug(F111,"sndbrk POSIX",ckitoa(msec),(msec/375));
  11105.     errno = 0;
  11106.     x = tcsendbreak(ttyfd,msec / 375);
  11107.     debug(F111,"sndbrk tcsendbreak",ckitoa(errno),x);
  11108.     return(x);
  11109.     }
  11110. #else
  11111. #ifdef PROVX1
  11112.     gtty(ttyfd,&ttbuf);                 /* Get current tty flags */
  11113.     spd = ttbuf.sg_ospeed;              /* Save speed */
  11114.     ttbuf.sg_ospeed = B50;              /* Change to 50 baud */
  11115.     stty(ttyfd,&ttbuf);                 /*  ... */
  11116.     n = (int)strlen(brnuls);        /* Send the right number of nulls */
  11117.     x = msec / 91;
  11118.     if (x > n) x = n;
  11119.     write(ttyfd,brnuls,n);
  11120.     ttbuf.sg_ospeed = spd;              /* Restore speed */
  11121.     stty(ttyfd,&ttbuf);                 /*  ... */
  11122.     return(0);
  11123. #else
  11124. #ifdef aegis
  11125.     sio_$control((short)ttyfd, sio_$send_break, msec, st);
  11126.     return(0);
  11127. #else
  11128. #ifdef BSDBREAK
  11129.     n = FWRITE;                         /* Flush output queue. */
  11130. /* Watch out for int vs long problems in &n arg! */
  11131.     debug(F101,"sndbrk BSDBREAK","",msec);
  11132.     ioctl(ttyfd,TIOCFLUSH,&n);          /* Ignore any errors.. */
  11133.     if (ioctl(ttyfd,TIOCSBRK,(char *)0) < 0) {  /* Turn on BREAK */
  11134.         perror("Can't send BREAK");
  11135.         return(-1);
  11136.     }
  11137.     x = msleep(msec);                    /* Sleep for so many milliseconds */
  11138.     if (ioctl(ttyfd,TIOCCBRK,(char *)0) < 0) {  /* Turn off BREAK */
  11139.         perror("BREAK stuck!!!");
  11140.         doexit(BAD_EXIT,-1);        /* Get out, closing the line. */
  11141.                                         /*   with bad exit status */
  11142.     }
  11143.     return(x);
  11144. #else
  11145. #ifdef ATTSV
  11146. /*
  11147.   No way to send a long BREAK in Sys V, so send a bunch of regular ones.
  11148.   (Actually, Sys V R4 is *supposed* to have the POSIX tcsendbreak() function,
  11149.   but there's no way for this code to know for sure.)
  11150. */
  11151.     debug(F101,"sndbrk ATTSV","",msec);
  11152.     x = msec / 275;
  11153.     for (n = 0; n < x; n++) {
  11154.     /* Reportedly the cast breaks this function on some systems */
  11155.     /* But then why was it here in the first place? */
  11156.     if (ioctl(ttyfd,TCSBRK, /* (char *) */ 0) < 0) {
  11157.         perror("Can't send BREAK");
  11158.         return(-1);
  11159.     }
  11160.     }
  11161.     return(0);
  11162. #else
  11163. #ifdef  V7
  11164.     debug(F101,"sndbrk V7","",msec);
  11165.     return(genbrk(ttyfd,250));        /* Simulate a BREAK */
  11166. #else
  11167.     debug(F101,"sndbrk catchall","",msec);
  11168.     ttoc(0);ttoc(0);ttoc(0);ttoc(0);
  11169.     return(0);
  11170. #endif /* V7 */
  11171. #endif /* BSDBREAK */
  11172. #endif /* ATTSV */
  11173. #endif /* aegis */
  11174. #endif /* PROVX1 */
  11175. #endif /* POSIX */
  11176. #endif /* Plan9 */
  11177. }
  11178.  
  11179. /*  T T S N D B  --  Send a BREAK signal  */
  11180.  
  11181. int
  11182. ttsndb() {
  11183. #ifdef TN_COMPORT
  11184.     if (netconn && istncomport())
  11185.       return((tnsndb(275L) >= 0) ? 0 : -1);
  11186.     else
  11187. #endif /* TN_COMPORT */
  11188.       return(sndbrk(275));
  11189. }
  11190.  
  11191. /*  T T S N D L B  --  Send a Long BREAK signal  */
  11192.  
  11193. int
  11194. ttsndlb() {
  11195. #ifdef TN_COMPORT
  11196.     if (netconn && istncomport())
  11197.       return((tnsndb(1800L) >= 0) ? 0 : -1);
  11198.     else
  11199. #endif /* TN_COMPORT */
  11200.     return(sndbrk(1500));
  11201. }
  11202.  
  11203. /*  M S L E E P  --  Millisecond version of sleep().  */
  11204.  
  11205. /*
  11206.   Call with number of milliseconds (thousandths of seconds) to sleep.
  11207.   Intended only for small intervals.  For big ones, just use sleep().
  11208.   Highly system-dependent.
  11209.   Returns 0 always, even if it didn't work.
  11210. */
  11211.  
  11212. /* Define MSLFTIME for systems that must use an ftime() loop. */
  11213. #ifdef ANYBSD                /* For pre-4.2 BSD versions */
  11214. #ifndef BSD4
  11215. #define MSLFTIME
  11216. #endif /* BSD4 */
  11217. #endif /* ANYBSD */
  11218.  
  11219. #ifdef TOWER1                /* NCR Tower OS 1.0 */
  11220. #define MSLFTIME
  11221. #endif /* TOWER1 */
  11222.  
  11223. #ifdef COHERENT         /* Coherent... */
  11224. #ifndef _I386           /* Maybe Coherent/386 should get this, too */
  11225. #define MSLFTIME        /* Opinions are divided */
  11226. #endif /* _I386 */
  11227. #endif /* COHERENT */
  11228.  
  11229. #ifdef COMMENT
  11230. #ifdef GETMSEC
  11231.  
  11232. /* Millisecond timer */
  11233.  
  11234. static long msecbase = 0L;        /* Unsigned long not portable */
  11235.  
  11236. long
  11237. getmsec() {                /* Milliseconds since base time */
  11238.     struct timeval xv;
  11239.     struct timezone xz;
  11240.     long secs, msecs;
  11241.     if (
  11242. #ifdef GTODONEARG
  11243.     gettimeofday(&tv)
  11244. #else
  11245. #ifdef PTX
  11246.     gettimeofday(&tv, NULL)
  11247. #else
  11248.     gettimeofday(&tv, &tz)
  11249. #endif /* PTX */
  11250. #endif /* GTODONEARG */
  11251.     < 0)
  11252.       return(-1);
  11253.     if (msecbase == 0L) {        /* First call, set base time. */
  11254.     msecbase = tv.tv_sec;
  11255.     debug(F101,"getmsec base","",msecbase);
  11256.     }
  11257.     return(((tv.tv_sec - msecbase) * 1000L) + (tv.tv_usec / 1000L));
  11258. }
  11259. #endif /* GETMSEC */
  11260. #endif /* COMMENT */
  11261.  
  11262. #ifdef SELECT
  11263. int
  11264. ttwait(fd, secs) int fd, secs; {
  11265.     int x;
  11266.     fd_set rfds;
  11267.     FD_ZERO(&rfds);
  11268.     FD_SET(fd,&rfds);
  11269.     tv.tv_sec = secs;
  11270.     tv.tv_usec = 0L;
  11271.     errno = 0;
  11272.     if ((x = select(FD_SETSIZE,
  11273. #ifdef HPUX9
  11274.             (int *)
  11275. #else
  11276. #ifdef HPUX1000
  11277.             (int *)
  11278. #endif /* HPUX1000 */
  11279. #endif /* HPUX9 */
  11280.             &rfds,
  11281.             0, 0, &tv)) < 0) {
  11282.     debug(F101,"ttwait select errno","",errno);
  11283.     return(0);
  11284.     } else {
  11285.     debug(F101,"ttwait OK","",errno);
  11286.     x = FD_ISSET(fd, &rfds);
  11287.     debug(F101,"ttwait select x","",x);
  11288.     return(x ? 1 : 0);
  11289.     }
  11290. }
  11291. #endif /* SELECT */
  11292.  
  11293. int
  11294. msleep(m) int m; {
  11295. /*
  11296.   Other possibilities here are:
  11297.    nanosleep(), reportedly defined in POSIX.4.
  11298.    sginap(), IRIX only (back to what IRIX version I don't know).
  11299. */
  11300. #ifdef Plan9
  11301.     return _SLEEP(m);
  11302. #else
  11303. #ifdef BEOSORBEBOX
  11304.     snooze(m*1000);
  11305. #else /* BEOSORBEBOX */
  11306. #ifdef SELECT
  11307.     int t1, x;
  11308.     debug(F101,"msleep SELECT 1","",m);
  11309.     if (m <= 0) return(0);
  11310.     if (m >= 1000) {            /* Catch big arguments. */
  11311.     sleep(m/1000);
  11312.     m = m % 1000;
  11313.     if (m < 10) return(0);
  11314.     }
  11315.     debug(F101,"msleep SELECT 2","",m);
  11316. #ifdef BELLV10
  11317.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, m );
  11318.     debug(F101,"msleep BELLV10 select","",x);
  11319. #else /* BELLV10 */
  11320. #ifdef HPUX9
  11321.     gettimeofday(&tv, &tz);
  11322. #else
  11323.  
  11324. #ifndef COHERENT
  11325. #ifdef GTODONEARG
  11326.     if (gettimeofday(&tv) < 0)
  11327. #else
  11328. #ifdef PTX
  11329.     if (gettimeofday(&tv,NULL) < 0)
  11330. #else
  11331. #ifdef NOTIMEZONE
  11332.     if (gettimeofday(&tv, NULL) < 0)    /* wonder what this does... */
  11333. #else
  11334.     if (gettimeofday(&tv, &tz) < 0)
  11335. #endif /* NOTIMEZONE */
  11336. #endif /* PTX */
  11337. #endif /* GTODONEARG */
  11338.       return(-1);
  11339.     t1 = tv.tv_sec;                     /* Seconds */
  11340. #endif /* COHERENT */
  11341. #endif /* HPUX9 */
  11342.     tv.tv_sec = 0;                      /* Use select() */
  11343.     tv.tv_usec = m * 1000L;
  11344. #ifdef BSD44
  11345.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11346.     debug(F101,"msleep BSD44 select","",x);
  11347. #else /* BSD44 */
  11348. #ifdef __linux__
  11349.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11350.     debug(F101,"msleep __linux__ select","",x);
  11351. #else /* __linux__ */
  11352. #ifdef BSD43
  11353.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11354.     debug(F101,"msleep BSD43 select","",x);
  11355. #else /* BSD43 */
  11356. #ifdef QNX6
  11357.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11358.     debug(F101,"msleep QNX6 select","",x);
  11359. #else /* QNX6 */
  11360. #ifdef QNX
  11361.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11362.     debug(F101,"msleep QNX select","",x);
  11363. #else /* QNX */
  11364. #ifdef COHERENT
  11365.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11366.     debug(F101,"msleep COHERENT select","",x);
  11367. #else /* COHERENT */
  11368. #ifdef HPUX1000                /* 10.00 only, not 10.10 or later */
  11369.     x = select( 0, (int *)0, (int *)0, (int *)0, &tv );
  11370.     debug(F101,"msleep HP-UX 10.00 select","",x);
  11371. #else /* HPUX1000 */
  11372. #ifdef SVR4
  11373.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11374.     debug(F101,"msleep SVR4 select","",x);
  11375. #else /* SVR4 */
  11376. #ifdef OSF40
  11377.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11378.     debug(F101,"msleep OSF40 select","",x);
  11379. #else /* OSF40 */
  11380. #ifdef PTX
  11381.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11382.     debug(F101,"msleep OSF40 select","",x);
  11383. #else
  11384.     x = select( 0, (int *)0, (int *)0, (int *)0, &tv );
  11385.     debug(F101,"msleep catch-all select","",x);
  11386. #endif /* PTX */
  11387. #endif /* OSF40 */
  11388. #endif /* HP1000 */
  11389. #endif /* SVR4 */
  11390. #endif /* COHERENT */
  11391. #endif /* QNX */
  11392. #endif /* QNX6 */
  11393. #endif /* BSD43 */
  11394. #endif /* __linux__ */
  11395. #endif /* BSD44 */
  11396. #endif /* BELLV10 */
  11397.     return(0);
  11398.  
  11399. #else                    /* Not SELECT */
  11400. #ifdef CK_POLL                /* We have poll() */
  11401.     struct pollfd pfd;            /* Supply a valid address for poll() */
  11402.  
  11403. #ifdef ODT30                /* But in SCO ODT 3.0 */
  11404. #ifdef NAP                /* we should use nap() instead */
  11405.     debug(F101,"msleep ODT 3.0 NAP","",m); /* because using poll() here */
  11406.     nap((long)m);               /* seems to break dialing. */
  11407.     return(0);
  11408. #else
  11409.     debug(F101,"msleep ODT 3.0 POLL","",m);
  11410.     poll(&pfd, 0, m);
  11411.     return(0);
  11412. #endif /* NAP */
  11413. #else
  11414.     debug(F101,"msleep POLL","",m);
  11415.     poll(&pfd, 0, m);
  11416.     return(0);
  11417. #endif /* ODT30 */
  11418.  
  11419. /*
  11420.   We could handle the above more cleanly by just letting nap() always
  11421.   take precedence over poll() in this routine, but there is no way to know
  11422.   whether that would break something else.
  11423. */
  11424.  
  11425. #else                    /* Not POLL */
  11426. #ifdef USLEEP
  11427. /*
  11428.   "This routine is implemented using setitimer(2); it requires eight
  11429.   system calls...".  In other words, it might take 5 minutes to sleep
  11430.   10 milliseconds...
  11431. */
  11432.     debug(F101,"msleep USLEEP","",m);
  11433.     if (m >= 1000) {            /* Catch big arguments. */
  11434.     sleep(m/1000);
  11435.     m = m % 1000;
  11436.     if (m < 10) return(0);
  11437.     }
  11438.     usleep((unsigned int)(m * 1000));
  11439.     return(0);
  11440. #else
  11441. #ifdef aegis
  11442.     time_$clock_t dur;
  11443.     debug(F101,"msleep aegis","",m);
  11444.     dur.c2.high16 = 0;
  11445.     dur.c2.low32  = 250 * m; /* one millisecond = 250 four microsecond ticks */
  11446.     time_$wait(time_$relative, dur, st);
  11447.     return(0);
  11448. #else
  11449. #ifdef PROVX1
  11450.     debug(F101,"msleep Venix","",m);
  11451.     if (m <= 0) return(0);
  11452.     sleep(-((m * 60 + 500) / 1000));
  11453.     return(0);
  11454. #else
  11455. #ifdef NAP
  11456.     debug(F101,"msleep NAP","",m);
  11457.     nap((long)m);
  11458.     return(0);
  11459. #else
  11460. #ifdef ATTSV
  11461. #ifndef BSD44
  11462.     extern long times();        /* Or #include <times.h> ? */
  11463. #endif /* BSD44 */
  11464.     long t1, t2, tarray[4];
  11465.     int t3;
  11466.     char *cp = getenv("HZ");
  11467.     int CLOCK_TICK;
  11468.     int hertz;
  11469.  
  11470.     if (cp && (hertz = atoi(cp))) {
  11471.         CLOCK_TICK  = 1000 / hertz;
  11472.     } else {                /* probably single user mode */
  11473. #ifdef HZ
  11474.         CLOCK_TICK  = 1000 / HZ;
  11475. #else
  11476.     static warned = 0;
  11477.     /* HZ always exists in, for instance, SCO Xenix, so you don't have to
  11478.      * make special #ifdefs for XENIX here, like in ver 4F. Also, if you
  11479.      * have Xenix, you have should have nap(), so the best is to use -DNAP
  11480.      * in the makefile. Most systems have HZ.
  11481.      */
  11482.     CLOCK_TICK = 17;        /* 1/60 sec */
  11483.     if (!warned) {
  11484.           printf("warning: environment variable HZ bad... using HZ=%d\r\n",
  11485.          1000 / CLOCK_TICK);
  11486.           warned = 1;
  11487.     }
  11488. #endif /* !HZ */
  11489.     }
  11490.     debug(F101,"msleep ATTSV","",m);
  11491.     if (m <= 0) return(0);
  11492.     if (m >= 1000) {            /* Catch big arguments. */
  11493.     sleep(m/1000);
  11494.     m = m % 1000;
  11495.     if (m < 10) return(0);
  11496.     }
  11497.     if ((t1 = times(tarray)) < 0) return(-1);
  11498.     while (1) {
  11499.         if ((t2 = times(tarray)) < 0) return(-1);
  11500.         t3 = ((int)(t2 - t1)) * CLOCK_TICK;
  11501.         if (t3 > m) return(t3);
  11502.     }
  11503. #else /* Not ATTSV */
  11504. #ifdef MSLFTIME                /* Use ftime() loop... */
  11505.     int t1, t3 = 0;
  11506.     debug(F101,"msleep MSLFTIME","",m);
  11507.     if (m <= 0) return(0);
  11508.     if (m >= 1000) {            /* Catch big arguments. */
  11509.     sleep(m/1000);
  11510.     m = m % 1000;
  11511.     if (m < 10) return(0);
  11512.     }
  11513. #ifdef QNX
  11514.     ftime(&ftp);            /* void ftime() in QNX */
  11515. #else
  11516.     if (ftime(&ftp) < 0) return(-1);    /* Get base time. */
  11517. #endif /* QNX */
  11518.     t1 = ((ftp.time & 0xff) * 1000) + ftp.millitm;
  11519.     while (1) {
  11520.         ftime(&ftp);            /* Get current time and compare. */
  11521.         t3 = (((ftp.time & 0xff) * 1000) + ftp.millitm) - t1;
  11522.         if (t3 > m) return(0);
  11523.     }
  11524. #else
  11525. /* This includes true POSIX, which has no way to do this. */
  11526.     debug(F101,"msleep busy loop","",m);
  11527.     if (m >= 1000) {            /* Catch big arguments. */
  11528.     sleep(m/1000);
  11529.     m = m % 1000;
  11530.     if (m < 10) return(0);
  11531.     }
  11532.     if (m > 0) while (m > 0) m--;    /* Just a dumb busy loop */
  11533.     return(0);
  11534. #endif /* MSLFTIME */
  11535. #endif /* ATTSV */
  11536. #endif /* NAP */
  11537. #endif /* PROVX1 */
  11538. #endif /* aegis */
  11539. #endif /* CK_POLL */
  11540. #endif /* SELECT */
  11541. #endif /* BEOSORBEBOX */
  11542. #endif /* USLEEP */
  11543. #endif /* Plan9 */
  11544. }
  11545.  
  11546. /*  R T I M E R --  Reset elapsed time counter  */
  11547.  
  11548. VOID
  11549. rtimer() {
  11550.     tcount = time( (time_t *) 0 );
  11551. }
  11552.  
  11553.  
  11554. /*  G T I M E R --  Get current value of elapsed time counter in seconds  */
  11555.  
  11556. int
  11557. gtimer() {
  11558.     int x;
  11559.     x = (int) (time( (time_t *) 0 ) - tcount);
  11560.     debug(F101,"gtimer","",x);
  11561.     return( (x < 0) ? 0 : x );
  11562. }
  11563.  
  11564. #ifdef GFTIMER
  11565. /*
  11566.   Floating-point timers.  Require not only floating point support, but
  11567.   also gettimeofday().
  11568. */
  11569. static struct timeval tzero;
  11570.  
  11571. VOID
  11572. rftimer() {
  11573. #ifdef GTODONEARG    /* Account for Mot's definition */
  11574.     (VOID) gettimeofday(&tzero);
  11575. #else
  11576.     (VOID) gettimeofday(&tzero, (struct timezone *)0);
  11577. #endif /* GTODONEARG */
  11578. }
  11579.  
  11580. CKFLOAT
  11581. gftimer() {
  11582.     struct timeval tnow, tdelta;
  11583.     CKFLOAT s;
  11584. #ifdef DEBUG
  11585.     char fpbuf[64];
  11586. #endif /* DEBUG */
  11587. #ifdef GTODONEARG    /* Acount for Mot's definition */
  11588.     (VOID) gettimeofday(&tnow);
  11589. #else
  11590.     (VOID) gettimeofday(&tnow, (struct timezone *)0);
  11591. #endif /* GTODONEARG */
  11592.     tdelta.tv_sec = tnow.tv_sec - tzero.tv_sec;
  11593.     tdelta.tv_usec = tnow.tv_usec - tzero.tv_usec;
  11594.     if (tdelta.tv_usec < 0) {
  11595.     tdelta.tv_sec--;
  11596.     tdelta.tv_usec += 1000000;
  11597.     }
  11598.     s = (CKFLOAT) tdelta.tv_sec + ((CKFLOAT) tdelta.tv_usec / 1000000.0);
  11599.     if (s < GFMINTIME)
  11600.       s = GFMINTIME;
  11601. #ifdef DEBUG
  11602.     if (deblog) {
  11603.     sprintf(fpbuf,"%f",s);
  11604.     debug(F110,"gftimer",fpbuf,0);
  11605.     }
  11606. #endif /* DEBUG */
  11607.     return(s);
  11608. }
  11609. #endif /* GFTIMER */
  11610.  
  11611. /*  Z T I M E  --  Return asctime()-format date/time string  */
  11612. /*
  11613.   NOTE: as a side effect of calling this routine, we can also set the
  11614.   following two variables, giving the micro- and milliseconds (fractions of
  11615.   seconds) of the clock time.  Currently this is done only in BSD-based builds
  11616.   that use gettimeofday().  When these variables are not filled in, they are
  11617.   left with a value of -1L.
  11618. */
  11619. static char asctmbuf[64];
  11620.  
  11621. VOID
  11622. ztime(s) char **s; {
  11623.  
  11624. #ifdef GFTIMER
  11625. /*
  11626.   The gettimeofday() method, which also sets ztmsec and ztusec, works for
  11627.   all GFTIMER builds.  NOTE: ztmsec and ztusec are defined in ckcmai.c,
  11628.   and extern declarations for them are in ckcdeb.h; thus they are
  11629.   declared in this file by inclusion of ckcdeb.h.
  11630. */
  11631.     char *asctime();
  11632.     struct tm *localtime();
  11633.     struct tm *tp;
  11634.     ztmsec = -1L;
  11635.     ztusec = -1L;
  11636.  
  11637.     if (!s)
  11638.       debug(F100,"ztime s==NULL","",0);
  11639.  
  11640. #ifdef GTODONEARG
  11641.     /* No 2nd arg in Motorola SV88 and some others */
  11642.     if (gettimeofday(&tv) > -1)
  11643. #else
  11644. #ifndef COHERENT
  11645. #ifdef PTX
  11646.     if (gettimeofday(&tv,NULL) > -1)
  11647. #else
  11648. #ifdef NOTIMEZONE
  11649.     if (gettimeofday(&tv, NULL) > -1)    /* wonder what this does... */
  11650. #else
  11651.     if (gettimeofday(&tv, &tz) > -1)
  11652. #endif /* NOTIMEZONE */
  11653. #endif /* PTX */
  11654. #endif /* COHERENT */
  11655. #endif /* GTODONEARG */
  11656.       {                    /* Fill in tm struct */
  11657.     ztusec = tv.tv_usec;        /* Microseconds */
  11658.     ztmsec = ztusec / 1000L;    /* Milliseconds */
  11659. #ifdef HPUX9
  11660.     {
  11661.         time_t zz;
  11662.         zz = tv.tv_sec;
  11663.         tp = localtime(&zz);    /* Convert to local time */
  11664.     }
  11665. #else
  11666. #ifdef HPUX1000
  11667.     {
  11668.         time_t zz;
  11669.         zz = tv.tv_sec;
  11670.         tp = localtime(&zz);
  11671.     }
  11672. #else
  11673. #ifdef LINUX
  11674.     {   /* avoid unaligned access trap on 64-bit platforms */
  11675.         time_t zz;
  11676.         zz = tv.tv_sec;
  11677.         tp = localtime(&zz);
  11678.     }
  11679. #else
  11680. #ifdef MACOSX
  11681.     tp = localtime((time_t *)&tv.tv_sec); /* Convert to local time */
  11682. #else
  11683.     tp = localtime(&tv.tv_sec);
  11684. #endif /* MACOSX */
  11685. #endif /* LINUX */
  11686. #endif /* HPUX1000 */
  11687. #endif /* HPUX9 */
  11688.     if (s) {
  11689.         char * s2;
  11690.         s2 = asctime(tp);        /* Convert result to ASCII string */
  11691.         asctmbuf[0] = '\0';
  11692.         if (s2) ckstrncpy(asctmbuf,s2,64);
  11693.         *s = asctmbuf;
  11694.         debug(F111,"ztime GFTIMER gettimeofday",*s,ztusec);
  11695.     }
  11696.     }
  11697. #else  /* Not GFTIMER */
  11698.  
  11699. #undef ZTIMEV7                /* Which systems need to use */
  11700. #ifdef COHERENT                /* old UNIX Version 7 way... */
  11701. #define ZTIMEV7
  11702. #endif /* COHERENT */
  11703. #ifdef TOWER1
  11704. #define ZTIMEV7
  11705. #endif /* TOWER1 */
  11706. #ifdef ANYBSD
  11707. #ifndef BSD42
  11708. #define ZTIMEV7
  11709. #endif /* BSD42 */
  11710. #endif /* ANYBSD */
  11711. #ifdef V7
  11712. #ifndef MINIX
  11713. #define ZTIMEV7
  11714. #endif /* MINIX */
  11715. #endif /* V7 */
  11716. #ifdef POSIX
  11717. #define ZTIMEV7
  11718. #endif /* POSIX */
  11719.  
  11720. #ifdef HPUX1020
  11721. /*
  11722.   Prototypes are in <time.h>, included above.
  11723. */
  11724.     time_t clock_storage;
  11725.     clock_storage = time((void *) 0);
  11726.     if (s) {
  11727.     *s = ctime(&clock_storage);
  11728.     debug(F110,"ztime: HPUX 10.20",*s,0);
  11729.     }
  11730. #else
  11731. #ifdef ATTSV                /* AT&T way */
  11732. /*  extern long time(); */        /* Theoretically these should */
  11733.     char *ctime();            /* already been dcl'd in <time.h> */
  11734.     time_t clock_storage;
  11735.     clock_storage = time(
  11736. #ifdef IRIX60
  11737.              (time_t *)
  11738. #else
  11739. #ifdef BSD44
  11740.              (time_t *)
  11741. #else
  11742.              (long *)
  11743. #endif /* BSD44 */
  11744. #endif /* IRIX60 */
  11745.              0 );
  11746.     if (s) {
  11747.     *s = ctime( &clock_storage );
  11748.     debug(F110,"ztime: ATTSV",*s,0);
  11749.     }
  11750. #else
  11751. #ifdef PROVX1                /* Venix 1.0 way */
  11752.     int utime[2];
  11753.     time(utime);
  11754.     if (s) {
  11755.     *s = ctime(utime);
  11756.     debug(F110,"ztime: PROVX1",*s,0);
  11757.     }
  11758. #else
  11759. #ifdef BSD42                /* 4.2BSD way */
  11760.     char *asctime();
  11761.     struct tm *localtime();
  11762.     struct tm *tp;
  11763.     gettimeofday(&tv, &tz);
  11764.     ztusec = tv.tv_usec;
  11765.     ztmsec = tv.tv_usec / 1000L;
  11766.     tp = localtime(&tv.tv_sec);
  11767.     if (s) {
  11768.     *s = asctime(tp);
  11769.     debug(F111,"ztime: BSD42",*s,ztusec);
  11770.     }
  11771. #else
  11772. #ifdef MINIX                /* MINIX way */
  11773. #ifdef COMMENT
  11774.     extern long time();            /* Already got these from <time.h> */
  11775.     extern char *ctime();
  11776. #endif /* COMMENT */
  11777.     time_t utime[2];
  11778.     time(utime);
  11779.     if (s) {
  11780.     *s = ctime(utime);
  11781.     debug(F110,"ztime: MINIX",*s,0);
  11782.     }
  11783. #else
  11784. #ifdef ZTIMEV7                /* The regular way */
  11785.     char *asctime();
  11786.     struct tm *localtime();
  11787.     struct tm *tp;
  11788.     long xclock;            /* or unsigned long for BeBox? */
  11789.     time(&xclock);
  11790.     tp = localtime(&xclock);
  11791.     if (s) {
  11792.     *s = asctime(tp);
  11793.     debug(F110,"ztime: ZTIMEV7",*s,0);
  11794.     }
  11795. #else                    /* Catch-all for others... */
  11796.     if (s) {
  11797.     *s = "Day Mon 00 00:00:00 0000\n"; /* Dummy in asctime() format */
  11798.     debug(F110,"ztime: catch-all",*s,0);
  11799.     }
  11800. #endif /* ZTIMEV7 */
  11801. #endif /* MINIX */
  11802. #endif /* BSD42 */
  11803. #endif /* PROVX1 */
  11804. #endif /* ATTSV */
  11805. #endif /* HPUX1020 */
  11806. #endif /* GFTIMER */
  11807. }
  11808.  
  11809. /*  C O N G M  --  Get console terminal modes.  */
  11810.  
  11811. /*
  11812.   Saves initial console mode, and establishes variables for switching
  11813.   between current (presumably normal) mode and other modes.
  11814.   Should be called when program starts, but only after establishing
  11815.   whether program is in the foreground or background.
  11816.   Returns 1 if it got the modes OK, 0 if it did nothing, -1 on error.
  11817. */
  11818. int
  11819. congm() {
  11820.     int fd;
  11821.     if (backgrd || !isatty(0)) {    /* If in background. */
  11822.     cgmf = -1;            /* Don't bother, modes are garbage. */
  11823.     return(-1);
  11824.     }
  11825.     if (cgmf > 0) return(0);        /* Already did this. */
  11826.     debug(F100,"congm getting modes","",0); /* Need to do it. */
  11827. #ifdef aegis
  11828.     ios_$inq_type_uid(ios_$stdin, conuid, st);
  11829.     if (st.all != status_$ok) {
  11830.     fprintf(stderr, "problem getting stdin objtype: ");
  11831.     error_$print(st);
  11832.     }
  11833.     concrp = (conuid == mbx_$uid);
  11834.     conbufn = 0;
  11835. #endif /* aegis */
  11836.  
  11837. #ifndef BEBOX
  11838.     if ((fd = open(CTTNAM,2)) < 0) {    /* Open controlling terminal */
  11839. #ifdef COMMENT
  11840.     fprintf(stderr,"Error opening %s\n", CTTNAM);
  11841.     perror("congm");
  11842.     return(-1);
  11843. #else
  11844.     fd = 0;
  11845. #endif /* COMMENT */
  11846.     }
  11847. #else
  11848.     fd = 0;
  11849. #endif /* !BEBOX */
  11850. #ifdef BSD44ORPOSIX
  11851.     if (tcgetattr(fd,&ccold) < 0) return(-1);
  11852.     if (tcgetattr(fd,&cccbrk) < 0) return(-1);
  11853.     if (tcgetattr(fd,&ccraw) < 0) return(-1);
  11854. #else
  11855. #ifdef ATTSV
  11856.     if (ioctl(fd,TCGETA,&ccold)  < 0) return(-1);
  11857.     if (ioctl(fd,TCGETA,&cccbrk) < 0) return(-1);
  11858.     if (ioctl(fd,TCGETA,&ccraw)  < 0) return(-1);
  11859. #ifdef VXVE
  11860.     cccbrk.c_line = 0;            /* STTY line 0 for CDC VX/VE */
  11861.     if (ioctl(fd,TCSETA,&cccbrk) < 0) return(-1);
  11862.     ccraw.c_line = 0;            /* STTY line 0 for CDC VX/VE */
  11863.     if (ioctl(fd,TCSETA,&ccraw) < 0) return(-1);
  11864. #endif /* VXVE */
  11865. #else
  11866. #ifdef BELLV10
  11867.     if (ioctl(fd,TIOCGETP,&ccold) < 0) return(-1);
  11868.     if (ioctl(fd,TIOCGETP,&cccbrk) < 0) return(-1);
  11869.     if (ioctl(fd,TIOCGETP,&ccraw) < 0) return(-1);
  11870.     debug(F101,"cccbrk.sg_flags orig","", cccbrk.sg_flags);
  11871. #else
  11872.     if (gtty(fd,&ccold) < 0) return(-1);
  11873.     if (gtty(fd,&cccbrk) < 0) return(-1);
  11874.     if (gtty(fd,&ccraw) < 0) return(-1);
  11875. #endif /* BELLV10 */
  11876. #endif /* ATTSV */
  11877. #endif /* BSD44ORPOSIX */
  11878. #ifdef sony_news            /* Sony NEWS */
  11879.     if (ioctl(fd,TIOCKGET,&km_con) < 0) { /* Get console Kanji mode */
  11880.     perror("congm error getting Kanji mode");
  11881.     debug(F101,"congm error getting Kanji mode","",0);
  11882.     km_con = -1;            /* Make sure this stays undefined. */
  11883.     return(-1);
  11884.     }
  11885. #endif /* sony_news */
  11886.     if (fd > 0)
  11887.       close(fd);
  11888.     cgmf = 1;                /* Flag that we got them. */
  11889.     return(1);
  11890. }
  11891.  
  11892.  
  11893. static VOID
  11894. congetbuf(x) int x; {
  11895.     int n;
  11896.     n = CONBUFSIZ - (conbufp - conbuf);    /* How much room left in buffer? */
  11897.     if (x > n) {
  11898.     debug(F101,"congetbuf char loss","",x-n);
  11899.     x = n;
  11900.     }
  11901.     x = read(0,conbufp,x);
  11902.     conbufn += x;
  11903.     debug(F111,"congetbuf readahead",conbuf,x);
  11904. }
  11905.  
  11906.  
  11907. /*  C O N C B --  Put console in cbreak mode.  */
  11908.  
  11909. /*  Returns 0 if ok, -1 if not  */
  11910.  
  11911. int
  11912. #ifdef CK_ANSIC
  11913. concb(char esc)
  11914. #else
  11915. concb(esc) char esc;
  11916. #endif /* CK_ANSIC */
  11917. /* concb */ {
  11918.     int x;
  11919.     debug(F101,"concb constate","",constate);
  11920.     debug(F101,"concb cgmf","",cgmf);
  11921.     debug(F101,"concb backgrd","",backgrd);
  11922.  
  11923.     if (constate == CON_CB)
  11924.       return(0);
  11925.  
  11926.     if (cgmf < 1)            /* Did we get console modes yet? */
  11927.       if (!backgrd)            /* No, in background? */
  11928.     congm();            /* No, try to get them now. */
  11929.     if (cgmf < 1)            /* Still don't have them? */
  11930.       return(0);            /* Give up. */
  11931.     debug(F101,"concb ttyfd","",ttyfd);
  11932.     debug(F101,"concb ttfdflg","",ttfdflg);
  11933. #ifdef COMMENT
  11934.     /* This breaks returning to prompt after protocol with "-l 0" */
  11935.     /* Commented out July 1998 */
  11936.     if (ttfdflg && ttyfd >= 0 && ttyfd < 3)
  11937.       return(0);
  11938. #endif /* COMMENT */
  11939.     x = isatty(0);
  11940.     debug(F101,"concb isatty","",x);
  11941.     if (!x) return(0);            /* Only when running on real ttys */
  11942.     debug(F101,"concb xsuspend","",xsuspend);
  11943.     if (backgrd)            /* Do nothing if in background. */
  11944.       return(0);
  11945.     escchr = esc;                       /* Make this available to other fns */
  11946.     ckxech = 1;                         /* Program can echo characters */
  11947. #ifdef aegis
  11948.     conbufn = 0;
  11949.     if (concrp) return(write(1, "\035\002", 2));
  11950.     if (conuid == input_pad_$uid) {pad_$raw(ios_$stdin, st); return(0);}
  11951. #endif /* aegis */
  11952.  
  11953. #ifdef COHERENT
  11954. #define SVORPOSIX
  11955. #endif /* COHERENT */
  11956.  
  11957. #ifdef Plan9
  11958.     x = p9concb();
  11959. #else
  11960. #ifndef SVORPOSIX            /* BSD, V7, etc */
  11961.     debug(F101,"cccbrk.sg_flags concb 1","", cccbrk.sg_flags);
  11962.     debug(F101,"concb stty CBREAK","",0);
  11963.     cccbrk.sg_flags |= (CBREAK|CRMOD);    /* Set to character wakeup, */
  11964.     cccbrk.sg_flags &= ~ECHO;           /* no echo. */
  11965.     debug(F101,"cccbrk.sg_flags concb 2","", cccbrk.sg_flags);
  11966.     errno = 0;
  11967. /*
  11968.   BSD stty() clears the console buffer.  So if anything is waiting in it,
  11969.   we have to read it now to avoid losing it.
  11970. */
  11971.     x = conchk();
  11972.     if (x > 0)
  11973.       congetbuf(x);
  11974.  
  11975. #ifdef BELLV10
  11976.     x = ioctl(0,TIOCSETP,&cccbrk);
  11977. #else
  11978.     x = stty(0,&cccbrk);
  11979.     debug(F101,"cccbrk.sg_flags concb x","", x);
  11980. #endif /* BELLV10 */
  11981. #else                    /* Sys V and POSIX */
  11982. #ifndef OXOS
  11983.     debug(F101,"concb cccbrk.c_flag","",cccbrk.c_lflag);
  11984. #ifdef QNX
  11985.     /* Don't mess with IEXTEN */
  11986.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  11987. #else
  11988. #ifdef COHERENT
  11989.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  11990. #else
  11991.     cccbrk.c_lflag &= ~(ICANON|ECHO|IEXTEN);
  11992. #endif /* COHERENT */
  11993. #endif /* QNX */
  11994.     cccbrk.c_lflag |= ISIG;        /* Allow signals in command mode. */
  11995.     cccbrk.c_iflag |= IGNBRK;        /* But ignore BREAK signal */
  11996.     cccbrk.c_iflag &= ~BRKINT;
  11997.  
  11998. #else /* OXOS */
  11999.     debug(F100,"concb OXOS is defined","",0);
  12000.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  12001.     cccbrk.c_cc[VDISCARD] = cccbrk.c_cc[VLNEXT] = CDISABLE;
  12002. #endif /* OXOS */
  12003. #ifdef COMMENT
  12004. /*
  12005.   Believe it or not, in SCO UNIX, VSUSP is greater than NCC, and so this
  12006.   array reference is out of bounds.  It's only a debug() call so who needs it.
  12007. */
  12008. #ifdef VSUSP
  12009.     debug(F101,"concb c_cc[VSUSP]","",cccbrk.c_cc[VSUSP]);
  12010. #endif /* VSUSP */
  12011. #endif /* COMMENT */
  12012. #ifndef VINTR
  12013.     debug(F101,"concb c_cc[0]","",cccbrk.c_cc[0]);
  12014.     cccbrk.c_cc[0] = 003;               /* Interrupt char is Control-C */
  12015. #else
  12016.     debug(F101,"concb c_cc[VINTR]","",cccbrk.c_cc[0]);
  12017.     cccbrk.c_cc[VINTR] = 003;
  12018. #endif /* VINTR */
  12019. #ifndef VQUIT
  12020.     cccbrk.c_cc[1] = escchr;            /* escape during packet modes */
  12021. #else
  12022.     cccbrk.c_cc[VQUIT] = escchr;
  12023. #endif /* VQUIT */
  12024. #ifndef VEOF
  12025.     cccbrk.c_cc[4] = 1;
  12026. #else
  12027. #ifndef OXOS
  12028. #ifdef VMIN
  12029.     cccbrk.c_cc[VMIN] = 1;
  12030. #endif /* VMIN */
  12031. #else /* OXOS */
  12032.     cccbrk.c_min = 1;
  12033. #endif /* OXOS */
  12034. #endif /* VEOF */
  12035. #ifdef ZILOG
  12036.     cccbrk.c_cc[5] = 0;
  12037. #else
  12038. #ifndef VEOL
  12039.     cccbrk.c_cc[5] = 1;
  12040. #else
  12041. #ifndef OXOS
  12042. #ifdef VTIME
  12043.     cccbrk.c_cc[VTIME] = 1;
  12044. #endif /* VTIME */
  12045. #else /* OXOS */
  12046.     cccbrk.c_time = 1;
  12047. #endif /* OXOS */
  12048. #endif /* VEOL */
  12049. #endif /* ZILOG */
  12050.     errno = 0;
  12051. #ifdef BSD44ORPOSIX            /* Set new modes */
  12052.     x = tcsetattr(0,TCSADRAIN,&cccbrk);
  12053. #else /* ATTSV */                  /* or the POSIX way */
  12054.     x = ioctl(0,TCSETAW,&cccbrk);    /* the Sys V way */
  12055. #endif /* BSD44ORPOSIX */
  12056. #endif /* SVORPOSIX */
  12057.  
  12058. #ifdef COHERENT
  12059. #undef SVORPOSIX
  12060. #endif /* COHERENT */
  12061.     debug(F101,"concb x","",x);
  12062.     debug(F101,"concb errno","",errno);
  12063. #ifdef NONOSETBUF
  12064.     if (x > -1) {
  12065.     setbuf(stdout,NULL);    /* Make console unbuffered. */
  12066.     debug(F100,"concb setbuf A","",0);
  12067.     }
  12068. #else
  12069. #ifndef aegis
  12070. #ifndef NOSETBUF
  12071.     if (x > -1) {
  12072.     setbuf(stdout,NULL);    /* Make console unbuffered. */
  12073.     debug(F100,"concb setbuf B","",0);
  12074.     }
  12075. #endif /* NOSETBUF */
  12076. #endif /* aegis */
  12077. #endif /* NONOSETBUF */
  12078.  
  12079. #ifdef  V7
  12080. #ifndef MINIX
  12081.     if (kmem[CON] < 0) {
  12082.         qaddr[CON] = initrawq(0);
  12083.         if((kmem[CON] = open("/dev/kmem", 0)) < 0) {
  12084.             fprintf(stderr, "Can't read /dev/kmem in concb.\n");
  12085.             perror("/dev/kmem");
  12086.             exit(1);
  12087.         }
  12088.     }
  12089. #endif /* MINIX */
  12090. #endif /* V7 */
  12091. #endif /* Plan9 */
  12092.  
  12093.     if (x > -1)
  12094.       constate = CON_CB;
  12095.  
  12096.     debug(F101,"concb returns","",x);
  12097.     return(x);
  12098. }
  12099.  
  12100. /*  C O N B I N  --  Put console in binary mode  */
  12101.  
  12102. /*  Returns 0 if ok, -1 if not  */
  12103.  
  12104. int
  12105. #ifdef CK_ANSIC
  12106. conbin(char esc)
  12107. #else
  12108. conbin(esc) char esc;
  12109. #endif /* CK_ANSIC */
  12110. /* conbin */  {
  12111.  
  12112.     int x;
  12113.  
  12114.     debug(F101,"conbin constate","",constate);
  12115.  
  12116.     if (constate == CON_BIN)
  12117.       return(0);
  12118.  
  12119.     if (!isatty(0)) return(0);          /* only for real ttys */
  12120.     congm();                /* Get modes if necessary. */
  12121.     debug(F100,"conbin","",0);
  12122.     escchr = esc;                       /* Make this available to other fns */
  12123.     ckxech = 1;                         /* Program can echo characters */
  12124. #ifdef aegis
  12125.     conbufn = 0;
  12126.     if (concrp) return(write(1, "\035\002", 2));
  12127.     if (conuid == input_pad_$uid) {
  12128.     pad_$raw(ios_$stdin, st);
  12129.     return(0);
  12130.       }
  12131. #endif /* aegis */
  12132.  
  12133. #ifdef COHERENT
  12134. #define SVORPOSIX
  12135. #endif /* COHERENT */
  12136.  
  12137. #ifdef Plan9
  12138.     return p9conbin();
  12139. #else
  12140. #ifdef SVORPOSIX
  12141. #ifndef OXOS
  12142. #ifdef QNX
  12143.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  12144. #else
  12145. #ifdef COHERENT
  12146.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  12147. #else
  12148.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO|IEXTEN);
  12149. #endif /* COHERENT */
  12150. #endif /* QNX */
  12151. #else /* OXOS */
  12152.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  12153.     ccraw.c_cc[VDISCARD] = ccraw.c_cc[VLNEXT] = CDISABLE;
  12154. #endif /* OXOS */
  12155.     ccraw.c_iflag |= IGNPAR;
  12156. /*
  12157.   Note that for terminal sessions we disable Xon/Xoff flow control to allow
  12158.   the passage ^Q and ^S as data characters for EMACS, and to allow XMODEM
  12159.   transfers to work when C-Kermit is in the middle, etc.  Hardware flow
  12160.   control, if in use, is not affected.
  12161. */
  12162. #ifdef ATTSV
  12163. #ifdef BSD44
  12164.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IXON|IXANY|IXOFF
  12165.                         |INPCK|ISTRIP);
  12166. #else
  12167.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IUCLC|IXON|IXANY|IXOFF
  12168.                         |INPCK|ISTRIP);
  12169. #endif /* BSD44 */
  12170. #else /* POSIX */
  12171.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IXON|IXOFF|INPCK|ISTRIP);
  12172. #endif /* ATTSV */
  12173.     ccraw.c_oflag &= ~OPOST;
  12174. #ifdef COMMENT
  12175. /*
  12176.   WHAT THE HECK WAS THIS FOR?
  12177.   The B9600 setting (obviously) prevents CONNECT from working at any
  12178.   speed other than 9600 when you are logged in to the 7300 on a serial
  12179.   line.  Maybe some of the other flags are necessary -- if so, put back
  12180.   the ones that are needed.  This code is supposed to work the same, no
  12181.   matter whether you are logged in to the 7300 on the real console device,
  12182.   or through a serial port.
  12183. */
  12184. #ifdef ATT7300
  12185.     ccraw.c_cflag = CLOCAL | B9600 | CS8 | CREAD | HUPCL;
  12186. #endif /* ATT7300 */
  12187. #endif /* COMMENT */
  12188.  
  12189. /*** Kermit used to put the console in 8-bit raw mode, but some users have
  12190.  *** pointed out that this should not be done, since some sites actually
  12191.  *** use terminals with parity settings on their Unix systems, and if we
  12192.  *** override the current settings and stop doing parity, then their terminals
  12193.  *** will display blotches for characters whose parity is wrong.  Therefore,
  12194.  *** the following two lines are commented out (Larry Afrin, Clemson U):
  12195.  ***
  12196.  ***   ccraw.c_cflag &= ~(PARENB|CSIZE);
  12197.  ***   ccraw.c_cflag |= (CS8|CREAD);
  12198.  ***
  12199.  *** Sys III/V sites that have trouble with this can restore these lines.
  12200.  ***/
  12201. #ifndef VINTR
  12202.     ccraw.c_cc[0] = 003;        /* Interrupt char is Ctrl-C */
  12203. #else
  12204.     ccraw.c_cc[VINTR] = 003;
  12205. #endif /* VINTR */
  12206. #ifndef VQUIT
  12207.     ccraw.c_cc[1] = escchr;        /* Escape during packet mode */
  12208. #else
  12209.     ccraw.c_cc[VQUIT] = escchr;
  12210. #endif /* VQUIT */
  12211. #ifndef VEOF
  12212.     ccraw.c_cc[4] = 1;
  12213. #else
  12214. #ifndef OXOS
  12215. #ifdef VMIN
  12216.     ccraw.c_cc[VMIN] = 1;
  12217. #endif /* VMIN */
  12218. #else /* OXOS */
  12219.     ccraw.c_min = 1;
  12220. #endif /* OXOS */
  12221. #endif /* VEOF */
  12222.  
  12223. #ifdef ZILOG
  12224.     ccraw.c_cc[5] = 0;
  12225. #else
  12226. #ifndef VEOL
  12227.     ccraw.c_cc[5] = 1;
  12228. #else
  12229. #ifndef OXOS
  12230. #ifdef VTIME
  12231.     ccraw.c_cc[VTIME] = 1;
  12232. #endif /* VTIME */
  12233. #else /* OXOS */
  12234.     ccraw.c_time = 1;
  12235. #endif /* OXOS */
  12236. #endif /* VEOL */
  12237. #endif /* ZILOG */
  12238.  
  12239. #ifdef BSD44ORPOSIX
  12240.     x = tcsetattr(0,TCSADRAIN,&ccraw);    /* Set new modes. */
  12241. #else
  12242.     x = ioctl(0,TCSETAW,&ccraw);
  12243. #endif /* BSD44ORPOSIX */
  12244. #else /* Berkeley, etc. */
  12245.     x = conchk();            /* Because stty() is destructive */
  12246.     if (x > 0)
  12247.       congetbuf(x);
  12248.     ccraw.sg_flags |= (RAW|TANDEM);     /* Set rawmode, XON/XOFF (ha) */
  12249.     ccraw.sg_flags &= ~(ECHO|CRMOD);    /* Set char wakeup, no echo */
  12250. #ifdef BELLV10
  12251.     x = ioctl(0,TIOCSETP,&ccraw);
  12252. #else
  12253.     x = stty(0,&ccraw);
  12254. #endif /* BELLV10 */
  12255. #endif /* SVORPOSIX */
  12256. #endif /* Plan9 */
  12257.  
  12258.     if (x > -1)
  12259.       constate = CON_BIN;
  12260.  
  12261.     debug(F101,"conbin returns","",x);
  12262.     return(x);
  12263.  
  12264. #ifdef COHERENT
  12265. #undef SVORPOSIX
  12266. #endif /* COHERENT */
  12267.  
  12268. }
  12269.  
  12270.  
  12271. /*  C O N R E S  --  Restore the console terminal  */
  12272.  
  12273. int
  12274. conres() {
  12275.     int x;
  12276.     debug(F101,"conres cgmf","",cgmf);
  12277.     debug(F101,"conres constate","",constate);
  12278.  
  12279.     if (cgmf < 1)            /* Do nothing if modes unchanged */
  12280.       return(0);
  12281.     if (constate == CON_RES)
  12282.       return(0);
  12283.  
  12284.     if (!isatty(0)) return(0);          /* only for real ttys */
  12285.     debug(F100,"conres isatty ok","",0);
  12286.     ckxech = 0;                         /* System should echo chars */
  12287.  
  12288. #ifdef aegis
  12289.     conbufn = 0;
  12290.     if (concrp) return(write(1, "\035\001", 2));
  12291.     if (conuid == input_pad_$uid) {
  12292.     pad_$cooked(ios_$stdin, st);
  12293.     constate = CON_RES;
  12294.     return(0);
  12295.     }
  12296. #endif /* aegis */
  12297.  
  12298. #ifdef Plan9
  12299.     p9conres();
  12300. #else
  12301. #ifdef BSD44ORPOSIX
  12302.     debug(F100,"conres restoring tcsetattr","",0);
  12303.     x = tcsetattr(0,TCSADRAIN,&ccold);
  12304. #else
  12305. #ifdef ATTSV
  12306.     debug(F100,"conres restoring ioctl","",0);
  12307.     x = ioctl(0,TCSETAW,&ccold);
  12308. #else /* BSD, V7, and friends */
  12309. #ifdef sony_news            /* Sony NEWS */
  12310.     if (km_con != -1)
  12311.       ioctl(0,TIOCKSET,&km_con);    /* Restore console Kanji mode */
  12312. #endif /* sony_news */
  12313.     msleep(100);
  12314.     debug(F100,"conres restoring stty","",0);
  12315.     x = conchk();            /* Because stty() is destructive */
  12316.     if (x > 0)
  12317.       congetbuf(x);
  12318. #ifdef BELLV10
  12319.     x = ioctl(0,TIOCSETP,&ccold);
  12320. #else
  12321.     x = stty(0,&ccold);
  12322. #endif /* BELLV10 */
  12323. #endif /* ATTSV */
  12324. #endif /* BSD44ORPOSIX */
  12325. #endif /* Plan9 */
  12326.     if (x > -1)
  12327.       constate = CON_RES;
  12328.  
  12329.     debug(F101,"conres returns","",x);
  12330.     return(x);
  12331. }
  12332.  
  12333. /*  C O N O C  --  Output a character to the console terminal  */
  12334.  
  12335. int
  12336. #ifdef CK_ANSIC
  12337. conoc(char c)
  12338. #else
  12339. conoc(c) char c;
  12340. #endif /* CK_ANSIC */
  12341. /* conoc */ {
  12342.  
  12343. #ifdef IKSD
  12344.     if (inserver && !local)
  12345.       return(ttoc(c));
  12346.  
  12347. #ifdef CK_ENCRYPTION
  12348.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  12349.         ck_tn_encrypt(&c,1);
  12350. #endif /* CK_ENCRYPTION */
  12351. #endif /* IKSD */
  12352.  
  12353. #ifdef Plan9
  12354.     return conwrite(&c,1);
  12355. #else
  12356.     return(write(1,&c,1));
  12357. #endif /* Plan9 */
  12358. }
  12359.  
  12360. /*  C O N X O  --  Write x characters to the console terminal  */
  12361.  
  12362. int
  12363. conxo(x,s) int x; char *s; {
  12364.  
  12365. #ifdef IKSD
  12366.     if (inserver && !local)
  12367.       return(ttol((CHAR *)s,x));
  12368.  
  12369. #ifdef CK_ENCRYPTION
  12370.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  12371.         ck_tn_encrypt(s,x);
  12372. #endif /* CK_ENCRYPTION */
  12373. #endif /* IKSD */
  12374.  
  12375. #ifdef Plan9
  12376.     return(conwrite(s,x));
  12377. #else
  12378.     return(write(1,s,x));
  12379. #endif /* Plan9 */
  12380. }
  12381.  
  12382. /*  C O N O L  --  Write a line to the console terminal  */
  12383.  
  12384. int
  12385. conol(s) char *s; {
  12386.     int len;
  12387.     if (!s) s = "";            /* Always do this! */
  12388.     len = strlen(s);
  12389.     if (len == 0)
  12390.       return(0);
  12391.  
  12392. #ifdef IKSD
  12393.     if (inserver && !local)
  12394.       return(ttol((CHAR *)s,len));
  12395.  
  12396. #ifdef CK_ENCRYPTION
  12397.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION)) {
  12398.     if (nxpacket < len) {
  12399.         if (xpacket) {
  12400.         free(xpacket);
  12401.         xpacket = NULL;
  12402.         nxpacket = 0;
  12403.         }
  12404.         len = len > 10240 ? len : 10240;
  12405.         xpacket = (char *)malloc(len);
  12406.         if (!xpacket) {
  12407.         fprintf(stderr,"ttol malloc failure\n");
  12408.         return(-1);
  12409.         } else
  12410.           nxpacket = len;
  12411.     }
  12412.     memcpy(xpacket,s,len);
  12413.     s = xpacket;
  12414.     ck_tn_encrypt(s,len);
  12415.     }
  12416. #endif /* CK_ENCRYPTION */
  12417. #endif /* IKSD */
  12418.  
  12419. #ifdef Plan9
  12420.     return(conwrite(s,len));
  12421. #else
  12422.     return(write(1,s,len));
  12423. #endif /* Plan9 */
  12424. }
  12425.  
  12426. /*  C O N O L A  --  Write an array of lines to the console terminal */
  12427.  
  12428. int
  12429. conola(s) char *s[]; {
  12430.     char * p;
  12431.     int i, x;
  12432.  
  12433.  
  12434.     if (!s) return(0);
  12435.     for (i = 0; ; i++) {
  12436.     p = s[i];
  12437.     if (!p) p = "";            /* Let's not dump core shall we? */
  12438.     if (!*p)
  12439.       break;
  12440. #ifdef IKSD
  12441.     if (inserver && !local)
  12442.       x = ttol((CHAR *)p,(int)strlen(p));
  12443.     else
  12444. #endif /* IKSD */
  12445.       x = conol(p);
  12446.     if (x < 0)
  12447.       return(-1);
  12448.     }
  12449.     return(0);
  12450. }
  12451.  
  12452. /*  C O N O L L  --  Output a string followed by CRLF  */
  12453.  
  12454. int
  12455. conoll(s) char *s; {
  12456.     CHAR buf[3];
  12457.     buf[0] = '\r';
  12458.     buf[1] = '\n';
  12459.     buf[2] = '\0';
  12460.     if (!s) s = "";
  12461.  
  12462. #ifdef IKSD
  12463.     if (inserver && !local) {
  12464.     if (*s) ttol((CHAR *)s,(int)strlen(s));
  12465.     return(ttol(buf,2));
  12466.     }
  12467. #endif /* IKSD */
  12468.  
  12469.     if (*s) conol(s);
  12470. #ifdef IKSD
  12471. #ifdef CK_ENCRYPTION
  12472.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  12473.       ck_tn_encrypt(buf,2);
  12474. #endif /* CK_ENCRYPTION */
  12475. #endif /* IKSD */
  12476.  
  12477. #ifdef Plan9
  12478.     return(conwrite(buf, 2));
  12479. #else
  12480.     return(write(1,buf,2));
  12481. #endif /* Plan9 */
  12482. }
  12483.  
  12484. /*  C O N C H K  --  Return how many characters available at console  */
  12485. /*
  12486.   We could also use select() here to cover a few more systems that are not
  12487.   covered by any of the following, e.g. HP-UX 9.0x on the model 800.
  12488. */
  12489. int
  12490. conchk() {
  12491.     static int contyp = 0;        /* +1 for isatty, -1 otherwise */
  12492.  
  12493.     if (contyp == 0)            /* This prevents unnecessary */
  12494.       contyp = (isatty(0) ? 1 : -1);    /* duplicated calls to isatty() */
  12495.     debug(F101,"conchk contyp","",contyp);
  12496.     if (backgrd || (contyp < 0))
  12497.       return(0);
  12498.  
  12499. #ifdef aegis
  12500.     if (conbufn > 0) return(conbufn);   /* use old count if nonzero */
  12501.  
  12502.     /* read in more characters */
  12503.     conbufn = ios_$get(ios_$stdin,
  12504.               ios_$cond_opt, conbuf, (long)sizeof(conbuf), st);
  12505.     if (st.all != status_$ok) conbufn = 0;
  12506.     conbufp = conbuf;
  12507.     return(conbufn);
  12508. #else
  12509. #ifdef IKSD
  12510.     if (inserver && !local)
  12511.       return(in_chk(1,ttyfd));
  12512.     else
  12513. #endif /* IKSD */
  12514.       return(in_chk(0,0));
  12515. #endif /* aegis */
  12516. }
  12517.  
  12518. /*  C O N I N C  --  Get a character from the console  */
  12519. /*
  12520.   Call with timo > 0 to do a timed read, timo == 0 to do an untimed blocking
  12521.   read.  Upon success, returns the character.  Upon failure, returns -1.
  12522.   A timed read that does not complete within the timeout period returns -2.
  12523. */
  12524. int
  12525. coninc(timo) int timo; {
  12526.     int n = 0; CHAR ch;
  12527.     int xx;
  12528.  
  12529.     if (conbufn > 0) {            /* If something already buffered */
  12530.     --conbufn;
  12531.     return((unsigned)(*conbufp++ & 0xff));
  12532.     }
  12533.  
  12534.     errno = 0;                /* Clear this */
  12535. #ifdef IKSD
  12536.     if (inserver && !local) {
  12537.     xx = ttinc(timo);
  12538.     if (xx < 0)
  12539.       return(ttinctimo ? -2 : -1);
  12540.     else
  12541.       return(xx);
  12542.     }
  12543. #endif /* IKSD */
  12544.  
  12545. #ifdef aegis                /* Apollo Aegis only... */
  12546.     debug(F101,"coninc timo","",timo);
  12547.     fflush(stdout);
  12548.     if (conchk() > 0) {
  12549.     --conbufn;
  12550.     return((unsigned)(*conbufp++ & 0xff));
  12551.     }
  12552. #endif /* aegis */
  12553.  
  12554. #ifdef TTLEBUF
  12555.     if (
  12556. #ifdef IKSD
  12557.     inserver &&
  12558. #endif /* IKSD */
  12559.     !xlocal
  12560.     ) {
  12561.     if (ttpush >= 0) {
  12562.         debug(F111,"ttinc","ttpush",ttpush);
  12563.         ch = ttpush;
  12564.         ttpush = -1;
  12565.         return(ch);
  12566.     }
  12567.     if (le_data) {
  12568.         if (le_getchar(&ch) > 0) {
  12569.         debug(F111,"ttinc LocalEchoInBuf","ch",ch);
  12570.         return(ch);
  12571.         }
  12572.     }
  12573.     }
  12574. #endif /* TTLEBUF */
  12575.  
  12576.     if (timo <= 0) {            /* Untimed, blocking read. */
  12577.     while (1) {            /* Keep trying till we get one. */
  12578.         n = read(0, &ch, 1);    /* Read a character. */
  12579.         if (n == 0) continue;    /* Shouldn't happen. */
  12580.         if (n > 0) {        /* If read was successful, */
  12581. #ifdef IKSD
  12582. #ifdef CK_ENCRYPTION
  12583.                 debug(F100,"coninc decrypt 1","",0);
  12584.                 if (inserver && !local && TELOPT_U(TELOPT_ENCRYPTION))
  12585.           ck_tn_decrypt(&ch,1);
  12586. #endif /* CK_ENCRYPTION */
  12587. #endif /* IKSD */
  12588.         return((unsigned)(ch & 0xff)); /* return the character. */
  12589.             }
  12590.  
  12591. /* Come here if read() returned an error. */
  12592.  
  12593.         debug(F101, "coninc(0) errno","",errno); /* Log the error. */
  12594. #ifndef OXOS
  12595. #ifdef SVORPOSIX
  12596. #ifdef CIE                             /* CIE Regulus has no EINTR symbol? */
  12597. #ifndef EINTR
  12598. #define EINTR 4
  12599. #endif /* EINTR */
  12600. #endif /* CIE */
  12601. /*
  12602.   This routine is used for several different purposes.  In CONNECT mode, it is
  12603.   used to do an untimed, blocking read from the keyboard in the lower CONNECT
  12604.   fork.  During local-mode file transfer, it reads a character from the
  12605.   console to interrupt the file transfer (like A for a status report, X to
  12606.   cancel a file, etc).  Obviously, we don't want the reads in the latter case
  12607.   to be blocking, or the file transfer would stop until the user typed
  12608.   something.  Unfortunately, System V does not allow the console device input
  12609.   buffer to be sampled nondestructively (e.g. by conchk()), so a kludge is
  12610.   used instead.  During local-mode file transfer, the SIGQUIT signal is armed
  12611.   and trapped by esctrp(), and this routine pretends to have read the quit
  12612.   character from the keyboard normally.  But, kludge or no kludge, the read()
  12613.   issued by this command, under System V only, can fail if a signal -- ANY
  12614.   signal -- is caught while the read is pending.  This can occur not only when
  12615.   the user types the quit character, but also during telnet negotiations, when
  12616.   the lower CONNECT fork signals the upper one about an echoing mode change.
  12617.   When this happens, we have to post the read() again.  This is apparently not
  12618.   a problem in BSD-based UNIX versions.
  12619. */
  12620.         if (errno == EINTR)        /* Read interrupted. */
  12621.           if (conesc)  {        /* If by SIGQUIT, */
  12622.           conesc = 0;        /* the conesc variable is set, */
  12623.           return(escchr);    /* so return the escape character. */
  12624.          } else continue;        /* By other signal, try again. */
  12625. #else
  12626. /*
  12627.   This might be dangerous, but let's do this on non-System V versions too,
  12628.   since at least one SunOS 4.1.2 user complains of immediate disconnections
  12629.   upon first making a TELNET connection.
  12630. */
  12631.         if (errno == EINTR)        /* Read interrupted. */
  12632.           continue;
  12633. #endif /* SVORPOSIX */
  12634. #else /* OXOS */
  12635.         if (errno == EINTR)        /* Read interrupted. */
  12636.           continue;
  12637. #endif /* OXOS */
  12638.         return(-1);            /* Error */
  12639.     }
  12640.     }
  12641. #ifdef DEBUG
  12642.     if (deblog && timo <= 0) {
  12643.     debug(F100,"coninc timeout logic error","",0);
  12644.     timo = 1;
  12645.     }
  12646. #endif /* DEBUG */
  12647.  
  12648. /* Timed read... */
  12649.  
  12650.     saval = signal(SIGALRM,timerh);    /* Set up timeout handler. */
  12651.     xx = alarm(timo);            /* Set the alarm. */
  12652.     debug(F101,"coninc alarm set","",timo);
  12653.     if (
  12654. #ifdef CK_POSIX_SIG
  12655.     sigsetjmp(sjbuf,1)
  12656. #else
  12657.     setjmp(sjbuf)
  12658. #endif /* CK_POSIX_SIG */
  12659.     )                /* The read() timed out. */
  12660.       n = -2;                /* Code for timeout. */
  12661.     else
  12662.       n = read(0, &ch, 1);
  12663.     ttimoff();                /* Turn off timer */
  12664.     if (n > 0) {            /* Got character OK. */
  12665. #ifdef IKSD
  12666. #ifdef CK_ENCRYPTION
  12667.         debug(F100,"coninc decrypt 2","",0);
  12668.         if (inserver && !local && TELOPT_U(TELOPT_ENCRYPTION))
  12669.       ck_tn_decrypt(&ch,1);
  12670. #endif /* CK_ENCRYPTION */
  12671. #endif /* IKSD */
  12672.     return((unsigned)(ch & 0xff));    /* Return it. */
  12673.     }
  12674. /*
  12675.   read() returned an error.  Same deal as above, but without the loop.
  12676. */
  12677.     debug(F101, "coninc(timo) n","",n);
  12678.     debug(F101, "coninc(timo) errno","",errno);
  12679. #ifndef OXOS
  12680. #ifdef SVORPOSIX
  12681.     if (n == -1 && errno == EINTR && conesc != 0) {
  12682.     conesc = 0;
  12683.     return(escchr);            /* User entered escape character. */
  12684.     }
  12685. #endif /* SVORPOSIX */
  12686.     if (n == 0 && errno > 0) {        /* It's an error */
  12687.     return(-1);
  12688.     }
  12689. #endif /* ! OXOS */
  12690.     return(n);
  12691. }
  12692.  
  12693. /*  C O N G K S  --  Console Get Keyboard Scancode  */
  12694.  
  12695. #ifndef congks
  12696. /*
  12697.   This function needs to be filled in with the various system-dependent
  12698.   system calls used by SUNOS, NeXT OS, Xenix, Aviion, etc, to read a full
  12699.   keyboard scan code.  Unfortunately there aren't any.
  12700. */
  12701. int
  12702. congks(timo) int timo; {
  12703.  
  12704. #ifdef IKSD
  12705.     if (inserver && !local)
  12706.       return(ttinc(timo));
  12707. #endif /* IKSD */
  12708.  
  12709.     return(coninc(timo));
  12710. }
  12711. #endif /* congks */
  12712.  
  12713. #ifdef ATT7300
  12714.  
  12715. /*  A T T D I A L  --  Dial up the remote system using internal modem
  12716.  * Purpose: to open and dial a number on the internal modem available on the
  12717.  * ATT7300 UNIX PC.  Written by Joe Doupnik. Superceeds version written by
  12718.  * Richard E. Hill, Dickinson, TX. which employed dial(3c).
  12719.  * Uses information in <sys/phone.h> and our status int attmodem.
  12720.  */
  12721. attdial(ttname,speed,telnbr) char *ttname,*telnbr; long speed; {
  12722.     char *telnum;
  12723.  
  12724.     attmodem &= ~ISMODEM;                       /* modem not in use yet */
  12725.                     /* Ensure O_NDELAY is set, else i/o traffic hangs */
  12726.                     /* We turn this flag off once the dial is complete */
  12727.     fcntl(ttyfd, F_SETFL, fcntl(ttyfd, F_GETFL, 0) | O_NDELAY);
  12728.  
  12729.     /* Condition line, check availability & DATA mode, turn on speaker */
  12730.     if (ioctl(ttyfd,PIOCOFFHOOK, &dialer) == -1) {
  12731.         printf("cannot access phone\n");
  12732.         ttclos(0);
  12733.         return (-2);
  12734.     }
  12735.     ioctl(ttyfd,PIOCGETP,&dialer);      /* get phone dialer parameters */
  12736.  
  12737.     if (dialer.c_lineparam & VOICE) {    /* phone must be in DATA mode */
  12738.         printf(" Should not dial with modem in VOICE mode.\n");
  12739.         printf(" Exit Kermit, switch to DATA and retry call.\n");
  12740.         ttclos(0);
  12741.         return (-2);
  12742.     }
  12743. #ifdef ATTTONED                /* Old way, tone dialing only. */
  12744.     dialer.c_lineparam = DATA | DTMF;    /* Dial with tones, */
  12745.     dialer.c_lineparam &= ~PULSE;    /* not with pulses. */
  12746. #else
  12747.     /* Leave current pulse/tone state alone. */
  12748.     /* But what about DATA?  Add it back if you have trouble. */
  12749.     /* sys/phone says you get DATA automatically by opening device RDWR */
  12750. #endif
  12751.     dialer.c_waitdialtone = 5;                  /* wait 5 sec for dialtone */
  12752. #ifdef COMMENT
  12753.     dialer.c_feedback = SPEAKERON|NORMSPK|RINGON;  /* control speaker */
  12754. #else
  12755.     /* sys/phone says RINGON used only for incoming voice calls */
  12756.     dialer.c_feedback &= ~(SOFTSPK|LOUDSPK);
  12757.     dialer.c_feedback |= SPEAKERON|NORMSPK;
  12758. #endif
  12759.     dialer.c_waitflash = 500;                   /* 0.5 sec flash hook */
  12760.     if(ioctl(ttyfd,PIOCSETP,&dialer) == -1) {   /* set phone parameters */
  12761.         printf("Cannot set modem characteristics\n");
  12762.         ttclos(0);
  12763.         return (-2);
  12764.     }
  12765.     ioctl(ttyfd,PIOCRECONN,0);        /* Turns on speaker for pulse */
  12766.  
  12767. #ifdef COMMENT
  12768.     fprintf(stderr,"Phone line status. line_par:%o dialtone_wait:%o \
  12769. line_status:%o feedback:%o\n",
  12770.     dialer.c_lineparam, dialer.c_waitdialtone,
  12771.     dialer.c_linestatus, dialer.c_feedback);
  12772. #endif
  12773.  
  12774.     attmodem |= ISMODEM;                        /* modem is now in-use */
  12775.     sleep(1);
  12776.     for (telnum = telnbr; *telnum != '\0'; telnum++)    /* dial number */
  12777. #ifdef ATTTONED
  12778.       /* Tone dialing only */
  12779.       if (ioctl(ttyfd,PIOCDIAL,telnum) != 0) {
  12780.       perror("Error in dialing");
  12781.       ttclos(0);
  12782.       return(-2);
  12783.       }
  12784. #else /* Allow Pulse or Tone dialing */
  12785.     switch (*telnum) {
  12786.       case 't': case 'T': case '%':    /* Tone dialing requested */
  12787.     dialer.c_lineparam |= DTMF;
  12788.     dialer.c_lineparam &= ~PULSE;
  12789.     if (ioctl(ttyfd,PIOCSETP,&dialer) == -1) {
  12790.         printf("Cannot set modem to tone dialing\n");
  12791.         ttclos(0);
  12792.         return(-2);
  12793.     }
  12794.     break;
  12795.       case 'd': case 'D': case 'p': case 'P': case '^':
  12796.     dialer.c_lineparam |= PULSE;
  12797.     dialer.c_lineparam &= ~DTMF;
  12798.     if (ioctl(ttyfd,PIOCSETP,&dialer) == -1) {
  12799.         printf("Cannot set modem to pulse dialing\n");
  12800.         ttclos(0);
  12801.         return(-2);
  12802.     }
  12803.     break;
  12804.       default:
  12805.         if (ioctl(ttyfd,PIOCDIAL,telnum) != 0) {
  12806.         perror("Dialing error");
  12807.         ttclos(0);
  12808.         return(-2);
  12809.     }
  12810.     break;
  12811.     }
  12812. #endif
  12813.  
  12814.     ioctl(ttyfd,PIOCDIAL,"@");        /* terminator for data call */
  12815.     do {                /* wait for modems to Connect */
  12816.         if (ioctl(ttyfd,PIOCGETP,&dialer) != 0)    { /* get params */
  12817.         perror("Cannot get modems to connect");
  12818.         ttclos(0);
  12819.         return(-2);
  12820.     }
  12821.     } while ((dialer.c_linestatus & MODEMCONNECTED) == 0);
  12822.     /* Turn off O_NDELAY flag now. */
  12823.     fcntl(ttyfd, F_SETFL, fcntl(ttyfd, F_GETFL, 0) & ~O_NDELAY);
  12824.     signal(SIGHUP, sighup);             /* hangup on loss of carrier */
  12825.     return(0);                          /* return success */
  12826. }
  12827.  
  12828. /*
  12829.   Offgetty, ongetty functions. These function get the 'getty(1m)' off
  12830.   and restore it to the indicated line.  Shell's return codes are:
  12831.     0: Can't do it.  Probably a user logged on.
  12832.     1: No need.  No getty on that line.
  12833.     2: Done, you should restore the getty when you're done.
  12834.   DOGETY System(3), however, returns them as 0, 256, 512, respectively.
  12835.   Thanks to Kevin O'Gorman, Anarm Software Systems.
  12836.  
  12837.    getoff.sh looks like:   geton.sh looks like:
  12838.      setgetty $1 0           setgetty $1 1
  12839.      err=$?                  exit $?
  12840.      sleep 2
  12841.      exit $err
  12842. */
  12843.  
  12844. /*  O F F G E T T Y  --  Turn off getty(1m) for the communications tty line
  12845.  * and get status so it can be restarted after the line is hung up.
  12846.  */
  12847. int
  12848. offgetty(ttname) char *ttname; {
  12849.     char temp[30];
  12850.     while (*ttname != '\0') ttname++;       /* seek terminator of path */
  12851.     ttname -= 3;                            /* get last 3 chars of name */
  12852.     sprintf(temp,"/usr/bin/getoff.sh %s",ttname);
  12853.     return(zsyscmd(temp));
  12854. }
  12855.  
  12856. /*  O N G E T T Y  --  Turn on getty(1m) for the communications tty line */
  12857.  
  12858. int
  12859. ongetty(ttname) char *ttname; {
  12860.     char temp[30];
  12861.     while (*ttname != '\0') ttname++;       /* comms tty path name */
  12862.     ttname -= 3;
  12863.     sprintf(temp,"/usr/bin/geton.sh %s",ttname);
  12864.     return(zsyscmd(temp));
  12865. }
  12866. #endif /* ATT7300 */
  12867.  
  12868. /*  T T S C A R R  --  Set ttcarr variable, controlling carrier handling.
  12869.  *
  12870.  *  0 = Off: Always ignore carrier. E.g. you can connect without carrier.
  12871.  *  1 = On: Heed carrier, except during dialing. Carrier loss gives disconnect.
  12872.  *  2 = Auto: For "modem direct": The same as "Off".
  12873.  *            For real modem types: Heed carrier during connect, but ignore
  12874.  *                it anytime else.  Compatible with pre-5A C-Kermit versions.
  12875.  *
  12876.  * As you can see, this setting does not affect dialing, which always ignores
  12877.  * carrier (unless there is some special exception for some modem type).  It
  12878.  * does affect ttopen() if it is set before ttopen() is used.  This setting
  12879.  * takes effect on the next call to ttopen()/ttpkt()/ttvt().  And they are
  12880.  * (or should be) always called before any communications is tried, which
  12881.  * means that, practically speaking, the effect is immediate.
  12882.  *
  12883.  * Of course, nothing of this applies to remote mode (xlocal = 0).
  12884.  *
  12885.  * Someone has yet to uncover how to manipulate the carrier in the BSD
  12886.  * environment (or any non-termio using environment).  Until that time, this
  12887.  * will simply be a no-op for BSD.
  12888.  *
  12889.  * Note that in previous versions, the carrier was most often left unchanged
  12890.  * in ttpkt()/ttvt() unless they were called with FLO_DIAL or FLO_DIAX.  This
  12891.  * has changed.  Now it is controlled by ttcarr in conjunction with these
  12892.  * modes.
  12893.  */
  12894. int
  12895. ttscarr(carrier) int carrier; {
  12896.     ttcarr = carrier;
  12897.     debug(F101, "ttscarr","",ttcarr);
  12898.     return(ttcarr);
  12899. }
  12900.  
  12901. /* C A R R C T L  --  Set tty modes for carrier treatment.
  12902.  *
  12903.  * Sets the appropriate bits in a termio or sgttyb struct for carrier control
  12904.  * (actually, there are no bits in sgttyb for that), or performs any other
  12905.  * operations needed to control this on the current system.  The function does
  12906.  * not do the actual TCSETA or stty, since often we want to set other bits too
  12907.  * first.  Don't call this function when xlocal is 0, or the tty is not opened.
  12908.  *
  12909.  * We don't know how to do anything like carrier control on non-ATTSV systems,
  12910.  * except, apparently, ultrix.  See above.  It is also known that this doesn't
  12911.  * have much effect on a Xenix system.  For Xenix, one should switch back and
  12912.  * forth between the upper and lower case device files.  Maybe later.
  12913.  * Presently, Xenix will stick to the mode it was opened with.
  12914.  *
  12915.  * carrier: 0 = ignore carrier, 1 = require carrier.
  12916.  * The current state is saved in curcarr, and checked to save labour.
  12917.  */
  12918. #ifdef SVORPOSIX
  12919. int
  12920. #ifdef BSD44ORPOSIX
  12921. carrctl(ttpar, carrier)    struct termios *ttpar; int carrier;
  12922. #else /* ATTSV */
  12923. carrctl(ttpar, carrier)    struct termio *ttpar; int carrier;
  12924. #endif /* BSD44ORPOSIX */
  12925. /* carrctl */ {
  12926.     debug(F101, "carrctl","",carrier);
  12927.     if (carrier)
  12928.       ttpar->c_cflag &= ~CLOCAL;
  12929.     else
  12930.       ttpar->c_cflag |= CLOCAL;
  12931.     return(0);
  12932. }
  12933. #else /* Berkeley, V7, et al... */
  12934. int
  12935. carrctl(ttpar, carrier) struct sgttyb *ttpar; int carrier; {
  12936.     debug(F101, "carrctl","",carrier);
  12937.     if (carrier == curcarr)
  12938.       return(0);
  12939.     curcarr = carrier;
  12940. #ifdef ultrix
  12941. #ifdef COMMENT
  12942. /*
  12943.   Old code from somebody at DEC that tends to get stuck, time out, etc.
  12944. */
  12945.     if (carrier) {
  12946.     ioctl(ttyfd, TIOCMODEM, &temp);
  12947.     ioctl(ttyfd, TIOCHPCL, 0);
  12948.     } else {
  12949.     /* (According to the manuals, TIOCNCAR should be preferred */
  12950.     /* over TIOCNMODEM...) */
  12951.     ioctl(ttyfd, TIOCNMODEM, &temp);
  12952.     }
  12953. #else
  12954. /*
  12955.   New code from Jamie Watson that, he says, eliminates the problems.
  12956. */
  12957.     if (carrier) {
  12958.     ioctl(ttyfd, TIOCCAR);
  12959.     ioctl(ttyfd, TIOCHPCL);
  12960.     } else {
  12961.     ioctl(ttyfd, TIOCNCAR);
  12962.     }
  12963. #endif /* COMMENT */
  12964. #endif /* ultrix */
  12965.     return(0);
  12966. }
  12967. #endif /* SVORPOSIX */
  12968.  
  12969.  
  12970. /*  T T G M D M  --  Get modem signals  */
  12971. /*
  12972.  Looks for RS-232 modem signals, and returns those that are on in as its
  12973.  return value, in a bit mask composed of the BM_xxx values defined in ckcdeb.h.
  12974.  Returns:
  12975.  -3 Not implemented
  12976.  -2 if the communication device does not have modem control (e.g. telnet)
  12977.  -1 on error.
  12978.  >= 0 on success, with a bit mask containing the modem signals that are on.
  12979. */
  12980.  
  12981. /*
  12982.   Define the symbol K_MDMCTL if we have Sys V R3 / 4.3 BSD style
  12983.   modem control, namely the TIOCMGET ioctl.
  12984. */
  12985.  
  12986. #ifdef BSD43
  12987. #define K_MDMCTL
  12988. #endif /* BSD43 */
  12989.  
  12990. #ifdef SUNOS4
  12991. #define K_MDMCTL
  12992. #endif /* SUNOS4 */
  12993.  
  12994. /*
  12995.   SCO OpenServer R5.0.4.  The TIOCMGET definition is hardwired in because it
  12996.   is skipped in termio.h when _POSIX_SOURCE is defined.  But _POSIX_SOURCE
  12997.   must be defined in order to get the high serial speeds that are new to
  12998.   5.0.4.  However, the regular SCO drivers do not implement TIOCMGET, so the
  12999.   ioctl() returns -1 with errno 22 (invalid function).  But third-party
  13000.   drivers, e.g. for Digiboard, do implement it, and so it should work on ports
  13001.   driven by those drivers.
  13002. */
  13003. #ifdef SCO_OSR504
  13004. #ifndef TIOCMGET
  13005. #define TIOCMGET (('t'<<8)|29)
  13006. #endif /* TIOCMGET */
  13007. #endif /* SCO_OSR504 */
  13008.  
  13009. #ifdef CK_SCOV5
  13010. /* Because POSIX strictness in <sys/termio.h> won't let us see these. */
  13011. #ifndef TIOCM_DTR
  13012. #define TIOCM_DTR    0x0002        /* data terminal ready */
  13013. #define TIOCM_RTS    0x0004        /* request to send */
  13014. #define TIOCM_CTS    0x0020        /* clear to send */
  13015. #define TIOCM_CAR    0x0040        /* carrier detect */
  13016. #define TIOCM_RNG    0x0080        /* ring */
  13017. #define TIOCM_DSR    0x0100        /* data set ready */
  13018. #define TIOCM_CD    TIOCM_CAR
  13019. #define TIOCM_RI    TIOCM_RNG
  13020. #endif /* TIOCM_DTR */
  13021. #endif /* CK_SCOV5 */
  13022.  
  13023. #ifdef QNX
  13024. #define K_MDMCTL
  13025. #else
  13026. #ifdef TIOCMGET
  13027. #define K_MDMCTL
  13028. #endif /* TIOCMGET */
  13029. #endif /* QNX */
  13030. /*
  13031.   "A serial communication program that can't read modem signals
  13032.    is like a car without windows."
  13033. */
  13034. int
  13035. ttgmdm() {
  13036.  
  13037. #ifdef QNX
  13038. #include <sys/qioctl.h>
  13039.  
  13040.     unsigned long y, mdmbits[2];
  13041.     int x, z = 0;
  13042.  
  13043.     if (xlocal && ttyfd < 0)
  13044.       return(-1);
  13045.  
  13046. #ifdef NETCONN
  13047.     if (netconn) {            /* Network connection */
  13048. #ifdef TN_COMPORT
  13049.         if (istncomport()) {
  13050.         gotsigs = 1;
  13051.         return(tngmdm());
  13052.     } else
  13053. #endif /* TN_COMPORT */
  13054.       return(-2);            /* No modem signals */
  13055.     }
  13056. #endif /* NETCONN */
  13057.  
  13058. #ifdef NETCMD
  13059.     if (ttpipe) return(-2);
  13060. #endif /* NETCMD */
  13061. #ifdef NETPTY
  13062.     if (ttpty) return(-2);
  13063. #endif /* NETPTY */
  13064.  
  13065.     mdmbits[0] = 0L;
  13066.     mdmbits[1] = 0L;
  13067. /*
  13068.  * From <sys/qioctl.h>:
  13069.  *
  13070.  * SERIAL devices   (all Dev.ser versions)
  13071.  * 0 : DTR           8 = Data Bits 0  16 - reserved     24 - reserved
  13072.  * 1 : RTS           9 = Data Bits 1  17 - reserved     25 - reserved
  13073.  * 2 = Out 1        10 = Stop Bits    18 - reserved     26 - reserved
  13074.  * 3 = Int Enable   11 = Par Enable   19 - reserved     27 - reserved
  13075.  * 4 = Loop         12 = Par Even     20 = CTS          28 - reserved
  13076.  * 5 - reserved     13 = Par Stick    21 = DSR          29 - reserved
  13077.  * 6 - reserved     14 : Break        22 = RI           30 - reserved
  13078.  * 7 - reserved     15 = 0            23 = CD           31 - reserved
  13079.  */
  13080.     errno = 0;
  13081.     x = qnx_ioctl(ttyfd, QCTL_DEV_CTL, &mdmbits[0], 8, &mdmbits[0], 4);
  13082.     debug(F101,"ttgmdm qnx_ioctl","",x);
  13083.     debug(F101,"ttgmdm qnx_ioctl errno","",errno);
  13084.     if (!x) {
  13085.     debug(F101,"ttgmdm qnx_ioctl mdmbits[0]","",mdmbits[0]);
  13086.     debug(F101,"ttgmdm qnx_ioctl mdmbits[1]","",mdmbits[1]);
  13087.     y = mdmbits[0];
  13088.     if (y & 0x000001L) z |= BM_DTR;    /* Bit  0 */
  13089.     if (y & 0x000002L) z |= BM_RTS;    /* Bit  1 */
  13090.     if (y & 0x100000L) z |= BM_CTS;    /* Bit 20 */
  13091.     if (y & 0x200000L) z |= BM_DSR;    /* Bit 21 */
  13092.     if (y & 0x400000L) z |= BM_RNG;    /* Bit 22 */
  13093.     if (y & 0x800000L) z |= BM_DCD;    /* Bit 23 */
  13094.     debug(F101,"ttgmdm qnx result","",z);
  13095.     debug(F110,"ttgmdm qnx CD = ",(z & BM_DCD) ? "On" : "Off", 0);
  13096.     gotsigs = 1;
  13097.     return(z);
  13098.     } else return(-1);
  13099. #else /* QNX */
  13100. #ifdef HPUX                /* HPUX has its own way */
  13101.     int x, z;
  13102.  
  13103. #ifdef HPUX10                /* Modem flag word */
  13104.     mflag y;                /* mflag typedef'd in <sys/modem.h> */
  13105. #else
  13106. #ifdef HPUX9
  13107.     mflag y;
  13108. #else
  13109. #ifdef HPUX8
  13110.     mflag y;
  13111. #else
  13112.     unsigned long y;            /* Not sure about pre-8.0... */
  13113. #endif /* HPUX8 */
  13114. #endif /* HPUX9 */
  13115. #endif /* HPUX10 */
  13116.  
  13117.     if (xlocal && ttyfd < 0)
  13118.       return(-1);
  13119.  
  13120. #ifdef NETCONN
  13121.     if (netconn) {            /* Network connection */
  13122. #ifdef TN_COMPORT
  13123.         if (istncomport()) {
  13124.         gotsigs = 1;
  13125.         return(tngmdm());
  13126.     } else
  13127. #endif /* TN_COMPORT */
  13128.       return(-2);            /* No modem signals */
  13129.     }
  13130. #endif /* NETCONN */
  13131.  
  13132. #ifdef NETCMD
  13133.     if (ttpipe) return(-2);
  13134. #endif /* NETCMD */
  13135. #ifdef NETPTY
  13136.     if (ttpty) return(-2);
  13137. #endif /* NETPTY */
  13138.  
  13139.     if (xlocal)                /* Get modem signals */
  13140.       x = ioctl(ttyfd,MCGETA,&y);
  13141.     else
  13142.       x = ioctl(0,MCGETA,&y);
  13143.     if (x < 0) return(-1);
  13144.     debug(F101,"ttgmdm","",y);
  13145.  
  13146.     z = 0;                /* Initialize return value */
  13147.  
  13148. /* Now set bits for each modem signal that is reported to be on. */
  13149.  
  13150. #ifdef MCTS
  13151.     /* Clear To Send */
  13152.     debug(F101,"ttgmdm HPUX CTS","",y & MCTS);
  13153.     if (y & MCTS) z |= BM_CTS;
  13154. #endif
  13155. #ifdef MDSR
  13156.     /* Data Set Ready */
  13157.     debug(F101,"ttgmdm HPUX DSR","",y & MDSR);
  13158.     if (y & MDSR) z |= BM_DSR;
  13159. #endif
  13160. #ifdef MDCD
  13161.     /* Carrier */
  13162.     debug(F101,"ttgmdm HPUX DCD","",y & MDCD);
  13163.     if (y & MDCD) z |= BM_DCD;
  13164. #endif
  13165. #ifdef MRI
  13166.     /* Ring Indicate */
  13167.     debug(F101,"ttgmdm HPUX RI","",y & MRI);
  13168.     if (y & MRI) z |= BM_RNG;
  13169. #endif
  13170. #ifdef MDTR
  13171.     /* Data Terminal Ready */
  13172.     debug(F101,"ttgmdm HPUX DTR","",y & MDTR);
  13173.     if (y & MDTR) z |= BM_DTR;
  13174. #endif
  13175. #ifdef MRTS
  13176.     /* Request To Send */
  13177.     debug(F101,"ttgmdm HPUX RTS","",y & MRTS);
  13178.     if (y & MRTS) z |= BM_RTS;
  13179. #endif
  13180.     gotsigs = 1;
  13181.     return(z);
  13182.  
  13183. #else /* ! HPUX */
  13184.  
  13185. #ifdef K_MDMCTL
  13186. /*
  13187.   Note, TIOCMGET might already have been defined in <sys/ioctl.h> or elsewhere.
  13188.   If not, we try including <sys/ttycom.h> -- if this blows up then more ifdefs
  13189.   are needed.
  13190. */
  13191. #ifndef TIOCMGET
  13192. #include <sys/ttycom.h>
  13193. #endif /* TIOCMGET */
  13194.  
  13195.     int x, y, z;
  13196.  
  13197.     debug(F100,"ttgmdm K_MDMCTL defined","",0);
  13198.  
  13199. #ifdef NETCONN
  13200.     if (netconn) {            /* Network connection */
  13201. #ifdef TN_COMPORT
  13202.         if (istncomport()) {
  13203.         gotsigs = 1;
  13204.         return(tngmdm());
  13205.     } else
  13206. #endif /* TN_COMPORT */
  13207.       return(-2);            /* No modem signals */
  13208.     }
  13209. #endif /* NETCONN */
  13210.  
  13211. #ifdef NETCMD
  13212.     if (ttpipe) return(-2);
  13213. #endif /* NETCMD */
  13214. #ifdef NETPTY
  13215.     if (ttpty) return(-2);
  13216. #endif /* NETPTY */
  13217.  
  13218.     if (xlocal && ttyfd < 0)
  13219.       return(-1);
  13220.  
  13221.     if (xlocal)
  13222.       x = ioctl(ttyfd,TIOCMGET,&y);    /* Get modem signals. */
  13223.     else
  13224.       x = ioctl(0,TIOCMGET,&y);
  13225.     debug(F101,"ttgmdm TIOCMGET ioctl","",x);
  13226.     if (x < 0) {
  13227.     debug(F101,"ttgmdm errno","",errno);
  13228.     return(-1);
  13229.     }
  13230.     debug(F101,"ttgmdm bits","",y);
  13231.  
  13232.     z = 0;                /* Initialize return value. */
  13233. #ifdef TIOCM_CTS
  13234.     /* Clear To Send */
  13235.     if (y & TIOCM_CTS) z |= BM_CTS;
  13236.     debug(F101,"ttgmdm TIOCM_CTS defined","",TIOCM_CTS); 
  13237. #else
  13238.     debug(F100,"ttgmdm TIOCM_CTS not defined","",0);
  13239. #endif
  13240. #ifdef TIOCM_DSR
  13241.     /* Data Set Ready */
  13242.     if (y & TIOCM_DSR) z |= BM_DSR;
  13243.     debug(F101,"ttgmdm TIOCM_DSR defined","",TIOCM_DSR); 
  13244. #else
  13245.     debug(F100,"ttgmdm TIOCM_DSR not defined","",0);
  13246. #endif
  13247. #ifdef TIOCM_CAR
  13248.     /* Carrier */
  13249.     if (y & TIOCM_CAR) z |= BM_DCD;
  13250.     debug(F101,"ttgmdm TIOCM_CAR defined","",TIOCM_CAR); 
  13251. #else
  13252.     debug(F100,"ttgmdm TIOCM_CAR not defined","",0);
  13253. #endif
  13254. #ifdef TIOCM_RNG
  13255.     /* Ring Indicate */
  13256.     if (y & TIOCM_RNG) z |= BM_RNG;
  13257.     debug(F101,"ttgmdm TIOCM_RNG defined","",TIOCM_RNG); 
  13258. #else
  13259.     debug(F100,"ttgmdm TIOCM_RNG not defined","",0);
  13260. #endif
  13261. #ifdef TIOCM_DTR
  13262.     /* Data Terminal Ready */
  13263.     if (y & TIOCM_DTR) z |= BM_DTR;
  13264.     debug(F101,"ttgmdm TIOCM_DTR defined","",TIOCM_DTR); 
  13265. #else
  13266.     debug(F100,"ttgmdm TIOCM_DTR not defined","",0);
  13267. #endif
  13268. #ifdef TIOCM_RTS
  13269.     /* Request To Send */
  13270.     if (y & TIOCM_RTS) z |= BM_RTS;
  13271.     debug(F101,"ttgmdm TIOCM_RTS defined","",TIOCM_RTS); 
  13272. #else
  13273.     debug(F100,"ttgmdm TIOCM_RTS not defined","",0);
  13274. #endif
  13275.     gotsigs = 1;
  13276.     return(z);
  13277.  
  13278. #else /* !K_MDMCTL catch-All */
  13279.  
  13280.     debug(F100,"ttgmdm K_MDMCTL not defined","",0);
  13281. #ifdef TIOCMGET
  13282.     debug(F100,"ttgmdm TIOCMGET defined","",0);
  13283. #else
  13284.     debug(F100,"ttgmdm TIOCMGET not defined","",0);
  13285. #endif /* TIOCMGET */
  13286. #ifdef _SVID3
  13287.     debug(F100,"ttgmdm _SVID3 defined","",0);
  13288. #else
  13289.     debug(F100,"ttgmdm _SVID3 not defined","",0);
  13290. #endif /* _SVID3 */
  13291.  
  13292. #ifdef NETCONN
  13293.     if (netconn) {            /* Network connection */
  13294. #ifdef TN_COMPORT
  13295.         if (istncomport()) {
  13296.         gotsigs = 1;
  13297.         return(tngmdm());
  13298.     } else
  13299. #endif /* TN_COMPORT */
  13300.       return(-2);            /* No modem signals */
  13301.     }
  13302. #endif /* NETCONN */
  13303.  
  13304. #ifdef NETCMD
  13305.     if (ttpipe) return(-2);
  13306. #endif /* NETCMD */
  13307. #ifdef NETPTY
  13308.     if (ttpty) return(-2);
  13309. #endif /* NETPTY */
  13310.  
  13311.     return(-3);                /* Sorry, I don't know how... */
  13312.  
  13313. #endif /* K_MDMCTL */
  13314. #endif /* HPUX */
  13315. #endif /* QNX */
  13316. }
  13317.  
  13318. /*  P S U S P E N D  --  Put this process in the background.  */
  13319.  
  13320. /*
  13321.   Call with flag nonzero if suspending is allowed, zero if not allowed.
  13322.   Returns 0 on apparent success, -1 on failure (flag was zero, or
  13323.   kill() returned an error code.
  13324. */
  13325. int
  13326. psuspend(flag) int flag; {
  13327.  
  13328. #ifdef RTU
  13329.     extern int rtu_bug;
  13330. #endif /* RTU */
  13331.  
  13332.     if (flag == 0) return(-1);
  13333.  
  13334. #ifdef NOJC
  13335.     return(-1);
  13336. #else
  13337. #ifdef SIGTSTP
  13338. /*
  13339.   The big question here is whether job control is *really* supported.
  13340.   There's no way Kermit can know for sure.  The fact that SIGTSTP is
  13341.   defined does not guarantee the Unix kernel supports it, and the fact
  13342.   that the Unix kernel supports it doesn't guarantee that the user's
  13343.   shell (or other process that invoked Kermit) supports it.
  13344. */
  13345. #ifdef RTU
  13346.     rtu_bug = 1;
  13347. #endif /* RTU */
  13348.     if (kill(0,SIGSTOP) < 0
  13349. #ifdef MIPS
  13350. /* Let's try this for MIPS too. */
  13351.     && kill(getpid(),SIGSTOP) < 0
  13352. #endif /* MIPS */
  13353.     ) {                /* If job control, suspend the job */
  13354.     perror("suspend");
  13355.     debug(F101,"psuspend error","",errno);
  13356.     return(-1);
  13357.     }
  13358.     debug(F100,"psuspend ok","",0);
  13359.     return(0);
  13360. #else
  13361.     return(-1);
  13362. #endif /* SIGTSTP */
  13363. #endif /* NOJC */
  13364. }
  13365.  
  13366. /*
  13367.   setuid package, by Kristoffer Eriksson, with contributions from Dean
  13368.   Long and fdc.
  13369. */
  13370.  
  13371. /* The following is for SCO when CK_ANSILIBS is defined... */
  13372. #ifdef M_UNIX
  13373. #ifdef CK_ANSILIBS
  13374. #ifndef NOGETID_PROTOS
  13375. #define NOGETID_PROTOS
  13376. #endif /* NOGETID_PROTOS */
  13377. #endif /* CK_ANSILIBS */
  13378. #endif /* M_UNIX */
  13379.  
  13380. #ifndef _POSIX_SOURCE
  13381. #ifndef SUNOS4
  13382. #ifndef NEXT
  13383. #ifndef PS2AIX10
  13384. #ifndef sequent
  13385. #ifndef HPUX9
  13386. #ifndef COHERENT
  13387. #ifndef NOGETID_PROTOS
  13388. extern UID_T getuid(), geteuid(), getreuid();
  13389. extern GID_T getgid(), getegid(), getregid();
  13390. #endif /* NOGETID_PROTOS */
  13391. #else
  13392. extern UID_T getreuid();
  13393. extern GID_T getregid();
  13394. #endif /* COHERENT */
  13395. #endif /* HPUX9 */
  13396. #endif /* sequent */
  13397. #endif /* PS2AIX10 */
  13398. #endif /* NEXT */
  13399. #endif /* SUNOS4 */
  13400. #endif /* _POSIX_SOURCE */
  13401.  
  13402. /*
  13403. Subject: Set-user-id
  13404. To: fdc@watsun.cc.columbia.edu (Frank da Cruz)
  13405. Date: Sat, 21 Apr 90 4:48:25 MES
  13406. From: Kristoffer Eriksson <ske@pkmab.se>
  13407.  
  13408. This is a set of functions to be used in programs that may be run set-user-id
  13409. and/or set-group-id. They handle both the case where the program is not run
  13410. with such privileges (nothing special happens then), and the case where one
  13411. or both of these set-id modes are used.  The program is made to run with the
  13412. user's real user and group ids most of the time, except for when more
  13413. privileges are needed.  Don't set-user-id to "root".
  13414.  
  13415. This works on System V and POSIX.  In BSD, it depends on the
  13416. "saved-set-user-id" feature.
  13417. */
  13418.  
  13419. #define UID_ROOT 0            /* Root user and group ids */
  13420. #define GID_ROOT 0
  13421.  
  13422. /*
  13423.   The following code defines the symbol SETEUID for UNIX systems based
  13424.   on BSD4.4 (either -Encumbered or -Lite).  This program will then use
  13425.   seteuid() and setegid() instead of setuid() and setgid(), which still
  13426.   don't allow arbitrary switching.  It also avoids setreuid() and
  13427.   setregid(), which are included in BSD4.4 for compatibility only, are
  13428.   insecure, and print warnings to stderr under at least one system (NetBSD
  13429.   1.0).  Note that POSIX systems should still use setuid() and setgid();
  13430.   the seteuid() and setegid() functions are BSD4.4 extensions to the
  13431.   POSIX model.  Mike Long <mike.long@analog.com>, 8/94.
  13432. */
  13433. #ifdef BSD44
  13434. #define SETEUID
  13435. #endif /* BSD44 */
  13436.  
  13437. /*
  13438.   The following construction automatically defines the symbol SETREUID for
  13439.   UNIX versions based on Berkeley Unix 4.2 and 4.3.  If this symbol is
  13440.   defined, then this program will use getreuid() and getregid() calls in
  13441.   preference to getuid() and getgid(), which in Berkeley-based Unixes do
  13442.   not allow arbitrary switching back and forth of real & effective uid.
  13443.   This construction also allows -DSETREUID to be put on the cc command line
  13444.   for any system that has and wants to use setre[ug]id().  It also prevents
  13445.   automatic definition of SETREUID if -DNOSETREU is included on the cc
  13446.   command line (or otherwise defined).
  13447. */
  13448. #ifdef FT18                /* None of this for Fortune. */
  13449. #define NOSETREU
  13450. #endif /* FT18 */
  13451.  
  13452. #ifdef ANYBSD
  13453. #ifndef BSD29
  13454. #ifndef BSD41
  13455. #ifndef SETREUID
  13456. #ifndef NOSETREU
  13457. #ifndef SETEUID
  13458. #define SETREUID
  13459. #endif /* SETEUID */
  13460. #endif /* NOSETREU */
  13461. #endif /* SETREUID */
  13462. #endif /* !BSD41 */
  13463. #endif /* !BSD29 */
  13464. #endif /* ANYBSD */
  13465.  
  13466. /* Variables for user and group IDs. */
  13467.  
  13468. static UID_T realuid = (UID_T) -1, privuid = (UID_T) -1;
  13469. static GID_T realgid = (GID_T) -1, privgid = (GID_T) -1;
  13470.  
  13471.  
  13472. /* P R I V _ I N I  --  Initialize privileges package  */
  13473.  
  13474. /* Called as early as possible in a set-uid or set-gid program to store the
  13475.  * set-to uid and/or gid and step down to the users real uid and gid. The
  13476.  * stored id's can be temporarily restored (allowed in System V) during
  13477.  * operations that require the privilege.  Most of the time, the program
  13478.  * should execute in unpriviliged state, to not impose any security threat.
  13479.  *
  13480.  * Note: Don't forget that access() always uses the real id:s to determine
  13481.  * file access, even with privileges restored.
  13482.  *
  13483.  * Returns an error mask, with error values or:ed together:
  13484.  *   1 if setuid() fails,
  13485.  *   2 if setgid() fails, and
  13486.  *   4 if the program is set-user-id to "root", which can't be handled.
  13487.  *
  13488.  * Only the return value 0 indicates real success. In case of failure,
  13489.  * those privileges that could be reduced have been, at least, but the
  13490.  * program should be aborted none-the-less.
  13491.  *
  13492.  * Also note that these functions do not expect the uid or gid to change
  13493.  * without their knowing. It may work if it is only done temporarily, but
  13494.  * you're on your own.
  13495.  */
  13496. int
  13497. priv_ini() {
  13498.     int err = 0;
  13499.  
  13500.     /* Save real ID:s. */
  13501.     realuid = getuid();
  13502.     realgid = getgid();
  13503.  
  13504.     /* Save current effective ID:s, those set to at program exec. */
  13505.     privuid = geteuid();
  13506.     privgid = getegid();
  13507.  
  13508.     /* If running set-uid, go down to real uid, otherwise remember that
  13509.      * no privileged uid is available.
  13510.      *
  13511.      * Exceptions:
  13512.      *
  13513.      * 1) If the real uid is already "root" and the set-uid uid (the
  13514.      * initial effective uid) is not "root", then we would have trouble
  13515.      * if we went "down" to "root" here, and then temporarily back to the
  13516.      * set-uid uid (not "root") and then again tried to become "root". I
  13517.      * think the "saved set-uid" is lost when changing uid from effective
  13518.      * uid "root", which changes all uid, not only the effective uid. But
  13519.      * in this situation, we can simply go to "root" and stay there all
  13520.      * the time. That should give sufficient privilege (understatement!),
  13521.      * and give the right uids for subprocesses.
  13522.      *
  13523.      * 2) If the set-uid (the initial effective uid) is "root", and we
  13524.      * change uid to the real uid, we can't change it back to "root" when
  13525.      * we need the privilege, for the same reason as in 1). Thus, we can't
  13526.      * handle programs that are set-user-id to "root" at all. The program
  13527.      * should be stopped.  Use some other uid.  "root" is probably too
  13528.      * privileged for such things, anyway. (The uid is reverted to the
  13529.      * real uid until termination.)
  13530.      *
  13531.      * These two exceptions have the effect that the "root" uid will never
  13532.      * be one of the two uids that are being switched between, which also
  13533.      * means we don't have to check for such cases in the switching
  13534.      * functions.
  13535.      *
  13536.      * Note that exception 1) is handled by these routines (by constantly
  13537.      * running with uid "root", while exception 2) is a serious error, and
  13538.      * is not provided for at all in the switching functions.
  13539.      */
  13540.     if (realuid == privuid)
  13541.     privuid = (UID_T) -1;        /* Not running set-user-id. */
  13542.  
  13543.     /* If running set-gid, go down to real gid, otherwise remember that
  13544.      * no privileged gid is available.
  13545.      *
  13546.      * There are no exception like there is for the user id, since there
  13547.      * is no group id that is privileged in the manner of uid "root".
  13548.      * There could be equivalent problems for group changing if the
  13549.      * program sometimes ran with uid "root" and sometimes not, but
  13550.      * that is already avoided as explained above.
  13551.      *
  13552.      * Thus we can expect always to be able to switch to the "saved set-
  13553.      * gid" when we want, and back to the real gid again. You may also
  13554.      * draw the conclusion that set-gid provides for fewer hassles than
  13555.      * set-uid.
  13556.      */
  13557.  
  13558. #ifdef SUIDDEBUG
  13559.     fprintf(stderr,"UID_ROOT=%d\n",UID_ROOT);
  13560.     fprintf(stderr,"realuid=%d\n",realuid);
  13561.     fprintf(stderr,"privuid=%d\n",privuid);
  13562. #endif /* SUIDDEBUG */
  13563.  
  13564.     if (realgid == privgid)        /* If not running set-user-id, */
  13565.       privgid = (GID_T) -1;        /*  remember it this way. */
  13566.  
  13567.     err = priv_off();            /* Turn off setuid privilege. */
  13568.  
  13569.     if (privuid == UID_ROOT)        /* If setuid to root, */
  13570.       err |= 4;                /* return this error. */
  13571.  
  13572.     if (realuid == UID_ROOT) {        /* If real id is root, */
  13573.     privuid = (UID_T) -1;        /* stay root at all times. */
  13574. #ifdef ATT7300
  13575.     /* If Kermit installed SUID uucp and user is running as root */
  13576.     err &= ~1;            /* System V R0 does not save UID */
  13577. #endif /* ATT7300 */
  13578.     }
  13579.     return(err);
  13580. }
  13581.  
  13582.  
  13583. /* Macros for hiding the differences in UID/GID setting between various Unix
  13584.  * systems. These macros should always be called with both the privileged ID
  13585.  * and the non-privileged ID. The one in the second argument, will become the
  13586.  * effective ID. The one in the first argument will be retained for later
  13587.  * retrieval.
  13588.  */
  13589. #ifdef SETREUID
  13590. #ifdef SAVEDUID
  13591. /* On BSD systems with the saved-UID feature, we just juggle the effective
  13592.  * UID back and forth, and leave the real UID at its true value.  The kernel
  13593.  * allows switching to both the current real UID, the effective UID, and the
  13594.  * UID which the program is set-UID to.  The saved set-UID always holds the
  13595.  * privileged UID for us, and the real UID will always be the non-privileged,
  13596.  * and we can freely choose one of them for the effective UID at any time.
  13597.  */
  13598. #define switchuid(hidden,active) setreuid( (UID_T) -1, active)
  13599. #define switchgid(hidden,active) setregid( (GID_T) -1, active)
  13600.  
  13601. #else   /* SETREUID,!SAVEDUID */
  13602.  
  13603. /* On systems with setreXid() but without the saved-UID feature, notably
  13604.  * BSD 4.2, we swap the real and effective UIDs each time.  It's
  13605.  * the effective UID that we are interested in, but we have to retain the
  13606.  * unused UID somewhere to enable us to restore it later, and we do this
  13607.  * in the real UID.  The kernel only allows switching to either the current
  13608.  * real or the effective UID, unless you're "root".
  13609.  */
  13610. #define switchuid(hidden,active)    setreuid(hidden,active)
  13611. #define switchgid(hidden,active)    setregid(hidden,active)
  13612. #endif
  13613.  
  13614. #else /* !SETREUID, !SAVEDUID */
  13615.  
  13616. #ifdef SETEUID
  13617. /*
  13618.   BSD 4.4 works similarly to System V and POSIX (see below), but uses
  13619.   seteXid() instead of setXid() to change effective IDs.  In addition, the
  13620.   seteXid() functions work the same for "root" as for other users.
  13621. */
  13622. #define switchuid(hidden,active)    seteuid(active)
  13623. #define switchgid(hidden,active)    setegid(active)
  13624.  
  13625. #else /* !SETEUID */
  13626.  
  13627. /* On System V and POSIX, the only thing we can change is the effective UID
  13628.  * (unless the current effective UID is "root", but initsuid() avoids that for
  13629.  * us).  The kernel allows switching to the current real UID or to the saved
  13630.  * set-UID.  These are always set to the non-privileged UID and the privileged
  13631.  * UID, respectively, and we only change the effective UID.  This breaks if
  13632.  * the current effective UID is "root", though, because for "root" setuid/gid
  13633.  * becomes more powerful, which is why initsuid() treats "root" specially.
  13634.  * Note: That special treatment maybe could be ignored for BSD?  Note: For
  13635.  * systems that don't fit any of these four cases, we simply can't support
  13636.  * set-UID.
  13637.  */
  13638. #define switchuid(hidden,active)    setuid(active)
  13639. #define switchgid(hidden,active)    setgid(active)
  13640.  
  13641. #endif /* SETEUID */
  13642. #endif /* SETREUID */
  13643.  
  13644.  
  13645. /* P R I V _ O N  --  Turn on the setuid and/or setgid */
  13646.  
  13647. /* Go to the privileged uid (gid) that the program is set-user-id
  13648.  * (set-group-id) to, unless the program is running unprivileged.
  13649.  * If setuid() fails, return value will be 1. If getuid() fails it
  13650.  * will be 2.  Return immediately after first failure, and the function
  13651.  * tries to restore any partial work done.  Returns 0 on success.
  13652.  * Group id is changed first, since it is less serious than user id.
  13653.  */
  13654. int
  13655. priv_on() {
  13656.     if (privgid != (GID_T) -1)
  13657.       if (switchgid(realgid,privgid))
  13658.         return(2);
  13659.  
  13660.     if (privuid != (UID_T) -1)
  13661.       if (switchuid(realuid,privuid)) {
  13662.       if (privgid != (GID_T) -1)
  13663.         switchgid(privgid,realgid);
  13664.       return(1);
  13665.       }
  13666.     return(0);
  13667. }
  13668.  
  13669. /* P R I V _ O F F  --  Turn on the real uid and gid */
  13670.  
  13671. /* Return to the unprivileged uid (gid) after an temporary visit to
  13672.  * privileged status, unless the program is running without set-user-id
  13673.  * (set-group-id). Returns 1 for failure in setuid() and 2 for failure
  13674.  * in setgid() or:ed together. The functions tries to return both uid
  13675.  * and gid to unprivileged state, regardless of errors. Returns 0 on
  13676.  * success.
  13677.  */
  13678. int
  13679. priv_off() {
  13680.     int err = 0;
  13681.  
  13682.     if (privuid != (UID_T) -1)
  13683.        if (switchuid(privuid,realuid))
  13684.       err |= 1;
  13685.  
  13686.     if (privgid != (GID_T) -1)
  13687.        if (switchgid(privgid,realgid))
  13688.     err |= 2;
  13689.  
  13690.     return(err);
  13691. }
  13692.  
  13693. /* Turn off privilege permanently.  No going back.  This is necessary before
  13694.  * a fork() on BSD43 machines that don't save the setUID or setGID, because
  13695.  * we swap the real and effective ids, and we don't want to let the forked
  13696.  * process swap them again and get the privilege back. It will work on other
  13697.  * machines too, such that you can rely on its effect always being the same,
  13698.  * for instance, even when you're in priv_on() state when this is called.
  13699.  * (Well, that part about "permanent" is on System V only true if you follow
  13700.  * this with a call to exec(), but that's what we want it for anyway.)
  13701.  * Added by Dean Long -- dlong@midgard.ucsc.edu
  13702.  */
  13703. int
  13704. priv_can() {
  13705.  
  13706. #ifdef SETREUID
  13707.     int err = 0;
  13708.     if (privuid != (UID_T) -1)
  13709.        if (setreuid(realuid,realuid))
  13710.       err |= 1;
  13711.  
  13712.     if (privgid != (GID_T) -1)
  13713.         if (setregid(realgid,realgid))
  13714.        err |= 2;
  13715.  
  13716.     return(err);
  13717.  
  13718. #else
  13719. #ifdef SETEUID
  13720.     int err = 0;
  13721.     if (privuid != (UID_T) -1)
  13722.     if (setuid(realuid)) {
  13723.         debug(F101,"setuid failed","",errno);
  13724.         err |= 1;
  13725.         debug(F101,"ruid","",getuid());
  13726.         debug(F101,"euid","",geteuid());
  13727.     }
  13728.     debug(F101,"setuid","",realuid);
  13729.     if (privgid != (GID_T) -1)
  13730.         if (setgid(realgid)) {
  13731.         debug(F101,"setgid failed","",errno);
  13732.         err |= 2;
  13733.         debug(F101,"rgid","",getgid());
  13734.         debug(F101,"egid","",getegid());
  13735.     }
  13736.     debug(F101,"setgid","",realgid);
  13737.     return(err);
  13738. #else
  13739.     /* Easy way of using setuid()/setgid() instead of setreuid()/setregid().*/
  13740.     return(priv_off());
  13741. #endif /* SETEUID */
  13742. #endif /* SETREUID */
  13743. }
  13744.  
  13745. /* P R I V _ O P N  --  For opening protected files or devices. */
  13746.  
  13747. int
  13748. priv_opn(name, modes) char *name; int modes; {
  13749.     int x;
  13750.     priv_on();                /* Turn privileges on */
  13751.     debug(F111,"priv_opn",name,modes);
  13752.     errno = 0;
  13753.     x = open(name, modes);        /* Try to open the device */
  13754.     debug(F101,"priv_opn result","",x);
  13755.     debug(F101,"priv_opn errno","",errno);
  13756.     priv_off();                /* Turn privileges off */
  13757.     return(x);                /* Return open's return code */
  13758. }
  13759.  
  13760. /*  P R I V _ C H K  --  Check privileges.  */
  13761.  
  13762. /*  Try to turn them off.  If turning them off did not succeed, cancel them */
  13763.  
  13764. int
  13765. priv_chk() {
  13766.     int x, y = 0;
  13767.     x = priv_off();            /* Turn off privs. */
  13768.     if (x != 0 || getuid() == privuid || geteuid() == privuid)
  13769.       y = priv_can();
  13770.     if (x != 0 || getgid() == privgid || getegid() == privgid)
  13771.       y = y | priv_can();
  13772.     return(y);
  13773. }
  13774.  
  13775. UID_T
  13776. real_uid() {
  13777.     return(realuid);
  13778. }
  13779.  
  13780. VOID
  13781. ttimoff() {                /* Turn off any timer interrupts */
  13782.     /* int xx; */
  13783. /*
  13784.   As of 5A(183), we set SIGALRM to SIG_IGN (to ignore alarms) rather than to
  13785.   SIG_DFL (to catch alarms, or if there is no handler, to exit).  This is to
  13786.   cure (mask, really) a deeper problem with stray alarms that occurs on some
  13787.   systems, possibly having to do with sleep(), that caused core dumps.  It
  13788.   should be OK to do this, because no code in this module uses nested alarms.
  13789.   (But we still have to watch out for SCRIPT and DIAL...)
  13790. */
  13791.     /* xx = */ alarm(0);
  13792.     /* debug(F101,"ttimoff alarm","",xx); */
  13793.     if (saval) {            /* Restore any previous */
  13794.     signal(SIGALRM,saval);        /* alarm handler. */
  13795.     /* debug(F101,"ttimoff alarm restoring saval","",saval); */
  13796.     saval = NULL;
  13797.     } else {
  13798.     signal(SIGALRM,SIG_IGN);    /* Used to be SIG_DFL */
  13799.     /* debug(F100,"ttimoff alarm SIG_IGN","",0); */
  13800.     }
  13801. }
  13802.  
  13803. /* T T R U N C M D  --  Redirect an external command over the connection. */
  13804.  
  13805. #ifdef CK_REDIR
  13806. int
  13807. ttruncmd(s) char *s; {
  13808.     PID_T pid;                /* pid of lower fork */
  13809.     int wstat;                /* for wait() */
  13810.     int x;
  13811.     int statusp;
  13812.  
  13813.     if (ttyfd == -1) {
  13814.     printf("?Sorry, device is not open\n");
  13815.     return(0);
  13816.     }
  13817.     if (nopush) {
  13818.     debug(F100,"ttruncmd fail: nopush","",0);
  13819.     return(0);
  13820.     }
  13821.     conres();                /* Make console normal  */
  13822.     pexitstat = -4;
  13823.     if ((pid = fork()) == 0) {        /* Make a child fork */
  13824.     if (priv_can())            /* Child: turn off privs. */
  13825.       exit(1);
  13826.     dup2(ttyfd, 0);            /* Give stdin/out to the line */
  13827.     dup2(ttyfd, 1);
  13828.     x = system(s);
  13829.     debug(F101,"ttruncmd system",s,x);
  13830.     _exit(x ? BAD_EXIT : 0);
  13831.     } else {
  13832.     SIGTYP (*istat)(), (*qstat)();
  13833.     if (pid == (PID_T) -1)        /* fork() failed? */
  13834.       return(0);
  13835.     istat = signal(SIGINT,SIG_IGN); /* Let the fork handle keyboard */
  13836.     qstat = signal(SIGQUIT,SIG_IGN); /* interrupts itself... */
  13837.  
  13838. #ifdef COMMENT
  13839.         while (((wstat = wait(&statusp)) != pid) && (wstat != -1)) ;
  13840. #else  /* Not COMMENT */
  13841.         while (1) {
  13842.         wstat = wait(&statusp);
  13843.         debug(F101,"ttruncmd wait","",wstat);
  13844.         if (wstat == pid || wstat == -1)
  13845.           break;
  13846.     }
  13847. #endif /* COMMENT */
  13848.  
  13849.     pexitstat = (statusp & 0xff) ? statusp : statusp >> 8;
  13850.     debug(F101,"ttruncmd wait statusp","",statusp);
  13851.     debug(F101,"ttruncmd wait pexitstat","",pexitstat);
  13852.     signal(SIGINT,istat);        /* Restore interrupts */
  13853.     signal(SIGQUIT,qstat);
  13854.     }
  13855.     concb((char)escchr);        /* Restore console to CBREAK mode */
  13856.     return(statusp == 0 ? 1 : 0);
  13857. }
  13858. #endif /* CK_REDIR */
  13859.  
  13860. struct tm *
  13861. #ifdef CK_ANSIC
  13862. cmdate2tm(char * date, int gmt)         /* date as "yyyymmdd hh:mm:ss" */
  13863. #else
  13864. cmdate2tm(date,gmt) char * date; int gmt;
  13865. #endif
  13866. {
  13867.     /* date as "yyyymmdd hh:mm:ss" */
  13868.     static struct tm _tm;
  13869.     time_t now;
  13870.  
  13871.     if (strlen(date) != 17 ||
  13872.     date[8] != ' ' ||
  13873.     date[11] != ':' ||
  13874.     date[14] != ':')
  13875.       return(NULL);
  13876.  
  13877.     time(&now);
  13878.     if (gmt)
  13879.       _tm = *gmtime(&now);
  13880.     else
  13881.       _tm = *localtime(&now);
  13882.     _tm.tm_year = (date[0]-'0')*1000 + (date[1]-'0')*100 +
  13883.                   (date[2]-'0')*10   + (date[3]-'0')-1900;
  13884.     _tm.tm_mon  = (date[4]-'0')*10   + (date[5]-'0')-1;
  13885.     _tm.tm_mday = (date[6]-'0')*10   + (date[7]-'0');
  13886.     _tm.tm_hour = (date[9]-'0')*10   + (date[10]-'0');
  13887.     _tm.tm_min  = (date[12]-'0')*10  + (date[13]-'0');
  13888.     _tm.tm_sec  = (date[15]-'0')*10  + (date[16]-'0');
  13889.  
  13890.     /* Should we set _tm.tm_isdst to -1 here? */
  13891.  
  13892.     _tm.tm_wday = 0;
  13893.     _tm.tm_yday = 0;
  13894.  
  13895.     return(&_tm);
  13896. }
  13897.  
  13898. #ifdef OXOS
  13899. #undef kill
  13900. #endif /* OXOS */
  13901.  
  13902. #ifdef OXOS
  13903. int
  13904. priv_kill(pid, sig) int pid, sig; {
  13905.     int    i;
  13906.  
  13907.     if (priv_on())
  13908.     debug(F100,"priv_kill priv_on failed","",0);
  13909.     i = kill(pid, sig);
  13910.     if (priv_off())
  13911.     debug(F100,"priv_kill priv_off failed","",0);
  13912.     return(i);
  13913. }
  13914. #endif /* OXOS */
  13915.  
  13916. #ifdef BEOSORBEBOX
  13917. /* #ifdef BE_DR_7 */
  13918. /*
  13919.   alarm() function not supplied with Be OS DR7 - this one contributed by
  13920.   Neal P. Murphy.
  13921. */
  13922.  
  13923. /*
  13924.   This should mimic the UNIX/POSIX alarm() function well enough, with the
  13925.   caveat that one's SIGALRM handler must call alarm_expired() to clean up vars
  13926.   and wait for the alarm thread to finish.
  13927. */
  13928. unsigned int
  13929. alarm(unsigned int seconds) {
  13930.     long time_left = 0;
  13931.  
  13932. /* If an alarm is active, turn it off, saving the unused time */
  13933.     if (alarm_thread != -1) {
  13934.         /* We'll be generous and count partial seconds as whole seconds. */
  13935.         time_left = alarm_struct.time -
  13936.       ((system_time() - time_started) / 1000000.0);
  13937.  
  13938.         /* Kill the alarm thread */
  13939.         kill_thread (alarm_thread);
  13940.  
  13941.         /* We need to clean up as though the alarm occured. */
  13942.         time_started = 0;
  13943.         alarm_struct.thread = -1;
  13944.         alarm_struct.time = 0;
  13945.         alarm_expired();
  13946.     }
  13947.  
  13948. /* Set a new alarm clock, if requested. */
  13949.     if (seconds > 0) {
  13950.         alarm_struct.thread = find_thread(NULL);
  13951.         alarm_struct.time = seconds;
  13952.         time_started = system_time();
  13953.         alarm_thread = spawn_thread (do_alarm,
  13954.                                      "alarm_thread",
  13955.                                      B_NORMAL_PRIORITY,
  13956.                                      (void *) &alarm_struct
  13957.                      );
  13958.         resume_thread (alarm_thread);
  13959.     }
  13960.  
  13961. /* Now return [unused time | 0] */
  13962.     return ((unsigned int) time_left);
  13963. }
  13964.  
  13965. /*
  13966.   This function is the departure from UNIX/POSIX alarm handling. In the case
  13967.   of Be's missing alarm() function, this stuff needs to be done in the SIGALRM
  13968.   handler. When Be implements alarm(), this function call can be eliminated
  13969.   from user's SIGALRM signal handlers.
  13970. */
  13971.  
  13972. void
  13973. alarm_expired(void) {
  13974.     long ret_val;
  13975.  
  13976.     if (alarm_thread != -1) {
  13977.         wait_for_thread (alarm_thread, &ret_val);
  13978.         alarm_thread = -1;
  13979.     }
  13980. }
  13981.  
  13982. /*
  13983.   This is the function that snoozes the requisite number of seconds and then
  13984.   SIGALRMs the calling thread. Note that kill() wants a pid_t arg, whilst Be
  13985.   uses thread_id; currently they are both typdef'ed as long, but I'll do the
  13986.   cast anyway. This function is run in a separate thread.
  13987. */
  13988.  
  13989. long
  13990. do_alarm (void *alarm_struct) {
  13991.     snooze ((double) ((struct ALARM_STRUCT *) alarm_struct)->time * 1000000.0);
  13992.     kill ((pid_t)((struct ALARM_STRUCT *) alarm_struct)->thread, SIGALRM);
  13993.     time_started = 0;
  13994.     ((struct ALARM_STRUCT *) alarm_struct)->thread = -1;
  13995.     ((struct ALARM_STRUCT *) alarm_struct)->time = 0;
  13996. }
  13997. /* #endif */ /* BE_DR_7 */
  13998. #endif /* BEOSORBEBOX */
  13999.  
  14000. #ifdef Plan9
  14001.  
  14002. int
  14003. p9ttyctl(char letter, int num, int param) {
  14004.     char cmd[20];
  14005.     int len;
  14006.  
  14007.     if (ttyctlfd < 0)
  14008.       return -1;
  14009.  
  14010.     cmd[0] = letter;
  14011.     if (num)
  14012.       len = sprintf(cmd + 1, "%d", param) + 1;
  14013.     else {
  14014.     cmd[1] = param;
  14015.     len = 2;
  14016.     }
  14017.     if (write(ttyctlfd, cmd, len) == len) {
  14018.     cmd[len] = 0;
  14019.     /* fprintf(stdout, "wrote '%s'\n", cmd); */
  14020.     return 0;
  14021.     }
  14022.     return -1;
  14023. }
  14024.  
  14025. int
  14026. p9ttyparity(char l) {
  14027.     return p9ttyctl('p', 0, l);
  14028. }
  14029.  
  14030. int
  14031. p9tthflow(int flow, int status) {
  14032.     return p9ttyctl('m', 1, status);
  14033. }
  14034.  
  14035. int
  14036. p9ttsspd(int cps) {
  14037.     if (p9ttyctl('b', 1, cps * 10) < 0)
  14038.       return -1;
  14039.     ttylastspeed = cps * 10;
  14040.     return 0;
  14041. }
  14042.  
  14043. int
  14044. p9openttyctl(char *ttname) {
  14045.     char name[100];
  14046.  
  14047.     if (ttyctlfd >= 0) {
  14048.     close(ttyctlfd);
  14049.     ttyctlfd = -1;
  14050.     ttylastspeed = -1;
  14051.     }
  14052.     sprintf(name, "%sctl", ttname);
  14053.     ttyctlfd = open(name, 1);
  14054.     return ttyctlfd;
  14055. }
  14056.  
  14057. int
  14058. p9concb() {
  14059.     if (consctlfd >= 0) {
  14060.     if (write(consctlfd, "rawon", 5) == 5)
  14061.       return 0;
  14062.     }
  14063.     return -1;
  14064. }
  14065.  
  14066. int
  14067. p9conbin() {
  14068.     return p9concb();
  14069. }
  14070.  
  14071. int
  14072. p9conres() {
  14073.     if (consctlfd >= 0) {
  14074.     if (write(consctlfd, "rawoff", 6) == 6)
  14075.       return 0;
  14076.     }
  14077.     return -1;
  14078. }
  14079.  
  14080. int
  14081. p9sndbrk(int msec) {
  14082.     if (ttyctlfd >= 0) {
  14083.     char cmd[20];
  14084.     int i = sprintf(cmd, "k%d", msec);
  14085.     if (write(ttyctlfd, cmd, i) == i)
  14086.       return 0;
  14087.     }
  14088.     return -1;
  14089. }
  14090.  
  14091. int
  14092. conwrite(char *buf, int n) {
  14093.     int x;
  14094.     static int length = 0;
  14095.     static int holdingcr = 0;
  14096.     int normal = 0;
  14097.     for (x = 0; x < n; x++) {
  14098.     char c = buf[x];
  14099.     if (c == 007) {
  14100.         if (normal) {
  14101.         write(1, buf + (x - normal), normal);
  14102.         length += normal;
  14103.         normal = 0;
  14104.         }
  14105.         /* write(noisefd, "1000 300", 8); */
  14106.         holdingcr = 0;
  14107.     } else if (c == '\r') {
  14108.         if (normal) {
  14109.         write(1, buf + (x - normal), normal);
  14110.         length += normal;
  14111.         normal = 0;
  14112.         }
  14113.         holdingcr = 1;
  14114.     } else if (c == '\n') {
  14115.         write(1, buf + (x - normal), normal + 1);
  14116.         normal = 0;
  14117.         length = 0;
  14118.         holdingcr = 0;
  14119.     } else if (c == '\b') {
  14120.         if (normal) {
  14121.         write(1, buf + (x - normal), normal);
  14122.         length += normal;
  14123.         normal = 0;
  14124.         }
  14125.         if (length) {
  14126.         write(1, &c, 1);
  14127.         length--;
  14128.         }
  14129.         holdingcr = 0;
  14130.     } else {
  14131.         if (holdingcr) {
  14132.         char b = '\b';
  14133.         while (length-- > 0)
  14134.           write(1, &b, 1);
  14135.         length = 0;    /* compiler bug */
  14136.         }
  14137.         holdingcr = 0;
  14138.         normal++;
  14139.     }
  14140.     }
  14141.     if (normal) {
  14142.     write(1, buf + (x - normal), normal);
  14143.     length += normal;
  14144.     }
  14145.     return n;
  14146. }
  14147.  
  14148. void
  14149. conprint(char *fmt, ...) {
  14150.     static char buf[1000];        /* not safe if on the stack */
  14151.  
  14152.     va_list ap;
  14153.     int i;
  14154.  
  14155.     va_start(ap, fmt);
  14156.     i = vsprintf(buf, fmt, ap);
  14157.     conwrite(buf, i);
  14158. }
  14159. #endif /* Plan9 */
  14160.  
  14161. /* fprintf, printf, perror replacements... */
  14162.  
  14163. /* f p r i n t f */
  14164.  
  14165. #ifdef UNIX
  14166. #ifdef CK_ANSIC
  14167. #include <stdarg.h>
  14168. #else /* CK_ANSIC */
  14169. #include <varargs.h>
  14170. #endif /* CK_ANSIC */
  14171. #ifdef fprintf
  14172. #undef fprintf
  14173. static char str1[4096];
  14174. static char str2[4096];
  14175. int
  14176. #ifdef CK_ANSIC
  14177. ckxfprintf(FILE * file, const char * format, ...)
  14178. #else /* CK_ANSIC */
  14179. ckxfprintf(va_alist) va_dcl
  14180. #endif /* CK_ANSIC */
  14181. /* ckxfprintf */ {
  14182.     int i, j, len, got_cr;
  14183.     va_list args;
  14184.     int rc = 0;
  14185.  
  14186. #ifdef CK_ANSIC
  14187.     va_start(args, format);
  14188. #else /* CK_ANSIC */
  14189.     char * format;
  14190.     FILE * file;
  14191.     va_start(args);
  14192.     file = va_arg(args,FILE *);
  14193.     format = va_arg(args,char *);
  14194. #endif /* CK_ANSIC */
  14195.  
  14196.     if (!inserver || (file != stdout && file != stderr && file != stdin)) {
  14197.     rc = vfprintf(file,format,args);
  14198.     } else {
  14199.     unsigned int c;
  14200.         rc = vsprintf(str1, format, args);
  14201.         len = strlen(str1);
  14202.         if (len >= sizeof(str1)) {
  14203.             debug(F101,"ckxfprintf() buffer overflow","",len);
  14204.             doexit(BAD_EXIT,1);
  14205.         }
  14206.         for (i = 0, j = 0, got_cr = 0;
  14207.          i < len && j < sizeof(str1)-2;
  14208.          i++, j++ ) {
  14209.         /* We can't use 255 as a case label because of signed chars */
  14210.         c = (unsigned)(str1[i] & 0xff);
  14211. #ifdef TNCODE
  14212.         if (c == 255) {
  14213.         if (got_cr && !TELOPT_ME(TELOPT_BINARY))
  14214.           str2[j++] = '\0';
  14215.         str2[j++] = IAC;
  14216.         str2[j] = IAC;
  14217.         got_cr = 0;
  14218.         } else
  14219. #endif /* TNCODE */
  14220.         switch (c) {
  14221.           case '\r':
  14222.                 if (got_cr
  14223. #ifdef TNCODE
  14224.             && !TELOPT_ME(TELOPT_BINARY)
  14225. #endif /* TNCODE */
  14226.             )
  14227.           str2[j++] = '\0';
  14228.                 str2[j] = str1[i];
  14229.                 got_cr = 1;
  14230.                 break;
  14231.           case '\n':
  14232.                 if (!got_cr)
  14233.           str2[j++] = '\r';
  14234.                 str2[j] = str1[i];
  14235.                 got_cr = 0;
  14236.                 break;
  14237.           default:
  14238.                 if (got_cr
  14239. #ifdef TNCODE
  14240.             && !TELOPT_ME(TELOPT_BINARY)
  14241. #endif /* TNCODE */
  14242.             )
  14243.           str2[j++] = '\0';
  14244.                 str2[j] = str1[i];
  14245.                 got_cr = 0;
  14246.             }
  14247.         }
  14248.         if (got_cr
  14249. #ifdef TNCODE
  14250.              && !TELOPT_ME(TELOPT_BINARY)
  14251. #endif /* TNCODE */
  14252.              )
  14253.             str2[j++] = '\0';
  14254. #ifdef CK_ENCRYPTION
  14255. #ifdef TNCODE
  14256.         if (TELOPT_ME(TELOPT_ENCRYPTION))
  14257.       ck_tn_encrypt(str2,j);
  14258. #endif /* TNCODE */
  14259. #endif /* CK_ENCRYPTION */
  14260. #ifdef CK_SSL
  14261.     if (inserver && (ssl_active_flag || tls_active_flag)) {
  14262.         /* Write using SSL */
  14263.             char * p = str2;
  14264.           ssl_retry:
  14265.             if (ssl_active_flag)
  14266.           rc = SSL_write(ssl_con, p, j);
  14267.             else
  14268.           rc = SSL_write(tls_con, p, j);
  14269.         debug(F111,"ckxfprintf","SSL_write",rc);
  14270.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,rc)) {
  14271.           case SSL_ERROR_NONE:
  14272.                 if (rc == j)
  14273.           break;
  14274.                 p += rc;
  14275.                 j -= rc;
  14276.                 goto ssl_retry;
  14277.           case SSL_ERROR_WANT_WRITE:
  14278.           case SSL_ERROR_WANT_READ:
  14279.           case SSL_ERROR_SYSCALL:
  14280.                 if (rc != 0)
  14281.           return(-1);
  14282.           case SSL_ERROR_WANT_X509_LOOKUP:
  14283.           case SSL_ERROR_SSL:
  14284.           case SSL_ERROR_ZERO_RETURN:
  14285.           default:
  14286.                 rc = 0;
  14287.             }
  14288.     } else
  14289. #endif /* CK_SSL */
  14290.         fwrite(str2,sizeof(char),j,stdout);
  14291.     }
  14292.     va_end(args);
  14293.     return(rc);
  14294. }
  14295. #endif /* fprintf */
  14296.  
  14297. /* p r i n t f */
  14298.  
  14299. #ifdef printf
  14300. #undef printf
  14301. int
  14302. #ifdef CK_ANSIC
  14303. ckxprintf(const char * format, ...)
  14304. #else /* CK_ANSIC */
  14305. ckxprintf(va_alist) va_dcl
  14306. #endif /* CK_ANSIC */
  14307. /* ckxprintf */ {
  14308.     int i, j, len, got_cr;
  14309.     va_list args;
  14310.     int rc = 0;
  14311.  
  14312. #ifdef CK_ANSIC
  14313.     va_start(args, format);
  14314. #else /* CK_ANSIC */
  14315.     char * format;
  14316.     va_start(args);
  14317.     format = va_arg(args,char *);
  14318. #endif /* CK_ANSIC */
  14319.  
  14320.     if (!inserver) {
  14321.     rc = vprintf(format, args);
  14322.     } else {
  14323.     unsigned int c;
  14324.         rc = vsprintf(str1, format, args);
  14325.         len = strlen(str1);
  14326.         if (len >= sizeof(str1)) {
  14327.             debug(F101,"ckxprintf() buffer overflow","",len);
  14328.             doexit(BAD_EXIT,1);
  14329.         }
  14330.         for (i = 0, j = 0, got_cr=0;
  14331.          i < len && j < sizeof(str1)-2;
  14332.          i++, j++ ) {
  14333.         c = (unsigned)(str1[i] & 0xff);
  14334. #ifdef TNCODE
  14335.         if (c == 255) {
  14336.         if (got_cr && !TELOPT_ME(TELOPT_BINARY))
  14337.           str2[j++] = '\0';
  14338.         str2[j++] = IAC;
  14339.         str2[j] = IAC;
  14340.         got_cr = 0;
  14341.         } else
  14342. #endif /* TNCODE */
  14343.         switch (c) {
  14344.           case '\r':
  14345.                 if (got_cr
  14346. #ifdef TNCODE
  14347.             && !TELOPT_ME(TELOPT_BINARY)
  14348. #endif /* TNCODE */
  14349.             )
  14350.           str2[j++] = '\0';
  14351.                 str2[j] = str1[i];
  14352.                 got_cr = 1;
  14353.                 break;
  14354.           case '\n':
  14355.                 if (!got_cr)
  14356.           str2[j++] = '\r';
  14357.                 str2[j] = str1[i];
  14358.                 got_cr = 0;
  14359.                 break;
  14360.           default:
  14361.                 if (got_cr
  14362. #ifdef TNCODE
  14363.             && !TELOPT_ME(TELOPT_BINARY)
  14364. #endif /* TNCODE */
  14365.             )
  14366.           str2[j++] = '\0';
  14367.                 str2[j] = str1[i];
  14368.                 got_cr = 0;
  14369.                 break;
  14370.         }
  14371.         }
  14372.         if (got_cr
  14373. #ifdef TNCODE
  14374.              && !TELOPT_ME(TELOPT_BINARY)
  14375. #endif /* TNCODE */
  14376.              )
  14377.             str2[j++] = '\0';
  14378. #ifdef CK_ENCRYPTION
  14379. #ifdef TNCODE
  14380.         if (TELOPT_ME(TELOPT_ENCRYPTION))
  14381.       ck_tn_encrypt(str2,j);
  14382. #endif /* TNCODE */
  14383. #endif /* CK_ENCRYPTION */
  14384. #ifdef CK_SSL
  14385.     if (inserver && (ssl_active_flag || tls_active_flag)) {
  14386.             char * p = str2;
  14387.         /* Write using SSL */
  14388.           ssl_retry:
  14389.             if (ssl_active_flag)
  14390.           rc = SSL_write(ssl_con, p, j);
  14391.             else
  14392.           rc = SSL_write(tls_con, p, j);
  14393.         debug(F111,"ckxprintf","SSL_write",rc);
  14394.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,rc)) {
  14395.           case SSL_ERROR_NONE:
  14396.                 if (rc == j)
  14397.           break;
  14398.                 p += rc;
  14399.                 j -= rc;
  14400.                 goto ssl_retry;
  14401.           case SSL_ERROR_WANT_WRITE:
  14402.           case SSL_ERROR_WANT_READ:
  14403.           case SSL_ERROR_SYSCALL:
  14404.                 if (rc != 0)
  14405.           return(-1);
  14406.           case SSL_ERROR_WANT_X509_LOOKUP:
  14407.           case SSL_ERROR_SSL:
  14408.           case SSL_ERROR_ZERO_RETURN:
  14409.           default:
  14410.                 rc = 0;
  14411.             }
  14412.     } else
  14413. #endif /* CK_SSL */
  14414.       rc = fwrite(str2,sizeof(char),j,stdout);
  14415.     }
  14416.     va_end(args);
  14417.     return(rc);
  14418. }
  14419. #endif /* printf */
  14420.  
  14421. /*  p e r r o r  */
  14422.  
  14423. #ifdef perror
  14424. #undef perror
  14425. _PROTOTYP(char * ck_errstr,(VOID));
  14426. #ifdef NEXT
  14427. void
  14428. #else
  14429. #ifdef CK_SCOV5
  14430. void
  14431. #else
  14432. int
  14433. #endif /* CK_SCOV5 */
  14434. #endif /* NEXT */
  14435. #ifdef CK_ANSIC
  14436. ckxperror(const char * str)
  14437. #else /* CK_ANSIC */
  14438. ckxperror(str) char * str;
  14439. #endif /* CK_ANSIC */
  14440. /* ckxperror */ {
  14441.     char * errstr = ck_errstr();
  14442. #ifndef NEXT
  14443. #ifndef CK_SCOV5
  14444.     return
  14445. #endif /* CK_SCOV5 */
  14446. #endif /* NEXT */
  14447.       ckxprintf("%s%s %s\n",str,*errstr?":":"",errstr);
  14448. }
  14449. #endif /* perror */
  14450. #endif /* UNIX */
  14451.  
  14452. #ifdef MINIX2
  14453.  
  14454. /* Minix doesn't have a gettimeofday call. We fake one here using time(2) */
  14455.  
  14456. int
  14457. gettimeofday(struct timeval *tp, struct timezone *tzp) {
  14458.     tp->tv_usec = 0L;            /* Close enough for horseshoes */
  14459.     if(time(&(tp->tv_sec))==-1)
  14460.       return(-1);
  14461.     return(0);
  14462. }
  14463.  
  14464. /* Minix does not support symbolic links. We implement a version of
  14465.    readlink that always fails */
  14466.  
  14467. int
  14468. readlink(const char *path, void *buf, size_t bufsiz) {
  14469.     errno = ENOSYS;
  14470.     return(-1);
  14471. }
  14472. #endif /* MINIX2 */
  14473.