home *** CD-ROM | disk | FTP | other *** search
/ kermit.columbia.edu / kermit.columbia.edu.tar / kermit.columbia.edu / tmp4 / ckutio.c < prev    next >
C/C++ Source or Header  |  2009-10-16  |  470KB  |  15,986 lines

  1. #define CKUTIO_C
  2.  
  3. #ifdef aegis
  4. char *ckxv = "Aegis Communications support, 9.0.318, 16 Oct 2009";
  5. #else
  6. #ifdef Plan9
  7. char *ckxv = "Plan 9 Communications support, 9.0.318, 16 Oct 2009";
  8. #else
  9. char *ckxv = "UNIX Communications support, 9.0.318, 16 Oct 2009";
  10. #endif /* Plan9 */
  11. #endif /* aegis */
  12.  
  13. /*  C K U T I O  */
  14.  
  15. /* C-Kermit interrupt, communications control and I/O functions for UNIX */
  16.  
  17. /*
  18.   Author: Frank da Cruz (fdc@columbia.edu),
  19.   Columbia University Academic Information Systems, New York City.
  20.  
  21.   Copyright (C) 1985, 2009,
  22.     Trustees of Columbia University in the City of New York.
  23.     All rights reserved.  See the C-Kermit COPYING.TXT file or the
  24.     copyright text in the ckcmai.c module for disclaimer and permissions.
  25. */
  26.  
  27. /*
  28.   NOTE TO CONTRIBUTORS: This file, and all the other C-Kermit files, must be
  29.   compatible with C preprocessors that support only #ifdef, #else, #endif,
  30.   #define, and #undef.  Please do not use #if, logical operators, or other
  31.   preprocessor features in any of the portable C-Kermit modules.  You can,
  32.   of course, use these constructions in platform-specific modules when they
  33.   are supported by all compilers/preprocessors that could be used on that
  34.   platform.
  35. */
  36.  
  37. extern int nettype;            /* Defined in ckcmai.c */
  38. extern int duplex;
  39.  
  40. /* Includes */
  41.  
  42. #include "ckcsym.h"            /* This must go first   */
  43. #include "ckcdeb.h"            /* This must go second  */
  44.  
  45. #ifdef OSF13
  46. #ifdef CK_ANSIC
  47. #ifdef _NO_PROTO
  48. #undef _NO_PROTO
  49. #endif /* _NO_PROTO */
  50. #endif /* CK_ANSIC */
  51. #endif /* OSF13 */
  52.  
  53. #include <errno.h>            /* System error numbers */
  54.  
  55. #ifdef __386BSD__
  56. #define ENOTCONN 57
  57. #else
  58. #ifdef __bsdi__
  59. #define ENOTCONN 57
  60. #else
  61. #ifdef __FreeBSD__
  62. #define ENOTCONN 57
  63. #endif /* __FreeBSD__ */
  64. #endif /* __bsdi__ */
  65. #endif /* __386BSD__ */
  66.  
  67. #ifdef SCO_OSR504
  68. #define NBBY 8
  69. #endif /* SCO_OSR504 */
  70.  
  71. #ifdef Plan9
  72. #define SELECT
  73. #include <sys/time.h>
  74. #include <select.h>
  75. #define FD_SETSIZE (3 * sizeof(long) * 8)
  76. static struct timeval tv;
  77. #endif /* Plan9 */
  78.  
  79. #ifdef CLIX
  80. #include <sys/time.h>
  81. #endif /* CLIX */
  82.  
  83. #include "ckcnet.h"            /* Symbols for network types. */
  84. #ifdef CK_SSL
  85. #include "ck_ssl.h"
  86. #endif /* CK_SSL */
  87.  
  88. /*
  89.   The directory-related includes are here because we need to test some
  90.   file-system-related symbols to find out which system we're being compiled
  91.   under.  For example, MAXNAMLEN is defined in BSD4.2 but not 4.1.
  92. */
  93. #ifdef SDIRENT                /* Directory bits... */
  94. #define DIRENT
  95. #endif /* SDIRENT */
  96.  
  97. #ifdef XNDIR
  98. #include <sys/ndir.h>
  99. #else /* !XNDIR */
  100. #ifdef NDIR
  101. #include <ndir.h>
  102. #else /* !NDIR, !XNDIR */
  103. #ifdef RTU
  104. #include "/usr/lib/ndir.h"
  105. #else /* !RTU, !NDIR, !XNDIR */
  106. #ifdef DIRENT
  107. #ifdef SDIRENT
  108. #include <sys/dirent.h>
  109. #else
  110. #include <dirent.h>
  111. #endif /* SDIRENT */
  112. #else /* !RTU, !NDIR, !XNDIR, !DIRENT, i.e. all others */
  113. #include <sys/dir.h>
  114. #endif /* DIRENT */
  115. #endif /* RTU */
  116. #endif /* NDIR */
  117. #endif /* XNDIR */
  118.  
  119. #ifdef QNX
  120. #include <sys/dev.h>
  121. #endif /* QNX */
  122.  
  123. #ifdef HPUX5
  124. #ifndef TCPSOCKET
  125. /* I don't know why this is needed here since we never reference bzero(). */
  126. /* But without it C-Kermit won't link in an HP-UX 5.xx non-TCP build. */
  127. void
  128. bzero(s,n) char *s; int n; {
  129.     extern char * memset();
  130.     memset(s,0,n);
  131. }
  132. #endif /* TCPSOCKET */
  133. #endif /* HPUX5 */
  134.  
  135. /* Definition of HZ, used in msleep() */
  136.  
  137. #ifdef MIPS
  138. #define HZ ( 1000 / CLOCK_TICK )
  139. #else  /* MIPS */
  140. #ifdef ATTSV
  141. #ifndef NAP
  142. #ifdef TRS16
  143. #define HZ ( 1000 / CLOCK_TICK )
  144. #endif /* TRS16 */
  145. #ifdef NAPHACK
  146. #define nap(x) (void)syscall(3112, (x))
  147. #define NAP
  148. #endif /* NAPHACK */
  149. #endif /* NAP */
  150. #endif /* ATTSV */
  151. #endif /* MIPS */
  152.  
  153. #ifdef M_UNIX
  154. #undef NGROUPS_MAX        /* Prevent multiple definition warnings */
  155. #endif /* M_UNIX */
  156.  
  157. /*
  158.   NOTE: HP-UX 8.0 has a <sys/poll.h>, but there is no corresponding
  159.   library routine, so _poll comes up undefined at link time.
  160. */
  161. #ifdef CK_POLL
  162. #ifndef AIXRS            /* IBM AIX needs special handling */
  163. #include <poll.h>        /* "standard" (SVID) i/o multiplexing, etc */
  164. #else /* AIXRS */
  165. #ifdef SVR4            /* AIX 3.2 is like SVID... */
  166. #include <poll.h>
  167. #else                /* But AIX 3.1 is not ... */
  168. #include <sys/poll.h>        /* The include file is in include/sys */
  169. #define events reqevents    /* And it does not map IBM-specific member */
  170. #define revents rtnevents    /* names to the System V equivalents */
  171. #endif /* SVR4 */
  172. #endif /* AIXRS */
  173. #endif /* CK_POLL */
  174.  
  175. #include <signal.h>                     /* Signals */
  176.  
  177. /* For setjmp and longjmp */
  178.  
  179. #ifndef ZILOG
  180. #include <setjmp.h>
  181. #else
  182. #include <setret.h>
  183. #endif /* ZILOG */
  184.  
  185. /*
  186.   The following test differentiates between 4.1 BSD and 4.2 & later.
  187.   If you have a 4.1BSD system with the DIRENT library, this test could
  188.   mistakenly diagnose 4.2BSD and then later enable the use of system calls
  189.   that aren't defined.  If indeed there are such systems, we can use some
  190.   other way of testing for 4.1BSD, or add yet another compile-time switch.
  191. */
  192. #ifdef BSD4
  193. #ifdef MAXNAMLEN
  194. #ifndef FT21                /* Except for Fortune. */
  195. #ifndef FT18
  196. #ifndef BELLV10                /* And Bell Labs Research UNIX V10 */
  197. #define BSD42
  198. #endif /* BELLV10 */
  199. #endif /* FT18 */
  200. #endif /* FT21 */
  201. #endif /* MAXNAMLEN */
  202. #endif /* BSD4 */
  203. /*
  204.   Minix 2.0 support added by Terry McConnell,
  205.   Syracuse University <tmc@barnyard.syr.edu>
  206.   No more sgtty interface, posix compliant.
  207. */
  208. #ifdef MINIX2
  209. #define _MINIX   /* Needed for some Minix header files */
  210. #undef MINIX     /* Old minix 1.0: used sgtty interface */
  211. #define BSD44ORPOSIX
  212. #define SVORPOSIX
  213. #ifndef MINIX3
  214. #define DCLTIMEVAL
  215. #endif    /* MINIX3 */
  216. #define NOFILEH
  217. #include <sys/types.h>
  218. #include <sys/ioctl.h>
  219. #include <termios.h>
  220. #include <limits.h>
  221. #undef TIOCGETC    /* defined in sys/ioctl.h, but not really supported */
  222. #define TANDEM 0
  223. #endif /* MINIX2 */
  224.  
  225. /*
  226.  MINIX 1.0 support added by Charles Hedrick,
  227.  Rutgers University <hedrick@aramis.rutgers.edu>.
  228.  MINIX also has V7 enabled.
  229. */
  230. #ifdef MINIX
  231. #define TANDEM 0
  232. #define MYREAD
  233. #define NOSYSIOCTLH
  234. #include <limits.h>
  235. #endif /* MINIX */
  236.  
  237. #ifdef CK_REDIR        /* <sys/wait.h> needed only for REDIRECT command. */
  238. /*
  239.   If anybody can figure out how to make this work with NeXTSTEP, be
  240.   my guest!  (NeXTBlah/NeXTBlah/bsd/sys/wait.h does not define WEXITSTATUS)
  241. */
  242. #ifndef CK_WAIT_H            /* If wait.h not already included... */
  243. #ifdef OSF                /* force OSF to select POSIX wait */
  244. #ifdef _BSD                /* instead of BSD (see ckcdeb.h) */
  245. #define CK_OSF_BSD
  246. #undef _BSD
  247. #endif /* _BSD */
  248. #endif /* OSF */
  249. #include <sys/wait.h>            /* Include it */
  250. #ifdef OSF
  251. #ifdef CK_OSF_BSD
  252. #define _BSD                /* Restore it */
  253. #undef CK_OSF_BSD
  254. #endif /* CK_OSF_BSD */
  255. #endif /* OSF */
  256. #endif /* CK_WAIT_H */
  257. #endif /* CK_REDIR */
  258.  
  259. #include "ckuver.h"            /* Version herald */
  260. char *ckxsys = HERALD;
  261.  
  262. #ifdef CK_UTSNAME
  263. #include <sys/utsname.h>
  264.  
  265. #ifdef TRU64                /* Tru64 UNIX 4.0 and later */
  266. /* Verified on Tru64 4.0F - might break on 4.0E or earlier */
  267. #include <sys/sysinfo.h>        /* (don't know about OSF/1 or DU) */
  268. #include <machine/hal_sysinfo.h>
  269. #endif /* TRU64 */
  270.  
  271. #ifdef SOLARIS25            /* Solaris 2.5 and later */
  272. #include <sys/systeminfo.h>        /* (don't know about earlier ones) */
  273. #endif /* SOLARIS25 */
  274.  
  275. #ifdef UW7
  276. #ifndef SYS_NMLN
  277. #define SYS_NMLN 257
  278. #endif /* NMLN */
  279. #endif /* UW7 */
  280. #ifdef HPUX9PLUS
  281. static int hpis800 = 0;
  282. #endif /* HPUX9PLUS */
  283. #ifdef SYS_NMLN
  284. #define CK_SYSNMLN SYS_NMLN
  285. #else
  286. #ifdef _SYS_NMLN
  287. #define CK_SYSNMLN _SYS_NMLN
  288. #else
  289. #ifdef UTSLEN
  290. #define CK_SYSNMLN UTSLEN
  291. #else
  292. #define CK_SYSNMLN 31
  293. #endif /* UTSLEN */
  294. #endif /* _SYS_NMLN */
  295. #endif /* SYS_NMLN */
  296. char unm_mch[CK_SYSNMLN+1] = { '\0', '\0' };
  297. char unm_mod[CK_SYSNMLN+1] = { '\0', '\0' };
  298. char unm_nam[CK_SYSNMLN+1] = { '\0', '\0' };
  299. char unm_rel[CK_SYSNMLN+1] = { '\0', '\0' };
  300. char unm_ver[CK_SYSNMLN+1] = { '\0', '\0' };
  301. #endif /* CK_UTSNAME */
  302.  
  303. #ifdef CIE
  304. #include <stat.h>            /* For chasing symlinks, etc. */
  305. #else
  306. #include <sys/stat.h>
  307. #endif /* CIE */
  308.  
  309. /* UUCP lockfile material... */
  310.  
  311. #ifndef NOUUCP
  312. #ifdef USETTYLOCK
  313. #ifdef HAVE_BAUDBOY            /* Red Hat baudboy/lockdev */
  314. /*
  315.   Watch out: baudboy.h references open() without making sure it has been
  316.   declared, resulting in warnings on at least Red Hat 7.3.  It's declared in
  317.   fcntl.h, but we don't include that until later.  In this case only, we
  318.   include it here, and then the second include is harmless because in Red Hat
  319.   Linux (the only place where you find baudboy.h) fcntl.h is protected from
  320.   multiple inclusion by _FCNTL_H.   - fdc, 10 May 2004.
  321.  
  322.   NOTE: Although Linux /usr/sbin/lockdev obviates the need for setuid or
  323.   setgid bits to access the lockfile, C-Kermit will still need them to access
  324.   the serial port itself unless the port is open for world read/write.
  325.   Normally setgid uucp does the trick.
  326.  
  327.  */
  328. #include <fcntl.h>            /* This has to come before baudboy */
  329. #include <baudboy.h>
  330. #define LOCK_DIR "/var/lock"        /* (even though we don't care) */
  331.  
  332. #else  /* !HAVE_BAUDBOY */
  333.  
  334. #ifdef USE_UU_LOCK
  335. #ifdef __FreeBSD__
  336. #include <libutil.h>            /* FreeBSD */
  337. #else
  338. #include <util.h>            /* OpenBSD */
  339. #endif /* HAVE_BAUDBOY */
  340. #endif /* __FreeBSD */
  341. #endif /* USE_UU_LOCK */
  342. #else  /* USETTYLOCK */
  343.  
  344. /* Name of UUCP tty device lockfile */
  345.  
  346. #ifdef LINUXFSSTND
  347. #ifndef HDBUUCP
  348. #define HDBUUCP
  349. #endif /* HDBUUCP */
  350. #endif /* LINUXFSSTND */
  351.  
  352. #ifdef ACUCNTRL
  353. #define LCKDIR
  354. #endif /* ACUCNTRL */
  355.  
  356. /*
  357.   PIDSTRING means use ASCII string to represent pid in lockfile.
  358. */
  359. #ifndef PIDSTRING
  360. #ifdef HDBUUCP
  361. #define PIDSTRING
  362. #else
  363. #ifdef BSD44
  364. #define PIDSTRING
  365. #else
  366. #ifdef RTAIX
  367. #define PIDSTRING
  368. #else
  369. #ifdef AIXRS
  370. #define PIDSTRING
  371. #else
  372. #ifdef COHERENT
  373. #define PIDSTRING
  374. #endif /* COHERENT */
  375. #endif /* AIXRS */
  376. #endif /* RTAIX */
  377. #endif /* BSD44 */
  378. #endif /* HDBUUCP */
  379. #endif /* PIDSTRING */
  380.  
  381. /* Now the PIDSTRING exceptions... */
  382.  
  383. #ifdef PIDSTRING
  384. #ifdef HPUX
  385. #undef PIDSTRING
  386. #endif /* HPUX */
  387. #endif /* PIDSTRING */
  388.  
  389. #ifdef __bsdi__                /* BSDI (at least thru 1.1) */
  390. #ifdef PIDSTRING
  391. #undef PIDSTRING
  392. #endif /* PIDSTRING */
  393. #endif /* __bsdi__ */
  394.  
  395. #ifdef OSF32                /* Digital UNIX (OSF/1) 3.2 */
  396. #ifdef PIDSTRING
  397. #undef PIDSTRING
  398. #endif /* PIDSTRING */
  399. #endif /* OSF32 */
  400.  
  401. /*
  402.   LOCK_DIR is the name of the lockfile directory.
  403.   If LOCK_DIR is already defined (e.g. on command line), we don't change it.
  404. */
  405.  
  406. #ifndef LOCK_DIR
  407. #ifdef MACOSX
  408. #define LOCK_DIR "/var/spool/lock"
  409. #endif /* MACOSX */
  410. #endif/* LOCK_DIR */
  411.  
  412. #ifndef LOCK_DIR
  413. #ifdef BSD44
  414. #ifdef __386BSD__
  415. #define LOCK_DIR "/var/spool/lock"
  416. #else
  417. #ifdef __FreeBSD__
  418. #define LOCK_DIR "/var/spool/lock"
  419. #else
  420. #ifdef __NetBSD__
  421. #define LOCK_DIR "/var/spool/lock"
  422. #else
  423. #ifdef __OpenBSD__
  424. #define LOCK_DIR "/var/spool/lock"
  425. #else
  426. /* So which ones is this for? */
  427. /* Probably original 4.4BSD on Vangogh */
  428. /* Plus who knows about Mac OS X... It doesn't even have a cu program */
  429. #define LOCK_DIR "/var/spool/uucp"
  430. #endif /* __OpenBSD__ */
  431. #endif /* __NetBSD__ */
  432. #endif /* __FreeBSD__ */
  433. #endif /* __386BSD__ */
  434. #else
  435. #ifdef DGUX430
  436. #define LOCK_DIR "/var/spool/locks"
  437. #else
  438. #ifdef HPUX10
  439. #define LOCK_DIR "/var/spool/locks"
  440. #else
  441. #ifdef RTAIX                /* IBM RT PC AIX 2.2.1 */
  442. #define LOCK_DIR "/etc/locks"
  443. #else
  444. #ifdef AIXRS
  445. #define LOCK_DIR "/etc/locks"
  446. #else
  447. #ifdef ISIII
  448. #define LOCK_DIR "/etc/locks"
  449. #else
  450. #ifdef HDBUUCP
  451. #ifdef M_SYS5
  452. #define LOCK_DIR "/usr/spool/uucp"
  453. #else
  454. #ifdef M_UNIX
  455. #define LOCK_DIR "/usr/spool/uucp"
  456. #else
  457. #ifdef SVR4
  458. #define LOCK_DIR "/var/spool/locks"
  459. #else
  460. #ifdef SUNOS4
  461. #define LOCK_DIR "/var/spool/locks"
  462. #else
  463. #ifdef LINUXFSSTND
  464. #define LOCK_DIR "/var/lock";
  465. #else
  466. #define LOCK_DIR "/usr/spool/locks"
  467. #endif /* LINUXFSSTND */
  468. #endif /* SUNOS4 */
  469. #endif /* SVR4 */
  470. #endif /* M_UNIX */
  471. #endif /* M_SYS5 */
  472. #else
  473. #ifdef LCKDIR
  474. #define LOCK_DIR "/usr/spool/uucp/LCK"
  475. #else
  476. #ifdef COHERENT
  477. #define LOCK_DIR "/usr/spool/uucp"
  478. #else
  479. #define LOCK_DIR "/usr/spool/uucp"
  480. #endif /* COHERENT */
  481. #endif /* LCKDIR */
  482. #endif /* HDBUUCP */
  483. #endif /* ISIII */
  484. #endif /* AIXRS */
  485. #endif /* RTAIX */
  486. #endif /* HPUX10 */
  487. #endif /* DGUX430 */
  488. #endif /* BSD44 */
  489. #endif /* !LOCK_DIR (outside ifndef) */
  490.  
  491. #ifdef OSF2                /* OSF/1 2.0 or later */
  492. #ifdef LOCK_DIR                /* (maybe 1.x too, who knows...) */
  493. #undef LOCK_DIR
  494. #define LOCK_DIR "/var/spool/locks"
  495. #endif /* LOCK_DIR */
  496. #endif /* OSF2 */
  497.  
  498. #ifdef COMMENT
  499. /* Sorry no more lockf() -- we lock first and THEN open the device. */
  500. #ifdef SVR4
  501. #ifndef BSD44
  502. #ifndef LOCKF
  503. #define LOCKF                /* Use lockf() on tty device in SVR4 */
  504. #endif /* LOCKF */
  505. #endif /* BSD44 */
  506. #endif /* SVR4 */
  507. #endif /* COMMENT */
  508.  
  509. #ifdef NOLOCKF                /* But NOLOCKF cancels LOCKF */
  510. #ifdef LOCKF
  511. #undef LOCKF
  512. #endif /* LOCKF */
  513. #endif /* NOLOCKF */
  514.  
  515. /* More about this below... */
  516.  
  517. #endif /* USETTYLOCK */
  518. #endif /* NOUUCP */
  519.  
  520. /*
  521.   MYREAD means use our internally defined nonblocking buffered read routine.
  522. */
  523. #ifdef ATTSV
  524. #define MYREAD
  525. #endif /* ATTSV */
  526.  
  527. #ifdef ATT7300
  528. #ifndef MYREAD
  529. #define MYREAD
  530. #endif /* MYREAD */
  531. /* bits for attmodem: internal modem in use, restart getty */
  532. #define ISMODEM 1
  533. #define DOGETY 512
  534. #endif  /* ATT7300 */
  535.  
  536. #ifdef BSD42
  537. #define MYREAD
  538. #endif /* BSD42 */
  539.  
  540. #ifdef POSIX
  541. #define MYREAD
  542. #endif /* POSIX */
  543. #ifdef __bsdi__
  544. #ifndef O_NDELAY
  545. #define O_NDELAY O_NONBLOCK
  546. #endif /* O_NDELAY */
  547. #endif /* __bsdi__ */
  548.  
  549. /*
  550.  Variables available to outside world:
  551.  
  552.    dftty  -- Pointer to default tty name string, like "/dev/tty".
  553.    dfloc  -- 0 if dftty is console, 1 if external line.
  554.    dfprty -- Default parity
  555.    dfflow -- Default flow control
  556.    ckxech -- Flag for who echoes console typein:
  557.      1 - The program (system echo is turned off)
  558.      0 - The system (or front end, or terminal).
  559.    functions that want to do their own echoing should check this flag
  560.    before doing so.
  561.  
  562.    flfnam  -- Name of lock file, including its path, e.g.,
  563.                 "/usr/spool/uucp/LCK..cul0" or "/etc/locks/tty77"
  564.    lkflfn  -- Name of link to lock file, including its paths
  565.    haslock -- Flag set if this kermit established a uucp lock.
  566.    lockpid -- PID of other process that has desired line open, as string.
  567.    backgrd -- Flag indicating program executing in background ( & on
  568.                 end of shell command). Used to ignore INT and QUIT signals.
  569.    rtu_bug -- Set by stptrap().  RTU treats ^Z as EOF (but only when we handle
  570.                 SIGTSTP)
  571.  
  572.  Functions for assigned communication line (either external or console tty):
  573.  
  574.    sysinit()               -- System dependent program initialization
  575.    syscleanup()            -- System dependent program shutdown
  576.    ttopen(ttname,local,mdmtyp,timo) -- Open the named tty for exclusive access.
  577.    ttclos()                -- Close & reset the tty, releasing any access lock.
  578.    ttsspd(cps)             -- Set the transmission speed of the tty.
  579.    ttgspd()                -- Get (read) the the transmission speed of the tty.
  580.    ttpkt(speed,flow,parity) -- Put the tty in packet mode and set the speed.
  581.    ttvt(speed,flow)        -- Put the tty in virtual terminal mode.
  582.                                 or in DIALING or CONNECTED modem control state.
  583.    ttres()                 -- Restore original tty modes.
  584.    ttscarr(carrier)        -- Set carrier control mode, on/off/auto.
  585.    ttinl(dest,max,timo)    -- Timed read line from the tty.
  586.    ttinc(timo)             -- Timed read character from tty.
  587.    myread()                -- Raw mode bulk buffer read, gives subsequent
  588.                                 chars one at a time and simulates FIONREAD.
  589.    myunrd(c)               -- Places c back in buffer to be read (one only)
  590.    ttchk()                 -- See how many characters in tty input buffer.
  591.    ttxin(n,buf)            -- Read n characters from tty (untimed).
  592.    ttol(string,length)     -- Write a string to the tty.
  593.    ttoc(c)                 -- Write a character to the tty.
  594.    ttflui()                -- Flush tty input buffer.
  595.    ttsndb()                -- Send BREAK signal.
  596.    ttsndlb()               -- Send Long BREAK signal.
  597.  
  598.    ttlock(ttname)          -- "Lock" tty device against uucp collisions.
  599.    ttunlck()               -- Unlock tty device.
  600.  
  601.                               For ATT7300/Unix PC, System V:
  602.    attdial(ttname,speed,telnbr) -- dials ATT7300/Unix PC internal modem
  603.    offgetty(ttname)        -- Turns off getty(1m) for comms line
  604.    ongetty(ttname)         -- Restores getty() to comms line
  605. */
  606.  
  607. /*
  608. Functions for console terminal:
  609.  
  610.    congm()   -- Get console terminal modes.
  611.    concb(esc) -- Put the console in single-character wakeup mode with no echo.
  612.    conbin(esc) -- Put the console in binary (raw) mode.
  613.    conres()  -- Restore the console to mode obtained by congm().
  614.    conoc(c)  -- Unbuffered output, one character to console.
  615.    conol(s)  -- Unbuffered output, null-terminated string to the console.
  616.    conola(s) -- Unbuffered output, array of strings to the console.
  617.    conxo(n,s) -- Unbuffered output, n characters to the console.
  618.    conchk()  -- Check if characters available at console (bsd 4.2).
  619.                 Check if escape char (^\) typed at console (System III/V).
  620.    coninc(timo)  -- Timed get a character from the console.
  621.    congks(timo)  -- Timed get keyboard scan code.
  622.    conint()  -- Enable terminal interrupts on the console if not background.
  623.    connoi()  -- Disable terminal interrupts on the console if not background.
  624.  
  625. Time functions
  626.  
  627.    msleep(m) -- Millisecond sleep
  628.    ztime(&s) -- Return pointer to date/time string
  629.    rtimer() --  Reset timer
  630.    gtimer()  -- Get elapsed time since last call to rtimer()
  631. */
  632.  
  633. /* Conditional Includes */
  634.  
  635. /* Whether to include <sys/file.h> */
  636.  
  637. #ifdef RTU                /* RTU doesn't */
  638. #define NOFILEH
  639. #endif /* RTU */
  640.  
  641. #ifdef CIE                /* CIE does. */
  642. #undef NOFILEH
  643. #endif /* CIE */
  644.  
  645. #ifdef BSD41                /* 4.1 BSD doesn't */
  646. #define NOFILEH
  647. #endif /* BSD41 */
  648.  
  649. #ifdef is68k                /* Integrated Solutions 68000 UNIX  */
  650. #define NOFILEH                /* e.g. on Plexux P60 and Sun-1 */
  651. #endif /* is68k */
  652.  
  653. #ifdef MINIX                /* MINIX */
  654. #define NOFILEH
  655. #endif /* MINIX */
  656.  
  657. #ifdef COHERENT                /* Coherent */
  658. #define NOFILEH
  659. #endif /* COHERENT */
  660.  
  661. #ifndef NOFILEH                /* Now include if selected. */
  662. #include <sys/file.h>
  663. #endif /* NOFILEH */
  664.  
  665. /* POSIX */
  666.  
  667. #ifdef BSD44ORPOSIX            /* POSIX uses termios.h */
  668. #define TERMIOS
  669. #ifdef __bsdi__
  670. #ifdef POSIX
  671. #undef _POSIX_SOURCE            /* Get extra stuff from termios.h */
  672. #endif /* POSIX */
  673. #endif /* __bsdi__ */
  674. #include <termios.h>
  675. #ifdef LINUX
  676. #include <sys/ioctl.h>
  677. #endif /* LINUX */
  678. #ifdef QNX16
  679. #include <ioctl.h>
  680. #else
  681. #ifdef QNX6
  682. #include <ioctl.h>
  683. #endif /* QNX6 */
  684. #endif /* QNX16 */
  685. #ifdef __bsdi__
  686. #ifdef POSIX
  687. #define _POSIX_SOURCE
  688. #endif /* POSIX */
  689. #endif /* __bsdi__ */
  690. #ifndef BSD44                /* Really POSIX */
  691. #ifndef CK_QNX32            /* was CK_QNX32 */
  692. #define NOSYSIOCTLH            /* No ioctl's allowed. */
  693. #undef ultrix                /* Turn off any ultrix features. */
  694. #endif /* CK_QNX32 */
  695. #endif /* BSD44 */
  696. #endif /* POSIX */
  697.  
  698. /* System III, System V */
  699.  
  700. #ifdef ATTSV
  701. #ifndef BSD44
  702. #ifndef POSIX
  703. #include <termio.h>
  704. #endif /* POSIX */
  705. #endif /* BSD44 */
  706. #ifdef TERMIOX
  707. /* Need this for termiox structure, RTS/CTS and DTR/CD flow control */
  708. #include <termiox.h>
  709.   struct termiox rctsx;
  710. #else
  711. #ifdef STERMIOX
  712. #ifdef SCO_OSR504
  713. /* Sorry, this is truly disgusting but it's SCO's fault. */
  714. #ifndef _SVID3
  715. #define _CK_SVID3_X
  716. #define _SVID3
  717. #endif /* _SVID3 */
  718. #endif /* SCO_OSR504 */
  719. #include <sys/termiox.h>
  720.   struct termiox rctsx;
  721. #ifdef CK_SVID3_X
  722. #undef _SVID3
  723. #undef CK_SVID3_X
  724. #endif /* CK_SVID3_X */
  725. #endif /* STERMIOX */
  726. #endif /* TERMIOX */
  727. #endif /* ATTSV */
  728.  
  729. #ifdef COHERENT            /* Use termio.h, not sgtty.h for Coherent */
  730. #include <termio.h>
  731. #endif /* COHERENT */
  732.  
  733. #ifdef MINIX                /* MINIX uses ioctl's */
  734. #define NOSYSIOCTLH            /* but has no <sys/ioctl.h> */
  735. #endif /* MINIX */
  736.  
  737. /* Others */
  738.  
  739. #ifndef NOSYSIOCTLH            /* Others use ioctl() */
  740. #ifdef SUN4S5
  741. /*
  742.   This is to get rid of cpp warning messages that occur because all of
  743.   these symbols are defined by both termios.h and ioctl.h on the SUN.
  744. */
  745. #undef ECHO
  746. #undef NL0
  747. #undef NL1
  748. #undef TAB0
  749. #undef TAB1
  750. #undef TAB2
  751. #undef XTABS
  752. #undef CR0
  753. #undef CR1
  754. #undef CR2
  755. #undef CR3
  756. #undef FF0
  757. #undef FF1
  758. #undef BS0
  759. #undef BS1
  760. #undef TOSTOP
  761. #undef FLUSHO
  762. #undef PENDIN
  763. #undef NOFLSH
  764. #endif /* SUN4S5 */
  765. #include <sys/ioctl.h>
  766. #endif /* NOSYSIOCTLH */
  767. /*
  768.   We really, really, REALLY want FIONREAD, because it is the only way to find
  769.   out not just *if* stuff is waiting to be read, but how much, which is
  770.   critical to our sliding-window and streaming procedures, not to mention
  771.   efficiency of CONNECT, etc.
  772. */
  773. #ifdef BELLV10
  774. #include <sys/filio.h>            /* For FIONREAD */
  775. #ifdef FIONREAD
  776. #define MYREAD
  777. #endif /* MYREAD */
  778. #endif /* BELLV10 */
  779.  
  780. #ifndef FIONREAD
  781. /* It wasn't found in ioctl.h or term*.h - try these places: */
  782. #ifdef UNIXWARE
  783. #include <sys/filio.h>
  784. #else
  785. #ifdef SOLARIS
  786. #include <sys/filio.h>
  787. #endif /* SOLARIS */
  788. #endif /* UNIXWARE */
  789. #endif /* FIONREAD */
  790.  
  791. #ifdef XENIX /* Was M_UNIX but XENIX implies M_UNIX and applies to XENIX too */
  792. /*
  793.   <sys/socket.h> included above via "ckcnet.h" defines FIONREAD as
  794.   something.  Due to this, in_chk() uses the FIONREAD instead of RDCHK
  795.   and the hot keys during file transfer (X to cancel file etc) do not
  796.   work because FIONREAD doesn't work even though it is defined.
  797.  
  798.   NOTE: This might also be true elsewhere.
  799. */
  800. #ifdef FIONREAD
  801. #undef FIONREAD
  802. #endif /* FIONREAD */
  803. #endif /* XENIX */
  804.  
  805. #ifdef CK_SCOV5                /* Ditto for SCO OpenServer 5.0 */
  806. #ifdef FIONREAD
  807. #undef FIONREAD
  808. #endif /* FIONREAD */
  809. #endif /* XENIX */
  810.  
  811. /* Whether to include <fcntl.h> */
  812.  
  813. #ifndef is68k                /* Only a few don't have this one. */
  814. #ifndef BSD41
  815. #ifndef FT21
  816. #ifndef FT18
  817. #ifndef COHERENT
  818. #include <fcntl.h>
  819. #endif /* COHERENT */
  820. #endif /* FT18 */
  821. #endif /* FT21 */
  822. #endif /* BSD41 */
  823. #endif /* not is68k */
  824.  
  825. #ifdef COHERENT
  826. #ifdef _I386
  827. #include <fcntl.h>
  828. #else
  829. #include <sys/fcntl.h>
  830. #endif /* _I386 */
  831. #endif /* COHERENT */
  832.  
  833. #ifdef ATT7300                /* Unix PC, internal modem dialer */
  834. #include <sys/phone.h>
  835. #endif /* ATT7300 */
  836.  
  837. #ifdef HPUX                /* HP-UX variations. */
  838. #define HPUXJOBCTL
  839. #include <sys/modem.h>            /* HP-UX modem signals */
  840. #ifdef hp9000s500            /* Model 500 */
  841. #undef HPUXJOBCTL
  842. #endif /* hp9000s500 */
  843. #ifdef HPUXPRE65
  844. #undef HPUXJOBCTL
  845. typedef long mflag;
  846. #endif /* HPUXPRE65 */
  847. #ifdef HPUXJOBCTL
  848. #include <sys/bsdtty.h>            /* HP-UX Berkeley tty support */
  849. #endif /* HPUXJOBCTL */
  850. #endif /* HPUX */
  851.  
  852. /*
  853.   Which time.h files to include... See ckcdeb.h for defaults.
  854.   Note that 0, 1, 2, or all 3 of these can be included according to
  855.   the symbol definitions.
  856. */
  857. #ifndef NOTIMEH
  858. #ifdef TIMEH
  859. #include <time.h>
  860. #endif /* TIMEH */
  861. #endif /* NOTIMEH */
  862.  
  863. #ifndef NOSYSTIMEH
  864. #ifdef SYSTIMEH
  865. #include <sys/time.h>
  866. #endif /* SYSTIMEH */
  867. #endif /* NOSYSTIMEH */
  868.  
  869. #ifndef NOSYSTIMEBH
  870. #ifdef SYSTIMEBH
  871. #include <sys/timeb.h>
  872. #endif /* SYSTIMEBH */
  873. #endif /* NOSYSTIMEBH */
  874.  
  875. #ifndef NODCLTIMEVAL
  876. #ifdef DCLTIMEVAL
  877. /*
  878.   In certain POSIX builds (like Unixware 7), <[sys/]time.h> refuses to
  879.   define the structs we need to access the higher speeds, so we have to
  880.   do it ourselves.
  881. */
  882. struct timeval {
  883.     long tv_sec;
  884.     long tv_usec;
  885. };
  886. struct timezone {
  887.     int tz_minuteswest;
  888.     int tz_dsttime;
  889. };
  890. #endif /* DCLTIMEVAL */
  891. #endif /* NODCLTIMEVAL */
  892.  
  893. #ifdef __linux__
  894. /* THIS IS OBSOLETE since about Linux 0.92 */
  895. #ifdef OLINUXHISPEED
  896. #include <linux/serial.h>
  897. #endif /* OLINUXHISPEED */
  898. #ifdef __alpha__            /* Linux on DEC Alpha */
  899. #ifndef __GLIBC__            /* But not with glibc */
  900. #include <asm/termios.h>
  901. #endif /* __GLIBC__ */
  902. #endif /* __alpha__ */
  903. #endif /* __linux__ */
  904.  
  905. #ifdef NOIEXTEN                /* This is broken on some systems */
  906. #undef IEXTEN                /* like Convex/OS 9.1 */
  907. #endif /* NOIEXTEN */
  908. #ifndef IEXTEN                /* Turn off ^O/^V processing. */
  909. #define IEXTEN 0            /* Needed, at least, on BSDI. */
  910. #endif /* IEXTEN */
  911. /*
  912.   Pick up definitions needed for select() if we don't have them already.
  913.   Normally they come from <sys/types.h> but some systems get them from
  914.   <sys/select.h>...  Rather than hardwire all of them into the source, we
  915.   include it if SELECT_H is defined in compile-time CFLAGS.
  916. */
  917. #ifndef SCO_OSR504
  918. #ifdef SELECT_H
  919. #include <sys/select.h>
  920. #endif /* SELECT_H */
  921. #endif /* SCO_OSR504 */
  922.  
  923. #ifdef aegis
  924. #include "/sys/ins/base.ins.c"
  925. #include "/sys/ins/error.ins.c"
  926. #include "/sys/ins/ios.ins.c"
  927. #include "/sys/ins/sio.ins.c"
  928. #include "/sys/ins/pad.ins.c"
  929. #include "/sys/ins/time.ins.c"
  930. #include "/sys/ins/pfm.ins.c"
  931. #include "/sys/ins/pgm.ins.c"
  932. #include "/sys/ins/ec2.ins.c"
  933. #include "/sys/ins/type_uids.ins.c"
  934. #include <default_acl.h>
  935. #undef TIOCEXCL
  936. #undef FIONREAD
  937. #endif /* aegis */
  938.  
  939. #ifdef sxaE50                /* PFU Compact A SX/A TISP V10/L50 */
  940. #undef FIONREAD
  941. #endif /* sxaE50 */
  942.  
  943. /* The following #defines are catch-alls for those systems */
  944. /* that didn't have or couldn't find <file.h>... */
  945.  
  946. #ifndef FREAD
  947. #define FREAD 0x01
  948. #endif /* FREAD */
  949.  
  950. #ifndef FWRITE
  951. #define FWRITE 0x10
  952. #endif /* FWRITE */
  953.  
  954. #ifndef O_RDONLY
  955. #define O_RDONLY 000
  956. #endif /* O_RDONLY */
  957.  
  958. /* This is for ancient Unixes that don't have these tty symbols defined. */
  959.  
  960. #ifndef PENDIN
  961. #define PENDIN ICANON
  962. #endif /* PENDIN */
  963. #ifndef FLUSHO
  964. #define FLUSHO ICANON
  965. #endif /* FLUSHO */
  966. #ifndef EXTPROC
  967. #define EXTPROC ICANON
  968. #endif /* EXTPROC */
  969.  
  970. #ifdef SVORPOSIX
  971. /*
  972.   Modem signals are also forbidden in the POSIX world.  But some POSIX-based
  973.   platforms let us at them anyway if we know where to look.
  974. */
  975. #ifndef NEEDMDMDEFS
  976. /* Doesn't work for Linux */
  977. #ifdef UNIXWARE7
  978. #define NEEDMDMDEFS
  979. #endif /* UNIXWARE7 */
  980. #endif /* NEEDMDMDEFS */
  981.  
  982. #ifdef NEEDMDMDEFS
  983. #ifndef TIOCMGET
  984. #define TIOCMGET (('t'<<8)|29)
  985. #endif /* TIOCMGET */
  986.  
  987. #ifndef TIOCM_DTR
  988. #define TIOCM_DTR 0x0002
  989. #endif /* TIOCM_DTR */
  990. #ifndef TIOCM_RTS
  991. #define TIOCM_RTS 0x0004
  992. #endif /* TIOCM_RTS */
  993. #ifndef TIOCM_CTS
  994. #define TIOCM_CTS 0x0020
  995. #endif /* TIOCM_CTS */
  996. #ifndef TIOCM_CAR
  997. #define TIOCM_CAR 0x0040
  998. #endif /* TIOCM_CAR */
  999. #ifndef TIOCM_RNG
  1000. #define TIOCM_RNG 0x0080
  1001. #endif /* TIOCM_RNG */
  1002. #ifndef TIOCM_DSR
  1003. #define TIOCM_DSR 0x0100
  1004. #endif /* TIOCM_DSR */
  1005. #endif /* NEEDMDMDEFS */
  1006. #endif /* SVORPOSIX */
  1007.  
  1008. /* Declarations */
  1009.  
  1010. #ifdef OXOS
  1011. #undef TCGETA
  1012. #undef TCSETA
  1013. #undef TCSETAW
  1014. #undef TCSETAF
  1015. #define TCGETA TCGETS
  1016. #define TCSETA TCSETS
  1017. #define TCSETAW TCSETSW
  1018. #define TCSETAF TCSETSF
  1019. #define termio termios
  1020. #endif /* OXOS */
  1021.  
  1022. #ifdef SVORPOSIX            /* AT&T Sys V or POSIX */
  1023. #ifdef UNIXWAREPOSIX            /* UnixWare 7 POSIX build */
  1024. /*
  1025.   In Unixware POSIX builds, <[sys/]time.h> refuses to define the
  1026.   structs we need to access the higher speeds, so we have to do it
  1027.   ourselves.
  1028. */
  1029. struct timeval {
  1030.     long tv_sec;
  1031.     long tv_usec;
  1032. };
  1033. struct timezone {
  1034.     int tz_minuteswest;
  1035.     int tz_dsttime;
  1036. };
  1037. #endif /* UNIXWAREPOSIX */
  1038. #endif /* SVORPOSIX */
  1039.  
  1040. #ifdef __GNUC__
  1041. #ifdef XENIX
  1042. /*
  1043.   Because Xenix <time.h> doesn't declare time() if we're using gcc.
  1044. */
  1045. time_t time();
  1046. #endif /* XENIX */
  1047. #endif /* __GNUC__ */
  1048.  
  1049. /* Special stuff for V7 input buffer peeking */
  1050.  
  1051. #ifdef  V7
  1052. int kmem[2] = { -1, -1};
  1053. char *initrawq(), *qaddr[2]={0,0};
  1054. #define CON 0
  1055. #define TTY 1
  1056. #endif /* V7 */
  1057.  
  1058. /* dftty is the device name of the default device for file transfer */
  1059. /* dfloc is 0 if dftty is the user's console terminal, 1 if an external line */
  1060.  
  1061. #ifdef BEOS
  1062.     char * dftty = NULL;
  1063.     char * dfmdm = "none";
  1064.     int dfloc = 0;                  /* that goes in local mode by default */
  1065. #else
  1066. #ifndef DFTTY
  1067. #ifdef PROVX1
  1068.     char *dftty = "/dev/com1.dout"; /* Only example so far of a system */
  1069.     char *dfmdm = "none";
  1070.     int dfloc = 1;                  /* that goes in local mode by default */
  1071. #else
  1072.     char *dftty = CTTNAM;               /* Remote by default, use normal */
  1073.     char *dfmdm = "none";
  1074.     int dfloc = 0;                      /* controlling terminal name. */
  1075. #endif /* PROVX1 */
  1076. #else
  1077.     char *dftty = DFTTY;        /* Default location specified on */
  1078.     char *dfmdm = "none";        /* command line. */
  1079.     int dfloc = 1;                      /* controlling terminal name. */
  1080. #endif /* DFTTY */
  1081. #endif /* BEOS */
  1082.  
  1083. #define CON_RES 0            /* Console state is "reset" */
  1084. #define CON_CB  1            /* Console state is CBREAK */
  1085. #define CON_BIN 2            /* Console state is binary */
  1086.     static int constate = CON_RES;
  1087.  
  1088. #define CONI_RES 0            /* Console interrupts are "reset" */
  1089. #define CONI_INT 1            /* Console intterupts are set */
  1090. #define CONI_NOI 2            /* Console intterupts are disabled */
  1091.     static int conistate = CONI_RES;
  1092.  
  1093. #ifdef CK_SMALL
  1094. #define CONBUFSIZ 15
  1095. #else
  1096. #define CONBUFSIZ 255
  1097. #endif /* CK_SMALL */
  1098.     static char conbuf[CONBUFSIZ];    /* Console readahead buffer */
  1099.     static int  conbufn = 0;        /* Chars in readahead buffer */
  1100.     static char *conbufp = conbuf;    /* Next char in readahead buffer */
  1101.  
  1102.     char cttnam[DEVNAMLEN+1] = { '\0', '\0' }; /* Determined at runtime */
  1103.  
  1104. #ifdef RTU
  1105.     int rtu_bug = 0;            /* set to 1 when returning from SIGTSTP */
  1106. #endif /* RTU */
  1107.  
  1108.     int dfprty = DEFPAR;                /* Default parity (0 = none) */
  1109.     int ttprty = 0;                     /* The parity that is in use. */
  1110.     static int ttpmsk = 0xff;        /* Parity stripping mask. */
  1111.     int ttmdm = 0;                      /* Modem in use. */
  1112.     int ttcarr = CAR_AUT;        /* Carrier handling mode. */
  1113.     int dfflow = FLO_NONE;        /* Default flow control is NONE */
  1114.     int backgrd = 0;                    /* Assume in foreground (no '&' ) */
  1115. #ifdef F_SETFL
  1116.     int iniflags = -1;            /* fcntl flags for ttyfd */
  1117. #endif /* F_SETFL */
  1118.     int fdflag = 0;            /* Flag for redirected stdio */
  1119.     int ttfdflg = 0;            /* Open File descriptor was given */
  1120.     int tvtflg = 0;            /* Flag that ttvt has been called */
  1121.     long ttspeed = -1L;            /* For saving speed */
  1122.     int ttflow = -9;            /* For saving flow */
  1123.     int ttld = -1;            /* Line discipline */
  1124.  
  1125. #ifdef sony_news
  1126.     static int km_con = -1;        /* Kanji mode for console tty */
  1127.     static int km_ext = -1;        /* Kanji mode for external device */
  1128. #endif /* sony_news */
  1129.  
  1130. #ifdef PARSENSE
  1131.     static int needpchk = 1;        /* Need parity check */
  1132. #else
  1133.     static int needpchk = 0;
  1134. #endif /* PARSENSE */
  1135.  
  1136.     extern int stopbits;        /* Stop bits */
  1137. #ifdef HWPARITY
  1138. /*
  1139.   Unfortunately we must do this with global variables rather than through the
  1140.   tt...() APIs to avoid changing the APIs and the many modules that use them.
  1141.   If hwparity != 0, this indicates 8 data bits + parity, rather than 7 data
  1142.   bits + parity or 8 data bits and no parity, and overrides the regular parity
  1143.   variable, which is communicated to this module thru ttpkt(), and represented
  1144.   locally by the ttprty variable.
  1145. */
  1146.     extern int hwparity;        /* Hardware parity */
  1147. #endif /* HWPARITY */
  1148.  
  1149. #ifdef TCPSOCKET
  1150. #ifdef TCP_NODELAY
  1151. static int nodelay_sav = -1;
  1152. #endif /* TCP_NODELAY */
  1153. #endif /* TCPSOCKET */
  1154.  
  1155. static int sigint_ign = 0;        /* SIGINT is ignored */
  1156.  
  1157. /*
  1158.   Having this module rely on external globals is bad, but fixing this
  1159.   requires overhaul of the ck*tio.c modules for all the different operating
  1160.   systems supported by C-Kermit.  Left for a future release.
  1161. */
  1162. extern int ttnproto;            /* Defined in ckcnet.c */
  1163. extern int ttnet;            /* Defined in ckcnet.c */
  1164. extern int nopush, xfrcan, xfrchr, xfrnum; /* Defined in ckcmai.c */
  1165. extern int xsuspend, wasclosed;
  1166. extern int inserver, local;
  1167.  
  1168. int ckxech = 0; /* 0 if system normally echoes console characters, else 1 */
  1169.  
  1170. int ckmaxfiles = 0;            /* Max number of open files */
  1171.  
  1172. #ifdef CK_ENCRYPTION            /* Kerberos */
  1173. #include "ckuath.h"
  1174. extern int me_encrypt, u_encrypt;
  1175. #endif /* CK_ENCRYPTION */
  1176.  
  1177. /* Declarations of variables global within this module */
  1178.  
  1179. #ifdef TTLEBUF                /* See ckcnet.h */
  1180. int ttpush = -1;
  1181. #define LEBUFSIZ 4096
  1182. static CHAR le_buf[LEBUFSIZ];
  1183. static int le_start = 0, le_end = 0, le_data = 0;
  1184. #endif /* TTLEBUF */
  1185.  
  1186. #define MSGBUF_SIZE 1024        /* For debugging */
  1187. static char msgbuf[MSGBUF_SIZE];
  1188.  
  1189. static int gotsigs = 0;
  1190.  
  1191. static time_t tcount = (time_t)0;    /* Elapsed time counter */
  1192.  
  1193. static SIGTYP (*saval)()     = NULL;    /* For saving alarm() handler */
  1194. static SIGTYP (*savquit)()   = NULL;    /* and other signal handlers */
  1195. #ifdef SIGUSR1
  1196. static SIGTYP (*savusr1)()   = NULL;
  1197. #endif /* SIGUSR1 */
  1198. #ifdef SIGUSR2
  1199. static SIGTYP (*savusr2)()   = NULL;
  1200. #endif /* SIGUSR2 */
  1201. #ifdef SIGPIPE
  1202. static SIGTYP (*savpipe)()   = NULL;
  1203. #endif /* SIGPIPE */
  1204. #ifdef SIGDANGER
  1205. static SIGTYP (*savdanger)() = NULL;
  1206. #endif /* SIGDANGER */
  1207.  
  1208. #ifndef NOJC
  1209. static SIGTYP (*jchdlr)()    = NULL;    /* For checking suspend handler */
  1210. #endif /* NOJC */
  1211. static int jcshell = -1;        /* And flag for result */
  1212.  
  1213. /*
  1214.   BREAKNULS is defined for systems that simulate sending a BREAK signal
  1215.   by sending a bunch of NUL characters at low speed.
  1216. */
  1217. #ifdef PROVX1
  1218. #ifndef BREAKNULS
  1219. #define BREAKNULS
  1220. #endif /* BREAKNULS */
  1221. #endif /* PROVX1 */
  1222.  
  1223. #ifdef V7
  1224. #ifndef BREAKNULS
  1225. #define BREAKNULS
  1226. #endif /* BREAKNULS */
  1227. #endif /* V7 */
  1228.  
  1229. #ifdef BREAKNULS
  1230. static char                /* A string of nulls */
  1231. *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";
  1232. #endif /* BREAKNULS */
  1233.  
  1234. #ifdef CK_POSIX_SIG            /* Longjump buffers */
  1235. static sigjmp_buf sjbuf;        /* POSIX signal handling */
  1236. #else
  1237. static jmp_buf sjbuf;
  1238. #endif /* CK_POSIX_SIG */
  1239.  
  1240. #ifdef V7
  1241. static jmp_buf jjbuf;
  1242. #endif /* V7 */
  1243.  
  1244. /* static */                /* (Not static any more) */
  1245. int ttyfd = -1;                /* TTY file descriptor */
  1246.  
  1247. int ttpipe = 0;                /* NETCMD: Use pipe instead of ttyfd */
  1248. int ttpty  = 0;                         /* NETPTY: Use pty instead of ttfyd */
  1249.  
  1250. #ifdef NETPTY                /* These are in ckupty.c */
  1251. extern PID_T pty_fork_pid;
  1252. extern int pty_master_fd, pty_slave_fd;
  1253. #endif    /* NETPTY */
  1254.  
  1255. #ifdef NETCMD
  1256. #ifdef NETCONN
  1257. static int pipe0[2], pipe1[2];        /* Pipes for net i/o */
  1258. #endif /* NETCONN */
  1259. static PID_T ttpid = 0;            /* Process ID for fork */
  1260. static int fdin, fdout;            /* File descriptors for pipe */
  1261. static FILE * ttout = NULL;        /* File pointer for output pipe */
  1262. #ifdef DCLFDOPEN
  1263. /* fdopen() needs declaring because it's not declared in <stdio.h> */
  1264. _PROTOTYP( FILE * fdopen, (int, char *) );
  1265. #endif /* DCLFDOPEN */
  1266. #endif /* NETCMD */
  1267.  
  1268. extern int pexitstat, quiet;
  1269.  
  1270. #ifdef Plan9
  1271. int ttyctlfd  = -1;   /* TTY control channel - What? UNIX doesn't have one? */
  1272. int consctlfd = -1;            /* Console control channel */
  1273. int noisefd = -1;            /* tone channel */
  1274. static int ttylastspeed = -1;        /* So we can lie about the speed */
  1275. #endif /* Plan9 */
  1276.  
  1277. int telnetfd = 0;            /* File descriptor is for telnet */
  1278. #ifdef NETCONN
  1279. int x25fd = 0;                /* File descriptor is for X.25 */
  1280. #endif /* NETCONN */
  1281.  
  1282. char lockpid[16] = { '\0', '\0' };    /* PID stored in lockfile, as string */
  1283.  
  1284. static int lkf = 0,                     /* Line lock flag */
  1285.     cgmf = 0,                           /* Flag that console modes saved */
  1286.     xlocal = 0,                         /* Flag for tty local or remote */
  1287.     curcarr = 0;            /* Carrier mode: require/ignore. */
  1288.  
  1289. static int netconn = 0;            /* 1 if network connection active */
  1290.  
  1291. static char escchr;                     /* Escape or attn character */
  1292.  
  1293. #ifdef CK_SCO32V4
  1294. #include <sys/time.h>
  1295. #endif /* CK_SCO32V4 */
  1296.  
  1297. #ifdef HAVE_TV
  1298.     static struct timeval tv;        /* For getting time, from sys/time.h */
  1299. #endif /* HAVE_TV */
  1300. #ifdef HAVE_TZ
  1301.     static struct timezone tz;
  1302. #endif /* HAVE_TZ */
  1303.  
  1304. #ifdef OSF
  1305.     static struct timeb ftp;            /* And from sys/timeb.h */
  1306. #endif /* OSF */
  1307.  
  1308. #ifdef BSD29
  1309.     static long xclock;            /* For getting time from sys/time.h */
  1310.     static struct timeb ftp;            /* And from sys/timeb.h */
  1311. #endif /* BSD29 */
  1312.  
  1313. #ifdef BSD41
  1314.     static long xclock;            /* For getting time from sys/time.h */
  1315.     static struct timeb ftp;            /* And from sys/timeb.h */
  1316. #endif /* BSD41 */
  1317.  
  1318. #ifdef BELLV10
  1319.     static long xclock;            /* For getting time from sys/time.h */
  1320.     static struct timeb ftp;            /* And from sys/timeb.h */
  1321. #endif /* BELLV10 */
  1322.  
  1323. #ifdef FT21
  1324.     static long xclock;            /* For getting time from sys/time.h */
  1325.     static struct timeb ftp;            /* And from sys/timeb.h */
  1326. #endif /* FT21 */
  1327.  
  1328. #ifdef TOWER1
  1329.     static long xclock;            /* For getting time from sys/time.h */
  1330.     static struct timeb ftp;        /* And from sys/timeb.h */
  1331. #endif /* TOWER1 */
  1332.  
  1333. #ifdef COHERENT
  1334.     static long xclock;            /* For getting time from sys/time.h */
  1335.     static struct timeb ftp;        /* And from sys/timeb.h */
  1336. #endif /* COHERENT */
  1337.  
  1338. #ifdef V7
  1339.     static long xclock;
  1340. #endif /* V7 */
  1341.  
  1342. /* sgtty/termio information... */
  1343.  
  1344. #ifdef BSD44ORPOSIX            /* POSIX or BSD44 */
  1345.   static struct termios
  1346.     ttold, ttraw, tttvt, ttcur,
  1347.     ccold, ccraw, cccbrk;
  1348. #else                    /* BSD, V7, etc */
  1349.  
  1350. #ifdef COHERENT                /* Hack alert... */
  1351. #define ATTSV
  1352. #endif /* COHERENT */
  1353.  
  1354. #ifdef ATTSV
  1355.   static struct termio ttold = {0};    /* Init'd for word alignment, */
  1356.   static struct termio ttraw = {0};    /* which is important for some */
  1357.   static struct termio tttvt = {0};    /* systems, like Zilog... */
  1358.   static struct termio ttcur = {0};
  1359.   static struct termio ccold = {0};
  1360.   static struct termio ccraw = {0};
  1361.   static struct termio cccbrk = {0};
  1362. #else
  1363.   static struct sgttyb                  /* sgtty info... */
  1364.     ttold, ttraw, tttvt, ttcur,     /* for communication line */
  1365.     ccold, ccraw, cccbrk;        /* and for console */
  1366. #ifdef BELLV10
  1367.   static struct ttydevb            /* Device info... */
  1368.     tdold, tdcur;            /* for communication device */
  1369. #endif /* BELLV10 */
  1370. #ifdef TIOCGETC
  1371.   static struct tchars tchold, tchnoi;
  1372.  
  1373.   static int tcharf;
  1374. #endif /* TIOCGETC */
  1375. #ifdef TIOCGLTC
  1376.   static struct ltchars ltchold, ltchnoi;
  1377.   static int ltcharf;
  1378. #endif /* TIOCGLTC */
  1379.   int lmodef = 0;            /* Local modes */
  1380.   int lmode = 0;
  1381. #endif /* ATTSV */
  1382. #endif /* BSD44ORPOSIX */
  1383.  
  1384. #ifdef COMMENT
  1385. /* It picks up the speeds but they don't work */
  1386. #ifdef UNIXWARE                /* For higher serial speeds */
  1387. #ifdef UW7                /* in Unixware 7.0 */
  1388. #include <sys/asyc.h>            /* This picks up 57600 and 115200 */
  1389. #endif /* UW7 */
  1390. #endif /* UNIXWARE */
  1391. #endif /* COMMENT */
  1392.  
  1393. #ifdef PROVX1
  1394.   static struct sgttyb ttbuf;
  1395. #endif /* PROVX1 */
  1396.  
  1397. #ifdef ultrix
  1398. /* do we really need this? */
  1399.   static struct sgttyb vanilla;
  1400. #endif /* ultrix */
  1401.  
  1402. #ifdef ATT7300
  1403. static int attmodem = 0;                /* ATT7300 internal-modem status */
  1404. struct updata dialer = {0};        /* Condition dialer for data call */
  1405. #endif /* ATT7300 */
  1406.  
  1407. #ifndef NOUUCP
  1408. #define FLFNAML 128
  1409. #ifndef USETTYLOCK
  1410. #ifdef RTAIX
  1411. char lkflfn[FLFNAML] = { '\0', '\0' };    /* and possible link to it */
  1412. #endif /* RTAIX */
  1413. char lock2[FLFNAML] =  { '\0', '\0' };    /* Name of second lockfile */
  1414. #endif /* USETTYLOCK */
  1415. #else
  1416. #define FLFNAML 7
  1417. #endif /* NOUUCP */
  1418. char flfnam[FLFNAML+1] = { '\0', '\0' }; /* UUCP lock file path name */
  1419.  
  1420. int haslock = 0;            /* =1 if this kermit locked uucp */
  1421.  
  1422. #ifndef OXOS
  1423. #ifdef SVORPOSIX
  1424. static int conesc = 0;                  /* set to 1 if esc char (^\) typed */
  1425. #else
  1426. #ifdef V7
  1427. static int conesc = 0;
  1428. #else
  1429. #ifdef C70
  1430. static int conesc = 0;
  1431. #endif /* C70 */
  1432. #endif /* V7 */
  1433. #endif /* SVORPOSIX */
  1434. #endif /* OXOS */
  1435.  
  1436. /* Local copy of comm device name or network host */
  1437. static char ttnmsv[DEVNAMLEN+1] = { '\0', '\0' };
  1438. #ifdef USETTYLOCK
  1439. static char lockname[DEVNAMLEN+1];    /* Ditto, the part after "/dev/". */
  1440. #endif /* USETTYLOCK */
  1441.  
  1442. #ifdef aegis
  1443. static status_$t st;                    /* error status return value */
  1444. static short concrp = 0;                /* true if console is CRP pad */
  1445. static uid_$t ttyuid;                   /* tty type uid */
  1446. static uid_$t conuid;                   /* stdout type uid */
  1447.  
  1448. /* APOLLO Aegis main()
  1449.  * establish acl usage and cleanup handling
  1450.  *    this makes sure that CRP pads
  1451.  *    get restored to a usable mode
  1452.  */
  1453. main(argc,argv) int argc; char **argv; {
  1454.         status_$t status;
  1455.         pfm_$cleanup_rec dirty;
  1456.  
  1457.         PID_T pid = getpid();
  1458.  
  1459.         /* acl usage according to invoking environment */
  1460.         default_acl(USE_DEFENV);
  1461.  
  1462.         /* establish a cleanup continuation */
  1463.         status = pfm_$cleanup(dirty);
  1464.         if (status.all != pfm_$cleanup_set) {
  1465.                 /* only handle faults for the original process */
  1466.                 if (pid == getpid() && status.all > pgm_$max_severity) {
  1467.             /* blew up in main process */
  1468.             status_$t quo;
  1469.             pfm_$cleanup_rec clean;
  1470.  
  1471.             /* restore the console in any case */
  1472.             conres();
  1473.  
  1474.             /* attempt a clean exit */
  1475.             debug(F101, "cleanup fault status", "", status.all);
  1476.  
  1477.             /* doexit(), then send status to continuation */
  1478.             quo = pfm_$cleanup(clean);
  1479.             if (quo.all == pfm_$cleanup_set)
  1480.               doexit(pgm_$program_faulted,-1);
  1481.             else if (quo.all > pgm_$max_severity)
  1482.               pfm_$signal(quo); /* blew up in doexit() */
  1483.                 }
  1484.                 /* send to the original continuation */
  1485.                 pfm_$signal(status);
  1486.                 /*NOTREACHED*/
  1487.         }
  1488.         return(ckcmai(argc, argv));
  1489. }
  1490. #endif /* aegis */
  1491.  
  1492. /* ANSI-style prototypes for internal functions. */
  1493. /* Functions used outside this module are prototyped in ckcker.h. */
  1494.  
  1495. #ifdef apollo
  1496. _PROTOTYP( SIGTYP timerh, () );
  1497. _PROTOTYP( SIGTYP cctrap, () );
  1498. _PROTOTYP( SIGTYP esctrp, () );
  1499. _PROTOTYP( SIGTYP sig_ign, () );
  1500. #else
  1501. _PROTOTYP( SIGTYP timerh, (int) );
  1502. _PROTOTYP( SIGTYP cctrap, (int) );
  1503. _PROTOTYP( SIGTYP esctrp, (int) );
  1504. #endif /* apollo */
  1505. _PROTOTYP( int do_open, (char *) );
  1506. _PROTOTYP( static int in_chk, (int, int) );
  1507. _PROTOTYP( static int ttrpid, (char *) );
  1508. _PROTOTYP( static int ttchkpid, (char *) );
  1509. _PROTOTYP( static int ttlock, (char *) );
  1510. _PROTOTYP( static int ttunlck, (void) );
  1511. _PROTOTYP( static VOID sigchld_handler, (int) );
  1512. _PROTOTYP( int mygetbuf, (void) );
  1513. _PROTOTYP( int myfillbuf, (void) );
  1514. _PROTOTYP( VOID conbgt, (int) );
  1515. #ifdef ACUCNTRL
  1516. _PROTOTYP( VOID acucntrl, (char *, char *) );
  1517. #endif /* ACUCNTRL */
  1518.  
  1519. #ifdef BSD44ORPOSIX
  1520. _PROTOTYP( int carrctl, (struct termios *, int) );
  1521. #else
  1522. #ifdef ATTSV
  1523. _PROTOTYP( int carrctl, (struct termio *, int) );
  1524. #else
  1525. _PROTOTYP( int carrctl, (struct sgttyb *, int) );
  1526. #endif /* ATTSV */
  1527. #endif /* BSD44ORPOSIX */
  1528.  
  1529. #ifdef ATT7300
  1530. _PROTOTYP( int attdial, (char *, long, char *) );
  1531. _PROTOTYP( int offgetty, (char *) );
  1532. _PROTOTYP( int ongetty, (char *) );
  1533. #endif /* ATT7300 */
  1534.  
  1535. #ifdef BEOSORBEBOX
  1536. #ifdef SELECT
  1537.     /* BeOS is not capable of using SELECT on anything but sockets */
  1538. #undef SELECT
  1539. #endif /* SELECT */
  1540. #include <kernel/OS.h>
  1541. /* #ifdef BE_DR_7 */
  1542. static double time_started = 0.0;
  1543. struct ALARM_STRUCT {
  1544.     thread_id thread;
  1545.     int time;
  1546. };
  1547. static thread_id alarm_thread = -1;
  1548. static struct ALARM_STRUCT alarm_struct;
  1549. _PROTOTYP( long do_alarm, (void *) );
  1550. _PROTOTYP( unsigned int alarm, (unsigned int) );
  1551. _PROTOTYP( void alarm_expired, (void) );
  1552. /* #endif */ /* BE_DR_7 */
  1553. #endif /* BEOSORBEBOX */
  1554.  
  1555. #ifndef xunchar
  1556. #define xunchar(ch) (((ch) - 32 ) & 0xFF )    /* Character to number */
  1557. #endif /* xunchar */
  1558.  
  1559. #ifdef CK_ANSIC
  1560. static char *
  1561. xxlast(char *s, char c)
  1562. #else
  1563. static char *
  1564. xxlast(s,c) char *s; char c;
  1565. #endif /* CK_ANSIC */
  1566. /* xxlast */ {        /*  Last occurrence of character c in string s. */
  1567.     int i;
  1568.     for (i = (int)strlen(s); i > 0; i--)
  1569.       if (s[i-1] == c ) return(s + (i - 1));
  1570.     return(NULL);
  1571. }
  1572.  
  1573. /* Timeout handler for communication line input functions */
  1574.  
  1575. /*ARGSUSED*/
  1576. SIGTYP
  1577. timerh(foo) int foo; {
  1578.     ttimoff();
  1579. #ifdef BEOSORBEBOX
  1580. /* #ifdef BE_DR_7 */
  1581.     alarm_expired();
  1582. /* #endif */ /* BE_DR_7 */
  1583. #endif /* BEOSORBEBOX */
  1584. #ifdef CK_POSIX_SIG
  1585.     siglongjmp(sjbuf,1);
  1586. #else
  1587.     longjmp(sjbuf,1);
  1588. #endif /* CK_POSIX_SIG */
  1589. }
  1590.  
  1591. /*ARGSUSED*/
  1592. SIGTYP
  1593. xtimerh(foo) int foo; {            /* Like timerh() but does */
  1594. #ifdef BEOSORBEBOX            /* not reset the timer itslef */
  1595. /* #ifdef BE_DR_7 */
  1596.     alarm_expired();
  1597. /* #endif */ /* BE_DR_7 */
  1598. #endif /* BEOSORBEBOX */
  1599. #ifdef CK_POSIX_SIG
  1600.     siglongjmp(sjbuf,1);
  1601. #else
  1602.     longjmp(sjbuf,1);
  1603. #endif /* CK_POSIX_SIG */
  1604. }
  1605.  
  1606.  
  1607. /* Control-C trap for communication line input functions */
  1608.  
  1609. int cc_int;                /* Flag */
  1610. SIGTYP (* occt)();            /* For saving old SIGINT handler */
  1611.  
  1612. /*ARGSUSED*/
  1613. SIGTYP
  1614. cctrap(foo) int foo; {            /* Needs arg for ANSI C */
  1615.   cc_int = 1;                /* signal() prototype. */
  1616.   return;
  1617. }
  1618.  
  1619. /*  S Y S I N I T  --  System-dependent program initialization.  */
  1620.  
  1621. /*
  1622.  * ttgwsiz() returns:
  1623.  *    1    tt_rows and tt_cols are known, both altered, both > 0
  1624.  *    0    tt_rows and/or tt_cols are known, both altered, one or both <= 0
  1625.  *    -1   tt_rows and tt_cols are unknown and unaltered
  1626.  */
  1627.  
  1628. extern int tt_rows, tt_cols;
  1629.  
  1630. static int
  1631. xttgwsiz() {
  1632.     char *p;
  1633.     int rows = 0, cols = 0;
  1634.     p = getenv("LINES");
  1635.     debug(F110,"xttgwsiz LINES",p,0);
  1636.     if (p) {
  1637.     rows = atol(p);
  1638.     if (rows > 0) {
  1639.         p = getenv("COLUMNS");
  1640.         debug(F110,"xttgwsiz COLUMNS",p,0);
  1641.         if (p) {
  1642.         cols = atol(p);
  1643.         if (cols > 0) {
  1644.             tt_rows = rows;
  1645.             tt_cols = cols;
  1646.             return(1);
  1647.         }
  1648.         return(0);
  1649.         }
  1650.     }
  1651.     }
  1652.     return(-1);
  1653. }
  1654.  
  1655. #ifdef TTLEBUF
  1656. VOID
  1657. le_init() {                /* LocalEchoInit() */
  1658.     int i;
  1659.     for (i = 0; i < LEBUFSIZ; i++)
  1660.       le_buf[i] = '\0';
  1661.     le_start = 0;
  1662.     le_end = 0;
  1663.     le_data = 0;
  1664. }
  1665.  
  1666. VOID
  1667. le_clean() {                /* LocalEchoCleanup() */
  1668.     le_init();
  1669.     return;
  1670. }
  1671.  
  1672. int
  1673. le_inbuf() {
  1674.     int rc = 0;
  1675.     if (le_start != le_end) {
  1676.     rc = (le_end -
  1677.           le_start +
  1678.           LEBUFSIZ) % LEBUFSIZ;
  1679.     }
  1680.     debug(F111,"le_inbuf","chars waiting",rc);
  1681.     return(rc);
  1682. }
  1683.  
  1684. int
  1685. #ifdef CK_ANSIC
  1686. le_putchar(CHAR ch)
  1687. #else
  1688. le_putchar(ch) CHAR ch;
  1689. #endif /* CK_ANSIC */
  1690. /* le_putchar */ {
  1691. #ifdef COMMENT
  1692.     /* In UNIX we do not have another thread taking chars out of the buffer */
  1693.     while ((le_start - le_end == 1) ||
  1694.             (le_start == 0 && le_end == LEBUFSIZ - 1)) {
  1695.     /* Buffer is full */
  1696.         debug(F111,"le_putchar","Buffer is Full",ch);
  1697.         ReleaseLocalEchoMutex() ;
  1698.         msleep(250);
  1699.         RequestLocalEchoMutex( SEM_INDEFINITE_WAIT ) ;
  1700.     }
  1701. #else
  1702.     if ((le_start - le_end + LEBUFSIZ)%LEBUFSIZ == 1) {
  1703.         debug(F110,"le_putchar","buffer is full",0);
  1704.         return(-1);
  1705.     }
  1706. #endif /* COMMENT */
  1707.     le_buf[le_end++] = ch;
  1708.     if (le_end == LEBUFSIZ)
  1709.       le_end = 0;
  1710.     le_data = 1;
  1711.     return(0);
  1712. }
  1713.  
  1714. int
  1715. #ifdef CK_ANSIC
  1716. le_puts(CHAR * s, int n)
  1717. #else
  1718. le_puts(s,n) CHAR * s; int n;
  1719. #endif /* CK_ANSIC */
  1720. /* le_puts */ {
  1721.     int rc = 0;
  1722.     int i = 0;
  1723.     CHAR * p = (CHAR *)"le_puts";
  1724.     hexdump(p,s,n);
  1725.     for (i = 0; i < n; i++)
  1726.       rc = le_putchar((char)s[i]);
  1727.     debug(F101,"le_puts","",rc);
  1728.     return(rc);
  1729. }
  1730.  
  1731. int
  1732. #ifdef CK_ANSIC
  1733. le_putstr(CHAR * s)
  1734. #else
  1735. le_putstr(s) CHAR * s;
  1736. #endif /* CK_ANSIC */
  1737. /* le_puts */ {
  1738.     CHAR * p;
  1739.     int rc = 0;
  1740.     p = (CHAR *)"le_putstr";
  1741.     hexdump(p,s,(int)strlen((char *)s));
  1742.     for (p = s; *p && !rc; p++)
  1743.       rc = le_putchar(*p);
  1744.     return(rc);
  1745. }
  1746.  
  1747. int
  1748. #ifdef CK_ANSIC
  1749. le_getchar(CHAR * pch)
  1750. #else /* CK_ANSIC */
  1751. le_getchar(pch) CHAR * pch;
  1752. #endif /* CK_ANSIC */
  1753. /* le_gatchar */ {
  1754.     int rc = 0;
  1755.     if (le_start != le_end) {
  1756.         *pch = le_buf[le_start];
  1757.         le_buf[le_start] = 0;
  1758.         le_start++;
  1759.  
  1760.         if (le_start == LEBUFSIZ)
  1761.           le_start = 0;
  1762.  
  1763.         if (le_start == le_end) {
  1764.             le_data = 0;
  1765.         }
  1766.         rc++;
  1767.     } else {
  1768.         *pch = 0;
  1769.     }
  1770.     return(rc);
  1771. }
  1772. #endif /* TTLEBUF */
  1773.  
  1774. #ifdef COMMENT
  1775. /*
  1776.   Some systems like OSF/1 use TIOCGSIZE instead of TIOCGWINSZ.
  1777.   But as far as I know, whenever TIOCGSIZE is defined, it is
  1778.   equated to TIOCGWINSZ.  For cases where this is not done, try this:
  1779. */
  1780. #ifndef TIOCGWINSZ
  1781. #ifdef TIOCGSIZE
  1782. #define TIOCGWINSZ TIOCGSIZE
  1783. #endif /* TIOCGSIZE */
  1784. #endif /* TIOCGWINSZ */
  1785. #endif /* COMMENT */
  1786.  
  1787. static int tt_xpixel = 0, tt_ypixel = 0;
  1788.  
  1789. int
  1790. ttgwsiz() {
  1791.     int x = 0;
  1792. #ifndef NONAWS
  1793. #ifdef QNX
  1794. /*
  1795.   NOTE: TIOCGWSIZ works here too, but only in the 32-bit version.
  1796.   This code works for both the 16- and 32-bit versions.
  1797. */
  1798.     extern int dev_size(int, int, int, int *, int *);
  1799.     int r, c;
  1800.  
  1801.     if (dev_size(0, -1, -1, &r, &c) == 0) {
  1802.     debug(F101,"ttgwsiz QNX r","",r);
  1803.     debug(F101,"ttgwsiz QNX c","",c);
  1804.     tt_rows = r;
  1805.     tt_cols = c;
  1806.     return ((r > 0 && c > 0) ? 1 : 0);
  1807.     } else return(xttgwsiz());
  1808. #else /* QNX */
  1809. #ifdef TIOCGWINSZ
  1810.  
  1811. /* Note, this was M_UNIX, changed to XENIX to allow cross compilation... */
  1812. #ifdef XENIX                /* SCO UNIX 3.2v4.0 */
  1813. #include <sys/stream.h>            /* typedef mblk_t needed by ptem.h */
  1814. #include <sys/ptem.h>            /* for ttgwsiz() */
  1815. #endif /* XENIX */
  1816.  
  1817. #ifdef I386IX                /* Ditto for Interactive */
  1818. #include <sys/stream.h>
  1819. #include <sys/ptem.h>
  1820. #endif /* I386IX */
  1821.  
  1822. /* Note, the above might be needed for some other older SVR3 Intel makes... */
  1823.  
  1824.     struct winsize w;
  1825.     tt_xpixel = 0;
  1826.     tt_ypixel = 0;
  1827.  
  1828. #ifdef IKSD
  1829.     if (inserver)
  1830.       return(xttgwsiz());
  1831. #endif /* IKSD */
  1832.     x = ioctl(0, (int)TIOCGWINSZ, (char *)&w);
  1833.     debug(F101,"ttgwsiz TIOCGWINSZ","",x);
  1834.     if (x < 0) {
  1835.     return(xttgwsiz());
  1836.     } else if (w.ws_row > 0 && w.ws_col > 0) {
  1837.     tt_rows = w.ws_row;
  1838.     tt_cols = w.ws_col;
  1839.     tt_xpixel = w.ws_xpixel;
  1840.     tt_ypixel = w.ws_ypixel;
  1841.     debug(F101,"ttgwsiz tt_rows","",tt_rows);
  1842.     debug(F101,"ttgwsiz tt_cols","",tt_cols);
  1843.     return(1);
  1844.     } else {
  1845.     debug(F100,"ttgwsiz TIOCGWINSZ 00","",0);
  1846.     return(xttgwsiz());
  1847.     }
  1848. #else
  1849.     return(xttgwsiz());
  1850. #endif /* TIOCGWINSZ */
  1851. #endif /* QNX */
  1852. #endif /* NONAWS */
  1853. }
  1854.  
  1855.  
  1856. #ifdef RLOGCODE
  1857. _PROTOTYP( int rlog_naws, (void) );
  1858. #endif    /* RLOGCODE */
  1859.  
  1860. #ifndef NOSIGWINCH
  1861. #ifdef SIGWINCH
  1862. SIGTYP
  1863. winchh(foo) int foo; {            /* SIGWINCH handler */
  1864.     int x = 0;
  1865. #ifdef CK_TTYFD
  1866. #ifndef VMS
  1867.     extern int ttyfd;
  1868. #endif /* VMS */
  1869. #endif /* CK_TTYFD */
  1870.     extern int tt_rows, tt_cols, cmd_rows, cmd_cols;
  1871. #ifdef DEBUG
  1872.     if (deblog) {
  1873.     debug(F100,"***************","",0);
  1874.     debug(F100,"SIGWINCH caught","",0);
  1875.     debug(F100,"***************","",0);
  1876. #ifdef NETPTY
  1877.     debug(F101,"SIGWINCH pty_fork_pid","",pty_fork_pid);
  1878. #endif /* NETPTY */
  1879.     }
  1880. #endif /* DEUB */
  1881.     signal(SIGWINCH,winchh);            /* Re-arm the signal */
  1882.     x = ttgwsiz();                      /* Get new window size */
  1883.     cmd_rows = tt_rows;            /* Adjust command screen too */
  1884.     cmd_cols = tt_cols;
  1885.  
  1886. #ifdef CK_TTYFD
  1887.     if                    /* If we don't have a connection */
  1888. #ifdef VMS                /* we're done. */
  1889.       (vmsttyfd() == -1)
  1890. #else
  1891.       (ttyfd == -1)
  1892. #endif /* VMS */
  1893. #else
  1894.       (!local)
  1895. #endif /* CK_TTYFD */
  1896.         return;
  1897.  
  1898. #ifdef NETPTY
  1899.     if (pty_fork_pid > -1) {        /* "set host" to a PTY? */
  1900.     int x;
  1901.  
  1902. #ifdef TIOCSWINSZ
  1903.     struct winsize w;        /* Resize the PTY */
  1904.     errno = 0;
  1905.     w.ws_col = tt_cols;
  1906.     w.ws_row = tt_rows;
  1907.     w.ws_xpixel = tt_xpixel;
  1908.     w.ws_ypixel = tt_ypixel;
  1909.     x = ioctl(ttyfd,TIOCSWINSZ,&w);
  1910.     debug(F101,"winchh TIOCSWINSZ","",x);
  1911.     debug(F101,"winchh TIOCSWINSZ errno","",errno);
  1912. #endif /* TIOCSWINSZ */
  1913.  
  1914.     errno = 0;
  1915.     x = kill(pty_fork_pid,SIGWINCH);
  1916.     debug(F101,"winchh kill","",x);
  1917.     debug(F101,"winchh kill errno","",errno);
  1918.     }
  1919. #endif /* NETPTY */
  1920.  
  1921. /*
  1922.   This should be OK.  It might seem that sending this from
  1923.   interrupt level could interfere with another TELNET IAC string
  1924.   that was in the process of being sent.  But we always send
  1925.   TELNET strings with a single write(), which should prevent mixups.
  1926.   blah_snaws() should protect themselves from being called on the
  1927.   wrong kind of connection.
  1928. */
  1929. #ifdef TCPSOCKET
  1930. #ifndef NOTTGWSIZ
  1931.     if (x > 0 && tt_rows > 0 && tt_cols > 0) {
  1932.         tn_snaws();
  1933. #ifdef RLOGCODE
  1934.         rlog_naws();
  1935. #endif /* RLOGCODE */
  1936.     }
  1937. #endif /* NOTTGWSIZ */
  1938. #endif /* TCPSOCKET */
  1939.     SIGRETURN;
  1940. }
  1941. #endif /* SIGWINCH */
  1942. #endif /* NOSIGWINCH */
  1943.  
  1944. SIGTYP
  1945. sighup(foo) int foo; {            /* SIGHUP handler */
  1946.     backgrd = 1;
  1947.     debug(F100,"***************","",0);
  1948.     debug(F100,"SIGHUP received","",0);
  1949.     debug(F100,"***************","",0);
  1950.     doexit(BAD_EXIT,-1);
  1951.     /*NOTREACHED*/
  1952.     SIGRETURN;                /* Shut picky compilers up... */
  1953. }
  1954.  
  1955. #ifdef CK_SCO32V4
  1956. /* Exists but there is no prototype in the header files */
  1957. _PROTOTYP( char * ttyname, (int) );
  1958. #else
  1959. #ifdef SV68R3V6
  1960. _PROTOTYP( char * ttyname, (int) );
  1961. #else
  1962. #ifdef ultrix
  1963. _PROTOTYP( char * ttyname, (int) );
  1964. #else
  1965. #ifdef HPUX6
  1966. _PROTOTYP( char * ttyname, (int) );
  1967. #else
  1968. #ifdef HPUX5
  1969. _PROTOTYP( char * ttyname, (int) );
  1970. #else
  1971. #ifdef PS2AIX10
  1972. _PROTOTYP( char * ttyname, (int) );
  1973. #else
  1974. #ifdef BSD42
  1975. _PROTOTYP( char * ttyname, (int) );
  1976. #endif /* BSD42 */
  1977. #endif /* PS2AIX10 */
  1978. #endif /* HPUX5 */
  1979. #endif /* HPUX6 */
  1980. #endif /* ultrix */
  1981. #endif /* SV68R3V6 */
  1982. #endif /* CK_SCO32V4 */
  1983.  
  1984. #ifndef SIGUSR1                /* User-defined signals */
  1985. #define SIGUSR1 30
  1986. #endif /* SIGUSR1 */
  1987.  
  1988. #ifndef SIGUSR2
  1989. #define SIGUSR2 31
  1990. #endif /* SIGUSR2 */
  1991.  
  1992. /*
  1993.   ignorsigs() sets certain signals to SIG_IGN.  But when a signal is
  1994.   ignored, it remains ignored across exec(), so we have to restore these
  1995.   signals before exec(), which is the purpose of restorsigs().
  1996. */
  1997. static VOID
  1998. ignorsigs() {                /* Ignore these signals */
  1999.     savquit = signal(SIGQUIT,SIG_IGN);    /* Ignore Quit signal */
  2000.  
  2001. #ifdef SIGDANGER            /* Ignore danger signals */
  2002. /*
  2003.   This signal is sent when the system is low on swap space.  Processes
  2004.   that don't handle it are candidates for termination.  If swap space doesn't
  2005.   clear out enough, we still might be terminated via kill() -- nothing we can
  2006.   do about that!  Conceivably, this could be improved by installing a real
  2007.   signal handler that warns the user, but that would be pretty complicated,
  2008.   since we are not always in control of the screen -- e.g. during remote-mode
  2009.   file transfer.
  2010. */
  2011.     savdanger = signal(SIGDANGER,SIG_IGN); /* e.g. in AIX */
  2012. #endif /* SIGDANGER */
  2013. #ifdef SIGPIPE
  2014. /*
  2015.   This one comes when a TCP/IP connection is broken by the remote.
  2016.   We prefer to catch this situation by examining error codes from write().
  2017. */
  2018.     savpipe = signal(SIGPIPE,SIG_IGN);
  2019. #endif /* SIGPIPE */
  2020.     savusr1 = signal(SIGUSR1,SIG_IGN);    /* Ignore user-defined signals */
  2021.     savusr2 = signal(SIGUSR2,SIG_IGN);
  2022. }
  2023.  
  2024. VOID
  2025. restorsigs() {                /* Restore these signals */
  2026.     (VOID) signal(SIGQUIT,savquit);    /* (used in ckufio.c) */
  2027. #ifdef SIGDANGER
  2028.     (VOID) signal(SIGDANGER,savdanger);
  2029. #endif /* SIGDANGER */
  2030. #ifdef SIGPIPE
  2031.     (VOID) signal(SIGPIPE,savpipe);
  2032. #endif /* SIGPIPE */
  2033.     (VOID) signal(SIGUSR1,savusr1);
  2034.     (VOID) signal(SIGUSR2,savusr2);
  2035. }
  2036.  
  2037. int
  2038. sysinit() {
  2039.     int x;
  2040.     char * s;
  2041. #ifdef CK_UTSNAME
  2042.     struct utsname name;
  2043. #endif /* CK_UTSNAME */
  2044.  
  2045.     extern char startupdir[];
  2046. /*
  2047.   BEFORE ANYTHING ELSE: Initialize the setuid package.
  2048.   Change to the user's real user and group ID.
  2049.   If this can't be done, don't run at all.
  2050. */
  2051.     x = priv_ini();
  2052. #ifdef SUIDDEBUG
  2053.     fprintf(stderr,"PRIV_INI=%d\n",x);
  2054. #endif /* SUIDDEBUG */
  2055.     if (x) {
  2056.     if (x & 1) fprintf(stderr,"Fatal: setuid failure.\n");
  2057.     if (x & 2) fprintf(stderr,"Fatal: setgid failure.\n");
  2058.     if (x & 4) fprintf(stderr,"Fatal: C-Kermit setuid to root!\n");
  2059.     exit(1);
  2060.     }
  2061.     signal(SIGINT,SIG_IGN);        /* Ignore interrupts at first */
  2062.     signal(SIGFPE,SIG_IGN);        /* Ignore floating-point exceptions */
  2063.     signal(SIGHUP,sighup);        /* Catch SIGHUP */
  2064. #ifndef NOSIGWINCH
  2065. #ifdef SIGWINCH
  2066.     signal(SIGWINCH,winchh);        /* Catch window-size change */
  2067. #endif /* SIGWINCH */
  2068. #endif /* NOSIGWINCH */
  2069.  
  2070. #ifdef SIGXFSZ
  2071.     signal(SIGXFSZ,SIG_IGN);        /* Ignore writing past file limit */ 
  2072. #endif    /* SIGXFSZ */
  2073.  
  2074. #ifndef NOJC
  2075. /*
  2076.   Get the initial job control state.
  2077.   If it is SIG_IGN, that means the shell does not support job control,
  2078.   and so we'd better not suspend ourselves.
  2079. */
  2080. #ifdef SIGTSTP
  2081.     jchdlr = signal(SIGTSTP,SIG_IGN);
  2082.     if (jchdlr == SIG_IGN) {
  2083.     jcshell = 0;
  2084.     debug(F100,"sysinit jchdlr: SIG_IGN","",0);
  2085.     } else if (jchdlr == SIG_DFL) {
  2086.     debug(F100,"sysinit jchdlr: SIG_DFL","",0);
  2087.     jcshell = 1;
  2088.     } else {
  2089.     debug(F100,"sysinit jchdlr: other","",0);
  2090.     jcshell = 3;
  2091.     }
  2092.     (VOID) signal(SIGTSTP,jchdlr);    /* Put it back... */
  2093. #endif /* SIGTSTP */
  2094. #endif /* NOJC */
  2095.  
  2096.     conbgt(0);                /* See if we're in the background */
  2097.     congm();                /* Get console modes */
  2098.  
  2099.     (VOID) signal(SIGALRM,SIG_IGN);    /* Ignore alarms */
  2100.  
  2101.     ignorsigs();            /* Ignore some other signals */
  2102.  
  2103. #ifdef F_SETFL
  2104.     iniflags = fcntl(0,F_GETFL,0);    /* Get stdin flags */
  2105. #endif /* F_SETFL */
  2106.  
  2107. #ifdef ultrix
  2108.     gtty(0,&vanilla);            /* Get sgtty info */
  2109. #else
  2110. #ifdef AUX
  2111.     set42sig();                /* Don't ask! (hakanson@cs.orst.edu) */
  2112. #endif /* AUX */
  2113. #endif /* ultrix */
  2114. /*
  2115.   Warning: on some UNIX systems (SVR4?), ttyname() reportedly opens /dev but
  2116.   never closes it.  If it is called often enough, we run out of file
  2117.   descriptors and subsequent open()'s of other devices or files can fail.
  2118. */
  2119.     s = NULL;
  2120. #ifndef MINIX
  2121.     if (isatty(0))            /* Name of controlling terminal */
  2122.       s = ttyname(0);
  2123.     else if (isatty(1))
  2124.       s = ttyname(1);
  2125.     else if (isatty(2))
  2126.       s = ttyname(2);
  2127.     debug(F110,"sysinit ttyname(0)",s,0);
  2128. #endif /* MINIX */
  2129.  
  2130. #ifdef BEOS
  2131.     if (!dftty)
  2132.       makestr(&dftty,s);
  2133. #endif /* BEOS */
  2134.  
  2135.     if (s)
  2136.       ckstrncpy((char *)cttnam,s,DEVNAMLEN+1);
  2137. #ifdef SVORPOSIX
  2138.     if (!cttnam[0])
  2139.       ctermid(cttnam);
  2140. #endif /* SVORPOSIX */
  2141.     if (!cttnam[0])
  2142.       ckstrncpy((char *)cttnam,dftty,DEVNAMLEN+1);
  2143.     debug(F110,"sysinit CTTNAM",CTTNAM,0);
  2144.     debug(F110,"sysinit cttnam",cttnam,0);
  2145.  
  2146.     ttgwsiz();                /* Get window (screen) dimensions. */
  2147.  
  2148. #ifndef NOSYSCONF
  2149. #ifdef _SC_OPEN_MAX
  2150.     ckmaxfiles = sysconf(_SC_OPEN_MAX);
  2151. #endif /* _SC_OPEN_MAX */
  2152. #endif /* NOSYSCONF */
  2153.  
  2154. #ifdef Plan9
  2155.     if (!backgrd) {
  2156.         consctlfd = open("/dev/consctl", O_WRONLY);
  2157.         /*noisefd = open("/dev/noise", O_WRONLY)*/
  2158.     }
  2159.     ckxech = 1;
  2160. #endif /* Plan9 */
  2161.  
  2162. #ifdef CK_UTSNAME
  2163.     if (uname(&name) > -1) {
  2164.     ckstrncpy(unm_mch,name.machine,CK_SYSNMLN);
  2165.     ckstrncpy(unm_nam,name.sysname,CK_SYSNMLN);
  2166.     ckstrncpy(unm_rel,name.release,CK_SYSNMLN);
  2167.     ckstrncpy(unm_ver,name.version,CK_SYSNMLN);
  2168. #ifdef DEBUG
  2169.     if (deblog) {
  2170.         debug(F110,"sysinit uname machine",unm_mch,0);
  2171.         debug(F110,"sysinit uname sysname",unm_nam,0);
  2172.         debug(F110,"sysinit uname release",unm_rel,0);
  2173.         debug(F110,"sysinit uname version",unm_ver,0);
  2174.     }
  2175. #endif /* DEBUG */
  2176.  
  2177. #ifdef HPUX9PLUS
  2178.     if (name.machine[5] == '8')
  2179.       hpis800 = 1;
  2180.     else
  2181.       hpis800 = 0;
  2182.     debug(F101,"sysinit hpis800","",hpis800);
  2183. #endif /* HPUX9PLUS */
  2184. #ifdef TRU64
  2185.         getsysinfo(GSI_PLATFORM_NAME, unm_mod, CK_SYSNMLN, 0, 0);
  2186.         debug(F110,"sysinit getsysinfo model",unm_mod,0);
  2187. #endif /* TRU64 */
  2188. #ifdef SOLARIS25
  2189.         sysinfo(SI_PLATFORM, unm_mod, CK_SYSNMLN);
  2190.         debug(F110,"sysinit sysinfo model",unm_mod,0);
  2191. #endif /* SOLARIS25 */
  2192.     }
  2193. #endif /* CK_UTSNAME */
  2194.  
  2195. #ifdef CK_ENVIRONMENT
  2196.     {
  2197. #ifdef TNCODE
  2198.     extern char tn_env_acct[], tn_env_disp[], tn_env_job[],
  2199.     tn_env_prnt[], tn_env_sys[];
  2200. #endif /* TNCODE */
  2201.     extern char uidbuf[];
  2202.         extern char * whoami();
  2203.     char *p;
  2204. #ifdef CKSENDUID
  2205.         uidbuf[0] = '\0';
  2206. #ifdef IKSD
  2207.         if (!inserver) {
  2208. #endif /* IKSD */
  2209.             p = getenv("USER");
  2210.             debug(F110,"sysinit uidbuf from USER",uidbuf,0);
  2211.         if (!p) p = "";
  2212.             if (!*p) {
  2213.                 p = getenv("LOGNAME");
  2214.                 debug(F110,"sysinit uidbuf from LOGNAME",uidbuf,0);
  2215.             }
  2216.         if (!p) p = "";
  2217.             if (!*p) {
  2218.                 p = whoami();
  2219.                 debug(F110,"sysinit uidbuf from whoami()",uidbuf,0);
  2220.             }
  2221.         if (!p) p = "";
  2222.         ckstrncpy(uidbuf, *p ? p : "UNKNOWN", UIDBUFLEN);
  2223. #ifdef IKSD
  2224.         }
  2225. #endif /* IKSD */
  2226.     debug(F110,"sysinit final uidbuf",uidbuf,0);
  2227. #endif /* CKSENDUID */
  2228.  
  2229. #ifdef TNCODE
  2230.     if ((p = getenv("JOB"))) ckstrncpy(tn_env_job,p,63);
  2231.     if ((p = getenv("ACCT"))) ckstrncpy(tn_env_acct,p,63);
  2232.     if ((p = getenv("PRINTER"))) ckstrncpy(tn_env_prnt,p,63);
  2233.     if ((p = getenv("DISPLAY"))) ckstrncpy(tn_env_disp,p,63);
  2234. #ifdef aegis
  2235.     ckstrncpy(tn_env_sys,"Aegis",64);
  2236. #else
  2237. #ifdef Plan9
  2238.     ckstrncpy(tn_env_sys,"Plan9",64);
  2239. #else
  2240.     ckstrncpy(tn_env_sys,"UNIX",64);
  2241. #endif /* Plan9 */
  2242. #endif /* aegis */
  2243. #endif /* TNCODE */
  2244.     }
  2245. #endif /* CK_ENVIRONMENT */
  2246. #ifdef CK_SNDLOC
  2247.     {
  2248.     extern char * tn_loc;
  2249.     char *p;
  2250.     if (p = getenv("LOCATION"))
  2251.       if (tn_loc = (char *)malloc((int)strlen(p)+1))
  2252.         strcpy(tn_loc,p);        /* safe */
  2253.     }
  2254. #endif /* CK_SNDLOC */
  2255.  
  2256.     ckstrncpy(startupdir, zgtdir(), CKMAXPATH);
  2257.     startupdir[CKMAXPATH] = '\0';
  2258.     x = strlen(startupdir);
  2259.     if (x <= 0) {
  2260.     startupdir[0] = '/';
  2261.     startupdir[1] = '\0';
  2262.     } else if (startupdir[x-1] != '/') {
  2263.     startupdir[x] = '/';
  2264.     startupdir[x+1] = '\0';
  2265.     }
  2266.     debug(F110,"sysinit startupdir",startupdir,0);
  2267. #ifdef TTLEBUF
  2268.     le_init();
  2269. #endif /* TTLEBUF */
  2270. #ifdef BSD44ORPOSIX
  2271.     /* This should catch the ncurses platforms */
  2272.     /* Some platforms don't have putenv(), like NeXTSTEP */
  2273.     putenv("NCURSES_NO_SETBUF=1");
  2274. #endif /* BSD44ORPOSIX */
  2275.     return(0);
  2276. }
  2277.  
  2278. /*  S Y S C L E A N U P  --  System-dependent program cleanup.  */
  2279.  
  2280. int
  2281. syscleanup() {
  2282. #ifdef F_SETFL
  2283.     if (iniflags > -1)
  2284.       fcntl(0,F_SETFL,iniflags);    /* Restore stdin flags */
  2285. #endif /* F_SETFL */
  2286. #ifdef ultrix
  2287.     stty(0,&vanilla);                   /* Get sgtty info */
  2288. #endif /* ultrix */
  2289. #ifdef NETCMD
  2290.     if (ttpid) kill(ttpid,9);
  2291. #endif /* NETCMD */
  2292.     return(0);
  2293. }
  2294.  
  2295. /*  T T O P E N  --  Open a tty for exclusive access.  */
  2296.  
  2297. /*
  2298.   Call with:
  2299.     ttname: character string - device name or network host name.
  2300.     lcl:
  2301.   If called with lcl < 0, sets value of lcl as follows:
  2302.   0: the terminal named by ttname is the job's controlling terminal.
  2303.   1: the terminal named by ttname is not the job's controlling terminal.
  2304.   But watch out: if a line is already open, or if requested line can't
  2305.   be opened, then lcl remains (and is returned as) -1.
  2306.     modem:
  2307.   Less than zero: ttname is a network host name.
  2308.   Zero or greater: ttname is a terminal device name.
  2309.   Zero means a local connection (don't use modem signals).
  2310.   Positive means use modem signals.
  2311.    timo:
  2312.   0 = no timer.
  2313.   nonzero = number of seconds to wait for open() to return before timing out.
  2314.  
  2315.   Returns:
  2316.     0 on success
  2317.    -5 if device is in use
  2318.    -4 if access to device is denied
  2319.    -3 if access to lock directory denied
  2320.    -2 upon timeout waiting for device to open
  2321.    -1 on other error
  2322. */
  2323. static int ttotmo = 0;            /* Timeout flag */
  2324. /* Flag kept here to avoid being clobbered by longjmp.  */
  2325.  
  2326. int
  2327. ttopen(ttname,lcl,modem,timo) char *ttname; int *lcl, modem, timo; {
  2328.  
  2329. #ifdef BSD44
  2330. #define ctermid(x) strcpy(x,"")
  2331. #else
  2332. #ifdef SVORPOSIX
  2333. #ifndef CIE
  2334.     extern char *ctermid();        /* Wish they all had this! */
  2335. #else                    /* CIE Regulus */
  2336. #define ctermid(x) strcpy(x,"")
  2337. #endif /* CIE */
  2338. #endif /* SVORPOSIX */
  2339. #endif /* BSD44 */
  2340.  
  2341. #ifdef ultrix
  2342.     int temp = 0;
  2343. #endif /* ultrix */
  2344.  
  2345. #ifndef OPENFIRST
  2346.     char fullname[DEVNAMLEN+1];
  2347. #endif /* OPENFIRST */
  2348.  
  2349.     char * fnam;            /* Full name after expansion */
  2350.  
  2351.     int y;
  2352.  
  2353. #ifndef pdp11
  2354. #define NAMEFD     /* Feature to allow name to be an open file descriptor */
  2355. #endif /* pdp11 */
  2356.  
  2357. #ifdef NAMEFD
  2358.     char *p;
  2359.     debug(F101,"ttopen telnetfd","",telnetfd);
  2360. #endif /* NAMEFD */
  2361.  
  2362.     debug(F110,"ttopen ttname",ttname,0);
  2363.     debug(F110,"ttopen ttnmsv",ttnmsv,0);
  2364.     debug(F101,"ttopen modem","",modem);
  2365.     debug(F101,"ttopen netconn","",netconn);
  2366.     debug(F101,"ttopen ttyfd","",ttyfd);
  2367.     debug(F101,"ttopen *lcl","",*lcl);
  2368.     debug(F101,"ttopen ttmdm","",ttmdm);
  2369.     debug(F101,"ttopen ttnet","",ttnet);
  2370.  
  2371.     ttpmsk = 0xff;
  2372.     lockpid[0] = '\0';
  2373.  
  2374.     if (ttyfd > -1) {            /* If device already opened */
  2375.         if (!strncmp(ttname,ttnmsv,DEVNAMLEN)) /* are new & old names equal? */
  2376.       return(0);            /* Yes, nothing to do - just return */
  2377.     ttnmsv[0] = '\0';        /* No, clear out old name */
  2378.     ttclos(ttyfd);            /* close old connection.  */
  2379.     }
  2380.     wasclosed = 0;            /* New connection, not closed yet. */
  2381.     ttpipe = 0;                /* Assume it's not a pipe */
  2382.     ttpty = 0;                /* or a pty... */
  2383.  
  2384. #ifdef NETCONN
  2385. /*
  2386.   This is a bit tricky...  Suppose that previously Kermit had dialed a telnet
  2387.   modem server ("set host xxx:2001, set modem type usr, dial ...").  Then the
  2388.   connection was closed (ttyfd = -1), and then a REDIAL command was given.  At
  2389.   this point we've obliterated the negative modem type hack, and so would
  2390.   treat the IP hostname as a device name, and would then fail because of "No
  2391.   such device or directory".  But the previous connection has left behind some
  2392.   clues, so let's use them...
  2393. */
  2394.     if (ttyfd < 0) {            /* Connection is not open */
  2395.     if (!strcmp(ttname,ttnmsv)) {    /* Old and new names the same? */
  2396.         if (((netconn > 0) && (ttmdm < 0)) ||
  2397.         ((ttnet > 0) &&
  2398.          (!ckstrchr(ttname,'/')) && (ckstrchr(ttname,':')))
  2399.         ) {
  2400.         int x, rc;
  2401.         x = (ttmdm < 0) ? -ttmdm : ttnet;
  2402.         rc = netopen(ttname, lcl, x);
  2403.         debug(F111,"ttopen REOPEN netopen",ttname,rc);
  2404.         if (rc > -1) {
  2405.             netconn = 1;
  2406.             xlocal = *lcl = 1;
  2407.         } else {
  2408.             netconn = 0;
  2409.         }
  2410.         gotsigs = 0;
  2411.         return(rc);
  2412.         }
  2413.     }
  2414.     }
  2415. #endif /* NETCONN */
  2416.  
  2417. #ifdef MAXNAMLEN
  2418.     debug(F100,"ttopen MAXNAMLEN defined","",0);
  2419. #else
  2420.     debug(F100,"ttopen MAXNAMLEN *NOT* defined","",0);
  2421. #endif
  2422.  
  2423. #ifdef BSD4
  2424.     debug(F100,"ttopen BSD4 defined","",0);
  2425. #else
  2426.     debug(F100,"ttopen BSD4 *NOT* defined","",0);
  2427. #endif /* BSD4 */
  2428.  
  2429. #ifdef BSD42
  2430.     debug(F100,"ttopen BSD42 defined","",0);
  2431. #else
  2432.     debug(F100,"ttopen BSD42 *NOT* defined","",0);
  2433. #endif /* BSD42 */
  2434.  
  2435. #ifdef MYREAD
  2436.     debug(F100,"ttopen MYREAD defined","",0);
  2437. #else
  2438.     debug(F100,"ttopen MYREAD *NOT* defined","",0);
  2439. #endif /* MYREAD */
  2440.  
  2441. #ifdef    NETCONN
  2442.     if (modem < 0) {            /* modem < 0 = code for network */
  2443.     int x;
  2444.     ttmdm = modem;
  2445.     modem = -modem;            /* Positive network type number */
  2446.     fdflag = 0;            /* Stdio not redirected. */
  2447.     netconn = 1;            /* And it's a network connection */
  2448.     debug(F111,"ttopen net",ttname,modem);
  2449. #ifdef NAMEFD
  2450.     for (p = ttname; isdigit(*p); p++) ; /* Check for all digits */
  2451.      if (*p == '\0' && (telnetfd || x25fd)) { /* Avoid X.121 addresses */
  2452.         ttyfd = atoi(ttname);    /* Is there a way to test it's open? */
  2453.         ttfdflg = 1;        /* We got an open file descriptor */
  2454.         debug(F111,"ttopen net ttfdflg",ttname,ttfdflg);
  2455.         debug(F101,"ttopen net ttyfd","",ttyfd);
  2456.         ckstrncpy(ttnmsv,ttname,DEVNAMLEN); /* Remember the "name". */
  2457.         x = 1;            /* Return code is "good". */
  2458.         if (telnetfd) {
  2459.         ttnet = NET_TCPB;
  2460.         if (ttnproto != NP_TCPRAW)
  2461.           ttnproto = NP_TELNET;
  2462. #ifdef SUNX25
  2463.         } else if (x25fd) {
  2464.         ttnet = NET_SX25;
  2465.         ttnproto = NP_NONE;
  2466. #endif /* SUNX25 */
  2467.         }
  2468.     } else {            /* Host name or address given */
  2469. #ifdef NETPTY
  2470.         if (modem == NET_PTY) {
  2471.         int x;
  2472.         if (nopush) {
  2473.             debug(F100,"ttopen PTY: nopush","",0);
  2474.             return(-1);
  2475.         }
  2476.                 ttnet = NET_PTY;
  2477.         ttnproto = NP_NONE;
  2478.                 netconn = 1;            /* but we don't use network i/o */
  2479.                 ttpty = 1;
  2480.                 debug(F110,"ttopen PTY",ttname,0);
  2481.         x = do_pty(&ttyfd,ttname,0);
  2482.         if (x > -1) {
  2483.             ckstrncpy(ttnmsv,ttname,DEVNAMLEN);
  2484.             xlocal = *lcl = 1;    /* It's local */
  2485.         } else {
  2486.             ttpty = 0;
  2487.             netconn = 0;
  2488.         }
  2489.         gotsigs = 0;
  2490.         return(x);
  2491.         }
  2492. #endif /* NETPTY */
  2493. #ifdef NETCMD
  2494. /*
  2495.   dup2() is not available on older System V platforms like AT&T 3Bx.  For
  2496.   those systems we punt by not defining NETCMD, but we might be able to do
  2497.   better -- see workarounds for this problem in ckufio.c (search for dup2).
  2498. */
  2499.         if (modem == NET_CMD) {
  2500.         if (nopush) {
  2501.             debug(F100,"ttopen pipe: nopush","",0);
  2502.             return(-1);
  2503.         }
  2504.         if (pipe(pipe0) || pipe(pipe1)) {
  2505.             perror("Pipe error");
  2506.             return(-1);
  2507.         }
  2508.         ttpid = fork();        /* Make a fork */
  2509.  
  2510.         switch (ttpid) {
  2511.           case -1:        /* Error making fork */
  2512.             close(pipe0[0]);
  2513.             close(pipe0[1]);
  2514.             close(pipe1[0]);
  2515.             close(pipe1[1]);
  2516.             perror("Fork error");
  2517.             return(-1);
  2518.           case 0:        /* Child. */
  2519.             close(pipe0[0]);
  2520.             close(pipe1[1]);
  2521.             dup2(pipe0[1], 1);
  2522.             close(pipe0[1]);
  2523.             dup2(pipe1[0], 0);
  2524.             close(pipe1[0]);
  2525.             system(ttname);
  2526.             _exit(0);
  2527.           default:        /* Parent */
  2528.             close(pipe0[1]);
  2529.             close(pipe1[0]);
  2530.             fdin = pipe0[0];    /* Read from pipe */
  2531.             fdout = pipe1[1];    /* Write to pipe */
  2532.             ttout = fdopen(fdout,"w"); /* Get stream so we can */
  2533.             if (!ttout) {    /* make it unbuffered. */
  2534.             perror("fdopen failure");
  2535.             return(-1);
  2536.             }
  2537.             setbuf(ttout,NULL);
  2538.             ckstrncpy(ttnmsv,ttname,DEVNAMLEN);
  2539.             xlocal = *lcl = 1;    /* It's local */
  2540.             netconn = 1;    /* Call it a network connection */
  2541.             ttmdm = modem;    /* Remember network type */
  2542.             ttyfd = fdin;
  2543.             ttpipe = 1;
  2544.             gotsigs = 0;
  2545.             return(0);
  2546.         }
  2547.         }
  2548. #endif /* NETCMD */
  2549. #endif /* NAMEFD */
  2550.         x = netopen(ttname, lcl, modem); /* (see ckcnet.h) */
  2551.         if (x > -1) {
  2552.         ckstrncpy(ttnmsv,ttname,DEVNAMLEN);
  2553.         } else netconn = 0;
  2554. #ifdef NAMEFD
  2555.     }
  2556. #endif /* NAMEFD */
  2557.  
  2558. #ifdef sony_news            /* Sony NEWS */
  2559.     if (ioctl(ttyfd,TIOCKGET,&km_ext) < 0) { /* Get Kanji mode */
  2560.         perror("ttopen error getting Kanji mode (network)");
  2561.         debug(F111,"ttopen error getting Kanji mode","network",0);
  2562.         km_ext = -1;        /* Make sure this stays undefined. */
  2563.     }
  2564. #endif /* sony_news */
  2565.  
  2566.     xlocal = *lcl = 1;        /* Network connections are local. */
  2567.     debug(F101,"ttopen net x","",x);
  2568. #ifdef COMMENT
  2569. /* Let netopen() do this */
  2570.     if (x > -1 && !x25fd)
  2571.       x = tn_ini();            /* Initialize TELNET protocol */
  2572. #endif /* COMMENT */
  2573.     gotsigs = 0;
  2574.     return(x);
  2575.     } else {                /* Terminal device */
  2576. #endif    /* NETCONN */
  2577.  
  2578. #ifdef NAMEFD
  2579. /*
  2580.   This code lets you give Kermit an open file descriptor for a serial
  2581.   communication device, rather than a device name.  Kermit assumes that the
  2582.   line is already open, locked, conditioned with the right parameters, etc.
  2583. */
  2584.     for (p = ttname; isdigit(*p); p++) ; /* Check for all-digits */
  2585.     if (*p == '\0') {
  2586.         ttyfd = atoi(ttname);    /* Is there a way to test it's open? */
  2587.         debug(F111,"ttopen got open fd",ttname,ttyfd);
  2588.         ckstrncpy(ttnmsv,ttname,DEVNAMLEN); /* Remember the "name". */
  2589.         if (ttyfd >= 0 && ttyfd < 3) /* If it's stdio... */
  2590.           xlocal = *lcl = 0;    /* we're in remote mode */
  2591.         else            /* otherwise */
  2592.           xlocal = *lcl = 1;    /* local mode. */
  2593.         netconn = 0;        /* Assume it's not a network. */
  2594.         tvtflg = 0;            /* Might need to initialize modes. */
  2595.         ttmdm = modem;        /* Remember modem type. */
  2596.         fdflag = 0;            /* Stdio not redirected. */
  2597.         ttfdflg = 1;        /* Flag we were opened this way. */
  2598.         debug(F111,"ttopen non-net ttfdflg",ttname,ttfdflg);
  2599.         debug(F101,"ttopen non-net ttyfd","",ttyfd);
  2600.  
  2601. #ifdef sony_news            /* Sony NEWS */
  2602.         /* Get device Kanji mode */
  2603.         if (ioctl(ttyfd,TIOCKGET,&km_ext) < 0) {
  2604.         perror("ttopen error getting Kanji mode");
  2605.         debug(F101,"ttopen error getting Kanji mode","",0);
  2606.         km_ext = -1;        /* Make sure this stays undefined. */
  2607.         }
  2608. #endif /* sony_news */
  2609.         gotsigs = 0;
  2610.         return(0);            /* Return success */
  2611.     }
  2612. #endif /* NAMEFD */
  2613. #ifdef NETCONN
  2614.     }
  2615. #endif /* NETCONN */
  2616.  
  2617. /* Here we have to open a serial device of the given name. */
  2618.  
  2619.     netconn = 0;            /* So it's not a network connection */
  2620.     occt = signal(SIGINT, cctrap);    /* Set Control-C trap, save old one */
  2621.     sigint_ign = 0;
  2622.  
  2623.     tvtflg = 0;            /* Flag for use by ttvt(). */
  2624.                 /* 0 = ttvt not called yet for this device */
  2625.  
  2626.     fdflag = (!isatty(0) || !isatty(1)); /* Flag for stdio redirected */
  2627.     debug(F101,"ttopen fdflag","",fdflag);
  2628.  
  2629.     ttmdm = modem;                      /* Make this available to other fns */
  2630.     xlocal = *lcl;                      /* Make this available to other fns */
  2631.  
  2632. /* Code for handling bidirectional tty lines goes here. */
  2633. /* Use specified method for turning off logins and suppressing getty. */
  2634.  
  2635. #ifdef ACUCNTRL
  2636.     /* Should put call to priv_on() here, but that would be very risky! */
  2637.     acucntrl("disable",ttname);         /* acucntrl() program. */
  2638.     /* and priv_off() here... */
  2639. #else
  2640. #ifdef ATT7300
  2641.     if ((attmodem & DOGETY) == 0)       /* offgetty() program. */
  2642.       attmodem |= offgetty(ttname);    /* Remember response.  */
  2643. #endif /* ATT7300 */
  2644. #endif /* ACUCNTRL */
  2645.  
  2646. #ifdef OPENFIRST
  2647. /*
  2648.  1985-2001: opens device first then gets lock; reason:
  2649.  Kermit usually has to run setuid or setgid in order to create a lockfile.
  2650.  If you give a SET LINE command for a device that happens to be your job's
  2651.  controlling terminal, Kermit doesn't have to create a lockfile, and in fact
  2652.  should not create one, and would fail if it tried to if it did not have the
  2653.  required privileges.  But you can't find out if two tty device names are
  2654.  equivalent until you have a file descriptor that you can give to ttyname().
  2655.  But this can cause a race condition between Kermit and [m]getty.  So see
  2656.  the [#]else part...
  2657. */ 
  2658.  
  2659. /*
  2660.  In the following section, we open the tty device for read/write.
  2661.  If a modem has been specified via "set modem" prior to "set line"
  2662.  then the O_NDELAY parameter is used in the open, provided this symbol
  2663.  is defined (e.g. in fcntl.h), so that the program does not hang waiting
  2664.  for carrier (which in most cases won't be present because a connection
  2665.  has not been dialed yet).  O_NDELAY is removed later on in ttopen().  It
  2666.  would make more sense to first determine if the line is local before
  2667.  doing this, but because ttyname() requires a file descriptor, we have
  2668.  to open it first.  See do_open().
  2669.  
  2670.  Now open the device using the desired treatment of carrier.
  2671.  If carrier is REQUIRED, then open could hang forever, so an optional
  2672.  timer is provided.  If carrier is not required, the timer should never
  2673.  go off, and should do no harm...
  2674. */
  2675.     ttotmo = 0;                /* Flag no timeout */
  2676.     debug(F101,"ttopen timo","",timo);
  2677.     debug(F101,"ttopen xlocal","",xlocal);
  2678.     if (timo > 0) {
  2679.     int xx;
  2680.     saval = signal(SIGALRM,timerh);    /* Timed, set up timer. */
  2681.     xx = alarm(timo);        /* Timed open() */
  2682.     debug(F101,"ttopen alarm","",xx);
  2683.     if (
  2684. #ifdef CK_POSIX_SIG
  2685.         sigsetjmp(sjbuf,1)
  2686. #else
  2687.         setjmp(sjbuf)
  2688. #endif /* CK_POSIX_SIG */
  2689.         ) {
  2690.         ttotmo = 1;            /* Flag timeout. */
  2691.     } else ttyfd = do_open(ttname);
  2692.     ttimoff();
  2693.     debug(F111,"ttopen","modem",modem);
  2694.     debug(F101,"ttopen ttyfd","",ttyfd);
  2695.     debug(F101,"ttopen alarm return","",ttotmo);
  2696.     } else {
  2697.     errno = 0;
  2698.     ttyfd = do_open(ttname);
  2699.     }
  2700.     debug(F111,"ttopen ttyfd",ttname,ttyfd);
  2701.     if (ttyfd < 0) {            /* If couldn't open, fail. */
  2702.     debug(F101,"ttopen errno","",errno);
  2703.     if (errno > 0 && !quiet)
  2704.       perror(ttname);        /* Print message */
  2705.  
  2706. #ifdef ATT7300
  2707.     if (attmodem & DOGETY)        /* was getty(1m) running before us? */
  2708.       ongetty(ttnmsv);        /* yes, restart on tty line */
  2709.     attmodem &= ~DOGETY;        /* no phone in use, getty restored */
  2710. #else
  2711. #ifdef ACUCNTRL
  2712.         /* Should put call to priv_on() here, but that would be risky! */
  2713.     acucntrl("enable",ttname);    /* acucntrl() program. */
  2714.     /* and priv_off() here... */
  2715. #endif /* ACUNTRL */
  2716. #endif /* ATT7300 */
  2717.  
  2718.     signal(SIGINT,occt);        /* Put old Ctrl-C trap back. */
  2719.     if (errno == EACCES) {        /* Device is protected against user */
  2720.         debug(F110,"ttopen EACCESS",ttname,0); /* Return -4 */
  2721.         return(-4);
  2722.     } else return(ttotmo ? -2 : -1); /* Otherwise -2 if timeout, or -1 */
  2723.     }
  2724.  
  2725. #ifdef QNX
  2726.     {
  2727.     extern int qnxportlock;
  2728.     x = qnxopencount();
  2729.     debug(F101,"ttopen qnxopencount","",x);
  2730.     debug(F101,"ttopen qnxportlock","",qnxportlock);
  2731.     if (x < 0 && qnxportlock) {
  2732.         ttclos(0);
  2733.         printf("?Can't get port open count\n");
  2734.         printf("(Try again with SET QNX-PORT-LOCK OFF)\n");
  2735.         return(-1);            /* Indicate device is in use */
  2736.     }
  2737.     if (x > 1) {            /* 1 == me */
  2738.         if (qnxportlock)
  2739.           ttclos(0);
  2740.           return(-2);        /* Indicate device is in use */
  2741.         else if (!quiet)
  2742.           printf("WARNING: \"%s\" looks busy...\n",ttdev);
  2743.     }
  2744.     }
  2745. #endif /* QNX */
  2746.  
  2747. #ifdef Plan9
  2748.     /* take this opportunity to open the control channel */
  2749.     if (p9openttyctl(ttname) < 0)
  2750. #else
  2751.     /* Make sure it's a real tty. */
  2752.     if (!ttfdflg && !isatty(ttyfd) && strcmp(ttname,"/dev/null"))
  2753. #endif /* Plan9 */
  2754.       {
  2755.     fprintf(stderr,"%s is not a terminal device\n",ttname);
  2756.     debug(F111,"ttopen not a tty",ttname,errno);
  2757.     close(ttyfd);
  2758.     ttyfd = -1;
  2759.     wasclosed = 1;
  2760.     signal(SIGINT,occt);
  2761.     return(-1);
  2762.     }
  2763.  
  2764. #ifdef aegis
  2765.     /* Apollo C runtime claims that console pads are tty devices, which
  2766.      * is reasonable, but they aren't any good for packet transfer. */
  2767.     ios_$inq_type_uid((short)ttyfd, ttyuid, st);
  2768.     if (st.all != status_$ok) {
  2769.         fprintf(stderr, "problem getting tty object type: ");
  2770.         error_$print(st);
  2771.     } else if (ttyuid != sio_$uid) { /* reject non-SIO lines */
  2772.         close(ttyfd); ttyfd = -1;
  2773.         wasclosed = 1;
  2774.         errno = ENOTTY; perror(ttname);
  2775.         signal(SIGINT,occt);
  2776.         return(-1);
  2777.     }
  2778. #endif /* aegis */
  2779.  
  2780.     sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  2781.  
  2782.     ckstrncpy(ttnmsv,ttname,DEVNAMLEN);    /* Keep copy of name locally. */
  2783.  
  2784. /* Caller wants us to figure out if line is controlling tty */
  2785.  
  2786.     if (*lcl < 0) {
  2787.         if (strcmp(ttname,CTTNAM) == 0) { /* "/dev/tty" always remote */
  2788.             xlocal = 0;
  2789.         debug(F111,"ttopen ttname=CTTNAM",ttname,xlocal);
  2790.         } else if (strcmp(ttname,cttnam) == 0) {
  2791.             xlocal = 0;
  2792.         debug(F111,"ttopen ttname=cttnam",ttname,xlocal);
  2793.     } else if (cttnam[0]) {
  2794. #ifdef BEBOX_DR7
  2795.             x = ttnmsv;            /* ttyname() is broken */
  2796. #else
  2797.             x = ttyname(ttyfd);         /* Get real name of ttname. */
  2798. #endif /* BEBOX_DR7 */
  2799.         if (!x) x = "";
  2800.         if (*x)
  2801.           xlocal = ((strncmp(x,cttnam,DEVNAMLEN) == 0) ? 0 : 1);
  2802.         else
  2803.           xlocal = 1;
  2804.             debug(F111,"ttopen ttyname(ttyfd) xlocal",x,xlocal);
  2805.         }
  2806.     }
  2807.  
  2808. #ifndef NOFDZERO
  2809. /* Note, the following code was added so that Unix "idle-line" snoopers */
  2810. /* would not think Kermit was idle when it was transferring files, and */
  2811. /* maybe log people out. */
  2812.     if (xlocal == 0) {            /* Remote mode */
  2813.     if (fdflag == 0) {        /* Standard i/o is not redirected */
  2814.         debug(F100,"ttopen setting ttyfd = 0","",0);
  2815. #ifdef LYNXOS
  2816.         /* On Lynx OS, fd 0 is open for read only. */
  2817.         dup2(ttyfd,0);
  2818. #endif /* LYNXOS */
  2819.         close(ttyfd);        /* Use file descriptor 0 */
  2820.         ttyfd = 0;
  2821.     } else {            /* Standard i/o is redirected */
  2822.         debug(F101,"ttopen stdio redirected","",ttyfd);
  2823.     }
  2824.     }
  2825. #endif /* NOFDZERO */
  2826.  
  2827. /* Now check if line is locked -- if so fail, else lock for ourselves */
  2828. /* Note: After having done this, don't forget to delete the lock if you */
  2829. /* leave ttopen() with an error condition. */
  2830.  
  2831.     lkf = 0;                            /* Check lock */
  2832.     if (xlocal > 0) {
  2833.     int xx; int xpid;
  2834.         if ((xx = ttlock(ttname)) < 0) { /* Can't lock it. */
  2835.             debug(F111,"ttopen ttlock fails",ttname,xx);
  2836.         /* WARNING - This close() can hang if tty is an empty socket... */
  2837.             close(ttyfd);        /* Close the device. */
  2838.         ttyfd = -1;            /* Erase its file descriptor. */
  2839.         wasclosed = 1;
  2840.         signal(SIGINT,occt);    /* Put old SIGINT back. */
  2841.         sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  2842.         if (xx == -2) {        /* If lockfile says device in use, */
  2843. #ifndef NOUUCP
  2844.         debug(F111,"ttopen reading lockfile pid",flfnam,xx);
  2845.         xpid = ttrpid(flfnam);    /* Try to read pid from lockfile */
  2846.         if (xpid > -1) {    /* If we got a pid */
  2847.                     if (!quiet)
  2848.               printf("Locked by process %d\n",xpid); /* tell them. */
  2849.             sprintf(lockpid,"%d",xpid);    /* Record it too */
  2850.             debug(F110,"ttopen lockpid",lockpid,0);
  2851.         } else if (*flfnam) {
  2852.             extern char *DIRCMD;
  2853.             char *p = NULL;
  2854.             int x;
  2855.             x = (int)strlen(flfnam) + (int)strlen(DIRCMD) + 2;
  2856.             p = malloc(x);    /* Print a directory listing. */
  2857. /*
  2858.   Note: priv_on() won't help here, because we do not pass privs along to
  2859.   to inferior processes, in this case ls.  So if the real user does not have
  2860.   directory-listing access to the lockfile directory, this will result in
  2861.   something like "not found".  That's why we try this only as a last resort.
  2862. */
  2863.             if (p) {        /* If we got the space... */
  2864.             ckmakmsg(p,x,DIRCMD," ",flfnam,NULL);
  2865.             zsyscmd(p);    /* Get listing. */
  2866.             if (p) {    /* free the space */
  2867.                 free(p);
  2868.                 p = NULL;
  2869.             }
  2870.             }
  2871.         }
  2872. #endif /* NOUUCP */
  2873.         return(-5);        /* Code for device in use */
  2874.         } else return(-3);        /* Access denied */
  2875.         } else lkf = 1;
  2876.     }
  2877. #else  /* OPENFIRST */
  2878.  
  2879. /*
  2880.   27 Oct 2001: New simpler code that gets the lock first and then opens the
  2881.   device, which eliminates the race condition.  The downside is you can no
  2882.   longer say "set line /dev/ttyp0" or whatever, where /dev/ttyp0 is your login
  2883.   terminal, without trying to create a lockfile, which fails if C-Kermit lacks
  2884.   privs, and if it succeeds, it has created a lockfile where it didn't create
  2885.   one before.
  2886. */
  2887.     xlocal = *lcl;            /* Is the device my login terminal? */
  2888.     debug(F111,"ttopen xlocal","A",xlocal);
  2889.     fnam = ttname;
  2890.     if (strcmp(ttname,CTTNAM) && netconn == 0) {
  2891.     if (zfnqfp(ttname,DEVNAMLEN+1,fullname)) {
  2892.         if ((int)strlen(fullname) > 0)
  2893.           fnam = fullname;
  2894.     }
  2895.     }
  2896.     debug(F110,"ttopen fnam",fnam,0);
  2897.     if (xlocal < 0) {
  2898.     xlocal = (strcmp(fnam,CTTNAM) != 0);
  2899.     }
  2900.     debug(F111,"ttopen xlocal","B",xlocal);
  2901.  
  2902.     lkf = 0;                            /* No lock yet */
  2903.     if (xlocal > 0) {            /* If not... */
  2904.     int xx; int xpid;
  2905.     xx = ttlock(fnam);        /* Try to lock it. */
  2906.     debug(F101,"ttopen ttlock","",xx);
  2907.         if (xx < 0) {            /* Can't lock it. */
  2908.             debug(F111,"ttopen ttlock fails",fnam,xx);
  2909.         if (xx == -2) {        /* If lockfile says device in use, */
  2910. #ifndef NOUUCP
  2911.         debug(F111,"ttopen reading lockfile pid",flfnam,xx);
  2912.         xpid = ttrpid(flfnam);    /* Try to read pid from lockfile */
  2913.         if (xpid > -1) {    /* If we got a pid */
  2914.                     if (!quiet)
  2915.               printf("Locked by process %d\n",xpid); /* tell them. */
  2916.             ckstrncpy(lockpid,ckitoa(xpid),16);
  2917.             debug(F110,"ttopen lockpid",lockpid,0);
  2918. #ifndef NOPUSH
  2919.         } else if (flfnam[0] && !nopush) {
  2920.             extern char *DIRCMD;
  2921.             char *p = NULL;
  2922.             int x;
  2923.             x = (int)strlen(flfnam) + (int)strlen(DIRCMD) + 2;
  2924.             p = malloc(x);    /* Print a directory listing. */
  2925. /*
  2926.   Note: priv_on() won't help here, because we do not pass privs along to
  2927.   to inferior processes, in this case ls.  So if the real user does not have
  2928.   directory-listing access to the lockfile directory, this will result in
  2929.   something like "not found".  That's why we try this only as a last resort.
  2930. */
  2931.             if (p) {        /* If we got the space... */
  2932.             ckmakmsg(p,x,DIRCMD," ",flfnam,NULL);
  2933.             zsyscmd(p);    /* Get listing. */
  2934.             if (p) {    /* free the space */
  2935.                 free(p);
  2936.                 p = NULL;
  2937.             }
  2938.             }
  2939. #endif /* NOPUSH */
  2940.         }
  2941. #endif /* NOUUCP */
  2942.         return(-5);        /* Code for device in use */
  2943.         } else return(-3);        /* Access denied */
  2944.         } else lkf = 1;
  2945.     }
  2946.     /* Have lock -- now it's safe to open the device */
  2947.  
  2948.     debug(F101,"ttopen lkf","",lkf);
  2949.     debug(F101,"ttopen timo","",timo);
  2950.  
  2951.     ttotmo = 0;                /* Flag no timeout */
  2952.     if (timo > 0) {
  2953.     int xx;
  2954.     saval = signal(SIGALRM,timerh);    /* Timed, set up timer. */
  2955.     xx = alarm(timo);        /* Timed open() */
  2956.     debug(F101,"ttopen alarm","",xx);
  2957.     if (
  2958. #ifdef CK_POSIX_SIG
  2959.         sigsetjmp(sjbuf,1)
  2960. #else
  2961.         setjmp(sjbuf)
  2962. #endif /* CK_POSIX_SIG */
  2963.         ) {
  2964.         ttotmo = 1;            /* Flag timeout. */
  2965.     } else {
  2966.         ttyfd = do_open(fnam);
  2967.     }
  2968.     ttimoff();
  2969.     debug(F111,"ttopen timed ttyfd",fnam,ttyfd);
  2970.     } else {
  2971.     errno = 0;
  2972.     ttyfd = do_open(fnam);
  2973.     debug(F111,"ttopen untimed ttyfd",fnam,ttyfd);
  2974.     }
  2975.     if (ttyfd < 0) {            /* If couldn't open, fail. */
  2976.     debug(F111,"ttopen errno",fnam,errno);
  2977.     debug(F111,"ttopen xlocal","C",xlocal);
  2978.     if (xlocal == 0) {
  2979.         debug(F100,"ttopen substituting 0","",0);
  2980.         ttyfd = 0;
  2981.     } else {
  2982.         if (errno > 0 && !quiet) {
  2983.             debug(F111,"ttopen perror",fnam,errno);
  2984.         perror(fnam);        /* Print message */
  2985.         }
  2986.         if (ttunlck())                  /* Release the lock file */
  2987.           fprintf(stderr,"Warning, problem releasing lock\r\n");
  2988.     }
  2989.     }
  2990.  
  2991.     if (ttyfd < 0) {            /* ttyfd is still < 0? */
  2992. #ifdef ATT7300
  2993.     if (attmodem & DOGETY)        /* was getty(1m) running before us? */
  2994.       ongetty(ttnmsv);        /* yes, restart on tty line */
  2995.     attmodem &= ~DOGETY;        /* no phone in use, getty restored */
  2996. #else
  2997. #ifdef ACUCNTRL
  2998.         /* Should put call to priv_on() here, but that would be risky! */
  2999.     acucntrl("enable",fnam);    /* acucntrl() program. */
  3000.     /* and priv_off() here... */
  3001. #endif /* ACUNTRL */
  3002. #endif /* ATT7300 */
  3003.  
  3004.     signal(SIGINT,occt);        /* Put old Ctrl-C trap back. */
  3005.     if (errno == EACCES) {        /* Device is protected against user */
  3006.         debug(F110,"ttopen EACCESS",fnam,0); /* Return -4 */
  3007.         return(-4);
  3008.     } else return(ttotmo ? -2 : -1); /* Otherwise -2 if timeout, or -1 */
  3009.     }
  3010.  
  3011. /* Make sure it's a real tty. */
  3012.  
  3013. #ifdef Plan9
  3014.     /* take this opportunity to open the control channel */
  3015.     if (p9openttyctl(fnam) < 0)       
  3016. #else
  3017.       if (!ttfdflg && !isatty(ttyfd) && strcmp(fnam,"/dev/null"))
  3018. #endif /* Plan9 */
  3019.     {
  3020.         fprintf(stderr,"%s is not a terminal device\n",fnam);
  3021.         debug(F111,"ttopen not a tty",fnam,errno);
  3022.         if (ttunlck())        /* Release the lock file */
  3023.           fprintf(stderr,"Warning, problem releasing lock\r\n");
  3024.         close(ttyfd);
  3025.         ttyfd = -1;
  3026.         wasclosed = 1;
  3027.         signal(SIGINT,occt);
  3028.         return(-1);
  3029.     }
  3030.  
  3031. #ifdef aegis
  3032.     /*
  3033.       Apollo C runtime claims that console pads are tty devices, which
  3034.       is reasonable, but they aren't any good for packet transfer.
  3035.     */
  3036.     ios_$inq_type_uid((short)ttyfd, ttyuid, st);
  3037.     if (st.all != status_$ok) {
  3038.     fprintf(stderr, "problem getting tty object type: ");
  3039.     error_$print(st);
  3040.     } else if (ttyuid != sio_$uid) {    /* Reject non-SIO lines */
  3041.     close(ttyfd); ttyfd = -1;
  3042.     wasclosed = 1;
  3043.     errno = ENOTTY; perror(fnam);
  3044.     signal(SIGINT,occt);
  3045.     return(-1);
  3046.     }
  3047. #endif /* aegis */
  3048.  
  3049.     sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  3050.  
  3051.     ckstrncpy(ttnmsv,ttname,DEVNAMLEN);    /* Keep copy of name locally. */
  3052.  
  3053. /* Caller wants us to figure out if line is controlling tty */
  3054.  
  3055.     if (*lcl < 0) {
  3056.     char * s;
  3057.         if (strcmp(fnam,CTTNAM) == 0) { /* "/dev/tty" always remote */
  3058.             xlocal = 0;
  3059.         debug(F111,"ttopen fnam=CTTNAM",fnam,xlocal);
  3060.         } else if (strcmp(fnam,cttnam) == 0) {
  3061.             xlocal = 0;
  3062.         debug(F111,"ttopen fnam=cttnam",fnam,xlocal);
  3063.     } else if (cttnam[0]) {
  3064. #ifdef BEBOX_DR7
  3065.             s = ttnmsv;            /* ttyname() is broken */
  3066. #else
  3067.             s = ttyname(ttyfd);         /* Get real name of ttname. */
  3068. #endif /* BEBOX_DR7 */
  3069.         if (!s) s = "";
  3070.         if (*s)
  3071.           xlocal = ((strncmp(s,cttnam,DEVNAMLEN) == 0) ? 0 : 1);
  3072.         else
  3073.           xlocal = 1;
  3074.             debug(F111,"ttopen ttyname(ttyfd) xlocal",s,xlocal);
  3075.         }
  3076.     }
  3077.  
  3078. #ifndef NOFDZERO
  3079. /* Note, the following code was added so that Unix "idle-line" snoopers */
  3080. /* would not think Kermit was idle when it was transferring files, and */
  3081. /* maybe log people out. */
  3082.     if (xlocal == 0) {            /* Remote mode */
  3083.     if (fdflag == 0) {        /* Standard i/o is not redirected */
  3084.         debug(F100,"ttopen setting ttyfd = 0","",0);
  3085. #ifdef LYNXOS
  3086.         /* On Lynx OS, fd 0 is open for read only. */
  3087.         dup2(ttyfd,0);
  3088. #endif /* LYNXOS */
  3089.         close(ttyfd);        /* Use file descriptor 0 */
  3090.         ttyfd = 0;
  3091.     } else {            /* Standard i/o is redirected */
  3092.         debug(F101,"ttopen stdio redirected","",ttyfd);
  3093.     }
  3094.     }
  3095. #endif /* NOFDZERO */
  3096. #endif /* OPENFIRST */
  3097.  
  3098. /* Got the line, now set the desired value for local. */
  3099.  
  3100.     if (*lcl != 0) *lcl = xlocal;
  3101.  
  3102. /* Some special stuff for v7... */
  3103.  
  3104. #ifdef  V7
  3105. #ifndef MINIX
  3106.     if (kmem[TTY] < 0) {        /*  If open, then skip this.  */
  3107.     qaddr[TTY] = initrawq(ttyfd);   /* Init the queue. */
  3108.     if ((kmem[TTY] = open("/dev/kmem", 0)) < 0) {
  3109.         fprintf(stderr, "Can't read /dev/kmem in ttopen.\n");
  3110.         perror("/dev/kmem");
  3111.         exit(1);
  3112.     }
  3113.     }
  3114. #endif /* !MINIX */
  3115. #endif /* V7 */
  3116.  
  3117. /* No failure returns after this point */
  3118.  
  3119. #ifdef ultrix
  3120.     ioctl(ttyfd, TIOCMODEM, &temp);
  3121. #ifdef TIOCSINUSE
  3122.     if (xlocal && ioctl(ttyfd, TIOCSINUSE, NULL) < 0) {
  3123.     if (!quiet)
  3124.       perror(fnam);
  3125.     }
  3126. #endif /* TIOCSINUSE */
  3127. #endif /* ultrix */
  3128.  
  3129. /* Get tty device settings  */
  3130.  
  3131. #ifdef BSD44ORPOSIX            /* POSIX */
  3132.     tcgetattr(ttyfd,&ttold);
  3133.     debug(F101,"ttopen tcgetattr ttold.c_lflag","",ttold.c_lflag);
  3134.     tcgetattr(ttyfd,&ttraw);
  3135.     debug(F101,"ttopen tcgetattr ttraw.c_lflag","",ttraw.c_lflag);
  3136.     tcgetattr(ttyfd,&tttvt);
  3137.     debug(F101,"ttopen tcgetattr tttvt.c_lflag","",tttvt.c_lflag);
  3138. #else                    /* BSD, V7, and all others */
  3139. #ifdef ATTSV                /* AT&T UNIX */
  3140.     ioctl(ttyfd,TCGETA,&ttold);
  3141.     debug(F101,"ttopen ioctl TCGETA ttold.c_lflag","",ttold.c_lflag);
  3142.     ioctl(ttyfd,TCGETA,&ttraw);
  3143.     ioctl(ttyfd,TCGETA,&tttvt);
  3144. #else
  3145. #ifdef BELLV10
  3146.     ioctl(ttyfd,TIOCGETP,&ttold);
  3147.     debug(F101,"ttopen BELLV10 ttold.sg_flags","",ttold.sg_flags);
  3148.     ioctl(ttyfd,TIOCGDEV,&tdold);
  3149.     debug(F101,"ttopen BELLV10 tdold.flags","",tdold.flags);
  3150. #else
  3151.     gtty(ttyfd,&ttold);
  3152.     debug(F101,"ttopen gtty ttold.sg_flags","",ttold.sg_flags);
  3153. #endif /* BELLV10 */
  3154.  
  3155. #ifdef sony_news            /* Sony NEWS */
  3156.     if (ioctl(ttyfd,TIOCKGET,&km_ext) < 0) { /* Get console Kanji mode */
  3157.     perror("ttopen error getting Kanji mode");
  3158.     debug(F101,"ttopen error getting Kanji mode","",0);
  3159.     km_ext = -1;            /* Make sure this stays undefined. */
  3160.     }
  3161. #endif /* sony_news */
  3162.  
  3163. #ifdef TIOCGETC
  3164.     debug(F100,"ttopen TIOCGETC","",0);
  3165.     tcharf = 0;                /* In remote mode, also get */
  3166.     if (xlocal == 0) {            /* special characters */
  3167.     if (ioctl(ttyfd,TIOCGETC,&tchold) < 0) {
  3168.         debug(F100,"ttopen TIOCGETC failed","",0);
  3169.     } else {
  3170.         tcharf = 1;            /* It worked. */
  3171.         ioctl(ttyfd,TIOCGETC,&tchnoi); /* Get another copy */
  3172.         debug(F100,"ttopen TIOCGETC ok","",0);
  3173.     }
  3174.     }
  3175. #else
  3176.     debug(F100,"ttopen TIOCGETC not defined","",0);
  3177. #endif /* TIOCGETC */
  3178.  
  3179. #ifdef TIOCGLTC
  3180.     debug(F100,"ttopen TIOCGLTC","",0);
  3181.     ltcharf = 0;            /* In remote mode, also get */
  3182.     if (xlocal == 0) {            /* local special characters */
  3183.     if (ioctl(ttyfd,TIOCGLTC,<chold) < 0) {
  3184.         debug(F100,"ttopen TIOCGLTC failed","",0);
  3185.     } else {
  3186.         ltcharf = 1;        /* It worked. */
  3187.         ioctl(ttyfd,TIOCGLTC,<chnoi); /* Get another copy */
  3188.         debug(F100,"ttopen TIOCGLTC ok","",0);
  3189.     }
  3190.     }
  3191. #else
  3192.     debug(F100,"ttopen TIOCGLTC not defined","",0);
  3193. #endif /* TIOCGLTC */
  3194.  
  3195. #ifdef TIOCLGET
  3196.     debug(F100,"ttopen TIOCLGET","",0);
  3197.     lmodef = 0;
  3198.     if (ioctl(ttyfd,TIOCLGET,&lmode) < 0) {
  3199.     debug(F100,"ttopen TIOCLGET failed","",0);
  3200.     } else {
  3201.     lmodef = 1;
  3202.     debug(F100,"ttopen TIOCLGET ok","",0);
  3203.     }
  3204. #endif /* TIOCLGET */
  3205.  
  3206. #ifdef BELLV10
  3207.     ioctl(ttyfd,TIOCGETP,&ttraw);
  3208.     ioctl(ttyfd,TIOCGETP,&tttvt);
  3209. #else
  3210.     gtty(ttyfd,&ttraw);                 /* And a copy of it for packets*/
  3211.     gtty(ttyfd,&tttvt);                 /* And one for virtual tty service */
  3212. #endif /* BELLV10 */
  3213.  
  3214. #endif /* ATTSV */
  3215. #endif /* BSD44ORPOSIX */
  3216.  
  3217. /* Section for changing line discipline.  It's restored in ttres(). */
  3218.  
  3219. #ifdef AIXRS
  3220. #ifndef AIX41
  3221.     { union txname ld_name; int ld_idx = 0;
  3222.       ttld = 0;
  3223.         do {
  3224.         ld_name.tx_which = ld_idx++;
  3225.         ioctl(ttyfd, TXGETCD, &ld_name);
  3226.       if (!strncmp(ld_name.tx_name, "rts", 3))
  3227.           ttld |= 1;
  3228.         } while (*ld_name.tx_name);
  3229.         debug(F101,"AIX line discipline","",ttld);
  3230.       }
  3231. #endif /* AIX41 */
  3232. #endif /* AIXRS */
  3233.  
  3234. #ifdef BSD41
  3235. /* For 4.1BSD only, force "old" tty driver, new one botches TANDEM. */
  3236.     { int k;
  3237.       ioctl(ttyfd, TIOCGETD, &ttld);    /* Get and save line discipline */
  3238.       debug(F101,"4.1bsd line discipline","",ttld);
  3239.       k = OTTYDISC;            /* Switch to "old" discipline */
  3240.       k = ioctl(ttyfd, TIOCSETD, &k);
  3241.       debug(F101,"4.1bsd tiocsetd","",k);
  3242.     }
  3243. #endif /* BSD41 */
  3244.  
  3245. #ifdef aegis
  3246.     /* This was previously done before the last two TCGETA or gtty above,
  3247.      * in both the ATTSV and not-ATTSV case.  If it is not okay to have only
  3248.      * one copy if it here instead, give us a shout!
  3249.      */
  3250.     sio_$control((short)ttyfd, sio_$raw_nl, false, st);
  3251.     if (xlocal) {       /* ignore breaks from local line */
  3252.         sio_$control((short)ttyfd, sio_$int_enable, false, st);
  3253.         sio_$control((short)ttyfd, sio_$quit_enable, false, st);
  3254.     }
  3255. #endif /* aegis */
  3256.  
  3257. #ifdef VXVE
  3258.     ttraw.c_line = 0;                   /* STTY line 0 for VX/VE */
  3259.     tttvt.c_line = 0;                   /* STTY line 0 for VX/VE */
  3260.     ioctl(ttyfd,TCSETA,&ttraw);
  3261. #endif /* vxve */
  3262.  
  3263. /* If O_NDELAY was used during open(), then remove it now. */
  3264.  
  3265. #ifdef O_NDELAY
  3266.     debug(F100,"ttopen O_NDELAY","",0);
  3267.     if (xlocal > 0) {
  3268.       if (fcntl(ttyfd, F_GETFL, 0) & O_NDELAY) {
  3269.     debug(F100,"ttopen fcntl O_NDELAY","",0);
  3270. #ifndef aegis
  3271.     if (fcntl(ttyfd,F_SETFL, fcntl(ttyfd, F_GETFL, 0) & ~O_NDELAY) < 0) {
  3272.         debug(F100,"ttopen fcntl failure to unset O_NDELAY","",0);
  3273.         perror("Can't unset O_NDELAY");
  3274.     }
  3275. #endif /* aegis */
  3276.     /* Some systems, notably Xenix (don't know how common this is in
  3277.      * other systems), need special treatment to get rid of the O_NDELAY
  3278.      * behaviour on read() with respect to carrier presence (i.e. read()
  3279.      * returning 0 when carrier absent), even though the above fcntl()
  3280.      * is enough to make read() wait for input when carrier is present.
  3281.      * This magic, in turn, requires CLOCAL for working when the carrier
  3282.      * is absent. But if xlocal == 0, presumably you already have CLOCAL
  3283.      * or you have a carrier, otherwise you wouldn't be running this.
  3284.      */
  3285.     debug(F101,"ttopen xlocal","",xlocal);
  3286. #ifdef ATTSV
  3287. #ifdef BSD44ORPOSIX
  3288. #ifdef COMMENT                /* 12 Aug 1997 */
  3289. #ifdef __bsdi__
  3290.     if (xlocal)
  3291.       ttraw.c_cflag |= CLOCAL;
  3292. #else
  3293. #ifdef __FreeBSD__
  3294.     if (xlocal)
  3295.       ttraw.c_cflag |= CLOCAL;
  3296. #endif /* __FreeBSD__ */
  3297. #endif /* __bsdi__ */
  3298. #else /* Not COMMENT */
  3299. #ifdef CLOCAL
  3300.     if (xlocal)            /* Unset this if it's defined. */
  3301.       ttraw.c_cflag |= CLOCAL;
  3302. #endif /* CLOCAL */
  3303. #endif /* COMMENT */
  3304.     debug(F101,"ttopen BSD44ORPOSIX calling tcsetattr","",TCSADRAIN);
  3305.     if (tcsetattr(ttyfd, TCSADRAIN, &ttraw) < 0) {
  3306.         debug(F100,"ttopen POSIX tcseattr fails","",0);
  3307.         perror("tcsetattr");
  3308.     }
  3309. #else /* !BSD44ORPOSIX */
  3310.     if (xlocal) {
  3311.         ttraw.c_cflag |= CLOCAL;
  3312.         debug(F100,"ttopen calling ioctl(TCSETA)","",0);
  3313.         errno = 0;
  3314.         if (ioctl(ttyfd, TCSETA, &ttraw) < 0) {
  3315.                 debug(F101,"ttopen ioctl(TCSETA) fails","",errno);
  3316.                 perror("ioctl(TCSETA)");
  3317.             }
  3318.     }
  3319. #endif /* BSD44ORPOSIX */
  3320. #endif /* ATTSV */
  3321. #ifndef NOCOTFMC /* = NO Close(Open()) To Force Mode Change */
  3322. /* Reportedly lets uugetty grab the device in SCO UNIX 3.2 / XENIX 2.3 */
  3323.     debug(F100,"ttopen executing close/open","",0);
  3324.     close( priv_opn(fnam, O_RDWR) ); /* Magic to force change. */
  3325. #endif /* NOCOTFMC */
  3326.       }
  3327.     }
  3328. #endif /* O_NDELAY */
  3329.  
  3330. /* Instruct the system how to treat the carrier, and set a few other tty
  3331.  * parameters.
  3332.  *
  3333.  * This also undoes the temporary setting of CLOCAL that may have been done
  3334.  * for the close(open()) above (except in Xenix).  Also throw in ~ECHO, to
  3335.  * prevent the other end of the line from sitting there talking to itself,
  3336.  * producing garbage when the user performs a connect.
  3337.  *
  3338.  * SCO Xenix unfortunately seems to ignore the actual state of CLOCAL.
  3339.  * Now it thinks CLOCAL is always on. It seems the only real solution for
  3340.  * Xenix is to switch between the lower and upper case device names.
  3341.  *
  3342.  * This section may at some future time expand into setting a complete
  3343.  * collection of tty parameters, or call a function shared with ttpkt()/
  3344.  * ttvt() that does so.  On the other hand, the initial parameters are not
  3345.  * that important, since ttpkt() or ttvt() should always fix that before
  3346.  * any communication is done.  Well, we'll see...
  3347.  */
  3348.     if (xlocal) {
  3349.         curcarr = -2;
  3350.     debug(F100,"ttopen calling carrctl","",0);
  3351.     carrctl(&ttraw, ttcarr == CAR_ON);
  3352.     debug(F100,"ttopen carrctl ok","",0);
  3353.  
  3354. #ifdef COHERENT
  3355. #define SVORPOSIX
  3356. #endif /* COHERENT */
  3357.  
  3358. #ifdef SVORPOSIX
  3359.     ttraw.c_lflag &= ~ECHO;
  3360.     ttold.c_lflag &= ~ECHO;
  3361. #ifdef BSD44ORPOSIX
  3362.     y = tcsetattr(ttyfd, TCSADRAIN, &ttraw);
  3363.     debug(F101,"ttopen tcsetattr","",y);
  3364. #else
  3365.     y = ioctl(ttyfd, TCSETA, &ttraw);
  3366.     debug(F100,"ttopen ioctl","",y);
  3367. #endif /* BSD44ORPOSIX */
  3368.  
  3369. #else /* BSD, etc */
  3370.     ttraw.sg_flags &= ~ECHO;
  3371.     ttold.sg_flags &= ~ECHO;
  3372. #ifdef BELLV10
  3373.     y = ioctl(ttyfd,TIOCSETP,&ttraw);
  3374.     debug(F100,"ttopen ioctl","",y);
  3375. #else
  3376.     y = stty(ttyfd,&ttraw);
  3377.     debug(F100,"ttopen stty","",y);
  3378. #endif /* BELLV10 */
  3379. #endif /* SVORPOSIX */
  3380.  
  3381. #ifdef COHERENT
  3382. #undef SVORPOSIX
  3383. #endif /* COHERENT */
  3384.  
  3385.     /* ttflui(); */  /*  This fails for some reason.  */
  3386.     }
  3387.  
  3388.     /* Get current speed */
  3389.  
  3390. #ifndef BEBOX
  3391.     ttspeed = ttgspd();
  3392. #else
  3393.     ttspeed = 19200;
  3394. #endif /* !BEBOX */
  3395.     debug(F101,"ttopen ttspeed","",ttspeed);
  3396.  
  3397.     /* Done, make entries in debug log, restore Ctrl-C trap, and return. */
  3398.  
  3399.     debug(F101,"ttopen ttyfd","",ttyfd);
  3400.     debug(F101,"ttopen *lcl","",*lcl);
  3401.     debug(F111,"ttopen lock file",flfnam,lkf);
  3402.     signal(SIGINT,occt);
  3403.     sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  3404.     gotsigs = 0;
  3405.     return(0);
  3406. }
  3407.  
  3408.  
  3409. /*  D O _ O P E N  --  Do the right kind of open() call for the tty. */
  3410.  
  3411. int
  3412. do_open(ttname) char *ttname; {
  3413.     int flags;
  3414.  
  3415. #ifdef QNX6
  3416.     /* O_NONBLOCK on /dev/tty makes open() fail */
  3417.     return(priv_opn(ttname, O_RDWR |
  3418.             (
  3419.              ((int)strcmp(ttname,"/dev/tty") == 0) ?
  3420.              0 :
  3421.              (ttcarr != CAR_ON) ? O_NONBLOCK : 0)
  3422.             )
  3423.        ); 
  3424. #else  /* !QNX6 */
  3425.  
  3426. #ifndef    O_NDELAY            /* O_NDELAY not defined */
  3427.     return(priv_opn(ttname,2));
  3428. #else                    /* O_NDELAY defined */
  3429.  
  3430. #ifdef ATT7300
  3431. /*
  3432.  Open comms line without waiting for carrier so initial call does not hang
  3433.  because state of "modem" is likely unknown at the initial call  -jrd.
  3434.  If this is needed for the getty stuff to work, and the open would not work
  3435.  without O_NDELAY when getty is still on, then this special case is ok.
  3436.  Otherwise, get rid of it. -ske
  3437. */
  3438.     return(priv_opn(ttname, O_RDWR | O_NDELAY));
  3439.  
  3440. #else    /* !ATT7300 */
  3441.  
  3442.     /* Normal case. Use O_NDELAY according to SET CARRIER. See ttscarr(). */
  3443.     flags = O_RDWR;
  3444.     debug(F101,"do_open xlocal","",xlocal);
  3445.     debug(F111,"do_open flags A",ttname,flags);
  3446.     if (xlocal && (ttcarr != CAR_ON))
  3447.       flags |= O_NDELAY;
  3448.     debug(F111,"do_open flags B",ttname,flags);
  3449.     return(priv_opn(ttname, flags));
  3450. #endif /* !ATT7300 */
  3451. #endif /* O_NDELAY */
  3452. #endif /* QNX6 */
  3453. }
  3454.  
  3455. /*  T T C L O S  --  Close the TTY, releasing any lock.  */
  3456.  
  3457. static int ttc_state = 0;        /* ttclose() state */
  3458. static char * ttc_nam[] = { "setup", "hangup", "reset", "close" };
  3459.  
  3460. int
  3461. ttclos(foo) int foo; {            /* Arg req'd for signal() prototype */
  3462.     int xx, x = 0;
  3463.     extern int exithangup;
  3464.  
  3465.     debug(F101,"ttclos ttyfd","",ttyfd);
  3466.     debug(F101,"ttclos netconn","",netconn);
  3467.     debug(F101,"ttclos xlocal","",xlocal);
  3468. #ifdef NOFDZERO
  3469.     debug(F100,"ttclos NOFDZERO","",0);
  3470. #endif /* NOFDZERO */
  3471.  
  3472. #ifdef COMMENT
  3473. #ifdef TTLEBUF
  3474.     le_init();                /* No need for any of this */
  3475. #endif /* TTLEBUF */
  3476. #endif /* COMMENT */
  3477.  
  3478.     if (ttyfd < 0)            /* Wasn't open. */
  3479.       return(0);
  3480.  
  3481.     if (ttfdflg)            /* If we inherited ttyfd from */
  3482.       return(0);            /* another process, don't close it. */
  3483.  
  3484.     tvtflg = 0;                /* (some day get rid of this...) */
  3485.     gotsigs = 0;
  3486.  
  3487. #ifdef IKSD
  3488.     if (inserver) {
  3489. #ifdef TNCODE
  3490.           tn_push();                    /* Place any waiting data into input*/
  3491.           tn_sopt(DO,TELOPT_LOGOUT);    /* Send LOGOUT option before close */
  3492.           TELOPT_UNANSWERED_DO(TELOPT_LOGOUT) = 1;
  3493.           tn_reset();                   /* The Reset Telnet Option table.  */
  3494. #endif /* TNCODE */
  3495. #ifdef CK_SSL
  3496.       if (ssl_active_flag) {
  3497.           if (ssl_debug_flag)
  3498.         BIO_printf(bio_err,"calling SSL_shutdown(ssl)\n");
  3499.           SSL_shutdown(ssl_con);
  3500.           SSL_free(ssl_con);
  3501.           ssl_con = NULL;
  3502.           ssl_active_flag = 0;
  3503.       }
  3504.       if (tls_active_flag) {
  3505.           if (ssl_debug_flag)
  3506.         BIO_printf(bio_err,"calling SSL_shutdown(tls)\n");
  3507.           SSL_shutdown(tls_con);
  3508.           SSL_free(tls_con);
  3509.           tls_con = NULL;
  3510.           tls_active_flag = 0;
  3511.       }
  3512. #endif /* CK_SSL */
  3513.     }
  3514. #endif /* IKSD */
  3515. #ifdef NETCMD
  3516.     if (ttpipe) {            /* We've been using a pipe */
  3517.     /* ttpipe = 0; */
  3518.     if (ttpid > 0) {
  3519.         int wstat;
  3520.         int statusp;
  3521.         close(fdin);        /* Close these. */
  3522.         close(fdout);
  3523.         fdin = fdout = -1;
  3524.         kill(ttpid,1);        /* Kill fork with SIGHUP */
  3525.         while (1) {
  3526.         wstat = wait(&statusp);
  3527.         if (wstat == ttpid || wstat == -1)
  3528.           break;
  3529.         pexitstat = (statusp & 0xff) ? statusp : statusp >> 8;
  3530.         }
  3531.         ttpid = 0;
  3532.     }
  3533.     netconn = 0;
  3534.     wasclosed = 1;
  3535.     ttyfd = -1;
  3536.     return(0);
  3537.     }
  3538. #endif /* NETCMD */
  3539. #ifdef NETPTY
  3540.     if (ttpty) {
  3541. #ifndef NODOPTY
  3542.         end_pty();
  3543. #endif /* NODOPTY */
  3544.         close(ttyfd);
  3545.     netconn = 0;
  3546.     wasclosed = 1;
  3547.         ttpty = 0;
  3548.         ttyfd = -1;
  3549.         return(0);
  3550.     }
  3551. #endif /* NETPTY */
  3552.  
  3553. #ifdef    NETCONN
  3554.     if (netconn) {            /* If it's a network connection. */
  3555.     debug(F100,"ttclos closing net","",0);
  3556.     netclos();            /* Let the network module close it. */
  3557.     netconn = 0;            /* No more network connection. */
  3558.     debug(F101,"ttclos ttyfd after netclos","",ttyfd); /* Should be -1 */
  3559.     return(0);
  3560.     }
  3561. #endif    /* NETCONN */
  3562.  
  3563.     if (xlocal) {            /* We're closing a SET LINE device */
  3564. #ifdef FT21                /* Fortune 2.1-specific items ... */
  3565.     ioctl(ttyfd,TIOCHPCL, NULL);
  3566. #endif /* FT21 */
  3567. #ifdef ultrix                /* Ultrix-specific items ... */
  3568. #ifdef TIOCSINUSE
  3569.     /* Unset the INUSE flag that we set in ttopen() */
  3570.     ioctl(ttyfd, TIOCSINUSE, NULL);
  3571. #endif /* TIOCSINUSE */
  3572.     ioctl(ttyfd, TIOCNMODEM, &x);
  3573. #ifdef COMMENT
  3574.     /* What was this? */
  3575.     ioctl(ttyfd, TIOCNCAR, NULL);
  3576. #endif /* COMMENT */
  3577. #endif /* ultrix */
  3578.     }
  3579.  
  3580.     /* This is to prevent us from sticking in tthang() or close(). */
  3581.  
  3582. #ifdef O_NDELAY
  3583. #ifndef aegis
  3584.     if (ttyfd > 0) {            /* But skip it on stdin. */
  3585.     debug(F100,"ttclos setting O_NDELAY","",0);
  3586.     x = fcntl(ttyfd,F_SETFL,fcntl(ttyfd,F_GETFL, 0)|O_NDELAY);
  3587. #ifdef DEBUG
  3588.     if (deblog && x == -1) {
  3589.         perror("Warning - Can't set O_NDELAY");
  3590.         debug(F101,"ttclos fcntl failure to set O_NDELAY","",x);
  3591.     }
  3592. #endif /* DEBUG */
  3593.     }
  3594. #endif /* aegis */
  3595. #endif /* O_NDELAY */
  3596.  
  3597.     x = 0;
  3598.     ttc_state = 0;
  3599.     if (xlocal
  3600. #ifdef NOFDZERO
  3601.     || ttyfd > 0
  3602. #endif /* NOFDZERO */
  3603.     ) {
  3604.     saval = signal(SIGALRM,xtimerh); /* Enable timer interrupt. */
  3605.     xx = alarm(8);            /* Allow 8 seconds. */
  3606.     debug(F101,"ttclos alarm","",xx);
  3607.     if (
  3608. #ifdef CK_POSIX_SIG
  3609.         sigsetjmp(sjbuf,1)
  3610. #else
  3611.         setjmp(sjbuf)
  3612. #endif /* CK_POSIX_SIG */
  3613.         ) {                /* Timer went off? */
  3614.         x = -1;
  3615. #ifdef DEBUG
  3616.         debug(F111,"ttclos ALARM TRAP errno",ckitoa(ttc_state),errno);
  3617.         printf("ttclos() timeout: %s\n", ttc_nam[ttc_state]);
  3618. #endif /* DEBUG */
  3619.     }
  3620.     /* Hang up the device (drop DTR) */
  3621.  
  3622.     errno = 0;
  3623.     debug(F111,"ttclos A",ckitoa(x),ttc_state);
  3624.     if (ttc_state < 1) {
  3625.         ttc_state = 1;
  3626.         debug(F101,"ttclos exithangup","",exithangup);
  3627.         if (exithangup) {
  3628.         alarm(8);        /* Re-arm the timer */
  3629.         debug(F101,"ttclos calling tthang()","",x);
  3630.         x = tthang();        /* Hang up first, then... */
  3631.         debug(F101,"ttclos tthang()","",x);
  3632.         }
  3633. #ifndef CK_NOHUPCL
  3634. /*
  3635.   Oct 2006 - Leave DTR on if SET EXIT HANGUP OFF.
  3636.   Suggested by Soewono Effendi.
  3637. */
  3638. #ifdef HUPCL
  3639.         else {
  3640.         ttold.c_cflag &= ~HUPCL; /* Let's see how this travels */
  3641. #ifdef BSD44ORPOSIX
  3642.         tcsetattr(ttyfd,TCSANOW,&ttold);
  3643. #else /* !BSD44ORPOSIX */
  3644. #ifdef ATTSV
  3645.         ioctl(ttyfd,TCSETAW,&ttold);        
  3646. #else  /* !ATTSV */
  3647.         stty(ttyfd,&ttold);
  3648. #endif    /* ATTSV */
  3649. #endif    /* BSD44ORPOSIX */
  3650.         }
  3651. #endif    /* HUPCL */
  3652. #endif    /* CK_NOHUPCL */
  3653.     }
  3654.     /* Put back device modes as we found them */
  3655.  
  3656.     errno = 0;
  3657.     debug(F111,"ttclos B",ckitoa(x),ttc_state);
  3658.     if (ttc_state < 2) {
  3659.         ttc_state = 2;
  3660.         /* Don't try to mess with tty modes if tthang failed() */
  3661.         /* since it probably won't work. */
  3662.         if (x > -1) {
  3663.         debug(F101,"ttclos calling ttres()","",x);
  3664.         signal(SIGALRM,xtimerh); /* Re-enable the alarm. */
  3665.         alarm(8);        /* Re-arm the timer */
  3666.         x = ttres();        /* Reset device modes. */
  3667.         debug(F101,"ttclos ttres()","",x);
  3668.         alarm(0);
  3669.         }
  3670.     }
  3671.     /* Close the device */
  3672.  
  3673.     errno = 0;
  3674.     debug(F101,"ttclos C","",ttc_state);
  3675.     if (ttc_state < 3) {
  3676.         ttc_state = 3;
  3677.         errno = 0;
  3678.         debug(F101,"ttclos calling close","",x);
  3679.         signal(SIGALRM,xtimerh);    /* Re-enable alarm. */
  3680.         alarm(8);            /* Re-arm the timer */
  3681.         x = close(ttyfd);        /* Close the device. */
  3682.         debug(F101,"ttclos close()","",x);
  3683.         if (x > -1)
  3684.           ttc_state = 3;
  3685.     }
  3686.     debug(F101,"ttclos D","",ttc_state);
  3687.     ttimoff();            /* Turn off timer. */
  3688.     if (x < 0) {
  3689.         printf("?WARNING - close failed: %s\n",ttnmsv);
  3690. #ifdef DEBUG
  3691.         if (deblog) {
  3692.         printf("errno = %d\n", errno);
  3693.         debug(F101,"ttclos failed","",errno);
  3694.         }
  3695. #endif /* DEBUG */
  3696.     }
  3697.     /* Unlock after closing but before any getty mumbo jumbo */
  3698.  
  3699.     debug(F100,"ttclos about to call ttunlck","",0);
  3700.         if (ttunlck())                  /* Release uucp-style lock */
  3701.       fprintf(stderr,"Warning, problem releasing lock\r\n");
  3702.     }
  3703.  
  3704. /* For bidirectional lines, restore getty if it was there before. */
  3705.  
  3706. #ifdef ACUCNTRL                /* 4.3BSD acucntrl() method. */
  3707.     if (xlocal) {
  3708.     debug(F100,"ttclos ACUCNTRL","",0);
  3709.     acucntrl("enable",ttnmsv);    /* Enable getty on the device. */
  3710.     }
  3711. #else
  3712. #ifdef ATT7300                /* ATT UNIX PC (3B1, 7300) method. */
  3713.     if (xlocal) {
  3714.     debug(F100,"ttclos ATT7300 ongetty","",0);
  3715.     if (attmodem & DOGETY)        /* Was getty(1m) running before us? */
  3716.       ongetty(ttnmsv);        /* Yes, restart getty on tty line */
  3717.     attmodem &= ~DOGETY;        /* No phone in use, getty restored */
  3718.     }
  3719. #endif /* ATT7300 */
  3720. #endif /* System-dependent getty-restoring methods */
  3721.  
  3722. #ifdef sony_news
  3723.     km_ext = -1;            /* Invalidate device's Kanji-mode */
  3724. #endif /* sony_news */
  3725.  
  3726.     ttyfd = -1;                         /* Invalidate the file descriptor. */
  3727.     wasclosed = 1;
  3728.     debug(F100,"ttclos done","",0);
  3729.     return(0);
  3730. }
  3731.  
  3732. /*  T T H A N G  --  Hangup phone line or network connection.  */
  3733. /*
  3734.   Returns:
  3735.   0 if it does nothing.
  3736.   1 if it believes that it hung up successfully.
  3737.  -1 if it believes that the hangup attempt failed.
  3738. */
  3739.  
  3740. #define HUPTIME 500            /* Milliseconds for hangup */
  3741.  
  3742. #ifdef COMMENT
  3743. /* The following didn't work but TIOCSDTR does work */
  3744. #ifdef UNIXWARE
  3745. /* Define HUP_POSIX to force non-POSIX builds to use the POSIX hangup method */
  3746. #ifndef POSIX                /* Such as Unixware 1.x, 2.x */
  3747. #ifndef HUP_POSIX
  3748. #define HUP_POSIX
  3749. #endif /* HUP_POSIX */
  3750. #endif /* POSIX */
  3751. #endif /* UNIXWARE */
  3752. #endif /* COMMENT */
  3753.  
  3754. #ifndef USE_TIOCSDTR
  3755. #ifdef __NetBSD__
  3756. /* Because the POSIX method (set output speed to 0) doesn't work in NetBSD */
  3757. #ifdef TIOCSDTR
  3758. #ifdef TIOCCDTR
  3759. #define USE_TIOCSDTR
  3760. #endif /* TIOCCDTR */
  3761. #endif /* TIOCSDTR */
  3762. #endif /* __NetBSD__ */
  3763. #endif /* USE_TIOCSDTR */
  3764.  
  3765. #ifndef HUP_CLOSE_POSIX
  3766. #ifdef OU8
  3767. #define HUP_CLOSE_POSIX
  3768. #else
  3769. #ifdef CK_SCOV5
  3770. #define HUP_CLOSE_POSIX
  3771. #endif /* CK_SCOV5 */
  3772. #endif /* OU8 */
  3773. #endif /* HUP_CLOSE_POSIX */
  3774.  
  3775. #ifdef NO_HUP_CLOSE_POSIX
  3776. #ifdef HUP_CLOSE_POSIX
  3777. #undef HUP_CLOSE_POSIX
  3778. #endif /* HUP_CLOSE_POSIX */
  3779. #endif /* NO_HUP_CLOSE_POSIX */
  3780.  
  3781. int
  3782. tthang() {
  3783. #ifdef NOLOCAL
  3784.     return(0);
  3785. #else
  3786.     int x = 0;                /* Sometimes used as return code. */
  3787. #ifndef POSIX
  3788.     int z;                /* worker */
  3789. #endif /* POSIX */
  3790.  
  3791. #ifdef COHERENT
  3792. #define SVORPOSIX
  3793. #endif /* COHERENT */
  3794.  
  3795. #ifdef SVORPOSIX            /* AT&T, POSIX, HPUX declarations. */
  3796.     int spdsav;                /* for saving speed */
  3797. #ifdef HUP_POSIX
  3798.     int spdsavi;
  3799. #else
  3800. #ifdef BSD44ORPOSIX
  3801.     int spdsavi;
  3802. #endif /* BSD44ORPOSIX */
  3803. #endif /* HUP_POSIX */
  3804. #ifdef HPUX
  3805. /*
  3806.   Early versions of HP-UX omitted the mflag typedef.  If you get complaints
  3807.   about it, just change it to long (or better still, unsigned long).
  3808. */
  3809.     mflag
  3810.       dtr_down = 00000000000,
  3811.       modem_rtn,
  3812.       modem_sav;
  3813.     char modem_state[64];
  3814. #endif /* HPUX */
  3815.     int flags;                /* fcntl flags */
  3816.     unsigned short ttc_save;
  3817. #endif /* SVORPOSIX */
  3818.  
  3819.     if (ttyfd < 0) return(0);           /* Don't do this if not open  */
  3820.     if (xlocal < 1) return(0);        /* Don't do this if not local */
  3821.  
  3822. #ifdef NETCMD
  3823.     if (ttpipe)
  3824.       return((ttclos(0) < 0) ? -1 : 1);
  3825. #endif /* NETCMD */
  3826. #ifdef NETPTY
  3827.     if (ttpty)
  3828.       return((ttclos(0) < 0) ? -1 : 1);
  3829. #endif /* NETPTY */
  3830. #ifdef NETCONN
  3831.     if (netconn) {            /* Network connection. */
  3832. #ifdef TN_COMPORT
  3833.         if (istncomport()) {
  3834.             int rc = tnc_set_dtr_state(0);
  3835.             if (rc >= 0) {
  3836.                 msleep(HUPTIME);
  3837.                 rc = tnc_set_dtr_state(1);
  3838.             }
  3839.             return(rc >= 0 ? 1 : -1);
  3840.         } else
  3841. #endif /* TN_COMPORT */
  3842.       return((netclos() < 0) ? -1 : 1); /* Just close it. */
  3843.   }
  3844. #endif /* NETCONN */
  3845.  
  3846. /* From here down, we handle real tty devices. */
  3847. #ifdef HUP_POSIX
  3848. /*
  3849.   e.g. for Unixware 2, where we don't have a full POSIX build, we
  3850.   still have to use POSIX-style hangup.  Thus the duplication of this
  3851.   and the next case, the only difference being we use a local termios
  3852.   struct here, since a different model is used elsewhere.
  3853.  
  3854.   NO LONGER USED as of C-Kermit 8.0 -- it turns out that this method,
  3855.   even though it compiles and executes without error, doesn't actually
  3856.   work (i.e. DTR does not drop), whereas the TIOCSDTR method works just fine,
  3857. */
  3858.     {
  3859.     struct termios ttcur;
  3860.     int x;
  3861.     debug(F100,"tthang HUP_POSIX style","",0);
  3862.     x = tcgetattr(ttyfd, &ttcur);    /* Get current attributes */
  3863.     debug(F111,"tthang tcgetattr",ckitoa(errno),x);
  3864.     if (x < 0) return(-1);
  3865.     spdsav = cfgetospeed(&ttcur);    /* Get current speed */
  3866.     debug(F111,"tthang cfgetospeed",ckitoa(errno),spdsav);
  3867.     spdsavi = cfgetispeed(&ttcur);    /* Get current speed */
  3868.     debug(F111,"tthang cfgetispeed",ckitoa(errno),spdsavi);
  3869.     x = cfsetospeed(&ttcur,B0);    /* Replace by 0 */
  3870.     debug(F111,"tthang cfsetospeed",ckitoa(errno),x);
  3871.     if (x < 0) return(-1);
  3872.     x = cfsetispeed(&ttcur,B0);
  3873.     debug(F111,"tthang cfsetispeed",ckitoa(errno),x);
  3874.     if (x < 0) return(-1);
  3875.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3876.     debug(F111,"tthang tcsetattr B0",ckitoa(errno),x);
  3877.     if (x < 0) return(-1);
  3878.     msleep(HUPTIME);        /* Sleep 0.5 sec */
  3879.     x = cfsetospeed(&ttcur,spdsav); /* Restore prev speed */
  3880.     if (x < 0) return(-1);
  3881.     debug(F111,"tthang cfsetospeed prev",ckitoa(errno),x);
  3882.     x = cfsetispeed(&ttcur,spdsavi);
  3883.     debug(F111,"tthang cfsetispeed prev",ckitoa(errno),x);
  3884.     if (x < 0) return(-1);
  3885.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3886.     debug(F111,"tthang tcsetattr restore",ckitoa(errno),x);
  3887.     if (x < 0) return(-1);
  3888.     return(1);
  3889.     }
  3890. #else
  3891. #ifdef BSD44ORPOSIX
  3892. #ifdef QNX
  3893.     {
  3894.     int x;
  3895.     x = tcdropline(ttyfd,500);
  3896.     debug(F101,"tthang QNX tcdropline","",x);
  3897.     ttcur.c_cflag |= CLOCAL;
  3898.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3899.     debug(F101,"tthang QNX tcsetattr restore","",x);
  3900.     if (x < 0) {
  3901.         debug(F101,"tthang QNX tcsetattr restore errno","",errno);
  3902.         return(-1);
  3903.     }
  3904.     /* Fix flags - ensure O_NONBLOCK is off */
  3905.  
  3906.     errno = 0;
  3907.     debug(F101,"tthang QNX iniflags","",iniflags);
  3908.     if (fcntl(ttyfd, F_SETFL, iniflags) == -1) {
  3909.         debug(F101,"tthang QNX F_SETFL errno","",errno);
  3910.         return(-1);
  3911.     }
  3912.     return(x);
  3913.     }
  3914. #else  /* QNX */
  3915.     {
  3916.     int x;
  3917. #ifdef USE_TIOCSDTR
  3918.     debug(F100,"tthang BSD44ORPOSIX USE_TIOCSDTR","",0);
  3919.     errno = 0;
  3920.     x = ioctl(ttyfd, TIOCCDTR, NULL);
  3921.     debug(F111,"tthang BSD44ORPOSIX ioctl TIOCCDTR",ckitoa(errno),x);
  3922.     if (x < 0) return(-1);
  3923.     msleep(HUPTIME);        /* Sleep 0.5 sec */
  3924.     errno = 0;
  3925.     x = ioctl(ttyfd, TIOCSDTR, NULL);
  3926.     debug(F111,"tthang BSD44ORPOSIX ioctl TIOCSDTR",ckitoa(errno),x);
  3927.     if (x < 0) return(-1);
  3928. #else  /* USE_TIOCSDTR */
  3929.  
  3930. #ifdef HUP_CLOSE_POSIX
  3931. /*
  3932.   In OSR5 versions where TIOCSDTR is not defined (up to and including at
  3933.   least 5.0.6a) the POSIX APIs in the "#else" part below are available but
  3934.   don't work, and no other APIs are available that do work.  In this case
  3935.   we have to drop DTR by brute force: close and reopen the port.  This
  3936.   code actually works, but all the steps are crucial: setting CLOCAL, the
  3937.   O_NDELAY manipulations, etc.
  3938. */
  3939.     debug(F100,"tthang HUP_CLOSE_POSIX close/open","",0);
  3940.     debug(F101,"tthang HUP_CLOSE_POSIX O_NONBLOCK","",O_NONBLOCK);
  3941.     debug(F101,"tthang HUP_CLOSE_POSIX O_NDELAY","",O_NDELAY);
  3942.     errno = 0;
  3943.     x = tcgetattr(ttyfd, &ttcur);    /* Get current attributes */
  3944.     debug(F101,"tthang HUP_CLOSE_POSIX tcgetattr","",x);
  3945.     if (x < 0) {
  3946.         debug(F101,"tthang HUP_CLOSE_POSIX tcgetattr errno","",errno);
  3947.         return(-1);
  3948.     }
  3949.     errno = 0;
  3950.  
  3951.     x = close(ttyfd);        /* Close without releasing lock */
  3952.     if (x < 0) {
  3953.         debug(F101,"tthang HUP_CLOSE_POSIX close errno","",errno);
  3954.         return(-1);
  3955.     }
  3956.     errno = 0;
  3957.     x = msleep(500);        /* Pause half a second */
  3958.     if (x < 0) {            /* Or if that doesn't work, 1 sec */
  3959.         debug(F101,"tthang HUP_CLOSE_POSIX msleep errno","",errno);
  3960.         sleep(1);
  3961.     }
  3962.     errno = 0;
  3963.     ttyfd = priv_opn(ttnmsv, (O_RDWR|O_NDELAY)); /* Reopen the device */
  3964.     debug(F111,"tthang HUP_CLOSE_POSIX reopen",ttnmsv,ttyfd);
  3965.     if (ttyfd < 0) {
  3966.         debug(F101,"tthang HUP_CLOSE_POSIX reopen errno","",errno);
  3967.         return(-1);
  3968.     }
  3969.     debug(F101,"tthang HUP_CLOSE_POSIX re-ttopen ttyfd","",ttyfd);
  3970.  
  3971.     /* Restore previous attributes */
  3972.  
  3973.     errno = 0;
  3974.     tvtflg = 0;
  3975.     ttcur.c_cflag |= CLOCAL;
  3976.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3977.     debug(F101,"tthang HUP_CLOSE_POSIX tcsetattr restore","",x);
  3978.     if (x < 0) {
  3979.         debug(F101,"tthang HUP_CLOSE_POSIX tcsetattr restore errno",
  3980.           "",errno);
  3981.         return(-1);
  3982.     }
  3983.     /* Fix flags - ensure O_NDELAY and O_NONBLOCK are off */
  3984.  
  3985.     errno = 0;
  3986.         if ((x = fcntl(ttyfd, F_GETFL, 0)) == -1) {
  3987.         debug(F101,"tthang HUP_CLOSE_POSIX F_GETFL errno","",errno);
  3988.         return(-1);
  3989.     }
  3990.     debug(F101,"tthang HUP_CLOSE_POSIX flags","",x);
  3991.     errno = 0;
  3992.         x &= ~(O_NONBLOCK|O_NDELAY);
  3993.     debug(F101,"tthang HUP_CLOSE_POSIX flags to set","",x);
  3994.     debug(F101,"tthang HUP_CLOSE_POSIX iniflags","",iniflags);
  3995.     if (fcntl(ttyfd, F_SETFL, x) == -1) {
  3996.         debug(F101,"tthang HUP_CLOSE_POSIX F_SETFL errno","",errno);
  3997.         return(-1);
  3998.     }
  3999. #ifdef DEBUG
  4000.     if (deblog) {
  4001.         if ((x = fcntl(ttyfd, F_GETFL, 0)) > -1) {
  4002.         debug(F101,"tthang HUP_CLOSE_POSIX flags","",x);
  4003.         debug(F101,"tthang HUP_CLOSE_POSIX flags & O_NONBLOCK",
  4004.               "",x&O_NONBLOCK);
  4005.         debug(F101,"tthang HUP_CLOSE_POSIX flags & O_NDELAY",
  4006.               "",x&O_NDELAY);
  4007.         }
  4008.     }
  4009. #endif /* DEBUG */
  4010.  
  4011. #else  /* HUP_CLOSE_POSIX */
  4012.     
  4013.     /* General BSD44ORPOSIX case (Linux, BSDI, FreeBSD, etc) */
  4014.  
  4015.     debug(F100,"tthang BSD44ORPOSIX B0","",0);
  4016.     x = tcgetattr(ttyfd, &ttcur);    /* Get current attributes */
  4017.     debug(F111,"tthang BSD44ORPOSIX tcgetattr",ckitoa(errno),x);
  4018.     if (x < 0) return(-1);
  4019.     spdsav = cfgetospeed(&ttcur);    /* Get current speed */
  4020.     debug(F111,"tthang BSD44ORPOSIX cfgetospeed",ckitoa(errno),spdsav);
  4021.     spdsavi = cfgetispeed(&ttcur);    /* Get current speed */
  4022.     debug(F111,"tthang BSD44ORPOSIX cfgetispeed",ckitoa(errno),spdsavi);
  4023.     x = cfsetospeed(&ttcur,B0);    /* Replace by 0 */
  4024.     debug(F111,"tthang BSD44ORPOSIX cfsetospeed",ckitoa(errno),x);
  4025.     if (x < 0) return(-1);
  4026.     x = cfsetispeed(&ttcur,B0);
  4027.     debug(F111,"tthang BSD44ORPOSIX cfsetispeed",ckitoa(errno),x);
  4028.     if (x < 0) return(-1);
  4029.     /* This gets EINVAL on NetBSD 1.4.1 because of B0... */
  4030.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  4031.     debug(F111,"tthang BSD44ORPOSIX tcsetattr B0",ckitoa(errno),x);
  4032.     if (x < 0) return(-1);
  4033.     msleep(HUPTIME);        /* Sleep 0.5 sec */
  4034.     debug(F101,"tthang BSD44ORPOSIX restore output speed","",spdsav);
  4035.     x = cfsetospeed(&ttcur,spdsav); /* Restore prev speed */
  4036.     debug(F111,"tthang BSD44ORPOSIX cfsetospeed prev",ckitoa(errno),x);
  4037.     if (x < 0) return(-1);
  4038.     debug(F101,"tthang BSD44ORPOSIX restore input speed","",spdsavi);
  4039.     x = cfsetispeed(&ttcur,spdsavi);
  4040.     debug(F111,"tthang BSD44ORPOSIX cfsetispeed prev",ckitoa(errno),x);
  4041.     if (x < 0) return(-1);
  4042.     ttcur.c_cflag |= CLOCAL;    /* Don't expect CD after hangup */
  4043.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  4044.     debug(F111,"tthang BSD44ORPOSIX tcsetattr restore",ckitoa(errno),x);
  4045.     if (x < 0) return(-1);
  4046.  
  4047. #endif /* HUP_CLOSE_POSIX */
  4048. #endif /* USE_TIOCSDTR */
  4049.  
  4050.     return(1);
  4051.     }
  4052.  
  4053. #endif /* QNX */
  4054. #else /* BSD44ORPOSIX */
  4055.  
  4056. #ifdef aegis                /* Apollo Aegis */
  4057.     sio_$control((short)ttyfd, sio_$dtr, false, st);    /* DTR down */
  4058.     msleep(HUPTIME);                    /* pause */
  4059.     sio_$control((short)ttyfd, sio_$dtr, true,  st);    /* DTR up */
  4060.     return(1);
  4061. #endif /* aegis */
  4062.  
  4063. #ifdef ANYBSD                /* Any BSD version. */
  4064. #ifdef TIOCCDTR                /* Except those that don't have this */
  4065.     debug(F100,"tthang BSD style","",0);
  4066.     if (ioctl(ttyfd,TIOCCDTR,0) < 0) {    /* Clear DTR. */
  4067.     debug(F101,"tthang TIOCCDTR fails","",errno);
  4068.     return(-1);
  4069.     }
  4070.     msleep(HUPTIME);            /* For about 1/2 sec */
  4071.     errno = 0;
  4072.     x = ioctl(ttyfd,TIOCSDTR,0);    /* Restore DTR */
  4073.     if (x < 0) {
  4074.     /*
  4075.       For some reason, this tends to fail with "no such device or address"
  4076.       but the operation still works, probably because of the close/open
  4077.       later on.  So let's not scare the user unnecessarily here.
  4078.     */
  4079.     debug(F101,"tthang TIOCSDTR errno","",errno); /* Log the error */
  4080.     x = 1;                /* Pretend we succeeded */
  4081.     } else if (x == 0) x = 1;        /* Success */
  4082. #ifdef COMMENT
  4083. #ifdef FT21
  4084.     ioctl(ttyfd, TIOCSAVEMODES, 0);
  4085.     ioctl(ttyfd, TIOCHPCL, 0);
  4086.     close(ttyfd);            /* Yes, must do this twice */
  4087.     if ((ttyfd = open(ttnmsv,2)) < 0)    /* on Fortune computers... */
  4088.       return(-1);            /* (but why?) */
  4089.     else x = 1;
  4090. #endif /* FT21 */
  4091. #endif /* COMMENT */
  4092. #endif /* TIOCCDTR */
  4093.     close(do_open(ttnmsv));        /* Clear i/o error condition */
  4094.     errno = 0;
  4095. #ifdef COMMENT
  4096. /* This is definitely dangerous.  Why was it here? */
  4097.     z = ttvt(ttspeed,ttflow);        /* Restore modes. */
  4098.     debug(F101,"tthang ttvt returns","",z);
  4099.     return(z < 0 ? -1 : 1);
  4100. #else
  4101.     return(x);
  4102. #endif /* COMMENT */
  4103. #endif /* ANYBSD */
  4104.  
  4105. #ifdef ATTSV
  4106. /* AT&T UNIX section, includes HP-UX and generic AT&T System III/V... */
  4107.  
  4108. #ifdef HPUX
  4109. /* Hewlett Packard allows explicit manipulation of modem signals. */
  4110.  
  4111. #ifdef COMMENT
  4112. /* Old way... */
  4113.     debug(F100,"tthang HP-UX style","",0);
  4114.     if (ioctl(ttyfd,MCSETAF,&dtr_down) < 0)        /* lower DTR */
  4115.       return(-1);                           /* oops, can't. */
  4116.     msleep(HUPTIME);                       /* Pause half a second. */
  4117.     x = 1;                           /* Set return code */
  4118.     if (ioctl(ttyfd,MCGETA,&modem_rtn) > -1) {     /* Get line status. */
  4119.     if ((modem_rtn & MDCD) != 0)             /* Check if CD is low. */
  4120.       x = -1;                                  /* CD didn't drop, fail. */
  4121.     } else x = -1;
  4122.  
  4123.     /* Even if above calls fail, RTS & DTR should be turned back on. */
  4124.     modem_rtn = MRTS | MDTR;
  4125.     if (ioctl(ttyfd,MCSETAF,&modem_rtn) < 0) x = -1;
  4126.     return(x);
  4127. #else
  4128. /* New way, from Hellmuth Michaelis */
  4129.     debug(F100,"tthang HP-UX style, HPUXDEBUG","",0);
  4130.     if (ioctl(ttyfd,MCGETA,&modem_rtn) == -1) { /* Get current status. */
  4131.     debug(F100,"tthang HP-UX: can't get modem lines, NO HANGUP!","",0);
  4132.     return(-1);
  4133.     }
  4134.     sprintf(modem_state,"%#lx",modem_rtn);
  4135.     debug(F110,"tthang HP-UX: modem lines = ",modem_state,0);
  4136.     modem_sav = modem_rtn;        /* Save current modem signals */
  4137.     modem_rtn &= ~MDTR;            /* Turn DTR bit off */
  4138.     sprintf(modem_state,"%#lx",modem_rtn);
  4139.     debug(F110,"tthang HP-UX: DTR down = ",modem_state,0);
  4140.     if (ioctl(ttyfd,MCSETAF,&modem_rtn) < 0) { /* lower DTR */
  4141.     debug(F100,"tthang HP-UX: can't lower DTR!","",0);
  4142.     return(-1);            /* oops, can't. */
  4143.     }
  4144.     msleep(HUPTIME);            /* Pause half a second. */
  4145.     x = 1;                /* Set return code */
  4146.     if (ioctl(ttyfd,MCGETA,&modem_rtn) > -1) { /* Get line status. */
  4147.     sprintf(modem_state,"%#lx",modem_rtn);
  4148.     debug(F110,"tthang HP-UX: modem lines got = ",modem_state,0);
  4149.     if ((modem_rtn & MDCD) != 0) {    /* Check if CD is low. */
  4150.         debug(F100,"tthang HP-UX: DCD not down","",0);
  4151.         x = -1;            /* CD didn't drop, fail. */
  4152.     } else {
  4153.         debug(F100,"tthang HP-UX: DCD down","",0);
  4154.     }
  4155.     } else {
  4156.     x = -1;
  4157.     debug(F100,"tthang HP-UX: can't get DCD status !","",0);
  4158.     }
  4159.  
  4160.     /* Even if above calls fail, DTR should be turned back on. */
  4161.  
  4162.     modem_sav |= MDTR;
  4163.     if (ioctl(ttyfd,MCSETAF,&modem_sav) < 0) {
  4164.     x = -1;
  4165.     debug(F100,"tthang HP-UX: can't set saved state","",0);
  4166.     } else {
  4167.     sprintf(modem_state,"%#lx",modem_sav);
  4168.     debug(F110,"tthang HP-UX: final modem lines = ",modem_state,0);
  4169.     }
  4170.     return(x);
  4171. #endif /* COMMENT */
  4172.  
  4173. #else /* AT&T but not HP-UX */
  4174.  
  4175. /* SVID for AT&T System V R3 defines ioctl's for handling modem signals. */
  4176. /* It is not known how many, if any, systems actually implement them, */
  4177. /* so we include them here in ifdef's. */
  4178.  
  4179. /*
  4180.   Unixware has the TIOCMxxx symbols defined, but calling ioctl() with them
  4181.   gives error 22 (invalid argument).
  4182. */
  4183. #ifndef _IBMR2
  4184. /*
  4185.   No modem-signal twiddling for IBM RT PC or RS/6000.
  4186.   In AIX 3.1 and earlier, the ioctl() call is broken.
  4187.   This code could be activated for AIX 3.1 with PTF 2006 or later
  4188.   (e.g. AIX 3.2), but close/open does the job too, so why bother.
  4189. */
  4190. #ifdef TIOCMBIS                /* Bit Set */
  4191. #ifdef TIOCMBIC                /* Bit Clear */
  4192. #ifdef TIOCM_DTR            /* DTR */
  4193.  
  4194. /* Clear DTR, sleep 300 msec, turn it back on. */
  4195. /* If any of the ioctl's return failure, go on to the next section. */
  4196.  
  4197.     z = TIOCM_DTR;            /* Code for DTR. */
  4198. #ifdef COMMENT
  4199. /*
  4200.   This was the cause of the troubles with the Solaris Port Monitor.
  4201.   The problem is: RTS never comes back on.  Moral: Don't do it!
  4202.   (But why doesn't it come back on?  See the TIOCMBIS call...)
  4203. */
  4204. #ifdef TIOCM_RTS            /* Lower RTS too if symbol is known. */
  4205.     z |= TIOCM_RTS;
  4206. #endif /* TIOCM_RTS */
  4207. #endif /* COMMENT */
  4208.  
  4209.     debug(F101,"tthang TIOCM signal mask","",z);
  4210.     if (ioctl(ttyfd,TIOCMBIC,&z) > -1) {   /* Try to lower DTR. */
  4211.     debug(F100,"tthang TIOCMBIC ok","",0);
  4212.     msleep(HUPTIME);           /* Pause half a second. */
  4213.     if (ioctl(ttyfd,TIOCMBIS,&z) > -1) { /* Try to turn it back on. */
  4214.         debug(F100,"tthang TIOCMBIS ok","",0);
  4215. #ifndef CLSOPN
  4216.         return(1);            /* Success, done. */
  4217. #endif /* CLSOPN */
  4218.     } else {            /* Couldn't raise, continue. */
  4219.         debug(F101,"tthang TIOCMBIS errno","",errno);
  4220.     }
  4221.     } else {                /* Couldn't lower, continue. */
  4222.      debug(F101,"tthang TIOCMBIC errno","",errno);
  4223.     }
  4224. #endif /* TIOCM_DTR */
  4225. #endif /* TIOCMBIC */
  4226. #endif /* TIOCMBIS */
  4227. #endif /* _IBMR2 */
  4228.  
  4229. /*
  4230.   General AT&T UNIX case, not HPUX.  The following code is highly suspect.  No
  4231.   two AT&T-based systems seem to do this the same way.  The object is simply
  4232.   to turn off DTR and then turn it back on.  SVID says the universal method
  4233.   for turning off DTR is to set the speed to zero, and this does seem to do
  4234.   the trick in all cases.  But neither SVID nor any known man pages say how to
  4235.   turn DTR back on again.  Some variants, like most Xenix implementations,
  4236.   raise DTR again when the speed is restored to a nonzero value.  Others
  4237.   require the device to be closed and opened again, but this is risky because
  4238.   getty could seize the device during the instant it is closed.
  4239. */
  4240.  
  4241. /* Return code for ioctl failures... */
  4242. #ifdef ATT6300
  4243.     x = 1;                /* ATT6300 doesn't want to fail... */
  4244. #else
  4245.     x = -1;
  4246. #endif /* ATT6300 */
  4247.  
  4248.     debug(F100,"tthang get settings","",0);
  4249.     if (ioctl(ttyfd,TCGETA,&ttcur) < 0) /* Get current settings. */
  4250.       return(x);            /* Fail if this doesn't work. */
  4251.     if ((flags = fcntl(ttyfd,F_GETFL,0)) < 0) /* Get device flags. */
  4252.       return(x);
  4253.     ttc_save = ttcur.c_cflag;        /* Remember current speed. */
  4254.     spdsav = ttc_save & CBAUD;
  4255.     debug(F101,"tthang speed","",spdsav);
  4256.  
  4257. #ifdef O_NDELAY
  4258.     debug(F100,"tthang turning O_NDELAY on","",0);
  4259.     fcntl(ttyfd, F_SETFL, flags | O_NDELAY); /* Activate O_NDELAY */
  4260. #endif /* O_NDELAY */
  4261.  
  4262. #ifdef ATT7300 /* This is the way it is SUPPOSED to work */
  4263.     ttcur.c_cflag &= ~CBAUD;        /* Change the speed to zero.  */
  4264. #else
  4265. #ifdef RTAIX
  4266.     ttcur.c_cflag &= ~CBAUD;        /* Change the speed to zero.  */
  4267. #else          /* This way really works but may be dangerous */
  4268. #ifdef u3b2
  4269.     ttcur.c_cflag = ~(CBAUD|CLOCAL);    /* Special for AT&T 3B2s */
  4270.                     /* (CLOCAL must be OFF) */
  4271. #else
  4272. #ifdef SCO3R2                /* SCO UNIX 3.2 */
  4273. /*
  4274.   This is complete nonsense, but an SCO user claimed this change made
  4275.   hanging up work.  Comments from other SCO UNIX 3.2 users would be
  4276.   appreciated.
  4277. */
  4278.     ttcur.c_cflag = CBAUD|B0;
  4279. #else
  4280. #ifdef AIXRS                /* AIX on RS/6000 */
  4281. /*
  4282.   Can't set speed to zero on AIX 3.1 on RS/6000 64-port adapter,
  4283.   even though you can do it on the built-in port and the 8- and 16-port
  4284.   adapters.  (Untested on 128-port adapter.)
  4285. */
  4286.     ttcur.c_cflag = CLOCAL|HUPCL|spdsav; /* Speed 0 causes EINVAL */
  4287. #else                    /* None of the above */
  4288. /*
  4289.   Set everything, including the speed, to zero, except for the CLOCAL
  4290.   and HUPCL bits.
  4291. */
  4292.     ttcur.c_cflag = CLOCAL|HUPCL;
  4293. #endif /* AIXRS */
  4294. #endif /* SCO3R2 */
  4295. #endif /* u3b2 */
  4296. #endif /* RTAIX */
  4297. #endif /* ATT7300 */
  4298.  
  4299. #ifdef COMMENT
  4300.     /* and if none of those work, try one of these... */
  4301.     ttcur.c_cflag = 0;
  4302.     ttcur.c_cflag = CLOCAL;
  4303.     ttcur.c_cflag &= ~(CBAUD|HUPCL);
  4304.     ttcur.c_cflag &= ~(CBAUD|CREAD);
  4305.     ttcur.c_cflag &= ~(CBAUD|CREAD|HUPCL);
  4306.     /* or other combinations */
  4307. #endif /* COMMENT */
  4308.  
  4309. #ifdef TCXONC
  4310.     debug(F100,"tthang TCXONC","",0);
  4311.     if (ioctl(ttyfd, TCXONC, 1) < 0) {
  4312.     debug(F101,"tthang TCXONC failed","",errno);
  4313.     }
  4314. #endif /* TCXONC */
  4315.  
  4316. #ifdef TIOCSTART
  4317.     debug(F100,"tthang TIOCSTART","",0);
  4318.     if (ioctl(ttyfd, TIOCSTART, 0) < 0) {
  4319.     debug(F101,"tthang TIOCSTART failed","",errno);
  4320.     }
  4321. #endif /* TIOCSTART */
  4322.  
  4323.     if (ioctl(ttyfd,TCSETAF,&ttcur) < 0) { /* Fail if we can't. */
  4324.     debug(F101,"tthang TCSETAF failed","",errno);
  4325.     fcntl(ttyfd, F_SETFL, flags);    /* Restore flags */
  4326.     return(-1);            /* before returning. */
  4327.     }
  4328.     msleep(300);            /* Give modem time to notice. */
  4329.  
  4330. #ifndef NOCOTFMC
  4331.  
  4332. /* Now, even though it doesn't say this in SVID or any man page, we have */
  4333. /* to close and reopen the device.  This is not necessary for all systems, */
  4334. /* but it's impossible to predict which ones need it and which ones don't. */
  4335.  
  4336. #ifdef ATT7300
  4337. /*
  4338.   Special handling for ATT 7300 UNIX PC and 3B1, which have "phone"
  4339.   related ioctl's for their internal modems.  attmodem has getty status and
  4340.   modem-in-use bit.  Reportedly the ATT7300/3B1 PIOCDISC call is necessary,
  4341.   but also ruins the file descriptor, and no other phone(7) ioctl call can fix
  4342.   it.  Whatever it does, it seems to escape detection with PIOCGETA and TCGETA.
  4343.   The only way to undo the damage is to close the fd and then reopen it.
  4344. */
  4345.     if (attmodem & ISMODEM) {
  4346.     debug(F100,"tthang attmodem close/open","",0);
  4347.     ioctl(ttyfd,PIOCUNHOLD,&dialer); /* Return call to handset. */
  4348.     ioctl(ttyfd,PIOCDISC,&dialer);    /* Disconnect phone. */
  4349.     close(ttyfd);            /* Close and reopen the fd. */
  4350.     ttyfd = priv_opn(ttnmsv, O_RDWR | O_NDELAY);
  4351.     attmodem &= ~ISMODEM;        /* Phone no longer in use. */
  4352.     }
  4353. #else /* !ATT7300 */
  4354. /* It seems we have to close and open the device for other AT&T systems */
  4355. /* too, and this is the place to do it.  The following code does the */
  4356. /* famous close(open(...)) magic by default.  If that doesn't work for you, */
  4357. /* then try uncommenting the following statement or putting -DCLSOPN in */
  4358. /* the makefile CFLAGS. */
  4359.  
  4360. /* #define CLSOPN */
  4361.  
  4362. #ifndef SCO32 /* Not needed by, and harmful to, SCO UNIX 3.2 / Xenix 2.3 */
  4363.  
  4364. #ifdef O_NDELAY
  4365. #define OPENFLGS O_RDWR | O_NDELAY
  4366. #else
  4367. #define OPENFLGS O_RDWR
  4368. #endif
  4369.  
  4370. #ifndef CLSOPN
  4371. /* This method is used by default, i.e. unless CLSOPN is defined. */
  4372. /* It is thought to be safer because there is no window where getty */
  4373. /* can seize control of the device.  The drawback is that it might not work. */
  4374.  
  4375.     debug(F101,"tthang close(open()), OPENFLGS","",OPENFLGS);
  4376.     close(priv_opn(ttnmsv, OPENFLGS));
  4377.  
  4378. #else
  4379. /* This method is used if you #define CLSOPN.  It is more likely to work */
  4380. /* than the previous method, but it's also more dangerous. */
  4381.  
  4382.     debug(F101,"tthang close/open, OPENFLGS","",OPENFLGS);
  4383.     close(ttyfd);
  4384.     msleep(10);
  4385.     ttyfd = priv_opn(ttnmsv, OPENFLGS);    /* Open it again */
  4386. #endif /* CLSOPN */
  4387. #undef OPENFLGS
  4388.  
  4389. #endif /* SCO32 */
  4390. #endif /* ATT7300 */
  4391.  
  4392. #endif /* NOCOTFMC */
  4393.  
  4394. /* Now put all flags & modes back the way we found them. */
  4395. /* (Does the order of ioctl & fcntl matter ? ) */
  4396.  
  4397.     debug(F100,"tthang restore settings","",0);
  4398.     ttcur.c_cflag = ttc_save;        /* Get old speed back. */
  4399.     if (ioctl(ttyfd,TCSETAF,&ttcur) < 0) /* ioctl parameters. */
  4400.       return(-1);
  4401. #ifdef O_NDELAY
  4402. /*
  4403.   This is required for IBM RT and RS/6000, probably helps elsewhere too (?).
  4404.   After closing a modem line, the modem will probably not be asserting
  4405.   carrier any more, so we should not require carrier any more.  If this
  4406.   causes trouble on non-IBM UNIXes, change the #ifdef to use _IBMR2 rather
  4407.   than O_NDELAY.
  4408. */
  4409.     flags &= ~O_NDELAY;            /* Don't require carrier on reopen */
  4410. #endif /* O_NDELAY */
  4411.     if (fcntl(ttyfd,F_SETFL,flags) < 0)    /* fcntl parameters */
  4412.       return(-1);
  4413.  
  4414.     return(1);
  4415. #endif /* not HPUX */
  4416. #endif /* ATTSV */
  4417. #endif /* BSD44ORPOSIX */
  4418. #endif /* HUP_POSIX */
  4419. #endif /* NOLOCAL */
  4420. }
  4421.  
  4422. /*
  4423.   Major change in 5A(174).  We used to use LPASS8, if it was defined, to
  4424.   allow 8-bit data and Xon/Xoff flow control at the same time.  But this
  4425.   LPASS8 business seems to have been causing trouble for everybody but me!
  4426.   For example, Annex terminal servers, commonly used with Encore computers,
  4427.   do not support LPASS8 even though the Encore itself does.  Ditto for many
  4428.   other terminal servers, TELNET connections, rlogin connections, etc etc.
  4429.   Now, reportedly, even vanilla 4.3 BSD systems can't do this right on their
  4430.   serial lines, even though LPASS8 is a feature of 4.3BSD.  So let's turn it
  4431.   off for everybody.  That means we goes back to using raw mode, with no
  4432.   flow control.  Phooey.
  4433.  
  4434.   NOTE: This must be done before the first reference to LPASS8 in this file,
  4435.   and after the last #include statment.
  4436. */
  4437. #ifdef LPASS8
  4438. #undef LPASS8
  4439. #endif /* LPASS8 */
  4440.  
  4441. /*  T T R E S  --  Restore terminal to "normal" mode.  */
  4442.  
  4443. /* ske@pkmab.se: There are two choices for what this function should do.
  4444.  * (1) Restore the tty to current "normal" mode, with carrier treatment
  4445.  * according to ttcarr, to be used after every kermit command. (2) Restore
  4446.  * the tty to the state it was in before kermit opened it. These choices
  4447.  * conflict, since ttold can't hold both choices of tty parameters.  ttres()
  4448.  * is currently being called as in choice (1), but ttold basically holds
  4449.  * the initial parameters, as in (2), and the description at the beginning
  4450.  * of this file says (2).
  4451.  *
  4452.  * I don't think restoring tty parameters after all kermit commands makes
  4453.  * much of a difference.  Restoring them upon exit from kermit may be of
  4454.  * some use in some cases (when the line is not restored automatically on
  4455.  * close, by the operating system).
  4456.  *
  4457.  * I can't choose which one it should be, so I haven't changed it. It
  4458.  * probably works as it is, too. It would probably even work even with
  4459.  * ttres() entirely deleted...
  4460.  *
  4461.  * (from fdc: Actually, this function operates in remote mode too, so
  4462.  * it restores the console (command) terminal to whatever mode it was
  4463.  * in before packet operations began, so that commands work right again.)
  4464.  */
  4465. int
  4466. ttres() {                               /* Restore the tty to normal. */
  4467.     int x;
  4468.  
  4469.     if (ttyfd < 0) return(-1);          /* Not open. */
  4470.  
  4471.     if (ttfdflg) return(0);        /* Don't mess with terminal modes if */
  4472.                     /* we got ttyfd from another process */
  4473. #ifdef    NETCONN
  4474.     if (netconn) {            /* Network connection */
  4475.         tvtflg = 0;
  4476. #ifdef TCPSOCKET
  4477. #ifdef TCP_NODELAY
  4478.         {
  4479.         extern int tcp_nodelay;    /* Just put this back if necessary */
  4480.         if (ttnet == NET_TCPB) {
  4481.         if (nodelay_sav > -1) {
  4482.             no_delay(ttyfd,nodelay_sav);
  4483.             nodelay_sav = -1;
  4484.         }
  4485.         }
  4486.         }
  4487. #endif /* TCP_NODELAY */
  4488. #ifdef TN_COMPORT
  4489.         if (istncomport()) {
  4490.             int rc = -1;
  4491.             if ((rc = tnsetflow(ttflow)) < 0)
  4492.           return(rc);
  4493.             if (ttspeed <= 0) 
  4494.           ttspeed = tnc_get_baud();
  4495.             else if ((rc = tnc_set_baud(ttspeed)) < 0)
  4496.           return(rc);
  4497.             tnc_set_datasize(8);
  4498.         tnc_set_stopsize(stopbits);
  4499.  
  4500. #ifdef HWPARITY
  4501.             if (hwparity) {
  4502.                 switch (hwparity) {
  4503.           case 'e':            /* Even */
  4504.                     debug(F100,"ttres 8 bits + even parity","",0);
  4505.                     tnc_set_parity(3);
  4506.                     break;
  4507.           case 'o':            /* Odd */
  4508.                     debug(F100,"ttres 8 bits + odd parity","",0);
  4509.                     tnc_set_parity(2);
  4510.                     break;
  4511.           case 'm':            /* Mark */
  4512.                     debug(F100,"ttres 8 bits + invalid parity: mark","",0);
  4513.                     tnc_set_parity(4);
  4514.                     break;
  4515.           case 's':            /* Space */
  4516.                     debug(F100,"ttres 8 bits + invalid parity: space","",0);
  4517.                     tnc_set_parity(5);
  4518.                     break;
  4519.                 }
  4520.             } else
  4521. #endif /* HWPARITY */
  4522.         {
  4523.                 tnc_set_parity(1);              /* None */
  4524.             }
  4525.             tvtflg = 0;
  4526.             return(0);
  4527.         }
  4528. #endif /* TN_COMPORT */
  4529. #endif /* TCPSOCKET */
  4530.     return(0);
  4531.     }
  4532. #endif    /* NETCONN */
  4533. #ifdef NETCMD
  4534.     if (ttpipe) return(0);
  4535. #endif /* NETCMD */
  4536. #ifdef NETPTY
  4537.     if (ttpty) return(0);
  4538. #endif /* NETPTY */
  4539.  
  4540. /* Real terminal device, so restore its original modes */
  4541.  
  4542. #ifdef BSD44ORPOSIX            /* For POSIX like this */
  4543.     debug(F100,"ttres BSD44ORPOSIX","",0);
  4544.     x = tcsetattr(ttyfd,TCSADRAIN,&ttold);
  4545. #else                    /* For all others... */
  4546. #ifdef ATTSV                            /* For AT&T versions... */
  4547.     debug(F100,"ttres ATTSV","",0);
  4548.     x = ioctl(ttyfd,TCSETAW,&ttold);    /* Restore tty modes this way. */
  4549. #else
  4550. /* Here we restore the modes for BSD */
  4551.  
  4552. #ifdef LPASS8                /* Undo "pass8" if it were done */
  4553.     if (lmodef) {
  4554.     if (ioctl(ttyfd,TIOCLSET,&lmode) < 0)
  4555.       debug(F100,"ttres TIOCLSET failed","",0);
  4556.     else
  4557.       debug(F100,"ttres TIOCLSET ok","",0);
  4558.     }
  4559. #endif /* LPASS8 */
  4560.  
  4561. #ifdef CK_DTRCTS           /* Undo hardware flow if it were done */
  4562.     if (lmodef) {
  4563.      if (ioctl(ttyfd,TIOCLSET,&lmode) < 0)
  4564.        debug(F100,"ttres TIOCLSET failed","",0);
  4565.      else
  4566.        debug(F100,"ttres TIOCLSET ok","",0);
  4567.     }
  4568. #endif /* CK_DTRCTS */
  4569.  
  4570. #ifdef TIOCGETC                /* Put back special characters */
  4571.     if (tcharf && (xlocal == 0)) {
  4572.     if (ioctl(ttyfd,TIOCSETC,&tchold) < 0)
  4573.       debug(F100,"ttres TIOCSETC failed","",0);
  4574.     else
  4575.       debug(F100,"ttres TIOCSETC ok","",0);
  4576.     }
  4577. #endif /* TIOCGETC */
  4578.  
  4579. #ifdef TIOCGLTC                /* Put back local special characters */
  4580.     if (ltcharf && (xlocal == 0)) {
  4581.     if (ioctl(ttyfd,TIOCSLTC,<chold) < 0)
  4582.       debug(F100,"ttres TIOCSLTC failed","",0);
  4583.     else
  4584.       debug(F100,"ttres TIOCSLTC ok","",0);
  4585.     }
  4586. #endif /* TIOCGLTC */
  4587.  
  4588. #ifdef BELLV10
  4589.     debug(F100,"ttres BELLV10","",0);
  4590.     x = ioctl(ttyfd,TIOCSETP,&ttold);    /* Restore both structs */
  4591.     x = ioctl(ttyfd,TIOCSDEV,&tdold);
  4592. #else
  4593.     debug(F100,"ttres stty","",0);
  4594.     x = stty(ttyfd,&ttold);             /* Restore tty modes the old way. */
  4595. #endif /* BELLV10 */
  4596.  
  4597.     if (!xlocal)
  4598.       msleep(100);            /* This replaces sleep(1)... */
  4599.                     /* Put back sleep(1) if tty is */
  4600.                     /* messed up after close. */
  4601. #endif /* ATTSV */
  4602. #endif /* BSD44ORPOSIX */
  4603.  
  4604.     debug(F101,"ttres result","",x);
  4605. #ifndef QNX
  4606.     if (x < 0) debug(F101,"ttres errno","",errno);
  4607. #endif /* QNX */
  4608.  
  4609. #ifdef AIXRS
  4610. #ifndef AIX41
  4611.     x = ioctl(ttyfd, ttld & 1 ? TXADDCD : TXDELCD, "rts");
  4612.     debug(F101,"ttres AIX line discipline rts restore","",x);
  4613. #endif /* AIX41 */
  4614. #endif /* AIXRS */
  4615.  
  4616. #ifdef BSD41
  4617.     if (ttld > -1) {            /* Put back line discipline */
  4618.     x = ioctl(ttyfd, TIOCSETD, &ttld);
  4619.     debug(F101,"ttres BSD41 line discipline restore","",x);
  4620.     if (x < 0) debug(F101,"...ioctl errno","",errno);
  4621.     ttld = -1;
  4622.     }
  4623. #endif /* BSD41 */
  4624.  
  4625. #ifdef sony_news
  4626.     x = xlocal ? km_ext : km_con;    /* Restore Kanji mode. */
  4627.     if (x != -1) {            /* Make sure we know original modes. */
  4628.     if (ioctl(ttyfd,TIOCKSET, &x) < 0) {
  4629.         perror("ttres can't set Kanji mode");
  4630.         debug(F101,"ttres error setting Kanji mode","",x);
  4631.         return(-1);
  4632.     }
  4633.     }
  4634.     debug(F100,"ttres set Kanji mode ok","",0);
  4635. #endif /* sony_news */
  4636.  
  4637.     tvtflg = 0;                /* Invalidate terminal mode settings */
  4638.     debug(F101,"ttres return code","",x);
  4639.     return(x);
  4640. }
  4641.  
  4642. #ifndef NOUUCP
  4643.  
  4644. /*  T T C H K P I D  --  Check lockfile pid  */
  4645. /*
  4646.   Read pid from lockfile named f, check that it's still valid.
  4647.   If so, return 1.
  4648.   On failure to read pid, return 1.
  4649.   Otherwise, try to delete lockfile f and return 0 if successful, else 1.
  4650. */
  4651. static int
  4652. ttchkpid(f) char *f; {
  4653.     int pid, mypid, x;
  4654.     pid = ttrpid(f);            /* Read pid from file. */
  4655.     if (pid > -1) {            /* If we were able to read the pid.. */
  4656.     debug(F101,"ttchkpid lock pid","",pid);
  4657.     errno = 0;            /* See if process still exists. */
  4658.     mypid = (int)getpid();        /* Get my own pid. */
  4659.     debug(F101,"ttchkpid my pid","",mypid);
  4660.     if (pid == mypid) {        /* It's me! */
  4661.         x = -1;            /* So I can delete it */
  4662.         errno = ESRCH;        /* pretend it's invalid */
  4663.     } else {            /* It's not me */
  4664.         x = kill((PID_T)pid, 0);    /* See if it's a live process */
  4665.         debug(F101,"ttchkpid kill errno","",errno);
  4666.     }
  4667.     debug(F101,"ttchkpid pid test","",x);
  4668.     if (x < 0 && errno == ESRCH) { /* pid is invalid */
  4669.         debug(F111,"removing stale lock",f,pid);
  4670.         if (!backgrd)
  4671.           printf("Removing stale lock %s (pid %d terminated)\n", f, pid);
  4672.         priv_on();
  4673.         x = unlink(f);        /* Remove the lockfile. */
  4674.         priv_off();
  4675.         debug(F111,"ttchkpid unlink",f,x);
  4676.         if (x > -1)
  4677.           return(0);        /* Device is not locked after all */
  4678.         else if (!backgrd)
  4679.           perror(f);
  4680.     }
  4681.     return(1);
  4682.     }
  4683.     return(1);                /* Failure to read pid */
  4684. }
  4685.  
  4686. #ifdef HPUX
  4687.  
  4688. /* Aliases (different drivers) for HP-UX dialout devices: */
  4689.  
  4690. static char *devprefix[] = { "tty", "ttyd", "cul", "cua", "cuad", "culd", "" };
  4691. static int ttydexists = 0;
  4692.  
  4693. #endif /* HPUX */
  4694.  
  4695. /*  T T R P I D  --  Read pid from lockfile "name" */
  4696.  
  4697. static int
  4698. ttrpid(name) char *name; {
  4699.     long len;
  4700.     int x, fd, pid;
  4701.     short spid;
  4702.     char buf[32];
  4703.  
  4704.     debug(F110,"ttrpid",name,0);
  4705.     if (!name) return(-1);
  4706.     if (!*name) return(-1);
  4707.     priv_on();
  4708.     len = zchki(name);            /* Get file length */
  4709.     priv_off();
  4710.     debug(F101,"ttrpid zchki","",len);
  4711.     if (len < 0)
  4712.       return(-1);
  4713.     if (len > 31)
  4714.       return(-1);
  4715.     priv_on();
  4716.     fd = open(name,O_RDONLY);        /* Try to open lockfile. */
  4717.     priv_off();
  4718.     debug(F101,"ttrpid fd","",fd);
  4719.     if (fd <= 0)
  4720.       return(-1);
  4721. /*
  4722.   Here we try to be flexible and allow for all different binary and string
  4723.   formats at runtime, rather than a specific format for each configuration
  4724.   hardwired at compile time.
  4725. */
  4726.     pid = -1;
  4727. #ifndef COHERENT
  4728. /*
  4729.   COHERENT uses a string PID but without leading spaces or 0's, so there is
  4730.   no way to tell from the file's length whether it contains a string or binary
  4731.   pid.  So for COHERENT only, we only allow string pids.  For all others, we
  4732.   decide based on the size of the lockfile.
  4733. */
  4734.     if (len > 4) {            /* If file > 4 bytes it's a string */
  4735. #endif /* COHERENT */
  4736.     x = read(fd,buf,(int)len);
  4737.     debug(F111,"ttrpid string read",buf,x);
  4738.     if (x < 0) {
  4739.         pid = -1;
  4740.     } else {
  4741.         buf[31] = '\0';
  4742.         x = sscanf(buf,"%d",&pid);    /* Get the integer pid from it. */
  4743.     }
  4744. #ifndef COHERENT
  4745.     } else if (len == 4) {        /* 4 bytes so binary */
  4746.     x = read(fd, (char *)&pid, 4);    /* Read the bytes into an int */
  4747.     debug(F101,"ttrpid integer read","",x);
  4748.     if (x < 4)
  4749.       pid = -1;
  4750.     } else if (len == 2) {        /* 2 bytes binary */
  4751.     x = read(fd, (char *)&spid, 2);    /* Read the bytes into a short */
  4752.     debug(F101,"ttrpid short read","",x);
  4753.     if (x < 2)
  4754.       pid = -1;
  4755.     else
  4756.       pid = spid;
  4757.     } else
  4758.       pid = -1;
  4759. #endif /* COHERENT */
  4760.     close(fd);                /* Close the lockfile */
  4761.     debug(F101,"ttrpid pid","",pid);
  4762.     return(pid);
  4763. }
  4764. #endif /* NOUUCP */
  4765.  
  4766. /*  T T L O C K  */
  4767.  
  4768. /*
  4769.   This function attempts to coordinate use of the communication device with
  4770.   other copies of Kermit and any other program that follows the UUCP
  4771.   device-locking conventions, which, unfortunately, vary among different UNIX
  4772.   implementations.  The idea is to look for a file of a certain name, the
  4773.   "lockfile", in a certain directory.  If such a file is found, then the line
  4774.   is presumed to be in use, and Kermit should not use it.  If no such file is
  4775.   found, Kermit attempts to create one so that other programs will not use the
  4776.   same line at the same time.  Because the lockfile and/or the directory it's
  4777.   in might lack write permission for the person running Kermit, Kermit could
  4778.   find itself running setuid to uucp or other user that does have the
  4779.   necessary permissions.  At startup, Kermit has changed its effective uid to
  4780.   the user's real uid, and so ttlock() must switch back to the original
  4781.   effective uid in order to create the lockfile, and then back again to the
  4782.   real uid to prevent unauthorized access to other directories or files owned
  4783.   by the user the program is setuid to.
  4784.  
  4785.   Totally rewritten for C-Kermit 5A to eliminate windows of vulnerability,
  4786.   based on suggestions from Warren Tucker.  Call with pointer to name of
  4787.   tty device.  Returns:
  4788.  
  4789.    0 on success
  4790.   -1 on failure
  4791.  
  4792.   Note: Once privileges are turned on using priv_on(), it is essential that
  4793.   they are turned off again before this function returns.
  4794. */
  4795. #ifdef SVR4                /* Lockfile uses device numbers. */
  4796. /*
  4797.   Although I can't find this in writing anywhere (e.g. in SVID for SVR4),
  4798.   it is the behavior of the "reference version" of SVR4, i.e. the Intel
  4799.   port from UNIX Systems Laboratories, then called Univel UnixWare,
  4800.   then called Novell UnixWare, then called SCO Unixware, then called Caldera
  4801.   Open UNIX...  It also makes much more sense than device-name-based lockfiles
  4802.   since there can be multiple names for the same device, symlinks, etc.
  4803. */
  4804. #ifndef NOLFDEVNO
  4805. #ifndef LFDEVNO                /* Define this for SVR4 */
  4806. #ifndef AIXRS                /* But not for RS/6000 AIX 3.2, etc. */
  4807. #ifndef BSD44                /* If anybody else needs it... */
  4808. #ifndef __386BSD__
  4809. #ifndef __FreeBSD__
  4810. #ifndef HPUX10
  4811. #ifndef IRIX51                /* SGI IRIX 5.1 or later */
  4812. #ifndef CK_SCOV5            /* SCO Open Server 5.0 */
  4813. #define LFDEVNO
  4814. #endif /* CK_SCOV5 */
  4815. #endif /* IRIX51 */
  4816. #endif /* HPUX10 */
  4817. #endif /* __FreeBSD__ */
  4818. #endif /* __386BSD__ */
  4819. #endif /* BSD44 */
  4820. #endif /* AIXRS */
  4821. #endif /* LFDEVNO */            /* ... define it here or on CC */
  4822. #endif /* NOLFDEVNO */
  4823. #endif /* SVR4 */            /* command line. */
  4824.  
  4825. #ifdef COHERENT
  4826. #define LFDEVNO
  4827. #endif /* COHERENT */
  4828.  
  4829. /*
  4830.   For platforms where the lockfile name is made from device/major/minor
  4831.   device number, as in SVR4.  Which, if we must have lockfiles at all, is
  4832.   by far the best format, since it eliminates all the confusion that stems
  4833.   from multiple names (or drivers) for the same port, not to mention
  4834.   symlinks.  It might even be a good idea to start using this form even
  4835.   on platforms where it's not supported, alongside the normal forms for those
  4836.   platforms, in order to get people used to it...
  4837. */
  4838. #ifdef LFDEVNO
  4839. #ifndef major                /* If we didn't find it */
  4840. #ifdef SVR4                /* then for Sys V R4 */
  4841. #include <sys/mkdev.h>            /* look here */
  4842. #else                    /* or for SunOS versions */
  4843. #ifdef SUNOS4                /* ... */
  4844. #include <sys/sysmacros.h>        /* look here */
  4845. #else                    /* Otherwise take a chance: */
  4846. #define    major(dev) ( (int) ( ((unsigned)(dev) >> 8) & 0xff))
  4847. #define    minor(dev) ( (int) ( (dev) & 0xff))
  4848. #endif /* SUNOS4 */
  4849. #endif /* SVR4 */
  4850. #endif /* major */
  4851. #endif /* LFDEVNO */
  4852.  
  4853. /* No advisory locks if F_TLOCK and F_ULOCK are not defined at this point */
  4854.  
  4855. #ifdef LOCKF
  4856. #ifndef F_TLOCK
  4857. #undef LOCKF
  4858. #ifndef NOLOCKF
  4859. #define NOLOCKF
  4860. #endif /* NOLOCKF */
  4861. #endif /* F_TLOCK */
  4862. #endif /* LOCKF */
  4863.  
  4864. #ifdef LOCKF
  4865. #ifndef F_ULOCK
  4866. #undef LOCKF
  4867. #ifndef NOLOCKF
  4868. #define NOLOCKF
  4869. #endif /* NOLOCKF */
  4870. #endif /* F_ULOCK */
  4871. #endif /* LOCKF */
  4872.  
  4873. static char linkto[DEVNAMLEN+1];
  4874. static char * linkdev = NULL;
  4875.  
  4876. #ifndef NOUUCP
  4877. #ifdef USETTYLOCK
  4878. #ifdef LOCK_DIR
  4879. char * uucplockdir = LOCK_DIR;
  4880. #else
  4881. char * uucplockdir = "";
  4882. #endif /* LOCK_DIR */
  4883. #else
  4884. #ifdef LOCK_DIR
  4885. char * uucplockdir = LOCK_DIR;
  4886. #else
  4887. char * uucplockdir = "";
  4888. #endif /* LOCK_DIR */
  4889. #endif /* USETTYLOCK */
  4890. #else
  4891. char * uucplockdir = "";
  4892. #endif /* NOUUCP */
  4893.  
  4894. #ifdef QNX                /* Only for QNX4 */
  4895. int                    /* Visible to outside world */
  4896. qnxopencount() {            /* Get QNX device open count */
  4897.     struct _dev_info_entry info;
  4898.     int x;
  4899.  
  4900.     x = -1;                /* Unknown */
  4901.     if (ttyfd > -1) {
  4902.     if (!dev_info(ttyfd, &info)) {
  4903.         debug(F101,"ttlock QNX open_count","",info.open_count);
  4904.         x = info.open_count;
  4905.     }
  4906.     }
  4907.     return(x);
  4908. }
  4909. #endif /* QNX */
  4910.  
  4911. char *
  4912. ttglckdir() {                /* Get Lockfile directory name */
  4913. #ifdef __OpenBSD__
  4914.     return("/var/spool/lock");
  4915. #else /* __OpenBSD__ */
  4916. #ifdef __FreeBSD__
  4917.     return("/var/spool/lock");
  4918. #else  /* __FreeBSD__ */
  4919. #ifdef LOCK_DIR
  4920.     char * s = LOCK_DIR;
  4921. #endif /* LOCK_DIR */
  4922. #ifdef NOUUCP
  4923.     return("");
  4924. #else  /* NOUUCP */
  4925. #ifdef LOCK_DIR
  4926.     return(s);
  4927. #else  /* LOCK_DIR */
  4928.     return("");
  4929. #endif /* LOCK_DIR */
  4930. #endif /* NOUUCP */
  4931. #endif /* __FreeBSD__ */
  4932. #endif /* __OpenBSD__ */
  4933. }
  4934.  
  4935. static int
  4936. ttlock(ttdev) char *ttdev; {
  4937.  
  4938.     int x, n;
  4939.     int islink = 0;
  4940.  
  4941. #ifdef NOUUCP
  4942.     debug(F100,"ttlock NOUUCP","",0);
  4943.     ckstrncpy(flfnam,"NOLOCK",FLFNAML);
  4944.     haslock = 1;
  4945.     return(0);
  4946. #else /* !NOUUCP */
  4947.  
  4948. #ifdef USETTYLOCK
  4949.     haslock = 0;                        /* Not locked yet. */
  4950.     *flfnam = '\0';            /* Lockfile name is empty. */
  4951.     if (!strncmp(ttdev,"/dev/",5) && ttdev[5])
  4952.       ckstrncpy(lockname,ttdev+5,DEVNAMLEN);
  4953.     else
  4954.       ckstrncpy(lockname,ttdev,DEVNAMLEN);
  4955. /*
  4956.   This might be overkill, but it's not clear from the man pages whether
  4957.   ttylock() can be called without calling ttylocked() first, since the doc
  4958.   says that ttylocked() removes any stale lockfiles, but it does not say this
  4959.   about ttylock().  Also the docs don't say what ttylocked() returns in the
  4960.   case when it finds and removes a stale lockfile.  So one or both calls to
  4961.   to ttylocked() might be superfluous, but they should do no harm.  Also I'm
  4962.   assuming that we have to do all the same ID swapping, etc, with these
  4963.   routines as we do without them.  Thus the priv_on/off() sandwich.
  4964. */
  4965. #ifdef USE_UU_LOCK
  4966.     priv_on();                /* Turn on privs */
  4967.     x = uu_lock(lockname);        /* Try to set the lock */
  4968.     priv_off();                /* Turn privs off */
  4969.     debug(F111,"ttlock uu_lock",lockname,x);
  4970.     switch (x) {
  4971.       case UU_LOCK_INUSE:
  4972.     return(-2);
  4973.       case UU_LOCK_OK:
  4974. #ifdef BSD44
  4975.     ckmakmsg(flfnam,FLFNAML,"/var/spool/lock/LCK..",lockname,NULL,NULL);
  4976. #endif /* BSD44 */
  4977.     haslock = 1;
  4978.     return(0);
  4979.       default:
  4980.     return(-1);
  4981.     }
  4982. #else  /* USE_UU_LOCK */
  4983.     priv_on();                /* Turn on privs */
  4984.     if (ttylocked(lockname)) {        /* This should remove any stale lock */
  4985.     if (ttylocked(lockname)) {    /* so check again. */
  4986.         priv_off();
  4987.         return(-5);            /* Still locked, fail. */
  4988.     }
  4989.     }
  4990.     x = ttylock(lockname);        /* Lock it. */
  4991.     priv_off();                /* Turn off privs */
  4992.  
  4993.     debug(F111,"ttlock lockname",lockname,x);
  4994.     if (x > -1) {
  4995.     /*
  4996.       We don't really know the name of the lockfile, but
  4997.       this is what the man page says it is.  In USETTYLOCK
  4998.           builds, it is used only for display by SHOW COMM.
  4999.     */
  5000.     ckmakmsg(flfnam,FLFNAML,"/etc/locks/LCK..",lockname,NULL,NULL);
  5001.     haslock = 1;
  5002.     }
  5003.     return(x);
  5004. #endif /* USE_UU_LOCK */
  5005. #else  /* Systems that don't have ttylock()... */
  5006.  
  5007. #ifndef HPUX
  5008.  
  5009.     int lockfd;                /* File descriptor for lock file. */
  5010.     PID_T pid;                /* Process id of this process. */
  5011.     int tries;                /* How many times we've tried... */
  5012.     struct stat devbuf;            /* For device numbers (SVR4). */
  5013.  
  5014. #ifdef PIDSTRING
  5015.     char pid_str[32];            /* My pid in string format. */
  5016. #endif /* PIDSTRING */
  5017.  
  5018.     char *device, *devname;
  5019.  
  5020. #define LFNAML 256            /* Max length for lock file name. */
  5021.     char lockfil[LFNAML];        /* Lock file name */
  5022. #ifdef RTAIX
  5023.     char lklockf[LFNAML];        /* Name for link to lock file  */
  5024. #endif /* RTAIX */
  5025. #ifdef CKSYMLINK
  5026.     char symlock[LFNAML];        /* Name for symlink lockfile name */
  5027. #endif /* CKSYMLINK */
  5028.     char tmpnam[LFNAML+30];        /* Temporary lockfile name. */
  5029.     char *lockdir = LOCK_DIR;        /* Defined near top of this file, */
  5030.                     /* or on cc command line. */
  5031.     haslock = 0;                        /* Not locked yet. */
  5032.     *flfnam = '\0';            /* Lockfile name is empty. */
  5033.     lock2[0] = '\0';            /* Clear secondary lockfile name. */
  5034.     pid = getpid();            /* Get id of this process. */
  5035.  
  5036. /*  Construct name of lockfile and temporary file */
  5037.  
  5038. /*  device  = name of tty device without the path, e.g. "ttyh8" */
  5039. /*  lockfil = name of lock file, without path, e.g. "LCK..ttyh8" */
  5040.  
  5041.     device = ((devname = xxlast(ttdev,'/')) != NULL ? devname+1 : ttdev);
  5042.  
  5043.     if (stat(ttdev,&devbuf) < 0)
  5044.       return(-1);
  5045.  
  5046. #ifdef CKSYMLINK
  5047.     islink = 1;                /* Assume it's a symlink */
  5048.     linkto[0] = '\0';            /* But we don't know to what */
  5049. #ifdef COMMENT
  5050. /*
  5051.   This is undependable.  If it worked it would save the readlink call if
  5052.   we knew the device name was not a link.
  5053. */
  5054. #ifdef S_ISLNK
  5055.     islink = S_ISLNK(devbuf.st_mode);
  5056.     debug(F101,"ttlock stat S_ISLNK","",islink);
  5057. #endif /* S_ISLNK */
  5058. #endif /* COMMENT */
  5059.     if (islink) {
  5060.     n = readlink(ttdev,linkto,DEVNAMLEN); /* See if it's a link */
  5061.     debug(F111,"ttlock readlink",ttdev,n);
  5062.     if (n > -1)            /* It is */
  5063.       linkto[n] = '\0';
  5064.     else                /* It's not */
  5065.       islink = 0;
  5066.     debug(F111,"ttlock link",linkto,islink);
  5067.     }
  5068.     if (islink) {
  5069.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  5070.     debug(F110,"ttlock linkdev",linkdev,0);
  5071.     }
  5072. #endif /* CKSYMLINK */
  5073.  
  5074. /*
  5075.   On SCO platforms, if we don't have a symlink, then let's pretend the
  5076.   name given for the device is a symlink, because later we will change
  5077.   the name if it contains any uppercase characters.
  5078. */
  5079. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  5080.     if (!islink) {
  5081.     islink = 1;
  5082.     ckstrncpy(linkto,ttdev,DEVNAMLEN);
  5083.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  5084.     debug(F110,"ttlock linkdev",linkdev,0);
  5085.     }
  5086. #else
  5087. #ifdef M_XENIX                /* SCO Xenix or UNIX */
  5088.     if (!islink) {
  5089.     islink = 1;
  5090.     ckstrncpy(linkto,ttdev,DEVNAMLEN);
  5091.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  5092.     debug(F110,"ttlock linkdev",linkdev,0);
  5093.     }
  5094. #endif /* M_XENIX */
  5095. #endif /* CK_SCOV5 */
  5096.  
  5097. #ifdef ISIII                /* Interactive System III, PC/IX */
  5098.     ckstrncpy(lockfil, device, DEVNAMLEN);
  5099. #else  /* not ISIII */
  5100. #ifdef LFDEVNO                /* Lockfilename has device numbers. */
  5101. #ifdef COHERENT
  5102.     sprintf(lockfil,"LCK..%d.%d",    /* SAFE */
  5103.         major(devbuf.st_rdev),       /* major device number */
  5104.         0x1f & minor(devbuf.st_rdev)); /* minor device number */
  5105. #else
  5106.     /* Note: %d changed to %u in 8.0 -- %u is part of SVID for SVR4 */
  5107.     /* Lockfile name format verified to agree with Solaris cu, Dec 2001 */
  5108.     sprintf(lockfil,"LK.%03u.%03u.%03u", /* SAFE */
  5109.         major(devbuf.st_dev),    /* device */
  5110.         major(devbuf.st_rdev),    /* major device number */
  5111.         minor(devbuf.st_rdev));    /* minor device number */
  5112. #endif /* COHERENT */
  5113. #else  /* Not LFDEVNO */
  5114. #ifdef PTX                /* Dynix PTX */
  5115.     if ((device != &ttdev[5]) && (strncmp(ttdev,"/dev/",5) == 0)) {
  5116.     if ((int)strlen(device) + 8 < LFNAML)
  5117.       sprintf(lockfil,"LCK..%.3s%s", &ttdev[5], device);
  5118.     else
  5119.       ckstrncpy(lockfil,"LOCKFILE_NAME_TOO_LONG",LFNAML);
  5120.     } else
  5121. #endif /* PTX */
  5122.       if ((int)strlen(device) + 5 < LFNAML)
  5123.     sprintf(lockfil,"LCK..%s", device);
  5124.       else
  5125.     ckstrncpy(lockfil,"LOCKFILE_NAME_TOO_LONG",LFNAML);
  5126. #ifdef RTAIX
  5127.     ckstrncpy(lklockf,device,DEVNAMLEN);
  5128. #endif /* RTAIX */
  5129. #ifdef CKSYMLINK
  5130.     symlock[0] = '\0';
  5131.     if (islink)
  5132.       ckmakmsg(symlock,LFNAML, "LCK..", linkdev, NULL, NULL);
  5133. #endif /* CKSYMLINK */
  5134. #endif /* LFDEVNO */
  5135. #endif /* ISIII */
  5136.  
  5137. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  5138.     {
  5139.     /* Lowercase the entire filename. */
  5140.         /* SCO says we must do this in V5.0 and later. */
  5141.     /* BUT... watch out for devices -- like Digiboard Portserver */
  5142.     /* That can have hundreds of ports... */
  5143.     char *p = (char *)(lockfil + 5);
  5144.     while (*p) { if (isupper(*p)) *p = (char) tolower(*p); p++; }
  5145.     }
  5146. #ifdef CKSYMLINK
  5147.     if (islink) {            /* If no change */
  5148.     if (!strcmp(lockfil,symlock)) {    /* then no second lockfile needed */
  5149.         islink = 0;
  5150.         symlock[0] = '\0';
  5151.     }
  5152.     }
  5153. #endif /* CKSYMLINK */
  5154. #else
  5155. #ifdef M_XENIX                /* SCO Xenix or UNIX */
  5156.     {
  5157.     int x; char c;
  5158.     x = (int)strlen(lockfil) - 1;    /* Get last letter of device name. */
  5159.     if (x > 0) {            /* If it's uppercase, lower it. */
  5160.         c = lockfil[x];
  5161.         if (c >= 'A' && c <= 'Z') lockfil[x] += ('a' - 'A');
  5162.     }
  5163.     }
  5164. #ifdef CKSYMLINK
  5165.     if (islink) {
  5166.     if (!strcmp(lockfil,symlock)) {    /* No change */
  5167.         islink = 0;            /* so no second lockfile */
  5168.         symlock[0] = '\0';
  5169.     }
  5170.     }
  5171. #endif /* CKSYMLINK */
  5172. #endif /* M_XENIX */
  5173. #endif /* CK_SCOV5 */
  5174.  
  5175. /*  flfnam = full lockfile pathname, e.g. "/usr/spool/uucp/LCK..ttyh8" */
  5176. /*  tmpnam = temporary unique, e.g. "/usr/spool/uucp/LTMP..pid" */
  5177.  
  5178.     ckmakmsg(flfnam,LFNAML,lockdir,"/",lockfil,NULL);
  5179.  
  5180. #ifdef RTAIX
  5181.     ckmakmsg(lkflfn,FLFNAML,lockdir,"/",lklockf,NULL);
  5182. #endif /* RTAIX */
  5183.  
  5184. #ifndef LFDEVNO
  5185. #ifdef CKSYMLINK
  5186.     /* If it's a link then also make a lockfile for the real name */
  5187.     debug(F111,"ttlock link symlock",symlock,islink);
  5188.     if (islink && symlock[0]) {
  5189.     /* But only if the lockfile names would be different. */
  5190.     /* WARNING: They won't be, e.g. for /dev/ttyd2 => /hw/ttys/ttyd2 */
  5191.     ckmakmsg(lock2,FLFNAML,lockdir,"/",symlock,NULL);
  5192.     debug(F110,"ttlock lock2",lock2,0);
  5193.     if (!strcmp(lock2,flfnam)) {    /* Are lockfile names the same? */
  5194.         debug(F100,"ttlock lock2 cleared","",0);
  5195.         lock2[0] = '\0';        /* Clear secondary lockfile name. */
  5196.     }
  5197.     }
  5198. #endif /* CKSYMLINK */
  5199. #endif /* LFDEVNO */
  5200.  
  5201.     sprintf(tmpnam,"%s/LTMP.%05d",lockdir,(int) pid); /* safe */
  5202.     debug(F110,"ttlock flfnam",flfnam,0);
  5203.     debug(F110,"ttlock tmpnam",tmpnam,0);
  5204.  
  5205.     priv_on();                /* Turn on privileges if possible. */
  5206.     lockfd = creat(tmpnam, 0444);    /* Try to create temp lock file. */
  5207.     if (lockfd < 0) {            /* Create failed. */
  5208.     debug(F111,"ttlock creat failed",tmpnam,errno);
  5209.     if (errno == ENOENT) {
  5210.         perror(lockdir);
  5211.         printf("UUCP not installed or Kermit misconfigured\n");
  5212.     } else {
  5213.         if (!quiet)
  5214.           perror(lockdir);
  5215.         unlink(tmpnam);        /* Get rid of the temporary file. */
  5216.     }
  5217.     priv_off();            /* Turn off privileges!!! */
  5218.     return(-1);            /* Return failure code. */
  5219.     }
  5220. /* Now write the pid into the temp lockfile in the appropriate format */
  5221.  
  5222. #ifdef PIDSTRING            /* For Honey DanBer UUCP, */
  5223.     sprintf(                /* write PID as decimal string */
  5224.         pid_str,
  5225. #ifdef LINUXFSSTND            /* The "Linux File System Standard" */
  5226. #ifdef FSSTND10                /* Version 1.0 calls for */
  5227.         "%010d\n",            /* leading zeros */
  5228. #else                    /* while version 1.2 calls for */
  5229.         "%10d\n",            /* leading spaces */
  5230. #endif /* FSSTND10 */
  5231. #else
  5232. #ifdef COHERENT
  5233.         "%d\n",            /* with leading nothing */
  5234. #else
  5235.         "%10d\n",            /* with leading blanks */
  5236. #endif /* COHERENT */
  5237. #endif /* LINUXFSSTND */
  5238.         (int) pid
  5239.         );                /* safe */
  5240.     write(lockfd, pid_str, 11);
  5241.     debug(F111,"ttlock hdb pid string",pid_str,(int) pid);
  5242.  
  5243. #else /* Not PIDSTRING, use integer PID */
  5244.  
  5245.     write(lockfd, (char *)&pid, sizeof(pid) );
  5246.     debug(F101,"ttlock pid","",(int) pid);
  5247.  
  5248. #endif /* PIDSTRING */
  5249.  
  5250. /* Now try to rename the temp file to the real lock file name. */
  5251. /* This will fail if a lock file of that name already exists.  */
  5252.  
  5253.     close(lockfd);            /* Close the temp lockfile. */
  5254.     chmod(tmpnam,0444);            /* Permission for a valid lock. */
  5255.     tries = 0;
  5256.     while (!haslock && tries++ < 2) {
  5257.     haslock = (link(tmpnam,flfnam) == 0); /* Create a link to it. */
  5258.     if (haslock) {                  /* If we got the lockfile */
  5259. #ifdef RTAIX
  5260.         link(flfnam,lkflfn);
  5261. #endif /* RTAIX */
  5262. #ifdef CKSYMLINK
  5263. #ifndef LFDEVNO
  5264.         if (islink && lock2[0])
  5265.           link(flfnam,lock2);
  5266. #endif /* LFDEVNO */
  5267. #endif /* CKSYMLINK */
  5268.  
  5269. #ifdef COMMENT
  5270. /* Can't do this any more because device is not open yet so no ttyfd. */
  5271. #ifdef LOCKF
  5272. /*
  5273.   Advisory file locking works on SVR4, so we use it.  In fact, it is
  5274.   necessary in some cases, e.g. when SLIP is involved.  But it still doesn't
  5275.   seem to prevent multiple users accessing the same device by different names.
  5276. */
  5277.             while (lockf(ttyfd, F_TLOCK, 0L) != 0) {
  5278.                 debug(F111, "ttlock lockf returns errno", "", errno);
  5279.                 if ((++tries >= 3) || (errno != EAGAIN)) {
  5280.                     x = unlink(flfnam); /* remove the lockfile */
  5281. #ifdef RTAIX
  5282.             unlink(lkflfn);    /* And any links to it... */
  5283. #endif /* RTAIX */
  5284. #ifdef CKSYMLINK
  5285. #ifndef LFDEVNO
  5286.             if (islink && lock2[0])
  5287.               unlink(lock2);    /* ditto... */
  5288. #endif /* LFDEVNO */
  5289. #endif /* CKSYMLINK */
  5290.                     debug(F111,"ttlock unlink",flfnam,x);
  5291.                     haslock = 0;
  5292.             break;
  5293.         }
  5294.                 sleep(2);
  5295.         }
  5296.         if (haslock)        /* If we got an advisory lock */
  5297. #endif /* LOCKF */
  5298. #endif /* COMMENT */
  5299.           break;            /* We're done. */
  5300.  
  5301.     } else {            /* We didn't create a new lockfile. */
  5302.         priv_off();
  5303.         if (ttchkpid(flfnam)) {    /* Check existing lockfile */
  5304.         priv_on();        /* cause ttchkpid turns priv_off... */
  5305.         unlink(tmpnam);        /* Delete the tempfile */
  5306.         debug(F100,"ttlock found tty locked","",0);
  5307.         priv_off();        /* Turn off privs */
  5308.         return(-2);        /* Code for device is in use. */
  5309.         }
  5310.         priv_on();
  5311.     }
  5312.     }
  5313.     unlink(tmpnam);            /* Unlink (remove) the temp file. */
  5314.     priv_off();                /* Turn off privs */
  5315.     return(haslock ? 0 : -1);        /* Return link's return code. */
  5316.  
  5317. #else /* HPUX */
  5318.  
  5319. /*
  5320.   HP-UX gets its own copy of this routine, modeled after the observed behavior
  5321.   of the HP-UX 'cu' program.  HP-UX serial device names consist of a base name
  5322.   such as "tty", "ttyd", "cua", "cul", "cuad", or "culd", followed by a unit
  5323.   designator which is a string of digits, possibly containing an imbedded
  5324.   letter "p".  Examples (for base name "tty"):
  5325.  
  5326.      /dev/tty0, /dev/tty00, dev/ttyd00, /dev/tty0p0
  5327.  
  5328.   According to the HP-UX UUCP manual of 1988, the "0p0" notation has been
  5329.   used on Series 800 since HP-UX 2.00, and the "non-p" notation was used
  5330.   on other models.  In HP-UX 10.00, "0p0" notation was adopted for all models.
  5331.   However, we make and enforce no such distinctions; either notation is
  5332.   accepted on any model or HP-UX version as a valid unit designator.
  5333.  
  5334.   If a valid unit is specified (as opposed to a designer name or symlink), we
  5335.   check for all aliases of the given unit according to the devprefix[] array.
  5336.   If no lockfiles are found for the given unit, we can have the device; we
  5337.   create a lockfile LCK..name in the lockfile directory appropriate for the
  5338.   HP-UX version (/var/spool/locks for 10.00 and later, /usr/spool/uucp for
  5339.   9.xx and earlier).  If it is a "cua" or "cul" device, a second lockfile is
  5340.   created with the "ttyd" prefix.  This is exactly what cu does.
  5341.  
  5342.   If the "set line" device does not have a valid unit designator, then it is
  5343.   used literally and no synomyms are searched for and only one lockfile is
  5344.   created.
  5345.  
  5346.   -fdc, March 1998.
  5347. */
  5348. #define LFNAML 80            /* Max length for lock file name. */
  5349.  
  5350.     int lockfd;                /* File descriptor for lock file. */
  5351.     PID_T pid;                /* Process ID of this process. */
  5352.     int fpid;                /* pid found in existing lockfile. */
  5353.     int tries;                /* How many times we've tried... */
  5354.     int i, k;                /* Workers */
  5355.  
  5356.     char *device, *devname;        /* "/dev/xxx", "xxx" */
  5357.     char *unit, *p;            /* <instance>p<port> part of xxx */
  5358.  
  5359.     char lockfil[LFNAML];        /* Lockfile name (no path) */
  5360.     char tmpnam[LFNAML];        /* Temporary lockfile name. */
  5361.  
  5362. #ifdef HPUX10                /* Lockfile directory */
  5363.     char *lockdir = "/var/spool/locks";    /* Always this for 10.00 and higher */
  5364. #else  /* HP-UX 9.xx and below */
  5365. #ifdef LOCK_DIR
  5366.     char *lockdir = LOCK_DIR;        /* Defined near top of this file */
  5367. #else
  5368.     char *lockdir = "/usr/spool/uucp";    /* or not... */
  5369. #endif /* LOCK_DIR */
  5370. #endif /* HPUX10 */
  5371.  
  5372.     haslock = 0;                        /* Not locked yet. */
  5373.     *flfnam = '\0';            /* Lockfile name is empty. */
  5374.     lock2[0] = '\0';            /* Second one too. */
  5375.     pid = getpid();            /* Get my process ID */
  5376. /*
  5377.   Construct name of lockfile and temporary file...
  5378.   device  = name of tty device without the path, e.g. "tty0p0"
  5379.   lockfil = name of lock file, without path, e.g. "LCK..tty0p0"
  5380. */
  5381.     device = ((devname = xxlast(ttdev,'/')) != NULL ? devname+1 : ttdev);
  5382.     debug(F110,"TTLOCK device",device,0);
  5383.     ckmakmsg(lockfil,LFNAML,"LCK..",device,NULL,NULL);
  5384.  
  5385.     k = 0;                /* Assume device is not locked */
  5386.     n = 0;                /* Digit counter */
  5387.     unit = device;            /* Unit = <instance>p<port> */
  5388.     while (*unit && !isdigit(*unit))    /* Search for digit... */
  5389.       unit++;
  5390.     p = unit;                /* Verify <num>p<num> format... */
  5391.     debug(F110,"TTLOCK unit 1",unit,0);
  5392. /*
  5393.   The unit number is recognized as:
  5394.   (a) any sequence of digits that runs to the end of the string.
  5395.   (b) any (a) that includes one and only one letter "p", with at least
  5396.       one digit before and after it.
  5397. */
  5398.     while (isdigit(*p)) p++, n++;    /* Get a run of digits */
  5399.     if (*p && n > 0) {            /* Have a "p"? */
  5400.     if (*p == 'p' && isdigit(*(p+1))) {
  5401.         p++;
  5402.         n = 0;
  5403.         while (isdigit(*p)) p++, n++;
  5404.     }
  5405.     }
  5406.     if (n == 0 || *p) unit = "";
  5407.     debug(F110,"TTLOCK unit 2",unit,0);
  5408.  
  5409.     if (*unit) {            /* Device name has unit number. */
  5410.     /* The following loop not only searches for the various lockfile    */
  5411.     /* synonyms, but also removes all -- not just one -- stale lockfile */
  5412.     /* for the device, should there be more than one.  See ttchkpid().  */
  5413.     ttydexists = 0;
  5414.     for (i = 0; *devprefix[i]; i++) { /* For each driver... */
  5415.         /* Make device name */
  5416.         ckmakmsg(lock2,FLFNAML,"/dev/",devprefix[i],unit,NULL);
  5417.         priv_on();            /* Privs on */
  5418.         k = zchki(lock2) != -1;    /* See if device exists */
  5419.         priv_off();            /* Privs off */
  5420.         debug(F111,"TTLOCK exist",lock2,k);
  5421.             if (k) {
  5422.         if (!strcmp(devprefix[i],"ttyd")) /* ttyd device exists */
  5423.           ttydexists = 1;
  5424.         /* Make lockfile name */
  5425.         ckmakmsg(lock2,FLFNAML,lockdir,"/LCK..",devprefix[i],unit);
  5426.         debug(F110,"TTLOCK checking",lock2,0);
  5427.         priv_on();        /* Privs on */
  5428.         k = zchki(lock2) != -1;    /* See if lockfile exists */
  5429.         priv_off();        /* Privs off */
  5430.         debug(F111,"TTLOCK check for lock A",lock2,k);
  5431.         if (k) if (ttchkpid(lock2)) { /* If pid still active, fail. */
  5432.             ckstrncpy(flfnam,lock2,FLFNAML);
  5433.             return(-2);
  5434.         }
  5435.         }
  5436.     }
  5437.     } else {                /* Some other device-name format */
  5438.     /* This takes care of symbolic links, etc... */
  5439.     /* But does not chase them down! */
  5440.     ckmakmsg(lock2,FLFNAML,lockdir,"/LCK..",device,NULL);
  5441.     priv_on();
  5442.     k = zchki(lock2) != -1;        /* Check for existing lockfile */
  5443.     priv_off();
  5444.     debug(F111,"TTLOCK check for lock B",lock2,k);
  5445.     if (k) if (ttchkpid(lock2)) {    /* Check pid from lockfile */
  5446.         ckstrncpy(flfnam,lock2,FLFNAML);
  5447.         debug(F110,"TTLOCK in use",device,0);
  5448.         debug(F101,"TTLOCK returns","",-2);
  5449.         return(-2);
  5450.     }
  5451.     }
  5452. /*
  5453.   Get here only if there is no (more) lockfile, so now we make one (or two)...
  5454.   flfnam = full lockfile pathname, e.g. "/usr/spool/uucp/LCK..cul0p0".
  5455.   tmpnam = unique temporary filname, e.g. "/usr/spool/uucp/LTMP..pid".
  5456. */
  5457.     ckmakmsg(flfnam,FLFNAML,lockdir,"/",lockfil,NULL); /* SET LINE device */
  5458.  
  5459.     /* If dialout device, also make one for corresponding dialin device */
  5460.     lock2[0] = '\0';
  5461.     if (!strncmp(device,"cu",2) && *unit && ttydexists)
  5462.       ckmakmsg(lock2,FLFNAML,lockdir,"/LCK..ttyd",unit,NULL);
  5463.  
  5464.     if ((int)strlen(lockdir)+12 < LFNAML)
  5465.       sprintf(tmpnam,"%s/LTMP.%05d",lockdir,(int) pid); /* Make temp name */
  5466. #ifdef DEBUG
  5467.     if (deblog) {
  5468.     debug(F110,"TTLOCK flfnam",flfnam,0);
  5469.     debug(F110,"TTLOCK lock2",lock2,0);
  5470.     debug(F110,"TTLOCK tmpnam",tmpnam,0);
  5471.     }
  5472. #endif /* DEBUG */
  5473. /*
  5474.    Lockfile permissions...
  5475.    444 is standard, HP-UX 10.00 uses 664.  It doesn't matter.
  5476.    Kermit uses 444; the difference lets us tell whether Kermit created
  5477.    the lock file.
  5478. */
  5479.     priv_on();                /* Turn on privileges. */
  5480.     lockfd = creat(tmpnam, 0444);    /* Try to create temporary file. */
  5481.     if (lockfd < 0) {            /* Create failed. */
  5482.     debug(F111,"TTLOCK creat failed",tmpnam,errno);
  5483.     if (errno == ENOENT) {
  5484.         perror(lockdir);
  5485.         printf("UUCP not installed or Kermit misconfigured\n");
  5486.     } else {
  5487.         if (!quiet)
  5488.           perror(lockdir);
  5489.         unlink(tmpnam);        /* Get rid of the temporary file. */
  5490.     }
  5491.     priv_off();            /* Turn off privileges!!! */
  5492.     debug(F101,"TTLOCK returns","",-1);
  5493.     return(-1);            /* Return failure code. */
  5494.     }
  5495.     debug(F110,"TTLOCK temp ok",tmpnam,0);
  5496.  
  5497. /* Now write our pid into the temp lockfile in integer format. */
  5498.  
  5499.     i = write(lockfd, (char *)&pid, sizeof(pid));
  5500.  
  5501. #ifdef DEBUG
  5502.     if (deblog) {
  5503.     debug(F101,"TTLOCK pid","",pid);
  5504.     debug(F101,"TTLOCK sizeof pid","",sizeof(pid));
  5505.     debug(F101,"TTLOCK write pid returns","",i);
  5506.     }
  5507. #endif /* DEBUG */
  5508.  
  5509. /*
  5510.   Now try to rename the temporary file to the real lockfile name.
  5511.   This will fail if a lock file of that name already exists, which
  5512.   will catch race conditions with other users.
  5513. */
  5514.     close(lockfd);            /* Close the temp lockfile. */
  5515.     chmod(tmpnam,0444);
  5516.  
  5517.     tries = 0;
  5518.     while (!haslock && tries++ < 2) {
  5519.     haslock = (link(tmpnam,flfnam) == 0); /* Create a link to it. */
  5520.     debug(F101,"TTLOCK link","",haslock);
  5521.     if (haslock) {            /* If we made the lockfile... */
  5522.  
  5523. #ifdef COMMENT
  5524. /* We can't do this any more because we don't have a file descriptor yet. */
  5525. #ifdef LOCKF                /* Can be canceled with -DNOLOCKF */
  5526. /*
  5527.   Create an advisory lock on the device through its file descriptor.
  5528.   This code actually seems to work.  If it is executed, and then another
  5529.   process tries to open the same device under a different name to circumvent
  5530.   the lockfile, they get a "device busy" error.
  5531. */
  5532.         debug(F100,"TTLOCK LOCKF code...","",0);
  5533.             while ( lockf(ttyfd, F_TLOCK, 0L) != 0 ) {
  5534.                 debug(F111, "TTLOCK lockf error", "", errno);
  5535.                 if ((++tries >= 3) || (errno != EAGAIN)) {
  5536.                     x = unlink(flfnam); /* Remove the lockfile */
  5537.             if (errno == EACCES && !quiet)
  5538.               printf("Device already locked by another process\n");
  5539.                     haslock = 0;
  5540.             break;
  5541.         }
  5542.                 sleep(2);
  5543.         }
  5544. #endif /* LOCKF */
  5545. #endif /* COMMENT */
  5546.  
  5547.         if (haslock) {        /* If we made the lockfile ... */
  5548.         if (lock2[0]) {        /* if there is to be a 2nd lockfile */
  5549.             lockfd = creat(lock2, 0444); /* Create it */
  5550.             debug(F111,"TTLOCK lock2 creat", lock2, lockfd);
  5551.             if (lockfd > -1) {    /* Created OK, write pid. */
  5552.             write(lockfd, (char *)&pid, sizeof(pid) );
  5553.             close(lockfd);    /* Close and */
  5554.             chmod(lock2, 0444); /* set permissions. */
  5555.             } else {         /* Not OK, but don't fail. */
  5556.             lock2[0] = '\0'; /* Just remember it's not there. */
  5557.             }
  5558.         }
  5559.         break;            /* and we're done. */
  5560.         }
  5561.     }
  5562.     }
  5563.     unlink(tmpnam);            /* Unlink (remove) the temp file. */
  5564.     priv_off();                /* Turn off privs */
  5565.     i = haslock ? 0 : -1;        /* Our return value */
  5566.     debug(F101,"TTLOCK returns","",i);
  5567.     return(i);
  5568. #endif /* HPUX */
  5569. #endif /* USETTYLOCK */
  5570. #endif /* !NOUUCP */
  5571. }
  5572.  
  5573. /*  T T U N L O C K  */
  5574.  
  5575. static int
  5576. ttunlck() {                             /* Remove UUCP lockfile(s). */
  5577. #ifndef NOUUCP
  5578.     int x;
  5579.  
  5580.     debug(F111,"ttunlck",flfnam,haslock);
  5581.  
  5582. #ifdef USETTYLOCK
  5583.  
  5584.     if (haslock && *flfnam) {
  5585.     int x;
  5586.     priv_on();            /* Turn on privs */
  5587. #ifdef USE_UU_LOCK
  5588.     x = uu_unlock(lockname);
  5589. #else  /* USE_UU_LOCK */
  5590.     x = ttyunlock(lockname);    /* Try to unlock */
  5591. #endif /* USE_UU_LOCK */
  5592.     priv_off();            /* Turn off privs */
  5593.     if (x < 0 && !quiet)
  5594.       printf("Warning - Can't remove lockfile: %s\n", flfnam);
  5595.  
  5596.     *flfnam = '\0';            /* Erase the name. */
  5597.     haslock = 0;
  5598.     return(0);
  5599.     }
  5600.  
  5601. #else  /* No ttylock()... */
  5602.  
  5603.     if (haslock && *flfnam) {
  5604.     /* Don't remove lockfile if we didn't make it ourselves */
  5605.     if ((x = ttrpid(flfnam)) != (int)getpid()) {
  5606.         debug(F111,"ttunlck lockfile seized",flfnam,x);
  5607.         printf("Warning - Lockfile %s seized by pid %d\n",
  5608.            flfnam,
  5609.            x
  5610.            );
  5611.         return(0);
  5612.     }
  5613.     priv_on();            /* Turn privileges on.  */
  5614.     errno = 0;
  5615.     x = unlink(flfnam);        /* Remove the lockfile. */
  5616.     debug(F111,"ttunlck unlink",flfnam,x);
  5617.     if (x < 0) {
  5618.         if (errno && !quiet)
  5619.           perror(ttnmsv);
  5620.         printf("Warning - Can't remove lockfile: %s\n", flfnam);
  5621.     }
  5622.     haslock = 0;
  5623.     *flfnam = '\0';            /* Erase the name. */
  5624.  
  5625. #ifdef RTAIX
  5626.     errno = 0;
  5627.     x = unlink(lkflfn);        /* Remove link to lockfile */
  5628.     debug(F111,"ttunlck AIX link unlink",lkflfn,x);
  5629.     if (x < 0) {
  5630.         if (errno && !quiet)
  5631.           perror(ttnmsv);
  5632.         printf("Warning - Can't remove link to lockfile: %s\n", lkflfn);
  5633.     }
  5634.     *lkflfn = '\0';
  5635. #else
  5636.     if (lock2[0]) {            /* If there is a second lockfile, */
  5637.         errno = 0;
  5638.         x = unlink(lock2);        /*  remove it too. */
  5639.         debug(F111,"ttunlck lock2 unlink",lock2,x);
  5640.         if (x < 0) {
  5641.         if (errno && !quiet)
  5642.           perror(ttnmsv);
  5643.         printf("Warning - Can't remove secondary lockfile: %s\n",
  5644.                lock2
  5645.                );
  5646.         }
  5647.         lock2[0] = '\0';        /* Forget its name. */
  5648.     }
  5649. #endif /* RTAIX */
  5650.  
  5651. #ifdef COMMENT
  5652. #ifdef LOCKF
  5653.         (VOID) lockf(ttyfd, F_ULOCK, 0L); /* Remove advisory lock */
  5654. #endif /* LOCKF */
  5655. #endif /* COMMENT */
  5656.  
  5657.     priv_off();            /* Turn privileges off. */
  5658.     }
  5659. #endif /* USETTYLOCK */
  5660. #endif /* !NOUUCP */
  5661.     return(0);
  5662. }
  5663.  
  5664. /*
  5665.   4.3BSD-style UUCP line direction control.
  5666.   (Stan Barber, Rice U, 1980-something...)
  5667. */
  5668. #ifndef NOUUCP
  5669. #ifdef ACUCNTRL
  5670. VOID
  5671. acucntrl(flag,ttname) char *flag, *ttname; {
  5672.     char x[DEVNAMLEN+32], *device, *devname;
  5673.  
  5674.     if (strcmp(ttname,CTTNAM) == 0 || xlocal == 0) /* If not local, */
  5675.       return;                /* just return. */
  5676.     device = ((devname = xxlast(ttname,'/')) != NULL ? devname+1 : ttname);
  5677.     if (strncmp(device,"LCK..",4) == 0) device += 5;
  5678.     ckmakmsg(x,DEVNAMLEN+32,"/usr/lib/uucp/acucntrl ",flag," ",device);
  5679.     debug(F110,"called ",x,0);
  5680.     zsyscmd(x);
  5681. }
  5682. #endif /* ACUCNTRL */
  5683. #endif /* NOUUCP */
  5684.  
  5685. /*
  5686.   T T H F L O W  --  Set or Reset hardware flow control.
  5687.  
  5688.   This is an attempt to collect all hardware-flow-control related code
  5689.   into a single module.  Thanks to Rick Sladkey and John Kohl for lots of
  5690.   help here.  Overview:
  5691.  
  5692.   Hardware flow control is not supported in many UNIX implementions.  Even
  5693.   when it is supported, there is no (ha ha) "standard" for the programming
  5694.   interface.  In general, 4.3BSD and earlier (sometimes), 4.4BSD, System V,
  5695.   SunOS, AIX, etc, have totally different methods.  (And, not strictly
  5696.   relevant here, the programming interface often brings one only to a no-op
  5697.   in the device driver!)
  5698.  
  5699.   Among all these, we have two major types of APIs: those in which hardware
  5700.   flow control is determined by bits in the same termio/termios/sgtty mode
  5701.   word(s) that are used for controlling such items as CBREAK vs RAW mode, and
  5702.   which are also used by the ttvt(), ttpkt(), conbin(), and concb() routines
  5703.   for changing terminal modes.  And those that use entirely different
  5704.   mechanisms.
  5705.  
  5706.   In the first category, it is important that any change in the mode bits be
  5707.   reflected in the relevant termio(s)/sgtty structure, so that subsequent
  5708.   changes to that structure do not wipe out the effects of this routine.  That
  5709.   is why a pointer, attrs, to the appropriate structure is passed as a
  5710.   parameter to this routine.
  5711.  
  5712.   The second category should give us no worries, since any changes to hardware
  5713.   flow control accomplished by this routine should not affect the termio(s)/
  5714.   sgtty structures, and therefore will not be undone by later changes to them.
  5715.  
  5716.   The second argument, status, means to turn on hardware flow control if
  5717.   nonzero, and to turn it off if zero.
  5718.  
  5719.   Returns: 0 on apparent success, -1 on probable failure.
  5720. */
  5721.  
  5722. /*
  5723.   The following business is for BSDI, where it was discovered that two
  5724.   separate bits, CCTS_OFLOW and CRTS_IFLOW, are used in hardware flow control,
  5725.   but CTRSCTS is defined (in <termios.h>) to be just CCTS_OFLOW rather both
  5726.   bits, so hwfc only works in one direction if you use CRTSCTS to control it.
  5727.   Other 4.4BSD-based Unixes such as FreeBSD 4.1, which use these two bits,
  5728.   define CRTSCTS correctly.
  5729. */
  5730. #ifdef FIXCRTSCTS
  5731. #ifdef CRTSCTS
  5732. #ifdef CCTS_OFLOW
  5733. #ifdef CRTS_IFLOW
  5734. #undef CRTSCTS
  5735. #define CRTSCTS (CRTS_IFLOW|CCTS_OFLOW)
  5736. #endif /* CRTS_IFLOW */
  5737. #endif /* CCTS_OFLOW */
  5738. #endif /* CRTSCTS */
  5739. #endif /* FIXCRTSCTS */
  5740.  
  5741. static int
  5742. tthflow(flow, status, attrs)
  5743.     int flow,                /* Type of flow control (ckcdeb.h) */
  5744.     status;                /* Nonzero = turn it on */
  5745.                     /* Zero = turn it off */
  5746. #ifdef BSD44ORPOSIX            /* POSIX or BSD44 */
  5747.     struct termios *attrs;
  5748. #else                    /* System V */
  5749. #ifdef ATTSV
  5750. #ifdef ATT7300
  5751. #ifdef UNIX351M
  5752. /* AT&T UNIX 3.51m can set but not test for hardware flow control */
  5753. #define RTSFLOW CTSCD
  5754. #define CTSFLOW CTSCD
  5755. #endif /* ATT7300 */
  5756. #endif /* UNIX351M */
  5757.     struct termio *attrs;
  5758. #else                    /* BSD, V7, etc */
  5759.     struct sgttyb *attrs;        /* sgtty info... */
  5760. #endif /* ATTSV */
  5761. #endif /* BSD44ORPOSIX */
  5762. /* tthflow */ {
  5763.  
  5764.     int x = 0;                /* tthflow() return code */
  5765.  
  5766. #ifdef Plan9
  5767.     return p9tthflow(flow, status);
  5768. #else
  5769.  
  5770. #ifndef OXOS                /* NOT Olivetti X/OS... */
  5771. /*
  5772.   For SunOS 4.0 and later in the BSD environment ...
  5773.  
  5774.   The declarations are copied and interpreted from the System V header files,
  5775.   so we don't actually have to pull in all the System V junk when building
  5776.   C-Kermit for SunOS in the BSD environment, which would be dangerous because
  5777.   having those symbols defined would cause us to take the wrong paths through
  5778.   the code.  The code in this section is used in both the BSD and Sys V SunOS
  5779.   versions.
  5780. */
  5781. #ifdef SUNOS41
  5782. /*
  5783.   In SunOS 4.1 and later, we use the POSIX calls rather than ioctl calls
  5784.   because GNU CC uses different formats for the _IOxxx macros than regular CC;
  5785.   the POSIX forms work for both.  But the POSIX calls are not available in
  5786.   SunOS 4.0.
  5787. */
  5788. #define CRTSCTS 0x80000000        /* RTS/CTS flow control */
  5789. #define TCSANOW 0            /* Do it now */
  5790.  
  5791.     struct termios {
  5792.     unsigned long c_iflag;        /* Input modes */
  5793.     unsigned long c_oflag;        /* Output modes */
  5794.     unsigned long c_cflag;        /* Control modes */
  5795.     unsigned long c_lflag;        /* Line discipline modes */
  5796.     char c_line;
  5797.     CHAR c_cc[17];
  5798.     };
  5799.     struct termios temp;
  5800.  
  5801. _PROTOTYP( int tcgetattr, (int, struct termios *) );
  5802. _PROTOTYP( int tcsetattr, (int, int, struct termios *) );
  5803. /*
  5804.   When CRTSCTS is set, SunOS won't do output unless both CTS and CD are
  5805.   asserted.  So we don't set CRTSCTS unless CD is up.  This should be OK,
  5806.   since we don't need RTS/CTS during dialing, and after dialing is complete,
  5807.   we should have CD.  If not, we still communicate, but without RTS/CTS.
  5808. */
  5809.     int mflags;                /* Modem signal flags */
  5810.  
  5811. #ifdef NETCMD
  5812.     if (ttpipe) return(0);
  5813. #endif /* NETCMD */
  5814. #ifdef NETPTY
  5815.     if (ttpty) return(0);
  5816. #endif /* NETPTY */
  5817.  
  5818.     debug(F101,"tthflow SUNOS41 entry status","",status);
  5819.     if (!status) {            /* Turn hard flow off */
  5820.     if (tcgetattr(ttyfd, &temp) > -1 && /* Get device attributes */
  5821.         (temp.c_cflag & CRTSCTS)) { /* Check for RTS/CTS */
  5822.         temp.c_cflag &= ~CRTSCTS;    /* It's there, remove it */
  5823.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5824.     }
  5825.     } else {                /* Turn hard flow on */
  5826.     if (ioctl(ttyfd,TIOCMGET,&mflags) > -1 && /* Get modem signals */
  5827.         (mflags & TIOCM_CAR)) {        /* Check for CD */
  5828.         debug(F100,"tthflow SunOS has CD","",0);
  5829.         if (tcgetattr(ttyfd, &temp) > -1 && /* Get device attributes */
  5830.         !(temp.c_cflag & CRTSCTS)) { /* Check for RTS/CTS */
  5831.         temp.c_cflag |= CRTSCTS;    /* Not there, add it */
  5832.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5833.         }
  5834.     } else {
  5835.         x = -1;
  5836.         debug(F100,"tthflow SunOS no CD","",0);
  5837.     }
  5838.     }
  5839. #else
  5840. #ifdef QNX
  5841.     struct termios temp;
  5842. #ifdef NETCMD
  5843.     if (ttpipe) return(0);
  5844. #endif /* NETCMD */
  5845. #ifdef NETPTY
  5846.     if (ttpty) return(0);
  5847. #endif /* NETPTY */
  5848.     debug(F101,"tthflow QNX entry status","",status);
  5849.     if (tcgetattr(ttyfd, &temp) > -1) {    /* Get device attributes */
  5850.     if (!status) {            /* Turn hard flow off */
  5851.         if ((temp.c_cflag & (IHFLOW|OHFLOW)) == (IHFLOW|OHFLOW)) {
  5852.         temp.c_cflag &= ~(IHFLOW|OHFLOW); /* It's there, remove it */
  5853.         attrs->c_cflag &= ~(IHFLOW|OHFLOW);
  5854.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5855.         }
  5856.     } else {            /* Turn hard flow on */
  5857.         if ((temp.c_cflag & (IHFLOW|OHFLOW)) != (IHFLOW|OHFLOW)) {
  5858.         temp.c_cflag |= (IHFLOW|OHFLOW); /* Not there, add it */
  5859.         temp.c_iflag &= ~(IXON|IXOFF);   /* Bye to IXON/IXOFF */
  5860.         ttraw.c_lflag |= IEXTEN;         /* Must be on */
  5861.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5862.         attrs->c_cflag |= (IHFLOW|OHFLOW);
  5863.         attrs->c_iflag &= ~(IXON|IXOFF);
  5864.         }
  5865.     }
  5866.     } else {
  5867.     x = -1;
  5868.     debug(F100, "tthflow QNX getattr fails", "", 0);
  5869.     }
  5870. #else
  5871. #ifdef POSIX_CRTSCTS
  5872. /*
  5873.   POSIX_CRTSCTS is defined in ckcdeb.h or on CC command line.
  5874.   Note: Do not assume CRTSCTS is a one-bit field!
  5875. */
  5876.     struct termios temp;
  5877. #ifdef NETCMD
  5878.     if (ttpipe) return(0);
  5879. #endif /* NETCMD */
  5880. #ifdef NETPTY
  5881.     if (ttpty) return(0);
  5882. #endif /* NETPTY */
  5883.     debug(F101,"tthflow POSIX_CRTSCTS entry status","",status);
  5884.     errno = 0;
  5885.     x = tcgetattr(ttyfd, &temp);
  5886.     debug(F111,"tthflow POSIX_CRTSCTS tcgetattr",ckitoa(x),errno);
  5887.     errno = 0;
  5888.     if (x < 0) {
  5889.     x = -1;
  5890.     } else {
  5891.     if (!status) {            /* Turn hard flow off */
  5892.         if (
  5893. #ifdef COMMENT
  5894.         /* This can fail because of sign extension */
  5895.         /* e.g. in Linux where it's Bit 31 */
  5896.         (temp.c_cflag & CRTSCTS) == CRTSCTS
  5897. #else
  5898.         (temp.c_cflag & CRTSCTS) != 0
  5899. #endif /* COMMENT */
  5900.         ) {
  5901.         temp.c_cflag &= ~CRTSCTS; /* It's there, remove it */
  5902.         attrs->c_cflag &= ~CRTSCTS;
  5903.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5904.         debug(F111,"tthflow POSIX_CRTSCTS OFF tcsetattr",
  5905.               ckitoa(x),errno);
  5906.         }
  5907.     } else {            /* Turn hard flow on */
  5908.         if (
  5909. #ifdef COMMENT
  5910.         /* This can fail because of sign extension */
  5911.         (temp.c_cflag & CRTSCTS) != CRTSCTS
  5912. #else
  5913.         (temp.c_cflag & CRTSCTS) == 0
  5914. #endif /* COMMENT */
  5915.         ) {
  5916.         temp.c_cflag |= CRTSCTS; /* Not there, add it */
  5917.         temp.c_iflag &= ~(IXON|IXOFF|IXANY); /* Bye to IXON/IXOFF */
  5918.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5919.         debug(F111,"tthflow POSIX_CRTSCTS ON tcsetattr",
  5920.               ckitoa(x),errno);
  5921.         attrs->c_cflag |= CRTSCTS;
  5922.         attrs->c_iflag &= ~(IXON|IXOFF|IXANY);
  5923.         }
  5924.     }
  5925.     }
  5926. #else
  5927. #ifdef SUNOS4
  5928. /*
  5929.   SunOS 4.0 (and maybe earlier?).  This code is dangerous because it
  5930.   prevents compilation with GNU gcc, which uses different formats for the
  5931.   _IORxxx macros than regular cc.  SunOS 4.1 and later can use the POSIX
  5932.   routines above, which work for both cc and gcc.
  5933. */
  5934. #define TCGETS _IOR(T, 8, struct termios) /* Get modes into termios struct */
  5935. #define TCSETS _IOW(T, 9, struct termios) /* Set modes from termios struct */
  5936. #define CRTSCTS 0x80000000          /* RTS/CTS flow control */
  5937.  
  5938.     struct termios {
  5939.     unsigned long c_iflag;        /* Input modes */
  5940.     unsigned long c_oflag;        /* Output modes */
  5941.     unsigned long c_cflag;        /* Control modes */
  5942.     unsigned long c_lflag;        /* Line discipline modes */
  5943.     char c_line;
  5944.     CHAR c_cc[17];
  5945.     };
  5946.     struct termios temp;
  5947. #ifdef NETCMD
  5948.     if (ttpipe) return(0);
  5949. #endif /* NETCMD */
  5950. #ifdef NETPTY
  5951.     if (ttpty) return(0);
  5952. #endif /* NETPTY */
  5953.     debug(F101,"tthflow entry status","",status);
  5954.     if (ioctl(ttyfd,TCGETS,&temp) > -1) { /* Get terminal modes. */
  5955.     if (status) {            /* Turn hard flow on */
  5956.         temp.c_cflag |= CRTSCTS;    /* Add RTS/CTS to them. */
  5957.         x = ioctl(ttyfd,TCSETS,&temp); /* Set them again. */
  5958.         attrs->c_cflag |= CRTSCTS;    /* Add to global info. */
  5959.     } else {            /* Turn hard flow off */
  5960.         temp.c_cflag &= ~CRTSCTS;
  5961.         x = ioctl(ttyfd,TCSETS,&temp);
  5962.         attrs->c_cflag &= ~CRTSCTS;
  5963.     }
  5964.     }
  5965. #else                    /* Not SunOS 4.0 or later */
  5966. #ifdef AIXRS                /* IBM AIX RS/6000 */
  5967. #ifndef AIX41                /* But only pre-4.x == SVR4 */
  5968. #ifdef NETCMD
  5969.     if (ttpipe) return(0);
  5970. #endif /* NETCMD */
  5971. #ifdef NETPTY
  5972.     if (ttpty) return(0);
  5973. #endif /* NETPTY */
  5974.     if (status) {
  5975.     if ((x = ioctl(ttyfd, TXADDCD, "rts")) < 0 && errno != EBUSY)
  5976.       debug(F100,"hardflow TXADDCD (rts) error", "", 0);
  5977.     } else {
  5978.     if ((x = ioctl(ttyfd, TXDELCD, "rts")) < 0 && errno != EINVAL)
  5979.       debug(F100,"hardflow TXDELCD (rts) error", "", 0);
  5980.     }
  5981. #endif /* AIX41 */
  5982. #else                    /* Not AIX RS/6000 */
  5983.  
  5984. #ifdef ATTSV                /* System V... */
  5985.  
  5986. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  5987. #define CK_SCOUNIX
  5988. #else
  5989. #ifdef M_UNIX                /* SCO UNIX 3.2v4.x or earlier */
  5990. #define CK_SCOUNIX
  5991. #endif /* M_UNIX */
  5992. #endif /* CK_SCOV5 */
  5993.  
  5994. #ifdef SCO_FORCE_RTSXOFF
  5995. #ifdef CK_SCOUNIX            /* But not SCO OpenServer 5.0.4 */
  5996. #ifdef SCO_OSR504            /* or later... */
  5997. #undef CK_SCOUNIX
  5998. #endif /* SCO_OSR504 */
  5999. #endif /* CK_SCOUNIX */
  6000. #endif /* SCO_FORCE_RTSXOFF */
  6001.  
  6002. #ifdef CK_SCOUNIX
  6003. #ifdef POSIX
  6004.     struct termios temp;
  6005. #ifdef NETCMD
  6006.     if (ttpipe) return(0);
  6007. #endif /* NETCMD */
  6008. #ifdef NETPTY
  6009.     if (ttpty) return(0);
  6010. #endif /* NETPTY */
  6011.     debug(F101,"tthflow SCOUNIX POSIX entry status","",status);
  6012.     errno = 0;
  6013.     x = tcgetattr(ttyfd, &temp);
  6014.     debug(F111,"tthflow SCO UNIX POSIX tcgetattr",ckitoa(x),errno);
  6015. #else /* POSIX */
  6016.     struct termio temp;
  6017. #ifdef NETCMD
  6018.     if (ttpipe) return(0);
  6019. #endif /* NETCMD */
  6020. #ifdef NETPTY
  6021.     if (ttpty) return(0);
  6022. #endif /* NETPTY */
  6023.     debug(F101,"tthflow SCOUNIX non-POSIX entry status","",status);
  6024.     x = ioctl(ttyfd, TCGETA, &temp);
  6025.     debug(F111,"tthflow SCO UNIX non-POSIX TCGETA",ckitoa(x),errno);
  6026. #endif /* POSIX */
  6027. /*
  6028.   This is not really POSIX, since POSIX does not deal with hardware flow
  6029.   control, but we are using the POSIX APIs.  In fact, RTSFLOW and CTSFLOW
  6030.   are defined in termio.h, but within #ifndef _POSIX_SOURCE..#endif.  So
  6031.   let's try forcing their definitions here.
  6032. */
  6033. #ifndef CTSFLOW
  6034. #define CTSFLOW 0020000
  6035.     debug(F101,"tthflow SCO defining CTSFLOW","",CTSFLOW);
  6036. #else
  6037.     debug(F101,"tthflow SCO CTSFLOW","",CTSFLOW);
  6038. #endif /* CTSFLOW */
  6039. #ifndef RTSFLOW
  6040. #define RTSFLOW 0040000
  6041.     debug(F101,"tthflow SCO defining RTSFLOW","",RTSFLOW);
  6042. #else
  6043.     debug(F101,"tthflow SCO RTSFLOW","",RTSFLOW);
  6044. #endif /* RTSFLOW */
  6045. #ifndef ORTSFL
  6046. #define ORTSFL 0100000
  6047.     debug(F101,"tthflow SCO defining ORTSFL","",ORTSFL);
  6048. #else
  6049.     debug(F101,"tthflow SCO ORTSFL","",ORTSFL);
  6050. #endif /* ORTSFL */
  6051.  
  6052.     if (x != -1) {
  6053.     if (status) {            /* Turn it ON */
  6054.         temp.c_cflag |= RTSFLOW|CTSFLOW;
  6055.         attrs->c_cflag |= RTSFLOW|CTSFLOW;
  6056. #ifdef ORTSFL
  6057.         temp.c_cflag &= ~ORTSFL;
  6058.         attrs->c_cflag &= ~ORTSFL;
  6059. #endif /* ORTSFL */
  6060.         temp.c_iflag &= ~(IXON|IXOFF|IXANY);
  6061.         attrs->c_iflag &= ~(IXON|IXOFF|IXANY);
  6062.     } else {            /* Turn it OFF */
  6063. #ifdef ORTSFL
  6064.         temp.c_cflag &= ~(RTSFLOW|CTSFLOW|ORTSFL);
  6065.         attrs->c_cflag &= ~(RTSFLOW|CTSFLOW|ORTSFL);
  6066. #else  /* ORTSFL */
  6067.         temp.c_cflag &= ~(RTSFLOW|CTSFLOW);
  6068.         attrs->c_cflag &= ~(RTSFLOW|CTSFLOW);
  6069. #endif /* ORTSFL */
  6070.     }
  6071. #ifdef POSIX
  6072.     x = tcsetattr(ttyfd, TCSADRAIN, &temp);
  6073. #else
  6074.     x = ioctl(ttyfd, TCSETA, &temp);
  6075. #endif /* POSIX */
  6076.     debug(F101,"tthflow SCO set modes","",x);
  6077.     }
  6078. #else /* Not SCO UNIX */
  6079. #ifdef NETCMD
  6080.     if (ttpipe) return(0);
  6081. #endif /* NETCMD */
  6082. #ifdef NETPTY
  6083.     if (ttpty) return(0);
  6084. #endif /* NETPTY */
  6085.     if (!status) {            /* Turn it OFF */
  6086. #ifdef RTSXOFF
  6087.     debug(F100,"tthflow ATTSV RTS/CTS OFF","",0);
  6088.     rctsx.x_hflag &= ~(RTSXOFF|CTSXON);
  6089. #ifdef TCSETX
  6090.     x = ioctl(ttyfd,TCSETX,&rctsx);
  6091.     debug(F101,"tthflow ATTSV TCSETX OFF","",x);
  6092. #else
  6093.     x = -1
  6094.     debug(F100,"tthflow TCSETX not defined","",0);
  6095. #endif /* TCSETX */
  6096. #else
  6097.     debug(F100,"tthflow ATTSV RTSXOFF not defined","",0);
  6098. #endif /* RTSXOFF */
  6099. #ifdef DTRXOFF
  6100.     debug(F100,"tthflow ATTSV DTR/CD OFF","",0);
  6101.     rctsx.x_hflag &= ~(DTRXOFF|CDXON);
  6102.     x = ioctl(ttyfd,TCSETX,&rctsx);
  6103.     debug(F101,"tthflow ATTSV DTRXOFF OFF","",x);
  6104. #else
  6105.     debug(F100,"tthflow ATTSV DTRXOFF not defined","",0);
  6106. #endif /* DTRXOFF */
  6107.     } else {                /* Turn it ON. */
  6108.     if (flow == FLO_RTSC) {    /* RTS/CTS Flow control... */
  6109.         debug(F100,"tthflow ATTSV RTS/CTS ON","",0);
  6110. #ifdef RTSXOFF
  6111.         /* This is the preferred way, according to SVID3 */
  6112. #ifdef TCGETX
  6113.         x = ioctl(ttyfd,TCGETX,&rctsx);
  6114.         debug(F101,"tthflow TCGETX","",x);
  6115.         if (x > -1) {
  6116.         rctsx.x_hflag |= RTSXOFF | CTSXON;
  6117.         x = ioctl(ttyfd,TCSETX,&rctsx);
  6118.         debug(F100,"tthflow ATTSV ioctl","",x);
  6119.         }
  6120. #else
  6121.         debug(F100,"tthflow TCGETX not defined","",0);
  6122.         x = -1
  6123. #endif /* TCGETX */
  6124. #else
  6125.         debug(F100,"tthflow RTSXOFF not defined","",0);
  6126.         x = -1;
  6127. #endif /* RTSXOFF */
  6128.     } else if (flow == FLO_DTRC) {    /* DTR/CD Flow control... */
  6129.         debug(F100,"tthflow ATTSV DTR/CD ON","",0);
  6130. #ifdef DTRXOFF
  6131.         /* This is straight out of SVID R4 */
  6132.         if (ioctl(ttyfd,TCGETX,&rctsx) > -1) {
  6133.         rctsx.x_hflag &= ~(DTRXOFF|CDXON);
  6134.         x = ioctl(ttyfd,TCSETX,&rctsx);
  6135.         }
  6136. #else
  6137.         debug(F100,"tthflow ATTSV DTRXOFF not defined","",0);
  6138.         x = -1;
  6139. #endif /* DTRXOFF */
  6140.     }
  6141.     }
  6142. #endif /* CK_SCOUNIX */
  6143.  
  6144. #else /* not System V... */
  6145.  
  6146. #ifdef CK_DTRCTS
  6147. #ifdef LDODTR
  6148. #ifdef LDOCTS
  6149. #ifdef NETCMD
  6150.     if (ttpipe) return(0);
  6151. #endif /* NETCMD */
  6152. #ifdef NETPTY
  6153.     if (ttpty) return(0);
  6154. #endif /* NETPTY */
  6155.     x = LDODTR | LDOCTS;        /* Found only on UTEK? */
  6156.     if (flow == FLO_DTRT && status) {    /* Use hardware flow control */
  6157.     if (lmodef) {
  6158.         x = ioctl(ttyfd,TIOCLBIS,&x);
  6159.         if (x < 0) {
  6160.             debug(F100,"hardflow TIOCLBIS error","",0);
  6161.         } else {
  6162.         lmodef++;
  6163.         debug(F100,"hardflow TIOCLBIS ok","",0);
  6164.         }
  6165.     }
  6166.     } else {
  6167.     if (lmodef) {
  6168.         x = ioctl(ttyfd,TIOCLBIC,&x);
  6169.         if (x < 0) {
  6170.             debug(F100,"hardflow TIOCLBIC error","",0);
  6171.         } else {
  6172.         lmodef++;
  6173.         debug(F100,"hardflow TIOCLBIC ok","",0);
  6174.         }
  6175.     }
  6176.     }
  6177. #endif /* LDODTR */
  6178. #endif /* LDOCTS */
  6179. #endif /* CK_DTRCTS */
  6180. #endif /* ATTSV */
  6181. #endif /* AIXRS */
  6182. #endif /* SUNOS4 */
  6183. #endif /* QNX */
  6184. #endif /* POSIX_CRTSCTS */
  6185. #endif /* SUNOS41 */
  6186.  
  6187. #else /* OXOS */
  6188.  
  6189.     struct termios temp;        /* Olivetti X/OS ... */
  6190.  
  6191. #ifdef NETCMD
  6192.     if (ttpipe) return(0);
  6193. #endif /* NETCMD */
  6194. #ifdef NETPTY
  6195.     if (ttpty) return(0);
  6196. #endif /* NETPTY */
  6197.     x = ioctl(ttyfd,TCGETS,&temp);
  6198.     if (x == 0) {
  6199.     temp.c_cflag &= ~(CRTSCTS|CDTRCTS|CBRKFLOW|CDTRDSR|CRTSDSR);
  6200.     if (status) {
  6201.         switch (flow) {
  6202.           case FLO_RTSC: temp.c_cflag |= CRTSCTS; /* RTS/CTS (hard) */
  6203.         break;
  6204.           case FLO_DTRT: temp.c_cflag |= CDTRCTS; /* DTR/CTS (hard) */
  6205.         break;
  6206.         }
  6207.     }
  6208.     x = ioctl(ttyfd,TCSETS,&temp);
  6209.     }
  6210. #endif /* OXOS */
  6211.     return(x);
  6212.  
  6213. #endif /* Plan9 */
  6214. }
  6215.  
  6216. /*  T T P K T  --  Condition the communication line for packets */
  6217. /*                 or for modem dialing */
  6218.  
  6219. /*
  6220.   If called with speed > -1, also set the speed.
  6221.   Returns 0 on success, -1 on failure.
  6222.  
  6223.   NOTE: the "xflow" parameter is supposed to be the currently selected
  6224.   type of flow control, but for historical reasons, this parameter is also
  6225.   used to indicate that we are dialing.  Therefore, when the true flow
  6226.   control setting is needed, we access the external variable "flow", rather
  6227.   than trusting our "xflow" argument.
  6228. */
  6229. int
  6230. #ifdef CK_ANSIC
  6231. ttpkt(long speed, int xflow, int parity)
  6232. #else
  6233. ttpkt(speed,xflow,parity) long speed; int xflow, parity;
  6234. #endif /* CK_ANSIC */
  6235. /* ttpkt */ {
  6236. #ifndef NOLOCAL
  6237.     int s2;
  6238.     int s = -1;
  6239. #endif /* NOLOCAL */
  6240.     int x;
  6241.     extern int flow;            /* REAL flow-control setting */
  6242.  
  6243.     if (ttyfd < 0) return(-1);          /* Not open. */
  6244.  
  6245.     debug(F101,"ttpkt parity","",parity);
  6246.     debug(F101,"ttpkt xflow","",xflow);
  6247.     debug(F101,"ttpkt speed","",(int) speed);
  6248.  
  6249.     ttprty = parity;                    /* Let other tt functions see these. */
  6250.     ttspeed = speed;            /* Make global copy for this module */
  6251.     ttpmsk = ttprty ? 0177 : 0377;    /* Parity stripping mask */
  6252. #ifdef PARSENSE
  6253.     needpchk = ttprty ? 0 : 1;        /* Parity check needed? */
  6254. #else
  6255.     needpchk = 0;
  6256. #endif /* PARSENSE */
  6257.  
  6258.     debug(F101,"ttpkt ttpmsk","",ttpmsk);
  6259.     debug(F101,"ttpkt netconn","",netconn);
  6260.  
  6261. #ifdef NETCONN                /* No mode-changing for telnet */
  6262.     if (netconn) {
  6263. #ifdef TCPSOCKET
  6264. #ifdef TCP_NODELAY
  6265.         if (ttnet == NET_TCPB) {    /* But turn off Nagle */
  6266.             extern int tcp_nodelay;
  6267.             nodelay_sav = tcp_nodelay;
  6268.             no_delay(ttyfd,1);
  6269.         }
  6270. #endif /* TCP_NODELAY */
  6271. #ifdef TN_COMPORT
  6272.         if (istncomport()) {
  6273.             int rc = -1;
  6274.             if (tvtflg == 0 && speed == ttspeed && flow == ttflow
  6275.                  /* && ttcarr == curcarr */ ) {
  6276.                 debug(F100,"ttpkt modes already set, skipping...","",0);
  6277.                 return(0);        /* Already been called. */
  6278.             }
  6279.             if (flow != ttflow) {
  6280.                 if ((rc = tnsetflow(flow)) < 0)
  6281.           return(rc);
  6282.                 ttflow = flow;
  6283.             }
  6284.             if (speed != ttspeed) {
  6285.                 if (speed <= 0) 
  6286.           speed = tnc_get_baud();
  6287.                 else if ((rc = tnc_set_baud(speed)) < 0)
  6288.           return(rc);
  6289.                 ttspeed = speed;
  6290.             }
  6291.             tnc_set_datasize(8);
  6292.         tnc_set_stopsize(stopbits);
  6293.  
  6294. #ifdef HWPARITY
  6295.             if (hwparity) {
  6296.                 switch (hwparity) {
  6297.           case 'e':            /* Even */
  6298.                     debug(F100,"ttres 8 bits + even parity","",0);
  6299.                     tnc_set_parity(3);
  6300.                     break;
  6301.           case 'o':            /* Odd */
  6302.                     debug(F100,"ttres 8 bits + odd parity","",0);
  6303.                     tnc_set_parity(2);
  6304.                     break;
  6305.           case 'm':            /* Mark */
  6306.                     debug(F100,"ttres 8 bits + invalid parity: mark","",0);
  6307.                     tnc_set_parity(4);
  6308.                     break;
  6309.           case 's':            /* Space */
  6310.                     debug(F100,"ttres 8 bits + invalid parity: space","",0);
  6311.                     tnc_set_parity(5);
  6312.                     break;
  6313.                 }
  6314.             } else 
  6315. #endif /* HWPARITY */
  6316.         {
  6317.                 tnc_set_parity(1);              /* None */
  6318.             }
  6319.             tvtflg = 0;
  6320.             return(0);
  6321.         }
  6322. #endif /* TN_COMPORT */
  6323. #endif /* TCPSOCKET */
  6324.         tvtflg = 0;
  6325.         return(0);
  6326.     }
  6327. #endif /* NETCONN */
  6328. #ifdef NETCMD
  6329.     if (ttpipe) return(0);
  6330. #endif /* NETCMD */
  6331. #ifdef NETPTY
  6332.     if (ttpty) return(0);
  6333. #endif /* NETPTY */
  6334.  
  6335. #ifndef Plan9
  6336.     if (ttfdflg && !isatty(ttyfd)) return(0);
  6337. #endif /* Plan9 */
  6338.  
  6339. #ifdef COHERENT
  6340. #define SVORPOSIX
  6341. #endif /* COHERENT */
  6342.  
  6343. #ifndef SVORPOSIX            /* Berkeley, V7, etc. */
  6344. #ifdef LPASS8
  6345. /*
  6346.  For some reason, with BSD terminal drivers, you can't set FLOW to XON/XOFF
  6347.  after having previously set it to NONE without closing and reopening the
  6348.  device.  Unless there's something I overlooked below...
  6349. */
  6350.     if (ttflow == FLO_NONE && flow == FLO_XONX && xlocal == 0) {
  6351.     debug(F101,"ttpkt executing horrible flow kludge","",0);
  6352.     ttclos(0);            /* Close it */
  6353.     x = 0;
  6354.     ttopen(ttnmsv,&x,ttmdm,0);    /* Open it again */
  6355.     }
  6356. #endif /* LPASS8 */
  6357. #endif /* SVORPOSIX */
  6358.  
  6359. #ifdef COHERENT                /* This must be vestigial since we */
  6360. #undef SVORPOSIX            /* reverse it a few lines below... */
  6361. #endif /* COHERENT */
  6362.  
  6363.     if (xflow != FLO_DIAL && xflow != FLO_DIAX)
  6364.       ttflow = xflow;            /* Now make this available too. */
  6365.  
  6366. #ifndef NOLOCAL
  6367.     if (xlocal) {
  6368.     s2 = (int) (speed / 10L);    /* Convert bps to cps */
  6369.     debug(F101,"ttpkt calling ttsspd","",s2);
  6370.     s = ttsspd(s2);            /* Check and set the speed */
  6371.     debug(F101,"ttpkt ttsspd result","",s);
  6372.      carrctl(&ttraw, xflow != FLO_DIAL /* Carrier control */
  6373.         && (ttcarr == CAR_ON || (ttcarr == CAR_AUT && ttmdm != 0)));
  6374.     tvtflg = 0;            /* So ttvt() will work next time */
  6375.     }
  6376. #endif /* NOLOCAL */
  6377.  
  6378. #ifdef COHERENT
  6379. #define SVORPOSIX
  6380. #endif /* COHERENT */
  6381.  
  6382. #ifndef SVORPOSIX            /* BSD section */
  6383.     if (flow == FLO_RTSC ||        /* Hardware flow control */
  6384.     flow == FLO_DTRC ||
  6385.     flow == FLO_DTRT) {
  6386.     tthflow(flow, 1, &ttraw);
  6387.     debug(F100,"ttpkt hard flow, TANDEM off, RAW on","",0);
  6388.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6389.     ttraw.sg_flags |= RAW;        /* Enter raw mode */
  6390.     } else if (flow == FLO_NONE) {    /* No flow control */
  6391.     debug(F100,"ttpkt no flow, TANDEM off, RAW on","",0);
  6392.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6393.     tthflow(flow, 0, &ttraw);    /* Turn off any hardware f/c too */
  6394.     ttraw.sg_flags |= RAW;        /* Enter raw mode */
  6395.     } else if (flow == FLO_KEEP) {    /* Keep device's original setting */
  6396.     debug(F100,"ttpkt keeping original TANDEM","",0);
  6397.     ttraw.sg_flags &= ~TANDEM;
  6398.     ttraw.sg_flags |= (ttold.sg_flags & TANDEM);
  6399.     /* NOTE: We should also handle hardware flow control here! */
  6400.     }
  6401.  
  6402. /* SET FLOW XON/XOFF is in effect, or SET FLOW KEEP resulted in Xon/Xoff */
  6403.  
  6404.     if ((flow == FLO_XONX) || (ttraw.sg_flags & TANDEM)) {
  6405.     debug(F100,"ttpkt turning on TANDEM","",0);
  6406.     ttraw.sg_flags |= TANDEM;    /* So ask for it. */
  6407.  
  6408. #ifdef LPASS8                /* Can pass 8-bit data through? */
  6409. /* If the LPASS8 local mode is available, then flow control can always  */
  6410. /* be used, even if parity is none and we are transferring 8-bit data.  */
  6411. /* But we only need to do all this if Xon/Xoff is requested. */
  6412. /* BUT... this tends not to work through IP or LAT connections, terminal */
  6413. /* servers, telnet, rlogin, etc, so it is currently disabled. */
  6414.     x = LPASS8;            /* If LPASS8 defined, then */
  6415.     debug(F100,"ttpkt executing LPASS8 code","",0);
  6416.     if (lmodef) {            /* TIOCLBIS must be too. */
  6417.         x = ioctl(ttyfd,TIOCLBIS,&x); /* Try to set LPASS8. */
  6418.         if (x < 0) {
  6419.         debug(F100,"ttpkt TIOCLBIS error","",0);
  6420.         } else {
  6421.         lmodef++;
  6422.         debug(F100,"ttpkt TIOCLBIS ok","",0);
  6423.         }
  6424.     }
  6425. /*
  6426.  But if we use LPASS8 mode, we must explicitly turn off
  6427.  terminal interrupts of all kinds.
  6428. */
  6429. #ifdef TIOCGETC                /* Not rawmode, */
  6430.     if (tcharf && (xlocal == 0)) {    /* must turn off */
  6431.         tchnoi.t_intrc = -1;    /* interrupt character */
  6432.         tchnoi.t_quitc = -1;    /* and quit character. */
  6433.         tchnoi.t_startc = 17;    /* Make sure xon */
  6434.         tchnoi.t_stopc = 19;    /* and xoff not ignored. */
  6435. #ifndef NOBRKC
  6436.         tchnoi.t_eofc = -1;        /* eof character. */
  6437.         tchnoi.t_brkc = -1;        /* brk character. */
  6438. #endif /* NOBRKC */
  6439.         if (ioctl(ttyfd,TIOCSETC,&tchnoi) < 0) {
  6440.         debug(F100,"ttpkt TIOCSETC failed","",0);
  6441.         } else {
  6442.         tcharf = 1;
  6443.         debug(F100,"ttpkt TIOCSETC ok","",0);
  6444.         }
  6445. #ifdef COMMENT
  6446. /* only for paranoid debugging */
  6447.         if (tcharf) {
  6448.         struct tchars foo;
  6449.         char tchbuf[100];
  6450.         ioctl(0,TIOCGETC,&foo);
  6451.         sprintf(tchbuf,
  6452.             "intr=%d,quit=%d, start=%d, stop=%d, eof=%d, brk=%d",
  6453.             foo.t_intrc, foo.t_quitc, foo.t_startc,
  6454.             foo.t_stopc, foo.t_eofc,  foo.t_brkc);
  6455.         debug(F110,"ttpkt chars",tchbuf,0);
  6456.         }
  6457. #endif /* COMMENT */
  6458.     }
  6459.     ttraw.sg_flags |= CBREAK;    /* Needed for unknown reason */
  6460. #endif /* TIOCGETC */
  6461.  
  6462. /* Prevent suspend during packet mode */
  6463. #ifdef TIOCGLTC                /* Not rawmode, */
  6464.     if (ltcharf && (xlocal == 0)) {    /* must turn off */
  6465.         ltchnoi.t_suspc = -1;    /* suspend character */
  6466.         ltchnoi.t_dsuspc = -1;    /* and delayed suspend character */
  6467.         if (ioctl(ttyfd,TIOCSLTC,&tchnoi) < 0) {
  6468.         debug(F100,"ttpkt TIOCSLTC failed","",0);
  6469.         } else {
  6470.         ltcharf = 1;
  6471.         debug(F100,"ttpkt TIOCSLTC ok","",0);
  6472.         }
  6473.     }
  6474. #endif /* TIOCGLTC */
  6475.  
  6476. #else /* LPASS8 not defined */
  6477.  
  6478. /* Previously, BSD-based implementations always */
  6479. /* used rawmode for packets.  Now, we use rawmode only if parity is NONE. */
  6480. /* This allows the flow control requested above to actually work, but only */
  6481. /* if the user asks for parity (which also means they get 8th-bit quoting). */
  6482.  
  6483.     if (parity) {            /* If parity, */
  6484.         ttraw.sg_flags &= ~RAW;    /* use cooked mode */
  6485. #ifdef COMMENT
  6486. /* WHY??? */
  6487.         if (xlocal)
  6488. #endif /* COMMENT */
  6489.           ttraw.sg_flags |= CBREAK;
  6490.         debug(F101,"ttpkt cooked, cbreak, parity","",parity);
  6491. #ifdef TIOCGETC                /* Not rawmode, */
  6492.         if (tcharf && (xlocal == 0)) { /* must turn off */
  6493.         tchnoi.t_intrc = -1;    /* interrupt character */
  6494.         tchnoi.t_quitc = -1;    /* and quit character. */
  6495.         tchnoi.t_startc = 17;    /* Make sure xon */
  6496.         tchnoi.t_stopc = 19;    /* and xoff not ignored. */
  6497. #ifndef NOBRKC
  6498.         tchnoi.t_eofc = -1;    /* eof character. */
  6499.         tchnoi.t_brkc = -1;    /* brk character. */
  6500. #endif /* NOBRKC */
  6501.         if (ioctl(ttyfd,TIOCSETC,&tchnoi) < 0) {
  6502.             debug(F100,"ttpkt TIOCSETC failed","",0);
  6503.         } else {
  6504.             tcharf = 1;
  6505.             debug(F100,"ttpkt TIOCSETC ok","",0);
  6506.         }
  6507.         }
  6508. #endif /* TIOCGETC */
  6509. #ifdef TIOCGLTC                /* Not rawmode, */
  6510. /* Prevent suspend during packet mode */
  6511.         if (ltcharf && (xlocal == 0)) { /* must turn off */
  6512.         ltchnoi.t_suspc = -1;    /* suspend character */
  6513.         ltchnoi.t_dsuspc = -1;    /* and delayed suspend character */
  6514.         if (ioctl(ttyfd,TIOCSLTC,&tchnoi) < 0) {
  6515.             debug(F100,"ttpkt TIOCSLTC failed","",0);
  6516.         } else {
  6517.             ltcharf = 1;
  6518.             debug(F100,"ttpkt TIOCSLTC ok","",0);
  6519.         }
  6520.         }
  6521. #endif /* TIOCGLTC */
  6522.     } else {            /* If no parity, */
  6523.         ttraw.sg_flags |= RAW;    /* must use 8-bit raw mode. */
  6524.         debug(F101,"ttpkt setting rawmode, parity","",parity);
  6525.     }
  6526. #endif /* LPASS8 */
  6527.     } /* End of Xon/Xoff section */
  6528.  
  6529.     /* Don't echo, don't map CR to CRLF on output, don't fool with case */
  6530. #ifdef LCASE
  6531.     ttraw.sg_flags &= ~(ECHO|CRMOD|LCASE);
  6532. #else
  6533.     ttraw.sg_flags &= ~(ECHO|CRMOD);
  6534. #endif /* LCASE */
  6535.  
  6536. #ifdef TOWER1
  6537.     ttraw.sg_flags &= ~ANYP;            /* Must set this on old Towers */
  6538. #endif /* TOWER1 */
  6539.  
  6540. #ifdef BELLV10
  6541.     if (ioctl(ttyfd,TIOCSETP,&ttraw) < 0) /* Set the new modes. */
  6542.       return(-1);
  6543. #else
  6544.     errno = 0;
  6545.     if (stty(ttyfd,&ttraw) < 0) {       /* Set the new modes. */
  6546.         debug(F101,"ttpkt stty failed","",errno);
  6547.         return(-1);
  6548.     }
  6549. #endif /* BELLV10 */
  6550.     debug(F100,"ttpkt stty ok","",0);
  6551.  
  6552. #ifdef sony_news
  6553.     x = xlocal ? km_ext : km_con;    /* Put line in ASCII mode. */
  6554.     if (x != -1) {            /* Make sure we know original modes. */
  6555.     x &= ~KM_TTYPE;
  6556.     x |= KM_ASCII;
  6557.     if (ioctl(ttyfd,TIOCKSET, &x) < 0) {
  6558.         perror("ttpkt can't set ASCII mode");
  6559.         debug(F101,"ttpkt error setting ASCII mode","",x);
  6560.         return(-1);
  6561.     }
  6562.     }
  6563.     debug(F100,"ttpkt set ASCII mode ok","",0);
  6564. #endif /* sony_news */
  6565.  
  6566.     if (xlocal == 0) {            /* Turn this off so we can read */
  6567.     signal(SIGINT,SIG_IGN);        /* Ctrl-C chars typed at console */
  6568.     sigint_ign = 1;
  6569.     }
  6570.     tvtflg = 0;                /* So ttvt() will work next time */
  6571.     debug(F100,"ttpkt success","",0);
  6572.     return(0);
  6573.  
  6574. #endif /* Not ATTSV or POSIX */
  6575.  
  6576. /* AT&T UNIX and POSIX */
  6577.  
  6578. #ifdef COHERENT
  6579. #define SVORPOSIX
  6580. #endif /* COHERENT */
  6581.  
  6582. #ifdef SVORPOSIX
  6583.     if (flow == FLO_XONX) {        /* Xon/Xoff */
  6584.     ttraw.c_iflag |= (IXON|IXOFF);
  6585.     tthflow(flow, 0, &ttraw);
  6586.     } else if (flow == FLO_NONE) {    /* None */
  6587.     /* NOTE: We should also turn off hardware flow control here! */
  6588.     ttraw.c_iflag &= ~(IXON|IXOFF);
  6589.     tthflow(flow, 0, &ttraw);
  6590.     } else if (flow == FLO_KEEP) {    /* Keep */
  6591.     ttraw.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff flags */
  6592.     ttraw.c_iflag |= (ttold.c_iflag & (IXON|IXOFF)); /* OR in old ones */
  6593.     /* NOTE: We should also handle hardware flow control here! */
  6594. #ifdef POSIX_CRTSCTS
  6595. /* In Linux case, we do this, which is unlikely to be portable */
  6596.         ttraw.c_cflag &= ~CRTSCTS;    /* Turn off RTS/CTS flag */
  6597.         ttraw.c_cflag |= (ttold.c_cflag & CRTSCTS); /* OR in old one */
  6598. #endif /* POSIX_CRTSCTS */
  6599.     } else if (flow == FLO_RTSC ||    /* Hardware */
  6600.            flow == FLO_DTRC ||
  6601.            flow == FLO_DTRT) {
  6602.     ttraw.c_iflag &= ~(IXON|IXOFF);    /* (190) */
  6603.     tthflow(flow, 1, &ttraw);
  6604.     }
  6605.     ttraw.c_lflag &= ~(ICANON|ECHO);
  6606.     ttraw.c_lflag &= ~ISIG;        /* Do NOT check for interrupt chars */
  6607.  
  6608. #ifndef OXOS
  6609. #ifdef QNX
  6610.     if (flow != FLO_RTSC && flow != FLO_DTRC && flow != FLO_DTRT)
  6611. #endif /* QNX */
  6612. #ifndef COHERENT
  6613.       ttraw.c_lflag &= ~IEXTEN;        /* Turn off ^O/^V processing */
  6614. #endif /* COHERENT */
  6615. #else /* OXOS */
  6616.     ttraw.c_cc[VDISCARD] = ttraw.c_cc[VLNEXT] = CDISABLE;
  6617. #endif /* OXOS */
  6618.     ttraw.c_lflag |= NOFLSH;        /* Don't flush */
  6619.     ttraw.c_iflag |= IGNPAR;        /* Ignore parity errors */
  6620. #ifdef ATTSV
  6621. #ifdef BSD44
  6622.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|INPCK|ISTRIP|IXANY);
  6623. #else
  6624.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IUCLC|INPCK|ISTRIP|IXANY);
  6625. #endif /* BSD44 */
  6626. #else /* POSIX */
  6627.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|INPCK|ISTRIP);
  6628. #endif /* ATTSV */
  6629.     ttraw.c_oflag &= ~OPOST;
  6630.     ttraw.c_cflag &= ~(CSIZE);
  6631.     ttraw.c_cflag |= (CS8|CREAD|HUPCL);
  6632.  
  6633. #ifdef CSTOPB
  6634.     if (xlocal) {
  6635.     if (stopbits == 2) {
  6636.         ttraw.c_cflag |= CSTOPB;    /* 2 stop bits */
  6637.         debug(F100,"ttpkt 2 stopbits","",0);
  6638.     } else if (stopbits == 1) {
  6639.         ttraw.c_cflag &= ~(CSTOPB);    /* 1 stop bit */
  6640.         debug(F100,"ttpkt 1 stopbit","",0);
  6641.     }
  6642.     }
  6643. #endif /* CSTOPB */
  6644.  
  6645. #ifdef HWPARITY
  6646.     if (hwparity && xlocal) {        /* Hardware parity */
  6647.     ttraw.c_cflag |= PARENB;    /* Enable parity */
  6648. #ifdef COMMENT
  6649. /* Uncomment this only if needed -- I don't think it is */
  6650.     ttraw.c_cflag &= ~(CSIZE);    /* Clear out character-size mask */
  6651.     ttraw.c_cflag |= CS8;        /* And set it to 8 */
  6652. #endif /* COMMENT */
  6653. #ifdef IGNPAR
  6654.     ttraw.c_iflag |= IGNPAR;    /* Don't discard incoming bytes */
  6655.     debug(F100,"ttpkt IGNPAR","",0); /* that have parity errors */
  6656. #endif /* IGNPAR */
  6657.     switch (hwparity) {
  6658.       case 'e':            /* Even */
  6659.         ttraw.c_cflag &= ~(PARODD);
  6660.         debug(F100,"ttpkt 8 bits + even parity","",0);
  6661.         break;
  6662.       case 'o':            /* Odd */
  6663.         ttraw.c_cflag |= PARODD;
  6664.         debug(F100,"ttpkt 8 bits + odd parity","",0);
  6665.         break;
  6666.       case 'm':            /* Mark */
  6667.       case 's':            /* Space */
  6668.         /* PAREXT is mentioned in SVID but the details are not given. */
  6669.         /* PAREXT is not included in POSIX ISO/IEC 9945-1. */
  6670.         debug(F100,"ttpkt 8 bits + invalid parity","",0);
  6671.         break;
  6672.     }
  6673.     } else {                /* We handle parity ourselves */
  6674. #endif /* HWPARITY */
  6675.     ttraw.c_cflag &= ~(PARENB);    /* Don't enable parity */
  6676. #ifdef HWPARITY
  6677.     }
  6678. #endif /* HWPARITY */
  6679.  
  6680. #ifdef IX370
  6681.     ttraw.c_cc[4] = 48;  /* So Series/1 doesn't interrupt on every char */
  6682.     ttraw.c_cc[5] = 1;
  6683. #else
  6684. #ifndef VEOF                /* for DGUX this is VEOF, not VMIN */
  6685.     ttraw.c_cc[4] = 1;   /* [VMIN]  return max of this many characters or */
  6686. #else
  6687. #ifndef OXOS
  6688. #ifdef VMIN
  6689.     ttraw.c_cc[VMIN] = 1;
  6690. #endif /* VMIN */
  6691. #else /* OXOS */
  6692.     ttraw.c_min = 1;
  6693. #endif /* OXOS */
  6694. #endif /* VEOF */
  6695. #ifndef VEOL                /* for DGUX this is VEOL, not VTIME */
  6696.     ttraw.c_cc[5] = 0;     /* [VTIME] when this many secs/10 expire w/no input */
  6697. #else
  6698. #ifndef OXOS
  6699. #ifdef VTIME
  6700.     ttraw.c_cc[VTIME] = 0;
  6701. #endif /* VTIME */
  6702. #else /* OXOS */
  6703.     ttraw.c_time = 0;
  6704. #endif /* OXOS */
  6705. #endif /* VEOL */
  6706. #endif /* IX370 */
  6707.  
  6708. #ifdef VINTR                /* Turn off interrupt character */
  6709.     if (xlocal == 0)            /* so ^C^C can break us out of */
  6710.       ttraw.c_cc[VINTR] = 0;        /* packet mode. */
  6711. #endif /* VINTR */
  6712.  
  6713. #ifdef Plan9
  6714.     if (p9ttyparity('n') < 0)
  6715.     return -1;
  6716. #else
  6717. #ifdef BSD44ORPOSIX
  6718.     errno = 0;
  6719. #ifdef BEOSORBEBOX
  6720.     ttraw.c_cc[VMIN] = 0;        /* DR7 can only poll. */
  6721. #endif /* BEOSORBEBOX */
  6722.  
  6723. #define TESTING234
  6724. #ifdef TESTING234
  6725.     if (1) {
  6726.     debug(F100,"ttpkt TESTING234 rawmode","",0);
  6727.  
  6728.     /* iflags */
  6729.     ttraw.c_iflag &= ~(PARMRK|ISTRIP|BRKINT|INLCR|IGNCR|ICRNL);
  6730.     ttraw.c_iflag &= ~(INPCK|IGNPAR|IMAXBEL|IXANY|IXON|IXOFF);
  6731.     ttraw.c_iflag |= IGNBRK;
  6732. #ifdef IUCLC
  6733.     ttraw.c_iflag &= ~IUCLC;
  6734. #endif /* IUCLC */
  6735.  
  6736.     /* oflags */
  6737.     ttraw.c_oflag &= ~OPOST;
  6738. #ifdef OXTABS
  6739.     ttraw.c_oflag &= ~OXTABS;
  6740. #endif /* OXTABS */
  6741. #ifdef ONOCR
  6742.     ttraw.c_oflag &= ~ONOCR;
  6743. #endif /* ONOCR */
  6744. #ifdef ONLRET
  6745.     ttraw.c_oflag &= ~ONLRET;
  6746. #endif /* ONLRET */
  6747. #ifdef ONLCR
  6748.     ttraw.c_oflag &= ~ONLCR;
  6749. #endif /* ONLCR */
  6750.  
  6751.     /* lflags */
  6752.     ttraw.c_lflag &= ~ECHO;
  6753. #ifdef ECHOE
  6754.     ttraw.c_lflag &= ~ECHOE;
  6755. #endif /* ECHOE */
  6756. #ifdef ECHONL
  6757.     ttraw.c_lflag &= ~ECHONL;
  6758. #endif /* ECHONL */
  6759. #ifdef ECHOPRT
  6760.     ttraw.c_lflag &= ~ECHOPRT;
  6761. #endif /* ECHOPRT */
  6762. #ifdef ECHOKE
  6763.     ttraw.c_lflag &= ~ECHOKE;
  6764. #endif /* ECHOKE */
  6765. #ifdef ECHOCTL
  6766.     ttraw.c_lflag &= ~ECHOCTL;
  6767. #endif /* ECHOCTL */
  6768. #ifdef ALTWERASE
  6769.     ttraw.c_lflag &= ~ALTWERASE;
  6770. #endif /* ALTWERASE */
  6771. #ifdef EXTPROC
  6772.     ttraw.c_lflag &= ~EXTPROC;
  6773. #endif /* EXTPROC */
  6774.     ttraw.c_lflag &= ~(ICANON|ISIG|IEXTEN|TOSTOP|FLUSHO|PENDIN);
  6775. #ifdef NOKERNINFO
  6776.     ttraw.c_lflag |= NOKERNINFO;
  6777. #endif    /* NOKERNINFO */
  6778.     /* ttraw.c_lflag |= NOFLSH; */
  6779.     ttraw.c_lflag &= ~NOFLSH;
  6780.  
  6781.     /* cflags */
  6782.     ttraw.c_cflag &= ~(CSIZE|PARENB|PARODD);
  6783.     ttraw.c_cflag |= CS8|CREAD;
  6784. #ifdef VMIN
  6785.     ttraw.c_cc[VMIN] = 1;        /* Supposedly needed for AIX */
  6786. #endif    /* VMIN */
  6787.  
  6788.     }
  6789. #endif /* TESTING234 */
  6790.  
  6791.     debug(F100,"ttpkt calling tcsetattr(TCSETAW)","",0);
  6792.     x = tcsetattr(ttyfd,TCSADRAIN,&ttraw);
  6793.     debug(F101,"ttpkt BSD44ORPOSIX tcsetattr","",x);
  6794.     if (x < 0) {
  6795.     debug(F101,"ttpkt BSD44ORPOSIX tcsetattr errno","",errno);
  6796.         return(-1);
  6797.     }
  6798. #else /* BSD44ORPOSIX */
  6799.     x = ioctl(ttyfd,TCSETAW,&ttraw);
  6800.     debug(F101,"ttpkt ATTSV ioctl TCSETAW","",x);
  6801.     if (x < 0) {  /* set new modes . */
  6802.     debug(F101,"ttpkt ATTSV ioctl TCSETAW errno","",errno);
  6803.         return(-1);
  6804.     }
  6805. #endif /* BSD44ORPOSIX */
  6806. #endif /* Plan9 */
  6807.     tvtflg = 0;
  6808.     debug(F100,"ttpkt ok","",0);
  6809.     return(0);
  6810. #endif /* ATTSV */
  6811.  
  6812. #ifdef COHERENT
  6813. #undef SVORPOSIX
  6814. #endif /* COHERENT */
  6815.  
  6816. }
  6817.  
  6818. /*  T T S E T F L O W  --  Set flow control immediately.  */
  6819.  
  6820. #ifdef COHERENT
  6821. #define SVORPOSIX
  6822. #endif /* COHERENT */
  6823.  
  6824. int
  6825. ttsetflow(flow) int flow; {
  6826.     if (ttyfd < 0)            /* A channel must be open */
  6827.       return(-1);
  6828.  
  6829.     debug(F101,"ttsetflow flow","",flow);
  6830.  
  6831. #ifdef TN_COMPORT
  6832.     if (netconn && istncomport()) {
  6833.     debug(F101,"ttsetflow net modem","",ttmdm);
  6834.     return(tnsetflow(flow));
  6835.     }
  6836. #endif /* TN_COMPORT */
  6837. #ifdef NETCMD
  6838.     if (ttpipe) return(0);
  6839. #endif /* NETCMD */
  6840. #ifdef NETPTY
  6841.     if (ttpty) return(0);
  6842. #endif /* NETPTY */
  6843.  
  6844. #ifdef COMMENT
  6845.     /* This seems to hurt... */
  6846.     if (flow == FLO_KEEP)
  6847.       return(0);
  6848. #endif /* COMMENT */
  6849.  
  6850.     if (flow == FLO_RTSC ||        /* Hardware flow control... */
  6851.     flow == FLO_DTRC ||
  6852.     flow == FLO_DTRT) {
  6853.     tthflow(flow, 1, &ttraw);
  6854. #ifndef SVORPOSIX
  6855.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6856. #else
  6857.     ttraw.c_iflag &= ~(IXON|IXOFF);
  6858. #endif /* SVORPOSIX */
  6859.  
  6860.     } else if (flow == FLO_XONX) {    /* Xon/Xoff... */
  6861.  
  6862. #ifndef SVORPOSIX
  6863.     ttraw.sg_flags |= TANDEM;
  6864. #else
  6865.     ttraw.c_iflag |= (IXON|IXOFF);
  6866. #endif /* SVORPOSIX */
  6867.     tthflow(FLO_RTSC, 0, &ttraw);    /* Turn off hardware flow control */
  6868.  
  6869.     } else if (flow == FLO_NONE) {    /* No flow control */
  6870.  
  6871. #ifndef SVORPOSIX
  6872.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6873. #else
  6874.     ttraw.c_iflag &= ~(IXON|IXOFF);
  6875. #endif /* SVORPOSIX */
  6876.     tthflow(FLO_RTSC, 0, &ttraw);    /* Turn off any hardware f/c too */
  6877.     }
  6878.  
  6879. /* Set the new modes... */
  6880.  
  6881. #ifndef SVORPOSIX            /* BSD and friends */
  6882. #ifdef BELLV10
  6883.     if (ioctl(ttyfd,TIOCSETP,&ttraw) < 0)
  6884.       return(-1);
  6885. #else
  6886. #ifndef MINIX2
  6887.     if (stty(ttyfd,&ttraw) < 0)
  6888.       return(-1);
  6889. #endif /* MINIX2 */
  6890. #endif /* BELLV10 */
  6891. #else
  6892. #ifdef BSD44ORPOSIX            /* POSIX */
  6893.     if (tcsetattr(ttyfd,TCSADRAIN,&ttraw) < 0)
  6894.       return(-1);
  6895. #else                    /* System V */
  6896.     if (ioctl(ttyfd,TCSETAW,&ttraw) < 0)
  6897.       return(-1);
  6898. #endif /* BSD44ORPOSIX */
  6899. #endif /* SVORPOSIX */
  6900.     return(0);
  6901. }
  6902. #ifdef COHERENT
  6903. #undef SVORPOSIX
  6904. #endif /* COHERENT */
  6905.  
  6906. /*  T T V T -- Condition communication device for use as virtual terminal. */
  6907.  
  6908. int
  6909. #ifdef CK_ANSIC
  6910. ttvt(long speed, int flow)
  6911. #else
  6912. ttvt(speed,flow) long speed; int flow;
  6913. #endif /* CK_ANSIC */
  6914. /* ttvt */ {
  6915.     int s, s2, x;
  6916.  
  6917.     debug(F101,"ttvt ttyfd","",ttyfd);
  6918.     debug(F101,"ttvt tvtflg","",tvtflg);
  6919.     debug(F111,"ttvt speed",ckitoa(ttspeed),speed);
  6920.     debug(F111,"ttvt flow",ckitoa(ttflow),flow);
  6921.     debug(F111,"ttvt curcarr",ckitoa(ttcarr),curcarr);
  6922.  
  6923. /* Note: NetBSD and maybe other BSD44s have cfmakeraw() */
  6924. /* Maybe it would be simpler to use it... */
  6925.  
  6926.     ttpmsk = 0xff;
  6927. #ifdef NOLOCAL
  6928.     return(conbin((char)escchr));
  6929. #else
  6930.     if (ttyfd < 0) {            /* Not open. */
  6931.     if (ttchk() < 0)
  6932.       return(-1);
  6933.     else                /* But maybe something buffered. */
  6934.       return(0);
  6935.     }
  6936. #ifdef NETCMD
  6937.     if (ttpipe) return(0);
  6938. #endif /* NETCMD */
  6939. #ifdef NETPTY
  6940.     if (ttpty) return(0);
  6941. #endif /* NETPTY */
  6942. #ifdef NETCONN
  6943.     if (netconn) {
  6944. #ifdef TCPSOCKET
  6945. #ifdef TCP_NODELAY
  6946.         {
  6947.         extern int tcp_nodelay;
  6948.         if (ttnet == NET_TCPB) {
  6949.         if (nodelay_sav > -1) {
  6950.             no_delay(ttyfd,nodelay_sav);
  6951.             nodelay_sav = -1;
  6952.         }
  6953.         }
  6954.         }
  6955. #endif /* TCP_NODELAY */
  6956. #ifdef TN_COMPORT
  6957.         if (istncomport()) {
  6958.             int rc = -1;
  6959.             if (tvtflg != 0 && speed == ttspeed && flow == ttflow
  6960.                  /* && ttcarr == curcarr */ ) {
  6961.                 debug(F100,"ttvt modes already set, skipping...","",0);
  6962.                 return(0);            /* Already been called. */
  6963.             }
  6964.             if (flow != ttflow) {
  6965.                 if ((rc = tnsetflow(flow)) < 0)
  6966.           return(rc);
  6967.                 ttflow = flow;
  6968.             }
  6969.             if (speed != ttspeed) {
  6970.                 if (speed <= 0) 
  6971.           speed = tnc_get_baud();
  6972.                 else if ((rc = tnc_set_baud(speed)) < 0)
  6973.           return(rc);
  6974.                 ttspeed = speed;
  6975.             }
  6976.             tnc_set_datasize(8);
  6977.         tnc_set_stopsize(stopbits);
  6978.  
  6979. #ifdef HWPARITY
  6980.             if (hwparity) {
  6981.                 switch (hwparity) {
  6982.           case 'e':        /* Even */
  6983.                     debug(F100,"ttres 8 bits + even parity","",0);
  6984.                     tnc_set_parity(3);
  6985.                     break;
  6986.           case 'o':        /* Odd */
  6987.                     debug(F100,"ttres 8 bits + odd parity","",0);
  6988.                     tnc_set_parity(2);
  6989.                     break;
  6990.           case 'm':        /* Mark */
  6991.                     debug(F100,"ttres 8 bits + invalid parity: mark","",0);
  6992.                     tnc_set_parity(4);
  6993.                     break;
  6994.           case 's':        /* Space */
  6995.                     debug(F100,"ttres 8 bits + invalid parity: space","",0);
  6996.                     tnc_set_parity(5);
  6997.                     break;
  6998.                 }
  6999.             } else
  7000. #endif /* HWPARITY */
  7001.             {
  7002.                 tnc_set_parity(1);    /* None */
  7003.             }
  7004.             tvtflg = 1;
  7005.             return(0);
  7006.         }
  7007. #endif /* TN_COMPORT */
  7008. #endif /* TCPSOCKET */
  7009.     tvtflg = 1;            /* Network connections... */
  7010.     debug(F100,"ttvt network connection, skipping...","",0);
  7011.     return(0);            /* ... require no special setup */
  7012.     }
  7013. #endif /* NETCONN */
  7014.  
  7015.     if (tvtflg != 0 && speed == ttspeed && flow == ttflow
  7016.     /* && ttcarr == curcarr */ )
  7017.       {
  7018.       debug(F100,"ttvt modes already set, skipping...","",0);
  7019.       return(0);            /* Already been called. */
  7020.       }
  7021.  
  7022.     if (ttfdflg
  7023. #ifndef Plan9
  7024.     && !isatty(ttyfd)
  7025. #endif /* Plan9 */
  7026.     ) {
  7027.     debug(F100,"ttvt using external fd, skipping...","",0);
  7028.     return(0);
  7029.     }
  7030.  
  7031.     debug(F100,"ttvt setting modes...","",0);
  7032.  
  7033.     if (xlocal) {            /* For external lines... */
  7034.     s2 = (int) (speed / 10L);
  7035.     s = ttsspd(s2);            /* Check/set the speed */
  7036.     carrctl(&tttvt, flow != FLO_DIAL /* Do carrier control */
  7037.         && (ttcarr == CAR_ON || (ttcarr == CAR_AUT && ttmdm != 0)));
  7038.     } else
  7039.       s = s2 = -1;
  7040.  
  7041. #ifdef COHERENT
  7042. #define SVORPOSIX
  7043. #endif /* COHERENT */
  7044.  
  7045. #ifndef SVORPOSIX
  7046.     /* Berkeley, V7, etc */
  7047.     if (flow == FLO_RTSC ||        /* Hardware flow control */
  7048.     flow == FLO_DTRC ||
  7049.     flow == FLO_DTRT) {
  7050.     tthflow(flow, 1, &tttvt);
  7051.     debug(F100,"ttvt hard flow, TANDEM off","",0);
  7052.     tttvt.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  7053.     } else if (flow == FLO_XONX) {    /* Xon/Xoff flow control */
  7054.     debug(F100,"ttvt TANDEM on","",0);
  7055.     tttvt.sg_flags |= TANDEM;    /* Ask for it. */
  7056.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  7057.     } else if (flow == FLO_NONE) {
  7058.     debug(F100,"ttvt no flow, TANDEM off, RAW on","",0);
  7059.     tttvt.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  7060.     tthflow(flow, 0, &tttvt);    /* Turn off any hardware f/c too */
  7061.     tttvt.sg_flags |= RAW;        /* Enter raw mode */
  7062.     } else if (flow == FLO_KEEP) {    /* Keep device's original setting */
  7063.     debug(F100,"ttvt keeping original TANDEM","",0);
  7064.     tttvt.sg_flags &= ~TANDEM;
  7065.     tttvt.sg_flags |= (ttold.sg_flags & TANDEM);
  7066.     /* NOTE: We should also handle hardware flow control here! */
  7067.     }
  7068.     tttvt.sg_flags |= RAW;              /* Raw mode in all cases */
  7069. #ifdef TOWER1
  7070.     tttvt.sg_flags &= ~(ECHO|ANYP);     /* No echo or parity */
  7071. #else
  7072.     tttvt.sg_flags &= ~ECHO;            /* No echo */
  7073. #endif /* TOWER1 */
  7074.  
  7075. #ifdef BELLV10
  7076.     if (ioctl(ttyfd,TIOCSETP,&tttvt) < 0) /* Set the new modes */
  7077.       return(-1);
  7078. #else
  7079.     if (stty(ttyfd,&tttvt) < 0)        /* Set the new modes */
  7080.       return(-1);
  7081. #endif /* BELLV10 */
  7082.  
  7083. #else /* It is ATTSV or POSIX */
  7084.  
  7085.     if (flow == FLO_XONX) {        /* Software flow control */
  7086.     tttvt.c_iflag |= (IXON|IXOFF);    /* On if requested. */
  7087.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  7088.     debug(F100,"ttvt SVORPOSIX flow XON/XOFF","",0);
  7089.     } else if (flow == FLO_NONE) {    /* NONE */
  7090.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff */
  7091.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  7092.     debug(F100,"ttvt SVORPOSIX flow NONE","",0);
  7093.     } else if (flow == FLO_KEEP) {
  7094.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff flags */
  7095.     tttvt.c_iflag |= (ttold.c_iflag & (IXON|IXOFF)); /* OR in old ones */
  7096. #ifdef POSIX_CRTSCTS
  7097.         tttvt.c_cflag &= ~CRTSCTS;    /* Turn off RTS/CTS flag */
  7098.         tttvt.c_cflag |= (ttold.c_cflag & CRTSCTS); /* OR in old one */
  7099. #endif /* POSIX_CRTSCTS */
  7100.     debug(F100,"ttvt SVORPOSIX flow KEEP","",0);
  7101.     } else if (flow == FLO_RTSC ||    /* Hardware flow control */
  7102.            flow == FLO_DTRC ||
  7103.            flow == FLO_DTRT) {
  7104.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* (196) */
  7105.     tthflow(flow, 1, &tttvt);
  7106.     debug(F100,"ttvt SVORPOSIX flow HARD","",0);
  7107.     }
  7108. #ifndef OXOS
  7109. #ifdef COHERENT
  7110.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO);
  7111. #else
  7112.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO|IEXTEN);
  7113. #endif /* COHERENT */
  7114. #ifdef QNX
  7115.     /* Needed for hwfc */
  7116.     if (flow == FLO_RTSC || flow == FLO_DTRC || flow == FLO_DTRT)
  7117.       tttvt.c_lflag |= IEXTEN;
  7118. #endif /* QNX */
  7119. #else /* OXOS */
  7120.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO);
  7121.     tttvt.c_cc[VDISCARD] = tttvt.c_cc[VLNEXT] = CDISABLE;
  7122. #endif /* OXOS */
  7123.  
  7124.     tttvt.c_iflag |= (IGNBRK|IGNPAR);
  7125.  
  7126. /* Stop bits */
  7127.  
  7128. #ifdef CSTOPB
  7129.     if (xlocal) {
  7130.     if (stopbits == 2) {
  7131.         tttvt.c_cflag |= CSTOPB;    /* 2 stop bits */
  7132.         debug(F100,"ttvt 2 stopbits","",0);
  7133.     } else if (stopbits == 1) {
  7134.         tttvt.c_cflag &= ~(CSTOPB);    /* 1 stop bit */
  7135.         debug(F100,"ttvt 1 stopbit","",0);
  7136.     }
  7137.     }
  7138. #endif /* CSTOPB */
  7139.  
  7140. /* Parity */
  7141.  
  7142. #ifdef HWPARITY
  7143.     if (hwparity && xlocal) {        /* Hardware parity */
  7144. #ifdef COMMENT
  7145. /* Uncomment this only if needed -- I don't think it is */
  7146.     ttraw.c_cflag &= ~(CSIZE);    /* Clear out character-size mask */
  7147.     ttraw.c_cflag |= CS8;        /* And set it to 8 */
  7148. #endif /* COMMENT */
  7149. #ifdef IGNPAR
  7150.     debug(F101,"ttvt hwparity IGNPAR","",IGNPAR);
  7151.     tttvt.c_iflag |= IGNPAR;    /* Don't discard incoming bytes */
  7152. #endif /* IGNPAR */
  7153.     tttvt.c_cflag |= PARENB;    /* Enable parity */
  7154.  
  7155.     switch (hwparity) {
  7156.       case 'e':            /* Even */
  7157.         tttvt.c_cflag &= ~(PARODD);
  7158.         debug(F100,"ttvt 8 bits + even parity","",0);
  7159.         break;
  7160.       case 'o':            /* Odd */
  7161.         tttvt.c_cflag |= PARODD;
  7162.         debug(F100,"ttvt 8 bits + odd parity","",0);
  7163.         break;
  7164.       case 'm':            /* Mark */
  7165.       case 's':            /* Space */
  7166.         /* PAREXT is mentioned in SVID but the details are not given. */
  7167.         /* PAREXT is not included in POSIX ISO/IEC 9945-1. */
  7168.         debug(F100,"ttvt 8 bits + invalid parity","",0);
  7169.         break;
  7170.     }
  7171.     } else {                /* We handle parity ourselves */
  7172. #endif /* HWPARITY */
  7173.     tttvt.c_cflag &= ~(PARENB);    /* Don't enable parity */
  7174. #ifdef HWPARITY
  7175.     }
  7176. #endif /* HWPARITY */
  7177.  
  7178. #ifdef ATTSV
  7179. #ifdef BSD44
  7180.     /* Things not to do... */
  7181.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|INPCK|ISTRIP|IXANY);
  7182. #else
  7183.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|IUCLC|INPCK|ISTRIP|IXANY);
  7184. #endif /* BSD44 */
  7185. #else /* POSIX */
  7186.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|INPCK|ISTRIP);
  7187. #endif /* ATTSV */
  7188.     tttvt.c_cflag &= ~(CSIZE);        /* Zero out the char size field */
  7189.     tttvt.c_cflag |= (CS8|CREAD|HUPCL);    /* Char size 8, enable receiver, hup */
  7190.     tttvt.c_oflag &= ~OPOST;        /* Don't postprocess output */
  7191. #ifndef VEOF /* DGUX termio has VEOF at entry 4, see comment above */
  7192.     tttvt.c_cc[4] = 1;
  7193. #else
  7194. #ifndef OXOS
  7195. #ifdef VMIN
  7196.     tttvt.c_cc[VMIN] = 1;
  7197. #endif /* VMIN */
  7198. #else /* OXOS */
  7199.     tttvt.c_min = 1;
  7200. #endif /* OXOS */
  7201. #endif /* VEOF */
  7202. #ifndef VEOL    /* DGUX termio has VEOL at entry 5, see comment above */
  7203.     tttvt.c_cc[5] = 0;
  7204. #else
  7205. #ifndef OXOS
  7206. #ifdef VTIME
  7207.     tttvt.c_cc[VTIME] = 0;
  7208. #endif /* VTIME */
  7209. #else /* OXOS */
  7210.     tttvt.c_time = 0;
  7211. #endif /* OXOS */
  7212. #endif /* VEOL */
  7213.  
  7214. #ifdef Plan9
  7215.     if (p9ttyparity('n') < 0)
  7216.       return -1;
  7217. #else
  7218. #ifdef BSD44ORPOSIX
  7219.     errno = 0;
  7220. #ifdef BEOSORBEBOX
  7221.     tttvt.c_cc[VMIN] = 0;        /* DR7 can only poll. */
  7222. #endif /* BEOSORBEBOX */
  7223.  
  7224.     x = tcsetattr(ttyfd,TCSADRAIN,&tttvt);
  7225.     debug(F101,"ttvt BSD44ORPOSIX tcsetattr","",x);
  7226.     if (x < 0) {
  7227.     debug(F101,"ttvt BSD44ORPOSIX tcsetattr errno","",errno);
  7228.     return(-1);
  7229.     }
  7230. #else /* ATTSV */
  7231.     x = ioctl(ttyfd,TCSETAW,&tttvt);
  7232.     debug(F101,"ttvt ATTSV ioctl TCSETAW","",x);
  7233.     if (x < 0) {            /* set new modes . */
  7234.     debug(F101,"ttvt ATTSV ioctl TCSETAW errno","",errno);
  7235.     return(-1);    
  7236.     }
  7237. #endif /* BSD44ORPOSIX */
  7238. #endif /* Plan9 */
  7239. #endif /* ATTSV */
  7240.  
  7241.     ttspeed = speed;            /* Done, remember how we were */
  7242.     ttflow = flow;            /* called, so we can decide how to */
  7243.     tvtflg = 1;                /* respond next time. */
  7244.     debug(F100,"ttvt ok","",0);
  7245.     return(0);
  7246.  
  7247. #ifdef COHERENT
  7248. #undef SVORPOSIX
  7249. #endif /* COHERENT */
  7250.  
  7251. #endif /* NOLOCAL */
  7252. }
  7253.  
  7254. #ifndef NOLOCAL
  7255.  
  7256. /* Serial speed department . . . */
  7257.  
  7258. /*
  7259.   SCO OSR5.0.x might or might not support high speeds.  Sometimes they are not
  7260.   defined in the header files but they are supported (e.g. when building with
  7261.   UDK compiler rather than /bin/cc), sometimes vice versa.  Even though 5.0.4
  7262.   was the first release that came with high serial speeds standard, releases
  7263.   back to 5.0.0 could use them if certain patches (or "supplements") were
  7264.   applied to the SIO driver.  Plus a lot of SCO installations run third-party
  7265.   drivers.
  7266. */
  7267. #ifdef CK_SCOV5
  7268. #ifndef B38400
  7269. #define    B38400    0000017
  7270. #endif /* B38400 */
  7271. #ifndef B57600
  7272. #define    B57600    0000021
  7273. #endif /* B57600 */
  7274. #ifndef B76800
  7275. #define    B76800    0000022
  7276. #endif /* B76800 */
  7277. #ifndef B115200
  7278. #define    B115200    0000023
  7279. #endif /* B115200 */
  7280. #ifndef B230400
  7281. #define    B230400    0000024
  7282. #endif /* B230400 */
  7283. #ifndef B460800
  7284. #define    B460800    0000025
  7285. #endif /* B460800 */
  7286. #ifndef B921600
  7287. #define    B921600    0000026
  7288. #endif /* B921600 */
  7289. #endif /* CK_SCOV5 */
  7290. /*
  7291.   Plan 9's native speed setting interface lets you set anything you like,
  7292.   but will fail if the hardware doesn't like it, so we allow all the common
  7293.   speeds.
  7294. */
  7295. #ifdef Plan9
  7296. #ifndef B50
  7297. #define B50 50
  7298. #endif /* B50 */
  7299. #ifndef B75
  7300. #define B75 75
  7301. #endif /* B75 */
  7302. #ifndef B110
  7303. #define B110 110
  7304. #endif /* B110 */
  7305. #ifndef B134
  7306. #define B134 134
  7307. #endif /* B134 */
  7308. #ifndef B200
  7309. #define B200 200
  7310. #endif /* B200 */
  7311. #ifndef B300
  7312. #define B300 300
  7313. #endif /* B300 */
  7314. #ifndef B1200
  7315. #define B1200 1200
  7316. #endif /* B1200 */
  7317. #ifndef B1800
  7318. #define B1800 1800
  7319. #endif /* B1800 */
  7320. #ifndef B2400
  7321. #define B2400 2400
  7322. #endif /* B2400 */
  7323. #ifndef B4800
  7324. #define B4800 4800
  7325. #endif /* B4800 */
  7326. #ifndef B9600
  7327. #define B9600 9600
  7328. #endif /* B9600 */
  7329. #ifndef B14400
  7330. #define B14400 14400
  7331. #endif /* B14400 */
  7332. #ifndef B19200
  7333. #define B19200 19200
  7334. #endif /* B19200 */
  7335. #ifndef B28800
  7336. #define B28800 28800
  7337. #endif /* B28800 */
  7338. #ifndef B38400
  7339. #define B38400 38400
  7340. #endif /* B38400 */
  7341. #ifndef B57600
  7342. #define B57600 57600
  7343. #endif /* B57600 */
  7344. #ifndef B76800
  7345. #define B76800 76800
  7346. #endif /* B76800 */
  7347. #ifndef B115200
  7348. #define B115200 115200
  7349. #endif /* B115200 */
  7350. #ifndef B230400
  7351. #define B230400 230400
  7352. #endif /* B230400 */
  7353. #ifndef B460800
  7354. #define B460800 460800
  7355. #endif /* B460800 */
  7356. #ifndef B921600
  7357. #define B921600 921600
  7358. #endif /* B921600 */
  7359. #endif /* Plan9 */
  7360.  
  7361. /*  T T S S P D  --  Checks and sets transmission rate.  */
  7362.  
  7363. /*  Call with speed in characters (not bits!) per second. */
  7364. /*  Returns -1 on failure, 0 if it did nothing, 1 if it changed the speed. */
  7365.  
  7366. #ifdef USETCSETSPEED
  7367. /*
  7368.   The tcsetspeed() / tcgetspeed() interface lets you pass any number at all
  7369.   to be used as a speed to be set, rather than forcing a choice from a
  7370.   predefined list.  It seems to be peculiar to UnixWare 7.
  7371.  
  7372.   These are the function codes to be passed to tc[gs]etspeed(),
  7373.   but for some reason they don't seem to be picked up from termios.h.
  7374. */
  7375. #ifndef TCS_ALL
  7376. #define TCS_ALL 0
  7377. #endif /* TCS_ALL */
  7378. #ifndef TCS_IN
  7379. #define TCS_IN 1
  7380. #endif /* TCS_IN */
  7381. #ifndef TCS_OUT
  7382. #define TCS_OUT 2
  7383. #endif /* TCS_OUT */
  7384. #endif /* USETCSETSPEED */
  7385.  
  7386. int
  7387. ttsspd(cps) int cps; {
  7388.     int x;
  7389. #ifdef POSIX
  7390. /* Watch out, speed_t should be unsigned, so don't compare with -1, etc... */
  7391.     speed_t
  7392. #else
  7393.     int
  7394. #endif /* POSIX */
  7395.       s, s2;
  7396.     int ok = 1;                /* Speed check result, assume ok */
  7397.  
  7398. #ifdef OLINUXHISPEED
  7399.     unsigned int spd_flags = 0;
  7400.     struct serial_struct serinfo;
  7401. #endif /* OLINUXHISPEED */
  7402.  
  7403.     debug(F101,"ttsspd cps","",cps);
  7404.     debug(F101,"ttsspd ttyfd","",ttyfd);
  7405.     debug(F101,"ttsspd xlocal","",xlocal);
  7406.  
  7407.     if (ttyfd < 0 || xlocal == 0)    /* Don't set speed on console */
  7408.       return(0);
  7409.  
  7410. #ifdef    NETCONN
  7411.     if (netconn) {
  7412. #ifdef TN_COMPORT
  7413.         if (istncomport())
  7414.       return(tnc_set_baud(cps * 10));
  7415.         else
  7416. #endif /* TN_COMPORT */
  7417.     return(0);
  7418.   }
  7419. #endif    /* NETCONN */
  7420. #ifdef NETCMD
  7421.     if (ttpipe) return(0);
  7422. #endif /* NETCMD */
  7423. #ifdef NETPTY
  7424.     if (ttpty) return(0);
  7425. #endif /* NETPTY */
  7426.  
  7427.     if (cps < 0) return(-1);
  7428.     s = s2 = 0;                /* NB: s and s2 might be unsigned */
  7429.  
  7430. #ifdef USETCSETSPEED
  7431.  
  7432.     s = cps * 10L;
  7433.  
  7434.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  7435.     debug(F101,"ttsspd tcgetattr","",x);
  7436.     if (x < 0)
  7437.       return(-1);
  7438.     debug(F101,"ttsspd TCSETSPEED speed","",s);
  7439.  
  7440.     errno = 0;
  7441.     if (s == 8880L) {            /* 75/1200 split speed requested */
  7442.     tcsetspeed(TCS_IN, &ttcur, 1200L);
  7443.     tcsetspeed(TCS_OUT, &ttcur, 75L);
  7444.     } else
  7445.       tcsetspeed(TCS_ALL, &ttcur, s);    /* Put new speed in structs */
  7446. #ifdef DEBUG
  7447.     if (errno & deblog) {
  7448.     debug(F101,"ttsspd TCSETSPEED errno","",errno);
  7449.     }
  7450. #endif /* DEBUG */
  7451.  
  7452. #ifdef COMMENT
  7453.     tcsetspeed(TCS_ALL, &ttraw, s);
  7454.     tcsetspeed(TCS_ALL, &tttvt, s);
  7455.     tcsetspeed(TCS_ALL, &ttold, s);
  7456. #else
  7457.     if (s == 8880L) {            /* 75/1200 split speed requested */
  7458.     tcsetspeed(TCS_IN, &ttraw, 1200L);
  7459.     tcsetspeed(TCS_OUT, &ttraw, 75L);
  7460.     tcsetspeed(TCS_IN, &tttvt, 1200L);
  7461.     tcsetspeed(TCS_OUT, &tttvt, 75L);
  7462.     tcsetspeed(TCS_IN, &ttold, 1200L);
  7463.     tcsetspeed(TCS_OUT, &ttold, 75L);
  7464.     } else {
  7465.     tcsetspeed(TCS_ALL, &ttraw, s);
  7466.     tcsetspeed(TCS_ALL, &tttvt, s);
  7467.     tcsetspeed(TCS_ALL, &ttold, s);
  7468.     }
  7469. #endif /* COMMENT */
  7470.  
  7471.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur); /* Set the speed */
  7472.     debug(F101,"ttsspd tcsetattr","",x);
  7473.     if (x < 0)
  7474.       return(-1);
  7475.  
  7476. #else  /* Not USETCSETSPEED */
  7477.  
  7478. #ifdef MINIX2        /* Hack alert */
  7479. #define MINIX        /* Use pre-2.0 speed selection for Minix 2.0 as well */
  7480. #endif /* MINIX2 */
  7481.  
  7482.     /* First check that the given speed is valid. */
  7483.  
  7484.     switch (cps) {
  7485. #ifndef MINIX
  7486.       case 0:   s = B0;    break;
  7487.       case 5:   s = B50;   break;
  7488.       case 7:   s = B75;   break;
  7489. #endif /* MINIX */
  7490.       case 11:  s = B110;  break;
  7491. #ifndef MINIX
  7492.       case 13:  s = B134;  break;
  7493.       case 15:  s = B150;  break;
  7494.       case 20:  s = B200;  break;
  7495. #endif /* MINIX */
  7496.       case 30:  s = B300;  break;
  7497. #ifndef MINIX
  7498.       case 60:  s = B600;  break;
  7499. #endif /* MINIX */
  7500.       case 120: s = B1200; break;
  7501. #ifndef MINIX
  7502.       case 180: s = B1800; break;
  7503. #endif /* MINIX */
  7504.       case 240: s = B2400; break;
  7505.       case 480: s = B4800; break;
  7506. #ifndef MINIX
  7507.       case 888: s = B75; s2 = B1200; break; /* 888 = 75/1200 split speed */
  7508. #endif /* MINIX */
  7509. #ifdef B7200
  7510.       case 720: s = B7200; break;
  7511. #endif /* B7200 */
  7512.       case 960: s = B9600; break;
  7513. #ifdef B14400
  7514.       case 1440: s = B14400; break;
  7515. #endif /* B14400 */
  7516. #ifdef B19200
  7517.       case 1920: s = B19200; break;
  7518. #else
  7519. #ifdef EXTA
  7520.       case 1920: s = EXTA; break;
  7521. #endif /* EXTA */
  7522. #endif /* B19200 */
  7523. #ifdef B28800
  7524.       case 2880: s = B28800; break;
  7525. #endif /* B28800 */
  7526. #ifdef B38400
  7527.       case 3840: s = B38400;
  7528. #ifdef OLINUXHISPEED
  7529.         spd_flags = ~ASYNC_SPD_MASK;    /* Nonzero, but zero flags */
  7530. #endif /* OLINUXHISPEED */
  7531.     break;
  7532. #else /* B38400 not defined... */
  7533. #ifdef EXTB
  7534.       case 3840: s = EXTB; break;
  7535. #endif /* EXTB */
  7536. #endif /* B38400 */
  7537.  
  7538. #ifdef HPUX
  7539. #ifdef _B57600
  7540.       case 5760: s = _B57600; break;
  7541. #endif /* _B57600 */
  7542. #ifdef _B115200
  7543.       case 11520: s = _B115200; break;
  7544. #endif /* _B115200 */
  7545. #else
  7546. #ifdef OLINUXHISPEED
  7547. /*
  7548.   This bit from <carlo@sg.tn.tudelft.nl>:
  7549.   "Only note to make is maybe this: When the ASYNC_SPD_CUST flags are set then
  7550.   setting the speed to 38400 will set the custom speed (and ttgspd returns
  7551.   38400), but speeds 57600 and 115200 won't work any more because I didn't
  7552.   want to mess up the speed flags when someone is doing sophisticated stuff
  7553.   like custom speeds..."
  7554. */
  7555.       case 5760: s = B38400; spd_flags = ASYNC_SPD_HI; break;
  7556.       case 11520: s = B38400; spd_flags = ASYNC_SPD_VHI; break;
  7557. #else
  7558. #ifdef B57600
  7559.       case 5760: s = B57600; break;
  7560. #endif /* B57600 */
  7561. #ifdef B76800
  7562.       case 7680: s = B76800; break;
  7563. #endif /* B76800 */
  7564. #ifdef B115200
  7565.       case 11520: s = B115200; break;
  7566. #endif /* B115200 */
  7567. #endif /* OLINUXHISPEED */
  7568. #ifdef B153600
  7569.       case 15360: s = B153600; break;
  7570. #endif /* B153600 */
  7571. #ifdef B230400
  7572.       case 23040: s = B230400; break;
  7573. #endif /* B230400 */
  7574. #ifdef B307200
  7575.       case 30720: s = B307200; break;
  7576. #endif /* B307200 */
  7577. #ifdef B460800
  7578.       case 46080: s = B460800; break;
  7579. #endif /* 460800 */
  7580. #ifdef B921600
  7581.       case 92160: s = B921600; break;
  7582. #endif /* B921600 */
  7583. #endif /* HPUX */
  7584.       default:
  7585.     ok = 0;                /* Good speed not found, so not ok */
  7586.     break;
  7587.     }
  7588.     debug(F101,"ttsspd ok","",ok);
  7589.     debug(F101,"ttsspd s","",s);
  7590.  
  7591.     if (!ok) {
  7592.     debug(F100,"ttsspd fails","",0);
  7593.     return(-1);
  7594.     } else {
  7595.     if (!s2) s2 = s;        /* Set input speed */
  7596. #ifdef Plan9
  7597.     if (p9ttsspd(cps) < 0)
  7598.       return(-1);
  7599. #else
  7600. #ifdef BSD44ORPOSIX
  7601.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  7602.     debug(F101,"ttsspd tcgetattr","",x);
  7603.     if (x < 0)
  7604.       return(-1);
  7605. #ifdef OLINUXHISPEED
  7606.     debug(F101,"ttsspd spd_flags","",spd_flags);
  7607.     if (spd_flags && spd_flags != ASYNC_SPD_CUST) {
  7608.         if (ioctl(ttyfd, TIOCGSERIAL, &serinfo) < 0) {
  7609.         debug(F100,"ttsspd: TIOCGSERIAL failed","",0);
  7610.         return(-1);
  7611.         } else debug(F100,"ttsspd: TIOCGSERIAL ok","",0);
  7612.         serinfo.flags &= ~ASYNC_SPD_MASK;
  7613.         serinfo.flags |= (spd_flags & ASYNC_SPD_MASK);
  7614.         if (ioctl(ttyfd, TIOCSSERIAL, &serinfo) < 0)
  7615.           return(-1);
  7616.     }
  7617. #endif /* OLINUXHISPEED */
  7618.     cfsetospeed(&ttcur,s);
  7619.     cfsetispeed(&ttcur,s2);
  7620.     cfsetospeed(&ttraw,s);
  7621.     cfsetispeed(&ttraw,s2);
  7622.     cfsetospeed(&tttvt,s);
  7623.     cfsetispeed(&tttvt,s2);
  7624.     cfsetospeed(&ttold,s);
  7625.     cfsetispeed(&ttold,s2);
  7626.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  7627.     debug(F101,"ttsspd tcsetattr","",x);
  7628.     if (x < 0) return(-1);
  7629. #else
  7630. #ifdef ATTSV
  7631.     if (cps == 888) return(-1);    /* No split speeds, sorry. */
  7632.     x = ioctl(ttyfd,TCGETA,&ttcur);
  7633.     debug(F101,"ttsspd TCGETA ioctl","",x);
  7634.     if (x < 0) return(-1);
  7635.     ttcur.c_cflag &= ~CBAUD;
  7636.     ttcur.c_cflag |= s;
  7637.     tttvt.c_cflag &= ~CBAUD;
  7638.     tttvt.c_cflag |= s;
  7639.     ttraw.c_cflag &= ~CBAUD;
  7640.     ttraw.c_cflag |= s;
  7641.     ttold.c_cflag &= ~CBAUD;
  7642.     ttold.c_cflag |= s;
  7643.     x = ioctl(ttyfd,TCSETAW,&ttcur);
  7644.     debug(F101,"ttsspd TCSETAW ioctl","",x);
  7645.     if (x < 0) return(-1);
  7646. #else
  7647. #ifdef BELLV10
  7648.     x = ioctl(ttyfd,TIOCGDEV,&tdcur);
  7649.     debug(F101,"ttsspd TIOCGDEV ioctl","",x);
  7650.     if (x < 0) return(-1);
  7651.     tdcur.ispeed = s2;
  7652.     tdcur.ospeed = s;
  7653.     errno = 0;
  7654.     ok = ioctl(ttyfd,TIOCSDEV,&tdcur);
  7655.     debug(F101,"ttsspd BELLV10 ioctl","",ok);
  7656.     if (ok < 0) {
  7657.         perror(ttnmsv);
  7658.         debug(F101,"ttsspd BELLV10 errno","",ok);
  7659.         return(-1);
  7660.     }
  7661. #else
  7662.     x = gtty(ttyfd,&ttcur);
  7663.     debug(F101,"ttsspd gtty","",x);
  7664.     if (x < 0) return(-1);
  7665.     ttcur.sg_ospeed = s; ttcur.sg_ispeed = s2;
  7666.     tttvt.sg_ospeed = s; tttvt.sg_ispeed = s2;
  7667.     ttraw.sg_ospeed = s; ttraw.sg_ispeed = s2;
  7668.     ttold.sg_ospeed = s; ttold.sg_ispeed = s2;
  7669.     x = stty(ttyfd,&ttcur);
  7670.     debug(F101,"ttsspd stty","",x);
  7671.     if (x < 0) return(-1);
  7672. #endif /* BELLV10 */
  7673. #endif /* ATTSV */
  7674. #endif /* BSD44ORPOSIX */
  7675. #endif /* Plan9 */
  7676.     }
  7677.     return(1);                /* Return 1 = success. */
  7678. #endif /* USETCSETSPEED */
  7679. }
  7680.  
  7681. #endif /* NOLOCAL */
  7682.  
  7683. /* C O N G S P D  -  Get speed of console terminal  */
  7684.  
  7685. long
  7686. congspd() {
  7687. /*
  7688.   This is a disgusting hack.  The right way to do this would be to pass an
  7689.   argument to ttgspd(), but then we'd need to change the Kermit API and
  7690.   all of the ck?tio.c modules.  (Currently used only for rlogin.)
  7691. */
  7692.     int t1;
  7693.     long spd;
  7694. #ifdef NETCONN
  7695.     int t2 = netconn;
  7696.     netconn = 0;
  7697. #endif /* NETCONN */
  7698.     t1 = ttyfd;
  7699.     ttyfd = -1;
  7700.     spd = ttgspd();
  7701.     debug(F101,"congspd","",spd);
  7702. #ifdef NETCONN
  7703.     netconn = t2;
  7704. #endif /* NETCONN */
  7705.     ttyfd = t1;
  7706.     return(spd);
  7707. }
  7708.  
  7709. /*  T T S P D L I S T  -- Get list of serial speeds allowed on this platform */
  7710.  
  7711. #define NSPDLIST 64
  7712. static long spdlist[NSPDLIST];
  7713. /*
  7714.   As written, this picks up the speeds known at compile time, and thus
  7715.   apply to the system where C-Kermit was built, rather than to the one where
  7716.   it is running.  Suggestions for improvement are always welcome.
  7717. */
  7718. long *
  7719. ttspdlist() {
  7720.     int i;
  7721.     for (i = 0; i < NSPDLIST; i++)    /* Initialize the list */
  7722.       spdlist[i] = -1L;
  7723.     i = 1;
  7724.  
  7725. #ifdef USETCSETSPEED            /* No way to find out what's legal */
  7726.     debug(F100,"ttspdlist USETCSETSPEED","",0);
  7727.     spdlist[i++] = 50L;
  7728. #ifndef UW7
  7729.     spdlist[i++] = 75L;
  7730. #endif /* UW7 */
  7731.     spdlist[i++] = 110L;
  7732. #ifndef UW7
  7733.     spdlist[i++] = 134L;
  7734. #endif /* UW7 */
  7735.     spdlist[i++] = 150L;
  7736.     spdlist[i++] = 200L;
  7737.     spdlist[i++] = 300L;
  7738.     spdlist[i++] = 600L;
  7739.     spdlist[i++] = 1200L;
  7740.     spdlist[i++] = 1800L;
  7741.     spdlist[i++] = 2400L;
  7742.     spdlist[i++] = 4800L;
  7743.     spdlist[i++] = 8880L;
  7744.     spdlist[i++] = 9600L;
  7745.     spdlist[i++] = 14400L;
  7746.     spdlist[i++] = 19200L;
  7747.     spdlist[i++] = 28800L;
  7748. #ifndef UW7
  7749.     spdlist[i++] = 33600L;
  7750. #endif /* UW7 */
  7751.     spdlist[i++] = 38400L;
  7752.     spdlist[i++] = 57600L;
  7753.     spdlist[i++] = 76800L;
  7754.     spdlist[i++] = 115200L;
  7755. #ifndef UW7
  7756.     spdlist[i++] = 153600L;
  7757.     spdlist[i++] = 230400L;
  7758.     spdlist[i++] = 307200L;
  7759.     spdlist[i++] = 460800L;
  7760.     spdlist[i++] = 921600L;
  7761. #endif /* UW7 */
  7762.  
  7763. #else  /* USETCSETSPEED */
  7764.  
  7765.     debug(F100,"ttspdlist no USETCSETSPEED","",0);
  7766.  
  7767. #ifdef B50
  7768.     debug(F101,"ttspdlist B50","",B50);
  7769.     spdlist[i++] = 50L;
  7770. #endif /* B50 */
  7771. #ifdef B75
  7772.     debug(F101,"ttspdlist B75","",B75);
  7773.     spdlist[i++] = 75L;
  7774. #endif /* B75 */
  7775. #ifdef B110
  7776.     debug(F101,"ttspdlist B110","",B110);
  7777.     spdlist[i++] = 110L;
  7778. #endif /* B110 */
  7779. #ifdef B134
  7780.     debug(F101,"ttspdlist B134","",B134);
  7781.     spdlist[i++] = 134L;
  7782. #endif /* B134 */
  7783. #ifdef B150
  7784.     debug(F101,"ttspdlist B150","",B150);
  7785.     spdlist[i++] = 150L;
  7786. #endif /* B150 */
  7787. #ifdef B200
  7788.     debug(F101,"ttspdlist B200","",B200);
  7789.     spdlist[i++] = 200L;
  7790. #endif /* B200 */
  7791. #ifdef B300
  7792.     debug(F101,"ttspdlist B300","",B300);
  7793.     spdlist[i++] = 300L;
  7794. #endif /* B300 */
  7795. #ifdef B600
  7796.     debug(F101,"ttspdlist B600","",B600);
  7797.     spdlist[i++] = 600L;
  7798. #endif /* B600 */
  7799. #ifdef B1200
  7800.     debug(F101,"ttspdlist B1200","",B1200);
  7801.     spdlist[i++] = 1200L;
  7802. #endif /* B1200 */
  7803. #ifdef B1800
  7804.     debug(F101,"ttspdlist B1800","",B1800);
  7805.     spdlist[i++] = 1800L;
  7806. #endif /* B1800 */
  7807. #ifdef B2400
  7808.     debug(F101,"ttspdlist B2400","",B2400);
  7809.     spdlist[i++] = 2400L;
  7810. #endif /* B2400 */
  7811. #ifdef B4800
  7812.     debug(F101,"ttspdlist B4800","",B4800);
  7813.     spdlist[i++] = 4800L;
  7814. #endif /* B4800 */
  7815. #ifdef B9600
  7816.     debug(F101,"ttspdlist B9600","",B9600);
  7817.     spdlist[i++] = 9600L;
  7818. #endif /* B9600 */
  7819. #ifdef B14400
  7820.     debug(F101,"ttspdlist B14400","",B14400);
  7821.     spdlist[i++] = 14400L;
  7822. #endif /* B14400 */
  7823. #ifdef B19200
  7824.     debug(F101,"ttspdlist B19200","",B19200);
  7825.     spdlist[i++] = 19200L;
  7826. #else
  7827. #ifdef EXTA
  7828.     debug(F101,"ttspdlist EXTA","",EXTA);
  7829.     spdlist[i++] = 19200L;
  7830. #endif /* EXTA */
  7831. #endif /* B19200 */
  7832. #ifdef B28800
  7833.     debug(F101,"ttspdlist B28800","",B28800);
  7834.     spdlist[i++] = 28800L;
  7835. #endif /* B28800 */
  7836. #ifdef B33600
  7837.     debug(F101,"ttspdlist B33600","",B33600);
  7838.     spdlist[i++] = 33600L;
  7839. #endif /* B33600 */
  7840. #ifdef B38400
  7841.     debug(F101,"ttspdlist B38400","",B38400);
  7842.     spdlist[i++] = 38400L;
  7843. #else
  7844. #ifdef EXTB
  7845.     debug(F101,"ttspdlist EXTB","",EXTB);
  7846.     spdlist[i++] = 38400L;
  7847. #endif /* EXTB */
  7848. #endif /* B38400 */
  7849. #ifdef _B57600
  7850.     debug(F101,"ttspdlist _B57600","",_B57600);
  7851.     spdlist[i++] = 57600L;
  7852. #else
  7853. #ifdef B57600
  7854.     debug(F101,"ttspdlist B57600","",B57600);
  7855.     spdlist[i++] = 57600L;
  7856. #endif /* B57600 */
  7857. #endif /* _B57600 */
  7858. #ifdef B76800
  7859.     debug(F101,"ttspdlist B76800","",B76800);
  7860.     spdlist[i++] = 76800L;
  7861. #endif /* B76800 */
  7862. #ifdef _B115200
  7863.     debug(F101,"ttspdlist _B115200","",_B115200);
  7864.     spdlist[i++] = 115200L;
  7865. #else
  7866. #ifdef B115200
  7867.     debug(F101,"ttspdlist B115200","",B115200);
  7868.     spdlist[i++] = 115200L;
  7869. #endif /* B115200 */
  7870. #endif /* _B115200 */
  7871. #ifdef B153600
  7872.     debug(F101,"ttspdlist B153600","",B153600);
  7873.     spdlist[i++] = 153600L;
  7874. #endif /* B153600 */
  7875. #ifdef B230400
  7876.     debug(F101,"ttspdlist B230400","",B230400);
  7877.     spdlist[i++] = 230400L;
  7878. #endif /* B230400 */
  7879. #ifdef B307200
  7880.     debug(F101,"ttspdlist B307200","",B307200);
  7881.     spdlist[i++] = 307200L;
  7882. #endif /* B307200 */
  7883. #ifdef B460800
  7884.     debug(F101,"ttspdlist B460800","",B460800);
  7885.     spdlist[i++] = 460800L;
  7886. #endif /* B460800 */
  7887. #ifdef B921600
  7888.     debug(F101,"ttspdlist B921600","",B921600);
  7889.     spdlist[i++] = 921600L;
  7890. #endif /* B921600 */
  7891. #endif /* USETCSETSPEED */
  7892.     spdlist[0] = i - 1;            /* Return count in 0th element */
  7893.     debug(F111,"ttspdlist spdlist","0",spdlist[0]);
  7894.     return((long *)spdlist);
  7895. }
  7896.  
  7897. /* T T G S P D  -  Get speed of currently selected tty line  */
  7898.  
  7899. /*
  7900.   Unreliable.  After SET LINE, it returns an actual speed, but not necessarily
  7901.   the real speed.  On some systems, it returns the line's nominal speed, from
  7902.   /etc/ttytab.  Even if you SET SPEED to something else, this function might
  7903.   not notice.
  7904. */
  7905. long
  7906. ttgspd() {                /* Get current serial device speed */
  7907. #ifdef NOLOCAL
  7908.     return(-1L);
  7909. #else
  7910. #ifdef POSIX
  7911.     speed_t                /* Should be unsigned */
  7912. #else
  7913.     int                    /* Isn't unsigned */
  7914. #endif /* POSIX */
  7915.       s;
  7916.     int x;
  7917.     long ss;
  7918. #ifdef OLINUXHISPEED
  7919.     unsigned int spd_flags = 0;
  7920.     struct serial_struct serinfo;
  7921. #endif /* OLINUXHISPEED */
  7922.  
  7923. #ifdef NETCONN
  7924.     if (netconn) {
  7925. #ifdef TN_COMPORT
  7926.     if (istncomport())
  7927.       return(tnc_get_baud());
  7928.     else
  7929. #endif /* TN_COMPORT */
  7930.       return(-1);            /* -1 if network connection */
  7931.     }
  7932. #endif /* NETCONN */
  7933. #ifdef NETCMD
  7934.     if (ttpipe) return(-1);
  7935. #endif /* NETCMD */
  7936. #ifdef NETPTY
  7937.     if (ttpty) return(-1);
  7938. #endif /* NETPTY */
  7939.  
  7940.     debug(F101,"ttgspd ttyfd","",ttyfd);
  7941.  
  7942. #ifdef USETCSETSPEED
  7943.  
  7944.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  7945.     debug(F101,"ttgspd tcgetattr","",x);
  7946.     if (x < 0)
  7947.       return(-1);
  7948.     errno = 0;
  7949.     s = tcgetspeed(TCS_ALL, &ttcur);
  7950.     debug(F101,"ttsspd TCGETSPEED speed","",s);
  7951.     if (s == 0) {
  7952.     long s1, s2;
  7953.     s1 = tcgetspeed(TCS_IN, &ttcur);
  7954.     s2 = tcgetspeed(TCS_OUT, &ttcur);
  7955.     if (s1 == 1200L && s2 == 75L)
  7956.       return(8880L);
  7957.     }
  7958. #ifdef DEBUG
  7959.     if (errno & deblog) {
  7960.     debug(F101,"ttsspd TCGETSPEED errno","",errno);
  7961.     }
  7962. #endif /* DEBUG */
  7963.     return(s);
  7964.  
  7965. #else  /* Not USETCSETSPEED */
  7966.  
  7967. #ifdef Plan9
  7968.     if (ttyfd < 0)
  7969.       ss = -1;
  7970.     else
  7971.       ss = ttylastspeed;
  7972. #else
  7973. #ifdef OLINUXHISPEED
  7974.     debug(F100,"ttgspd Linux OLINUXHISPEED","",0);
  7975. #endif /* OLINUXHISPEED */
  7976.  
  7977.     if (ttyfd < 0) {
  7978. #ifdef BSD44ORPOSIX
  7979.     s = cfgetospeed(&ccold);
  7980.     debug(F101,"ttgspd cfgetospeed 1 POSIX","",s);
  7981. #else
  7982. #ifdef ATTSV
  7983.     s = ccold.c_cflag & CBAUD;
  7984.     debug(F101,"ttgspd c_cflag CBAUD 1 ATTSV","",s);
  7985. #else
  7986.     s = ccold.sg_ospeed;        /* (obtained by congm()) */
  7987.     debug(F101,"ttgspd sg_ospeed 1","",s);
  7988. #endif /* ATTSV */
  7989. #endif /* BSD44POSIX */
  7990.  
  7991.     } else {
  7992. #ifdef BSD44ORPOSIX
  7993.     if (tcgetattr(ttyfd,&ttcur) < 0) return(-1);
  7994.     s = cfgetospeed(&ttcur);
  7995.     debug(F101,"ttgspd cfgetospeed 2 BSDORPOSIX","",s);
  7996. #ifdef OLINUXHISPEED
  7997.     if (ioctl(ttyfd,TIOCGSERIAL,&serinfo) > -1)
  7998.       spd_flags = serinfo.flags & ASYNC_SPD_MASK;
  7999.     debug(F101,"ttgspd spd_flags","",spd_flags);
  8000. #endif /* OLINUXHISPEED */
  8001. #else
  8002. #ifdef ATTSV
  8003.     x = ioctl(ttyfd,TCGETA,&ttcur);
  8004.     debug(F101,"ttgspd ioctl 2 ATTSV x","",x);
  8005.     debug(F101,"ttgspd ioctl 2 ATTSV errno","",errno);
  8006.     if (x < 0) return(-1);
  8007.     s = ttcur.c_cflag & CBAUD;
  8008.     debug(F101,"ttgspd ioctl 2 ATTSV speed","",s);
  8009. #else
  8010. #ifdef BELLV10
  8011.     x = ioctl(ttyfd,TIOCGDEV,&tdcur);
  8012.     debug(F101,"ttgspd ioctl 2 BELLV10 x","",x);
  8013.     if (x < 0) return(-1);
  8014.     s = tdcur.ospeed;
  8015.     debug(F101,"ttgspd ioctl 2 BELLV10 speed","",s);
  8016. #else
  8017.     x = gtty(ttyfd,&ttcur);
  8018.     debug(F101,"ttgspd gtty 2 x","",x);
  8019.     debug(F101,"ttgspd gtty 2 errno","",errno);
  8020.     if (x < 0) return(-1);
  8021.     s = ttcur.sg_ospeed;
  8022.     debug(F101,"ttgspd gtty 2 speed","",s);
  8023. #endif /* BELLV10 */
  8024. #endif /* ATTSV */
  8025. #endif /* BSD44ORPOSIX */
  8026.     }
  8027.     debug(F101,"ttgspd code","",s);
  8028. #ifdef OLINUXHISPEED
  8029.     debug(F101,"ttgspd spd_flags","",spd_flags);
  8030. #endif /* OLINUXHISPEED */
  8031.     switch (s) {
  8032. #ifdef B0
  8033.       case B0:    ss = 0L; break;
  8034. #endif /* B0 */
  8035.  
  8036. #ifndef MINIX
  8037. /*
  8038.  MINIX defines the Bxx symbols to be bps/100, so B50==B75, B110==B134==B150,
  8039.  etc, making for many "duplicate case in switch" errors, which are fatal.
  8040. */
  8041. #ifdef B50
  8042.       case B50:   ss = 50L; break;
  8043. #endif /* B50 */
  8044. #ifdef B75
  8045.       case B75:   ss = 75L; break;
  8046. #endif /* B75 */
  8047. #endif /* MINIX */
  8048.  
  8049. #ifdef B110
  8050.       case B110:  ss = 110L; break;
  8051. #endif /* B110 */
  8052.  
  8053. #ifndef MINIX
  8054. #ifdef B134
  8055.       case B134:  ss = 134L; break;
  8056. #endif /* B134 */
  8057. #ifdef B150
  8058.       case B150:  ss = 150L; break;
  8059. #endif /* B150 */
  8060. #endif /* MINIX */
  8061.  
  8062. #ifdef B200
  8063.       case B200:  ss = 200L; break;
  8064. #endif /* B200 */
  8065.  
  8066. #ifdef B300
  8067.       case B300:  ss = 300L; break;
  8068. #endif /* B300 */
  8069.  
  8070. #ifdef B600
  8071.       case B600:  ss = 600L; break;
  8072. #endif /* B600 */
  8073.  
  8074. #ifdef B1200
  8075.       case B1200: ss = 1200L; break;
  8076. #endif /* B1200 */
  8077.  
  8078. #ifdef B1800
  8079.       case B1800: ss = 1800L; break;
  8080. #endif /* B1800 */
  8081.  
  8082. #ifdef B2400
  8083.       case B2400: ss = 2400L; break;
  8084. #endif /* B2400 */
  8085.  
  8086. #ifdef B4800
  8087.       case B4800: ss = 4800L; break;
  8088. #endif /* B4800 */
  8089.  
  8090. #ifdef B7200
  8091.       case B7200: ss = 7200L; break;
  8092. #endif /* B7200 */
  8093.  
  8094. #ifdef B9600
  8095.       case B9600: ss = 9600L; break;
  8096. #endif /* B9600 */
  8097.  
  8098. #ifdef B19200
  8099.       case B19200: ss = 19200L; break;
  8100. #else
  8101. #ifdef EXTA
  8102.       case EXTA: ss = 19200L; break;
  8103. #endif /* EXTA */
  8104. #endif /* B19200 */
  8105.  
  8106. #ifdef MINIX2
  8107. /* End of hack to make MINIX2 use MINIX1 speed setting */
  8108. #undef MINIX
  8109. #endif /* MINIX2 */
  8110.  
  8111. #ifndef MINIX
  8112. #ifdef B38400
  8113.       case B38400:
  8114.         ss = 38400L;
  8115. #ifdef OLINUXHISPEED
  8116.         switch(spd_flags) {
  8117.           case ASYNC_SPD_HI:  ss =  57600L; break;
  8118.           case ASYNC_SPD_VHI: ss = 115200L; break;
  8119.     }
  8120. #endif /* OLINUXHISPEED */
  8121.         break;
  8122. #else
  8123. #ifdef EXTB
  8124.       case EXTB: ss = 38400L; break;
  8125. #endif /* EXTB */
  8126. #endif /* B38400 */
  8127. #endif /* MINIX */
  8128.  
  8129. #ifdef HPUX
  8130. #ifdef _B57600
  8131.       case _B57600: ss = 57600L; break;
  8132. #endif /* _B57600 */
  8133. #ifdef _B115200
  8134.       case _B115200: ss = 115200L; break;
  8135. #endif /* _B115200 */
  8136. #else
  8137. #ifdef B57600
  8138.       case B57600: ss = 57600L; break;
  8139. #endif /* B57600 */
  8140. #ifdef B76800
  8141.       case B76800: ss = 76800L; break;
  8142. #endif /* B76800 */
  8143. #ifdef B115200
  8144.       case B115200: ss = 115200L; break;
  8145. #endif /* B115200 */
  8146. #ifdef B153600
  8147.       case B153600: ss = 153600L; break;
  8148. #endif /* B153600 */
  8149. #ifdef B230400
  8150.       case B230400: ss = 230400L; break;
  8151. #endif /* B230400 */
  8152. #ifdef B307200
  8153.       case B307200: ss = 307200L; break;
  8154. #endif /* B307200 */
  8155. #ifdef B460800
  8156.       case B460800: ss = 460800L; break;
  8157. #endif /* B460800 */
  8158. #endif /* HPUX */
  8159. #ifdef B921600
  8160.       case B921600: ss = 921600L; break;
  8161. #endif /* B921600 */
  8162.       default:
  8163.     ss = -1; break;
  8164.     }
  8165. #endif /* Plan9 */
  8166.     debug(F101,"ttgspd speed","",ss);
  8167.     return(ss);
  8168.  
  8169. #endif /* USETCSETSPEED */
  8170. #endif /* NOLOCAL */
  8171. }
  8172. #ifdef MINIX2                /* Another hack alert */
  8173. #define MINIX
  8174. #endif /* MINIX2 */
  8175.  
  8176. /*
  8177.   FIONREAD data type...  This has been defined as "long" for many, many
  8178.   years, and it worked OK until 64-bit platforms appeared.  Thus we use
  8179.   int for 64-bit platforms, but keep long for the others.  If we changed
  8180.   the default PEEKTYPE to int, this would probably break 16-bit builds
  8181.   (note that sizeof(long) == sizeof(int) on most 32-bit platforms), many
  8182.   of which we have no way of testing any more.  Therefore, do not change
  8183.   the default definition of PEEKTYPE -- only add exceptions to it as needed.
  8184. */
  8185. #ifdef COHERENT
  8186. #ifdef FIONREAD
  8187. #undef FIONREAD
  8188. #endif /* FIONREAD */
  8189. /* #define FIONREAD TIOCQUERY */
  8190. /* #define PEEKTYPE int */
  8191. #else  /* Not COHERENT... */
  8192.  
  8193. #ifdef OSF32                /* Digital UNIX 3.2 or higher */
  8194. #define PEEKTYPE int
  8195. #else
  8196. #define PEEKTYPE long            /* Elsewhere (see notes above) */
  8197. #endif /* OSF32 */
  8198. #endif /* COHERENT */
  8199.  
  8200. /* ckumyr.c by Kristoffer Eriksson, ske@pkmab.se, 15 Mar 1990. */
  8201.  
  8202. #ifdef MYREAD
  8203.  
  8204. /* Private buffer for myread() and its companions.  Not for use by anything
  8205.  * else.  ttflui() is allowed to reset them to initial values.  ttchk() is
  8206.  * allowed to read my_count.
  8207.  *
  8208.  * my_item is an index into mybuf[].  Increment it *before* reading mybuf[].
  8209.  *
  8210.  * A global parity mask variable could be useful too.  We could use it to
  8211.  * let myread() strip the parity on its own, instead of stripping sign
  8212.  * bits as it does now.
  8213.  */
  8214. #ifdef BIGBUFOK
  8215. #define MYBUFLEN 32768
  8216. #else
  8217. #ifdef pdp11
  8218. #define MYBUFLEN 256
  8219. #else
  8220. #define MYBUFLEN 1024
  8221. #endif /* pdp11 */
  8222. #endif /* BIGBUFOK */
  8223.  
  8224. #ifdef ANYX25
  8225. #undef MYBUFLEN
  8226. #define MYBUFLEN 256
  8227. /*
  8228.   On X.25 connections, there is an extra control byte at the beginning.
  8229. */
  8230. static CHAR x25buf[MYBUFLEN+1];        /* Communication device input buffer */
  8231. static CHAR  *mybuf = x25buf+1;
  8232. #else
  8233. static CHAR mybuf[MYBUFLEN];
  8234. #endif /* ANYX25 */
  8235.  
  8236. static int my_count = 0;        /* Number of chars still in mybuf */
  8237. static int my_item = -1;        /* Last index read from mybuf[]   */
  8238.  
  8239. /*  T T P E E K  --  Peek into our internal communications input buffers. */
  8240.  
  8241. /*
  8242.   NOTE: This routine is peculiar to UNIX, and is used only by the
  8243.   select()-based CONNECT module, ckucns.c.  It need not be replicated in
  8244.   the ck?tio.c of other platforms.
  8245. */
  8246. int
  8247. ttpeek() {
  8248. #ifdef TTLEBUF
  8249.     int rc = 0;
  8250.     if (ttpush >= 0)
  8251.       rc++;
  8252.     rc += le_inbuf();
  8253.     if (rc > 0)
  8254.       return(rc);
  8255.     else
  8256. #endif /* TTLEBUF */
  8257.  
  8258. #ifdef MYREAD
  8259.     return(my_count);
  8260. #else
  8261.     return(0);
  8262. #endif /* MYREAD */
  8263. }
  8264.  
  8265. /* myread() -- Efficient read of one character from communications line.
  8266.  *
  8267.  * NOTE: myread() and its helpers mygetbuf() and myfillbuf() return raw
  8268.  * bytes from connection, so when the connection is encrypted, these bytes
  8269.  * must be decrypted.
  8270.  *
  8271.  * Uses a private buffer to minimize the number of expensive read() system
  8272.  * calls.  Essentially performs the equivalent of read() of 1 character, which
  8273.  * is then returned.  By reading all available input from the system buffers
  8274.  * to the private buffer in one chunk, and then working from this buffer, the
  8275.  * number of system calls is reduced in any case where more than one character
  8276.  * arrives during the processing of the previous chunk, for instance high
  8277.  * baud rates or network type connections where input arrives in packets.
  8278.  * If the time needed for a read() system call approaches the time for more
  8279.  * than one character to arrive, then this mechanism automatically compensates
  8280.  * for that by performing bigger read()s less frequently.  If the system load
  8281.  * is high, the same mechanism compensates for that too.
  8282.  *
  8283.  * myread() is a macro that returns the next character from the buffer.  If the
  8284.  * buffer is empty, mygetbuf() is called.  See mygetbuf() for possible error
  8285.  * returns.
  8286.  *
  8287.  * This should be efficient enough for any one-character-at-a-time loops.
  8288.  * For even better efficiency you might use memcpy()/bcopy() or such between
  8289.  * buffers (since they are often better optimized for copying), but it may not
  8290.  * be worth it if you have to take an extra pass over the buffer to strip
  8291.  * parity and check for CTRL-C anyway.
  8292.  *
  8293.  * Note that if you have been using myread() from another program module, you
  8294.  * may have some trouble accessing this macro version and the private variables
  8295.  * it uses.  In that case, just add a function in this module, that invokes the
  8296.  * macro.
  8297.  */
  8298. #define myread() (--my_count < 0 ? mygetbuf() : 255 & (int)mybuf[++my_item])
  8299.  
  8300. /* Specification: Push back up to one character onto myread()'s queue.
  8301.  *
  8302.  * This implementation: Push back characters into mybuf. At least one character
  8303.  * must have been read through myread() before myunrd() may be used.  After
  8304.  * EOF or read error, again, myunrd() can not be used.  Sometimes more than
  8305.  * one character can be pushed back, but only one character is guaranteed.
  8306.  * Since a previous myread() must have read its character out of mybuf[],
  8307.  * that guarantees that there is space for at least one character.  If push
  8308.  * back was really needed after EOF, a small addition could provide that.
  8309.  *
  8310.  * As of 02/2007 myunrd() is used by ttinl().
  8311.  */
  8312. VOID
  8313. #ifdef CK_ANSIC
  8314. myunrd(CHAR ch)
  8315. #else
  8316. myunrd(ch) CHAR ch;
  8317. #endif    /* CK_ANSIC */
  8318. {
  8319.     if (my_item >= 0) {
  8320.     mybuf[my_item--] = ch;
  8321.     ++my_count;
  8322.     }
  8323. }
  8324.  
  8325. /*  T T P U S H B A C K  --  Put n bytes back into the myread buffer */
  8326.  
  8327. static CHAR * pushbuf = NULL;
  8328. /* static int pushed = 0; */
  8329.  
  8330. int
  8331. ttpushback(s,n) CHAR * s; int n; {
  8332.     debug(F101,"ttpushback n","",n);
  8333.     if (pushbuf || n > MYBUFLEN || n < 1)
  8334.       return(-1);
  8335.     debug(F101,"ttpushback my_count","",my_count);
  8336.     if (my_count > 0) {
  8337.     if (!(pushbuf = (CHAR *)malloc(n+1)))
  8338.       return(-1);
  8339.     memcpy(pushbuf,mybuf,my_count);
  8340.     /* pushed = my_count; */ /* (set but never used) */
  8341.     }
  8342.     memcpy(mybuf,s,n);
  8343.     my_count = n;
  8344.     my_item = -1;
  8345.     return(0);
  8346. }
  8347.  
  8348. /* mygetbuf() -- Fill buffer for myread() and return first character.
  8349.  *
  8350.  * This function is what myread() uses when it can't get the next character
  8351.  * directly from its buffer.  First, it calls a system dependent myfillbuf()
  8352.  * to read at least one new character into the buffer, and then it returns
  8353.  * the first character just as myread() would have done.  This function also
  8354.  * is responsible for all error conditions that myread() can indicate.
  8355.  *
  8356.  * Returns: When OK    => a positive character, 0 or greater.
  8357.  *        When EOF    => -2.
  8358.  *        When error    => -3, error code in errno.
  8359.  *
  8360.  * Older myread()s additionally returned -1 to indicate that there was nothing
  8361.  * to read, upon which the caller would call myread() again until it got
  8362.  * something.  The new myread()/mygetbuf() always gets something.  If it
  8363.  * doesn't, then make it do so!  Any program that actually depends on the old
  8364.  * behaviour will break.
  8365.  *
  8366.  * The older version also used to return -2 both for EOF and other errors,
  8367.  * and used to set errno to 9999 on EOF.  The errno stuff is gone, EOF and
  8368.  * other errors now return different results, although Kermit currently never
  8369.  * checks to see which it was.  It just disconnects in both cases.
  8370.  *
  8371.  * Kermit lets the user use the quit key to perform some special commands
  8372.  * during file transfer.  This causes read(), and thus also mygetbuf(), to
  8373.  * finish without reading anything and return the EINTR error.  This should
  8374.  * be checked by the caller.  Mygetbuf() could retry the read() on EINTR,
  8375.  * but if there is nothing to read, this could delay Kermit's reaction to
  8376.  * the command, and make Kermit appear unresponsive.
  8377.  *
  8378.  * The debug() call should be removed for optimum performance.
  8379.  */
  8380. int
  8381. mygetbuf() {
  8382.     int x;
  8383.     errno = 0;
  8384. #ifdef DEBUG
  8385.     if (deblog && my_count > 0)
  8386.       debug(F101,"mygetbuf IMPROPERLY CALLED with my_count","",my_count);
  8387. #endif /* DEBUG */
  8388.     if (my_count <= 0)
  8389.       my_count = myfillbuf();
  8390.  
  8391. #ifdef DEBUG
  8392. #ifdef COMMENT
  8393.     if (deblog) debug(F101, "mygetbuf read", "", my_count);
  8394. #else /* COMMENT */
  8395.     if (deblog) hexdump("mygetbuf read", mybuf, my_count);
  8396. #endif /* COMMENT */
  8397. #endif /* DEBUG */
  8398.     x = my_count;
  8399.     if (my_count <= 0) {
  8400.     my_count = 0;
  8401.     my_item = -1;
  8402.     debug(F101,"mygetbuf errno","",errno);
  8403. #ifdef TCPSOCKET
  8404.     if (netconn && ttnet == NET_TCPB && errno != 0) {
  8405.         if (errno != EINTR) {
  8406.         debug(F101,"mygetbuf TCP error","",errno);
  8407.         ttclos(0);        /* Close the connection. */
  8408.         }
  8409.         return(-3);
  8410.     }
  8411. #endif /* TCPSOCKET */
  8412.     if (!netconn && xlocal && errno) {
  8413.         if (errno != EINTR) {
  8414.         debug(F101,"mygetbuf SERIAL error","",errno);
  8415.         x = -3;
  8416.         ttclos(0);        /* Close the connection. */
  8417.         }
  8418.     }
  8419.     return((x < 0) ? -3 : -2);
  8420.     }
  8421.     --my_count;
  8422.     return((unsigned)(0xff & mybuf[my_item = 0]));
  8423. }
  8424.  
  8425. /* myfillbuf():
  8426.  * System-dependent read() into mybuf[], as many characters as possible.
  8427.  *
  8428.  * Returns: OK => number of characters read, always more than zero.
  8429.  *          EOF => 0
  8430.  *          Error => -1, error code in errno.
  8431.  *
  8432.  * If there is input available in the system's buffers, all of it should be
  8433.  * read into mybuf[] and the function return immediately.  If no input is
  8434.  * available, it should wait for a character to arrive, and return with that
  8435.  * one in mybuf[] as soon as possible.  It may wait somewhat past the first
  8436.  * character, but be aware that any such delay lengthens the packet turnaround
  8437.  * time during kermit file transfers.  Should never return with zero characters
  8438.  * unless EOF or irrecoverable read error.
  8439.  *
  8440.  * Correct functioning depends on the correct tty parameters being used.
  8441.  * Better control of current parameters is required than may have been the
  8442.  * case in older Kermit releases.  For instance, O_NDELAY (or equivalent) can
  8443.  * no longer be sometimes off and sometimes on like it used to, unless a
  8444.  * special myfillbuf() is written to handle that.  Otherwise the ordinary
  8445.  * myfillbuf()s may think they have come to EOF.
  8446.  *
  8447.  * If your system has a facility to directly perform the functioning of
  8448.  * myfillbuf(), then use it.  If the system can tell you how many characters
  8449.  * are available in its buffers, then read that amount (but not less than 1).
  8450.  * If the system can return a special indication when you try to read without
  8451.  * anything to read, while allowing you to read all there is when there is
  8452.  * something, you may loop until there is something to read, but probably that
  8453.  * is not good for the system load.
  8454.  */
  8455.  
  8456. #ifdef SVORPOSIX
  8457.     /* This is for System III/V with VMIN>0, VTIME=0 and O_NDELAY off,
  8458.      * and CLOCAL set any way you like.  This way, read() will do exactly
  8459.      * what is required by myfillbuf(): If there is data in the buffers
  8460.      * of the O.S., all available data is read into mybuf, up to the size
  8461.      * of mybuf.  If there is none, the first character to arrive is
  8462.      * awaited and returned.
  8463.      */
  8464. int
  8465. myfillbuf() {
  8466.     int fd, n;
  8467. #ifdef NETCMD
  8468.     if (ttpipe)
  8469.       fd = fdin;
  8470.     else
  8471. #endif /* NETCMD */
  8472.       fd = ttyfd;
  8473.  
  8474. #ifdef sxaE50
  8475.     /* From S. Dezawa at Fujifilm in Japan.  I don't know why this is */
  8476.     /* necessary for the sxa E50, but it is. */
  8477.     return read(fd, mybuf, 255);
  8478. #else
  8479. #ifdef BEOSORBEBOX
  8480.     while (1) {
  8481. #ifdef NETCONN
  8482.         if (netconn) {
  8483.             n = netxin(sizeof(mybuf), (char *)mybuf);
  8484.             debug(F101,"BEBOX SVORPOSIX network myfillbuf","",n);
  8485.     }
  8486.         else
  8487. #endif /* NETCONN */
  8488.       n = read(fd, mybuf, sizeof(mybuf));
  8489.     debug(F101,"BEBOX SVORPOSIX notnet myfillbuf","",n);
  8490.         if (n > 0)
  8491.       return(n);
  8492.         snooze(1000.0);
  8493.     }
  8494. #else /* BEOSORBEBOX */
  8495.     errno = 0;
  8496.     /* debug(F101,"SVORPOSIX myfillbuf calling read() fd","",fd); */
  8497. #ifdef IBMX25
  8498.     if (netconn && (nettype == NET_IX25)) {
  8499.     /* can't use sizeof because mybuf is a pointer, and not an array! */
  8500.     n = x25xin( MYBUFLEN, mybuf );
  8501.     } else
  8502. #endif /* IBMX25 */
  8503.  
  8504. #ifdef CK_SSL
  8505.       if (ssl_active_flag || tls_active_flag) {
  8506.       int error, n = 0;
  8507.       debug(F100,"myfillbuf calling SSL_read() fd","",0);
  8508.       while (n == 0) {
  8509.           if (ssl_active_flag)
  8510.                 n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  8511.           else if (tls_active_flag)
  8512.                 n = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  8513.               else
  8514.         break;
  8515.           switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  8516.         case SSL_ERROR_NONE:
  8517.           if (n > 0)
  8518.                     return(n);
  8519.           if (n < 0)
  8520.                     return(-2);
  8521.           msleep(50);
  8522.           break;
  8523.         case SSL_ERROR_WANT_WRITE:
  8524.         case SSL_ERROR_WANT_READ:
  8525.           return(-1);
  8526.         case SSL_ERROR_SYSCALL:
  8527.           if (n != 0)
  8528.             return(-1);
  8529.         case SSL_ERROR_WANT_X509_LOOKUP:
  8530.         case SSL_ERROR_SSL:
  8531.         case SSL_ERROR_ZERO_RETURN:
  8532.         default:
  8533.           ttclos(0);
  8534.           return(-3);
  8535.             }
  8536.         }
  8537.     }
  8538. #endif /* CK_SSL */
  8539. #ifdef CK_KERBEROS
  8540. #ifdef KRB4
  8541. #ifdef RLOGCODE
  8542.     if (ttnproto == NP_EK4LOGIN) {
  8543.     debug(F101,"myfillbuf calling krb4_des_read() fd","",ttyfd);
  8544.         if ((n = krb4_des_read(ttyfd,(char *)mybuf,sizeof(mybuf))) < 0)
  8545.       return(-3);
  8546.         else
  8547.       return(n);
  8548.     }
  8549. #endif /* RLOGCODE */
  8550. #endif /* KRB4 */
  8551. #ifdef KRB5
  8552. #ifdef RLOGCODE
  8553.     if (ttnproto == NP_EK5LOGIN) {
  8554.     debug(F101,"myfillbuf calling krb5_des_read() fd","",ttyfd);
  8555.         if ((n = krb5_des_read(ttyfd,(char *)mybuf,sizeof(mybuf),0)) < 0)
  8556.       return(-3);
  8557.         else
  8558.       return(n);
  8559.     }
  8560. #endif /* RLOGCODE */
  8561. #ifdef KRB5_U2U
  8562.     if (ttnproto == NP_K5U2U) {
  8563.     debug(F101,"myfillbuf calling krb5_u2u_read() fd","",ttyfd);
  8564.         if ((n = krb5_u2u_read(ttyfd,(char *)mybuf,sizeof(mybuf))) < 0)
  8565.       return(-3);
  8566.         else
  8567.       return(n);
  8568.     }
  8569. #endif /* KRB5_U2U */
  8570. #endif /* KRB5 */
  8571. #endif /* CK_KERBEROS */
  8572.  
  8573. #ifdef NETPTY
  8574. #ifdef HAVE_PTYTRAP
  8575.     /* Special handling for HP-UX pty i/o */
  8576.   ptyread:
  8577.     if (ttpty && pty_trap_pending(ttyfd) > 0) {
  8578.     debug(F101,"myfillbuf calling pty_trap_handler() fd","",ttyfd);
  8579.         if (pty_trap_handler(ttyfd) > 0) {
  8580.             ttclos(0);
  8581.             return(-3);
  8582.         }
  8583.     }
  8584. #endif /* HAVE_PTYTRAP */
  8585. #endif /* NETPTY */
  8586.     debug(F101,"myfillbuf calling read() fd","",ttyfd);
  8587.     n = read(fd, mybuf, sizeof(mybuf));
  8588.     debug(F101,"SVORPOSIX myfillbuf read","",n);
  8589.     debug(F101,"SVORPOSIX myfillbuf errno","",errno);
  8590.     debug(F101,"SVORPOSIX myfillbuf ttcarr","",ttcarr);
  8591.     if (n < 1) {
  8592. #ifdef NETPTY
  8593. #ifdef HAVE_PTYTRAP
  8594.         /* When we have a PTY trap in place the connection cannot */
  8595.         /* be closed until the trap receives a close indication.  */
  8596.         if (n == 0 && ttpty)
  8597.             goto ptyread;
  8598. #endif /* HAVE_PTYTRAP */
  8599. #endif /* NETPTY */
  8600.         return(-3);
  8601.     }
  8602.     return(n);
  8603. #endif /* BEOSORBEBOX */
  8604. #endif /* sxaE50 */
  8605. }
  8606.  
  8607. #else /* not AT&T or POSIX */
  8608.  
  8609. #ifdef aegis
  8610.     /* This is quoted from the old myread().  The semantics seem to be
  8611.      * alright, but maybe errno would not need to be set even when
  8612.      * there is no error?  I don't know aegis.
  8613.      */
  8614. int
  8615. myfillbuf() {
  8616.     int count;
  8617. #ifdef NETCMD
  8618.     if (ttpipe)
  8619.       fd = fdin;
  8620.     else
  8621. #endif /* NETCMD */
  8622.       fd = ttyfd;
  8623.  
  8624.     count = ios_$get((short)fd, ios_$cond_opt, mybuf, 256L, st);
  8625.     errno = EIO;
  8626.     if (st.all == ios_$get_conditional_failed) /* get at least one */
  8627.       count = ios_$get((short)fd, 0, mybuf, 1L, st);
  8628.     if (st.all == ios_$end_of_file)
  8629.       return(-3);
  8630.     else if (st.all != status_$ok) {
  8631.     errno = EIO;
  8632.     return(-1);
  8633.     }
  8634.     return(count > 0 ? count : -3);
  8635. }
  8636. #else /* !aegis */
  8637.  
  8638. #ifdef FIONREAD
  8639.     /* This is for systems with FIONREAD.  FIONREAD returns the number
  8640.      * of characters available for reading. If none are available, wait
  8641.      * until something arrives, otherwise return all there is.
  8642.      */
  8643. int
  8644. myfillbuf() {
  8645.     PEEKTYPE avail = 0;
  8646.     int x, fd;
  8647. #ifdef NETCMD
  8648.     if (ttpipe)
  8649.       fd = fdin;
  8650.     else
  8651. #endif /* NETCMD */
  8652.       fd = ttyfd;
  8653.  
  8654. #ifdef SUNX25
  8655. /*
  8656.   SunLink X.25 support in this routine from Stefaan A. Eeckels, Eurostat (CEC).
  8657.   Depends on SunOS having FIONREAD, not because we use it, but just so this
  8658.   code is grouped correctly within the #ifdefs.  Let's hope Solaris keeps it.
  8659.  
  8660.   We call x25xin() instead of read() so that Q-Bit packets, which contain
  8661.   X.25 service-level information (e.g. PAD parameter changes), can be processed
  8662.   transparently to the upper-level code.  This is a blocking read, and so
  8663.   we depend on higher-level code (such as ttinc()) to set any necessary alarms.
  8664. */
  8665.     extern int nettype;
  8666.     if (netconn && nettype == NET_SX25) {
  8667.     while ((x = x25xin(sizeof(x25buf), x25buf)) < 1) ;
  8668.     return(x - 1);            /* "-1" compensates for extra status byte */
  8669.     }
  8670. #endif /* SUNX25 */
  8671.  
  8672. #ifdef CK_SSL
  8673.     if (ssl_active_flag || tls_active_flag) {
  8674.         int error, n = 0;
  8675.         while (n == 0) {
  8676.             if (ssl_active_flag)
  8677.           n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  8678.             else
  8679.           n = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  8680.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  8681.           case SSL_ERROR_NONE:
  8682.                 if (n > 0)
  8683.           return(n);
  8684.                 if (n < 0)
  8685.           return(-2);
  8686.                 msleep(50);
  8687.                 break;
  8688.           case SSL_ERROR_WANT_WRITE:
  8689.           case SSL_ERROR_WANT_READ:
  8690.                 return(-1);
  8691.           case SSL_ERROR_SYSCALL:
  8692.         if (n != 0)
  8693.           return(-1);
  8694.           case SSL_ERROR_WANT_X509_LOOKUP:
  8695.           case SSL_ERROR_SSL:
  8696.           case SSL_ERROR_ZERO_RETURN:
  8697.           default:
  8698.                 ttclos(0);
  8699.                 return(-2);
  8700.             }
  8701.         }
  8702.     }
  8703. #endif /* CK_SSL */
  8704. #ifdef CK_KERBEROS
  8705. #ifdef KRB4
  8706. #ifdef RLOGCODE
  8707.     if (ttnproto == NP_EK4LOGIN) {
  8708.         if ((x = krb4_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8709.       return(-1);
  8710.         else
  8711.       return(x);
  8712.     }
  8713. #endif /* RLOGCODE */
  8714. #endif /* KRB4 */
  8715. #ifdef KRB5
  8716. #ifdef RLOGCODE
  8717.     if (ttnproto == NP_EK5LOGIN) {
  8718.         if ((x = krb5_des_read(ttyfd,mybuf,sizeof(mybuf),0)) < 0)
  8719.       return(-1);
  8720.         else
  8721.       return(x);
  8722.     }
  8723. #endif /* RLOGCODE */
  8724. #ifdef KRB5_U2U
  8725.     if (ttnproto == NP_K5U2U) {
  8726.         if ((x = krb5_u2u_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8727.       return(-1);
  8728.         else
  8729.       return(x);
  8730.     }
  8731. #endif /* KRB5_U2U */
  8732. #endif /* KRB5 */
  8733. #endif /* CK_KERBEROS */
  8734.  
  8735.     errno = 0;
  8736.     debug(F101,"myfillbuf calling FIONREAD ioctl","",xlocal);
  8737.     x = ioctl(fd, FIONREAD, &avail);
  8738. #ifdef DEBUG
  8739.     if (deblog) {
  8740.     debug(F101,"myfillbuf FIONREAD","",x);
  8741.     debug(F101,"myfillbuf FIONREAD avail","",avail);
  8742.     debug(F101,"myfillbuf FIONREAD errno","",errno);
  8743.     }
  8744. #endif /* DEBUG */
  8745.     if (x < 0 || avail == 0)
  8746.       avail = 1;
  8747.  
  8748.     if (avail > MYBUFLEN)
  8749.       avail = MYBUFLEN;
  8750.  
  8751.     errno = 0;
  8752.  
  8753.     x = read(fd, mybuf, (int) avail);
  8754. #ifdef DEBUG
  8755.     if (deblog) {
  8756.     debug(F101,"myfillbuf avail","",avail);
  8757.     debug(F101,"myfillbuf read","",x);
  8758.     debug(F101,"myfillbuf read errno","",errno);
  8759.         if (x > 0)
  8760.       hexdump("myfillbuf mybuf",mybuf,x);
  8761.     }
  8762. #endif /* DEBUG */
  8763.     if (x < 1) x = -3;            /* read 0 == connection loss */
  8764.     return(x);
  8765. }
  8766.  
  8767. #else /* !FIONREAD */
  8768. /* Add other systems here, between #ifdef and #else, e.g. NETCONN. */
  8769. /* When there is no other possibility, read 1 character at a time. */
  8770. int
  8771. myfillbuf() {
  8772.     int x;
  8773.  
  8774. #ifdef CK_SSL
  8775.     if (ssl_active_flag || tls_active_flag) {
  8776.         int error, n = 0;
  8777.         while (n == 0) {
  8778.             if (ssl_active_flag)
  8779.           n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  8780.             else
  8781.           count = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  8782.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  8783.           case SSL_ERROR_NONE:
  8784.                 if (n > 0)
  8785.           return(n);
  8786.                 if (n < 0)
  8787.           return(-2);
  8788.                 msleep(50);
  8789.                 break;
  8790.           case SSL_ERROR_WANT_WRITE:
  8791.           case SSL_ERROR_WANT_READ:
  8792.                 return(-1);
  8793.           case SSL_ERROR_SYSCALL:
  8794.         if (n != 0)
  8795.           return(-1);
  8796.           case SSL_ERROR_WANT_X509_LOOKUP:
  8797.           case SSL_ERROR_SSL:
  8798.           case SSL_ERROR_ZERO_RETURN:
  8799.           default:
  8800.                 ttclos(0);
  8801.                 return(-2);
  8802.             }
  8803.         }
  8804.     }
  8805. #endif /* CK_SSL */
  8806. #ifdef CK_KERBEROS
  8807. #ifdef KRB4
  8808. #ifdef RLOGCODE
  8809.     if (ttnproto == NP_EK4LOGIN) {
  8810.         if ((len = krb4_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8811.       return(-1);
  8812.         else
  8813.       return(len);
  8814.     }
  8815. #endif /* RLOGCODE */
  8816. #endif /* KRB4 */
  8817. #ifdef KRB5
  8818. #ifdef RLOGCODE
  8819.     if (ttnproto == NP_EK5LOGIN) {
  8820.         if ((len = krb5_des_read(ttyfd,mybuf,sizeof(mybuf),0)) < 0)
  8821.       return(-1);
  8822.         else
  8823.       return(len);
  8824.     }
  8825. #endif /* RLOGCODE */
  8826. #ifdef KRB5_U2U
  8827.     if (ttnproto == NP_K5U2U) {
  8828.         if ((len = krb5_u2u_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8829.       return(-1);
  8830.         else
  8831.       return(len);
  8832.     }
  8833. #endif /* KRB5_U2U */
  8834. #endif /* KRB5 */
  8835. #endif /* CK_KERBEROS */
  8836.  
  8837. #ifdef NETCMD
  8838.     if (ttpipe)
  8839.       fd = fdin;
  8840.     else
  8841. #endif /* NETCMD */
  8842.       fd = ttyfd;
  8843.     x = read(fd, mybuf, 1);
  8844.     return(x > 0 ? x : -3);
  8845. }
  8846.  
  8847. #endif /* !FIONREAD */
  8848. #endif /* !aegis */
  8849. #endif /* !ATTSV */
  8850.  
  8851. #endif /* MYREAD */
  8852.  
  8853. #ifdef MINIX2
  8854. #undef MINIX
  8855. #endif /* MINIX2 */
  8856.  
  8857. /*  T T _ T N O P T  --  Handle Telnet negotions in incoming data */
  8858. /*
  8859.   Call with the IAC that was encountered.
  8860.   Returns:
  8861.    -3: If connection has dropped or gone bad.
  8862.    -2: On Telnet protocol error resulting in inconsistent states.
  8863.     0: If negotiation OK and caller has nothing to do.
  8864.     1: If packet start character has changed (new value is in global stchr).
  8865.   255: If there was a quoted IAC as data.
  8866.    or: Not at all if we got a legitimate Telnet Logout request.
  8867. */
  8868. #ifdef TCPSOCKET
  8869. static int
  8870. tt_tnopt(n) int n; {            /* Handle Telnet options */
  8871.     /* In case caller did not already check these conditions...  */
  8872.     if (n == IAC &&
  8873.     ((xlocal && netconn && IS_TELNET()) ||
  8874.      (!xlocal && sstelnet))) {
  8875.     extern int server;
  8876.     int tx = 0;
  8877.     debug(F100,"ttinl calling tn_doop()","",0);
  8878.     tx = tn_doop((CHAR)(n & 0xff),duplex,ttinc);
  8879.     debug(F111,"ttinl tn_doop() returned","tx",tx);
  8880.     switch (tx) {
  8881.       case 0:
  8882.         return(0);
  8883.       case -1:            /* I/O error */
  8884.         ttimoff();            /* Turn off timer */
  8885.         return(-3);
  8886.           case -2:            /* Connection failed. */
  8887.           case -3:
  8888.         ttimoff();            /* Turn off timer */
  8889.         ttclos(0);
  8890.         return(-3);
  8891.       case 1:            /* ECHO change */
  8892.         duplex = 1;
  8893.         return(0);
  8894.       case 2:            /* ECHO change */
  8895.         duplex = 0;
  8896.         return(0);
  8897.       case 3:            /* Quoted IAC */
  8898.         n = 255;
  8899.         return((unsigned)255);
  8900. #ifdef IKS_OPTION
  8901.       case 4: {
  8902.           if (TELOPT_SB(TELOPT_KERMIT).kermit.u_start && server
  8903. #ifdef IKSD
  8904.           && !inserver
  8905. #endif /* IKSD */
  8906.           ) {            /* Remote in Server mode */
  8907.           ttimoff();        /* Turn off timer */
  8908.           debug(F100,"u_start and !inserver","",0);
  8909.           return(-2);        /* End server mode */
  8910.           } else if (!TELOPT_SB(TELOPT_KERMIT).kermit.me_start &&
  8911.              server
  8912.              ) {        /* I'm no longer in Server Mode */
  8913.           debug(F100,"me_start and server","",0);
  8914.           ttimoff();
  8915.           return(-2);
  8916.           }
  8917.           return(0);
  8918.       }
  8919.       case 5: {            /* Start character change */
  8920.           /* extern CHAR stchr; */
  8921.           /* start = stchr; */
  8922.           return(1);
  8923.       }
  8924. #endif /* IKS_OPTION */
  8925.       case 6:            /* Remote Logout */
  8926.         ttimoff();
  8927.         ttclos(0);
  8928. #ifdef IKSD
  8929.         if (inserver && !local)
  8930.           doexit(GOOD_EXIT,0);
  8931.         else
  8932. #endif /* IKSD */
  8933.           return(-2);
  8934.       default:
  8935.         return(0);
  8936.     }
  8937.     } else
  8938.       return(0);
  8939. }
  8940. #endif /* TCPSOCKET */
  8941.  
  8942. /*  T T F L U I  --  Flush tty input buffer */
  8943.  
  8944. void
  8945. ttflux() {                /* But first... */
  8946. #ifdef MYREAD
  8947. /*
  8948.   Flush internal MYREAD buffer.
  8949. */
  8950. #ifdef TCPSOCKET
  8951.     int dotnopts, x;
  8952.     dotnopts = (((xlocal && netconn && IS_TELNET()) ||
  8953.          (!xlocal && sstelnet)));
  8954. #endif /* TCPSOCKET */
  8955.     debug(F101,"ttflux my_count","",my_count);
  8956. #ifdef TCPSOCKET
  8957.     if (dotnopts) {
  8958.     CHAR ch = '\0';
  8959.         while (my_count > 0) {
  8960.         ch = myread();
  8961. #ifdef CK_ENCRYPTION
  8962.             if (TELOPT_U(TELOPT_ENCRYPTION))
  8963.           ck_tn_decrypt((char *)&ch,1);
  8964. #endif /* CK_ENCRYPTION */
  8965.             if (ch == IAC)
  8966.           x = tt_tnopt(ch);
  8967.         }
  8968.     } else
  8969. #endif /* TCPSOCKET */
  8970. #ifdef COMMENT
  8971. #ifdef CK_ENCRYPTION
  8972.     if (TELOPT_U(TELOPT_ENCRYPTION) && my_count > 0)
  8973.       ck_tn_decrypt(&mybuf[my_item+1],my_count);
  8974. #endif /* CK_ENCRYPTION */
  8975. #endif /* COMMENT */
  8976.     my_count = 0;            /* Reset count to zero */
  8977.     my_item = -1;            /* And buffer index to -1 */
  8978. #endif /* MYREAD */
  8979. }
  8980.  
  8981. int
  8982. ttflui() {
  8983.     int n, fd;
  8984. #ifdef TCPSOCKET
  8985.     int dotnopts;
  8986.     dotnopts = (((xlocal && netconn && IS_TELNET()) ||
  8987.          (!xlocal && sstelnet)));
  8988. #endif /* TCPSOCKET */
  8989.  
  8990. #ifdef NETCMD
  8991.     if (ttpipe)
  8992.       fd = fdin;
  8993.     else
  8994. #endif /* NETCMD */
  8995.       fd = ttyfd;
  8996.  
  8997. #ifdef TTLEBUF
  8998.     ttpush = -1;            /* Clear the peek-ahead char */
  8999.     while (le_data && (le_inbuf() > 0)) {
  9000.         CHAR ch = '\0';
  9001.         if (le_getchar(&ch) > 0) {    /* Clear any more... */
  9002.             debug(F101,"ttflui le_inbuf ch","",ch);
  9003.         }
  9004.     }
  9005. #endif /* TTLEBUF */
  9006.     debug(F101,"ttflui ttpipe","",ttpipe);
  9007.  
  9008. #ifdef MYREAD
  9009. /*
  9010.   Flush internal MYREAD buffer *NEXT*, in all cases.
  9011. */
  9012.     ttflux();
  9013. #endif /* MYREAD */
  9014.  
  9015. #ifdef NETCONN
  9016. /* Network flush is done specially, in the network support module. */
  9017.     if ((netconn || sstelnet) && !ttpipe && !ttpty) {
  9018.     debug(F100,"ttflui netflui","",0);
  9019. #ifdef COMMENT
  9020. #ifdef TN_COMPORT
  9021.     if (istncomport())
  9022.             tnc_send_purge_data(TNC_PURGE_RECEIVE);
  9023. #endif /* TN_COMPORT */
  9024. #endif /* COMMENT */
  9025.     return(netflui());
  9026.     }
  9027. #endif /* NETCONN */
  9028.  
  9029.     debug(F101,"ttflui ttyfd","",ttyfd); /* Not network */
  9030.     if (ttyfd < 0)
  9031.       return(-1);
  9032.  
  9033. #ifdef aegis
  9034.     sio_$control((short)yfd, sio_$flush_in, true, st);
  9035.     if (st.all != status_$ok) {
  9036.     fprintf(stderr, "flush failed: "); error_$print(st);
  9037.     } else {      /* sometimes the flush doesn't work */
  9038.         for (;;) {
  9039.         char buf[256];
  9040.             /* eat all the characters that shouldn't be available */
  9041.             ios_$get((short)fd, ios_$cond_opt, buf, 256L, st); /* (void) */
  9042.             if (st.all == ios_$get_conditional_failed) break;
  9043.             fprintf(stderr, "flush failed(2): "); error_$print(st);
  9044.         }
  9045.     }
  9046. #else
  9047. #ifdef BSD44                /* 4.4 BSD */
  9048.     n = FREAD;                          /* Specify read queue */
  9049.     debug(F100,"ttflui BSD44","",0);
  9050.     ioctl(fd,TIOCFLUSH,&n);
  9051. #else
  9052. #ifdef Plan9
  9053. #undef POSIX                /* Uh oh... */
  9054. #endif /* Plan9 */
  9055. #ifdef POSIX                /* POSIX */
  9056.     debug(F100,"ttflui POSIX","",0);
  9057.     tcflush(fd,TCIFLUSH);
  9058. #else
  9059. #ifdef ATTSV                /* System V */
  9060. #ifndef VXVE
  9061.     debug(F100,"ttflui ATTSV","",0);
  9062.     ioctl(fd,TCFLSH,0);
  9063. #endif /* VXVE */
  9064. #else                    /* Not BSD44, POSIX, or Sys V */
  9065. #ifdef TIOCFLUSH            /* Those with TIOCFLUSH defined */
  9066. #ifdef ANYBSD                /* Berkeley */
  9067.     n = FREAD;                          /* Specify read queue */
  9068.     debug(F100,"ttflui TIOCFLUSH ANYBSD","",0);
  9069.     ioctl(fd,TIOCFLUSH,&n);
  9070. #else                    /* Others (V7, etc) */
  9071.     debug(F100,"ttflui TIOCFLUSH","",0);
  9072.     ioctl(fd,TIOCFLUSH,0);
  9073. #endif /* ANYBSD */
  9074. #else                    /* All others... */
  9075. /*
  9076.   No system call (that we know about) for input buffer flushing.
  9077.   So see how many there are and read them in a loop, using ttinc().
  9078.   ttinc() is buffered, so we're not getting charged with a system call
  9079.   per character, just a function call.
  9080. */
  9081.     if ((n = ttchk()) > 0) {
  9082.     debug(F101,"ttflui read loop","",n);
  9083.     while ((n--) && ttinc(0) > 0) ;
  9084.     }
  9085. #endif /* TIOCFLUSH */
  9086. #endif /* ATTSV */
  9087. #endif /* POSIX */
  9088. #ifdef Plan9
  9089. #define POSIX
  9090. #endif /* Plan9 */
  9091. #endif /* BSD44 */
  9092. #endif /* aegis */
  9093.     return(0);
  9094. }
  9095.  
  9096. int
  9097. ttfluo() {                /* Flush output buffer */
  9098.     int fd;
  9099. #ifdef NETCMD
  9100.     if (ttpipe)
  9101.       fd = fdout;
  9102.     else
  9103. #endif /* NETCMD */
  9104.       fd = ttyfd;
  9105.  
  9106. #ifdef Plan9
  9107.     return 0;
  9108. #else
  9109. #ifdef POSIX
  9110.     return(tcflush(fd,TCOFLUSH));
  9111. #else
  9112. #ifdef OXOS
  9113.     return(ioctl(fd,TCFLSH,1));
  9114. #else
  9115.     return(0);                /* All others, nothing */
  9116. #endif /* OXOS */
  9117. #endif /* POSIX */
  9118. #endif /* Plan9 */
  9119. }
  9120.  
  9121. /* Interrupt Functions */
  9122.  
  9123. /* Set up terminal interrupts on console terminal */
  9124.  
  9125. #ifndef FIONREAD            /* We don't need esctrp() */
  9126. #ifndef SELECT                /* if we have any of these... */
  9127. #ifndef CK_POLL
  9128. #ifndef RDCHK
  9129.  
  9130. #ifndef OXOS
  9131. #ifdef SVORPOSIX
  9132. SIGTYP
  9133. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  9134.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  9135.     conesc = 1;
  9136.     debug(F101,"esctrp caught SIGQUIT","",conesc);
  9137. }
  9138. #endif /* SVORPOSIX */
  9139. #endif /* OXOS */
  9140.  
  9141. #ifdef V7
  9142. #ifndef MINIX2
  9143. SIGTYP
  9144. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  9145.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  9146.     conesc = 1;
  9147.     debug(F101,"esctrp caught SIGQUIT","",conesc);
  9148. }
  9149. #endif /* MINIX2 */
  9150. #endif /* V7 */
  9151.  
  9152. #ifdef C70
  9153. SIGTYP
  9154. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  9155.     conesc = 1;
  9156.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  9157. }
  9158. #endif /* C70 */
  9159.  
  9160. #endif /* RDCHK */
  9161. #endif /* CK_POLL */
  9162. #endif /* SELECT */
  9163. #endif /* FIONREAD */
  9164.  
  9165. /*  C O N B G T  --  Background Test  */
  9166.  
  9167. static int jc = 0;            /* 0 = no job control */
  9168.  
  9169. /*
  9170.   Call with flag == 1 to prevent signal test, which can not be expected
  9171.   to work during file transfer, when SIGINT probably *is* set to SIG_IGN.
  9172.  
  9173.   Call with flag == 0 to use the signal test, but only if the process-group
  9174.   test fails, as it does on some UNIX systems, where getpgrp() is buggy,
  9175.   requires an argument when the man page says it doesn't, or vice versa.
  9176.  
  9177.   If flag == 0 and the process-group test fails, then we determine background
  9178.   status simply (but not necessarily reliably) from isatty().
  9179.  
  9180.   conbgt() sets the global backgrd = 1 if we appear to be in the background,
  9181.   and to 0 if we seem to be in the foreground.  conbgt() is highly prone to
  9182.   misbehavior.
  9183. */
  9184. VOID
  9185. conbgt(flag) int flag; {
  9186.     int x = -1,                /* process group or SIGINT test */
  9187.         y = 0;                /* isatty() test */
  9188. /*
  9189.   Check for background operation, even if not running on real tty, so that
  9190.   background flag can be set correctly.  If background status is detected,
  9191.   then Kermit will not issue its interactive prompt or most messages.
  9192.   If your prompt goes away, you can blame (and fix?) this function.
  9193. */
  9194.  
  9195. /* Use process-group test if possible. */
  9196.  
  9197. #ifdef POSIX                /* We can do it in POSIX */
  9198. #define PGROUP_T
  9199. #else
  9200. #ifdef BSD4                /* and in BSD 4.x. */
  9201. #define PGROUP_T
  9202. #else
  9203. #ifdef HPUXJOBCTL            /* and in most HP-UX's */
  9204. #define PGROUP_T
  9205. #else
  9206. #ifdef TIOCGPGRP            /* and anyplace that has this ioctl. */
  9207. #define PGROUP_T
  9208. #endif /* TIOCGPGRP */
  9209. #endif /* HPUXJOBCTL */
  9210. #endif /* BSD4 */
  9211. #endif /* POSIX */
  9212.  
  9213. #ifdef MIPS                /* Except if it doesn't work... */
  9214. #undef PGROUP_T
  9215. #endif /* MIPS */
  9216.  
  9217. #ifdef PGROUP_T
  9218. /*
  9219.   Semi-reliable process-group test.  Check whether this process's group is
  9220.   the same as the controlling terminal's process group.  This works if the
  9221.   getpgrp() call doesn't lie (as it does in the SUNOS System V environment).
  9222. */
  9223.     PID_T mypgrp = (PID_T)0;        /* Kermit's process group */
  9224.     PID_T ctpgrp = (PID_T)0;        /* The terminal's process group */
  9225. #ifndef _POSIX_SOURCE
  9226. /*
  9227.   The getpgrp() prototype is obtained from system header files for POSIX
  9228.   and Sys V R4 compilations.  Other systems, who knows.  Some complain about
  9229.   a duplicate declaration here, others don't, so it's safer to leave it in
  9230.   if we don't know for certain.
  9231. */
  9232. #ifndef SVR4
  9233. #ifndef PS2AIX10
  9234. #ifndef HPUX9
  9235.     extern PID_T getpgrp();
  9236. #endif /* HPUX9 */
  9237. #endif /* PS2AIX10 */
  9238. #endif /* SVR4 */
  9239. #endif /* _POSIX_SOURCE */
  9240.  
  9241. /* Get my process group. */
  9242.  
  9243. #ifdef SVR3 /* Maybe this should be ATTSV? */
  9244. /* This function is not described in SVID R2 */
  9245.     mypgrp = getpgrp();
  9246.     /* debug(F101,"ATTSV conbgt process group","",(int) mypgrp); */
  9247. #else
  9248. #ifdef POSIX
  9249.     mypgrp = getpgrp();
  9250.     /* debug(F101,"POSIX conbgt process group","",(int) mypgrp); */
  9251. #else
  9252. #ifdef OSFPC
  9253.     mypgrp = getpgrp();
  9254.     /* debug(F101,"OSF conbgt process group","",(int) mypgrp); */
  9255. #else
  9256. #ifdef QNX
  9257.     mypgrp = getpgrp();
  9258.     /* debug(F101,"QNX conbgt process group","",(int) mypgrp); */
  9259. #else
  9260. #ifdef OSF32                /* (was OSF40) */
  9261.     mypgrp = getpgrp();
  9262.     /* debug(F101,"Digital UNIX conbgt process group","",(int) mypgrp); */
  9263. #else /* BSD, V7, etc */
  9264. #ifdef MINIX2
  9265.     mypgrp = getpgrp();
  9266. #else
  9267.     mypgrp = getpgrp(0);
  9268. #endif /* MINIX2 */
  9269.     /* debug(F101,"BSD conbgt process group","",(int) mypgrp); */
  9270. #endif /* OSF32 */
  9271. #endif /* QNX */
  9272. #endif /* OSFPC */
  9273. #endif /* POSIX */
  9274. #endif /* SVR3 */
  9275.  
  9276. #ifdef MINIX2
  9277. #undef BSD44ORPOSIX
  9278. #endif /* MINIX2 */
  9279.  
  9280. /* Now get controlling tty's process group */
  9281. #ifdef BSD44ORPOSIX
  9282.     ctpgrp = tcgetpgrp(1);        /* The POSIX way */
  9283.     /* debug(F101,"POSIX conbgt terminal process group","",(int) ctpgrp); */
  9284. #else
  9285.     ioctl(1, TIOCGPGRP, &ctpgrp);    /* Or the BSD way */
  9286.    /* debug(F101,"non-POSIX conbgt terminal process group","",(int) ctpgrp); */
  9287. #endif /* BSD44ORPOSIX */
  9288.  
  9289. #ifdef MINIX2
  9290. #define BSD44ORPOSIX
  9291. #endif /* MINIX2 */
  9292.  
  9293.     if ((mypgrp > (PID_T) 0) && (ctpgrp > (PID_T) 0))
  9294.       x = (mypgrp == ctpgrp) ? 0 : 1;    /* If they differ, then background. */
  9295.     else x = -1;            /* If error, remember. */
  9296.     debug(F101,"conbgt process group test","",x);
  9297. #endif /* PGROUP_T */
  9298.  
  9299. /* Try to see if job control is available */
  9300.  
  9301. #ifdef NOJC                /* User override */
  9302.     jc = 0;                /* No job control allowed */
  9303.     debug(F111,"NOJC","jc",jc);
  9304. #else
  9305. #ifdef BSD44
  9306.     jc = 1;
  9307. #else
  9308. #ifdef SVR4ORPOSIX            /* POSIX actually tells us */
  9309.     debug(F100,"SVR4ORPOSIX jc test...","",0);
  9310. #ifdef _SC_JOB_CONTROL
  9311. #ifdef __bsdi__
  9312.     jc = 1;
  9313. #else
  9314. #ifdef __386BSD__
  9315.     jc = 1;
  9316. #else
  9317.     jc = sysconf(_SC_JOB_CONTROL);    /* Whatever system says */
  9318.     if (jc < 0) {
  9319.     debug(F101,"sysconf fails, jcshell","",jcshell);
  9320.     jc = (jchdlr == SIG_DFL) ? 1 : 0;
  9321.     } else
  9322.       debug(F111,"sysconf(_SC_JOB_CONTROL)","jc",jc);
  9323. #endif /* __386BSD__ */
  9324. #endif /* __bsdi__ */
  9325. #else
  9326. #ifdef _POSIX_JOB_CONTROL
  9327.     jc = 1;                /* By definition */
  9328.     debug(F111,"_POSIX_JOB_CONTROL is defined","jc",jc);
  9329. #else
  9330.     jc = 0;                /* Assume job control not allowed */
  9331.     debug(F111,"SVR4ORPOSIX _SC/POSIX_JOB_CONTROL not defined","jc",jc);
  9332. #endif /* _POSIX_JOB_CONTROL */
  9333. #endif /* _SC_JOB_CONTROL */
  9334. #else
  9335. #ifdef BSD4
  9336.     jc = 1;                /* Job control allowed */
  9337.     debug(F111,"BSD job control","jc",jc);
  9338. #else
  9339. #ifdef SVR3JC
  9340.     jc = 1;                /* JC allowed */
  9341.     debug(F111,"SVR3 job control","jc",jc);
  9342. #else
  9343. #ifdef OXOS
  9344.     jc = 1;                /* JC allowed */
  9345.     debug(F111,"X/OS job control","jc",jc);
  9346. #else
  9347. #ifdef HPUX9
  9348.     jc = 1;                /* JC allowed */
  9349.     debug(F111,"HP-UX 9.0 job control","jc",jc);
  9350. #else
  9351. #ifdef HPUX10
  9352.     jc = 1;                /* JC allowed */
  9353.     debug(F111,"HP-UX 10.0 job control","jc",jc);
  9354. #else
  9355.     jc = 0;                /* JC not allowed */
  9356.     debug(F111,"job control catch-all","jc",jc);
  9357. #endif /* HPUX10 */
  9358. #endif /* HPUX9 */
  9359. #endif /* OXOS */
  9360. #endif /* SVR3JC */
  9361. #endif /* BSD4 */
  9362. #endif /* SVR4ORPOSIX */
  9363. #endif /* BSD44 */
  9364. #endif /* NOJC */
  9365.     debug(F101,"conbgt jc","",jc);
  9366. #ifndef NOJC
  9367.     debug(F101,"conbgt jcshell","",jcshell);
  9368. /*
  9369.   At this point, if jc == 1 but jcshell == 0, it means that the OS supports
  9370.   job control, but the shell or other process we are running under does not
  9371.   (jcshell is set in sysinit()) and so if we suspend ourselves, nothing good
  9372.   will come of it.  So...
  9373. */
  9374.     if (jc < 0) jc = 0;
  9375.     if (jc > 0 && jcshell == 0) jc = 0;
  9376. #endif /* NOJC */
  9377.  
  9378. /*
  9379.   Another background test.
  9380.   Test if SIGINT (terminal interrupt) is set to SIG_IGN (ignore),
  9381.   which is done by the shell (sh) if the program is started with '&'.
  9382.   Unfortunately, this is NOT done by csh or ksh so watch out!
  9383.   Note, it's safe to set SIGINT to SIG_IGN here, because further down
  9384.   we always set it to something else.
  9385.   Note: as of 16 Jul 1999, we also skip this test if we set SIGINT to
  9386.   SIG_IGN ourselves.
  9387. */
  9388.     if (x < 0 && !flag && !sigint_ign) { /* Didn't get good results above... */
  9389.  
  9390.     SIGTYP (*osigint)();
  9391.  
  9392.     osigint = signal(SIGINT,SIG_IGN);    /* What is SIGINT set to? */
  9393.     sigint_ign = 1;
  9394.     x = (osigint == SIG_IGN) ? 1 : 0;    /* SIG_IGN? */
  9395.     /* debug(F101,"conbgt osigint","",osigint); */
  9396.     /* debug(F101,"conbgt signal test","",x); */
  9397.     }
  9398.  
  9399. /* Also check to see if we're running with redirected stdio. */
  9400. /* This is not really background operation, but we want to act as though */
  9401. /* it were. */
  9402.  
  9403. #ifdef IKSD
  9404.     if (inserver) {            /* Internet Kermit Server */
  9405.     backgrd = 0;            /* is not in the background */
  9406.     return;
  9407.     }
  9408. #endif /* IKSD */
  9409.  
  9410.     y = (isatty(0) && isatty(1)) ? 1 : 0;
  9411.     debug(F101,"conbgt isatty test","",y);
  9412.  
  9413. #ifdef BSD29
  9414. /* The process group and/or signal test doesn't work under these... */
  9415.     backgrd = !y;
  9416. #else
  9417. #ifdef sxaE50
  9418.     backgrd = !y;
  9419. #else
  9420. #ifdef MINIX
  9421.     backgrd = !y;
  9422. #else
  9423. #ifdef MINIX2
  9424.     backgrd = !y;
  9425. #else
  9426.     if (x > -1)
  9427.       backgrd = (x || !y) ? 1 : 0;
  9428.     else backgrd = !y;
  9429. #endif /* BSD29 */
  9430. #endif /* sxaE50 */
  9431. #endif /* MINIX */
  9432. #endif /* MINIX2 */
  9433.     debug(F101,"conbgt backgrd","",backgrd);
  9434. }
  9435.  
  9436. /*  C O N I N T  --  Console Interrupt setter  */
  9437.  
  9438. /*
  9439.   First arg is pointer to function to handle SIGTERM & SIGINT (like Ctrl-C).
  9440.   Second arg is pointer to function to handle SIGTSTP (suspend).
  9441. */
  9442.  
  9443. VOID                    /* Set terminal interrupt traps. */
  9444. #ifdef CK_ANSIC
  9445. #ifdef apollo
  9446. conint(f,s) SIGTYP (*f)(), (*s)();
  9447. #else
  9448. conint(SIGTYP (*f)(int), SIGTYP (*s)(int))
  9449. #endif /* apollo */
  9450. #else
  9451. conint(f,s) SIGTYP (*f)(), (*s)();
  9452. #endif /* CK_ANSIC */
  9453. /* conint */ {
  9454.  
  9455.     debug(F101,"conint conistate","",conistate);
  9456.  
  9457.     conbgt(0);                /* Do background test. */
  9458.  
  9459. /* Set the desired handlers for hangup and software termination. */
  9460.  
  9461. #ifdef SIGTERM
  9462.     signal(SIGTERM,f);                  /* Software termination */
  9463. #endif /* SIGTERM */
  9464.  
  9465. /*
  9466.   Prior to July 1999 we used to call sighup() here but now it's called in
  9467.   sysinit() so SIGHUP can be caught during execution of the init file or
  9468.   a kerbang script.
  9469. */
  9470.  
  9471. /* Now handle keyboard stop, quit, and interrupt signals. */
  9472. /* Check if invoked in background -- if so signals set to be ignored. */
  9473. /* However, if running under a job control shell, don't ignore them. */
  9474. /* We won't be getting any, as we aren't in the terminal's process group. */
  9475.  
  9476.     debug(F101,"conint backgrd","",backgrd);
  9477.     debug(F101,"conint jc","",jc);
  9478.  
  9479.     if (backgrd && !jc) {        /* In background, ignore signals */
  9480.     debug(F101,"conint background ignoring signals, jc","",jc);
  9481. #ifdef SIGTSTP
  9482.         signal(SIGTSTP,SIG_IGN);        /* Keyboard stop */
  9483. #endif /* SIGTSTP */
  9484.         signal(SIGQUIT,SIG_IGN);        /* Keyboard quit */
  9485.         signal(SIGINT,SIG_IGN);         /* Keyboard interrupt */
  9486.     sigint_ign = 1;
  9487.     conistate = CONI_NOI;
  9488.     } else {                /* Else in foreground or suspended */
  9489.     debug(F101,"conint foreground catching signals, jc","",jc);
  9490.         signal(SIGINT,f);               /* Catch terminal interrupt */
  9491.     sigint_ign = (f == SIG_IGN) ? 1 : 0;
  9492.  
  9493. #ifdef SIGTSTP                /* Keyboard stop (suspend) */
  9494.     /* debug(F101,"conint SIGSTSTP","",s); */
  9495.     if (s == NULL) s = SIG_DFL;
  9496. #ifdef NOJC                /* No job control allowed. */
  9497.     signal(SIGTSTP,SIG_IGN);
  9498. #else                    /* Job control allowed */
  9499.     if (jc)                /* if available. */
  9500.       signal(SIGTSTP,s);
  9501.     else
  9502.       signal(SIGTSTP,SIG_IGN);
  9503. #endif /* NOJC */
  9504. #endif /* SIGTSTP */
  9505.  
  9506. #ifndef OXOS
  9507. #ifdef SVORPOSIX
  9508. #ifndef FIONREAD            /* Watch out, we don't know this... */
  9509. #ifndef SELECT
  9510. #ifndef CK_POLL
  9511. #ifndef RDCHK
  9512.         signal(SIGQUIT,esctrp);         /* Quit signal, Sys III/V. */
  9513. #endif /* RDCHK */
  9514. #endif /* CK_POLL */
  9515. #endif /* SELECT */
  9516. #endif /* FIONREAD */
  9517.         if (conesc) conesc = 0;         /* Clear out pending escapes */
  9518. #else
  9519. #ifdef V7
  9520.         signal(SIGQUIT,esctrp);         /* V7 like Sys III/V */
  9521.         if (conesc) conesc = 0;
  9522. #else
  9523. #ifdef aegis
  9524.         signal(SIGQUIT,f);              /* Apollo, catch it like others. */
  9525. #else
  9526.         signal(SIGQUIT,SIG_IGN);        /* Others, ignore like 4D & earlier. */
  9527. #endif /* aegis */
  9528. #endif /* V7 */
  9529. #endif /* SVORPOSIX */
  9530. #endif /* OXOS */
  9531.     conistate = CONI_INT;
  9532.     }
  9533. }
  9534.  
  9535.  
  9536. /*  C O N N O I  --  Reset console terminal interrupts */
  9537.  
  9538. VOID
  9539. connoi() {                              /* Console-no-interrupts */
  9540.  
  9541.     debug(F101,"connoi conistate","",conistate);
  9542. #ifdef SIGTSTP
  9543.     signal(SIGTSTP,SIG_IGN);        /* Suspend */
  9544. #endif /* SIGTSTP */
  9545.     conint(SIG_IGN,SIG_IGN);        /* Interrupt */
  9546.     sigint_ign = 1;            /* Remember we did this ourselves */
  9547. #ifdef SIGQUIT
  9548.     signal(SIGQUIT,SIG_IGN);        /* Quit */
  9549. #endif /* SIGQUIT */
  9550. #ifdef SIGTERM
  9551.     signal(SIGTERM,SIG_IGN);        /* Term */
  9552. #endif /* SIGTERM */
  9553.     conistate = CONI_NOI;
  9554. }
  9555.  
  9556. /*  I N I T R A W Q  --  Set up to read /dev/kmem for character count.  */
  9557.  
  9558. #ifdef  V7
  9559. /*
  9560.  Used in Version 7 to simulate Berkeley's FIONREAD ioctl call.  This
  9561.  eliminates blocking on a read, because we can read /dev/kmem to get the
  9562.  number of characters available for raw input.  If your system can't
  9563.  or you won't let the world read /dev/kmem then you must figure out a
  9564.  different way to do the counting of characters available, or else replace
  9565.  this by a dummy function that always returns 0.
  9566. */
  9567. /*
  9568.  * Call this routine as: initrawq(tty)
  9569.  * where tty is the file descriptor of a terminal.  It will return
  9570.  * (as a char *) the kernel-mode memory address of the rawq character
  9571.  * count, which may then be read.  It has the side-effect of flushing
  9572.  * input on the terminal.
  9573.  */
  9574. /*
  9575.  * John Mackin, Physiology Dept., University of Sydney (Australia)
  9576.  * ...!decvax!mulga!physiol.su.oz!john
  9577.  *
  9578.  * Permission is hereby granted to do anything with this code, as
  9579.  * long as this comment is retained unmodified and no commercial
  9580.  * advantage is gained.
  9581.  */
  9582. #ifndef MINIX
  9583. #ifndef MINIX2
  9584. #ifndef COHERENT
  9585. #include <a.out.h>
  9586. #include <sys/proc.h>
  9587. #endif /* COHERENT */
  9588. #endif /* MINIX2 */
  9589. #endif /* MINIX */
  9590.  
  9591. #ifdef COHERENT
  9592. #include <l.out.h>
  9593. #include <sys/proc.h>
  9594. #endif /* COHERENT */
  9595.  
  9596. char *
  9597. initrawq(tty) int tty; {
  9598. #ifdef MINIX
  9599.     return(0);
  9600. #else
  9601. #ifdef MINIX2
  9602.     return(0);
  9603. #else
  9604. #ifdef UTS24
  9605.     return(0);
  9606. #else
  9607. #ifdef BSD29
  9608.     return(0);
  9609. #else
  9610.     long lseek();
  9611.     static struct nlist nl[] = {
  9612.         {PROCNAME},
  9613.         {NPROCNAME},
  9614.         {""}
  9615.     };
  9616.     static struct proc *pp;
  9617.     char *qaddr, *p, c;
  9618.     int m;
  9619.     PID_T pid, me;
  9620.     NPTYPE xproc;                       /* Its type is defined in makefile. */
  9621.     int catch();
  9622.  
  9623.     me = getpid();
  9624.     if ((m = open("/dev/kmem", 0)) < 0) err("kmem");
  9625.     nlist(BOOTNAME, nl);
  9626.     if (nl[0].n_type == 0) err("proc array");
  9627.  
  9628.     if (nl[1].n_type == 0) err("nproc");
  9629.  
  9630.     lseek(m, (long)(nl[1].n_value), 0);
  9631.     read (m, &xproc, sizeof(xproc));
  9632.     saval = signal(SIGALRM, catch);
  9633.     if ((pid = fork()) == 0) {
  9634.         while(1)
  9635.             read(tty, &c, 1);
  9636.     }
  9637.     alarm(2);
  9638.  
  9639.     if(setjmp(jjbuf) == 0) {
  9640.         while(1)
  9641.       read(tty, &c, 1);
  9642.     }
  9643.     signal(SIGALRM, SIG_DFL);
  9644.  
  9645. #ifdef DIRECT
  9646.     pp = (struct proc *) nl[0].n_value;
  9647. #else
  9648.     if (lseek(m, (long)(nl[0].n_value), 0) < 0L) err("seek");
  9649.     if (read(m, &pp, sizeof(pp)) != sizeof(pp))  err("no read of proc ptr");
  9650. #endif
  9651.     lseek(m, (long)(nl[1].n_value), 0);
  9652.     read(m, &xproc, sizeof(xproc));
  9653.  
  9654.     if (lseek(m, (long)pp, 0) < 0L) err("Can't seek to proc");
  9655.     if ((p = malloc(xproc * sizeof(struct proc))) == NULL) err("malloc");
  9656.     if (read(m,p,xproc * sizeof(struct proc)) != xproc*sizeof(struct proc))
  9657.         err("read proc table");
  9658.     for (pp = (struct proc *)p; xproc > 0; --xproc, ++pp) {
  9659.         if (pp -> p_pid == (short) pid) goto iout;
  9660.     }
  9661.     err("no such proc");
  9662.  
  9663. iout:
  9664.     close(m);
  9665.     qaddr = (char *)(pp -> p_wchan);
  9666.     free (p);
  9667.     kill(pid, SIGKILL);
  9668.     wait((WAIT_T *)0);
  9669.     return (qaddr);
  9670. #endif
  9671. #endif
  9672. #endif
  9673. #endif
  9674. }
  9675.  
  9676. /*  More V7-support functions...  */
  9677.  
  9678. static VOID
  9679. err(s) char *s; {
  9680.     char buf[200];
  9681.  
  9682.     ckmakmsg(buf,200,"fatal error in initrawq: ", s, NULL, NULL);
  9683.     perror(buf);
  9684.     doexit(1,-1);
  9685. }
  9686.  
  9687. static VOID
  9688. catch(foo) int foo; {
  9689.     longjmp(jjbuf, -1);
  9690. }
  9691.  
  9692.  
  9693. /*  G E N B R K  --  Simulate a modem break.  */
  9694.  
  9695. #ifdef MINIX
  9696. #define BSPEED B110
  9697. #else
  9698. #ifdef MINIX2
  9699. #define BSPEED B110
  9700. #else
  9701. #define BSPEED B150
  9702. #endif /* MINIX2 */
  9703. #endif /* MINIX */
  9704.  
  9705. #ifndef MINIX2
  9706. VOID
  9707. genbrk(fn,msec) int fn, msec; {
  9708.     struct sgttyb ttbuf;
  9709.     int ret, sospeed, x, y;
  9710.  
  9711.     ret = ioctl(fn, TIOCGETP, &ttbuf);
  9712.     sospeed = ttbuf.sg_ospeed;
  9713.     ttbuf.sg_ospeed = BSPEED;
  9714.     ret = ioctl(fn, TIOCSETP, &ttbuf);
  9715.     y = (int)strlen(brnuls);
  9716.     x = ( BSPEED * 100 ) / msec;
  9717.     if (x > y) x = y;
  9718.     ret = write(fn, brnuls, (( BSPEED * 100 ) / msec ));
  9719.     ttbuf.sg_ospeed = sospeed;
  9720.     ret = ioctl(fn, TIOCSETP, &ttbuf);
  9721.     ret = write(fn, "@", 1);
  9722.     return;
  9723. }
  9724. #endif /* MINIX2 */
  9725.  
  9726. #ifdef MINIX2
  9727. int
  9728. genbrk(fn,msec) int fn, msec; {
  9729.     struct termios ttbuf;
  9730.     int ret, x, y;
  9731.     speed_t sospeed;
  9732.  
  9733.     ret = tcgetattr(fn, &ttbuf);
  9734.     sospeed = ttbuf.c_ospeed;
  9735.     ttbuf.c_ospeed = BSPEED;
  9736.     ret = tcsetattr(fn,TCSADRAIN, &ttbuf);
  9737.     y = (int)strlen(brnuls);
  9738.     x = ( BSPEED * 100 ) / msec;
  9739.     if (x > y) x = y;
  9740.     ret = write(fn, brnuls, (( BSPEED * 100 ) / msec ));
  9741.     ttbuf.c_ospeed = sospeed;
  9742.     ret = tcsetattr(fn, TCSADRAIN, &ttbuf);
  9743.     ret = write(fn, "@", 1);
  9744.     return ret;
  9745. }
  9746. #endif /* MINIX2 */
  9747. #endif /* V7 */
  9748.  
  9749. /*
  9750.   I N C H K  --  Check if chars waiting to be read on given file descriptor.
  9751.  
  9752.   This routine is a merger of ttchk() and conchk().
  9753.   Call with:
  9754.     channel == 0 to check console.
  9755.     channel == 1 to check communications connection.
  9756.   and:
  9757.     fd = file descriptor.
  9758.   Returns:
  9759.    >= 0: number of characters waiting, 0 or greater,
  9760.      -1: on any kind of error,
  9761.      -2: if there is (definitely) no connection.
  9762.   Note: In UNIX we don't have to call nettchk() because a socket
  9763.   file descriptor works just like in serial i/o, ioctls and all.
  9764.   (But this will change if we add non-file-descriptor channels,
  9765.   such as IBM X.25 for AIX...)
  9766. */
  9767. static int
  9768. in_chk(channel, fd) int channel, fd; {
  9769.     int x, n = 0;            /* Workers, n = return value */
  9770.     extern int clsondisc;        /* Close on disconnect */
  9771. /*
  9772.   The first section checks to make sure we have a connection,
  9773.   but only if we're in local mode.
  9774. */
  9775. #ifdef DEBUG
  9776.     if (deblog) {
  9777.     debug(F111,"in_chk entry",ckitoa(fd),channel);
  9778.     debug(F101,"in_chk ttyfd","",ttyfd);
  9779.     debug(F101,"in_chk ttpty","",ttpty);
  9780.     }
  9781. #endif /* DEBUG */
  9782. /*
  9783.   But don't say connection is gone if we have any buffered-stuff.
  9784. */
  9785. #ifdef TTLEBUF
  9786.     debug(F101,"in_chk ttpush","",ttpush);
  9787.     if (channel == 1) {
  9788.     if (ttpush >= 0)
  9789.       n++;
  9790.     n += le_inbuf();
  9791.     if (n > 0)
  9792.       return(n);
  9793.     }
  9794. #endif /* TTLEBUF */
  9795.  
  9796. #ifdef NETPTY
  9797. #ifdef HAVE_PTYTRAP
  9798.     /* Special handling for HP-UX pty i/o */
  9799.     if (ttpty && pty_trap_pending(ttyfd) > 0) {
  9800.         if (pty_trap_handler(ttyfd) > 0) {
  9801.             ttclos(0);
  9802.             return(-2);
  9803.         }
  9804.     }
  9805. #endif /* HAVE_PTYTRAP */
  9806. #endif /* NETPTY */
  9807.  
  9808.     if (channel) {            /* Checking communications channel */
  9809.     if (ttyfd < 0) {        /* No connection */
  9810.       return(-2);            /* That's what this means */
  9811.     } else if (xlocal &&        /* In local mode */
  9812.            (!netconn        /* Serial connection or */
  9813. #ifdef TN_COMPORT
  9814.             || istncomport()    /* Telnet Com Port */
  9815. #endif /* TN_COMPORT */
  9816.            ) && ttcarr != CAR_OFF /* with CARRIER WATCH ON (or AUTO) */
  9817. #ifdef COMMENT
  9818. #ifdef MYREAD
  9819. /*
  9820.   Seems like this would be a good idea but it prevents C-Kermit from
  9821.   popping back to the prompt automatically when carrier drops.  However,
  9822.   commenting this out prevents us from seeing the NO CARRIER message.
  9823.   Needs more work...
  9824. */
  9825.            && my_count < 1    /* Nothing in our internal buffer */
  9826. #endif /* MYREAD */
  9827. #endif /* COMMENT */
  9828.            ) {
  9829.         int x;
  9830.         x = ttgmdm();        /* So get modem signals */
  9831.         debug(F101,"in_chk close-on-disconnect","",clsondisc);
  9832.         if (x > -1) {        /* Check for carrier */
  9833.         if (!(x & BM_DCD)) {    /* No carrier */
  9834.             debug(F101,"in_chk carrier lost","",x);
  9835.             if (clsondisc)    /* If "close-on-disconnect" */
  9836.               ttclos(0);    /* close device & release lock. */
  9837.             return(-2);        /* This means "disconnected" */
  9838.         }
  9839.         /* In case I/O to device after CD dropped always fails */
  9840.         /* as in Debian Linux 2.1 and Unixware 2.1... */
  9841.         } else {
  9842.             debug(F101,"in_chk ttgmdm I/O error","",errno);
  9843.             debug(F101,"in_chk ttgmdm gotsigs","",gotsigs);
  9844.             if (gotsigs) {        /* If we got signals before... */
  9845.             if (errno == 5 || errno == 6) { /* I/O error etc */
  9846.                 if (clsondisc)    /* like when modem hangs up */
  9847.               ttclos(0);
  9848.             return(-2);
  9849.             }
  9850.         }
  9851.         /* If we never got modem signals successfully on this */
  9852.         /* connection before, we can't conclude that THIS failure */
  9853.         /* means the connection was lost. */
  9854.         return(0);
  9855.         }
  9856.     }
  9857.     }
  9858.  
  9859. /* We seem to have a connection so now see if any bytes are waiting on it */
  9860.  
  9861. #ifdef CK_SSL
  9862.     if (ssl_active_flag || tls_active_flag) {
  9863.         n += SSL_pending(ssl_active_flag?ssl_con:tls_con);
  9864.         debug(F101,"in_chk SSL_pending","",n);
  9865.         if (n < 0) {
  9866.             ttclos(0);
  9867.             return(-1);
  9868.         } else if (n > 0) {
  9869.             return(n);
  9870.         }
  9871.     }
  9872. #endif /* CK_SSL */
  9873. #ifdef RLOGCODE
  9874. #ifdef CK_KERBEROS
  9875.     /* It is not safe to read any data when using encrypted Klogin */
  9876.     if (ttnproto == NP_EK4LOGIN || ttnproto == NP_EK5LOGIN) {
  9877. #ifdef KRB4
  9878.         if (ttnproto == NP_EK4LOGIN) {
  9879.             n += krb4_des_avail(ttyfd);
  9880.             debug(F101,"in_chk krb4_des_avail","",n);
  9881.         }
  9882. #endif /* KRB4 */
  9883. #ifdef KRB5
  9884.         if (ttnproto == NP_EK5LOGIN) {
  9885.             n += krb5_des_avail(ttyfd);
  9886.             debug(F101,"in_chk krb5_des_avail","",n);
  9887.         }
  9888. #ifdef KRB5_U2U
  9889.         if (ttnproto == NP_K5U2U) {
  9890.             n += krb5_u2u_avail(ttyfd);
  9891.             debug(F101,"in_chk krb5_des_avail","",n);
  9892.         }
  9893. #endif /* KRB5_U2U */
  9894. #endif /* KRB5 */
  9895.         if (n < 0)            /* Is this right? */
  9896.       return(-1);
  9897.         else
  9898.       return(n);
  9899.     }
  9900. #endif /* CK_KERBEROS */
  9901. #endif /* RLOGCODE */
  9902.  
  9903.     errno = 0;                /* Reset this so we log good info */
  9904. #ifdef FIONREAD
  9905.     x = ioctl(fd, FIONREAD, &n);    /* BSD and lots of others */
  9906. #ifdef DEBUG                /* (the more the better) */
  9907.     if (deblog) {
  9908.     debug(F101,"in_chk FIONREAD return code","",x);
  9909.     debug(F101,"in_chk FIONREAD count","",n);
  9910.     debug(F101,"in_chk FIONREAD errno","",errno);
  9911.     }
  9912. #endif /* DEBUG */
  9913. #else /* FIONREAD not defined */
  9914. /*
  9915.   Here, if (netconn && ttnet == NET_TCPB), we might try calling recvmsg()
  9916.   with flags MSG_PEEK|MSG_DONTWAIT on the socket (ttyfd), except this is not
  9917.   portable (MSG_DONTWAIT isn't defined in any of the <sys/socket.h> files
  9918.   that I looked at, but it is needed to prevent the call from blocking), and
  9919.   the msghdr struct differs from place to place, so we would need another
  9920.   avalanche of ifdefs.  Still, when FIONREAD is not available, this is the
  9921.   only other known method of asking the OS for the *number* of characters
  9922.   available for reading.
  9923. */
  9924. #ifdef V7                /* UNIX V7: look in kernel memory */
  9925. #ifdef MINIX
  9926.     n = 0;                /* But not in MINIX */
  9927. #else
  9928. #ifdef MINIX2
  9929.     n = 0;
  9930. #else
  9931.     lseek(kmem[TTY], (long) qaddr[TTY], 0); /* 7th Edition Unix */
  9932.     x = read(kmem[TTY], &n, sizeof(int));
  9933.     if (x != sizeof(int))
  9934.       n = 0;
  9935. #endif /* MINIX2 */
  9936. #endif /* MINIX */
  9937. #else /* Not V7 */
  9938. #ifdef PROVX1
  9939.     x = ioctl(fd, TIOCQCNT, &ttbuf);    /* DEC Pro/3xx Venix V.1 */
  9940.     n = ttbuf.sg_ispeed & 0377;        /* Circa 1984 */
  9941.     if (x < 0) n = 0;
  9942. #else
  9943. #ifdef MYREAD
  9944. /*
  9945.   Here we skip all the undependable and expensive calls below if we
  9946.   already have something in our internal buffer.  This tends to work quite
  9947.   nicely, so the only really bad case remaining is the one in which neither
  9948.   FIONREAD or MYREAD are defined, which is increasingly rare these days.
  9949. */
  9950.     if (channel != 0 && my_count > 0) {
  9951.     debug(F101,"in_chk buf my_count","",my_count);
  9952.     n = my_count;            /* n was 0 before we got here */
  9953.     return(n);
  9954.     }
  9955. #endif /* MYREAD */
  9956. /*
  9957.   rdchk(), select(), and poll() tell us *if* data is available to be read, but
  9958.   not how much, so these should be used only as a final resort.  Especially
  9959.   since these calls tend to add a lot overhead.
  9960. */
  9961. #ifdef RDCHK                /* This mostly SCO-specific */
  9962.     n = rdchk(fd);
  9963.     debug(F101,"in_chk rdchk","",n);
  9964. #else /* No RDCHK */
  9965. #ifdef SELECT
  9966. #ifdef Plan9
  9967.     /* Only allows select on the console ... don't ask */
  9968.     if (channel == 0)
  9969. #endif /* Plan9 */
  9970.       {
  9971.     fd_set rfds;            /* Read file descriptors */
  9972. #ifdef BELLV10
  9973.     FD_ZERO(rfds);            /* Initialize them */
  9974.     FD_SET(fd,rfds);        /* We want to look at this fd */
  9975. #else
  9976.     FD_ZERO(&rfds);            /* Initialize them */
  9977.     FD_SET(fd,&rfds);        /* We want to look at this fd */
  9978.     tv.tv_sec = tv.tv_usec = 0L;    /* A 0-valued timeval structure */
  9979. #endif /* BELLV10 */
  9980. #ifdef Plan9
  9981.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9982.     debug(F101,"in_chk Plan 9 select","",n);
  9983. #else
  9984. #ifdef BELLV10
  9985.     n = select( 128, rfds, (fd_set *)0, (fd_set *)0, 0 );
  9986.     debug(F101,"in_chk BELLV10 select","",n);
  9987. #else
  9988. #ifdef BSD44
  9989.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9990.     debug(F101,"in_chk BSD44 select","",n);
  9991. #else
  9992. #ifdef BSD43
  9993.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9994.     debug(F101,"in_chk BSD43 select","",n);
  9995. #else
  9996. #ifdef SOLARIS
  9997.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  9998.     debug(F101,"in_chk SOLARIS select","",n);
  9999. #else
  10000. #ifdef QNX6
  10001.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10002.     debug(F101,"in_chk QNX6 select","",n);
  10003. #else
  10004. #ifdef QNX
  10005.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10006.     debug(F101,"in_chk QNX select","",n);
  10007. #else
  10008. #ifdef COHERENT
  10009.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10010.     debug(F101,"in_chk COHERENT select","",n);
  10011. #else
  10012. #ifdef SVR4
  10013.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10014.     debug(F101,"in_chk SVR4 select","",n);
  10015. #else
  10016. #ifdef __linux__
  10017.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10018.     debug(F101,"in_chk LINUX select","",n);
  10019. #ifdef OSF
  10020.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10021.     debug(F101,"in_chk OSF select","",n);
  10022. #else
  10023.     n = select( FD_SETSIZE, &rfds, (int *)0, (int *)0, &tv );
  10024.     debug(F101,"in_chk catchall select","",n);
  10025. #endif /* OSF */
  10026. #endif /* __linux__ */
  10027. #endif /* SVR4 */
  10028. #endif /* COHERENT */
  10029. #endif /* QNX */
  10030. #endif /* QNX6 */
  10031. #endif /* SOLARIS */
  10032. #endif /* BSD43 */
  10033. #endif /* BSD44 */
  10034. #endif /* BELLV10 */
  10035. #endif /* Plan9 */
  10036.     }
  10037. #else  /* Not SELECT */
  10038. #ifdef CK_POLL
  10039.     {
  10040.       struct pollfd pfd;
  10041.  
  10042.       pfd.fd = fd;
  10043.       pfd.events = POLLIN;
  10044.       pfd.revents = 0;
  10045.       n = poll(&pfd, 1, 0);
  10046.       debug(F101,"in_chk poll","",n);
  10047.       if ((n > 0) && (pfd.revents & POLLIN))
  10048.     n = 1;
  10049.     }
  10050. #endif /* CK_POLL */
  10051. #endif /* SELECT */
  10052. #endif /* RDCHK */
  10053. #endif /* PROVX1 */
  10054. #endif /* V7 */
  10055. #endif /* FIONREAD */
  10056.  
  10057. /* From here down, treat console and communication device differently... */
  10058.  
  10059.     if (channel == 0) {            /* Console */
  10060.  
  10061. #ifdef SVORPOSIX
  10062. #ifndef FIONREAD
  10063. #ifndef SELECT
  10064. #ifndef CK_POLL
  10065. #ifndef RDCHK
  10066. /*
  10067.   This is the hideous hack used in System V and POSIX systems that don't
  10068.   support FIONREAD, rdchk(), select(), poll(), etc, in which the user's
  10069.   CONNECT-mode escape character is attached to SIGQUIT.  Used, obviously,
  10070.   only on the console.
  10071. */
  10072.     if (conesc) {            /* Escape character typed == SIGQUIT */
  10073.         debug(F100,"in_chk conesc","",conesc);
  10074.         conesc = 0;
  10075.         signal(SIGQUIT,esctrp);    /* Restore signal */
  10076.         n += 1;
  10077.     }
  10078. #endif /* RDCHK */
  10079. #endif /* CK_POLL */
  10080. #endif /* SELECT */
  10081. #endif /* FIONREAD */
  10082. #endif /* SVORPOSIX */
  10083.  
  10084.     return(n);            /* Done with console */
  10085.     }
  10086.  
  10087.     if (channel != 0) {            /* Communications connection */
  10088.  
  10089. #ifdef MYREAD
  10090. #ifndef FIONREAD
  10091. /*
  10092.   select() or rdchk(), etc, has told us that something is waiting, but we
  10093.   don't know how much.  So we do a read to get it and then we know.  Note:
  10094.   This read is NOT nonblocking if nothing is there (because of VMIN=1), but
  10095.   it should be safe in this case since the OS tells us at least one byte is
  10096.   waiting to be read, and MYREAD reads return as much as is there without
  10097.   waiting for any more.  Controlled tests on Solaris and Unixware (with
  10098.   FIONREAD deliberately undefined) show this to be true.
  10099. */
  10100.     debug(F101,"in_chk read my_count","",my_count);
  10101.     debug(F101,"in_chk read n","",n);
  10102.     if (n > 0 && my_count == 0) {
  10103.         /* This also catches disconnects etc */
  10104.         /* Do what mygetbuf does except don't grab a character */
  10105.         my_count = myfillbuf();
  10106.         my_item = -1;        /* ^^^ */
  10107.         debug(F101,"in_chk myfillbuf my_count","",my_count);
  10108.         if (my_count < 0)
  10109.           return(-1);
  10110.         else
  10111.           n = 0;            /* NB: n is replaced by my_count */
  10112.     }
  10113. #endif /* FIONREAD */
  10114. /*
  10115.   Here we add whatever we think is unread to what is still in our
  10116.   our internal buffer.  Thus the importance of setting n to 0 just above.
  10117. */
  10118.     debug(F101,"in_chk my_count","",my_count);
  10119.     debug(F101,"in_chk n","",n);
  10120.     if (my_count > 0)
  10121.       n += my_count;
  10122. #endif /* MYREAD */
  10123.     }
  10124.     debug(F101,"in_chk result","",n);
  10125.  
  10126.     /* Errors here don't prove the connection has dropped so just say 0 */
  10127.  
  10128.     return(n < 0 ? 0 : n);
  10129. }
  10130.  
  10131.  
  10132. /*  T T C H K  --  Tell how many characters are waiting in tty input buffer  */
  10133.  
  10134. int
  10135. ttchk() {
  10136.     int fd;
  10137. #ifdef NETCMD
  10138.     if (ttpipe)
  10139.       fd = fdin;
  10140.     else
  10141. #endif /* NETCMD */
  10142.       fd = ttyfd;
  10143.     return(in_chk(1,fd));
  10144. }
  10145.  
  10146. /*  T T X I N  --  Get n characters from tty input buffer  */
  10147.  
  10148. /*  Returns number of characters actually gotten, or -1 on failure  */
  10149.  
  10150. /*  Intended for use only when it is known that n characters are actually */
  10151. /*  Available in the input buffer.  */
  10152.  
  10153. int
  10154. ttxin(n,buf) int n; CHAR *buf; {
  10155.     register int x = 0, c = -2;
  10156. #ifdef TTLEBUF
  10157.     register int i = 0;
  10158. #endif /* TTLEBUF */
  10159.     int fd;
  10160.  
  10161.     if (n < 1)                /* Nothing to do */
  10162.       return(0);
  10163.  
  10164. #ifdef TTLEBUF
  10165.     if (ttpush >= 0) {
  10166.         buf[0] = ttpush;        /* Put pushed char in buffer*/
  10167.         ttpush = -1;            /* Clear the push buffer */
  10168.         if (ttchk() > 0)
  10169.       return(ttxin(n-1, &buf[1]) + 1);
  10170.         else
  10171.       return(1);
  10172.     }
  10173.     if (le_data) {
  10174.         while (le_inbuf() > 0) {
  10175.         if (le_getchar(&buf[i])) {
  10176.                 i++;
  10177.                 n--;
  10178.             }
  10179.         }
  10180.         if (ttchk() > 0)
  10181.       return(ttxin(n,&buf[i])+i);
  10182.         else
  10183.       return(i);
  10184.     }
  10185. #endif /* TTLEBUF */
  10186.  
  10187. #ifdef NETCMD
  10188.     if (ttpipe)
  10189.       fd = fdin;
  10190.     else
  10191. #endif /* NETCMD */
  10192.       fd = ttyfd;
  10193.  
  10194. #ifdef SUNX25
  10195.     if (netconn && (ttnet == NET_SX25))    /* X.25 connection */
  10196.       return(x25xin(n,buf));
  10197. #endif /* SUNX25 */
  10198.  
  10199. #ifdef IBMX25
  10200.     /* riehm: possibly not needed. Test worked with normal reads and writes */
  10201.     if (netconn && (ttnet == NET_IX25))    { /* X.25 connection */
  10202.     x = x25xin(n,buf);
  10203.     if (x > 0) buf[x] = '\0';
  10204.     return(x);
  10205.     }
  10206. #endif /* IBMX25 */
  10207.  
  10208. #ifdef MYREAD
  10209.     debug(F101,"ttxin MYREAD","",n);
  10210.     while (x < n) {
  10211.     c = myread();
  10212.     if (c < 0) {
  10213.         debug(F101,"ttxin myread returns","",c);
  10214.         if (c == -3) x = -1;
  10215.         break;
  10216.         }
  10217.     buf[x++] = c & ttpmsk;
  10218. #ifdef RLOGCODE
  10219. #ifdef CK_KERBEROS
  10220.         /* It is impossible to know how many characters are waiting */
  10221.         /* to be read when you are using Encrypted Rlogin or SSL    */
  10222.         /* as the transport since the number of real data bytes     */
  10223.         /* can be greater or less than the number of bytes on the   */
  10224.         /* wire which is what ttchk() returns.                      */
  10225.         if (netconn && (ttnproto == NP_EK4LOGIN || ttnproto == NP_EK5LOGIN))
  10226.       if (ttchk() <= 0)
  10227.         break;
  10228. #endif /* CK_KERBEROS */
  10229. #endif /* RLOGCODE */
  10230. #ifdef CK_SSL
  10231.         if (ssl_active_flag || tls_active_flag)
  10232.       if (ttchk() <= 0)
  10233.         break;
  10234. #endif /* CK_SSL */
  10235.     }
  10236. #else
  10237.     debug(F101,"ttxin READ","",n);
  10238.     x = read(fd,buf,n);
  10239.     for (c = 0; c < n; c++)        /* Strip any parity */
  10240.       buf[c] &= ttpmsk;
  10241. #endif /* MYREAD */
  10242.  
  10243.     debug(F101,"ttxin x","",x);        /* Done */
  10244.     if (x > 0) buf[x] = '\0';
  10245.     if (x < 0) x = -1;
  10246.     return(x);
  10247. }
  10248.  
  10249. /*  T T O L  --  Write string s, length n, to communication device.  */
  10250. /*
  10251.   Returns:
  10252.    >= 0 on success, number of characters actually written.
  10253.    -1 on failure.
  10254. */
  10255. #ifdef CK_ENCRYPTION
  10256. CHAR * xpacket = NULL;
  10257. int nxpacket = 0;
  10258. #endif /* CK_ENCRYPTION */
  10259.  
  10260. #define TTOLMAXT 5
  10261. int
  10262. ttol(s,n) int n; CHAR *s; {
  10263.     int x, len, tries, fd;
  10264. #ifdef CKXXCHAR
  10265.     extern int dblflag;            /* For SET SEND DOUBLE-CHARACTER */
  10266.     extern short dblt[];
  10267.     CHAR *p = NULL, *p2, *s2, c;
  10268.     int n2 = 0;
  10269. #endif /* CKXXCHAR */
  10270.  
  10271.     if (ttyfd < 0)            /* Not open? */
  10272.       return(-3);
  10273. #ifdef DEBUG
  10274.     if (deblog) {
  10275.     /* debug(F101,"ttol ttyfd","",ttyfd); */
  10276.     hexdump("ttol s",s,n);
  10277.     }
  10278. #endif /* DEBUG */
  10279.  
  10280. #ifdef NETCMD
  10281.     if (ttpipe)
  10282.       fd = fdout;
  10283.     else
  10284. #endif /* NETCMD */
  10285.       fd = ttyfd;
  10286.  
  10287. #ifdef CKXXCHAR
  10288. /*  Double any characters that must be doubled.  */
  10289.     debug(F101,"ttol dblflag","",dblflag);
  10290.     if (dblflag) {
  10291.     p = (CHAR *) malloc(n + n + 1);
  10292.     if (p) {
  10293.         s2 = s;
  10294.         p2 = p;
  10295.         n2 = 0;
  10296.         while (*s2) {
  10297.         c = *s2++;
  10298.         *p2++ = c;
  10299.         n2++;
  10300.         if (dblt[(unsigned) c] & 2) {
  10301.             *p2++ = c;
  10302.             n2++;
  10303.         }
  10304.         }
  10305.         s = p;
  10306.         n = n2;
  10307.         s[n] = '\0';
  10308.     }
  10309. #ifdef DEBUG
  10310.         if (deblog) hexdump("ttol doubled s",s,n);
  10311. #endif /* DEBUG */
  10312.     }
  10313. #endif /* CKXXCHAR */
  10314.  
  10315.     tries = TTOLMAXT;            /* Allow up to this many tries */
  10316.     len = n;                /* Remember original length */
  10317.  
  10318. #ifdef CK_ENCRYPTION
  10319. /*
  10320.   This is to avoid encrypting a packet that is already encrypted, e.g.
  10321.   when we resend a packet directly out of the packet buffer, and also to
  10322.   avoid encrypting a constant (literal) string, which can cause a memory
  10323.   fault.
  10324. */
  10325.     if (TELOPT_ME(TELOPT_ENCRYPTION)) {
  10326.     int x;
  10327.     if (nxpacket < n) {
  10328.         if (xpacket) {
  10329.         free(xpacket);
  10330.         xpacket = NULL;
  10331.         nxpacket = 0;
  10332.         }
  10333.         x = n > 10240 ? n : 10240;
  10334.         xpacket = (CHAR *)malloc(x);
  10335.         if (!xpacket) {
  10336.         fprintf(stderr,"ttol malloc failure\n");
  10337.         return(-1);
  10338.         } else
  10339.           nxpacket = x;
  10340.     }
  10341.     memcpy((char *)xpacket,(char *)s,n);
  10342.     s = xpacket;
  10343.     ck_tn_encrypt((char *)s,n);
  10344.     }
  10345. #endif /* CK_ENCRYPTION */
  10346.  
  10347.     while (n > 0 &&
  10348.        (tries-- > 0
  10349. #ifdef CK_ENCRYPTION
  10350.         /* keep trying if we are encrypting */
  10351.         || TELOPT_ME(TELOPT_ENCRYPTION)
  10352. #endif /* CK_ENCRYPTION */
  10353.             )) {            /* Be persistent */
  10354.     debug(F101,"ttol try","",TTOLMAXT - tries);
  10355. #ifdef BEOSORBEBOX
  10356.         if (netconn && !ttpipe && !ttpty)
  10357.       x = nettol((char *)s,n);    /* Write string to device */
  10358.         else
  10359. #endif /* BEOSORBEBOX */
  10360. #ifdef IBMX25
  10361.       if (ttnet == NET_IX25)
  10362.         /*
  10363.          * this is a more controlled way of writing to X25
  10364.          * STREAMS, however write should also work!
  10365.          */
  10366.         x = x25write(ttyfd, s, n);
  10367.       else
  10368. #endif /* IBMX25 */
  10369. #ifdef CK_SSL
  10370.         if (ssl_active_flag || tls_active_flag) {
  10371.         int error;
  10372.         /* Write using SSL */
  10373.                 ssl_retry:
  10374.         if (ssl_active_flag)
  10375.                   x = SSL_write(ssl_con, s, n);
  10376.         else
  10377.                   x = SSL_write(tls_con, s, n);
  10378.         switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,x)) {
  10379.                 case SSL_ERROR_NONE:
  10380.                     if (x == n)
  10381.               return(len);
  10382.                     s += x;
  10383.                     n -= x;
  10384.                     goto ssl_retry;
  10385.           case SSL_ERROR_WANT_WRITE:
  10386.           case SSL_ERROR_WANT_READ:
  10387.             x = 0;
  10388.             break;
  10389.           case SSL_ERROR_SYSCALL:
  10390.                     if (x != 0)
  10391.               return(-1);
  10392.           case SSL_ERROR_WANT_X509_LOOKUP:
  10393.           case SSL_ERROR_SSL:
  10394.           case SSL_ERROR_ZERO_RETURN:
  10395.           default:
  10396.             ttclos(0);
  10397.             return(-3);
  10398.         }
  10399.         } else
  10400. #endif /* CK_SSL */
  10401. #ifdef CK_KERBEROS
  10402. #ifdef KRB4
  10403. #ifdef RLOGCODE
  10404.         if (ttnproto == NP_EK4LOGIN) {
  10405.         return(krb4_des_write(ttyfd,s,n));
  10406.         } else
  10407. #endif /* RLOGCODE */
  10408. #endif /* KRB4 */
  10409. #ifdef KRB5
  10410. #ifdef RLOGCODE
  10411.             if (ttnproto == NP_EK5LOGIN) {
  10412.                 return(krb5_des_write(ttyfd,(char *)s,n,0));
  10413.             } else
  10414. #endif /* RLOGCODE */
  10415. #ifdef KRB5_U2U
  10416.             if (ttnproto == NP_K5U2U) {
  10417.                 return(krb5_u2u_write(ttyfd,(char *)s,n));
  10418.             } else
  10419. #endif /* KRB5_U2U */
  10420. #endif /* KRB5 */
  10421. #endif /* CK_KERBEROS */
  10422.           x = write(fd,s,n);    /* Write string to device */
  10423.  
  10424.     if (x == n) {            /* Worked? */
  10425.         debug(F101,"ttol ok","",x);    /* OK */
  10426. #ifdef CKXXCHAR
  10427.         if (p) free(p);
  10428. #endif /* CKXXCHAR */
  10429.         return(len);        /* Done */
  10430.     } else if (x < 0) {        /* No, got error? */
  10431.         debug(F101,"ttol write error","",errno);
  10432. #ifdef EWOULDBLOCK
  10433.         if (errno == EWOULDBLOCK) {
  10434.         msleep(10);
  10435.         continue;
  10436.         } else
  10437. #endif /* EWOULDBLOCK */
  10438. #ifdef TCPSOCKET
  10439.         if (netconn && ttnet == NET_TCPB) {
  10440.         debug(F101,"ttol TCP error","",errno);
  10441.         ttclos(0);        /* Close the connection. */
  10442.         x = -3;
  10443.         }
  10444. #endif /* TCPSOCKET */
  10445. #ifdef CKXXCHAR
  10446.         if (p) free(p);
  10447. #endif /* CKXXCHAR */
  10448.         return(x);
  10449.     } else {            /* No error, so partial success */
  10450.         debug(F101,"ttol partial","",x); /* This never happens */
  10451.         s += x;            /* Point to part not written yet */
  10452.         n -= x;            /* Adjust length */
  10453.         if (x > 0) msleep(10);    /* Wait 10 msec */
  10454.     }                /* Go back and try again */
  10455.     }
  10456. #ifdef CKXXCHAR
  10457.     if (p) free(p);
  10458. #endif /* CKXXCHAR */
  10459.     return(n < 1 ? len : -1);        /* Return the results */
  10460. }
  10461.  
  10462. /*  T T O C  --  Output a character to the communication line  */
  10463.  
  10464. /*
  10465.  This function should only be used for interactive, character-mode operations,
  10466.  like terminal connection, script execution, dialer i/o, where the overhead
  10467.  of the signals and alarms does not create a bottleneck.
  10468. */
  10469. int
  10470. #ifdef CK_ANSIC
  10471. ttoc(char c)
  10472. #else
  10473. ttoc(c) char c;
  10474. #endif /* CK_ANSIC */
  10475. /* ttoc */ {
  10476. #define TTOC_TMO 15            /* Timeout in case we get stuck */
  10477.     int xx, fd;
  10478.  
  10479.     if (ttyfd < 0)            /* Check for not open. */
  10480.       return(-1);
  10481.  
  10482. #ifdef NETCMD
  10483.     if (ttpipe)
  10484.       fd = fdout;
  10485.     else
  10486. #endif /* NETCMD */
  10487.       fd = ttyfd;
  10488.  
  10489.     c &= 0xff;
  10490.     /* debug(F101,"ttoc","",(CHAR) c); */
  10491.     saval = signal(SIGALRM,timerh);    /* Enable timer interrupt */
  10492.     xx = alarm(TTOC_TMO);        /* for this many seconds. */
  10493.     if (xx < 0) xx = 0;            /* Save old alarm value. */
  10494.     /* debug(F101,"ttoc alarm","",xx); */
  10495.     if (
  10496. #ifdef CK_POSIX_SIG
  10497.     sigsetjmp(sjbuf,1)
  10498. #else
  10499.     setjmp(sjbuf)
  10500. #endif /* CK_POSIX_SIG */
  10501.     ) {        /* Timer went off? */
  10502.     ttimoff();            /* Yes, cancel this alarm. */
  10503.     if (xx - TTOC_TMO > 0) alarm(xx - TTOC_TMO); /* Restore previous one */
  10504.         /* debug(F100,"ttoc timeout","",0); */
  10505. #ifdef NETCONN
  10506.     if (!netconn) {
  10507. #endif /* NETCONN */
  10508.         debug(F101,"ttoc timeout","",c);
  10509.         if (ttflow == FLO_XONX) {
  10510.         debug(F101,"ttoc flow","",ttflow); /* Maybe we're xoff'd */
  10511. #ifndef Plan9
  10512. #ifdef POSIX
  10513.         /* POSIX way to unstick. */
  10514.         debug(F100,"ttoc tcflow","",tcflow(ttyfd,TCOON));
  10515. #else
  10516. #ifdef BSD4                /* Berkeley way to do it. */
  10517. #ifdef TIOCSTART
  10518. /* .... Used to be "ioctl(ttyfd, TIOCSTART, 0);".  Who knows? */
  10519.         {
  10520.           int x = 0;
  10521.           debug(F101,"ttoc TIOCSTART","",ioctl(ttyfd, TIOCSTART, &x));
  10522.         }
  10523. #endif /* TIOCSTART */
  10524. #endif /* BSD4 */
  10525.                     /* Is there a Sys V way to do this? */
  10526. #endif /* POSIX */
  10527. #endif /* Plan9 */
  10528.         }
  10529. #ifdef NETCONN
  10530.         }
  10531. #endif /* NETCONN */
  10532.     return(-1);            /* Return failure code. */
  10533.     } else {
  10534.         int rc;
  10535. #ifdef BEOSORBEBOX
  10536. #ifdef NETCONN
  10537.         if (netconn && !ttpipe && !ttpty)
  10538.       rc = nettoc(c);
  10539.         else
  10540. #endif /*  BEOSORBEBOX */
  10541. #endif /* NETCONN */
  10542. #ifdef CK_ENCRYPTION
  10543.       if (TELOPT_ME(TELOPT_ENCRYPTION))
  10544.         ck_tn_encrypt(&c,1);
  10545. #endif /* CK_ENCRYPTION */
  10546. #ifdef IBMX25
  10547.     /* riehm: maybe this isn't necessary after all. Test program
  10548.      * worked fine with data being sent and retrieved with normal
  10549.      * read's and writes!
  10550.      */
  10551.     if (ttnet == NET_IX25)
  10552.       rc = x25write(ttyfd,&c,1); /* as above for X25 streams */
  10553.     else
  10554. #endif /* IBMX25 */
  10555. #ifdef CK_SSL
  10556.       if (ssl_active_flag || tls_active_flag) {
  10557.           int error;
  10558.           /* Write using SSL */
  10559.           if (ssl_active_flag)
  10560.                 rc = SSL_write(ssl_con, &c, 1);
  10561.           else
  10562.                 rc = SSL_write(tls_con, &c, 1);
  10563.           switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,rc)){
  10564.         case SSL_ERROR_NONE:
  10565.           break;
  10566.         case SSL_ERROR_WANT_WRITE:
  10567.         case SSL_ERROR_WANT_READ:
  10568.           rc = 0;
  10569.           break;
  10570.         case SSL_ERROR_SYSCALL:
  10571.           if (rc != 0)
  10572.             return(-1);
  10573.         case SSL_ERROR_WANT_X509_LOOKUP:
  10574.         case SSL_ERROR_SSL:
  10575.         case SSL_ERROR_ZERO_RETURN:
  10576.         default:
  10577.           ttclos(0);
  10578.           return(-1);
  10579.           }
  10580.       } else
  10581. #endif /* CK_SSL */
  10582. #ifdef CK_KERBEROS
  10583. #ifdef KRB4
  10584. #ifdef RLOGCODE
  10585.       if (ttnproto == NP_EK4LOGIN) {
  10586.           rc = (krb4_des_write(ttyfd,(char *)&c,1) == 1);
  10587.       } else
  10588. #endif /* RLOGCODE */
  10589. #endif /* KRB4 */
  10590. #ifdef KRB5
  10591. #ifdef RLOGCODE
  10592.           if (ttnproto == NP_EK5LOGIN) {
  10593.               rc = (krb5_des_write(ttyfd,&c,1,0) == 1);
  10594.           } else
  10595. #endif /* RLOGCODE */
  10596. #ifdef KRB5_U2U
  10597.           if (ttnproto == NP_K5U2U) {
  10598.               rc = (krb5_u2u_write(ttyfd,&c,1) == 1);
  10599.           } else
  10600. #endif /* KRB5_U2U */
  10601. #endif /* KRB5 */
  10602. #endif /* CK_KERBEROS */
  10603.         rc = write(fd,&c,1);    /* Try to write the character. */
  10604.     if (rc < 1) {            /* Failed */
  10605.         ttimoff();            /* Turn off the alarm. */
  10606.         alarm(xx);            /* Restore previous alarm. */
  10607.         debug(F101,"ttoc errno","",errno); /* Log the error, */
  10608.         return(-1);            /* and return the error code. */
  10609.     }
  10610.     }
  10611.     ttimoff();                /* Success, turn off the alarm. */
  10612.     alarm(xx);                /* Restore previous alarm. */
  10613.     return(0);                /* Return good code. */
  10614. }
  10615.  
  10616. /*  T T I N L  --  Read a record (up to break character) from comm line.  */
  10617. /*
  10618.   Reads up to "max" characters from the connection, terminating on:
  10619.     (a) the packet length field if the "turn" argument is zero, or
  10620.     (b) on the packet-end character (eol) if the "turn" argument is nonzero
  10621.     (c) a certain number of Ctrl-C's in a row
  10622.  
  10623.   Returns:
  10624.     >= 0, the number of characters read upon success;
  10625.     -1 if "max" exceeded, timeout, or other correctable error;
  10626.     -2 on user interruption (c);
  10627.     -3 on fatal error like connection lost.
  10628.  
  10629.   The name of this routine dates from the early days when Kermit packets
  10630.   were, indeed, always lines of text.  That was before control-character
  10631.   unprefixing and length-driven packet framing were introduced, which this
  10632.   version handle.  NB: this routine is ONLY for reading incoming Kermit
  10633.   packets, nothing else.  To read other kinds of incoming material, use
  10634.   ttinc() or ttxin().
  10635.  
  10636.   The bytes that were input are copied into "dest" with their parity bits
  10637.   stripped if parity was selected.  Returns the number of bytes read.
  10638.   Bytes after the eol are available upon the next call to this function.
  10639.  
  10640.   The idea is to minimize the number of system calls per packet, and also to
  10641.   minimize timeouts.  This function is the inner loop of the protocol and must
  10642.   be as efficient as possible.  The current strategy is to use myread(), a
  10643.   macro to manage buffered (and generally nonblocking) reads.
  10644.  
  10645.   WARNING: This function calls parchk(), which is defined in another module.
  10646.   Normally, ckutio.c does not depend on code from any other module, but there
  10647.   is an exception in this case because all the other ck?tio.c modules also
  10648.   need to call parchk(), so it's better to have it defined in a common place.
  10649. */
  10650. #ifdef CTRLC
  10651. #undef CTRLC
  10652. #endif /* CTRLC */
  10653. #define CTRLC '\03'
  10654. /*
  10655.   We have four different declarations here because:
  10656.   (a) to allow Kermit to be built without the automatic parity sensing feature
  10657.   (b) one of each type for ANSI C, one for non-ANSI.
  10658. */
  10659. #ifndef NOXFER
  10660.  
  10661. static int pushedback = 0;
  10662.  
  10663. int
  10664. #ifdef PARSENSE
  10665. #ifdef CK_ANSIC
  10666. ttinl(CHAR *dest, int max,int timo, CHAR eol, CHAR start, int turn)
  10667. #else
  10668. ttinl(dest,max,timo,eol,start,turn) int max,timo,turn; CHAR *dest, eol, start;
  10669. #endif /* CK_ANSIC */
  10670. #else /* not PARSENSE */
  10671. #ifdef CK_ANSIC
  10672. ttinl(CHAR *dest, int max,int timo, CHAR eol)
  10673. #else
  10674. ttinl(dest,max,timo,eol) int max,timo; CHAR *dest, eol;
  10675. #endif /* CK_ANSIC */
  10676. #endif /* PARSENSE */
  10677. /* ttinl */ {
  10678.  
  10679. #ifndef MYREAD
  10680.     CHAR ch, dum;
  10681. #endif /* MYREAD */
  10682. #ifdef PARSENSE
  10683.     int pktlen = -1;
  10684.     int lplen = 0;
  10685.     int havelen = 0;
  10686. #endif /* PARSENSE */
  10687.     int fd;
  10688.     int sopmask = 0xff;            /* Start-Of-Packet mask */
  10689. #ifdef CKXXCHAR
  10690.     extern short dblt[];        /* Ignore-character table */
  10691.     extern int ignflag;
  10692. #endif /* CKXXCHAR */
  10693. #ifdef TCPSOCKET
  10694.     extern CHAR stchr;
  10695. #endif /* TCPSOCKET */
  10696.     int x;
  10697. #ifdef STREAMING
  10698.     extern int streaming;
  10699.     extern int sndtyp;
  10700. #endif /* STREAMING */
  10701.  
  10702.     if (ttyfd < 0) return(-3);          /* Not open. */
  10703. /*
  10704.   In February 2007 I fixed ttinl() to work better under the truly awful
  10705.   conditions encountered by the AM-APEX oceanographic floats that gather
  10706.   hurricane data and phone home using Iridium satellite modems, which under
  10707.   certain conditions, can send two packets back to back after a long pause.
  10708.   In this case the second packet would be ignored because the SOH was skipped
  10709.   due to the ttflui() call.  But the reworked lookahead/pushback logic broke
  10710.   Kermit transfers on encrypted connections.  This was fixed 12-13 August
  10711.   2007.  All of this happened after 8.0.212 Dev.27 was released and before
  10712.   Dev.28, so no harm done other than the delay.
  10713. */
  10714.     debug(F101,"ttinl max","",max);
  10715.     debug(F101,"ttinl timo","",timo);
  10716.  
  10717. #ifdef NETCMD
  10718.     if (ttpipe)
  10719.       fd = fdin;
  10720.     else
  10721. #endif /* NETCMD */
  10722.       fd = ttyfd;
  10723.  
  10724. #ifdef COMMENT
  10725.     if (xlocal && conchk() > 0)        /* Allow for console interruptions */
  10726.       return(-1);
  10727. #endif /* COMMENT */
  10728.  
  10729.     *dest = '\0';                       /* Clear destination buffer */
  10730.     if (timo < 0) timo = 0;        /* Safety */
  10731.     if (timo) {                /* Don't time out if timo == 0 */
  10732.     int xx;
  10733.     saval = signal(SIGALRM,timerh);    /* Enable timer interrupt */
  10734.     xx = alarm(timo);        /* Set it. */
  10735.     debug(F101,"ttinl alarm","",xx);
  10736.     }
  10737.     if (
  10738. #ifdef CK_POSIX_SIG
  10739.     sigsetjmp(sjbuf,1)
  10740. #else
  10741.     setjmp(sjbuf)
  10742. #endif /* CK_POSIX_SIG */
  10743.     ) {                /* Timer went off? */
  10744.     debug(F100,"ttinl timout","",0); /* Get here on timeout. */
  10745.     /* debug(F110," with",(char *) dest,0); */
  10746.     ttimoff();            /* Turn off timer */
  10747.     return(-1);            /* and return error code. */
  10748.     } else {
  10749.     register int i, n = -1;        /* local variables */
  10750.     int ccn = 0;
  10751. #ifdef PARSENSE
  10752.     register int flag = 0;
  10753.     debug(F000,"ttinl start","",start);
  10754. #endif /* PARSENSE */
  10755.  
  10756.     ttpmsk = ttprty ? 0177 : 0377;    /* Set parity stripping mask. */
  10757.     sopmask = needpchk ? 0177 : ttpmsk; /* And SOP matching mask. */
  10758.  
  10759. /* Now read into destination, stripping parity and looking for the */
  10760. /* the packet terminator, and also for several Ctrl-C's typed in a row. */
  10761.  
  10762.     i = 0;                /* Destination index */
  10763.     debug(F101,"ttinl eol","",eol);
  10764.  
  10765.     while (i < max-1) {
  10766. #ifdef MYREAD
  10767.         errno = 0;
  10768.         /* On encrypted connections myread returns encrypted bytes */
  10769.         n = myread();
  10770.         debug(F000,"TTINL myread char","",n);
  10771.         if (n < 0) {    /* Timeout or i/o error? */
  10772. #ifdef DEBUG
  10773.         if (deblog) {
  10774.             debug(F101,"ttinl myread failure, n","",n);
  10775.             debug(F101,"ttinl myread errno","",errno);
  10776.         }
  10777. #endif /* DEBUG */
  10778.         /* Don't let EINTR break packets. */
  10779.         if (n == -3) {
  10780.             if (errno == EINTR && i > 0) {
  10781.             debug(F111,"ttinl EINTR myread i","continuing",i);
  10782.             continue;
  10783.             } else {
  10784.             debug(F110,"ttinl non-EINTR -3","closing",0);
  10785.             wasclosed = 1;
  10786.             ttimoff();    /* Turn off timer */
  10787.             ttclos(0);
  10788.             return(n);
  10789.             }
  10790.         } else if (n == -2 && netconn /* && timo == 0 */ ) {
  10791.             /* Here we try to catch broken network connections */
  10792.             /* even when ioctl() and read() do not catch them */
  10793.             debug(F111,"ttinl network myread failure","closing",n);
  10794.             wasclosed = 1;
  10795.             ttimoff();
  10796.             ttclos(0);
  10797.             return(-3);
  10798.         }
  10799. #ifdef STREAMING
  10800.         /* Streaming and no data to read */
  10801.         else if (n == 0 && streaming && sndtyp == 'D')
  10802.           return(0);
  10803. #endif /* STREAMING */
  10804.         break;            /* Break out of while loop */
  10805.         }
  10806.  
  10807. #else /* not MYREAD (is this code used anywhere any more?) */
  10808. /*
  10809.   The non-MYREAD code dates from the 1980s and was needed on certain platforms
  10810.   where there were no nonblocking reads.  -fdc, 2007/02/22.
  10811. */
  10812.         if ((n = read(fd, &n, 1)) < 1)
  10813.           break;            /* Error - break out of while loop */
  10814.  
  10815. #endif /* MYREAD */
  10816.  
  10817.         /* Get here with char in n */
  10818.  
  10819. #ifdef CK_ENCRYPTION
  10820.         if (TELOPT_U(TELOPT_ENCRYPTION) && !pushedback) {
  10821.         CHAR ch = n;
  10822.         ck_tn_decrypt((char *)&ch,1);
  10823.         n = ch;
  10824.         debug(F000,"TTINL decryp char","",n);
  10825.         }
  10826.         pushedback = 0;
  10827. #endif /* CK_ENCRYPTION */
  10828.  
  10829. #ifdef TCPSOCKET
  10830.         if (n == IAC &&        /* Handle Telnet options */
  10831.         ((xlocal && netconn && IS_TELNET()) ||
  10832.         (!xlocal && sstelnet))) {
  10833.         n = tt_tnopt(n);
  10834.         if (n < 0)
  10835.           return(n);
  10836. #ifndef NOPARSEN
  10837.         else if (n == 1)
  10838.           start = stchr;
  10839. #endif /* NOPARSEN */
  10840.         if (n != 255)        /* No data - go back for next char */
  10841.           continue;
  10842.         }                /* Quoted IAC - keep going */
  10843. #endif /* TCPSOCKET */
  10844.  
  10845. #ifdef CKXXCHAR
  10846.         if (ignflag)
  10847.           if (dblt[(unsigned) n] & 1) /* Character to ignore? */
  10848.         continue;
  10849. #endif /* CKXXCHAR */
  10850. /*
  10851.   Use parity mask, rather than always stripping parity, to check for
  10852.   cancellation.  Otherwise, runs like \x03\x83\x03 in a packet could cancel
  10853.   the transfer when parity is NONE.  (Note that \x03\x03\x03 is extremely
  10854.   unlikely due to run-length encoding.)
  10855. */
  10856.         /* Check cancellation */
  10857.         if (!xlocal && xfrcan && ((n & ttpmsk) == xfrchr)) {
  10858.         if (++ccn >= xfrnum) {    /* If xfrnum in a row, bail out. */
  10859.             if (timo) {        /* Clear timer. */
  10860.             ttimoff();
  10861.             }
  10862.             if (xfrchr < 32)
  10863.               printf("^%c...\r\n",(char)(xfrchr+64));
  10864.             else
  10865.               printf("Canceled...\r\n");
  10866.             return(-2);
  10867.         }
  10868.         } else ccn = 0;        /* No cancellation, reset counter, */
  10869.  
  10870. #ifdef PARSENSE
  10871. /*
  10872.   Restructured code allows for a new packet to appear somewhere in the
  10873.   middle of a previous one.  -fdc, 24 Feb 2007.
  10874. */
  10875.         if ((n & sopmask) == start) { /* Start of Packet */
  10876.         debug(F101,"ttinl SOP i","",i);
  10877.         flag = 1;        /* Flag that we are in a packet */
  10878.         havelen = 0;        /* Invalidate previous length */
  10879.         pktlen = -1;        /* (if any) in case we were */
  10880.         lplen = 0;        /* alread processand a packet */
  10881.         i = 0;            /* and reset the dest buffer pointer */
  10882.         }
  10883.         if (flag == 0) {        /* No SOP yet... */
  10884.         debug(F000,"ttinl skipping","",n);
  10885.         continue;
  10886.         }
  10887.         dest[i++] = n & ttpmsk;
  10888. /*
  10889.   If we have not been instructed to wait for a turnaround character, we
  10890.   can go by the packet length field.  If turn != 0, we must wait for the
  10891.   end of line (eol) character before returning.  This is an egregious
  10892.   violation of all principles of layering...
  10893. */
  10894.         if (!havelen) {
  10895.         if (i == 2) {
  10896.             pktlen = xunchar(dest[1] & 0x7f);
  10897.             if (pktlen > 1) {
  10898.             havelen = 1;
  10899.             debug(F101,"ttinl pktlen value","",pktlen);
  10900.             }
  10901.         } else if (i == 5 && pktlen == 0) {
  10902.             lplen = xunchar(dest[4] & 0x7f);
  10903.         } else if (i == 6 && pktlen == 0) {
  10904.             pktlen = lplen * 95 + xunchar(dest[5] & 0x7f) + 5;
  10905.             havelen = 1;
  10906.             debug(F101,"ttinl extended length","",pktlen);
  10907.         }
  10908.         }
  10909.  
  10910. /*
  10911.   Suppose we looked at the sequence number here and found it was out of
  10912.   range?  This would mean either (a) incoming packets had SOP unprefixed
  10913.   and we are out of sync, or (b) the packet is damaged.  Since (a) is bad
  10914.   practice, let's ignore it.  So what should we do here if we know the
  10915.   packet is damaged?
  10916.  
  10917.    1. Nothing -- keep trying to read the packet till we find what we think
  10918.       is the end, or we time out, and let the upper layer decide what to
  10919.       do.  But since either the packet is corrupt or we are out of sync,
  10920.       our criterion for finding the end does not apply and we are likely
  10921.       to time out (or swallow a piece of the next packet) if our assumed
  10922.       length is too long.  (This was the behavior prior to version 7.0.)
  10923.  
  10924.    2. set flag = 0 and continue?  This would force us to wait for the
  10925.       next packet to come in, and therefore (in the nonwindowing case),
  10926.       would force a timeout in the other Kermit.
  10927.  
  10928.    3. set flag = 0 and continue, but only if the window size is > 1 and
  10929.       the window is not blocked?  Talk about cheating!
  10930.  
  10931.    4. Return a failure code and let the upper layer decide what to do.
  10932.       This should be equivalent to 3, but without the cheating.  So let's
  10933.       do it that way...  But note that we must ignore the parity bit
  10934.       in case this is the first packet and we have not yet run parchk().
  10935. */
  10936.         if (i == 3) {        /* Peek at sequence number */
  10937.         x = xunchar((dest[i-1] & 0x7f)); /* If it's not in range... */
  10938.         if (x < 0 || x > 63) {
  10939.             debug(F111,"ttinl bad seq",dest,x);
  10940.             if (timo) ttimoff();
  10941.             return(-1);        /* return a nonfatal error */
  10942.         }
  10943.         }
  10944.  
  10945. #else /* PARSENSE */
  10946.         dest[i++] = n & ttpmsk;
  10947. #endif /* PARSENSE */
  10948.  
  10949.     /* Check for end of packet */
  10950.  
  10951.         if (
  10952. #ifdef PARSENSE
  10953. /*
  10954.   Purely length-driven if SET HANDSHAKE NONE (i.e. turn == 0).
  10955.   This allows packet terminators and handshake characters to appear
  10956.   literally inside a packet data field.
  10957. */
  10958.         (havelen && (i > pktlen+1) &&
  10959.          (!turn || (turn && (n & 0x7f) == turn))) /* (turn, not eol) */
  10960. #else /* !PARSENSE */
  10961. /*
  10962.   Built without PARSENSE, so just look for packet terminator.
  10963. */
  10964.         ((n & 0x7f) == eol)
  10965. #endif /* PARSENSE */
  10966.         ) {
  10967. /*
  10968.   Here we have either read the last byte of the packet based on its length
  10969.   field, or else we have read the packet terminator (eol) or the half-duplex
  10970.   line-turnaround char (turn).
  10971. */
  10972. #ifndef PARSENSE
  10973.         debug(F101,"ttinl got eol","",eol); /* (or turn) */
  10974.         dest[i] = '\0';        /* Yes, terminate the string, */
  10975.         /* debug(F101,"ttinl i","",i); */
  10976.  
  10977. #else  /* PARSENSE */
  10978.  
  10979. #ifdef DEBUG
  10980.         if (deblog) {
  10981.             if ((n & 0x7f) != eol) {
  10982.             debug(F101,"ttinl EOP length","",pktlen);
  10983.             debug(F000,"ttinl EOP current char","",n);
  10984.             debug(F101,"ttinl EOP packet buf index","",i);
  10985.             } else debug(F101,"ttinl got eol","",eol);
  10986.         }
  10987. #endif /* DEBUG */
  10988.  
  10989. #ifdef MYREAD
  10990. /*
  10991.   The packet was read based on its length.  This leaves the packet terminator
  10992.   unread, and so ttchk() will always return at least 1 because of this,
  10993.   possibly giving a false positive to the "is there another packet waiting?"
  10994.   test.  But if we know the terminator (or any other interpacket junk) is
  10995.   there, we can safely get rid of it.
  10996.  
  10997.   NOTE: This code reworked to (a) execute even if the debug log isn't active;
  10998.   and (b) actually work.  -fdc, 2007/02/22.  And again 2007/08/12-13 to also
  10999.   work on encrypted connections.
  11000. */    
  11001.         debug(F101,"TTINL my_count","",my_count);
  11002.         if ((n & ttpmsk) != eol) { /* Not the packet terminator */
  11003.             int x;
  11004.             while (my_count > 0) {
  11005.             x = myread();       /* (was ttinc(0) */
  11006.             debug(F000,"TTINL lkread char","",x);
  11007. #ifdef CK_ENCRYPTION
  11008.             if (TELOPT_U(TELOPT_ENCRYPTION)) {
  11009.                 CHAR ch = x;
  11010.                 ck_tn_decrypt((char *)&ch,1);
  11011.                 x = ch;
  11012.                 debug(F000,"TTINL lkdecr char","",x); 
  11013.             }
  11014. #endif    /* CK_ENCRYPTION */
  11015.             /*
  11016.               Note: while it might seem more elegant to simply
  11017.               push back the encrypted byte, that desynchronizes
  11018.               the decryption stream; the flag is necessary so we
  11019.               don't try to decrypt the same byte twice.
  11020.             */
  11021.             if ((x & ttpmsk) == start) { /* Start of next packet */
  11022.                 myunrd(x);    /* Push back the decrypted byte */
  11023.                 pushedback = 1; /* And set flag */
  11024.                 debug(F000,"TTINL lkpush char","",x);
  11025.                 break;
  11026.             }
  11027.             }
  11028.         }
  11029. #endif /* MYREAD */
  11030.  
  11031.         dest[i] = '\0';        /* Terminate the string, */
  11032.             if (needpchk) {        /* Parity checked yet? */
  11033.             if (ttprty == 0) {    /* No, check. */
  11034.             if ((ttprty = parchk(dest,start,i)) > 0) {
  11035.                 int j;
  11036.                 debug(F101,"ttinl senses parity","",ttprty);
  11037.                 debug(F110,"ttinl packet before",dest,0);
  11038.                 ttpmsk = 0x7f;
  11039.                 for (j = 0; j < i; j++)
  11040.                   dest[j] &= 0x7f;    /* Strip parity from packet */
  11041.                 debug(F110,"ttinl packet after ",dest,0);
  11042.             } else ttprty = 0; /* Restore if parchk error */
  11043.             }
  11044.             sopmask = ttpmsk;
  11045.             needpchk = 0;
  11046.         }
  11047. #endif /* PARSENSE */
  11048.  
  11049.         if (timo)        /* Turn off timer if it was on */
  11050.           ttimoff();
  11051.                 hexdump("ttinl got",dest,i);
  11052.  
  11053. #ifdef STREAMING
  11054.         /* ttinl() was called because there was non-packet */
  11055.         /* data sitting in the back channel.  Ignore it.   */
  11056.         if (streaming && sndtyp == 'D')
  11057.           return(-1);
  11058. #endif /* STREAMING */
  11059.         return(i);
  11060.         }
  11061.     } /* End of while() */
  11062.     ttimoff();
  11063.     return(n);
  11064.     }
  11065. }
  11066. #endif /* NOXFER */
  11067.  
  11068. /*  T T I N C --  Read a character from the communication line  */
  11069. /*
  11070.  On success, returns the character that was read, >= 0.
  11071.  On failure, returns -1 or other negative myread error code,
  11072.    or -2 if connection is broken or ttyfd < 0.
  11073.    or -3 if session limit has expired,
  11074.    or -4 if something or other...
  11075.  NOTE: The API does not provide for ttinc() returning a special code
  11076.  upon timeout, but we need it.  So for this we have a global variable,
  11077.  ttinctimo.
  11078. */
  11079. static int ttinctimo = 0;        /* Yuk */
  11080.  
  11081. int
  11082. ttinc(timo) int timo; {
  11083.  
  11084.     int n = 0, fd;
  11085.     int is_tn = 0;
  11086.     CHAR ch = 0;
  11087.  
  11088.     ttinctimo = 0;
  11089.  
  11090.     if (ttyfd < 0) return(-2);          /* Not open. */
  11091.  
  11092.     is_tn = (xlocal && netconn && IS_TELNET()) ||
  11093.         (!xlocal && sstelnet);
  11094.  
  11095. #ifdef TTLEBUF
  11096.     if (ttpush >= 0) {
  11097.         debug(F111,"ttinc","ttpush",ttpush);
  11098.         ch = ttpush;
  11099.         ttpush = -1;
  11100.         return(ch);
  11101.     }
  11102.     if (le_data) {
  11103.         if (le_getchar(&ch) > 0) {
  11104.             debug(F111,"ttinc le_getchar","ch",ch);
  11105.             return(ch);
  11106.         }
  11107.     }
  11108. #endif /* TTLEBUF */
  11109.  
  11110. #ifdef NETCMD
  11111.     if (ttpipe)
  11112.       fd = fdin;
  11113.     else
  11114. #endif /* NETCMD */
  11115.       fd = ttyfd;
  11116.  
  11117.     if ((timo <= 0)            /* Untimed. */
  11118. #ifdef MYREAD
  11119.     || (my_count > 0)        /* Buffered char already waiting. */
  11120. #endif /* MYREAD */
  11121.     ) {
  11122. #ifdef MYREAD
  11123.         /* Comm line failure returns -1 thru myread, so no &= 0377 */
  11124.     n = myread();            /* Wait for a character... */
  11125.     /* debug(F000,"ttinc MYREAD n","",n); */
  11126. #ifdef CK_ENCRYPTION
  11127.     /* debug(F101,"ttinc u_encrypt","",TELOPT_U(TELOPT_ENCRYPTION)); */
  11128.     if (TELOPT_U(TELOPT_ENCRYPTION) && n >= 0) {
  11129.         ch = n;
  11130.         ck_tn_decrypt((char *)&ch,1);
  11131.         n = ch;
  11132.     }
  11133. #endif /* CK_ENCRYPTION */
  11134.  
  11135. #ifdef NETPTY
  11136.     if (ttpty && n < 0) {
  11137.         debug(F101,"ttinc error on pty","",n);
  11138.         ttclos(0);
  11139.         return(n);
  11140.     }
  11141. #endif /* NETPTY */
  11142.  
  11143. #ifdef TNCODE
  11144.     if ((n > -1) && is_tn)
  11145.       return((unsigned)(n & 0xff));
  11146.     else
  11147. #endif /* TNCODE */
  11148.       return(n < 0 ? n : (unsigned)(n & ttpmsk));
  11149.  
  11150. #else  /* MYREAD */
  11151.  
  11152.         while ((n = read(fd,&ch,1)) == 0) /* Wait for a character. */
  11153.         /* Shouldn't have to loop in ver 5A. */
  11154. #ifdef NETCONN
  11155.       if (netconn) {        /* Special handling for net */
  11156.           netclos();        /* If read() returns 0 it means */
  11157.           netconn = 0;        /* the connection has dropped. */
  11158.           errno = ENOTCONN;
  11159.           return(-2);
  11160.       }
  11161. #endif /* NETCONN */
  11162.       ;
  11163.     /* debug(F101,"ttinc","",ch); */
  11164. #ifdef TNCODE
  11165.     if ((n > 0) && is_tn) {
  11166. #ifdef CK_ENCRYPTION
  11167.         if (TELOPT_U(TELOPT_ENCRYPTION)) {
  11168.         ck_tn_decrypt(&ch,1);
  11169.         n = ch;
  11170.         }
  11171. #endif /* CK_ENCRYPTION */
  11172.         return((unsigned)(ch & 0xff));
  11173.     } else
  11174. #endif /* TNCODE */
  11175.         return((n < 0) ? -4 : ((n == 0) ? -1 : (unsigned)(ch & ttpmsk)));
  11176. #endif /* MYREAD */
  11177.  
  11178.     } else {                /* Timed read */
  11179.  
  11180.     int oldalarm;
  11181.     saval = signal(SIGALRM,timerh);    /* Set up handler, save old one. */
  11182.     oldalarm = alarm(timo);        /* Set alarm, save old one. */
  11183.     if (
  11184. #ifdef CK_POSIX_SIG
  11185.         sigsetjmp(sjbuf,1)
  11186. #else
  11187.         setjmp(sjbuf)
  11188. #endif /* CK_POSIX_SIG */
  11189.         ) {                /* Timer expired */
  11190.         ttinctimo = 1;
  11191.         n = -1;            /* set flag */
  11192.     } else {
  11193. #ifdef MYREAD
  11194.         n = myread();        /* If managing own buffer... */
  11195.         debug(F101,"ttinc myread","",n);
  11196.         ch = n;
  11197. #else
  11198.         n = read(fd,&ch,1);        /* Otherwise call the system. */
  11199.         if (n == 0) n = -1;
  11200.         debug(F101,"ttinc read","",n);
  11201. #endif /* MYREAD */
  11202.  
  11203. #ifdef CK_ENCRYPTION
  11204.         if (TELOPT_U(TELOPT_ENCRYPTION) && n >= 0) {
  11205.         ck_tn_decrypt((char *)&ch,1);
  11206.         }
  11207. #endif /* CK_ENCRYPTION */
  11208.         if (n >= 0)
  11209.           n = (unsigned) (ch & 0xff);
  11210.         else
  11211.           n = (n < 0) ? -4 : -2;    /* Special return codes. */
  11212.     }
  11213.     ttimoff();            /* Turn off the timer */
  11214.     if (oldalarm > 0) {
  11215.         if (n == -1)        /* and restore any previous alarm */
  11216.           oldalarm -= timo;
  11217.         if (oldalarm < 0)        /* adjusted by our timeout interval */
  11218.           oldalarm = 0;
  11219.         if (oldalarm) {
  11220.             debug(F101,"ttinc restoring oldalarm","",oldalarm);
  11221.         alarm(oldalarm);
  11222.         }
  11223.     }
  11224. #ifdef NETCONN
  11225.     if (netconn) {
  11226.         if (n == -2) {        /* read() returns 0 */
  11227.         netclos();        /* on network read failure */
  11228.         netconn = 0;
  11229.         errno = ENOTCONN;
  11230.         }
  11231.     }
  11232. #endif    /* NETCONN */
  11233. #ifdef TNCODE
  11234.     if ((n > -1) && is_tn)
  11235.       return((unsigned)(n & 0xff));
  11236.     else
  11237. #endif /* TNCODE */
  11238.       /* Return masked char or neg. */
  11239.       return( (n < 0) ? n : (unsigned)(n & ttpmsk) );
  11240.     }
  11241. }
  11242.  
  11243. /*  S N D B R K  --  Send a BREAK signal of the given duration  */
  11244.  
  11245. static int
  11246. #ifdef CK_ANSIC
  11247. sndbrk(int msec) {            /* Argument is milliseconds */
  11248. #else
  11249. sndbrk(msec) int msec; {
  11250. #endif /* CK_ANSIC */
  11251. #ifndef POSIX
  11252.     int x, n;
  11253. #endif /* POSIX */
  11254.  
  11255. #ifdef OXOS
  11256. #define BSDBREAK
  11257. #endif /* OXOS */
  11258.  
  11259. #ifdef ANYBSD
  11260. #define BSDBREAK
  11261. #endif /* ANYBSD */
  11262.  
  11263. #ifdef BSD44
  11264. #define BSDBREAK
  11265. #endif /* BSD44 */
  11266.  
  11267. #ifdef COHERENT
  11268. #ifdef BSDBREAK
  11269. #undef BSDBREAK
  11270. #endif /* BSDBREAK */
  11271. #endif /* COHERENT */
  11272.  
  11273. #ifdef BELLV10
  11274. #ifdef BSDBREAK
  11275. #undef BSDBREAK
  11276. #endif /* BSDBREAK */
  11277. #endif /* BELLV10 */
  11278.  
  11279. #ifdef PROVX1
  11280.     char spd;
  11281. #endif /* PROVX1 */
  11282.  
  11283.     debug(F101,"ttsndb ttyfd","",ttyfd);
  11284.     if (ttyfd < 0) return(-1);          /* Not open. */
  11285.  
  11286. #ifdef Plan9
  11287.     return p9sndbrk(msec);
  11288. #else
  11289. #ifdef NETCONN
  11290. #ifdef NETCMD
  11291.     if (ttpipe)                /* Pipe */
  11292.       return(ttoc('\0'));
  11293. #endif /* NETCMD */
  11294. #ifdef NETPTY
  11295.     if (ttpty)
  11296.       return(ttoc('\0'));
  11297. #endif /* NETPTY */
  11298.     if (netconn)             /* Send network BREAK */
  11299.       return(netbreak());
  11300. #endif /* NETCONN */
  11301.  
  11302.     if (msec < 1 || msec > 5000) return(-1); /* Bad argument */
  11303.  
  11304. #ifdef POSIX                /* Easy in POSIX */
  11305.     {
  11306.     int x;
  11307.     debug(F111,"sndbrk POSIX",ckitoa(msec),(msec/375));
  11308.     errno = 0;
  11309.     x = tcsendbreak(ttyfd,msec / 375);
  11310.     debug(F111,"sndbrk tcsendbreak",ckitoa(errno),x);
  11311.     return(x);
  11312.     }
  11313. #else
  11314. #ifdef PROVX1
  11315.     gtty(ttyfd,&ttbuf);                 /* Get current tty flags */
  11316.     spd = ttbuf.sg_ospeed;              /* Save speed */
  11317.     ttbuf.sg_ospeed = B50;              /* Change to 50 baud */
  11318.     stty(ttyfd,&ttbuf);                 /*  ... */
  11319.     n = (int)strlen(brnuls);        /* Send the right number of nulls */
  11320.     x = msec / 91;
  11321.     if (x > n) x = n;
  11322.     write(ttyfd,brnuls,n);
  11323.     ttbuf.sg_ospeed = spd;              /* Restore speed */
  11324.     stty(ttyfd,&ttbuf);                 /*  ... */
  11325.     return(0);
  11326. #else
  11327. #ifdef aegis
  11328.     sio_$control((short)ttyfd, sio_$send_break, msec, st);
  11329.     return(0);
  11330. #else
  11331. #ifdef BSDBREAK
  11332.     n = FWRITE;                         /* Flush output queue. */
  11333. /* Watch out for int vs long problems in &n arg! */
  11334.     debug(F101,"sndbrk BSDBREAK","",msec);
  11335.     ioctl(ttyfd,TIOCFLUSH,&n);          /* Ignore any errors.. */
  11336.     if (ioctl(ttyfd,TIOCSBRK,(char *)0) < 0) {  /* Turn on BREAK */
  11337.         perror("Can't send BREAK");
  11338.         return(-1);
  11339.     }
  11340.     x = msleep(msec);                    /* Sleep for so many milliseconds */
  11341.     if (ioctl(ttyfd,TIOCCBRK,(char *)0) < 0) {  /* Turn off BREAK */
  11342.         perror("BREAK stuck!!!");
  11343.         doexit(BAD_EXIT,-1);        /* Get out, closing the line. */
  11344.                                         /*   with bad exit status */
  11345.     }
  11346.     return(x);
  11347. #else
  11348. #ifdef ATTSV
  11349. /*
  11350.   No way to send a long BREAK in Sys V, so send a bunch of regular ones.
  11351.   (Actually, Sys V R4 is *supposed* to have the POSIX tcsendbreak() function,
  11352.   but there's no way for this code to know for sure.)
  11353. */
  11354.     debug(F101,"sndbrk ATTSV","",msec);
  11355.     x = msec / 275;
  11356.     for (n = 0; n < x; n++) {
  11357.     /* Reportedly the cast breaks this function on some systems */
  11358.     /* But then why was it here in the first place? */
  11359.     if (ioctl(ttyfd,TCSBRK, /* (char *) */ 0) < 0) {
  11360.         perror("Can't send BREAK");
  11361.         return(-1);
  11362.     }
  11363.     }
  11364.     return(0);
  11365. #else
  11366. #ifdef  V7
  11367.     debug(F101,"sndbrk V7","",msec);
  11368.     return(genbrk(ttyfd,250));        /* Simulate a BREAK */
  11369. #else
  11370.     debug(F101,"sndbrk catchall","",msec);
  11371.     ttoc(0);ttoc(0);ttoc(0);ttoc(0);
  11372.     return(0);
  11373. #endif /* V7 */
  11374. #endif /* BSDBREAK */
  11375. #endif /* ATTSV */
  11376. #endif /* aegis */
  11377. #endif /* PROVX1 */
  11378. #endif /* POSIX */
  11379. #endif /* Plan9 */
  11380. }
  11381.  
  11382. /*  T T S N D B  --  Send a BREAK signal  */
  11383.  
  11384. int
  11385. ttsndb() {
  11386. #ifdef TN_COMPORT
  11387.     if (netconn && istncomport())
  11388.       return((tnsndb(275L) >= 0) ? 0 : -1);
  11389.     else
  11390. #endif /* TN_COMPORT */
  11391.       return(sndbrk(275));
  11392. }
  11393.  
  11394. /*  T T S N D L B  --  Send a Long BREAK signal  */
  11395.  
  11396. int
  11397. ttsndlb() {
  11398. #ifdef TN_COMPORT
  11399.     if (netconn && istncomport())
  11400.       return((tnsndb(1800L) >= 0) ? 0 : -1);
  11401.     else
  11402. #endif /* TN_COMPORT */
  11403.     return(sndbrk(1500));
  11404. }
  11405.  
  11406. /*  M S L E E P  --  Millisecond version of sleep().  */
  11407.  
  11408. /*
  11409.   Call with number of milliseconds (thousandths of seconds) to sleep.
  11410.   Intended only for small intervals.  For big ones, just use sleep().
  11411.   Highly system-dependent.
  11412.   Returns 0 always, even if it didn't work.
  11413. */
  11414.  
  11415. /* Define MSLFTIME for systems that must use an ftime() loop. */
  11416. #ifdef ANYBSD                /* For pre-4.2 BSD versions */
  11417. #ifndef BSD4
  11418. #define MSLFTIME
  11419. #endif /* BSD4 */
  11420. #endif /* ANYBSD */
  11421.  
  11422. #ifdef TOWER1                /* NCR Tower OS 1.0 */
  11423. #define MSLFTIME
  11424. #endif /* TOWER1 */
  11425.  
  11426. #ifdef COHERENT         /* Coherent... */
  11427. #ifndef _I386           /* Maybe Coherent/386 should get this, too */
  11428. #define MSLFTIME        /* Opinions are divided */
  11429. #endif /* _I386 */
  11430. #endif /* COHERENT */
  11431.  
  11432. #ifdef COMMENT
  11433. #ifdef GETMSEC
  11434.  
  11435. /* Millisecond timer */
  11436.  
  11437. static long msecbase = 0L;        /* Unsigned long not portable */
  11438.  
  11439. long
  11440. getmsec() {                /* Milliseconds since base time */
  11441.     struct timeval xv;
  11442.     struct timezone xz;
  11443.     long secs, msecs;
  11444.     if (
  11445. #ifdef GTODONEARG
  11446.     gettimeofday(&tv)
  11447. #else
  11448. #ifdef PTX
  11449.     gettimeofday(&tv, NULL)
  11450. #else
  11451.     gettimeofday(&tv, &tz)
  11452. #endif /* PTX */
  11453. #endif /* GTODONEARG */
  11454.     < 0)
  11455.       return(-1);
  11456.     if (msecbase == 0L) {        /* First call, set base time. */
  11457.     msecbase = tv.tv_sec;
  11458.     debug(F101,"getmsec base","",msecbase);
  11459.     }
  11460.     return(((tv.tv_sec - msecbase) * 1000L) + (tv.tv_usec / 1000L));
  11461. }
  11462. #endif /* GETMSEC */
  11463. #endif /* COMMENT */
  11464.  
  11465. #ifdef SELECT
  11466. int
  11467. ttwait(fd, secs) int fd, secs; {
  11468.     int x;
  11469.     fd_set rfds;
  11470.     FD_ZERO(&rfds);
  11471.     FD_SET(fd,&rfds);
  11472.     tv.tv_sec = secs;
  11473.     tv.tv_usec = 0L;
  11474.     errno = 0;
  11475.     if ((x = select(FD_SETSIZE,
  11476. #ifdef HPUX9
  11477.             (int *)
  11478. #else
  11479. #ifdef HPUX1000
  11480.             (int *)
  11481. #endif /* HPUX1000 */
  11482. #endif /* HPUX9 */
  11483.             &rfds,
  11484.             0, 0, &tv)) < 0) {
  11485.     debug(F101,"ttwait select errno","",errno);
  11486.     return(0);
  11487.     } else {
  11488.     debug(F101,"ttwait OK","",errno);
  11489.     x = FD_ISSET(fd, &rfds);
  11490.     debug(F101,"ttwait select x","",x);
  11491.     return(x ? 1 : 0);
  11492.     }
  11493. }
  11494. #endif /* SELECT */
  11495.  
  11496. int
  11497. msleep(m) int m; {
  11498. /*
  11499.   Other possibilities here are:
  11500.    nanosleep(), reportedly defined in POSIX.4.
  11501.    sginap(), IRIX only (back to what IRIX version I don't know).
  11502. */
  11503. #ifdef Plan9
  11504.     return _SLEEP(m);
  11505. #else
  11506. #ifdef BEOSORBEBOX
  11507.     snooze(m*1000);
  11508. #else /* BEOSORBEBOX */
  11509. #ifdef SELECT
  11510.     int t1, x;
  11511.     debug(F101,"msleep SELECT 1","",m);
  11512.     if (m <= 0) return(0);
  11513.     if (m >= 1000) {            /* Catch big arguments. */
  11514.     sleep(m/1000);
  11515.     m = m % 1000;
  11516.     if (m < 10) return(0);
  11517.     }
  11518.     debug(F101,"msleep SELECT 2","",m);
  11519. #ifdef BELLV10
  11520.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, m );
  11521.     debug(F101,"msleep BELLV10 select","",x);
  11522. #else /* BELLV10 */
  11523. #ifdef HPUX9
  11524.     gettimeofday(&tv, &tz);
  11525. #else
  11526.  
  11527. #ifndef COHERENT
  11528. #ifdef GTODONEARG
  11529.     if (gettimeofday(&tv) < 0)
  11530. #else
  11531. #ifdef PTX
  11532.     if (gettimeofday(&tv,NULL) < 0)
  11533. #else
  11534. #ifdef NOTIMEZONE
  11535.     if (gettimeofday(&tv, NULL) < 0)    /* wonder what this does... */
  11536. #else
  11537.     if (gettimeofday(&tv, &tz) < 0)
  11538. #endif /* NOTIMEZONE */
  11539. #endif /* PTX */
  11540. #endif /* GTODONEARG */
  11541.       return(-1);
  11542.     t1 = tv.tv_sec;                     /* Seconds */
  11543. #endif /* COHERENT */
  11544. #endif /* HPUX9 */
  11545.     tv.tv_sec = 0;                      /* Use select() */
  11546.     tv.tv_usec = m * 1000L;
  11547. #ifdef BSD44
  11548.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11549.     debug(F101,"msleep BSD44 select","",x);
  11550. #else /* BSD44 */
  11551. #ifdef __linux__
  11552.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11553.     debug(F101,"msleep __linux__ select","",x);
  11554. #else /* __linux__ */
  11555. #ifdef BSD43
  11556.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11557.     debug(F101,"msleep BSD43 select","",x);
  11558. #else /* BSD43 */
  11559. #ifdef QNX6
  11560.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11561.     debug(F101,"msleep QNX6 select","",x);
  11562. #else /* QNX6 */
  11563. #ifdef QNX
  11564.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11565.     debug(F101,"msleep QNX select","",x);
  11566. #else /* QNX */
  11567. #ifdef COHERENT
  11568.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11569.     debug(F101,"msleep COHERENT select","",x);
  11570. #else /* COHERENT */
  11571. #ifdef HPUX1000                /* 10.00 only, not 10.10 or later */
  11572.     x = select( 0, (int *)0, (int *)0, (int *)0, &tv );
  11573.     debug(F101,"msleep HP-UX 10.00 select","",x);
  11574. #else /* HPUX1000 */
  11575. #ifdef SVR4
  11576.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11577.     debug(F101,"msleep SVR4 select","",x);
  11578. #else /* SVR4 */
  11579. #ifdef OSF40
  11580.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11581.     debug(F101,"msleep OSF40 select","",x);
  11582. #else /* OSF40 */
  11583. #ifdef PTX
  11584.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11585.     debug(F101,"msleep OSF40 select","",x);
  11586. #else
  11587.     x = select( 0, (int *)0, (int *)0, (int *)0, &tv );
  11588.     debug(F101,"msleep catch-all select","",x);
  11589. #endif /* PTX */
  11590. #endif /* OSF40 */
  11591. #endif /* HP1000 */
  11592. #endif /* SVR4 */
  11593. #endif /* COHERENT */
  11594. #endif /* QNX */
  11595. #endif /* QNX6 */
  11596. #endif /* BSD43 */
  11597. #endif /* __linux__ */
  11598. #endif /* BSD44 */
  11599. #endif /* BELLV10 */
  11600.     return(0);
  11601.  
  11602. #else                    /* Not SELECT */
  11603. #ifdef CK_POLL                /* We have poll() */
  11604.     struct pollfd pfd;            /* Supply a valid address for poll() */
  11605.  
  11606. #ifdef ODT30                /* But in SCO ODT 3.0 */
  11607. #ifdef NAP                /* we should use nap() instead */
  11608.     debug(F101,"msleep ODT 3.0 NAP","",m); /* because using poll() here */
  11609.     nap((long)m);               /* seems to break dialing. */
  11610.     return(0);
  11611. #else
  11612.     debug(F101,"msleep ODT 3.0 POLL","",m);
  11613.     poll(&pfd, 0, m);
  11614.     return(0);
  11615. #endif /* NAP */
  11616. #else
  11617.     debug(F101,"msleep POLL","",m);
  11618.     poll(&pfd, 0, m);
  11619.     return(0);
  11620. #endif /* ODT30 */
  11621.  
  11622. /*
  11623.   We could handle the above more cleanly by just letting nap() always
  11624.   take precedence over poll() in this routine, but there is no way to know
  11625.   whether that would break something else.
  11626. */
  11627.  
  11628. #else                    /* Not POLL */
  11629. #ifdef USLEEP
  11630. /*
  11631.   "This routine is implemented using setitimer(2); it requires eight
  11632.   system calls...".  In other words, it might take 5 minutes to sleep
  11633.   10 milliseconds...
  11634. */
  11635.     debug(F101,"msleep USLEEP","",m);
  11636.     if (m >= 1000) {            /* Catch big arguments. */
  11637.     sleep(m/1000);
  11638.     m = m % 1000;
  11639.     if (m < 10) return(0);
  11640.     }
  11641.     usleep((unsigned int)(m * 1000));
  11642.     return(0);
  11643. #else
  11644. #ifdef aegis
  11645.     time_$clock_t dur;
  11646.     debug(F101,"msleep aegis","",m);
  11647.     dur.c2.high16 = 0;
  11648.     dur.c2.low32  = 250 * m; /* one millisecond = 250 four microsecond ticks */
  11649.     time_$wait(time_$relative, dur, st);
  11650.     return(0);
  11651. #else
  11652. #ifdef PROVX1
  11653.     debug(F101,"msleep Venix","",m);
  11654.     if (m <= 0) return(0);
  11655.     sleep(-((m * 60 + 500) / 1000));
  11656.     return(0);
  11657. #else
  11658. #ifdef NAP
  11659.     debug(F101,"msleep NAP","",m);
  11660.     nap((long)m);
  11661.     return(0);
  11662. #else
  11663. #ifdef ATTSV
  11664. #ifndef BSD44
  11665.     extern long times();        /* Or #include <times.h> ? */
  11666. #endif /* BSD44 */
  11667.     long t1, t2, tarray[4];
  11668.     int t3;
  11669.     char *cp = getenv("HZ");
  11670.     int CLOCK_TICK;
  11671.     int hertz;
  11672.  
  11673.     if (cp && (hertz = atoi(cp))) {
  11674.         CLOCK_TICK  = 1000 / hertz;
  11675.     } else {                /* probably single user mode */
  11676. #ifdef HZ
  11677.         CLOCK_TICK  = 1000 / HZ;
  11678. #else
  11679.     static warned = 0;
  11680.     /* HZ always exists in, for instance, SCO Xenix, so you don't have to
  11681.      * make special #ifdefs for XENIX here, like in ver 4F. Also, if you
  11682.      * have Xenix, you have should have nap(), so the best is to use -DNAP
  11683.      * in the makefile. Most systems have HZ.
  11684.      */
  11685.     CLOCK_TICK = 17;        /* 1/60 sec */
  11686.     if (!warned) {
  11687.           printf("warning: environment variable HZ bad... using HZ=%d\r\n",
  11688.          1000 / CLOCK_TICK);
  11689.           warned = 1;
  11690.     }
  11691. #endif /* !HZ */
  11692.     }
  11693.     debug(F101,"msleep ATTSV","",m);
  11694.     if (m <= 0) return(0);
  11695.     if (m >= 1000) {            /* Catch big arguments. */
  11696.     sleep(m/1000);
  11697.     m = m % 1000;
  11698.     if (m < 10) return(0);
  11699.     }
  11700.     if ((t1 = times(tarray)) < 0) return(-1);
  11701.     while (1) {
  11702.         if ((t2 = times(tarray)) < 0) return(-1);
  11703.         t3 = ((int)(t2 - t1)) * CLOCK_TICK;
  11704.         if (t3 > m) return(t3);
  11705.     }
  11706. #else /* Not ATTSV */
  11707. #ifdef MSLFTIME                /* Use ftime() loop... */
  11708.     int t1, t3 = 0;
  11709.     debug(F101,"msleep MSLFTIME","",m);
  11710.     if (m <= 0) return(0);
  11711.     if (m >= 1000) {            /* Catch big arguments. */
  11712.     sleep(m/1000);
  11713.     m = m % 1000;
  11714.     if (m < 10) return(0);
  11715.     }
  11716. #ifdef QNX
  11717.     ftime(&ftp);            /* void ftime() in QNX */
  11718. #else
  11719.     if (ftime(&ftp) < 0) return(-1);    /* Get base time. */
  11720. #endif /* QNX */
  11721.     t1 = ((ftp.time & 0xff) * 1000) + ftp.millitm;
  11722.     while (1) {
  11723.         ftime(&ftp);            /* Get current time and compare. */
  11724.         t3 = (((ftp.time & 0xff) * 1000) + ftp.millitm) - t1;
  11725.         if (t3 > m) return(0);
  11726.     }
  11727. #else
  11728. /* This includes true POSIX, which has no way to do this. */
  11729.     debug(F101,"msleep busy loop","",m);
  11730.     if (m >= 1000) {            /* Catch big arguments. */
  11731.     sleep(m/1000);
  11732.     m = m % 1000;
  11733.     if (m < 10) return(0);
  11734.     }
  11735.     if (m > 0) while (m > 0) m--;    /* Just a dumb busy loop */
  11736.     return(0);
  11737. #endif /* MSLFTIME */
  11738. #endif /* ATTSV */
  11739. #endif /* NAP */
  11740. #endif /* PROVX1 */
  11741. #endif /* aegis */
  11742. #endif /* CK_POLL */
  11743. #endif /* SELECT */
  11744. #endif /* BEOSORBEBOX */
  11745. #endif /* USLEEP */
  11746. #endif /* Plan9 */
  11747. }
  11748.  
  11749. /*  R T I M E R --  Reset elapsed time counter  */
  11750.  
  11751. VOID
  11752. rtimer() {
  11753.     tcount = time( (time_t *) 0 );
  11754. }
  11755.  
  11756.  
  11757. /*  G T I M E R --  Get current value of elapsed time counter in seconds  */
  11758.  
  11759. int
  11760. gtimer() {
  11761.     int x;
  11762.     x = (int) (time( (time_t *) 0 ) - tcount);
  11763.     debug(F101,"gtimer","",x);
  11764.     return( (x < 0) ? 0 : x );
  11765. }
  11766.  
  11767. #ifdef GFTIMER
  11768. /*
  11769.   Floating-point timers.  Require not only floating point support, but
  11770.   also gettimeofday().
  11771. */
  11772. static struct timeval tzero;
  11773.  
  11774. VOID
  11775. rftimer() {
  11776. #ifdef GTODONEARG            /* Account for Mot's definition */
  11777.     (VOID) gettimeofday(&tzero);
  11778. #else
  11779.     (VOID) gettimeofday(&tzero, (struct timezone *)0);
  11780. #endif /* GTODONEARG */
  11781. }
  11782.  
  11783. CKFLOAT
  11784. gftimer() {
  11785.     struct timeval tnow, tdelta;
  11786.     CKFLOAT s;
  11787. #ifdef DEBUG
  11788.     char fpbuf[64];
  11789. #endif /* DEBUG */
  11790. #ifdef GTODONEARG            /* Account for Mot's definition */
  11791.     (VOID) gettimeofday(&tnow);
  11792. #else
  11793.     (VOID) gettimeofday(&tnow, (struct timezone *)0);
  11794. #endif /* GTODONEARG */
  11795.  
  11796.     tdelta.tv_sec = tnow.tv_sec - tzero.tv_sec;
  11797.     tdelta.tv_usec = tnow.tv_usec - tzero.tv_usec;
  11798.  
  11799.     if (tdelta.tv_usec < 0) {
  11800.     tdelta.tv_sec--;
  11801.     tdelta.tv_usec += 1000000;
  11802.     }
  11803.     s = (CKFLOAT) tdelta.tv_sec + ((CKFLOAT) tdelta.tv_usec / 1000000.0);
  11804.     if (s < GFMINTIME)
  11805.       s = GFMINTIME;
  11806. #ifdef DEBUG
  11807.     if (deblog) {
  11808.     sprintf(fpbuf,"%f",s);
  11809.     debug(F110,"gftimer",fpbuf,0);
  11810.     }
  11811. #endif /* DEBUG */
  11812.     return(s);
  11813. }
  11814. #endif /* GFTIMER */
  11815.  
  11816. /*  Z T I M E  --  Return asctime()-format date/time string  */
  11817. /*
  11818.   NOTE: as a side effect of calling this routine, we can also set the
  11819.   following two variables, giving the micro- and milliseconds (fractions of
  11820.   seconds) of the clock time.  Currently this is done only in BSD-based builds
  11821.   that use gettimeofday().  When these variables are not filled in, they are
  11822.   left with a value of -1L.
  11823. */
  11824. static char asctmbuf[64];
  11825.  
  11826. VOID
  11827. ztime(s) char **s; {
  11828.  
  11829. #ifdef GFTIMER
  11830. /*
  11831.   The gettimeofday() method, which also sets ztmsec and ztusec, works for
  11832.   all GFTIMER builds.  NOTE: ztmsec and ztusec are defined in ckcmai.c,
  11833.   and extern declarations for them are in ckcdeb.h; thus they are
  11834.   declared in this file by inclusion of ckcdeb.h.
  11835. */
  11836.     char *asctime();
  11837.     struct tm *localtime();
  11838.     struct tm *tp;
  11839.     ztmsec = -1L;
  11840.     ztusec = -1L;
  11841.  
  11842.     if (!s)
  11843.       debug(F100,"ztime s==NULL","",0);
  11844.  
  11845. #ifdef GTODONEARG
  11846.     /* No 2nd arg in Motorola SV88 and some others */
  11847.     if (gettimeofday(&tv) > -1)
  11848. #else
  11849. #ifndef COHERENT
  11850. #ifdef PTX
  11851.     if (gettimeofday(&tv,NULL) > -1)
  11852. #else
  11853. #ifdef NOTIMEZONE
  11854.     if (gettimeofday(&tv, NULL) > -1)    /* wonder what this does... */
  11855. #else
  11856.     if (gettimeofday(&tv, &tz) > -1)
  11857. #endif /* NOTIMEZONE */
  11858. #endif /* PTX */
  11859. #endif /* COHERENT */
  11860. #endif /* GTODONEARG */
  11861.       {                    /* Fill in tm struct */
  11862.     ztusec = tv.tv_usec;        /* Microseconds */
  11863.     ztmsec = ztusec / 1000L;    /* Milliseconds */
  11864. #ifdef HPUX9
  11865.     {
  11866.         time_t zz;
  11867.         zz = tv.tv_sec;
  11868.         tp = localtime(&zz);    /* Convert to local time */
  11869.     }
  11870. #else
  11871. #ifdef HPUX1000
  11872.     {
  11873.         time_t zz;
  11874.         zz = tv.tv_sec;
  11875.         tp = localtime(&zz);
  11876.     }
  11877. #else
  11878. #ifdef LINUX
  11879.     {   /* avoid unaligned access trap on 64-bit platforms */
  11880.         time_t zz;
  11881.         zz = tv.tv_sec;
  11882.         tp = localtime(&zz);
  11883.     }
  11884. #else
  11885. #ifdef MACOSX
  11886.     tp = localtime((time_t *)&tv.tv_sec); /* Convert to local time */
  11887. #else
  11888.     tp = localtime(&tv.tv_sec);
  11889. #endif /* MACOSX */
  11890. #endif /* LINUX */
  11891. #endif /* HPUX1000 */
  11892. #endif /* HPUX9 */
  11893.     if (s) {
  11894.         char * s2;
  11895.         s2 = asctime(tp);        /* Convert result to ASCII string */
  11896.         asctmbuf[0] = '\0';
  11897.         if (s2) ckstrncpy(asctmbuf,s2,64);
  11898.         *s = asctmbuf;
  11899.         debug(F111,"ztime GFTIMER gettimeofday",*s,ztusec);
  11900.     }
  11901.     }
  11902. #else  /* Not GFTIMER */
  11903.  
  11904. #undef ZTIMEV7                /* Which systems need to use */
  11905. #ifdef COHERENT                /* old UNIX Version 7 way... */
  11906. #define ZTIMEV7
  11907. #endif /* COHERENT */
  11908. #ifdef TOWER1
  11909. #define ZTIMEV7
  11910. #endif /* TOWER1 */
  11911. #ifdef ANYBSD
  11912. #ifndef BSD42
  11913. #define ZTIMEV7
  11914. #endif /* BSD42 */
  11915. #endif /* ANYBSD */
  11916. #ifdef V7
  11917. #ifndef MINIX
  11918. #define ZTIMEV7
  11919. #endif /* MINIX */
  11920. #endif /* V7 */
  11921. #ifdef POSIX
  11922. #define ZTIMEV7
  11923. #endif /* POSIX */
  11924.  
  11925. #ifdef HPUX1020
  11926. /*
  11927.   Prototypes are in <time.h>, included above.
  11928. */
  11929.     time_t clock_storage;
  11930.     clock_storage = time((void *) 0);
  11931.     if (s) {
  11932.     *s = ctime(&clock_storage);
  11933.     debug(F110,"ztime: HPUX 10.20",*s,0);
  11934.     }
  11935. #else
  11936. #ifdef ATTSV                /* AT&T way */
  11937. /*  extern long time(); */        /* Theoretically these should */
  11938.     char *ctime();            /* already been dcl'd in <time.h> */
  11939.     time_t clock_storage;
  11940.     clock_storage = time(
  11941. #ifdef IRIX60
  11942.              (time_t *)
  11943. #else
  11944. #ifdef BSD44
  11945.              (time_t *)
  11946. #else
  11947.              (long *)
  11948. #endif /* BSD44 */
  11949. #endif /* IRIX60 */
  11950.              0 );
  11951.     if (s) {
  11952.     *s = ctime( &clock_storage );
  11953.     debug(F110,"ztime: ATTSV",*s,0);
  11954.     }
  11955. #else
  11956. #ifdef PROVX1                /* Venix 1.0 way */
  11957.     int utime[2];
  11958.     time(utime);
  11959.     if (s) {
  11960.     *s = ctime(utime);
  11961.     debug(F110,"ztime: PROVX1",*s,0);
  11962.     }
  11963. #else
  11964. #ifdef BSD42                /* 4.2BSD way */
  11965.     char *asctime();
  11966.     struct tm *localtime();
  11967.     struct tm *tp;
  11968.     gettimeofday(&tv, &tz);
  11969.     ztusec = tv.tv_usec;
  11970.     ztmsec = tv.tv_usec / 1000L;
  11971.     tp = localtime(&tv.tv_sec);
  11972.     if (s) {
  11973.     *s = asctime(tp);
  11974.     debug(F111,"ztime: BSD42",*s,ztusec);
  11975.     }
  11976. #else
  11977. #ifdef MINIX                /* MINIX way */
  11978. #ifdef COMMENT
  11979.     extern long time();            /* Already got these from <time.h> */
  11980.     extern char *ctime();
  11981. #endif /* COMMENT */
  11982.     time_t utime[2];
  11983.     time(utime);
  11984.     if (s) {
  11985.     *s = ctime(utime);
  11986.     debug(F110,"ztime: MINIX",*s,0);
  11987.     }
  11988. #else
  11989. #ifdef ZTIMEV7                /* The regular way */
  11990.     char *asctime();
  11991.     struct tm *localtime();
  11992.     struct tm *tp;
  11993.     long xclock;            /* or unsigned long for BeBox? */
  11994.     time(&xclock);
  11995.     tp = localtime(&xclock);
  11996.     if (s) {
  11997.     *s = asctime(tp);
  11998.     debug(F110,"ztime: ZTIMEV7",*s,0);
  11999.     }
  12000. #else                    /* Catch-all for others... */
  12001.     if (s) {
  12002.     *s = "Day Mon 00 00:00:00 0000\n"; /* Dummy in asctime() format */
  12003.     debug(F110,"ztime: catch-all",*s,0);
  12004.     }
  12005. #endif /* ZTIMEV7 */
  12006. #endif /* MINIX */
  12007. #endif /* BSD42 */
  12008. #endif /* PROVX1 */
  12009. #endif /* ATTSV */
  12010. #endif /* HPUX1020 */
  12011. #endif /* GFTIMER */
  12012. }
  12013.  
  12014. /*  C O N G M  --  Get console terminal modes.  */
  12015.  
  12016. /*
  12017.   Saves initial console mode, and establishes variables for switching
  12018.   between current (presumably normal) mode and other modes.
  12019.   Should be called when program starts, but only after establishing
  12020.   whether program is in the foreground or background.
  12021.   Returns 1 if it got the modes OK, 0 if it did nothing, -1 on error.
  12022. */
  12023. int
  12024. congm() {
  12025.     int fd;
  12026.     if (backgrd || !isatty(0)) {    /* If in background. */
  12027.     cgmf = -1;            /* Don't bother, modes are garbage. */
  12028.     return(-1);
  12029.     }
  12030.     if (cgmf > 0) return(0);        /* Already did this. */
  12031.     debug(F100,"congm getting modes","",0); /* Need to do it. */
  12032. #ifdef aegis
  12033.     ios_$inq_type_uid(ios_$stdin, conuid, st);
  12034.     if (st.all != status_$ok) {
  12035.     fprintf(stderr, "problem getting stdin objtype: ");
  12036.     error_$print(st);
  12037.     }
  12038.     concrp = (conuid == mbx_$uid);
  12039.     conbufn = 0;
  12040. #endif /* aegis */
  12041.  
  12042. #ifndef BEBOX
  12043.     if ((fd = open(CTTNAM,2)) < 0) {    /* Open controlling terminal */
  12044. #ifdef COMMENT
  12045.     fprintf(stderr,"Error opening %s\n", CTTNAM);
  12046.     perror("congm");
  12047.     return(-1);
  12048. #else
  12049.     fd = 0;
  12050. #endif /* COMMENT */
  12051.     }
  12052. #else
  12053.     fd = 0;
  12054. #endif /* !BEBOX */
  12055. #ifdef BSD44ORPOSIX
  12056.     if (tcgetattr(fd,&ccold) < 0) return(-1);
  12057.     if (tcgetattr(fd,&cccbrk) < 0) return(-1);
  12058.     if (tcgetattr(fd,&ccraw) < 0) return(-1);
  12059. #else
  12060. #ifdef ATTSV
  12061.     if (ioctl(fd,TCGETA,&ccold)  < 0) return(-1);
  12062.     if (ioctl(fd,TCGETA,&cccbrk) < 0) return(-1);
  12063.     if (ioctl(fd,TCGETA,&ccraw)  < 0) return(-1);
  12064. #ifdef VXVE
  12065.     cccbrk.c_line = 0;            /* STTY line 0 for CDC VX/VE */
  12066.     if (ioctl(fd,TCSETA,&cccbrk) < 0) return(-1);
  12067.     ccraw.c_line = 0;            /* STTY line 0 for CDC VX/VE */
  12068.     if (ioctl(fd,TCSETA,&ccraw) < 0) return(-1);
  12069. #endif /* VXVE */
  12070. #else
  12071. #ifdef BELLV10
  12072.     if (ioctl(fd,TIOCGETP,&ccold) < 0) return(-1);
  12073.     if (ioctl(fd,TIOCGETP,&cccbrk) < 0) return(-1);
  12074.     if (ioctl(fd,TIOCGETP,&ccraw) < 0) return(-1);
  12075.     debug(F101,"cccbrk.sg_flags orig","", cccbrk.sg_flags);
  12076. #else
  12077.     if (gtty(fd,&ccold) < 0) return(-1);
  12078.     if (gtty(fd,&cccbrk) < 0) return(-1);
  12079.     if (gtty(fd,&ccraw) < 0) return(-1);
  12080. #endif /* BELLV10 */
  12081. #endif /* ATTSV */
  12082. #endif /* BSD44ORPOSIX */
  12083. #ifdef sony_news            /* Sony NEWS */
  12084.     if (ioctl(fd,TIOCKGET,&km_con) < 0) { /* Get console Kanji mode */
  12085.     perror("congm error getting Kanji mode");
  12086.     debug(F101,"congm error getting Kanji mode","",0);
  12087.     km_con = -1;            /* Make sure this stays undefined. */
  12088.     return(-1);
  12089.     }
  12090. #endif /* sony_news */
  12091.     if (fd > 0)
  12092.       close(fd);
  12093.     cgmf = 1;                /* Flag that we got them. */
  12094.     return(1);
  12095. }
  12096.  
  12097.  
  12098. static VOID
  12099. congetbuf(x) int x; {
  12100.     int n;
  12101.     n = CONBUFSIZ - (conbufp - conbuf);    /* How much room left in buffer? */
  12102.     if (x > n) {
  12103.     debug(F101,"congetbuf char loss","",x-n);
  12104.     x = n;
  12105.     }
  12106.     x = read(0,conbufp,x);
  12107.     conbufn += x;
  12108.     debug(F111,"congetbuf readahead",conbuf,x);
  12109. }
  12110.  
  12111.  
  12112. /*  C O N C B --  Put console in cbreak mode.  */
  12113.  
  12114. /*  Returns 0 if ok, -1 if not  */
  12115.  
  12116. int
  12117. #ifdef CK_ANSIC
  12118. concb(char esc)
  12119. #else
  12120. concb(esc) char esc;
  12121. #endif /* CK_ANSIC */
  12122. /* concb */ {
  12123.     int x, y = 0;
  12124.     debug(F101,"concb constate","",constate);
  12125.     debug(F101,"concb cgmf","",cgmf);
  12126.     debug(F101,"concb backgrd","",backgrd);
  12127.  
  12128.     if (constate == CON_CB)
  12129.       return(0);
  12130.  
  12131.     if (cgmf < 1)            /* Did we get console modes yet? */
  12132.       if (!backgrd)            /* No, in background? */
  12133.     congm();            /* No, try to get them now. */
  12134.     if (cgmf < 1)            /* Still don't have them? */
  12135.       return(0);            /* Give up. */
  12136.     debug(F101,"concb ttyfd","",ttyfd);
  12137.     debug(F101,"concb ttfdflg","",ttfdflg);
  12138. #ifdef COMMENT
  12139.     /* This breaks returning to prompt after protocol with "-l 0" */
  12140.     /* Commented out July 1998 */
  12141.     if (ttfdflg && ttyfd >= 0 && ttyfd < 3)
  12142.       return(0);
  12143. #endif /* COMMENT */
  12144.     x = isatty(0);
  12145.     debug(F101,"concb isatty","",x);
  12146.     if (!x) return(0);            /* Only when running on real ttys */
  12147.     debug(F101,"concb xsuspend","",xsuspend);
  12148.     if (backgrd)            /* Do nothing if in background. */
  12149.       return(0);
  12150.     escchr = esc;                       /* Make this available to other fns */
  12151.     ckxech = 1;                         /* Program can echo characters */
  12152. #ifdef aegis
  12153.     conbufn = 0;
  12154.     if (concrp) return(write(1, "\035\002", 2));
  12155.     if (conuid == input_pad_$uid) {pad_$raw(ios_$stdin, st); return(0);}
  12156. #endif /* aegis */
  12157.  
  12158. #ifdef COHERENT
  12159. #define SVORPOSIX
  12160. #endif /* COHERENT */
  12161.  
  12162. #ifdef Plan9
  12163.     x = p9concb();
  12164. #else
  12165. #ifndef SVORPOSIX            /* BSD, V7, etc */
  12166.     debug(F101,"cccbrk.sg_flags concb 1","", cccbrk.sg_flags);
  12167.     debug(F101,"concb stty CBREAK","",0);
  12168.     cccbrk.sg_flags |= (CBREAK|CRMOD);    /* Set to character wakeup, */
  12169.     cccbrk.sg_flags &= ~ECHO;           /* no echo. */
  12170.     debug(F101,"cccbrk.sg_flags concb 2","", cccbrk.sg_flags);
  12171.     errno = 0;
  12172. /*
  12173.   BSD stty() clears the console buffer.  So if anything is waiting in it,
  12174.   we have to read it now to avoid losing it.
  12175. */
  12176.     x = conchk();
  12177.     if (x > 0)
  12178.       congetbuf(x);
  12179.  
  12180. #ifdef BELLV10
  12181.     x = ioctl(0,TIOCSETP,&cccbrk);
  12182. #else
  12183.     x = stty(0,&cccbrk);
  12184.     debug(F101,"cccbrk.sg_flags concb x","", x);
  12185. #endif /* BELLV10 */
  12186. #else                    /* Sys V and POSIX */
  12187. #ifndef OXOS
  12188.     debug(F101,"concb cccbrk.c_flag","",cccbrk.c_lflag);
  12189. #ifdef QNX
  12190.     /* Don't mess with IEXTEN */
  12191.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  12192. #else
  12193. #ifdef COHERENT
  12194.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  12195. #else
  12196.     cccbrk.c_lflag &= ~(ICANON|ECHO|IEXTEN);
  12197. #endif /* COHERENT */
  12198. #endif /* QNX */
  12199.     cccbrk.c_lflag |= ISIG;        /* Allow signals in command mode. */
  12200.     cccbrk.c_iflag |= IGNBRK;        /* But ignore BREAK signal */
  12201.     cccbrk.c_iflag &= ~BRKINT;
  12202.  
  12203. #else /* OXOS */
  12204.     debug(F100,"concb OXOS is defined","",0);
  12205.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  12206.     cccbrk.c_cc[VDISCARD] = cccbrk.c_cc[VLNEXT] = CDISABLE;
  12207. #endif /* OXOS */
  12208. #ifdef COMMENT
  12209. /*
  12210.   Believe it or not, in SCO UNIX, VSUSP is greater than NCC, and so this
  12211.   array reference is out of bounds.  It's only a debug() call so who needs it.
  12212. */
  12213. #ifdef VSUSP
  12214.     debug(F101,"concb c_cc[VSUSP]","",cccbrk.c_cc[VSUSP]);
  12215. #endif /* VSUSP */
  12216. #endif /* COMMENT */
  12217. #ifndef VINTR
  12218.     debug(F101,"concb c_cc[0]","",cccbrk.c_cc[0]);
  12219.     cccbrk.c_cc[0] = 003;               /* Interrupt char is Control-C */
  12220. #else
  12221.     debug(F101,"concb c_cc[VINTR]","",cccbrk.c_cc[0]);
  12222.     cccbrk.c_cc[VINTR] = 003;
  12223. #endif /* VINTR */
  12224. #ifndef VQUIT
  12225.     cccbrk.c_cc[1] = escchr;            /* escape during packet modes */
  12226. #else
  12227.     cccbrk.c_cc[VQUIT] = escchr;
  12228. #endif /* VQUIT */
  12229. #ifndef VEOF
  12230.     cccbrk.c_cc[4] = 1;
  12231. #else
  12232. #ifndef OXOS
  12233. #ifdef VMIN
  12234.     cccbrk.c_cc[VMIN] = 1;
  12235. #endif /* VMIN */
  12236. #else /* OXOS */
  12237.     cccbrk.c_min = 1;
  12238. #endif /* OXOS */
  12239. #endif /* VEOF */
  12240. #ifdef ZILOG
  12241.     cccbrk.c_cc[5] = 0;
  12242. #else
  12243. #ifndef VEOL
  12244.     cccbrk.c_cc[5] = 1;
  12245. #else
  12246. #ifndef OXOS
  12247. #ifdef VTIME
  12248.     cccbrk.c_cc[VTIME] = 1;
  12249. #endif /* VTIME */
  12250. #else /* OXOS */
  12251.     cccbrk.c_time = 1;
  12252. #endif /* OXOS */
  12253. #endif /* VEOL */
  12254. #endif /* ZILOG */
  12255.     errno = 0;
  12256. #ifdef BSD44ORPOSIX            /* Set new modes */
  12257.     x = tcsetattr(0,TCSADRAIN,&cccbrk);
  12258. #else /* ATTSV */                  /* or the POSIX way */
  12259.     x = ioctl(0,TCSETAW,&cccbrk);    /* the Sys V way */
  12260. #endif /* BSD44ORPOSIX */
  12261. #endif /* SVORPOSIX */
  12262.  
  12263. #ifdef COHERENT
  12264. #undef SVORPOSIX
  12265. #endif /* COHERENT */
  12266.  
  12267.     debug(F101,"concb x","",x);
  12268.     debug(F101,"concb errno","",errno);
  12269.  
  12270. #ifdef  V7
  12271. #ifndef MINIX
  12272.     if (kmem[CON] < 0) {
  12273.         qaddr[CON] = initrawq(0);
  12274.         if((kmem[CON] = open("/dev/kmem", 0)) < 0) {
  12275.             fprintf(stderr, "Can't read /dev/kmem in concb.\n");
  12276.             perror("/dev/kmem");
  12277.             exit(1);
  12278.         }
  12279.     }
  12280. #endif /* MINIX */
  12281. #endif /* V7 */
  12282. #endif /* Plan9 */
  12283.  
  12284.     if (x > -1)
  12285.       constate = CON_CB;
  12286.  
  12287.     debug(F101,"concb returns","",x);
  12288.     return(x);
  12289. }
  12290.  
  12291. /*  C O N B I N  --  Put console in binary mode  */
  12292.  
  12293. /*  Returns 0 if ok, -1 if not  */
  12294.  
  12295. int
  12296. #ifdef CK_ANSIC
  12297. conbin(char esc)
  12298. #else
  12299. conbin(esc) char esc;
  12300. #endif /* CK_ANSIC */
  12301. /* conbin */  {
  12302.  
  12303.     int x;
  12304.  
  12305.     debug(F101,"conbin constate","",constate);
  12306.  
  12307.     if (constate == CON_BIN)
  12308.       return(0);
  12309.  
  12310.     if (!isatty(0)) return(0);          /* only for real ttys */
  12311.     congm();                /* Get modes if necessary. */
  12312.     debug(F100,"conbin","",0);
  12313.     escchr = esc;                       /* Make this available to other fns */
  12314.     ckxech = 1;                         /* Program can echo characters */
  12315. #ifdef aegis
  12316.     conbufn = 0;
  12317.     if (concrp) return(write(1, "\035\002", 2));
  12318.     if (conuid == input_pad_$uid) {
  12319.     pad_$raw(ios_$stdin, st);
  12320.     return(0);
  12321.       }
  12322. #endif /* aegis */
  12323.  
  12324. #ifdef COHERENT
  12325. #define SVORPOSIX
  12326. #endif /* COHERENT */
  12327.  
  12328. #ifdef Plan9
  12329.     return p9conbin();
  12330. #else
  12331. #ifdef SVORPOSIX
  12332. #ifndef OXOS
  12333. #ifdef QNX
  12334.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  12335. #else
  12336. #ifdef COHERENT
  12337.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  12338. #else
  12339.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO|IEXTEN);
  12340. #endif /* COHERENT */
  12341. #endif /* QNX */
  12342. #else /* OXOS */
  12343.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  12344.     ccraw.c_cc[VDISCARD] = ccraw.c_cc[VLNEXT] = CDISABLE;
  12345. #endif /* OXOS */
  12346.     ccraw.c_iflag |= IGNPAR;
  12347. /*
  12348.   Note that for terminal sessions we disable Xon/Xoff flow control to allow
  12349.   the passage ^Q and ^S as data characters for EMACS, and to allow XMODEM
  12350.   transfers to work when C-Kermit is in the middle, etc.  Hardware flow
  12351.   control, if in use, is not affected.
  12352. */
  12353. #ifdef ATTSV
  12354. #ifdef BSD44
  12355.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IXON|IXANY|IXOFF
  12356.                         |INPCK|ISTRIP);
  12357. #else
  12358.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IUCLC|IXON|IXANY|IXOFF
  12359.                         |INPCK|ISTRIP);
  12360. #endif /* BSD44 */
  12361. #else /* POSIX */
  12362.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IXON|IXOFF|INPCK|ISTRIP);
  12363. #endif /* ATTSV */
  12364.     ccraw.c_oflag &= ~OPOST;
  12365. #ifdef COMMENT
  12366. /*
  12367.   WHAT THE HECK WAS THIS FOR?
  12368.   The B9600 setting (obviously) prevents CONNECT from working at any
  12369.   speed other than 9600 when you are logged in to the 7300 on a serial
  12370.   line.  Maybe some of the other flags are necessary -- if so, put back
  12371.   the ones that are needed.  This code is supposed to work the same, no
  12372.   matter whether you are logged in to the 7300 on the real console device,
  12373.   or through a serial port.
  12374. */
  12375. #ifdef ATT7300
  12376.     ccraw.c_cflag = CLOCAL | B9600 | CS8 | CREAD | HUPCL;
  12377. #endif /* ATT7300 */
  12378. #endif /* COMMENT */
  12379.  
  12380. /*** Kermit used to put the console in 8-bit raw mode, but some users have
  12381.  *** pointed out that this should not be done, since some sites actually
  12382.  *** use terminals with parity settings on their Unix systems, and if we
  12383.  *** override the current settings and stop doing parity, then their terminals
  12384.  *** will display blotches for characters whose parity is wrong.  Therefore,
  12385.  *** the following two lines are commented out (Larry Afrin, Clemson U):
  12386.  ***
  12387.  ***   ccraw.c_cflag &= ~(PARENB|CSIZE);
  12388.  ***   ccraw.c_cflag |= (CS8|CREAD);
  12389.  ***
  12390.  *** Sys III/V sites that have trouble with this can restore these lines.
  12391.  ***/
  12392. #ifndef VINTR
  12393.     ccraw.c_cc[0] = 003;        /* Interrupt char is Ctrl-C */
  12394. #else
  12395.     ccraw.c_cc[VINTR] = 003;
  12396. #endif /* VINTR */
  12397. #ifndef VQUIT
  12398.     ccraw.c_cc[1] = escchr;        /* Escape during packet mode */
  12399. #else
  12400.     ccraw.c_cc[VQUIT] = escchr;
  12401. #endif /* VQUIT */
  12402. #ifndef VEOF
  12403.     ccraw.c_cc[4] = 1;
  12404. #else
  12405. #ifndef OXOS
  12406. #ifdef VMIN
  12407.     ccraw.c_cc[VMIN] = 1;
  12408. #endif /* VMIN */
  12409. #else /* OXOS */
  12410.     ccraw.c_min = 1;
  12411. #endif /* OXOS */
  12412. #endif /* VEOF */
  12413.  
  12414. #ifdef ZILOG
  12415.     ccraw.c_cc[5] = 0;
  12416. #else
  12417. #ifndef VEOL
  12418.     ccraw.c_cc[5] = 1;
  12419. #else
  12420. #ifndef OXOS
  12421. #ifdef VTIME
  12422.     ccraw.c_cc[VTIME] = 1;
  12423. #endif /* VTIME */
  12424. #else /* OXOS */
  12425.     ccraw.c_time = 1;
  12426. #endif /* OXOS */
  12427. #endif /* VEOL */
  12428. #endif /* ZILOG */
  12429.  
  12430. #ifdef BSD44ORPOSIX
  12431.     x = tcsetattr(0,TCSADRAIN,&ccraw);    /* Set new modes. */
  12432. #else
  12433.     x = ioctl(0,TCSETAW,&ccraw);
  12434. #endif /* BSD44ORPOSIX */
  12435. #else /* Berkeley, etc. */
  12436.     x = conchk();            /* Because stty() is destructive */
  12437.     if (x > 0)
  12438.       congetbuf(x);
  12439.     ccraw.sg_flags |= (RAW|TANDEM);     /* Set rawmode, XON/XOFF (ha) */
  12440.     ccraw.sg_flags &= ~(ECHO|CRMOD);    /* Set char wakeup, no echo */
  12441. #ifdef BELLV10
  12442.     x = ioctl(0,TIOCSETP,&ccraw);
  12443. #else
  12444.     x = stty(0,&ccraw);
  12445. #endif /* BELLV10 */
  12446. #endif /* SVORPOSIX */
  12447. #endif /* Plan9 */
  12448.  
  12449.     if (x > -1)
  12450.       constate = CON_BIN;
  12451.  
  12452.     debug(F101,"conbin returns","",x);
  12453.     return(x);
  12454.  
  12455. #ifdef COHERENT
  12456. #undef SVORPOSIX
  12457. #endif /* COHERENT */
  12458.  
  12459. }
  12460.  
  12461.  
  12462. /*  C O N R E S  --  Restore the console terminal  */
  12463.  
  12464. int
  12465. conres() {
  12466.     int x;
  12467.     debug(F101,"conres cgmf","",cgmf);
  12468.     debug(F101,"conres constate","",constate);
  12469.  
  12470.     if (cgmf < 1)            /* Do nothing if modes unchanged */
  12471.       return(0);
  12472.     if (constate == CON_RES)
  12473.       return(0);
  12474.  
  12475.     if (!isatty(0)) return(0);          /* only for real ttys */
  12476.     debug(F100,"conres isatty ok","",0);
  12477.     ckxech = 0;                         /* System should echo chars */
  12478.  
  12479. #ifdef aegis
  12480.     conbufn = 0;
  12481.     if (concrp) return(write(1, "\035\001", 2));
  12482.     if (conuid == input_pad_$uid) {
  12483.     pad_$cooked(ios_$stdin, st);
  12484.     constate = CON_RES;
  12485.     return(0);
  12486.     }
  12487. #endif /* aegis */
  12488.  
  12489. #ifdef Plan9
  12490.     p9conres();
  12491. #else
  12492. #ifdef BSD44ORPOSIX
  12493.     debug(F100,"conres restoring tcsetattr","",0);
  12494.     x = tcsetattr(0,TCSADRAIN,&ccold);
  12495. #else
  12496. #ifdef ATTSV
  12497.     debug(F100,"conres restoring ioctl","",0);
  12498.     x = ioctl(0,TCSETAW,&ccold);
  12499. #else /* BSD, V7, and friends */
  12500. #ifdef sony_news            /* Sony NEWS */
  12501.     if (km_con != -1)
  12502.       ioctl(0,TIOCKSET,&km_con);    /* Restore console Kanji mode */
  12503. #endif /* sony_news */
  12504.     msleep(100);
  12505.     debug(F100,"conres restoring stty","",0);
  12506.     x = conchk();            /* Because stty() is destructive */
  12507.     if (x > 0)
  12508.       congetbuf(x);
  12509. #ifdef BELLV10
  12510.     x = ioctl(0,TIOCSETP,&ccold);
  12511. #else
  12512.     x = stty(0,&ccold);
  12513. #endif /* BELLV10 */
  12514. #endif /* ATTSV */
  12515. #endif /* BSD44ORPOSIX */
  12516. #endif /* Plan9 */
  12517.     if (x > -1)
  12518.       constate = CON_RES;
  12519.  
  12520.     debug(F101,"conres returns","",x);
  12521.     return(x);
  12522. }
  12523.  
  12524. /*  C O N O C  --  Output a character to the console terminal  */
  12525.  
  12526. int
  12527. #ifdef CK_ANSIC
  12528. conoc(char c)
  12529. #else
  12530. conoc(c) char c;
  12531. #endif /* CK_ANSIC */
  12532. /* conoc */ {
  12533.  
  12534. #ifdef IKSD
  12535.     if (inserver && !local)
  12536.       return(ttoc(c));
  12537.  
  12538. #ifdef CK_ENCRYPTION
  12539.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  12540.         ck_tn_encrypt(&c,1);
  12541. #endif /* CK_ENCRYPTION */
  12542. #endif /* IKSD */
  12543.  
  12544. #ifdef Plan9
  12545.     return conwrite(&c,1);
  12546. #else
  12547.     return(write(1,&c,1));
  12548. #endif /* Plan9 */
  12549. }
  12550.  
  12551. /*  C O N X O  --  Write x characters to the console terminal  */
  12552.  
  12553. int
  12554. conxo(x,s) int x; char *s; {
  12555.  
  12556. #ifdef IKSD
  12557.     if (inserver && !local)
  12558.       return(ttol((CHAR *)s,x));
  12559.  
  12560. #ifdef CK_ENCRYPTION
  12561.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  12562.         ck_tn_encrypt(s,x);
  12563. #endif /* CK_ENCRYPTION */
  12564. #endif /* IKSD */
  12565.  
  12566. #ifdef Plan9
  12567.     return(conwrite(s,x));
  12568. #else
  12569.     return(write(1,s,x));
  12570. #endif /* Plan9 */
  12571. }
  12572.  
  12573. /*  C O N O L  --  Write a line to the console terminal  */
  12574.  
  12575. int
  12576. conol(s) char *s; {
  12577.     int len;
  12578.     if (!s) s = "";            /* Always do this! */
  12579.     len = strlen(s);
  12580.     if (len == 0)
  12581.       return(0);
  12582.  
  12583. #ifdef IKSD
  12584.     if (inserver && !local)
  12585.       return(ttol((CHAR *)s,len));
  12586.  
  12587. #ifdef CK_ENCRYPTION
  12588.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION)) {
  12589.     if (nxpacket < len) {
  12590.         if (xpacket) {
  12591.         free(xpacket);
  12592.         xpacket = NULL;
  12593.         nxpacket = 0;
  12594.         }
  12595.         len = len > 10240 ? len : 10240;
  12596.         xpacket = (CHAR *)malloc(len);
  12597.         if (!xpacket) {
  12598.         fprintf(stderr,"ttol malloc failure\n");
  12599.         return(-1);
  12600.         } else
  12601.           nxpacket = len;
  12602.     }
  12603.     memcpy(xpacket,s,len);
  12604.     s = (char *)xpacket;
  12605.     ck_tn_encrypt(s,len);
  12606.     }
  12607. #endif /* CK_ENCRYPTION */
  12608. #endif /* IKSD */
  12609.  
  12610. #ifdef Plan9
  12611.     return(conwrite(s,len));
  12612. #else
  12613.     return(write(1,s,len));
  12614. #endif /* Plan9 */
  12615. }
  12616.  
  12617. /*  C O N O L A  --  Write an array of lines to the console terminal */
  12618.  
  12619. int
  12620. conola(s) char *s[]; {
  12621.     char * p;
  12622.     int i, x;
  12623.  
  12624.  
  12625.     if (!s) return(0);
  12626.     for (i = 0; ; i++) {
  12627.     p = s[i];
  12628.     if (!p) p = "";            /* Let's not dump core shall we? */
  12629.     if (!*p)
  12630.       break;
  12631. #ifdef IKSD
  12632.     if (inserver && !local)
  12633.       x = ttol((CHAR *)p,(int)strlen(p));
  12634.     else
  12635. #endif /* IKSD */
  12636.       x = conol(p);
  12637.     if (x < 0)
  12638.       return(-1);
  12639.     }
  12640.     return(0);
  12641. }
  12642.  
  12643. /*  C O N O L L  --  Output a string followed by CRLF  */
  12644.  
  12645. int
  12646. conoll(s) char *s; {
  12647.     CHAR buf[3];
  12648.     buf[0] = '\r';
  12649.     buf[1] = '\n';
  12650.     buf[2] = '\0';
  12651.     if (!s) s = "";
  12652.  
  12653. #ifdef IKSD
  12654.     if (inserver && !local) {
  12655.     if (*s) ttol((CHAR *)s,(int)strlen(s));
  12656.     return(ttol(buf,2));
  12657.     }
  12658. #endif /* IKSD */
  12659.  
  12660.     if (*s) conol(s);
  12661. #ifdef IKSD
  12662. #ifdef CK_ENCRYPTION
  12663.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  12664.       ck_tn_encrypt((char *)buf,2);
  12665. #endif /* CK_ENCRYPTION */
  12666. #endif /* IKSD */
  12667.  
  12668. #ifdef Plan9
  12669.     return(conwrite(buf, 2));
  12670. #else
  12671.     return(write(1,buf,2));
  12672. #endif /* Plan9 */
  12673. }
  12674.  
  12675. /*  C O N C H K  --  Return how many characters available at console  */
  12676. /*
  12677.   We could also use select() here to cover a few more systems that are not
  12678.   covered by any of the following, e.g. HP-UX 9.0x on the model 800.
  12679. */
  12680. int
  12681. conchk() {
  12682.     static int contyp = 0;        /* +1 for isatty, -1 otherwise */
  12683.  
  12684.     if (contyp == 0)            /* This prevents unnecessary */
  12685.       contyp = (isatty(0) ? 1 : -1);    /* duplicated calls to isatty() */
  12686.     debug(F101,"conchk contyp","",contyp);
  12687.     if (backgrd || (contyp < 0))
  12688.       return(0);
  12689.  
  12690. #ifdef aegis
  12691.     if (conbufn > 0) return(conbufn);   /* use old count if nonzero */
  12692.  
  12693.     /* read in more characters */
  12694.     conbufn = ios_$get(ios_$stdin,
  12695.               ios_$cond_opt, conbuf, (long)sizeof(conbuf), st);
  12696.     if (st.all != status_$ok) conbufn = 0;
  12697.     conbufp = conbuf;
  12698.     return(conbufn);
  12699. #else
  12700. #ifdef IKSD
  12701.     if (inserver && !local)
  12702.       return(in_chk(1,ttyfd));
  12703.     else
  12704. #endif /* IKSD */
  12705.       return(in_chk(0,0));
  12706. #endif /* aegis */
  12707. }
  12708.  
  12709. /*  C O N I N C  --  Get a character from the console  */
  12710. /*
  12711.   Call with timo > 0 to do a timed read, timo == 0 to do an untimed blocking
  12712.   read.  Upon success, returns the character.  Upon failure, returns -1.
  12713.   A timed read that does not complete within the timeout period returns -2.
  12714. */
  12715. int
  12716. coninc(timo) int timo; {
  12717.     int n = 0; CHAR ch;
  12718.     int xx;
  12719.  
  12720.     if (conbufn > 0) {            /* If something already buffered */
  12721.     --conbufn;
  12722.     return((unsigned)(*conbufp++ & 0xff));
  12723.     }
  12724.  
  12725.     errno = 0;                /* Clear this */
  12726. #ifdef IKSD
  12727.     if (inserver && !local) {
  12728.     xx = ttinc(timo);
  12729.     if (xx < 0)
  12730.       return(ttinctimo ? -2 : -1);
  12731.     else
  12732.       return(xx);
  12733.     }
  12734. #endif /* IKSD */
  12735.  
  12736. #ifdef aegis                /* Apollo Aegis only... */
  12737.     debug(F101,"coninc timo","",timo);
  12738.     fflush(stdout);
  12739.     if (conchk() > 0) {
  12740.     --conbufn;
  12741.     return((unsigned)(*conbufp++ & 0xff));
  12742.     }
  12743. #endif /* aegis */
  12744.  
  12745. #ifdef TTLEBUF
  12746.     if (
  12747. #ifdef IKSD
  12748.     inserver &&
  12749. #endif /* IKSD */
  12750.     !xlocal
  12751.     ) {
  12752.     if (ttpush >= 0) {
  12753.         debug(F111,"ttinc","ttpush",ttpush);
  12754.         ch = ttpush;
  12755.         ttpush = -1;
  12756.         return(ch);
  12757.     }
  12758.     if (le_data) {
  12759.         if (le_getchar(&ch) > 0) {
  12760.         debug(F111,"ttinc LocalEchoInBuf","ch",ch);
  12761.         return(ch);
  12762.         }
  12763.     }
  12764.     }
  12765. #endif /* TTLEBUF */
  12766.  
  12767.     if (timo <= 0) {            /* Untimed, blocking read. */
  12768.     while (1) {            /* Keep trying till we get one. */
  12769.         n = read(0, &ch, 1);    /* Read a character. */
  12770.         if (n == 0) continue;    /* Shouldn't happen. */
  12771.         if (n > 0) {        /* If read was successful, */
  12772. #ifdef IKSD
  12773. #ifdef CK_ENCRYPTION
  12774.                 debug(F100,"coninc decrypt 1","",0);
  12775.                 if (inserver && !local && TELOPT_U(TELOPT_ENCRYPTION))
  12776.           ck_tn_decrypt((char *)&ch,1);
  12777. #endif /* CK_ENCRYPTION */
  12778. #endif /* IKSD */
  12779.         return((unsigned)(ch & 0xff)); /* return the character. */
  12780.             }
  12781.  
  12782. /* Come here if read() returned an error. */
  12783.  
  12784.         debug(F101, "coninc(0) errno","",errno); /* Log the error. */
  12785. #ifndef OXOS
  12786. #ifdef SVORPOSIX
  12787. #ifdef CIE                             /* CIE Regulus has no EINTR symbol? */
  12788. #ifndef EINTR
  12789. #define EINTR 4
  12790. #endif /* EINTR */
  12791. #endif /* CIE */
  12792. /*
  12793.   This routine is used for several different purposes.  In CONNECT mode, it is
  12794.   used to do an untimed, blocking read from the keyboard in the lower CONNECT
  12795.   fork.  During local-mode file transfer, it reads a character from the
  12796.   console to interrupt the file transfer (like A for a status report, X to
  12797.   cancel a file, etc).  Obviously, we don't want the reads in the latter case
  12798.   to be blocking, or the file transfer would stop until the user typed
  12799.   something.  Unfortunately, System V does not allow the console device input
  12800.   buffer to be sampled nondestructively (e.g. by conchk()), so a kludge is
  12801.   used instead.  During local-mode file transfer, the SIGQUIT signal is armed
  12802.   and trapped by esctrp(), and this routine pretends to have read the quit
  12803.   character from the keyboard normally.  But, kludge or no kludge, the read()
  12804.   issued by this command, under System V only, can fail if a signal -- ANY
  12805.   signal -- is caught while the read is pending.  This can occur not only when
  12806.   the user types the quit character, but also during telnet negotiations, when
  12807.   the lower CONNECT fork signals the upper one about an echoing mode change.
  12808.   When this happens, we have to post the read() again.  This is apparently not
  12809.   a problem in BSD-based UNIX versions.
  12810. */
  12811.         if (errno == EINTR)        /* Read interrupted. */
  12812.           if (conesc)  {        /* If by SIGQUIT, */
  12813.           conesc = 0;        /* the conesc variable is set, */
  12814.           return(escchr);    /* so return the escape character. */
  12815.          } else continue;        /* By other signal, try again. */
  12816. #else
  12817. /*
  12818.   This might be dangerous, but let's do this on non-System V versions too,
  12819.   since at least one SunOS 4.1.2 user complains of immediate disconnections
  12820.   upon first making a TELNET connection.
  12821. */
  12822.         if (errno == EINTR)        /* Read interrupted. */
  12823.           continue;
  12824. #endif /* SVORPOSIX */
  12825. #else /* OXOS */
  12826.         if (errno == EINTR)        /* Read interrupted. */
  12827.           continue;
  12828. #endif /* OXOS */
  12829.         return(-1);            /* Error */
  12830.     }
  12831.     }
  12832. #ifdef DEBUG
  12833.     if (deblog && timo <= 0) {
  12834.     debug(F100,"coninc timeout logic error","",0);
  12835.     timo = 1;
  12836.     }
  12837. #endif /* DEBUG */
  12838.  
  12839. /* Timed read... */
  12840.  
  12841.     saval = signal(SIGALRM,timerh);    /* Set up timeout handler. */
  12842.     xx = alarm(timo);            /* Set the alarm. */
  12843.     debug(F101,"coninc alarm set","",timo);
  12844.     if (
  12845. #ifdef CK_POSIX_SIG
  12846.     sigsetjmp(sjbuf,1)
  12847. #else
  12848.     setjmp(sjbuf)
  12849. #endif /* CK_POSIX_SIG */
  12850.     )                /* The read() timed out. */
  12851.       n = -2;                /* Code for timeout. */
  12852.     else
  12853.       n = read(0, &ch, 1);
  12854.     ttimoff();                /* Turn off timer */
  12855.     if (n > 0) {            /* Got character OK. */
  12856. #ifdef IKSD
  12857. #ifdef CK_ENCRYPTION
  12858.         debug(F100,"coninc decrypt 2","",0);
  12859.         if (inserver && !local && TELOPT_U(TELOPT_ENCRYPTION))
  12860.       ck_tn_decrypt((char *)&ch,1);
  12861. #endif /* CK_ENCRYPTION */
  12862. #endif /* IKSD */
  12863.     return((unsigned)(ch & 0xff));    /* Return it. */
  12864.     }
  12865. /*
  12866.   read() returned an error.  Same deal as above, but without the loop.
  12867. */
  12868.     debug(F101, "coninc(timo) n","",n);
  12869.     debug(F101, "coninc(timo) errno","",errno);
  12870. #ifndef OXOS
  12871. #ifdef SVORPOSIX
  12872.     if (n == -1 && errno == EINTR && conesc != 0) {
  12873.     conesc = 0;
  12874.     return(escchr);            /* User entered escape character. */
  12875.     }
  12876. #endif /* SVORPOSIX */
  12877.     if (n == 0 && errno > 0) {        /* It's an error */
  12878.     return(-1);
  12879.     }
  12880. #endif /* ! OXOS */
  12881.     return(n);
  12882. }
  12883.  
  12884. /*  C O N G K S  --  Console Get Keyboard Scancode  */
  12885.  
  12886. #ifndef congks
  12887. /*
  12888.   This function needs to be filled in with the various system-dependent
  12889.   system calls used by SUNOS, NeXT OS, Xenix, Aviion, etc, to read a full
  12890.   keyboard scan code.  Unfortunately there aren't any.
  12891. */
  12892. int
  12893. congks(timo) int timo; {
  12894.  
  12895. #ifdef IKSD
  12896.     if (inserver && !local)
  12897.       return(ttinc(timo));
  12898. #endif /* IKSD */
  12899.  
  12900.     return(coninc(timo));
  12901. }
  12902. #endif /* congks */
  12903.  
  12904. #ifdef ATT7300
  12905.  
  12906. /*  A T T D I A L  --  Dial up the remote system using internal modem
  12907.  * Purpose: to open and dial a number on the internal modem available on the
  12908.  * ATT7300 UNIX PC.  Written by Joe Doupnik. Superceeds version written by
  12909.  * Richard E. Hill, Dickinson, TX. which employed dial(3c).
  12910.  * Uses information in <sys/phone.h> and our status int attmodem.
  12911.  */
  12912. attdial(ttname,speed,telnbr) char *ttname,*telnbr; long speed; {
  12913.     char *telnum;
  12914.  
  12915.     attmodem &= ~ISMODEM;                       /* modem not in use yet */
  12916.                     /* Ensure O_NDELAY is set, else i/o traffic hangs */
  12917.                     /* We turn this flag off once the dial is complete */
  12918.     fcntl(ttyfd, F_SETFL, fcntl(ttyfd, F_GETFL, 0) | O_NDELAY);
  12919.  
  12920.     /* Condition line, check availability & DATA mode, turn on speaker */
  12921.     if (ioctl(ttyfd,PIOCOFFHOOK, &dialer) == -1) {
  12922.         printf("cannot access phone\n");
  12923.         ttclos(0);
  12924.         return (-2);
  12925.     }
  12926.     ioctl(ttyfd,PIOCGETP,&dialer);      /* get phone dialer parameters */
  12927.  
  12928.     if (dialer.c_lineparam & VOICE) {    /* phone must be in DATA mode */
  12929.         printf(" Should not dial with modem in VOICE mode.\n");
  12930.         printf(" Exit Kermit, switch to DATA and retry call.\n");
  12931.         ttclos(0);
  12932.         return (-2);
  12933.     }
  12934. #ifdef ATTTONED                /* Old way, tone dialing only. */
  12935.     dialer.c_lineparam = DATA | DTMF;    /* Dial with tones, */
  12936.     dialer.c_lineparam &= ~PULSE;    /* not with pulses. */
  12937. #else
  12938.     /* Leave current pulse/tone state alone. */
  12939.     /* But what about DATA?  Add it back if you have trouble. */
  12940.     /* sys/phone says you get DATA automatically by opening device RDWR */
  12941. #endif
  12942.     dialer.c_waitdialtone = 5;                  /* wait 5 sec for dialtone */
  12943. #ifdef COMMENT
  12944.     dialer.c_feedback = SPEAKERON|NORMSPK|RINGON;  /* control speaker */
  12945. #else
  12946.     /* sys/phone says RINGON used only for incoming voice calls */
  12947.     dialer.c_feedback &= ~(SOFTSPK|LOUDSPK);
  12948.     dialer.c_feedback |= SPEAKERON|NORMSPK;
  12949. #endif
  12950.     dialer.c_waitflash = 500;                   /* 0.5 sec flash hook */
  12951.     if(ioctl(ttyfd,PIOCSETP,&dialer) == -1) {   /* set phone parameters */
  12952.         printf("Cannot set modem characteristics\n");
  12953.         ttclos(0);
  12954.         return (-2);
  12955.     }
  12956.     ioctl(ttyfd,PIOCRECONN,0);        /* Turns on speaker for pulse */
  12957.  
  12958. #ifdef COMMENT
  12959.     fprintf(stderr,"Phone line status. line_par:%o dialtone_wait:%o \
  12960. line_status:%o feedback:%o\n",
  12961.     dialer.c_lineparam, dialer.c_waitdialtone,
  12962.     dialer.c_linestatus, dialer.c_feedback);
  12963. #endif
  12964.  
  12965.     attmodem |= ISMODEM;                        /* modem is now in-use */
  12966.     sleep(1);
  12967.     for (telnum = telnbr; *telnum != '\0'; telnum++)    /* dial number */
  12968. #ifdef ATTTONED
  12969.       /* Tone dialing only */
  12970.       if (ioctl(ttyfd,PIOCDIAL,telnum) != 0) {
  12971.       perror("Error in dialing");
  12972.       ttclos(0);
  12973.       return(-2);
  12974.       }
  12975. #else /* Allow Pulse or Tone dialing */
  12976.     switch (*telnum) {
  12977.       case 't': case 'T': case '%':    /* Tone dialing requested */
  12978.     dialer.c_lineparam |= DTMF;
  12979.     dialer.c_lineparam &= ~PULSE;
  12980.     if (ioctl(ttyfd,PIOCSETP,&dialer) == -1) {
  12981.         printf("Cannot set modem to tone dialing\n");
  12982.         ttclos(0);
  12983.         return(-2);
  12984.     }
  12985.     break;
  12986.       case 'd': case 'D': case 'p': case 'P': case '^':
  12987.     dialer.c_lineparam |= PULSE;
  12988.     dialer.c_lineparam &= ~DTMF;
  12989.     if (ioctl(ttyfd,PIOCSETP,&dialer) == -1) {
  12990.         printf("Cannot set modem to pulse dialing\n");
  12991.         ttclos(0);
  12992.         return(-2);
  12993.     }
  12994.     break;
  12995.       default:
  12996.         if (ioctl(ttyfd,PIOCDIAL,telnum) != 0) {
  12997.         perror("Dialing error");
  12998.         ttclos(0);
  12999.         return(-2);
  13000.     }
  13001.     break;
  13002.     }
  13003. #endif
  13004.  
  13005.     ioctl(ttyfd,PIOCDIAL,"@");        /* terminator for data call */
  13006.     do {                /* wait for modems to Connect */
  13007.         if (ioctl(ttyfd,PIOCGETP,&dialer) != 0)    { /* get params */
  13008.         perror("Cannot get modems to connect");
  13009.         ttclos(0);
  13010.         return(-2);
  13011.     }
  13012.     } while ((dialer.c_linestatus & MODEMCONNECTED) == 0);
  13013.     /* Turn off O_NDELAY flag now. */
  13014.     fcntl(ttyfd, F_SETFL, fcntl(ttyfd, F_GETFL, 0) & ~O_NDELAY);
  13015.     signal(SIGHUP, sighup);             /* hangup on loss of carrier */
  13016.     return(0);                          /* return success */
  13017. }
  13018.  
  13019. /*
  13020.   Offgetty, ongetty functions. These function get the 'getty(1m)' off
  13021.   and restore it to the indicated line.  Shell's return codes are:
  13022.     0: Can't do it.  Probably a user logged on.
  13023.     1: No need.  No getty on that line.
  13024.     2: Done, you should restore the getty when you're done.
  13025.   DOGETY System(3), however, returns them as 0, 256, 512, respectively.
  13026.   Thanks to Kevin O'Gorman, Anarm Software Systems.
  13027.  
  13028.    getoff.sh looks like:   geton.sh looks like:
  13029.      setgetty $1 0           setgetty $1 1
  13030.      err=$?                  exit $?
  13031.      sleep 2
  13032.      exit $err
  13033. */
  13034.  
  13035. /*  O F F G E T T Y  --  Turn off getty(1m) for the communications tty line
  13036.  * and get status so it can be restarted after the line is hung up.
  13037.  */
  13038. int
  13039. offgetty(ttname) char *ttname; {
  13040.     char temp[30];
  13041.     while (*ttname != '\0') ttname++;       /* seek terminator of path */
  13042.     ttname -= 3;                            /* get last 3 chars of name */
  13043.     sprintf(temp,"/usr/bin/getoff.sh %s",ttname);
  13044.     return(zsyscmd(temp));
  13045. }
  13046.  
  13047. /*  O N G E T T Y  --  Turn on getty(1m) for the communications tty line */
  13048.  
  13049. int
  13050. ongetty(ttname) char *ttname; {
  13051.     char temp[30];
  13052.     while (*ttname != '\0') ttname++;       /* comms tty path name */
  13053.     ttname -= 3;
  13054.     sprintf(temp,"/usr/bin/geton.sh %s",ttname);
  13055.     return(zsyscmd(temp));
  13056. }
  13057. #endif /* ATT7300 */
  13058.  
  13059. /*  T T S C A R R  --  Set ttcarr variable, controlling carrier handling.
  13060.  *
  13061.  *  0 = Off: Always ignore carrier. E.g. you can connect without carrier.
  13062.  *  1 = On: Heed carrier, except during dialing. Carrier loss gives disconnect.
  13063.  *  2 = Auto: For "modem direct": The same as "Off".
  13064.  *            For real modem types: Heed carrier during connect, but ignore
  13065.  *                it anytime else.  Compatible with pre-5A C-Kermit versions.
  13066.  *
  13067.  * As you can see, this setting does not affect dialing, which always ignores
  13068.  * carrier (unless there is some special exception for some modem type).  It
  13069.  * does affect ttopen() if it is set before ttopen() is used.  This setting
  13070.  * takes effect on the next call to ttopen()/ttpkt()/ttvt().  And they are
  13071.  * (or should be) always called before any communications is tried, which
  13072.  * means that, practically speaking, the effect is immediate.
  13073.  *
  13074.  * Of course, nothing of this applies to remote mode (xlocal = 0).
  13075.  *
  13076.  * Someone has yet to uncover how to manipulate the carrier in the BSD
  13077.  * environment (or any non-termio using environment).  Until that time, this
  13078.  * will simply be a no-op for BSD.
  13079.  *
  13080.  * Note that in previous versions, the carrier was most often left unchanged
  13081.  * in ttpkt()/ttvt() unless they were called with FLO_DIAL or FLO_DIAX.  This
  13082.  * has changed.  Now it is controlled by ttcarr in conjunction with these
  13083.  * modes.
  13084.  */
  13085. int
  13086. ttscarr(carrier) int carrier; {
  13087.     ttcarr = carrier;
  13088.     debug(F101, "ttscarr","",ttcarr);
  13089.     return(ttcarr);
  13090. }
  13091.  
  13092. /* C A R R C T L  --  Set tty modes for carrier treatment.
  13093.  *
  13094.  * Sets the appropriate bits in a termio or sgttyb struct for carrier control
  13095.  * (actually, there are no bits in sgttyb for that), or performs any other
  13096.  * operations needed to control this on the current system.  The function does
  13097.  * not do the actual TCSETA or stty, since often we want to set other bits too
  13098.  * first.  Don't call this function when xlocal is 0, or the tty is not opened.
  13099.  *
  13100.  * We don't know how to do anything like carrier control on non-ATTSV systems,
  13101.  * except, apparently, ultrix.  See above.  It is also known that this doesn't
  13102.  * have much effect on a Xenix system.  For Xenix, one should switch back and
  13103.  * forth between the upper and lower case device files.  Maybe later.
  13104.  * Presently, Xenix will stick to the mode it was opened with.
  13105.  *
  13106.  * carrier: 0 = ignore carrier, 1 = require carrier.
  13107.  * The current state is saved in curcarr, and checked to save labour.
  13108.  */
  13109. #ifdef SVORPOSIX
  13110. int
  13111. #ifdef BSD44ORPOSIX
  13112. carrctl(ttpar, carrier)    struct termios *ttpar; int carrier;
  13113. #else /* ATTSV */
  13114. carrctl(ttpar, carrier)    struct termio *ttpar; int carrier;
  13115. #endif /* BSD44ORPOSIX */
  13116. /* carrctl */ {
  13117.     debug(F101, "carrctl","",carrier);
  13118.     if (carrier)
  13119.       ttpar->c_cflag &= ~CLOCAL;
  13120.     else
  13121.       ttpar->c_cflag |= CLOCAL;
  13122.     return(0);
  13123. }
  13124. #else /* Berkeley, V7, et al... */
  13125. int
  13126. carrctl(ttpar, carrier) struct sgttyb *ttpar; int carrier; {
  13127.     debug(F101, "carrctl","",carrier);
  13128.     if (carrier == curcarr)
  13129.       return(0);
  13130.     curcarr = carrier;
  13131. #ifdef ultrix
  13132. #ifdef COMMENT
  13133. /*
  13134.   Old code from somebody at DEC that tends to get stuck, time out, etc.
  13135. */
  13136.     if (carrier) {
  13137.     ioctl(ttyfd, TIOCMODEM, &temp);
  13138.     ioctl(ttyfd, TIOCHPCL, 0);
  13139.     } else {
  13140.     /* (According to the manuals, TIOCNCAR should be preferred */
  13141.     /* over TIOCNMODEM...) */
  13142.     ioctl(ttyfd, TIOCNMODEM, &temp);
  13143.     }
  13144. #else
  13145. /*
  13146.   New code from Jamie Watson that, he says, eliminates the problems.
  13147. */
  13148.     if (carrier) {
  13149.     ioctl(ttyfd, TIOCCAR);
  13150.     ioctl(ttyfd, TIOCHPCL);
  13151.     } else {
  13152.     ioctl(ttyfd, TIOCNCAR);
  13153.     }
  13154. #endif /* COMMENT */
  13155. #endif /* ultrix */
  13156.     return(0);
  13157. }
  13158. #endif /* SVORPOSIX */
  13159.  
  13160.  
  13161. /*  T T G M D M  --  Get modem signals  */
  13162. /*
  13163.  Looks for RS-232 modem signals, and returns those that are on in as its
  13164.  return value, in a bit mask composed of the BM_xxx values defined in ckcdeb.h.
  13165.  Returns:
  13166.  -3 Not implemented
  13167.  -2 if the communication device does not have modem control (e.g. telnet)
  13168.  -1 on error.
  13169.  >= 0 on success, with a bit mask containing the modem signals that are on.
  13170. */
  13171.  
  13172. /*
  13173.   Define the symbol K_MDMCTL if we have Sys V R3 / 4.3 BSD style
  13174.   modem control, namely the TIOCMGET ioctl.
  13175. */
  13176.  
  13177. #ifdef BSD43
  13178. #define K_MDMCTL
  13179. #endif /* BSD43 */
  13180.  
  13181. #ifdef SUNOS4
  13182. #define K_MDMCTL
  13183. #endif /* SUNOS4 */
  13184.  
  13185. /*
  13186.   SCO OpenServer R5.0.4.  The TIOCMGET definition is hardwired in because it
  13187.   is skipped in termio.h when _POSIX_SOURCE is defined.  But _POSIX_SOURCE
  13188.   must be defined in order to get the high serial speeds that are new to
  13189.   5.0.4.  However, the regular SCO drivers do not implement TIOCMGET, so the
  13190.   ioctl() returns -1 with errno 22 (invalid function).  But third-party
  13191.   drivers, e.g. for Digiboard, do implement it, and so it should work on ports
  13192.   driven by those drivers.
  13193. */
  13194. #ifdef SCO_OSR504
  13195. #ifndef TIOCMGET
  13196. #define TIOCMGET (('t'<<8)|29)
  13197. #endif /* TIOCMGET */
  13198. #endif /* SCO_OSR504 */
  13199.  
  13200. #ifdef CK_SCOV5
  13201. /* Because POSIX strictness in <sys/termio.h> won't let us see these. */
  13202. #ifndef TIOCM_DTR
  13203. #define TIOCM_DTR    0x0002        /* data terminal ready */
  13204. #define TIOCM_RTS    0x0004        /* request to send */
  13205. #define TIOCM_CTS    0x0020        /* clear to send */
  13206. #define TIOCM_CAR    0x0040        /* carrier detect */
  13207. #define TIOCM_RNG    0x0080        /* ring */
  13208. #define TIOCM_DSR    0x0100        /* data set ready */
  13209. #define TIOCM_CD    TIOCM_CAR
  13210. #define TIOCM_RI    TIOCM_RNG
  13211. #endif /* TIOCM_DTR */
  13212. #endif /* CK_SCOV5 */
  13213.  
  13214. #ifdef QNX
  13215. #define K_MDMCTL
  13216. #else
  13217. #ifdef TIOCMGET
  13218. #define K_MDMCTL
  13219. #endif /* TIOCMGET */
  13220. #endif /* QNX */
  13221. /*
  13222.   "A serial communication program that can't read modem signals
  13223.    is like a car without windows."
  13224. */
  13225. int
  13226. ttgmdm() {
  13227.  
  13228. #ifdef QNX
  13229. #include <sys/qioctl.h>
  13230.  
  13231.     unsigned long y, mdmbits[2];
  13232.     int x, z = 0;
  13233.  
  13234.     if (xlocal && ttyfd < 0)
  13235.       return(-1);
  13236.  
  13237. #ifdef NETCONN
  13238.     if (netconn) {            /* Network connection */
  13239. #ifdef TN_COMPORT
  13240.         if (istncomport()) {
  13241.         gotsigs = 1;
  13242.         return(tngmdm());
  13243.     } else
  13244. #endif /* TN_COMPORT */
  13245.       return(-2);            /* No modem signals */
  13246.     }
  13247. #endif /* NETCONN */
  13248.  
  13249. #ifdef NETCMD
  13250.     if (ttpipe) return(-2);
  13251. #endif /* NETCMD */
  13252. #ifdef NETPTY
  13253.     if (ttpty) return(-2);
  13254. #endif /* NETPTY */
  13255.  
  13256.     mdmbits[0] = 0L;
  13257.     mdmbits[1] = 0L;
  13258. /*
  13259.  * From <sys/qioctl.h>:
  13260.  *
  13261.  * SERIAL devices   (all Dev.ser versions)
  13262.  * 0 : DTR           8 = Data Bits 0  16 - reserved     24 - reserved
  13263.  * 1 : RTS           9 = Data Bits 1  17 - reserved     25 - reserved
  13264.  * 2 = Out 1        10 = Stop Bits    18 - reserved     26 - reserved
  13265.  * 3 = Int Enable   11 = Par Enable   19 - reserved     27 - reserved
  13266.  * 4 = Loop         12 = Par Even     20 = CTS          28 - reserved
  13267.  * 5 - reserved     13 = Par Stick    21 = DSR          29 - reserved
  13268.  * 6 - reserved     14 : Break        22 = RI           30 - reserved
  13269.  * 7 - reserved     15 = 0            23 = CD           31 - reserved
  13270.  */
  13271.     errno = 0;
  13272.     x = qnx_ioctl(ttyfd, QCTL_DEV_CTL, &mdmbits[0], 8, &mdmbits[0], 4);
  13273.     debug(F101,"ttgmdm qnx_ioctl","",x);
  13274.     debug(F101,"ttgmdm qnx_ioctl errno","",errno);
  13275.     if (!x) {
  13276.     debug(F101,"ttgmdm qnx_ioctl mdmbits[0]","",mdmbits[0]);
  13277.     debug(F101,"ttgmdm qnx_ioctl mdmbits[1]","",mdmbits[1]);
  13278.     y = mdmbits[0];
  13279.     if (y & 0x000001L) z |= BM_DTR;    /* Bit  0 */
  13280.     if (y & 0x000002L) z |= BM_RTS;    /* Bit  1 */
  13281.     if (y & 0x100000L) z |= BM_CTS;    /* Bit 20 */
  13282.     if (y & 0x200000L) z |= BM_DSR;    /* Bit 21 */
  13283.     if (y & 0x400000L) z |= BM_RNG;    /* Bit 22 */
  13284.     if (y & 0x800000L) z |= BM_DCD;    /* Bit 23 */
  13285.     debug(F101,"ttgmdm qnx result","",z);
  13286.     debug(F110,"ttgmdm qnx CD = ",(z & BM_DCD) ? "On" : "Off", 0);
  13287.     gotsigs = 1;
  13288.     return(z);
  13289.     } else return(-1);
  13290. #else /* QNX */
  13291. #ifdef HPUX                /* HPUX has its own way */
  13292.     int x, z;
  13293.  
  13294. #ifdef HPUX10                /* Modem flag word */
  13295.     mflag y;                /* mflag typedef'd in <sys/modem.h> */
  13296. #else
  13297. #ifdef HPUX9
  13298.     mflag y;
  13299. #else
  13300. #ifdef HPUX8
  13301.     mflag y;
  13302. #else
  13303.     unsigned long y;            /* Not sure about pre-8.0... */
  13304. #endif /* HPUX8 */
  13305. #endif /* HPUX9 */
  13306. #endif /* HPUX10 */
  13307.  
  13308.     if (xlocal && ttyfd < 0)
  13309.       return(-1);
  13310.  
  13311. #ifdef NETCONN
  13312.     if (netconn) {            /* Network connection */
  13313. #ifdef TN_COMPORT
  13314.         if (istncomport()) {
  13315.         gotsigs = 1;
  13316.         return(tngmdm());
  13317.     } else
  13318. #endif /* TN_COMPORT */
  13319.       return(-2);            /* No modem signals */
  13320.     }
  13321. #endif /* NETCONN */
  13322.  
  13323. #ifdef NETCMD
  13324.     if (ttpipe) return(-2);
  13325. #endif /* NETCMD */
  13326. #ifdef NETPTY
  13327.     if (ttpty) return(-2);
  13328. #endif /* NETPTY */
  13329.  
  13330.     if (xlocal)                /* Get modem signals */
  13331.       x = ioctl(ttyfd,MCGETA,&y);
  13332.     else
  13333.       x = ioctl(0,MCGETA,&y);
  13334.     if (x < 0) return(-1);
  13335.     debug(F101,"ttgmdm","",y);
  13336.  
  13337.     z = 0;                /* Initialize return value */
  13338.  
  13339. /* Now set bits for each modem signal that is reported to be on. */
  13340.  
  13341. #ifdef MCTS
  13342.     /* Clear To Send */
  13343.     debug(F101,"ttgmdm HPUX CTS","",y & MCTS);
  13344.     if (y & MCTS) z |= BM_CTS;
  13345. #endif
  13346. #ifdef MDSR
  13347.     /* Data Set Ready */
  13348.     debug(F101,"ttgmdm HPUX DSR","",y & MDSR);
  13349.     if (y & MDSR) z |= BM_DSR;
  13350. #endif
  13351. #ifdef MDCD
  13352.     /* Carrier */
  13353.     debug(F101,"ttgmdm HPUX DCD","",y & MDCD);
  13354.     if (y & MDCD) z |= BM_DCD;
  13355. #endif
  13356. #ifdef MRI
  13357.     /* Ring Indicate */
  13358.     debug(F101,"ttgmdm HPUX RI","",y & MRI);
  13359.     if (y & MRI) z |= BM_RNG;
  13360. #endif
  13361. #ifdef MDTR
  13362.     /* Data Terminal Ready */
  13363.     debug(F101,"ttgmdm HPUX DTR","",y & MDTR);
  13364.     if (y & MDTR) z |= BM_DTR;
  13365. #endif
  13366. #ifdef MRTS
  13367.     /* Request To Send */
  13368.     debug(F101,"ttgmdm HPUX RTS","",y & MRTS);
  13369.     if (y & MRTS) z |= BM_RTS;
  13370. #endif
  13371.     gotsigs = 1;
  13372.     return(z);
  13373.  
  13374. #else /* ! HPUX */
  13375.  
  13376. #ifdef K_MDMCTL
  13377. /*
  13378.   Note, TIOCMGET might already have been defined in <sys/ioctl.h> or elsewhere.
  13379.   If not, we try including <sys/ttycom.h> -- if this blows up then more ifdefs
  13380.   are needed.
  13381. */
  13382. #ifndef TIOCMGET
  13383. #include <sys/ttycom.h>
  13384. #endif /* TIOCMGET */
  13385.  
  13386.     int x, y, z;
  13387.  
  13388.     debug(F100,"ttgmdm K_MDMCTL defined","",0);
  13389.  
  13390. #ifdef NETCONN
  13391.     if (netconn) {            /* Network connection */
  13392. #ifdef TN_COMPORT
  13393.         if (istncomport()) {
  13394.         gotsigs = 1;
  13395.         return(tngmdm());
  13396.     } else
  13397. #endif /* TN_COMPORT */
  13398.       return(-2);            /* No modem signals */
  13399.     }
  13400. #endif /* NETCONN */
  13401.  
  13402. #ifdef NETCMD
  13403.     if (ttpipe) return(-2);
  13404. #endif /* NETCMD */
  13405. #ifdef NETPTY
  13406.     if (ttpty) return(-2);
  13407. #endif /* NETPTY */
  13408.  
  13409.     if (xlocal && ttyfd < 0)
  13410.       return(-1);
  13411.  
  13412.     if (xlocal)
  13413.       x = ioctl(ttyfd,TIOCMGET,&y);    /* Get modem signals. */
  13414.     else
  13415.       x = ioctl(0,TIOCMGET,&y);
  13416.     debug(F101,"ttgmdm TIOCMGET ioctl","",x);
  13417.     if (x < 0) {
  13418.     debug(F101,"ttgmdm errno","",errno);
  13419.     return(-1);
  13420.     }
  13421.     debug(F101,"ttgmdm bits","",y);
  13422.  
  13423.     z = 0;                /* Initialize return value. */
  13424. #ifdef TIOCM_CTS
  13425.     /* Clear To Send */
  13426.     if (y & TIOCM_CTS) z |= BM_CTS;
  13427.     debug(F101,"ttgmdm TIOCM_CTS defined","",TIOCM_CTS); 
  13428. #else
  13429.     debug(F100,"ttgmdm TIOCM_CTS not defined","",0);
  13430. #endif
  13431. #ifdef TIOCM_DSR
  13432.     /* Data Set Ready */
  13433.     if (y & TIOCM_DSR) z |= BM_DSR;
  13434.     debug(F101,"ttgmdm TIOCM_DSR defined","",TIOCM_DSR); 
  13435. #else
  13436.     debug(F100,"ttgmdm TIOCM_DSR not defined","",0);
  13437. #endif
  13438. #ifdef TIOCM_CAR
  13439.     /* Carrier */
  13440.     if (y & TIOCM_CAR) z |= BM_DCD;
  13441.     debug(F101,"ttgmdm TIOCM_CAR defined","",TIOCM_CAR); 
  13442. #else
  13443.     debug(F100,"ttgmdm TIOCM_CAR not defined","",0);
  13444. #endif
  13445. #ifdef TIOCM_RNG
  13446.     /* Ring Indicate */
  13447.     if (y & TIOCM_RNG) z |= BM_RNG;
  13448.     debug(F101,"ttgmdm TIOCM_RNG defined","",TIOCM_RNG); 
  13449. #else
  13450.     debug(F100,"ttgmdm TIOCM_RNG not defined","",0);
  13451. #endif
  13452. #ifdef TIOCM_DTR
  13453.     /* Data Terminal Ready */
  13454.     if (y & TIOCM_DTR) z |= BM_DTR;
  13455.     debug(F101,"ttgmdm TIOCM_DTR defined","",TIOCM_DTR); 
  13456. #else
  13457.     debug(F100,"ttgmdm TIOCM_DTR not defined","",0);
  13458. #endif
  13459. #ifdef TIOCM_RTS
  13460.     /* Request To Send */
  13461.     if (y & TIOCM_RTS) z |= BM_RTS;
  13462.     debug(F101,"ttgmdm TIOCM_RTS defined","",TIOCM_RTS); 
  13463. #else
  13464.     debug(F100,"ttgmdm TIOCM_RTS not defined","",0);
  13465. #endif
  13466.     gotsigs = 1;
  13467.     return(z);
  13468.  
  13469. #else /* !K_MDMCTL catch-All */
  13470.  
  13471.     debug(F100,"ttgmdm K_MDMCTL not defined","",0);
  13472. #ifdef TIOCMGET
  13473.     debug(F100,"ttgmdm TIOCMGET defined","",0);
  13474. #else
  13475.     debug(F100,"ttgmdm TIOCMGET not defined","",0);
  13476. #endif /* TIOCMGET */
  13477. #ifdef _SVID3
  13478.     debug(F100,"ttgmdm _SVID3 defined","",0);
  13479. #else
  13480.     debug(F100,"ttgmdm _SVID3 not defined","",0);
  13481. #endif /* _SVID3 */
  13482.  
  13483. #ifdef NETCONN
  13484.     if (netconn) {            /* Network connection */
  13485. #ifdef TN_COMPORT
  13486.         if (istncomport()) {
  13487.         gotsigs = 1;
  13488.         return(tngmdm());
  13489.     } else
  13490. #endif /* TN_COMPORT */
  13491.       return(-2);            /* No modem signals */
  13492.     }
  13493. #endif /* NETCONN */
  13494.  
  13495. #ifdef NETCMD
  13496.     if (ttpipe) return(-2);
  13497. #endif /* NETCMD */
  13498. #ifdef NETPTY
  13499.     if (ttpty) return(-2);
  13500. #endif /* NETPTY */
  13501.  
  13502.     return(-3);                /* Sorry, I don't know how... */
  13503.  
  13504. #endif /* K_MDMCTL */
  13505. #endif /* HPUX */
  13506. #endif /* QNX */
  13507. }
  13508.  
  13509. /*  P S U S P E N D  --  Put this process in the background.  */
  13510.  
  13511. /*
  13512.   Call with flag nonzero if suspending is allowed, zero if not allowed.
  13513.   Returns 0 on apparent success, -1 on failure (flag was zero, or
  13514.   kill() returned an error code.
  13515. */
  13516. int
  13517. psuspend(flag) int flag; {
  13518.  
  13519. #ifdef RTU
  13520.     extern int rtu_bug;
  13521. #endif /* RTU */
  13522.  
  13523.     if (flag == 0) return(-1);
  13524.  
  13525. #ifdef NOJC
  13526.     return(-1);
  13527. #else
  13528. #ifdef SIGTSTP
  13529. /*
  13530.   The big question here is whether job control is *really* supported.
  13531.   There's no way Kermit can know for sure.  The fact that SIGTSTP is
  13532.   defined does not guarantee the Unix kernel supports it, and the fact
  13533.   that the Unix kernel supports it doesn't guarantee that the user's
  13534.   shell (or other process that invoked Kermit) supports it.
  13535. */
  13536. #ifdef RTU
  13537.     rtu_bug = 1;
  13538. #endif /* RTU */
  13539.     if (kill(0,SIGSTOP) < 0
  13540. #ifdef MIPS
  13541. /* Let's try this for MIPS too. */
  13542.     && kill(getpid(),SIGSTOP) < 0
  13543. #endif /* MIPS */
  13544.     ) {                /* If job control, suspend the job */
  13545.     perror("suspend");
  13546.     debug(F101,"psuspend error","",errno);
  13547.     return(-1);
  13548.     }
  13549.     debug(F100,"psuspend ok","",0);
  13550.     return(0);
  13551. #else
  13552.     return(-1);
  13553. #endif /* SIGTSTP */
  13554. #endif /* NOJC */
  13555. }
  13556.  
  13557. /*
  13558.   setuid package, by Kristoffer Eriksson, with contributions from Dean
  13559.   Long and fdc.
  13560. */
  13561.  
  13562. /* The following is for SCO when CK_ANSILIBS is defined... */
  13563. #ifdef M_UNIX
  13564. #ifdef CK_ANSILIBS
  13565. #ifndef NOGETID_PROTOS
  13566. #define NOGETID_PROTOS
  13567. #endif /* NOGETID_PROTOS */
  13568. #endif /* CK_ANSILIBS */
  13569. #endif /* M_UNIX */
  13570.  
  13571. #ifndef _POSIX_SOURCE
  13572. #ifndef SUNOS4
  13573. #ifndef NEXT
  13574. #ifndef PS2AIX10
  13575. #ifndef sequent
  13576. #ifndef HPUX9
  13577. #ifndef HPUX10
  13578. #ifndef COHERENT
  13579. #ifndef NOGETID_PROTOS
  13580. _PROTOTYP( UID_T getuid, (void) );
  13581. _PROTOTYP( UID_T geteuid, (void) );
  13582. _PROTOTYP( UID_T getreuid, (void) );
  13583. _PROTOTYP( UID_T getgid, (void) );
  13584. _PROTOTYP( UID_T getegid, (void) );
  13585. _PROTOTYP( UID_T getregid, (void) );
  13586. #endif /* NOGETID_PROTOS */
  13587. #else
  13588. _PROTOTYP( UID_T getreuid, (void) );
  13589. _PROTOTYP( UID_T getregid, (void) );
  13590. #endif /* COHERENT */
  13591. #endif /* HPUX10 */
  13592. #endif /* HPUX9 */
  13593. #endif /* sequent */
  13594. #endif /* PS2AIX10 */
  13595. #endif /* NEXT */
  13596. #endif /* SUNOS4 */
  13597. #endif /* _POSIX_SOURCE */
  13598.  
  13599. /*
  13600. Subject: Set-user-id
  13601. To: fdc@watsun.cc.columbia.edu (Frank da Cruz)
  13602. Date: Sat, 21 Apr 90 4:48:25 MES
  13603. From: Kristoffer Eriksson <ske@pkmab.se>
  13604.  
  13605. This is a set of functions to be used in programs that may be run set-user-id
  13606. and/or set-group-id. They handle both the case where the program is not run
  13607. with such privileges (nothing special happens then), and the case where one
  13608. or both of these set-id modes are used.  The program is made to run with the
  13609. user's real user and group ids most of the time, except for when more
  13610. privileges are needed.  Don't set-user-id to "root".
  13611.  
  13612. This works on System V and POSIX.  In BSD, it depends on the
  13613. "saved-set-user-id" feature.
  13614. */
  13615.  
  13616. #define UID_ROOT 0            /* Root user and group ids */
  13617. #define GID_ROOT 0
  13618.  
  13619. /*
  13620.   The following code defines the symbol SETEUID for UNIX systems based
  13621.   on BSD4.4 (either -Encumbered or -Lite).  This program will then use
  13622.   seteuid() and setegid() instead of setuid() and setgid(), which still
  13623.   don't allow arbitrary switching.  It also avoids setreuid() and
  13624.   setregid(), which are included in BSD4.4 for compatibility only, are
  13625.   insecure, and print warnings to stderr under at least one system (NetBSD
  13626.   1.0).  Note that POSIX systems should still use setuid() and setgid();
  13627.   the seteuid() and setegid() functions are BSD4.4 extensions to the
  13628.   POSIX model.  Mike Long <mike.long@analog.com>, 8/94.
  13629. */
  13630. #ifdef BSD44
  13631. #define SETEUID
  13632. #endif /* BSD44 */
  13633.  
  13634. /*
  13635.   The following construction automatically defines the symbol SETREUID for
  13636.   UNIX versions based on Berkeley Unix 4.2 and 4.3.  If this symbol is
  13637.   defined, then this program will use getreuid() and getregid() calls in
  13638.   preference to getuid() and getgid(), which in Berkeley-based Unixes do
  13639.   not allow arbitrary switching back and forth of real & effective uid.
  13640.   This construction also allows -DSETREUID to be put on the cc command line
  13641.   for any system that has and wants to use setre[ug]id().  It also prevents
  13642.   automatic definition of SETREUID if -DNOSETREU is included on the cc
  13643.   command line (or otherwise defined).
  13644. */
  13645. #ifdef FT18                /* None of this for Fortune. */
  13646. #define NOSETREU
  13647. #endif /* FT18 */
  13648.  
  13649. #ifdef ANYBSD
  13650. #ifndef BSD29
  13651. #ifndef BSD41
  13652. #ifndef SETREUID
  13653. #ifndef NOSETREU
  13654. #ifndef SETEUID
  13655. #define SETREUID
  13656. #endif /* SETEUID */
  13657. #endif /* NOSETREU */
  13658. #endif /* SETREUID */
  13659. #endif /* !BSD41 */
  13660. #endif /* !BSD29 */
  13661. #endif /* ANYBSD */
  13662.  
  13663. /* Variables for user and group IDs. */
  13664.  
  13665. static UID_T realuid = (UID_T) -1, privuid = (UID_T) -1;
  13666. static GID_T realgid = (GID_T) -1, privgid = (GID_T) -1;
  13667.  
  13668.  
  13669. /* P R I V _ I N I  --  Initialize privileges package  */
  13670.  
  13671. /* Called as early as possible in a set-uid or set-gid program to store the
  13672.  * set-to uid and/or gid and step down to the users real uid and gid. The
  13673.  * stored id's can be temporarily restored (allowed in System V) during
  13674.  * operations that require the privilege.  Most of the time, the program
  13675.  * should execute in unpriviliged state, to not impose any security threat.
  13676.  *
  13677.  * Note: Don't forget that access() always uses the real id:s to determine
  13678.  * file access, even with privileges restored.
  13679.  *
  13680.  * Returns an error mask, with error values or:ed together:
  13681.  *   1 if setuid() fails,
  13682.  *   2 if setgid() fails, and
  13683.  *   4 if the program is set-user-id to "root", which can't be handled.
  13684.  *
  13685.  * Only the return value 0 indicates real success. In case of failure,
  13686.  * those privileges that could be reduced have been, at least, but the
  13687.  * program should be aborted none-the-less.
  13688.  *
  13689.  * Also note that these functions do not expect the uid or gid to change
  13690.  * without their knowing. It may work if it is only done temporarily, but
  13691.  * you're on your own.
  13692.  */
  13693. int
  13694. priv_ini() {
  13695.     int err = 0;
  13696.  
  13697. #ifndef HAVE_BAUDBOY
  13698.  
  13699.     /* Save real ID:s. */
  13700.     realuid = getuid();
  13701.     realgid = getgid();
  13702.  
  13703.     /* Save current effective ID:s, those set to at program exec. */
  13704.     privuid = geteuid();
  13705.     privgid = getegid();
  13706.  
  13707.     /* If running set-uid, go down to real uid, otherwise remember that
  13708.      * no privileged uid is available.
  13709.      *
  13710.      * Exceptions:
  13711.      *
  13712.      * 1) If the real uid is already "root" and the set-uid uid (the
  13713.      * initial effective uid) is not "root", then we would have trouble
  13714.      * if we went "down" to "root" here, and then temporarily back to the
  13715.      * set-uid uid (not "root") and then again tried to become "root". I
  13716.      * think the "saved set-uid" is lost when changing uid from effective
  13717.      * uid "root", which changes all uid, not only the effective uid. But
  13718.      * in this situation, we can simply go to "root" and stay there all
  13719.      * the time. That should give sufficient privilege (understatement!),
  13720.      * and give the right uids for subprocesses.
  13721.      *
  13722.      * 2) If the set-uid (the initial effective uid) is "root", and we
  13723.      * change uid to the real uid, we can't change it back to "root" when
  13724.      * we need the privilege, for the same reason as in 1). Thus, we can't
  13725.      * handle programs that are set-user-id to "root" at all. The program
  13726.      * should be stopped.  Use some other uid.  "root" is probably too
  13727.      * privileged for such things, anyway. (The uid is reverted to the
  13728.      * real uid until termination.)
  13729.      *
  13730.      * These two exceptions have the effect that the "root" uid will never
  13731.      * be one of the two uids that are being switched between, which also
  13732.      * means we don't have to check for such cases in the switching
  13733.      * functions.
  13734.      *
  13735.      * Note that exception 1) is handled by these routines (by constantly
  13736.      * running with uid "root", while exception 2) is a serious error, and
  13737.      * is not provided for at all in the switching functions.
  13738.      */
  13739.     if (realuid == privuid)
  13740.     privuid = (UID_T) -1;        /* Not running set-user-id. */
  13741.  
  13742.     /* If running set-gid, go down to real gid, otherwise remember that
  13743.      * no privileged gid is available.
  13744.      *
  13745.      * There are no exception like there is for the user id, since there
  13746.      * is no group id that is privileged in the manner of uid "root".
  13747.      * There could be equivalent problems for group changing if the
  13748.      * program sometimes ran with uid "root" and sometimes not, but
  13749.      * that is already avoided as explained above.
  13750.      *
  13751.      * Thus we can expect always to be able to switch to the "saved set-
  13752.      * gid" when we want, and back to the real gid again. You may also
  13753.      * draw the conclusion that set-gid provides for fewer hassles than
  13754.      * set-uid.
  13755.      */
  13756.  
  13757. #ifdef SUIDDEBUG
  13758.     fprintf(stderr,"UID_ROOT=%d\n",UID_ROOT);
  13759.     fprintf(stderr,"realuid=%d\n",realuid);
  13760.     fprintf(stderr,"privuid=%d\n",privuid);
  13761. #endif /* SUIDDEBUG */
  13762.  
  13763.     if (realgid == privgid)        /* If not running set-user-id, */
  13764.       privgid = (GID_T) -1;        /*  remember it this way. */
  13765.  
  13766.     err = priv_off();            /* Turn off setuid privilege. */
  13767.  
  13768.     if (privuid == UID_ROOT)        /* If setuid to root, */
  13769.       err |= 4;                /* return this error. */
  13770.  
  13771.     if (realuid == UID_ROOT) {        /* If real id is root, */
  13772.     privuid = (UID_T) -1;        /* stay root at all times. */
  13773. #ifdef ATT7300
  13774.     /* If Kermit installed SUID uucp and user is running as root */
  13775.     err &= ~1;            /* System V R0 does not save UID */
  13776. #endif /* ATT7300 */
  13777.     }
  13778. #endif /* HAVE_BAUDBOY */
  13779.     return(err);
  13780. }
  13781.  
  13782.  
  13783. /* Macros for hiding the differences in UID/GID setting between various Unix
  13784.  * systems. These macros should always be called with both the privileged ID
  13785.  * and the non-privileged ID. The one in the second argument, will become the
  13786.  * effective ID. The one in the first argument will be retained for later
  13787.  * retrieval.
  13788.  */
  13789. #ifdef SETREUID
  13790. #ifdef SAVEDUID
  13791. /* On BSD systems with the saved-UID feature, we just juggle the effective
  13792.  * UID back and forth, and leave the real UID at its true value.  The kernel
  13793.  * allows switching to both the current real UID, the effective UID, and the
  13794.  * UID which the program is set-UID to.  The saved set-UID always holds the
  13795.  * privileged UID for us, and the real UID will always be the non-privileged,
  13796.  * and we can freely choose one of them for the effective UID at any time.
  13797.  */
  13798. #define switchuid(hidden,active) setreuid( (UID_T) -1, active)
  13799. #define switchgid(hidden,active) setregid( (GID_T) -1, active)
  13800.  
  13801. #else   /* SETREUID,!SAVEDUID */
  13802.  
  13803. /* On systems with setreXid() but without the saved-UID feature, notably
  13804.  * BSD 4.2, we swap the real and effective UIDs each time.  It's
  13805.  * the effective UID that we are interested in, but we have to retain the
  13806.  * unused UID somewhere to enable us to restore it later, and we do this
  13807.  * in the real UID.  The kernel only allows switching to either the current
  13808.  * real or the effective UID, unless you're "root".
  13809.  */
  13810. #define switchuid(hidden,active)    setreuid(hidden,active)
  13811. #define switchgid(hidden,active)    setregid(hidden,active)
  13812. #endif
  13813.  
  13814. #else /* !SETREUID, !SAVEDUID */
  13815.  
  13816. #ifdef SETEUID
  13817. /*
  13818.   BSD 4.4 works similarly to System V and POSIX (see below), but uses
  13819.   seteXid() instead of setXid() to change effective IDs.  In addition, the
  13820.   seteXid() functions work the same for "root" as for other users.
  13821. */
  13822. #define switchuid(hidden,active)    seteuid(active)
  13823. #define switchgid(hidden,active)    setegid(active)
  13824.  
  13825. #else /* !SETEUID */
  13826.  
  13827. /* On System V and POSIX, the only thing we can change is the effective UID
  13828.  * (unless the current effective UID is "root", but initsuid() avoids that for
  13829.  * us).  The kernel allows switching to the current real UID or to the saved
  13830.  * set-UID.  These are always set to the non-privileged UID and the privileged
  13831.  * UID, respectively, and we only change the effective UID.  This breaks if
  13832.  * the current effective UID is "root", though, because for "root" setuid/gid
  13833.  * becomes more powerful, which is why initsuid() treats "root" specially.
  13834.  * Note: That special treatment maybe could be ignored for BSD?  Note: For
  13835.  * systems that don't fit any of these four cases, we simply can't support
  13836.  * set-UID.
  13837.  */
  13838. #define switchuid(hidden,active)    setuid(active)
  13839. #define switchgid(hidden,active)    setgid(active)
  13840.  
  13841. #endif /* SETEUID */
  13842. #endif /* SETREUID */
  13843.  
  13844.  
  13845. /* P R I V _ O N  --  Turn on the setuid and/or setgid */
  13846.  
  13847. /* Go to the privileged uid (gid) that the program is set-user-id
  13848.  * (set-group-id) to, unless the program is running unprivileged.
  13849.  * If setuid() fails, return value will be 1. If getuid() fails it
  13850.  * will be 2.  Return immediately after first failure, and the function
  13851.  * tries to restore any partial work done.  Returns 0 on success.
  13852.  * Group id is changed first, since it is less serious than user id.
  13853.  */
  13854. int
  13855. priv_on() {
  13856. #ifndef HAVE_BAUDBOY
  13857.     if (privgid != (GID_T) -1)
  13858.       if (switchgid(realgid,privgid))
  13859.         return(2);
  13860.  
  13861.     if (privuid != (UID_T) -1)
  13862.       if (switchuid(realuid,privuid)) {
  13863.       if (privgid != (GID_T) -1)
  13864.         switchgid(privgid,realgid);
  13865.       return(1);
  13866.       }
  13867. #endif /* HAVE_BAUDBOY */
  13868.     return(0);
  13869. }
  13870.  
  13871. /* P R I V _ O F F  --  Turn on the real uid and gid */
  13872.  
  13873. /* Return to the unprivileged uid (gid) after an temporary visit to
  13874.  * privileged status, unless the program is running without set-user-id
  13875.  * (set-group-id). Returns 1 for failure in setuid() and 2 for failure
  13876.  * in setgid() or:ed together. The functions tries to return both uid
  13877.  * and gid to unprivileged state, regardless of errors. Returns 0 on
  13878.  * success.
  13879.  */
  13880. int
  13881. priv_off() {
  13882.     int err = 0;
  13883. #ifndef HAVE_BAUDBOY
  13884.     if (privuid != (UID_T) -1)
  13885.        if (switchuid(privuid,realuid))
  13886.       err |= 1;
  13887.  
  13888.     if (privgid != (GID_T) -1)
  13889.        if (switchgid(privgid,realgid))
  13890.     err |= 2;
  13891. #endif /* HAVE_BAUDBOY */
  13892.     return(err);
  13893. }
  13894.  
  13895. /* Turn off privilege permanently.  No going back.  This is necessary before
  13896.  * a fork() on BSD43 machines that don't save the setUID or setGID, because
  13897.  * we swap the real and effective ids, and we don't want to let the forked
  13898.  * process swap them again and get the privilege back. It will work on other
  13899.  * machines too, such that you can rely on its effect always being the same,
  13900.  * for instance, even when you're in priv_on() state when this is called.
  13901.  * (Well, that part about "permanent" is on System V only true if you follow
  13902.  * this with a call to exec(), but that's what we want it for anyway.)
  13903.  * Added by Dean Long -- dlong@midgard.ucsc.edu
  13904.  */
  13905. int
  13906. priv_can() {
  13907. #ifndef HAVE_BAUDBOY
  13908. #ifdef SETREUID
  13909.     int err = 0;
  13910.     if (privuid != (UID_T) -1)
  13911.        if (setreuid(realuid,realuid))
  13912.       err |= 1;
  13913.  
  13914.     if (privgid != (GID_T) -1)
  13915.         if (setregid(realgid,realgid))
  13916.        err |= 2;
  13917.  
  13918.     return(err);
  13919.  
  13920. #else
  13921. #ifdef SETEUID
  13922.     int err = 0;
  13923.     if (privuid != (UID_T) -1)
  13924.     if (setuid(realuid)) {
  13925.         debug(F101,"setuid failed","",errno);
  13926.         err |= 1;
  13927.         debug(F101,"ruid","",getuid());
  13928.         debug(F101,"euid","",geteuid());
  13929.     }
  13930.     debug(F101,"setuid","",realuid);
  13931.     if (privgid != (GID_T) -1)
  13932.         if (setgid(realgid)) {
  13933.         debug(F101,"setgid failed","",errno);
  13934.         err |= 2;
  13935.         debug(F101,"rgid","",getgid());
  13936.         debug(F101,"egid","",getegid());
  13937.     }
  13938.     debug(F101,"setgid","",realgid);
  13939.     return(err);
  13940. #else
  13941.     /* Easy way of using setuid()/setgid() instead of setreuid()/setregid().*/
  13942.     return(priv_off());
  13943. #endif /* SETEUID */
  13944. #endif /* SETREUID */
  13945. #else
  13946.     return(0);
  13947. #endif /* HAVE_BAUDBOY */
  13948. }
  13949.  
  13950. /* P R I V _ O P N  --  For opening protected files or devices. */
  13951.  
  13952. int
  13953. priv_opn(name, modes) char *name; int modes; {
  13954.     int x;
  13955.     priv_on();                /* Turn privileges on */
  13956.     debug(F111,"priv_opn",name,modes);
  13957.     errno = 0;
  13958.     x = open(name, modes);        /* Try to open the device */
  13959.     debug(F101,"priv_opn result","",x);
  13960.     debug(F101,"priv_opn errno","",errno);
  13961.     priv_off();                /* Turn privileges off */
  13962.     return(x);                /* Return open's return code */
  13963. }
  13964.  
  13965. /*  P R I V _ C H K  --  Check privileges.  */
  13966.  
  13967. /*  Try to turn them off.  If turning them off did not succeed, cancel them */
  13968.  
  13969. int
  13970. priv_chk() {
  13971.     int x, y = 0;
  13972.     x = priv_off();            /* Turn off privs. */
  13973.     if (x != 0 || getuid() == privuid || geteuid() == privuid)
  13974.       y = priv_can();
  13975.     if (x != 0 || getgid() == privgid || getegid() == privgid)
  13976.       y = y | priv_can();
  13977.     return(y);
  13978. }
  13979.  
  13980. UID_T
  13981. real_uid() {
  13982.     return(realuid);
  13983. }
  13984.  
  13985. VOID
  13986. ttimoff() {                /* Turn off any timer interrupts */
  13987.     /* int xx; */
  13988. /*
  13989.   As of 5A(183), we set SIGALRM to SIG_IGN (to ignore alarms) rather than to
  13990.   SIG_DFL (to catch alarms, or if there is no handler, to exit).  This is to
  13991.   cure (mask, really) a deeper problem with stray alarms that occurs on some
  13992.   systems, possibly having to do with sleep(), that caused core dumps.  It
  13993.   should be OK to do this, because no code in this module uses nested alarms.
  13994.   (But we still have to watch out for SCRIPT and DIAL...)
  13995. */
  13996.     /* xx = */ alarm(0);
  13997.     /* debug(F101,"ttimoff alarm","",xx); */
  13998.     if (saval) {            /* Restore any previous */
  13999.     signal(SIGALRM,saval);        /* alarm handler. */
  14000.     /* debug(F101,"ttimoff alarm restoring saval","",saval); */
  14001.     saval = NULL;
  14002.     } else {
  14003.     signal(SIGALRM,SIG_IGN);    /* Used to be SIG_DFL */
  14004.     /* debug(F100,"ttimoff alarm SIG_IGN","",0); */
  14005.     }
  14006. }
  14007.  
  14008.  
  14009. int
  14010. tt_is_secure() {      /* Tells whether the current connection is secure */
  14011.  
  14012.     if (ttyfd == -1)
  14013.       return(0);
  14014.  
  14015.     if (0
  14016. #ifdef SSHBUILTIN
  14017.     || IS_SSH()
  14018. #endif /* SSHBUILTIN */
  14019. #ifdef CK_ENCRYPTION
  14020.     || ck_tn_encrypting() && ck_tn_decrypting()
  14021. #endif /* CK_ENCRYPTION */
  14022. #ifdef CK_SSL
  14023.     || tls_active_flag || ssl_active_flag
  14024. #endif /* CK_SSL */
  14025. #ifdef RLOGCODE
  14026. #ifdef CK_KERBEROS
  14027. #ifdef CK_ENCRYPTION
  14028.     || ttnproto == NP_EK4LOGIN || ttnproto == NP_EK5LOGIN
  14029. #endif /* CK_ENCRYPTION */
  14030. #endif /* CK_KERBEROS */
  14031. #endif /* RLOGCODE */
  14032.     )
  14033.       return(1);
  14034.     return(0);
  14035. }
  14036.  
  14037. #ifdef CK_REDIR
  14038.   
  14039. /* External protocol handler parameters from ckuus3.c */
  14040. extern int exp_handler, exp_stderr, exp_timo;
  14041.  
  14042. #ifdef SELECT
  14043. #ifdef NETPTY
  14044.  
  14045. /* The right size is 24576 */
  14046.  
  14047. #ifndef PTY_PBUF_SIZE            /* Size of buffer to read from pty */
  14048. #define PTY_PBUF_SIZE 24576        /* and write to net. */
  14049. #endif    /* PTY_PBUF_SIZE */
  14050.  
  14051. #ifndef PTY_TBUF_SIZE            /* Size of buffer to read from net */
  14052. #define PTY_TBUF_SIZE 24576        /* and write to pty. */
  14053. #endif    /* PTY_TBUF_SIZE */
  14054.  
  14055. #ifdef O_NDELAY                /* Whether to use nonblocking */
  14056. #ifndef PTY_NO_NDELAY            /* reads on the pseudoterminal */
  14057. #ifndef PTY_USE_NDELAY
  14058. #define PTY_USE_NDELAY
  14059. #endif    /* PTY_USE_NDELAY */
  14060. #endif    /* PTY_NO_NDELAY */
  14061. #endif    /* O_NDELAY */
  14062.  
  14063. #ifndef HAVE_OPENPTY
  14064. #ifndef USE_CKUPTY_C
  14065. #define USE_CKUPTY_C
  14066. #endif /* USE_CKUPTY_C */
  14067. #endif /* HAVE_OPENPTY */
  14068.  
  14069. VOID
  14070. pty_make_raw(fd) int fd; {
  14071.     int x = -23, i;
  14072.  
  14073. #ifdef BSD44ORPOSIX            /* POSIX */
  14074.     struct termios tp;
  14075. #else
  14076. #ifdef ATTSV                /* AT&T UNIX */
  14077. #ifdef CK_ANSIC
  14078.     struct termio tp = {0};
  14079. #else
  14080.     struct termio tp;
  14081. #endif    /* CK_ANSIC */
  14082. #else
  14083.     struct sgttyb tp;            /* Traditional */
  14084. #endif /* ATTSV */
  14085. #endif /* BSD44ORPOSIX */
  14086.  
  14087.     debug(F101,"pty_make_raw fd","",fd);
  14088.     errno = 0;
  14089.  
  14090. #ifdef BSD44ORPOSIX            /* POSIX */
  14091.     x = tcgetattr(fd,&tp);
  14092.     debug(F101,"pty_make_raw tcgetattr","",x);
  14093. #else
  14094. #ifdef ATTSV                /* AT&T UNIX */
  14095.     x = ioctl(fd,TCGETA,&tp);
  14096.     debug(F101,"pty_make_raw TCGETA ioctl","",x);
  14097. #else
  14098.     x = gtty(fd,&tp);
  14099.     debug(F101,"pty_make_raw ttty","",x);
  14100. #endif /* ATTSV */
  14101. #endif /* BSD44ORPOSIX */
  14102.     debug(F101,"pty_make_raw GET errno","",errno);
  14103.  
  14104. #ifdef USE_CFMAKERAW
  14105.     errno = 0;
  14106.     cfmakeraw(&tp);
  14107.     debug(F101,"pty_make_raw cfmakeraw errno","",errno);
  14108. #else  /* USE_CFMAKERAW */
  14109.  
  14110. #ifdef COMMENT
  14111.  
  14112. /* This very simple version recommended by Serg Iakolev doesn't work */
  14113.  
  14114.     tp.c_lflag &= ~(ECHO|ICANON|IEXTEN|ISIG);
  14115.     tp.c_iflag &= ~(BRKINT|ICRNL|INPCK|ISTRIP|IXON);
  14116.     tp.c_cflag &= ~(CSIZE|PARENB);
  14117.     tp.c_cflag |= CS8;
  14118.     tp.c_oflag &= ~(OPOST);
  14119.     tp.c_cc[VMIN] = 1;
  14120.     tp.c_cc[VTIME] = 0;
  14121.  
  14122.     debug(F101,"pty_make_raw 1 c_cc[] NCCS","",NCCS);
  14123.     debug(F101,"pty_make_raw 1 iflags","",tp.c_iflag);
  14124.     debug(F101,"pty_make_raw 1 oflags","",tp.c_oflag);
  14125.     debug(F101,"pty_make_raw 1 lflags","",tp.c_lflag);
  14126.     debug(F101,"pty_make_raw 1 cflags","",tp.c_cflag);
  14127.  
  14128. #else
  14129. #ifdef COMMENT
  14130. /*
  14131.   In this version we unset everything and then set only the
  14132.   bits we know we need.
  14133. */
  14134.     /* iflags */
  14135.     tp.c_iflag = 0L;
  14136.     tp.c_iflag |= IGNBRK;
  14137. #ifdef IMAXBEL
  14138.     tp.c_iflag |= IMAXBEL;
  14139. #endif /* IMAXBEL */
  14140.  
  14141.     /* oflags */
  14142.     tp.c_oflag = 0L;
  14143.  
  14144.     /* lflags */
  14145.     tp.c_lflag = 0L;
  14146. #ifdef NOKERNINFO
  14147.     tp.c_lflag |= NOKERNINFO;
  14148. #endif    /* NOKERNINFO */
  14149.  
  14150.     /* cflags */
  14151.     tp.c_cflag = 0L;
  14152.     tp.c_cflag |= CS8|CREAD;
  14153.  
  14154.     for (i = 0; i < NCCS; i++) {    /* No special characters */
  14155.     tp.c_cc[i] = 0;
  14156.     }
  14157. #ifdef VMIN
  14158.     tp.c_cc[VMIN] = 1;            /* But always wait for input */
  14159. #endif    /* VMIN */
  14160.     debug(F101,"pty_make_raw 2 c_cc[] NCCS","",NCCS);
  14161.     debug(F101,"pty_make_raw 2 iflags","",tp.c_iflag);
  14162.     debug(F101,"pty_make_raw 2 oflags","",tp.c_oflag);
  14163.     debug(F101,"pty_make_raw 2 lflags","",tp.c_lflag);
  14164.     debug(F101,"pty_make_raw 2 cflags","",tp.c_cflag);
  14165.  
  14166. #else  /* COMMENT */
  14167. /*
  14168.   In this version we set or unset every single flag explicitly.  It works a
  14169.   bit better than the simple version just above, but it's still far from
  14170.   adequate.
  14171. */
  14172.     /* iflags */
  14173.     tp.c_iflag &= ~(PARMRK|ISTRIP|BRKINT|INLCR|IGNCR|ICRNL);
  14174.     tp.c_iflag &= ~(INPCK|IGNPAR|IXANY|IXON|IXOFF);
  14175.     tp.c_iflag |= IGNBRK;
  14176. #ifdef IMAXBEL
  14177. #ifdef COMMENT
  14178.     tp.c_iflag |= IMAXBEL;
  14179. #else
  14180.     tp.c_iflag &= ~IMAXBEL;
  14181. #endif /* COMMENT */
  14182. #endif /* IMAXBEL */
  14183. #ifdef IUCLC
  14184.     tp.c_iflag &= ~IUCLC;
  14185. #endif /* IUCLC */
  14186.  
  14187.     /* oflags */
  14188. #ifdef BSDLY
  14189.     tp.c_oflag &= ~BSDLY;
  14190. #endif /* BSDLY */
  14191. #ifdef CRDLY
  14192.     tp.c_oflag &= ~CRDLY;
  14193. #endif /* CRDLY */
  14194. #ifdef FFDLY
  14195.     tp.c_oflag &= ~FFDLY;
  14196. #endif /* FFDLY */
  14197. #ifdef NLDLY
  14198.     tp.c_oflag &= ~NLDLY;
  14199. #endif /* NLDLY */
  14200. #ifdef TABDLY
  14201.     tp.c_oflag &= ~TABDLY;
  14202. #endif /* TABDLY */
  14203. #ifdef VTDLY
  14204.     tp.c_oflag &= ~VTDLY;
  14205. #endif /* VTDLY */
  14206. #ifdef OFDEL
  14207.     tp.c_oflag &= ~OFDEL;
  14208. #endif /* OFDEL */
  14209. #ifdef OFILL
  14210.     tp.c_oflag &= ~OFILL;
  14211. #endif /* OFILL */
  14212. #ifdef OLCUC
  14213.     tp.c_oflag &= ~OLCUC;
  14214. #endif /* OLCUC */
  14215. #ifdef CMSPAR
  14216.     tp.c_oflag &= ~CMSPAR;
  14217. #endif /* CMSPAR */
  14218.     tp.c_oflag &= ~OPOST;
  14219. #ifdef OXTABS
  14220.     tp.c_oflag &= ~OXTABS;
  14221. #endif /* OXTABS */
  14222. #ifdef COMMENT
  14223. #ifdef ONOCR
  14224.     tp.c_oflag &= ~ONOCR;        /* Maybe should be |=? */
  14225.     tp.c_oflag |= ONOCR;        /* makes no difference either way */
  14226. #endif /* ONOCR */
  14227. #endif /* COMMENT */
  14228. #ifdef ONOEOT
  14229.     tp.c_oflag &= ~ONOEOT;
  14230. #endif /* ONOEOT */
  14231. #ifdef ONLRET
  14232.     tp.c_oflag &= ~ONLRET;
  14233. #endif /* ONLRET */
  14234. #ifdef ONLCR
  14235.     tp.c_oflag &= ~ONLCR;
  14236. #endif /* ONLCR */
  14237. #ifdef OCRNL
  14238.     tp.c_oflag &= ~OCRNL;
  14239. #endif /* OCRNL */
  14240.  
  14241.     /* lflags */
  14242.     tp.c_lflag &= ~ECHO;
  14243. #ifdef ECHOE
  14244.     tp.c_lflag &= ~ECHOE;
  14245. #endif /* ECHOE */
  14246. #ifdef ECHONL
  14247.     tp.c_lflag &= ~ECHONL;
  14248. #endif /* ECHONL */
  14249. #ifdef ECHOPRT
  14250.     tp.c_lflag &= ~ECHOPRT;
  14251. #endif /* ECHOPRT */
  14252. #ifdef ECHOKE
  14253.     tp.c_lflag &= ~ECHOKE;
  14254. #endif /* ECHOKE */
  14255. #ifdef ECHOCTL
  14256.     tp.c_lflag &= ~ECHOCTL;
  14257. #endif /* ECHOCTL */
  14258. #ifdef XCASE
  14259.     tp.c_lflag &= ~XCASE;
  14260. #endif /* XCASE */
  14261. #ifdef ALTWERASE
  14262.     tp.c_lflag &= ~ALTWERASE;
  14263. #endif /* ALTWERASE */
  14264. #ifdef EXTPROC
  14265.     tp.c_lflag &= ~(ICANON|ISIG|IEXTEN|TOSTOP|FLUSHO|PENDIN|EXTPROC);
  14266. #else
  14267.     tp.c_lflag &= ~(ICANON|ISIG|IEXTEN|TOSTOP|FLUSHO|PENDIN);
  14268. #endif    /* EXTPROC */
  14269. #ifdef NOKERNINFO
  14270.     tp.c_lflag |= NOKERNINFO;
  14271. #endif    /* NOKERNINFO */
  14272. #ifndef COMMENT
  14273.     tp.c_lflag &= ~NOFLSH;        /* TRY IT THE OTHER WAY? */
  14274. #else
  14275.     tp.c_lflag |= NOFLSH;        /* No, this way is worse */
  14276. #endif /* COMMENT */
  14277.  
  14278.     /* cflags */
  14279.     tp.c_cflag &= ~(CSIZE|PARENB|PARODD);
  14280.     tp.c_cflag |= CS8|CREAD;
  14281.  
  14282. #ifdef MDMBUF
  14283.     tp.c_cflag &= ~(MDMBUF);
  14284. #else
  14285. #ifdef CCAR_OFLOW
  14286.     tp.c_cflag &= ~(CCAR_OFLOW);    /* two names for the same thing */
  14287. #endif /* CCAR_OFLOW */
  14288. #endif /* MDMBUF */
  14289.  
  14290. #ifdef CCTS_OFLOW
  14291.     tp.c_cflag &= ~(CCTS_OFLOW);
  14292. #endif /* CCTS_OFLOW */
  14293. #ifdef CDSR_OFLOW
  14294.     tp.c_cflag &= ~(CDSR_OFLOW);
  14295. #endif /* CDSR_OFLOW */
  14296. #ifdef CDTR_IFLOW
  14297.     tp.c_cflag &= ~(CDTR_IFLOW);
  14298. #endif /* CDTR_IFLOW */
  14299. #ifdef CRTS_IFLOW
  14300.     tp.c_cflag &= ~(CRTS_IFLOW);
  14301. #endif /* CRTS_IFLOW */
  14302. #ifdef CRTSXOFF
  14303.     tp.c_cflag &= ~(CRTSXOFF);
  14304. #endif /* CRTSXOFF */
  14305. #ifdef CRTSCTS
  14306.     tp.c_cflag &= ~(CRTSCTS);
  14307. #endif /* CRTSCTS */
  14308. #ifdef CLOCAL
  14309.     tp.c_cflag &= ~(CLOCAL);
  14310. #endif /* CLOCAL */
  14311. #ifdef CSTOPB
  14312.     tp.c_cflag &= ~(CSTOPB);
  14313. #endif /* CSTOPB */
  14314. #ifdef HUPCL
  14315.     tp.c_cflag &= ~(HUPCL);
  14316. #endif /* HUPCL */
  14317.  
  14318.     for (i = 0; i < NCCS; i++) {    /* No special characters */
  14319.     tp.c_cc[i] = 0;
  14320.     }
  14321. #ifdef VMIN
  14322.     tp.c_cc[VMIN] = 1;            /* But always wait for input */
  14323. #endif    /* VMIN */
  14324.     debug(F101,"pty_make_raw 3 c_cc[] NCCS","",NCCS);
  14325.     debug(F101,"pty_make_raw 3 iflags","",tp.c_iflag);
  14326.     debug(F101,"pty_make_raw 3 oflags","",tp.c_oflag);
  14327.     debug(F101,"pty_make_raw 3 lflags","",tp.c_lflag);
  14328.     debug(F101,"pty_make_raw 3 cflags","",tp.c_cflag);
  14329. #endif /* COMMENT */
  14330. #endif /* COMMENT */
  14331.  
  14332.     errno = 0;
  14333. #ifdef BSD44ORPOSIX            /* POSIX */
  14334.     x = tcsetattr(fd,TCSANOW,&tp);
  14335.     debug(F101,"pty_make_raw tcsetattr","",x);
  14336. #else
  14337. #ifdef ATTSV                /* AT&T UNIX */
  14338.     x = ioctl(fd,TCSETA,&tp);
  14339.     debug(F101,"pty_make_raw ioctl","",x);
  14340. #else
  14341.     x = stty(fd,&tp);            /* Traditional */
  14342.     debug(F101,"pty_make_raw stty","",x);
  14343. #endif /* ATTSV */
  14344. #endif /* BSD44ORPOSIX */
  14345.     debug(F101,"pty_make_raw errno","",errno);
  14346.  
  14347. #endif /* __NetBSD__ */
  14348. }
  14349.  
  14350. static int
  14351. pty_chk(fd) int fd; {
  14352.     int x, n = 0;
  14353.     errno = 0;
  14354. #ifdef FIONREAD
  14355.     x = ioctl(fd, FIONREAD, &n);    /* BSD and most others */
  14356.     ckmakmsg(msgbuf,500,
  14357.          "pty_chk ioctl FIONREAD errno=",
  14358.          ckitoa(errno),
  14359.          " count=",
  14360.          ckitoa(n));
  14361.     debug(F100,msgbuf,"",0);
  14362. #else
  14363.     n = rdchk(fd);
  14364.     debug(F101,"pty_chk rdchk","",n);
  14365. #ifdef RDCHK
  14366. #endif    /* RDCHK */
  14367. #endif    /* FIONREAD */
  14368.     return((n > -1) ? n : 0);
  14369. }
  14370.  
  14371. static int
  14372. pty_get_status(fd,pid) int fd; PID_T pid; {
  14373.     int x, status = -1;
  14374.     PID_T w;
  14375.  
  14376.     debug(F101,"pty_get_status fd","",fd);
  14377.     debug(F101,"pty_get_status pid","",pid);
  14378.  
  14379.     if (pexitstat > -1)
  14380.       return(pexitstat);
  14381.  
  14382. #ifdef COMMENT
  14383.     /* Not only unnecessary but harmful */
  14384.     errno = 0;
  14385.     x = kill(pty_fork_pid,0);
  14386.     debug(F101,"pty_get_status kill value","",x);
  14387.     debug(F101,"pty_get_status kill errno","",errno);
  14388.     if (x > -1 && errno != ESRCH)
  14389.       return(-1);            /* Fork still there */
  14390.     /* Fork seems to be gone */
  14391. #endif    /* COMMENT */
  14392.  
  14393.     errno = 0;
  14394.     x = waitpid(pty_fork_pid,&status,WNOHANG);
  14395.     debug(F111,"pty_get_status waitpid",ckitoa(errno),x);
  14396.     if (x <= 0 && errno == 0) {
  14397.     debug(F101,"pty_get_status waitpid return","",-1);
  14398.     return(-1);
  14399.     }
  14400.     if (x > 0) {
  14401.     if (x != pty_fork_pid)
  14402.       debug(F101,
  14403.         "pty_get_status waitpid pid doesn't match","",pty_fork_pid); 
  14404.     debug(F101,"pty_get_status waitpid status","",status);
  14405.     debug(F101,"pty_get_status waitpid errno","",errno);
  14406.     if (WIFEXITED(status)) {
  14407.         debug(F100,"pty_get_status WIFEXITED","",0);
  14408.         status = WEXITSTATUS(status);
  14409.         debug(F101,"pty_get_status fork exit status","",status);
  14410. #ifdef COMMENT
  14411.         end_pty();
  14412. #endif    /* COMMENT */
  14413.         close(fd);
  14414.         pexitstat = status;
  14415.     } else {
  14416.         debug(F100,"pty_get_status waitpid unexpected status","",0);
  14417.     }
  14418.     }
  14419.     debug(F101,"pty_get_status return status","",status);
  14420.     return(status);
  14421. }
  14422.  
  14423. /* t t p t y c m d  --  Run command on pty and forward to net */
  14424.  
  14425. /*
  14426.   Needed for running external protocols on secure connections.
  14427.   For example, if C-Kermit has made an SSL/TLS or Kerberos Telnet
  14428.   connection, and then needs to transfer a file with Zmodem, which is
  14429.   an external program, this routine reads Zmodem's output, encrypts it,
  14430.   and then forwards it out the connection, and reads the encrypted data
  14431.   stream coming in from the connection, decrypts it, and forwards it to
  14432.   Zmodem.
  14433.  
  14434.   Works like a TCP/IP port forwarder except one end is a pty rather
  14435.   than a socket, which introduces some complications:
  14436.  
  14437.    . On most platforms, select() always indicates the output side of
  14438.      the pty has characters waiting to be read, even when it doesn't,
  14439.      even when the pty process has already exited.
  14440.  
  14441.    . Nonblocking reads must be used on the pty, because there is no
  14442.      way on certain platforms (e.g. NetBSD) to find out how many characters
  14443.      are available to be read (the FIONREAD ioctl always says 0).  The code
  14444.      also allows for blocking reads (if O_NDELAY and O_NONBLOCK are not
  14445.      defined, or if PTY_NO_NDELAY is defined), but on some platforms this can
  14446.      result in single-byte reads and writes (NetBSD again).
  14447.  
  14448.    . Testing for "EOF" on the pty is problematic.  select() never gives
  14449.      any indication.  After the pty process has exited and the fork has
  14450.      disappeared, read() can still return with 0 bytes read but without an
  14451.      error (NetBSD); no known test on the pty file descriptor will indicate
  14452.      that it is no longer valid.  The process ID of the pty fork can be
  14453.      tested on some platforms (NetBSD, luckily) but not others (Solaris,
  14454.      Linux).
  14455.  
  14456.   On the network side, we use ttinc() and ttoc(), which, for network 
  14457.   connections, handle any active security methods.
  14458.  
  14459.   Call with s = command.
  14460.   Returns 0 on failure, 1 on success.
  14461.   fdc - December 2006 - August 2007.
  14462.  
  14463.   NOTE: This code defaults to nonblocking reads if O_NDELAY or O_NONBLOCK are
  14464.   defined in the header files, which should be true of every recent Unix
  14465.   platform.  If this causes trouble somewhere, define PTY_NO_NDELAY, e.g. when
  14466.   building C-Kermit:
  14467.  
  14468.     touch ckutio.c
  14469.     make platformname KFLAGS=-DPTY_NO_NODELAY
  14470. */
  14471. static int have_pty = 0;        /* Do we have a pty? */
  14472.  
  14473. static SIGTYP (*save_sigchld)() = NULL;    /* For catching SIGCHLD */
  14474.  
  14475. static VOID
  14476. sigchld_handler(sig) int sig; {
  14477.     have_pty = 0;            /* We don't have a pty */
  14478. #ifdef DEBUG
  14479.     if (save_sigchld) {
  14480.     (VOID) signal(SIGCHLD,save_sigchld);
  14481.     save_sigchld = NULL;
  14482.     }
  14483.     if (deblog) {
  14484.     debug(F100,"**************","",0);
  14485.     debug(F100,"SIGCHLD caught","",0);
  14486.     debug(F100,"**************","",0);
  14487.     }
  14488. #endif    /* DEBUG */
  14489. }
  14490. #define HAVE_IAC 1
  14491. #define HAVE_CR  2
  14492.  
  14493. int
  14494. ttptycmd(s) char *s; {
  14495.     CHAR tbuf[PTY_TBUF_SIZE];        /* Read from net, write to pty */
  14496.     int tbuf_avail = 0;            /* Pointers for tbuf */
  14497.     int tbuf_written = 0;
  14498.     static int in_state = 0;        /* For TELNET IAC and NVT in */
  14499.     static int out_prev = 0;        /* Simpler scheme for out */
  14500.  
  14501.     CHAR pbuf[PTY_PBUF_SIZE];        /* Read from pty, write to net */
  14502.     CHAR dbuf[PTY_PBUF_SIZE + PTY_PBUF_SIZE + 1]; /* Double-size buffer */
  14503.     int pbuf_avail = 0;            /* Pointers for pbuf */
  14504.     int pbuf_written = 0;
  14505.  
  14506.     int ptyfd = -1;            /* Pty file descriptor */
  14507.     int have_net = 0;            /* We have a network connection */
  14508.     int pty_err = 0;            /* Got error on pty */
  14509.     int net_err = 0;            /* Got error on net */
  14510.     int status = -1;            /* Pty process exit status */
  14511.     int rc = 0;                /* Our return code */
  14512.  
  14513.     int x1 = 0, x2 = 0;            /* Workers... */
  14514.     int c, n, m, t, x;            /* Workers */
  14515.  
  14516.     long seconds_to_wait = 0L;        /* select() timeout */
  14517.     struct timeval tv, *tv2;        /* For select() */
  14518. #ifdef INTSELECT
  14519.     int in, out, err;            /* For select() */
  14520. #else
  14521.     fd_set in, out, err;
  14522. #endif /* INTSELECT */
  14523.     int nfds = 0;            /* For select() */
  14524.  
  14525.     int pset = 0, tset = 0, pnotset = 0, tnotset = 0; /* stats/debuggin only */
  14526.     int read_net_bytes = 0;        /* Stats */
  14527.     int write_net_bytes = 0;        /* Stats */
  14528.     int read_pty_bytes = 0;        /* Stats */
  14529.     int write_pty_bytes = 0;        /* Stats */
  14530.     int is_tn = 0;            /* TELNET protocol is active */
  14531.  
  14532.     int masterfd = -1;
  14533.     int slavefd = -1;
  14534. #ifndef USE_CKUPTY_C
  14535.     struct termios term;
  14536.     struct winsize twin;
  14537.     struct stringarray * q;
  14538.     char ** args = NULL;
  14539. #endif /* USE_CKUPTY_C */
  14540.  
  14541.     in_state = 0;            /* No previous character yet */
  14542.  
  14543.     if (ttyfd == -1) {
  14544.     printf("?Sorry, communication channel is not open\n");
  14545.     return(0);
  14546.     } else {
  14547.     have_net = 1;
  14548.     }
  14549.     if (nopush) {
  14550.     debug(F100,"ttptycmd fail: nopush","",0);
  14551.     return(0);
  14552.     }
  14553.     if (!s) s = "";            /* Defense de bogus arguments */
  14554.     if (!*s) return(0);
  14555.     pexitstat = -1;            /* Fork process exit status */
  14556.  
  14557. #ifdef TNCODE
  14558.     is_tn = (xlocal && netconn && IS_TELNET()) || /* Telnet protocol active */
  14559.         (!xlocal && sstelnet);
  14560. #endif /* TNCODE */
  14561.  
  14562.     debug(F110,"ttptycmd command",s,0);
  14563.     debug(F101,"ttptycmd ttyfd","",ttyfd);
  14564.     debug(F101,"ttptycmd is_tn","",is_tn);
  14565.     debug(F101,"ttptycmd ckermit pid","",getpid());
  14566.  
  14567. #ifdef USE_CKUPTY_C
  14568.     /* Call ckupty.c module to get and set up the pty fork */
  14569.     /* fc 1 == "run an external protocol" */
  14570.     debug(F100,"ttptycmd using ckupty.c","",0);
  14571.     if (do_pty(&ptyfd,s,1) < 0) {    /* Start the command on a pty */
  14572.     debug(F100,"ttptycmd do_pty fails","",0);
  14573.     return(0);
  14574.     }
  14575.     masterfd = ptyfd;
  14576.     pty_master_fd = ptyfd;
  14577. #ifdef COMMENT
  14578.     slavefd = pty_slave_fd;        /* This is not visible to us */
  14579. #endif /* COMMENT */
  14580.     debug(F111,"ttptycmd ptyfd","USE_CKUPTY_C",ptyfd);
  14581.     debug(F111,"ttptycmd masterfd","USE_CKUPTY_C",masterfd);
  14582.     debug(F111,"ttptycmd fork pid","USE_CKUPTY_C",pty_fork_pid);
  14583. #ifndef SOLARIS
  14584.     /* "ioctl inappropriate on device" for pty master */
  14585.     pty_make_raw(masterfd);
  14586. #endif /* SOLARIS */
  14587.  
  14588. #else /* USE_CKUPTY_C */
  14589.  
  14590.     debug(F100,"ttptycmd OPENPTY","",0);
  14591.     if (tcgetattr(0, &term) == -1) {    /* Get controlling terminal's modes */
  14592.     perror("tcgetattr");
  14593.     return(0);
  14594.     }
  14595.     if (ioctl(0, TIOCGWINSZ, (char *) &twin) == -1) { /* and window size */
  14596.     perror("ioctl TIOCGWINSZ");
  14597.     return(0);
  14598.     }
  14599.     if (openpty(&masterfd, &slavefd, NULL, NULL, NULL) == -1) {
  14600.     debug(F101,"ttptycmd openpty failed errno","",errno);
  14601.     perror("opentpy");
  14602.     return(0);
  14603.     }
  14604.     debug(F101,"ttptycmd openpty masterfd","",masterfd);
  14605.     debug(F101,"ttptycmd openpty slavefd","",slavefd);
  14606.     pty_master_fd = masterfd;
  14607.     pty_slave_fd = slavefd;
  14608.     debug(F101,"ttptycmd openpty pty_master_fd","",pty_master_fd);
  14609.  
  14610.     /* Put pty master in raw mode but let forked app control the slave */
  14611.     pty_make_raw(masterfd);
  14612.  
  14613. #ifdef COMMENT
  14614. #ifdef TIOCREMOTE
  14615.     /* TIOCREMOTE,0 = disable all termio processing */
  14616.     x = ioctl(masterfd, TIOCREMOTE, 1);
  14617.     debug(F111,"ttptycmd ioctl TIOCREMOTE",ckitoa(x),errno);
  14618. #endif    /* TIOCREMOTE */
  14619. #ifdef TIOCTTY
  14620.     /* TIOCTTY,0 = disable all termio processing */
  14621.     x = ioctl(masterfd, TIOCTTY, 0);
  14622.     debug(F111,"ttptycmd ioctl TIOCTTY",ckitoa(x),errno);
  14623. #endif    /* TIOCTTY */
  14624. #endif /* COMMENT */
  14625.  
  14626.     have_pty = 1;            /* We have an open pty */
  14627.     save_sigchld = signal(SIGCHLD, sigchld_handler); /* Catch fork quit */
  14628.  
  14629.     pty_fork_pid = fork();        /* Make fork for external protocol */
  14630.     debug(F101,"ttptycmd pty_fork_pid","",pty_fork_pid);
  14631.     if (pty_fork_pid == -1) {
  14632.     perror("fork");
  14633.     return(0);
  14634.     } else if (pty_fork_pid == 0) {    /* In new fork */
  14635.     int x;
  14636.     debug(F101,"ttptycmd new fork pid","",getpid());
  14637.     close(masterfd);        /* Slave quarters no masters allowed */
  14638.     x = setsid();
  14639.     debug(F101,"ttptycmd new fork setsid","",x);
  14640.     if (x == -1) {
  14641.         perror("ttptycmd setsid");
  14642.         exit(1);
  14643.     }
  14644.     signal(SIGINT,SIG_IGN);        /* Let upper fork catch this */
  14645.     
  14646. #ifdef COMMENT
  14647. #ifdef TIOCSCTTY
  14648.     /* Make pty the controlling terminal for the process */
  14649.     /* THIS CAUSES AN INFINITE SIGWINCH INTERRUPT LOOP */
  14650.     x = ioctl(slavefd, TIOCSCTTY, NULL);
  14651.     debug(F101,"ttptycmd TIOCSCTTY","",x);
  14652. #endif    /* TIOCSCTTY */
  14653. #endif    /* COMMENT */
  14654.  
  14655.     /* Initialize slave pty modes and size to those of our terminal */
  14656.     if (tcsetattr(slavefd, TCSANOW, &term) == -1) {
  14657.         perror("ttptycmd tcsetattr");
  14658.         exit(1);
  14659.     }
  14660.     if (ioctl(slavefd, TIOCSWINSZ, &twin) == -1) {
  14661.         perror("ttptycmd ioctl");
  14662.         exit(1);
  14663.     }
  14664. #ifdef COMMENT
  14665. #ifdef TIOCNOTTY
  14666.     /* Disassociate this process from its terminal */
  14667.     /* THIS HAS NO EFFECT */
  14668.     x = ioctl(slavefd, TIOCNOTTY, NULL);
  14669.     debug(F101,"ttptycmd TIOCNOTTY","",x);
  14670. #endif    /* TIOCNOTTY */
  14671. #endif    /* COMMENT */
  14672.  
  14673. #ifdef COMMENT
  14674. #ifdef SIGTTOU    
  14675.     /* Ignore terminal output interrupts */
  14676.     /* THIS HAS NO EFFECT */
  14677.     debug(F100,"ttptycmd ignoring SIGTTOU","",0);
  14678.     signal(SIGTTOU, SIG_IGN);
  14679. #endif    /* SIGTTOU */
  14680. #ifdef SIGTSTP    
  14681.     /* Ignore terminal output interrupts */
  14682.     /* THIS HAS NO EFFECT */
  14683.     debug(F100,"ttptycmd ignoring SIGTSTP","",0);
  14684.     signal(SIGTSTP, SIG_IGN);
  14685. #endif    /* SIGTSTP */
  14686. #endif    /* COMMENT */
  14687.  
  14688.     pty_make_raw(slavefd);        /* Put it in rawmode */
  14689.  
  14690.     errno = 0;
  14691.     if (dup2(slavefd, STDIN_FILENO) != STDIN_FILENO ||
  14692.         dup2(slavefd, STDOUT_FILENO) != STDOUT_FILENO) {
  14693.         debug(F101,"ttptycmd new fork dup2 error","",errno);
  14694.         perror("ttptycmd dup2");
  14695.         exit(1);
  14696.     }
  14697.     debug(F100,"ttptycmd new fork dup2 ok","",0);
  14698.  
  14699.     /* Parse external protocol command line */
  14700.     q = cksplit(1,0,s,NULL,"\\%[]&$+-/=*^_@!{}/<>|.#~'`:;?",7,0,0);
  14701.     if (!q) {
  14702.         debug(F100,"ttptycmd cksplit failed","",0);
  14703.         exit(1);
  14704.     } else {
  14705.         int i, n;
  14706.         debug(F100,"ttptycmd cksplit ok","",0);
  14707.         n = q->a_size;
  14708.         args = q->a_head + 1;
  14709.         for (i = 0; i <= n; i++) {
  14710.         if (!args[i]) {
  14711.             break;
  14712.         } else {
  14713.             /* sometimes cksplit() doesn't terminate the list */
  14714.             if ((i == n) && args[i]) {
  14715.             if ((int)strlen(args[i]) == 0)
  14716.               makestr(&(args[i]),NULL);
  14717.             }
  14718.         }
  14719.         }        
  14720.     }
  14721. #ifdef COMMENT
  14722. /*
  14723.   Putting the slave pty in rawmode should not be necessary because the
  14724.   external protocol program is supposed to do that itself.  Yet doing this
  14725.   here cuts down on Zmodem binary-file transmission errors by 30-50% but
  14726.   still doesn't eliminate them.
  14727. */
  14728.     pty_make_raw(STDIN_FILENO);
  14729.     pty_make_raw(STDOUT_FILENO);
  14730. #endif /* COMMENT */
  14731.  
  14732.     debug(F100,"ttptycmd execvp'ing external protocol","",0);
  14733.     execvp(args[0],args);
  14734.     perror("execvp failed");
  14735.     debug(F101,"ttptycmd execvp failed","",errno);
  14736.     close(slavefd);
  14737.     exit(1);
  14738.     } 
  14739.     /* (there are better ways to do this...) */
  14740.     msleep(1000);          /* Make parent wait for child to be ready */
  14741.     ptyfd = masterfd;            /* We talk to the master */
  14742.  
  14743. #endif /* USE_CKUPTY_C */
  14744.  
  14745.     debug(F101,"ttptycmd ptyfd","",ptyfd);
  14746.     if (ptyfd < 0) {
  14747.     printf("?Failure to get pty\n");
  14748.     return(-9);
  14749.     }
  14750.     have_pty = 1;          /* We have an open pty or we wouldn't he here */
  14751.  
  14752.     debug(F101,"ttptycmd PTY_PBUF_SIZE","",PTY_PBUF_SIZE);
  14753.     debug(F101,"ttptycmd PTY_TBUF_SIZE","",PTY_TBUF_SIZE);
  14754.  
  14755. #ifdef PTY_USE_NDELAY
  14756.     /* 
  14757.        NOTE: If select() and ioctl(ptyfd,FIONREAD,&n) return true indications
  14758.        on the pty, we don't need nonblocking reads.  Performance of either
  14759.        method seems to be about the same, so use whatever works.
  14760.     */
  14761.     errno = 0;
  14762.     x = fcntl(ptyfd,F_SETFL,fcntl(ptyfd,F_GETFL, 0)|O_NDELAY);
  14763.     ckmakmsg(msgbuf,500,
  14764.          "ttptycmd set O_NDELAY errno=",
  14765.          ckitoa(errno),
  14766.          " fcntl=",
  14767.          ckitoa(x));
  14768.     debug(F100,msgbuf,"",0);
  14769. #endif /* PTY_USE_NDELAY */
  14770.  
  14771. #ifdef COMMENT
  14772. /* Not necessary, the protocol module already did this */
  14773.  
  14774. #ifdef USE_CFMAKERAW
  14775.     if (tcgetattr(ttyfd, &term) > -1) {
  14776.     cfmakeraw(&term);
  14777.     debug(F101,"ttptycmd net cfmakeraw errno","",errno);
  14778.     x tcsetattr(ttyfd, TCSANOW, &term);
  14779.     debug(F101,"ttptycmd net tcsetattr","",x);
  14780.     debug(F101,"ttptycmd net tcsetattr","",errno);
  14781.     }
  14782. #else
  14783.     if (local)                /* Put network connection in */
  14784.       ttpkt(ttspeed,ttflow,ttprty);    /* "packet mode". */
  14785.     else
  14786.       conbin((char)escchr);        /* OR... pty_make_raw(0) */
  14787. #endif /* USE_CFMAKERAW */
  14788. #endif /* COMMENT */
  14789.  
  14790. #ifdef TNCODE
  14791.     if (is_tn) {
  14792.       debug(F101,"<<< ttptycmd TELOPT_ME_BINARY","",TELOPT_ME(TELOPT_BINARY));
  14793.       debug(F101,"<<< ttptycmd TELOPT_U_BINARY","",TELOPT_U(TELOPT_BINARY));
  14794.     }
  14795. #endif /* TNCODE */
  14796.  
  14797.     debug(F101,"ttptycmd entering loop - seconds_to_wait","",seconds_to_wait);
  14798.  
  14799.     while (have_pty || have_net) {
  14800.     FD_ZERO(&in);            /* Initialize select() structs */
  14801.     FD_ZERO(&out);
  14802.     FD_ZERO(&err);            /* (not used because useless) */
  14803.     nfds = -1;
  14804.  
  14805.     debug(F101,"ttptycmd loop top have_pty","",have_pty);
  14806.     debug(F101,"ttptycmd loop top have_net","",have_net);
  14807.  
  14808.     /* Pty is open and we have room to read from it? */
  14809.     if (have_pty && pbuf_avail < PTY_PBUF_SIZE) {
  14810.         debug(F100,"ttptycmd FD_SET ptyfd in","",0);
  14811.             FD_SET(ptyfd, &in);
  14812.         nfds = ptyfd;
  14813.         }
  14814.     /* Network is open and we have room to read from it? */
  14815.         if (have_net && have_pty && tbuf_avail < PTY_TBUF_SIZE) {
  14816.         debug(F100,"ttptycmd FD_SET ttyfd in","",0);
  14817.             FD_SET(ttyfd, &in);
  14818.         if (ttyfd > nfds) nfds = ttyfd;
  14819.         }
  14820.     /* Pty is open and we have stuff to write to it? */
  14821.         if (have_pty && tbuf_avail - tbuf_written > 0) {
  14822.         debug(F100,"ttptycmd FD_SET ptyfd out","",0);
  14823.             FD_SET (ptyfd, &out);
  14824.         if (ptyfd > nfds) nfds = ptyfd;
  14825.         }
  14826.     /* Net is open and we have stuff to write to it? */
  14827.     debug(F101,"ttptycmd pbuf_avail-pbuf_written","",
  14828.           pbuf_avail - pbuf_written);
  14829.         if (have_net && pbuf_avail - pbuf_written > 0) {
  14830.         debug(F100,"ttptycmd FD_SET ttyfd out","",0);
  14831.             FD_SET (ttyfd, &out);
  14832.         if (ttyfd > nfds) nfds = ttyfd;
  14833.         }
  14834.     /* We don't use err because it's not really for errors, */
  14835.     /* but for out of band data on the TCP socket, which, if it is */
  14836.     /* to be handled at all, is handled in the tt*() routines */
  14837.  
  14838.     nfds++;                /* 0-based to 1-based */
  14839.     debug(F101,"ttptycmd nfds","",nfds);
  14840.     if (!nfds) {
  14841.         debug(F100,"ttptycmd NO FDs set for select","",0);
  14842.         if (have_pty) {
  14843.         /* This is not right -- sleeping won't accomplish anything */
  14844.         debug(F101,"ttptycmd msleep","",100);
  14845.         msleep(100);        
  14846.         } else {
  14847.         debug(F100,"ttptycmd no pty - quitting loop","",0);
  14848.         break;
  14849.         }
  14850.     }
  14851.     errno = 0;
  14852.  
  14853.     if (seconds_to_wait > 0L) {    /* Timeout in case nothing happens */
  14854.         tv.tv_sec = seconds_to_wait; /* for a long time */
  14855.         tv.tv_usec = 0L;        
  14856.         tv2 = &tv;
  14857.         } else {
  14858.             tv2 = NULL;
  14859.     }
  14860.     x = select(nfds, &in, &out, NULL, tv2);
  14861.     debug(F101,"ttptycmd select","",x);
  14862.     if (x < 0) {
  14863.         if (errno == EINTR)
  14864.           continue;
  14865.         debug(F101,"ttptycmd select error","",errno);
  14866.         break;
  14867.     }
  14868.     if (x == 0) {
  14869.         debug(F101,"ttptycmd +++ select timeout","",seconds_to_wait); 
  14870.         if (have_pty) {
  14871.         status = pty_get_status(ptyfd,pty_fork_pid);
  14872.         debug(F101,"ttptycmd pty_get_status A","",status);
  14873.         if (status > -1) pexitstat = status;
  14874.         have_pty = 0;
  14875.         }
  14876.         break;
  14877.     }
  14878.     /* We want to handle any pending writes first to make room */
  14879.     /* for new incoming. */
  14880.  
  14881.     if (FD_ISSET(ttyfd, &out)) {    /* Can write to net? */
  14882.         CHAR * s;
  14883.         s = pbuf + pbuf_written;    /* Current spot for sending */
  14884. #ifdef TNCODE
  14885.         if (is_tn) {        /* ttol() doesn't double IACs */
  14886.         CHAR c;            /* Rewrite string with IACs doubled */
  14887.         int i;
  14888.         s = pbuf + pbuf_written; /* Source */
  14889.         x = 0;              /* Count */
  14890.         for (i = 0; i < pbuf_avail - pbuf_written; i++) {
  14891.             c = s[i];        /* Next character */
  14892.             if (c == IAC) {    /* If it's IAC */
  14893.             dbuf[x++] = c;    /* put another one */
  14894.             debug(F000,">>> QUOTED IAC","",c);
  14895.             } else if (c != 0x0a && out_prev == 0x0d) {    /* Bare CR */
  14896.             if (!TELOPT_ME(TELOPT_BINARY)) { /* NVT rule */
  14897.                 c = 0x00;
  14898.                 dbuf[x++] = c;
  14899.                 debug(F000,">>> CR-NUL","",c);
  14900.             }            
  14901.             }
  14902.             dbuf[x++] = c;    /* Copy and count it */
  14903.             debug(F000,">>> char",ckitoa(in_state),c);
  14904.             out_prev = c;
  14905.         }
  14906.         s = dbuf;        /* New source */
  14907.         } else
  14908. #endif /* TNCODE */
  14909.           x = pbuf_avail - pbuf_written; /* How much to send */
  14910.  
  14911.         debug(F101,"ttptycmd bytes to send","",x);
  14912.         x = ttol(s, x);
  14913.         debug(F101,">>> ttol","",x);
  14914.         if (x < 0) {
  14915.         net_err++;
  14916.         debug(F111,"ttptycmd ttol error",ckitoa(x),errno);
  14917.         x = 0;
  14918.         }
  14919.         write_net_bytes += x;
  14920.         pbuf_written += x;
  14921.     }
  14922.     if (FD_ISSET(ptyfd, &out)) {    /* Can write to pty? */
  14923.         debug(F100,"ttptycmd FD_ISSET ptyfd out","",0);
  14924.         errno = 0;
  14925. #ifndef COMMENT
  14926.         x = write(ptyfd,tbuf + tbuf_written,tbuf_avail - tbuf_written);
  14927. #else
  14928.         /* Byte loop to rule out data overruns in the pty */
  14929.         /* (it makes no difference) */
  14930.         {
  14931.         char *p = tbuf+tbuf_written;
  14932.         int n = tbuf_avail - tbuf_written;
  14933.         for (x = 0; x < n; x++) {
  14934.             msleep(10);
  14935.             if (write(ptyfd,&(p[x]),1) < 0)
  14936.               break;
  14937.         }
  14938.         }
  14939. #endif /* COMMENT */
  14940.         debug(F111,"ttptycmd ptyfd write",ckitoa(errno),x);
  14941.         if (x > 0) {
  14942.         tbuf_written += x;
  14943.         write_pty_bytes += x;
  14944.         } else {
  14945.         x = 0;
  14946.         pty_err++;
  14947.         if (pexitstat < 0) {
  14948.             status = pty_get_status(ptyfd,pty_fork_pid);
  14949.             debug(F101,"ttptycmd pty_get_status B","",status);
  14950.             if (status > -1) pexitstat = status;
  14951.             have_pty = 0;
  14952.         }
  14953.         debug(F100,"ttptycmd +++ ptyfd write error","",0);
  14954.         }
  14955.     }
  14956.     if (FD_ISSET(ttyfd, &in)) {    /* Can read from net? */
  14957.         tset++;
  14958.         debug(F100,"ttptycmd FD_ISSET ttyfd in","",0);
  14959.         n = in_chk(1,ttyfd);
  14960.         debug(F101,"ttptycmd in_chk(ttyfd)","",n); 
  14961.         if (n < 0 || ttyfd == -1) {
  14962.         debug(F101,"ttptycmd +++ ttyfd errno","",errno);
  14963.         net_err++;
  14964.         } else if (n > 0) {
  14965.         if (n > PTY_TBUF_SIZE - tbuf_avail)
  14966.           n = PTY_TBUF_SIZE - tbuf_avail;
  14967.         debug(F101,"ttptycmd net read size adjusted","",n); 
  14968.         if (xlocal && netconn) {
  14969.             /*
  14970.               We have to use a byte loop here because ttxin()
  14971.               does not decrypt or, for that matter, handle Telnet.
  14972.             */
  14973.             int c;
  14974.             CHAR * p;
  14975.             p = tbuf + tbuf_avail;
  14976.             for (x = 0; x < n; x++) {
  14977.             if ((c = ttinc(0)) < 0)
  14978.               break;
  14979.             if (!is_tn) {    /* Not Telnet - keep all bytes */
  14980.                 *p++ = (CHAR)c;
  14981.                 debug(F000,"<<< char","",c);
  14982. #ifdef TNCODE
  14983.             } else {    /* Telnet - must handle IAC and NVT */
  14984.                 debug(F000,"<<< char",ckitoa(in_state),c);
  14985.                 switch (c) {
  14986.                   case 0x00: /* NUL */
  14987.                 if (in_state == HAVE_CR) {
  14988.                     debug(F000,"<<< SKIP","",c);
  14989.                 } else {
  14990.                     *p++ = c;
  14991.                     debug(F000,"<<< Keep","",c);
  14992.                 }
  14993.                 in_state = 0;
  14994.                 break;
  14995.                   case 0x0d: /* CR */
  14996.                 if (!TELOPT_U(TELOPT_BINARY))
  14997.                   in_state = HAVE_CR;
  14998.                 *p++ = c;
  14999.                 debug(F000,"<<< Keep","",c);
  15000.                 break;
  15001. #ifdef COMMENT
  15002.                   case 0x0f: /* Ctrl-O */
  15003.                   case 0x16: /* Ctrl-V */
  15004.                 *p++ = 0x16;
  15005.                 *p++ = c;
  15006.                 debug(F000,"<<< QUOT","",c);
  15007.                 break;
  15008. #endif /* COMMENT */
  15009.                   case 0xff: /* IAC */
  15010.                 if (in_state == HAVE_IAC) {
  15011.                     debug(F000,"<<< KEEP","",c);
  15012.                     *p++ = c;
  15013.                     in_state = 0;
  15014.                 } else {
  15015.                     debug(F000,"<<< SKIP","",c);
  15016.                     in_state = HAVE_IAC;
  15017.                 }
  15018.                 break;
  15019.                   default:    /* All others */
  15020.                 if (in_state == HAVE_IAC) {
  15021. #ifdef COMMENT
  15022. /*
  15023.   tn_doop() will consume an unknown number of bytes and we'll overshoot
  15024.   the for-loop.  The only Telnet command I've ever seen arrive here is
  15025.   a Data Mark, which comes when the remote protocol exits and the remote
  15026.   job returns to its shell prompt.  On the assumption it's a 1-byte command,
  15027.   we don't write out the IAC or the command, and we clear the state.  If
  15028.   we called tn_doop() we'd have no way of knowing how many bytes it took
  15029.   from the input stream.
  15030. */
  15031.                     int xx;
  15032.                     xx = tn_doop((CHAR)c,duplex,ttinc);
  15033.                     debug(F111,"<<< DOOP",ckctoa(c),xx);
  15034. #else
  15035.                     debug(F101,"<<< DOOP","",c);
  15036. #endif    /* COMMENT */
  15037.                     in_state = 0;
  15038.                 } else {
  15039.                     *p++ = c;
  15040.                     debug(F000,"<<< keep","",c);
  15041.                     in_state = 0;
  15042.                 }
  15043.                 }
  15044. #endif    /* TNCODE */
  15045.             }
  15046.             }
  15047.             ckmakmsg(msgbuf,500,
  15048.                  "ttptycmd read net [ttinc loop] errno=",
  15049.                  ckitoa(errno),
  15050.                  " count=",
  15051.                  ckitoa(x));
  15052.             debug(F100,msgbuf,"",0);
  15053.         } else {
  15054.             x = ttxin(n,tbuf+tbuf_avail);
  15055.             debug(F101,"ttptycmd ttxin x","",x); 
  15056.         }
  15057.  
  15058.         if (x < 0) {
  15059.             debug(F101,"ttptycmd read net error","",x);
  15060.             net_err++;
  15061.         }
  15062.         tbuf_avail += x;
  15063.         read_net_bytes += x;
  15064.         }
  15065.  
  15066.     } else
  15067.       tnotset++;
  15068.  
  15069.     if (FD_ISSET(ptyfd, &in)) {    /* Read from pty? */
  15070.         pset++;
  15071.         debug(F100,"ttptycmd FD_ISSET ptyfd in","",0);
  15072. #ifdef PTY_USE_NDELAY
  15073.         n = PTY_PBUF_SIZE;
  15074. #else
  15075.         /*
  15076.           This does not work on nonblocking channels
  15077.           on certain platforms such as NetBSD.
  15078.         */
  15079.         n = pty_chk(ptyfd);
  15080. #endif /* PTY_USE_NDELAY */
  15081.         debug(F101,"ttptycmd pty_chk() n","",n); 
  15082.  
  15083.         if (n < 0)
  15084.           n = 0;
  15085.         if (n > 0) {
  15086.         if (n > PTY_PBUF_SIZE - pbuf_avail)
  15087.           n = PTY_PBUF_SIZE - pbuf_avail;
  15088.         debug(F101,"ttptycmd pty read size adjusted","",n); 
  15089.         errno = 0;
  15090.         x = read(ptyfd,pbuf+pbuf_avail,n);
  15091. #ifdef DEBUG
  15092.         if (deblog) {
  15093.             ckmakmsg(msgbuf,500,
  15094.                  "ttptycmd read pty errno=",
  15095.                  ckitoa(errno),
  15096.                  " count=",
  15097.                  ckitoa(x));
  15098.             debug(F100,msgbuf,"",0);
  15099.         }
  15100. #endif    /* DEBUG */
  15101.  
  15102.         if (x < 0 && errno == EAGAIN)
  15103.           x = 0;
  15104.  
  15105.         if (x < 0) {        /* This works on Solaris and Linux */
  15106.             pty_err++;        /* but not NetBSD */
  15107.             debug(F100,"TERMINATION TEST A","",0);
  15108. #ifdef COMMENT
  15109.             if (errno == EIO)
  15110.               rc = 1;
  15111. #endif    /* COMMENT */
  15112.             if (pexitstat < 0) {
  15113.             status = pty_get_status(ptyfd,pty_fork_pid);
  15114.             debug(F101,"ttptycmd pty_get_status C","",status);
  15115.             if (status > -1) pexitstat = status;
  15116.             }
  15117.             have_pty = 0;
  15118.             x = 0;
  15119.         }
  15120.         if (x == 0 && !pty_err) { /* This works on NetBSD but */
  15121.             debug(F100,"TERMINATION TEST B","",0);
  15122.             status = pexitstat > -1 ? pexitstat :
  15123.             pty_get_status(ptyfd,pty_fork_pid);
  15124.             debug(F101,"ttptycmd pty_get_status D","",status);
  15125.             if (status > -1) {
  15126.             pexitstat = status;
  15127.             pty_err++;
  15128.             have_pty = 0;
  15129.             } else {        /* Select() lied */
  15130.             pty_err = 0;    /* pty still there but has nothing */
  15131.             msleep(100);    /* sleep a bit */
  15132.             }
  15133.             x = 0;
  15134.         } 
  15135.         /* Hopefully the next two are no longer needed... */
  15136.         if (!pty_err && (
  15137. #ifndef PTY_USE_NDELAY
  15138.             x < 1 || errno
  15139. #else
  15140.             errno != 0 && errno != EAGAIN
  15141. #endif /* PTY_USE_NDELAY */
  15142.             )) {
  15143.             debug(F100,"TERMINATION TEST C","",0);
  15144.             pty_err++;
  15145.             debug(F101,"ttptycmd SET pty_err","",pty_err);
  15146.             if (errno == EIO)    /* errno == EIO is like EOF */
  15147.               rc = 1;
  15148.             if (x < 0)
  15149.               x = 0;
  15150.         }
  15151. #ifdef COMMENT
  15152. #ifdef DEBUG
  15153.         if (deblog) {
  15154.             pbuf[pbuf_avail + x] = '\0';
  15155.             debug(F111,"ttptycmd added to pty buffer",
  15156.               pbuf+pbuf_avail,x);
  15157.         }
  15158. #endif    /* DEBUG */
  15159. #endif    /* COMMENT */
  15160.         pbuf_avail += x;
  15161.         read_pty_bytes += x;
  15162.         } else {            /* n == 0 with blocking reads */
  15163.         debug(F100,
  15164.               "PTY READ RETURNED ZERO BYTES - SHOULD NOT HAPPEN",
  15165.               "",0);
  15166.         }
  15167.     } else
  15168.       pnotset++;
  15169.  
  15170.     /* If writes have caught up to reads, reset the buffers */
  15171.  
  15172.     if (pbuf_written == pbuf_avail)
  15173.       pbuf_written = pbuf_avail = 0;
  15174.     if (tbuf_written == tbuf_avail)
  15175.       tbuf_written = tbuf_avail = 0;
  15176.  
  15177.     /* See if we can exit */
  15178.  
  15179.     x1 = pbuf_avail - pbuf_written; 
  15180.     x2 = tbuf_avail - tbuf_written;
  15181.  
  15182.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST pty_err","",pty_err);
  15183.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST x1 [write to net]","",x1);
  15184.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST x2 [write to pty]","",x2);
  15185.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST rc","",rc);
  15186.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST status","",status);
  15187.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST pexitstat","",pexitstat);
  15188.  
  15189.     if (net_err) {            /* Net error? */
  15190.         debug(F101,"ttptycmd net_err LOOP EXIT TEST net_err","",net_err);
  15191.         if (have_net) {
  15192.         if (local) {
  15193.             ttclos(0);
  15194.             printf("?Connection closed\n");
  15195.         }
  15196.         have_net = 0;
  15197.         }
  15198.         debug(F101,"ttptycmd net_err LOOP EXIT TEST x1","",x1);
  15199.         if (x1 == 0)
  15200.           break;
  15201.     }
  15202.     if (pty_err) {            /* Pty error? */
  15203.         if (have_pty) {
  15204.         if (pexitstat < 0) {        
  15205.             status = pty_get_status(ptyfd,pty_fork_pid);
  15206.             debug(F101,"ttptycmd pty_get_status E","",status);
  15207.             if (status > -1) pexitstat = status;
  15208.         }
  15209.         have_pty = 0;
  15210.         }
  15211.         if (x1 == 0 && x2 == 0) {    /* If buffers are caught up */
  15212.         rc = 1;            /* set preliminary return to success */
  15213.         debug(F101,"ttptycmd pty_err LOOP EXIT TEST rc 2","",rc);
  15214.         break;            /* and exit the loop */
  15215.         }
  15216.     }
  15217.     }
  15218.     debug(F101,"ttptycmd +++ have_pty","",have_pty);
  15219.     if (have_pty) {            /* In case select() failed */
  15220. #ifdef USE_CKUPTY_C
  15221.     end_pty();
  15222.     close(ptyfd);
  15223. #else
  15224.     close(slavefd);
  15225.     close(masterfd);
  15226. #endif /* USE_CKUPTY_C */
  15227.     }
  15228.     pty_master_fd = -1;
  15229.     debug(F101,"ttptycmd +++ pexitstat","",pexitstat);
  15230.     if (pexitstat < 0) {        /* Try one last time to get status */
  15231.     status = pty_get_status(ptyfd,pty_fork_pid);
  15232.     debug(F101,"ttptycmd pty_get_status F","",status);
  15233.     if (status > -1) pexitstat = status;
  15234.     }
  15235.     debug(F101,"ttptycmd +++ final pexitstat","",pexitstat);
  15236.     if (deblog) {            /* Stats for debug log */
  15237.     debug(F101,"ttptycmd +++ pset    ","",pset);
  15238.     debug(F101,"ttptycmd +++ pnotset","",pnotset);
  15239.     debug(F101,"ttptycmd +++ tset    ","",tset);
  15240.     debug(F101,"ttptycmd +++ tnotset","",tnotset);
  15241.  
  15242.     debug(F101,"ttptycmd +++  read_pty_bytes","",read_pty_bytes);
  15243.     debug(F101,"ttptycmd +++ write_net_bytes","",write_net_bytes);
  15244.     debug(F101,"ttptycmd +++  read_net_bytes","",read_net_bytes);
  15245.     debug(F101,"ttptycmd +++ write_pty_bytes","",write_pty_bytes);
  15246.     }
  15247. /*
  15248.   If we got the external protocol's exit status from waitpid(), we use that
  15249.   to set our return code.  If not, we fall back on whatever rc was previously
  15250.   set to, namely 1 (success) if the pty fork seemed to terminate, 0 otherwise.
  15251. */
  15252.     if (save_sigchld) {            /* Restore this if we changed it */
  15253.     (VOID) signal(SIGCHLD,save_sigchld);
  15254.     save_sigchld = NULL;
  15255.     }
  15256.     msleep(500);
  15257.     x = kill(pty_fork_pid,SIGHUP);    /* In case it's still there */
  15258.     pty_fork_pid = -1;
  15259.     debug(F101,"ttptycmd fork kill SIGHUP","",x);
  15260.     if (pexitstat > -1)
  15261.       rc = (pexitstat == 0 ? 1 : 0);
  15262.     debug(F101,"ttptycmd +++ rc","",rc);
  15263.     if (!local) {            /* If in remote mode */
  15264.     conres();            /* restore console to CBREAK mode */
  15265.     concb((char)escchr);
  15266.     }
  15267.     return(rc);
  15268. }
  15269. #endif    /* NETPTY */
  15270. #endif    /* SELECT */
  15271.  
  15272. /* T T R U N C M D  --  Redirect an external command over the connection. */
  15273.  
  15274. /*
  15275.   TTRUNCMD is the routine that was originally used for running external
  15276.   protocols.  It is very simple and works fine provided (a) the connection
  15277.   is not encrypted, and (b) the external protocol uses standard i/o
  15278.   (file descriptors 0 and 1) for file transfer.
  15279. */
  15280.  
  15281. int
  15282. ttruncmd(s) char *s; {
  15283.     PID_T pid;                /* pid of lower fork */
  15284.     int wstat;                /* for wait() */
  15285.     int x;
  15286.     int statusp;
  15287.  
  15288.     if (ttyfd == -1) {
  15289.     printf("?Sorry, device is not open\n");
  15290.     return(0);
  15291.     }
  15292.     if (nopush) {
  15293.     debug(F100,"ttruncmd fail: nopush","",0);
  15294.     return(0);
  15295.     }
  15296.  
  15297. #ifdef NETPTY
  15298. /***************
  15299.   It might also be necessary to use the pty routine for other reasons,
  15300.   e.g. because the external program does not use stdio.
  15301. */
  15302. #ifdef NETCONN
  15303. /*
  15304.   If we have a network connection we use a different routine because
  15305.   (a) if the connection is encrypted, the mechanism used here can't deal
  15306.   with it; and (b) it won't handle any network protocols either, e.g.
  15307.   Telnet, Rlogin, K5 U-to-U, etc.  However, this routine works much
  15308.   better (faster, more transparent) on serial connections and when
  15309.   C-Kermit is in remote mode (i.e. is on the far end).
  15310. */
  15311.     /* For testing always use this */
  15312.     if (netconn)
  15313.       return(ttptycmd(s));
  15314. #endif /* NETCONN */
  15315.  
  15316. /***************/
  15317. #else  /* NETPTY */
  15318.     if (tt_is_secure()) {
  15319.     printf("?Sorry, \
  15320. external protocols over secure connections not supported in this OS.\n"
  15321.               );
  15322.         return(0);
  15323.     }
  15324. #endif    /* NETPTY */
  15325.  
  15326.     conres();                /* Make console normal  */
  15327.     pexitstat = -4;
  15328.     if ((pid = fork()) == 0) {        /* Make a child fork */
  15329.     if (priv_can())            /* Child: turn off privs. */
  15330.       exit(1);
  15331.     dup2(ttyfd, 0);            /* Give stdin/out to the line */
  15332.     dup2(ttyfd, 1);
  15333.     x = system(s);
  15334.     debug(F101,"ttruncmd system",s,x);
  15335.     _exit(x ? BAD_EXIT : 0);
  15336.     } else {
  15337.     SIGTYP (*istat)(), (*qstat)();
  15338.     if (pid == (PID_T) -1)        /* fork() failed? */
  15339.       return(0);
  15340.     istat = signal(SIGINT,SIG_IGN); /* Let the fork handle keyboard */
  15341.     qstat = signal(SIGQUIT,SIG_IGN); /* interrupts itself... */
  15342.  
  15343. #ifdef COMMENT
  15344.         while (((wstat = wait(&statusp)) != pid) && (wstat != -1)) ;
  15345. #else  /* Not COMMENT */
  15346.         while (1) {
  15347.         wstat = wait(&statusp);
  15348.         debug(F101,"ttruncmd wait","",wstat);
  15349.         if (wstat == pid || wstat == -1)
  15350.           break;
  15351.     }
  15352. #endif /* COMMENT */
  15353.  
  15354.     pexitstat = (statusp & 0xff) ? statusp : statusp >> 8;
  15355.     debug(F101,"ttruncmd wait statusp","",statusp);
  15356.     debug(F101,"ttruncmd wait pexitstat","",pexitstat);
  15357.     signal(SIGINT,istat);        /* Restore interrupts */
  15358.     signal(SIGQUIT,qstat);
  15359.     }
  15360.     concb((char)escchr);        /* Restore console to CBREAK mode */
  15361.     return(statusp == 0 ? 1 : 0);
  15362. }
  15363. #endif    /* CK_REDIR */
  15364.  
  15365. struct tm *
  15366. #ifdef CK_ANSIC
  15367. cmdate2tm(char * date, int gmt)         /* date as "yyyymmdd hh:mm:ss" */
  15368. #else
  15369. cmdate2tm(date,gmt) char * date; int gmt;
  15370. #endif
  15371. {
  15372.     /* date as "yyyymmdd hh:mm:ss" */
  15373.     static struct tm _tm;
  15374.     time_t now;
  15375.  
  15376.     if (strlen(date) != 17 ||
  15377.     date[8] != ' ' ||
  15378.     date[11] != ':' ||
  15379.     date[14] != ':')
  15380.       return(NULL);
  15381.  
  15382.     time(&now);
  15383.     if (gmt)
  15384.       _tm = *gmtime(&now);
  15385.     else
  15386.       _tm = *localtime(&now);
  15387.     _tm.tm_year = (date[0]-'0')*1000 + (date[1]-'0')*100 +
  15388.                   (date[2]-'0')*10   + (date[3]-'0')-1900;
  15389.     _tm.tm_mon  = (date[4]-'0')*10   + (date[5]-'0')-1;
  15390.     _tm.tm_mday = (date[6]-'0')*10   + (date[7]-'0');
  15391.     _tm.tm_hour = (date[9]-'0')*10   + (date[10]-'0');
  15392.     _tm.tm_min  = (date[12]-'0')*10  + (date[13]-'0');
  15393.     _tm.tm_sec  = (date[15]-'0')*10  + (date[16]-'0');
  15394.  
  15395.     /* Should we set _tm.tm_isdst to -1 here? */
  15396.  
  15397.     _tm.tm_wday = 0;
  15398.     _tm.tm_yday = 0;
  15399.  
  15400.     return(&_tm);
  15401. }
  15402.  
  15403. #ifdef OXOS
  15404. #undef kill
  15405. #endif /* OXOS */
  15406.  
  15407. #ifdef OXOS
  15408. int
  15409. priv_kill(pid, sig) int pid, sig; {
  15410.     int    i;
  15411.  
  15412.     if (priv_on())
  15413.     debug(F100,"priv_kill priv_on failed","",0);
  15414.     i = kill(pid, sig);
  15415.     if (priv_off())
  15416.     debug(F100,"priv_kill priv_off failed","",0);
  15417.     return(i);
  15418. }
  15419. #endif /* OXOS */
  15420.  
  15421. #ifdef BEOSORBEBOX
  15422. /* #ifdef BE_DR_7 */
  15423. /*
  15424.   alarm() function not supplied with Be OS DR7 - this one contributed by
  15425.   Neal P. Murphy.
  15426. */
  15427.  
  15428. /*
  15429.   This should mimic the UNIX/POSIX alarm() function well enough, with the
  15430.   caveat that one's SIGALRM handler must call alarm_expired() to clean up vars
  15431.   and wait for the alarm thread to finish.
  15432. */
  15433. unsigned int
  15434. alarm(unsigned int seconds) {
  15435.     long time_left = 0;
  15436.  
  15437. /* If an alarm is active, turn it off, saving the unused time */
  15438.     if (alarm_thread != -1) {
  15439.         /* We'll be generous and count partial seconds as whole seconds. */
  15440.         time_left = alarm_struct.time -
  15441.       ((system_time() - time_started) / 1000000.0);
  15442.  
  15443.         /* Kill the alarm thread */
  15444.         kill_thread (alarm_thread);
  15445.  
  15446.         /* We need to clean up as though the alarm occured. */
  15447.         time_started = 0;
  15448.         alarm_struct.thread = -1;
  15449.         alarm_struct.time = 0;
  15450.         alarm_expired();
  15451.     }
  15452.  
  15453. /* Set a new alarm clock, if requested. */
  15454.     if (seconds > 0) {
  15455.         alarm_struct.thread = find_thread(NULL);
  15456.         alarm_struct.time = seconds;
  15457.         time_started = system_time();
  15458.         alarm_thread = spawn_thread (do_alarm,
  15459.                                      "alarm_thread",
  15460.                                      B_NORMAL_PRIORITY,
  15461.                                      (void *) &alarm_struct
  15462.                      );
  15463.         resume_thread (alarm_thread);
  15464.     }
  15465.  
  15466. /* Now return [unused time | 0] */
  15467.     return ((unsigned int) time_left);
  15468. }
  15469.  
  15470. /*
  15471.   This function is the departure from UNIX/POSIX alarm handling. In the case
  15472.   of Be's missing alarm() function, this stuff needs to be done in the SIGALRM
  15473.   handler. When Be implements alarm(), this function call can be eliminated
  15474.   from user's SIGALRM signal handlers.
  15475. */
  15476.  
  15477. void
  15478. alarm_expired(void) {
  15479.     long ret_val;
  15480.  
  15481.     if (alarm_thread != -1) {
  15482.         wait_for_thread (alarm_thread, &ret_val);
  15483.         alarm_thread = -1;
  15484.     }
  15485. }
  15486.  
  15487. /*
  15488.   This is the function that snoozes the requisite number of seconds and then
  15489.   SIGALRMs the calling thread. Note that kill() wants a pid_t arg, whilst Be
  15490.   uses thread_id; currently they are both typdef'ed as long, but I'll do the
  15491.   cast anyway. This function is run in a separate thread.
  15492. */
  15493.  
  15494. long
  15495. do_alarm (void *alarm_struct) {
  15496.     snooze ((double) ((struct ALARM_STRUCT *) alarm_struct)->time * 1000000.0);
  15497.     kill ((pid_t)((struct ALARM_STRUCT *) alarm_struct)->thread, SIGALRM);
  15498.     time_started = 0;
  15499.     ((struct ALARM_STRUCT *) alarm_struct)->thread = -1;
  15500.     ((struct ALARM_STRUCT *) alarm_struct)->time = 0;
  15501. }
  15502. /* #endif */ /* BE_DR_7 */
  15503. #endif /* BEOSORBEBOX */
  15504.  
  15505. #ifdef Plan9
  15506.  
  15507. int
  15508. p9ttyctl(char letter, int num, int param) {
  15509.     char cmd[20];
  15510.     int len;
  15511.  
  15512.     if (ttyctlfd < 0)
  15513.       return -1;
  15514.  
  15515.     cmd[0] = letter;
  15516.     if (num)
  15517.       len = sprintf(cmd + 1, "%d", param) + 1;
  15518.     else {
  15519.     cmd[1] = param;
  15520.     len = 2;
  15521.     }
  15522.     if (write(ttyctlfd, cmd, len) == len) {
  15523.     cmd[len] = 0;
  15524.     /* fprintf(stdout, "wrote '%s'\n", cmd); */
  15525.     return 0;
  15526.     }
  15527.     return -1;
  15528. }
  15529.  
  15530. int
  15531. p9ttyparity(char l) {
  15532.     return p9ttyctl('p', 0, l);
  15533. }
  15534.  
  15535. int
  15536. p9tthflow(int flow, int status) {
  15537.     return p9ttyctl('m', 1, status);
  15538. }
  15539.  
  15540. int
  15541. p9ttsspd(int cps) {
  15542.     if (p9ttyctl('b', 1, cps * 10) < 0)
  15543.       return -1;
  15544.     ttylastspeed = cps * 10;
  15545.     return 0;
  15546. }
  15547.  
  15548. int
  15549. p9openttyctl(char *ttname) {
  15550.     char name[100];
  15551.  
  15552.     if (ttyctlfd >= 0) {
  15553.     close(ttyctlfd);
  15554.     ttyctlfd = -1;
  15555.     ttylastspeed = -1;
  15556.     }
  15557.     sprintf(name, "%sctl", ttname);
  15558.     ttyctlfd = open(name, 1);
  15559.     return ttyctlfd;
  15560. }
  15561.  
  15562. int
  15563. p9concb() {
  15564.     if (consctlfd >= 0) {
  15565.     if (write(consctlfd, "rawon", 5) == 5)
  15566.       return 0;
  15567.     }
  15568.     return -1;
  15569. }
  15570.  
  15571. int
  15572. p9conbin() {
  15573.     return p9concb();
  15574. }
  15575.  
  15576. int
  15577. p9conres() {
  15578.     if (consctlfd >= 0) {
  15579.     if (write(consctlfd, "rawoff", 6) == 6)
  15580.       return 0;
  15581.     }
  15582.     return -1;
  15583. }
  15584.  
  15585. int
  15586. p9sndbrk(int msec) {
  15587.     if (ttyctlfd >= 0) {
  15588.     char cmd[20];
  15589.     int i = sprintf(cmd, "k%d", msec);
  15590.     if (write(ttyctlfd, cmd, i) == i)
  15591.       return 0;
  15592.     }
  15593.     return -1;
  15594. }
  15595.  
  15596. int
  15597. conwrite(char *buf, int n) {
  15598.     int x;
  15599.     static int length = 0;
  15600.     static int holdingcr = 0;
  15601.     int normal = 0;
  15602.     for (x = 0; x < n; x++) {
  15603.     char c = buf[x];
  15604.     if (c == 007) {
  15605.         if (normal) {
  15606.         write(1, buf + (x - normal), normal);
  15607.         length += normal;
  15608.         normal = 0;
  15609.         }
  15610.         /* write(noisefd, "1000 300", 8); */
  15611.         holdingcr = 0;
  15612.     } else if (c == '\r') {
  15613.         if (normal) {
  15614.         write(1, buf + (x - normal), normal);
  15615.         length += normal;
  15616.         normal = 0;
  15617.         }
  15618.         holdingcr = 1;
  15619.     } else if (c == '\n') {
  15620.         write(1, buf + (x - normal), normal + 1);
  15621.         normal = 0;
  15622.         length = 0;
  15623.         holdingcr = 0;
  15624.     } else if (c == '\b') {
  15625.         if (normal) {
  15626.         write(1, buf + (x - normal), normal);
  15627.         length += normal;
  15628.         normal = 0;
  15629.         }
  15630.         if (length) {
  15631.         write(1, &c, 1);
  15632.         length--;
  15633.         }
  15634.         holdingcr = 0;
  15635.     } else {
  15636.         if (holdingcr) {
  15637.         char b = '\b';
  15638.         while (length-- > 0)
  15639.           write(1, &b, 1);
  15640.         length = 0;    /* compiler bug */
  15641.         }
  15642.         holdingcr = 0;
  15643.         normal++;
  15644.     }
  15645.     }
  15646.     if (normal) {
  15647.     write(1, buf + (x - normal), normal);
  15648.     length += normal;
  15649.     }
  15650.     return n;
  15651. }
  15652.  
  15653. void
  15654. conprint(char *fmt, ...) {
  15655.     static char buf[1000];        /* not safe if on the stack */
  15656.  
  15657.     va_list ap;
  15658.     int i;
  15659.  
  15660.     va_start(ap, fmt);
  15661.     i = vsprintf(buf, fmt, ap);
  15662.     conwrite(buf, i);
  15663. }
  15664. #endif /* Plan9 */
  15665.  
  15666. /* fprintf, printf, perror replacements... */
  15667.  
  15668. /* f p r i n t f */
  15669.  
  15670. #ifdef UNIX
  15671. #ifdef CK_ANSIC
  15672. #include <stdarg.h>
  15673. #else /* CK_ANSIC */
  15674. #ifdef __GNUC__
  15675. #include <stdarg.h>
  15676. #else
  15677. #include <varargs.h>
  15678. #endif    /* __GNUC__ */
  15679. #endif /* CK_ANSIC */
  15680. #ifdef fprintf
  15681. #undef fprintf
  15682. static char str1[4096];
  15683. static char str2[4096];
  15684. int
  15685. #ifdef CK_ANSIC
  15686. ckxfprintf(FILE * file, const char * format, ...)
  15687. #else /* CK_ANSIC */
  15688. ckxfprintf(va_alist) va_dcl
  15689. #endif /* CK_ANSIC */
  15690. /* ckxfprintf */ {
  15691.     int i, j, len, got_cr;
  15692.     va_list args;
  15693.     int rc = 0;
  15694.  
  15695. #ifdef CK_ANSIC
  15696.     va_start(args, format);
  15697. #else /* CK_ANSIC */
  15698.     char * format;
  15699.     FILE * file;
  15700.     va_start(args);
  15701.     file = va_arg(args,FILE *);
  15702.     format = va_arg(args,char *);
  15703. #endif /* CK_ANSIC */
  15704.  
  15705.     if (!inserver || (file != stdout && file != stderr && file != stdin)) {
  15706.     rc = vfprintf(file,format,args);
  15707.     } else {
  15708.     unsigned int c;
  15709.         rc = vsprintf(str1, format, args);
  15710.         len = strlen(str1);
  15711.         if (len >= sizeof(str1)) {
  15712.             debug(F101,"ckxfprintf() buffer overflow","",len);
  15713.             doexit(BAD_EXIT,1);
  15714.         }
  15715.         for (i = 0, j = 0, got_cr = 0;
  15716.          i < len && j < sizeof(str1)-2;
  15717.          i++, j++ ) {
  15718.         /* We can't use 255 as a case label because of signed chars */
  15719.         c = (unsigned)(str1[i] & 0xff);
  15720. #ifdef TNCODE
  15721.         if (c == 255) {
  15722.         if (got_cr && !TELOPT_ME(TELOPT_BINARY))
  15723.           str2[j++] = '\0';
  15724.         str2[j++] = IAC;
  15725.         str2[j] = IAC;
  15726.         got_cr = 0;
  15727.         } else
  15728. #endif /* TNCODE */
  15729.         switch (c) {
  15730.           case '\r':
  15731.                 if (got_cr
  15732. #ifdef TNCODE
  15733.             && !TELOPT_ME(TELOPT_BINARY)
  15734. #endif /* TNCODE */
  15735.             )
  15736.           str2[j++] = '\0';
  15737.                 str2[j] = str1[i];
  15738.                 got_cr = 1;
  15739.                 break;
  15740.           case '\n':
  15741.                 if (!got_cr)
  15742.           str2[j++] = '\r';
  15743.                 str2[j] = str1[i];
  15744.                 got_cr = 0;
  15745.                 break;
  15746.           default:
  15747.                 if (got_cr
  15748. #ifdef TNCODE
  15749.             && !TELOPT_ME(TELOPT_BINARY)
  15750. #endif /* TNCODE */
  15751.             )
  15752.           str2[j++] = '\0';
  15753.                 str2[j] = str1[i];
  15754.                 got_cr = 0;
  15755.             }
  15756.         }
  15757.         if (got_cr
  15758. #ifdef TNCODE
  15759.              && !TELOPT_ME(TELOPT_BINARY)
  15760. #endif /* TNCODE */
  15761.              )
  15762.             str2[j++] = '\0';
  15763. #ifdef CK_ENCRYPTION
  15764. #ifdef TNCODE
  15765.         if (TELOPT_ME(TELOPT_ENCRYPTION))
  15766.       ck_tn_encrypt(str2,j);
  15767. #endif /* TNCODE */
  15768. #endif /* CK_ENCRYPTION */
  15769. #ifdef CK_SSL
  15770.     if (inserver && (ssl_active_flag || tls_active_flag)) {
  15771.         /* Write using SSL */
  15772.             char * p = str2;
  15773.           ssl_retry:
  15774.             if (ssl_active_flag)
  15775.           rc = SSL_write(ssl_con, p, j);
  15776.             else
  15777.           rc = SSL_write(tls_con, p, j);
  15778.         debug(F111,"ckxfprintf","SSL_write",rc);
  15779.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,rc)) {
  15780.           case SSL_ERROR_NONE:
  15781.                 if (rc == j)
  15782.           break;
  15783.                 p += rc;
  15784.                 j -= rc;
  15785.                 goto ssl_retry;
  15786.           case SSL_ERROR_WANT_WRITE:
  15787.           case SSL_ERROR_WANT_READ:
  15788.           case SSL_ERROR_SYSCALL:
  15789.                 if (rc != 0)
  15790.           return(-1);
  15791.           case SSL_ERROR_WANT_X509_LOOKUP:
  15792.           case SSL_ERROR_SSL:
  15793.           case SSL_ERROR_ZERO_RETURN:
  15794.           default:
  15795.                 rc = 0;
  15796.             }
  15797.     } else
  15798. #endif /* CK_SSL */
  15799.         fwrite(str2,sizeof(char),j,stdout);
  15800.     }
  15801.     va_end(args);
  15802.     return(rc);
  15803. }
  15804. #endif /* fprintf */
  15805.  
  15806. /* p r i n t f */
  15807.  
  15808. #ifdef printf
  15809. #undef printf
  15810. int
  15811. #ifdef CK_ANSIC
  15812. ckxprintf(const char * format, ...)
  15813. #else /* CK_ANSIC */
  15814. ckxprintf(va_alist) va_dcl
  15815. #endif /* CK_ANSIC */
  15816. /* ckxprintf */ {
  15817.     int i, j, len, got_cr;
  15818.     va_list args;
  15819.     int rc = 0;
  15820.  
  15821. #ifdef CK_ANSIC
  15822.     va_start(args, format);
  15823. #else /* CK_ANSIC */
  15824.     char * format;
  15825.     va_start(args);
  15826.     format = va_arg(args,char *);
  15827. #endif /* CK_ANSIC */
  15828.  
  15829.     if (!inserver) {
  15830.     rc = vprintf(format, args);
  15831.     } else {
  15832.     unsigned int c;
  15833.         rc = vsprintf(str1, format, args);
  15834.         len = strlen(str1);
  15835.         if (len >= sizeof(str1)) {
  15836.             debug(F101,"ckxprintf() buffer overflow","",len);
  15837.             doexit(BAD_EXIT,1);
  15838.         }
  15839.         for (i = 0, j = 0, got_cr=0;
  15840.          i < len && j < sizeof(str1)-2;
  15841.          i++, j++ ) {
  15842.         c = (unsigned)(str1[i] & 0xff);
  15843. #ifdef TNCODE
  15844.         if (c == 255) {
  15845.         if (got_cr && !TELOPT_ME(TELOPT_BINARY))
  15846.           str2[j++] = '\0';
  15847.         str2[j++] = IAC;
  15848.         str2[j] = IAC;
  15849.         got_cr = 0;
  15850.         } else
  15851. #endif /* TNCODE */
  15852.         switch (c) {
  15853.           case '\r':
  15854.                 if (got_cr
  15855. #ifdef TNCODE
  15856.             && !TELOPT_ME(TELOPT_BINARY)
  15857. #endif /* TNCODE */
  15858.             )
  15859.           str2[j++] = '\0';
  15860.                 str2[j] = str1[i];
  15861.                 got_cr = 1;
  15862.                 break;
  15863.           case '\n':
  15864.                 if (!got_cr)
  15865.           str2[j++] = '\r';
  15866.                 str2[j] = str1[i];
  15867.                 got_cr = 0;
  15868.                 break;
  15869.           default:
  15870.                 if (got_cr
  15871. #ifdef TNCODE
  15872.             && !TELOPT_ME(TELOPT_BINARY)
  15873. #endif /* TNCODE */
  15874.             )
  15875.           str2[j++] = '\0';
  15876.                 str2[j] = str1[i];
  15877.                 got_cr = 0;
  15878.                 break;
  15879.         }
  15880.         }
  15881.         if (got_cr
  15882. #ifdef TNCODE
  15883.              && !TELOPT_ME(TELOPT_BINARY)
  15884. #endif /* TNCODE */
  15885.              )
  15886.             str2[j++] = '\0';
  15887. #ifdef CK_ENCRYPTION
  15888. #ifdef TNCODE
  15889.         if (TELOPT_ME(TELOPT_ENCRYPTION))
  15890.       ck_tn_encrypt(str2,j);
  15891. #endif /* TNCODE */
  15892. #endif /* CK_ENCRYPTION */
  15893. #ifdef CK_SSL
  15894.     if (inserver && (ssl_active_flag || tls_active_flag)) {
  15895.             char * p = str2;
  15896.         /* Write using SSL */
  15897.           ssl_retry:
  15898.             if (ssl_active_flag)
  15899.           rc = SSL_write(ssl_con, p, j);
  15900.             else
  15901.           rc = SSL_write(tls_con, p, j);
  15902.         debug(F111,"ckxprintf","SSL_write",rc);
  15903.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,rc)) {
  15904.           case SSL_ERROR_NONE:
  15905.                 if (rc == j)
  15906.           break;
  15907.                 p += rc;
  15908.                 j -= rc;
  15909.                 goto ssl_retry;
  15910.           case SSL_ERROR_WANT_WRITE:
  15911.           case SSL_ERROR_WANT_READ:
  15912.           case SSL_ERROR_SYSCALL:
  15913.                 if (rc != 0)
  15914.           return(-1);
  15915.           case SSL_ERROR_WANT_X509_LOOKUP:
  15916.           case SSL_ERROR_SSL:
  15917.           case SSL_ERROR_ZERO_RETURN:
  15918.           default:
  15919.                 rc = 0;
  15920.             }
  15921.     } else
  15922. #endif /* CK_SSL */
  15923.       rc = fwrite(str2,sizeof(char),j,stdout);
  15924.     }
  15925.     va_end(args);
  15926.     return(rc);
  15927. }
  15928. #endif /* printf */
  15929.  
  15930. /*  p e r r o r  */
  15931.  
  15932. #ifdef perror
  15933. #undef perror
  15934. _PROTOTYP(char * ck_errstr,(VOID));
  15935. #ifdef NEXT
  15936. void
  15937. #else
  15938. #ifdef CK_SCOV5
  15939. void
  15940. #else
  15941. int
  15942. #endif /* CK_SCOV5 */
  15943. #endif /* NEXT */
  15944. #ifdef CK_ANSIC
  15945. ckxperror(const char * str)
  15946. #else /* CK_ANSIC */
  15947. ckxperror(str) char * str;
  15948. #endif /* CK_ANSIC */
  15949. /* ckxperror */ {
  15950.     char * errstr = ck_errstr();
  15951. #ifndef NEXT
  15952. #ifndef CK_SCOV5
  15953.     return
  15954. #endif /* CK_SCOV5 */
  15955. #endif /* NEXT */
  15956.       ckxprintf("%s%s %s\n",str,*errstr?":":"",errstr);
  15957. }
  15958. #endif /* perror */
  15959. #endif /* UNIX */
  15960.  
  15961. #ifdef MINIX2
  15962.  
  15963. /* Minix doesn't have a gettimeofday call (but MINIX3 does).
  15964.  * We fake one here using time(2)
  15965.  */
  15966.  
  15967. #ifndef MINIX3
  15968. int
  15969. gettimeofday(struct timeval *tp, struct timezone *tzp) {
  15970.     tp->tv_usec = 0L;            /* Close enough for horseshoes */
  15971.     if(time(&(tp->tv_sec))==-1)
  15972.       return(-1);
  15973.     return(0);
  15974. }
  15975. #endif    /* MINIX3 */
  15976.  
  15977. #ifndef MINIX3
  15978. int
  15979. readlink(const char *path, void *buf, size_t bufsiz) {
  15980.     errno = ENOSYS;
  15981.     return(-1);
  15982. }
  15983. #endif    /* MINIX3 */
  15984.  
  15985. #endif /* MINIX2 */
  15986.