home *** CD-ROM | disk | FTP | other *** search
/ Columbia Kermit / kermit.zip / archives / ck208 / cku208.tar.gz / cku208.tar / ckutio.c < prev    next >
C/C++ Source or Header  |  2003-01-14  |  410KB  |  14,471 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 suspend, 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 LFDEVNO                /* Define this for SVR4 */
  4726. #ifndef AIXRS                /* But not for RS/6000 AIX 3.2, etc. */
  4727. #ifndef BSD44                /* If anybody else needs it... */
  4728. #ifndef __386BSD__
  4729. #ifndef __FreeBSD__
  4730. #ifndef HPUX10
  4731. #ifndef IRIX51                /* SGI IRIX 5.1 or later */
  4732. #ifndef CK_SCOV5            /* SCO Open Server 5.0 */
  4733. #define LFDEVNO
  4734. #endif /* CK_SCOV5 */
  4735. #endif /* IRIX51 */
  4736. #endif /* HPUX10 */
  4737. #endif /* __FreeBSD__ */
  4738. #endif /* __386BSD__ */
  4739. #endif /* BSD44 */
  4740. #endif /* AIXRS */
  4741. #endif /* LFDEVNO */            /* ... define it here or on CC */
  4742. #endif /* SVR4 */            /* command line. */
  4743.  
  4744. #ifdef COHERENT
  4745. #define LFDEVNO
  4746. #endif /* COHERENT */
  4747.  
  4748. /*
  4749.   For platforms where the lockfile name is made from device/major/minor
  4750.   device number, as in SVR4.  Which, if we must have lockfiles at all, is
  4751.   by far the best format, since it eliminates all the confusion that stems
  4752.   from multiple names (or drivers) for the same port, not to mention
  4753.   symlinks.  It might even be a good idea to start using this form even
  4754.   on platforms where it's not supported, alongside the normal forms for those
  4755.   platforms, in order to get people used to it...
  4756. */
  4757. #ifdef LFDEVNO
  4758. #ifndef major                /* If we didn't find it */
  4759. #ifdef SVR4                /* then for Sys V R4 */
  4760. #include <sys/mkdev.h>            /* look here */
  4761. #else                    /* or for SunOS versions */
  4762. #ifdef SUNOS4                /* ... */
  4763. #include <sys/sysmacros.h>        /* look here */
  4764. #else                    /* Otherwise take a chance: */
  4765. #define    major(dev) ( (int) ( ((unsigned)(dev) >> 8) & 0xff))
  4766. #define    minor(dev) ( (int) ( (dev) & 0xff))
  4767. #endif /* SUNOS4 */
  4768. #endif /* SVR4 */
  4769. #endif /* major */
  4770. #endif /* LFDEVNO */
  4771.  
  4772. /* No advisory locks if F_TLOCK and F_ULOCK are not defined at this point */
  4773.  
  4774. #ifdef LOCKF
  4775. #ifndef F_TLOCK
  4776. #undef LOCKF
  4777. #ifndef NOLOCKF
  4778. #define NOLOCKF
  4779. #endif /* NOLOCKF */
  4780. #endif /* F_TLOCK */
  4781. #endif /* LOCKF */
  4782.  
  4783. #ifdef LOCKF
  4784. #ifndef F_ULOCK
  4785. #undef LOCKF
  4786. #ifndef NOLOCKF
  4787. #define NOLOCKF
  4788. #endif /* NOLOCKF */
  4789. #endif /* F_ULOCK */
  4790. #endif /* LOCKF */
  4791.  
  4792. static char linkto[DEVNAMLEN+1];
  4793. static char * linkdev = NULL;
  4794.  
  4795. #ifndef NOUUCP
  4796. #ifdef USETTYLOCK
  4797. #ifdef LOCK_DIR
  4798. char * uucplockdir = LOCK_DIR;
  4799. #else
  4800. char * uucplockdir = "";
  4801. #endif /* LOCK_DIR */
  4802. #else
  4803. #ifdef LOCK_DIR
  4804. char * uucplockdir = LOCK_DIR;
  4805. #else
  4806. char * uucplockdir = "";
  4807. #endif /* LOCK_DIR */
  4808. #endif /* USETTYLOCK */
  4809. #else
  4810. char * uucplockdir = "";
  4811. #endif /* NOUUCP */
  4812.  
  4813. #ifdef QNX                /* Only for QNX4 */
  4814. int                    /* Visible to outside world */
  4815. qnxopencount() {            /* Get QNX device open count */
  4816.     struct _dev_info_entry info;
  4817.     int x;
  4818.  
  4819.     x = -1;                /* Unknown */
  4820.     if (ttyfd > -1) {
  4821.     if (!dev_info(ttyfd, &info)) {
  4822.         debug(F101,"ttlock QNX open_count","",info.open_count);
  4823.         x = info.open_count;
  4824.     }
  4825.     }
  4826.     return(x);
  4827. }
  4828. #endif /* QNX */
  4829.  
  4830. char *
  4831. ttglckdir() {                /* Get Lockfile directory name */
  4832. #ifdef __OpenBSD__
  4833.     return("/var/spool/lock");
  4834. #else /* __OpenBSD__ */
  4835. #ifdef __FreeBSD__
  4836.     return("/var/spool/lock");
  4837. #else  /* __FreeBSD__ */
  4838. #ifdef LOCK_DIR
  4839.     char * s = LOCK_DIR;
  4840. #endif /* LOCK_DIR */
  4841. #ifdef NOUUCP
  4842.     return("");
  4843. #else  /* NOUUCP */
  4844. #ifdef LOCK_DIR
  4845.     return(s);
  4846. #else  /* LOCK_DIR */
  4847.     return("");
  4848. #endif /* LOCK_DIR */
  4849. #endif /* NOUUCP */
  4850. #endif /* __FreeBSD__ */
  4851. #endif /* __OpenBSD__ */
  4852. }
  4853.  
  4854. static int
  4855. ttlock(ttdev) char *ttdev; {
  4856.  
  4857.     int x, n;
  4858.     int islink = 0;
  4859.  
  4860. #ifdef NOUUCP
  4861.     debug(F100,"ttlock NOUUCP","",0);
  4862.     ckstrncpy(flfnam,"NOLOCK",FLFNAML);
  4863.     haslock = 1;
  4864.     return(0);
  4865. #else /* !NOUUCP */
  4866.  
  4867. #ifdef USETTYLOCK
  4868.     haslock = 0;                        /* Not locked yet. */
  4869.     *flfnam = '\0';            /* Lockfile name is empty. */
  4870.     if (!strncmp(ttdev,"/dev/",5) && ttdev[5])
  4871.       ckstrncpy(lockname,ttdev+5,DEVNAMLEN);
  4872.     else
  4873.       ckstrncpy(lockname,ttdev,DEVNAMLEN);
  4874. /*
  4875.   This might be overkill, but it's not clear from the man pages whether
  4876.   ttylock() can be called without calling ttylocked() first, since the doc
  4877.   says that ttylocked() removes any stale lockfiles, but it does not say this
  4878.   about ttylock().  Also the docs don't say what ttylocked() returns in the
  4879.   case when it finds and removes a stale lockfile.  So one or both calls to
  4880.   to ttylocked() might be superfluous, but they should do no harm.  Also I'm
  4881.   assuming that we have to do all the same ID swapping, etc, with these
  4882.   routines as we do without them.  Thus the priv_on/off() sandwich.
  4883. */
  4884. #ifdef USE_UU_LOCK
  4885.     priv_on();                /* Turn on privs */
  4886.     x = uu_lock(lockname);        /* Try to set the lock */
  4887.     priv_off();                /* Turn privs off */
  4888.     debug(F111,"ttlock uu_lock",lockname,x);
  4889.     switch (x) {
  4890.       case UU_LOCK_INUSE:
  4891.     return(-2);
  4892.       case UU_LOCK_OK:
  4893. #ifdef BSD44
  4894.     ckmakmsg(flfnam,FLFNAML,"/var/spool/lock/LCK..",lockname,NULL,NULL);
  4895. #endif /* BSD44 */
  4896.     haslock = 1;
  4897.     return(0);
  4898.       default:
  4899.     return(-1);
  4900.     }
  4901. #else  /* USE_UU_LOCK */
  4902.     priv_on();                /* Turn on privs */
  4903.     if (ttylocked(lockname)) {        /* This should remove any stale lock */
  4904.     if (ttylocked(lockname)) {    /* so check again. */
  4905.         priv_off();
  4906.         return(-5);            /* Still locked, fail. */
  4907.     }
  4908.     }
  4909.     x = ttylock(lockname);        /* Lock it. */
  4910.     priv_off();                /* Turn off privs */
  4911.  
  4912.     debug(F111,"ttlock lockname",lockname,x);
  4913.     if (x > -1) {
  4914.     /*
  4915.       We don't really know the name of the lockfile, but
  4916.       this is what the man page says it is.  In USETTYLOCK
  4917.           builds, it is used only for display by SHOW COMM.
  4918.     */
  4919.     ckmakmsg(flfnam,FLFNAML,"/etc/locks/LCK..",lockname,NULL,NULL);
  4920.     haslock = 1;
  4921.     }
  4922.     return(x);
  4923. #endif /* USE_UU_LOCK */
  4924. #else  /* Systems that don't have ttylock()... */
  4925.  
  4926. #ifndef HPUX
  4927.  
  4928.     int lockfd;                /* File descriptor for lock file. */
  4929.     PID_T pid;                /* Process id of this process. */
  4930.     int tries;                /* How many times we've tried... */
  4931.     struct stat devbuf;            /* For device numbers (SVR4). */
  4932.  
  4933. #ifdef PIDSTRING
  4934.     char pid_str[32];            /* My pid in string format. */
  4935. #endif /* PIDSTRING */
  4936.  
  4937.     char *device, *devname;
  4938.  
  4939. #define LFNAML 256            /* Max length for lock file name. */
  4940.     char lockfil[LFNAML];        /* Lock file name */
  4941. #ifdef RTAIX
  4942.     char lklockf[LFNAML];        /* Name for link to lock file  */
  4943. #endif /* RTAIX */
  4944. #ifdef CKSYMLINK
  4945.     char symlock[LFNAML];        /* Name for symlink lockfile name */
  4946. #endif /* CKSYMLINK */
  4947.     char tmpnam[LFNAML+30];        /* Temporary lockfile name. */
  4948.     char *lockdir = LOCK_DIR;        /* Defined near top of this file, */
  4949.                     /* or on cc command line. */
  4950.     haslock = 0;                        /* Not locked yet. */
  4951.     *flfnam = '\0';            /* Lockfile name is empty. */
  4952.     lock2[0] = '\0';            /* Clear secondary lockfile name. */
  4953.     pid = getpid();            /* Get id of this process. */
  4954.  
  4955. /*  Construct name of lockfile and temporary file */
  4956.  
  4957. /*  device  = name of tty device without the path, e.g. "ttyh8" */
  4958. /*  lockfil = name of lock file, without path, e.g. "LCK..ttyh8" */
  4959.  
  4960.     device = ((devname = xxlast(ttdev,'/')) != NULL ? devname+1 : ttdev);
  4961.  
  4962.     if (stat(ttdev,&devbuf) < 0)
  4963.       return(-1);
  4964.  
  4965. #ifdef CKSYMLINK
  4966.     islink = 1;                /* Assume it's a symlink */
  4967.     linkto[0] = '\0';            /* But we don't know to what */
  4968. #ifdef COMMENT
  4969. /*
  4970.   This is undependable.  If it worked it would save the readlink call if
  4971.   we knew the device name was not a link.
  4972. */
  4973. #ifdef S_ISLNK
  4974.     islink = S_ISLNK(devbuf.st_mode);
  4975.     debug(F101,"ttlock stat S_ISLNK","",islink);
  4976. #endif /* S_ISLNK */
  4977. #endif /* COMMENT */
  4978.     if (islink) {
  4979.     n = readlink(ttdev,linkto,DEVNAMLEN); /* See if it's a link */
  4980.     debug(F111,"ttlock readlink",ttdev,n);
  4981.     if (n > -1)            /* It is */
  4982.       linkto[n] = '\0';
  4983.     else                /* It's not */
  4984.       islink = 0;
  4985.     debug(F111,"ttlock link",linkto,islink);
  4986.     }
  4987.     if (islink) {
  4988.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  4989.     debug(F110,"ttlock linkdev",linkdev,0);
  4990.     }
  4991. #endif /* CKSYMLINK */
  4992.  
  4993. /*
  4994.   On SCO platforms, if we don't have a symlink, then let's pretend the
  4995.   name given for the device is a symlink, because later we will change
  4996.   the name if it contains any uppercase characters.
  4997. */
  4998. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  4999.     if (!islink) {
  5000.     islink = 1;
  5001.     ckstrncpy(linkto,ttdev,DEVNAMLEN);
  5002.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  5003.     debug(F110,"ttlock linkdev",linkdev,0);
  5004.     }
  5005. #else
  5006. #ifdef M_XENIX                /* SCO Xenix or UNIX */
  5007.     if (!islink) {
  5008.     islink = 1;
  5009.     ckstrncpy(linkto,ttdev,DEVNAMLEN);
  5010.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  5011.     debug(F110,"ttlock linkdev",linkdev,0);
  5012.     }
  5013. #endif /* M_XENIX */
  5014. #endif /* CK_SCOV5 */
  5015.  
  5016. #ifdef ISIII                /* Interactive System III, PC/IX */
  5017.     ckstrncpy(lockfil, device, DEVNAMLEN);
  5018. #else  /* not ISIII */
  5019. #ifdef LFDEVNO                /* Lockfilename has device numbers. */
  5020. #ifdef COHERENT
  5021.     sprintf(lockfil,"LCK..%d.%d",    /* SAFE */
  5022.         major(devbuf.st_rdev),       /* major device number */
  5023.         0x1f & minor(devbuf.st_rdev)); /* minor device number */
  5024. #else
  5025.     /* Note: %d changed to %u in 8.0 -- %u is part of SVID for SVR4 */
  5026.     /* Lockfile name format verified to agree with Solaris cu, Dec 2001 */
  5027.     sprintf(lockfil,"LK.%03u.%03u.%03u", /* SAFE */
  5028.         major(devbuf.st_dev),    /* device */
  5029.         major(devbuf.st_rdev),    /* major device number */
  5030.         minor(devbuf.st_rdev));    /* minor device number */
  5031. #endif /* COHERENT */
  5032. #else  /* Not LFDEVNO */
  5033. #ifdef PTX                /* Dynix PTX */
  5034.     if ((device != &ttdev[5]) && (strncmp(ttdev,"/dev/",5) == 0)) {
  5035.     if ((int)strlen(device) + 8 < LFNAML)
  5036.       sprintf(lockfil,"LCK..%.3s%s", &ttdev[5], device);
  5037.     else
  5038.       ckstrncpy(lockfil,"LOCKFILE_NAME_TOO_LONG",LFNAML);
  5039.     } else
  5040. #endif /* PTX */
  5041.       if ((int)strlen(device) + 5 < LFNAML)
  5042.     sprintf(lockfil,"LCK..%s", device);
  5043.       else
  5044.     ckstrncpy(lockfil,"LOCKFILE_NAME_TOO_LONG",LFNAML);
  5045. #ifdef RTAIX
  5046.     ckstrncpy(lklockf,device,DEVNAMLEN);
  5047. #endif /* RTAIX */
  5048. #ifdef CKSYMLINK
  5049.     symlock[0] = '\0';
  5050.     if (islink)
  5051.       ckmakmsg(symlock,LFNAML, "LCK..", linkdev, NULL, NULL);
  5052. #endif /* CKSYMLINK */
  5053. #endif /* LFDEVNO */
  5054. #endif /* ISIII */
  5055.  
  5056. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  5057.     {
  5058.     /* Lowercase the entire filename. */
  5059.         /* SCO says we must do this in V5.0 and later. */
  5060.     /* BUT... watch out for devices -- like Digiboard Portserver */
  5061.     /* That can have hundreds of ports... */
  5062.     char *p = (char *)(lockfil + 5);
  5063.     while (*p) { if (isupper(*p)) *p = (char) tolower(*p); p++; }
  5064.     }
  5065. #ifdef CKSYMLINK
  5066.     if (islink) {            /* If no change */
  5067.     if (!strcmp(lockfil,symlock)) {    /* then no second lockfile needed */
  5068.         islink = 0;
  5069.         symlock[0] = '\0';
  5070.     }
  5071.     }
  5072. #endif /* CKSYMLINK */
  5073. #else
  5074. #ifdef M_XENIX                /* SCO Xenix or UNIX */
  5075.     {
  5076.     int x; char c;
  5077.     x = (int)strlen(lockfil) - 1;    /* Get last letter of device name. */
  5078.     if (x > 0) {            /* If it's uppercase, lower it. */
  5079.         c = lockfil[x];
  5080.         if (c >= 'A' && c <= 'Z') lockfil[x] += ('a' - 'A');
  5081.     }
  5082.     }
  5083. #ifdef CKSYMLINK
  5084.     if (islink) {
  5085.     if (!strcmp(lockfil,symlock)) {    /* No change */
  5086.         islink = 0;            /* so no second lockfile */
  5087.         symlock[0] = '\0';
  5088.     }
  5089.     }
  5090. #endif /* CKSYMLINK */
  5091. #endif /* M_XENIX */
  5092. #endif /* CK_SCOV5 */
  5093.  
  5094. /*  flfnam = full lockfile pathname, e.g. "/usr/spool/uucp/LCK..ttyh8" */
  5095. /*  tmpnam = temporary unique, e.g. "/usr/spool/uucp/LTMP..pid" */
  5096.  
  5097.     ckmakmsg(flfnam,LFNAML,lockdir,"/",lockfil,NULL);
  5098.  
  5099. #ifdef RTAIX
  5100.     ckmakmsg(lkflfn,FLFNAML,lockdir,"/",lklockf,NULL);
  5101. #endif /* RTAIX */
  5102.  
  5103. #ifndef LFDEVNO
  5104. #ifdef CKSYMLINK
  5105.     /* If it's a link then also make a lockfile for the real name */
  5106.     debug(F111,"ttlock link symlock",symlock,islink);
  5107.     if (islink && symlock[0]) {
  5108.     /* But only if the lockfile names would be different. */
  5109.     /* WARNING: They won't be, e.g. for /dev/ttyd2 => /hw/ttys/ttyd2 */
  5110.     ckmakmsg(lock2,FLFNAML,lockdir,"/",symlock,NULL);
  5111.     debug(F110,"ttlock lock2",lock2,0);
  5112.     if (!strcmp(lock2,flfnam)) {    /* Are lockfile names the same? */
  5113.         debug(F100,"ttlock lock2 cleared","",0);
  5114.         lock2[0] = '\0';        /* Clear secondary lockfile name. */
  5115.     }
  5116.     }
  5117. #endif /* CKSYMLINK */
  5118. #endif /* LFDEVNO */
  5119.  
  5120.     sprintf(tmpnam,"%s/LTMP.%05d",lockdir,(int) pid); /* safe */
  5121.     debug(F110,"ttlock flfnam",flfnam,0);
  5122.     debug(F110,"ttlock tmpnam",tmpnam,0);
  5123.  
  5124.     priv_on();                /* Turn on privileges if possible. */
  5125.     lockfd = creat(tmpnam, 0444);    /* Try to create temp lock file. */
  5126.     if (lockfd < 0) {            /* Create failed. */
  5127.     debug(F111,"ttlock creat failed",tmpnam,errno);
  5128.     if (errno == ENOENT) {
  5129.         perror(lockdir);
  5130.         printf("UUCP not installed or Kermit misconfigured\n");
  5131.     } else {
  5132.         if (!quiet)
  5133.           perror(lockdir);
  5134.         unlink(tmpnam);        /* Get rid of the temporary file. */
  5135.     }
  5136.     priv_off();            /* Turn off privileges!!! */
  5137.     return(-1);            /* Return failure code. */
  5138.     }
  5139. /* Now write the pid into the temp lockfile in the appropriate format */
  5140.  
  5141. #ifdef PIDSTRING            /* For Honey DanBer UUCP, */
  5142.     sprintf(                /* write PID as decimal string */
  5143.         pid_str,
  5144. #ifdef LINUXFSSTND            /* The "Linux File System Standard" */
  5145. #ifdef FSSTND10                /* Version 1.0 calls for */
  5146.         "%010d\n",            /* leading zeros */
  5147. #else                    /* while version 1.2 calls for */
  5148.         "%10d\n",            /* leading spaces */
  5149. #endif /* FSSTND10 */
  5150. #else
  5151. #ifdef COHERENT
  5152.         "%d\n",            /* with leading nothing */
  5153. #else
  5154.         "%10d\n",            /* with leading blanks */
  5155. #endif /* COHERENT */
  5156. #endif /* LINUXFSSTND */
  5157.         (int) pid
  5158.         );                /* safe */
  5159.     write(lockfd, pid_str, 11);
  5160.     debug(F111,"ttlock hdb pid string",pid_str,(int) pid);
  5161.  
  5162. #else /* Not PIDSTRING, use integer PID */
  5163.  
  5164.     write(lockfd, (char *)&pid, sizeof(pid) );
  5165.     debug(F101,"ttlock pid","",(int) pid);
  5166.  
  5167. #endif /* PIDSTRING */
  5168.  
  5169. /* Now try to rename the temp file to the real lock file name. */
  5170. /* This will fail if a lock file of that name already exists.  */
  5171.  
  5172.     close(lockfd);            /* Close the temp lockfile. */
  5173.     chmod(tmpnam,0444);            /* Permission for a valid lock. */
  5174.     tries = 0;
  5175.     while (!haslock && tries++ < 2) {
  5176.     haslock = (link(tmpnam,flfnam) == 0); /* Create a link to it. */
  5177.     if (haslock) {                  /* If we got the lockfile */
  5178. #ifdef RTAIX
  5179.         link(flfnam,lkflfn);
  5180. #endif /* RTAIX */
  5181. #ifdef CKSYMLINK
  5182. #ifndef LFDEVNO
  5183.         if (islink && lock2[0])
  5184.           link(flfnam,lock2);
  5185. #endif /* LFDEVNO */
  5186. #endif /* CKSYMLINK */
  5187.  
  5188. #ifdef COMMENT
  5189. /* Can't do this any more because device is not open yet so no ttyfd. */
  5190. #ifdef LOCKF
  5191. /*
  5192.   Advisory file locking works on SVR4, so we use it.  In fact, it is
  5193.   necessary in some cases, e.g. when SLIP is involved.  But it still doesn't
  5194.   seem to prevent multiple users accessing the same device by different names.
  5195. */
  5196.             while (lockf(ttyfd, F_TLOCK, 0L) != 0) {
  5197.                 debug(F111, "ttlock lockf returns errno", "", errno);
  5198.                 if ((++tries >= 3) || (errno != EAGAIN)) {
  5199.                     x = unlink(flfnam); /* remove the lockfile */
  5200. #ifdef RTAIX
  5201.             unlink(lkflfn);    /* And any links to it... */
  5202. #endif /* RTAIX */
  5203. #ifdef CKSYMLINK
  5204. #ifndef LFDEVNO
  5205.             if (islink && lock2[0])
  5206.               unlink(lock2);    /* ditto... */
  5207. #endif /* LFDEVNO */
  5208. #endif /* CKSYMLINK */
  5209.                     debug(F111,"ttlock unlink",flfnam,x);
  5210.                     haslock = 0;
  5211.             break;
  5212.         }
  5213.                 sleep(2);
  5214.         }
  5215.         if (haslock)        /* If we got an advisory lock */
  5216. #endif /* LOCKF */
  5217. #endif /* COMMENT */
  5218.           break;            /* We're done. */
  5219.  
  5220.     } else {            /* We didn't create a new lockfile. */
  5221.         priv_off();
  5222.         if (ttchkpid(flfnam)) {    /* Check existing lockfile */
  5223.         priv_on();        /* cause ttchkpid turns priv_off... */
  5224.         unlink(tmpnam);        /* Delete the tempfile */
  5225.         debug(F100,"ttlock found tty locked","",0);
  5226.         priv_off();        /* Turn off privs */
  5227.         return(-2);        /* Code for device is in use. */
  5228.         }
  5229.         priv_on();
  5230.     }
  5231.     }
  5232.     unlink(tmpnam);            /* Unlink (remove) the temp file. */
  5233.     priv_off();                /* Turn off privs */
  5234.     return(haslock ? 0 : -1);        /* Return link's return code. */
  5235.  
  5236. #else /* HPUX */
  5237.  
  5238. /*
  5239.   HP-UX gets its own copy of this routine, modeled after the observed behavior
  5240.   of the HP-UX 'cu' program.  HP-UX serial device names consist of a base name
  5241.   such as "tty", "ttyd", "cua", "cul", "cuad", or "culd", followed by a unit
  5242.   designator which is a string of digits, possibly containing an imbedded
  5243.   letter "p".  Examples (for base name "tty"):
  5244.  
  5245.      /dev/tty0, /dev/tty00, dev/ttyd00, /dev/tty0p0
  5246.  
  5247.   According to the HP-UX UUCP manual of 1988, the "0p0" notation has been
  5248.   used on Series 800 since HP-UX 2.00, and the "non-p" notation was used
  5249.   on other models.  In HP-UX 10.00, "0p0" notation was adopted for all models.
  5250.   However, we make and enforce no such distinctions; either notation is
  5251.   accepted on any model or HP-UX version as a valid unit designator.
  5252.  
  5253.   If a valid unit is specified (as opposed to a designer name or symlink), we
  5254.   check for all aliases of the given unit according to the devprefix[] array.
  5255.   If no lockfiles are found for the given unit, we can have the device; we
  5256.   create a lockfile LCK..name in the lockfile directory appropriate for the
  5257.   HP-UX version (/var/spool/locks for 10.00 and later, /usr/spool/uucp for
  5258.   9.xx and earlier).  If it is a "cua" or "cul" device, a second lockfile is
  5259.   created with the "ttyd" prefix.  This is exactly what cu does.
  5260.  
  5261.   If the "set line" device does not have a valid unit designator, then it is
  5262.   used literally and no synomyms are searched for and only one lockfile is
  5263.   created.
  5264.  
  5265.   -fdc, March 1998.
  5266. */
  5267. #define LFNAML 80            /* Max length for lock file name. */
  5268.  
  5269.     int lockfd;                /* File descriptor for lock file. */
  5270.     PID_T pid;                /* Process ID of this process. */
  5271.     int fpid;                /* pid found in existing lockfile. */
  5272.     int tries;                /* How many times we've tried... */
  5273.     int i, k;                /* Workers */
  5274.  
  5275.     char *device, *devname;        /* "/dev/xxx", "xxx" */
  5276.     char *unit, *p;            /* <instance>p<port> part of xxx */
  5277.  
  5278.     char lockfil[LFNAML];        /* Lockfile name (no path) */
  5279.     char tmpnam[LFNAML];        /* Temporary lockfile name. */
  5280.  
  5281. #ifdef HPUX10                /* Lockfile directory */
  5282.     char *lockdir = "/var/spool/locks";    /* Always this for 10.00 and higher */
  5283. #else  /* HP-UX 9.xx and below */
  5284. #ifdef LOCK_DIR
  5285.     char *lockdir = LOCK_DIR;        /* Defined near top of this file */
  5286. #else
  5287.     char *lockdir = "/usr/spool/uucp";    /* or not... */
  5288. #endif /* LOCK_DIR */
  5289. #endif /* HPUX10 */
  5290.  
  5291.     haslock = 0;                        /* Not locked yet. */
  5292.     *flfnam = '\0';            /* Lockfile name is empty. */
  5293.     lock2[0] = '\0';            /* Second one too. */
  5294.     pid = getpid();            /* Get my process ID */
  5295. /*
  5296.   Construct name of lockfile and temporary file...
  5297.   device  = name of tty device without the path, e.g. "tty0p0"
  5298.   lockfil = name of lock file, without path, e.g. "LCK..tty0p0"
  5299. */
  5300.     device = ((devname = xxlast(ttdev,'/')) != NULL ? devname+1 : ttdev);
  5301.     debug(F110,"TTLOCK device",device,0);
  5302.     ckmakmsg(lockfil,LFNAML,"LCK..",device,NULL,NULL);
  5303.  
  5304.     k = 0;                /* Assume device is not locked */
  5305.     n = 0;                /* Digit counter */
  5306.     unit = device;            /* Unit = <instance>p<port> */
  5307.     while (*unit && !isdigit(*unit))    /* Search for digit... */
  5308.       unit++;
  5309.     p = unit;                /* Verify <num>p<num> format... */
  5310.     debug(F110,"TTLOCK unit 1",unit,0);
  5311. /*
  5312.   The unit number is recognized as:
  5313.   (a) any sequence of digits that runs to the end of the string.
  5314.   (b) any (a) that includes one and only one letter "p", with at least
  5315.       one digit before and after it.
  5316. */
  5317.     while (isdigit(*p)) p++, n++;    /* Get a run of digits */
  5318.     if (*p && n > 0) {            /* Have a "p"? */
  5319.     if (*p == 'p' && isdigit(*(p+1))) {
  5320.         p++;
  5321.         n = 0;
  5322.         while (isdigit(*p)) p++, n++;
  5323.     }
  5324.     }
  5325.     if (n == 0 || *p) unit = "";
  5326.     debug(F110,"TTLOCK unit 2",unit,0);
  5327.  
  5328.     if (*unit) {            /* Device name has unit number. */
  5329.     /* The following loop not only searches for the various lockfile    */
  5330.     /* synonyms, but also removes all -- not just one -- stale lockfile */
  5331.     /* for the device, should there be more than one.  See ttchkpid().  */
  5332.     ttydexists = 0;
  5333.     for (i = 0; *devprefix[i]; i++) { /* For each driver... */
  5334.         /* Make device name */
  5335.         ckmakmsg(lock2,FLFNAML,"/dev/",devprefix[i],unit,NULL);
  5336.         priv_on();            /* Privs on */
  5337.         k = zchki(lock2) != -1;    /* See if device exists */
  5338.         priv_off();            /* Privs off */
  5339.         debug(F111,"TTLOCK exist",lock2,k);
  5340.             if (k) {
  5341.         if (!strcmp(devprefix[i],"ttyd")) /* ttyd device exists */
  5342.           ttydexists = 1;
  5343.         /* Make lockfile name */
  5344.         ckmakmsg(lock2,FLFNAML,lockdir,"/LCK..",devprefix[i],unit);
  5345.         debug(F110,"TTLOCK checking",lock2,0);
  5346.         priv_on();        /* Privs on */
  5347.         k = zchki(lock2) != -1;    /* See if lockfile exists */
  5348.         priv_off();        /* Privs off */
  5349.         debug(F111,"TTLOCK check for lock A",lock2,k);
  5350.         if (k) if (ttchkpid(lock2)) { /* If pid still active, fail. */
  5351.             ckstrncpy(flfnam,lock2,FLFNAML);
  5352.             return(-2);
  5353.         }
  5354.         }
  5355.     }
  5356.     } else {                /* Some other device-name format */
  5357.     /* This takes care of symbolic links, etc... */
  5358.     /* But does not chase them down! */
  5359.     ckmakmsg(lock2,FLFNAML,lockdir,"/LCK..",device,NULL);
  5360.     priv_on();
  5361.     k = zchki(lock2) != -1;        /* Check for existing lockfile */
  5362.     priv_off();
  5363.     debug(F111,"TTLOCK check for lock B",lock2,k);
  5364.     if (k) if (ttchkpid(lock2)) {    /* Check pid from lockfile */
  5365.         ckstrncpy(flfnam,lock2,FLFNAML);
  5366.         debug(F110,"TTLOCK in use",device,0);
  5367.         debug(F101,"TTLOCK returns","",-2);
  5368.         return(-2);
  5369.     }
  5370.     }
  5371. /*
  5372.   Get here only if there is no (more) lockfile, so now we make one (or two)...
  5373.   flfnam = full lockfile pathname, e.g. "/usr/spool/uucp/LCK..cul0p0".
  5374.   tmpnam = unique temporary filname, e.g. "/usr/spool/uucp/LTMP..pid".
  5375. */
  5376.     ckmakmsg(flfnam,FLFNAML,lockdir,"/",lockfil,NULL); /* SET LINE device */
  5377.  
  5378.     /* If dialout device, also make one for corresponding dialin device */
  5379.     lock2[0] = '\0';
  5380.     if (!strncmp(device,"cu",2) && *unit && ttydexists)
  5381.       ckmakmsg(lock2,FLFNAML,lockdir,"/LCK..ttyd",unit,NULL);
  5382.  
  5383.     if ((int)strlen(lockdir)+12 < LFNAML)
  5384.       sprintf(tmpnam,"%s/LTMP.%05d",lockdir,(int) pid); /* Make temp name */
  5385. #ifdef DEBUG
  5386.     if (deblog) {
  5387.     debug(F110,"TTLOCK flfnam",flfnam,0);
  5388.     debug(F110,"TTLOCK lock2",lock2,0);
  5389.     debug(F110,"TTLOCK tmpnam",tmpnam,0);
  5390.     }
  5391. #endif /* DEBUG */
  5392. /*
  5393.    Lockfile permissions...
  5394.    444 is standard, HP-UX 10.00 uses 664.  It doesn't matter.
  5395.    Kermit uses 444; the difference lets us tell whether Kermit created
  5396.    the lock file.
  5397. */
  5398.     priv_on();                /* Turn on privileges. */
  5399.     lockfd = creat(tmpnam, 0444);    /* Try to create temporary file. */
  5400.     if (lockfd < 0) {            /* Create failed. */
  5401.     debug(F111,"TTLOCK creat failed",tmpnam,errno);
  5402.     if (errno == ENOENT) {
  5403.         perror(lockdir);
  5404.         printf("UUCP not installed or Kermit misconfigured\n");
  5405.     } else {
  5406.         if (!quiet)
  5407.           perror(lockdir);
  5408.         unlink(tmpnam);        /* Get rid of the temporary file. */
  5409.     }
  5410.     priv_off();            /* Turn off privileges!!! */
  5411.     debug(F101,"TTLOCK returns","",-1);
  5412.     return(-1);            /* Return failure code. */
  5413.     }
  5414.     debug(F110,"TTLOCK temp ok",tmpnam,0);
  5415.  
  5416. /* Now write our pid into the temp lockfile in integer format. */
  5417.  
  5418.     i = write(lockfd, (char *)&pid, sizeof(pid));
  5419.  
  5420. #ifdef DEBUG
  5421.     if (deblog) {
  5422.     debug(F101,"TTLOCK pid","",pid);
  5423.     debug(F101,"TTLOCK sizeof pid","",sizeof(pid));
  5424.     debug(F101,"TTLOCK write pid returns","",i);
  5425.     }
  5426. #endif /* DEBUG */
  5427.  
  5428. /*
  5429.   Now try to rename the temporary file to the real lockfile name.
  5430.   This will fail if a lock file of that name already exists, which
  5431.   will catch race conditions with other users.
  5432. */
  5433.     close(lockfd);            /* Close the temp lockfile. */
  5434.     chmod(tmpnam,0444);
  5435.  
  5436.     tries = 0;
  5437.     while (!haslock && tries++ < 2) {
  5438.     haslock = (link(tmpnam,flfnam) == 0); /* Create a link to it. */
  5439.     debug(F101,"TTLOCK link","",haslock);
  5440.     if (haslock) {            /* If we made the lockfile... */
  5441.  
  5442. #ifdef COMMENT
  5443. /* We can't do this any more because we don't have a file descriptor yet. */
  5444. #ifdef LOCKF                /* Can be canceled with -DNOLOCKF */
  5445. /*
  5446.   Create an advisory lock on the device through its file descriptor.
  5447.   This code actually seems to work.  If it is executed, and then another
  5448.   process tries to open the same device under a different name to circumvent
  5449.   the lockfile, they get a "device busy" error.
  5450. */
  5451.         debug(F100,"TTLOCK LOCKF code...","",0);
  5452.             while ( lockf(ttyfd, F_TLOCK, 0L) != 0 ) {
  5453.                 debug(F111, "TTLOCK lockf error", "", errno);
  5454.                 if ((++tries >= 3) || (errno != EAGAIN)) {
  5455.                     x = unlink(flfnam); /* Remove the lockfile */
  5456.             if (errno == EACCES && !quiet)
  5457.               printf("Device already locked by another process\n");
  5458.                     haslock = 0;
  5459.             break;
  5460.         }
  5461.                 sleep(2);
  5462.         }
  5463. #endif /* LOCKF */
  5464. #endif /* COMMENT */
  5465.  
  5466.         if (haslock) {        /* If we made the lockfile ... */
  5467.         if (lock2[0]) {        /* if there is to be a 2nd lockfile */
  5468.             lockfd = creat(lock2, 0444); /* Create it */
  5469.             debug(F111,"TTLOCK lock2 creat", lock2, lockfd);
  5470.             if (lockfd > -1) {    /* Created OK, write pid. */
  5471.             write(lockfd, (char *)&pid, sizeof(pid) );
  5472.             close(lockfd);    /* Close and */
  5473.             chmod(lock2, 0444); /* set permissions. */
  5474.             } else {         /* Not OK, but don't fail. */
  5475.             lock2[0] = '\0'; /* Just remember it's not there. */
  5476.             }
  5477.         }
  5478.         break;            /* and we're done. */
  5479.         }
  5480.     }
  5481.     }
  5482.     unlink(tmpnam);            /* Unlink (remove) the temp file. */
  5483.     priv_off();                /* Turn off privs */
  5484.     i = haslock ? 0 : -1;        /* Our return value */
  5485.     debug(F101,"TTLOCK returns","",i);
  5486.     return(i);
  5487. #endif /* HPUX */
  5488. #endif /* USETTYLOCK */
  5489. #endif /* !NOUUCP */
  5490. }
  5491.  
  5492. /*  T T U N L O C K  */
  5493.  
  5494. static int
  5495. ttunlck() {                             /* Remove UUCP lockfile(s). */
  5496. #ifndef NOUUCP
  5497.     int x;
  5498.  
  5499.     debug(F111,"ttunlck",flfnam,haslock);
  5500.  
  5501. #ifdef USETTYLOCK
  5502.  
  5503.     if (haslock && *flfnam) {
  5504.     int x;
  5505.     priv_on();            /* Turn on privs */
  5506. #ifdef USE_UU_LOCK
  5507.     x = uu_unlock(lockname);
  5508. #else  /* USE_UU_LOCK */
  5509.     x = ttyunlock(lockname);    /* Try to unlock */
  5510. #endif /* USE_UU_LOCK */
  5511.     priv_off();            /* Turn off privs */
  5512.     if (x < 0 && !quiet)
  5513.       printf("Warning - Can't remove lockfile: %s\n", flfnam);
  5514.  
  5515.     *flfnam = '\0';            /* Erase the name. */
  5516.     haslock = 0;
  5517.     return(0);
  5518.     }
  5519.  
  5520. #else  /* No ttylock()... */
  5521.  
  5522.     if (haslock && *flfnam) {
  5523.     /* Don't remove lockfile if we didn't make it ourselves */
  5524.     if ((x = ttrpid(flfnam)) != (int)getpid()) {
  5525.         debug(F111,"ttunlck lockfile seized",flfnam,x);
  5526.         printf("Warning - Lockfile %s seized by pid %d\n",
  5527.            flfnam,
  5528.            x
  5529.            );
  5530.         return(0);
  5531.     }
  5532.     priv_on();            /* Turn privileges on.  */
  5533.     errno = 0;
  5534.     x = unlink(flfnam);        /* Remove the lockfile. */
  5535.     debug(F111,"ttunlck unlink",flfnam,x);
  5536.     if (x < 0) {
  5537.         if (errno && !quiet)
  5538.           perror(ttnmsv);
  5539.         printf("Warning - Can't remove lockfile: %s\n", flfnam);
  5540.     }
  5541.     haslock = 0;
  5542.     *flfnam = '\0';            /* Erase the name. */
  5543.  
  5544. #ifdef RTAIX
  5545.     errno = 0;
  5546.     x = unlink(lkflfn);        /* Remove link to lockfile */
  5547.     debug(F111,"ttunlck AIX link unlink",lkflfn,x);
  5548.     if (x < 0) {
  5549.         if (errno && !quiet)
  5550.           perror(ttnmsv);
  5551.         printf("Warning - Can't remove link to lockfile: %s\n", lkflfn);
  5552.     }
  5553.     *lkflfn = '\0';
  5554. #else
  5555.     if (lock2[0]) {            /* If there is a second lockfile, */
  5556.         errno = 0;
  5557.         x = unlink(lock2);        /*  remove it too. */
  5558.         debug(F111,"ttunlck lock2 unlink",lock2,x);
  5559.         if (x < 0) {
  5560.         if (errno && !quiet)
  5561.           perror(ttnmsv);
  5562.         printf("Warning - Can't remove secondary lockfile: %s\n",
  5563.                lock2
  5564.                );
  5565.         }
  5566.         lock2[0] = '\0';        /* Forget its name. */
  5567.     }
  5568. #endif /* RTAIX */
  5569.  
  5570. #ifdef COMMENT
  5571. #ifdef LOCKF
  5572.         (VOID) lockf(ttyfd, F_ULOCK, 0L); /* Remove advisory lock */
  5573. #endif /* LOCKF */
  5574. #endif /* COMMENT */
  5575.  
  5576.     priv_off();            /* Turn privileges off. */
  5577.     }
  5578. #endif /* USETTYLOCK */
  5579. #endif /* !NOUUCP */
  5580.     return(0);
  5581. }
  5582.  
  5583. /*
  5584.   4.3BSD-style UUCP line direction control.
  5585.   (Stan Barber, Rice U, 1980-something...)
  5586. */
  5587. #ifndef NOUUCP
  5588. #ifdef ACUCNTRL
  5589. VOID
  5590. acucntrl(flag,ttname) char *flag, *ttname; {
  5591.     char x[DEVNAMLEN+32], *device, *devname;
  5592.  
  5593.     if (strcmp(ttname,CTTNAM) == 0 || xlocal == 0) /* If not local, */
  5594.       return;                /* just return. */
  5595.     device = ((devname = xxlast(ttname,'/')) != NULL ? devname+1 : ttname);
  5596.     if (strncmp(device,"LCK..",4) == 0) device += 5;
  5597.     ckmakmsg(x,DEVNAMLEN+32,"/usr/lib/uucp/acucntrl ",flag," ",device);
  5598.     debug(F110,"called ",x,0);
  5599.     zsyscmd(x);
  5600. }
  5601. #endif /* ACUCNTRL */
  5602. #endif /* NOUUCP */
  5603.  
  5604. /*
  5605.   T T H F L O W  --  Set or Reset hardware flow control.
  5606.  
  5607.   This is an attempt to collect all hardware-flow-control related code
  5608.   into a single module.  Thanks to Rick Sladkey and John Kohl for lots of
  5609.   help here.  Overview:
  5610.  
  5611.   Hardware flow control is not supported in many UNIX implementions.  Even
  5612.   when it is supported, there is no (ha ha) "standard" for the programming
  5613.   interface.  In general, 4.3BSD and earlier (sometimes), 4.4BSD, System V,
  5614.   SunOS, AIX, etc, have totally different methods.  (And, not strictly
  5615.   relevant here, the programming interface often brings one only to a no-op
  5616.   in the device driver!)
  5617.  
  5618.   Among all these, we have two major types of APIs: those in which hardware
  5619.   flow control is determined by bits in the same termio/termios/sgtty mode
  5620.   word(s) that are used for controlling such items as CBREAK vs RAW mode, and
  5621.   which are also used by the ttvt(), ttpkt(), conbin(), and concb() routines
  5622.   for changing terminal modes.  And those that use entirely different
  5623.   mechanisms.
  5624.  
  5625.   In the first category, it is important that any change in the mode bits be
  5626.   reflected in the relevant termio(s)/sgtty structure, so that subsequent
  5627.   changes to that structure do not wipe out the effects of this routine.  That
  5628.   is why a pointer, attrs, to the appropriate structure is passed as a
  5629.   parameter to this routine.
  5630.  
  5631.   The second category should give us no worries, since any changes to hardware
  5632.   flow control accomplished by this routine should not affect the termio(s)/
  5633.   sgtty structures, and therefore will not be undone by later changes to them.
  5634.  
  5635.   The second argument, status, means to turn on hardware flow control if
  5636.   nonzero, and to turn it off if zero.
  5637.  
  5638.   Returns: 0 on apparent success, -1 on probable failure.
  5639. */
  5640.  
  5641. /*
  5642.   The following business is for BSDI, where it was discovered that two
  5643.   separate bits, CCTS_OFLOW and CRTS_IFLOW, are used in hardware flow control,
  5644.   but CTRSCTS is defined (in <termios.h>) to be just CCTS_OFLOW rather both
  5645.   bits, so hwfc only works in one direction if you use CRTSCTS to control it.
  5646.   Other 4.4BSD-based Unixes such as FreeBSD 4.1, which use these two bits,
  5647.   define CRTSCTS correctly.
  5648. */
  5649. #ifdef FIXCRTSCTS
  5650. #ifdef CRTSCTS
  5651. #ifdef CCTS_OFLOW
  5652. #ifdef CRTS_IFLOW
  5653. #undef CRTSCTS
  5654. #define CRTSCTS (CRTS_IFLOW|CCTS_OFLOW)
  5655. #endif /* CRTS_IFLOW */
  5656. #endif /* CCTS_OFLOW */
  5657. #endif /* CRTSCTS */
  5658. #endif /* FIXCRTSCTS */
  5659.  
  5660. static int
  5661. tthflow(flow, status, attrs)
  5662.     int flow,                /* Type of flow control (ckcdeb.h) */
  5663.     status;                /* Nonzero = turn it on */
  5664.                     /* Zero = turn it off */
  5665. #ifdef BSD44ORPOSIX            /* POSIX or BSD44 */
  5666.     struct termios *attrs;
  5667. #else                    /* System V */
  5668. #ifdef ATTSV
  5669. #ifdef ATT7300
  5670. #ifdef UNIX351M
  5671. /* AT&T UNIX 3.51m can set but not test for hardware flow control */
  5672. #define RTSFLOW CTSCD
  5673. #define CTSFLOW CTSCD
  5674. #endif /* ATT7300 */
  5675. #endif /* UNIX351M */
  5676.     struct termio *attrs;
  5677. #else                    /* BSD, V7, etc */
  5678.     struct sgttyb *attrs;        /* sgtty info... */
  5679. #endif /* ATTSV */
  5680. #endif /* BSD44ORPOSIX */
  5681. /* tthflow */ {
  5682.  
  5683.     int x = 0;                /* tthflow() return code */
  5684.  
  5685. #ifdef Plan9
  5686.     return p9tthflow(flow, status);
  5687. #else
  5688.  
  5689. #ifndef OXOS                /* NOT Olivetti X/OS... */
  5690. /*
  5691.   For SunOS 4.0 and later in the BSD environment ...
  5692.  
  5693.   The declarations are copied and interpreted from the System V header files,
  5694.   so we don't actually have to pull in all the System V junk when building
  5695.   C-Kermit for SunOS in the BSD environment, which would be dangerous because
  5696.   having those symbols defined would cause us to take the wrong paths through
  5697.   the code.  The code in this section is used in both the BSD and Sys V SunOS
  5698.   versions.
  5699. */
  5700. #ifdef SUNOS41
  5701. /*
  5702.   In SunOS 4.1 and later, we use the POSIX calls rather than ioctl calls
  5703.   because GNU CC uses different formats for the _IOxxx macros than regular CC;
  5704.   the POSIX forms work for both.  But the POSIX calls are not available in
  5705.   SunOS 4.0.
  5706. */
  5707. #define CRTSCTS 0x80000000        /* RTS/CTS flow control */
  5708. #define TCSANOW 0            /* Do it now */
  5709.  
  5710.     struct termios {
  5711.     unsigned long c_iflag;        /* Input modes */
  5712.     unsigned long c_oflag;        /* Output modes */
  5713.     unsigned long c_cflag;        /* Control modes */
  5714.     unsigned long c_lflag;        /* Line discipline modes */
  5715.     char c_line;
  5716.     CHAR c_cc[17];
  5717.     };
  5718.     struct termios temp;
  5719.  
  5720. _PROTOTYP( int tcgetattr, (int, struct termios *) );
  5721. _PROTOTYP( int tcsetattr, (int, int, struct termios *) );
  5722. /*
  5723.   When CRTSCTS is set, SunOS won't do output unless both CTS and CD are
  5724.   asserted.  So we don't set CRTSCTS unless CD is up.  This should be OK,
  5725.   since we don't need RTS/CTS during dialing, and after dialing is complete,
  5726.   we should have CD.  If not, we still communicate, but without RTS/CTS.
  5727. */
  5728.     int mflags;                /* Modem signal flags */
  5729.  
  5730. #ifdef NETCMD
  5731.     if (ttpipe) return(0);
  5732. #endif /* NETCMD */
  5733. #ifdef NETPTY
  5734.     if (ttpty) return(0);
  5735. #endif /* NETPTY */
  5736.  
  5737.     debug(F101,"tthflow SUNOS41 entry status","",status);
  5738.     if (!status) {            /* Turn hard flow off */
  5739.     if (tcgetattr(ttyfd, &temp) > -1 && /* Get device attributes */
  5740.         (temp.c_cflag & CRTSCTS)) { /* Check for RTS/CTS */
  5741.         temp.c_cflag &= ~CRTSCTS;    /* It's there, remove it */
  5742.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5743.     }
  5744.     } else {                /* Turn hard flow on */
  5745.     if (ioctl(ttyfd,TIOCMGET,&mflags) > -1 && /* Get modem signals */
  5746.         (mflags & TIOCM_CAR)) {        /* Check for CD */
  5747.         debug(F100,"tthflow SunOS has CD","",0);
  5748.         if (tcgetattr(ttyfd, &temp) > -1 && /* Get device attributes */
  5749.         !(temp.c_cflag & CRTSCTS)) { /* Check for RTS/CTS */
  5750.         temp.c_cflag |= CRTSCTS;    /* Not there, add it */
  5751.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5752.         }
  5753.     } else {
  5754.         x = -1;
  5755.         debug(F100,"tthflow SunOS no CD","",0);
  5756.     }
  5757.     }
  5758. #else
  5759. #ifdef QNX
  5760.     struct termios temp;
  5761. #ifdef NETCMD
  5762.     if (ttpipe) return(0);
  5763. #endif /* NETCMD */
  5764. #ifdef NETPTY
  5765.     if (ttpty) return(0);
  5766. #endif /* NETPTY */
  5767.     debug(F101,"tthflow QNX entry status","",status);
  5768.     if (tcgetattr(ttyfd, &temp) > -1) {    /* Get device attributes */
  5769.     if (!status) {            /* Turn hard flow off */
  5770.         if ((temp.c_cflag & (IHFLOW|OHFLOW)) == (IHFLOW|OHFLOW)) {
  5771.         temp.c_cflag &= ~(IHFLOW|OHFLOW); /* It's there, remove it */
  5772.         attrs->c_cflag &= ~(IHFLOW|OHFLOW);
  5773.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5774.         }
  5775.     } else {            /* Turn hard flow on */
  5776.         if ((temp.c_cflag & (IHFLOW|OHFLOW)) != (IHFLOW|OHFLOW)) {
  5777.         temp.c_cflag |= (IHFLOW|OHFLOW); /* Not there, add it */
  5778.         temp.c_iflag &= ~(IXON|IXOFF);   /* Bye to IXON/IXOFF */
  5779.         ttraw.c_lflag |= IEXTEN;         /* Must be on */
  5780.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5781.         attrs->c_cflag |= (IHFLOW|OHFLOW);
  5782.         attrs->c_iflag &= ~(IXON|IXOFF);
  5783.         }
  5784.     }
  5785.     } else {
  5786.     x = -1;
  5787.     debug(F100, "tthflow QNX getattr fails", "", 0);
  5788.     }
  5789. #else
  5790. #ifdef POSIX_CRTSCTS
  5791. /*
  5792.   POSIX_CRTSCTS is defined in ckcdeb.h or on CC command line.
  5793.   Note: Do not assume CRTSCTS is a one-bit field!
  5794. */
  5795.     struct termios temp;
  5796. #ifdef NETCMD
  5797.     if (ttpipe) return(0);
  5798. #endif /* NETCMD */
  5799. #ifdef NETPTY
  5800.     if (ttpty) return(0);
  5801. #endif /* NETPTY */
  5802.     debug(F101,"tthflow POSIX_CRTSCTS entry status","",status);
  5803.     errno = 0;
  5804.     x = tcgetattr(ttyfd, &temp);
  5805.     debug(F111,"tthflow POSIX_CRTSCTS tcgetattr",ckitoa(x),errno);
  5806.     errno = 0;
  5807.     if (x < 0) {
  5808.     x = -1;
  5809.     } else {
  5810.     if (!status) {            /* Turn hard flow off */
  5811.         if (
  5812. #ifdef COMMENT
  5813.         /* This can fail because of sign extension */
  5814.         /* e.g. in Linux where it's Bit 31 */
  5815.         (temp.c_cflag & CRTSCTS) == CRTSCTS
  5816. #else
  5817.         (temp.c_cflag & CRTSCTS) != 0
  5818. #endif /* COMMENT */
  5819.         ) {
  5820.         temp.c_cflag &= ~CRTSCTS; /* It's there, remove it */
  5821.         attrs->c_cflag &= ~CRTSCTS;
  5822.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5823.         debug(F111,"tthflow POSIX_CRTSCTS OFF tcsetattr",
  5824.               ckitoa(x),errno);
  5825.         }
  5826.     } else {            /* Turn hard flow on */
  5827.         if (
  5828. #ifdef COMMENT
  5829.         /* This can fail because of sign extension */
  5830.         (temp.c_cflag & CRTSCTS) != CRTSCTS
  5831. #else
  5832.         (temp.c_cflag & CRTSCTS) == 0
  5833. #endif /* COMMENT */
  5834.         ) {
  5835.         temp.c_cflag |= CRTSCTS; /* Not there, add it */
  5836.         temp.c_iflag &= ~(IXON|IXOFF|IXANY); /* Bye to IXON/IXOFF */
  5837.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5838.         debug(F111,"tthflow POSIX_CRTSCTS ON tcsetattr",
  5839.               ckitoa(x),errno);
  5840.         attrs->c_cflag |= CRTSCTS;
  5841.         attrs->c_iflag &= ~(IXON|IXOFF|IXANY);
  5842.         }
  5843.     }
  5844.     }
  5845. #else
  5846. #ifdef SUNOS4
  5847. /*
  5848.   SunOS 4.0 (and maybe earlier?).  This code is dangerous because it
  5849.   prevents compilation with GNU gcc, which uses different formats for the
  5850.   _IORxxx macros than regular cc.  SunOS 4.1 and later can use the POSIX
  5851.   routines above, which work for both cc and gcc.
  5852. */
  5853. #define TCGETS _IOR(T, 8, struct termios) /* Get modes into termios struct */
  5854. #define TCSETS _IOW(T, 9, struct termios) /* Set modes from termios struct */
  5855. #define CRTSCTS 0x80000000          /* RTS/CTS flow control */
  5856.  
  5857.     struct termios {
  5858.     unsigned long c_iflag;        /* Input modes */
  5859.     unsigned long c_oflag;        /* Output modes */
  5860.     unsigned long c_cflag;        /* Control modes */
  5861.     unsigned long c_lflag;        /* Line discipline modes */
  5862.     char c_line;
  5863.     CHAR c_cc[17];
  5864.     };
  5865.     struct termios temp;
  5866. #ifdef NETCMD
  5867.     if (ttpipe) return(0);
  5868. #endif /* NETCMD */
  5869. #ifdef NETPTY
  5870.     if (ttpty) return(0);
  5871. #endif /* NETPTY */
  5872.     debug(F101,"tthflow entry status","",status);
  5873.     if (ioctl(ttyfd,TCGETS,&temp) > -1) { /* Get terminal modes. */
  5874.     if (status) {            /* Turn hard flow on */
  5875.         temp.c_cflag |= CRTSCTS;    /* Add RTS/CTS to them. */
  5876.         x = ioctl(ttyfd,TCSETS,&temp); /* Set them again. */
  5877.         attrs->c_cflag |= CRTSCTS;    /* Add to global info. */
  5878.     } else {            /* Turn hard flow off */
  5879.         temp.c_cflag &= ~CRTSCTS;
  5880.         x = ioctl(ttyfd,TCSETS,&temp);
  5881.         attrs->c_cflag &= ~CRTSCTS;
  5882.     }
  5883.     }
  5884. #else                    /* Not SunOS 4.0 or later */
  5885. #ifdef AIXRS                /* IBM AIX RS/6000 */
  5886. #ifndef AIX41                /* But only pre-4.x == SVR4 */
  5887. #ifdef NETCMD
  5888.     if (ttpipe) return(0);
  5889. #endif /* NETCMD */
  5890. #ifdef NETPTY
  5891.     if (ttpty) return(0);
  5892. #endif /* NETPTY */
  5893.     if (status) {
  5894.     if ((x = ioctl(ttyfd, TXADDCD, "rts")) < 0 && errno != EBUSY)
  5895.       debug(F100,"hardflow TXADDCD (rts) error", "", 0);
  5896.     } else {
  5897.     if ((x = ioctl(ttyfd, TXDELCD, "rts")) < 0 && errno != EINVAL)
  5898.       debug(F100,"hardflow TXDELCD (rts) error", "", 0);
  5899.     }
  5900. #endif /* AIX41 */
  5901. #else                    /* Not AIX RS/6000 */
  5902.  
  5903. #ifdef ATTSV                /* System V... */
  5904.  
  5905. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  5906. #define CK_SCOUNIX
  5907. #else
  5908. #ifdef M_UNIX                /* SCO UNIX 3.2v4.x or earlier */
  5909. #define CK_SCOUNIX
  5910. #endif /* M_UNIX */
  5911. #endif /* CK_SCOV5 */
  5912.  
  5913. #ifdef SCO_FORCE_RTSXOFF
  5914. #ifdef CK_SCOUNIX            /* But not SCO OpenServer 5.0.4 */
  5915. #ifdef SCO_OSR504            /* or later... */
  5916. #undef CK_SCOUNIX
  5917. #endif /* SCO_OSR504 */
  5918. #endif /* CK_SCOUNIX */
  5919. #endif /* SCO_FORCE_RTSXOFF */
  5920.  
  5921. #ifdef CK_SCOUNIX
  5922. #ifdef POSIX
  5923.     struct termios temp;
  5924. #ifdef NETCMD
  5925.     if (ttpipe) return(0);
  5926. #endif /* NETCMD */
  5927. #ifdef NETPTY
  5928.     if (ttpty) return(0);
  5929. #endif /* NETPTY */
  5930.     debug(F101,"tthflow SCOUNIX POSIX entry status","",status);
  5931.     errno = 0;
  5932.     x = tcgetattr(ttyfd, &temp);
  5933.     debug(F111,"tthflow SCO UNIX POSIX tcgetattr",ckitoa(x),errno);
  5934. #else /* POSIX */
  5935.     struct termio temp;
  5936. #ifdef NETCMD
  5937.     if (ttpipe) return(0);
  5938. #endif /* NETCMD */
  5939. #ifdef NETPTY
  5940.     if (ttpty) return(0);
  5941. #endif /* NETPTY */
  5942.     debug(F101,"tthflow SCOUNIX non-POSIX entry status","",status);
  5943.     x = ioctl(ttyfd, TCGETA, &temp);
  5944.     debug(F111,"tthflow SCO UNIX non-POSIX TCGETA",ckitoa(x),errno);
  5945. #endif /* POSIX */
  5946. /*
  5947.   This is not really POSIX, since POSIX does not deal with hardware flow
  5948.   control, but we are using the POSIX APIs.  In fact, RTSFLOW and CTSFLOW
  5949.   are defined in termio.h, but within #ifndef _POSIX_SOURCE..#endif.  So
  5950.   let's try forcing their definitions here.
  5951. */
  5952. #ifndef CTSFLOW
  5953. #define CTSFLOW 0020000
  5954.     debug(F101,"tthflow SCO defining CTSFLOW","",CTSFLOW);
  5955. #else
  5956.     debug(F101,"tthflow SCO CTSFLOW","",CTSFLOW);
  5957. #endif /* CTSFLOW */
  5958. #ifndef RTSFLOW
  5959. #define RTSFLOW 0040000
  5960.     debug(F101,"tthflow SCO defining RTSFLOW","",RTSFLOW);
  5961. #else
  5962.     debug(F101,"tthflow SCO RTSFLOW","",RTSFLOW);
  5963. #endif /* RTSFLOW */
  5964. #ifndef ORTSFL
  5965. #define ORTSFL 0100000
  5966.     debug(F101,"tthflow SCO defining ORTSFL","",ORTSFL);
  5967. #else
  5968.     debug(F101,"tthflow SCO ORTSFL","",ORTSFL);
  5969. #endif /* ORTSFL */
  5970.  
  5971.     if (x != -1) {
  5972.     if (status) {            /* Turn it ON */
  5973.         temp.c_cflag |= RTSFLOW|CTSFLOW;
  5974.         attrs->c_cflag |= RTSFLOW|CTSFLOW;
  5975. #ifdef ORTSFL
  5976.         temp.c_cflag &= ~ORTSFL;
  5977.         attrs->c_cflag &= ~ORTSFL;
  5978. #endif /* ORTSFL */
  5979.         temp.c_iflag &= ~(IXON|IXOFF|IXANY);
  5980.         attrs->c_iflag &= ~(IXON|IXOFF|IXANY);
  5981.     } else {            /* Turn it OFF */
  5982. #ifdef ORTSFL
  5983.         temp.c_cflag &= ~(RTSFLOW|CTSFLOW|ORTSFL);
  5984.         attrs->c_cflag &= ~(RTSFLOW|CTSFLOW|ORTSFL);
  5985. #else  /* ORTSFL */
  5986.         temp.c_cflag &= ~(RTSFLOW|CTSFLOW);
  5987.         attrs->c_cflag &= ~(RTSFLOW|CTSFLOW);
  5988. #endif /* ORTSFL */
  5989.     }
  5990. #ifdef POSIX
  5991.     x = tcsetattr(ttyfd, TCSADRAIN, &temp);
  5992. #else
  5993.     x = ioctl(ttyfd, TCSETA, &temp);
  5994. #endif /* POSIX */
  5995.     debug(F101,"tthflow SCO set modes","",x);
  5996.     }
  5997. #else /* Not SCO UNIX */
  5998. #ifdef NETCMD
  5999.     if (ttpipe) return(0);
  6000. #endif /* NETCMD */
  6001. #ifdef NETPTY
  6002.     if (ttpty) return(0);
  6003. #endif /* NETPTY */
  6004.     if (!status) {            /* Turn it OFF */
  6005. #ifdef RTSXOFF
  6006.     debug(F100,"tthflow ATTSV RTS/CTS OFF","",0);
  6007.     rctsx.x_hflag &= ~(RTSXOFF|CTSXON);
  6008. #ifdef TCSETX
  6009.     x = ioctl(ttyfd,TCSETX,&rctsx);
  6010.     debug(F101,"tthflow ATTSV TCSETX OFF","",x);
  6011. #else
  6012.     x = -1
  6013.     debug(F100,"tthflow TCSETX not defined","",0);
  6014. #endif /* TCSETX */
  6015. #else
  6016.     debug(F100,"tthflow ATTSV RTSXOFF not defined","",0);
  6017. #endif /* RTSXOFF */
  6018. #ifdef DTRXOFF
  6019.     debug(F100,"tthflow ATTSV DTR/CD OFF","",0);
  6020.     rctsx.x_hflag &= ~(DTRXOFF|CDXON);
  6021.     x = ioctl(ttyfd,TCSETX,&rctsx);
  6022.     debug(F101,"tthflow ATTSV DTRXOFF OFF","",x);
  6023. #else
  6024.     debug(F100,"tthflow ATTSV DTRXOFF not defined","",0);
  6025. #endif /* DTRXOFF */
  6026.     } else {                /* Turn it ON. */
  6027.     if (flow == FLO_RTSC) {    /* RTS/CTS Flow control... */
  6028.         debug(F100,"tthflow ATTSV RTS/CTS ON","",0);
  6029. #ifdef RTSXOFF
  6030.         /* This is the preferred way, according to SVID3 */
  6031. #ifdef TCGETX
  6032.         x = ioctl(ttyfd,TCGETX,&rctsx);
  6033.         debug(F101,"tthflow TCGETX","",x);
  6034.         if (x > -1) {
  6035.         rctsx.x_hflag |= RTSXOFF | CTSXON;
  6036.         x = ioctl(ttyfd,TCSETX,&rctsx);
  6037.         debug(F100,"tthflow ATTSV ioctl","",x);
  6038.         }
  6039. #else
  6040.         debug(F100,"tthflow TCGETX not defined","",0);
  6041.         x = -1
  6042. #endif /* TCGETX */
  6043. #else
  6044.         debug(F100,"tthflow RTSXOFF not defined","",0);
  6045.         x = -1;
  6046. #endif /* RTSXOFF */
  6047.     } else if (flow == FLO_DTRC) {    /* DTR/CD Flow control... */
  6048.         debug(F100,"tthflow ATTSV DTR/CD ON","",0);
  6049. #ifdef DTRXOFF
  6050.         /* This is straight out of SVID R4 */
  6051.         if (ioctl(ttyfd,TCGETX,&rctsx) > -1) {
  6052.         rctsx.x_hflag &= ~(DTRXOFF|CDXON);
  6053.         x = ioctl(ttyfd,TCSETX,&rctsx);
  6054.         }
  6055. #else
  6056.         debug(F100,"tthflow ATTSV DTRXOFF not defined","",0);
  6057.         x = -1;
  6058. #endif /* DTRXOFF */
  6059.     }
  6060.     }
  6061. #endif /* CK_SCOUNIX */
  6062.  
  6063. #else /* not System V... */
  6064.  
  6065. #ifdef CK_DTRCTS
  6066. #ifdef LDODTR
  6067. #ifdef LDOCTS
  6068. #ifdef NETCMD
  6069.     if (ttpipe) return(0);
  6070. #endif /* NETCMD */
  6071. #ifdef NETPTY
  6072.     if (ttpty) return(0);
  6073. #endif /* NETPTY */
  6074.     x = LDODTR | LDOCTS;        /* Found only on UTEK? */
  6075.     if (flow == FLO_DTRT && status) {    /* Use hardware flow control */
  6076.     if (lmodef) {
  6077.         x = ioctl(ttyfd,TIOCLBIS,&x);
  6078.         if (x < 0) {
  6079.             debug(F100,"hardflow TIOCLBIS error","",0);
  6080.         } else {
  6081.         lmodef++;
  6082.         debug(F100,"hardflow TIOCLBIS ok","",0);
  6083.         }
  6084.     }
  6085.     } else {
  6086.     if (lmodef) {
  6087.         x = ioctl(ttyfd,TIOCLBIC,&x);
  6088.         if (x < 0) {
  6089.             debug(F100,"hardflow TIOCLBIC error","",0);
  6090.         } else {
  6091.         lmodef++;
  6092.         debug(F100,"hardflow TIOCLBIC ok","",0);
  6093.         }
  6094.     }
  6095.     }
  6096. #endif /* LDODTR */
  6097. #endif /* LDOCTS */
  6098. #endif /* CK_DTRCTS */
  6099. #endif /* ATTSV */
  6100. #endif /* AIXRS */
  6101. #endif /* SUNOS4 */
  6102. #endif /* QNX */
  6103. #endif /* POSIX_CRTSCTS */
  6104. #endif /* SUNOS41 */
  6105.  
  6106. #else /* OXOS */
  6107.  
  6108.     struct termios temp;        /* Olivetti X/OS ... */
  6109.  
  6110. #ifdef NETCMD
  6111.     if (ttpipe) return(0);
  6112. #endif /* NETCMD */
  6113. #ifdef NETPTY
  6114.     if (ttpty) return(0);
  6115. #endif /* NETPTY */
  6116.     x = ioctl(ttyfd,TCGETS,&temp);
  6117.     if (x == 0) {
  6118.     temp.c_cflag &= ~(CRTSCTS|CDTRCTS|CBRKFLOW|CDTRDSR|CRTSDSR);
  6119.     if (status) {
  6120.         switch (flow) {
  6121.           case FLO_RTSC: temp.c_cflag |= CRTSCTS; /* RTS/CTS (hard) */
  6122.         break;
  6123.           case FLO_DTRT: temp.c_cflag |= CDTRCTS; /* DTR/CTS (hard) */
  6124.         break;
  6125.         }
  6126.     }
  6127.     x = ioctl(ttyfd,TCSETS,&temp);
  6128.     }
  6129. #endif /* OXOS */
  6130.     return(x);
  6131.  
  6132. #endif /* Plan9 */
  6133. }
  6134.  
  6135. /*  T T P K T  --  Condition the communication line for packets */
  6136. /*                 or for modem dialing */
  6137.  
  6138. /*
  6139.   If called with speed > -1, also set the speed.
  6140.   Returns 0 on success, -1 on failure.
  6141.  
  6142.   NOTE: the "xflow" parameter is supposed to be the currently selected
  6143.   type of flow control, but for historical reasons, this parameter is also
  6144.   used to indicate that we are dialing.  Therefore, when the true flow
  6145.   control setting is needed, we access the external variable "flow", rather
  6146.   than trusting our "xflow" argument.
  6147. */
  6148. int
  6149. #ifdef CK_ANSIC
  6150. ttpkt(long speed, int xflow, int parity)
  6151. #else
  6152. ttpkt(speed,xflow,parity) long speed; int xflow, parity;
  6153. #endif /* CK_ANSIC */
  6154. /* ttpkt */ {
  6155. #ifndef NOLOCAL
  6156.     int s2;
  6157.     int s = -1;
  6158. #endif /* NOLOCAL */
  6159.     int x;
  6160.     extern int flow;            /* REAL flow-control setting */
  6161.  
  6162.     if (ttyfd < 0) return(-1);          /* Not open. */
  6163.  
  6164.     debug(F101,"ttpkt parity","",parity);
  6165.     debug(F101,"ttpkt xflow","",xflow);
  6166.     debug(F101,"ttpkt speed","",(int) speed);
  6167.  
  6168.     ttprty = parity;                    /* Let other tt functions see these. */
  6169.     ttspeed = speed;            /* Make global copy for this module */
  6170.     ttpmsk = ttprty ? 0177 : 0377;    /* Parity stripping mask */
  6171. #ifdef PARSENSE
  6172.     needpchk = ttprty ? 0 : 1;        /* Parity check needed? */
  6173. #else
  6174.     needpchk = 0;
  6175. #endif /* PARSENSE */
  6176.  
  6177.     debug(F101,"ttpkt ttpmsk","",ttpmsk);
  6178.     debug(F101,"ttpkt netconn","",netconn);
  6179.  
  6180. #ifdef NETCONN                /* No mode-changing for telnet */
  6181.     if (netconn) {
  6182. #ifdef TCPSOCKET
  6183. #ifdef TCP_NODELAY
  6184.         if (ttnet == NET_TCPB) {    /* But turn off Nagle */
  6185.             extern int tcp_nodelay;
  6186.             nodelay_sav = tcp_nodelay;
  6187.             no_delay(ttyfd,1);
  6188.         }
  6189. #endif /* TCP_NODELAY */
  6190. #ifdef TN_COMPORT
  6191.         if (istncomport()) {
  6192.             int rc = -1;
  6193.             if (tvtflg == 0 && speed == ttspeed && flow == ttflow
  6194.                  /* && ttcarr == curcarr */ ) {
  6195.                 debug(F100,"ttpkt modes already set, skipping...","",0);
  6196.                 return(0);        /* Already been called. */
  6197.             }
  6198.             if (flow != ttflow) {
  6199.                 if ((rc = tnsetflow(flow)) < 0)
  6200.           return(rc);
  6201.                 ttflow = flow;
  6202.             }
  6203.             if (speed != ttspeed) {
  6204.                 if (speed <= 0) 
  6205.           speed = tnc_get_baud();
  6206.                 else if ((rc = tnc_set_baud(speed)) < 0)
  6207.           return(rc);
  6208.                 ttspeed = speed;
  6209.             }
  6210.             tnc_set_datasize(8);
  6211.         tnc_set_stopsize(stopbits);
  6212.  
  6213. #ifdef HWPARITY
  6214.             if (hwparity) {
  6215.                 switch (hwparity) {
  6216.           case 'e':            /* Even */
  6217.                     debug(F100,"ttres 8 bits + even parity","",0);
  6218.                     tnc_set_parity(3);
  6219.                     break;
  6220.           case 'o':            /* Odd */
  6221.                     debug(F100,"ttres 8 bits + odd parity","",0);
  6222.                     tnc_set_parity(2);
  6223.                     break;
  6224.           case 'm':            /* Mark */
  6225.                     debug(F100,"ttres 8 bits + invalid parity: mark","",0);
  6226.                     tnc_set_parity(4);
  6227.                     break;
  6228.           case 's':            /* Space */
  6229.                     debug(F100,"ttres 8 bits + invalid parity: space","",0);
  6230.                     tnc_set_parity(5);
  6231.                     break;
  6232.                 }
  6233.             } else 
  6234. #endif /* HWPARITY */
  6235.         {
  6236.                 tnc_set_parity(1);              /* None */
  6237.             }
  6238.             tvtflg = 0;
  6239.             return(0);
  6240.         }
  6241. #endif /* TN_COMPORT */
  6242. #endif /* TCPSOCKET */
  6243.         tvtflg = 0;
  6244.         return(0);
  6245.     }
  6246. #endif /* NETCONN */
  6247. #ifdef NETCMD
  6248.     if (ttpipe) return(0);
  6249. #endif /* NETCMD */
  6250. #ifdef NETPTY
  6251.     if (ttpty) return(0);
  6252. #endif /* NETPTY */
  6253.  
  6254. #ifndef Plan9
  6255.     if (ttfdflg && !isatty(ttyfd)) return(0);
  6256. #endif /* Plan9 */
  6257.  
  6258. #ifdef COHERENT
  6259. #define SVORPOSIX
  6260. #endif /* COHERENT */
  6261.  
  6262. #ifndef SVORPOSIX            /* Berkeley, V7, etc. */
  6263. #ifdef LPASS8
  6264. /*
  6265.  For some reason, with BSD terminal drivers, you can't set FLOW to XON/XOFF
  6266.  after having previously set it to NONE without closing and reopening the
  6267.  device.  Unless there's something I overlooked below...
  6268. */
  6269.     if (ttflow == FLO_NONE && flow == FLO_XONX && xlocal == 0) {
  6270.     debug(F101,"ttpkt executing horrible flow kludge","",0);
  6271.     ttclos(0);            /* Close it */
  6272.     x = 0;
  6273.     ttopen(ttnmsv,&x,ttmdm,0);    /* Open it again */
  6274.     }
  6275. #endif /* LPASS8 */
  6276. #endif /* SVORPOSIX */
  6277.  
  6278. #ifdef COHERENT                /* This must be vestigial since we */
  6279. #undef SVORPOSIX            /* reverse it a few lines below... */
  6280. #endif /* COHERENT */
  6281.  
  6282.     if (xflow != FLO_DIAL && xflow != FLO_DIAX)
  6283.       ttflow = xflow;            /* Now make this available too. */
  6284.  
  6285. #ifndef NOLOCAL
  6286.     if (xlocal) {
  6287.     s2 = (int) (speed / 10L);    /* Convert bps to cps */
  6288.     debug(F101,"ttpkt calling ttsspd","",s2);
  6289.     s = ttsspd(s2);            /* Check and set the speed */
  6290.     debug(F101,"ttpkt ttsspd result","",s);
  6291.      carrctl(&ttraw, xflow != FLO_DIAL /* Carrier control */
  6292.         && (ttcarr == CAR_ON || (ttcarr == CAR_AUT && ttmdm != 0)));
  6293.     tvtflg = 0;            /* So ttvt() will work next time */
  6294.     }
  6295. #endif /* NOLOCAL */
  6296.  
  6297. #ifdef COHERENT
  6298. #define SVORPOSIX
  6299. #endif /* COHERENT */
  6300.  
  6301. #ifndef SVORPOSIX            /* BSD section */
  6302.     if (flow == FLO_RTSC ||        /* Hardware flow control */
  6303.     flow == FLO_DTRC ||
  6304.     flow == FLO_DTRT) {
  6305.     tthflow(flow, 1, &ttraw);
  6306.     debug(F100,"ttpkt hard flow, TANDEM off, RAW on","",0);
  6307.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6308.     ttraw.sg_flags |= RAW;        /* Enter raw mode */
  6309.     } else if (flow == FLO_NONE) {    /* No flow control */
  6310.     debug(F100,"ttpkt no flow, TANDEM off, RAW on","",0);
  6311.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6312.     tthflow(flow, 0, &ttraw);    /* Turn off any hardware f/c too */
  6313.     ttraw.sg_flags |= RAW;        /* Enter raw mode */
  6314.     } else if (flow == FLO_KEEP) {    /* Keep device's original setting */
  6315.     debug(F100,"ttpkt keeping original TANDEM","",0);
  6316.     ttraw.sg_flags &= ~TANDEM;
  6317.     ttraw.sg_flags |= (ttold.sg_flags & TANDEM);
  6318.     /* NOTE: We should also handle hardware flow control here! */
  6319.     }
  6320.  
  6321. /* SET FLOW XON/XOFF is in effect, or SET FLOW KEEP resulted in Xon/Xoff */
  6322.  
  6323.     if ((flow == FLO_XONX) || (ttraw.sg_flags & TANDEM)) {
  6324.     debug(F100,"ttpkt turning on TANDEM","",0);
  6325.     ttraw.sg_flags |= TANDEM;    /* So ask for it. */
  6326.  
  6327. #ifdef LPASS8                /* Can pass 8-bit data through? */
  6328. /* If the LPASS8 local mode is available, then flow control can always  */
  6329. /* be used, even if parity is none and we are transferring 8-bit data.  */
  6330. /* But we only need to do all this if Xon/Xoff is requested. */
  6331. /* BUT... this tends not to work through IP or LAT connections, terminal */
  6332. /* servers, telnet, rlogin, etc, so it is currently disabled. */
  6333.     x = LPASS8;            /* If LPASS8 defined, then */
  6334.     debug(F100,"ttpkt executing LPASS8 code","",0);
  6335.     if (lmodef) {            /* TIOCLBIS must be too. */
  6336.         x = ioctl(ttyfd,TIOCLBIS,&x); /* Try to set LPASS8. */
  6337.         if (x < 0) {
  6338.         debug(F100,"ttpkt TIOCLBIS error","",0);
  6339.         } else {
  6340.         lmodef++;
  6341.         debug(F100,"ttpkt TIOCLBIS ok","",0);
  6342.         }
  6343.     }
  6344. /*
  6345.  But if we use LPASS8 mode, we must explicitly turn off
  6346.  terminal interrupts of all kinds.
  6347. */
  6348. #ifdef TIOCGETC                /* Not rawmode, */
  6349.     if (tcharf && (xlocal == 0)) {    /* must turn off */
  6350.         tchnoi.t_intrc = -1;    /* interrupt character */
  6351.         tchnoi.t_quitc = -1;    /* and quit character. */
  6352.         tchnoi.t_startc = 17;    /* Make sure xon */
  6353.         tchnoi.t_stopc = 19;    /* and xoff not ignored. */
  6354. #ifndef NOBRKC
  6355.         tchnoi.t_eofc = -1;        /* eof character. */
  6356.         tchnoi.t_brkc = -1;        /* brk character. */
  6357. #endif /* NOBRKC */
  6358.         if (ioctl(ttyfd,TIOCSETC,&tchnoi) < 0) {
  6359.         debug(F100,"ttpkt TIOCSETC failed","",0);
  6360.         } else {
  6361.         tcharf = 1;
  6362.         debug(F100,"ttpkt TIOCSETC ok","",0);
  6363.         }
  6364. #ifdef COMMENT
  6365. /* only for paranoid debugging */
  6366.         if (tcharf) {
  6367.         struct tchars foo;
  6368.         char tchbuf[100];
  6369.         ioctl(0,TIOCGETC,&foo);
  6370.         sprintf(tchbuf,
  6371.             "intr=%d,quit=%d, start=%d, stop=%d, eof=%d, brk=%d",
  6372.             foo.t_intrc, foo.t_quitc, foo.t_startc,
  6373.             foo.t_stopc, foo.t_eofc,  foo.t_brkc);
  6374.         debug(F110,"ttpkt chars",tchbuf,0);
  6375.         }
  6376. #endif /* COMMENT */
  6377.     }
  6378.     ttraw.sg_flags |= CBREAK;    /* Needed for unknown reason */
  6379. #endif /* TIOCGETC */
  6380.  
  6381. /* Prevent suspend during packet mode */
  6382. #ifdef TIOCGLTC                /* Not rawmode, */
  6383.     if (ltcharf && (xlocal == 0)) {    /* must turn off */
  6384.         ltchnoi.t_suspc = -1;    /* suspend character */
  6385.         ltchnoi.t_dsuspc = -1;    /* and delayed suspend character */
  6386.         if (ioctl(ttyfd,TIOCSLTC,&tchnoi) < 0) {
  6387.         debug(F100,"ttpkt TIOCSLTC failed","",0);
  6388.         } else {
  6389.         ltcharf = 1;
  6390.         debug(F100,"ttpkt TIOCSLTC ok","",0);
  6391.         }
  6392.     }
  6393. #endif /* TIOCGLTC */
  6394.  
  6395. #else /* LPASS8 not defined */
  6396.  
  6397. /* Previously, BSD-based implementations always */
  6398. /* used rawmode for packets.  Now, we use rawmode only if parity is NONE. */
  6399. /* This allows the flow control requested above to actually work, but only */
  6400. /* if the user asks for parity (which also means they get 8th-bit quoting). */
  6401.  
  6402.     if (parity) {            /* If parity, */
  6403.         ttraw.sg_flags &= ~RAW;    /* use cooked mode */
  6404. #ifdef COMMENT
  6405. /* WHY??? */
  6406.         if (xlocal)
  6407. #endif /* COMMENT */
  6408.           ttraw.sg_flags |= CBREAK;
  6409.         debug(F101,"ttpkt cooked, cbreak, parity","",parity);
  6410. #ifdef TIOCGETC                /* Not rawmode, */
  6411.         if (tcharf && (xlocal == 0)) { /* must turn off */
  6412.         tchnoi.t_intrc = -1;    /* interrupt character */
  6413.         tchnoi.t_quitc = -1;    /* and quit character. */
  6414.         tchnoi.t_startc = 17;    /* Make sure xon */
  6415.         tchnoi.t_stopc = 19;    /* and xoff not ignored. */
  6416. #ifndef NOBRKC
  6417.         tchnoi.t_eofc = -1;    /* eof character. */
  6418.         tchnoi.t_brkc = -1;    /* brk character. */
  6419. #endif /* NOBRKC */
  6420.         if (ioctl(ttyfd,TIOCSETC,&tchnoi) < 0) {
  6421.             debug(F100,"ttpkt TIOCSETC failed","",0);
  6422.         } else {
  6423.             tcharf = 1;
  6424.             debug(F100,"ttpkt TIOCSETC ok","",0);
  6425.         }
  6426.         }
  6427. #endif /* TIOCGETC */
  6428. #ifdef TIOCGLTC                /* Not rawmode, */
  6429. /* Prevent suspend during packet mode */
  6430.         if (ltcharf && (xlocal == 0)) { /* must turn off */
  6431.         ltchnoi.t_suspc = -1;    /* suspend character */
  6432.         ltchnoi.t_dsuspc = -1;    /* and delayed suspend character */
  6433.         if (ioctl(ttyfd,TIOCSLTC,&tchnoi) < 0) {
  6434.             debug(F100,"ttpkt TIOCSLTC failed","",0);
  6435.         } else {
  6436.             ltcharf = 1;
  6437.             debug(F100,"ttpkt TIOCSLTC ok","",0);
  6438.         }
  6439.         }
  6440. #endif /* TIOCGLTC */
  6441.     } else {            /* If no parity, */
  6442.         ttraw.sg_flags |= RAW;    /* must use 8-bit raw mode. */
  6443.         debug(F101,"ttpkt setting rawmode, parity","",parity);
  6444.     }
  6445. #endif /* LPASS8 */
  6446.     } /* End of Xon/Xoff section */
  6447.  
  6448.     /* Don't echo, don't map CR to CRLF on output, don't fool with case */
  6449. #ifdef LCASE
  6450.     ttraw.sg_flags &= ~(ECHO|CRMOD|LCASE);
  6451. #else
  6452.     ttraw.sg_flags &= ~(ECHO|CRMOD);
  6453. #endif /* LCASE */
  6454.  
  6455. #ifdef TOWER1
  6456.     ttraw.sg_flags &= ~ANYP;            /* Must set this on old Towers */
  6457. #endif /* TOWER1 */
  6458.  
  6459. #ifdef BELLV10
  6460.     if (ioctl(ttyfd,TIOCSETP,&ttraw) < 0) /* Set the new modes. */
  6461.       return(-1);
  6462. #else
  6463.     errno = 0;
  6464.     if (stty(ttyfd,&ttraw) < 0) {       /* Set the new modes. */
  6465.         debug(F101,"ttpkt stty failed","",errno);
  6466.         return(-1);
  6467.     }
  6468. #endif /* BELLV10 */
  6469.     debug(F100,"ttpkt stty ok","",0);
  6470.  
  6471. #ifdef sony_news
  6472.     x = xlocal ? km_ext : km_con;    /* Put line in ASCII mode. */
  6473.     if (x != -1) {            /* Make sure we know original modes. */
  6474.     x &= ~KM_TTYPE;
  6475.     x |= KM_ASCII;
  6476.     if (ioctl(ttyfd,TIOCKSET, &x) < 0) {
  6477.         perror("ttpkt can't set ASCII mode");
  6478.         debug(F101,"ttpkt error setting ASCII mode","",x);
  6479.         return(-1);
  6480.     }
  6481.     }
  6482.     debug(F100,"ttpkt set ASCII mode ok","",0);
  6483. #endif /* sony_news */
  6484.  
  6485.     if (xlocal == 0) {            /* Turn this off so we can read */
  6486.     signal(SIGINT,SIG_IGN);        /* Ctrl-C chars typed at console */
  6487.     sigint_ign = 1;
  6488.     }
  6489.     tvtflg = 0;                /* So ttvt() will work next time */
  6490.     debug(F100,"ttpkt success","",0);
  6491.     return(0);
  6492.  
  6493. #endif /* Not ATTSV or POSIX */
  6494.  
  6495. /* AT&T UNIX and POSIX */
  6496.  
  6497. #ifdef COHERENT
  6498. #define SVORPOSIX
  6499. #endif /* COHERENT */
  6500.  
  6501. #ifdef SVORPOSIX
  6502.     if (flow == FLO_XONX) {        /* Xon/Xoff */
  6503.     ttraw.c_iflag |= (IXON|IXOFF);
  6504.     tthflow(flow, 0, &ttraw);
  6505.     } else if (flow == FLO_NONE) {    /* None */
  6506.     /* NOTE: We should also turn off hardware flow control here! */
  6507.     ttraw.c_iflag &= ~(IXON|IXOFF);
  6508.     tthflow(flow, 0, &ttraw);
  6509.     } else if (flow == FLO_KEEP) {    /* Keep */
  6510.     ttraw.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff flags */
  6511.     ttraw.c_iflag |= (ttold.c_iflag & (IXON|IXOFF)); /* OR in old ones */
  6512.     /* NOTE: We should also handle hardware flow control here! */
  6513. #ifdef POSIX_CRTSCTS
  6514. /* In Linux case, we do this, which is unlikely to be portable */
  6515.         ttraw.c_cflag &= ~CRTSCTS;    /* Turn off RTS/CTS flag */
  6516.         ttraw.c_cflag |= (ttold.c_cflag & CRTSCTS); /* OR in old one */
  6517. #endif /* POSIX_CRTSCTS */
  6518.     } else if (flow == FLO_RTSC ||    /* Hardware */
  6519.            flow == FLO_DTRC ||
  6520.            flow == FLO_DTRT) {
  6521.     ttraw.c_iflag &= ~(IXON|IXOFF);    /* (190) */
  6522.     tthflow(flow, 1, &ttraw);
  6523.     }
  6524.     ttraw.c_lflag &= ~(ICANON|ECHO);
  6525.     ttraw.c_lflag &= ~ISIG;        /* Do NOT check for interrupt chars */
  6526.  
  6527. #ifndef OXOS
  6528. #ifdef QNX
  6529.     if (flow != FLO_RTSC && flow != FLO_DTRC && flow != FLO_DTRT)
  6530. #endif /* QNX */
  6531. #ifndef COHERENT
  6532.       ttraw.c_lflag &= ~IEXTEN;        /* Turn off ^O/^V processing */
  6533. #endif /* COHERENT */
  6534. #else /* OXOS */
  6535.     ttraw.c_cc[VDISCARD] = ttraw.c_cc[VLNEXT] = CDISABLE;
  6536. #endif /* OXOS */
  6537.     ttraw.c_lflag |= NOFLSH;        /* Don't flush */
  6538.     ttraw.c_iflag |= IGNPAR;        /* Ignore parity errors */
  6539. #ifdef ATTSV
  6540. #ifdef BSD44
  6541.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|INPCK|ISTRIP|IXANY);
  6542. #else
  6543.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IUCLC|INPCK|ISTRIP|IXANY);
  6544. #endif /* BSD44 */
  6545. #else /* POSIX */
  6546.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|INPCK|ISTRIP);
  6547. #endif /* ATTSV */
  6548.     ttraw.c_oflag &= ~OPOST;
  6549.     ttraw.c_cflag &= ~(CSIZE);
  6550.     ttraw.c_cflag |= (CS8|CREAD|HUPCL);
  6551.  
  6552. #ifdef CSTOPB
  6553.     if (xlocal) {
  6554.     if (stopbits == 2) {
  6555.         ttraw.c_cflag |= CSTOPB;    /* 2 stop bits */
  6556.         debug(F100,"ttpkt 2 stopbits","",0);
  6557.     } else if (stopbits == 1) {
  6558.         ttraw.c_cflag &= ~(CSTOPB);    /* 1 stop bit */
  6559.         debug(F100,"ttpkt 1 stopbit","",0);
  6560.     }
  6561.     }
  6562. #endif /* CSTOPB */
  6563.  
  6564. #ifdef HWPARITY
  6565.     if (hwparity && xlocal) {        /* Hardware parity */
  6566.     ttraw.c_cflag |= PARENB;    /* Enable parity */
  6567. #ifdef COMMENT
  6568. /* Uncomment this only if needed -- I don't think it is */
  6569.     ttraw.c_cflag &= ~(CSIZE);    /* Clear out character-size mask */
  6570.     ttraw.c_cflag |= CS8;        /* And set it to 8 */
  6571. #endif /* COMMENT */
  6572. #ifdef IGNPAR
  6573.     ttraw.c_iflag |= IGNPAR;    /* Don't discard incoming bytes */
  6574.     debug(F100,"ttpkt IGNPAR","",0); /* that have parity errors */
  6575. #endif /* IGNPAR */
  6576.     switch (hwparity) {
  6577.       case 'e':            /* Even */
  6578.         ttraw.c_cflag &= ~(PARODD);
  6579.         debug(F100,"ttpkt 8 bits + even parity","",0);
  6580.         break;
  6581.       case 'o':            /* Odd */
  6582.         ttraw.c_cflag |= PARODD;
  6583.         debug(F100,"ttpkt 8 bits + odd parity","",0);
  6584.         break;
  6585.       case 'm':            /* Mark */
  6586.       case 's':            /* Space */
  6587.         /* PAREXT is mentioned in SVID but the details are not given. */
  6588.         /* PAREXT is not included in POSIX ISO/IEC 9945-1. */
  6589.         debug(F100,"ttpkt 8 bits + invalid parity","",0);
  6590.         break;
  6591.     }
  6592.     } else {                /* We handle parity ourselves */
  6593. #endif /* HWPARITY */
  6594.     ttraw.c_cflag &= ~(PARENB);    /* Don't enable parity */
  6595. #ifdef HWPARITY
  6596.     }
  6597. #endif /* HWPARITY */
  6598.  
  6599. #ifdef IX370
  6600.     ttraw.c_cc[4] = 48;  /* So Series/1 doesn't interrupt on every char */
  6601.     ttraw.c_cc[5] = 1;
  6602. #else
  6603. #ifndef VEOF                /* for DGUX this is VEOF, not VMIN */
  6604.     ttraw.c_cc[4] = 1;   /* [VMIN]  return max of this many characters or */
  6605. #else
  6606. #ifndef OXOS
  6607. #ifdef VMIN
  6608.     ttraw.c_cc[VMIN] = 1;
  6609. #endif /* VMIN */
  6610. #else /* OXOS */
  6611.     ttraw.c_min = 1;
  6612. #endif /* OXOS */
  6613. #endif /* VEOF */
  6614. #ifndef VEOL                /* for DGUX this is VEOL, not VTIME */
  6615.     ttraw.c_cc[5] = 0;     /* [VTIME] when this many secs/10 expire w/no input */
  6616. #else
  6617. #ifndef OXOS
  6618. #ifdef VTIME
  6619.     ttraw.c_cc[VTIME] = 0;
  6620. #endif /* VTIME */
  6621. #else /* OXOS */
  6622.     ttraw.c_time = 0;
  6623. #endif /* OXOS */
  6624. #endif /* VEOL */
  6625. #endif /* IX370 */
  6626.  
  6627. #ifdef VINTR                /* Turn off interrupt character */
  6628.     if (xlocal == 0)            /* so ^C^C can break us out of */
  6629.       ttraw.c_cc[VINTR] = 0;        /* packet mode. */
  6630. #endif /* VINTR */
  6631.  
  6632. #ifdef Plan9
  6633.     if (p9ttyparity('n') < 0)
  6634.     return -1;
  6635. #else
  6636. #ifdef BSD44ORPOSIX
  6637.     errno = 0;
  6638. #ifdef BEOSORBEBOX
  6639.     ttraw.c_cc[VMIN] = 0;        /* DR7 can only poll. */
  6640. #endif /* BEOSORBEBOX */
  6641.     debug(F100,"ttpkt calling tcsetattr(TCSETAW)","",0);
  6642.     x = tcsetattr(ttyfd,TCSADRAIN,&ttraw);
  6643.     debug(F101,"ttpkt BSD44ORPOSIX tcsetattr","",x);
  6644.     if (x < 0) {
  6645.     debug(F101,"ttpkt BSD44ORPOSIX tcsetattr errno","",errno);
  6646.         return(-1);
  6647.     }
  6648. #else /* BSD44ORPOSIX */
  6649.     x = ioctl(ttyfd,TCSETAW,&ttraw);
  6650.     debug(F101,"ttpkt ATTSV ioctl TCSETAW","",x);
  6651.     if (x < 0) {  /* set new modes . */
  6652.     debug(F101,"ttpkt ATTSV ioctl TCSETAW errno","",errno);
  6653.         return(-1);
  6654.     }
  6655. #endif /* BSD44ORPOSIX */
  6656. #endif /* Plan9 */
  6657.     tvtflg = 0;
  6658.     debug(F100,"ttpkt ok","",0);
  6659.     return(0);
  6660. #endif /* ATTSV */
  6661.  
  6662. #ifdef COHERENT
  6663. #undef SVORPOSIX
  6664. #endif /* COHERENT */
  6665.  
  6666. }
  6667.  
  6668. /*  T T S E T F L O W  --  Set flow control immediately.  */
  6669.  
  6670. #ifdef COHERENT
  6671. #define SVORPOSIX
  6672. #endif /* COHERENT */
  6673.  
  6674. int
  6675. ttsetflow(flow) int flow; {
  6676.     if (ttyfd < 0)            /* A channel must be open */
  6677.       return(-1);
  6678.  
  6679.     debug(F101,"ttsetflow flow","",flow);
  6680.  
  6681. #ifdef TN_COMPORT
  6682.     if (netconn && istncomport()) {
  6683.     debug(F101,"ttsetflow net modem","",ttmdm);
  6684.     return(tnsetflow(flow));
  6685.     }
  6686. #endif /* TN_COMPORT */
  6687. #ifdef NETCMD
  6688.     if (ttpipe) return(0);
  6689. #endif /* NETCMD */
  6690. #ifdef NETPTY
  6691.     if (ttpty) return(0);
  6692. #endif /* NETPTY */
  6693.  
  6694. #ifdef COMMENT
  6695.     /* This seems to hurt... */
  6696.     if (flow == FLO_KEEP)
  6697.       return(0);
  6698. #endif /* COMMENT */
  6699.  
  6700.     if (flow == FLO_RTSC ||        /* Hardware flow control... */
  6701.     flow == FLO_DTRC ||
  6702.     flow == FLO_DTRT) {
  6703.     tthflow(flow, 1, &ttraw);
  6704. #ifndef SVORPOSIX
  6705.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6706. #else
  6707.     ttraw.c_iflag &= ~(IXON|IXOFF);
  6708. #endif /* SVORPOSIX */
  6709.  
  6710.     } else if (flow == FLO_XONX) {    /* Xon/Xoff... */
  6711.  
  6712. #ifndef SVORPOSIX
  6713.     ttraw.sg_flags |= TANDEM;
  6714. #else
  6715.     ttraw.c_iflag |= (IXON|IXOFF);
  6716. #endif /* SVORPOSIX */
  6717.     tthflow(FLO_RTSC, 0, &ttraw);    /* Turn off hardware flow control */
  6718.  
  6719.     } else if (flow == FLO_NONE) {    /* No flow control */
  6720.  
  6721. #ifndef SVORPOSIX
  6722.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6723. #else
  6724.     ttraw.c_iflag &= ~(IXON|IXOFF);
  6725. #endif /* SVORPOSIX */
  6726.     tthflow(FLO_RTSC, 0, &ttraw);    /* Turn off any hardware f/c too */
  6727.     }
  6728.  
  6729. /* Set the new modes... */
  6730.  
  6731. #ifndef SVORPOSIX            /* BSD and friends */
  6732. #ifdef BELLV10
  6733.     if (ioctl(ttyfd,TIOCSETP,&ttraw) < 0)
  6734.       return(-1);
  6735. #else
  6736. #ifndef MINIX2
  6737.     if (stty(ttyfd,&ttraw) < 0)
  6738.       return(-1);
  6739. #endif /* MINIX2 */
  6740. #endif /* BELLV10 */
  6741. #else
  6742. #ifdef BSD44ORPOSIX            /* POSIX */
  6743.     if (tcsetattr(ttyfd,TCSADRAIN,&ttraw) < 0)
  6744.       return(-1);
  6745. #else                    /* System V */
  6746.     if (ioctl(ttyfd,TCSETAW,&ttraw) < 0)
  6747.       return(-1);
  6748. #endif /* BSD44ORPOSIX */
  6749. #endif /* SVORPOSIX */
  6750.     return(0);
  6751. }
  6752. #ifdef COHERENT
  6753. #undef SVORPOSIX
  6754. #endif /* COHERENT */
  6755.  
  6756. /*  T T V T -- Condition communication device for use as virtual terminal. */
  6757.  
  6758. int
  6759. #ifdef CK_ANSIC
  6760. ttvt(long speed, int flow)
  6761. #else
  6762. ttvt(speed,flow) long speed; int flow;
  6763. #endif /* CK_ANSIC */
  6764. /* ttvt */ {
  6765.     int s, s2, x;
  6766.  
  6767.     debug(F101,"ttvt ttyfd","",ttyfd);
  6768.     debug(F101,"ttvt tvtflg","",tvtflg);
  6769.     debug(F111,"ttvt speed",ckitoa(ttspeed),speed);
  6770.     debug(F111,"ttvt flow",ckitoa(ttflow),flow);
  6771.     debug(F111,"ttvt curcarr",ckitoa(ttcarr),curcarr);
  6772.  
  6773. /* Note: NetBSD and maybe other BSD44s have cfmakeraw() */
  6774. /* Maybe it would be simpler to use it... */
  6775.  
  6776.     ttpmsk = 0xff;
  6777. #ifdef NOLOCAL
  6778.     return(conbin((char)escchr));
  6779. #else
  6780.     if (ttyfd < 0) {            /* Not open. */
  6781.     if (ttchk() < 0)
  6782.       return(-1);
  6783.     else                /* But maybe something buffered. */
  6784.       return(0);
  6785.     }
  6786. #ifdef NETCMD
  6787.     if (ttpipe) return(0);
  6788. #endif /* NETCMD */
  6789. #ifdef NETPTY
  6790.     if (ttpty) return(0);
  6791. #endif /* NETPTY */
  6792. #ifdef NETCONN
  6793.     if (netconn) {
  6794. #ifdef TCPSOCKET
  6795. #ifdef TCP_NODELAY
  6796.         {
  6797.         extern int tcp_nodelay;
  6798.         if (ttnet == NET_TCPB) {
  6799.         if (nodelay_sav > -1) {
  6800.             no_delay(ttyfd,nodelay_sav);
  6801.             nodelay_sav = -1;
  6802.         }
  6803.         }
  6804.         }
  6805. #endif /* TCP_NODELAY */
  6806. #ifdef TN_COMPORT
  6807.         if (istncomport()) {
  6808.             int rc = -1;
  6809.             if (tvtflg != 0 && speed == ttspeed && flow == ttflow
  6810.                  /* && ttcarr == curcarr */ ) {
  6811.                 debug(F100,"ttvt modes already set, skipping...","",0);
  6812.                 return(0);            /* Already been called. */
  6813.             }
  6814.             if (flow != ttflow) {
  6815.                 if ((rc = tnsetflow(flow)) < 0)
  6816.           return(rc);
  6817.                 ttflow = flow;
  6818.             }
  6819.             if (speed != ttspeed) {
  6820.                 if (speed <= 0) 
  6821.           speed = tnc_get_baud();
  6822.                 else if ((rc = tnc_set_baud(speed)) < 0)
  6823.           return(rc);
  6824.                 ttspeed = speed;
  6825.             }
  6826.             tnc_set_datasize(8);
  6827.         tnc_set_stopsize(stopbits);
  6828.  
  6829. #ifdef HWPARITY
  6830.             if (hwparity) {
  6831.                 switch (hwparity) {
  6832.           case 'e':        /* Even */
  6833.                     debug(F100,"ttres 8 bits + even parity","",0);
  6834.                     tnc_set_parity(3);
  6835.                     break;
  6836.           case 'o':        /* Odd */
  6837.                     debug(F100,"ttres 8 bits + odd parity","",0);
  6838.                     tnc_set_parity(2);
  6839.                     break;
  6840.           case 'm':        /* Mark */
  6841.                     debug(F100,"ttres 8 bits + invalid parity: mark","",0);
  6842.                     tnc_set_parity(4);
  6843.                     break;
  6844.           case 's':        /* Space */
  6845.                     debug(F100,"ttres 8 bits + invalid parity: space","",0);
  6846.                     tnc_set_parity(5);
  6847.                     break;
  6848.                 }
  6849.             } else
  6850. #endif /* HWPARITY */
  6851.             {
  6852.                 tnc_set_parity(1);    /* None */
  6853.             }
  6854.             tvtflg = 1;
  6855.             return(0);
  6856.         }
  6857. #endif /* TN_COMPORT */
  6858. #endif /* TCPSOCKET */
  6859.     tvtflg = 1;            /* Network connections... */
  6860.     debug(F100,"ttvt network connection, skipping...","",0);
  6861.     return(0);            /* ... require no special setup */
  6862.     }
  6863. #endif /* NETCONN */
  6864.  
  6865.     if (tvtflg != 0 && speed == ttspeed && flow == ttflow
  6866.     /* && ttcarr == curcarr */ )
  6867.       {
  6868.       debug(F100,"ttvt modes already set, skipping...","",0);
  6869.       return(0);            /* Already been called. */
  6870.       }
  6871.  
  6872.     if (ttfdflg
  6873. #ifndef Plan9
  6874.     && !isatty(ttyfd)
  6875. #endif /* Plan9 */
  6876.     ) {
  6877.     debug(F100,"ttvt using external fd, skipping...","",0);
  6878.     return(0);
  6879.     }
  6880.  
  6881.     debug(F100,"ttvt setting modes...","",0);
  6882.  
  6883.     if (xlocal) {            /* For external lines... */
  6884.     s2 = (int) (speed / 10L);
  6885.     s = ttsspd(s2);            /* Check/set the speed */
  6886.     carrctl(&tttvt, flow != FLO_DIAL /* Do carrier control */
  6887.         && (ttcarr == CAR_ON || (ttcarr == CAR_AUT && ttmdm != 0)));
  6888.     } else
  6889.       s = s2 = -1;
  6890.  
  6891. #ifdef COHERENT
  6892. #define SVORPOSIX
  6893. #endif /* COHERENT */
  6894.  
  6895. #ifndef SVORPOSIX
  6896.     /* Berkeley, V7, etc */
  6897.     if (flow == FLO_RTSC ||        /* Hardware flow control */
  6898.     flow == FLO_DTRC ||
  6899.     flow == FLO_DTRT) {
  6900.     tthflow(flow, 1, &tttvt);
  6901.     debug(F100,"ttvt hard flow, TANDEM off","",0);
  6902.     tttvt.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6903.     } else if (flow == FLO_XONX) {    /* Xon/Xoff flow control */
  6904.     debug(F100,"ttvt TANDEM on","",0);
  6905.     tttvt.sg_flags |= TANDEM;    /* Ask for it. */
  6906.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  6907.     } else if (flow == FLO_NONE) {
  6908.     debug(F100,"ttvt no flow, TANDEM off, RAW on","",0);
  6909.     tttvt.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6910.     tthflow(flow, 0, &tttvt);    /* Turn off any hardware f/c too */
  6911.     tttvt.sg_flags |= RAW;        /* Enter raw mode */
  6912.     } else if (flow == FLO_KEEP) {    /* Keep device's original setting */
  6913.     debug(F100,"ttvt keeping original TANDEM","",0);
  6914.     tttvt.sg_flags &= ~TANDEM;
  6915.     tttvt.sg_flags |= (ttold.sg_flags & TANDEM);
  6916.     /* NOTE: We should also handle hardware flow control here! */
  6917.     }
  6918.     tttvt.sg_flags |= RAW;              /* Raw mode in all cases */
  6919. #ifdef TOWER1
  6920.     tttvt.sg_flags &= ~(ECHO|ANYP);     /* No echo or parity */
  6921. #else
  6922.     tttvt.sg_flags &= ~ECHO;            /* No echo */
  6923. #endif /* TOWER1 */
  6924.  
  6925. #ifdef BELLV10
  6926.     if (ioctl(ttyfd,TIOCSETP,&tttvt) < 0) /* Set the new modes */
  6927.       return(-1);
  6928. #else
  6929.     if (stty(ttyfd,&tttvt) < 0)        /* Set the new modes */
  6930.       return(-1);
  6931. #endif /* BELLV10 */
  6932.  
  6933. #else /* It is ATTSV or POSIX */
  6934.  
  6935.     if (flow == FLO_XONX) {        /* Software flow control */
  6936.     tttvt.c_iflag |= (IXON|IXOFF);    /* On if requested. */
  6937.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  6938.     debug(F100,"ttvt SVORPOSIX flow XON/XOFF","",0);
  6939.     } else if (flow == FLO_NONE) {    /* NONE */
  6940.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff */
  6941.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  6942.     debug(F100,"ttvt SVORPOSIX flow NONE","",0);
  6943.     } else if (flow == FLO_KEEP) {
  6944.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff flags */
  6945.     tttvt.c_iflag |= (ttold.c_iflag & (IXON|IXOFF)); /* OR in old ones */
  6946. #ifdef POSIX_CRTSCTS
  6947.         tttvt.c_cflag &= ~CRTSCTS;    /* Turn off RTS/CTS flag */
  6948.         tttvt.c_cflag |= (ttold.c_cflag & CRTSCTS); /* OR in old one */
  6949. #endif /* POSIX_CRTSCTS */
  6950.     debug(F100,"ttvt SVORPOSIX flow KEEP","",0);
  6951.     } else if (flow == FLO_RTSC ||    /* Hardware flow control */
  6952.            flow == FLO_DTRC ||
  6953.            flow == FLO_DTRT) {
  6954.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* (196) */
  6955.     tthflow(flow, 1, &tttvt);
  6956.     debug(F100,"ttvt SVORPOSIX flow HARD","",0);
  6957.     }
  6958. #ifndef OXOS
  6959. #ifdef COHERENT
  6960.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO);
  6961. #else
  6962.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO|IEXTEN);
  6963. #endif /* COHERENT */
  6964. #ifdef QNX
  6965.     /* Needed for hwfc */
  6966.     if (flow == FLO_RTSC || flow == FLO_DTRC || flow == FLO_DTRT)
  6967.       tttvt.c_lflag |= IEXTEN;
  6968. #endif /* QNX */
  6969. #else /* OXOS */
  6970.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO);
  6971.     tttvt.c_cc[VDISCARD] = tttvt.c_cc[VLNEXT] = CDISABLE;
  6972. #endif /* OXOS */
  6973.  
  6974.     tttvt.c_iflag |= (IGNBRK|IGNPAR);
  6975.  
  6976. /* Stop bits */
  6977.  
  6978. #ifdef CSTOPB
  6979.     if (xlocal) {
  6980.     if (stopbits == 2) {
  6981.         tttvt.c_cflag |= CSTOPB;    /* 2 stop bits */
  6982.         debug(F100,"ttvt 2 stopbits","",0);
  6983.     } else if (stopbits == 1) {
  6984.         tttvt.c_cflag &= ~(CSTOPB);    /* 1 stop bit */
  6985.         debug(F100,"ttvt 1 stopbit","",0);
  6986.     }
  6987.     }
  6988. #endif /* CSTOPB */
  6989.  
  6990. /* Parity */
  6991.  
  6992. #ifdef HWPARITY
  6993.     if (hwparity && xlocal) {        /* Hardware parity */
  6994. #ifdef COMMENT
  6995. /* Uncomment this only if needed -- I don't think it is */
  6996.     ttraw.c_cflag &= ~(CSIZE);    /* Clear out character-size mask */
  6997.     ttraw.c_cflag |= CS8;        /* And set it to 8 */
  6998. #endif /* COMMENT */
  6999. #ifdef IGNPAR
  7000.     debug(F101,"ttvt hwparity IGNPAR","",IGNPAR);
  7001.     tttvt.c_iflag |= IGNPAR;    /* Don't discard incoming bytes */
  7002. #endif /* IGNPAR */
  7003.     tttvt.c_cflag |= PARENB;    /* Enable parity */
  7004.  
  7005.     switch (hwparity) {
  7006.       case 'e':            /* Even */
  7007.         tttvt.c_cflag &= ~(PARODD);
  7008.         debug(F100,"ttvt 8 bits + even parity","",0);
  7009.         break;
  7010.       case 'o':            /* Odd */
  7011.         tttvt.c_cflag |= PARODD;
  7012.         debug(F100,"ttvt 8 bits + odd parity","",0);
  7013.         break;
  7014.       case 'm':            /* Mark */
  7015.       case 's':            /* Space */
  7016.         /* PAREXT is mentioned in SVID but the details are not given. */
  7017.         /* PAREXT is not included in POSIX ISO/IEC 9945-1. */
  7018.         debug(F100,"ttvt 8 bits + invalid parity","",0);
  7019.         break;
  7020.     }
  7021.     } else {                /* We handle parity ourselves */
  7022. #endif /* HWPARITY */
  7023.     tttvt.c_cflag &= ~(PARENB);    /* Don't enable parity */
  7024. #ifdef HWPARITY
  7025.     }
  7026. #endif /* HWPARITY */
  7027.  
  7028. #ifdef ATTSV
  7029. #ifdef BSD44
  7030.     /* Things not to do... */
  7031.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|INPCK|ISTRIP|IXANY);
  7032. #else
  7033.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|IUCLC|INPCK|ISTRIP|IXANY);
  7034. #endif /* BSD44 */
  7035. #else /* POSIX */
  7036.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|INPCK|ISTRIP);
  7037. #endif /* ATTSV */
  7038.     tttvt.c_cflag &= ~(CSIZE);        /* Zero out the char size field */
  7039.     tttvt.c_cflag |= (CS8|CREAD|HUPCL);    /* Char size 8, enable receiver, hup */
  7040.     tttvt.c_oflag &= ~OPOST;        /* Don't postprocess output */
  7041. #ifndef VEOF /* DGUX termio has VEOF at entry 4, see comment above */
  7042.     tttvt.c_cc[4] = 1;
  7043. #else
  7044. #ifndef OXOS
  7045. #ifdef VMIN
  7046.     tttvt.c_cc[VMIN] = 1;
  7047. #endif /* VMIN */
  7048. #else /* OXOS */
  7049.     tttvt.c_min = 1;
  7050. #endif /* OXOS */
  7051. #endif /* VEOF */
  7052. #ifndef VEOL    /* DGUX termio has VEOL at entry 5, see comment above */
  7053.     tttvt.c_cc[5] = 0;
  7054. #else
  7055. #ifndef OXOS
  7056. #ifdef VTIME
  7057.     tttvt.c_cc[VTIME] = 0;
  7058. #endif /* VTIME */
  7059. #else /* OXOS */
  7060.     tttvt.c_time = 0;
  7061. #endif /* OXOS */
  7062. #endif /* VEOL */
  7063.  
  7064. #ifdef Plan9
  7065.     if (p9ttyparity('n') < 0)
  7066.       return -1;
  7067. #else
  7068. #ifdef BSD44ORPOSIX
  7069.     errno = 0;
  7070. #ifdef BEOSORBEBOX
  7071.     tttvt.c_cc[VMIN] = 0;        /* DR7 can only poll. */
  7072. #endif /* BEOSORBEBOX */
  7073.  
  7074.     x = tcsetattr(ttyfd,TCSADRAIN,&tttvt);
  7075.     debug(F101,"ttvt BSD44ORPOSIX tcsetattr","",x);
  7076.     if (x < 0) {
  7077.     debug(F101,"ttvt BSD44ORPOSIX tcsetattr errno","",errno);
  7078.     return(-1);
  7079.     }
  7080. #else /* ATTSV */
  7081.     x = ioctl(ttyfd,TCSETAW,&tttvt);
  7082.     debug(F101,"ttvt ATTSV ioctl TCSETAW","",x);
  7083.     if (x < 0) {            /* set new modes . */
  7084.     debug(F101,"ttvt ATTSV ioctl TCSETAW errno","",errno);
  7085.     return(-1);    
  7086.     }
  7087. #endif /* BSD44ORPOSIX */
  7088. #endif /* Plan9 */
  7089. #endif /* ATTSV */
  7090.  
  7091.     ttspeed = speed;            /* Done, remember how we were */
  7092.     ttflow = flow;            /* called, so we can decide how to */
  7093.     tvtflg = 1;                /* respond next time. */
  7094.     debug(F100,"ttvt ok","",0);
  7095.     return(0);
  7096.  
  7097. #ifdef COHERENT
  7098. #undef SVORPOSIX
  7099. #endif /* COHERENT */
  7100.  
  7101. #endif /* NOLOCAL */
  7102. }
  7103.  
  7104. #ifndef NOLOCAL
  7105.  
  7106. /* Serial speed department . . . */
  7107.  
  7108. /*
  7109.   SCO OSR5.0.x might or might not support high speeds.  Sometimes they are not
  7110.   defined in the header files but they are supported (e.g. when building with
  7111.   UDK compiler rather than /bin/cc), sometimes vice versa.  Even though 5.0.4
  7112.   was the first release that came with high serial speeds standard, releases
  7113.   back to 5.0.0 could use them if certain patches (or "supplements") were
  7114.   applied to the SIO driver.  Plus a lot of SCO installations run third-party
  7115.   drivers.
  7116. */
  7117. #ifdef CK_SCOV5
  7118. #ifndef B38400
  7119. #define    B38400    0000017
  7120. #endif /* B38400 */
  7121. #ifndef B57600
  7122. #define    B57600    0000021
  7123. #endif /* B57600 */
  7124. #ifndef B76800
  7125. #define    B76800    0000022
  7126. #endif /* B76800 */
  7127. #ifndef B115200
  7128. #define    B115200    0000023
  7129. #endif /* B115200 */
  7130. #ifndef B230400
  7131. #define    B230400    0000024
  7132. #endif /* B230400 */
  7133. #ifndef B460800
  7134. #define    B460800    0000025
  7135. #endif /* B460800 */
  7136. #ifndef B921600
  7137. #define    B921600    0000026
  7138. #endif /* B921600 */
  7139. #endif /* CK_SCOV5 */
  7140. /*
  7141.   Plan 9's native speed setting interface lets you set anything you like,
  7142.   but will fail if the hardware doesn't like it, so we allow all the common
  7143.   speeds.
  7144. */
  7145. #ifdef Plan9
  7146. #ifndef B50
  7147. #define B50 50
  7148. #endif /* B50 */
  7149. #ifndef B75
  7150. #define B75 75
  7151. #endif /* B75 */
  7152. #ifndef B110
  7153. #define B110 110
  7154. #endif /* B110 */
  7155. #ifndef B134
  7156. #define B134 134
  7157. #endif /* B134 */
  7158. #ifndef B200
  7159. #define B200 200
  7160. #endif /* B200 */
  7161. #ifndef B300
  7162. #define B300 300
  7163. #endif /* B300 */
  7164. #ifndef B1200
  7165. #define B1200 1200
  7166. #endif /* B1200 */
  7167. #ifndef B1800
  7168. #define B1800 1800
  7169. #endif /* B1800 */
  7170. #ifndef B2400
  7171. #define B2400 2400
  7172. #endif /* B2400 */
  7173. #ifndef B4800
  7174. #define B4800 4800
  7175. #endif /* B4800 */
  7176. #ifndef B9600
  7177. #define B9600 9600
  7178. #endif /* B9600 */
  7179. #ifndef B14400
  7180. #define B14400 14400
  7181. #endif /* B14400 */
  7182. #ifndef B19200
  7183. #define B19200 19200
  7184. #endif /* B19200 */
  7185. #ifndef B28800
  7186. #define B28800 28800
  7187. #endif /* B28800 */
  7188. #ifndef B38400
  7189. #define B38400 38400
  7190. #endif /* B38400 */
  7191. #ifndef B57600
  7192. #define B57600 57600
  7193. #endif /* B57600 */
  7194. #ifndef B76800
  7195. #define B76800 76800
  7196. #endif /* B76800 */
  7197. #ifndef B115200
  7198. #define B115200 115200
  7199. #endif /* B115200 */
  7200. #ifndef B230400
  7201. #define B230400 230400
  7202. #endif /* B230400 */
  7203. #ifndef B460800
  7204. #define B460800 460800
  7205. #endif /* B460800 */
  7206. #ifndef B921600
  7207. #define B921600 921600
  7208. #endif /* B921600 */
  7209. #endif /* Plan9 */
  7210.  
  7211. /*  T T S S P D  --  Checks and sets transmission rate.  */
  7212.  
  7213. /*  Call with speed in characters (not bits!) per second. */
  7214. /*  Returns -1 on failure, 0 if it did nothing, 1 if it changed the speed. */
  7215.  
  7216. #ifdef USETCSETSPEED
  7217. /*
  7218.   The tcsetspeed() / tcgetspeed() interface lets you pass any number at all
  7219.   to be used as a speed to be set, rather than forcing a choice from a
  7220.   predefined list.  It seems to be peculiar to UnixWare 7.
  7221.  
  7222.   These are the function codes to be passed to tc[gs]etspeed(),
  7223.   but for some reason they don't seem to be picked up from termios.h.
  7224. */
  7225. #ifndef TCS_ALL
  7226. #define TCS_ALL 0
  7227. #endif /* TCS_ALL */
  7228. #ifndef TCS_IN
  7229. #define TCS_IN 1
  7230. #endif /* TCS_IN */
  7231. #ifndef TCS_OUT
  7232. #define TCS_OUT 2
  7233. #endif /* TCS_OUT */
  7234. #endif /* USETCSETSPEED */
  7235.  
  7236. int
  7237. ttsspd(cps) int cps; {
  7238.     int x;
  7239. #ifdef POSIX
  7240. /* Watch out, speed_t should be unsigned, so don't compare with -1, etc... */
  7241.     speed_t
  7242. #else
  7243.     int
  7244. #endif /* POSIX */
  7245.       s, s2;
  7246.     int ok = 1;                /* Speed check result, assume ok */
  7247.  
  7248. #ifdef OLINUXHISPEED
  7249.     unsigned int spd_flags = 0;
  7250.     struct serial_struct serinfo;
  7251. #endif /* OLINUXHISPEED */
  7252.  
  7253.     debug(F101,"ttsspd cps","",cps);
  7254.     debug(F101,"ttsspd ttyfd","",ttyfd);
  7255.     debug(F101,"ttsspd xlocal","",xlocal);
  7256.  
  7257.     if (ttyfd < 0 || xlocal == 0)    /* Don't set speed on console */
  7258.       return(0);
  7259.  
  7260. #ifdef    NETCONN
  7261.     if (netconn) {
  7262. #ifdef TN_COMPORT
  7263.         if (istncomport())
  7264.       return(tnc_set_baud(cps * 10));
  7265.         else
  7266. #endif /* TN_COMPORT */
  7267.     return(0);
  7268.   }
  7269. #endif    /* NETCONN */
  7270. #ifdef NETCMD
  7271.     if (ttpipe) return(0);
  7272. #endif /* NETCMD */
  7273. #ifdef NETPTY
  7274.     if (ttpty) return(0);
  7275. #endif /* NETPTY */
  7276.  
  7277.     if (cps < 0) return(-1);
  7278.     s = s2 = 0;                /* NB: s and s2 might be unsigned */
  7279.  
  7280. #ifdef USETCSETSPEED
  7281.  
  7282.     s = cps * 10L;
  7283.  
  7284.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  7285.     debug(F101,"ttsspd tcgetattr","",x);
  7286.     if (x < 0)
  7287.       return(-1);
  7288.     debug(F101,"ttsspd TCSETSPEED speed","",s);
  7289.  
  7290.     errno = 0;
  7291.     if (s == 8880L) {            /* 75/1200 split speed requested */
  7292.     tcsetspeed(TCS_IN, &ttcur, 1200L);
  7293.     tcsetspeed(TCS_OUT, &ttcur, 75L);
  7294.     } else
  7295.       tcsetspeed(TCS_ALL, &ttcur, s);    /* Put new speed in structs */
  7296. #ifdef DEBUG
  7297.     if (errno & deblog) {
  7298.     debug(F101,"ttsspd TCSETSPEED errno","",errno);
  7299.     }
  7300. #endif /* DEBUG */
  7301.  
  7302. #ifdef COMMENT
  7303.     tcsetspeed(TCS_ALL, &ttraw, s);
  7304.     tcsetspeed(TCS_ALL, &tttvt, s);
  7305.     tcsetspeed(TCS_ALL, &ttold, s);
  7306. #else
  7307.     if (s == 8880L) {            /* 75/1200 split speed requested */
  7308.     tcsetspeed(TCS_IN, &ttraw, 1200L);
  7309.     tcsetspeed(TCS_OUT, &ttraw, 75L);
  7310.     tcsetspeed(TCS_IN, &tttvt, 1200L);
  7311.     tcsetspeed(TCS_OUT, &tttvt, 75L);
  7312.     tcsetspeed(TCS_IN, &ttold, 1200L);
  7313.     tcsetspeed(TCS_OUT, &ttold, 75L);
  7314.     } else {
  7315.     tcsetspeed(TCS_ALL, &ttraw, s);
  7316.     tcsetspeed(TCS_ALL, &tttvt, s);
  7317.     tcsetspeed(TCS_ALL, &ttold, s);
  7318.     }
  7319. #endif /* COMMENT */
  7320.  
  7321.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur); /* Set the speed */
  7322.     debug(F101,"ttsspd tcsetattr","",x);
  7323.     if (x < 0)
  7324.       return(-1);
  7325.  
  7326. #else  /* Not USETCSETSPEED */
  7327.  
  7328. #ifdef MINIX2        /* Hack alert */
  7329. #define MINIX        /* Use pre-2.0 speed selection for Minix 2.0 as well */
  7330. #endif /* MINIX2 */
  7331.  
  7332.     /* First check that the given speed is valid. */
  7333.  
  7334.     switch (cps) {
  7335. #ifndef MINIX
  7336.       case 0:   s = B0;    break;
  7337.       case 5:   s = B50;   break;
  7338.       case 7:   s = B75;   break;
  7339. #endif /* MINIX */
  7340.       case 11:  s = B110;  break;
  7341. #ifndef MINIX
  7342.       case 13:  s = B134;  break;
  7343.       case 15:  s = B150;  break;
  7344.       case 20:  s = B200;  break;
  7345. #endif /* MINIX */
  7346.       case 30:  s = B300;  break;
  7347. #ifndef MINIX
  7348.       case 60:  s = B600;  break;
  7349. #endif /* MINIX */
  7350.       case 120: s = B1200; break;
  7351. #ifndef MINIX
  7352.       case 180: s = B1800; break;
  7353. #endif /* MINIX */
  7354.       case 240: s = B2400; break;
  7355.       case 480: s = B4800; break;
  7356. #ifndef MINIX
  7357.       case 888: s = B75; s2 = B1200; break; /* 888 = 75/1200 split speed */
  7358. #endif /* MINIX */
  7359. #ifdef B7200
  7360.       case 720: s = B7200; break;
  7361. #endif /* B7200 */
  7362.       case 960: s = B9600; break;
  7363. #ifdef B14400
  7364.       case 1440: s = B14400; break;
  7365. #endif /* B14400 */
  7366. #ifdef B19200
  7367.       case 1920: s = B19200; break;
  7368. #else
  7369. #ifdef EXTA
  7370.       case 1920: s = EXTA; break;
  7371. #endif /* EXTA */
  7372. #endif /* B19200 */
  7373. #ifdef B28800
  7374.       case 2880: s = B28800; break;
  7375. #endif /* B28800 */
  7376. #ifdef B38400
  7377.       case 3840: s = B38400;
  7378. #ifdef OLINUXHISPEED
  7379.         spd_flags = ~ASYNC_SPD_MASK;    /* Nonzero, but zero flags */
  7380. #endif /* OLINUXHISPEED */
  7381.     break;
  7382. #else /* B38400 not defined... */
  7383. #ifdef EXTB
  7384.       case 3840: s = EXTB; break;
  7385. #endif /* EXTB */
  7386. #endif /* B38400 */
  7387.  
  7388. #ifdef HPUX
  7389. #ifdef _B57600
  7390.       case 5760: s = _B57600; break;
  7391. #endif /* _B57600 */
  7392. #ifdef _B115200
  7393.       case 11520: s = _B115200; break;
  7394. #endif /* _B115200 */
  7395. #else
  7396. #ifdef OLINUXHISPEED
  7397. /*
  7398.   This bit from <carlo@sg.tn.tudelft.nl>:
  7399.   "Only note to make is maybe this: When the ASYNC_SPD_CUST flags are set then
  7400.   setting the speed to 38400 will set the custom speed (and ttgspd returns
  7401.   38400), but speeds 57600 and 115200 won't work any more because I didn't
  7402.   want to mess up the speed flags when someone is doing sophisticated stuff
  7403.   like custom speeds..."
  7404. */
  7405.       case 5760: s = B38400; spd_flags = ASYNC_SPD_HI; break;
  7406.       case 11520: s = B38400; spd_flags = ASYNC_SPD_VHI; break;
  7407. #else
  7408. #ifdef B57600
  7409.       case 5760: s = B57600; break;
  7410. #endif /* B57600 */
  7411. #ifdef B76800
  7412.       case 7680: s = B76800; break;
  7413. #endif /* B76800 */
  7414. #ifdef B115200
  7415.       case 11520: s = B115200; break;
  7416. #endif /* B115200 */
  7417. #endif /* OLINUXHISPEED */
  7418. #ifdef B153600
  7419.       case 15360: s = B153600; break;
  7420. #endif /* B153600 */
  7421. #ifdef B230400
  7422.       case 23040: s = B230400; break;
  7423. #endif /* B230400 */
  7424. #ifdef B307200
  7425.       case 30720: s = B307200; break;
  7426. #endif /* B307200 */
  7427. #ifdef B460800
  7428.       case 46080: s = B460800; break;
  7429. #endif /* 460800 */
  7430. #ifdef B921600
  7431.       case 92160: s = B921600; break;
  7432. #endif /* B921600 */
  7433. #endif /* HPUX */
  7434.       default:
  7435.     ok = 0;                /* Good speed not found, so not ok */
  7436.     break;
  7437.     }
  7438.     debug(F101,"ttsspd ok","",ok);
  7439.     debug(F101,"ttsspd s","",s);
  7440.  
  7441.     if (!ok) {
  7442.     debug(F100,"ttsspd fails","",0);
  7443.     return(-1);
  7444.     } else {
  7445.     if (!s2) s2 = s;        /* Set input speed */
  7446. #ifdef Plan9
  7447.     if (p9ttsspd(cps) < 0)
  7448.       return(-1);
  7449. #else
  7450. #ifdef BSD44ORPOSIX
  7451.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  7452.     debug(F101,"ttsspd tcgetattr","",x);
  7453.     if (x < 0)
  7454.       return(-1);
  7455. #ifdef OLINUXHISPEED
  7456.     debug(F101,"ttsspd spd_flags","",spd_flags);
  7457.     if (spd_flags && spd_flags != ASYNC_SPD_CUST) {
  7458.         if (ioctl(ttyfd, TIOCGSERIAL, &serinfo) < 0) {
  7459.         debug(F100,"ttsspd: TIOCGSERIAL failed","",0);
  7460.         return(-1);
  7461.         } else debug(F100,"ttsspd: TIOCGSERIAL ok","",0);
  7462.         serinfo.flags &= ~ASYNC_SPD_MASK;
  7463.         serinfo.flags |= (spd_flags & ASYNC_SPD_MASK);
  7464.         if (ioctl(ttyfd, TIOCSSERIAL, &serinfo) < 0)
  7465.           return(-1);
  7466.     }
  7467. #endif /* OLINUXHISPEED */
  7468.     cfsetospeed(&ttcur,s);
  7469.     cfsetispeed(&ttcur,s2);
  7470.     cfsetospeed(&ttraw,s);
  7471.     cfsetispeed(&ttraw,s2);
  7472.     cfsetospeed(&tttvt,s);
  7473.     cfsetispeed(&tttvt,s2);
  7474.     cfsetospeed(&ttold,s);
  7475.     cfsetispeed(&ttold,s2);
  7476.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  7477.     debug(F101,"ttsspd tcsetattr","",x);
  7478.     if (x < 0) return(-1);
  7479. #else
  7480. #ifdef ATTSV
  7481.     if (cps == 888) return(-1);    /* No split speeds, sorry. */
  7482.     x = ioctl(ttyfd,TCGETA,&ttcur);
  7483.     debug(F101,"ttsspd TCGETA ioctl","",x);
  7484.     if (x < 0) return(-1);
  7485.     ttcur.c_cflag &= ~CBAUD;
  7486.     ttcur.c_cflag |= s;
  7487.     tttvt.c_cflag &= ~CBAUD;
  7488.     tttvt.c_cflag |= s;
  7489.     ttraw.c_cflag &= ~CBAUD;
  7490.     ttraw.c_cflag |= s;
  7491.     ttold.c_cflag &= ~CBAUD;
  7492.     ttold.c_cflag |= s;
  7493.     x = ioctl(ttyfd,TCSETAW,&ttcur);
  7494.     debug(F101,"ttsspd TCSETAW ioctl","",x);
  7495.     if (x < 0) return(-1);
  7496. #else
  7497. #ifdef BELLV10
  7498.     x = ioctl(ttyfd,TIOCGDEV,&tdcur);
  7499.     debug(F101,"ttsspd TIOCGDEV ioctl","",x);
  7500.     if (x < 0) return(-1);
  7501.     tdcur.ispeed = s2;
  7502.     tdcur.ospeed = s;
  7503.     errno = 0;
  7504.     ok = ioctl(ttyfd,TIOCSDEV,&tdcur);
  7505.     debug(F101,"ttsspd BELLV10 ioctl","",ok);
  7506.     if (ok < 0) {
  7507.         perror(ttnmsv);
  7508.         debug(F101,"ttsspd BELLV10 errno","",ok);
  7509.         return(-1);
  7510.     }
  7511. #else
  7512.     x = gtty(ttyfd,&ttcur);
  7513.     debug(F101,"ttsspd gtty","",x);
  7514.     if (x < 0) return(-1);
  7515.     ttcur.sg_ospeed = s; ttcur.sg_ispeed = s2;
  7516.     tttvt.sg_ospeed = s; tttvt.sg_ispeed = s2;
  7517.     ttraw.sg_ospeed = s; ttraw.sg_ispeed = s2;
  7518.     ttold.sg_ospeed = s; ttold.sg_ispeed = s2;
  7519.     x = stty(ttyfd,&ttcur);
  7520.     debug(F101,"ttsspd stty","",x);
  7521.     if (x < 0) return(-1);
  7522. #endif /* BELLV10 */
  7523. #endif /* ATTSV */
  7524. #endif /* BSD44ORPOSIX */
  7525. #endif /* Plan9 */
  7526.     }
  7527.     return(1);                /* Return 1 = success. */
  7528. #endif /* USETCSETSPEED */
  7529. }
  7530.  
  7531. #endif /* NOLOCAL */
  7532.  
  7533. /* C O N G S P D  -  Get speed of console terminal  */
  7534.  
  7535. long
  7536. congspd() {
  7537. /*
  7538.   This is a disgusting hack.  The right way to do this would be to pass an
  7539.   argument to ttgspd(), but then we'd need to change the Kermit API and
  7540.   all of the ck?tio.c modules.  (Currently used only for rlogin.)
  7541. */
  7542.     int t1;
  7543.     long spd;
  7544. #ifdef NETCONN
  7545.     int t2 = netconn;
  7546.     netconn = 0;
  7547. #endif /* NETCONN */
  7548.     t1 = ttyfd;
  7549.     ttyfd = -1;
  7550.     spd = ttgspd();
  7551.     debug(F101,"congspd","",spd);
  7552. #ifdef NETCONN
  7553.     netconn = t2;
  7554. #endif /* NETCONN */
  7555.     ttyfd = t1;
  7556.     return(spd);
  7557. }
  7558.  
  7559. /*  T T S P D L I S T  -- Get list of serial speeds allowed on this platform */
  7560.  
  7561. #define NSPDLIST 64
  7562. static long spdlist[NSPDLIST];
  7563. /*
  7564.   As written, this picks up the speeds known at compile time, and thus
  7565.   apply to the system where C-Kermit was built, rather than to the one where
  7566.   it is running.  Suggestions for improvement are always welcome.
  7567. */
  7568. long *
  7569. ttspdlist() {
  7570.     int i;
  7571.     for (i = 0; i < NSPDLIST; i++)    /* Initialize the list */
  7572.       spdlist[i] = -1L;
  7573.     i = 1;
  7574.  
  7575. #ifdef USETCSETSPEED            /* No way to find out what's legal */
  7576.     debug(F100,"ttspdlist USETCSETSPEED","",0);
  7577.     spdlist[i++] = 50L;
  7578. #ifndef UW7
  7579.     spdlist[i++] = 75L;
  7580. #endif /* UW7 */
  7581.     spdlist[i++] = 110L;
  7582. #ifndef UW7
  7583.     spdlist[i++] = 134L;
  7584. #endif /* UW7 */
  7585.     spdlist[i++] = 150L;
  7586.     spdlist[i++] = 200L;
  7587.     spdlist[i++] = 300L;
  7588.     spdlist[i++] = 600L;
  7589.     spdlist[i++] = 1200L;
  7590.     spdlist[i++] = 1800L;
  7591.     spdlist[i++] = 2400L;
  7592.     spdlist[i++] = 4800L;
  7593.     spdlist[i++] = 8880L;
  7594.     spdlist[i++] = 9600L;
  7595.     spdlist[i++] = 14400L;
  7596.     spdlist[i++] = 19200L;
  7597.     spdlist[i++] = 28800L;
  7598. #ifndef UW7
  7599.     spdlist[i++] = 33600L;
  7600. #endif /* UW7 */
  7601.     spdlist[i++] = 38400L;
  7602.     spdlist[i++] = 57600L;
  7603.     spdlist[i++] = 76800L;
  7604.     spdlist[i++] = 115200L;
  7605. #ifndef UW7
  7606.     spdlist[i++] = 153600L;
  7607.     spdlist[i++] = 230400L;
  7608.     spdlist[i++] = 307200L;
  7609.     spdlist[i++] = 460800L;
  7610.     spdlist[i++] = 921600L;
  7611. #endif /* UW7 */
  7612.  
  7613. #else  /* USETCSETSPEED */
  7614.  
  7615.     debug(F100,"ttspdlist no USETCSETSPEED","",0);
  7616.  
  7617. #ifdef B50
  7618.     debug(F101,"ttspdlist B50","",B50);
  7619.     spdlist[i++] = 50L;
  7620. #endif /* B50 */
  7621. #ifdef B75
  7622.     debug(F101,"ttspdlist B75","",B75);
  7623.     spdlist[i++] = 75L;
  7624. #endif /* B75 */
  7625. #ifdef B110
  7626.     debug(F101,"ttspdlist B110","",B110);
  7627.     spdlist[i++] = 110L;
  7628. #endif /* B110 */
  7629. #ifdef B134
  7630.     debug(F101,"ttspdlist B134","",B134);
  7631.     spdlist[i++] = 134L;
  7632. #endif /* B134 */
  7633. #ifdef B150
  7634.     debug(F101,"ttspdlist B150","",B150);
  7635.     spdlist[i++] = 150L;
  7636. #endif /* B150 */
  7637. #ifdef B200
  7638.     debug(F101,"ttspdlist B200","",B200);
  7639.     spdlist[i++] = 200L;
  7640. #endif /* B200 */
  7641. #ifdef B300
  7642.     debug(F101,"ttspdlist B300","",B300);
  7643.     spdlist[i++] = 300L;
  7644. #endif /* B300 */
  7645. #ifdef B600
  7646.     debug(F101,"ttspdlist B600","",B600);
  7647.     spdlist[i++] = 600L;
  7648. #endif /* B600 */
  7649. #ifdef B1200
  7650.     debug(F101,"ttspdlist B1200","",B1200);
  7651.     spdlist[i++] = 1200L;
  7652. #endif /* B1200 */
  7653. #ifdef B1800
  7654.     debug(F101,"ttspdlist B1800","",B1800);
  7655.     spdlist[i++] = 1800L;
  7656. #endif /* B1800 */
  7657. #ifdef B2400
  7658.     debug(F101,"ttspdlist B2400","",B2400);
  7659.     spdlist[i++] = 2400L;
  7660. #endif /* B2400 */
  7661. #ifdef B4800
  7662.     debug(F101,"ttspdlist B4800","",B4800);
  7663.     spdlist[i++] = 4800L;
  7664. #endif /* B4800 */
  7665. #ifdef B9600
  7666.     debug(F101,"ttspdlist B9600","",B9600);
  7667.     spdlist[i++] = 9600L;
  7668. #endif /* B9600 */
  7669. #ifdef B14400
  7670.     debug(F101,"ttspdlist B14400","",B14400);
  7671.     spdlist[i++] = 14400L;
  7672. #endif /* B14400 */
  7673. #ifdef B19200
  7674.     debug(F101,"ttspdlist B19200","",B19200);
  7675.     spdlist[i++] = 19200L;
  7676. #else
  7677. #ifdef EXTA
  7678.     debug(F101,"ttspdlist EXTA","",EXTA);
  7679.     spdlist[i++] = 19200L;
  7680. #endif /* EXTA */
  7681. #endif /* B19200 */
  7682. #ifdef B28800
  7683.     debug(F101,"ttspdlist B28800","",B28800);
  7684.     spdlist[i++] = 28800L;
  7685. #endif /* B28800 */
  7686. #ifdef B33600
  7687.     debug(F101,"ttspdlist B33600","",B33600);
  7688.     spdlist[i++] = 33600L;
  7689. #endif /* B33600 */
  7690. #ifdef B38400
  7691.     debug(F101,"ttspdlist B38400","",B38400);
  7692.     spdlist[i++] = 38400L;
  7693. #else
  7694. #ifdef EXTB
  7695.     debug(F101,"ttspdlist EXTB","",EXTB);
  7696.     spdlist[i++] = 38400L;
  7697. #endif /* EXTB */
  7698. #endif /* B38400 */
  7699. #ifdef _B57600
  7700.     debug(F101,"ttspdlist _B57600","",_B57600);
  7701.     spdlist[i++] = 57600L;
  7702. #else
  7703. #ifdef B57600
  7704.     debug(F101,"ttspdlist B57600","",B57600);
  7705.     spdlist[i++] = 57600L;
  7706. #endif /* B57600 */
  7707. #endif /* _B57600 */
  7708. #ifdef B76800
  7709.     debug(F101,"ttspdlist B76800","",B76800);
  7710.     spdlist[i++] = 76800L;
  7711. #endif /* B76800 */
  7712. #ifdef _B115200
  7713.     debug(F101,"ttspdlist _B115200","",_B115200);
  7714.     spdlist[i++] = 115200L;
  7715. #else
  7716. #ifdef B115200
  7717.     debug(F101,"ttspdlist B115200","",B115200);
  7718.     spdlist[i++] = 115200L;
  7719. #endif /* B115200 */
  7720. #endif /* _B115200 */
  7721. #ifdef B153600
  7722.     debug(F101,"ttspdlist B153600","",B153600);
  7723.     spdlist[i++] = 153600L;
  7724. #endif /* B153600 */
  7725. #ifdef B230400
  7726.     debug(F101,"ttspdlist B230400","",B230400);
  7727.     spdlist[i++] = 230400L;
  7728. #endif /* B230400 */
  7729. #ifdef B307200
  7730.     debug(F101,"ttspdlist B307200","",B307200);
  7731.     spdlist[i++] = 307200L;
  7732. #endif /* B307200 */
  7733. #ifdef B460800
  7734.     debug(F101,"ttspdlist B460800","",B460800);
  7735.     spdlist[i++] = 460800L;
  7736. #endif /* B460800 */
  7737. #ifdef B921600
  7738.     debug(F101,"ttspdlist B921600","",B921600);
  7739.     spdlist[i++] = 921600L;
  7740. #endif /* B921600 */
  7741. #endif /* USETCSETSPEED */
  7742.     spdlist[0] = i - 1;            /* Return count in 0th element */
  7743.     debug(F111,"ttspdlist spdlist","0",spdlist[0]);
  7744.     return((long *)spdlist);
  7745. }
  7746.  
  7747. /* T T G S P D  -  Get speed of currently selected tty line  */
  7748.  
  7749. /*
  7750.   Unreliable.  After SET LINE, it returns an actual speed, but not necessarily
  7751.   the real speed.  On some systems, it returns the line's nominal speed, from
  7752.   /etc/ttytab.  Even if you SET SPEED to something else, this function might
  7753.   not notice.
  7754. */
  7755. long
  7756. ttgspd() {                /* Get current serial device speed */
  7757. #ifdef NOLOCAL
  7758.     return(-1L);
  7759. #else
  7760. #ifdef POSIX
  7761.     speed_t                /* Should be unsigned */
  7762. #else
  7763.     int                    /* Isn't unsigned */
  7764. #endif /* POSIX */
  7765.       s;
  7766.     int x;
  7767.     long ss;
  7768. #ifdef OLINUXHISPEED
  7769.     unsigned int spd_flags = 0;
  7770.     struct serial_struct serinfo;
  7771. #endif /* OLINUXHISPEED */
  7772.  
  7773. #ifdef NETCONN
  7774.     if (netconn) {
  7775. #ifdef TN_COMPORT
  7776.     if (istncomport())
  7777.       return(tnc_get_baud());
  7778.     else
  7779. #endif /* TN_COMPORT */
  7780.       return(-1);            /* -1 if network connection */
  7781.     }
  7782. #endif /* NETCONN */
  7783. #ifdef NETCMD
  7784.     if (ttpipe) return(-1);
  7785. #endif /* NETCMD */
  7786. #ifdef NETPTY
  7787.     if (ttpty) return(-1);
  7788. #endif /* NETPTY */
  7789.  
  7790.     debug(F101,"ttgspd ttyfd","",ttyfd);
  7791.  
  7792. #ifdef USETCSETSPEED
  7793.  
  7794.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  7795.     debug(F101,"ttgspd tcgetattr","",x);
  7796.     if (x < 0)
  7797.       return(-1);
  7798.     errno = 0;
  7799.     s = tcgetspeed(TCS_ALL, &ttcur);
  7800.     debug(F101,"ttsspd TCGETSPEED speed","",s);
  7801.     if (s == 0) {
  7802.     long s1, s2;
  7803.     s1 = tcgetspeed(TCS_IN, &ttcur);
  7804.     s2 = tcgetspeed(TCS_OUT, &ttcur);
  7805.     if (s1 == 1200L && s2 == 75L)
  7806.       return(8880L);
  7807.     }
  7808. #ifdef DEBUG
  7809.     if (errno & deblog) {
  7810.     debug(F101,"ttsspd TCGETSPEED errno","",errno);
  7811.     }
  7812. #endif /* DEBUG */
  7813.     return(s);
  7814.  
  7815. #else  /* Not USETCSETSPEED */
  7816.  
  7817. #ifdef Plan9
  7818.     if (ttyfd < 0)
  7819.       ss = -1;
  7820.     else
  7821.       ss = ttylastspeed;
  7822. #else
  7823. #ifdef OLINUXHISPEED
  7824.     debug(F100,"ttgspd Linux OLINUXHISPEED","",0);
  7825. #endif /* OLINUXHISPEED */
  7826.  
  7827.     if (ttyfd < 0) {
  7828. #ifdef BSD44ORPOSIX
  7829.     s = cfgetospeed(&ccold);
  7830.     debug(F101,"ttgspd cfgetospeed 1 POSIX","",s);
  7831. #else
  7832. #ifdef ATTSV
  7833.     s = ccold.c_cflag & CBAUD;
  7834.     debug(F101,"ttgspd c_cflag CBAUD 1 ATTSV","",s);
  7835. #else
  7836.     s = ccold.sg_ospeed;        /* (obtained by congm()) */
  7837.     debug(F101,"ttgspd sg_ospeed 1","",s);
  7838. #endif /* ATTSV */
  7839. #endif /* BSD44POSIX */
  7840.  
  7841.     } else {
  7842. #ifdef BSD44ORPOSIX
  7843.     if (tcgetattr(ttyfd,&ttcur) < 0) return(-1);
  7844.     s = cfgetospeed(&ttcur);
  7845.     debug(F101,"ttgspd cfgetospeed 2 BSDORPOSIX","",s);
  7846. #ifdef OLINUXHISPEED
  7847.     if (ioctl(ttyfd,TIOCGSERIAL,&serinfo) > -1)
  7848.       spd_flags = serinfo.flags & ASYNC_SPD_MASK;
  7849.     debug(F101,"ttgspd spd_flags","",spd_flags);
  7850. #endif /* OLINUXHISPEED */
  7851. #else
  7852. #ifdef ATTSV
  7853.     x = ioctl(ttyfd,TCGETA,&ttcur);
  7854.     debug(F101,"ttgspd ioctl 2 ATTSV x","",x);
  7855.     debug(F101,"ttgspd ioctl 2 ATTSV errno","",errno);
  7856.     if (x < 0) return(-1);
  7857.     s = ttcur.c_cflag & CBAUD;
  7858.     debug(F101,"ttgspd ioctl 2 ATTSV speed","",s);
  7859. #else
  7860. #ifdef BELLV10
  7861.     x = ioctl(ttyfd,TIOCGDEV,&tdcur);
  7862.     debug(F101,"ttgspd ioctl 2 BELLV10 x","",x);
  7863.     if (x < 0) return(-1);
  7864.     s = tdcur.ospeed;
  7865.     debug(F101,"ttgspd ioctl 2 BELLV10 speed","",s);
  7866. #else
  7867.     x = gtty(ttyfd,&ttcur);
  7868.     debug(F101,"ttgspd gtty 2 x","",x);
  7869.     debug(F101,"ttgspd gtty 2 errno","",errno);
  7870.     if (x < 0) return(-1);
  7871.     s = ttcur.sg_ospeed;
  7872.     debug(F101,"ttgspd gtty 2 speed","",s);
  7873. #endif /* BELLV10 */
  7874. #endif /* ATTSV */
  7875. #endif /* BSD44ORPOSIX */
  7876.     }
  7877.     debug(F101,"ttgspd code","",s);
  7878. #ifdef OLINUXHISPEED
  7879.     debug(F101,"ttgspd spd_flags","",spd_flags);
  7880. #endif /* OLINUXHISPEED */
  7881.     switch (s) {
  7882. #ifdef B0
  7883.       case B0:    ss = 0L; break;
  7884. #endif /* B0 */
  7885.  
  7886. #ifndef MINIX
  7887. /*
  7888.  MINIX defines the Bxx symbols to be bps/100, so B50==B75, B110==B134==B150,
  7889.  etc, making for many "duplicate case in switch" errors, which are fatal.
  7890. */
  7891. #ifdef B50
  7892.       case B50:   ss = 50L; break;
  7893. #endif /* B50 */
  7894. #ifdef B75
  7895.       case B75:   ss = 75L; break;
  7896. #endif /* B75 */
  7897. #endif /* MINIX */
  7898.  
  7899. #ifdef B110
  7900.       case B110:  ss = 110L; break;
  7901. #endif /* B110 */
  7902.  
  7903. #ifndef MINIX
  7904. #ifdef B134
  7905.       case B134:  ss = 134L; break;
  7906. #endif /* B134 */
  7907. #ifdef B150
  7908.       case B150:  ss = 150L; break;
  7909. #endif /* B150 */
  7910. #endif /* MINIX */
  7911.  
  7912. #ifdef B200
  7913.       case B200:  ss = 200L; break;
  7914. #endif /* B200 */
  7915.  
  7916. #ifdef B300
  7917.       case B300:  ss = 300L; break;
  7918. #endif /* B300 */
  7919.  
  7920. #ifdef B600
  7921.       case B600:  ss = 600L; break;
  7922. #endif /* B600 */
  7923.  
  7924. #ifdef B1200
  7925.       case B1200: ss = 1200L; break;
  7926. #endif /* B1200 */
  7927.  
  7928. #ifdef B1800
  7929.       case B1800: ss = 1800L; break;
  7930. #endif /* B1800 */
  7931.  
  7932. #ifdef B2400
  7933.       case B2400: ss = 2400L; break;
  7934. #endif /* B2400 */
  7935.  
  7936. #ifdef B4800
  7937.       case B4800: ss = 4800L; break;
  7938. #endif /* B4800 */
  7939.  
  7940. #ifdef B7200
  7941.       case B7200: ss = 7200L; break;
  7942. #endif /* B7200 */
  7943.  
  7944. #ifdef B9600
  7945.       case B9600: ss = 9600L; break;
  7946. #endif /* B9600 */
  7947.  
  7948. #ifdef B19200
  7949.       case B19200: ss = 19200L; break;
  7950. #else
  7951. #ifdef EXTA
  7952.       case EXTA: ss = 19200L; break;
  7953. #endif /* EXTA */
  7954. #endif /* B19200 */
  7955.  
  7956. #ifdef MINIX2
  7957. /* End of hack to make MINIX2 use MINIX1 speed setting */
  7958. #undef MINIX
  7959. #endif /* MINIX2 */
  7960.  
  7961. #ifndef MINIX
  7962. #ifdef B38400
  7963.       case B38400:
  7964.         ss = 38400L;
  7965. #ifdef OLINUXHISPEED
  7966.         switch(spd_flags) {
  7967.           case ASYNC_SPD_HI:  ss =  57600L; break;
  7968.           case ASYNC_SPD_VHI: ss = 115200L; break;
  7969.     }
  7970. #endif /* OLINUXHISPEED */
  7971.         break;
  7972. #else
  7973. #ifdef EXTB
  7974.       case EXTB: ss = 38400L; break;
  7975. #endif /* EXTB */
  7976. #endif /* B38400 */
  7977. #endif /* MINIX */
  7978.  
  7979. #ifdef HPUX
  7980. #ifdef _B57600
  7981.       case _B57600: ss = 57600L; break;
  7982. #endif /* _B57600 */
  7983. #ifdef _B115200
  7984.       case _B115200: ss = 115200L; break;
  7985. #endif /* _B115200 */
  7986. #else
  7987. #ifdef B57600
  7988.       case B57600: ss = 57600L; break;
  7989. #endif /* B57600 */
  7990. #ifdef B76800
  7991.       case B76800: ss = 76800L; break;
  7992. #endif /* B76800 */
  7993. #ifdef B115200
  7994.       case B115200: ss = 115200L; break;
  7995. #endif /* B115200 */
  7996. #ifdef B153600
  7997.       case B153600: ss = 153600L; break;
  7998. #endif /* B153600 */
  7999. #ifdef B230400
  8000.       case B230400: ss = 230400L; break;
  8001. #endif /* B230400 */
  8002. #ifdef B307200
  8003.       case B307200: ss = 307200L; break;
  8004. #endif /* B307200 */
  8005. #ifdef B460800
  8006.       case B460800: ss = 460800L; break;
  8007. #endif /* B460800 */
  8008. #endif /* HPUX */
  8009. #ifdef B921600
  8010.       case 92160: ss = 921600L; break;
  8011. #endif /* B921600 */
  8012.       default:
  8013.     ss = -1; break;
  8014.     }
  8015. #endif /* Plan9 */
  8016.     debug(F101,"ttgspd speed","",ss);
  8017.     return(ss);
  8018.  
  8019. #endif /* USETCSETSPEED */
  8020. #endif /* NOLOCAL */
  8021. }
  8022. #ifdef MINIX2                /* Another hack alert */
  8023. #define MINIX
  8024. #endif /* MINIX2 */
  8025.  
  8026. /*
  8027.   FIONREAD data type...  This has been defined as "long" for many, many
  8028.   years, and it worked OK until 64-bit platforms appeared.  Thus we use
  8029.   int for 64-bit platforms, but keep long for the others.  If we changed
  8030.   the default PEEKTYPE to int, this would probably break 16-bit builds
  8031.   (note that sizeof(long) == sizeof(int) on most 32-bit platforms), many
  8032.   of which we have no way of testing any more.  Therefore, do not change
  8033.   the default definition of PEEKTYPE -- only add exceptions to it as needed.
  8034. */
  8035. #ifdef COHERENT
  8036. #ifdef FIONREAD
  8037. #undef FIONREAD
  8038. #endif /* FIONREAD */
  8039. /* #define FIONREAD TIOCQUERY */
  8040. /* #define PEEKTYPE int */
  8041. #else  /* Not COHERENT... */
  8042.  
  8043. #ifdef OSF32                /* Digital UNIX 3.2 or higher */
  8044. #define PEEKTYPE int
  8045. #else
  8046. #define PEEKTYPE long            /* Elsewhere (see notes above) */
  8047. #endif /* OSF32 */
  8048. #endif /* COHERENT */
  8049.  
  8050. /* ckumyr.c by Kristoffer Eriksson, ske@pkmab.se, 15 Mar 1990. */
  8051.  
  8052. #ifdef MYREAD
  8053.  
  8054. /* Private buffer for myread() and its companions.  Not for use by anything
  8055.  * else.  ttflui() is allowed to reset them to initial values.  ttchk() is
  8056.  * allowed to read my_count.
  8057.  *
  8058.  * my_item is an index into mybuf[].  Increment it *before* reading mybuf[].
  8059.  *
  8060.  * A global parity mask variable could be useful too.  We could use it to
  8061.  * let myread() strip the parity on its own, instead of stripping sign
  8062.  * bits as it does now.
  8063.  */
  8064. #ifdef BIGBUFOK
  8065. #define MYBUFLEN 32768
  8066. #else
  8067. #ifdef pdp11
  8068. #define MYBUFLEN 256
  8069. #else
  8070. #define MYBUFLEN 1024
  8071. #endif /* pdp11 */
  8072. #endif /* BIGBUFOK */
  8073.  
  8074. #ifdef ANYX25
  8075. #undef MYBUFLEN
  8076. #define MYBUFLEN 256
  8077. /*
  8078.   On X.25 connections, there is an extra control byte at the beginning.
  8079. */
  8080. static CHAR x25buf[MYBUFLEN+1];        /* Communication device input buffer */
  8081. static CHAR  *mybuf = x25buf+1;
  8082. #else
  8083. static CHAR mybuf[MYBUFLEN];
  8084. #endif /* ANYX25 */
  8085.  
  8086. static int my_count = 0;        /* Number of chars still in mybuf */
  8087. static int my_item = -1;        /* Last index read from mybuf[]   */
  8088.  
  8089. /*  T T P E E K  --  Peek into our internal communications input buffers. */
  8090.  
  8091. /*
  8092.   NOTE: This routine is peculiar to UNIX, and is used only by the
  8093.   select()-based CONNECT module, ckucns.c.  It need not be replicated in
  8094.   the ck?tio.c of other platforms.
  8095. */
  8096. int
  8097. ttpeek() {
  8098. #ifdef TTLEBUF
  8099.     int rc = 0;
  8100.     if (ttpush >= 0)
  8101.       rc++;
  8102.     rc += le_inbuf();
  8103.     if (rc > 0)
  8104.       return(rc);
  8105.     else
  8106. #endif /* TTLEBUF */
  8107.  
  8108. #ifdef MYREAD
  8109.     return(my_count);
  8110. #else
  8111.     return(0);
  8112. #endif /* MYREAD */
  8113. }
  8114.  
  8115. /* myread() -- Efficient read of one character from communications line.
  8116.  *
  8117.  * Uses a private buffer to minimize the number of expensive read() system
  8118.  * calls.  Essentially performs the equivalent of read() of 1 character, which
  8119.  * is then returned.  By reading all available input from the system buffers
  8120.  * to the private buffer in one chunk, and then working from this buffer, the
  8121.  * number of system calls is reduced in any case where more than one character
  8122.  * arrives during the processing of the previous chunk, for instance high
  8123.  * baud rates or network type connections where input arrives in packets.
  8124.  * If the time needed for a read() system call approaches the time for more
  8125.  * than one character to arrive, then this mechanism automatically compensates
  8126.  * for that by performing bigger read()s less frequently.  If the system load
  8127.  * is high, the same mechanism compensates for that too.
  8128.  *
  8129.  * myread() is a macro that returns the next character from the buffer.  If the
  8130.  * buffer is empty, mygetbuf() is called.  See mygetbuf() for possible error
  8131.  * returns.
  8132.  *
  8133.  * This should be efficient enough for any one-character-at-a-time loops.
  8134.  * For even better efficiency you might use memcpy()/bcopy() or such between
  8135.  * buffers (since they are often better optimized for copying), but it may not
  8136.  * be worth it if you have to take an extra pass over the buffer to strip
  8137.  * parity and check for CTRL-C anyway.
  8138.  *
  8139.  * Note that if you have been using myread() from another program module, you
  8140.  * may have some trouble accessing this macro version and the private variables
  8141.  * it uses.  In that case, just add a function in this module, that invokes the
  8142.  * macro.
  8143.  */
  8144. #define myread() (--my_count < 0 ? mygetbuf() : 255 & (int)mybuf[++my_item])
  8145.  
  8146. /* Specification: Push back up to one character onto myread()'s queue.
  8147.  *
  8148.  * This implementation: Push back characters into mybuf. At least one character
  8149.  * must have been read through myread() before myunrd() may be used.  After
  8150.  * EOF or read error, again, myunrd() can not be used.  Sometimes more than
  8151.  * one character can be pushed back, but only one character is guaranteed.
  8152.  * Since a previous myread() must have read its character out of mybuf[],
  8153.  * that guarantees that there is space for at least one character.  If push
  8154.  * back was really needed after EOF, a small addition could provide that.
  8155.  *
  8156.  * myunrd() is currently not called from anywhere inside kermit...
  8157.  */
  8158. #ifdef COMMENT /* not used */
  8159. myunrd(ch) CHAR ch; {
  8160.     if (my_item >= 0) {
  8161.     mybuf[my_item--] = ch;
  8162.     ++my_count;
  8163.     }
  8164. }
  8165. #endif /* COMMENT */
  8166.  
  8167. /*  T T P U S H B A C K  --  Put n bytes back into the myread buffer */
  8168.  
  8169. static CHAR * pushbuf = NULL;
  8170. /* static int pushed = 0; */
  8171.  
  8172. int
  8173. ttpushback(s,n) CHAR * s; int n; {
  8174.     debug(F101,"ttpushback n","",n);
  8175.     if (pushbuf || n > MYBUFLEN || n < 1)
  8176.       return(-1);
  8177.     debug(F101,"ttpushback my_count","",my_count);
  8178.     if (my_count > 0) {
  8179.     if (!(pushbuf = (CHAR *)malloc(n+1)))
  8180.       return(-1);
  8181.     memcpy(pushbuf,mybuf,my_count);
  8182.     /* pushed = my_count; */ /* (set but never used) */
  8183.     }
  8184.     memcpy(mybuf,s,n);
  8185.     my_count = n;
  8186.     my_item = -1;
  8187.     return(0);
  8188. }
  8189.  
  8190. /* mygetbuf() -- Fill buffer for myread() and return first character.
  8191.  *
  8192.  * This function is what myread() uses when it can't get the next character
  8193.  * directly from its buffer.  First, it calls a system dependent myfillbuf()
  8194.  * to read at least one new character into the buffer, and then it returns
  8195.  * the first character just as myread() would have done.  This function also
  8196.  * is responsible for all error conditions that myread() can indicate.
  8197.  *
  8198.  * Returns: When OK    => a positive character, 0 or greater.
  8199.  *        When EOF    => -2.
  8200.  *        When error    => -3, error code in errno.
  8201.  *
  8202.  * Older myread()s additionally returned -1 to indicate that there was nothing
  8203.  * to read, upon which the caller would call myread() again until it got
  8204.  * something.  The new myread()/mygetbuf() always gets something.  If it
  8205.  * doesn't, then make it do so!  Any program that actually depends on the old
  8206.  * behaviour will break.
  8207.  *
  8208.  * The older version also used to return -2 both for EOF and other errors,
  8209.  * and used to set errno to 9999 on EOF.  The errno stuff is gone, EOF and
  8210.  * other errors now return different results, although Kermit currently never
  8211.  * checks to see which it was.  It just disconnects in both cases.
  8212.  *
  8213.  * Kermit lets the user use the quit key to perform some special commands
  8214.  * during file transfer.  This causes read(), and thus also mygetbuf(), to
  8215.  * finish without reading anything and return the EINTR error.  This should
  8216.  * be checked by the caller.  Mygetbuf() could retry the read() on EINTR,
  8217.  * but if there is nothing to read, this could delay Kermit's reaction to
  8218.  * the command, and make Kermit appear unresponsive.
  8219.  *
  8220.  * The debug() call should be removed for optimum performance.
  8221.  */
  8222. int
  8223. mygetbuf() {
  8224.     int x;
  8225.     errno = 0;
  8226. #ifdef DEBUG
  8227.     if (deblog && my_count > 0)
  8228.       debug(F101,"mygetbuf IMPROPERLY CALLED with my_count","",my_count);
  8229. #endif /* DEBUG */
  8230.     if (my_count <= 0)
  8231.       my_count = myfillbuf();
  8232.  
  8233. #ifdef DEBUG
  8234. #ifdef COMMENT
  8235.     if (deblog) debug(F101, "mygetbuf read", "", my_count);
  8236. #else /* COMMENT */
  8237.     if (deblog) hexdump("mygetbuf read", mybuf, my_count);
  8238. #endif /* COMMENT */
  8239. #endif /* DEBUG */
  8240.     x = my_count;
  8241.     if (my_count <= 0) {
  8242.     my_count = 0;
  8243.     my_item = -1;
  8244.     debug(F101,"mygetbuf errno","",errno);
  8245. #ifdef TCPSOCKET
  8246.     if (netconn && ttnet == NET_TCPB && errno != 0) {
  8247.         if (errno != EINTR) {
  8248.         debug(F101,"mygetbuf TCP error","",errno);
  8249.         ttclos(0);        /* Close the connection. */
  8250.         }
  8251.         return(-3);
  8252.     }
  8253. #endif /* TCPSOCKET */
  8254.     if (!netconn && xlocal && errno) {
  8255.         if (errno != EINTR) {
  8256.         debug(F101,"mygetbuf SERIAL error","",errno);
  8257.         x = -3;
  8258.         ttclos(0);        /* Close the connection. */
  8259.         }
  8260.     }
  8261.     return((x < 0) ? -3 : -2);
  8262.     }
  8263.     --my_count;
  8264.     return((unsigned)(0xff & mybuf[my_item = 0]));
  8265. }
  8266.  
  8267. /* myfillbuf():
  8268.  * System-dependent read() into mybuf[], as many characters as possible.
  8269.  *
  8270.  * Returns: OK => number of characters read, always more than zero.
  8271.  *          EOF => 0
  8272.  *          Error => -1, error code in errno.
  8273.  *
  8274.  * If there is input available in the system's buffers, all of it should be
  8275.  * read into mybuf[] and the function return immediately.  If no input is
  8276.  * available, it should wait for a character to arrive, and return with that
  8277.  * one in mybuf[] as soon as possible.  It may wait somewhat past the first
  8278.  * character, but be aware that any such delay lengthens the packet turnaround
  8279.  * time during kermit file transfers.  Should never return with zero characters
  8280.  * unless EOF or irrecoverable read error.
  8281.  *
  8282.  * Correct functioning depends on the correct tty parameters being used.
  8283.  * Better control of current parameters is required than may have been the
  8284.  * case in older Kermit releases.  For instance, O_NDELAY (or equivalent) can
  8285.  * no longer be sometimes off and sometimes on like it used to, unless a
  8286.  * special myfillbuf() is written to handle that.  Otherwise the ordinary
  8287.  * myfillbuf()s may think they have come to EOF.
  8288.  *
  8289.  * If your system has a facility to directly perform the functioning of
  8290.  * myfillbuf(), then use it.  If the system can tell you how many characters
  8291.  * are available in its buffers, then read that amount (but not less than 1).
  8292.  * If the system can return a special indication when you try to read without
  8293.  * anything to read, while allowing you to read all there is when there is
  8294.  * something, you may loop until there is something to read, but probably that
  8295.  * is not good for the system load.
  8296.  */
  8297.  
  8298. #ifdef SVORPOSIX
  8299.     /* This is for System III/V with VMIN>0, VTIME=0 and O_NDELAY off,
  8300.      * and CLOCAL set any way you like.  This way, read() will do exactly
  8301.      * what is required by myfillbuf(): If there is data in the buffers
  8302.      * of the O.S., all available data is read into mybuf, up to the size
  8303.      * of mybuf.  If there is none, the first character to arrive is
  8304.      * awaited and returned.
  8305.      */
  8306. int
  8307. myfillbuf() {
  8308.     int fd, n;
  8309. #ifdef NETCMD
  8310.     if (ttpipe)
  8311.       fd = fdin;
  8312.     else
  8313. #endif /* NETCMD */
  8314.       fd = ttyfd;
  8315.  
  8316. #ifdef sxaE50
  8317.     /* From S. Dezawa at Fujifilm in Japan.  I don't know why this is */
  8318.     /* necessary for the sxa E50, but it is. */
  8319.     return read(fd, mybuf, 255);
  8320. #else
  8321. #ifdef BEOSORBEBOX
  8322.     while (1) {
  8323. #ifdef NETCONN
  8324.         if (netconn) {
  8325.             n = netxin(sizeof(mybuf), (char *)mybuf);
  8326.             debug(F101,"BEBOX SVORPOSIX network myfillbuf","",n);
  8327.     }
  8328.         else
  8329. #endif /* NETCONN */
  8330.       n = read(fd, mybuf, sizeof(mybuf));
  8331.     debug(F101,"BEBOX SVORPOSIX notnet myfillbuf","",n);
  8332.         if (n > 0)
  8333.       return(n);
  8334.         snooze(1000.0);
  8335.     }
  8336. #else /* BEOSORBEBOX */
  8337.     errno = 0;
  8338.     debug(F100,"SVORPOSIX myfillbuf calling read()","",0);
  8339. #ifdef IBMX25
  8340.     if (netconn && (nettype == NET_IX25)) {
  8341.     /* can't use sizeof because mybuf is a pointer, and not an array! */
  8342.     n = x25xin( MYBUFLEN, mybuf );
  8343.     } else
  8344. #endif /* IBMX25 */
  8345.  
  8346. #ifdef CK_SSL
  8347.       if (ssl_active_flag || tls_active_flag) {
  8348.       int error, n = 0;
  8349.       while (n == 0) {
  8350.           if (ssl_active_flag)
  8351.                 n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  8352.           else if (tls_active_flag)
  8353.                 n = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  8354.               else
  8355.         break;
  8356.           switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  8357.         case SSL_ERROR_NONE:
  8358.           if (n > 0)
  8359.                     return(n);
  8360.           if (n < 0)
  8361.                     return(-2);
  8362.           msleep(50);
  8363.           break;
  8364.         case SSL_ERROR_WANT_WRITE:
  8365.         case SSL_ERROR_WANT_READ:
  8366.           return(-1);
  8367.         case SSL_ERROR_SYSCALL:
  8368.           if (n != 0)
  8369.             return(-1);
  8370.         case SSL_ERROR_WANT_X509_LOOKUP:
  8371.         case SSL_ERROR_SSL:
  8372.         case SSL_ERROR_ZERO_RETURN:
  8373.         default:
  8374.           ttclos(0);
  8375.           return(-3);
  8376.             }
  8377.         }
  8378.     }
  8379. #endif /* CK_SSL */
  8380. #ifdef CK_KERBEROS
  8381. #ifdef KRB4
  8382. #ifdef RLOGCODE
  8383.     if (ttnproto == NP_EK4LOGIN) {
  8384.         if ((n = krb4_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8385.       return(-3);
  8386.         else
  8387.       return(n);
  8388.     }
  8389. #endif /* RLOGCODE */
  8390. #endif /* KRB4 */
  8391. #ifdef KRB5
  8392. #ifdef RLOGCODE
  8393.     if (ttnproto == NP_EK5LOGIN) {
  8394.         if ((n = krb5_des_read(ttyfd,mybuf,sizeof(mybuf),0)) < 0)
  8395.       return(-3);
  8396.         else
  8397.       return(n);
  8398.     }
  8399. #endif /* RLOGCODE */
  8400. #ifdef KRB5_U2U
  8401.     if (ttnproto == NP_K5U2U) {
  8402.         if ((n = krb5_u2u_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8403.       return(-3);
  8404.         else
  8405.       return(n);
  8406.     }
  8407. #endif /* KRB5_U2U */
  8408. #endif /* KRB5 */
  8409. #endif /* CK_KERBEROS */
  8410.  
  8411. #ifdef NETPTY
  8412. #ifdef HAVE_PTYTRAP
  8413.     /* Special handling for HP-UX pty i/o */
  8414.   ptyread:
  8415.     if (ttpty && pty_trap_pending(ttyfd) > 0) {
  8416.         if (pty_trap_handler(ttyfd) > 0) {
  8417.             ttclos(0);
  8418.             return(-3);
  8419.         }
  8420.     }
  8421. #endif /* HAVE_PTYTRAP */
  8422. #endif /* NETPTY */
  8423.     n = read(fd, mybuf, sizeof(mybuf));
  8424.     debug(F101,"SVORPOSIX myfillbuf","",n);
  8425.     debug(F101,"SVORPOSIX myfillbuf ttcarr","",ttcarr);
  8426.     debug(F101,"SVORPOSIX myfillbuf errno","",errno);
  8427.     if (n < 1) {
  8428. #ifdef NETPTY
  8429. #ifdef HAVE_PTYTRAP
  8430.         /* When we have a PTY trap in place the connection cannot */
  8431.         /* be closed until the trap receives a close indication.  */
  8432.         if (n == 0 && ttpty)
  8433.             goto ptyread;
  8434. #endif /* HAVE_PTYTRAP */
  8435. #endif /* NETPTY */
  8436.         return(-3);
  8437.     }
  8438.     return(n);
  8439. #endif /* BEOSORBEBOX */
  8440. #endif /* sxaE50 */
  8441. }
  8442.  
  8443. #else /* not AT&T or POSIX */
  8444.  
  8445. #ifdef aegis
  8446.     /* This is quoted from the old myread().  The semantics seem to be
  8447.      * alright, but maybe errno would not need to be set even when
  8448.      * there is no error?  I don't know aegis.
  8449.      */
  8450. int
  8451. myfillbuf() {
  8452.     int count;
  8453. #ifdef NETCMD
  8454.     if (ttpipe)
  8455.       fd = fdin;
  8456.     else
  8457. #endif /* NETCMD */
  8458.       fd = ttyfd;
  8459.  
  8460.     count = ios_$get((short)fd, ios_$cond_opt, mybuf, 256L, st);
  8461.     errno = EIO;
  8462.     if (st.all == ios_$get_conditional_failed) /* get at least one */
  8463.       count = ios_$get((short)fd, 0, mybuf, 1L, st);
  8464.     if (st.all == ios_$end_of_file)
  8465.       return(-3);
  8466.     else if (st.all != status_$ok) {
  8467.     errno = EIO;
  8468.     return(-1);
  8469.     }
  8470.     return(count > 0 ? count : -3);
  8471. }
  8472. #else /* !aegis */
  8473.  
  8474. #ifdef FIONREAD
  8475.     /* This is for systems with FIONREAD.  FIONREAD returns the number
  8476.      * of characters available for reading. If none are available, wait
  8477.      * until something arrives, otherwise return all there is.
  8478.      */
  8479. int
  8480. myfillbuf() {
  8481.     PEEKTYPE avail = 0;
  8482.     int x, fd;
  8483. #ifdef NETCMD
  8484.     if (ttpipe)
  8485.       fd = fdin;
  8486.     else
  8487. #endif /* NETCMD */
  8488.       fd = ttyfd;
  8489.  
  8490. #ifdef SUNX25
  8491. /*
  8492.   SunLink X.25 support in this routine from Stefaan A. Eeckels, Eurostat (CEC).
  8493.   Depends on SunOS having FIONREAD, not because we use it, but just so this
  8494.   code is grouped correctly within the #ifdefs.  Let's hope Solaris keeps it.
  8495.  
  8496.   We call x25xin() instead of read() so that Q-Bit packets, which contain
  8497.   X.25 service-level information (e.g. PAD parameter changes), can be processed
  8498.   transparently to the upper-level code.  This is a blocking read, and so
  8499.   we depend on higher-level code (such as ttinc()) to set any necessary alarms.
  8500. */
  8501.     extern int nettype;
  8502.     if (netconn && nettype == NET_SX25) {
  8503.     while ((x = x25xin(sizeof(x25buf), x25buf)) < 1) ;
  8504.     return(x - 1);            /* "-1" compensates for extra status byte */
  8505.     }
  8506. #endif /* SUNX25 */
  8507.  
  8508. #ifdef CK_SSL
  8509.     if (ssl_active_flag || tls_active_flag) {
  8510.         int error, n = 0;
  8511.         while (n == 0) {
  8512.             if (ssl_active_flag)
  8513.           n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  8514.             else
  8515.           n = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  8516.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  8517.           case SSL_ERROR_NONE:
  8518.                 if (n > 0)
  8519.           return(n);
  8520.                 if (n < 0)
  8521.           return(-2);
  8522.                 msleep(50);
  8523.                 break;
  8524.           case SSL_ERROR_WANT_WRITE:
  8525.           case SSL_ERROR_WANT_READ:
  8526.                 return(-1);
  8527.           case SSL_ERROR_SYSCALL:
  8528.         if (n != 0)
  8529.           return(-1);
  8530.           case SSL_ERROR_WANT_X509_LOOKUP:
  8531.           case SSL_ERROR_SSL:
  8532.           case SSL_ERROR_ZERO_RETURN:
  8533.           default:
  8534.                 ttclos(0);
  8535.                 return(-2);
  8536.             }
  8537.         }
  8538.     }
  8539. #endif /* CK_SSL */
  8540. #ifdef CK_KERBEROS
  8541. #ifdef KRB4
  8542. #ifdef RLOGCODE
  8543.     if (ttnproto == NP_EK4LOGIN) {
  8544.         if ((x = krb4_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8545.       return(-1);
  8546.         else
  8547.       return(x);
  8548.     }
  8549. #endif /* RLOGCODE */
  8550. #endif /* KRB4 */
  8551. #ifdef KRB5
  8552. #ifdef RLOGCODE
  8553.     if (ttnproto == NP_EK5LOGIN) {
  8554.         if ((x = krb5_des_read(ttyfd,mybuf,sizeof(mybuf),0)) < 0)
  8555.       return(-1);
  8556.         else
  8557.       return(x);
  8558.     }
  8559. #endif /* RLOGCODE */
  8560. #ifdef KRB5_U2U
  8561.     if (ttnproto == NP_K5U2U) {
  8562.         if ((x = krb5_u2u_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8563.       return(-1);
  8564.         else
  8565.       return(x);
  8566.     }
  8567. #endif /* KRB5_U2U */
  8568. #endif /* KRB5 */
  8569. #endif /* CK_KERBEROS */
  8570.  
  8571.     errno = 0;
  8572.     debug(F101,"myfillbuf calling FIONREAD ioctl","",xlocal);
  8573.     x = ioctl(fd, FIONREAD, &avail);
  8574. #ifdef DEBUG
  8575.     if (deblog) {
  8576.     debug(F101,"myfillbuf FIONREAD","",x);
  8577.     debug(F101,"myfillbuf FIONREAD avail","",avail);
  8578.     debug(F101,"myfillbuf FIONREAD errno","",errno);
  8579.     }
  8580. #endif /* DEBUG */
  8581.     if (x < 0 || avail == 0)
  8582.       avail = 1;
  8583.  
  8584.     if (avail > MYBUFLEN)
  8585.       avail = MYBUFLEN;
  8586.  
  8587.     errno = 0;
  8588.  
  8589.     x = read(fd, mybuf, (int) avail);
  8590. #ifdef DEBUG
  8591.     if (deblog) {
  8592.     debug(F101,"myfillbuf avail","",avail);
  8593.     debug(F101,"myfillbuf read","",x);
  8594.     debug(F101,"myfillbuf read errno","",errno);
  8595.         if (x > 0)
  8596.       hexdump("myfillbuf mybuf",mybuf,x);
  8597.     }
  8598. #endif /* DEBUG */
  8599.     if (x < 1) x = -3;            /* read 0 == connection loss */
  8600.     return(x);
  8601. }
  8602.  
  8603. #else /* !FIONREAD */
  8604. /* Add other systems here, between #ifdef and #else, e.g. NETCONN. */
  8605. /* When there is no other possibility, read 1 character at a time. */
  8606. int
  8607. myfillbuf() {
  8608.     int x;
  8609.  
  8610. #ifdef CK_SSL
  8611.     if (ssl_active_flag || tls_active_flag) {
  8612.         int error, n = 0;
  8613.         while (n == 0) {
  8614.             if (ssl_active_flag)
  8615.           n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  8616.             else
  8617.           count = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  8618.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  8619.           case SSL_ERROR_NONE:
  8620.                 if (n > 0)
  8621.           return(n);
  8622.                 if (n < 0)
  8623.           return(-2);
  8624.                 msleep(50);
  8625.                 break;
  8626.           case SSL_ERROR_WANT_WRITE:
  8627.           case SSL_ERROR_WANT_READ:
  8628.                 return(-1);
  8629.           case SSL_ERROR_SYSCALL:
  8630.         if (n != 0)
  8631.           return(-1);
  8632.           case SSL_ERROR_WANT_X509_LOOKUP:
  8633.           case SSL_ERROR_SSL:
  8634.           case SSL_ERROR_ZERO_RETURN:
  8635.           default:
  8636.                 ttclos(0);
  8637.                 return(-2);
  8638.             }
  8639.         }
  8640.     }
  8641. #endif /* CK_SSL */
  8642. #ifdef CK_KERBEROS
  8643. #ifdef KRB4
  8644. #ifdef RLOGCODE
  8645.     if (ttnproto == NP_EK4LOGIN) {
  8646.         if ((len = krb4_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8647.       return(-1);
  8648.         else
  8649.       return(len);
  8650.     }
  8651. #endif /* RLOGCODE */
  8652. #endif /* KRB4 */
  8653. #ifdef KRB5
  8654. #ifdef RLOGCODE
  8655.     if (ttnproto == NP_EK5LOGIN) {
  8656.         if ((len = krb5_des_read(ttyfd,mybuf,sizeof(mybuf),0)) < 0)
  8657.       return(-1);
  8658.         else
  8659.       return(len);
  8660.     }
  8661. #endif /* RLOGCODE */
  8662. #ifdef KRB5_U2U
  8663.     if (ttnproto == NP_K5U2U) {
  8664.         if ((len = krb5_u2u_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8665.       return(-1);
  8666.         else
  8667.       return(len);
  8668.     }
  8669. #endif /* KRB5_U2U */
  8670. #endif /* KRB5 */
  8671. #endif /* CK_KERBEROS */
  8672.  
  8673. #ifdef NETCMD
  8674.     if (ttpipe)
  8675.       fd = fdin;
  8676.     else
  8677. #endif /* NETCMD */
  8678.       fd = ttyfd;
  8679.     x = read(fd, mybuf, 1);
  8680.     return(x > 0 ? x : -3);
  8681. }
  8682.  
  8683. #endif /* !FIONREAD */
  8684. #endif /* !aegis */
  8685. #endif /* !ATTSV */
  8686.  
  8687. #endif /* MYREAD */
  8688.  
  8689. #ifdef MINIX2
  8690. #undef MINIX
  8691. #endif /* MINIX2 */
  8692.  
  8693. /*  T T _ T N O P T  --  Handle Telnet negotions in incoming data */
  8694. /*
  8695.   Call with the IAC that was encountered.
  8696.   Returns:
  8697.    -3: If connection has dropped or gone bad.
  8698.    -2: On Telnet protocol error resulting in inconsistent states.
  8699.     0: If negotiation OK and caller has nothing to do.
  8700.     1: If packet start character has changed (new value is in global stchr).
  8701.   255: If there was a quoted IAC as data.
  8702.    or: Not at all if we got a legitimate Telnet Logout request.
  8703. */
  8704. #ifdef TCPSOCKET
  8705. static int
  8706. tt_tnopt(n) int n; {            /* Handle Telnet options */
  8707.     /* In case caller did not already check these conditions...  */
  8708.     if (n == IAC &&
  8709.     ((xlocal && netconn && IS_TELNET()) ||
  8710.      (!xlocal && sstelnet))) {
  8711.     extern int duplex;
  8712.     extern int server;
  8713.     int tx = 0;
  8714.     debug(F100,"ttinl calling tn_doop()","",0);
  8715.     tx = tn_doop((CHAR)(n & 0xff),duplex,ttinc);
  8716.     debug(F111,"ttinl tn_doop() returned","tx",tx);
  8717.     switch (tx) {
  8718.       case 0:
  8719.         return(0);
  8720.       case -1:            /* I/O error */
  8721.         ttimoff();            /* Turn off timer */
  8722.         return(-3);
  8723.           case -2:            /* Connection failed. */
  8724.           case -3:
  8725.         ttimoff();            /* Turn off timer */
  8726.         ttclos(0);
  8727.         return(-3);
  8728.       case 1:            /* ECHO change */
  8729.         duplex = 1;
  8730.         return(0);
  8731.       case 2:            /* ECHO change */
  8732.         duplex = 0;
  8733.         return(0);
  8734.       case 3:            /* Quoted IAC */
  8735.         n = 255;
  8736.         return((unsigned)255);
  8737. #ifdef IKS_OPTION
  8738.       case 4: {
  8739.           if (TELOPT_SB(TELOPT_KERMIT).kermit.u_start && server
  8740. #ifdef IKSD
  8741.           && !inserver
  8742. #endif /* IKSD */
  8743.           ) {            /* Remote in Server mode */
  8744.           ttimoff();        /* Turn off timer */
  8745.           debug(F100,"u_start and !inserver","",0);
  8746.           return(-2);        /* End server mode */
  8747.           } else if (!TELOPT_SB(TELOPT_KERMIT).kermit.me_start &&
  8748.              server
  8749.              ) {        /* I'm no longer in Server Mode */
  8750.           debug(F100,"me_start and server","",0);
  8751.           ttimoff();
  8752.           return(-2);
  8753.           }
  8754.           return(0);
  8755.       }
  8756.       case 5: {            /* Start character change */
  8757.           /* extern CHAR stchr; */
  8758.           /* start = stchr; */
  8759.           return(1);
  8760.       }
  8761. #endif /* IKS_OPTION */
  8762.       case 6:            /* Remote Logout */
  8763.         ttimoff();
  8764.         ttclos(0);
  8765. #ifdef IKSD
  8766.         if (inserver && !local)
  8767.           doexit(GOOD_EXIT,0);
  8768.         else
  8769. #endif /* IKSD */
  8770.           return(-2);
  8771.       default:
  8772.         return(0);
  8773.     }
  8774.     } else
  8775.       return(0);
  8776. }
  8777. #endif /* TCPSOCKET */
  8778.  
  8779. /*  T T F L U I  --  Flush tty input buffer */
  8780.  
  8781. void
  8782. ttflux() {                /* But first... */
  8783. #ifdef MYREAD
  8784. /*
  8785.   Flush internal MYREAD buffer.
  8786. */
  8787. #ifdef TCPSOCKET
  8788.     int dotnopts, x;
  8789.     dotnopts = (((xlocal && netconn && IS_TELNET()) ||
  8790.          (!xlocal && sstelnet)));
  8791. #endif /* TCPSOCKET */
  8792.     debug(F101,"ttflux my_count","",my_count);
  8793. #ifdef TCPSOCKET
  8794.     if (dotnopts) {
  8795.     CHAR ch = '\0';
  8796.         while (my_count > 0) {
  8797.         ch = myread();
  8798. #ifdef CK_ENCRYPTION
  8799.             if (TELOPT_U(TELOPT_ENCRYPTION))
  8800.           ck_tn_decrypt(&ch,1);
  8801. #endif /* CK_ENCRYPTION */
  8802.             if (ch == IAC)
  8803.           x = tt_tnopt(ch);
  8804.         }
  8805.     } else
  8806. #endif /* TCPSOCKET */
  8807. #ifdef COMMENT
  8808. #ifdef CK_ENCRYPTION
  8809.     if (TELOPT_U(TELOPT_ENCRYPTION) && my_count > 0)
  8810.       ck_tn_decrypt(&mybuf[my_item+1],my_count);
  8811. #endif /* CK_ENCRYPTION */
  8812. #endif /* COMMENT */
  8813.     my_count = 0;            /* Reset count to zero */
  8814.     my_item = -1;            /* And buffer index to -1 */
  8815. #endif /* MYREAD */
  8816. }
  8817.  
  8818. int
  8819. ttflui() {
  8820.     int n, fd;
  8821. #ifdef TCPSOCKET
  8822.     int dotnopts;
  8823.     dotnopts = (((xlocal && netconn && IS_TELNET()) ||
  8824.          (!xlocal && sstelnet)));
  8825. #endif /* TCPSOCKET */
  8826.  
  8827. #ifdef NETCMD
  8828.     if (ttpipe)
  8829.       fd = fdin;
  8830.     else
  8831. #endif /* NETCMD */
  8832.       fd = ttyfd;
  8833.  
  8834. #ifdef TTLEBUF
  8835.     ttpush = -1;            /* Clear the peek-ahead char */
  8836.     while (le_data && (le_inbuf() > 0)) {
  8837.         CHAR ch = '\0';
  8838.         if (le_getchar(&ch) > 0) {    /* Clear any more... */
  8839.             debug(F101,"ttflui le_inbuf ch","",ch);
  8840.         }
  8841.     }
  8842. #endif /* TTLEBUF */
  8843.     debug(F101,"ttflui ttpipe","",ttpipe);
  8844.  
  8845. #ifdef MYREAD
  8846. /*
  8847.   Flush internal MYREAD buffer *NEXT*, in all cases.
  8848. */
  8849.     ttflux();
  8850. #endif /* MYREAD */
  8851.  
  8852. #ifdef NETCONN
  8853. /* Network flush is done specially, in the network support module. */
  8854.     if ((netconn || sstelnet) && !ttpipe && !ttpty) {
  8855.     debug(F100,"ttflui netflui","",0);
  8856. #ifdef COMMENT
  8857. #ifdef TN_COMPORT
  8858.     if (istncomport())
  8859.             tnc_send_purge_data(TNC_PURGE_RECEIVE);
  8860. #endif /* TN_COMPORT */
  8861. #endif /* COMMENT */
  8862.     return(netflui());
  8863.     }
  8864. #endif /* NETCONN */
  8865.  
  8866.     debug(F101,"ttflui ttyfd","",ttyfd); /* Not network */
  8867.     if (ttyfd < 0)
  8868.       return(-1);
  8869.  
  8870. #ifdef aegis
  8871.     sio_$control((short)yfd, sio_$flush_in, true, st);
  8872.     if (st.all != status_$ok) {
  8873.     fprintf(stderr, "flush failed: "); error_$print(st);
  8874.     } else {      /* sometimes the flush doesn't work */
  8875.         for (;;) {
  8876.         char buf[256];
  8877.             /* eat all the characters that shouldn't be available */
  8878.             ios_$get((short)fd, ios_$cond_opt, buf, 256L, st); /* (void) */
  8879.             if (st.all == ios_$get_conditional_failed) break;
  8880.             fprintf(stderr, "flush failed(2): "); error_$print(st);
  8881.         }
  8882.     }
  8883. #else
  8884. #ifdef BSD44                /* 4.4 BSD */
  8885.     n = FREAD;                          /* Specify read queue */
  8886.     debug(F100,"ttflui BSD44","",0);
  8887.     ioctl(fd,TIOCFLUSH,&n);
  8888. #else
  8889. #ifdef Plan9
  8890. #undef POSIX                /* Uh oh... */
  8891. #endif /* Plan9 */
  8892. #ifdef POSIX                /* POSIX */
  8893.     debug(F100,"ttflui POSIX","",0);
  8894.     tcflush(fd,TCIFLUSH);
  8895. #else
  8896. #ifdef ATTSV                /* System V */
  8897. #ifndef VXVE
  8898.     debug(F100,"ttflui ATTSV","",0);
  8899.     ioctl(fd,TCFLSH,0);
  8900. #endif /* VXVE */
  8901. #else                    /* Not BSD44, POSIX, or Sys V */
  8902. #ifdef TIOCFLUSH            /* Those with TIOCFLUSH defined */
  8903. #ifdef ANYBSD                /* Berkeley */
  8904.     n = FREAD;                          /* Specify read queue */
  8905.     debug(F100,"ttflui TIOCFLUSH ANYBSD","",0);
  8906.     ioctl(fd,TIOCFLUSH,&n);
  8907. #else                    /* Others (V7, etc) */
  8908.     debug(F100,"ttflui TIOCFLUSH","",0);
  8909.     ioctl(fd,TIOCFLUSH,0);
  8910. #endif /* ANYBSD */
  8911. #else                    /* All others... */
  8912. /*
  8913.   No system call (that we know about) for input buffer flushing.
  8914.   So see how many there are and read them in a loop, using ttinc().
  8915.   ttinc() is buffered, so we're not getting charged with a system call
  8916.   per character, just a function call.
  8917. */
  8918.     if ((n = ttchk()) > 0) {
  8919.     debug(F101,"ttflui read loop","",n);
  8920.     while ((n--) && ttinc(0) > 0) ;
  8921.     }
  8922. #endif /* TIOCFLUSH */
  8923. #endif /* ATTSV */
  8924. #endif /* POSIX */
  8925. #ifdef Plan9
  8926. #define POSIX
  8927. #endif /* Plan9 */
  8928. #endif /* BSD44 */
  8929. #endif /* aegis */
  8930.     return(0);
  8931. }
  8932.  
  8933. int
  8934. ttfluo() {                /* Flush output buffer */
  8935.     int fd;
  8936. #ifdef NETCMD
  8937.     if (ttpipe)
  8938.       fd = fdout;
  8939.     else
  8940. #endif /* NETCMD */
  8941.       fd = ttyfd;
  8942.  
  8943. #ifdef Plan9
  8944.     return 0;
  8945. #else
  8946. #ifdef POSIX
  8947.     return(tcflush(fd,TCOFLUSH));
  8948. #else
  8949. #ifdef OXOS
  8950.     return(ioctl(fd,TCFLSH,1));
  8951. #else
  8952.     return(0);                /* All others, nothing */
  8953. #endif /* OXOS */
  8954. #endif /* POSIX */
  8955. #endif /* Plan9 */
  8956. }
  8957.  
  8958. /* Interrupt Functions */
  8959.  
  8960. /* Set up terminal interrupts on console terminal */
  8961.  
  8962. #ifndef FIONREAD            /* We don't need esctrp() */
  8963. #ifndef SELECT                /* if we have any of these... */
  8964. #ifndef CK_POLL
  8965. #ifndef RDCHK
  8966.  
  8967. #ifndef OXOS
  8968. #ifdef SVORPOSIX
  8969. SIGTYP
  8970. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  8971.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  8972.     conesc = 1;
  8973.     debug(F101,"esctrp caught SIGQUIT","",conesc);
  8974. }
  8975. #endif /* SVORPOSIX */
  8976. #endif /* OXOS */
  8977.  
  8978. #ifdef V7
  8979. #ifndef MINIX2
  8980. SIGTYP
  8981. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  8982.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  8983.     conesc = 1;
  8984.     debug(F101,"esctrp caught SIGQUIT","",conesc);
  8985. }
  8986. #endif /* MINIX2 */
  8987. #endif /* V7 */
  8988.  
  8989. #ifdef C70
  8990. SIGTYP
  8991. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  8992.     conesc = 1;
  8993.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  8994. }
  8995. #endif /* C70 */
  8996.  
  8997. #endif /* RDCHK */
  8998. #endif /* CK_POLL */
  8999. #endif /* SELECT */
  9000. #endif /* FIONREAD */
  9001.  
  9002. /*  C O N B G T  --  Background Test  */
  9003.  
  9004. static int jc = 0;            /* 0 = no job control */
  9005.  
  9006. /*
  9007.   Call with flag == 1 to prevent signal test, which can not be expected
  9008.   to work during file transfer, when SIGINT probably *is* set to SIG_IGN.
  9009.  
  9010.   Call with flag == 0 to use the signal test, but only if the process-group
  9011.   test fails, as it does on some UNIX systems, where getpgrp() is buggy,
  9012.   requires an argument when the man page says it doesn't, or vice versa.
  9013.  
  9014.   If flag == 0 and the process-group test fails, then we determine background
  9015.   status simply (but not necessarily reliably) from isatty().
  9016.  
  9017.   conbgt() sets the global backgrd = 1 if we appear to be in the background,
  9018.   and to 0 if we seem to be in the foreground.  conbgt() is highly prone to
  9019.   misbehavior.
  9020. */
  9021. VOID
  9022. conbgt(flag) int flag; {
  9023.     int x = -1,                /* process group or SIGINT test */
  9024.         y = 0;                /* isatty() test */
  9025. /*
  9026.   Check for background operation, even if not running on real tty, so that
  9027.   background flag can be set correctly.  If background status is detected,
  9028.   then Kermit will not issue its interactive prompt or most messages.
  9029.   If your prompt goes away, you can blame (and fix?) this function.
  9030. */
  9031.  
  9032. /* Use process-group test if possible. */
  9033.  
  9034. #ifdef POSIX                /* We can do it in POSIX */
  9035. #define PGROUP_T
  9036. #else
  9037. #ifdef BSD4                /* and in BSD 4.x. */
  9038. #define PGROUP_T
  9039. #else
  9040. #ifdef HPUXJOBCTL            /* and in most HP-UX's */
  9041. #define PGROUP_T
  9042. #else
  9043. #ifdef TIOCGPGRP            /* and anyplace that has this ioctl. */
  9044. #define PGROUP_T
  9045. #endif /* TIOCGPGRP */
  9046. #endif /* HPUXJOBCTL */
  9047. #endif /* BSD4 */
  9048. #endif /* POSIX */
  9049.  
  9050. #ifdef MIPS                /* Except if it doesn't work... */
  9051. #undef PGROUP_T
  9052. #endif /* MIPS */
  9053.  
  9054. #ifdef PGROUP_T
  9055. /*
  9056.   Semi-reliable process-group test.  Check whether this process's group is
  9057.   the same as the controlling terminal's process group.  This works if the
  9058.   getpgrp() call doesn't lie (as it does in the SUNOS System V environment).
  9059. */
  9060.     PID_T mypgrp = (PID_T)0;        /* Kermit's process group */
  9061.     PID_T ctpgrp = (PID_T)0;        /* The terminal's process group */
  9062. #ifndef _POSIX_SOURCE
  9063. /*
  9064.   The getpgrp() prototype is obtained from system header files for POSIX
  9065.   and Sys V R4 compilations.  Other systems, who knows.  Some complain about
  9066.   a duplicate declaration here, others don't, so it's safer to leave it in
  9067.   if we don't know for certain.
  9068. */
  9069. #ifndef SVR4
  9070. #ifndef PS2AIX10
  9071. #ifndef HPUX9
  9072.     extern PID_T getpgrp();
  9073. #endif /* HPUX9 */
  9074. #endif /* PS2AIX10 */
  9075. #endif /* SVR4 */
  9076. #endif /* _POSIX_SOURCE */
  9077.  
  9078. /* Get my process group. */
  9079.  
  9080. #ifdef SVR3 /* Maybe this should be ATTSV? */
  9081. /* This function is not described in SVID R2 */
  9082.     mypgrp = getpgrp();
  9083.     /* debug(F101,"ATTSV conbgt process group","",(int) mypgrp); */
  9084. #else
  9085. #ifdef POSIX
  9086.     mypgrp = getpgrp();
  9087.     /* debug(F101,"POSIX conbgt process group","",(int) mypgrp); */
  9088. #else
  9089. #ifdef OSFPC
  9090.     mypgrp = getpgrp();
  9091.     /* debug(F101,"OSF conbgt process group","",(int) mypgrp); */
  9092. #else
  9093. #ifdef QNX
  9094.     mypgrp = getpgrp();
  9095.     /* debug(F101,"QNX conbgt process group","",(int) mypgrp); */
  9096. #else
  9097. #ifdef OSF32                /* (was OSF40) */
  9098.     mypgrp = getpgrp();
  9099.     /* debug(F101,"Digital UNIX conbgt process group","",(int) mypgrp); */
  9100. #else /* BSD, V7, etc */
  9101. #ifdef MINIX2
  9102.     mypgrp = getpgrp();
  9103. #else
  9104.     mypgrp = getpgrp(0);
  9105. #endif /* MINIX2 */
  9106.     /* debug(F101,"BSD conbgt process group","",(int) mypgrp); */
  9107. #endif /* OSF32 */
  9108. #endif /* QNX */
  9109. #endif /* OSFPC */
  9110. #endif /* POSIX */
  9111. #endif /* SVR3 */
  9112.  
  9113. #ifdef MINIX2
  9114. #undef BSD44ORPOSIX
  9115. #endif /* MINIX2 */
  9116.  
  9117. /* Now get controlling tty's process group */
  9118. #ifdef BSD44ORPOSIX
  9119.     ctpgrp = tcgetpgrp(1);        /* The POSIX way */
  9120.     /* debug(F101,"POSIX conbgt terminal process group","",(int) ctpgrp); */
  9121. #else
  9122.     ioctl(1, TIOCGPGRP, &ctpgrp);    /* Or the BSD way */
  9123.    /* debug(F101,"non-POSIX conbgt terminal process group","",(int) ctpgrp); */
  9124. #endif /* BSD44ORPOSIX */
  9125.  
  9126. #ifdef MINIX2
  9127. #define BSD44ORPOSIX
  9128. #endif /* MINIX2 */
  9129.  
  9130.     if ((mypgrp > (PID_T) 0) && (ctpgrp > (PID_T) 0))
  9131.       x = (mypgrp == ctpgrp) ? 0 : 1;    /* If they differ, then background. */
  9132.     else x = -1;            /* If error, remember. */
  9133.     debug(F101,"conbgt process group test","",x);
  9134. #endif /* PGROUP_T */
  9135.  
  9136. /* Try to see if job control is available */
  9137.  
  9138. #ifdef NOJC                /* User override */
  9139.     jc = 0;                /* No job control allowed */
  9140.     debug(F111,"NOJC","jc",jc);
  9141. #else
  9142. #ifdef BSD44
  9143.     jc = 1;
  9144. #else
  9145. #ifdef SVR4ORPOSIX            /* POSIX actually tells us */
  9146.     debug(F100,"SVR4ORPOSIX jc test...","",0);
  9147. #ifdef _SC_JOB_CONTROL
  9148. #ifdef __bsdi__
  9149.     jc = 1;
  9150. #else
  9151. #ifdef __386BSD__
  9152.     jc = 1;
  9153. #else
  9154.     jc = sysconf(_SC_JOB_CONTROL);    /* Whatever system says */
  9155.     if (jc < 0) {
  9156.     debug(F101,"sysconf fails, jcshell","",jcshell);
  9157.     jc = (jchdlr == SIG_DFL) ? 1 : 0;
  9158.     } else
  9159.       debug(F111,"sysconf(_SC_JOB_CONTROL)","jc",jc);
  9160. #endif /* __386BSD__ */
  9161. #endif /* __bsdi__ */
  9162. #else
  9163. #ifdef _POSIX_JOB_CONTROL
  9164.     jc = 1;                /* By definition */
  9165.     debug(F111,"_POSIX_JOB_CONTROL is defined","jc",jc);
  9166. #else
  9167.     jc = 0;                /* Assume job control not allowed */
  9168.     debug(F111,"SVR4ORPOSIX _SC/POSIX_JOB_CONTROL not defined","jc",jc);
  9169. #endif /* _POSIX_JOB_CONTROL */
  9170. #endif /* _SC_JOB_CONTROL */
  9171. #else
  9172. #ifdef BSD4
  9173.     jc = 1;                /* Job control allowed */
  9174.     debug(F111,"BSD job control","jc",jc);
  9175. #else
  9176. #ifdef SVR3JC
  9177.     jc = 1;                /* JC allowed */
  9178.     debug(F111,"SVR3 job control","jc",jc);
  9179. #else
  9180. #ifdef OXOS
  9181.     jc = 1;                /* JC allowed */
  9182.     debug(F111,"X/OS job control","jc",jc);
  9183. #else
  9184. #ifdef HPUX9
  9185.     jc = 1;                /* JC allowed */
  9186.     debug(F111,"HP-UX 9.0 job control","jc",jc);
  9187. #else
  9188. #ifdef HPUX10
  9189.     jc = 1;                /* JC allowed */
  9190.     debug(F111,"HP-UX 10.0 job control","jc",jc);
  9191. #else
  9192.     jc = 0;                /* JC not allowed */
  9193.     debug(F111,"job control catch-all","jc",jc);
  9194. #endif /* HPUX10 */
  9195. #endif /* HPUX9 */
  9196. #endif /* OXOS */
  9197. #endif /* SVR3JC */
  9198. #endif /* BSD4 */
  9199. #endif /* SVR4ORPOSIX */
  9200. #endif /* BSD44 */
  9201. #endif /* NOJC */
  9202.     debug(F101,"conbgt jc","",jc);
  9203. #ifndef NOJC
  9204.     debug(F101,"conbgt jcshell","",jcshell);
  9205. /*
  9206.   At this point, if jc == 1 but jcshell == 0, it means that the OS supports
  9207.   job control, but the shell or other process we are running under does not
  9208.   (jcshell is set in sysinit()) and so if we suspend ourselves, nothing good
  9209.   will come of it.  So...
  9210. */
  9211.     if (jc < 0) jc = 0;
  9212.     if (jc > 0 && jcshell == 0) jc = 0;
  9213. #endif /* NOJC */
  9214.  
  9215. /*
  9216.   Another background test.
  9217.   Test if SIGINT (terminal interrupt) is set to SIG_IGN (ignore),
  9218.   which is done by the shell (sh) if the program is started with '&'.
  9219.   Unfortunately, this is NOT done by csh or ksh so watch out!
  9220.   Note, it's safe to set SIGINT to SIG_IGN here, because further down
  9221.   we always set it to something else.
  9222.   Note: as of 16 Jul 1999, we also skip this test if we set SIGINT to
  9223.   SIG_IGN ourselves.
  9224. */
  9225.     if (x < 0 && !flag && !sigint_ign) { /* Didn't get good results above... */
  9226.  
  9227.     SIGTYP (*osigint)();
  9228.  
  9229.     osigint = signal(SIGINT,SIG_IGN);    /* What is SIGINT set to? */
  9230.     sigint_ign = 1;
  9231.     x = (osigint == SIG_IGN) ? 1 : 0;    /* SIG_IGN? */
  9232.     debug(F101,"conbgt osigint","",osigint);
  9233.     debug(F101,"conbgt signal test","",x);
  9234.     }
  9235.  
  9236. /* Also check to see if we're running with redirected stdio. */
  9237. /* This is not really background operation, but we want to act as though */
  9238. /* it were. */
  9239.  
  9240. #ifdef IKSD
  9241.     if (inserver) {            /* Internet Kermit Server */
  9242.     backgrd = 0;            /* is not in the background */
  9243.     return;
  9244.     }
  9245. #endif /* IKSD */
  9246.  
  9247.     y = (isatty(0) && isatty(1)) ? 1 : 0;
  9248.     debug(F101,"conbgt isatty test","",y);
  9249.  
  9250. #ifdef BSD29
  9251. /* The process group and/or signal test doesn't work under these... */
  9252.     backgrd = !y;
  9253. #else
  9254. #ifdef sxaE50
  9255.     backgrd = !y;
  9256. #else
  9257. #ifdef MINIX
  9258.     backgrd = !y;
  9259. #else
  9260. #ifdef MINIX2
  9261.     backgrd = !y;
  9262. #else
  9263.     if (x > -1)
  9264.       backgrd = (x || !y) ? 1 : 0;
  9265.     else backgrd = !y;
  9266. #endif /* BSD29 */
  9267. #endif /* sxaE50 */
  9268. #endif /* MINIX */
  9269. #endif /* MINIX2 */
  9270.     debug(F101,"conbgt backgrd","",backgrd);
  9271. }
  9272.  
  9273. /*  C O N I N T  --  Console Interrupt setter  */
  9274.  
  9275. /*
  9276.   First arg is pointer to function to handle SIGTERM & SIGINT (like Ctrl-C).
  9277.   Second arg is pointer to function to handle SIGTSTP (suspend).
  9278. */
  9279.  
  9280. VOID                    /* Set terminal interrupt traps. */
  9281. #ifdef CK_ANSIC
  9282. #ifdef apollo
  9283. conint(f,s) SIGTYP (*f)(), (*s)();
  9284. #else
  9285. conint(SIGTYP (*f)(int), SIGTYP (*s)(int))
  9286. #endif /* apollo */
  9287. #else
  9288. conint(f,s) SIGTYP (*f)(), (*s)();
  9289. #endif /* CK_ANSIC */
  9290. /* conint */ {
  9291.  
  9292.     debug(F101,"conint conistate","",conistate);
  9293.  
  9294.     conbgt(0);                /* Do background test. */
  9295.  
  9296. /* Set the desired handlers for hangup and software termination. */
  9297.  
  9298. #ifdef SIGTERM
  9299.     signal(SIGTERM,f);                  /* Software termination */
  9300. #endif /* SIGTERM */
  9301.  
  9302. /*
  9303.   Prior to July 1999 we used to call sighup() here but now it's called in
  9304.   sysinit() so SIGHUP can be caught during execution of the init file or
  9305.   a kerbang script.
  9306. */
  9307.  
  9308. /* Now handle keyboard stop, quit, and interrupt signals. */
  9309. /* Check if invoked in background -- if so signals set to be ignored. */
  9310. /* However, if running under a job control shell, don't ignore them. */
  9311. /* We won't be getting any, as we aren't in the terminal's process group. */
  9312.  
  9313.     debug(F101,"conint backgrd","",backgrd);
  9314.     debug(F101,"conint jc","",jc);
  9315.  
  9316.     if (backgrd && !jc) {        /* In background, ignore signals */
  9317.     debug(F101,"conint background ignoring signals, jc","",jc);
  9318. #ifdef SIGTSTP
  9319.         signal(SIGTSTP,SIG_IGN);        /* Keyboard stop */
  9320. #endif /* SIGTSTP */
  9321.         signal(SIGQUIT,SIG_IGN);        /* Keyboard quit */
  9322.         signal(SIGINT,SIG_IGN);         /* Keyboard interrupt */
  9323.     sigint_ign = 1;
  9324.     conistate = CONI_NOI;
  9325.     } else {                /* Else in foreground or suspended */
  9326.     debug(F101,"conint foreground catching signals, jc","",jc);
  9327.         signal(SIGINT,f);               /* Catch terminal interrupt */
  9328.     sigint_ign = (f == SIG_IGN) ? 1 : 0;
  9329.  
  9330. #ifdef SIGTSTP                /* Keyboard stop (suspend) */
  9331.     /* debug(F101,"conint SIGSTSTP","",s); */
  9332.     if (s == NULL) s = SIG_DFL;
  9333. #ifdef NOJC                /* No job control allowed. */
  9334.     signal(SIGTSTP,SIG_IGN);
  9335. #else                    /* Job control allowed */
  9336.     if (jc)                /* if available. */
  9337.       signal(SIGTSTP,s);
  9338.     else
  9339.       signal(SIGTSTP,SIG_IGN);
  9340. #endif /* NOJC */
  9341. #endif /* SIGTSTP */
  9342.  
  9343. #ifndef OXOS
  9344. #ifdef SVORPOSIX
  9345. #ifndef FIONREAD            /* Watch out, we don't know this... */
  9346. #ifndef SELECT
  9347. #ifndef CK_POLL
  9348. #ifndef RDCHK
  9349.         signal(SIGQUIT,esctrp);         /* Quit signal, Sys III/V. */
  9350. #endif /* RDCHK */
  9351. #endif /* CK_POLL */
  9352. #endif /* SELECT */
  9353. #endif /* FIONREAD */
  9354.         if (conesc) conesc = 0;         /* Clear out pending escapes */
  9355. #else
  9356. #ifdef V7
  9357.         signal(SIGQUIT,esctrp);         /* V7 like Sys III/V */
  9358.         if (conesc) conesc = 0;
  9359. #else
  9360. #ifdef aegis
  9361.         signal(SIGQUIT,f);              /* Apollo, catch it like others. */
  9362. #else
  9363.         signal(SIGQUIT,SIG_IGN);        /* Others, ignore like 4D & earlier. */
  9364. #endif /* aegis */
  9365. #endif /* V7 */
  9366. #endif /* SVORPOSIX */
  9367. #endif /* OXOS */
  9368.     conistate = CONI_INT;
  9369.     }
  9370. }
  9371.  
  9372.  
  9373. /*  C O N N O I  --  Reset console terminal interrupts */
  9374.  
  9375. VOID
  9376. connoi() {                              /* Console-no-interrupts */
  9377.  
  9378.     debug(F101,"connoi conistate","",conistate);
  9379. #ifdef SIGTSTP
  9380.     signal(SIGTSTP,SIG_IGN);        /* Suspend */
  9381. #endif /* SIGTSTP */
  9382.     conint(SIG_IGN,SIG_IGN);        /* Interrupt */
  9383.     sigint_ign = 1;            /* Remember we did this ourselves */
  9384. #ifdef SIGQUIT
  9385.     signal(SIGQUIT,SIG_IGN);        /* Quit */
  9386. #endif /* SIGQUIT */
  9387. #ifdef SIGTERM
  9388.     signal(SIGTERM,SIG_IGN);        /* Term */
  9389. #endif /* SIGTERM */
  9390.     conistate = CONI_NOI;
  9391. }
  9392.  
  9393. /*  I N I T R A W Q  --  Set up to read /dev/kmem for character count.  */
  9394.  
  9395. #ifdef  V7
  9396. /*
  9397.  Used in Version 7 to simulate Berkeley's FIONREAD ioctl call.  This
  9398.  eliminates blocking on a read, because we can read /dev/kmem to get the
  9399.  number of characters available for raw input.  If your system can't
  9400.  or you won't let the world read /dev/kmem then you must figure out a
  9401.  different way to do the counting of characters available, or else replace
  9402.  this by a dummy function that always returns 0.
  9403. */
  9404. /*
  9405.  * Call this routine as: initrawq(tty)
  9406.  * where tty is the file descriptor of a terminal.  It will return
  9407.  * (as a char *) the kernel-mode memory address of the rawq character
  9408.  * count, which may then be read.  It has the side-effect of flushing
  9409.  * input on the terminal.
  9410.  */
  9411. /*
  9412.  * John Mackin, Physiology Dept., University of Sydney (Australia)
  9413.  * ...!decvax!mulga!physiol.su.oz!john
  9414.  *
  9415.  * Permission is hereby granted to do anything with this code, as
  9416.  * long as this comment is retained unmodified and no commercial
  9417.  * advantage is gained.
  9418.  */
  9419. #ifndef MINIX
  9420. #ifndef MINIX2
  9421. #ifndef COHERENT
  9422. #include <a.out.h>
  9423. #include <sys/proc.h>
  9424. #endif /* COHERENT */
  9425. #endif /* MINIX2 */
  9426. #endif /* MINIX */
  9427.  
  9428. #ifdef COHERENT
  9429. #include <l.out.h>
  9430. #include <sys/proc.h>
  9431. #endif /* COHERENT */
  9432.  
  9433. char *
  9434. initrawq(tty) int tty; {
  9435. #ifdef MINIX
  9436.     return(0);
  9437. #else
  9438. #ifdef MINIX2
  9439.     return(0);
  9440. #else
  9441. #ifdef UTS24
  9442.     return(0);
  9443. #else
  9444. #ifdef BSD29
  9445.     return(0);
  9446. #else
  9447.     long lseek();
  9448.     static struct nlist nl[] = {
  9449.         {PROCNAME},
  9450.         {NPROCNAME},
  9451.         {""}
  9452.     };
  9453.     static struct proc *pp;
  9454.     char *qaddr, *p, c;
  9455.     int m;
  9456.     PID_T pid, me;
  9457.     NPTYPE xproc;                       /* Its type is defined in makefile. */
  9458.     int catch();
  9459.  
  9460.     me = getpid();
  9461.     if ((m = open("/dev/kmem", 0)) < 0) err("kmem");
  9462.     nlist(BOOTNAME, nl);
  9463.     if (nl[0].n_type == 0) err("proc array");
  9464.  
  9465.     if (nl[1].n_type == 0) err("nproc");
  9466.  
  9467.     lseek(m, (long)(nl[1].n_value), 0);
  9468.     read (m, &xproc, sizeof(xproc));
  9469.     saval = signal(SIGALRM, catch);
  9470.     if ((pid = fork()) == 0) {
  9471.         while(1)
  9472.             read(tty, &c, 1);
  9473.     }
  9474.     alarm(2);
  9475.  
  9476.     if(setjmp(jjbuf) == 0) {
  9477.         while(1)
  9478.       read(tty, &c, 1);
  9479.     }
  9480.     signal(SIGALRM, SIG_DFL);
  9481.  
  9482. #ifdef DIRECT
  9483.     pp = (struct proc *) nl[0].n_value;
  9484. #else
  9485.     if (lseek(m, (long)(nl[0].n_value), 0) < 0L) err("seek");
  9486.     if (read(m, &pp, sizeof(pp)) != sizeof(pp))  err("no read of proc ptr");
  9487. #endif
  9488.     lseek(m, (long)(nl[1].n_value), 0);
  9489.     read(m, &xproc, sizeof(xproc));
  9490.  
  9491.     if (lseek(m, (long)pp, 0) < 0L) err("Can't seek to proc");
  9492.     if ((p = malloc(xproc * sizeof(struct proc))) == NULL) err("malloc");
  9493.     if (read(m,p,xproc * sizeof(struct proc)) != xproc*sizeof(struct proc))
  9494.         err("read proc table");
  9495.     for (pp = (struct proc *)p; xproc > 0; --xproc, ++pp) {
  9496.         if (pp -> p_pid == (short) pid) goto iout;
  9497.     }
  9498.     err("no such proc");
  9499.  
  9500. iout:
  9501.     close(m);
  9502.     qaddr = (char *)(pp -> p_wchan);
  9503.     free (p);
  9504.     kill(pid, SIGKILL);
  9505.     wait((WAIT_T *)0);
  9506.     return (qaddr);
  9507. #endif
  9508. #endif
  9509. #endif
  9510. #endif
  9511. }
  9512.  
  9513. /*  More V7-support functions...  */
  9514.  
  9515. static VOID
  9516. err(s) char *s; {
  9517.     char buf[200];
  9518.  
  9519.     ckmakmsg(buf,200,"fatal error in initrawq: ", s, NULL, NULL);
  9520.     perror(buf);
  9521.     doexit(1,-1);
  9522. }
  9523.  
  9524. static VOID
  9525. catch(foo) int foo; {
  9526.     longjmp(jjbuf, -1);
  9527. }
  9528.  
  9529.  
  9530. /*  G E N B R K  --  Simulate a modem break.  */
  9531.  
  9532. #ifdef MINIX
  9533. #define BSPEED B110
  9534. #else
  9535. #ifdef MINIX2
  9536. #define BSPEED B110
  9537. #else
  9538. #define BSPEED B150
  9539. #endif /* MINIX2 */
  9540. #endif /* MINIX */
  9541.  
  9542. #ifndef MINIX2
  9543. VOID
  9544. genbrk(fn,msec) int fn, msec; {
  9545.     struct sgttyb ttbuf;
  9546.     int ret, sospeed, x, y;
  9547.  
  9548.     ret = ioctl(fn, TIOCGETP, &ttbuf);
  9549.     sospeed = ttbuf.sg_ospeed;
  9550.     ttbuf.sg_ospeed = BSPEED;
  9551.     ret = ioctl(fn, TIOCSETP, &ttbuf);
  9552.     y = (int)strlen(brnuls);
  9553.     x = ( BSPEED * 100 ) / msec;
  9554.     if (x > y) x = y;
  9555.     ret = write(fn, brnuls, (( BSPEED * 100 ) / msec ));
  9556.     ttbuf.sg_ospeed = sospeed;
  9557.     ret = ioctl(fn, TIOCSETP, &ttbuf);
  9558.     ret = write(fn, "@", 1);
  9559.     return;
  9560. }
  9561. #endif /* MINIX2 */
  9562.  
  9563. #ifdef MINIX2
  9564. int
  9565. genbrk(fn,msec) int fn, msec; {
  9566.     struct termios ttbuf;
  9567.     int ret, x, y;
  9568.     speed_t sospeed;
  9569.  
  9570.     ret = tcgetattr(fn, &ttbuf);
  9571.     sospeed = ttbuf.c_ospeed;
  9572.     ttbuf.c_ospeed = BSPEED;
  9573.     ret = tcsetattr(fn,TCSADRAIN, &ttbuf);
  9574.     y = (int)strlen(brnuls);
  9575.     x = ( BSPEED * 100 ) / msec;
  9576.     if (x > y) x = y;
  9577.     ret = write(fn, brnuls, (( BSPEED * 100 ) / msec ));
  9578.     ttbuf.c_ospeed = sospeed;
  9579.     ret = tcsetattr(fn, TCSADRAIN, &ttbuf);
  9580.     ret = write(fn, "@", 1);
  9581.     return ret;
  9582. }
  9583. #endif /* MINIX2 */
  9584. #endif /* V7 */
  9585.  
  9586. /*
  9587.   I N C H K  --  Check if chars waiting to be read on given file descriptor.
  9588.  
  9589.   This routine is a merger of ttchk() and conchk().
  9590.   Call with:
  9591.     channel == 0 to check console.
  9592.     channel == 1 to check communications connection.
  9593.   and:
  9594.     fd = file descriptor.
  9595.   Returns:
  9596.    >= 0: number of characters waiting, 0 or greater,
  9597.      -1: on any kind of error,
  9598.      -2: if there is (definitely) no connection.
  9599.   Note: In UNIX we don't have to call nettchk() because a socket
  9600.   file descriptor works just like in serial i/o, ioctls and all.
  9601.   (But this will change if we add non-file-descriptor channels,
  9602.   such as IBM X.25 for AIX...)
  9603. */
  9604. static int
  9605. in_chk(channel, fd) int channel, fd; {
  9606.     int x, n = 0;            /* Workers, n = return value */
  9607.     extern int clsondisc;        /* Close on disconnect */
  9608. /*
  9609.   The first section checks to make sure we have a connection,
  9610.   but only if we're in local mode.
  9611. */
  9612. #ifdef DEBUG
  9613.     if (deblog) {
  9614.     debug(F111,"in_chk entry",ckitoa(fd),channel);
  9615.     debug(F101,"in_chk ttyfd","",ttyfd);
  9616.     debug(F101,"in_chk ttpty","",ttpty);
  9617.     }
  9618. #endif /* DEBUG */
  9619. /*
  9620.   But don't say connection is gone if we have any buffered-stuff.
  9621. */
  9622. #ifdef TTLEBUF
  9623.     debug(F101,"in_chk ttpush","",ttpush);
  9624.     if (channel == 1) {
  9625.     if (ttpush >= 0)
  9626.       n++;
  9627.     n += le_inbuf();
  9628.     if (n > 0)
  9629.       return(n);
  9630.     }
  9631. #endif /* TTLEBUF */
  9632.  
  9633. #ifdef NETPTY
  9634. #ifdef HAVE_PTYTRAP
  9635.     /* Special handling for HP-UX pty i/o */
  9636.     if (ttpty && pty_trap_pending(ttyfd) > 0) {
  9637.         if (pty_trap_handler(ttyfd) > 0) {
  9638.             ttclos(0);
  9639.             return(-2);
  9640.         }
  9641.     }
  9642. #endif /* HAVE_PTYTRAP */
  9643. #endif /* NETPTY */
  9644.  
  9645.     if (channel) {            /* Checking communications channel */
  9646.     if (ttyfd < 0) {        /* No connection */
  9647.       return(-2);            /* That's what this means */
  9648.     } else if (xlocal &&        /* In local mode */
  9649.            (!netconn        /* Serial connection or */
  9650. #ifdef TN_COMPORT
  9651.             || istncomport()    /* Telnet Com Port */
  9652. #endif /* TN_COMPORT */
  9653.            ) && ttcarr != CAR_OFF /* with CARRIER WATCH ON (or AUTO) */
  9654. #ifdef COMMENT
  9655. #ifdef MYREAD
  9656. /*
  9657.   Seems like this would be a good idea but it prevents C-Kermit from
  9658.   popping back to the prompt automatically when carrier drops.  However,
  9659.   commenting this out prevents us from seeing the NO CARRIER message.
  9660.   Needs more work...
  9661. */
  9662.            && my_count < 1    /* Nothing in our internal buffer */
  9663. #endif /* MYREAD */
  9664. #endif /* COMMENT */
  9665.            ) {
  9666.         int x;
  9667.         x = ttgmdm();        /* So get modem signals */
  9668.         debug(F101,"in_chk close-on-disconnect","",clsondisc);
  9669.         if (x > -1) {        /* Check for carrier */
  9670.         if (!(x & BM_DCD)) {    /* No carrier */
  9671.             debug(F101,"in_chk carrier lost","",x);
  9672.             if (clsondisc)    /* If "close-on-disconnect" */
  9673.               ttclos(0);    /* close device & release lock. */
  9674.             return(-2);        /* This means "disconnected" */
  9675.         }
  9676.         /* In case I/O to device after CD dropped always fails */
  9677.         /* as in Debian Linux 2.1 and Unixware 2.1... */
  9678.         } else {
  9679.             debug(F101,"in_chk ttgmdm I/O error","",errno);
  9680.             debug(F101,"in_chk ttgmdm gotsigs","",gotsigs);
  9681.             if (gotsigs) {        /* If we got signals before... */
  9682.             if (errno == 5 || errno == 6) { /* I/O error etc */
  9683.                 if (clsondisc)    /* like when modem hangs up */
  9684.               ttclos(0);
  9685.             return(-2);
  9686.             }
  9687.         }
  9688.         /* If we never got modem signals successfully on this */
  9689.         /* connection before, we can't conclude that THIS failure */
  9690.         /* means the connection was lost. */
  9691.         return(0);
  9692.         }
  9693.     }
  9694.     }
  9695.  
  9696. /* We seem to have a connection so now see if any bytes are waiting on it */
  9697.  
  9698. #ifdef CK_SSL
  9699.     if (ssl_active_flag || tls_active_flag) {
  9700.         n += SSL_pending(ssl_active_flag?ssl_con:tls_con);
  9701.         debug(F101,"in_chk SSL_pending","",n);
  9702.         if (n < 0) {
  9703.             ttclos(0);
  9704.             return(-1);
  9705.         } else if (n > 0) {
  9706.             return(n);
  9707.         }
  9708.     }
  9709. #endif /* CK_SSL */
  9710. #ifdef RLOGCODE
  9711. #ifdef CK_KERBEROS
  9712.     /* It is not safe to read any data when using encrypted Klogin */
  9713.     if (ttnproto == NP_EK4LOGIN || ttnproto == NP_EK5LOGIN) {
  9714. #ifdef KRB4
  9715.         if (ttnproto == NP_EK4LOGIN) {
  9716.             n += krb4_des_avail(ttyfd);
  9717.             debug(F101,"in_chk krb4_des_avail","",n);
  9718.         }
  9719. #endif /* KRB4 */
  9720. #ifdef KRB5
  9721.         if (ttnproto == NP_EK5LOGIN) {
  9722.             n += krb5_des_avail(ttyfd);
  9723.             debug(F101,"in_chk krb5_des_avail","",n);
  9724.         }
  9725. #ifdef KRB5_U2U
  9726.         if (ttnproto == NP_K5U2U) {
  9727.             n += krb5_u2u_avail(ttyfd);
  9728.             debug(F101,"in_chk krb5_des_avail","",n);
  9729.         }
  9730. #endif /* KRB5_U2U */
  9731. #endif /* KRB5 */
  9732.         if (n < 0)            /* Is this right? */
  9733.       return(-1);
  9734.         else
  9735.       return(n);
  9736.     }
  9737. #endif /* CK_KERBEROS */
  9738. #endif /* RLOGCODE */
  9739.  
  9740.     errno = 0;                /* Reset this so we log good info */
  9741. #ifdef FIONREAD
  9742.     x = ioctl(fd, FIONREAD, &n);    /* BSD and lots of others */
  9743. #ifdef DEBUG                /* (the more the better) */
  9744.     if (deblog) {
  9745.     debug(F101,"in_chk FIONREAD return code","",x);
  9746.     debug(F101,"in_chk FIONREAD count","",n);
  9747.     debug(F101,"in_chk FIONREAD errno","",errno);
  9748.     }
  9749. #endif /* DEBUG */
  9750. #else /* FIONREAD not defined */
  9751. /*
  9752.   Here, if (netconn && ttnet == NET_TCPB), we might try calling recvmsg()
  9753.   with flags MSG_PEEK|MSG_DONTWAIT on the socket (ttyfd), except this is not
  9754.   portable (MSG_DONTWAIT isn't defined in any of the <sys/socket.h> files
  9755.   that I looked at, but it is needed to prevent the call from blocking), and
  9756.   the msghdr struct differs from place to place, so we would need another
  9757.   avalanche of ifdefs.  Still, when FIONREAD is not available, this is the
  9758.   only other known method of asking the OS for the *number* of characters
  9759.   available for reading.
  9760. */
  9761. #ifdef V7                /* UNIX V7: look in kernel memory */
  9762. #ifdef MINIX
  9763.     n = 0;                /* But not in MINIX */
  9764. #else
  9765. #ifdef MINIX2
  9766.     n = 0;
  9767. #else
  9768.     lseek(kmem[TTY], (long) qaddr[TTY], 0); /* 7th Edition Unix */
  9769.     x = read(kmem[TTY], &n, sizeof(int));
  9770.     if (x != sizeof(int))
  9771.       n = 0;
  9772. #endif /* MINIX2 */
  9773. #endif /* MINIX */
  9774. #else /* Not V7 */
  9775. #ifdef PROVX1
  9776.     x = ioctl(fd, TIOCQCNT, &ttbuf);    /* DEC Pro/3xx Venix V.1 */
  9777.     n = ttbuf.sg_ispeed & 0377;        /* Circa 1984 */
  9778.     if (x < 0) n = 0;
  9779. #else
  9780. #ifdef MYREAD
  9781. /*
  9782.   Here we skip all the undependable and expensive calls below if we
  9783.   already have something in our internal buffer.  This tends to work quite
  9784.   nicely, so the only really bad case remaining is the one in which neither
  9785.   FIONREAD or MYREAD are defined, which is increasingly rare these days.
  9786. */
  9787.     if (channel != 0 && my_count > 0) {
  9788.     debug(F101,"in_chk buf my_count","",my_count);
  9789.     n = my_count;            /* n was 0 before we got here */
  9790.     return(n);
  9791.     }
  9792. #endif /* MYREAD */
  9793. /*
  9794.   rdchk(), select(), and poll() tell us *if* data is available to be read, but
  9795.   not how much, so these should be used only as a final resort.  Especially
  9796.   since these calls tend to add a lot overhead.
  9797. */
  9798. #ifdef RDCHK                /* This mostly SCO-specific */
  9799.     n = rdchk(fd);
  9800.     debug(F101,"in_chk rdchk","",n);
  9801. #else /* No RDCHK */
  9802. #ifdef SELECT
  9803. #ifdef Plan9
  9804.     /* Only allows select on the console ... don't ask */
  9805.     if (channel == 0)
  9806. #endif /* Plan9 */
  9807.       {
  9808.     fd_set rfds;            /* Read file descriptors */
  9809. #ifdef BELLV10
  9810.     FD_ZERO(rfds);            /* Initialize them */
  9811.     FD_SET(fd,rfds);        /* We want to look at this fd */
  9812. #else
  9813.     FD_ZERO(&rfds);            /* Initialize them */
  9814.     FD_SET(fd,&rfds);        /* We want to look at this fd */
  9815.     tv.tv_sec = tv.tv_usec = 0L;    /* A 0-valued timeval structure */
  9816. #endif /* BELLV10 */
  9817. #ifdef Plan9
  9818.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9819.     debug(F101,"in_chk Plan 9 select","",n);
  9820. #else
  9821. #ifdef BELLV10
  9822.     n = select( 128, rfds, (fd_set *)0, (fd_set *)0, 0 );
  9823.     debug(F101,"in_chk BELLV10 select","",n);
  9824. #else
  9825. #ifdef BSD44
  9826.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9827.     debug(F101,"in_chk BSD44 select","",n);
  9828. #else
  9829. #ifdef BSD43
  9830.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9831.     debug(F101,"in_chk BSD43 select","",n);
  9832. #else
  9833. #ifdef SOLARIS
  9834.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9835.     debug(F101,"in_chk SOLARIS select","",n);
  9836. #else
  9837. #ifdef QNX6
  9838.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9839.     debug(F101,"in_chk QNX6 select","",n);
  9840. #else
  9841. #ifdef QNX
  9842.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9843.     debug(F101,"in_chk QNX select","",n);
  9844. #else
  9845. #ifdef COHERENT
  9846.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9847.     debug(F101,"in_chk COHERENT select","",n);
  9848. #else
  9849. #ifdef SVR4
  9850.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9851.     debug(F101,"in_chk SVR4 select","",n);
  9852. #else
  9853. #ifdef __linux__
  9854.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9855.     debug(F101,"in_chk LINUX select","",n);
  9856. #ifdef OSF
  9857.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9858.     debug(F101,"in_chk OSF select","",n);
  9859. #else
  9860.     n = select( FD_SETSIZE, &rfds, (int *)0, (int *)0, &tv );
  9861.     debug(F101,"in_chk catchall select","",n);
  9862. #endif /* OSF */
  9863. #endif /* __linux__ */
  9864. #endif /* SVR4 */
  9865. #endif /* COHERENT */
  9866. #endif /* QNX */
  9867. #endif /* QNX6 */
  9868. #endif /* SOLARIS */
  9869. #endif /* BSD43 */
  9870. #endif /* BSD44 */
  9871. #endif /* BELLV10 */
  9872. #endif /* Plan9 */
  9873.     }
  9874. #else  /* Not SELECT */
  9875. #ifdef CK_POLL
  9876.     {
  9877.       struct pollfd pfd;
  9878.  
  9879.       pfd.fd = fd;
  9880.       pfd.events = POLLIN;
  9881.       pfd.revents = 0;
  9882.       n = poll(&pfd, 1, 0);
  9883.       debug(F101,"in_chk poll","",n);
  9884.       if ((n > 0) && (pfd.revents & POLLIN))
  9885.     n = 1;
  9886.     }
  9887. #endif /* CK_POLL */
  9888. #endif /* SELECT */
  9889. #endif /* RDCHK */
  9890. #endif /* PROVX1 */
  9891. #endif /* V7 */
  9892. #endif /* FIONREAD */
  9893.  
  9894. /* From here down, treat console and communication device differently... */
  9895.  
  9896.     if (channel == 0) {            /* Console */
  9897.  
  9898. #ifdef SVORPOSIX
  9899. #ifndef FIONREAD
  9900. #ifndef SELECT
  9901. #ifndef CK_POLL
  9902. #ifndef RDCHK
  9903. /*
  9904.   This is the hideous hack used in System V and POSIX systems that don't
  9905.   support FIONREAD, rdchk(), select(), poll(), etc, in which the user's
  9906.   CONNECT-mode escape character is attached to SIGQUIT.  Used, obviously,
  9907.   only on the console.
  9908. */
  9909.     if (conesc) {            /* Escape character typed == SIGQUIT */
  9910.         debug(F100,"in_chk conesc","",conesc);
  9911.         conesc = 0;
  9912.         signal(SIGQUIT,esctrp);    /* Restore signal */
  9913.         n += 1;
  9914.     }
  9915. #endif /* RDCHK */
  9916. #endif /* CK_POLL */
  9917. #endif /* SELECT */
  9918. #endif /* FIONREAD */
  9919. #endif /* SVORPOSIX */
  9920.  
  9921.     return(n);            /* Done with console */
  9922.     }
  9923.  
  9924.     if (channel != 0) {            /* Communications connection */
  9925.  
  9926. #ifdef MYREAD
  9927. #ifndef FIONREAD
  9928. /*
  9929.   select() or rdchk(), etc, has told us that something is waiting, but we
  9930.   don't know how much.  So we do a read to get it and then we know.  Note:
  9931.   This read is NOT nonblocking if nothing is there (because of VMIN=1), but
  9932.   it should be safe in this case since the OS tells us at least one byte is
  9933.   waiting to be read, and MYREAD reads return as much as is there without
  9934.   waiting for any more.  Controlled tests on Solaris and Unixware (with
  9935.   FIONREAD deliberately undefined) show this to be true.
  9936. */
  9937.     debug(F101,"in_chk read my_count","",my_count);
  9938.     debug(F101,"in_chk read n","",n);
  9939.     if (n > 0 && my_count == 0) {
  9940.         /* This also catches disconnects etc */
  9941.         /* Do what mygetbuf does except don't grab a character */
  9942.         my_count = myfillbuf();
  9943.         my_item = -1;        /* ^^^ */
  9944.         debug(F101,"in_chk myfillbuf my_count","",my_count);
  9945.         if (my_count < 0)
  9946.           return(-1);
  9947.         else
  9948.           n = 0;            /* NB: n is replaced by my_count */
  9949.     }
  9950. #endif /* FIONREAD */
  9951. /*
  9952.   Here we add whatever we think is unread to what is still in our
  9953.   our internal buffer.  Thus the importance of setting n to 0 just above.
  9954. */
  9955.     debug(F101,"in_chk my_count","",my_count);
  9956.     debug(F101,"in_chk n","",n);
  9957.     if (my_count > 0)
  9958.       n += my_count;
  9959. #endif /* MYREAD */
  9960.     }
  9961.     debug(F101,"in_chk result","",n);
  9962.  
  9963.     /* Errors here don't prove the connection has dropped so just say 0 */
  9964.  
  9965.     return(n < 0 ? 0 : n);
  9966. }
  9967.  
  9968.  
  9969. /*  T T C H K  --  Tell how many characters are waiting in tty input buffer  */
  9970.  
  9971. int
  9972. ttchk() {
  9973.     int fd;
  9974. #ifdef NETCMD
  9975.     if (ttpipe)
  9976.       fd = fdin;
  9977.     else
  9978. #endif /* NETCMD */
  9979.       fd = ttyfd;
  9980.     return(in_chk(1,fd));
  9981. }
  9982.  
  9983. /*  T T X I N  --  Get n characters from tty input buffer  */
  9984.  
  9985. /*  Returns number of characters actually gotten, or -1 on failure  */
  9986.  
  9987. /*  Intended for use only when it is known that n characters are actually */
  9988. /*  Available in the input buffer.  */
  9989.  
  9990. int
  9991. ttxin(n,buf) int n; CHAR *buf; {
  9992.     register int x = 0, c = -2;
  9993. #ifdef TTLEBUF
  9994.     register int i = 0;
  9995. #endif /* TTLEBUF */
  9996.     int fd;
  9997.  
  9998.     if (n < 1)                /* Nothing to do */
  9999.       return(0);
  10000.  
  10001. #ifdef TTLEBUF
  10002.     if (ttpush >= 0) {
  10003.         buf[0] = ttpush;        /* Put pushed char in buffer*/
  10004.         ttpush = -1;            /* Clear the push buffer */
  10005.         if (ttchk() > 0)
  10006.       return(ttxin(n-1, &buf[1]) + 1);
  10007.         else
  10008.       return(1);
  10009.     }
  10010.     if (le_data) {
  10011.         while (le_inbuf() > 0) {
  10012.         if (le_getchar(&buf[i])) {
  10013.                 i++;
  10014.                 n--;
  10015.             }
  10016.         }
  10017.         if (ttchk() > 0)
  10018.       return(ttxin(n,&buf[i])+i);
  10019.         else
  10020.       return(i);
  10021.     }
  10022. #endif /* TTLEBUF */
  10023.  
  10024. #ifdef NETCMD
  10025.     if (ttpipe)
  10026.       fd = fdin;
  10027.     else
  10028. #endif /* NETCMD */
  10029.       fd = ttyfd;
  10030.  
  10031. #ifdef SUNX25
  10032.     if (netconn && (ttnet == NET_SX25))    /* X.25 connection */
  10033.       return(x25xin(n,buf));
  10034. #endif /* SUNX25 */
  10035.  
  10036. #ifdef IBMX25
  10037.     /* riehm: possibly not needed. Test worked with normal reads and writes */
  10038.     if (netconn && (ttnet == NET_IX25))    { /* X.25 connection */
  10039.     x = x25xin(n,buf);
  10040.     if (x > 0) buf[x] = '\0';
  10041.     return(x);
  10042.     }
  10043. #endif /* IBMX25 */
  10044.  
  10045. #ifdef MYREAD
  10046.     debug(F101,"ttxin MYREAD","",n);
  10047.     while (x < n) {
  10048.     c = myread();
  10049.     if (c < 0) {
  10050.         debug(F101,"ttxin myread returns","",c);
  10051.         if (c == -3) x = -1;
  10052.         break;
  10053.         }
  10054.     buf[x++] = c & ttpmsk;
  10055. #ifdef RLOGCODE
  10056. #ifdef CK_KERBEROS
  10057.         /* It is impossible to know how many characters are waiting */
  10058.         /* to be read when you are using Encrypted Rlogin or SSL    */
  10059.         /* as the transport since the number of real data bytes     */
  10060.         /* can be greater or less than the number of bytes on the   */
  10061.         /* wire which is what ttchk() returns.                      */
  10062.         if (netconn && (ttnproto == NP_EK4LOGIN || ttnproto == NP_EK5LOGIN))
  10063.       if (ttchk() <= 0)
  10064.         break;
  10065. #endif /* CK_KERBEROS */
  10066. #endif /* RLOGCODE */
  10067. #ifdef CK_SSL
  10068.         if (ssl_active_flag || tls_active_flag)
  10069.       if (ttchk() <= 0)
  10070.         break;
  10071. #endif /* CK_SSL */
  10072.     }
  10073. #else
  10074.     debug(F101,"ttxin READ","",n);
  10075.     x = read(fd,buf,n);
  10076.     for (c = 0; c < n; c++)        /* Strip any parity */
  10077.       buf[c] &= ttpmsk;
  10078. #endif /* MYREAD */
  10079.  
  10080.     debug(F101,"ttxin x","",x);        /* Done */
  10081.     if (x > 0) buf[x] = '\0';
  10082.     if (x < 0) x = -1;
  10083.     return(x);
  10084. }
  10085.  
  10086. /*  T T O L  --  Write string s, length n, to communication device.  */
  10087. /*
  10088.   Returns:
  10089.    >= 0 on success, number of characters actually written.
  10090.    -1 on failure.
  10091. */
  10092. #ifdef CK_ENCRYPTION
  10093. CHAR * xpacket = NULL;
  10094. int nxpacket = 0;
  10095. #endif /* CK_ENCRYPTION */
  10096.  
  10097. #define TTOLMAXT 5
  10098. int
  10099. ttol(s,n) int n; CHAR *s; {
  10100.     int x, len, tries, fd;
  10101. #ifdef CKXXCHAR
  10102.     extern int dblflag;            /* For SET SEND DOUBLE-CHARACTER */
  10103.     extern short dblt[];
  10104.     CHAR *p = NULL, *p2, *s2, c;
  10105.     int n2 = 0;
  10106. #endif /* CKXXCHAR */
  10107.  
  10108.     if (ttyfd < 0)            /* Not open? */
  10109.       return(-3);
  10110. #ifdef DEBUG
  10111.     if (deblog) hexdump("ttol s",s,n);
  10112. #endif /* DEBUG */
  10113.  
  10114. #ifdef NETCMD
  10115.     if (ttpipe)
  10116.       fd = fdout;
  10117.     else
  10118. #endif /* NETCMD */
  10119.       fd = ttyfd;
  10120.  
  10121. #ifdef CKXXCHAR
  10122. /*  Double any characters that must be doubled.  */
  10123.     debug(F101,"ttol dblflag","",dblflag);
  10124.     if (dblflag) {
  10125.     p = (CHAR *) malloc(n + n + 1);
  10126.     if (p) {
  10127.         s2 = s;
  10128.         p2 = p;
  10129.         n2 = 0;
  10130.         while (*s2) {
  10131.         c = *s2++;
  10132.         *p2++ = c;
  10133.         n2++;
  10134.         if (dblt[(unsigned) c] & 2) {
  10135.             *p2++ = c;
  10136.             n2++;
  10137.         }
  10138.         }
  10139.         s = p;
  10140.         n = n2;
  10141.         s[n] = '\0';
  10142.     }
  10143. #ifdef DEBUG
  10144.         if (deblog) hexdump("ttol doubled s",s,n);
  10145. #endif /* DEBUG */
  10146.     }
  10147. #endif /* CKXXCHAR */
  10148.  
  10149.     tries = TTOLMAXT;            /* Allow up to this many tries */
  10150.     len = n;                /* Remember original length */
  10151.  
  10152. #ifdef CK_ENCRYPTION
  10153. /*
  10154.   This is to avoid encrypting a packet that is already encrypted, e.g.
  10155.   when we resend a packet directly out of the packet buffer, and also to
  10156.   avoid encrypting a constant (literal) string, which can cause a memory
  10157.   fault.
  10158. */
  10159.     if (TELOPT_ME(TELOPT_ENCRYPTION)) {
  10160.     int x;
  10161.     if (nxpacket < n) {
  10162.         if (xpacket) {
  10163.         free(xpacket);
  10164.         xpacket = NULL;
  10165.         nxpacket = 0;
  10166.         }
  10167.         x = n > 10240 ? n : 10240;
  10168.         xpacket = (CHAR *)malloc(x);
  10169.         if (!xpacket) {
  10170.         fprintf(stderr,"ttol malloc failure\n");
  10171.         return(-1);
  10172.         } else
  10173.           nxpacket = x;
  10174.     }
  10175.     memcpy((char *)xpacket,(char *)s,n);
  10176.     s = xpacket;
  10177.     ck_tn_encrypt((char *)s,n);
  10178.     }
  10179. #endif /* CK_ENCRYPTION */
  10180.  
  10181.     while (n > 0 &&
  10182.        (tries-- > 0
  10183. #ifdef CK_ENCRYPTION
  10184.         /* keep trying if we are encrypting */
  10185.         || TELOPT_ME(TELOPT_ENCRYPTION)
  10186. #endif /* CK_ENCRYPTION */
  10187.             )) {            /* Be persistent */
  10188.     debug(F101,"ttol try","",TTOLMAXT - tries);
  10189. #ifdef BEOSORBEBOX
  10190.         if (netconn && !ttpipe && !ttpty)
  10191.       x = nettol((char *)s,n);    /* Write string to device */
  10192.         else
  10193. #endif /* BEOSORBEBOX */
  10194. #ifdef IBMX25
  10195.       if (ttnet == NET_IX25)
  10196.         /*
  10197.          * this is a more controlled way of writing to X25
  10198.          * STREAMS, however write should also work!
  10199.          */
  10200.         x = x25write(ttyfd, s, n);
  10201.       else
  10202. #endif /* IBMX25 */
  10203. #ifdef CK_SSL
  10204.         if (ssl_active_flag || tls_active_flag) {
  10205.         int error;
  10206.         /* Write using SSL */
  10207.                 ssl_retry:
  10208.         if (ssl_active_flag)
  10209.                   x = SSL_write(ssl_con, s, n);
  10210.         else
  10211.                   x = SSL_write(tls_con, s, n);
  10212.         switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,x)) {
  10213.                 case SSL_ERROR_NONE:
  10214.                     if (x == n)
  10215.               return(len);
  10216.                     s += x;
  10217.                     n -= x;
  10218.                     goto ssl_retry;
  10219.           case SSL_ERROR_WANT_WRITE:
  10220.           case SSL_ERROR_WANT_READ:
  10221.             x = 0;
  10222.             break;
  10223.           case SSL_ERROR_SYSCALL:
  10224.                     if (x != 0)
  10225.               return(-1);
  10226.           case SSL_ERROR_WANT_X509_LOOKUP:
  10227.           case SSL_ERROR_SSL:
  10228.           case SSL_ERROR_ZERO_RETURN:
  10229.           default:
  10230.             ttclos(0);
  10231.             return(-3);
  10232.         }
  10233.         } else
  10234. #endif /* CK_SSL */
  10235. #ifdef CK_KERBEROS
  10236. #ifdef KRB4
  10237. #ifdef RLOGCODE
  10238.         if (ttnproto == NP_EK4LOGIN) {
  10239.         return(krb4_des_write(ttyfd,s,n));
  10240.         } else
  10241. #endif /* RLOGCODE */
  10242. #endif /* KRB4 */
  10243. #ifdef KRB5
  10244. #ifdef RLOGCODE
  10245.             if (ttnproto == NP_EK5LOGIN) {
  10246.                 return(krb5_des_write(ttyfd,s,n,0));
  10247.             } else
  10248. #endif /* RLOGCODE */
  10249. #ifdef KRB5_U2U
  10250.             if (ttnproto == NP_K5U2U) {
  10251.                 return(krb5_u2u_write(ttyfd,s,n));
  10252.             } else
  10253. #endif /* KRB5_U2U */
  10254. #endif /* KRB5 */
  10255. #endif /* CK_KERBEROS */
  10256.           x = write(fd,s,n);    /* Write string to device */
  10257.  
  10258.     if (x == n) {            /* Worked? */
  10259.         debug(F101,"ttol ok","",x);    /* OK */
  10260. #ifdef CKXXCHAR
  10261.         if (p) free(p);
  10262. #endif /* CKXXCHAR */
  10263.         return(len);        /* Done */
  10264.     } else if (x < 0) {        /* No, got error? */
  10265.         debug(F101,"ttol write error","",errno);
  10266. #ifdef EWOULDBLOCK
  10267.         if (errno == EWOULDBLOCK) {
  10268.         msleep(10);
  10269.         continue;
  10270.         } else
  10271. #endif /* EWOULDBLOCK */
  10272. #ifdef TCPSOCKET
  10273.         if (netconn && ttnet == NET_TCPB) {
  10274.         debug(F101,"ttol TCP error","",errno);
  10275.         ttclos(0);        /* Close the connection. */
  10276.         x = -3;
  10277.         }
  10278. #endif /* TCPSOCKET */
  10279. #ifdef CKXXCHAR
  10280.         if (p) free(p);
  10281. #endif /* CKXXCHAR */
  10282.         return(x);
  10283.     } else {            /* No error, so partial success */
  10284.         debug(F101,"ttol partial","",x); /* This never happens */
  10285.         s += x;            /* Point to part not written yet */
  10286.         n -= x;            /* Adjust length */
  10287.         if (x > 0) msleep(10);    /* Wait 10 msec */
  10288.     }                /* Go back and try again */
  10289.     }
  10290. #ifdef CKXXCHAR
  10291.     if (p) free(p);
  10292. #endif /* CKXXCHAR */
  10293.     return(n < 1 ? len : -1);        /* Return the results */
  10294. }
  10295.  
  10296. /*  T T O C  --  Output a character to the communication line  */
  10297.  
  10298. /*
  10299.  This function should only be used for interactive, character-mode operations,
  10300.  like terminal connection, script execution, dialer i/o, where the overhead
  10301.  of the signals and alarms does not create a bottleneck.
  10302. */
  10303. int
  10304. #ifdef CK_ANSIC
  10305. ttoc(char c)
  10306. #else
  10307. ttoc(c) char c;
  10308. #endif /* CK_ANSIC */
  10309. /* ttoc */ {
  10310. #define TTOC_TMO 15            /* Timeout in case we get stuck */
  10311.     int xx, fd;
  10312.  
  10313.     if (ttyfd < 0)            /* Check for not open. */
  10314.       return(-1);
  10315.  
  10316. #ifdef NETCMD
  10317.     if (ttpipe)
  10318.       fd = fdout;
  10319.     else
  10320. #endif /* NETCMD */
  10321.       fd = ttyfd;
  10322.  
  10323.     c &= 0xff;
  10324.     /* debug(F101,"ttoc","",(CHAR) c); */
  10325.     saval = signal(SIGALRM,timerh);    /* Enable timer interrupt */
  10326.     xx = alarm(TTOC_TMO);        /* for this many seconds. */
  10327.     if (xx < 0) xx = 0;            /* Save old alarm value. */
  10328.     /* debug(F101,"ttoc alarm","",xx); */
  10329.     if (
  10330. #ifdef CK_POSIX_SIG
  10331.     sigsetjmp(sjbuf,1)
  10332. #else
  10333.     setjmp(sjbuf)
  10334. #endif /* CK_POSIX_SIG */
  10335.     ) {        /* Timer went off? */
  10336.     ttimoff();            /* Yes, cancel this alarm. */
  10337.     if (xx - TTOC_TMO > 0) alarm(xx - TTOC_TMO); /* Restore previous one */
  10338.         /* debug(F100,"ttoc timeout","",0); */
  10339. #ifdef NETCONN
  10340.     if (!netconn) {
  10341. #endif /* NETCONN */
  10342.         debug(F101,"ttoc timeout","",c);
  10343.         if (ttflow == FLO_XONX) {
  10344.         debug(F101,"ttoc flow","",ttflow); /* Maybe we're xoff'd */
  10345. #ifndef Plan9
  10346. #ifdef POSIX
  10347.         /* POSIX way to unstick. */
  10348.         debug(F100,"ttoc tcflow","",tcflow(ttyfd,TCOON));
  10349. #else
  10350. #ifdef BSD4                /* Berkeley way to do it. */
  10351. #ifdef TIOCSTART
  10352. /* .... Used to be "ioctl(ttyfd, TIOCSTART, 0);".  Who knows? */
  10353.         {
  10354.           int x = 0;
  10355.           debug(F101,"ttoc TIOCSTART","",ioctl(ttyfd, TIOCSTART, &x));
  10356.         }
  10357. #endif /* TIOCSTART */
  10358. #endif /* BSD4 */
  10359.                     /* Is there a Sys V way to do this? */
  10360. #endif /* POSIX */
  10361. #endif /* Plan9 */
  10362.         }
  10363. #ifdef NETCONN
  10364.         }
  10365. #endif /* NETCONN */
  10366.     return(-1);            /* Return failure code. */
  10367.     } else {
  10368.         int rc;
  10369. #ifdef BEOSORBEBOX
  10370. #ifdef NETCONN
  10371.         if (netconn && !ttpipe && !ttpty)
  10372.       rc = nettoc(c);
  10373.         else
  10374. #endif /*  BEOSORBEBOX */
  10375. #endif /* NETCONN */
  10376. #ifdef CK_ENCRYPTION
  10377.       if (TELOPT_ME(TELOPT_ENCRYPTION))
  10378.         ck_tn_encrypt(&c,1);
  10379. #endif /* CK_ENCRYPTION */
  10380. #ifdef IBMX25
  10381.     /* riehm: maybe this isn't necessary after all. Test program
  10382.      * worked fine with data being sent and retrieved with normal
  10383.      * read's and writes!
  10384.      */
  10385.     if (ttnet == NET_IX25)
  10386.       rc = x25write(ttyfd,&c,1); /* as above for X25 streams */
  10387.     else
  10388. #endif /* IBMX25 */
  10389. #ifdef CK_SSL
  10390.       if (ssl_active_flag || tls_active_flag) {
  10391.           int error;
  10392.           /* Write using SSL */
  10393.           if (ssl_active_flag)
  10394.                 rc = SSL_write(ssl_con, &c, 1);
  10395.           else
  10396.                 rc = SSL_write(tls_con, &c, 1);
  10397.           switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,rc)){
  10398.         case SSL_ERROR_NONE:
  10399.           break;
  10400.         case SSL_ERROR_WANT_WRITE:
  10401.         case SSL_ERROR_WANT_READ:
  10402.           rc = 0;
  10403.           break;
  10404.         case SSL_ERROR_SYSCALL:
  10405.           if (rc != 0)
  10406.             return(-1);
  10407.         case SSL_ERROR_WANT_X509_LOOKUP:
  10408.         case SSL_ERROR_SSL:
  10409.         case SSL_ERROR_ZERO_RETURN:
  10410.         default:
  10411.           ttclos(0);
  10412.           return(-1);
  10413.           }
  10414.       } else
  10415. #endif /* CK_SSL */
  10416. #ifdef CK_KERBEROS
  10417. #ifdef KRB4
  10418. #ifdef RLOGCODE
  10419.       if (ttnproto == NP_EK4LOGIN) {
  10420.           rc = (krb4_des_write(ttyfd,&c,1) == 1);
  10421.       } else
  10422. #endif /* RLOGCODE */
  10423. #endif /* KRB4 */
  10424. #ifdef KRB5
  10425. #ifdef RLOGCODE
  10426.           if (ttnproto == NP_EK5LOGIN) {
  10427.               rc = (krb5_des_write(ttyfd,&c,1,0) == 1);
  10428.           } else
  10429. #endif /* RLOGCODE */
  10430. #ifdef KRB5_U2U
  10431.           if (ttnproto == NP_K5U2U) {
  10432.               rc = (krb5_u2u_write(ttyfd,&c,1) == 1);
  10433.           } else
  10434. #endif /* KRB5_U2U */
  10435. #endif /* KRB5 */
  10436. #endif /* CK_KERBEROS */
  10437.         rc = write(fd,&c,1);    /* Try to write the character. */
  10438.     if (rc < 1) {            /* Failed */
  10439.         ttimoff();            /* Turn off the alarm. */
  10440.         alarm(xx);            /* Restore previous alarm. */
  10441.         debug(F101,"ttoc errno","",errno); /* Log the error, */
  10442.         return(-1);            /* and return the error code. */
  10443.     }
  10444.     }
  10445.     ttimoff();                /* Success, turn off the alarm. */
  10446.     alarm(xx);                /* Restore previous alarm. */
  10447.     return(0);                /* Return good code. */
  10448. }
  10449.  
  10450. /*  T T I N L  --  Read a record (up to break character) from comm line.  */
  10451. /*
  10452.   Reads up to "max" characters from the communication line, terminating on:
  10453.     (a) the packet length field if the "turn" argument is zero, or
  10454.     (b) on the packet-end character (eol) if the "turn" argument is nonzero
  10455.     (c) a certain number of Ctrl-C's in a row
  10456.  
  10457.   Returns:
  10458.     >= 0, the number of characters read upon success;
  10459.     -1 if "max" exceeded, timeout, or other correctable error;
  10460.     -2 on user interruption (c);
  10461.     -3 on fatal error like connection lost.
  10462.  
  10463.   The characters that were input are copied into "dest" with their parity bits
  10464.   stripped if parity was selected.  Returns the number of characters read.
  10465.   Characters after the eol are available upon the next call to this function.
  10466.  
  10467.   The idea is to minimize the number of system calls per packet, and also to
  10468.   minimize timeouts.  This function is the inner loop of the protocol and must
  10469.   be as efficient as possible.  The current strategy is to use myread().
  10470.  
  10471.   WARNING: This function calls parchk(), which is defined in another module.
  10472.   Normally, ckutio.c does not depend on code from any other module, but there
  10473.   is an exception in this case because all the other ck?tio.c modules also
  10474.   need to call parchk(), so it's better to have it defined in a common place.
  10475. */
  10476. #ifdef CTRLC
  10477. #undef CTRLC
  10478. #endif /* CTRLC */
  10479. #define CTRLC '\03'
  10480. /*
  10481.   We have four different declarations here because:
  10482.   (a) to allow Kermit to be built without the automatic parity sensing feature
  10483.   (b) one of each type for ANSI C, one for non-ANSI.
  10484. */
  10485.  
  10486. static int csave = -1;
  10487.  
  10488. #ifndef NOXFER
  10489. int
  10490. #ifdef PARSENSE
  10491. #ifdef CK_ANSIC
  10492. ttinl(CHAR *dest, int max,int timo, CHAR eol, CHAR start, int turn)
  10493. #else
  10494. ttinl(dest,max,timo,eol,start,turn) int max,timo,turn; CHAR *dest, eol, start;
  10495. #endif /* CK_ANSIC */
  10496. #else /* not PARSENSE */
  10497. #ifdef CK_ANSIC
  10498. ttinl(CHAR *dest, int max,int timo, CHAR eol)
  10499. #else
  10500. ttinl(dest,max,timo,eol) int max,timo; CHAR *dest, eol;
  10501. #endif /* __SDTC__ */
  10502. #endif /* PARSENSE */
  10503. /* ttinl */ {
  10504.  
  10505. #ifndef MYREAD
  10506.     CHAR ch, dum;
  10507. #endif /* MYREAD */
  10508. #ifdef PARSENSE
  10509.     int pktlen = -1;
  10510.     int lplen = 0;
  10511.     int havelen = 0;
  10512. #endif /* PARSENSE */
  10513.     int fd;
  10514.     int sopmask = 0xff;            /* Start-Of-Packet mask */
  10515. #ifdef CKXXCHAR
  10516.     extern short dblt[];        /* Ignore-character table */
  10517.     extern int ignflag;
  10518. #endif /* CKXXCHAR */
  10519. #ifdef TCPSOCKET
  10520.     extern CHAR stchr;
  10521. #endif /* TCPSOCKET */
  10522.     int x;
  10523. #ifdef STREAMING
  10524.     extern int streaming;
  10525.     extern int sndtyp;
  10526. #endif /* STREAMING */
  10527.  
  10528.     if (ttyfd < 0) return(-3);          /* Not open. */
  10529.  
  10530.     debug(F101,"ttinl max","",max);
  10531.     debug(F101,"ttinl timo","",timo);
  10532.  
  10533. #ifdef NETCMD
  10534.     if (ttpipe)
  10535.       fd = fdin;
  10536.     else
  10537. #endif /* NETCMD */
  10538.       fd = ttyfd;
  10539.  
  10540. #ifdef COMMENT
  10541.     if (xlocal && conchk() > 0)        /* Allow for console interruptions */
  10542.       return(-1);
  10543. #endif /* COMMENT */
  10544.  
  10545.     *dest = '\0';                       /* Clear destination buffer */
  10546.     if (timo < 0) timo = 0;        /* Safety */
  10547.     if (timo) {                /* Don't time out if timo == 0 */
  10548.     int xx;
  10549.     saval = signal(SIGALRM,timerh);    /* Enable timer interrupt */
  10550.     xx = alarm(timo);        /* Set it. */
  10551.     debug(F101,"ttinl alarm","",xx);
  10552.     }
  10553.     if (
  10554. #ifdef CK_POSIX_SIG
  10555.     sigsetjmp(sjbuf,1)
  10556. #else
  10557.     setjmp(sjbuf)
  10558. #endif /* CK_POSIX_SIG */
  10559.     ) {                /* Timer went off? */
  10560.     debug(F100,"ttinl timout","",0); /* Get here on timeout. */
  10561.     /* debug(F110," with",(char *) dest,0); */
  10562.     ttimoff();            /* Turn off timer */
  10563.     return(-1);            /* and return error code. */
  10564.     } else {
  10565.     register int i, n = -1;        /* local variables */
  10566.     int ccn = 0;
  10567. #ifdef PARSENSE
  10568.     register int flag = 0;
  10569.     debug(F000,"ttinl start","",start);
  10570. #endif /* PARSENSE */
  10571.  
  10572.     ttpmsk = ttprty ? 0177 : 0377;    /* Set parity stripping mask. */
  10573.     sopmask = needpchk ? 0177 : ttpmsk; /* And SOP matching mask. */
  10574.  
  10575. /* Now read into destination, stripping parity and looking for the */
  10576. /* the packet terminator, and also for several Ctrl-C's typed in a row. */
  10577.  
  10578.     i = 0;                /* Destination index */
  10579.     debug(F101,"ttinl eol","",eol);
  10580.  
  10581.     while (i < max-1) {
  10582. #ifdef MYREAD
  10583.         /* debug(F101,"ttinl i","",i); */
  10584.         errno = 0;
  10585.         if (csave > -1) {
  10586.             n = csave;
  10587.         debug(F101,"ttinl unsaving","",n);
  10588.         } else
  10589. #ifdef COMMENT
  10590.           if (xlocal && conchk() > 0) {
  10591.           /* Here we could catch keyboard interruptions. */
  10592.           /* But this would be VERY expensive. */
  10593.           /* We could also do it in myread() but it would be */
  10594.           /* expensive there too -- even if done with select()... */
  10595.           }
  10596. #endif /* COMMENT */
  10597.           if ((n = myread()) < 0) {    /* Timeout or i/o error? */
  10598. #ifdef DEBUG
  10599.         if (deblog) {
  10600.             debug(F101,"ttinl myread failure, n","",n);
  10601.             debug(F101,"ttinl myread errno","",errno);
  10602.         }
  10603. #endif /* DEBUG */
  10604.         /* Don't let EINTR break packets. */
  10605.         if (n == -3) {
  10606.             if (errno == EINTR && i > 0) {
  10607.             debug(F111,"ttinl EINTR myread i","continuing",i);
  10608.             continue;
  10609.             } else {
  10610.             debug(F110,"ttinl non-EINTR -3","closing",0);
  10611.             wasclosed = 1;
  10612.             ttimoff();    /* Turn off timer */
  10613.             ttclos(0);
  10614.             return(n);
  10615.             }
  10616.         } else if (n == -2 && netconn /* && timo == 0 */ ) {
  10617.             /* Here we try to catch broken network connections */
  10618.             /* even when ioctl() and read() do not catch them */
  10619.             debug(F111,"ttinl network myread failure","closing",n);
  10620.             wasclosed = 1;
  10621.             ttimoff();
  10622.             ttclos(0);
  10623.             return(-3);
  10624.         }
  10625. #ifdef STREAMING
  10626.         /* Streaming and no data to read */
  10627.         else if (n == 0 && streaming && sndtyp == 'D')
  10628.           return(0);
  10629. #endif /* STREAMING */
  10630.         break;            /* Break out of while loop */
  10631.         }
  10632.  
  10633. #else /* not MYREAD (is this code used anywhere any more?) */
  10634.  
  10635.         if (csave > -1)        /* Char saved from last time */
  10636.           ch = csave;
  10637.         else if ((n = read(fd, &ch, 1)) < 1)
  10638.           break;            /* Error - break out of while loop */
  10639.         n = ch;
  10640.  
  10641. #endif /* MYREAD */
  10642.  
  10643.         /* Get here with char in n */
  10644.  
  10645. #ifdef CK_ENCRYPTION
  10646.         /* If csave > -1 we already decrypted this character */
  10647.         /* So don't decrypt it again */
  10648.         if (TELOPT_U(TELOPT_ENCRYPTION) && csave == -1) {
  10649.         CHAR ch = n;
  10650.         ck_tn_decrypt(&ch,1);
  10651.         n = ch;
  10652.         }
  10653. #endif /* CK_ENCRYPTION */
  10654.  
  10655.         csave = -1;            /* Unflag that we unsaved a char */
  10656.  
  10657. #ifdef TCPSOCKET
  10658.         if (n == IAC &&        /* Handle Telnet options */
  10659.         ((xlocal && netconn && IS_TELNET()) ||
  10660.         (!xlocal && sstelnet))) {
  10661.         n = tt_tnopt(n);
  10662.         if (n < 0)
  10663.           return(n);
  10664. #ifndef NOPARSEN
  10665.         else if (n == 1)
  10666.           start = stchr;
  10667. #endif /* NOPARSEN */
  10668.         if (n != 255)        /* No data - go back for next char */
  10669.           continue;
  10670.         }                /* Quoted IAC - keep going */
  10671. #endif /* TCPSOCKET */
  10672. #ifdef CKXXCHAR
  10673.         if (ignflag)
  10674.           if (dblt[(unsigned) n] & 1) /* Character to ignore? */
  10675.         continue;
  10676. #endif /* CKXXCHAR */
  10677.  
  10678. /*
  10679.   Use parity mask, rather than always stripping parity, to check for
  10680.   cancellation.  Otherwise, runs like \x03\x83\x03 in a packet could cancel
  10681.   the transfer when parity is NONE.  (Note that \x03\x03\x03 is extremely
  10682.   unlikely due to run-length encoding.)
  10683. */
  10684.         /* Check cancellation */
  10685.         if (!xlocal && xfrcan && ((n & ttpmsk) == xfrchr)) {
  10686.         if (++ccn >= xfrnum) {    /* If xfrnum in a row, bail out. */
  10687.             if (timo) {        /* Clear timer. */
  10688.             ttimoff();
  10689.             }
  10690.             if (xfrchr < 32)
  10691.               printf("^%c...\r\n",(char)(xfrchr+64));
  10692.             else
  10693.               printf("Canceled...\r\n");
  10694.             return(-2);
  10695.         }
  10696.         } else ccn = 0;        /* No cancellation, reset counter, */
  10697.  
  10698. #ifdef PARSENSE
  10699.         if (flag == 0) {        /* Find the Start-Of-Packet. */
  10700.         if ((n & sopmask) == start) { /* Got it */
  10701.             flag = 1;
  10702.         } else {        /* Keep looking... */
  10703.             debug(F000,"ttinl skipping","",n);
  10704.             continue;
  10705.         }
  10706.         }
  10707.         dest[i++] = n & ttpmsk;
  10708. /*
  10709.   If we have not been instructed to wait for a turnaround character, we
  10710.   can go by the packet length field.  If turn != 0, we must wait for the
  10711.   end of line (eol) character before returning.  This is an egregious
  10712.   violation of all principles of layering...
  10713. */
  10714.         if (!havelen) {
  10715.         if (i == 2) {
  10716.             pktlen = xunchar(dest[1] & 0x7f);
  10717.             if (pktlen > 1) {
  10718.             havelen = 1;
  10719.             debug(F101,"ttinl length","",pktlen);
  10720.             }
  10721.         } else if (i == 5 && pktlen == 0) {
  10722.             lplen = xunchar(dest[4] & 0x7f);
  10723.         } else if (i == 6 && pktlen == 0) {
  10724.             pktlen = lplen * 95 + xunchar(dest[5] & 0x7f) + 5;
  10725.             havelen = 1;
  10726.             debug(F101,"ttinl extended length","",pktlen);
  10727.         }
  10728.         }
  10729.  
  10730. /*
  10731.   Suppose we looked at the sequence number here and found it was out of
  10732.   range?  This would mean either (a) incoming packets had SOP unprefixed
  10733.   and we are out of sync, or (b) the packet is damaged.  Since (a) is bad
  10734.   practice, let's ignore it.  So what should we do here if we know the
  10735.   packet is damaged?
  10736.  
  10737.    1. Nothing -- keep trying to read the packet till we find what we think
  10738.       is the end, or we time out, and let the upper layer decide what to
  10739.       do.  But since either the packet is corrupt or we are out of sync,
  10740.       our criterion for finding the end does not apply and we are likely
  10741.       to time out (or swallow a piece of the next packet) if our assumed
  10742.       length is too long.  (This was the behavior prior to version 7.0.)
  10743.  
  10744.    2. set flag = 0 and continue?  This would force us to wait for the
  10745.       next packet to come in, and therefore (in the nonwindowing case),
  10746.       would force a timeout in the other Kermit.
  10747.  
  10748.    3. set flag = 0 and continue, but only if the window size is > 1 and
  10749.       the window is not blocked?  Talk about cheating!
  10750.  
  10751.    4. Return a failure code and let the upper layer decide what to do.
  10752.       This should be equivalent to 3, but without the cheating.  So let's
  10753.       do it that way...  But note that we must ignore the parity bit
  10754.       in case this is the first packet and we have not yet run parchk().
  10755. */
  10756.         if (i == 3) {        /* Peek at sequence number */
  10757.         x = xunchar((dest[i-1] & 0x7f)); /* If it's not in range... */
  10758.         if (x < 0 || x > 63) {
  10759.             debug(F111,"ttinl bad seq",dest,x);
  10760.             if (timo) ttimoff();
  10761.             return(-1);        /* return a nonfatal error */
  10762.         }
  10763.         }
  10764.  
  10765. #else /* PARSENSE */
  10766.         dest[i++] = n & ttpmsk;
  10767. #endif /* PARSENSE */
  10768.  
  10769.     /* Check for end of packet */
  10770.  
  10771.         if (
  10772. #ifdef PARSENSE
  10773. /*
  10774.   Purely length-driven if SET HANDSHAKE NONE (i.e. turn == 0).
  10775.   This allows packet terminators and handshake characters to appear
  10776.   literally inside a packet data field.
  10777. */
  10778.         (havelen && (i > pktlen+1) &&
  10779.          (!turn || (turn && (n & 0x7f) == turn))) /* (turn, not eol) */
  10780. #else /* !PARSENSE */
  10781. /*
  10782.   Built without PARSENSE, so just look for packet terminator.
  10783. */
  10784.         ((n & 0x7f) == eol)
  10785. #endif /* PARSENSE */
  10786.         ) {
  10787. #ifndef PARSENSE
  10788.         debug(F101,"ttinl got eol","",eol); /* (or turn) */
  10789.         dest[i] = '\0';        /* Yes, terminate the string, */
  10790.         /* debug(F101,"ttinl i","",i); */
  10791. #else
  10792. #ifdef DEBUG
  10793.         if (deblog) {
  10794.             if ((n & 0x7f) != eol) {
  10795.             debug(F101,"ttinl EOP length","",pktlen);
  10796.             debug(F101,"ttinl i","",i);
  10797. #ifdef MYREAD
  10798. #ifdef PARSENSE
  10799. /*
  10800.   We read a packet based on its length.  This leaves the EOP character still
  10801.   unread, and so ttchk() will always return at least 1 because of this.  But
  10802.   if we know it is there, we can safely get rid of it.  So...
  10803. */
  10804.             {
  10805.                 int x;
  10806.                 while (my_count > 0) {
  10807.                 x = ttinc(0);
  10808.                 /* Start of next packet */
  10809.                 if (x == start) { /* Save for next time */
  10810.                     csave = (unsigned)((unsigned)x & 0xff);
  10811.                     debug(F000,"ttinl csaved","",x);
  10812.                     break;
  10813.                 }
  10814.                 debug(F000,"ttinl removed","",x);
  10815.                 }
  10816.             }
  10817. #endif /* PARSENSE */
  10818. #endif /* MYREAD */
  10819.  
  10820.             } else debug(F101,"ttinl got eol","",eol); /* (or turn) */
  10821.         }
  10822. #endif /* DEBUG */
  10823.         dest[i] = '\0';        /* Terminate the string, */
  10824.             if (needpchk) {        /* Parity checked yet? */
  10825.             if (ttprty == 0) {    /* No, check. */
  10826.             if ((ttprty = parchk(dest,start,i)) > 0) {
  10827.                 int j;
  10828.                 debug(F101,"ttinl senses parity","",ttprty);
  10829.                 debug(F110,"ttinl packet before",dest,0);
  10830.                 ttpmsk = 0x7f;
  10831.                 for (j = 0; j < i; j++)
  10832.                   dest[j] &= 0x7f;    /* Strip parity from packet */
  10833.                 debug(F110,"ttinl packet after ",dest,0);
  10834.             } else ttprty = 0; /* Restore if parchk error */
  10835.             }
  10836.             sopmask = ttprty;
  10837.             needpchk = 0;
  10838.         }
  10839. #endif /* PARSENSE */
  10840.         if (timo) {        /* Turn off timer. */
  10841.             ttimoff();
  10842.         }
  10843. #ifdef COMMENT
  10844.         debug(F011,"ttinl got", dest, (i < 60) ? i : -60);
  10845. #else /* COMMENT */
  10846.                 hexdump("ttinl got",dest,i);
  10847. #endif /* COMMENT */
  10848. #ifdef STREAMING
  10849.         /* ttinl() was called because there was non-packet */
  10850.         /* data sitting int the channel.  Ignore it.       */
  10851.         if (streaming && sndtyp == 'D')
  10852.           return(-1);
  10853. #endif /* STREAMING */
  10854.         return(i);
  10855.         }
  10856.     } /* End of while() */
  10857.     ttimoff();
  10858.     return(n);
  10859.     }
  10860. }
  10861. #endif /* NOXFER */
  10862.  
  10863. /*  T T I N C --  Read a character from the communication line  */
  10864. /*
  10865.  On success, returns the character that was read, >= 0.
  10866.  On failure, returns -1 or other negative myread error code,
  10867.    or -2 if connection is broken or ttyfd < 0.
  10868.    or -3 if session limit has expired,
  10869.    or -4 if something or other...
  10870.  NOTE: The API does not provide for ttinc() returning a special code
  10871.  upon timeout, but we need it.  So for this we have a global variable,
  10872.  ttinctimo.
  10873. */
  10874. static int ttinctimo = 0;        /* Yuk */
  10875.  
  10876. int
  10877. ttinc(timo) int timo; {
  10878.  
  10879.     int n = 0, fd;
  10880.     int is_tn = 0;
  10881.     CHAR ch = 0;
  10882.  
  10883.     ttinctimo = 0;
  10884.  
  10885.     if (ttyfd < 0) return(-2);          /* Not open. */
  10886.  
  10887.     is_tn = (xlocal && netconn && IS_TELNET()) ||
  10888.         (!xlocal && sstelnet);
  10889.  
  10890. #ifdef TTLEBUF
  10891.     if (ttpush >= 0) {
  10892.         debug(F111,"ttinc","ttpush",ttpush);
  10893.         ch = ttpush;
  10894.         ttpush = -1;
  10895.         return(ch);
  10896.     }
  10897.     if (le_data) {
  10898.         if (le_getchar(&ch) > 0) {
  10899.             debug(F111,"ttinc le_getchar","ch",ch);
  10900.             return(ch);
  10901.         }
  10902.     }
  10903. #endif /* TTLEBUF */
  10904.  
  10905. #ifdef NETCMD
  10906.     if (ttpipe)
  10907.       fd = fdin;
  10908.     else
  10909. #endif /* NETCMD */
  10910.       fd = ttyfd;
  10911.  
  10912.     if ((timo <= 0)            /* Untimed. */
  10913. #ifdef MYREAD
  10914.     || (my_count > 0)        /* Buffered char already waiting. */
  10915. #endif /* MYREAD */
  10916.     ) {
  10917. #ifdef MYREAD
  10918.         /* Comm line failure returns -1 thru myread, so no &= 0377 */
  10919.     n = myread();            /* Wait for a character... */
  10920.     /* debug(F000,"ttinc MYREAD n","",n); */
  10921. #ifdef CK_ENCRYPTION
  10922.     /* debug(F101,"ttinc u_encrypt","",TELOPT_U(TELOPT_ENCRYPTION)); */
  10923.     if (TELOPT_U(TELOPT_ENCRYPTION) && n >= 0) {
  10924.         ch = n;
  10925.         ck_tn_decrypt(&ch,1);
  10926.         n = ch;
  10927.     }
  10928. #endif /* CK_ENCRYPTION */
  10929.  
  10930. #ifdef NETPTY
  10931.     if (ttpty && n < 0) {
  10932.         debug(F101,"ttinc error on pty","",n);
  10933.         ttclos(0);
  10934.         return(n);
  10935.     }
  10936. #endif /* NETPTY */
  10937.  
  10938. #ifdef TNCODE
  10939.     if ((n > -1) && is_tn)
  10940.       return((unsigned)(n & 0xff));
  10941.     else
  10942. #endif /* TNCODE */
  10943.       return(n < 0 ? n : (unsigned)(n & ttpmsk));
  10944.  
  10945. #else  /* MYREAD */
  10946.  
  10947.         while ((n = read(fd,&ch,1)) == 0) /* Wait for a character. */
  10948.         /* Shouldn't have to loop in ver 5A. */
  10949. #ifdef NETCONN
  10950.       if (netconn) {        /* Special handling for net */
  10951.           netclos();        /* If read() returns 0 it means */
  10952.           netconn = 0;        /* the connection has dropped. */
  10953.           errno = ENOTCONN;
  10954.           return(-2);
  10955.       }
  10956. #endif /* NETCONN */
  10957.       ;
  10958.     /* debug(F101,"ttinc","",ch); */
  10959. #ifdef TNCODE
  10960.     if ((n > 0) && is_tn) {
  10961. #ifdef CK_ENCRYPTION
  10962.         if (TELOPT_U(TELOPT_ENCRYPTION)) {
  10963.         ck_tn_decrypt(&ch,1);
  10964.         n = ch;
  10965.         }
  10966. #endif /* CK_ENCRYPTION */
  10967.         return((unsigned)(ch & 0xff));
  10968.     } else
  10969. #endif /* TNCODE */
  10970.         return((n < 0) ? -4 : ((n == 0) ? -1 : (unsigned)(ch & ttpmsk)));
  10971. #endif /* MYREAD */
  10972.  
  10973.     } else {                /* Timed read */
  10974.  
  10975.     int oldalarm;
  10976.     saval = signal(SIGALRM,timerh);    /* Set up handler, save old one. */
  10977.     oldalarm = alarm(timo);        /* Set alarm, save old one. */
  10978.     if (
  10979. #ifdef CK_POSIX_SIG
  10980.         sigsetjmp(sjbuf,1)
  10981. #else
  10982.         setjmp(sjbuf)
  10983. #endif /* CK_POSIX_SIG */
  10984.         ) {                /* Timer expired */
  10985.         ttinctimo = 1;
  10986.         n = -1;            /* set flag */
  10987.     } else {
  10988. #ifdef MYREAD
  10989.         n = myread();        /* If managing own buffer... */
  10990.         debug(F101,"ttinc myread","",n);
  10991.         ch = n;
  10992. #else
  10993.         n = read(fd,&ch,1);        /* Otherwise call the system. */
  10994.         if (n == 0) n = -1;
  10995.         debug(F101,"ttinc read","",n);
  10996. #endif /* MYREAD */
  10997.  
  10998. #ifdef CK_ENCRYPTION
  10999.         if (TELOPT_U(TELOPT_ENCRYPTION) && n >= 0) {
  11000.         ck_tn_decrypt(&ch,1);
  11001.         }
  11002. #endif /* CK_ENCRYPTION */
  11003.         if (n >= 0)
  11004.           n = (unsigned) (ch & 0xff);
  11005.         else
  11006.           n = (n < 0) ? -4 : -2;    /* Special return codes. */
  11007.     }
  11008.     ttimoff();            /* Turn off the timer */
  11009.     if (oldalarm > 0) {
  11010.         if (n == -1)        /* and restore any previous alarm */
  11011.           oldalarm -= timo;
  11012.         if (oldalarm < 0)        /* adjusted by our timeout interval */
  11013.           oldalarm = 0;
  11014.         if (oldalarm) {
  11015.             debug(F101,"ttinc restoring oldalarm","",oldalarm);
  11016.         alarm(oldalarm);
  11017.         }
  11018.     }
  11019. #ifdef NETCONN
  11020.     if (netconn) {
  11021.         if (n == -2) {        /* read() returns 0 */
  11022.         netclos();        /* on network read failure */
  11023.         netconn = 0;
  11024.         errno = ENOTCONN;
  11025.         }
  11026.     }
  11027. #endif    /* NETCONN */
  11028. #ifdef TNCODE
  11029.     if ((n > -1) && is_tn)
  11030.       return((unsigned)(n & 0xff));
  11031.     else
  11032. #endif /* TNCODE */
  11033.       /* Return masked char or neg. */
  11034.       return( (n < 0) ? n : (unsigned)(n & ttpmsk) );
  11035.     }
  11036. }
  11037.  
  11038. /*  S N D B R K  --  Send a BREAK signal of the given duration  */
  11039.  
  11040. static int
  11041. #ifdef CK_ANSIC
  11042. sndbrk(int msec) {            /* Argument is milliseconds */
  11043. #else
  11044. sndbrk(msec) int msec; {
  11045. #endif /* CK_ANSIC */
  11046. #ifndef POSIX
  11047.     int x, n;
  11048. #endif /* POSIX */
  11049.  
  11050. #ifdef OXOS
  11051. #define BSDBREAK
  11052. #endif /* OXOS */
  11053.  
  11054. #ifdef ANYBSD
  11055. #define BSDBREAK
  11056. #endif /* ANYBSD */
  11057.  
  11058. #ifdef BSD44
  11059. #define BSDBREAK
  11060. #endif /* BSD44 */
  11061.  
  11062. #ifdef COHERENT
  11063. #ifdef BSDBREAK
  11064. #undef BSDBREAK
  11065. #endif /* BSDBREAK */
  11066. #endif /* COHERENT */
  11067.  
  11068. #ifdef BELLV10
  11069. #ifdef BSDBREAK
  11070. #undef BSDBREAK
  11071. #endif /* BSDBREAK */
  11072. #endif /* BELLV10 */
  11073.  
  11074. #ifdef PROVX1
  11075.     char spd;
  11076. #endif /* PROVX1 */
  11077.  
  11078.     debug(F101,"ttsndb ttyfd","",ttyfd);
  11079.     if (ttyfd < 0) return(-1);          /* Not open. */
  11080.  
  11081. #ifdef Plan9
  11082.     return p9sndbrk(msec);
  11083. #else
  11084. #ifdef NETCONN
  11085. #ifdef NETCMD
  11086.     if (ttpipe)                /* Pipe */
  11087.       return(ttoc('\0'));
  11088. #endif /* NETCMD */
  11089. #ifdef NETPTY
  11090.     if (ttpty)
  11091.       return(ttoc('\0'));
  11092. #endif /* NETPTY */
  11093.     if (netconn)             /* Send network BREAK */
  11094.       return(netbreak());
  11095. #endif /* NETCONN */
  11096.  
  11097.     if (msec < 1 || msec > 5000) return(-1); /* Bad argument */
  11098.  
  11099. #ifdef POSIX                /* Easy in POSIX */
  11100.     {
  11101.     int x;
  11102.     debug(F111,"sndbrk POSIX",ckitoa(msec),(msec/375));
  11103.     errno = 0;
  11104.     x = tcsendbreak(ttyfd,msec / 375);
  11105.     debug(F111,"sndbrk tcsendbreak",ckitoa(errno),x);
  11106.     return(x);
  11107.     }
  11108. #else
  11109. #ifdef PROVX1
  11110.     gtty(ttyfd,&ttbuf);                 /* Get current tty flags */
  11111.     spd = ttbuf.sg_ospeed;              /* Save speed */
  11112.     ttbuf.sg_ospeed = B50;              /* Change to 50 baud */
  11113.     stty(ttyfd,&ttbuf);                 /*  ... */
  11114.     n = (int)strlen(brnuls);        /* Send the right number of nulls */
  11115.     x = msec / 91;
  11116.     if (x > n) x = n;
  11117.     write(ttyfd,brnuls,n);
  11118.     ttbuf.sg_ospeed = spd;              /* Restore speed */
  11119.     stty(ttyfd,&ttbuf);                 /*  ... */
  11120.     return(0);
  11121. #else
  11122. #ifdef aegis
  11123.     sio_$control((short)ttyfd, sio_$send_break, msec, st);
  11124.     return(0);
  11125. #else
  11126. #ifdef BSDBREAK
  11127.     n = FWRITE;                         /* Flush output queue. */
  11128. /* Watch out for int vs long problems in &n arg! */
  11129.     debug(F101,"sndbrk BSDBREAK","",msec);
  11130.     ioctl(ttyfd,TIOCFLUSH,&n);          /* Ignore any errors.. */
  11131.     if (ioctl(ttyfd,TIOCSBRK,(char *)0) < 0) {  /* Turn on BREAK */
  11132.         perror("Can't send BREAK");
  11133.         return(-1);
  11134.     }
  11135.     x = msleep(msec);                    /* Sleep for so many milliseconds */
  11136.     if (ioctl(ttyfd,TIOCCBRK,(char *)0) < 0) {  /* Turn off BREAK */
  11137.         perror("BREAK stuck!!!");
  11138.         doexit(BAD_EXIT,-1);        /* Get out, closing the line. */
  11139.                                         /*   with bad exit status */
  11140.     }
  11141.     return(x);
  11142. #else
  11143. #ifdef ATTSV
  11144. /*
  11145.   No way to send a long BREAK in Sys V, so send a bunch of regular ones.
  11146.   (Actually, Sys V R4 is *supposed* to have the POSIX tcsendbreak() function,
  11147.   but there's no way for this code to know for sure.)
  11148. */
  11149.     debug(F101,"sndbrk ATTSV","",msec);
  11150.     x = msec / 275;
  11151.     for (n = 0; n < x; n++) {
  11152.     /* Reportedly the cast breaks this function on some systems */
  11153.     /* But then why was it here in the first place? */
  11154.     if (ioctl(ttyfd,TCSBRK, /* (char *) */ 0) < 0) {
  11155.         perror("Can't send BREAK");
  11156.         return(-1);
  11157.     }
  11158.     }
  11159.     return(0);
  11160. #else
  11161. #ifdef  V7
  11162.     debug(F101,"sndbrk V7","",msec);
  11163.     return(genbrk(ttyfd,250));        /* Simulate a BREAK */
  11164. #else
  11165.     debug(F101,"sndbrk catchall","",msec);
  11166.     ttoc(0);ttoc(0);ttoc(0);ttoc(0);
  11167.     return(0);
  11168. #endif /* V7 */
  11169. #endif /* BSDBREAK */
  11170. #endif /* ATTSV */
  11171. #endif /* aegis */
  11172. #endif /* PROVX1 */
  11173. #endif /* POSIX */
  11174. #endif /* Plan9 */
  11175. }
  11176.  
  11177. /*  T T S N D B  --  Send a BREAK signal  */
  11178.  
  11179. int
  11180. ttsndb() {
  11181. #ifdef TN_COMPORT
  11182.     if (netconn && istncomport())
  11183.       return((tnsndb(275L) >= 0) ? 0 : -1);
  11184.     else
  11185. #endif /* TN_COMPORT */
  11186.       return(sndbrk(275));
  11187. }
  11188.  
  11189. /*  T T S N D L B  --  Send a Long BREAK signal  */
  11190.  
  11191. int
  11192. ttsndlb() {
  11193. #ifdef TN_COMPORT
  11194.     if (netconn && istncomport())
  11195.       return((tnsndb(1800L) >= 0) ? 0 : -1);
  11196.     else
  11197. #endif /* TN_COMPORT */
  11198.     return(sndbrk(1500));
  11199. }
  11200.  
  11201. /*  M S L E E P  --  Millisecond version of sleep().  */
  11202.  
  11203. /*
  11204.   Call with number of milliseconds (thousandths of seconds) to sleep.
  11205.   Intended only for small intervals.  For big ones, just use sleep().
  11206.   Highly system-dependent.
  11207.   Returns 0 always, even if it didn't work.
  11208. */
  11209.  
  11210. /* Define MSLFTIME for systems that must use an ftime() loop. */
  11211. #ifdef ANYBSD                /* For pre-4.2 BSD versions */
  11212. #ifndef BSD4
  11213. #define MSLFTIME
  11214. #endif /* BSD4 */
  11215. #endif /* ANYBSD */
  11216.  
  11217. #ifdef TOWER1                /* NCR Tower OS 1.0 */
  11218. #define MSLFTIME
  11219. #endif /* TOWER1 */
  11220.  
  11221. #ifdef COHERENT         /* Coherent... */
  11222. #ifndef _I386           /* Maybe Coherent/386 should get this, too */
  11223. #define MSLFTIME        /* Opinions are divided */
  11224. #endif /* _I386 */
  11225. #endif /* COHERENT */
  11226.  
  11227. #ifdef COMMENT
  11228. #ifdef GETMSEC
  11229.  
  11230. /* Millisecond timer */
  11231.  
  11232. static long msecbase = 0L;        /* Unsigned long not portable */
  11233.  
  11234. long
  11235. getmsec() {                /* Milliseconds since base time */
  11236.     struct timeval xv;
  11237.     struct timezone xz;
  11238.     long secs, msecs;
  11239.     if (
  11240. #ifdef GTODONEARG
  11241.     gettimeofday(&tv)
  11242. #else
  11243. #ifdef PTX
  11244.     gettimeofday(&tv, NULL)
  11245. #else
  11246.     gettimeofday(&tv, &tz)
  11247. #endif /* PTX */
  11248. #endif /* GTODONEARG */
  11249.     < 0)
  11250.       return(-1);
  11251.     if (msecbase == 0L) {        /* First call, set base time. */
  11252.     msecbase = tv.tv_sec;
  11253.     debug(F101,"getmsec base","",msecbase);
  11254.     }
  11255.     return(((tv.tv_sec - msecbase) * 1000L) + (tv.tv_usec / 1000L));
  11256. }
  11257. #endif /* GETMSEC */
  11258. #endif /* COMMENT */
  11259.  
  11260. #ifdef SELECT
  11261. int
  11262. ttwait(fd, secs) int fd, secs; {
  11263.     int x;
  11264.     fd_set rfds;
  11265.     FD_ZERO(&rfds);
  11266.     FD_SET(fd,&rfds);
  11267.     tv.tv_sec = secs;
  11268.     tv.tv_usec = 0L;
  11269.     errno = 0;
  11270.     if ((x = select(FD_SETSIZE,
  11271. #ifdef HPUX9
  11272.             (int *)
  11273. #else
  11274. #ifdef HPUX1000
  11275.             (int *)
  11276. #endif /* HPUX1000 */
  11277. #endif /* HPUX9 */
  11278.             &rfds,
  11279.             0, 0, &tv)) < 0) {
  11280.     debug(F101,"ttwait select errno","",errno);
  11281.     return(0);
  11282.     } else {
  11283.     debug(F101,"ttwait OK","",errno);
  11284.     x = FD_ISSET(fd, &rfds);
  11285.     debug(F101,"ttwait select x","",x);
  11286.     return(x ? 1 : 0);
  11287.     }
  11288. }
  11289. #endif /* SELECT */
  11290.  
  11291. int
  11292. msleep(m) int m; {
  11293. /*
  11294.   Other possibilities here are:
  11295.    nanosleep(), reportedly defined in POSIX.4.
  11296.    sginap(), IRIX only (back to what IRIX version I don't know).
  11297. */
  11298. #ifdef Plan9
  11299.     return _SLEEP(m);
  11300. #else
  11301. #ifdef BEOSORBEBOX
  11302.     snooze(m*1000);
  11303. #else /* BEOSORBEBOX */
  11304. #ifdef SELECT
  11305.     int t1, x;
  11306.     debug(F101,"msleep SELECT 1","",m);
  11307.     if (m <= 0) return(0);
  11308.     if (m >= 1000) {            /* Catch big arguments. */
  11309.     sleep(m/1000);
  11310.     m = m % 1000;
  11311.     if (m < 10) return(0);
  11312.     }
  11313.     debug(F101,"msleep SELECT 2","",m);
  11314. #ifdef BELLV10
  11315.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, m );
  11316.     debug(F101,"msleep BELLV10 select","",x);
  11317. #else /* BELLV10 */
  11318. #ifdef HPUX9
  11319.     gettimeofday(&tv, &tz);
  11320. #else
  11321.  
  11322. #ifndef COHERENT
  11323. #ifdef GTODONEARG
  11324.     if (gettimeofday(&tv) < 0)
  11325. #else
  11326. #ifdef PTX
  11327.     if (gettimeofday(&tv,NULL) < 0)
  11328. #else
  11329. #ifdef NOTIMEZONE
  11330.     if (gettimeofday(&tv, NULL) < 0)    /* wonder what this does... */
  11331. #else
  11332.     if (gettimeofday(&tv, &tz) < 0)
  11333. #endif /* NOTIMEZONE */
  11334. #endif /* PTX */
  11335. #endif /* GTODONEARG */
  11336.       return(-1);
  11337.     t1 = tv.tv_sec;                     /* Seconds */
  11338. #endif /* COHERENT */
  11339. #endif /* HPUX9 */
  11340.     tv.tv_sec = 0;                      /* Use select() */
  11341.     tv.tv_usec = m * 1000L;
  11342. #ifdef BSD44
  11343.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11344.     debug(F101,"msleep BSD44 select","",x);
  11345. #else /* BSD44 */
  11346. #ifdef __linux__
  11347.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11348.     debug(F101,"msleep __linux__ select","",x);
  11349. #else /* __linux__ */
  11350. #ifdef BSD43
  11351.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11352.     debug(F101,"msleep BSD43 select","",x);
  11353. #else /* BSD43 */
  11354. #ifdef QNX6
  11355.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11356.     debug(F101,"msleep QNX6 select","",x);
  11357. #else /* QNX6 */
  11358. #ifdef QNX
  11359.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11360.     debug(F101,"msleep QNX select","",x);
  11361. #else /* QNX */
  11362. #ifdef COHERENT
  11363.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11364.     debug(F101,"msleep COHERENT select","",x);
  11365. #else /* COHERENT */
  11366. #ifdef HPUX1000                /* 10.00 only, not 10.10 or later */
  11367.     x = select( 0, (int *)0, (int *)0, (int *)0, &tv );
  11368.     debug(F101,"msleep HP-UX 10.00 select","",x);
  11369. #else /* HPUX1000 */
  11370. #ifdef SVR4
  11371.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11372.     debug(F101,"msleep SVR4 select","",x);
  11373. #else /* SVR4 */
  11374. #ifdef OSF40
  11375.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11376.     debug(F101,"msleep OSF40 select","",x);
  11377. #else /* OSF40 */
  11378. #ifdef PTX
  11379.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11380.     debug(F101,"msleep OSF40 select","",x);
  11381. #else
  11382.     x = select( 0, (int *)0, (int *)0, (int *)0, &tv );
  11383.     debug(F101,"msleep catch-all select","",x);
  11384. #endif /* PTX */
  11385. #endif /* OSF40 */
  11386. #endif /* HP1000 */
  11387. #endif /* SVR4 */
  11388. #endif /* COHERENT */
  11389. #endif /* QNX */
  11390. #endif /* QNX6 */
  11391. #endif /* BSD43 */
  11392. #endif /* __linux__ */
  11393. #endif /* BSD44 */
  11394. #endif /* BELLV10 */
  11395.     return(0);
  11396.  
  11397. #else                    /* Not SELECT */
  11398. #ifdef CK_POLL                /* We have poll() */
  11399.     struct pollfd pfd;            /* Supply a valid address for poll() */
  11400.  
  11401. #ifdef ODT30                /* But in SCO ODT 3.0 */
  11402. #ifdef NAP                /* we should use nap() instead */
  11403.     debug(F101,"msleep ODT 3.0 NAP","",m); /* because using poll() here */
  11404.     nap((long)m);               /* seems to break dialing. */
  11405.     return(0);
  11406. #else
  11407.     debug(F101,"msleep ODT 3.0 POLL","",m);
  11408.     poll(&pfd, 0, m);
  11409.     return(0);
  11410. #endif /* NAP */
  11411. #else
  11412.     debug(F101,"msleep POLL","",m);
  11413.     poll(&pfd, 0, m);
  11414.     return(0);
  11415. #endif /* ODT30 */
  11416.  
  11417. /*
  11418.   We could handle the above more cleanly by just letting nap() always
  11419.   take precedence over poll() in this routine, but there is no way to know
  11420.   whether that would break something else.
  11421. */
  11422.  
  11423. #else                    /* Not POLL */
  11424. #ifdef USLEEP
  11425. /*
  11426.   "This routine is implemented using setitimer(2); it requires eight
  11427.   system calls...".  In other words, it might take 5 minutes to sleep
  11428.   10 milliseconds...
  11429. */
  11430.     debug(F101,"msleep USLEEP","",m);
  11431.     if (m >= 1000) {            /* Catch big arguments. */
  11432.     sleep(m/1000);
  11433.     m = m % 1000;
  11434.     if (m < 10) return(0);
  11435.     }
  11436.     usleep((unsigned int)(m * 1000));
  11437.     return(0);
  11438. #else
  11439. #ifdef aegis
  11440.     time_$clock_t dur;
  11441.     debug(F101,"msleep aegis","",m);
  11442.     dur.c2.high16 = 0;
  11443.     dur.c2.low32  = 250 * m; /* one millisecond = 250 four microsecond ticks */
  11444.     time_$wait(time_$relative, dur, st);
  11445.     return(0);
  11446. #else
  11447. #ifdef PROVX1
  11448.     debug(F101,"msleep Venix","",m);
  11449.     if (m <= 0) return(0);
  11450.     sleep(-((m * 60 + 500) / 1000));
  11451.     return(0);
  11452. #else
  11453. #ifdef NAP
  11454.     debug(F101,"msleep NAP","",m);
  11455.     nap((long)m);
  11456.     return(0);
  11457. #else
  11458. #ifdef ATTSV
  11459. #ifndef BSD44
  11460.     extern long times();        /* Or #include <times.h> ? */
  11461. #endif /* BSD44 */
  11462.     long t1, t2, tarray[4];
  11463.     int t3;
  11464.     char *cp = getenv("HZ");
  11465.     int CLOCK_TICK;
  11466.     int hertz;
  11467.  
  11468.     if (cp && (hertz = atoi(cp))) {
  11469.         CLOCK_TICK  = 1000 / hertz;
  11470.     } else {                /* probably single user mode */
  11471. #ifdef HZ
  11472.         CLOCK_TICK  = 1000 / HZ;
  11473. #else
  11474.     static warned = 0;
  11475.     /* HZ always exists in, for instance, SCO Xenix, so you don't have to
  11476.      * make special #ifdefs for XENIX here, like in ver 4F. Also, if you
  11477.      * have Xenix, you have should have nap(), so the best is to use -DNAP
  11478.      * in the makefile. Most systems have HZ.
  11479.      */
  11480.     CLOCK_TICK = 17;        /* 1/60 sec */
  11481.     if (!warned) {
  11482.           printf("warning: environment variable HZ bad... using HZ=%d\r\n",
  11483.          1000 / CLOCK_TICK);
  11484.           warned = 1;
  11485.     }
  11486. #endif /* !HZ */
  11487.     }
  11488.     debug(F101,"msleep ATTSV","",m);
  11489.     if (m <= 0) return(0);
  11490.     if (m >= 1000) {            /* Catch big arguments. */
  11491.     sleep(m/1000);
  11492.     m = m % 1000;
  11493.     if (m < 10) return(0);
  11494.     }
  11495.     if ((t1 = times(tarray)) < 0) return(-1);
  11496.     while (1) {
  11497.         if ((t2 = times(tarray)) < 0) return(-1);
  11498.         t3 = ((int)(t2 - t1)) * CLOCK_TICK;
  11499.         if (t3 > m) return(t3);
  11500.     }
  11501. #else /* Not ATTSV */
  11502. #ifdef MSLFTIME                /* Use ftime() loop... */
  11503.     int t1, t3 = 0;
  11504.     debug(F101,"msleep MSLFTIME","",m);
  11505.     if (m <= 0) return(0);
  11506.     if (m >= 1000) {            /* Catch big arguments. */
  11507.     sleep(m/1000);
  11508.     m = m % 1000;
  11509.     if (m < 10) return(0);
  11510.     }
  11511. #ifdef QNX
  11512.     ftime(&ftp);            /* void ftime() in QNX */
  11513. #else
  11514.     if (ftime(&ftp) < 0) return(-1);    /* Get base time. */
  11515. #endif /* QNX */
  11516.     t1 = ((ftp.time & 0xff) * 1000) + ftp.millitm;
  11517.     while (1) {
  11518.         ftime(&ftp);            /* Get current time and compare. */
  11519.         t3 = (((ftp.time & 0xff) * 1000) + ftp.millitm) - t1;
  11520.         if (t3 > m) return(0);
  11521.     }
  11522. #else
  11523. /* This includes true POSIX, which has no way to do this. */
  11524.     debug(F101,"msleep busy loop","",m);
  11525.     if (m >= 1000) {            /* Catch big arguments. */
  11526.     sleep(m/1000);
  11527.     m = m % 1000;
  11528.     if (m < 10) return(0);
  11529.     }
  11530.     if (m > 0) while (m > 0) m--;    /* Just a dumb busy loop */
  11531.     return(0);
  11532. #endif /* MSLFTIME */
  11533. #endif /* ATTSV */
  11534. #endif /* NAP */
  11535. #endif /* PROVX1 */
  11536. #endif /* aegis */
  11537. #endif /* CK_POLL */
  11538. #endif /* SELECT */
  11539. #endif /* BEOSORBEBOX */
  11540. #endif /* USLEEP */
  11541. #endif /* Plan9 */
  11542. }
  11543.  
  11544. /*  R T I M E R --  Reset elapsed time counter  */
  11545.  
  11546. VOID
  11547. rtimer() {
  11548.     tcount = time( (time_t *) 0 );
  11549. }
  11550.  
  11551.  
  11552. /*  G T I M E R --  Get current value of elapsed time counter in seconds  */
  11553.  
  11554. int
  11555. gtimer() {
  11556.     int x;
  11557.     x = (int) (time( (time_t *) 0 ) - tcount);
  11558.     debug(F101,"gtimer","",x);
  11559.     return( (x < 0) ? 0 : x );
  11560. }
  11561.  
  11562. #ifdef GFTIMER
  11563. /*
  11564.   Floating-point timers.  Require not only floating point support, but
  11565.   also gettimeofday().
  11566. */
  11567. static struct timeval tzero;
  11568.  
  11569. VOID
  11570. rftimer() {
  11571. #ifdef GTODONEARG    /* Account for Mot's definition */
  11572.     (VOID) gettimeofday(&tzero);
  11573. #else
  11574.     (VOID) gettimeofday(&tzero, (struct timezone *)0);
  11575. #endif /* GTODONEARG */
  11576. }
  11577.  
  11578. CKFLOAT
  11579. gftimer() {
  11580.     struct timeval tnow, tdelta;
  11581.     CKFLOAT s;
  11582. #ifdef DEBUG
  11583.     char fpbuf[64];
  11584. #endif /* DEBUG */
  11585. #ifdef GTODONEARG    /* Acount for Mot's definition */
  11586.     (VOID) gettimeofday(&tnow);
  11587. #else
  11588.     (VOID) gettimeofday(&tnow, (struct timezone *)0);
  11589. #endif /* GTODONEARG */
  11590.     tdelta.tv_sec = tnow.tv_sec - tzero.tv_sec;
  11591.     tdelta.tv_usec = tnow.tv_usec - tzero.tv_usec;
  11592.     if (tdelta.tv_usec < 0) {
  11593.     tdelta.tv_sec--;
  11594.     tdelta.tv_usec += 1000000;
  11595.     }
  11596.     s = (CKFLOAT) tdelta.tv_sec + ((CKFLOAT) tdelta.tv_usec / 1000000.0);
  11597.     if (s < GFMINTIME)
  11598.       s = GFMINTIME;
  11599. #ifdef DEBUG
  11600.     if (deblog) {
  11601.     sprintf(fpbuf,"%f",s);
  11602.     debug(F110,"gftimer",fpbuf,0);
  11603.     }
  11604. #endif /* DEBUG */
  11605.     return(s);
  11606. }
  11607. #endif /* GFTIMER */
  11608.  
  11609. /*  Z T I M E  --  Return asctime()-format date/time string  */
  11610. /*
  11611.   NOTE: as a side effect of calling this routine, we can also set the
  11612.   following two variables, giving the micro- and milliseconds (fractions of
  11613.   seconds) of the clock time.  Currently this is done only in BSD-based builds
  11614.   that use gettimeofday().  When these variables are not filled in, they are
  11615.   left with a value of -1L.
  11616. */
  11617. static char asctmbuf[64];
  11618.  
  11619. VOID
  11620. ztime(s) char **s; {
  11621.  
  11622. #ifdef GFTIMER
  11623. /*
  11624.   The gettimeofday() method, which also sets ztmsec and ztusec, works for
  11625.   all GFTIMER builds.  NOTE: ztmsec and ztusec are defined in ckcmai.c,
  11626.   and extern declarations for them are in ckcdeb.h; thus they are
  11627.   declared in this file by inclusion of ckcdeb.h.
  11628. */
  11629.     char *asctime();
  11630.     struct tm *localtime();
  11631.     struct tm *tp;
  11632.     ztmsec = -1L;
  11633.     ztusec = -1L;
  11634.  
  11635.     if (!s)
  11636.       debug(F100,"ztime s==NULL","",0);
  11637.  
  11638. #ifdef GTODONEARG
  11639.     /* No 2nd arg in Motorola SV88 and some others */
  11640.     if (gettimeofday(&tv) > -1)
  11641. #else
  11642. #ifndef COHERENT
  11643. #ifdef PTX
  11644.     if (gettimeofday(&tv,NULL) > -1)
  11645. #else
  11646. #ifdef NOTIMEZONE
  11647.     if (gettimeofday(&tv, NULL) > -1)    /* wonder what this does... */
  11648. #else
  11649.     if (gettimeofday(&tv, &tz) > -1)
  11650. #endif /* NOTIMEZONE */
  11651. #endif /* PTX */
  11652. #endif /* COHERENT */
  11653. #endif /* GTODONEARG */
  11654.       {                    /* Fill in tm struct */
  11655.     ztusec = tv.tv_usec;        /* Microseconds */
  11656.     ztmsec = ztusec / 1000L;    /* Milliseconds */
  11657. #ifdef HPUX9
  11658.     {
  11659.         time_t zz;
  11660.         zz = tv.tv_sec;
  11661.         tp = localtime(&zz);    /* Convert to local time */
  11662.     }
  11663. #else
  11664. #ifdef HPUX1000
  11665.     {
  11666.         time_t zz;
  11667.         zz = tv.tv_sec;
  11668.         tp = localtime(&zz);
  11669.     }
  11670. #else
  11671. #ifdef LINUX
  11672.     {   /* avoid unaligned access trap on 64-bit platforms */
  11673.         time_t zz;
  11674.         zz = tv.tv_sec;
  11675.         tp = localtime(&zz);
  11676.     }
  11677. #else
  11678. #ifdef MACOSX
  11679.     tp = localtime((time_t *)&tv.tv_sec); /* Convert to local time */
  11680. #else
  11681.     tp = localtime(&tv.tv_sec);
  11682. #endif /* MACOSX */
  11683. #endif /* LINUX */
  11684. #endif /* HPUX1000 */
  11685. #endif /* HPUX9 */
  11686.     if (s) {
  11687.         char * s2;
  11688.         s2 = asctime(tp);        /* Convert result to ASCII string */
  11689.         asctmbuf[0] = '\0';
  11690.         if (s2) ckstrncpy(asctmbuf,s2,64);
  11691.         *s = asctmbuf;
  11692.         debug(F111,"ztime GFTIMER gettimeofday",*s,ztusec);
  11693.     }
  11694.     }
  11695. #else  /* Not GFTIMER */
  11696.  
  11697. #undef ZTIMEV7                /* Which systems need to use */
  11698. #ifdef COHERENT                /* old UNIX Version 7 way... */
  11699. #define ZTIMEV7
  11700. #endif /* COHERENT */
  11701. #ifdef TOWER1
  11702. #define ZTIMEV7
  11703. #endif /* TOWER1 */
  11704. #ifdef ANYBSD
  11705. #ifndef BSD42
  11706. #define ZTIMEV7
  11707. #endif /* BSD42 */
  11708. #endif /* ANYBSD */
  11709. #ifdef V7
  11710. #ifndef MINIX
  11711. #define ZTIMEV7
  11712. #endif /* MINIX */
  11713. #endif /* V7 */
  11714. #ifdef POSIX
  11715. #define ZTIMEV7
  11716. #endif /* POSIX */
  11717.  
  11718. #ifdef HPUX1020
  11719. /*
  11720.   Prototypes are in <time.h>, included above.
  11721. */
  11722.     time_t clock_storage;
  11723.     clock_storage = time((void *) 0);
  11724.     if (s) {
  11725.     *s = ctime(&clock_storage);
  11726.     debug(F110,"ztime: HPUX 10.20",*s,0);
  11727.     }
  11728. #else
  11729. #ifdef ATTSV                /* AT&T way */
  11730. /*  extern long time(); */        /* Theoretically these should */
  11731.     char *ctime();            /* already been dcl'd in <time.h> */
  11732.     time_t clock_storage;
  11733.     clock_storage = time(
  11734. #ifdef IRIX60
  11735.              (time_t *)
  11736. #else
  11737. #ifdef BSD44
  11738.              (time_t *)
  11739. #else
  11740.              (long *)
  11741. #endif /* BSD44 */
  11742. #endif /* IRIX60 */
  11743.              0 );
  11744.     if (s) {
  11745.     *s = ctime( &clock_storage );
  11746.     debug(F110,"ztime: ATTSV",*s,0);
  11747.     }
  11748. #else
  11749. #ifdef PROVX1                /* Venix 1.0 way */
  11750.     int utime[2];
  11751.     time(utime);
  11752.     if (s) {
  11753.     *s = ctime(utime);
  11754.     debug(F110,"ztime: PROVX1",*s,0);
  11755.     }
  11756. #else
  11757. #ifdef BSD42                /* 4.2BSD way */
  11758.     char *asctime();
  11759.     struct tm *localtime();
  11760.     struct tm *tp;
  11761.     gettimeofday(&tv, &tz);
  11762.     ztusec = tv.tv_usec;
  11763.     ztmsec = tv.tv_usec / 1000L;
  11764.     tp = localtime(&tv.tv_sec);
  11765.     if (s) {
  11766.     *s = asctime(tp);
  11767.     debug(F111,"ztime: BSD42",*s,ztusec);
  11768.     }
  11769. #else
  11770. #ifdef MINIX                /* MINIX way */
  11771. #ifdef COMMENT
  11772.     extern long time();            /* Already got these from <time.h> */
  11773.     extern char *ctime();
  11774. #endif /* COMMENT */
  11775.     time_t utime[2];
  11776.     time(utime);
  11777.     if (s) {
  11778.     *s = ctime(utime);
  11779.     debug(F110,"ztime: MINIX",*s,0);
  11780.     }
  11781. #else
  11782. #ifdef ZTIMEV7                /* The regular way */
  11783.     char *asctime();
  11784.     struct tm *localtime();
  11785.     struct tm *tp;
  11786.     long xclock;            /* or unsigned long for BeBox? */
  11787.     time(&xclock);
  11788.     tp = localtime(&xclock);
  11789.     if (s) {
  11790.     *s = asctime(tp);
  11791.     debug(F110,"ztime: ZTIMEV7",*s,0);
  11792.     }
  11793. #else                    /* Catch-all for others... */
  11794.     if (s) {
  11795.     *s = "Day Mon 00 00:00:00 0000\n"; /* Dummy in asctime() format */
  11796.     debug(F110,"ztime: catch-all",*s,0);
  11797.     }
  11798. #endif /* ZTIMEV7 */
  11799. #endif /* MINIX */
  11800. #endif /* BSD42 */
  11801. #endif /* PROVX1 */
  11802. #endif /* ATTSV */
  11803. #endif /* HPUX1020 */
  11804. #endif /* GFTIMER */
  11805. }
  11806.  
  11807. /*  C O N G M  --  Get console terminal modes.  */
  11808.  
  11809. /*
  11810.   Saves initial console mode, and establishes variables for switching
  11811.   between current (presumably normal) mode and other modes.
  11812.   Should be called when program starts, but only after establishing
  11813.   whether program is in the foreground or background.
  11814.   Returns 1 if it got the modes OK, 0 if it did nothing, -1 on error.
  11815. */
  11816. int
  11817. congm() {
  11818.     int fd;
  11819.     if (backgrd || !isatty(0)) {    /* If in background. */
  11820.     cgmf = -1;            /* Don't bother, modes are garbage. */
  11821.     return(-1);
  11822.     }
  11823.     if (cgmf > 0) return(0);        /* Already did this. */
  11824.     debug(F100,"congm getting modes","",0); /* Need to do it. */
  11825. #ifdef aegis
  11826.     ios_$inq_type_uid(ios_$stdin, conuid, st);
  11827.     if (st.all != status_$ok) {
  11828.     fprintf(stderr, "problem getting stdin objtype: ");
  11829.     error_$print(st);
  11830.     }
  11831.     concrp = (conuid == mbx_$uid);
  11832.     conbufn = 0;
  11833. #endif /* aegis */
  11834.  
  11835. #ifndef BEBOX
  11836.     if ((fd = open(CTTNAM,2)) < 0) {    /* Open controlling terminal */
  11837. #ifdef COMMENT
  11838.     fprintf(stderr,"Error opening %s\n", CTTNAM);
  11839.     perror("congm");
  11840.     return(-1);
  11841. #else
  11842.     fd = 0;
  11843. #endif /* COMMENT */
  11844.     }
  11845. #else
  11846.     fd = 0;
  11847. #endif /* !BEBOX */
  11848. #ifdef BSD44ORPOSIX
  11849.     if (tcgetattr(fd,&ccold) < 0) return(-1);
  11850.     if (tcgetattr(fd,&cccbrk) < 0) return(-1);
  11851.     if (tcgetattr(fd,&ccraw) < 0) return(-1);
  11852. #else
  11853. #ifdef ATTSV
  11854.     if (ioctl(fd,TCGETA,&ccold)  < 0) return(-1);
  11855.     if (ioctl(fd,TCGETA,&cccbrk) < 0) return(-1);
  11856.     if (ioctl(fd,TCGETA,&ccraw)  < 0) return(-1);
  11857. #ifdef VXVE
  11858.     cccbrk.c_line = 0;            /* STTY line 0 for CDC VX/VE */
  11859.     if (ioctl(fd,TCSETA,&cccbrk) < 0) return(-1);
  11860.     ccraw.c_line = 0;            /* STTY line 0 for CDC VX/VE */
  11861.     if (ioctl(fd,TCSETA,&ccraw) < 0) return(-1);
  11862. #endif /* VXVE */
  11863. #else
  11864. #ifdef BELLV10
  11865.     if (ioctl(fd,TIOCGETP,&ccold) < 0) return(-1);
  11866.     if (ioctl(fd,TIOCGETP,&cccbrk) < 0) return(-1);
  11867.     if (ioctl(fd,TIOCGETP,&ccraw) < 0) return(-1);
  11868.     debug(F101,"cccbrk.sg_flags orig","", cccbrk.sg_flags);
  11869. #else
  11870.     if (gtty(fd,&ccold) < 0) return(-1);
  11871.     if (gtty(fd,&cccbrk) < 0) return(-1);
  11872.     if (gtty(fd,&ccraw) < 0) return(-1);
  11873. #endif /* BELLV10 */
  11874. #endif /* ATTSV */
  11875. #endif /* BSD44ORPOSIX */
  11876. #ifdef sony_news            /* Sony NEWS */
  11877.     if (ioctl(fd,TIOCKGET,&km_con) < 0) { /* Get console Kanji mode */
  11878.     perror("congm error getting Kanji mode");
  11879.     debug(F101,"congm error getting Kanji mode","",0);
  11880.     km_con = -1;            /* Make sure this stays undefined. */
  11881.     return(-1);
  11882.     }
  11883. #endif /* sony_news */
  11884.     if (fd > 0)
  11885.       close(fd);
  11886.     cgmf = 1;                /* Flag that we got them. */
  11887.     return(1);
  11888. }
  11889.  
  11890.  
  11891. static VOID
  11892. congetbuf(x) int x; {
  11893.     int n;
  11894.     n = CONBUFSIZ - (conbufp - conbuf);    /* How much room left in buffer? */
  11895.     if (x > n) {
  11896.     debug(F101,"congetbuf char loss","",x-n);
  11897.     x = n;
  11898.     }
  11899.     x = read(0,conbufp,x);
  11900.     conbufn += x;
  11901.     debug(F111,"congetbuf readahead",conbuf,x);
  11902. }
  11903.  
  11904.  
  11905. /*  C O N C B --  Put console in cbreak mode.  */
  11906.  
  11907. /*  Returns 0 if ok, -1 if not  */
  11908.  
  11909. int
  11910. #ifdef CK_ANSIC
  11911. concb(char esc)
  11912. #else
  11913. concb(esc) char esc;
  11914. #endif /* CK_ANSIC */
  11915. /* concb */ {
  11916.     int x;
  11917.     debug(F101,"concb constate","",constate);
  11918.     debug(F101,"concb cgmf","",cgmf);
  11919.     debug(F101,"concb backgrd","",backgrd);
  11920.  
  11921.     if (constate == CON_CB)
  11922.       return(0);
  11923.  
  11924.     if (cgmf < 1)            /* Did we get console modes yet? */
  11925.       if (!backgrd)            /* No, in background? */
  11926.     congm();            /* No, try to get them now. */
  11927.     if (cgmf < 1)            /* Still don't have them? */
  11928.       return(0);            /* Give up. */
  11929.     debug(F101,"concb ttyfd","",ttyfd);
  11930.     debug(F101,"concb ttfdflg","",ttfdflg);
  11931. #ifdef COMMENT
  11932.     /* This breaks returning to prompt after protocol with "-l 0" */
  11933.     /* Commented out July 1998 */
  11934.     if (ttfdflg && ttyfd >= 0 && ttyfd < 3)
  11935.       return(0);
  11936. #endif /* COMMENT */
  11937.     x = isatty(0);
  11938.     debug(F101,"concb isatty","",x);
  11939.     if (!x) return(0);            /* Only when running on real ttys */
  11940.     debug(F101,"concb suspend","",suspend);
  11941.     if (backgrd)            /* Do nothing if in background. */
  11942.       return(0);
  11943.     escchr = esc;                       /* Make this available to other fns */
  11944.     ckxech = 1;                         /* Program can echo characters */
  11945. #ifdef aegis
  11946.     conbufn = 0;
  11947.     if (concrp) return(write(1, "\035\002", 2));
  11948.     if (conuid == input_pad_$uid) {pad_$raw(ios_$stdin, st); return(0);}
  11949. #endif /* aegis */
  11950.  
  11951. #ifdef COHERENT
  11952. #define SVORPOSIX
  11953. #endif /* COHERENT */
  11954.  
  11955. #ifdef Plan9
  11956.     x = p9concb();
  11957. #else
  11958. #ifndef SVORPOSIX            /* BSD, V7, etc */
  11959.     debug(F101,"cccbrk.sg_flags concb 1","", cccbrk.sg_flags);
  11960.     debug(F101,"concb stty CBREAK","",0);
  11961.     cccbrk.sg_flags |= (CBREAK|CRMOD);    /* Set to character wakeup, */
  11962.     cccbrk.sg_flags &= ~ECHO;           /* no echo. */
  11963.     debug(F101,"cccbrk.sg_flags concb 2","", cccbrk.sg_flags);
  11964.     errno = 0;
  11965. /*
  11966.   BSD stty() clears the console buffer.  So if anything is waiting in it,
  11967.   we have to read it now to avoid losing it.
  11968. */
  11969.     x = conchk();
  11970.     if (x > 0)
  11971.       congetbuf(x);
  11972.  
  11973. #ifdef BELLV10
  11974.     x = ioctl(0,TIOCSETP,&cccbrk);
  11975. #else
  11976.     x = stty(0,&cccbrk);
  11977.     debug(F101,"cccbrk.sg_flags concb x","", x);
  11978. #endif /* BELLV10 */
  11979. #else                    /* Sys V and POSIX */
  11980. #ifndef OXOS
  11981.     debug(F101,"concb cccbrk.c_flag","",cccbrk.c_lflag);
  11982. #ifdef QNX
  11983.     /* Don't mess with IEXTEN */
  11984.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  11985. #else
  11986. #ifdef COHERENT
  11987.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  11988. #else
  11989.     cccbrk.c_lflag &= ~(ICANON|ECHO|IEXTEN);
  11990. #endif /* COHERENT */
  11991. #endif /* QNX */
  11992.     cccbrk.c_lflag |= ISIG;        /* Allow signals in command mode. */
  11993.     cccbrk.c_iflag |= IGNBRK;        /* But ignore BREAK signal */
  11994.     cccbrk.c_iflag &= ~BRKINT;
  11995.  
  11996. #else /* OXOS */
  11997.     debug(F100,"concb OXOS is defined","",0);
  11998.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  11999.     cccbrk.c_cc[VDISCARD] = cccbrk.c_cc[VLNEXT] = CDISABLE;
  12000. #endif /* OXOS */
  12001. #ifdef COMMENT
  12002. /*
  12003.   Believe it or not, in SCO UNIX, VSUSP is greater than NCC, and so this
  12004.   array reference is out of bounds.  It's only a debug() call so who needs it.
  12005. */
  12006. #ifdef VSUSP
  12007.     debug(F101,"concb c_cc[VSUSP]","",cccbrk.c_cc[VSUSP]);
  12008. #endif /* VSUSP */
  12009. #endif /* COMMENT */
  12010. #ifndef VINTR
  12011.     debug(F101,"concb c_cc[0]","",cccbrk.c_cc[0]);
  12012.     cccbrk.c_cc[0] = 003;               /* Interrupt char is Control-C */
  12013. #else
  12014.     debug(F101,"concb c_cc[VINTR]","",cccbrk.c_cc[0]);
  12015.     cccbrk.c_cc[VINTR] = 003;
  12016. #endif /* VINTR */
  12017. #ifndef VQUIT
  12018.     cccbrk.c_cc[1] = escchr;            /* escape during packet modes */
  12019. #else
  12020.     cccbrk.c_cc[VQUIT] = escchr;
  12021. #endif /* VQUIT */
  12022. #ifndef VEOF
  12023.     cccbrk.c_cc[4] = 1;
  12024. #else
  12025. #ifndef OXOS
  12026. #ifdef VMIN
  12027.     cccbrk.c_cc[VMIN] = 1;
  12028. #endif /* VMIN */
  12029. #else /* OXOS */
  12030.     cccbrk.c_min = 1;
  12031. #endif /* OXOS */
  12032. #endif /* VEOF */
  12033. #ifdef ZILOG
  12034.     cccbrk.c_cc[5] = 0;
  12035. #else
  12036. #ifndef VEOL
  12037.     cccbrk.c_cc[5] = 1;
  12038. #else
  12039. #ifndef OXOS
  12040. #ifdef VTIME
  12041.     cccbrk.c_cc[VTIME] = 1;
  12042. #endif /* VTIME */
  12043. #else /* OXOS */
  12044.     cccbrk.c_time = 1;
  12045. #endif /* OXOS */
  12046. #endif /* VEOL */
  12047. #endif /* ZILOG */
  12048.     errno = 0;
  12049. #ifdef BSD44ORPOSIX            /* Set new modes */
  12050.     x = tcsetattr(0,TCSADRAIN,&cccbrk);
  12051. #else /* ATTSV */                  /* or the POSIX way */
  12052.     x = ioctl(0,TCSETAW,&cccbrk);    /* the Sys V way */
  12053. #endif /* BSD44ORPOSIX */
  12054. #endif /* SVORPOSIX */
  12055.  
  12056. #ifdef COHERENT
  12057. #undef SVORPOSIX
  12058. #endif /* COHERENT */
  12059.     debug(F101,"concb x","",x);
  12060.     debug(F101,"concb errno","",errno);
  12061. #ifdef NONOSETBUF
  12062.     if (x > -1) {
  12063.     setbuf(stdout,NULL);    /* Make console unbuffered. */
  12064.     debug(F100,"concb setbuf A","",0);
  12065.     }
  12066. #else
  12067. #ifndef aegis
  12068. #ifndef NOSETBUF
  12069.     if (x > -1) {
  12070.     setbuf(stdout,NULL);    /* Make console unbuffered. */
  12071.     debug(F100,"concb setbuf B","",0);
  12072.     }
  12073. #endif /* NOSETBUF */
  12074. #endif /* aegis */
  12075. #endif /* NONOSETBUF */
  12076.  
  12077. #ifdef  V7
  12078. #ifndef MINIX
  12079.     if (kmem[CON] < 0) {
  12080.         qaddr[CON] = initrawq(0);
  12081.         if((kmem[CON] = open("/dev/kmem", 0)) < 0) {
  12082.             fprintf(stderr, "Can't read /dev/kmem in concb.\n");
  12083.             perror("/dev/kmem");
  12084.             exit(1);
  12085.         }
  12086.     }
  12087. #endif /* MINIX */
  12088. #endif /* V7 */
  12089. #endif /* Plan9 */
  12090.  
  12091.     if (x > -1)
  12092.       constate = CON_CB;
  12093.  
  12094.     debug(F101,"concb returns","",x);
  12095.     return(x);
  12096. }
  12097.  
  12098. /*  C O N B I N  --  Put console in binary mode  */
  12099.  
  12100. /*  Returns 0 if ok, -1 if not  */
  12101.  
  12102. int
  12103. #ifdef CK_ANSIC
  12104. conbin(char esc)
  12105. #else
  12106. conbin(esc) char esc;
  12107. #endif /* CK_ANSIC */
  12108. /* conbin */  {
  12109.  
  12110.     int x;
  12111.  
  12112.     debug(F101,"conbin constate","",constate);
  12113.  
  12114.     if (constate == CON_BIN)
  12115.       return(0);
  12116.  
  12117.     if (!isatty(0)) return(0);          /* only for real ttys */
  12118.     congm();                /* Get modes if necessary. */
  12119.     debug(F100,"conbin","",0);
  12120.     escchr = esc;                       /* Make this available to other fns */
  12121.     ckxech = 1;                         /* Program can echo characters */
  12122. #ifdef aegis
  12123.     conbufn = 0;
  12124.     if (concrp) return(write(1, "\035\002", 2));
  12125.     if (conuid == input_pad_$uid) {
  12126.     pad_$raw(ios_$stdin, st);
  12127.     return(0);
  12128.       }
  12129. #endif /* aegis */
  12130.  
  12131. #ifdef COHERENT
  12132. #define SVORPOSIX
  12133. #endif /* COHERENT */
  12134.  
  12135. #ifdef Plan9
  12136.     return p9conbin();
  12137. #else
  12138. #ifdef SVORPOSIX
  12139. #ifndef OXOS
  12140. #ifdef QNX
  12141.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  12142. #else
  12143. #ifdef COHERENT
  12144.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  12145. #else
  12146.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO|IEXTEN);
  12147. #endif /* COHERENT */
  12148. #endif /* QNX */
  12149. #else /* OXOS */
  12150.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  12151.     ccraw.c_cc[VDISCARD] = ccraw.c_cc[VLNEXT] = CDISABLE;
  12152. #endif /* OXOS */
  12153.     ccraw.c_iflag |= IGNPAR;
  12154. /*
  12155.   Note that for terminal sessions we disable Xon/Xoff flow control to allow
  12156.   the passage ^Q and ^S as data characters for EMACS, and to allow XMODEM
  12157.   transfers to work when C-Kermit is in the middle, etc.  Hardware flow
  12158.   control, if in use, is not affected.
  12159. */
  12160. #ifdef ATTSV
  12161. #ifdef BSD44
  12162.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IXON|IXANY|IXOFF
  12163.                         |INPCK|ISTRIP);
  12164. #else
  12165.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IUCLC|IXON|IXANY|IXOFF
  12166.                         |INPCK|ISTRIP);
  12167. #endif /* BSD44 */
  12168. #else /* POSIX */
  12169.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IXON|IXOFF|INPCK|ISTRIP);
  12170. #endif /* ATTSV */
  12171.     ccraw.c_oflag &= ~OPOST;
  12172. #ifdef COMMENT
  12173. /*
  12174.   WHAT THE HECK WAS THIS FOR?
  12175.   The B9600 setting (obviously) prevents CONNECT from working at any
  12176.   speed other than 9600 when you are logged in to the 7300 on a serial
  12177.   line.  Maybe some of the other flags are necessary -- if so, put back
  12178.   the ones that are needed.  This code is supposed to work the same, no
  12179.   matter whether you are logged in to the 7300 on the real console device,
  12180.   or through a serial port.
  12181. */
  12182. #ifdef ATT7300
  12183.     ccraw.c_cflag = CLOCAL | B9600 | CS8 | CREAD | HUPCL;
  12184. #endif /* ATT7300 */
  12185. #endif /* COMMENT */
  12186.  
  12187. /*** Kermit used to put the console in 8-bit raw mode, but some users have
  12188.  *** pointed out that this should not be done, since some sites actually
  12189.  *** use terminals with parity settings on their Unix systems, and if we
  12190.  *** override the current settings and stop doing parity, then their terminals
  12191.  *** will display blotches for characters whose parity is wrong.  Therefore,
  12192.  *** the following two lines are commented out (Larry Afrin, Clemson U):
  12193.  ***
  12194.  ***   ccraw.c_cflag &= ~(PARENB|CSIZE);
  12195.  ***   ccraw.c_cflag |= (CS8|CREAD);
  12196.  ***
  12197.  *** Sys III/V sites that have trouble with this can restore these lines.
  12198.  ***/
  12199. #ifndef VINTR
  12200.     ccraw.c_cc[0] = 003;        /* Interrupt char is Ctrl-C */
  12201. #else
  12202.     ccraw.c_cc[VINTR] = 003;
  12203. #endif /* VINTR */
  12204. #ifndef VQUIT
  12205.     ccraw.c_cc[1] = escchr;        /* Escape during packet mode */
  12206. #else
  12207.     ccraw.c_cc[VQUIT] = escchr;
  12208. #endif /* VQUIT */
  12209. #ifndef VEOF
  12210.     ccraw.c_cc[4] = 1;
  12211. #else
  12212. #ifndef OXOS
  12213. #ifdef VMIN
  12214.     ccraw.c_cc[VMIN] = 1;
  12215. #endif /* VMIN */
  12216. #else /* OXOS */
  12217.     ccraw.c_min = 1;
  12218. #endif /* OXOS */
  12219. #endif /* VEOF */
  12220.  
  12221. #ifdef ZILOG
  12222.     ccraw.c_cc[5] = 0;
  12223. #else
  12224. #ifndef VEOL
  12225.     ccraw.c_cc[5] = 1;
  12226. #else
  12227. #ifndef OXOS
  12228. #ifdef VTIME
  12229.     ccraw.c_cc[VTIME] = 1;
  12230. #endif /* VTIME */
  12231. #else /* OXOS */
  12232.     ccraw.c_time = 1;
  12233. #endif /* OXOS */
  12234. #endif /* VEOL */
  12235. #endif /* ZILOG */
  12236.  
  12237. #ifdef BSD44ORPOSIX
  12238.     x = tcsetattr(0,TCSADRAIN,&ccraw);    /* Set new modes. */
  12239. #else
  12240.     x = ioctl(0,TCSETAW,&ccraw);
  12241. #endif /* BSD44ORPOSIX */
  12242. #else /* Berkeley, etc. */
  12243.     x = conchk();            /* Because stty() is destructive */
  12244.     if (x > 0)
  12245.       congetbuf(x);
  12246.     ccraw.sg_flags |= (RAW|TANDEM);     /* Set rawmode, XON/XOFF (ha) */
  12247.     ccraw.sg_flags &= ~(ECHO|CRMOD);    /* Set char wakeup, no echo */
  12248. #ifdef BELLV10
  12249.     x = ioctl(0,TIOCSETP,&ccraw);
  12250. #else
  12251.     x = stty(0,&ccraw);
  12252. #endif /* BELLV10 */
  12253. #endif /* SVORPOSIX */
  12254. #endif /* Plan9 */
  12255.  
  12256.     if (x > -1)
  12257.       constate = CON_BIN;
  12258.  
  12259.     debug(F101,"conbin returns","",x);
  12260.     return(x);
  12261.  
  12262. #ifdef COHERENT
  12263. #undef SVORPOSIX
  12264. #endif /* COHERENT */
  12265.  
  12266. }
  12267.  
  12268.  
  12269. /*  C O N R E S  --  Restore the console terminal  */
  12270.  
  12271. int
  12272. conres() {
  12273.     int x;
  12274.     debug(F101,"conres cgmf","",cgmf);
  12275.     debug(F101,"conres constate","",constate);
  12276.  
  12277.     if (cgmf < 1)            /* Do nothing if modes unchanged */
  12278.       return(0);
  12279.     if (constate == CON_RES)
  12280.       return(0);
  12281.  
  12282.     if (!isatty(0)) return(0);          /* only for real ttys */
  12283.     debug(F100,"conres isatty ok","",0);
  12284.     ckxech = 0;                         /* System should echo chars */
  12285.  
  12286. #ifdef aegis
  12287.     conbufn = 0;
  12288.     if (concrp) return(write(1, "\035\001", 2));
  12289.     if (conuid == input_pad_$uid) {
  12290.     pad_$cooked(ios_$stdin, st);
  12291.     constate = CON_RES;
  12292.     return(0);
  12293.     }
  12294. #endif /* aegis */
  12295.  
  12296. #ifdef Plan9
  12297.     p9conres();
  12298. #else
  12299. #ifdef BSD44ORPOSIX
  12300.     debug(F100,"conres restoring tcsetattr","",0);
  12301.     x = tcsetattr(0,TCSADRAIN,&ccold);
  12302. #else
  12303. #ifdef ATTSV
  12304.     debug(F100,"conres restoring ioctl","",0);
  12305.     x = ioctl(0,TCSETAW,&ccold);
  12306. #else /* BSD, V7, and friends */
  12307. #ifdef sony_news            /* Sony NEWS */
  12308.     if (km_con != -1)
  12309.       ioctl(0,TIOCKSET,&km_con);    /* Restore console Kanji mode */
  12310. #endif /* sony_news */
  12311.     msleep(100);
  12312.     debug(F100,"conres restoring stty","",0);
  12313.     x = conchk();            /* Because stty() is destructive */
  12314.     if (x > 0)
  12315.       congetbuf(x);
  12316. #ifdef BELLV10
  12317.     x = ioctl(0,TIOCSETP,&ccold);
  12318. #else
  12319.     x = stty(0,&ccold);
  12320. #endif /* BELLV10 */
  12321. #endif /* ATTSV */
  12322. #endif /* BSD44ORPOSIX */
  12323. #endif /* Plan9 */
  12324.     if (x > -1)
  12325.       constate = CON_RES;
  12326.  
  12327.     debug(F101,"conres returns","",x);
  12328.     return(x);
  12329. }
  12330.  
  12331. /*  C O N O C  --  Output a character to the console terminal  */
  12332.  
  12333. int
  12334. #ifdef CK_ANSIC
  12335. conoc(char c)
  12336. #else
  12337. conoc(c) char c;
  12338. #endif /* CK_ANSIC */
  12339. /* conoc */ {
  12340.  
  12341. #ifdef IKSD
  12342.     if (inserver && !local)
  12343.       return(ttoc(c));
  12344.  
  12345. #ifdef CK_ENCRYPTION
  12346.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  12347.         ck_tn_encrypt(&c,1);
  12348. #endif /* CK_ENCRYPTION */
  12349. #endif /* IKSD */
  12350.  
  12351. #ifdef Plan9
  12352.     return conwrite(&c,1);
  12353. #else
  12354.     return(write(1,&c,1));
  12355. #endif /* Plan9 */
  12356. }
  12357.  
  12358. /*  C O N X O  --  Write x characters to the console terminal  */
  12359.  
  12360. int
  12361. conxo(x,s) int x; char *s; {
  12362.  
  12363. #ifdef IKSD
  12364.     if (inserver && !local)
  12365.       return(ttol((CHAR *)s,x));
  12366.  
  12367. #ifdef CK_ENCRYPTION
  12368.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  12369.         ck_tn_encrypt(s,x);
  12370. #endif /* CK_ENCRYPTION */
  12371. #endif /* IKSD */
  12372.  
  12373. #ifdef Plan9
  12374.     return(conwrite(s,x));
  12375. #else
  12376.     return(write(1,s,x));
  12377. #endif /* Plan9 */
  12378. }
  12379.  
  12380. /*  C O N O L  --  Write a line to the console terminal  */
  12381.  
  12382. int
  12383. conol(s) char *s; {
  12384.     int len;
  12385.     if (!s) s = "";            /* Always do this! */
  12386.     len = strlen(s);
  12387.     if (len == 0)
  12388.       return(0);
  12389.  
  12390. #ifdef IKSD
  12391.     if (inserver && !local)
  12392.       return(ttol((CHAR *)s,len));
  12393.  
  12394. #ifdef CK_ENCRYPTION
  12395.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION)) {
  12396.     if (nxpacket < len) {
  12397.         if (xpacket) {
  12398.         free(xpacket);
  12399.         xpacket = NULL;
  12400.         nxpacket = 0;
  12401.         }
  12402.         len = len > 10240 ? len : 10240;
  12403.         xpacket = (char *)malloc(len);
  12404.         if (!xpacket) {
  12405.         fprintf(stderr,"ttol malloc failure\n");
  12406.         return(-1);
  12407.         } else
  12408.           nxpacket = len;
  12409.     }
  12410.     memcpy(xpacket,s,len);
  12411.     s = xpacket;
  12412.     ck_tn_encrypt(s,len);
  12413.     }
  12414. #endif /* CK_ENCRYPTION */
  12415. #endif /* IKSD */
  12416.  
  12417. #ifdef Plan9
  12418.     return(conwrite(s,len));
  12419. #else
  12420.     return(write(1,s,len));
  12421. #endif /* Plan9 */
  12422. }
  12423.  
  12424. /*  C O N O L A  --  Write an array of lines to the console terminal */
  12425.  
  12426. int
  12427. conola(s) char *s[]; {
  12428.     char * p;
  12429.     int i, x;
  12430.  
  12431.  
  12432.     if (!s) return(0);
  12433.     for (i = 0; ; i++) {
  12434.     p = s[i];
  12435.     if (!p) p = "";            /* Let's not dump core shall we? */
  12436.     if (!*p)
  12437.       break;
  12438. #ifdef IKSD
  12439.     if (inserver && !local)
  12440.       x = ttol((CHAR *)p,(int)strlen(p));
  12441.     else
  12442. #endif /* IKSD */
  12443.       x = conol(p);
  12444.     if (x < 0)
  12445.       return(-1);
  12446.     }
  12447.     return(0);
  12448. }
  12449.  
  12450. /*  C O N O L L  --  Output a string followed by CRLF  */
  12451.  
  12452. int
  12453. conoll(s) char *s; {
  12454.     CHAR buf[3];
  12455.     buf[0] = '\r';
  12456.     buf[1] = '\n';
  12457.     buf[2] = '\0';
  12458.     if (!s) s = "";
  12459.  
  12460. #ifdef IKSD
  12461.     if (inserver && !local) {
  12462.     if (*s) ttol((CHAR *)s,(int)strlen(s));
  12463.     return(ttol(buf,2));
  12464.     }
  12465. #endif /* IKSD */
  12466.  
  12467.     if (*s) conol(s);
  12468. #ifdef IKSD
  12469. #ifdef CK_ENCRYPTION
  12470.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  12471.       ck_tn_encrypt(buf,2);
  12472. #endif /* CK_ENCRYPTION */
  12473. #endif /* IKSD */
  12474.  
  12475. #ifdef Plan9
  12476.     return(conwrite(buf, 2));
  12477. #else
  12478.     return(write(1,buf,2));
  12479. #endif /* Plan9 */
  12480. }
  12481.  
  12482. /*  C O N C H K  --  Return how many characters available at console  */
  12483. /*
  12484.   We could also use select() here to cover a few more systems that are not
  12485.   covered by any of the following, e.g. HP-UX 9.0x on the model 800.
  12486. */
  12487. int
  12488. conchk() {
  12489.     static int contyp = 0;        /* +1 for isatty, -1 otherwise */
  12490.  
  12491.     if (contyp == 0)            /* This prevents unnecessary */
  12492.       contyp = (isatty(0) ? 1 : -1);    /* duplicated calls to isatty() */
  12493.     debug(F101,"conchk contyp","",contyp);
  12494.     if (backgrd || (contyp < 0))
  12495.       return(0);
  12496.  
  12497. #ifdef aegis
  12498.     if (conbufn > 0) return(conbufn);   /* use old count if nonzero */
  12499.  
  12500.     /* read in more characters */
  12501.     conbufn = ios_$get(ios_$stdin,
  12502.               ios_$cond_opt, conbuf, (long)sizeof(conbuf), st);
  12503.     if (st.all != status_$ok) conbufn = 0;
  12504.     conbufp = conbuf;
  12505.     return(conbufn);
  12506. #else
  12507. #ifdef IKSD
  12508.     if (inserver && !local)
  12509.       return(in_chk(1,ttyfd));
  12510.     else
  12511. #endif /* IKSD */
  12512.       return(in_chk(0,0));
  12513. #endif /* aegis */
  12514. }
  12515.  
  12516. /*  C O N I N C  --  Get a character from the console  */
  12517. /*
  12518.   Call with timo > 0 to do a timed read, timo == 0 to do an untimed blocking
  12519.   read.  Upon success, returns the character.  Upon failure, returns -1.
  12520.   A timed read that does not complete within the timeout period returns -2.
  12521. */
  12522. int
  12523. coninc(timo) int timo; {
  12524.     int n = 0; CHAR ch;
  12525.     int xx;
  12526.  
  12527.     if (conbufn > 0) {            /* If something already buffered */
  12528.     --conbufn;
  12529.     return((unsigned)(*conbufp++ & 0xff));
  12530.     }
  12531.  
  12532.     errno = 0;                /* Clear this */
  12533. #ifdef IKSD
  12534.     if (inserver && !local) {
  12535.     xx = ttinc(timo);
  12536.     if (xx < 0)
  12537.       return(ttinctimo ? -2 : -1);
  12538.     else
  12539.       return(xx);
  12540.     }
  12541. #endif /* IKSD */
  12542.  
  12543. #ifdef aegis                /* Apollo Aegis only... */
  12544.     debug(F101,"coninc timo","",timo);
  12545.     fflush(stdout);
  12546.     if (conchk() > 0) {
  12547.     --conbufn;
  12548.     return((unsigned)(*conbufp++ & 0xff));
  12549.     }
  12550. #endif /* aegis */
  12551.  
  12552. #ifdef TTLEBUF
  12553.     if (
  12554. #ifdef IKSD
  12555.     inserver &&
  12556. #endif /* IKSD */
  12557.     !xlocal
  12558.     ) {
  12559.     if (ttpush >= 0) {
  12560.         debug(F111,"ttinc","ttpush",ttpush);
  12561.         ch = ttpush;
  12562.         ttpush = -1;
  12563.         return(ch);
  12564.     }
  12565.     if (le_data) {
  12566.         if (le_getchar(&ch) > 0) {
  12567.         debug(F111,"ttinc LocalEchoInBuf","ch",ch);
  12568.         return(ch);
  12569.         }
  12570.     }
  12571.     }
  12572. #endif /* TTLEBUF */
  12573.  
  12574.     if (timo <= 0) {            /* Untimed, blocking read. */
  12575.     while (1) {            /* Keep trying till we get one. */
  12576.         n = read(0, &ch, 1);    /* Read a character. */
  12577.         if (n == 0) continue;    /* Shouldn't happen. */
  12578.         if (n > 0) {        /* If read was successful, */
  12579. #ifdef IKSD
  12580. #ifdef CK_ENCRYPTION
  12581.                 debug(F100,"coninc decrypt 1","",0);
  12582.                 if (inserver && !local && TELOPT_U(TELOPT_ENCRYPTION))
  12583.           ck_tn_decrypt(&ch,1);
  12584. #endif /* CK_ENCRYPTION */
  12585. #endif /* IKSD */
  12586.         return((unsigned)(ch & 0xff)); /* return the character. */
  12587.             }
  12588.  
  12589. /* Come here if read() returned an error. */
  12590.  
  12591.         debug(F101, "coninc(0) errno","",errno); /* Log the error. */
  12592. #ifndef OXOS
  12593. #ifdef SVORPOSIX
  12594. #ifdef CIE                             /* CIE Regulus has no EINTR symbol? */
  12595. #ifndef EINTR
  12596. #define EINTR 4
  12597. #endif /* EINTR */
  12598. #endif /* CIE */
  12599. /*
  12600.   This routine is used for several different purposes.  In CONNECT mode, it is
  12601.   used to do an untimed, blocking read from the keyboard in the lower CONNECT
  12602.   fork.  During local-mode file transfer, it reads a character from the
  12603.   console to interrupt the file transfer (like A for a status report, X to
  12604.   cancel a file, etc).  Obviously, we don't want the reads in the latter case
  12605.   to be blocking, or the file transfer would stop until the user typed
  12606.   something.  Unfortunately, System V does not allow the console device input
  12607.   buffer to be sampled nondestructively (e.g. by conchk()), so a kludge is
  12608.   used instead.  During local-mode file transfer, the SIGQUIT signal is armed
  12609.   and trapped by esctrp(), and this routine pretends to have read the quit
  12610.   character from the keyboard normally.  But, kludge or no kludge, the read()
  12611.   issued by this command, under System V only, can fail if a signal -- ANY
  12612.   signal -- is caught while the read is pending.  This can occur not only when
  12613.   the user types the quit character, but also during telnet negotiations, when
  12614.   the lower CONNECT fork signals the upper one about an echoing mode change.
  12615.   When this happens, we have to post the read() again.  This is apparently not
  12616.   a problem in BSD-based UNIX versions.
  12617. */
  12618.         if (errno == EINTR)        /* Read interrupted. */
  12619.           if (conesc)  {        /* If by SIGQUIT, */
  12620.           conesc = 0;        /* the conesc variable is set, */
  12621.           return(escchr);    /* so return the escape character. */
  12622.          } else continue;        /* By other signal, try again. */
  12623. #else
  12624. /*
  12625.   This might be dangerous, but let's do this on non-System V versions too,
  12626.   since at least one SunOS 4.1.2 user complains of immediate disconnections
  12627.   upon first making a TELNET connection.
  12628. */
  12629.         if (errno == EINTR)        /* Read interrupted. */
  12630.           continue;
  12631. #endif /* SVORPOSIX */
  12632. #else /* OXOS */
  12633.         if (errno == EINTR)        /* Read interrupted. */
  12634.           continue;
  12635. #endif /* OXOS */
  12636.         return(-1);            /* Error */
  12637.     }
  12638.     }
  12639. #ifdef DEBUG
  12640.     if (deblog && timo <= 0) {
  12641.     debug(F100,"coninc timeout logic error","",0);
  12642.     timo = 1;
  12643.     }
  12644. #endif /* DEBUG */
  12645.  
  12646. /* Timed read... */
  12647.  
  12648.     saval = signal(SIGALRM,timerh);    /* Set up timeout handler. */
  12649.     xx = alarm(timo);            /* Set the alarm. */
  12650.     debug(F101,"coninc alarm set","",timo);
  12651.     if (
  12652. #ifdef CK_POSIX_SIG
  12653.     sigsetjmp(sjbuf,1)
  12654. #else
  12655.     setjmp(sjbuf)
  12656. #endif /* CK_POSIX_SIG */
  12657.     )                /* The read() timed out. */
  12658.       n = -2;                /* Code for timeout. */
  12659.     else
  12660.       n = read(0, &ch, 1);
  12661.     ttimoff();                /* Turn off timer */
  12662.     if (n > 0) {            /* Got character OK. */
  12663. #ifdef IKSD
  12664. #ifdef CK_ENCRYPTION
  12665.         debug(F100,"coninc decrypt 2","",0);
  12666.         if (inserver && !local && TELOPT_U(TELOPT_ENCRYPTION))
  12667.       ck_tn_decrypt(&ch,1);
  12668. #endif /* CK_ENCRYPTION */
  12669. #endif /* IKSD */
  12670.     return((unsigned)(ch & 0xff));    /* Return it. */
  12671.     }
  12672. /*
  12673.   read() returned an error.  Same deal as above, but without the loop.
  12674. */
  12675.     debug(F101, "coninc(timo) n","",n);
  12676.     debug(F101, "coninc(timo) errno","",errno);
  12677. #ifndef OXOS
  12678. #ifdef SVORPOSIX
  12679.     if (n == -1 && errno == EINTR && conesc != 0) {
  12680.     conesc = 0;
  12681.     return(escchr);            /* User entered escape character. */
  12682.     }
  12683. #endif /* SVORPOSIX */
  12684.     if (n == 0 && errno > 0) {        /* It's an error */
  12685.     return(-1);
  12686.     }
  12687. #endif /* ! OXOS */
  12688.     return(n);
  12689. }
  12690.  
  12691. /*  C O N G K S  --  Console Get Keyboard Scancode  */
  12692.  
  12693. #ifndef congks
  12694. /*
  12695.   This function needs to be filled in with the various system-dependent
  12696.   system calls used by SUNOS, NeXT OS, Xenix, Aviion, etc, to read a full
  12697.   keyboard scan code.  Unfortunately there aren't any.
  12698. */
  12699. int
  12700. congks(timo) int timo; {
  12701.  
  12702. #ifdef IKSD
  12703.     if (inserver && !local)
  12704.       return(ttinc(timo));
  12705. #endif /* IKSD */
  12706.  
  12707.     return(coninc(timo));
  12708. }
  12709. #endif /* congks */
  12710.  
  12711. #ifdef ATT7300
  12712.  
  12713. /*  A T T D I A L  --  Dial up the remote system using internal modem
  12714.  * Purpose: to open and dial a number on the internal modem available on the
  12715.  * ATT7300 UNIX PC.  Written by Joe Doupnik. Superceeds version written by
  12716.  * Richard E. Hill, Dickinson, TX. which employed dial(3c).
  12717.  * Uses information in <sys/phone.h> and our status int attmodem.
  12718.  */
  12719. attdial(ttname,speed,telnbr) char *ttname,*telnbr; long speed; {
  12720.     char *telnum;
  12721.  
  12722.     attmodem &= ~ISMODEM;                       /* modem not in use yet */
  12723.                     /* Ensure O_NDELAY is set, else i/o traffic hangs */
  12724.                     /* We turn this flag off once the dial is complete */
  12725.     fcntl(ttyfd, F_SETFL, fcntl(ttyfd, F_GETFL, 0) | O_NDELAY);
  12726.  
  12727.     /* Condition line, check availability & DATA mode, turn on speaker */
  12728.     if (ioctl(ttyfd,PIOCOFFHOOK, &dialer) == -1) {
  12729.         printf("cannot access phone\n");
  12730.         ttclos(0);
  12731.         return (-2);
  12732.     }
  12733.     ioctl(ttyfd,PIOCGETP,&dialer);      /* get phone dialer parameters */
  12734.  
  12735.     if (dialer.c_lineparam & VOICE) {    /* phone must be in DATA mode */
  12736.         printf(" Should not dial with modem in VOICE mode.\n");
  12737.         printf(" Exit Kermit, switch to DATA and retry call.\n");
  12738.         ttclos(0);
  12739.         return (-2);
  12740.     }
  12741. #ifdef ATTTONED                /* Old way, tone dialing only. */
  12742.     dialer.c_lineparam = DATA | DTMF;    /* Dial with tones, */
  12743.     dialer.c_lineparam &= ~PULSE;    /* not with pulses. */
  12744. #else
  12745.     /* Leave current pulse/tone state alone. */
  12746.     /* But what about DATA?  Add it back if you have trouble. */
  12747.     /* sys/phone says you get DATA automatically by opening device RDWR */
  12748. #endif
  12749.     dialer.c_waitdialtone = 5;                  /* wait 5 sec for dialtone */
  12750. #ifdef COMMENT
  12751.     dialer.c_feedback = SPEAKERON|NORMSPK|RINGON;  /* control speaker */
  12752. #else
  12753.     /* sys/phone says RINGON used only for incoming voice calls */
  12754.     dialer.c_feedback &= ~(SOFTSPK|LOUDSPK);
  12755.     dialer.c_feedback |= SPEAKERON|NORMSPK;
  12756. #endif
  12757.     dialer.c_waitflash = 500;                   /* 0.5 sec flash hook */
  12758.     if(ioctl(ttyfd,PIOCSETP,&dialer) == -1) {   /* set phone parameters */
  12759.         printf("Cannot set modem characteristics\n");
  12760.         ttclos(0);
  12761.         return (-2);
  12762.     }
  12763.     ioctl(ttyfd,PIOCRECONN,0);        /* Turns on speaker for pulse */
  12764.  
  12765. #ifdef COMMENT
  12766.     fprintf(stderr,"Phone line status. line_par:%o dialtone_wait:%o \
  12767. line_status:%o feedback:%o\n",
  12768.     dialer.c_lineparam, dialer.c_waitdialtone,
  12769.     dialer.c_linestatus, dialer.c_feedback);
  12770. #endif
  12771.  
  12772.     attmodem |= ISMODEM;                        /* modem is now in-use */
  12773.     sleep(1);
  12774.     for (telnum = telnbr; *telnum != '\0'; telnum++)    /* dial number */
  12775. #ifdef ATTTONED
  12776.       /* Tone dialing only */
  12777.       if (ioctl(ttyfd,PIOCDIAL,telnum) != 0) {
  12778.       perror("Error in dialing");
  12779.       ttclos(0);
  12780.       return(-2);
  12781.       }
  12782. #else /* Allow Pulse or Tone dialing */
  12783.     switch (*telnum) {
  12784.       case 't': case 'T': case '%':    /* Tone dialing requested */
  12785.     dialer.c_lineparam |= DTMF;
  12786.     dialer.c_lineparam &= ~PULSE;
  12787.     if (ioctl(ttyfd,PIOCSETP,&dialer) == -1) {
  12788.         printf("Cannot set modem to tone dialing\n");
  12789.         ttclos(0);
  12790.         return(-2);
  12791.     }
  12792.     break;
  12793.       case 'd': case 'D': case 'p': case 'P': case '^':
  12794.     dialer.c_lineparam |= PULSE;
  12795.     dialer.c_lineparam &= ~DTMF;
  12796.     if (ioctl(ttyfd,PIOCSETP,&dialer) == -1) {
  12797.         printf("Cannot set modem to pulse dialing\n");
  12798.         ttclos(0);
  12799.         return(-2);
  12800.     }
  12801.     break;
  12802.       default:
  12803.         if (ioctl(ttyfd,PIOCDIAL,telnum) != 0) {
  12804.         perror("Dialing error");
  12805.         ttclos(0);
  12806.         return(-2);
  12807.     }
  12808.     break;
  12809.     }
  12810. #endif
  12811.  
  12812.     ioctl(ttyfd,PIOCDIAL,"@");        /* terminator for data call */
  12813.     do {                /* wait for modems to Connect */
  12814.         if (ioctl(ttyfd,PIOCGETP,&dialer) != 0)    { /* get params */
  12815.         perror("Cannot get modems to connect");
  12816.         ttclos(0);
  12817.         return(-2);
  12818.     }
  12819.     } while ((dialer.c_linestatus & MODEMCONNECTED) == 0);
  12820.     /* Turn off O_NDELAY flag now. */
  12821.     fcntl(ttyfd, F_SETFL, fcntl(ttyfd, F_GETFL, 0) & ~O_NDELAY);
  12822.     signal(SIGHUP, sighup);             /* hangup on loss of carrier */
  12823.     return(0);                          /* return success */
  12824. }
  12825.  
  12826. /*
  12827.   Offgetty, ongetty functions. These function get the 'getty(1m)' off
  12828.   and restore it to the indicated line.  Shell's return codes are:
  12829.     0: Can't do it.  Probably a user logged on.
  12830.     1: No need.  No getty on that line.
  12831.     2: Done, you should restore the getty when you're done.
  12832.   DOGETY System(3), however, returns them as 0, 256, 512, respectively.
  12833.   Thanks to Kevin O'Gorman, Anarm Software Systems.
  12834.  
  12835.    getoff.sh looks like:   geton.sh looks like:
  12836.      setgetty $1 0           setgetty $1 1
  12837.      err=$?                  exit $?
  12838.      sleep 2
  12839.      exit $err
  12840. */
  12841.  
  12842. /*  O F F G E T T Y  --  Turn off getty(1m) for the communications tty line
  12843.  * and get status so it can be restarted after the line is hung up.
  12844.  */
  12845. int
  12846. offgetty(ttname) char *ttname; {
  12847.     char temp[30];
  12848.     while (*ttname != '\0') ttname++;       /* seek terminator of path */
  12849.     ttname -= 3;                            /* get last 3 chars of name */
  12850.     sprintf(temp,"/usr/bin/getoff.sh %s",ttname);
  12851.     return(zsyscmd(temp));
  12852. }
  12853.  
  12854. /*  O N G E T T Y  --  Turn on getty(1m) for the communications tty line */
  12855.  
  12856. int
  12857. ongetty(ttname) char *ttname; {
  12858.     char temp[30];
  12859.     while (*ttname != '\0') ttname++;       /* comms tty path name */
  12860.     ttname -= 3;
  12861.     sprintf(temp,"/usr/bin/geton.sh %s",ttname);
  12862.     return(zsyscmd(temp));
  12863. }
  12864. #endif /* ATT7300 */
  12865.  
  12866. /*  T T S C A R R  --  Set ttcarr variable, controlling carrier handling.
  12867.  *
  12868.  *  0 = Off: Always ignore carrier. E.g. you can connect without carrier.
  12869.  *  1 = On: Heed carrier, except during dialing. Carrier loss gives disconnect.
  12870.  *  2 = Auto: For "modem direct": The same as "Off".
  12871.  *            For real modem types: Heed carrier during connect, but ignore
  12872.  *                it anytime else.  Compatible with pre-5A C-Kermit versions.
  12873.  *
  12874.  * As you can see, this setting does not affect dialing, which always ignores
  12875.  * carrier (unless there is some special exception for some modem type).  It
  12876.  * does affect ttopen() if it is set before ttopen() is used.  This setting
  12877.  * takes effect on the next call to ttopen()/ttpkt()/ttvt().  And they are
  12878.  * (or should be) always called before any communications is tried, which
  12879.  * means that, practically speaking, the effect is immediate.
  12880.  *
  12881.  * Of course, nothing of this applies to remote mode (xlocal = 0).
  12882.  *
  12883.  * Someone has yet to uncover how to manipulate the carrier in the BSD
  12884.  * environment (or any non-termio using environment).  Until that time, this
  12885.  * will simply be a no-op for BSD.
  12886.  *
  12887.  * Note that in previous versions, the carrier was most often left unchanged
  12888.  * in ttpkt()/ttvt() unless they were called with FLO_DIAL or FLO_DIAX.  This
  12889.  * has changed.  Now it is controlled by ttcarr in conjunction with these
  12890.  * modes.
  12891.  */
  12892. int
  12893. ttscarr(carrier) int carrier; {
  12894.     ttcarr = carrier;
  12895.     debug(F101, "ttscarr","",ttcarr);
  12896.     return(ttcarr);
  12897. }
  12898.  
  12899. /* C A R R C T L  --  Set tty modes for carrier treatment.
  12900.  *
  12901.  * Sets the appropriate bits in a termio or sgttyb struct for carrier control
  12902.  * (actually, there are no bits in sgttyb for that), or performs any other
  12903.  * operations needed to control this on the current system.  The function does
  12904.  * not do the actual TCSETA or stty, since often we want to set other bits too
  12905.  * first.  Don't call this function when xlocal is 0, or the tty is not opened.
  12906.  *
  12907.  * We don't know how to do anything like carrier control on non-ATTSV systems,
  12908.  * except, apparently, ultrix.  See above.  It is also known that this doesn't
  12909.  * have much effect on a Xenix system.  For Xenix, one should switch back and
  12910.  * forth between the upper and lower case device files.  Maybe later.
  12911.  * Presently, Xenix will stick to the mode it was opened with.
  12912.  *
  12913.  * carrier: 0 = ignore carrier, 1 = require carrier.
  12914.  * The current state is saved in curcarr, and checked to save labour.
  12915.  */
  12916. #ifdef SVORPOSIX
  12917. int
  12918. #ifdef BSD44ORPOSIX
  12919. carrctl(ttpar, carrier)    struct termios *ttpar; int carrier;
  12920. #else /* ATTSV */
  12921. carrctl(ttpar, carrier)    struct termio *ttpar; int carrier;
  12922. #endif /* BSD44ORPOSIX */
  12923. /* carrctl */ {
  12924.     debug(F101, "carrctl","",carrier);
  12925.     if (carrier)
  12926.       ttpar->c_cflag &= ~CLOCAL;
  12927.     else
  12928.       ttpar->c_cflag |= CLOCAL;
  12929.     return(0);
  12930. }
  12931. #else /* Berkeley, V7, et al... */
  12932. int
  12933. carrctl(ttpar, carrier) struct sgttyb *ttpar; int carrier; {
  12934.     debug(F101, "carrctl","",carrier);
  12935.     if (carrier == curcarr)
  12936.       return(0);
  12937.     curcarr = carrier;
  12938. #ifdef ultrix
  12939. #ifdef COMMENT
  12940. /*
  12941.   Old code from somebody at DEC that tends to get stuck, time out, etc.
  12942. */
  12943.     if (carrier) {
  12944.     ioctl(ttyfd, TIOCMODEM, &temp);
  12945.     ioctl(ttyfd, TIOCHPCL, 0);
  12946.     } else {
  12947.     /* (According to the manuals, TIOCNCAR should be preferred */
  12948.     /* over TIOCNMODEM...) */
  12949.     ioctl(ttyfd, TIOCNMODEM, &temp);
  12950.     }
  12951. #else
  12952. /*
  12953.   New code from Jamie Watson that, he says, eliminates the problems.
  12954. */
  12955.     if (carrier) {
  12956.     ioctl(ttyfd, TIOCCAR);
  12957.     ioctl(ttyfd, TIOCHPCL);
  12958.     } else {
  12959.     ioctl(ttyfd, TIOCNCAR);
  12960.     }
  12961. #endif /* COMMENT */
  12962. #endif /* ultrix */
  12963.     return(0);
  12964. }
  12965. #endif /* SVORPOSIX */
  12966.  
  12967.  
  12968. /*  T T G M D M  --  Get modem signals  */
  12969. /*
  12970.  Looks for RS-232 modem signals, and returns those that are on in as its
  12971.  return value, in a bit mask composed of the BM_xxx values defined in ckcdeb.h.
  12972.  Returns:
  12973.  -3 Not implemented
  12974.  -2 if the communication device does not have modem control (e.g. telnet)
  12975.  -1 on error.
  12976.  >= 0 on success, with a bit mask containing the modem signals that are on.
  12977. */
  12978.  
  12979. /*
  12980.   Define the symbol K_MDMCTL if we have Sys V R3 / 4.3 BSD style
  12981.   modem control, namely the TIOCMGET ioctl.
  12982. */
  12983.  
  12984. #ifdef BSD43
  12985. #define K_MDMCTL
  12986. #endif /* BSD43 */
  12987.  
  12988. #ifdef SUNOS4
  12989. #define K_MDMCTL
  12990. #endif /* SUNOS4 */
  12991.  
  12992. /*
  12993.   SCO OpenServer R5.0.4.  The TIOCMGET definition is hardwired in because it
  12994.   is skipped in termio.h when _POSIX_SOURCE is defined.  But _POSIX_SOURCE
  12995.   must be defined in order to get the high serial speeds that are new to
  12996.   5.0.4.  However, the regular SCO drivers do not implement TIOCMGET, so the
  12997.   ioctl() returns -1 with errno 22 (invalid function).  But third-party
  12998.   drivers, e.g. for Digiboard, do implement it, and so it should work on ports
  12999.   driven by those drivers.
  13000. */
  13001. #ifdef SCO_OSR504
  13002. #ifndef TIOCMGET
  13003. #define TIOCMGET (('t'<<8)|29)
  13004. #endif /* TIOCMGET */
  13005. #endif /* SCO_OSR504 */
  13006.  
  13007. #ifdef CK_SCOV5
  13008. /* Because POSIX strictness in <sys/termio.h> won't let us see these. */
  13009. #ifndef TIOCM_DTR
  13010. #define TIOCM_DTR    0x0002        /* data terminal ready */
  13011. #define TIOCM_RTS    0x0004        /* request to send */
  13012. #define TIOCM_CTS    0x0020        /* clear to send */
  13013. #define TIOCM_CAR    0x0040        /* carrier detect */
  13014. #define TIOCM_RNG    0x0080        /* ring */
  13015. #define TIOCM_DSR    0x0100        /* data set ready */
  13016. #define TIOCM_CD    TIOCM_CAR
  13017. #define TIOCM_RI    TIOCM_RNG
  13018. #endif /* TIOCM_DTR */
  13019. #endif /* CK_SCOV5 */
  13020.  
  13021. #ifdef QNX
  13022. #define K_MDMCTL
  13023. #else
  13024. #ifdef TIOCMGET
  13025. #define K_MDMCTL
  13026. #endif /* TIOCMGET */
  13027. #endif /* QNX */
  13028. /*
  13029.   "A serial communication program that can't read modem signals
  13030.    is like a car without windows."
  13031. */
  13032. int
  13033. ttgmdm() {
  13034.  
  13035. #ifdef QNX
  13036. #include <sys/qioctl.h>
  13037.  
  13038.     unsigned long y, mdmbits[2];
  13039.     int x, z = 0;
  13040.  
  13041.     if (xlocal && ttyfd < 0)
  13042.       return(-1);
  13043.  
  13044. #ifdef NETCONN
  13045.     if (netconn) {            /* Network connection */
  13046. #ifdef TN_COMPORT
  13047.         if (istncomport()) {
  13048.         gotsigs = 1;
  13049.         return(tngmdm());
  13050.     } else
  13051. #endif /* TN_COMPORT */
  13052.       return(-2);            /* No modem signals */
  13053.     }
  13054. #endif /* NETCONN */
  13055.  
  13056. #ifdef NETCMD
  13057.     if (ttpipe) return(-2);
  13058. #endif /* NETCMD */
  13059. #ifdef NETPTY
  13060.     if (ttpty) return(-2);
  13061. #endif /* NETPTY */
  13062.  
  13063.     mdmbits[0] = 0L;
  13064.     mdmbits[1] = 0L;
  13065. /*
  13066.  * From <sys/qioctl.h>:
  13067.  *
  13068.  * SERIAL devices   (all Dev.ser versions)
  13069.  * 0 : DTR           8 = Data Bits 0  16 - reserved     24 - reserved
  13070.  * 1 : RTS           9 = Data Bits 1  17 - reserved     25 - reserved
  13071.  * 2 = Out 1        10 = Stop Bits    18 - reserved     26 - reserved
  13072.  * 3 = Int Enable   11 = Par Enable   19 - reserved     27 - reserved
  13073.  * 4 = Loop         12 = Par Even     20 = CTS          28 - reserved
  13074.  * 5 - reserved     13 = Par Stick    21 = DSR          29 - reserved
  13075.  * 6 - reserved     14 : Break        22 = RI           30 - reserved
  13076.  * 7 - reserved     15 = 0            23 = CD           31 - reserved
  13077.  */
  13078.     errno = 0;
  13079.     x = qnx_ioctl(ttyfd, QCTL_DEV_CTL, &mdmbits[0], 8, &mdmbits[0], 4);
  13080.     debug(F101,"ttgmdm qnx_ioctl","",x);
  13081.     debug(F101,"ttgmdm qnx_ioctl errno","",errno);
  13082.     if (!x) {
  13083.     debug(F101,"ttgmdm qnx_ioctl mdmbits[0]","",mdmbits[0]);
  13084.     debug(F101,"ttgmdm qnx_ioctl mdmbits[1]","",mdmbits[1]);
  13085.     y = mdmbits[0];
  13086.     if (y & 0x000001L) z |= BM_DTR;    /* Bit  0 */
  13087.     if (y & 0x000002L) z |= BM_RTS;    /* Bit  1 */
  13088.     if (y & 0x100000L) z |= BM_CTS;    /* Bit 20 */
  13089.     if (y & 0x200000L) z |= BM_DSR;    /* Bit 21 */
  13090.     if (y & 0x400000L) z |= BM_RNG;    /* Bit 22 */
  13091.     if (y & 0x800000L) z |= BM_DCD;    /* Bit 23 */
  13092.     debug(F101,"ttgmdm qnx result","",z);
  13093.     debug(F110,"ttgmdm qnx CD = ",(z & BM_DCD) ? "On" : "Off", 0);
  13094.     gotsigs = 1;
  13095.     return(z);
  13096.     } else return(-1);
  13097. #else /* QNX */
  13098. #ifdef HPUX                /* HPUX has its own way */
  13099.     int x, z;
  13100.  
  13101. #ifdef HPUX10                /* Modem flag word */
  13102.     mflag y;                /* mflag typedef'd in <sys/modem.h> */
  13103. #else
  13104. #ifdef HPUX9
  13105.     mflag y;
  13106. #else
  13107. #ifdef HPUX8
  13108.     mflag y;
  13109. #else
  13110.     unsigned long y;            /* Not sure about pre-8.0... */
  13111. #endif /* HPUX8 */
  13112. #endif /* HPUX9 */
  13113. #endif /* HPUX10 */
  13114.  
  13115.     if (xlocal && ttyfd < 0)
  13116.       return(-1);
  13117.  
  13118. #ifdef NETCONN
  13119.     if (netconn) {            /* Network connection */
  13120. #ifdef TN_COMPORT
  13121.         if (istncomport()) {
  13122.         gotsigs = 1;
  13123.         return(tngmdm());
  13124.     } else
  13125. #endif /* TN_COMPORT */
  13126.       return(-2);            /* No modem signals */
  13127.     }
  13128. #endif /* NETCONN */
  13129.  
  13130. #ifdef NETCMD
  13131.     if (ttpipe) return(-2);
  13132. #endif /* NETCMD */
  13133. #ifdef NETPTY
  13134.     if (ttpty) return(-2);
  13135. #endif /* NETPTY */
  13136.  
  13137.     if (xlocal)                /* Get modem signals */
  13138.       x = ioctl(ttyfd,MCGETA,&y);
  13139.     else
  13140.       x = ioctl(0,MCGETA,&y);
  13141.     if (x < 0) return(-1);
  13142.     debug(F101,"ttgmdm","",y);
  13143.  
  13144.     z = 0;                /* Initialize return value */
  13145.  
  13146. /* Now set bits for each modem signal that is reported to be on. */
  13147.  
  13148. #ifdef MCTS
  13149.     /* Clear To Send */
  13150.     debug(F101,"ttgmdm HPUX CTS","",y & MCTS);
  13151.     if (y & MCTS) z |= BM_CTS;
  13152. #endif
  13153. #ifdef MDSR
  13154.     /* Data Set Ready */
  13155.     debug(F101,"ttgmdm HPUX DSR","",y & MDSR);
  13156.     if (y & MDSR) z |= BM_DSR;
  13157. #endif
  13158. #ifdef MDCD
  13159.     /* Carrier */
  13160.     debug(F101,"ttgmdm HPUX DCD","",y & MDCD);
  13161.     if (y & MDCD) z |= BM_DCD;
  13162. #endif
  13163. #ifdef MRI
  13164.     /* Ring Indicate */
  13165.     debug(F101,"ttgmdm HPUX RI","",y & MRI);
  13166.     if (y & MRI) z |= BM_RNG;
  13167. #endif
  13168. #ifdef MDTR
  13169.     /* Data Terminal Ready */
  13170.     debug(F101,"ttgmdm HPUX DTR","",y & MDTR);
  13171.     if (y & MDTR) z |= BM_DTR;
  13172. #endif
  13173. #ifdef MRTS
  13174.     /* Request To Send */
  13175.     debug(F101,"ttgmdm HPUX RTS","",y & MRTS);
  13176.     if (y & MRTS) z |= BM_RTS;
  13177. #endif
  13178.     gotsigs = 1;
  13179.     return(z);
  13180.  
  13181. #else /* ! HPUX */
  13182.  
  13183. #ifdef K_MDMCTL
  13184. /*
  13185.   Note, TIOCMGET might already have been defined in <sys/ioctl.h> or elsewhere.
  13186.   If not, we try including <sys/ttycom.h> -- if this blows up then more ifdefs
  13187.   are needed.
  13188. */
  13189. #ifndef TIOCMGET
  13190. #include <sys/ttycom.h>
  13191. #endif /* TIOCMGET */
  13192.  
  13193.     int x, y, z;
  13194.  
  13195.     debug(F100,"ttgmdm K_MDMCTL defined","",0);
  13196.  
  13197. #ifdef NETCONN
  13198.     if (netconn) {            /* Network connection */
  13199. #ifdef TN_COMPORT
  13200.         if (istncomport()) {
  13201.         gotsigs = 1;
  13202.         return(tngmdm());
  13203.     } else
  13204. #endif /* TN_COMPORT */
  13205.       return(-2);            /* No modem signals */
  13206.     }
  13207. #endif /* NETCONN */
  13208.  
  13209. #ifdef NETCMD
  13210.     if (ttpipe) return(-2);
  13211. #endif /* NETCMD */
  13212. #ifdef NETPTY
  13213.     if (ttpty) return(-2);
  13214. #endif /* NETPTY */
  13215.  
  13216.     if (xlocal && ttyfd < 0)
  13217.       return(-1);
  13218.  
  13219.     if (xlocal)
  13220.       x = ioctl(ttyfd,TIOCMGET,&y);    /* Get modem signals. */
  13221.     else
  13222.       x = ioctl(0,TIOCMGET,&y);
  13223.     debug(F101,"ttgmdm TIOCMGET ioctl","",x);
  13224.     if (x < 0) {
  13225.     debug(F101,"ttgmdm errno","",errno);
  13226.     return(-1);
  13227.     }
  13228.     debug(F101,"ttgmdm bits","",y);
  13229.  
  13230.     z = 0;                /* Initialize return value. */
  13231. #ifdef TIOCM_CTS
  13232.     /* Clear To Send */
  13233.     if (y & TIOCM_CTS) z |= BM_CTS;
  13234.     debug(F101,"ttgmdm TIOCM_CTS defined","",TIOCM_CTS); 
  13235. #else
  13236.     debug(F100,"ttgmdm TIOCM_CTS not defined","",0);
  13237. #endif
  13238. #ifdef TIOCM_DSR
  13239.     /* Data Set Ready */
  13240.     if (y & TIOCM_DSR) z |= BM_DSR;
  13241.     debug(F101,"ttgmdm TIOCM_DSR defined","",TIOCM_DSR); 
  13242. #else
  13243.     debug(F100,"ttgmdm TIOCM_DSR not defined","",0);
  13244. #endif
  13245. #ifdef TIOCM_CAR
  13246.     /* Carrier */
  13247.     if (y & TIOCM_CAR) z |= BM_DCD;
  13248.     debug(F101,"ttgmdm TIOCM_CAR defined","",TIOCM_CAR); 
  13249. #else
  13250.     debug(F100,"ttgmdm TIOCM_CAR not defined","",0);
  13251. #endif
  13252. #ifdef TIOCM_RNG
  13253.     /* Ring Indicate */
  13254.     if (y & TIOCM_RNG) z |= BM_RNG;
  13255.     debug(F101,"ttgmdm TIOCM_RNG defined","",TIOCM_RNG); 
  13256. #else
  13257.     debug(F100,"ttgmdm TIOCM_RNG not defined","",0);
  13258. #endif
  13259. #ifdef TIOCM_DTR
  13260.     /* Data Terminal Ready */
  13261.     if (y & TIOCM_DTR) z |= BM_DTR;
  13262.     debug(F101,"ttgmdm TIOCM_DTR defined","",TIOCM_DTR); 
  13263. #else
  13264.     debug(F100,"ttgmdm TIOCM_DTR not defined","",0);
  13265. #endif
  13266. #ifdef TIOCM_RTS
  13267.     /* Request To Send */
  13268.     if (y & TIOCM_RTS) z |= BM_RTS;
  13269.     debug(F101,"ttgmdm TIOCM_RTS defined","",TIOCM_RTS); 
  13270. #else
  13271.     debug(F100,"ttgmdm TIOCM_RTS not defined","",0);
  13272. #endif
  13273.     gotsigs = 1;
  13274.     return(z);
  13275.  
  13276. #else /* !K_MDMCTL catch-All */
  13277.  
  13278.     debug(F100,"ttgmdm K_MDMCTL not defined","",0);
  13279. #ifdef TIOCMGET
  13280.     debug(F100,"ttgmdm TIOCMGET defined","",0);
  13281. #else
  13282.     debug(F100,"ttgmdm TIOCMGET not defined","",0);
  13283. #endif /* TIOCMGET */
  13284. #ifdef _SVID3
  13285.     debug(F100,"ttgmdm _SVID3 defined","",0);
  13286. #else
  13287.     debug(F100,"ttgmdm _SVID3 not defined","",0);
  13288. #endif /* _SVID3 */
  13289.  
  13290. #ifdef NETCONN
  13291.     if (netconn) {            /* Network connection */
  13292. #ifdef TN_COMPORT
  13293.         if (istncomport()) {
  13294.         gotsigs = 1;
  13295.         return(tngmdm());
  13296.     } else
  13297. #endif /* TN_COMPORT */
  13298.       return(-2);            /* No modem signals */
  13299.     }
  13300. #endif /* NETCONN */
  13301.  
  13302. #ifdef NETCMD
  13303.     if (ttpipe) return(-2);
  13304. #endif /* NETCMD */
  13305. #ifdef NETPTY
  13306.     if (ttpty) return(-2);
  13307. #endif /* NETPTY */
  13308.  
  13309.     return(-3);                /* Sorry, I don't know how... */
  13310.  
  13311. #endif /* K_MDMCTL */
  13312. #endif /* HPUX */
  13313. #endif /* QNX */
  13314. }
  13315.  
  13316. /*  P S U S P E N D  --  Put this process in the background.  */
  13317.  
  13318. /*
  13319.   Call with flag nonzero if suspending is allowed, zero if not allowed.
  13320.   Returns 0 on apparent success, -1 on failure (flag was zero, or
  13321.   kill() returned an error code.
  13322. */
  13323. int
  13324. psuspend(flag) int flag; {
  13325.  
  13326. #ifdef RTU
  13327.     extern int rtu_bug;
  13328. #endif /* RTU */
  13329.  
  13330.     if (flag == 0) return(-1);
  13331.  
  13332. #ifdef NOJC
  13333.     return(-1);
  13334. #else
  13335. #ifdef SIGTSTP
  13336. /*
  13337.   The big question here is whether job control is *really* supported.
  13338.   There's no way Kermit can know for sure.  The fact that SIGTSTP is
  13339.   defined does not guarantee the Unix kernel supports it, and the fact
  13340.   that the Unix kernel supports it doesn't guarantee that the user's
  13341.   shell (or other process that invoked Kermit) supports it.
  13342. */
  13343. #ifdef RTU
  13344.     rtu_bug = 1;
  13345. #endif /* RTU */
  13346.     if (kill(0,SIGSTOP) < 0
  13347. #ifdef MIPS
  13348. /* Let's try this for MIPS too. */
  13349.     && kill(getpid(),SIGSTOP) < 0
  13350. #endif /* MIPS */
  13351.     ) {                /* If job control, suspend the job */
  13352.     perror("suspend");
  13353.     debug(F101,"psuspend error","",errno);
  13354.     return(-1);
  13355.     }
  13356.     debug(F100,"psuspend ok","",0);
  13357.     return(0);
  13358. #else
  13359.     return(-1);
  13360. #endif /* SIGTSTP */
  13361. #endif /* NOJC */
  13362. }
  13363.  
  13364. /*
  13365.   setuid package, by Kristoffer Eriksson, with contributions from Dean
  13366.   Long and fdc.
  13367. */
  13368.  
  13369. /* The following is for SCO when CK_ANSILIBS is defined... */
  13370. #ifdef M_UNIX
  13371. #ifdef CK_ANSILIBS
  13372. #ifndef NOGETID_PROTOS
  13373. #define NOGETID_PROTOS
  13374. #endif /* NOGETID_PROTOS */
  13375. #endif /* CK_ANSILIBS */
  13376. #endif /* M_UNIX */
  13377.  
  13378. #ifndef _POSIX_SOURCE
  13379. #ifndef SUNOS4
  13380. #ifndef NEXT
  13381. #ifndef PS2AIX10
  13382. #ifndef sequent
  13383. #ifndef HPUX9
  13384. #ifndef COHERENT
  13385. #ifndef NOGETID_PROTOS
  13386. extern UID_T getuid(), geteuid(), getreuid();
  13387. extern GID_T getgid(), getegid(), getregid();
  13388. #endif /* NOGETID_PROTOS */
  13389. #else
  13390. extern UID_T getreuid();
  13391. extern GID_T getregid();
  13392. #endif /* COHERENT */
  13393. #endif /* HPUX9 */
  13394. #endif /* sequent */
  13395. #endif /* PS2AIX10 */
  13396. #endif /* NEXT */
  13397. #endif /* SUNOS4 */
  13398. #endif /* _POSIX_SOURCE */
  13399.  
  13400. /*
  13401. Subject: Set-user-id
  13402. To: fdc@watsun.cc.columbia.edu (Frank da Cruz)
  13403. Date: Sat, 21 Apr 90 4:48:25 MES
  13404. From: Kristoffer Eriksson <ske@pkmab.se>
  13405.  
  13406. This is a set of functions to be used in programs that may be run set-user-id
  13407. and/or set-group-id. They handle both the case where the program is not run
  13408. with such privileges (nothing special happens then), and the case where one
  13409. or both of these set-id modes are used.  The program is made to run with the
  13410. user's real user and group ids most of the time, except for when more
  13411. privileges are needed.  Don't set-user-id to "root".
  13412.  
  13413. This works on System V and POSIX.  In BSD, it depends on the
  13414. "saved-set-user-id" feature.
  13415. */
  13416.  
  13417. #define UID_ROOT 0            /* Root user and group ids */
  13418. #define GID_ROOT 0
  13419.  
  13420. /*
  13421.   The following code defines the symbol SETEUID for UNIX systems based
  13422.   on BSD4.4 (either -Encumbered or -Lite).  This program will then use
  13423.   seteuid() and setegid() instead of setuid() and setgid(), which still
  13424.   don't allow arbitrary switching.  It also avoids setreuid() and
  13425.   setregid(), which are included in BSD4.4 for compatibility only, are
  13426.   insecure, and print warnings to stderr under at least one system (NetBSD
  13427.   1.0).  Note that POSIX systems should still use setuid() and setgid();
  13428.   the seteuid() and setegid() functions are BSD4.4 extensions to the
  13429.   POSIX model.  Mike Long <mike.long@analog.com>, 8/94.
  13430. */
  13431. #ifdef BSD44
  13432. #define SETEUID
  13433. #endif /* BSD44 */
  13434.  
  13435. /*
  13436.   The following construction automatically defines the symbol SETREUID for
  13437.   UNIX versions based on Berkeley Unix 4.2 and 4.3.  If this symbol is
  13438.   defined, then this program will use getreuid() and getregid() calls in
  13439.   preference to getuid() and getgid(), which in Berkeley-based Unixes do
  13440.   not allow arbitrary switching back and forth of real & effective uid.
  13441.   This construction also allows -DSETREUID to be put on the cc command line
  13442.   for any system that has and wants to use setre[ug]id().  It also prevents
  13443.   automatic definition of SETREUID if -DNOSETREU is included on the cc
  13444.   command line (or otherwise defined).
  13445. */
  13446. #ifdef FT18                /* None of this for Fortune. */
  13447. #define NOSETREU
  13448. #endif /* FT18 */
  13449.  
  13450. #ifdef ANYBSD
  13451. #ifndef BSD29
  13452. #ifndef BSD41
  13453. #ifndef SETREUID
  13454. #ifndef NOSETREU
  13455. #ifndef SETEUID
  13456. #define SETREUID
  13457. #endif /* SETEUID */
  13458. #endif /* NOSETREU */
  13459. #endif /* SETREUID */
  13460. #endif /* !BSD41 */
  13461. #endif /* !BSD29 */
  13462. #endif /* ANYBSD */
  13463.  
  13464. /* Variables for user and group IDs. */
  13465.  
  13466. static UID_T realuid = (UID_T) -1, privuid = (UID_T) -1;
  13467. static GID_T realgid = (GID_T) -1, privgid = (GID_T) -1;
  13468.  
  13469.  
  13470. /* P R I V _ I N I  --  Initialize privileges package  */
  13471.  
  13472. /* Called as early as possible in a set-uid or set-gid program to store the
  13473.  * set-to uid and/or gid and step down to the users real uid and gid. The
  13474.  * stored id's can be temporarily restored (allowed in System V) during
  13475.  * operations that require the privilege.  Most of the time, the program
  13476.  * should execute in unpriviliged state, to not impose any security threat.
  13477.  *
  13478.  * Note: Don't forget that access() always uses the real id:s to determine
  13479.  * file access, even with privileges restored.
  13480.  *
  13481.  * Returns an error mask, with error values or:ed together:
  13482.  *   1 if setuid() fails,
  13483.  *   2 if setgid() fails, and
  13484.  *   4 if the program is set-user-id to "root", which can't be handled.
  13485.  *
  13486.  * Only the return value 0 indicates real success. In case of failure,
  13487.  * those privileges that could be reduced have been, at least, but the
  13488.  * program should be aborted none-the-less.
  13489.  *
  13490.  * Also note that these functions do not expect the uid or gid to change
  13491.  * without their knowing. It may work if it is only done temporarily, but
  13492.  * you're on your own.
  13493.  */
  13494. int
  13495. priv_ini() {
  13496.     int err = 0;
  13497.  
  13498.     /* Save real ID:s. */
  13499.     realuid = getuid();
  13500.     realgid = getgid();
  13501.  
  13502.     /* Save current effective ID:s, those set to at program exec. */
  13503.     privuid = geteuid();
  13504.     privgid = getegid();
  13505.  
  13506.     /* If running set-uid, go down to real uid, otherwise remember that
  13507.      * no privileged uid is available.
  13508.      *
  13509.      * Exceptions:
  13510.      *
  13511.      * 1) If the real uid is already "root" and the set-uid uid (the
  13512.      * initial effective uid) is not "root", then we would have trouble
  13513.      * if we went "down" to "root" here, and then temporarily back to the
  13514.      * set-uid uid (not "root") and then again tried to become "root". I
  13515.      * think the "saved set-uid" is lost when changing uid from effective
  13516.      * uid "root", which changes all uid, not only the effective uid. But
  13517.      * in this situation, we can simply go to "root" and stay there all
  13518.      * the time. That should give sufficient privilege (understatement!),
  13519.      * and give the right uids for subprocesses.
  13520.      *
  13521.      * 2) If the set-uid (the initial effective uid) is "root", and we
  13522.      * change uid to the real uid, we can't change it back to "root" when
  13523.      * we need the privilege, for the same reason as in 1). Thus, we can't
  13524.      * handle programs that are set-user-id to "root" at all. The program
  13525.      * should be stopped.  Use some other uid.  "root" is probably too
  13526.      * privileged for such things, anyway. (The uid is reverted to the
  13527.      * real uid until termination.)
  13528.      *
  13529.      * These two exceptions have the effect that the "root" uid will never
  13530.      * be one of the two uids that are being switched between, which also
  13531.      * means we don't have to check for such cases in the switching
  13532.      * functions.
  13533.      *
  13534.      * Note that exception 1) is handled by these routines (by constantly
  13535.      * running with uid "root", while exception 2) is a serious error, and
  13536.      * is not provided for at all in the switching functions.
  13537.      */
  13538.     if (realuid == privuid)
  13539.     privuid = (UID_T) -1;        /* Not running set-user-id. */
  13540.  
  13541.     /* If running set-gid, go down to real gid, otherwise remember that
  13542.      * no privileged gid is available.
  13543.      *
  13544.      * There are no exception like there is for the user id, since there
  13545.      * is no group id that is privileged in the manner of uid "root".
  13546.      * There could be equivalent problems for group changing if the
  13547.      * program sometimes ran with uid "root" and sometimes not, but
  13548.      * that is already avoided as explained above.
  13549.      *
  13550.      * Thus we can expect always to be able to switch to the "saved set-
  13551.      * gid" when we want, and back to the real gid again. You may also
  13552.      * draw the conclusion that set-gid provides for fewer hassles than
  13553.      * set-uid.
  13554.      */
  13555.  
  13556. #ifdef SUIDDEBUG
  13557.     fprintf(stderr,"UID_ROOT=%d\n",UID_ROOT);
  13558.     fprintf(stderr,"realuid=%d\n",realuid);
  13559.     fprintf(stderr,"privuid=%d\n",privuid);
  13560. #endif /* SUIDDEBUG */
  13561.  
  13562.     if (realgid == privgid)        /* If not running set-user-id, */
  13563.       privgid = (GID_T) -1;        /*  remember it this way. */
  13564.  
  13565.     err = priv_off();            /* Turn off setuid privilege. */
  13566.  
  13567.     if (privuid == UID_ROOT)        /* If setuid to root, */
  13568.       err |= 4;                /* return this error. */
  13569.  
  13570.     if (realuid == UID_ROOT) {        /* If real id is root, */
  13571.     privuid = (UID_T) -1;        /* stay root at all times. */
  13572. #ifdef ATT7300
  13573.     /* If Kermit installed SUID uucp and user is running as root */
  13574.     err &= ~1;            /* System V R0 does not save UID */
  13575. #endif /* ATT7300 */
  13576.     }
  13577.     return(err);
  13578. }
  13579.  
  13580.  
  13581. /* Macros for hiding the differences in UID/GID setting between various Unix
  13582.  * systems. These macros should always be called with both the privileged ID
  13583.  * and the non-privileged ID. The one in the second argument, will become the
  13584.  * effective ID. The one in the first argument will be retained for later
  13585.  * retrieval.
  13586.  */
  13587. #ifdef SETREUID
  13588. #ifdef SAVEDUID
  13589. /* On BSD systems with the saved-UID feature, we just juggle the effective
  13590.  * UID back and forth, and leave the real UID at its true value.  The kernel
  13591.  * allows switching to both the current real UID, the effective UID, and the
  13592.  * UID which the program is set-UID to.  The saved set-UID always holds the
  13593.  * privileged UID for us, and the real UID will always be the non-privileged,
  13594.  * and we can freely choose one of them for the effective UID at any time.
  13595.  */
  13596. #define switchuid(hidden,active) setreuid( (UID_T) -1, active)
  13597. #define switchgid(hidden,active) setregid( (GID_T) -1, active)
  13598.  
  13599. #else   /* SETREUID,!SAVEDUID */
  13600.  
  13601. /* On systems with setreXid() but without the saved-UID feature, notably
  13602.  * BSD 4.2, we swap the real and effective UIDs each time.  It's
  13603.  * the effective UID that we are interested in, but we have to retain the
  13604.  * unused UID somewhere to enable us to restore it later, and we do this
  13605.  * in the real UID.  The kernel only allows switching to either the current
  13606.  * real or the effective UID, unless you're "root".
  13607.  */
  13608. #define switchuid(hidden,active)    setreuid(hidden,active)
  13609. #define switchgid(hidden,active)    setregid(hidden,active)
  13610. #endif
  13611.  
  13612. #else /* !SETREUID, !SAVEDUID */
  13613.  
  13614. #ifdef SETEUID
  13615. /*
  13616.   BSD 4.4 works similarly to System V and POSIX (see below), but uses
  13617.   seteXid() instead of setXid() to change effective IDs.  In addition, the
  13618.   seteXid() functions work the same for "root" as for other users.
  13619. */
  13620. #define switchuid(hidden,active)    seteuid(active)
  13621. #define switchgid(hidden,active)    setegid(active)
  13622.  
  13623. #else /* !SETEUID */
  13624.  
  13625. /* On System V and POSIX, the only thing we can change is the effective UID
  13626.  * (unless the current effective UID is "root", but initsuid() avoids that for
  13627.  * us).  The kernel allows switching to the current real UID or to the saved
  13628.  * set-UID.  These are always set to the non-privileged UID and the privileged
  13629.  * UID, respectively, and we only change the effective UID.  This breaks if
  13630.  * the current effective UID is "root", though, because for "root" setuid/gid
  13631.  * becomes more powerful, which is why initsuid() treats "root" specially.
  13632.  * Note: That special treatment maybe could be ignored for BSD?  Note: For
  13633.  * systems that don't fit any of these four cases, we simply can't support
  13634.  * set-UID.
  13635.  */
  13636. #define switchuid(hidden,active)    setuid(active)
  13637. #define switchgid(hidden,active)    setgid(active)
  13638.  
  13639. #endif /* SETEUID */
  13640. #endif /* SETREUID */
  13641.  
  13642.  
  13643. /* P R I V _ O N  --  Turn on the setuid and/or setgid */
  13644.  
  13645. /* Go to the privileged uid (gid) that the program is set-user-id
  13646.  * (set-group-id) to, unless the program is running unprivileged.
  13647.  * If setuid() fails, return value will be 1. If getuid() fails it
  13648.  * will be 2.  Return immediately after first failure, and the function
  13649.  * tries to restore any partial work done.  Returns 0 on success.
  13650.  * Group id is changed first, since it is less serious than user id.
  13651.  */
  13652. int
  13653. priv_on() {
  13654.     if (privgid != (GID_T) -1)
  13655.       if (switchgid(realgid,privgid))
  13656.         return(2);
  13657.  
  13658.     if (privuid != (UID_T) -1)
  13659.       if (switchuid(realuid,privuid)) {
  13660.       if (privgid != (GID_T) -1)
  13661.         switchgid(privgid,realgid);
  13662.       return(1);
  13663.       }
  13664.     return(0);
  13665. }
  13666.  
  13667. /* P R I V _ O F F  --  Turn on the real uid and gid */
  13668.  
  13669. /* Return to the unprivileged uid (gid) after an temporary visit to
  13670.  * privileged status, unless the program is running without set-user-id
  13671.  * (set-group-id). Returns 1 for failure in setuid() and 2 for failure
  13672.  * in setgid() or:ed together. The functions tries to return both uid
  13673.  * and gid to unprivileged state, regardless of errors. Returns 0 on
  13674.  * success.
  13675.  */
  13676. int
  13677. priv_off() {
  13678.     int err = 0;
  13679.  
  13680.     if (privuid != (UID_T) -1)
  13681.        if (switchuid(privuid,realuid))
  13682.       err |= 1;
  13683.  
  13684.     if (privgid != (GID_T) -1)
  13685.        if (switchgid(privgid,realgid))
  13686.     err |= 2;
  13687.  
  13688.     return(err);
  13689. }
  13690.  
  13691. /* Turn off privilege permanently.  No going back.  This is necessary before
  13692.  * a fork() on BSD43 machines that don't save the setUID or setGID, because
  13693.  * we swap the real and effective ids, and we don't want to let the forked
  13694.  * process swap them again and get the privilege back. It will work on other
  13695.  * machines too, such that you can rely on its effect always being the same,
  13696.  * for instance, even when you're in priv_on() state when this is called.
  13697.  * (Well, that part about "permanent" is on System V only true if you follow
  13698.  * this with a call to exec(), but that's what we want it for anyway.)
  13699.  * Added by Dean Long -- dlong@midgard.ucsc.edu
  13700.  */
  13701. int
  13702. priv_can() {
  13703.  
  13704. #ifdef SETREUID
  13705.     int err = 0;
  13706.     if (privuid != (UID_T) -1)
  13707.        if (setreuid(realuid,realuid))
  13708.       err |= 1;
  13709.  
  13710.     if (privgid != (GID_T) -1)
  13711.         if (setregid(realgid,realgid))
  13712.        err |= 2;
  13713.  
  13714.     return(err);
  13715.  
  13716. #else
  13717. #ifdef SETEUID
  13718.     int err = 0;
  13719.     if (privuid != (UID_T) -1)
  13720.     if (setuid(realuid)) {
  13721.         debug(F101,"setuid failed","",errno);
  13722.         err |= 1;
  13723.         debug(F101,"ruid","",getuid());
  13724.         debug(F101,"euid","",geteuid());
  13725.     }
  13726.     debug(F101,"setuid","",realuid);
  13727.     if (privgid != (GID_T) -1)
  13728.         if (setgid(realgid)) {
  13729.         debug(F101,"setgid failed","",errno);
  13730.         err |= 2;
  13731.         debug(F101,"rgid","",getgid());
  13732.         debug(F101,"egid","",getegid());
  13733.     }
  13734.     debug(F101,"setgid","",realgid);
  13735.     return(err);
  13736. #else
  13737.     /* Easy way of using setuid()/setgid() instead of setreuid()/setregid().*/
  13738.     return(priv_off());
  13739. #endif /* SETEUID */
  13740. #endif /* SETREUID */
  13741. }
  13742.  
  13743. /* P R I V _ O P N  --  For opening protected files or devices. */
  13744.  
  13745. int
  13746. priv_opn(name, modes) char *name; int modes; {
  13747.     int x;
  13748.     priv_on();                /* Turn privileges on */
  13749.     debug(F111,"priv_opn",name,modes);
  13750.     errno = 0;
  13751.     x = open(name, modes);        /* Try to open the device */
  13752.     debug(F101,"priv_opn result","",x);
  13753.     debug(F101,"priv_opn errno","",errno);
  13754.     priv_off();                /* Turn privileges off */
  13755.     return(x);                /* Return open's return code */
  13756. }
  13757.  
  13758. /*  P R I V _ C H K  --  Check privileges.  */
  13759.  
  13760. /*  Try to turn them off.  If turning them off did not succeed, cancel them */
  13761.  
  13762. int
  13763. priv_chk() {
  13764.     int x, y = 0;
  13765.     x = priv_off();            /* Turn off privs. */
  13766.     if (x != 0 || getuid() == privuid || geteuid() == privuid)
  13767.       y = priv_can();
  13768.     if (x != 0 || getgid() == privgid || getegid() == privgid)
  13769.       y = y | priv_can();
  13770.     return(y);
  13771. }
  13772.  
  13773. UID_T
  13774. real_uid() {
  13775.     return(realuid);
  13776. }
  13777.  
  13778. VOID
  13779. ttimoff() {                /* Turn off any timer interrupts */
  13780.     /* int xx; */
  13781. /*
  13782.   As of 5A(183), we set SIGALRM to SIG_IGN (to ignore alarms) rather than to
  13783.   SIG_DFL (to catch alarms, or if there is no handler, to exit).  This is to
  13784.   cure (mask, really) a deeper problem with stray alarms that occurs on some
  13785.   systems, possibly having to do with sleep(), that caused core dumps.  It
  13786.   should be OK to do this, because no code in this module uses nested alarms.
  13787.   (But we still have to watch out for SCRIPT and DIAL...)
  13788. */
  13789.     /* xx = */ alarm(0);
  13790.     /* debug(F101,"ttimoff alarm","",xx); */
  13791.     if (saval) {            /* Restore any previous */
  13792.     signal(SIGALRM,saval);        /* alarm handler. */
  13793.     /* debug(F101,"ttimoff alarm restoring saval","",saval); */
  13794.     saval = NULL;
  13795.     } else {
  13796.     signal(SIGALRM,SIG_IGN);    /* Used to be SIG_DFL */
  13797.     /* debug(F100,"ttimoff alarm SIG_IGN","",0); */
  13798.     }
  13799. }
  13800.  
  13801. /* T T R U N C M D  --  Redirect an external command over the connection. */
  13802.  
  13803. #ifdef CK_REDIR
  13804. int
  13805. ttruncmd(s) char *s; {
  13806.     PID_T pid;                /* pid of lower fork */
  13807.     int wstat;                /* for wait() */
  13808.     int x;
  13809.     int statusp;
  13810.  
  13811.     if (ttyfd == -1) {
  13812.     printf("?Sorry, device is not open\n");
  13813.     return(0);
  13814.     }
  13815.     if (nopush) {
  13816.     debug(F100,"ttruncmd fail: nopush","",0);
  13817.     return(0);
  13818.     }
  13819.     conres();                /* Make console normal  */
  13820.     pexitstat = -4;
  13821.     if ((pid = fork()) == 0) {        /* Make a child fork */
  13822.     if (priv_can())            /* Child: turn off privs. */
  13823.       exit(1);
  13824.     dup2(ttyfd, 0);            /* Give stdin/out to the line */
  13825.     dup2(ttyfd, 1);
  13826.     x = system(s);
  13827.     debug(F101,"ttruncmd system",s,x);
  13828.     _exit(x ? BAD_EXIT : 0);
  13829.     } else {
  13830.     SIGTYP (*istat)(), (*qstat)();
  13831.     if (pid == (PID_T) -1)        /* fork() failed? */
  13832.       return(0);
  13833.     istat = signal(SIGINT,SIG_IGN); /* Let the fork handle keyboard */
  13834.     qstat = signal(SIGQUIT,SIG_IGN); /* interrupts itself... */
  13835.  
  13836. #ifdef COMMENT
  13837.         while (((wstat = wait(&statusp)) != pid) && (wstat != -1)) ;
  13838. #else  /* Not COMMENT */
  13839.         while (1) {
  13840.         wstat = wait(&statusp);
  13841.         debug(F101,"ttruncmd wait","",wstat);
  13842.         if (wstat == pid || wstat == -1)
  13843.           break;
  13844.     }
  13845. #endif /* COMMENT */
  13846.  
  13847.     pexitstat = (statusp & 0xff) ? statusp : statusp >> 8;
  13848.     debug(F101,"ttruncmd wait statusp","",statusp);
  13849.     debug(F101,"ttruncmd wait pexitstat","",pexitstat);
  13850.     signal(SIGINT,istat);        /* Restore interrupts */
  13851.     signal(SIGQUIT,qstat);
  13852.     }
  13853.     concb((char)escchr);        /* Restore console to CBREAK mode */
  13854.     return(statusp == 0 ? 1 : 0);
  13855. }
  13856. #endif /* CK_REDIR */
  13857.  
  13858. struct tm *
  13859. #ifdef CK_ANSIC
  13860. cmdate2tm(char * date, int gmt)         /* date as "yyyymmdd hh:mm:ss" */
  13861. #else
  13862. cmdate2tm(date,gmt) char * date; int gmt;
  13863. #endif
  13864. {
  13865.     /* date as "yyyymmdd hh:mm:ss" */
  13866.     static struct tm _tm;
  13867.     time_t now;
  13868.  
  13869.     if (strlen(date) != 17 ||
  13870.     date[8] != ' ' ||
  13871.     date[11] != ':' ||
  13872.     date[14] != ':')
  13873.       return(NULL);
  13874.  
  13875.     time(&now);
  13876.     if (gmt)
  13877.       _tm = *gmtime(&now);
  13878.     else
  13879.       _tm = *localtime(&now);
  13880.     _tm.tm_year = (date[0]-'0')*1000 + (date[1]-'0')*100 +
  13881.                   (date[2]-'0')*10   + (date[3]-'0')-1900;
  13882.     _tm.tm_mon  = (date[4]-'0')*10   + (date[5]-'0')-1;
  13883.     _tm.tm_mday = (date[6]-'0')*10   + (date[7]-'0');
  13884.     _tm.tm_hour = (date[9]-'0')*10   + (date[10]-'0');
  13885.     _tm.tm_min  = (date[12]-'0')*10  + (date[13]-'0');
  13886.     _tm.tm_sec  = (date[15]-'0')*10  + (date[16]-'0');
  13887.  
  13888.     /* Should we set _tm.tm_isdst to -1 here? */
  13889.  
  13890.     _tm.tm_wday = 0;
  13891.     _tm.tm_yday = 0;
  13892.  
  13893.     return(&_tm);
  13894. }
  13895.  
  13896. #ifdef OXOS
  13897. #undef kill
  13898. #endif /* OXOS */
  13899.  
  13900. #ifdef OXOS
  13901. int
  13902. priv_kill(pid, sig) int pid, sig; {
  13903.     int    i;
  13904.  
  13905.     if (priv_on())
  13906.     debug(F100,"priv_kill priv_on failed","",0);
  13907.     i = kill(pid, sig);
  13908.     if (priv_off())
  13909.     debug(F100,"priv_kill priv_off failed","",0);
  13910.     return(i);
  13911. }
  13912. #endif /* OXOS */
  13913.  
  13914. #ifdef BEOSORBEBOX
  13915. /* #ifdef BE_DR_7 */
  13916. /*
  13917.   alarm() function not supplied with Be OS DR7 - this one contributed by
  13918.   Neal P. Murphy.
  13919. */
  13920.  
  13921. /*
  13922.   This should mimic the UNIX/POSIX alarm() function well enough, with the
  13923.   caveat that one's SIGALRM handler must call alarm_expired() to clean up vars
  13924.   and wait for the alarm thread to finish.
  13925. */
  13926. unsigned int
  13927. alarm(unsigned int seconds) {
  13928.     long time_left = 0;
  13929.  
  13930. /* If an alarm is active, turn it off, saving the unused time */
  13931.     if (alarm_thread != -1) {
  13932.         /* We'll be generous and count partial seconds as whole seconds. */
  13933.         time_left = alarm_struct.time -
  13934.       ((system_time() - time_started) / 1000000.0);
  13935.  
  13936.         /* Kill the alarm thread */
  13937.         kill_thread (alarm_thread);
  13938.  
  13939.         /* We need to clean up as though the alarm occured. */
  13940.         time_started = 0;
  13941.         alarm_struct.thread = -1;
  13942.         alarm_struct.time = 0;
  13943.         alarm_expired();
  13944.     }
  13945.  
  13946. /* Set a new alarm clock, if requested. */
  13947.     if (seconds > 0) {
  13948.         alarm_struct.thread = find_thread(NULL);
  13949.         alarm_struct.time = seconds;
  13950.         time_started = system_time();
  13951.         alarm_thread = spawn_thread (do_alarm,
  13952.                                      "alarm_thread",
  13953.                                      B_NORMAL_PRIORITY,
  13954.                                      (void *) &alarm_struct
  13955.                      );
  13956.         resume_thread (alarm_thread);
  13957.     }
  13958.  
  13959. /* Now return [unused time | 0] */
  13960.     return ((unsigned int) time_left);
  13961. }
  13962.  
  13963. /*
  13964.   This function is the departure from UNIX/POSIX alarm handling. In the case
  13965.   of Be's missing alarm() function, this stuff needs to be done in the SIGALRM
  13966.   handler. When Be implements alarm(), this function call can be eliminated
  13967.   from user's SIGALRM signal handlers.
  13968. */
  13969.  
  13970. void
  13971. alarm_expired(void) {
  13972.     long ret_val;
  13973.  
  13974.     if (alarm_thread != -1) {
  13975.         wait_for_thread (alarm_thread, &ret_val);
  13976.         alarm_thread = -1;
  13977.     }
  13978. }
  13979.  
  13980. /*
  13981.   This is the function that snoozes the requisite number of seconds and then
  13982.   SIGALRMs the calling thread. Note that kill() wants a pid_t arg, whilst Be
  13983.   uses thread_id; currently they are both typdef'ed as long, but I'll do the
  13984.   cast anyway. This function is run in a separate thread.
  13985. */
  13986.  
  13987. long
  13988. do_alarm (void *alarm_struct) {
  13989.     snooze ((double) ((struct ALARM_STRUCT *) alarm_struct)->time * 1000000.0);
  13990.     kill ((pid_t)((struct ALARM_STRUCT *) alarm_struct)->thread, SIGALRM);
  13991.     time_started = 0;
  13992.     ((struct ALARM_STRUCT *) alarm_struct)->thread = -1;
  13993.     ((struct ALARM_STRUCT *) alarm_struct)->time = 0;
  13994. }
  13995. /* #endif */ /* BE_DR_7 */
  13996. #endif /* BEOSORBEBOX */
  13997.  
  13998. #ifdef Plan9
  13999.  
  14000. int
  14001. p9ttyctl(char letter, int num, int param) {
  14002.     char cmd[20];
  14003.     int len;
  14004.  
  14005.     if (ttyctlfd < 0)
  14006.       return -1;
  14007.  
  14008.     cmd[0] = letter;
  14009.     if (num)
  14010.       len = sprintf(cmd + 1, "%d", param) + 1;
  14011.     else {
  14012.     cmd[1] = param;
  14013.     len = 2;
  14014.     }
  14015.     if (write(ttyctlfd, cmd, len) == len) {
  14016.     cmd[len] = 0;
  14017.     /* fprintf(stdout, "wrote '%s'\n", cmd); */
  14018.     return 0;
  14019.     }
  14020.     return -1;
  14021. }
  14022.  
  14023. int
  14024. p9ttyparity(char l) {
  14025.     return p9ttyctl('p', 0, l);
  14026. }
  14027.  
  14028. int
  14029. p9tthflow(int flow, int status) {
  14030.     return p9ttyctl('m', 1, status);
  14031. }
  14032.  
  14033. int
  14034. p9ttsspd(int cps) {
  14035.     if (p9ttyctl('b', 1, cps * 10) < 0)
  14036.       return -1;
  14037.     ttylastspeed = cps * 10;
  14038.     return 0;
  14039. }
  14040.  
  14041. int
  14042. p9openttyctl(char *ttname) {
  14043.     char name[100];
  14044.  
  14045.     if (ttyctlfd >= 0) {
  14046.     close(ttyctlfd);
  14047.     ttyctlfd = -1;
  14048.     ttylastspeed = -1;
  14049.     }
  14050.     sprintf(name, "%sctl", ttname);
  14051.     ttyctlfd = open(name, 1);
  14052.     return ttyctlfd;
  14053. }
  14054.  
  14055. int
  14056. p9concb() {
  14057.     if (consctlfd >= 0) {
  14058.     if (write(consctlfd, "rawon", 5) == 5)
  14059.       return 0;
  14060.     }
  14061.     return -1;
  14062. }
  14063.  
  14064. int
  14065. p9conbin() {
  14066.     return p9concb();
  14067. }
  14068.  
  14069. int
  14070. p9conres() {
  14071.     if (consctlfd >= 0) {
  14072.     if (write(consctlfd, "rawoff", 6) == 6)
  14073.       return 0;
  14074.     }
  14075.     return -1;
  14076. }
  14077.  
  14078. int
  14079. p9sndbrk(int msec) {
  14080.     if (ttyctlfd >= 0) {
  14081.     char cmd[20];
  14082.     int i = sprintf(cmd, "k%d", msec);
  14083.     if (write(ttyctlfd, cmd, i) == i)
  14084.       return 0;
  14085.     }
  14086.     return -1;
  14087. }
  14088.  
  14089. int
  14090. conwrite(char *buf, int n) {
  14091.     int x;
  14092.     static int length = 0;
  14093.     static int holdingcr = 0;
  14094.     int normal = 0;
  14095.     for (x = 0; x < n; x++) {
  14096.     char c = buf[x];
  14097.     if (c == 007) {
  14098.         if (normal) {
  14099.         write(1, buf + (x - normal), normal);
  14100.         length += normal;
  14101.         normal = 0;
  14102.         }
  14103.         /* write(noisefd, "1000 300", 8); */
  14104.         holdingcr = 0;
  14105.     } else if (c == '\r') {
  14106.         if (normal) {
  14107.         write(1, buf + (x - normal), normal);
  14108.         length += normal;
  14109.         normal = 0;
  14110.         }
  14111.         holdingcr = 1;
  14112.     } else if (c == '\n') {
  14113.         write(1, buf + (x - normal), normal + 1);
  14114.         normal = 0;
  14115.         length = 0;
  14116.         holdingcr = 0;
  14117.     } else if (c == '\b') {
  14118.         if (normal) {
  14119.         write(1, buf + (x - normal), normal);
  14120.         length += normal;
  14121.         normal = 0;
  14122.         }
  14123.         if (length) {
  14124.         write(1, &c, 1);
  14125.         length--;
  14126.         }
  14127.         holdingcr = 0;
  14128.     } else {
  14129.         if (holdingcr) {
  14130.         char b = '\b';
  14131.         while (length-- > 0)
  14132.           write(1, &b, 1);
  14133.         length = 0;    /* compiler bug */
  14134.         }
  14135.         holdingcr = 0;
  14136.         normal++;
  14137.     }
  14138.     }
  14139.     if (normal) {
  14140.     write(1, buf + (x - normal), normal);
  14141.     length += normal;
  14142.     }
  14143.     return n;
  14144. }
  14145.  
  14146. void
  14147. conprint(char *fmt, ...) {
  14148.     static char buf[1000];        /* not safe if on the stack */
  14149.  
  14150.     va_list ap;
  14151.     int i;
  14152.  
  14153.     va_start(ap, fmt);
  14154.     i = vsprintf(buf, fmt, ap);
  14155.     conwrite(buf, i);
  14156. }
  14157. #endif /* Plan9 */
  14158.  
  14159. /* fprintf, printf, perror replacements... */
  14160.  
  14161. /* f p r i n t f */
  14162.  
  14163. #ifdef UNIX
  14164. #ifdef CK_ANSIC
  14165. #include <stdarg.h>
  14166. #else /* CK_ANSIC */
  14167. #include <varargs.h>
  14168. #endif /* CK_ANSIC */
  14169. #ifdef fprintf
  14170. #undef fprintf
  14171. static char str1[4096];
  14172. static char str2[4096];
  14173. int
  14174. #ifdef CK_ANSIC
  14175. ckxfprintf(FILE * file, const char * format, ...)
  14176. #else /* CK_ANSIC */
  14177. ckxfprintf(va_alist) va_dcl
  14178. #endif /* CK_ANSIC */
  14179. /* ckxfprintf */ {
  14180.     int i, j, len, got_cr;
  14181.     va_list args;
  14182.     int rc = 0;
  14183.  
  14184. #ifdef CK_ANSIC
  14185.     va_start(args, format);
  14186. #else /* CK_ANSIC */
  14187.     char * format;
  14188.     FILE * file;
  14189.     va_start(args);
  14190.     file = va_arg(args,FILE *);
  14191.     format = va_arg(args,char *);
  14192. #endif /* CK_ANSIC */
  14193.  
  14194.     if (!inserver || (file != stdout && file != stderr && file != stdin)) {
  14195.     rc = vfprintf(file,format,args);
  14196.     } else {
  14197.     unsigned int c;
  14198.         rc = vsprintf(str1, format, args);
  14199.         len = strlen(str1);
  14200.         if (len >= sizeof(str1)) {
  14201.             debug(F101,"ckxfprintf() buffer overflow","",len);
  14202.             doexit(BAD_EXIT,1);
  14203.         }
  14204.         for (i = 0, j = 0, got_cr = 0;
  14205.          i < len && j < sizeof(str1)-2;
  14206.          i++, j++ ) {
  14207.         /* We can't use 255 as a case label because of signed chars */
  14208.         c = (unsigned)(str1[i] & 0xff);
  14209. #ifdef TNCODE
  14210.         if (c == 255) {
  14211.         if (got_cr && !TELOPT_ME(TELOPT_BINARY))
  14212.           str2[j++] = '\0';
  14213.         str2[j++] = IAC;
  14214.         str2[j] = IAC;
  14215.         got_cr = 0;
  14216.         } else
  14217. #endif /* TNCODE */
  14218.         switch (c) {
  14219.           case '\r':
  14220.                 if (got_cr
  14221. #ifdef TNCODE
  14222.             && !TELOPT_ME(TELOPT_BINARY)
  14223. #endif /* TNCODE */
  14224.             )
  14225.           str2[j++] = '\0';
  14226.                 str2[j] = str1[i];
  14227.                 got_cr = 1;
  14228.                 break;
  14229.           case '\n':
  14230.                 if (!got_cr)
  14231.           str2[j++] = '\r';
  14232.                 str2[j] = str1[i];
  14233.                 got_cr = 0;
  14234.                 break;
  14235.           default:
  14236.                 if (got_cr
  14237. #ifdef TNCODE
  14238.             && !TELOPT_ME(TELOPT_BINARY)
  14239. #endif /* TNCODE */
  14240.             )
  14241.           str2[j++] = '\0';
  14242.                 str2[j] = str1[i];
  14243.                 got_cr = 0;
  14244.             }
  14245.         }
  14246.         if (got_cr
  14247. #ifdef TNCODE
  14248.              && !TELOPT_ME(TELOPT_BINARY)
  14249. #endif /* TNCODE */
  14250.              )
  14251.             str2[j++] = '\0';
  14252. #ifdef CK_ENCRYPTION
  14253. #ifdef TNCODE
  14254.         if (TELOPT_ME(TELOPT_ENCRYPTION))
  14255.       ck_tn_encrypt(str2,j);
  14256. #endif /* TNCODE */
  14257. #endif /* CK_ENCRYPTION */
  14258. #ifdef CK_SSL
  14259.     if (inserver && (ssl_active_flag || tls_active_flag)) {
  14260.         /* Write using SSL */
  14261.             char * p = str2;
  14262.           ssl_retry:
  14263.             if (ssl_active_flag)
  14264.           rc = SSL_write(ssl_con, p, j);
  14265.             else
  14266.           rc = SSL_write(tls_con, p, j);
  14267.         debug(F111,"ckxfprintf","SSL_write",rc);
  14268.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,rc)) {
  14269.           case SSL_ERROR_NONE:
  14270.                 if (rc == j)
  14271.           break;
  14272.                 p += rc;
  14273.                 j -= rc;
  14274.                 goto ssl_retry;
  14275.           case SSL_ERROR_WANT_WRITE:
  14276.           case SSL_ERROR_WANT_READ:
  14277.           case SSL_ERROR_SYSCALL:
  14278.                 if (rc != 0)
  14279.           return(-1);
  14280.           case SSL_ERROR_WANT_X509_LOOKUP:
  14281.           case SSL_ERROR_SSL:
  14282.           case SSL_ERROR_ZERO_RETURN:
  14283.           default:
  14284.                 rc = 0;
  14285.             }
  14286.     } else
  14287. #endif /* CK_SSL */
  14288.         fwrite(str2,sizeof(char),j,stdout);
  14289.     }
  14290.     va_end(args);
  14291.     return(rc);
  14292. }
  14293. #endif /* fprintf */
  14294.  
  14295. /* p r i n t f */
  14296.  
  14297. #ifdef printf
  14298. #undef printf
  14299. int
  14300. #ifdef CK_ANSIC
  14301. ckxprintf(const char * format, ...)
  14302. #else /* CK_ANSIC */
  14303. ckxprintf(va_alist) va_dcl
  14304. #endif /* CK_ANSIC */
  14305. /* ckxprintf */ {
  14306.     int i, j, len, got_cr;
  14307.     va_list args;
  14308.     int rc = 0;
  14309.  
  14310. #ifdef CK_ANSIC
  14311.     va_start(args, format);
  14312. #else /* CK_ANSIC */
  14313.     char * format;
  14314.     va_start(args);
  14315.     format = va_arg(args,char *);
  14316. #endif /* CK_ANSIC */
  14317.  
  14318.     if (!inserver) {
  14319.     rc = vprintf(format, args);
  14320.     } else {
  14321.     unsigned int c;
  14322.         rc = vsprintf(str1, format, args);
  14323.         len = strlen(str1);
  14324.         if (len >= sizeof(str1)) {
  14325.             debug(F101,"ckxprintf() buffer overflow","",len);
  14326.             doexit(BAD_EXIT,1);
  14327.         }
  14328.         for (i = 0, j = 0, got_cr=0;
  14329.          i < len && j < sizeof(str1)-2;
  14330.          i++, j++ ) {
  14331.         c = (unsigned)(str1[i] & 0xff);
  14332. #ifdef TNCODE
  14333.         if (c == 255) {
  14334.         if (got_cr && !TELOPT_ME(TELOPT_BINARY))
  14335.           str2[j++] = '\0';
  14336.         str2[j++] = IAC;
  14337.         str2[j] = IAC;
  14338.         got_cr = 0;
  14339.         } else
  14340. #endif /* TNCODE */
  14341.         switch (c) {
  14342.           case '\r':
  14343.                 if (got_cr
  14344. #ifdef TNCODE
  14345.             && !TELOPT_ME(TELOPT_BINARY)
  14346. #endif /* TNCODE */
  14347.             )
  14348.           str2[j++] = '\0';
  14349.                 str2[j] = str1[i];
  14350.                 got_cr = 1;
  14351.                 break;
  14352.           case '\n':
  14353.                 if (!got_cr)
  14354.           str2[j++] = '\r';
  14355.                 str2[j] = str1[i];
  14356.                 got_cr = 0;
  14357.                 break;
  14358.           default:
  14359.                 if (got_cr
  14360. #ifdef TNCODE
  14361.             && !TELOPT_ME(TELOPT_BINARY)
  14362. #endif /* TNCODE */
  14363.             )
  14364.           str2[j++] = '\0';
  14365.                 str2[j] = str1[i];
  14366.                 got_cr = 0;
  14367.                 break;
  14368.         }
  14369.         }
  14370.         if (got_cr
  14371. #ifdef TNCODE
  14372.              && !TELOPT_ME(TELOPT_BINARY)
  14373. #endif /* TNCODE */
  14374.              )
  14375.             str2[j++] = '\0';
  14376. #ifdef CK_ENCRYPTION
  14377. #ifdef TNCODE
  14378.         if (TELOPT_ME(TELOPT_ENCRYPTION))
  14379.       ck_tn_encrypt(str2,j);
  14380. #endif /* TNCODE */
  14381. #endif /* CK_ENCRYPTION */
  14382. #ifdef CK_SSL
  14383.     if (inserver && (ssl_active_flag || tls_active_flag)) {
  14384.             char * p = str2;
  14385.         /* Write using SSL */
  14386.           ssl_retry:
  14387.             if (ssl_active_flag)
  14388.           rc = SSL_write(ssl_con, p, j);
  14389.             else
  14390.           rc = SSL_write(tls_con, p, j);
  14391.         debug(F111,"ckxprintf","SSL_write",rc);
  14392.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,rc)) {
  14393.           case SSL_ERROR_NONE:
  14394.                 if (rc == j)
  14395.           break;
  14396.                 p += rc;
  14397.                 j -= rc;
  14398.                 goto ssl_retry;
  14399.           case SSL_ERROR_WANT_WRITE:
  14400.           case SSL_ERROR_WANT_READ:
  14401.           case SSL_ERROR_SYSCALL:
  14402.                 if (rc != 0)
  14403.           return(-1);
  14404.           case SSL_ERROR_WANT_X509_LOOKUP:
  14405.           case SSL_ERROR_SSL:
  14406.           case SSL_ERROR_ZERO_RETURN:
  14407.           default:
  14408.                 rc = 0;
  14409.             }
  14410.     } else
  14411. #endif /* CK_SSL */
  14412.       rc = fwrite(str2,sizeof(char),j,stdout);
  14413.     }
  14414.     va_end(args);
  14415.     return(rc);
  14416. }
  14417. #endif /* printf */
  14418.  
  14419. /*  p e r r o r  */
  14420.  
  14421. #ifdef perror
  14422. #undef perror
  14423. _PROTOTYP(char * ck_errstr,(VOID));
  14424. #ifdef NEXT
  14425. void
  14426. #else
  14427. #ifdef CK_SCOV5
  14428. void
  14429. #else
  14430. int
  14431. #endif /* CK_SCOV5 */
  14432. #endif /* NEXT */
  14433. #ifdef CK_ANSIC
  14434. ckxperror(const char * str)
  14435. #else /* CK_ANSIC */
  14436. ckxperror(str) char * str;
  14437. #endif /* CK_ANSIC */
  14438. /* ckxperror */ {
  14439.     char * errstr = ck_errstr();
  14440. #ifndef NEXT
  14441. #ifndef CK_SCOV5
  14442.     return
  14443. #endif /* CK_SCOV5 */
  14444. #endif /* NEXT */
  14445.       ckxprintf("%s%s %s\n",str,*errstr?":":"",errstr);
  14446. }
  14447. #endif /* perror */
  14448. #endif /* UNIX */
  14449.  
  14450. #ifdef MINIX2
  14451.  
  14452. /* Minix doesn't have a gettimeofday call. We fake one here using time(2) */
  14453.  
  14454. int
  14455. gettimeofday(struct timeval *tp, struct timezone *tzp) {
  14456.     tp->tv_usec = 0L;            /* Close enough for horseshoes */
  14457.     if(time(&(tp->tv_sec))==-1)
  14458.       return(-1);
  14459.     return(0);
  14460. }
  14461.  
  14462. /* Minix does not support symbolic links. We implement a version of
  14463.    readlink that always fails */
  14464.  
  14465. int
  14466. readlink(const char *path, void *buf, size_t bufsiz) {
  14467.     errno = ENOSYS;
  14468.     return(-1);
  14469. }
  14470. #endif /* MINIX2 */
  14471.