home *** CD-ROM | disk | FTP | other *** search
/ Columbia Kermit / kermit.zip / archives / ckv301.zip / ckutio.c < prev    next >
C/C++ Source or Header  |  2011-07-14  |  471KB  |  16,039 lines

  1. #define CKUTIO_C
  2.  
  3. #ifdef aegis
  4. char *ckxv = "Aegis Communications support, 9.0.325, 14 July 2011";
  5. #else
  6. #ifdef Plan9
  7. char *ckxv = "Plan 9 Communications support, 9.0.325, 14 July 2011";
  8. #else
  9. char *ckxv = "UNIX Communications support, 9.0.325, 14 July 2011";
  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, 2011,
  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. #ifndef HPUXPRE65
  54. #include <errno.h>            /* Error number symbols */
  55. #else
  56. #ifndef ERRNO_INCLUDED
  57. #include <errno.h>            /* Error number symbols */
  58. #endif    /* ERRNO_INCLUDED */
  59. #endif    /* HPUXPRE65 */
  60.  
  61. #ifdef __386BSD__
  62. #define ENOTCONN 57
  63. #else
  64. #ifdef __bsdi__
  65. #define ENOTCONN 57
  66. #else
  67. #ifdef __FreeBSD__
  68. #define ENOTCONN 57
  69. #endif /* __FreeBSD__ */
  70. #endif /* __bsdi__ */
  71. #endif /* __386BSD__ */
  72.  
  73. #ifdef SCO_OSR504
  74. #define NBBY 8
  75. #endif /* SCO_OSR504 */
  76.  
  77. #ifdef Plan9
  78. #define SELECT
  79. #include <sys/time.h>
  80. #include <select.h>
  81. #define FD_SETSIZE (3 * sizeof(long) * 8)
  82. static struct timeval tv;
  83. #endif /* Plan9 */
  84.  
  85. #ifdef CLIX
  86. #include <sys/time.h>
  87. #endif /* CLIX */
  88.  
  89. #include "ckcnet.h"            /* Symbols for network types. */
  90. #ifdef CK_SSL
  91. #include "ck_ssl.h"
  92. #endif /* CK_SSL */
  93.  
  94. /*
  95.   The directory-related includes are here because we need to test some
  96.   file-system-related symbols to find out which system we're being compiled
  97.   under.  For example, MAXNAMLEN is defined in BSD4.2 but not 4.1.
  98. */
  99. #ifdef SDIRENT                /* Directory bits... */
  100. #define DIRENT
  101. #endif /* SDIRENT */
  102.  
  103. #ifdef XNDIR
  104. #include <sys/ndir.h>
  105. #else /* !XNDIR */
  106. #ifdef NDIR
  107. #include <ndir.h>
  108. #else /* !NDIR, !XNDIR */
  109. #ifdef RTU
  110. #include "/usr/lib/ndir.h"
  111. #else /* !RTU, !NDIR, !XNDIR */
  112. #ifdef DIRENT
  113. #ifdef SDIRENT
  114. #include <sys/dirent.h>
  115. #else
  116. #include <dirent.h>
  117. #endif /* SDIRENT */
  118. #else /* !RTU, !NDIR, !XNDIR, !DIRENT, i.e. all others */
  119. #include <sys/dir.h>
  120. #endif /* DIRENT */
  121. #endif /* RTU */
  122. #endif /* NDIR */
  123. #endif /* XNDIR */
  124.  
  125. #ifdef QNX
  126. #include <sys/dev.h>
  127. #endif /* QNX */
  128.  
  129. #ifdef HPUX5
  130. #ifndef TCPSOCKET
  131. /* I don't know why this is needed here since we never reference bzero(). */
  132. /* But without it C-Kermit won't link in an HP-UX 5.xx non-TCP build. */
  133. void
  134. bzero(s,n) char *s; int n; {
  135.     extern char * memset();
  136.     memset(s,0,n);
  137. }
  138. #endif /* TCPSOCKET */
  139. #endif /* HPUX5 */
  140.  
  141. /* Definition of HZ, used in msleep() */
  142.  
  143. #ifdef MIPS
  144. #define HZ ( 1000 / CLOCK_TICK )
  145. #else  /* MIPS */
  146. #ifdef ATTSV
  147. #ifndef NAP
  148. #ifdef TRS16
  149. #define HZ ( 1000 / CLOCK_TICK )
  150. #endif /* TRS16 */
  151. #ifdef NAPHACK
  152. #define nap(x) (void)syscall(3112, (x))
  153. #define NAP
  154. #endif /* NAPHACK */
  155. #endif /* NAP */
  156. #endif /* ATTSV */
  157. #endif /* MIPS */
  158.  
  159. #ifdef M_UNIX
  160. #undef NGROUPS_MAX        /* Prevent multiple definition warnings */
  161. #endif /* M_UNIX */
  162.  
  163. /*
  164.   NOTE: HP-UX 8.0 has a <sys/poll.h>, but there is no corresponding
  165.   library routine, so _poll comes up undefined at link time.
  166. */
  167. #ifdef CK_POLL
  168. #ifndef AIXRS            /* IBM AIX needs special handling */
  169. #include <poll.h>        /* "standard" (SVID) i/o multiplexing, etc */
  170. #else /* AIXRS */
  171. #ifdef SVR4            /* AIX 3.2 is like SVID... */
  172. #include <poll.h>
  173. #else                /* But AIX 3.1 is not ... */
  174. #include <sys/poll.h>        /* The include file is in include/sys */
  175. #define events reqevents    /* And it does not map IBM-specific member */
  176. #define revents rtnevents    /* names to the System V equivalents */
  177. #endif /* SVR4 */
  178. #endif /* AIXRS */
  179. #endif /* CK_POLL */
  180.  
  181. #include <signal.h>                     /* Signals */
  182.  
  183. /* For setjmp and longjmp */
  184.  
  185. #ifndef ZILOG
  186. #include <setjmp.h>
  187. #else
  188. #include <setret.h>
  189. #endif /* ZILOG */
  190.  
  191. /*
  192.   The following test differentiates between 4.1 BSD and 4.2 & later.
  193.   If you have a 4.1BSD system with the DIRENT library, this test could
  194.   mistakenly diagnose 4.2BSD and then later enable the use of system calls
  195.   that aren't defined.  If indeed there are such systems, we can use some
  196.   other way of testing for 4.1BSD, or add yet another compile-time switch.
  197. */
  198. #ifdef BSD4
  199. #ifdef MAXNAMLEN
  200. #ifndef FT21                /* Except for Fortune. */
  201. #ifndef FT18
  202. #ifndef BELLV10                /* And Bell Labs Research UNIX V10 */
  203. #define BSD42
  204. #endif /* BELLV10 */
  205. #endif /* FT18 */
  206. #endif /* FT21 */
  207. #endif /* MAXNAMLEN */
  208. #endif /* BSD4 */
  209.  
  210. #ifdef SUNOS41                /* From Christian Corti */
  211. #define BSD44ORPOSIX            /* Uni Stuttgart */
  212. #define SVORPOSIX            /* February 2010 */
  213. #include <termios.h>
  214. #include <sys/ioctl.h>
  215. #include <unistd.h>
  216. #include <limits.h>
  217. #endif    /* SUNOS41 */
  218.  
  219. #ifdef SNI542
  220. #include <sys/filio.h>            /* 299 for FIONREAD */
  221. #endif    /* SNI542 */
  222.  
  223. /*
  224.   Minix 2.0 support added by Terry McConnell,
  225.   Syracuse University <tmc@barnyard.syr.edu>
  226.   No more sgtty interface, posix compliant.
  227. */
  228. #ifdef MINIX2
  229. #define _MINIX   /* Needed for some Minix header files */
  230. #define BSD44ORPOSIX
  231. #define SVORPOSIX
  232. #ifndef MINIX3
  233. #define DCLTIMEVAL
  234. #endif    /* MINIX3 */
  235. #define NOFILEH
  236. #include <sys/types.h>
  237. #include <sys/ioctl.h>
  238. #include <termios.h>
  239. #include <limits.h>
  240. #undef TIOCGETC    /* defined in sys/ioctl.h, but not really supported */
  241. #define TANDEM 0
  242. #endif /* MINIX2 */
  243.  
  244. /*
  245.  MINIX 1.0 support added by Charles Hedrick,
  246.  Rutgers University <hedrick@aramis.rutgers.edu>.
  247.  MINIX also has V7 enabled.
  248. */
  249. #ifdef MINIX
  250. #define TANDEM 0
  251. #define MYREAD
  252. #define NOSYSIOCTLH
  253. #include <limits.h>
  254. #endif /* MINIX */
  255.  
  256. #ifdef CK_REDIR        /* <sys/wait.h> needed only for REDIRECT command. */
  257. /*
  258.   If anybody can figure out how to make this work with NeXTSTEP, be
  259.   my guest!  (NeXTBlah/NeXTBlah/bsd/sys/wait.h does not define WEXITSTATUS)
  260. */
  261. #ifndef CK_WAIT_H            /* If wait.h not already included... */
  262. #ifdef OSF                /* force OSF to select POSIX wait */
  263. #ifdef _BSD                /* instead of BSD (see ckcdeb.h) */
  264. #define CK_OSF_BSD
  265. #undef _BSD
  266. #endif /* _BSD */
  267. #endif /* OSF */
  268. #include <sys/wait.h>            /* Include it */
  269. #ifdef OSF
  270. #ifdef CK_OSF_BSD
  271. #define _BSD                /* Restore it */
  272. #undef CK_OSF_BSD
  273. #endif /* CK_OSF_BSD */
  274. #endif /* OSF */
  275. #endif /* CK_WAIT_H */
  276. #endif /* CK_REDIR */
  277.  
  278. #include "ckuver.h"            /* Version herald */
  279. char *ckxsys = HERALD;
  280.  
  281. #ifdef CK_UTSNAME
  282. #include <sys/utsname.h>
  283.  
  284. #ifdef TRU64                /* Tru64 UNIX 4.0 and later */
  285. /* Verified on Tru64 4.0F - might break on 4.0E or earlier */
  286. #include <sys/sysinfo.h>        /* (don't know about OSF/1 or DU) */
  287. #include <machine/hal_sysinfo.h>
  288. #endif /* TRU64 */
  289.  
  290. #ifdef SOLARIS25            /* Solaris 2.5 and later */
  291. #include <sys/systeminfo.h>        /* (don't know about earlier ones) */
  292. #endif /* SOLARIS25 */
  293.  
  294. #ifdef UW7
  295. #ifndef SYS_NMLN
  296. #define SYS_NMLN 257
  297. #endif /* NMLN */
  298. #endif /* UW7 */
  299. #ifdef HPUX9PLUS
  300. static int hpis800 = 0;
  301. #endif /* HPUX9PLUS */
  302. #ifdef SYS_NMLN
  303. #define CK_SYSNMLN SYS_NMLN
  304. #else
  305. #ifdef _SYS_NMLN
  306. #define CK_SYSNMLN _SYS_NMLN
  307. #else
  308. #ifdef UTSLEN
  309. #define CK_SYSNMLN UTSLEN
  310. #else
  311. #define CK_SYSNMLN 31
  312. #endif /* UTSLEN */
  313. #endif /* _SYS_NMLN */
  314. #endif /* SYS_NMLN */
  315. char unm_mch[CK_SYSNMLN+1] = { '\0', '\0' };
  316. char unm_mod[CK_SYSNMLN+1] = { '\0', '\0' };
  317. char unm_nam[CK_SYSNMLN+1] = { '\0', '\0' };
  318. char unm_rel[CK_SYSNMLN+1] = { '\0', '\0' };
  319. char unm_ver[CK_SYSNMLN+1] = { '\0', '\0' };
  320. #endif /* CK_UTSNAME */
  321.  
  322. #ifdef CIE
  323. #include <stat.h>            /* For chasing symlinks, etc. */
  324. #else
  325. #include <sys/stat.h>
  326. #endif /* CIE */
  327.  
  328. #ifdef QNX                /* 299 */
  329. #ifndef IXANY
  330. #define IXANY 0
  331. #endif    /* IXANY */
  332. #endif    /* QNX */
  333.  
  334. /* UUCP lockfile material... */
  335.  
  336. #ifndef NOUUCP
  337. #ifdef USETTYLOCK
  338. #ifdef HAVE_LOCKDEV            /* Red Hat baudboy/lockdev */
  339. /*
  340.   Watch out: baudboy.h references open() without making sure it has been
  341.   declared, resulting in warnings on at least Red Hat 7.3.  It's declared in
  342.   fcntl.h, but we don't include that until later.  In this case only, we
  343.   include it here, and then the second include is harmless because in Red Hat
  344.   Linux (the only place where you find baudboy.h) fcntl.h is protected from
  345.   multiple inclusion by _FCNTL_H.   - fdc, 10 May 2004.
  346.  
  347.   NOTE: Although Linux /usr/sbin/lockdev obviates the need for setuid or
  348.   setgid bits to access the lockfile, C-Kermit will still need them to access
  349.   the serial port itself unless the port is open for world read/write.
  350.   Normally setgid uucp does the trick.
  351.  
  352.   Extra: HAVE_LOCKDEV has been added als openSuSE >= 11.3 doesn't use baudboy
  353.   but ttylock.  - jb, 26 Jul 2010
  354. */
  355. #include <fcntl.h>            /* This has to come before baudboy */
  356. #ifdef HAVE_BAUDBOY            /* Red Hat baudboy/lockdev */
  357. #include <baudboy.h>
  358. #else  /* !HAVE_BAUDBOY */        /* openSuSE lock via ttylock */
  359. #include <ttylock.h>
  360. #endif  /* HAVE_BAUDBOY */
  361. #define LOCK_DIR "/var/lock"        /* (even though we don't care) */
  362.  
  363. #else  /* !HAVE_LOCKDEV */
  364.  
  365. #ifdef USE_UU_LOCK
  366. #ifdef __FreeBSD__
  367. #include <libutil.h>            /* FreeBSD */
  368. #else
  369. #include <util.h>            /* OpenBSD */
  370. #endif /* HAVE_LOCKDEV */
  371. #endif /* __FreeBSD */
  372. #endif /* USE_UU_LOCK */
  373. #else  /* USETTYLOCK */
  374.  
  375. /* Name of UUCP tty device lockfile */
  376.  
  377. #ifdef LINUXFSSTND
  378. #ifndef HDBUUCP
  379. #define HDBUUCP
  380. #endif /* HDBUUCP */
  381. #endif /* LINUXFSSTND */
  382.  
  383. #ifdef ACUCNTRL
  384. #define LCKDIR
  385. #endif /* ACUCNTRL */
  386.  
  387. /*
  388.   PIDSTRING means use ASCII string to represent pid in lockfile.
  389. */
  390. #ifndef PIDSTRING
  391. #ifdef HDBUUCP
  392. #define PIDSTRING
  393. #else
  394. #ifdef BSD44
  395. #define PIDSTRING
  396. #else
  397. #ifdef RTAIX
  398. #define PIDSTRING
  399. #else
  400. #ifdef AIXRS
  401. #define PIDSTRING
  402. #else
  403. #ifdef COHERENT
  404. #define PIDSTRING
  405. #endif /* COHERENT */
  406. #endif /* AIXRS */
  407. #endif /* RTAIX */
  408. #endif /* BSD44 */
  409. #endif /* HDBUUCP */
  410. #endif /* PIDSTRING */
  411.  
  412. /* Now the PIDSTRING exceptions... */
  413.  
  414. #ifdef PIDSTRING
  415. #ifdef HPUX
  416. #undef PIDSTRING
  417. #endif /* HPUX */
  418. #endif /* PIDSTRING */
  419.  
  420. #ifdef __bsdi__                /* BSDI (at least thru 1.1) */
  421. #ifdef PIDSTRING
  422. #undef PIDSTRING
  423. #endif /* PIDSTRING */
  424. #endif /* __bsdi__ */
  425.  
  426. #ifdef OSF32                /* Digital UNIX (OSF/1) 3.2 */
  427. #ifdef PIDSTRING
  428. #undef PIDSTRING
  429. #endif /* PIDSTRING */
  430. #endif /* OSF32 */
  431.  
  432. /*
  433.   LOCK_DIR is the name of the lockfile directory.
  434.   If LOCK_DIR is already defined (e.g. on command line), we don't change it.
  435. */
  436.  
  437. #ifndef LOCK_DIR
  438. #ifdef MACOSX
  439. #define LOCK_DIR "/var/spool/lock"
  440. #endif /* MACOSX */
  441. #endif/* LOCK_DIR */
  442.  
  443. #ifndef LOCK_DIR
  444. #ifdef BSD44
  445. #ifdef __386BSD__
  446. #define LOCK_DIR "/var/spool/lock"
  447. #else
  448. #ifdef __FreeBSD__
  449. #define LOCK_DIR "/var/spool/lock"
  450. #else
  451. #ifdef __NetBSD__
  452. #define LOCK_DIR "/var/spool/lock"
  453. #else
  454. #ifdef __OpenBSD__
  455. #define LOCK_DIR "/var/spool/lock"
  456. #else
  457. /* So which ones is this for? */
  458. /* Probably original 4.4BSD on Vangogh */
  459. /* Plus who knows about Mac OS X... It doesn't even have a cu program */
  460. #define LOCK_DIR "/var/spool/uucp"
  461. #endif /* __OpenBSD__ */
  462. #endif /* __NetBSD__ */
  463. #endif /* __FreeBSD__ */
  464. #endif /* __386BSD__ */
  465. #else
  466. #ifdef DGUX430
  467. #define LOCK_DIR "/var/spool/locks"
  468. #else
  469. #ifdef HPUX10
  470. #define LOCK_DIR "/var/spool/locks"
  471. #else
  472. #ifdef RTAIX                /* IBM RT PC AIX 2.2.1 */
  473. #define LOCK_DIR "/etc/locks"
  474. #else
  475. #ifdef AIXRS
  476. #define LOCK_DIR "/etc/locks"
  477. #else
  478. #ifdef ISIII
  479. #define LOCK_DIR "/etc/locks"
  480. #else
  481. #ifdef HDBUUCP
  482. #ifdef M_SYS5
  483. #define LOCK_DIR "/usr/spool/uucp"
  484. #else
  485. #ifdef M_UNIX
  486. #define LOCK_DIR "/usr/spool/uucp"
  487. #else
  488. #ifdef SVR4
  489. #define LOCK_DIR "/var/spool/locks"
  490. #else
  491. #ifdef SUNOS4
  492. #define LOCK_DIR "/var/spool/locks"
  493. #else
  494. #ifdef LINUXFSSTND
  495. #define LOCK_DIR "/var/lock";
  496. #else
  497. #define LOCK_DIR "/usr/spool/locks"
  498. #endif /* LINUXFSSTND */
  499. #endif /* SUNOS4 */
  500. #endif /* SVR4 */
  501. #endif /* M_UNIX */
  502. #endif /* M_SYS5 */
  503. #else
  504. #ifdef LCKDIR
  505. #define LOCK_DIR "/usr/spool/uucp/LCK"
  506. #else
  507. #ifdef COHERENT
  508. #define LOCK_DIR "/usr/spool/uucp"
  509. #else
  510. #define LOCK_DIR "/usr/spool/uucp"
  511. #endif /* COHERENT */
  512. #endif /* LCKDIR */
  513. #endif /* HDBUUCP */
  514. #endif /* ISIII */
  515. #endif /* AIXRS */
  516. #endif /* RTAIX */
  517. #endif /* HPUX10 */
  518. #endif /* DGUX430 */
  519. #endif /* BSD44 */
  520. #endif /* !LOCK_DIR (outside ifndef) */
  521.  
  522. #ifdef OSF2                /* OSF/1 2.0 or later */
  523. #ifdef LOCK_DIR                /* (maybe 1.x too, who knows...) */
  524. #undef LOCK_DIR
  525. #define LOCK_DIR "/var/spool/locks"
  526. #endif /* LOCK_DIR */
  527. #endif /* OSF2 */
  528.  
  529. #ifdef COMMENT
  530. /* Sorry no more lockf() -- we lock first and THEN open the device. */
  531. #ifdef SVR4
  532. #ifndef BSD44
  533. #ifndef LOCKF
  534. #define LOCKF                /* Use lockf() on tty device in SVR4 */
  535. #endif /* LOCKF */
  536. #endif /* BSD44 */
  537. #endif /* SVR4 */
  538. #endif /* COMMENT */
  539.  
  540. #ifdef NOLOCKF                /* But NOLOCKF cancels LOCKF */
  541. #ifdef LOCKF
  542. #undef LOCKF
  543. #endif /* LOCKF */
  544. #endif /* NOLOCKF */
  545.  
  546. /* More about this below... */
  547.  
  548. #endif /* USETTYLOCK */
  549. #endif /* NOUUCP */
  550.  
  551. /*
  552.   MYREAD means use our internally defined nonblocking buffered read routine.
  553. */
  554. #ifdef ATTSV
  555. #define MYREAD
  556. #endif /* ATTSV */
  557.  
  558. #ifdef ATT7300
  559. #ifndef MYREAD
  560. #define MYREAD
  561. #endif /* MYREAD */
  562. /* bits for attmodem: internal modem in use, restart getty */
  563. #define ISMODEM 1
  564. #define DOGETY 512
  565. #endif  /* ATT7300 */
  566.  
  567. #ifdef BSD42
  568. #define MYREAD
  569. #endif /* BSD42 */
  570.  
  571. #ifdef POSIX
  572. #define MYREAD
  573. #endif /* POSIX */
  574. #ifdef __bsdi__
  575. #ifndef O_NDELAY
  576. #define O_NDELAY O_NONBLOCK
  577. #endif /* O_NDELAY */
  578. #endif /* __bsdi__ */
  579.  
  580. /*
  581.  Variables available to outside world:
  582.  
  583.    dftty  -- Pointer to default tty name string, like "/dev/tty".
  584.    dfloc  -- 0 if dftty is console, 1 if external line.
  585.    dfprty -- Default parity
  586.    dfflow -- Default flow control
  587.    ckxech -- Flag for who echoes console typein:
  588.      1 - The program (system echo is turned off)
  589.      0 - The system (or front end, or terminal).
  590.    functions that want to do their own echoing should check this flag
  591.    before doing so.
  592.  
  593.    flfnam  -- Name of lock file, including its path, e.g.,
  594.                 "/usr/spool/uucp/LCK..cul0" or "/etc/locks/tty77"
  595.    lkflfn  -- Name of link to lock file, including its paths
  596.    haslock -- Flag set if this kermit established a uucp lock.
  597.    lockpid -- PID of other process that has desired line open, as string.
  598.    backgrd -- Flag indicating program executing in background ( & on
  599.                 end of shell command). Used to ignore INT and QUIT signals.
  600.    rtu_bug -- Set by stptrap().  RTU treats ^Z as EOF (but only when we handle
  601.                 SIGTSTP)
  602.  
  603.  Functions for assigned communication line (either external or console tty):
  604.  
  605.    sysinit()               -- System dependent program initialization
  606.    syscleanup()            -- System dependent program shutdown
  607.    ttopen(ttname,local,mdmtyp,timo) -- Open the named tty for exclusive access.
  608.    ttclos()                -- Close & reset the tty, releasing any access lock.
  609.    ttsspd(cps)             -- Set the transmission speed of the tty.
  610.    ttgspd()                -- Get (read) the the transmission speed of the tty.
  611.    ttpkt(speed,flow,parity) -- Put the tty in packet mode and set the speed.
  612.    ttvt(speed,flow)        -- Put the tty in virtual terminal mode.
  613.                                 or in DIALING or CONNECTED modem control state.
  614.    ttres()                 -- Restore original tty modes.
  615.    ttscarr(carrier)        -- Set carrier control mode, on/off/auto.
  616.    ttinl(dest,max,timo)    -- Timed read line from the tty.
  617.    ttinc(timo)             -- Timed read character from tty.
  618.    myread()                -- Raw mode bulk buffer read, gives subsequent
  619.                                 chars one at a time and simulates FIONREAD.
  620.    myunrd(c)               -- Places c back in buffer to be read (one only)
  621.    ttchk()                 -- See how many characters in tty input buffer.
  622.    ttxin(n,buf)            -- Read n characters from tty (untimed).
  623.    ttol(string,length)     -- Write a string to the tty.
  624.    ttoc(c)                 -- Write a character to the tty.
  625.    ttflui()                -- Flush tty input buffer.
  626.    ttsndb()                -- Send BREAK signal.
  627.    ttsndlb()               -- Send Long BREAK signal.
  628.  
  629.    ttlock(ttname)          -- "Lock" tty device against uucp collisions.
  630.    ttunlck()               -- Unlock tty device.
  631.  
  632.                               For ATT7300/Unix PC, System V:
  633.    attdial(ttname,speed,telnbr) -- dials ATT7300/Unix PC internal modem
  634.    offgetty(ttname)        -- Turns off getty(1m) for comms line
  635.    ongetty(ttname)         -- Restores getty() to comms line
  636. */
  637.  
  638. /*
  639. Functions for console terminal:
  640.  
  641.    congm()   -- Get console terminal modes.
  642.    concb(esc) -- Put the console in single-character wakeup mode with no echo.
  643.    conbin(esc) -- Put the console in binary (raw) mode.
  644.    conres()  -- Restore the console to mode obtained by congm().
  645.    conoc(c)  -- Unbuffered output, one character to console.
  646.    conol(s)  -- Unbuffered output, null-terminated string to the console.
  647.    conola(s) -- Unbuffered output, array of strings to the console.
  648.    conxo(n,s) -- Unbuffered output, n characters to the console.
  649.    conchk()  -- Check if characters available at console (bsd 4.2).
  650.                 Check if escape char (^\) typed at console (System III/V).
  651.    coninc(timo)  -- Timed get a character from the console.
  652.    congks(timo)  -- Timed get keyboard scan code.
  653.    conint()  -- Enable terminal interrupts on the console if not background.
  654.    connoi()  -- Disable terminal interrupts on the console if not background.
  655.  
  656. Time functions
  657.  
  658.    msleep(m) -- Millisecond sleep
  659.    ztime(&s) -- Return pointer to date/time string
  660.    rtimer() --  Reset timer
  661.    gtimer()  -- Get elapsed time since last call to rtimer()
  662. */
  663.  
  664. /* Conditional Includes */
  665.  
  666. /* Whether to include <sys/file.h> */
  667.  
  668. #ifdef RTU                /* RTU doesn't */
  669. #define NOFILEH
  670. #endif /* RTU */
  671.  
  672. #ifdef CIE                /* CIE does. */
  673. #undef NOFILEH
  674. #endif /* CIE */
  675.  
  676. #ifdef BSD41                /* 4.1 BSD doesn't */
  677. #define NOFILEH
  678. #endif /* BSD41 */
  679.  
  680. #ifdef is68k                /* Integrated Solutions 68000 UNIX  */
  681. #define NOFILEH                /* e.g. on Plexux P60 and Sun-1 */
  682. #endif /* is68k */
  683.  
  684. #ifdef MINIX                /* MINIX */
  685. #define NOFILEH
  686. #endif /* MINIX */
  687.  
  688. #ifdef COHERENT                /* Coherent */
  689. #define NOFILEH
  690. #endif /* COHERENT */
  691.  
  692. #ifndef NOFILEH                /* Now include if selected. */
  693. #include <sys/file.h>
  694. #endif /* NOFILEH */
  695.  
  696. /* POSIX */
  697.  
  698. #ifdef BSD44ORPOSIX            /* POSIX uses termios.h */
  699. #define TERMIOS
  700. #ifdef __bsdi__
  701. #ifdef POSIX
  702. #undef _POSIX_SOURCE            /* Get extra stuff from termios.h */
  703. #endif /* POSIX */
  704. #endif /* __bsdi__ */
  705. #include <termios.h>
  706. #ifdef LINUX
  707. #include <sys/ioctl.h>
  708. #endif /* LINUX */
  709. #ifdef QNX16
  710. #include <ioctl.h>
  711. #else
  712. #ifdef QNX6
  713. #include <ioctl.h>
  714. #endif /* QNX6 */
  715. #endif /* QNX16 */
  716. #ifdef __bsdi__
  717. #ifdef POSIX
  718. #define _POSIX_SOURCE
  719. #endif /* POSIX */
  720. #endif /* __bsdi__ */
  721. #ifndef BSD44                /* Really POSIX */
  722. #ifndef CK_QNX32            /* was CK_QNX32 */
  723. #define NOSYSIOCTLH            /* No ioctl's allowed. */
  724. #undef ultrix                /* Turn off any ultrix features. */
  725. #endif /* CK_QNX32 */
  726. #endif /* BSD44 */
  727. #endif /* POSIX */
  728.  
  729. /* System III, System V */
  730.  
  731. #ifdef ATTSV
  732. #ifndef BSD44
  733. #ifndef POSIX
  734. #include <termio.h>
  735. #endif /* POSIX */
  736. #endif /* BSD44 */
  737. #ifdef TERMIOX
  738. /* Need this for termiox structure, RTS/CTS and DTR/CD flow control */
  739. #include <termiox.h>
  740.   struct termiox rctsx;
  741. #else
  742. #ifdef STERMIOX
  743. #ifdef SCO_OSR504
  744. /* Sorry, this is truly disgusting but it's SCO's fault. */
  745. #ifndef _SVID3
  746. #define _CK_SVID3_X
  747. #define _SVID3
  748. #endif /* _SVID3 */
  749. #endif /* SCO_OSR504 */
  750. #include <sys/termiox.h>
  751.   struct termiox rctsx;
  752. #ifdef CK_SVID3_X
  753. #undef _SVID3
  754. #undef CK_SVID3_X
  755. #endif /* CK_SVID3_X */
  756. #endif /* STERMIOX */
  757. #endif /* TERMIOX */
  758. #endif /* ATTSV */
  759.  
  760. #ifdef COHERENT            /* Use termio.h, not sgtty.h for Coherent */
  761. #include <termio.h>
  762. #endif /* COHERENT */
  763.  
  764. #ifdef MINIX                /* MINIX uses ioctl's */
  765. #define NOSYSIOCTLH            /* but has no <sys/ioctl.h> */
  766. #endif /* MINIX */
  767.  
  768. /* Others */
  769.  
  770. #ifndef NOSYSIOCTLH            /* Others use ioctl() */
  771. #ifdef SUN4S5
  772. /*
  773.   This is to get rid of cpp warning messages that occur because all of
  774.   these symbols are defined by both termios.h and ioctl.h on the SUN.
  775. */
  776. #undef ECHO
  777. #undef NL0
  778. #undef NL1
  779. #undef TAB0
  780. #undef TAB1
  781. #undef TAB2
  782. #undef XTABS
  783. #undef CR0
  784. #undef CR1
  785. #undef CR2
  786. #undef CR3
  787. #undef FF0
  788. #undef FF1
  789. #undef BS0
  790. #undef BS1
  791. #undef TOSTOP
  792. #undef FLUSHO
  793. #undef PENDIN
  794. #undef NOFLSH
  795. #endif /* SUN4S5 */
  796. #include <sys/ioctl.h>
  797. #endif /* NOSYSIOCTLH */
  798. /*
  799.   We really, really, REALLY want FIONREAD, because it is the only way to find
  800.   out not just *if* stuff is waiting to be read, but how much, which is
  801.   critical to our sliding-window and streaming procedures, not to mention
  802.   efficiency of CONNECT, etc.
  803. */
  804. #ifdef BELLV10
  805. #include <sys/filio.h>            /* For FIONREAD */
  806. #ifdef FIONREAD
  807. #define MYREAD
  808. #endif /* MYREAD */
  809. #endif /* BELLV10 */
  810.  
  811. #ifndef FIONREAD
  812. /* It wasn't found in ioctl.h or term*.h - try these places: */
  813. #ifdef UNIXWARE
  814. #include <sys/filio.h>
  815. #else
  816. #ifdef SOLARIS
  817. #include <sys/filio.h>
  818. #endif /* SOLARIS */
  819. #endif /* UNIXWARE */
  820. #endif /* FIONREAD */
  821.  
  822. #ifdef XENIX /* Was M_UNIX but XENIX implies M_UNIX and applies to XENIX too */
  823. /*
  824.   <sys/socket.h> included above via "ckcnet.h" defines FIONREAD as
  825.   something.  Due to this, in_chk() uses the FIONREAD instead of RDCHK
  826.   and the hot keys during file transfer (X to cancel file etc) do not
  827.   work because FIONREAD doesn't work even though it is defined.
  828.  
  829.   NOTE: This might also be true elsewhere.
  830. */
  831. #ifdef FIONREAD
  832. #undef FIONREAD
  833. #endif /* FIONREAD */
  834. #endif /* XENIX */
  835.  
  836. #ifdef CK_SCOV5                /* Ditto for SCO OpenServer 5.0 */
  837. #ifndef SCO_OSR507            /* 299 */
  838. #ifdef FIONREAD
  839. #undef FIONREAD
  840. #endif /* FIONREAD */
  841. #endif    /* SCO_OSR507 */
  842. #endif /* CK_SCOV5 */
  843.  
  844. #ifdef SCO_OSR507            /* 299 */
  845. #ifdef RDCHK
  846. #undef RDCHK
  847. #endif    /* RDCHK */
  848. #endif    /* SCO_OSR507 */
  849.  
  850. /* Whether to include <fcntl.h> */
  851.  
  852. #ifndef is68k                /* Only a few don't have this one. */
  853. #ifndef BSD41
  854. #ifndef FT21
  855. #ifndef FT18
  856. #ifndef COHERENT
  857. #include <fcntl.h>
  858. #endif /* COHERENT */
  859. #endif /* FT18 */
  860. #endif /* FT21 */
  861. #endif /* BSD41 */
  862. #endif /* not is68k */
  863.  
  864. #ifdef COHERENT
  865. #ifdef _I386
  866. #include <fcntl.h>
  867. #else
  868. #include <sys/fcntl.h>
  869. #endif /* _I386 */
  870. #endif /* COHERENT */
  871.  
  872. #ifdef ATT7300                /* Unix PC, internal modem dialer */
  873. #include <sys/phone.h>
  874. #endif /* ATT7300 */
  875.  
  876. #ifdef HPUX                /* HP-UX variations. */
  877. #define HPUXJOBCTL
  878. #include <sys/modem.h>            /* HP-UX modem signals */
  879. #ifdef hp9000s500            /* Model 500 */
  880. #undef HPUXJOBCTL
  881. #endif /* hp9000s500 */
  882. #ifdef HPUXPRE65
  883. #undef HPUXJOBCTL
  884. typedef long mflag;
  885. #endif /* HPUXPRE65 */
  886. #ifdef HPUXJOBCTL
  887. #include <sys/bsdtty.h>            /* HP-UX Berkeley tty support */
  888. #endif /* HPUXJOBCTL */
  889. #endif /* HPUX */
  890.  
  891. /*
  892.   Which time.h files to include... See ckcdeb.h for defaults.
  893.   Note that 0, 1, 2, or all 3 of these can be included according to
  894.   the symbol definitions.
  895. */
  896. #ifndef NOTIMEH
  897. #ifdef TIMEH
  898. #include <time.h>
  899. #endif /* TIMEH */
  900. #endif /* NOTIMEH */
  901.  
  902. #ifndef NOSYSTIMEH
  903. #ifdef SYSTIMEH
  904. #include <sys/time.h>
  905. #endif /* SYSTIMEH */
  906. #endif /* NOSYSTIMEH */
  907.  
  908. #ifndef NOSYSTIMEBH
  909. #ifdef SYSTIMEBH
  910. #include <sys/timeb.h>
  911. #endif /* SYSTIMEBH */
  912. #endif /* NOSYSTIMEBH */
  913.  
  914. #ifndef NODCLTIMEVAL
  915. #ifdef DCLTIMEVAL
  916. /*
  917.   In certain POSIX builds (like Unixware 7), <[sys/]time.h> refuses to
  918.   define the structs we need to access the higher speeds, so we have to
  919.   do it ourselves.
  920. */
  921. struct timeval {
  922.     long tv_sec;
  923.     long tv_usec;
  924. };
  925. struct timezone {
  926.     int tz_minuteswest;
  927.     int tz_dsttime;
  928. };
  929. #endif /* DCLTIMEVAL */
  930. #endif /* NODCLTIMEVAL */
  931.  
  932. #ifdef __linux__
  933. /* THIS IS OBSOLETE since about Linux 0.92 */
  934. #ifdef OLINUXHISPEED
  935. #include <linux/serial.h>
  936. #endif /* OLINUXHISPEED */
  937. #ifdef __alpha__            /* Linux on DEC Alpha */
  938. #ifndef __GLIBC__            /* But not with glibc */
  939. #include <asm/termios.h>
  940. #endif /* __GLIBC__ */
  941. #endif /* __alpha__ */
  942. #endif /* __linux__ */
  943.  
  944. #ifdef NOIEXTEN                /* This is broken on some systems */
  945. #undef IEXTEN                /* like Convex/OS 9.1 */
  946. #endif /* NOIEXTEN */
  947. #ifndef IEXTEN                /* Turn off ^O/^V processing. */
  948. #define IEXTEN 0            /* Needed, at least, on BSDI. */
  949. #endif /* IEXTEN */
  950. /*
  951.   Pick up definitions needed for select() if we don't have them already.
  952.   Normally they come from <sys/types.h> but some systems get them from
  953.   <sys/select.h>...  Rather than hardwire all of them into the source, we
  954.   include it if SELECT_H is defined in compile-time CFLAGS.
  955. */
  956. #ifndef SCO_OSR504
  957. #ifdef SELECT_H
  958. #include <sys/select.h>
  959. #endif /* SELECT_H */
  960. #endif /* SCO_OSR504 */
  961.  
  962. #ifdef aegis
  963. #include "/sys/ins/base.ins.c"
  964. #include "/sys/ins/error.ins.c"
  965. #include "/sys/ins/ios.ins.c"
  966. #include "/sys/ins/sio.ins.c"
  967. #include "/sys/ins/pad.ins.c"
  968. #include "/sys/ins/time.ins.c"
  969. #include "/sys/ins/pfm.ins.c"
  970. #include "/sys/ins/pgm.ins.c"
  971. #include "/sys/ins/ec2.ins.c"
  972. #include "/sys/ins/type_uids.ins.c"
  973. #include <default_acl.h>
  974. #undef TIOCEXCL
  975. #undef FIONREAD
  976. #endif /* aegis */
  977.  
  978. #ifdef sxaE50                /* PFU Compact A SX/A TISP V10/L50 */
  979. #undef FIONREAD
  980. #endif /* sxaE50 */
  981.  
  982. /* The following #defines are catch-alls for those systems */
  983. /* that didn't have or couldn't find <file.h>... */
  984.  
  985. #ifndef FREAD
  986. #define FREAD 0x01
  987. #endif /* FREAD */
  988.  
  989. #ifndef FWRITE
  990. #define FWRITE 0x10
  991. #endif /* FWRITE */
  992.  
  993. #ifndef O_RDONLY
  994. #define O_RDONLY 000
  995. #endif /* O_RDONLY */
  996.  
  997. /* This is for ancient Unixes that don't have these tty symbols defined. */
  998.  
  999. #ifndef PENDIN
  1000. #define PENDIN ICANON
  1001. #endif /* PENDIN */
  1002. #ifndef FLUSHO
  1003. #define FLUSHO ICANON
  1004. #endif /* FLUSHO */
  1005. #ifndef EXTPROC
  1006. #define EXTPROC ICANON
  1007. #endif /* EXTPROC */
  1008.  
  1009. #ifdef SVORPOSIX
  1010. /*
  1011.   Modem signals are also forbidden in the POSIX world.  But some POSIX-based
  1012.   platforms let us at them anyway if we know where to look.
  1013. */
  1014. #ifndef NEEDMDMDEFS
  1015. /* Doesn't work for Linux */
  1016. #ifdef UNIXWARE7
  1017. #define NEEDMDMDEFS
  1018. #endif /* UNIXWARE7 */
  1019. #endif /* NEEDMDMDEFS */
  1020.  
  1021. #ifdef NEEDMDMDEFS
  1022. #ifndef TIOCMGET
  1023. #define TIOCMGET (('t'<<8)|29)
  1024. #endif /* TIOCMGET */
  1025.  
  1026. #ifndef TIOCM_DTR
  1027. #define TIOCM_DTR 0x0002
  1028. #endif /* TIOCM_DTR */
  1029. #ifndef TIOCM_RTS
  1030. #define TIOCM_RTS 0x0004
  1031. #endif /* TIOCM_RTS */
  1032. #ifndef TIOCM_CTS
  1033. #define TIOCM_CTS 0x0020
  1034. #endif /* TIOCM_CTS */
  1035. #ifndef TIOCM_CAR
  1036. #define TIOCM_CAR 0x0040
  1037. #endif /* TIOCM_CAR */
  1038. #ifndef TIOCM_RNG
  1039. #define TIOCM_RNG 0x0080
  1040. #endif /* TIOCM_RNG */
  1041. #ifndef TIOCM_DSR
  1042. #define TIOCM_DSR 0x0100
  1043. #endif /* TIOCM_DSR */
  1044. #endif /* NEEDMDMDEFS */
  1045. #endif /* SVORPOSIX */
  1046.  
  1047. /* Declarations */
  1048.  
  1049. #ifdef OXOS
  1050. #undef TCGETA
  1051. #undef TCSETA
  1052. #undef TCSETAW
  1053. #undef TCSETAF
  1054. #define TCGETA TCGETS
  1055. #define TCSETA TCSETS
  1056. #define TCSETAW TCSETSW
  1057. #define TCSETAF TCSETSF
  1058. #define termio termios
  1059. #endif /* OXOS */
  1060.  
  1061. #ifdef SVORPOSIX            /* AT&T Sys V or POSIX */
  1062. #ifdef UNIXWAREPOSIX            /* UnixWare 7 POSIX build */
  1063. /*
  1064.   In Unixware POSIX builds, <[sys/]time.h> refuses to define the
  1065.   structs we need to access the higher speeds, so we have to do it
  1066.   ourselves.
  1067. */
  1068. struct timeval {
  1069.     long tv_sec;
  1070.     long tv_usec;
  1071. };
  1072. struct timezone {
  1073.     int tz_minuteswest;
  1074.     int tz_dsttime;
  1075. };
  1076. #endif /* UNIXWAREPOSIX */
  1077. #endif /* SVORPOSIX */
  1078.  
  1079. #ifdef __GNUC__
  1080. #ifdef XENIX
  1081. /*
  1082.   Because Xenix <time.h> doesn't declare time() if we're using gcc.
  1083. */
  1084. time_t time();
  1085. #endif /* XENIX */
  1086. #endif /* __GNUC__ */
  1087.  
  1088. /* Special stuff for V7 input buffer peeking */
  1089.  
  1090. #ifdef  V7
  1091. int kmem[2] = { -1, -1};
  1092. char *initrawq(), *qaddr[2]={0,0};
  1093. #define CON 0
  1094. #define TTY 1
  1095. #endif /* V7 */
  1096.  
  1097. /* dftty is the device name of the default device for file transfer */
  1098. /* dfloc is 0 if dftty is the user's console terminal, 1 if an external line */
  1099.  
  1100. #ifdef BEOS
  1101.     char * dftty = NULL;
  1102.     char * dfmdm = "none";
  1103.     int dfloc = 0;                  /* that goes in local mode by default */
  1104. #else
  1105. #ifndef DFTTY
  1106. #ifdef PROVX1
  1107.     char *dftty = "/dev/com1.dout"; /* Only example so far of a system */
  1108.     char *dfmdm = "none";
  1109.     int dfloc = 1;                  /* that goes in local mode by default */
  1110. #else
  1111.     char *dftty = CTTNAM;               /* Remote by default, use normal */
  1112.     char *dfmdm = "none";
  1113.     int dfloc = 0;                      /* controlling terminal name. */
  1114. #endif /* PROVX1 */
  1115. #else
  1116.     char *dftty = DFTTY;        /* Default location specified on */
  1117.     char *dfmdm = "none";        /* command line. */
  1118.     int dfloc = 1;                      /* controlling terminal name. */
  1119. #endif /* DFTTY */
  1120. #endif /* BEOS */
  1121.  
  1122. #define CON_RES 0            /* Console state is "reset" */
  1123. #define CON_CB  1            /* Console state is CBREAK */
  1124. #define CON_BIN 2            /* Console state is binary */
  1125.     static int constate = CON_RES;
  1126.  
  1127. #define CONI_RES 0            /* Console interrupts are "reset" */
  1128. #define CONI_INT 1            /* Console intterupts are set */
  1129. #define CONI_NOI 2            /* Console intterupts are disabled */
  1130.     static int conistate = CONI_RES;
  1131.  
  1132. #ifdef CK_SMALL
  1133. #define CONBUFSIZ 15
  1134. #else
  1135. #define CONBUFSIZ 255
  1136. #endif /* CK_SMALL */
  1137.     static char conbuf[CONBUFSIZ];    /* Console readahead buffer */
  1138.     static int  conbufn = 0;        /* Chars in readahead buffer */
  1139.     static char *conbufp = conbuf;    /* Next char in readahead buffer */
  1140.  
  1141.     char cttnam[DEVNAMLEN+1] = { '\0', '\0' }; /* Determined at runtime */
  1142.  
  1143. #ifdef RTU
  1144.     int rtu_bug = 0;            /* set to 1 when returning from SIGTSTP */
  1145. #endif /* RTU */
  1146.  
  1147.     int dfprty = DEFPAR;                /* Default parity (0 = none) */
  1148.     int ttprty = 0;                     /* The parity that is in use. */
  1149.     static int ttpmsk = 0xff;        /* Parity stripping mask. */
  1150.     int ttmdm = 0;                      /* Modem in use. */
  1151.     int ttcarr = CAR_AUT;        /* Carrier handling mode. */
  1152.     int dfflow = FLO_NONE;        /* Default flow control is NONE */
  1153.     int backgrd = 0;                    /* Assume in foreground (no '&' ) */
  1154. #ifdef F_SETFL
  1155.     int iniflags = -1;            /* fcntl flags for ttyfd */
  1156. #endif /* F_SETFL */
  1157.     int fdflag = 0;            /* Flag for redirected stdio */
  1158.     int ttfdflg = 0;            /* Open File descriptor was given */
  1159.     int tvtflg = 0;            /* Flag that ttvt has been called */
  1160.     long ttspeed = -1L;            /* For saving speed */
  1161.     int ttflow = -9;            /* For saving flow */
  1162.     int ttld = -1;            /* Line discipline */
  1163.  
  1164. #ifdef sony_news
  1165.     static int km_con = -1;        /* Kanji mode for console tty */
  1166.     static int km_ext = -1;        /* Kanji mode for external device */
  1167. #endif /* sony_news */
  1168.  
  1169. #ifdef PARSENSE
  1170.     static int needpchk = 1;        /* Need parity check */
  1171. #else
  1172.     static int needpchk = 0;
  1173. #endif /* PARSENSE */
  1174.  
  1175.     extern int stopbits;        /* Stop bits */
  1176. #ifdef HWPARITY
  1177. /*
  1178.   Unfortunately we must do this with global variables rather than through the
  1179.   tt...() APIs to avoid changing the APIs and the many modules that use them.
  1180.   If hwparity != 0, this indicates 8 data bits + parity, rather than 7 data
  1181.   bits + parity or 8 data bits and no parity, and overrides the regular parity
  1182.   variable, which is communicated to this module thru ttpkt(), and represented
  1183.   locally by the ttprty variable.
  1184. */
  1185.     extern int hwparity;        /* Hardware parity */
  1186. #endif /* HWPARITY */
  1187.  
  1188. #ifdef TCPSOCKET
  1189. #ifdef TCP_NODELAY
  1190. static int nodelay_sav = -1;
  1191. #endif /* TCP_NODELAY */
  1192. #endif /* TCPSOCKET */
  1193.  
  1194. static int sigint_ign = 0;        /* SIGINT is ignored */
  1195.  
  1196. /*
  1197.   Having this module rely on external globals is bad, but fixing this
  1198.   requires overhaul of the ck*tio.c modules for all the different operating
  1199.   systems supported by C-Kermit.  Left for a future release.
  1200. */
  1201. extern int ttnproto;            /* Defined in ckcnet.c */
  1202. extern int ttnet;            /* Defined in ckcnet.c */
  1203. extern int nopush, xfrcan, xfrchr, xfrnum; /* Defined in ckcmai.c */
  1204. extern int xsuspend, wasclosed;
  1205. extern int inserver, local;
  1206.  
  1207. int ckxech = 0; /* 0 if system normally echoes console characters, else 1 */
  1208.  
  1209. int ckmaxfiles = 0;            /* Max number of open files */
  1210.  
  1211. #ifdef CK_ENCRYPTION            /* Kerberos */
  1212. #include "ckuath.h"
  1213. extern int me_encrypt, u_encrypt;
  1214. #endif /* CK_ENCRYPTION */
  1215.  
  1216. /* Declarations of variables global within this module */
  1217.  
  1218. #ifdef TTLEBUF                /* See ckcnet.h */
  1219. int ttpush = -1;
  1220. #define LEBUFSIZ 4096
  1221. static CHAR le_buf[LEBUFSIZ];
  1222. static int le_start = 0, le_end = 0, le_data = 0;
  1223. #endif /* TTLEBUF */
  1224.  
  1225. #define MSGBUF_SIZE 1024        /* For debugging */
  1226. static char msgbuf[MSGBUF_SIZE];
  1227.  
  1228. static int gotsigs = 0;
  1229.  
  1230. static time_t tcount = (time_t)0;    /* Elapsed time counter */
  1231.  
  1232. static SIGTYP (*saval)()     = NULL;    /* For saving alarm() handler */
  1233. static SIGTYP (*savquit)()   = NULL;    /* and other signal handlers */
  1234. #ifdef SIGUSR1
  1235. static SIGTYP (*savusr1)()   = NULL;
  1236. #endif /* SIGUSR1 */
  1237. #ifdef SIGUSR2
  1238. static SIGTYP (*savusr2)()   = NULL;
  1239. #endif /* SIGUSR2 */
  1240. #ifdef SIGPIPE
  1241. static SIGTYP (*savpipe)()   = NULL;
  1242. #endif /* SIGPIPE */
  1243. #ifdef SIGDANGER
  1244. static SIGTYP (*savdanger)() = NULL;
  1245. #endif /* SIGDANGER */
  1246.  
  1247. #ifndef NOJC
  1248. static SIGTYP (*jchdlr)()    = NULL;    /* For checking suspend handler */
  1249. #endif /* NOJC */
  1250. static int jcshell = -1;        /* And flag for result */
  1251.  
  1252. /*
  1253.   BREAKNULS is defined for systems that simulate sending a BREAK signal
  1254.   by sending a bunch of NUL characters at low speed.
  1255. */
  1256. #ifdef PROVX1
  1257. #ifndef BREAKNULS
  1258. #define BREAKNULS
  1259. #endif /* BREAKNULS */
  1260. #endif /* PROVX1 */
  1261.  
  1262. #ifdef V7
  1263. #ifndef BREAKNULS
  1264. #define BREAKNULS
  1265. #endif /* BREAKNULS */
  1266. #endif /* V7 */
  1267.  
  1268. #ifdef BREAKNULS
  1269. static char                /* A string of nulls */
  1270. *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";
  1271. #endif /* BREAKNULS */
  1272.  
  1273. #ifdef CK_POSIX_SIG            /* Longjump buffers */
  1274. static sigjmp_buf sjbuf;        /* POSIX signal handling */
  1275. #else
  1276. static jmp_buf sjbuf;
  1277. #endif /* CK_POSIX_SIG */
  1278.  
  1279. #ifdef V7
  1280. static jmp_buf jjbuf;
  1281. #endif /* V7 */
  1282.  
  1283. /* static */                /* (Not static any more) */
  1284. int ttyfd = -1;                /* TTY file descriptor */
  1285.  
  1286. int ttpipe = 0;                /* NETCMD: Use pipe instead of ttyfd */
  1287. int ttpty  = 0;                         /* NETPTY: Use pty instead of ttfyd */
  1288.  
  1289. #ifdef NETPTY                /* These are in ckupty.c */
  1290. extern PID_T pty_fork_pid;
  1291. extern int pty_master_fd, pty_slave_fd;
  1292. #endif    /* NETPTY */
  1293.  
  1294. #ifdef NETCMD
  1295. #ifdef NETCONN
  1296. static int pipe0[2], pipe1[2];        /* Pipes for net i/o */
  1297. #endif /* NETCONN */
  1298. static PID_T ttpid = 0;            /* Process ID for fork */
  1299. static int fdin, fdout;            /* File descriptors for pipe */
  1300. static FILE * ttout = NULL;        /* File pointer for output pipe */
  1301. #ifdef DCLFDOPEN
  1302. /* fdopen() needs declaring because it's not declared in <stdio.h> */
  1303. _PROTOTYP( FILE * fdopen, (int, char *) );
  1304. #endif /* DCLFDOPEN */
  1305. #endif /* NETCMD */
  1306.  
  1307. extern int pexitstat, quiet;
  1308.  
  1309. #ifdef Plan9
  1310. int ttyctlfd  = -1;   /* TTY control channel - What? UNIX doesn't have one? */
  1311. int consctlfd = -1;            /* Console control channel */
  1312. int noisefd = -1;            /* tone channel */
  1313. static int ttylastspeed = -1;        /* So we can lie about the speed */
  1314. #endif /* Plan9 */
  1315.  
  1316. int telnetfd = 0;            /* File descriptor is for telnet */
  1317. #ifdef NETCONN
  1318. int x25fd = 0;                /* File descriptor is for X.25 */
  1319. #endif /* NETCONN */
  1320.  
  1321. char lockpid[16] = { '\0', '\0' };    /* PID stored in lockfile, as string */
  1322.  
  1323. static int lkf = 0,                     /* Line lock flag */
  1324.     cgmf = 0,                           /* Flag that console modes saved */
  1325.     xlocal = 0,                         /* Flag for tty local or remote */
  1326.     curcarr = 0;            /* Carrier mode: require/ignore. */
  1327.  
  1328. static int netconn = 0;            /* 1 if network connection active */
  1329.  
  1330. static char escchr;                     /* Escape or attn character */
  1331.  
  1332. #ifdef CK_SCO32V4
  1333. #include <sys/time.h>
  1334. #endif /* CK_SCO32V4 */
  1335.  
  1336. #ifdef HAVE_TV
  1337.     static struct timeval tv;        /* For getting time, from sys/time.h */
  1338. #endif /* HAVE_TV */
  1339. #ifdef HAVE_TZ
  1340.     static struct timezone tz;
  1341. #endif /* HAVE_TZ */
  1342.  
  1343. #ifdef OSF
  1344.     static struct timeb ftp;            /* And from sys/timeb.h */
  1345. #endif /* OSF */
  1346.  
  1347. #ifdef BSD29
  1348.     static long xclock;            /* For getting time from sys/time.h */
  1349.     static struct timeb ftp;            /* And from sys/timeb.h */
  1350. #endif /* BSD29 */
  1351.  
  1352. #ifdef BSD41
  1353.     static long xclock;            /* For getting time from sys/time.h */
  1354.     static struct timeb ftp;            /* And from sys/timeb.h */
  1355. #endif /* BSD41 */
  1356.  
  1357. #ifdef BELLV10
  1358.     static long xclock;            /* For getting time from sys/time.h */
  1359.     static struct timeb ftp;            /* And from sys/timeb.h */
  1360. #endif /* BELLV10 */
  1361.  
  1362. #ifdef FT21
  1363.     static long xclock;            /* For getting time from sys/time.h */
  1364.     static struct timeb ftp;            /* And from sys/timeb.h */
  1365. #endif /* FT21 */
  1366.  
  1367. #ifdef TOWER1
  1368.     static long xclock;            /* For getting time from sys/time.h */
  1369.     static struct timeb ftp;        /* And from sys/timeb.h */
  1370. #endif /* TOWER1 */
  1371.  
  1372. #ifdef COHERENT
  1373.     static long xclock;            /* For getting time from sys/time.h */
  1374.     static struct timeb ftp;        /* And from sys/timeb.h */
  1375. #endif /* COHERENT */
  1376.  
  1377. #ifdef V7
  1378.     static long xclock;
  1379. #endif /* V7 */
  1380.  
  1381. /* sgtty/termio information... */
  1382.  
  1383. #ifdef BSD44ORPOSIX            /* POSIX or BSD44 */
  1384.   static struct termios
  1385.     ttold, ttraw, tttvt, ttcur,
  1386.     ccold, ccraw, cccbrk;
  1387. #else                    /* BSD, V7, etc */
  1388.  
  1389. #ifdef COHERENT                /* Hack alert... */
  1390. #define ATTSV
  1391. #endif /* COHERENT */
  1392.  
  1393. #ifdef ATTSV
  1394.   static struct termio ttold = {0};    /* Init'd for word alignment, */
  1395.   static struct termio ttraw = {0};    /* which is important for some */
  1396.   static struct termio tttvt = {0};    /* systems, like Zilog... */
  1397.   static struct termio ttcur = {0};
  1398.   static struct termio ccold = {0};
  1399.   static struct termio ccraw = {0};
  1400.   static struct termio cccbrk = {0};
  1401. #else
  1402.   static struct sgttyb                  /* sgtty info... */
  1403.     ttold, ttraw, tttvt, ttcur,     /* for communication line */
  1404.     ccold, ccraw, cccbrk;        /* and for console */
  1405. #ifdef BELLV10
  1406.   static struct ttydevb            /* Device info... */
  1407.     tdold, tdcur;            /* for communication device */
  1408. #endif /* BELLV10 */
  1409. #ifdef TIOCGETC
  1410.   static struct tchars tchold, tchnoi;
  1411.  
  1412.   static int tcharf;
  1413. #endif /* TIOCGETC */
  1414. #ifdef TIOCGLTC
  1415.   static struct ltchars ltchold, ltchnoi;
  1416.   static int ltcharf;
  1417. #endif /* TIOCGLTC */
  1418.   int lmodef = 0;            /* Local modes */
  1419.   int lmode = 0;
  1420. #endif /* ATTSV */
  1421. #endif /* BSD44ORPOSIX */
  1422.  
  1423. #ifdef COMMENT
  1424. /* It picks up the speeds but they don't work */
  1425. #ifdef UNIXWARE                /* For higher serial speeds */
  1426. #ifdef UW7                /* in Unixware 7.0 */
  1427. #include <sys/asyc.h>            /* This picks up 57600 and 115200 */
  1428. #endif /* UW7 */
  1429. #endif /* UNIXWARE */
  1430. #endif /* COMMENT */
  1431.  
  1432. #ifdef PROVX1
  1433.   static struct sgttyb ttbuf;
  1434. #endif /* PROVX1 */
  1435.  
  1436. #ifdef ultrix
  1437. /* do we really need this? */
  1438.   static struct sgttyb vanilla;
  1439. #endif /* ultrix */
  1440.  
  1441. #ifdef ATT7300
  1442. static int attmodem = 0;                /* ATT7300 internal-modem status */
  1443. struct updata dialer = {0};        /* Condition dialer for data call */
  1444. #endif /* ATT7300 */
  1445.  
  1446. #ifndef NOUUCP
  1447. #define FLFNAML 128
  1448. #ifndef USETTYLOCK
  1449. #ifdef RTAIX
  1450. char lkflfn[FLFNAML] = { '\0', '\0' };    /* and possible link to it */
  1451. #endif /* RTAIX */
  1452. char lock2[FLFNAML] =  { '\0', '\0' };    /* Name of second lockfile */
  1453. #endif /* USETTYLOCK */
  1454. #else
  1455. #define FLFNAML 7
  1456. #endif /* NOUUCP */
  1457. char flfnam[FLFNAML+1] = { '\0', '\0' }; /* UUCP lock file path name */
  1458.  
  1459. int haslock = 0;            /* =1 if this kermit locked uucp */
  1460.  
  1461. #ifndef OXOS
  1462. #ifdef SVORPOSIX
  1463. static int conesc = 0;                  /* set to 1 if esc char (^\) typed */
  1464. #else
  1465. #ifdef V7
  1466. static int conesc = 0;
  1467. #else
  1468. #ifdef C70
  1469. static int conesc = 0;
  1470. #endif /* C70 */
  1471. #endif /* V7 */
  1472. #endif /* SVORPOSIX */
  1473. #endif /* OXOS */
  1474.  
  1475. /* Local copy of comm device name or network host */
  1476. static char ttnmsv[DEVNAMLEN+1] = { '\0', '\0' };
  1477. #ifdef USETTYLOCK
  1478. static char lockname[DEVNAMLEN+1];    /* Ditto, the part after "/dev/". */
  1479. #endif /* USETTYLOCK */
  1480.  
  1481. #ifdef aegis
  1482. static status_$t st;                    /* error status return value */
  1483. static short concrp = 0;                /* true if console is CRP pad */
  1484. static uid_$t ttyuid;                   /* tty type uid */
  1485. static uid_$t conuid;                   /* stdout type uid */
  1486.  
  1487. /* APOLLO Aegis main()
  1488.  * establish acl usage and cleanup handling
  1489.  *    this makes sure that CRP pads
  1490.  *    get restored to a usable mode
  1491.  */
  1492. main(argc,argv) int argc; char **argv; {
  1493.         status_$t status;
  1494.         pfm_$cleanup_rec dirty;
  1495.  
  1496.         PID_T pid = getpid();
  1497.  
  1498.         /* acl usage according to invoking environment */
  1499.         default_acl(USE_DEFENV);
  1500.  
  1501.         /* establish a cleanup continuation */
  1502.         status = pfm_$cleanup(dirty);
  1503.         if (status.all != pfm_$cleanup_set) {
  1504.                 /* only handle faults for the original process */
  1505.                 if (pid == getpid() && status.all > pgm_$max_severity) {
  1506.             /* blew up in main process */
  1507.             status_$t quo;
  1508.             pfm_$cleanup_rec clean;
  1509.  
  1510.             /* restore the console in any case */
  1511.             conres();
  1512.  
  1513.             /* attempt a clean exit */
  1514.             debug(F101, "cleanup fault status", "", status.all);
  1515.  
  1516.             /* doexit(), then send status to continuation */
  1517.             quo = pfm_$cleanup(clean);
  1518.             if (quo.all == pfm_$cleanup_set)
  1519.               doexit(pgm_$program_faulted,-1);
  1520.             else if (quo.all > pgm_$max_severity)
  1521.               pfm_$signal(quo); /* blew up in doexit() */
  1522.                 }
  1523.                 /* send to the original continuation */
  1524.                 pfm_$signal(status);
  1525.                 /*NOTREACHED*/
  1526.         }
  1527.         return(ckcmai(argc, argv));
  1528. }
  1529. #endif /* aegis */
  1530.  
  1531. /* ANSI-style prototypes for internal functions. */
  1532. /* Functions used outside this module are prototyped in ckcker.h. */
  1533.  
  1534. #ifdef apollo
  1535. _PROTOTYP( SIGTYP timerh, () );
  1536. _PROTOTYP( SIGTYP cctrap, () );
  1537. _PROTOTYP( SIGTYP esctrp, () );
  1538. _PROTOTYP( SIGTYP sig_ign, () );
  1539. #else
  1540. _PROTOTYP( SIGTYP timerh, (int) );
  1541. _PROTOTYP( SIGTYP cctrap, (int) );
  1542. _PROTOTYP( SIGTYP esctrp, (int) );
  1543. #endif /* apollo */
  1544. _PROTOTYP( int do_open, (char *) );
  1545. _PROTOTYP( static int in_chk, (int, int) );
  1546. _PROTOTYP( static int ttrpid, (char *) );
  1547. _PROTOTYP( static int ttchkpid, (char *) );
  1548. _PROTOTYP( static int ttlock, (char *) );
  1549. _PROTOTYP( static int ttunlck, (void) );
  1550. _PROTOTYP( static VOID sigchld_handler, (int) );
  1551. _PROTOTYP( int mygetbuf, (void) );
  1552. _PROTOTYP( int myfillbuf, (void) );
  1553. _PROTOTYP( VOID conbgt, (int) );
  1554. #ifdef ACUCNTRL
  1555. _PROTOTYP( VOID acucntrl, (char *, char *) );
  1556. #endif /* ACUCNTRL */
  1557.  
  1558. #ifdef BSD44ORPOSIX
  1559. _PROTOTYP( int carrctl, (struct termios *, int) );
  1560. #else
  1561. #ifdef ATTSV
  1562. _PROTOTYP( int carrctl, (struct termio *, int) );
  1563. #else
  1564. _PROTOTYP( int carrctl, (struct sgttyb *, int) );
  1565. #endif /* ATTSV */
  1566. #endif /* BSD44ORPOSIX */
  1567.  
  1568. #ifdef ATT7300
  1569. _PROTOTYP( int attdial, (char *, long, char *) );
  1570. _PROTOTYP( int offgetty, (char *) );
  1571. _PROTOTYP( int ongetty, (char *) );
  1572. #endif /* ATT7300 */
  1573.  
  1574. #ifdef BEOSORBEBOX
  1575. #ifdef SELECT
  1576.     /* BeOS is not capable of using SELECT on anything but sockets */
  1577. #undef SELECT
  1578. #endif /* SELECT */
  1579. #include <kernel/OS.h>
  1580. /* #ifdef BE_DR_7 */
  1581. static double time_started = 0.0;
  1582. struct ALARM_STRUCT {
  1583.     thread_id thread;
  1584.     int time;
  1585. };
  1586. static thread_id alarm_thread = -1;
  1587. static struct ALARM_STRUCT alarm_struct;
  1588. _PROTOTYP( long do_alarm, (void *) );
  1589. _PROTOTYP( unsigned int alarm, (unsigned int) );
  1590. _PROTOTYP( void alarm_expired, (void) );
  1591. /* #endif */ /* BE_DR_7 */
  1592. #endif /* BEOSORBEBOX */
  1593.  
  1594. #ifndef xunchar
  1595. #define xunchar(ch) (((ch) - 32 ) & 0xFF )    /* Character to number */
  1596. #endif /* xunchar */
  1597.  
  1598. #ifdef CK_ANSIC
  1599. static char *
  1600. xxlast(char *s, char c)
  1601. #else
  1602. static char *
  1603. xxlast(s,c) char *s; char c;
  1604. #endif /* CK_ANSIC */
  1605. /* xxlast */ {        /*  Last occurrence of character c in string s. */
  1606.     int i;
  1607.     for (i = (int)strlen(s); i > 0; i--)
  1608.       if (s[i-1] == c ) return(s + (i - 1));
  1609.     return(NULL);
  1610. }
  1611.  
  1612. /* Timeout handler for communication line input functions */
  1613.  
  1614. /*ARGSUSED*/
  1615. SIGTYP
  1616. timerh(foo) int foo; {
  1617.     ttimoff();
  1618. #ifdef BEOSORBEBOX
  1619. /* #ifdef BE_DR_7 */
  1620.     alarm_expired();
  1621. /* #endif */ /* BE_DR_7 */
  1622. #endif /* BEOSORBEBOX */
  1623. #ifdef CK_POSIX_SIG
  1624.     siglongjmp(sjbuf,1);
  1625. #else
  1626.     longjmp(sjbuf,1);
  1627. #endif /* CK_POSIX_SIG */
  1628. }
  1629.  
  1630. /*ARGSUSED*/
  1631. SIGTYP
  1632. xtimerh(foo) int foo; {            /* Like timerh() but does */
  1633. #ifdef BEOSORBEBOX            /* not reset the timer itself */
  1634. /* #ifdef BE_DR_7 */
  1635.     alarm_expired();
  1636. /* #endif */ /* BE_DR_7 */
  1637. #endif /* BEOSORBEBOX */
  1638. #ifdef CK_POSIX_SIG
  1639.     siglongjmp(sjbuf,1);
  1640. #else
  1641.     longjmp(sjbuf,1);
  1642. #endif /* CK_POSIX_SIG */
  1643. }
  1644.  
  1645.  
  1646. /* Control-C trap for communication line input functions */
  1647.  
  1648. int cc_int;                /* Flag */
  1649. SIGTYP (* occt)();            /* For saving old SIGINT handler */
  1650.  
  1651. /*ARGSUSED*/
  1652. SIGTYP
  1653. cctrap(foo) int foo; {            /* Needs arg for ANSI C */
  1654.   cc_int = 1;                /* signal() prototype. */
  1655.   return;
  1656. }
  1657.  
  1658. /*  S Y S I N I T  --  System-dependent program initialization.  */
  1659.  
  1660. /*
  1661.  * ttgwsiz() returns:
  1662.  *    1    tt_rows and tt_cols are known, both altered, both > 0
  1663.  *    0    tt_rows and/or tt_cols are known, both altered, one or both <= 0
  1664.  *    -1   tt_rows and tt_cols are unknown and unaltered
  1665.  */
  1666.  
  1667. extern int tt_rows, tt_cols;
  1668.  
  1669. static int
  1670. xttgwsiz() {
  1671.     char *p;
  1672.     int rows = 0, cols = 0;
  1673.     p = getenv("LINES");
  1674.     debug(F110,"xttgwsiz LINES",p,0);
  1675.     if (p) {
  1676.     rows = atol(p);
  1677.     if (rows > 0) {
  1678.         p = getenv("COLUMNS");
  1679.         debug(F110,"xttgwsiz COLUMNS",p,0);
  1680.         if (p) {
  1681.         cols = atol(p);
  1682.         if (cols > 0) {
  1683.             tt_rows = rows;
  1684.             tt_cols = cols;
  1685.             return(1);
  1686.         }
  1687.         return(0);
  1688.         }
  1689.     }
  1690.     }
  1691.     return(-1);
  1692. }
  1693.  
  1694. #ifdef TTLEBUF
  1695. VOID
  1696. le_init() {                /* LocalEchoInit() */
  1697.     int i;
  1698.     for (i = 0; i < LEBUFSIZ; i++)
  1699.       le_buf[i] = '\0';
  1700.     le_start = 0;
  1701.     le_end = 0;
  1702.     le_data = 0;
  1703. }
  1704.  
  1705. VOID
  1706. le_clean() {                /* LocalEchoCleanup() */
  1707.     le_init();
  1708.     return;
  1709. }
  1710.  
  1711. int
  1712. le_inbuf() {
  1713.     int rc = 0;
  1714.     if (le_start != le_end) {
  1715.     rc = (le_end -
  1716.           le_start +
  1717.           LEBUFSIZ) % LEBUFSIZ;
  1718.     }
  1719.     debug(F111,"le_inbuf","chars waiting",rc);
  1720.     return(rc);
  1721. }
  1722.  
  1723. int
  1724. #ifdef CK_ANSIC
  1725. le_putchar(CHAR ch)
  1726. #else
  1727. le_putchar(ch) CHAR ch;
  1728. #endif /* CK_ANSIC */
  1729. /* le_putchar */ {
  1730. #ifdef COMMENT
  1731.     /* In UNIX we do not have another thread taking chars out of the buffer */
  1732.     while ((le_start - le_end == 1) ||
  1733.             (le_start == 0 && le_end == LEBUFSIZ - 1)) {
  1734.     /* Buffer is full */
  1735.         debug(F111,"le_putchar","Buffer is Full",ch);
  1736.         ReleaseLocalEchoMutex() ;
  1737.         msleep(250);
  1738.         RequestLocalEchoMutex( SEM_INDEFINITE_WAIT ) ;
  1739.     }
  1740. #else
  1741.     if ((le_start - le_end + LEBUFSIZ)%LEBUFSIZ == 1) {
  1742.         debug(F110,"le_putchar","buffer is full",0);
  1743.         return(-1);
  1744.     }
  1745. #endif /* COMMENT */
  1746.     le_buf[le_end++] = ch;
  1747.     if (le_end == LEBUFSIZ)
  1748.       le_end = 0;
  1749.     le_data = 1;
  1750.     return(0);
  1751. }
  1752.  
  1753. int
  1754. #ifdef CK_ANSIC
  1755. le_puts(CHAR * s, int n)
  1756. #else
  1757. le_puts(s,n) CHAR * s; int n;
  1758. #endif /* CK_ANSIC */
  1759. /* le_puts */ {
  1760.     int rc = 0;
  1761.     int i = 0;
  1762.     CHAR * p = (CHAR *)"le_puts";
  1763.     ckhexdump(p,s,n);
  1764.     for (i = 0; i < n; i++)
  1765.       rc = le_putchar((char)s[i]);
  1766.     debug(F101,"le_puts","",rc);
  1767.     return(rc);
  1768. }
  1769.  
  1770. int
  1771. #ifdef CK_ANSIC
  1772. le_putstr(CHAR * s)
  1773. #else
  1774. le_putstr(s) CHAR * s;
  1775. #endif /* CK_ANSIC */
  1776. /* le_puts */ {
  1777.     CHAR * p;
  1778.     int rc = 0;
  1779.     p = (CHAR *)"le_putstr";
  1780.     ckhexdump(p,s,(int)strlen((char *)s));
  1781.     for (p = s; *p && !rc; p++)
  1782.       rc = le_putchar(*p);
  1783.     return(rc);
  1784. }
  1785.  
  1786. int
  1787. #ifdef CK_ANSIC
  1788. le_getchar(CHAR * pch)
  1789. #else /* CK_ANSIC */
  1790. le_getchar(pch) CHAR * pch;
  1791. #endif /* CK_ANSIC */
  1792. /* le_gatchar */ {
  1793.     int rc = 0;
  1794.     if (le_start != le_end) {
  1795.         *pch = le_buf[le_start];
  1796.         le_buf[le_start] = 0;
  1797.         le_start++;
  1798.  
  1799.         if (le_start == LEBUFSIZ)
  1800.           le_start = 0;
  1801.  
  1802.         if (le_start == le_end) {
  1803.             le_data = 0;
  1804.         }
  1805.         rc++;
  1806.     } else {
  1807.         *pch = 0;
  1808.     }
  1809.     return(rc);
  1810. }
  1811. #endif /* TTLEBUF */
  1812.  
  1813. #ifdef COMMENT
  1814. /*
  1815.   Some systems like OSF/1 use TIOCGSIZE instead of TIOCGWINSZ.
  1816.   But as far as I know, whenever TIOCGSIZE is defined, it is
  1817.   equated to TIOCGWINSZ.  For cases where this is not done, try this:
  1818. */
  1819. #ifndef TIOCGWINSZ
  1820. #ifdef TIOCGSIZE
  1821. #define TIOCGWINSZ TIOCGSIZE
  1822. #endif /* TIOCGSIZE */
  1823. #endif /* TIOCGWINSZ */
  1824. #endif /* COMMENT */
  1825.  
  1826. static int tt_xpixel = 0, tt_ypixel = 0;
  1827.  
  1828. int
  1829. ttgwsiz() {
  1830.     int x = 0;
  1831. #ifndef NONAWS
  1832. #ifdef QNX
  1833. /*
  1834.   NOTE: TIOCGWSIZ works here too, but only in the 32-bit version.
  1835.   This code works for both the 16- and 32-bit versions.
  1836. */
  1837.     extern int dev_size(int, int, int, int *, int *);
  1838.     int r, c;
  1839.  
  1840.     if (dev_size(0, -1, -1, &r, &c) == 0) {
  1841.     debug(F101,"ttgwsiz QNX r","",r);
  1842.     debug(F101,"ttgwsiz QNX c","",c);
  1843.     tt_rows = r;
  1844.     tt_cols = c;
  1845.     return ((r > 0 && c > 0) ? 1 : 0);
  1846.     } else return(xttgwsiz());
  1847. #else /* QNX */
  1848. #ifdef TIOCGWINSZ
  1849.  
  1850. /* Note, this was M_UNIX, changed to XENIX to allow cross compilation... */
  1851. #ifdef XENIX                /* SCO UNIX 3.2v4.0 */
  1852. #include <sys/stream.h>            /* typedef mblk_t needed by ptem.h */
  1853. #include <sys/ptem.h>            /* for ttgwsiz() */
  1854. #endif /* XENIX */
  1855.  
  1856. #ifdef I386IX                /* Ditto for Interactive */
  1857. #include <sys/stream.h>
  1858. #include <sys/ptem.h>
  1859. #endif /* I386IX */
  1860.  
  1861. /* Note, the above might be needed for some other older SVR3 Intel makes... */
  1862.  
  1863.     struct winsize w;
  1864.     tt_xpixel = 0;
  1865.     tt_ypixel = 0;
  1866.  
  1867. #ifdef IKSD
  1868.     if (inserver)
  1869.       return(xttgwsiz());
  1870. #endif /* IKSD */
  1871.     x = ioctl(0, (int)TIOCGWINSZ, (char *)&w);
  1872.     debug(F101,"ttgwsiz TIOCGWINSZ","",x);
  1873.     if (x < 0) {
  1874.     return(xttgwsiz());
  1875.     } else if (w.ws_row > 0 && w.ws_col > 0) {
  1876.     tt_rows = w.ws_row;
  1877.     tt_cols = w.ws_col;
  1878.     tt_xpixel = w.ws_xpixel;
  1879.     tt_ypixel = w.ws_ypixel;
  1880.     debug(F101,"ttgwsiz tt_rows","",tt_rows);
  1881.     debug(F101,"ttgwsiz tt_cols","",tt_cols);
  1882.     return(1);
  1883.     } else {
  1884.     debug(F100,"ttgwsiz TIOCGWINSZ 00","",0);
  1885.     return(xttgwsiz());
  1886.     }
  1887. #else
  1888.     return(xttgwsiz());
  1889. #endif /* TIOCGWINSZ */
  1890. #endif /* QNX */
  1891. #endif /* NONAWS */
  1892. }
  1893.  
  1894.  
  1895. #ifdef RLOGCODE
  1896. _PROTOTYP( int rlog_naws, (void) );
  1897. #endif    /* RLOGCODE */
  1898.  
  1899. #ifndef NOSIGWINCH
  1900. #ifdef SIGWINCH
  1901. SIGTYP
  1902. winchh(foo) int foo; {            /* SIGWINCH handler */
  1903.     int x = 0;
  1904. #ifdef CK_TTYFD
  1905. #ifndef VMS
  1906.     extern int ttyfd;
  1907. #endif /* VMS */
  1908. #endif /* CK_TTYFD */
  1909.     extern int tt_rows, tt_cols, cmd_rows, cmd_cols;
  1910. #ifdef DEBUG
  1911.     if (deblog) {
  1912.     debug(F100,"***************","",0);
  1913.     debug(F100,"SIGWINCH caught","",0);
  1914.     debug(F100,"***************","",0);
  1915. #ifdef NETPTY
  1916.     debug(F101,"SIGWINCH pty_fork_pid","",pty_fork_pid);
  1917. #endif /* NETPTY */
  1918.     }
  1919. #endif /* DEUB */
  1920.     signal(SIGWINCH,winchh);            /* Re-arm the signal */
  1921.     x = ttgwsiz();                      /* Get new window size */
  1922.     cmd_rows = tt_rows;            /* Adjust command screen too */
  1923.     cmd_cols = tt_cols;
  1924.  
  1925. #ifdef CK_TTYFD
  1926.     if                    /* If we don't have a connection */
  1927. #ifdef VMS                /* we're done. */
  1928.       (vmsttyfd() == -1)
  1929. #else
  1930.       (ttyfd == -1)
  1931. #endif /* VMS */
  1932. #else
  1933.       (!local)
  1934. #endif /* CK_TTYFD */
  1935.         return;
  1936.  
  1937. #ifdef NETPTY
  1938.     if (pty_fork_pid > -1) {        /* "set host" to a PTY? */
  1939.     int x;
  1940.  
  1941. #ifdef TIOCSWINSZ
  1942.     struct winsize w;        /* Resize the PTY */
  1943.     errno = 0;
  1944.     w.ws_col = tt_cols;
  1945.     w.ws_row = tt_rows;
  1946.     w.ws_xpixel = tt_xpixel;
  1947.     w.ws_ypixel = tt_ypixel;
  1948.     x = ioctl(ttyfd,TIOCSWINSZ,&w);
  1949.     debug(F101,"winchh TIOCSWINSZ","",x);
  1950.     debug(F101,"winchh TIOCSWINSZ errno","",errno);
  1951. #endif /* TIOCSWINSZ */
  1952.  
  1953.     errno = 0;
  1954.     x = kill(pty_fork_pid,SIGWINCH);
  1955.     debug(F101,"winchh kill","",x);
  1956.     debug(F101,"winchh kill errno","",errno);
  1957.     }
  1958. #endif /* NETPTY */
  1959.  
  1960. /*
  1961.   This should be OK.  It might seem that sending this from
  1962.   interrupt level could interfere with another TELNET IAC string
  1963.   that was in the process of being sent.  But we always send
  1964.   TELNET strings with a single write(), which should prevent mixups.
  1965.   blah_snaws() should protect themselves from being called on the
  1966.   wrong kind of connection.
  1967. */
  1968. #ifdef TCPSOCKET
  1969. #ifndef NOTTGWSIZ
  1970.     if (x > 0 && tt_rows > 0 && tt_cols > 0) {
  1971.         tn_snaws();
  1972. #ifdef RLOGCODE
  1973.         rlog_naws();
  1974. #endif /* RLOGCODE */
  1975.     }
  1976. #endif /* NOTTGWSIZ */
  1977. #endif /* TCPSOCKET */
  1978.     SIGRETURN;
  1979. }
  1980. #endif /* SIGWINCH */
  1981. #endif /* NOSIGWINCH */
  1982.  
  1983. SIGTYP
  1984. sighup(foo) int foo; {            /* SIGHUP handler */
  1985.     backgrd = 1;
  1986.     debug(F100,"***************","",0);
  1987.     debug(F100,"SIGHUP received","",0);
  1988.     debug(F100,"***************","",0);
  1989.     doexit(BAD_EXIT,-1);
  1990.     /*NOTREACHED*/
  1991.     SIGRETURN;                /* Shut picky compilers up... */
  1992. }
  1993.  
  1994. #ifdef CK_SCO32V4
  1995. /* Exists but there is no prototype in the header files */
  1996. _PROTOTYP( char * ttyname, (int) );
  1997. #else
  1998. #ifdef SV68R3V6
  1999. _PROTOTYP( char * ttyname, (int) );
  2000. #else
  2001. #ifdef ultrix
  2002. _PROTOTYP( char * ttyname, (int) );
  2003. #else
  2004. #ifdef HPUX6
  2005. _PROTOTYP( char * ttyname, (int) );
  2006. #else
  2007. #ifdef HPUX5
  2008. _PROTOTYP( char * ttyname, (int) );
  2009. #else
  2010. #ifdef PS2AIX10
  2011. _PROTOTYP( char * ttyname, (int) );
  2012. #else
  2013. #ifdef BSD42
  2014. _PROTOTYP( char * ttyname, (int) );
  2015. #endif /* BSD42 */
  2016. #endif /* PS2AIX10 */
  2017. #endif /* HPUX5 */
  2018. #endif /* HPUX6 */
  2019. #endif /* ultrix */
  2020. #endif /* SV68R3V6 */
  2021. #endif /* CK_SCO32V4 */
  2022.  
  2023. #ifndef SIGUSR1                /* User-defined signals */
  2024. #define SIGUSR1 30
  2025. #endif /* SIGUSR1 */
  2026.  
  2027. #ifndef SIGUSR2
  2028. #define SIGUSR2 31
  2029. #endif /* SIGUSR2 */
  2030.  
  2031. /*
  2032.   ignorsigs() sets certain signals to SIG_IGN.  But when a signal is
  2033.   ignored, it remains ignored across exec(), so we have to restore these
  2034.   signals before exec(), which is the purpose of restorsigs().
  2035. */
  2036. static VOID
  2037. ignorsigs() {                /* Ignore these signals */
  2038.     savquit = signal(SIGQUIT,SIG_IGN);    /* Ignore Quit signal */
  2039.  
  2040. #ifdef SIGDANGER            /* Ignore danger signals */
  2041. /*
  2042.   This signal is sent when the system is low on swap space.  Processes
  2043.   that don't handle it are candidates for termination.  If swap space doesn't
  2044.   clear out enough, we still might be terminated via kill() -- nothing we can
  2045.   do about that!  Conceivably, this could be improved by installing a real
  2046.   signal handler that warns the user, but that would be pretty complicated,
  2047.   since we are not always in control of the screen -- e.g. during remote-mode
  2048.   file transfer.
  2049. */
  2050.     savdanger = signal(SIGDANGER,SIG_IGN); /* e.g. in AIX */
  2051. #endif /* SIGDANGER */
  2052. #ifdef SIGPIPE
  2053. /*
  2054.   This one comes when a TCP/IP connection is broken by the remote.
  2055.   We prefer to catch this situation by examining error codes from write().
  2056. */
  2057.     savpipe = signal(SIGPIPE,SIG_IGN);
  2058. #endif /* SIGPIPE */
  2059.     savusr1 = signal(SIGUSR1,SIG_IGN);    /* Ignore user-defined signals */
  2060.     savusr2 = signal(SIGUSR2,SIG_IGN);
  2061. }
  2062.  
  2063. VOID
  2064. restorsigs() {                /* Restore these signals */
  2065.     (VOID) signal(SIGQUIT,savquit);    /* (used in ckufio.c) */
  2066. #ifdef SIGDANGER
  2067.     (VOID) signal(SIGDANGER,savdanger);
  2068. #endif /* SIGDANGER */
  2069. #ifdef SIGPIPE
  2070.     (VOID) signal(SIGPIPE,savpipe);
  2071. #endif /* SIGPIPE */
  2072.     (VOID) signal(SIGUSR1,savusr1);
  2073.     (VOID) signal(SIGUSR2,savusr2);
  2074. }
  2075.  
  2076. int
  2077. sysinit() {
  2078.     int x;
  2079.     char * s;
  2080. #ifdef CK_UTSNAME
  2081.     struct utsname name;
  2082. #endif /* CK_UTSNAME */
  2083.  
  2084.     extern char startupdir[];
  2085. /*
  2086.   BEFORE ANYTHING ELSE: Initialize the setuid package.
  2087.   Change to the user's real user and group ID.
  2088.   If this can't be done, don't run at all.
  2089. */
  2090.     x = priv_ini();
  2091. #ifdef SUIDDEBUG
  2092.     fprintf(stderr,"PRIV_INI=%d\n",x);
  2093. #endif /* SUIDDEBUG */
  2094.     if (x) {
  2095.     if (x & 1) fprintf(stderr,"Fatal: setuid failure.\n");
  2096.     if (x & 2) fprintf(stderr,"Fatal: setgid failure.\n");
  2097.     if (x & 4) fprintf(stderr,"Fatal: C-Kermit setuid to root!\n");
  2098.     exit(1);
  2099.     }
  2100.     signal(SIGINT,SIG_IGN);        /* Ignore interrupts at first */
  2101.     signal(SIGFPE,SIG_IGN);        /* Ignore floating-point exceptions */
  2102.     signal(SIGHUP,sighup);        /* Catch SIGHUP */
  2103. #ifndef NOSIGWINCH
  2104. #ifdef SIGWINCH
  2105.     signal(SIGWINCH,winchh);        /* Catch window-size change */
  2106. #endif /* SIGWINCH */
  2107. #endif /* NOSIGWINCH */
  2108.  
  2109. #ifdef SIGXFSZ
  2110.     signal(SIGXFSZ,SIG_IGN);        /* Ignore writing past file limit */ 
  2111. #endif    /* SIGXFSZ */
  2112.  
  2113. #ifndef NOJC
  2114. /*
  2115.   Get the initial job control state.
  2116.   If it is SIG_IGN, that means the shell does not support job control,
  2117.   and so we'd better not suspend ourselves.
  2118. */
  2119. #ifdef SIGTSTP
  2120.     jchdlr = signal(SIGTSTP,SIG_IGN);
  2121.     if (jchdlr == SIG_IGN) {
  2122.     jcshell = 0;
  2123.     debug(F100,"sysinit jchdlr: SIG_IGN","",0);
  2124.     } else if (jchdlr == SIG_DFL) {
  2125.     debug(F100,"sysinit jchdlr: SIG_DFL","",0);
  2126.     jcshell = 1;
  2127.     } else {
  2128.     debug(F100,"sysinit jchdlr: other","",0);
  2129.     jcshell = 3;
  2130.     }
  2131.     (VOID) signal(SIGTSTP,jchdlr);    /* Put it back... */
  2132. #endif /* SIGTSTP */
  2133. #endif /* NOJC */
  2134.  
  2135.     conbgt(0);                /* See if we're in the background */
  2136.     congm();                /* Get console modes */
  2137.  
  2138.     (VOID) signal(SIGALRM,SIG_IGN);    /* Ignore alarms */
  2139.  
  2140.     ignorsigs();            /* Ignore some other signals */
  2141.  
  2142. #ifdef F_SETFL
  2143.     iniflags = fcntl(0,F_GETFL,0);    /* Get stdin flags */
  2144. #endif /* F_SETFL */
  2145.  
  2146. #ifdef ultrix
  2147.     gtty(0,&vanilla);            /* Get sgtty info */
  2148. #else
  2149. #ifdef AUX
  2150.     set42sig();                /* Don't ask! (hakanson@cs.orst.edu) */
  2151. #endif /* AUX */
  2152. #endif /* ultrix */
  2153. /*
  2154.   Warning: on some UNIX systems (SVR4?), ttyname() reportedly opens /dev but
  2155.   never closes it.  If it is called often enough, we run out of file
  2156.   descriptors and subsequent open()'s of other devices or files can fail.
  2157. */
  2158.     s = NULL;
  2159. #ifndef MINIX
  2160.     if (isatty(0))            /* Name of controlling terminal */
  2161.       s = ttyname(0);
  2162.     else if (isatty(1))
  2163.       s = ttyname(1);
  2164.     else if (isatty(2))
  2165.       s = ttyname(2);
  2166.     debug(F110,"sysinit ttyname(0)",s,0);
  2167. #endif /* MINIX */
  2168.  
  2169. #ifdef BEOS
  2170.     if (!dftty)
  2171.       makestr(&dftty,s);
  2172. #endif /* BEOS */
  2173.  
  2174.     if (s)
  2175.       ckstrncpy((char *)cttnam,s,DEVNAMLEN+1);
  2176. #ifdef SVORPOSIX
  2177.     if (!cttnam[0])
  2178.       ctermid(cttnam);
  2179. #endif /* SVORPOSIX */
  2180.     if (!cttnam[0])
  2181.       ckstrncpy((char *)cttnam,dftty,DEVNAMLEN+1);
  2182.     debug(F110,"sysinit CTTNAM",CTTNAM,0);
  2183.     debug(F110,"sysinit cttnam",cttnam,0);
  2184.  
  2185.     ttgwsiz();                /* Get window (screen) dimensions. */
  2186.  
  2187. #ifndef NOSYSCONF
  2188. #ifdef _SC_OPEN_MAX
  2189.     ckmaxfiles = sysconf(_SC_OPEN_MAX);
  2190. #endif /* _SC_OPEN_MAX */
  2191. #endif /* NOSYSCONF */
  2192.  
  2193. #ifdef Plan9
  2194.     if (!backgrd) {
  2195.         consctlfd = open("/dev/consctl", O_WRONLY);
  2196.         /*noisefd = open("/dev/noise", O_WRONLY)*/
  2197.     }
  2198.     ckxech = 1;
  2199. #endif /* Plan9 */
  2200.  
  2201. #ifdef CK_UTSNAME
  2202.     if (uname(&name) > -1) {
  2203.     ckstrncpy(unm_mch,name.machine,CK_SYSNMLN);
  2204.     ckstrncpy(unm_nam,name.sysname,CK_SYSNMLN);
  2205.     ckstrncpy(unm_rel,name.release,CK_SYSNMLN);
  2206.     ckstrncpy(unm_ver,name.version,CK_SYSNMLN);
  2207. #ifdef DEBUG
  2208.     if (deblog) {
  2209.         debug(F110,"sysinit uname machine",unm_mch,0);
  2210.         debug(F110,"sysinit uname sysname",unm_nam,0);
  2211.         debug(F110,"sysinit uname release",unm_rel,0);
  2212.         debug(F110,"sysinit uname version",unm_ver,0);
  2213.     }
  2214. #endif /* DEBUG */
  2215.  
  2216. #ifdef HPUX9PLUS
  2217.     if (name.machine[5] == '8')
  2218.       hpis800 = 1;
  2219.     else
  2220.       hpis800 = 0;
  2221.     debug(F101,"sysinit hpis800","",hpis800);
  2222. #endif /* HPUX9PLUS */
  2223. #ifdef TRU64
  2224.         getsysinfo(GSI_PLATFORM_NAME, unm_mod, CK_SYSNMLN, 0, 0);
  2225.         debug(F110,"sysinit getsysinfo model",unm_mod,0);
  2226. #endif /* TRU64 */
  2227. #ifdef SOLARIS25
  2228.         sysinfo(SI_PLATFORM, unm_mod, CK_SYSNMLN);
  2229.         debug(F110,"sysinit sysinfo model",unm_mod,0);
  2230. #endif /* SOLARIS25 */
  2231.     }
  2232. #endif /* CK_UTSNAME */
  2233.  
  2234. #ifdef CK_ENVIRONMENT
  2235.     {
  2236. #ifdef TNCODE
  2237.     extern char tn_env_acct[], tn_env_disp[], tn_env_job[],
  2238.     tn_env_prnt[], tn_env_sys[];
  2239. #endif /* TNCODE */
  2240.     extern char uidbuf[];
  2241.         extern char * whoami();
  2242.     char *p;
  2243. #ifdef CKSENDUID
  2244.         uidbuf[0] = '\0';
  2245. #ifdef IKSD
  2246.         if (!inserver) {
  2247. #endif /* IKSD */
  2248.             p = getenv("USER");
  2249.             debug(F110,"sysinit uidbuf from USER",uidbuf,0);
  2250.         if (!p) p = "";
  2251.             if (!*p) {
  2252.                 p = getenv("LOGNAME");
  2253.                 debug(F110,"sysinit uidbuf from LOGNAME",uidbuf,0);
  2254.             }
  2255.         if (!p) p = "";
  2256.             if (!*p) {
  2257.                 p = whoami();
  2258.                 debug(F110,"sysinit uidbuf from whoami()",uidbuf,0);
  2259.             }
  2260.         if (!p) p = "";
  2261.         ckstrncpy(uidbuf, *p ? p : "UNKNOWN", UIDBUFLEN);
  2262. #ifdef IKSD
  2263.         }
  2264. #endif /* IKSD */
  2265.     debug(F110,"sysinit final uidbuf",uidbuf,0);
  2266. #endif /* CKSENDUID */
  2267.  
  2268. #ifdef TNCODE
  2269.     if ((p = getenv("JOB"))) ckstrncpy(tn_env_job,p,63);
  2270.     if ((p = getenv("ACCT"))) ckstrncpy(tn_env_acct,p,63);
  2271.     if ((p = getenv("PRINTER"))) ckstrncpy(tn_env_prnt,p,63);
  2272.     if ((p = getenv("DISPLAY"))) ckstrncpy(tn_env_disp,p,63);
  2273. #ifdef aegis
  2274.     ckstrncpy(tn_env_sys,"Aegis",64);
  2275. #else
  2276. #ifdef Plan9
  2277.     ckstrncpy(tn_env_sys,"Plan9",64);
  2278. #else
  2279.     ckstrncpy(tn_env_sys,"UNIX",64);
  2280. #endif /* Plan9 */
  2281. #endif /* aegis */
  2282. #endif /* TNCODE */
  2283.     }
  2284. #endif /* CK_ENVIRONMENT */
  2285. #ifdef CK_SNDLOC
  2286.     {
  2287.     extern char * tn_loc;
  2288.     char *p;
  2289.     if (p = getenv("LOCATION"))
  2290.       if (tn_loc = (char *)malloc((int)strlen(p)+1))
  2291.         strcpy(tn_loc,p);        /* safe */
  2292.     }
  2293. #endif /* CK_SNDLOC */
  2294.  
  2295.     ckstrncpy(startupdir, zgtdir(), CKMAXPATH);
  2296.     startupdir[CKMAXPATH] = '\0';
  2297.     x = strlen(startupdir);
  2298.     if (x <= 0) {
  2299.     startupdir[0] = '/';
  2300.     startupdir[1] = '\0';
  2301.     } else if (startupdir[x-1] != '/') {
  2302.     startupdir[x] = '/';
  2303.     startupdir[x+1] = '\0';
  2304.     }
  2305.     debug(F110,"sysinit startupdir",startupdir,0);
  2306. #ifdef TTLEBUF
  2307.     le_init();
  2308. #endif /* TTLEBUF */
  2309. #ifdef BSD44ORPOSIX
  2310.     /* This should catch the ncurses platforms */
  2311.     /* Some platforms don't have putenv(), like NeXTSTEP */
  2312.     putenv("NCURSES_NO_SETBUF=1");
  2313. #endif /* BSD44ORPOSIX */
  2314.     return(0);
  2315. }
  2316.  
  2317. /*  S Y S C L E A N U P  --  System-dependent program cleanup.  */
  2318.  
  2319. int
  2320. syscleanup() {
  2321. #ifdef F_SETFL
  2322.     if (iniflags > -1)
  2323.       fcntl(0,F_SETFL,iniflags);    /* Restore stdin flags */
  2324. #endif /* F_SETFL */
  2325. #ifdef ultrix
  2326.     stty(0,&vanilla);                   /* Get sgtty info */
  2327. #endif /* ultrix */
  2328. #ifdef NETCMD
  2329.     if (ttpid) kill(ttpid,9);
  2330. #endif /* NETCMD */
  2331.     return(0);
  2332. }
  2333.  
  2334. /*  T T O P E N  --  Open a tty for exclusive access.  */
  2335.  
  2336. /*
  2337.   Call with:
  2338.     ttname: character string - device name or network host name.
  2339.     lcl:
  2340.   If called with lcl < 0, sets value of lcl as follows:
  2341.   0: the terminal named by ttname is the job's controlling terminal.
  2342.   1: the terminal named by ttname is not the job's controlling terminal.
  2343.   But watch out: if a line is already open, or if requested line can't
  2344.   be opened, then lcl remains (and is returned as) -1.
  2345.     modem:
  2346.   Less than zero: ttname is a network host name.
  2347.   Zero or greater: ttname is a terminal device name.
  2348.   Zero means a local connection (don't use modem signals).
  2349.   Positive means use modem signals.
  2350.    timo:
  2351.   0 = no timer.
  2352.   nonzero = number of seconds to wait for open() to return before timing out.
  2353.  
  2354.   Returns:
  2355.     0 on success
  2356.    -5 if device is in use
  2357.    -4 if access to device is denied
  2358.    -3 if access to lock directory denied
  2359.    -2 upon timeout waiting for device to open
  2360.    -1 on other error
  2361. */
  2362. static int ttotmo = 0;            /* Timeout flag */
  2363. /* Flag kept here to avoid being clobbered by longjmp.  */
  2364.  
  2365. int
  2366. ttopen(ttname,lcl,modem,timo) char *ttname; int *lcl, modem, timo; {
  2367.  
  2368. #ifdef BSD44
  2369. #define ctermid(x) strcpy(x,"")
  2370. #else
  2371. #ifdef SVORPOSIX
  2372. #ifndef CIE
  2373.     extern char *ctermid();        /* Wish they all had this! */
  2374. #else                    /* CIE Regulus */
  2375. #define ctermid(x) strcpy(x,"")
  2376. #endif /* CIE */
  2377. #endif /* SVORPOSIX */
  2378. #endif /* BSD44 */
  2379.  
  2380. #ifdef ultrix
  2381.     int temp = 0;
  2382. #endif /* ultrix */
  2383.  
  2384. #ifndef OPENFIRST
  2385.     char fullname[DEVNAMLEN+1];
  2386. #endif /* OPENFIRST */
  2387.  
  2388.     char * fnam;            /* Full name after expansion */
  2389.  
  2390.     int y;
  2391.  
  2392. #ifndef pdp11
  2393. #define NAMEFD     /* Feature to allow name to be an open file descriptor */
  2394. #endif /* pdp11 */
  2395.  
  2396. #ifdef NAMEFD
  2397.     char *p;
  2398.     debug(F101,"ttopen telnetfd","",telnetfd);
  2399. #endif /* NAMEFD */
  2400.  
  2401.     debug(F110,"ttopen ttname",ttname,0);
  2402.     debug(F110,"ttopen ttnmsv",ttnmsv,0);
  2403.     debug(F101,"ttopen modem","",modem);
  2404.     debug(F101,"ttopen netconn","",netconn);
  2405.     debug(F101,"ttopen ttyfd","",ttyfd);
  2406.     debug(F101,"ttopen *lcl","",*lcl);
  2407.     debug(F101,"ttopen ttmdm","",ttmdm);
  2408.     debug(F101,"ttopen ttnet","",ttnet);
  2409.  
  2410.     ttpmsk = 0xff;
  2411.     lockpid[0] = '\0';
  2412.  
  2413.     if (ttyfd > -1) {            /* If device already opened */
  2414.         if (!strncmp(ttname,ttnmsv,DEVNAMLEN)) /* are new & old names equal? */
  2415.       return(0);            /* Yes, nothing to do - just return */
  2416.     ttnmsv[0] = '\0';        /* No, clear out old name */
  2417.     ttclos(ttyfd);            /* close old connection.  */
  2418.     }
  2419.     wasclosed = 0;            /* New connection, not closed yet. */
  2420.     ttpipe = 0;                /* Assume it's not a pipe */
  2421.     ttpty = 0;                /* or a pty... */
  2422.  
  2423. #ifdef NETCONN
  2424. /*
  2425.   This is a bit tricky...  Suppose that previously Kermit had dialed a telnet
  2426.   modem server ("set host xxx:2001, set modem type usr, dial ...").  Then the
  2427.   connection was closed (ttyfd = -1), and then a REDIAL command was given.  At
  2428.   this point we've obliterated the negative modem type hack, and so would
  2429.   treat the IP hostname as a device name, and would then fail because of "No
  2430.   such device or directory".  But the previous connection has left behind some
  2431.   clues, so let's use them...
  2432. */
  2433.     if (ttyfd < 0) {            /* Connection is not open */
  2434.     if (!strcmp(ttname,ttnmsv)) {    /* Old and new names the same? */
  2435.         if (((netconn > 0) && (ttmdm < 0)) ||
  2436.         ((ttnet > 0) &&
  2437.          (!ckstrchr(ttname,'/')) && (ckstrchr(ttname,':')))
  2438.         ) {
  2439.         int x, rc;
  2440.         x = (ttmdm < 0) ? -ttmdm : ttnet;
  2441.         rc = netopen(ttname, lcl, x);
  2442.         debug(F111,"ttopen REOPEN netopen",ttname,rc);
  2443.         if (rc > -1) {
  2444.             netconn = 1;
  2445.             xlocal = *lcl = 1;
  2446.         } else {
  2447.             netconn = 0;
  2448.         }
  2449.         gotsigs = 0;
  2450.         return(rc);
  2451.         }
  2452.     }
  2453.     }
  2454. #endif /* NETCONN */
  2455.  
  2456. #ifdef MAXNAMLEN
  2457.     debug(F100,"ttopen MAXNAMLEN defined","",0);
  2458. #else
  2459.     debug(F100,"ttopen MAXNAMLEN *NOT* defined","",0);
  2460. #endif
  2461.  
  2462. #ifdef BSD4
  2463.     debug(F100,"ttopen BSD4 defined","",0);
  2464. #else
  2465.     debug(F100,"ttopen BSD4 *NOT* defined","",0);
  2466. #endif /* BSD4 */
  2467.  
  2468. #ifdef BSD42
  2469.     debug(F100,"ttopen BSD42 defined","",0);
  2470. #else
  2471.     debug(F100,"ttopen BSD42 *NOT* defined","",0);
  2472. #endif /* BSD42 */
  2473.  
  2474. #ifdef MYREAD
  2475.     debug(F100,"ttopen MYREAD defined","",0);
  2476. #else
  2477.     debug(F100,"ttopen MYREAD *NOT* defined","",0);
  2478. #endif /* MYREAD */
  2479.  
  2480. #ifdef    NETCONN
  2481.     if (modem < 0) {            /* modem < 0 = code for network */
  2482.     int x;
  2483.     ttmdm = modem;
  2484.     modem = -modem;            /* Positive network type number */
  2485.     fdflag = 0;            /* Stdio not redirected. */
  2486.     netconn = 1;            /* And it's a network connection */
  2487.     debug(F111,"ttopen net",ttname,modem);
  2488. #ifdef NAMEFD
  2489.     for (p = ttname; isdigit(*p); p++) ; /* Check for all digits */
  2490.      if (*p == '\0' && (telnetfd || x25fd)) { /* Avoid X.121 addresses */
  2491.         ttyfd = atoi(ttname);    /* Is there a way to test it's open? */
  2492.         ttfdflg = 1;        /* We got an open file descriptor */
  2493.         debug(F111,"ttopen net ttfdflg",ttname,ttfdflg);
  2494.         debug(F101,"ttopen net ttyfd","",ttyfd);
  2495.         ckstrncpy(ttnmsv,ttname,DEVNAMLEN); /* Remember the "name". */
  2496.         x = 1;            /* Return code is "good". */
  2497.         if (telnetfd) {
  2498.         ttnet = NET_TCPB;
  2499.         if (ttnproto != NP_TCPRAW)
  2500.           ttnproto = NP_TELNET;
  2501. #ifdef SUNX25
  2502.         } else if (x25fd) {
  2503.         ttnet = NET_SX25;
  2504.         ttnproto = NP_NONE;
  2505. #endif /* SUNX25 */
  2506.         }
  2507.     } else {            /* Host name or address given */
  2508. #ifdef NETPTY
  2509.         if (modem == NET_PTY) {
  2510.         int x;
  2511.         if (nopush) {
  2512.             debug(F100,"ttopen PTY: nopush","",0);
  2513.             return(-1);
  2514.         }
  2515.                 ttnet = NET_PTY;
  2516.         ttnproto = NP_NONE;
  2517.                 netconn = 1;            /* but we don't use network i/o */
  2518.                 ttpty = 1;
  2519.                 debug(F110,"ttopen PTY",ttname,0);
  2520.         x = do_pty(&ttyfd,ttname,0);
  2521.         if (x > -1) {
  2522.             ckstrncpy(ttnmsv,ttname,DEVNAMLEN);
  2523.             xlocal = *lcl = 1;    /* It's local */
  2524.         } else {
  2525.             ttpty = 0;
  2526.             netconn = 0;
  2527.         }
  2528.         gotsigs = 0;
  2529.         return(x);
  2530.         }
  2531. #endif /* NETPTY */
  2532. #ifdef NETCMD
  2533. /*
  2534.   dup2() is not available on older System V platforms like AT&T 3Bx.  For
  2535.   those systems we punt by not defining NETCMD, but we might be able to do
  2536.   better -- see workarounds for this problem in ckufio.c (search for dup2).
  2537. */
  2538.         if (modem == NET_CMD) {
  2539.         if (nopush) {
  2540.             debug(F100,"ttopen pipe: nopush","",0);
  2541.             return(-1);
  2542.         }
  2543.         if (pipe(pipe0) || pipe(pipe1)) {
  2544.             perror("Pipe error");
  2545.             return(-1);
  2546.         }
  2547.         ttpid = fork();        /* Make a fork */
  2548.  
  2549.         switch (ttpid) {
  2550.           case -1:        /* Error making fork */
  2551.             close(pipe0[0]);
  2552.             close(pipe0[1]);
  2553.             close(pipe1[0]);
  2554.             close(pipe1[1]);
  2555.             perror("Fork error");
  2556.             return(-1);
  2557.           case 0:        /* Child. */
  2558.             close(pipe0[0]);
  2559.             close(pipe1[1]);
  2560.             dup2(pipe0[1], 1);
  2561.             close(pipe0[1]);
  2562.             dup2(pipe1[0], 0);
  2563.             close(pipe1[0]);
  2564.             system(ttname);
  2565.             _exit(0);
  2566.           default:        /* Parent */
  2567.             close(pipe0[1]);
  2568.             close(pipe1[0]);
  2569.             fdin = pipe0[0];    /* Read from pipe */
  2570.             fdout = pipe1[1];    /* Write to pipe */
  2571.             ttout = fdopen(fdout,"w"); /* Get stream so we can */
  2572.             if (!ttout) {    /* make it unbuffered. */
  2573.             perror("fdopen failure");
  2574.             return(-1);
  2575.             }
  2576.             setbuf(ttout,NULL);
  2577.             ckstrncpy(ttnmsv,ttname,DEVNAMLEN);
  2578.             xlocal = *lcl = 1;    /* It's local */
  2579.             netconn = 1;    /* Call it a network connection */
  2580.             ttmdm = modem;    /* Remember network type */
  2581.             ttyfd = fdin;
  2582.             ttpipe = 1;
  2583.             gotsigs = 0;
  2584.             return(0);
  2585.         }
  2586.         }
  2587. #endif /* NETCMD */
  2588. #endif /* NAMEFD */
  2589.         x = netopen(ttname, lcl, modem); /* (see ckcnet.h) */
  2590.         if (x > -1) {
  2591.         ckstrncpy(ttnmsv,ttname,DEVNAMLEN);
  2592.         } else netconn = 0;
  2593. #ifdef NAMEFD
  2594.     }
  2595. #endif /* NAMEFD */
  2596.  
  2597. #ifdef sony_news            /* Sony NEWS */
  2598.     if (ioctl(ttyfd,TIOCKGET,&km_ext) < 0) { /* Get Kanji mode */
  2599.         perror("ttopen error getting Kanji mode (network)");
  2600.         debug(F111,"ttopen error getting Kanji mode","network",0);
  2601.         km_ext = -1;        /* Make sure this stays undefined. */
  2602.     }
  2603. #endif /* sony_news */
  2604.  
  2605.     xlocal = *lcl = 1;        /* Network connections are local. */
  2606.     debug(F101,"ttopen net x","",x);
  2607. #ifdef COMMENT
  2608. /* Let netopen() do this */
  2609.     if (x > -1 && !x25fd)
  2610.       x = tn_ini();            /* Initialize TELNET protocol */
  2611. #endif /* COMMENT */
  2612.     gotsigs = 0;
  2613.     return(x);
  2614.     } else {                /* Terminal device */
  2615. #endif    /* NETCONN */
  2616.  
  2617. #ifdef NAMEFD
  2618. /*
  2619.   This code lets you give Kermit an open file descriptor for a serial
  2620.   communication device, rather than a device name.  Kermit assumes that the
  2621.   line is already open, locked, conditioned with the right parameters, etc.
  2622. */
  2623.     for (p = ttname; isdigit(*p); p++) ; /* Check for all-digits */
  2624.     if (*p == '\0') {
  2625.         ttyfd = atoi(ttname);    /* Is there a way to test it's open? */
  2626.         debug(F111,"ttopen got open fd",ttname,ttyfd);
  2627.         ckstrncpy(ttnmsv,ttname,DEVNAMLEN); /* Remember the "name". */
  2628.         if (ttyfd >= 0 && ttyfd < 3) /* If it's stdio... */
  2629.           xlocal = *lcl = 0;    /* we're in remote mode */
  2630.         else            /* otherwise */
  2631.           xlocal = *lcl = 1;    /* local mode. */
  2632.         netconn = 0;        /* Assume it's not a network. */
  2633.         tvtflg = 0;            /* Might need to initialize modes. */
  2634.         ttmdm = modem;        /* Remember modem type. */
  2635.         fdflag = 0;            /* Stdio not redirected. */
  2636.         ttfdflg = 1;        /* Flag we were opened this way. */
  2637.         debug(F111,"ttopen non-net ttfdflg",ttname,ttfdflg);
  2638.         debug(F101,"ttopen non-net ttyfd","",ttyfd);
  2639.  
  2640. #ifdef sony_news            /* Sony NEWS */
  2641.         /* Get device Kanji mode */
  2642.         if (ioctl(ttyfd,TIOCKGET,&km_ext) < 0) {
  2643.         perror("ttopen error getting Kanji mode");
  2644.         debug(F101,"ttopen error getting Kanji mode","",0);
  2645.         km_ext = -1;        /* Make sure this stays undefined. */
  2646.         }
  2647. #endif /* sony_news */
  2648.         gotsigs = 0;
  2649.         return(0);            /* Return success */
  2650.     }
  2651. #endif /* NAMEFD */
  2652. #ifdef NETCONN
  2653.     }
  2654. #endif /* NETCONN */
  2655.  
  2656. /* Here we have to open a serial device of the given name. */
  2657.  
  2658.     netconn = 0;            /* So it's not a network connection */
  2659.     occt = signal(SIGINT, cctrap);    /* Set Control-C trap, save old one */
  2660.     sigint_ign = 0;
  2661.  
  2662.     tvtflg = 0;            /* Flag for use by ttvt(). */
  2663.                 /* 0 = ttvt not called yet for this device */
  2664.  
  2665.     fdflag = (!isatty(0) || !isatty(1)); /* Flag for stdio redirected */
  2666.     debug(F101,"ttopen fdflag","",fdflag);
  2667.  
  2668.     ttmdm = modem;                      /* Make this available to other fns */
  2669.     xlocal = *lcl;                      /* Make this available to other fns */
  2670.  
  2671. /* Code for handling bidirectional tty lines goes here. */
  2672. /* Use specified method for turning off logins and suppressing getty. */
  2673.  
  2674. #ifdef ACUCNTRL
  2675.     /* Should put call to priv_on() here, but that would be very risky! */
  2676.     acucntrl("disable",ttname);         /* acucntrl() program. */
  2677.     /* and priv_off() here... */
  2678. #else
  2679. #ifdef ATT7300
  2680.     if ((attmodem & DOGETY) == 0)       /* offgetty() program. */
  2681.       attmodem |= offgetty(ttname);    /* Remember response.  */
  2682. #endif /* ATT7300 */
  2683. #endif /* ACUCNTRL */
  2684.  
  2685. #ifdef OPENFIRST
  2686. /*
  2687.  1985-2001: opens device first then gets lock; reason:
  2688.  Kermit usually has to run setuid or setgid in order to create a lockfile.
  2689.  If you give a SET LINE command for a device that happens to be your job's
  2690.  controlling terminal, Kermit doesn't have to create a lockfile, and in fact
  2691.  should not create one, and would fail if it tried to if it did not have the
  2692.  required privileges.  But you can't find out if two tty device names are
  2693.  equivalent until you have a file descriptor that you can give to ttyname().
  2694.  But this can cause a race condition between Kermit and [m]getty.  So see
  2695.  the [#]else part...
  2696. */ 
  2697.  
  2698. /*
  2699.  In the following section, we open the tty device for read/write.
  2700.  If a modem has been specified via "set modem" prior to "set line"
  2701.  then the O_NDELAY parameter is used in the open, provided this symbol
  2702.  is defined (e.g. in fcntl.h), so that the program does not hang waiting
  2703.  for carrier (which in most cases won't be present because a connection
  2704.  has not been dialed yet).  O_NDELAY is removed later on in ttopen().  It
  2705.  would make more sense to first determine if the line is local before
  2706.  doing this, but because ttyname() requires a file descriptor, we have
  2707.  to open it first.  See do_open().
  2708.  
  2709.  Now open the device using the desired treatment of carrier.
  2710.  If carrier is REQUIRED, then open could hang forever, so an optional
  2711.  timer is provided.  If carrier is not required, the timer should never
  2712.  go off, and should do no harm...
  2713. */
  2714.     ttotmo = 0;                /* Flag no timeout */
  2715.     debug(F101,"ttopen timo","",timo);
  2716.     debug(F101,"ttopen xlocal","",xlocal);
  2717.     if (timo > 0) {
  2718.     int xx;
  2719.     saval = signal(SIGALRM,timerh);    /* Timed, set up timer. */
  2720.     xx = alarm(timo);        /* Timed open() */
  2721.     debug(F101,"ttopen alarm","",xx);
  2722.     if (
  2723. #ifdef CK_POSIX_SIG
  2724.         sigsetjmp(sjbuf,1)
  2725. #else
  2726.         setjmp(sjbuf)
  2727. #endif /* CK_POSIX_SIG */
  2728.         ) {
  2729.         ttotmo = 1;            /* Flag timeout. */
  2730.     } else ttyfd = do_open(ttname);
  2731.     ttimoff();
  2732.     debug(F111,"ttopen","modem",modem);
  2733.     debug(F101,"ttopen ttyfd","",ttyfd);
  2734.     debug(F101,"ttopen alarm return","",ttotmo);
  2735.     } else {
  2736.     errno = 0;
  2737.     ttyfd = do_open(ttname);
  2738.     }
  2739.     debug(F111,"ttopen ttyfd",ttname,ttyfd);
  2740.     if (ttyfd < 0) {            /* If couldn't open, fail. */
  2741.     debug(F101,"ttopen errno","",errno);
  2742.     if (errno > 0 && !quiet)
  2743.       perror(ttname);        /* Print message */
  2744.  
  2745. #ifdef ATT7300
  2746.     if (attmodem & DOGETY)        /* was getty(1m) running before us? */
  2747.       ongetty(ttnmsv);        /* yes, restart on tty line */
  2748.     attmodem &= ~DOGETY;        /* no phone in use, getty restored */
  2749. #else
  2750. #ifdef ACUCNTRL
  2751.         /* Should put call to priv_on() here, but that would be risky! */
  2752.     acucntrl("enable",ttname);    /* acucntrl() program. */
  2753.     /* and priv_off() here... */
  2754. #endif /* ACUNTRL */
  2755. #endif /* ATT7300 */
  2756.  
  2757.     signal(SIGINT,occt);        /* Put old Ctrl-C trap back. */
  2758.     if (errno == EACCES) {        /* Device is protected against user */
  2759.         debug(F110,"ttopen EACCESS",ttname,0); /* Return -4 */
  2760.         return(-4);
  2761.     } else return(ttotmo ? -2 : -1); /* Otherwise -2 if timeout, or -1 */
  2762.     }
  2763.  
  2764. #ifdef QNX
  2765.     {
  2766.     extern int qnxportlock;
  2767.     x = qnxopencount();
  2768.     debug(F101,"ttopen qnxopencount","",x);
  2769.     debug(F101,"ttopen qnxportlock","",qnxportlock);
  2770.     if (x < 0 && qnxportlock) {
  2771.         ttclos(0);
  2772.         printf("?Can't get port open count\n");
  2773.         printf("(Try again with SET QNX-PORT-LOCK OFF)\n");
  2774.         return(-1);            /* Indicate device is in use */
  2775.     }
  2776.     if (x > 1) {            /* 1 == me */
  2777.         if (qnxportlock)
  2778.           ttclos(0);
  2779.           return(-2);        /* Indicate device is in use */
  2780.         else if (!quiet)
  2781.           printf("WARNING: \"%s\" looks busy...\n",ttdev);
  2782.     }
  2783.     }
  2784. #endif /* QNX */
  2785.  
  2786. #ifdef Plan9
  2787.     /* take this opportunity to open the control channel */
  2788.     if (p9openttyctl(ttname) < 0)
  2789. #else
  2790.     /* Make sure it's a real tty. */
  2791.     if (!ttfdflg && !isatty(ttyfd) && strcmp(ttname,"/dev/null"))
  2792. #endif /* Plan9 */
  2793.       {
  2794.     fprintf(stderr,"%s is not a terminal device\n",ttname);
  2795.     debug(F111,"ttopen not a tty",ttname,errno);
  2796.     close(ttyfd);
  2797.     ttyfd = -1;
  2798.     wasclosed = 1;
  2799.     signal(SIGINT,occt);
  2800.     return(-1);
  2801.     }
  2802.  
  2803. #ifdef aegis
  2804.     /* Apollo C runtime claims that console pads are tty devices, which
  2805.      * is reasonable, but they aren't any good for packet transfer. */
  2806.     ios_$inq_type_uid((short)ttyfd, ttyuid, st);
  2807.     if (st.all != status_$ok) {
  2808.         fprintf(stderr, "problem getting tty object type: ");
  2809.         error_$print(st);
  2810.     } else if (ttyuid != sio_$uid) { /* reject non-SIO lines */
  2811.         close(ttyfd); ttyfd = -1;
  2812.         wasclosed = 1;
  2813.         errno = ENOTTY; perror(ttname);
  2814.         signal(SIGINT,occt);
  2815.         return(-1);
  2816.     }
  2817. #endif /* aegis */
  2818.  
  2819.     sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  2820.  
  2821.     ckstrncpy(ttnmsv,ttname,DEVNAMLEN);    /* Keep copy of name locally. */
  2822.  
  2823. /* Caller wants us to figure out if line is controlling tty */
  2824.  
  2825.     if (*lcl < 0) {
  2826.         if (strcmp(ttname,CTTNAM) == 0) { /* "/dev/tty" always remote */
  2827.             xlocal = 0;
  2828.         debug(F111,"ttopen ttname=CTTNAM",ttname,xlocal);
  2829.         } else if (strcmp(ttname,cttnam) == 0) {
  2830.             xlocal = 0;
  2831.         debug(F111,"ttopen ttname=cttnam",ttname,xlocal);
  2832.     } else if (cttnam[0]) {
  2833. #ifdef BEBOX_DR7
  2834.             x = ttnmsv;            /* ttyname() is broken */
  2835. #else
  2836.             x = ttyname(ttyfd);         /* Get real name of ttname. */
  2837. #endif /* BEBOX_DR7 */
  2838.         if (!x) x = "";
  2839.         if (*x)
  2840.           xlocal = ((strncmp(x,cttnam,DEVNAMLEN) == 0) ? 0 : 1);
  2841.         else
  2842.           xlocal = 1;
  2843.             debug(F111,"ttopen ttyname(ttyfd) xlocal",x,xlocal);
  2844.         }
  2845.     }
  2846.  
  2847. #ifndef NOFDZERO
  2848. /* Note, the following code was added so that Unix "idle-line" snoopers */
  2849. /* would not think Kermit was idle when it was transferring files, and */
  2850. /* maybe log people out. */
  2851.     if (xlocal == 0) {            /* Remote mode */
  2852.     if (fdflag == 0) {        /* Standard i/o is not redirected */
  2853.         debug(F100,"ttopen setting ttyfd = 0","",0);
  2854. #ifdef LYNXOS
  2855.         /* On Lynx OS, fd 0 is open for read only. */
  2856.         dup2(ttyfd,0);
  2857. #endif /* LYNXOS */
  2858.         close(ttyfd);        /* Use file descriptor 0 */
  2859.         ttyfd = 0;
  2860.     } else {            /* Standard i/o is redirected */
  2861.         debug(F101,"ttopen stdio redirected","",ttyfd);
  2862.     }
  2863.     }
  2864. #endif /* NOFDZERO */
  2865.  
  2866. /* Now check if line is locked -- if so fail, else lock for ourselves */
  2867. /* Note: After having done this, don't forget to delete the lock if you */
  2868. /* leave ttopen() with an error condition. */
  2869.  
  2870.     lkf = 0;                            /* Check lock */
  2871.     if (xlocal > 0) {
  2872.     int xx; int xpid;
  2873.         if ((xx = ttlock(ttname)) < 0) { /* Can't lock it. */
  2874.             debug(F111,"ttopen ttlock fails",ttname,xx);
  2875.         /* WARNING - This close() can hang if tty is an empty socket... */
  2876.             close(ttyfd);        /* Close the device. */
  2877.         ttyfd = -1;            /* Erase its file descriptor. */
  2878.         wasclosed = 1;
  2879.         signal(SIGINT,occt);    /* Put old SIGINT back. */
  2880.         sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  2881.         if (xx == -2) {        /* If lockfile says device in use, */
  2882. #ifndef NOUUCP
  2883.         debug(F111,"ttopen reading lockfile pid",flfnam,xx);
  2884.         xpid = ttrpid(flfnam);    /* Try to read pid from lockfile */
  2885.         if (xpid > -1) {    /* If we got a pid */
  2886.                     if (!quiet)
  2887.               printf("Locked by process %d\n",xpid); /* tell them. */
  2888.             sprintf(lockpid,"%d",xpid);    /* Record it too */
  2889.             debug(F110,"ttopen lockpid",lockpid,0);
  2890.         } else if (*flfnam) {
  2891.             extern char *DIRCMD;
  2892.             char *p = NULL;
  2893.             int x;
  2894.             x = (int)strlen(flfnam) + (int)strlen(DIRCMD) + 2;
  2895.             p = malloc(x);    /* Print a directory listing. */
  2896. /*
  2897.   Note: priv_on() won't help here, because we do not pass privs along to
  2898.   to inferior processes, in this case ls.  So if the real user does not have
  2899.   directory-listing access to the lockfile directory, this will result in
  2900.   something like "not found".  That's why we try this only as a last resort.
  2901. */
  2902.             if (p) {        /* If we got the space... */
  2903.             ckmakmsg(p,x,DIRCMD," ",flfnam,NULL);
  2904.             zsyscmd(p);    /* Get listing. */
  2905.             if (p) {    /* free the space */
  2906.                 free(p);
  2907.                 p = NULL;
  2908.             }
  2909.             }
  2910.         }
  2911. #endif /* NOUUCP */
  2912.         return(-5);        /* Code for device in use */
  2913.         } else return(-3);        /* Access denied */
  2914.         } else lkf = 1;
  2915.     }
  2916. #else  /* OPENFIRST */
  2917.  
  2918. /*
  2919.   27 Oct 2001: New simpler code that gets the lock first and then opens the
  2920.   device, which eliminates the race condition.  The downside is you can no
  2921.   longer say "set line /dev/ttyp0" or whatever, where /dev/ttyp0 is your login
  2922.   terminal, without trying to create a lockfile, which fails if C-Kermit lacks
  2923.   privs, and if it succeeds, it has created a lockfile where it didn't create
  2924.   one before.
  2925. */
  2926.     xlocal = *lcl;            /* Is the device my login terminal? */
  2927.     debug(F111,"ttopen xlocal","A",xlocal);
  2928.     fnam = ttname;
  2929.     if (strcmp(ttname,CTTNAM) && netconn == 0) {
  2930.     if (zfnqfp(ttname,DEVNAMLEN+1,fullname)) {
  2931.         if ((int)strlen(fullname) > 0)
  2932.           fnam = fullname;
  2933.     }
  2934.     }
  2935.     debug(F110,"ttopen fnam",fnam,0);
  2936.     if (xlocal < 0) {
  2937.     xlocal = (strcmp(fnam,CTTNAM) != 0);
  2938.     }
  2939.     debug(F111,"ttopen xlocal","B",xlocal);
  2940.  
  2941.     lkf = 0;                            /* No lock yet */
  2942.     if (xlocal > 0) {            /* If not... */
  2943.     int xx; int xpid;
  2944.     xx = ttlock(fnam);        /* Try to lock it. */
  2945.     debug(F101,"ttopen ttlock","",xx);
  2946.         if (xx < 0) {            /* Can't lock it. */
  2947.             debug(F111,"ttopen ttlock fails",fnam,xx);
  2948.         if (xx == -2) {        /* If lockfile says device in use, */
  2949. #ifndef NOUUCP
  2950.         debug(F111,"ttopen reading lockfile pid",flfnam,xx);
  2951.         xpid = ttrpid(flfnam);    /* Try to read pid from lockfile */
  2952.         if (xpid > -1) {    /* If we got a pid */
  2953.                     if (!quiet)
  2954.               printf("Locked by process %d\n",xpid); /* tell them. */
  2955.             ckstrncpy(lockpid,ckitoa(xpid),16);
  2956.             debug(F110,"ttopen lockpid",lockpid,0);
  2957. #ifndef NOPUSH
  2958.         } else if (flfnam[0] && !nopush) {
  2959.             extern char *DIRCMD;
  2960.             char *p = NULL;
  2961.             int x;
  2962.             x = (int)strlen(flfnam) + (int)strlen(DIRCMD) + 2;
  2963.             p = malloc(x);    /* Print a directory listing. */
  2964. /*
  2965.   Note: priv_on() won't help here, because we do not pass privs along to
  2966.   to inferior processes, in this case ls.  So if the real user does not have
  2967.   directory-listing access to the lockfile directory, this will result in
  2968.   something like "not found".  That's why we try this only as a last resort.
  2969. */
  2970.             if (p) {        /* If we got the space... */
  2971.             ckmakmsg(p,x,DIRCMD," ",flfnam,NULL);
  2972.             zsyscmd(p);    /* Get listing. */
  2973.             if (p) {    /* free the space */
  2974.                 free(p);
  2975.                 p = NULL;
  2976.             }
  2977.             }
  2978. #endif /* NOPUSH */
  2979.         }
  2980. #endif /* NOUUCP */
  2981.         return(-5);        /* Code for device in use */
  2982.         } else return(-3);        /* Access denied */
  2983.         } else lkf = 1;
  2984.     }
  2985.     /* Have lock -- now it's safe to open the device */
  2986.  
  2987.     debug(F101,"ttopen lkf","",lkf);
  2988.     debug(F101,"ttopen timo","",timo);
  2989.  
  2990.     ttotmo = 0;                /* Flag no timeout */
  2991.     if (timo > 0) {
  2992.     int xx;
  2993.     saval = signal(SIGALRM,timerh);    /* Timed, set up timer. */
  2994.     xx = alarm(timo);        /* Timed open() */
  2995.     debug(F101,"ttopen alarm","",xx);
  2996.     if (
  2997. #ifdef CK_POSIX_SIG
  2998.         sigsetjmp(sjbuf,1)
  2999. #else
  3000.         setjmp(sjbuf)
  3001. #endif /* CK_POSIX_SIG */
  3002.         ) {
  3003.         ttotmo = 1;            /* Flag timeout. */
  3004.     } else {
  3005.         ttyfd = do_open(fnam);
  3006.     }
  3007.     ttimoff();
  3008.     debug(F111,"ttopen timed ttyfd",fnam,ttyfd);
  3009.     } else {
  3010.     errno = 0;
  3011.     ttyfd = do_open(fnam);
  3012.     debug(F111,"ttopen untimed ttyfd",fnam,ttyfd);
  3013.     }
  3014.     if (ttyfd < 0) {            /* If couldn't open, fail. */
  3015.     debug(F111,"ttopen errno",fnam,errno);
  3016.     debug(F111,"ttopen xlocal","C",xlocal);
  3017.     if (xlocal == 0) {
  3018.         debug(F100,"ttopen substituting 0","",0);
  3019.         ttyfd = 0;
  3020.     } else {
  3021.         if (errno > 0 && !quiet) {
  3022.             debug(F111,"ttopen perror",fnam,errno);
  3023.         perror(fnam);        /* Print message */
  3024.         }
  3025.         if (ttunlck())                  /* Release the lock file */
  3026.           fprintf(stderr,"Warning, problem releasing lock\r\n");
  3027.     }
  3028.     }
  3029.  
  3030.     if (ttyfd < 0) {            /* ttyfd is still < 0? */
  3031. #ifdef ATT7300
  3032.     if (attmodem & DOGETY)        /* was getty(1m) running before us? */
  3033.       ongetty(ttnmsv);        /* yes, restart on tty line */
  3034.     attmodem &= ~DOGETY;        /* no phone in use, getty restored */
  3035. #else
  3036. #ifdef ACUCNTRL
  3037.         /* Should put call to priv_on() here, but that would be risky! */
  3038.     acucntrl("enable",fnam);    /* acucntrl() program. */
  3039.     /* and priv_off() here... */
  3040. #endif /* ACUNTRL */
  3041. #endif /* ATT7300 */
  3042.  
  3043.     signal(SIGINT,occt);        /* Put old Ctrl-C trap back. */
  3044.     if (errno == EACCES) {        /* Device is protected against user */
  3045.         debug(F110,"ttopen EACCESS",fnam,0); /* Return -4 */
  3046.         return(-4);
  3047.     } else return(ttotmo ? -2 : -1); /* Otherwise -2 if timeout, or -1 */
  3048.     }
  3049.  
  3050. /* Make sure it's a real tty. */
  3051.  
  3052. #ifdef Plan9
  3053.     /* take this opportunity to open the control channel */
  3054.     if (p9openttyctl(fnam) < 0)       
  3055. #else
  3056.       if (!ttfdflg && !isatty(ttyfd) && strcmp(fnam,"/dev/null"))
  3057. #endif /* Plan9 */
  3058.     {
  3059.         fprintf(stderr,"%s is not a terminal device\n",fnam);
  3060.         debug(F111,"ttopen not a tty",fnam,errno);
  3061.         if (ttunlck())        /* Release the lock file */
  3062.           fprintf(stderr,"Warning, problem releasing lock\r\n");
  3063.         close(ttyfd);
  3064.         ttyfd = -1;
  3065.         wasclosed = 1;
  3066.         signal(SIGINT,occt);
  3067.         return(-1);
  3068.     }
  3069.  
  3070. #ifdef aegis
  3071.     /*
  3072.       Apollo C runtime claims that console pads are tty devices, which
  3073.       is reasonable, but they aren't any good for packet transfer.
  3074.     */
  3075.     ios_$inq_type_uid((short)ttyfd, ttyuid, st);
  3076.     if (st.all != status_$ok) {
  3077.     fprintf(stderr, "problem getting tty object type: ");
  3078.     error_$print(st);
  3079.     } else if (ttyuid != sio_$uid) {    /* Reject non-SIO lines */
  3080.     close(ttyfd); ttyfd = -1;
  3081.     wasclosed = 1;
  3082.     errno = ENOTTY; perror(fnam);
  3083.     signal(SIGINT,occt);
  3084.     return(-1);
  3085.     }
  3086. #endif /* aegis */
  3087.  
  3088.     sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  3089.  
  3090.     ckstrncpy(ttnmsv,ttname,DEVNAMLEN);    /* Keep copy of name locally. */
  3091.  
  3092. /* Caller wants us to figure out if line is controlling tty */
  3093.  
  3094.     if (*lcl < 0) {
  3095.     char * s;
  3096.         if (strcmp(fnam,CTTNAM) == 0) { /* "/dev/tty" always remote */
  3097.             xlocal = 0;
  3098.         debug(F111,"ttopen fnam=CTTNAM",fnam,xlocal);
  3099.         } else if (strcmp(fnam,cttnam) == 0) {
  3100.             xlocal = 0;
  3101.         debug(F111,"ttopen fnam=cttnam",fnam,xlocal);
  3102.     } else if (cttnam[0]) {
  3103. #ifdef BEBOX_DR7
  3104.             s = ttnmsv;            /* ttyname() is broken */
  3105. #else
  3106.             s = ttyname(ttyfd);         /* Get real name of ttname. */
  3107. #endif /* BEBOX_DR7 */
  3108.         if (!s) s = "";
  3109.         if (*s)
  3110.           xlocal = ((strncmp(s,cttnam,DEVNAMLEN) == 0) ? 0 : 1);
  3111.         else
  3112.           xlocal = 1;
  3113.             debug(F111,"ttopen ttyname(ttyfd) xlocal",s,xlocal);
  3114.         }
  3115.     }
  3116.  
  3117. #ifndef NOFDZERO
  3118. /* Note, the following code was added so that Unix "idle-line" snoopers */
  3119. /* would not think Kermit was idle when it was transferring files, and */
  3120. /* maybe log people out. */
  3121.     if (xlocal == 0) {            /* Remote mode */
  3122.     if (fdflag == 0) {        /* Standard i/o is not redirected */
  3123.         debug(F100,"ttopen setting ttyfd = 0","",0);
  3124. #ifdef LYNXOS
  3125.         /* On Lynx OS, fd 0 is open for read only. */
  3126.         dup2(ttyfd,0);
  3127. #endif /* LYNXOS */
  3128.         close(ttyfd);        /* Use file descriptor 0 */
  3129.         ttyfd = 0;
  3130.     } else {            /* Standard i/o is redirected */
  3131.         debug(F101,"ttopen stdio redirected","",ttyfd);
  3132.     }
  3133.     }
  3134. #endif /* NOFDZERO */
  3135. #endif /* OPENFIRST */
  3136.  
  3137. /* Got the line, now set the desired value for local. */
  3138.  
  3139.     if (*lcl != 0) *lcl = xlocal;
  3140.  
  3141. /* Some special stuff for v7... */
  3142.  
  3143. #ifdef  V7
  3144. #ifndef MINIX
  3145.     if (kmem[TTY] < 0) {        /*  If open, then skip this.  */
  3146.     qaddr[TTY] = initrawq(ttyfd);   /* Init the queue. */
  3147.     if ((kmem[TTY] = open("/dev/kmem", 0)) < 0) {
  3148.         fprintf(stderr, "Can't read /dev/kmem in ttopen.\n");
  3149.         perror("/dev/kmem");
  3150.         exit(1);
  3151.     }
  3152.     }
  3153. #endif /* !MINIX */
  3154. #endif /* V7 */
  3155.  
  3156. /* No failure returns after this point */
  3157.  
  3158. #ifdef ultrix
  3159.     ioctl(ttyfd, TIOCMODEM, &temp);
  3160. #ifdef TIOCSINUSE
  3161.     if (xlocal && ioctl(ttyfd, TIOCSINUSE, NULL) < 0) {
  3162.     if (!quiet)
  3163.       perror(fnam);
  3164.     }
  3165. #endif /* TIOCSINUSE */
  3166. #endif /* ultrix */
  3167.  
  3168. /* Get tty device settings  */
  3169.  
  3170. #ifdef BSD44ORPOSIX            /* POSIX */
  3171.     tcgetattr(ttyfd,&ttold);
  3172.     debug(F101,"ttopen tcgetattr ttold.c_lflag","",ttold.c_lflag);
  3173.     tcgetattr(ttyfd,&ttraw);
  3174.     debug(F101,"ttopen tcgetattr ttraw.c_lflag","",ttraw.c_lflag);
  3175.     tcgetattr(ttyfd,&tttvt);
  3176.     debug(F101,"ttopen tcgetattr tttvt.c_lflag","",tttvt.c_lflag);
  3177. #else                    /* BSD, V7, and all others */
  3178. #ifdef ATTSV                /* AT&T UNIX */
  3179.     ioctl(ttyfd,TCGETA,&ttold);
  3180.     debug(F101,"ttopen ioctl TCGETA ttold.c_lflag","",ttold.c_lflag);
  3181.     ioctl(ttyfd,TCGETA,&ttraw);
  3182.     ioctl(ttyfd,TCGETA,&tttvt);
  3183. #else
  3184. #ifdef BELLV10
  3185.     ioctl(ttyfd,TIOCGETP,&ttold);
  3186.     debug(F101,"ttopen BELLV10 ttold.sg_flags","",ttold.sg_flags);
  3187.     ioctl(ttyfd,TIOCGDEV,&tdold);
  3188.     debug(F101,"ttopen BELLV10 tdold.flags","",tdold.flags);
  3189. #else
  3190.     gtty(ttyfd,&ttold);
  3191.     debug(F101,"ttopen gtty ttold.sg_flags","",ttold.sg_flags);
  3192. #endif /* BELLV10 */
  3193.  
  3194. #ifdef sony_news            /* Sony NEWS */
  3195.     if (ioctl(ttyfd,TIOCKGET,&km_ext) < 0) { /* Get console Kanji mode */
  3196.     perror("ttopen error getting Kanji mode");
  3197.     debug(F101,"ttopen error getting Kanji mode","",0);
  3198.     km_ext = -1;            /* Make sure this stays undefined. */
  3199.     }
  3200. #endif /* sony_news */
  3201.  
  3202. #ifdef TIOCGETC
  3203.     debug(F100,"ttopen TIOCGETC","",0);
  3204.     tcharf = 0;                /* In remote mode, also get */
  3205.     if (xlocal == 0) {            /* special characters */
  3206.     if (ioctl(ttyfd,TIOCGETC,&tchold) < 0) {
  3207.         debug(F100,"ttopen TIOCGETC failed","",0);
  3208.     } else {
  3209.         tcharf = 1;            /* It worked. */
  3210.         ioctl(ttyfd,TIOCGETC,&tchnoi); /* Get another copy */
  3211.         debug(F100,"ttopen TIOCGETC ok","",0);
  3212.     }
  3213.     }
  3214. #else
  3215.     debug(F100,"ttopen TIOCGETC not defined","",0);
  3216. #endif /* TIOCGETC */
  3217.  
  3218. #ifdef TIOCGLTC
  3219.     debug(F100,"ttopen TIOCGLTC","",0);
  3220.     ltcharf = 0;            /* In remote mode, also get */
  3221.     if (xlocal == 0) {            /* local special characters */
  3222.     if (ioctl(ttyfd,TIOCGLTC,<chold) < 0) {
  3223.         debug(F100,"ttopen TIOCGLTC failed","",0);
  3224.     } else {
  3225.         ltcharf = 1;        /* It worked. */
  3226.         ioctl(ttyfd,TIOCGLTC,<chnoi); /* Get another copy */
  3227.         debug(F100,"ttopen TIOCGLTC ok","",0);
  3228.     }
  3229.     }
  3230. #else
  3231.     debug(F100,"ttopen TIOCGLTC not defined","",0);
  3232. #endif /* TIOCGLTC */
  3233.  
  3234. #ifdef TIOCLGET
  3235.     debug(F100,"ttopen TIOCLGET","",0);
  3236.     lmodef = 0;
  3237.     if (ioctl(ttyfd,TIOCLGET,&lmode) < 0) {
  3238.     debug(F100,"ttopen TIOCLGET failed","",0);
  3239.     } else {
  3240.     lmodef = 1;
  3241.     debug(F100,"ttopen TIOCLGET ok","",0);
  3242.     }
  3243. #endif /* TIOCLGET */
  3244.  
  3245. #ifdef BELLV10
  3246.     ioctl(ttyfd,TIOCGETP,&ttraw);
  3247.     ioctl(ttyfd,TIOCGETP,&tttvt);
  3248. #else
  3249.     gtty(ttyfd,&ttraw);                 /* And a copy of it for packets*/
  3250.     gtty(ttyfd,&tttvt);                 /* And one for virtual tty service */
  3251. #endif /* BELLV10 */
  3252.  
  3253. #endif /* ATTSV */
  3254. #endif /* BSD44ORPOSIX */
  3255.  
  3256. /* Section for changing line discipline.  It's restored in ttres(). */
  3257.  
  3258. #ifdef AIXRS
  3259. #ifndef AIX41
  3260.     { union txname ld_name; int ld_idx = 0;
  3261.       ttld = 0;
  3262.         do {
  3263.         ld_name.tx_which = ld_idx++;
  3264.         ioctl(ttyfd, TXGETCD, &ld_name);
  3265.       if (!strncmp(ld_name.tx_name, "rts", 3))
  3266.           ttld |= 1;
  3267.         } while (*ld_name.tx_name);
  3268.         debug(F101,"AIX line discipline","",ttld);
  3269.       }
  3270. #endif /* AIX41 */
  3271. #endif /* AIXRS */
  3272.  
  3273. #ifdef BSD41
  3274. /* For 4.1BSD only, force "old" tty driver, new one botches TANDEM. */
  3275.     { int k;
  3276.       ioctl(ttyfd, TIOCGETD, &ttld);    /* Get and save line discipline */
  3277.       debug(F101,"4.1bsd line discipline","",ttld);
  3278.       k = OTTYDISC;            /* Switch to "old" discipline */
  3279.       k = ioctl(ttyfd, TIOCSETD, &k);
  3280.       debug(F101,"4.1bsd tiocsetd","",k);
  3281.     }
  3282. #endif /* BSD41 */
  3283.  
  3284. #ifdef aegis
  3285.     /* This was previously done before the last two TCGETA or gtty above,
  3286.      * in both the ATTSV and not-ATTSV case.  If it is not okay to have only
  3287.      * one copy if it here instead, give us a shout!
  3288.      */
  3289.     sio_$control((short)ttyfd, sio_$raw_nl, false, st);
  3290.     if (xlocal) {       /* ignore breaks from local line */
  3291.         sio_$control((short)ttyfd, sio_$int_enable, false, st);
  3292.         sio_$control((short)ttyfd, sio_$quit_enable, false, st);
  3293.     }
  3294. #endif /* aegis */
  3295.  
  3296. #ifdef VXVE
  3297.     ttraw.c_line = 0;                   /* STTY line 0 for VX/VE */
  3298.     tttvt.c_line = 0;                   /* STTY line 0 for VX/VE */
  3299.     ioctl(ttyfd,TCSETA,&ttraw);
  3300. #endif /* vxve */
  3301.  
  3302. /* If O_NDELAY was used during open(), then remove it now. */
  3303.  
  3304. #ifdef O_NDELAY
  3305.     debug(F100,"ttopen O_NDELAY","",0);
  3306.     if (xlocal > 0) {
  3307.       if (fcntl(ttyfd, F_GETFL, 0) & O_NDELAY) {
  3308.     debug(F100,"ttopen fcntl O_NDELAY","",0);
  3309. #ifndef aegis
  3310.     if (fcntl(ttyfd,F_SETFL, fcntl(ttyfd, F_GETFL, 0) & ~O_NDELAY) < 0) {
  3311.         debug(F100,"ttopen fcntl failure to unset O_NDELAY","",0);
  3312.         perror("Can't unset O_NDELAY");
  3313.     }
  3314. #endif /* aegis */
  3315.     /* Some systems, notably Xenix (don't know how common this is in
  3316.      * other systems), need special treatment to get rid of the O_NDELAY
  3317.      * behaviour on read() with respect to carrier presence (i.e. read()
  3318.      * returning 0 when carrier absent), even though the above fcntl()
  3319.      * is enough to make read() wait for input when carrier is present.
  3320.      * This magic, in turn, requires CLOCAL for working when the carrier
  3321.      * is absent. But if xlocal == 0, presumably you already have CLOCAL
  3322.      * or you have a carrier, otherwise you wouldn't be running this.
  3323.      */
  3324.     debug(F101,"ttopen xlocal","",xlocal);
  3325. #ifdef ATTSV
  3326. #ifdef BSD44ORPOSIX
  3327. #ifdef COMMENT                /* 12 Aug 1997 */
  3328. #ifdef __bsdi__
  3329.     if (xlocal)
  3330.       ttraw.c_cflag |= CLOCAL;
  3331. #else
  3332. #ifdef __FreeBSD__
  3333.     if (xlocal)
  3334.       ttraw.c_cflag |= CLOCAL;
  3335. #endif /* __FreeBSD__ */
  3336. #endif /* __bsdi__ */
  3337. #else /* Not COMMENT */
  3338. #ifdef CLOCAL
  3339.     if (xlocal)            /* Unset this if it's defined. */
  3340.       ttraw.c_cflag |= CLOCAL;
  3341. #endif /* CLOCAL */
  3342. #endif /* COMMENT */
  3343.     debug(F101,"ttopen BSD44ORPOSIX calling tcsetattr","",TCSADRAIN);
  3344.     if (tcsetattr(ttyfd, TCSADRAIN, &ttraw) < 0) {
  3345.         debug(F100,"ttopen POSIX tcseattr fails","",0);
  3346.         perror("tcsetattr");
  3347.     }
  3348. #else /* !BSD44ORPOSIX */
  3349.     if (xlocal) {
  3350.         ttraw.c_cflag |= CLOCAL;
  3351.         debug(F100,"ttopen calling ioctl(TCSETA)","",0);
  3352.         errno = 0;
  3353.         if (ioctl(ttyfd, TCSETA, &ttraw) < 0) {
  3354.                 debug(F101,"ttopen ioctl(TCSETA) fails","",errno);
  3355.                 perror("ioctl(TCSETA)");
  3356.             }
  3357.     }
  3358. #endif /* BSD44ORPOSIX */
  3359. #endif /* ATTSV */
  3360. #ifndef NOCOTFMC /* = NO Close(Open()) To Force Mode Change */
  3361. /* Reportedly lets uugetty grab the device in SCO UNIX 3.2 / XENIX 2.3 */
  3362.     debug(F100,"ttopen executing close/open","",0);
  3363.     close( priv_opn(fnam, O_RDWR) ); /* Magic to force change. */
  3364. #endif /* NOCOTFMC */
  3365.       }
  3366.     }
  3367. #endif /* O_NDELAY */
  3368.  
  3369. /* Instruct the system how to treat the carrier, and set a few other tty
  3370.  * parameters.
  3371.  *
  3372.  * This also undoes the temporary setting of CLOCAL that may have been done
  3373.  * for the close(open()) above (except in Xenix).  Also throw in ~ECHO, to
  3374.  * prevent the other end of the line from sitting there talking to itself,
  3375.  * producing garbage when the user performs a connect.
  3376.  *
  3377.  * SCO Xenix unfortunately seems to ignore the actual state of CLOCAL.
  3378.  * Now it thinks CLOCAL is always on. It seems the only real solution for
  3379.  * Xenix is to switch between the lower and upper case device names.
  3380.  *
  3381.  * This section may at some future time expand into setting a complete
  3382.  * collection of tty parameters, or call a function shared with ttpkt()/
  3383.  * ttvt() that does so.  On the other hand, the initial parameters are not
  3384.  * that important, since ttpkt() or ttvt() should always fix that before
  3385.  * any communication is done.  Well, we'll see...
  3386.  */
  3387.     if (xlocal) {
  3388.         curcarr = -2;
  3389.     debug(F100,"ttopen calling carrctl","",0);
  3390.     carrctl(&ttraw, ttcarr == CAR_ON);
  3391.     debug(F100,"ttopen carrctl ok","",0);
  3392.  
  3393. #ifdef COHERENT
  3394. #define SVORPOSIX
  3395. #endif /* COHERENT */
  3396.  
  3397. #ifdef SVORPOSIX
  3398.     ttraw.c_lflag &= ~ECHO;
  3399.     ttold.c_lflag &= ~ECHO;
  3400. #ifdef BSD44ORPOSIX
  3401.     y = tcsetattr(ttyfd, TCSADRAIN, &ttraw);
  3402.     debug(F101,"ttopen tcsetattr","",y);
  3403. #else
  3404.     y = ioctl(ttyfd, TCSETA, &ttraw);
  3405.     debug(F100,"ttopen ioctl","",y);
  3406. #endif /* BSD44ORPOSIX */
  3407.  
  3408. #else /* BSD, etc */
  3409.     ttraw.sg_flags &= ~ECHO;
  3410.     ttold.sg_flags &= ~ECHO;
  3411. #ifdef BELLV10
  3412.     y = ioctl(ttyfd,TIOCSETP,&ttraw);
  3413.     debug(F100,"ttopen ioctl","",y);
  3414. #else
  3415.     y = stty(ttyfd,&ttraw);
  3416.     debug(F100,"ttopen stty","",y);
  3417. #endif /* BELLV10 */
  3418. #endif /* SVORPOSIX */
  3419.  
  3420. #ifdef COHERENT
  3421. #undef SVORPOSIX
  3422. #endif /* COHERENT */
  3423.  
  3424.     /* ttflui(); */  /*  This fails for some reason.  */
  3425.     }
  3426.  
  3427.     /* Get current speed */
  3428.  
  3429. #ifndef BEBOX
  3430.     ttspeed = ttgspd();
  3431. #else
  3432.     ttspeed = 19200;
  3433. #endif /* !BEBOX */
  3434.     debug(F101,"ttopen ttspeed","",ttspeed);
  3435.  
  3436.     /* Done, make entries in debug log, restore Ctrl-C trap, and return. */
  3437.  
  3438.     debug(F101,"ttopen ttyfd","",ttyfd);
  3439.     debug(F101,"ttopen *lcl","",*lcl);
  3440.     debug(F111,"ttopen lock file",flfnam,lkf);
  3441.     signal(SIGINT,occt);
  3442.     sigint_ign = (occt == SIG_IGN) ? 1 : 0;
  3443.     gotsigs = 0;
  3444.     return(0);
  3445. }
  3446.  
  3447.  
  3448. /*  D O _ O P E N  --  Do the right kind of open() call for the tty. */
  3449.  
  3450. int
  3451. do_open(ttname) char *ttname; {
  3452.     int flags;
  3453.  
  3454. #ifdef QNX6
  3455.     /* O_NONBLOCK on /dev/tty makes open() fail */
  3456.     return(priv_opn(ttname, O_RDWR |
  3457.             (
  3458.              ((int)strcmp(ttname,"/dev/tty") == 0) ?
  3459.              0 :
  3460.              (ttcarr != CAR_ON) ? O_NONBLOCK : 0)
  3461.             )
  3462.        ); 
  3463. #else  /* !QNX6 */
  3464.  
  3465. #ifndef    O_NDELAY            /* O_NDELAY not defined */
  3466.     return(priv_opn(ttname,2));
  3467. #else                    /* O_NDELAY defined */
  3468.  
  3469. #ifdef ATT7300
  3470. /*
  3471.  Open comms line without waiting for carrier so initial call does not hang
  3472.  because state of "modem" is likely unknown at the initial call  -jrd.
  3473.  If this is needed for the getty stuff to work, and the open would not work
  3474.  without O_NDELAY when getty is still on, then this special case is ok.
  3475.  Otherwise, get rid of it. -ske
  3476. */
  3477.     return(priv_opn(ttname, O_RDWR | O_NDELAY));
  3478.  
  3479. #else    /* !ATT7300 */
  3480.  
  3481.     /* Normal case. Use O_NDELAY according to SET CARRIER. See ttscarr(). */
  3482.     flags = O_RDWR;
  3483.     debug(F101,"do_open xlocal","",xlocal);
  3484.     debug(F111,"do_open flags A",ttname,flags);
  3485.     if (xlocal && (ttcarr != CAR_ON))
  3486.       flags |= O_NDELAY;
  3487.     debug(F111,"do_open flags B",ttname,flags);
  3488.     return(priv_opn(ttname, flags));
  3489. #endif /* !ATT7300 */
  3490. #endif /* O_NDELAY */
  3491. #endif /* QNX6 */
  3492. }
  3493.  
  3494. /*  T T C L O S  --  Close the TTY, releasing any lock.  */
  3495.  
  3496. static int ttc_state = 0;        /* ttclose() state */
  3497. static char * ttc_nam[] = { "setup", "hangup", "reset", "close" };
  3498.  
  3499. int
  3500. ttclos(foo) int foo; {            /* Arg req'd for signal() prototype */
  3501.     int xx, x = 0;
  3502.     extern int exithangup;
  3503.  
  3504.     debug(F101,"ttclos ttyfd","",ttyfd);
  3505.     debug(F101,"ttclos netconn","",netconn);
  3506.     debug(F101,"ttclos xlocal","",xlocal);
  3507. #ifdef NOFDZERO
  3508.     debug(F100,"ttclos NOFDZERO","",0);
  3509. #endif /* NOFDZERO */
  3510.  
  3511. #ifdef COMMENT
  3512. #ifdef TTLEBUF
  3513.     le_init();                /* No need for any of this */
  3514. #endif /* TTLEBUF */
  3515. #endif /* COMMENT */
  3516.  
  3517.     if (ttyfd < 0)            /* Wasn't open. */
  3518.       return(0);
  3519.  
  3520.     if (ttfdflg)            /* If we inherited ttyfd from */
  3521.       return(0);            /* another process, don't close it. */
  3522.  
  3523.     tvtflg = 0;                /* (some day get rid of this...) */
  3524.     gotsigs = 0;
  3525.  
  3526. #ifdef IKSD
  3527.     if (inserver) {
  3528. #ifdef TNCODE
  3529.           tn_push();                    /* Place any waiting data into input*/
  3530.           tn_sopt(DO,TELOPT_LOGOUT);    /* Send LOGOUT option before close */
  3531.           TELOPT_UNANSWERED_DO(TELOPT_LOGOUT) = 1;
  3532.           tn_reset();                   /* The Reset Telnet Option table.  */
  3533. #endif /* TNCODE */
  3534. #ifdef CK_SSL
  3535.       if (ssl_active_flag) {
  3536.           if (ssl_debug_flag)
  3537.         BIO_printf(bio_err,"calling SSL_shutdown(ssl)\n");
  3538.           SSL_shutdown(ssl_con);
  3539.           SSL_free(ssl_con);
  3540.           ssl_con = NULL;
  3541.           ssl_active_flag = 0;
  3542.       }
  3543.       if (tls_active_flag) {
  3544.           if (ssl_debug_flag)
  3545.         BIO_printf(bio_err,"calling SSL_shutdown(tls)\n");
  3546.           SSL_shutdown(tls_con);
  3547.           SSL_free(tls_con);
  3548.           tls_con = NULL;
  3549.           tls_active_flag = 0;
  3550.       }
  3551. #endif /* CK_SSL */
  3552.     }
  3553. #endif /* IKSD */
  3554. #ifdef NETCMD
  3555.     if (ttpipe) {            /* We've been using a pipe */
  3556.     /* ttpipe = 0; */
  3557.     if (ttpid > 0) {
  3558.         int wstat;
  3559.         int statusp;
  3560.         close(fdin);        /* Close these. */
  3561.         close(fdout);
  3562.         fdin = fdout = -1;
  3563.         kill(ttpid,1);        /* Kill fork with SIGHUP */
  3564.         while (1) {
  3565.         wstat = wait(&statusp);
  3566.         if (wstat == ttpid || wstat == -1)
  3567.           break;
  3568.         pexitstat = (statusp & 0xff) ? statusp : statusp >> 8;
  3569.         }
  3570.         ttpid = 0;
  3571.     }
  3572.     netconn = 0;
  3573.     wasclosed = 1;
  3574.     ttyfd = -1;
  3575.     return(0);
  3576.     }
  3577. #endif /* NETCMD */
  3578. #ifdef NETPTY
  3579.     if (ttpty) {
  3580. #ifndef NODOPTY
  3581.         end_pty();
  3582. #endif /* NODOPTY */
  3583.         close(ttyfd);
  3584.     netconn = 0;
  3585.     wasclosed = 1;
  3586.         ttpty = 0;
  3587.         ttyfd = -1;
  3588.         return(0);
  3589.     }
  3590. #endif /* NETPTY */
  3591.  
  3592. #ifdef    NETCONN
  3593.     if (netconn) {            /* If it's a network connection. */
  3594.     debug(F100,"ttclos closing net","",0);
  3595.     netclos();            /* Let the network module close it. */
  3596.     netconn = 0;            /* No more network connection. */
  3597.     debug(F101,"ttclos ttyfd after netclos","",ttyfd); /* Should be -1 */
  3598.     return(0);
  3599.     }
  3600. #endif    /* NETCONN */
  3601.  
  3602.     if (xlocal) {            /* We're closing a SET LINE device */
  3603. #ifdef FT21                /* Fortune 2.1-specific items ... */
  3604.     ioctl(ttyfd,TIOCHPCL, NULL);
  3605. #endif /* FT21 */
  3606. #ifdef ultrix                /* Ultrix-specific items ... */
  3607. #ifdef TIOCSINUSE
  3608.     /* Unset the INUSE flag that we set in ttopen() */
  3609.     ioctl(ttyfd, TIOCSINUSE, NULL);
  3610. #endif /* TIOCSINUSE */
  3611.     ioctl(ttyfd, TIOCNMODEM, &x);
  3612. #ifdef COMMENT
  3613.     /* What was this? */
  3614.     ioctl(ttyfd, TIOCNCAR, NULL);
  3615. #endif /* COMMENT */
  3616. #endif /* ultrix */
  3617.     }
  3618.  
  3619.     /* This is to prevent us from sticking in tthang() or close(). */
  3620.  
  3621. #ifdef O_NDELAY
  3622. #ifndef aegis
  3623.     if (ttyfd > 0) {            /* But skip it on stdin. */
  3624.     debug(F100,"ttclos setting O_NDELAY","",0);
  3625.     x = fcntl(ttyfd,F_SETFL,fcntl(ttyfd,F_GETFL, 0)|O_NDELAY);
  3626. #ifdef DEBUG
  3627.     if (deblog && x == -1) {
  3628.         perror("Warning - Can't set O_NDELAY");
  3629.         debug(F101,"ttclos fcntl failure to set O_NDELAY","",x);
  3630.     }
  3631. #endif /* DEBUG */
  3632.     }
  3633. #endif /* aegis */
  3634. #endif /* O_NDELAY */
  3635.  
  3636.     x = 0;
  3637.     ttc_state = 0;
  3638.     if (xlocal
  3639. #ifdef NOFDZERO
  3640.     || ttyfd > 0
  3641. #endif /* NOFDZERO */
  3642.     ) {
  3643.     saval = signal(SIGALRM,xtimerh); /* Enable timer interrupt. */
  3644.     xx = alarm(8);            /* Allow 8 seconds. */
  3645.     debug(F101,"ttclos alarm","",xx);
  3646.     if (
  3647. #ifdef CK_POSIX_SIG
  3648.         sigsetjmp(sjbuf,1)
  3649. #else
  3650.         setjmp(sjbuf)
  3651. #endif /* CK_POSIX_SIG */
  3652.         ) {                /* Timer went off? */
  3653.         x = -1;
  3654. #ifdef DEBUG
  3655.         debug(F111,"ttclos ALARM TRAP errno",ckitoa(ttc_state),errno);
  3656.         printf("ttclos() timeout: %s\n", ttc_nam[ttc_state]);
  3657. #endif /* DEBUG */
  3658.     }
  3659.     /* Hang up the device (drop DTR) */
  3660.  
  3661.     errno = 0;
  3662.     debug(F111,"ttclos A",ckitoa(x),ttc_state);
  3663.     if (ttc_state < 1) {
  3664.         ttc_state = 1;
  3665.         debug(F101,"ttclos exithangup","",exithangup);
  3666.         if (exithangup) {
  3667.         alarm(8);        /* Re-arm the timer */
  3668.         debug(F101,"ttclos calling tthang()","",x);
  3669.         x = tthang();        /* Hang up first, then... */
  3670.         debug(F101,"ttclos tthang()","",x);
  3671.         }
  3672. #ifndef CK_NOHUPCL
  3673. /*
  3674.   Oct 2006 - Leave DTR on if SET EXIT HANGUP OFF.
  3675.   Suggested by Soewono Effendi.
  3676. */
  3677. #ifdef HUPCL
  3678.         else {
  3679.         ttold.c_cflag &= ~HUPCL; /* Let's see how this travels */
  3680. #ifdef BSD44ORPOSIX
  3681.         tcsetattr(ttyfd,TCSANOW,&ttold);
  3682. #else /* !BSD44ORPOSIX */
  3683. #ifdef ATTSV
  3684.         ioctl(ttyfd,TCSETAW,&ttold);        
  3685. #else  /* !ATTSV */
  3686.         stty(ttyfd,&ttold);
  3687. #endif    /* ATTSV */
  3688. #endif    /* BSD44ORPOSIX */
  3689.         }
  3690. #endif    /* HUPCL */
  3691. #endif    /* CK_NOHUPCL */
  3692.     }
  3693.     /* Put back device modes as we found them */
  3694.  
  3695.     errno = 0;
  3696.     debug(F111,"ttclos B",ckitoa(x),ttc_state);
  3697.     if (ttc_state < 2) {
  3698.         ttc_state = 2;
  3699.         /* Don't try to mess with tty modes if tthang failed() */
  3700.         /* since it probably won't work. */
  3701.         if (x > -1) {
  3702.         debug(F101,"ttclos calling ttres()","",x);
  3703.         signal(SIGALRM,xtimerh); /* Re-enable the alarm. */
  3704.         alarm(8);        /* Re-arm the timer */
  3705.         x = ttres();        /* Reset device modes. */
  3706.         debug(F101,"ttclos ttres()","",x);
  3707.         alarm(0);
  3708.         }
  3709.     }
  3710.     /* Close the device */
  3711.  
  3712.     errno = 0;
  3713.     debug(F101,"ttclos C","",ttc_state);
  3714.     if (ttc_state < 3) {
  3715.         ttc_state = 3;
  3716.         errno = 0;
  3717.         debug(F101,"ttclos calling close","",x);
  3718.         signal(SIGALRM,xtimerh);    /* Re-enable alarm. */
  3719.         alarm(8);            /* Re-arm the timer */
  3720.         x = close(ttyfd);        /* Close the device. */
  3721.         debug(F101,"ttclos close()","",x);
  3722.         if (x > -1)
  3723.           ttc_state = 3;
  3724.     }
  3725.     debug(F101,"ttclos D","",ttc_state);
  3726.     ttimoff();            /* Turn off timer. */
  3727.     if (x < 0) {
  3728.         printf("?WARNING - close failed: %s\n",ttnmsv);
  3729. #ifdef DEBUG
  3730.         if (deblog) {
  3731.         printf("errno = %d\n", errno);
  3732.         debug(F101,"ttclos failed","",errno);
  3733.         }
  3734. #endif /* DEBUG */
  3735.     }
  3736.     /* Unlock after closing but before any getty mumbo jumbo */
  3737.  
  3738.     debug(F100,"ttclos about to call ttunlck","",0);
  3739.         if (ttunlck())                  /* Release uucp-style lock */
  3740.       fprintf(stderr,"Warning, problem releasing lock\r\n");
  3741.     }
  3742.  
  3743. /* For bidirectional lines, restore getty if it was there before. */
  3744.  
  3745. #ifdef ACUCNTRL                /* 4.3BSD acucntrl() method. */
  3746.     if (xlocal) {
  3747.     debug(F100,"ttclos ACUCNTRL","",0);
  3748.     acucntrl("enable",ttnmsv);    /* Enable getty on the device. */
  3749.     }
  3750. #else
  3751. #ifdef ATT7300                /* ATT UNIX PC (3B1, 7300) method. */
  3752.     if (xlocal) {
  3753.     debug(F100,"ttclos ATT7300 ongetty","",0);
  3754.     if (attmodem & DOGETY)        /* Was getty(1m) running before us? */
  3755.       ongetty(ttnmsv);        /* Yes, restart getty on tty line */
  3756.     attmodem &= ~DOGETY;        /* No phone in use, getty restored */
  3757.     }
  3758. #endif /* ATT7300 */
  3759. #endif /* System-dependent getty-restoring methods */
  3760.  
  3761. #ifdef sony_news
  3762.     km_ext = -1;            /* Invalidate device's Kanji-mode */
  3763. #endif /* sony_news */
  3764.  
  3765.     ttyfd = -1;                         /* Invalidate the file descriptor. */
  3766.     wasclosed = 1;
  3767.     debug(F100,"ttclos done","",0);
  3768.     return(0);
  3769. }
  3770.  
  3771. /*  T T H A N G  --  Hangup phone line or network connection.  */
  3772. /*
  3773.   Returns:
  3774.   0 if it does nothing.
  3775.   1 if it believes that it hung up successfully.
  3776.  -1 if it believes that the hangup attempt failed.
  3777. */
  3778.  
  3779. #define HUPTIME 500            /* Milliseconds for hangup */
  3780.  
  3781. #ifdef COMMENT
  3782. /* The following didn't work but TIOCSDTR does work */
  3783. #ifdef UNIXWARE
  3784. /* Define HUP_POSIX to force non-POSIX builds to use the POSIX hangup method */
  3785. #ifndef POSIX                /* Such as Unixware 1.x, 2.x */
  3786. #ifndef HUP_POSIX
  3787. #define HUP_POSIX
  3788. #endif /* HUP_POSIX */
  3789. #endif /* POSIX */
  3790. #endif /* UNIXWARE */
  3791. #endif /* COMMENT */
  3792.  
  3793. #ifndef USE_TIOCSDTR
  3794. #ifdef __NetBSD__
  3795. /* Because the POSIX method (set output speed to 0) doesn't work in NetBSD */
  3796. #ifdef TIOCSDTR
  3797. #ifdef TIOCCDTR
  3798. #define USE_TIOCSDTR
  3799. #endif /* TIOCCDTR */
  3800. #endif /* TIOCSDTR */
  3801. #endif /* __NetBSD__ */
  3802. #endif /* USE_TIOCSDTR */
  3803.  
  3804. #ifndef HUP_CLOSE_POSIX
  3805. #ifdef OU8
  3806. #define HUP_CLOSE_POSIX
  3807. #else
  3808. #ifdef CK_SCOV5
  3809. #define HUP_CLOSE_POSIX
  3810. #endif /* CK_SCOV5 */
  3811. #endif /* OU8 */
  3812. #endif /* HUP_CLOSE_POSIX */
  3813.  
  3814. #ifdef NO_HUP_CLOSE_POSIX
  3815. #ifdef HUP_CLOSE_POSIX
  3816. #undef HUP_CLOSE_POSIX
  3817. #endif /* HUP_CLOSE_POSIX */
  3818. #endif /* NO_HUP_CLOSE_POSIX */
  3819.  
  3820. int
  3821. tthang() {
  3822. #ifdef NOLOCAL
  3823.     return(0);
  3824. #else
  3825.     int x = 0;                /* Sometimes used as return code. */
  3826. #ifndef POSIX
  3827.     int z;                /* worker */
  3828. #endif /* POSIX */
  3829.  
  3830. #ifdef COHERENT
  3831. #define SVORPOSIX
  3832. #endif /* COHERENT */
  3833.  
  3834. #ifdef SVORPOSIX            /* AT&T, POSIX, HPUX declarations. */
  3835.     int spdsav;                /* for saving speed */
  3836. #ifdef HUP_POSIX
  3837.     int spdsavi;
  3838. #else
  3839. #ifdef BSD44ORPOSIX
  3840.     int spdsavi;
  3841. #endif /* BSD44ORPOSIX */
  3842. #endif /* HUP_POSIX */
  3843. #ifdef HPUX
  3844. /*
  3845.   Early versions of HP-UX omitted the mflag typedef.  If you get complaints
  3846.   about it, just change it to long (or better still, unsigned long).
  3847. */
  3848.     mflag
  3849.       dtr_down = 00000000000,
  3850.       modem_rtn,
  3851.       modem_sav;
  3852.     char modem_state[64];
  3853. #endif /* HPUX */
  3854.     int flags;                /* fcntl flags */
  3855.     unsigned short ttc_save;
  3856. #endif /* SVORPOSIX */
  3857.  
  3858.     if (ttyfd < 0) return(0);           /* Don't do this if not open  */
  3859.     if (xlocal < 1) return(0);        /* Don't do this if not local */
  3860.  
  3861. #ifdef NETCMD
  3862.     if (ttpipe)
  3863.       return((ttclos(0) < 0) ? -1 : 1);
  3864. #endif /* NETCMD */
  3865. #ifdef NETPTY
  3866.     if (ttpty)
  3867.       return((ttclos(0) < 0) ? -1 : 1);
  3868. #endif /* NETPTY */
  3869. #ifdef NETCONN
  3870.     if (netconn) {            /* Network connection. */
  3871. #ifdef TN_COMPORT
  3872.         if (istncomport()) {
  3873.             int rc = tnc_set_dtr_state(0);
  3874.             if (rc >= 0) {
  3875.                 msleep(HUPTIME);
  3876.                 rc = tnc_set_dtr_state(1);
  3877.             }
  3878.             return(rc >= 0 ? 1 : -1);
  3879.         } else
  3880. #endif /* TN_COMPORT */
  3881.       return((netclos() < 0) ? -1 : 1); /* Just close it. */
  3882.   }
  3883. #endif /* NETCONN */
  3884.  
  3885. /* From here down, we handle real tty devices. */
  3886. #ifdef HUP_POSIX
  3887. /*
  3888.   e.g. for Unixware 2, where we don't have a full POSIX build, we
  3889.   still have to use POSIX-style hangup.  Thus the duplication of this
  3890.   and the next case, the only difference being we use a local termios
  3891.   struct here, since a different model is used elsewhere.
  3892.  
  3893.   NO LONGER USED as of C-Kermit 8.0 -- it turns out that this method,
  3894.   even though it compiles and executes without error, doesn't actually
  3895.   work (i.e. DTR does not drop), whereas the TIOCSDTR method works just fine,
  3896. */
  3897.     {
  3898.     struct termios ttcur;
  3899.     int x;
  3900.     debug(F100,"tthang HUP_POSIX style","",0);
  3901.     x = tcgetattr(ttyfd, &ttcur);    /* Get current attributes */
  3902.     debug(F111,"tthang tcgetattr",ckitoa(errno),x);
  3903.     if (x < 0) return(-1);
  3904.     spdsav = cfgetospeed(&ttcur);    /* Get current speed */
  3905.     debug(F111,"tthang cfgetospeed",ckitoa(errno),spdsav);
  3906.     spdsavi = cfgetispeed(&ttcur);    /* Get current speed */
  3907.     debug(F111,"tthang cfgetispeed",ckitoa(errno),spdsavi);
  3908.     x = cfsetospeed(&ttcur,B0);    /* Replace by 0 */
  3909.     debug(F111,"tthang cfsetospeed",ckitoa(errno),x);
  3910.     if (x < 0) return(-1);
  3911.     x = cfsetispeed(&ttcur,B0);
  3912.     debug(F111,"tthang cfsetispeed",ckitoa(errno),x);
  3913.     if (x < 0) return(-1);
  3914.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3915.     debug(F111,"tthang tcsetattr B0",ckitoa(errno),x);
  3916.     if (x < 0) return(-1);
  3917.     msleep(HUPTIME);        /* Sleep 0.5 sec */
  3918.     x = cfsetospeed(&ttcur,spdsav); /* Restore prev speed */
  3919.     if (x < 0) return(-1);
  3920.     debug(F111,"tthang cfsetospeed prev",ckitoa(errno),x);
  3921.     x = cfsetispeed(&ttcur,spdsavi);
  3922.     debug(F111,"tthang cfsetispeed prev",ckitoa(errno),x);
  3923.     if (x < 0) return(-1);
  3924.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3925.     debug(F111,"tthang tcsetattr restore",ckitoa(errno),x);
  3926.     if (x < 0) return(-1);
  3927.     return(1);
  3928.     }
  3929. #else
  3930. #ifdef BSD44ORPOSIX
  3931. #ifdef QNX
  3932.     {
  3933.     int x;
  3934.     x = tcdropline(ttyfd,500);
  3935.     debug(F101,"tthang QNX tcdropline","",x);
  3936.     ttcur.c_cflag |= CLOCAL;
  3937.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  3938.     debug(F101,"tthang QNX tcsetattr restore","",x);
  3939.     if (x < 0) {
  3940.         debug(F101,"tthang QNX tcsetattr restore errno","",errno);
  3941.         return(-1);
  3942.     }
  3943.     /* Fix flags - ensure O_NONBLOCK is off */
  3944.  
  3945.     errno = 0;
  3946.     debug(F101,"tthang QNX iniflags","",iniflags);
  3947.     if (fcntl(ttyfd, F_SETFL, iniflags) == -1) {
  3948.         debug(F101,"tthang QNX F_SETFL errno","",errno);
  3949.         return(-1);
  3950.     }
  3951.     return(x);
  3952.     }
  3953. #else  /* QNX */
  3954.     {
  3955.     int x;
  3956. #ifdef USE_TIOCSDTR
  3957.     debug(F100,"tthang BSD44ORPOSIX USE_TIOCSDTR","",0);
  3958.     errno = 0;
  3959.     x = ioctl(ttyfd, TIOCCDTR, NULL);
  3960.     debug(F111,"tthang BSD44ORPOSIX ioctl TIOCCDTR",ckitoa(errno),x);
  3961.     if (x < 0) return(-1);
  3962.     msleep(HUPTIME);        /* Sleep 0.5 sec */
  3963.     errno = 0;
  3964.     x = ioctl(ttyfd, TIOCSDTR, NULL);
  3965.     debug(F111,"tthang BSD44ORPOSIX ioctl TIOCSDTR",ckitoa(errno),x);
  3966.     if (x < 0) return(-1);
  3967. #else  /* USE_TIOCSDTR */
  3968.  
  3969. #ifdef HUP_CLOSE_POSIX
  3970. /*
  3971.   In OSR5 versions where TIOCSDTR is not defined (up to and including at
  3972.   least 5.0.6a) the POSIX APIs in the "#else" part below are available but
  3973.   don't work, and no other APIs are available that do work.  In this case
  3974.   we have to drop DTR by brute force: close and reopen the port.  This
  3975.   code actually works, but all the steps are crucial: setting CLOCAL, the
  3976.   O_NDELAY manipulations, etc.
  3977. */
  3978.     debug(F100,"tthang HUP_CLOSE_POSIX close/open","",0);
  3979.     debug(F101,"tthang HUP_CLOSE_POSIX O_NONBLOCK","",O_NONBLOCK);
  3980.     debug(F101,"tthang HUP_CLOSE_POSIX O_NDELAY","",O_NDELAY);
  3981.     errno = 0;
  3982.     x = tcgetattr(ttyfd, &ttcur);    /* Get current attributes */
  3983.     debug(F101,"tthang HUP_CLOSE_POSIX tcgetattr","",x);
  3984.     if (x < 0) {
  3985.         debug(F101,"tthang HUP_CLOSE_POSIX tcgetattr errno","",errno);
  3986.         return(-1);
  3987.     }
  3988.     errno = 0;
  3989.  
  3990.     x = close(ttyfd);        /* Close without releasing lock */
  3991.     if (x < 0) {
  3992.         debug(F101,"tthang HUP_CLOSE_POSIX close errno","",errno);
  3993.         return(-1);
  3994.     }
  3995.     errno = 0;
  3996.     x = msleep(500);        /* Pause half a second */
  3997.     if (x < 0) {            /* Or if that doesn't work, 1 sec */
  3998.         debug(F101,"tthang HUP_CLOSE_POSIX msleep errno","",errno);
  3999.         sleep(1);
  4000.     }
  4001.     errno = 0;
  4002.     ttyfd = priv_opn(ttnmsv, (O_RDWR|O_NDELAY)); /* Reopen the device */
  4003.     debug(F111,"tthang HUP_CLOSE_POSIX reopen",ttnmsv,ttyfd);
  4004.     if (ttyfd < 0) {
  4005.         debug(F101,"tthang HUP_CLOSE_POSIX reopen errno","",errno);
  4006.         return(-1);
  4007.     }
  4008.     debug(F101,"tthang HUP_CLOSE_POSIX re-ttopen ttyfd","",ttyfd);
  4009.  
  4010.     /* Restore previous attributes */
  4011.  
  4012.     errno = 0;
  4013.     tvtflg = 0;
  4014.     ttcur.c_cflag |= CLOCAL;
  4015.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  4016.     debug(F101,"tthang HUP_CLOSE_POSIX tcsetattr restore","",x);
  4017.     if (x < 0) {
  4018.         debug(F101,"tthang HUP_CLOSE_POSIX tcsetattr restore errno",
  4019.           "",errno);
  4020.         return(-1);
  4021.     }
  4022.     /* Fix flags - ensure O_NDELAY and O_NONBLOCK are off */
  4023.  
  4024.     errno = 0;
  4025.         if ((x = fcntl(ttyfd, F_GETFL, 0)) == -1) {
  4026.         debug(F101,"tthang HUP_CLOSE_POSIX F_GETFL errno","",errno);
  4027.         return(-1);
  4028.     }
  4029.     debug(F101,"tthang HUP_CLOSE_POSIX flags","",x);
  4030.     errno = 0;
  4031.         x &= ~(O_NONBLOCK|O_NDELAY);
  4032.     debug(F101,"tthang HUP_CLOSE_POSIX flags to set","",x);
  4033.     debug(F101,"tthang HUP_CLOSE_POSIX iniflags","",iniflags);
  4034.     if (fcntl(ttyfd, F_SETFL, x) == -1) {
  4035.         debug(F101,"tthang HUP_CLOSE_POSIX F_SETFL errno","",errno);
  4036.         return(-1);
  4037.     }
  4038. #ifdef DEBUG
  4039.     if (deblog) {
  4040.         if ((x = fcntl(ttyfd, F_GETFL, 0)) > -1) {
  4041.         debug(F101,"tthang HUP_CLOSE_POSIX flags","",x);
  4042.         debug(F101,"tthang HUP_CLOSE_POSIX flags & O_NONBLOCK",
  4043.               "",x&O_NONBLOCK);
  4044.         debug(F101,"tthang HUP_CLOSE_POSIX flags & O_NDELAY",
  4045.               "",x&O_NDELAY);
  4046.         }
  4047.     }
  4048. #endif /* DEBUG */
  4049.  
  4050. #else  /* HUP_CLOSE_POSIX */
  4051.     
  4052.     /* General BSD44ORPOSIX case (Linux, BSDI, FreeBSD, etc) */
  4053.  
  4054.     debug(F100,"tthang BSD44ORPOSIX B0","",0);
  4055.     x = tcgetattr(ttyfd, &ttcur);    /* Get current attributes */
  4056.     debug(F111,"tthang BSD44ORPOSIX tcgetattr",ckitoa(errno),x);
  4057.     if (x < 0) return(-1);
  4058.     spdsav = cfgetospeed(&ttcur);    /* Get current speed */
  4059.     debug(F111,"tthang BSD44ORPOSIX cfgetospeed",ckitoa(errno),spdsav);
  4060.     spdsavi = cfgetispeed(&ttcur);    /* Get current speed */
  4061.     debug(F111,"tthang BSD44ORPOSIX cfgetispeed",ckitoa(errno),spdsavi);
  4062.     x = cfsetospeed(&ttcur,B0);    /* Replace by 0 */
  4063.     debug(F111,"tthang BSD44ORPOSIX cfsetospeed",ckitoa(errno),x);
  4064.     if (x < 0) return(-1);
  4065.     x = cfsetispeed(&ttcur,B0);
  4066.     debug(F111,"tthang BSD44ORPOSIX cfsetispeed",ckitoa(errno),x);
  4067.     if (x < 0) return(-1);
  4068.     /* This gets EINVAL on NetBSD 1.4.1 because of B0... */
  4069.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  4070.     debug(F111,"tthang BSD44ORPOSIX tcsetattr B0",ckitoa(errno),x);
  4071.     if (x < 0) return(-1);
  4072.     msleep(HUPTIME);        /* Sleep 0.5 sec */
  4073.     debug(F101,"tthang BSD44ORPOSIX restore output speed","",spdsav);
  4074.     x = cfsetospeed(&ttcur,spdsav); /* Restore prev speed */
  4075.     debug(F111,"tthang BSD44ORPOSIX cfsetospeed prev",ckitoa(errno),x);
  4076.     if (x < 0) return(-1);
  4077.     debug(F101,"tthang BSD44ORPOSIX restore input speed","",spdsavi);
  4078.     x = cfsetispeed(&ttcur,spdsavi);
  4079.     debug(F111,"tthang BSD44ORPOSIX cfsetispeed prev",ckitoa(errno),x);
  4080.     if (x < 0) return(-1);
  4081.     ttcur.c_cflag |= CLOCAL;    /* Don't expect CD after hangup */
  4082.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  4083.     debug(F111,"tthang BSD44ORPOSIX tcsetattr restore",ckitoa(errno),x);
  4084.     if (x < 0) return(-1);
  4085.  
  4086. #endif /* HUP_CLOSE_POSIX */
  4087. #endif /* USE_TIOCSDTR */
  4088.  
  4089.     return(1);
  4090.     }
  4091.  
  4092. #endif /* QNX */
  4093. #else /* BSD44ORPOSIX */
  4094.  
  4095. #ifdef aegis                /* Apollo Aegis */
  4096.     sio_$control((short)ttyfd, sio_$dtr, false, st);    /* DTR down */
  4097.     msleep(HUPTIME);                    /* pause */
  4098.     sio_$control((short)ttyfd, sio_$dtr, true,  st);    /* DTR up */
  4099.     return(1);
  4100. #endif /* aegis */
  4101.  
  4102. #ifdef ANYBSD                /* Any BSD version. */
  4103. #ifdef TIOCCDTR                /* Except those that don't have this */
  4104.     debug(F100,"tthang BSD style","",0);
  4105.     if (ioctl(ttyfd,TIOCCDTR,0) < 0) {    /* Clear DTR. */
  4106.     debug(F101,"tthang TIOCCDTR fails","",errno);
  4107.     return(-1);
  4108.     }
  4109.     msleep(HUPTIME);            /* For about 1/2 sec */
  4110.     errno = 0;
  4111.     x = ioctl(ttyfd,TIOCSDTR,0);    /* Restore DTR */
  4112.     if (x < 0) {
  4113.     /*
  4114.       For some reason, this tends to fail with "no such device or address"
  4115.       but the operation still works, probably because of the close/open
  4116.       later on.  So let's not scare the user unnecessarily here.
  4117.     */
  4118.     debug(F101,"tthang TIOCSDTR errno","",errno); /* Log the error */
  4119.     x = 1;                /* Pretend we succeeded */
  4120.     } else if (x == 0) x = 1;        /* Success */
  4121. #ifdef COMMENT
  4122. #ifdef FT21
  4123.     ioctl(ttyfd, TIOCSAVEMODES, 0);
  4124.     ioctl(ttyfd, TIOCHPCL, 0);
  4125.     close(ttyfd);            /* Yes, must do this twice */
  4126.     if ((ttyfd = open(ttnmsv,2)) < 0)    /* on Fortune computers... */
  4127.       return(-1);            /* (but why?) */
  4128.     else x = 1;
  4129. #endif /* FT21 */
  4130. #endif /* COMMENT */
  4131. #endif /* TIOCCDTR */
  4132.     close(do_open(ttnmsv));        /* Clear i/o error condition */
  4133.     errno = 0;
  4134. #ifdef COMMENT
  4135. /* This is definitely dangerous.  Why was it here? */
  4136.     z = ttvt(ttspeed,ttflow);        /* Restore modes. */
  4137.     debug(F101,"tthang ttvt returns","",z);
  4138.     return(z < 0 ? -1 : 1);
  4139. #else
  4140.     return(x);
  4141. #endif /* COMMENT */
  4142. #endif /* ANYBSD */
  4143.  
  4144. #ifdef ATTSV
  4145. /* AT&T UNIX section, includes HP-UX and generic AT&T System III/V... */
  4146.  
  4147. #ifdef HPUX
  4148. /* Hewlett Packard allows explicit manipulation of modem signals. */
  4149.  
  4150. #ifdef COMMENT
  4151. /* Old way... */
  4152.     debug(F100,"tthang HP-UX style","",0);
  4153.     if (ioctl(ttyfd,MCSETAF,&dtr_down) < 0)        /* lower DTR */
  4154.       return(-1);                           /* oops, can't. */
  4155.     msleep(HUPTIME);                       /* Pause half a second. */
  4156.     x = 1;                           /* Set return code */
  4157.     if (ioctl(ttyfd,MCGETA,&modem_rtn) > -1) {     /* Get line status. */
  4158.     if ((modem_rtn & MDCD) != 0)             /* Check if CD is low. */
  4159.       x = -1;                                  /* CD didn't drop, fail. */
  4160.     } else x = -1;
  4161.  
  4162.     /* Even if above calls fail, RTS & DTR should be turned back on. */
  4163.     modem_rtn = MRTS | MDTR;
  4164.     if (ioctl(ttyfd,MCSETAF,&modem_rtn) < 0) x = -1;
  4165.     return(x);
  4166. #else
  4167. /* New way, from Hellmuth Michaelis */
  4168.     debug(F100,"tthang HP-UX style, HPUXDEBUG","",0);
  4169.     if (ioctl(ttyfd,MCGETA,&modem_rtn) == -1) { /* Get current status. */
  4170.     debug(F100,"tthang HP-UX: can't get modem lines, NO HANGUP!","",0);
  4171.     return(-1);
  4172.     }
  4173.     sprintf(modem_state,"%#lx",modem_rtn);
  4174.     debug(F110,"tthang HP-UX: modem lines = ",modem_state,0);
  4175.     modem_sav = modem_rtn;        /* Save current modem signals */
  4176.     modem_rtn &= ~MDTR;            /* Turn DTR bit off */
  4177.     sprintf(modem_state,"%#lx",modem_rtn);
  4178.     debug(F110,"tthang HP-UX: DTR down = ",modem_state,0);
  4179.     if (ioctl(ttyfd,MCSETAF,&modem_rtn) < 0) { /* lower DTR */
  4180.     debug(F100,"tthang HP-UX: can't lower DTR!","",0);
  4181.     return(-1);            /* oops, can't. */
  4182.     }
  4183.     msleep(HUPTIME);            /* Pause half a second. */
  4184.     x = 1;                /* Set return code */
  4185.     if (ioctl(ttyfd,MCGETA,&modem_rtn) > -1) { /* Get line status. */
  4186.     sprintf(modem_state,"%#lx",modem_rtn);
  4187.     debug(F110,"tthang HP-UX: modem lines got = ",modem_state,0);
  4188.     if ((modem_rtn & MDCD) != 0) {    /* Check if CD is low. */
  4189.         debug(F100,"tthang HP-UX: DCD not down","",0);
  4190.         x = -1;            /* CD didn't drop, fail. */
  4191.     } else {
  4192.         debug(F100,"tthang HP-UX: DCD down","",0);
  4193.     }
  4194.     } else {
  4195.     x = -1;
  4196.     debug(F100,"tthang HP-UX: can't get DCD status !","",0);
  4197.     }
  4198.  
  4199.     /* Even if above calls fail, DTR should be turned back on. */
  4200.  
  4201.     modem_sav |= MDTR;
  4202.     if (ioctl(ttyfd,MCSETAF,&modem_sav) < 0) {
  4203.     x = -1;
  4204.     debug(F100,"tthang HP-UX: can't set saved state","",0);
  4205.     } else {
  4206.     sprintf(modem_state,"%#lx",modem_sav);
  4207.     debug(F110,"tthang HP-UX: final modem lines = ",modem_state,0);
  4208.     }
  4209.     return(x);
  4210. #endif /* COMMENT */
  4211.  
  4212. #else /* AT&T but not HP-UX */
  4213.  
  4214. /* SVID for AT&T System V R3 defines ioctl's for handling modem signals. */
  4215. /* It is not known how many, if any, systems actually implement them, */
  4216. /* so we include them here in ifdef's. */
  4217.  
  4218. /*
  4219.   Unixware has the TIOCMxxx symbols defined, but calling ioctl() with them
  4220.   gives error 22 (invalid argument).
  4221. */
  4222. #ifndef _IBMR2
  4223. /*
  4224.   No modem-signal twiddling for IBM RT PC or RS/6000.
  4225.   In AIX 3.1 and earlier, the ioctl() call is broken.
  4226.   This code could be activated for AIX 3.1 with PTF 2006 or later
  4227.   (e.g. AIX 3.2), but close/open does the job too, so why bother.
  4228. */
  4229. #ifdef TIOCMBIS                /* Bit Set */
  4230. #ifdef TIOCMBIC                /* Bit Clear */
  4231. #ifdef TIOCM_DTR            /* DTR */
  4232.  
  4233. /* Clear DTR, sleep 300 msec, turn it back on. */
  4234. /* If any of the ioctl's return failure, go on to the next section. */
  4235.  
  4236.     z = TIOCM_DTR;            /* Code for DTR. */
  4237. #ifdef COMMENT
  4238. /*
  4239.   This was the cause of the troubles with the Solaris Port Monitor.
  4240.   The problem is: RTS never comes back on.  Moral: Don't do it!
  4241.   (But why doesn't it come back on?  See the TIOCMBIS call...)
  4242. */
  4243. #ifdef TIOCM_RTS            /* Lower RTS too if symbol is known. */
  4244.     z |= TIOCM_RTS;
  4245. #endif /* TIOCM_RTS */
  4246. #endif /* COMMENT */
  4247.  
  4248.     debug(F101,"tthang TIOCM signal mask","",z);
  4249.     if (ioctl(ttyfd,TIOCMBIC,&z) > -1) {   /* Try to lower DTR. */
  4250.     debug(F100,"tthang TIOCMBIC ok","",0);
  4251.     msleep(HUPTIME);           /* Pause half a second. */
  4252.     if (ioctl(ttyfd,TIOCMBIS,&z) > -1) { /* Try to turn it back on. */
  4253.         debug(F100,"tthang TIOCMBIS ok","",0);
  4254. #ifndef CLSOPN
  4255.         return(1);            /* Success, done. */
  4256. #endif /* CLSOPN */
  4257.     } else {            /* Couldn't raise, continue. */
  4258.         debug(F101,"tthang TIOCMBIS errno","",errno);
  4259.     }
  4260.     } else {                /* Couldn't lower, continue. */
  4261.      debug(F101,"tthang TIOCMBIC errno","",errno);
  4262.     }
  4263. #endif /* TIOCM_DTR */
  4264. #endif /* TIOCMBIC */
  4265. #endif /* TIOCMBIS */
  4266. #endif /* _IBMR2 */
  4267.  
  4268. /*
  4269.   General AT&T UNIX case, not HPUX.  The following code is highly suspect.  No
  4270.   two AT&T-based systems seem to do this the same way.  The object is simply
  4271.   to turn off DTR and then turn it back on.  SVID says the universal method
  4272.   for turning off DTR is to set the speed to zero, and this does seem to do
  4273.   the trick in all cases.  But neither SVID nor any known man pages say how to
  4274.   turn DTR back on again.  Some variants, like most Xenix implementations,
  4275.   raise DTR again when the speed is restored to a nonzero value.  Others
  4276.   require the device to be closed and opened again, but this is risky because
  4277.   getty could seize the device during the instant it is closed.
  4278. */
  4279.  
  4280. /* Return code for ioctl failures... */
  4281. #ifdef ATT6300
  4282.     x = 1;                /* ATT6300 doesn't want to fail... */
  4283. #else
  4284.     x = -1;
  4285. #endif /* ATT6300 */
  4286.  
  4287.     debug(F100,"tthang get settings","",0);
  4288.     if (ioctl(ttyfd,TCGETA,&ttcur) < 0) /* Get current settings. */
  4289.       return(x);            /* Fail if this doesn't work. */
  4290.     if ((flags = fcntl(ttyfd,F_GETFL,0)) < 0) /* Get device flags. */
  4291.       return(x);
  4292.     ttc_save = ttcur.c_cflag;        /* Remember current speed. */
  4293.     spdsav = ttc_save & CBAUD;
  4294.     debug(F101,"tthang speed","",spdsav);
  4295.  
  4296. #ifdef O_NDELAY
  4297.     debug(F100,"tthang turning O_NDELAY on","",0);
  4298.     fcntl(ttyfd, F_SETFL, flags | O_NDELAY); /* Activate O_NDELAY */
  4299. #endif /* O_NDELAY */
  4300.  
  4301. #ifdef ATT7300 /* This is the way it is SUPPOSED to work */
  4302.     ttcur.c_cflag &= ~CBAUD;        /* Change the speed to zero.  */
  4303. #else
  4304. #ifdef RTAIX
  4305.     ttcur.c_cflag &= ~CBAUD;        /* Change the speed to zero.  */
  4306. #else          /* This way really works but may be dangerous */
  4307. #ifdef u3b2
  4308.     ttcur.c_cflag = ~(CBAUD|CLOCAL);    /* Special for AT&T 3B2s */
  4309.                     /* (CLOCAL must be OFF) */
  4310. #else
  4311. #ifdef SCO3R2                /* SCO UNIX 3.2 */
  4312. /*
  4313.   This is complete nonsense, but an SCO user claimed this change made
  4314.   hanging up work.  Comments from other SCO UNIX 3.2 users would be
  4315.   appreciated.
  4316. */
  4317.     ttcur.c_cflag = CBAUD|B0;
  4318. #else
  4319. #ifdef AIXRS                /* AIX on RS/6000 */
  4320. /*
  4321.   Can't set speed to zero on AIX 3.1 on RS/6000 64-port adapter,
  4322.   even though you can do it on the built-in port and the 8- and 16-port
  4323.   adapters.  (Untested on 128-port adapter.)
  4324. */
  4325.     ttcur.c_cflag = CLOCAL|HUPCL|spdsav; /* Speed 0 causes EINVAL */
  4326. #else                    /* None of the above */
  4327. /*
  4328.   Set everything, including the speed, to zero, except for the CLOCAL
  4329.   and HUPCL bits.
  4330. */
  4331.     ttcur.c_cflag = CLOCAL|HUPCL;
  4332. #endif /* AIXRS */
  4333. #endif /* SCO3R2 */
  4334. #endif /* u3b2 */
  4335. #endif /* RTAIX */
  4336. #endif /* ATT7300 */
  4337.  
  4338. #ifdef COMMENT
  4339.     /* and if none of those work, try one of these... */
  4340.     ttcur.c_cflag = 0;
  4341.     ttcur.c_cflag = CLOCAL;
  4342.     ttcur.c_cflag &= ~(CBAUD|HUPCL);
  4343.     ttcur.c_cflag &= ~(CBAUD|CREAD);
  4344.     ttcur.c_cflag &= ~(CBAUD|CREAD|HUPCL);
  4345.     /* or other combinations */
  4346. #endif /* COMMENT */
  4347.  
  4348. #ifdef TCXONC
  4349.     debug(F100,"tthang TCXONC","",0);
  4350.     if (ioctl(ttyfd, TCXONC, 1) < 0) {
  4351.     debug(F101,"tthang TCXONC failed","",errno);
  4352.     }
  4353. #endif /* TCXONC */
  4354.  
  4355. #ifdef TIOCSTART
  4356.     debug(F100,"tthang TIOCSTART","",0);
  4357.     if (ioctl(ttyfd, TIOCSTART, 0) < 0) {
  4358.     debug(F101,"tthang TIOCSTART failed","",errno);
  4359.     }
  4360. #endif /* TIOCSTART */
  4361.  
  4362.     if (ioctl(ttyfd,TCSETAF,&ttcur) < 0) { /* Fail if we can't. */
  4363.     debug(F101,"tthang TCSETAF failed","",errno);
  4364.     fcntl(ttyfd, F_SETFL, flags);    /* Restore flags */
  4365.     return(-1);            /* before returning. */
  4366.     }
  4367.     msleep(300);            /* Give modem time to notice. */
  4368.  
  4369. #ifndef NOCOTFMC
  4370.  
  4371. /* Now, even though it doesn't say this in SVID or any man page, we have */
  4372. /* to close and reopen the device.  This is not necessary for all systems, */
  4373. /* but it's impossible to predict which ones need it and which ones don't. */
  4374.  
  4375. #ifdef ATT7300
  4376. /*
  4377.   Special handling for ATT 7300 UNIX PC and 3B1, which have "phone"
  4378.   related ioctl's for their internal modems.  attmodem has getty status and
  4379.   modem-in-use bit.  Reportedly the ATT7300/3B1 PIOCDISC call is necessary,
  4380.   but also ruins the file descriptor, and no other phone(7) ioctl call can fix
  4381.   it.  Whatever it does, it seems to escape detection with PIOCGETA and TCGETA.
  4382.   The only way to undo the damage is to close the fd and then reopen it.
  4383. */
  4384.     if (attmodem & ISMODEM) {
  4385.     debug(F100,"tthang attmodem close/open","",0);
  4386.     ioctl(ttyfd,PIOCUNHOLD,&dialer); /* Return call to handset. */
  4387.     ioctl(ttyfd,PIOCDISC,&dialer);    /* Disconnect phone. */
  4388.     close(ttyfd);            /* Close and reopen the fd. */
  4389.     ttyfd = priv_opn(ttnmsv, O_RDWR | O_NDELAY);
  4390.     attmodem &= ~ISMODEM;        /* Phone no longer in use. */
  4391.     }
  4392. #else /* !ATT7300 */
  4393. /* It seems we have to close and open the device for other AT&T systems */
  4394. /* too, and this is the place to do it.  The following code does the */
  4395. /* famous close(open(...)) magic by default.  If that doesn't work for you, */
  4396. /* then try uncommenting the following statement or putting -DCLSOPN in */
  4397. /* the makefile CFLAGS. */
  4398.  
  4399. /* #define CLSOPN */
  4400.  
  4401. #ifndef SCO32 /* Not needed by, and harmful to, SCO UNIX 3.2 / Xenix 2.3 */
  4402.  
  4403. #ifdef O_NDELAY
  4404. #define OPENFLGS O_RDWR | O_NDELAY
  4405. #else
  4406. #define OPENFLGS O_RDWR
  4407. #endif
  4408.  
  4409. #ifndef CLSOPN
  4410. /* This method is used by default, i.e. unless CLSOPN is defined. */
  4411. /* It is thought to be safer because there is no window where getty */
  4412. /* can seize control of the device.  The drawback is that it might not work. */
  4413.  
  4414.     debug(F101,"tthang close(open()), OPENFLGS","",OPENFLGS);
  4415.     close(priv_opn(ttnmsv, OPENFLGS));
  4416.  
  4417. #else
  4418. /* This method is used if you #define CLSOPN.  It is more likely to work */
  4419. /* than the previous method, but it's also more dangerous. */
  4420.  
  4421.     debug(F101,"tthang close/open, OPENFLGS","",OPENFLGS);
  4422.     close(ttyfd);
  4423.     msleep(10);
  4424.     ttyfd = priv_opn(ttnmsv, OPENFLGS);    /* Open it again */
  4425. #endif /* CLSOPN */
  4426. #undef OPENFLGS
  4427.  
  4428. #endif /* SCO32 */
  4429. #endif /* ATT7300 */
  4430.  
  4431. #endif /* NOCOTFMC */
  4432.  
  4433. /* Now put all flags & modes back the way we found them. */
  4434. /* (Does the order of ioctl & fcntl matter ? ) */
  4435.  
  4436.     debug(F100,"tthang restore settings","",0);
  4437.     ttcur.c_cflag = ttc_save;        /* Get old speed back. */
  4438.     if (ioctl(ttyfd,TCSETAF,&ttcur) < 0) /* ioctl parameters. */
  4439.       return(-1);
  4440. #ifdef O_NDELAY
  4441. /*
  4442.   This is required for IBM RT and RS/6000, probably helps elsewhere too (?).
  4443.   After closing a modem line, the modem will probably not be asserting
  4444.   carrier any more, so we should not require carrier any more.  If this
  4445.   causes trouble on non-IBM UNIXes, change the #ifdef to use _IBMR2 rather
  4446.   than O_NDELAY.
  4447. */
  4448.     flags &= ~O_NDELAY;            /* Don't require carrier on reopen */
  4449. #endif /* O_NDELAY */
  4450.     if (fcntl(ttyfd,F_SETFL,flags) < 0)    /* fcntl parameters */
  4451.       return(-1);
  4452.  
  4453.     return(1);
  4454. #endif /* not HPUX */
  4455. #endif /* ATTSV */
  4456. #endif /* BSD44ORPOSIX */
  4457. #endif /* HUP_POSIX */
  4458. #endif /* NOLOCAL */
  4459. }
  4460.  
  4461. /*
  4462.   Major change in 5A(174).  We used to use LPASS8, if it was defined, to
  4463.   allow 8-bit data and Xon/Xoff flow control at the same time.  But this
  4464.   LPASS8 business seems to have been causing trouble for everybody but me!
  4465.   For example, Annex terminal servers, commonly used with Encore computers,
  4466.   do not support LPASS8 even though the Encore itself does.  Ditto for many
  4467.   other terminal servers, TELNET connections, rlogin connections, etc etc.
  4468.   Now, reportedly, even vanilla 4.3 BSD systems can't do this right on their
  4469.   serial lines, even though LPASS8 is a feature of 4.3BSD.  So let's turn it
  4470.   off for everybody.  That means we goes back to using raw mode, with no
  4471.   flow control.  Phooey.
  4472.  
  4473.   NOTE: This must be done before the first reference to LPASS8 in this file,
  4474.   and after the last #include statment.
  4475. */
  4476. #ifdef LPASS8
  4477. #undef LPASS8
  4478. #endif /* LPASS8 */
  4479.  
  4480. /*  T T R E S  --  Restore terminal to "normal" mode.  */
  4481.  
  4482. /* ske@pkmab.se: There are two choices for what this function should do.
  4483.  * (1) Restore the tty to current "normal" mode, with carrier treatment
  4484.  * according to ttcarr, to be used after every kermit command. (2) Restore
  4485.  * the tty to the state it was in before kermit opened it. These choices
  4486.  * conflict, since ttold can't hold both choices of tty parameters.  ttres()
  4487.  * is currently being called as in choice (1), but ttold basically holds
  4488.  * the initial parameters, as in (2), and the description at the beginning
  4489.  * of this file says (2).
  4490.  *
  4491.  * I don't think restoring tty parameters after all kermit commands makes
  4492.  * much of a difference.  Restoring them upon exit from kermit may be of
  4493.  * some use in some cases (when the line is not restored automatically on
  4494.  * close, by the operating system).
  4495.  *
  4496.  * I can't choose which one it should be, so I haven't changed it. It
  4497.  * probably works as it is, too. It would probably even work even with
  4498.  * ttres() entirely deleted...
  4499.  *
  4500.  * (from fdc: Actually, this function operates in remote mode too, so
  4501.  * it restores the console (command) terminal to whatever mode it was
  4502.  * in before packet operations began, so that commands work right again.)
  4503.  */
  4504. int
  4505. ttres() {                               /* Restore the tty to normal. */
  4506.     int x;
  4507.  
  4508.     if (ttyfd < 0) return(-1);          /* Not open. */
  4509.  
  4510.     if (ttfdflg) return(0);        /* Don't mess with terminal modes if */
  4511.                     /* we got ttyfd from another process */
  4512. #ifdef    NETCONN
  4513.     if (netconn) {            /* Network connection */
  4514.         tvtflg = 0;
  4515. #ifdef TCPSOCKET
  4516. #ifdef TCP_NODELAY
  4517.         {
  4518.         extern int tcp_nodelay;    /* Just put this back if necessary */
  4519.         if (ttnet == NET_TCPB) {
  4520.         if (nodelay_sav > -1) {
  4521.             no_delay(ttyfd,nodelay_sav);
  4522.             nodelay_sav = -1;
  4523.         }
  4524.         }
  4525.         }
  4526. #endif /* TCP_NODELAY */
  4527. #ifdef TN_COMPORT
  4528.         if (istncomport()) {
  4529.             int rc = -1;
  4530.             if ((rc = tnsetflow(ttflow)) < 0)
  4531.           return(rc);
  4532.             if (ttspeed <= 0) 
  4533.           ttspeed = tnc_get_baud();
  4534.             else if ((rc = tnc_set_baud(ttspeed)) < 0)
  4535.           return(rc);
  4536.             tnc_set_datasize(8);
  4537.         tnc_set_stopsize(stopbits);
  4538.  
  4539. #ifdef HWPARITY
  4540.             if (hwparity) {
  4541.                 switch (hwparity) {
  4542.           case 'e':            /* Even */
  4543.                     debug(F100,"ttres 8 bits + even parity","",0);
  4544.                     tnc_set_parity(3);
  4545.                     break;
  4546.           case 'o':            /* Odd */
  4547.                     debug(F100,"ttres 8 bits + odd parity","",0);
  4548.                     tnc_set_parity(2);
  4549.                     break;
  4550.           case 'm':            /* Mark */
  4551.                     debug(F100,"ttres 8 bits + invalid parity: mark","",0);
  4552.                     tnc_set_parity(4);
  4553.                     break;
  4554.           case 's':            /* Space */
  4555.                     debug(F100,"ttres 8 bits + invalid parity: space","",0);
  4556.                     tnc_set_parity(5);
  4557.                     break;
  4558.                 }
  4559.             } else
  4560. #endif /* HWPARITY */
  4561.         {
  4562.                 tnc_set_parity(1);              /* None */
  4563.             }
  4564.             tvtflg = 0;
  4565.             return(0);
  4566.         }
  4567. #endif /* TN_COMPORT */
  4568. #endif /* TCPSOCKET */
  4569.     return(0);
  4570.     }
  4571. #endif    /* NETCONN */
  4572. #ifdef NETCMD
  4573.     if (ttpipe) return(0);
  4574. #endif /* NETCMD */
  4575. #ifdef NETPTY
  4576.     if (ttpty) return(0);
  4577. #endif /* NETPTY */
  4578.  
  4579. /* Real terminal device, so restore its original modes */
  4580.  
  4581. #ifdef BSD44ORPOSIX            /* For POSIX like this */
  4582.     debug(F100,"ttres BSD44ORPOSIX","",0);
  4583.     x = tcsetattr(ttyfd,TCSADRAIN,&ttold);
  4584. #else                    /* For all others... */
  4585. #ifdef ATTSV                            /* For AT&T versions... */
  4586.     debug(F100,"ttres ATTSV","",0);
  4587.     x = ioctl(ttyfd,TCSETAW,&ttold);    /* Restore tty modes this way. */
  4588. #else
  4589. /* Here we restore the modes for BSD */
  4590.  
  4591. #ifdef LPASS8                /* Undo "pass8" if it were done */
  4592.     if (lmodef) {
  4593.     if (ioctl(ttyfd,TIOCLSET,&lmode) < 0)
  4594.       debug(F100,"ttres TIOCLSET failed","",0);
  4595.     else
  4596.       debug(F100,"ttres TIOCLSET ok","",0);
  4597.     }
  4598. #endif /* LPASS8 */
  4599.  
  4600. #ifdef CK_DTRCTS           /* Undo hardware flow if it were done */
  4601.     if (lmodef) {
  4602.      if (ioctl(ttyfd,TIOCLSET,&lmode) < 0)
  4603.        debug(F100,"ttres TIOCLSET failed","",0);
  4604.      else
  4605.        debug(F100,"ttres TIOCLSET ok","",0);
  4606.     }
  4607. #endif /* CK_DTRCTS */
  4608.  
  4609. #ifdef TIOCGETC                /* Put back special characters */
  4610.     if (tcharf && (xlocal == 0)) {
  4611.     if (ioctl(ttyfd,TIOCSETC,&tchold) < 0)
  4612.       debug(F100,"ttres TIOCSETC failed","",0);
  4613.     else
  4614.       debug(F100,"ttres TIOCSETC ok","",0);
  4615.     }
  4616. #endif /* TIOCGETC */
  4617.  
  4618. #ifdef TIOCGLTC                /* Put back local special characters */
  4619.     if (ltcharf && (xlocal == 0)) {
  4620.     if (ioctl(ttyfd,TIOCSLTC,<chold) < 0)
  4621.       debug(F100,"ttres TIOCSLTC failed","",0);
  4622.     else
  4623.       debug(F100,"ttres TIOCSLTC ok","",0);
  4624.     }
  4625. #endif /* TIOCGLTC */
  4626.  
  4627. #ifdef BELLV10
  4628.     debug(F100,"ttres BELLV10","",0);
  4629.     x = ioctl(ttyfd,TIOCSETP,&ttold);    /* Restore both structs */
  4630.     x = ioctl(ttyfd,TIOCSDEV,&tdold);
  4631. #else
  4632.     debug(F100,"ttres stty","",0);
  4633.     x = stty(ttyfd,&ttold);             /* Restore tty modes the old way. */
  4634. #endif /* BELLV10 */
  4635.  
  4636.     if (!xlocal)
  4637.       msleep(100);            /* This replaces sleep(1)... */
  4638.                     /* Put back sleep(1) if tty is */
  4639.                     /* messed up after close. */
  4640. #endif /* ATTSV */
  4641. #endif /* BSD44ORPOSIX */
  4642.  
  4643.     debug(F101,"ttres result","",x);
  4644. #ifndef QNX
  4645.     if (x < 0) debug(F101,"ttres errno","",errno);
  4646. #endif /* QNX */
  4647.  
  4648. #ifdef AIXRS
  4649. #ifndef AIX41
  4650.     x = ioctl(ttyfd, ttld & 1 ? TXADDCD : TXDELCD, "rts");
  4651.     debug(F101,"ttres AIX line discipline rts restore","",x);
  4652. #endif /* AIX41 */
  4653. #endif /* AIXRS */
  4654.  
  4655. #ifdef BSD41
  4656.     if (ttld > -1) {            /* Put back line discipline */
  4657.     x = ioctl(ttyfd, TIOCSETD, &ttld);
  4658.     debug(F101,"ttres BSD41 line discipline restore","",x);
  4659.     if (x < 0) debug(F101,"...ioctl errno","",errno);
  4660.     ttld = -1;
  4661.     }
  4662. #endif /* BSD41 */
  4663.  
  4664. #ifdef sony_news
  4665.     x = xlocal ? km_ext : km_con;    /* Restore Kanji mode. */
  4666.     if (x != -1) {            /* Make sure we know original modes. */
  4667.     if (ioctl(ttyfd,TIOCKSET, &x) < 0) {
  4668.         perror("ttres can't set Kanji mode");
  4669.         debug(F101,"ttres error setting Kanji mode","",x);
  4670.         return(-1);
  4671.     }
  4672.     }
  4673.     debug(F100,"ttres set Kanji mode ok","",0);
  4674. #endif /* sony_news */
  4675.  
  4676.     tvtflg = 0;                /* Invalidate terminal mode settings */
  4677.     debug(F101,"ttres return code","",x);
  4678.     return(x);
  4679. }
  4680.  
  4681. #ifndef NOUUCP
  4682.  
  4683. /*  T T C H K P I D  --  Check lockfile pid  */
  4684. /*
  4685.   Read pid from lockfile named f, check that it's still valid.
  4686.   If so, return 1.
  4687.   On failure to read pid, return 1.
  4688.   Otherwise, try to delete lockfile f and return 0 if successful, else 1.
  4689. */
  4690. static int
  4691. ttchkpid(f) char *f; {
  4692.     int pid, mypid, x;
  4693.     pid = ttrpid(f);            /* Read pid from file. */
  4694.     if (pid > -1) {            /* If we were able to read the pid.. */
  4695.     debug(F101,"ttchkpid lock pid","",pid);
  4696.     errno = 0;            /* See if process still exists. */
  4697.     mypid = (int)getpid();        /* Get my own pid. */
  4698.     debug(F101,"ttchkpid my pid","",mypid);
  4699.     if (pid == mypid) {        /* It's me! */
  4700.         x = -1;            /* So I can delete it */
  4701.         errno = ESRCH;        /* pretend it's invalid */
  4702.     } else {            /* It's not me */
  4703.         x = kill((PID_T)pid, 0);    /* See if it's a live process */
  4704.         debug(F101,"ttchkpid kill errno","",errno);
  4705.     }
  4706.     debug(F101,"ttchkpid pid test","",x);
  4707.     if (x < 0 && errno == ESRCH) { /* pid is invalid */
  4708.         debug(F111,"removing stale lock",f,pid);
  4709.         if (!backgrd)
  4710.           printf("Removing stale lock %s (pid %d terminated)\n", f, pid);
  4711.         priv_on();
  4712.         x = unlink(f);        /* Remove the lockfile. */
  4713.         priv_off();
  4714.         debug(F111,"ttchkpid unlink",f,x);
  4715.         if (x > -1)
  4716.           return(0);        /* Device is not locked after all */
  4717.         else if (!backgrd)
  4718.           perror(f);
  4719.     }
  4720.     return(1);
  4721.     }
  4722.     return(1);                /* Failure to read pid */
  4723. }
  4724.  
  4725. #ifdef HPUX
  4726.  
  4727. /* Aliases (different drivers) for HP-UX dialout devices: */
  4728.  
  4729. static char *devprefix[] = { "tty", "ttyd", "cul", "cua", "cuad", "culd", "" };
  4730. static int ttydexists = 0;
  4731.  
  4732. #endif /* HPUX */
  4733.  
  4734. /*  T T R P I D  --  Read pid from lockfile "name" */
  4735.  
  4736. static int
  4737. ttrpid(name) char *name; {
  4738.     long len;
  4739.     int x, fd, pid;
  4740.     short spid;
  4741.     char buf[32];
  4742.  
  4743.     debug(F110,"ttrpid",name,0);
  4744.     if (!name) return(-1);
  4745.     if (!*name) return(-1);
  4746.     priv_on();
  4747.     len = zchki(name);            /* Get file length */
  4748.     priv_off();
  4749.     debug(F101,"ttrpid zchki","",len);
  4750.     if (len < 0)
  4751.       return(-1);
  4752.     if (len > 31)
  4753.       return(-1);
  4754.     priv_on();
  4755.     fd = open(name,O_RDONLY);        /* Try to open lockfile. */
  4756.     priv_off();
  4757.     debug(F101,"ttrpid fd","",fd);
  4758.     if (fd <= 0)
  4759.       return(-1);
  4760. /*
  4761.   Here we try to be flexible and allow for all different binary and string
  4762.   formats at runtime, rather than a specific format for each configuration
  4763.   hardwired at compile time.
  4764. */
  4765.     pid = -1;
  4766. #ifndef COHERENT
  4767. /*
  4768.   COHERENT uses a string PID but without leading spaces or 0's, so there is
  4769.   no way to tell from the file's length whether it contains a string or binary
  4770.   pid.  So for COHERENT only, we only allow string pids.  For all others, we
  4771.   decide based on the size of the lockfile.
  4772. */
  4773.     if (len > 4) {            /* If file > 4 bytes it's a string */
  4774. #endif /* COHERENT */
  4775.     x = read(fd,buf,(int)len);
  4776.     debug(F111,"ttrpid string read",buf,x);
  4777.     if (x < 0) {
  4778.         pid = -1;
  4779.     } else {
  4780.         buf[31] = '\0';
  4781.         x = sscanf(buf,"%d",&pid);    /* Get the integer pid from it. */
  4782.     }
  4783. #ifndef COHERENT
  4784.     } else if (len == 4) {        /* 4 bytes so binary */
  4785.     x = read(fd, (char *)&pid, 4);    /* Read the bytes into an int */
  4786.     debug(F101,"ttrpid integer read","",x);
  4787.     if (x < 4)
  4788.       pid = -1;
  4789.     } else if (len == 2) {        /* 2 bytes binary */
  4790.     x = read(fd, (char *)&spid, 2);    /* Read the bytes into a short */
  4791.     debug(F101,"ttrpid short read","",x);
  4792.     if (x < 2)
  4793.       pid = -1;
  4794.     else
  4795.       pid = spid;
  4796.     } else
  4797.       pid = -1;
  4798. #endif /* COHERENT */
  4799.     close(fd);                /* Close the lockfile */
  4800.     debug(F101,"ttrpid pid","",pid);
  4801.     return(pid);
  4802. }
  4803. #endif /* NOUUCP */
  4804.  
  4805. /*  T T L O C K  */
  4806.  
  4807. /*
  4808.   This function attempts to coordinate use of the communication device with
  4809.   other copies of Kermit and any other program that follows the UUCP
  4810.   device-locking conventions, which, unfortunately, vary among different UNIX
  4811.   implementations.  The idea is to look for a file of a certain name, the
  4812.   "lockfile", in a certain directory.  If such a file is found, then the line
  4813.   is presumed to be in use, and Kermit should not use it.  If no such file is
  4814.   found, Kermit attempts to create one so that other programs will not use the
  4815.   same line at the same time.  Because the lockfile and/or the directory it's
  4816.   in might lack write permission for the person running Kermit, Kermit could
  4817.   find itself running setuid to uucp or other user that does have the
  4818.   necessary permissions.  At startup, Kermit has changed its effective uid to
  4819.   the user's real uid, and so ttlock() must switch back to the original
  4820.   effective uid in order to create the lockfile, and then back again to the
  4821.   real uid to prevent unauthorized access to other directories or files owned
  4822.   by the user the program is setuid to.
  4823.  
  4824.   Totally rewritten for C-Kermit 5A to eliminate windows of vulnerability,
  4825.   based on suggestions from Warren Tucker.  Call with pointer to name of
  4826.   tty device.  Returns:
  4827.  
  4828.    0 on success
  4829.   -1 on failure
  4830.  
  4831.   Note: Once privileges are turned on using priv_on(), it is essential that
  4832.   they are turned off again before this function returns.
  4833. */
  4834. #ifdef SVR4                /* Lockfile uses device numbers. */
  4835. /*
  4836.   Although I can't find this in writing anywhere (e.g. in SVID for SVR4),
  4837.   it is the behavior of the "reference version" of SVR4, i.e. the Intel
  4838.   port from UNIX Systems Laboratories, then called Univel UnixWare,
  4839.   then called Novell UnixWare, then called SCO Unixware, then called Caldera
  4840.   Open UNIX...  It also makes much more sense than device-name-based lockfiles
  4841.   since there can be multiple names for the same device, symlinks, etc.
  4842. */
  4843. #ifndef NOLFDEVNO
  4844. #ifndef LFDEVNO                /* Define this for SVR4 */
  4845. #ifndef AIXRS                /* But not for RS/6000 AIX 3.2, etc. */
  4846. #ifndef BSD44                /* If anybody else needs it... */
  4847. #ifndef __386BSD__
  4848. #ifndef __FreeBSD__
  4849. #ifndef HPUX10
  4850. #ifndef IRIX51                /* SGI IRIX 5.1 or later */
  4851. #ifndef CK_SCOV5            /* SCO Open Server 5.0 */
  4852. #define LFDEVNO
  4853. #endif /* CK_SCOV5 */
  4854. #endif /* IRIX51 */
  4855. #endif /* HPUX10 */
  4856. #endif /* __FreeBSD__ */
  4857. #endif /* __386BSD__ */
  4858. #endif /* BSD44 */
  4859. #endif /* AIXRS */
  4860. #endif /* LFDEVNO */            /* ... define it here or on CC */
  4861. #endif /* NOLFDEVNO */
  4862. #endif /* SVR4 */            /* command line. */
  4863.  
  4864. #ifdef COHERENT
  4865. #define LFDEVNO
  4866. #endif /* COHERENT */
  4867.  
  4868. /*
  4869.   For platforms where the lockfile name is made from device/major/minor
  4870.   device number, as in SVR4.  Which, if we must have lockfiles at all, is
  4871.   by far the best format, since it eliminates all the confusion that stems
  4872.   from multiple names (or drivers) for the same port, not to mention
  4873.   symlinks.  It might even be a good idea to start using this form even
  4874.   on platforms where it's not supported, alongside the normal forms for those
  4875.   platforms, in order to get people used to it...
  4876. */
  4877. #ifdef LFDEVNO
  4878. #ifndef major                /* If we didn't find it */
  4879. #ifdef SVR4                /* then for Sys V R4 */
  4880. #include <sys/mkdev.h>            /* look here */
  4881. #else                    /* or for SunOS versions */
  4882. #ifdef SUNOS4                /* ... */
  4883. #include <sys/sysmacros.h>        /* look here */
  4884. #else                    /* Otherwise take a chance: */
  4885. #define    major(dev) ( (int) ( ((unsigned)(dev) >> 8) & 0xff))
  4886. #define    minor(dev) ( (int) ( (dev) & 0xff))
  4887. #endif /* SUNOS4 */
  4888. #endif /* SVR4 */
  4889. #endif /* major */
  4890. #endif /* LFDEVNO */
  4891.  
  4892. /* No advisory locks if F_TLOCK and F_ULOCK are not defined at this point */
  4893.  
  4894. #ifdef LOCKF
  4895. #ifndef F_TLOCK
  4896. #undef LOCKF
  4897. #ifndef NOLOCKF
  4898. #define NOLOCKF
  4899. #endif /* NOLOCKF */
  4900. #endif /* F_TLOCK */
  4901. #endif /* LOCKF */
  4902.  
  4903. #ifdef LOCKF
  4904. #ifndef F_ULOCK
  4905. #undef LOCKF
  4906. #ifndef NOLOCKF
  4907. #define NOLOCKF
  4908. #endif /* NOLOCKF */
  4909. #endif /* F_ULOCK */
  4910. #endif /* LOCKF */
  4911.  
  4912. static char linkto[DEVNAMLEN+1];
  4913. static char * linkdev = NULL;
  4914.  
  4915. #ifndef NOUUCP
  4916. #ifdef USETTYLOCK
  4917. #ifdef LOCK_DIR
  4918. char * uucplockdir = LOCK_DIR;
  4919. #else
  4920. char * uucplockdir = "";
  4921. #endif /* LOCK_DIR */
  4922. #else
  4923. #ifdef LOCK_DIR
  4924. char * uucplockdir = LOCK_DIR;
  4925. #else
  4926. char * uucplockdir = "";
  4927. #endif /* LOCK_DIR */
  4928. #endif /* USETTYLOCK */
  4929. #else
  4930. char * uucplockdir = "";
  4931. #endif /* NOUUCP */
  4932.  
  4933. #ifdef QNX                /* Only for QNX4 */
  4934. int                    /* Visible to outside world */
  4935. qnxopencount() {            /* Get QNX device open count */
  4936.     struct _dev_info_entry info;
  4937.     int x;
  4938.  
  4939.     x = -1;                /* Unknown */
  4940.     if (ttyfd > -1) {
  4941.     if (!dev_info(ttyfd, &info)) {
  4942.         debug(F101,"ttlock QNX open_count","",info.open_count);
  4943.         x = info.open_count;
  4944.     }
  4945.     }
  4946.     return(x);
  4947. }
  4948. #endif /* QNX */
  4949.  
  4950. char *
  4951. ttglckdir() {                /* Get Lockfile directory name */
  4952. #ifdef __OpenBSD__
  4953.     return("/var/spool/lock");
  4954. #else /* __OpenBSD__ */
  4955. #ifdef __FreeBSD__
  4956.     return("/var/spool/lock");
  4957. #else  /* __FreeBSD__ */
  4958. #ifdef LOCK_DIR
  4959.     char * s = LOCK_DIR;
  4960. #endif /* LOCK_DIR */
  4961. #ifdef NOUUCP
  4962.     return("");
  4963. #else  /* NOUUCP */
  4964. #ifdef LOCK_DIR
  4965.     return(s);
  4966. #else  /* LOCK_DIR */
  4967.     return("");
  4968. #endif /* LOCK_DIR */
  4969. #endif /* NOUUCP */
  4970. #endif /* __FreeBSD__ */
  4971. #endif /* __OpenBSD__ */
  4972. }
  4973.  
  4974. static int
  4975. ttlock(ttdev) char *ttdev; {
  4976.  
  4977.     int x, n;
  4978.     int islink = 0;
  4979.  
  4980. #ifdef NOUUCP
  4981.     debug(F100,"ttlock NOUUCP","",0);
  4982.     ckstrncpy(flfnam,"NOLOCK",FLFNAML);
  4983.     haslock = 1;
  4984.     return(0);
  4985. #else /* !NOUUCP */
  4986.  
  4987. #ifdef USETTYLOCK
  4988.     haslock = 0;                        /* Not locked yet. */
  4989.     *flfnam = '\0';            /* Lockfile name is empty. */
  4990.     if (!strncmp(ttdev,"/dev/",5) && ttdev[5])
  4991.       ckstrncpy(lockname,ttdev+5,DEVNAMLEN);
  4992.     else
  4993.       ckstrncpy(lockname,ttdev,DEVNAMLEN);
  4994. /*
  4995.   This might be overkill, but it's not clear from the man pages whether
  4996.   ttylock() can be called without calling ttylocked() first, since the doc
  4997.   says that ttylocked() removes any stale lockfiles, but it does not say this
  4998.   about ttylock().  Also the docs don't say what ttylocked() returns in the
  4999.   case when it finds and removes a stale lockfile.  So one or both calls to
  5000.   to ttylocked() might be superfluous, but they should do no harm.  Also I'm
  5001.   assuming that we have to do all the same ID swapping, etc, with these
  5002.   routines as we do without them.  Thus the priv_on/off() sandwich.
  5003. */
  5004. #ifdef USE_UU_LOCK
  5005.     priv_on();                /* Turn on privs */
  5006.     x = uu_lock(lockname);        /* Try to set the lock */
  5007.     priv_off();                /* Turn privs off */
  5008.     debug(F111,"ttlock uu_lock",lockname,x);
  5009.     switch (x) {
  5010.       case UU_LOCK_INUSE:
  5011.     return(-2);
  5012.       case UU_LOCK_OK:
  5013. #ifdef BSD44
  5014.     ckmakmsg(flfnam,FLFNAML,"/var/spool/lock/LCK..",lockname,NULL,NULL);
  5015. #endif /* BSD44 */
  5016.     haslock = 1;
  5017.     return(0);
  5018.       default:
  5019.     return(-1);
  5020.     }
  5021. #else  /* USE_UU_LOCK */
  5022.     priv_on();                /* Turn on privs */
  5023.     if (ttylocked(lockname)) {        /* This should remove any stale lock */
  5024.     if (ttylocked(lockname)) {    /* so check again. */
  5025.         priv_off();
  5026.         return(-5);            /* Still locked, fail. */
  5027.     }
  5028.     }
  5029.     x = ttylock(lockname);        /* Lock it. */
  5030.     priv_off();                /* Turn off privs */
  5031.  
  5032.     debug(F111,"ttlock lockname",lockname,x);
  5033.     if (x > -1) {
  5034.     /*
  5035.       We don't really know the name of the lockfile, but
  5036.       this is what the man page says it is.  In USETTYLOCK
  5037.           builds, it is used only for display by SHOW COMM.
  5038.     */
  5039.     ckmakmsg(flfnam,FLFNAML,"/etc/locks/LCK..",lockname,NULL,NULL);
  5040.     haslock = 1;
  5041.     }
  5042.     return(x);
  5043. #endif /* USE_UU_LOCK */
  5044. #else  /* Systems that don't have ttylock()... */
  5045.  
  5046. #ifndef HPUX
  5047.  
  5048.     int lockfd;                /* File descriptor for lock file. */
  5049.     PID_T pid;                /* Process id of this process. */
  5050.     int tries;                /* How many times we've tried... */
  5051.     struct stat devbuf;            /* For device numbers (SVR4). */
  5052.  
  5053. #ifdef PIDSTRING
  5054.     char pid_str[32];            /* My pid in string format. */
  5055. #endif /* PIDSTRING */
  5056.  
  5057.     char *device, *devname;
  5058.  
  5059. #define LFNAML 256            /* Max length for lock file name. */
  5060.     char lockfil[LFNAML];        /* Lock file name */
  5061. #ifdef RTAIX
  5062.     char lklockf[LFNAML];        /* Name for link to lock file  */
  5063. #endif /* RTAIX */
  5064. #ifdef CKSYMLINK
  5065.     char symlock[LFNAML];        /* Name for symlink lockfile name */
  5066. #endif /* CKSYMLINK */
  5067.     char tmpnam[LFNAML+30];        /* Temporary lockfile name. */
  5068.     char *lockdir = LOCK_DIR;        /* Defined near top of this file, */
  5069.                     /* or on cc command line. */
  5070.     haslock = 0;                        /* Not locked yet. */
  5071.     *flfnam = '\0';            /* Lockfile name is empty. */
  5072.     lock2[0] = '\0';            /* Clear secondary lockfile name. */
  5073.     pid = getpid();            /* Get id of this process. */
  5074.  
  5075. /*  Construct name of lockfile and temporary file */
  5076.  
  5077. /*  device  = name of tty device without the path, e.g. "ttyh8" */
  5078. /*  lockfil = name of lock file, without path, e.g. "LCK..ttyh8" */
  5079.  
  5080.     device = ((devname = xxlast(ttdev,'/')) != NULL ? devname+1 : ttdev);
  5081.  
  5082.     if (stat(ttdev,&devbuf) < 0)
  5083.       return(-1);
  5084.  
  5085. #ifdef CKSYMLINK
  5086.     islink = 1;                /* Assume it's a symlink */
  5087.     linkto[0] = '\0';            /* But we don't know to what */
  5088. #ifdef COMMENT
  5089. /*
  5090.   This is undependable.  If it worked it would save the readlink call if
  5091.   we knew the device name was not a link.
  5092. */
  5093. #ifdef S_ISLNK
  5094.     islink = S_ISLNK(devbuf.st_mode);
  5095.     debug(F101,"ttlock stat S_ISLNK","",islink);
  5096. #endif /* S_ISLNK */
  5097. #endif /* COMMENT */
  5098.     if (islink) {
  5099.     n = readlink(ttdev,linkto,DEVNAMLEN); /* See if it's a link */
  5100.     debug(F111,"ttlock readlink",ttdev,n);
  5101.     if (n > -1)            /* It is */
  5102.       linkto[n] = '\0';
  5103.     else                /* It's not */
  5104.       islink = 0;
  5105.     debug(F111,"ttlock link",linkto,islink);
  5106.     }
  5107.     if (islink) {
  5108.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  5109.     debug(F110,"ttlock linkdev",linkdev,0);
  5110.     }
  5111. #endif /* CKSYMLINK */
  5112.  
  5113. /*
  5114.   On SCO platforms, if we don't have a symlink, then let's pretend the
  5115.   name given for the device is a symlink, because later we will change
  5116.   the name if it contains any uppercase characters.
  5117. */
  5118. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  5119.     if (!islink) {
  5120.     islink = 1;
  5121.     ckstrncpy(linkto,ttdev,DEVNAMLEN);
  5122.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  5123.     debug(F110,"ttlock linkdev",linkdev,0);
  5124.     }
  5125. #else
  5126. #ifdef M_XENIX                /* SCO Xenix or UNIX */
  5127.     if (!islink) {
  5128.     islink = 1;
  5129.     ckstrncpy(linkto,ttdev,DEVNAMLEN);
  5130.     linkdev = (devname = xxlast(linkto,'/')) ? devname + 1 : linkto;
  5131.     debug(F110,"ttlock linkdev",linkdev,0);
  5132.     }
  5133. #endif /* M_XENIX */
  5134. #endif /* CK_SCOV5 */
  5135.  
  5136. #ifdef ISIII                /* Interactive System III, PC/IX */
  5137.     ckstrncpy(lockfil, device, DEVNAMLEN);
  5138. #else  /* not ISIII */
  5139. #ifdef LFDEVNO                /* Lockfilename has device numbers. */
  5140. #ifdef COHERENT
  5141.     sprintf(lockfil,"LCK..%d.%d",    /* SAFE */
  5142.         major(devbuf.st_rdev),       /* major device number */
  5143.         0x1f & minor(devbuf.st_rdev)); /* minor device number */
  5144. #else
  5145.     /* Note: %d changed to %u in 8.0 -- %u is part of SVID for SVR4 */
  5146.     /* Lockfile name format verified to agree with Solaris cu, Dec 2001 */
  5147.     sprintf(lockfil,"LK.%03u.%03u.%03u", /* SAFE */
  5148.         major(devbuf.st_dev),    /* device */
  5149.         major(devbuf.st_rdev),    /* major device number */
  5150.         minor(devbuf.st_rdev));    /* minor device number */
  5151. #endif /* COHERENT */
  5152. #else  /* Not LFDEVNO */
  5153. #ifdef PTX                /* Dynix PTX */
  5154.     if ((device != &ttdev[5]) && (strncmp(ttdev,"/dev/",5) == 0)) {
  5155.     if ((int)strlen(device) + 8 < LFNAML)
  5156.       sprintf(lockfil,"LCK..%.3s%s", &ttdev[5], device);
  5157.     else
  5158.       ckstrncpy(lockfil,"LOCKFILE_NAME_TOO_LONG",LFNAML);
  5159.     } else
  5160. #endif /* PTX */
  5161.       if ((int)strlen(device) + 5 < LFNAML)
  5162.     sprintf(lockfil,"LCK..%s", device);
  5163.       else
  5164.     ckstrncpy(lockfil,"LOCKFILE_NAME_TOO_LONG",LFNAML);
  5165. #ifdef RTAIX
  5166.     ckstrncpy(lklockf,device,DEVNAMLEN);
  5167. #endif /* RTAIX */
  5168. #ifdef CKSYMLINK
  5169.     symlock[0] = '\0';
  5170.     if (islink)
  5171.       ckmakmsg(symlock,LFNAML, "LCK..", linkdev, NULL, NULL);
  5172. #endif /* CKSYMLINK */
  5173. #endif /* LFDEVNO */
  5174. #endif /* ISIII */
  5175.  
  5176. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  5177.     {
  5178.     /* Lowercase the entire filename. */
  5179.         /* SCO says we must do this in V5.0 and later. */
  5180.     /* BUT... watch out for devices -- like Digiboard Portserver */
  5181.     /* That can have hundreds of ports... */
  5182.     char *p = (char *)(lockfil + 5);
  5183.     while (*p) { if (isupper(*p)) *p = (char) tolower(*p); p++; }
  5184.     }
  5185. #ifdef CKSYMLINK
  5186.     if (islink) {            /* If no change */
  5187.     if (!strcmp(lockfil,symlock)) {    /* then no second lockfile needed */
  5188.         islink = 0;
  5189.         symlock[0] = '\0';
  5190.     }
  5191.     }
  5192. #endif /* CKSYMLINK */
  5193. #else
  5194. #ifdef M_XENIX                /* SCO Xenix or UNIX */
  5195.     {
  5196.     int x; char c;
  5197.     x = (int)strlen(lockfil) - 1;    /* Get last letter of device name. */
  5198.     if (x > 0) {            /* If it's uppercase, lower it. */
  5199.         c = lockfil[x];
  5200.         if (c >= 'A' && c <= 'Z') lockfil[x] += ('a' - 'A');
  5201.     }
  5202.     }
  5203. #ifdef CKSYMLINK
  5204.     if (islink) {
  5205.     if (!strcmp(lockfil,symlock)) {    /* No change */
  5206.         islink = 0;            /* so no second lockfile */
  5207.         symlock[0] = '\0';
  5208.     }
  5209.     }
  5210. #endif /* CKSYMLINK */
  5211. #endif /* M_XENIX */
  5212. #endif /* CK_SCOV5 */
  5213.  
  5214. /*  flfnam = full lockfile pathname, e.g. "/usr/spool/uucp/LCK..ttyh8" */
  5215. /*  tmpnam = temporary unique, e.g. "/usr/spool/uucp/LTMP..pid" */
  5216.  
  5217.     ckmakmsg(flfnam,LFNAML,lockdir,"/",lockfil,NULL);
  5218.  
  5219. #ifdef RTAIX
  5220.     ckmakmsg(lkflfn,FLFNAML,lockdir,"/",lklockf,NULL);
  5221. #endif /* RTAIX */
  5222.  
  5223. #ifndef LFDEVNO
  5224. #ifdef CKSYMLINK
  5225.     /* If it's a link then also make a lockfile for the real name */
  5226.     debug(F111,"ttlock link symlock",symlock,islink);
  5227.     if (islink && symlock[0]) {
  5228.     /* But only if the lockfile names would be different. */
  5229.     /* WARNING: They won't be, e.g. for /dev/ttyd2 => /hw/ttys/ttyd2 */
  5230.     ckmakmsg(lock2,FLFNAML,lockdir,"/",symlock,NULL);
  5231.     debug(F110,"ttlock lock2",lock2,0);
  5232.     if (!strcmp(lock2,flfnam)) {    /* Are lockfile names the same? */
  5233.         debug(F100,"ttlock lock2 cleared","",0);
  5234.         lock2[0] = '\0';        /* Clear secondary lockfile name. */
  5235.     }
  5236.     }
  5237. #endif /* CKSYMLINK */
  5238. #endif /* LFDEVNO */
  5239.  
  5240.     sprintf(tmpnam,"%s/LTMP.%05d",lockdir,(int) pid); /* safe */
  5241.     debug(F110,"ttlock flfnam",flfnam,0);
  5242.     debug(F110,"ttlock tmpnam",tmpnam,0);
  5243.  
  5244.     priv_on();                /* Turn on privileges if possible. */
  5245.     lockfd = creat(tmpnam, 0444);    /* Try to create temp lock file. */
  5246.     if (lockfd < 0) {            /* Create failed. */
  5247.     debug(F111,"ttlock creat failed",tmpnam,errno);
  5248.     if (errno == ENOENT) {
  5249.         perror(lockdir);
  5250.         printf("UUCP not installed or Kermit misconfigured\n");
  5251.     } else {
  5252.         if (!quiet)
  5253.           perror(lockdir);
  5254.         unlink(tmpnam);        /* Get rid of the temporary file. */
  5255.     }
  5256.     priv_off();            /* Turn off privileges!!! */
  5257.     return(-1);            /* Return failure code. */
  5258.     }
  5259. /* Now write the pid into the temp lockfile in the appropriate format */
  5260.  
  5261. #ifdef PIDSTRING            /* For Honey DanBer UUCP, */
  5262.     sprintf(                /* write PID as decimal string */
  5263.         pid_str,
  5264. #ifdef LINUXFSSTND            /* The "Linux File System Standard" */
  5265. #ifdef FSSTND10                /* Version 1.0 calls for */
  5266.         "%010d\n",            /* leading zeros */
  5267. #else                    /* while version 1.2 calls for */
  5268.         "%10d\n",            /* leading spaces */
  5269. #endif /* FSSTND10 */
  5270. #else
  5271. #ifdef COHERENT
  5272.         "%d\n",            /* with leading nothing */
  5273. #else
  5274.         "%10d\n",            /* with leading blanks */
  5275. #endif /* COHERENT */
  5276. #endif /* LINUXFSSTND */
  5277.         (int) pid
  5278.         );                /* safe */
  5279.     write(lockfd, pid_str, 11);
  5280.     debug(F111,"ttlock hdb pid string",pid_str,(int) pid);
  5281.  
  5282. #else /* Not PIDSTRING, use integer PID */
  5283.  
  5284.     write(lockfd, (char *)&pid, sizeof(pid) );
  5285.     debug(F101,"ttlock pid","",(int) pid);
  5286.  
  5287. #endif /* PIDSTRING */
  5288.  
  5289. /* Now try to rename the temp file to the real lock file name. */
  5290. /* This will fail if a lock file of that name already exists.  */
  5291.  
  5292.     close(lockfd);            /* Close the temp lockfile. */
  5293.     chmod(tmpnam,0444);            /* Permission for a valid lock. */
  5294.     tries = 0;
  5295.     while (!haslock && tries++ < 2) {
  5296.     haslock = (link(tmpnam,flfnam) == 0); /* Create a link to it. */
  5297.     if (haslock) {                  /* If we got the lockfile */
  5298. #ifdef RTAIX
  5299.         link(flfnam,lkflfn);
  5300. #endif /* RTAIX */
  5301. #ifdef CKSYMLINK
  5302. #ifndef LFDEVNO
  5303.         if (islink && lock2[0])
  5304.           link(flfnam,lock2);
  5305. #endif /* LFDEVNO */
  5306. #endif /* CKSYMLINK */
  5307.  
  5308. #ifdef COMMENT
  5309. /* Can't do this any more because device is not open yet so no ttyfd. */
  5310. #ifdef LOCKF
  5311. /*
  5312.   Advisory file locking works on SVR4, so we use it.  In fact, it is
  5313.   necessary in some cases, e.g. when SLIP is involved.  But it still doesn't
  5314.   seem to prevent multiple users accessing the same device by different names.
  5315. */
  5316.             while (lockf(ttyfd, F_TLOCK, 0L) != 0) {
  5317.                 debug(F111, "ttlock lockf returns errno", "", errno);
  5318.                 if ((++tries >= 3) || (errno != EAGAIN)) {
  5319.                     x = unlink(flfnam); /* remove the lockfile */
  5320. #ifdef RTAIX
  5321.             unlink(lkflfn);    /* And any links to it... */
  5322. #endif /* RTAIX */
  5323. #ifdef CKSYMLINK
  5324. #ifndef LFDEVNO
  5325.             if (islink && lock2[0])
  5326.               unlink(lock2);    /* ditto... */
  5327. #endif /* LFDEVNO */
  5328. #endif /* CKSYMLINK */
  5329.                     debug(F111,"ttlock unlink",flfnam,x);
  5330.                     haslock = 0;
  5331.             break;
  5332.         }
  5333.                 sleep(2);
  5334.         }
  5335.         if (haslock)        /* If we got an advisory lock */
  5336. #endif /* LOCKF */
  5337. #endif /* COMMENT */
  5338.           break;            /* We're done. */
  5339.  
  5340.     } else {            /* We didn't create a new lockfile. */
  5341.         priv_off();
  5342.         if (ttchkpid(flfnam)) {    /* Check existing lockfile */
  5343.         priv_on();        /* cause ttchkpid turns priv_off... */
  5344.         unlink(tmpnam);        /* Delete the tempfile */
  5345.         debug(F100,"ttlock found tty locked","",0);
  5346.         priv_off();        /* Turn off privs */
  5347.         return(-2);        /* Code for device is in use. */
  5348.         }
  5349.         priv_on();
  5350.     }
  5351.     }
  5352.     unlink(tmpnam);            /* Unlink (remove) the temp file. */
  5353.     priv_off();                /* Turn off privs */
  5354.     return(haslock ? 0 : -1);        /* Return link's return code. */
  5355.  
  5356. #else /* HPUX */
  5357.  
  5358. /*
  5359.   HP-UX gets its own copy of this routine, modeled after the observed behavior
  5360.   of the HP-UX 'cu' program.  HP-UX serial device names consist of a base name
  5361.   such as "tty", "ttyd", "cua", "cul", "cuad", or "culd", followed by a unit
  5362.   designator which is a string of digits, possibly containing an imbedded
  5363.   letter "p".  Examples (for base name "tty"):
  5364.  
  5365.      /dev/tty0, /dev/tty00, dev/ttyd00, /dev/tty0p0
  5366.  
  5367.   According to the HP-UX UUCP manual of 1988, the "0p0" notation has been
  5368.   used on Series 800 since HP-UX 2.00, and the "non-p" notation was used
  5369.   on other models.  In HP-UX 10.00, "0p0" notation was adopted for all models.
  5370.   However, we make and enforce no such distinctions; either notation is
  5371.   accepted on any model or HP-UX version as a valid unit designator.
  5372.  
  5373.   If a valid unit is specified (as opposed to a designer name or symlink), we
  5374.   check for all aliases of the given unit according to the devprefix[] array.
  5375.   If no lockfiles are found for the given unit, we can have the device; we
  5376.   create a lockfile LCK..name in the lockfile directory appropriate for the
  5377.   HP-UX version (/var/spool/locks for 10.00 and later, /usr/spool/uucp for
  5378.   9.xx and earlier).  If it is a "cua" or "cul" device, a second lockfile is
  5379.   created with the "ttyd" prefix.  This is exactly what cu does.
  5380.  
  5381.   If the "set line" device does not have a valid unit designator, then it is
  5382.   used literally and no synomyms are searched for and only one lockfile is
  5383.   created.
  5384.  
  5385.   -fdc, March 1998.
  5386. */
  5387. #define LFNAML 80            /* Max length for lock file name. */
  5388.  
  5389.     int lockfd;                /* File descriptor for lock file. */
  5390.     PID_T pid;                /* Process ID of this process. */
  5391.     int fpid;                /* pid found in existing lockfile. */
  5392.     int tries;                /* How many times we've tried... */
  5393.     int i, k;                /* Workers */
  5394.  
  5395.     char *device, *devname;        /* "/dev/xxx", "xxx" */
  5396.     char *unit, *p;            /* <instance>p<port> part of xxx */
  5397.  
  5398.     char lockfil[LFNAML];        /* Lockfile name (no path) */
  5399.     char tmpnam[LFNAML];        /* Temporary lockfile name. */
  5400.  
  5401. #ifdef HPUX10                /* Lockfile directory */
  5402.     char *lockdir = "/var/spool/locks";    /* Always this for 10.00 and higher */
  5403. #else  /* HP-UX 9.xx and below */
  5404. #ifdef LOCK_DIR
  5405.     char *lockdir = LOCK_DIR;        /* Defined near top of this file */
  5406. #else
  5407.     char *lockdir = "/usr/spool/uucp";    /* or not... */
  5408. #endif /* LOCK_DIR */
  5409. #endif /* HPUX10 */
  5410.  
  5411.     haslock = 0;                        /* Not locked yet. */
  5412.     *flfnam = '\0';            /* Lockfile name is empty. */
  5413.     lock2[0] = '\0';            /* Second one too. */
  5414.     pid = getpid();            /* Get my process ID */
  5415. /*
  5416.   Construct name of lockfile and temporary file...
  5417.   device  = name of tty device without the path, e.g. "tty0p0"
  5418.   lockfil = name of lock file, without path, e.g. "LCK..tty0p0"
  5419. */
  5420.     device = ((devname = xxlast(ttdev,'/')) != NULL ? devname+1 : ttdev);
  5421.     debug(F110,"TTLOCK device",device,0);
  5422.     ckmakmsg(lockfil,LFNAML,"LCK..",device,NULL,NULL);
  5423.  
  5424.     k = 0;                /* Assume device is not locked */
  5425.     n = 0;                /* Digit counter */
  5426.     unit = device;            /* Unit = <instance>p<port> */
  5427.     while (*unit && !isdigit(*unit))    /* Search for digit... */
  5428.       unit++;
  5429.     p = unit;                /* Verify <num>p<num> format... */
  5430.     debug(F110,"TTLOCK unit 1",unit,0);
  5431. /*
  5432.   The unit number is recognized as:
  5433.   (a) any sequence of digits that runs to the end of the string.
  5434.   (b) any (a) that includes one and only one letter "p", with at least
  5435.       one digit before and after it.
  5436. */
  5437.     while (isdigit(*p)) p++, n++;    /* Get a run of digits */
  5438.     if (*p && n > 0) {            /* Have a "p"? */
  5439.     if (*p == 'p' && isdigit(*(p+1))) {
  5440.         p++;
  5441.         n = 0;
  5442.         while (isdigit(*p)) p++, n++;
  5443.     }
  5444.     }
  5445.     if (n == 0 || *p) unit = "";
  5446.     debug(F110,"TTLOCK unit 2",unit,0);
  5447.  
  5448.     if (*unit) {            /* Device name has unit number. */
  5449.     /* The following loop not only searches for the various lockfile    */
  5450.     /* synonyms, but also removes all -- not just one -- stale lockfile */
  5451.     /* for the device, should there be more than one.  See ttchkpid().  */
  5452.     ttydexists = 0;
  5453.     for (i = 0; *devprefix[i]; i++) { /* For each driver... */
  5454.         /* Make device name */
  5455.         ckmakmsg(lock2,FLFNAML,"/dev/",devprefix[i],unit,NULL);
  5456.         priv_on();            /* Privs on */
  5457.         k = zchki(lock2) != -1;    /* See if device exists */
  5458.         priv_off();            /* Privs off */
  5459.         debug(F111,"TTLOCK exist",lock2,k);
  5460.             if (k) {
  5461.         if (!strcmp(devprefix[i],"ttyd")) /* ttyd device exists */
  5462.           ttydexists = 1;
  5463.         /* Make lockfile name */
  5464.         ckmakmsg(lock2,FLFNAML,lockdir,"/LCK..",devprefix[i],unit);
  5465.         debug(F110,"TTLOCK checking",lock2,0);
  5466.         priv_on();        /* Privs on */
  5467.         k = zchki(lock2) != -1;    /* See if lockfile exists */
  5468.         priv_off();        /* Privs off */
  5469.         debug(F111,"TTLOCK check for lock A",lock2,k);
  5470.         if (k) if (ttchkpid(lock2)) { /* If pid still active, fail. */
  5471.             ckstrncpy(flfnam,lock2,FLFNAML);
  5472.             return(-2);
  5473.         }
  5474.         }
  5475.     }
  5476.     } else {                /* Some other device-name format */
  5477.     /* This takes care of symbolic links, etc... */
  5478.     /* But does not chase them down! */
  5479.     ckmakmsg(lock2,FLFNAML,lockdir,"/LCK..",device,NULL);
  5480.     priv_on();
  5481.     k = zchki(lock2) != -1;        /* Check for existing lockfile */
  5482.     priv_off();
  5483.     debug(F111,"TTLOCK check for lock B",lock2,k);
  5484.     if (k) if (ttchkpid(lock2)) {    /* Check pid from lockfile */
  5485.         ckstrncpy(flfnam,lock2,FLFNAML);
  5486.         debug(F110,"TTLOCK in use",device,0);
  5487.         debug(F101,"TTLOCK returns","",-2);
  5488.         return(-2);
  5489.     }
  5490.     }
  5491. /*
  5492.   Get here only if there is no (more) lockfile, so now we make one (or two)...
  5493.   flfnam = full lockfile pathname, e.g. "/usr/spool/uucp/LCK..cul0p0".
  5494.   tmpnam = unique temporary filname, e.g. "/usr/spool/uucp/LTMP..pid".
  5495. */
  5496.     ckmakmsg(flfnam,FLFNAML,lockdir,"/",lockfil,NULL); /* SET LINE device */
  5497.  
  5498.     /* If dialout device, also make one for corresponding dialin device */
  5499.     lock2[0] = '\0';
  5500.     if (!strncmp(device,"cu",2) && *unit && ttydexists)
  5501.       ckmakmsg(lock2,FLFNAML,lockdir,"/LCK..ttyd",unit,NULL);
  5502.  
  5503.     if ((int)strlen(lockdir)+12 < LFNAML)
  5504.       sprintf(tmpnam,"%s/LTMP.%05d",lockdir,(int) pid); /* Make temp name */
  5505. #ifdef DEBUG
  5506.     if (deblog) {
  5507.     debug(F110,"TTLOCK flfnam",flfnam,0);
  5508.     debug(F110,"TTLOCK lock2",lock2,0);
  5509.     debug(F110,"TTLOCK tmpnam",tmpnam,0);
  5510.     }
  5511. #endif /* DEBUG */
  5512. /*
  5513.    Lockfile permissions...
  5514.    444 is standard, HP-UX 10.00 uses 664.  It doesn't matter.
  5515.    Kermit uses 444; the difference lets us tell whether Kermit created
  5516.    the lock file.
  5517. */
  5518.     priv_on();                /* Turn on privileges. */
  5519.     lockfd = creat(tmpnam, 0444);    /* Try to create temporary file. */
  5520.     if (lockfd < 0) {            /* Create failed. */
  5521.     debug(F111,"TTLOCK creat failed",tmpnam,errno);
  5522.     if (errno == ENOENT) {
  5523.         perror(lockdir);
  5524.         printf("UUCP not installed or Kermit misconfigured\n");
  5525.     } else {
  5526.         if (!quiet)
  5527.           perror(lockdir);
  5528.         unlink(tmpnam);        /* Get rid of the temporary file. */
  5529.     }
  5530.     priv_off();            /* Turn off privileges!!! */
  5531.     debug(F101,"TTLOCK returns","",-1);
  5532.     return(-1);            /* Return failure code. */
  5533.     }
  5534.     debug(F110,"TTLOCK temp ok",tmpnam,0);
  5535.  
  5536. /* Now write our pid into the temp lockfile in integer format. */
  5537.  
  5538.     i = write(lockfd, (char *)&pid, sizeof(pid));
  5539.  
  5540. #ifdef DEBUG
  5541.     if (deblog) {
  5542.     debug(F101,"TTLOCK pid","",pid);
  5543.     debug(F101,"TTLOCK sizeof pid","",sizeof(pid));
  5544.     debug(F101,"TTLOCK write pid returns","",i);
  5545.     }
  5546. #endif /* DEBUG */
  5547.  
  5548. /*
  5549.   Now try to rename the temporary file to the real lockfile name.
  5550.   This will fail if a lock file of that name already exists, which
  5551.   will catch race conditions with other users.
  5552. */
  5553.     close(lockfd);            /* Close the temp lockfile. */
  5554.     chmod(tmpnam,0444);
  5555.  
  5556.     tries = 0;
  5557.     while (!haslock && tries++ < 2) {
  5558.     haslock = (link(tmpnam,flfnam) == 0); /* Create a link to it. */
  5559.     debug(F101,"TTLOCK link","",haslock);
  5560.     if (haslock) {            /* If we made the lockfile... */
  5561.  
  5562. #ifdef COMMENT
  5563. /* We can't do this any more because we don't have a file descriptor yet. */
  5564. #ifdef LOCKF                /* Can be canceled with -DNOLOCKF */
  5565. /*
  5566.   Create an advisory lock on the device through its file descriptor.
  5567.   This code actually seems to work.  If it is executed, and then another
  5568.   process tries to open the same device under a different name to circumvent
  5569.   the lockfile, they get a "device busy" error.
  5570. */
  5571.         debug(F100,"TTLOCK LOCKF code...","",0);
  5572.             while ( lockf(ttyfd, F_TLOCK, 0L) != 0 ) {
  5573.                 debug(F111, "TTLOCK lockf error", "", errno);
  5574.                 if ((++tries >= 3) || (errno != EAGAIN)) {
  5575.                     x = unlink(flfnam); /* Remove the lockfile */
  5576.             if (errno == EACCES && !quiet)
  5577.               printf("Device already locked by another process\n");
  5578.                     haslock = 0;
  5579.             break;
  5580.         }
  5581.                 sleep(2);
  5582.         }
  5583. #endif /* LOCKF */
  5584. #endif /* COMMENT */
  5585.  
  5586.         if (haslock) {        /* If we made the lockfile ... */
  5587.         if (lock2[0]) {        /* if there is to be a 2nd lockfile */
  5588.             lockfd = creat(lock2, 0444); /* Create it */
  5589.             debug(F111,"TTLOCK lock2 creat", lock2, lockfd);
  5590.             if (lockfd > -1) {    /* Created OK, write pid. */
  5591.             write(lockfd, (char *)&pid, sizeof(pid) );
  5592.             close(lockfd);    /* Close and */
  5593.             chmod(lock2, 0444); /* set permissions. */
  5594.             } else {         /* Not OK, but don't fail. */
  5595.             lock2[0] = '\0'; /* Just remember it's not there. */
  5596.             }
  5597.         }
  5598.         break;            /* and we're done. */
  5599.         }
  5600.     }
  5601.     }
  5602.     unlink(tmpnam);            /* Unlink (remove) the temp file. */
  5603.     priv_off();                /* Turn off privs */
  5604.     i = haslock ? 0 : -1;        /* Our return value */
  5605.     debug(F101,"TTLOCK returns","",i);
  5606.     return(i);
  5607. #endif /* HPUX */
  5608. #endif /* USETTYLOCK */
  5609. #endif /* !NOUUCP */
  5610. }
  5611.  
  5612. /*  T T U N L O C K  */
  5613.  
  5614. static int
  5615. ttunlck() {                             /* Remove UUCP lockfile(s). */
  5616. #ifndef NOUUCP
  5617.     int x;
  5618.  
  5619.     debug(F111,"ttunlck",flfnam,haslock);
  5620.  
  5621. #ifdef USETTYLOCK
  5622.  
  5623.     if (haslock && *flfnam) {
  5624.     int x;
  5625.     priv_on();            /* Turn on privs */
  5626. #ifdef USE_UU_LOCK
  5627.     x = uu_unlock(lockname);
  5628. #else  /* USE_UU_LOCK */
  5629.     x = ttyunlock(lockname);    /* Try to unlock */
  5630. #endif /* USE_UU_LOCK */
  5631.     priv_off();            /* Turn off privs */
  5632.     if (x < 0 && !quiet)
  5633.       printf("Warning - Can't remove lockfile: %s\n", flfnam);
  5634.  
  5635.     *flfnam = '\0';            /* Erase the name. */
  5636.     haslock = 0;
  5637.     return(0);
  5638.     }
  5639.  
  5640. #else  /* No ttylock()... */
  5641.  
  5642.     if (haslock && *flfnam) {
  5643.     /* Don't remove lockfile if we didn't make it ourselves */
  5644.     if ((x = ttrpid(flfnam)) != (int)getpid()) {
  5645.         debug(F111,"ttunlck lockfile seized",flfnam,x);
  5646.         printf("Warning - Lockfile %s seized by pid %d\n",
  5647.            flfnam,
  5648.            x
  5649.            );
  5650.         return(0);
  5651.     }
  5652.     priv_on();            /* Turn privileges on.  */
  5653.     errno = 0;
  5654.     x = unlink(flfnam);        /* Remove the lockfile. */
  5655.     debug(F111,"ttunlck unlink",flfnam,x);
  5656.     if (x < 0) {
  5657.         if (errno && !quiet)
  5658.           perror(ttnmsv);
  5659.         printf("Warning - Can't remove lockfile: %s\n", flfnam);
  5660.     }
  5661.     haslock = 0;
  5662.     *flfnam = '\0';            /* Erase the name. */
  5663.  
  5664. #ifdef RTAIX
  5665.     errno = 0;
  5666.     x = unlink(lkflfn);        /* Remove link to lockfile */
  5667.     debug(F111,"ttunlck AIX link unlink",lkflfn,x);
  5668.     if (x < 0) {
  5669.         if (errno && !quiet)
  5670.           perror(ttnmsv);
  5671.         printf("Warning - Can't remove link to lockfile: %s\n", lkflfn);
  5672.     }
  5673.     *lkflfn = '\0';
  5674. #else
  5675.     if (lock2[0]) {            /* If there is a second lockfile, */
  5676.         errno = 0;
  5677.         x = unlink(lock2);        /*  remove it too. */
  5678.         debug(F111,"ttunlck lock2 unlink",lock2,x);
  5679.         if (x < 0) {
  5680.         if (errno && !quiet)
  5681.           perror(ttnmsv);
  5682.         printf("Warning - Can't remove secondary lockfile: %s\n",
  5683.                lock2
  5684.                );
  5685.         }
  5686.         lock2[0] = '\0';        /* Forget its name. */
  5687.     }
  5688. #endif /* RTAIX */
  5689.  
  5690. #ifdef COMMENT
  5691. #ifdef LOCKF
  5692.         (VOID) lockf(ttyfd, F_ULOCK, 0L); /* Remove advisory lock */
  5693. #endif /* LOCKF */
  5694. #endif /* COMMENT */
  5695.  
  5696.     priv_off();            /* Turn privileges off. */
  5697.     }
  5698. #endif /* USETTYLOCK */
  5699. #endif /* !NOUUCP */
  5700.     return(0);
  5701. }
  5702.  
  5703. /*
  5704.   4.3BSD-style UUCP line direction control.
  5705.   (Stan Barber, Rice U, 1980-something...)
  5706. */
  5707. #ifndef NOUUCP
  5708. #ifdef ACUCNTRL
  5709. VOID
  5710. acucntrl(flag,ttname) char *flag, *ttname; {
  5711.     char x[DEVNAMLEN+32], *device, *devname;
  5712.  
  5713.     if (strcmp(ttname,CTTNAM) == 0 || xlocal == 0) /* If not local, */
  5714.       return;                /* just return. */
  5715.     device = ((devname = xxlast(ttname,'/')) != NULL ? devname+1 : ttname);
  5716.     if (strncmp(device,"LCK..",4) == 0) device += 5;
  5717.     ckmakmsg(x,DEVNAMLEN+32,"/usr/lib/uucp/acucntrl ",flag," ",device);
  5718.     debug(F110,"called ",x,0);
  5719.     zsyscmd(x);
  5720. }
  5721. #endif /* ACUCNTRL */
  5722. #endif /* NOUUCP */
  5723.  
  5724. /*
  5725.   T T H F L O W  --  Set or Reset hardware flow control.
  5726.  
  5727.   This is an attempt to collect all hardware-flow-control related code
  5728.   into a single module.  Thanks to Rick Sladkey and John Kohl for lots of
  5729.   help here.  Overview:
  5730.  
  5731.   Hardware flow control is not supported in many UNIX implementions.  Even
  5732.   when it is supported, there is no (ha ha) "standard" for the programming
  5733.   interface.  In general, 4.3BSD and earlier (sometimes), 4.4BSD, System V,
  5734.   SunOS, AIX, etc, have totally different methods.  (And, not strictly
  5735.   relevant here, the programming interface often brings one only to a no-op
  5736.   in the device driver!)
  5737.  
  5738.   Among all these, we have two major types of APIs: those in which hardware
  5739.   flow control is determined by bits in the same termio/termios/sgtty mode
  5740.   word(s) that are used for controlling such items as CBREAK vs RAW mode, and
  5741.   which are also used by the ttvt(), ttpkt(), conbin(), and concb() routines
  5742.   for changing terminal modes.  And those that use entirely different
  5743.   mechanisms.
  5744.  
  5745.   In the first category, it is important that any change in the mode bits be
  5746.   reflected in the relevant termio(s)/sgtty structure, so that subsequent
  5747.   changes to that structure do not wipe out the effects of this routine.  That
  5748.   is why a pointer, attrs, to the appropriate structure is passed as a
  5749.   parameter to this routine.
  5750.  
  5751.   The second category should give us no worries, since any changes to hardware
  5752.   flow control accomplished by this routine should not affect the termio(s)/
  5753.   sgtty structures, and therefore will not be undone by later changes to them.
  5754.  
  5755.   The second argument, status, means to turn on hardware flow control if
  5756.   nonzero, and to turn it off if zero.
  5757.  
  5758.   Returns: 0 on apparent success, -1 on probable failure.
  5759. */
  5760.  
  5761. /*
  5762.   The following business is for BSDI, where it was discovered that two
  5763.   separate bits, CCTS_OFLOW and CRTS_IFLOW, are used in hardware flow control,
  5764.   but CTRSCTS is defined (in <termios.h>) to be just CCTS_OFLOW rather both
  5765.   bits, so hwfc only works in one direction if you use CRTSCTS to control it.
  5766.   Other 4.4BSD-based Unixes such as FreeBSD 4.1, which use these two bits,
  5767.   define CRTSCTS correctly.
  5768. */
  5769. #ifdef FIXCRTSCTS
  5770. #ifdef CRTSCTS
  5771. #ifdef CCTS_OFLOW
  5772. #ifdef CRTS_IFLOW
  5773. #undef CRTSCTS
  5774. #define CRTSCTS (CRTS_IFLOW|CCTS_OFLOW)
  5775. #endif /* CRTS_IFLOW */
  5776. #endif /* CCTS_OFLOW */
  5777. #endif /* CRTSCTS */
  5778. #endif /* FIXCRTSCTS */
  5779.  
  5780. static int
  5781. tthflow(flow, status, attrs)
  5782.     int flow,                /* Type of flow control (ckcdeb.h) */
  5783.     status;                /* Nonzero = turn it on */
  5784.                     /* Zero = turn it off */
  5785. #ifdef BSD44ORPOSIX            /* POSIX or BSD44 */
  5786.     struct termios *attrs;
  5787. #else                    /* System V */
  5788. #ifdef ATTSV
  5789. #ifdef ATT7300
  5790. #ifdef UNIX351M
  5791. /* AT&T UNIX 3.51m can set but not test for hardware flow control */
  5792. #define RTSFLOW CTSCD
  5793. #define CTSFLOW CTSCD
  5794. #endif /* ATT7300 */
  5795. #endif /* UNIX351M */
  5796.     struct termio *attrs;
  5797. #else                    /* BSD, V7, etc */
  5798.     struct sgttyb *attrs;        /* sgtty info... */
  5799. #endif /* ATTSV */
  5800. #endif /* BSD44ORPOSIX */
  5801. /* tthflow */ {
  5802.  
  5803.     int x = 0;                /* tthflow() return code */
  5804.  
  5805. #ifdef Plan9
  5806.     return p9tthflow(flow, status);
  5807. #else
  5808.  
  5809. #ifndef OXOS                /* NOT Olivetti X/OS... */
  5810. /*
  5811.   For SunOS 4.0 and later in the BSD environment ...
  5812.  
  5813.   The declarations are copied and interpreted from the System V header files,
  5814.   so we don't actually have to pull in all the System V junk when building
  5815.   C-Kermit for SunOS in the BSD environment, which would be dangerous because
  5816.   having those symbols defined would cause us to take the wrong paths through
  5817.   the code.  The code in this section is used in both the BSD and Sys V SunOS
  5818.   versions.
  5819. */
  5820. #ifdef SUNOS41
  5821. /*
  5822.   In SunOS 4.1 and later, we use the POSIX calls rather than ioctl calls
  5823.   because GNU CC uses different formats for the _IOxxx macros than regular CC;
  5824.   the POSIX forms work for both.  But the POSIX calls are not available in
  5825.   SunOS 4.0.
  5826. */
  5827. #define CRTSCTS 0x80000000        /* RTS/CTS flow control */
  5828. #define TCSANOW 0            /* Do it now */
  5829.  
  5830.     struct termios {
  5831.     unsigned long c_iflag;        /* Input modes */
  5832.     unsigned long c_oflag;        /* Output modes */
  5833.     unsigned long c_cflag;        /* Control modes */
  5834.     unsigned long c_lflag;        /* Line discipline modes */
  5835.     char c_line;
  5836.     CHAR c_cc[17];
  5837.     };
  5838.     struct termios temp;
  5839.  
  5840. _PROTOTYP( int tcgetattr, (int, struct termios *) );
  5841. _PROTOTYP( int tcsetattr, (int, int, struct termios *) );
  5842. /*
  5843.   When CRTSCTS is set, SunOS won't do output unless both CTS and CD are
  5844.   asserted.  So we don't set CRTSCTS unless CD is up.  This should be OK,
  5845.   since we don't need RTS/CTS during dialing, and after dialing is complete,
  5846.   we should have CD.  If not, we still communicate, but without RTS/CTS.
  5847. */
  5848.     int mflags;                /* Modem signal flags */
  5849.  
  5850. #ifdef NETCMD
  5851.     if (ttpipe) return(0);
  5852. #endif /* NETCMD */
  5853. #ifdef NETPTY
  5854.     if (ttpty) return(0);
  5855. #endif /* NETPTY */
  5856.  
  5857.     debug(F101,"tthflow SUNOS41 entry status","",status);
  5858.     if (!status) {            /* Turn hard flow off */
  5859.     if (tcgetattr(ttyfd, &temp) > -1 && /* Get device attributes */
  5860.         (temp.c_cflag & CRTSCTS)) { /* Check for RTS/CTS */
  5861.         temp.c_cflag &= ~CRTSCTS;    /* It's there, remove it */
  5862.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5863.     }
  5864.     } else {                /* Turn hard flow on */
  5865.     if (ioctl(ttyfd,TIOCMGET,&mflags) > -1 && /* Get modem signals */
  5866.         (mflags & TIOCM_CAR)) {        /* Check for CD */
  5867.         debug(F100,"tthflow SunOS has CD","",0);
  5868.         if (tcgetattr(ttyfd, &temp) > -1 && /* Get device attributes */
  5869.         !(temp.c_cflag & CRTSCTS)) { /* Check for RTS/CTS */
  5870.         temp.c_cflag |= CRTSCTS;    /* Not there, add it */
  5871.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5872.         }
  5873.     } else {
  5874.         x = -1;
  5875.         debug(F100,"tthflow SunOS no CD","",0);
  5876.     }
  5877.     }
  5878. #else
  5879. #ifdef QNX
  5880.     struct termios temp;
  5881. #ifdef NETCMD
  5882.     if (ttpipe) return(0);
  5883. #endif /* NETCMD */
  5884. #ifdef NETPTY
  5885.     if (ttpty) return(0);
  5886. #endif /* NETPTY */
  5887.     debug(F101,"tthflow QNX entry status","",status);
  5888.     if (tcgetattr(ttyfd, &temp) > -1) {    /* Get device attributes */
  5889.     if (!status) {            /* Turn hard flow off */
  5890.         if ((temp.c_cflag & (IHFLOW|OHFLOW)) == (IHFLOW|OHFLOW)) {
  5891.         temp.c_cflag &= ~(IHFLOW|OHFLOW); /* It's there, remove it */
  5892.         attrs->c_cflag &= ~(IHFLOW|OHFLOW);
  5893.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5894.         }
  5895.     } else {            /* Turn hard flow on */
  5896.         if ((temp.c_cflag & (IHFLOW|OHFLOW)) != (IHFLOW|OHFLOW)) {
  5897.         temp.c_cflag |= (IHFLOW|OHFLOW); /* Not there, add it */
  5898.         temp.c_iflag &= ~(IXON|IXOFF);   /* Bye to IXON/IXOFF */
  5899.         ttraw.c_lflag |= IEXTEN;         /* Must be on */
  5900.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5901.         attrs->c_cflag |= (IHFLOW|OHFLOW);
  5902.         attrs->c_iflag &= ~(IXON|IXOFF);
  5903.         }
  5904.     }
  5905.     } else {
  5906.     x = -1;
  5907.     debug(F100, "tthflow QNX getattr fails", "", 0);
  5908.     }
  5909. #else
  5910. #ifdef POSIX_CRTSCTS
  5911. /*
  5912.   POSIX_CRTSCTS is defined in ckcdeb.h or on CC command line.
  5913.   Note: Do not assume CRTSCTS is a one-bit field!
  5914. */
  5915.     struct termios temp;
  5916. #ifdef NETCMD
  5917.     if (ttpipe) return(0);
  5918. #endif /* NETCMD */
  5919. #ifdef NETPTY
  5920.     if (ttpty) return(0);
  5921. #endif /* NETPTY */
  5922.     debug(F101,"tthflow POSIX_CRTSCTS entry status","",status);
  5923.     errno = 0;
  5924.     x = tcgetattr(ttyfd, &temp);
  5925.     debug(F111,"tthflow POSIX_CRTSCTS tcgetattr",ckitoa(x),errno);
  5926.     errno = 0;
  5927.     if (x < 0) {
  5928.     x = -1;
  5929.     } else {
  5930.     if (!status) {            /* Turn hard flow off */
  5931.         if (
  5932. #ifdef COMMENT
  5933.         /* This can fail because of sign extension */
  5934.         /* e.g. in Linux where it's Bit 31 */
  5935.         (temp.c_cflag & CRTSCTS) == CRTSCTS
  5936. #else
  5937.         (temp.c_cflag & CRTSCTS) != 0
  5938. #endif /* COMMENT */
  5939.         ) {
  5940.         temp.c_cflag &= ~CRTSCTS; /* It's there, remove it */
  5941.         attrs->c_cflag &= ~CRTSCTS;
  5942.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5943.         debug(F111,"tthflow POSIX_CRTSCTS OFF tcsetattr",
  5944.               ckitoa(x),errno);
  5945.         } else {            /* John Dunlap 2010-01-26 */
  5946.         debug(F001,
  5947.               "tthflow before forcing off attrs CRTSCTS",
  5948.               "",
  5949.               attrs->c_cflag&CRTSCTS
  5950.               );
  5951.         attrs->c_cflag &= ~CRTSCTS; /* force it off if !status */
  5952.         debug(F001,
  5953.               "tthflow after forcing off attrs CRTSCTS",
  5954.               "",
  5955.               attrs->c_cflag&CRTSCTS
  5956.               );
  5957.         }
  5958.     } else {            /* Turn hard flow on */
  5959.         if (
  5960. #ifdef COMMENT
  5961.         /* This can fail because of sign extension */
  5962.         (temp.c_cflag & CRTSCTS) != CRTSCTS
  5963. #else
  5964.         (temp.c_cflag & CRTSCTS) == 0
  5965. #endif /* COMMENT */
  5966.         ) {
  5967.         temp.c_cflag |= CRTSCTS; /* Not there, add it */
  5968.         temp.c_iflag &= ~(IXON|IXOFF|IXANY); /* Bye to IXON/IXOFF */
  5969.         x = tcsetattr(ttyfd,TCSANOW,&temp);
  5970.         debug(F111,"tthflow POSIX_CRTSCTS ON tcsetattr",
  5971.               ckitoa(x),errno);
  5972.         attrs->c_cflag |= CRTSCTS;
  5973.         attrs->c_iflag &= ~(IXON|IXOFF|IXANY);
  5974.         }
  5975.     }
  5976.     }
  5977. #else
  5978. #ifdef SUNOS4
  5979. /*
  5980.   SunOS 4.0 (and maybe earlier?).  This code is dangerous because it
  5981.   prevents compilation with GNU gcc, which uses different formats for the
  5982.   _IORxxx macros than regular cc.  SunOS 4.1 and later can use the POSIX
  5983.   routines above, which work for both cc and gcc.
  5984. */
  5985. #define TCGETS _IOR(T, 8, struct termios) /* Get modes into termios struct */
  5986. #define TCSETS _IOW(T, 9, struct termios) /* Set modes from termios struct */
  5987. #define CRTSCTS 0x80000000          /* RTS/CTS flow control */
  5988.  
  5989.     struct termios {
  5990.     unsigned long c_iflag;        /* Input modes */
  5991.     unsigned long c_oflag;        /* Output modes */
  5992.     unsigned long c_cflag;        /* Control modes */
  5993.     unsigned long c_lflag;        /* Line discipline modes */
  5994.     char c_line;
  5995.     CHAR c_cc[17];
  5996.     };
  5997.     struct termios temp;
  5998. #ifdef NETCMD
  5999.     if (ttpipe) return(0);
  6000. #endif /* NETCMD */
  6001. #ifdef NETPTY
  6002.     if (ttpty) return(0);
  6003. #endif /* NETPTY */
  6004.     debug(F101,"tthflow entry status","",status);
  6005.     if (ioctl(ttyfd,TCGETS,&temp) > -1) { /* Get terminal modes. */
  6006.     if (status) {            /* Turn hard flow on */
  6007.         temp.c_cflag |= CRTSCTS;    /* Add RTS/CTS to them. */
  6008.         x = ioctl(ttyfd,TCSETS,&temp); /* Set them again. */
  6009.         attrs->c_cflag |= CRTSCTS;    /* Add to global info. */
  6010.     } else {            /* Turn hard flow off */
  6011.         temp.c_cflag &= ~CRTSCTS;
  6012.         x = ioctl(ttyfd,TCSETS,&temp);
  6013.         attrs->c_cflag &= ~CRTSCTS;
  6014.     }
  6015.     }
  6016. #else                    /* Not SunOS 4.0 or later */
  6017. #ifdef AIXRS                /* IBM AIX RS/6000 */
  6018. #ifndef AIX41                /* But only pre-4.x == SVR4 */
  6019. #ifdef NETCMD
  6020.     if (ttpipe) return(0);
  6021. #endif /* NETCMD */
  6022. #ifdef NETPTY
  6023.     if (ttpty) return(0);
  6024. #endif /* NETPTY */
  6025.     if (status) {
  6026.     if ((x = ioctl(ttyfd, TXADDCD, "rts")) < 0 && errno != EBUSY)
  6027.       debug(F100,"hardflow TXADDCD (rts) error", "", 0);
  6028.     } else {
  6029.     if ((x = ioctl(ttyfd, TXDELCD, "rts")) < 0 && errno != EINVAL)
  6030.       debug(F100,"hardflow TXDELCD (rts) error", "", 0);
  6031.     }
  6032. #endif /* AIX41 */
  6033. #else                    /* Not AIX RS/6000 */
  6034.  
  6035. #ifdef ATTSV                /* System V... */
  6036.  
  6037. #ifdef CK_SCOV5                /* SCO Open Server 5.0 */
  6038. #define CK_SCOUNIX
  6039. #else
  6040. #ifdef M_UNIX                /* SCO UNIX 3.2v4.x or earlier */
  6041. #define CK_SCOUNIX
  6042. #endif /* M_UNIX */
  6043. #endif /* CK_SCOV5 */
  6044.  
  6045. #ifdef SCO_FORCE_RTSXOFF
  6046. #ifdef CK_SCOUNIX            /* But not SCO OpenServer 5.0.4 */
  6047. #ifdef SCO_OSR504            /* or later... */
  6048. #undef CK_SCOUNIX
  6049. #endif /* SCO_OSR504 */
  6050. #endif /* CK_SCOUNIX */
  6051. #endif /* SCO_FORCE_RTSXOFF */
  6052.  
  6053. #ifdef CK_SCOUNIX
  6054. #ifdef POSIX
  6055.     struct termios temp;
  6056. #ifdef NETCMD
  6057.     if (ttpipe) return(0);
  6058. #endif /* NETCMD */
  6059. #ifdef NETPTY
  6060.     if (ttpty) return(0);
  6061. #endif /* NETPTY */
  6062.     debug(F101,"tthflow SCOUNIX POSIX entry status","",status);
  6063.     errno = 0;
  6064.     x = tcgetattr(ttyfd, &temp);
  6065.     debug(F111,"tthflow SCO UNIX POSIX tcgetattr",ckitoa(x),errno);
  6066. #else /* POSIX */
  6067.     struct termio temp;
  6068. #ifdef NETCMD
  6069.     if (ttpipe) return(0);
  6070. #endif /* NETCMD */
  6071. #ifdef NETPTY
  6072.     if (ttpty) return(0);
  6073. #endif /* NETPTY */
  6074.     debug(F101,"tthflow SCOUNIX non-POSIX entry status","",status);
  6075.     x = ioctl(ttyfd, TCGETA, &temp);
  6076.     debug(F111,"tthflow SCO UNIX non-POSIX TCGETA",ckitoa(x),errno);
  6077. #endif /* POSIX */
  6078. /*
  6079.   This is not really POSIX, since POSIX does not deal with hardware flow
  6080.   control, but we are using the POSIX APIs.  In fact, RTSFLOW and CTSFLOW
  6081.   are defined in termio.h, but within #ifndef _POSIX_SOURCE..#endif.  So
  6082.   let's try forcing their definitions here.
  6083. */
  6084. #ifndef CTSFLOW
  6085. #define CTSFLOW 0020000
  6086.     debug(F101,"tthflow SCO defining CTSFLOW","",CTSFLOW);
  6087. #else
  6088.     debug(F101,"tthflow SCO CTSFLOW","",CTSFLOW);
  6089. #endif /* CTSFLOW */
  6090. #ifndef RTSFLOW
  6091. #define RTSFLOW 0040000
  6092.     debug(F101,"tthflow SCO defining RTSFLOW","",RTSFLOW);
  6093. #else
  6094.     debug(F101,"tthflow SCO RTSFLOW","",RTSFLOW);
  6095. #endif /* RTSFLOW */
  6096. #ifndef ORTSFL
  6097. #define ORTSFL 0100000
  6098.     debug(F101,"tthflow SCO defining ORTSFL","",ORTSFL);
  6099. #else
  6100.     debug(F101,"tthflow SCO ORTSFL","",ORTSFL);
  6101. #endif /* ORTSFL */
  6102.  
  6103.     if (x != -1) {
  6104.     if (status) {            /* Turn it ON */
  6105.         temp.c_cflag |= RTSFLOW|CTSFLOW;
  6106.         attrs->c_cflag |= RTSFLOW|CTSFLOW;
  6107. #ifdef ORTSFL
  6108.         temp.c_cflag &= ~ORTSFL;
  6109.         attrs->c_cflag &= ~ORTSFL;
  6110. #endif /* ORTSFL */
  6111.         temp.c_iflag &= ~(IXON|IXOFF|IXANY);
  6112.         attrs->c_iflag &= ~(IXON|IXOFF|IXANY);
  6113.     } else {            /* Turn it OFF */
  6114. #ifdef ORTSFL
  6115.         temp.c_cflag &= ~(RTSFLOW|CTSFLOW|ORTSFL);
  6116.         attrs->c_cflag &= ~(RTSFLOW|CTSFLOW|ORTSFL);
  6117. #else  /* ORTSFL */
  6118.         temp.c_cflag &= ~(RTSFLOW|CTSFLOW);
  6119.         attrs->c_cflag &= ~(RTSFLOW|CTSFLOW);
  6120. #endif /* ORTSFL */
  6121.     }
  6122. #ifdef POSIX
  6123.     x = tcsetattr(ttyfd, TCSADRAIN, &temp);
  6124. #else
  6125.     x = ioctl(ttyfd, TCSETA, &temp);
  6126. #endif /* POSIX */
  6127.     debug(F101,"tthflow SCO set modes","",x);
  6128.     }
  6129. #else /* Not SCO UNIX */
  6130. #ifdef NETCMD
  6131.     if (ttpipe) return(0);
  6132. #endif /* NETCMD */
  6133. #ifdef NETPTY
  6134.     if (ttpty) return(0);
  6135. #endif /* NETPTY */
  6136.     if (!status) {            /* Turn it OFF */
  6137. #ifdef RTSXOFF
  6138.     debug(F100,"tthflow ATTSV RTS/CTS OFF","",0);
  6139.     rctsx.x_hflag &= ~(RTSXOFF|CTSXON);
  6140. #ifdef TCSETX
  6141.     x = ioctl(ttyfd,TCSETX,&rctsx);
  6142.     debug(F101,"tthflow ATTSV TCSETX OFF","",x);
  6143. #else
  6144.     x = -1
  6145.     debug(F100,"tthflow TCSETX not defined","",0);
  6146. #endif /* TCSETX */
  6147. #else
  6148.     debug(F100,"tthflow ATTSV RTSXOFF not defined","",0);
  6149. #endif /* RTSXOFF */
  6150. #ifdef DTRXOFF
  6151.     debug(F100,"tthflow ATTSV DTR/CD OFF","",0);
  6152.     rctsx.x_hflag &= ~(DTRXOFF|CDXON);
  6153.     x = ioctl(ttyfd,TCSETX,&rctsx);
  6154.     debug(F101,"tthflow ATTSV DTRXOFF OFF","",x);
  6155. #else
  6156.     debug(F100,"tthflow ATTSV DTRXOFF not defined","",0);
  6157. #endif /* DTRXOFF */
  6158.     } else {                /* Turn it ON. */
  6159.     if (flow == FLO_RTSC) {    /* RTS/CTS Flow control... */
  6160.         debug(F100,"tthflow ATTSV RTS/CTS ON","",0);
  6161. #ifdef RTSXOFF
  6162.         /* This is the preferred way, according to SVID3 */
  6163. #ifdef TCGETX
  6164.         x = ioctl(ttyfd,TCGETX,&rctsx);
  6165.         debug(F101,"tthflow TCGETX","",x);
  6166.         if (x > -1) {
  6167.         rctsx.x_hflag |= RTSXOFF | CTSXON;
  6168.         x = ioctl(ttyfd,TCSETX,&rctsx);
  6169.         debug(F100,"tthflow ATTSV ioctl","",x);
  6170.         }
  6171. #else
  6172.         debug(F100,"tthflow TCGETX not defined","",0);
  6173.         x = -1
  6174. #endif /* TCGETX */
  6175. #else
  6176.         debug(F100,"tthflow RTSXOFF not defined","",0);
  6177.         x = -1;
  6178. #endif /* RTSXOFF */
  6179.     } else if (flow == FLO_DTRC) {    /* DTR/CD Flow control... */
  6180.         debug(F100,"tthflow ATTSV DTR/CD ON","",0);
  6181. #ifdef DTRXOFF
  6182.         /* This is straight out of SVID R4 */
  6183.         if (ioctl(ttyfd,TCGETX,&rctsx) > -1) {
  6184.         rctsx.x_hflag &= ~(DTRXOFF|CDXON);
  6185.         x = ioctl(ttyfd,TCSETX,&rctsx);
  6186.         }
  6187. #else
  6188.         debug(F100,"tthflow ATTSV DTRXOFF not defined","",0);
  6189.         x = -1;
  6190. #endif /* DTRXOFF */
  6191.     }
  6192.     }
  6193. #endif /* CK_SCOUNIX */
  6194.  
  6195. #else /* not System V... */
  6196.  
  6197. #ifdef CK_DTRCTS
  6198. #ifdef LDODTR
  6199. #ifdef LDOCTS
  6200. #ifdef NETCMD
  6201.     if (ttpipe) return(0);
  6202. #endif /* NETCMD */
  6203. #ifdef NETPTY
  6204.     if (ttpty) return(0);
  6205. #endif /* NETPTY */
  6206.     x = LDODTR | LDOCTS;        /* Found only on UTEK? */
  6207.     if (flow == FLO_DTRT && status) {    /* Use hardware flow control */
  6208.     if (lmodef) {
  6209.         x = ioctl(ttyfd,TIOCLBIS,&x);
  6210.         if (x < 0) {
  6211.             debug(F100,"hardflow TIOCLBIS error","",0);
  6212.         } else {
  6213.         lmodef++;
  6214.         debug(F100,"hardflow TIOCLBIS ok","",0);
  6215.         }
  6216.     }
  6217.     } else {
  6218.     if (lmodef) {
  6219.         x = ioctl(ttyfd,TIOCLBIC,&x);
  6220.         if (x < 0) {
  6221.             debug(F100,"hardflow TIOCLBIC error","",0);
  6222.         } else {
  6223.         lmodef++;
  6224.         debug(F100,"hardflow TIOCLBIC ok","",0);
  6225.         }
  6226.     }
  6227.     }
  6228. #endif /* LDODTR */
  6229. #endif /* LDOCTS */
  6230. #endif /* CK_DTRCTS */
  6231. #endif /* ATTSV */
  6232. #endif /* AIXRS */
  6233. #endif /* SUNOS4 */
  6234. #endif /* QNX */
  6235. #endif /* POSIX_CRTSCTS */
  6236. #endif /* SUNOS41 */
  6237.  
  6238. #else /* OXOS */
  6239.  
  6240.     struct termios temp;        /* Olivetti X/OS ... */
  6241.  
  6242. #ifdef NETCMD
  6243.     if (ttpipe) return(0);
  6244. #endif /* NETCMD */
  6245. #ifdef NETPTY
  6246.     if (ttpty) return(0);
  6247. #endif /* NETPTY */
  6248.     x = ioctl(ttyfd,TCGETS,&temp);
  6249.     if (x == 0) {
  6250.     temp.c_cflag &= ~(CRTSCTS|CDTRCTS|CBRKFLOW|CDTRDSR|CRTSDSR);
  6251.     if (status) {
  6252.         switch (flow) {
  6253.           case FLO_RTSC: temp.c_cflag |= CRTSCTS; /* RTS/CTS (hard) */
  6254.         break;
  6255.           case FLO_DTRT: temp.c_cflag |= CDTRCTS; /* DTR/CTS (hard) */
  6256.         break;
  6257.         }
  6258.     }
  6259.     x = ioctl(ttyfd,TCSETS,&temp);
  6260.     }
  6261. #endif /* OXOS */
  6262.     return(x);
  6263.  
  6264. #endif /* Plan9 */
  6265. }
  6266.  
  6267. /*  T T P K T  --  Condition the communication line for packets */
  6268. /*                 or for modem dialing */
  6269.  
  6270. /*
  6271.   If called with speed > -1, also set the speed.
  6272.   Returns 0 on success, -1 on failure.
  6273.  
  6274.   NOTE: the "xflow" parameter is supposed to be the currently selected
  6275.   type of flow control, but for historical reasons, this parameter is also
  6276.   used to indicate that we are dialing.  Therefore, when the true flow
  6277.   control setting is needed, we access the external variable "flow", rather
  6278.   than trusting our "xflow" argument.
  6279. */
  6280. int
  6281. #ifdef CK_ANSIC
  6282. ttpkt(long speed, int xflow, int parity)
  6283. #else
  6284. ttpkt(speed,xflow,parity) long speed; int xflow, parity;
  6285. #endif /* CK_ANSIC */
  6286. /* ttpkt */ {
  6287. #ifndef NOLOCAL
  6288.     int s2;
  6289.     int s = -1;
  6290. #endif /* NOLOCAL */
  6291.     int x;
  6292.     extern int flow;            /* REAL flow-control setting */
  6293.  
  6294.     if (ttyfd < 0) return(-1);          /* Not open. */
  6295.  
  6296.     debug(F101,"ttpkt parity","",parity);
  6297.     debug(F101,"ttpkt xflow","",xflow);
  6298.     debug(F101,"ttpkt speed","",(int) speed);
  6299.  
  6300.     ttprty = parity;                    /* Let other tt functions see these. */
  6301.     ttspeed = speed;            /* Make global copy for this module */
  6302.     ttpmsk = ttprty ? 0177 : 0377;    /* Parity stripping mask */
  6303. #ifdef PARSENSE
  6304.     needpchk = ttprty ? 0 : 1;        /* Parity check needed? */
  6305. #else
  6306.     needpchk = 0;
  6307. #endif /* PARSENSE */
  6308.  
  6309.     debug(F101,"ttpkt ttpmsk","",ttpmsk);
  6310.     debug(F101,"ttpkt netconn","",netconn);
  6311.  
  6312. #ifdef NETCONN                /* No mode-changing for telnet */
  6313.     if (netconn) {
  6314. #ifdef TCPSOCKET
  6315. #ifdef TCP_NODELAY
  6316.         if (ttnet == NET_TCPB) {    /* But turn off Nagle */
  6317.             extern int tcp_nodelay;
  6318.             nodelay_sav = tcp_nodelay;
  6319.             no_delay(ttyfd,1);
  6320.         }
  6321. #endif /* TCP_NODELAY */
  6322. #ifdef TN_COMPORT
  6323.         if (istncomport()) {
  6324.             int rc = -1;
  6325.             if (tvtflg == 0 && speed == ttspeed && flow == ttflow
  6326.                  /* && ttcarr == curcarr */ ) {
  6327.                 debug(F100,"ttpkt modes already set, skipping...","",0);
  6328.                 return(0);        /* Already been called. */
  6329.             }
  6330.             if (flow != ttflow) {
  6331.                 if ((rc = tnsetflow(flow)) < 0)
  6332.           return(rc);
  6333.                 ttflow = flow;
  6334.             }
  6335.             if (speed != ttspeed) {
  6336.                 if (speed <= 0) 
  6337.           speed = tnc_get_baud();
  6338.                 else if ((rc = tnc_set_baud(speed)) < 0)
  6339.           return(rc);
  6340.                 ttspeed = speed;
  6341.             }
  6342.             tnc_set_datasize(8);
  6343.         tnc_set_stopsize(stopbits);
  6344.  
  6345. #ifdef HWPARITY
  6346.             if (hwparity) {
  6347.                 switch (hwparity) {
  6348.           case 'e':            /* Even */
  6349.                     debug(F100,"ttres 8 bits + even parity","",0);
  6350.                     tnc_set_parity(3);
  6351.                     break;
  6352.           case 'o':            /* Odd */
  6353.                     debug(F100,"ttres 8 bits + odd parity","",0);
  6354.                     tnc_set_parity(2);
  6355.                     break;
  6356.           case 'm':            /* Mark */
  6357.                     debug(F100,"ttres 8 bits + invalid parity: mark","",0);
  6358.                     tnc_set_parity(4);
  6359.                     break;
  6360.           case 's':            /* Space */
  6361.                     debug(F100,"ttres 8 bits + invalid parity: space","",0);
  6362.                     tnc_set_parity(5);
  6363.                     break;
  6364.                 }
  6365.             } else 
  6366. #endif /* HWPARITY */
  6367.         {
  6368.                 tnc_set_parity(1);              /* None */
  6369.             }
  6370.             tvtflg = 0;
  6371.             return(0);
  6372.         }
  6373. #endif /* TN_COMPORT */
  6374. #endif /* TCPSOCKET */
  6375.         tvtflg = 0;
  6376.         return(0);
  6377.     }
  6378. #endif /* NETCONN */
  6379. #ifdef NETCMD
  6380.     if (ttpipe) return(0);
  6381. #endif /* NETCMD */
  6382. #ifdef NETPTY
  6383.     if (ttpty) return(0);
  6384. #endif /* NETPTY */
  6385.  
  6386. #ifndef Plan9
  6387.     if (ttfdflg && !isatty(ttyfd)) return(0);
  6388. #endif /* Plan9 */
  6389.  
  6390. #ifdef COHERENT
  6391. #define SVORPOSIX
  6392. #endif /* COHERENT */
  6393.  
  6394. #ifndef SVORPOSIX            /* Berkeley, V7, etc. */
  6395. #ifdef LPASS8
  6396. /*
  6397.  For some reason, with BSD terminal drivers, you can't set FLOW to XON/XOFF
  6398.  after having previously set it to NONE without closing and reopening the
  6399.  device.  Unless there's something I overlooked below...
  6400. */
  6401.     if (ttflow == FLO_NONE && flow == FLO_XONX && xlocal == 0) {
  6402.     debug(F101,"ttpkt executing horrible flow kludge","",0);
  6403.     ttclos(0);            /* Close it */
  6404.     x = 0;
  6405.     ttopen(ttnmsv,&x,ttmdm,0);    /* Open it again */
  6406.     }
  6407. #endif /* LPASS8 */
  6408. #endif /* SVORPOSIX */
  6409.  
  6410. #ifdef COHERENT                /* This must be vestigial since we */
  6411. #undef SVORPOSIX            /* reverse it a few lines below... */
  6412. #endif /* COHERENT */
  6413.  
  6414.     if (xflow != FLO_DIAL && xflow != FLO_DIAX)
  6415.       ttflow = xflow;            /* Now make this available too. */
  6416.  
  6417. #ifndef NOLOCAL
  6418.     if (xlocal) {
  6419.     s2 = (int) (speed / 10L);    /* Convert bps to cps */
  6420.     debug(F101,"ttpkt calling ttsspd","",s2);
  6421.     s = ttsspd(s2);            /* Check and set the speed */
  6422.     debug(F101,"ttpkt ttsspd result","",s);
  6423.      carrctl(&ttraw, xflow != FLO_DIAL /* Carrier control */
  6424.         && (ttcarr == CAR_ON || (ttcarr == CAR_AUT && ttmdm != 0)));
  6425.     tvtflg = 0;            /* So ttvt() will work next time */
  6426.     }
  6427. #endif /* NOLOCAL */
  6428.  
  6429. #ifdef COHERENT
  6430. #define SVORPOSIX
  6431. #endif /* COHERENT */
  6432.  
  6433. #ifndef SVORPOSIX            /* BSD section */
  6434.     if (flow == FLO_RTSC ||        /* Hardware flow control */
  6435.     flow == FLO_DTRC ||
  6436.     flow == FLO_DTRT) {
  6437.     tthflow(flow, 1, &ttraw);
  6438.     debug(F100,"ttpkt hard flow, TANDEM off, RAW on","",0);
  6439.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6440.     ttraw.sg_flags |= RAW;        /* Enter raw mode */
  6441.     } else if (flow == FLO_NONE) {    /* No flow control */
  6442.     debug(F100,"ttpkt no flow, TANDEM off, RAW on","",0);
  6443.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6444.     tthflow(flow, 0, &ttraw);    /* Turn off any hardware f/c too */
  6445.     ttraw.sg_flags |= RAW;        /* Enter raw mode */
  6446.     } else if (flow == FLO_KEEP) {    /* Keep device's original setting */
  6447.     debug(F100,"ttpkt keeping original TANDEM","",0);
  6448.     ttraw.sg_flags &= ~TANDEM;
  6449.     ttraw.sg_flags |= (ttold.sg_flags & TANDEM);
  6450.     /* NOTE: We should also handle hardware flow control here! */
  6451.     }
  6452.  
  6453. /* SET FLOW XON/XOFF is in effect, or SET FLOW KEEP resulted in Xon/Xoff */
  6454.  
  6455.     if ((flow == FLO_XONX) || (ttraw.sg_flags & TANDEM)) {
  6456.     debug(F100,"ttpkt turning on TANDEM","",0);
  6457.     ttraw.sg_flags |= TANDEM;    /* So ask for it. */
  6458.  
  6459. #ifdef LPASS8                /* Can pass 8-bit data through? */
  6460. /* If the LPASS8 local mode is available, then flow control can always  */
  6461. /* be used, even if parity is none and we are transferring 8-bit data.  */
  6462. /* But we only need to do all this if Xon/Xoff is requested. */
  6463. /* BUT... this tends not to work through IP or LAT connections, terminal */
  6464. /* servers, telnet, rlogin, etc, so it is currently disabled. */
  6465.     x = LPASS8;            /* If LPASS8 defined, then */
  6466.     debug(F100,"ttpkt executing LPASS8 code","",0);
  6467.     if (lmodef) {            /* TIOCLBIS must be too. */
  6468.         x = ioctl(ttyfd,TIOCLBIS,&x); /* Try to set LPASS8. */
  6469.         if (x < 0) {
  6470.         debug(F100,"ttpkt TIOCLBIS error","",0);
  6471.         } else {
  6472.         lmodef++;
  6473.         debug(F100,"ttpkt TIOCLBIS ok","",0);
  6474.         }
  6475.     }
  6476. /*
  6477.  But if we use LPASS8 mode, we must explicitly turn off
  6478.  terminal interrupts of all kinds.
  6479. */
  6480. #ifdef TIOCGETC                /* Not rawmode, */
  6481.     if (tcharf && (xlocal == 0)) {    /* must turn off */
  6482.         tchnoi.t_intrc = -1;    /* interrupt character */
  6483.         tchnoi.t_quitc = -1;    /* and quit character. */
  6484.         tchnoi.t_startc = 17;    /* Make sure xon */
  6485.         tchnoi.t_stopc = 19;    /* and xoff not ignored. */
  6486. #ifndef NOBRKC
  6487.         tchnoi.t_eofc = -1;        /* eof character. */
  6488.         tchnoi.t_brkc = -1;        /* brk character. */
  6489. #endif /* NOBRKC */
  6490.         if (ioctl(ttyfd,TIOCSETC,&tchnoi) < 0) {
  6491.         debug(F100,"ttpkt TIOCSETC failed","",0);
  6492.         } else {
  6493.         tcharf = 1;
  6494.         debug(F100,"ttpkt TIOCSETC ok","",0);
  6495.         }
  6496. #ifdef COMMENT
  6497. /* only for paranoid debugging */
  6498.         if (tcharf) {
  6499.         struct tchars foo;
  6500.         char tchbuf[100];
  6501.         ioctl(0,TIOCGETC,&foo);
  6502.         sprintf(tchbuf,
  6503.             "intr=%d,quit=%d, start=%d, stop=%d, eof=%d, brk=%d",
  6504.             foo.t_intrc, foo.t_quitc, foo.t_startc,
  6505.             foo.t_stopc, foo.t_eofc,  foo.t_brkc);
  6506.         debug(F110,"ttpkt chars",tchbuf,0);
  6507.         }
  6508. #endif /* COMMENT */
  6509.     }
  6510.     ttraw.sg_flags |= CBREAK;    /* Needed for unknown reason */
  6511. #endif /* TIOCGETC */
  6512.  
  6513. /* Prevent suspend during packet mode */
  6514. #ifdef TIOCGLTC                /* Not rawmode, */
  6515.     if (ltcharf && (xlocal == 0)) {    /* must turn off */
  6516.         ltchnoi.t_suspc = -1;    /* suspend character */
  6517.         ltchnoi.t_dsuspc = -1;    /* and delayed suspend character */
  6518.         if (ioctl(ttyfd,TIOCSLTC,&tchnoi) < 0) {
  6519.         debug(F100,"ttpkt TIOCSLTC failed","",0);
  6520.         } else {
  6521.         ltcharf = 1;
  6522.         debug(F100,"ttpkt TIOCSLTC ok","",0);
  6523.         }
  6524.     }
  6525. #endif /* TIOCGLTC */
  6526.  
  6527. #else /* LPASS8 not defined */
  6528.  
  6529. /* Previously, BSD-based implementations always */
  6530. /* used rawmode for packets.  Now, we use rawmode only if parity is NONE. */
  6531. /* This allows the flow control requested above to actually work, but only */
  6532. /* if the user asks for parity (which also means they get 8th-bit quoting). */
  6533.  
  6534.     if (parity) {            /* If parity, */
  6535.         ttraw.sg_flags &= ~RAW;    /* use cooked mode */
  6536. #ifdef COMMENT
  6537. /* WHY??? */
  6538.         if (xlocal)
  6539. #endif /* COMMENT */
  6540.           ttraw.sg_flags |= CBREAK;
  6541.         debug(F101,"ttpkt cooked, cbreak, parity","",parity);
  6542. #ifdef TIOCGETC                /* Not rawmode, */
  6543.         if (tcharf && (xlocal == 0)) { /* must turn off */
  6544.         tchnoi.t_intrc = -1;    /* interrupt character */
  6545.         tchnoi.t_quitc = -1;    /* and quit character. */
  6546.         tchnoi.t_startc = 17;    /* Make sure xon */
  6547.         tchnoi.t_stopc = 19;    /* and xoff not ignored. */
  6548. #ifndef NOBRKC
  6549.         tchnoi.t_eofc = -1;    /* eof character. */
  6550.         tchnoi.t_brkc = -1;    /* brk character. */
  6551. #endif /* NOBRKC */
  6552.         if (ioctl(ttyfd,TIOCSETC,&tchnoi) < 0) {
  6553.             debug(F100,"ttpkt TIOCSETC failed","",0);
  6554.         } else {
  6555.             tcharf = 1;
  6556.             debug(F100,"ttpkt TIOCSETC ok","",0);
  6557.         }
  6558.         }
  6559. #endif /* TIOCGETC */
  6560. #ifdef TIOCGLTC                /* Not rawmode, */
  6561. /* Prevent suspend during packet mode */
  6562.         if (ltcharf && (xlocal == 0)) { /* must turn off */
  6563.         ltchnoi.t_suspc = -1;    /* suspend character */
  6564.         ltchnoi.t_dsuspc = -1;    /* and delayed suspend character */
  6565.         if (ioctl(ttyfd,TIOCSLTC,&tchnoi) < 0) {
  6566.             debug(F100,"ttpkt TIOCSLTC failed","",0);
  6567.         } else {
  6568.             ltcharf = 1;
  6569.             debug(F100,"ttpkt TIOCSLTC ok","",0);
  6570.         }
  6571.         }
  6572. #endif /* TIOCGLTC */
  6573.     } else {            /* If no parity, */
  6574.         ttraw.sg_flags |= RAW;    /* must use 8-bit raw mode. */
  6575.         debug(F101,"ttpkt setting rawmode, parity","",parity);
  6576.     }
  6577. #endif /* LPASS8 */
  6578.     } /* End of Xon/Xoff section */
  6579.  
  6580.     /* Don't echo, don't map CR to CRLF on output, don't fool with case */
  6581. #ifdef LCASE
  6582.     ttraw.sg_flags &= ~(ECHO|CRMOD|LCASE);
  6583. #else
  6584.     ttraw.sg_flags &= ~(ECHO|CRMOD);
  6585. #endif /* LCASE */
  6586.  
  6587. #ifdef TOWER1
  6588.     ttraw.sg_flags &= ~ANYP;            /* Must set this on old Towers */
  6589. #endif /* TOWER1 */
  6590.  
  6591. #ifdef BELLV10
  6592.     if (ioctl(ttyfd,TIOCSETP,&ttraw) < 0) /* Set the new modes. */
  6593.       return(-1);
  6594. #else
  6595.     errno = 0;
  6596.     if (stty(ttyfd,&ttraw) < 0) {       /* Set the new modes. */
  6597.         debug(F101,"ttpkt stty failed","",errno);
  6598.         return(-1);
  6599.     }
  6600. #endif /* BELLV10 */
  6601.     debug(F100,"ttpkt stty ok","",0);
  6602.  
  6603. #ifdef sony_news
  6604.     x = xlocal ? km_ext : km_con;    /* Put line in ASCII mode. */
  6605.     if (x != -1) {            /* Make sure we know original modes. */
  6606.     x &= ~KM_TTYPE;
  6607.     x |= KM_ASCII;
  6608.     if (ioctl(ttyfd,TIOCKSET, &x) < 0) {
  6609.         perror("ttpkt can't set ASCII mode");
  6610.         debug(F101,"ttpkt error setting ASCII mode","",x);
  6611.         return(-1);
  6612.     }
  6613.     }
  6614.     debug(F100,"ttpkt set ASCII mode ok","",0);
  6615. #endif /* sony_news */
  6616.  
  6617.     if (xlocal == 0) {            /* Turn this off so we can read */
  6618.     signal(SIGINT,SIG_IGN);        /* Ctrl-C chars typed at console */
  6619.     sigint_ign = 1;
  6620.     }
  6621.     tvtflg = 0;                /* So ttvt() will work next time */
  6622.     debug(F100,"ttpkt success","",0);
  6623.     return(0);
  6624.  
  6625. #endif /* Not ATTSV or POSIX */
  6626.  
  6627. /* AT&T UNIX and POSIX */
  6628.  
  6629. #ifdef COHERENT
  6630. #define SVORPOSIX
  6631. #endif /* COHERENT */
  6632.  
  6633. #ifdef SVORPOSIX
  6634.     if (flow == FLO_XONX) {        /* Xon/Xoff */
  6635.     ttraw.c_iflag |= (IXON|IXOFF);
  6636.     tthflow(flow, 0, &ttraw);
  6637.     } else if (flow == FLO_NONE) {    /* None */
  6638.     /* NOTE: We should also turn off hardware flow control here! */
  6639.     ttraw.c_iflag &= ~(IXON|IXOFF);
  6640.     tthflow(flow, 0, &ttraw);
  6641.     } else if (flow == FLO_KEEP) {    /* Keep */
  6642.     ttraw.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff flags */
  6643.     ttraw.c_iflag |= (ttold.c_iflag & (IXON|IXOFF)); /* OR in old ones */
  6644.     /* NOTE: We should also handle hardware flow control here! */
  6645. #ifdef POSIX_CRTSCTS
  6646. /* In Linux case, we do this, which is unlikely to be portable */
  6647.         ttraw.c_cflag &= ~CRTSCTS;    /* Turn off RTS/CTS flag */
  6648.         ttraw.c_cflag |= (ttold.c_cflag & CRTSCTS); /* OR in old one */
  6649. #endif /* POSIX_CRTSCTS */
  6650.     } else if (flow == FLO_RTSC ||    /* Hardware */
  6651.            flow == FLO_DTRC ||
  6652.            flow == FLO_DTRT) {
  6653.     ttraw.c_iflag &= ~(IXON|IXOFF);    /* (190) */
  6654.     tthflow(flow, 1, &ttraw);
  6655.     }
  6656.     ttraw.c_lflag &= ~(ICANON|ECHO);
  6657.     ttraw.c_lflag &= ~ISIG;        /* Do NOT check for interrupt chars */
  6658.  
  6659. #ifndef OXOS
  6660. #ifdef QNX
  6661.     if (flow != FLO_RTSC && flow != FLO_DTRC && flow != FLO_DTRT)
  6662. #endif /* QNX */
  6663. #ifndef COHERENT
  6664.       ttraw.c_lflag &= ~IEXTEN;        /* Turn off ^O/^V processing */
  6665. #endif /* COHERENT */
  6666. #else /* OXOS */
  6667.     ttraw.c_cc[VDISCARD] = ttraw.c_cc[VLNEXT] = CDISABLE;
  6668. #endif /* OXOS */
  6669.     ttraw.c_lflag |= NOFLSH;        /* Don't flush */
  6670.     ttraw.c_iflag |= IGNPAR;        /* Ignore parity errors */
  6671. #ifdef ATTSV
  6672. #ifdef BSD44
  6673.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|INPCK|ISTRIP|IXANY);
  6674. #else
  6675.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IUCLC|INPCK|ISTRIP|IXANY);
  6676. #endif /* BSD44 */
  6677. #else /* POSIX */
  6678.     ttraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|INPCK|ISTRIP);
  6679. #endif /* ATTSV */
  6680.     ttraw.c_oflag &= ~OPOST;
  6681.     ttraw.c_cflag &= ~(CSIZE);
  6682.     ttraw.c_cflag |= (CS8|CREAD|HUPCL);
  6683.  
  6684. #ifdef CSTOPB
  6685.     if (xlocal) {
  6686.     if (stopbits == 2) {
  6687.         ttraw.c_cflag |= CSTOPB;    /* 2 stop bits */
  6688.         debug(F100,"ttpkt 2 stopbits","",0);
  6689.     } else if (stopbits == 1) {
  6690.         ttraw.c_cflag &= ~(CSTOPB);    /* 1 stop bit */
  6691.         debug(F100,"ttpkt 1 stopbit","",0);
  6692.     }
  6693.     }
  6694. #endif /* CSTOPB */
  6695.  
  6696. #ifdef HWPARITY
  6697.     if (hwparity && xlocal) {        /* Hardware parity */
  6698.     ttraw.c_cflag |= PARENB;    /* Enable parity */
  6699. #ifdef COMMENT
  6700. /* Uncomment this only if needed -- I don't think it is */
  6701.     ttraw.c_cflag &= ~(CSIZE);    /* Clear out character-size mask */
  6702.     ttraw.c_cflag |= CS8;        /* And set it to 8 */
  6703. #endif /* COMMENT */
  6704. #ifdef IGNPAR
  6705.     ttraw.c_iflag |= IGNPAR;    /* Don't discard incoming bytes */
  6706.     debug(F100,"ttpkt IGNPAR","",0); /* that have parity errors */
  6707. #endif /* IGNPAR */
  6708.     switch (hwparity) {
  6709.       case 'e':            /* Even */
  6710.         ttraw.c_cflag &= ~(PARODD);
  6711.         debug(F100,"ttpkt 8 bits + even parity","",0);
  6712.         break;
  6713.       case 'o':            /* Odd */
  6714.         ttraw.c_cflag |= PARODD;
  6715.         debug(F100,"ttpkt 8 bits + odd parity","",0);
  6716.         break;
  6717.       case 'm':            /* Mark */
  6718.       case 's':            /* Space */
  6719.         /* PAREXT is mentioned in SVID but the details are not given. */
  6720.         /* PAREXT is not included in POSIX ISO/IEC 9945-1. */
  6721.         debug(F100,"ttpkt 8 bits + invalid parity","",0);
  6722.         break;
  6723.     }
  6724.     } else {                /* We handle parity ourselves */
  6725. #endif /* HWPARITY */
  6726.     ttraw.c_cflag &= ~(PARENB);    /* Don't enable parity */
  6727. #ifdef HWPARITY
  6728.     }
  6729. #endif /* HWPARITY */
  6730.  
  6731. #ifdef IX370
  6732.     ttraw.c_cc[4] = 48;  /* So Series/1 doesn't interrupt on every char */
  6733.     ttraw.c_cc[5] = 1;
  6734. #else
  6735. #ifndef VEOF                /* for DGUX this is VEOF, not VMIN */
  6736.     ttraw.c_cc[4] = 1;   /* [VMIN]  return max of this many characters or */
  6737. #else
  6738. #ifndef OXOS
  6739. #ifdef VMIN
  6740.     ttraw.c_cc[VMIN] = 1;
  6741. #endif /* VMIN */
  6742. #else /* OXOS */
  6743.     ttraw.c_min = 1;
  6744. #endif /* OXOS */
  6745. #endif /* VEOF */
  6746. #ifndef VEOL                /* for DGUX this is VEOL, not VTIME */
  6747.     ttraw.c_cc[5] = 0;     /* [VTIME] when this many secs/10 expire w/no input */
  6748. #else
  6749. #ifndef OXOS
  6750. #ifdef VTIME
  6751.     ttraw.c_cc[VTIME] = 0;
  6752. #endif /* VTIME */
  6753. #else /* OXOS */
  6754.     ttraw.c_time = 0;
  6755. #endif /* OXOS */
  6756. #endif /* VEOL */
  6757. #endif /* IX370 */
  6758.  
  6759. #ifdef VINTR                /* Turn off interrupt character */
  6760.     if (xlocal == 0)            /* so ^C^C can break us out of */
  6761.       ttraw.c_cc[VINTR] = 0;        /* packet mode. */
  6762. #endif /* VINTR */
  6763.  
  6764. #ifdef Plan9
  6765.     if (p9ttyparity('n') < 0)
  6766.     return -1;
  6767. #else
  6768. #ifdef BSD44ORPOSIX
  6769.     errno = 0;
  6770. #ifdef BEOSORBEBOX
  6771.     ttraw.c_cc[VMIN] = 0;        /* DR7 can only poll. */
  6772. #endif /* BEOSORBEBOX */
  6773.  
  6774. #define TESTING234
  6775. #ifdef TESTING234
  6776.     if (1) {
  6777.     debug(F100,"ttpkt TESTING234 rawmode","",0);
  6778.  
  6779.     /* iflags */
  6780.     ttraw.c_iflag &= ~(PARMRK|ISTRIP|BRKINT|INLCR|IGNCR|ICRNL);
  6781.     ttraw.c_iflag &= ~(INPCK|IGNPAR|IXON|IXOFF);
  6782.     ttraw.c_iflag |= IGNBRK;
  6783. #ifdef IMAXBEL
  6784.     ttraw.c_iflag &= ~IMAXBEL;
  6785. #endif    /* IMAXBEL */
  6786. #ifdef IXANY
  6787.     ttraw.c_iflag &= ~IXANY;
  6788. #endif    /* IXANY */
  6789. #ifdef IUCLC
  6790.     ttraw.c_iflag &= ~IUCLC;
  6791. #endif /* IUCLC */
  6792.  
  6793.     /* oflags */
  6794.     ttraw.c_oflag &= ~OPOST;
  6795. #ifdef OXTABS
  6796.     ttraw.c_oflag &= ~OXTABS;
  6797. #endif /* OXTABS */
  6798. #ifdef ONOCR
  6799.     ttraw.c_oflag &= ~ONOCR;
  6800. #endif /* ONOCR */
  6801. #ifdef ONLRET
  6802.     ttraw.c_oflag &= ~ONLRET;
  6803. #endif /* ONLRET */
  6804. #ifdef ONLCR
  6805.     ttraw.c_oflag &= ~ONLCR;
  6806. #endif /* ONLCR */
  6807.  
  6808.     /* lflags */
  6809.     ttraw.c_lflag &= ~ECHO;
  6810. #ifdef ECHOE
  6811.     ttraw.c_lflag &= ~ECHOE;
  6812. #endif /* ECHOE */
  6813. #ifdef ECHONL
  6814.     ttraw.c_lflag &= ~ECHONL;
  6815. #endif /* ECHONL */
  6816. #ifdef ECHOPRT
  6817.     ttraw.c_lflag &= ~ECHOPRT;
  6818. #endif /* ECHOPRT */
  6819. #ifdef ECHOKE
  6820.     ttraw.c_lflag &= ~ECHOKE;
  6821. #endif /* ECHOKE */
  6822. #ifdef ECHOCTL
  6823.     ttraw.c_lflag &= ~ECHOCTL;
  6824. #endif /* ECHOCTL */
  6825. #ifdef ALTWERASE
  6826.     ttraw.c_lflag &= ~ALTWERASE;
  6827. #endif /* ALTWERASE */
  6828. #ifdef EXTPROC
  6829.     ttraw.c_lflag &= ~EXTPROC;
  6830. #endif /* EXTPROC */
  6831.     ttraw.c_lflag &= ~(ICANON|ISIG|IEXTEN|TOSTOP|FLUSHO|PENDIN);
  6832. #ifdef NOKERNINFO
  6833.     ttraw.c_lflag |= NOKERNINFO;
  6834. #endif    /* NOKERNINFO */
  6835.     /* ttraw.c_lflag |= NOFLSH; */
  6836.     ttraw.c_lflag &= ~NOFLSH;
  6837.  
  6838.     /* cflags */
  6839.     ttraw.c_cflag &= ~(CSIZE|PARENB|PARODD);
  6840.     ttraw.c_cflag |= CS8|CREAD;
  6841. #ifdef VMIN
  6842.     ttraw.c_cc[VMIN] = 1;        /* Supposedly needed for AIX */
  6843. #endif    /* VMIN */
  6844.  
  6845.     }
  6846. #endif /* TESTING234 */
  6847.  
  6848.     debug(F100,"ttpkt calling tcsetattr(TCSETAW)","",0);
  6849.     x = tcsetattr(ttyfd,TCSADRAIN,&ttraw);
  6850.     debug(F101,"ttpkt BSD44ORPOSIX tcsetattr","",x);
  6851.     if (x < 0) {
  6852.     debug(F101,"ttpkt BSD44ORPOSIX tcsetattr errno","",errno);
  6853.         return(-1);
  6854.     }
  6855. #else /* BSD44ORPOSIX */
  6856.     x = ioctl(ttyfd,TCSETAW,&ttraw);
  6857.     debug(F101,"ttpkt ATTSV ioctl TCSETAW","",x);
  6858.     if (x < 0) {  /* set new modes . */
  6859.     debug(F101,"ttpkt ATTSV ioctl TCSETAW errno","",errno);
  6860.         return(-1);
  6861.     }
  6862. #endif /* BSD44ORPOSIX */
  6863. #endif /* Plan9 */
  6864.     tvtflg = 0;
  6865.     debug(F100,"ttpkt ok","",0);
  6866.     return(0);
  6867. #endif /* ATTSV */
  6868.  
  6869. #ifdef COHERENT
  6870. #undef SVORPOSIX
  6871. #endif /* COHERENT */
  6872.  
  6873. }
  6874.  
  6875. /*  T T S E T F L O W  --  Set flow control immediately.  */
  6876.  
  6877. #ifdef COHERENT
  6878. #define SVORPOSIX
  6879. #endif /* COHERENT */
  6880.  
  6881. int
  6882. ttsetflow(flow) int flow; {
  6883.     if (ttyfd < 0)            /* A channel must be open */
  6884.       return(-1);
  6885.  
  6886.     debug(F101,"ttsetflow flow","",flow);
  6887.  
  6888. #ifdef TN_COMPORT
  6889.     if (netconn && istncomport()) {
  6890.     debug(F101,"ttsetflow net modem","",ttmdm);
  6891.     return(tnsetflow(flow));
  6892.     }
  6893. #endif /* TN_COMPORT */
  6894. #ifdef NETCMD
  6895.     if (ttpipe) return(0);
  6896. #endif /* NETCMD */
  6897. #ifdef NETPTY
  6898.     if (ttpty) return(0);
  6899. #endif /* NETPTY */
  6900.  
  6901. #ifdef COMMENT
  6902.     /* This seems to hurt... */
  6903.     if (flow == FLO_KEEP)
  6904.       return(0);
  6905. #endif /* COMMENT */
  6906.  
  6907.     if (flow == FLO_RTSC ||        /* Hardware flow control... */
  6908.     flow == FLO_DTRC ||
  6909.     flow == FLO_DTRT) {
  6910.     tthflow(flow, 1, &ttraw);
  6911. #ifndef SVORPOSIX
  6912.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6913. #else
  6914.     ttraw.c_iflag &= ~(IXON|IXOFF);
  6915. #endif /* SVORPOSIX */
  6916.  
  6917.     } else if (flow == FLO_XONX) {    /* Xon/Xoff... */
  6918.  
  6919. #ifndef SVORPOSIX
  6920.     ttraw.sg_flags |= TANDEM;
  6921. #else
  6922.     ttraw.c_iflag |= (IXON|IXOFF);
  6923. #endif /* SVORPOSIX */
  6924.     tthflow(FLO_RTSC, 0, &ttraw);    /* Turn off hardware flow control */
  6925.  
  6926.     } else if (flow == FLO_NONE) {    /* No flow control */
  6927.  
  6928. #ifndef SVORPOSIX
  6929.     ttraw.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  6930. #else
  6931.     ttraw.c_iflag &= ~(IXON|IXOFF);
  6932. #endif /* SVORPOSIX */
  6933.     tthflow(FLO_RTSC, 0, &ttraw);    /* Turn off any hardware f/c too */
  6934.     }
  6935.  
  6936. /* Set the new modes... */
  6937.  
  6938. #ifndef SVORPOSIX            /* BSD and friends */
  6939. #ifdef BELLV10
  6940.     if (ioctl(ttyfd,TIOCSETP,&ttraw) < 0)
  6941.       return(-1);
  6942. #else
  6943. #ifndef MINIX2
  6944.     if (stty(ttyfd,&ttraw) < 0)
  6945.       return(-1);
  6946. #endif /* MINIX2 */
  6947. #endif /* BELLV10 */
  6948. #else
  6949. #ifdef BSD44ORPOSIX            /* POSIX */
  6950.     if (tcsetattr(ttyfd,TCSADRAIN,&ttraw) < 0)
  6951.       return(-1);
  6952. #else                    /* System V */
  6953.     if (ioctl(ttyfd,TCSETAW,&ttraw) < 0)
  6954.       return(-1);
  6955. #endif /* BSD44ORPOSIX */
  6956. #endif /* SVORPOSIX */
  6957.     return(0);
  6958. }
  6959. #ifdef COHERENT
  6960. #undef SVORPOSIX
  6961. #endif /* COHERENT */
  6962.  
  6963. /*  T T V T -- Condition communication device for use as virtual terminal. */
  6964.  
  6965. int
  6966. #ifdef CK_ANSIC
  6967. ttvt(long speed, int flow)
  6968. #else
  6969. ttvt(speed,flow) long speed; int flow;
  6970. #endif /* CK_ANSIC */
  6971. /* ttvt */ {
  6972.     int s, s2, x;
  6973.  
  6974.     debug(F101,"ttvt ttyfd","",ttyfd);
  6975.     debug(F101,"ttvt tvtflg","",tvtflg);
  6976.     debug(F111,"ttvt speed",ckitoa(ttspeed),speed);
  6977.     debug(F111,"ttvt flow",ckitoa(ttflow),flow);
  6978.     debug(F111,"ttvt curcarr",ckitoa(ttcarr),curcarr);
  6979.  
  6980. /* Note: NetBSD and maybe other BSD44s have cfmakeraw() */
  6981. /* Maybe it would be simpler to use it... */
  6982.  
  6983.     ttpmsk = 0xff;
  6984. #ifdef NOLOCAL
  6985.     return(conbin((char)escchr));
  6986. #else
  6987.     if (ttyfd < 0) {            /* Not open. */
  6988.     if (ttchk() < 0)
  6989.       return(-1);
  6990.     else                /* But maybe something buffered. */
  6991.       return(0);
  6992.     }
  6993. #ifdef NETCMD
  6994.     if (ttpipe) return(0);
  6995. #endif /* NETCMD */
  6996. #ifdef NETPTY
  6997.     if (ttpty) return(0);
  6998. #endif /* NETPTY */
  6999. #ifdef NETCONN
  7000.     if (netconn) {
  7001. #ifdef TCPSOCKET
  7002. #ifdef TCP_NODELAY
  7003.         {
  7004.         extern int tcp_nodelay;
  7005.         if (ttnet == NET_TCPB) {
  7006.         if (nodelay_sav > -1) {
  7007.             no_delay(ttyfd,nodelay_sav);
  7008.             nodelay_sav = -1;
  7009.         }
  7010.         }
  7011.         }
  7012. #endif /* TCP_NODELAY */
  7013. #ifdef TN_COMPORT
  7014.         if (istncomport()) {
  7015.             int rc = -1;
  7016.             if (tvtflg != 0 && speed == ttspeed && flow == ttflow
  7017.                  /* && ttcarr == curcarr */ ) {
  7018.                 debug(F100,"ttvt modes already set, skipping...","",0);
  7019.                 return(0);            /* Already been called. */
  7020.             }
  7021.             if (flow != ttflow) {
  7022.                 if ((rc = tnsetflow(flow)) < 0)
  7023.           return(rc);
  7024.                 ttflow = flow;
  7025.             }
  7026.             if (speed != ttspeed) {
  7027.                 if (speed <= 0) 
  7028.           speed = tnc_get_baud();
  7029.                 else if ((rc = tnc_set_baud(speed)) < 0)
  7030.           return(rc);
  7031.                 ttspeed = speed;
  7032.             }
  7033.             tnc_set_datasize(8);
  7034.         tnc_set_stopsize(stopbits);
  7035.  
  7036. #ifdef HWPARITY
  7037.             if (hwparity) {
  7038.                 switch (hwparity) {
  7039.           case 'e':        /* Even */
  7040.                     debug(F100,"ttres 8 bits + even parity","",0);
  7041.                     tnc_set_parity(3);
  7042.                     break;
  7043.           case 'o':        /* Odd */
  7044.                     debug(F100,"ttres 8 bits + odd parity","",0);
  7045.                     tnc_set_parity(2);
  7046.                     break;
  7047.           case 'm':        /* Mark */
  7048.                     debug(F100,"ttres 8 bits + invalid parity: mark","",0);
  7049.                     tnc_set_parity(4);
  7050.                     break;
  7051.           case 's':        /* Space */
  7052.                     debug(F100,"ttres 8 bits + invalid parity: space","",0);
  7053.                     tnc_set_parity(5);
  7054.                     break;
  7055.                 }
  7056.             } else
  7057. #endif /* HWPARITY */
  7058.             {
  7059.                 tnc_set_parity(1);    /* None */
  7060.             }
  7061.             tvtflg = 1;
  7062.             return(0);
  7063.         }
  7064. #endif /* TN_COMPORT */
  7065. #endif /* TCPSOCKET */
  7066.     tvtflg = 1;            /* Network connections... */
  7067.     debug(F100,"ttvt network connection, skipping...","",0);
  7068.     return(0);            /* ... require no special setup */
  7069.     }
  7070. #endif /* NETCONN */
  7071.  
  7072.     if (tvtflg != 0 && speed == ttspeed && flow == ttflow
  7073.     /* && ttcarr == curcarr */ )
  7074.       {
  7075.       debug(F100,"ttvt modes already set, skipping...","",0);
  7076.       return(0);            /* Already been called. */
  7077.       }
  7078.  
  7079.     if (ttfdflg
  7080. #ifndef Plan9
  7081.     && !isatty(ttyfd)
  7082. #endif /* Plan9 */
  7083.     ) {
  7084.     debug(F100,"ttvt using external fd, skipping...","",0);
  7085.     return(0);
  7086.     }
  7087.  
  7088.     debug(F100,"ttvt setting modes...","",0);
  7089.  
  7090.     if (xlocal) {            /* For external lines... */
  7091.     s2 = (int) (speed / 10L);
  7092.     s = ttsspd(s2);            /* Check/set the speed */
  7093.     carrctl(&tttvt, flow != FLO_DIAL /* Do carrier control */
  7094.         && (ttcarr == CAR_ON || (ttcarr == CAR_AUT && ttmdm != 0)));
  7095.     } else
  7096.       s = s2 = -1;
  7097.  
  7098. #ifdef COHERENT
  7099. #define SVORPOSIX
  7100. #endif /* COHERENT */
  7101.  
  7102. #ifndef SVORPOSIX
  7103.     /* Berkeley, V7, etc */
  7104.     if (flow == FLO_RTSC ||        /* Hardware flow control */
  7105.     flow == FLO_DTRC ||
  7106.     flow == FLO_DTRT) {
  7107.     tthflow(flow, 1, &tttvt);
  7108.     debug(F100,"ttvt hard flow, TANDEM off","",0);
  7109.     tttvt.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  7110.     } else if (flow == FLO_XONX) {    /* Xon/Xoff flow control */
  7111.     debug(F100,"ttvt TANDEM on","",0);
  7112.     tttvt.sg_flags |= TANDEM;    /* Ask for it. */
  7113.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  7114.     } else if (flow == FLO_NONE) {
  7115.     debug(F100,"ttvt no flow, TANDEM off, RAW on","",0);
  7116.     tttvt.sg_flags &= ~TANDEM;    /* Turn off software flow control */
  7117.     tthflow(flow, 0, &tttvt);    /* Turn off any hardware f/c too */
  7118.     tttvt.sg_flags |= RAW;        /* Enter raw mode */
  7119.     } else if (flow == FLO_KEEP) {    /* Keep device's original setting */
  7120.     debug(F100,"ttvt keeping original TANDEM","",0);
  7121.     tttvt.sg_flags &= ~TANDEM;
  7122.     tttvt.sg_flags |= (ttold.sg_flags & TANDEM);
  7123.     /* NOTE: We should also handle hardware flow control here! */
  7124.     }
  7125.     tttvt.sg_flags |= RAW;              /* Raw mode in all cases */
  7126. #ifdef TOWER1
  7127.     tttvt.sg_flags &= ~(ECHO|ANYP);     /* No echo or parity */
  7128. #else
  7129.     tttvt.sg_flags &= ~ECHO;            /* No echo */
  7130. #endif /* TOWER1 */
  7131.  
  7132. #ifdef BELLV10
  7133.     if (ioctl(ttyfd,TIOCSETP,&tttvt) < 0) /* Set the new modes */
  7134.       return(-1);
  7135. #else
  7136.     if (stty(ttyfd,&tttvt) < 0)        /* Set the new modes */
  7137.       return(-1);
  7138. #endif /* BELLV10 */
  7139.  
  7140. #else /* It is ATTSV or POSIX */
  7141.  
  7142.     if (flow == FLO_XONX) {        /* Software flow control */
  7143.     tttvt.c_iflag |= (IXON|IXOFF);    /* On if requested. */
  7144.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  7145.     debug(F100,"ttvt SVORPOSIX flow XON/XOFF","",0);
  7146.     } else if (flow == FLO_NONE) {    /* NONE */
  7147.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff */
  7148.     tthflow(flow, 0, &tttvt);    /* Turn off hardware f/c */
  7149.     debug(F100,"ttvt SVORPOSIX flow NONE","",0);
  7150.     } else if (flow == FLO_KEEP) {
  7151.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* Turn off Xon/Xoff flags */
  7152.     tttvt.c_iflag |= (ttold.c_iflag & (IXON|IXOFF)); /* OR in old ones */
  7153. #ifdef POSIX_CRTSCTS
  7154.         tttvt.c_cflag &= ~CRTSCTS;    /* Turn off RTS/CTS flag */
  7155.         tttvt.c_cflag |= (ttold.c_cflag & CRTSCTS); /* OR in old one */
  7156. #endif /* POSIX_CRTSCTS */
  7157.     debug(F100,"ttvt SVORPOSIX flow KEEP","",0);
  7158.     } else if (flow == FLO_RTSC ||    /* Hardware flow control */
  7159.            flow == FLO_DTRC ||
  7160.            flow == FLO_DTRT) {
  7161.     tttvt.c_iflag &= ~(IXON|IXOFF);    /* (196) */
  7162.     tthflow(flow, 1, &tttvt);
  7163.     debug(F100,"ttvt SVORPOSIX flow HARD","",0);
  7164.     }
  7165. #ifndef OXOS
  7166. #ifdef COHERENT
  7167.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO);
  7168. #else
  7169.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO|IEXTEN);
  7170. #endif /* COHERENT */
  7171. #ifdef QNX
  7172.     /* Needed for hwfc */
  7173.     if (flow == FLO_RTSC || flow == FLO_DTRC || flow == FLO_DTRT)
  7174.       tttvt.c_lflag |= IEXTEN;
  7175. #endif /* QNX */
  7176. #else /* OXOS */
  7177.     tttvt.c_lflag &= ~(ISIG|ICANON|ECHO);
  7178.     tttvt.c_cc[VDISCARD] = tttvt.c_cc[VLNEXT] = CDISABLE;
  7179. #endif /* OXOS */
  7180.  
  7181.     tttvt.c_iflag |= (IGNBRK|IGNPAR);
  7182.  
  7183. /* Stop bits */
  7184.  
  7185. #ifdef CSTOPB
  7186.     if (xlocal) {
  7187.     if (stopbits == 2) {
  7188.         tttvt.c_cflag |= CSTOPB;    /* 2 stop bits */
  7189.         debug(F100,"ttvt 2 stopbits","",0);
  7190.     } else if (stopbits == 1) {
  7191.         tttvt.c_cflag &= ~(CSTOPB);    /* 1 stop bit */
  7192.         debug(F100,"ttvt 1 stopbit","",0);
  7193.     }
  7194.     }
  7195. #endif /* CSTOPB */
  7196.  
  7197. /* Parity */
  7198.  
  7199. #ifdef HWPARITY
  7200.     if (hwparity && xlocal) {        /* Hardware parity */
  7201. #ifdef COMMENT
  7202. /* Uncomment this only if needed -- I don't think it is */
  7203.     ttraw.c_cflag &= ~(CSIZE);    /* Clear out character-size mask */
  7204.     ttraw.c_cflag |= CS8;        /* And set it to 8 */
  7205. #endif /* COMMENT */
  7206. #ifdef IGNPAR
  7207.     debug(F101,"ttvt hwparity IGNPAR","",IGNPAR);
  7208.     tttvt.c_iflag |= IGNPAR;    /* Don't discard incoming bytes */
  7209. #endif /* IGNPAR */
  7210.     tttvt.c_cflag |= PARENB;    /* Enable parity */
  7211.  
  7212.     switch (hwparity) {
  7213.       case 'e':            /* Even */
  7214.         tttvt.c_cflag &= ~(PARODD);
  7215.         debug(F100,"ttvt 8 bits + even parity","",0);
  7216.         break;
  7217.       case 'o':            /* Odd */
  7218.         tttvt.c_cflag |= PARODD;
  7219.         debug(F100,"ttvt 8 bits + odd parity","",0);
  7220.         break;
  7221.       case 'm':            /* Mark */
  7222.       case 's':            /* Space */
  7223.         /* PAREXT is mentioned in SVID but the details are not given. */
  7224.         /* PAREXT is not included in POSIX ISO/IEC 9945-1. */
  7225.         debug(F100,"ttvt 8 bits + invalid parity","",0);
  7226.         break;
  7227.     }
  7228.     } else {                /* We handle parity ourselves */
  7229. #endif /* HWPARITY */
  7230.     tttvt.c_cflag &= ~(PARENB);    /* Don't enable parity */
  7231. #ifdef HWPARITY
  7232.     }
  7233. #endif /* HWPARITY */
  7234.  
  7235. #ifdef ATTSV
  7236. #ifdef BSD44
  7237.     /* Things not to do... */
  7238.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|INPCK|ISTRIP|IXANY);
  7239. #else
  7240.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|IUCLC|INPCK|ISTRIP|IXANY);
  7241. #endif /* BSD44 */
  7242. #else /* POSIX */
  7243.     tttvt.c_iflag &= ~(INLCR|IGNCR|ICRNL|INPCK|ISTRIP);
  7244. #endif /* ATTSV */
  7245.     tttvt.c_cflag &= ~(CSIZE);        /* Zero out the char size field */
  7246.     tttvt.c_cflag |= (CS8|CREAD|HUPCL);    /* Char size 8, enable receiver, hup */
  7247.     tttvt.c_oflag &= ~OPOST;        /* Don't postprocess output */
  7248. #ifndef VEOF /* DGUX termio has VEOF at entry 4, see comment above */
  7249.     tttvt.c_cc[4] = 1;
  7250. #else
  7251. #ifndef OXOS
  7252. #ifdef VMIN
  7253.     tttvt.c_cc[VMIN] = 1;
  7254. #endif /* VMIN */
  7255. #else /* OXOS */
  7256.     tttvt.c_min = 1;
  7257. #endif /* OXOS */
  7258. #endif /* VEOF */
  7259. #ifndef VEOL    /* DGUX termio has VEOL at entry 5, see comment above */
  7260.     tttvt.c_cc[5] = 0;
  7261. #else
  7262. #ifndef OXOS
  7263. #ifdef VTIME
  7264.     tttvt.c_cc[VTIME] = 0;
  7265. #endif /* VTIME */
  7266. #else /* OXOS */
  7267.     tttvt.c_time = 0;
  7268. #endif /* OXOS */
  7269. #endif /* VEOL */
  7270.  
  7271. #ifdef Plan9
  7272.     if (p9ttyparity('n') < 0)
  7273.       return -1;
  7274. #else
  7275. #ifdef BSD44ORPOSIX
  7276.     errno = 0;
  7277. #ifdef BEOSORBEBOX
  7278.     tttvt.c_cc[VMIN] = 0;        /* DR7 can only poll. */
  7279. #endif /* BEOSORBEBOX */
  7280.  
  7281.     x = tcsetattr(ttyfd,TCSADRAIN,&tttvt);
  7282.     debug(F101,"ttvt BSD44ORPOSIX tcsetattr","",x);
  7283.     if (x < 0) {
  7284.     debug(F101,"ttvt BSD44ORPOSIX tcsetattr errno","",errno);
  7285.     return(-1);
  7286.     }
  7287. #else /* ATTSV */
  7288.     x = ioctl(ttyfd,TCSETAW,&tttvt);
  7289.     debug(F101,"ttvt ATTSV ioctl TCSETAW","",x);
  7290.     if (x < 0) {            /* set new modes . */
  7291.     debug(F101,"ttvt ATTSV ioctl TCSETAW errno","",errno);
  7292.     return(-1);    
  7293.     }
  7294. #endif /* BSD44ORPOSIX */
  7295. #endif /* Plan9 */
  7296. #endif /* ATTSV */
  7297.  
  7298.     ttspeed = speed;            /* Done, remember how we were */
  7299.     ttflow = flow;            /* called, so we can decide how to */
  7300.     tvtflg = 1;                /* respond next time. */
  7301.     debug(F100,"ttvt ok","",0);
  7302.     return(0);
  7303.  
  7304. #ifdef COHERENT
  7305. #undef SVORPOSIX
  7306. #endif /* COHERENT */
  7307.  
  7308. #endif /* NOLOCAL */
  7309. }
  7310.  
  7311. #ifndef NOLOCAL
  7312.  
  7313. /* Serial speed department . . . */
  7314.  
  7315. /*
  7316.   SCO OSR5.0.x might or might not support high speeds.  Sometimes they are not
  7317.   defined in the header files but they are supported (e.g. when building with
  7318.   UDK compiler rather than /bin/cc), sometimes vice versa.  Even though 5.0.4
  7319.   was the first release that came with high serial speeds standard, releases
  7320.   back to 5.0.0 could use them if certain patches (or "supplements") were
  7321.   applied to the SIO driver.  Plus a lot of SCO installations run third-party
  7322.   drivers.
  7323. */
  7324. #ifdef CK_SCOV5
  7325. #ifndef B38400
  7326. #define    B38400    0000017
  7327. #endif /* B38400 */
  7328. #ifndef B57600
  7329. #define    B57600    0000021
  7330. #endif /* B57600 */
  7331. #ifndef B76800
  7332. #define    B76800    0000022
  7333. #endif /* B76800 */
  7334. #ifndef B115200
  7335. #define    B115200    0000023
  7336. #endif /* B115200 */
  7337. #ifndef B230400
  7338. #define    B230400    0000024
  7339. #endif /* B230400 */
  7340. #ifndef B460800
  7341. #define    B460800    0000025
  7342. #endif /* B460800 */
  7343. #ifndef B921600
  7344. #define    B921600    0000026
  7345. #endif /* B921600 */
  7346. #endif /* CK_SCOV5 */
  7347. /*
  7348.   Plan 9's native speed setting interface lets you set anything you like,
  7349.   but will fail if the hardware doesn't like it, so we allow all the common
  7350.   speeds.
  7351. */
  7352. #ifdef Plan9
  7353. #ifndef B50
  7354. #define B50 50
  7355. #endif /* B50 */
  7356. #ifndef B75
  7357. #define B75 75
  7358. #endif /* B75 */
  7359. #ifndef B110
  7360. #define B110 110
  7361. #endif /* B110 */
  7362. #ifndef B134
  7363. #define B134 134
  7364. #endif /* B134 */
  7365. #ifndef B200
  7366. #define B200 200
  7367. #endif /* B200 */
  7368. #ifndef B300
  7369. #define B300 300
  7370. #endif /* B300 */
  7371. #ifndef B1200
  7372. #define B1200 1200
  7373. #endif /* B1200 */
  7374. #ifndef B1800
  7375. #define B1800 1800
  7376. #endif /* B1800 */
  7377. #ifndef B2400
  7378. #define B2400 2400
  7379. #endif /* B2400 */
  7380. #ifndef B4800
  7381. #define B4800 4800
  7382. #endif /* B4800 */
  7383. #ifndef B9600
  7384. #define B9600 9600
  7385. #endif /* B9600 */
  7386. #ifndef B14400
  7387. #define B14400 14400
  7388. #endif /* B14400 */
  7389. #ifndef B19200
  7390. #define B19200 19200
  7391. #endif /* B19200 */
  7392. #ifndef B28800
  7393. #define B28800 28800
  7394. #endif /* B28800 */
  7395. #ifndef B38400
  7396. #define B38400 38400
  7397. #endif /* B38400 */
  7398. #ifndef B57600
  7399. #define B57600 57600
  7400. #endif /* B57600 */
  7401. #ifndef B76800
  7402. #define B76800 76800
  7403. #endif /* B76800 */
  7404. #ifndef B115200
  7405. #define B115200 115200
  7406. #endif /* B115200 */
  7407. #ifndef B230400
  7408. #define B230400 230400
  7409. #endif /* B230400 */
  7410. #ifndef B460800
  7411. #define B460800 460800
  7412. #endif /* B460800 */
  7413. #ifndef B921600
  7414. #define B921600 921600
  7415. #endif /* B921600 */
  7416. #endif /* Plan9 */
  7417.  
  7418. /*  T T S S P D  --  Checks and sets transmission rate.  */
  7419.  
  7420. /*  Call with speed in characters (not bits!) per second. */
  7421. /*  Returns -1 on failure, 0 if it did nothing, 1 if it changed the speed. */
  7422.  
  7423. #ifdef USETCSETSPEED
  7424. /*
  7425.   The tcsetspeed() / tcgetspeed() interface lets you pass any number at all
  7426.   to be used as a speed to be set, rather than forcing a choice from a
  7427.   predefined list.  It seems to be peculiar to UnixWare 7.
  7428.  
  7429.   These are the function codes to be passed to tc[gs]etspeed(),
  7430.   but for some reason they don't seem to be picked up from termios.h.
  7431. */
  7432. #ifndef TCS_ALL
  7433. #define TCS_ALL 0
  7434. #endif /* TCS_ALL */
  7435. #ifndef TCS_IN
  7436. #define TCS_IN 1
  7437. #endif /* TCS_IN */
  7438. #ifndef TCS_OUT
  7439. #define TCS_OUT 2
  7440. #endif /* TCS_OUT */
  7441. #endif /* USETCSETSPEED */
  7442.  
  7443. int
  7444. ttsspd(cps) int cps; {
  7445.     int x;
  7446. #ifdef POSIX
  7447. /* Watch out, speed_t should be unsigned, so don't compare with -1, etc... */
  7448.     speed_t
  7449. #else
  7450.     int
  7451. #endif /* POSIX */
  7452.       s, s2;
  7453.     int ok = 1;                /* Speed check result, assume ok */
  7454.  
  7455. #ifdef OLINUXHISPEED
  7456.     unsigned int spd_flags = 0;
  7457.     struct serial_struct serinfo;
  7458. #endif /* OLINUXHISPEED */
  7459.  
  7460.     debug(F101,"ttsspd cps","",cps);
  7461.     debug(F101,"ttsspd ttyfd","",ttyfd);
  7462.     debug(F101,"ttsspd xlocal","",xlocal);
  7463.  
  7464.     if (ttyfd < 0 || xlocal == 0)    /* Don't set speed on console */
  7465.       return(0);
  7466.  
  7467. #ifdef    NETCONN
  7468.     if (netconn) {
  7469. #ifdef TN_COMPORT
  7470.         if (istncomport())
  7471.       return(tnc_set_baud(cps * 10));
  7472.         else
  7473. #endif /* TN_COMPORT */
  7474.     return(0);
  7475.   }
  7476. #endif    /* NETCONN */
  7477. #ifdef NETCMD
  7478.     if (ttpipe) return(0);
  7479. #endif /* NETCMD */
  7480. #ifdef NETPTY
  7481.     if (ttpty) return(0);
  7482. #endif /* NETPTY */
  7483.  
  7484.     if (cps < 0) return(-1);
  7485.     s = s2 = 0;                /* NB: s and s2 might be unsigned */
  7486.  
  7487. #ifdef USETCSETSPEED
  7488.  
  7489.     s = cps * 10L;
  7490.  
  7491.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  7492.     debug(F101,"ttsspd tcgetattr","",x);
  7493.     if (x < 0)
  7494.       return(-1);
  7495.     debug(F101,"ttsspd TCSETSPEED speed","",s);
  7496.  
  7497.     errno = 0;
  7498.     if (s == 8880L) {            /* 75/1200 split speed requested */
  7499.     tcsetspeed(TCS_IN, &ttcur, 1200L);
  7500.     tcsetspeed(TCS_OUT, &ttcur, 75L);
  7501.     } else
  7502.       tcsetspeed(TCS_ALL, &ttcur, s);    /* Put new speed in structs */
  7503. #ifdef DEBUG
  7504.     if (errno & deblog) {
  7505.     debug(F101,"ttsspd TCSETSPEED errno","",errno);
  7506.     }
  7507. #endif /* DEBUG */
  7508.  
  7509. #ifdef COMMENT
  7510.     tcsetspeed(TCS_ALL, &ttraw, s);
  7511.     tcsetspeed(TCS_ALL, &tttvt, s);
  7512.     tcsetspeed(TCS_ALL, &ttold, s);
  7513. #else
  7514.     if (s == 8880L) {            /* 75/1200 split speed requested */
  7515.     tcsetspeed(TCS_IN, &ttraw, 1200L);
  7516.     tcsetspeed(TCS_OUT, &ttraw, 75L);
  7517.     tcsetspeed(TCS_IN, &tttvt, 1200L);
  7518.     tcsetspeed(TCS_OUT, &tttvt, 75L);
  7519.     tcsetspeed(TCS_IN, &ttold, 1200L);
  7520.     tcsetspeed(TCS_OUT, &ttold, 75L);
  7521.     } else {
  7522.     tcsetspeed(TCS_ALL, &ttraw, s);
  7523.     tcsetspeed(TCS_ALL, &tttvt, s);
  7524.     tcsetspeed(TCS_ALL, &ttold, s);
  7525.     }
  7526. #endif /* COMMENT */
  7527.  
  7528.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur); /* Set the speed */
  7529.     debug(F101,"ttsspd tcsetattr","",x);
  7530.     if (x < 0)
  7531.       return(-1);
  7532.  
  7533. #else  /* Not USETCSETSPEED */
  7534.  
  7535.     /* First check that the given speed is valid. */
  7536.  
  7537.     switch (cps) {
  7538. #ifndef MINIX
  7539.       case 0:   s = B0;    break;
  7540.       case 5:   s = B50;   break;
  7541.       case 7:   s = B75;   break;
  7542. #endif /* MINIX */
  7543.       case 11:  s = B110;  break;
  7544. #ifndef MINIX
  7545.       case 13:  s = B134;  break;
  7546.       case 15:  s = B150;  break;
  7547.       case 20:  s = B200;  break;
  7548. #endif /* MINIX */
  7549.       case 30:  s = B300;  break;
  7550. #ifndef MINIX
  7551.       case 60:  s = B600;  break;
  7552. #endif /* MINIX */
  7553.       case 120: s = B1200; break;
  7554. #ifndef MINIX
  7555.       case 180: s = B1800; break;
  7556. #endif /* MINIX */
  7557.       case 240: s = B2400; break;
  7558.       case 480: s = B4800; break;
  7559. #ifndef MINIX
  7560.       case 888: s = B75; s2 = B1200; break; /* 888 = 75/1200 split speed */
  7561. #endif /* MINIX */
  7562. #ifdef B7200
  7563.       case 720: s = B7200; break;
  7564. #endif /* B7200 */
  7565.       case 960: s = B9600; break;
  7566. #ifdef B14400
  7567.       case 1440: s = B14400; break;
  7568. #endif /* B14400 */
  7569. #ifdef B19200
  7570.       case 1920: s = B19200; break;
  7571. #else
  7572. #ifdef EXTA
  7573.       case 1920: s = EXTA; break;
  7574. #endif /* EXTA */
  7575. #endif /* B19200 */
  7576. #ifdef B28800
  7577.       case 2880: s = B28800; break;
  7578. #endif /* B28800 */
  7579. #ifdef B38400
  7580.       case 3840: s = B38400;
  7581. #ifdef OLINUXHISPEED
  7582.         spd_flags = ~ASYNC_SPD_MASK;    /* Nonzero, but zero flags */
  7583. #endif /* OLINUXHISPEED */
  7584.     break;
  7585. #else /* B38400 not defined... */
  7586. #ifdef EXTB
  7587.       case 3840: s = EXTB; break;
  7588. #endif /* EXTB */
  7589. #endif /* B38400 */
  7590.  
  7591. #ifdef HPUX
  7592. #ifdef _B57600
  7593.       case 5760: s = _B57600; break;
  7594. #endif /* _B57600 */
  7595. #ifdef _B115200
  7596.       case 11520: s = _B115200; break;
  7597. #endif /* _B115200 */
  7598. #else
  7599. #ifdef OLINUXHISPEED
  7600. /*
  7601.   This bit from <carlo@sg.tn.tudelft.nl>:
  7602.   "Only note to make is maybe this: When the ASYNC_SPD_CUST flags are set then
  7603.   setting the speed to 38400 will set the custom speed (and ttgspd returns
  7604.   38400), but speeds 57600 and 115200 won't work any more because I didn't
  7605.   want to mess up the speed flags when someone is doing sophisticated stuff
  7606.   like custom speeds..."
  7607. */
  7608.       case 5760: s = B38400; spd_flags = ASYNC_SPD_HI; break;
  7609.       case 11520: s = B38400; spd_flags = ASYNC_SPD_VHI; break;
  7610. #else
  7611. #ifdef B57600
  7612.       case 5760: s = B57600; break;
  7613. #endif /* B57600 */
  7614. #ifdef B76800
  7615.       case 7680: s = B76800; break;
  7616. #endif /* B76800 */
  7617. #ifdef B115200
  7618.       case 11520: s = B115200; break;
  7619. #endif /* B115200 */
  7620. #endif /* OLINUXHISPEED */
  7621. #ifdef B153600
  7622.       case 15360: s = B153600; break;
  7623. #endif /* B153600 */
  7624. #ifdef B230400
  7625.       case 23040: s = B230400; break;
  7626. #endif /* B230400 */
  7627. #ifdef B307200
  7628.       case 30720: s = B307200; break;
  7629. #endif /* B307200 */
  7630. #ifdef B460800
  7631.       case 46080: s = B460800; break;
  7632. #endif /* 460800 */
  7633. #ifdef B921600
  7634.       case 92160: s = B921600; break;
  7635. #endif /* B921600 */
  7636. #endif /* HPUX */
  7637.       default:
  7638.     ok = 0;                /* Good speed not found, so not ok */
  7639.     break;
  7640.     }
  7641.     debug(F101,"ttsspd ok","",ok);
  7642.     debug(F101,"ttsspd s","",s);
  7643.  
  7644.     if (!ok) {
  7645.     debug(F100,"ttsspd fails","",0);
  7646.     return(-1);
  7647.     } else {
  7648.     if (!s2) s2 = s;        /* Set input speed */
  7649. #ifdef Plan9
  7650.     if (p9ttsspd(cps) < 0)
  7651.       return(-1);
  7652. #else
  7653. #ifdef BSD44ORPOSIX
  7654.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  7655.     debug(F101,"ttsspd tcgetattr","",x);
  7656.     if (x < 0)
  7657.       return(-1);
  7658. #ifdef OLINUXHISPEED
  7659.     debug(F101,"ttsspd spd_flags","",spd_flags);
  7660.     if (spd_flags && spd_flags != ASYNC_SPD_CUST) {
  7661.         if (ioctl(ttyfd, TIOCGSERIAL, &serinfo) < 0) {
  7662.         debug(F100,"ttsspd: TIOCGSERIAL failed","",0);
  7663.         return(-1);
  7664.         } else debug(F100,"ttsspd: TIOCGSERIAL ok","",0);
  7665.         serinfo.flags &= ~ASYNC_SPD_MASK;
  7666.         serinfo.flags |= (spd_flags & ASYNC_SPD_MASK);
  7667.         if (ioctl(ttyfd, TIOCSSERIAL, &serinfo) < 0)
  7668.           return(-1);
  7669.     }
  7670. #endif /* OLINUXHISPEED */
  7671.     cfsetospeed(&ttcur,s);
  7672.     cfsetispeed(&ttcur,s2);
  7673.     cfsetospeed(&ttraw,s);
  7674.     cfsetispeed(&ttraw,s2);
  7675.     cfsetospeed(&tttvt,s);
  7676.     cfsetispeed(&tttvt,s2);
  7677.     cfsetospeed(&ttold,s);
  7678.     cfsetispeed(&ttold,s2);
  7679.     x = tcsetattr(ttyfd,TCSADRAIN,&ttcur);
  7680.     debug(F101,"ttsspd tcsetattr","",x);
  7681.     if (x < 0) return(-1);
  7682. #else
  7683. #ifdef ATTSV
  7684.     if (cps == 888) return(-1);    /* No split speeds, sorry. */
  7685.     x = ioctl(ttyfd,TCGETA,&ttcur);
  7686.     debug(F101,"ttsspd TCGETA ioctl","",x);
  7687.     if (x < 0) return(-1);
  7688.     ttcur.c_cflag &= ~CBAUD;
  7689.     ttcur.c_cflag |= s;
  7690.     tttvt.c_cflag &= ~CBAUD;
  7691.     tttvt.c_cflag |= s;
  7692.     ttraw.c_cflag &= ~CBAUD;
  7693.     ttraw.c_cflag |= s;
  7694.     ttold.c_cflag &= ~CBAUD;
  7695.     ttold.c_cflag |= s;
  7696.     x = ioctl(ttyfd,TCSETAW,&ttcur);
  7697.     debug(F101,"ttsspd TCSETAW ioctl","",x);
  7698.     if (x < 0) return(-1);
  7699. #else
  7700. #ifdef BELLV10
  7701.     x = ioctl(ttyfd,TIOCGDEV,&tdcur);
  7702.     debug(F101,"ttsspd TIOCGDEV ioctl","",x);
  7703.     if (x < 0) return(-1);
  7704.     tdcur.ispeed = s2;
  7705.     tdcur.ospeed = s;
  7706.     errno = 0;
  7707.     ok = ioctl(ttyfd,TIOCSDEV,&tdcur);
  7708.     debug(F101,"ttsspd BELLV10 ioctl","",ok);
  7709.     if (ok < 0) {
  7710.         perror(ttnmsv);
  7711.         debug(F101,"ttsspd BELLV10 errno","",ok);
  7712.         return(-1);
  7713.     }
  7714. #else
  7715.     x = gtty(ttyfd,&ttcur);
  7716.     debug(F101,"ttsspd gtty","",x);
  7717.     if (x < 0) return(-1);
  7718.     ttcur.sg_ospeed = s; ttcur.sg_ispeed = s2;
  7719.     tttvt.sg_ospeed = s; tttvt.sg_ispeed = s2;
  7720.     ttraw.sg_ospeed = s; ttraw.sg_ispeed = s2;
  7721.     ttold.sg_ospeed = s; ttold.sg_ispeed = s2;
  7722.     x = stty(ttyfd,&ttcur);
  7723.     debug(F101,"ttsspd stty","",x);
  7724.     if (x < 0) return(-1);
  7725. #endif /* BELLV10 */
  7726. #endif /* ATTSV */
  7727. #endif /* BSD44ORPOSIX */
  7728. #endif /* Plan9 */
  7729.     }
  7730.     return(1);                /* Return 1 = success. */
  7731. #endif /* USETCSETSPEED */
  7732. }
  7733.  
  7734. #endif /* NOLOCAL */
  7735.  
  7736. /* C O N G S P D  -  Get speed of console terminal  */
  7737.  
  7738. long
  7739. congspd() {
  7740. /*
  7741.   This is a disgusting hack.  The right way to do this would be to pass an
  7742.   argument to ttgspd(), but then we'd need to change the Kermit API and
  7743.   all of the ck?tio.c modules.  (Currently used only for rlogin.)
  7744. */
  7745.     int t1;
  7746.     long spd;
  7747. #ifdef NETCONN
  7748.     int t2 = netconn;
  7749.     netconn = 0;
  7750. #endif /* NETCONN */
  7751.     t1 = ttyfd;
  7752.     ttyfd = -1;
  7753.     spd = ttgspd();
  7754.     debug(F101,"congspd","",spd);
  7755. #ifdef NETCONN
  7756.     netconn = t2;
  7757. #endif /* NETCONN */
  7758.     ttyfd = t1;
  7759.     return(spd);
  7760. }
  7761.  
  7762. /*  T T S P D L I S T  -- Get list of serial speeds allowed on this platform */
  7763.  
  7764. #define NSPDLIST 64
  7765. static long spdlist[NSPDLIST];
  7766. /*
  7767.   As written, this picks up the speeds known at compile time, and thus
  7768.   apply to the system where C-Kermit was built, rather than to the one where
  7769.   it is running.  Suggestions for improvement are always welcome.
  7770. */
  7771. long *
  7772. ttspdlist() {
  7773.     int i;
  7774.     for (i = 0; i < NSPDLIST; i++)    /* Initialize the list */
  7775.       spdlist[i] = -1L;
  7776.     i = 1;
  7777.  
  7778. #ifdef USETCSETSPEED            /* No way to find out what's legal */
  7779.     debug(F100,"ttspdlist USETCSETSPEED","",0);
  7780.     spdlist[i++] = 50L;
  7781. #ifndef UW7
  7782.     spdlist[i++] = 75L;
  7783. #endif /* UW7 */
  7784.     spdlist[i++] = 110L;
  7785. #ifndef UW7
  7786.     spdlist[i++] = 134L;
  7787. #endif /* UW7 */
  7788.     spdlist[i++] = 150L;
  7789.     spdlist[i++] = 200L;
  7790.     spdlist[i++] = 300L;
  7791.     spdlist[i++] = 600L;
  7792.     spdlist[i++] = 1200L;
  7793.     spdlist[i++] = 1800L;
  7794.     spdlist[i++] = 2400L;
  7795.     spdlist[i++] = 4800L;
  7796.     spdlist[i++] = 8880L;
  7797.     spdlist[i++] = 9600L;
  7798.     spdlist[i++] = 14400L;
  7799.     spdlist[i++] = 19200L;
  7800.     spdlist[i++] = 28800L;
  7801. #ifndef UW7
  7802.     spdlist[i++] = 33600L;
  7803. #endif /* UW7 */
  7804.     spdlist[i++] = 38400L;
  7805.     spdlist[i++] = 57600L;
  7806.     spdlist[i++] = 76800L;
  7807.     spdlist[i++] = 115200L;
  7808. #ifndef UW7
  7809.     spdlist[i++] = 153600L;
  7810.     spdlist[i++] = 230400L;
  7811.     spdlist[i++] = 307200L;
  7812.     spdlist[i++] = 460800L;
  7813.     spdlist[i++] = 921600L;
  7814. #endif /* UW7 */
  7815.  
  7816. #else  /* USETCSETSPEED */
  7817.  
  7818.     debug(F100,"ttspdlist no USETCSETSPEED","",0);
  7819.  
  7820. #ifdef B50
  7821.     debug(F101,"ttspdlist B50","",B50);
  7822.     spdlist[i++] = 50L;
  7823. #endif /* B50 */
  7824. #ifdef B75
  7825.     debug(F101,"ttspdlist B75","",B75);
  7826.     spdlist[i++] = 75L;
  7827. #endif /* B75 */
  7828. #ifdef B110
  7829.     debug(F101,"ttspdlist B110","",B110);
  7830.     spdlist[i++] = 110L;
  7831. #endif /* B110 */
  7832. #ifdef B134
  7833.     debug(F101,"ttspdlist B134","",B134);
  7834.     spdlist[i++] = 134L;
  7835. #endif /* B134 */
  7836. #ifdef B150
  7837.     debug(F101,"ttspdlist B150","",B150);
  7838.     spdlist[i++] = 150L;
  7839. #endif /* B150 */
  7840. #ifdef B200
  7841.     debug(F101,"ttspdlist B200","",B200);
  7842.     spdlist[i++] = 200L;
  7843. #endif /* B200 */
  7844. #ifdef B300
  7845.     debug(F101,"ttspdlist B300","",B300);
  7846.     spdlist[i++] = 300L;
  7847. #endif /* B300 */
  7848. #ifdef B600
  7849.     debug(F101,"ttspdlist B600","",B600);
  7850.     spdlist[i++] = 600L;
  7851. #endif /* B600 */
  7852. #ifdef B1200
  7853.     debug(F101,"ttspdlist B1200","",B1200);
  7854.     spdlist[i++] = 1200L;
  7855. #endif /* B1200 */
  7856. #ifdef B1800
  7857.     debug(F101,"ttspdlist B1800","",B1800);
  7858.     spdlist[i++] = 1800L;
  7859. #endif /* B1800 */
  7860. #ifdef B2400
  7861.     debug(F101,"ttspdlist B2400","",B2400);
  7862.     spdlist[i++] = 2400L;
  7863. #endif /* B2400 */
  7864. #ifdef B4800
  7865.     debug(F101,"ttspdlist B4800","",B4800);
  7866.     spdlist[i++] = 4800L;
  7867. #endif /* B4800 */
  7868. #ifdef B9600
  7869.     debug(F101,"ttspdlist B9600","",B9600);
  7870.     spdlist[i++] = 9600L;
  7871. #endif /* B9600 */
  7872. #ifdef B14400
  7873.     debug(F101,"ttspdlist B14400","",B14400);
  7874.     spdlist[i++] = 14400L;
  7875. #endif /* B14400 */
  7876. #ifdef B19200
  7877.     debug(F101,"ttspdlist B19200","",B19200);
  7878.     spdlist[i++] = 19200L;
  7879. #else
  7880. #ifdef EXTA
  7881.     debug(F101,"ttspdlist EXTA","",EXTA);
  7882.     spdlist[i++] = 19200L;
  7883. #endif /* EXTA */
  7884. #endif /* B19200 */
  7885. #ifdef B28800
  7886.     debug(F101,"ttspdlist B28800","",B28800);
  7887.     spdlist[i++] = 28800L;
  7888. #endif /* B28800 */
  7889. #ifdef B33600
  7890.     debug(F101,"ttspdlist B33600","",B33600);
  7891.     spdlist[i++] = 33600L;
  7892. #endif /* B33600 */
  7893. #ifdef B38400
  7894.     debug(F101,"ttspdlist B38400","",B38400);
  7895.     spdlist[i++] = 38400L;
  7896. #else
  7897. #ifdef EXTB
  7898.     debug(F101,"ttspdlist EXTB","",EXTB);
  7899.     spdlist[i++] = 38400L;
  7900. #endif /* EXTB */
  7901. #endif /* B38400 */
  7902. #ifdef _B57600
  7903.     debug(F101,"ttspdlist _B57600","",_B57600);
  7904.     spdlist[i++] = 57600L;
  7905. #else
  7906. #ifdef B57600
  7907.     debug(F101,"ttspdlist B57600","",B57600);
  7908.     spdlist[i++] = 57600L;
  7909. #endif /* B57600 */
  7910. #endif /* _B57600 */
  7911. #ifdef B76800
  7912.     debug(F101,"ttspdlist B76800","",B76800);
  7913.     spdlist[i++] = 76800L;
  7914. #endif /* B76800 */
  7915. #ifdef _B115200
  7916.     debug(F101,"ttspdlist _B115200","",_B115200);
  7917.     spdlist[i++] = 115200L;
  7918. #else
  7919. #ifdef B115200
  7920.     debug(F101,"ttspdlist B115200","",B115200);
  7921.     spdlist[i++] = 115200L;
  7922. #endif /* B115200 */
  7923. #endif /* _B115200 */
  7924. #ifdef B153600
  7925.     debug(F101,"ttspdlist B153600","",B153600);
  7926.     spdlist[i++] = 153600L;
  7927. #endif /* B153600 */
  7928. #ifdef B230400
  7929.     debug(F101,"ttspdlist B230400","",B230400);
  7930.     spdlist[i++] = 230400L;
  7931. #endif /* B230400 */
  7932. #ifdef B307200
  7933.     debug(F101,"ttspdlist B307200","",B307200);
  7934.     spdlist[i++] = 307200L;
  7935. #endif /* B307200 */
  7936. #ifdef B460800
  7937.     debug(F101,"ttspdlist B460800","",B460800);
  7938.     spdlist[i++] = 460800L;
  7939. #endif /* B460800 */
  7940. #ifdef B921600
  7941.     debug(F101,"ttspdlist B921600","",B921600);
  7942.     spdlist[i++] = 921600L;
  7943. #endif /* B921600 */
  7944. #endif /* USETCSETSPEED */
  7945.     spdlist[0] = i - 1;            /* Return count in 0th element */
  7946.     debug(F111,"ttspdlist spdlist","0",spdlist[0]);
  7947.     return((long *)spdlist);
  7948. }
  7949.  
  7950. /* T T G S P D  -  Get speed of currently selected tty line  */
  7951.  
  7952. /*
  7953.   Unreliable.  After SET LINE, it returns an actual speed, but not necessarily
  7954.   the real speed.  On some systems, it returns the line's nominal speed, from
  7955.   /etc/ttytab.  Even if you SET SPEED to something else, this function might
  7956.   not notice.
  7957. */
  7958. long
  7959. ttgspd() {                /* Get current serial device speed */
  7960. #ifdef NOLOCAL
  7961.     return(-1L);
  7962. #else
  7963. #ifdef POSIX
  7964.     speed_t                /* Should be unsigned */
  7965. #else
  7966.     int                    /* Isn't unsigned */
  7967. #endif /* POSIX */
  7968.       s;
  7969.     int x;
  7970.     long ss;
  7971. #ifdef OLINUXHISPEED
  7972.     unsigned int spd_flags = 0;
  7973.     struct serial_struct serinfo;
  7974. #endif /* OLINUXHISPEED */
  7975.  
  7976. #ifdef NETCONN
  7977.     if (netconn) {
  7978. #ifdef TN_COMPORT
  7979.     if (istncomport())
  7980.       return(tnc_get_baud());
  7981.     else
  7982. #endif /* TN_COMPORT */
  7983.       return(-1);            /* -1 if network connection */
  7984.     }
  7985. #endif /* NETCONN */
  7986. #ifdef NETCMD
  7987.     if (ttpipe) return(-1);
  7988. #endif /* NETCMD */
  7989. #ifdef NETPTY
  7990.     if (ttpty) return(-1);
  7991. #endif /* NETPTY */
  7992.  
  7993.     debug(F101,"ttgspd ttyfd","",ttyfd);
  7994.  
  7995. #ifdef USETCSETSPEED
  7996.  
  7997.     x = tcgetattr(ttyfd,&ttcur);    /* Get current speed */
  7998.     debug(F101,"ttgspd tcgetattr","",x);
  7999.     if (x < 0)
  8000.       return(-1);
  8001.     errno = 0;
  8002.     s = tcgetspeed(TCS_ALL, &ttcur);
  8003.     debug(F101,"ttsspd TCGETSPEED speed","",s);
  8004.     if (s == 0) {
  8005.     long s1, s2;
  8006.     s1 = tcgetspeed(TCS_IN, &ttcur);
  8007.     s2 = tcgetspeed(TCS_OUT, &ttcur);
  8008.     if (s1 == 1200L && s2 == 75L)
  8009.       return(8880L);
  8010.     }
  8011. #ifdef DEBUG
  8012.     if (errno & deblog) {
  8013.     debug(F101,"ttsspd TCGETSPEED errno","",errno);
  8014.     }
  8015. #endif /* DEBUG */
  8016.     return(s);
  8017.  
  8018. #else  /* Not USETCSETSPEED */
  8019.  
  8020. #ifdef Plan9
  8021.     if (ttyfd < 0)
  8022.       ss = -1;
  8023.     else
  8024.       ss = ttylastspeed;
  8025. #else
  8026. #ifdef OLINUXHISPEED
  8027.     debug(F100,"ttgspd Linux OLINUXHISPEED","",0);
  8028. #endif /* OLINUXHISPEED */
  8029.  
  8030.     if (ttyfd < 0) {
  8031. #ifdef BSD44ORPOSIX
  8032.     s = cfgetospeed(&ccold);
  8033.     debug(F101,"ttgspd cfgetospeed 1 POSIX","",s);
  8034. #else
  8035. #ifdef ATTSV
  8036.     s = ccold.c_cflag & CBAUD;
  8037.     debug(F101,"ttgspd c_cflag CBAUD 1 ATTSV","",s);
  8038. #else
  8039.     s = ccold.sg_ospeed;        /* (obtained by congm()) */
  8040.     debug(F101,"ttgspd sg_ospeed 1","",s);
  8041. #endif /* ATTSV */
  8042. #endif /* BSD44POSIX */
  8043.  
  8044.     } else {
  8045. #ifdef BSD44ORPOSIX
  8046.     if (tcgetattr(ttyfd,&ttcur) < 0) return(-1);
  8047.     s = cfgetospeed(&ttcur);
  8048.     debug(F101,"ttgspd cfgetospeed 2 BSDORPOSIX","",s);
  8049. #ifdef OLINUXHISPEED
  8050.     if (ioctl(ttyfd,TIOCGSERIAL,&serinfo) > -1)
  8051.       spd_flags = serinfo.flags & ASYNC_SPD_MASK;
  8052.     debug(F101,"ttgspd spd_flags","",spd_flags);
  8053. #endif /* OLINUXHISPEED */
  8054. #else
  8055. #ifdef ATTSV
  8056.     x = ioctl(ttyfd,TCGETA,&ttcur);
  8057.     debug(F101,"ttgspd ioctl 2 ATTSV x","",x);
  8058.     debug(F101,"ttgspd ioctl 2 ATTSV errno","",errno);
  8059.     if (x < 0) return(-1);
  8060.     s = ttcur.c_cflag & CBAUD;
  8061.     debug(F101,"ttgspd ioctl 2 ATTSV speed","",s);
  8062. #else
  8063. #ifdef BELLV10
  8064.     x = ioctl(ttyfd,TIOCGDEV,&tdcur);
  8065.     debug(F101,"ttgspd ioctl 2 BELLV10 x","",x);
  8066.     if (x < 0) return(-1);
  8067.     s = tdcur.ospeed;
  8068.     debug(F101,"ttgspd ioctl 2 BELLV10 speed","",s);
  8069. #else
  8070.     x = gtty(ttyfd,&ttcur);
  8071.     debug(F101,"ttgspd gtty 2 x","",x);
  8072.     debug(F101,"ttgspd gtty 2 errno","",errno);
  8073.     if (x < 0) return(-1);
  8074.     s = ttcur.sg_ospeed;
  8075.     debug(F101,"ttgspd gtty 2 speed","",s);
  8076. #endif /* BELLV10 */
  8077. #endif /* ATTSV */
  8078. #endif /* BSD44ORPOSIX */
  8079.     }
  8080.     debug(F101,"ttgspd code","",s);
  8081. #ifdef OLINUXHISPEED
  8082.     debug(F101,"ttgspd spd_flags","",spd_flags);
  8083. #endif /* OLINUXHISPEED */
  8084.     switch (s) {
  8085. #ifdef B0
  8086.       case B0:    ss = 0L; break;
  8087. #endif /* B0 */
  8088.  
  8089. #ifndef MINIX
  8090. /*
  8091.  MINIX defines the Bxx symbols to be bps/100, so B50==B75, B110==B134==B150,
  8092.  etc, making for many "duplicate case in switch" errors, which are fatal.
  8093. */
  8094. #ifdef B50
  8095.       case B50:   ss = 50L; break;
  8096. #endif /* B50 */
  8097. #ifdef B75
  8098.       case B75:   ss = 75L; break;
  8099. #endif /* B75 */
  8100. #endif /* MINIX */
  8101.  
  8102. #ifdef B110
  8103.       case B110:  ss = 110L; break;
  8104. #endif /* B110 */
  8105.  
  8106. #ifndef MINIX
  8107. #ifdef B134
  8108.       case B134:  ss = 134L; break;
  8109. #endif /* B134 */
  8110. #ifdef B150
  8111.       case B150:  ss = 150L; break;
  8112. #endif /* B150 */
  8113. #endif /* MINIX */
  8114.  
  8115. #ifdef B200
  8116.       case B200:  ss = 200L; break;
  8117. #endif /* B200 */
  8118.  
  8119. #ifdef B300
  8120.       case B300:  ss = 300L; break;
  8121. #endif /* B300 */
  8122.  
  8123. #ifdef B600
  8124.       case B600:  ss = 600L; break;
  8125. #endif /* B600 */
  8126.  
  8127. #ifdef B1200
  8128.       case B1200: ss = 1200L; break;
  8129. #endif /* B1200 */
  8130.  
  8131. #ifdef B1800
  8132.       case B1800: ss = 1800L; break;
  8133. #endif /* B1800 */
  8134.  
  8135. #ifdef B2400
  8136.       case B2400: ss = 2400L; break;
  8137. #endif /* B2400 */
  8138.  
  8139. #ifdef B4800
  8140.       case B4800: ss = 4800L; break;
  8141. #endif /* B4800 */
  8142.  
  8143. #ifdef B7200
  8144.       case B7200: ss = 7200L; break;
  8145. #endif /* B7200 */
  8146.  
  8147. #ifdef B9600
  8148.       case B9600: ss = 9600L; break;
  8149. #endif /* B9600 */
  8150.  
  8151. #ifdef B19200
  8152.       case B19200: ss = 19200L; break;
  8153. #else
  8154. #ifdef EXTA
  8155.       case EXTA: ss = 19200L; break;
  8156. #endif /* EXTA */
  8157. #endif /* B19200 */
  8158.  
  8159. #ifndef MINIX
  8160. #ifdef B38400
  8161.       case B38400:
  8162.         ss = 38400L;
  8163. #ifdef OLINUXHISPEED
  8164.         switch(spd_flags) {
  8165.           case ASYNC_SPD_HI:  ss =  57600L; break;
  8166.           case ASYNC_SPD_VHI: ss = 115200L; break;
  8167.     }
  8168. #endif /* OLINUXHISPEED */
  8169.         break;
  8170. #else
  8171. #ifdef EXTB
  8172.       case EXTB: ss = 38400L; break;
  8173. #endif /* EXTB */
  8174. #endif /* B38400 */
  8175. #endif /* MINIX */
  8176.  
  8177. #ifdef HPUX
  8178. #ifdef _B57600
  8179.       case _B57600: ss = 57600L; break;
  8180. #endif /* _B57600 */
  8181. #ifdef _B115200
  8182.       case _B115200: ss = 115200L; break;
  8183. #endif /* _B115200 */
  8184. #else
  8185. #ifdef B57600
  8186.       case B57600: ss = 57600L; break;
  8187. #endif /* B57600 */
  8188. #ifdef B76800
  8189.       case B76800: ss = 76800L; break;
  8190. #endif /* B76800 */
  8191. #ifdef B115200
  8192.       case B115200: ss = 115200L; break;
  8193. #endif /* B115200 */
  8194. #ifdef B153600
  8195.       case B153600: ss = 153600L; break;
  8196. #endif /* B153600 */
  8197. #ifdef B230400
  8198.       case B230400: ss = 230400L; break;
  8199. #endif /* B230400 */
  8200. #ifdef B307200
  8201.       case B307200: ss = 307200L; break;
  8202. #endif /* B307200 */
  8203. #ifdef B460800
  8204.       case B460800: ss = 460800L; break;
  8205. #endif /* B460800 */
  8206. #endif /* HPUX */
  8207. #ifdef B921600
  8208.       case B921600: ss = 921600L; break;
  8209. #endif /* B921600 */
  8210.       default:
  8211.     ss = -1; break;
  8212.     }
  8213. #endif /* Plan9 */
  8214.     debug(F101,"ttgspd speed","",ss);
  8215.     return(ss);
  8216.  
  8217. #endif /* USETCSETSPEED */
  8218. #endif /* NOLOCAL */
  8219. }
  8220. #ifdef MINIX2                /* Another hack alert */
  8221. #define MINIX
  8222. #endif /* MINIX2 */
  8223.  
  8224. /*
  8225.   FIONREAD data type...  This has been defined as "long" for many, many
  8226.   years, and it worked OK until 64-bit platforms appeared.  Thus we use
  8227.   int for 64-bit platforms, but keep long for the others.  If we changed
  8228.   the default PEEKTYPE to int, this would probably break 16-bit builds
  8229.   (note that sizeof(long) == sizeof(int) on most 32-bit platforms), many
  8230.   of which we have no way of testing any more.  Therefore, do not change
  8231.   the default definition of PEEKTYPE -- only add exceptions to it as needed.
  8232. */
  8233. #ifdef COHERENT
  8234. #ifdef FIONREAD
  8235. #undef FIONREAD
  8236. #endif /* FIONREAD */
  8237. /* #define FIONREAD TIOCQUERY */
  8238. /* #define PEEKTYPE int */
  8239. #else  /* Not COHERENT... */
  8240.  
  8241. #ifdef OSF32                /* Digital UNIX 3.2 or higher */
  8242. #define PEEKTYPE int
  8243. #else
  8244. #define PEEKTYPE long            /* Elsewhere (see notes above) */
  8245. #endif /* OSF32 */
  8246. #endif /* COHERENT */
  8247.  
  8248. /* ckumyr.c by Kristoffer Eriksson, ske@pkmab.se, 15 Mar 1990. */
  8249.  
  8250. #ifdef MYREAD
  8251.  
  8252. /* Private buffer for myread() and its companions.  Not for use by anything
  8253.  * else.  ttflui() is allowed to reset them to initial values.  ttchk() is
  8254.  * allowed to read my_count.
  8255.  *
  8256.  * my_item is an index into mybuf[].  Increment it *before* reading mybuf[].
  8257.  *
  8258.  * A global parity mask variable could be useful too.  We could use it to
  8259.  * let myread() strip the parity on its own, instead of stripping sign
  8260.  * bits as it does now.
  8261.  */
  8262. #ifdef BIGBUFOK
  8263. #define MYBUFLEN 32768
  8264. #else
  8265. #ifdef pdp11
  8266. #define MYBUFLEN 256
  8267. #else
  8268. #define MYBUFLEN 1024
  8269. #endif /* pdp11 */
  8270. #endif /* BIGBUFOK */
  8271.  
  8272. #ifdef ANYX25
  8273. #undef MYBUFLEN
  8274. #define MYBUFLEN 256
  8275. /*
  8276.   On X.25 connections, there is an extra control byte at the beginning.
  8277. */
  8278. static CHAR x25buf[MYBUFLEN+1];        /* Communication device input buffer */
  8279. static CHAR  *mybuf = x25buf+1;
  8280. #else
  8281. static CHAR mybuf[MYBUFLEN];
  8282. #endif /* ANYX25 */
  8283.  
  8284. static int my_count = 0;        /* Number of chars still in mybuf */
  8285. static int my_item = -1;        /* Last index read from mybuf[]   */
  8286.  
  8287. /*  T T P E E K  --  Peek into our internal communications input buffers. */
  8288.  
  8289. /*
  8290.   NOTE: This routine is peculiar to UNIX, and is used only by the
  8291.   select()-based CONNECT module, ckucns.c.  It need not be replicated in
  8292.   the ck?tio.c of other platforms.
  8293. */
  8294. int
  8295. ttpeek() {
  8296. #ifdef TTLEBUF
  8297.     int rc = 0;
  8298.     if (ttpush >= 0)
  8299.       rc++;
  8300.     rc += le_inbuf();
  8301.     if (rc > 0)
  8302.       return(rc);
  8303.     else
  8304. #endif /* TTLEBUF */
  8305.  
  8306. #ifdef MYREAD
  8307.     return(my_count);
  8308. #else
  8309.     return(0);
  8310. #endif /* MYREAD */
  8311. }
  8312.  
  8313. /* myread() -- Efficient read of one character from communications line.
  8314.  *
  8315.  * NOTE: myread() and its helpers mygetbuf() and myfillbuf() return raw
  8316.  * bytes from connection, so when the connection is encrypted, these bytes
  8317.  * must be decrypted.
  8318.  *
  8319.  * Uses a private buffer to minimize the number of expensive read() system
  8320.  * calls.  Essentially performs the equivalent of read() of 1 character, which
  8321.  * is then returned.  By reading all available input from the system buffers
  8322.  * to the private buffer in one chunk, and then working from this buffer, the
  8323.  * number of system calls is reduced in any case where more than one character
  8324.  * arrives during the processing of the previous chunk, for instance high
  8325.  * baud rates or network type connections where input arrives in packets.
  8326.  * If the time needed for a read() system call approaches the time for more
  8327.  * than one character to arrive, then this mechanism automatically compensates
  8328.  * for that by performing bigger read()s less frequently.  If the system load
  8329.  * is high, the same mechanism compensates for that too.
  8330.  *
  8331.  * myread() is a macro that returns the next character from the buffer.  If the
  8332.  * buffer is empty, mygetbuf() is called.  See mygetbuf() for possible error
  8333.  * returns.
  8334.  *
  8335.  * This should be efficient enough for any one-character-at-a-time loops.
  8336.  * For even better efficiency you might use memcpy()/bcopy() or such between
  8337.  * buffers (since they are often better optimized for copying), but it may not
  8338.  * be worth it if you have to take an extra pass over the buffer to strip
  8339.  * parity and check for CTRL-C anyway.
  8340.  *
  8341.  * Note that if you have been using myread() from another program module, you
  8342.  * may have some trouble accessing this macro version and the private variables
  8343.  * it uses.  In that case, just add a function in this module, that invokes the
  8344.  * macro.
  8345.  */
  8346. #define myread() (--my_count < 0 ? mygetbuf() : 255 & (int)mybuf[++my_item])
  8347.  
  8348. /* Specification: Push back up to one character onto myread()'s queue.
  8349.  *
  8350.  * This implementation: Push back characters into mybuf. At least one character
  8351.  * must have been read through myread() before myunrd() may be used.  After
  8352.  * EOF or read error, again, myunrd() can not be used.  Sometimes more than
  8353.  * one character can be pushed back, but only one character is guaranteed.
  8354.  * Since a previous myread() must have read its character out of mybuf[],
  8355.  * that guarantees that there is space for at least one character.  If push
  8356.  * back was really needed after EOF, a small addition could provide that.
  8357.  *
  8358.  * As of 02/2007 myunrd() is used by ttinl().
  8359.  */
  8360. VOID
  8361. #ifdef CK_ANSIC
  8362. myunrd(CHAR ch)
  8363. #else
  8364. myunrd(ch) CHAR ch;
  8365. #endif    /* CK_ANSIC */
  8366. {
  8367.     if (my_item >= 0) {
  8368.     mybuf[my_item--] = ch;
  8369.     ++my_count;
  8370.     }
  8371. }
  8372.  
  8373. /*  T T P U S H B A C K  --  Put n bytes back into the myread buffer */
  8374.  
  8375. static CHAR * pushbuf = NULL;
  8376. /* static int pushed = 0; */
  8377.  
  8378. int
  8379. ttpushback(s,n) CHAR * s; int n; {
  8380.     debug(F101,"ttpushback n","",n);
  8381.     if (pushbuf || n > MYBUFLEN || n < 1)
  8382.       return(-1);
  8383.     debug(F101,"ttpushback my_count","",my_count);
  8384.     if (my_count > 0) {
  8385.     if (!(pushbuf = (CHAR *)malloc(n+1)))
  8386.       return(-1);
  8387.     memcpy(pushbuf,mybuf,my_count);
  8388.     /* pushed = my_count; */ /* (set but never used) */
  8389.     }
  8390.     memcpy(mybuf,s,n);
  8391.     my_count = n;
  8392.     my_item = -1;
  8393.     return(0);
  8394. }
  8395.  
  8396. /* mygetbuf() -- Fill buffer for myread() and return first character.
  8397.  *
  8398.  * This function is what myread() uses when it can't get the next character
  8399.  * directly from its buffer.  First, it calls a system dependent myfillbuf()
  8400.  * to read at least one new character into the buffer, and then it returns
  8401.  * the first character just as myread() would have done.  This function also
  8402.  * is responsible for all error conditions that myread() can indicate.
  8403.  *
  8404.  * Returns: When OK    => a positive character, 0 or greater.
  8405.  *        When EOF    => -2.
  8406.  *        When error    => -3, error code in errno.
  8407.  *
  8408.  * Older myread()s additionally returned -1 to indicate that there was nothing
  8409.  * to read, upon which the caller would call myread() again until it got
  8410.  * something.  The new myread()/mygetbuf() always gets something.  If it
  8411.  * doesn't, then make it do so!  Any program that actually depends on the old
  8412.  * behaviour will break.
  8413.  *
  8414.  * The older version also used to return -2 both for EOF and other errors,
  8415.  * and used to set errno to 9999 on EOF.  The errno stuff is gone, EOF and
  8416.  * other errors now return different results, although Kermit currently never
  8417.  * checks to see which it was.  It just disconnects in both cases.
  8418.  *
  8419.  * Kermit lets the user use the quit key to perform some special commands
  8420.  * during file transfer.  This causes read(), and thus also mygetbuf(), to
  8421.  * finish without reading anything and return the EINTR error.  This should
  8422.  * be checked by the caller.  Mygetbuf() could retry the read() on EINTR,
  8423.  * but if there is nothing to read, this could delay Kermit's reaction to
  8424.  * the command, and make Kermit appear unresponsive.
  8425.  *
  8426.  * The debug() call should be removed for optimum performance.
  8427.  */
  8428. int
  8429. mygetbuf() {
  8430.     int x;
  8431.     errno = 0;
  8432. #ifdef DEBUG
  8433.     if (deblog && my_count > 0)
  8434.       debug(F101,"mygetbuf IMPROPERLY CALLED with my_count","",my_count);
  8435. #endif /* DEBUG */
  8436.     if (my_count <= 0)
  8437.       my_count = myfillbuf();
  8438.  
  8439. #ifdef DEBUG
  8440. #ifdef COMMENT
  8441.     if (deblog) debug(F101, "mygetbuf read", "", my_count);
  8442. #else /* COMMENT */
  8443.     ckhexdump("mygetbuf read", mybuf, my_count);
  8444. #endif /* COMMENT */
  8445. #endif /* DEBUG */
  8446.     x = my_count;
  8447.     if (my_count <= 0) {
  8448.     my_count = 0;
  8449.     my_item = -1;
  8450.     debug(F101,"mygetbuf errno","",errno);
  8451. #ifdef TCPSOCKET
  8452.     if (netconn && ttnet == NET_TCPB && errno != 0) {
  8453.         if (errno != EINTR) {
  8454.         debug(F101,"mygetbuf TCP error","",errno);
  8455.         ttclos(0);        /* Close the connection. */
  8456.         }
  8457.         return(-3);
  8458.     }
  8459. #endif /* TCPSOCKET */
  8460.     if (!netconn && xlocal && errno) {
  8461.         if (errno != EINTR) {
  8462.         debug(F101,"mygetbuf SERIAL error","",errno);
  8463.         x = -3;
  8464.         ttclos(0);        /* Close the connection. */
  8465.         }
  8466.     }
  8467.     return((x < 0) ? -3 : -2);
  8468.     }
  8469.     --my_count;
  8470.     return((unsigned)(0xff & mybuf[my_item = 0]));
  8471. }
  8472.  
  8473. /* myfillbuf():
  8474.  * System-dependent read() into mybuf[], as many characters as possible.
  8475.  *
  8476.  * Returns: OK => number of characters read, always more than zero.
  8477.  *          EOF => 0
  8478.  *          Error => -1, error code in errno.
  8479.  *
  8480.  * If there is input available in the system's buffers, all of it should be
  8481.  * read into mybuf[] and the function return immediately.  If no input is
  8482.  * available, it should wait for a character to arrive, and return with that
  8483.  * one in mybuf[] as soon as possible.  It may wait somewhat past the first
  8484.  * character, but be aware that any such delay lengthens the packet turnaround
  8485.  * time during kermit file transfers.  Should never return with zero characters
  8486.  * unless EOF or irrecoverable read error.
  8487.  *
  8488.  * Correct functioning depends on the correct tty parameters being used.
  8489.  * Better control of current parameters is required than may have been the
  8490.  * case in older Kermit releases.  For instance, O_NDELAY (or equivalent) can
  8491.  * no longer be sometimes off and sometimes on like it used to, unless a
  8492.  * special myfillbuf() is written to handle that.  Otherwise the ordinary
  8493.  * myfillbuf()s may think they have come to EOF.
  8494.  *
  8495.  * If your system has a facility to directly perform the functioning of
  8496.  * myfillbuf(), then use it.  If the system can tell you how many characters
  8497.  * are available in its buffers, then read that amount (but not less than 1).
  8498.  * If the system can return a special indication when you try to read without
  8499.  * anything to read, while allowing you to read all there is when there is
  8500.  * something, you may loop until there is something to read, but probably that
  8501.  * is not good for the system load.
  8502.  */
  8503.  
  8504. #ifdef SVORPOSIX
  8505.     /* This is for System III/V with VMIN>0, VTIME=0 and O_NDELAY off,
  8506.      * and CLOCAL set any way you like.  This way, read() will do exactly
  8507.      * what is required by myfillbuf(): If there is data in the buffers
  8508.      * of the O.S., all available data is read into mybuf, up to the size
  8509.      * of mybuf.  If there is none, the first character to arrive is
  8510.      * awaited and returned.
  8511.      */
  8512. int
  8513. myfillbuf() {
  8514.     int fd, n;
  8515. #ifdef NETCMD
  8516.     if (ttpipe)
  8517.       fd = fdin;
  8518.     else
  8519. #endif /* NETCMD */
  8520.       fd = ttyfd;
  8521.  
  8522. #ifdef sxaE50
  8523.     /* From S. Dezawa at Fujifilm in Japan.  I don't know why this is */
  8524.     /* necessary for the sxa E50, but it is. */
  8525.     return read(fd, mybuf, 255);
  8526. #else
  8527. #ifdef BEOSORBEBOX
  8528.     while (1) {
  8529. #ifdef NETCONN
  8530.         if (netconn) {
  8531.             n = netxin(sizeof(mybuf), (char *)mybuf);
  8532.             debug(F101,"BEBOX SVORPOSIX network myfillbuf","",n);
  8533.     }
  8534.         else
  8535. #endif /* NETCONN */
  8536.       n = read(fd, mybuf, sizeof(mybuf));
  8537.     debug(F101,"BEBOX SVORPOSIX notnet myfillbuf","",n);
  8538.         if (n > 0)
  8539.       return(n);
  8540.         snooze(1000.0);
  8541.     }
  8542. #else /* BEOSORBEBOX */
  8543.     errno = 0;
  8544.     /* debug(F101,"SVORPOSIX myfillbuf calling read() fd","",fd); */
  8545. #ifdef IBMX25
  8546.     if (netconn && (nettype == NET_IX25)) {
  8547.     /* can't use sizeof because mybuf is a pointer, and not an array! */
  8548.     n = x25xin( MYBUFLEN, mybuf );
  8549.     } else
  8550. #endif /* IBMX25 */
  8551.  
  8552. #ifdef CK_SSL
  8553.       if (ssl_active_flag || tls_active_flag) {
  8554.       int error, n = 0;
  8555.       debug(F100,"myfillbuf calling SSL_read() fd","",0);
  8556.       while (n == 0) {
  8557.           if (ssl_active_flag)
  8558.                 n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  8559.           else if (tls_active_flag)
  8560.                 n = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  8561.               else
  8562.         break;
  8563.           switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  8564.         case SSL_ERROR_NONE:
  8565.           if (n > 0)
  8566.                     return(n);
  8567.           if (n < 0)
  8568.                     return(-2);
  8569.           msleep(50);
  8570.           break;
  8571.         case SSL_ERROR_WANT_WRITE:
  8572.         case SSL_ERROR_WANT_READ:
  8573.           return(-1);
  8574.         case SSL_ERROR_SYSCALL:
  8575.           if (n != 0)
  8576.             return(-1);
  8577.         case SSL_ERROR_WANT_X509_LOOKUP:
  8578.         case SSL_ERROR_SSL:
  8579.         case SSL_ERROR_ZERO_RETURN:
  8580.         default:
  8581.           ttclos(0);
  8582.           return(-3);
  8583.             }
  8584.         }
  8585.     }
  8586. #endif /* CK_SSL */
  8587. #ifdef CK_KERBEROS
  8588. #ifdef KRB4
  8589. #ifdef RLOGCODE
  8590.     if (ttnproto == NP_EK4LOGIN) {
  8591.     debug(F101,"myfillbuf calling krb4_des_read() fd","",ttyfd);
  8592.         if ((n = krb4_des_read(ttyfd,(char *)mybuf,sizeof(mybuf))) < 0)
  8593.       return(-3);
  8594.         else
  8595.       return(n);
  8596.     }
  8597. #endif /* RLOGCODE */
  8598. #endif /* KRB4 */
  8599. #ifdef KRB5
  8600. #ifdef RLOGCODE
  8601.     if (ttnproto == NP_EK5LOGIN) {
  8602.     debug(F101,"myfillbuf calling krb5_des_read() fd","",ttyfd);
  8603.         if ((n = krb5_des_read(ttyfd,(char *)mybuf,sizeof(mybuf),0)) < 0)
  8604.       return(-3);
  8605.         else
  8606.       return(n);
  8607.     }
  8608. #endif /* RLOGCODE */
  8609. #ifdef KRB5_U2U
  8610.     if (ttnproto == NP_K5U2U) {
  8611.     debug(F101,"myfillbuf calling krb5_u2u_read() fd","",ttyfd);
  8612.         if ((n = krb5_u2u_read(ttyfd,(char *)mybuf,sizeof(mybuf))) < 0)
  8613.       return(-3);
  8614.         else
  8615.       return(n);
  8616.     }
  8617. #endif /* KRB5_U2U */
  8618. #endif /* KRB5 */
  8619. #endif /* CK_KERBEROS */
  8620.  
  8621. #ifdef NETPTY
  8622. #ifdef HAVE_PTYTRAP
  8623.     /* Special handling for HP-UX pty i/o */
  8624.   ptyread:
  8625.     if (ttpty && pty_trap_pending(ttyfd) > 0) {
  8626.     debug(F101,"myfillbuf calling pty_trap_handler() fd","",ttyfd);
  8627.         if (pty_trap_handler(ttyfd) > 0) {
  8628.             ttclos(0);
  8629.             return(-3);
  8630.         }
  8631.     }
  8632. #endif /* HAVE_PTYTRAP */
  8633. #endif /* NETPTY */
  8634.     debug(F101,"myfillbuf calling read() fd","",ttyfd);
  8635.     n = read(fd, mybuf, sizeof(mybuf));
  8636.     debug(F101,"SVORPOSIX myfillbuf read","",n);
  8637.     debug(F101,"SVORPOSIX myfillbuf errno","",errno);
  8638.     debug(F101,"SVORPOSIX myfillbuf ttcarr","",ttcarr);
  8639.     if (n < 1) {
  8640. #ifdef NETPTY
  8641. #ifdef HAVE_PTYTRAP
  8642.         /* When we have a PTY trap in place the connection cannot */
  8643.         /* be closed until the trap receives a close indication.  */
  8644.         if (n == 0 && ttpty)
  8645.             goto ptyread;
  8646. #endif /* HAVE_PTYTRAP */
  8647. #endif /* NETPTY */
  8648.         return(-3);
  8649.     }
  8650.     return(n);
  8651. #endif /* BEOSORBEBOX */
  8652. #endif /* sxaE50 */
  8653. }
  8654.  
  8655. #else /* not AT&T or POSIX */
  8656.  
  8657. #ifdef aegis
  8658.     /* This is quoted from the old myread().  The semantics seem to be
  8659.      * alright, but maybe errno would not need to be set even when
  8660.      * there is no error?  I don't know aegis.
  8661.      */
  8662. int
  8663. myfillbuf() {
  8664.     int count;
  8665. #ifdef NETCMD
  8666.     if (ttpipe)
  8667.       fd = fdin;
  8668.     else
  8669. #endif /* NETCMD */
  8670.       fd = ttyfd;
  8671.  
  8672.     count = ios_$get((short)fd, ios_$cond_opt, mybuf, 256L, st);
  8673.     errno = EIO;
  8674.     if (st.all == ios_$get_conditional_failed) /* get at least one */
  8675.       count = ios_$get((short)fd, 0, mybuf, 1L, st);
  8676.     if (st.all == ios_$end_of_file)
  8677.       return(-3);
  8678.     else if (st.all != status_$ok) {
  8679.     errno = EIO;
  8680.     return(-1);
  8681.     }
  8682.     return(count > 0 ? count : -3);
  8683. }
  8684. #else /* !aegis */
  8685.  
  8686. #ifdef FIONREAD
  8687.     /* This is for systems with FIONREAD.  FIONREAD returns the number
  8688.      * of characters available for reading. If none are available, wait
  8689.      * until something arrives, otherwise return all there is.
  8690.      */
  8691. int
  8692. myfillbuf() {
  8693.     PEEKTYPE avail = 0;
  8694.     int x, fd;
  8695. #ifdef NETCMD
  8696.     if (ttpipe)
  8697.       fd = fdin;
  8698.     else
  8699. #endif /* NETCMD */
  8700.       fd = ttyfd;
  8701.  
  8702. #ifdef SUNX25
  8703. /*
  8704.   SunLink X.25 support in this routine from Stefaan A. Eeckels, Eurostat (CEC).
  8705.   Depends on SunOS having FIONREAD, not because we use it, but just so this
  8706.   code is grouped correctly within the #ifdefs.  Let's hope Solaris keeps it.
  8707.  
  8708.   We call x25xin() instead of read() so that Q-Bit packets, which contain
  8709.   X.25 service-level information (e.g. PAD parameter changes), can be processed
  8710.   transparently to the upper-level code.  This is a blocking read, and so
  8711.   we depend on higher-level code (such as ttinc()) to set any necessary alarms.
  8712. */
  8713.     extern int nettype;
  8714.     if (netconn && nettype == NET_SX25) {
  8715.     while ((x = x25xin(sizeof(x25buf), x25buf)) < 1) ;
  8716.     return(x - 1);            /* "-1" compensates for extra status byte */
  8717.     }
  8718. #endif /* SUNX25 */
  8719.  
  8720. #ifdef CK_SSL
  8721.     if (ssl_active_flag || tls_active_flag) {
  8722.         int error, n = 0;
  8723.         while (n == 0) {
  8724.             if (ssl_active_flag)
  8725.           n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  8726.             else
  8727.           n = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  8728.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  8729.           case SSL_ERROR_NONE:
  8730.                 if (n > 0)
  8731.           return(n);
  8732.                 if (n < 0)
  8733.           return(-2);
  8734.                 msleep(50);
  8735.                 break;
  8736.           case SSL_ERROR_WANT_WRITE:
  8737.           case SSL_ERROR_WANT_READ:
  8738.                 return(-1);
  8739.           case SSL_ERROR_SYSCALL:
  8740.         if (n != 0)
  8741.           return(-1);
  8742.           case SSL_ERROR_WANT_X509_LOOKUP:
  8743.           case SSL_ERROR_SSL:
  8744.           case SSL_ERROR_ZERO_RETURN:
  8745.           default:
  8746.                 ttclos(0);
  8747.                 return(-2);
  8748.             }
  8749.         }
  8750.     }
  8751. #endif /* CK_SSL */
  8752. #ifdef CK_KERBEROS
  8753. #ifdef KRB4
  8754. #ifdef RLOGCODE
  8755.     if (ttnproto == NP_EK4LOGIN) {
  8756.         if ((x = krb4_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8757.       return(-1);
  8758.         else
  8759.       return(x);
  8760.     }
  8761. #endif /* RLOGCODE */
  8762. #endif /* KRB4 */
  8763. #ifdef KRB5
  8764. #ifdef RLOGCODE
  8765.     if (ttnproto == NP_EK5LOGIN) {
  8766.         if ((x = krb5_des_read(ttyfd,mybuf,sizeof(mybuf),0)) < 0)
  8767.       return(-1);
  8768.         else
  8769.       return(x);
  8770.     }
  8771. #endif /* RLOGCODE */
  8772. #ifdef KRB5_U2U
  8773.     if (ttnproto == NP_K5U2U) {
  8774.         if ((x = krb5_u2u_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8775.       return(-1);
  8776.         else
  8777.       return(x);
  8778.     }
  8779. #endif /* KRB5_U2U */
  8780. #endif /* KRB5 */
  8781. #endif /* CK_KERBEROS */
  8782.  
  8783.     errno = 0;
  8784.     debug(F101,"myfillbuf calling FIONREAD ioctl","",xlocal);
  8785.     x = ioctl(fd, FIONREAD, &avail);
  8786. #ifdef DEBUG
  8787.     if (deblog) {
  8788.     debug(F101,"myfillbuf FIONREAD","",x);
  8789.     debug(F101,"myfillbuf FIONREAD avail","",avail);
  8790.     debug(F101,"myfillbuf FIONREAD errno","",errno);
  8791.     }
  8792. #endif /* DEBUG */
  8793.     if (x < 0 || avail == 0)
  8794.       avail = 1;
  8795.  
  8796.     if (avail > MYBUFLEN)
  8797.       avail = MYBUFLEN;
  8798.  
  8799.     errno = 0;
  8800.  
  8801.     x = read(fd, mybuf, (int) avail);
  8802. #ifdef DEBUG
  8803.     if (deblog) {
  8804.     debug(F101,"myfillbuf avail","",avail);
  8805.     debug(F101,"myfillbuf read","",x);
  8806.     debug(F101,"myfillbuf read errno","",errno);
  8807.         if (x > 0)
  8808.       ckhexdump("myfillbuf mybuf",mybuf,x);
  8809.     }
  8810. #endif /* DEBUG */
  8811.     if (x < 1) x = -3;            /* read 0 == connection loss */
  8812.     return(x);
  8813. }
  8814.  
  8815. #else /* !FIONREAD */
  8816. /* Add other systems here, between #ifdef and #else, e.g. NETCONN. */
  8817. /* When there is no other possibility, read 1 character at a time. */
  8818. int
  8819. myfillbuf() {
  8820.     int x;
  8821.  
  8822. #ifdef CK_SSL
  8823.     if (ssl_active_flag || tls_active_flag) {
  8824.         int error, n = 0;
  8825.         while (n == 0) {
  8826.             if (ssl_active_flag)
  8827.           n = SSL_read(ssl_con, (char *)mybuf, sizeof(mybuf));
  8828.             else
  8829.           count = SSL_read(tls_con, (char *)mybuf, sizeof(mybuf));
  8830.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,n)) {
  8831.           case SSL_ERROR_NONE:
  8832.                 if (n > 0)
  8833.           return(n);
  8834.                 if (n < 0)
  8835.           return(-2);
  8836.                 msleep(50);
  8837.                 break;
  8838.           case SSL_ERROR_WANT_WRITE:
  8839.           case SSL_ERROR_WANT_READ:
  8840.                 return(-1);
  8841.           case SSL_ERROR_SYSCALL:
  8842.         if (n != 0)
  8843.           return(-1);
  8844.           case SSL_ERROR_WANT_X509_LOOKUP:
  8845.           case SSL_ERROR_SSL:
  8846.           case SSL_ERROR_ZERO_RETURN:
  8847.           default:
  8848.                 ttclos(0);
  8849.                 return(-2);
  8850.             }
  8851.         }
  8852.     }
  8853. #endif /* CK_SSL */
  8854. #ifdef CK_KERBEROS
  8855. #ifdef KRB4
  8856. #ifdef RLOGCODE
  8857.     if (ttnproto == NP_EK4LOGIN) {
  8858.         if ((len = krb4_des_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8859.       return(-1);
  8860.         else
  8861.       return(len);
  8862.     }
  8863. #endif /* RLOGCODE */
  8864. #endif /* KRB4 */
  8865. #ifdef KRB5
  8866. #ifdef RLOGCODE
  8867.     if (ttnproto == NP_EK5LOGIN) {
  8868.         if ((len = krb5_des_read(ttyfd,mybuf,sizeof(mybuf),0)) < 0)
  8869.       return(-1);
  8870.         else
  8871.       return(len);
  8872.     }
  8873. #endif /* RLOGCODE */
  8874. #ifdef KRB5_U2U
  8875.     if (ttnproto == NP_K5U2U) {
  8876.         if ((len = krb5_u2u_read(ttyfd,mybuf,sizeof(mybuf))) < 0)
  8877.       return(-1);
  8878.         else
  8879.       return(len);
  8880.     }
  8881. #endif /* KRB5_U2U */
  8882. #endif /* KRB5 */
  8883. #endif /* CK_KERBEROS */
  8884.  
  8885. #ifdef NETCMD
  8886.     if (ttpipe)
  8887.       fd = fdin;
  8888.     else
  8889. #endif /* NETCMD */
  8890.       fd = ttyfd;
  8891.     x = read(fd, mybuf, 1);
  8892.     return(x > 0 ? x : -3);
  8893. }
  8894.  
  8895. #endif /* !FIONREAD */
  8896. #endif /* !aegis */
  8897. #endif /* !ATTSV */
  8898.  
  8899. #endif /* MYREAD */
  8900.  
  8901. /*  T T _ T N O P T  --  Handle Telnet negotions in incoming data */
  8902. /*
  8903.   Call with the IAC that was encountered.
  8904.   Returns:
  8905.    -3: If connection has dropped or gone bad.
  8906.    -2: On Telnet protocol error resulting in inconsistent states.
  8907.     0: If negotiation OK and caller has nothing to do.
  8908.     1: If packet start character has changed (new value is in global stchr).
  8909.   255: If there was a quoted IAC as data.
  8910.    or: Not at all if we got a legitimate Telnet Logout request.
  8911. */
  8912. #ifdef TCPSOCKET
  8913. static int
  8914. tt_tnopt(n) int n; {            /* Handle Telnet options */
  8915.     /* In case caller did not already check these conditions...  */
  8916.     if (n == IAC &&
  8917.     ((xlocal && netconn && IS_TELNET()) ||
  8918.      (!xlocal && sstelnet))) {
  8919.     extern int server;
  8920.     int tx = 0;
  8921.     debug(F100,"ttinl calling tn_doop()","",0);
  8922.     tx = tn_doop((CHAR)(n & 0xff),duplex,ttinc);
  8923.     debug(F111,"ttinl tn_doop() returned","tx",tx);
  8924.     switch (tx) {
  8925.       case 0:
  8926.         return(0);
  8927.       case -1:            /* I/O error */
  8928.         ttimoff();            /* Turn off timer */
  8929.         return(-3);
  8930.           case -2:            /* Connection failed. */
  8931.           case -3:
  8932.         ttimoff();            /* Turn off timer */
  8933.         ttclos(0);
  8934.         return(-3);
  8935.       case 1:            /* ECHO change */
  8936.         duplex = 1;
  8937.         return(0);
  8938.       case 2:            /* ECHO change */
  8939.         duplex = 0;
  8940.         return(0);
  8941.       case 3:            /* Quoted IAC */
  8942.         n = 255;
  8943.         return((unsigned)255);
  8944. #ifdef IKS_OPTION
  8945.       case 4: {
  8946.           if (TELOPT_SB(TELOPT_KERMIT).kermit.u_start && server
  8947. #ifdef IKSD
  8948.           && !inserver
  8949. #endif /* IKSD */
  8950.           ) {            /* Remote in Server mode */
  8951.           ttimoff();        /* Turn off timer */
  8952.           debug(F100,"u_start and !inserver","",0);
  8953.           return(-2);        /* End server mode */
  8954.           } else if (!TELOPT_SB(TELOPT_KERMIT).kermit.me_start &&
  8955.              server
  8956.              ) {        /* I'm no longer in Server Mode */
  8957.           debug(F100,"me_start and server","",0);
  8958.           ttimoff();
  8959.           return(-2);
  8960.           }
  8961.           return(0);
  8962.       }
  8963.       case 5: {            /* Start character change */
  8964.           /* extern CHAR stchr; */
  8965.           /* start = stchr; */
  8966.           return(1);
  8967.       }
  8968. #endif /* IKS_OPTION */
  8969.       case 6:            /* Remote Logout */
  8970.         ttimoff();
  8971.         ttclos(0);
  8972. #ifdef IKSD
  8973.         if (inserver && !local)
  8974.           doexit(GOOD_EXIT,0);
  8975.         else
  8976. #endif /* IKSD */
  8977.           return(-2);
  8978.       default:
  8979.         return(0);
  8980.     }
  8981.     } else
  8982.       return(0);
  8983. }
  8984. #endif /* TCPSOCKET */
  8985.  
  8986. /*  T T F L U I  --  Flush tty input buffer */
  8987.  
  8988. void
  8989. ttflux() {                /* But first... */
  8990. #ifdef MYREAD
  8991. /*
  8992.   Flush internal MYREAD buffer.
  8993. */
  8994. #ifdef TCPSOCKET
  8995.     int dotnopts, x;
  8996.     dotnopts = (((xlocal && netconn && IS_TELNET()) ||
  8997.          (!xlocal && sstelnet)));
  8998. #endif /* TCPSOCKET */
  8999.     debug(F101,"ttflux my_count","",my_count);
  9000. #ifdef TCPSOCKET
  9001.     if (dotnopts) {
  9002.     CHAR ch = '\0';
  9003.         while (my_count > 0) {
  9004.         ch = myread();
  9005. #ifdef CK_ENCRYPTION
  9006.             if (TELOPT_U(TELOPT_ENCRYPTION))
  9007.           ck_tn_decrypt((char *)&ch,1);
  9008. #endif /* CK_ENCRYPTION */
  9009.             if (ch == IAC)
  9010.           x = tt_tnopt(ch);
  9011.         }
  9012.     } else
  9013. #endif /* TCPSOCKET */
  9014. #ifdef COMMENT
  9015. #ifdef CK_ENCRYPTION
  9016.     if (TELOPT_U(TELOPT_ENCRYPTION) && my_count > 0)
  9017.       ck_tn_decrypt(&mybuf[my_item+1],my_count);
  9018. #endif /* CK_ENCRYPTION */
  9019. #endif /* COMMENT */
  9020.     my_count = 0;            /* Reset count to zero */
  9021.     my_item = -1;            /* And buffer index to -1 */
  9022. #endif /* MYREAD */
  9023. }
  9024.  
  9025. int
  9026. ttflui() {
  9027.     int n, fd;
  9028. #ifdef TCPSOCKET
  9029.     int dotnopts;
  9030.     dotnopts = (((xlocal && netconn && IS_TELNET()) ||
  9031.          (!xlocal && sstelnet)));
  9032. #endif /* TCPSOCKET */
  9033.  
  9034. #ifdef NETCMD
  9035.     if (ttpipe)
  9036.       fd = fdin;
  9037.     else
  9038. #endif /* NETCMD */
  9039.       fd = ttyfd;
  9040.  
  9041. #ifdef TTLEBUF
  9042.     ttpush = -1;            /* Clear the peek-ahead char */
  9043.     while (le_data && (le_inbuf() > 0)) {
  9044.         CHAR ch = '\0';
  9045.         if (le_getchar(&ch) > 0) {    /* Clear any more... */
  9046.             debug(F101,"ttflui le_inbuf ch","",ch);
  9047.         }
  9048.     }
  9049. #endif /* TTLEBUF */
  9050.     debug(F101,"ttflui ttpipe","",ttpipe);
  9051.  
  9052. #ifdef MYREAD
  9053. /*
  9054.   Flush internal MYREAD buffer *NEXT*, in all cases.
  9055. */
  9056.     ttflux();
  9057. #endif /* MYREAD */
  9058.  
  9059. #ifdef NETCONN
  9060. /* Network flush is done specially, in the network support module. */
  9061.     if ((netconn || sstelnet) && !ttpipe && !ttpty) {
  9062.     debug(F100,"ttflui netflui","",0);
  9063. #ifdef COMMENT
  9064. #ifdef TN_COMPORT
  9065.     if (istncomport())
  9066.             tnc_send_purge_data(TNC_PURGE_RECEIVE);
  9067. #endif /* TN_COMPORT */
  9068. #endif /* COMMENT */
  9069.     return(netflui());
  9070.     }
  9071. #endif /* NETCONN */
  9072.  
  9073.     debug(F101,"ttflui ttyfd","",ttyfd); /* Not network */
  9074.     if (ttyfd < 0)
  9075.       return(-1);
  9076.  
  9077. #ifdef aegis
  9078.     sio_$control((short)yfd, sio_$flush_in, true, st);
  9079.     if (st.all != status_$ok) {
  9080.     fprintf(stderr, "flush failed: "); error_$print(st);
  9081.     } else {      /* sometimes the flush doesn't work */
  9082.         for (;;) {
  9083.         char buf[256];
  9084.             /* eat all the characters that shouldn't be available */
  9085.             ios_$get((short)fd, ios_$cond_opt, buf, 256L, st); /* (void) */
  9086.             if (st.all == ios_$get_conditional_failed) break;
  9087.             fprintf(stderr, "flush failed(2): "); error_$print(st);
  9088.         }
  9089.     }
  9090. #else
  9091. #ifdef BSD44                /* 4.4 BSD */
  9092.     n = FREAD;                          /* Specify read queue */
  9093.     debug(F100,"ttflui BSD44","",0);
  9094.     ioctl(fd,TIOCFLUSH,&n);
  9095. #else
  9096. #ifdef Plan9
  9097. #undef POSIX                /* Uh oh... */
  9098. #endif /* Plan9 */
  9099. #ifdef POSIX                /* POSIX */
  9100.     debug(F100,"ttflui POSIX","",0);
  9101.     tcflush(fd,TCIFLUSH);
  9102. #else
  9103. #ifdef ATTSV                /* System V */
  9104. #ifndef VXVE
  9105.     debug(F100,"ttflui ATTSV","",0);
  9106.     ioctl(fd,TCFLSH,0);
  9107. #endif /* VXVE */
  9108. #else                    /* Not BSD44, POSIX, or Sys V */
  9109. #ifdef TIOCFLUSH            /* Those with TIOCFLUSH defined */
  9110. #ifdef ANYBSD                /* Berkeley */
  9111.     n = FREAD;                          /* Specify read queue */
  9112.     debug(F100,"ttflui TIOCFLUSH ANYBSD","",0);
  9113.     ioctl(fd,TIOCFLUSH,&n);
  9114. #else                    /* Others (V7, etc) */
  9115.     debug(F100,"ttflui TIOCFLUSH","",0);
  9116.     ioctl(fd,TIOCFLUSH,0);
  9117. #endif /* ANYBSD */
  9118. #else                    /* All others... */
  9119. /*
  9120.   No system call (that we know about) for input buffer flushing.
  9121.   So see how many there are and read them in a loop, using ttinc().
  9122.   ttinc() is buffered, so we're not getting charged with a system call
  9123.   per character, just a function call.
  9124. */
  9125.     if ((n = ttchk()) > 0) {
  9126.     debug(F101,"ttflui read loop","",n);
  9127.     while ((n--) && ttinc(0) > 0) ;
  9128.     }
  9129. #endif /* TIOCFLUSH */
  9130. #endif /* ATTSV */
  9131. #endif /* POSIX */
  9132. #ifdef Plan9
  9133. #define POSIX
  9134. #endif /* Plan9 */
  9135. #endif /* BSD44 */
  9136. #endif /* aegis */
  9137.     return(0);
  9138. }
  9139.  
  9140. int
  9141. ttfluo() {                /* Flush output buffer */
  9142.     int fd;
  9143. #ifdef NETCMD
  9144.     if (ttpipe)
  9145.       fd = fdout;
  9146.     else
  9147. #endif /* NETCMD */
  9148.       fd = ttyfd;
  9149.  
  9150. #ifdef Plan9
  9151.     return 0;
  9152. #else
  9153. #ifdef POSIX
  9154.     return(tcflush(fd,TCOFLUSH));
  9155. #else
  9156. #ifdef OXOS
  9157.     return(ioctl(fd,TCFLSH,1));
  9158. #else
  9159.     return(0);                /* All others, nothing */
  9160. #endif /* OXOS */
  9161. #endif /* POSIX */
  9162. #endif /* Plan9 */
  9163. }
  9164.  
  9165. /* Interrupt Functions */
  9166.  
  9167. /* Set up terminal interrupts on console terminal */
  9168.  
  9169. #ifndef FIONREAD            /* We don't need esctrp() */
  9170. #ifndef SELECT                /* if we have any of these... */
  9171. #ifndef CK_POLL
  9172. #ifndef RDCHK
  9173.  
  9174. #ifndef OXOS
  9175. #ifdef SVORPOSIX
  9176. SIGTYP
  9177. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  9178.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  9179.     conesc = 1;
  9180.     debug(F101,"esctrp caught SIGQUIT","",conesc);
  9181. }
  9182. #endif /* SVORPOSIX */
  9183. #endif /* OXOS */
  9184.  
  9185. #ifdef V7
  9186. #ifndef MINIX2
  9187. SIGTYP
  9188. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  9189.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  9190.     conesc = 1;
  9191.     debug(F101,"esctrp caught SIGQUIT","",conesc);
  9192. }
  9193. #endif /* MINIX2 */
  9194. #endif /* V7 */
  9195.  
  9196. #ifdef C70
  9197. SIGTYP
  9198. esctrp(foo) int foo; {            /* trap console escapes (^\) */
  9199.     conesc = 1;
  9200.     signal(SIGQUIT,SIG_IGN);            /* ignore until trapped */
  9201. }
  9202. #endif /* C70 */
  9203.  
  9204. #endif /* RDCHK */
  9205. #endif /* CK_POLL */
  9206. #endif /* SELECT */
  9207. #endif /* FIONREAD */
  9208.  
  9209. /*  C O N B G T  --  Background Test  */
  9210.  
  9211. static int jc = 0;            /* 0 = no job control */
  9212.  
  9213. /*
  9214.   Call with flag == 1 to prevent signal test, which can not be expected
  9215.   to work during file transfer, when SIGINT probably *is* set to SIG_IGN.
  9216.  
  9217.   Call with flag == 0 to use the signal test, but only if the process-group
  9218.   test fails, as it does on some UNIX systems, where getpgrp() is buggy,
  9219.   requires an argument when the man page says it doesn't, or vice versa.
  9220.  
  9221.   If flag == 0 and the process-group test fails, then we determine background
  9222.   status simply (but not necessarily reliably) from isatty().
  9223.  
  9224.   conbgt() sets the global backgrd = 1 if we appear to be in the background,
  9225.   and to 0 if we seem to be in the foreground.  conbgt() is highly prone to
  9226.   misbehavior.
  9227. */
  9228. VOID
  9229. conbgt(flag) int flag; {
  9230.     int x = -1,                /* process group or SIGINT test */
  9231.         y = 0;                /* isatty() test */
  9232. /*
  9233.   Check for background operation, even if not running on real tty, so that
  9234.   background flag can be set correctly.  If background status is detected,
  9235.   then Kermit will not issue its interactive prompt or most messages.
  9236.   If your prompt goes away, you can blame (and fix?) this function.
  9237. */
  9238.  
  9239. /* Use process-group test if possible. */
  9240.  
  9241. #ifdef POSIX                /* We can do it in POSIX */
  9242. #define PGROUP_T
  9243. #else
  9244. #ifdef BSD4                /* and in BSD 4.x. */
  9245. #define PGROUP_T
  9246. #else
  9247. #ifdef HPUXJOBCTL            /* and in most HP-UX's */
  9248. #define PGROUP_T
  9249. #else
  9250. #ifdef TIOCGPGRP            /* and anyplace that has this ioctl. */
  9251. #define PGROUP_T
  9252. #endif /* TIOCGPGRP */
  9253. #endif /* HPUXJOBCTL */
  9254. #endif /* BSD4 */
  9255. #endif /* POSIX */
  9256.  
  9257. #ifdef MIPS                /* Except if it doesn't work... */
  9258. #undef PGROUP_T
  9259. #endif /* MIPS */
  9260.  
  9261. #ifdef MINIX
  9262. #undef PGROUP_T
  9263. #endif    /* MINIX */
  9264.  
  9265. #ifdef PGROUP_T
  9266. /*
  9267.   Semi-reliable process-group test.  Check whether this process's group is
  9268.   the same as the controlling terminal's process group.  This works if the
  9269.   getpgrp() call doesn't lie (as it does in the SUNOS System V environment).
  9270. */
  9271.     PID_T mypgrp = (PID_T)0;        /* Kermit's process group */
  9272.     PID_T ctpgrp = (PID_T)0;        /* The terminal's process group */
  9273. #ifndef _POSIX_SOURCE
  9274. /*
  9275.   The getpgrp() prototype is obtained from system header files for POSIX
  9276.   and Sys V R4 compilations.  Other systems, who knows.  Some complain about
  9277.   a duplicate declaration here, others don't, so it's safer to leave it in
  9278.   if we don't know for certain.
  9279. */
  9280. #ifndef SVR4
  9281. #ifndef PS2AIX10
  9282. #ifndef HPUX9
  9283.     extern PID_T getpgrp();
  9284. #endif /* HPUX9 */
  9285. #endif /* PS2AIX10 */
  9286. #endif /* SVR4 */
  9287. #endif /* _POSIX_SOURCE */
  9288.  
  9289. /* Get my process group. */
  9290.  
  9291. #ifdef SVR3 /* Maybe this should be ATTSV? */
  9292. /* This function is not described in SVID R2 */
  9293.     mypgrp = getpgrp();
  9294.     /* debug(F101,"ATTSV conbgt process group","",(int) mypgrp); */
  9295. #else
  9296. #ifdef POSIX
  9297.     mypgrp = getpgrp();
  9298.     /* debug(F101,"POSIX conbgt process group","",(int) mypgrp); */
  9299. #else
  9300. #ifdef OSFPC
  9301.     mypgrp = getpgrp();
  9302.     /* debug(F101,"OSF conbgt process group","",(int) mypgrp); */
  9303. #else
  9304. #ifdef QNX
  9305.     mypgrp = getpgrp();
  9306.     /* debug(F101,"QNX conbgt process group","",(int) mypgrp); */
  9307. #else
  9308. #ifdef OSF32                /* (was OSF40) */
  9309.     mypgrp = getpgrp();
  9310.     /* debug(F101,"Digital UNIX conbgt process group","",(int) mypgrp); */
  9311. #else /* BSD, V7, etc */
  9312. #ifdef MINIX2
  9313.     mypgrp = getpgrp();
  9314. #else
  9315.     mypgrp = getpgrp(0);
  9316. #endif /* MINIX2 */
  9317.     /* debug(F101,"BSD conbgt process group","",(int) mypgrp); */
  9318. #endif /* OSF32 */
  9319. #endif /* QNX */
  9320. #endif /* OSFPC */
  9321. #endif /* POSIX */
  9322. #endif /* SVR3 */
  9323.  
  9324. #ifdef MINIX
  9325.     /* MINIX does not support job control so Kermit is always in foreground */
  9326.     x = 0;
  9327.  
  9328. #else  /* Not MINIX */
  9329.  
  9330. /* Now get controlling tty's process group */
  9331. #ifdef BSD44ORPOSIX
  9332.     ctpgrp = tcgetpgrp(1);        /* The POSIX way */
  9333.     /* debug(F101,"POSIX conbgt terminal process group","",(int) ctpgrp); */
  9334. #else
  9335.     ioctl(1, TIOCGPGRP, &ctpgrp);    /* Or the BSD way */
  9336.    /* debug(F101,"non-POSIX conbgt terminal process group","",(int) ctpgrp); */
  9337. #endif /* BSD44ORPOSIX */
  9338.  
  9339.     if ((mypgrp > (PID_T) 0) && (ctpgrp > (PID_T) 0))
  9340.       x = (mypgrp == ctpgrp) ? 0 : 1;    /* If they differ, then background. */
  9341.     else x = -1;            /* If error, remember. */
  9342.     debug(F101,"conbgt process group test","",x);
  9343. #endif /* PGROUP_T */
  9344. #endif    /* MINIX */
  9345.  
  9346. /* Try to see if job control is available */
  9347.  
  9348. #ifdef NOJC                /* User override */
  9349.     jc = 0;                /* No job control allowed */
  9350.     debug(F111,"NOJC","jc",jc);
  9351. #else
  9352. #ifdef BSD44
  9353.     jc = 1;
  9354. #else
  9355. #ifdef SVR4ORPOSIX            /* POSIX actually tells us */
  9356.     debug(F100,"SVR4ORPOSIX jc test...","",0);
  9357. #ifdef _SC_JOB_CONTROL
  9358. #ifdef __bsdi__
  9359.     jc = 1;
  9360. #else
  9361. #ifdef __386BSD__
  9362.     jc = 1;
  9363. #else
  9364.     jc = sysconf(_SC_JOB_CONTROL);    /* Whatever system says */
  9365.     if (jc < 0) {
  9366.     debug(F101,"sysconf fails, jcshell","",jcshell);
  9367.     jc = (jchdlr == SIG_DFL) ? 1 : 0;
  9368.     } else
  9369.       debug(F111,"sysconf(_SC_JOB_CONTROL)","jc",jc);
  9370. #endif /* __386BSD__ */
  9371. #endif /* __bsdi__ */
  9372. #else
  9373. #ifdef _POSIX_JOB_CONTROL
  9374.     jc = 1;                /* By definition */
  9375.     debug(F111,"_POSIX_JOB_CONTROL is defined","jc",jc);
  9376. #else
  9377.     jc = 0;                /* Assume job control not allowed */
  9378.     debug(F111,"SVR4ORPOSIX _SC/POSIX_JOB_CONTROL not defined","jc",jc);
  9379. #endif /* _POSIX_JOB_CONTROL */
  9380. #endif /* _SC_JOB_CONTROL */
  9381. #else
  9382. #ifdef BSD4
  9383.     jc = 1;                /* Job control allowed */
  9384.     debug(F111,"BSD job control","jc",jc);
  9385. #else
  9386. #ifdef SVR3JC
  9387.     jc = 1;                /* JC allowed */
  9388.     debug(F111,"SVR3 job control","jc",jc);
  9389. #else
  9390. #ifdef OXOS
  9391.     jc = 1;                /* JC allowed */
  9392.     debug(F111,"X/OS job control","jc",jc);
  9393. #else
  9394. #ifdef HPUX9
  9395.     jc = 1;                /* JC allowed */
  9396.     debug(F111,"HP-UX 9.0 job control","jc",jc);
  9397. #else
  9398. #ifdef HPUX10
  9399.     jc = 1;                /* JC allowed */
  9400.     debug(F111,"HP-UX 10.0 job control","jc",jc);
  9401. #else
  9402.     jc = 0;                /* JC not allowed */
  9403.     debug(F111,"job control catch-all","jc",jc);
  9404. #endif /* HPUX10 */
  9405. #endif /* HPUX9 */
  9406. #endif /* OXOS */
  9407. #endif /* SVR3JC */
  9408. #endif /* BSD4 */
  9409. #endif /* SVR4ORPOSIX */
  9410. #endif /* BSD44 */
  9411. #endif /* NOJC */
  9412.     debug(F101,"conbgt jc","",jc);
  9413. #ifndef NOJC
  9414.     debug(F101,"conbgt jcshell","",jcshell);
  9415. /*
  9416.   At this point, if jc == 1 but jcshell == 0, it means that the OS supports
  9417.   job control, but the shell or other process we are running under does not
  9418.   (jcshell is set in sysinit()) and so if we suspend ourselves, nothing good
  9419.   will come of it.  So...
  9420. */
  9421.     if (jc < 0) jc = 0;
  9422.     if (jc > 0 && jcshell == 0) jc = 0;
  9423. #endif /* NOJC */
  9424.  
  9425. /*
  9426.   Another background test.
  9427.   Test if SIGINT (terminal interrupt) is set to SIG_IGN (ignore),
  9428.   which is done by the shell (sh) if the program is started with '&'.
  9429.   Unfortunately, this is NOT done by csh or ksh so watch out!
  9430.   Note, it's safe to set SIGINT to SIG_IGN here, because further down
  9431.   we always set it to something else.
  9432.   Note: as of 16 Jul 1999, we also skip this test if we set SIGINT to
  9433.   SIG_IGN ourselves.
  9434. */
  9435.     if (x < 0 && !flag && !sigint_ign) { /* Didn't get good results above... */
  9436.  
  9437.     SIGTYP (*osigint)();
  9438.  
  9439.     osigint = signal(SIGINT,SIG_IGN);    /* What is SIGINT set to? */
  9440.     sigint_ign = 1;
  9441.     x = (osigint == SIG_IGN) ? 1 : 0;    /* SIG_IGN? */
  9442.     /* debug(F101,"conbgt osigint","",osigint); */
  9443.     /* debug(F101,"conbgt signal test","",x); */
  9444.     }
  9445.  
  9446. /* Also check to see if we're running with redirected stdio. */
  9447. /* This is not really background operation, but we want to act as though */
  9448. /* it were. */
  9449.  
  9450. #ifdef IKSD
  9451.     if (inserver) {            /* Internet Kermit Server */
  9452.     backgrd = 0;            /* is not in the background */
  9453.     return;
  9454.     }
  9455. #endif /* IKSD */
  9456.  
  9457.     y = (isatty(0) && isatty(1)) ? 1 : 0;
  9458.     debug(F101,"conbgt isatty test","",y);
  9459.  
  9460. #ifdef BSD29
  9461. /* The process group and/or signal test doesn't work under these... */
  9462.     backgrd = !y;
  9463. #else
  9464. #ifdef sxaE50
  9465.     backgrd = !y;
  9466. #else
  9467. #ifdef MINIX
  9468.     backgrd = !y;
  9469. #else
  9470. #ifdef MINIX2
  9471.     backgrd = !y;
  9472. #else
  9473.     if (x > -1)
  9474.       backgrd = (x || !y) ? 1 : 0;
  9475.     else backgrd = !y;
  9476. #endif /* BSD29 */
  9477. #endif /* sxaE50 */
  9478. #endif /* MINIX */
  9479. #endif /* MINIX2 */
  9480.     debug(F101,"conbgt backgrd","",backgrd);
  9481. }
  9482.  
  9483. /*  C O N I N T  --  Console Interrupt setter  */
  9484.  
  9485. /*
  9486.   First arg is pointer to function to handle SIGTERM & SIGINT (like Ctrl-C).
  9487.   Second arg is pointer to function to handle SIGTSTP (suspend).
  9488. */
  9489.  
  9490. VOID                    /* Set terminal interrupt traps. */
  9491. #ifdef CK_ANSIC
  9492. #ifdef apollo
  9493. conint(f,s) SIGTYP (*f)(), (*s)();
  9494. #else
  9495. conint(SIGTYP (*f)(int), SIGTYP (*s)(int))
  9496. #endif /* apollo */
  9497. #else
  9498. conint(f,s) SIGTYP (*f)(), (*s)();
  9499. #endif /* CK_ANSIC */
  9500. /* conint */ {
  9501.  
  9502.     debug(F101,"conint conistate","",conistate);
  9503.  
  9504.     conbgt(0);                /* Do background test. */
  9505.  
  9506. /* Set the desired handlers for hangup and software termination. */
  9507.  
  9508. #ifdef SIGTERM
  9509.     signal(SIGTERM,f);                  /* Software termination */
  9510. #endif /* SIGTERM */
  9511.  
  9512. /*
  9513.   Prior to July 1999 we used to call sighup() here but now it's called in
  9514.   sysinit() so SIGHUP can be caught during execution of the init file or
  9515.   a kerbang script.
  9516. */
  9517.  
  9518. /* Now handle keyboard stop, quit, and interrupt signals. */
  9519. /* Check if invoked in background -- if so signals set to be ignored. */
  9520. /* However, if running under a job control shell, don't ignore them. */
  9521. /* We won't be getting any, as we aren't in the terminal's process group. */
  9522.  
  9523.     debug(F101,"conint backgrd","",backgrd);
  9524.     debug(F101,"conint jc","",jc);
  9525.  
  9526.     if (backgrd && !jc) {        /* In background, ignore signals */
  9527.     debug(F101,"conint background ignoring signals, jc","",jc);
  9528. #ifdef SIGTSTP
  9529.         signal(SIGTSTP,SIG_IGN);        /* Keyboard stop */
  9530. #endif /* SIGTSTP */
  9531.         signal(SIGQUIT,SIG_IGN);        /* Keyboard quit */
  9532.         signal(SIGINT,SIG_IGN);         /* Keyboard interrupt */
  9533.     sigint_ign = 1;
  9534.     conistate = CONI_NOI;
  9535.     } else {                /* Else in foreground or suspended */
  9536.     debug(F101,"conint foreground catching signals, jc","",jc);
  9537.         signal(SIGINT,f);               /* Catch terminal interrupt */
  9538.     sigint_ign = (f == SIG_IGN) ? 1 : 0;
  9539.  
  9540. #ifdef SIGTSTP                /* Keyboard stop (suspend) */
  9541.     /* debug(F101,"conint SIGSTSTP","",s); */
  9542.     if (s == NULL) s = SIG_DFL;
  9543. #ifdef NOJC                /* No job control allowed. */
  9544.     signal(SIGTSTP,SIG_IGN);
  9545. #else                    /* Job control allowed */
  9546.     if (jc)                /* if available. */
  9547.       signal(SIGTSTP,s);
  9548.     else
  9549.       signal(SIGTSTP,SIG_IGN);
  9550. #endif /* NOJC */
  9551. #endif /* SIGTSTP */
  9552.  
  9553. #ifndef OXOS
  9554. #ifdef SVORPOSIX
  9555. #ifndef FIONREAD            /* Watch out, we don't know this... */
  9556. #ifndef SELECT
  9557. #ifndef CK_POLL
  9558. #ifndef RDCHK
  9559.         signal(SIGQUIT,esctrp);         /* Quit signal, Sys III/V. */
  9560. #endif /* RDCHK */
  9561. #endif /* CK_POLL */
  9562. #endif /* SELECT */
  9563. #endif /* FIONREAD */
  9564.         if (conesc) conesc = 0;         /* Clear out pending escapes */
  9565. #else
  9566. #ifdef V7
  9567.         signal(SIGQUIT,esctrp);         /* V7 like Sys III/V */
  9568.         if (conesc) conesc = 0;
  9569. #else
  9570. #ifdef aegis
  9571.         signal(SIGQUIT,f);              /* Apollo, catch it like others. */
  9572. #else
  9573.         signal(SIGQUIT,SIG_IGN);        /* Others, ignore like 4D & earlier. */
  9574. #endif /* aegis */
  9575. #endif /* V7 */
  9576. #endif /* SVORPOSIX */
  9577. #endif /* OXOS */
  9578.     conistate = CONI_INT;
  9579.     }
  9580. }
  9581.  
  9582.  
  9583. /*  C O N N O I  --  Reset console terminal interrupts */
  9584.  
  9585. VOID
  9586. connoi() {                              /* Console-no-interrupts */
  9587.  
  9588.     debug(F101,"connoi conistate","",conistate);
  9589. #ifdef SIGTSTP
  9590.     signal(SIGTSTP,SIG_IGN);        /* Suspend */
  9591. #endif /* SIGTSTP */
  9592.     conint(SIG_IGN,SIG_IGN);        /* Interrupt */
  9593.     sigint_ign = 1;            /* Remember we did this ourselves */
  9594. #ifdef SIGQUIT
  9595.     signal(SIGQUIT,SIG_IGN);        /* Quit */
  9596. #endif /* SIGQUIT */
  9597. #ifdef SIGTERM
  9598.     signal(SIGTERM,SIG_IGN);        /* Term */
  9599. #endif /* SIGTERM */
  9600.     conistate = CONI_NOI;
  9601. }
  9602.  
  9603. /*  I N I T R A W Q  --  Set up to read /dev/kmem for character count.  */
  9604.  
  9605. #ifdef  V7
  9606. /*
  9607.  Used in Version 7 to simulate Berkeley's FIONREAD ioctl call.  This
  9608.  eliminates blocking on a read, because we can read /dev/kmem to get the
  9609.  number of characters available for raw input.  If your system can't
  9610.  or you won't let the world read /dev/kmem then you must figure out a
  9611.  different way to do the counting of characters available, or else replace
  9612.  this by a dummy function that always returns 0.
  9613. */
  9614. /*
  9615.  * Call this routine as: initrawq(tty)
  9616.  * where tty is the file descriptor of a terminal.  It will return
  9617.  * (as a char *) the kernel-mode memory address of the rawq character
  9618.  * count, which may then be read.  It has the side-effect of flushing
  9619.  * input on the terminal.
  9620.  */
  9621. /*
  9622.  * John Mackin, Physiology Dept., University of Sydney (Australia)
  9623.  * ...!decvax!mulga!physiol.su.oz!john
  9624.  *
  9625.  * Permission is hereby granted to do anything with this code, as
  9626.  * long as this comment is retained unmodified and no commercial
  9627.  * advantage is gained.
  9628.  */
  9629. #ifndef MINIX
  9630. #ifndef MINIX2
  9631. #ifndef COHERENT
  9632. #include <a.out.h>
  9633. #include <sys/proc.h>
  9634. #endif /* COHERENT */
  9635. #endif /* MINIX2 */
  9636. #endif /* MINIX */
  9637.  
  9638. #ifdef COHERENT
  9639. #include <l.out.h>
  9640. #include <sys/proc.h>
  9641. #endif /* COHERENT */
  9642.  
  9643. char *
  9644. initrawq(tty) int tty; {
  9645. #ifdef MINIX
  9646.     return(0);
  9647. #else
  9648. #ifdef MINIX2
  9649.     return(0);
  9650. #else
  9651. #ifdef UTS24
  9652.     return(0);
  9653. #else
  9654. #ifdef BSD29
  9655.     return(0);
  9656. #else
  9657.     long lseek();
  9658.     static struct nlist nl[] = {
  9659.         {PROCNAME},
  9660.         {NPROCNAME},
  9661.         {""}
  9662.     };
  9663.     static struct proc *pp;
  9664.     char *qaddr, *p, c;
  9665.     int m;
  9666.     PID_T pid, me;
  9667.     NPTYPE xproc;                       /* Its type is defined in makefile. */
  9668.     int catch();
  9669.  
  9670.     me = getpid();
  9671.     if ((m = open("/dev/kmem", 0)) < 0) err("kmem");
  9672.     nlist(BOOTNAME, nl);
  9673.     if (nl[0].n_type == 0) err("proc array");
  9674.  
  9675.     if (nl[1].n_type == 0) err("nproc");
  9676.  
  9677.     lseek(m, (long)(nl[1].n_value), 0);
  9678.     read (m, &xproc, sizeof(xproc));
  9679.     saval = signal(SIGALRM, catch);
  9680.     if ((pid = fork()) == 0) {
  9681.         while(1)
  9682.             read(tty, &c, 1);
  9683.     }
  9684.     alarm(2);
  9685.  
  9686.     if(setjmp(jjbuf) == 0) {
  9687.         while(1)
  9688.       read(tty, &c, 1);
  9689.     }
  9690.     signal(SIGALRM, SIG_DFL);
  9691.  
  9692. #ifdef DIRECT
  9693.     pp = (struct proc *) nl[0].n_value;
  9694. #else
  9695.     if (lseek(m, (long)(nl[0].n_value), 0) < 0L) err("seek");
  9696.     if (read(m, &pp, sizeof(pp)) != sizeof(pp))  err("no read of proc ptr");
  9697. #endif
  9698.     lseek(m, (long)(nl[1].n_value), 0);
  9699.     read(m, &xproc, sizeof(xproc));
  9700.  
  9701.     if (lseek(m, (long)pp, 0) < 0L) err("Can't seek to proc");
  9702.     if ((p = malloc(xproc * sizeof(struct proc))) == NULL) err("malloc");
  9703.     if (read(m,p,xproc * sizeof(struct proc)) != xproc*sizeof(struct proc))
  9704.         err("read proc table");
  9705.     for (pp = (struct proc *)p; xproc > 0; --xproc, ++pp) {
  9706.         if (pp -> p_pid == (short) pid) goto iout;
  9707.     }
  9708.     err("no such proc");
  9709.  
  9710. iout:
  9711.     close(m);
  9712.     qaddr = (char *)(pp -> p_wchan);
  9713.     free (p);
  9714.     kill(pid, SIGKILL);
  9715.     wait((WAIT_T *)0);
  9716.     return (qaddr);
  9717. #endif
  9718. #endif
  9719. #endif
  9720. #endif
  9721. }
  9722.  
  9723. /*  More V7-support functions...  */
  9724.  
  9725. static VOID
  9726. err(s) char *s; {
  9727.     char buf[200];
  9728.  
  9729.     ckmakmsg(buf,200,"fatal error in initrawq: ", s, NULL, NULL);
  9730.     perror(buf);
  9731.     doexit(1,-1);
  9732. }
  9733.  
  9734. static VOID
  9735. catch(foo) int foo; {
  9736.     longjmp(jjbuf, -1);
  9737. }
  9738.  
  9739.  
  9740. /*  G E N B R K  --  Simulate a modem break.  */
  9741.  
  9742. #ifdef MINIX
  9743. #define BSPEED B110
  9744. #else
  9745. #ifdef MINIX2
  9746. #define BSPEED B110
  9747. #else
  9748. #define BSPEED B150
  9749. #endif /* MINIX2 */
  9750. #endif /* MINIX */
  9751.  
  9752. #ifndef MINIX2
  9753. VOID
  9754. genbrk(fn,msec) int fn, msec; {
  9755.     struct sgttyb ttbuf;
  9756.     int ret, sospeed, x, y;
  9757.  
  9758.     ret = ioctl(fn, TIOCGETP, &ttbuf);
  9759.     sospeed = ttbuf.sg_ospeed;
  9760.     ttbuf.sg_ospeed = BSPEED;
  9761.     ret = ioctl(fn, TIOCSETP, &ttbuf);
  9762.     y = (int)strlen(brnuls);
  9763.     x = ( BSPEED * 100 ) / msec;
  9764.     if (x > y) x = y;
  9765.     ret = write(fn, brnuls, (( BSPEED * 100 ) / msec ));
  9766.     ttbuf.sg_ospeed = sospeed;
  9767.     ret = ioctl(fn, TIOCSETP, &ttbuf);
  9768.     ret = write(fn, "@", 1);
  9769.     return;
  9770. }
  9771. #endif /* MINIX2 */
  9772.  
  9773. #ifdef MINIX2
  9774. int
  9775. genbrk(fn,msec) int fn, msec; {
  9776.     struct termios ttbuf;
  9777.     int ret, x, y;
  9778.     speed_t sospeed;
  9779.  
  9780.     ret = tcgetattr(fn, &ttbuf);
  9781.     sospeed = ttbuf.c_ospeed;
  9782.     ttbuf.c_ospeed = BSPEED;
  9783.     ret = tcsetattr(fn,TCSADRAIN, &ttbuf);
  9784.     y = (int)strlen(brnuls);
  9785.     x = ( BSPEED * 100 ) / msec;
  9786.     if (x > y) x = y;
  9787.     ret = write(fn, brnuls, (( BSPEED * 100 ) / msec ));
  9788.     ttbuf.c_ospeed = sospeed;
  9789.     ret = tcsetattr(fn, TCSADRAIN, &ttbuf);
  9790.     ret = write(fn, "@", 1);
  9791.     return ret;
  9792. }
  9793. #endif /* MINIX2 */
  9794. #endif /* V7 */
  9795.  
  9796. /*
  9797.   I N C H K  --  Check if chars waiting to be read on given file descriptor.
  9798.  
  9799.   This routine is a merger of ttchk() and conchk().
  9800.   Call with:
  9801.     channel == 0 to check console.
  9802.     channel == 1 to check communications connection.
  9803.   and:
  9804.     fd = file descriptor.
  9805.   Returns:
  9806.    >= 0: number of characters waiting, 0 or greater,
  9807.      -1: on any kind of error,
  9808.      -2: if there is (definitely) no connection.
  9809.   Note: In UNIX we don't have to call nettchk() because a socket
  9810.   file descriptor works just like in serial i/o, ioctls and all.
  9811.   (But this will change if we add non-file-descriptor channels,
  9812.   such as IBM X.25 for AIX...)
  9813. */
  9814. static int
  9815. in_chk(channel, fd) int channel, fd; {
  9816.     int x, n = 0;            /* Workers, n = return value */
  9817.     extern int clsondisc;        /* Close on disconnect */
  9818. /*
  9819.   The first section checks to make sure we have a connection,
  9820.   but only if we're in local mode.
  9821. */
  9822. #ifdef DEBUG
  9823.     if (deblog) {
  9824.     debug(F111,"in_chk entry",ckitoa(fd),channel);
  9825.     debug(F101,"in_chk ttyfd","",ttyfd);
  9826.     debug(F101,"in_chk ttpty","",ttpty);
  9827.     }
  9828. #endif /* DEBUG */
  9829. /*
  9830.   But don't say connection is gone if we have any buffered-stuff.
  9831. */
  9832. #ifdef TTLEBUF
  9833.     debug(F101,"in_chk ttpush","",ttpush);
  9834.     if (channel == 1) {
  9835.     if (ttpush >= 0)
  9836.       n++;
  9837.     n += le_inbuf();
  9838.     if (n > 0)
  9839.       return(n);
  9840.     }
  9841. #endif /* TTLEBUF */
  9842.  
  9843. #ifdef NETPTY
  9844. #ifdef HAVE_PTYTRAP
  9845.     /* Special handling for HP-UX pty i/o */
  9846.     if (ttpty && pty_trap_pending(ttyfd) > 0) {
  9847.         if (pty_trap_handler(ttyfd) > 0) {
  9848.             ttclos(0);
  9849.             return(-2);
  9850.         }
  9851.     }
  9852. #endif /* HAVE_PTYTRAP */
  9853. #endif /* NETPTY */
  9854.  
  9855.     if (channel) {            /* Checking communications channel */
  9856.     if (ttyfd < 0) {        /* No connection */
  9857.       return(-2);            /* That's what this means */
  9858.     } else if (xlocal &&        /* In local mode */
  9859.            (!netconn        /* Serial connection or */
  9860. #ifdef TN_COMPORT
  9861.             || istncomport()    /* Telnet Com Port */
  9862. #endif /* TN_COMPORT */
  9863.            ) && ttcarr != CAR_OFF /* with CARRIER WATCH ON (or AUTO) */
  9864. #ifdef COMMENT
  9865. #ifdef MYREAD
  9866. /*
  9867.   Seems like this would be a good idea but it prevents C-Kermit from
  9868.   popping back to the prompt automatically when carrier drops.  However,
  9869.   commenting this out prevents us from seeing the NO CARRIER message.
  9870.   Needs more work...
  9871. */
  9872.            && my_count < 1    /* Nothing in our internal buffer */
  9873. #endif /* MYREAD */
  9874. #endif /* COMMENT */
  9875.            ) {
  9876.         int x;
  9877.         x = ttgmdm();        /* So get modem signals */
  9878.         debug(F101,"in_chk close-on-disconnect","",clsondisc);
  9879.         if (x > -1) {        /* Check for carrier */
  9880.         if (!(x & BM_DCD)) {    /* No carrier */
  9881.             debug(F101,"in_chk carrier lost","",x);
  9882.             if (clsondisc)    /* If "close-on-disconnect" */
  9883.               ttclos(0);    /* close device & release lock. */
  9884.             return(-2);        /* This means "disconnected" */
  9885.         }
  9886.         /* In case I/O to device after CD dropped always fails */
  9887.         /* as in Debian Linux 2.1 and Unixware 2.1... */
  9888.         } else {
  9889.             debug(F101,"in_chk ttgmdm I/O error","",errno);
  9890.             debug(F101,"in_chk ttgmdm gotsigs","",gotsigs);
  9891.             if (gotsigs) {        /* If we got signals before... */
  9892.             if (errno == 5 || errno == 6) { /* I/O error etc */
  9893.                 if (clsondisc)    /* like when modem hangs up */
  9894.               ttclos(0);
  9895.             return(-2);
  9896.             }
  9897.         }
  9898.         /* If we never got modem signals successfully on this */
  9899.         /* connection before, we can't conclude that THIS failure */
  9900.         /* means the connection was lost. */
  9901.         return(0);
  9902.         }
  9903.     }
  9904.     }
  9905.  
  9906. /* We seem to have a connection so now see if any bytes are waiting on it */
  9907.  
  9908. #ifdef CK_SSL
  9909.     if (ssl_active_flag || tls_active_flag) {
  9910.         n += SSL_pending(ssl_active_flag?ssl_con:tls_con);
  9911.         debug(F101,"in_chk SSL_pending","",n);
  9912.         if (n < 0) {
  9913.             ttclos(0);
  9914.             return(-1);
  9915.         } else if (n > 0) {
  9916.             return(n);
  9917.         }
  9918.     }
  9919. #endif /* CK_SSL */
  9920. #ifdef RLOGCODE
  9921. #ifdef CK_KERBEROS
  9922.     /* It is not safe to read any data when using encrypted Klogin */
  9923.     if (ttnproto == NP_EK4LOGIN || ttnproto == NP_EK5LOGIN) {
  9924. #ifdef KRB4
  9925.         if (ttnproto == NP_EK4LOGIN) {
  9926.             n += krb4_des_avail(ttyfd);
  9927.             debug(F101,"in_chk krb4_des_avail","",n);
  9928.         }
  9929. #endif /* KRB4 */
  9930. #ifdef KRB5
  9931.         if (ttnproto == NP_EK5LOGIN) {
  9932.             n += krb5_des_avail(ttyfd);
  9933.             debug(F101,"in_chk krb5_des_avail","",n);
  9934.         }
  9935. #ifdef KRB5_U2U
  9936.         if (ttnproto == NP_K5U2U) {
  9937.             n += krb5_u2u_avail(ttyfd);
  9938.             debug(F101,"in_chk krb5_des_avail","",n);
  9939.         }
  9940. #endif /* KRB5_U2U */
  9941. #endif /* KRB5 */
  9942.         if (n < 0)            /* Is this right? */
  9943.       return(-1);
  9944.         else
  9945.       return(n);
  9946.     }
  9947. #endif /* CK_KERBEROS */
  9948. #endif /* RLOGCODE */
  9949.  
  9950.     errno = 0;                /* Reset this so we log good info */
  9951. #ifdef FIONREAD
  9952.     x = ioctl(fd, FIONREAD, &n);    /* BSD and lots of others */
  9953. #ifdef DEBUG                /* (the more the better) */
  9954.     if (deblog) {
  9955.     debug(F101,"in_chk FIONREAD return code","",x);
  9956.     debug(F101,"in_chk FIONREAD count","",n);
  9957.     debug(F101,"in_chk FIONREAD errno","",errno);
  9958.     }
  9959. #endif /* DEBUG */
  9960. #else /* FIONREAD not defined */
  9961. /*
  9962.   Here, if (netconn && ttnet == NET_TCPB), we might try calling recvmsg()
  9963.   with flags MSG_PEEK|MSG_DONTWAIT on the socket (ttyfd), except this is not
  9964.   portable (MSG_DONTWAIT isn't defined in any of the <sys/socket.h> files
  9965.   that I looked at, but it is needed to prevent the call from blocking), and
  9966.   the msghdr struct differs from place to place, so we would need another
  9967.   avalanche of ifdefs.  Still, when FIONREAD is not available, this is the
  9968.   only other known method of asking the OS for the *number* of characters
  9969.   available for reading.
  9970. */
  9971. #ifdef V7                /* UNIX V7: look in kernel memory */
  9972. #ifdef MINIX
  9973.     n = 0;                /* But not in MINIX */
  9974. #else
  9975. #ifdef MINIX2
  9976.     n = 0;
  9977. #else
  9978.     lseek(kmem[TTY], (long) qaddr[TTY], 0); /* 7th Edition Unix */
  9979.     x = read(kmem[TTY], &n, sizeof(int));
  9980.     if (x != sizeof(int))
  9981.       n = 0;
  9982. #endif /* MINIX2 */
  9983. #endif /* MINIX */
  9984. #else /* Not V7 */
  9985. #ifdef PROVX1
  9986.     x = ioctl(fd, TIOCQCNT, &ttbuf);    /* DEC Pro/3xx Venix V.1 */
  9987.     n = ttbuf.sg_ispeed & 0377;        /* Circa 1984 */
  9988.     if (x < 0) n = 0;
  9989. #else
  9990. #ifdef MYREAD
  9991. /*
  9992.   Here we skip all the undependable and expensive calls below if we
  9993.   already have something in our internal buffer.  This tends to work quite
  9994.   nicely, so the only really bad case remaining is the one in which neither
  9995.   FIONREAD or MYREAD are defined, which is increasingly rare these days.
  9996. */
  9997.     if (channel != 0 && my_count > 0) {
  9998.     debug(F101,"in_chk buf my_count","",my_count);
  9999.     n = my_count;            /* n was 0 before we got here */
  10000.     return(n);
  10001.     }
  10002. #endif /* MYREAD */
  10003. /*
  10004.   rdchk(), select(), and poll() tell us *if* data is available to be read, but
  10005.   not how much, so these should be used only as a final resort.  Especially
  10006.   since these calls tend to add a lot overhead.
  10007. */
  10008. #ifdef RDCHK                /* This mostly SCO-specific */
  10009.     n = rdchk(fd);
  10010.     debug(F101,"in_chk rdchk","",n);
  10011. #else /* No RDCHK */
  10012. #ifdef SELECT
  10013. #ifdef Plan9
  10014.     /* Only allows select on the console ... don't ask */
  10015.     if (channel == 0)
  10016. #endif /* Plan9 */
  10017.       {
  10018.     fd_set rfds;            /* Read file descriptors */
  10019. #ifdef BELLV10
  10020.     FD_ZERO(rfds);            /* Initialize them */
  10021.     FD_SET(fd,rfds);        /* We want to look at this fd */
  10022. #else
  10023.     FD_ZERO(&rfds);            /* Initialize them */
  10024.     FD_SET(fd,&rfds);        /* We want to look at this fd */
  10025.     tv.tv_sec = tv.tv_usec = 0L;    /* A 0-valued timeval structure */
  10026. #endif /* BELLV10 */
  10027. #ifdef Plan9
  10028.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10029.     debug(F101,"in_chk Plan 9 select","",n);
  10030. #else
  10031. #ifdef BELLV10
  10032.     n = select( 128, rfds, (fd_set *)0, (fd_set *)0, 0 );
  10033.     debug(F101,"in_chk BELLV10 select","",n);
  10034. #else
  10035. #ifdef BSD44
  10036.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10037.     debug(F101,"in_chk BSD44 select","",n);
  10038. #else
  10039. #ifdef BSD43
  10040.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10041.     debug(F101,"in_chk BSD43 select","",n);
  10042. #else
  10043. #ifdef SOLARIS
  10044.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10045.     debug(F101,"in_chk SOLARIS select","",n);
  10046. #else
  10047. #ifdef QNX6
  10048.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10049.     debug(F101,"in_chk QNX6 select","",n);
  10050. #else
  10051. #ifdef QNX
  10052.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10053.     debug(F101,"in_chk QNX select","",n);
  10054. #else
  10055. #ifdef COHERENT
  10056.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10057.     debug(F101,"in_chk COHERENT select","",n);
  10058. #else
  10059. #ifdef SVR4
  10060.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10061.     debug(F101,"in_chk SVR4 select","",n);
  10062. #else
  10063. #ifdef __linux__
  10064.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10065.     debug(F101,"in_chk LINUX select","",n);
  10066. #ifdef OSF
  10067.     n = select( FD_SETSIZE, &rfds, (fd_set *)0, (fd_set *)0, &tv );
  10068.     debug(F101,"in_chk OSF select","",n);
  10069. #else
  10070.     n = select( FD_SETSIZE, &rfds, (int *)0, (int *)0, &tv );
  10071.     debug(F101,"in_chk catchall select","",n);
  10072. #endif /* OSF */
  10073. #endif /* __linux__ */
  10074. #endif /* SVR4 */
  10075. #endif /* COHERENT */
  10076. #endif /* QNX */
  10077. #endif /* QNX6 */
  10078. #endif /* SOLARIS */
  10079. #endif /* BSD43 */
  10080. #endif /* BSD44 */
  10081. #endif /* BELLV10 */
  10082. #endif /* Plan9 */
  10083.     }
  10084. #else  /* Not SELECT */
  10085. #ifdef CK_POLL
  10086.     {
  10087.       struct pollfd pfd;
  10088.  
  10089.       pfd.fd = fd;
  10090.       pfd.events = POLLIN;
  10091.       pfd.revents = 0;
  10092.       n = poll(&pfd, 1, 0);
  10093.       debug(F101,"in_chk poll","",n);
  10094.       if ((n > 0) && (pfd.revents & POLLIN))
  10095.     n = 1;
  10096.     }
  10097. #endif /* CK_POLL */
  10098. #endif /* SELECT */
  10099. #endif /* RDCHK */
  10100. #endif /* PROVX1 */
  10101. #endif /* V7 */
  10102. #endif /* FIONREAD */
  10103.  
  10104. /* From here down, treat console and communication device differently... */
  10105.  
  10106.     if (channel == 0) {            /* Console */
  10107.  
  10108. #ifdef SVORPOSIX
  10109. #ifndef FIONREAD
  10110. #ifndef SELECT
  10111. #ifndef CK_POLL
  10112. #ifndef RDCHK
  10113. /*
  10114.   This is the hideous hack used in System V and POSIX systems that don't
  10115.   support FIONREAD, rdchk(), select(), poll(), etc, in which the user's
  10116.   CONNECT-mode escape character is attached to SIGQUIT.  Used, obviously,
  10117.   only on the console.
  10118. */
  10119.     if (conesc) {            /* Escape character typed == SIGQUIT */
  10120.         debug(F100,"in_chk conesc","",conesc);
  10121.         conesc = 0;
  10122.         signal(SIGQUIT,esctrp);    /* Restore signal */
  10123.         n += 1;
  10124.     }
  10125. #endif /* RDCHK */
  10126. #endif /* CK_POLL */
  10127. #endif /* SELECT */
  10128. #endif /* FIONREAD */
  10129. #endif /* SVORPOSIX */
  10130.  
  10131.     return(n);            /* Done with console */
  10132.     }
  10133.  
  10134.     if (channel != 0) {            /* Communications connection */
  10135.  
  10136. #ifdef MYREAD
  10137. #ifndef FIONREAD
  10138. /*
  10139.   select() or rdchk(), etc, has told us that something is waiting, but we
  10140.   don't know how much.  So we do a read to get it and then we know.  Note:
  10141.   This read is NOT nonblocking if nothing is there (because of VMIN=1), but
  10142.   it should be safe in this case since the OS tells us at least one byte is
  10143.   waiting to be read, and MYREAD reads return as much as is there without
  10144.   waiting for any more.  Controlled tests on Solaris and Unixware (with
  10145.   FIONREAD deliberately undefined) show this to be true.
  10146. */
  10147.     debug(F101,"in_chk read my_count","",my_count);
  10148.     debug(F101,"in_chk read n","",n);
  10149.     if (n > 0 && my_count == 0) {
  10150.         /* This also catches disconnects etc */
  10151.         /* Do what mygetbuf does except don't grab a character */
  10152.         my_count = myfillbuf();
  10153.         my_item = -1;        /* ^^^ */
  10154.         debug(F101,"in_chk myfillbuf my_count","",my_count);
  10155.         if (my_count < 0)
  10156.           return(-1);
  10157.         else
  10158.           n = 0;            /* NB: n is replaced by my_count */
  10159.     }
  10160. #endif /* FIONREAD */
  10161. /*
  10162.   Here we add whatever we think is unread to what is still in our
  10163.   our internal buffer.  Thus the importance of setting n to 0 just above.
  10164. */
  10165.     debug(F101,"in_chk my_count","",my_count);
  10166.     debug(F101,"in_chk n","",n);
  10167.     if (my_count > 0)
  10168.       n += my_count;
  10169. #endif /* MYREAD */
  10170.     }
  10171.     debug(F101,"in_chk result","",n);
  10172.  
  10173.     /* Errors here don't prove the connection has dropped so just say 0 */
  10174.  
  10175.     return(n < 0 ? 0 : n);
  10176. }
  10177.  
  10178.  
  10179. /*  T T C H K  --  Tell how many characters are waiting in tty input buffer  */
  10180.  
  10181. int
  10182. ttchk() {
  10183.     int fd;
  10184. #ifdef NETCMD
  10185.     if (ttpipe)
  10186.       fd = fdin;
  10187.     else
  10188. #endif /* NETCMD */
  10189.       fd = ttyfd;
  10190.     return(in_chk(1,fd));
  10191. }
  10192.  
  10193. /*  T T X I N  --  Get n characters from tty input buffer  */
  10194.  
  10195. /*  Returns number of characters actually gotten, or -1 on failure  */
  10196.  
  10197. /*  Intended for use only when it is known that n characters are actually */
  10198. /*  Available in the input buffer.  */
  10199.  
  10200. int
  10201. ttxin(n,buf) int n; CHAR *buf; {
  10202.     register int x = 0, c = -2;
  10203. #ifdef TTLEBUF
  10204.     register int i = 0;
  10205. #endif /* TTLEBUF */
  10206.     int fd;
  10207.  
  10208.     if (n < 1)                /* Nothing to do */
  10209.       return(0);
  10210.  
  10211. #ifdef TTLEBUF
  10212.     if (ttpush >= 0) {
  10213.         buf[0] = ttpush;        /* Put pushed char in buffer*/
  10214.         ttpush = -1;            /* Clear the push buffer */
  10215.         if (ttchk() > 0)
  10216.       return(ttxin(n-1, &buf[1]) + 1);
  10217.         else
  10218.       return(1);
  10219.     }
  10220.     if (le_data) {
  10221.         while (le_inbuf() > 0) {
  10222.         if (le_getchar(&buf[i])) {
  10223.                 i++;
  10224.                 n--;
  10225.             }
  10226.         }
  10227.         if (ttchk() > 0)
  10228.       return(ttxin(n,&buf[i])+i);
  10229.         else
  10230.       return(i);
  10231.     }
  10232. #endif /* TTLEBUF */
  10233.  
  10234. #ifdef NETCMD
  10235.     if (ttpipe)
  10236.       fd = fdin;
  10237.     else
  10238. #endif /* NETCMD */
  10239.       fd = ttyfd;
  10240.  
  10241. #ifdef SUNX25
  10242.     if (netconn && (ttnet == NET_SX25))    /* X.25 connection */
  10243.       return(x25xin(n,buf));
  10244. #endif /* SUNX25 */
  10245.  
  10246. #ifdef IBMX25
  10247.     /* riehm: possibly not needed. Test worked with normal reads and writes */
  10248.     if (netconn && (ttnet == NET_IX25))    { /* X.25 connection */
  10249.     x = x25xin(n,buf);
  10250.     if (x > 0) buf[x] = '\0';
  10251.     return(x);
  10252.     }
  10253. #endif /* IBMX25 */
  10254.  
  10255. #ifdef MYREAD
  10256.     debug(F101,"ttxin MYREAD","",n);
  10257.     while (x < n) {
  10258.     c = myread();
  10259.     if (c < 0) {
  10260.         debug(F101,"ttxin myread returns","",c);
  10261.         if (c == -3) x = -1;
  10262.         break;
  10263.         }
  10264.     buf[x++] = c & ttpmsk;
  10265. #ifdef RLOGCODE
  10266. #ifdef CK_KERBEROS
  10267.         /* It is impossible to know how many characters are waiting */
  10268.         /* to be read when you are using Encrypted Rlogin or SSL    */
  10269.         /* as the transport since the number of real data bytes     */
  10270.         /* can be greater or less than the number of bytes on the   */
  10271.         /* wire which is what ttchk() returns.                      */
  10272.         if (netconn && (ttnproto == NP_EK4LOGIN || ttnproto == NP_EK5LOGIN))
  10273.       if (ttchk() <= 0)
  10274.         break;
  10275. #endif /* CK_KERBEROS */
  10276. #endif /* RLOGCODE */
  10277. #ifdef CK_SSL
  10278.         if (ssl_active_flag || tls_active_flag)
  10279.       if (ttchk() <= 0)
  10280.         break;
  10281. #endif /* CK_SSL */
  10282.     }
  10283. #else
  10284.     debug(F101,"ttxin READ","",n);
  10285.     x = read(fd,buf,n);
  10286.     for (c = 0; c < n; c++)        /* Strip any parity */
  10287.       buf[c] &= ttpmsk;
  10288. #endif /* MYREAD */
  10289.  
  10290.     debug(F101,"ttxin x","",x);        /* Done */
  10291.     if (x > 0) buf[x] = '\0';
  10292.     if (x < 0) x = -1;
  10293.     return(x);
  10294. }
  10295.  
  10296. /*  T T O L  --  Write string s, length n, to communication device.  */
  10297. /*
  10298.   Returns:
  10299.    >= 0 on success, number of characters actually written.
  10300.    -1 on failure.
  10301. */
  10302. #ifdef CK_ENCRYPTION
  10303. CHAR * xpacket = NULL;
  10304. int nxpacket = 0;
  10305. #endif /* CK_ENCRYPTION */
  10306.  
  10307. #define TTOLMAXT 5
  10308. int
  10309. ttol(s,n) int n; CHAR *s; {
  10310.     int x, len, tries, fd;
  10311. #ifdef CKXXCHAR
  10312.     extern int dblflag;            /* For SET SEND DOUBLE-CHARACTER */
  10313.     extern short dblt[];
  10314.     CHAR *p = NULL, *p2, *s2, c;
  10315.     int n2 = 0;
  10316. #endif /* CKXXCHAR */
  10317.  
  10318.     if (ttyfd < 0)            /* Not open? */
  10319.       return(-3);
  10320. #ifdef DEBUG
  10321.     if (deblog) {
  10322.     /* debug(F101,"ttol ttyfd","",ttyfd); */
  10323.     ckhexdump("ttol s",s,n);
  10324.     }
  10325. #endif /* DEBUG */
  10326.  
  10327. #ifdef NETCMD
  10328.     if (ttpipe)
  10329.       fd = fdout;
  10330.     else
  10331. #endif /* NETCMD */
  10332.       fd = ttyfd;
  10333.  
  10334. #ifdef CKXXCHAR
  10335. /*  Double any characters that must be doubled.  */
  10336.     debug(F101,"ttol dblflag","",dblflag);
  10337.     if (dblflag) {
  10338.     p = (CHAR *) malloc(n + n + 1);
  10339.     if (p) {
  10340.         s2 = s;
  10341.         p2 = p;
  10342.         n2 = 0;
  10343.         while (*s2) {
  10344.         c = *s2++;
  10345.         *p2++ = c;
  10346.         n2++;
  10347.         if (dblt[(unsigned) c] & 2) {
  10348.             *p2++ = c;
  10349.             n2++;
  10350.         }
  10351.         }
  10352.         s = p;
  10353.         n = n2;
  10354.         s[n] = '\0';
  10355.     }
  10356. #ifdef DEBUG
  10357.         ckhexdump("ttol doubled s",s,n);
  10358. #endif /* DEBUG */
  10359.     }
  10360. #endif /* CKXXCHAR */
  10361.  
  10362.     tries = TTOLMAXT;            /* Allow up to this many tries */
  10363.     len = n;                /* Remember original length */
  10364.  
  10365. #ifdef CK_ENCRYPTION
  10366. /*
  10367.   This is to avoid encrypting a packet that is already encrypted, e.g.
  10368.   when we resend a packet directly out of the packet buffer, and also to
  10369.   avoid encrypting a constant (literal) string, which can cause a memory
  10370.   fault.
  10371. */
  10372.     if (TELOPT_ME(TELOPT_ENCRYPTION)) {
  10373.     int x;
  10374.     if (nxpacket < n) {
  10375.         if (xpacket) {
  10376.         free(xpacket);
  10377.         xpacket = NULL;
  10378.         nxpacket = 0;
  10379.         }
  10380.         x = n > 10240 ? n : 10240;
  10381.         xpacket = (CHAR *)malloc(x);
  10382.         if (!xpacket) {
  10383.         fprintf(stderr,"ttol malloc failure\n");
  10384.         return(-1);
  10385.         } else
  10386.           nxpacket = x;
  10387.     }
  10388.     memcpy((char *)xpacket,(char *)s,n);
  10389.     s = xpacket;
  10390.     ck_tn_encrypt((char *)s,n);
  10391.     }
  10392. #endif /* CK_ENCRYPTION */
  10393.  
  10394.     while (n > 0 &&
  10395.        (tries-- > 0
  10396. #ifdef CK_ENCRYPTION
  10397.         /* keep trying if we are encrypting */
  10398.         || TELOPT_ME(TELOPT_ENCRYPTION)
  10399. #endif /* CK_ENCRYPTION */
  10400.             )) {            /* Be persistent */
  10401.     debug(F101,"ttol try","",TTOLMAXT - tries);
  10402. #ifdef BEOSORBEBOX
  10403.         if (netconn && !ttpipe && !ttpty)
  10404.       x = nettol((char *)s,n);    /* Write string to device */
  10405.         else
  10406. #endif /* BEOSORBEBOX */
  10407. #ifdef IBMX25
  10408.       if (ttnet == NET_IX25)
  10409.         /*
  10410.          * this is a more controlled way of writing to X25
  10411.          * STREAMS, however write should also work!
  10412.          */
  10413.         x = x25write(ttyfd, s, n);
  10414.       else
  10415. #endif /* IBMX25 */
  10416. #ifdef CK_SSL
  10417.         if (ssl_active_flag || tls_active_flag) {
  10418.         int error;
  10419.         /* Write using SSL */
  10420.                 ssl_retry:
  10421.         if (ssl_active_flag)
  10422.                   x = SSL_write(ssl_con, s, n);
  10423.         else
  10424.                   x = SSL_write(tls_con, s, n);
  10425.         switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,x)) {
  10426.                 case SSL_ERROR_NONE:
  10427.                     if (x == n)
  10428.               return(len);
  10429.                     s += x;
  10430.                     n -= x;
  10431.                     goto ssl_retry;
  10432.           case SSL_ERROR_WANT_WRITE:
  10433.           case SSL_ERROR_WANT_READ:
  10434.             x = 0;
  10435.             break;
  10436.           case SSL_ERROR_SYSCALL:
  10437.                     if (x != 0)
  10438.               return(-1);
  10439.           case SSL_ERROR_WANT_X509_LOOKUP:
  10440.           case SSL_ERROR_SSL:
  10441.           case SSL_ERROR_ZERO_RETURN:
  10442.           default:
  10443.             ttclos(0);
  10444.             return(-3);
  10445.         }
  10446.         } else
  10447. #endif /* CK_SSL */
  10448. #ifdef CK_KERBEROS
  10449. #ifdef KRB4
  10450. #ifdef RLOGCODE
  10451.         if (ttnproto == NP_EK4LOGIN) {
  10452.         return(krb4_des_write(ttyfd,s,n));
  10453.         } else
  10454. #endif /* RLOGCODE */
  10455. #endif /* KRB4 */
  10456. #ifdef KRB5
  10457. #ifdef RLOGCODE
  10458.             if (ttnproto == NP_EK5LOGIN) {
  10459.                 return(krb5_des_write(ttyfd,(char *)s,n,0));
  10460.             } else
  10461. #endif /* RLOGCODE */
  10462. #ifdef KRB5_U2U
  10463.             if (ttnproto == NP_K5U2U) {
  10464.                 return(krb5_u2u_write(ttyfd,(char *)s,n));
  10465.             } else
  10466. #endif /* KRB5_U2U */
  10467. #endif /* KRB5 */
  10468. #endif /* CK_KERBEROS */
  10469.           x = write(fd,s,n);    /* Write string to device */
  10470.  
  10471.     if (x == n) {            /* Worked? */
  10472.         debug(F101,"ttol ok","",x);    /* OK */
  10473. #ifdef CKXXCHAR
  10474.         if (p) free(p);
  10475. #endif /* CKXXCHAR */
  10476.         return(len);        /* Done */
  10477.     } else if (x < 0) {        /* No, got error? */
  10478.         debug(F101,"ttol write error","",errno);
  10479. #ifdef EWOULDBLOCK
  10480.         if (errno == EWOULDBLOCK) {
  10481.         msleep(10);
  10482.         continue;
  10483.         } else
  10484. #endif /* EWOULDBLOCK */
  10485. #ifdef TCPSOCKET
  10486.         if (netconn && ttnet == NET_TCPB) {
  10487.         debug(F101,"ttol TCP error","",errno);
  10488.         ttclos(0);        /* Close the connection. */
  10489.         x = -3;
  10490.         }
  10491. #endif /* TCPSOCKET */
  10492. #ifdef CKXXCHAR
  10493.         if (p) free(p);
  10494. #endif /* CKXXCHAR */
  10495.         return(x);
  10496.     } else {            /* No error, so partial success */
  10497.         debug(F101,"ttol partial","",x); /* This never happens */
  10498.         s += x;            /* Point to part not written yet */
  10499.         n -= x;            /* Adjust length */
  10500.         if (x > 0) msleep(10);    /* Wait 10 msec */
  10501.     }                /* Go back and try again */
  10502.     }
  10503. #ifdef CKXXCHAR
  10504.     if (p) free(p);
  10505. #endif /* CKXXCHAR */
  10506.     return(n < 1 ? len : -1);        /* Return the results */
  10507. }
  10508.  
  10509. /*  T T O C  --  Output a character to the communication line  */
  10510.  
  10511. /*
  10512.  This function should only be used for interactive, character-mode operations,
  10513.  like terminal connection, script execution, dialer i/o, where the overhead
  10514.  of the signals and alarms does not create a bottleneck.
  10515. */
  10516. int
  10517. #ifdef CK_ANSIC
  10518. ttoc(char c)
  10519. #else
  10520. ttoc(c) char c;
  10521. #endif /* CK_ANSIC */
  10522. /* ttoc */ {
  10523. #define TTOC_TMO 15            /* Timeout in case we get stuck */
  10524.     int xx, fd;
  10525.  
  10526.     if (ttyfd < 0)            /* Check for not open. */
  10527.       return(-1);
  10528.  
  10529. #ifdef NETCMD
  10530.     if (ttpipe)
  10531.       fd = fdout;
  10532.     else
  10533. #endif /* NETCMD */
  10534.       fd = ttyfd;
  10535.  
  10536.     c &= 0xff;
  10537.     /* debug(F101,"ttoc","",(CHAR) c); */
  10538.     saval = signal(SIGALRM,timerh);    /* Enable timer interrupt */
  10539.     xx = alarm(TTOC_TMO);        /* for this many seconds. */
  10540.     if (xx < 0) xx = 0;            /* Save old alarm value. */
  10541.     /* debug(F101,"ttoc alarm","",xx); */
  10542.     if (
  10543. #ifdef CK_POSIX_SIG
  10544.     sigsetjmp(sjbuf,1)
  10545. #else
  10546.     setjmp(sjbuf)
  10547. #endif /* CK_POSIX_SIG */
  10548.     ) {        /* Timer went off? */
  10549.     ttimoff();            /* Yes, cancel this alarm. */
  10550.     if (xx - TTOC_TMO > 0) alarm(xx - TTOC_TMO); /* Restore previous one */
  10551.         /* debug(F100,"ttoc timeout","",0); */
  10552. #ifdef NETCONN
  10553.     if (!netconn) {
  10554. #endif /* NETCONN */
  10555.         debug(F101,"ttoc timeout","",c);
  10556.         if (ttflow == FLO_XONX) {
  10557.         debug(F101,"ttoc flow","",ttflow); /* Maybe we're xoff'd */
  10558. #ifndef Plan9
  10559. #ifdef POSIX
  10560.         /* POSIX way to unstick. */
  10561.         debug(F100,"ttoc tcflow","",tcflow(ttyfd,TCOON));
  10562. #else
  10563. #ifdef BSD4                /* Berkeley way to do it. */
  10564. #ifdef TIOCSTART
  10565. /* .... Used to be "ioctl(ttyfd, TIOCSTART, 0);".  Who knows? */
  10566.         {
  10567.           int x = 0;
  10568.           debug(F101,"ttoc TIOCSTART","",ioctl(ttyfd, TIOCSTART, &x));
  10569.         }
  10570. #endif /* TIOCSTART */
  10571. #endif /* BSD4 */
  10572.                     /* Is there a Sys V way to do this? */
  10573. #endif /* POSIX */
  10574. #endif /* Plan9 */
  10575.         }
  10576. #ifdef NETCONN
  10577.         }
  10578. #endif /* NETCONN */
  10579.     return(-1);            /* Return failure code. */
  10580.     } else {
  10581.         int rc;
  10582. #ifdef BEOSORBEBOX
  10583. #ifdef NETCONN
  10584.         if (netconn && !ttpipe && !ttpty)
  10585.       rc = nettoc(c);
  10586.         else
  10587. #endif /*  BEOSORBEBOX */
  10588. #endif /* NETCONN */
  10589. #ifdef CK_ENCRYPTION
  10590.       if (TELOPT_ME(TELOPT_ENCRYPTION))
  10591.         ck_tn_encrypt(&c,1);
  10592. #endif /* CK_ENCRYPTION */
  10593. #ifdef IBMX25
  10594.     /* riehm: maybe this isn't necessary after all. Test program
  10595.      * worked fine with data being sent and retrieved with normal
  10596.      * read's and writes!
  10597.      */
  10598.     if (ttnet == NET_IX25)
  10599.       rc = x25write(ttyfd,&c,1); /* as above for X25 streams */
  10600.     else
  10601. #endif /* IBMX25 */
  10602. #ifdef CK_SSL
  10603.       if (ssl_active_flag || tls_active_flag) {
  10604.           int error;
  10605.           /* Write using SSL */
  10606.           if (ssl_active_flag)
  10607.                 rc = SSL_write(ssl_con, &c, 1);
  10608.           else
  10609.                 rc = SSL_write(tls_con, &c, 1);
  10610.           switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,rc)){
  10611.         case SSL_ERROR_NONE:
  10612.           break;
  10613.         case SSL_ERROR_WANT_WRITE:
  10614.         case SSL_ERROR_WANT_READ:
  10615.           rc = 0;
  10616.           break;
  10617.         case SSL_ERROR_SYSCALL:
  10618.           if (rc != 0)
  10619.             return(-1);
  10620.         case SSL_ERROR_WANT_X509_LOOKUP:
  10621.         case SSL_ERROR_SSL:
  10622.         case SSL_ERROR_ZERO_RETURN:
  10623.         default:
  10624.           ttclos(0);
  10625.           return(-1);
  10626.           }
  10627.       } else
  10628. #endif /* CK_SSL */
  10629. #ifdef CK_KERBEROS
  10630. #ifdef KRB4
  10631. #ifdef RLOGCODE
  10632.       if (ttnproto == NP_EK4LOGIN) {
  10633.           rc = (krb4_des_write(ttyfd,(char *)&c,1) == 1);
  10634.       } else
  10635. #endif /* RLOGCODE */
  10636. #endif /* KRB4 */
  10637. #ifdef KRB5
  10638. #ifdef RLOGCODE
  10639.           if (ttnproto == NP_EK5LOGIN) {
  10640.               rc = (krb5_des_write(ttyfd,&c,1,0) == 1);
  10641.           } else
  10642. #endif /* RLOGCODE */
  10643. #ifdef KRB5_U2U
  10644.           if (ttnproto == NP_K5U2U) {
  10645.               rc = (krb5_u2u_write(ttyfd,&c,1) == 1);
  10646.           } else
  10647. #endif /* KRB5_U2U */
  10648. #endif /* KRB5 */
  10649. #endif /* CK_KERBEROS */
  10650.         rc = write(fd,&c,1);    /* Try to write the character. */
  10651.     if (rc < 1) {            /* Failed */
  10652.         ttimoff();            /* Turn off the alarm. */
  10653.         alarm(xx);            /* Restore previous alarm. */
  10654.         debug(F101,"ttoc errno","",errno); /* Log the error, */
  10655.         return(-1);            /* and return the error code. */
  10656.     }
  10657.     }
  10658.     ttimoff();                /* Success, turn off the alarm. */
  10659.     alarm(xx);                /* Restore previous alarm. */
  10660.     return(0);                /* Return good code. */
  10661. }
  10662.  
  10663. /*  T T I N L  --  Read a record (up to break character) from comm line.  */
  10664. /*
  10665.   Reads up to "max" characters from the connection, terminating on:
  10666.     (a) the packet length field if the "turn" argument is zero, or
  10667.     (b) on the packet-end character (eol) if the "turn" argument is nonzero
  10668.     (c) a certain number of Ctrl-C's in a row
  10669.  
  10670.   Returns:
  10671.     >= 0, the number of characters read upon success;
  10672.     -1 if "max" exceeded, timeout, or other correctable error;
  10673.     -2 on user interruption (c);
  10674.     -3 on fatal error like connection lost.
  10675.  
  10676.   The name of this routine dates from the early days when Kermit packets
  10677.   were, indeed, always lines of text.  That was before control-character
  10678.   unprefixing and length-driven packet framing were introduced, which this
  10679.   version handle.  NB: this routine is ONLY for reading incoming Kermit
  10680.   packets, nothing else.  To read other kinds of incoming material, use
  10681.   ttinc() or ttxin().
  10682.  
  10683.   The bytes that were input are copied into "dest" with their parity bits
  10684.   stripped if parity was selected.  Returns the number of bytes read.
  10685.   Bytes after the eol are available upon the next call to this function.
  10686.  
  10687.   The idea is to minimize the number of system calls per packet, and also to
  10688.   minimize timeouts.  This function is the inner loop of the protocol and must
  10689.   be as efficient as possible.  The current strategy is to use myread(), a
  10690.   macro to manage buffered (and generally nonblocking) reads.
  10691.  
  10692.   WARNING: This function calls parchk(), which is defined in another module.
  10693.   Normally, ckutio.c does not depend on code from any other module, but there
  10694.   is an exception in this case because all the other ck?tio.c modules also
  10695.   need to call parchk(), so it's better to have it defined in a common place.
  10696. */
  10697. #ifdef CTRLC
  10698. #undef CTRLC
  10699. #endif /* CTRLC */
  10700. #define CTRLC '\03'
  10701. /*
  10702.   We have four different declarations here because:
  10703.   (a) to allow Kermit to be built without the automatic parity sensing feature
  10704.   (b) one of each type for ANSI C, one for non-ANSI.
  10705. */
  10706. #ifndef NOXFER
  10707.  
  10708. static int pushedback = 0;
  10709.  
  10710. int
  10711. #ifdef PARSENSE
  10712. #ifdef CK_ANSIC
  10713. ttinl(CHAR *dest, int max,int timo, CHAR eol, CHAR start, int turn)
  10714. #else
  10715. ttinl(dest,max,timo,eol,start,turn) int max,timo,turn; CHAR *dest, eol, start;
  10716. #endif /* CK_ANSIC */
  10717. #else /* not PARSENSE */
  10718. #ifdef CK_ANSIC
  10719. ttinl(CHAR *dest, int max,int timo, CHAR eol)
  10720. #else
  10721. ttinl(dest,max,timo,eol) int max,timo; CHAR *dest, eol;
  10722. #endif /* CK_ANSIC */
  10723. #endif /* PARSENSE */
  10724. /* ttinl */ {
  10725.  
  10726. #ifndef MYREAD
  10727.     CHAR ch, dum;
  10728. #endif /* MYREAD */
  10729. #ifdef PARSENSE
  10730.     int pktlen = -1;
  10731.     int lplen = 0;
  10732.     int havelen = 0;
  10733. #endif /* PARSENSE */
  10734.     int fd;
  10735.     int sopmask = 0xff;            /* Start-Of-Packet mask */
  10736. #ifdef CKXXCHAR
  10737.     extern short dblt[];        /* Ignore-character table */
  10738.     extern int ignflag;
  10739. #endif /* CKXXCHAR */
  10740. #ifdef TCPSOCKET
  10741.     extern CHAR stchr;
  10742. #endif /* TCPSOCKET */
  10743.     int x;
  10744. #ifdef STREAMING
  10745.     extern int streaming;
  10746.     extern int sndtyp;
  10747. #endif /* STREAMING */
  10748.  
  10749.     if (ttyfd < 0) return(-3);          /* Not open. */
  10750. /*
  10751.   In February 2007 I fixed ttinl() to work better under the truly awful
  10752.   conditions encountered by the AM-APEX oceanographic floats that gather
  10753.   hurricane data and phone home using Iridium satellite modems, which under
  10754.   certain conditions, can send two packets back to back after a long pause.
  10755.   In this case the second packet would be ignored because the SOH was skipped
  10756.   due to the ttflui() call.  But the reworked lookahead/pushback logic broke
  10757.   Kermit transfers on encrypted connections.  This was fixed 12-13 August
  10758.   2007.  All of this happened after 8.0.212 Dev.27 was released and before
  10759.   Dev.28, so no harm done other than the delay.
  10760. */
  10761.     debug(F101,"ttinl max","",max);
  10762.     debug(F101,"ttinl timo","",timo);
  10763.  
  10764. #ifdef NETCMD
  10765.     if (ttpipe)
  10766.       fd = fdin;
  10767.     else
  10768. #endif /* NETCMD */
  10769.       fd = ttyfd;
  10770.  
  10771. #ifdef COMMENT
  10772.     if (xlocal && conchk() > 0)        /* Allow for console interruptions */
  10773.       return(-1);
  10774. #endif /* COMMENT */
  10775.  
  10776.     *dest = '\0';                       /* Clear destination buffer */
  10777.     if (timo < 0) timo = 0;        /* Safety */
  10778.     if (timo) {                /* Don't time out if timo == 0 */
  10779.     int xx;
  10780.     saval = signal(SIGALRM,timerh);    /* Enable timer interrupt */
  10781.     xx = alarm(timo);        /* Set it. */
  10782.     debug(F101,"ttinl alarm","",xx);
  10783.     }
  10784.     if (
  10785. #ifdef CK_POSIX_SIG
  10786.     sigsetjmp(sjbuf,1)
  10787. #else
  10788.     setjmp(sjbuf)
  10789. #endif /* CK_POSIX_SIG */
  10790.     ) {                /* Timer went off? */
  10791.     debug(F100,"ttinl timout","",0); /* Get here on timeout. */
  10792.     /* debug(F110," with",(char *) dest,0); */
  10793.     ttimoff();            /* Turn off timer */
  10794.     return(-1);            /* and return error code. */
  10795.     } else {
  10796.     register int i, n = -1;        /* local variables */
  10797.     int ccn = 0;
  10798. #ifdef PARSENSE
  10799.     register int flag = 0;
  10800.     debug(F000,"ttinl start","",start);
  10801. #endif /* PARSENSE */
  10802.  
  10803.     ttpmsk = ttprty ? 0177 : 0377;    /* Set parity stripping mask. */
  10804.     sopmask = needpchk ? 0177 : ttpmsk; /* And SOP matching mask. */
  10805.  
  10806. /* Now read into destination, stripping parity and looking for the */
  10807. /* the packet terminator, and also for several Ctrl-C's typed in a row. */
  10808.  
  10809.     i = 0;                /* Destination index */
  10810.     debug(F101,"ttinl eol","",eol);
  10811.  
  10812.     while (i < max-1) {
  10813. #ifdef MYREAD
  10814.         errno = 0;
  10815.         /* On encrypted connections myread returns encrypted bytes */
  10816.         n = myread();
  10817.         debug(F000,"TTINL myread char","",n);
  10818.         if (n < 0) {    /* Timeout or i/o error? */
  10819. #ifdef DEBUG
  10820.         if (deblog) {
  10821.             debug(F101,"ttinl myread failure, n","",n);
  10822.             debug(F101,"ttinl myread errno","",errno);
  10823.         }
  10824. #endif /* DEBUG */
  10825.         /* Don't let EINTR break packets. */
  10826.         if (n == -3) {
  10827.             if (errno == EINTR && i > 0) {
  10828.             debug(F111,"ttinl EINTR myread i","continuing",i);
  10829.             continue;
  10830.             } else {
  10831.             debug(F110,"ttinl non-EINTR -3","closing",0);
  10832.             wasclosed = 1;
  10833.             ttimoff();    /* Turn off timer */
  10834.             ttclos(0);
  10835.             return(n);
  10836.             }
  10837.         } else if (n == -2 && netconn /* && timo == 0 */ ) {
  10838.             /* Here we try to catch broken network connections */
  10839.             /* even when ioctl() and read() do not catch them */
  10840.             debug(F111,"ttinl network myread failure","closing",n);
  10841.             wasclosed = 1;
  10842.             ttimoff();
  10843.             ttclos(0);
  10844.             return(-3);
  10845.         }
  10846. #ifdef STREAMING
  10847.         /* Streaming and no data to read */
  10848.         else if (n == 0 && streaming && sndtyp == 'D')
  10849.           return(0);
  10850. #endif /* STREAMING */
  10851.         break;            /* Break out of while loop */
  10852.         }
  10853.  
  10854. #else /* not MYREAD (is this code used anywhere any more?) */
  10855. /*
  10856.   The non-MYREAD code dates from the 1980s and was needed on certain platforms
  10857.   where there were no nonblocking reads.  -fdc, 2007/02/22.
  10858. */
  10859.         if ((n = read(fd, &n, 1)) < 1)
  10860.           break;            /* Error - break out of while loop */
  10861.  
  10862. #endif /* MYREAD */
  10863.  
  10864.         /* Get here with char in n */
  10865.  
  10866. #ifdef CK_ENCRYPTION
  10867.         if (TELOPT_U(TELOPT_ENCRYPTION) && !pushedback) {
  10868.         CHAR ch = n;
  10869.         ck_tn_decrypt((char *)&ch,1);
  10870.         n = ch;
  10871.         debug(F000,"TTINL decryp char","",n);
  10872.         }
  10873.         pushedback = 0;
  10874. #endif /* CK_ENCRYPTION */
  10875.  
  10876. #ifdef TCPSOCKET
  10877.         if (n == IAC &&        /* Handle Telnet options */
  10878.         ((xlocal && netconn && IS_TELNET()) ||
  10879.         (!xlocal && sstelnet))) {
  10880.         n = tt_tnopt(n);
  10881.         if (n < 0)
  10882.           return(n);
  10883. #ifndef NOPARSEN
  10884.         else if (n == 1)
  10885.           start = stchr;
  10886. #endif /* NOPARSEN */
  10887.         if (n != 255)        /* No data - go back for next char */
  10888.           continue;
  10889.         }                /* Quoted IAC - keep going */
  10890. #endif /* TCPSOCKET */
  10891.  
  10892. #ifdef CKXXCHAR
  10893.         if (ignflag)
  10894.           if (dblt[(unsigned) n] & 1) /* Character to ignore? */
  10895.         continue;
  10896. #endif /* CKXXCHAR */
  10897. /*
  10898.   Use parity mask, rather than always stripping parity, to check for
  10899.   cancellation.  Otherwise, runs like \x03\x83\x03 in a packet could cancel
  10900.   the transfer when parity is NONE.  (Note that \x03\x03\x03 is extremely
  10901.   unlikely due to run-length encoding.)
  10902. */
  10903.         /* Check cancellation */
  10904.         if (!xlocal && xfrcan && ((n & ttpmsk) == xfrchr)) {
  10905.         if (++ccn >= xfrnum) {    /* If xfrnum in a row, bail out. */
  10906.             if (timo) {        /* Clear timer. */
  10907.             ttimoff();
  10908.             }
  10909.             if (xfrchr < 32)
  10910.               printf("^%c...\r\n",(char)(xfrchr+64));
  10911.             else
  10912.               printf("Canceled...\r\n");
  10913.             return(-2);
  10914.         }
  10915.         } else ccn = 0;        /* No cancellation, reset counter, */
  10916.  
  10917. #ifdef PARSENSE
  10918. /*
  10919.   Restructured code allows for a new packet to appear somewhere in the
  10920.   middle of a previous one.  -fdc, 24 Feb 2007.
  10921. */
  10922.         if ((n & sopmask) == start) { /* Start of Packet */
  10923.         debug(F101,"ttinl SOP i","",i);
  10924.         flag = 1;        /* Flag that we are in a packet */
  10925.         havelen = 0;        /* Invalidate previous length */
  10926.         pktlen = -1;        /* (if any) in case we were */
  10927.         lplen = 0;        /* alread processand a packet */
  10928.         i = 0;            /* and reset the dest buffer pointer */
  10929.         }
  10930.         if (flag == 0) {        /* No SOP yet... */
  10931.         debug(F000,"ttinl skipping","",n);
  10932.         continue;
  10933.         }
  10934.         dest[i++] = n & ttpmsk;
  10935. /*
  10936.   If we have not been instructed to wait for a turnaround character, we can go
  10937.   by the packet length field.  If turn != 0, we must wait for the end of line
  10938.   (eol) character before returning.  This is an egregious violation of all
  10939.   principles of layering...  (Less egregious in C-Kermit 9.0, in which we go
  10940.   by the length field but also look for the eol in case it arrives early,
  10941.   e.g. if the length field was corrupted upwards.)
  10942. */
  10943.         if (!havelen) {
  10944.         if (i == 2) {
  10945.             if ((dest[1] & 0x7f) < 32) /* Garbage in length field */
  10946.               return(-1);    /* fdc - 13 Apr 2010 */
  10947.             pktlen = xunchar(dest[1] & 0x7f);
  10948.                     if (pktlen > 94)    /* Rubout in length field */
  10949.               return(-1);    /* fdc - 13 Apr 2010 */
  10950.             if (pktlen > 1) {
  10951.             havelen = 1;
  10952.             debug(F101,"ttinl pktlen value","",pktlen);
  10953.             }
  10954.         } else if (i == 5 && pktlen == 0) {
  10955.             lplen = xunchar(dest[4] & 0x7f);
  10956.         } else if (i == 6 && pktlen == 0) {
  10957.             pktlen = lplen * 95 + xunchar(dest[5] & 0x7f) + 5;
  10958.             havelen = 1;
  10959.             debug(F101,"ttinl extended length","",pktlen);
  10960.         }
  10961.         }
  10962.  
  10963. /*
  10964.   Suppose we looked at the sequence number here and found it was out of
  10965.   range?  This would mean either (a) incoming packets had SOP unprefixed
  10966.   and we are out of sync, or (b) the packet is damaged.  Since (a) is bad
  10967.   practice, let's ignore it.  So what should we do here if we know the
  10968.   packet is damaged?
  10969.  
  10970.    1. Nothing -- keep trying to read the packet till we find what we think
  10971.       is the end, or we time out, and let the upper layer decide what to
  10972.       do.  But since either the packet is corrupt or we are out of sync,
  10973.       our criterion for finding the end does not apply and we are likely
  10974.       to time out (or swallow a piece of the next packet) if our assumed
  10975.       length is too long.  (This was the behavior prior to version 7.0.)
  10976.  
  10977.    2. set flag = 0 and continue?  This would force us to wait for the
  10978.       next packet to come in, and therefore (in the nonwindowing case),
  10979.       would force a timeout in the other Kermit.
  10980.  
  10981.    3. set flag = 0 and continue, but only if the window size is > 1 and
  10982.       the window is not blocked?  Talk about cheating!
  10983.  
  10984.    4. Return a failure code and let the upper layer decide what to do.
  10985.       This should be equivalent to 3, but without the cheating.  So let's
  10986.       do it that way...  But note that we must ignore the parity bit
  10987.       in case this is the first packet and we have not yet run parchk().
  10988. */
  10989.         if (i == 3) {        /* Peek at sequence number */
  10990.         x = xunchar((dest[i-1] & 0x7f)); /* If it's not in range... */
  10991.         if (x < 0 || x > 63) {
  10992.             debug(F111,"ttinl bad seq",dest,x);
  10993.             if (timo) ttimoff();
  10994.             return(-1);        /* return a nonfatal error */
  10995.         }
  10996.         }
  10997.  
  10998. #else /* PARSENSE */
  10999.         dest[i++] = n & ttpmsk;
  11000. #endif /* PARSENSE */
  11001.  
  11002.     /* Check for end of packet */
  11003.  
  11004.         if (
  11005.         ((n & ttpmsk) == eol)    /* Always break on the eol char */
  11006. #ifdef PARSENSE
  11007.          ||            /* fdc - see notes of 13 Apr 2010 */
  11008. /*
  11009.   Purely length-driven if SET HANDSHAKE NONE (i.e. turn == 0).
  11010.   This allows packet terminators and handshake characters to appear
  11011.   literally inside a packet data field.
  11012. */
  11013.         (havelen && (i > pktlen+1) &&
  11014.          (!turn || (turn && (n & 0x7f) == turn))) /* (turn, not eol) */
  11015.  
  11016. #endif /* PARSENSE */
  11017.         ) {
  11018. /*
  11019.   Here we have either read the last byte of the packet based on its length
  11020.   field, or else we have read the packet terminator (eol) or the half-duplex
  11021.   line-turnaround char (turn).
  11022. */
  11023. #ifndef PARSENSE
  11024.         debug(F101,"ttinl got eol","",eol); /* (or turn) */
  11025.         dest[i] = '\0';        /* Yes, terminate the string, */
  11026.         /* debug(F101,"ttinl i","",i); */
  11027.  
  11028. #else  /* PARSENSE */
  11029.  
  11030. #ifdef DEBUG
  11031.         if (deblog) {
  11032.             if ((n & ttpmsk) != eol) {
  11033.             debug(F101,"ttinl EOP length","",pktlen);
  11034.             debug(F000,"ttinl EOP current char","",n);
  11035.             debug(F101,"ttinl EOP packet buf index","",i);
  11036.             } else debug(F101,"ttinl got eol","",eol);
  11037.         }
  11038. #endif /* DEBUG */
  11039.  
  11040. #ifdef MYREAD
  11041. /*
  11042.   The packet was read based on its length.  This leaves the packet terminator
  11043.   unread, and so ttchk() will always return at least 1 because of this,
  11044.   possibly giving a false positive to the "is there another packet waiting?"
  11045.   test.  But if we know the terminator (or any other interpacket junk) is
  11046.   there, we can safely get rid of it.
  11047.  
  11048.   NOTE: This code reworked to (a) execute even if the debug log isn't active;
  11049.   and (b) actually work.  -fdc, 2007/02/22.  And again 2007/08/12-13 to also
  11050.   work on encrypted connections.
  11051. */    
  11052.         debug(F101,"TTINL my_count","",my_count);
  11053.         if ((n & ttpmsk) != eol) { /* Not the packet terminator */
  11054.             int x;
  11055.             while (my_count > 0) {
  11056.             x = myread();       /* (was ttinc(0) */
  11057.             debug(F000,"TTINL lkread char","",x);
  11058. #ifdef CK_ENCRYPTION
  11059.             if (TELOPT_U(TELOPT_ENCRYPTION)) {
  11060.                 CHAR ch = x;
  11061.                 ck_tn_decrypt((char *)&ch,1);
  11062.                 x = ch;
  11063.                 debug(F000,"TTINL lkdecr char","",x); 
  11064.             }
  11065. #endif    /* CK_ENCRYPTION */
  11066.             /*
  11067.               Note: while it might seem more elegant to simply
  11068.               push back the encrypted byte, that desynchronizes
  11069.               the decryption stream; the flag is necessary so we
  11070.               don't try to decrypt the same byte twice.
  11071.             */
  11072.             if ((x & ttpmsk) == start) { /* Start of next packet */
  11073.                 myunrd(x);    /* Push back the decrypted byte */
  11074.                 pushedback = 1; /* And set flag */
  11075.                 debug(F000,"TTINL lkpush char","",x);
  11076.                 break;
  11077.             }
  11078.             }
  11079.         }
  11080. #endif /* MYREAD */
  11081.  
  11082.         dest[i] = '\0';        /* Terminate the string, */
  11083.             if (needpchk) {        /* Parity checked yet? */
  11084.             if (ttprty == 0) {    /* No, check. */
  11085.             if ((ttprty = parchk(dest,start,i)) > 0) {
  11086.                 int j;
  11087.                 debug(F101,"ttinl senses parity","",ttprty);
  11088.                 debug(F110,"ttinl packet before",dest,0);
  11089.                 ttpmsk = 0x7f;
  11090.                 for (j = 0; j < i; j++)
  11091.                   dest[j] &= 0x7f;    /* Strip parity from packet */
  11092.                 debug(F110,"ttinl packet after ",dest,0);
  11093.             } else ttprty = 0; /* Restore if parchk error */
  11094.             }
  11095.             sopmask = ttpmsk;
  11096.             needpchk = 0;
  11097.         }
  11098. #endif /* PARSENSE */
  11099.  
  11100.         if (timo)        /* Turn off timer if it was on */
  11101.           ttimoff();
  11102.                 ckhexdump("ttinl got",dest,i);
  11103.  
  11104. #ifdef STREAMING
  11105.         /* ttinl() was called because there was non-packet */
  11106.         /* data sitting in the back channel.  Ignore it.   */
  11107.         if (streaming && sndtyp == 'D')
  11108.           return(-1);
  11109. #endif /* STREAMING */
  11110.         return(i);
  11111.         }
  11112.     } /* End of while() */
  11113.     ttimoff();
  11114.     return(n);
  11115.     }
  11116. }
  11117. #endif /* NOXFER */
  11118.  
  11119. /*  T T I N C --  Read a character from the communication line  */
  11120. /*
  11121.  On success, returns the character that was read, >= 0.
  11122.  On failure, returns -1 or other negative myread error code,
  11123.    or -2 if connection is broken or ttyfd < 0.
  11124.    or -3 if session limit has expired,
  11125.    or -4 if something or other...
  11126.  NOTE: The API does not provide for ttinc() returning a special code
  11127.  upon timeout, but we need it.  So for this we have a global variable,
  11128.  ttinctimo.
  11129. */
  11130. static int ttinctimo = 0;        /* Yuk */
  11131.  
  11132. int
  11133. ttinc(timo) int timo; {
  11134.  
  11135.     int n = 0, fd;
  11136.     int is_tn = 0;
  11137.     CHAR ch = 0;
  11138.  
  11139.     ttinctimo = 0;
  11140.  
  11141.     if (ttyfd < 0) return(-2);          /* Not open. */
  11142.  
  11143.     is_tn = (xlocal && netconn && IS_TELNET()) ||
  11144.         (!xlocal && sstelnet);
  11145.  
  11146. #ifdef TTLEBUF
  11147.     if (ttpush >= 0) {
  11148.         debug(F111,"ttinc","ttpush",ttpush);
  11149.         ch = ttpush;
  11150.         ttpush = -1;
  11151.         return(ch);
  11152.     }
  11153.     if (le_data) {
  11154.         if (le_getchar(&ch) > 0) {
  11155.             debug(F111,"ttinc le_getchar","ch",ch);
  11156.             return(ch);
  11157.         }
  11158.     }
  11159. #endif /* TTLEBUF */
  11160.  
  11161. #ifdef NETCMD
  11162.     if (ttpipe)
  11163.       fd = fdin;
  11164.     else
  11165. #endif /* NETCMD */
  11166.       fd = ttyfd;
  11167.  
  11168.     if ((timo <= 0)            /* Untimed. */
  11169. #ifdef MYREAD
  11170.     || (my_count > 0)        /* Buffered char already waiting. */
  11171. #endif /* MYREAD */
  11172.     ) {
  11173. #ifdef MYREAD
  11174.         /* Comm line failure returns -1 thru myread, so no &= 0377 */
  11175.     n = myread();            /* Wait for a character... */
  11176.     /* debug(F000,"ttinc MYREAD n","",n); */
  11177. #ifdef CK_ENCRYPTION
  11178.     /* debug(F101,"ttinc u_encrypt","",TELOPT_U(TELOPT_ENCRYPTION)); */
  11179.     if (TELOPT_U(TELOPT_ENCRYPTION) && n >= 0) {
  11180.         ch = n;
  11181.         ck_tn_decrypt((char *)&ch,1);
  11182.         n = ch;
  11183.     }
  11184. #endif /* CK_ENCRYPTION */
  11185.  
  11186. #ifdef NETPTY
  11187.     if (ttpty && n < 0) {
  11188.         debug(F101,"ttinc error on pty","",n);
  11189.         ttclos(0);
  11190.         return(n);
  11191.     }
  11192. #endif /* NETPTY */
  11193.  
  11194. #ifdef TNCODE
  11195.     if ((n > -1) && is_tn)
  11196.       return((unsigned)(n & 0xff));
  11197.     else
  11198. #endif /* TNCODE */
  11199.       return(n < 0 ? n : (unsigned)(n & ttpmsk));
  11200.  
  11201. #else  /* MYREAD */
  11202.  
  11203.         while ((n = read(fd,&ch,1)) == 0) /* Wait for a character. */
  11204.         /* Shouldn't have to loop in ver 5A. */
  11205. #ifdef NETCONN
  11206.       if (netconn) {        /* Special handling for net */
  11207.           netclos();        /* If read() returns 0 it means */
  11208.           netconn = 0;        /* the connection has dropped. */
  11209.           errno = ENOTCONN;
  11210.           return(-2);
  11211.       }
  11212. #endif /* NETCONN */
  11213.       ;
  11214.     /* debug(F101,"ttinc","",ch); */
  11215. #ifdef TNCODE
  11216.     if ((n > 0) && is_tn) {
  11217. #ifdef CK_ENCRYPTION
  11218.         if (TELOPT_U(TELOPT_ENCRYPTION)) {
  11219.         ck_tn_decrypt(&ch,1);
  11220.         n = ch;
  11221.         }
  11222. #endif /* CK_ENCRYPTION */
  11223.         return((unsigned)(ch & 0xff));
  11224.     } else
  11225. #endif /* TNCODE */
  11226.         return((n < 0) ? -4 : ((n == 0) ? -1 : (unsigned)(ch & ttpmsk)));
  11227. #endif /* MYREAD */
  11228.  
  11229.     } else {                /* Timed read */
  11230.  
  11231.     int oldalarm;
  11232.     saval = signal(SIGALRM,timerh);    /* Set up handler, save old one. */
  11233.     oldalarm = alarm(timo);        /* Set alarm, save old one. */
  11234.     if (
  11235. #ifdef CK_POSIX_SIG
  11236.         sigsetjmp(sjbuf,1)
  11237. #else
  11238.         setjmp(sjbuf)
  11239. #endif /* CK_POSIX_SIG */
  11240.         ) {                /* Timer expired */
  11241.         ttinctimo = 1;
  11242.         n = -1;            /* set flag */
  11243.     } else {
  11244. #ifdef MYREAD
  11245.         n = myread();        /* If managing own buffer... */
  11246.         debug(F101,"ttinc myread","",n);
  11247.         ch = n;
  11248. #else
  11249.         n = read(fd,&ch,1);        /* Otherwise call the system. */
  11250.         if (n == 0) n = -1;
  11251.         debug(F101,"ttinc read","",n);
  11252. #endif /* MYREAD */
  11253.  
  11254. #ifdef CK_ENCRYPTION
  11255.         if (TELOPT_U(TELOPT_ENCRYPTION) && n >= 0) {
  11256.         ck_tn_decrypt((char *)&ch,1);
  11257.         }
  11258. #endif /* CK_ENCRYPTION */
  11259.         if (n >= 0)
  11260.           n = (unsigned) (ch & 0xff);
  11261.         else
  11262.           n = (n < 0) ? -4 : -2;    /* Special return codes. */
  11263.     }
  11264.     ttimoff();            /* Turn off the timer */
  11265.     if (oldalarm > 0) {
  11266.         if (n == -1)        /* and restore any previous alarm */
  11267.           oldalarm -= timo;
  11268.         if (oldalarm < 0)        /* adjusted by our timeout interval */
  11269.           oldalarm = 0;
  11270.         if (oldalarm) {
  11271.             debug(F101,"ttinc restoring oldalarm","",oldalarm);
  11272.         alarm(oldalarm);
  11273.         }
  11274.     }
  11275. #ifdef NETCONN
  11276.     if (netconn) {
  11277.         if (n == -2) {        /* read() returns 0 */
  11278.         netclos();        /* on network read failure */
  11279.         netconn = 0;
  11280.         errno = ENOTCONN;
  11281.         }
  11282.     }
  11283. #endif    /* NETCONN */
  11284. #ifdef TNCODE
  11285.     if ((n > -1) && is_tn)
  11286.       return((unsigned)(n & 0xff));
  11287.     else
  11288. #endif /* TNCODE */
  11289.       /* Return masked char or neg. */
  11290.       return( (n < 0) ? n : (unsigned)(n & ttpmsk) );
  11291.     }
  11292. }
  11293.  
  11294. /*  S N D B R K  --  Send a BREAK signal of the given duration  */
  11295.  
  11296. static int
  11297. #ifdef CK_ANSIC
  11298. sndbrk(int msec) {            /* Argument is milliseconds */
  11299. #else
  11300. sndbrk(msec) int msec; {
  11301. #endif /* CK_ANSIC */
  11302. #ifndef POSIX
  11303.     int x, n;
  11304. #endif /* POSIX */
  11305.  
  11306. #ifdef OXOS
  11307. #define BSDBREAK
  11308. #endif /* OXOS */
  11309.  
  11310. #ifdef ANYBSD
  11311. #define BSDBREAK
  11312. #endif /* ANYBSD */
  11313.  
  11314. #ifdef BSD44
  11315. #define BSDBREAK
  11316. #endif /* BSD44 */
  11317.  
  11318. #ifdef COHERENT
  11319. #ifdef BSDBREAK
  11320. #undef BSDBREAK
  11321. #endif /* BSDBREAK */
  11322. #endif /* COHERENT */
  11323.  
  11324. #ifdef BELLV10
  11325. #ifdef BSDBREAK
  11326. #undef BSDBREAK
  11327. #endif /* BSDBREAK */
  11328. #endif /* BELLV10 */
  11329.  
  11330. #ifdef PROVX1
  11331.     char spd;
  11332. #endif /* PROVX1 */
  11333.  
  11334.     debug(F101,"ttsndb ttyfd","",ttyfd);
  11335.     if (ttyfd < 0) return(-1);          /* Not open. */
  11336.  
  11337. #ifdef Plan9
  11338.     return p9sndbrk(msec);
  11339. #else
  11340. #ifdef NETCONN
  11341. #ifdef NETCMD
  11342.     if (ttpipe)                /* Pipe */
  11343.       return(ttoc('\0'));
  11344. #endif /* NETCMD */
  11345. #ifdef NETPTY
  11346.     if (ttpty)
  11347.       return(ttoc('\0'));
  11348. #endif /* NETPTY */
  11349.     if (netconn)             /* Send network BREAK */
  11350.       return(netbreak());
  11351. #endif /* NETCONN */
  11352.  
  11353.     if (msec < 1 || msec > 5000) return(-1); /* Bad argument */
  11354.  
  11355. #ifdef POSIX                /* Easy in POSIX */
  11356.     {
  11357.     int x;
  11358.     debug(F111,"sndbrk POSIX",ckitoa(msec),(msec/375));
  11359.     errno = 0;
  11360.     x = tcsendbreak(ttyfd,msec / 375);
  11361.     debug(F111,"sndbrk tcsendbreak",ckitoa(errno),x);
  11362.     return(x);
  11363.     }
  11364. #else
  11365. #ifdef PROVX1
  11366.     gtty(ttyfd,&ttbuf);                 /* Get current tty flags */
  11367.     spd = ttbuf.sg_ospeed;              /* Save speed */
  11368.     ttbuf.sg_ospeed = B50;              /* Change to 50 baud */
  11369.     stty(ttyfd,&ttbuf);                 /*  ... */
  11370.     n = (int)strlen(brnuls);        /* Send the right number of nulls */
  11371.     x = msec / 91;
  11372.     if (x > n) x = n;
  11373.     write(ttyfd,brnuls,n);
  11374.     ttbuf.sg_ospeed = spd;              /* Restore speed */
  11375.     stty(ttyfd,&ttbuf);                 /*  ... */
  11376.     return(0);
  11377. #else
  11378. #ifdef aegis
  11379.     sio_$control((short)ttyfd, sio_$send_break, msec, st);
  11380.     return(0);
  11381. #else
  11382. #ifdef BSDBREAK
  11383.     n = FWRITE;                         /* Flush output queue. */
  11384. /* Watch out for int vs long problems in &n arg! */
  11385.     debug(F101,"sndbrk BSDBREAK","",msec);
  11386.     ioctl(ttyfd,TIOCFLUSH,&n);          /* Ignore any errors.. */
  11387.     if (ioctl(ttyfd,TIOCSBRK,(char *)0) < 0) {  /* Turn on BREAK */
  11388.         perror("Can't send BREAK");
  11389.         return(-1);
  11390.     }
  11391.     x = msleep(msec);                    /* Sleep for so many milliseconds */
  11392.     if (ioctl(ttyfd,TIOCCBRK,(char *)0) < 0) {  /* Turn off BREAK */
  11393.         perror("BREAK stuck!!!");
  11394.         doexit(BAD_EXIT,-1);        /* Get out, closing the line. */
  11395.                                         /*   with bad exit status */
  11396.     }
  11397.     return(x);
  11398. #else
  11399. #ifdef ATTSV
  11400. /*
  11401.   No way to send a long BREAK in Sys V, so send a bunch of regular ones.
  11402.   (Actually, Sys V R4 is *supposed* to have the POSIX tcsendbreak() function,
  11403.   but there's no way for this code to know for sure.)
  11404. */
  11405.     debug(F101,"sndbrk ATTSV","",msec);
  11406.     x = msec / 275;
  11407.     for (n = 0; n < x; n++) {
  11408.     /* Reportedly the cast breaks this function on some systems */
  11409.     /* But then why was it here in the first place? */
  11410.     if (ioctl(ttyfd,TCSBRK, /* (char *) */ 0) < 0) {
  11411.         perror("Can't send BREAK");
  11412.         return(-1);
  11413.     }
  11414.     }
  11415.     return(0);
  11416. #else
  11417. #ifdef  V7
  11418.     debug(F101,"sndbrk V7","",msec);
  11419.     return(genbrk(ttyfd,250));        /* Simulate a BREAK */
  11420. #else
  11421.     debug(F101,"sndbrk catchall","",msec);
  11422.     ttoc(0);ttoc(0);ttoc(0);ttoc(0);
  11423.     return(0);
  11424. #endif /* V7 */
  11425. #endif /* BSDBREAK */
  11426. #endif /* ATTSV */
  11427. #endif /* aegis */
  11428. #endif /* PROVX1 */
  11429. #endif /* POSIX */
  11430. #endif /* Plan9 */
  11431. }
  11432.  
  11433. /*  T T S N D B  --  Send a BREAK signal  */
  11434.  
  11435. int
  11436. ttsndb() {
  11437. #ifdef TN_COMPORT
  11438.     if (netconn && istncomport())
  11439.       return((tnsndb(275L) >= 0) ? 0 : -1);
  11440.     else
  11441. #endif /* TN_COMPORT */
  11442.       return(sndbrk(275));
  11443. }
  11444.  
  11445. /*  T T S N D L B  --  Send a Long BREAK signal  */
  11446.  
  11447. int
  11448. ttsndlb() {
  11449. #ifdef TN_COMPORT
  11450.     if (netconn && istncomport())
  11451.       return((tnsndb(1800L) >= 0) ? 0 : -1);
  11452.     else
  11453. #endif /* TN_COMPORT */
  11454.     return(sndbrk(1500));
  11455. }
  11456.  
  11457. /*  M S L E E P  --  Millisecond version of sleep().  */
  11458.  
  11459. /*
  11460.   Call with number of milliseconds (thousandths of seconds) to sleep.
  11461.   Intended only for small intervals.  For big ones, just use sleep().
  11462.   Highly system-dependent.
  11463.   Returns 0 always, even if it didn't work.
  11464. */
  11465.  
  11466. /* Define MSLFTIME for systems that must use an ftime() loop. */
  11467. #ifdef ANYBSD                /* For pre-4.2 BSD versions */
  11468. #ifndef BSD4
  11469. #define MSLFTIME
  11470. #endif /* BSD4 */
  11471. #endif /* ANYBSD */
  11472.  
  11473. #ifdef TOWER1                /* NCR Tower OS 1.0 */
  11474. #define MSLFTIME
  11475. #endif /* TOWER1 */
  11476.  
  11477. #ifdef COHERENT         /* Coherent... */
  11478. #ifndef _I386           /* Maybe Coherent/386 should get this, too */
  11479. #define MSLFTIME        /* Opinions are divided */
  11480. #endif /* _I386 */
  11481. #endif /* COHERENT */
  11482.  
  11483. #ifdef COMMENT
  11484. #ifdef GETMSEC
  11485.  
  11486. /* Millisecond timer */
  11487.  
  11488. static long msecbase = 0L;        /* Unsigned long not portable */
  11489.  
  11490. long
  11491. getmsec() {                /* Milliseconds since base time */
  11492.     struct timeval xv;
  11493.     struct timezone xz;
  11494.     long secs, msecs;
  11495.     if (
  11496. #ifdef GTODONEARG
  11497.     gettimeofday(&tv)
  11498. #else
  11499. #ifdef PTX
  11500.     gettimeofday(&tv, NULL)
  11501. #else
  11502.     gettimeofday(&tv, &tz)
  11503. #endif /* PTX */
  11504. #endif /* GTODONEARG */
  11505.     < 0)
  11506.       return(-1);
  11507.     if (msecbase == 0L) {        /* First call, set base time. */
  11508.     msecbase = tv.tv_sec;
  11509.     debug(F101,"getmsec base","",msecbase);
  11510.     }
  11511.     return(((tv.tv_sec - msecbase) * 1000L) + (tv.tv_usec / 1000L));
  11512. }
  11513. #endif /* GETMSEC */
  11514. #endif /* COMMENT */
  11515.  
  11516. #ifdef SELECT
  11517. int
  11518. ttwait(fd, secs) int fd, secs; {
  11519.     int x;
  11520.     fd_set rfds;
  11521.     FD_ZERO(&rfds);
  11522.     FD_SET(fd,&rfds);
  11523.     tv.tv_sec = secs;
  11524.     tv.tv_usec = 0L;
  11525.     errno = 0;
  11526.     if ((x = select(FD_SETSIZE,
  11527. #ifdef HPUX9
  11528.             (int *)
  11529. #else
  11530. #ifdef HPUX1000
  11531.             (int *)
  11532. #endif /* HPUX1000 */
  11533. #endif /* HPUX9 */
  11534.             &rfds,
  11535.             0, 0, &tv)) < 0) {
  11536.     debug(F101,"ttwait select errno","",errno);
  11537.     return(0);
  11538.     } else {
  11539.     debug(F101,"ttwait OK","",errno);
  11540.     x = FD_ISSET(fd, &rfds);
  11541.     debug(F101,"ttwait select x","",x);
  11542.     return(x ? 1 : 0);
  11543.     }
  11544. }
  11545. #endif /* SELECT */
  11546.  
  11547. int
  11548. msleep(m) int m; {
  11549. /*
  11550.   Other possibilities here are:
  11551.    nanosleep(), reportedly defined in POSIX.4.
  11552.    sginap(), IRIX only (back to what IRIX version I don't know).
  11553. */
  11554. #ifdef Plan9
  11555.     return _SLEEP(m);
  11556. #else
  11557. #ifdef BEOSORBEBOX
  11558.     snooze(m*1000);
  11559. #else /* BEOSORBEBOX */
  11560. #ifdef SELECT
  11561.     int t1, x;
  11562.     debug(F101,"msleep SELECT 1","",m);
  11563.     if (m <= 0) return(0);
  11564.     if (m >= 1000) {            /* Catch big arguments. */
  11565.     sleep(m/1000);
  11566.     m = m % 1000;
  11567.     if (m < 10) return(0);
  11568.     }
  11569.     debug(F101,"msleep SELECT 2","",m);
  11570. #ifdef BELLV10
  11571.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, m );
  11572.     debug(F101,"msleep BELLV10 select","",x);
  11573. #else /* BELLV10 */
  11574. #ifdef HPUX9
  11575.     gettimeofday(&tv, &tz);
  11576. #else
  11577.  
  11578. #ifndef COHERENT
  11579. #ifdef GTODONEARG
  11580.     if (gettimeofday(&tv) < 0)
  11581. #else
  11582. #ifdef PTX
  11583.     if (gettimeofday(&tv,NULL) < 0)
  11584. #else
  11585. #ifdef NOTIMEZONE
  11586.     if (gettimeofday(&tv, NULL) < 0)    /* wonder what this does... */
  11587. #else
  11588.     if (gettimeofday(&tv, &tz) < 0)
  11589. #endif /* NOTIMEZONE */
  11590. #endif /* PTX */
  11591. #endif /* GTODONEARG */
  11592.       return(-1);
  11593.     t1 = tv.tv_sec;                     /* Seconds */
  11594. #endif /* COHERENT */
  11595. #endif /* HPUX9 */
  11596.     tv.tv_sec = 0;                      /* Use select() */
  11597.     tv.tv_usec = m * 1000L;
  11598. #ifdef BSD44
  11599.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11600.     debug(F101,"msleep BSD44 select","",x);
  11601. #else /* BSD44 */
  11602. #ifdef __linux__
  11603.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11604.     debug(F101,"msleep __linux__ select","",x);
  11605. #else /* __linux__ */
  11606. #ifdef BSD43
  11607.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11608.     debug(F101,"msleep BSD43 select","",x);
  11609. #else /* BSD43 */
  11610. #ifdef QNX6
  11611.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11612.     debug(F101,"msleep QNX6 select","",x);
  11613. #else /* QNX6 */
  11614. #ifdef QNX
  11615.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11616.     debug(F101,"msleep QNX select","",x);
  11617. #else /* QNX */
  11618. #ifdef COHERENT
  11619.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11620.     debug(F101,"msleep COHERENT select","",x);
  11621. #else /* COHERENT */
  11622. #ifdef HPUX1000                /* 10.00 only, not 10.10 or later */
  11623.     x = select( 0, (int *)0, (int *)0, (int *)0, &tv );
  11624.     debug(F101,"msleep HP-UX 10.00 select","",x);
  11625. #else /* HPUX1000 */
  11626. #ifdef SVR4
  11627.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11628.     debug(F101,"msleep SVR4 select","",x);
  11629. #else /* SVR4 */
  11630. #ifdef OSF40
  11631.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11632.     debug(F101,"msleep OSF40 select","",x);
  11633. #else /* OSF40 */
  11634. #ifdef PTX
  11635.     x = select( 0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &tv );
  11636.     debug(F101,"msleep OSF40 select","",x);
  11637. #else
  11638.     x = select( 0, (int *)0, (int *)0, (int *)0, &tv );
  11639.     debug(F101,"msleep catch-all select","",x);
  11640. #endif /* PTX */
  11641. #endif /* OSF40 */
  11642. #endif /* HP1000 */
  11643. #endif /* SVR4 */
  11644. #endif /* COHERENT */
  11645. #endif /* QNX */
  11646. #endif /* QNX6 */
  11647. #endif /* BSD43 */
  11648. #endif /* __linux__ */
  11649. #endif /* BSD44 */
  11650. #endif /* BELLV10 */
  11651.     return(0);
  11652.  
  11653. #else                    /* Not SELECT */
  11654. #ifdef CK_POLL                /* We have poll() */
  11655.     struct pollfd pfd;            /* Supply a valid address for poll() */
  11656.  
  11657. #ifdef ODT30                /* But in SCO ODT 3.0 */
  11658. #ifdef NAP                /* we should use nap() instead */
  11659.     debug(F101,"msleep ODT 3.0 NAP","",m); /* because using poll() here */
  11660.     nap((long)m);               /* seems to break dialing. */
  11661.     return(0);
  11662. #else
  11663.     debug(F101,"msleep ODT 3.0 POLL","",m);
  11664.     poll(&pfd, 0, m);
  11665.     return(0);
  11666. #endif /* NAP */
  11667. #else
  11668.     debug(F101,"msleep POLL","",m);
  11669.     poll(&pfd, 0, m);
  11670.     return(0);
  11671. #endif /* ODT30 */
  11672.  
  11673. /*
  11674.   We could handle the above more cleanly by just letting nap() always
  11675.   take precedence over poll() in this routine, but there is no way to know
  11676.   whether that would break something else.
  11677. */
  11678.  
  11679. #else                    /* Not POLL */
  11680. #ifdef USLEEP
  11681. /*
  11682.   "This routine is implemented using setitimer(2); it requires eight
  11683.   system calls...".  In other words, it might take 5 minutes to sleep
  11684.   10 milliseconds...
  11685. */
  11686.     debug(F101,"msleep USLEEP","",m);
  11687.     if (m >= 1000) {            /* Catch big arguments. */
  11688.     sleep(m/1000);
  11689.     m = m % 1000;
  11690.     if (m < 10) return(0);
  11691.     }
  11692.     usleep((unsigned int)(m * 1000));
  11693.     return(0);
  11694. #else
  11695. #ifdef aegis
  11696.     time_$clock_t dur;
  11697.     debug(F101,"msleep aegis","",m);
  11698.     dur.c2.high16 = 0;
  11699.     dur.c2.low32  = 250 * m; /* one millisecond = 250 four microsecond ticks */
  11700.     time_$wait(time_$relative, dur, st);
  11701.     return(0);
  11702. #else
  11703. #ifdef PROVX1
  11704.     debug(F101,"msleep Venix","",m);
  11705.     if (m <= 0) return(0);
  11706.     sleep(-((m * 60 + 500) / 1000));
  11707.     return(0);
  11708. #else
  11709. #ifdef NAP
  11710.     debug(F101,"msleep NAP","",m);
  11711.     nap((long)m);
  11712.     return(0);
  11713. #else
  11714. #ifdef ATTSV
  11715. #ifndef BSD44
  11716.     extern long times();        /* Or #include <times.h> ? */
  11717. #endif /* BSD44 */
  11718.     long t1, t2, tarray[4];
  11719.     int t3;
  11720.     char *cp = getenv("HZ");
  11721.     int CLOCK_TICK;
  11722.     int hertz;
  11723.  
  11724.     if (cp && (hertz = atoi(cp))) {
  11725.         CLOCK_TICK  = 1000 / hertz;
  11726.     } else {                /* probably single user mode */
  11727. #ifdef HZ
  11728.         CLOCK_TICK  = 1000 / HZ;
  11729. #else
  11730.     static warned = 0;
  11731.     /* HZ always exists in, for instance, SCO Xenix, so you don't have to
  11732.      * make special #ifdefs for XENIX here, like in ver 4F. Also, if you
  11733.      * have Xenix, you have should have nap(), so the best is to use -DNAP
  11734.      * in the makefile. Most systems have HZ.
  11735.      */
  11736.     CLOCK_TICK = 17;        /* 1/60 sec */
  11737.     if (!warned) {
  11738.           printf("warning: environment variable HZ bad... using HZ=%d\r\n",
  11739.          1000 / CLOCK_TICK);
  11740.           warned = 1;
  11741.     }
  11742. #endif /* !HZ */
  11743.     }
  11744.     debug(F101,"msleep ATTSV","",m);
  11745.     if (m <= 0) return(0);
  11746.     if (m >= 1000) {            /* Catch big arguments. */
  11747.     sleep(m/1000);
  11748.     m = m % 1000;
  11749.     if (m < 10) return(0);
  11750.     }
  11751.     if ((t1 = times(tarray)) < 0) return(-1);
  11752.     while (1) {
  11753.         if ((t2 = times(tarray)) < 0) return(-1);
  11754.         t3 = ((int)(t2 - t1)) * CLOCK_TICK;
  11755.         if (t3 > m) return(t3);
  11756.     }
  11757. #else /* Not ATTSV */
  11758. #ifdef MSLFTIME                /* Use ftime() loop... */
  11759.     int t1, t3 = 0;
  11760.     debug(F101,"msleep MSLFTIME","",m);
  11761.     if (m <= 0) return(0);
  11762.     if (m >= 1000) {            /* Catch big arguments. */
  11763.     sleep(m/1000);
  11764.     m = m % 1000;
  11765.     if (m < 10) return(0);
  11766.     }
  11767. #ifdef QNX
  11768.     ftime(&ftp);            /* void ftime() in QNX */
  11769. #else
  11770.     if (ftime(&ftp) < 0) return(-1);    /* Get base time. */
  11771. #endif /* QNX */
  11772.     t1 = ((ftp.time & 0xff) * 1000) + ftp.millitm;
  11773.     while (1) {
  11774.         ftime(&ftp);            /* Get current time and compare. */
  11775.         t3 = (((ftp.time & 0xff) * 1000) + ftp.millitm) - t1;
  11776.         if (t3 > m) return(0);
  11777.     }
  11778. #else
  11779. /* This includes true POSIX, which has no way to do this. */
  11780.     debug(F101,"msleep busy loop","",m);
  11781.     if (m >= 1000) {            /* Catch big arguments. */
  11782.     sleep(m/1000);
  11783.     m = m % 1000;
  11784.     if (m < 10) return(0);
  11785.     }
  11786.     if (m > 0) while (m > 0) m--;    /* Just a dumb busy loop */
  11787.     return(0);
  11788. #endif /* MSLFTIME */
  11789. #endif /* ATTSV */
  11790. #endif /* NAP */
  11791. #endif /* PROVX1 */
  11792. #endif /* aegis */
  11793. #endif /* CK_POLL */
  11794. #endif /* SELECT */
  11795. #endif /* BEOSORBEBOX */
  11796. #endif /* USLEEP */
  11797. #endif /* Plan9 */
  11798. }
  11799.  
  11800. /*  R T I M E R --  Reset elapsed time counter  */
  11801.  
  11802. VOID
  11803. rtimer() {
  11804.     tcount = time( (time_t *) 0 );
  11805. }
  11806.  
  11807.  
  11808. /*  G T I M E R --  Get current value of elapsed time counter in seconds  */
  11809.  
  11810. int
  11811. gtimer() {
  11812.     int x;
  11813.     x = (int) (time( (time_t *) 0 ) - tcount);
  11814.     debug(F101,"gtimer","",x);
  11815.     return( (x < 0) ? 0 : x );
  11816. }
  11817.  
  11818. #ifdef GFTIMER
  11819. /*
  11820.   Floating-point timers.  Require not only floating point support, but
  11821.   also gettimeofday().
  11822. */
  11823. static struct timeval tzero;
  11824.  
  11825. VOID
  11826. rftimer() {
  11827. #ifdef GTODONEARG            /* Account for Mot's definition */
  11828.     (VOID) gettimeofday(&tzero);
  11829. #else
  11830.     (VOID) gettimeofday(&tzero, (struct timezone *)0);
  11831. #endif /* GTODONEARG */
  11832. }
  11833.  
  11834. CKFLOAT
  11835. gftimer() {
  11836.     struct timeval tnow, tdelta;
  11837.     CKFLOAT s;
  11838. #ifdef DEBUG
  11839.     char fpbuf[64];
  11840. #endif /* DEBUG */
  11841. #ifdef GTODONEARG            /* Account for Mot's definition */
  11842.     (VOID) gettimeofday(&tnow);
  11843. #else
  11844.     (VOID) gettimeofday(&tnow, (struct timezone *)0);
  11845. #endif /* GTODONEARG */
  11846.  
  11847.     tdelta.tv_sec = tnow.tv_sec - tzero.tv_sec;
  11848.     tdelta.tv_usec = tnow.tv_usec - tzero.tv_usec;
  11849.  
  11850.     if (tdelta.tv_usec < 0) {
  11851.     tdelta.tv_sec--;
  11852.     tdelta.tv_usec += 1000000;
  11853.     }
  11854.     s = (CKFLOAT) tdelta.tv_sec + ((CKFLOAT) tdelta.tv_usec / 1000000.0);
  11855.     if (s < GFMINTIME)
  11856.       s = GFMINTIME;
  11857. #ifdef DEBUG
  11858.     if (deblog) {
  11859.     sprintf(fpbuf,"%f",s);
  11860.     debug(F110,"gftimer",fpbuf,0);
  11861.     }
  11862. #endif /* DEBUG */
  11863.     return(s);
  11864. }
  11865. #endif /* GFTIMER */
  11866.  
  11867. /*  Z T I M E  --  Return asctime()-format date/time string  */
  11868. /*
  11869.   NOTE: as a side effect of calling this routine, we can also set the
  11870.   following two variables, giving the micro- and milliseconds (fractions of
  11871.   seconds) of the clock time.  Currently this is done only in BSD-based builds
  11872.   that use gettimeofday().  When these variables are not filled in, they are
  11873.   left with a value of -1L.
  11874. */
  11875. static char asctmbuf[64];
  11876.  
  11877. VOID
  11878. ztime(s) char **s; {
  11879.  
  11880. #ifdef GFTIMER
  11881. /*
  11882.   The gettimeofday() method, which also sets ztmsec and ztusec, works for
  11883.   all GFTIMER builds.  NOTE: ztmsec and ztusec are defined in ckcmai.c,
  11884.   and extern declarations for them are in ckcdeb.h; thus they are
  11885.   declared in this file by inclusion of ckcdeb.h.
  11886. */
  11887.     char *asctime();
  11888.     struct tm *localtime();
  11889.     struct tm *tp;
  11890.     ztmsec = -1L;
  11891.     ztusec = -1L;
  11892.  
  11893.     if (!s)
  11894.       debug(F100,"ztime s==NULL","",0);
  11895.  
  11896. #ifdef GTODONEARG
  11897.     /* No 2nd arg in Motorola SV88 and some others */
  11898.     if (gettimeofday(&tv) > -1)
  11899. #else
  11900. #ifndef COHERENT
  11901. #ifdef PTX
  11902.     if (gettimeofday(&tv,NULL) > -1)
  11903. #else
  11904. #ifdef NOTIMEZONE
  11905.     if (gettimeofday(&tv, NULL) > -1)    /* wonder what this does... */
  11906. #else
  11907.     if (gettimeofday(&tv, &tz) > -1)
  11908. #endif /* NOTIMEZONE */
  11909. #endif /* PTX */
  11910. #endif /* COHERENT */
  11911. #endif /* GTODONEARG */
  11912.       {                    /* Fill in tm struct */
  11913.     ztusec = tv.tv_usec;        /* Microseconds */
  11914.     ztmsec = ztusec / 1000L;    /* Milliseconds */
  11915. #ifdef HPUX9
  11916.     {
  11917.         time_t zz;
  11918.         zz = tv.tv_sec;
  11919.         tp = localtime(&zz);    /* Convert to local time */
  11920.     }
  11921. #else
  11922. #ifdef HPUX1000
  11923.     {
  11924.         time_t zz;
  11925.         zz = tv.tv_sec;
  11926.         tp = localtime(&zz);
  11927.     }
  11928. #else
  11929. #ifdef LINUX
  11930.     {   /* avoid unaligned access trap on 64-bit platforms */
  11931.         time_t zz;
  11932.         zz = tv.tv_sec;
  11933.         tp = localtime(&zz);
  11934.     }
  11935. #else
  11936. #ifdef MACOSX
  11937.     tp = localtime((time_t *)&tv.tv_sec); /* Convert to local time */
  11938. #else
  11939.     tp = localtime(&tv.tv_sec);
  11940. #endif /* MACOSX */
  11941. #endif /* LINUX */
  11942. #endif /* HPUX1000 */
  11943. #endif /* HPUX9 */
  11944.     if (s) {
  11945.         char * s2;
  11946.         s2 = asctime(tp);        /* Convert result to ASCII string */
  11947.         asctmbuf[0] = '\0';
  11948.         if (s2) ckstrncpy(asctmbuf,s2,64);
  11949.         *s = asctmbuf;
  11950.         debug(F111,"ztime GFTIMER gettimeofday",*s,ztusec);
  11951.     }
  11952.     }
  11953. #else  /* Not GFTIMER */
  11954.  
  11955. #undef ZTIMEV7                /* Which systems need to use */
  11956. #ifdef COHERENT                /* old UNIX Version 7 way... */
  11957. #define ZTIMEV7
  11958. #endif /* COHERENT */
  11959. #ifdef TOWER1
  11960. #define ZTIMEV7
  11961. #endif /* TOWER1 */
  11962. #ifdef ANYBSD
  11963. #ifndef BSD42
  11964. #define ZTIMEV7
  11965. #endif /* BSD42 */
  11966. #endif /* ANYBSD */
  11967. #ifdef V7
  11968. #ifndef MINIX
  11969. #define ZTIMEV7
  11970. #endif /* MINIX */
  11971. #endif /* V7 */
  11972. #ifdef POSIX
  11973. #define ZTIMEV7
  11974. #endif /* POSIX */
  11975.  
  11976. #ifdef HPUX1020
  11977. /*
  11978.   Prototypes are in <time.h>, included above.
  11979. */
  11980.     time_t clock_storage;
  11981.     clock_storage = time((void *) 0);
  11982.     if (s) {
  11983.     *s = ctime(&clock_storage);
  11984.     debug(F110,"ztime: HPUX 10.20",*s,0);
  11985.     }
  11986. #else
  11987. #ifdef ATTSV                /* AT&T way */
  11988. /*  extern long time(); */        /* Theoretically these should */
  11989.     char *ctime();            /* already been dcl'd in <time.h> */
  11990.     time_t clock_storage;
  11991.     clock_storage = time(
  11992. #ifdef IRIX60
  11993.              (time_t *)
  11994. #else
  11995. #ifdef BSD44
  11996.              (time_t *)
  11997. #else
  11998.              (long *)
  11999. #endif /* BSD44 */
  12000. #endif /* IRIX60 */
  12001.              0 );
  12002.     if (s) {
  12003.     *s = ctime( &clock_storage );
  12004.     debug(F110,"ztime: ATTSV",*s,0);
  12005.     }
  12006. #else
  12007. #ifdef PROVX1                /* Venix 1.0 way */
  12008.     int utime[2];
  12009.     time(utime);
  12010.     if (s) {
  12011.     *s = ctime(utime);
  12012.     debug(F110,"ztime: PROVX1",*s,0);
  12013.     }
  12014. #else
  12015. #ifdef BSD42                /* 4.2BSD way */
  12016.     char *asctime();
  12017.     struct tm *localtime();
  12018.     struct tm *tp;
  12019.     gettimeofday(&tv, &tz);
  12020.     ztusec = tv.tv_usec;
  12021.     ztmsec = tv.tv_usec / 1000L;
  12022.     tp = localtime(&tv.tv_sec);
  12023.     if (s) {
  12024.     *s = asctime(tp);
  12025.     debug(F111,"ztime: BSD42",*s,ztusec);
  12026.     }
  12027. #else
  12028. #ifdef MINIX                /* MINIX way */
  12029. #ifdef COMMENT
  12030.     extern long time();            /* Already got these from <time.h> */
  12031.     extern char *ctime();
  12032. #endif /* COMMENT */
  12033.     time_t utime[2];
  12034.     time(utime);
  12035.     if (s) {
  12036.     *s = ctime(utime);
  12037.     debug(F110,"ztime: MINIX",*s,0);
  12038.     }
  12039. #else
  12040. #ifdef ZTIMEV7                /* The regular way */
  12041.     char *asctime();
  12042.     struct tm *localtime();
  12043.     struct tm *tp;
  12044.     long xclock;            /* or unsigned long for BeBox? */
  12045.     time(&xclock);
  12046.     tp = localtime(&xclock);
  12047.     if (s) {
  12048.     *s = asctime(tp);
  12049.     debug(F110,"ztime: ZTIMEV7",*s,0);
  12050.     }
  12051. #else                    /* Catch-all for others... */
  12052.     if (s) {
  12053.     *s = "Day Mon 00 00:00:00 0000\n"; /* Dummy in asctime() format */
  12054.     debug(F110,"ztime: catch-all",*s,0);
  12055.     }
  12056. #endif /* ZTIMEV7 */
  12057. #endif /* MINIX */
  12058. #endif /* BSD42 */
  12059. #endif /* PROVX1 */
  12060. #endif /* ATTSV */
  12061. #endif /* HPUX1020 */
  12062. #endif /* GFTIMER */
  12063. }
  12064.  
  12065. /*  C O N G M  --  Get console terminal modes.  */
  12066.  
  12067. /*
  12068.   Saves initial console mode, and establishes variables for switching
  12069.   between current (presumably normal) mode and other modes.
  12070.   Should be called when program starts, but only after establishing
  12071.   whether program is in the foreground or background.
  12072.   Returns 1 if it got the modes OK, 0 if it did nothing, -1 on error.
  12073. */
  12074. int
  12075. congm() {
  12076.     int fd;
  12077.     if (backgrd || !isatty(0)) {    /* If in background. */
  12078.     cgmf = -1;            /* Don't bother, modes are garbage. */
  12079.     return(-1);
  12080.     }
  12081.     if (cgmf > 0) return(0);        /* Already did this. */
  12082.     debug(F100,"congm getting modes","",0); /* Need to do it. */
  12083. #ifdef aegis
  12084.     ios_$inq_type_uid(ios_$stdin, conuid, st);
  12085.     if (st.all != status_$ok) {
  12086.     fprintf(stderr, "problem getting stdin objtype: ");
  12087.     error_$print(st);
  12088.     }
  12089.     concrp = (conuid == mbx_$uid);
  12090.     conbufn = 0;
  12091. #endif /* aegis */
  12092.  
  12093. #ifndef BEBOX
  12094.     if ((fd = open(CTTNAM,2)) < 0) {    /* Open controlling terminal */
  12095. #ifdef COMMENT
  12096.     fprintf(stderr,"Error opening %s\n", CTTNAM);
  12097.     perror("congm");
  12098.     return(-1);
  12099. #else
  12100.     fd = 0;
  12101. #endif /* COMMENT */
  12102.     }
  12103. #else
  12104.     fd = 0;
  12105. #endif /* !BEBOX */
  12106. #ifdef BSD44ORPOSIX
  12107.     if (tcgetattr(fd,&ccold) < 0) return(-1);
  12108.     if (tcgetattr(fd,&cccbrk) < 0) return(-1);
  12109.     if (tcgetattr(fd,&ccraw) < 0) return(-1);
  12110. #else
  12111. #ifdef ATTSV
  12112.     if (ioctl(fd,TCGETA,&ccold)  < 0) return(-1);
  12113.     if (ioctl(fd,TCGETA,&cccbrk) < 0) return(-1);
  12114.     if (ioctl(fd,TCGETA,&ccraw)  < 0) return(-1);
  12115. #ifdef VXVE
  12116.     cccbrk.c_line = 0;            /* STTY line 0 for CDC VX/VE */
  12117.     if (ioctl(fd,TCSETA,&cccbrk) < 0) return(-1);
  12118.     ccraw.c_line = 0;            /* STTY line 0 for CDC VX/VE */
  12119.     if (ioctl(fd,TCSETA,&ccraw) < 0) return(-1);
  12120. #endif /* VXVE */
  12121. #else
  12122. #ifdef BELLV10
  12123.     if (ioctl(fd,TIOCGETP,&ccold) < 0) return(-1);
  12124.     if (ioctl(fd,TIOCGETP,&cccbrk) < 0) return(-1);
  12125.     if (ioctl(fd,TIOCGETP,&ccraw) < 0) return(-1);
  12126.     debug(F101,"cccbrk.sg_flags orig","", cccbrk.sg_flags);
  12127. #else
  12128.     if (gtty(fd,&ccold) < 0) return(-1);
  12129.     if (gtty(fd,&cccbrk) < 0) return(-1);
  12130.     if (gtty(fd,&ccraw) < 0) return(-1);
  12131. #endif /* BELLV10 */
  12132. #endif /* ATTSV */
  12133. #endif /* BSD44ORPOSIX */
  12134. #ifdef sony_news            /* Sony NEWS */
  12135.     if (ioctl(fd,TIOCKGET,&km_con) < 0) { /* Get console Kanji mode */
  12136.     perror("congm error getting Kanji mode");
  12137.     debug(F101,"congm error getting Kanji mode","",0);
  12138.     km_con = -1;            /* Make sure this stays undefined. */
  12139.     return(-1);
  12140.     }
  12141. #endif /* sony_news */
  12142.     if (fd > 0)
  12143.       close(fd);
  12144.     cgmf = 1;                /* Flag that we got them. */
  12145.     return(1);
  12146. }
  12147.  
  12148.  
  12149. static VOID
  12150. congetbuf(x) int x; {
  12151.     int n;
  12152.     n = CONBUFSIZ - (conbufp - conbuf);    /* How much room left in buffer? */
  12153.     if (x > n) {
  12154.     debug(F101,"congetbuf char loss","",x-n);
  12155.     x = n;
  12156.     }
  12157.     x = read(0,conbufp,x);
  12158.     conbufn += x;
  12159.     debug(F111,"congetbuf readahead",conbuf,x);
  12160. }
  12161.  
  12162.  
  12163. /*  C O N C B --  Put console in cbreak mode.  */
  12164.  
  12165. /*  Returns 0 if ok, -1 if not  */
  12166.  
  12167. int
  12168. #ifdef CK_ANSIC
  12169. concb(char esc)
  12170. #else
  12171. concb(esc) char esc;
  12172. #endif /* CK_ANSIC */
  12173. /* concb */ {
  12174.     int x, y = 0;
  12175.     debug(F101,"concb constate","",constate);
  12176.     debug(F101,"concb cgmf","",cgmf);
  12177.     debug(F101,"concb backgrd","",backgrd);
  12178.  
  12179.     if (constate == CON_CB)
  12180.       return(0);
  12181.  
  12182.     if (cgmf < 1)            /* Did we get console modes yet? */
  12183.       if (!backgrd)            /* No, in background? */
  12184.     congm();            /* No, try to get them now. */
  12185.     if (cgmf < 1)            /* Still don't have them? */
  12186.       return(0);            /* Give up. */
  12187.     debug(F101,"concb ttyfd","",ttyfd);
  12188.     debug(F101,"concb ttfdflg","",ttfdflg);
  12189. #ifdef COMMENT
  12190.     /* This breaks returning to prompt after protocol with "-l 0" */
  12191.     /* Commented out July 1998 */
  12192.     if (ttfdflg && ttyfd >= 0 && ttyfd < 3)
  12193.       return(0);
  12194. #endif /* COMMENT */
  12195.     x = isatty(0);
  12196.     debug(F101,"concb isatty","",x);
  12197.     if (!x) return(0);            /* Only when running on real ttys */
  12198.     debug(F101,"concb xsuspend","",xsuspend);
  12199.     if (backgrd)            /* Do nothing if in background. */
  12200.       return(0);
  12201.     escchr = esc;                       /* Make this available to other fns */
  12202.     ckxech = 1;                         /* Program can echo characters */
  12203. #ifdef aegis
  12204.     conbufn = 0;
  12205.     if (concrp) return(write(1, "\035\002", 2));
  12206.     if (conuid == input_pad_$uid) {pad_$raw(ios_$stdin, st); return(0);}
  12207. #endif /* aegis */
  12208.  
  12209. #ifdef COHERENT
  12210. #define SVORPOSIX
  12211. #endif /* COHERENT */
  12212.  
  12213. #ifdef Plan9
  12214.     x = p9concb();
  12215. #else
  12216. #ifndef SVORPOSIX            /* BSD, V7, etc */
  12217.     debug(F101,"cccbrk.sg_flags concb 1","", cccbrk.sg_flags);
  12218.     debug(F101,"concb stty CBREAK","",0);
  12219.     cccbrk.sg_flags |= (CBREAK|CRMOD);    /* Set to character wakeup, */
  12220.     cccbrk.sg_flags &= ~ECHO;           /* no echo. */
  12221.     debug(F101,"cccbrk.sg_flags concb 2","", cccbrk.sg_flags);
  12222.     errno = 0;
  12223. /*
  12224.   BSD stty() clears the console buffer.  So if anything is waiting in it,
  12225.   we have to read it now to avoid losing it.
  12226. */
  12227.     x = conchk();
  12228.     if (x > 0)
  12229.       congetbuf(x);
  12230.  
  12231. #ifdef BELLV10
  12232.     x = ioctl(0,TIOCSETP,&cccbrk);
  12233. #else
  12234.     x = stty(0,&cccbrk);
  12235.     debug(F101,"cccbrk.sg_flags concb x","", x);
  12236. #endif /* BELLV10 */
  12237. #else                    /* Sys V and POSIX */
  12238. #ifndef OXOS
  12239.     debug(F101,"concb cccbrk.c_flag","",cccbrk.c_lflag);
  12240. #ifdef QNX
  12241.     /* Don't mess with IEXTEN */
  12242.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  12243. #else
  12244. #ifdef COHERENT
  12245.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  12246. #else
  12247.     cccbrk.c_lflag &= ~(ICANON|ECHO|IEXTEN);
  12248. #endif /* COHERENT */
  12249. #endif /* QNX */
  12250.     cccbrk.c_lflag |= ISIG;        /* Allow signals in command mode. */
  12251.     cccbrk.c_iflag |= IGNBRK;        /* But ignore BREAK signal */
  12252.     cccbrk.c_iflag &= ~BRKINT;
  12253.  
  12254. #else /* OXOS */
  12255.     debug(F100,"concb OXOS is defined","",0);
  12256.     cccbrk.c_lflag &= ~(ICANON|ECHO);
  12257.     cccbrk.c_cc[VDISCARD] = cccbrk.c_cc[VLNEXT] = CDISABLE;
  12258. #endif /* OXOS */
  12259. #ifdef COMMENT
  12260. /*
  12261.   Believe it or not, in SCO UNIX, VSUSP is greater than NCC, and so this
  12262.   array reference is out of bounds.  It's only a debug() call so who needs it.
  12263. */
  12264. #ifdef VSUSP
  12265.     debug(F101,"concb c_cc[VSUSP]","",cccbrk.c_cc[VSUSP]);
  12266. #endif /* VSUSP */
  12267. #endif /* COMMENT */
  12268. #ifndef VINTR
  12269.     debug(F101,"concb c_cc[0]","",cccbrk.c_cc[0]);
  12270.     cccbrk.c_cc[0] = 003;               /* Interrupt char is Control-C */
  12271. #else
  12272.     debug(F101,"concb c_cc[VINTR]","",cccbrk.c_cc[0]);
  12273.     cccbrk.c_cc[VINTR] = 003;
  12274. #endif /* VINTR */
  12275. #ifndef VQUIT
  12276.     cccbrk.c_cc[1] = escchr;            /* escape during packet modes */
  12277. #else
  12278.     cccbrk.c_cc[VQUIT] = escchr;
  12279. #endif /* VQUIT */
  12280. #ifndef VEOF
  12281.     cccbrk.c_cc[4] = 1;
  12282. #else
  12283. #ifndef OXOS
  12284. #ifdef VMIN
  12285.     cccbrk.c_cc[VMIN] = 1;
  12286. #endif /* VMIN */
  12287. #else /* OXOS */
  12288.     cccbrk.c_min = 1;
  12289. #endif /* OXOS */
  12290. #endif /* VEOF */
  12291. #ifdef ZILOG
  12292.     cccbrk.c_cc[5] = 0;
  12293. #else
  12294. #ifndef VEOL
  12295.     cccbrk.c_cc[5] = 1;
  12296. #else
  12297. #ifndef OXOS
  12298. #ifdef VTIME
  12299.     cccbrk.c_cc[VTIME] = 1;
  12300. #endif /* VTIME */
  12301. #else /* OXOS */
  12302.     cccbrk.c_time = 1;
  12303. #endif /* OXOS */
  12304. #endif /* VEOL */
  12305. #endif /* ZILOG */
  12306.     errno = 0;
  12307. #ifdef BSD44ORPOSIX            /* Set new modes */
  12308.     x = tcsetattr(0,TCSADRAIN,&cccbrk);
  12309. #else /* ATTSV */                  /* or the POSIX way */
  12310.     x = ioctl(0,TCSETAW,&cccbrk);    /* the Sys V way */
  12311. #endif /* BSD44ORPOSIX */
  12312. #endif /* SVORPOSIX */
  12313.  
  12314. #ifdef COHERENT
  12315. #undef SVORPOSIX
  12316. #endif /* COHERENT */
  12317.  
  12318.     debug(F101,"concb x","",x);
  12319.     debug(F101,"concb errno","",errno);
  12320.  
  12321. #ifdef  V7
  12322. #ifndef MINIX
  12323.     if (kmem[CON] < 0) {
  12324.         qaddr[CON] = initrawq(0);
  12325.         if((kmem[CON] = open("/dev/kmem", 0)) < 0) {
  12326.             fprintf(stderr, "Can't read /dev/kmem in concb.\n");
  12327.             perror("/dev/kmem");
  12328.             exit(1);
  12329.         }
  12330.     }
  12331. #endif /* MINIX */
  12332. #endif /* V7 */
  12333. #endif /* Plan9 */
  12334.  
  12335.     if (x > -1)
  12336.       constate = CON_CB;
  12337.  
  12338.     debug(F101,"concb returns","",x);
  12339.     return(x);
  12340. }
  12341.  
  12342. /*  C O N B I N  --  Put console in binary mode  */
  12343.  
  12344. /*  Returns 0 if ok, -1 if not  */
  12345.  
  12346. int
  12347. #ifdef CK_ANSIC
  12348. conbin(char esc)
  12349. #else
  12350. conbin(esc) char esc;
  12351. #endif /* CK_ANSIC */
  12352. /* conbin */  {
  12353.  
  12354.     int x;
  12355.  
  12356.     debug(F101,"conbin constate","",constate);
  12357.  
  12358.     if (constate == CON_BIN)
  12359.       return(0);
  12360.  
  12361.     if (!isatty(0)) return(0);          /* only for real ttys */
  12362.     congm();                /* Get modes if necessary. */
  12363.     debug(F100,"conbin","",0);
  12364.     escchr = esc;                       /* Make this available to other fns */
  12365.     ckxech = 1;                         /* Program can echo characters */
  12366. #ifdef aegis
  12367.     conbufn = 0;
  12368.     if (concrp) return(write(1, "\035\002", 2));
  12369.     if (conuid == input_pad_$uid) {
  12370.     pad_$raw(ios_$stdin, st);
  12371.     return(0);
  12372.       }
  12373. #endif /* aegis */
  12374.  
  12375. #ifdef COHERENT
  12376. #define SVORPOSIX
  12377. #endif /* COHERENT */
  12378.  
  12379. #ifdef Plan9
  12380.     return p9conbin();
  12381. #else
  12382. #ifdef SVORPOSIX
  12383. #ifndef OXOS
  12384. #ifdef QNX
  12385.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  12386. #else
  12387. #ifdef COHERENT
  12388.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  12389. #else
  12390.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO|IEXTEN);
  12391. #endif /* COHERENT */
  12392. #endif /* QNX */
  12393. #else /* OXOS */
  12394.     ccraw.c_lflag &= ~(ISIG|ICANON|ECHO);
  12395.     ccraw.c_cc[VDISCARD] = ccraw.c_cc[VLNEXT] = CDISABLE;
  12396. #endif /* OXOS */
  12397.     ccraw.c_iflag |= IGNPAR;
  12398. /*
  12399.   Note that for terminal sessions we disable Xon/Xoff flow control to allow
  12400.   the passage ^Q and ^S as data characters for EMACS, and to allow XMODEM
  12401.   transfers to work when C-Kermit is in the middle, etc.  Hardware flow
  12402.   control, if in use, is not affected.
  12403. */
  12404. #ifdef ATTSV
  12405. #ifdef BSD44
  12406.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IXON|IXANY|IXOFF
  12407.                         |INPCK|ISTRIP);
  12408. #else
  12409.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IUCLC|IXON|IXANY|IXOFF
  12410.                         |INPCK|ISTRIP);
  12411. #endif /* BSD44 */
  12412. #else /* POSIX */
  12413.     ccraw.c_iflag &= ~(IGNBRK|INLCR|IGNCR|ICRNL|IXON|IXOFF|INPCK|ISTRIP);
  12414. #endif /* ATTSV */
  12415.     ccraw.c_oflag &= ~OPOST;
  12416. #ifdef COMMENT
  12417. /*
  12418.   WHAT THE HECK WAS THIS FOR?
  12419.   The B9600 setting (obviously) prevents CONNECT from working at any
  12420.   speed other than 9600 when you are logged in to the 7300 on a serial
  12421.   line.  Maybe some of the other flags are necessary -- if so, put back
  12422.   the ones that are needed.  This code is supposed to work the same, no
  12423.   matter whether you are logged in to the 7300 on the real console device,
  12424.   or through a serial port.
  12425. */
  12426. #ifdef ATT7300
  12427.     ccraw.c_cflag = CLOCAL | B9600 | CS8 | CREAD | HUPCL;
  12428. #endif /* ATT7300 */
  12429. #endif /* COMMENT */
  12430.  
  12431. /*** Kermit used to put the console in 8-bit raw mode, but some users have
  12432.  *** pointed out that this should not be done, since some sites actually
  12433.  *** use terminals with parity settings on their Unix systems, and if we
  12434.  *** override the current settings and stop doing parity, then their terminals
  12435.  *** will display blotches for characters whose parity is wrong.  Therefore,
  12436.  *** the following two lines are commented out (Larry Afrin, Clemson U):
  12437.  ***
  12438.  ***   ccraw.c_cflag &= ~(PARENB|CSIZE);
  12439.  ***   ccraw.c_cflag |= (CS8|CREAD);
  12440.  ***
  12441.  *** Sys III/V sites that have trouble with this can restore these lines.
  12442.  ***/
  12443. #ifndef VINTR
  12444.     ccraw.c_cc[0] = 003;        /* Interrupt char is Ctrl-C */
  12445. #else
  12446.     ccraw.c_cc[VINTR] = 003;
  12447. #endif /* VINTR */
  12448. #ifndef VQUIT
  12449.     ccraw.c_cc[1] = escchr;        /* Escape during packet mode */
  12450. #else
  12451.     ccraw.c_cc[VQUIT] = escchr;
  12452. #endif /* VQUIT */
  12453. #ifndef VEOF
  12454.     ccraw.c_cc[4] = 1;
  12455. #else
  12456. #ifndef OXOS
  12457. #ifdef VMIN
  12458.     ccraw.c_cc[VMIN] = 1;
  12459. #endif /* VMIN */
  12460. #else /* OXOS */
  12461.     ccraw.c_min = 1;
  12462. #endif /* OXOS */
  12463. #endif /* VEOF */
  12464.  
  12465. #ifdef ZILOG
  12466.     ccraw.c_cc[5] = 0;
  12467. #else
  12468. #ifndef VEOL
  12469.     ccraw.c_cc[5] = 1;
  12470. #else
  12471. #ifndef OXOS
  12472. #ifdef VTIME
  12473.     ccraw.c_cc[VTIME] = 1;
  12474. #endif /* VTIME */
  12475. #else /* OXOS */
  12476.     ccraw.c_time = 1;
  12477. #endif /* OXOS */
  12478. #endif /* VEOL */
  12479. #endif /* ZILOG */
  12480.  
  12481. #ifdef BSD44ORPOSIX
  12482.     x = tcsetattr(0,TCSADRAIN,&ccraw);    /* Set new modes. */
  12483. #else
  12484.     x = ioctl(0,TCSETAW,&ccraw);
  12485. #endif /* BSD44ORPOSIX */
  12486. #else /* Berkeley, etc. */
  12487.     x = conchk();            /* Because stty() is destructive */
  12488.     if (x > 0)
  12489.       congetbuf(x);
  12490.     ccraw.sg_flags |= (RAW|TANDEM);     /* Set rawmode, XON/XOFF (ha) */
  12491.     ccraw.sg_flags &= ~(ECHO|CRMOD);    /* Set char wakeup, no echo */
  12492. #ifdef BELLV10
  12493.     x = ioctl(0,TIOCSETP,&ccraw);
  12494. #else
  12495.     x = stty(0,&ccraw);
  12496. #endif /* BELLV10 */
  12497. #endif /* SVORPOSIX */
  12498. #endif /* Plan9 */
  12499.  
  12500.     if (x > -1)
  12501.       constate = CON_BIN;
  12502.  
  12503.     debug(F101,"conbin returns","",x);
  12504.     return(x);
  12505.  
  12506. #ifdef COHERENT
  12507. #undef SVORPOSIX
  12508. #endif /* COHERENT */
  12509.  
  12510. }
  12511.  
  12512.  
  12513. /*  C O N R E S  --  Restore the console terminal  */
  12514.  
  12515. int
  12516. conres() {
  12517.     int x;
  12518.     debug(F101,"conres cgmf","",cgmf);
  12519.     debug(F101,"conres constate","",constate);
  12520.  
  12521.     if (cgmf < 1)            /* Do nothing if modes unchanged */
  12522.       return(0);
  12523.     if (constate == CON_RES)
  12524.       return(0);
  12525.  
  12526.     if (!isatty(0)) return(0);          /* only for real ttys */
  12527.     debug(F100,"conres isatty ok","",0);
  12528.     ckxech = 0;                         /* System should echo chars */
  12529.  
  12530. #ifdef aegis
  12531.     conbufn = 0;
  12532.     if (concrp) return(write(1, "\035\001", 2));
  12533.     if (conuid == input_pad_$uid) {
  12534.     pad_$cooked(ios_$stdin, st);
  12535.     constate = CON_RES;
  12536.     return(0);
  12537.     }
  12538. #endif /* aegis */
  12539.  
  12540. #ifdef Plan9
  12541.     p9conres();
  12542. #else
  12543. #ifdef BSD44ORPOSIX
  12544.     debug(F100,"conres restoring tcsetattr","",0);
  12545.     x = tcsetattr(0,TCSADRAIN,&ccold);
  12546. #else
  12547. #ifdef ATTSV
  12548.     debug(F100,"conres restoring ioctl","",0);
  12549.     x = ioctl(0,TCSETAW,&ccold);
  12550. #else /* BSD, V7, and friends */
  12551. #ifdef sony_news            /* Sony NEWS */
  12552.     if (km_con != -1)
  12553.       ioctl(0,TIOCKSET,&km_con);    /* Restore console Kanji mode */
  12554. #endif /* sony_news */
  12555.     msleep(100);
  12556.     debug(F100,"conres restoring stty","",0);
  12557.     x = conchk();            /* Because stty() is destructive */
  12558.     if (x > 0)
  12559.       congetbuf(x);
  12560. #ifdef BELLV10
  12561.     x = ioctl(0,TIOCSETP,&ccold);
  12562. #else
  12563.     x = stty(0,&ccold);
  12564. #endif /* BELLV10 */
  12565. #endif /* ATTSV */
  12566. #endif /* BSD44ORPOSIX */
  12567. #endif /* Plan9 */
  12568.     if (x > -1)
  12569.       constate = CON_RES;
  12570.  
  12571.     debug(F101,"conres returns","",x);
  12572.     return(x);
  12573. }
  12574.  
  12575. /*  C O N O C  --  Output a character to the console terminal  */
  12576.  
  12577. int
  12578. #ifdef CK_ANSIC
  12579. conoc(char c)
  12580. #else
  12581. conoc(c) char c;
  12582. #endif /* CK_ANSIC */
  12583. /* conoc */ {
  12584.  
  12585. #ifdef IKSD
  12586.     if (inserver && !local)
  12587.       return(ttoc(c));
  12588.  
  12589. #ifdef CK_ENCRYPTION
  12590.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  12591.         ck_tn_encrypt(&c,1);
  12592. #endif /* CK_ENCRYPTION */
  12593. #endif /* IKSD */
  12594.  
  12595. #ifdef Plan9
  12596.     return conwrite(&c,1);
  12597. #else
  12598.     return(write(1,&c,1));
  12599. #endif /* Plan9 */
  12600. }
  12601.  
  12602. /*  C O N X O  --  Write x characters to the console terminal  */
  12603.  
  12604. int
  12605. conxo(x,s) int x; char *s; {
  12606.  
  12607. #ifdef IKSD
  12608.     if (inserver && !local)
  12609.       return(ttol((CHAR *)s,x));
  12610.  
  12611. #ifdef CK_ENCRYPTION
  12612.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  12613.         ck_tn_encrypt(s,x);
  12614. #endif /* CK_ENCRYPTION */
  12615. #endif /* IKSD */
  12616.  
  12617. #ifdef Plan9
  12618.     return(conwrite(s,x));
  12619. #else
  12620.     return(write(1,s,x));
  12621. #endif /* Plan9 */
  12622. }
  12623.  
  12624. /*  C O N O L  --  Write a line to the console terminal  */
  12625.  
  12626. int
  12627. conol(s) char *s; {
  12628.     int len;
  12629.     if (!s) s = "";            /* Always do this! */
  12630.     len = strlen(s);
  12631.     if (len == 0)
  12632.       return(0);
  12633.  
  12634. #ifdef IKSD
  12635.     if (inserver && !local)
  12636.       return(ttol((CHAR *)s,len));
  12637.  
  12638. #ifdef CK_ENCRYPTION
  12639.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION)) {
  12640.     if (nxpacket < len) {
  12641.         if (xpacket) {
  12642.         free(xpacket);
  12643.         xpacket = NULL;
  12644.         nxpacket = 0;
  12645.         }
  12646.         len = len > 10240 ? len : 10240;
  12647.         xpacket = (CHAR *)malloc(len);
  12648.         if (!xpacket) {
  12649.         fprintf(stderr,"ttol malloc failure\n");
  12650.         return(-1);
  12651.         } else
  12652.           nxpacket = len;
  12653.     }
  12654.     memcpy(xpacket,s,len);
  12655.     s = (char *)xpacket;
  12656.     ck_tn_encrypt(s,len);
  12657.     }
  12658. #endif /* CK_ENCRYPTION */
  12659. #endif /* IKSD */
  12660.  
  12661. #ifdef Plan9
  12662.     return(conwrite(s,len));
  12663. #else
  12664.     return(write(1,s,len));
  12665. #endif /* Plan9 */
  12666. }
  12667.  
  12668. /*  C O N O L A  --  Write an array of lines to the console terminal */
  12669.  
  12670. int
  12671. conola(s) char *s[]; {
  12672.     char * p;
  12673.     int i, x;
  12674.  
  12675.  
  12676.     if (!s) return(0);
  12677.     for (i = 0; ; i++) {
  12678.     p = s[i];
  12679.     if (!p) p = "";            /* Let's not dump core shall we? */
  12680.     if (!*p)
  12681.       break;
  12682. #ifdef IKSD
  12683.     if (inserver && !local)
  12684.       x = ttol((CHAR *)p,(int)strlen(p));
  12685.     else
  12686. #endif /* IKSD */
  12687.       x = conol(p);
  12688.     if (x < 0)
  12689.       return(-1);
  12690.     }
  12691.     return(0);
  12692. }
  12693.  
  12694. /*  C O N O L L  --  Output a string followed by CRLF  */
  12695.  
  12696. int
  12697. conoll(s) char *s; {
  12698.     CHAR buf[3];
  12699.     buf[0] = '\r';
  12700.     buf[1] = '\n';
  12701.     buf[2] = '\0';
  12702.     if (!s) s = "";
  12703.  
  12704. #ifdef IKSD
  12705.     if (inserver && !local) {
  12706.     if (*s) ttol((CHAR *)s,(int)strlen(s));
  12707.     return(ttol(buf,2));
  12708.     }
  12709. #endif /* IKSD */
  12710.  
  12711.     if (*s) conol(s);
  12712. #ifdef IKSD
  12713. #ifdef CK_ENCRYPTION
  12714.     if (inserver && TELOPT_ME(TELOPT_ENCRYPTION))
  12715.       ck_tn_encrypt((char *)buf,2);
  12716. #endif /* CK_ENCRYPTION */
  12717. #endif /* IKSD */
  12718.  
  12719. #ifdef Plan9
  12720.     return(conwrite(buf, 2));
  12721. #else
  12722.     return(write(1,buf,2));
  12723. #endif /* Plan9 */
  12724. }
  12725.  
  12726. /*  C O N C H K  --  Return how many characters available at console  */
  12727. /*
  12728.   We could also use select() here to cover a few more systems that are not
  12729.   covered by any of the following, e.g. HP-UX 9.0x on the model 800.
  12730. */
  12731. int
  12732. conchk() {
  12733.     static int contyp = 0;        /* +1 for isatty, -1 otherwise */
  12734.  
  12735.     if (contyp == 0)            /* This prevents unnecessary */
  12736.       contyp = (isatty(0) ? 1 : -1);    /* duplicated calls to isatty() */
  12737.     debug(F101,"conchk contyp","",contyp);
  12738.     if (backgrd || (contyp < 0))
  12739.       return(0);
  12740.  
  12741. #ifdef aegis
  12742.     if (conbufn > 0) return(conbufn);   /* use old count if nonzero */
  12743.  
  12744.     /* read in more characters */
  12745.     conbufn = ios_$get(ios_$stdin,
  12746.               ios_$cond_opt, conbuf, (long)sizeof(conbuf), st);
  12747.     if (st.all != status_$ok) conbufn = 0;
  12748.     conbufp = conbuf;
  12749.     return(conbufn);
  12750. #else
  12751. #ifdef IKSD
  12752.     if (inserver && !local)
  12753.       return(in_chk(1,ttyfd));
  12754.     else
  12755. #endif /* IKSD */
  12756.       return(in_chk(0,0));
  12757. #endif /* aegis */
  12758. }
  12759.  
  12760. /*  C O N I N C  --  Get a character from the console  */
  12761. /*
  12762.   Call with timo > 0 to do a timed read, timo == 0 to do an untimed blocking
  12763.   read.  Upon success, returns the character.  Upon failure, returns -1.
  12764.   A timed read that does not complete within the timeout period returns -2.
  12765. */
  12766. int
  12767. coninc(timo) int timo; {
  12768.     int n = 0; CHAR ch;
  12769.     int xx;
  12770.  
  12771.     if (conbufn > 0) {            /* If something already buffered */
  12772.     --conbufn;
  12773.     return((unsigned)(*conbufp++ & 0xff));
  12774.     }
  12775.  
  12776.     errno = 0;                /* Clear this */
  12777. #ifdef IKSD
  12778.     if (inserver && !local) {
  12779.     xx = ttinc(timo);
  12780.     if (xx < 0)
  12781.       return(ttinctimo ? -2 : -1);
  12782.     else
  12783.       return(xx);
  12784.     }
  12785. #endif /* IKSD */
  12786.  
  12787. #ifdef aegis                /* Apollo Aegis only... */
  12788.     debug(F101,"coninc timo","",timo);
  12789.     fflush(stdout);
  12790.     if (conchk() > 0) {
  12791.     --conbufn;
  12792.     return((unsigned)(*conbufp++ & 0xff));
  12793.     }
  12794. #endif /* aegis */
  12795.  
  12796. #ifdef TTLEBUF
  12797.     if (
  12798. #ifdef IKSD
  12799.     inserver &&
  12800. #endif /* IKSD */
  12801.     !xlocal
  12802.     ) {
  12803.     if (ttpush >= 0) {
  12804.         debug(F111,"ttinc","ttpush",ttpush);
  12805.         ch = ttpush;
  12806.         ttpush = -1;
  12807.         return(ch);
  12808.     }
  12809.     if (le_data) {
  12810.         if (le_getchar(&ch) > 0) {
  12811.         debug(F111,"ttinc LocalEchoInBuf","ch",ch);
  12812.         return(ch);
  12813.         }
  12814.     }
  12815.     }
  12816. #endif /* TTLEBUF */
  12817.  
  12818.     if (timo <= 0) {            /* Untimed, blocking read. */
  12819.     while (1) {            /* Keep trying till we get one. */
  12820.         n = read(0, &ch, 1);    /* Read a character. */
  12821.         if (n == 0) continue;    /* Shouldn't happen. */
  12822.         if (n > 0) {        /* If read was successful, */
  12823. #ifdef IKSD
  12824. #ifdef CK_ENCRYPTION
  12825.                 debug(F100,"coninc decrypt 1","",0);
  12826.                 if (inserver && !local && TELOPT_U(TELOPT_ENCRYPTION))
  12827.           ck_tn_decrypt((char *)&ch,1);
  12828. #endif /* CK_ENCRYPTION */
  12829. #endif /* IKSD */
  12830.         return((unsigned)(ch & 0xff)); /* return the character. */
  12831.             }
  12832.  
  12833. /* Come here if read() returned an error. */
  12834.  
  12835.         debug(F101, "coninc(0) errno","",errno); /* Log the error. */
  12836. #ifndef OXOS
  12837. #ifdef SVORPOSIX
  12838. #ifdef CIE                             /* CIE Regulus has no EINTR symbol? */
  12839. #ifndef EINTR
  12840. #define EINTR 4
  12841. #endif /* EINTR */
  12842. #endif /* CIE */
  12843. /*
  12844.   This routine is used for several different purposes.  In CONNECT mode, it is
  12845.   used to do an untimed, blocking read from the keyboard in the lower CONNECT
  12846.   fork.  During local-mode file transfer, it reads a character from the
  12847.   console to interrupt the file transfer (like A for a status report, X to
  12848.   cancel a file, etc).  Obviously, we don't want the reads in the latter case
  12849.   to be blocking, or the file transfer would stop until the user typed
  12850.   something.  Unfortunately, System V does not allow the console device input
  12851.   buffer to be sampled nondestructively (e.g. by conchk()), so a kludge is
  12852.   used instead.  During local-mode file transfer, the SIGQUIT signal is armed
  12853.   and trapped by esctrp(), and this routine pretends to have read the quit
  12854.   character from the keyboard normally.  But, kludge or no kludge, the read()
  12855.   issued by this command, under System V only, can fail if a signal -- ANY
  12856.   signal -- is caught while the read is pending.  This can occur not only when
  12857.   the user types the quit character, but also during telnet negotiations, when
  12858.   the lower CONNECT fork signals the upper one about an echoing mode change.
  12859.   When this happens, we have to post the read() again.  This is apparently not
  12860.   a problem in BSD-based UNIX versions.
  12861. */
  12862.         if (errno == EINTR)        /* Read interrupted. */
  12863.           if (conesc)  {        /* If by SIGQUIT, */
  12864.           conesc = 0;        /* the conesc variable is set, */
  12865.           return(escchr);    /* so return the escape character. */
  12866.          } else continue;        /* By other signal, try again. */
  12867. #else
  12868. /*
  12869.   This might be dangerous, but let's do this on non-System V versions too,
  12870.   since at least one SunOS 4.1.2 user complains of immediate disconnections
  12871.   upon first making a TELNET connection.
  12872. */
  12873.         if (errno == EINTR)        /* Read interrupted. */
  12874.           continue;
  12875. #endif /* SVORPOSIX */
  12876. #else /* OXOS */
  12877.         if (errno == EINTR)        /* Read interrupted. */
  12878.           continue;
  12879. #endif /* OXOS */
  12880.         return(-1);            /* Error */
  12881.     }
  12882.     }
  12883. #ifdef DEBUG
  12884.     if (deblog && timo <= 0) {
  12885.     debug(F100,"coninc timeout logic error","",0);
  12886.     timo = 1;
  12887.     }
  12888. #endif /* DEBUG */
  12889.  
  12890. /* Timed read... */
  12891.  
  12892.     saval = signal(SIGALRM,timerh);    /* Set up timeout handler. */
  12893.     xx = alarm(timo);            /* Set the alarm. */
  12894.     debug(F101,"coninc alarm set","",timo);
  12895.     if (
  12896. #ifdef CK_POSIX_SIG
  12897.     sigsetjmp(sjbuf,1)
  12898. #else
  12899.     setjmp(sjbuf)
  12900. #endif /* CK_POSIX_SIG */
  12901.     )                /* The read() timed out. */
  12902.       n = -2;                /* Code for timeout. */
  12903.     else
  12904.       n = read(0, &ch, 1);
  12905.     ttimoff();                /* Turn off timer */
  12906.     if (n > 0) {            /* Got character OK. */
  12907. #ifdef IKSD
  12908. #ifdef CK_ENCRYPTION
  12909.         debug(F100,"coninc decrypt 2","",0);
  12910.         if (inserver && !local && TELOPT_U(TELOPT_ENCRYPTION))
  12911.       ck_tn_decrypt((char *)&ch,1);
  12912. #endif /* CK_ENCRYPTION */
  12913. #endif /* IKSD */
  12914.     return((unsigned)(ch & 0xff));    /* Return it. */
  12915.     }
  12916. /*
  12917.   read() returned an error.  Same deal as above, but without the loop.
  12918. */
  12919.     debug(F101, "coninc(timo) n","",n);
  12920.     debug(F101, "coninc(timo) errno","",errno);
  12921. #ifndef OXOS
  12922. #ifdef SVORPOSIX
  12923.     if (n == -1 && errno == EINTR && conesc != 0) {
  12924.     conesc = 0;
  12925.     return(escchr);            /* User entered escape character. */
  12926.     }
  12927. #endif /* SVORPOSIX */
  12928.     if (n == 0 && errno > 0) {        /* It's an error */
  12929.     return(-1);
  12930.     }
  12931. #endif /* ! OXOS */
  12932.     return(n);
  12933. }
  12934.  
  12935. /*  C O N G K S  --  Console Get Keyboard Scancode  */
  12936.  
  12937. #ifndef congks
  12938. /*
  12939.   This function needs to be filled in with the various system-dependent
  12940.   system calls used by SUNOS, NeXT OS, Xenix, Aviion, etc, to read a full
  12941.   keyboard scan code.  Unfortunately there aren't any.
  12942. */
  12943. int
  12944. congks(timo) int timo; {
  12945.  
  12946. #ifdef IKSD
  12947.     if (inserver && !local)
  12948.       return(ttinc(timo));
  12949. #endif /* IKSD */
  12950.  
  12951.     return(coninc(timo));
  12952. }
  12953. #endif /* congks */
  12954.  
  12955. #ifdef ATT7300
  12956.  
  12957. /*  A T T D I A L  --  Dial up the remote system using internal modem
  12958.  * Purpose: to open and dial a number on the internal modem available on the
  12959.  * ATT7300 UNIX PC.  Written by Joe Doupnik. Superceeds version written by
  12960.  * Richard E. Hill, Dickinson, TX. which employed dial(3c).
  12961.  * Uses information in <sys/phone.h> and our status int attmodem.
  12962.  */
  12963. attdial(ttname,speed,telnbr) char *ttname,*telnbr; long speed; {
  12964.     char *telnum;
  12965.  
  12966.     attmodem &= ~ISMODEM;                       /* modem not in use yet */
  12967.                     /* Ensure O_NDELAY is set, else i/o traffic hangs */
  12968.                     /* We turn this flag off once the dial is complete */
  12969.     fcntl(ttyfd, F_SETFL, fcntl(ttyfd, F_GETFL, 0) | O_NDELAY);
  12970.  
  12971.     /* Condition line, check availability & DATA mode, turn on speaker */
  12972.     if (ioctl(ttyfd,PIOCOFFHOOK, &dialer) == -1) {
  12973.         printf("cannot access phone\n");
  12974.         ttclos(0);
  12975.         return (-2);
  12976.     }
  12977.     ioctl(ttyfd,PIOCGETP,&dialer);      /* get phone dialer parameters */
  12978.  
  12979.     if (dialer.c_lineparam & VOICE) {    /* phone must be in DATA mode */
  12980.         printf(" Should not dial with modem in VOICE mode.\n");
  12981.         printf(" Exit Kermit, switch to DATA and retry call.\n");
  12982.         ttclos(0);
  12983.         return (-2);
  12984.     }
  12985. #ifdef ATTTONED                /* Old way, tone dialing only. */
  12986.     dialer.c_lineparam = DATA | DTMF;    /* Dial with tones, */
  12987.     dialer.c_lineparam &= ~PULSE;    /* not with pulses. */
  12988. #else
  12989.     /* Leave current pulse/tone state alone. */
  12990.     /* But what about DATA?  Add it back if you have trouble. */
  12991.     /* sys/phone says you get DATA automatically by opening device RDWR */
  12992. #endif
  12993.     dialer.c_waitdialtone = 5;                  /* wait 5 sec for dialtone */
  12994. #ifdef COMMENT
  12995.     dialer.c_feedback = SPEAKERON|NORMSPK|RINGON;  /* control speaker */
  12996. #else
  12997.     /* sys/phone says RINGON used only for incoming voice calls */
  12998.     dialer.c_feedback &= ~(SOFTSPK|LOUDSPK);
  12999.     dialer.c_feedback |= SPEAKERON|NORMSPK;
  13000. #endif
  13001.     dialer.c_waitflash = 500;                   /* 0.5 sec flash hook */
  13002.     if(ioctl(ttyfd,PIOCSETP,&dialer) == -1) {   /* set phone parameters */
  13003.         printf("Cannot set modem characteristics\n");
  13004.         ttclos(0);
  13005.         return (-2);
  13006.     }
  13007.     ioctl(ttyfd,PIOCRECONN,0);        /* Turns on speaker for pulse */
  13008.  
  13009. #ifdef COMMENT
  13010.     fprintf(stderr,"Phone line status. line_par:%o dialtone_wait:%o \
  13011. line_status:%o feedback:%o\n",
  13012.     dialer.c_lineparam, dialer.c_waitdialtone,
  13013.     dialer.c_linestatus, dialer.c_feedback);
  13014. #endif
  13015.  
  13016.     attmodem |= ISMODEM;                        /* modem is now in-use */
  13017.     sleep(1);
  13018.     for (telnum = telnbr; *telnum != '\0'; telnum++)    /* dial number */
  13019. #ifdef ATTTONED
  13020.       /* Tone dialing only */
  13021.       if (ioctl(ttyfd,PIOCDIAL,telnum) != 0) {
  13022.       perror("Error in dialing");
  13023.       ttclos(0);
  13024.       return(-2);
  13025.       }
  13026. #else /* Allow Pulse or Tone dialing */
  13027.     switch (*telnum) {
  13028.       case 't': case 'T': case '%':    /* Tone dialing requested */
  13029.     dialer.c_lineparam |= DTMF;
  13030.     dialer.c_lineparam &= ~PULSE;
  13031.     if (ioctl(ttyfd,PIOCSETP,&dialer) == -1) {
  13032.         printf("Cannot set modem to tone dialing\n");
  13033.         ttclos(0);
  13034.         return(-2);
  13035.     }
  13036.     break;
  13037.       case 'd': case 'D': case 'p': case 'P': case '^':
  13038.     dialer.c_lineparam |= PULSE;
  13039.     dialer.c_lineparam &= ~DTMF;
  13040.     if (ioctl(ttyfd,PIOCSETP,&dialer) == -1) {
  13041.         printf("Cannot set modem to pulse dialing\n");
  13042.         ttclos(0);
  13043.         return(-2);
  13044.     }
  13045.     break;
  13046.       default:
  13047.         if (ioctl(ttyfd,PIOCDIAL,telnum) != 0) {
  13048.         perror("Dialing error");
  13049.         ttclos(0);
  13050.         return(-2);
  13051.     }
  13052.     break;
  13053.     }
  13054. #endif
  13055.  
  13056.     ioctl(ttyfd,PIOCDIAL,"@");        /* terminator for data call */
  13057.     do {                /* wait for modems to Connect */
  13058.         if (ioctl(ttyfd,PIOCGETP,&dialer) != 0)    { /* get params */
  13059.         perror("Cannot get modems to connect");
  13060.         ttclos(0);
  13061.         return(-2);
  13062.     }
  13063.     } while ((dialer.c_linestatus & MODEMCONNECTED) == 0);
  13064.     /* Turn off O_NDELAY flag now. */
  13065.     fcntl(ttyfd, F_SETFL, fcntl(ttyfd, F_GETFL, 0) & ~O_NDELAY);
  13066.     signal(SIGHUP, sighup);             /* hangup on loss of carrier */
  13067.     return(0);                          /* return success */
  13068. }
  13069.  
  13070. /*
  13071.   Offgetty, ongetty functions. These function get the 'getty(1m)' off
  13072.   and restore it to the indicated line.  Shell's return codes are:
  13073.     0: Can't do it.  Probably a user logged on.
  13074.     1: No need.  No getty on that line.
  13075.     2: Done, you should restore the getty when you're done.
  13076.   DOGETY System(3), however, returns them as 0, 256, 512, respectively.
  13077.   Thanks to Kevin O'Gorman, Anarm Software Systems.
  13078.  
  13079.    getoff.sh looks like:   geton.sh looks like:
  13080.      setgetty $1 0           setgetty $1 1
  13081.      err=$?                  exit $?
  13082.      sleep 2
  13083.      exit $err
  13084. */
  13085.  
  13086. /*  O F F G E T T Y  --  Turn off getty(1m) for the communications tty line
  13087.  * and get status so it can be restarted after the line is hung up.
  13088.  */
  13089. int
  13090. offgetty(ttname) char *ttname; {
  13091.     char temp[30];
  13092.     while (*ttname != '\0') ttname++;       /* seek terminator of path */
  13093.     ttname -= 3;                            /* get last 3 chars of name */
  13094.     sprintf(temp,"/usr/bin/getoff.sh %s",ttname);
  13095.     return(zsyscmd(temp));
  13096. }
  13097.  
  13098. /*  O N G E T T Y  --  Turn on getty(1m) for the communications tty line */
  13099.  
  13100. int
  13101. ongetty(ttname) char *ttname; {
  13102.     char temp[30];
  13103.     while (*ttname != '\0') ttname++;       /* comms tty path name */
  13104.     ttname -= 3;
  13105.     sprintf(temp,"/usr/bin/geton.sh %s",ttname);
  13106.     return(zsyscmd(temp));
  13107. }
  13108. #endif /* ATT7300 */
  13109.  
  13110. /*  T T S C A R R  --  Set ttcarr variable, controlling carrier handling.
  13111.  *
  13112.  *  0 = Off: Always ignore carrier. E.g. you can connect without carrier.
  13113.  *  1 = On: Heed carrier, except during dialing. Carrier loss gives disconnect.
  13114.  *  2 = Auto: For "modem direct": The same as "Off".
  13115.  *            For real modem types: Heed carrier during connect, but ignore
  13116.  *                it anytime else.  Compatible with pre-5A C-Kermit versions.
  13117.  *
  13118.  * As you can see, this setting does not affect dialing, which always ignores
  13119.  * carrier (unless there is some special exception for some modem type).  It
  13120.  * does affect ttopen() if it is set before ttopen() is used.  This setting
  13121.  * takes effect on the next call to ttopen()/ttpkt()/ttvt().  And they are
  13122.  * (or should be) always called before any communications is tried, which
  13123.  * means that, practically speaking, the effect is immediate.
  13124.  *
  13125.  * Of course, nothing of this applies to remote mode (xlocal = 0).
  13126.  *
  13127.  * Someone has yet to uncover how to manipulate the carrier in the BSD
  13128.  * environment (or any non-termio using environment).  Until that time, this
  13129.  * will simply be a no-op for BSD.
  13130.  *
  13131.  * Note that in previous versions, the carrier was most often left unchanged
  13132.  * in ttpkt()/ttvt() unless they were called with FLO_DIAL or FLO_DIAX.  This
  13133.  * has changed.  Now it is controlled by ttcarr in conjunction with these
  13134.  * modes.
  13135.  */
  13136. int
  13137. ttscarr(carrier) int carrier; {
  13138.     ttcarr = carrier;
  13139.     debug(F101, "ttscarr","",ttcarr);
  13140.     return(ttcarr);
  13141. }
  13142.  
  13143. /* C A R R C T L  --  Set tty modes for carrier treatment.
  13144.  *
  13145.  * Sets the appropriate bits in a termio or sgttyb struct for carrier control
  13146.  * (actually, there are no bits in sgttyb for that), or performs any other
  13147.  * operations needed to control this on the current system.  The function does
  13148.  * not do the actual TCSETA or stty, since often we want to set other bits too
  13149.  * first.  Don't call this function when xlocal is 0, or the tty is not opened.
  13150.  *
  13151.  * We don't know how to do anything like carrier control on non-ATTSV systems,
  13152.  * except, apparently, ultrix.  See above.  It is also known that this doesn't
  13153.  * have much effect on a Xenix system.  For Xenix, one should switch back and
  13154.  * forth between the upper and lower case device files.  Maybe later.
  13155.  * Presently, Xenix will stick to the mode it was opened with.
  13156.  *
  13157.  * carrier: 0 = ignore carrier, 1 = require carrier.
  13158.  * The current state is saved in curcarr, and checked to save labour.
  13159.  */
  13160. #ifdef SVORPOSIX
  13161. int
  13162. #ifdef BSD44ORPOSIX
  13163. carrctl(ttpar, carrier)    struct termios *ttpar; int carrier;
  13164. #else /* ATTSV */
  13165. carrctl(ttpar, carrier)    struct termio *ttpar; int carrier;
  13166. #endif /* BSD44ORPOSIX */
  13167. /* carrctl */ {
  13168.     debug(F101, "carrctl","",carrier);
  13169.     if (carrier)
  13170.       ttpar->c_cflag &= ~CLOCAL;
  13171.     else
  13172.       ttpar->c_cflag |= CLOCAL;
  13173.     return(0);
  13174. }
  13175. #else /* Berkeley, V7, et al... */
  13176. int
  13177. carrctl(ttpar, carrier) struct sgttyb *ttpar; int carrier; {
  13178.     debug(F101, "carrctl","",carrier);
  13179.     if (carrier == curcarr)
  13180.       return(0);
  13181.     curcarr = carrier;
  13182. #ifdef ultrix
  13183. #ifdef COMMENT
  13184. /*
  13185.   Old code from somebody at DEC that tends to get stuck, time out, etc.
  13186. */
  13187.     if (carrier) {
  13188.     ioctl(ttyfd, TIOCMODEM, &temp);
  13189.     ioctl(ttyfd, TIOCHPCL, 0);
  13190.     } else {
  13191.     /* (According to the manuals, TIOCNCAR should be preferred */
  13192.     /* over TIOCNMODEM...) */
  13193.     ioctl(ttyfd, TIOCNMODEM, &temp);
  13194.     }
  13195. #else
  13196. /*
  13197.   New code from Jamie Watson that, he says, eliminates the problems.
  13198. */
  13199.     if (carrier) {
  13200.     ioctl(ttyfd, TIOCCAR);
  13201.     ioctl(ttyfd, TIOCHPCL);
  13202.     } else {
  13203.     ioctl(ttyfd, TIOCNCAR);
  13204.     }
  13205. #endif /* COMMENT */
  13206. #endif /* ultrix */
  13207.     return(0);
  13208. }
  13209. #endif /* SVORPOSIX */
  13210.  
  13211.  
  13212. /*  T T G M D M  --  Get modem signals  */
  13213. /*
  13214.  Looks for RS-232 modem signals, and returns those that are on in as its
  13215.  return value, in a bit mask composed of the BM_xxx values defined in ckcdeb.h.
  13216.  Returns:
  13217.  -3 Not implemented
  13218.  -2 if the communication device does not have modem control (e.g. telnet)
  13219.  -1 on error.
  13220.  >= 0 on success, with a bit mask containing the modem signals that are on.
  13221. */
  13222.  
  13223. /*
  13224.   Define the symbol K_MDMCTL if we have Sys V R3 / 4.3 BSD style
  13225.   modem control, namely the TIOCMGET ioctl.
  13226. */
  13227.  
  13228. #ifdef BSD43
  13229. #define K_MDMCTL
  13230. #endif /* BSD43 */
  13231.  
  13232. #ifdef SUNOS4
  13233. #define K_MDMCTL
  13234. #endif /* SUNOS4 */
  13235.  
  13236. /*
  13237.   SCO OpenServer R5.0.4.  The TIOCMGET definition is hardwired in because it
  13238.   is skipped in termio.h when _POSIX_SOURCE is defined.  But _POSIX_SOURCE
  13239.   must be defined in order to get the high serial speeds that are new to
  13240.   5.0.4.  However, the regular SCO drivers do not implement TIOCMGET, so the
  13241.   ioctl() returns -1 with errno 22 (invalid function).  But third-party
  13242.   drivers, e.g. for Digiboard, do implement it, and so it should work on ports
  13243.   driven by those drivers.
  13244. */
  13245. #ifdef SCO_OSR504
  13246. #ifndef TIOCMGET
  13247. #define TIOCMGET (('t'<<8)|29)
  13248. #endif /* TIOCMGET */
  13249. #endif /* SCO_OSR504 */
  13250.  
  13251. #ifdef CK_SCOV5
  13252. /* Because POSIX strictness in <sys/termio.h> won't let us see these. */
  13253. #ifndef TIOCM_DTR
  13254. #define TIOCM_DTR    0x0002        /* data terminal ready */
  13255. #define TIOCM_RTS    0x0004        /* request to send */
  13256. #define TIOCM_CTS    0x0020        /* clear to send */
  13257. #define TIOCM_CAR    0x0040        /* carrier detect */
  13258. #define TIOCM_RNG    0x0080        /* ring */
  13259. #define TIOCM_DSR    0x0100        /* data set ready */
  13260. #define TIOCM_CD    TIOCM_CAR
  13261. #define TIOCM_RI    TIOCM_RNG
  13262. #endif /* TIOCM_DTR */
  13263. #endif /* CK_SCOV5 */
  13264.  
  13265. #ifdef QNX
  13266. #define K_MDMCTL
  13267. #else
  13268. #ifdef TIOCMGET
  13269. #define K_MDMCTL
  13270. #endif /* TIOCMGET */
  13271. #endif /* QNX */
  13272. /*
  13273.   "A serial communication program that can't read modem signals
  13274.    is like a car without windows."
  13275. */
  13276. int
  13277. ttgmdm() {
  13278.  
  13279. #ifdef QNX
  13280. #include <sys/qioctl.h>
  13281.  
  13282.     unsigned long y, mdmbits[2];
  13283.     int x, z = 0;
  13284.  
  13285.     if (xlocal && ttyfd < 0)
  13286.       return(-1);
  13287.  
  13288. #ifdef NETCONN
  13289.     if (netconn) {            /* Network connection */
  13290. #ifdef TN_COMPORT
  13291.         if (istncomport()) {
  13292.         gotsigs = 1;
  13293.         return(tngmdm());
  13294.     } else
  13295. #endif /* TN_COMPORT */
  13296.       return(-2);            /* No modem signals */
  13297.     }
  13298. #endif /* NETCONN */
  13299.  
  13300. #ifdef NETCMD
  13301.     if (ttpipe) return(-2);
  13302. #endif /* NETCMD */
  13303. #ifdef NETPTY
  13304.     if (ttpty) return(-2);
  13305. #endif /* NETPTY */
  13306.  
  13307.     mdmbits[0] = 0L;
  13308.     mdmbits[1] = 0L;
  13309. /*
  13310.  * From <sys/qioctl.h>:
  13311.  *
  13312.  * SERIAL devices   (all Dev.ser versions)
  13313.  * 0 : DTR           8 = Data Bits 0  16 - reserved     24 - reserved
  13314.  * 1 : RTS           9 = Data Bits 1  17 - reserved     25 - reserved
  13315.  * 2 = Out 1        10 = Stop Bits    18 - reserved     26 - reserved
  13316.  * 3 = Int Enable   11 = Par Enable   19 - reserved     27 - reserved
  13317.  * 4 = Loop         12 = Par Even     20 = CTS          28 - reserved
  13318.  * 5 - reserved     13 = Par Stick    21 = DSR          29 - reserved
  13319.  * 6 - reserved     14 : Break        22 = RI           30 - reserved
  13320.  * 7 - reserved     15 = 0            23 = CD           31 - reserved
  13321.  */
  13322.     errno = 0;
  13323.     x = qnx_ioctl(ttyfd, QCTL_DEV_CTL, &mdmbits[0], 8, &mdmbits[0], 4);
  13324.     debug(F101,"ttgmdm qnx_ioctl","",x);
  13325.     debug(F101,"ttgmdm qnx_ioctl errno","",errno);
  13326.     if (!x) {
  13327.     debug(F101,"ttgmdm qnx_ioctl mdmbits[0]","",mdmbits[0]);
  13328.     debug(F101,"ttgmdm qnx_ioctl mdmbits[1]","",mdmbits[1]);
  13329.     y = mdmbits[0];
  13330.     if (y & 0x000001L) z |= BM_DTR;    /* Bit  0 */
  13331.     if (y & 0x000002L) z |= BM_RTS;    /* Bit  1 */
  13332.     if (y & 0x100000L) z |= BM_CTS;    /* Bit 20 */
  13333.     if (y & 0x200000L) z |= BM_DSR;    /* Bit 21 */
  13334.     if (y & 0x400000L) z |= BM_RNG;    /* Bit 22 */
  13335.     if (y & 0x800000L) z |= BM_DCD;    /* Bit 23 */
  13336.     debug(F101,"ttgmdm qnx result","",z);
  13337.     debug(F110,"ttgmdm qnx CD = ",(z & BM_DCD) ? "On" : "Off", 0);
  13338.     gotsigs = 1;
  13339.     return(z);
  13340.     } else return(-1);
  13341. #else /* QNX */
  13342. #ifdef HPUX                /* HPUX has its own way */
  13343.     int x, z;
  13344.  
  13345. #ifdef HPUX10                /* Modem flag word */
  13346.     mflag y;                /* mflag typedef'd in <sys/modem.h> */
  13347. #else
  13348. #ifdef HPUX9
  13349.     mflag y;
  13350. #else
  13351. #ifdef HPUX8
  13352.     mflag y;
  13353. #else
  13354.     unsigned long y;            /* Not sure about pre-8.0... */
  13355. #endif /* HPUX8 */
  13356. #endif /* HPUX9 */
  13357. #endif /* HPUX10 */
  13358.  
  13359.     if (xlocal && ttyfd < 0)
  13360.       return(-1);
  13361.  
  13362. #ifdef NETCONN
  13363.     if (netconn) {            /* Network connection */
  13364. #ifdef TN_COMPORT
  13365.         if (istncomport()) {
  13366.         gotsigs = 1;
  13367.         return(tngmdm());
  13368.     } else
  13369. #endif /* TN_COMPORT */
  13370.       return(-2);            /* No modem signals */
  13371.     }
  13372. #endif /* NETCONN */
  13373.  
  13374. #ifdef NETCMD
  13375.     if (ttpipe) return(-2);
  13376. #endif /* NETCMD */
  13377. #ifdef NETPTY
  13378.     if (ttpty) return(-2);
  13379. #endif /* NETPTY */
  13380.  
  13381.     if (xlocal)                /* Get modem signals */
  13382.       x = ioctl(ttyfd,MCGETA,&y);
  13383.     else
  13384.       x = ioctl(0,MCGETA,&y);
  13385.     if (x < 0) return(-1);
  13386.     debug(F101,"ttgmdm","",y);
  13387.  
  13388.     z = 0;                /* Initialize return value */
  13389.  
  13390. /* Now set bits for each modem signal that is reported to be on. */
  13391.  
  13392. #ifdef MCTS
  13393.     /* Clear To Send */
  13394.     debug(F101,"ttgmdm HPUX CTS","",y & MCTS);
  13395.     if (y & MCTS) z |= BM_CTS;
  13396. #endif
  13397. #ifdef MDSR
  13398.     /* Data Set Ready */
  13399.     debug(F101,"ttgmdm HPUX DSR","",y & MDSR);
  13400.     if (y & MDSR) z |= BM_DSR;
  13401. #endif
  13402. #ifdef MDCD
  13403.     /* Carrier */
  13404.     debug(F101,"ttgmdm HPUX DCD","",y & MDCD);
  13405.     if (y & MDCD) z |= BM_DCD;
  13406. #endif
  13407. #ifdef MRI
  13408.     /* Ring Indicate */
  13409.     debug(F101,"ttgmdm HPUX RI","",y & MRI);
  13410.     if (y & MRI) z |= BM_RNG;
  13411. #endif
  13412. #ifdef MDTR
  13413.     /* Data Terminal Ready */
  13414.     debug(F101,"ttgmdm HPUX DTR","",y & MDTR);
  13415.     if (y & MDTR) z |= BM_DTR;
  13416. #endif
  13417. #ifdef MRTS
  13418.     /* Request To Send */
  13419.     debug(F101,"ttgmdm HPUX RTS","",y & MRTS);
  13420.     if (y & MRTS) z |= BM_RTS;
  13421. #endif
  13422.     gotsigs = 1;
  13423.     return(z);
  13424.  
  13425. #else /* ! HPUX */
  13426.  
  13427. #ifdef K_MDMCTL
  13428. /*
  13429.   Note, TIOCMGET might already have been defined in <sys/ioctl.h> or elsewhere.
  13430.   If not, we try including <sys/ttycom.h> -- if this blows up then more ifdefs
  13431.   are needed.
  13432. */
  13433. #ifndef TIOCMGET
  13434. #include <sys/ttycom.h>
  13435. #endif /* TIOCMGET */
  13436.  
  13437.     int x, y, z;
  13438.  
  13439.     debug(F100,"ttgmdm K_MDMCTL defined","",0);
  13440.  
  13441. #ifdef NETCONN
  13442.     if (netconn) {            /* Network connection */
  13443. #ifdef TN_COMPORT
  13444.         if (istncomport()) {
  13445.         gotsigs = 1;
  13446.         return(tngmdm());
  13447.     } else
  13448. #endif /* TN_COMPORT */
  13449.       return(-2);            /* No modem signals */
  13450.     }
  13451. #endif /* NETCONN */
  13452.  
  13453. #ifdef NETCMD
  13454.     if (ttpipe) return(-2);
  13455. #endif /* NETCMD */
  13456. #ifdef NETPTY
  13457.     if (ttpty) return(-2);
  13458. #endif /* NETPTY */
  13459.  
  13460.     if (xlocal && ttyfd < 0)
  13461.       return(-1);
  13462.  
  13463.     if (xlocal)
  13464.       x = ioctl(ttyfd,TIOCMGET,&y);    /* Get modem signals. */
  13465.     else
  13466.       x = ioctl(0,TIOCMGET,&y);
  13467.     debug(F101,"ttgmdm TIOCMGET ioctl","",x);
  13468.     if (x < 0) {
  13469.     debug(F101,"ttgmdm errno","",errno);
  13470.     return(-1);
  13471.     }
  13472.     debug(F101,"ttgmdm bits","",y);
  13473.  
  13474.     z = 0;                /* Initialize return value. */
  13475. #ifdef TIOCM_CTS
  13476.     /* Clear To Send */
  13477.     if (y & TIOCM_CTS) z |= BM_CTS;
  13478.     debug(F101,"ttgmdm TIOCM_CTS defined","",TIOCM_CTS); 
  13479. #else
  13480.     debug(F100,"ttgmdm TIOCM_CTS not defined","",0);
  13481. #endif
  13482. #ifdef TIOCM_DSR
  13483.     /* Data Set Ready */
  13484.     if (y & TIOCM_DSR) z |= BM_DSR;
  13485.     debug(F101,"ttgmdm TIOCM_DSR defined","",TIOCM_DSR); 
  13486. #else
  13487.     debug(F100,"ttgmdm TIOCM_DSR not defined","",0);
  13488. #endif
  13489. #ifdef TIOCM_CAR
  13490.     /* Carrier */
  13491.     if (y & TIOCM_CAR) z |= BM_DCD;
  13492.     debug(F101,"ttgmdm TIOCM_CAR defined","",TIOCM_CAR); 
  13493. #else
  13494.     debug(F100,"ttgmdm TIOCM_CAR not defined","",0);
  13495. #endif
  13496. #ifdef TIOCM_RNG
  13497.     /* Ring Indicate */
  13498.     if (y & TIOCM_RNG) z |= BM_RNG;
  13499.     debug(F101,"ttgmdm TIOCM_RNG defined","",TIOCM_RNG); 
  13500. #else
  13501.     debug(F100,"ttgmdm TIOCM_RNG not defined","",0);
  13502. #endif
  13503. #ifdef TIOCM_DTR
  13504.     /* Data Terminal Ready */
  13505.     if (y & TIOCM_DTR) z |= BM_DTR;
  13506.     debug(F101,"ttgmdm TIOCM_DTR defined","",TIOCM_DTR); 
  13507. #else
  13508.     debug(F100,"ttgmdm TIOCM_DTR not defined","",0);
  13509. #endif
  13510. #ifdef TIOCM_RTS
  13511.     /* Request To Send */
  13512.     if (y & TIOCM_RTS) z |= BM_RTS;
  13513.     debug(F101,"ttgmdm TIOCM_RTS defined","",TIOCM_RTS); 
  13514. #else
  13515.     debug(F100,"ttgmdm TIOCM_RTS not defined","",0);
  13516. #endif
  13517.     gotsigs = 1;
  13518.     return(z);
  13519.  
  13520. #else /* !K_MDMCTL catch-All */
  13521.  
  13522.     debug(F100,"ttgmdm K_MDMCTL not defined","",0);
  13523. #ifdef TIOCMGET
  13524.     debug(F100,"ttgmdm TIOCMGET defined","",0);
  13525. #else
  13526.     debug(F100,"ttgmdm TIOCMGET not defined","",0);
  13527. #endif /* TIOCMGET */
  13528. #ifdef _SVID3
  13529.     debug(F100,"ttgmdm _SVID3 defined","",0);
  13530. #else
  13531.     debug(F100,"ttgmdm _SVID3 not defined","",0);
  13532. #endif /* _SVID3 */
  13533.  
  13534. #ifdef NETCONN
  13535.     if (netconn) {            /* Network connection */
  13536. #ifdef TN_COMPORT
  13537.         if (istncomport()) {
  13538.         gotsigs = 1;
  13539.         return(tngmdm());
  13540.     } else
  13541. #endif /* TN_COMPORT */
  13542.       return(-2);            /* No modem signals */
  13543.     }
  13544. #endif /* NETCONN */
  13545.  
  13546. #ifdef NETCMD
  13547.     if (ttpipe) return(-2);
  13548. #endif /* NETCMD */
  13549. #ifdef NETPTY
  13550.     if (ttpty) return(-2);
  13551. #endif /* NETPTY */
  13552.  
  13553.     return(-3);                /* Sorry, I don't know how... */
  13554.  
  13555. #endif /* K_MDMCTL */
  13556. #endif /* HPUX */
  13557. #endif /* QNX */
  13558. }
  13559.  
  13560. /*  P S U S P E N D  --  Put this process in the background.  */
  13561.  
  13562. /*
  13563.   Call with flag nonzero if suspending is allowed, zero if not allowed.
  13564.   Returns 0 on apparent success, -1 on failure (flag was zero, or
  13565.   kill() returned an error code.
  13566. */
  13567. int
  13568. psuspend(flag) int flag; {
  13569.  
  13570. #ifdef RTU
  13571.     extern int rtu_bug;
  13572. #endif /* RTU */
  13573.  
  13574.     if (flag == 0) return(-1);
  13575.  
  13576. #ifdef NOJC
  13577.     return(-1);
  13578. #else
  13579. #ifdef SIGTSTP
  13580. /*
  13581.   The big question here is whether job control is *really* supported.
  13582.   There's no way Kermit can know for sure.  The fact that SIGTSTP is
  13583.   defined does not guarantee the Unix kernel supports it, and the fact
  13584.   that the Unix kernel supports it doesn't guarantee that the user's
  13585.   shell (or other process that invoked Kermit) supports it.
  13586. */
  13587. #ifdef RTU
  13588.     rtu_bug = 1;
  13589. #endif /* RTU */
  13590.     if (kill(0,SIGSTOP) < 0
  13591. #ifdef MIPS
  13592. /* Let's try this for MIPS too. */
  13593.     && kill(getpid(),SIGSTOP) < 0
  13594. #endif /* MIPS */
  13595.     ) {                /* If job control, suspend the job */
  13596.     perror("suspend");
  13597.     debug(F101,"psuspend error","",errno);
  13598.     return(-1);
  13599.     }
  13600.     debug(F100,"psuspend ok","",0);
  13601.     return(0);
  13602. #else
  13603.     return(-1);
  13604. #endif /* SIGTSTP */
  13605. #endif /* NOJC */
  13606. }
  13607.  
  13608. /*
  13609.   setuid package, by Kristoffer Eriksson, with contributions from Dean
  13610.   Long and fdc.
  13611. */
  13612.  
  13613. /* The following is for SCO when CK_ANSILIBS is defined... */
  13614. #ifdef M_UNIX
  13615. #ifdef CK_ANSILIBS
  13616. #ifndef NOGETID_PROTOS
  13617. #define NOGETID_PROTOS
  13618. #endif /* NOGETID_PROTOS */
  13619. #endif /* CK_ANSILIBS */
  13620. #endif /* M_UNIX */
  13621.  
  13622. #ifndef _POSIX_SOURCE
  13623. #ifndef SUNOS4
  13624. #ifndef NEXT
  13625. #ifndef PS2AIX10
  13626. #ifndef sequent
  13627. #ifndef HPUX9
  13628. #ifndef HPUX10
  13629. #ifndef COHERENT
  13630. #ifndef NOGETID_PROTOS
  13631. _PROTOTYP( UID_T getuid, (void) );
  13632. _PROTOTYP( UID_T geteuid, (void) );
  13633. _PROTOTYP( UID_T getreuid, (void) );
  13634. _PROTOTYP( UID_T getgid, (void) );
  13635. _PROTOTYP( UID_T getegid, (void) );
  13636. _PROTOTYP( UID_T getregid, (void) );
  13637. #endif /* NOGETID_PROTOS */
  13638. #else
  13639. _PROTOTYP( UID_T getreuid, (void) );
  13640. _PROTOTYP( UID_T getregid, (void) );
  13641. #endif /* COHERENT */
  13642. #endif /* HPUX10 */
  13643. #endif /* HPUX9 */
  13644. #endif /* sequent */
  13645. #endif /* PS2AIX10 */
  13646. #endif /* NEXT */
  13647. #endif /* SUNOS4 */
  13648. #endif /* _POSIX_SOURCE */
  13649.  
  13650. /*
  13651. Subject: Set-user-id
  13652. To: fdc@watsun.cc.columbia.edu (Frank da Cruz)
  13653. Date: Sat, 21 Apr 90 4:48:25 MES
  13654. From: Kristoffer Eriksson <ske@pkmab.se>
  13655.  
  13656. This is a set of functions to be used in programs that may be run set-user-id
  13657. and/or set-group-id. They handle both the case where the program is not run
  13658. with such privileges (nothing special happens then), and the case where one
  13659. or both of these set-id modes are used.  The program is made to run with the
  13660. user's real user and group ids most of the time, except for when more
  13661. privileges are needed.  Don't set-user-id to "root".
  13662.  
  13663. This works on System V and POSIX.  In BSD, it depends on the
  13664. "saved-set-user-id" feature.
  13665. */
  13666.  
  13667. #define UID_ROOT 0            /* Root user and group ids */
  13668. #define GID_ROOT 0
  13669.  
  13670. /*
  13671.   The following code defines the symbol SETEUID for UNIX systems based
  13672.   on BSD4.4 (either -Encumbered or -Lite).  This program will then use
  13673.   seteuid() and setegid() instead of setuid() and setgid(), which still
  13674.   don't allow arbitrary switching.  It also avoids setreuid() and
  13675.   setregid(), which are included in BSD4.4 for compatibility only, are
  13676.   insecure, and print warnings to stderr under at least one system (NetBSD
  13677.   1.0).  Note that POSIX systems should still use setuid() and setgid();
  13678.   the seteuid() and setegid() functions are BSD4.4 extensions to the
  13679.   POSIX model.  Mike Long <mike.long@analog.com>, 8/94.
  13680. */
  13681. #ifdef BSD44
  13682. #define SETEUID
  13683. #endif /* BSD44 */
  13684.  
  13685. /*
  13686.   The following construction automatically defines the symbol SETREUID for
  13687.   UNIX versions based on Berkeley Unix 4.2 and 4.3.  If this symbol is
  13688.   defined, then this program will use getreuid() and getregid() calls in
  13689.   preference to getuid() and getgid(), which in Berkeley-based Unixes do
  13690.   not allow arbitrary switching back and forth of real & effective uid.
  13691.   This construction also allows -DSETREUID to be put on the cc command line
  13692.   for any system that has and wants to use setre[ug]id().  It also prevents
  13693.   automatic definition of SETREUID if -DNOSETREU is included on the cc
  13694.   command line (or otherwise defined).
  13695. */
  13696. #ifdef FT18                /* None of this for Fortune. */
  13697. #define NOSETREU
  13698. #endif /* FT18 */
  13699.  
  13700. #ifdef ANYBSD
  13701. #ifndef BSD29
  13702. #ifndef BSD41
  13703. #ifndef SETREUID
  13704. #ifndef NOSETREU
  13705. #ifndef SETEUID
  13706. #define SETREUID
  13707. #endif /* SETEUID */
  13708. #endif /* NOSETREU */
  13709. #endif /* SETREUID */
  13710. #endif /* !BSD41 */
  13711. #endif /* !BSD29 */
  13712. #endif /* ANYBSD */
  13713.  
  13714. /* Variables for user and group IDs. */
  13715.  
  13716. static UID_T realuid = (UID_T) -1, privuid = (UID_T) -1;
  13717. static GID_T realgid = (GID_T) -1, privgid = (GID_T) -1;
  13718.  
  13719.  
  13720. /* P R I V _ I N I  --  Initialize privileges package  */
  13721.  
  13722. /* Called as early as possible in a set-uid or set-gid program to store the
  13723.  * set-to uid and/or gid and step down to the users real uid and gid. The
  13724.  * stored id's can be temporarily restored (allowed in System V) during
  13725.  * operations that require the privilege.  Most of the time, the program
  13726.  * should execute in unpriviliged state, to not impose any security threat.
  13727.  *
  13728.  * Note: Don't forget that access() always uses the real id:s to determine
  13729.  * file access, even with privileges restored.
  13730.  *
  13731.  * Returns an error mask, with error values or:ed together:
  13732.  *   1 if setuid() fails,
  13733.  *   2 if setgid() fails, and
  13734.  *   4 if the program is set-user-id to "root", which can't be handled.
  13735.  *
  13736.  * Only the return value 0 indicates real success. In case of failure,
  13737.  * those privileges that could be reduced have been, at least, but the
  13738.  * program should be aborted none-the-less.
  13739.  *
  13740.  * Also note that these functions do not expect the uid or gid to change
  13741.  * without their knowing. It may work if it is only done temporarily, but
  13742.  * you're on your own.
  13743.  */
  13744. int
  13745. priv_ini() {
  13746.     int err = 0;
  13747.  
  13748. #ifndef HAVE_LOCKDEV
  13749.  
  13750.     /* Save real ID:s. */
  13751.     realuid = getuid();
  13752.     realgid = getgid();
  13753.  
  13754.     /* Save current effective ID:s, those set to at program exec. */
  13755.     privuid = geteuid();
  13756.     privgid = getegid();
  13757.  
  13758.     /* If running set-uid, go down to real uid, otherwise remember that
  13759.      * no privileged uid is available.
  13760.      *
  13761.      * Exceptions:
  13762.      *
  13763.      * 1) If the real uid is already "root" and the set-uid uid (the
  13764.      * initial effective uid) is not "root", then we would have trouble
  13765.      * if we went "down" to "root" here, and then temporarily back to the
  13766.      * set-uid uid (not "root") and then again tried to become "root". I
  13767.      * think the "saved set-uid" is lost when changing uid from effective
  13768.      * uid "root", which changes all uid, not only the effective uid. But
  13769.      * in this situation, we can simply go to "root" and stay there all
  13770.      * the time. That should give sufficient privilege (understatement!),
  13771.      * and give the right uids for subprocesses.
  13772.      *
  13773.      * 2) If the set-uid (the initial effective uid) is "root", and we
  13774.      * change uid to the real uid, we can't change it back to "root" when
  13775.      * we need the privilege, for the same reason as in 1). Thus, we can't
  13776.      * handle programs that are set-user-id to "root" at all. The program
  13777.      * should be stopped.  Use some other uid.  "root" is probably too
  13778.      * privileged for such things, anyway. (The uid is reverted to the
  13779.      * real uid until termination.)
  13780.      *
  13781.      * These two exceptions have the effect that the "root" uid will never
  13782.      * be one of the two uids that are being switched between, which also
  13783.      * means we don't have to check for such cases in the switching
  13784.      * functions.
  13785.      *
  13786.      * Note that exception 1) is handled by these routines (by constantly
  13787.      * running with uid "root", while exception 2) is a serious error, and
  13788.      * is not provided for at all in the switching functions.
  13789.      */
  13790.     if (realuid == privuid)
  13791.     privuid = (UID_T) -1;        /* Not running set-user-id. */
  13792.  
  13793.     /* If running set-gid, go down to real gid, otherwise remember that
  13794.      * no privileged gid is available.
  13795.      *
  13796.      * There are no exception like there is for the user id, since there
  13797.      * is no group id that is privileged in the manner of uid "root".
  13798.      * There could be equivalent problems for group changing if the
  13799.      * program sometimes ran with uid "root" and sometimes not, but
  13800.      * that is already avoided as explained above.
  13801.      *
  13802.      * Thus we can expect always to be able to switch to the "saved set-
  13803.      * gid" when we want, and back to the real gid again. You may also
  13804.      * draw the conclusion that set-gid provides for fewer hassles than
  13805.      * set-uid.
  13806.      */
  13807.  
  13808. #ifdef SUIDDEBUG
  13809.     fprintf(stderr,"UID_ROOT=%d\n",UID_ROOT);
  13810.     fprintf(stderr,"realuid=%d\n",realuid);
  13811.     fprintf(stderr,"privuid=%d\n",privuid);
  13812. #endif /* SUIDDEBUG */
  13813.  
  13814.     if (realgid == privgid)        /* If not running set-user-id, */
  13815.       privgid = (GID_T) -1;        /*  remember it this way. */
  13816.  
  13817.     err = priv_off();            /* Turn off setuid privilege. */
  13818.  
  13819.     if (privuid == UID_ROOT)        /* If setuid to root, */
  13820.       err |= 4;                /* return this error. */
  13821.  
  13822.     if (realuid == UID_ROOT) {        /* If real id is root, */
  13823.     privuid = (UID_T) -1;        /* stay root at all times. */
  13824. #ifdef ATT7300
  13825.     /* If Kermit installed SUID uucp and user is running as root */
  13826.     err &= ~1;            /* System V R0 does not save UID */
  13827. #endif /* ATT7300 */
  13828.     }
  13829. #endif /* HAVE_LOCKDEV */
  13830.     return(err);
  13831. }
  13832.  
  13833.  
  13834. /* Macros for hiding the differences in UID/GID setting between various Unix
  13835.  * systems. These macros should always be called with both the privileged ID
  13836.  * and the non-privileged ID. The one in the second argument, will become the
  13837.  * effective ID. The one in the first argument will be retained for later
  13838.  * retrieval.
  13839.  */
  13840. #ifdef SETREUID
  13841. #ifdef SAVEDUID
  13842. /* On BSD systems with the saved-UID feature, we just juggle the effective
  13843.  * UID back and forth, and leave the real UID at its true value.  The kernel
  13844.  * allows switching to both the current real UID, the effective UID, and the
  13845.  * UID which the program is set-UID to.  The saved set-UID always holds the
  13846.  * privileged UID for us, and the real UID will always be the non-privileged,
  13847.  * and we can freely choose one of them for the effective UID at any time.
  13848.  */
  13849. #define switchuid(hidden,active) setreuid( (UID_T) -1, active)
  13850. #define switchgid(hidden,active) setregid( (GID_T) -1, active)
  13851.  
  13852. #else   /* SETREUID,!SAVEDUID */
  13853.  
  13854. /* On systems with setreXid() but without the saved-UID feature, notably
  13855.  * BSD 4.2, we swap the real and effective UIDs each time.  It's
  13856.  * the effective UID that we are interested in, but we have to retain the
  13857.  * unused UID somewhere to enable us to restore it later, and we do this
  13858.  * in the real UID.  The kernel only allows switching to either the current
  13859.  * real or the effective UID, unless you're "root".
  13860.  */
  13861. #define switchuid(hidden,active)    setreuid(hidden,active)
  13862. #define switchgid(hidden,active)    setregid(hidden,active)
  13863. #endif
  13864.  
  13865. #else /* !SETREUID, !SAVEDUID */
  13866.  
  13867. #ifdef SETEUID
  13868. /*
  13869.   BSD 4.4 works similarly to System V and POSIX (see below), but uses
  13870.   seteXid() instead of setXid() to change effective IDs.  In addition, the
  13871.   seteXid() functions work the same for "root" as for other users.
  13872. */
  13873. #define switchuid(hidden,active)    seteuid(active)
  13874. #define switchgid(hidden,active)    setegid(active)
  13875.  
  13876. #else /* !SETEUID */
  13877.  
  13878. /* On System V and POSIX, the only thing we can change is the effective UID
  13879.  * (unless the current effective UID is "root", but initsuid() avoids that for
  13880.  * us).  The kernel allows switching to the current real UID or to the saved
  13881.  * set-UID.  These are always set to the non-privileged UID and the privileged
  13882.  * UID, respectively, and we only change the effective UID.  This breaks if
  13883.  * the current effective UID is "root", though, because for "root" setuid/gid
  13884.  * becomes more powerful, which is why initsuid() treats "root" specially.
  13885.  * Note: That special treatment maybe could be ignored for BSD?  Note: For
  13886.  * systems that don't fit any of these four cases, we simply can't support
  13887.  * set-UID.
  13888.  */
  13889. #define switchuid(hidden,active)    setuid(active)
  13890. #define switchgid(hidden,active)    setgid(active)
  13891.  
  13892. #endif /* SETEUID */
  13893. #endif /* SETREUID */
  13894.  
  13895.  
  13896. /* P R I V _ O N  --  Turn on the setuid and/or setgid */
  13897.  
  13898. /* Go to the privileged uid (gid) that the program is set-user-id
  13899.  * (set-group-id) to, unless the program is running unprivileged.
  13900.  * If setuid() fails, return value will be 1. If getuid() fails it
  13901.  * will be 2.  Return immediately after first failure, and the function
  13902.  * tries to restore any partial work done.  Returns 0 on success.
  13903.  * Group id is changed first, since it is less serious than user id.
  13904.  */
  13905. int
  13906. priv_on() {
  13907. #ifndef HAVE_LOCKDEV
  13908.     if (privgid != (GID_T) -1)
  13909.       if (switchgid(realgid,privgid))
  13910.         return(2);
  13911.  
  13912.     if (privuid != (UID_T) -1)
  13913.       if (switchuid(realuid,privuid)) {
  13914.       if (privgid != (GID_T) -1)
  13915.         switchgid(privgid,realgid);
  13916.       return(1);
  13917.       }
  13918. #endif /* HAVE_LOCKDEV */
  13919.     return(0);
  13920. }
  13921.  
  13922. /* P R I V _ O F F  --  Turn on the real uid and gid */
  13923.  
  13924. /* Return to the unprivileged uid (gid) after an temporary visit to
  13925.  * privileged status, unless the program is running without set-user-id
  13926.  * (set-group-id). Returns 1 for failure in setuid() and 2 for failure
  13927.  * in setgid() or:ed together. The functions tries to return both uid
  13928.  * and gid to unprivileged state, regardless of errors. Returns 0 on
  13929.  * success.
  13930.  */
  13931. int
  13932. priv_off() {
  13933.     int err = 0;
  13934. #ifndef HAVE_LOCKDEV
  13935.     if (privuid != (UID_T) -1)
  13936.        if (switchuid(privuid,realuid))
  13937.       err |= 1;
  13938.  
  13939.     if (privgid != (GID_T) -1)
  13940.        if (switchgid(privgid,realgid))
  13941.     err |= 2;
  13942. #endif /* HAVE_LOCKDEV */
  13943.     return(err);
  13944. }
  13945.  
  13946. /* Turn off privilege permanently.  No going back.  This is necessary before
  13947.  * a fork() on BSD43 machines that don't save the setUID or setGID, because
  13948.  * we swap the real and effective ids, and we don't want to let the forked
  13949.  * process swap them again and get the privilege back. It will work on other
  13950.  * machines too, such that you can rely on its effect always being the same,
  13951.  * for instance, even when you're in priv_on() state when this is called.
  13952.  * (Well, that part about "permanent" is on System V only true if you follow
  13953.  * this with a call to exec(), but that's what we want it for anyway.)
  13954.  * Added by Dean Long -- dlong@midgard.ucsc.edu
  13955.  */
  13956. int
  13957. priv_can() {
  13958. #ifndef HAVE_LOCKDEV
  13959. #ifdef SETREUID
  13960.     int err = 0;
  13961.     if (privuid != (UID_T) -1)
  13962.        if (setreuid(realuid,realuid))
  13963.       err |= 1;
  13964.  
  13965.     if (privgid != (GID_T) -1)
  13966.         if (setregid(realgid,realgid))
  13967.        err |= 2;
  13968.  
  13969.     return(err);
  13970.  
  13971. #else
  13972. #ifdef SETEUID
  13973.     int err = 0;
  13974.     if (privuid != (UID_T) -1)
  13975.     if (setuid(realuid)) {
  13976.         debug(F101,"setuid failed","",errno);
  13977.         err |= 1;
  13978.         debug(F101,"ruid","",getuid());
  13979.         debug(F101,"euid","",geteuid());
  13980.     }
  13981.     debug(F101,"setuid","",realuid);
  13982.     if (privgid != (GID_T) -1)
  13983.         if (setgid(realgid)) {
  13984.         debug(F101,"setgid failed","",errno);
  13985.         err |= 2;
  13986.         debug(F101,"rgid","",getgid());
  13987.         debug(F101,"egid","",getegid());
  13988.     }
  13989.     debug(F101,"setgid","",realgid);
  13990.     return(err);
  13991. #else
  13992.     /* Easy way of using setuid()/setgid() instead of setreuid()/setregid().*/
  13993.     return(priv_off());
  13994. #endif /* SETEUID */
  13995. #endif /* SETREUID */
  13996. #else
  13997.     return(0);
  13998. #endif /* HAVE_LOCKDEV */
  13999. }
  14000.  
  14001. /* P R I V _ O P N  --  For opening protected files or devices. */
  14002.  
  14003. int
  14004. priv_opn(name, modes) char *name; int modes; {
  14005.     int x;
  14006.     priv_on();                /* Turn privileges on */
  14007.     debug(F111,"priv_opn",name,modes);
  14008.     errno = 0;
  14009.     x = open(name, modes);        /* Try to open the device */
  14010.     debug(F101,"priv_opn result","",x);
  14011.     debug(F101,"priv_opn errno","",errno);
  14012.     priv_off();                /* Turn privileges off */
  14013.     return(x);                /* Return open's return code */
  14014. }
  14015.  
  14016. /*  P R I V _ C H K  --  Check privileges.  */
  14017.  
  14018. /*  Try to turn them off.  If turning them off did not succeed, cancel them */
  14019.  
  14020. int
  14021. priv_chk() {
  14022.     int x, y = 0;
  14023.     x = priv_off();            /* Turn off privs. */
  14024.     if (x != 0 || getuid() == privuid || geteuid() == privuid)
  14025.       y = priv_can();
  14026.     if (x != 0 || getgid() == privgid || getegid() == privgid)
  14027.       y = y | priv_can();
  14028.     return(y);
  14029. }
  14030.  
  14031. UID_T
  14032. real_uid() {
  14033.     return(realuid);
  14034. }
  14035.  
  14036. VOID
  14037. ttimoff() {                /* Turn off any timer interrupts */
  14038.     /* int xx; */
  14039. /*
  14040.   As of 5A(183), we set SIGALRM to SIG_IGN (to ignore alarms) rather than to
  14041.   SIG_DFL (to catch alarms, or if there is no handler, to exit).  This is to
  14042.   cure (mask, really) a deeper problem with stray alarms that occurs on some
  14043.   systems, possibly having to do with sleep(), that caused core dumps.  It
  14044.   should be OK to do this, because no code in this module uses nested alarms.
  14045.   (But we still have to watch out for SCRIPT and DIAL...)
  14046. */
  14047.     /* xx = */ alarm(0);
  14048.     /* debug(F101,"ttimoff alarm","",xx); */
  14049.     if (saval) {            /* Restore any previous */
  14050.     signal(SIGALRM,saval);        /* alarm handler. */
  14051.     /* debug(F101,"ttimoff alarm restoring saval","",saval); */
  14052.     saval = NULL;
  14053.     } else {
  14054.     signal(SIGALRM,SIG_IGN);    /* Used to be SIG_DFL */
  14055.     /* debug(F100,"ttimoff alarm SIG_IGN","",0); */
  14056.     }
  14057. }
  14058.  
  14059.  
  14060. int
  14061. tt_is_secure() {      /* Tells whether the current connection is secure */
  14062.  
  14063.     if (ttyfd == -1)
  14064.       return(0);
  14065.  
  14066.     if (0
  14067. #ifdef SSHBUILTIN
  14068.     || IS_SSH()
  14069. #endif /* SSHBUILTIN */
  14070. #ifdef CK_ENCRYPTION
  14071.     || ck_tn_encrypting() && ck_tn_decrypting()
  14072. #endif /* CK_ENCRYPTION */
  14073. #ifdef CK_SSL
  14074.     || tls_active_flag || ssl_active_flag
  14075. #endif /* CK_SSL */
  14076. #ifdef RLOGCODE
  14077. #ifdef CK_KERBEROS
  14078. #ifdef CK_ENCRYPTION
  14079.     || ttnproto == NP_EK4LOGIN || ttnproto == NP_EK5LOGIN
  14080. #endif /* CK_ENCRYPTION */
  14081. #endif /* CK_KERBEROS */
  14082. #endif /* RLOGCODE */
  14083.     )
  14084.       return(1);
  14085.     return(0);
  14086. }
  14087.  
  14088. #ifdef CK_REDIR
  14089.   
  14090. /* External protocol handler parameters from ckuus3.c */
  14091. extern int exp_handler, exp_stderr, exp_timo;
  14092.  
  14093. #ifdef SELECT
  14094. #ifdef NETPTY
  14095.  
  14096. /* The right size is 24576 */
  14097.  
  14098. #ifndef PTY_PBUF_SIZE            /* Size of buffer to read from pty */
  14099. #define PTY_PBUF_SIZE 24576        /* and write to net. */
  14100. #endif    /* PTY_PBUF_SIZE */
  14101.  
  14102. #ifndef PTY_TBUF_SIZE            /* Size of buffer to read from net */
  14103. #define PTY_TBUF_SIZE 24576        /* and write to pty. */
  14104. #endif    /* PTY_TBUF_SIZE */
  14105.  
  14106. #ifdef O_NDELAY                /* Whether to use nonblocking */
  14107. #ifndef PTY_NO_NDELAY            /* reads on the pseudoterminal */
  14108. #ifndef PTY_USE_NDELAY
  14109. #define PTY_USE_NDELAY
  14110. #endif    /* PTY_USE_NDELAY */
  14111. #endif    /* PTY_NO_NDELAY */
  14112. #endif    /* O_NDELAY */
  14113.  
  14114. #ifndef HAVE_OPENPTY
  14115. #ifndef USE_CKUPTY_C
  14116. #define USE_CKUPTY_C
  14117. #endif /* USE_CKUPTY_C */
  14118. #endif /* HAVE_OPENPTY */
  14119.  
  14120. VOID
  14121. pty_make_raw(fd) int fd; {
  14122.     int x = -23, i;
  14123.  
  14124. #ifdef BSD44ORPOSIX            /* POSIX */
  14125.     struct termios tp;
  14126. #else
  14127. #ifdef ATTSV                /* AT&T UNIX */
  14128. #ifdef CK_ANSIC
  14129.     struct termio tp = {0};
  14130. #else
  14131.     struct termio tp;
  14132. #endif    /* CK_ANSIC */
  14133. #else
  14134.     struct sgttyb tp;            /* Traditional */
  14135. #endif /* ATTSV */
  14136. #endif /* BSD44ORPOSIX */
  14137.  
  14138.     debug(F101,"pty_make_raw fd","",fd);
  14139.     errno = 0;
  14140.  
  14141. #ifdef BSD44ORPOSIX            /* POSIX */
  14142.     x = tcgetattr(fd,&tp);
  14143.     debug(F101,"pty_make_raw tcgetattr","",x);
  14144. #else
  14145. #ifdef ATTSV                /* AT&T UNIX */
  14146.     x = ioctl(fd,TCGETA,&tp);
  14147.     debug(F101,"pty_make_raw TCGETA ioctl","",x);
  14148. #else
  14149.     x = gtty(fd,&tp);
  14150.     debug(F101,"pty_make_raw ttty","",x);
  14151. #endif /* ATTSV */
  14152. #endif /* BSD44ORPOSIX */
  14153.     debug(F101,"pty_make_raw GET errno","",errno);
  14154.  
  14155. #ifdef USE_CFMAKERAW
  14156.     errno = 0;
  14157.     cfmakeraw(&tp);
  14158.     debug(F101,"pty_make_raw cfmakeraw errno","",errno);
  14159. #else  /* USE_CFMAKERAW */
  14160.  
  14161. #ifdef COMMENT
  14162.  
  14163. /* This very simple version recommended by Serg Iakolev doesn't work */
  14164.  
  14165.     tp.c_lflag &= ~(ECHO|ICANON|IEXTEN|ISIG);
  14166.     tp.c_iflag &= ~(BRKINT|ICRNL|INPCK|ISTRIP|IXON);
  14167.     tp.c_cflag &= ~(CSIZE|PARENB);
  14168.     tp.c_cflag |= CS8;
  14169.     tp.c_oflag &= ~(OPOST);
  14170.     tp.c_cc[VMIN] = 1;
  14171.     tp.c_cc[VTIME] = 0;
  14172.  
  14173.     debug(F101,"pty_make_raw 1 c_cc[] NCCS","",NCCS);
  14174.     debug(F101,"pty_make_raw 1 iflags","",tp.c_iflag);
  14175.     debug(F101,"pty_make_raw 1 oflags","",tp.c_oflag);
  14176.     debug(F101,"pty_make_raw 1 lflags","",tp.c_lflag);
  14177.     debug(F101,"pty_make_raw 1 cflags","",tp.c_cflag);
  14178.  
  14179. #else
  14180. #ifdef COMMENT
  14181. /*
  14182.   In this version we unset everything and then set only the
  14183.   bits we know we need.
  14184. */
  14185.     /* iflags */
  14186.     tp.c_iflag = 0L;
  14187.     tp.c_iflag |= IGNBRK;
  14188. #ifdef IMAXBEL
  14189.     tp.c_iflag |= IMAXBEL;
  14190. #endif /* IMAXBEL */
  14191.  
  14192.     /* oflags */
  14193.     tp.c_oflag = 0L;
  14194.  
  14195.     /* lflags */
  14196.     tp.c_lflag = 0L;
  14197. #ifdef NOKERNINFO
  14198.     tp.c_lflag |= NOKERNINFO;
  14199. #endif    /* NOKERNINFO */
  14200.  
  14201.     /* cflags */
  14202.     tp.c_cflag = 0L;
  14203.     tp.c_cflag |= CS8|CREAD;
  14204.  
  14205.     for (i = 0; i < NCCS; i++) {    /* No special characters */
  14206.     tp.c_cc[i] = 0;
  14207.     }
  14208. #ifdef VMIN
  14209.     tp.c_cc[VMIN] = 1;            /* But always wait for input */
  14210. #endif    /* VMIN */
  14211.     debug(F101,"pty_make_raw 2 c_cc[] NCCS","",NCCS);
  14212.     debug(F101,"pty_make_raw 2 iflags","",tp.c_iflag);
  14213.     debug(F101,"pty_make_raw 2 oflags","",tp.c_oflag);
  14214.     debug(F101,"pty_make_raw 2 lflags","",tp.c_lflag);
  14215.     debug(F101,"pty_make_raw 2 cflags","",tp.c_cflag);
  14216.  
  14217. #else  /* COMMENT */
  14218. /*
  14219.   In this version we set or unset every single flag explicitly.  It works a
  14220.   bit better than the simple version just above, but it's still far from
  14221.   adequate.
  14222. */
  14223.     /* iflags */
  14224.     tp.c_iflag &= ~(PARMRK|ISTRIP|BRKINT|INLCR|IGNCR|ICRNL);
  14225.     tp.c_iflag &= ~(INPCK|IGNPAR|IXANY|IXON|IXOFF);
  14226.     tp.c_iflag |= IGNBRK;
  14227. #ifdef IMAXBEL
  14228. #ifdef COMMENT
  14229.     tp.c_iflag |= IMAXBEL;
  14230. #else
  14231.     tp.c_iflag &= ~IMAXBEL;
  14232. #endif /* COMMENT */
  14233. #endif /* IMAXBEL */
  14234. #ifdef IUCLC
  14235.     tp.c_iflag &= ~IUCLC;
  14236. #endif /* IUCLC */
  14237.  
  14238.     /* oflags */
  14239. #ifdef BSDLY
  14240.     tp.c_oflag &= ~BSDLY;
  14241. #endif /* BSDLY */
  14242. #ifdef CRDLY
  14243.     tp.c_oflag &= ~CRDLY;
  14244. #endif /* CRDLY */
  14245. #ifdef FFDLY
  14246.     tp.c_oflag &= ~FFDLY;
  14247. #endif /* FFDLY */
  14248. #ifdef NLDLY
  14249.     tp.c_oflag &= ~NLDLY;
  14250. #endif /* NLDLY */
  14251. #ifdef TABDLY
  14252.     tp.c_oflag &= ~TABDLY;
  14253. #endif /* TABDLY */
  14254. #ifdef VTDLY
  14255.     tp.c_oflag &= ~VTDLY;
  14256. #endif /* VTDLY */
  14257. #ifdef OFDEL
  14258.     tp.c_oflag &= ~OFDEL;
  14259. #endif /* OFDEL */
  14260. #ifdef OFILL
  14261.     tp.c_oflag &= ~OFILL;
  14262. #endif /* OFILL */
  14263. #ifdef OLCUC
  14264.     tp.c_oflag &= ~OLCUC;
  14265. #endif /* OLCUC */
  14266. #ifdef CMSPAR
  14267.     tp.c_oflag &= ~CMSPAR;
  14268. #endif /* CMSPAR */
  14269.     tp.c_oflag &= ~OPOST;
  14270. #ifdef OXTABS
  14271.     tp.c_oflag &= ~OXTABS;
  14272. #endif /* OXTABS */
  14273. #ifdef COMMENT
  14274. #ifdef ONOCR
  14275.     tp.c_oflag &= ~ONOCR;        /* Maybe should be |=? */
  14276.     tp.c_oflag |= ONOCR;        /* makes no difference either way */
  14277. #endif /* ONOCR */
  14278. #endif /* COMMENT */
  14279. #ifdef ONOEOT
  14280.     tp.c_oflag &= ~ONOEOT;
  14281. #endif /* ONOEOT */
  14282. #ifdef ONLRET
  14283.     tp.c_oflag &= ~ONLRET;
  14284. #endif /* ONLRET */
  14285. #ifdef ONLCR
  14286.     tp.c_oflag &= ~ONLCR;
  14287. #endif /* ONLCR */
  14288. #ifdef OCRNL
  14289.     tp.c_oflag &= ~OCRNL;
  14290. #endif /* OCRNL */
  14291.  
  14292.     /* lflags */
  14293.     tp.c_lflag &= ~ECHO;
  14294. #ifdef ECHOE
  14295.     tp.c_lflag &= ~ECHOE;
  14296. #endif /* ECHOE */
  14297. #ifdef ECHONL
  14298.     tp.c_lflag &= ~ECHONL;
  14299. #endif /* ECHONL */
  14300. #ifdef ECHOPRT
  14301.     tp.c_lflag &= ~ECHOPRT;
  14302. #endif /* ECHOPRT */
  14303. #ifdef ECHOKE
  14304.     tp.c_lflag &= ~ECHOKE;
  14305. #endif /* ECHOKE */
  14306. #ifdef ECHOCTL
  14307.     tp.c_lflag &= ~ECHOCTL;
  14308. #endif /* ECHOCTL */
  14309. #ifdef XCASE
  14310.     tp.c_lflag &= ~XCASE;
  14311. #endif /* XCASE */
  14312. #ifdef ALTWERASE
  14313.     tp.c_lflag &= ~ALTWERASE;
  14314. #endif /* ALTWERASE */
  14315. #ifdef EXTPROC
  14316.     tp.c_lflag &= ~(ICANON|ISIG|IEXTEN|TOSTOP|FLUSHO|PENDIN|EXTPROC);
  14317. #else
  14318.     tp.c_lflag &= ~(ICANON|ISIG|IEXTEN|TOSTOP|FLUSHO|PENDIN);
  14319. #endif    /* EXTPROC */
  14320. #ifdef NOKERNINFO
  14321.     tp.c_lflag |= NOKERNINFO;
  14322. #endif    /* NOKERNINFO */
  14323. #ifndef COMMENT
  14324.     tp.c_lflag &= ~NOFLSH;        /* TRY IT THE OTHER WAY? */
  14325. #else
  14326.     tp.c_lflag |= NOFLSH;        /* No, this way is worse */
  14327. #endif /* COMMENT */
  14328.  
  14329.     /* cflags */
  14330.     tp.c_cflag &= ~(CSIZE|PARENB|PARODD);
  14331.     tp.c_cflag |= CS8|CREAD;
  14332.  
  14333. #ifdef MDMBUF
  14334.     tp.c_cflag &= ~(MDMBUF);
  14335. #else
  14336. #ifdef CCAR_OFLOW
  14337.     tp.c_cflag &= ~(CCAR_OFLOW);    /* two names for the same thing */
  14338. #endif /* CCAR_OFLOW */
  14339. #endif /* MDMBUF */
  14340.  
  14341. #ifdef CCTS_OFLOW
  14342.     tp.c_cflag &= ~(CCTS_OFLOW);
  14343. #endif /* CCTS_OFLOW */
  14344. #ifdef CDSR_OFLOW
  14345.     tp.c_cflag &= ~(CDSR_OFLOW);
  14346. #endif /* CDSR_OFLOW */
  14347. #ifdef CDTR_IFLOW
  14348.     tp.c_cflag &= ~(CDTR_IFLOW);
  14349. #endif /* CDTR_IFLOW */
  14350. #ifdef CRTS_IFLOW
  14351.     tp.c_cflag &= ~(CRTS_IFLOW);
  14352. #endif /* CRTS_IFLOW */
  14353. #ifdef CRTSXOFF
  14354.     tp.c_cflag &= ~(CRTSXOFF);
  14355. #endif /* CRTSXOFF */
  14356. #ifdef CRTSCTS
  14357.     tp.c_cflag &= ~(CRTSCTS);
  14358. #endif /* CRTSCTS */
  14359. #ifdef CLOCAL
  14360.     tp.c_cflag &= ~(CLOCAL);
  14361. #endif /* CLOCAL */
  14362. #ifdef CSTOPB
  14363.     tp.c_cflag &= ~(CSTOPB);
  14364. #endif /* CSTOPB */
  14365. #ifdef HUPCL
  14366.     tp.c_cflag &= ~(HUPCL);
  14367. #endif /* HUPCL */
  14368.  
  14369.     for (i = 0; i < NCCS; i++) {    /* No special characters */
  14370.     tp.c_cc[i] = 0;
  14371.     }
  14372. #ifdef VMIN
  14373.     tp.c_cc[VMIN] = 1;            /* But always wait for input */
  14374. #endif    /* VMIN */
  14375.     debug(F101,"pty_make_raw 3 c_cc[] NCCS","",NCCS);
  14376.     debug(F101,"pty_make_raw 3 iflags","",tp.c_iflag);
  14377.     debug(F101,"pty_make_raw 3 oflags","",tp.c_oflag);
  14378.     debug(F101,"pty_make_raw 3 lflags","",tp.c_lflag);
  14379.     debug(F101,"pty_make_raw 3 cflags","",tp.c_cflag);
  14380. #endif /* COMMENT */
  14381. #endif /* COMMENT */
  14382.  
  14383.     errno = 0;
  14384. #ifdef BSD44ORPOSIX            /* POSIX */
  14385.     x = tcsetattr(fd,TCSANOW,&tp);
  14386.     debug(F101,"pty_make_raw tcsetattr","",x);
  14387. #else
  14388. #ifdef ATTSV                /* AT&T UNIX */
  14389.     x = ioctl(fd,TCSETA,&tp);
  14390.     debug(F101,"pty_make_raw ioctl","",x);
  14391. #else
  14392.     x = stty(fd,&tp);            /* Traditional */
  14393.     debug(F101,"pty_make_raw stty","",x);
  14394. #endif /* ATTSV */
  14395. #endif /* BSD44ORPOSIX */
  14396.     debug(F101,"pty_make_raw errno","",errno);
  14397.  
  14398. #endif /* __NetBSD__ */
  14399. }
  14400.  
  14401. static int
  14402. pty_chk(fd) int fd; {
  14403.     int x, n = 0;
  14404.     errno = 0;
  14405. #ifdef FIONREAD
  14406.     x = ioctl(fd, FIONREAD, &n);    /* BSD and most others */
  14407.     ckmakmsg(msgbuf,500,
  14408.          "pty_chk ioctl FIONREAD errno=",
  14409.          ckitoa(errno),
  14410.          " count=",
  14411.          ckitoa(n));
  14412.     debug(F100,msgbuf,"",0);
  14413. #else
  14414. #ifdef RDCHK
  14415.     n = rdchk(fd);
  14416.     debug(F101,"pty_chk rdchk","",n);
  14417. #else
  14418.     n = 1;
  14419. #endif    /* RDCHK */
  14420. #endif    /* FIONREAD */
  14421.     return((n > -1) ? n : 0);
  14422. }
  14423.  
  14424. static int
  14425. pty_get_status(fd,pid) int fd; PID_T pid; {
  14426.     int x, status = -1;
  14427.     PID_T w;
  14428.  
  14429.     debug(F101,"pty_get_status fd","",fd);
  14430.     debug(F101,"pty_get_status pid","",pid);
  14431.  
  14432.     if (pexitstat > -1)
  14433.       return(pexitstat);
  14434.  
  14435. #ifdef COMMENT
  14436.     /* Not only unnecessary but harmful */
  14437.     errno = 0;
  14438.     x = kill(pty_fork_pid,0);
  14439.     debug(F101,"pty_get_status kill value","",x);
  14440.     debug(F101,"pty_get_status kill errno","",errno);
  14441.     if (x > -1 && errno != ESRCH)
  14442.       return(-1);            /* Fork still there */
  14443.     /* Fork seems to be gone */
  14444. #endif    /* COMMENT */
  14445.  
  14446.     errno = 0;
  14447.     x = waitpid(pty_fork_pid,&status,WNOHANG);
  14448.     debug(F111,"pty_get_status waitpid",ckitoa(errno),x);
  14449.     if (x <= 0 && errno == 0) {
  14450.     debug(F101,"pty_get_status waitpid return","",-1);
  14451.     return(-1);
  14452.     }
  14453.     if (x > 0) {
  14454.     if (x != pty_fork_pid)
  14455.       debug(F101,
  14456.         "pty_get_status waitpid pid doesn't match","",pty_fork_pid); 
  14457.     debug(F101,"pty_get_status waitpid status","",status);
  14458.     debug(F101,"pty_get_status waitpid errno","",errno);
  14459.     if (WIFEXITED(status)) {
  14460.         debug(F100,"pty_get_status WIFEXITED","",0);
  14461.         status = WEXITSTATUS(status);
  14462.         debug(F101,"pty_get_status fork exit status","",status);
  14463. #ifdef COMMENT
  14464.         end_pty();
  14465. #endif    /* COMMENT */
  14466.         close(fd);
  14467.         pexitstat = status;
  14468.     } else {
  14469.         debug(F100,"pty_get_status waitpid unexpected status","",0);
  14470.     }
  14471.     }
  14472.     debug(F101,"pty_get_status return status","",status);
  14473.     return(status);
  14474. }
  14475.  
  14476. /* t t p t y c m d  --  Run command on pty and forward to net */
  14477.  
  14478. /*
  14479.   Needed for running external protocols on secure connections.
  14480.   For example, if C-Kermit has made an SSL/TLS or Kerberos Telnet
  14481.   connection, and then needs to transfer a file with Zmodem, which is
  14482.   an external program, this routine reads Zmodem's output, encrypts it,
  14483.   and then forwards it out the connection, and reads the encrypted data
  14484.   stream coming in from the connection, decrypts it, and forwards it to
  14485.   Zmodem.
  14486.  
  14487.   Works like a TCP/IP port forwarder except one end is a pty rather
  14488.   than a socket, which introduces some complications:
  14489.  
  14490.    . On most platforms, select() always indicates the output side of
  14491.      the pty has characters waiting to be read, even when it doesn't,
  14492.      even when the pty process has already exited.
  14493.  
  14494.    . Nonblocking reads must be used on the pty, because there is no
  14495.      way on certain platforms (e.g. NetBSD) to find out how many characters
  14496.      are available to be read (the FIONREAD ioctl always says 0).  The code
  14497.      also allows for blocking reads (if O_NDELAY and O_NONBLOCK are not
  14498.      defined, or if PTY_NO_NDELAY is defined), but on some platforms this can
  14499.      result in single-byte reads and writes (NetBSD again).
  14500.  
  14501.    . Testing for "EOF" on the pty is problematic.  select() never gives
  14502.      any indication.  After the pty process has exited and the fork has
  14503.      disappeared, read() can still return with 0 bytes read but without an
  14504.      error (NetBSD); no known test on the pty file descriptor will indicate
  14505.      that it is no longer valid.  The process ID of the pty fork can be
  14506.      tested on some platforms (NetBSD, luckily) but not others (Solaris,
  14507.      Linux).
  14508.  
  14509.   On the network side, we use ttinc() and ttoc(), which, for network 
  14510.   connections, handle any active security methods.
  14511.  
  14512.   Call with s = command.
  14513.   Returns 0 on failure, 1 on success.
  14514.   fdc - December 2006 - August 2007.
  14515.  
  14516.   NOTE: This code defaults to nonblocking reads if O_NDELAY or O_NONBLOCK are
  14517.   defined in the header files, which should be true of every recent Unix
  14518.   platform.  If this causes trouble somewhere, define PTY_NO_NDELAY, e.g. when
  14519.   building C-Kermit:
  14520.  
  14521.     touch ckutio.c
  14522.     make platformname KFLAGS=-DPTY_NO_NODELAY
  14523. */
  14524. static int have_pty = 0;        /* Do we have a pty? */
  14525.  
  14526. static SIGTYP (*save_sigchld)() = NULL;    /* For catching SIGCHLD */
  14527.  
  14528. static VOID
  14529. sigchld_handler(sig) int sig; {
  14530.     have_pty = 0;            /* We don't have a pty */
  14531. #ifdef DEBUG
  14532.     if (save_sigchld) {
  14533.     (VOID) signal(SIGCHLD,save_sigchld);
  14534.     save_sigchld = NULL;
  14535.     }
  14536.     if (deblog) {
  14537.     debug(F100,"**************","",0);
  14538.     debug(F100,"SIGCHLD caught","",0);
  14539.     debug(F100,"**************","",0);
  14540.     }
  14541. #endif    /* DEBUG */
  14542. }
  14543. #define HAVE_IAC 1
  14544. #define HAVE_CR  2
  14545.  
  14546. int
  14547. ttptycmd(s) char *s; {
  14548.     CHAR tbuf[PTY_TBUF_SIZE];        /* Read from net, write to pty */
  14549.     int tbuf_avail = 0;            /* Pointers for tbuf */
  14550.     int tbuf_written = 0;
  14551.     static int in_state = 0;        /* For TELNET IAC and NVT in */
  14552.     static int out_prev = 0;        /* Simpler scheme for out */
  14553.  
  14554.     CHAR pbuf[PTY_PBUF_SIZE];        /* Read from pty, write to net */
  14555.     CHAR dbuf[PTY_PBUF_SIZE + PTY_PBUF_SIZE + 1]; /* Double-size buffer */
  14556.     int pbuf_avail = 0;            /* Pointers for pbuf */
  14557.     int pbuf_written = 0;
  14558.  
  14559.     int ptyfd = -1;            /* Pty file descriptor */
  14560.     int have_net = 0;            /* We have a network connection */
  14561.     int pty_err = 0;            /* Got error on pty */
  14562.     int net_err = 0;            /* Got error on net */
  14563.     int status = -1;            /* Pty process exit status */
  14564.     int rc = 0;                /* Our return code */
  14565.  
  14566.     int x1 = 0, x2 = 0;            /* Workers... */
  14567.     int c, n, m, t, x;            /* Workers */
  14568.  
  14569.     long seconds_to_wait = 0L;        /* select() timeout */
  14570.     struct timeval tv, *tv2;        /* For select() */
  14571. #ifdef INTSELECT
  14572.     int in, out, err;            /* For select() */
  14573. #else
  14574.     fd_set in, out, err;
  14575. #endif /* INTSELECT */
  14576.     int nfds = 0;            /* For select() */
  14577.  
  14578.     int pset = 0, tset = 0, pnotset = 0, tnotset = 0; /* stats/debuggin only */
  14579.     int read_net_bytes = 0;        /* Stats */
  14580.     int write_net_bytes = 0;        /* Stats */
  14581.     int read_pty_bytes = 0;        /* Stats */
  14582.     int write_pty_bytes = 0;        /* Stats */
  14583.     int is_tn = 0;            /* TELNET protocol is active */
  14584.  
  14585.     int masterfd = -1;
  14586.     int slavefd = -1;
  14587. #ifndef USE_CKUPTY_C
  14588.     struct termios term;
  14589.     struct winsize twin;
  14590.     struct stringarray * q;
  14591.     char ** args = NULL;
  14592. #endif /* USE_CKUPTY_C */
  14593.  
  14594.     in_state = 0;            /* No previous character yet */
  14595.  
  14596.     if (ttyfd == -1) {
  14597.     printf("?Sorry, communication channel is not open\n");
  14598.     return(0);
  14599.     } else {
  14600.     have_net = 1;
  14601.     }
  14602.     if (nopush) {
  14603.     debug(F100,"ttptycmd fail: nopush","",0);
  14604.     return(0);
  14605.     }
  14606.     if (!s) s = "";            /* Defense de bogus arguments */
  14607.     if (!*s) return(0);
  14608.     pexitstat = -1;            /* Fork process exit status */
  14609.  
  14610. #ifdef TNCODE
  14611.     is_tn = (xlocal && netconn && IS_TELNET()) || /* Telnet protocol active */
  14612.         (!xlocal && sstelnet);
  14613. #endif /* TNCODE */
  14614.  
  14615.     debug(F110,"ttptycmd command",s,0);
  14616.     debug(F101,"ttptycmd ttyfd","",ttyfd);
  14617.     debug(F101,"ttptycmd is_tn","",is_tn);
  14618.     debug(F101,"ttptycmd ckermit pid","",getpid());
  14619.  
  14620. #ifdef USE_CKUPTY_C
  14621.     /* Call ckupty.c module to get and set up the pty fork */
  14622.     /* fc 1 == "run an external protocol" */
  14623.     debug(F100,"ttptycmd using ckupty.c","",0);
  14624.     if (do_pty(&ptyfd,s,1) < 0) {    /* Start the command on a pty */
  14625.     debug(F100,"ttptycmd do_pty fails","",0);
  14626.     return(0);
  14627.     }
  14628.     masterfd = ptyfd;
  14629.     pty_master_fd = ptyfd;
  14630. #ifdef COMMENT
  14631.     slavefd = pty_slave_fd;        /* This is not visible to us */
  14632. #endif /* COMMENT */
  14633.     debug(F111,"ttptycmd ptyfd","USE_CKUPTY_C",ptyfd);
  14634.     debug(F111,"ttptycmd masterfd","USE_CKUPTY_C",masterfd);
  14635.     debug(F111,"ttptycmd fork pid","USE_CKUPTY_C",pty_fork_pid);
  14636. #ifndef SOLARIS
  14637.     /* "ioctl inappropriate on device" for pty master */
  14638.     pty_make_raw(masterfd);
  14639. #endif /* SOLARIS */
  14640.  
  14641. #else /* USE_CKUPTY_C */
  14642.  
  14643.     debug(F100,"ttptycmd OPENPTY","",0);
  14644.     if (tcgetattr(0, &term) == -1) {    /* Get controlling terminal's modes */
  14645.     perror("tcgetattr");
  14646.     return(0);
  14647.     }
  14648.     if (ioctl(0, TIOCGWINSZ, (char *) &twin) == -1) { /* and window size */
  14649.     perror("ioctl TIOCGWINSZ");
  14650.     return(0);
  14651.     }
  14652.     if (openpty(&masterfd, &slavefd, NULL, NULL, NULL) == -1) {
  14653.     debug(F101,"ttptycmd openpty failed errno","",errno);
  14654.     perror("opentpy");
  14655.     return(0);
  14656.     }
  14657.     debug(F101,"ttptycmd openpty masterfd","",masterfd);
  14658.     debug(F101,"ttptycmd openpty slavefd","",slavefd);
  14659.     pty_master_fd = masterfd;
  14660.     pty_slave_fd = slavefd;
  14661.     debug(F101,"ttptycmd openpty pty_master_fd","",pty_master_fd);
  14662.  
  14663.     /* Put pty master in raw mode but let forked app control the slave */
  14664.     pty_make_raw(masterfd);
  14665.  
  14666. #ifdef COMMENT
  14667. #ifdef TIOCREMOTE
  14668.     /* TIOCREMOTE,0 = disable all termio processing */
  14669.     x = ioctl(masterfd, TIOCREMOTE, 1);
  14670.     debug(F111,"ttptycmd ioctl TIOCREMOTE",ckitoa(x),errno);
  14671. #endif    /* TIOCREMOTE */
  14672. #ifdef TIOCTTY
  14673.     /* TIOCTTY,0 = disable all termio processing */
  14674.     x = ioctl(masterfd, TIOCTTY, 0);
  14675.     debug(F111,"ttptycmd ioctl TIOCTTY",ckitoa(x),errno);
  14676. #endif    /* TIOCTTY */
  14677. #endif /* COMMENT */
  14678.  
  14679.     have_pty = 1;            /* We have an open pty */
  14680.     save_sigchld = signal(SIGCHLD, sigchld_handler); /* Catch fork quit */
  14681.  
  14682.     pty_fork_pid = fork();        /* Make fork for external protocol */
  14683.     debug(F101,"ttptycmd pty_fork_pid","",pty_fork_pid);
  14684.     if (pty_fork_pid == -1) {
  14685.     perror("fork");
  14686.     return(0);
  14687.     } else if (pty_fork_pid == 0) {    /* In new fork */
  14688.     int x;
  14689.     debug(F101,"ttptycmd new fork pid","",getpid());
  14690.     close(masterfd);        /* Slave quarters no masters allowed */
  14691.     x = setsid();
  14692.     debug(F101,"ttptycmd new fork setsid","",x);
  14693.     if (x == -1) {
  14694.         perror("ttptycmd setsid");
  14695.         exit(1);
  14696.     }
  14697.     signal(SIGINT,SIG_IGN);        /* Let upper fork catch this */
  14698.     
  14699. #ifdef COMMENT
  14700. #ifdef TIOCSCTTY
  14701.     /* Make pty the controlling terminal for the process */
  14702.     /* THIS CAUSES AN INFINITE SIGWINCH INTERRUPT LOOP */
  14703.     x = ioctl(slavefd, TIOCSCTTY, NULL);
  14704.     debug(F101,"ttptycmd TIOCSCTTY","",x);
  14705. #endif    /* TIOCSCTTY */
  14706. #endif    /* COMMENT */
  14707.  
  14708.     /* Initialize slave pty modes and size to those of our terminal */
  14709.     if (tcsetattr(slavefd, TCSANOW, &term) == -1) {
  14710.         perror("ttptycmd tcsetattr");
  14711.         exit(1);
  14712.     }
  14713.     if (ioctl(slavefd, TIOCSWINSZ, &twin) == -1) {
  14714.         perror("ttptycmd ioctl");
  14715.         exit(1);
  14716.     }
  14717. #ifdef COMMENT
  14718. #ifdef TIOCNOTTY
  14719.     /* Disassociate this process from its terminal */
  14720.     /* THIS HAS NO EFFECT */
  14721.     x = ioctl(slavefd, TIOCNOTTY, NULL);
  14722.     debug(F101,"ttptycmd TIOCNOTTY","",x);
  14723. #endif    /* TIOCNOTTY */
  14724. #endif    /* COMMENT */
  14725.  
  14726. #ifdef COMMENT
  14727. #ifdef SIGTTOU    
  14728.     /* Ignore terminal output interrupts */
  14729.     /* THIS HAS NO EFFECT */
  14730.     debug(F100,"ttptycmd ignoring SIGTTOU","",0);
  14731.     signal(SIGTTOU, SIG_IGN);
  14732. #endif    /* SIGTTOU */
  14733. #ifdef SIGTSTP    
  14734.     /* Ignore terminal output interrupts */
  14735.     /* THIS HAS NO EFFECT */
  14736.     debug(F100,"ttptycmd ignoring SIGTSTP","",0);
  14737.     signal(SIGTSTP, SIG_IGN);
  14738. #endif    /* SIGTSTP */
  14739. #endif    /* COMMENT */
  14740.  
  14741.     pty_make_raw(slavefd);        /* Put it in rawmode */
  14742.  
  14743.     errno = 0;
  14744.     if (dup2(slavefd, STDIN_FILENO) != STDIN_FILENO ||
  14745.         dup2(slavefd, STDOUT_FILENO) != STDOUT_FILENO) {
  14746.         debug(F101,"ttptycmd new fork dup2 error","",errno);
  14747.         perror("ttptycmd dup2");
  14748.         exit(1);
  14749.     }
  14750.     debug(F100,"ttptycmd new fork dup2 ok","",0);
  14751.  
  14752.     /* Parse external protocol command line */
  14753.     q = cksplit(1,0,s,NULL,"\\%[]&$+-/=*^_@!{}/<>|.#~'`:;?",7,0,0);
  14754.     if (!q) {
  14755.         debug(F100,"ttptycmd cksplit failed","",0);
  14756.         exit(1);
  14757.     } else {
  14758.         int i, n;
  14759.         debug(F100,"ttptycmd cksplit ok","",0);
  14760.         n = q->a_size;
  14761.         args = q->a_head + 1;
  14762.         for (i = 0; i <= n; i++) {
  14763.         if (!args[i]) {
  14764.             break;
  14765.         } else {
  14766.             /* sometimes cksplit() doesn't terminate the list */
  14767.             if ((i == n) && args[i]) {
  14768.             if ((int)strlen(args[i]) == 0)
  14769.               makestr(&(args[i]),NULL);
  14770.             }
  14771.         }
  14772.         }        
  14773.     }
  14774. #ifdef COMMENT
  14775. /*
  14776.   Putting the slave pty in rawmode should not be necessary because the
  14777.   external protocol program is supposed to do that itself.  Yet doing this
  14778.   here cuts down on Zmodem binary-file transmission errors by 30-50% but
  14779.   still doesn't eliminate them.
  14780. */
  14781.     pty_make_raw(STDIN_FILENO);
  14782.     pty_make_raw(STDOUT_FILENO);
  14783. #endif /* COMMENT */
  14784.  
  14785.     debug(F100,"ttptycmd execvp'ing external protocol","",0);
  14786.     execvp(args[0],args);
  14787.     perror("execvp failed");
  14788.     debug(F101,"ttptycmd execvp failed","",errno);
  14789.     close(slavefd);
  14790.     exit(1);
  14791.     } 
  14792.     /* (there are better ways to do this...) */
  14793.     msleep(1000);          /* Make parent wait for child to be ready */
  14794.     ptyfd = masterfd;            /* We talk to the master */
  14795.  
  14796. #endif /* USE_CKUPTY_C */
  14797.  
  14798.     debug(F101,"ttptycmd ptyfd","",ptyfd);
  14799.     if (ptyfd < 0) {
  14800.     printf("?Failure to get pty\n");
  14801.     return(-9);
  14802.     }
  14803.     have_pty = 1;          /* We have an open pty or we wouldn't he here */
  14804.  
  14805.     debug(F101,"ttptycmd PTY_PBUF_SIZE","",PTY_PBUF_SIZE);
  14806.     debug(F101,"ttptycmd PTY_TBUF_SIZE","",PTY_TBUF_SIZE);
  14807.  
  14808. #ifdef PTY_USE_NDELAY
  14809.     /* 
  14810.        NOTE: If select() and ioctl(ptyfd,FIONREAD,&n) return true indications
  14811.        on the pty, we don't need nonblocking reads.  Performance of either
  14812.        method seems to be about the same, so use whatever works.
  14813.     */
  14814.     errno = 0;
  14815.     x = fcntl(ptyfd,F_SETFL,fcntl(ptyfd,F_GETFL, 0)|O_NDELAY);
  14816.     ckmakmsg(msgbuf,500,
  14817.          "ttptycmd set O_NDELAY errno=",
  14818.          ckitoa(errno),
  14819.          " fcntl=",
  14820.          ckitoa(x));
  14821.     debug(F100,msgbuf,"",0);
  14822. #endif /* PTY_USE_NDELAY */
  14823.  
  14824. #ifdef COMMENT
  14825. /* Not necessary, the protocol module already did this */
  14826.  
  14827. #ifdef USE_CFMAKERAW
  14828.     if (tcgetattr(ttyfd, &term) > -1) {
  14829.     cfmakeraw(&term);
  14830.     debug(F101,"ttptycmd net cfmakeraw errno","",errno);
  14831.     x tcsetattr(ttyfd, TCSANOW, &term);
  14832.     debug(F101,"ttptycmd net tcsetattr","",x);
  14833.     debug(F101,"ttptycmd net tcsetattr","",errno);
  14834.     }
  14835. #else
  14836.     if (local)                /* Put network connection in */
  14837.       ttpkt(ttspeed,ttflow,ttprty);    /* "packet mode". */
  14838.     else
  14839.       conbin((char)escchr);        /* OR... pty_make_raw(0) */
  14840. #endif /* USE_CFMAKERAW */
  14841. #endif /* COMMENT */
  14842.  
  14843. #ifdef TNCODE
  14844.     if (is_tn) {
  14845.       debug(F101,"<<< ttptycmd TELOPT_ME_BINARY","",TELOPT_ME(TELOPT_BINARY));
  14846.       debug(F101,"<<< ttptycmd TELOPT_U_BINARY","",TELOPT_U(TELOPT_BINARY));
  14847.     }
  14848. #endif /* TNCODE */
  14849.  
  14850.     debug(F101,"ttptycmd entering loop - seconds_to_wait","",seconds_to_wait);
  14851.  
  14852.     while (have_pty || have_net) {
  14853.     FD_ZERO(&in);            /* Initialize select() structs */
  14854.     FD_ZERO(&out);
  14855.     FD_ZERO(&err);            /* (not used because useless) */
  14856.     nfds = -1;
  14857.  
  14858.     debug(F101,"ttptycmd loop top have_pty","",have_pty);
  14859.     debug(F101,"ttptycmd loop top have_net","",have_net);
  14860.  
  14861.     /* Pty is open and we have room to read from it? */
  14862.     if (have_pty && pbuf_avail < PTY_PBUF_SIZE) {
  14863.         debug(F100,"ttptycmd FD_SET ptyfd in","",0);
  14864.             FD_SET(ptyfd, &in);
  14865.         nfds = ptyfd;
  14866.         }
  14867.     /* Network is open and we have room to read from it? */
  14868.         if (have_net && have_pty && tbuf_avail < PTY_TBUF_SIZE) {
  14869.         debug(F100,"ttptycmd FD_SET ttyfd in","",0);
  14870.             FD_SET(ttyfd, &in);
  14871.         if (ttyfd > nfds) nfds = ttyfd;
  14872.         }
  14873.     /* Pty is open and we have stuff to write to it? */
  14874.         if (have_pty && tbuf_avail - tbuf_written > 0) {
  14875.         debug(F100,"ttptycmd FD_SET ptyfd out","",0);
  14876.             FD_SET (ptyfd, &out);
  14877.         if (ptyfd > nfds) nfds = ptyfd;
  14878.         }
  14879.     /* Net is open and we have stuff to write to it? */
  14880.     debug(F101,"ttptycmd pbuf_avail-pbuf_written","",
  14881.           pbuf_avail - pbuf_written);
  14882.         if (have_net && pbuf_avail - pbuf_written > 0) {
  14883.         debug(F100,"ttptycmd FD_SET ttyfd out","",0);
  14884.             FD_SET (ttyfd, &out);
  14885.         if (ttyfd > nfds) nfds = ttyfd;
  14886.         }
  14887.     /* We don't use err because it's not really for errors, */
  14888.     /* but for out of band data on the TCP socket, which, if it is */
  14889.     /* to be handled at all, is handled in the tt*() routines */
  14890.  
  14891.     nfds++;                /* 0-based to 1-based */
  14892.     debug(F101,"ttptycmd nfds","",nfds);
  14893.     if (!nfds) {
  14894.         debug(F100,"ttptycmd NO FDs set for select","",0);
  14895.         if (have_pty) {
  14896.         /* This is not right -- sleeping won't accomplish anything */
  14897.         debug(F101,"ttptycmd msleep","",100);
  14898.         msleep(100);        
  14899.         } else {
  14900.         debug(F100,"ttptycmd no pty - quitting loop","",0);
  14901.         break;
  14902.         }
  14903.     }
  14904.     errno = 0;
  14905.  
  14906.     if (seconds_to_wait > 0L) {    /* Timeout in case nothing happens */
  14907.         tv.tv_sec = seconds_to_wait; /* for a long time */
  14908.         tv.tv_usec = 0L;        
  14909.         tv2 = &tv;
  14910.         } else {
  14911.             tv2 = NULL;
  14912.     }
  14913.     x = select(nfds, &in, &out, NULL, tv2);
  14914.     debug(F101,"ttptycmd select","",x);
  14915.     if (x < 0) {
  14916.         if (errno == EINTR)
  14917.           continue;
  14918.         debug(F101,"ttptycmd select error","",errno);
  14919.         break;
  14920.     }
  14921.     if (x == 0) {
  14922.         debug(F101,"ttptycmd +++ select timeout","",seconds_to_wait); 
  14923.         if (have_pty) {
  14924.         status = pty_get_status(ptyfd,pty_fork_pid);
  14925.         debug(F101,"ttptycmd pty_get_status A","",status);
  14926.         if (status > -1) pexitstat = status;
  14927.         have_pty = 0;
  14928.         }
  14929.         break;
  14930.     }
  14931.     /* We want to handle any pending writes first to make room */
  14932.     /* for new incoming. */
  14933.  
  14934.     if (FD_ISSET(ttyfd, &out)) {    /* Can write to net? */
  14935.         CHAR * s;
  14936.         s = pbuf + pbuf_written;    /* Current spot for sending */
  14937. #ifdef TNCODE
  14938.         if (is_tn) {        /* ttol() doesn't double IACs */
  14939.         CHAR c;            /* Rewrite string with IACs doubled */
  14940.         int i;
  14941.         s = pbuf + pbuf_written; /* Source */
  14942.         x = 0;              /* Count */
  14943.         for (i = 0; i < pbuf_avail - pbuf_written; i++) {
  14944.             c = s[i];        /* Next character */
  14945.             if (c == IAC) {    /* If it's IAC */
  14946.             dbuf[x++] = c;    /* put another one */
  14947.             debug(F000,">>> QUOTED IAC","",c);
  14948.             } else if (c != 0x0a && out_prev == 0x0d) {    /* Bare CR */
  14949.             if (!TELOPT_ME(TELOPT_BINARY)) { /* NVT rule */
  14950.                 c = 0x00;
  14951.                 dbuf[x++] = c;
  14952.                 debug(F000,">>> CR-NUL","",c);
  14953.             }            
  14954.             }
  14955.             dbuf[x++] = c;    /* Copy and count it */
  14956.             debug(F000,">>> char",ckitoa(in_state),c);
  14957.             out_prev = c;
  14958.         }
  14959.         s = dbuf;        /* New source */
  14960.         } else
  14961. #endif /* TNCODE */
  14962.           x = pbuf_avail - pbuf_written; /* How much to send */
  14963.  
  14964.         debug(F101,"ttptycmd bytes to send","",x);
  14965.         x = ttol(s, x);
  14966.         debug(F101,">>> ttol","",x);
  14967.         if (x < 0) {
  14968.         net_err++;
  14969.         debug(F111,"ttptycmd ttol error",ckitoa(x),errno);
  14970.         x = 0;
  14971.         }
  14972.         write_net_bytes += x;
  14973.         pbuf_written += x;
  14974.     }
  14975.     if (FD_ISSET(ptyfd, &out)) {    /* Can write to pty? */
  14976.         debug(F100,"ttptycmd FD_ISSET ptyfd out","",0);
  14977.         errno = 0;
  14978. #ifndef COMMENT
  14979.         x = write(ptyfd,tbuf + tbuf_written,tbuf_avail - tbuf_written);
  14980. #else
  14981.         /* Byte loop to rule out data overruns in the pty */
  14982.         /* (it makes no difference) */
  14983.         {
  14984.         char *p = tbuf+tbuf_written;
  14985.         int n = tbuf_avail - tbuf_written;
  14986.         for (x = 0; x < n; x++) {
  14987.             msleep(10);
  14988.             if (write(ptyfd,&(p[x]),1) < 0)
  14989.               break;
  14990.         }
  14991.         }
  14992. #endif /* COMMENT */
  14993.         debug(F111,"ttptycmd ptyfd write",ckitoa(errno),x);
  14994.         if (x > 0) {
  14995.         tbuf_written += x;
  14996.         write_pty_bytes += x;
  14997.         } else {
  14998.         x = 0;
  14999.         pty_err++;
  15000.         if (pexitstat < 0) {
  15001.             status = pty_get_status(ptyfd,pty_fork_pid);
  15002.             debug(F101,"ttptycmd pty_get_status B","",status);
  15003.             if (status > -1) pexitstat = status;
  15004.             have_pty = 0;
  15005.         }
  15006.         debug(F100,"ttptycmd +++ ptyfd write error","",0);
  15007.         }
  15008.     }
  15009.     if (FD_ISSET(ttyfd, &in)) {    /* Can read from net? */
  15010.         tset++;
  15011.         debug(F100,"ttptycmd FD_ISSET ttyfd in","",0);
  15012.         n = in_chk(1,ttyfd);
  15013.         debug(F101,"ttptycmd in_chk(ttyfd)","",n); 
  15014.         if (n < 0 || ttyfd == -1) {
  15015.         debug(F101,"ttptycmd +++ ttyfd errno","",errno);
  15016.         net_err++;
  15017.         } else if (n > 0) {
  15018.         if (n > PTY_TBUF_SIZE - tbuf_avail)
  15019.           n = PTY_TBUF_SIZE - tbuf_avail;
  15020.         debug(F101,"ttptycmd net read size adjusted","",n); 
  15021.         if (xlocal && netconn) {
  15022.             /*
  15023.               We have to use a byte loop here because ttxin()
  15024.               does not decrypt or, for that matter, handle Telnet.
  15025.             */
  15026.             int c;
  15027.             CHAR * p;
  15028.             p = tbuf + tbuf_avail;
  15029.             for (x = 0; x < n; x++) {
  15030.             if ((c = ttinc(0)) < 0)
  15031.               break;
  15032.             if (!is_tn) {    /* Not Telnet - keep all bytes */
  15033.                 *p++ = (CHAR)c;
  15034.                 debug(F000,"<<< char","",c);
  15035. #ifdef TNCODE
  15036.             } else {    /* Telnet - must handle IAC and NVT */
  15037.                 debug(F000,"<<< char",ckitoa(in_state),c);
  15038.                 switch (c) {
  15039.                   case 0x00: /* NUL */
  15040.                 if (in_state == HAVE_CR) {
  15041.                     debug(F000,"<<< SKIP","",c);
  15042.                 } else {
  15043.                     *p++ = c;
  15044.                     debug(F000,"<<< Keep","",c);
  15045.                 }
  15046.                 in_state = 0;
  15047.                 break;
  15048.                   case 0x0d: /* CR */
  15049.                 if (!TELOPT_U(TELOPT_BINARY))
  15050.                   in_state = HAVE_CR;
  15051.                 *p++ = c;
  15052.                 debug(F000,"<<< Keep","",c);
  15053.                 break;
  15054. #ifdef COMMENT
  15055.                   case 0x0f: /* Ctrl-O */
  15056.                   case 0x16: /* Ctrl-V */
  15057.                 *p++ = 0x16;
  15058.                 *p++ = c;
  15059.                 debug(F000,"<<< QUOT","",c);
  15060.                 break;
  15061. #endif /* COMMENT */
  15062.                   case 0xff: /* IAC */
  15063.                 if (in_state == HAVE_IAC) {
  15064.                     debug(F000,"<<< KEEP","",c);
  15065.                     *p++ = c;
  15066.                     in_state = 0;
  15067.                 } else {
  15068.                     debug(F000,"<<< SKIP","",c);
  15069.                     in_state = HAVE_IAC;
  15070.                 }
  15071.                 break;
  15072.                   default:    /* All others */
  15073.                 if (in_state == HAVE_IAC) {
  15074. #ifdef COMMENT
  15075. /*
  15076.   tn_doop() will consume an unknown number of bytes and we'll overshoot
  15077.   the for-loop.  The only Telnet command I've ever seen arrive here is
  15078.   a Data Mark, which comes when the remote protocol exits and the remote
  15079.   job returns to its shell prompt.  On the assumption it's a 1-byte command,
  15080.   we don't write out the IAC or the command, and we clear the state.  If
  15081.   we called tn_doop() we'd have no way of knowing how many bytes it took
  15082.   from the input stream.
  15083. */
  15084.                     int xx;
  15085.                     xx = tn_doop((CHAR)c,duplex,ttinc);
  15086.                     debug(F111,"<<< DOOP",ckctoa(c),xx);
  15087. #else
  15088.                     debug(F101,"<<< DOOP","",c);
  15089. #endif    /* COMMENT */
  15090.                     in_state = 0;
  15091.                 } else {
  15092.                     *p++ = c;
  15093.                     debug(F000,"<<< keep","",c);
  15094.                     in_state = 0;
  15095.                 }
  15096.                 }
  15097. #endif    /* TNCODE */
  15098.             }
  15099.             }
  15100.             ckmakmsg(msgbuf,500,
  15101.                  "ttptycmd read net [ttinc loop] errno=",
  15102.                  ckitoa(errno),
  15103.                  " count=",
  15104.                  ckitoa(x));
  15105.             debug(F100,msgbuf,"",0);
  15106.         } else {
  15107.             x = ttxin(n,tbuf+tbuf_avail);
  15108.             debug(F101,"ttptycmd ttxin x","",x); 
  15109.         }
  15110.  
  15111.         if (x < 0) {
  15112.             debug(F101,"ttptycmd read net error","",x);
  15113.             net_err++;
  15114.         }
  15115.         tbuf_avail += x;
  15116.         read_net_bytes += x;
  15117.         }
  15118.  
  15119.     } else
  15120.       tnotset++;
  15121.  
  15122.     if (FD_ISSET(ptyfd, &in)) {    /* Read from pty? */
  15123.         pset++;
  15124.         debug(F100,"ttptycmd FD_ISSET ptyfd in","",0);
  15125. #ifdef PTY_USE_NDELAY
  15126.         n = PTY_PBUF_SIZE;
  15127. #else
  15128.         /*
  15129.           This does not work on nonblocking channels
  15130.           on certain platforms such as NetBSD.
  15131.         */
  15132.         n = pty_chk(ptyfd);
  15133. #endif /* PTY_USE_NDELAY */
  15134.         debug(F101,"ttptycmd pty_chk() n","",n); 
  15135.  
  15136.         if (n < 0)
  15137.           n = 0;
  15138.         if (n > 0) {
  15139.         if (n > PTY_PBUF_SIZE - pbuf_avail)
  15140.           n = PTY_PBUF_SIZE - pbuf_avail;
  15141.         debug(F101,"ttptycmd pty read size adjusted","",n); 
  15142.         errno = 0;
  15143.         x = read(ptyfd,pbuf+pbuf_avail,n);
  15144. #ifdef DEBUG
  15145.         if (deblog) {
  15146.             ckmakmsg(msgbuf,500,
  15147.                  "ttptycmd read pty errno=",
  15148.                  ckitoa(errno),
  15149.                  " count=",
  15150.                  ckitoa(x));
  15151.             debug(F100,msgbuf,"",0);
  15152.         }
  15153. #endif    /* DEBUG */
  15154.  
  15155.         if (x < 0 && errno == EAGAIN)
  15156.           x = 0;
  15157.  
  15158.         if (x < 0) {        /* This works on Solaris and Linux */
  15159.             pty_err++;        /* but not NetBSD */
  15160.             debug(F100,"TERMINATION TEST A","",0);
  15161. #ifdef COMMENT
  15162.             if (errno == EIO)
  15163.               rc = 1;
  15164. #endif    /* COMMENT */
  15165.             if (pexitstat < 0) {
  15166.             status = pty_get_status(ptyfd,pty_fork_pid);
  15167.             debug(F101,"ttptycmd pty_get_status C","",status);
  15168.             if (status > -1) pexitstat = status;
  15169.             }
  15170.             have_pty = 0;
  15171.             x = 0;
  15172.         }
  15173.         if (x == 0 && !pty_err) { /* This works on NetBSD but */
  15174.             debug(F100,"TERMINATION TEST B","",0);
  15175.             status = pexitstat > -1 ? pexitstat :
  15176.             pty_get_status(ptyfd,pty_fork_pid);
  15177.             debug(F101,"ttptycmd pty_get_status D","",status);
  15178.             if (status > -1) {
  15179.             pexitstat = status;
  15180.             pty_err++;
  15181.             have_pty = 0;
  15182.             } else {        /* Select() lied */
  15183.             pty_err = 0;    /* pty still there but has nothing */
  15184.             msleep(100);    /* sleep a bit */
  15185.             }
  15186.             x = 0;
  15187.         } 
  15188.         /* Hopefully the next two are no longer needed... */
  15189.         if (!pty_err && (
  15190. #ifndef PTY_USE_NDELAY
  15191.             x < 1 || errno
  15192. #else
  15193.             errno != 0 && errno != EAGAIN
  15194. #endif /* PTY_USE_NDELAY */
  15195.             )) {
  15196.             debug(F100,"TERMINATION TEST C","",0);
  15197.             pty_err++;
  15198.             debug(F101,"ttptycmd SET pty_err","",pty_err);
  15199.             if (errno == EIO)    /* errno == EIO is like EOF */
  15200.               rc = 1;
  15201.             if (x < 0)
  15202.               x = 0;
  15203.         }
  15204. #ifdef COMMENT
  15205. #ifdef DEBUG
  15206.         if (deblog) {
  15207.             pbuf[pbuf_avail + x] = '\0';
  15208.             debug(F111,"ttptycmd added to pty buffer",
  15209.               pbuf+pbuf_avail,x);
  15210.         }
  15211. #endif    /* DEBUG */
  15212. #endif    /* COMMENT */
  15213.         pbuf_avail += x;
  15214.         read_pty_bytes += x;
  15215.         } else {            /* n == 0 with blocking reads */
  15216.         debug(F100,
  15217.               "PTY READ RETURNED ZERO BYTES - SHOULD NOT HAPPEN",
  15218.               "",0);
  15219.         }
  15220.     } else
  15221.       pnotset++;
  15222.  
  15223.     /* If writes have caught up to reads, reset the buffers */
  15224.  
  15225.     if (pbuf_written == pbuf_avail)
  15226.       pbuf_written = pbuf_avail = 0;
  15227.     if (tbuf_written == tbuf_avail)
  15228.       tbuf_written = tbuf_avail = 0;
  15229.  
  15230.     /* See if we can exit */
  15231.  
  15232.     x1 = pbuf_avail - pbuf_written; 
  15233.     x2 = tbuf_avail - tbuf_written;
  15234.  
  15235.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST pty_err","",pty_err);
  15236.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST x1 [write to net]","",x1);
  15237.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST x2 [write to pty]","",x2);
  15238.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST rc","",rc);
  15239.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST status","",status);
  15240.     debug(F101,"ttptycmd pty_err LOOP EXIT TEST pexitstat","",pexitstat);
  15241.  
  15242.     if (net_err) {            /* Net error? */
  15243.         debug(F101,"ttptycmd net_err LOOP EXIT TEST net_err","",net_err);
  15244.         if (have_net) {
  15245.         if (local) {
  15246.             ttclos(0);
  15247.             printf("?Connection closed\n");
  15248.         }
  15249.         have_net = 0;
  15250.         }
  15251.         debug(F101,"ttptycmd net_err LOOP EXIT TEST x1","",x1);
  15252.         if (x1 == 0)
  15253.           break;
  15254.     }
  15255.     if (pty_err) {            /* Pty error? */
  15256.         if (have_pty) {
  15257.         if (pexitstat < 0) {        
  15258.             status = pty_get_status(ptyfd,pty_fork_pid);
  15259.             debug(F101,"ttptycmd pty_get_status E","",status);
  15260.             if (status > -1) pexitstat = status;
  15261.         }
  15262.         have_pty = 0;
  15263.         }
  15264.         if (x1 == 0 && x2 == 0) {    /* If buffers are caught up */
  15265.         rc = 1;            /* set preliminary return to success */
  15266.         debug(F101,"ttptycmd pty_err LOOP EXIT TEST rc 2","",rc);
  15267.         break;            /* and exit the loop */
  15268.         }
  15269.     }
  15270.     }
  15271.     debug(F101,"ttptycmd +++ have_pty","",have_pty);
  15272.     if (have_pty) {            /* In case select() failed */
  15273. #ifdef USE_CKUPTY_C
  15274.     end_pty();
  15275.     close(ptyfd);
  15276. #else
  15277.     close(slavefd);
  15278.     close(masterfd);
  15279. #endif /* USE_CKUPTY_C */
  15280.     }
  15281.     pty_master_fd = -1;
  15282.     debug(F101,"ttptycmd +++ pexitstat","",pexitstat);
  15283.     if (pexitstat < 0) {        /* Try one last time to get status */
  15284.     status = pty_get_status(ptyfd,pty_fork_pid);
  15285.     debug(F101,"ttptycmd pty_get_status F","",status);
  15286.     if (status > -1) pexitstat = status;
  15287.     }
  15288.     debug(F101,"ttptycmd +++ final pexitstat","",pexitstat);
  15289.     if (deblog) {            /* Stats for debug log */
  15290.     debug(F101,"ttptycmd +++ pset    ","",pset);
  15291.     debug(F101,"ttptycmd +++ pnotset","",pnotset);
  15292.     debug(F101,"ttptycmd +++ tset    ","",tset);
  15293.     debug(F101,"ttptycmd +++ tnotset","",tnotset);
  15294.  
  15295.     debug(F101,"ttptycmd +++  read_pty_bytes","",read_pty_bytes);
  15296.     debug(F101,"ttptycmd +++ write_net_bytes","",write_net_bytes);
  15297.     debug(F101,"ttptycmd +++  read_net_bytes","",read_net_bytes);
  15298.     debug(F101,"ttptycmd +++ write_pty_bytes","",write_pty_bytes);
  15299.     }
  15300. /*
  15301.   If we got the external protocol's exit status from waitpid(), we use that
  15302.   to set our return code.  If not, we fall back on whatever rc was previously
  15303.   set to, namely 1 (success) if the pty fork seemed to terminate, 0 otherwise.
  15304. */
  15305.     if (save_sigchld) {            /* Restore this if we changed it */
  15306.     (VOID) signal(SIGCHLD,save_sigchld);
  15307.     save_sigchld = NULL;
  15308.     }
  15309.     msleep(500);
  15310.     x = kill(pty_fork_pid,SIGHUP);    /* In case it's still there */
  15311.     pty_fork_pid = -1;
  15312.     debug(F101,"ttptycmd fork kill SIGHUP","",x);
  15313.     if (pexitstat > -1)
  15314.       rc = (pexitstat == 0 ? 1 : 0);
  15315.     debug(F101,"ttptycmd +++ rc","",rc);
  15316.     if (!local) {            /* If in remote mode */
  15317.     conres();            /* restore console to CBREAK mode */
  15318.     concb((char)escchr);
  15319.     }
  15320.     return(rc);
  15321. }
  15322. #endif    /* NETPTY */
  15323. #endif    /* SELECT */
  15324.  
  15325. /* T T R U N C M D  --  Redirect an external command over the connection. */
  15326.  
  15327. /*
  15328.   TTRUNCMD is the routine that was originally used for running external
  15329.   protocols.  It is very simple and works fine provided (a) the connection
  15330.   is not encrypted, and (b) the external protocol uses standard i/o
  15331.   (file descriptors 0 and 1) for file transfer.
  15332. */
  15333.  
  15334. int
  15335. ttruncmd(s) char *s; {
  15336.     PID_T pid;                /* pid of lower fork */
  15337.     int wstat;                /* for wait() */
  15338.     int x;
  15339.     int statusp;
  15340.  
  15341.     if (ttyfd == -1) {
  15342.     printf("?Sorry, device is not open\n");
  15343.     return(0);
  15344.     }
  15345.     if (nopush) {
  15346.     debug(F100,"ttruncmd fail: nopush","",0);
  15347.     return(0);
  15348.     }
  15349.  
  15350. #ifdef NETPTY
  15351. /***************
  15352.   It might also be necessary to use the pty routine for other reasons,
  15353.   e.g. because the external program does not use stdio.
  15354. */
  15355. #ifdef NETCONN
  15356. /*
  15357.   If we have a network connection we use a different routine because
  15358.   (a) if the connection is encrypted, the mechanism used here can't deal
  15359.   with it; and (b) it won't handle any network protocols either, e.g.
  15360.   Telnet, Rlogin, K5 U-to-U, etc.  However, this routine works much
  15361.   better (faster, more transparent) on serial connections and when
  15362.   C-Kermit is in remote mode (i.e. is on the far end).
  15363. */
  15364.     /* For testing always use this */
  15365.     if (netconn)
  15366.       return(ttptycmd(s));
  15367. #endif /* NETCONN */
  15368.  
  15369. /***************/
  15370. #else  /* NETPTY */
  15371.     if (tt_is_secure()) {
  15372.     printf("?Sorry, \
  15373. external protocols over secure connections not supported in this OS.\n"
  15374.               );
  15375.         return(0);
  15376.     }
  15377. #endif    /* NETPTY */
  15378.  
  15379.     conres();                /* Make console normal  */
  15380.     pexitstat = -4;
  15381.     if ((pid = fork()) == 0) {        /* Make a child fork */
  15382.     if (priv_can())            /* Child: turn off privs. */
  15383.       exit(1);
  15384.     dup2(ttyfd, 0);            /* Give stdin/out to the line */
  15385.     dup2(ttyfd, 1);
  15386.     x = system(s);
  15387.     debug(F101,"ttruncmd system",s,x);
  15388.     _exit(x ? BAD_EXIT : 0);
  15389.     } else {
  15390.     SIGTYP (*istat)(), (*qstat)();
  15391.     if (pid == (PID_T) -1)        /* fork() failed? */
  15392.       return(0);
  15393.     istat = signal(SIGINT,SIG_IGN); /* Let the fork handle keyboard */
  15394.     qstat = signal(SIGQUIT,SIG_IGN); /* interrupts itself... */
  15395.  
  15396. #ifdef COMMENT
  15397.         while (((wstat = wait(&statusp)) != pid) && (wstat != -1)) ;
  15398. #else  /* Not COMMENT */
  15399.         while (1) {
  15400.         wstat = wait(&statusp);
  15401.         debug(F101,"ttruncmd wait","",wstat);
  15402.         if (wstat == pid || wstat == -1)
  15403.           break;
  15404.     }
  15405. #endif /* COMMENT */
  15406.  
  15407.     pexitstat = (statusp & 0xff) ? statusp : statusp >> 8;
  15408.     debug(F101,"ttruncmd wait statusp","",statusp);
  15409.     debug(F101,"ttruncmd wait pexitstat","",pexitstat);
  15410.     signal(SIGINT,istat);        /* Restore interrupts */
  15411.     signal(SIGQUIT,qstat);
  15412.     }
  15413.     concb((char)escchr);        /* Restore console to CBREAK mode */
  15414.     return(statusp == 0 ? 1 : 0);
  15415. }
  15416. #endif    /* CK_REDIR */
  15417.  
  15418. struct tm *
  15419. #ifdef CK_ANSIC
  15420. cmdate2tm(char * date, int gmt)         /* date as "yyyymmdd hh:mm:ss" */
  15421. #else
  15422. cmdate2tm(date,gmt) char * date; int gmt;
  15423. #endif
  15424. {
  15425.     /* date as "yyyymmdd hh:mm:ss" */
  15426.     static struct tm _tm;
  15427.     time_t now;
  15428.  
  15429.     if (strlen(date) != 17 ||
  15430.     date[8] != ' ' ||
  15431.     date[11] != ':' ||
  15432.     date[14] != ':')
  15433.       return(NULL);
  15434.  
  15435.     time(&now);
  15436.     if (gmt)
  15437.       _tm = *gmtime(&now);
  15438.     else
  15439.       _tm = *localtime(&now);
  15440.     _tm.tm_year = (date[0]-'0')*1000 + (date[1]-'0')*100 +
  15441.                   (date[2]-'0')*10   + (date[3]-'0')-1900;
  15442.     _tm.tm_mon  = (date[4]-'0')*10   + (date[5]-'0')-1;
  15443.     _tm.tm_mday = (date[6]-'0')*10   + (date[7]-'0');
  15444.     _tm.tm_hour = (date[9]-'0')*10   + (date[10]-'0');
  15445.     _tm.tm_min  = (date[12]-'0')*10  + (date[13]-'0');
  15446.     _tm.tm_sec  = (date[15]-'0')*10  + (date[16]-'0');
  15447.  
  15448.     /* Should we set _tm.tm_isdst to -1 here? */
  15449.  
  15450.     _tm.tm_wday = 0;
  15451.     _tm.tm_yday = 0;
  15452.  
  15453.     return(&_tm);
  15454. }
  15455.  
  15456. #ifdef OXOS
  15457. #undef kill
  15458. #endif /* OXOS */
  15459.  
  15460. #ifdef OXOS
  15461. int
  15462. priv_kill(pid, sig) int pid, sig; {
  15463.     int    i;
  15464.  
  15465.     if (priv_on())
  15466.     debug(F100,"priv_kill priv_on failed","",0);
  15467.     i = kill(pid, sig);
  15468.     if (priv_off())
  15469.     debug(F100,"priv_kill priv_off failed","",0);
  15470.     return(i);
  15471. }
  15472. #endif /* OXOS */
  15473.  
  15474. #ifdef BEOSORBEBOX
  15475. /* #ifdef BE_DR_7 */
  15476. /*
  15477.   alarm() function not supplied with Be OS DR7 - this one contributed by
  15478.   Neal P. Murphy.
  15479. */
  15480.  
  15481. /*
  15482.   This should mimic the UNIX/POSIX alarm() function well enough, with the
  15483.   caveat that one's SIGALRM handler must call alarm_expired() to clean up vars
  15484.   and wait for the alarm thread to finish.
  15485. */
  15486. unsigned int
  15487. alarm(unsigned int seconds) {
  15488.     long time_left = 0;
  15489.  
  15490. /* If an alarm is active, turn it off, saving the unused time */
  15491.     if (alarm_thread != -1) {
  15492.         /* We'll be generous and count partial seconds as whole seconds. */
  15493.         time_left = alarm_struct.time -
  15494.       ((system_time() - time_started) / 1000000.0);
  15495.  
  15496.         /* Kill the alarm thread */
  15497.         kill_thread (alarm_thread);
  15498.  
  15499.         /* We need to clean up as though the alarm occured. */
  15500.         time_started = 0;
  15501.         alarm_struct.thread = -1;
  15502.         alarm_struct.time = 0;
  15503.         alarm_expired();
  15504.     }
  15505.  
  15506. /* Set a new alarm clock, if requested. */
  15507.     if (seconds > 0) {
  15508.         alarm_struct.thread = find_thread(NULL);
  15509.         alarm_struct.time = seconds;
  15510.         time_started = system_time();
  15511.         alarm_thread = spawn_thread (do_alarm,
  15512.                                      "alarm_thread",
  15513.                                      B_NORMAL_PRIORITY,
  15514.                                      (void *) &alarm_struct
  15515.                      );
  15516.         resume_thread (alarm_thread);
  15517.     }
  15518.  
  15519. /* Now return [unused time | 0] */
  15520.     return ((unsigned int) time_left);
  15521. }
  15522.  
  15523. /*
  15524.   This function is the departure from UNIX/POSIX alarm handling. In the case
  15525.   of Be's missing alarm() function, this stuff needs to be done in the SIGALRM
  15526.   handler. When Be implements alarm(), this function call can be eliminated
  15527.   from user's SIGALRM signal handlers.
  15528. */
  15529.  
  15530. void
  15531. alarm_expired(void) {
  15532.     long ret_val;
  15533.  
  15534.     if (alarm_thread != -1) {
  15535.         wait_for_thread (alarm_thread, &ret_val);
  15536.         alarm_thread = -1;
  15537.     }
  15538. }
  15539.  
  15540. /*
  15541.   This is the function that snoozes the requisite number of seconds and then
  15542.   SIGALRMs the calling thread. Note that kill() wants a pid_t arg, whilst Be
  15543.   uses thread_id; currently they are both typdef'ed as long, but I'll do the
  15544.   cast anyway. This function is run in a separate thread.
  15545. */
  15546.  
  15547. long
  15548. do_alarm (void *alarm_struct) {
  15549.     snooze ((double) ((struct ALARM_STRUCT *) alarm_struct)->time * 1000000.0);
  15550.     kill ((pid_t)((struct ALARM_STRUCT *) alarm_struct)->thread, SIGALRM);
  15551.     time_started = 0;
  15552.     ((struct ALARM_STRUCT *) alarm_struct)->thread = -1;
  15553.     ((struct ALARM_STRUCT *) alarm_struct)->time = 0;
  15554. }
  15555. /* #endif */ /* BE_DR_7 */
  15556. #endif /* BEOSORBEBOX */
  15557.  
  15558. #ifdef Plan9
  15559.  
  15560. int
  15561. p9ttyctl(char letter, int num, int param) {
  15562.     char cmd[20];
  15563.     int len;
  15564.  
  15565.     if (ttyctlfd < 0)
  15566.       return -1;
  15567.  
  15568.     cmd[0] = letter;
  15569.     if (num)
  15570.       len = sprintf(cmd + 1, "%d", param) + 1;
  15571.     else {
  15572.     cmd[1] = param;
  15573.     len = 2;
  15574.     }
  15575.     if (write(ttyctlfd, cmd, len) == len) {
  15576.     cmd[len] = 0;
  15577.     /* fprintf(stdout, "wrote '%s'\n", cmd); */
  15578.     return 0;
  15579.     }
  15580.     return -1;
  15581. }
  15582.  
  15583. int
  15584. p9ttyparity(char l) {
  15585.     return p9ttyctl('p', 0, l);
  15586. }
  15587.  
  15588. int
  15589. p9tthflow(int flow, int status) {
  15590.     return p9ttyctl('m', 1, status);
  15591. }
  15592.  
  15593. int
  15594. p9ttsspd(int cps) {
  15595.     if (p9ttyctl('b', 1, cps * 10) < 0)
  15596.       return -1;
  15597.     ttylastspeed = cps * 10;
  15598.     return 0;
  15599. }
  15600.  
  15601. int
  15602. p9openttyctl(char *ttname) {
  15603.     char name[100];
  15604.  
  15605.     if (ttyctlfd >= 0) {
  15606.     close(ttyctlfd);
  15607.     ttyctlfd = -1;
  15608.     ttylastspeed = -1;
  15609.     }
  15610.     sprintf(name, "%sctl", ttname);
  15611.     ttyctlfd = open(name, 1);
  15612.     return ttyctlfd;
  15613. }
  15614.  
  15615. int
  15616. p9concb() {
  15617.     if (consctlfd >= 0) {
  15618.     if (write(consctlfd, "rawon", 5) == 5)
  15619.       return 0;
  15620.     }
  15621.     return -1;
  15622. }
  15623.  
  15624. int
  15625. p9conbin() {
  15626.     return p9concb();
  15627. }
  15628.  
  15629. int
  15630. p9conres() {
  15631.     if (consctlfd >= 0) {
  15632.     if (write(consctlfd, "rawoff", 6) == 6)
  15633.       return 0;
  15634.     }
  15635.     return -1;
  15636. }
  15637.  
  15638. int
  15639. p9sndbrk(int msec) {
  15640.     if (ttyctlfd >= 0) {
  15641.     char cmd[20];
  15642.     int i = sprintf(cmd, "k%d", msec);
  15643.     if (write(ttyctlfd, cmd, i) == i)
  15644.       return 0;
  15645.     }
  15646.     return -1;
  15647. }
  15648.  
  15649. int
  15650. conwrite(char *buf, int n) {
  15651.     int x;
  15652.     static int length = 0;
  15653.     static int holdingcr = 0;
  15654.     int normal = 0;
  15655.     for (x = 0; x < n; x++) {
  15656.     char c = buf[x];
  15657.     if (c == 007) {
  15658.         if (normal) {
  15659.         write(1, buf + (x - normal), normal);
  15660.         length += normal;
  15661.         normal = 0;
  15662.         }
  15663.         /* write(noisefd, "1000 300", 8); */
  15664.         holdingcr = 0;
  15665.     } else if (c == '\r') {
  15666.         if (normal) {
  15667.         write(1, buf + (x - normal), normal);
  15668.         length += normal;
  15669.         normal = 0;
  15670.         }
  15671.         holdingcr = 1;
  15672.     } else if (c == '\n') {
  15673.         write(1, buf + (x - normal), normal + 1);
  15674.         normal = 0;
  15675.         length = 0;
  15676.         holdingcr = 0;
  15677.     } else if (c == '\b') {
  15678.         if (normal) {
  15679.         write(1, buf + (x - normal), normal);
  15680.         length += normal;
  15681.         normal = 0;
  15682.         }
  15683.         if (length) {
  15684.         write(1, &c, 1);
  15685.         length--;
  15686.         }
  15687.         holdingcr = 0;
  15688.     } else {
  15689.         if (holdingcr) {
  15690.         char b = '\b';
  15691.         while (length-- > 0)
  15692.           write(1, &b, 1);
  15693.         length = 0;    /* compiler bug */
  15694.         }
  15695.         holdingcr = 0;
  15696.         normal++;
  15697.     }
  15698.     }
  15699.     if (normal) {
  15700.     write(1, buf + (x - normal), normal);
  15701.     length += normal;
  15702.     }
  15703.     return n;
  15704. }
  15705.  
  15706. void
  15707. conprint(char *fmt, ...) {
  15708.     static char buf[1000];        /* not safe if on the stack */
  15709.  
  15710.     va_list ap;
  15711.     int i;
  15712.  
  15713.     va_start(ap, fmt);
  15714.     i = vsprintf(buf, fmt, ap);
  15715.     conwrite(buf, i);
  15716. }
  15717. #endif /* Plan9 */
  15718.  
  15719. /* fprintf, printf, perror replacements... */
  15720.  
  15721. /* f p r i n t f */
  15722.  
  15723. #ifdef UNIX
  15724. #ifdef CK_ANSIC
  15725. #include <stdarg.h>
  15726. #else /* CK_ANSIC */
  15727. #ifdef __GNUC__
  15728. #include <stdarg.h>
  15729. #else
  15730. #include <varargs.h>
  15731. #endif    /* __GNUC__ */
  15732. #endif /* CK_ANSIC */
  15733. #ifdef fprintf
  15734. #undef fprintf
  15735. static char str1[4096];
  15736. static char str2[4096];
  15737. int
  15738. #ifdef CK_ANSIC
  15739. ckxfprintf(FILE * file, const char * format, ...)
  15740. #else /* CK_ANSIC */
  15741. ckxfprintf(va_alist) va_dcl
  15742. #endif /* CK_ANSIC */
  15743. /* ckxfprintf */ {
  15744.     int i, j, len, got_cr;
  15745.     va_list args;
  15746.     int rc = 0;
  15747.  
  15748. #ifdef CK_ANSIC
  15749.     va_start(args, format);
  15750. #else /* CK_ANSIC */
  15751.     char * format;
  15752.     FILE * file;
  15753.     va_start(args);
  15754.     file = va_arg(args,FILE *);
  15755.     format = va_arg(args,char *);
  15756. #endif /* CK_ANSIC */
  15757.  
  15758.     if (!inserver || (file != stdout && file != stderr && file != stdin)) {
  15759.     rc = vfprintf(file,format,args);
  15760.     } else {
  15761.     unsigned int c;
  15762.         rc = vsprintf(str1, format, args);
  15763.         len = strlen(str1);
  15764.         if (len >= sizeof(str1)) {
  15765.             debug(F101,"ckxfprintf() buffer overflow","",len);
  15766.             doexit(BAD_EXIT,1);
  15767.         }
  15768.         for (i = 0, j = 0, got_cr = 0;
  15769.          i < len && j < sizeof(str1)-2;
  15770.          i++, j++ ) {
  15771.         /* We can't use 255 as a case label because of signed chars */
  15772.         c = (unsigned)(str1[i] & 0xff);
  15773. #ifdef TNCODE
  15774.         if (c == 255) {
  15775.         if (got_cr && !TELOPT_ME(TELOPT_BINARY))
  15776.           str2[j++] = '\0';
  15777.         str2[j++] = IAC;
  15778.         str2[j] = IAC;
  15779.         got_cr = 0;
  15780.         } else
  15781. #endif /* TNCODE */
  15782.         switch (c) {
  15783.           case '\r':
  15784.                 if (got_cr
  15785. #ifdef TNCODE
  15786.             && !TELOPT_ME(TELOPT_BINARY)
  15787. #endif /* TNCODE */
  15788.             )
  15789.           str2[j++] = '\0';
  15790.                 str2[j] = str1[i];
  15791.                 got_cr = 1;
  15792.                 break;
  15793.           case '\n':
  15794.                 if (!got_cr)
  15795.           str2[j++] = '\r';
  15796.                 str2[j] = str1[i];
  15797.                 got_cr = 0;
  15798.                 break;
  15799.           default:
  15800.                 if (got_cr
  15801. #ifdef TNCODE
  15802.             && !TELOPT_ME(TELOPT_BINARY)
  15803. #endif /* TNCODE */
  15804.             )
  15805.           str2[j++] = '\0';
  15806.                 str2[j] = str1[i];
  15807.                 got_cr = 0;
  15808.             }
  15809.         }
  15810.         if (got_cr
  15811. #ifdef TNCODE
  15812.              && !TELOPT_ME(TELOPT_BINARY)
  15813. #endif /* TNCODE */
  15814.              )
  15815.             str2[j++] = '\0';
  15816. #ifdef CK_ENCRYPTION
  15817. #ifdef TNCODE
  15818.         if (TELOPT_ME(TELOPT_ENCRYPTION))
  15819.       ck_tn_encrypt(str2,j);
  15820. #endif /* TNCODE */
  15821. #endif /* CK_ENCRYPTION */
  15822. #ifdef CK_SSL
  15823.     if (inserver && (ssl_active_flag || tls_active_flag)) {
  15824.         /* Write using SSL */
  15825.             char * p = str2;
  15826.           ssl_retry:
  15827.             if (ssl_active_flag)
  15828.           rc = SSL_write(ssl_con, p, j);
  15829.             else
  15830.           rc = SSL_write(tls_con, p, j);
  15831.         debug(F111,"ckxfprintf","SSL_write",rc);
  15832.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,rc)) {
  15833.           case SSL_ERROR_NONE:
  15834.                 if (rc == j)
  15835.           break;
  15836.                 p += rc;
  15837.                 j -= rc;
  15838.                 goto ssl_retry;
  15839.           case SSL_ERROR_WANT_WRITE:
  15840.           case SSL_ERROR_WANT_READ:
  15841.           case SSL_ERROR_SYSCALL:
  15842.                 if (rc != 0)
  15843.           return(-1);
  15844.           case SSL_ERROR_WANT_X509_LOOKUP:
  15845.           case SSL_ERROR_SSL:
  15846.           case SSL_ERROR_ZERO_RETURN:
  15847.           default:
  15848.                 rc = 0;
  15849.             }
  15850.     } else
  15851. #endif /* CK_SSL */
  15852.         fwrite(str2,sizeof(char),j,stdout);
  15853.     }
  15854.     va_end(args);
  15855.     return(rc);
  15856. }
  15857. #endif /* fprintf */
  15858.  
  15859. /* p r i n t f */
  15860.  
  15861. #ifdef printf
  15862. #undef printf
  15863. int
  15864. #ifdef CK_ANSIC
  15865. ckxprintf(const char * format, ...)
  15866. #else /* CK_ANSIC */
  15867. ckxprintf(va_alist) va_dcl
  15868. #endif /* CK_ANSIC */
  15869. /* ckxprintf */ {
  15870.     int i, j, len, got_cr;
  15871.     va_list args;
  15872.     int rc = 0;
  15873.  
  15874. #ifdef CK_ANSIC
  15875.     va_start(args, format);
  15876. #else /* CK_ANSIC */
  15877.     char * format;
  15878.     va_start(args);
  15879.     format = va_arg(args,char *);
  15880. #endif /* CK_ANSIC */
  15881.  
  15882.     if (!inserver) {
  15883.     rc = vprintf(format, args);
  15884.     } else {
  15885.     unsigned int c;
  15886.         rc = vsprintf(str1, format, args);
  15887.         len = strlen(str1);
  15888.         if (len >= sizeof(str1)) {
  15889.             debug(F101,"ckxprintf() buffer overflow","",len);
  15890.             doexit(BAD_EXIT,1);
  15891.         }
  15892.         for (i = 0, j = 0, got_cr=0;
  15893.          i < len && j < sizeof(str1)-2;
  15894.          i++, j++ ) {
  15895.         c = (unsigned)(str1[i] & 0xff);
  15896. #ifdef TNCODE
  15897.         if (c == 255) {
  15898.         if (got_cr && !TELOPT_ME(TELOPT_BINARY))
  15899.           str2[j++] = '\0';
  15900.         str2[j++] = IAC;
  15901.         str2[j] = IAC;
  15902.         got_cr = 0;
  15903.         } else
  15904. #endif /* TNCODE */
  15905.         switch (c) {
  15906.           case '\r':
  15907.                 if (got_cr
  15908. #ifdef TNCODE
  15909.             && !TELOPT_ME(TELOPT_BINARY)
  15910. #endif /* TNCODE */
  15911.             )
  15912.           str2[j++] = '\0';
  15913.                 str2[j] = str1[i];
  15914.                 got_cr = 1;
  15915.                 break;
  15916.           case '\n':
  15917.                 if (!got_cr)
  15918.           str2[j++] = '\r';
  15919.                 str2[j] = str1[i];
  15920.                 got_cr = 0;
  15921.                 break;
  15922.           default:
  15923.                 if (got_cr
  15924. #ifdef TNCODE
  15925.             && !TELOPT_ME(TELOPT_BINARY)
  15926. #endif /* TNCODE */
  15927.             )
  15928.           str2[j++] = '\0';
  15929.                 str2[j] = str1[i];
  15930.                 got_cr = 0;
  15931.                 break;
  15932.         }
  15933.         }
  15934.         if (got_cr
  15935. #ifdef TNCODE
  15936.              && !TELOPT_ME(TELOPT_BINARY)
  15937. #endif /* TNCODE */
  15938.              )
  15939.             str2[j++] = '\0';
  15940. #ifdef CK_ENCRYPTION
  15941. #ifdef TNCODE
  15942.         if (TELOPT_ME(TELOPT_ENCRYPTION))
  15943.       ck_tn_encrypt(str2,j);
  15944. #endif /* TNCODE */
  15945. #endif /* CK_ENCRYPTION */
  15946. #ifdef CK_SSL
  15947.     if (inserver && (ssl_active_flag || tls_active_flag)) {
  15948.             char * p = str2;
  15949.         /* Write using SSL */
  15950.           ssl_retry:
  15951.             if (ssl_active_flag)
  15952.           rc = SSL_write(ssl_con, p, j);
  15953.             else
  15954.           rc = SSL_write(tls_con, p, j);
  15955.         debug(F111,"ckxprintf","SSL_write",rc);
  15956.             switch (SSL_get_error(ssl_active_flag?ssl_con:tls_con,rc)) {
  15957.           case SSL_ERROR_NONE:
  15958.                 if (rc == j)
  15959.           break;
  15960.                 p += rc;
  15961.                 j -= rc;
  15962.                 goto ssl_retry;
  15963.           case SSL_ERROR_WANT_WRITE:
  15964.           case SSL_ERROR_WANT_READ:
  15965.           case SSL_ERROR_SYSCALL:
  15966.                 if (rc != 0)
  15967.           return(-1);
  15968.           case SSL_ERROR_WANT_X509_LOOKUP:
  15969.           case SSL_ERROR_SSL:
  15970.           case SSL_ERROR_ZERO_RETURN:
  15971.           default:
  15972.                 rc = 0;
  15973.             }
  15974.     } else
  15975. #endif /* CK_SSL */
  15976.       rc = fwrite(str2,sizeof(char),j,stdout);
  15977.     }
  15978.     va_end(args);
  15979.     return(rc);
  15980. }
  15981. #endif /* printf */
  15982.  
  15983. /*  p e r r o r  */
  15984.  
  15985. #ifdef perror
  15986. #undef perror
  15987. _PROTOTYP(char * ck_errstr,(VOID));
  15988. #ifdef NEXT
  15989. void
  15990. #else
  15991. #ifdef CK_SCOV5
  15992. void
  15993. #else
  15994. int
  15995. #endif /* CK_SCOV5 */
  15996. #endif /* NEXT */
  15997. #ifdef CK_ANSIC
  15998. ckxperror(const char * str)
  15999. #else /* CK_ANSIC */
  16000. ckxperror(str) char * str;
  16001. #endif /* CK_ANSIC */
  16002. /* ckxperror */ {
  16003.     char * errstr = ck_errstr();
  16004. #ifndef NEXT
  16005. #ifndef CK_SCOV5
  16006.     return
  16007. #endif /* CK_SCOV5 */
  16008. #endif /* NEXT */
  16009.       ckxprintf("%s%s %s\n",str,*errstr?":":"",errstr);
  16010. }
  16011. #endif /* perror */
  16012. #endif /* UNIX */
  16013.  
  16014. #ifdef MINIX2
  16015.  
  16016. /* Minix doesn't have a gettimeofday call (but MINIX3 does).
  16017.  * We fake one here using time(2)
  16018.  */
  16019.  
  16020. #ifndef MINIX3
  16021. int
  16022. gettimeofday(struct timeval *tp, struct timezone *tzp) {
  16023.     tp->tv_usec = 0L;            /* Close enough for horseshoes */
  16024.     if(time(&(tp->tv_sec))==-1)
  16025.       return(-1);
  16026.     return(0);
  16027. }
  16028. #endif    /* MINIX3 */
  16029.  
  16030. #ifndef MINIX3
  16031. int
  16032. readlink(const char *path, void *buf, size_t bufsiz) {
  16033.     errno = ENOSYS;
  16034.     return(-1);
  16035. }
  16036. #endif    /* MINIX3 */
  16037.  
  16038. #endif /* MINIX2 */
  16039.